forked from pytorch/executorch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharm_executor_runner.cpp
More file actions
1561 lines (1429 loc) · 53.8 KB
/
Copy patharm_executor_runner.cpp
File metadata and controls
1561 lines (1429 loc) · 53.8 KB
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.
* Copyright 2023-2026 Arm Limited and/or its affiliates.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
/* This is an example ExecuTorch runner running on Arm Cortex-M and Ethos-U
* based hardware. This example tries to illustrate a few ways to use ExecuTorch
* and you can use it as is or remove the unneeded parts. Please use this code
* as inspiration.
*
* Some defines used to configure the code:
*
* ET_MODEL_PTE_ADDR - Where in memory/flash your PTE model data is.
* ET_MODEL_PTE_SIZE - Size in bytes of the PTE at ET_MODEL_PTE_ADDR. CMake
* defaults to the legacy 0x10000000 upper bound.
* If the address is not set, the model is converted to a
* c-array named model_pte and put into model_pte.h in the
* network_model_sec linker section, controlled by your
* memory mode via the ETHOSU_MODEL cmake parameter. This
* is not used by the
* semihosting path, which either loads the model from a
* file or can reuse an embedded model with
* ET_COMPILED_PTE.
* ET_COMPILED_PTE - In SEMIHOSTING mode, reuse the model embedded in
* model_pte.h instead of passing the PTE as a host file.
* ET_NUM_INFERENCES - Numbers of times to run the inference
* ET_LOG_DUMP_INPUT - Control if you want input to be dumped to the log.
* ET_LOG_DUMP_OUTPUT - Control if you want output to be dumped to the log.
*
* Devtool BundleIO: Use Bundle PTE with input and reference output included to
* check if it matches.
*
* ET_BUNDLE_IO - Build in Devtools BundleIO, this makes it possible to
* use bpte with bundled input and output refdata to
* compare output.
* See also ET_ATOL and ET_RTOL
* ET_ATOL - The atol used to compare the output and ref data
* when using ET_BUNDLE_IO ET_RTOL - The rtol used to compare the
* output and ref data when using ET_BUNDLE_IO
*
* Devtools ETDump: Speed and dumping output
*
* ET_EVENT_TRACER_ENABLED - Build in Devtools ETDump event trace code
* to generate cycle data and print it base64
* coded in the log so you can get it out of
* your embedded target. This can be used to
* benchmark where time is spent. If you run
* on Ethos-U the delegate/commandstream is
* run in one go, this means that per op
* measurements is not possible.
* ET_DUMP_OUTPUTS - Collect and print outputs as a base64 buffer
* in the log, see ExecuTorch Devtools for more
* info. (Requires ET_EVENT_TRACER_ENABLED)
* ET_DUMP_INTERMEDIATE_OUTPUTS - Collect and print intermediate outputs as a
* base64 buffer in the log, see ExecuTorch
* Devtools for more info.
* (Requires ET_EVENT_TRACER_ENABLED)
* ET_DEBUG_BUFFER_SIZE - Override the size of memory area used by
* ET_DUMP_OUTPUTS or
* ET_DUMP_INTERMEDIATE_OUTPUTS
*
* Warning: CPU time measurements is NOT possible in the FVP simulator and a
* real target or FPGA must be used. NPU number are roughly OK, and can be used
* as guidance if timeing adaptor values are set correctly.
*
* SEMIHOSTING - When using the FVP simulator it can be built to access your dev
* machines filesystem. This is used both for unit-test style
* flows that load model and input files from the host and for
* host-driven prompt/input/output exchange while still reusing an
* embedded PTE via ET_COMPILED_PTE. The
* backends/arm/test/setup_testing.sh script builds the unittest
* configuration used with the FVP simulator.
*
* Memory areas used:
* You might want to configure this differently on your HW, like maybe all
* left over memory after code is linked. This needs to be big enough to fit
* and run your model. In our example using the FVP simulator we have much
* memory and set this quite high to be able to test larger models.
* Regarding heap/mallocs type of allocation from ExecuTorch,
* et_pal_allocate() is not implemented or needed.
*
* ET_ARM_BAREMETAL_METHOD_ALLOCATOR_POOL_SIZE - Size of memory area
* used when setting up
* the model
* ET_ARM_BAREMETAL_SEMIHOSTING_FILE_ALLOCATOR_POOL_SIZE
* - Size of memory area
* used to hold
* semihosted files,
* including input
* tensors and, when
* applicable, an
* external PTE file
* ET_ARM_BAREMETAL_FAST_SCRATCH_TEMP_ALLOCATOR_POOL_SIZE - Size of memory area
* used when running
* inferences
* ET_ARM_BAREMETAL_PLANNED_FAST_MEMORY_SIZE - Size of the fast
* planned memory area
* for mem_id = 3
*/
#include <errno.h>
#include <executorch/extension/data_loader/buffer_data_loader.h>
#include <executorch/extension/runner_util/inputs.h>
#include <executorch/runtime/core/exec_aten/util/scalar_type_util.h>
#include <executorch/runtime/core/memory_allocator.h>
#include <executorch/runtime/executor/program.h>
#include <executorch/runtime/platform/log.h>
#include <executorch/runtime/platform/platform.h>
#include <executorch/runtime/platform/runtime.h>
#include <stdio.h>
#include <unistd.h>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
#include "arm_memory_allocator.h"
#include "arm_perf_monitor.h"
// newlib-nano printf does not reliably handle the z length modifier. Values
// logged or printed by this runner use unsigned long with %lu instead of size_t
// with %zu.
using printf_size_t = unsigned long;
#if defined(ET_BUNDLE_IO)
#include <executorch/devtools/bundled_program/bundled_program.h>
#endif
#if defined(ET_EVENT_TRACER_ENABLED)
#include <executorch/devtools/etdump/etdump_flatcc.h>
#if defined(ET_DUMP_INTERMEDIATE_OUTPUTS) || defined(ET_DUMP_OUTPUTS)
#include <executorch/devtools/etdump/data_sinks/buffer_data_sink.h>
#if !defined(ET_DEBUG_BUFFER_SIZE)
#define ET_DEBUG_BUFFER_SIZE (2 * 1024 * 1024)
#endif
#endif
#if !defined(SEMIHOSTING)
#include <executorch/third-party/flatcc/include/flatcc/portable/pbase64.h>
#endif
#endif // defined(ET_EVENT_TRACER_ENABLED)
#if defined(SEMIHOSTING)
/**
* The input_file_allocation_pool should be large enough to fit the various
* input file data used when loading the data files when running semihosting
* e.g. the input file data and the pte file data
* In our unit test flow, we have the capability to provide an enitre model to
* the Corstone-3xx FVP using semi hosting. Hence, the input file allocation
* pool needs to be large enough to take an entire model and input.
* If you use semihosting on your HW this can be lowered to fit your
* files/memory
*/
#if !defined(ET_ARM_BAREMETAL_SEMIHOSTING_FILE_ALLOCATOR_POOL_SIZE)
#define ET_ARM_BAREMETAL_SEMIHOSTING_FILE_ALLOCATOR_POOL_SIZE (60 * 1024 * 1024)
#endif
const size_t input_file_allocation_pool_size =
ET_ARM_BAREMETAL_SEMIHOSTING_FILE_ALLOCATOR_POOL_SIZE;
unsigned char __attribute__((
section(".bss.input_file_allocator_sec"),
aligned(16))) input_file_allocation_pool[input_file_allocation_pool_size];
#endif
#if defined(ET_MODEL_PTE_ADDR) && defined(ET_COMPILED_PTE)
#error "ET_MODEL_PTE_ADDR and ET_COMPILED_PTE are mutually exclusive"
#endif
#if defined(ET_MODEL_PTE_ADDR) && !defined(ET_MODEL_PTE_SIZE)
#error "ET_MODEL_PTE_ADDR requires ET_MODEL_PTE_SIZE"
#endif
#if !defined(ET_MODEL_PTE_ADDR) && !defined(ET_COMPILED_PTE) && \
!defined(SEMIHOSTING)
#error \
"One of ET_MODEL_PTE_ADDR, ET_COMPILED_PTE, or SEMIHOSTING must be defined"
#endif
#if !defined(ET_MODEL_PTE_ADDR) && defined(ET_COMPILED_PTE)
/**
* This header file is generated by the build process based on the .pte file
* specified in the ET_PTE_FILE_PATH variable to the cmake build.
* Control of the action of the .pte, it's use of operators and delegates, and
* which are included in the bare metal build are also orchestrated by the
* CMakeLists file. For example use see examples/arm/run.sh
*
* e.g. This includes the pte as a big chunk of data struct into this file
*/
#include "model_pte.h"
#endif
using executorch::aten::ScalarType;
using executorch::aten::Tensor;
using executorch::aten::TensorImpl;
using executorch::extension::BufferDataLoader;
using executorch::runtime::Error;
using executorch::runtime::EValue;
using executorch::runtime::HierarchicalAllocator;
using executorch::runtime::MemoryAllocator;
using executorch::runtime::MemoryManager;
using executorch::runtime::Method;
using executorch::runtime::MethodMeta;
using executorch::runtime::Program;
using executorch::runtime::Result;
using executorch::runtime::Span;
using executorch::runtime::Tag;
using executorch::runtime::TensorInfo;
using executorch::runtime::toString;
#if defined(ET_BUNDLE_IO)
using executorch::bundled_program::compute_method_output_error_stats;
using executorch::bundled_program::ErrorStats;
using executorch::bundled_program::verify_method_outputs;
#endif
#if defined(ET_EVENT_TRACER_ENABLED)
using executorch::etdump::ETDumpGen;
using executorch::etdump::ETDumpResult;
using executorch::runtime::EventTracerDebugLogLevel;
using torch::executor::etdump_result;
#endif
/**
* The method_allocation_pool should be large enough to fit the setup, input
* used and other data used like the planned memory pool (e.g. memory-planned
* buffers to use for mutable tensor data) In this example we run on a
* Corstone-3xx FVP so we can use a lot of memory to be able to run and test
* large models if you run on HW this should be lowered to fit into your
* availible memory.
*/
#if !defined(ET_ARM_BAREMETAL_METHOD_ALLOCATOR_POOL_SIZE)
#define ET_ARM_BAREMETAL_METHOD_ALLOCATOR_POOL_SIZE (60 * 1024 * 1024)
#endif
const size_t method_allocation_pool_size =
ET_ARM_BAREMETAL_METHOD_ALLOCATOR_POOL_SIZE;
unsigned char __attribute__((
section(".bss.method_allocator_sec"),
aligned(16))) method_allocation_pool[method_allocation_pool_size];
#if defined(ET_BUNDLE_IO)
const size_t testset_idx = 0; // BundleIO test indexes to test if used
#if defined(ET_ATOL)
const float et_atol = ET_ATOL;
#else
const float et_atol = 0.01;
#endif
#if defined(ET_RTOL)
const float et_rtol = ET_RTOL;
#else
const float et_rtol = 0.01;
#endif
#endif
#if defined(ET_NUM_INFERENCES)
const int num_inferences = ET_NUM_INFERENCES;
#else
const int num_inferences = 1;
#endif
/**
* The temp_allocation_pool is used for allocating temporary data during kernel
* or delegate execution. This will be reset after each kernel or delegate call.
* Currently a MemoryAllocator is used but a PlatformMemoryAllocator is probably
* a better fit.
*
* The Corstone-300/Corstone-320 platforms have 2MB/4MB of SRAM respectively.
* For Shared_Sram, ET_ARM_BAREMETAL_SCRATCH_TEMP_ALLOCATOR_POOL_SIZE is
* 2MB and the linker script places the .bss.tensor_arena symbol in the SRAM.
* For Dedicated_Sram, the .bss.tensor_arena symbol is placed in the DDR in the
* linker script. Hence, we allocate 128MB in DDR and 384KB in the SRAM
* (.bss.ethosu_scratch is placed in the SRAM). The examples/arm/CMakeLists.txt
* contains the logic for the sizes of
* ET_ARM_BAREMETAL_SCRATCH_TEMP_ALLOCATOR_POOL_SIZE and
* ET_ARM_BAREMETAL_FAST_SCRATCH_TEMP_ALLOCATOR_POOL_SIZE
*/
const size_t temp_allocation_pool_size =
ET_ARM_BAREMETAL_SCRATCH_TEMP_ALLOCATOR_POOL_SIZE;
unsigned char __attribute__((
section(".bss.tensor_arena"),
aligned(16))) temp_allocation_pool[temp_allocation_pool_size];
#if defined(ET_ARM_BAREMETAL_FAST_SCRATCH_TEMP_ALLOCATOR_POOL_SIZE)
extern "C" {
size_t ethosu_fast_scratch_size =
ET_ARM_BAREMETAL_FAST_SCRATCH_TEMP_ALLOCATOR_POOL_SIZE;
unsigned char __attribute__((section(".bss.ethosu_scratch"), aligned(16)))
dedicated_sram[ET_ARM_BAREMETAL_FAST_SCRATCH_TEMP_ALLOCATOR_POOL_SIZE];
unsigned char* ethosu_fast_scratch = dedicated_sram;
}
#endif
#if defined(ET_ARM_BAREMETAL_PLANNED_FAST_MEMORY_SIZE)
const size_t planned_fast_memory_pool_size =
ET_ARM_BAREMETAL_PLANNED_FAST_MEMORY_SIZE;
unsigned char __attribute__((
section(".fast_memory"),
aligned(16))) planned_fast_memory_pool[planned_fast_memory_pool_size];
#endif
constexpr size_t FAST_MEMORY_REGION_INDEX = 2;
[[maybe_unused]] void et_pal_init(void) {
#if defined(__PMU_PRESENT) && (__PMU_PRESENT == 1U)
// Armv8.1-M Mainline cores (M55, M85) have the optional PMU extension.
// Pre-Armv8.1-M cores lack ARM_PMU_*; et_pal_current_ticks() returns 0.
ARM_PMU_Enable();
DCB->DEMCR |= DCB_DEMCR_TRCENA_Msk; // Trace enable
ARM_PMU_CYCCNT_Reset();
ARM_PMU_CNTR_Enable(PMU_CNTENSET_CCNTR_ENABLE_Msk);
#endif
}
/**
* Implementation of the et_pal_<funcs>()
*
* This functions are hardware adaption type of functions for things like
* time/logging/memory allocation that could call your RTOS or need to to
* be implemnted in some way.
*/
[[maybe_unused]] ET_NORETURN void et_pal_abort(void) {
#if !defined(SEMIHOSTING)
__builtin_trap();
#else
_exit(-1);
#endif
}
[[maybe_unused]] et_timestamp_t et_pal_current_ticks(void) {
#if defined(__PMU_PRESENT) && (__PMU_PRESENT == 1U)
return ARM_PMU_Get_CCNTR();
#else
return 0;
#endif
}
[[maybe_unused]] et_tick_ratio_t et_pal_ticks_to_ns_multiplier(void) {
// Since we don't know the CPU freq for your target and justs cycles in the
// FVP for et_pal_current_ticks() we return a conversion ratio of 1
return {1, 1};
}
/**
* Emit a log message via platform output (serial port, console, etc).
*/
[[maybe_unused]] void et_pal_emit_log_message(
ET_UNUSED et_timestamp_t timestamp,
et_pal_log_level_t level,
const char* filename,
ET_UNUSED const char* function,
size_t line,
const char* message,
ET_UNUSED size_t length) {
printf_size_t log_line = line;
fprintf(
stderr,
"%c [executorch:%s:%lu %s()] %s\n",
level,
filename,
log_line,
function,
message);
}
/**
* Dynamic memory allocators intended to be used by temp_allocator
* to implement malloc()/free() type of allocations.
* Currenyly not used.
*/
[[maybe_unused]] void* et_pal_allocate(ET_UNUSED size_t size) {
return nullptr;
}
// cppcheck-suppress constParameterPointer
[[maybe_unused]] void et_pal_free(ET_UNUSED void* ptr) {}
namespace {
/// Lightweight heapless container that constructs and stores a T in-place.
/// Useful when you want to avoid heap allocations but need to delay
/// construction.
template <typename T>
class Box {
public:
Box() = default;
~Box() {
if (has_value) {
ptr()->~T();
}
}
Box(const Box&) = delete;
Box& operator=(const Box&) = delete;
/// Destructs the already contained object if it's present and initialize a
/// new contained object while forwarding its constructor arguments.
template <typename... Args>
void reset(Args&&... args) {
if (has_value) {
// Destroy the already contained object.
reinterpret_cast<T*>(mem)->~T();
}
// Init the new object.
new (mem) T(std::forward<Args>(args)...);
has_value = true;
}
/// Returns a reference to the contained object.
T& value() {
return *ptr();
}
/// Returns a const reference to the contained object.
const T& value() const {
return *ptr();
}
T* operator->() {
return ptr();
}
const T* operator->() const {
return ptr();
}
private:
alignas(T) uint8_t mem[sizeof(T)] = {};
bool has_value = false;
T* ptr() {
return reinterpret_cast<T*>(mem);
}
const T* ptr() const {
return reinterpret_cast<const T*>(mem);
}
};
template <typename ValueType>
[[maybe_unused]] void fill_tensor_with_default_value(Tensor& tensor) {
ValueType fill_value{};
if constexpr (std::is_same_v<ValueType, bool>) {
fill_value = true;
} else {
fill_value = ValueType(1);
}
ValueType* data_ptr = tensor.mutable_data_ptr<ValueType>();
std::fill(data_ptr, data_ptr + tensor.numel(), fill_value);
}
Error prepare_input_tensors(
Method& method,
MemoryAllocator& allocator,
const std::vector<std::pair<char*, size_t>>& input_buffers) {
MethodMeta method_meta = method.method_meta();
size_t num_inputs = method_meta.num_inputs();
#if defined(SEMIHOSTING)
ET_CHECK_OR_RETURN_ERROR(
input_buffers.size() > 0 && num_inputs == input_buffers.size(),
InvalidArgument,
"Wrong number of inputs allocated compared to method");
#endif
EValue* input_evalues = allocator.allocateList<EValue>(num_inputs);
ET_CHECK_OR_RETURN_ERROR(
input_evalues != nullptr,
MemoryAllocationFailed,
"Could not allocate memory for input evalues.");
Error err = method.get_inputs(input_evalues, num_inputs);
ET_CHECK_OK_OR_RETURN_ERROR(err);
for (size_t i = 0; i < num_inputs; i++) {
printf_size_t input_idx = i;
auto tag = method_meta.input_tag(i);
ET_CHECK_OK_OR_RETURN_ERROR(tag.error());
if (tag.get() != Tag::Tensor) {
ET_LOG(Debug, "Skipping non-tensor input %lu", input_idx);
continue;
}
Result<TensorInfo> tensor_meta = method_meta.input_tensor_meta(i);
ET_CHECK_OK_OR_RETURN_ERROR(tensor_meta.error());
err = Error::Ok;
if (input_buffers.size() > 0) {
auto [buffer, buffer_size] = input_buffers.at(i);
if (buffer_size != tensor_meta->nbytes()) {
printf_size_t input_buffer_size = buffer_size;
printf_size_t tensor_size = tensor_meta->nbytes();
ET_LOG(
Error,
"input size (%lu) and tensor size (%lu) mismatch!",
input_buffer_size,
tensor_size);
err = Error::InvalidArgument;
} else if (input_evalues[i].isTensor()) {
// set_input copies shape metadata into its method-owned input tensor.
// For unplanned inputs it aliases only buffer, which remains valid
// through execute(); this temporary TensorImpl is not retained.
TensorImpl impl = TensorImpl(
tensor_meta->scalar_type(),
static_cast<ssize_t>(tensor_meta->sizes().size()),
const_cast<TensorImpl::SizesType*>(tensor_meta->sizes().data()),
buffer,
const_cast<TensorImpl::DimOrderType*>(
tensor_meta->dim_order().data()));
Tensor tensor(&impl);
err = method.set_input(tensor, i);
ET_CHECK_OK_OR_RETURN_ERROR(err);
}
}
// If there are no input buffers, fill inputs with 1s.
if (input_buffers.empty()) {
if (input_evalues[i].isTensor()) {
Tensor& tensor = input_evalues[i].toTensor();
switch (tensor.scalar_type()) {
#define HANDLE_SCALAR_TYPE(cpp_type, scalar_name) \
case ScalarType::scalar_name: \
fill_tensor_with_default_value<cpp_type>(tensor); \
break;
ET_FORALL_SCALAR_TYPES(HANDLE_SCALAR_TYPE)
#undef HANDLE_SCALAR_TYPE
default:
ET_LOG(
Error,
"Unhandled ScalarType %s",
toString(tensor.scalar_type()));
err = Error::InvalidArgument;
break;
}
} else {
printf("Input[%lu]: Not Tensor\n", input_idx);
}
}
}
return err;
}
#if defined(SEMIHOSTING)
std::pair<char*, size_t> read_binary_file(
const char* filename,
MemoryAllocator& allocator) {
FILE* fp = fopen(filename, "rb");
if (!fp) {
ET_LOG(
Fatal,
"Could not open file %s (errno: %d) for reading, exiting!",
filename,
errno);
return std::make_pair(nullptr, 0);
}
fseek(fp, 0, SEEK_END);
auto file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* buffer = static_cast<char*>(allocator.allocate(file_size));
if (buffer == nullptr) {
printf_size_t input_file_size = file_size;
ET_LOG(Fatal, "Failed to allocate input file size:%lu", input_file_size);
fclose(fp);
return std::make_pair(nullptr, 0);
}
auto read_size = fread(buffer, 1, file_size, fp);
if (read_size != file_size) {
printf_size_t input_read_size = read_size;
ET_LOG(
Info,
"Failed to read whole file (%s), read %lu bytes!",
filename,
input_read_size);
}
fclose(fp);
return std::make_pair(buffer, read_size);
}
#endif
/// Holds all state needed for setup and run phases
struct RunnerContext {
RunnerContext() = default;
RunnerContext(const RunnerContext& ctx) = delete;
RunnerContext& operator=(const RunnerContext& ctx) = delete;
const char* method_name = nullptr;
size_t planned_buffer_memsize = 0;
size_t method_loaded_memsize = 0;
size_t executor_membase = 0;
size_t program_data_len = 0;
size_t input_memsize = 0;
size_t model_data_size = 0;
bool bundle_io = false;
Box<BufferDataLoader> loader;
Box<Program> program;
Box<ArmMemoryAllocator> method_allocator;
Box<ArmMemoryAllocator> planned_fast_allocator;
Box<ArmMemoryAllocator> temp_allocator;
std::vector<Span<uint8_t>> planned_spans;
Box<HierarchicalAllocator> planned_memory;
Box<MemoryManager> memory_manager;
Box<Result<Method>> method;
#if defined(ET_EVENT_TRACER_ENABLED)
Box<ETDumpGen> etdump_gen;
#if defined(ET_DUMP_INTERMEDIATE_OUTPUTS) || defined(ET_DUMP_OUTPUTS)
void* debug_buffer = nullptr;
#endif
#endif
#if defined(SEMIHOSTING)
Box<ArmMemoryAllocator> input_file_allocator;
const char* output_basename = nullptr;
bool server_mode = false;
std::vector<const char*> input_filenames;
#endif
};
#if defined(SEMIHOSTING)
Error read_input_files(
RunnerContext& ctx,
const std::vector<const char*>& input_filenames,
std::vector<std::pair<char*, size_t>>& input_buffers) {
input_buffers.clear();
for (size_t i = 0; i < input_filenames.size(); ++i) {
auto [buffer, buffer_size] =
read_binary_file(input_filenames[i], ctx.input_file_allocator.value());
if (buffer == nullptr) {
ET_LOG(
Error,
"Reading input tensor %zu from file %s failed.",
i + 1,
input_filenames[i]);
return Error::AccessFailed;
}
input_buffers.push_back(std::make_pair(buffer, buffer_size));
}
return Error::Ok;
}
#endif
void runner_init(
RunnerContext& ctx,
const uint8_t* model_data,
size_t model_size,
std::vector<std::pair<char*, size_t>> input_buffers) {
// Find the offset to the embedded Program.
const void* program_data = model_data;
ctx.program_data_len = model_size;
ctx.model_data_size = model_size;
#if defined(ET_BUNDLE_IO)
ctx.bundle_io = executorch::bundled_program::is_bundled_program(
const_cast<uint8_t*>(model_data), ctx.model_data_size);
if (ctx.bundle_io) {
// BundleIO bpte is provided, dig out the actual model from the data area
Error status = executorch::bundled_program::get_program_data(
const_cast<uint8_t*>(model_data),
ctx.model_data_size,
&program_data,
&ctx.program_data_len);
ET_CHECK_MSG(
status == Error::Ok,
"get_program_data() from bundle PTE failed: 0x%x",
(unsigned int)status);
}
#endif
ctx.loader.reset(program_data, ctx.program_data_len);
auto& loader = ctx.loader.value();
ET_LOG(
Info,
"PTE Model data loaded. Size: %lu bytes.",
static_cast<unsigned long>(ctx.program_data_len));
// Parse the program file. This is immutable, and can also be reused
// between multiple execution invocations across multiple threads.
Result<Program> program_result = Program::load(&loader);
ET_CHECK_MSG(
program_result.ok(),
"Program loading failed @ %p: 0x%" PRIx32,
program_data,
program_result.error());
ctx.program.reset(std::move(program_result.get()));
Program& program = ctx.program.value();
ET_LOG(
Info,
"Model buffer loaded, has %lu methods",
static_cast<unsigned long>(program.num_methods()));
{
const auto method_name_result = program.get_method_name(0);
ET_CHECK_MSG(method_name_result.ok(), "Program has no methods");
ctx.method_name = *method_name_result;
}
ET_LOG(Info, "Running method %s", ctx.method_name);
Result<MethodMeta> method_meta = program.method_meta(ctx.method_name);
if (!method_meta.ok()) {
ET_LOG(
Info,
"Failed to get method_meta for %s: 0x%x",
ctx.method_name,
(unsigned int)method_meta.error());
}
ET_LOG(
Info,
"Setup Method allocator pool. Size: %lu bytes.",
static_cast<unsigned long>(method_allocation_pool_size));
ctx.method_allocator.reset(
method_allocation_pool_size, method_allocation_pool);
#if defined(ET_ARM_BAREMETAL_PLANNED_FAST_MEMORY_SIZE)
ET_LOG(
Info,
"Setup planned FAST_MEMORY_REGION pool. Size: %lu bytes.",
static_cast<unsigned long>(planned_fast_memory_pool_size));
ctx.planned_fast_allocator.reset(
planned_fast_memory_pool_size, planned_fast_memory_pool);
#endif
ctx.planned_spans.clear();
size_t num_memory_planned_buffers = method_meta->num_memory_planned_buffers();
ctx.planned_spans.reserve(num_memory_planned_buffers);
size_t planned_buffer_membase = ctx.method_allocator->used_size();
for (size_t id = 0; id < num_memory_planned_buffers; ++id) {
size_t buffer_size =
static_cast<size_t>(method_meta->memory_planned_buffer_size(id).get());
ET_LOG(
Info,
"Setting up planned buffer with mem_id=%lu, size %lu.",
static_cast<unsigned long>(id + 1),
static_cast<unsigned long>(buffer_size));
if (buffer_size == 0) {
ctx.planned_spans.push_back(Span<uint8_t>(
static_cast<uint8_t*>(nullptr), static_cast<size_t>(0)));
continue;
}
uint8_t* buffer = nullptr;
const char* memory_region = nullptr;
switch (id) {
case FAST_MEMORY_REGION_INDEX:
memory_region = "FAST_MEMORY_REGION";
#if defined(ET_ARM_BAREMETAL_PLANNED_FAST_MEMORY_SIZE)
buffer = reinterpret_cast<uint8_t*>(
ctx.planned_fast_allocator->allocate(buffer_size, 16UL));
#else
ET_CHECK_MSG(
false,
"Planned buffer %lu uses mem_id=%lu/FAST_MEMORY_REGION, but "
"ET_ARM_BAREMETAL_PLANNED_FAST_MEMORY_SIZE is not set",
static_cast<unsigned long>(id),
static_cast<unsigned long>(id + 1));
#endif
break;
default:
memory_region = "SLOW_MEMORY_REGION";
/* Ethos-U driver requires 16 bit alignment. */
buffer = reinterpret_cast<uint8_t*>(
ctx.method_allocator->allocate(buffer_size, 16UL));
break;
}
ET_CHECK_MSG(
buffer != nullptr,
"Could not allocate memory for planned buffer with mem_id=%lu, size "
"%lu in %s",
static_cast<unsigned long>(id + 1),
static_cast<unsigned long>(buffer_size),
memory_region);
ctx.planned_spans.push_back({buffer, buffer_size});
}
ctx.planned_buffer_memsize =
ctx.method_allocator->used_size() - planned_buffer_membase;
Span<Span<uint8_t>> planned_memory_span;
if (!ctx.planned_spans.empty()) {
planned_memory_span =
Span<Span<uint8_t>>(ctx.planned_spans.data(), ctx.planned_spans.size());
}
ctx.planned_memory.reset(planned_memory_span);
ctx.temp_allocator.reset(temp_allocation_pool_size, temp_allocation_pool);
ctx.memory_manager.reset(
&ctx.method_allocator.value(),
&ctx.planned_memory.value(),
&ctx.temp_allocator.value());
size_t method_loaded_membase = ctx.method_allocator->used_size();
executorch::runtime::EventTracer* event_tracer_ptr = nullptr;
#if defined(ET_EVENT_TRACER_ENABLED)
ET_LOG(Info, "Setting up ETDump");
ctx.etdump_gen.reset();
event_tracer_ptr = &ctx.etdump_gen.value();
#if defined(ET_DUMP_INTERMEDIATE_OUTPUTS) || defined(ET_DUMP_OUTPUTS)
// Alloc debug buffer and create if and only if we need to log intermediate
// tensor outputs
ctx.debug_buffer = ctx.method_allocator->allocate(ET_DEBUG_BUFFER_SIZE, 16);
if (ctx.debug_buffer != nullptr) {
Span<uint8_t> debug_buffer_span(
reinterpret_cast<uint8_t*>(ctx.debug_buffer), ET_DEBUG_BUFFER_SIZE);
Result<bool> result =
ctx.etdump_gen.value().set_debug_buffer(debug_buffer_span);
if (result.ok()) {
// Everything worked, we got the buffer setup, lets enable output logging
// depending on the compile flag ET_DUMP_INTERMEDIATE_OUTPUTS e.g.
// kIntermediateOutputs or kProgramOutputs
#if defined(ET_DUMP_INTERMEDIATE_OUTPUTS)
ET_LOG(
Info,
"ETDump: Allocated intermediate output buffer size: %d at 0x%p",
ET_DEBUG_BUFFER_SIZE,
ctx.debug_buffer);
ctx.etdump_gen.value().set_event_tracer_debug_level(
EventTracerDebugLogLevel::kIntermediateOutputs);
#else // defined(ET_DUMP_INTERMEDIATE_OUTPUTS)
ET_LOG(
Info,
"ETDump: Allocated output buffer size: %d at 0x%p",
ET_DEBUG_BUFFER_SIZE,
ctx.debug_buffer);
ctx.etdump_gen.value().set_event_tracer_debug_level(
EventTracerDebugLogLevel::kProgramOutputs);
#endif // defined(ET_DUMP_INTERMEDIATE_OUTPUTS)
} else {
// set_debug_buffer() failed
// Here we would free ctx.debug_buffer if it was possible, but we can't as
// the allocator don't support it.
ctx.debug_buffer = nullptr;
ET_LOG(
Error,
"ETDump: Could not set_debug_buffer() for output buffer size %lu error:0x%" PRIx32,
static_cast<unsigned long>(ET_DEBUG_BUFFER_SIZE),
result.error());
}
} else {
// debug buffer allocation failed
ET_LOG(
Error,
"ETDump: Could not allocate memory for output buffer size %lu",
static_cast<unsigned long>(ET_DEBUG_BUFFER_SIZE));
}
#endif // defined(ET_DUMP_INTERMEDIATE_OUTPUTS) || defined(ET_DUMP_OUTPUTS)
#endif // defined(ET_EVENT_TRACER_ENABLED)
ctx.method.reset(program.load_method(
ctx.method_name, &ctx.memory_manager.value(), event_tracer_ptr));
if (!ctx.method->ok()) {
ET_LOG(
Info,
"Loading of method %s failed with status 0x%" PRIx32,
ctx.method_name,
ctx.method->error());
}
ctx.method_loaded_memsize =
ctx.method_allocator->used_size() - method_loaded_membase;
ET_LOG(Info, "Method '%s' loaded.", ctx.method_name);
ET_LOG(Info, "Preparing inputs...");
size_t input_membase = ctx.method_allocator->used_size();
#if defined(ET_BUNDLE_IO)
if (ctx.bundle_io) {
// Get inputs from bundled IO ".bpte" data
// Useful for testing
ET_LOG(Info, "Input testset[%d] from bundled bpte", testset_idx);
Error status = executorch::bundled_program::load_bundled_input(
*ctx.method.value(), model_data, testset_idx);
ET_CHECK_MSG(
status == Error::Ok,
"load_bundled_input failed with status 0x%" PRIx32,
status);
} else
#endif
{
Error status = ::prepare_input_tensors(
*ctx.method.value(), ctx.method_allocator.value(), input_buffers);
ET_CHECK_MSG(
status == Error::Ok, "Failed to prepare inputs 0x%" PRIx32, status);
}
#if defined(ET_LOG_DUMP_INPUT)
{
std::vector<EValue> inputs((*ctx.method.value())->inputs_size());
ET_LOG(Info, "%lu inputs: ", static_cast<unsigned long>(inputs.size()));
Error status = ctx.method.value()->get_inputs(inputs.data(), inputs.size());
ET_CHECK(status == Error::Ok);
for (int i = 0; i < inputs.size(); ++i) {
if (inputs[i].isTensor()) {
Tensor tensor = inputs[i].toTensor();
// The output might be collected and parsed so printf() is used instead
// of ET_LOG() here
for (int j = 0; j < tensor.numel(); ++j) {
if (tensor.scalar_type() == ScalarType::Int) {
printf(
"Input[%d][%d]: (int) %d\n",
i,
j,
tensor.const_data_ptr<int>()[j]);
} else if (tensor.scalar_type() == ScalarType::Float) {
printf(
"Input[%d][%d]: (float) %f\n",
i,
j,
tensor.const_data_ptr<float>()[j]);
} else if (tensor.scalar_type() == ScalarType::Char) {
printf(
"Input[%d][%d]: (char) %d\n",
i,
j,
tensor.const_data_ptr<int8_t>()[j]);
} else if (tensor.scalar_type() == ScalarType::Bool) {
printf(
"Input[%d][%d]: (bool) %s (0x%x)\n",
i,
j,
tensor.const_data_ptr<int8_t>()[j] ? "true" : "false",
tensor.const_data_ptr<int8_t>()[j]);
}
}
} else {
printf("Input[%d]: Not Tensor\n", i);
}
}
}
#endif
ctx.input_memsize = ctx.method_allocator->used_size() - input_membase;
ctx.executor_membase = ctx.method_allocator->used_size();
ET_LOG(Info, "Input prepared.");
}
void log_mem_status(RunnerContext& ctx) {
size_t executor_memsize =
ctx.method_allocator->used_size() - ctx.executor_membase;
#if defined(ET_MODEL_PTE_ADDR)
ET_LOG(
Info,
"model_pte_program_size: %lu bytes.",
static_cast<unsigned long>(ctx.program_data_len));
ET_LOG(
Info,
"model_pte_loaded_size: %lu bytes.",
static_cast<unsigned long>(ctx.model_data_size));
#else
ET_LOG(
Info,
"model_pte_program_size: %lu bytes.",
static_cast<unsigned long>(ctx.program_data_len));
ET_LOG(
Info,
"model_pte_loaded_size: %lu bytes.",
static_cast<unsigned long>(ctx.model_data_size));
#endif
#if defined(SEMIHOSTING)
if (ctx.input_file_allocator->size() > 0) {
ET_LOG(
Info,
"input_file_allocator_used: %lu / %lu free: %lu ( used: %lu %% ) ",
static_cast<unsigned long>(ctx.input_file_allocator->used_size()),
static_cast<unsigned long>(ctx.input_file_allocator->size()),
static_cast<unsigned long>(ctx.input_file_allocator->free_size()),
static_cast<unsigned long>(
100 * ctx.input_file_allocator->used_size() /
ctx.input_file_allocator->size()));
}
#endif
if (ctx.method_allocator->size() != 0) {
size_t method_allocator_used = ctx.method_allocator->used_size();
ET_LOG(
Info,
"method_allocator_used: %lu / %lu free: %lu ( used: %lu %% ) ",