-
Notifications
You must be signed in to change notification settings - Fork 239
Expand file tree
/
Copy pathcompiled_model.cc
More file actions
1944 lines (1762 loc) · 75.2 KB
/
compiled_model.cc
File metadata and controls
1944 lines (1762 loc) · 75.2 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 2024 Google LLC.
//
// Licensed 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.
#include "litert/runtime/compiled_model.h"
#include <algorithm>
#include <array>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <functional>
#include <iterator>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#if !defined(LITERT_WINDOWS_OS)
#include <unistd.h>
#endif // !defined(LITERT_WINDOWS_OS)
#include "absl/functional/any_invocable.h" // from @com_google_absl
#include "absl/status/status.h" // from @com_google_absl
#include "litert/c/litert_layout.h"
#include "litert/cc/internal/litert_consts.h"
#if defined(__ANDROID__)
#include <android/hardware_buffer.h>
#endif
#include "absl/cleanup/cleanup.h" // from @com_google_absl
#include "absl/log/absl_check.h" // from @com_google_absl
#include "absl/strings/match.h" // from @com_google_absl
#include "absl/strings/str_cat.h" // from @com_google_absl
#include "absl/strings/str_format.h" // from @com_google_absl
#include "absl/strings/string_view.h" // from @com_google_absl
#include "absl/types/span.h" // from @com_google_absl
#include "litert/c/internal/litert_accelerator.h"
#include "litert/c/internal/litert_delegate_wrapper.h"
#include "litert/c/internal/litert_logging.h"
#include "litert/c/internal/litert_runtime_context.h"
#include "litert/c/internal/litert_scheduling_info.h"
#include "litert/c/litert_any.h"
#include "litert/c/litert_common.h"
#include "litert/c/litert_environment_options.h"
#include "litert/c/litert_opaque_options.h"
#include "litert/c/litert_options.h"
#include "litert/c/litert_profiler_event.h"
#include "litert/c/litert_tensor_buffer.h"
#include "litert/c/litert_tensor_buffer_requirements.h"
#include "litert/c/litert_tensor_buffer_types.h"
#include "litert/cc/internal/litert_handle.h"
#include "litert/cc/internal/litert_tensor_buffer_utils.h"
#include "litert/cc/litert_buffer_ref.h"
#include "litert/cc/litert_expected.h"
#include "litert/cc/litert_macros.h"
#include "litert/cc/litert_opaque_options.h"
#include "litert/core/buffer_error_reporter.h"
#include "litert/core/build_stamp.h"
#include "litert/core/error_reporter.h"
#include "litert/core/model/model.h"
#include "tflite/model_builder.h"
#if !defined(LITERT_DISABLE_NPU)
#include "litert/compiler/plugin/compiler_plugin.h"
#include "litert/core/cache/compilation_cache.h"
#include "litert/core/model/model_serialize.h"
#endif // !defined(LITERT_DISABLE_NPU)
#include "litert/core/options.h"
#include "litert/core/util/flatbuffer_tools.h"
#include "litert/runtime/accelerator.h"
#include "litert/runtime/custom_op_dispatcher.h"
#include "litert/runtime/dispatch/dispatch_opaque_options.h"
#include "litert/runtime/external_litert_buffer_context.h"
#if !defined(LITERT_DISABLE_CPU)
#include "litert/runtime/litert_cpu_options.h"
#endif // !defined(LITERT_DISABLE_CPU)
#include "litert/runtime/litert_runtime_options.h"
#include "litert/runtime/magic_number_utils.h"
#include "litert/runtime/metrics.h"
#include "litert/runtime/tensor_buffer.h"
#include "litert/runtime/tensor_buffer_requirements.h"
#include "litert/runtime/tensor_identifier.h"
#include "litert/runtime/tfl_utils.h"
#include "weight_loader/external_weight_loader_litert.h"
#include "tflite/converter/allocation.h"
#include "tflite/builtin_ops.h"
#include "tflite/core/api/profiler.h"
#include "tflite/core/interpreter_builder.h"
#include "tflite/interpreter.h"
#include "tflite/interpreter_options.h"
#if !defined(LITERT_NO_BUILTIN_OPS)
#include "tflite/kernels/register.h"
#endif // LITERT_NO_BUILTIN_OPS
#if defined(LITERT_NO_BUILTIN_OPS)
#include "litert/runtime/stub_op_resolver.h"
#endif // LITERT_NO_BUILTIN_OPS
using litert::Error;
using litert::Expected;
using litert::Unexpected;
using litert::internal::DispatchDelegateOptions;
using litert::internal::GetTensorIdentifier;
#if !defined(LITERT_DISABLE_NPU)
using litert::internal::SerializeModel;
#endif // !defined(LITERT_DISABLE_NPU)
using litert::internal::ParseLiteRtRuntimeOptions;
using litert::internal::TfLiteTensorIdentifier;
namespace {
std::optional<std::string> ExtractDirectory(absl::string_view path) {
const size_t last_sep = path.find_last_of("/\\");
if (last_sep == absl::string_view::npos) {
return std::nullopt;
}
return std::string(path.substr(0, last_sep));
}
void* StubOpInit([[maybe_unused]] TfLiteContext* context,
[[maybe_unused]] const char* buffer,
[[maybe_unused]] size_t length) {
return nullptr;
}
void StubOpFree([[maybe_unused]] TfLiteContext* context,
[[maybe_unused]] void* buffer) {}
TfLiteStatus StubOpPrepare([[maybe_unused]] TfLiteContext* context,
[[maybe_unused]] TfLiteNode* node) {
return kTfLiteOk;
}
TfLiteStatus StubOpEval(TfLiteContext* context,
[[maybe_unused]] TfLiteNode* node) {
// This should never be called as accelerators will handle the operations
context->ReportError(
context, "Stub operation invoked. This function should not be called.");
return kTfLiteError;
}
TfLiteRegistration sStubRegistration = {
.init = StubOpInit,
.free = StubOpFree,
.prepare = StubOpPrepare,
.invoke = StubOpEval,
};
#if !defined(LITERT_DISABLE_NPU)
LiteRtLogSeverity GetLogSeverityForJitCompilationFailure(
LiteRtHwAcceleratorSet hw_accelerators) {
return (hw_accelerators & kLiteRtHwAcceleratorNpu) ? LITERT_WARNING
: LITERT_VERBOSE;
}
#endif // !defined(LITERT_DISABLE_NPU)
constexpr uint32_t kAllSchedulingInfoFields =
kLiteRtSchedulingInfoFieldOriginalUid |
kLiteRtSchedulingInfoFieldDebugFeatureId |
kLiteRtSchedulingInfoFieldJobPriority | kLiteRtSchedulingInfoFieldGroupId;
bool IsValidSchedulingPriority(int32_t priority) {
return priority >= kLiteRtSchedulingInfoJobPriorityHighest &&
priority <= kLiteRtSchedulingInfoJobPriorityLowest;
}
int32_t GetDefaultOriginalUid() {
#if !defined(LITERT_WINDOWS_OS)
return static_cast<int32_t>(getuid());
#else
return -1;
#endif // !defined(LITERT_WINDOWS_OS)
}
LiteRtSchedulingInfo GetDefaultSchedulingInfo() {
LiteRtSchedulingInfo info{};
info.fields_mask = kAllSchedulingInfoFields;
info.original_uid = GetDefaultOriginalUid();
info.debug_feature_id = "";
info.job_priority = kLiteRtSchedulingInfoJobPriorityHighest;
memset(info.group_id, 0, sizeof(info.group_id));
return info;
}
Expected<void> ValidateSchedulingInfo(
const LiteRtSchedulingInfo& scheduling_info) {
if ((scheduling_info.fields_mask &
kLiteRtSchedulingInfoFieldDebugFeatureId) &&
scheduling_info.debug_feature_id == nullptr) {
return Unexpected(kLiteRtStatusErrorInvalidArgument,
"Scheduling info debug_feature_id cannot be null when "
"kLiteRtSchedulingInfoFieldDebugFeatureId is set");
}
if ((scheduling_info.fields_mask & kLiteRtSchedulingInfoFieldJobPriority) &&
!IsValidSchedulingPriority(scheduling_info.job_priority)) {
return Unexpected(
kLiteRtStatusErrorInvalidArgument,
absl::StrFormat(
"Scheduling info job_priority=%d is out of range [%d, %d]",
scheduling_info.job_priority,
kLiteRtSchedulingInfoJobPriorityHighest,
kLiteRtSchedulingInfoJobPriorityLowest));
}
return {};
}
void ApplySchedulingInfoOverrides(const LiteRtSchedulingInfo& overrides,
LiteRtSchedulingInfo& target) {
if (overrides.fields_mask & kLiteRtSchedulingInfoFieldOriginalUid) {
target.original_uid = overrides.original_uid;
}
if (overrides.fields_mask & kLiteRtSchedulingInfoFieldDebugFeatureId) {
target.debug_feature_id =
overrides.debug_feature_id != nullptr ? overrides.debug_feature_id : "";
}
if (overrides.fields_mask & kLiteRtSchedulingInfoFieldJobPriority) {
target.job_priority = overrides.job_priority;
}
if (overrides.fields_mask & kLiteRtSchedulingInfoFieldGroupId) {
memcpy(target.group_id, overrides.group_id, sizeof(target.group_id));
}
}
} // namespace
Expected<void> LiteRtCompiledModelT::InitializeRuntime(
LiteRtEnvironmentT* env, LiteRtHwAcceleratorSet hardware_accelerators,
LiteRtOptions jit_compilation_options) {
#ifdef LITERT_NO_BUILTIN_OPS
// Use StubOpResolver which provides minimal stub implementations for all
// builtin ops. These stubs allow the model to pass validation, but the
// actual operations will be handled by LiteRT's accelerator system
// (NPU > GPU > CPU) through their respective delegates.
litert::internal::StubOpResolver resolver;
#else
tflite::ops::builtin::BuiltinOpResolverWithoutDefaultDelegates resolver;
#endif // LITERT_NO_BUILTIN_OPS
// Apply custom ops.
if (jit_compilation_options) {
for (auto& option : jit_compilation_options->custom_op_options) {
custom_op_dispatchers_.push_back(
std::make_unique<litert::internal::CustomOpDispatcher>(option));
auto* tflite_registration =
custom_op_dispatchers_.back()->GetTfLiteRegistration();
resolver.AddCustom(option.op_name.c_str(), tflite_registration);
}
}
// Add custom ops that are supported by the CPU / GPU accelerators.
if (hardware_accelerators & kLiteRtHwAcceleratorGpu) {
const char* accelerator_supported_custom_ops[] = {
"Convolution2DTransposeBias", "MaxPoolingWithArgmax2D",
"MaxUnpooling2D", "Resampler", "custom_call.GroupNorm",
"custom_call.LayerNorm", "custom_call.RmsNorm",
"custom_call.PixelShuffle"};
for (const auto& op_name : accelerator_supported_custom_ops) {
resolver.AddCustom(op_name, &sStubRegistration);
}
} else if (hardware_accelerators & kLiteRtHwAcceleratorCpu) {
const char* accelerator_supported_custom_ops[] = {
"Convolution2DTransposeBias", "MaxPoolingWithArgmax2D",
"MaxUnpooling2D"};
for (const auto& op_name : accelerator_supported_custom_ops) {
resolver.AddCustom(op_name, &sStubRegistration);
}
}
#ifdef __EMSCRIPTEN__
else if (hardware_accelerators & kLiteRtHwAcceleratorWebNn) {
const char* accelerator_supported_custom_ops[] = {
"Convolution2DTransposeBias"};
for (const auto& op_name : accelerator_supported_custom_ops) {
resolver.AddCustom(op_name, &sStubRegistration);
}
}
#endif // __EMSCRIPTEN__
tflite::InterpreterOptions interpreter_options;
interpreter_options.SetUseSignatureTensorNames(true);
int num_threads = 1;
if (jit_compilation_options) {
auto opaque_options = litert::OpaqueOptions::WrapCObject(
jit_compilation_options->options, litert::OwnHandle::kNo);
if (auto runtime_options_data = litert::FindOpaqueData<const char>(
opaque_options, LiteRtRuntimeOptionsT::Identifier());
runtime_options_data) {
LiteRtRuntimeOptionsT runtime_options;
absl::string_view data_str(*runtime_options_data);
if (ParseLiteRtRuntimeOptions(data_str.data(), data_str.size(),
&runtime_options) != kLiteRtStatusOk) {
LITERT_LOG(LITERT_WARNING, "Failed to parse runtime options");
} else {
interpreter_options.SetShloCompositeInlining(true);
interpreter_options.SetCompressQuantizationZeroPoints(
runtime_options.compress_quantization_zero_points);
if (runtime_options.enable_profiling) {
profiler_ =
new LiteRtProfilerT(/*max_profiling_buffer_entries=*/2048);
}
// Create error reporter based on mode
switch (runtime_options.error_reporter_mode) {
case kLiteRtErrorReporterModeNone:
// No error reporter
break;
case kLiteRtErrorReporterModeStderr:
error_reporter_ = std::make_unique<litert::StderrReporter>();
break;
case kLiteRtErrorReporterModeBuffer:
error_reporter_ = std::make_unique<litert::BufferErrorReporter>();
break;
}
}
}
#if !defined(LITERT_DISABLE_CPU)
if (auto cpu_options_data = litert::FindOpaqueData<const char>(
opaque_options, LiteRtCpuOptionsT::Identifier());
cpu_options_data) {
LiteRtCpuOptionsT cpu_options;
absl::string_view data_str(*cpu_options_data);
if (litert::internal::ParseLiteRtCpuOptions(
data_str.data(), data_str.size(), &cpu_options) !=
kLiteRtStatusOk) {
LITERT_LOG(LITERT_WARNING, "Failed to parse CPU options");
} else {
num_threads = cpu_options.xnn.num_threads;
}
}
#endif // !defined(LITERT_DISABLE_CPU)
}
tflite::InterpreterBuilder builder(
fb_model_->GetModel(), resolver, error_reporter_.get(),
&interpreter_options, fb_model_->allocation());
builder(&interp_);
if (interp_ == nullptr) {
return Unexpected(kLiteRtStatusErrorRuntimeFailure,
"Failed to build TFL interpreter");
}
interp_->SetNumThreads(num_threads);
if (jit_compilation_options) {
const auto& bindings = jit_compilation_options->external_tensor_bindings;
for (const auto& binding : bindings) {
if (litert::internal::SetCustomAllocationForInputTensor(
interp_.get(), binding) != kTfLiteOk) {
ReportError("Failed to set custom allocation for tensor: %s",
binding.tensor_name.c_str());
return Unexpected(
kLiteRtStatusErrorInvalidArgument,
absl::StrFormat("Failed to apply external tensor binding for "
"signature %s, tensor %s.",
binding.signature_name, binding.tensor_name));
}
}
}
if (profiler_ != nullptr) {
interp_->SetProfiler(profiler_);
}
signature_keys_ = interp_->signature_keys();
if (signature_keys_.empty()) {
static auto* default_signature_key =
new std::string(litert::kDefaultSignatureKey);
signature_keys_.push_back(default_signature_key);
}
signature_needs_allocation_.clear();
auto get_tensor_id =
[tflite_interpreter = std::ref(*interp_)](
const TfLiteOpaqueTensor* target_tensor) -> TfLiteTensorIdentifier {
auto tensor_id = GetTensorIdentifier(
tflite_interpreter,
reinterpret_cast<const TfLiteTensor*>(target_tensor));
if (!tensor_id) {
LITERT_LOG(LITERT_ERROR, "Failed to get tensor identifier: %s",
tensor_id.Error().Message().c_str());
constexpr TfLiteTensorIdentifier kInvalidTensorId{-1, -1};
return kInvalidTensorId;
}
return *tensor_id;
};
// Register the ExternalLiteRtBufferContext for TensorBuffer handshaking.
buffer_context_ =
std::make_unique<LiteRtExternalLiteRtBufferContextT>(env, get_tensor_id);
interp_->SetExternalContext(kTfLiteLiteRtBufferContext,
buffer_context_.get());
std::unique_ptr<litert::ScopedWeightSource> scoped_weight_source;
auto* options_impl =
reinterpret_cast<LiteRtOptionsT*>(jit_compilation_options);
if (options_impl != nullptr) {
options_impl->weight_loader = nullptr;
scoped_weight_source = std::move(options_impl->scoped_weight_source);
}
weight_loader_ = weight_loader::CreateLiteRtWeightLoader(
fb_model_->GetModel(), model_directory_, std::move(scoped_weight_source));
has_external_weights_ = false;
if (weight_loader_) {
auto weight_infos = weight_loader_->GetWeightInfo();
has_external_weights_ = !weight_infos.empty();
if (!has_external_weights_) {
LITERT_LOG(LITERT_DEBUG,
"External weight loader: no external weight tensors found");
return {};
}
weight_loader::WeightAccessRequest request;
request.cpu = true;
// TODO(b/456318365): Handle weight access request to support multiple
// backends.
request.opencl = false;
absl::Status prepare_status = weight_loader_->PrepareAccess(request, env);
if (!prepare_status.ok()) {
return litert::Unexpected(kLiteRtStatusErrorRuntimeFailure,
std::string(prepare_status.message()));
}
if (options_impl != nullptr) {
options_impl->weight_loader = weight_loader_.get();
}
// Inspect the weight infos to log the available weights for GPU delegates.
LITERT_LOG(LITERT_DEBUG,
"External weight loader: %zu weight tensors available for GPU "
"delegates",
weight_infos.size());
for (const auto& info : weight_infos) {
if (info.packing.empty()) {
LITERT_LOG(LITERT_DEBUG,
" Weight tensor: external_buffer_id=%u, packing=<none>",
info.external_buffer_id);
} else {
LITERT_LOG(LITERT_DEBUG,
" Weight tensor: external_buffer_id=%u, packing=%.*s",
info.external_buffer_id,
static_cast<int>(info.packing.size()), info.packing.data());
}
}
}
return {};
}
Expected<void> LiteRtCompiledModelT::RestoreExternalWeightsForCpu() {
if (!weight_loader_ || !has_external_weights_) {
return {};
}
// Iterate through all subgraphs and restore external weights to tensors.
for (int subgraph_idx = 0; subgraph_idx < interp_->subgraphs_size();
++subgraph_idx) {
auto* subgraph = interp_->subgraph(subgraph_idx);
const auto& external_buffer_ids =
subgraph->GetExternalTensorBufferIdentifiers();
for (const auto& [tensor_index, external_buffer_id] : external_buffer_ids) {
const weight_loader::WeightAccess* weight_access =
weight_loader_->GetExternalWeightByBuffer(external_buffer_id);
if (!weight_access) {
return litert::Unexpected(
kLiteRtStatusErrorRuntimeFailure,
absl::StrFormat(
"Failed to get external weight for buffer id %u (tensor %zu)",
external_buffer_id, tensor_index));
}
LiteRtTensorBuffer host_buffer = weight_access->GetHostBuffer();
if (!host_buffer) {
return litert::Unexpected(
kLiteRtStatusErrorRuntimeFailure,
absl::StrFormat(
"Host tensor buffer is null for buffer id %u (tensor %zu)",
external_buffer_id, tensor_index));
}
void* host_memory_addr = nullptr;
if (LiteRtGetTensorBufferHostMemory(host_buffer, &host_memory_addr) !=
kLiteRtStatusOk) {
return litert::Unexpected(
kLiteRtStatusErrorRuntimeFailure,
absl::StrFormat(
"Failed to get host memory for buffer id %u (tensor %zu)",
external_buffer_id, tensor_index));
}
TfLiteTensor* tensor = subgraph->tensor(tensor_index);
if (!tensor) {
return litert::Unexpected(
kLiteRtStatusErrorRuntimeFailure,
absl::StrFormat("Tensor %zu not found in subgraph %d", tensor_index,
subgraph_idx));
}
// Set the tensor data to point to the external weight buffer.
// We use kTfLiteCustom allocation type so TFLite doesn't try to manage
// this memory. The memory is owned by weight_loader_ and stays valid
// until weight_loader_ is destroyed.
tensor->data.raw = static_cast<char*>(host_memory_addr);
tensor->allocation_type = kTfLiteCustom;
LITERT_LOG(LITERT_DEBUG,
"Restored external weight: subgraph=%d, tensor=%zu, "
"external_buffer_id=%u, addr=%p",
subgraph_idx, tensor_index, external_buffer_id,
host_memory_addr);
}
}
return {};
}
namespace {
int GetAllocationFd(const tflite::Allocation* allocation) {
if (allocation != nullptr &&
allocation->type() == tflite::Allocation::Type::kMMap) {
auto& mmap_allocation =
static_cast<const tflite::MMAPAllocation&>(*allocation);
return mmap_allocation.fd();
}
return -1;
}
#if !defined(LITERT_DISABLE_NPU)
Expected<std::vector<litert::internal::CompilerPlugin>> TryGetCompilerPlugins(
LiteRtOptionsT& options, LiteRtEnvironmentT& env,
LiteRtHwAcceleratorSet hw_accelerators) {
auto option = env.GetOption(kLiteRtEnvOptionTagCompilerPluginLibraryDir);
if (!option.has_value() || option->type != kLiteRtAnyTypeString) {
return Error(kLiteRtStatusErrorRuntimeFailure,
"Compiler plugin is not configured");
}
std::string compiler_plugin_lib_path = option->str_value;
const std::array<const absl::string_view, 1>
compiler_plugin_lib_search_paths = {compiler_plugin_lib_path};
Expected<std::vector<litert::internal::CompilerPlugin>>
compiler_plugins_expected = litert::internal::CompilerPlugin::LoadPlugins(
compiler_plugin_lib_search_paths, &env.GetOptions(), &options);
if (!compiler_plugins_expected) {
LITERT_LOG(GetLogSeverityForJitCompilationFailure(hw_accelerators),
"Failed to load compiler plugins: %s",
compiler_plugins_expected.Error().Message().c_str());
}
return compiler_plugins_expected;
}
std::optional<litert::internal::CompilationCache> MaybeCreateCompilationCache(
LiteRtEnvironmentT& env) {
std::optional<LiteRtAny> compiler_cache_dir_option =
env.GetOption(kLiteRtEnvOptionTagCompilerCacheDir);
if (compiler_cache_dir_option.has_value() &&
compiler_cache_dir_option->type == kLiteRtAnyTypeString) {
LITERT_LOG(LITERT_INFO,
"NPU JIT compilation caching enabled with cache dir: %s",
compiler_cache_dir_option->str_value);
auto compilation_cache_expected =
litert::internal::CompilationCache::Create(
compiler_cache_dir_option->str_value);
if (compilation_cache_expected.HasValue()) {
return compilation_cache_expected.Value();
}
}
return std::nullopt;
}
void TryApplyPluginsImpl(
LiteRtModel model, LiteRtHwAcceleratorSet selected_hw_accelerators,
std::vector<litert::internal::CompilerPlugin>& compiler_plugins,
bool* mutated) {
LITERT_LOG(LITERT_INFO, "Applying compiler plugins...");
// TODO: b/409819691 - Pass user provided `LiteRtOptions` down to the
// vendor code (nullptr are safe for now).
auto jit_result = litert::internal::ApplyPlugins(
model, selected_hw_accelerators, compiler_plugins, mutated);
if (!jit_result) {
LITERT_LOG(GetLogSeverityForJitCompilationFailure(selected_hw_accelerators),
"Failed to apply compiler plugins: %s",
jit_result.Error().Message().c_str());
} else {
LITERT_LOG(LITERT_INFO, "%d compiler plugins were applied successfully: %s",
jit_result->num_applied_plugins,
jit_result->success_message.c_str());
LITERT_LOG(LITERT_WARNING, "Plugin errs: %s",
jit_result->error_message.c_str());
}
}
#endif // !defined(LITERT_DISABLE_NPU)
} // namespace
Expected<void> LiteRtCompiledModelT::InitializeModel(
LiteRtModelT& model, LiteRtHwAcceleratorSet hw_accelerators,
LiteRtOptions options, LiteRtEnvironmentT& env) {
LITERT_RETURN_IF_ERROR(
litert::internal::ReplaceMagicNumbersIfAny(env, model));
if (auto source_path = model.SourcePath()) {
model_directory_ = ExtractDirectory(*source_path);
} else {
model_directory_.reset();
}
// If hardware acceleration is requested then apply the plugins to the model
// and initialize the compiled model from the translated LiteRt model.
if (hw_accelerators != kLiteRtHwAcceleratorNone) {
#if !defined(LITERT_DISABLE_NPU)
// Check if the model is pre-compiled by looking for LiteRt build stamp.
// Fall through to the next step if it's pre-compiled, else try to apply
// plugins to the model.
if (!IsCompiled(model)) {
Expected<bool> maybe_initialized_model =
ApplyPluginsWithCaching(model, hw_accelerators, *options, env);
if (maybe_initialized_model.HasValue() &&
maybe_initialized_model.Value() == true) {
// The compiled model's flatbuffer has initialized by applying the
// plugins.
return {};
}
// Deliberate fall through, failing to apply plugins is a recoverable
// error, we will try to initialize the compiled model from the incoming
// litert model.
} else {
if (env.GetOption(kLiteRtEnvOptionTagCompilerPluginLibraryDir)
.has_value()) {
LITERT_LOG(LITERT_WARNING,
"Compiler plugin path is provided in the environment, but "
"the model is "
"pre-compiled. Plugins won't be applied.");
}
}
#endif
}
const auto& tfl_wrapper = litert::internal::GetTflFlatbuffer(model);
// Currently, in all situations where litert model was import from a
// flatbuffer, the litert model will own said flatbuffer and stored it in the
// OwningBufferRef.
if (auto tfl_buf = tfl_wrapper.Buf(); tfl_buf.Data() != nullptr) {
LITERT_LOG(
LITERT_INFO,
"Flatbuffer model initialized directly from incoming litert model.");
fb_model_ = tflite::FlatBufferModel::BuildFromBuffer(
tfl_buf.StrData(), tfl_buf.Size(), error_reporter_.get());
fb_model_fd_ = GetAllocationFd(tfl_wrapper.FlatbufferModel().allocation());
return {};
}
// If we reach here, it means we weren't able to initialize the compiled
// model, neither from the incoming litert model nor from a transformed model
// after applying the plugins.
return Unexpected(kLiteRtStatusErrorInvalidArgument,
"Failed to build flatbuffer from incoming litert model");
}
namespace {
// A utility class that allows appending additional compilation options, but
// only for the duration of a scope.
class ScopedCompilationOptionsModifier {
public:
explicit ScopedCompilationOptionsModifier(LiteRtOptions compilation_options)
: accelerator_options_(&compilation_options->options) {}
~ScopedCompilationOptionsModifier() {
// Remove any option that was appended during the lifetime of this object.
while (--num_appended_options_ >= 0) {
LiteRtPopOpaqueOptions(accelerator_options_);
}
}
Expected<void> Append(litert::OpaqueOptions&& accelerator_options) {
LITERT_RETURN_IF_ERROR(LiteRtAppendOpaqueOptions(
accelerator_options_, accelerator_options.Release()));
++num_appended_options_;
return {};
}
private:
LiteRtOpaqueOptions* const accelerator_options_;
int num_appended_options_ = 0;
};
} // namespace
Expected<LiteRtCompiledModelT::Ptr> LiteRtCompiledModelT::Create(
LiteRtEnvironmentT* env, LiteRtModel model,
LiteRtOptions jit_compilation_options) {
if (!jit_compilation_options) {
return litert::ErrorStatusBuilder::InvalidArgument()
<< "No compilation options passed.";
}
auto compiled_model = std::make_unique<LiteRtCompiledModelT>(env);
LiteRtHwAcceleratorSet hardware_accelerators = kLiteRtHwAcceleratorNone;
LITERT_RETURN_IF_ERROR(LiteRtGetOptionsHardwareAccelerators(
jit_compilation_options, &hardware_accelerators));
if (hardware_accelerators == kLiteRtHwAcceleratorNone) {
return litert::ErrorStatusBuilder::InvalidArgument()
<< "No acceleration provided.";
}
LITERT_RETURN_IF_ERROR(compiled_model->InitializeModel(
*model, hardware_accelerators, jit_compilation_options, *env));
LITERT_RETURN_IF_ERROR(compiled_model->InitializeRuntime(
env, hardware_accelerators, jit_compilation_options));
if (compiled_model->GetModelBase() == nullptr) {
return Error(kLiteRtStatusErrorRuntimeFailure,
"Failed to initialize model memory.");
}
ScopedCompilationOptionsModifier scoped_modifier(jit_compilation_options);
{
// Add information about the model allocation to the opaque chain.
LITERT_ASSIGN_OR_RETURN(auto dispatch_options,
DispatchDelegateOptions::Create());
LITERT_RETURN_IF_ERROR(
dispatch_options.SetAllocBase(compiled_model->GetModelBase()));
LITERT_RETURN_IF_ERROR(
dispatch_options.SetAllocBaseFd(compiled_model->fb_model_fd_));
LITERT_RETURN_IF_ERROR(scoped_modifier.Append(std::move(dispatch_options)));
}
// Load and restore external weights for CPU execution before delegates are
// applied. This ensures that XNNPack and other CPU delegates can see the
// weight data.
if (hardware_accelerators & kLiteRtHwAcceleratorCpu) {
LITERT_RETURN_IF_ERROR(compiled_model->RestoreExternalWeightsForCpu());
}
// Apply accelerators matching the requested hardware support to the
// model in the order they were registered.
for (auto& accelerator : env->GetAcceleratorRegistry()) {
bool delegate_responsible_for_jit = false;
LITERT_RETURN_IF_ERROR(
LiteRtIsAcceleratorDelegateResponsibleForJitCompilation(
accelerator.get(), &delegate_responsible_for_jit));
LiteRtHwAcceleratorSet accelerator_supported_hardware;
LITERT_RETURN_IF_ERROR(accelerator->GetHardwareSupport(
accelerator.get(), &accelerator_supported_hardware));
// We don't apply the delegate if:
// - the delegate is responsible for JIT compilation
// - and JIT has not been requested for the hardware it supports.
if (delegate_responsible_for_jit &&
!(hardware_accelerators & accelerator_supported_hardware)) {
continue;
}
LITERT_DEBUG_CODE({
const char* accelerator_name = nullptr;
if (accelerator->GetName(accelerator.get(), &accelerator_name) !=
kLiteRtStatusOk ||
!accelerator_name) {
LITERT_LOG(LITERT_WARNING, "Failed to get name for accelerator");
} else {
LITERT_LOG(LITERT_DEBUG, "Apply accelerator %s", accelerator_name);
}
});
LiteRtDelegateWrapper delegate_wrapper = nullptr;
LITERT_RETURN_IF_ERROR(accelerator->CreateDelegate(
LrtGetRuntimeContext(), env, accelerator.get(), jit_compilation_options,
&delegate_wrapper));
TfLiteOpaqueDelegate* delegate_ptr = nullptr;
LrtGetRuntimeContext()->unwrap_delegate(delegate_wrapper, &delegate_ptr);
auto delegate = std::unique_ptr<LiteRtDelegateWrapperT,
std::function<void(LiteRtDelegateWrapper)>>{
delegate_wrapper, [destroy_fn = accelerator->DestroyDelegate](
LiteRtDelegateWrapper wrapper) {
if (destroy_fn) destroy_fn(LrtGetRuntimeContext(), wrapper);
}};
if (compiled_model->interp_->ModifyGraphWithDelegate(delegate_ptr) !=
kTfLiteOk) {
return Unexpected(kLiteRtStatusErrorRuntimeFailure,
"Failed to modify graph with delegate");
}
compiled_model->RegisterDelegate({std::move(delegate),
accelerator->StartMetricsCollection,
accelerator->StopMetricsCollection});
}
LITERT_ASSIGN_OR_RETURN(bool has_non_delegated_ops,
compiled_model->HasNonDelegatedOps());
if (!(hardware_accelerators & kLiteRtHwAcceleratorCpu) &&
has_non_delegated_ops) {
return Error(
kLiteRtStatusErrorCompilation,
"Some ops are not accelerated. Add kLiteRtHwAcceleratorCpu to the "
"compilation accelerator set to allow using the CPU to run those.");
}
compiled_model->CheckCpuTensors();
return compiled_model;
}
Expected<bool> LiteRtCompiledModelT::HasNonDelegatedOps() {
for (int subgraph_no = 0; subgraph_no < interp_->subgraphs_size();
++subgraph_no) {
const auto* const subgraph = interp_->subgraph(subgraph_no);
if (subgraph->IsDelegationSkippable()) {
continue;
}
const auto& execution_plan = subgraph->execution_plan();
const auto& nodes_and_registration = subgraph->nodes_and_registration();
for (int node_index : execution_plan) {
const TfLiteRegistration& registration =
nodes_and_registration[node_index].second;
if (registration.builtin_code != kTfLiteBuiltinDelegate &&
(registration.builtin_code != kTfLiteBuiltinCustom ||
litert::internal::kLiteRtDispatchOpCustomName !=
registration.custom_name)) {
return true;
}
}
}
return false;
}
void LiteRtCompiledModelT::CheckCpuTensors() {
cpu_tensors_.clear();
for (int subgraph_no = 0; subgraph_no < interp_->subgraphs_size();
++subgraph_no) {
auto* subgraph = interp_->subgraph(subgraph_no);
auto& execution_plan = subgraph->execution_plan();
auto& nodes_and_registration = subgraph->nodes_and_registration();
for (int node_index : execution_plan) {
const TfLiteNode& node = nodes_and_registration[node_index].first;
const TfLiteRegistration& registration =
nodes_and_registration[node_index].second;
// Don't mark delegate nodes as CPU nodes except for XNNPack ones.
if (registration.builtin_code == kTfLiteBuiltinDelegate &&
!(registration.custom_name &&
registration.custom_name ==
absl::string_view("TfLiteXNNPackDelegate"))) {
continue;
}
// Don't mark AOT compiled NPU custom ops as CPU nodes.
if (registration.builtin_code == kTfLiteBuiltinCustom &&
registration.custom_name &&
absl::StrContains(registration.custom_name,
litert::internal::kLiteRtDispatchOpCustomName)) {
continue;
}
// Mark input of node as CPU tensors.
for (int i = 0; i < node.inputs->size; ++i) {
int input_tensor_index = node.inputs->data[i];
if (input_tensor_index == kTfLiteOptionalTensor) continue;
cpu_tensors_.insert({subgraph_no, input_tensor_index});
}
}
}
}
#if !defined(LITERT_DISABLE_NPU)
Expected<bool> LiteRtCompiledModelT::ApplyPluginsWithCaching(
LiteRtModelT& model, LiteRtHwAcceleratorSet hw_accelerators,
LiteRtOptionsT& options, LiteRtEnvironmentT& env) {
bool need_reserialization = false;
compilation_cache_ = MaybeCreateCompilationCache(env);
std::optional<uint64_t> model_hash = std::nullopt;
// Load the plugins before JIT compilation attempt, so that we can check the
// cache first.
auto maybe_compiled_plugins =
TryGetCompilerPlugins(options, env, hw_accelerators);
// If we have a cache (user provided
// 'kLiteRtEnvOptionTagCompilerPluginLibraryDir'), and we loaded the plugins
// successfully, we can try to load the model from the cache.
if (compilation_cache_.has_value()) {
Expected<uint64_t> maybe_model_hash =
litert::internal::CompilationCache::TryGetModelHash(
model, &options, maybe_compiled_plugins);
if (maybe_model_hash.HasValue()) {
model_hash = maybe_model_hash.Value();
if (TryLoadingFromCache(model_hash.value())) {
LITERT_LOG(LITERT_INFO,
"Flatbuffer model initialized from cached model.");
return true;
}
}
}
// Cache miss, we need to continue with JIT compilation.
if (maybe_compiled_plugins.HasValue()) {
TryApplyPluginsImpl(&model, hw_accelerators, maybe_compiled_plugins.Value(),
&need_reserialization);
// Store the compiler plugins to a member variable to postpone its
// destruction and reduce initialization time.
maybe_compiled_plugins_ = std::move(maybe_compiled_plugins.Value());
}
if (!need_reserialization) {
return false;
}
LITERT_LOG(LITERT_INFO, "JIT compilation changed model, reserializing...");
LITERT_ASSIGN_OR_RETURN(auto serialized, SerializeModel(std::move(model)));
if (model_hash.has_value()) {
LITERT_LOG(LITERT_DEBUG, "Saving JIT compiled model to cache.");
LITERT_RETURN_IF_ERROR(
compilation_cache_.value().SaveModel(serialized, model_hash.value()));
}
model_buf_ = std::move(serialized);
fb_model_ = tflite::FlatBufferModel::BuildFromBuffer(
reinterpret_cast<const char*>(model_buf_.Data()), model_buf_.Size(),
error_reporter_.get());
if (fb_model_ == nullptr) {
return Unexpected(kLiteRtStatusErrorFileIO,
"Failed to build flatbuffer from buffer");
}
LITERT_LOG(LITERT_DEBUG,
"Plugins applied, flatbuffer model initialized from JIT compiled "
"model.");
fb_model_fd_ = GetAllocationFd(fb_model_->allocation());
return true;
}
bool LiteRtCompiledModelT::TryLoadingFromCache(uint64_t model_hash) {
if (!compilation_cache_.has_value()) {
return false;
}
// Check if we compiled this model before.
Expected<std::optional<LiteRtModelT::Ptr>> maybe_cached_model =
compilation_cache_.value().TryLoadModel(model_hash);
if (!maybe_cached_model) {
// The model was found in the cache, but failed to load.
LITERT_LOG(LITERT_WARNING, "Failed to load model from cache: %s",
maybe_cached_model.Error().Message().c_str());
return false;
}
std::optional<LiteRtModelT::Ptr> cached_model =
std::move(maybe_cached_model.Value());
if (!cached_model.has_value()) {
// The model was not found in the cache, don't log anything because this is
// expected when the cache is cleared, or when the model is new.
return false;
}
// Cache hit and model loaded successfully, initialize the compiled model
// with the cached model.
const auto& tfl_wrapper_from_cached_model =
litert::internal::GetTflFlatbuffer(*cached_model.value());
auto tfl_buf_from_cached_model = tfl_wrapper_from_cached_model.Buf();
fb_model_ = tflite::FlatBufferModel::BuildFromBuffer(
tfl_buf_from_cached_model.StrData(), tfl_buf_from_cached_model.Size(),
error_reporter_.get());
fb_model_fd_ = GetAllocationFd(
tfl_wrapper_from_cached_model.FlatbufferModel().allocation());
cached_model_ = std::move(cached_model.value());
return true;
}
#endif // !defined(LITERT_DISABLE_NPU)
Expected<const LiteRtTensorBufferRequirementsT*>
LiteRtCompiledModelT::GetTensorBufferRequirements(const TfLiteTensor* tensor) {
LITERT_ASSIGN_OR_RETURN(const auto tensor_id,
GetTensorIdentifier(*interp_, tensor));
// Use the buffer context to get the buffer requirements only if the tensor
// is not a CPU tensor.
if (cpu_tensors_.find(tensor_id) == cpu_tensors_.end()) {
if (auto requirements = buffer_context_->GetBufferRequirements(tensor)) {
return *requirements;
}
} else {
LITERT_LOG(LITERT_DEBUG, "Tensor %s is shared with CPU.\n", tensor->name);
}
// Check if we have a cached CPU buffer requirement.
auto cached_req = cpu_buffer_requirements_.find(tensor_id);
if (cached_req != cpu_buffer_requirements_.end()) {
return cached_req->second.get();
}