-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathdynamic_transform.cpp
More file actions
1664 lines (1487 loc) · 62.2 KB
/
dynamic_transform.cpp
File metadata and controls
1664 lines (1487 loc) · 62.2 KB
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 <device_lower/utils.h>
#include <dynamic_transform.h>
#include <expr_evaluator.h>
#include <fusion.h>
#include <ir/cloner.h>
#include <ir/iostream.h>
#include <ir/utils.h>
#include <logical_domain_map.h>
#include <ops/alias.h>
#include <ops/arith.h>
#include <ops/utils.h>
#include <runtime/executor_kernel_arg.h>
#include <runtime/executor_utils.h>
#include <transform_iter.h>
#include <transform_replay.h>
#include <transform_view.h>
#include "base.h"
#include <functional>
#include <optional>
namespace nvfuser {
DynamicTransformInitialInfo DynamicTransformInitialInfo::clone(
IrCloner& ir_cloner) const {
DynamicTransformInitialInfo cloned_info(ir_cloner.container()->as<Fusion>());
cloned_info.dynamic_reshaped_tvs_.reserve(dynamic_reshaped_tvs_.size());
for (const auto tv : dynamic_reshaped_tvs_) {
cloned_info.dynamic_reshaped_tvs_.push_back(ir_cloner.clone(tv));
}
cloned_info.dynamic_resized_ids_.reserve(dynamic_resized_ids_.size());
for (const auto id : dynamic_resized_ids_) {
cloned_info.dynamic_resized_ids_.push_back(ir_cloner.clone(id));
}
cloned_info.dynamic_expanded_tvs_.reserve(dynamic_expanded_tvs_.size());
for (const auto tv : dynamic_expanded_tvs_) {
cloned_info.dynamic_expanded_tvs_.push_back(ir_cloner.clone(tv));
}
cloned_info.dynamic_factory_tvs_.reserve(dynamic_factory_tvs_.size());
for (const auto v : dynamic_factory_tvs_) {
cloned_info.dynamic_factory_tvs_.push_back(ir_cloner.clone(v));
}
cloned_info.dynamic_topk_tvs_.reserve(dynamic_topk_tvs_.size());
for (const auto v : dynamic_topk_tvs_) {
cloned_info.dynamic_topk_tvs_.push_back(ir_cloner.clone(v));
}
cloned_info.maybe_zero_extents_set_.reserve(maybe_zero_extents_set_.size());
for (const auto v : maybe_zero_extents_set_) {
cloned_info.maybe_zero_extents_set_.insert(ir_cloner.clone(v));
}
cloned_info.maybe_zero_extents_.reserve(maybe_zero_extents_.size());
for (const auto v : maybe_zero_extents_) {
cloned_info.maybe_zero_extents_.push_back(ir_cloner.clone(v));
}
cloned_info.root_dynamic_vals_.reserve(root_dynamic_vals_.size());
for (const auto v : root_dynamic_vals_) {
cloned_info.root_dynamic_vals_.insert(ir_cloner.clone(v));
}
return cloned_info;
}
std::string DynamicTransformInitialInfo::toString() const {
std::stringstream ss;
ss << "DynamicTransformInitialInfo\n";
indent(ss, 1) << "Dynamic reshaped TensorViews:\n";
for (const auto& tv : dynamic_reshaped_tvs_) {
indent(ss, 2) << tv->toString() << "\n";
}
indent(ss, 1) << "Dynamic resized IterDomains:\n";
for (const auto& id : dynamic_resized_ids_) {
indent(ss, 2) << id->toString() << "\n";
}
indent(ss, 1) << "Dynamic expanded TensorViews:\n";
for (const auto& tv : dynamic_expanded_tvs_) {
indent(ss, 2) << tv->toString() << "\n";
}
indent(ss, 1) << "Dynamic factory-function output TensorViews:\n";
for (const auto& tv : dynamic_factory_tvs_) {
indent(ss, 2) << tv->toString() << "\n";
}
indent(ss, 1) << "Dynamic TopK output TensorViews:\n";
for (const auto& tv : dynamic_topk_tvs_) {
indent(ss, 2) << tv->toString() << "\n";
}
indent(ss, 1) << "Dynamic extent Vals:\n";
for (const auto& v : maybe_zero_extents_) {
indent(ss, 2) << v->toInlineString() << "\n";
}
indent(ss, 1) << "Root dynamic Vals:\n";
for (const auto& v : root_dynamic_vals_) {
indent(ss, 2) << v->toInlineString() << "\n";
}
return ss.str();
}
//! Gather information about concretizing transformations without
//! concrete input sizes.
class DynamicTransformInitialInfoBuilder : public IterVisitor {
public:
DynamicTransformInitialInfoBuilder(Fusion* fusion) : info_(fusion) {
NVF_ERROR(
!fusion->isA<kir::Kernel>(),
"Invalid container. Kernel container not allowed.\n");
traverseTo(fusion->getTerminatingOutputs(), false, false);
finalizeDynamicVals();
finalizeMaybeEmptyExtents();
}
const auto& getInfo() const {
return info_;
}
private:
using IterVisitor::dispatch;
using IterVisitor::handle;
void dispatch(Expr* expr) override {
// Detect factory methods by checking whether there are no TensorView inputs
if (std::none_of(
expr->inputs().begin(), expr->inputs().end(), [](Val* inp) {
return inp->vtype() == ValType::TensorView;
})) {
for (Val* out_val : expr->outputs()) {
if (TensorView* out_tv = dynamic_cast<TensorView*>(out_val)) {
const std::vector<IterDomain*>& out_rf = out_tv->getLogicalDomain();
if (std::ranges::any_of(
out_rf, std::mem_fn(&IterDomain::isSymbolic))) {
info_.dynamic_factory_tvs_.push_back(out_tv);
}
} else {
// Factory ops have only TensorView outputs, so we can skip Exprs that
// have scalar outputs
continue;
}
}
}
IterVisitor::dispatch(expr);
}
//! Find views that have symbolic outputs
void handle(ReshapeOp* op) override {
auto inp_tv = op->in()->as<TensorView>();
auto out_tv = op->out()->as<TensorView>();
// If there's no symbolic axis, this is a static reshape op
if (out_tv->domain()->hasSymbolicAxis()) {
info_.dynamic_reshaped_tvs_.push_back(out_tv);
// Input and output extent expressions both affect concretization
for (IterDomain* id :
inp_tv->getLogicalDomain() | TensorDomain::kNoReductions) {
loop_dynamic_vals_.push_back(id->getMaybeExpandedExtent());
}
for (const auto& id : out_tv->getLogicalDomain()) {
loop_dynamic_vals_.push_back(id->getMaybeExpandedExtent());
}
}
}
//! Find TopK operations that have symbolic outputs
void handle(TopKOp* op) override {
auto out_values = op->outValues()->as<TensorView>();
// Check if K of TopK is symbolic
if (op->k()->isConstScalar()) {
return;
}
info_.dynamic_topk_tvs_.push_back(out_values);
// The K parameter affects concretization
loop_dynamic_vals_.push_back(op->k());
const auto topk_dim = op->dim();
NVF_ERROR(
topk_dim >= 0 && topk_dim < std::ssize(out_values->getLogicalDomain()),
"Invalid TopK dimension ",
topk_dim);
auto topk_id = out_values->getLogicalDomain()[topk_dim];
loop_dynamic_vals_.push_back(topk_id->extent());
}
//! Find expands that have symbolic outputs. Of those, check whether the
//! extents match between input and output axes. If not, mark as dynamic.
void handle(ExpandOp* op) override {
auto inp_tv = op->in()->as<TensorView>();
auto out_tv = op->out()->as<TensorView>();
// If there's no symbolic axis, this is a static expand op
bool is_dynamic = false;
// Loop over all axes, check whether any expansions are undetermined
const std::vector<IterDomain*> inp_logical =
TensorDomain::noReductions(inp_tv->getLogicalDomain());
const std::vector<IterDomain*>& out_root = out_tv->getMaybeRootDomain();
NVF_ERROR(inp_logical.size() == out_root.size());
for (auto i : arange((int64_t)out_root.size())) {
IterDomain* out_id = out_root[i];
if (!out_id->isSymbolic()) {
continue;
}
Val* in_extent = inp_logical[i]->extent();
Val* out_extent = out_id->extent();
if (out_extent->sameAs(in_extent)) {
// Not expanding this axis
continue;
}
loop_dynamic_vals_.push_back(in_extent);
loop_dynamic_vals_.push_back(out_extent);
is_dynamic = true;
}
if (is_dynamic) {
info_.dynamic_expanded_tvs_.push_back(out_tv);
}
}
//! Detect possibly empty TensorViews and dynamic IterDomain transforms
void handle(TensorView* tv) override {
const auto& logical_dom = tv->getLogicalDomain();
ExpressionEvaluator ee;
for (auto id : logical_dom) {
if (!id->getMaybeExpandedExtent()->isConstScalar() ||
id->getMaybeExpandedExtent()->evaluate().as<int64_t>() == 0) {
info_.maybe_zero_extents_set_.insert(id->getMaybeExpandedExtent());
loop_dynamic_vals_.push_back(id->getMaybeExpandedExtent());
}
if (!id->definition() || id->getIterType() != IterType::Symbolic) {
continue;
}
if (id->definition()->isA<Resize>()) {
info_.dynamic_resized_ids_.push_back(id);
// extent of output determines its IterType
loop_dynamic_vals_.push_back(id->extent());
}
}
}
//! Process vector of loop dynamic values by finding inputs and recording the
//! result into info_
void finalizeDynamicVals() {
const auto inputs = InputsOf::outputs(loop_dynamic_vals_);
info_.root_dynamic_vals_.insert(inputs.begin(), inputs.end());
// initial_info_ provides a set of Vals that are used for concretization.
// Here we check which scalar inputs, if any, correspond to any of those
// Vals. These will be the inputs that are explicitly used in the cache ID
// for KernelArgumentHolder.
auto dyn_vals = info_.getRootDynamicVals();
for (const auto i : arange((int64_t)info_.fusion()->inputs().size())) {
auto input = info_.fusion()->inputs().at(i);
if (dyn_vals.find(input) != dyn_vals.end()) {
info_.scalar_inputs_affecting_concretization_.insert(i);
}
}
}
//! Convert maybe_zero_extents_set_ to a vector so we can index it reliably
void finalizeMaybeEmptyExtents() {
info_.maybe_zero_extents_ = std::vector<Val*>(
info_.maybe_zero_extents_set_.begin(),
info_.maybe_zero_extents_set_.end());
// Clear the corresponding set to free memory and speed up cloning
info_.maybe_zero_extents_set_.clear();
}
private:
DynamicTransformInitialInfo info_;
//! This is a collection of scalars that are explicitly checked during
//! concretization of dynamic ops, meaning they influence the structure of the
//! resulting concretized Fusion. We track these while traversing the graph
//! and when we are finished traversing we extract all of the corresponding
//! non-constant root Vals, which provides us with a minimal list of input
//! scalars that influence concretization. That list of scalars is then used
//! to compute a minimal cache key in InputsIdLookup::lookupId().
std::vector<Val*> loop_dynamic_vals_;
};
DynamicTransformConcretizationInfo::DynamicTransformConcretizationInfo(
const DynamicTransformInitialInfo* initial_info,
ExpressionEvaluator* expr_eval,
ExactLogicalDomainMap* exact_map)
: initial_info_(initial_info) {
NVF_ERROR(
!fusion()->isA<kir::Kernel>(),
"Invalid container. Kernel container not allowed.\n");
// Make sure all exactly mapped IDs have the same value in the
// evaluator when any one of the IDs has a known value
expr_eval->propagateBoundValuesThroughExactMaps(
initial_info_->fusion(), exact_map);
analyzeReshapes(expr_eval);
analyzeResizes(expr_eval);
analyzeExpands(expr_eval);
analyzeFactoryOutputs(expr_eval);
analyzeTopK(expr_eval);
auto maybe_zero_extents = initial_info_->getMaybeZeroExtents();
for (auto i : arange((int64_t)maybe_zero_extents.size())) {
auto ext = maybe_zero_extents.at(i);
auto ext_opt = expr_eval->evaluate(ext);
NVF_ERROR(
ext_opt.hasValue(),
"Could not evaluate dynamic extent: ",
ext->toString());
if (ext_opt == 0) {
empty_extents_.push_back(i);
}
}
}
void DynamicTransformConcretizationInfo::analyzeReshapes(
ExpressionEvaluator* expr_eval) {
const auto& reshape_tvs = initial_info_->getDynamicReshapedTensorViews();
for (const auto tv_index : arange((int64_t)reshape_tvs.size())) {
auto out_tv = reshape_tvs.at(tv_index);
auto op = out_tv->definition()->as<ReshapeOp>();
auto inp_tv = op->in()->as<TensorView>();
// If there's no symblic axis, this is a static reshape op
if (!out_tv->domain()->hasSymbolicAxis()) {
return;
}
NVF_ERROR(
out_tv->hasRoot(),
"Unexpected output tv of ReshapeOp: ",
out_tv->toString());
const auto& inp_dom =
TensorDomain::noReductions(inp_tv->getLogicalDomain());
// Determine input shape using expr evaluator
std::vector<int64_t> inp_shape(inp_dom.size(), 0);
bool is_empty = false;
for (const auto i : arange((int64_t)inp_dom.size())) {
auto inp_id = inp_dom.at(i);
// This should have been validated when initially creating reshape
// op, but just in case
NVF_ERROR(
!inp_id->maybePartial(),
"Invalid domain to reshape: ",
inp_id->toString());
auto extent_val = expr_eval->evaluate(inp_id->getMaybeExpandedExtent());
NVF_ERROR(
extent_val.hasValue(),
"Cannot evaluate the extent of an input domain to reshape: ",
inp_id->toString());
NVF_ERROR(
extent_val.is<int64_t>(),
"Invalid evaluated value of domain extent: ",
inp_id->toString());
NVF_ERROR(
extent_val.as<int64_t>() >= 0,
"Invalid input domain extent: ",
extent_val.as<int64_t>());
inp_shape.at(i) = extent_val.as<int64_t>();
if (inp_shape.at(i) == 0l) {
is_empty = true;
}
}
const auto& out_dom = out_tv->getLogicalDomain();
// Determine output shape using expr evaluator. Note there may be
// one domain of extent -1
std::vector<int64_t> out_shape(out_dom.size(), 0);
std::vector<int64_t> out_symbolic_sizes;
for (const auto i : arange((int64_t)out_dom.size())) {
auto out_id = out_dom.at(i);
auto extent_val = expr_eval->evaluate(out_id->extent());
NVF_ERROR(
extent_val.hasValue(),
"Cannot evaluate the extent of an output domain to reshape: ",
out_id->toString());
NVF_ERROR(
extent_val.is<int64_t>(),
"Invalid evaluated value of domain extent: ",
out_id->toString());
auto extent_int = extent_val.as<int64_t>();
if (extent_int == -1) {
// For non-constant Scalar sizes, check that we have not passed -1.
NVF_CHECK(
is_empty || out_id->extent()->isConst(),
"Values of -1 passed to reshape must be constant at definition.")
}
out_shape.at(i) = extent_int;
if (is_empty) {
if (extent_int == 1l) {
// Indicates we should concretize to IterType::Broadcast
out_symbolic_sizes.push_back(1l);
} else if (extent_int == 0l || extent_int == -1l) {
// Indicates we should concretize to IterType::Iteration and
// concretize extent to 0
out_symbolic_sizes.push_back(0l);
} else {
// Indicates we should concretize to IterType::Iteration
out_symbolic_sizes.push_back(-1l);
}
}
}
if (is_empty) {
reshape_transforms_.emplace_back(tv_index, out_symbolic_sizes);
} else {
reshape_transforms_.emplace_back(
tv_index, analyzeView(inp_tv, inp_shape, out_shape));
}
}
}
void DynamicTransformConcretizationInfo::analyzeResizes(
ExpressionEvaluator* expr_eval) {
const auto& resize_ids = initial_info_->getDynamicResizedIterDomains();
for (const auto id_index : arange((int64_t)resize_ids.size())) {
auto out_id = resize_ids.at(id_index);
auto op = out_id->definition()->as<Resize>();
NVF_CHECK(
out_id->getIterType() == IterType::Symbolic,
"Found non-dynamic Resize in initial concretization info: ",
op->toString());
auto extent_val = expr_eval->evaluate(out_id->getMaybeExpandedExtent());
NVF_ERROR(
extent_val.hasValue(),
"Cannot evaluate the extent of a resized domain: ",
out_id->toString());
NVF_ERROR(
extent_val.is<int64_t>(),
"Invalid evaluated value of resized domain extent: ",
out_id->toString());
auto extent_int = extent_val.as<int64_t>();
NVF_ERROR(
extent_int >= 0,
"Invalid resized domain extent ",
extent_int,
" for domain ",
out_id->toString());
auto iter_type =
extent_int == 1 ? IterType::Broadcast : IterType::Iteration;
resize_itertypes_.emplace_back(id_index, iter_type);
}
}
void DynamicTransformConcretizationInfo::analyzeExpands(
ExpressionEvaluator* expr_eval) {
const std::vector<TensorView*>& expanded_tvs =
initial_info_->getDynamicExpandedTensorViews();
for (const auto tv_index : arange((int64_t)expanded_tvs.size())) {
const TensorView* out_tv = expanded_tvs.at(tv_index);
const TensorView* inp_tv = out_tv->definition()->as<ExpandOp>()->in();
const std::vector<IterDomain*>& out_root = out_tv->getMaybeRootDomain();
const std::vector<IterDomain*> inp_logical =
TensorDomain::noReductions(inp_tv->getLogicalDomain());
NVF_ERROR(out_root.size() == inp_logical.size());
std::vector<bool> expand_axes;
expand_axes.reserve(out_root.size());
for (int64_t i : arange((int64_t)out_root.size())) {
const IterDomain* inp_id = inp_logical[i];
const IterDomain* out_id = out_root[i];
if (out_id->isIteration()) {
expand_axes.push_back(false);
continue;
}
// For Broadcast or Symbolic axes, check the sizes of the input and output
int64_t out_size = expr_eval->evaluate(out_id->extent()).as<int64_t>();
// Use getMaybeExpandedExtent() here so we can mark "false" if we are just
// preserving a pre-existing expansion.
int64_t in_size =
expr_eval->evaluate(inp_id->getMaybeExpandedExtent()).as<int64_t>();
if (in_size == 1) {
expand_axes.push_back(out_size != in_size);
} else {
NVF_CHECK(
out_size == in_size,
"Mismatch in sizes when concretizing expand. Expanded or Iteration "
"domain ",
inp_id->toString(),
" has possibly expanded extent ",
in_size,
" which is incompatible with expansion to size ",
out_size,
". Note that already-expanded axes may not themselves be "
"expanded.");
expand_axes.push_back(false);
}
}
expand_axes_.emplace_back(tv_index, expand_axes);
}
}
void DynamicTransformConcretizationInfo::analyzeFactoryOutputs(
ExpressionEvaluator* expr_eval) {
const std::vector<TensorView*>& factory_tvs =
initial_info_->getDynamicFactoryOutputs();
factory_output_itertypes_.reserve(factory_tvs.size());
for (const auto tv_index : arange((int64_t)factory_tvs.size())) {
const TensorView* tv = factory_tvs.at(tv_index);
const std::vector<IterDomain*>& logical_dom = tv->getLogicalDomain();
std::vector<std::pair<int64_t, IterType>> conc_iter_types;
for (int64_t pos : arange((int64_t)logical_dom.size())) {
const IterDomain* id = logical_dom[pos];
if (!id->isSymbolic()) {
continue;
}
PolymorphicValue extent = expr_eval->evaluate(id->extent());
NVF_CHECK(
extent.hasValue(),
"Could not evaluate dynamic factory op output extent ",
id->extent());
NVF_ERROR(
extent.is<int64_t>(),
"Expected integer evaluated extent but found ",
extent);
IterType iter_type = (extent.as<int64_t>() == 1) ? IterType::Broadcast
: IterType::Iteration;
conc_iter_types.emplace_back(pos, iter_type);
}
factory_output_itertypes_.push_back(conc_iter_types);
}
}
void DynamicTransformConcretizationInfo::analyzeTopK(
ExpressionEvaluator* expr_eval) {
const auto& topk_tvs = initial_info_->getDynamicTopKTensorViews();
for (const auto [i, tv] : enumerate(topk_tvs)) {
auto topk_op = dynamic_cast<TopKOp*>(tv->definition());
NVF_ERROR(topk_op != nullptr, "Expected TopKOp for TopK TensorView");
// Evaluate K parameter
auto k_val = expr_eval->evaluate(topk_op->k());
NVF_ERROR(k_val.hasValue(), "Could not evaluate K parameter for TopK");
auto k_int = k_val.as<int64_t>();
NVF_ERROR(
k_int >= 0,
"Invalid TopK K parameter ",
k_int,
" for operation ",
topk_op->toString());
auto iter_type = (k_int == 1) ? IterType::Broadcast : IterType::Iteration;
topk_itertypes_.emplace_back(i, iter_type);
}
}
bool DynamicTransformConcretizationInfo::operator==(
const DynamicTransformConcretizationInfo& other) const {
if (this == &other) {
return true;
}
if (reshape_transforms_.size() != other.reshape_transforms_.size() ||
resize_itertypes_.size() != other.resize_itertypes_.size() ||
empty_extents_.size() != other.empty_extents_.size() ||
factory_output_itertypes_.size() !=
other.factory_output_itertypes_.size() ||
topk_itertypes_.size() != other.topk_itertypes_.size()) {
return false;
}
for (const auto i : arange((int64_t)reshape_transforms_.size())) {
const auto& analysis = reshape_transforms_.at(i);
const auto& other_analysis = other.reshape_transforms_.at(i);
if (analysis != other_analysis) {
return false;
}
}
for (const auto i : arange((int64_t)resize_itertypes_.size())) {
const auto& itertype = resize_itertypes_.at(i);
const auto& other_itertype = other.resize_itertypes_.at(i);
if (itertype != other_itertype) {
return false;
}
}
if (factory_output_itertypes_ != other.factory_output_itertypes_) {
return false;
}
for (const auto [topk_itertype, other_topk_itertype] :
zip(topk_itertypes_, other.topk_itertypes_)) {
if (topk_itertype != other_topk_itertype) {
return false;
}
}
for (const auto i : arange((int64_t)expand_axes_.size())) {
const auto& expand_axes = expand_axes_.at(i);
const auto& other_expand_axes = other.expand_axes_.at(i);
if (expand_axes != other_expand_axes) {
return false;
}
}
for (const auto i : arange((int64_t)empty_extents_.size())) {
const auto& ee = empty_extents_.at(i);
const auto& other_ee = other.empty_extents_.at(i);
if (ee != other_ee) {
return false;
}
}
return true;
}
std::string DynamicTransformConcretizationInfo::toString() const {
std::stringstream ss;
ss << "DynamicTransformConcretizationInfo\n";
indent(ss, 1) << "Empty tensor extents:\n";
for (const auto& i : empty_extents_) {
auto ext = initial_info_->getMaybeZeroExtents().at(i);
indent(ss, 2) << ext->toString() << " is zero\n";
}
indent(ss, 1) << "Reshape:\n";
NVF_ERROR(
reshape_transforms_.size() ==
initial_info_->getDynamicReshapedTensorViews().size());
for (const auto& [tv_index, view_info] : reshape_transforms_) {
auto tv = initial_info_->getDynamicReshapedTensorViews().at(tv_index);
if (std::holds_alternative<AnalyzeViewResult>(view_info)) {
indent(ss, 2) << tv->toString() << " (index=" << tv_index << "), "
<< std::get<AnalyzeViewResult>(view_info).toString()
<< "\n";
} else {
indent(ss, 2) << tv->toString() << " (index=" << tv_index
<< "), is empty. Symbolic reshape sizes: "
<< std::get<std::vector<int64_t>>(view_info) << "\n";
}
}
indent(ss, 1) << "Resize:\n";
NVF_ERROR(
resize_itertypes_.size() ==
initial_info_->getDynamicResizedIterDomains().size());
for (const auto& [id_index, iter_type] : resize_itertypes_) {
auto id = initial_info_->getDynamicResizedIterDomains().at(id_index);
indent(ss, 2) << id->toString() << " (index=" << id_index << "), "
<< iter_type << "\n";
}
indent(ss, 1) << "Expand:\n";
NVF_ERROR(
expand_axes_.size() ==
initial_info_->getDynamicExpandedTensorViews().size());
for (const auto& [tv_index, expand_axes] : expand_axes_) {
auto tv = initial_info_->getDynamicExpandedTensorViews().at(tv_index);
indent(ss, 2) << tv->toString() << " (index=" << tv_index << "), {";
bool first = true;
for (bool e : expand_axes) {
if (!first) {
ss << ", ";
}
first = false;
ss << (e ? "true" : "false");
}
ss << "}\n";
}
indent(ss, 1) << "Factory Output IterTypes:\n";
NVF_ERROR(
factory_output_itertypes_.size() ==
initial_info_->getDynamicFactoryOutputs().size());
for (int64_t i : arange((int64_t)factory_output_itertypes_.size())) {
TensorView* tv = initial_info_->getDynamicFactoryOutputs().at(i);
indent(ss, 2) << tv->toString() << '\n';
for (const auto& [pos, iter_type] : factory_output_itertypes_.at(i)) {
indent(ss, 3) << tv->getLogicalDomain().at(pos)->toString() << " => "
<< iter_type << '\n';
}
}
indent(ss, 1) << "TopK:\n";
NVF_ERROR(
topk_itertypes_.size() ==
initial_info_->getDynamicTopKTensorViews().size());
for (const auto& [tv_index, iter_type] : topk_itertypes_) {
auto tv = initial_info_->getDynamicTopKTensorViews().at(tv_index);
indent(ss, 2) << tv->toString() << " (index=" << tv_index << "), "
<< iter_type << "\n";
}
return ss.str();
}
//! Concretize a symbolic fusion with concrete transformation info
class DynamicTransformConcretizer : public OptOutMutator {
public:
DynamicTransformConcretizer(
Fusion* fusion,
const DynamicTransformConcretizationInfo* info)
: info_(info) {
NVF_ERROR(
fusion == info->fusion(),
"Invalid DynamicTransformInitialInfo. The associated Fusion is "
"different from the given Fusion");
FusionGuard fg(fusion);
concretize();
}
//! Return map from original symbolic value to new concrete value.
std::unordered_map<Val*, Val*> getSymbolicToConcretizedMap() {
return symbolic_to_concretized_map_;
}
private:
void concretize();
//! Concretize a single reshape which has a non-empty input tensor
TensorView* concretizeNonEmptyReshape(
TensorView* inp_tv,
TensorView* incomplete_out_tv,
const AnalyzeViewResult& view_analysis);
//! Concretize a single reshape given that we know that numel=0.
//! The symbolic sizes are the actual sizes 0 or 1, or -1 if the size of a
//! given reshaped dimension is greater than 1.
TensorView* concretizeEmptyReshape(
TensorView* inp_tv,
TensorView* incomplete_out_tv,
const std::vector<int64_t>& symbolic_sizes);
void concretizeReshape();
void concretizeResize();
void concretizeExpand();
void concretizeEmptyExtents();
void concretizeFactoryOutputs();
void concretizeTopK();
//! Use this instead of calling registerMutation directly, since it will also
//! check that the concretized value is a valid input to all of its uses.
void registerConcretization(Val* old_val, Val* new_val) {
symbolic_to_concretized_map_.emplace(old_val, new_val);
checkConcretizedUses(old_val, new_val);
NVF_ERROR(
old_val->dtype() == new_val->dtype(),
"registerConcretization should not be used to change dtype of Val ",
old_val->toString(),
". Old dtype: ",
old_val->dtype(),
". New dtype: ",
new_val->dtype());
registerMutation(old_val, new_val);
}
//! Check uses of old_val to ensure that new_val does not violate
//! assumptions. This is currently only used to check that inputs to SqueezeOp
//! are marked broadcast during concretization.
void checkConcretizedUses(Val* old_val, Val* new_val) const;
using OptOutMutator::mutate;
void mutate(TensorView* tv) final;
void mutate(TensorDomain* td) final;
void mutate(IterDomain* id) final;
void mutate(Expr* expr) final;
//! Concretizes the root domain of a symbolic consumer tensor from
//! its producer domains. Returns true if any root ID is concretized.
bool propagateFromProducerToConsumer(TensorView* consumer);
private:
const DynamicTransformConcretizationInfo* info_;
//! Map from original symbolic value to new concretized_value.
//! This map is separate from mutation_ to avoid interfering with
//! OptOutMutator
std::unordered_map<Val*, Val*> symbolic_to_concretized_map_;
};
void DynamicTransformConcretizer::concretize() {
// Concretize all dynamic reshape ops
concretizeReshape();
// Set output IterTypes for dynamic resize ops
concretizeResize();
// Overwrite expanded IterDomains for dynamic expand ops
concretizeExpand();
// Registers replacement of all empty extents with zeroVal()
concretizeEmptyExtents();
// Set IterTypes for factory op outputs
concretizeFactoryOutputs();
// Set IterTypes for TopK op outputs
concretizeTopK();
// Finally, propagate concretized domains
auto all_stmts = StmtSort::getStmts(
info_->fusion(),
/*traverse_members*/ true,
/*traverse_attributes*/ true,
/*traverse_siblings*/ true);
for (auto stmt : all_stmts) {
// We mutate all scalar and TensorView Vals and Exprs in topological order.
// This alone is enough to modify scalars and their Exprs properly. Above,
// concretizeEmptyExtents will register some scalar extents as zeroVal(),
// and those will be properly propagated in this type of traversal.
//
// However, an important part of concretization is mutating IterDomains and
// IterDomain expressions. To do this, we have registered some mutations in
// the above calls; for example concretizeResize registers IterTypes as
// Iteration or Broadcast. There may still be many Symbolic IterDomains that
// are not yet registered for mutation though; these need to be registered
// by propagating the IterTypes and modified extents through the Fusion in
// the P2C direction. Importantly, this means traversing across TensorView
// expressions and using exact mapping between producer and consumer TVs to
// infer IterTypes of consumer root IterDomains from concretized producer
// logical IterDomains.
//
// The order of StmtSort::getStmts guarantees a topological ordering with
// respect to our IR graph. That IR does not explicitly hold TensorView
// dependencies for IterDomains; i.e. we rely on TensorView expressions to
// infer that one IterDomain is a producer logical which another consumer
// root domain depends on. So we avoid processing IterDomains and
// TensorDomains until we reach the TensorView that contains them. Otherwise
// we would not be able to propagate across exact maps before processing
// all root->logical IterDomains and expressions.
if (const auto op = dynamic_cast<Expr*>(stmt); stmt->isA<IterDomain>() ||
stmt->isA<TensorDomain>() || (op && op->output(0)->isA<IterDomain>())) {
continue;
}
OptOutMutator::dispatchMutate(stmt);
}
for (Val* outp : info_->fusion()->outputs()) {
Val* new_outp = maybeMutated(outp);
if (new_outp != outp) {
info_->fusion()->replaceOutput(outp, new_outp);
}
}
}
void DynamicTransformConcretizer::concretizeEmptyExtents() {
auto fusion = FusionGuard::getCurFusion();
for (const auto& ext_index : info_->getEmptyExtents()) {
auto ext = info_->initialInfo()->getMaybeZeroExtents().at(ext_index);
auto zero = fusion->zeroVal(ext->getDataType());
auto uses = ext->uses();
for (auto use : uses) {
ir_utils::replaceValInExprInputs(use, ext, zero);
}
// Register the concretization of this scalar, which allows us to replace it
// whenever it is used as an extent member of an IterDomain.
//
// When we ext in all uses above, it affects downstream expressions. For
// example we might replace i0 with 0 in (i0 + i1) + i2 to form (0 + i1) +
// i2. However, i0 itself might be used as the extent, start, or stop values
// in an IterDomain, so we register the concretization here so that we can
// replace these values whenever we encounter them.
registerConcretization(ext, zero);
}
}
TensorView* DynamicTransformConcretizer::concretizeNonEmptyReshape(
TensorView* inp_tv,
TensorView* incomplete_out_tv,
const AnalyzeViewResult& view_analysis) {
TensorView* concrete_reshape_out_tv = reshape(inp_tv, view_analysis);
// Inherit the mesh from the original output TV instead of the input TV. If
// the original output TV doesn't have a mesh, it's subject to sharding
// propagation so we should assign the new output TV an empty mesh.
// Otherwise, the original output TV has a user-specified sharding, which
// TransformReplay::selfReplay will clone (cf. #3950), and we should assign
// the output TV the same mesh.
concrete_reshape_out_tv->setDeviceMesh(incomplete_out_tv->getDeviceMesh());
// Extent expressions often change when concretizing a reshape. Here we
// replace these in all downstream expressions so that the Fusion looks just
// like it would have if we had used a static reshape instead.
//
// Note that Reduction IterDomains might be present in the concretized
// reshape. For example, suppose we are given the following dynamic Fusion
//
// Inputs:
// T0
// Outputs:
// T3
// T1[ iS2{i0} rS3{i1} ] = sum(T0[ iS0{i0} iS1{i1} ])
// T2[ ?S4{i2} ] = view(T1[ iS2{i0} rS3{i1} ])
// T3[ ?S4{i2} ] = -T2[ ?S4{i2} ]
//
// Then we will concretize this as
//
// Inputs:
// T0
// Outputs:
// T3
// T1[ iS2{i0} rS3{i1} ] = sum(T0[ iS0{i0} iS1{i1} ])
// T3[ iS4{i0} ] = -T1[ iS2{i0} rS3{i1} ]
//
// Notice here that the ReshapeOp is gone since we recognized that there is no
// transformation to perform. Instead, T1 is used directly in place of T2.
// We also replace the extent i2 from the dynamic reshape output T2 with i0,
// which is what the code below implements. Since T1 includes a Reduction
// IterDomain, we must ignore it in order to match ?S4{i2} with iS2{i0}.
auto old_logical = incomplete_out_tv->getLogicalDomain();
auto new_logical =
TensorDomain::noReductions(concrete_reshape_out_tv->getLogicalDomain());
NVF_ERROR(
old_logical.size() == new_logical.size(),
"Concretized reshape logical size does not match symbolic logical size");
TransformReplay::selfReplay(
incomplete_out_tv->domain(), concrete_reshape_out_tv->domain());
for (auto&& [old_id, new_id] : zip(old_logical, new_logical)) {
Val* old_extent = old_id->extent();
Val* new_extent = new_id->extent();
// If the old extent did not have a definition, we don't need to replace
// it, since it will get bound whenever this tensor is a segmentation
// edge.
//
// Also, if the old extent is already a constant, don't replace it with a
// non-constant, since this could cause downstream extents to become
// non-constant. See https://github.com/NVIDIA/Fuser/issues/1572
if (old_extent->definition() && !new_extent->sameAs(old_extent) &&
(!old_extent->isConstScalar() || new_extent->isConstScalar())) {
registerConcretization(old_extent, new_extent);
}
}
return concrete_reshape_out_tv;
}
TensorView* DynamicTransformConcretizer::concretizeEmptyReshape(
TensorView* inp_tv,
TensorView* incomplete_out_tv,
const std::vector<int64_t>& symbolic_sizes) {
std::vector<Val*> new_shape;
const std::vector<IterDomain*>& old_logical =
incomplete_out_tv->getLogicalDomain();
NVF_ERROR(symbolic_sizes.size() == old_logical.size());
new_shape.reserve(incomplete_out_tv->getLogicalDomain().size());
for (size_t i : arange(old_logical.size())) {
int64_t symbolic_size = symbolic_sizes[i];
if (symbolic_size == 0l) {
new_shape.push_back(inp_tv->fusion()->zeroVal(DataType::Index));
} else if (symbolic_size == 1l) {
new_shape.push_back(inp_tv->fusion()->oneVal(DataType::Index));
} else {
NVF_ERROR(symbolic_size == -1l);
IterDomain* id = incomplete_out_tv->getLogicalDomain().at(i);
new_shape.push_back(id->extent());
}
}
TensorView* concrete_reshape_out_tv = full(
new_shape, inp_tv->fusion()->zeroVal(inp_tv->dtype()), inp_tv->dtype());
const std::vector<IterDomain*>& new_logical =
concrete_reshape_out_tv->getLogicalDomain();
NVF_ERROR(symbolic_sizes.size() == new_logical.size());
for (size_t i : arange(symbolic_sizes.size())) {
int64_t symbolic_size = symbolic_sizes[i];
IterType iter_type =
symbolic_size == 1l ? IterType::Broadcast : IterType::Iteration;
IterDomain* new_id = new_logical[i];
Val* extent = symbolic_size == 0l
? new_id->fusion()->zeroVal(DataType::Index)
: maybeMutated(new_id->extent());
registerConcretization(old_logical[i]->extent(), extent);
if (!new_id->isSymbolic()) {
NVF_ERROR(new_id->getIterType() == iter_type);
continue;
}
// Concretize Symbolic IterDomains that were just created
registerConcretization(
new_id,
IterDomainBuilder(new_id).extent(extent).iter_type(iter_type).build());
}
return concrete_reshape_out_tv;
}
void DynamicTransformConcretizer::concretizeReshape() {