forked from pytorch/executorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmethod.cpp
1460 lines (1335 loc) · 50.4 KB
/
method.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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <executorch/runtime/executor/method.h>
#include <array>
#include <cinttypes> // @donotremove
#include <cstdint>
#include <cstdio>
#include <executorch/runtime/backend/interface.h>
#include <executorch/runtime/core/event_tracer_hooks.h>
#include <executorch/runtime/core/exec_aten/util/tensor_util.h>
#include <executorch/runtime/core/span.h>
#include <executorch/runtime/executor/memory_manager.h>
#include <executorch/runtime/executor/platform_memory_allocator.h>
#include <executorch/runtime/executor/program.h>
#include <executorch/runtime/executor/tensor_parser.h>
#include <executorch/runtime/kernel/kernel_runtime_context.h>
#include <executorch/runtime/kernel/operator_registry.h>
#include <executorch/runtime/platform/assert.h>
#include <executorch/runtime/platform/log.h>
#include <executorch/runtime/platform/profiler.h>
#include <executorch/schema/program_generated.h>
namespace executorch {
namespace runtime {
using internal::PlatformMemoryAllocator;
/**
* Runtime state for a backend delegate.
*/
// This lint wants to wrap the class in an anonymous namespace, but it must be
// visible because it's forward-declared and used in Executor.h.
// @lint-ignore CLANGTIDY facebook-hte-ShadowingClass
class BackendDelegate final {
public:
/**
* Initializes an already-allocated BackendDelegate from its serialized
* representation.
*
* @param[in] delegate The serialized backend delegate to load.
* @param[in] program The serialized program to load from.
* @param[in] backend_init_context The context pointer to pass to the
* backend's init() method.
* @param[out] out The BackendDelegate to initialize.
*
* @returns Error::Ok if the initialization succeeded, or an error otherwise.
*/
static Error Init(
const executorch_flatbuffer::BackendDelegate& delegate,
const Program* program,
BackendInitContext& backend_init_context,
BackendDelegate* out) {
// Look up the backend.
ET_CHECK_OR_RETURN_ERROR(
delegate.id() != nullptr, InvalidProgram, "Missing backend id");
const char* backend_id = delegate.id()->c_str();
BackendInterface* backend = get_backend_class(backend_id);
ET_CHECK_OR_RETURN_ERROR(
backend != nullptr,
NotFound,
"Backend %s is not registered.",
backend_id);
ET_CHECK_OR_RETURN_ERROR(
backend->is_available(),
NotFound,
"Backend %s is not available.",
backend_id);
// Get the delegate data.
Result<FreeableBuffer> processed_data = GetProcessedData(delegate, program);
if (!processed_data.ok()) {
ET_LOG(Error, "Failed to load data for backend %s", backend_id);
return processed_data.error();
}
// Parse compilation specs from program
CompileSpec* compile_specs;
Error err = PopulateCompileSpecs(
delegate.compile_specs(), backend_init_context, &compile_specs);
if (err != Error::Ok) {
ET_LOG(Error, "Failed to get compile specs for backend %s", backend_id);
return err;
}
size_t num_compile_specs = delegate.compile_specs()->size();
out->backend_ = backend;
out->handle_ = nullptr;
// Pass a pointer to this buffer to the backend. It's safe for the backend
// to point its handle to this object, since it will outlive the backend.
new (&out->segment_) FreeableBuffer(std::move(processed_data.get()));
// Initialize the delegate.
Result<DelegateHandle*> handle = backend->init(
backend_init_context,
&out->segment_,
ArrayRef<CompileSpec>(compile_specs, num_compile_specs));
if (!handle.ok()) {
ET_LOG(
Error,
"Init failed for backend %s: 0x%" PRIx32,
backend_id,
static_cast<uint32_t>(handle.error()));
out->segment_.Free();
return handle.error();
}
out->handle_ = handle.get();
return Error::Ok;
}
~BackendDelegate() {
if (backend_ != nullptr) {
backend_->destroy(handle_);
}
}
Error Execute(
BackendExecutionContext& backend_execution_context,
EValue** args) const {
EXECUTORCH_SCOPE_PROF("delegate_execute");
return backend_->execute(backend_execution_context, handle_, args);
}
private:
// Not constructible.
BackendDelegate() = delete;
// Disallow copy/move.
BackendDelegate(const BackendDelegate&) = delete;
BackendDelegate& operator=(const BackendDelegate&) = delete;
BackendDelegate(BackendDelegate&&) = delete;
BackendDelegate& operator=(BackendDelegate&&) = delete;
static Error PopulateCompileSpecs(
const flatbuffers::Vector<flatbuffers::Offset<
executorch_flatbuffer::CompileSpec>>* compile_specs_in_program,
BackendInitContext& backend_init_context,
CompileSpec** out_spec) {
auto number_of_compile_specs = compile_specs_in_program->size();
CompileSpec* compile_specs_list =
backend_init_context.get_runtime_allocator()->allocateList<CompileSpec>(
number_of_compile_specs);
if (compile_specs_list == nullptr) {
return Error::MemoryAllocationFailed;
}
// Initialize the spec list for each method spec
for (size_t j = 0; j < number_of_compile_specs; j++) {
auto compile_spec_in_program = compile_specs_in_program->Get(j);
compile_specs_list[j].key = compile_spec_in_program->key()->c_str();
compile_specs_list[j].value = {
/*buffer*/ static_cast<void*>(
const_cast<uint8_t*>(compile_spec_in_program->value()->Data())),
/*nbytes*/ compile_spec_in_program->value()->size(),
};
}
*out_spec = compile_specs_list;
return Error::Ok;
}
static Result<FreeableBuffer> GetProcessedData(
const executorch_flatbuffer::BackendDelegate& delegate,
const Program* program) {
const executorch_flatbuffer::BackendDelegateDataReference* processed =
delegate.processed();
switch (processed->location()) {
case executorch_flatbuffer::DataLocation::INLINE: {
const void* data;
size_t size;
Error err = program->get_backend_delegate_data(
processed->index(), &data, &size);
if (err != Error::Ok) {
return err;
}
return FreeableBuffer(
data,
size,
/*free_fn=*/nullptr);
}
case executorch_flatbuffer::DataLocation::SEGMENT: {
const char* backend_id = delegate.id()->c_str();
return program->LoadSegment(DataLoader::SegmentInfo(
DataLoader::SegmentInfo::Type::Backend,
processed->index(),
backend_id));
}
default:
ET_LOG(
Error,
"Unknown data location %u",
static_cast<unsigned int>(processed->location()));
return Error::Internal;
}
}
FreeableBuffer segment_;
const BackendInterface* backend_;
DelegateHandle* handle_;
};
/**
* Runtime state for a chain of instructions.
*/
struct Chain {
/// Pointer to the associated flatbuffer chain.
const executorch_flatbuffer::Chain* s_chain_;
/// Each entry is a list of parameters for a kernel or delegate call.
Span<InstructionArgs> argument_lists_;
/// Each instruction will have one kernel (not for delegate).
OpFunction* kernels_;
};
namespace {
Result<InstructionArgs> gen_instruction_arguments(
MemoryAllocator* method_allocator,
size_t num_values,
EValue* values,
size_t num_args,
const int32_t* arg_idxs) {
EValue** arg_list = method_allocator->allocateList<EValue*>(num_args);
if (arg_list == nullptr) {
return Error::MemoryAllocationFailed;
}
for (size_t i = 0; i < num_args; ++i) {
int32_t arg_idx = arg_idxs[i];
ET_CHECK_OR_RETURN_ERROR(
arg_idx < num_values,
InvalidProgram,
"Arg index %d >= %zu",
arg_idx,
num_values);
arg_list[i] = &values[arg_idx];
}
return InstructionArgs(arg_list, num_args);
}
Result<bool> parse_cond_value(const EValue& cond_value) {
// The cond value attached to the JF instruction at the beginning of an
// if/else branch is a Tensor which we parse and decide whether to continue
// to execute the if branch or jump to the else branch.
// The cond value attached to the JF instruction at the end of the if branch
// is a Bool Scalar which resolves to false and points us to the instruction
// to jump to which will take us to a point that is after the else branch.
if (cond_value.isTensor()) {
const exec_aten::Tensor& cond_val = cond_value.toTensor();
// All the tensors and scalar cond values should be of bool type
// currently. If that's not the case then something is wrong in the model
// and we should exit.
ET_CHECK_OR_RETURN_ERROR(
exec_aten::ScalarType::Bool == cond_val.scalar_type(),
InvalidProgram,
"Expected dtype of %" PRId8 " got %" PRId8,
static_cast<int8_t>(exec_aten::ScalarType::Bool),
static_cast<int8_t>(cond_val.scalar_type()));
const bool* cond_data = cond_val.const_data_ptr<bool>();
for (size_t i = 0; i < cond_val.numel(); i++) {
if (!cond_data[i]) {
return false;
}
}
} else if (cond_value.isBool()) {
if (!cond_value.toBool()) {
return false;
}
} else {
ET_LOG(
Error, "Unsupported JF EValue type %" PRIu32, (uint32_t)cond_value.tag);
return Error::InvalidProgram;
}
return true;
}
} // namespace
Error Method::parse_values() {
auto flatbuffer_values = serialization_plan_->values();
ET_CHECK_OR_RETURN_ERROR(
flatbuffer_values != nullptr, InvalidProgram, "Missing values");
size_t n_value = flatbuffer_values->size();
values_ = memory_manager_->method_allocator()->allocateList<EValue>(n_value);
if (values_ == nullptr) {
return Error::MemoryAllocationFailed;
}
// n_value_ counts the number of successfully-initialized values for ~Method()
// to clean up, and is incremented at the bottom of the loop. This makes it
// safe for errors to return without updating any state.
n_value_ = 0;
for (size_t i = 0; i < n_value; ++i) {
auto serialization_value = flatbuffer_values->Get(i);
// Ensure that the `val_as_X()` calls will return non-null pointers.
ET_CHECK_OR_RETURN_ERROR(
serialization_value != nullptr &&
(serialization_value->val_type() ==
executorch_flatbuffer::KernelTypes::Null ||
serialization_value->val() != nullptr),
InvalidProgram,
"Null value at index %zu",
i);
const auto val = serialization_value->val();
switch (serialization_value->val_type()) {
case executorch_flatbuffer::KernelTypes::Null: {
// Placement new as the list elements are not initialized, so calling
// copy assignment is not defined if its non trivial (Imagine the
// garbage in values_[i] thinks its an at::Tensor).
new (&values_[i]) EValue();
} break;
case executorch_flatbuffer::KernelTypes::Int: {
new (&values_[i]) EValue(
static_cast<const executorch_flatbuffer::Int*>(val)->int_val());
} break;
case executorch_flatbuffer::KernelTypes::Double: {
new (&values_[i])
EValue(static_cast<const executorch_flatbuffer::Double*>(val)
->double_val());
} break;
case executorch_flatbuffer::KernelTypes::Bool: {
new (&values_[i]) EValue(
static_cast<const executorch_flatbuffer::Bool*>(val)->bool_val());
} break;
case executorch_flatbuffer::KernelTypes::IntList: {
const auto items =
static_cast<const executorch_flatbuffer::IntList*>(val)->items();
ET_CHECK_OR_RETURN_ERROR(
items != nullptr, InvalidProgram, "Missing list at index %zu", i);
// Allocate space for boxed and unboxed list representations using
// values_ as source of truth
auto* evalp_list =
memory_manager_->method_allocator()->allocateList<EValue*>(
items->size());
auto* int_list =
memory_manager_->method_allocator()->allocateList<int64_t>(
items->size());
// initialize boxed list
for (size_t j = 0; j < items->size(); j++) {
auto value_index = items->Get(j);
ET_CHECK_OR_RETURN_ERROR(
value_index >= 0 && value_index < n_value,
InvalidProgram,
"Invalid value index %" PRId64 " for IntList %zu index %zu",
value_index,
i,
j);
evalp_list[j] = &values_[static_cast<size_t>(value_index)];
}
new (&values_[i]) EValue(
BoxedEvalueList<int64_t>(evalp_list, int_list, items->size()));
} break;
case executorch_flatbuffer::KernelTypes::BoolList: {
const auto items =
static_cast<const executorch_flatbuffer::BoolList*>(val)->items();
ET_CHECK_OR_RETURN_ERROR(
items != nullptr, InvalidProgram, "Missing list at index %zu", i);
// NOTE: This is technically not portable. A platform could technically
// define boolean as something longer than a byte. This would be an
// exceptionally rare case, and this type is currently unused in any
// operators in ATen that we would need to support. To be properly
// portable here we need to allocate a new array of bool and copy cast
// the flatbuffer data into it, but because of how exceptionally rare
// this case is its low prio TODO: jakeszwe
new (&values_[i]) EValue(exec_aten::ArrayRef<bool>(
(const bool*)items->data(), items->size()));
} break;
case executorch_flatbuffer::KernelTypes::DoubleList: {
const auto items =
static_cast<const executorch_flatbuffer::DoubleList*>(val)->items();
ET_CHECK_OR_RETURN_ERROR(
items != nullptr, InvalidProgram, "Missing list at index %zu", i);
new (&values_[i])
EValue(exec_aten::ArrayRef<double>(items->data(), items->size()));
} break;
case executorch_flatbuffer::KernelTypes::String: {
const auto fb_str =
static_cast<const executorch_flatbuffer::String*>(val)
->string_val();
ET_CHECK_OR_RETURN_ERROR(
fb_str != nullptr,
InvalidProgram,
"Missing string at index %zu",
i);
new (&values_[i]) EValue(fb_str->c_str(), fb_str->size());
} break;
case executorch_flatbuffer::KernelTypes::Tensor: {
auto t = deserialization::parseTensor(
program_,
memory_manager_,
static_cast<const executorch_flatbuffer::Tensor*>(val));
if (!t.ok()) {
ET_LOG(
Error,
"Failed parsing tensor at index %zu: 0x%" PRIx32,
i,
static_cast<uint32_t>(t.error()));
return t.error();
}
new (&values_[i]) EValue(t.get());
} break;
case executorch_flatbuffer::KernelTypes::TensorList: {
const auto items =
static_cast<const executorch_flatbuffer::TensorList*>(val)->items();
ET_CHECK_OR_RETURN_ERROR(
items != nullptr, InvalidProgram, "Missing list at index %zu", i);
// get list of serialization tensors and allocate storage for executor
// tensors
auto tensors = deserialization::parseTensorList(
items,
values_,
n_value, // The size of the full array.
memory_manager_);
if (!tensors.ok()) {
ET_LOG(
Error,
"Failed parsing tensor list at index %zu: 0x%" PRIx32,
i,
static_cast<uint32_t>(tensors.error()));
return tensors.error();
}
new (&values_[i]) EValue(tensors.get());
} break;
case executorch_flatbuffer::KernelTypes::OptionalTensorList: {
const auto items =
static_cast<const executorch_flatbuffer::OptionalTensorList*>(val)
->items();
ET_CHECK_OR_RETURN_ERROR(
items != nullptr, InvalidProgram, "Missing list at index %zu", i);
// Same as TensorList but optional<Tensor> instead of Tensor
auto tensors =
deserialization::parseListOptionalType<exec_aten::Tensor>(
items,
values_,
n_value, // The size of the full array.
memory_manager_);
if (!tensors.ok()) {
ET_LOG(
Error,
"Failed parsing optional tensor list at index %zu: 0x%" PRIx32,
i,
static_cast<uint32_t>(tensors.error()));
return tensors.error();
}
new (&values_[i]) EValue(tensors.get());
} break;
default:
// flatbuffer enums start at 0, but they generate a hidden NONE enum
// and give it that value. schema.fbs doesnt show this type, so I
// subtract one to keep the output in 0 based indexing for a
// disgruntled debugger seeing this error message and checking
// schema.fbs
ET_LOG(
Error,
"Unknown KernelTypes value %" PRIu32 " at index %zu",
static_cast<uint32_t>(serialization_value->val_type()) - 1,
i);
return Error::InvalidProgram;
}
// ~Method() will try to clean up n_value_ entries in the values_ array.
// Only increment this once we know the entry is valid, so that we don't try
// to clean up an uninitialized entry.
n_value_ = i + 1;
}
return Error::Ok;
}
namespace {
/**
* Private/helper method for populating operator_name from the Operator.
* operator_name is a char pointer that is already allocated. The size of
* of this buffer is of size operator_name_size.
*/
Error populate_operator_name(
const executorch_flatbuffer::Operator* const& op,
const size_t operator_name_size,
char* operator_name) {
const bool has_overload =
op->overload() != nullptr && op->overload()->size() > 0;
ET_CHECK_OR_RETURN_ERROR(
op->name() != nullptr, InvalidProgram, "Missing operator name");
int cx = snprintf(
operator_name,
operator_name_size,
"%s%s%s",
op->name()->c_str(),
// Don't append any overload if the overload string is empty.
has_overload ? "." : "",
has_overload ? op->overload()->c_str() : "");
ET_CHECK_OR_RETURN_ERROR(cx >= 0, Internal, "snprintf failed: %d", cx);
ET_CHECK_OR_RETURN_ERROR(
cx < operator_name_size,
Internal,
"Operator name %s%s%s with length %d "
"truncated to %zu due to internal buffer limit.",
op->name()->c_str(),
has_overload ? "." : "",
has_overload ? op->overload()->c_str() : "",
cx,
operator_name_size);
return Error::Ok;
}
} // namespace
Error Method::resolve_operator(
int32_t op_index,
OpFunction* kernels,
size_t kernel_index,
InstructionArgs args,
size_t n_args) {
// TODO(T153505381, T153506819) Investigate optimizing this function for both
// space and time.
// resolve name
constexpr size_t kTempBufferSizeForName = 100;
char operator_name[kTempBufferSizeForName];
const auto ops = serialization_plan_->operators();
ET_CHECK_OR_RETURN_ERROR(
ops != nullptr && op_index < ops->size(),
InvalidProgram,
"Op index %" PRIu32 " out of range",
op_index);
const auto& op = ops->Get(op_index);
Error err = populate_operator_name(op, kTempBufferSizeForName, operator_name);
if (err != Error::Ok) {
return err;
}
// resolve tensor meta
auto method_allocator = memory_manager_->method_allocator();
TensorMeta* meta = method_allocator->allocateList<TensorMeta>(n_args);
if (meta == nullptr) {
return Error::MemoryAllocationFailed;
}
size_t count = 0;
for (size_t i = 0; i < n_args; i++) {
EValue* eval = args[i];
// handle tensor list as well
if (eval->isTensor()) {
auto tensor = eval->toTensor();
meta[count].dtype_ = tensor.scalar_type();
exec_aten::DimOrderType* dim_order_ptr =
method_allocator->allocateList<exec_aten::DimOrderType>(tensor.dim());
if (dim_order_ptr == nullptr) {
return Error::MemoryAllocationFailed;
}
size_t size = tensor.dim();
err = get_dim_order(tensor, dim_order_ptr, size);
ET_CHECK_OR_RETURN_ERROR(
err == Error::Ok,
InvalidArgument,
"Error setting dim_order %zu: 0x%" PRIx32,
i,
static_cast<uint32_t>(err));
meta[count].dim_order_ =
Span<exec_aten::DimOrderType>(dim_order_ptr, size);
count++;
}
}
// Find a kernel with the matching name and tensor meta.
Result<OpFunction> op_function =
get_op_function_from_registry(operator_name, {meta, count});
if (!op_function.ok()) {
ET_LOG(Error, "Missing operator: [%d] %s", op_index, operator_name);
return op_function.error();
}
kernels[kernel_index] = op_function.get();
return Error::Ok;
}
Result<Method> Method::load(
executorch_flatbuffer::ExecutionPlan* s_plan,
const Program* program,
MemoryManager* memory_manager,
EventTracer* event_tracer) {
MemoryAllocator* temp_allocator = memory_manager->temp_allocator();
if (temp_allocator == nullptr) {
PlatformMemoryAllocator* platform_allocator =
memory_manager->method_allocator()
->allocateInstance<PlatformMemoryAllocator>();
if (platform_allocator == nullptr) {
return Error::MemoryAllocationFailed;
}
new (platform_allocator) PlatformMemoryAllocator();
temp_allocator = platform_allocator;
}
Method method(program, memory_manager, event_tracer, temp_allocator);
Error err = method.init(s_plan);
if (err != Error::Ok) {
return err;
} else {
ET_CHECK(method.initialized());
return method;
}
}
Error Method::init(executorch_flatbuffer::ExecutionPlan* s_plan) {
EXECUTORCH_SCOPE_PROF("Method::init");
internal::EventTracerProfileMethodScope event_tracer_profile_scope =
internal::EventTracerProfileMethodScope(event_tracer_, "Method::init");
ET_CHECK_OR_RETURN_ERROR(
// Don't use !initialized() here because we also want to fail on the
// InitializationFailed state.
init_state_ == InitializationState::Uninitialized,
InvalidState,
"Method already initialized, or previously failed to initialize.");
init_state_ =
InitializationState::InitializationFailed; // Until proven otherwise
serialization_plan_ = s_plan;
auto method_allocator = memory_manager_->method_allocator();
{
// Parse the elements of the values_ array.
Error err = parse_values();
if (err != Error::Ok) {
return err;
}
}
{
// Resolve delegates
const auto delegates = serialization_plan_->delegates();
ET_CHECK_OR_RETURN_ERROR(
delegates != nullptr, InvalidProgram, "Missing delegates field");
size_t n_delegate = delegates->size();
delegates_ = method_allocator->allocateList<BackendDelegate>(n_delegate);
if (delegates_ == nullptr) {
return Error::MemoryAllocationFailed;
}
// n_delegate_ counts the number of successfully-initialized delegates for
// ~Method() to clean up, and is incremented at the bottom of the loop. This
// makes it safe for errors to return without updating any state.
n_delegate_ = 0;
for (size_t i = 0; i < n_delegate; ++i) {
const auto& delegate = *delegates->Get(i);
BackendInitContext backend_init_context(
method_allocator,
/*event_tracer=*/event_tracer_,
/*method_name=*/serialization_plan_->name()->c_str());
Error err = BackendDelegate::Init(
delegate, program_, backend_init_context, &delegates_[i]);
if (err != Error::Ok) {
return err;
}
// ~Method() will try to clean up n_delegate_ entries in the delegates_
// array. Only increment this once we know the entry is valid, so that
// we don't try to clean up an uninitialized entry.
n_delegate_ = i + 1;
}
}
{
// Load chains
const auto chains = serialization_plan_->chains();
ET_CHECK_OR_RETURN_ERROR(
chains != nullptr && chains->size() > 0, InvalidProgram, "No chains");
n_chains_ = chains->size();
chains_ = method_allocator->allocateList<Chain>(n_chains_);
if (chains_ == nullptr) {
return Error::MemoryAllocationFailed;
}
// Try resolving all operators before failing, to make it easier to debug
// multiple problems at once.
Error delayed_error = Error::Ok;
int32_t num_instructions_missing_op = 0;
for (size_t i = 0; i < n_chains_; ++i) {
auto s_chain = chains->Get(i);
auto s_instructions = s_chain->instructions();
ET_CHECK_OR_RETURN_ERROR(
s_instructions != nullptr,
InvalidProgram,
"Missing instructions in chain %zu",
i);
auto num_instructions = s_instructions->size();
auto chain_instruction_kernels =
method_allocator->allocateList<OpFunction>(num_instructions);
if (chain_instruction_kernels == nullptr) {
return Error::MemoryAllocationFailed;
}
auto chain_instruction_arg_lists =
method_allocator->allocateList<InstructionArgs>(num_instructions);
if (chain_instruction_arg_lists == nullptr) {
return Error::MemoryAllocationFailed;
}
// Set up the argument lists ahead of time and store pointers to them to
// use when the instructions are called
for (size_t instr_idx = 0; instr_idx < s_instructions->size();
++instr_idx) {
const auto instruction = s_instructions->Get(instr_idx);
// Ensure that the `instr_args_as_X()` calls will return non-null.
ET_CHECK_OR_RETURN_ERROR(
instruction != nullptr && instruction->instr_args() != nullptr,
InvalidProgram,
"Null instruction at index %zu",
instr_idx);
const void* instr_args = instruction->instr_args();
switch (instruction->instr_args_type()) {
case executorch_flatbuffer::InstructionArguments::KernelCall: {
const auto* instr_args_as_KernelCall =
static_cast<const executorch_flatbuffer::KernelCall*>(
instr_args);
const auto arg_idxs = instr_args_as_KernelCall->args();
ET_CHECK_OR_RETURN_ERROR(
arg_idxs != nullptr, InvalidProgram, "KernelCall args missing");
auto res = gen_instruction_arguments(
method_allocator,
n_value_,
values_,
arg_idxs->size(),
arg_idxs->data());
if (!res.ok()) {
return res.error();
}
chain_instruction_arg_lists[instr_idx] = res.get();
auto err = resolve_operator(
instr_args_as_KernelCall->op_index(),
chain_instruction_kernels,
instr_idx,
res.get(),
arg_idxs->size());
if (err == Error::OperatorMissing) {
num_instructions_missing_op++;
} else if (err == Error::MemoryAllocationFailed) {
return err;
} else {
delayed_error = err;
}
} break;
case executorch_flatbuffer::InstructionArguments::DelegateCall: {
const auto arg_idxs =
static_cast<const executorch_flatbuffer::DelegateCall*>(
instr_args)
->args();
ET_CHECK_OR_RETURN_ERROR(
arg_idxs != nullptr,
InvalidProgram,
"DelegateCall args missing");
auto res = gen_instruction_arguments(
method_allocator,
n_value_,
values_,
arg_idxs->size(),
arg_idxs->data());
if (!res.ok()) {
return res.error();
}
chain_instruction_arg_lists[instr_idx] = res.get();
} break;
case executorch_flatbuffer::InstructionArguments::JumpFalseCall: {
// Validate the index at load time so we can trust it during
// execution.
auto index =
static_cast<const executorch_flatbuffer::JumpFalseCall*>(
instr_args)
->cond_value_index();
ET_CHECK_OR_RETURN_ERROR(
index >= 0 && index < n_value_,
InvalidProgram,
"Index %d negative or >= %zu",
index,
n_value_);
chain_instruction_arg_lists[instr_idx] = InstructionArgs();
} break;
default: {
chain_instruction_arg_lists[instr_idx] = InstructionArgs();
} break;
}
}
chains_[i] = Chain{
s_chain,
Span<InstructionArgs>(chain_instruction_arg_lists, num_instructions),
chain_instruction_kernels,
};
}
ET_CHECK_OR_RETURN_ERROR(
num_instructions_missing_op == 0,
OperatorMissing,
"There are %d instructions don't have corresponding operator registered. "
"See logs for details",
num_instructions_missing_op);
if (delayed_error != Error::Ok) {
return delayed_error;
}
}
step_state_ = StepState{0, 0};
init_state_ = InitializationState::Initialized;
return Error::Ok;
}
ET_NODISCARD Error
Method::set_input(const EValue& input_evalue, size_t input_idx) {
ET_CHECK_OR_RETURN_ERROR(
initialized(),
InvalidState,
"Input can not be set until method has been initialized.");
ET_CHECK_OR_RETURN_ERROR(
step_state_.instr_idx == 0 && step_state_.chain_idx == 0,
InvalidState,
"Inputs can not be set mid execution.");
ET_CHECK_OR_RETURN_ERROR(
input_idx < inputs_size(),
InvalidArgument,
"Input index (%zu) must be less than the number of inputs in method (%zu).",
input_idx,
inputs_size());
const auto& e = get_value(get_input_index(input_idx));
if (!e.isTensor() && !e.isScalar()) {
#if ET_LOG_ENABLED
std::array<char, kTagNameBufferSize> tag_name;
tag_to_string(e.tag, tag_name.data(), tag_name.size());
ET_LOG(
Error,
"Input %zu was expected to be a Tensor or primitive but was %s.",
input_idx,
tag_name.data());
#endif
return Error::InvalidArgument;
}
if (e.tag != input_evalue.tag) {
#if ET_LOG_ENABLED
std::array<char, kTagNameBufferSize> e_tag_name;
std::array<char, kTagNameBufferSize> input_tag_name;
tag_to_string(e.tag, e_tag_name.data(), e_tag_name.size());
tag_to_string(
input_evalue.tag, input_tag_name.data(), input_tag_name.size());
ET_LOG(
Error,
"Input %zu was expected to have type %s but was %s.",
input_idx,
e_tag_name.data(),
input_tag_name.data());
#endif
return Error::InvalidArgument;
}
if (e.isTensor()) {
const auto& t_dst = e.toTensor();
const auto& t_src = input_evalue.toTensor();
ET_CHECK_OR_RETURN_ERROR(
t_dst.scalar_type() == t_src.scalar_type(),
InvalidArgument,
"Input %zu has unexpected scalar type: expected %s but was %s.",
input_idx,
executorch::runtime::toString(t_dst.scalar_type()),
executorch::runtime::toString(t_src.scalar_type()));
// Reset the shape for the Method's input as the size of forwarded input
// tensor for shape dynamism. Also is a safety check if need memcpy.
Error err = resize_tensor(t_dst, t_src.sizes());
ET_CHECK_OR_RETURN_ERROR(
err == Error::Ok,
InvalidArgument,
"Error setting input %zu: 0x%" PRIx32,
input_idx,
static_cast<uint32_t>(err));
Error error;
auto tensor_meta = this->method_meta().input_tensor_meta(input_idx);
if (tensor_meta->is_memory_planned()) {
error = internal::copy_tensor_data(t_dst, t_src);
} else {
error = internal::share_tensor_data(t_dst, t_src);
}
ET_CHECK_OR_RETURN_ERROR(
error == Error::Ok,
InvalidArgument,
"Error setting data_ptr %zu: 0x%" PRIx32,
input_idx,
static_cast<uint32_t>(error));
// Prims have to be the same as what was traced
} else if (e.isInt()) {
ET_CHECK_OR_RETURN_ERROR(
e.toInt() == input_evalue.toInt(),
InvalidArgument,
"The %zu-th input of method should have the same value as the input_evalue, but got %" PRId64
" and %" PRId64,
input_idx,
e.toInt(),
input_evalue.toInt());
} else if (e.isBool()) {
ET_CHECK_OR_RETURN_ERROR(
e.toBool() == input_evalue.toBool(),
InvalidArgument,
"The %zu-th input of method should have the same value as the input_evalue, but got %" PRId64
" and %" PRId64,
input_idx,
(int64_t)e.toBool(),
(int64_t)input_evalue.toBool());
} else if (e.isDouble()) {
double lhs = input_evalue.toDouble();
double rhs = e.toDouble();
double atol = 1e-4;
double rtol = 1e-5;
bool is_equal = true;
if (std::isnan(lhs) && std::isnan(rhs)) {
// NaN == NaN
} else if (
!std::isfinite(lhs) && !std::isfinite(rhs) &&
((lhs > 0) == (rhs > 0))) {
// -Inf == -Inf
// +Inf == +Inf
} else {
auto allowed_error = atol + std::abs(rtol * rhs);
auto actual_error = std::abs(lhs - rhs);
if (!std::isfinite(actual_error) || actual_error > allowed_error) {
is_equal = false;
}
}
ET_CHECK_OR_RETURN_ERROR(
is_equal,
InvalidArgument,
"The %zu-th input of method should have the same value as the input_evalue, but get %f and %f",
input_idx,
lhs,
rhs);
} else if (e.isString()) {
ET_CHECK_OR_RETURN_ERROR(
e.toString() == input_evalue.toString(),
InvalidArgument,
"The %zu-th input of method should have the same value as the input_evalue, but get %s and %s",
input_idx,
e.toString().data(),
input_evalue.toString().data());
} else {
#if ET_LOG_ENABLED
std::array<char, kTagNameBufferSize> tag_name;
tag_to_string(e.tag, tag_name.data(), tag_name.size());
ET_LOG(Error, "Unsupported input type: %s", tag_name.data());
#endif
return Error::InvalidArgument;
}
return Error::Ok;
}
ET_NODISCARD Error
Method::set_inputs(const exec_aten::ArrayRef<EValue>& input_evalues) {
ET_CHECK_OR_RETURN_ERROR(
initialized(),
InvalidState,
"Inputs can not be set until method has been initialized.");
ET_CHECK_OR_RETURN_ERROR(
step_state_.instr_idx == 0 && step_state_.chain_idx == 0,
InvalidState,
"Inputs can not be set mid execution.");
size_t input_size = inputs_size();
ET_CHECK_OR_RETURN_ERROR(
input_size == input_evalues.size(),
InvalidArgument,
"The length of given input array (%zu) must be same as the number of inputs in method (%zu).",
input_evalues.size(),
input_size);
for (size_t i = 0; i < input_size; i++) {
Error status = set_input(input_evalues[i], i);
if (status != Error::Ok) {
return status;
}
}
return Error::Ok;
}
ET_NODISCARD Error