forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimpl.cpp
2195 lines (1972 loc) · 71.9 KB
/
impl.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/runtime/static/impl.h>
#include <ATen/MemoryOverlap.h>
#include <ATen/core/symbol.h>
#include <ATen/record_function.h>
#include <c10/core/CPUAllocator.h>
#include <c10/core/InferenceMode.h>
#include <c10/macros/Macros.h>
#include <c10/util/MaybeOwned.h>
#include <c10/util/irange.h>
#include <caffe2/core/scope_guard.h>
#include <caffe2/core/timer.h>
#include <torch/csrc/jit/ir/alias_analysis.h>
#include <torch/csrc/jit/jit_log.h>
#include <torch/csrc/jit/passes/add_if_then_else.h>
#include <torch/csrc/jit/passes/canonicalize.h>
#include <torch/csrc/jit/passes/dead_code_elimination.h>
#include <torch/csrc/jit/passes/eliminate_no_ops.h>
#include <torch/csrc/jit/passes/freeze_module.h>
#include <torch/csrc/jit/passes/remove_mutation.h>
#include <torch/csrc/jit/passes/subgraph_rewrite.h>
#include <torch/csrc/jit/passes/variadic_ops.h>
#include <torch/csrc/jit/runtime/graph_iterator.h>
#include <torch/csrc/jit/runtime/static/fusion.h>
#include <torch/csrc/jit/runtime/static/memory_planner.h>
#include <torch/csrc/jit/runtime/static/ops.h>
#include <torch/csrc/jit/runtime/static/passes.h>
#include <torch/csrc/jit/runtime/vararg_functions.h>
#include <algorithm>
#ifndef AT_PER_OPERATOR_HEADERS
#include <ATen/NativeFunctions.h>
#else
#include <ATen/ops/clone_native.h>
#endif
#include <iterator>
#include <limits>
#include <sstream>
#include <stdexcept>
#ifdef FBCODE_CAFFE2
#include <common/logging/logging.h>
#include <folly/dynamic.h>
#include <folly/json.h>
#endif
// used in test only
C10_DEFINE_bool(
static_runtime_disable_debug_memory_overlap_check,
false,
"If true, disable the memory overlap check in debug mode in ProcessedNode::run()");
namespace torch {
namespace jit {
namespace {
bool allArgsAreTensors(Node* node) {
const auto& inputs = node->inputs();
return std::all_of(inputs.begin(), inputs.end(), [](Value* value) {
return value->type()->kind() == TypeKind::TensorType;
});
}
} // namespace
// A manually curated set of ops that are disallowed in static runtime.
// These are rarely-used ops. Disallowing them typically eliminates
// corner cases in graph optimizations, allowing for more aggressive
// optimizations and better performance.
bool isUnsupportedOp(Node* node) {
auto kind = node->kind();
if (kind != aten::__is__ && kind != aten::__isnot__) {
return false;
}
// We can't support aten::__is__ (and __isnot__) with tensor arguments.
// Consider the following graph:
// def forward(x):
// y = x.detach()
// return x is y
// We have a graph optimization that removes the `detach` node since it is
// a no-op during inference. But this affects the result - we get true
// instead of false! There are many other graph passes affected by this
// issue.
return allArgsAreTensors(node);
}
// graph must be frozen or canEnableStaticRuntime would return false
// if there's any prim::CallMethod op left in the graph
bool canEnableStaticRuntime(const std::shared_ptr<torch::jit::Graph>& graph) {
// check for sub-blocks
bool can_support = true;
for (auto* node : graph->block()->nodes()) {
const auto kind = node->kind();
if (kind == prim::Constant) {
continue;
}
// check if can get op from Node
const Operator* op = node->maybeOperator();
if (isUnsupportedOp(node) || (!op && !nativeOpIsRegistered(kind))) {
can_support = false;
LOG(WARNING) << "Found unsupported op: " << kind.toQualString();
}
}
return can_support;
}
namespace {
// CustomClass extending torch::CustomClassHolder can be typecasted
// to IValue StaticRuntimeMetadata is created so that we can attach
// SR metadata to IR's prim::fork nodes. These CustomClass needs to be
// registered first in order to be used as IValue.below is an
// UNUSED VARIABLE but NEEDED to invoke the class_ constructor necessary
// for class registration.
auto sr_metadata_registerer = torch::class_<StaticRuntimeMetadata>(
"StaticRuntime",
"StaticRuntimeMetadata");
} // namespace
std::string dumpValueSet(
const FastSet<const Value*>& value_set,
const char* set_name) {
std::ostringstream oss;
oss << set_name << ": {";
for (const auto* val : value_set) {
oss << "%" << val->debugName() << ", ";
}
oss << "}";
return oss.str();
}
namespace {
void OptimizeGraph(
std::shared_ptr<torch::jit::Graph>& graph,
const StaticModuleOptions& opts,
std::vector<IValue> sample_inputs) {
GRAPH_DUMP("Before optimizations: ", graph);
if (opts.enable_tensorexpr_fusion) {
if (sample_inputs.empty()) {
VLOG(1) << "Cannot perform TensorExpr fusion - sample_inputs is empty";
} else {
VLOG(1) << "Performing TensorExpr fusion";
performTensorExprFusion(graph, std::move(sample_inputs));
}
}
Inline(*graph);
ConstantPropagation(graph);
Canonicalize(graph);
ConstantPropagation(graph);
RemoveTensorMutation(graph);
ConstantPropagation(graph);
EliminateNoOpSlice(graph);
EliminateDeadCode(graph);
FuseInferenceOpsForSparseNN(graph);
UseVariadicCat(graph);
UseVariadicStack(graph);
EliminateTrivialEquallySplit(graph);
EliminateExtraPermuteOps(graph);
if (opts.enable_out_variant) {
UseVariadicOp(
graph,
fromQualString("fb::sigrid_transforms_torch_bind"),
fromQualString("fb::variadic_sigrid_transforms_torch_bind"));
UseVariadicOp(
graph,
fromQualString("torcharrow::inference_wrapper_run_flat"),
fromQualString("torcharrow::variadic_inference_wrapper_run_flat"));
// These fused ops only have out variants - we can't do the fusion when
// out variants are disabled.
FuseSignLog1P(graph);
FuseClampNaNToNum(graph);
#ifdef FBCODE_CAFFE2
if (opts.use_copy_variants && !opts.enable_tensorexpr_fusion) {
ReplaceWithCopy(graph);
} else {
ReplacePermuteWithCopy(graph);
}
if (opts.use_maybe_copy_variants && !opts.enable_tensorexpr_fusion) {
ReplaceWithMaybeCopy(graph);
}
FuseListUnpack(graph);
RemoveUnnecessaryOutputs(graph);
#endif
}
ConstantPropagation(graph);
RemoveImmutableInputDictLookups(graph);
UseVariadicTupleUnpack(graph);
UseVariadicGroupedAccessor(graph);
EliminateNoOps(
graph, /* custom_ops */ {fromQualString("fb::scale_gradient")});
AddIfThenElseOp(graph);
UseSplitAndSqueeze(graph);
UseInPlaceGetRealInputsFromOptionalInputsV2(graph);
GRAPH_DUMP("Final graph after optimizations: ", graph);
}
bool IsSelfInGraphInput(std::shared_ptr<torch::jit::Graph>& graph) {
return !graph->inputs().empty() && graph->inputs().at(0)->type()->is_module();
}
// remove unused input 0 from graph
bool removeSelfFromGraphInput(std::shared_ptr<torch::jit::Graph>& graph) {
if (graph->inputs().at(0)->type()->is_module()) {
if (graph->inputs().at(0)->hasUses()) {
return false;
}
graph->eraseInput(0);
}
return true;
}
std::vector<Value*> valueVecFromFastSet(const FastSet<const Value*>& s) {
std::vector<Value*> result;
result.reserve(s.size());
for (auto* v : s) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
result.emplace_back(const_cast<Value*>(v));
}
return result;
}
bool mayContainAlias(const AliasDb& db, const Value* v1, const Value* v2) {
// AliasDb is not const-correct here, so we have to const_cast
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
return db.mayContainAlias(const_cast<Value*>(v1), const_cast<Value*>(v2));
}
bool mayContainAlias(
const AliasDb& db,
const Value* a,
const FastSet<const Value*>& b) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
return db.mayContainAlias(const_cast<Value*>(a), valueVecFromFastSet(b));
}
bool escapesScope(const AliasDb& db, const Value* a) {
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
return db.escapesScope({const_cast<Value*>(a)});
}
void PrepareGraphForStaticModule(
std::shared_ptr<torch::jit::Graph> graph,
const StaticModuleOptions& opts,
std::vector<IValue> sample_inputs) {
TORCH_CHECK(canEnableStaticRuntime(graph));
OptimizeGraph(graph, opts, std::move(sample_inputs));
// Static runtime moves its outputs out of the runtime
// by default. In some rare cases, this is not actually safe to
// do - for example, if the value is a constant, static runtime
// needs to hold onto a copy. Rather than adding special logic
// to handle this rare case, we use this pass to detect it and
// create an owned reference that can be safely moved out of the
// runtime.
CreateOwnedRefsForSpecialValues(*graph);
// We assume that each sub-block has at least one output. If we
// detect any that have 0, force the sub-block to return None.
ForceNonEmptyOutputs(*graph);
}
std::pair<std::shared_ptr<Graph>, c10::optional<Module>> PrepareForStaticModule(
const torch::jit::Module& m,
bool is_frozen,
const StaticModuleOptions& opts,
std::vector<IValue> sample_inputs) {
LOG(INFO) << "StaticModuleOptions: enable_out_variant "
<< opts.enable_out_variant << ", optimize_memory "
<< opts.optimize_memory << ", manage_output_tensors "
<< opts.manage_output_tensors << ", use_copy_variants "
<< opts.use_copy_variants << ", use_maybe_copy_variants "
<< opts.use_maybe_copy_variants << ", enable_tensorexpr_fusion "
<< opts.enable_tensorexpr_fusion;
Module module = m.copy();
if (!is_frozen) {
module.eval();
module = freeze_module(module);
}
Method method = module.get_method("forward");
auto graph = module.get_method("forward").graph();
if (!sample_inputs.empty() && IsSelfInGraphInput(graph)) {
sample_inputs.insert(sample_inputs.begin(), m._ivalue());
}
PrepareGraphForStaticModule(graph, opts, std::move(sample_inputs));
return std::make_pair(graph, module);
}
std::pair<std::shared_ptr<Graph>, c10::optional<Module>> PrepareForStaticModule(
std::shared_ptr<torch::jit::Graph> graph,
const StaticModuleOptions& opts,
std::vector<IValue> sample_inputs) {
PrepareGraphForStaticModule(graph, opts, std::move(sample_inputs));
return std::make_pair(graph, c10::nullopt);
}
} // namespace
void ValueGroup::init(const Block& block, const AliasDb& db) {
external_aliases_.clear();
output_aliases_.clear();
// Build `external_aliases` as we look through nodes forwardly from
// the graph's inputs and add aliases of the inputs being created by the
// nodes.
external_aliases_.insert(block.inputs().begin(), block.inputs().end());
for (const auto* node : block.nodes()) {
if (node->kind() == prim::Constant) {
for (const auto* output : node->outputs()) {
external_aliases_.insert(output);
}
}
}
for (const auto* node : block.nodes()) {
if (node->kind() == prim::Constant) {
// Constants are already in `external_aliases`.
continue;
}
for (const auto* v : node->outputs()) {
if (escapesScope(db, v) || mayContainAlias(db, v, external_aliases_)) {
external_aliases_.insert(v);
}
}
}
// Build `output_aliases` as we look through nodes reversely so that we can
// start from the output values, and follow the flows backwardly from there.
output_aliases_.insert(block.outputs().begin(), block.outputs().end());
for (const auto* node : block.nodes().reverse()) {
if (node->kind() == prim::Constant) {
// Constants cannot create any aliases.
continue;
}
for (const auto* v : node->outputs()) {
if (mayContainAlias(db, v, output_aliases_)) {
output_aliases_.insert(v);
}
}
}
}
namespace {
bool isTensorList(const Value* value) {
auto* type = value->type()->castRaw<ListType>();
if (!type) {
return false;
}
return type->getElementType()->kind() == c10::TypeKind::TensorType;
}
bool containTensorsOnly(at::ArrayRef<Value*> values) {
// return true only if all outputs are tensors
return std::all_of(values.begin(), values.end(), [](const Value* value) {
return value->type()->kind() == c10::TypeKind::TensorType ||
isTensorList(value);
});
}
bool isPureFunction(const Node* node) {
auto* schema = node->maybeSchema();
return schema &&
schema->aliasAnalysis() == c10::AliasAnalysisKind::PURE_FUNCTION;
}
} // namespace
ManagedTensorRanges::ManagedTensorRanges(
Block& block,
const AliasDb& alias_db,
const FastSet<const Value*>& managed_tensor_values) {
const std::vector<Node*> nodes(block.nodes().begin(), block.nodes().end());
const FastSet<const Value*> graph_inputs(
block.inputs().begin(), block.inputs().end());
const auto num_nodes = nodes.size();
for (const auto i : c10::irange(num_nodes)) {
auto* node = nodes[i];
for (auto* input : node->inputs()) {
auto* lifetime = getLifetime(input);
if (!lifetime) {
continue;
}
DCHECK(lifetime->end <= i);
lifetime->end = i;
}
for (auto* output : node->outputs()) {
if (!alias_db.isMutableType(output)) {
continue;
}
value_lifetimes_.emplace(output, Lifetime(i, i));
}
}
for (auto* graph_output : block.outputs()) {
auto* lifetime = getLifetime(graph_output);
if (!lifetime) {
continue;
}
lifetime->end = num_nodes;
}
// Handle aliases. Aliases may extend a Value*'s lifetime. If a node
// has an input and output that may alias each other, set the input's
// lifetime end to max(input.lifetime_end, output.lifetime_end). Iterate
// backwards to handle chains of aliases.
for (const auto* node : block.nodes().reverse()) {
if (isPureFunction(node)) {
// If the node is a pure function, it doesn't create any aliases,
// so we can safely skip it.
continue;
}
auto inputs = collectValuesWithTrackedLifetimes(node->inputs());
auto outputs = collectValuesWithTrackedLifetimes(node->outputs());
for (auto* input : inputs) {
auto* input_lifetime = getLifetime(input);
DCHECK(input_lifetime != nullptr);
for (auto* output : outputs) {
if (mayContainAlias(alias_db, input, output)) {
auto* output_lifetime = getLifetime(output);
DCHECK(output_lifetime != nullptr);
input_lifetime->end =
std::max(output_lifetime->end, input_lifetime->end);
}
}
}
}
for (auto* managed_tensor : managed_tensor_values) {
auto* lifetime = getLifetime(managed_tensor);
DCHECK(lifetime && lifetime->end <= num_nodes);
// NOLINTNEXTLINE(cppcoreguidelines-init-variables)
Node* freeing_node;
if (lifetime->end == num_nodes) {
freeing_node = block.return_node();
} else {
freeing_node = nodes[lifetime->end];
}
node_to_newly_free_tensors_[freeing_node].emplace_back(managed_tensor);
}
}
bool ManagedTensorRanges::nodeFreesManagedTensors(Node* node) const {
auto it = node_to_newly_free_tensors_.find(node);
return it != node_to_newly_free_tensors_.end() && !it->second.empty();
}
const std::vector<const Value*>& ManagedTensorRanges::
availableTensorValuesAfterNode(Node* node) const {
return node_to_newly_free_tensors_.at(node);
}
bool ManagedTensorRanges::lifetimesOverlap(const Value* v1, const Value* v2)
const {
const auto* v1_lifetime = getLifetime(v1);
const auto* v2_lifetime = getLifetime(v2);
if (!v1_lifetime || !v2_lifetime) {
return false;
}
if (v1_lifetime->start < v2_lifetime->start) {
return v1_lifetime->end >= v2_lifetime->start;
}
return v2_lifetime->end >= v1_lifetime->start;
}
const ManagedTensorRanges::Lifetime* ManagedTensorRanges::getLifetime(
const Value* value) const {
auto it = value_lifetimes_.find(value);
if (it != value_lifetimes_.end()) {
return &it->second;
}
return nullptr;
}
ManagedTensorRanges::Lifetime* ManagedTensorRanges::getLifetime(
const Value* value) {
// const_cast is safe here, this is just a way to avoid code duplication
// between the const/non-const versions of getLifetime.
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
const auto* const_this = const_cast<const ManagedTensorRanges*>(this);
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
return const_cast<ManagedTensorRanges::Lifetime*>(
const_this->getLifetime(value));
}
std::vector<const Value*> ManagedTensorRanges::
collectValuesWithTrackedLifetimes(at::ArrayRef<const Value*> values) {
std::vector<const Value*> mutable_values;
mutable_values.reserve(values.size());
std::copy_if(
values.begin(),
values.end(),
std::back_inserter(mutable_values),
[this](const Value* value) { return getLifetime(value) != nullptr; });
return mutable_values;
}
StaticModule::StaticModule(
std::shared_ptr<torch::jit::Graph> g,
const StaticModuleOptions& opts,
std::vector<IValue> sample_inputs)
: StaticModule(
PrepareForStaticModule(g->copy(), opts, std::move(sample_inputs)),
opts) {}
StaticModule::StaticModule(
const torch::jit::Module& m,
bool is_frozen,
const StaticModuleOptions& opts,
std::vector<IValue> sample_inputs)
: StaticModule(
PrepareForStaticModule(m, is_frozen, opts, std::move(sample_inputs)),
opts) {}
StaticModule::StaticModule(
std::pair<std::shared_ptr<torch::jit::Graph>, c10::optional<Module>>
graph_and_module,
const StaticModuleOptions& opts)
: opts_(opts),
graph_(std::move(graph_and_module.first)),
module_(std::move(graph_and_module.second)),
num_inputs_(graph_->inputs().size()) {
sr_metadata_ = c10::make_intrusive<jit::StaticRuntimeMetadata>(opts_);
// recursively attach metadata to prim::fork nodes
attachNodeMetadata(graph_->block());
// check opt flags
if (opts.manage_output_tensors) {
TORCH_CHECK(
opts_.enable_out_variant,
"When manage_output_tensors is true, enable_out_variant must be set to true");
}
if (opts_.optimize_memory) {
TORCH_CHECK(
opts_.enable_out_variant,
"When optimize_memory is true, enable_out_variant must be set to true");
}
// handle schema
if (module_.has_value()) {
Method method = module_->get_method("forward");
schema_ = method.function().getSchema();
const auto num_schema_args = schema_->arguments().size();
DCHECK(num_schema_args > 0);
if (removeSelfFromGraphInput(graph_)) {
module_ = c10::nullopt;
num_inputs_ = num_schema_args - 1;
}
}
{
size_t nodes_size = 0, constants_size = 0;
for (Node* node : graph_->nodes()) {
++(node->kind() == prim::Constant ? constants_size : nodes_size);
}
constants_.reserve(constants_size);
functions_.reserve(nodes_size);
}
// Create ProcessedFunction instances first to freeze their addresses to pass
// to ProcessedNode.
AliasDb alias_db(graph_, /*isFrozen=*/false);
GRAPH_DEBUG("AliasDb: ", alias_db.toString());
// Maps each Value* in the graph to its index in the values_ array that will
// eventually be created by StaticRuntime.
FastMap<const Value*, uint32_t> value_to_index;
prepareFunctionsAndConstants(graph_->block(), alias_db, value_to_index);
const auto constants_index_offset = 0;
const auto values_index_offset = constants_index_offset + constants().size();
value_buffer_size_ = values_index_offset;
value_buffer_size_ +=
prepareBlockInfo(graph_->block(), values_index_offset, value_to_index);
prepareStaticNodeInfos(graph_->block(), value_to_index, alias_db);
for (auto& block_and_info : block_infos_) {
auto& block_info = block_and_info.second;
block_info.prepare_for_memory_planner(alias_db, opts);
}
}
size_t StaticModule::prepareBlockInfo(
Block* block,
const size_t start_idx,
FastMap<const Value*, uint32_t>& value_to_index) {
block_infos_.emplace(block, BlockInfo(start_idx, *block));
const auto num_inputs = block->inputs().size();
for (const auto i : c10::irange(num_inputs)) {
value_to_index.emplace(block->inputs()[i], start_idx + i);
}
auto cur_idx = start_idx + num_inputs;
for (auto* node : block->nodes()) {
for (auto* sub_block : node->blocks()) {
cur_idx += prepareBlockInfo(sub_block, cur_idx, value_to_index);
}
if (node->kind() == prim::Constant) {
continue;
}
TORCH_CHECK(
cur_idx < (1 << 16),
"outputs offset in values table",
cur_idx,
" would overflow 2-byte index storage");
const auto num_outputs = node->outputs().size();
for (const auto i : c10::irange(num_outputs)) {
value_to_index.emplace(node->outputs()[i], cur_idx + i);
}
cur_idx += num_outputs;
}
std::vector<uint16_t> output_indices;
output_indices.reserve(block->outputs().size());
for (auto* output : block->outputs()) {
const auto output_idx = value_to_index.at(output);
TORCH_CHECK(
output_idx < (1 << 16),
"outputs offset in values table",
output_idx,
" would overflow 2-byte index storage");
output_indices.push_back(output_idx);
}
block_infos_.at(block).set_output_indices(std::move(output_indices));
return cur_idx - start_idx;
}
void StaticModule::attachNodeMetadata(Block* block) {
for (auto* node : block->nodes()) {
if (node->kind() == prim::fork) {
node->ival_(getStaticRuntimeMetadataSymbol(), IValue(sr_metadata_));
}
for (auto* sub_block : node->blocks()) {
attachNodeMetadata(sub_block);
}
}
}
void StaticModule::prepareFunctionsAndConstants(
Block* block,
const AliasDb& alias_db,
FastMap<const Value*, uint32_t>& value_to_index) {
for (auto* node : block->nodes()) {
for (auto* sub_block : node->blocks()) {
prepareFunctionsAndConstants(sub_block, alias_db, value_to_index);
}
if (node->kind() == prim::Constant) {
auto* v = node->output();
TORCH_CHECK(v->type()->kind() != FunctionType::Kind);
value_to_index.emplace(v, constants_.size());
constants_.emplace_back(toIValue(v).value());
continue;
}
// see [Check and correct bad schema alias info at runtime]
bool check_outputs_for_overlap =
!alias_db.mayContainAlias(node->inputs(), node->outputs()) &&
containTensorsOnly(node->outputs());
// new ProcessedFunction
functions_.emplace_back(
node, opts_.enable_out_variant, check_outputs_for_overlap);
}
}
size_t StaticModule::prepareStaticNodeInfos(
Block* block,
const FastMap<const Value*, uint32_t>& value_to_index,
const AliasDb& alias_db,
size_t node_idx) {
const auto node_start = node_idx;
auto& block_info = block_infos_.at(block);
std::vector<StaticNodeInfo> nodes;
FastMap<Node*, bool> node_has_out_variant;
for (auto* node : block->nodes()) {
if (node->kind() == prim::Constant) {
continue;
}
for (auto* sub_block : node->blocks()) {
node_idx +=
prepareStaticNodeInfos(sub_block, value_to_index, alias_db, node_idx);
}
ProcessedNodeInputs input_indices(node->inputs().size());
for (const auto input_idx : c10::irange(node->inputs().size())) {
auto* input = node->inputs()[input_idx];
auto input_ivalue_idx = value_to_index.at(input);
TORCH_CHECK(
input_ivalue_idx < (1 << 16),
"input index in values table ",
input_ivalue_idx,
" would overflow 2-byte index storage");
input_indices[input_idx] = input_ivalue_idx;
}
ProcessedFunction* fn = &functions_[node_idx];
// create a new ProcessedNode
const auto node_output_idx = node->outputs().empty()
// The index is unused if there are no outputs, so just create a
// placeholder value.
? std::numeric_limits<uint16_t>::max()
: value_to_index.at(node->output(0));
nodes.emplace_back(node, fn, std::move(input_indices), node_output_idx);
node_has_out_variant.emplace(node, nodes.back().has_out_variant());
++node_idx;
}
block_info.set_nodes(std::move(nodes), node_has_out_variant);
block_info.init_value_group(alias_db);
return node_idx - node_start;
}
void BlockInfo::set_nodes(
std::vector<StaticNodeInfo> nodes,
const FastMap<Node*, bool>& node_has_out_variant) {
nodes_ = std::move(nodes);
for (auto& node : nodes_) {
if (node.num_outputs() == 1 &&
isOptimizableContainerType(node.node(), node_has_out_variant)) {
node_is_optimizable_container_type_.emplace(node.node());
}
}
}
void BlockInfo::prepare_for_memory_planner(
const AliasDb& alias_db,
const StaticModuleOptions& opts) {
if (!opts.enable_out_variant) {
return;
}
// Never manage graph outputs so that we can do std::move(output_ivalue).
// This does not affect performance if the graph returns a collection object.
FastSet<const Value*> graph_output_values(
block_.outputs().begin(), block_.outputs().end());
// collect register indices of outputs of ops with out variant
for (StaticNodeInfo& pnode : nodes_) {
if (!pnode.has_out_variant()) {
continue;
}
auto outputs = pnode.node()->outputs();
for (const auto i : c10::irange(outputs.size())) {
const Value* out_v = outputs[i];
// Types are stored in the underlying TorchScript IR
bool is_tensor_type = out_v->type()->castRaw<TensorType>();
if (opts.manage_output_tensors && is_tensor_type &&
graph_output_values.find(out_v) == graph_output_values.end() &&
value_group_.isOutputAlias(out_v)) {
managed_output_tensor_values_.insert(out_v);
continue;
}
if (value_group_.isAlwaysAlive(out_v)) {
continue;
}
if (is_tensor_type) {
managed_tensor_values_.insert(out_v);
} else if (node_is_optimizable_container_type(pnode.node())) {
// We "leak" certain container types because their allocations
// take a long time
leaked_values_.insert(out_v);
}
}
}
for (const Value* output : block_.outputs()) {
managed_tensor_values_.erase(output);
}
GRAPH_DEBUG("managed_tensor_values: ", dumpValueSet(managed_tensor_values_));
GRAPH_DEBUG(
"managed_output_tensor_values_: ",
dumpValueSet(managed_output_tensor_values_));
managed_tensor_ranges_ =
ManagedTensorRanges(block_, alias_db, managed_tensor_values_);
}
const StaticModuleOptions& StaticModule::opts() const {
return opts_;
}
size_t StaticModule::num_outputs() const {
return graph_->outputs().size();
}
size_t StaticModule::num_inputs() const {
return num_inputs_;
}
StaticRuntime& StaticModule::runtime() {
if (!cached_runtime_) {
cached_runtime_ = std::make_unique<StaticRuntime>(*this);
}
return *cached_runtime_;
}
Node* StaticModule::findNodeWithKindForTesting(const std::string& kind) const {
for (auto& block_and_info : block_infos_) {
auto& block_info = block_and_info.second;
for (auto& pnode : block_info.nodes()) {
if (pnode.node()->kind().toQualString() == kind) {
return pnode.node();
}
}
}
return nullptr;
}
c10::IValue StaticModule::operator()(
const std::vector<c10::IValue>& args,
const KeywordArgs& kwargs) {
return runtime()(args, kwargs);
}
c10::IValue StaticModule::operator()(
std::vector<c10::IValue>&& args,
const KeywordArgs& kwargs) {
return runtime()(std::move(args), kwargs);
}
BlockRunner::BlockRunner(
const StaticModule& sm,
IValue* values,
Block* block,
torch::jit::TaskLauncher* launcher,
bool is_root_block)
: static_module_(sm),
block_info_(static_module_.block_info(block)),
is_root_block_(is_root_block),
first_input_is_self_(
is_root_block_ && static_module_.first_input_is_self()),
inputs_begin_(block_info_.block_inputs_idx()),
// TODO(T108633124): Turn on manage output tensors for sub-blocks.
manage_output_tensors_enabled_(
is_root_block_ && sm.opts().manage_output_tensors),
values_(values) {
nodes_.reserve(block_info_.nodes().size());
for (auto& pre_pnode : block_info_.nodes()) {
nodes_.emplace_back(pre_pnode, values_);
}
for (auto index : block_info_.block_output_indices()) {
outputs_.emplace_back(&values_[index]);
}
for (auto& pnode : nodes_) {
auto* node = pnode.node();
// attach the async taskLauncher to processedNodes
pnode.set_metadata(launcher);
auto blocks = node->blocks();
const auto num_blocks = blocks.size();
if (num_blocks == 0) {
continue;
}
DCHECK(node->kind() == prim::If || node->kind() == prim::Loop);
std::vector<BlockRunner> block_runners;
block_runners.reserve(num_blocks);
for (auto* b : blocks) {
block_runners.emplace_back(sm, values_, b, launcher);
}
pnode.set_metadata(std::move(block_runners));
}
}
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
BlockRunner::BlockRunner(BlockRunner&&) noexcept = default;
BlockRunner::~BlockRunner() = default;
void BlockRunner::set_arg(const size_t idx, std::vector<IValue>&& args) {
DCHECK(idx < args.size());
Input(idx + first_input_is_self_) = std::move(args[idx]);
}
void BlockRunner::set_arg(const size_t idx, const std::vector<IValue>& args) {
DCHECK(idx < args.size());
Input(idx + first_input_is_self_) = args[idx];
}
void BlockRunner::set_arg(const size_t idx, const IValue& arg) {
Input(idx + first_input_is_self_) = arg;
}
namespace {
void check_type(const Argument& schema_arg, const IValue& arg) {
// Fast path for most common case
if (arg.isTensor() &&
schema_arg.type()->kind() == c10::TypeKind::TensorType) {
return;
}
TORCH_CHECK(arg.type()->isSubtypeOf(schema_arg.type()));
}
} // namespace
template <typename IValueList>
void BlockRunner::set_inputs(
IValueList&& args,
const std::unordered_map<std::string, c10::IValue>& kwargs) {
const auto& schema = static_module_.schema();
if (first_input_is_self_) {
Input(0) = static_module_.module()._ivalue();
}
if (!is_root_block_ || C10_UNLIKELY(!schema)) {
TORCH_CHECK(
kwargs.empty(), "Schema is not available, but BlockRunner got kwargs.");
const auto total_num_inputs = args.size() + first_input_is_self_;
TORCH_CHECK(total_num_inputs == block_info_.num_inputs());
for (size_t i = 0; i < args.size(); ++i) {
set_arg(i, std::forward<IValueList>(args));
}
return;
}
const auto& schema_args = schema->arguments();
size_t consumed_kwargs = 0;
DCHECK(schema_args.size() > 0);
TORCH_CHECK(
args.size() < schema_args.size(),
"Static runtime got too many arguments");
for (size_t i = 0; i < schema_args.size() - 1; ++i) {
// Start at 1 since the schema always contains `self`.
const auto& schema_arg = schema_args[i + 1];
if (i < args.size()) {
check_type(schema_arg, args[i]);
set_arg(i, std::forward<IValueList>(args));
continue;
}
auto it = kwargs.find(schema_arg.name());
if (it != kwargs.end()) {
check_type(schema_arg, it->second);
set_arg(i, it->second);
++consumed_kwargs;
continue;
}
auto maybe_default_val = schema_arg.default_value();
if (maybe_default_val) {
set_arg(i, *maybe_default_val);
continue;
}
TORCH_CHECK(
false, "Static runtime is missing required kwarg ", schema_arg.name());
}
TORCH_CHECK(consumed_kwargs == kwargs.size());
}
void BlockRunner::create_memory_planner() {
if (!planner_) {
planner_ = std::make_unique<StandardMemoryPlanner>(
this,
block_info_,
static_module_.opts().enable_out_variant,
manage_output_tensors_enabled_,
static_module_.opts().optimize_memory);
}
}
namespace {
void destroyNodeOutputs(ProcessedNode& p_node) {
const auto borrows_outputs = borrowsOutputs(p_node.node()->kind());
for (const auto i : c10::irange(p_node.num_outputs())) {
auto& output = p_node.Output(i);
if (doesNotHeapAllocateWhenStoredInIValue(*output.type())) {
continue;
}