forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alias_analysis.cpp
2016 lines (1800 loc) · 64.3 KB
/
alias_analysis.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
#include <torch/csrc/jit/ir/alias_analysis.h>
#include <ATen/core/interned_strings.h>
#include <c10/util/flat_hash_map.h>
#include <c10/util/irange.h>
#include <torch/csrc/jit/api/function_impl.h>
#include <torch/csrc/jit/jit_log.h>
#include <torch/csrc/jit/passes/inliner.h>
#include <torch/csrc/jit/passes/utils/subgraph_utils.h>
#include <torch/csrc/jit/runtime/operator.h>
#include <torch/csrc/utils/memory.h>
#include <fstream>
namespace torch::jit {
namespace {
c10::MaybeOwned<TypePtr> toSingleType(const AliasTypeSet& mut_types) {
return mut_types.size() == 1
? c10::MaybeOwned<TypePtr>::borrowed(mut_types[0])
: c10::MaybeOwned<TypePtr>::owned(c10::UnionType::create(mut_types));
}
// This class determines whether a type is mutable, and, if so, it maps
// the type to its "mutable equivalent" (see definition in
// `mapTypeToAliasTypeSet`). It uses a cache of TypePtrs to speed up these
// type lookups
class MutableTypePtrHelper {
public:
explicit MutableTypePtrHelper(
ska::flat_hash_map<TypePtr, AliasTypeSet>* mutable_type_cache)
: mutable_type_cache_(mutable_type_cache) {}
// Map any mutable type to a type such that all other types which the
// mutable type can alias will be mapped to the same type. For
// example, calling this method on `Optional[List[int]]` should be
// the same as calling this method on `List[int]`.
//
// Rules:
// - If the type is not mutable, return `nullopt`
// - If the type is a `Tuple`, that means that it's an immutable
// object that can itself contain mutable objects. We want to make
// sure that the mutable objects are correctly aliased, so we
// remove the immutable objects. (For example,
// `Tuple[int, Tensor]` would become `Tuple[Tensor]`, while
// `Tuple[int, str]` would be returned as `nullopt`.) This is a
// convenience that makes it easy to check if the `Tuple`
// contains only immutable objects, though it's not technically
// necessary
// - For any Tensor type (including Tensor types that are part of
// a larger container, e.g. `List[Tensor]`), return the
// "unshaped" version of that Tensor. An "unshaped" Tensor is a
// Tensor with shape information removed. For example, a Tensor
// of dimension 4 would map to the same type as a Tensor of
// dimension 1. This allows us to treat all subclasses of Tensor
// as a single, homogenous "Tensor" type.
c10::optional<AliasTypeSet> mapTypeToAliasTypeSet(const TypePtr& type) {
if (mutable_type_cache_) {
const AliasTypeSet* result = mapTypeToBorrowedAliasTypeSet(type);
if (result) {
return *result;
}
}
return mapTypeToAliasTypeSetImpl(type);
}
const AliasTypeSet* mapTypeToBorrowedAliasTypeSet(const TypePtr& type) {
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(mutable_type_cache_ != nullptr);
auto maybe_type_mapping = mutable_type_cache_->find(type);
if (maybe_type_mapping != mutable_type_cache_->end()) {
return &maybe_type_mapping->second;
}
auto mutable_types = mapTypeToAliasTypeSetImpl(type);
if (mutable_types) {
auto it =
mutable_type_cache_->emplace(type, std::move(*mutable_types)).first;
return &it->second;
} else {
return nullptr;
}
}
private:
c10::optional<AliasTypeSet> mapTypeToAliasTypeSetImpl(const TypePtr& type) {
switch (type->kind()) {
case TypeKind::ListType:
case TypeKind::DictType:
case TypeKind::ClassType:
case TypeKind::TensorType:
// TODO: Look up cached contained types. this is kind of tricky
// because a `List[Optional[T]]` should still be
// `List[Optional[Unshaped(T)]]`, but
// `mapTypeToAliasTypeSet(Optional[T])` should be `T`
return AliasTypeSet{unshapedType(type)};
case TypeKind::UnionType: {
AliasTypeSet mutable_types;
for (const TypePtr& inner :
type->expectRef<UnionType>().containedTypes()) {
if (auto maybe_inner_types = mapTypeToAliasTypeSet(inner)) {
mutable_types.insert(
mutable_types.end(),
(*maybe_inner_types).begin(),
(*maybe_inner_types).end());
}
}
if (mutable_types.empty()) {
return c10::nullopt;
}
return mutable_types;
}
case TypeKind::OptionalType: {
auto inner = type->castRaw<OptionalType>()->getElementType();
return mapTypeToAliasTypeSet(inner);
}
case TypeKind::AnyType:
return {AliasTypeSet{type}};
case TypeKind::FutureType: {
if (auto maybe_mut_types = mapTypeToAliasTypeSet(
type->castRaw<FutureType>()->getElementType())) {
return {AliasTypeSet{
FutureType::create(*toSingleType(*maybe_mut_types))}};
}
return c10::nullopt;
}
case TypeKind::AwaitType: {
if (auto maybe_mut_types = mapTypeToAliasTypeSet(
type->castRaw<AwaitType>()->getElementType())) {
return {
AliasTypeSet{AwaitType::create(*toSingleType(*maybe_mut_types))}};
}
return c10::nullopt;
}
case TypeKind::TupleType: {
std::vector<TypePtr> mutable_types;
for (const TypePtr& inner : type->expectRef<TupleType>().elements()) {
if (auto maybe_inner_types = mapTypeToAliasTypeSet(inner)) {
mutable_types.insert(
mutable_types.end(),
(*maybe_inner_types).begin(),
(*maybe_inner_types).end());
}
}
if (mutable_types.empty()) {
return c10::nullopt;
}
return {AliasTypeSet{TupleType::create(mutable_types)}};
}
default:
return c10::nullopt;
}
}
ska::flat_hash_map<TypePtr, AliasTypeSet>* mutable_type_cache_;
};
bool isMutableTypeImpl(
const TypePtr& type,
ska::flat_hash_map<TypePtr, AliasTypeSet>* mutable_type_cache) {
// Check common cases to avoid recursively constructing type in
// `mapTypeToAliasTypeSetPtrImpl`
auto kind = type->kind();
if (kind == TypeKind::TensorType || kind == TypeKind::ListType ||
kind == TypeKind::ClassType || kind == TypeKind::DictType) {
return true;
}
MutableTypePtrHelper helper(mutable_type_cache);
if (mutable_type_cache) {
return helper.mapTypeToBorrowedAliasTypeSet(type) != nullptr;
} else {
return helper.mapTypeToAliasTypeSet(type).has_value();
}
}
} // namespace
// Static `isMutableType` does not use cache of type -> mutable type equivalent
bool AliasDb::isMutableType(const TypePtr& type) {
return isMutableTypeImpl(type, nullptr);
}
bool AliasDb::isMutableType(const Value* v) {
return isMutableType(v->type());
}
// Make use of type -> mutable cache
bool AliasDb::isMutableTypeInternal(const TypePtr& type) const {
return isMutableTypeImpl(type, &mapped_mutable_types_);
}
bool AliasDb::isMutableTypeInternal(const Value* v) const {
return isMutableTypeInternal(v->type());
}
const AliasTypeSet* AliasDb::mapTypeToAliasTypeSetPtr(
const TypePtr& type) const {
MutableTypePtrHelper helper(&mapped_mutable_types_);
return helper.mapTypeToBorrowedAliasTypeSet(type);
}
AliasDb::~AliasDb() = default;
// Structure used during analysis to keep track of all writes at a high
// level. When the analysis is completed, this will be used to construct
// a more efficient WriteIndex
struct AliasDb::WriteRegistry {
void registerWrite(const Value* v, Node* n) {
writes_[n].emplace_back(v);
}
void registerWriteToAllContained(const Value* v, Node* n) {
containedWrites_[n].emplace_back(v);
}
void registerWriteToAllWildcards(Node* n) {
writesToAllWildcards_.insert(n);
}
std::unordered_map<Node*, std::vector<const Value*>> writes_;
std::unordered_map<Node*, std::vector<const Value*>> containedWrites_;
std::unordered_set<Node*> writesToAllWildcards_;
};
AliasDb::AliasDb(
std::shared_ptr<Graph> graph,
bool isFrozen,
bool descendFunctionCalls)
: graph_(std::move(graph)),
isFrozen_(isFrozen),
descend_function_calls_(descendFunctionCalls),
memoryDAGBuilder_(std::make_unique<MemoryDAGBuilder>()),
writeRegistry_(std::make_unique<AliasDb::WriteRegistry>()) {
analyze(graph_);
memoryDAG_ = std::make_unique<MemoryDAG>(std::move(memoryDAGBuilder_));
memoryDAGBuilder_ = nullptr; // to make further access a hard error
memoryDAG_->setWildcards(
wildcards_, elementMap_, [&](const Value* v) -> Element* {
return getWildcard(v->type());
});
// Now we build up the various write indices based on information in the write
// registry that we populated during analysis
// Initialize the write index
writeIndex_ = TWriteIndex();
auto& writeIndex = *writeIndex_; // to make operator[] less ugly
// Build the write index
for (const auto& write : writeRegistry_->writes_) {
Node* node = write.first;
const std::vector<const Value*> writtenValues = write.second;
for (const Value* writtenValue : writtenValues) {
auto it = elementMap_.find(writtenValue);
TORCH_INTERNAL_ASSERT(
it != elementMap_.end(), "Tried to write to value not in MemoryDAG");
const auto& writtenMemoryLocations =
memoryDAG_->getMemoryLocations(it->second);
writeIndex[node] |= writtenMemoryLocations;
}
}
for (const auto& write : writeRegistry_->containedWrites_) {
Node* node = write.first;
const std::vector<const Value*>& writtenValues = write.second;
for (const Value* writtenValue : writtenValues) {
auto elem = elementMap_.at(writtenValue);
MemoryLocations writtenMemoryLocations;
memoryDAG_->collectAllContainedMemoryLocations(
elem, writtenMemoryLocations);
writeIndex[node] |= writtenMemoryLocations;
}
}
for (const auto& write : writeRegistry_->writesToAllWildcards_) {
for (const auto& pr : wildcardIndex_) {
writeIndex[write].set(pr.second->index);
}
}
// Now that we've built the write index, we can null out the WriteRegistry to
// make future access an error. In this way we prevent the index from getting
// out of sync (since we have no way of registering new writes)
writeRegistry_ = nullptr;
// Initialize the write cache
buildWrittenToLocationsIndex();
GRAPH_DEBUG(toString());
}
bool AliasDb::isMutable(Node* n) const {
ValueSet vs;
for (const auto input : n->inputs()) {
vs.insert(input);
}
return writesToAlias(n, vs);
}
bool AliasDb::hasInputWriters(const Node* n) const {
for (const auto input : n->inputs()) {
if (hasWriters(input)) {
return true;
}
}
return false;
}
bool AliasDb::hasOutputWriters(const Node* n) const {
for (const auto output : n->outputs()) {
if (hasWriters(output)) {
return true;
}
}
return false;
}
bool AliasDb::hasWriters(const Node* n) const {
return hasInputWriters(n) || hasOutputWriters(n);
}
bool AliasDb::hasWriters(const Value* v) const {
if (v->mustBeNone()) {
return false;
}
auto it = elementMap_.find(v);
if (it == elementMap_.end()) {
return false;
}
const auto& el = it->second;
return writtenToLocationsIndex_->intersects(
memoryDAG_->getMemoryLocations(el));
}
void AliasDb::getWritesImpl(Node* n, MemoryLocations& ret) const {
if (writeIndex_->count(n)) {
const auto& writes = writeIndex_->at(n);
ret |= writes;
}
for (auto block : n->blocks()) {
for (auto node : block->nodes()) {
getWritesImpl(node, ret);
}
}
}
// Does `n` write to an alias of one of the values in `vs`?
bool AliasDb::writesToAlias(Node* n, const ValueSet& vs) const {
const auto writtenTo = getWrites(n);
if (writtenTo.empty()) {
return false;
}
MemoryLocations locs;
for (const auto v : vs) {
auto it = elementMap_.find(v);
if (it != elementMap_.end()) {
const auto& vlocs = memoryDAG_->getMemoryLocations(it->second);
if (writtenTo.intersects(vlocs)) {
return true;
}
}
}
return false;
}
MemoryLocations AliasDb::getWrites(Node* n) const {
MemoryLocations writes;
getWritesImpl(n, writes);
return writes;
}
void AliasDb::getReadsImpl(Node* n, MemoryLocations& ret) const {
for (const auto input : n->inputs()) {
auto it = elementMap_.find(input);
if (it != elementMap_.end()) {
auto el = it->second;
// Add all memory locations this element may alias and their contained
// elements
memoryDAG_->collectAllContainedMemoryLocations(el, ret);
}
}
for (auto block : n->blocks()) {
for (auto node : block->nodes()) {
getReadsImpl(node, ret);
}
}
}
MemoryLocations AliasDb::getReads(Node* n) const {
MemoryLocations reads;
getReadsImpl(n, reads);
return reads;
}
std::string AliasDb::getElementName(const Element* e) const {
if (e->values.empty()) {
// Not the most efficient way, but given the fact there are
// not too many types and even fewer of them will end up in
// `wildcardIndex_`, we should be fine with a linear search
// each time we hit a Wildcard leaf
for (const auto& ent : wildcardIndex_) {
if (ent.second == e) {
return std::string("WILDCARD for type ") + ent.first->str();
}
}
return "WILDCARD";
} else {
std::ostringstream ss;
if (e->values.size() == 1) {
ss << "%" << (*e->values.begin())->debugName();
return ss.str();
}
ss << "(";
for (const Value* v : e->values) {
ss << "%" << v->debugName() << ", ";
}
ss << ")";
return ss.str();
}
}
void AliasDb::dump() const {
std::cout << toString();
}
std::string AliasDb::toString() const {
std::stringstream ss{};
ss << "\n===1. GRAPH===\n";
ss << graph_->toString();
ss << "\n===2. ALIAS DB===\n";
for (const auto& ptrPair : elementMap_) {
const auto element = ptrPair.second;
int ct = 0;
if (!element->pointsTo.empty()) {
ss << getElementName(element) << " points to: ";
for (const auto pointedTo : element->pointsTo) {
if (ct > 0) {
ss << ", ";
}
++ct;
ss << getElementName(memoryDAG_->fromIndex(pointedTo));
}
ss << "\n";
}
ct = 0;
if (!element->containedElements.empty()) {
ss << getElementName(element) << " contains: ";
for (const auto contained : element->containedElements) {
ss << getElementName(memoryDAG_->fromIndex(contained));
if (ct > 0) {
ss << ", ";
}
++ct;
}
ss << "\n";
}
}
ss << "\n===3. Writes===\n";
for (const auto& pr : *writeIndex_) {
const auto node = pr.first;
const auto& values = pr.second;
ss << *node;
ss << " ";
for (const auto value : values) {
ss << getElementName(memoryDAG_->fromIndex(value)) << ", ";
}
ss << "\n";
}
ss << "\n";
return ss.str();
}
bool AliasDb::dumpToGraphvizFile(const char* filename) const {
std::ofstream dot_file(filename);
if (!dot_file.good()) {
std::cout << "Failed to create Graphviz file: '" << filename << "'\n";
return false;
}
dot_file << toGraphviz();
return true;
}
std::string AliasDb::toGraphviz() const {
std::stringstream dot;
// Local helper to generate a graphviz-friendly name encoding
// See also AliasDb::getElementName()
const auto name = [this](const Element* e) -> std::string {
if (e->values.empty()) {
for (const auto& ent : wildcardIndex_) {
if (ent.second == e) {
return std::string("\"WILDCARD for ") + ent.first->str() + "\"";
}
}
return "\"WILDCARD\"";
} else {
std::ostringstream ss;
if (e->values.size() == 1) {
ss << "\"\\%" << (*e->values.begin())->debugName() << "\"";
return ss.str();
}
ss << "\"(";
for (const Value* v : e->values) {
ss << "\\%" << v->debugName() << ", ";
}
ss << ")\"";
return ss.str();
}
};
// Include the textual representation for reference
dot << "/*\n";
dot << toString();
dot << "*/\n";
dot << "digraph alias_db {\n"
<< " rankdir=LR\n"
<< " node [shape=rect, color=gray];\n"
<< " edge [color=black];\n";
for (const auto& ptrPair : elementMap_) {
const auto element = ptrPair.second;
if (!element->pointsTo.empty()) {
for (const auto pointedTo : element->pointsTo) {
dot << " " << name(element) << " -> "
<< name(memoryDAG_->fromIndex(pointedTo)) << "\n";
}
}
if (!element->containedElements.empty()) {
for (const auto contained : element->containedElements) {
dot << " " << name(element) << " -> "
<< name(memoryDAG_->fromIndex(contained))
<< " [style=dashed, color=blue]\n";
}
}
}
dot << "}\n";
return dot.str();
}
void AliasDb::analyze(const std::shared_ptr<Graph>& graph) {
for (auto input : graph->inputs()) {
setWildcard(input);
}
analyze(graph->block());
}
void AliasDb::analyze(Block* block) {
for (auto node : block->nodes()) {
analyze(node);
}
}
void AliasDb::analyze(Node* node) {
analyzeImpl(node);
}
// Returns true if analysis was run using
// the registered analyzer.
bool AliasDb::tryRegisteredAnalysis(Node* node) {
const Operator& op = node->getOperator();
auto analysis = op.aliasAnalysisKind();
if (AliasAnalysisKind::PURE_FUNCTION == analysis) {
analyzeCreator(node);
return true;
}
return false;
}
// The basic strategy is:
// 1. Retrieve alias information for every input.
// 2. Use the node's schema's alias annotations to propgagate alias/write
// information to the outputs. For unschematized nodes, a special analyzer
// will have to be handwritten.
void AliasDb::analyzeImpl(Node* node) {
auto op = node->maybeOperator();
const bool hasSpecialCase = aliasAnalysisHasSpecialCaseFor(node->kind());
if (op) {
const auto analysis = op->aliasAnalysisKind();
const bool registeredAsSpecialCase =
analysis == AliasAnalysisKind::INTERNAL_SPECIAL_CASE;
if (C10_UNLIKELY(registeredAsSpecialCase && !hasSpecialCase)) {
TORCH_INTERNAL_ASSERT(
false,
"Op ",
node->kind().toDisplayString(),
" is registered with AliasAnalysisKind::INTERNAL_SPECIAL_CASE but doesn't have a special case.");
} else if (C10_UNLIKELY(!registeredAsSpecialCase && hasSpecialCase)) {
TORCH_INTERNAL_ASSERT(
false,
"Op ",
node->kind().toDisplayString(),
" has a special case and should be registered with AliasAnalysisKind::INTERNAL_SPECIAL_CASE but is registered with ",
c10::toString(analysis));
}
} else {
if (!hasSpecialCase) {
std::ostringstream oss;
for (const auto input : node->inputs()) {
oss << input->type()->str() << ", ";
}
oss << "\n\nCandidates:";
const auto& candidates = getAllOperatorsFor(node->kind());
for (const auto& candidate : candidates) {
oss << "\n\t" << candidate->schema();
}
TORCH_INTERNAL_ASSERT(
0,
"We don't have an op for ",
node->kind().toDisplayString(),
" but it isn't a special case. ",
"Argument types: ",
oss.str());
}
}
// These nodes are not schematized, so we need to handle them specially
switch (node->kind()) {
case prim::If:
return analyzeIf(node);
case prim::Loop:
return analyzeLoop(node);
case prim::FusionGroup:
case prim::CudaFusionGroup:
case prim::oneDNNFusionGroup:
case prim::FunctionalGraph:
case prim::DifferentiableGraph:
case prim::FallbackGraph:
return analyzeSubgraph(node);
case prim::fork:
return analyzeFork(node);
case aten::wait:
return analyzeWait(node);
case prim::awaitable:
case prim::awaitable_nowait:
return analyzeAwaitable(node);
case prim::awaitable_wait:
return analyzeAwaitableWait(node);
case prim::rpc_async:
case prim::rpc_sync:
case prim::rpc_remote:
return analyzeRpcAsync(node);
case aten::batch_norm:
return analyzeBatchNorm(node);
case aten::instance_norm:
return analyzeInstanceNorm(node);
case prim::GradOf:
return analyzeGradOf(node);
case prim::BroadcastMKLDNNTensors: {
makePointerTo(node->outputs().at(0), node->inputs().at(0));
makePointerTo(node->outputs().at(1), node->inputs().at(1));
return;
}
// TODO: think more about TensorExpr alias correctness
case prim::TensorExprGroup:
case prim::TensorExprDynamicGroup:
case prim::MKLDNNGroup:
case prim::ConstantMKLDNNTensor:
case prim::StaticSubgraph:
case prim::Constant:
case prim::AutogradZero:
case prim::AutogradAdd:
case prim::FusedConcat:
case prim::MMTreeReduce:
case prim::MMBatchSide:
case prim::BroadcastSizes:
case prim::ChunkSizes:
// this should never be seen outside of initial compilation
// but because of some dependencies with closure invoking alias
// db needs to be handled here
case prim::EmptyListLiteral:
case prim::Closure:
case prim::CreateObject:
case prim::tolist:
case prim::Uninitialized:
return analyzeCreator(node);
case prim::TupleConstruct:
case prim::DictConstruct:
case prim::ListConstruct:
return analyzeContainerConstruct(node);
case prim::TupleUnpack:
case prim::TupleIndex:
case prim::TupleSlice:
case prim::ListUnpack:
case prim::PythonOp:
case prim::GetAttr:
if (isFrozen_ && node->kind() == prim::GetAttr) {
auto& ty = node->input()->type();
if (ty->expectRef<ClassType>().is_module()) {
return analyzeCreator(node);
}
}
return analyzeExtractor(node);
case prim::unchecked_cast:
return makePointerTo(node->output(), node->input());
case prim::ConstantChunk:
return analyzeChunk(node);
case prim::BroadcastingChunk:
return analyzeBroadcastingChunk(node);
case prim::SetAttr:
return analyzeSetAttr(node);
case prim::profile_ivalue:
case prim::profile:
makePointerTo(node->output(), node->inputs().at(0));
return;
case prim::TypeCheck:
case prim::RequiresGradCheck: {
auto num_inputs = node->inputs().size();
for (const auto i : c10::irange(num_inputs)) {
makePointerTo(node->outputs().at(i), node->inputs().at(i));
}
return;
}
case prim::BailOut:
TORCH_INTERNAL_ASSERT(
node->inputs().at(0)->node()->kind() == prim::BailoutTemplate);
makePointerTo(node->output(), node->inputs().at(1));
return;
case prim::Guard:
makePointerTo(node->output(), node->inputs().at(0));
return;
case prim::CallFunction:
case prim::CallMethod: {
// TODO: this can be improved with summarizes of what the function does
// for now we assume the worst
if (!descend_function_calls_) {
return analyzeConservative(node);
}
auto g = tryToGraphFunction(node);
if (!g) {
return analyzeConservative(node);
}
// this is an unoptimized path - we copy the subgraph for each function
// call past the first - so we do not generally enable the recursive
// analysis. use cases for fine-grained alias analysis without inlining
// are very uncommon
auto graph = g->optimized_graph();
// alias analysis will use Value* as mappings for information,
// so for each analysis of a particular function call we need a new graph
// for all copies made, store them for duration of analysis so we do not
// run into lifetime issues with the graph
std::vector<std::shared_ptr<Graph>>& graphs =
function_call_copies_[graph.get()];
if (graphs.empty()) {
graphs.push_back(graph);
analyzeSubgraph(node, graph);
} else {
auto copied_graph = graph->copy();
graphs.push_back(copied_graph);
analyzeSubgraph(node, copied_graph);
}
return;
}
case prim::Enter:
case prim::Exit:
// TODO: this can be improved with summarizes of what the function does
// for now we assume the worst
// NB: update safeToChangeAliasingRelationship if changed
return analyzeConservative(node);
case prim::Print:
case prim::isinstance:
// These ops do nothing
return;
default:
if (tryRegisteredAnalysis(node)) {
return;
}
}
TORCH_INTERNAL_ASSERT(op, "We should have an op schema if we get to here");
const AliasAnalysisKind analysis = op->aliasAnalysisKind();
TORCH_INTERNAL_ASSERT(
analysis != AliasAnalysisKind::INTERNAL_SPECIAL_CASE &&
!aliasAnalysisHasSpecialCaseFor(node->kind()),
"Special cases should be handled already if we're here.");
if (node->kind().is_aten() || node->kind().is_prim() ||
node->kind().is_cuda()) {
// TODO There is nothing in the system that relies on aten:: and prim::
// ops using AliasAnalysisKind::FROM_SCHEMA or
// AliasAnalysisKind::INTERNAL_SPECIAL_CASE, but this is the intended
// behavior for all current ops and a good error check. We can consider
// lifting this constraint later if we have a use case for it.
TORCH_INTERNAL_ASSERT(
analysis == AliasAnalysisKind::FROM_SCHEMA ||
analysis == AliasAnalysisKind::CONSERVATIVE,
"aten:: and prim:: operators should use AliasAnalysisKind::FROM_SCHEMA or "
"AliasAnalysisKind::CONSERVATIVE(if really necessary), but ",
node->kind().toDisplayString(),
" doesn't. Note: Ideally, prim:: operators actually shouldn't have a schema ",
"and then use AliasAnalysisKind::INTERNAL_SPECIAL_CASE instead.");
}
if (analysis == AliasAnalysisKind::CONSERVATIVE) {
// TODO A previous implementation of alias analysis always accessed
// node->schema , which cause the schema caches in the Node class to be
// filled for the full graph. Unfortunately, our JIT passes started relying
// on that, so we need to keep doing this. Details: in
// caffe2/torch/onnx/utils.py, _jit_pass_onnx is called on an invalid JIT
// graph because we called _jit_pass_erase_number_types right before and
// ints are now Tensors instead. So if _jit_pass_onnx tries to look up
// operator schemas, it will crash. However, _jit_pass_constant_propagation,
// which is called before it, runs alias analysis and prefills the schema
// cache in the all Node instances so that _jit_pass_onnx doesn't look up
// operators to get the schemas anymore. We should fix this.
node->schema(); // fill the schema cache in the Node class
return analyzeConservative(node);
}
TORCH_INTERNAL_ASSERT(
analysis == AliasAnalysisKind::FROM_SCHEMA,
"AliasAnalysisKind::CONSERVATIVE/PURE_FUNCTION/INTERNAL_SPECIAL_CASE should already have been handled above");
const auto& schema = node->schema();
// Bind the schema's "formal" alias annotation to the actual values those
// schema arguments represent
std::unordered_map<Symbol, Value*> formalToActual;
for (const auto i : c10::irange(schema.arguments().size())) {
const at::AliasInfo* formal = schema.arguments()[i].alias_info();
const auto& actualValue = node->inputs().at(i);
// Skip if there's no alias annotation
if (!formal) {
continue;
}
// If this type cannot alias, continue. Can occur with a VarType schema
if (!isMutableTypeInternal(actualValue)) {
continue;
}
// Do sanity checks on the alias annotation
TORCH_INTERNAL_ASSERT(
formal->containedTypes().size() <= 1,
"Composite types for alias analysis not yet supported");
TORCH_INTERNAL_ASSERT(
!formal->isWildcardBefore(),
"Doesn't make sense for a input value to begin as a wildcard");
// This is a special case where we have alias info before [] but not after,
// such as `Tensor(a!)[]`
if (formal->containedTypes().size() == 1 && formal->beforeSets().empty()) {
// Use the first containedType in alias info.
formal = &(formal->containedTypes()[0]);
}
const auto& formalAlias = formal->beforeSet();
// skip if we've already bound this alias
if (formalToActual.count(formalAlias) != 0) {
continue;
}
// Bind the formal to the actual
formalToActual[formalAlias] = actualValue;
// Record writes
if (formal->isWrite()) {
registerWrite(actualValue, node);
}
// Now deal with sets after the '->'
if (formal->isWildcardAfter()) {
TORCH_INTERNAL_ASSERT(
formal->afterSets().size() == 1,
"If the after set contains a wildcard, "
"there should be no other alias sets specified.");
setWildcard(actualValue);
} else {
// We don't understand anything else in the after yet, so assert there's
// been no change.
TORCH_INTERNAL_ASSERT(formal->beforeSets() == formal->afterSets());
}
}
// Use the formal-actual mapping to give aliases to the outputs
for (const auto i : c10::irange(schema.returns().size())) {
const auto actual = node->outputs().at(i);
const at::AliasInfo* formal = schema.returns()[i].alias_info();
if (!formal) {
// This is a fresh tensor
giveFreshAlias(actual);
continue;
}
// If this type cannot alias, continue. Can occur with a VarType schema
if (!isMutableType(actual)) {
continue;
}
TORCH_INTERNAL_ASSERT(
formal->containedTypes().size() <= 1,
"Composite types for alias analysis not yet supported");
TORCH_INTERNAL_ASSERT(formal->beforeSets() == formal->afterSets());
if (formal->containedTypes().size() == 1 && formal->beforeSets().empty()) {
// Use the first containedType in alias info.
formal = &(formal->containedTypes()[0]);
}
if (formal->isWildcardBefore()) {
TORCH_INTERNAL_ASSERT(
formal->beforeSets().size() == 1,
"If an output is a wildcard, "
"there should be no other alias sets specified.");
setWildcard(actual);
continue;
}
bool inputs_has_alias = false;
for (const auto& formalAlias : formal->beforeSets()) {
if (formalToActual.count(formalAlias)) {
inputs_has_alias = true;
auto toAlias = formalToActual.at(formalAlias);
makePointerTo(actual, toAlias);
}
}
// If all the alias annotation that we encounter weren't in the inputs:
// e.g. foo(Tensor(a) self) -> Tensor(b)
// or foo(Tensor(a) self) -> Tensor(b|c)
// Otherwise it is the form of a|fresh, which we can ignore, taking the
// conservative assumption that the output must alias `a`, e.g
// aten::cuda(Tensor(a) self) -> Tensor(a|fresh)
if (!inputs_has_alias && !formal->beforeSets().empty()) {
giveFreshAlias(actual);
}
// Record writes
if (formal->isWrite()) {
registerWrite(actual, node);
}
}
}
// Register the fact that `n` writes to `v`.
void AliasDb::registerWrite(const Value* v, Node* n, bool writeToContained) {
if (!isMutableTypeInternal(v)) {
// don't need to register a write if the value isn't mutable
return;
}
if (writeToContained) {
writeRegistry_->registerWriteToAllContained(v, n);
} else {
writeRegistry_->registerWrite(v, n);
}
}
void AliasDb::analyzeIf(Node* node) {
// For if statements, the alias set of an output is the union of the
// alias sets generated by the if and else block
const auto trueBlock = node->blocks().at(0);
const auto falseBlock = node->blocks().at(1);
analyze(trueBlock);
analyze(falseBlock);
for (const auto i : c10::irange(node->outputs().size())) {
const auto nodeOutput = node->outputs()[i];
const auto trueOutput = trueBlock->outputs().at(i);
const auto falseOutput = falseBlock->outputs().at(i);
makePointerTo(nodeOutput, trueOutput);
makePointerTo(nodeOutput, falseOutput);
}
}
void AliasDb::analyzeLoop(Node* node) {
const auto bodyBlock = node->blocks().at(0);
const auto loopCarriedInputs = node->inputs().slice(2); // skip max, cond
const auto blockInputs = bodyBlock->inputs().slice(1); // skip trip
const auto blockOutputs = bodyBlock->outputs().slice(1); // skip trip
TORCH_INTERNAL_ASSERT(loopCarriedInputs.size() == blockInputs.size());
TORCH_INTERNAL_ASSERT(blockOutputs.size() == node->outputs().size());
// Run alias analysis on the loop body, iterating until the block output
// alias info converges. Copy node input aliases to block input
mapAliases(blockInputs, loopCarriedInputs);
// Populate block output alias info by analyzing the body
analyze(bodyBlock);
// Copy the alias info from the block output to the node output
mapAliases(node->outputs(), blockOutputs);
}
void AliasDb::analyzeGradOf(Node* node) {
const auto grad_of_block = node->blocks().at(0);
analyze(grad_of_block);
mapAliases(node->outputs(), grad_of_block->outputs());
}
void AliasDb::analyzeSubgraph(Node* node, std::shared_ptr<Graph> subgraph) {
const auto subgraphBlock = subgraph->block();
// CallFunction nodes have an extra first parameter