-
Notifications
You must be signed in to change notification settings - Fork 42
/
utils.cpp
2510 lines (2224 loc) · 83.3 KB
/
utils.cpp
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
// clang-format off
/*
* SPDX-FileCopyrightText: Copyright (c) 2023-present NVIDIA CORPORATION & AFFILIATES.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
// clang-format on
#include <scheduler/registry.h>
#include <scheduler/utils.h>
#include <scheduler/vectorize_helper.h>
#include <contiguity.h>
#include <expr_evaluator.h>
#include <instrumentation.h>
#include <ir/utils.h>
#include <multidevice/utils.h>
#include <ops/all_ops.h>
#include <root_domain_map.h>
#include <scheduler/mma_utils.h>
#include <transform_iter.h>
#include <transform_replay.h>
#include <algorithm>
#include <queue>
namespace nvfuser {
namespace scheduler_utils {
// Returns number of "valid" dimensions. e.g. if tv has
// [I1, R2, I3, I4, R3{1}]
// where R3{1} is in dont_merge, resulting domain should be:
// [I1, I3*I4, R2, R3{1}] with return value 3
//
// if tv has
// [R1, I2, R3, I4, R4, R5{1}, R6{1}]
// where R5{1} and R6{1} are in dont_merge, resulting domain should be:
// [I2*I4, R1*R3, R4, R5{1}, R6{1}]
// with return value 3
size_t merge_3d(TensorView* tv) {
bool active_is_reduction = false;
bool first_dim = true;
int prev_i = -1;
for (int i = static_cast<int>(tv->nDims()) - 1; i >= 0; i--) {
if (first_dim) {
active_is_reduction = tv->axis(i)->isReduction();
prev_i = i;
first_dim = false;
} else {
if (tv->axis(i)->isReduction() != active_is_reduction) {
break;
}
tv->merge(i, prev_i);
prev_i = i;
}
}
if (prev_i == -1) {
// Zero dimensional
return 0;
}
// put inner most dimension as last dimension
tv->reorder({{prev_i, -1}});
active_is_reduction = false;
first_dim = true;
prev_i = -1;
for (int i = static_cast<int>(tv->nDims()) - 2; i >= 0; i--) {
auto id = tv->axis(i);
if (first_dim) {
active_is_reduction = id->isReduction();
prev_i = i;
first_dim = false;
} else if (id->isReduction() == active_is_reduction) {
tv->merge(i, prev_i);
prev_i = i;
}
}
// put second dimension as second to last dimension
if (prev_i == -1) {
// One dimensional, put merged dimension as first
tv->reorder({{-1, 0}});
return 1;
} else {
// put new dimension as second to last
tv->reorder({{prev_i, -2}});
}
active_is_reduction = false;
first_dim = true;
prev_i = -1;
for (int i = static_cast<int>(tv->nDims()) - 3; i >= 0; i--) {
if (first_dim) {
active_is_reduction = tv->axis(i)->isReduction();
prev_i = i;
first_dim = false;
} else if (tv->axis(i)->isReduction() == active_is_reduction) {
tv->merge(i, prev_i);
prev_i = i;
}
}
// put third dimension as second to last dimension
if (prev_i == -1) {
// Two dimensional, put merged dimensions first
tv->reorder({{-1, 0}, {-2, 1}});
// [outer, inner, dont_merge...]
if (tv->axis(0)->isReduction()) {
// put reductions as second axis
tv->reorder({{0, 1}, {1, 0}});
}
return 2;
} else {
// put new dimension as third to last
tv->reorder({{prev_i, -3}});
// Stable sort to have iteration domains first, then reduction
if (tv->axis(0)->isReduction() && !tv->axis(1)->isReduction()) {
tv->reorder({{0, 1}, {1, 0}});
}
if (tv->axis(1)->isReduction() && !tv->axis(2)->isReduction()) {
tv->reorder({{1, 2}, {2, 1}});
}
if (tv->axis(0)->isReduction() && !tv->axis(1)->isReduction()) {
tv->reorder({{0, 1}, {1, 0}});
}
return 3;
}
}
void splitDims(
TensorView* tv,
std::vector<std::pair<int64_t, int64_t>> to_split, // (dim, size)
std::vector<int64_t>& to_update) {
std::stable_sort(
to_split.begin(),
to_split.end(),
[](const std::pair<int64_t, int64_t>& p1,
const std::pair<int64_t, int64_t>& p2) {
return p1.first < p2.first;
});
int64_t dim_offset = 0;
int64_t pending_dim_offset = 0;
int64_t prev_dim = 0;
for (auto entry : to_split) {
int64_t dim = entry.first;
int64_t size = entry.second;
if (dim != prev_dim) {
dim_offset += pending_dim_offset;
pending_dim_offset = 0;
}
int64_t actual_dim = dim_offset + dim;
tv->split(actual_dim, size);
pending_dim_offset++;
for (auto& i : to_update) {
if (i > actual_dim) {
i++;
}
}
prev_dim = dim;
}
}
std::optional<int64_t> mergeDims(
TensorView* tv,
std::vector<int64_t> to_merge,
std::vector<int64_t>& to_update) {
if (to_merge.empty()) {
return std::nullopt;
}
if (to_merge.size() == 1) {
return to_merge[0];
}
auto inner = to_merge[0];
// NOTE: The merge is done in the order of `to_merge`, assuming going from
// inner to outer dimensions. We want the merged IterDomain to be like:
//
// tv->axis(to_merge[i-1])*tv->axis(to_merge[i-2])*...*tv->axis(to_merge[0])
//
// Otherwise this could results in misaligned memory access due to indexing.
// This is because we compute vectorization width before applying scheduling
// transformations.
for (int64_t i = 1; i < (int64_t)to_merge.size(); i++) {
auto outer = to_merge[i];
// If outer > inner, the merge order conflicts with their order in leaf
// domain
if (outer > inner) {
// NOTE: reorder here is necessary to work around the automatic swap in
// `TensorDomain::merge`, if the first axis position is larger than the
// second. we want to have the merge dimension be like
// (tv->axis(to_merge[i]) * tv->axis(to_merge[i-1])), reorder allows us to
// compensate the automatic swap in `TensorDomain::merge`.
tv->reorder({{inner, outer}, {outer, inner}});
// swapping inner with outer since we also need to keep track of the
// actual outer position for the remaining merge operations as well as for
// return value.
std::swap(inner, outer);
}
// from
// (i..., tv->axis(outer), j..., tv->axis(inner), k...)
// to
// (i..., tv->axis(outer) * tv->axis(inner), j..., k...)
tv->merge(static_cast<int>(outer), static_cast<int>(inner));
// compensate future indices for the diminishing inner.
for (int64_t j = i + 1; j < (int64_t)to_merge.size(); j++) {
if (to_merge[j] > inner) {
to_merge[j]--;
}
}
for (auto& val : to_update) {
if (val == inner) {
val = outer;
} else if (val > inner) {
val--;
}
}
inner = outer;
}
return inner;
}
int64_t mergeReduction(TensorView* tv) {
int prev_i = -1;
int64_t num_merged = 0;
for (int i = static_cast<int>(tv->nDims()) - 1; i >= 0; i--) {
if (!tv->axis(i)->isReduction()) {
continue;
}
if (prev_i == -1) {
prev_i = i;
} else {
tv->merge(i, prev_i);
prev_i = i;
num_merged++;
}
}
if (prev_i != 0) {
tv->reorder({{prev_i, 0}});
}
return prev_i == -1 ? 0 : num_merged + 1;
}
int64_t mergeNonReduction(TensorView* tv) {
bool has_device_dim = false;
int prev_i = -1;
int64_t num_merged = 0;
if (tv->nDims() == 0) {
return 0;
}
for (int i = static_cast<int>(tv->nDims()) - 1; i >= 0; i--) {
if (tv->axis(i)->isReduction()) {
continue;
}
if (tv->axis(i)->isDeviceDim()) {
has_device_dim = true;
continue;
}
if (prev_i == -1) {
prev_i = i;
} else {
tv->merge(i, prev_i);
prev_i = i;
num_merged++;
}
}
if (prev_i != -1) {
tv->reorder({{prev_i, 0}});
}
if (has_device_dim) {
// in this case the layout at this point is [i, r , d]
// we want to put the device dim back to outmost
tv->reorder({{prev_i != -1 ? 2 : 1, 0}});
}
return prev_i == -1 ? 0 : num_merged + 1;
}
void parallelizeAllLike(
TensorView* reference_tv,
int64_t pos,
std::vector<TensorView*> selected_tvs,
const std::unordered_set<ParallelType>& selected_parallel_types,
bool propagate_padding) {
FusionGuard fg(reference_tv->fusion());
if (pos < 0) {
pos += (int64_t)reference_tv->nDims() + 1;
}
NVF_CHECK(
pos >= 0 && pos <= (int64_t)reference_tv->nDims(),
"parallelizeAllLike called on an position outside valid range.");
std::unordered_map<IterDomain*, IterDomain*> concrete_to_reference_map;
auto ca_map = ComputeAtMap(FusionGuard::getCurFusion());
const auto& reference_dom = reference_tv->getLeafDomain();
for (auto it = reference_dom.begin(); it != reference_dom.begin() + pos;
it++) {
auto ca_id =
ca_map.getConcreteMappedID(*it, IdMappingMode::PERMISSIVE_RESIZE);
concrete_to_reference_map[ca_id] = *it;
}
if (selected_tvs.empty()) {
selected_tvs = ir_utils::allTvs(reference_tv->fusion());
}
for (auto tv : selected_tvs) {
if (tv->isFusionInput()) {
continue;
}
for (const auto i : c10::irange((int64_t)tv->getLeafDomain().size())) {
auto ca_id = ca_map.getConcreteMappedID(
tv->axis(i), IdMappingMode::PERMISSIVE_RESIZE);
if (concrete_to_reference_map.count(ca_id) > 0) {
auto reference_id = concrete_to_reference_map.at(ca_id);
auto reference_parallel_type = reference_id->getParallelType();
if (selected_parallel_types.empty() ||
selected_parallel_types.count(reference_parallel_type)) {
tv->axis(i)->parallelize(reference_parallel_type);
}
if (propagate_padding) {
if (reference_id->hasPaddingToMultipleOfWarp()) {
tv->axis(i)->padToMultipleOfWarp(
reference_id->getMaybeSizeAfterPadding());
}
}
}
}
}
}
namespace {
// Find the resolution points of the persistent buffers in the provided
// persistent_buffer_info. Resolution points are identified by tracking if a
// tensor view is dependent on a reduction, or a persistent buffer. When an
// expression has inputs that are on both a reduction and persistent buffer
// path, that's a point where we may be resolving the persistent buffer. In
// other words, we know the persistent buffer has to be live at that point, but
// don't know if it has to be live after it.
//
// For example if we have:
//
// t0 = makeSymbolicTensor(2)
// t1 = set(t0)
// t2 = sum(t1, 1)
// t3 = broadcast(t2, {false, true})
// t4 = set(t1)
// t5 = add(t4, t3)
//
// In this case, t1 is the persistent buffer, that buffer is resolved at t5, so
// it needs to exist in full until t5 is "resolved". This class assumes all
// reduction patterns in the fusion are matching.
class PersistentBufferResolution : public IterVisitor {
public:
static std::vector<TensorView*> getResolutionPointsOf(
Fusion* fusion,
TensorView* persistent_buffer) {
PersistentBufferResolution resolution(fusion, persistent_buffer);
NVF_ERROR(
!resolution.resolution_points_.empty(),
"Could not resolve persistent buffer: ",
persistent_buffer);
return resolution.resolution_points_;
}
PersistentBufferResolution() = delete;
private:
PersistentBufferResolution(Fusion* fusion, TensorView* persistent_buffer)
: persistent_buffer_(persistent_buffer) {
traverse(fusion);
}
private:
void dispatch(Val* val) final {
if (!val->isA<TensorView>()) {
return;
}
auto tv = val->as<TensorView>();
if (tv == persistent_buffer_) {
persistent_buffer_hit = true;
on_persitent_buffer_path_.emplace(tv);
return;
}
if (!persistent_buffer_hit) {
return;
}
if (tv->hasReduction()) {
if (std::any_of(
resolution_points_.begin(),
resolution_points_.end(),
[&tv](TensorView* resolution_point) {
return DependencyCheck::isDependencyOf(resolution_point, tv);
})) {
// If already resolved, don't start a new reduction path.
return;
}
on_reduction_path_.emplace(tv);
}
}
void dispatch(Expr* expr) final {
if (!persistent_buffer_hit) {
return;
}
bool output_is_reduction =
std::any_of(expr->outputs().begin(), expr->outputs().end(), [](Val* v) {
if (!v->isA<TensorView>()) {
return false;
}
return v->as<TensorView>()->hasReduction();
});
// Persistent buffers cannot be resolved on a reduction expression
if (output_is_reduction) {
return;
}
bool input_on_reduction_path = std::any_of(
expr->inputs().begin(), expr->inputs().end(), [&](Val* inp) {
return on_reduction_path_.count(inp);
});
auto input_on_persitent_buffer_path_it = std::find_if(
expr->inputs().begin(), expr->inputs().end(), [&](Val* inp) {
return on_persitent_buffer_path_.count(inp);
});
bool input_on_persistent_buffer_path =
input_on_persitent_buffer_path_it != expr->inputs().end();
if (input_on_reduction_path && input_on_persistent_buffer_path) {
// Expression has inputs on both a reduction and persistent buffer path,
// this is a resolution.
auto out_tvs = ir_utils::filterByType<TensorView>(expr->outputs());
// Add resolution point
resolution_points_.insert(
resolution_points_.end(), out_tvs.begin(), out_tvs.end());
// Outputs are still on a persistent path
for (auto out : expr->outputs()) {
on_persitent_buffer_path_.emplace(out);
}
} else if (input_on_reduction_path) {
// Propagate forward the reduction path
on_reduction_path_.insert(expr->outputs().begin(), expr->outputs().end());
} else if (input_on_persistent_buffer_path) {
// Propagate forward the persistent path
for (auto out : expr->outputs()) {
on_persitent_buffer_path_.emplace(out);
}
}
}
// Don't do processing until we see the buffer we're looking for
bool persistent_buffer_hit = false;
// Track if key is dependent on a persistent reduction, resolves if
// encountering a persistent buffer. For this analysis doesn't matter which
// reduction the path is based on.
std::unordered_set<Val*> on_reduction_path_;
// Track if key is dependent on a persistent buffer, resolves if encountering
// a persistent reduction or changes path if encountering another persistent
// buffer
std::unordered_set<Val*> on_persitent_buffer_path_;
// Tracks where the persistent buffer (key) is resolved (values)
std::vector<TensorView*> resolution_points_;
const TensorView* persistent_buffer_;
};
} // namespace
namespace {
// This function checks if there is a broadcast tv in the dependencies between
// the reduction_tv and the persistent_buffer. A tv is considered projectable
// if its definition is a broadcast, has the same number of dimensions as the
// reduction_tv, and each reduction dimension in reduction_tv corresponds to
// a broadcast dimension in the broadcast tv.
// Return the broadcast tv if there is one, otherwise return nullptr.
TensorView* getBufferProjectableBroadcastsTv(
TensorView* reduction_tv,
TensorView* persistent_buffer) {
const auto& dep_vals =
DependencyCheck::getAllValsBetween({reduction_tv}, {persistent_buffer});
for (auto val : dep_vals) {
if (auto tv = dynamic_cast<TensorView*>(val)) {
if (!tv->definition()->isA<BroadcastOp>()) {
continue;
}
if (reduction_tv->nDims() != tv->nDims()) {
continue;
}
// Each reduction dimension the producer, must be mapped to a broadcast
// dimension in the consumer, otherwise it is not a valid broadcast after
// reduction.
bool is_broadcast_after_reduction = true;
for (auto i : c10::irange(reduction_tv->nDims())) {
if (reduction_tv->axis(i)->isReduction() &&
!tv->axis(i)->isBroadcast()) {
is_broadcast_after_reduction = false;
break;
}
}
if (is_broadcast_after_reduction) {
return tv;
}
}
}
return nullptr;
}
} // namespace
std::pair<bool, std::vector<TensorView*>> canProjectToInputsWithoutReduction(
const std::vector<TensorView*> reduction_tvs,
TensorView* persistent_buffer) {
std::vector<TensorView*> dep_reduction_tvs, target_broadcast_tvs;
dep_reduction_tvs.reserve(reduction_tvs.size());
for (auto tv : reduction_tvs) {
if (DependencyCheck::isDependencyOf(tv, persistent_buffer)) {
dep_reduction_tvs.push_back(tv);
}
}
// (1) The persistent buffer doesn't depend on any reduction tv
if (dep_reduction_tvs.empty()) {
return std::make_pair(true, target_broadcast_tvs);
}
// (2) It depends on reduction tv(s), but after each reduction tv, there is a
// broadcasted tv can be projected to.
target_broadcast_tvs.reserve(dep_reduction_tvs.size());
for (auto reduction_tv : dep_reduction_tvs) {
auto broadcast_tv =
getBufferProjectableBroadcastsTv(reduction_tv, persistent_buffer);
if (!broadcast_tv) {
return std::make_pair(false, target_broadcast_tvs);
}
target_broadcast_tvs.push_back(broadcast_tv);
}
return std::make_pair(true, target_broadcast_tvs);
}
PersistentBufferInfo persistentBuffers(Fusion* fusion) {
FusionGuard fg(fusion);
PersistentBufferInfo persistent_buffer_info;
ComputeAtRootDomainMap root_map;
root_map.build();
auto all_tvs = ir_utils::allTvs(fusion);
for (auto producer : all_tvs) {
// Are all producer ids mappable to all consumers
bool mappable = true;
auto consumers = ir_utils::consumerTvsOf(producer);
if (consumers.empty()) {
continue;
}
// Track which consumers have unmappable dims from producer
std::vector<TensorView*> unmappable_consumers;
for (auto consumer : consumers) {
if (dynamic_cast<SelectOp*>(consumer->definition()) ||
dynamic_cast<IndexSelectOp*>(consumer->definition()) ||
dynamic_cast<TorchGatherOp*>(consumer->definition())) {
continue;
}
bool consumer_mappable = true;
auto mappable_roots =
root_map.getMappableDims(producer->domain(), consumer->domain());
auto p_root = producer->getMaybeRFactorDomain();
for (auto p_root_id : p_root) {
if (p_root_id->isReduction() || p_root_id->isBroadcast()) {
continue;
}
if (!mappable_roots.count(p_root_id)) {
mappable = false;
consumer_mappable = false;
persistent_buffer_info.unmappable_dims.emplace(p_root_id);
}
}
if (!consumer_mappable) {
unmappable_consumers.emplace_back(consumer);
}
}
if (!mappable) {
// If there's unmappable dims from producer to consumer, producer is a
// persistent buffer.
persistent_buffer_info.persistent_buffers.emplace_back(producer);
}
}
// Set the persistent buffer resolution points
persistent_buffer_info.persistent_buffer_resolution_points = {};
for (auto buffer : persistent_buffer_info.persistent_buffers) {
persistent_buffer_info.persistent_buffer_resolution_points.emplace_back(
PersistentBufferResolution::getResolutionPointsOf(fusion, buffer));
}
// Find projectable persistent buffers
auto reduction_tvs = getReductionTvs(fusion);
for (auto persistent_buffer : persistent_buffer_info.persistent_buffers) {
// Inputs marked as persistent buffers can't be projected any further back
if (persistent_buffer->isFusionInput()) {
continue;
}
// can project to input if the persistent_buffer can be recalculated without
// doing reduction.
if (canProjectToInputsWithoutReduction(reduction_tvs, persistent_buffer)
.first) {
persistent_buffer_info.projectable_persistent_buffers.push_back(
persistent_buffer);
}
}
// Get a list of inputs of the projectable buffers
auto all_inputs = ir_utils::inputTvsOf(
persistent_buffer_info.projectable_persistent_buffers);
// Map unmappable dims to inputs, doesn't matter which compute at map used
auto ca_map = ComputeAtMap(fusion);
std::unordered_set<IterDomain*> unmappable_concrete_ids;
for (auto id : persistent_buffer_info.unmappable_dims) {
unmappable_concrete_ids.emplace(
ca_map.getConcreteMappedID(id, IdMappingMode::EXACT));
}
for (auto input : all_inputs) {
bool has_unmappable_dim = false;
for (auto input_id : input->getMaybeRFactorDomain()) {
auto concrete_input_id =
ca_map.getConcreteMappedID(input_id, IdMappingMode::EXACT);
if (unmappable_concrete_ids.find(concrete_input_id) !=
unmappable_concrete_ids.end()) {
persistent_buffer_info.unamppable_dims_projected_to_inputs.emplace(
input_id);
has_unmappable_dim = true;
}
}
if (has_unmappable_dim) {
persistent_buffer_info.projectable_buffer_inputs.emplace_back(input);
}
}
return persistent_buffer_info;
}
ReductionTvProperties getReductionProperties(
Fusion* fusion,
SchedulerRuntimeInfo& runtime_info,
TensorView* tv) {
FusionGuard fg(fusion);
NVF_ERROR(tv != nullptr);
bool fastest_dim_reduction = isFastestDimReduction(tv);
// Tracks the dimensionality of the problem starts on inner most dim and works
// outward
int64_t dimensionality = 1;
// Initialize for dimensionality analysis
bool cur_dim_is_reduction = fastest_dim_reduction;
// Compute the size of the inner most dimension
int64_t inner_most_dimension_numel = 1;
int64_t inner_most_dimension_ndims = 0;
// Start from the inner most dimension, and work outwards. If this is a 3D
// pattern, i.e. theres a pattern like [r0, r1, i2, r3] or [i0, r1, r2, i3,
// i4] then compute the inner most dimension to compute separately.
const auto& root_dom = tv->getRootDomain();
for (size_t i = root_dom.size(); i > 0; i--) {
auto id = root_dom[i - 1];
if (id->isBroadcast()) {
continue;
}
if (id->isReduction() != cur_dim_is_reduction) {
dimensionality++;
cur_dim_is_reduction = !cur_dim_is_reduction;
} else if (dimensionality == 1) {
auto inferred_val =
runtime_info.expressionEvaluator().evaluate(id->extent());
NVF_ERROR(inferred_val.hasValue(), "Error inferring reduction size.");
inner_most_dimension_numel =
inner_most_dimension_numel * inferred_val.as<int64_t>();
inner_most_dimension_ndims++;
}
}
// Non reduction element count
int64_t total_iteration_numel = 1;
// Reduction element count
int64_t total_reduction_numel = 1;
for (auto id : root_dom) {
auto inferred_val =
runtime_info.expressionEvaluator().evaluate(id->extent());
NVF_ERROR(
inferred_val.hasValue(),
"Error inferring dimensions of reduction fusion.");
if (id->isReduction()) {
total_reduction_numel *= inferred_val.as<int64_t>();
} else {
total_iteration_numel *= inferred_val.as<int64_t>();
}
}
ReductionTvProperties properties;
properties.total_reduction_numel = total_reduction_numel;
properties.total_iteration_numel = total_iteration_numel;
properties.fastest_dim_reduction = fastest_dim_reduction;
properties.inner_most_dimension_numel = inner_most_dimension_numel;
properties.inner_most_dimension_ndims = inner_most_dimension_ndims;
properties.dimensionality = dimensionality;
return properties;
}
namespace {
// Figure out which persistent buffers are active at the generation of values in
// the fusion. This will be used at runtime to compute the size and max size of
// the persistent buffers.
std::unique_ptr<HeuristicCompileTime::ScopedPersistenceBufferMap>
getScopePersistenceFactors(
Fusion* fusion,
const PersistentBufferInfo& persistent_buffer_info) {
auto new_persistent_factor_map_ptr =
std::make_unique<HeuristicCompileTime::ScopedPersistenceBufferMap>();
auto& new_persistent_factor_map = *new_persistent_factor_map_ptr;
// Convenience accessors
const auto& persistent_buffers = persistent_buffer_info.persistent_buffers;
const auto& projectable_buffer_inputs =
persistent_buffer_info.projectable_buffer_inputs;
const auto& projectable_persistent_buffers =
persistent_buffer_info.projectable_persistent_buffers;
const auto& persistent_buffer_resolution_points =
persistent_buffer_info.persistent_buffer_resolution_points;
// Append projectable buffer inputs, going to compute size of those as well.
auto persistent_buffers_and_inputs = persistent_buffers;
persistent_buffers_and_inputs.insert(
persistent_buffers_and_inputs.end(),
projectable_buffer_inputs.begin(),
projectable_buffer_inputs.end());
for (auto persistent_buffer_i : c10::irange(persistent_buffers.size())) {
auto persistent_buffer = persistent_buffers[persistent_buffer_i];
// All expressions between tv and its resolution points must have tv's
// persistent buffer allocated. This is an optimistic view on how many
// registers we need allocated in the kernel, since if we ordered two
// persistent buffers that are completely independent to somehow overlap
// with eachothers loop nests both persistent buffers would have to be
// allocated at the same time even though this function would assume they
// don't.
//
// Unfortunately this limitation is hard to work around as we would have
// to actually generate the kernel before we know if it would fit
// persistently in registers. In practice, though, this should not happen
// as inlining loop structures where the persistent buffer is used should
// prevent muiltiple persistent buffers from being merged togther if not
// necessary.
auto resolution_points =
persistent_buffer_resolution_points[persistent_buffer_i];
for (auto val : DependencyCheck::getAllValsBetween(
{persistent_buffer},
{resolution_points.begin(), resolution_points.end()})) {
// Persistent normalization kernels imply that all persistent buffers
// have the same dimensionality. Assume if a persistent buffer is
// consumed by another we can alias and reuse the memory.
if (val == persistent_buffer) {
continue;
}
// All vals between resolution point and the corresponding buffer have
// that buffer live during their generation.
if (new_persistent_factor_map.find(val) ==
new_persistent_factor_map.end()) {
new_persistent_factor_map[val] =
std::vector<bool>(persistent_buffers_and_inputs.size(), false);
}
new_persistent_factor_map.at(val)[persistent_buffer_i] = true;
}
}
// Processing projectable persistent buffers is a little more complex, simply
// because we have to line up inputs with their persistent buffers.
// Offset into the bool vector
size_t bool_vector_offset = persistent_buffers.size();
for (auto projectable_persistent_buffer_i :
c10::irange(projectable_persistent_buffers.size())) {
auto projectable_persistent_buffer =
projectable_persistent_buffers[projectable_persistent_buffer_i];
auto inputs = ir_utils::inputTvsOf(projectable_persistent_buffer);
for (auto input : inputs) {
auto input_it = std::find(
projectable_buffer_inputs.begin(),
projectable_buffer_inputs.end(),
input);
// If input wasn't recorded as a projectable buffer input, then it doesn't
// have any persistent dims, so ignore it.
if (input_it == projectable_buffer_inputs.end()) {
continue;
}
// get inuput index entry in the buffer inputs vector
auto input_i = std::distance(projectable_buffer_inputs.begin(), input_it);
// Get the offset in the bool vector for this input
input_i += (int64_t)bool_vector_offset;
// If we project persistence from the persistent buffers to the inputs,
// then it would have to be active from the resolution points of the
// persistent buffer all the way back to the projected inputs.
auto resolution_points =
persistent_buffer_resolution_points[projectable_persistent_buffer_i];
for (auto val : DependencyCheck::getAllValsBetween(
{input}, {resolution_points.begin(), resolution_points.end()})) {
// Persistent normalization kernels imply that all persistent buffers
// have the same dimensionality. Assume if a persistent buffer is
// consumed by another we can alias and reuse the memory.
if (val == input) {
continue;
}
if (new_persistent_factor_map.find(val) ==
new_persistent_factor_map.end()) {
new_persistent_factor_map[val] =
std::vector<bool>(persistent_buffers_and_inputs.size(), false);
}
new_persistent_factor_map.at(val)[input_i] = true;
}
}
}
return new_persistent_factor_map_ptr;
}
} // namespace
// Returns true if a persistent tv can be projected to its persistent producers.
bool canProjectToPersistentProducer(
TensorView* buffer,
const std::vector<TensorView*>& producers,
const std::unordered_set<TensorView*>& persistent_buffer_set) {
if (buffer->hasReduction() || producers.empty()) {
return false;
}
if (std::all_of(producers.begin(), producers.end(), [&](auto producer) {
return persistent_buffer_set.count(producer) > 0;
})) {
return true;
} else {
return false;
}
}
int64_t getPersistentBufferSizeOfTensor(
const TensorView* buffer,
SchedulerRuntimeInfo& runtime_info,
const PersistentBufferInfo& persistent_buffer_info) {
int64_t buffer_bytes = -1;
bool is_input =
std::find(
persistent_buffer_info.projectable_buffer_inputs.begin(),
persistent_buffer_info.projectable_buffer_inputs.end(),
buffer) != persistent_buffer_info.projectable_buffer_inputs.end();
for (auto id : buffer->getMaybeRFactorDomain()) {
if (id->isReduction() || id->isBroadcast()) {
continue;
}
// Unmappable dimensions are those that we cannot inline into other
// tensor views. So they're the ones that need to be persistent.
if (!is_input && !persistent_buffer_info.unmappable_dims.count(id)) {
continue;
}
if (is_input &&
!persistent_buffer_info.unamppable_dims_projected_to_inputs.count(id)) {
continue;
}
auto id_size = runtime_info.expressionEvaluator().evaluate(id->extent());
NVF_ERROR(id_size.hasValue(), "Could not infer persistent buffer size.");
if (buffer_bytes == -1) {
buffer_bytes = id_size.as<int64_t>();
} else {
buffer_bytes *= id_size.as<int64_t>();
}
}
buffer_bytes = buffer_bytes == -1 ? 0
: buffer_bytes *
(int64_t)dataTypeSize(buffer->getDataType().value(),
runtime_info.getIndexType());
return buffer_bytes;
}
PersistentBufferSizeReturn persistentBufferSize(
Fusion* fusion,
SchedulerRuntimeInfo& runtime_info,
const PersistentBufferInfo& persistent_buffer_info,
HeuristicSummary* data_cache) {
FUSER_PERF_SCOPE("scheduler_utils::persistentBufferSize");
if (persistent_buffer_info.persistent_buffers.empty()) {
PersistentBufferSizeReturn empty_sizes;
return empty_sizes;
}
// Compute size of all the buffers
const auto& persistent_buffers = persistent_buffer_info.persistent_buffers;
const auto& projectable_buffers =
persistent_buffer_info.projectable_persistent_buffers;
const auto& projectable_buffers_inputs =
persistent_buffer_info.projectable_buffer_inputs;
std::vector<TensorView*> all_buffers = persistent_buffers;
all_buffers.insert(
all_buffers.end(),
projectable_buffers_inputs.begin(),
projectable_buffers_inputs.end());
std::vector<int64_t> persistent_buffer_sizes(all_buffers.size(), -1);
for (auto buffer_i : c10::irange(all_buffers.size())) {
auto buffer = all_buffers[buffer_i];
persistent_buffer_sizes[buffer_i] = getPersistentBufferSizeOfTensor(
buffer, runtime_info, persistent_buffer_info);
}
// Buffers involved in normal persistence
std::vector<bool> persistent_mask(all_buffers.size(), false);
std::unordered_set<TensorView*> persistent_buffer_set(
persistent_buffers.begin(), persistent_buffers.end());
for (auto buffer_i : c10::irange(persistent_buffers.size())) {
auto buffer = persistent_buffers[buffer_i];
const auto& producers = ir_utils::producerTvsOf(buffer);
if (!canProjectToPersistentProducer(
buffer, producers, persistent_buffer_set)) {
persistent_mask[buffer_i] = true;
}
}
// Buffers involved in projected to inputs
std::vector<bool> projected_mask(all_buffers.size(), true);
for (auto buffer_i : c10::irange(persistent_buffers.size())) {
auto buffer = persistent_buffers[buffer_i];
// Not a projectable buffer, or an input of a projectable buffer
if (std::find(
projectable_buffers.begin(), projectable_buffers.end(), buffer) !=
projectable_buffers.end()) {
projected_mask[buffer_i] = false;
}
}
// Function to take the mask of active buffers at a val, the mask (for if this
// is a normal persistent calculation, or a calculation projected on to the
// input buffers), and sizes, and returns total persistent buffer size.
auto masked_dot_product = [](const std::vector<bool>& mask0,
const std::vector<bool>& mask1,
const std::vector<int64_t>& sizes,
const std::vector<TensorView*>& all_buffers) {
int64_t buffer_size = 0;
NVF_ERROR(
mask0.size() == mask1.size() && mask0.size() == sizes.size() &&
mask0.size() == all_buffers.size());
// Keep track of which buffer is counted as there can be tensors
// that are both a persistent buffer and an input to a projectable
// buffer
std::unordered_set<TensorView*> active_buffers;
for (auto buffer_i : c10::irange(sizes.size())) {
if (mask0[buffer_i] && mask1[buffer_i] &&
active_buffers.count(all_buffers[buffer_i]) == 0) {
buffer_size += sizes[buffer_i];
active_buffers.insert(all_buffers[buffer_i]);