tvm
transform.h
Go to the documentation of this file.
1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
24 #ifndef TVM_TOPI_TRANSFORM_H_
25 #define TVM_TOPI_TRANSFORM_H_
26 
27 #include <tvm/arith/analyzer.h>
28 #include <tvm/te/operation.h>
29 #include <tvm/tir/data_layout.h>
30 #include <tvm/tir/index_map.h>
31 #include <tvm/topi/broadcast.h>
37 #include <tvm/topi/tags.h>
38 
39 #include <algorithm>
40 #include <iterator>
41 #include <limits>
42 #include <string>
43 #include <unordered_set>
44 #include <utility>
45 #include <vector>
46 
47 #include "tvm/ir/expr.h"
48 #include "tvm/runtime/data_type.h"
49 #include "tvm/tir/expr.h"
50 #include "tvm/tir/op.h"
51 #include "tvm/tir/var.h"
52 
53 namespace tvm {
54 namespace topi {
55 
56 using namespace tvm::te;
57 using namespace topi::detail;
58 
76 inline Tensor sliding_window(const Tensor& x, int axis, ffi::Array<Integer> window_shape,
77  ffi::Array<Integer> strides, std::string name = "T_sliding_window",
78  std::string tag = "") {
79  CHECK_GE(axis, 0);
80  auto _axis = size_t(axis);
81  CHECK_LT(_axis, x->shape.size()) << "axis must be a valid dimension index of x.";
82  CHECK_EQ(x->shape.size() - _axis, window_shape.size())
83  << "There must be a window shape for every dimension of x "
84  << "over which we are sliding the window.";
85  CHECK_EQ(strides.size(), window_shape.size()) << "Windows and strides should be the same length.";
86 
87  // Compute the new shape.
88  ffi::Array<PrimExpr> new_shape;
89  // Dimensions up until `axis` remain the same.
90  for (size_t i = 0; i < _axis; ++i) {
91  new_shape.push_back(x->shape[i]);
92  }
93 
94  // New dimensions which result from sliding the window in each dimension. One new dimension per
95  // window dimension.
96  for (size_t i = 0; i < window_shape.size(); ++i) {
97  // Length of the shape along this dimension.
98  auto dim_len = x->shape[_axis + i];
99  // Length of the window along this dimension.
100  auto window_len = window_shape[i];
101  // Strides along this dimension.
102  auto stride = strides[i];
103 
104  new_shape.push_back(floordiv(dim_len - (window_len - 1) + stride - 1, stride));
105  }
106 
107  // Dimensions comprising the window.
108  for (size_t i = 0; i < window_shape.size(); ++i) {
109  new_shape.push_back(window_shape[i]);
110  }
111 
112  ICHECK(new_shape.size() == _axis + 2 * window_shape.size());
113 
114  return compute(
115  new_shape,
116  [&](const ffi::Array<Var>& indices) {
117  // The index at which to index the old tensor x.
118  ffi::Array<PrimExpr> idx;
119 
120  // Dimensions up until `axis` remain the same.
121  for (size_t i = 0; i < _axis; ++i) {
122  idx.push_back(indices[i]);
123  }
124 
125  for (size_t i = 0; i < window_shape.size(); ++i) {
126  // Which window in this dimension we are indexing.
127  auto window_idx = indices[_axis + i];
128  // Which index within the window we are indexing.
129  auto idx_within_window = indices[_axis + window_shape.size() + i];
130  // Stride value for this dimension.
131  auto stride = strides[i];
132 
133  idx.push_back(window_idx * stride + idx_within_window);
134  }
135 
136  ICHECK(idx.size() == x->shape.size());
137 
138  return x(idx);
139  },
140  name, tag);
141 }
142 
155 inline Tensor expand_dims(const Tensor& x, int axis, int num_newaxis = 1,
156  std::string name = "T_expand_dims", std::string tag = kBroadcast) {
157  int ndim = static_cast<int>(x->shape.size());
158  ICHECK(-ndim - 1 <= axis && axis <= ndim)
159  << "expand_dims only accepts `axis` in [-data.ndim - 1, data.ndim]"
160  << ", but got axis = " << axis << ", and data.ndim = " << ndim;
161  ICHECK(num_newaxis >= 0) << "expand_dims only accepts `num_newaxis >= 0`"
162  << ", but got num_newaxis = " << num_newaxis;
163  if (axis < 0) {
164  // Calculate offset from last dimension
165  axis = ndim + axis + 1;
166  }
167  ffi::Array<PrimExpr> new_shape;
168  for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {
169  new_shape.push_back(x->shape[i]);
170  }
171  for (size_t i = 0; i < static_cast<size_t>(num_newaxis); ++i) {
172  new_shape.push_back(1);
173  }
174  for (size_t i = axis; i < x->shape.size(); ++i) {
175  new_shape.push_back(x->shape[i]);
176  }
177 
178  return compute(
179  new_shape,
180  [&](const ffi::Array<Var>& indices) {
181  ffi::Array<PrimExpr> idx;
182  for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {
183  idx.push_back(indices[i]);
184  }
185  for (size_t i = axis + num_newaxis; i < indices.size(); ++i) {
186  idx.push_back(indices[i]);
187  }
188  return x(idx);
189  },
190  name, tag);
191 }
192 
204 inline Tensor transpose(const Tensor& x, ffi::Optional<ffi::Array<Integer>> opt_axes,
205  std::string name = "T_transpose", std::string tag = kInjective) {
206  ffi::Array<Integer> axes = opt_axes.value_or({});
207  if (axes.size() == 0) {
208  for (int i = static_cast<int>(x->shape.size()) - 1; i >= 0; --i) {
209  axes.push_back(i);
210  }
211  }
212 
213  ffi::Array<PrimExpr> new_shape;
214  for (size_t i = 0; i < axes.size(); ++i) {
215  int axis = static_cast<int>(axes[i]->value);
216  int new_axis = axis;
217  if (axis < 0) {
218  new_axis = static_cast<int>(x->shape.size()) + axis;
219  axes.Set(i, new_axis);
220  }
221  ICHECK((new_axis >= 0) && (new_axis < static_cast<int>(x->shape.size())))
222  << "axis=" << axis << " is invalid for the " << static_cast<int>(x->shape.size())
223  << "-dimensional input tensor";
224 
225  for (size_t j = 0; j < axes.size(); ++j) {
226  if (i != j) {
227  ICHECK(new_axis != static_cast<int>(axes[j]->value)) << "repeated axis in transpose";
228  }
229  }
230  new_shape.push_back(x->shape[new_axis]);
231  }
232 
233  return compute(
234  new_shape,
235  [&](const ffi::Array<Var>& indices) {
236  std::vector<PrimExpr> idx;
237  for (size_t i = 0; i < axes.size(); ++i) {
238  idx.push_back(1);
239  }
240  for (size_t i = 0; i < axes.size(); ++i) {
241  int axis = static_cast<int>(axes[i]->value);
242  idx[axis] = indices[i];
243  }
244  return x(idx);
245  },
246  name, tag);
247 }
248 
263 inline Tensor reverse_sequence(const Tensor& x, const Tensor& seq_lengths, int seq_axis = 1,
264  int batch_axis = 0, std::string name = "T_reverse_sequence",
265  std::string tag = kInjective) {
266  size_t src_tensor_dim = x->shape.size();
267  int seq_axis_inp = seq_axis;
268 
269  if (seq_lengths.defined()) {
270  size_t seq_lengths_dim = seq_lengths->shape.size();
271  int batch_axis_inp = batch_axis;
272  if (batch_axis < 0) {
273  batch_axis = static_cast<int>(x->shape.size()) + batch_axis;
274  }
275 
276  ICHECK(seq_lengths_dim == 1) << "seq_lengths should be 1D vector";
277 
278  ICHECK(GetConstInt(seq_lengths->shape[0]) == GetConstInt(x->shape[batch_axis]))
279  << "For reverse_sequnece seq_lengths size should match with dimension of batch axis"
280  << ", but got dimension of batch_axis = " << GetConstInt(x->shape[batch_axis])
281  << ", and seq_length size = " << GetConstInt(seq_lengths->shape[0]);
282 
283  ICHECK((0 <= batch_axis) && (batch_axis < static_cast<int>(x->shape.size())))
284  << "batch_axis=" << batch_axis_inp << " is invalid for the "
285  << static_cast<int>(x->shape.size()) << "-dimensional input tensor";
286  }
287 
288  if (seq_axis < 0) {
289  seq_axis = static_cast<int>(x->shape.size()) + seq_axis;
290  }
291  ICHECK((0 <= seq_axis) && (seq_axis < static_cast<int>(x->shape.size())))
292  << "seq_axis=" << seq_axis_inp << " is invalid for the " << static_cast<int>(x->shape.size())
293  << "-dimensional input tensor";
294 
295  auto func = [&](const ffi::Array<Var>& indices) {
296  ffi::Array<PrimExpr> real_indices;
297  for (size_t i = 0; i < src_tensor_dim; ++i) {
298  if (i == static_cast<size_t>(seq_axis)) {
299  if (seq_lengths.defined()) {
300  auto len = seq_lengths(indices[batch_axis]);
301  auto idx = if_then_else(
302  len <= 1 || len <= indices[i], indices[i],
303  if_then_else(len > x->shape[i], x->shape[i] - 1 - indices[i], len - 1 - indices[i]));
304  real_indices.push_back(idx);
305  } else {
306  real_indices.push_back(x->shape[i] - 1 - indices[i]);
307  }
308  } else {
309  real_indices.push_back(indices[i]);
310  }
311  }
312  return x(real_indices);
313  };
314 
315  return compute(x->shape, func, name, tag);
316 }
317 
328 inline Tensor reshape(const Tensor& x, ffi::Array<PrimExpr> newshape,
329  std::string name = "T_reshape", std::string tag = kInjective) {
330  auto x_shape = x->shape;
331  ffi::Array<PrimExpr> target_shape;
332 
333  for (const auto& ele : newshape) {
334  target_shape.push_back(ele);
335  }
336 
337  // If either the input shape or the target shape contains a zero, return an empty tensor.
338  if (is_empty_shape(target_shape) || is_empty_shape(x->shape)) {
339  return compute(
340  target_shape, [&](const ffi::Array<Var>& indices) { return tvm::cast(x->dtype, 0); }, name,
341  tag);
342  } else {
343  return compute(
344  target_shape,
345  [&](const ffi::Array<Var>& indices) {
346  return x(UnravelIndex(
347  RavelIndex(ffi::Array<PrimExpr>{indices.begin(), indices.end()}, target_shape),
348  x_shape));
349  },
350  name, tag);
351  }
352 }
353 
365 inline Tensor unravel_index(const Tensor& x, const Tensor& shape, std::string name = "T_unravel",
366  std::string tag = kInjective) {
367  auto x_shape = x->shape;
368  auto shape_shape = shape->shape;
369 
370  ffi::Array<PrimExpr> oshape;
371  oshape.push_back(shape_shape[0]);
372  if (x_shape.size() != 0) {
373  oshape.push_back(x_shape[0]);
374  }
375 
376  auto func = [&](const ffi::Array<Var>& indices) {
377  auto i = indices[0];
378  std::vector<PrimExpr> indices_divs;
379  PrimExpr ret = 0;
380  PrimExpr cur_val = 0;
381  PrimExpr index_val = 0;
382 
383  if (x_shape.size() != 0) {
384  index_val = x[indices[1]];
385  } else {
386  index_val = x();
387  }
388  indices_divs.push_back(index_val);
389  for (int v = GetConstInt(shape_shape[0]) - 1; v >= 0; --v) {
390  ret = tvm::if_then_else(i == v, indexmod(indices_divs.back(), shape[v]), ret);
391  cur_val = indexdiv(indices_divs.back(), shape[v]);
392  indices_divs.push_back(cur_val);
393  }
394  return ret;
395  };
396 
397  return compute(oshape, func, name, tag);
398 }
399 
413 inline Tensor squeeze(const Tensor& x, ffi::Optional<ffi::Array<Integer>> opt_axes,
414  bool atleast1d = false, std::string name = "T_squeeze",
415  std::string tag = kInjective) {
416  auto ndim = x->shape.size();
417  std::vector<int> axis_val;
418  if (!opt_axes.has_value()) {
419  for (size_t i = 0; i < ndim; ++i) {
420  if (IsConstInt(x->shape[i]) && GetConstInt(x->shape[i]) == 1) {
421  axis_val.push_back(static_cast<int>(i));
422  }
423  }
424  } else {
425  ffi::Array<Integer> axis = *std::move(opt_axes);
426  for (size_t i = 0; i < axis.size(); ++i) {
427  int64_t val = axis[i]->value;
428  if (val < 0) {
429  val += static_cast<int>(x->shape.size());
430  }
431  if (IsConstInt(x->shape[val])) {
432  ICHECK_EQ(GetConstInt(x->shape[val]), 1) << "Dimension " << val << " must have size 1";
433  }
434  axis_val.push_back(val);
435  }
436  }
437 
438  std::unordered_set<int> axis_set(axis_val.begin(), axis_val.end());
439 
440  ffi::Array<PrimExpr> out_shape;
441  for (size_t i = 0; i < ndim; ++i) {
442  if (axis_set.count(static_cast<int>(i)) == 0) {
443  out_shape.push_back(x->shape[i]);
444  }
445  }
446  if (out_shape.size() == 0 && atleast1d) {
447  out_shape.push_back(1);
448  }
449 
450  return compute(
451  out_shape,
452  [&](const ffi::Array<Var>& indices) {
453  ffi::Array<PrimExpr> real_indices;
454  int flag = 0;
455  for (size_t i = 0; i < ndim; ++i) {
456  if (axis_set.count(static_cast<int>(i)) == 0) {
457  real_indices.push_back(indices[i - flag]);
458  } else {
459  real_indices.push_back(0);
460  flag += 1;
461  }
462  }
463  return x(real_indices);
464  },
465  name, tag);
466 }
467 
478 inline Tensor concatenate(const ffi::Array<Tensor>& inputs, int axis = 0,
479  std::string name = "T_concat", std::string tag = kInjective) {
480  int ndim = static_cast<int>(inputs[0]->shape.size());
481  ICHECK(-ndim <= axis && axis < ndim) << "concatenate only accepts `axis` in [-ndim, ndim)"
482  << ", but got axis = " << axis << ", and ndim = " << ndim;
483  if (axis < 0) {
484  axis += ndim;
485  }
486  ICHECK_LT(axis, inputs[0]->shape.size()) << "axis out of bounds";
487 
488  ffi::Array<PrimExpr> axis_sizes;
489  for (auto t : inputs) {
490  axis_sizes.push_back(t->shape[axis]);
491  }
492  arith::Analyzer analyzer;
493  PrimExpr join_size = axis_sizes[0];
494  for (size_t i = 1; i < axis_sizes.size(); ++i) {
495  join_size += axis_sizes[i];
496  }
497  join_size = analyzer.Simplify(join_size);
498  ffi::Array<PrimExpr> out_shape;
499  for (size_t i = 0; i < inputs[0]->shape.size(); ++i) {
500  out_shape.push_back(i == static_cast<size_t>(axis) ? join_size : inputs[0]->shape[i]);
501  }
502 
503  return compute(
504  out_shape,
505  [&](const ffi::Array<Var>& indices) {
506  auto ret = inputs[0](indices);
507  auto ind = indices[axis];
508  for (size_t i = 0; i < inputs.size() - 1; ++i) {
509  ind -= axis_sizes[i];
510 
511  ffi::Array<PrimExpr> idx;
512  for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {
513  idx.push_back(indices[i]);
514  }
515  idx.push_back(ind);
516  for (size_t i = axis + 1; i < indices.size(); ++i) {
517  idx.push_back(indices[i]);
518  }
519 
520  ret = tvm::if_then_else(ind >= 0, inputs[i + 1](idx), ret);
521  }
522  return ret;
523  },
524  name, tag);
525 }
526 
537 inline Tensor stack(const ffi::Array<Tensor>& inputs, int axis = 0, std::string name = "T_stack",
538  std::string tag = kInjective) {
539  int ndim = static_cast<int>(inputs[0]->shape.size());
540  ICHECK(-ndim - 1 <= axis && axis <= ndim)
541  << "stack only accepts `axis` in [-ndim, ndim)"
542  << ", but got axis = " << axis << ", and ndim = " << ndim;
543  if (axis < 0) {
544  axis += ndim + 1;
545  }
546  ICHECK_LT(axis, inputs[0]->shape.size() + 1) << "axis out of bounds";
547 
548  const int stack_size = static_cast<int>(inputs.size());
549  ffi::Array<PrimExpr> out_shape;
550  for (size_t i = 0; i < static_cast<size_t>(axis); ++i) out_shape.push_back(inputs[0]->shape[i]);
551  out_shape.push_back(stack_size);
552  for (size_t i = static_cast<size_t>(axis); i < static_cast<size_t>(ndim); ++i)
553  out_shape.push_back(inputs[0]->shape[i]);
554 
555  return compute(
556  out_shape,
557  [&](const ffi::Array<Var>& indices) {
558  ffi::Array<PrimExpr> idx;
559  for (size_t i = 0; i < indices.size(); ++i)
560  if (i != static_cast<size_t>(axis)) idx.push_back(indices[i]);
561  auto ind = indices[axis];
562  auto ret = inputs[0](idx);
563  for (int i = 0; i < static_cast<int>(inputs.size() - 1); ++i) {
564  ret = tvm::if_then_else(ind == i + 1, inputs[i + 1](idx), ret);
565  }
566  return ret;
567  },
568  name, tag);
569 }
570 
583 inline ffi::Array<Tensor> split_indices_array(const Tensor& x, ffi::Array<PrimExpr> split_indices,
584  int axis, std::string name = "T_split",
585  std::string tag = kInjective) {
586  if (axis < 0) {
587  axis += static_cast<int>(x->shape.size());
588  }
589  ICHECK_LT(axis, x->shape.size()) << "axis out of bounds";
590 
591  auto src_axis_size = x->shape[axis];
592  std::vector<PrimExpr> begin_ids;
593  begin_ids.push_back(0);
594 
595  for (auto idx : split_indices) {
596  auto idx_node = idx.as<IntImmNode>();
597  auto back_node = begin_ids.back().as<IntImmNode>();
598  if (idx_node && back_node) {
599  ICHECK_GT(idx_node->value, back_node->value) << "split_indices must be sorted";
600  }
601  begin_ids.push_back(idx);
602  }
603 
604  ffi::Array<ffi::Array<PrimExpr>> out_shapes;
605  for (size_t i = 0; i < begin_ids.size(); ++i) {
606  PrimExpr out_axis_size;
607  if (i == begin_ids.size() - 1) {
608  out_axis_size = src_axis_size - begin_ids[i];
609  } else {
610  out_axis_size = begin_ids[i + 1] - begin_ids[i];
611  }
612 
613  ffi::Array<PrimExpr> shape;
614  for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {
615  shape.push_back(x->shape[i]);
616  }
617  shape.push_back(out_axis_size);
618  for (size_t i = axis + 1; i < x->shape.size(); ++i) {
619  shape.push_back(x->shape[i]);
620  }
621 
622  out_shapes.push_back(shape);
623  }
624 
625  ffi::Array<Tensor> result;
626  for (size_t i = 0; i < begin_ids.size(); ++i) {
627  result.push_back(compute(
628  out_shapes[i],
629  [&](const ffi::Array<Var>& indices) {
630  auto begin = begin_ids[i];
631  ffi::Array<PrimExpr> real_indices;
632  for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {
633  real_indices.push_back(indices[j]);
634  }
635  real_indices.push_back(indices[axis] + begin);
636  for (size_t j = axis + 1; j < indices.size(); ++j) {
637  real_indices.push_back(indices[j]);
638  }
639 
640  return x(real_indices);
641  },
642  name, tag));
643  }
644 
645  return result;
646 }
647 
649  auto idx_var = index.as<tvm::tir::VarNode>();
650  auto extent_var = extent.as<tvm::tir::VarNode>();
651 
652  if (idx_var && extent_var && idx_var->name_hint == extent_var->name_hint) {
653  return index;
654  }
655 
656  PrimExpr begin_range = tvm::if_then_else(stride < 0, -1, 0);
657  PrimExpr end_range = tvm::if_then_else(stride < 0, extent - 1, extent);
658 
659  if (!(index->IsInstance<tvm::IntImmNode>() && GetConstInt(index) >= 0)) {
660  index = tvm::if_then_else(index < 0, index + extent, index);
661  }
662 
663  return tvm::min(tvm::max(index, begin_range), end_range);
664 }
665 
666 inline int64_t StaticCanonicalizeIndex(int64_t index, int64_t extent, int64_t stride) {
667  int64_t begin_range = stride < 0 ? -1 : 0;
668  int64_t end_range = stride < 0 ? extent - 1 : extent;
669  if (index < 0) {
670  index += extent;
671  }
672  return std::min(std::max(index, begin_range), end_range);
673 }
674 
675 inline PrimExpr CanonicalizeIndex(PrimExpr index, PrimExpr extent, PrimExpr stride) {
676  if (index->IsInstance<tvm::IntImmNode>() && extent->IsInstance<tvm::IntImmNode>() &&
677  stride->IsInstance<tvm::IntImmNode>()) {
678  return tvm::IntImm(
679  tvm::DataType::Int(64),
680  StaticCanonicalizeIndex(GetConstInt(index), GetConstInt(extent), GetConstInt(stride)));
681  }
682  return DynamicCanonicalizeIndex(index, extent, stride);
683 }
684 
685 inline PrimExpr GetLength(PrimExpr begin, PrimExpr end, PrimExpr stride, PrimExpr extent,
686  bool assume_inbound = true) {
687  if (assume_inbound) {
688  return ceildiv(end - begin, stride);
689  } else {
690  begin = CanonicalizeIndex(begin, extent, stride);
691  end = CanonicalizeIndex(end, extent, stride);
692  return tvm::if_then_else(stride < 0, ceildiv(begin - end, -stride),
693  ceildiv(end - begin, stride));
694  }
695 }
696 
713  const te::Tensor& x, const ffi::Array<PrimExpr>& begin, const ffi::Array<PrimExpr>& end,
714  const ffi::Array<PrimExpr>& strides, const ffi::Array<Integer>& axes,
715  bool assume_inbound = true, std::string name = "T_dynamic_strided_slice_with_axes",
716  std::string tag = kInjective) {
717  const size_t src_tensor_dim = x->shape.size();
718  ICHECK_EQ(begin.size(), end.size());
719  ICHECK_EQ(begin.size(), strides.size());
720  ICHECK_EQ(begin.size(), axes.size());
721  ICHECK_LE(begin.size(), src_tensor_dim);
722 
723  for (const auto& axis_imm : axes) {
724  int axis = axis_imm->value;
725  ICHECK_LT(axis, src_tensor_dim);
726  }
727 
728  arith::Analyzer analyzer;
729 
730  ffi::Array<PrimExpr> out_shape = x->shape;
731  for (size_t i = 0; i < begin.size(); i++) {
732  int axis = axes[i]->value;
733  PrimExpr new_shape =
734  analyzer.Simplify(GetLength(begin[i], end[i], strides[i], out_shape[axis], assume_inbound));
735  out_shape.Set(axis, new_shape);
736  }
737 
738  return te::compute(
739  out_shape,
740  [&](const ffi::Array<tvm::tir::Var>& indices) {
741  ffi::Array<PrimExpr> real_indices =
742  indices.Map([](const auto& var) -> PrimExpr { return var; });
743 
744  for (size_t i = 0; i < begin.size(); i++) {
745  int axis = axes[i]->value;
746  PrimExpr new_index = indices[axis] * strides[i] + begin[i];
747  real_indices.Set(axis, new_index);
748  }
749 
750  return x(real_indices);
751  },
752  name, tag);
753 }
754 
769 inline Tensor dynamic_strided_slice(const Tensor& x, const ffi::Array<PrimExpr>& begin,
770  const ffi::Array<PrimExpr>& end,
771  const ffi::Array<PrimExpr>& strides, bool assume_inbound = true,
772  std::string name = "T_dynamic_strided_slice",
773  std::string tag = kInjective) {
774  const size_t src_tensor_dim = x->shape.size();
775  ICHECK_LE(begin.size(), src_tensor_dim);
776  ICHECK_LE(end.size(), src_tensor_dim);
777  ICHECK_LE(strides.size(), src_tensor_dim);
778  ICHECK_EQ(begin.size(), end.size());
779  ICHECK_EQ(begin.size(), strides.size());
780 
781  const size_t num_slice_axes = begin.size();
782  ffi::Array<PrimExpr> out_shape;
783 
784  arith::Analyzer analyzer;
785  for (size_t i = 0; i < num_slice_axes; ++i) {
786  // Check ProducerLoad to keep backward compatibility for Relax.
787  if (!begin[i]->IsInstance<ProducerLoadNode>() && !end[i]->IsInstance<ProducerLoadNode>() &&
788  !strides[i]->IsInstance<ProducerLoadNode>()) {
789  out_shape.push_back(
790  analyzer.Simplify(GetLength(begin[i], end[i], strides[i], x->shape[i], assume_inbound)));
791  } else {
792  out_shape.push_back(tvm::tir::Var("dim"));
793  }
794  }
795 
796  for (size_t i = num_slice_axes; i < src_tensor_dim; ++i) {
797  out_shape.push_back(x->shape[i]);
798  }
799 
800  return te::compute(
801  out_shape,
802  [&](const ffi::Array<tvm::tir::Var>& indices) {
803  ffi::Array<PrimExpr> real_indices;
804  for (size_t i = 0; i < num_slice_axes; ++i) {
805  real_indices.push_back(indices[i] * strides[i] + tvm::min(begin[i], x->shape[i] - 1));
806  }
807  // keep input dim
808  for (size_t i = num_slice_axes; i < src_tensor_dim; ++i) {
809  real_indices.push_back(indices[i]);
810  }
811  return x(real_indices);
812  },
813  name, tag);
814 }
815 
831  const te::Tensor& end, const te::Tensor& strides,
832  bool assume_inbound = true,
833  std::string name = "T_strided_slice_dynamic",
834  std::string tag = topi::kInjective) {
835  DataType index_dtype = begin->shape[0]->dtype;
836  const int64_t num_dynamic_axes = begin->shape[0].as<IntImmNode>()->value;
837  ICHECK_EQ(end->shape[0].as<IntImmNode>()->value, num_dynamic_axes);
838  ICHECK_EQ(strides->shape[0].as<IntImmNode>()->value, num_dynamic_axes);
839 
840  ffi::Array<PrimExpr> begin_expr, end_expr, strides_expr;
841  for (int64_t i = 0; i < num_dynamic_axes; ++i) {
842  auto ind = make_const(index_dtype, i);
843  begin_expr.push_back(begin(ind));
844  end_expr.push_back(end(ind));
845  strides_expr.push_back(strides(ind));
846  }
847  return dynamic_strided_slice(x, begin_expr, end_expr, strides_expr, assume_inbound, name, tag);
848 }
849 
864 inline ffi::Array<PrimExpr> StridedSliceOutputShape(const ffi::Array<PrimExpr>& ishape,
865  const ffi::Array<Integer>& begin,
866  const ffi::Array<Integer>& end,
867  const ffi::Array<Integer>& strides,
868  const ffi::Array<Integer>& axes,
869  const std::string& slice_mode) {
870  ICHECK(axes.size() == begin.size() && axes.size() == end.size() && axes.size() == strides.size());
871  std::vector<int64_t> begin_vec, end_vec, strides_vec;
872  std::tie(begin_vec, end_vec, strides_vec) = ConvertToVec(begin, end, strides, slice_mode);
873  auto begin_canonicalized = StridedSliceCanonicalizeBegin(ishape, begin_vec, strides_vec, axes,
874  begin[0]->dtype, slice_mode);
875  return StridedSliceOutputShape(ishape, begin_vec, end_vec, strides_vec, axes, slice_mode,
876  begin_canonicalized, true);
877 }
878 
895 inline Tensor strided_slice_with_axes(const Tensor& x, const ffi::Array<Integer>& begin,
896  const ffi::Array<Integer>& end,
897  const ffi::Array<Integer>& strides,
898  const ffi::Array<Integer>& axes,
899  std::string slice_mode = "end",
900  std::string name = "T_strided_slice_with_axes",
901  std::string tag = kInjective) {
902  const size_t src_tensor_dim = x->shape.size();
903  ICHECK(axes.size() <= src_tensor_dim);
904  ICHECK(axes.size() == begin.size() && axes.size() == end.size() && axes.size() == strides.size());
905 
906  std::vector<int64_t> begin_vec, end_vec, strides_vec;
907  std::tie(begin_vec, end_vec, strides_vec) = ConvertToVec(begin, end, strides, slice_mode);
908 
909  auto begin_expr = StridedSliceCanonicalizeBegin(x->shape, begin_vec, strides_vec, axes,
910  begin[0]->dtype, slice_mode);
911  auto out_shape = StridedSliceOutputShape(x->shape, begin_vec, end_vec, strides_vec, axes,
912  slice_mode, begin_expr);
913 
914  return te::compute(
915  out_shape,
916  [&](const ffi::Array<tir::Var>& indices) {
917  ffi::Array<PrimExpr> real_indices;
918  for (size_t i = 0; i < out_shape.size(); ++i) real_indices.push_back(indices[i]);
919  for (size_t i = 0; i < axes.size(); ++i) {
920  auto stride = make_const(strides[i].dtype(), strides_vec[i]);
921  PrimExpr ind = indices[axes[i].IntValue()] * stride + begin_expr[i];
922  real_indices.Set(axes[i].IntValue(), ind);
923  }
924  return x(real_indices);
925  },
926  name, tag);
927 }
928 
943 inline Tensor strided_slice(const Tensor& x, const ffi::Array<Integer>& begin,
944  const ffi::Array<Integer>& end, const ffi::Array<Integer>& strides,
945  std::string slice_mode = "end", std::string name = "T_strided_slice",
946  std::string tag = kInjective) {
947  size_t src_tensor_dim = static_cast<size_t>(x->shape.size());
948  ffi::Array<Integer> axes;
949  for (size_t i = 0; i < src_tensor_dim; ++i) axes.push_back(i);
950  ffi::Array<Integer> begin_full(begin);
951  ffi::Array<Integer> end_full(end);
952  ffi::Array<Integer> strides_full(strides);
953 
954  DataType index_dtype = begin.size() > 0 ? begin[0]->dtype : DataType::Int(64);
955  const IntImm one = IntImm(index_dtype, 1);
956  const IntImm zero = IntImm(index_dtype, 0);
957  const IntImm max_range = Downcast<IntImm>(max_value(index_dtype));
958 
959  for (size_t i = strides.size(); i < src_tensor_dim; ++i) {
960  strides_full.push_back(one);
961  }
962  for (size_t i = begin.size(); i < src_tensor_dim; ++i) {
963  begin_full.push_back(GetConstInt(strides_full[i]) > 0 ? zero : max_range);
964  }
965  for (size_t i = end.size(); i < src_tensor_dim; ++i) {
966  end_full.push_back(GetConstInt(strides_full[i]) < 0 ? zero : max_range);
967  }
968 
969  return strided_slice_with_axes(x, begin_full, end_full, strides_full, axes, slice_mode, name,
970  tag);
971 }
972 
985 inline ffi::Array<Tensor> split_n_sections(const Tensor& x, int num_sections, int axis,
986  std::string name = "T_split_sections",
987  std::string tag = kInjective) {
988  if (axis < 0) {
989  axis += static_cast<int>(x->shape.size());
990  }
991  ICHECK_LT(axis, x->shape.size()) << "axis out of bounds";
992 
993  auto src_axis_size = x->shape[axis];
994 
995  ICHECK_GT(num_sections, 0) << "Slice count must be > 0";
996 
997  ffi::Array<PrimExpr> split_indices;
998  auto seg_size = indexdiv(src_axis_size + num_sections - 1, num_sections);
999  for (int i = 0; i < num_sections; ++i) {
1000  // region at index 0 is added by split()
1001  if (i != 0) {
1002  split_indices.push_back(seg_size * i);
1003  }
1004  }
1005 
1006  return split_indices_array(x, split_indices, axis, name, tag);
1007 }
1008 
1021 inline Tensor take(const Tensor& a, const Tensor& indices, int batch_dims,
1022  std::string mode = "fast", std::string name = "T_take",
1023  std::string tag = kInjective) {
1024  ffi::Array<PrimExpr> a_shape = a->shape;
1025  ffi::Array<PrimExpr> out_shape = indices->shape;
1026  PrimExpr a_size = 1;
1027  for (size_t i = 0; i < a_shape.size(); ++i) {
1028  a_size = a_size * a_shape[i];
1029  }
1030 
1031  if (mode == "clip") {
1032  return compute(
1033  out_shape,
1034  [&](const ffi::Array<Var>& out_index) {
1035  auto idx = tvm::min(tvm::max(0, indices(out_index)), a_size - 1);
1036  return a(UnravelIndex(idx, a_shape));
1037  },
1038  name, tag);
1039  } else if (mode == "fast") {
1040  LOG(WARNING) << "Fast mode segfaults when there are out-of-bounds indices. "
1041  "Make sure input indices are in bound";
1042  return compute(
1043  out_shape,
1044  [&](const ffi::Array<Var>& out_index) {
1045  return a(UnravelIndex(indices(out_index), a_shape));
1046  },
1047  name, tag);
1048  } else if (mode == "nan") {
1049  return compute(
1050  out_shape,
1051  [&](const ffi::Array<Var>& out_index) {
1052  auto idx = tvm::if_then_else(
1053  indices(out_index) < 0 || indices(out_index) >= a_size,
1054  tvm::FloatImm(a->dtype, std::numeric_limits<float>::quiet_NaN()), indices(out_index));
1055  return a(UnravelIndex(idx, a_shape));
1056  },
1057  name, tag);
1058  } else { // mode == "wrap"
1059  return compute(
1060  out_shape,
1061  [&](const ffi::Array<Var>& out_index) {
1062  auto idx = truncmod(truncmod(indices(out_index), a_size) + a_size, a_size);
1063  return a(UnravelIndex(idx, a_shape));
1064  },
1065  name, tag);
1066  }
1067 }
1068 
1081 inline Tensor sequence_mask(const Tensor& data, const Tensor& valid_length, double mask_value,
1082  int axis, std::string name = "T_sequence_mask",
1083  std::string tag = kInjective) {
1084  ICHECK(axis == 0 || axis == 1) << "axis must be either 0 or 1";
1085  ICHECK_EQ(valid_length->shape.size(), 1) << "valid_length must have ndim=1, i.e., (batch_size,).";
1086  auto length_dim = data->shape[axis];
1087  auto batch_dim = data->shape[1 - axis];
1088  ffi::Array<PrimExpr> out_shape = data->shape;
1089  Tensor out = compute(
1090  out_shape,
1091  [&](const ffi::Array<Var>& out_index) {
1092  ffi::Array<PrimExpr> len_index;
1093  auto tid = out_index[axis];
1094  auto bid = out_index[1 - axis];
1095  len_index.push_back(bid);
1096  PrimExpr ret =
1097  tvm::if_then_else(tvm::cast(valid_length->dtype, tid) >= valid_length(len_index),
1098  tvm::tir::make_const(data->dtype, mask_value), data(out_index));
1099  return ret;
1100  },
1101  name, tag);
1102  return out;
1103 }
1104 
1119 inline Tensor take(const Tensor& a, ffi::Variant<Tensor, PrimExpr> indices, int batch_dims,
1120  int axis, std::string mode = "fast", std::string name = "T_take",
1121  std::string tag = kInjective) {
1122  if (axis < 0) {
1123  axis += static_cast<int>(a->shape.size());
1124  }
1125  ICHECK_GE(axis, 0) << "axis out of bounds";
1126  ICHECK_LT(axis, a->shape.size()) << "axis out of bounds";
1127  auto axis_dim = a->shape[axis];
1128  auto indices_shape = [&]() -> ffi::Array<PrimExpr> {
1129  if (auto tensor = indices.as<TensorNode>()) {
1130  return tensor->shape;
1131  } else {
1132  return {};
1133  }
1134  }();
1135 
1136  int indices_len = static_cast<int>(indices_shape.size());
1137 
1138  int batch_dims_ = batch_dims;
1139  if (batch_dims_ != 0) {
1140  ICHECK_GE(batch_dims_, -indices_len) << "batch_dims out of bounds";
1141  ICHECK_LE(batch_dims_, indices_len) << "batch_dims out of bounds";
1142 
1143  if (batch_dims_ < 0) {
1144  batch_dims_ = indices_len + batch_dims_;
1145  }
1146 
1147  ICHECK_LT(batch_dims_, a->shape.size()) << "batch_dims out of bounds";
1148  ICHECK_LE(batch_dims_, axis) << "batch_dims must be less than or equal to axis";
1149  for (int i = 0; i < batch_dims_; ++i) {
1150  auto addr1 = a->shape[i];
1151  auto addr2 = indices_shape[i];
1152  auto v1 = static_cast<IntImm*>(&addr1)->get()->value;
1153  auto v2 = static_cast<IntImm*>(&addr2)->get()->value;
1154  ICHECK_EQ(v1, v2) << "a.shape[" << i << "] should be equal to indices.shape[" << i << "]";
1155  }
1156  }
1157 
1158  // The result shape is a.shape[:axis] + indices.shape[batch_dims:] +
1159  // a.shape[axis + 1:].
1160 
1161  ffi::Array<PrimExpr> out_shape;
1162  for (int i = 0; i < batch_dims_; ++i) {
1163  out_shape.push_back(a->shape[i]);
1164  }
1165  for (int i = batch_dims_; i < axis; ++i) {
1166  out_shape.push_back(a->shape[i]);
1167  }
1168  for (int i = batch_dims_; i < indices_len; ++i) {
1169  out_shape.push_back(indices_shape[i]);
1170  }
1171  for (size_t i = axis + 1; i < a->shape.size(); ++i) {
1172  out_shape.push_back(a->shape[i]);
1173  }
1174 
1175  auto get_index = [&](const ffi::Array<PrimExpr>& indices_position) -> PrimExpr {
1176  if (auto tensor = indices.as<Tensor>()) {
1177  return tensor.value()(indices_position);
1178  } else if (auto prim = indices.as<PrimExpr>()) {
1179  ICHECK_EQ(indices_position.size(), 0);
1180  return prim.value();
1181  } else {
1182  LOG(FATAL) << "Variant did not contain either allowed type";
1183  }
1184  };
1185 
1186  if (mode == "clip") {
1187  if (batch_dims_ == 0) {
1188  return compute(
1189  out_shape,
1190  [&](const ffi::Array<Var>& out_index) {
1191  ffi::Array<PrimExpr> indices_position;
1192  for (size_t j = axis; j < static_cast<size_t>(axis + indices_len); ++j) {
1193  indices_position.push_back(out_index[j]);
1194  }
1195  ffi::Array<PrimExpr> real_indices;
1196  for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {
1197  real_indices.push_back(out_index[j]);
1198  }
1199  auto idx = tvm::min(tvm::max(0, get_index(indices_position)), axis_dim - 1);
1200  real_indices.push_back(idx);
1201  for (size_t j = axis + indices_len; j < out_index.size(); ++j) {
1202  real_indices.push_back(out_index[j]);
1203  }
1204  return a(real_indices);
1205  },
1206  name, tag);
1207  } else {
1208  return compute(
1209  out_shape,
1210  [&](const ffi::Array<Var>& out_index) {
1211  ffi::Array<PrimExpr> indices_position;
1212  for (size_t j = 0; j < static_cast<size_t>(batch_dims_); ++j) {
1213  indices_position.push_back(out_index[j]);
1214  }
1215  for (size_t j = axis; j < static_cast<size_t>(axis + indices_len - batch_dims_); ++j) {
1216  indices_position.push_back(out_index[j]);
1217  }
1218  ffi::Array<PrimExpr> real_indices;
1219  for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {
1220  real_indices.push_back(out_index[j]);
1221  }
1222  auto idx = tvm::min(tvm::max(0, get_index(indices_position)), axis_dim - 1);
1223  real_indices.push_back(idx);
1224  for (size_t j = axis + indices_len - batch_dims_; j < out_index.size(); ++j) {
1225  real_indices.push_back(out_index[j]);
1226  }
1227  return a(real_indices);
1228  },
1229  name, tag);
1230  }
1231  } else if (mode == "fast") {
1232  LOG(WARNING) << "Fast mode segfaults when there are out-of-bounds indices. "
1233  "Make sure input indices are in bound";
1234  return compute(
1235  out_shape,
1236  [&](const ffi::Array<Var>& out_index) {
1237  ffi::Array<PrimExpr> indices_position;
1238  for (size_t j = axis; j < static_cast<size_t>(axis + indices_len); ++j) {
1239  indices_position.push_back(out_index[j]);
1240  }
1241  ffi::Array<PrimExpr> real_indices;
1242  for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {
1243  real_indices.push_back(out_index[j]);
1244  }
1245  real_indices.push_back(get_index(indices_position));
1246  for (size_t j = axis + indices_len; j < out_index.size(); ++j) {
1247  real_indices.push_back(out_index[j]);
1248  }
1249  return a(real_indices);
1250  },
1251  name, tag);
1252  } else if (mode == "nan") {
1253  return compute(
1254  out_shape,
1255  [&](const ffi::Array<Var>& out_index) {
1256  ffi::Array<PrimExpr> indices_position;
1257  for (size_t j = axis; j < static_cast<size_t>(axis + indices_len); ++j) {
1258  indices_position.push_back(out_index[j]);
1259  }
1260  ffi::Array<PrimExpr> real_indices;
1261  for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {
1262  real_indices.push_back(out_index[j]);
1263  }
1264  PrimExpr idx = get_index(indices_position);
1265  real_indices.push_back(idx);
1266  for (size_t j = axis + indices_len; j < out_index.size(); ++j) {
1267  real_indices.push_back(out_index[j]);
1268  }
1269  PrimExpr in_bounds = idx >= 0 && idx < axis_dim;
1270  return tvm::if_then_else(
1271  in_bounds, a(real_indices),
1272  tvm::tir::make_const(a->dtype, std::numeric_limits<float>::quiet_NaN()));
1273  },
1274  name, tag);
1275  } else { // mode == "wrap"
1276  return compute(
1277  out_shape,
1278  [&](const ffi::Array<Var>& out_index) {
1279  ffi::Array<PrimExpr> indices_position;
1280  for (size_t j = axis; j < static_cast<size_t>(axis + indices_len); ++j) {
1281  indices_position.push_back(out_index[j]);
1282  }
1283  ffi::Array<PrimExpr> real_indices;
1284  for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {
1285  real_indices.push_back(out_index[j]);
1286  }
1287  auto idx = truncmod(truncmod(get_index(indices_position), axis_dim) + axis_dim, axis_dim);
1288  real_indices.push_back(idx);
1289  for (size_t j = axis + indices_len; j < out_index.size(); ++j) {
1290  real_indices.push_back(out_index[j]);
1291  }
1292  return a(real_indices);
1293  },
1294  name, tag);
1295  }
1296 }
1297 
1309 inline Tensor where(const Tensor& condition, const Tensor& x, const Tensor& y,
1310  std::string name = "T_where", std::string tag = kBroadcast) {
1311  ICHECK_EQ(x->dtype, y->dtype) << "x and y must have the same dtype: " << x->dtype << " vs "
1312  << y->dtype;
1313  auto get_out_shape = [&]() {
1314  auto bh1 = detail::BroadcastShape(x->shape, y->shape);
1315  ffi::Array<PrimExpr> common_shape1(bh1.common_shape.begin(), bh1.common_shape.end());
1316  auto bh2 = detail::BroadcastShape(condition->shape, common_shape1);
1317  ffi::Array<PrimExpr> common_shape2(bh2.common_shape.begin(), bh2.common_shape.end());
1318  return common_shape2;
1319  };
1320 
1321  auto oshape = get_out_shape();
1322 
1323  auto c_bh = detail::BroadcastShape(condition->shape, oshape);
1324  auto x_bh = detail::BroadcastShape(x->shape, oshape);
1325  auto y_bh = detail::BroadcastShape(y->shape, oshape);
1326 
1327  auto select = [&](tvm::ffi::Array<tvm::tir::Var> ovars) {
1328  auto c = condition(InputIndexFromBroadcast(ovars, condition, c_bh.vars1, c_bh.all_vars));
1329  auto true_val = x(InputIndexFromBroadcast(ovars, x, x_bh.vars1, x_bh.all_vars));
1330  auto false_val = y(InputIndexFromBroadcast(ovars, y, y_bh.vars1, y_bh.all_vars));
1331  return tvm::tir::Select(c != 0, true_val, false_val);
1332  };
1333 
1334  return compute(oshape, select, name, tag);
1335 }
1336 
1349 inline Tensor repeat(const Tensor& x, int repeats, int axis, std::string name = "T_repeat",
1350  std::string tag = kBroadcast) {
1351  int ndim = static_cast<int>(x->shape.size());
1352  ICHECK(-ndim - 1 <= axis && axis <= ndim)
1353  << "repeat only accepts `axis` in [-data.ndim - 1, data.ndim]"
1354  << ", but got axis = " << axis << ", and data.ndim = " << ndim;
1355  ICHECK(repeats >= 1) << "repeat only accepts `repeats >= 1`"
1356  << ", but got repeats = " << repeats;
1357  if (axis < 0) {
1358  // Calculate offset from last dimension
1359  axis += ndim;
1360  }
1361  ffi::Array<PrimExpr> new_shape;
1362  for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {
1363  new_shape.push_back(x->shape[i]);
1364  }
1365  new_shape.push_back(repeats * x->shape[axis]);
1366  for (size_t i = axis + 1; i < x->shape.size(); ++i) {
1367  new_shape.push_back(x->shape[i]);
1368  }
1369 
1370  return compute(
1371  new_shape,
1372  [&](const ffi::Array<Var>& indices) {
1373  ffi::Array<PrimExpr> idx;
1374  for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {
1375  idx.push_back(indices[i]);
1376  }
1377  idx.push_back(indexdiv(indices[axis], repeats));
1378  for (size_t i = axis + 1; i < indices.size(); ++i) {
1379  idx.push_back(indices[i]);
1380  }
1381  return x(idx);
1382  },
1383  name, tag);
1384 }
1385 
1396 inline Tensor tile(const Tensor& x, ffi::Array<Integer> reps, std::string name = "T_tile",
1397  std::string tag = kBroadcast) {
1398  size_t ndim = x->shape.size();
1399  size_t rdim = reps.size();
1400  size_t tdim = (ndim > rdim) ? ndim : rdim;
1401  ffi::Array<PrimExpr> data_shape;
1402  ffi::Array<PrimExpr> reps_shape;
1403  ffi::Array<PrimExpr> new_shape;
1404  if (ndim == rdim) {
1405  for (size_t i = 0; i < ndim; ++i) {
1406  data_shape.push_back(x->shape[i]);
1407  reps_shape.push_back(reps[i]);
1408  }
1409  } else if (ndim > rdim) {
1410  for (size_t i = 0; i < ndim; ++i) data_shape.push_back(x->shape[i]);
1411  for (size_t i = 0; i < (ndim - rdim); ++i) reps_shape.push_back(1);
1412  for (size_t i = 0; i < rdim; ++i) reps_shape.push_back(reps[i]);
1413  } else {
1414  for (size_t i = 0; i < (rdim - ndim); ++i) data_shape.push_back(1);
1415  for (size_t i = 0; i < ndim; ++i) data_shape.push_back(x->shape[i]);
1416  for (size_t i = 0; i < rdim; ++i) reps_shape.push_back(reps[i]);
1417  }
1418  for (size_t i = 0; i < tdim; ++i) new_shape.push_back(data_shape[i] * reps_shape[i]);
1419 
1420  if (is_empty_shape(new_shape)) {
1421  return compute(
1422  new_shape, [&](const ffi::Array<Var>& indices) { return tvm::cast(x->dtype, 0); }, name,
1423  tag);
1424  } else {
1425  return compute(
1426  new_shape,
1427  [&](const ffi::Array<Var>& indices) {
1428  ffi::Array<PrimExpr> idx;
1429  if (ndim >= rdim) {
1430  for (size_t i = 0; i < ndim; ++i) idx.push_back(indexmod(indices[i], x->shape[i]));
1431  } else {
1432  for (size_t i = 0; i < ndim; ++i)
1433  idx.push_back(indexmod(indices[rdim - ndim + i], x->shape[i]));
1434  }
1435  return x(idx);
1436  },
1437  name, tag);
1438  }
1439 }
1440 
1452 inline Tensor dyn_tile(const Tensor& x, ffi::Array<PrimExpr> new_shape, size_t rdim,
1453  std::string name = "T_tile", std::string tag = kBroadcast) {
1454  size_t ndim = x->shape.size();
1455  if (is_empty_shape(new_shape)) {
1456  return compute(
1457  new_shape, [&](const ffi::Array<Var>& indices) { return tvm::cast(x->dtype, 0); }, name,
1458  tag);
1459  } else {
1460  return compute(
1461  new_shape,
1462  [&](const ffi::Array<Var>& indices) {
1463  ffi::Array<PrimExpr> idx;
1464  if (ndim >= rdim) {
1465  for (size_t i = 0; i < ndim; ++i) {
1466  idx.push_back(indexmod(indices[i], x->shape[i]));
1467  }
1468  } else {
1469  for (size_t i = 0; i < ndim; ++i) {
1470  idx.push_back(indexmod(indices[rdim - ndim + i], x->shape[i]));
1471  }
1472  }
1473  return x(idx);
1474  },
1475  name, tag);
1476  }
1477 }
1478 
1490 inline Tensor gather(const Tensor& data, int axis, const Tensor& indices,
1491  std::string name = "T_gather", std::string tag = kInjective) {
1492  size_t ndim_d = data->shape.size();
1493  size_t ndim_i = indices->shape.size();
1494  ICHECK_GE(ndim_d, 1) << "Cannot gather from a scalar.";
1495  ICHECK_EQ(ndim_d, ndim_i);
1496  if (axis < 0) {
1497  axis += ndim_d;
1498  }
1499  ICHECK_GE(axis, 0);
1500  ICHECK_LT(axis, ndim_d);
1501  if (indices->shape[axis].as<IntImmNode>()) {
1502  size_t indices_dim_i = static_cast<size_t>(GetConstInt(indices->shape[axis]));
1503  ICHECK_GE(indices_dim_i, 1);
1504  }
1505  ICHECK(indices->dtype.is_int() || indices->dtype.is_uint());
1506 
1507  ffi::Array<PrimExpr> out_shape;
1508  for (size_t i = 0; i < ndim_i; ++i) {
1509  out_shape.push_back(indices->shape[i]);
1510  }
1511 
1512  return compute(
1513  out_shape,
1514  [&](const ffi::Array<Var>& out_index) {
1515  ffi::Array<PrimExpr> indices_position;
1516  for (size_t i = 0; i < ndim_i; ++i) {
1517  indices_position.push_back(out_index[i]);
1518  }
1519  ffi::Array<PrimExpr> real_indices;
1520  for (size_t i = 0; i < ndim_i; ++i) {
1521  if (i == static_cast<size_t>(axis)) {
1522  real_indices.push_back(indices(indices_position));
1523  } else {
1524  real_indices.push_back(indices_position[i]);
1525  }
1526  }
1527  return data(real_indices);
1528  },
1529  name, tag);
1530 }
1531 
1543 inline Tensor gather_nd(const Tensor& data, const Tensor& indices, int batch_dims = 0,
1544  std::string name = "T_gather_nd", std::string tag = kInjective) {
1545  size_t ndim_d = data->shape.size();
1546  size_t ndim_i = indices->shape.size();
1547  ICHECK_GE(ndim_i, 1) << "indices tensor must have at least 1 dimensions";
1548  size_t indices_dim0 = static_cast<size_t>(GetConstInt(indices->shape[0]));
1549  ICHECK_LE(indices_dim0, ndim_d) << "dim 0 of indices tensor must be no more "
1550  << "than dimensions of data tensor";
1551  ffi::Array<PrimExpr> out_shape;
1552  for (size_t i = 1; i < ndim_i; ++i) {
1553  out_shape.push_back(indices->shape[i]);
1554  }
1555  for (size_t i = indices_dim0 + batch_dims; i < ndim_d; ++i) {
1556  out_shape.push_back(data->shape[i]);
1557  }
1558  return compute(
1559  out_shape,
1560  [&](const ffi::Array<Var>& out_index) {
1561  ffi::Array<PrimExpr> indices_position;
1562  indices_position.push_back(0);
1563  for (size_t i = 0; i < ndim_i - 1; ++i) {
1564  indices_position.push_back(out_index[i]);
1565  }
1566  ffi::Array<PrimExpr> real_indices;
1567  for (size_t i = 0; i < static_cast<size_t>(batch_dims); ++i) {
1568  real_indices.push_back(out_index[i]);
1569  }
1570  for (size_t i = 0; i < indices_dim0; ++i) {
1571  indices_position.Set(0, make_const(DataType::Int(32), i));
1572  if (indices->dtype.is_int() || indices->dtype.is_uint()) {
1573  real_indices.push_back(indices(indices_position));
1574  } else {
1575  real_indices.push_back(tvm::cast(tvm::DataType::Int(32), indices(indices_position)));
1576  }
1577  }
1578  if (real_indices.size() == ndim_d) {
1579  return data(real_indices);
1580  }
1581  for (size_t i = ndim_i - 1; i < out_index.size(); ++i) {
1582  real_indices.push_back(out_index[i]);
1583  }
1584  return data(real_indices);
1585  },
1586  name, tag);
1587 }
1588 
1605  bool trans_a = false, bool trans_b = false,
1606  std::string name = "T_matmul", std::string tag = kMatMul) {
1607  tvm::ffi::Array<tvm::PrimExpr> output_shape{A->shape[trans_a ? 1 : 0], B->shape[trans_b ? 0 : 1]};
1608  auto k = tvm::te::reduce_axis(tvm::Range{0, A->shape[trans_a ? 0 : 1]}, "k");
1609  auto l = [&](tvm::tir::Var i, tvm::tir::Var j) {
1610  return tvm::sum((trans_a ? A[k][i] : A[i][k]) * (trans_b ? B[j][k] : B[k][j]), {k});
1611  };
1612  return tvm::te::compute(output_shape, l, name, tag);
1613 }
1614 
1626 inline Tensor tensordot(const Tensor& A, const tvm::te::Tensor& B, int axes = 2,
1627  std::string name = "T_tensordot", std::string tag = kMatMul) {
1628  ICHECK_GE(A->shape.size(), axes);
1629  ICHECK_GE(B->shape.size(), axes);
1630 
1631  ffi::Array<PrimExpr> output_shape(A->shape.begin(), A->shape.end() + (-axes));
1632  for (auto it = B->shape.begin() + axes; it != B->shape.end(); ++it) output_shape.push_back(*it);
1633 
1634  ffi::Array<IterVar> iter_vars;
1635  for (int i = 0; i < axes; ++i)
1636  iter_vars.push_back(reduce_axis(Range(0, B->shape[i]), "k" + std::to_string(i)));
1637 
1638  auto func = [&A, &B, &iter_vars, axes](const ffi::Array<Var>& input_indices) {
1639  ffi::Array<PrimExpr> A_indices(input_indices.begin(),
1640  input_indices.begin() + (A->shape.size() - axes));
1641  for (auto& v : iter_vars) A_indices.push_back(v);
1642 
1643  ffi::Array<PrimExpr> B_indices;
1644  for (auto& v : iter_vars) B_indices.push_back(v);
1645 
1646  auto it = input_indices.begin() + (A->shape.size() - axes);
1647  for (; it != input_indices.end(); ++it) B_indices.push_back(*it);
1648 
1649  // Some passes don't like reductions with empty axis, so avoid it here
1650  if (iter_vars.empty()) {
1651  return A(A_indices) * B(B_indices);
1652  } else {
1653  return sum(A(A_indices) * B(B_indices), iter_vars);
1654  }
1655  };
1656 
1657  return compute(output_shape, func, name, tag);
1658 }
1659 
1672 inline Tensor tensordot(const Tensor& A, const tvm::te::Tensor& B, ffi::Array<PrimExpr> A_axes,
1673  ffi::Array<PrimExpr> B_axes, std::string name = "T_tensordot",
1674  std::string tag = kMatMul) {
1675  ICHECK_EQ(A_axes.size(), B_axes.size());
1676 
1677  auto A_axes_val = GetConstIntValues(A_axes, "A_axes");
1678  auto B_axes_val = GetConstIntValues(B_axes, "B_axes");
1679 
1680  ffi::Array<PrimExpr> output_shape;
1681  for (unsigned i = 0; i < A->shape.size(); ++i)
1682  if (std::find(A_axes_val.begin(), A_axes_val.end(), i) == A_axes_val.end())
1683  output_shape.push_back(A->shape[i]);
1684  for (unsigned i = 0; i < B->shape.size(); ++i)
1685  if (std::find(B_axes_val.begin(), B_axes_val.end(), i) == B_axes_val.end())
1686  output_shape.push_back(B->shape[i]);
1687 
1688  ffi::Array<IterVar> iter_vars;
1689  for (unsigned i = 0; i < B_axes_val.size(); ++i)
1690  iter_vars.push_back(reduce_axis(Range(0, B->shape[B_axes_val[i]]), "k" + std::to_string(i)));
1691 
1692  auto func = [&A, &B, &iter_vars, A_axes_val, B_axes_val](const ffi::Array<Var>& input_indices) {
1693  int idx_input = 0;
1694  ffi::Array<PrimExpr> A_indices;
1695  for (unsigned i = 0; i < A->shape.size(); ++i) {
1696  auto axes_pos = std::find(A_axes_val.begin(), A_axes_val.end(), i);
1697  if (axes_pos == A_axes_val.end()) {
1698  A_indices.push_back(input_indices[idx_input++]);
1699  } else {
1700  A_indices.push_back(iter_vars[axes_pos - A_axes_val.begin()]);
1701  }
1702  }
1703 
1704  ffi::Array<PrimExpr> B_indices;
1705  for (unsigned i = 0; i < B->shape.size(); ++i) {
1706  auto axes_pos = std::find(B_axes_val.begin(), B_axes_val.end(), i);
1707  if (axes_pos == B_axes_val.end()) {
1708  B_indices.push_back(input_indices[idx_input++]);
1709  } else {
1710  B_indices.push_back(iter_vars[axes_pos - B_axes_val.begin()]);
1711  }
1712  }
1713  return sum(A(A_indices) * B(B_indices), iter_vars);
1714  };
1715  return compute(output_shape, func, name, tag);
1716 }
1717 
1718 inline Tensor arange(const PrimExpr& start, const PrimExpr& stop, const PrimExpr& step,
1719  DataType dtype, std::string name = "T_arange", std::string tag = kInjective) {
1720  arith::Analyzer analyzer;
1721  PrimExpr num_elem;
1722  bool is_all_int = start.dtype().is_int() && stop.dtype().is_int() && step.dtype().is_int();
1723  if (is_all_int && analyzer.CanProveGreaterEqual(step, 1)) {
1724  // fast path for integer arange when step is positive
1725  num_elem = tvm::floordiv((stop - start + step - 1), step);
1726  } else if (is_all_int && analyzer.CanProveLess(step, 0)) {
1727  // fast path for integer arange when step is negative
1728  num_elem = tvm::floordiv((start - stop - step - 1), -step);
1729  } else {
1730  // fallback path for non-integer or step of unknown sign
1731  num_elem = tvm::cast(DefaultIndexType(),
1732  tvm::ceil(tvm::cast(tvm::DataType::Float(32), stop - start) / step));
1733  }
1734  num_elem = analyzer.Simplify(num_elem);
1735 
1736  return compute(
1737  {num_elem},
1738  [&](const ffi::Array<Var>& indices) { return tvm::cast(dtype, start + step * indices[0]); },
1739  name, tag);
1740 }
1741 
1752 inline ffi::Array<Tensor> meshgrid(const ffi::Array<Tensor>& inputs, const std::string& indexing,
1753  std::string name = "T_meshgrid", std::string tag = kInjective) {
1754  const bool cartesian_indexing = indexing == "xy" && inputs.size() >= 2;
1755  ffi::Array<PrimExpr> out_shape;
1756  for (size_t i = 0; i < inputs.size(); ++i) {
1757  const int src_index = (cartesian_indexing && i < 2) ? 1 - i : i;
1758  out_shape.push_back(inputs[src_index]->shape.size() == 0 ? 1 : inputs[src_index]->shape[0]);
1759  }
1760  ffi::Array<Tensor> result;
1761  for (size_t i = 0; i < inputs.size(); ++i) {
1762  result.push_back(compute(
1763  out_shape,
1764  [&](const ffi::Array<Var>& indices) {
1765  const int src_index = (cartesian_indexing && i < 2) ? 1 - i : i;
1766  auto ndim = inputs[i]->GetShape().size();
1767  ffi::Array<PrimExpr> real_indices = {};
1768  if (ndim > 0) {
1769  real_indices = {indices[src_index]};
1770  }
1771  return inputs[i](real_indices);
1772  },
1773  name, tag));
1774  }
1775  return result;
1776 }
1777 
1788 inline Tensor layout_transform(const Tensor& src, const std::string& src_layout,
1789  const std::string& dst_layout,
1790  const std::string schedule_rule = "None",
1791  const std::string name = "T_layout_trans",
1792  const std::string tag = kInjective) {
1793  Layout src_layout_struct(src_layout);
1794  Layout dst_layout_struct(dst_layout);
1795 
1796  if (src_layout_struct.Equals(dst_layout_struct)) {
1797  return src;
1798  }
1799 
1800  ICHECK(src_layout_struct.defined() && dst_layout_struct.defined())
1801  << "cannot convert from/to undefined layout";
1802 
1803  auto layout_converter = tir::BijectiveLayout(src_layout_struct, dst_layout_struct);
1804  ICHECK(layout_converter.defined())
1805  << "cannot convert from " << src_layout << " to " << dst_layout;
1806 
1807  ffi::Array<PrimExpr> dst_shape = layout_converter.ForwardShape(src->shape);
1808 
1809  ffi::Map<ffi::String, ffi::Any> attrs = {{"schedule_rule", ffi::String(schedule_rule)},
1810  // Information about layouts needed for the schedule rule
1811  {"src_layout", ffi::String(src_layout)},
1812  {"dst_layout", ffi::String(dst_layout)},
1813  {"input_shape", src->shape}};
1814 
1815  return compute(
1816  dst_shape,
1817  [&](const ffi::Array<Var>& dst_indices) {
1818  ffi::Array<PrimExpr> dst_indices_expr(dst_indices.begin(), dst_indices.end());
1819  ffi::Array<PrimExpr> src_indices = layout_converter.BackwardIndex(dst_indices_expr);
1820  PrimExpr in_range = PrimExpr(1) > PrimExpr(0); // init with dtype=bool and value=true
1821  for (size_t i = 0; i < src.ndim(); ++i) {
1822  in_range = in_range && (src_indices[i] < src->shape[i]);
1823  }
1824  return if_then_else(in_range, src(src_indices), tvm::cast(src->dtype, PrimExpr(0)));
1825  },
1826  name, tag, attrs);
1827 }
1828 
1830 inline void parse_auto_scheduler_layout(const ffi::String& layout, ffi::Array<PrimExpr>* shape,
1831  std::vector<std::string>* axes) {
1832  int32_t factor = 0;
1833  std::string axis = "";
1834  for (char c : std::string(layout)) {
1835  if (c >= 'A' && c <= 'z') {
1836  axis += c;
1837  if (factor != 0) {
1838  shape->push_back(factor);
1839  factor = 0;
1840  }
1841  } else if (c >= '0' && c <= '9') {
1842  factor = factor * 10 + c - '0';
1843  if (!axis.empty()) {
1844  axes->push_back(axis);
1845  axis = "";
1846  }
1847  } else {
1848  LOG(FATAL) << "Invalid layout " << layout;
1849  }
1850  }
1851  if (!axis.empty()) {
1852  axes->push_back(axis);
1853  }
1854 }
1855 
1867  const Tensor& src, const ffi::String& src_layout, const ffi::String& dst_layout,
1868  const ffi::String name = "T_auto_scheduler_layout_trans", const ffi::String tag = kInjective) {
1869  ffi::Array<PrimExpr> src_shape;
1870  std::vector<std::string> src_axes;
1871  ffi::Array<PrimExpr> dst_shape;
1872  std::vector<std::string> dst_axes;
1873 
1874  parse_auto_scheduler_layout(src_layout, &src_shape, &src_axes);
1875  parse_auto_scheduler_layout(dst_layout, &dst_shape, &dst_axes);
1876  return compute(
1877  dst_shape,
1878  [&](const ffi::Array<Var>& dst_indices) {
1879  ffi::Array<PrimExpr> dst_indices_expr(dst_indices.begin(), dst_indices.end());
1880  ffi::Array<PrimExpr> src_indices;
1881  for (const std::string& src_axis : src_axes) {
1882  PrimExpr src_index = 0;
1883  CHECK_EQ(dst_indices_expr.size(), dst_axes.size());
1884  for (size_t i = 0; i < dst_axes.size(); ++i) {
1885  if (dst_axes[i] == src_axis) {
1886  src_index = src_index * dst_shape[i] + dst_indices_expr[i];
1887  }
1888  }
1889  src_indices.push_back(src_index);
1890  }
1891  return src(src_indices);
1892  },
1893  name, tag);
1894 }
1895 
1933  const Tensor& src, const tir::IndexMap& index_map,
1934  const ffi::String name = "T_meta_schedule_layout_trans", const ffi::String tag = kInjective) {
1935  arith::Analyzer analyzer;
1936  ffi::Array<Range> iter_domain;
1937  iter_domain.reserve(src->shape.size());
1938  for (const PrimExpr& e : src->shape) {
1939  iter_domain.push_back(Range::FromMinExtent(make_zero(e->dtype), e));
1940  }
1941  ffi::Array<PrimExpr> post_transform_shape = index_map->MapShape(src->shape, &analyzer);
1942  return compute(
1943  post_transform_shape,
1944  [src, inv = index_map.Inverse(iter_domain, &analyzer),
1945  &analyzer](const ffi::Array<Var>& indices) -> PrimExpr {
1946  return src(
1947  inv->MapIndices(ffi::Array<PrimExpr>{indices.begin(), indices.end()}, &analyzer));
1948  },
1949  name, tag);
1950 }
1951 
1960 inline Tensor shape(const Tensor& src, DataType dtype, const std::string name = "T_shape",
1961  const std::string tag = kInjective) {
1962  int ndim = static_cast<int>(src->shape.size());
1963  ffi::Array<PrimExpr> out_shape{ndim};
1964  return compute(
1965  out_shape,
1966  [&](const ffi::Array<Var>& indices) {
1967  auto idx = indices[0];
1968  PrimExpr ret = 0;
1969  for (int i = 0; i < ndim; ++i) {
1970  ret = tvm::if_then_else(idx == i, src->shape[i], ret);
1971  }
1972  return tvm::cast(dtype, ret);
1973  },
1974  name, tag);
1975 }
1976 
1985 inline te::Tensor tensor_size(const te::Tensor& src, const DataType& dtype,
1986  const std::string& name = "tensor_size",
1987  const std::string& tag = kInjective) {
1988  int ndim = static_cast<int>(src->shape.size());
1989  ffi::Array<PrimExpr> out_tensor_size = {};
1990  return compute(
1991  out_tensor_size,
1992  [&](const ffi::Array<Var>& indices) {
1993  PrimExpr ret = 1;
1994  for (int i = 0; i < ndim; ++i) {
1995  ret *= src->shape[i];
1996  }
1997  return tvm::cast(dtype, ret);
1998  },
1999  name, tag);
2000 }
2001 
2016 inline Tensor one_hot(const Tensor& indices, const PrimExpr on_value, const PrimExpr off_value,
2017  int depth, int axis, const DataType& dtype,
2018  ffi::Array<PrimExpr> oshape = ffi::Array<PrimExpr>(),
2019  const std::string name = "T_one_hot", const std::string tag = kInjective) {
2020  int true_axis = (axis == -1) ? indices->shape.size() : axis;
2021  if (oshape.size() == 0) {
2022  int ndim = indices->shape.size() + 1;
2023  int indices_index = 0;
2024  for (int i = 0; i < ndim; i++) {
2025  if (i == true_axis) {
2026  oshape.push_back(Integer(depth));
2027  } else {
2028  oshape.push_back(indices->shape[indices_index++]);
2029  }
2030  }
2031  }
2032 
2033  PrimExpr on_value_cast = cast(dtype, on_value);
2034  PrimExpr off_value_cast = cast(dtype, off_value);
2035  return compute(
2036  oshape,
2037  [&](const ffi::Array<Var>& iter_vars) {
2038  ffi::Array<Var> indices_indices;
2039  for (size_t i = 0; i < iter_vars.size(); i++) {
2040  if (static_cast<int>(i) == true_axis) {
2041  continue;
2042  }
2043 
2044  indices_indices.push_back(iter_vars[i]);
2045  }
2046 
2047  auto idx = iter_vars[true_axis];
2048  return tir::Select(indices(indices_indices) == idx, on_value_cast, off_value_cast);
2049  },
2050  name, tag);
2051 }
2052 
2063 inline Tensor sparse_to_dense(const Tensor& sparse_indices,
2064  const ffi::Array<PrimExpr>& output_shape, const Tensor& sparse_values,
2065  const PrimExpr& default_value,
2066  const std::string name = "T_sparse_to_dense",
2067  const std::string tag = kInjective) {
2068  ICHECK(sparse_indices->dtype.is_int()) << "sparse_indices only accepts integer values";
2069  ICHECK_LE(sparse_indices->shape.size(), 3)
2070  << "sparse_indices tensor should be 0D, 1D, or 2D only";
2071  ICHECK_LE(sparse_values->shape.size(), 2) << "sparse_values tensor should be 0D or 1D only";
2072 
2073  const auto rank_sparse_indices = static_cast<int>(sparse_indices->shape.size());
2074  ffi::Array<PrimExpr> oshape;
2075  for (auto l : output_shape) {
2076  oshape.push_back(l);
2077  }
2078  return compute(
2079  oshape,
2080  [&](const ffi::Array<Var>& indices) {
2081  PrimExpr ret = default_value;
2082  if (0 == rank_sparse_indices) {
2083  ret = if_then_else(indices[0] == sparse_indices(), sparse_values(), ret);
2084  } else if (1 == rank_sparse_indices) {
2085  for (int j = 0; j < GetConstInt(sparse_indices->shape[0]); j++) {
2086  ret = if_then_else(indices[0] == sparse_indices[j], sparse_values[j], ret);
2087  }
2088  } else {
2089  for (int j = 0; j < GetConstInt(sparse_indices->shape[0]); j++) {
2090  PrimExpr aggregate_condition;
2091  for (int k = 0; k < GetConstInt(sparse_indices->shape[1]); k++) {
2092  PrimExpr comparision = indices[k] == sparse_indices[j][k];
2093  aggregate_condition = 0 == k ? comparision : aggregate_condition && comparision;
2094  }
2095  ret = if_then_else(aggregate_condition, sparse_values[j], ret);
2096  }
2097  }
2098  return ret;
2099  },
2100  name, tag);
2101 }
2102 
2115 inline Tensor matrix_set_diag(const Tensor& input, const Tensor& diagonal, int k1, int k2,
2116  bool super_diag_right_align, bool sub_diag_right_align,
2117  const std::string name = "T_matrix_set_diag",
2118  const std::string tag = kInjective) {
2119  size_t ndim = input->shape.size() - 1;
2120 
2121  bool only_one_diagonal = k1 == k2;
2122 
2123  return compute(
2124  input->shape,
2125  [&](const ffi::Array<Var>& iter_vars) {
2126  auto get_diag = [&]() {
2127  ffi::Array<PrimExpr> diagonal_indices;
2128  PrimExpr k, offset = 0;
2129  for (size_t i = 0; i < ndim - 1; i++) {
2130  diagonal_indices.push_back(iter_vars[i]);
2131  }
2132  if (only_one_diagonal) {
2133  k = k1;
2134  } else {
2135  // Determining which diagonal/sub-diagonal/super-diagonal it is
2136  k = iter_vars[ndim] - iter_vars[ndim - 1];
2137  diagonal_indices.push_back(k2 - k);
2138 
2139  // Calculating the offset in diagonal tensor for this diagonal
2140  auto get_offset = [&](PrimExpr M, PrimExpr N) {
2141  // offset = max_diagonal_length - diagonal_length
2142  return diagonal->shape[diagonal->shape.size() - 1] - if_then_else(M < N, M, N);
2143  };
2144  offset = if_then_else(
2145  k >= 0,
2146  super_diag_right_align ? get_offset(input->shape[ndim] - k, input->shape[ndim - 1])
2147  : 0,
2148  sub_diag_right_align ? get_offset(input->shape[ndim], input->shape[ndim - 1] + k)
2149  : 0);
2150  }
2151  diagonal_indices.push_back(if_then_else(k >= 0, iter_vars[ndim - 1], iter_vars[ndim]) +
2152  offset);
2153  return diagonal(diagonal_indices);
2154  };
2155  return if_then_else((PrimExpr)iter_vars[ndim] - iter_vars[ndim - 1] >= k1,
2156  if_then_else((PrimExpr)iter_vars[ndim] - iter_vars[ndim - 1] <= k2,
2157  get_diag(), input(iter_vars)),
2158  input(iter_vars));
2159  },
2160  name, tag);
2161 }
2162 
2171 inline Tensor adv_index(const Tensor& data, const ffi::Array<Tensor>& indices,
2172  const std::string name = "advanced_index",
2173  const std::string tag = kInjective) {
2174  ICHECK_LE(indices.size(), data->shape.size()) << "too many indices for data!";
2175  ffi::Array<PrimExpr> oshape;
2176  ffi::Array<PrimExpr> broadcast_shape;
2177  ffi::Array<Tensor> bindices;
2178 
2179  broadcast_shape = indices[0]->shape;
2180  for (size_t i = 1; i < indices.size(); ++i) {
2181  auto bh = detail::BroadcastShape(broadcast_shape, indices[i]->shape);
2182  broadcast_shape = ffi::Array<PrimExpr>(bh.common_shape.begin(), bh.common_shape.end());
2183  }
2184  if (indices.size() == 1) {
2185  // quick path
2186  bindices = indices;
2187  } else {
2188  // Do broadcast for indices
2189  for (size_t i = 0; i < indices.size(); ++i) {
2190  bindices.push_back(broadcast_to(indices[i], broadcast_shape));
2191  }
2192  }
2193 
2194  for (const auto& dim : broadcast_shape) {
2195  oshape.push_back(dim);
2196  }
2197  for (size_t i = indices.size(); i < data->shape.size(); ++i) {
2198  oshape.push_back(data->shape[i]);
2199  }
2200 
2201  return compute(
2202  oshape,
2203  [&](const ffi::Array<Var>& iter_var) {
2204  ffi::Array<PrimExpr> tensor_indices;
2205  for (size_t i = 0; i < broadcast_shape.size(); ++i) {
2206  tensor_indices.push_back(iter_var[i]);
2207  }
2208  ffi::Array<PrimExpr> real_indices;
2209  for (size_t i = 0; i < bindices.size(); ++i) {
2210  real_indices.push_back(bindices[i](tensor_indices));
2211  }
2212  for (size_t i = broadcast_shape.size(); i < iter_var.size(); ++i) {
2213  real_indices.push_back(iter_var[i]);
2214  }
2215 
2216  return data(real_indices);
2217  },
2218  name, tag);
2219 }
2220 
2221 namespace relax {
2222 // relax dynamic slice
2224  const te::Tensor& end, const te::Tensor& strides,
2225  ffi::Array<PrimExpr> output_shape,
2226  std::string name = "T_strided_slice_dynamic",
2227  std::string tag = kInjective) {
2228  const size_t num_dynamic_axes = x.ndim();
2229  ICHECK_EQ(begin.ndim(), 1);
2230  ICHECK_EQ(end.ndim(), 1);
2231  ICHECK_EQ(strides.ndim(), 1);
2232  const auto* len_begin = begin->shape[0].as<IntImmNode>();
2233  const auto* len_end = end->shape[0].as<IntImmNode>();
2234  const auto* len_strides = strides->shape[0].as<IntImmNode>();
2235  ICHECK(len_begin);
2236  ICHECK(len_end);
2237  ICHECK(len_strides);
2238  ICHECK_EQ(len_begin->value, num_dynamic_axes);
2239  ICHECK_EQ(len_end->value, num_dynamic_axes);
2240  ICHECK_EQ(len_strides->value, num_dynamic_axes);
2241 
2242  return te::compute(
2243  output_shape,
2244  [&](const ffi::Array<tvm::tir::Var>& indices) {
2245  ffi::Array<PrimExpr> real_indices;
2246  for (size_t i = 0; i < num_dynamic_axes; ++i) {
2247  auto ind = make_const(DataType::Int(64), i);
2248  real_indices.push_back(indices[i] * strides(ind) + tvm::min(begin(ind), x->shape[i] - 1));
2249  }
2250  return x(real_indices);
2251  },
2252  name, tag);
2253 }
2254 
2255 } // namespace relax
2256 
2257 } // namespace topi
2258 } // namespace tvm
2259 #endif // TVM_TOPI_TRANSFORM_H_
Algebra expression simplifications.
Broadcast op constructions.
Managed reference class to FloatImmNode.
Definition: expr.h:545
Constant integer literals in the program.
Definition: expr.h:493
int64_t value
the Internal value.
Definition: expr.h:496
Managed reference class to IntImmNode.
Definition: expr.h:510
Container of constant int that adds more constructors.
Definition: expr.h:600
Reference to PrimExprNode.
Definition: expr.h:124
DataType dtype() const
Definition: expr.h:138
Range container
Definition: expr.h:689
static Range FromMinExtent(PrimExpr min, PrimExpr extent, Span span=Span())
construct a new range with min and extent The corresponding constructor is removed,...
Analyzer that contains bunch of sub-analyzers.
Definition: analyzer.h:634
bool CanProveGreaterEqual(const PrimExpr &expr, int64_t lower_bound)
Whether can we prove expr >= val.
PrimExpr Simplify(const PrimExpr &expr, int steps=2)
Simplify expr.
bool CanProveLess(const PrimExpr &expr, int64_t upper_bound)
Whether can we prove expr < val.
Runtime primitive data type.
Definition: data_type.h:47
static DataType Float(int bits, int lanes=1)
Construct an float type.
Definition: data_type.h:291
bool is_int() const
Definition: data_type.h:190
static DataType Int(int bits, int lanes=1)
Construct an int type.
Definition: data_type.h:274
Managed Tensor. The array is backed by reference counted blocks.
Definition: tensor.h:53
Node to represent a tensor.
Definition: tensor.h:70
Tensor structure representing a possible input, or intermediate computation result.
Definition: tensor.h:100
size_t ndim() const
Definition: tensor.h:212
Bijective function mapping for data layout transformation. Given two Layout, BijectiveLayout build an...
Definition: data_layout.h:333
Definition: index_map.h:169
IndexMap Inverse(ffi::Array< Range > initial_ranges, arith::Analyzer *analyzer) const
Generate the inverse mapping.
Managed reference to LayoutNode.
Definition: data_layout.h:124
bool Equals(const Layout &rhs) const
Whether the two layouts are equal.
Definition: data_layout.h:279
Managed reference to SelectNode.
Definition: expr.h:515
A variable node in the IR.
Definition: var.h:48
ffi::String name_hint
The hint to the variable name.
Definition: var.h:54
a named variable in TIR
Definition: var.h:77
Utility functions for handling constants in TVM expressions.
Layout expression to describe the data organization of a tensor. And BijectiveLayout to mapping two d...
Detail broadcast.
Defines a remapping of buffer indices.
Base expr nodes in TVM.
Tensor expression language DSL.
Definition: extracted_task.h:33
IterVar reduce_axis(Range dom, std::string name="rv")
Create a new IterVar for reduction operations.
Tensor compute(ffi::Array< PrimExpr > shape, FCompute fcompute, std::string name="tensor", std::string tag="", ffi::Map< ffi::String, ffi::Any > attrs={})
Construct a new tensor by computing over shape, using the computation rule: result_tensor[axis] = fco...
Var var(std::string name_hint, DataType t=DataType::Int(32))
Construct a new Var expression.
PrimExpr make_const(DataType t, ValueType value, Span span=Span())
Make a const value with certain data type.
Definition: op.h:994
DataType DefaultIndexType()
if TVM_INDEX_DEFAULT_I64 is set, return int64, otherwise return int32
Definition: buffer.h:43
PrimExpr make_zero(DataType t, Span span=Span())
Make a const zero expr.
Definition: op.h:1008
te::Tensor dynamic_strided_slice(const te::Tensor &x, const te::Tensor &begin, const te::Tensor &end, const te::Tensor &strides, ffi::Array< PrimExpr > output_shape, std::string name="T_strided_slice_dynamic", std::string tag=kInjective)
Definition: transform.h:2223
PrimExpr GetLength(PrimExpr begin, PrimExpr end, PrimExpr stride, PrimExpr extent, bool assume_inbound=true)
Definition: transform.h:685
Tensor sequence_mask(const Tensor &data, const Tensor &valid_length, double mask_value, int axis, std::string name="T_sequence_mask", std::string tag=kInjective)
Mask the out-of-boundary elements of each sequence.
Definition: transform.h:1081
Tensor gather_nd(const Tensor &data, const Tensor &indices, int batch_dims=0, std::string name="T_gather_nd", std::string tag=kInjective)
Gather elements from a n-dimension array.
Definition: transform.h:1543
int64_t StaticCanonicalizeIndex(int64_t index, int64_t extent, int64_t stride)
Definition: transform.h:666
Tensor reshape(const Tensor &x, ffi::Array< PrimExpr > newshape, std::string name="T_reshape", std::string tag=kInjective)
Reshape a tensor.
Definition: transform.h:328
Tensor one_hot(const Tensor &indices, const PrimExpr on_value, const PrimExpr off_value, int depth, int axis, const DataType &dtype, ffi::Array< PrimExpr > oshape=ffi::Array< PrimExpr >(), const std::string name="T_one_hot", const std::string tag=kInjective)
Returns a one-hot tensor where the locations repsented by indices take value on_value,...
Definition: transform.h:2016
tvm::te::Tensor broadcast_to(const tvm::te::Tensor &t, const tvm::ffi::Array< tvm::PrimExpr > &output_shape, std::string name="T_broadcast_to", std::string tag=kBroadcast)
Creates an operation that broadcasts a tensor into a compatible shape according to numpy's rules.
Definition: broadcast.h:48
constexpr auto kBroadcast
Definition: tags.h:36
Tensor arange(const PrimExpr &start, const PrimExpr &stop, const PrimExpr &step, DataType dtype, std::string name="T_arange", std::string tag=kInjective)
Definition: transform.h:1718
constexpr auto kInjective
Definition: tags.h:33
Tensor stack(const ffi::Array< Tensor > &inputs, int axis=0, std::string name="T_stack", std::string tag=kInjective)
Join a sequence of tensors along a new axis.
Definition: transform.h:537
Tensor auto_scheduler_layout_transform(const Tensor &src, const ffi::String &src_layout, const ffi::String &dst_layout, const ffi::String name="T_auto_scheduler_layout_trans", const ffi::String tag=kInjective)
Transform the auto-scheduler generated layout according to src_layout and dst_layout.
Definition: transform.h:1866
ffi::Array< PrimExpr > StridedSliceOutputShape(const ffi::Array< PrimExpr > &ishape, const ffi::Array< Integer > &begin, const ffi::Array< Integer > &end, const ffi::Array< Integer > &strides, const ffi::Array< Integer > &axes, const std::string &slice_mode)
Calculate the output shape of strided_slice, the entry point for Relax type relation.
Definition: transform.h:864
PrimExpr CanonicalizeIndex(PrimExpr index, PrimExpr extent, PrimExpr stride)
Definition: transform.h:675
te::Tensor dynamic_strided_slice_with_axes(const te::Tensor &x, const ffi::Array< PrimExpr > &begin, const ffi::Array< PrimExpr > &end, const ffi::Array< PrimExpr > &strides, const ffi::Array< Integer > &axes, bool assume_inbound=true, std::string name="T_dynamic_strided_slice_with_axes", std::string tag=kInjective)
strided_slice of a tensor where begin/end/stride can be mixed static and dynamic
Definition: transform.h:712
Tensor transpose(const Tensor &x, ffi::Optional< ffi::Array< Integer >> opt_axes, std::string name="T_transpose", std::string tag=kInjective)
Permute the dimensions of an array.
Definition: transform.h:204
void parse_auto_scheduler_layout(const ffi::String &layout, ffi::Array< PrimExpr > *shape, std::vector< std::string > *axes)
Utility function for auto_scheduler_layout_transform.
Definition: transform.h:1830
Tensor squeeze(const Tensor &x, ffi::Optional< ffi::Array< Integer >> opt_axes, bool atleast1d=false, std::string name="T_squeeze", std::string tag=kInjective)
Remove size 1 dimensions from the shape of a tensor. The removed dimensions must have a constant size...
Definition: transform.h:413
ffi::Array< Tensor > split_n_sections(const Tensor &x, int num_sections, int axis, std::string name="T_split_sections", std::string tag=kInjective)
Split a tensor into a number of sub-tensors.
Definition: transform.h:985
Tensor cast(const Tensor &x, DataType type, std::string name="T_cast", std::string tag=kElementWise)
Cast each element of x to the given type. If expr is scalar and type is a corresponding vector type,...
Definition: elemwise.h:281
Tensor expand_dims(const Tensor &x, int axis, int num_newaxis=1, std::string name="T_expand_dims", std::string tag=kBroadcast)
Creates an operation to insert new dimensions of length 1.
Definition: transform.h:155
Tensor sparse_to_dense(const Tensor &sparse_indices, const ffi::Array< PrimExpr > &output_shape, const Tensor &sparse_values, const PrimExpr &default_value, const std::string name="T_sparse_to_dense", const std::string tag=kInjective)
Get a dense tensor.
Definition: transform.h:2063
Tensor unravel_index(const Tensor &x, const Tensor &shape, std::string name="T_unravel", std::string tag=kInjective)
Converts a flat index or array of flat indices into a tuple of coordinate arrays.
Definition: transform.h:365
Tensor layout_transform(const Tensor &src, const std::string &src_layout, const std::string &dst_layout, const std::string schedule_rule="None", const std::string name="T_layout_trans", const std::string tag=kInjective)
Transform the layout according to src_layout and dst_layout.
Definition: transform.h:1788
Tensor adv_index(const Tensor &data, const ffi::Array< Tensor > &indices, const std::string name="advanced_index", const std::string tag=kInjective)
Numpy style advanced indexing with tensor.
Definition: transform.h:2171
Tensor strided_slice(const Tensor &x, const ffi::Array< Integer > &begin, const ffi::Array< Integer > &end, const ffi::Array< Integer > &strides, std::string slice_mode="end", std::string name="T_strided_slice", std::string tag=kInjective)
strided_slice of a tensor
Definition: transform.h:943
Tensor concatenate(const ffi::Array< Tensor > &inputs, int axis=0, std::string name="T_concat", std::string tag=kInjective)
Join a sequence of tensors along an existing axis.
Definition: transform.h:478
ffi::Array< Tensor > meshgrid(const ffi::Array< Tensor > &inputs, const std::string &indexing, std::string name="T_meshgrid", std::string tag=kInjective)
Produce grids by expanding input over dimensions defined by other inputs.
Definition: transform.h:1752
constexpr auto kMatMul
Definition: tags.h:37
Tensor strided_slice_with_axes(const Tensor &x, const ffi::Array< Integer > &begin, const ffi::Array< Integer > &end, const ffi::Array< Integer > &strides, const ffi::Array< Integer > &axes, std::string slice_mode="end", std::string name="T_strided_slice_with_axes", std::string tag=kInjective)
strided_slice of a tensor
Definition: transform.h:895
Tensor dyn_tile(const Tensor &x, ffi::Array< PrimExpr > new_shape, size_t rdim, std::string name="T_tile", std::string tag=kBroadcast)
Creates an operation to tile elements of an array.
Definition: transform.h:1452
Tensor reverse_sequence(const Tensor &x, const Tensor &seq_lengths, int seq_axis=1, int batch_axis=0, std::string name="T_reverse_sequence", std::string tag=kInjective)
Reverse the tensor for variable length slices. Input is first sliced along batch axis and then elemen...
Definition: transform.h:263
ffi::Array< Tensor > split_indices_array(const Tensor &x, ffi::Array< PrimExpr > split_indices, int axis, std::string name="T_split", std::string tag=kInjective)
Split a tensor into multiple sub-tensors.
Definition: transform.h:583
Tensor tensordot(const Tensor &A, const tvm::te::Tensor &B, int axes=2, std::string name="T_tensordot", std::string tag=kMatMul)
A generalization of matrix multiplication to tensors.
Definition: transform.h:1626
Tensor sum(const Tensor &data, const ffi::Optional< ffi::Array< Integer >> &axis, bool keepdims=false, bool atleast1d=false)
Creates an operation that sums array elements over a given axis.
Definition: reduction.h:328
Tensor meta_schedule_layout_transform(const Tensor &src, const tir::IndexMap &index_map, const ffi::String name="T_meta_schedule_layout_trans", const ffi::String tag=kInjective)
Transform the meta-schedule generated layout according to TIR's IndexMap.
Definition: transform.h:1932
Tensor tile(const Tensor &x, ffi::Array< Integer > reps, std::string name="T_tile", std::string tag=kBroadcast)
Creates an operation to tile elements of an array.
Definition: transform.h:1396
Tensor take(const Tensor &a, const Tensor &indices, int batch_dims, std::string mode="fast", std::string name="T_take", std::string tag=kInjective)
Take elements from an flattened input array when axis is None.
Definition: transform.h:1021
PrimExpr DynamicCanonicalizeIndex(PrimExpr index, PrimExpr extent, PrimExpr stride)
Definition: transform.h:648
tvm::te::Tensor matmul(const tvm::te::Tensor &A, const tvm::te::Tensor &B, bool trans_a=false, bool trans_b=false, std::string name="T_matmul", std::string tag=kMatMul)
Creates an operation that calculates a matrix multiplication (row-major notation): A(i,...
Definition: transform.h:1604
Tensor dynamic_strided_slice(const Tensor &x, const ffi::Array< PrimExpr > &begin, const ffi::Array< PrimExpr > &end, const ffi::Array< PrimExpr > &strides, bool assume_inbound=true, std::string name="T_dynamic_strided_slice", std::string tag=kInjective)
strided_slice of a tensor where begin/end/stride can be mixed static and dynamic
Definition: transform.h:769
Tensor matrix_set_diag(const Tensor &input, const Tensor &diagonal, int k1, int k2, bool super_diag_right_align, bool sub_diag_right_align, const std::string name="T_matrix_set_diag", const std::string tag=kInjective)
Returns a tensor with the diagonal of input tensor replaced with the provided diagonals.
Definition: transform.h:2115
Tensor where(const Tensor &condition, const Tensor &x, const Tensor &y, std::string name="T_where", std::string tag=kBroadcast)
Return the elements, either from x or y, depending on the condition.
Definition: transform.h:1309
Tensor shape(const Tensor &src, DataType dtype, const std::string name="T_shape", const std::string tag=kInjective)
Get the shape of input tensor.
Definition: transform.h:1960
Tensor gather(const Tensor &data, int axis, const Tensor &indices, std::string name="T_gather", std::string tag=kInjective)
Gather values along given axis from given indices.
Definition: transform.h:1490
Tensor sliding_window(const Tensor &x, int axis, ffi::Array< Integer > window_shape, ffi::Array< Integer > strides, std::string name="T_sliding_window", std::string tag="")
Creates an operation to slide a window over the input x.
Definition: transform.h:76
te::Tensor tensor_size(const te::Tensor &src, const DataType &dtype, const std::string &name="tensor_size", const std::string &tag=kInjective)
Get the size of input tensor.
Definition: transform.h:1985
Tensor repeat(const Tensor &x, int repeats, int axis, std::string name="T_repeat", std::string tag=kBroadcast)
Creates an operation to repeat elements of an array.
Definition: transform.h:1349
Performance counters for profiling via the PAPI library.
Definition: analyzer.h:37
PrimExpr ceildiv(PrimExpr a, PrimExpr b, Span span=Span())
compute ceil(a / b)
PrimExpr ret(PrimExpr value, Span span=Span())
Return the value.
PrimExpr max(PrimExpr a, PrimExpr b, Span span=Span())
take maximum of two values
PrimExpr truncmod(PrimExpr a, PrimExpr b, Span span=Span())
compute the remainder of truncdiv
PrimExpr if_then_else(PrimExpr cond, PrimExpr true_value, PrimExpr false_value, Span span=Span())
Conditional expression.
PrimExpr cast(const DataType &t, PrimExpr value, Span span=Span())
cast value to type.
PrimExpr max_value(const DataType &dtype, Span span=Span())
PrimExpr ceil(PrimExpr x, Span span=Span())
Calculate ceil(x)
PrimExpr sum(PrimExpr source, ffi::Array< tir::IterVar > axis, ffi::Array< PrimExpr > init={}, Span span=Span())
sum of source expression over axis
PrimExpr indexdiv(PrimExpr a, PrimExpr b, Span span=Span())
compute floor(a / b) where a and b are non-negative.
PrimExpr min(PrimExpr a, PrimExpr b, Span span=Span())
take minimum of two values
PrimExpr indexmod(PrimExpr a, PrimExpr b, Span span=Span())
compute the remainder floor(a / b) where a and b are non-negative.
PrimExpr floordiv(PrimExpr a, PrimExpr b, Span span=Span())
compute floor(a / b)
Operation node can generate one or multiple Tensors.
Index ravel and unraval operations.
Utility functions for strided_slice op.
External function interface to rocBLAS libraries.
Utility functions for handling tensor.
TIR expressions.
Common operators defined for Expr.
Variables in the TIR.