Repository navigation
Expand file tree
/
Copy pathpybindings.cpp
More file actions
4855 lines (4590 loc) · 179 KB
/
Copy pathpybindings.cpp
File metadata and controls
4855 lines (4590 loc) · 179 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.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <algorithm>
#include <cinttypes>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <limits>
#include <memory>
#include <mutex>
#include <numeric>
#include <stdexcept>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <executorch/devtools/bundled_program/bundled_program.h>
#include <executorch/devtools/bundled_program/schema/bundled_program_schema_generated.h>
#include <executorch/devtools/etdump/etdump_flatcc.h>
#include <executorch/extension/data_loader/buffer_data_loader.h>
#include <executorch/extension/data_loader/mmap_data_loader.h>
#include <executorch/extension/flat_tensor/flat_tensor_data_map.h>
#include <executorch/extension/memory_allocator/malloc_memory_allocator.h>
#include <executorch/extension/module/bundled_module.h>
#include <executorch/extension/module/module.h>
#include <executorch/extension/pybindings/pybindings_cuda.h>
#include <executorch/extension/pybindings/pybindings_data_loader.h>
#include <executorch/extension/pybindings/pybindings_dlpack.h>
#include <executorch/extension/pybindings/pybindings_executorch_result.h>
#include <executorch/extension/tensor/tensor_ptr.h>
#include <executorch/extension/tensor/tensor_ptr_maker.h>
#include <executorch/extension/threadpool/threadpool.h>
#include <executorch/runtime/backend/interface.h>
#include <executorch/runtime/core/data_loader.h>
#include <executorch/runtime/core/device_memory_buffer.h>
#include <executorch/runtime/core/exec_aten/util/dim_order_util.h>
#include <executorch/runtime/core/exec_aten/util/scalar_type_util.h>
#include <executorch/runtime/core/exec_aten/util/tensor_dimension_limit.h>
#include <executorch/runtime/executor/method.h>
#include <executorch/runtime/executor/program.h>
#include <executorch/runtime/kernel/operator_registry.h>
#include <executorch/runtime/platform/assert.h>
#include <executorch/runtime/platform/platform.h>
#include <executorch/runtime/platform/profiler.h>
#include <executorch/runtime/platform/runtime.h>
#ifdef USE_ATEN_LIB
#include <ATen/Functions.h>
#include <ATen/Tensor.h>
#include <ATen/core/functional.h>
#include <c10/core/ScalarTypeToTypeMeta.h>
#include <c10/core/impl/LocalDispatchKeySet.h>
#include <torch/csrc/utils/pybind.h>
#include <torch/python.h>
#endif
/// Throws a runtime_error with the provided message if `error` is not `Ok`,
/// followed by the errors the runtime logged during this call.
#define THROW_IF_ERROR(error, message, ...) \
({ \
if ((error) != Error::Ok) { \
char msg_buf[128]; \
snprintf(msg_buf, sizeof(msg_buf), message, ##__VA_ARGS__); \
/* pybind will convert this to a python exception. */ \
throw std::runtime_error(with_runtime_errors(msg_buf)); \
} \
})
#define THROW_INDEX_IF_ERROR(error, message, ...) \
({ \
if ((error) != Error::Ok) { \
char msg_buf[128]; \
snprintf(msg_buf, sizeof(msg_buf), message, ##__VA_ARGS__); \
/* pybind will convert this to a python exception. */ \
throw std::out_of_range(with_runtime_errors(msg_buf)); \
} \
})
namespace py = pybind11;
using ::executorch::ET_RUNTIME_NAMESPACE::BackendInterface;
using ::executorch::ET_RUNTIME_NAMESPACE::get_backend_class;
using ::executorch::ET_RUNTIME_NAMESPACE::get_backend_name;
using ::executorch::ET_RUNTIME_NAMESPACE::get_num_registered_backends;
using ::executorch::ET_RUNTIME_NAMESPACE::get_registered_kernels;
using ::executorch::ET_RUNTIME_NAMESPACE::Kernel;
using ::executorch::ET_RUNTIME_NAMESPACE::Method;
using ::executorch::ET_RUNTIME_NAMESPACE::MethodMeta;
using ::executorch::ET_RUNTIME_NAMESPACE::Program;
using ::executorch::extension::BufferDataLoader;
using ::executorch::extension::MallocMemoryAllocator;
using ::executorch::extension::MmapDataLoader;
using ::executorch::extension::ET_BUNDLED_MODULE_NAMESPACE::BundledModule;
using ::executorch::extension::pybindings::PyDataLoader;
using ::executorch::runtime::BackendOption;
using ::executorch::runtime::DataLoader;
using ::executorch::runtime::DeviceMemoryBuffer;
using ::executorch::runtime::Error;
using ::executorch::runtime::EValue;
using ::executorch::runtime::EventTracerDebugLogLevel;
using ::executorch::runtime::HierarchicalAllocator;
using ::executorch::runtime::kMaxOptionKeyLength;
using ::executorch::runtime::kMaxOptionValueLength;
using ::executorch::runtime::LoadBackendOptionsMap;
using ::executorch::runtime::MemoryAllocator;
using ::executorch::runtime::MemoryManager;
using ::executorch::runtime::prof_result_t;
using ::executorch::runtime::Result;
using ::executorch::runtime::Span;
using ::executorch::runtime::Tag;
using torch::executor::etdump_result;
using torch::executor::ETDumpGen;
namespace executorch {
namespace extension {
namespace pybindings {
namespace {
// The errors the runtime logged on this thread, which RuntimeErrorScope
// limits to the current binding call. The runtime explains a failure only in
// its log and returns a bare error code, so the exceptions raised here carry
// these lines too. Plain arrays, because a log can arrive while thread_local
// objects with destructors are already destroyed at exit.
constexpr size_t kRuntimeErrorsCapacity = 1024;
thread_local char runtime_errors[kRuntimeErrorsCapacity];
thread_local size_t runtime_errors_size = 0;
// How many binding calls are running on this thread. Lines logged outside
// any, such as on worker threads, are not kept, so they never linger.
thread_local size_t runtime_error_scopes = 0;
std::string with_runtime_errors(const char* message) {
std::string result(message);
if (runtime_errors_size != 0) {
result.append(": ").append(runtime_errors, runtime_errors_size);
runtime_errors_size = 0;
}
return result;
}
// Starts every binding call with no runtime errors recorded, and gives an
// outer call its own back when a nested call returns.
struct RuntimeErrorScope final {
RuntimeErrorScope() : outer_(runtime_errors, runtime_errors_size) {
runtime_errors_size = 0;
++runtime_error_scopes;
}
~RuntimeErrorScope() {
--runtime_error_scopes;
std::memcpy(runtime_errors, outer_.data(), outer_.size());
runtime_errors_size = outer_.size();
}
private:
std::string outer_;
};
#ifndef USE_ATEN_LIB
constexpr char kTensorOutputEnvironmentVariable[] =
"EXECUTORCH_PYBINDINGS_TENSOR_OUTPUT";
enum class PortableTensorOutput { Torch, ExecuTorch };
PortableTensorOutput& portable_tensor_output() {
static PortableTensorOutput output = PortableTensorOutput::Torch;
return output;
}
void configure_portable_tensor_output() {
const char* value = std::getenv(kTensorOutputEnvironmentVariable);
if (value != nullptr && std::strcmp(value, "executorch") == 0) {
portable_tensor_output() = PortableTensorOutput::ExecuTorch;
return;
}
if (value != nullptr && std::strcmp(value, "torch") != 0) {
throw py::value_error(
std::string(kTensorOutputEnvironmentVariable) +
" must be either 'torch' or 'executorch', but was '" + value + "'");
}
try {
py::module_::import("torch");
(void)loaded_torch_module();
portable_tensor_output() = PortableTensorOutput::Torch;
} catch (py::error_already_set& error) {
if (value != nullptr || !error.matches(PyExc_ImportError)) {
throw;
}
portable_tensor_output() = PortableTensorOutput::ExecuTorch;
}
}
#endif
// Python tensor adapters can release the GIL while holding native state.
// Recursive locking also covers compound calls that invoke other methods.
class ObjectLock final {
public:
explicit ObjectLock(std::recursive_mutex& mutex)
: lock_(mutex, std::defer_lock) {
py::gil_scoped_release release;
lock_.lock();
}
private:
std::unique_lock<std::recursive_mutex> lock_;
};
#ifdef USE_ATEN_LIB
void* mutable_tensor_data_ptr_no_cow(const at::Tensor& tensor) {
if (tensor.numel() == 0) {
return nullptr;
}
if (!tensor.has_storage()) {
throw py::value_error(
"Tensor has a non-zero number of elements, but its data is not allocated");
}
auto* storage_data = static_cast<char*>(tensor.unsafeGetTensorImpl()
->unsafe_storage()
.unsafeGetStorageImpl()
->_mutable_data_ptr_no_checks()
.mutable_get());
if (storage_data == nullptr) {
throw py::value_error(
"Tensor has a non-zero number of elements, but its data is not allocated");
}
return storage_data + tensor.storage_offset() * tensor.itemsize();
}
#endif
// Copies dense data into the strides of another dimension order. The source
// strides must describe a dense layout of `sizes`.
template <size_t kItemSize>
void copy_to_layout(
const uint8_t* from,
const std::vector<int>& source_strides,
uint8_t* to,
const std::vector<int>& destination_strides,
const std::vector<int>& sizes) {
const size_t rank = sizes.size();
size_t count = 1;
for (const auto size : sizes) {
count *= static_cast<size_t>(size);
}
std::vector<int> index(rank, 0);
ptrdiff_t from_offset = 0;
ptrdiff_t to_offset = 0;
for (size_t element = 0; element < count; ++element) {
std::memcpy(
to + to_offset * static_cast<ptrdiff_t>(kItemSize),
from + from_offset * static_cast<ptrdiff_t>(kItemSize),
kItemSize);
for (size_t dim = rank; dim > 0; --dim) {
from_offset += source_strides[dim - 1];
to_offset += destination_strides[dim - 1];
if (++index[dim - 1] < sizes[dim - 1]) {
break;
}
from_offset -=
static_cast<ptrdiff_t>(sizes[dim - 1]) * source_strides[dim - 1];
to_offset -=
static_cast<ptrdiff_t>(sizes[dim - 1]) * destination_strides[dim - 1];
index[dim - 1] = 0;
}
}
}
void copy_to_layout(
const void* source,
const std::vector<int>& source_strides,
void* destination,
const std::vector<int>& destination_strides,
const std::vector<int>& sizes,
size_t itemsize) {
const auto* from = static_cast<const uint8_t*>(source);
auto* to = static_cast<uint8_t*>(destination);
switch (itemsize) {
case 1:
return copy_to_layout<1>(
from, source_strides, to, destination_strides, sizes);
case 2:
return copy_to_layout<2>(
from, source_strides, to, destination_strides, sizes);
case 4:
return copy_to_layout<4>(
from, source_strides, to, destination_strides, sizes);
case 8:
return copy_to_layout<8>(
from, source_strides, to, destination_strides, sizes);
case 16:
return copy_to_layout<16>(
from, source_strides, to, destination_strides, sizes);
default:
throw std::runtime_error(
"Unsupported element size " + std::to_string(itemsize));
}
}
// Whether data dense in `strides` is already laid out in `dim_order`. Size-one
// dimensions can sit anywhere in either order without moving any data.
bool has_layout(
const std::vector<int>& sizes,
const std::vector<int>& strides,
Span<const uint8_t> dim_order) {
std::vector<int> expected(sizes.size());
if (runtime::dim_order_to_stride(
sizes.data(), dim_order.data(), sizes.size(), expected.data()) !=
Error::Ok) {
return false;
}
for (size_t dim = 0; dim < sizes.size(); ++dim) {
if (sizes[dim] > 1 && strides[dim] != expected[dim]) {
return false;
}
}
return true;
}
/** Holds a Python buffer export and presents its metadata to ExecuTorch. */
class BufferTensor final {
public:
BufferTensor(
const py::handle& value,
const MethodMeta& method_meta,
size_t input_index)
: buffer_(py::reinterpret_borrow<py::buffer>(value)),
info_(buffer_.request()) {
check_rank();
const auto input_meta = method_meta.input_tensor_meta(input_index);
THROW_IF_ERROR(input_meta.error(), "not a tensor input");
const bool raw_bfloat16 =
input_meta->scalar_type() == executorch::aten::ScalarType::BFloat16 &&
info_.ndim == 1 &&
scalar_type_from_buffer(info_) == executorch::aten::ScalarType::Byte;
if (raw_bfloat16) {
if (info_.strides.size() != 1 || info_.strides[0] != 1) {
throw py::buffer_error(
"Raw bfloat16 inputs require contiguous byte buffers");
}
if (static_cast<size_t>(info_.size) != input_meta->nbytes()) {
throw py::value_error(
"raw bfloat16 input has " + std::to_string(info_.size) +
" bytes, but the method expects " +
std::to_string(input_meta->nbytes()));
}
scalar_type_ = executorch::aten::ScalarType::BFloat16;
sizes_.assign(input_meta->sizes().begin(), input_meta->sizes().end());
dim_order_.assign(
input_meta->dim_order().begin(), input_meta->dim_order().end());
strides_.resize(sizes_.size());
const auto status = runtime::dim_order_to_stride(
sizes_.data(), dim_order_.data(), sizes_.size(), strides_.data());
THROW_IF_ERROR(
status, "Invalid dimension order for input %zu", input_index);
} else {
read_layout();
}
if ((info_.readonly || raw_bfloat16) && info_.size > 0) {
owned_data_.resize(info_.size * info_.itemsize);
std::memcpy(owned_data_.data(), info_.ptr, owned_data_.size());
info_ = py::buffer_info(
owned_data_.data(),
info_.itemsize,
info_.format,
info_.ndim,
info_.shape,
info_.strides);
buffer_ = py::buffer();
}
}
// A buffer that is not bound to a method input. Its data is borrowed, not
// copied.
explicit BufferTensor(const py::handle& value)
: buffer_(py::reinterpret_borrow<py::buffer>(value)),
info_(buffer_.request()) {
check_rank();
read_layout();
}
void* data() const {
return owned_data_.empty() ? info_.ptr
: const_cast<uint8_t*>(owned_data_.data());
}
const std::vector<int>& sizes() const {
return sizes_;
}
const std::vector<int>& strides() const {
return strides_;
}
const std::vector<uint8_t>& dim_order() const {
return dim_order_;
}
executorch::aten::ScalarType scalar_type() const {
return scalar_type_;
}
// Describes the data in the exported dimension order. Data dense in another
// order is copied into that order, since reading it with the exported
// strides would permute its values. Empty data needs no copy. ATen builds
// keep the data as it is: there the runtime gives each input contiguous
// strides when it resizes it, so only contiguous data reads correctly.
void use_layout(Span<const uint8_t> dim_order) {
// The input check that follows reports a rank mismatch.
if (dim_order.size() != sizes_.size()) {
return;
}
const bool empty = has_empty_dimension();
#ifdef USE_ATEN_LIB
if (!empty) {
return;
}
#endif
if (!empty && has_layout(sizes_, strides_, dim_order)) {
return;
}
std::vector<int> strides(sizes_.size());
const auto status = runtime::dim_order_to_stride(
sizes_.data(), dim_order.data(), sizes_.size(), strides.data());
THROW_IF_ERROR(status, "Invalid dimension order for buffer input");
if (!empty) {
std::vector<uint8_t> converted(nbytes());
copy_to_layout(
data(),
strides_,
converted.data(),
strides,
sizes_,
static_cast<size_t>(info_.itemsize));
owned_data_ = std::move(converted);
std::vector<py::ssize_t> byte_strides(strides.begin(), strides.end());
for (auto& stride : byte_strides) {
stride *= info_.itemsize;
}
// Drop the export too, so the caller's object is released.
info_ = py::buffer_info(
owned_data_.data(),
info_.itemsize,
info_.format,
info_.ndim,
info_.shape,
byte_strides);
buffer_ = py::buffer();
}
strides_ = std::move(strides);
dim_order_.assign(dim_order.begin(), dim_order.end());
}
bool borrows_data() const {
return owned_data_.empty() && info_.size > 0;
}
std::pair<const void*, size_t> current_storage() const {
const auto current = buffer_.request();
return {
current.ptr,
static_cast<size_t>(current.size) *
static_cast<size_t>(current.itemsize)};
}
size_t nbytes() const {
return static_cast<size_t>(info_.size) *
static_cast<size_t>(info_.itemsize);
}
py::object result_backing_owner() const {
if (!owned_data_.empty()) {
return py::none();
}
PyObject* numpy = PyDict_GetItemString(PyImport_GetModuleDict(), "numpy");
py::object array_type = py::none();
if (numpy != nullptr) {
array_type = py::reinterpret_borrow<py::object>(numpy).attr("ndarray");
}
py::object source = buffer_;
while (source &&
((!array_type.is_none() && py::isinstance(source, array_type)) ||
py::isinstance<py::memoryview>(source))) {
source = !array_type.is_none() && py::isinstance(source, array_type)
? py::reinterpret_borrow<py::array>(source).base()
: source.attr("obj");
}
if (source && py::isinstance<PyExecuTorchResult>(source)) {
return source.cast<std::shared_ptr<PyExecuTorchResult>>()->backing_owner(
source);
}
return py::none();
}
private:
void check_rank() const {
if (info_.ndim < 0 ||
static_cast<size_t>(info_.ndim) > runtime::kTensorDimensionLimit) {
throw py::buffer_error("Buffer rank is too large for ExecuTorch");
}
}
void read_layout() {
scalar_type_ = scalar_type_from_buffer(info_);
sizes_.reserve(info_.shape.size());
strides_.reserve(info_.strides.size());
for (const auto size : info_.shape) {
sizes_.push_back(checked_int(size, "dimension"));
}
for (const auto byte_stride : info_.strides) {
if (byte_stride < 0 || byte_stride % info_.itemsize != 0) {
throw py::buffer_error(
"ExecuTorch inputs require non-negative, element-aligned strides");
}
strides_.push_back(checked_int(byte_stride / info_.itemsize, "stride"));
}
dim_order_.resize(sizes_.size());
std::iota(dim_order_.begin(), dim_order_.end(), 0);
std::stable_sort(
dim_order_.begin(), dim_order_.end(), [this](uint8_t a, uint8_t b) {
return strides_[a] > strides_[b];
});
if (!has_empty_dimension()) {
validate_dense_layout();
}
}
bool has_empty_dimension() const {
return std::find(sizes_.begin(), sizes_.end(), 0) != sizes_.end();
}
static int checked_int(py::ssize_t value, const char* name) {
if (value < 0 || value > std::numeric_limits<int>::max()) {
throw py::buffer_error(
std::string("Buffer ") + name + " is too large for ExecuTorch");
}
return static_cast<int>(value);
}
// PEP 3118 formats: an optional byte-order prefix, then a struct code. The
// code gives the kind of number and itemsize gives its width, which also
// covers platform-sized codes such as 'l' and 'n'. ctypes spells out the
// native byte order with a prefix.
static executorch::aten::ScalarType scalar_type_from_buffer(
const py::buffer_info& info) {
using executorch::aten::ScalarType;
const std::string& format = info.format;
const uint16_t one = 1;
const bool little_endian = *reinterpret_cast<const uint8_t*>(&one) == 1;
size_t code_offset = 0;
if (!format.empty() &&
std::string("@=<>!").find(format[0]) != std::string::npos) {
const bool native = format[0] == '@' || format[0] == '=' ||
(format[0] == '<' && little_endian) ||
(format[0] != '<' && !little_endian);
if (!native) {
throw py::buffer_error(
"Buffer format '" + format +
"' is not in this machine's byte order. Convert the data to the "
"native byte order before passing it.");
}
code_offset = 1;
}
const auto type_for_itemsize =
[&info](std::initializer_list<std::pair<int, ScalarType>> types)
-> std::optional<ScalarType> {
for (const auto& [itemsize, type] : types) {
if (info.itemsize == itemsize) {
return type;
}
}
return std::nullopt;
};
std::optional<ScalarType> type;
if (format.size() == code_offset + 1) {
switch (format[code_offset]) {
case '?':
type = type_for_itemsize({{1, ScalarType::Bool}});
break;
case 'b':
case 'h':
case 'i':
case 'l':
case 'q':
case 'n':
type = type_for_itemsize(
{{1, ScalarType::Char},
{2, ScalarType::Short},
{4, ScalarType::Int},
{8, ScalarType::Long}});
break;
case 'B':
case 'H':
case 'I':
case 'L':
case 'Q':
case 'N':
type = type_for_itemsize(
{{1, ScalarType::Byte},
{2, ScalarType::UInt16},
{4, ScalarType::UInt32},
{8, ScalarType::UInt64}});
break;
case 'e':
case 'f':
case 'd':
type = type_for_itemsize(
{{2, ScalarType::Half},
{4, ScalarType::Float},
{8, ScalarType::Double}});
break;
}
} else if (format.size() == code_offset + 2 && format[code_offset] == 'Z') {
if (format[code_offset + 1] == 'f' || format[code_offset + 1] == 'd') {
type = type_for_itemsize(
{{8, ScalarType::ComplexFloat}, {16, ScalarType::ComplexDouble}});
}
}
if (!type) {
throw py::buffer_error(
"Unsupported buffer format '" + format + "' with item size " +
std::to_string(info.itemsize) +
". Use a buffer of booleans, integers, floats, or complex numbers.");
}
return *type;
}
void validate_dense_layout() const {
int64_t expected_stride = 1;
for (size_t i = dim_order_.size(); i > 0; --i) {
const auto dim = dim_order_[i - 1];
const auto size = sizes_[dim];
if (size > 1 && strides_[dim] != expected_stride) {
throw py::buffer_error(
"ExecuTorch inputs must have a dense, non-overlapping layout");
}
expected_stride *= std::max(size, 1);
if (expected_stride > std::numeric_limits<int>::max()) {
throw py::buffer_error("Buffer is too large for ExecuTorch");
}
}
}
py::buffer buffer_;
py::buffer_info info_;
std::vector<uint8_t> owned_data_;
std::vector<int> sizes_;
std::vector<int> strides_;
std::vector<uint8_t> dim_order_;
executorch::aten::ScalarType scalar_type_;
};
bool is_torch_tensor(const py::handle& value) {
static PyObject* tensor_type = nullptr;
if (tensor_type == nullptr) {
PyObject* torch_module = loaded_torch_module();
if (torch_module == nullptr) {
return false;
}
tensor_type = PyObject_GetAttrString(torch_module, "Tensor");
if (tensor_type == nullptr) {
throw py::error_already_set();
}
}
const int result = PyObject_IsInstance(value.ptr(), tensor_type);
if (result < 0) {
throw py::error_already_set();
}
return result == 1;
}
// Runs `read`, which builds one input from a Python object, and names the
// input and its method in its errors, which the readers cannot see. A Python
// error keeps its exact type and gets the name as a note; the C++ errors
// caught below get it in their message. Others, such as std::bad_alloc, pass
// through unnamed, so pybind11 maps them to their own Python type.
template <typename Read>
auto read_input(const MethodMeta& method_meta, size_t index, Read&& read) {
const auto name = [&] {
return "Input " + std::to_string(index) + " of method '" +
method_meta.name() + "'";
};
const auto named = [&name](const char* message) {
return name() + ": " + message;
};
try {
return read();
} catch (py::error_already_set& error) {
// Rebuilding the exception as type(message) would fail for any exception
// whose constructor is not a single string.
if (error.value()) {
try {
error.value().attr("add_note")(name());
} catch (...) {
// add_note is best effort; never hide the original error.
}
}
throw;
} catch (const py::buffer_error& error) {
throw py::buffer_error(named(error.what()));
} catch (const py::value_error& error) {
throw py::value_error(named(error.what()));
} catch (const py::type_error& error) {
throw py::type_error(named(error.what()));
} catch (const std::invalid_argument& error) {
throw py::value_error(named(error.what()));
} catch (const std::runtime_error& error) {
throw std::runtime_error(named(error.what()));
}
}
void validate_tensor_input(
const MethodMeta& method_meta,
size_t index,
executorch::aten::ScalarType scalar_type,
const std::vector<int>& sizes) {
const auto input_meta = method_meta.input_tensor_meta(index);
THROW_IF_ERROR(
input_meta.error(),
"Input %zu of method '%s' is not a tensor input",
index,
method_meta.name());
const std::string input_name = "Input " + std::to_string(index) +
" of method '" + method_meta.name() + "'";
if (input_meta->scalar_type() != scalar_type) {
throw py::value_error(
input_name + " has dtype " +
std::string(runtime::toString(scalar_type)) +
" but the method expects " +
std::string(runtime::toString(input_meta->scalar_type())));
}
const auto expected_rank = input_meta->sizes().size();
if (expected_rank != sizes.size()) {
throw py::value_error(
input_name + " has rank " + std::to_string(sizes.size()) +
", but the method expects rank " + std::to_string(expected_rank));
}
}
void validate_buffer_input(
const MethodMeta& method_meta,
size_t index,
BufferTensor& buffer) {
const auto input_meta = method_meta.input_tensor_meta(index);
if (input_meta.ok()) {
buffer.use_layout(input_meta->dim_order());
}
validate_tensor_input(
method_meta, index, buffer.scalar_type(), buffer.sizes());
}
#ifndef USE_ATEN_LIB
void validate_input_device(
const Method& method,
size_t index,
executorch::aten::Device device,
size_t nbytes) {
if (nbytes == 0) {
return;
}
const auto expected = method.get_input(index).toTensor().device();
if (device != expected) {
const auto name = [](executorch::aten::Device value) {
return value.is_cpu() ? std::string("cpu")
: "cuda:" + std::to_string(value.index());
};
std::string message = "Input " + std::to_string(index) + " of method '" +
method.method_meta().name() + "' is on device " + name(device) +
", but the method expects " + name(expected);
if (device.is_cpu()) {
message +=
". Pass device memory instead, such as "
"ExecuTorchResult.from_host(...) or a CUDA tensor";
}
throw py::value_error(message);
}
}
/** A torch.Tensor input read through its public Python API, copied only to
* change its layout. */
class TorchTensorView final {
public:
TorchTensorView(const py::handle& value, size_t index)
: owner_(py::reinterpret_borrow<py::object>(value)), index_(index) {
if (owner_.attr("is_neg")().cast<bool>() ||
owner_.attr("is_conj")().cast<bool>()) {
throw py::value_error(
"Lazy conjugate and negative torch tensor views must be resolved before execution");
}
const auto numel = owner_.attr("numel")().cast<int64_t>();
const auto device_type =
py::str(owner_.attr("device").attr("type")).cast<std::string>();
if (device_type == "cuda") {
const auto index = owner_.attr("device").attr("index").cast<int>();
if (index < 0 ||
index > std::numeric_limits<runtime::etensor::DeviceIndex>::max()) {
throw py::value_error(
"Torch CUDA device index is too large for ExecuTorch");
}
device_ =
executorch::aten::Device(executorch::aten::DeviceType::CUDA, index);
} else if (device_type != "cpu" && numel != 0) {
throw std::runtime_error(
"Torch tensor is on device " + device_type +
", and only CPU and CUDA tensors can be passed to portable bindings.");
}
scalar_type_ = scalar_type_from_torch_dtype(
py::str(owner_.attr("dtype")).cast<std::string>());
nbytes_ = numel * runtime::elementSize(scalar_type_);
sizes_ = checked_vector(owner_.attr("shape"), "dimension");
strides_ = checked_vector(owner_.attr("stride")(), "stride");
if (sizes_.size() > runtime::kTensorDimensionLimit ||
sizes_.size() != strides_.size()) {
throw py::value_error("Invalid torch tensor metadata");
}
dim_order_.resize(sizes_.size());
std::iota(dim_order_.begin(), dim_order_.end(), 0);
std::stable_sort(
dim_order_.begin(), dim_order_.end(), [this](uint8_t a, uint8_t b) {
return strides_[a] > strides_[b];
});
if (numel != 0) {
validate_dense_layout();
}
const auto address =
numel == 0 ? 0 : owner_.attr("data_ptr")().cast<uintptr_t>();
if (address == 0 && numel != 0) {
throw py::value_error("Torch tensor data is not allocated");
}
data_ = reinterpret_cast<void*>(address);
}
size_t index() const {
return index_;
}
void* data() const {
return data_;
}
const std::vector<int>& sizes() const {
return sizes_;
}
const std::vector<int>& strides() const {
return strides_;
}
const std::vector<uint8_t>& dim_order() const {
return dim_order_;
}
executorch::aten::ScalarType scalar_type() const {
return scalar_type_;
}
size_t nbytes() const {
return nbytes_;
}
executorch::aten::Device device() const {
return device_;
}
const py::object& owner() const {
return owner_;
}
// Describes the tensor in the exported dimension order. A tensor dense in
// another order is first copied by torch into that order on its own device,
// since reading it with the exported strides would permute its values.
// owner() is then the copy.
void use_layout(Span<const uint8_t> dim_order) {
// The exported strides are computed as int. The input's own strides fit
// in int already, so only a conversion can need a larger one.
int64_t outer_stride = 1;
for (size_t i = 1; i < dim_order.size(); ++i) {
outer_stride *= std::max(sizes_[dim_order[i]], 1);
}
if (outer_stride > std::numeric_limits<int>::max()) {
throw py::value_error(
"Torch tensor is too large to convert to the exported layout");
}
std::vector<int> strides(sizes_.size());
const auto status = runtime::dim_order_to_stride(
sizes_.data(), dim_order.data(), sizes_.size(), strides.data());
THROW_IF_ERROR(status, "Invalid dimension order for torch tensor input");
if (nbytes_ != 0 && !has_layout(sizes_, strides_, dim_order)) {
// torch copies on its current stream, which may run before a write the
// producer queued on another stream, so wait for the device first.
if (device_.type() == executorch::aten::DeviceType::CUDA) {
synchronize_torch_cuda_device(device_.index());
}
owner_ = py::reinterpret_borrow<py::object>(loaded_torch_module())
.attr("empty_strided")(
sizes_,
strides,
py::arg("dtype") = owner_.attr("dtype"),
py::arg("device") = owner_.attr("device"))
.attr("copy_")(owner_);
data_ =
reinterpret_cast<void*>(owner_.attr("data_ptr")().cast<uintptr_t>());
}
strides_ = std::move(strides);
dim_order_.assign(dim_order.begin(), dim_order.end());
}
private:
static std::vector<int> checked_vector(
const py::handle& values,
const char* name) {
std::vector<int> result;
for (const auto value : py::reinterpret_borrow<py::iterable>(values)) {
const auto number = py::cast<int64_t>(value);
if (number < 0 || number > std::numeric_limits<int>::max()) {
throw py::value_error(
std::string("Torch tensor ") + name +
" is too large for ExecuTorch");
}
result.push_back(static_cast<int>(number));
}
return result;
}
void validate_dense_layout() const {
int64_t expected_stride = 1;
for (size_t i = dim_order_.size(); i > 0; --i) {
const auto dim = dim_order_[i - 1];
const auto size = sizes_[dim];
if (size > 1 && strides_[dim] != expected_stride) {
throw py::value_error(
"ExecuTorch inputs must have a dense, non-overlapping layout");
}
expected_stride *= std::max(size, 1);
}
}
py::object owner_;
size_t index_;
void* data_ = nullptr;
std::vector<int> sizes_;
std::vector<int> strides_;
std::vector<uint8_t> dim_order_;
executorch::aten::ScalarType scalar_type_;
size_t nbytes_;
executorch::aten::Device device_{executorch::aten::DeviceType::CPU};
};
#endif
class BorrowedInput final {
public:
BorrowedInput(size_t index, const py::handle& torch_tensor)
: index_(index),
torch_tensor_(py::reinterpret_borrow<py::object>(torch_tensor)) {
std::tie(data_, nbytes_) = torch_storage();
}
BorrowedInput(size_t index, std::shared_ptr<BufferTensor> buffer)
: index_(index),
buffer_(std::move(buffer)),
data_(buffer_->data()),
nbytes_(buffer_->nbytes()) {}
void validate(const char* method_name) const {
const auto [current_data, current_nbytes] =
buffer_ ? buffer_->current_storage() : torch_storage();
if (current_data != data_ || current_nbytes != nbytes_) {
throw py::value_error(
"Input " + std::to_string(index_) + " of method '" + method_name +
"': its storage changed after it was passed in; pass it again");
}
}
private:
std::pair<const void*, size_t> torch_storage() const {
const auto numel = torch_tensor_.attr("numel")().cast<size_t>();
const auto address =
numel == 0 ? 0 : torch_tensor_.attr("data_ptr")().cast<uintptr_t>();
const auto element_size =
torch_tensor_.attr("element_size")().cast<size_t>();
return {reinterpret_cast<const void*>(address), numel * element_size};
}
size_t index_;
py::object torch_tensor_;
std::shared_ptr<BufferTensor> buffer_;
const void* data_;
size_t nbytes_;
};
#ifndef USE_ATEN_LIB