-
Notifications
You must be signed in to change notification settings - Fork 211
/
ragged_ops.cu
2326 lines (2065 loc) · 89.6 KB
/
ragged_ops.cu
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
/**
* Copyright 2020 Xiaomi Corporation (authors: Daniel Povey, Haowen Qiu)
* Mobvoi Inc. (authors: Fangjun Kuang)
* Yiming Wang
*
* See LICENSE for clarification regarding multiple authors
*
* Licensed 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.
*/
#include <algorithm>
#include <cmath>
#include <memory>
#include <vector>
#include "k2/csrc/array_ops.h"
#include "k2/csrc/cub.h"
#include "k2/csrc/macros.h"
#include "k2/csrc/math.h"
#include "k2/csrc/moderngpu_allocator.h"
#include "k2/csrc/ragged.h"
#include "k2/csrc/ragged_ops.h"
#include "k2/csrc/ragged_utils.h"
namespace {
/*
A helper function used in RaggedShape3;
if both first and second are non-NULL, it will check if the context of them
is compatible or not and return that context if compatible;
if one of them is NULL, returns the other one's context.
*/
static k2::ContextPtr GetContext(const k2::Array1<int32_t> *first,
const k2::Array1<int32_t> *second) {
K2_CHECK(first != nullptr || second != nullptr)
<< "At least one of first and second must be non-NULL";
if (first == nullptr)
return second->Context();
else if (second == nullptr)
return first->Context();
else
return k2::GetContext(*first, *second);
}
} // namespace
namespace k2 {
RaggedShape RandomRaggedShape(bool set_row_ids, int32_t min_num_axes,
int32_t max_num_axes, int32_t min_num_elements,
int32_t max_num_elements) {
ContextPtr c = GetCpuContext();
K2_CHECK(min_num_axes >= 2 && max_num_axes >= min_num_axes &&
min_num_elements >= 0 && max_num_elements >= min_num_elements);
int32_t num_axes = RandInt(min_num_axes, max_num_axes);
int32_t num_elements = RandIntGeometric(min_num_elements, max_num_elements);
bool done_repeats = false;
std::vector<RaggedShapeLayer> axes(num_axes - 1);
for (int32_t axis = num_axes - 2; axis >= 0; axis--) {
// this axis will have row_ids of length num_elements and
// row_splits of length to be determined.
int32_t cur_row_split = 0;
std::vector<int32_t> row_splits_vec;
std::vector<int32_t> row_ids_vec;
row_splits_vec.push_back(cur_row_split);
// The reason for "|| RandInt(0, 2) == 0)" is so that even if there
// are no elements we can still potentially generate empty row-splits.
while (cur_row_split < num_elements || RandInt(0, 2) == 0) {
int32_t split_size = RandIntGeometric(0, num_elements - cur_row_split);
cur_row_split += split_size;
// sometimes we have a bunch of empty rows in a row (this will test out
// more of the code), so here we generate a bunch of empty rows, but we
// just do this only once (that's why we declare `done_repeats` here).
if (split_size == 0 && RandInt(0, 30) == 0 && !done_repeats) {
int32_t num_repeats = RandIntGeometric(1, 128);
row_splits_vec.insert(row_splits_vec.end(), num_repeats, cur_row_split);
// don't need to set `row_ids_vec` as there's no element.
done_repeats = true;
}
row_splits_vec.push_back(cur_row_split);
if (set_row_ids) {
int32_t cur_row = static_cast<int32_t>(row_splits_vec.size()) - 2;
row_ids_vec.insert(row_ids_vec.end(), split_size, cur_row);
}
}
axes[axis].row_splits = Array1<int32_t>(c, row_splits_vec);
if (set_row_ids) axes[axis].row_ids = Array1<int32_t>(c, row_ids_vec);
axes[axis].cached_tot_size = num_elements;
num_elements = axes[axis].row_splits.Dim() - 1;
}
// RaggedShape(axes, true) will check the returned RaggedShape for
// consistency.
return RaggedShape(axes, true);
}
RaggedShape RaggedShape2(Array1<int32_t> *row_splits, Array1<int32_t> *row_ids,
int32_t cached_tot_size) {
NVTX_RANGE(K2_FUNC);
K2_CHECK(row_splits != nullptr || row_ids != nullptr)
<< "At least one of row_splits and row_ids must be defined";
ContextPtr ctx = ::GetContext(row_splits, row_ids);
if (cached_tot_size != -1) {
if (row_ids != nullptr) K2_CHECK_EQ(cached_tot_size, row_ids->Dim());
if (row_splits != nullptr) {
// may be slow as it may copy memory from device to host
K2_DCHECK_EQ(cached_tot_size, row_splits->Back())
<< "Bad row splits is: " << *row_splits;
}
}
std::vector<RaggedShapeLayer> axes(1);
if (row_splits != nullptr) {
axes[0].row_splits = *row_splits;
} else {
// we need to work out row_splits as we always require row_splits is not
// empty for RaggedShape. Note here we suppose the last element in row_ids
// is num_rows - 1, i.e. there're no empty rows after row `row_ids[-1]`.
int32_t num_rows = row_ids->Dim() == 0 ? 0 : row_ids->Back() + 1;
Array1<int32_t> row_splits_array(ctx, num_rows + 1);
RowIdsToRowSplits(*row_ids, &row_splits_array);
axes[0].row_splits = row_splits_array;
}
if (row_ids != nullptr) axes[0].row_ids = *row_ids;
if (cached_tot_size == -1) {
cached_tot_size =
row_ids != nullptr ? row_ids->Dim() : axes[0].row_splits.Back();
}
axes[0].cached_tot_size = cached_tot_size;
// note below line will check if row_splits and row_ids are valid and agree
// with each other.
return RaggedShape(axes);
}
RaggedShape ComposeRaggedShapes(const RaggedShape &a, const RaggedShape &b) {
NVTX_RANGE(K2_FUNC);
if (a.NumElements() != b.Dim0()) {
K2_LOG(FATAL) << "ComposeRaggedShapes: shape mismatch: " << a.NumElements()
<< " vs. " << b.Dim0();
}
K2_CHECK(IsCompatible(a, b));
const auto &a_axes = a.Layers();
const auto &b_axes = b.Layers();
std::size_t a_size = a_axes.size(), b_size = b_axes.size();
std::vector<RaggedShapeLayer> axes;
axes.reserve(a_size + b_size);
for (std::size_t i = 0; i < a_size; ++i) axes.emplace_back(a_axes[i]);
for (std::size_t i = 0; i < b_size; ++i) axes.emplace_back(b_axes[i]);
bool validate = false;
return RaggedShape(axes, validate);
}
RaggedShape ComposeRaggedShapes3(const RaggedShape &a, const RaggedShape &b,
const RaggedShape &c) {
NVTX_RANGE(K2_FUNC);
if (a.NumElements() != b.Dim0()) {
K2_LOG(FATAL) << "ComposeRaggedShapes: shape mismatch: " << a.NumElements()
<< " vs. " << b.Dim0();
}
if (b.NumElements() != c.Dim0()) {
K2_LOG(FATAL) << "ComposeRaggedShapes: shape mismatch: " << b.NumElements()
<< " vs. " << c.Dim0();
}
K2_CHECK(IsCompatible(a, b));
K2_CHECK(IsCompatible(b, c));
const auto &a_axes = a.Layers();
const auto &b_axes = b.Layers();
const auto &c_axes = c.Layers();
std::size_t a_size = a_axes.size(), b_size = b_axes.size(),
c_size = c_axes.size();
std::vector<RaggedShapeLayer> axes;
axes.reserve(a_size + b_size + c_size);
for (std::size_t i = 0; i < a_size; ++i) axes.emplace_back(a_axes[i]);
for (std::size_t i = 0; i < b_size; ++i) axes.emplace_back(b_axes[i]);
for (std::size_t i = 0; i < c_size; ++i) axes.emplace_back(c_axes[i]);
bool validate = false;
return RaggedShape(axes, validate);
}
RaggedShape RaggedShape3(Array1<int32_t> *row_splits1,
Array1<int32_t> *row_ids1, int32_t cached_tot_size1,
Array1<int32_t> *row_splits2,
Array1<int32_t> *row_ids2, int32_t cached_tot_size2) {
NVTX_RANGE(K2_FUNC);
RaggedShape shape1 = RaggedShape2(row_splits1, row_ids1, cached_tot_size1);
Array1<int32_t> temp_array;
if (row_splits2 == nullptr) {
K2_CHECK_NE(row_ids2, nullptr)
<< "Either row-splits or row-ids must be defined";
temp_array = Array1<int32_t>(row_ids2->Context(), shape1.NumElements() + 1);
row_splits2 = &temp_array;
RowIdsToRowSplits(*row_ids2, row_splits2);
}
return ComposeRaggedShapes(
shape1, RaggedShape2(row_splits2, row_ids2, cached_tot_size2));
}
RaggedShape RaggedShape4(Array1<int32_t> *row_splits1,
Array1<int32_t> *row_ids1, int32_t cached_tot_size1,
Array1<int32_t> *row_splits2,
Array1<int32_t> *row_ids2, int32_t cached_tot_size2,
Array1<int32_t> *row_splits3,
Array1<int32_t> *row_ids3, int32_t cached_tot_size3) {
NVTX_RANGE(K2_FUNC);
RaggedShape shape12 = RaggedShape3(row_splits1, row_ids1, cached_tot_size1,
row_splits2, row_ids2, cached_tot_size2);
Array1<int32_t> temp_array;
if (row_splits3 == nullptr) {
K2_CHECK_NE(row_ids3, nullptr)
<< "Either row-splits or row-ids must be defined";
temp_array =
Array1<int32_t>(row_ids3->Context(), shape12.NumElements() + 1);
row_splits3 = &temp_array;
RowIdsToRowSplits(*row_ids3, row_splits3);
}
return ComposeRaggedShapes(
shape12, RaggedShape2(row_splits3, row_ids3, cached_tot_size3));
}
RaggedShape RaggedShapeFromTotSizes(ContextPtr c, int32_t num_axes,
const int32_t *tot_sizes) {
NVTX_RANGE(K2_FUNC);
K2_CHECK_GE(num_axes, 2);
std::vector<RaggedShapeLayer> axes(num_axes - 1);
// In future we might choose to allocate everything in one big array, to avoid
// multiple allocations, but for now just do it the simple way.
for (int32_t axis = 1; axis < num_axes; ++axis) {
axes[axis - 1].row_splits = Array1<int32_t>(c, tot_sizes[axis - 1] + 1);
axes[axis - 1].row_ids = Array1<int32_t>(c, tot_sizes[axis]);
axes[axis - 1].cached_tot_size = tot_sizes[axis];
}
// Not check here as we did not set the values of row_splits and row_ids
return RaggedShape(axes, false);
}
// See declaration in ragged.h for documentation of its purpose and interface.
RaggedShape Unsqueeze(const RaggedShape &src, int32_t axis) {
// If axis == 0, initial row_splits and row_ids will look like the following,
// if for example src.Dim0() was 5: [ 0 5 ], [ 0 0 0 0 0 ]. The other axes
// would be pushed forward.
//
// If 0 < axis <= src.NumAxes(), the inserted row_splits and row_ids would
// look like the following, if for instance the src.TotSize(axis) = 8:
// [ 0 1 2 3 4 5 6 7 8 ], [ 0 1 2 3 4 5 6 7 ].
//
// The reason why the code is different for axis == 0, is that in that case we
// are really making visible an "implicit" axis of the input `src`; we could
// call it axis 0 of the original RaggedShape. Imagine that "implicit" axis's
// row_splits and row_ids map respectively from an idx_minus1 -> idx0 and from
// an idx_0 to idx_minus1, where idx_minus1 is always 0 and 0 <= idx0 <
// Dim0().
NVTX_RANGE(K2_FUNC);
ContextPtr &c = src.Context();
K2_CHECK(axis >= 0 && axis <= src.NumAxes());
const std::vector<RaggedShapeLayer> &axes_in = src.Layers();
int32_t num_axes_in = src.NumAxes();
// Note: in RaggedShape, the vector of RaggedShapeLayer is of length
// num_axes - 1, so the output will have one more axis than the input.
std::vector<RaggedShapeLayer> axes_out(num_axes_in);
int32_t row_splits_dim, row_ids_dim;
Array1<int32_t> mem;
if (axis == 0) {
row_splits_dim = 2; // e.g. [ 0 5 ]
row_ids_dim = src.Dim0(); // e.g. [ 0 0 0 0 0 ]
mem = Array1<int32_t>(c, row_splits_dim + row_ids_dim);
int32_t *mem_data = mem.Data();
K2_EVAL(
c, mem.Dim(), lambda_set_mem, (int32_t i)->void {
if (i == 1)
mem_data[i] = row_ids_dim;
else
mem_data[i] = 0;
});
} else {
int32_t tot_size = src.TotSize(axis);
row_splits_dim = tot_size + 1;
row_ids_dim = tot_size;
mem = Array1<int32_t>(c, row_splits_dim + row_ids_dim);
int32_t *mem_data = mem.Data();
K2_EVAL(
c, mem.Dim(), lambda_set_mem2,
(int32_t i)->void { mem_data[i] = i % (tot_size + 1); });
}
axes_out[axis].row_splits = mem.Range(0, row_splits_dim);
axes_out[axis].row_ids = mem.Range(row_splits_dim, row_ids_dim);
axes_out[axis].cached_tot_size = row_ids_dim;
for (int32_t i = 0; i < axis; ++i) axes_out[i] = axes_in[i];
// Note: the returned array has `num_axes_in + 1` axes, so its
// array of RaggedShapeLayer is of length `num_axes_in`.
for (int32_t i = axis + 1; i < num_axes_in; ++i) axes_out[i] = axes_in[i - 1];
return RaggedShape(axes_out);
}
std::vector<RaggedShape> UnsqueezeParallel(int32_t num_srcs, RaggedShape **src,
int32_t axis) {
NVTX_RANGE(K2_FUNC);
K2_CHECK_EQ(axis, 0);
std::vector<RaggedShape> ans;
if (num_srcs == 0) return ans;
ans.reserve(num_srcs);
ContextPtr &c = src[0]->Context();
std::vector<int32_t> all_row_splits_vec(num_srcs * 2);
int32_t max_dim = 0;
// all_row_splits_vec will contain [ 0 d0 0 d1 0 d2 .. ]
// where d0 == src[0]->Dim0(), d1 == src[1]->Dim0()..
for (int32_t i = 0; i < num_srcs; ++i) {
int32_t this_dim0 = src[i]->Dim0();
if (this_dim0 > max_dim) max_dim = this_dim0;
all_row_splits_vec[i * 2] = 0;
all_row_splits_vec[i * 2 + 1] = this_dim0;
}
Array1<int32_t> all_row_splits(c, all_row_splits_vec);
Array1<int32_t> all_row_ids(c, max_dim, 0);
for (int32_t i = 0; i < num_srcs; ++i) {
int32_t num_axes = src[i]->NumAxes();
std::vector<RaggedShapeLayer> axes;
axes.reserve(num_axes); // note, the size of the `layers` of a RaggedShape
// is its NumAxes() - 1.
axes.resize(1);
int32_t this_old_dim0 = all_row_splits_vec[i * 2 + 1];
axes[0].row_splits = all_row_splits.Range(i * 2, 2);
axes[0].row_ids = all_row_ids.Range(0, this_old_dim0);
axes[0].cached_tot_size = this_old_dim0;
axes.insert(axes.end(), src[i]->Layers().begin(), src[i]->Layers().end());
ans.emplace_back(std::move(axes));
}
return ans;
}
/*
Internal function used in Index(), which gets certain arrays used internally.
@param [in] src Source shape to be indexed
@param [in] new2old Array of indexes into axis 0 of src; elements
equal to -1 will be interpreted as referring to
an empty list.
@param [out] old_offsets Will be set to new Array2 with dimension
(src.NumAxes(), new2old.Dim()), whose (i,j)'th
element contains the offset into axis i of `src`
where the slice of `src` with index0 (i.e. index
into 0'th-axis of `src`) equal to `new2old[j]`
begins.
@param [out] new_offsets Will be set to new Array2 with dimension
(src.NumAxes(), new2old.Dim()+1), whose (i,j)'th
element contains the offset into axis i of `ans`
where the data in `ans` corresponding to
index j (i.e. index j into axis 0 of `ans`) begins.
Note: `ans` is the result of Index(), with
ans.Dim0() == new2old.Dim().
*/
inline void GetOldAndNewOffsets(RaggedShape &src,
const Array1<int32_t> &new2old,
Array2<int32_t> *old_offsets,
Array2<int32_t> *new_offsets) {
NVTX_RANGE(K2_FUNC);
K2_CHECK_GT(src.NumAxes(), 1);
ContextPtr &c = src.Context();
int32_t num_axes = src.NumAxes(), ans_dim0 = new2old.Dim();
// max 5 layers.
RowSplitsAccessor<5> row_splits_acc(src);
const int32_t *new2old_data = new2old.Data();
*old_offsets = Array2<int32_t>(c, num_axes, ans_dim0);
*new_offsets = Array2<int32_t>(c, num_axes, ans_dim0 + 1);
auto old_offsets_acc = old_offsets->Accessor(),
new_offsets_acc = new_offsets->Accessor();
// Set old_offsets; and for now, set new_offsets to the corresponding
// sizes of the output slices.
K2_EVAL(
c, ans_dim0, lambda_set_offsets, (int32_t i)->void {
// 0 <= i < ans_dim0
int32_t old_offset = new2old_data[i],
old_offset_next = old_offset + 1,
offset_diff = 1;
// The following is a special case that interprets -1 as referring to an
// empty list. In this case, old_offset == old_offset_next == 0.
// The specific value 0 is not necessary; they could be equal
// and have any value in [0, src.Dim0() - 1] and still refer to
// the empty list.
if (old_offset == -1)
old_offset = 0;
for (int32_t axis = 0;; axis++) {
old_offsets_acc(axis, i) = old_offset;
// Below, 'new_offsets_acc' currently contains the size rather
// than the offset; we need to do exclusive-sum.
new_offsets_acc(axis, i) = offset_diff;
if (axis + 1 == num_axes) return;
old_offset = row_splits_acc(axis)[old_offset];
old_offset_next = row_splits_acc(axis)[old_offset_next];
offset_diff = old_offset_next - old_offset;
}
});
ExclusiveSum(*new_offsets, new_offsets);
}
static RaggedShape IndexAxis0(RaggedShape &src, const Array1<int32_t> &new2old,
Array1<int32_t> *elem_indexes /*=nullptr*/) {
NVTX_RANGE(K2_FUNC);
ContextPtr &c = src.Context();
bool is_cpu = (c->GetDeviceType() == kCpu);
K2_CHECK(IsCompatible(src, new2old));
int32_t num_axes = src.NumAxes(), src_dim0 = src.Dim0(),
ans_dim0 = new2old.Dim();
if (ans_dim0 == 0) {
if (elem_indexes) *elem_indexes = Array1<int32_t>(c, 0);
return EmptyRaggedShape(c, num_axes);
}
Array2<int32_t> old_offsets, // num_axes by ans_dim0
new_offsets; // num_axes by (ans_dim0 + 1).
GetOldAndNewOffsets(src, new2old, &old_offsets, &new_offsets);
// tot_sizes_out is of dimension (num_axes), tot_sizes_out[i] is
// ans.TotSize(i)
Array1<int32_t> tot_sizes_out =
Array1<int32_t>(new_offsets.Col(ans_dim0)).To(GetCpuContext());
int32_t *tot_sizes_out_cpu_data = tot_sizes_out.Data();
if (elem_indexes)
*elem_indexes = Array1<int32_t>(c, tot_sizes_out_cpu_data[num_axes - 1]);
RaggedShape ans =
RaggedShapeFromTotSizes(c, num_axes, tot_sizes_out_cpu_data);
auto old_offsets_acc = old_offsets.Accessor(),
new_offsets_acc = new_offsets.Accessor();
for (int32_t axis = 1; axis < num_axes; axis++) {
// we are not creating the actual row_ids here, except for axis 1; we are
// creating "composed row_ids" which map to the index on axis 0.
Array1<int32_t> row_ids = ans.RowIds(axis);
RowSplitsToRowIds(new_offsets.Row(axis), &row_ids);
}
ans.Layers()[0].row_splits = new_offsets.Row(1);
// Caution: e.g. old_row_splits_acc(i) == src.RowSplits(i+1).
RowSplitsAccessor<5> old_row_splits_acc(src),
new_row_splits_acc(ans);
RowIdsAccessor<5> old_row_ids_acc(src),
new_row_ids_acc(ans);
SmallVec<int32_t, 6> tot_sizes;
K2_CHECK(num_axes <= 6);
int32_t max_tot_size = 0;
for (int32_t i = 0; i < num_axes; i++) {
tot_sizes.data[i] = tot_sizes_out_cpu_data[i];
max_tot_size = std::max<int32_t>(max_tot_size,
tot_sizes.data[i]);
}
int32_t *elem_indexes_data = (elem_indexes != nullptr ?
elem_indexes->Data() : nullptr);
// Note, the first row_splits vector was set above, ans.Layers()[0].row_splits
// = new_offsets.Row(1).
auto lambda_set_row_splits_and_ids = [=] __host__ __device__(
int32_t axis, int32_t i) -> void {
axis++; // make it one-based.
int32_t tot_size = tot_sizes(axis); // == new_offsets_acc(axis, ans_dim0);
if (i > tot_size)
return;
int32_t *composed_row_ids_data = new_row_ids_acc(axis - 1);
int32_t ans_idx0 = (i == tot_size ? ans_dim0 :
composed_row_ids_data[i]),
job_begin = new_offsets_acc(axis, ans_idx0),
job_this_idx0 = i - job_begin;
K2_CHECK_GE(job_this_idx0, 0);
int32_t row_split_value = 0, new_next_offset = 0;
if (axis + 1 < num_axes)
new_next_offset = new_offsets_acc(axis + 1, ans_idx0);
if (i < tot_size) {
// "prev" means for axis - 1
int32_t new_prev_offset = new_offsets_acc(axis - 1, ans_idx0),
old_prev_offset = old_offsets_acc(axis - 1, ans_idx0),
old_offset = old_offsets_acc(axis, ans_idx0),
old_idx = old_offset + job_this_idx0;
if (axis != 1) {
// Write row-ids.
// Actually doing this for axis == 1 is harmless, but unnecessary, as it
// would write back the same values that were already there. We avoid
// the memory access.
// this_new_row_ids = new_row_ids_acc(axis - 1);
int32_t *this_new_row_ids = composed_row_ids_data;
const int32_t *this_old_row_ids = old_row_ids_acc(axis - 1);
int32_t old_row_id = this_old_row_ids[old_idx],
new_row_id = old_row_id + new_prev_offset - old_prev_offset;
this_new_row_ids[i] = new_row_id;
}
if (elem_indexes_data != nullptr && axis == num_axes - 1)
elem_indexes_data[i] = old_idx;
if (axis + 1 < num_axes) {
int32_t old_next_offset = old_offsets_acc(axis + 1, ans_idx0),
next_offset_diff = new_next_offset - old_next_offset;
const int32_t *old_row_splits_data = old_row_splits_acc(axis);
row_split_value = next_offset_diff + old_row_splits_data[old_idx];
}
} else {
row_split_value = new_next_offset;
}
if (axis + 1 < num_axes) {
int32_t *new_row_splits_data = new_row_splits_acc(axis);
new_row_splits_data[i] = row_split_value;
}
};
constexpr int32_t cutoff = 50000;
if (c->GetDeviceType() == kCpu) {
for (int32_t axis = 0; axis < num_axes - 1; axis++) {
int32_t this_size = tot_sizes(axis + 1);
for (int32_t i = 0; i <= this_size; i++)
lambda_set_row_splits_and_ids(axis, i);
}
} else if (max_tot_size * (num_axes - 1) < cutoff) {
Eval2Device(c, num_axes - 1, max_tot_size + 1,
lambda_set_row_splits_and_ids);
} else {
// Loop in the kernel rather than submitting an excessive number of threads.
auto lambda_loop = [=] __device__(int32_t i) {
for (int32_t axis = 0; axis < num_axes - 1; axis++) {
lambda_set_row_splits_and_ids(axis, i);
}
};
EvalDevice(c, max_tot_size + 1, lambda_loop);
}
#if !defined(NDEBUG)
ans.Check();
#endif
return ans;
}
RaggedShape Index(RaggedShape &src, int32_t axis,
const Array1<int32_t> &indexes,
Array1<int32_t> *elem_indexes /*=nullptr*/) {
NVTX_RANGE(K2_FUNC);
int32_t num_axes = src.NumAxes();
K2_CHECK_LT(static_cast<uint32_t>(axis), static_cast<uint32_t>(num_axes));
if (axis == 0) {
return IndexAxis0(src, indexes, elem_indexes);
} else if (axis == src.NumAxes() - 1) {
// This code is related to SubsampleRaggedShape(). `indexes` corresponds
// to `new2old`.
Array1<int32_t> last_row_ids = src.RowIds(num_axes - 1)[indexes];
#ifndef NDEBUG
if (!IsMonotonic(last_row_ids)) {
K2_LOG(FATAL) << "Invalid indexes used when indexing RaggedShape";
}
#endif
Array1<int32_t> last_row_splits(last_row_ids.Context(),
src.TotSize(num_axes - 2) + 1);
RowIdsToRowSplits(last_row_ids, &last_row_splits);
if (elem_indexes)
*elem_indexes = indexes;
std::vector<RaggedShapeLayer> axes = src.Layers();
axes.back().row_splits = last_row_splits;
axes.back().row_ids = last_row_ids;
axes.back().cached_tot_size = last_row_ids.Dim();
// TODO: disable checking by changing true to false.
return RaggedShape(axes, true);
} else {
RaggedShape top, bottom;
DecomposeRaggedShape(src, axis, &top, &bottom);
RaggedShape top_indexed = Index(top, axis, indexes, nullptr),
bottom_indexed = IndexAxis0(bottom, indexes, elem_indexes);
return ComposeRaggedShapes(top_indexed, bottom_indexed);
}
}
// returns array of dim (src[0]->NumAxes() + 1) by (num_srcs + 1),
// see documentation in header.
Array2<int32_t> GetOffsets(int32_t num_srcs, RaggedShape **src) {
NVTX_RANGE(K2_FUNC);
K2_CHECK_GT(num_srcs, 0);
int32_t num_axes_in = src[0]->NumAxes();
ContextPtr &ctx = src[0]->Context();
Array2<int32_t> src_offsets(GetCpuContext(), num_axes_in + 1, num_srcs + 1);
int32_t *src_offsets_data = src_offsets.Data();
int32_t src_offsets_stride0 = src_offsets.ElemStride0();
// Check if they have same num-axes and compatible context
for (int32_t i = 1; i < num_srcs; ++i) {
K2_CHECK_EQ(src[i]->NumAxes(), num_axes_in);
K2_CHECK(ctx->IsCompatible(*src[i]->Context()));
}
for (int32_t axis = 0; axis <= num_axes_in; ++axis) {
int32_t sum = 0;
for (int32_t i = 0; i <= num_srcs; ++i) { // i is the column
src_offsets_data[axis * src_offsets_stride0 + i] = sum;
if (i < num_srcs) {
sum += (axis == 0 ? 1 : src[i]->TotSize(axis - 1));
}
}
}
return src_offsets;
}
void GetRowInfo(RaggedShape &src, Array1<int32_t *> *row_splits,
Array1<int32_t *> *row_ids) {
NVTX_RANGE(K2_FUNC);
int32_t axes = src.NumAxes();
K2_CHECK_GE(axes, 2);
src.Populate();
std::vector<int32_t *> row_splits_ptrs(axes - 1);
std::vector<int32_t *> row_ids_ptrs(axes - 1);
for (int32_t i = 1; i != axes; ++i) {
row_splits_ptrs[i - 1] = src.RowSplits(i).Data();
row_ids_ptrs[i - 1] = src.RowIds(i).Data();
}
ContextPtr ctx = src.Context();
*row_splits = Array1<int32_t *>(ctx, row_splits_ptrs);
*row_ids = Array1<int32_t *>(ctx, row_ids_ptrs);
}
void GetRowInfoMulti(int32_t num_srcs, RaggedShape **src,
Array2<int32_t *> *row_splits,
Array2<int32_t *> *row_ids) {
NVTX_RANGE(K2_FUNC);
K2_CHECK_GT(num_srcs, 0);
int32_t num_axes_in = src[0]->NumAxes();
K2_CHECK_GE(num_axes_in, 2);
ContextPtr ctx = src[0]->Context();
// check if they have same num-axes and compatible context
for (int32_t i = 1; i < num_srcs; ++i) {
K2_CHECK_EQ(src[i]->NumAxes(), num_axes_in);
K2_CHECK(ctx->IsCompatible(*src[i]->Context()));
}
Array2<int32_t *> row_splits_ptrs(GetCpuContext(), num_axes_in - 1, num_srcs);
Array2<int32_t *> row_ids_ptrs(GetCpuContext(), num_axes_in - 1, num_srcs);
int32_t **splits_ptr_data = row_splits_ptrs.Data();
int32_t **ids_ptr_data = row_ids_ptrs.Data();
int32_t stride0 = row_splits_ptrs.ElemStride0();
K2_CHECK_EQ(stride0, row_ids_ptrs.ElemStride0());
for (int32_t axis = 0; axis != num_axes_in - 1; ++axis) {
for (int32_t i = 0; i != num_srcs; ++i) {
splits_ptr_data[axis * stride0 + i] = src[i]->RowSplits(axis + 1).Data();
ids_ptr_data[axis * stride0 + i] = src[i]->RowIds(axis + 1).Data();
}
}
*row_splits = row_splits_ptrs.To(ctx);
*row_ids = row_ids_ptrs.To(ctx);
}
static RaggedShape StackAxis0(int32_t num_srcs, RaggedShape **src,
Array1<uint32_t> *merge_map /* == nullptr*/) {
NVTX_RANGE(K2_FUNC);
if (num_srcs == 1) {
if (merge_map)
*merge_map =
Arange<uint32_t>(src[0]->Context(), 0, src[0]->NumElements());
RaggedShape top_layer = TrivialShape(src[0]->Context(), src[0]->Dim0());
return ComposeRaggedShapes(top_layer, **src);
}
// We can't handle num_srcs == 0 because we won't have a context object.
K2_CHECK_GT(num_srcs, 1);
int32_t num_axes_in = src[0]->NumAxes(),
num_axes_out = num_axes_in + 1;
ContextPtr c = src[0]->Context();
bool is_cpu = (c->GetDeviceType() == kCpu);
// Check if they have same num-axes and compatible context
for (int32_t i = 1; i < num_srcs; ++i) {
K2_CHECK_EQ(num_axes_in, src[i]->NumAxes());
K2_CHECK(IsCompatible(*src[0], *src[i]));
}
// `offsets` will be on CPU for now.
// It shape is (num_axes_in + 1 == num_axes_out, num_srcs + 1).
Array2<int32_t> offsets = GetOffsets(num_srcs, src);
auto offsets_acc = offsets.Accessor();
SmallVec<int32_t, 6> tot_sizes_out;
K2_CHECK(num_axes_out <= 6);
int32_t max_tot_size = 0;
for (int32_t axis = 0; axis < num_axes_out; axis++) {
tot_sizes_out.data[axis] = offsets_acc(axis, num_srcs);
max_tot_size = std::max<int32_t>(max_tot_size,
tot_sizes_out.data[axis]);
}
RaggedShape ans = RaggedShapeFromTotSizes(c, num_axes_out,
tot_sizes_out.data);
// src_row_splits and src_row_ids are of dim num_axes_in-1 by num_srcs.
Array2<int32_t *> src_row_splits, src_row_ids;
GetRowInfoMulti(num_srcs, src, &src_row_splits, &src_row_ids);
auto src_row_splits_acc = src_row_splits.Accessor(),
src_row_ids_acc = src_row_ids.Accessor();
offsets = offsets.To(c);
offsets_acc = offsets.Accessor();
for (int32_t axis = 1; axis < num_axes_out; axis++) {
// we are not creating the actual row_ids here, except for axis 1; we are
// creating "composed row_ids" which map to the index on axis 0.
Array1<int32_t> row_ids = ans.RowIds(axis);
RowSplitsToRowIds(offsets.Row(axis), &row_ids);
}
ans.Layers()[0].row_splits = offsets.Row(1);
// Caution: e.g. old_row_splits_acc(i) == src.RowSplits(i+1).
RowSplitsAccessor<5> new_row_splits_acc(ans);
RowIdsAccessor<5> new_row_ids_acc(ans);
uint32_t *merge_map_data;
if (merge_map != nullptr) {
*merge_map = Array1<uint32_t>(c, tot_sizes_out.data[num_axes_out - 1]);
merge_map_data = merge_map->Data();
} else {
merge_map_data = nullptr;
}
// Note, the first row_splits vector was set above, ans.Layers()[0].row_splits
// = new_offsets.Row(1).
auto lambda_set_row_splits_and_ids = [=] __host__ __device__(
int32_t axis, int32_t i) -> void {
++axis; // We want this to be called starting with axis == 1, but Eval2
// doesn't suppor that.
// At this point, 1 < axis < num_axes_out.
// This kernel will be writing one or both of:
// the row-splits for output-layer==`axis`/input-layer==`axis-1`,
// the row-ids for output-layer=`axis-1`/input-layer==`axis-2`.
int32_t tot_size = tot_sizes_out(axis); // == offsets_acc(axis, num_srcs);
if (i > tot_size)
return;
int32_t *composed_row_ids_data = new_row_ids_acc(axis - 1);
int32_t ans_idx0 =
(i == tot_size
? num_srcs
: composed_row_ids_data[i]), // note: ans_idx0 == src_idx.
job_begin = offsets_acc(axis, ans_idx0), job_this_idx0 = i - job_begin;
K2_CHECK_GE(job_this_idx0, 0);
int32_t row_split_value = 0, new_next_offset = 0;
uint32_t *merge_map_data_local = nullptr;
if (axis + 1 < num_axes_out) {
new_next_offset = offsets_acc(axis + 1, ans_idx0);
} else {
merge_map_data_local = merge_map_data;
}
if (i < tot_size) {
// "prev" means for axis - 1
int32_t new_prev_offset = offsets_acc(axis - 1, ans_idx0);
if (axis != 1) {
// Write row-ids.
// this_new_row_ids = new_row_ids_acc(axis - 1);
int32_t *this_new_row_ids = composed_row_ids_data;
const int32_t *this_src_row_ids = src_row_ids_acc(axis - 2, ans_idx0);
int32_t old_row_id = this_src_row_ids[job_this_idx0],
new_row_id = old_row_id + new_prev_offset;
this_new_row_ids[i] = new_row_id;
}
if (merge_map_data_local != nullptr) {
merge_map_data_local[i] = ans_idx0 + num_srcs * job_this_idx0;
}
if (axis + 1 < num_axes_out) {
const int32_t *src_row_splits_data = src_row_splits_acc(axis - 1,
ans_idx0);
int32_t old_row_split = src_row_splits_data[job_this_idx0];
row_split_value = new_next_offset + old_row_split;
}
} else {
row_split_value = new_next_offset;
}
if (axis + 1 < num_axes_out) {
int32_t *new_row_splits_data = new_row_splits_acc(axis);
new_row_splits_data[i] = row_split_value;
}
};
constexpr int32_t cutoff = 50000;
if (c->GetDeviceType() == kCpu) {
for (int32_t axis = 0; axis < num_axes_out - 1; axis++) {
int32_t this_size = tot_sizes_out(axis + 1);
for (int32_t i = 0; i <= this_size; i++)
lambda_set_row_splits_and_ids(axis, i);
}
} else if (max_tot_size * (num_axes_out - 1) < cutoff) {
Eval2Device(c, num_axes_out - 1, max_tot_size + 1,
lambda_set_row_splits_and_ids);
} else {
// Loop in the kernel rather than submitting an excessive number of threads.
auto lambda_loop = [=] __device__(int32_t i) {
for (int32_t axis = 0; axis < num_axes_out - 1; axis++) {
lambda_set_row_splits_and_ids(axis, i);
}
};
EvalDevice(c, max_tot_size + 1, lambda_loop);
}
#if !defined(NDEBUG)
ans.Check();
#endif
return ans;
}
RaggedShape Cat(int32_t axis, int32_t num_srcs, RaggedShape **src,
Array1<uint32_t> *merge_map /* == nullptr*/) {
NVTX_RANGE(K2_FUNC);
K2_CHECK_GT(num_srcs, 0);
if (axis == 0) {
RaggedShape temp = StackAxis0(num_srcs, src, merge_map);
std::vector<RaggedShapeLayer> ans_layers(
temp.Layers().begin() + 1, temp.Layers().end());
return RaggedShape(ans_layers, false);
}
K2_CHECK_LT(static_cast<uint32_t>(axis),
static_cast<uint32_t>(src[0]->NumAxes()));
int32_t num_axes = src[0]->NumAxes();
std::vector<RaggedShapeLayer> ans_layers(num_axes - 1);
// If axis >= 2, some layers of `src` will pass through unchanged (we should
// check that they are identical across all sources).
for (int32_t l = 0; l + 1 < axis; l++) {
CheckLayerEqual(l, num_srcs, src);
ans_layers[l] = src[0]->Layers()[l];
}
Array1<uint32_t> merge_map_local;
Array1<uint32_t> *this_m =
(axis + 1 == num_axes ? merge_map : &merge_map_local);
RaggedShape s = IntersperseRaggedLayer(axis - 1, num_srcs, src, this_m),
t = SubsampleRaggedLayer(s, 0, num_srcs);
ans_layers[axis - 1] = t.Layers()[0];
for (int32_t l = axis; l + 1 < num_axes; l++) {
Array1<uint32_t> merge_map_next;
Array1<uint32_t> *this_m =
(l + 2 == num_axes ? merge_map : &merge_map_next);
RaggedShape r = MergeRaggedLayer(l, num_srcs, src, merge_map_local, this_m);
ans_layers[l] = r.Layers()[0];
merge_map_local = merge_map_next;
}
// TODO(dan) after this is debugged: add ", false".
return RaggedShape(ans_layers);
}
RaggedShape RemoveAxis(RaggedShape &src, int32_t axis) {
NVTX_RANGE(K2_FUNC);
K2_CHECK_GT(src.NumAxes(), 2);
K2_CHECK(axis >= 0 && axis < src.NumAxes());
// note, `axes_in` is of dim src.NumAxes() - 1.
// Also note: axes_in[i] pertains to the relationship between
// axes i and i+1 in the source.
src.Populate();
const std::vector<RaggedShapeLayer> &axes_in = src.Layers();
std::vector<RaggedShapeLayer> axes_out(axes_in.size() - 1);
int32_t axes_out_size = static_cast<int32_t>(axes_out.size());
for (int32_t i = 0; i < axis - 1; ++i) axes_out[i] = axes_in[i];
if (axis > 0 && axis + 1 < src.NumAxes()) {
axes_out[axis - 1].row_ids =
axes_in[axis - 1].row_ids[axes_in[axis].row_ids];
axes_out[axis - 1].row_splits =
axes_in[axis].row_splits[axes_in[axis - 1].row_splits];
axes_out[axis - 1].cached_tot_size = axes_out[axis - 1].row_ids.Dim();
}
for (int32_t i = axis; i < axes_out_size; ++i) axes_out[i] = axes_in[i + 1];
return RaggedShape(axes_out);
}
RaggedShape MakeTransposable(RaggedShape &src) {
NVTX_RANGE(K2_FUNC);
K2_CHECK_GE(src.NumAxes(), 2);
int32_t src_dim0 = src.Dim0(), src_tot_size1 = src.TotSize(1);
if (src_dim0 <= 1) return src;
ContextPtr c = src.Context();
int32_t num_axes = src.NumAxes();
int32_t max_size = src.MaxSize(1);
if (max_size <= 0) return src;
int32_t ans_tot_size1 = max_size * src_dim0;
src.Populate();
const std::vector<RaggedShapeLayer> &axes_in = src.Layers();
std::vector<RaggedShapeLayer> axes_out(num_axes - 1);
const int32_t *src_row_splits1_data = src.RowSplits(1).Data();
const int32_t *src_row_ids1_data = src.RowIds(1).Data();
{
ParallelRunner pr(c);
RaggedShapeLayer &axis1_shape = axes_out[0];
{
// set ans.RowSplits(1);
With w(pr.NewStream());
axis1_shape.row_splits = Range(c, src_dim0 + 1, 0, max_size);
}
{
// set ans.RowIds(1);
With w(pr.NewStream());
axis1_shape.row_ids = Array1<int32_t>(c, ans_tot_size1);
int32_t *row_ids1_data = axis1_shape.row_ids.Data();
axis1_shape.cached_tot_size = ans_tot_size1;
K2_EVAL(
c, ans_tot_size1, lambda_set_row_ids1,
(int32_t i)->void { row_ids1_data[i] = i / max_size; });
}
if (num_axes > 2) {
RaggedShapeLayer &axis2_shape = axes_out[1];
const int32_t *src_row_splits2_data = src.RowSplits(2).Data();
{
// set ans.RowSplits(2);
With w(pr.NewStream());
axis2_shape.cached_tot_size = src.TotSize(2);
axis2_shape.row_splits = Array1<int32_t>(c, ans_tot_size1 + 1);
int32_t *ans_row_splits2_data = axis2_shape.row_splits.Data();
K2_EVAL(
c, ans_tot_size1 + 1, lambda_set_row_splits2,
(int32_t idx01)->void {
if (idx01 == ans_tot_size1) {
ans_row_splits2_data[idx01] =
src_row_splits2_data[src_tot_size1];
return;
}
int32_t idx0 = idx01 / max_size, idx1 = idx01 % max_size;
int32_t idx0x = src_row_splits1_data[idx0],
idx0x_next = src_row_splits1_data[idx0 + 1];
int32_t num_elems_this_row = idx0x_next - idx0x;
if (idx1 < num_elems_this_row)
ans_row_splits2_data[idx01] =
src_row_splits2_data[idx0x + idx1];
else
ans_row_splits2_data[idx01] =
src_row_splits2_data[idx0x_next]; // append empty row
});
}
{
// set ans.RowIds(2);
With w(pr.NewStream());
int32_t tot_size2 = src.TotSize(2);
axis2_shape.row_ids = Array1<int32_t>(c, tot_size2);
int32_t *ans_row_ids2_data = axis2_shape.row_ids.Data();
const int32_t *src_row_ids2_data = src.RowIds(2).Data();
K2_EVAL(
c, tot_size2, lambda_set_row_ids2, (int32_t idx012)->void {
int32_t src_idx01 = src_row_ids2_data[idx012];
int32_t src_idx0 = src_row_ids1_data[src_idx01];
int32_t src_idx1 = src_idx01 - src_row_splits1_data[src_idx0];
ans_row_ids2_data[idx012] = (src_idx0 * max_size) + src_idx1;
});
}
}
}
// copy left row_splits and row_ids;
for (int32_t i = 2; i < num_axes - 1; ++i) axes_out[i] = axes_in[i];
return RaggedShape(axes_out);
}
// transpose axes 0 and 1.
RaggedShape Transpose(RaggedShape &src, Array1<int32_t> *value_indexes) {
NVTX_RANGE(K2_FUNC);
K2_CHECK_GT(src.NumAxes(), 2);
ContextPtr c = src.Context();