Repository navigation
Expand file tree
/
Copy pathlitert_tensor_buffer.h
More file actions
915 lines (824 loc) · 35.5 KB
/
Copy pathlitert_tensor_buffer.h
File metadata and controls
915 lines (824 loc) · 35.5 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
// 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.
#ifndef ODML_LITERT_LITERT_CC_LITERT_TENSOR_BUFFER_H_
#define ODML_LITERT_LITERT_CC_LITERT_TENSOR_BUFFER_H_
#include <cstddef>
#include <cstring>
#include <string>
#include <utility>
#include <vector>
#include "litert/c/litert_common.h"
#include "litert/c/litert_custom_tensor_buffer.h"
#include "litert/c/litert_gl_types.h"
#include "litert/c/litert_model_types.h"
#include "litert/c/litert_opencl_types.h"
#include "litert/c/litert_tensor_buffer_types.h"
#include "litert/c/litert_webgpu_types.h"
#include "litert/cc/internal/litert_handle.h"
#include "litert/cc/litert_api_types.h"
#include "litert/cc/litert_common.h"
#include "litert/cc/litert_environment.h"
#include "litert/cc/litert_event.h"
#include "litert/cc/litert_expected.h"
#include "litert/cc/litert_macros.h"
#include "litert/cc/litert_ranked_tensor_type.h"
#include "litert/cc/litert_tensor_buffer_requirements.h"
#include "litert/cc/litert_tensor_buffer_types.h"
/// @file
/// @brief Defines C++ wrappers for LiteRT tensor buffers and related utilities.
namespace litert {
class TensorBufferRequirements;
namespace internal::tensor_buffer_detail {
inline Expected<LiteRtTensorBufferRequirements>
ToLiteRtTensorBufferRequirements(const internal::EnvironmentHolder& env,
const TensorBufferRequirements& requirements) {
LITERT_ASSIGN_OR_RETURN(const auto supported_types,
requirements.SupportedTypes());
LITERT_ASSIGN_OR_RETURN(const auto buffer_size, requirements.BufferSize());
LITERT_ASSIGN_OR_RETURN(const auto alignment, requirements.Alignment());
LITERT_ASSIGN_OR_RETURN(const auto strides, requirements.Strides());
std::vector<LiteRtTensorBufferType> litert_buffer_types;
litert_buffer_types.reserve(supported_types.size());
for (auto type : supported_types) {
litert_buffer_types.push_back(static_cast<LiteRtTensorBufferType>(type));
}
LiteRtTensorBufferRequirements litert_requirements;
LITERT_RETURN_IF_ERROR(
env.runtime->CreateTensorBufferRequirementsWithAlignment(
litert_buffer_types.size(), litert_buffer_types.data(), buffer_size,
strides.size(), strides.data(), alignment, &litert_requirements));
return litert_requirements;
}
} // namespace internal::tensor_buffer_detail
/// @brief A C++ wrapper for `LiteRtTensorBuffer`, representing a tensor and
/// its associated backing buffer.
class TensorBuffer : public internal::BaseHandle<LiteRtTensorBuffer> {
public:
// TODO(b/479340050): Remove the default constructor.
[[deprecated("Do NOT use the default constructor.")]]
TensorBuffer()
: TensorBuffer(GetDefaultEnvironment()->GetHolder(), nullptr,
OwnHandle::kNo) {}
/// @brief Creates a managed `TensorBuffer` of a given buffer type and size.
///
/// The returned object is owned by the caller. For host memory, this
/// allocator guarantees `LITERT_HOST_MEMORY_BUFFER_ALIGNMENT` alignment and
/// reserves any delegate-specific padding (e.g., XNNPACK extra bytes), so
/// callers do not need to over-allocate manually.
static Expected<TensorBuffer> CreateManaged(
const Environment& env, TensorBufferType buffer_type,
const RankedTensorType& tensor_type, size_t buffer_size) {
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(env_holder.runtime->CreateManagedTensorBuffer(
env_holder.handle, static_cast<LiteRtTensorBufferType>(buffer_type),
&litert_tensor_type, buffer_size, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
}
/// @brief Creates a managed `TensorBuffer` from requirements.
///
/// The returned object is owned by the caller. It automatically selects
/// the best buffer type and applies required alignment and padding.
static Expected<TensorBuffer> CreateManagedFromRequirements(
const Environment& env, const RankedTensorType& tensor_type,
const TensorBufferRequirements& requirements) {
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_ASSIGN_OR_RETURN(
LiteRtTensorBufferRequirements litert_requirements,
internal::tensor_buffer_detail::ToLiteRtTensorBufferRequirements(
env_holder, requirements));
auto cleanup = internal::MakeCleanup([&env_holder, litert_requirements] {
env_holder.runtime->DestroyTensorBufferRequirements(litert_requirements);
});
LITERT_RETURN_IF_ERROR(
env_holder.runtime->CreateManagedTensorBufferFromRequirements(
env_holder.handle, &litert_tensor_type, litert_requirements,
&tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
}
/// @brief Creates a managed host memory `TensorBuffer` using the default
/// environment (if applicable).
///
/// The returned object is owned by the caller.
/// @deprecated Use API with explicit Environment instead.
[[deprecated("Use API with explicit Environment instead.")]]
static Expected<TensorBuffer> CreateManagedHostMemory(
const RankedTensorType& tensor_type, size_t buffer_size) {
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = GetDefaultEnvironment()->GetHolder();
LITERT_RETURN_IF_ERROR(env_holder.runtime->CreateManagedTensorBuffer(
/*env=*/nullptr, kLiteRtTensorBufferTypeHostMemory, &litert_tensor_type,
buffer_size, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
}
/// @brief Creates a `TensorBuffer` that wraps the provided host memory.
///
/// The provided host memory is not owned by the `TensorBuffer` object and
/// must outlive it. Callers are responsible for ensuring that the pointer is
/// aligned to at least `LITERT_HOST_MEMORY_BUFFER_ALIGNMENT` bytes (or
/// `kHostMemoryBufferAlignment`) and that any required padding for delegates
/// like XNNPACK is included and initialized.
///
/// Note: When passing host memory to specific hardware accelerators that may
/// have stricter alignment requirements, query the tensor's requirements via
/// `CompiledModel::GetInputBufferRequirements` / `TensorBufferRequirements`.
static Expected<TensorBuffer> CreateFromHostMemory(
const Environment& env, const RankedTensorType& tensor_type,
void* host_mem_addr, size_t buffer_size) {
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(env_holder.runtime->CreateTensorBufferFromHostMemory(
&litert_tensor_type, host_mem_addr, buffer_size,
/*deallocator=*/nullptr, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
}
/// @deprecated Use API with explicit Environment instead.
[[deprecated("Use API with explicit Environment instead.")]]
static Expected<TensorBuffer> CreateFromHostMemory(
const RankedTensorType& tensor_type, void* host_mem_addr,
size_t buffer_size) {
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = GetDefaultEnvironment()->GetHolder();
LITERT_RETURN_IF_ERROR(env_holder.runtime->CreateTensorBufferFromHostMemory(
&litert_tensor_type, host_mem_addr, buffer_size,
/*deallocator=*/nullptr, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
}
/// @brief Creates a `TensorBuffer` that wraps an Android Hardware Buffer.
///
/// The `TensorBuffer` acquires its own reference to the provided
/// `AHardwareBuffer` and releases it on destruction; the caller remains
/// responsible for releasing its own reference.
/// @param ahwb_offset The offset in bytes from the start of the
/// `AHardwareBuffer` where the tensor data begins.
static Expected<TensorBuffer> CreateFromAhwb(
const Environment& env, const RankedTensorType& tensor_type,
AHardwareBuffer* ahwb, size_t ahwb_offset) {
#if LITERT_HAS_AHWB_SUPPORT
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(env_holder.runtime->CreateTensorBufferFromAhwb(
env_holder.handle, &litert_tensor_type, ahwb, ahwb_offset,
/*deallocator=*/nullptr, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
#else
return litert::Unexpected(
kLiteRtStatusErrorRuntimeFailure,
"AHardwareBuffer is not supported on this platform");
#endif
}
/// @brief Creates a `TensorBuffer` that wraps an ION buffer.
///
/// The provided ION buffer is not owned by the `TensorBuffer` and must
/// outlive it.
/// @param ion_buffer_offset The offset in bytes from the start of the
/// ION buffer where the tensor data begins.
static Expected<TensorBuffer> CreateFromIonBuffer(
const Environment& env, const RankedTensorType& tensor_type,
void* ion_buffer_addr, int ion_buffer_fd, size_t ion_buffer_size,
size_t ion_buffer_offset) {
#if LITERT_HAS_ION_SUPPORT
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(env_holder.runtime->CreateTensorBufferFromIonBuffer(
&litert_tensor_type, ion_buffer_addr, ion_buffer_fd, ion_buffer_size,
ion_buffer_offset, /*deallocator=*/nullptr, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
#else
return litert::Unexpected(Status::kErrorRuntimeFailure,
"ION is not supported on this platform");
#endif
}
/// @brief Creates a `TensorBuffer` that wraps a DMA-BUF buffer.
///
/// The provided DMA-BUF buffer is not owned by the `TensorBuffer` and must
/// outlive it.
/// @param dmabuf_buffer_offset The offset in bytes from the start of the
/// DMA-BUF buffer where the tensor data begins.
static Expected<TensorBuffer> CreateFromDmaBufBuffer(
const Environment& env, const RankedTensorType& tensor_type,
void* dmabuf_buffer_addr, int dmabuf_buffer_fd, size_t dmabuf_buffer_size,
size_t dmabuf_buffer_offset) {
#if LITERT_HAS_DMABUF_SUPPORT
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(
env_holder.runtime->CreateTensorBufferFromDmaBufBuffer(
&litert_tensor_type, dmabuf_buffer_addr, dmabuf_buffer_fd,
dmabuf_buffer_size, dmabuf_buffer_offset, /*deallocator=*/nullptr,
&tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
#else
return litert::Unexpected(Status::kErrorRuntimeFailure,
"DMA-BUF is not supported on this platform");
#endif
}
/// @brief Creates a `TensorBuffer` that wraps a FastRPC buffer.
///
/// The provided FastRPC buffer is not owned by the `TensorBuffer` and must
/// outlive it.
/// @param fastrpc_buffer_offset The offset in bytes from the start of the
/// FastRPC buffer where the tensor data begins.
static Expected<TensorBuffer> CreateFromFastRpcBuffer(
const Environment& env, const RankedTensorType& tensor_type,
void* fastrpc_buffer_addr, int fastrpc_buffer_fd,
size_t fastrpc_buffer_size, size_t fastrpc_buffer_offset) {
#if LITERT_HAS_FASTRPC_SUPPORT
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(
env_holder.runtime->CreateTensorBufferFromFastRpcBuffer(
&litert_tensor_type, fastrpc_buffer_addr, fastrpc_buffer_fd,
fastrpc_buffer_size, fastrpc_buffer_offset, /*deallocator=*/nullptr,
&tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
#else
return litert::Unexpected(Status::kErrorRuntimeFailure,
"FastRPC is not supported on this platform");
#endif
}
/// @brief Wraps an existing handle as a tensor buffer of a custom
/// `buffer_type` (e.g. kLiteRtTensorBufferTypeOpenVINOTensorBuffer), via that
/// type's registered import handler. `handle` is the custom handle of an
/// existing buffer of that type, as returned by `GetCustomHandle()`, so this
/// can create a view of `tensor_type` onto that buffer's memory. The
/// returned buffer does not own the memory; the caller keeps the source
/// buffer alive.
static Expected<TensorBuffer> CreateFromCustomHandle(
const Environment& env, const RankedTensorType& tensor_type,
TensorBufferType buffer_type, HwMemoryHandle handle, size_t size_bytes) {
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(
env_holder.runtime->CreateTensorBufferFromCustomHandle(
env_holder.handle, &litert_tensor_type,
static_cast<LiteRtTensorBufferType>(buffer_type), handle,
size_bytes, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
}
static Expected<TensorBuffer> CreateFromClBuffer(
const Environment& env, const RankedTensorType& tensor_type,
TensorBufferType buffer_type, LiteRtClMem cl_memory, size_t size_bytes) {
#if LITERT_HAS_OPENCL_SUPPORT
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(
env_holder.runtime->CreateTensorBufferFromOpenClMemory(
env_holder.handle, &litert_tensor_type,
static_cast<LiteRtTensorBufferType>(buffer_type), cl_memory,
size_bytes, /*deallocator=*/nullptr, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
#else
return litert::Unexpected(Status::kErrorRuntimeFailure,
"OpenCL is not supported on this platform");
#endif
}
static Expected<TensorBuffer> CreateFromGlBuffer(
const Environment& env, const RankedTensorType& tensor_type,
LiteRtGLenum target, LiteRtGLuint id, size_t size_bytes, size_t offset) {
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(env_holder.runtime->CreateTensorBufferFromGlBuffer(
env_holder.handle, &litert_tensor_type, target, id, size_bytes, offset,
/*deallocator=*/nullptr, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
}
static Expected<TensorBuffer> CreateFromGlTexture(
const Environment& env, const RankedTensorType& tensor_type,
LiteRtGLenum target, LiteRtGLuint id, LiteRtGLenum format,
size_t size_bytes, LiteRtGLint layer) {
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(env_holder.runtime->CreateTensorBufferFromGlTexture(
env_holder.handle, &litert_tensor_type, target, id, format, size_bytes,
layer, /*deallocator=*/nullptr, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
}
#if LITERT_HAS_WEBGPU_SUPPORT
static Expected<TensorBuffer> CreateFromWebGpuBuffer(
const Environment& env, const RankedTensorType& tensor_type,
TensorBufferType buffer_type, LiteRtWGPUBuffer buffer,
size_t size_bytes) {
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(
env_holder.runtime->CreateTensorBufferFromWebGpuBuffer(
env_holder.handle, &litert_tensor_type,
static_cast<LiteRtTensorBufferType>(buffer_type), buffer,
size_bytes,
/*deallocator=*/nullptr, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
}
static Expected<TensorBuffer> CreateFromWebGpuTexture(
const Environment& env, const RankedTensorType& tensor_type,
void* texture, size_t size_bytes) {
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(
env_holder.runtime->CreateTensorBufferFromWebGpuTexture(
env_holder.handle, &litert_tensor_type, texture, size_bytes,
/*deallocator=*/nullptr, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
}
#endif // LITERT_HAS_WEBGPU_SUPPORT
#if LITERT_HAS_METAL_SUPPORT
static Expected<TensorBuffer> CreateFromMetalBuffer(
const Environment& env, const RankedTensorType& tensor_type,
TensorBufferType buffer_type, void* buffer, size_t size_bytes) {
LiteRtTensorBuffer tensor_buffer;
auto litert_tensor_type = static_cast<LiteRtRankedTensorType>(tensor_type);
auto env_holder = env.GetHolder();
LITERT_RETURN_IF_ERROR(
env_holder.runtime->CreateTensorBufferFromMetalMemory(
env_holder.handle, &litert_tensor_type,
static_cast<LiteRtTensorBufferType>(buffer_type), buffer,
size_bytes,
/*deallocator=*/nullptr, &tensor_buffer));
return TensorBuffer(env_holder, tensor_buffer, OwnHandle::kYes);
}
#endif // LITERT_HAS_METAL_SUPPORT
/// @brief Creates a duplicate of the current `TensorBuffer` object.
///
/// The returned object is reference-counted, so the underlying
/// `LiteRtTensorBuffer` handle is not released until the last reference is
/// removed.
Expected<TensorBuffer> Duplicate() const {
if (!IsOwned()) {
return Unexpected(Status::kErrorInvalidArgument,
"Cannot duplicate a non-owned tensor buffer");
}
LITERT_RETURN_IF_ERROR(env_.runtime->DuplicateTensorBuffer(Get()));
return TensorBuffer(env_, Get(), OwnHandle::kYes);
}
litert::Expected<AHardwareBuffer*> GetAhwb() const {
#if LITERT_HAS_AHWB_SUPPORT
AHardwareBuffer* ahwb;
LITERT_RETURN_IF_ERROR(env_.runtime->GetTensorBufferAhwb(Get(), &ahwb));
return ahwb;
#else
return litert::Unexpected(
kLiteRtStatusErrorRuntimeFailure,
"AHardwareBuffer is not supported on this platform");
#endif
}
struct DmaBuf {
void* addr;
int fd;
};
litert::Expected<DmaBuf> GetDmaBuf() const {
#if LITERT_HAS_DMABUF_SUPPORT
DmaBuf dma_buf;
LITERT_RETURN_IF_ERROR(env_.runtime->GetTensorBufferDmaBufBuffer(
Get(), &dma_buf.addr, &dma_buf.fd));
return dma_buf;
#else
return litert::Unexpected(Status::kErrorRuntimeFailure,
"DMA-BUF is not supported on this platform");
#endif
}
struct IonBuf {
void* addr;
int fd;
};
litert::Expected<IonBuf> GetIonBuf() const {
#if LITERT_HAS_ION_SUPPORT
IonBuf ion_buf;
LITERT_RETURN_IF_ERROR(env_.runtime->GetTensorBufferIonBuffer(
Get(), &ion_buf.addr, &ion_buf.fd));
return ion_buf;
#else
return litert::Unexpected(Status::kErrorRuntimeFailure,
"ION is not supported on this platform");
#endif
}
struct FastRpcBuf {
void* addr;
int fd;
};
litert::Expected<FastRpcBuf> GetFastRpcBuf() const {
#if LITERT_HAS_FASTRPC_SUPPORT
FastRpcBuf fastrpc_buf;
LITERT_RETURN_IF_ERROR(env_.runtime->GetTensorBufferFastRpcBuffer(
Get(), &fastrpc_buf.addr, &fastrpc_buf.fd));
return fastrpc_buf;
#else
return litert::Unexpected(Status::kErrorRuntimeFailure,
"FastRPC is not supported on this platform");
#endif
}
Expected<LiteRtClMem> GetOpenClMemory() const {
#if LITERT_HAS_OPENCL_SUPPORT
LiteRtClMem cl_mem;
LITERT_RETURN_IF_ERROR(
env_.runtime->GetTensorBufferOpenClMemory(Get(), &cl_mem));
return cl_mem;
#else
return litert::Unexpected(Status::kErrorRuntimeFailure,
"OpenCL is not supported on this platform");
#endif
}
/// @brief Returns the handle of a custom tensor buffer (buffer types in the
/// `kLiteRtTensorBufferTypeUserCustomBuffer` range). What the handle is
/// depends on the buffer type's provider; it can be passed to
/// `CreateFromCustomHandle()` with the same buffer type.
Expected<HwMemoryHandle> GetCustomHandle() const {
HwMemoryHandle hw_memory_handle;
LITERT_RETURN_IF_ERROR(
env_.runtime->GetTensorBufferCustomTensorBufferHandle(
Get(), &hw_memory_handle));
return hw_memory_handle;
}
Expected<HwMemoryHandle> GetWebGpuBuffer() const {
#if LITERT_HAS_WEBGPU_SUPPORT
HwMemoryHandle hw_memory_handle;
LITERT_RETURN_IF_ERROR(
env_.runtime->GetTensorBufferWebGpuBuffer(Get(), &hw_memory_handle));
return hw_memory_handle;
#else
return litert::Unexpected(Status::kErrorRuntimeFailure,
"WebGPU is not supported on this platform");
#endif
}
Expected<void*> GetMetalBuffer() const {
#if LITERT_HAS_METAL_SUPPORT
HwMemoryHandle hw_memory_handle;
LITERT_RETURN_IF_ERROR(
env_.runtime->GetTensorBufferMetalMemory(Get(), &hw_memory_handle));
return hw_memory_handle;
#else
return litert::Unexpected(Status::kErrorRuntimeFailure,
"Metal is not supported on this platform");
#endif // LITERT_HAS_METAL_SUPPORT
}
Expected<HwMemoryHandle> GetVulkanMemory() const {
#if LITERT_HAS_VULKAN_SUPPORT
HwMemoryHandle hw_memory_handle;
LITERT_RETURN_IF_ERROR(
env_.runtime->GetTensorBufferVulkanMemory(Get(), &hw_memory_handle));
return hw_memory_handle;
#else
return litert::Unexpected(Status::kErrorRuntimeFailure,
"Vulkan is not supported on this platform");
#endif
}
struct GlBuffer {
LiteRtGLenum target;
LiteRtGLuint id;
size_t size_bytes;
size_t offset;
};
Expected<GlBuffer> GetGlBuffer() const {
GlBuffer gl_buffer;
LITERT_RETURN_IF_ERROR(env_.runtime->GetTensorBufferGlBuffer(
Get(), &gl_buffer.target, &gl_buffer.id, &gl_buffer.size_bytes,
&gl_buffer.offset));
return gl_buffer;
}
struct GlTexture {
LiteRtGLenum target;
LiteRtGLuint id;
LiteRtGLenum format;
size_t size_bytes;
LiteRtGLint layer;
};
Expected<GlTexture> GetGlTexture() const {
GlTexture gl_texture;
LITERT_RETURN_IF_ERROR(env_.runtime->GetTensorBufferGlTexture(
Get(), &gl_texture.target, &gl_texture.id, &gl_texture.format,
&gl_texture.size_bytes, &gl_texture.layer));
return gl_texture;
}
Expected<TensorBufferType> BufferType() const {
LiteRtTensorBufferType tensor_buffer_type;
LITERT_RETURN_IF_ERROR(
env_.runtime->GetTensorBufferType(Get(), &tensor_buffer_type));
return static_cast<enum TensorBufferType>(tensor_buffer_type);
}
/// @brief Returns `true` if the tensor buffer is an OpenCL memory object.
/// @note This function does not return an `Expected<bool>` to prevent
/// potential misuse.
bool IsOpenClMemory() const {
LiteRtTensorBufferType tensor_buffer_type;
if (env_.runtime->GetTensorBufferType(Get(), &tensor_buffer_type) !=
kLiteRtStatusOk) {
return false;
}
return ::IsOpenClMemory(tensor_buffer_type);
}
/// @brief Returns `true` if the tensor buffer is a WebGPU memory object.
/// @note This function does not return an `Expected<bool>` to prevent
/// potential misuse.
bool IsWebGpuMemory() const {
LiteRtTensorBufferType tensor_buffer_type;
if (env_.runtime->GetTensorBufferType(Get(), &tensor_buffer_type) !=
kLiteRtStatusOk) {
return false;
}
return ::IsWebGpuMemory(tensor_buffer_type);
}
/// @brief Returns `true` if the tensor buffer is a Metal memory object.
/// @note This function does not return an `Expected<bool>` to prevent
/// potential misuse.
bool IsMetalMemory() const {
LiteRtTensorBufferType tensor_buffer_type;
if (env_.runtime->GetTensorBufferType(Get(), &tensor_buffer_type) !=
kLiteRtStatusOk) {
return false;
}
return ::IsMetalMemory(tensor_buffer_type);
}
/// @brief Returns `true` if the tensor buffer is a Vulkan memory object.
/// @note This function does not return an `Expected<bool>` to prevent
/// potential misuse.
bool IsVulkanMemory() const {
LiteRtTensorBufferType tensor_buffer_type;
if (env_.runtime->GetTensorBufferType(Get(), &tensor_buffer_type) !=
kLiteRtStatusOk) {
return false;
}
return ::IsVulkanMemory(tensor_buffer_type);
}
Expected<RankedTensorType> TensorType() const {
LiteRtRankedTensorType tensor_type;
LITERT_RETURN_IF_ERROR(
env_.runtime->GetTensorBufferTensorType(Get(), &tensor_type));
return RankedTensorType(tensor_type);
}
bool HasType(const RankedTensorType& type) const {
auto t = TensorType();
return t && *t == type;
}
bool HasType(const LiteRtRankedTensorType& type) const {
auto t = TensorType();
return t && *t == ::litert::RankedTensorType(type);
}
/// @brief Returns the size of the underlying hardware tensor buffer.
///
/// This size can differ from `PackedSize()` if striding and padding exist.
Expected<size_t> Size() const {
size_t size;
LITERT_RETURN_IF_ERROR(env_.runtime->GetTensorBufferSize(Get(), &size));
return size;
}
/// @brief Returns the size of the tensor buffer in packed bytes.
///
/// This size is used for reading/writing data on a locked tensor buffer.
Expected<size_t> PackedSize() const {
size_t size;
LITERT_RETURN_IF_ERROR(
env_.runtime->GetTensorBufferPackedSize(Get(), &size));
return size;
}
Expected<size_t> Offset() const {
size_t offset;
LITERT_RETURN_IF_ERROR(env_.runtime->GetTensorBufferOffset(Get(), &offset));
return offset;
}
bool HasEvent() const {
bool has_event;
auto status = env_.runtime->HasTensorBufferEvent(Get(), &has_event);
LITERT_INTERNAL_CHECK_EQ(status, kLiteRtStatusOk);
return has_event;
}
Expected<Event> GetEvent() const {
LiteRtEvent event;
LITERT_RETURN_IF_ERROR(env_.runtime->GetTensorBufferEvent(Get(), &event));
return Event::WrapCObject(env_, event, OwnHandle::kNo);
}
/// @brief Sets the C++ `Event` object for the tensor buffer.
///
/// This function takes ownership of the provided `Event` object.
Expected<void> SetEvent(Event&& event) {
if (!event.IsOwned()) {
return Error(Status::kErrorInvalidArgument, "Expected an owned event");
}
LITERT_RETURN_IF_ERROR(
env_.runtime->SetTensorBufferEvent(Get(), event.Release()));
return {};
}
Expected<void> ClearEvent() {
LITERT_RETURN_IF_ERROR(env_.runtime->ClearTensorBufferEvent(Get()));
return {};
}
enum class LockMode {
kRead = kLiteRtTensorBufferLockModeRead,
kWrite = kLiteRtTensorBufferLockModeWrite,
kReadWrite = kLiteRtTensorBufferLockModeReadWrite,
};
static LiteRtTensorBufferLockMode ToLiteRtLockMode(LockMode mode) {
switch (mode) {
case LockMode::kRead:
return kLiteRtTensorBufferLockModeRead;
case LockMode::kWrite:
return kLiteRtTensorBufferLockModeWrite;
case LockMode::kReadWrite:
return kLiteRtTensorBufferLockModeReadWrite;
}
}
/// @brief Locks the tensor buffer and returns a pointer to the host memory.
///
/// The mapped host memory is synchronized with the underlying hardware
/// tensor buffer.
/// For some memory types like AHWB, the pointer reflects changes of
/// underlying memory after locking, but it's not always the case.
/// For example, for most GPU memory types, the pointer memory is a snapshot
/// of the underlying memory at the time of locking. If the underlying
/// memory is modified after locking, the changes are not reflected in the
/// mapped host memory.
///
/// The same thing happens to write lock. If you locked a tensor buffer for
/// write, the underlying memory is not guaranteed to be updated immediately.
/// For most GPU memory types, the CPU -> GPU copy is only performed when the
/// tensor buffer is unlocked.
Expected<void*> Lock(LockMode mode = LockMode::kWrite) {
void* host_mem_addr;
LITERT_RETURN_IF_ERROR(env_.runtime->LockTensorBuffer(
Get(), &host_mem_addr, ToLiteRtLockMode(mode)));
return host_mem_addr;
}
/// @brief Unlocks the tensor buffer and may synchronize the underlying
/// hardware tensor buffer.
///
/// For most GPU memory types, the CPU -> GPU copy is performed if it was
/// locked for write.
Expected<void> Unlock() {
LITERT_RETURN_IF_ERROR(env_.runtime->UnlockTensorBuffer(Get()));
return {};
}
/// @brief Writes data from a user-provided `Span<const T>` to the
/// tensor buffer.
///
/// Returns an error if the provided buffer is larger than the tensor
/// buffer's size.
template <typename T>
Expected<void> Write(Span<const T> data) {
LITERT_ASSIGN_OR_RETURN(void* host_mem_addr, Lock(LockMode::kWrite));
auto unlock = internal::MakeCleanup([this] { Unlock(); });
LITERT_ASSIGN_OR_RETURN(size_t size, PackedSize());
if (size < data.size() * sizeof(T)) {
return Unexpected(
kLiteRtStatusErrorRuntimeFailure,
"TensorBuffer host memory buffer size is smaller than the given "
"data size, " +
std::to_string(size) + " vs " +
std::to_string(data.size() * sizeof(T)));
}
std::memcpy(host_mem_addr, data.data(), data.size() * sizeof(T));
return {};
}
/// @brief Reads data from the tensor buffer into a user-provided
/// `Span<T>`.
///
/// If the provided buffer is smaller than the tensor buffer, data will be
/// read up to the size of the provided buffer. Returns an error if the
/// provided buffer is larger than the tensor buffer.
template <typename T>
Expected<void> Read(Span<T> data) {
LITERT_ASSIGN_OR_RETURN(void* host_mem_addr, Lock(LockMode::kRead));
auto unlock = internal::MakeCleanup([this] { Unlock(); });
LITERT_ASSIGN_OR_RETURN(size_t size, PackedSize());
size_t total_read_size = data.size() * sizeof(T);
if (size < total_read_size) {
return Unexpected(
kLiteRtStatusErrorRuntimeFailure,
"TensorBuffer host memory buffer size is smaller than the given "
"data size, " +
std::to_string(size) + " vs " + std::to_string(total_read_size));
}
std::memcpy(data.data(), host_mem_addr, total_read_size);
return {};
}
/// @brief Clears the tensor buffer possibly asynchronously.
///
/// It may return immediately after scheduling a clear operation though it
/// guarantees that Read() will return data cleared, i.e. all zeros.
Expected<void> Clear() {
if (env_.runtime->ClearTensorBuffer(Get()) == kLiteRtStatusOk) {
return {};
}
// Fall back to synchronous write.
LITERT_ASSIGN_OR_RETURN(void* host_mem_addr, Lock(LockMode::kWrite));
auto unlock = internal::MakeCleanup([this] { Unlock(); });
LITERT_ASSIGN_OR_RETURN(size_t size, PackedSize());
std::memset(host_mem_addr, 0, size);
return {};
}
/// @internal
/// @brief Wraps a `LiteRtTensorBuffer` C object in a `TensorBuffer` C++
/// object.
/// @warning This is for internal use only.
[[deprecated("Use the other WrapCObject method instead.")]]
static TensorBuffer WrapCObject(LiteRtTensorBuffer tensor_buffer,
OwnHandle owned) {
return TensorBuffer(GetDefaultEnvironment()->GetHolder(), tensor_buffer,
owned);
}
/// @internal
/// @brief Wraps a `LiteRtTensorBuffer` C object in a `TensorBuffer` C++
/// object.
/// @warning This is for internal use only.
static TensorBuffer WrapCObject(const internal::EnvironmentHolder& env,
LiteRtTensorBuffer tensor_buffer,
OwnHandle owned) {
return TensorBuffer(env, tensor_buffer, owned);
}
private:
/// @param owned Indicates if the created `TensorBuffer` object should take
/// ownership of the provided `tensor_buffer` handle.
explicit TensorBuffer(const internal::EnvironmentHolder& env,
LiteRtTensorBuffer tensor_buffer, OwnHandle owned)
: internal::BaseHandle<LiteRtTensorBuffer>(
tensor_buffer,
[runtime = env.runtime](LiteRtTensorBuffer tensor_buffer) {
runtime->DestroyTensorBuffer(tensor_buffer);
},
owned),
env_(env) {}
// This is only used for managing the lifetime of ad-hoc environment for
// legacy cases.
[[deprecated("Do not use this field.")]]
static const Expected<Environment>& GetDefaultEnvironment() {
static const Expected<Environment> kDefaultEnvironment =
Environment::Create({});
return kDefaultEnvironment;
}
internal::EnvironmentHolder env_;
friend class TensorBufferScopedLock;
};
/// @brief A scoped lock for a `TensorBuffer`.
class TensorBufferScopedLock {
public:
TensorBufferScopedLock(const TensorBufferScopedLock& arg) = delete;
TensorBufferScopedLock(TensorBufferScopedLock&& arg) noexcept
: env_(arg.env_), tensor_buffer_(arg.tensor_buffer_) {
arg.tensor_buffer_ = nullptr;
};
TensorBufferScopedLock& operator=(TensorBufferScopedLock&& other) noexcept {
if (this != &other) {
env_ = other.env_;
tensor_buffer_ = other.tensor_buffer_;
other.tensor_buffer_ = nullptr;
}
return *this;
}
~TensorBufferScopedLock() {
if (tensor_buffer_ != nullptr) {
(void)env_.runtime->UnlockTensorBuffer(tensor_buffer_);
}
}
template <typename T = void>
static Expected<std::pair<TensorBufferScopedLock, T*>> Create(
TensorBuffer& tensor_buffer, TensorBuffer::LockMode mode) {
return Create<T>(tensor_buffer.env_, tensor_buffer.Get(), mode);
}
template <typename T = void>
static Expected<std::pair<TensorBufferScopedLock, const T*>> Create(
const TensorBuffer& tensor_buffer, TensorBuffer::LockMode mode) {
return Create<const T>(tensor_buffer.env_, tensor_buffer.Get(), mode);
}
template <typename T = void>
static Expected<std::pair<TensorBufferScopedLock, T*>> Create(
const internal::EnvironmentHolder& env, LiteRtTensorBuffer tensor_buffer,
TensorBuffer::LockMode mode) {
void* host_mem_addr;
LITERT_RETURN_IF_ERROR(env.runtime->LockTensorBuffer(
tensor_buffer, &host_mem_addr, TensorBuffer::ToLiteRtLockMode(mode)));
return std::make_pair(TensorBufferScopedLock(env, tensor_buffer),
static_cast<T*>(host_mem_addr));
}
private:
explicit TensorBufferScopedLock(const internal::EnvironmentHolder& env,
LiteRtTensorBuffer& tensor_buffer)
: env_(env), tensor_buffer_(tensor_buffer) {}
internal::EnvironmentHolder env_;
LiteRtTensorBuffer tensor_buffer_;
};
} // namespace litert
#endif // ODML_LITERT_LITERT_CC_LITERT_TENSOR_BUFFER_H_