From 36db372588e8ed7767128179df4ef4a236a60bd1 Mon Sep 17 00:00:00 2001 From: wangxiao Date: Thu, 4 May 2023 20:15:58 +0800 Subject: [PATCH] Broadcast of index. --- torch_npu/csrc/aten/ops/IndexKernelNpu.cpp | 3 +- .../csrc/framework/utils/AdvancedIndex.cpp | 29 +++++++++++++++++++ .../csrc/framework/utils/AdvancedIndex.h | 3 ++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/torch_npu/csrc/aten/ops/IndexKernelNpu.cpp b/torch_npu/csrc/aten/ops/IndexKernelNpu.cpp index 5b66480c01..203536c015 100644 --- a/torch_npu/csrc/aten/ops/IndexKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/IndexKernelNpu.cpp @@ -175,9 +175,10 @@ at::Tensor NPUNativeFunctions::index(const at::Tensor& self, const torch::List AdvanceIndex::npu_expand_tensors( return result; } +std::vector AdvanceIndex::npu_broadcast_tensors(std::vector to_broadcast) { + // Broadcast a list of Tensors, ignoring undefined (null) tensors. + bool first = true; + std::vector sizes; + for (int i = 0; i < to_broadcast.size(); ++i) { + if (!to_broadcast[i].defined()) { + continue; + } else if (first) { + // The initial value of sizes is the first defined tensor's shape. + sizes = to_broadcast[i].sizes().vec(); + first = false; + } else { + sizes = at::infer_size(sizes, to_broadcast[i].sizes()); + } + } + + std::vector result(to_broadcast.size()); + for (int i = 0; i < to_broadcast.size(); ++i) { + if (!to_broadcast[i].defined()) { + continue; + } else if (to_broadcast[i].sizes().equals(sizes)) { + result[i] = to_broadcast[i]; + } else { + result[i] = NPUNativeFunctions::npu_broadcast(to_broadcast[i], sizes); + } + } + return result; +} + } // namespace native } // namespace at_npu diff --git a/torch_npu/csrc/framework/utils/AdvancedIndex.h b/torch_npu/csrc/framework/utils/AdvancedIndex.h index 96aab3dc5b..640406868b 100644 --- a/torch_npu/csrc/framework/utils/AdvancedIndex.h +++ b/torch_npu/csrc/framework/utils/AdvancedIndex.h @@ -19,6 +19,8 @@ #include #include +#include "torch_npu/csrc/framework/utils/NpuUtils.h" + namespace at_npu { namespace native { @@ -43,6 +45,7 @@ public: static std::vector npu_expand_tensors( const at::Tensor& self, const torch::List>& indices); + static std::vector npu_broadcast_tensors(std::vector to_broadcast); }; } // namespace native