forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.cpp
3094 lines (2844 loc) · 109 KB
/
compiler.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/script/compiler.h>
#include <c10/util/Exception.h>
#include <torch/csrc/jit/hooks_for_testing.h>
#include <torch/csrc/jit/interpreter.h>
#include <torch/csrc/jit/ir.h>
#include <torch/csrc/jit/operator.h>
#include <torch/csrc/jit/passes/canonicalize.h>
#include <torch/csrc/jit/passes/constant_pooling.h>
#include <torch/csrc/jit/passes/lower_tuples.h>
#include <torch/csrc/jit/script/final_returns.h>
#include <torch/csrc/jit/script/parser.h>
#include <torch/csrc/jit/script/schema_matching.h>
#include <torch/csrc/jit/script/script_type_parser.h>
#include <torch/csrc/jit/constants.h>
#include <c10/util/Optional.h>
#include <atomic>
#include <climits>
#include <set>
namespace torch {
namespace jit {
namespace script {
using FunctionTable = std::unordered_map<std::string, Function&>;
using ValueTable = std::unordered_map<std::string, SugaredValuePtr>;
using AttributeMap = std::unordered_map<std::string, Const>;
using ListAttributeMap = std::unordered_map<std::string, std::vector<Const>>;
using TypeAndRange = std::pair<TypePtr, const SourceRange*>;
// Holds mappings from a variable name to a refined type for that variable
// E.g if x is not None is true than we can refine x from type t? to t.
struct Refinements {
// using ordered map for deterministic graph output
std::map<std::string, TypeAndRange> mappings_;
void setRefinement(const std::string& name, TypeAndRange mapping) {
mappings_[name] = std::move(mapping);
}
c10::optional<TypeAndRange> getRefinement(const std::string& name) const {
const auto& maybe_mapping = mappings_.find(name);
if (maybe_mapping == mappings_.end()) {
return c10::nullopt;
}
return maybe_mapping->second;
}
// return the intersection of the values to type mappings between this
// types can be unified
void intersectRefinements(const Refinements& other) {
Refinements ret;
for (const auto& name_mapping : mappings_) {
const auto& name = name_mapping.first;
const auto& mapping = name_mapping.second;
if (auto other_mapping = other.getRefinement(name_mapping.first)) {
const auto maybe_unified_type =
unifyTypes(mapping.first, other_mapping->first);
if (maybe_unified_type) {
ret.setRefinement(
name, TypeAndRange(*maybe_unified_type, mapping.second));
}
}
}
mappings_ = std::move(ret.mappings_);
}
// return the union of the values to type mappings in a and b whose
// types can be unified
void unionRefinements(const Refinements& other) {
Refinements ret;
for (const auto& name_mapping : mappings_) {
const auto& name = name_mapping.first;
const auto& mapping = name_mapping.second;
TypePtr t_1 = mapping.first;
if (auto other_mapping = other.getRefinement(name_mapping.first)) {
TypePtr t_2 = other_mapping->first;
c10::optional<TypePtr> maybe_unified_type = c10::nullopt;
if (t_1->isSubtypeOf(t_2)) {
maybe_unified_type = t_1;
} else if (t_2->isSubtypeOf(t_1)) {
maybe_unified_type = t_2;
}
if (maybe_unified_type) {
ret.setRefinement(
name, TypeAndRange(*maybe_unified_type, mapping.second));
}
} else {
ret.setRefinement(name, mapping);
}
}
for (auto& name_mapping : other.mappings_) {
if (!getRefinement(name_mapping.first)) {
ret.setRefinement(name_mapping.first, name_mapping.second);
}
}
mappings_ = std::move(ret.mappings_);
}
};
// 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 statememt, the true and
// false refinements are inserted into the corresponding blocks
struct BoolInfo {
BoolInfo(Refinements true_refinements, Refinements false_refinements)
: true_refinements_(std::move(true_refinements)),
false_refinements_(std::move(false_refinements)){};
BoolInfo() = default;
Refinements true_refinements_;
Refinements false_refinements_;
BoolInfo* mergeOr(const BoolInfo& other) {
// 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.
true_refinements_.intersectRefinements(other.true_refinements_);
false_refinements_.unionRefinements(other.false_refinements_);
return this;
}
BoolInfo* mergeAnd(const BoolInfo& other) {
// 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.
true_refinements_.unionRefinements(other.true_refinements_);
false_refinements_.intersectRefinements(other.false_refinements_);
return this;
}
};
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);
}
// we consider _N where N is a number, to be a non-meaningful name
// and do not record it as a unique name. This allows python printing to
// be able to export and import more consistently named graphs
static bool meaningfulName(const std::string& name) {
if (name.size() == 0)
return false;
if (name[0] == '$')
return false;
if (name[0] != '_')
return true;
for (size_t i = 1; i < name.size(); ++i) {
if (!isdigit(name[i]))
return true;
}
return false;
}
// 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 algorithm is roughly as follows:
// 1) While emitting a block within a control operator, add inputs and outputs
// from the block for each value referenced (both "reads" and "writes").
// This sets the value up as a candidate loop carried dependency.
// 2) When we reach the end of the block, examine all the values in the current
// scope's value map. If the name also resides in an outer scope with a
// different Value*, this is a true loop-carried dependency. If not, this
// value was not assigned to. Replace all references to the block input
// with the Value* pointed to in the tightest enclosing scope. Then delete
// that block input and output.
// 3) When we emit the actual control operator, take all of the loop-carried
// dependency values as inputs and return them as outputs from the control
// op
//
// Note that an alternative implementation could only add the loop-carried dep
// inputs and outputs when we see a value that is mutated. This, however
// requires replacing all references to that value *within the current
// block* with a new input. That is to say: we need to traverse the pre-
// decessor nodes and replace inputs that reference that value with the
// newly-created input. This could be made less expensive with a change to
// the IR API, but for now we choose to pessimisitically create inputs and
// delete unnecessary ones later with replaceAllusesWith().
struct Environment {
Environment(
Function& method,
ResolverPtr resolver,
Block* b,
std::shared_ptr<Environment> next = nullptr)
: method(method),
resolver(std::move(resolver)),
b(b),
next(std::move(next)) {}
Function& method;
ResolverPtr resolver;
std::vector<std::string> captured_inputs;
std::unordered_map<std::string, std::string> error_messages;
Block* b;
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, const std::string& msg) {
auto runner = this;
while (runner->next) {
runner = runner->next.get();
}
runner->error_messages[name] = 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 findInThisFrame(const std::string& name) {
auto it = value_table.find(name);
if (it != value_table.end()) {
return it->second;
}
return nullptr;
}
SugaredValuePtr findInParentFrame(const std::string& name) {
return next ? next->findInAnyFrame(name) : nullptr;
}
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;
}
Value* getValueInThisFrame(const SourceRange& loc, const std::string& name) {
return value_table.at(name)->asValue(loc, method);
}
SugaredValuePtr createCapturedInput(Value* orig, const std::string& name) {
// insert the captured input alphabetically in the capture list.
// this ensures consistency of the order of loop-carried dependencies
// even when the use in the loop is in a different order
size_t insert_pos = 0;
while (insert_pos < captured_inputs.size() &&
name > captured_inputs[insert_pos]) {
insert_pos++;
}
captured_inputs.insert(captured_inputs.begin() + insert_pos, name);
// Create the input
const size_t loop_carried_block_inputs_offset = 1;
Value* new_input =
b->insertInput(loop_carried_block_inputs_offset + insert_pos)
->setType(orig->type());
// Associate this name with this value
auto sv = std::make_shared<SimpleValue>(new_input);
value_table[name] = sv;
return sv;
}
SugaredValuePtr createCapturedInputIfNeeded(
const SourceRange& loc,
const std::string& ident) {
auto in_frame = findInThisFrame(ident);
if (in_frame) {
return in_frame;
}
// recursively handles the case where parent blocks are also loops
auto from_parent =
next ? next->createCapturedInputIfNeeded(loc, ident) : nullptr;
// recursively create the captured input if it is the loop block
if (from_parent && getBlockOwningKind() == prim::Loop) {
if (Value* simple_val = asSimple(from_parent))
from_parent = createCapturedInput(simple_val, ident);
}
return from_parent;
}
Block* block() {
return b;
}
Symbol getBlockOwningKind() {
Symbol owning_kind = Symbol();
if (b->owningNode()) {
owning_kind = b->owningNode()->kind();
}
return owning_kind;
}
void setVar(const SourceRange& loc, const std::string& name, Value* value) {
setSugaredVar(loc, name, std::make_shared<SimpleValue>(value));
}
void setSugaredVar(
const SourceRange& loc,
const std::string& name,
SugaredValuePtr value) {
Value* as_simple_value = asSimple(value);
if (as_simple_value && !as_simple_value->hasUniqueName() &&
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->setUniqueName(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 (!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";
}
if (!as_simple_value->type()->isSubtypeOf(
unshapedType(simple_parent->type()))) {
std::stringstream errMsg;
errMsg << "variable '" << name << "' previously has type "
<< simple_parent->type()->python_str()
<< " but is now being assigned to a value of type "
<< as_simple_value->type()->python_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) {
errMsg << "\n. (Note: empty lists are constructed as Tensor[]; "
<< "if you want an empty list of a different type, "
<< "use `torch.jit.annotate(List[T], [])`, "
<< "where `T` is the type of elements in the list)";
}
throw ErrorReport(loc) << errMsg.str();
}
}
if (as_simple_value)
createCapturedInputIfNeeded(loc, name);
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);
}
SugaredValuePtr getSugaredVar(
const std::string& ident,
const SourceRange& range,
bool required = true) {
auto retval = createCapturedInputIfNeeded(range, ident);
if (!retval) {
static std::unordered_map<std::string, SugaredValuePtr> globals = {
{"print", std::make_shared<PrintValue>()},
{"float",
makeMagic(
"__float__",
std::make_shared<CastValue>(FloatType::get(), prim::Float))},
{"int",
makeMagic(
"__int__",
std::make_shared<CastValue>(IntType::get(), prim::Int))},
{"bool",
makeMagic(
"__bool__",
std::make_shared<CastValue>(BoolType::get(), prim::Bool))},
{"str",
makeMagic(
"__str__",
std::make_shared<CastValue>(StringType::get(), prim::str))},
{"getattr", std::make_shared<GetAttrValue>()},
{"isinstance", std::make_shared<IsInstanceValue>()},
// 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))},
{"hash", std::make_shared<BuiltinFunction>(aten::hash, 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)},
{"list", std::make_shared<BuiltinFunction>(aten::list, at::nullopt)},
{"ord", std::make_shared<BuiltinFunction>(aten::ord, at::nullopt)},
{"rangelist",
std::make_shared<BuiltinFunction>(prim::rangelist, at::nullopt)},
};
auto it = globals.find(ident);
if (it != globals.end()) {
retval = it->second;
}
}
if (!retval) {
if (auto type = resolver->resolveType(ident)) {
const auto class_type = type->expect<ClassType>();
retval = std::make_shared<script::ClassValue>(class_type);
}
}
if (!retval) {
retval = resolver->resolveValue(ident, method, range);
}
if (!retval && required) {
// 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;
}
return retval;
}
Value* getVar(const std::string& ident, const SourceRange& range) {
return getSugaredVar(ident, range)->asValue(range, method);
}
// Given that after emitting statements in a block, we've added block inputs
// for all value references and assignments, delete inputs for which there was
// no assignment, only references.
void deleteExtraInputs(const SourceRange& loc) {
// note: skip i == 0, it is the loop trip count for inputs
// and the loop condition for outputs.
// captured_inputs is indexed by i - 1 since it only contains loop
// carried dependencies
// inputs: loop_counter, lcd0, lcd1, ...
// outputs: loop_condition, lcd0, lcd1, ...
// captured_inputs: lcd0, lcd1, ...
AT_ASSERT(b->inputs().size() == b->outputs().size());
AT_ASSERT(b->inputs().size() == captured_inputs.size() + 1);
for (size_t i = b->inputs().size() - 1; i > 0; i--) {
// nothing changed along this loop
if (b->inputs()[i] == b->outputs()[i]) {
auto name = captured_inputs[i - 1];
Value* orig = findInParentFrame(name)->asValue(loc, method);
b->inputs()[i]->replaceAllUsesWith(orig);
b->eraseInput(i);
b->eraseOutput(i);
captured_inputs.erase(captured_inputs.begin() + i - 1);
}
}
}
std::vector<std::string> definedVariables() {
std::vector<std::string> result;
for (auto& kv : value_table) {
result.push_back(kv.first);
}
return result;
}
private:
ValueTable value_table;
};
template <class T>
static Value* materializeConstant(
T val,
Graph& graph,
const SourceRange& r,
std::unordered_map<T, Value*>& 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, nullptr, r);
map[val] = new_constant;
return new_constant;
}
static Value* ensureInt(const SourceRange& range, Value* v) {
if (!v->type()->isSubtypeOf(IntType::get())) {
throw ErrorReport(range)
<< "expected a int but found a " << v->type()->python_str();
}
return v;
}
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
};
struct to_ir {
to_ir(
const Def& def,
ResolverPtr resolver_,
const Self& self,
Function& 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().size() == 0) {
throw ErrorReport(def.decl().params().range())
<< "methods must have a self argument";
}
method.setSchema(emitDef(def, self, graph->block()));
runCleanupPasses(graph);
}
private:
Function& method;
std::shared_ptr<Graph> graph;
ResolverPtr resolver;
std::unordered_map<int64_t, Value*> integral_constants;
std::unordered_map<double, Value*> fp_constants;
ScriptTypeParser typeParser_;
// 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_;
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;
}
void runCleanupPasses(std::shared_ptr<Graph>& to_clean) {
// remove any uses of tuples that we inserted that are not needed
LowerSimpleTuples(to_clean);
ConstantPooling(to_clean);
// For jitter
CanonicalizeOutputs(to_clean);
}
FunctionSchema emitDef(const Def& def, const Self& self, Block* block) {
auto schema = extractSchemaFromDef(def, 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 = moveAllReturnsToEnd(def.statements());
emitStatements(stmts_list.begin(), stmts_list.end());
std::vector<Argument> returns = {emitOutput(def.range(), schema, block)};
return {def.name().name(), "", std::move(arguments), std::move(returns)};
}
std::vector<IValue> evaluateDefaults(
const SourceRange& r,
const std::vector<Expr>& default_types,
const std::vector<Expr>& default_exprs) {
std::vector<IValue> default_values;
if (default_exprs.empty())
return default_values;
// To evaluate the default expressions, we create a graph with no inputs,
// and whose returns are the default values we need.
// We then run constant prop on this graph and check the results are
// constant. This approach avoids having to have separate handling of
// default arguments from standard expressions by piecing together existing
// machinery for graph generation, constant propgation, and constant
// extraction.
auto tuple_type = Subscript::create(
r,
Var::create(r, Ident::create(r, "Tuple")),
List<Expr>::create(r, default_types));
auto blank_decl = Decl::create(
r, List<Param>::create(r, {}), Maybe<Expr>::create(r, tuple_type));
auto tuple_expr =
TupleLiteral::create(r, List<Expr>::create(r, default_exprs));
auto ret = Return::create(r, tuple_expr);
auto def = Def::create(
r,
Ident::create(r, "defaults"),
blank_decl,
List<Stmt>::create(r, {ret}));
auto m = std::make_shared<Module>();
CompilationUnit cu;
// set optimize to false since we don't need to run it in optimize mode
cu.set_optimized(false);
cu.define({def}, {resolver}, nullptr);
Stack stack;
cu.get_function("defaults").run(stack);
return stack.at(0).toTuple()->elements();
}
std::vector<Argument> parseArgsFromDecl(const Decl& decl, const Self& self) {
auto params_begin = decl.params().begin();
auto params_end = decl.params().end();
if (self) {
++params_begin;
}
std::vector<Argument> retval;
std::vector<Expr> default_types;
std::vector<Expr> default_exprs;
// gather any non-empty default arguments
for (auto it = params_begin; it != params_end; ++it) {
auto param = *it;
auto def = param.defaultValue();
if (def.present()) {
default_types.emplace_back(param.type());
default_exprs.emplace_back(def.get());
}
}
auto default_values =
evaluateDefaults(decl.range(), default_types, default_exprs);
auto defaults_it = default_values.begin();
for (auto it = params_begin; it != params_end; ++it) {
auto decl_arg = *it;
TypePtr type;
c10::optional<int32_t> N;
// BroadcastList list can only appear at the argument level
if (auto maybe_broad_list =
typeParser_.parseBroadcastList(decl_arg.type())) {
type = maybe_broad_list->first;
N = maybe_broad_list->second;
} else {
type = typeParser_.parseTypeFromExpr(decl_arg.type());
N = c10::nullopt;
}
c10::optional<IValue> default_value = c10::nullopt;
if (decl_arg.defaultValue().present()) {
default_value = *defaults_it++;
}
auto arg = Argument(
decl_arg.ident().name(),
type,
N,
default_value,
decl_arg.kwarg_only());
retval.push_back(arg);
}
return retval;
}
std::vector<Argument> parseReturnFromDecl(const Decl& decl) {
// we represent no annoation on a return type as having no values in the
// schema's return() list
// in emitReturn we take the actual return value to be the value of the
// return statement if no one was provided here
if (!decl.return_type().present())
return {};
if (typeParser_.parseBroadcastList(decl.return_type().get()))
throw ErrorReport(decl.return_type().range())
<< "Broadcastable lists cannot appear as a return type";
auto parsed_type = typeParser_.parseTypeFromExpr(decl.return_type().get());
return {Argument(
"",
parsed_type,
/*N =*/c10::nullopt,
/*default_value =*/c10::nullopt,
/*kwarg_only =*/false)};
}
FunctionSchema extractSchemaFromDef(const Def& def, const Self& self) {
const auto name = def.name().name();
std::vector<Argument> args = parseArgsFromDecl(def.decl(), self);
std::vector<Argument> returns = parseReturnFromDecl(def.decl());
return FunctionSchema(
name, "", std::move(args), std::move(returns), false, false);
}
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()->setUniqueName(name);
environment_stack->setSugaredVar(
(*it).ident().range(), name, self(new_input));
arguments.emplace_back(name, new_input->type());
++it;
}
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->setUniqueName(name);
}
environment_stack->setVar((*it).ident().range(), name, new_input);
// Record the type for the schema and set the Type on the Value*
arguments.push_back(schema.arguments().at(arg_annotation_idx++));
new_input->setType(arguments.back().type());
}
return arguments;
}
Argument emitOutput(
const SourceRange& range,
const FunctionSchema& schema,
Block* block) {
// rewrites ensure there is always a return statement in program
AT_ASSERT(def_stack_.back().merged_return_type_);
// outputs
Value* result = environment_stack->getVar("$return", range);
block->registerOutput(result);
return Argument("", def_stack_.back().merged_return_type_);
}
void emitStatements(const List<Stmt>& statements) {
return emitStatements(statements.begin(), statements.end());
}
std::pair<std::shared_ptr<Graph>, Value*> lambdaLift(Block* block) {
auto subgraph = std::make_shared<Graph>();
// note: type is set later on pack_context and context when we know it
Node* pack_context =
graph->insertNode(graph->create(prim::TupleConstruct, {}, 1));
Value* context = subgraph->addInput("context");
// cannot use createTupleUnpack because the type is not known yet
Node* unpack_context =
subgraph->insertNode(subgraph->create(prim::TupleUnpack, {context}, 0));
std::unordered_map<Value*, Value*> captures;
auto env = [&](Value* v) -> Value* {
auto it = captures.find(v);
if (it != captures.end()) {
return it->second;
}
pack_context->addInput(v);
Value* r = unpack_context->addOutput()->copyMetadata(v);
captures[v] = r;
return r;
};
subgraph->block()->cloneFrom(block, env);
auto context_type = TupleType::create(
fmap(pack_context->inputs(), [](Value* v) { return v->type(); }));
pack_context->output()->setType(context_type);
context->setType(context_type);
return std::make_pair(std::move(subgraph), pack_context->output());
}
// XXX - right now closures are used _only_ for defining gradients internally
// There are several unfinished aspects that make them unusable generally
// 1. We do not have a type, ivalue, operator to represent prim::Function, so
// closure_node has type None
// and any graphs that contain it cannot be run
// 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.
void emitClosure(const Def& def) {
Node* closure_node = graph->insertNode(graph->create(prim::Function, 1));
closure_node->output()->setType(
NoneType::get()); // it is not a real thing yet, so just say the type is
// none.
Block* block = closure_node->addBlock();
{
WithInsertPoint guard(block);
pushFrame(block, /*starts_def=*/true);
emitDef(
def,
nullptr,
block); // ignore schema return, we just wont use it for now since we
// never create a Method for the closure
popFrame(/*ends_def=*/true);
}
std::shared_ptr<Graph> subgraph;
Value* context;
std::tie(subgraph, context) = lambdaLift(block);
runCleanupPasses(subgraph);
closure_node->eraseBlock(0);
closure_node->g_(attr::Subgraph, std::move(subgraph));
auto tup =
graph->insertNode(graph->createTuple({closure_node->output(), context}))
->output();
environment_stack->setVar(def.name().range(), def.name().name(), tup);
}
void emitReturn(const Return& stmt) {
Value* result = emitExpr(stmt.expr());
TypePtr result_type = def_stack_.back().declared_return_type_;
// result type is annotated, every return must convert to that type
if (result_type) {
// this guard skips implicit conversion from None -> Tensor for the return
// type. otherwise forgetting a return a function returning a tensor will
// cause a None to be converted to a tensor.
if (!(result_type->isSubtypeOf(TensorType::get()) &&
result->type()->isSubtypeOf(NoneType::get()))) {
result = tryConvertToType(
stmt.range(),
*graph,
result_type,
result,
/*allow_conversions=*/true);
}
if (!result->type()->isSubtypeOf(result_type)) {
throw ErrorReport(stmt.range())
<< "Return value was annotated as having type "
<< result_type->python_str() << " but is actually of type "
<< result->type()->python_str();
}
} else {
result_type = def_stack_.back().merged_return_type_;
if (!result_type) {
result_type = result->type();
}
if (!unifyTypes(result_type, result->type())) {
throw ErrorReport(stmt.range())
<< "Previous return statement returned a value of type "
<< result_type->python_str()
<< " but this return statement returns a value of type "
<< result->type()->python_str();
}
}
AT_ASSERT(result_type);
def_stack_.back().merged_return_type_ = result_type;
environment_stack->setVar(stmt.range(), "$return", result);
}
void emitStatements(
List<Stmt>::const_iterator begin,
List<Stmt>::const_iterator end) {
for (; begin != end; ++begin) {
auto stmt = *begin;
switch (stmt.kind()) {
case TK_IF:
emitIf(If(stmt));
break;
case TK_WHILE:
emitWhile(While(stmt));
break;
case TK_FOR:
emitFor(For(stmt));
break;
case TK_ASSIGN:
emitAssignment(Assign(stmt));
break;
case TK_AUG_ASSIGN:
emitAugAssignment(AugAssign(stmt));
break;
case TK_GLOBAL:
for (auto ident : Global(stmt).names()) {
const auto& name = Ident(ident).name();
environment_stack->setVar(
ident.range(), name, graph->addInput(name));
}
break;
case TK_EXPR_STMT: {
auto expr = ExprStmt(stmt).expr();
emitSugaredExpr(expr, 0);
} break;
case TK_RAISE:
emitRaise(Raise(stmt).range());
break;
case TK_ASSERT:
emitAssert(Assert(stmt));
break;
case TK_RETURN: {
emitReturn(Return(stmt));
} break;
case TK_PASS:
// Emit nothing for pass
break;
case TK_DEF:
emitClosure(Def(stmt));
break;
default:
throw ErrorReport(stmt)
<< "Unrecognized statement kind " << kindToString(stmt.kind());
}
}
}
std::shared_ptr<Environment> emitSingleIfBranch(
Block* b,
const List<Stmt>& branch,
const Refinements& refinements) {
pushFrame(b);
WithInsertPoint guard(b);
insertRefinements(refinements);
emitStatements(branch);
return popFrame();
}
Node* create(Symbol kind, const SourceRange& loc, size_t n_outputs) {
return graph->create(kind, n_outputs)->setSourceRange(loc);
}
Value* emitTernaryIf(const TernaryIf& expr) {
const auto& bool_info = findRefinements(expr.cond());
Value* cond_value = emitCond(expr.cond());
auto true_expr = [&] {
insertRefinements(bool_info.true_refinements_);
return emitExpr(expr.true_expr());
};
auto false_expr = [&] {
insertRefinements(bool_info.false_refinements_);
return emitExpr(expr.false_expr());
};
return emitIfExpr(expr.range(), cond_value, true_expr, false_expr);
}
Value* emitListComprehension(const ListComp& lc) {
// this avoids a race condition where we would re-use the same temp name
static std::atomic<size_t> tmp_count{0};
const auto tmp_name =
std::string("___list_acc") + std::to_string(tmp_count++);
const auto list_value = emitExpr(lc.iter());
if (list_value->type()->kind() != TypeKind::ListType) {
// TODO: constraining iterators to be simple lists for now