TensorIndexing.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. #pragma once
  2. #include <ATen/ExpandUtils.h>
  3. #include <ATen/ScalarOps.h>
  4. #include <ATen/core/Tensor.h>
  5. #include <ATen/core/TensorBody.h>
  6. #include <c10/core/SymInt.h>
  7. #include <c10/util/irange.h>
  8. #include <optional>
  9. #ifndef AT_PER_OPERATOR_HEADERS
  10. #include <ATen/Functions.h>
  11. #include <ATen/NativeFunctions.h>
  12. #else
  13. #include <ATen/ops/alias.h>
  14. #include <ATen/ops/empty.h>
  15. #include <ATen/ops/scalar_tensor.h>
  16. #include <ATen/ops/zeros.h>
  17. #endif
  18. #include <ATen/core/List.h>
  19. #include <utility>
  20. namespace at::indexing {
  21. constexpr int64_t INDEX_MIN = c10::SymInt::min_representable_int();
  22. constexpr int64_t INDEX_MAX = -(INDEX_MIN + 1);
  23. enum class TensorIndexType { None, Ellipsis, SymInt, Boolean, Slice, Tensor };
  24. constexpr std::nullopt_t None = std::nullopt;
  25. struct TORCH_API EllipsisIndexType final {
  26. EllipsisIndexType() = default;
  27. };
  28. TORCH_API extern const EllipsisIndexType Ellipsis;
  29. struct TORCH_API Slice final {
  30. public:
  31. Slice(
  32. std::optional<c10::SymInt> start_index = std::nullopt,
  33. std::optional<c10::SymInt> stop_index = std::nullopt,
  34. std::optional<c10::SymInt> step_index = std::nullopt) {
  35. if (!step_index.has_value()) {
  36. step_ = c10::SymInt(1);
  37. } else {
  38. step_ = std::move(step_index).value();
  39. }
  40. TORCH_CHECK_VALUE(
  41. step_.sym_ne(0).expect_true(__FILE__, __LINE__),
  42. "slice step cannot be zero");
  43. if (!start_index.has_value()) {
  44. start_ = c10::SymInt(step_ < 0 ? INDEX_MAX : 0);
  45. } else {
  46. start_ = std::move(start_index).value();
  47. }
  48. if (!stop_index.has_value()) {
  49. stop_ = c10::SymInt(step_ < 0 ? INDEX_MIN : INDEX_MAX);
  50. } else {
  51. stop_ = std::move(stop_index).value();
  52. }
  53. }
  54. inline c10::SymInt start() const {
  55. return start_;
  56. }
  57. inline c10::SymInt stop() const {
  58. return stop_;
  59. }
  60. inline c10::SymInt step() const {
  61. return step_;
  62. }
  63. private:
  64. c10::SymInt start_;
  65. c10::SymInt stop_;
  66. c10::SymInt step_;
  67. };
  68. TORCH_API std::ostream& operator<<(std::ostream& stream, const Slice& slice);
  69. // `at::indexing::TensorIndex` is used for converting C++ tensor indices such as
  70. // `{None, "...", Ellipsis, 0, true, Slice(1, None, 2), torch::tensor({1, 2})}`
  71. // into its equivalent `std::vector<TensorIndex>`, so that further tensor
  72. // indexing operations can be performed using the supplied indices.
  73. //
  74. // There is one-to-one correspondence between Python and C++ tensor index types:
  75. // Python | C++
  76. // -----------------------------------------------------
  77. // `None` | `at::indexing::None`
  78. // `Ellipsis` | `at::indexing::Ellipsis`
  79. // `...` | `"..."`
  80. // `123` | `123`
  81. // `True` / `False` | `true` / `false`
  82. // `:` | `Slice()` / `Slice(None, None)`
  83. // `::` | `Slice()` / `Slice(None, None, None)`
  84. // `1:` | `Slice(1, None)`
  85. // `1::` | `Slice(1, None, None)`
  86. // `:3` | `Slice(None, 3)`
  87. // `:3:` | `Slice(None, 3, None)`
  88. // `::2` | `Slice(None, None, 2)`
  89. // `1:3` | `Slice(1, 3)`
  90. // `1::2` | `Slice(1, None, 2)`
  91. // `:3:2` | `Slice(None, 3, 2)`
  92. // `1:3:2` | `Slice(1, 3, 2)`
  93. // `torch.tensor([1, 2])`) | `torch::tensor({1, 2})`
  94. struct TORCH_API TensorIndex final {
  95. // Case 1: `at::indexing::None`
  96. TensorIndex(std::nullopt_t) : type_(TensorIndexType::None) {}
  97. // Case 2: "..." / `at::indexing::Ellipsis`
  98. TensorIndex(at::indexing::EllipsisIndexType)
  99. : type_(TensorIndexType::Ellipsis) {}
  100. TensorIndex(const char* str) : TensorIndex(at::indexing::Ellipsis) {
  101. TORCH_CHECK_VALUE(
  102. strcmp(str, "...") == 0,
  103. "Expected \"...\" to represent an ellipsis index, but got \"",
  104. str,
  105. "\"");
  106. }
  107. // Case 3: (Sym) Integer value
  108. TensorIndex(SymInt integer)
  109. : integer_(std::move(integer)), type_(TensorIndexType::SymInt) {}
  110. TensorIndex(int64_t integer) : TensorIndex(SymInt(integer)) {}
  111. TensorIndex(int integer) : TensorIndex(SymInt(integer)) {}
  112. // Case 4: Boolean value
  113. template <class T, class = std::enable_if_t<std::is_same_v<bool, T>>>
  114. TensorIndex(T boolean) : boolean_(boolean), type_(TensorIndexType::Boolean) {}
  115. // Case 5: Slice represented in `at::indexing::Slice` form
  116. TensorIndex(Slice slice)
  117. : slice_(std::move(slice)), type_(TensorIndexType::Slice) {}
  118. // Case 6: Tensor value
  119. TensorIndex(Tensor tensor)
  120. : tensor_(std::move(tensor)), type_(TensorIndexType::Tensor) {}
  121. inline bool is_none() const {
  122. return type_ == TensorIndexType::None;
  123. }
  124. inline bool is_ellipsis() const {
  125. return type_ == TensorIndexType::Ellipsis;
  126. }
  127. inline bool is_integer() const {
  128. return type_ == TensorIndexType::SymInt;
  129. }
  130. inline SymInt integer() const {
  131. return integer_;
  132. }
  133. inline bool is_boolean() const {
  134. return type_ == TensorIndexType::Boolean;
  135. }
  136. inline bool boolean() const {
  137. return boolean_;
  138. }
  139. inline bool is_slice() const {
  140. return type_ == TensorIndexType::Slice;
  141. }
  142. inline const Slice& slice() const {
  143. return slice_;
  144. }
  145. inline bool is_tensor() const {
  146. return type_ == TensorIndexType::Tensor;
  147. }
  148. inline const Tensor& tensor() const {
  149. return tensor_;
  150. }
  151. private:
  152. SymInt integer_ = 0;
  153. bool boolean_ = false;
  154. Slice slice_;
  155. Tensor tensor_;
  156. TensorIndexType type_;
  157. };
  158. TORCH_API std::ostream& operator<<(
  159. std::ostream& stream,
  160. const TensorIndex& tensor_index);
  161. TORCH_API std::ostream& operator<<(
  162. std::ostream& stream,
  163. const std::vector<TensorIndex>& tensor_indices);
  164. namespace impl {
  165. inline Tensor applySlice(
  166. const Tensor& self,
  167. int64_t dim,
  168. c10::SymInt start,
  169. c10::SymInt stop,
  170. c10::SymInt step,
  171. bool disable_slice_optimization,
  172. const at::Device& self_device,
  173. const std::optional<SymIntArrayRef>& self_sizes) {
  174. // TODO: implement negative step
  175. TORCH_CHECK_VALUE(
  176. step.sym_gt(0).expect_true(__FILE__, __LINE__),
  177. "step must be greater than zero");
  178. // See NOTE [nested tensor size for indexing]
  179. if (self_sizes.has_value() && self_sizes.value().size() > 0) {
  180. // Skip this optimization if we are tracing, as the trace may be polymorphic
  181. // over the shape of the `self` tensor, and we still want to record
  182. // the slice.
  183. SymInt length = (self_device == at::kCPU || self_device == at::kCUDA)
  184. ? (*self_sizes)[dim]
  185. : self.sym_size(dim);
  186. if (!disable_slice_optimization &&
  187. TORCH_STATICALLY_KNOWN_TRUE(start.sym_eq(0)) &&
  188. TORCH_STATICALLY_KNOWN_TRUE(length.sym_le(stop)) && step == 1) {
  189. return self;
  190. }
  191. }
  192. return self.slice_symint(
  193. dim, std::move(start), std::move(stop), std::move(step));
  194. }
  195. inline Tensor applySelect(
  196. const Tensor& self,
  197. int64_t dim,
  198. SymInt index,
  199. int64_t real_dim,
  200. const at::Device& /*self_device*/,
  201. const std::optional<SymIntArrayRef>& self_sizes) {
  202. // See NOTE [nested tensor size for indexing]
  203. if (self_sizes.has_value()) {
  204. auto maybe_index = index.maybe_as_int();
  205. if (maybe_index.has_value()) {
  206. TORCH_CHECK_INDEX(
  207. !(maybe_index.value() == 0 && dim == 0 && self_sizes->empty()),
  208. "invalid index of a 0-dim tensor. ",
  209. "Use `tensor.item()` in Python or `tensor.item<T>()` in C++ to convert a 0-dim tensor to a number");
  210. }
  211. auto size = (*self_sizes)[dim];
  212. // Note: `size >= -index` is not equivalent to `size > -1 - index` if index
  213. // is INT64_MIN For std::numeric_limits<int64_t>::min() result of unary
  214. // minus is undefined by the standard but in practice is equal to self. On
  215. // the other hand, indexing wrapping is valid for all negative int64_t
  216. // values, as x[INT64_MIN] is the same as x[INT64_MAX]
  217. TORCH_CHECK_INDEX(
  218. size.sym_gt(-1 - index)
  219. .sym_and(size.sym_gt(index))
  220. .expect_true(__FILE__, __LINE__),
  221. "index ",
  222. index,
  223. " is out of bounds for dimension ",
  224. real_dim,
  225. " with size ",
  226. size);
  227. }
  228. // if the index is negative, do not normalize it because that would fix the
  229. // index on the current tensor size in the tracer. aten::select also works on
  230. // negative indices
  231. return self.select_symint(dim, std::move(index));
  232. }
  233. inline Tensor boolToIndexingTensorCPUOrCUDA(const Tensor& self, bool value) {
  234. // booleans add a dimension of size 1. true indexes this dimension as if 0:,
  235. // false as empty.
  236. if (value) {
  237. return at::empty({1}, self.options().dtype(kLong)).fill_(0.);
  238. } else {
  239. return at::empty({0}, self.options().dtype(kLong));
  240. }
  241. }
  242. inline Tensor boolToIndexingTensorNonNativeDeviceType(
  243. const Tensor& self,
  244. bool value) {
  245. // booleans add a dimension of size 1. true indexes this dimension as if 0:,
  246. // false as empty.
  247. if (value) {
  248. return at::zeros({1}, self.options().dtype(kLong));
  249. } else {
  250. return at::empty({0}, self.options().dtype(kLong));
  251. }
  252. }
  253. inline Tensor boolToIndexingTensor(
  254. const Tensor& self,
  255. bool value,
  256. const at::Device& self_device) {
  257. if (self_device == at::kCPU || self_device == at::kCUDA) {
  258. return boolToIndexingTensorCPUOrCUDA(self, value);
  259. } else {
  260. return boolToIndexingTensorNonNativeDeviceType(self, value);
  261. }
  262. }
  263. inline Tensor scalarToTensorNonNativeDeviceType(
  264. const Scalar& v,
  265. const TensorOptions& options) {
  266. return at::scalar_tensor(v, options);
  267. }
  268. inline void recordTensorIndex(
  269. const Tensor& tensor,
  270. std::vector<Tensor>& outIndices,
  271. int64_t* dim_ptr) {
  272. if (outIndices.empty()) {
  273. outIndices.resize(*dim_ptr + 1);
  274. outIndices[*dim_ptr] = tensor;
  275. } else {
  276. outIndices.push_back(tensor);
  277. }
  278. if (tensor.scalar_type() == kByte || tensor.scalar_type() == kBool) {
  279. *dim_ptr += tensor.dim();
  280. } else {
  281. *dim_ptr += 1;
  282. }
  283. }
  284. inline c10::List<::std::optional<Tensor>> typeConvertIndices(
  285. const Tensor& /*self*/,
  286. std::vector<Tensor>&& indices) {
  287. c10::List<::std::optional<Tensor>> converted_inds;
  288. converted_inds.reserve(indices.size());
  289. for (auto&& i : std::move(indices)) {
  290. converted_inds.push_back(std::move(i));
  291. }
  292. return converted_inds;
  293. }
  294. // NOTE: Why do we mirror instead of replace the `count_specified_dimensions`
  295. // function in torch/csrc/autograd/python_variable_indexing.cpp? It's because
  296. // `count_specified_dimensions` is on the hot path of Python tensor multi-dim
  297. // indexing (i.e. it's called by `applySlicing` which is called by
  298. // `THPVariable_getitem` / `THPVariable_setitem` when handling indexing of more
  299. // than one dimension). If we were to merge the Python/C++
  300. // `count_specified_dimensions` function, on the Python side we would have to
  301. // construct a `std::vector` container to be consumed by the C++
  302. // `count_specified_dimensions` function, which adds 100s of nanoseconds
  303. // overhead and is undesirable.
  304. inline int64_t count_specified_dimensions(
  305. const ArrayRef<TensorIndex>& indices) {
  306. // Count the number of indexed dimensions (everything but ellipsis and None)
  307. int64_t count = 0;
  308. for (auto& obj : indices) {
  309. if (obj.is_tensor()) {
  310. auto& tensor = obj.tensor();
  311. if (tensor.scalar_type() == kByte || tensor.scalar_type() == kBool) {
  312. count += tensor.dim();
  313. } else {
  314. count++;
  315. }
  316. } else if (!obj.is_none() && !obj.is_ellipsis() && !obj.is_boolean()) {
  317. count++;
  318. }
  319. }
  320. return count;
  321. }
  322. } // namespace impl
  323. // NOTE: Many functions below are only for consumption from Python indexing
  324. // implementation, they include:
  325. //
  326. // - `Tensor scalarToTensor(...)`
  327. // - `IntArrayRef slicePrefix1sSize(...)`
  328. // - `void copy_to(...)`
  329. // - `Tensor handleDimInMultiDimIndexing(...)`
  330. // - `Tensor dispatch_index(...)`
  331. // - `Tensor dispatch_index_put_(...)`
  332. // - `Tensor get_item(...)`
  333. // - `void set_item(...)`
  334. //
  335. // The rest of the functions are in `at::indexing::impl` namespace, signifying
  336. // that they shouldn't be used from Python indexing implementation.
  337. inline Tensor scalarToTensor(
  338. const Scalar& v,
  339. const TensorOptions& options,
  340. const at::Device& self_device) {
  341. if (self_device == at::kCPU && !v.isSymbolic()) {
  342. return at::detail::scalar_tensor_static(
  343. v,
  344. // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
  345. options.dtype_opt()->toScalarType(),
  346. self_device);
  347. } else {
  348. return impl::scalarToTensorNonNativeDeviceType(v, options);
  349. }
  350. }
  351. // To match numpy semantics:
  352. // As a special case for backwards compatibility,
  353. // strip away unit dimensions from the left of 'src'
  354. inline SymIntArrayRef slicePrefix1sSize(const SymIntArrayRef& sizes) {
  355. size_t first_non1_src = sizes.size();
  356. for (const auto i : c10::irange(sizes.size())) {
  357. // Unbacked SymInt has different behavior, but this is sound because
  358. // failing to slice will only ever cause an error, not divergent
  359. // behavior
  360. if (!sizes[i].has_hint() || sizes[i] != 1) {
  361. first_non1_src = i;
  362. break;
  363. }
  364. }
  365. return sizes.slice(first_non1_src);
  366. }
  367. inline void copy_to(const Tensor& dst, const Tensor& src) {
  368. if (dst.sym_sizes().equals(src.sym_sizes())) {
  369. // A shortcut to avoid generating hard-coded constant sizes during tracing.
  370. // This is not a perfect solution: when src & dst have different shapes,
  371. // constants will still appear. Users can workaround that case by
  372. // dst[index..] = src.reshape(..)
  373. dst.copy_(src);
  374. return;
  375. } else if (src.dim() == 0 && src.device().type() == at::kCPU) {
  376. dst.fill_(src);
  377. return;
  378. }
  379. auto src_view = src.view_symint(slicePrefix1sSize(src.sym_sizes()));
  380. c10::MaybeOwned<Tensor> b_src = expand_inplace(dst, src_view, "setitem");
  381. dst.copy_(*b_src);
  382. }
  383. // See NOTE [ Setting `disable_slice_optimization` when calling C++ tensor
  384. // indexing functions from Python ]
  385. inline Tensor handleDimInMultiDimIndexing(
  386. const Tensor& prev_dim_result,
  387. const Tensor& original_tensor,
  388. const TensorIndex& index,
  389. int64_t* dim_ptr,
  390. int64_t* specified_dims_ptr,
  391. int64_t real_dim,
  392. std::vector<Tensor>& outIndices,
  393. bool disable_slice_optimization,
  394. const at::Device& original_tensor_device,
  395. const std::optional<SymIntArrayRef>& prev_dim_result_sizes) {
  396. if (index.is_integer()) {
  397. return impl::applySelect(
  398. prev_dim_result,
  399. *dim_ptr,
  400. index.integer(),
  401. real_dim,
  402. original_tensor_device,
  403. prev_dim_result_sizes);
  404. } else if (index.is_slice()) {
  405. Tensor result = impl::applySlice(
  406. prev_dim_result,
  407. *dim_ptr,
  408. index.slice().start(),
  409. index.slice().stop(),
  410. index.slice().step(),
  411. /*disable_slice_optimization=*/disable_slice_optimization,
  412. original_tensor_device,
  413. prev_dim_result_sizes);
  414. (*dim_ptr)++;
  415. if (!outIndices.empty()) {
  416. outIndices.resize(outIndices.size() + 1);
  417. }
  418. return result;
  419. } else if (index.is_ellipsis()) {
  420. auto ellipsis_ndims = original_tensor.dim() - *specified_dims_ptr;
  421. (*dim_ptr) += ellipsis_ndims;
  422. if (!outIndices.empty()) {
  423. outIndices.resize(outIndices.size() + ellipsis_ndims);
  424. }
  425. return prev_dim_result;
  426. } else if (index.is_none()) {
  427. Tensor result = prev_dim_result.unsqueeze(*dim_ptr);
  428. (*dim_ptr)++;
  429. if (!outIndices.empty()) {
  430. outIndices.resize(outIndices.size() + 1);
  431. }
  432. return result;
  433. } else if (index.is_boolean()) {
  434. Tensor result = prev_dim_result.unsqueeze(*dim_ptr);
  435. impl::recordTensorIndex(
  436. impl::boolToIndexingTensor(
  437. result, index.boolean(), original_tensor_device),
  438. outIndices,
  439. dim_ptr);
  440. return result;
  441. } else if (index.is_tensor()) {
  442. Tensor result = prev_dim_result;
  443. const Tensor& tensor = index.tensor();
  444. auto scalar_type = tensor.scalar_type();
  445. if (tensor.dim() == 0 &&
  446. at::isIntegralType(scalar_type, /*includeBool=*/true)) {
  447. if (scalar_type != at::kByte && scalar_type != at::kBool) {
  448. result = impl::applySelect(
  449. result,
  450. *dim_ptr,
  451. tensor.item<int64_t>(),
  452. real_dim,
  453. original_tensor_device,
  454. prev_dim_result_sizes);
  455. } else {
  456. result = result.unsqueeze(*dim_ptr);
  457. if (scalar_type == at::kBool) {
  458. impl::recordTensorIndex(
  459. impl::boolToIndexingTensor(
  460. result, tensor.item<bool>() != 0, original_tensor_device),
  461. outIndices,
  462. dim_ptr);
  463. } else {
  464. impl::recordTensorIndex(
  465. impl::boolToIndexingTensor(
  466. result, tensor.item<uint8_t>() != 0, original_tensor_device),
  467. outIndices,
  468. dim_ptr);
  469. }
  470. }
  471. } else {
  472. impl::recordTensorIndex(tensor, outIndices, dim_ptr);
  473. }
  474. return result;
  475. } else {
  476. TORCH_INTERNAL_ASSERT(false, "Invalid TensorIndex type");
  477. }
  478. }
  479. namespace impl {
  480. // This mirrors `applySlicing` in
  481. // torch/csrc/autograd/python_variable_indexing.cpp
  482. inline Tensor applySlicing(
  483. const Tensor& self,
  484. const ArrayRef<TensorIndex>& indices,
  485. std::vector<Tensor>& outIndices,
  486. bool disable_slice_optimization,
  487. const at::Device& self_device,
  488. const std::optional<SymIntArrayRef>& self_sizes) {
  489. int64_t dim = 0;
  490. int64_t specified_dims = impl::count_specified_dimensions(indices);
  491. // See NOTE [nested tensor size for indexing]
  492. if (self_sizes.has_value()) {
  493. TORCH_CHECK_INDEX(
  494. specified_dims <= (int64_t)self_sizes->size(),
  495. "too many indices for tensor of dimension ",
  496. (int)self_sizes->size());
  497. }
  498. Tensor result = self;
  499. for (const auto i : c10::irange(indices.size())) {
  500. auto& obj = indices[i];
  501. // See NOTE [nested tensor size for indexing]
  502. std::optional<SymIntArrayRef> result_sizes = result.is_nested()
  503. ? std::optional<SymIntArrayRef>(std::nullopt)
  504. : std::optional<SymIntArrayRef>(result.sym_sizes());
  505. result = handleDimInMultiDimIndexing(
  506. /*prev_dim_result=*/result,
  507. /*original_tensor=*/self,
  508. /*index=*/obj,
  509. /*dim_ptr=*/&dim,
  510. /*specified_dims_ptr=*/&specified_dims,
  511. /*real_dim=*/static_cast<int64_t>(i),
  512. /*outIndices=*/outIndices,
  513. /*disable_slice_optimization=*/disable_slice_optimization,
  514. /*original_tensor_device=*/self_device,
  515. /*prev_dim_result_sizes=*/result_sizes);
  516. }
  517. return result;
  518. }
  519. } // namespace impl
  520. inline Tensor dispatch_index(
  521. const Tensor& self,
  522. std::vector<Tensor>&& indices) {
  523. // Remove trailing null elements from indices
  524. while (!indices.empty() && !indices.back().defined()) {
  525. indices.pop_back();
  526. }
  527. return self.index(impl::typeConvertIndices(self, std::move(indices)));
  528. }
  529. inline Tensor dispatch_index_put_(
  530. Tensor& self,
  531. std::vector<Tensor>&& indices,
  532. const Tensor& value) {
  533. // Remove trailing null elements from indices
  534. while (!indices.empty() && !indices.back().defined()) {
  535. indices.pop_back();
  536. }
  537. return self.index_put_(
  538. impl::typeConvertIndices(self, std::move(indices)), value);
  539. }
  540. // NOTE [ Setting `disable_slice_optimization` when calling C++ tensor indexing
  541. // functions from Python ]
  542. //
  543. // Question: When should we set `disable_slice_optimization` to `true` when
  544. // calling C++ tensor indexing functions from Python indexing code?
  545. //
  546. // Answer: What "slice optimization" means: when we have a slicing expression
  547. // like `x[0:5, 0]`, where the sliced tensor was of size 5 in dimension 0, we
  548. // would skip dispatching the actual slice call as an optimization. However,
  549. // here are the cases where we DON'T want this optimization:
  550. //
  551. // 1. When we are doing 1-D slicing (e.g. `tensor[:]`).
  552. // Reason: we always return a shallow copy for expressions such as
  553. // `tensor[:]` / `tensor[...]` / `tensor[:, :]`. (Note that for `tensor[:,
  554. // :]`, we return an alias of `tensor` by doing the following:
  555. // ```
  556. // Tensor sliced = impl::applySlicing(self, indices, tensorIndices,
  557. // disable_slice_optimization, self_device, self_sizes); if
  558. // (tensorIndices.empty()) {
  559. // if (sliced.is_same(self)) {
  560. // // ensure we return a shallow copy for things like x[...]
  561. // sliced = at::alias(sliced);
  562. // }
  563. // return sliced;
  564. // }
  565. // ```)
  566. // 2. When we are doing JIT tracing.
  567. // Reason: JIT tracing needs the `self.slice(...)` call to properly trace the
  568. // slice operation.
  569. // This mirrors `THPVariable_getitem` in
  570. // torch/csrc/autograd/python_variable_indexing.cpp See NOTE [ Setting
  571. // `disable_slice_optimization` when calling C++ tensor indexing functions from
  572. // Python ]
  573. inline Tensor get_item(
  574. const Tensor& self,
  575. const ArrayRef<TensorIndex>& indices,
  576. bool disable_slice_optimization = false) {
  577. at::Device self_device = self.device();
  578. // NOTE [nested tensor size for indexing]
  579. // nested tensor does not have a size (yet) so for now we represent its size
  580. // as null may need to be changed after we reach a better solution for nested
  581. // tensor size
  582. std::optional<SymIntArrayRef> self_sizes = self.is_nested()
  583. ? std::optional<SymIntArrayRef>(std::nullopt)
  584. : std::optional<SymIntArrayRef>(self.sym_sizes());
  585. // handle simple types: integers, slices, none, ellipsis, bool
  586. if (indices.size() == 1) {
  587. const TensorIndex& index = indices[0];
  588. if (index.is_integer()) {
  589. return impl::applySelect(
  590. self, 0, index.integer(), 0, self_device, self_sizes);
  591. } else if (index.is_slice()) {
  592. return impl::applySlice(
  593. self,
  594. 0,
  595. index.slice().start(),
  596. index.slice().stop(),
  597. index.slice().step(),
  598. /*disable_slice_optimization=*/true,
  599. self_device,
  600. self_sizes);
  601. } else if (index.is_none()) {
  602. return self.unsqueeze(0);
  603. } else if (index.is_ellipsis()) {
  604. return at::alias(self);
  605. } else if (index.is_boolean()) {
  606. Tensor result = self.unsqueeze(0);
  607. return dispatch_index(
  608. result,
  609. std::vector<Tensor>{impl::boolToIndexingTensor(
  610. result, index.boolean(), self_device)});
  611. }
  612. }
  613. std::vector<Tensor> tensorIndices;
  614. Tensor sliced = impl::applySlicing(
  615. self,
  616. indices,
  617. tensorIndices,
  618. disable_slice_optimization,
  619. self_device,
  620. self_sizes);
  621. if (tensorIndices.empty()) {
  622. if (sliced.is_same(self)) {
  623. // ensure we return a shallow copy for things like x[...]
  624. sliced = at::alias(sliced);
  625. }
  626. return sliced;
  627. }
  628. // indexing by tensors ("advanced" indexing)
  629. return dispatch_index(sliced, std::move(tensorIndices));
  630. }
  631. // This mirrors `THPVariable_setitem` in
  632. // torch/csrc/autograd/python_variable_indexing.cpp for "the assigned value is a
  633. // Tensor" case See NOTE [ Setting `disable_slice_optimization` when calling C++
  634. // tensor indexing functions from Python ]
  635. inline void set_item(
  636. const Tensor& self,
  637. const ArrayRef<TensorIndex>& indices,
  638. const Tensor& value,
  639. bool disable_slice_optimization = false) {
  640. at::Device self_device = self.device();
  641. SymIntArrayRef self_sizes = self.sym_sizes();
  642. // handle simple types: integers, slices, ellipsis, bool
  643. if (indices.size() == 1) {
  644. const TensorIndex& index = indices[0];
  645. if (index.is_boolean() && !index.boolean()) {
  646. // do nothing for false (technically we should check the size, but we
  647. // don't have real 0-sized shapes.
  648. return;
  649. } else if (index.is_ellipsis()) {
  650. copy_to(self, value);
  651. return;
  652. } else if (index.is_none() || (index.is_boolean() && index.boolean())) {
  653. copy_to(self.unsqueeze(0), value);
  654. return;
  655. } else if (index.is_integer()) {
  656. copy_to(
  657. impl::applySelect(
  658. self, 0, index.integer(), 0, self_device, self_sizes),
  659. value);
  660. return;
  661. } else if (index.is_slice()) {
  662. copy_to(
  663. impl::applySlice(
  664. self,
  665. 0,
  666. index.slice().start(),
  667. index.slice().stop(),
  668. index.slice().step(),
  669. /*disable_slice_optimization=*/disable_slice_optimization,
  670. self_device,
  671. self_sizes),
  672. value);
  673. return;
  674. }
  675. }
  676. std::vector<Tensor> tensorIndices;
  677. Tensor sliced = impl::applySlicing(
  678. self,
  679. indices,
  680. tensorIndices,
  681. disable_slice_optimization,
  682. self_device,
  683. self_sizes);
  684. if (tensorIndices.empty()) {
  685. copy_to(sliced, value);
  686. return;
  687. }
  688. SymIntArrayRef valueSizes = value.sym_sizes();
  689. SymIntArrayRef slicedValueSizes = slicePrefix1sSize(valueSizes);
  690. Tensor valuesSliced;
  691. if (!valueSizes.equals(slicedValueSizes)) {
  692. valuesSliced = value.view_symint(slicedValueSizes);
  693. } else {
  694. valuesSliced = value;
  695. }
  696. dispatch_index_put_(sliced, std::move(tensorIndices), valuesSliced);
  697. return;
  698. }
  699. } // namespace at::indexing