/
transform.h
2151 lines (1984 loc) · 78.1 KB
/
transform.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file topi/transform.h
* \brief Transform op constructors
*/
#ifndef TVM_TOPI_TRANSFORM_H_
#define TVM_TOPI_TRANSFORM_H_
#include <tvm/arith/analyzer.h>
#include <tvm/te/operation.h>
#include <tvm/tir/data_layout.h>
#include <tvm/tir/index_map.h>
#include <tvm/topi/broadcast.h>
#include <tvm/topi/detail/broadcast.h>
#include <tvm/topi/detail/constant_utils.h>
#include <tvm/topi/detail/ravel_unravel.h>
#include <tvm/topi/detail/strided_slice.h>
#include <tvm/topi/detail/tensor_utils.h>
#include <tvm/topi/tags.h>
#include <algorithm>
#include <iterator>
#include <limits>
#include <string>
#include <unordered_set>
#include <vector>
#include "tvm/tir/expr.h"
namespace tvm {
namespace topi {
using namespace tvm::te;
using namespace topi::detail;
/*!
* \brief Creates an operation to slide a window over the input x.
*
* \param x The input tensor.
* \param axis What axis the window begins sliding over. Window will be slid
* over this axis and all following axes. The axis value determines the window
* shape (and thus, the number of strides): window shape and strides must both
* be of length `data.ndim-axis`.
* \param window_shape The window shape to form over the input. Window shape
* must be of length `data.ndim-axis`.
* \param strides How to stride the window along each dimension. Strides must be
* of length `data.ndim-axis`.
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the sliding_window operation
*/
inline Tensor sliding_window(const Tensor& x, int axis, Array<Integer> window_shape,
Array<Integer> strides, std::string name = "T_sliding_window",
std::string tag = "") {
CHECK_GE(axis, 0);
auto _axis = size_t(axis);
CHECK_LT(_axis, x->shape.size()) << "axis must be a valid dimension index of x.";
CHECK_EQ(x->shape.size() - _axis, window_shape.size())
<< "There must be a window shape for every dimension of x "
<< "over which we are sliding the window.";
CHECK_EQ(strides.size(), window_shape.size()) << "Windows and strides should be the same length.";
// Compute the new shape.
Array<PrimExpr> new_shape;
// Dimensions up until `axis` remain the same.
for (size_t i = 0; i < _axis; ++i) {
new_shape.push_back(x->shape[i]);
}
// New dimensions which result from sliding the window in each dimension. One new dimension per
// window dimension.
for (size_t i = 0; i < window_shape.size(); ++i) {
// Length of the shape along this dimension.
auto dim_len = x->shape[_axis + i];
// Length of the window along this dimension.
auto window_len = window_shape[i];
// Strides along this dimension.
auto stride = strides[i];
new_shape.push_back(floordiv(dim_len - (window_len - 1) + stride - 1, stride));
}
// Dimensions comprising the window.
for (size_t i = 0; i < window_shape.size(); ++i) {
new_shape.push_back(window_shape[i]);
}
ICHECK(new_shape.size() == _axis + 2 * window_shape.size());
return compute(
new_shape,
[&](const Array<Var>& indices) {
// The index at which to index the old tensor x.
Array<PrimExpr> idx;
// Dimensions up until `axis` remain the same.
for (size_t i = 0; i < _axis; ++i) {
idx.push_back(indices[i]);
}
for (size_t i = 0; i < window_shape.size(); ++i) {
// Which window in this dimension we are indexing.
auto window_idx = indices[_axis + i];
// Which index within the window we are indexing.
auto idx_within_window = indices[_axis + window_shape.size() + i];
// Stride value for this dimension.
auto stride = strides[i];
idx.push_back(window_idx * stride + idx_within_window);
}
ICHECK(idx.size() == x->shape.size());
return x(idx);
},
name, tag);
}
/*!
* \brief Creates an operation to insert new dimensions of length 1
*
* \param x The input tensor
* \param axis The index of the first new dimension (allows negative
* indices as offsets from the last dimension)
* \param num_newaxis The number of new dimensions to insert
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the dim expansion operation
*/
inline Tensor expand_dims(const Tensor& x, int axis, int num_newaxis = 1,
std::string name = "T_expand_dims", std::string tag = kBroadcast) {
int ndim = static_cast<int>(x->shape.size());
ICHECK(-ndim - 1 <= axis && axis <= ndim)
<< "expand_dims only accepts `axis` in [-data.ndim - 1, data.ndim]"
<< ", but got axis = " << axis << ", and data.ndim = " << ndim;
ICHECK(num_newaxis >= 0) << "expand_dims only accepts `num_newaxis >= 0`"
<< ", but got num_newaxis = " << num_newaxis;
if (axis < 0) {
// Calculate offset from last dimension
axis = ndim + axis + 1;
}
Array<PrimExpr> new_shape;
for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {
new_shape.push_back(x->shape[i]);
}
for (size_t i = 0; i < static_cast<size_t>(num_newaxis); ++i) {
new_shape.push_back(1);
}
for (size_t i = axis; i < x->shape.size(); ++i) {
new_shape.push_back(x->shape[i]);
}
return compute(
new_shape,
[&](const Array<Var>& indices) {
Array<PrimExpr> idx;
for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {
idx.push_back(indices[i]);
}
for (size_t i = axis + num_newaxis; i < indices.size(); ++i) {
idx.push_back(indices[i]);
}
return x(idx);
},
name, tag);
}
/*!
* \brief Permute the dimensions of an array
*
* \param x The input tensor
* \param axes The indices of the permutation. If this is empty,
* the dimensions will be reversed.
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the transpose operation
*/
inline Tensor transpose(const Tensor& x, Array<Integer> axes, std::string name = "T_transpose",
std::string tag = kInjective) {
if (!axes.defined() || axes.size() == 0) {
axes = Array<Integer>();
for (int i = static_cast<int>(x->shape.size()) - 1; i >= 0; --i) {
axes.push_back(i);
}
}
Array<PrimExpr> new_shape;
for (size_t i = 0; i < axes.size(); ++i) {
int axis = static_cast<int>(axes[i]->value);
int new_axis = axis;
if (axis < 0) {
new_axis = static_cast<int>(x->shape.size()) + axis;
axes.Set(i, new_axis);
}
ICHECK((new_axis >= 0) && (new_axis < static_cast<int>(x->shape.size())))
<< "axis=" << axis << " is invalid for the " << static_cast<int>(x->shape.size())
<< "-dimensional input tensor";
for (size_t j = 0; j < axes.size(); ++j) {
if (i != j) {
ICHECK(new_axis != static_cast<int>(axes[j]->value)) << "repeated axis in transpose";
}
}
new_shape.push_back(x->shape[new_axis]);
}
return compute(
new_shape,
[&](const Array<Var>& indices) {
std::vector<PrimExpr> idx;
for (size_t i = 0; i < axes.size(); ++i) {
idx.push_back(1);
}
for (size_t i = 0; i < axes.size(); ++i) {
int axis = static_cast<int>(axes[i]->value);
idx[axis] = indices[i];
}
return x(idx);
},
name, tag);
}
/*!
* \brief Reverse the tensor for variable length slices.
* Input is first sliced along batch axis and then elements are reversed along seq axis.
*
* \param x The input tensor
* \param seq_lengths A 1D Tensor with length x.dims[batch_axis]. Optional Tensor() can be passed.
* If not defined batch axis is ignored and tensor is reversed along seq_axis.
* \param seq_axis The axis along which the elements will be reveresed
* \param batch_axis The axis along which the tensor will be sliced
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the reverse_sequence operation
*/
inline 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) {
size_t src_tensor_dim = x->shape.size();
int seq_axis_inp = seq_axis;
if (seq_lengths.defined()) {
size_t seq_lengths_dim = seq_lengths->shape.size();
int batch_axis_inp = batch_axis;
if (batch_axis < 0) {
batch_axis = static_cast<int>(x->shape.size()) + batch_axis;
}
ICHECK(seq_lengths_dim == 1) << "seq_lengths should be 1D vector";
ICHECK(GetConstInt(seq_lengths->shape[0]) == GetConstInt(x->shape[batch_axis]))
<< "For reverse_sequnece seq_lengths size should match with dimension of batch axis"
<< ", but got dimension of batch_axis = " << GetConstInt(x->shape[batch_axis])
<< ", and seq_length size = " << GetConstInt(seq_lengths->shape[0]);
ICHECK((0 <= batch_axis) && (batch_axis < static_cast<int>(x->shape.size())))
<< "batch_axis=" << batch_axis_inp << " is invalid for the "
<< static_cast<int>(x->shape.size()) << "-dimensional input tensor";
}
if (seq_axis < 0) {
seq_axis = static_cast<int>(x->shape.size()) + seq_axis;
}
ICHECK((0 <= seq_axis) && (seq_axis < static_cast<int>(x->shape.size())))
<< "seq_axis=" << seq_axis_inp << " is invalid for the " << static_cast<int>(x->shape.size())
<< "-dimensional input tensor";
auto func = [&](const Array<Var>& indices) {
Array<PrimExpr> real_indices;
for (size_t i = 0; i < src_tensor_dim; ++i) {
if (i == static_cast<size_t>(seq_axis)) {
if (seq_lengths.defined()) {
auto len = seq_lengths(indices[batch_axis]);
auto idx = if_then_else(
len <= 1 || len <= indices[i], indices[i],
if_then_else(len > x->shape[i], x->shape[i] - 1 - indices[i], len - 1 - indices[i]));
real_indices.push_back(idx);
} else {
real_indices.push_back(x->shape[i] - 1 - indices[i]);
}
} else {
real_indices.push_back(indices[i]);
}
}
return x(real_indices);
};
return compute(x->shape, func, name, tag);
}
/*!
* \brief Reshape a tensor
*
* \param x The input tensor
* \param newshape The new shape
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the reshape operation
*/
inline Tensor reshape(const Tensor& x, Array<PrimExpr> newshape, std::string name = "T_reshape",
std::string tag = kInjective) {
auto x_shape = x->shape;
Array<PrimExpr> target_shape;
for (const auto& ele : newshape) {
target_shape.push_back(ele);
}
// If either the input shape or the target shape contains a zero, return an empty tensor.
if (is_empty_shape(target_shape) || is_empty_shape(x->shape)) {
return compute(
target_shape, [&](const Array<Var>& indices) { return tvm::cast(x->dtype, 0); }, name, tag);
} else {
return compute(
target_shape,
[&](const Array<Var>& indices) {
return x(UnravelIndex(
RavelIndex(Array<PrimExpr>{indices.begin(), indices.end()}, target_shape), x_shape));
},
name, tag);
}
}
/*!
* \brief Converts a flat index or array of flat indices into a tuple of coordinate arrays
*
* \param x The input tensor having indices.
* \param shape The shape tensor
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor of coordinate arrays.
*/
inline Tensor unravel_index(const Tensor& x, const Tensor& shape, std::string name = "T_unravel",
std::string tag = kInjective) {
auto x_shape = x->shape;
auto shape_shape = shape->shape;
Array<PrimExpr> oshape;
oshape.push_back(shape_shape[0]);
if (x_shape.size() != 0) {
oshape.push_back(x_shape[0]);
}
auto func = [&](const Array<Var>& indices) {
auto i = indices[0];
std::vector<PrimExpr> indices_divs;
PrimExpr ret = 0;
PrimExpr cur_val = 0;
PrimExpr index_val = 0;
if (x_shape.size() != 0) {
index_val = x[indices[1]];
} else {
index_val = x();
}
indices_divs.push_back(index_val);
for (int v = GetConstInt(shape_shape[0]) - 1; v >= 0; --v) {
ret = tvm::if_then_else(i == v, indexmod(indices_divs.back(), shape[v]), ret);
cur_val = indexdiv(indices_divs.back(), shape[v]);
indices_divs.push_back(cur_val);
}
return ret;
};
return compute(oshape, func, name, tag);
}
/*!
* \brief Remove size 1 dimensions from the shape of a tensor.
* The removed dimensions must have a constant size of 1.
*
* \param x The input tensor
* \param axis Indices of the dimensions to remove. If this is None,
* all entries with a constant size of 1 will be removed.
* \param atleast1d Whether the output need to be atleast1d.
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the squeeze operation
*/
inline Tensor squeeze(const Tensor& x, Array<Integer> axis, bool atleast1d = false,
std::string name = "T_squeeze", std::string tag = kInjective) {
auto ndim = x->shape.size();
std::vector<int> axis_val;
if (!axis.defined()) {
for (size_t i = 0; i < ndim; ++i) {
if (IsConstInt(x->shape[i]) && GetConstInt(x->shape[i]) == 1) {
axis_val.push_back(static_cast<int>(i));
}
}
} else {
for (size_t i = 0; i < axis.size(); ++i) {
int64_t val = axis[i]->value;
if (val < 0) {
val += static_cast<int>(x->shape.size());
}
if (IsConstInt(x->shape[val])) {
ICHECK_EQ(GetConstInt(x->shape[val]), 1) << "Dimension " << val << " must have size 1";
}
axis_val.push_back(val);
}
}
std::unordered_set<int> axis_set(axis_val.begin(), axis_val.end());
Array<PrimExpr> out_shape;
for (size_t i = 0; i < ndim; ++i) {
if (axis_set.count(static_cast<int>(i)) == 0) {
out_shape.push_back(x->shape[i]);
}
}
if (out_shape.size() == 0 && atleast1d) {
out_shape.push_back(1);
}
return compute(
out_shape,
[&](const Array<Var>& indices) {
Array<PrimExpr> real_indices;
int flag = 0;
for (size_t i = 0; i < ndim; ++i) {
if (axis_set.count(static_cast<int>(i)) == 0) {
real_indices.push_back(indices[i - flag]);
} else {
real_indices.push_back(0);
flag += 1;
}
}
return x(real_indices);
},
name, tag);
}
/*!
* \brief Join a sequence of tensors along an existing axis
*
* \param inputs The input tensors
* \param axis The axis along which the tensors will be joined
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the concatenate operation
*/
inline Tensor concatenate(const Array<Tensor>& inputs, int axis = 0, std::string name = "T_concat",
std::string tag = kInjective) {
int ndim = static_cast<int>(inputs[0]->shape.size());
ICHECK(-ndim <= axis && axis < ndim) << "concatenate only accepts `axis` in [-ndim, ndim)"
<< ", but got axis = " << axis << ", and ndim = " << ndim;
if (axis < 0) {
axis += ndim;
}
ICHECK_LT(axis, inputs[0]->shape.size()) << "axis out of bounds";
Array<PrimExpr> axis_sizes;
for (auto t : inputs) {
axis_sizes.push_back(t->shape[axis]);
}
arith::Analyzer analyzer;
PrimExpr join_size = axis_sizes[0];
for (size_t i = 1; i < axis_sizes.size(); ++i) {
join_size += axis_sizes[i];
}
join_size = analyzer.Simplify(join_size);
Array<PrimExpr> out_shape;
for (size_t i = 0; i < inputs[0]->shape.size(); ++i) {
out_shape.push_back(i == static_cast<size_t>(axis) ? join_size : inputs[0]->shape[i]);
}
return compute(
out_shape,
[&](const Array<Var>& indices) {
auto ret = inputs[0](indices);
auto ind = indices[axis];
for (size_t i = 0; i < inputs.size() - 1; ++i) {
ind -= axis_sizes[i];
Array<PrimExpr> idx;
for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {
idx.push_back(indices[i]);
}
idx.push_back(ind);
for (size_t i = axis + 1; i < indices.size(); ++i) {
idx.push_back(indices[i]);
}
ret = tvm::if_then_else(ind >= 0, inputs[i + 1](idx), ret);
}
return ret;
},
name, tag);
}
/*!
* \brief Join a sequence of tensors along a new axis.
*
* \param inputs The input tensors
* \param axis The axis along which the tensors will be stacked
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the stack operation
*/
inline Tensor stack(const Array<Tensor>& inputs, int axis = 0, std::string name = "T_stack",
std::string tag = kInjective) {
int ndim = static_cast<int>(inputs[0]->shape.size());
ICHECK(-ndim - 1 <= axis && axis <= ndim)
<< "stack only accepts `axis` in [-ndim, ndim)"
<< ", but got axis = " << axis << ", and ndim = " << ndim;
if (axis < 0) {
axis += ndim + 1;
}
ICHECK_LT(axis, inputs[0]->shape.size() + 1) << "axis out of bounds";
const int stack_size = static_cast<int>(inputs.size());
Array<PrimExpr> out_shape;
for (size_t i = 0; i < static_cast<size_t>(axis); ++i) out_shape.push_back(inputs[0]->shape[i]);
out_shape.push_back(stack_size);
for (size_t i = static_cast<size_t>(axis); i < static_cast<size_t>(ndim); ++i)
out_shape.push_back(inputs[0]->shape[i]);
return compute(
out_shape,
[&](const Array<Var>& indices) {
Array<PrimExpr> idx;
for (size_t i = 0; i < indices.size(); ++i)
if (i != static_cast<size_t>(axis)) idx.push_back(indices[i]);
auto ind = indices[axis];
auto ret = inputs[0](idx);
for (int i = 0; i < static_cast<int>(inputs.size() - 1); ++i) {
ret = tvm::if_then_else(ind == i + 1, inputs[i + 1](idx), ret);
}
return ret;
},
name, tag);
}
/*!
* \brief Split a tensor into multiple sub-tensors
*
* \param x The input tensor
* \param split_indices The indices to split the input at. This must be in ascending
* order.
* \param axis The axis to split along.
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the split operation
*/
inline Array<Tensor> split(const Tensor& x, Array<PrimExpr> split_indices, int axis,
std::string name = "T_split", std::string tag = kInjective) {
if (axis < 0) {
axis += static_cast<int>(x->shape.size());
}
ICHECK_LT(axis, x->shape.size()) << "axis out of bounds";
auto src_axis_size = x->shape[axis];
std::vector<PrimExpr> begin_ids;
begin_ids.push_back(0);
for (auto idx : split_indices) {
auto idx_node = idx.as<IntImmNode>();
auto back_node = begin_ids.back().as<IntImmNode>();
if (idx_node && back_node) {
ICHECK_GT(idx_node->value, back_node->value) << "split_indices must be sorted";
}
begin_ids.push_back(idx);
}
Array<Array<PrimExpr>> out_shapes;
for (size_t i = 0; i < begin_ids.size(); ++i) {
PrimExpr out_axis_size;
if (i == begin_ids.size() - 1) {
out_axis_size = src_axis_size - begin_ids[i];
} else {
out_axis_size = begin_ids[i + 1] - begin_ids[i];
}
Array<PrimExpr> shape;
for (size_t i = 0; i < static_cast<size_t>(axis); ++i) {
shape.push_back(x->shape[i]);
}
shape.push_back(out_axis_size);
for (size_t i = axis + 1; i < x->shape.size(); ++i) {
shape.push_back(x->shape[i]);
}
out_shapes.push_back(shape);
}
Array<Tensor> result;
for (size_t i = 0; i < begin_ids.size(); ++i) {
result.push_back(compute(
out_shapes[i],
[&](const Array<Var>& indices) {
auto begin = begin_ids[i];
Array<PrimExpr> real_indices;
for (size_t j = 0; j < static_cast<size_t>(axis); ++j) {
real_indices.push_back(indices[j]);
}
real_indices.push_back(indices[axis] + begin);
for (size_t j = axis + 1; j < indices.size(); ++j) {
real_indices.push_back(indices[j]);
}
return x(real_indices);
},
name, tag));
}
return result;
}
/*!
* \brief strided_slice of a tensor where begin/end/stride can be mixed static and dynamic
*
* \param x The input tensor
* \param begin The indices to begin with in the slicing
* \param end Indices indicating end of the slice
* \param strides Specifies the stride values, it can be negative
* in that case, the input tensor will be reversed in that particular axis
* \param axes Specifies which axes will be updated.
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the dynamic_strided_slice operation
*/
inline Tensor dynamic_strided_slice_with_axes(
const Tensor& x, const Array<PrimExpr>& begin, const Array<PrimExpr>& end,
const Array<PrimExpr>& strides, const Array<Integer>& axes,
std::string name = "T_dynamic_strided_slice_with_axes", std::string tag = kInjective) {
const size_t src_tensor_dim = x->shape.size();
ICHECK_EQ(begin.size(), end.size());
ICHECK_EQ(begin.size(), strides.size());
ICHECK_EQ(begin.size(), axes.size());
ICHECK_LE(begin.size(), src_tensor_dim);
for (const auto& axis_imm : axes) {
int axis = axis_imm->value;
ICHECK_LT(axis, src_tensor_dim);
}
arith::Analyzer analyzer;
Array<PrimExpr> out_shape = x->shape;
for (size_t i = 0; i < begin.size(); i++) {
int axis = axes[i]->value;
PrimExpr new_shape = analyzer.Simplify(ceildiv(end[i] - begin[i], strides[i]));
out_shape.Set(axis, new_shape);
}
return te::compute(
out_shape,
[&](const Array<tvm::tir::Var>& indices) {
Array<PrimExpr> real_indices = indices.Map([](const auto& var) -> PrimExpr { return var; });
for (size_t i = 0; i < begin.size(); i++) {
int axis = axes[i]->value;
PrimExpr new_index = indices[axis] * strides[i] + begin[i];
real_indices.Set(axis, new_index);
}
return x(real_indices);
},
name, tag);
}
/*!
* \brief strided_slice of a tensor where begin/end/stride can be mixed static and dynamic
*
* \param x The input tensor
* \param begin The indices to begin with in the slicing
* \param end Indices indicating end of the slice
* \param strides Specifies the stride values, it can be negative
* in that case, the input tensor will be reversed in that particular axis
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the dynamic_strided_slice operation
*/
inline Tensor dynamic_strided_slice(const Tensor& x, const Array<PrimExpr>& begin,
const Array<PrimExpr>& end, const Array<PrimExpr>& strides,
std::string name = "T_dynamic_strided_slice",
std::string tag = kInjective) {
const size_t src_tensor_dim = x->shape.size();
ICHECK_LE(begin.size(), src_tensor_dim);
ICHECK_LE(end.size(), src_tensor_dim);
ICHECK_LE(strides.size(), src_tensor_dim);
ICHECK_EQ(begin.size(), end.size());
ICHECK_EQ(begin.size(), strides.size());
const size_t num_slice_axes = begin.size();
Array<PrimExpr> out_shape;
arith::Analyzer analyzer;
for (size_t i = 0; i < num_slice_axes; ++i) {
// Check ProducerLoad to keep backward compatibility for Relay.
if (!begin[i]->IsInstance<ProducerLoadNode>() && !end[i]->IsInstance<ProducerLoadNode>() &&
!strides[i]->IsInstance<ProducerLoadNode>()) {
out_shape.push_back(analyzer.Simplify(ceildiv(end[i] - begin[i], strides[i])));
} else {
out_shape.push_back(tvm::tir::Var("dim"));
}
}
for (size_t i = num_slice_axes; i < src_tensor_dim; ++i) {
out_shape.push_back(x->shape[i]);
}
return te::compute(
out_shape,
[&](const Array<tvm::tir::Var>& indices) {
Array<PrimExpr> real_indices;
for (size_t i = 0; i < num_slice_axes; ++i) {
real_indices.push_back(indices[i] * strides[i] + tvm::min(begin[i], x->shape[i] - 1));
}
// keep input dim
for (size_t i = num_slice_axes; i < src_tensor_dim; ++i) {
real_indices.push_back(indices[i]);
}
return x(real_indices);
},
name, tag);
}
/*!
* \brief strided_slice of a tensor with dynamic begin/end/stride
*
* \param x The input tensor
* \param begin The indices to begin with in the slicing
* \param end Indices indicating end of the slice
* \param strides Specifies the stride values, it can be negative
* in that case, the input tensor will be reversed in that particular axis
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the dynamic_strided_slice operation
*/
inline te::Tensor dynamic_strided_slice(const te::Tensor& x, const te::Tensor& begin,
const te::Tensor& end, const te::Tensor& strides,
std::string name = "T_strided_slice_dynamic",
std::string tag = topi::kInjective) {
DataType index_dtype = begin->shape[0]->dtype;
const int64_t num_dynamic_axes = begin->shape[0].as<IntImmNode>()->value;
ICHECK_EQ(end->shape[0].as<IntImmNode>()->value, num_dynamic_axes);
ICHECK_EQ(strides->shape[0].as<IntImmNode>()->value, num_dynamic_axes);
Array<PrimExpr> begin_expr, end_expr, strides_expr;
for (int64_t i = 0; i < num_dynamic_axes; ++i) {
auto ind = make_const(index_dtype, i);
begin_expr.push_back(begin(ind));
end_expr.push_back(end(ind));
strides_expr.push_back(strides(ind));
}
return dynamic_strided_slice(x, begin_expr, end_expr, strides_expr, name, tag);
}
/*!
* \brief Calculate the output shape of strided_slice, the entry point for Relay type relation
*
* \param ishape The input tensor shape
* \param begin The indices to begin with in the slicing
* \param end Indices indicating end of the slice
* \param strides Specifies the stride values, it can be negative
* in that case, the input tensor will be reversed in that particular axis
* \param axes Axes along which slicing is applied. When it is specified, the length of begin, end,
* strides, and axes argument must be equal
* \param slice_mode Specifies the slice mode
*
* \return The output shape of strided_slice using the arguments above
*/
inline Array<PrimExpr> StridedSliceOutputShape(
const Array<PrimExpr>& ishape, const Array<Integer>& begin, const Array<Integer>& end,
const Array<Integer>& strides, const Array<Integer>& axes, const std::string& slice_mode) {
ICHECK(axes.size() == begin.size() && axes.size() == end.size() && axes.size() == strides.size());
std::vector<int64_t> begin_vec, end_vec, strides_vec;
std::tie(begin_vec, end_vec, strides_vec) = ConvertToVec(begin, end, strides, slice_mode);
auto begin_canonicalized = StridedSliceCanonicalizeBegin(ishape, begin_vec, strides_vec, axes,
begin[0]->dtype, slice_mode);
return StridedSliceOutputShape(ishape, begin_vec, end_vec, strides_vec, axes, slice_mode,
begin_canonicalized, true);
}
/*!
* \brief strided_slice of a tensor
*
* \param x The input tensor
* \param begin The indices to begin with in the slicing
* \param end Indices indicating end of the slice
* \param strides Specifies the stride values, it can be negative
* in that case, the input tensor will be reversed in that particular axis
* \param axes Axes along which slicing is applied. When it is specified, the length of begin, end,
* strides, and axes argument must be equal
* \param slice_mode Specifies the slice mode
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the sstrided_slice operation
*/
inline Tensor strided_slice_with_axes(const Tensor& x, const Array<Integer>& begin,
const Array<Integer>& end, const Array<Integer>& strides,
const Array<Integer>& axes, std::string slice_mode = "end",
std::string name = "T_strided_slice_with_axes",
std::string tag = kInjective) {
const size_t src_tensor_dim = x->shape.size();
ICHECK(axes.size() <= src_tensor_dim);
ICHECK(axes.size() == begin.size() && axes.size() == end.size() && axes.size() == strides.size());
std::vector<int64_t> begin_vec, end_vec, strides_vec;
std::tie(begin_vec, end_vec, strides_vec) = ConvertToVec(begin, end, strides, slice_mode);
auto begin_expr = StridedSliceCanonicalizeBegin(x->shape, begin_vec, strides_vec, axes,
begin[0]->dtype, slice_mode);
auto out_shape = StridedSliceOutputShape(x->shape, begin_vec, end_vec, strides_vec, axes,
slice_mode, begin_expr);
return te::compute(
out_shape,
[&](const Array<tir::Var>& indices) {
Array<PrimExpr> real_indices;
for (size_t i = 0; i < out_shape.size(); ++i) real_indices.push_back(indices[i]);
for (size_t i = 0; i < axes.size(); ++i) {
auto stride = make_const(strides[i].dtype(), strides_vec[i]);
PrimExpr ind = indices[axes[i].IntValue()] * stride + begin_expr[i];
real_indices.Set(axes[i].IntValue(), ind);
}
return x(real_indices);
},
name, tag);
}
/*!
* \brief strided_slice of a tensor
*
* \param x The input tensor
* \param begin The indices to begin with in the slicing
* \param end Indices indicating end of the slice
* \param strides Specifies the stride values, it can be negative
* in that case, the input tensor will be reversed in that particular axis
* \param slice_mode Specifies the slice mode
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the strided_slice operation
*/
inline Tensor strided_slice(const Tensor& x, const Array<Integer>& begin, const Array<Integer>& end,
const Array<Integer>& strides, std::string slice_mode = "end",
std::string name = "T_strided_slice", std::string tag = kInjective) {
size_t src_tensor_dim = static_cast<size_t>(x->shape.size());
Array<Integer> axes;
for (size_t i = 0; i < src_tensor_dim; ++i) axes.push_back(i);
Array<Integer> begin_full(begin);
Array<Integer> end_full(end);
Array<Integer> strides_full(strides);
DataType index_dtype = begin.size() > 0 ? begin[0]->dtype : DataType::Int(64);
const IntImm one = IntImm(index_dtype, 1);
const IntImm zero = IntImm(index_dtype, 0);
const IntImm max_range = Downcast<IntImm>(max_value(index_dtype));
for (size_t i = strides.size(); i < src_tensor_dim; ++i) {
strides_full.push_back(one);
}
for (size_t i = begin.size(); i < src_tensor_dim; ++i) {
begin_full.push_back(GetConstInt(strides_full[i]) > 0 ? zero : max_range);
}
for (size_t i = end.size(); i < src_tensor_dim; ++i) {
end_full.push_back(GetConstInt(strides_full[i]) < 0 ? zero : max_range);
}
return strided_slice_with_axes(x, begin_full, end_full, strides_full, axes, slice_mode, name,
tag);
}
/*!
* \brief Split a tensor into a number of sub-tensors
*
* \param x The input tensor
* \param num_sections The number of sections to split the tensor into.
* this must be an integer factor of the size of the axis being split.
* \param axis The axis to split along.
* \param name The name of the operation
* \param tag The tag to mark the operation
*
* \return A Tensor whose op member is the split operation
*/
inline Array<Tensor> split_sections(const Tensor& x, int num_sections, int axis,
std::string name = "T_split_sections",
std::string tag = kInjective) {
if (axis < 0) {
axis += static_cast<int>(x->shape.size());
}
ICHECK_LT(axis, x->shape.size()) << "axis out of bounds";
auto src_axis_size = x->shape[axis];
ICHECK_GT(num_sections, 0) << "Slice count must be > 0";
if (auto node = src_axis_size.as<IntImmNode>()) {
ICHECK_EQ(node->value % num_sections, 0)
<< "num_sections must be an integer factor of the size of axis " << axis << " ("
<< node->value << ")";
}
Array<PrimExpr> split_indices;
auto seg_size = indexdiv(src_axis_size, num_sections);
for (int i = 0; i < num_sections; ++i) {
// region at index 0 is added by split()
if (i != 0) {
split_indices.push_back(seg_size * i);
}
}
return split(x, split_indices, axis, name, tag);
}
/*!
* \brief Take elements from an flattened input array when axis is None.
*
* \param a The source array.
* \param indices The indices of the values to extract.
* \param batch_dims The number of batch dimensions.
* \param mode The mode of the operation.
* \param name The name of the operation.
* \param tag The tag to mark the operation.
*
* \return A Tensor whose op member is the take operation
*/
inline Tensor take(const Tensor& a, const Tensor& indices, int batch_dims,
std::string mode = "clip", std::string name = "T_take",
std::string tag = kInjective) {
Array<PrimExpr> a_shape = a->shape;
Array<PrimExpr> out_shape = indices->shape;
PrimExpr a_size = 1;
for (size_t i = 0; i < a_shape.size(); ++i) {
a_size = a_size * a_shape[i];
}
if (mode == "clip") {
return compute(
out_shape,
[&](const Array<Var>& out_index) {
auto idx = tvm::min(tvm::max(0, indices(out_index)), a_size - 1);
return a(UnravelIndex(idx, a_shape));
},
name, tag);
} else if (mode == "fast") {
LOG(WARNING) << "Fast mode segfaults when there are out-of-bounds indices. "
"Make sure input indices are in bound";
return compute(
out_shape,
[&](const Array<Var>& out_index) { return a(UnravelIndex(indices(out_index), a_shape)); },
name, tag);
} else { // mode == "wrap"
return compute(
out_shape,
[&](const Array<Var>& out_index) {
auto idx = truncmod(truncmod(indices(out_index), a_size) + a_size, a_size);
return a(UnravelIndex(idx, a_shape));
},
name, tag);
}
}
/*!
* \brief Mask the out-of-boundary elements of each sequence.
*
* \param data The source array.
* \param valid_length The real length of each sequence.
* \param mask_value The masking value.
* \param axis The axis of the temporal dimension of the sequence
* \param name The name of the operation.
* \param tag The tag to mark the operation.
*
* \return A Tensor whose op member is the sequence_mask operation
*/