forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ir.cpp
1854 lines (1654 loc) · 52.6 KB
/
ir.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.h>
#include <c10/util/Exception.h>
#include <c10/util/StringUtil.h>
#include <torch/csrc/jit/constants.h>
#include <torch/csrc/jit/function.h>
#include <torch/csrc/jit/operator.h>
#include <torch/csrc/jit/passes/python_print.h>
#include <torch/csrc/jit/script/schema_matching.h>
#include <algorithm>
#include <iostream>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
namespace torch {
namespace jit {
// Constants relating to maintaining the topological index of nodes.
//
// Lower and upper bounds of the index. Inclusive range.
static constexpr topo_position_t kLowerBound = INT64_MIN;
static constexpr topo_position_t kUpperBound = INT64_MAX;
static constexpr topo_position_t kMidPoint = 0;
// How far away to space nodes that are appended to the graph.
// should be 2^n, where:
// - n is the maximum number of repeated insertions without a re-index
// - 2^(64-n) is the maximum number of appends to the end without reindex
static constexpr topo_position_t kAppendInterval = 1099511627776ULL /* 2^40 */;
static void printValueRef(std::ostream& out, const Value* n) {
out << "%" << n->debugName();
}
// NB: This overload will become ambiguous with the one Caffe2 provides in its
// logging, if they ever intersect.
template <typename T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& nodes) {
out << at::ArrayRef<T>{nodes};
return out;
}
template <typename T>
static std::ostream& printValueRefs(
std::ostream& out,
const at::ArrayRef<T> nodes) {
size_t i = 0;
for (auto n : nodes) {
if (i++ > 0) {
out << ", ";
}
printValueRef(out, n);
}
return out;
}
// Can't make these two overloads directly a template, it'll be ambiguous with
// the global printer for operator<<.
std::ostream& operator<<(
std::ostream& out,
const at::ArrayRef<const Value*> nodes) {
return printValueRefs(out, nodes);
}
std::ostream& operator<<(std::ostream& out, const at::ArrayRef<Value*> nodes) {
return printValueRefs(out, nodes);
}
struct const_value_list_with_types {
const ArrayRef<const Value*> values;
std::string delim;
const_value_list_with_types(
ArrayRef<const Value*> values,
std::string delim_ = ", ")
: values(values), delim(std::move(delim_)) {}
};
std::ostream& operator<<(
std::ostream& out,
const const_value_list_with_types& l) {
size_t i = 0;
for (auto n : l.values) {
if (i++ > 0) {
out << l.delim;
}
printValueRef(out, n);
out << " : ";
out << *n->type();
}
return out;
}
static void printAttribute(std::ostream& out, const at::Tensor& tensor) {
// 1-elem tensors are usually boxed scalars, so print them like it
if (tensor.numel() == 1) {
auto scalar_tensor = tensor.view({}).item();
out << "{";
if (scalar_tensor.isFloatingPoint()) {
out << scalar_tensor.toDouble();
} else {
out << scalar_tensor.toLong();
}
out << "}";
} else if (tensor.numel() <= max_tensor_display_size) {
// TODO: This is awful code. Also it doesn't work on Windows.
std::ostringstream tensor_ss;
tensor_ss << tensor;
std::string tensor_s{tensor_ss.str()};
// Remove newlines
std::replace(tensor_s.begin(), tensor_s.end(), '\n', ' ');
out << tensor_s;
} else {
out << "<Tensor>";
}
}
static void printAttribute(std::ostream& out, const IValue& ival) {
const auto customFormatter = [](std::ostream& ss, const IValue& input) {
if (input.isTensor()) {
printAttribute(ss, input.toTensor());
return true;
} else if (input.isTensorList()) {
ss << "[<Tensors>]";
return true;
}
return false;
};
ival.repr(out, customFormatter);
}
static void printTypeList(
std::ostream& out,
const std::vector<TypePtr>& items) {
out << "[";
int i = 0;
for (auto& item : items) {
if (i++ > 0)
out << ", ";
out << *item;
}
out << "]";
}
void Node::printAttrValue(std::ostream& out, const Symbol& name) const {
switch (kindOf(name)) {
case AttributeKind::f:
printAttribute(out, f(name));
break;
case AttributeKind::fs:
printAttribute(out, fs(name));
break;
case AttributeKind::i:
printAttribute(out, i(name));
break;
case AttributeKind::is:
printAttribute(out, is(name));
break;
case AttributeKind::s:
printAttribute(out, s(name));
break;
case AttributeKind::ss:
printAttribute(out, ss(name));
break;
case AttributeKind::t:
printAttribute(out, t(name));
break;
case AttributeKind::ts:
out << "[<Tensors>]";
break;
case AttributeKind::ival:
printAttribute(out, ival(name));
break;
case AttributeKind::g:
out << "<Graph>";
break;
case AttributeKind::gs:
out << "[<Graphs>]";
break;
case AttributeKind::ty:
out << *ty(name);
break;
case AttributeKind::tys:
printTypeList(out, tys(name));
break;
}
}
void Node::printAttributes(std::ostream& out, bool ignore_subgraph = false)
const {
out << "[";
auto names = attributeNames();
int i = 0;
for (auto name : names) {
if (ignore_subgraph && name == attr::Subgraph) {
continue;
}
if (i++ > 0) {
out << ", ";
}
// TODO: debugging mode to see the qualifier. We definitely
// don't want to print the qualifier since it should always
// be attribute, but you might be able to track down a weird
// bug by printing it out.
out << name.toUnqualString() << "=";
printAttrValue(out, name);
}
out << "]";
}
SourceRange Node::sourceRange() const {
if (source_range_) {
return *source_range_;
}
return SourceRange();
}
static std::ostream& indent(std::ostream& out, size_t level) {
for (size_t i = 0; i < level; ++i) {
out << " ";
}
return out;
}
std::ostream& Node::print(
std::ostream& out,
size_t level,
std::vector<const Node*>* groups,
bool print_source_locations,
bool print_attributes,
bool print_scopes,
bool print_body) const {
auto outs = outputs();
indent(out, level) << const_value_list_with_types(outs);
out << " = ";
if (kind() == prim::PythonOp) {
auto* pyOp = static_cast<const ::torch::jit::PythonOp*>(this);
out << "^" << pyOp->name();
pyOp->writeScalars(out);
} else if (hasAttribute(attr::Subgraph) && groups) {
out << kind().toQualString() << "_" << groups->size();
if (print_attributes && numAttributes() > 1 &&
kind() != prim::DifferentiableGraph) {
printAttributes(out, /*ignore_subgraph=*/true);
}
groups->push_back(this);
} else {
out << kind().toQualString();
if (print_attributes && hasAttributes()) {
printAttributes(out);
}
}
out << "(" << inputs() << ")";
if (print_scopes) {
std::string scName = scopeName();
if (!scName.empty()) {
out << ", ";
out << "scope: " << scName;
}
}
// In debug print, append file:line:col as a comment after each node
if (print_source_locations) {
SourceRange r = sourceRange();
if (sourceRange().source()) {
if (auto orig = sourceRange().source()->findSourceRangeThatGenerated(r)) {
r = *orig;
}
}
if (auto file_line_col = r.file_line_col()) {
std::string filename;
size_t line, col;
std::tie(filename, line, col) = *file_line_col;
out << " # " << filename << ":" << line << ":" << col;
}
}
if (!print_body) {
return out;
}
out << "\n";
for (size_t i = 0; i < blocks().size(); ++i) {
auto b = blocks()[i];
indent(out, level + 1) << "block" << i << "("
<< const_value_list_with_types(b->inputs())
<< "):\n";
for (auto nested : b->nodes()) {
nested->print(out, level + 2, groups);
}
indent(out, level + 2) << "-> (" << b->outputs() << ")\n";
}
return out;
}
std::ostream& operator<<(std::ostream& out, const Node& n) {
return n.print(out, 0, nullptr);
}
std::ostream& Graph::print(std::ostream& out, bool print_source_locations)
const {
out << "graph(" << const_value_list_with_types(inputs(), ",\n ")
<< "):\n";
std::vector<const Node*> groups;
for (auto n : nodes()) {
n->print(out, 1, &groups, print_source_locations);
}
out << " return (" << outputs() << ")\n";
size_t i = 0;
for (auto fg : groups) {
out << "with " << fg->kind().toQualString() << "_" << i++ << " = "
<< *fg->g(attr::Subgraph);
}
/*
// Uncomment this to debug all_nodes issues
{
out << "\n";
out << "all_nodes:\n";
for (auto& n : all_nodes) {
printNode(out, const_cast<Node*>(n), nullptr);
}
}
*/
return out;
}
std::ostream& operator<<(std::ostream& out, const Graph& g) {
return g.print(out, true);
}
static void checkSameDevice(const Node* node) {
bool has_device = false;
c10::optional<at::Device> device = c10::nullopt;
auto checkValue = [&](const Value* v) {
if (TensorTypePtr type = v->type()->cast<TensorType>()) {
if (type->device() && !has_device) {
has_device = true;
device = *type->device();
} else {
AT_ASSERT(device == type->device());
}
}
};
for (auto input : node->inputs()) {
checkValue(input);
}
for (auto output : node->outputs()) {
checkValue(output);
}
}
using node_set = std::set<const Node*>;
#define ALL_OF(container) container.begin(), container.end()
// These functions purposely operate on the internal members directly, to force
// you to think about how the invariants change if you change the data
// representation (even if the external API does not change.)
// NB: This assert is written to assume you don't have any unattached
// nodes. Unattached nodes can occur while manipulations to the
// graph are occurring.
void Node::lint() const {
// Node invariants
// - if node should live in list, nodes_iter is consistent
// - Inputs are all marked as a use by the nodes they refer to
// - Owning graph is non-null and consistent
// - The "Select" invariant, when the node is MultiReturn
//
// The handle invariant:
// If a node takes a handle as an input, it is always the
// LAST input of the node. There is at most one handle input.
{
size_t i = 0;
for (auto input : inputs_) {
// WARNING: O(n^2)
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
AT_ASSERT(
std::find(ALL_OF(input->uses_), Use(const_cast<Node*>(this), i)) !=
input->uses_.end());
AT_ASSERT(graph_->all_nodes.count(this) == 1);
i++;
}
}
for (auto o : outputs()) {
size_t i = 0;
for (auto use : o->uses()) {
// Use invariants
// - Use is consistent with inputs
// - Every user node is live (checked in Graph)
AT_ASSERT(use.user->inputs_[use.offset] == o);
i++;
}
}
// Node subclass invariants
switch (kind()) {
case prim::Constant:
AT_ASSERT(inputs_.size() == 0);
break;
case prim::Return:
// Return uses is zero
AT_ASSERT(outputs().size() == 0);
break;
case prim::Param:
// Param inputs is zero
AT_ASSERT(inputs_.size() == 0);
break;
case prim::PythonOp: {
// Python operator cconv is correct
auto* value = static_cast<const PythonOp*>(this);
value->lint_python();
break;
}
case prim::Eval:
// TODO: add invariants
// TODO: It's not good for these ops to be top-level, it makes cases
// longer.
break;
case prim::FusionGroup:
checkSameDevice(this);
// TODO: Typecheck the parameters
g(attr::Subgraph)->lint();
break;
}
}
// TODO: When lint fails, give better indication about which
// instruction triggered the failure.
void Graph::lint() const {
// Graph invariants
// Uncomment the following to see the graph
// std::cout << *const_cast<Graph*>(this);
// nodes
// - nodes_ is a valid topological ordering for inputs
// - No repeated nodes
// - Params and return do NOT occur in nodes
// - next_unique_ is greater than all uniques in graph
// - uniques in all_nodes are unique
// - every use will occur later in the topsort
struct LintScope {
LintScope() = default;
LintScope(std::unique_ptr<LintScope> parent) : parent(std::move(parent)) {}
bool contains(const Value* v) {
return values.count(v) > 0 || (parent && parent->contains(v));
}
bool contains(const Node* n) {
return nodes.count(n) > 0 || (parent && parent->contains(n));
}
void insert(const Value* v) {
AT_ASSERT(!contains(v));
values.insert(v);
}
void insert(const Node* n) {
AT_ASSERT(!contains(n));
nodes.insert(n);
}
std::unique_ptr<LintScope> parent;
private:
std::unordered_set<const Value*> values;
std::unordered_set<const Node*> nodes;
};
// Struct enables mutual recursion in linting methods.
// Putting it inside Graph::lint enables access to private Graph members
struct LintImpl {
LintImpl(const Graph& g)
: g(g),
scope(new LintScope()),
all_nodes_set(ALL_OF(g.all_nodes)) {} // NB: all_nodes is *unordered*
const Graph& g;
std::unique_ptr<LintScope> scope;
std::unordered_set<size_t> seen_uniques;
std::unordered_map<const Node*, int64_t> anticipated_uses;
node_set all_nodes_set;
node_set sum_set;
void check_value(const Value* v) {
scope->insert(v);
auto b2 = seen_uniques.insert(v->unique());
AT_ASSERT(b2.second); // insertion took place
AT_ASSERT(v->unique() < g.next_unique_);
for (auto use : v->uses()) {
AT_ASSERT(!scope->contains(use.user));
AT_ASSERT(g.all_nodes.count(use.user) == 1);
anticipated_uses[use.user]++; // int default constructs to 0
}
}
void check_node(const Node* n) {
for (auto input : n->inputs_) {
if (!scope->contains(input)) {
AT_ASSERTM(0, input->unique(), " not in scope");
}
}
AT_ASSERT(anticipated_uses[n] == static_cast<int64_t>(n->inputs_.size()));
anticipated_uses[n] = -1; // we saw the anticipated user!
scope->insert(n);
for (auto block : n->blocks()) {
std::unique_ptr<LintScope> new_scope(new LintScope(std::move(scope)));
scope = std::move(new_scope);
check_block(block);
scope = std::move(scope->parent);
}
size_t i = 0;
for (auto o : n->outputs()) {
AT_ASSERT(o->node() == n);
AT_ASSERT(i++ == o->offset_);
check_value(o);
}
n->lint();
}
void check_block(const Block* b) {
// Check topological ordering
AT_ASSERT(b->param_node()->isBefore(*b->nodes().begin()));
auto curNode = *b->nodes().begin();
while (curNode != b->return_node()) {
AT_ASSERT(curNode->isBefore(curNode->next()));
curNode = curNode->next();
}
for (auto input : b->inputs()) {
check_value(input);
AT_ASSERT(input->node()->kind_ == prim::Param);
}
for (auto n : b->nodes()) {
AT_ASSERT(n->kind_ != prim::Param);
AT_ASSERT(n->kind_ != prim::Return);
check_node(n);
}
AT_ASSERT(b->output_->kind() == prim::Return);
check_node(b->output_);
// all_nodes
// - inputs_, output_ and nodes_ are all included in all_nodes
// - all_nodes does not contain dead nodes??? (likely to be temporarily
// suspended). Weaker: all_nodes contains all inputs and returns
// - only one return node???
node_set nodes_set(ALL_OF(b->nodes()));
node_set inputs_set{b->input_};
node_set output_set{b->output_};
// TODO: Make a more type safe std::includes wrapper which disallows use
// on non-ordered containers
AT_ASSERT(std::includes(ALL_OF(all_nodes_set), ALL_OF(nodes_set)));
AT_ASSERT(std::includes(ALL_OF(all_nodes_set), ALL_OF(inputs_set)));
AT_ASSERT(std::includes(ALL_OF(all_nodes_set), ALL_OF(output_set)));
sum_set.insert(ALL_OF(nodes_set));
sum_set.insert(ALL_OF(inputs_set));
sum_set.insert(ALL_OF(output_set));
}
void check_graph() {
node_set all_nodes_set(
ALL_OF(g.all_nodes)); // NB: all_nodes is *unordered*
check_block(g.block_);
for (auto kv : anticipated_uses) {
AT_ASSERT(kv.second == -1);
}
AT_ASSERT(std::includes(ALL_OF(sum_set), ALL_OF(all_nodes_set)));
}
};
LintImpl(*this).check_graph();
}
void Graph::dump() const {
std::cout << *this << "\n";
}
void Graph::push_scope(const std::string& scope_name) {
current_scope_ = current_scope_->push(Symbol::scope(scope_name));
Node* block_node = insertNode(create(prim::TracedModuleForward, 0));
block_node->s_(attr::scope, scope_name);
Block* b = block_node->addBlock();
setInsertPoint(b);
}
void Graph::pop_scope() {
current_scope_ = current_scope_->parent();
if (insertPoint()->owningBlock()->owningNode()->kind() ==
prim::TracedModuleForward) {
setInsertPoint(insertPoint()->owningBlock()->owningNode()->next());
}
}
void LintGraph(const std::shared_ptr<Graph>& graph) {
graph->lint();
}
Block::Block(Graph* graph_, Node* node_)
: graph_(graph_),
output_(graph_->create(prim::Return, 0)),
input_(graph_->create(prim::Param, 0)),
owning_node_(node_) {
input_->next() = output_;
input_->prev() = output_;
output_->next() = input_;
output_->prev() = input_;
graph_->all_blocks.emplace(this);
output_->owning_block_ = this;
output_->topo_position_ = kUpperBound;
input_->owning_block_ = this;
input_->topo_position_ = kLowerBound;
}
void Block::reIndexTopology() {
auto curPos = kLowerBound;
for (auto node : nodes()) {
AT_ASSERT(curPos <= (kUpperBound - kAppendInterval));
curPos += kAppendInterval;
node->topo_position_ = curPos;
}
}
void Block::cloneFrom(Block* src, std::function<Value*(Value*)> value_map) {
std::unordered_map<Value*, Value*> local_map;
auto env = [&](Value* v) {
auto it = local_map.find(v);
if (it != local_map.end()) {
return it->second;
}
return value_map(v);
};
auto graph = owningGraph();
for (auto input : src->inputs()) {
local_map[input] = this->addInput()->copyMetadata(input);
}
for (auto node : src->nodes()) {
auto new_node = this->appendNode(graph->createClone(node, env));
for (size_t i = 0; i < node->outputs().size(); ++i) {
auto oo = node->outputs()[i];
auto no = new_node->outputs()[i];
local_map[oo] = no;
no->copyMetadata(oo);
}
}
for (auto output : src->outputs()) {
this->registerOutput(env(output));
}
}
void Block::destroy() {
// we cannot destroy the output because it is used as the sentinel
// for the nodes() list and has to remain valid for the loop
output_->removeAllInputs();
for (auto it = this->nodes().reverse().begin(),
end = this->nodes().reverse().end();
it != end;
++it) {
it.destroyCurrent();
}
output_->destroy();
input_->destroy();
graph_->freeBlock(this);
}
std::shared_ptr<Graph> Graph::copy() {
auto new_g = std::make_shared<Graph>();
auto env = [](Value* v) -> Value* {
AT_ERROR(
"Graph::copy() encountered a use of a value " + v->debugName() +
" not in scope. Run lint!");
};
new_g->block()->cloneFrom(this->block(), env);
return new_g;
}
void Block::remapTypes(const std::function<TypePtr(TypePtr)>& type_map) {
for (Value* input : inputs()) {
input->setType(type_map(input->type()));
}
for (Node* node : nodes()) {
for (Value* output : node->outputs()) {
output->setType(type_map(output->type()));
}
for (Block* sub_block : node->blocks()) {
sub_block->remapTypes(type_map);
}
for (Symbol name : node->attributeNames()) {
if (node->kindOf(name) == AttributeKind::g) {
node->g(name)->remapTypes(type_map);
} else if (node->kindOf(name) == AttributeKind::gs) {
for (const auto& g : node->gs(name)) {
g->remapTypes(type_map);
}
}
}
}
}
void Graph::remapTypes(const std::function<TypePtr(TypePtr)>& type_map) {
block()->remapTypes(type_map);
}
void Value::inferTypeFrom(const at::Tensor& output) {
setType(TensorType::create(output));
}
bool Value::mustBeNone() const {
return node_->mustBeNone();
}
bool Value::mustNotBeNone() const {
return node_->kind() != prim::AutogradAdd && type() != NoneType::get() &&
!type()->cast<OptionalType>();
}
std::string Value::debugNameBase() const {
std::string name = debugName();
std::string name_base = name;
auto last_dot_pos = name.find_last_of('.');
if (last_dot_pos != std::string::npos && last_dot_pos + 1 != name.size()) {
if (name.find_first_not_of("0123456789", last_dot_pos + 1) ==
std::string::npos) {
name_base = name.substr(0, last_dot_pos);
}
}
return name_base;
}
bool Value::isValidName(const std::string& name) {
// Empty strings are legal
if (!name.size()) {
return true;
}
// Numbers are not legal
if (name.find_first_not_of("0123456789") == std::string::npos) {
return false;
}
return true;
}
Value* Value::setDebugName(const std::string& name) {
if (!isValidName(name)) {
throw std::runtime_error("Invalid name: '" + name + "'");
}
auto& names = node()->owningGraph()->unique_names_;
// clear any old name from the map
if (hasDebugName()) {
names.erase(unique_name_);
unique_name_ = "";
}
// allow "" to clear the uniquename
if (name == "") {
return this;
}
// if someone else has this name, then rename the other value
auto old_owner_of_name = names.find(name);
if (old_owner_of_name != names.end()) {
size_t suffix = 1;
std::string name_base = name;
auto last_dot_pos = name.find_last_of('.');
if (last_dot_pos != std::string::npos && last_dot_pos + 1 != name.size()) {
if (name.find_first_not_of("0123456789", last_dot_pos + 1) ==
std::string::npos) {
suffix = c10::stoll(name.substr(last_dot_pos + 1));
name_base = name.substr(0, last_dot_pos);
}
}
std::string replacement_name;
do {
std::stringstream ss;
ss << name_base << "." << suffix++;
replacement_name = ss.str();
} while (names.count(replacement_name) > 0);
old_owner_of_name->second->setDebugName(replacement_name);
}
names[name] = this;
unique_name_ = name;
return this;
}
Value* Value::copyMetadata(Value* from) {
setType(from->type());
if (from->hasDebugName()) {
setDebugName(from->debugName());
}
return this;
}
void Value::replaceFirstUseWith(Value* newValue) {
AT_ASSERT(owningGraph() == newValue->owningGraph());
auto u = uses()[0];
u.user->inputs_[u.offset] = newValue;
newValue->uses_.push_back(u);
uses_.erase(uses_.begin());
}
void Value::replaceAllUsesWith(Value* newValue) {
while (!uses().empty()) {
replaceFirstUseWith(newValue);
}
}
void Value::replaceAllUsesAfterNodeWith(const Node* node, Value* newValue) {
std::for_each(uses_.begin(), uses_.end(), [&node, newValue](Use& u) {
if (u.user->isAfter(node)) {
u.user->inputs_[u.offset] = newValue;
newValue->uses_.push_back(u);
}
});
uses_.erase(
std::remove_if(
uses_.begin(),
uses_.end(),
[&node](const Use& u) { return u.user->isAfter(node); }),
uses_.end());
}
size_t findArgument(const FunctionSchema& the_schema, Symbol name) {
auto name_str = name.toUnqualString();
for (size_t i = 0; i < the_schema.arguments().size(); ++i) {
const Argument* arg = &the_schema.arguments()[i];
if (arg->name() == name_str) {
return i;
}
}
throw std::runtime_error(
std::string("Couldn't find an argument called ") + name.toQualString());
}
c10::optional<IValue> Node::get(Symbol name) const {
return toIValue(namedInput(name));
}
Value* Node::namedInput(Symbol name) const {
return input(findArgument(schema(), name));
}
bool Node::matches(
const char* signature_literal,
at::ArrayRef<Symbol> const_inputs) const {
if (!sig(signature_literal).matches(this)) {
return false;
}
for (Symbol s : const_inputs) {
if (!is_constant(s)) {
return false;
}
}
return true;
}
bool Node::mustBeNone() const {
// We can statically deduce this Node has returning None if:
return
// It's an AutogradZero node, or ...
kind_ == prim::AutogradZero ||
// It has only one output and that output is NoneType, or ...
(outputs().size() == 1 && output()->type() == NoneType::get()) ||
// It's a constant optional with no value in the attributes.
(kind_ == prim::Constant && !this->hasAttributes() &&
output()->type()->cast<OptionalType>());
}
void Node::dump() const {
std::cout << *this << "\n";
}
const FunctionSchema& Node::schema() const {
if (op_) {
return op_->schema();
}
return getOperatorFor(this).schema();
}
const FunctionSchema* Node::maybeSchema() const {
if (auto op = maybeOperator()) {
return &op->schema();
}
return nullptr;
}
const Operator& Node::getOperator() const {
if (!op_) {
op_ = &getOperatorFor(this);
}
return *op_;
}
const Operator* Node::maybeOperator() const {
if (!op_) {
if (auto op = findOperatorFor(this)) {
op_ = op.get();
}
}
return op_;
}
bool Node::isNondeterministic() const {
static const OperatorSet nondeterministic_ops = {
"aten::dropout(Tensor input, float p, bool train) -> Tensor",
"aten::_fused_dropout(Tensor self, float p, Generator? generator) -> (Tensor, Tensor)",
"aten::_standard_gamma(Tensor self, Generator? generator) -> Tensor",
"aten::bernoulli(Tensor self, *, Generator? generator) -> Tensor",
"aten::bernoulli(Tensor self, float p, *, Generator? generator) -> Tensor",
"aten::multinomial(Tensor self, int num_samples, bool replacement, *, Generator? generator) -> Tensor",
"aten::normal(Tensor mean, Tensor std, *, Generator? generator) -> Tensor",
"aten::normal(float mean, Tensor std, *, Generator? generator) -> Tensor",
"aten::normal(Tensor mean, float std, *, Generator? generator) -> Tensor",
"aten::poisson(Tensor self, Generator? generator) -> Tensor",
"aten::rrelu(Tensor self, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor",
"aten::rrelu_with_noise(Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, Generator? generator) -> Tensor",
"aten::rand(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor",
"aten::rand_like(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor",
"aten::rand_like(Tensor self, *, int dtype, int layout, Device device, bool pin_memory, MemoryFormat? memory_format=None) -> Tensor",
"aten::randint(int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor",
"aten::randint(int low, int high, int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor",
"aten::randint_like(Tensor self, int high, *, MemoryFormat? memory_format=None) -> Tensor",
"aten::randint_like(Tensor self, int low, int high, *, MemoryFormat? memory_format=None) -> Tensor",
"aten::randint_like(Tensor self, int high, *, int dtype, int layout, Device device, bool pin_memory, MemoryFormat? memory_format=None) -> Tensor",
"aten::randint_like(Tensor self, int low, int high, *, int dtype, int layout, Device device, bool pin_memory, MemoryFormat? memory_format=None) -> Tensor",
"aten::randn(int[] size, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor",
"aten::randn_like(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor",
"aten::randn_like(Tensor self, *, int dtype, int layout, Device device, bool pin_memory, MemoryFormat? memory_format=None) -> Tensor",
"aten::randperm(int n, *, int? dtype, int? layout, Device? device, bool? pin_memory) -> Tensor"};
if (nondeterministic_ops.find(this) == nullptr) {
return false;
}
// Dropout with train = False is deterministic
if (matches("aten::dropout(Tensor input, float p, bool train) -> Tensor") &&
is_constant(attr::train) && !get<bool>(attr::train).value()) {
return false;
}
return true;
}
bool Node::hasSideEffects() const {
switch (kind_) {
case prim::PythonOp:
case prim::IgnoredPythonOp:
case prim::Print:
case prim::RaiseException:
case prim::SetAttr:
case aten::warn:
case aten::save:
case aten::manual_seed:
case prim::AddStatValue:
case prim::TimePoint:
case prim::CallFunction:
case prim::CallMethod:
case prim::BailoutTemplate:
case prim::profile:
case prim::BailOut:
case prim::Guard:
return true;
}
auto op = maybeOperator();
if (!op) {
TORCH_INTERNAL_ASSERT(
kind_.is_prim(),
"Only prim ops are allowed to not have a registered operator but ",
kind_.toDisplayString(),
" doesn't have one either. We don't know if this op has side effects.");
return false;
}
if (kind_.is_prim() || kind_.is_aten()) {
// TODO There is nothing in the system that relies on aten:: and prim::
// ops using AliasAnalysisKind::FROM_SCHEMA,
// AliasAnalysisKind::INTERNAL_SPECIAL_CASE, or
// AliasAnalysisKind::CONSERVATIVE 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(
op->aliasAnalysisKind() == AliasAnalysisKind::INTERNAL_SPECIAL_CASE ||
op->aliasAnalysisKind() == AliasAnalysisKind::FROM_SCHEMA ||
op->aliasAnalysisKind() == AliasAnalysisKind::CONSERVATIVE,
"aten:: and prim:: ops should have AliasAnalysisKind::INTERNAL_SPECIAL_CASE"
", AliasAnalysisKind::FROM_SCHEMA or AliasAnalysisKind::CONSERVATIVE but ",
kind_.toDisplayString(),
" has ",