forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ir_emitter.cpp
5734 lines (5245 loc) · 208 KB
/
ir_emitter.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/frontend/ir_emitter.h>
#include <torch/csrc/jit/frontend/tree_views.h>
#include <c10/util/Exception.h>
#include <c10/util/StringUtil.h>
#include <c10/util/irange.h>
#include <caffe2/serialize/versions.h>
#include <torch/csrc/jit/api/function_impl.h>
#include <torch/csrc/jit/frontend/canonicalize_modified_loop.h>
#include <torch/csrc/jit/frontend/convert_to_ssa.h>
#include <torch/csrc/jit/frontend/lexer.h>
#include <torch/csrc/jit/frontend/parser.h>
#include <torch/csrc/jit/frontend/schema_matching.h>
#include <torch/csrc/jit/frontend/script_type_parser.h>
#include <torch/csrc/jit/ir/ir.h>
#include <torch/csrc/jit/passes/annotate_warns.h>
#include <torch/csrc/jit/passes/canonicalize.h>
#include <torch/csrc/jit/passes/constant_pooling.h>
#include <torch/csrc/jit/passes/constant_propagation.h>
#include <torch/csrc/jit/passes/dead_code_elimination.h>
#include <torch/csrc/jit/passes/inline_forked_closures.h>
#include <torch/csrc/jit/passes/inliner.h>
#include <torch/csrc/jit/passes/lift_closures.h>
#include <torch/csrc/jit/passes/lower_tuples.h>
#include <torch/csrc/jit/passes/normalize_ops.h>
#include <torch/csrc/jit/passes/replacement_of_old_operators.h>
#include <torch/csrc/jit/runtime/graph_iterator.h>
#include <torch/csrc/jit/runtime/interpreter.h>
#include <torch/csrc/jit/runtime/operator.h>
#include <torch/csrc/jit/runtime/slice_indices_adjust.h>
#include <torch/csrc/jit/testing/hooks_for_testing.h>
#include <torch/csrc/jit/ir/constants.h>
#include <c10/util/Optional.h>
#include <c10/util/hash.h>
#include <ATen/core/interned_strings.h>
#include <ATen/core/jit_type.h>
#include <torch/csrc/jit/frontend/error_report.h>
#include <atomic>
#include <climits>
#include <set>
#include <stack>
namespace torch::jit {
using FunctionTable = std::unordered_map<std::string, Function&>;
using ValueTable = std::unordered_map<std::string, SugaredValuePtr>;
using TypeTable = std::unordered_map<std::string, TypePtr>;
using AttributeMap = std::unordered_map<std::string, Const>;
using ListAttributeMap = std::unordered_map<std::string, std::vector<Const>>;
struct Refinement {
Refinement(std::string identifier, TypePtr type)
: identifier_(std::move(identifier)), type_(std::move(type)) {}
const std::string& identifier() const {
return identifier_;
}
TypePtr type() const {
return type_;
}
private:
std::string identifier_;
TypePtr type_;
};
struct RefinementSet {
// When a comparison like x is None is made, we associate type refinements
// with its true value and its false value. If a boolean that has refinements
// associated with it is used in a conditional of an if statement, the true
// and false refinements are inserted into the corresponding blocks
using Refinements = std::vector<Refinement>;
RefinementSet(Refinements true_refinements, Refinements false_refinements)
: true_refinements_(std::move(true_refinements)),
false_refinements_(std::move(false_refinements)) {}
RefinementSet(Refinement single) : RefinementSet({std::move(single)}, {}) {}
RefinementSet(Refinement single_true, Refinement single_false)
: RefinementSet(
Refinements({std::move(single_true)}),
Refinements({std::move(single_false)})) {}
RefinementSet() = default; // empty
RefinementSet And(const RefinementSet& rhs) const {
// if the result of an AND is true, both a & b had to be true,
// so we take the union of a.true_refinements and b.true_refinements.
// if the result is false, either a or b could have been false,
// so we take their intersection.
return RefinementSet(
unionSet(true_refinements_, rhs.true_refinements_),
intersectSet(false_refinements_, rhs.false_refinements_));
}
RefinementSet Or(const RefinementSet& rhs) const {
// if the result of an OR is true, either a & b could have been true,
// so we take the intersection of a.true_refinements & b.true_refinements.
// if the result is false, both a and b had to be false,
// so we take their union.
return RefinementSet(
intersectSet(true_refinements_, rhs.true_refinements_),
unionSet(false_refinements_, rhs.false_refinements_));
}
RefinementSet Not() const {
return RefinementSet(false_refinements_, true_refinements_);
}
const std::vector<Refinement> activeRefinements() const {
return true_refinements_;
}
private:
static bool sameVar(const Refinement& a, const Refinement& b) {
return a.identifier() == b.identifier();
}
static Refinements unionSet(const Refinements& a, const Refinements& b) {
Refinements result = a;
for (const Refinement& r : b) {
auto it =
std::find_if(result.begin(), result.end(), [&](const Refinement& e) {
return e.identifier() == r.identifier();
});
if (it == result.end()) {
result.push_back(r);
} else if (*it->type() != *r.type()) {
// we only keep refinements when they exactly match one
// refinement type, for instance, we do not attempt to refine:
// isinstance(x, float) and isinstance(x, int)
result.erase(it);
}
}
return result;
}
static Refinements intersectSet(const Refinements& a, const Refinements& b) {
Refinements result;
for (const Refinement& r : a) {
auto it = std::find_if(b.begin(), b.end(), [&](const Refinement& e) {
return e.identifier() == r.identifier();
});
if (it != b.end() && r.type() == it->type()) {
result.push_back(r);
}
}
return result;
}
Refinements true_refinements_;
Refinements false_refinements_;
};
struct CondValue {
CondValue(
Value* value,
RefinementSet refinements,
c10::optional<bool> static_if)
: value_(value),
refinements_(std::move(refinements)),
static_if_(static_if) {}
CondValue(
Graph& g,
const SourceRange& loc,
bool static_value,
RefinementSet refinements)
: value_(g.insertConstant(static_value, loc)),
refinements_(std::move(refinements)),
static_if_(static_value) {}
Value* value() const {
return value_;
}
const RefinementSet& refinements() const {
return refinements_;
}
c10::optional<bool> staticIf() const {
return static_if_;
}
private:
Value* value_;
RefinementSet refinements_;
c10::optional<bool>
static_if_; // certain expression cause us to emit a static if statement
// this value is present if this is the case.
// this is not equivalent to value_ being a constant
// it is possible for value_ to be constant but for
// the expression that produced it to not trigger the
// static if behavior. e.g. use of a variable assigned
// to a constant
};
enum NoneStatus { ALWAYS, MAYBE, NEVER };
NoneStatus canBeNone(Value* v) {
if (v->node()->mustBeNone()) {
return ALWAYS;
}
if (v->type()->kind() == OptionalType::Kind ||
(v->type()->kind() == UnionType::Kind &&
v->type()->expect<UnionType>()->canHoldType(*NoneType::get()))) {
return MAYBE;
}
return NEVER;
}
static Value* asSimple(const SugaredValuePtr& value) {
if (SimpleValue* sv = dynamic_cast<SimpleValue*>(value.get())) {
return sv->getValue();
}
return nullptr;
}
static std::shared_ptr<MagicMethod> makeMagic(
const std::string& name,
SugaredValuePtr base) {
return std::make_shared<MagicMethod>(name, base);
}
// Auxiliary data structure for desugaring variable binding into our always
// explicitly scoped language as we descend down nested control structures in
// the frontend (which themselves don't introduce scopes)
//
// The Environment keeps track of two tables, one for values which are not first
// class and a type table for values which are. When a first class value
// is set in the environment, we emit a prim::Store which sets the
// name of the variable to appropriate type, and when a first-class value is
// referenced we emit a prim::Load that generates a value of the appropriate
// type.
//
// a = 1
// print(a)
// becomes:
// = prim::Store[name="a"](%a.1)
// %a : int = prim::Load[name="a"]()
// prim::Print(%a)
struct Environment {
Environment(
GraphFunction& method,
ResolverPtr resolver,
Block* b,
std::shared_ptr<Environment> next = nullptr)
: method(method),
resolver(std::move(resolver)),
b(b),
next(std::move(next)) {}
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
GraphFunction& method;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
ResolverPtr resolver;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
std::unordered_map<std::string, std::function<std::string()>> error_messages;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
Block* b;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
std::shared_ptr<Environment> next;
// set type error in the lowest environment. if the variable is used after an
// error has been set, then we will use the more informative error message
void setVariableTypeError(
const std::string& name,
std::function<std::string()> msg) {
auto runner = this;
while (runner->next) {
runner = runner->next.get();
}
runner->error_messages[name] = std::move(msg);
}
// see if type error has been set for a variable
c10::optional<std::string> findVariableTypeError(const std::string& name) {
auto runner = this;
while (runner->next) {
runner = runner->next.get();
}
auto msg = runner->error_messages.find(name);
if (msg != runner->error_messages.end()) {
return msg->second();
} else {
return c10::nullopt;
}
}
SugaredValuePtr insertLoad(const std::string& name, const TypePtr& type) {
auto g = b->owningGraph();
auto load = g->insertNode(g->createLoad(name, type));
if (meaningfulName(name)) {
load->output()->setDebugName(name);
}
return std::make_shared<SimpleValue>(load->output());
}
// note: type is not always the same as v->type(), e.g.
// type: Optional[Tensor]
// v->type(): Tensor
void insertStore(
const std::string& name,
const SourceRange& loc,
Value* v,
TypePtr type) {
auto g = b->owningGraph();
g->insertNode(g->createStore(name, v))->setSourceRange(loc);
type_table[name] = std::move(type);
}
SugaredValuePtr findInThisFrame(const std::string& name) {
auto it = value_table.find(name);
if (it != value_table.end()) {
return it->second;
}
auto it2 = type_table.find(name);
if (it2 != type_table.end()) {
return insertLoad(name, it2->second);
}
return nullptr;
}
SugaredValuePtr findInParentFrame(const std::string& name) {
return next ? next->findInAnyFrame(name) : nullptr;
}
void setType(const std::string& name, TypePtr type) {
type_table[name] = std::move(type);
}
SugaredValuePtr findInAnyFrame(const std::string& name) {
for (auto runner = this; runner; runner = runner->next.get()) {
if (auto r = runner->findInThisFrame(name)) {
return r;
}
}
return nullptr;
}
Block* block() {
return b;
}
void setVar(const SourceRange& loc, const std::string& name, Value* value) {
setSugaredVar(
loc,
name,
std::make_shared<SimpleValue>(value),
/*annotated_type=*/nullptr);
}
void setSugaredVar(
const SourceRange& loc,
const std::string& name,
SugaredValuePtr value,
TypePtr annotated_type) {
Value* as_simple_value = asSimple(value);
if (as_simple_value && !as_simple_value->hasDebugName() &&
meaningfulName(name) &&
// note: if the value wasn't defined in this block, we might be giving a
// name only used inside this block to a value outside of this. this is
// not normally helpful for debugging and causes import/export jitter.
as_simple_value->node()->owningBlock() == block()) {
as_simple_value->setDebugName(name);
}
// prevent re-assignment involving any sugared values
// any reassignment like:
// a = ...
// while ...
// a = ..
// requires 'a' to be first-class in the graph since its value depends on
// control flow
if (auto parent = findInParentFrame(name)) {
if (annotated_type) {
throw ErrorReport(loc)
<< "Attempting to declare and annotate the type of variable '"
<< name << "' but it is already defined in an outer block";
}
if (!as_simple_value) {
throw ErrorReport(loc)
<< "Cannot re-assign '" << name << "' to a value of type "
<< value->kind() << " because " << name
<< " is not a first-class value. Only reassignments to first-class values are allowed";
}
Value* simple_parent = asSimple(parent);
if (!simple_parent) {
throw ErrorReport(loc)
<< "Cannot re-assign '" << name << "' because it has type "
<< value->kind() << " and " << name
<< " is not a first-class value. Only reassignments to first-class values are allowed";
}
auto parent_type = unshapedType(simple_parent->type());
as_simple_value = tryConvertToType(
loc,
*b->owningGraph(),
parent_type,
as_simple_value,
/*allow_conversions=*/true);
std::stringstream why_not;
if (!as_simple_value->type()->isSubtypeOfExt(*parent_type, &why_not)) {
auto error = ErrorReport(loc);
error << "Variable '" << name << "' previously had type "
<< simple_parent->type()->repr_str()
<< " but is now being assigned to a value of type "
<< as_simple_value->type()->repr_str();
// Special-cased error msg if we're trying to assign to a tensor list.
if (simple_parent->type()->kind() == TypeKind::ListType &&
as_simple_value->type()->kind() == TypeKind::ListType) {
error << "\nEmpty lists default to List[Tensor]. Add a variable "
"annotation to the assignment to create an empty list "
"of another type (torch.jit.annotate(List[T, []]) where T "
"is the type of elements in the list for Python 2)";
}
error << "\n" << why_not.str();
throw error;
}
}
if (as_simple_value) {
if (annotated_type &&
!as_simple_value->type()->isSubtypeOf(*annotated_type)) {
throw ErrorReport(loc)
<< "Variable '" << name << "' is annotated with type "
<< annotated_type->repr_str()
<< " but is being assigned to a value of type "
<< as_simple_value->type()->repr_str();
}
auto value_store_type =
annotated_type ? annotated_type : as_simple_value->type();
insertStore(name, loc, as_simple_value, value_store_type);
} else {
value_table[name] = std::move(value);
}
}
SugaredValuePtr getSugaredVar(const Ident& ident, bool required = true) {
return getSugaredVar(ident.name(), ident.range());
}
Value* getVar(const Ident& ident) {
return getSugaredVar(ident)->asValue(ident.range(), method);
}
void throwVarNotFoundError(
const std::string& ident,
const SourceRange& range) {
// check if this value was not emitted in an if statement because of a
// type mismatch. if it was, then we print a more informative error msg
if (auto msg = findVariableTypeError(ident)) {
throw ErrorReport(range) << *msg << "and was used here";
}
throw ErrorReport(range) << "undefined value " << ident;
}
SugaredValuePtr getSugaredVar(
const std::string& ident,
const SourceRange& range,
bool required = true) {
auto retval = findInAnyFrame(ident);
if (!retval) {
static std::unordered_map<std::string, SugaredValuePtr> globals = {
{"print", std::make_shared<PrintValue>()},
{"tuple", SpecialFormValue::create(prim::TupleConstruct)},
{"float",
makeMagic(
"__float__",
std::make_shared<CastValue>(FloatType::get(), aten::Float))},
{"complex",
makeMagic(
"__complex__",
std::make_shared<CastValue>(ComplexType::get(), aten::Complex))},
{"int",
makeMagic(
"__int__",
std::make_shared<CastValue>(IntType::get(), aten::Int))},
{"bool",
makeMagic(
"__bool__",
std::make_shared<CastValue>(BoolType::get(), aten::Bool))},
{"str",
makeMagic(
"__str__",
std::make_shared<CastValue>(StringType::get(), aten::str))},
{"getattr", SpecialFormValue::create(prim::GetAttr)},
{"hasattr", SpecialFormValue::create(prim::HasAttr)},
{"isinstance", SpecialFormValue::create(prim::isinstance)},
// todo(zach): remove when we can correctly export torch.full via ONNX
// or we have implicit conversion that can convert numbers to tensors
{"_to_tensor",
std::make_shared<CastValue>(TensorType::get(), prim::NumToTensor)},
{"len",
makeMagic(
"__len__",
std::make_shared<BuiltinFunction>(aten::len, at::nullopt))},
{"hex",
makeMagic(
"__hex__",
std::make_shared<BuiltinFunction>(aten::hex, at::nullopt))},
{"oct",
makeMagic(
"__oct__",
std::make_shared<BuiltinFunction>(aten::oct, at::nullopt))},
{"round",
makeMagic(
"__round__",
std::make_shared<BuiltinFunction>(aten::round, at::nullopt))},
{"hash", std::make_shared<BuiltinFunction>(aten::hash, at::nullopt)},
{"id", std::make_shared<BuiltinFunction>(prim::id, at::nullopt)},
{"min", std::make_shared<BuiltinFunction>(prim::min, at::nullopt)},
{"max", std::make_shared<BuiltinFunction>(prim::max, at::nullopt)},
{"abs", std::make_shared<BuiltinFunction>(prim::abs, at::nullopt)},
{"all", std::make_shared<BuiltinFunction>(aten::all, at::nullopt)},
{"any", std::make_shared<BuiltinFunction>(aten::any, at::nullopt)},
{"divmod",
std::make_shared<BuiltinFunction>(aten::divmod, at::nullopt)},
{"sum", std::make_shared<BuiltinFunction>(aten::sum, at::nullopt)},
{"list", SpecialFormValue::create(prim::list)},
{"dict", SpecialFormValue::create(prim::dict)},
{"ord", std::make_shared<BuiltinFunction>(aten::ord, at::nullopt)},
{"chr", std::make_shared<BuiltinFunction>(aten::chr, at::nullopt)},
{"bin", std::make_shared<BuiltinFunction>(aten::bin, at::nullopt)},
{"pow", std::make_shared<BuiltinFunction>(aten::pow, at::nullopt)},
{"range", SpecialFormValue::create(prim::range)},
{"zip", SpecialFormValue::create(prim::zip)},
{"enumerate", SpecialFormValue::create(prim::enumerate)},
{"rangelist",
std::make_shared<BuiltinFunction>(prim::rangelist, at::nullopt)},
{"sorted",
std::make_shared<BuiltinFunction>(aten::sorted, at::nullopt)},
// Only AssertionError is bound so that we can use it from emitAssert,
// all other exceptions should be resolved at the Python level
{"AssertionError",
std::make_shared<ExceptionValue>("AssertionError")},
};
auto it = globals.find(ident);
if (it != globals.end()) {
retval = it->second;
}
}
if (!retval) {
if (auto type = resolver->resolveType(ident, range)) {
if (auto tuple_type = type->cast<TupleType>()) {
retval = std::make_shared<NamedTupleConstructor>(tuple_type);
}
}
}
if (!retval) {
retval = resolver->resolveValue(ident, method, range);
}
if (!retval) {
if (auto type = resolver->resolveType(ident, range)) {
if (auto class_type = type->cast<ClassType>()) {
retval = std::make_shared<ClassValue>(class_type);
}
}
}
if (!retval && required) {
throwVarNotFoundError(ident, range);
}
return retval;
}
Value* getVar(const std::string& ident, const SourceRange& range) {
return getSugaredVar(ident, range)->asValue(range, method);
}
void removeVar(const Ident& ident, bool check_if_removed = false) {
bool removed = false;
for (auto runner = this; runner; runner = runner->next.get()) {
auto a = runner->value_table.erase(ident.name());
auto b = runner->type_table.erase(ident.name());
removed = a || b;
}
if (check_if_removed && !removed) {
throwVarNotFoundError(ident.name(), ident.range());
}
}
std::vector<std::string> definedVariables() {
std::vector<std::string> result;
for (auto& kv : type_table) {
result.push_back(kv.first);
}
return result;
}
private:
TypeTable type_table;
ValueTable value_table;
};
template <class T, class Hash>
static Value* materializeConstant(
T val,
Graph& graph,
const SourceRange& r,
std::unordered_map<T, Value*, Hash>& map) {
auto existing_constant = map.find(val);
if (existing_constant != map.end()) {
return existing_constant->second;
}
WithInsertPoint guard(graph.block()->nodes().front());
auto new_constant = graph.insertConstant(val, r);
map[val] = new_constant;
return new_constant;
}
inline bool isSupportedListElementType(const TypePtr& type) {
return type->isSubtypeOf(*TensorType::get()) ||
type->isSubtypeOf(*NumberType::get());
}
// Information for each def being emitted.
// Defs can be nested to support closures so we need a stack of this information
// Currently records information about the functions return type.
struct DefContext {
TypePtr declared_return_type_; // nullptr if not annotated
TypePtr merged_return_type_; // nullptr if a Return has not been seen yet
};
enum class LoopStatus { NOT_IN_LOOP, IN_LOOP, IN_UNROLLED_LOOP };
struct WithLoopStatus {
WithLoopStatus(LoopStatus* prev, LoopStatus new_status) {
prev_value_ = *prev;
prev_ptr_ = prev;
*prev = new_status;
}
~WithLoopStatus() {
*prev_ptr_ = prev_value_;
}
private:
LoopStatus* prev_ptr_;
LoopStatus prev_value_;
};
struct to_ir {
to_ir(
const Def& def,
ResolverPtr resolver_,
const Self* self,
GraphFunction& method) // method being constructed
: method(method),
graph(method.graph()),
resolver(std::move(resolver_)),
typeParser_(resolver),
environment_stack(nullptr) {
AT_ASSERT(resolver);
pushFrame(graph->block(), /*starts_def=*/true);
// Type annotations exclude explicitly typing the "self" parameter, so in
// the case that this is a method with self we expect one fewer parameter
// annotation than the number of parameters this Def takes.
if (self && def.decl().params().empty()) {
throw ErrorReport(def.decl().params().range())
<< "methods must have a self argument";
}
method.setSchema(emitDef(def, self, graph->block()));
// At this point, we might have received a graph that is compiled with
// old operator schemas that might not exist in the system anymore.
// Therefore, we replace such ops with its' valid upgrader.
ReplaceOldOperatorsWithUpgraders(graph);
// NB ORDERING: SSA conversion has to occur before
// lifting of closures and forks, this way closures are converted
// to SSA while part of their original graph, and closures are ready to
// be inlined into forked closures
ConvertToSSA(graph);
// convert loops with an iter and body condition specified to
// python-recognize while loops. we do this so they can be exported,
// and run the pass early to avoid jitter. Like conversion to SSA,
// it only needs to run once.
CanonicalizeModifiedLoops(graph);
// Convert Ops to a Normalized Form
NormalizeOps(graph);
runCleanupPasses(graph);
}
private:
GraphFunction& method;
std::shared_ptr<Graph> graph;
ResolverPtr resolver;
std::unordered_map<int64_t, Value*, std::hash<int64_t>> integral_constants;
std::unordered_map<double, Value*, std::hash<double>> fp_constants;
std::unordered_map<
c10::complex<double>,
Value*,
c10::hash<c10::complex<double>>>
complex_constants;
std::unordered_set<Block*> exit_blocks;
ScriptTypeParser typeParser_;
LoopStatus loop_status_ = LoopStatus::NOT_IN_LOOP;
// Singly-linked list of environments. This top element contains a member
// `next` that points to the most immediate enclosing scope's value.
std::shared_ptr<Environment> environment_stack;
std::vector<DefContext> def_stack_;
size_t temp_name_count_ = 0;
std::string createTempName(const std::string& prefix) {
return prefix + c10::to_string(temp_name_count_++);
}
void pushFrame(Block* b, bool starts_def = false) {
if (starts_def) {
def_stack_.emplace_back();
}
environment_stack =
std::make_shared<Environment>(method, resolver, b, environment_stack);
}
std::shared_ptr<Environment> popFrame(bool ends_def = false) {
auto old_frame = environment_stack;
environment_stack = environment_stack->next;
if (ends_def) {
def_stack_.pop_back();
}
return old_frame;
}
// If the graph might not return, add an implicit None return at the end
void handleMaybeNoReturn(const Def& def, Block* block) {
auto decl_ret = def_stack_.back().declared_return_type_;
if (exit_blocks.count(block) == 0) {
auto decl_ret = def_stack_.back().declared_return_type_;
if (decl_ret && decl_ret != NoneType::get()) {
throw ErrorReport(def.range())
<< "Function was not annotated as having type None, but does not "
<< "return along all paths";
}
WithInsertPoint b(*block->nodes().end());
emitReturn(Return::create(
def.range(), Expr(Compound::create(TK_NONE, def.range(), {}))));
} else {
// if we haven't seen any return statements, but the graph block exits
// (the function always throws) then we accept the declared return type if
// it exists or set it to none
if (def_stack_.back().merged_return_type_ == nullptr) {
def_stack_.back().merged_return_type_ =
decl_ret != nullptr ? decl_ret : NoneType::get();
}
}
}
FunctionSchema emitDef(const Def& def, const Self* self, Block* block) {
auto schema = typeParser_.parseSchemaFromDef(def, bool(self));
// TODO need guards on init returning none
if (schema.returns().size() == 1) {
def_stack_.back().declared_return_type_ = schema.returns().at(0).type();
}
std::vector<Argument> arguments =
emitFormalArguments(def, self, schema, block);
// body
auto stmts_list = def.statements();
emitStatements(stmts_list.begin(), stmts_list.end());
handleMaybeNoReturn(def, block);
std::vector<Argument> returns = {emitOutput(def.range(), schema, block)};
return {def.name().name(), "", std::move(arguments), std::move(returns)};
}
// see [setstate type]
static TypePtr getTypeForSetStateArg(const Def& def, const Self* self) {
TORCH_CHECK(self, "Expected __setstate__ to have a `self` argument");
auto getstate = self->getClassType()->findMethod("__getstate__");
if (!getstate) {
throw ErrorReport(def.range())
<< "`__setstate__` defined but not `__getstate__`. "
<< "You must have both defined on a ScriptModule "
<< "to customize serialization.\n"
<< "Did you forget to use `@torch.jit.export`?";
}
getstate->ensure_defined();
return self->getClassType()
->getMethod("__getstate__")
.getSchema()
.returns()
.at(0)
.type();
}
// see [setstate type]
static bool shouldDeriveSetStateType(
const Def& def,
const FunctionSchema& schema) {
const bool noTypeAnnotations = std::all_of(
schema.arguments().begin(),
schema.arguments().end(),
[](const Argument& arg) { return arg.is_inferred_type(); });
bool shouldInfer = def.name().name() == "__setstate__" && noTypeAnnotations;
if (!shouldInfer) {
return false;
}
// Do some additional basic validation that the __setstate__ func is
// well-formed
TORCH_INTERNAL_ASSERT(def.name().name() == "__setstate__");
const auto numDeclParams = def.decl().params().size();
if (numDeclParams != 2) {
throw ErrorReport(def.range())
<< "Expected 2 arguments for `__setstate__`, got: " << numDeclParams;
}
return true;
}
std::vector<Argument> emitFormalArguments(
const Def& def,
const Self* self,
const FunctionSchema& schema,
Block* block) {
std::vector<Argument> arguments; // for schema
// inputs
auto it = def.decl().params().begin();
auto end = def.decl().params().end();
auto expected_annotation_size = def.decl().params().size();
if (self) {
expected_annotation_size--;
}
if (schema.arguments().size() != expected_annotation_size) {
throw ErrorReport(def.decl().params().range())
<< "Number of type annotations for"
<< " function parameters (" << schema.arguments().size() << ")"
<< " does not match the number of parameters on the function ("
<< expected_annotation_size << ")!";
}
if (self) {
AT_ASSERT(it != end);
const auto& name = (*it).ident().name();
Value* new_input = block->addInput()->setDebugName(name);
environment_stack->setSugaredVar(
(*it).ident().range(),
name,
self->makeSugared(new_input),
/*annotated_type=*/nullptr);
arguments.emplace_back(name, new_input->type());
++it;
}
// [setstate type]
// __setstate__ is special, because if the user leaves it un-annotated we
// will derive the type for `state` from the output type of __getstate__.
// This is necessary so that we can allow submodules to appear in `state`.
bool shouldDeriveType = shouldDeriveSetStateType(def, schema);
size_t arg_annotation_idx = 0;
for (; it != end; ++it) {
auto& name = (*it).ident().name();
// Add the input to the graph
Value* new_input = block->addInput();
if (meaningfulName(name)) {
new_input->setDebugName(name);
}
// Record the type for the schema and set the Type on the Value*
auto arg = schema.arguments().at(arg_annotation_idx++);
if (shouldDeriveType) {
TORCH_INTERNAL_ASSERT(schema.arguments().size() == 1);
const auto& inferredStateType = getTypeForSetStateArg(def, self);
arg = arg.cloneWithType(inferredStateType);
}
arguments.push_back(arg);
new_input->setType(arguments.back().type());
// NB: set type of new_input before setVar call so the Store is
// typed appropriately
environment_stack->setVar((*it).ident().range(), name, new_input);
}
return arguments;
}
Argument emitOutput(
const SourceRange& range,
const FunctionSchema& schema,
Block* block) {
// handleMaybeNoReturn ensures that merged_return_type_ is always set
auto ret_type = def_stack_.back().merged_return_type_;
TORCH_INTERNAL_ASSERT(ret_type);
// in the ConvertToSSA pass, prim::ReturnStmts are lowered so that the
// correct return value is set. Until then, we have a correctly-typed
// placeholder return value. This is needed so that closures & graphs
// are correctly typed.
auto placeholder_return =
graph->insertNode(graph->createUninitialized(ret_type))->output();
block->registerOutput(placeholder_return);
return Argument("", def_stack_.back().merged_return_type_);
}
void emitStatements(const List<Stmt>& statements) {
return emitStatements(statements.begin(), statements.end());
}
// XXX: Right now closures are not generically implemented and are only used
// as an intermediate form for special tasks, like defining gradients or
// forked functions.
//
// There are several unfinished aspects that make them unusable generally
// 1. We do not have a type, ivalue, operator to represent prim::Closure, so
// closure_node has type None
// 2. There is no export logic for it yet, so it cannot be
// exported/python_printed
// 3. There is nothing preventing the assignment of already existing variables
// inside the closures
// the changes to those variables will just get forgotten.
// 4. There is no parsing support in frontend.py, this is intentional since it
// prevents people from accidentally using this feature.
//
// This function leaves in the graph something like:
//
// %2 : None = prim::Closure()
// block0():
// %1 : Tensor = prim::DoSomething(%0)
// -> (%1)
//
// A separate pass is required to erase this closure and replace it with
// something actually executable (see liftClosure and inlineForkedClosure).
std::shared_ptr<ClosureValue> emitClosure(
const std::function<void(Block*)>& emit_body) {
Node* closure_node = graph->insertNode(graph->create(prim::Closure, 1));
// it is not a real thing yet, so just say the type is None
closure_node->output()->setType(NoneType::get());
Block* block = closure_node->addBlock();
WithLoopStatus loop_guard(&loop_status_, LoopStatus::NOT_IN_LOOP);
{
WithInsertPoint guard(block);
pushFrame(block, /*starts_def=*/true);
emit_body(block);
popFrame(/*ends_def=*/true);
}
return std::make_shared<ClosureValue>(closure_node->output());
}
void emitClosure(const Def& def) {
// invoked once the closure block is set as the environment
auto emit_body = [&](Block* closure_block) {
emitDef(
def,
nullptr,
closure_block); // ignore schema return, we just wont use it for now
// since we never create a Method for the closure
};
auto closure_value = emitClosure(emit_body);
environment_stack->setSugaredVar(
def.name().range(),
def.name().name(),
closure_value,
/*annotated_type=*/nullptr);
}
void checkBreakContinue(
const SourceRange& loc,
const std::string& stmt_name) {
if (loop_status_ == LoopStatus::NOT_IN_LOOP) {
throw ErrorReport(loc) << "SyntaxError: '" << stmt_name << "'"
<< " outside loop";
} else if (loop_status_ == LoopStatus::IN_UNROLLED_LOOP) {
throw ErrorReport(loc)
<< "Because we emit iteration over modulelists or tuples as "
"unrolled loops, we do not support break or continue inside the body of these loops";
}
}
void emitBreak(const Break& stmt) {
checkBreakContinue(stmt.range(), "break");
auto break_node =
graph->create(prim::BreakStmt, {}, 0)->setSourceRange(stmt.range());
graph->insertNode(break_node);
}
void emitContinue(const Continue& stmt) {
checkBreakContinue(stmt.range(), "continue");
auto continue_node =
graph->create(prim::ContinueStmt, {}, 0)->setSourceRange(stmt.range());
graph->insertNode(continue_node);
}
void emitDelete(const Delete& stmt) {
for (const auto& target : stmt.targets()) {
if (target.kind() == TK_SUBSCRIPT) {
Subscript subscript(target);
const List<Expr>& subscript_exprs = subscript.subscript_exprs();
if (subscript_exprs[0].kind() == TK_SLICE_EXPR) {
throw ErrorReport(target.range())
<< "del statements only support deletion at a single index, "
"slicing is not supported"
" (see https://github.com/pytorch/pytorch/issues/31430)";
}
const SugaredValuePtr sv = emitSugaredExpr(subscript.value(), 1);
const SourceRange& val_range = subscript.value().range();
Value* idx = emitExpr(subscript_exprs[0]);
Value* val = sv->asValue(val_range, method);
// If val is a class instance, this is a method call to a type-specific