/
aot_executor_codegen.cc
1455 lines (1310 loc) · 60.4 KB
/
aot_executor_codegen.cc
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
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file src/relay/backend/aot_executor_codegen.cc
* \brief AOT executor codegen
*/
#include <tvm/ir/module.h>
#include <tvm/relay/attrs/annotation.h>
#include <tvm/relay/attrs/call.h>
#include <tvm/relay/executor.h>
#include <tvm/relay/expr_functor.h>
#include <tvm/relay/runtime.h>
#include <tvm/runtime/device_api.h>
#include <tvm/runtime/name_transforms.h>
#include <tvm/runtime/object.h>
#include <tvm/tir/analysis.h>
#include <tvm/tir/builtin.h>
#include <tvm/tir/expr.h>
#include <tvm/tir/function.h>
#include <tvm/tir/stmt.h>
#include <tvm/tir/transform.h>
#include <tvm/tir/usmp/utils.h>
#include <algorithm>
#include <list>
#include <string>
#include <vector>
#include "../../target/source/codegen_source_base.h"
#include "../../tir/transforms/ir_utils.h"
#include "../op/annotation/annotation.h"
#include "../op/call/call.h"
#include "../op/memory/device_copy.h"
#include "../transforms/device_aware_visitors.h"
#include "./name_transforms.h"
#include "./te_compiler.h"
#include "./utils.h"
namespace tvm {
namespace relay {
namespace backend {
using StorageMap =
std::unordered_map<Expr, StorageInfo, runtime::ObjectPtrHash, runtime::ObjectPtrEqual>;
/**
* This is an on demand allocator for AOT. A new temporary
* (storage allocator identifier) is allocated for each operation.
*/
class AOTOnDemandAllocator : public transform::DeviceAwareExprVisitor {
public:
AOTOnDemandAllocator() : transform::DeviceAwareExprVisitor(Optional<IRModule>()) {}
// run the visitor on a global function.
void Run(const Function& func) { VisitExpr(func); }
std::vector<int> GetReturnIds() const { return return_ids_; }
std::vector<TensorType> GetReturnTtypes() const { return return_ttypes_; }
StorageMap GetStorageMap() const { return storage_device_map_; }
using ExprVisitor::VisitExpr_;
void VisitExpr_(const ConstantNode* op) final {
CreateStorage(op);
AssignReturnSid(GetRef<Expr>(op));
}
void DeviceAwareVisitExpr_(const CallNode* call_node) final {
// AOTOnDemandAllocator is run both before and after lowering, so we need to handle the case
// where the op of the call is a generic function
Expr func;
Array<Expr> args;
CallLoweredProps call_lowered_props = GetCallLoweredProps(call_node);
if (call_lowered_props.lowered_func.defined()) {
func = call_lowered_props.lowered_func;
args = call_lowered_props.arguments;
} else { // Relay functions that have not been lowered and lowered extern functions
func = call_node->op;
args = call_node->args;
if (call_node->op.as<GlobalVarNode>()) { // Lowered extern function
ICHECK(!(call_node->attrs.defined())) << "Extern functions should have null attributes.";
} else { // Relay function which has not been lowered yet
ICHECK(call_node->op.as<FunctionNode>())
<< "Expected the call to be to a lowered primfunc, a lowered extern function or a "
"unlowered Relay function.";
}
}
VisitExpr(func);
CreateStorage(call_node);
for (const Expr& arg : args) {
VisitExpr(arg);
}
AssignReturnSid(GetRef<Expr>(call_node));
}
void VisitExpr_(const VarNode* op) final { AssignReturnSid(GetRef<Expr>(op)); }
void DeviceAwareVisitExpr_(const FunctionNode* func_node) final {
if (function_nesting() > 1) {
// do not recurse into sub functions.
return;
}
if (func_node->HasNonzeroAttr(attr::kPrimitive)) {
// No storage needed for primitive functions.
return;
}
for (const auto& param : func_node->params) {
CreateStorage(param.get());
}
VisitExpr(func_node->body);
}
void VisitExpr_(const GlobalVarNode* op) final {
// Do nothing.
}
void VisitExpr_(const OpNode* op) final {
// Do nothing.
}
void VisitExpr_(const TupleNode* op) final {
std::vector<int64_t> storage_ids;
std::vector<VirtualDevice> virtual_devices;
std::vector<int64_t> storage_sizes_in_bytes;
Expr expr = GetRef<Expr>(op);
for (Expr field : op->fields) {
auto sid = GetStorage(field);
storage_ids.insert(storage_ids.end(), sid->storage_ids.begin(), sid->storage_ids.end());
virtual_devices.insert(virtual_devices.end(), sid->virtual_devices.begin(),
sid->virtual_devices.end());
storage_sizes_in_bytes.insert(storage_sizes_in_bytes.end(),
sid->storage_sizes_in_bytes.begin(),
sid->storage_sizes_in_bytes.end());
}
storage_device_map_[expr] = StorageInfo(storage_ids, virtual_devices, storage_sizes_in_bytes);
AssignReturnSid(expr);
}
void VisitExpr_(const TupleGetItemNode* op) final {
Expr expr = GetRef<Expr>(op);
auto sids = GetStorage(op->tuple);
ICHECK_LT(static_cast<size_t>(op->index), sids->storage_ids.size());
storage_device_map_[expr] =
StorageInfo({sids->storage_ids[op->index]}, {sids->virtual_devices[op->index]},
{sids->storage_sizes_in_bytes[op->index]});
AssignReturnSid(expr);
}
void VisitExpr_(const IfNode* op) final { LOG(FATAL) << "if is not supported."; }
void PreVisitLetBinding_(const Var& var, const Expr& value) final {
VisitExpr(value);
StorageInfo si = GetStorage(value);
storage_device_map_[var] = si;
}
private:
void AssignReturnSid(Expr e) {
if (storage_device_map_.find(e) != storage_device_map_.end()) {
StorageInfo& sinfo = storage_device_map_[e];
return_ids_.clear();
for (auto sid : sinfo->storage_ids) {
return_ids_.push_back(sid);
}
return_ttypes_.clear();
return_ttypes_ = FlattenTupleType(e->checked_type());
}
}
/*!
* \brief ceil(size/word_size) to get number of words.
* \param size The original size.
* \param word_size The element size.
*/
static size_t DivRoundUp(size_t size, size_t word_size) {
return (size + word_size - 1) / word_size;
}
/*!
* \brief Get the memory requirement.
* \param prototype The prototype token.
* \return The required memory size.
*
* TODO(mbs): Cf CalculateRelayExprSizeBytes in utils.cc, GetMemorySize is graph_plan_memory.cc
*/
size_t GetMemorySizeBytes(const TensorType& ttype) {
size_t size = 1;
for (IndexExpr dim : ttype->shape) {
const int64_t* pval = tir::as_const_int(dim);
ICHECK(pval != nullptr) << "Cannot allocate memory symbolic tensor shape " << ttype->shape;
ICHECK_GE(*pval, 0) << "Cannot allocate memory for tensor with negative shape" << *pval;
size *= static_cast<size_t>(pval[0]);
}
size *= DivRoundUp(ttype->dtype.bits() * ttype->dtype.lanes(), 8);
return size;
}
/*!
* \brief Get the necessary storage for the expression.
* \param expr The expression.
* \return The corresponding token.
*/
StorageInfo GetStorage(const Expr& expr) {
// See through "on_device" calls.
Expr true_expr = IgnoreOnDevice(expr);
VisitExpr(true_expr);
auto it = storage_device_map_.find(true_expr);
ICHECK(it != storage_device_map_.end()) << "Could not find " << true_expr->GetTypeKey() << " "
<< PrettyPrint(true_expr) << " in storage device map";
return it->second;
}
/*!
* \brief Create storage for the expression.
*/
void CreateStorage(const ExprNode* op) {
Expr expr = GetRef<Expr>(op);
return CreateStorage(expr, GetVirtualDevice(expr));
}
/*!
* \brief Create storage to hold the result of evaluating \p expr in \p virtual_device.
*/
void CreateStorage(const Expr& expr, const VirtualDevice& virtual_device) {
ICHECK(!virtual_device->IsFullyUnconstrained())
<< "invalid virtual device for expr:" << std::endl
<< PrettyPrint(expr);
std::vector<int64_t> storage_ids;
std::vector<VirtualDevice> virtual_devices;
std::vector<int64_t> storage_sizes_in_bytes;
for (const auto& ttype : FlattenTupleType(expr->checked_type())) {
storage_ids.push_back(next_available_sid_++);
virtual_devices.push_back(virtual_device);
storage_sizes_in_bytes.push_back(GetMemorySizeBytes(ttype));
}
storage_device_map_[expr] = StorageInfo(std::move(storage_ids), std::move(virtual_devices),
std::move(storage_sizes_in_bytes));
}
/*! \brief mapping of expression -> storageInfo */
StorageMap storage_device_map_;
/*! \brief current id of the temporary allocated */
int next_available_sid_{0};
/*! \brief the set of intermediate tensors that are return variables */
std::vector<int> return_ids_;
/*! \brief the data types of the return values */
std::vector<TensorType> return_ttypes_;
};
/*! \brief Code generator for AOT executor */
class AOTExecutorCodegen : public MixedModeVisitor {
protected:
/*! \brief Describes the type of kernel call emitted. */
enum CallType {
/*!
* \brief Emit PackedFunc calls bound just-in-time using TVMBackend* functions.
*
* When this type is selected, assumes all operators must be called via TVMFuncCall. Given the
* implementation of TVMFuncCall in the C++ runtime, this in practice implies that those
* functions are of type TVMBackendPackedCFunc.
*
* The following code is emitted at call sites to call a function named `func`:
* void* func_ptr = TVMBackendGetFuncFromEnv("func");
* TVMFuncCall(func_ptr, values, tcodes, num_args, ret_values, ret_tcodes)
*
* The arguments given to the tir::Call node are encoded into `values`, `tcodes`, and `num_args`
* by LowerTVMBuiltin TIR transform.
*
* If `resource_handle` is passed to `func`, it is determined by TVMFuncCall (often,
* `resource_handle` is registered with the C++ runtime to provide a `this` equivalent when
* `func` is implemented in C).
*
* Compatible with both C++ and C runtimes, implemented with the C runtime only.
*/
kPacked, // Emit tir.call_packed and wrap all arguments in DLTensor.
/*!
* \brief Directly call a TVMBackendPackedCFunc named according to the tir::Call.
*
* When this type is selected, assumes all operators are implemented in functions of type
* `TVMBackendPackedCFunc` and should be called directly. That is, presumes at the time of
* downstream compilation that there is a symbol named after the 0th arg to tir::Call of
* type `TVMBackendPackedCFunc`. This situation should occur when target_host == target.
*
* The following code is emitted at call sites to call a function named `func`:
* func(values, tcodes, num_args, ret_values, ret_tcodes, resource_handle)
*
* The arguments given to the tir::Call node are encoded into `values`, `tcodes`, and `num_args`
* by LowerTVMBuiltin TIR transform.
*
* `resource_handle` is encoded as the final argument to the tir::Call node. In practice, it is
* always the device context parameter when not null. At present, the implementation does not
* support forwarding device context parameters to CPacked.
*
* Compatible with the C runtime and C++ runtime (so long as target_host == target). Implemented
* in the same scenarios.
*/
kCPacked, // Emit tir.call_cpacked and wrap all arguments in DLTensor.
/*! \brief Directly call a function accepting the `data` arrays as args.
*
* When this type is selected, assumes all operaotrs are implemented in C functions whose
* arguments are 1-to-1 with those in the tir::Call. DLTensor arguments are encoded as just the
* `data` parameters (i.e. no DLTensor object is passed along).
*
* The following code is emitted at call sites to a function named `func`:
* func(void* arg0, void* arg1, ..., void* argN) // no resource_handle
* -or-
* func(void* arg0, void* arg1, ..., void* argN, void* resource_handle) // with resource_handle
*
* `resource_handle` is encoded as the final argument to the tir::Call node. In practice, it is
* always the device context parameter when not null.
*
* Compatible with the C runtime and C++ runtime (so long as target_host == target). Implemented
* with the C runtime only.
*/
kUnpacked, // Emit tir.call_extern passing only the `data` part of DLTensors.
};
/*!
* \brief Return a vector of variables that represents the sids for the given Relay Expr
*/
std::vector<tir::Var> PackSid(Expr expr) {
std::vector<tir::Var> buffer_vars;
ICHECK(storage_device_map_.find(expr) != storage_device_map_.end())
<< "Storage map did not contain constant expr " << PrettyPrint(expr);
StorageInfo& sinfo = storage_device_map_[expr];
// Note that an expression can have multiple sids associated with it
// e.g., returning multiple values from a function
for (auto sid : sinfo->storage_ids) {
// Determine if an sid is an output buffer
auto output_iter = std::find(return_sid_.begin(), return_sid_.end(), sid);
if (output_iter != return_sid_.end()) {
int output_index = std::distance(return_sid_.begin(), output_iter);
buffer_vars.push_back(GetBufferVarForIO(input_vars_.size() + output_index));
continue;
}
auto sid_value = sids_table_[sid];
buffer_vars.push_back(sid_value);
}
return buffer_vars;
}
/*!
* brief Given an expression return the variable(s) associated with that expression
*/
std::vector<te::Var> FindExpr(Expr arg) {
auto input_iter = std::find(input_vars_.begin(), input_vars_.end(), arg);
if (input_iter != input_vars_.end()) {
// Input variable
int main_index = std::distance(input_vars_.begin(), input_iter);
return {GetBufferVarForIO(main_index)};
} else {
// Storage identifier (i.e., intermediate memory)
return PackSid(arg);
}
}
/*!
* \brief Reverse lookup the device name in devices_ map.
* \param device_context Value in devices_ to find.
* \return Key matching device_context in devices_.
*/
std::string FindDeviceName(tir::Var device_context) {
for (std::pair<String, tir::Var> kv : devices_) {
if (kv.second->name_hint == device_context->name_hint) {
return kv.first;
}
}
ICHECK(false) << "Did not find a device name associated with " << device_context;
return "";
}
void PushArgs(const Expr& expr, const std::vector<tir::Var>& sids, Array<PrimExpr>* args) {
const TupleNode* t = expr.as<TupleNode>();
if (t != nullptr) {
CHECK_EQ(sids.size(), t->fields.size()) << "Relay tuple does not map 1:1 into TIR; AOT can't "
"handle this type of Relay Expr in a CallNode.";
}
args->insert(args->end(), sids.begin(), sids.end());
}
/*
* Wraps a call_extern with a tvm_check_return annotation if required otherwise
* returns the passed Call
*/
tir::Call AddCheckReturn(tir::Call existing_call) {
Array<PrimExpr> args = {tir::make_const(DataType::Int(32, 1), 0, Span()),
tir::make_const(DataType::Int(32, 1), -1, Span()), existing_call};
return tir::Call(DataType::Int(32), tir::builtin::tvm_check_return(), args);
}
/*!
* brief Create a function call
* \param call_lowered_props The lowered function and the arguments to call it with
* \param result_expr The call we got func and args from (so as to recover the storage
* ids to hold the result).
*/
void CreateFuncCall(CallLoweredProps call_lowered_props, const Expr& result_expr) {
std::string func_name = call_lowered_props.lowered_func->name_hint;
tvm::Array<PrimExpr> args{tvm::tir::StringImm(func_name)};
std::vector<tir::Stmt> create_func_call_stmts;
// Pack the inputs
for (const Expr& arg : call_lowered_props.arguments) {
if (params_by_expr_.find(arg) != params_by_expr_.end()) {
auto param_handle = tvm::tir::Call(DataType::Handle(), tvm::tir::builtin::lookup_param(),
{tir::StringImm(params_by_expr_[arg])});
// NOTE: this cast looks like a no-op, but is required for compilation downstream.
// Because DataType::Handle has default bits=64, but CodeGenC does not observe this field,
// adding this cast forces the codegen to insert the cast. In this case, a cast is required
// because param_handle is actually code-generated as `const void*`, and the `const` piece
// needs to be removed.
args.push_back(tvm::tir::Cast(DataType::Handle(32, 1), param_handle));
} else {
auto sids = FindExpr(arg);
PushArgs(arg, sids, &args);
}
}
// Pack the return(s) value. A call node can produce multiple outputs
auto result_expr_sid = PackSid(result_expr);
PushArgs(result_expr, result_expr_sid, &args);
GlobalVar global_var = call_lowered_props.lowered_func;
bool has_c_device_api_context = device_contexts_.count(global_var) != 0;
tir::Var device_context;
tir::Stmt func_call;
switch (call_type_) {
case CallType::kUnpacked: {
// call_extern calling convention with optional context
if (has_c_device_api_context) {
device_context = device_contexts_.Get(global_var).value();
// call_extern has no further legalization steps, and
// requires the number of arguments to match exactly. For
// internal calls, conditionally append the device context.
bool requires_device_context = [&]() -> bool {
Optional<Integer> opt = num_arguments_.Get(global_var);
if (!opt.defined()) {
// For external calls, we must trust that the user has
// supplied a kernel that accepts a device_context
// argument.
return true;
}
int num_callee_params = opt.value()->value;
int num_args = call_lowered_props.arguments.size();
if (num_callee_params == num_args) {
return false;
} else if (num_callee_params == num_args + 1) {
return true;
} else {
LOG(FATAL) << "Callee " << global_var << " requires " << num_callee_params
<< ", but is called with " << num_args << " arguments.";
}
}();
if (requires_device_context) {
args.push_back(device_context);
}
}
func_call = tir::Evaluate(AddCheckReturn(
tvm::tir::Call(DataType::Int(32), tvm::tir::builtin::call_extern(), args)));
break;
}
case CallType::kCPacked: {
if (has_c_device_api_context) {
device_context = device_contexts_.Get(global_var).value();
args.push_back(device_context);
} else {
// NOTE: LowerTVMBuiltin expects some device_context placeholder.
args.push_back(tir::make_zero(DataType::Handle()));
}
func_call = tir::Evaluate(
tvm::tir::Call(DataType::Int(32), tvm::tir::builtin::tvm_call_cpacked(), args));
create_func_call_stmts.push_back(func_call);
break;
}
case CallType::kPacked: {
// call_packed does not accept a device context.
CHECK(!has_c_device_api_context) << "CallType::kPacked does not accept a device context";
func_call = tir::Evaluate(AddCheckReturn(
tvm::tir::Call(DataType::Int(32), tvm::tir::builtin::tvm_call_packed(), args)));
create_func_call_stmts.push_back(func_call);
break;
}
default:
ICHECK(false) << "Unknown CallType: " << call_type_;
}
ICHECK(func_call.defined()) << "Must define func_call";
if (has_c_device_api_context) {
func_call = tir::SeqStmt(Array<tir::Stmt>({
GenerateDeviceHook(device_context, "Open"),
func_call,
GenerateDeviceHook(device_context, "Close"),
}));
}
tir::Stmt body = tir::SeqStmt::Flatten(func_call);
stmts_.push_back(body);
}
/*!
* \brief Copy a variable to the output. This function is mainly used in edge cases
* when we want to return an input or a parameter.
* TODO(giuseros): we should try to avoid unnecessary copy to the output, e.g., in a
* copy-on-write fashion.
*/
void CopyToOutput(PrimExpr out, PrimExpr in, bool pack_input, size_t size) {
std::vector<tir::Stmt> let_nest;
// Define intermediate DLTensor to load/store the data
tir::Buffer tmp_read =
tir::decl_buffer({IntImm(DataType::UInt(64), size)}, DataType::UInt(8), "tmp_read");
tir::Buffer tmp_write =
tir::decl_buffer({IntImm(DataType::UInt(64), size)}, DataType::UInt(8), "tmp_write");
// Re-use in/out as the buffer var, if possible
if (auto opt = out.as<tir::Var>()) {
tmp_write.CopyOnWrite()->data = opt.value();
} else {
let_nest.push_back(tir::LetStmt(tmp_write->data, out, tir::Evaluate(0)));
}
if (auto opt = in.as<tir::Var>()) {
tmp_read.CopyOnWrite()->data = opt.value();
} else {
let_nest.push_back(tir::LetStmt(tmp_read->data, in, tir::Evaluate(0)));
}
// Copy the variable from the input to the output
te::Var loop_idx("i", DataType::Int(32));
tir::Stmt copy = tir::BufferStore(tmp_write, tir::BufferLoad(tmp_read, {loop_idx}), {loop_idx});
copy = tir::For(loop_idx, 0, tir::make_const(DataType::Int(32, 1), size, Span()),
tir::ForKind::kSerial, copy);
copy = tir::MergeNest(let_nest, copy);
stmts_.push_back(copy);
}
/*
* \brief Collects device context variables for passing to operators
*/
void CollectDeviceVariables(const Map<GlobalVar, String>& device_contexts) {
Map<TargetKind, tir::Var> target_contexts;
TargetKindAttrMap<Bool> target_attr_map = tvm::TargetKind::GetAttrMap<Bool>("use_device_api");
for (const auto& it : device_contexts) {
const GlobalVar& global_var = it.first;
const std::string device_context_name = it.second;
Optional<TargetKind> target_kind = tvm::TargetKind::Get(device_context_name);
if (!target_kind || !target_attr_map.count(target_kind.value())) {
return;
}
if (target_attr_map[target_kind.value()]) {
std::string context_name = tvm::runtime::SanitizeName(device_context_name);
tir::Var device_context_var("device_context_" + context_name, DataType::Handle());
auto pair = target_contexts.find(target_kind.value());
if (pair != target_contexts.end()) {
device_context_var = (*pair).second;
} else {
main_signature_.push_back(device_context_var);
devices_.Set(context_name, device_context_var);
target_contexts.Set(target_kind.value(), device_context_var);
}
device_contexts_.Set(global_var, device_context_var);
}
}
}
/**
* \brief Generates a call to a given hook for all Devices found for C Device API
* \param Name of hook to generate statements for
* \return Statement with function calls for each device
*/
tir::Stmt GenerateAllDeviceHook(const String& hook) {
std::vector<tir::Stmt> device_hooks;
for (const auto& it : devices_) {
const String& device_name = it.first;
const tir::Var& context = it.second;
Array<String> sections = {"Device", device_name, hook};
String device_hook_name = ToCFunctionStyle(PrefixName(sections));
tir::Evaluate device_hook(
AddCheckReturn(tvm::tir::Call(DataType::Int(32), tvm::tir::builtin::call_extern(),
{tvm::tir::StringImm(device_hook_name), context})));
device_hooks.push_back(device_hook);
}
return tir::SeqStmt::Flatten(device_hooks);
}
/**
* \brief Generates a call to a given hook for a single Device function
* \param Var Device context to call hook on
* \param Name of hook to generate statements for
* \return Statement with function call to Device API
*/
tir::Stmt GenerateDeviceHook(const tir::Var& context, const String& hook) {
const auto& it = std::find_if(std::begin(devices_), std::end(devices_), [&](const auto& it) {
return it.second->name_hint == context->name_hint;
});
const String& device_name = (*it).first;
Array<String> sections = {"Device", device_name, hook};
String device_hook = ToCFunctionStyle(PrefixName(sections));
return tir::Evaluate(
AddCheckReturn(tir::Call(DataType::Int(32), tvm::tir::builtin::call_extern(),
{tvm::tir::StringImm(device_hook), context})));
}
/*!
* Utility function to string together different arguments
*/
template <typename... Args>
std::string MakeString(Args const&... args) {
std::ostringstream ss;
using List = int[];
(void)List{0, ((void)(ss << args), 0)...};
return ss.str();
}
void VisitExpr_(const CallNode* call_node) override {
OnDeviceProps on_device_props = GetOnDeviceProps(call_node);
if (on_device_props.body.defined()) {
VisitExpr(on_device_props.body);
return;
}
DeviceCopyProps device_copy_props = GetDeviceCopyProps(call_node);
CallLoweredProps call_lowered_props = GetCallLoweredProps(call_node);
if (device_copy_props.body.defined()) {
// TODO(mbs): device_copy cleaunp
// Suspect treating as no-op is better since already built into the StorageInfo?
LOG(FATAL) << "The AOT executor does not currently support device_copy";
}
// At this point we should only see calls of the form call_lowered(@callee, (args...)),
// where @callee can be a PrimFunc we've compiled or an external function supplied via
// some other mechanism.
ICHECK(call_lowered_props.lowered_func.defined())
<< "AOT does not support calling Relay functions. Attempting to call:" << std::endl
<< PrettyPrint(GetRef<Call>(call_node));
for (const auto& arg : call_lowered_props.arguments) {
// Evaluate the args
VisitExpr(arg);
}
CreateFuncCall(call_lowered_props, GetRef<Call>(call_node));
}
void VisitExpr_(const VarNode* op) override {
Expr expr = GetRef<Expr>(op);
StorageInfo& sinfo = storage_device_map_[expr];
// Let bound vars refer to a value, so these should not be considered "output" vars.
if (let_bound_vars_.find(GetRef<Var>(op)) != let_bound_vars_.end()) {
return;
}
// If the Var node is an output node we need to copy the content of the variable to the output
// It's safe to check the SID here because Var StorageToken are never reallocated
auto output_iter = std::find(return_sid_.begin(), return_sid_.end(), sinfo->storage_ids[0]);
if (output_iter != return_sid_.end()) {
int output_index = std::distance(return_sid_.begin(), output_iter);
if (params_by_expr_.find(expr) != params_by_expr_.end()) {
auto param_handle = tvm::tir::Call(DataType::Handle(), tvm::tir::builtin::lookup_param(),
{tir::StringImm(params_by_expr_[expr])});
CopyToOutput(GetBufferVarForIO(input_vars_.size() + output_index), param_handle,
/*pack_input*/ false, sinfo->storage_sizes_in_bytes[0]);
} else {
auto var_expr = FindExpr(expr);
CopyToOutput(GetBufferVarForIO(input_vars_.size() + output_index), var_expr[0],
/*pack_input*/ false, sinfo->storage_sizes_in_bytes[0]);
}
}
}
void VisitExpr_(const ConstantNode* op) override {
Expr expr = GetRef<Expr>(op);
ICHECK(storage_device_map_.find(expr) != storage_device_map_.end())
<< "Storage map did not contain constant expr " << PrettyPrint(expr);
StorageInfo& sinfo = storage_device_map_[expr];
std::stringstream ss;
ss << "constant_" << constant_map_.size();
tir::Var constant(ss.str(), PointerType(PrimType(DataType(op->data->dtype))));
constant_map_[constant] = op;
auto sid = sinfo->storage_ids[0];
sids_table_[sid] = constant;
// If the Constant node is an output node we need to copy the content of the parameter to the
// output. A node can only produce a single output
auto output_iter = std::find(return_sid_.begin(), return_sid_.end(), sid);
if (output_iter != return_sid_.end()) {
int output_index = std::distance(return_sid_.begin(), output_iter);
auto param_handle = tvm::tir::Call(DataType::Handle(), tvm::tir::builtin::lookup_param(),
{tir::StringImm(ss.str())});
CopyToOutput(GetBufferVarForIO(input_vars_.size() + output_index), constant,
/* pack_input */ false, sinfo->storage_sizes_in_bytes[0]);
}
}
void VisitExpr_(const TupleNode* op) override {
for (auto field : op->fields) {
VisitExpr(field);
}
}
void VisitExpr_(const LetNode* op) override {
auto pre_visit = [this](const LetNode* op) {
let_bound_vars_.insert(op->var);
this->VisitExpr(op->value);
};
auto post_visit = [this](const LetNode* op) {
this->VisitExpr(op->body);
this->visit_counter_[op] += 1;
};
ExpandANormalForm(op, pre_visit, post_visit);
}
void VisitExpr_(const TupleGetItemNode* op) override { VisitExpr(op->tuple); }
void VisitExpr_(const OpNode* op) override {
if (GetRef<Op>(op) != CallLoweredOp() && GetRef<Op>(op) != OnDeviceOp()) {
LOG(FATAL) << "All OpNodes except for call_lowered should have been expanded";
}
}
void VisitExpr_(const IfNode* op) override {
LOG(FATAL) << "All GlobalVarNodes should be removed before AOT executor's Codegen is called";
}
void VisitExpr_(const FunctionNode* op) override {
ICHECK(op->GetAttr<String>(attr::kCompiler).defined())
<< "FunctionNode only supported by custom codegen";
}
void VisitExpr_(const RefCreateNode* op) override {
LOG(FATAL) << "AOT executor does not support references (found RefCreateNode)";
}
void VisitExpr_(const RefReadNode* op) override {
LOG(FATAL) << "AOT executor does not support references (found RefReadNode)";
}
void VisitExpr_(const RefWriteNode* op) override {
LOG(FATAL) << "AOT executor does not support references (found RefWriteNode)";
}
void VisitExpr_(const ConstructorNode* op) override {
LOG(FATAL) << "AOT executor does not support ADTs (found ConstructorNode)";
}
void VisitExpr_(const MatchNode* op) override {
LOG(FATAL) << "AOT executor does not support matching (found MatchNode)";
}
// Create the main PrimFunc to execute the graph. Please note that
// the packed function calls don't pack their arguments. The AOT
// runner function needs to be legalized by the LegalizePackedCalls pass.
tir::PrimFunc CreateMainFunc(String mod_name, unsigned int relay_params) {
tir::Stmt body = tir::SeqStmt::Flatten(stmts_);
// Allocate the sids
std::unordered_map<int, bool> allocated;
for (auto kv : storage_device_map_) {
// Only allocate sids that are needed
const bool is_input =
(std::find(input_vars_.begin(), input_vars_.end(), kv.first) != input_vars_.end());
const bool is_param = (params_by_expr_.find(kv.first) != params_by_expr_.end());
if (is_input || is_param) {
continue;
}
for (unsigned int i = 0; i < kv.second->storage_ids.size(); i++) {
int size = kv.second->storage_sizes_in_bytes[i];
int sid = kv.second->storage_ids[i];
if (std::find(return_sid_.begin(), return_sid_.end(), sid) != return_sid_.end()) {
continue;
}
// Make sure it hasn't already been allocated, this can happen
// with let-bound var/value pairs.
if (allocated.find(sid) != allocated.end()) {
continue;
}
allocated[sid] = constant_map_.count(sids_table_[sid]);
// TODO(giuseros): we should allocate this once outside the PrimFunc
// so we don't pay the price of allocation for every inference
if (!allocated[sid]) {
PointerType ptype = Downcast<PointerType>(sids_table_[sid]->type_annotation);
DataType element_type = Downcast<PrimType>(ptype->element_type)->dtype;
body = tir::Allocate(sids_table_[sid], element_type, {size}, tir::const_true(), body);
}
allocated[sid] = true;
}
}
for (auto kv : constant_map_) {
auto buffer_var = kv.first;
auto dtype = DataType(kv.second->data->dtype);
int ndim = kv.second->data->ndim;
Array<PrimExpr> extents;
for (int i = 0; i < ndim; i++) {
int shape = kv.second->data->shape[i];
extents.push_back(tir::make_const(DataType::Int(32), shape, Span()));
}
body = tir::AllocateConst(buffer_var, dtype, extents, kv.second->data, body);
}
// Define the PrimFunc attributes
Map<String, ObjectRef> dict_attrs;
String run_func_name = runtime::get_name_mangled(mod_name, runtime::symbol::tvm_module_main);
dict_attrs.Set("global_symbol", run_func_name);
dict_attrs.Set("runner_function", Bool(true));
dict_attrs.Set(tvm::attr::kTarget, config_->host_target);
tir::Stmt device_activations = GenerateAllDeviceHook("Activate");
tir::Stmt device_deactivations = GenerateAllDeviceHook("Deactivate");
tir::Stmt final_body = tir::SeqStmt({device_activations, body, device_deactivations});
// Make the PrimFunc
return tir::PrimFunc(main_signature_, final_body, VoidType(), main_buffer_map_,
DictAttrs(dict_attrs));
}
/*!
* \brief Access IO vars using the buffer vars and
* not the actual var.
*/
tir::Var GetBufferVarForIO(int index) { return main_buffer_map_[main_signature_[index]]->data; }
/*!
* \brief Create tir::Var for input/output while updating the buffer_maps.
*
* \param expr The expression to evaluate.
* \param original_name The name of the tir::Var.
* \param use_unique_name Whether to generate a new unique name where a name conflicts.
*/
void CreateIOVar(const Expr& expr, const std::string& original_name,
bool use_unique_name = true) {
CreateIOVar(expr->checked_type(), original_name, use_unique_name);
}
/*!
* \brief Create tir::Var for input/output while updating the buffer_maps.
*
* \param expr The expression to evaluate.
* \param original_name The name of the tir::Var.
* \param use_unique_name Whether to generate a new unique name where a name conflicts.
*/
void CreateIOVar(const Type& type, const std::string& original_name,
bool use_unique_name = true) {
if (type->IsInstance<TupleTypeNode>()) {
TupleType tuple_type = Downcast<TupleType>(type);
for (unsigned i = 0; i < tuple_type->fields.size(); i++) {
CreateIOVar(tuple_type->fields[i], original_name);
}
} else {
std::string name = original_name;
if (use_unique_name) {
name = GetUniqueIOVarName(original_name);
}
tir::Var var = tir::Var(name, DataType::Handle());
main_signature_.push_back(var);
auto tensor_type = type.as<TensorTypeNode>();
ICHECK(tensor_type) << "Expected TensorType node but was " << type->GetTypeKey();
DataType elem_type = tensor_type->dtype;
tir::Var buffer_var =
tir::Var(name + "_buffer_var", PointerType(PrimType(elem_type), "global"));
tir::Buffer buffer = tir::Buffer(buffer_var, elem_type, tensor_type->shape, {}, 0,
name + "_buffer", 16, 1, tir::BufferType::kDefault);
main_buffer_map_.Set(var, buffer);
io_tensor_types_.Set(var, Downcast<TensorType>(type));
}
}
/*!
* \brief Create a unique name for I/O Var
*/
std::string GetUniqueIOVarName(std::string name) {
if (io_var_names_.find(name) == io_var_names_.end()) {
io_var_names_[name] = 1;
return name;
} else {
io_var_names_[name] = io_var_names_[name] + 1;
return name + std::to_string(io_var_names_[name]);
}
}
/*!
* \brief Calculate workspace sizes for PrimFuncs in the IRModule
*/
Map<String, FunctionInfo> CalculateWorkspaceSizes(
const IRModule& lowered_mod, const Map<String, FunctionInfo>& function_metadata) {
Integer workspace_byte_alignment = GetModuleWorkspaceByteAlignment(lowered_mod);
Map<String, FunctionInfo> updated_function_metadata;
for (const auto& kv : lowered_mod->functions) {
GlobalVar global_var = kv.first;
BaseFunc base_func = kv.second;
if (base_func->IsInstance<tir::PrimFuncNode>()) {
tir::PrimFunc pfunc = Downcast<tir::PrimFunc>(base_func);
Target tgt = pfunc->GetAttr<Target>(tvm::attr::kTarget).value();
const auto& ws = CalculateWorkspaceBytes(pfunc, workspace_byte_alignment);
if (function_metadata.count(global_var->name_hint)) {
updated_function_metadata.Set(global_var->name_hint,
function_metadata[global_var->name_hint]);
updated_function_metadata[global_var->name_hint]->workspace_sizes.Set(tgt, ws);
} else {
FunctionInfo finfo{{{tgt, ws}}, {}, {}, {{tgt, pfunc}}, {}};
updated_function_metadata.Set(global_var->name_hint, finfo);
}
}
}
return updated_function_metadata;
}
/*!
* \brief Run USMP to plan memory for lowered IRModule.
*/
IRModule PlanMemoryWithUSMP(const IRModule& mod) {
VLOG(1) << "Planning memory with USMP for module:" << std::endl << PrettyPrint(mod);
Integer workspace_byte_alignment = GetModuleWorkspaceByteAlignment(mod);
IRModule lowered_mod = mod->ShallowCopy();
lowered_mod = tir::transform::UnifiedStaticMemoryPlanner()(lowered_mod);
function_metadata_ = CalculateWorkspaceSizes(lowered_mod, function_metadata_);
Optional<Array<tir::usmp::AllocatedPoolInfo>> allocated_pool_infos =
lowered_mod->GetAttr<Array<tir::usmp::AllocatedPoolInfo>>(tvm::attr::kPoolArgs);
backend::FunctionInfo main_func_info =
lowered_mod->GetAttr<backend::FunctionInfo>("main_func_info").value();
main_func_info->workspace_sizes.clear();
if (allocated_pool_infos) {
for (const tir::usmp::AllocatedPoolInfo& allocated_pool_info : allocated_pool_infos.value()) {
for (const auto& tgt : allocated_pool_info->pool_info->targets) {
VLOG(1) << "USMP requires target " << tgt->ToDebugString() << " to have pool size "
<< allocated_pool_info->allocated_size->value;
size_t size = allocated_pool_info->allocated_size->value;
if (allocated_pool_info->pool_info->IsInstance<ConstantPoolInfoNode>()) {
size += main_func_info->constant_sizes.count(tgt)
? main_func_info->constant_sizes[tgt]->value
: 0;
main_func_info->constant_sizes.Set(tgt, size);
} else if (allocated_pool_info->pool_info->IsInstance<WorkspacePoolInfoNode>()) {
size += main_func_info->workspace_sizes.count(tgt)
? main_func_info->workspace_sizes[tgt]->value
: 0;
main_func_info->workspace_sizes.Set(tgt, size);
} else {
LOG(FATAL) << "Unknown pool type: " << allocated_pool_info->pool_info->GetTypeKey();
}
}
}
}
function_metadata_.Set(runtime::symbol::tvm_module_main, main_func_info);
return lowered_mod;
}
/*!
* \brief Run StorageRewrite to plan memory for lowered IRModule.
*/
IRModule PlanMemoryWithStorageRewrite(const IRModule& mod) {
Integer workspace_byte_alignment = GetModuleWorkspaceByteAlignment(mod);
IRModule lowered_mod = mod->ShallowCopy();
function_metadata_ = CalculateWorkspaceSizes(lowered_mod, function_metadata_);
// Running StorageRewrite just on the main function
tir::PrimFunc tir_main_func =
Downcast<tir::PrimFunc>(lowered_mod->Lookup(::tvm::runtime::symbol::tvm_module_main));
IRModule main_func_mod;
main_func_mod->Update(lowered_mod->GetGlobalVar(::tvm::runtime::symbol::tvm_module_main),
tir_main_func);
main_func_mod = tir::transform::StorageRewrite()(main_func_mod);
lowered_mod->Update(lowered_mod->GetGlobalVar(::tvm::runtime::symbol::tvm_module_main),
main_func_mod->Lookup(::tvm::runtime::symbol::tvm_module_main));
tir_main_func =
Downcast<tir::PrimFunc>(lowered_mod->Lookup(::tvm::runtime::symbol::tvm_module_main));
// Use the PrimFunc to calculate the workspace required to service the allocates