ZTWHHH commited on
Commit
dcaecbc
·
verified ·
1 Parent(s): e3665ef

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/__init__.cpython-310.pyc +0 -0
  2. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/graph_matcher.cpython-310.pyc +0 -0
  3. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/mappings.cpython-310.pyc +0 -0
  4. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/n_shadows_utils.cpython-310.pyc +0 -0
  5. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/ns_types.cpython-310.pyc +0 -0
  6. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/pattern_utils.cpython-310.pyc +0 -0
  7. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/qconfig_multi_mapping.cpython-310.pyc +0 -0
  8. videollama2/lib/python3.10/site-packages/torch/include/c10/core/Allocator.h +277 -0
  9. videollama2/lib/python3.10/site-packages/torch/include/c10/core/Backend.h +350 -0
  10. videollama2/lib/python3.10/site-packages/torch/include/c10/core/CPUAllocator.h +57 -0
  11. videollama2/lib/python3.10/site-packages/torch/include/c10/core/CompileTimeFunctionPointer.h +56 -0
  12. videollama2/lib/python3.10/site-packages/torch/include/c10/core/Contiguity.h +126 -0
  13. videollama2/lib/python3.10/site-packages/torch/include/c10/core/DeviceType.h +117 -0
  14. videollama2/lib/python3.10/site-packages/torch/include/c10/core/DispatchKey.h +732 -0
  15. videollama2/lib/python3.10/site-packages/torch/include/c10/core/DispatchKeySet.h +928 -0
  16. videollama2/lib/python3.10/site-packages/torch/include/c10/core/MemoryFormat.h +287 -0
  17. videollama2/lib/python3.10/site-packages/torch/include/c10/core/QEngine.h +46 -0
  18. videollama2/lib/python3.10/site-packages/torch/include/c10/core/Scalar.h +383 -0
  19. videollama2/lib/python3.10/site-packages/torch/include/c10/core/SingletonSymNodeImpl.h +176 -0
  20. videollama2/lib/python3.10/site-packages/torch/include/c10/core/StorageImpl.h +237 -0
  21. videollama2/lib/python3.10/site-packages/torch/include/c10/core/SymBool.h +88 -0
  22. videollama2/lib/python3.10/site-packages/torch/include/c10/core/SymFloat.h +109 -0
  23. videollama2/lib/python3.10/site-packages/torch/include/c10/core/SymInt.h +362 -0
  24. videollama2/lib/python3.10/site-packages/torch/include/c10/core/SymIntArrayRef.h +71 -0
  25. videollama2/lib/python3.10/site-packages/torch/include/c10/core/SymNodeImpl.h +207 -0
  26. videollama2/lib/python3.10/site-packages/torch/include/c10/core/TensorOptions.h +773 -0
  27. videollama2/lib/python3.10/site-packages/torch/include/c10/macros/Export.h +154 -0
  28. videollama2/lib/python3.10/site-packages/torch/include/c10/macros/Macros.h +558 -0
  29. videollama2/lib/python3.10/site-packages/torch/include/c10/macros/cmake_macros.h +14 -0
  30. videollama2/lib/python3.10/site-packages/torch/include/clog.h +100 -0
  31. videollama2/lib/python3.10/site-packages/torch/include/cpuinfo.h +1939 -0
  32. videollama2/lib/python3.10/site-packages/torch/include/dnnl.h +22 -0
  33. videollama2/lib/python3.10/site-packages/torch/include/dnnl_config.h +22 -0
  34. videollama2/lib/python3.10/site-packages/torch/include/dnnl_debug.h +22 -0
  35. videollama2/lib/python3.10/site-packages/torch/include/dnnl_ocl.h +22 -0
  36. videollama2/lib/python3.10/site-packages/torch/include/dnnl_sycl.h +22 -0
  37. videollama2/lib/python3.10/site-packages/torch/include/dnnl_sycl_types.h +22 -0
  38. videollama2/lib/python3.10/site-packages/torch/include/fxdiv.h +425 -0
  39. videollama2/lib/python3.10/site-packages/torch/include/nnpack.h +659 -0
  40. videollama2/lib/python3.10/site-packages/torch/include/pthreadpool.h +0 -0
  41. videollama2/lib/python3.10/site-packages/torch/include/qnnpack_func.h +166 -0
  42. videollama2/lib/python3.10/site-packages/torch/include/sleef.h +0 -0
  43. videollama2/lib/python3.10/site-packages/torch/include/xnnpack.h +0 -0
  44. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/array.h +49 -0
  45. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/buffer.h +587 -0
  46. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/buffer_builder.h +484 -0
  47. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/chunk_resolver.h +290 -0
  48. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/compare.h +145 -0
  49. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/config.h +98 -0
  50. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/csv/converter.h +82 -0
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (171 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/graph_matcher.cpython-310.pyc ADDED
Binary file (12.1 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/mappings.cpython-310.pyc ADDED
Binary file (9.97 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/n_shadows_utils.cpython-310.pyc ADDED
Binary file (24.1 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/ns_types.cpython-310.pyc ADDED
Binary file (977 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/pattern_utils.cpython-310.pyc ADDED
Binary file (4.03 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/qconfig_multi_mapping.cpython-310.pyc ADDED
Binary file (7.24 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/include/c10/core/Allocator.h ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <stddef.h>
4
+ #include <memory>
5
+
6
+ #include <c10/core/Device.h>
7
+ #include <c10/util/Exception.h>
8
+ #include <c10/util/ThreadLocalDebugInfo.h>
9
+ #include <c10/util/UniqueVoidPtr.h>
10
+
11
+ namespace c10 {
12
+
13
+ // A DataPtr is a unique pointer (with an attached deleter and some
14
+ // context for the deleter) to some memory, which also records what
15
+ // device is for its data.
16
+ //
17
+ // nullptr DataPtrs can still have a nontrivial device; this allows
18
+ // us to treat zero-size allocations uniformly with non-zero allocations.
19
+ //
20
+ class C10_API DataPtr {
21
+ private:
22
+ c10::detail::UniqueVoidPtr ptr_;
23
+ Device device_;
24
+
25
+ public:
26
+ // Choice of CPU here is arbitrary; if there's an "undefined" device
27
+ // we could use that too
28
+ DataPtr() : ptr_(), device_(DeviceType::CPU) {}
29
+ DataPtr(void* data, Device device) : ptr_(data), device_(device) {}
30
+ DataPtr(void* data, void* ctx, DeleterFnPtr ctx_deleter, Device device)
31
+ : ptr_(data, ctx, ctx_deleter), device_(device) {}
32
+ void* operator->() const {
33
+ return ptr_.get();
34
+ }
35
+ void clear() {
36
+ ptr_.clear();
37
+ }
38
+ void* get() const {
39
+ return ptr_.get();
40
+ }
41
+ void* mutable_get() {
42
+ return ptr_.get();
43
+ }
44
+ void* get_context() const {
45
+ return ptr_.get_context();
46
+ }
47
+ void* release_context() {
48
+ return ptr_.release_context();
49
+ }
50
+ std::unique_ptr<void, DeleterFnPtr>&& move_context() {
51
+ return ptr_.move_context();
52
+ }
53
+ operator bool() const {
54
+ return static_cast<bool>(ptr_);
55
+ }
56
+ template <typename T>
57
+ T* cast_context(DeleterFnPtr expected_deleter) const {
58
+ return ptr_.cast_context<T>(expected_deleter);
59
+ }
60
+ DeleterFnPtr get_deleter() const {
61
+ return ptr_.get_deleter();
62
+ }
63
+ /**
64
+ * Compare the deleter in a DataPtr to expected_deleter.
65
+ * If it matches, replace the deleter with new_deleter
66
+ * and return true; otherwise, does nothing and returns
67
+ * false.
68
+ *
69
+ * In general, it is not safe to unconditionally set the
70
+ * deleter on a DataPtr, because you don't know what
71
+ * the deleter is, and thus will have a hard time properly
72
+ * disposing of the deleter without storing the original
73
+ * deleter (this is difficult to do, because DeleterFnPtr
74
+ * is not a closure, and because the context on DataPtr is
75
+ * only a single word, you generally don't have enough
76
+ * space to store both the original deleter and its context).
77
+ * However, in some cases, you know /exactly/ what the deleter
78
+ * is, and you have a new deleter that manually wraps
79
+ * the old one. In this case, you can safely swap the deleter
80
+ * after asserting that the deleters line up.
81
+ *
82
+ * What are the requirements on new_deleter? It must still
83
+ * properly dispose of the void* pointer passed in as its argument,
84
+ * where void* is whatever the context of the original deleter
85
+ * is. So in general, you expect the new deleter to look something
86
+ * like this:
87
+ *
88
+ * [](void* ptr) {
89
+ * some_new_stuff(ptr);
90
+ * get_orig_allocator()->raw_deleter(ptr);
91
+ * }
92
+ *
93
+ * Note that it won't work to close over the original
94
+ * allocator; you don't have enough space to do that! Also,
95
+ * it's unsafe to assume that the passed in pointer in
96
+ * question is the memory pointer in question; it might not
97
+ * be; be sure to read the source code of the Allocator
98
+ * in question to confirm this.
99
+ */
100
+ C10_NODISCARD bool compare_exchange_deleter(
101
+ DeleterFnPtr expected_deleter,
102
+ DeleterFnPtr new_deleter) {
103
+ return ptr_.compare_exchange_deleter(expected_deleter, new_deleter);
104
+ }
105
+ Device device() const {
106
+ return device_;
107
+ }
108
+ // Unsafely mutates the device on a DataPtr. Under normal use,
109
+ // you should never actually need to call this function.
110
+ // We need this for the implementation of the hack detailed
111
+ // in Note [Masquerading as CUDA]
112
+ void unsafe_set_device(Device device) {
113
+ device_ = device;
114
+ }
115
+ };
116
+
117
+ // NB: Device is NOT tested for here; a CUDA nullptr is as much a nullptr as a
118
+ // CPU nullptr
119
+
120
+ inline bool operator==(const DataPtr& dp, std::nullptr_t) noexcept {
121
+ return !dp;
122
+ }
123
+ inline bool operator==(std::nullptr_t, const DataPtr& dp) noexcept {
124
+ return !dp;
125
+ }
126
+ inline bool operator!=(const DataPtr& dp, std::nullptr_t) noexcept {
127
+ return dp;
128
+ }
129
+ inline bool operator!=(std::nullptr_t, const DataPtr& dp) noexcept {
130
+ return dp;
131
+ }
132
+
133
+ // Note [raw_allocate/raw_deallocate and Thrust]
134
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
135
+ // Thrust's support for custom allocators requires us to write something
136
+ // like this:
137
+ //
138
+ // class ThrustAllocator {
139
+ // char* allocate(size_t);
140
+ // void deallocate(char*, size_t);
141
+ // };
142
+ //
143
+ // This is not good for our unique_ptr based allocator interface, as
144
+ // there is no way to get to the context when we free.
145
+ //
146
+ // However, in some cases the context is exactly the same as
147
+ // the data pointer. In this case, we can support the "raw"
148
+ // allocate and deallocate interface. This is what
149
+ // raw_deleter signifies. By default, it returns a nullptr, which means that
150
+ // the raw interface is not implemented. Be sure to implement it whenever
151
+ // possible, or the raw interface will incorrectly reported as unsupported,
152
+ // when it is actually possible.
153
+
154
+ struct C10_API Allocator {
155
+ virtual ~Allocator() = default;
156
+
157
+ virtual DataPtr allocate(size_t n) const = 0;
158
+
159
+ // If this returns a non nullptr, it means that allocate()
160
+ // is guaranteed to return a unique_ptr with this deleter attached;
161
+ // it means the rawAllocate and rawDeallocate APIs are safe to use.
162
+ // This function MUST always return the same BoundDeleter.
163
+ virtual DeleterFnPtr raw_deleter() const {
164
+ return nullptr;
165
+ }
166
+ void* raw_allocate(size_t n) {
167
+ auto dptr = allocate(n);
168
+ AT_ASSERT(dptr.get() == dptr.get_context());
169
+ return dptr.release_context();
170
+ }
171
+ void raw_deallocate(void* ptr) {
172
+ auto d = raw_deleter();
173
+ AT_ASSERT(d);
174
+ d(ptr);
175
+ }
176
+ };
177
+
178
+ // This context is used to generate DataPtr which have arbitrary
179
+ // std::function deleters associated with them. In some user facing
180
+ // functions, we give a (user-friendly) interface for constructing
181
+ // tensors from external data which take an arbitrary std::function
182
+ // deleter. Grep for InefficientStdFunctionContext to find these
183
+ // occurrences.
184
+ //
185
+ // This context is inefficient because we have to do a dynamic
186
+ // allocation InefficientStdFunctionContext, on top of the dynamic
187
+ // allocation which is implied by std::function itself.
188
+ struct C10_API InefficientStdFunctionContext {
189
+ std::unique_ptr<void, std::function<void(void*)>> ptr_;
190
+ InefficientStdFunctionContext(
191
+ std::unique_ptr<void, std::function<void(void*)>>&& ptr)
192
+ : ptr_(std::move(ptr)) {}
193
+ static DataPtr makeDataPtr(
194
+ void* ptr,
195
+ const std::function<void(void*)>& deleter,
196
+ Device device);
197
+ };
198
+
199
+ /** Set the allocator for DeviceType `t`. The passed in allocator pointer is
200
+ * expected to have static lifetime; this function does NOT take ownership
201
+ * of the raw pointer. (The reason for this is to prevent existing pointers
202
+ * to an allocator of a particular device from being invalidated when
203
+ * SetAllocator is called.)
204
+ *
205
+ * Also note that this is not thread-safe, and we assume this function will
206
+ * only be called during initialization.
207
+ *
208
+ * The 'priority' flag is introduced when we want to overwrite the default
209
+ * allocator, since the allocators are set statically. The default priority
210
+ * is 0, which means the lowest. Only higher or equal priority can overwrite
211
+ * existing ones.
212
+ */
213
+ C10_API void SetAllocator(DeviceType t, Allocator* alloc, uint8_t priority = 0);
214
+ C10_API Allocator* GetAllocator(const DeviceType& t);
215
+
216
+ template <DeviceType t>
217
+ struct AllocatorRegisterer {
218
+ explicit AllocatorRegisterer(Allocator* alloc) {
219
+ SetAllocator(t, alloc);
220
+ }
221
+ };
222
+
223
+ #define REGISTER_ALLOCATOR(t, f) \
224
+ namespace { \
225
+ static c10::AllocatorRegisterer<t> g_allocator_d(f); \
226
+ }
227
+
228
+ // An interface for reporting thread local memory usage
229
+ // per device
230
+ struct C10_API MemoryReportingInfoBase : public c10::DebugInfoBase {
231
+ MemoryReportingInfoBase();
232
+ ~MemoryReportingInfoBase() override = default;
233
+
234
+ /**
235
+ * alloc_size corresponds to the size of the ptr.
236
+ *
237
+ * total_allocated corresponds to total allocated memory.
238
+ *
239
+ * total_reserved corresponds to total size of memory pool, both used and
240
+ * unused, if applicable.
241
+ */
242
+ virtual void reportMemoryUsage(
243
+ void* ptr,
244
+ int64_t alloc_size,
245
+ size_t total_allocated,
246
+ size_t total_reserved,
247
+ Device device) = 0;
248
+
249
+ virtual void reportOutOfMemory(
250
+ int64_t alloc_size,
251
+ size_t total_allocated,
252
+ size_t total_reserved,
253
+ Device device);
254
+
255
+ virtual bool memoryProfilingEnabled() const = 0;
256
+ };
257
+
258
+ C10_API bool memoryProfilingEnabled();
259
+ C10_API void reportMemoryUsageToProfiler(
260
+ void* ptr,
261
+ int64_t alloc_size,
262
+ size_t total_allocated,
263
+ size_t total_reserved,
264
+ Device device);
265
+
266
+ C10_API void reportOutOfMemoryToProfiler(
267
+ int64_t alloc_size,
268
+ size_t total_allocated,
269
+ size_t total_reserved,
270
+ Device device);
271
+
272
+ // used to hold traceback information in allocators
273
+ struct GatheredContext {
274
+ virtual ~GatheredContext() = default;
275
+ };
276
+
277
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/Backend.h ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/DeviceType.h>
4
+ #include <c10/core/DispatchKey.h>
5
+ #include <c10/core/DispatchKeySet.h>
6
+ #include <c10/util/Exception.h>
7
+
8
+ #include <stdexcept>
9
+
10
+ namespace c10 {
11
+
12
+ /**
13
+ * This legacy enum class defines the set of backends supported by old school,
14
+ * code generated Type-based ATen. A "backend" in this sense roughly
15
+ * corresponds to the cartesian product of (device type, layout), but restricted
16
+ * only to combinations which we actually have kernels for. Backend does NOT
17
+ * include dtype.
18
+ *
19
+ * The reason we are sunsetting this enum class is because it doesn't allow for
20
+ * open registration; e.g., if you want to add SparseXLA, you'd have to
21
+ * edit this enum; you wouldn't be able to do it out of tree. DispatchKey is
22
+ * the replacement for Backend which supports open registration.
23
+ *
24
+ * NB: The concept of 'Backend' here disagrees with the notion of backend
25
+ * exposed to users in torch.backends. Backend here is something like "CPU"
26
+ * or "SparseCUDA"; backend in torch.backends is something like "MKL" or
27
+ * "CUDNN".
28
+ */
29
+ enum class Backend {
30
+ CPU,
31
+ CUDA,
32
+ HIP,
33
+ VE,
34
+ FPGA,
35
+ IPU,
36
+ XPU,
37
+ SparseCPU,
38
+ SparseCUDA,
39
+ SparseCsrCPU,
40
+ SparseCsrCUDA,
41
+ SparseHIP,
42
+ SparseVE,
43
+ SparseXPU,
44
+ SparsePrivateUse1,
45
+ ORT,
46
+ XLA,
47
+ Vulkan,
48
+ Metal,
49
+ Meta,
50
+ QuantizedCPU,
51
+ QuantizedCUDA,
52
+ QuantizedXPU,
53
+ QuantizedPrivateUse1,
54
+ Undefined,
55
+ MkldnnCPU,
56
+ MPS,
57
+ HPU,
58
+ Lazy,
59
+ MTIA,
60
+ PrivateUse1,
61
+ NumOptions
62
+ };
63
+
64
+ static inline Backend dispatchKeyToBackend(DispatchKey t) {
65
+ if (t == DispatchKey::CPU || t == DispatchKey::AutogradCPU) {
66
+ return Backend::CPU;
67
+ } else if (t == DispatchKey::CUDA || t == DispatchKey::AutogradCUDA) {
68
+ return Backend::CUDA;
69
+ } else if (t == DispatchKey::HIP) {
70
+ return Backend::HIP;
71
+ } else if (t == DispatchKey::VE) {
72
+ return Backend::VE;
73
+ } else if (t == DispatchKey::FPGA) {
74
+ return Backend::FPGA;
75
+ } else if (t == DispatchKey::ORT) {
76
+ return Backend::ORT;
77
+ } else if (t == DispatchKey::XLA || t == DispatchKey::AutogradXLA) {
78
+ return Backend::XLA;
79
+ } else if (t == DispatchKey::Lazy || t == DispatchKey::AutogradLazy) {
80
+ return Backend::Lazy;
81
+ } else if (t == DispatchKey::MPS || t == DispatchKey::AutogradMPS) {
82
+ return Backend::MPS;
83
+ } else if (t == DispatchKey::Vulkan) {
84
+ return Backend::Vulkan;
85
+ } else if (t == DispatchKey::Metal) {
86
+ return Backend::Metal;
87
+ } else if (t == DispatchKey::Meta) {
88
+ return Backend::Meta;
89
+ } else if (t == DispatchKey::SparseCPU) {
90
+ return Backend::SparseCPU;
91
+ } else if (t == DispatchKey::SparseCUDA) {
92
+ return Backend::SparseCUDA;
93
+ } else if (t == DispatchKey::SparseHIP) {
94
+ return Backend::SparseHIP;
95
+ } else if (t == DispatchKey::SparseVE) {
96
+ return Backend::SparseVE;
97
+ } else if (t == DispatchKey::SparsePrivateUse1) {
98
+ return Backend::SparsePrivateUse1;
99
+ } else if (t == DispatchKey::SparseCsrCPU) {
100
+ return Backend::SparseCsrCPU;
101
+ } else if (t == DispatchKey::SparseCsrCUDA) {
102
+ return Backend::SparseCsrCUDA;
103
+ } else if (t == DispatchKey::MkldnnCPU) {
104
+ return Backend::MkldnnCPU;
105
+ } else if (t == DispatchKey::QuantizedCPU) {
106
+ return Backend::QuantizedCPU;
107
+ } else if (t == DispatchKey::QuantizedCUDA) {
108
+ return Backend::QuantizedCUDA;
109
+ } else if (t == DispatchKey::IPU || t == DispatchKey::AutogradIPU) {
110
+ return Backend::IPU;
111
+ } else if (t == DispatchKey::XPU || t == DispatchKey::AutogradXPU) {
112
+ return Backend::XPU;
113
+ } else if (t == DispatchKey::SparseXPU) {
114
+ return Backend::SparseXPU;
115
+ } else if (t == DispatchKey::QuantizedXPU) {
116
+ return Backend::QuantizedXPU;
117
+ } else if (t == DispatchKey::QuantizedPrivateUse1) {
118
+ return Backend::QuantizedPrivateUse1;
119
+ } else if (t == DispatchKey::HPU || t == DispatchKey::AutogradHPU) {
120
+ return Backend::HPU;
121
+ } else if (t == DispatchKey::MTIA || t == DispatchKey::AutogradMTIA) {
122
+ return Backend::MTIA;
123
+ } else if (
124
+ t == DispatchKey::PrivateUse1 || t == DispatchKey::AutogradPrivateUse1) {
125
+ return Backend::PrivateUse1;
126
+ } else if (t == DispatchKey::Undefined) {
127
+ return Backend::Undefined;
128
+ } else {
129
+ TORCH_CHECK(false, "Unrecognized tensor type ID: ", t);
130
+ }
131
+ }
132
+
133
+ static inline DispatchKey backendToDispatchKey(Backend b) {
134
+ switch (b) {
135
+ case Backend::CPU:
136
+ return DispatchKey::CPU;
137
+ case Backend::CUDA:
138
+ return DispatchKey::CUDA;
139
+ case Backend::HIP:
140
+ return DispatchKey::HIP;
141
+ case Backend::VE:
142
+ return DispatchKey::VE;
143
+ case Backend::FPGA:
144
+ return DispatchKey::FPGA;
145
+ case Backend::ORT:
146
+ return DispatchKey::ORT;
147
+ case Backend::XLA:
148
+ return DispatchKey::XLA;
149
+ case Backend::Lazy:
150
+ return DispatchKey::Lazy;
151
+ case Backend::IPU:
152
+ return DispatchKey::IPU;
153
+ case Backend::XPU:
154
+ return DispatchKey::XPU;
155
+ case Backend::SparseXPU:
156
+ return DispatchKey::SparseXPU;
157
+ case Backend::SparseCPU:
158
+ return DispatchKey::SparseCPU;
159
+ case Backend::SparseCUDA:
160
+ return DispatchKey::SparseCUDA;
161
+ case Backend::SparseHIP:
162
+ return DispatchKey::SparseHIP;
163
+ case Backend::SparseVE:
164
+ return DispatchKey::SparseVE;
165
+ case Backend::SparsePrivateUse1:
166
+ return DispatchKey::SparsePrivateUse1;
167
+ case Backend::SparseCsrCPU:
168
+ return DispatchKey::SparseCsrCPU;
169
+ case Backend::SparseCsrCUDA:
170
+ return DispatchKey::SparseCsrCUDA;
171
+ case Backend::MkldnnCPU:
172
+ return DispatchKey::MkldnnCPU;
173
+ case Backend::Vulkan:
174
+ return DispatchKey::Vulkan;
175
+ case Backend::Metal:
176
+ return DispatchKey::Metal;
177
+ case Backend::Meta:
178
+ return DispatchKey::Meta;
179
+ case Backend::QuantizedCPU:
180
+ return DispatchKey::QuantizedCPU;
181
+ case Backend::QuantizedCUDA:
182
+ return DispatchKey::QuantizedCUDA;
183
+ case Backend::QuantizedPrivateUse1:
184
+ return DispatchKey::QuantizedPrivateUse1;
185
+ case Backend::Undefined:
186
+ return DispatchKey::Undefined;
187
+ case Backend::MPS:
188
+ return DispatchKey::MPS;
189
+ case Backend::HPU:
190
+ return DispatchKey::HPU;
191
+ case Backend::MTIA:
192
+ return DispatchKey::MTIA;
193
+ case Backend::PrivateUse1:
194
+ return DispatchKey::PrivateUse1;
195
+ default:
196
+ throw std::runtime_error("Unknown backend");
197
+ }
198
+ }
199
+
200
+ static inline DeviceType backendToDeviceType(Backend b) {
201
+ switch (b) {
202
+ case Backend::CPU:
203
+ case Backend::MkldnnCPU:
204
+ case Backend::SparseCPU:
205
+ case Backend::SparseCsrCPU:
206
+ case Backend::QuantizedCPU:
207
+ return DeviceType::CPU;
208
+ case Backend::CUDA:
209
+ case Backend::SparseCUDA:
210
+ case Backend::QuantizedCUDA:
211
+ case Backend::SparseCsrCUDA:
212
+ return DeviceType::CUDA;
213
+ case Backend::HIP:
214
+ return DeviceType::HIP;
215
+ case Backend::VE:
216
+ return DeviceType::VE;
217
+ case Backend::FPGA:
218
+ return DeviceType::FPGA;
219
+ case Backend::ORT:
220
+ return DeviceType::ORT;
221
+ case Backend::XLA:
222
+ return DeviceType::XLA;
223
+ case Backend::Lazy:
224
+ return DeviceType::Lazy;
225
+ case Backend::SparseHIP:
226
+ return DeviceType::HIP;
227
+ case Backend::SparseVE:
228
+ return DeviceType::VE;
229
+ case Backend::IPU:
230
+ return DeviceType::IPU;
231
+ case Backend::XPU:
232
+ case Backend::SparseXPU:
233
+ case Backend::QuantizedXPU:
234
+ return DeviceType::XPU;
235
+ case Backend::Vulkan:
236
+ return DeviceType::Vulkan;
237
+ case Backend::Metal:
238
+ return DeviceType::Metal;
239
+ case Backend::Meta:
240
+ return DeviceType::Meta;
241
+ case Backend::MPS:
242
+ return DeviceType::MPS;
243
+ case Backend::HPU:
244
+ return DeviceType::HPU;
245
+ case Backend::MTIA:
246
+ return DeviceType::MTIA;
247
+ case Backend::PrivateUse1:
248
+ case Backend::SparsePrivateUse1:
249
+ case Backend::QuantizedPrivateUse1:
250
+ return DeviceType::PrivateUse1;
251
+ case Backend::Undefined:
252
+ TORCH_CHECK(false, "Undefined backend is not a valid device type");
253
+ default:
254
+ TORCH_CHECK(false, "Unknown backend");
255
+ }
256
+ }
257
+
258
+ // TODO: This probably shouldn't actually be static inline
259
+ static inline const char* toString(Backend b) {
260
+ switch (b) {
261
+ case Backend::CPU:
262
+ return "CPU";
263
+ case Backend::CUDA:
264
+ return "CUDA";
265
+ case Backend::HIP:
266
+ return "HIP";
267
+ case Backend::VE:
268
+ return "VE";
269
+ case Backend::FPGA:
270
+ return "FPGA";
271
+ case Backend::XPU:
272
+ return "XPU";
273
+ case Backend::IPU:
274
+ return "IPU";
275
+ case Backend::ORT:
276
+ return "ORT";
277
+ case Backend::XLA:
278
+ return "XLA";
279
+ case Backend::Lazy:
280
+ return "Lazy";
281
+ case Backend::MPS:
282
+ return "MPS";
283
+ case Backend::SparseCPU:
284
+ return "SparseCPU";
285
+ case Backend::SparseCUDA:
286
+ return "SparseCUDA";
287
+ case Backend::SparseHIP:
288
+ return "SparseHIP";
289
+ case Backend::SparseVE:
290
+ return "SparseVE";
291
+ case Backend::SparseXPU:
292
+ return "SparseXPU";
293
+ case Backend::SparsePrivateUse1:
294
+ return "SparsePrivateUse1";
295
+ case Backend::SparseCsrCPU:
296
+ return "SparseCsrCPU";
297
+ case Backend::SparseCsrCUDA:
298
+ return "SparseCsrCUDA";
299
+ case Backend::MkldnnCPU:
300
+ return "MkldnnCPU";
301
+ case Backend::Vulkan:
302
+ return "Vulkan";
303
+ case Backend::Metal:
304
+ return "Metal";
305
+ case Backend::Meta:
306
+ return "Meta";
307
+ case Backend::QuantizedCPU:
308
+ return "QuantizedCPU";
309
+ case Backend::QuantizedCUDA:
310
+ return "QuantizedCUDA";
311
+ case Backend::QuantizedXPU:
312
+ return "QuantizedXPU";
313
+ case Backend::QuantizedPrivateUse1:
314
+ return "QuantizedPrivateUse1";
315
+ case Backend::HPU:
316
+ return "HPU";
317
+ case Backend::MTIA:
318
+ return "MTIA";
319
+ case Backend::PrivateUse1:
320
+ return "PrivateUseOne";
321
+ default:
322
+ return "UNKNOWN_BACKEND";
323
+ }
324
+ }
325
+
326
+ static inline bool isSparse(Backend b) {
327
+ switch (b) {
328
+ case Backend::SparseXPU:
329
+ case Backend::SparseCPU:
330
+ case Backend::SparseCUDA:
331
+ case Backend::SparseHIP:
332
+ case Backend::SparseVE:
333
+ case Backend::SparsePrivateUse1:
334
+ return true;
335
+ default:
336
+ return false;
337
+ }
338
+ }
339
+
340
+ static inline bool isSparseCsr(Backend b) {
341
+ switch (b) {
342
+ case Backend::SparseCsrCPU:
343
+ case Backend::SparseCsrCUDA:
344
+ return true;
345
+ default:
346
+ return false;
347
+ }
348
+ }
349
+
350
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/CPUAllocator.h ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstring>
4
+ #include <mutex>
5
+ #include <unordered_map>
6
+
7
+ #include <c10/core/Allocator.h>
8
+ #include <c10/util/Flags.h>
9
+
10
+ // TODO: rename to c10
11
+ C10_DECLARE_bool(caffe2_report_cpu_memory_usage);
12
+
13
+ namespace c10 {
14
+
15
+ using MemoryDeleter = void (*)(void*);
16
+
17
+ // A helper function that is basically doing nothing.
18
+ C10_API void NoDelete(void*);
19
+
20
+ // A simple struct that is used to report C10's memory allocation,
21
+ // deallocation status and out-of-memory events to the profiler
22
+ class C10_API ProfiledCPUMemoryReporter {
23
+ public:
24
+ ProfiledCPUMemoryReporter() = default;
25
+ void New(void* ptr, size_t nbytes);
26
+ void OutOfMemory(size_t nbytes);
27
+ void Delete(void* ptr);
28
+
29
+ private:
30
+ std::mutex mutex_;
31
+ std::unordered_map<void*, size_t> size_table_;
32
+ size_t allocated_ = 0;
33
+ size_t log_cnt_ = 0;
34
+ };
35
+
36
+ C10_API ProfiledCPUMemoryReporter& profiledCPUMemoryReporter();
37
+
38
+ // Get the CPU Allocator.
39
+ C10_API at::Allocator* GetCPUAllocator();
40
+ // Sets the CPU allocator to the given allocator: the caller gives away the
41
+ // ownership of the pointer.
42
+ C10_API void SetCPUAllocator(at::Allocator* alloc, uint8_t priority = 0);
43
+
44
+ // Get the Default CPU Allocator
45
+ C10_API at::Allocator* GetDefaultCPUAllocator();
46
+
47
+ // Get the Default Mobile CPU Allocator
48
+ C10_API at::Allocator* GetDefaultMobileCPUAllocator();
49
+
50
+ // The CPUCachingAllocator is experimental and might disappear in the future.
51
+ // The only place that uses it is in StaticRuntime.
52
+ // Set the CPU Caching Allocator
53
+ C10_API void SetCPUCachingAllocator(Allocator* alloc, uint8_t priority = 0);
54
+ // Get the CPU Caching Allocator
55
+ C10_API Allocator* GetCPUCachingAllocator();
56
+
57
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/CompileTimeFunctionPointer.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/util/TypeTraits.h>
4
+
5
+ namespace c10 {
6
+
7
+ /**
8
+ * Represent a function pointer as a C++ type.
9
+ * This allows using the function pointer as a type
10
+ * in a template and calling it from inside the template
11
+ * allows the compiler to inline the call because it
12
+ * knows the function pointer at compile time.
13
+ *
14
+ * Example 1:
15
+ * int add(int a, int b) {return a + b;}
16
+ * using Add = TORCH_FN_TYPE(add);
17
+ * template<class Func> struct Executor {
18
+ * int execute(int a, int b) {
19
+ * return Func::func_ptr()(a, b);
20
+ * }
21
+ * };
22
+ * Executor<Add> executor;
23
+ * EXPECT_EQ(3, executor.execute(1, 2));
24
+ *
25
+ * Example 2:
26
+ * int add(int a, int b) {return a + b;}
27
+ * template<class Func> int execute(Func, int a, int b) {
28
+ * return Func::func_ptr()(a, b);
29
+ * }
30
+ * EXPECT_EQ(3, execute(TORCH_FN(add), 1, 2));
31
+ */
32
+ template <class FuncType_, FuncType_* func_ptr_>
33
+ struct CompileTimeFunctionPointer final {
34
+ static_assert(
35
+ guts::is_function_type<FuncType_>::value,
36
+ "TORCH_FN can only wrap function types.");
37
+ using FuncType = FuncType_;
38
+
39
+ static constexpr FuncType* func_ptr() {
40
+ return func_ptr_;
41
+ }
42
+ };
43
+
44
+ template <class T>
45
+ struct is_compile_time_function_pointer : std::false_type {};
46
+ template <class FuncType, FuncType* func_ptr>
47
+ struct is_compile_time_function_pointer<
48
+ CompileTimeFunctionPointer<FuncType, func_ptr>> : std::true_type {};
49
+
50
+ } // namespace c10
51
+
52
+ #define TORCH_FN_TYPE(func) \
53
+ ::c10::CompileTimeFunctionPointer< \
54
+ std::remove_pointer_t<std::remove_reference_t<decltype(func)>>, \
55
+ func>
56
+ #define TORCH_FN(func) TORCH_FN_TYPE(func)()
videollama2/lib/python3.10/site-packages/torch/include/c10/core/Contiguity.h ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/util/ArrayRef.h>
3
+ #include <c10/util/SmallVector.h>
4
+ #include <c10/util/irange.h>
5
+
6
+ #include <algorithm>
7
+ #include <cstdint>
8
+
9
+ namespace c10 {
10
+
11
+ template <typename T>
12
+ bool _compute_contiguous(ArrayRef<T> sizes, ArrayRef<T> strides, T numel) {
13
+ bool is_contiguous = true;
14
+ if (numel == 0)
15
+ return is_contiguous;
16
+ T z = 1;
17
+ // NB: make sure we do signed arithmetic
18
+ for (int64_t d = int64_t(sizes.size()) - 1; d >= 0; d--) {
19
+ const auto& size_d = sizes[d];
20
+ if (size_d != 1) {
21
+ if (strides[d] == z) {
22
+ z *= size_d;
23
+ } else {
24
+ is_contiguous = false;
25
+ break;
26
+ }
27
+ }
28
+ }
29
+ return is_contiguous;
30
+ }
31
+
32
+ template <typename T>
33
+ bool _compute_channels_last_contiguous_2d(
34
+ ArrayRef<T> sizes,
35
+ ArrayRef<T> strides) {
36
+ // Please don't combine these code, constant array is used here to let
37
+ // compiler fully unroll the loop to get better performance
38
+ switch (sizes.size()) {
39
+ case 4: {
40
+ T expected = 1;
41
+ for (auto& d : {1, 3, 2, 0}) {
42
+ const auto& size_d = sizes[d];
43
+ if (size_d != 1) {
44
+ if (strides[d] != expected) {
45
+ return false;
46
+ }
47
+ expected *= size_d;
48
+ }
49
+ }
50
+ return true;
51
+ }
52
+ // NOLINTNEXTLINE(bugprone-branch-clone)
53
+ case 3:
54
+ // TODO dim == 3 case will be enabled once it is fully tested
55
+ return false;
56
+ default:
57
+ return false;
58
+ }
59
+ }
60
+
61
+ template <typename T>
62
+ bool _compute_channels_last_contiguous_3d(
63
+ ArrayRef<T> sizes,
64
+ ArrayRef<T> strides) {
65
+ // Please don't combine these code, constant array is used here to let
66
+ // compiler fully unroll the loop to get better performance
67
+ switch (sizes.size()) {
68
+ case 5: {
69
+ T expected = 1;
70
+ for (auto& d : {1, 4, 3, 2, 0}) {
71
+ const auto& size_d = sizes[d];
72
+ if (size_d != 1) {
73
+ if (strides[d] != expected) {
74
+ return false;
75
+ }
76
+ expected *= size_d;
77
+ }
78
+ }
79
+ return true;
80
+ }
81
+ // NOLINTNEXTLINE(bugprone-branch-clone)
82
+ case 4:
83
+ // TODO dim == 4 case will be enabled once it is fully tested
84
+ return false;
85
+ default:
86
+ return false;
87
+ }
88
+ }
89
+
90
+ template <typename T>
91
+ bool _compute_non_overlapping_and_dense(
92
+ ArrayRef<T> sizes,
93
+ ArrayRef<T> strides) {
94
+ auto dim = sizes.size();
95
+ if (dim == 1) {
96
+ return sizes[0] < 2 || strides[0] == 1;
97
+ }
98
+ SmallVector<int64_t, 5> perm;
99
+ perm.resize(dim);
100
+ for (const auto i : c10::irange(dim)) {
101
+ perm[i] = i;
102
+ }
103
+ // Sort by strides, leaving 0 and 1 sized dims at the end of the array
104
+ std::sort(perm.begin(), perm.end(), [&](int64_t a, int64_t b) {
105
+ if (sizes[a] < 2) {
106
+ return false;
107
+ } else if (sizes[b] < 2) {
108
+ return true;
109
+ }
110
+ return strides[a] < strides[b];
111
+ });
112
+ T require_stride = 1;
113
+ for (const auto i : c10::irange(dim)) {
114
+ const auto& size_perm_i = sizes[perm[i]];
115
+ if (size_perm_i < 2) {
116
+ return true;
117
+ }
118
+ if (strides[perm[i]] != require_stride) {
119
+ return false;
120
+ }
121
+ require_stride *= size_perm_i;
122
+ }
123
+ return true;
124
+ }
125
+
126
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/DeviceType.h ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // This is directly synchronized with caffe2/proto/caffe2.proto, but
4
+ // doesn't require me to figure out how to get Protobuf headers into
5
+ // ATen/core (which would require a lot more build system hacking.)
6
+ // If you modify me, keep me synchronized with that file.
7
+
8
+ #include <c10/macros/Export.h>
9
+
10
+ #include <functional>
11
+ #include <ostream>
12
+
13
+ namespace c10 {
14
+
15
+ // These contains all device types that also have a BackendComponent
16
+ // and therefore participate in per-backend functionality dispatch keys.
17
+ // This is most backends except PrivateUse2 and PrivateUse3
18
+ #define C10_FORALL_BACKEND_DEVICE_TYPES(_, extra) \
19
+ _(CPU, extra) \
20
+ _(CUDA, extra) \
21
+ _(HIP, extra) \
22
+ _(XLA, extra) \
23
+ _(MPS, extra) \
24
+ _(IPU, extra) \
25
+ _(XPU, extra) \
26
+ _(HPU, extra) \
27
+ _(VE, extra) \
28
+ _(Lazy, extra) \
29
+ _(Meta, extra) \
30
+ _(MTIA, extra) \
31
+ _(PrivateUse1, extra)
32
+
33
+ enum class DeviceType : int8_t {
34
+ CPU = 0,
35
+ CUDA = 1, // CUDA.
36
+ MKLDNN = 2, // Reserved for explicit MKLDNN
37
+ OPENGL = 3, // OpenGL
38
+ OPENCL = 4, // OpenCL
39
+ IDEEP = 5, // IDEEP.
40
+ HIP = 6, // AMD HIP
41
+ FPGA = 7, // FPGA
42
+ ORT = 8, // ONNX Runtime / Microsoft
43
+ XLA = 9, // XLA / TPU
44
+ Vulkan = 10, // Vulkan
45
+ Metal = 11, // Metal
46
+ XPU = 12, // XPU
47
+ MPS = 13, // MPS
48
+ Meta = 14, // Meta (tensors with no data)
49
+ HPU = 15, // HPU / HABANA
50
+ VE = 16, // SX-Aurora / NEC
51
+ Lazy = 17, // Lazy Tensors
52
+ IPU = 18, // Graphcore IPU
53
+ MTIA = 19, // Meta training and inference devices
54
+ PrivateUse1 = 20, // PrivateUse1 device
55
+ // NB: If you add more devices:
56
+ // - Change the implementations of DeviceTypeName and isValidDeviceType
57
+ // in DeviceType.cpp
58
+ // - Change the number below
59
+ COMPILE_TIME_MAX_DEVICE_TYPES = 21,
60
+ };
61
+
62
+ constexpr DeviceType kCPU = DeviceType::CPU;
63
+ constexpr DeviceType kCUDA = DeviceType::CUDA;
64
+ constexpr DeviceType kHIP = DeviceType::HIP;
65
+ constexpr DeviceType kFPGA = DeviceType::FPGA;
66
+ constexpr DeviceType kORT = DeviceType::ORT;
67
+ constexpr DeviceType kXLA = DeviceType::XLA;
68
+ constexpr DeviceType kMPS = DeviceType::MPS;
69
+ constexpr DeviceType kMeta = DeviceType::Meta;
70
+ constexpr DeviceType kVulkan = DeviceType::Vulkan;
71
+ constexpr DeviceType kMetal = DeviceType::Metal;
72
+ constexpr DeviceType kXPU = DeviceType::XPU;
73
+ constexpr DeviceType kHPU = DeviceType::HPU;
74
+ constexpr DeviceType kVE = DeviceType::VE;
75
+ constexpr DeviceType kLazy = DeviceType::Lazy;
76
+ constexpr DeviceType kIPU = DeviceType::IPU;
77
+ constexpr DeviceType kMTIA = DeviceType::MTIA;
78
+ constexpr DeviceType kPrivateUse1 = DeviceType::PrivateUse1;
79
+
80
+ // define explicit int constant
81
+ constexpr int COMPILE_TIME_MAX_DEVICE_TYPES =
82
+ static_cast<int>(DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES);
83
+
84
+ static_assert(
85
+ COMPILE_TIME_MAX_DEVICE_TYPES <= 21,
86
+ "Hey! You seem to be adding a lot of new DeviceTypes. The intent was "
87
+ "for this constant to reflect the actual number of DeviceTypes we support "
88
+ "in PyTorch; it's important that this number is not too large as we "
89
+ "use this to allocate stack arrays in some places in our code. If you "
90
+ "are indeed just adding the 20th device type, feel free to change "
91
+ "the check to 32; but if you are adding some sort of extensible device "
92
+ "types registration, please be aware that you are affecting code that "
93
+ "this number is small. Try auditing uses of this constant.");
94
+
95
+ C10_API std::string DeviceTypeName(DeviceType d, bool lower_case = false);
96
+
97
+ C10_API bool isValidDeviceType(DeviceType d);
98
+
99
+ C10_API std::ostream& operator<<(std::ostream& stream, DeviceType type);
100
+
101
+ C10_API void register_privateuse1_backend(const std::string& backend_name);
102
+ C10_API std::string get_privateuse1_backend(bool lower_case = true);
103
+
104
+ } // namespace c10
105
+
106
+ namespace std {
107
+ template <>
108
+ struct hash<c10::DeviceType> {
109
+ std::size_t operator()(c10::DeviceType k) const {
110
+ return std::hash<int>()(static_cast<int>(k));
111
+ }
112
+ };
113
+ } // namespace std
114
+
115
+ namespace torch {
116
+ using c10::DeviceType;
117
+ }
videollama2/lib/python3.10/site-packages/torch/include/c10/core/DispatchKey.h ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/DeviceType.h>
4
+ #include <c10/macros/Export.h>
5
+ #include <cstdint>
6
+ #include <ostream>
7
+ #include <string>
8
+
9
+ namespace c10 {
10
+
11
+ // Semantically, each value of BackendComponent identifies a "backend" for our
12
+ // dispatch. Some functionalities that we may dispatch to are allowed to
13
+ // register different handlers for each backend. The BackendComponent is then
14
+ // used to figure out which backend implementation to dispatch to.
15
+
16
+ // In implementation terms, the backend component identifies a specific "bit" in
17
+ // a DispatchKeySet. The bits in the DispatchKeySet are split between the bottom
18
+ // ~12 "BackendComponent" bits, while the remaining upper bits are assigned to
19
+ // functionalities. When we encounter a functionality bit that is known to be
20
+ // customizable per-backend, then we also look at the lower BackendComponent
21
+ // bits and take the highest bit to determine which backend's implementation to
22
+ // use.
23
+
24
+ // WARNING! If you add a new backend component to the end of this list,
25
+ // make sure you register it before Meta.
26
+ // Meta must be at the end so that meta key in tls triggers meta kernels.
27
+ // (But you shouldn't: private use keys should have higher precedence than all
28
+ // built-in keys)
29
+
30
+ // If you add a new (non-privateuse) backend here,
31
+ // make sure to add an Autograd<Backend> fallthrough kernel
32
+ // in aten/src/ATen/core/VariableFallbackKernel.cpp
33
+
34
+ #define C10_FORALL_BACKEND_COMPONENTS(_, extra) \
35
+ _(CPU, extra) \
36
+ _(CUDA, extra) \
37
+ _(HIP, extra) \
38
+ _(XLA, extra) \
39
+ _(MPS, extra) \
40
+ _(IPU, extra) \
41
+ _(XPU, extra) \
42
+ _(HPU, extra) \
43
+ _(VE, extra) \
44
+ _(Lazy, extra) \
45
+ _(MTIA, extra) \
46
+ _(PrivateUse1, extra) \
47
+ _(PrivateUse2, extra) \
48
+ _(PrivateUse3, extra) \
49
+ _(Meta, extra)
50
+
51
+ // WARNING! If we add a new per-backend functionality key that has higher
52
+ // priority than Autograd, then make sure you update EndOfRuntimeBackendKeys
53
+
54
+ #define C10_FORALL_FUNCTIONALITY_KEYS(_) \
55
+ _(Dense, ) \
56
+ _(Quantized, Quantized) \
57
+ _(Sparse, Sparse) \
58
+ _(NestedTensor, NestedTensor) \
59
+ _(AutogradFunctionality, Autograd)
60
+
61
+ enum class BackendComponent : uint8_t {
62
+
63
+ // A "backend" is colloquially used to refer to handlers for dispatch
64
+ // which actually implement the numerics of an operation in question.
65
+ //
66
+ // Due to the nature of the enum, these backends are specified in
67
+ // an ordered way, but for most backends this order is not semantically
68
+ // meaningful (e.g., it's valid to reorder these backends without changing
69
+ // semantics). The only situation when backend ordering is meaningful
70
+ // is when the backend participates in multiple dispatch with another
71
+ // backend; e.g., CPU and CUDA (cuda must have higher priority).
72
+
73
+ // These keys don't correspond to individual kernels.
74
+ // Instead, they represent the backends that are allowed to override specific
75
+ // pieces of functionality:
76
+ // - dense kernels (e.g. DispatchKey::CPU)
77
+ // - sparse kernels (e.g. DispatchKey::SparseCPU)
78
+ // - quantized kernels (e.g. DispatchKey::QuantizedCPU)
79
+ // - autograd kernels (e.g. DispatchKey::AutogradCPU)
80
+ // We reserve space in the runtime operator table for this full cross product
81
+ // of
82
+ // [backends in this enum] x [keys below that are explicitly marked as having
83
+ // per-backend functionality]
84
+ //
85
+ // A meta tensor is a tensor without any data associated with it. (They
86
+ // have also colloquially been referred to as tensors on the "null" device).
87
+ // A meta tensor can be used to dry run operators without actually doing any
88
+ // computation, e.g., add on two meta tensors would give you another meta
89
+ // tensor with the output shape and dtype, but wouldn't actually add anything.
90
+
91
+ InvalidBit = 0,
92
+ #define DEFINE_BACKEND_COMPONENT(n, _) n##Bit,
93
+ C10_FORALL_BACKEND_COMPONENTS(DEFINE_BACKEND_COMPONENT, unused)
94
+ #undef DEFINE_BACKEND_COMPONENT
95
+
96
+ // Define an alias to represent end of backend dispatch keys.
97
+ // If you add new backend keys after PrivateUse3, please also update it here.
98
+ EndOfBackendKeys = MetaBit,
99
+ };
100
+
101
+ // Semantically, a dispatch key identifies a possible "level" in our
102
+ // dispatch, for which a handler may be registered. Each handler corresponds
103
+ // to a type of functionality.
104
+ //
105
+ // In implementation terms, the dispatch key identifies a specific "bit" in a
106
+ // DispatchKeySet. Higher bit indexes get handled by dispatching first (because
107
+ // we "count leading zeros" when we extract the highest priority dispatch
108
+ // key.)
109
+ //
110
+ // Note [DispatchKey Classification]
111
+ // This enum actually contains several types of keys, which are explained
112
+ // in more detail further down:
113
+ // (1) non-customizable backends (e.g. FPGA)
114
+ // (2) non-customizable functionalities (e.g. Functionalize)
115
+ // (3) functionalized that are customizable per backend (e.g. Dense, Sparse,
116
+ // AutogradFunctionality) (4) per-backend instances of customizable
117
+ // functionalities (e.g. CPU, SparseCPU, AutogradCPU) (5) alias keys (e.g.
118
+ // CompositeImplicitAutograd)
119
+ //
120
+ // Of the categories above, it's important to note:
121
+ // (a) which keys are assigned individual bits in a DispatchKeySet
122
+ // (b) which keys are assigned individual slots in the runtime operator table
123
+ // ("Runtime keys")
124
+ //
125
+ // (1), (2) and (3) all get their own dedicated bits in the DispatchKeySet.
126
+ // (1), (2) and (4) all get their own dedicated slots in the runtime operator
127
+ // table.
128
+
129
+ // See Note [DispatchKeySet Internal Representation] for more details.
130
+ //
131
+ // NOTE: Keep the list in sync with `DispatchKey` in torchgen/model.py
132
+ enum class DispatchKey : uint16_t {
133
+
134
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~ UNDEFINED ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
135
+ // This is not a "real" functionality, but it exists to give us a "nullopt"
136
+ // element we can return for cases when a DispatchKeySet contains no elements.
137
+ // You can think a more semantically accurate definition of DispatchKey is:
138
+ //
139
+ // using DispatchKey = optional<RealDispatchKey>
140
+ //
141
+ // and Undefined == nullopt. We didn't actually represent
142
+ // it this way because optional<RealDispatchKey> would take two
143
+ // words, when DispatchKey fits in eight bits.
144
+
145
+ Undefined = 0,
146
+
147
+ // Define an alias for Undefined to represent CatchAll (long term
148
+ // this will get eliminated, but for now it's convenient)
149
+ CatchAll = Undefined,
150
+
151
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Functionality Keys ~~~~~~~~~~~~~~~~~~~~~~ //
152
+ // Every value in the enum (up to EndOfFunctionalityKeys)
153
+ // corresponds to an individual "functionality" that can be dispatched to.
154
+ // This is represented in the DispatchKeySet by assigning each of these enum
155
+ // values
156
+ // to each of the remaining (64 - len(BackendComponent)) bits.
157
+ //
158
+ // Most of these functionalities have a single handler assigned to them,
159
+ // making them "runtime keys".
160
+ // That map to a single slot in the runtime operator table.
161
+ //
162
+ // A few functionalities are allowed to be customizable per backend.
163
+ // See [Note: Per-Backend Functionality Dispatch Keys] for details.
164
+
165
+ // See [Note: Per-Backend Functionality Dispatch Keys]
166
+ Dense,
167
+
168
+ // Below are non-extensible backends.
169
+ // These are backends that currently don't have their own overrides for
170
+ // Autograd/Sparse/Quantized kernels,
171
+ // and we therefore don't waste space in the runtime operator table allocating
172
+ // space for them.
173
+ // If any of these backends ever need to customize, e.g., Autograd, then we'll
174
+ // need to add a DispatchKey::*Bit for them.
175
+
176
+ // TODO: put this in BackendComponents
177
+ FPGA, // Xilinx support lives out of tree at
178
+ // https://gitlab.com/pytorch-complex/vitis_kernels
179
+
180
+ // TODO: put this in BackendComponents
181
+ // ONNX Runtime, lives out of tree at https://github.com/pytorch/ort and
182
+ // https://github.com/microsoft/onnxruntime, and is also used to test general
183
+ // backend/extension machinery in the core. cf:
184
+ // - test/cpp_extensions/ort_extension.cpp
185
+ // - test/test_torch.py
186
+ // - aten/src/ATen/test/extension_backend_test.cpp
187
+ ORT,
188
+
189
+ Vulkan, // TODO: put this in BackendComponents
190
+ Metal, // TODO: put this in BackendComponents
191
+
192
+ // See [Note: Per-Backend Functionality Dispatch Keys]
193
+ Quantized,
194
+
195
+ // This backend is to support custom RNGs; it lets you go
196
+ // to a different kernel if you pass in a generator that is not a
197
+ // traditional CPUGeneratorImpl/CUDAGeneratorImpl. To make use of this
198
+ // key:
199
+ // 1) set it as a second parameter of at::Generator constructor call in
200
+ // the user-defined PRNG class.
201
+ // 2) use it as a dispatch key while registering custom kernels
202
+ // (templatized kernels specialized for user-defined PRNG class)
203
+ // intended for out of tree use; tested by aten/src/ATen/test/rng_test.cpp
204
+ CustomRNGKeyId,
205
+
206
+ // TODO: Make Mkldnn a functionality key, so we can give it Meta
207
+ // support
208
+ // Here are backends which specify more specialized operators
209
+ // based on the layout of the tensor. Note that the sparse backends
210
+ // are one case where ordering matters: sparse multi-dispatches with
211
+ // the corresponding dense tensors, and must be handled before them.
212
+ MkldnnCPU, // registered at build/aten/src/ATen/RegisterMkldnnCPU.cpp
213
+ // NB: not to be confused with MKLDNN, which is Caffe2 only
214
+
215
+ // See [Note: Per-Backend Functionality Dispatch Keys]
216
+ Sparse,
217
+
218
+ // TODO: Make SparseCsr a functionality key
219
+ SparseCsrCPU,
220
+ SparseCsrCUDA,
221
+
222
+ NestedTensor,
223
+
224
+ // In some situations, it is not immediately obvious what the correct
225
+ // backend for function is, because the function in question doesn't
226
+ // have any "tensor" arguments. In this case, a BackendSelect function
227
+ // can be registered to implement the custom determination of the
228
+ // correct backend.
229
+ BackendSelect,
230
+
231
+ Python,
232
+
233
+ // Out-of-core key for Fake Tensor in torchdistx.
234
+ // See https://pytorch.org/torchdistx/latest/fake_tensor.html
235
+ // TODO: delete this in favor of Python-implemented fake tensor
236
+ Fake,
237
+ // See Note [Out-of-tree vmap+grad prototype]. The purpose of this key
238
+ // is to insert code after the "autograd subsystem" runs, so this key should
239
+ // be directly after ADInplaceOrView and all of the autograd keys.
240
+ FuncTorchDynamicLayerBackMode,
241
+
242
+ // Alias and mutation removal.
243
+ // If some backends want to opt into only alias removal or only mutation
244
+ // removal,
245
+ // we can consider adding separate keys dedicated to those individual passes.
246
+ // See Note [Functionalization Pass In Core] for details.
247
+ Functionalize,
248
+
249
+ // The named dispatch key is set for any tensors with named dimensions.
250
+ // Although we have a dispatch key for named tensors, for historical reasons,
251
+ // this dispatch key doesn't do any of the substantive functionality for named
252
+ // tensor (though, hypothetically, it could!) At the moment, it's just
253
+ // responsible for letting us give good error messages when operations
254
+ // don't support named tensors.
255
+ //
256
+ // NB: If you ever consider moving named tensor functionality into
257
+ // this dispatch key, note that it might be necessary add another dispatch
258
+ // key that triggers before composite operators, in case a composite operator
259
+ // has named dimension propagation that doesn't match that of its
260
+ // constituent parts.
261
+ // TODO: delete this once torchdim lands in functorch
262
+ Named,
263
+
264
+ // The Conjugate dispatch key is set for any tensors that need to perform
265
+ // conjugation
266
+ // This is implemented at a dispatch level right before any backends run
267
+ Conjugate,
268
+
269
+ // The Negative dispatch key is set for any tensors that need to perform
270
+ // negation
271
+ // This is implemented at a dispatch level right before any backends run
272
+ Negative,
273
+
274
+ ZeroTensor, // registered at build/aten/src/ATen/RegisterZeroTensor.cpp
275
+
276
+ // Note [ADInplaceOrView key]
277
+ // ADInplaceOrView key is used by inplace or view ops to register a kernel
278
+ // that does additional setup for future autograd computation.
279
+ //
280
+ // 1. For inplace ops this kernel does version bump
281
+ // 2. For view ops this kernel does `as_view` setup where we properly setup
282
+ // DifferentiableViewMeta on the view tensors.
283
+ //
284
+ // For other ops it's fallthrough kernel since there's no extra
285
+ // work to do.
286
+ //
287
+ // Note [Dream: skip VariableType kernel when requires_grad=false]
288
+ //
289
+ // In an ideal world where we can skip VariableType kernel for inputs
290
+ // with requires_grad=false, instead of a fallthrough kernel, we'll
291
+ // register a kernel shown below to all functional ops as well:
292
+ // torch::Tensor my_functional_op(...) {
293
+ // {
294
+ // // Note for every op in VariableType, you need to go through
295
+ // // `AutoDispatchBelowADInplaceOrView` guard exactly once to add the
296
+ // // key to TLS excluded set. If you don't go through it at all,
297
+ // // inplace/view ops called through `at::` inside your backend
298
+ // // kernel will dispatch to ADInplaceOrView kernels and do a lot
299
+ // // of extra work.
300
+ // at::AutoDispatchBelowADInplaceOrView guard;
301
+ // at::redispatch::my_functional_op(...);
302
+ // }
303
+ // }
304
+ // But this work is currently blocked since it adds an extra dispatch
305
+ // for all ops and it's non-trivial overhead at model level(a few percents).
306
+ // Thus our current approach takes advantage of the fact every kernel go
307
+ // through VariableType kernel first and pulls the
308
+ // `at::AutoDispatchBelowADInplaceOrView` guard of functional ops
309
+ // up to the `VariableType` kernel. Thus we only add the extra dispatch
310
+ // to view/inplace ops to minimize its perf impact to real models.
311
+ ADInplaceOrView,
312
+ // Note [Alias Dispatch Key : Autograd]
313
+ // All backends are oblivious to autograd; autograd is handled as a
314
+ // layer which happens on top of all backends. It inspects the autograd
315
+ // metadata of all inputs, determines what autograd metadata should be
316
+ // constructed by the output, and otherwise defers to the backend to
317
+ // actually do the numeric computation. Autograd contains
318
+ // the bulk of this logic.
319
+
320
+ // Autograd is now an alias dispatch key which by default maps to all
321
+ // backend-specific autograd keys.
322
+ // Backend-specific allow backends to override the default kernel registered
323
+ // to Autograd key as needed.
324
+ // For example, XLA wants to define autograd for einsum directly.
325
+ // Registering a custom autograd implementation at the XLA key won't work
326
+ // because we process Autograd before XLA. This key has higher priority and
327
+ // gets processed first. You generally should NOT redispatch after handling
328
+ // autograd here (since that would result in execution of the Autograd
329
+ // operator, which you're trying to skip). In AutogradXLA implementations,
330
+ // you are responsible for handling autograd yourself, or deferring to other
331
+ // operators which support autograd.
332
+
333
+ // Currently we only have backend-specific autograd keys for CPU/CUDA/XLA and
334
+ // reserved user-defined backends. All other in-tree backends share the
335
+ // AutogradOther key. We can add specific autograd key for those backends
336
+ // upon request.
337
+ AutogradOther,
338
+
339
+ // See [Note: Per-Backend Functionality Dispatch Keys]
340
+ AutogradFunctionality,
341
+
342
+ // NestedTensor is an example of something that isn't a "real backend"
343
+ // (because it mostly consists of redispatching kernels)
344
+ // but it would like to override autograd functionality in C++.
345
+ // We can handle cases like this by adding an extra functionality key
346
+ // exclusively for handling autograd for NestedTensor.
347
+ // lives out of tree at
348
+ // https://github.com/pytorch/nestedtensor
349
+ AutogradNestedTensor,
350
+
351
+ Tracer,
352
+
353
+ // TODO: make Autocast a functionality key
354
+ // Autocasting precedes VariableTypeId, to ensure casts are autograd-exposed
355
+ // and inputs are saved for backward in the post-autocast type.
356
+ AutocastCPU,
357
+ AutocastXPU,
358
+ AutocastIPU,
359
+ AutocastHPU,
360
+ AutocastXLA,
361
+ // AutocastXLA is only being used for TPUs. XLA GPUs continue to use
362
+ // AutocastCUDA.
363
+ AutocastCUDA,
364
+ AutocastPrivateUse1,
365
+
366
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ WRAPPERS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
367
+ // There are a number of alternative modes which may want to handle before
368
+ // autograd; for example, error checking, tracing, profiling or vmap. They
369
+ // go here.
370
+
371
+ FuncTorchBatched, // See Note [Out-of-tree vmap+grad prototype]
372
+
373
+ // Dispatch key for BatchedTensorImpl wrapping a nested tensor.
374
+ BatchedNestedTensor,
375
+
376
+ FuncTorchVmapMode, // See Note [Out-of-tree vmap+grad prototype]
377
+
378
+ // This is the dispatch key for BatchedTensorImpl, which is used to implement
379
+ // batching rules for vmap.
380
+ Batched,
381
+
382
+ // When we are inside a vmap, all tensors dispatch on this key.
383
+ // See Note: [DispatchKey::VmapMode usage] for more details.
384
+ VmapMode,
385
+
386
+ FuncTorchGradWrapper, // See Note [Out-of-tree vmap+grad prototype]
387
+
388
+ // Out-of-core key for Deferred Module Initialization in torchdistx.
389
+ // See https://pytorch.org/torchdistx/latest/deferred_init.html
390
+ DeferredInit,
391
+
392
+ // Used by Python key logic to know the set of tls on entry to the dispatcher
393
+ // This kernel assumes it is the top-most non-functorch-related DispatchKey.
394
+ // If you add a key above, make sure to update the fallback implementation for
395
+ // this.
396
+ PythonTLSSnapshot,
397
+
398
+ // This key should be at the very top of the dispatcher
399
+ FuncTorchDynamicLayerFrontMode, // See Note [Out-of-tree vmap+grad prototype]
400
+
401
+ // TESTING: This is intended to be a generic testing tensor type id.
402
+ // Don't use it for anything real; its only acceptable use is within a single
403
+ // process test. Use it by creating a TensorImpl with this DispatchKey, and
404
+ // then registering operators to operate on this type id. See
405
+ // aten/src/ATen/core/dispatch/backend_fallback_test.cpp for a usage example.
406
+ TESTING_ONLY_GenericWrapper,
407
+
408
+ // TESTING: This is intended to be a generic testing tensor type id.
409
+ // Don't use it for anything real; its only acceptable use is within a ingle
410
+ // process test. Use it by toggling the mode on and off via
411
+ // TESTING_ONLY_tls_generic_mode_set_enabled and then registering operators
412
+ // to operate on this type id. See
413
+ // aten/src/ATen/core/dispatch/backend_fallback_test.cpp
414
+ // for a usage example
415
+ TESTING_ONLY_GenericMode,
416
+
417
+ // This key is used for pre-dispatch tracing in make_fx.
418
+ // It has lower priority than the PythonDispatcher key
419
+ // because we use the PythonDispatcher to intercept the key from python,
420
+ // and avoid having to implement it in C++.
421
+ PreDispatch,
422
+
423
+ // This is a bypass that allows you to skip running the C++ dispatcher
424
+ // entirely
425
+ PythonDispatcher,
426
+
427
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FIN ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
428
+ EndOfFunctionalityKeys, // End of functionality keys.
429
+
430
+ // ~~~~~~~~~~~~~~ "Dense" Per-Backend Dispatch keys ~~~~~~~~~~~~~~~~~~~~ //
431
+ // Here are backends which you think of as traditionally specifying
432
+ // how to implement operations on some device.
433
+
434
+ #define DEFINE_PER_BACKEND_KEYS_FOR_BACKEND(n, prefix) prefix##n,
435
+
436
+ #define DEFINE_PER_BACKEND_KEYS(fullname, prefix) \
437
+ StartOf##fullname##Backends, \
438
+ C10_FORALL_BACKEND_COMPONENTS( \
439
+ DEFINE_PER_BACKEND_KEYS_FOR_BACKEND, prefix) \
440
+ EndOf##fullname##Backends = prefix##Meta,
441
+
442
+ C10_FORALL_FUNCTIONALITY_KEYS(DEFINE_PER_BACKEND_KEYS)
443
+
444
+ #undef DEFINE_PER_BACKEND_KEYS
445
+ #undef DEFINE_PER_BACKEND_KEYS_FOR_BACKEND
446
+
447
+ EndOfRuntimeBackendKeys = EndOfAutogradFunctionalityBackends,
448
+
449
+ // ~~~~~~~~~~~~~~~~~~~~~~ Alias Dispatch Keys ~~~~~~~~~~~~~~~~~~~~~~~~~~ //
450
+ // Note [Alias Dispatch Keys]
451
+ // Alias dispatch keys are synthetic dispatch keys which map to multiple
452
+ // runtime dispatch keys. Alisa keys have precedence, but they are always
453
+ // lower precedence than runtime keys. You can register a kernel to an
454
+ // alias key, the kernel might be populated to the mapped runtime keys
455
+ // during dispatch table computation.
456
+ // If a runtime dispatch key has multiple kernels from alias keys, which
457
+ // kernel wins is done based on the precedence of alias keys (but runtime
458
+ // keys always have precedence over alias keys).
459
+ // Alias keys won't be directly called during runtime.
460
+
461
+ // See Note [Alias Dispatch Key : Autograd]
462
+ Autograd,
463
+ CompositeImplicitAutograd, // registered at
464
+ // build/aten/src/ATen/RegisterCompositeImplicitAutograd.cpp
465
+
466
+ // Note: The alias keyset for FuncTorchBatchedDecomposition is disjoint from
467
+ // all
468
+ // other alias keysets
469
+ // and so precedence order doesn't matter
470
+ FuncTorchBatchedDecomposition, // registered at
471
+ // build/aten/src/ATen/RegisterFuncTorchBatchedDecomposition.cpp
472
+ // Note: The alias keyset for CompositeImplicitAutogradNestedTensor is
473
+ // disjoint from all other alias keysets
474
+ CompositeImplicitAutogradNestedTensor, // registered at
475
+ // build/aten/src/ATen/RegisterCompositeImplicitAutogradNestedTensor.cpp
476
+ CompositeExplicitAutograd, // registered at
477
+ // build/aten/src/ATen/RegisterCompositeExplicitAutograd.cpp
478
+ // See Note [CompositeExplicitAutogradNonFunctional Key]
479
+ CompositeExplicitAutogradNonFunctional, // registered at
480
+ // build/aten/src/ATen/RegisterCompositeExplicitAutograd.cpp
481
+
482
+ // Define an alias key to represent end of alias dispatch keys.
483
+ // If you add new alias keys after Autograd, please also update it here.
484
+ StartOfAliasKeys = Autograd,
485
+ EndOfAliasKeys = CompositeExplicitAutogradNonFunctional, //
486
+
487
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~ BC ALIASES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
488
+ // The aliases exist for backwards compatibility reasons, they shouldn't
489
+ // be used
490
+ CPUTensorId = CPU,
491
+ CUDATensorId = CUDA,
492
+ DefaultBackend = CompositeExplicitAutograd,
493
+ PrivateUse1_PreAutograd = AutogradPrivateUse1,
494
+ PrivateUse2_PreAutograd = AutogradPrivateUse2,
495
+ PrivateUse3_PreAutograd = AutogradPrivateUse3,
496
+ Autocast = AutocastCUDA,
497
+ };
498
+
499
+ // Note [Private use DispatchKey]
500
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
501
+ // Private use tensor IDs are preallocated tensor type IDs for use in user
502
+ // applications. Similar to private use fields in HTTP, they can be used
503
+ // by end users for experimental or private applications, without needing
504
+ // to "standardize" the tensor ID (which would be done by submitting a PR
505
+ // to PyTorch to add your type ID).
506
+ //
507
+ // Private use tensor IDs are appropriate to use if you want to experiment
508
+ // with adding a new tensor type (without having to patch PyTorch first) or
509
+ // have a private, non-distributed application that needs to make use of a
510
+ // new tensor type. Private use tensor IDs are NOT appropriate to use for
511
+ // libraries intended to be distributed to further users: please contact
512
+ // the PyTorch developers to get a type ID registered in this case.
513
+ //
514
+ // We provide two classes of private user tensor id: regular DispatchKeys
515
+ // and Autograd DispatchKeys. DispatchKeys serve the role of ordinary "backend"
516
+ // DispatchKeys; if you were adding support for a new type of accelerator, you
517
+ // would use a backend DispatchKey, and ideally automatically reuse
518
+ // AutogradOther definitions already defined in PyTorch. AutogradPrivateUse
519
+ // DispatchKeys serve as "wrapper" DispatchKeys: they are only necessary for
520
+ // tensors that compose multiple internal tensors, and for cases when the
521
+ // built-in autograd formulas for operators are not appropriate.
522
+
523
+ static_assert(
524
+ (static_cast<uint8_t>(BackendComponent::EndOfBackendKeys) +
525
+ static_cast<uint8_t>(DispatchKey::EndOfFunctionalityKeys)) <= 64,
526
+ "The BackendComponent and DispatchKey enums (below EndOfFunctionalityKeys)"
527
+ " both map to backend and functionality bits"
528
+ " into a 64-bit bitmask; you must have less than 64 total entries between them");
529
+
530
+ // Check if a DispatchKey is an alias mapping to other runtime keys.
531
+ constexpr bool isAliasDispatchKey(DispatchKey k) {
532
+ return k >= DispatchKey::StartOfAliasKeys && k <= DispatchKey::EndOfAliasKeys;
533
+ }
534
+
535
+ // [Note: Per-Backend Functionality Dispatch Keys]
536
+ // Check if a DispatchKey is a per-backend functionality key
537
+ // Any functionalities that can be customized per-backend should be added here.
538
+ // These keys correspond to functionalities that can be customized individually
539
+ // per backend. While they only take up one bit in the `DispatchKeySet` bitset,
540
+ // they map to (# backends) slots in the operator table.
541
+ // Each of these keys also has a separate set of "runtime keys" in the dispatch
542
+ // key enum, per backend, which *do* map to the individual operator table slots.
543
+ // For example, the "Sparse" key maps to an individual bit in the
544
+ // DispatchKeySet, while `SparseCPU`, `SparseCUDA`, etc all map to individual
545
+ // slots in the runtime operator table.
546
+
547
+ constexpr bool isPerBackendFunctionalityKey(DispatchKey k) {
548
+ if (k == DispatchKey::Dense || k == DispatchKey::Quantized ||
549
+ k == DispatchKey::Sparse || k == DispatchKey::AutogradFunctionality ||
550
+ k == DispatchKey::NestedTensor) {
551
+ return true;
552
+ } else {
553
+ return false;
554
+ }
555
+ }
556
+
557
+ // Note that this includes Undefined in the total count.
558
+ // BUT EndOfFunctionalityKeys is its own (placeholder) key.
559
+ // e.g. Undefined=0, Dense=1, Sparse=2, EndOfFunctionalityKeys=3.
560
+ // In the above example, there are 3 total functionality keys.
561
+ constexpr uint8_t num_functionality_keys =
562
+ static_cast<uint8_t>(DispatchKey::EndOfFunctionalityKeys);
563
+
564
+ constexpr uint8_t num_backends =
565
+ static_cast<uint8_t>(BackendComponent::EndOfBackendKeys);
566
+
567
+ // Note [No More Than 16 Backends]
568
+ // Search for this note to find places in the code where the "no more than 16
569
+ // backends" invariant is baked in.
570
+ static_assert(
571
+ static_cast<uint8_t>(BackendComponent::EndOfBackendKeys) <= 16,
572
+ "BackendComponent currently only supports <= 16 backends. If we really need to extend this, \
573
+ there are a few places where this invariant is baked in");
574
+
575
+ constexpr uint8_t numPerBackendFunctionalityKeys() {
576
+ uint8_t count = 0;
577
+ for (uint8_t k = 0; k <= num_functionality_keys; ++k) {
578
+ if (isPerBackendFunctionalityKey(static_cast<DispatchKey>(k)))
579
+ ++count;
580
+ }
581
+ return count;
582
+ }
583
+
584
+ #if defined(C10_MOBILE_TRIM_DISPATCH_KEYS)
585
+ // See [Note: Trimmed Mobile Dispatch Keys]
586
+ constexpr uint16_t num_runtime_entries = 8;
587
+ #else
588
+ constexpr uint16_t num_runtime_entries = num_functionality_keys +
589
+ (numPerBackendFunctionalityKeys() * (num_backends - 1));
590
+ #endif
591
+
592
+ // See Note [No More Than 16 Backends]
593
+ constexpr uint16_t full_backend_mask =
594
+ (static_cast<uint16_t>(1) << num_backends) - 1;
595
+
596
+ C10_API const char* toString(DispatchKey);
597
+ C10_API const char* toString(BackendComponent);
598
+ C10_API std::ostream& operator<<(std::ostream&, DispatchKey);
599
+ C10_API std::ostream& operator<<(std::ostream&, BackendComponent);
600
+
601
+ C10_API DispatchKey getAutogradKeyFromBackend(BackendComponent k);
602
+
603
+ // Parses a string into a dispatch key.
604
+ // If the string cannot be correctly parsed, throws an exception.
605
+ C10_API c10::DispatchKey parseDispatchKey(const std::string& k);
606
+
607
+ // These are some convenience identifiers for dispatch keys which are
608
+ // shorter to type than their long counterparts. Note that some of these
609
+ // dispatch keys directly correspond to DeviceType; and most APIs that
610
+ // accept DispatchKey also accept DeviceType; e.g.,
611
+ // torch::dispatch(torch::kCPU, ...) is also valid.
612
+ constexpr DispatchKey kAutograd = DispatchKey::Autograd;
613
+
614
+ // See Note [The Ordering of Per-Backend Dispatch Keys Matters!]
615
+ // This function relies on the invariant that the dispatch keys between
616
+ // StartOfDenseBackends and EndOfRuntimeBackendKeys are ordered by backend
617
+ // in the same order as `BackendComponent`.
618
+ constexpr BackendComponent toBackendComponent(DispatchKey k) {
619
+ if (k >= DispatchKey::StartOfDenseBackends &&
620
+ k <= DispatchKey::EndOfDenseBackends) {
621
+ return static_cast<BackendComponent>(
622
+ static_cast<uint8_t>(k) -
623
+ static_cast<uint8_t>(DispatchKey::StartOfDenseBackends));
624
+ } else if (
625
+ k >= DispatchKey::StartOfQuantizedBackends &&
626
+ k <= DispatchKey::EndOfQuantizedBackends) {
627
+ return static_cast<BackendComponent>(
628
+ static_cast<uint8_t>(k) -
629
+ static_cast<uint8_t>(DispatchKey::StartOfQuantizedBackends));
630
+ } else if (
631
+ k >= DispatchKey::StartOfSparseBackends &&
632
+ k <= DispatchKey::EndOfSparseBackends) {
633
+ return static_cast<BackendComponent>(
634
+ static_cast<uint8_t>(k) -
635
+ static_cast<uint8_t>(DispatchKey::StartOfSparseBackends));
636
+ } else if (
637
+ k >= DispatchKey::StartOfNestedTensorBackends &&
638
+ k <= DispatchKey::EndOfNestedTensorBackends) {
639
+ return static_cast<BackendComponent>(
640
+ static_cast<uint8_t>(k) -
641
+ static_cast<uint8_t>(DispatchKey::StartOfNestedTensorBackends));
642
+ } else if (
643
+ k >= DispatchKey::StartOfAutogradFunctionalityBackends &&
644
+ k <= DispatchKey::EndOfAutogradFunctionalityBackends) {
645
+ return static_cast<BackendComponent>(
646
+ static_cast<uint8_t>(k) -
647
+ static_cast<uint8_t>(
648
+ DispatchKey::StartOfAutogradFunctionalityBackends));
649
+ } else {
650
+ return BackendComponent::InvalidBit;
651
+ }
652
+ }
653
+
654
+ constexpr DispatchKey toFunctionalityKey(DispatchKey k) {
655
+ if (k <= DispatchKey::EndOfFunctionalityKeys) {
656
+ return k;
657
+ } else if (k <= DispatchKey::EndOfDenseBackends) {
658
+ return DispatchKey::Dense;
659
+ } else if (k <= DispatchKey::EndOfQuantizedBackends) {
660
+ return DispatchKey::Quantized;
661
+ } else if (k <= DispatchKey::EndOfSparseBackends) {
662
+ return DispatchKey::Sparse;
663
+ } else if (k <= DispatchKey::EndOfNestedTensorBackends) {
664
+ return DispatchKey::NestedTensor;
665
+ } else if (k <= DispatchKey::EndOfAutogradFunctionalityBackends) {
666
+ return DispatchKey::AutogradFunctionality;
667
+ } else {
668
+ return DispatchKey::Undefined;
669
+ }
670
+ }
671
+
672
+ BackendComponent toBackendComponent(DeviceType device_type);
673
+
674
+ // Given (DispatchKey::Dense, BackendComponent::CUDABit), returns
675
+ // DispatchKey::CUDA.
676
+ // See Note [The Ordering of Per-Backend Dispatch Keys Matters!]
677
+ // This function relies on the invariant that the dispatch keys between
678
+ // StartOfDenseBackends and EndOfRuntimeBackendKeys are ordered by backend
679
+ // in the same order as `BackendComponent`.
680
+ constexpr DispatchKey toRuntimePerBackendFunctionalityKey(
681
+ DispatchKey functionality_k,
682
+ BackendComponent backend_k) {
683
+ if (functionality_k == DispatchKey::Dense) {
684
+ return static_cast<DispatchKey>(
685
+ static_cast<uint8_t>(DispatchKey::StartOfDenseBackends) +
686
+ static_cast<uint8_t>(backend_k));
687
+ }
688
+ if (functionality_k == DispatchKey::Sparse) {
689
+ return static_cast<DispatchKey>(
690
+ static_cast<uint8_t>(DispatchKey::StartOfSparseBackends) +
691
+ static_cast<uint8_t>(backend_k));
692
+ }
693
+ if (functionality_k == DispatchKey::Quantized) {
694
+ return static_cast<DispatchKey>(
695
+ static_cast<uint8_t>(DispatchKey::StartOfQuantizedBackends) +
696
+ static_cast<uint8_t>(backend_k));
697
+ }
698
+ if (functionality_k == DispatchKey::NestedTensor) {
699
+ return static_cast<DispatchKey>(
700
+ static_cast<uint8_t>(DispatchKey::StartOfNestedTensorBackends) +
701
+ static_cast<uint8_t>(backend_k));
702
+ }
703
+ if (functionality_k == DispatchKey::AutogradFunctionality) {
704
+ return static_cast<DispatchKey>(
705
+ static_cast<uint8_t>(
706
+ DispatchKey::StartOfAutogradFunctionalityBackends) +
707
+ static_cast<uint8_t>(backend_k));
708
+ }
709
+ return DispatchKey::Undefined;
710
+ }
711
+
712
+ } // namespace c10
713
+
714
+ namespace torch {
715
+ // Expose the constant, but not the TYPE (DispatchKey is an implementation
716
+ // detail!)
717
+ using c10::kAutograd;
718
+ } // namespace torch
719
+
720
+ // NB: You really shouldn't use this instance; this enum is guaranteed
721
+ // to be pretty small so a regular array should be acceptable.
722
+ namespace std {
723
+ template <>
724
+ struct hash<c10::DispatchKey> {
725
+ typedef size_t result_type;
726
+ typedef c10::DispatchKey argument_type;
727
+
728
+ size_t operator()(c10::DispatchKey x) const {
729
+ return static_cast<size_t>(x);
730
+ }
731
+ };
732
+ } // namespace std
videollama2/lib/python3.10/site-packages/torch/include/c10/core/DispatchKeySet.h ADDED
@@ -0,0 +1,928 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <c10/core/DispatchKey.h>
3
+ #include <c10/util/Exception.h>
4
+ #include <c10/util/Metaprogramming.h>
5
+ #include <c10/util/llvmMathExtras.h>
6
+ #include <array>
7
+ #include <ostream>
8
+
9
+ namespace c10 {
10
+
11
+ struct FunctionalityOffsetAndMask {
12
+ // empty constructor shouldn't be used; only needed to initialize
13
+ // the array before populating it.
14
+ FunctionalityOffsetAndMask() = default;
15
+ FunctionalityOffsetAndMask(uint16_t offset, uint16_t mask)
16
+ : offset(offset), mask(mask) {}
17
+ // This needs to big enough to cover the size of the operator table.
18
+ uint16_t offset{};
19
+ // See Note [No More Than 16 Backends]
20
+ // This mask needs to be big enough to mask all of the backend bits.
21
+ // We probably don't ever want to have more than 16 backend bits, so uint16_t
22
+ // should be enough.
23
+ uint16_t mask{};
24
+ };
25
+ static_assert(
26
+ c10::num_runtime_entries < 65536,
27
+ "The dispatcher currently only supports up to 2^16 runtime entries");
28
+
29
+ C10_API std::array<FunctionalityOffsetAndMask, num_functionality_keys>
30
+ initializeFunctionalityOffsetsAndMasks();
31
+
32
+ C10_ALWAYS_INLINE static const std::
33
+ array<FunctionalityOffsetAndMask, num_functionality_keys>&
34
+ offsetsAndMasks() {
35
+ static auto offsets_and_masks_ = initializeFunctionalityOffsetsAndMasks();
36
+ return offsets_and_masks_;
37
+ }
38
+
39
+ // A representation of a set of DispatchKeys. A DispatchKeySet contains both
40
+ // "functionality" bits and "backend bits", and every tensor holds its own
41
+ // DispatchKeySet. The Dispatcher implements multiple dispatch by grabbing the
42
+ // keyset on every input tensor, or’ing them together, and dispatching to a
43
+ // specific piece of functionality. The functionality bits are *ordered*. When
44
+ // multiple functionality bits are set, we use the highest priority
45
+ // functionality. Similarly, multiple backend bits can theoretically be set if
46
+ // you call an operator with multiple tensors from difference devices (e.g. CPU
47
+ // and CUDA), although support for mixed device dispatch is limited (the only
48
+ // kernels that gracefully handle mixed device inputs for now are cuda kernels
49
+ // that take in a scalar cpu tensor).
50
+
51
+ // A representation of a set of DispatchKeys. A tensor may have multiple
52
+ // tensor type ids, e.g., a Variable tensor can also be a CPU tensor; the
53
+ // DispatchKeySet specifies what type ids apply. The internal representation is
54
+ // as a 64-bit bit set (this means only 64 tensor type ids are supported).
55
+ //
56
+ // As mentioned above, DispatchKeys are ordered; thus, we can ask questions like
57
+ // "what is the highest priority DispatchKey in the set"? (The set itself is
58
+ // not ordered; two sets with the same ids will always have the ids ordered in
59
+ // the same way.)
60
+ //
61
+ // Note [DispatchKeySet Internal Representation]
62
+ // Internally, dispatch keys are packed into 64-bit DispatchKeySet objects
63
+ // that get passed around at runtime.
64
+ // However, there isn't necessarily a 1-to-1 mapping between bits in the keyset
65
+ // and individual dispatch keys.
66
+ //
67
+ // First: why do we have this distinction, and why not map every dispatch key
68
+ // directly to a bit? This is mostly because we have several types of
69
+ // functionalities that different backends would like to customize. For example,
70
+ // we have:
71
+ // - "Dense": CPU, CUDA, XLA, ... (~12 keys)
72
+ // - "Sparse": SparseCPU, SparseCUDA, ...
73
+ // - "Quantized": QuantizedCPU, QuantizedCUDA, QuantizedXLA, ...
74
+ // - "Autograd": AutogradCPU, AutogradCUDA, Autograd XLA, ...
75
+ // The problem is that total number of keys grows quadratically with [#
76
+ // backends] x [# functionalities], making it very difficult to map each key
77
+ // directly to a bit in a bitset without dramatically increasing the size of the
78
+ // bitset over time.
79
+ //
80
+ // The two enums (BackendComponent and DispatchKey) can be divided roughly into
81
+ // 5 categories.
82
+ //
83
+ // (1) "Building block" keys
84
+ // (a) backends: Everything in the BackendComponent enum (e.g. CPUBit,
85
+ // CUDABit) (b) functionalities: (per-backend) functionality-bit DispatchKeys
86
+ // (e.g. AutogradFunctionality, Sparse, Dense)
87
+ // (2) "Runtime" keys
88
+ // (a) "non-customizable backends" (e.g. FPGA)
89
+ // (b) "non-customizable functionalities" (e.g. Functionalize)
90
+ // (c) "per-backend instances of customizable functionalities" (e.g. CPU,
91
+ // SparseCPU, AutogradCPU)
92
+ // (3) "Alias" DispatchKeys (see Note [Alias Dispatch Keys])
93
+ //
94
+ // (1) Building block keys always correspond to individual bits in a
95
+ // DispatchKeySet. They can also be combined in a DispatchKeySet to form actual
96
+ // runtime keys. e.g.
97
+ // auto dense_cpu_ks = DispatchKeySet({DispatchKey::CPUBit,
98
+ // DispatchKey::Dense});
99
+ // // The keyset has the runtime dense-cpu key.
100
+ // dense_cpu_ks.has(DispatchKey::CPU);
101
+ // // And it contains the building block keys too.
102
+ // dense_cpu_ks.has(DispatchKey::CPUBit);
103
+ // dense_cpu_ks.has(DispatchKey::Dense);
104
+ //
105
+ // Not every backend and not every functionality counts as a "building block
106
+ // key". This is mostly to give us more levers to pull in the design space.
107
+ // Backend keys and functionality keys that count as "building blocks" will
108
+ // contribute to a full cross product of functionality that can be overriden.
109
+ //
110
+ // For example, right now we have at least 12 "backend" building blocks (CPU,
111
+ // CUDA, XLA, ...) and at least 4 "functionality" building blocks (Dense,
112
+ // Sparse, Quantized, AutogradFunctionality, ...). These keys together allow
113
+ // every dispatcher operator to be customized in up to 12*4 different ways. Each
114
+ // of those requires a slot in the operator table of every dispatcher operator.
115
+ // Not every piece of functionality necessarily needs to be customizable
116
+ // per-backend, and not every backend necessarily needs to be able to customize
117
+ // every type of functionality.
118
+ //
119
+ //
120
+ // (2) Every runtime key corresponds directly to a slot in an operator's runtime
121
+ // dispatch table, and you can directly register kernels to a runtime dispatch
122
+ // key.
123
+ //
124
+ // For per-backend functionalities like "Dense" or "AutogradFunctionality",
125
+ // you can think of the corresponding runtime dispatch keys as "instances" of
126
+ // that functionality, per backend. E.g. "CPU", "CUDA", "XLA", etc. are all
127
+ // runtime instances of the "Dense" building block key.
128
+
129
+ // (2a) and (2b) are represented identically in the DispatchKeySet logic:
130
+ // - backend-agnostic functionalities (e.g. FuncTorchBatched) are NOT
131
+ // customizable per backend.
132
+ // In order to do so, we'd need to promote it to a per-backend functionality
133
+ // "building block" key.
134
+ // - non-customizable backends (e.g. FPGA) can NOT customize existing
135
+ // functionality like Sparse, Autograd, etc.
136
+ // In order to do so, we'd need to promote it to a backend "building block"
137
+ // key.
138
+ //
139
+ // In both cases, these keys directly correspond to runtime slots in the
140
+ // operator table.
141
+ //
142
+ //
143
+ // (3) "Alias" keys
144
+ // See Note [Alias Dispatch Keys]
145
+ //
146
+ // Final note: for anyone making future changes to the Dispatcher +
147
+ // DispatchKeySet internals, there's a closed PR with a basic
148
+ // python-implementation of the Dispatcher that might be useful in quickly
149
+ // testing out and validating changes. See it at
150
+ // https://github.com/pytorch/pytorch/pull/68743
151
+
152
+ // An undefined tensor is one with an empty tensor type set.
153
+ class DispatchKeySet final {
154
+ public:
155
+ enum Full { FULL };
156
+ enum FullAfter { FULL_AFTER };
157
+ enum Raw { RAW };
158
+
159
+ // NB: default constructor representation as zero is MANDATORY as
160
+ // use of DispatchKeySet in TLS requires this.
161
+ constexpr DispatchKeySet() = default;
162
+
163
+ constexpr DispatchKeySet(Full)
164
+ : repr_((1ULL << (num_backends + num_functionality_keys - 1)) - 1) {}
165
+
166
+ constexpr DispatchKeySet(FullAfter, DispatchKey t)
167
+ // LSB after t are OK, but not t itself.
168
+ // "functionalities" have a notion of ordering (e.g. Autograd > Sparse >
169
+ // Quantized > Dense). But backends don't really have an ordering.
170
+ // Therefore, we're enforcing that FullAfter can only be used on
171
+ // "functionality" keys.
172
+ : repr_(
173
+ (1ULL
174
+ << (num_backends + static_cast<uint8_t>(toFunctionalityKey(t)) -
175
+ 1)) -
176
+ 1) {
177
+ *this = add(DispatchKey::PythonDispatcher);
178
+ }
179
+
180
+ // Public version of DispatchKeySet(uint64_t) API; external users
181
+ // must be explicit when they do this!
182
+ constexpr DispatchKeySet(Raw, uint64_t x) : repr_(x) {}
183
+
184
+ constexpr explicit DispatchKeySet(BackendComponent k) {
185
+ if (k == BackendComponent::InvalidBit) {
186
+ repr_ = 0;
187
+ } else {
188
+ repr_ = 1ULL << (static_cast<uint8_t>(k) - 1);
189
+ }
190
+ }
191
+
192
+ constexpr explicit DispatchKeySet(DispatchKey k) {
193
+ if (k == DispatchKey::Undefined) {
194
+ // Case 1: handle Undefined specifically
195
+ repr_ = 0;
196
+ } else if (k <= DispatchKey::EndOfFunctionalityKeys) {
197
+ // Case 2: handle "functionality-only" keys
198
+ // These keys have a functionality bit set, but no backend bits
199
+ // These can technically be either:
200
+ // - valid runtime keys (e.g. DispatchKey::AutogradOther,
201
+ // DispatchKey::FuncTorchBatched, etc)
202
+ // - "building block" keys that aren't actual runtime keys (e.g.
203
+ // DispatchKey::Dense or Sparse)
204
+ uint64_t functionality_val = 1ULL
205
+ << (num_backends + static_cast<uint8_t>(k) - 1);
206
+ repr_ = functionality_val;
207
+ } else if (k <= DispatchKey::EndOfRuntimeBackendKeys) {
208
+ // Case 3: "runtime" keys that have a functionality bit AND a backend bit.
209
+ // First compute which bit to flip for the functionality.
210
+ auto functionality_k = toFunctionalityKey(k);
211
+ // The - 1 is because Undefined is technically a "functionality" that
212
+ // doesn't show up in the bitset. So e.g. Dense is technically the second
213
+ // functionality, but the lowest functionality bit.
214
+ uint64_t functionality_val = 1ULL
215
+ << (num_backends + static_cast<uint8_t>(functionality_k) - 1);
216
+
217
+ // then compute which bit to flip for the backend
218
+ // Case 4a: handle the runtime instances of "per-backend functionality"
219
+ // keys For example, given DispatchKey::CPU, we should set:
220
+ // - the Dense functionality bit
221
+ // - the CPUBit backend bit
222
+ // first compute which bit to flip for the backend
223
+ auto backend_k = toBackendComponent(k);
224
+ uint64_t backend_val = backend_k == BackendComponent::InvalidBit
225
+ ? 0
226
+ : 1ULL << (static_cast<uint8_t>(backend_k) - 1);
227
+ repr_ = functionality_val + backend_val;
228
+ } else {
229
+ // At this point, we should have covered every case except for alias keys.
230
+ // Technically it would be possible to add alias dispatch keys to a
231
+ // DispatchKeySet, but the semantics are a little confusing and this
232
+ // currently isn't needed anywhere.
233
+ repr_ = 0;
234
+ }
235
+ }
236
+
237
+ constexpr uint64_t keys_to_repr(std::initializer_list<DispatchKey> ks) {
238
+ uint64_t repr = 0;
239
+ for (auto k : ks) {
240
+ repr |= DispatchKeySet(k).repr_;
241
+ }
242
+ return repr;
243
+ }
244
+
245
+ constexpr uint64_t backend_bits_to_repr(
246
+ std::initializer_list<BackendComponent> ks) {
247
+ uint64_t repr = 0;
248
+ for (auto k : ks) {
249
+ repr |= DispatchKeySet(k).repr_;
250
+ }
251
+ return repr;
252
+ }
253
+
254
+ explicit constexpr DispatchKeySet(std::initializer_list<DispatchKey> ks)
255
+ : repr_(keys_to_repr(ks)) {}
256
+
257
+ explicit constexpr DispatchKeySet(std::initializer_list<BackendComponent> ks)
258
+ // Note: for some reason, putting this logic directly in the constructor
259
+ // appears to fail to compile on CUDA 10.1.
260
+ // See an example internal failure at
261
+ // https://www.internalfb.com/intern/skycastle/run/76561193669136035/artifact/actionlog.76561193742069401.stderr
262
+ : repr_(backend_bits_to_repr(ks)) {}
263
+
264
+ // Test if a DispatchKey is in the set
265
+ inline bool has(DispatchKey t) const {
266
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(t != DispatchKey::Undefined);
267
+ return has_all(DispatchKeySet(t));
268
+ }
269
+ constexpr bool has_backend(BackendComponent t) const {
270
+ return has_all(DispatchKeySet(t));
271
+ }
272
+
273
+ // Test if a DispatchKey is in the set
274
+ // Given a DispatchKeySet of functionality keys and (potentially) backend
275
+ // keys, tests if all of them are in the current set.
276
+ constexpr bool has_all(DispatchKeySet ks) const {
277
+ return static_cast<bool>((repr_ & ks.repr_) == ks.repr_);
278
+ }
279
+
280
+ // Given a DispatchKeySet of functionality keys and (potentially) backend
281
+ // keys, tests if any of them are in the current set. This could technically
282
+ // be pretty easily implemented using has(). It is strictly a perf
283
+ // optimization though. There are many places in the code base where we want
284
+ // to test for multiple functionality keys together. HOWEVER, runtime
285
+ // per-backend functionality keys aren't allowed to be used with this
286
+ // function, because you can end up with weird results. e.g.
287
+ // DispatchKeySet(DispatchKey::AutogradCPU).has_any(DispatchKeySet(DispatchKey::CPU))
288
+ // would return true.
289
+ inline bool has_any(DispatchKeySet ks) const {
290
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
291
+ // Either there are no backend bits in the input keyset
292
+ ((ks.repr_ & full_backend_mask) == 0) ||
293
+ // or there are no per-backend-functionality bits
294
+ // See [Note: Per-Backend Functionality Dispatch Keys]
295
+ ((ks &
296
+ DispatchKeySet({
297
+ DispatchKey::Dense,
298
+ DispatchKey::Quantized,
299
+ DispatchKey::Sparse,
300
+ DispatchKey::AutogradFunctionality,
301
+ })
302
+ .repr_) == 0));
303
+ return static_cast<bool>((repr_ & ks.repr_) != 0);
304
+ }
305
+ // Test if DispatchKeySet is a superset of ks.
306
+ bool isSupersetOf(DispatchKeySet ks) const {
307
+ return (repr_ & ks.repr_) == ks.repr_;
308
+ }
309
+ // Perform set union
310
+ constexpr DispatchKeySet operator|(DispatchKeySet other) const {
311
+ return DispatchKeySet(repr_ | other.repr_);
312
+ }
313
+ // Perform set intersection
314
+ constexpr DispatchKeySet operator&(DispatchKeySet other) const {
315
+ return DispatchKeySet(repr_ & other.repr_);
316
+ }
317
+ // Compute the set difference self - other,
318
+ // but ONLY for the functionality keys.
319
+ // Any backend bits set on self will remain unchanged.
320
+ // See Note [Removing keys from DispatchKeySet Only Affects Functionality
321
+ // Keys]
322
+ constexpr DispatchKeySet operator-(DispatchKeySet other) const {
323
+ return DispatchKeySet(repr_ & (full_backend_mask | ~other.repr_));
324
+ }
325
+
326
+ // Compute self ^ other
327
+ constexpr DispatchKeySet operator^(DispatchKeySet other) const {
328
+ return DispatchKeySet(repr_ ^ other.repr_);
329
+ }
330
+ bool operator==(DispatchKeySet other) const {
331
+ return repr_ == other.repr_;
332
+ }
333
+ bool operator!=(DispatchKeySet other) const {
334
+ return repr_ != other.repr_;
335
+ }
336
+ // Add a DispatchKey to the DispatchKey set. Does NOT mutate,
337
+ // returns the extended DispatchKeySet!
338
+ C10_NODISCARD constexpr DispatchKeySet add(DispatchKey t) const {
339
+ return *this | DispatchKeySet(t);
340
+ }
341
+ C10_NODISCARD constexpr DispatchKeySet add(DispatchKeySet ks) const {
342
+ return *this | ks;
343
+ }
344
+
345
+ // Remove a DispatchKey from the DispatchKey set.
346
+ // This is generally not an operation you should be doing
347
+ // (it's used to implement the printing overload, operator<<)
348
+ //
349
+ // Note [Removing keys from DispatchKeySet Only Affects Functionality Keys]
350
+ // Only functionality bits are allowed to be removed from a keyset.
351
+ // For now, we're only allowing removal of "functionality bits" from the
352
+ // keyset, which is specifically needed by the fallthrough key calculation
353
+ // logic. Why is removing backend bits problematic? Consider this example:
354
+ //
355
+ // DispatchKeySet([DispatchKey.CPU, DispatchKey.AutogradCUDA,
356
+ // DispatchKey.CUDA]).remove(DispatchKey.AutogradCUDA)
357
+ // DispatchKeySet([DispatchKey.CPU,
358
+ // DispatchKey.AutogradCUDA]).remove(DispatchKey.AutogradCUDA)
359
+ //
360
+ // What do we want to happen?
361
+ // Technically, we'd like it to be true that after removal,
362
+ // the first keyset still has the CUDA dispatch key while the second doesn't.
363
+ // Unfortunately there's no way to represent that, because the two keysets are
364
+ // represented the same way internally: functionality bits: Autograd, Dense
365
+ // backend bits: CPU, CUDA
366
+ //
367
+ // Instead, remove(DispatchKey.AutogradCPU) will only remove the "Autograd"
368
+ // bit from the bitset.
369
+ C10_NODISCARD constexpr DispatchKeySet remove(DispatchKey t) const {
370
+ return DispatchKeySet(
371
+ repr_ & ~(DispatchKeySet(t).repr_ & ~full_backend_mask));
372
+ }
373
+ // You're allowed to remove a backend bit from a DispatchKeySet,
374
+ // but you have to be explicit about it (remove_backend() instead of
375
+ // remove()).
376
+ constexpr DispatchKeySet remove_backend(BackendComponent b) const {
377
+ return DispatchKeySet(repr_ & ~(DispatchKeySet(b).repr_));
378
+ }
379
+ // Is the set empty? (AKA undefined tensor)
380
+ bool empty() const {
381
+ return repr_ == 0;
382
+ }
383
+ uint64_t raw_repr() {
384
+ return repr_;
385
+ }
386
+
387
+ DispatchKey highestFunctionalityKey() const {
388
+ auto functionality_idx = indexOfHighestBit();
389
+ // This means that none of the functionality bits were set.
390
+ if (functionality_idx < num_backends)
391
+ return DispatchKey::Undefined;
392
+ // The first num_backend bits in the keyset don't correspond to real
393
+ // dispatch keys.
394
+ return static_cast<DispatchKey>(functionality_idx - num_backends);
395
+ }
396
+
397
+ // This is similar like toBackendComponent(DispatchKey), but less restrictive.
398
+ // toBackendComponent() errors out if the key that it was passed has no
399
+ // backend bits, which is useful for error checking. We need a version of that
400
+ // here that can also handle "fake" backends like FPGA, because they need to
401
+ // map to the AutogradOther key. For those backends, we return
402
+ // BackendComponent::InvalidBit.
403
+ BackendComponent highestBackendKey() const {
404
+ // mask to mask out functionality bits
405
+ auto backend_idx =
406
+ DispatchKeySet(repr_ & full_backend_mask).indexOfHighestBit();
407
+ // all zeros across the backend bits means that no backend bits are set.
408
+ if (backend_idx == 0)
409
+ return BackendComponent::InvalidBit;
410
+ return static_cast<BackendComponent>(backend_idx);
411
+ }
412
+
413
+ // returns the DispatchKey of highest priority in the set.
414
+ DispatchKey highestPriorityTypeId() const {
415
+ auto functionality_k = highestFunctionalityKey();
416
+ if (isPerBackendFunctionalityKey(functionality_k)) {
417
+ return toRuntimePerBackendFunctionalityKey(
418
+ functionality_k, highestBackendKey());
419
+ }
420
+ return functionality_k;
421
+ }
422
+
423
+ // Returns the index of the most-significant bit in the keyset.
424
+ // This is used to as part of the calculation into the operator table to get:
425
+ // - the highest "functionality" bit in the keyset.
426
+ // - the highest "backend" bit in the keyset.
427
+ uint8_t indexOfHighestBit() const {
428
+ return 64 - llvm::countLeadingZeros(repr_);
429
+ }
430
+
431
+ #if defined(C10_MOBILE_TRIM_DISPATCH_KEYS)
432
+ // [Note: Trimmed Mobile Dispatch Keys]
433
+ /**
434
+ * The method below maps the dispatch key in the enum DispatchKey to an
435
+ * integer index in the dispatchTable_ array in OperatorEntry. The array
436
+ * is trimmed for mobile to reduce peak memory usage since it's
437
+ * unnecessary to reserve additional space for dispatch keys that will
438
+ * never be used on mobile.
439
+ */
440
+ int getDispatchTableIndexForDispatchKeySet() const {
441
+ auto dk = highestPriorityTypeId();
442
+ switch (dk) {
443
+ case DispatchKey::Undefined:
444
+ return 0;
445
+ case DispatchKey::CPU:
446
+ return 1;
447
+ case DispatchKey::QuantizedCPU:
448
+ return 2;
449
+ case DispatchKey::SparseCPU:
450
+ return 3;
451
+ case DispatchKey::BackendSelect:
452
+ return 4;
453
+ case DispatchKey::ADInplaceOrView:
454
+ return 5;
455
+ case DispatchKey::AutogradOther:
456
+ return 6;
457
+ case DispatchKey::AutogradCPU:
458
+ return 7;
459
+ default:
460
+ return -1;
461
+ }
462
+ }
463
+ #else
464
+ // returns the index in the operator table of highest priority key in the the
465
+ // keyset Note that we could in theory implement this using
466
+ // highestPriorityTypeId(), but this code is very hotpath and we can do it
467
+ // faster without it.
468
+ int getDispatchTableIndexForDispatchKeySet() const {
469
+ auto functionality_idx =
470
+ DispatchKeySet(repr_ >> num_backends).indexOfHighestBit();
471
+ auto offset_and_mask = offsetsAndMasks()[functionality_idx];
472
+ // Mask the functionality bits out first, then right-shift by 1.
473
+ // right-shifting by 1 because everything is zero-indexed.
474
+ // E.g. 000001 (CPU) should give us an offset of 0, 000010 (CUDA) should
475
+ // give us an offset of 1, etc.
476
+ auto backend_idx =
477
+ DispatchKeySet((repr_ & offset_and_mask.mask) >> 1).indexOfHighestBit();
478
+ return offset_and_mask.offset + backend_idx;
479
+ }
480
+ #endif
481
+
482
+ // returns the "index" of the highest priority backend in the keyset.
483
+ // This is pretty similar to getBackendKey(), but:
484
+ // - It's hotpath code (part of the runtime bitset calculation)
485
+ // - I's returns an integer index, not an enum value
486
+ // - Everything is shifted to the right by 1.
487
+ // BackendComponent::InvalidBit is technically the lowest enum value,
488
+ // but it isn't included in the runtime table. So CPUBit = 1, CUDABit = 2,
489
+ // etc.
490
+ uint64_t getBackendIndex() const {
491
+ return DispatchKeySet((repr_ & full_backend_mask) >> 1).indexOfHighestBit();
492
+ }
493
+
494
+ private:
495
+ constexpr DispatchKeySet(uint64_t repr) : repr_(repr) {}
496
+ uint64_t repr_ = 0;
497
+
498
+ public:
499
+ // STL iterator for DispatchKeySet. Iterates through all runtime DispatchKeys
500
+ // in the set. The iterator is only invalidated by the destruction of the
501
+ // underlying DispatchKeySet as the iterator stores a pointer to the raw
502
+ // representation of the DispatchKeySet. Note: When we encounter a per-backend
503
+ // functionality (e.g. Dense or Sparse), we will iterate through EVERY backend
504
+ // in the keyset, for that functionality. For example, if the next
505
+ // functionality key to iterate over is Autograd, and the backend bits in the
506
+ // keyset correspond to [BackendComponent::CPUBit, BackendComponent::CUDABit],
507
+ // then the next two keys we return will be DispatchKey::AutogradCPU,
508
+ // DispatchKey::AutogradCUDA (CPU first because it has lower precedence than
509
+ // CUDA in DispatchKey.h).
510
+ class iterator {
511
+ public:
512
+ using self_type = iterator;
513
+ using iterator_category = std::input_iterator_tag;
514
+ using value_type = DispatchKey;
515
+ using difference_type = ptrdiff_t;
516
+ using reference = value_type&;
517
+ using pointer = value_type*;
518
+ // final mask value should mask out the entire keyset
519
+ static const uint8_t end_iter_mask_val =
520
+ num_backends + num_functionality_keys;
521
+ // final key value should be the last DispatchKey
522
+ static const uint8_t end_iter_key_val = num_functionality_keys;
523
+
524
+ // current_dispatchkey_idx_ will iterate through all functionality bits.
525
+ // current_backendcomponent_idx_ will iterate through all backend bits.
526
+ explicit iterator(
527
+ const uint64_t* data_ptr,
528
+ uint8_t next_functionality = num_backends,
529
+ uint8_t next_backend = 0)
530
+ : data_ptr_(data_ptr),
531
+ next_functionality_(next_functionality),
532
+ next_backend_(next_backend),
533
+ // These are in an invalid state at construction time, and set by the
534
+ // first increment call
535
+ current_dispatchkey_idx_(end_iter_key_val),
536
+ current_backendcomponent_idx_(end_iter_key_val) {
537
+ // Go to the first key in the set
538
+ TORCH_INTERNAL_ASSERT(
539
+ next_functionality_ >= num_backends,
540
+ "num_backends=",
541
+ static_cast<uint32_t>(num_backends),
542
+ "next_functionality_=",
543
+ static_cast<uint32_t>(next_functionality_));
544
+ ++(*this);
545
+ }
546
+
547
+ C10_API self_type& operator++();
548
+
549
+ self_type operator++(int) {
550
+ self_type previous_iterator = *this;
551
+ ++(*this);
552
+ return previous_iterator;
553
+ }
554
+
555
+ bool operator==(const self_type& rhs) const {
556
+ return next_functionality_ == rhs.next_functionality_ &&
557
+ current_dispatchkey_idx_ == rhs.current_dispatchkey_idx_ &&
558
+ next_backend_ == rhs.next_backend_ &&
559
+ current_backendcomponent_idx_ == rhs.current_backendcomponent_idx_;
560
+ }
561
+ bool operator!=(const self_type& rhs) const {
562
+ return next_functionality_ != rhs.next_functionality_ ||
563
+ current_dispatchkey_idx_ != rhs.current_dispatchkey_idx_ ||
564
+ next_backend_ != rhs.next_backend_ ||
565
+ current_backendcomponent_idx_ != rhs.current_backendcomponent_idx_;
566
+ }
567
+ DispatchKey operator*() const {
568
+ auto functionality_key =
569
+ static_cast<DispatchKey>(current_dispatchkey_idx_);
570
+ if (isPerBackendFunctionalityKey(functionality_key)) {
571
+ auto next_key = toRuntimePerBackendFunctionalityKey(
572
+ functionality_key,
573
+ static_cast<BackendComponent>(current_backendcomponent_idx_));
574
+ // We expect all of the Dense, Sparse, Quantized, and Autograd keys to
575
+ // be ordered the same way with respect to their backends
576
+ TORCH_INTERNAL_ASSERT(
577
+ toBackendComponent(next_key) ==
578
+ static_cast<BackendComponent>(current_backendcomponent_idx_),
579
+ "Tried to map functionality key ",
580
+ toString(functionality_key),
581
+ " and backend bit ",
582
+ toString(
583
+ static_cast<BackendComponent>(current_backendcomponent_idx_)),
584
+ " to a runtime key, but ended up with ",
585
+ toString(next_key),
586
+ ". This can happen if the order of the backend dispatch keys in DispatchKey.h isn't consistent.",
587
+ " Please double check that enum for inconsistencies.");
588
+ return next_key;
589
+ } else {
590
+ return functionality_key;
591
+ }
592
+ }
593
+
594
+ private:
595
+ const uint64_t* data_ptr_;
596
+ uint8_t next_functionality_;
597
+ uint8_t next_backend_;
598
+ uint8_t current_dispatchkey_idx_;
599
+ uint8_t current_backendcomponent_idx_;
600
+ };
601
+
602
+ public:
603
+ // Returns iterator to the first key in the set. If no keys are in the
604
+ // set, then will return the end iterator.
605
+ iterator begin() const {
606
+ return iterator(&repr_);
607
+ }
608
+
609
+ // We do not need to iterate beyond EndOfFunctionalityKeys so we will treat
610
+ // this as the end iterator.
611
+ iterator end() const {
612
+ return iterator(&repr_, iterator::end_iter_mask_val);
613
+ }
614
+ };
615
+
616
+ C10_API std::string toString(DispatchKeySet);
617
+ C10_API std::ostream& operator<<(std::ostream&, DispatchKeySet);
618
+
619
+ C10_API inline int getDispatchTableIndexForDispatchKey(DispatchKey k) {
620
+ return DispatchKeySet(k).getDispatchTableIndexForDispatchKeySet();
621
+ }
622
+
623
+ // Alias key DispatchKey::Autograd maps to
624
+ // (autograd_dispatch_keyset x full_backend_mask)
625
+ // NB: keys in this set also get associated with CompositeImplicitAutograd
626
+ //
627
+ // Note [autograd_dispatch_keyset Does Not Include Backend Bits]
628
+ // We don't want to include any backend bits (BackendComponent::CPUBit, etc)
629
+ // directly in autograd_dispatch_keyset.
630
+ // Why? keysets like autograd_dispatch_keyset are commonly used to remove
631
+ // autograd keys from a DispatchKeySet throughout the code base. However, you
632
+ // are only allowed to remove functionality bits from a keyset, not backend
633
+ // bits. See Note [Removing keys from DispatchKeySet Only Affects Functionality
634
+ // Keys] for details. To be consistent and avoid confusion, we're explicitly
635
+ // setting up autograd_dispatch_keyset to not have any backend bits.
636
+ constexpr DispatchKeySet autograd_dispatch_keyset = DispatchKeySet({
637
+ DispatchKey::AutogradFunctionality,
638
+ DispatchKey::AutogradOther,
639
+ DispatchKey::AutogradNestedTensor,
640
+ });
641
+
642
+ constexpr DispatchKeySet autocast_dispatch_keyset = DispatchKeySet({
643
+ DispatchKey::AutocastCPU,
644
+ DispatchKey::AutocastCUDA,
645
+ DispatchKey::AutocastXPU,
646
+ DispatchKey::AutocastIPU,
647
+ DispatchKey::AutocastHPU,
648
+ DispatchKey::AutocastXLA,
649
+ DispatchKey::AutocastPrivateUse1,
650
+ });
651
+
652
+ // See Note [TLS Initialization]
653
+ constexpr DispatchKeySet default_included_set = DispatchKeySet({
654
+ DispatchKey::BackendSelect,
655
+ DispatchKey::ADInplaceOrView,
656
+ });
657
+
658
+ constexpr DispatchKeySet default_excluded_set = DispatchKeySet({
659
+ DispatchKey::AutocastCPU,
660
+ DispatchKey::AutocastCUDA,
661
+ DispatchKey::AutocastXPU,
662
+ DispatchKey::AutocastIPU,
663
+ DispatchKey::AutocastHPU,
664
+ DispatchKey::AutocastXLA,
665
+ DispatchKey::AutocastPrivateUse1,
666
+ });
667
+
668
+ constexpr DispatchKeySet autograd_dispatch_keyset_with_ADInplaceOrView =
669
+ autograd_dispatch_keyset | DispatchKeySet(DispatchKey::ADInplaceOrView);
670
+
671
+ constexpr DispatchKeySet python_ks = DispatchKeySet({
672
+ DispatchKey::Python,
673
+ DispatchKey::PythonTLSSnapshot,
674
+ });
675
+
676
+ constexpr DispatchKeySet sparse_ks = DispatchKeySet(DispatchKey::Sparse);
677
+
678
+ constexpr DispatchKeySet sparse_csr_ks =
679
+ DispatchKeySet({DispatchKey::SparseCsrCPU, DispatchKey::SparseCsrCUDA});
680
+
681
+ constexpr DispatchKeySet mkldnn_ks = DispatchKeySet(DispatchKey::MkldnnCPU);
682
+
683
+ // backend dispatch keys that map to DispatchKey::AutogradOther
684
+ // NB: keys in this set also get associated with CompositeImplicitAutograd
685
+ constexpr DispatchKeySet autogradother_backends =
686
+ DispatchKeySet(
687
+ // HIP and VE aren't in this list: they now have their own backend bits
688
+ // which means that they can now have their own Autograd keys.
689
+ // Technically, HIP will now redispatch to its own custom AutogradHIP
690
+ // slot in the runtime table.
691
+ {DispatchKey::FPGA,
692
+ DispatchKey::ORT,
693
+ DispatchKey::Vulkan,
694
+ DispatchKey::Metal,
695
+ DispatchKey::SparseCsrCPU,
696
+ DispatchKey::SparseCsrCUDA,
697
+ DispatchKey::CustomRNGKeyId,
698
+ DispatchKey::MkldnnCPU,
699
+ // Sparse and Quantized backends also live here.
700
+ DispatchKey::Sparse,
701
+ DispatchKey::Quantized})
702
+ // Including the backend bits because this keyset is used during op
703
+ // registration, which requires looping over all runtime autogradother
704
+ // backend keys.
705
+ | DispatchKeySet(DispatchKeySet::RAW, full_backend_mask);
706
+
707
+ // The set of dispatch keys that come after autograd
708
+ // n.b. this relies on the fact that AutogradOther is currently the lowest
709
+ // Autograd key
710
+ constexpr DispatchKeySet after_autograd_keyset =
711
+ DispatchKeySet(DispatchKeySet::FULL_AFTER, c10::DispatchKey::AutogradOther);
712
+
713
+ // The set of dispatch keys that come after ADInplaceOrView
714
+ constexpr DispatchKeySet after_ADInplaceOrView_keyset = DispatchKeySet(
715
+ DispatchKeySet::FULL_AFTER,
716
+ c10::DispatchKey::ADInplaceOrView);
717
+
718
+ // The set of dispatch keys that come after Functionalize
719
+ constexpr DispatchKeySet after_func_keyset =
720
+ DispatchKeySet(DispatchKeySet::FULL_AFTER, c10::DispatchKey::Functionalize)
721
+ .remove(
722
+ // NOTE: we also need to remove ADInplaceOrView from the keyset when
723
+ // redispatching after the func kernels. This is because we're not
724
+ // calling the same op; we originally called an inplace op, and now
725
+ // we aren't. The original key calculation figured out which keys
726
+ // were Fallthrough based on the inplace op. That means that it did
727
+ // not include the ADInPlaceOrView kernel as a fallthrough key.
728
+ // However, we WANT the ADInPlaceOrView kernel to be ignored now
729
+ // that we're calling an out-of-place op. Re-invoking
730
+ // Dispatcher::call would re-run the Fallthrough key calculation and
731
+ // get us that, But at::redispatch is more performant. We can get
732
+ // away with it by explicitly removing the key here.
733
+ c10::DispatchKey::ADInplaceOrView);
734
+
735
+ constexpr DispatchKeySet backend_bitset_mask =
736
+ DispatchKeySet(DispatchKeySet::RAW, (1ULL << num_backends) - 1);
737
+
738
+ constexpr auto inplace_or_view_ks =
739
+ DispatchKeySet(DispatchKey::ADInplaceOrView);
740
+ constexpr auto autograd_cpu_ks = DispatchKeySet(DispatchKey::AutogradCPU);
741
+ constexpr auto autograd_ipu_ks = DispatchKeySet(DispatchKey::AutogradIPU);
742
+ constexpr auto autograd_xpu_ks = DispatchKeySet(DispatchKey::AutogradXPU);
743
+ constexpr auto autograd_cuda_ks = DispatchKeySet(DispatchKey::AutogradCUDA);
744
+ constexpr auto autograd_xla_ks = DispatchKeySet(DispatchKey::AutogradXLA);
745
+ constexpr auto autograd_lazy_ks = DispatchKeySet(DispatchKey::AutogradLazy);
746
+ constexpr auto autograd_meta_ks = DispatchKeySet(DispatchKey::AutogradMeta);
747
+ constexpr auto autograd_mps_ks = DispatchKeySet(DispatchKey::AutogradMPS);
748
+ constexpr auto autograd_hpu_ks = DispatchKeySet(DispatchKey::AutogradHPU);
749
+ constexpr auto autograd_privateuse1_ks =
750
+ DispatchKeySet(DispatchKey::AutogradPrivateUse1);
751
+ constexpr auto autograd_privateuse2_ks =
752
+ DispatchKeySet(DispatchKey::AutogradPrivateUse2);
753
+ constexpr auto autograd_privateuse3_ks =
754
+ DispatchKeySet(DispatchKey::AutogradPrivateUse3);
755
+ constexpr auto autograd_other_ks = DispatchKeySet(DispatchKey::AutogradOther);
756
+ constexpr auto autograd_nested =
757
+ DispatchKeySet(DispatchKey::AutogradNestedTensor);
758
+ // keyset corresponding to functorch keys that have their own dedicated
759
+ // TensorImpl subclass.
760
+ constexpr auto functorch_transforms_ks = DispatchKeySet(
761
+ {DispatchKey::FuncTorchBatched,
762
+ DispatchKey::FuncTorchVmapMode,
763
+ DispatchKey::Batched,
764
+ DispatchKey::VmapMode,
765
+ DispatchKey::FuncTorchGradWrapper});
766
+
767
+ constexpr auto functorch_batched_ks =
768
+ DispatchKeySet({DispatchKey::FuncTorchBatched});
769
+
770
+ // This keyset has:
771
+ // (1) the functionality bits corresponding to backends (dense, sparse,
772
+ // quantized) (2) all of the backend bits set
773
+ constexpr DispatchKeySet backend_functionality_keys =
774
+ DispatchKeySet({
775
+ DispatchKey::Dense,
776
+ DispatchKey::Quantized,
777
+ DispatchKey::Sparse,
778
+ }) |
779
+ DispatchKeySet(DispatchKeySet::RAW, full_backend_mask);
780
+
781
+ struct OpTableOffsetAndMask {
782
+ uint16_t offset;
783
+ uint16_t backend_mask;
784
+ };
785
+
786
+ static_assert(
787
+ num_backends <= 16,
788
+ "Right now we expect the number of backends not to exceed 16. In the (unlikely) event"
789
+ " that this changes, the size of OpTableOffsetAndMask::backend_mask needs to be increased too.");
790
+
791
+ // true if t is a backend dispatch key
792
+ C10_API bool isBackendDispatchKey(DispatchKey t);
793
+
794
+ // Resolve alias dispatch key to DispatchKeySet if applicable
795
+ C10_API DispatchKeySet getRuntimeDispatchKeySet(DispatchKey t);
796
+
797
+ // Resolve alias dispatch key to DispatchKeySet if applicable,
798
+ // and check if k is a part of that set
799
+ C10_API bool runtimeDispatchKeySetHas(DispatchKey t, DispatchKey k);
800
+
801
+ // Returns a DispatchKeySet of all backend keys mapped to Autograd dispatch key
802
+ // t, DispatchKeySet is empty if t is not alias of DispatchKey::Autograd.
803
+ C10_API DispatchKeySet getBackendKeySetFromAutograd(DispatchKey t);
804
+
805
+ // Returns a DispatchKeySet of autograd related keys mapped to backend.
806
+ // for a given backend key, use the associated autograd key.
807
+ // for non-backend keys, use AutogradOther as a default.
808
+ // Note: it's convenient and fast to return a default here rather than (say)
809
+ // returning an optional<DispatchKey>, or throwing. But it makes callers
810
+ // responsible for either a) enforcing the invariant that only backend keys
811
+ // be passed as arguments, or b) interpreting our return value carefully.
812
+ inline DispatchKeySet getAutogradRelatedKeySetFromBackend(BackendComponent t) {
813
+ switch (t) {
814
+ case BackendComponent::CPUBit:
815
+ return inplace_or_view_ks | autograd_cpu_ks;
816
+ case BackendComponent::IPUBit:
817
+ return inplace_or_view_ks | autograd_ipu_ks;
818
+ case BackendComponent::XPUBit:
819
+ return inplace_or_view_ks | autograd_xpu_ks;
820
+ case BackendComponent::CUDABit:
821
+ return inplace_or_view_ks | autograd_cuda_ks;
822
+ case BackendComponent::XLABit:
823
+ return inplace_or_view_ks | autograd_xla_ks;
824
+ case BackendComponent::LazyBit:
825
+ return inplace_or_view_ks | autograd_lazy_ks;
826
+ case BackendComponent::MetaBit:
827
+ return inplace_or_view_ks | autograd_meta_ks;
828
+ case BackendComponent::MPSBit:
829
+ return inplace_or_view_ks | autograd_mps_ks;
830
+ case BackendComponent::HPUBit:
831
+ return inplace_or_view_ks | autograd_hpu_ks;
832
+ case BackendComponent::PrivateUse1Bit:
833
+ return inplace_or_view_ks | autograd_privateuse1_ks;
834
+ case BackendComponent::PrivateUse2Bit:
835
+ return inplace_or_view_ks | autograd_privateuse2_ks;
836
+ case BackendComponent::PrivateUse3Bit:
837
+ return inplace_or_view_ks | autograd_privateuse3_ks;
838
+ default:
839
+ return inplace_or_view_ks | autograd_other_ks;
840
+ }
841
+ }
842
+
843
+ // Returns a DispatchKeySet of autocast related keys mapped to backend.
844
+ inline DispatchKeySet getAutocastRelatedKeySetFromBackend(BackendComponent t) {
845
+ constexpr auto autocast_cpu_ks = DispatchKeySet(DispatchKey::AutocastCPU);
846
+ constexpr auto autocast_xpu_ks = DispatchKeySet(DispatchKey::AutocastXPU);
847
+ constexpr auto autocast_ipu_ks = DispatchKeySet(DispatchKey::AutocastIPU);
848
+ constexpr auto autocast_hpu_ks = DispatchKeySet(DispatchKey::AutocastHPU);
849
+ constexpr auto autocast_cuda_ks = DispatchKeySet(DispatchKey::AutocastCUDA);
850
+ constexpr auto autocast_xla_ks = DispatchKeySet(DispatchKey::AutocastXLA);
851
+ constexpr auto autocast_privateuse1_ks =
852
+ DispatchKeySet(DispatchKey::AutocastPrivateUse1);
853
+ switch (t) {
854
+ case BackendComponent::CPUBit:
855
+ return autocast_cpu_ks;
856
+ case BackendComponent::XPUBit:
857
+ return autocast_xpu_ks;
858
+ case BackendComponent::IPUBit:
859
+ return autocast_ipu_ks;
860
+ case BackendComponent::HPUBit:
861
+ return autocast_hpu_ks;
862
+ case BackendComponent::CUDABit:
863
+ return autocast_cuda_ks;
864
+ case BackendComponent::XLABit:
865
+ return autocast_xla_ks;
866
+ case BackendComponent::PrivateUse1Bit:
867
+ return autocast_privateuse1_ks;
868
+ default:
869
+ return DispatchKeySet();
870
+ }
871
+ }
872
+
873
+ // returns the "backend" DispatchKey of highest priority in the set.
874
+ // This is basically like highestBackendKey(), except that we have some
875
+ // "functionality" bits that correspond to backends (Sparse, Quantized)
876
+ inline DispatchKey highestPriorityBackendTypeId(DispatchKeySet ks) {
877
+ return (ks & backend_functionality_keys).highestPriorityTypeId();
878
+ }
879
+
880
+ // This API exists because we have a use case for checking
881
+ // getRuntimeDispatchKeySet(alias).has(DispatchKey::Undefined)
882
+ // in OperatorEntry.cpp but we disallow it in has() API.
883
+ C10_API bool isIncludedInAlias(DispatchKey k, DispatchKey alias);
884
+
885
+ // Historically, every tensor only had a single DispatchKey, and it was always
886
+ // something like CPU, and there wasn't any of this business where TLS
887
+ // could cause the DispatchKey of a tensor to change. But we still have some
888
+ // legacy code that is still using DispatchKey for things like instanceof
889
+ // checks; if at all possible, refactor the code to stop using DispatchKey in
890
+ // those cases.
891
+ static inline DispatchKey legacyExtractDispatchKey(DispatchKeySet s) {
892
+ // NB: If you add any extra keys that can be stored in TensorImpl on
893
+ // top of existing "backend" keys like CPU/CUDA, you need to add it
894
+ // here. At the moment, autograd keys and ADInplaceOrView key need this
895
+ // treatment;
896
+ return (s - autograd_dispatch_keyset_with_ADInplaceOrView -
897
+ autocast_dispatch_keyset -
898
+ DispatchKeySet(
899
+ {DispatchKey::Functionalize,
900
+ DispatchKey::PythonTLSSnapshot,
901
+ DispatchKey::Python}))
902
+ .highestPriorityTypeId();
903
+ }
904
+
905
+ template <class T>
906
+ using is_not_DispatchKeySet = guts::negation<std::is_same<DispatchKeySet, T>>;
907
+
908
+ // Given a function type, constructs a function_traits type that drops the first
909
+ // parameter type if the first parameter is of type DispatchKeySet. NB:
910
+ // DispatchKeySet is currently explicitly hidden from JIT (mainly to avoid
911
+ // pushing unnecessary arguments on the stack - see Note [ Plumbing Keys Through
912
+ // the Dispatcher] for details). If at any point in the future we need to expose
913
+ // this type to JIT, revisit the usage of this type alias.
914
+ template <class FuncType>
915
+ using remove_DispatchKeySet_arg_from_func = guts::make_function_traits_t<
916
+ typename guts::infer_function_traits_t<FuncType>::return_type,
917
+ typename std::conditional_t<
918
+ std::is_same<
919
+ DispatchKeySet,
920
+ typename guts::typelist::head_with_default_t<
921
+ void,
922
+ typename guts::infer_function_traits_t<
923
+ FuncType>::parameter_types>>::value,
924
+ guts::typelist::drop_if_nonempty_t<
925
+ typename guts::infer_function_traits_t<FuncType>::parameter_types,
926
+ 1>,
927
+ typename guts::infer_function_traits_t<FuncType>::parameter_types>>;
928
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/MemoryFormat.h ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Backend.h>
4
+ #include <c10/util/ArrayRef.h>
5
+ #include <c10/util/Exception.h>
6
+
7
+ #include <ostream>
8
+
9
+ // Memory format is not the property of a Tensor. It is the way to tell an
10
+ // operator how the result should be organized in memory and nothing more. That
11
+ // means memory format should never be used as return value for any tensor state
12
+ // interrogation functions (internally and externally).
13
+ //
14
+ // Possible options are:
15
+ // Preserve:
16
+ // If any of the input tensors is in channels_last format, operator output
17
+ // should be in channels_last format
18
+ //
19
+ // Contiguous:
20
+ // Regardless of input tensors format, the output should be contiguous
21
+ // Tensor.
22
+ //
23
+ // ChannelsLast:
24
+ // Regardless of input tensors format, the output should be in channels_last
25
+ // format.
26
+
27
+ namespace c10 {
28
+ enum class MemoryFormat : int8_t {
29
+ Contiguous,
30
+ Preserve,
31
+ ChannelsLast,
32
+ ChannelsLast3d,
33
+ NumOptions
34
+ };
35
+
36
+ // If you are seeing this, it means that this call site was not checked if
37
+ // the memory format could be preserved, and it was switched to old default
38
+ // behaviour of contiguous
39
+ #define LEGACY_CONTIGUOUS_MEMORY_FORMAT c10::get_contiguous_memory_format()
40
+
41
+ inline MemoryFormat get_contiguous_memory_format() {
42
+ return MemoryFormat::Contiguous;
43
+ }
44
+
45
+ inline std::ostream& operator<<(
46
+ std::ostream& stream,
47
+ at::MemoryFormat memory_format) {
48
+ switch (memory_format) {
49
+ case MemoryFormat::Preserve:
50
+ return stream << "Preserve";
51
+ case MemoryFormat::Contiguous:
52
+ return stream << "Contiguous";
53
+ case MemoryFormat::ChannelsLast:
54
+ return stream << "ChannelsLast";
55
+ case MemoryFormat::ChannelsLast3d:
56
+ return stream << "ChannelsLast3d";
57
+ default:
58
+ TORCH_CHECK(false, "Unknown memory format ", memory_format);
59
+ }
60
+ }
61
+
62
+ // Note: Hardcoded the channel last stride indices here to get better
63
+ // performance
64
+ template <typename T>
65
+ inline std::vector<T> get_channels_last_strides_2d(ArrayRef<T> sizes) {
66
+ std::vector<T> strides(sizes.size());
67
+ switch (sizes.size()) {
68
+ case 4:
69
+ strides[1] = 1;
70
+ strides[3] = sizes[1];
71
+ strides[2] = strides[3] * sizes[3];
72
+ strides[0] = strides[2] * sizes[2];
73
+ return strides;
74
+ case 3:
75
+ strides[0] = 1;
76
+ strides[2] = sizes[0];
77
+ strides[1] = strides[2] * sizes[2];
78
+ return strides;
79
+ default:
80
+ TORCH_INTERNAL_ASSERT(
81
+ false, "ChannelsLast2d doesn't support size ", sizes.size());
82
+ }
83
+ }
84
+
85
+ inline std::vector<int64_t> get_channels_last_strides_2d(IntArrayRef sizes) {
86
+ return get_channels_last_strides_2d<int64_t>(sizes);
87
+ }
88
+
89
+ template <typename T>
90
+ std::vector<T> get_channels_last_strides_3d(ArrayRef<T> sizes) {
91
+ std::vector<T> strides(sizes.size());
92
+ switch (sizes.size()) {
93
+ case 5:
94
+ strides[1] = 1;
95
+ strides[4] = sizes[1];
96
+ strides[3] = strides[4] * sizes[4];
97
+ strides[2] = strides[3] * sizes[3];
98
+ strides[0] = strides[2] * sizes[2];
99
+ return strides;
100
+ case 4:
101
+ strides[0] = 1;
102
+ strides[3] = sizes[0];
103
+ strides[2] = strides[3] * sizes[3];
104
+ strides[1] = strides[2] * sizes[2];
105
+ return strides;
106
+ default:
107
+ TORCH_INTERNAL_ASSERT(
108
+ false, "ChannelsLast3d doesn't support size ", sizes.size());
109
+ }
110
+ }
111
+
112
+ inline std::vector<int64_t> get_channels_last_strides_3d(IntArrayRef sizes) {
113
+ return get_channels_last_strides_3d<int64_t>(sizes);
114
+ }
115
+
116
+ // NOTE:
117
+ // Below are Helper functions for is_channels_last_strides_xd.
118
+ // 1. Please do not combine these helper functions, each helper function handles
119
+ // exactly one case of sizes + memory_format, by doing this, the strides indices
120
+ // will be a constant array and we can access it using constant index number,
121
+ // the compiler will fully unroll the loop on strides indices to gain a better
122
+ // performance.
123
+ // 2. No error check in helper function, caller ensures the correctness of the
124
+ // input
125
+ // 3. All helper functions have similar comments, only 1st helper function is
126
+ // commented here.
127
+ template <typename T>
128
+ inline bool is_channels_last_strides_2d_s4(
129
+ const ArrayRef<T> sizes,
130
+ const ArrayRef<T> strides) {
131
+ T min = 0;
132
+ // special case for trivial C dimension. default to NCHW
133
+ if (strides[1] == 0) {
134
+ return false;
135
+ }
136
+ // loop strides indices
137
+ for (auto& d : {1, 3, 2, 0}) {
138
+ if (sizes[d] == 0) {
139
+ return false;
140
+ }
141
+ if (strides[d] < min) {
142
+ return false;
143
+ }
144
+ // Fallback to NCHW as default layout for ambiguous cases
145
+ // This is the flaw of implicit memory_format from strides.
146
+ // N111 tensor with identical strides for size 1 dimension;
147
+ // Two cases could lead us here:
148
+ // a. N111 contiguous Tensor ([N,1,1,1]@[1,1,1,1])
149
+ // b. N11W contiguous Tensor sliced on the W-dimension.
150
+ // ([N,1,1,1]@[W,W,W,W])
151
+ if (d == 0 && min == strides[1]) {
152
+ return false;
153
+ }
154
+ // This is necessary to:
155
+ // 1. distinguish the memory_format of N1H1;
156
+ // [H, 1, 1, 1] channels_last stride
157
+ // [H, H, 1, 1] contiguous stride
158
+ // 2. permutation of 1C1W:
159
+ // [1, C, 1, H]@[HC, H, H, 1] transpose(1, 3)
160
+ // [1, H, 1, C]@[HC, 1, H, H] shouldn't be identified as channels_last
161
+ min = strides[d];
162
+ if (sizes[d] > 1) {
163
+ min *= sizes[d];
164
+ }
165
+ }
166
+ return true;
167
+ }
168
+
169
+ template <typename T>
170
+ inline bool is_channels_last_strides_3d_s5(
171
+ const ArrayRef<T> sizes,
172
+ const ArrayRef<T> strides) {
173
+ T min = 0;
174
+ if (strides[1] == 0) {
175
+ return false;
176
+ }
177
+ for (auto& d : {1, 4, 3, 2, 0}) {
178
+ if (sizes[d] == 0) {
179
+ return false;
180
+ }
181
+ if (strides[d] < min) {
182
+ return false;
183
+ }
184
+ if (d == 0 && min == strides[1]) {
185
+ return false;
186
+ }
187
+ min = strides[d];
188
+ if (sizes[d] > 1) {
189
+ min *= sizes[d];
190
+ }
191
+ }
192
+ return true;
193
+ }
194
+
195
+ // Note [Ambiguous is_channels_last_strides_xd]
196
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
197
+ // The flaw of carrying memory_format implicitly through strides is very hard
198
+ // to WAR properly. issue #24090
199
+ // Without the history of permutation, we can't infer the memory_format of a
200
+ // tensor from the snapshot of its size & stride
201
+ // e.g.
202
+ //
203
+ // 1. We can NOT specify the memory_format of N111 tensor through strides in a
204
+ // meaningful way;
205
+ //
206
+ // 2. Two path that ended up with identical size/stride
207
+ // N11W contiguous tensor sliced at w-dimension becomes [N,1,1,1]@[W,W,W,W]
208
+ // NC11 channels_last tensor sliced at c-dimension becomes [N,1,1,1]@[C,C,C,C]
209
+ // So if we see a tensor [N,1,1,1]@[X,X,X,X], there's no way for us to infer
210
+ // the memory_format of the original tensor.
211
+ //
212
+ // Due to the limitations, our temporary WAR `is_channels_last_strides` does the
213
+ // best effort to infer whether the original memory_format of a tensor is
214
+ // at::MemoryFormat::ChannelsLast. The two objectives of this function (ordered
215
+ // by their importance):
216
+ // 1. Ensure that normal shape manipulation does not accidentally change the
217
+ // MemoryFormat of an existing tensor.
218
+ // 2. Allows user to mark MemoryFormat::ChannelsLast to tensors;
219
+ //
220
+ // The function does so via checking strides of the tensor, including strides of
221
+ // size-1 dimensions. Although conventionally PyTorch implies no restriction on
222
+ // trivial stride (stride for size-1 dimension).
223
+ //
224
+ // Note that this approach is a compromise. We did not solve the problem
225
+ // completely. Many cases we will not be able to infer the correct memory
226
+ // format.
227
+ // The implementation of `is_channels_last_strides` is to serve the objectives:
228
+ // MemoryFormat::ChannelsLast has to be explicitly opted-in (no accidental
229
+ // conversion); Best effort to maintain the ChannelsLast flag.
230
+ //
231
+ // Due to the fact that this is not a bulletproof solution, through testing
232
+ // (aten/src/ATen/test/memory_format_test.cpp)
233
+ // a. we ensure that the common tasks are supported;
234
+ // a. we identify corner cases where the implementation compromises on.
235
+ //
236
+ // By the time accumulated permutation is enabled to replace implicit
237
+ // memory_format through strides, we should be updating our tests and fix the
238
+ // issues in our tests.
239
+ //
240
+ // We use Channels Last 2d as an example above.
241
+ // This is a general problem for all the is_channels_last_strides_xd
242
+ // implementation. Please check the helper functions
243
+ // (is_channels_last_strides_*d_s*) for more details.
244
+
245
+ template <typename T>
246
+ inline bool is_channels_last_strides_2d(
247
+ const ArrayRef<T> sizes,
248
+ const ArrayRef<T> strides) {
249
+ switch (sizes.size()) {
250
+ case 4:
251
+ return is_channels_last_strides_2d_s4(sizes, strides);
252
+ case 3:
253
+ // TODO dim == 3 case will be enabled once it is fully tested
254
+ return false;
255
+ default:
256
+ return false;
257
+ }
258
+ }
259
+
260
+ template <typename T>
261
+ inline bool is_channels_last_strides_3d(
262
+ const ArrayRef<T> sizes,
263
+ const ArrayRef<T> strides) {
264
+ switch (sizes.size()) {
265
+ case 5:
266
+ return is_channels_last_strides_3d_s5(sizes, strides);
267
+ case 4:
268
+ // TODO dim == 4 case will be enabled once it is fully tested
269
+ return false;
270
+ default:
271
+ return false;
272
+ }
273
+ }
274
+
275
+ inline bool is_channels_last_strides_2d(
276
+ const IntArrayRef sizes,
277
+ const IntArrayRef strides) {
278
+ return is_channels_last_strides_2d<int64_t>(sizes, strides);
279
+ }
280
+
281
+ inline bool is_channels_last_strides_3d(
282
+ const IntArrayRef sizes,
283
+ const IntArrayRef strides) {
284
+ return is_channels_last_strides_3d<int64_t>(sizes, strides);
285
+ }
286
+
287
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/QEngine.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/DeviceType.h>
4
+ #include <c10/core/DispatchKey.h>
5
+ #include <c10/util/Exception.h>
6
+
7
+ namespace c10 {
8
+
9
+ /**
10
+ * QEngine is an enum that is used to select the engine to run quantized ops.
11
+ * Keep this enum in sync with get_qengine_id() in
12
+ * torch/backends/quantized/__init__.py
13
+ */
14
+ enum class QEngine : uint8_t {
15
+ NoQEngine = 0,
16
+ FBGEMM = 1,
17
+ QNNPACK = 2,
18
+ ONEDNN = 3,
19
+ X86 = 4,
20
+ };
21
+
22
+ constexpr auto kNoQEngine = QEngine::NoQEngine;
23
+ constexpr auto kFBGEMM = QEngine::FBGEMM;
24
+ constexpr auto kQNNPACK = QEngine::QNNPACK;
25
+ constexpr auto kONEDNN = QEngine::ONEDNN;
26
+ constexpr auto kX86 = QEngine::X86;
27
+
28
+ inline std::string toString(QEngine qengine) {
29
+ switch (qengine) {
30
+ case kNoQEngine:
31
+ return "NoQEngine";
32
+ case kFBGEMM:
33
+ return "FBGEMM";
34
+ case kQNNPACK:
35
+ return "QNNPACK";
36
+ case kONEDNN:
37
+ return "ONEDNN";
38
+ case kX86:
39
+ return "X86";
40
+ default:
41
+ TORCH_CHECK(
42
+ false, "Unrecognized Quantized Engine: ", static_cast<int>(qengine));
43
+ }
44
+ }
45
+
46
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/Scalar.h ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <stdint.h>
4
+ #include <stdexcept>
5
+ #include <type_traits>
6
+ #include <utility>
7
+
8
+ #include <c10/core/OptionalRef.h>
9
+ #include <c10/core/ScalarType.h>
10
+ #include <c10/core/SymFloat.h>
11
+ #include <c10/core/SymInt.h>
12
+ #include <c10/macros/Macros.h>
13
+ #include <c10/util/Exception.h>
14
+ #include <c10/util/Half.h>
15
+ #include <c10/util/TypeCast.h>
16
+ #include <c10/util/intrusive_ptr.h>
17
+
18
+ C10_CLANG_DIAGNOSTIC_PUSH()
19
+ #if C10_CLANG_HAS_WARNING("-Wimplicit-int-float-conversion")
20
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-int-float-conversion")
21
+ #endif
22
+
23
+ namespace c10 {
24
+
25
+ /**
26
+ * Scalar represents a 0-dimensional tensor which contains a single element.
27
+ * Unlike a tensor, numeric literals (in C++) are implicitly convertible to
28
+ * Scalar (which is why, for example, we provide both add(Tensor) and
29
+ * add(Scalar) overloads for many operations). It may also be used in
30
+ * circumstances where you statically know a tensor is 0-dim and single size,
31
+ * but don't know its type.
32
+ */
33
+ class C10_API Scalar {
34
+ public:
35
+ Scalar() : Scalar(int64_t(0)) {}
36
+
37
+ void destroy() {
38
+ if (Tag::HAS_si == tag || Tag::HAS_sd == tag || Tag::HAS_sb == tag) {
39
+ raw::intrusive_ptr::decref(v.p);
40
+ v.p = nullptr;
41
+ }
42
+ }
43
+
44
+ ~Scalar() {
45
+ destroy();
46
+ }
47
+
48
+ #define DEFINE_IMPLICIT_CTOR(type, name) \
49
+ Scalar(type vv) : Scalar(vv, true) {}
50
+
51
+ AT_FORALL_SCALAR_TYPES_AND7(
52
+ Half,
53
+ BFloat16,
54
+ Float8_e5m2,
55
+ Float8_e4m3fn,
56
+ Float8_e5m2fnuz,
57
+ Float8_e4m3fnuz,
58
+ ComplexHalf,
59
+ DEFINE_IMPLICIT_CTOR)
60
+ AT_FORALL_COMPLEX_TYPES(DEFINE_IMPLICIT_CTOR)
61
+
62
+ #undef DEFINE_IMPLICIT_CTOR
63
+
64
+ // Value* is both implicitly convertible to SymbolicVariable and bool which
65
+ // causes ambiguity error. Specialized constructor for bool resolves this
66
+ // problem.
67
+ template <
68
+ typename T,
69
+ typename std::enable_if<std::is_same<T, bool>::value, bool>::type* =
70
+ nullptr>
71
+ Scalar(T vv) : tag(Tag::HAS_b) {
72
+ v.i = convert<int64_t, bool>(vv);
73
+ }
74
+
75
+ template <
76
+ typename T,
77
+ typename std::enable_if<std::is_same<T, c10::SymBool>::value, bool>::
78
+ type* = nullptr>
79
+ Scalar(T vv) : tag(Tag::HAS_sb) {
80
+ v.i = convert<int64_t, c10::SymBool>(vv);
81
+ }
82
+
83
+ #define DEFINE_ACCESSOR(type, name) \
84
+ type to##name() const { \
85
+ if (Tag::HAS_d == tag) { \
86
+ return checked_convert<type, double>(v.d, #type); \
87
+ } else if (Tag::HAS_z == tag) { \
88
+ return checked_convert<type, c10::complex<double>>(v.z, #type); \
89
+ } \
90
+ if (Tag::HAS_b == tag) { \
91
+ return checked_convert<type, bool>(v.i, #type); \
92
+ } else if (Tag::HAS_i == tag) { \
93
+ return checked_convert<type, int64_t>(v.i, #type); \
94
+ } else if (Tag::HAS_si == tag) { \
95
+ return checked_convert<type, int64_t>( \
96
+ toSymInt().guard_int(__FILE__, __LINE__), #type); \
97
+ } else if (Tag::HAS_sd == tag) { \
98
+ return checked_convert<type, int64_t>( \
99
+ toSymFloat().guard_float(__FILE__, __LINE__), #type); \
100
+ } else if (Tag::HAS_sb == tag) { \
101
+ return checked_convert<type, int64_t>( \
102
+ toSymBool().guard_bool(__FILE__, __LINE__), #type); \
103
+ } \
104
+ TORCH_CHECK(false) \
105
+ }
106
+
107
+ // TODO: Support ComplexHalf accessor
108
+ AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(DEFINE_ACCESSOR)
109
+
110
+ #undef DEFINE_ACCESSOR
111
+
112
+ SymInt toSymInt() const {
113
+ if (Tag::HAS_si == tag) {
114
+ return c10::SymInt(intrusive_ptr<SymNodeImpl>::reclaim_copy(
115
+ static_cast<SymNodeImpl*>(v.p)));
116
+ } else {
117
+ return toLong();
118
+ }
119
+ }
120
+
121
+ SymFloat toSymFloat() const {
122
+ if (Tag::HAS_sd == tag) {
123
+ return c10::SymFloat(intrusive_ptr<SymNodeImpl>::reclaim_copy(
124
+ static_cast<SymNodeImpl*>(v.p)));
125
+ } else {
126
+ return toDouble();
127
+ }
128
+ }
129
+
130
+ SymBool toSymBool() const {
131
+ if (Tag::HAS_sb == tag) {
132
+ return c10::SymBool(intrusive_ptr<SymNodeImpl>::reclaim_copy(
133
+ static_cast<SymNodeImpl*>(v.p)));
134
+ } else {
135
+ return toBool();
136
+ }
137
+ }
138
+
139
+ // also support scalar.to<int64_t>();
140
+ // Deleted for unsupported types, but specialized below for supported types
141
+ template <typename T>
142
+ T to() const = delete;
143
+
144
+ // audit uses of data_ptr
145
+ const void* data_ptr() const {
146
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
147
+ return static_cast<const void*>(&v);
148
+ }
149
+
150
+ bool isFloatingPoint() const {
151
+ return Tag::HAS_d == tag || Tag::HAS_sd == tag;
152
+ }
153
+
154
+ C10_DEPRECATED_MESSAGE(
155
+ "isIntegral is deprecated. Please use the overload with 'includeBool' parameter instead.")
156
+ bool isIntegral() const {
157
+ return Tag::HAS_i == tag || Tag::HAS_si == tag;
158
+ }
159
+ bool isIntegral(bool includeBool) const {
160
+ return Tag::HAS_i == tag || Tag::HAS_si == tag ||
161
+ (includeBool && isBoolean());
162
+ }
163
+
164
+ bool isComplex() const {
165
+ return Tag::HAS_z == tag;
166
+ }
167
+ bool isBoolean() const {
168
+ return Tag::HAS_b == tag || Tag::HAS_sb == tag;
169
+ }
170
+
171
+ // you probably don't actually want these; they're mostly for testing
172
+ bool isSymInt() const {
173
+ return Tag::HAS_si == tag;
174
+ }
175
+ bool isSymFloat() const {
176
+ return Tag::HAS_sd == tag;
177
+ }
178
+ bool isSymBool() const {
179
+ return Tag::HAS_sb == tag;
180
+ }
181
+
182
+ bool isSymbolic() const {
183
+ return Tag::HAS_si == tag || Tag::HAS_sd == tag || Tag::HAS_sb == tag;
184
+ }
185
+
186
+ C10_ALWAYS_INLINE Scalar& operator=(Scalar&& other) noexcept {
187
+ if (&other == this) {
188
+ return *this;
189
+ }
190
+
191
+ destroy();
192
+ moveFrom(std::move(other));
193
+ return *this;
194
+ }
195
+
196
+ C10_ALWAYS_INLINE Scalar& operator=(const Scalar& other) {
197
+ if (&other == this) {
198
+ return *this;
199
+ }
200
+
201
+ *this = Scalar(other);
202
+ return *this;
203
+ }
204
+
205
+ Scalar operator-() const;
206
+ Scalar conj() const;
207
+ Scalar log() const;
208
+
209
+ template <
210
+ typename T,
211
+ typename std::enable_if<!c10::is_complex<T>::value, int>::type = 0>
212
+ bool equal(T num) const {
213
+ if (isComplex()) {
214
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
215
+ auto val = v.z;
216
+ return (val.real() == num) && (val.imag() == T());
217
+ } else if (isFloatingPoint()) {
218
+ TORCH_CHECK(!isSymbolic(), "NYI SymFloat equality");
219
+ return v.d == num;
220
+ } else if (isIntegral(/*includeBool=*/false)) {
221
+ TORCH_CHECK(!isSymbolic(), "NYI SymInt equality");
222
+ return v.i == num;
223
+ } else if (isBoolean()) {
224
+ // boolean scalar does not equal to a non boolean value
225
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
226
+ return false;
227
+ } else {
228
+ TORCH_INTERNAL_ASSERT(false);
229
+ }
230
+ }
231
+
232
+ template <
233
+ typename T,
234
+ typename std::enable_if<c10::is_complex<T>::value, int>::type = 0>
235
+ bool equal(T num) const {
236
+ if (isComplex()) {
237
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
238
+ return v.z == num;
239
+ } else if (isFloatingPoint()) {
240
+ TORCH_CHECK(!isSymbolic(), "NYI SymFloat equality");
241
+ return (v.d == num.real()) && (num.imag() == T());
242
+ } else if (isIntegral(/*includeBool=*/false)) {
243
+ TORCH_CHECK(!isSymbolic(), "NYI SymInt equality");
244
+ return (v.i == num.real()) && (num.imag() == T());
245
+ } else if (isBoolean()) {
246
+ // boolean scalar does not equal to a non boolean value
247
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
248
+ return false;
249
+ } else {
250
+ TORCH_INTERNAL_ASSERT(false);
251
+ }
252
+ }
253
+
254
+ bool equal(bool num) const {
255
+ if (isBoolean()) {
256
+ TORCH_INTERNAL_ASSERT(!isSymbolic());
257
+ return static_cast<bool>(v.i) == num;
258
+ } else {
259
+ return false;
260
+ }
261
+ }
262
+
263
+ ScalarType type() const {
264
+ if (isComplex()) {
265
+ return ScalarType::ComplexDouble;
266
+ } else if (isFloatingPoint()) {
267
+ return ScalarType::Double;
268
+ } else if (isIntegral(/*includeBool=*/false)) {
269
+ return ScalarType::Long;
270
+ } else if (isBoolean()) {
271
+ return ScalarType::Bool;
272
+ } else {
273
+ throw std::runtime_error("Unknown scalar type.");
274
+ }
275
+ }
276
+
277
+ Scalar(Scalar&& rhs) noexcept : tag(rhs.tag) {
278
+ moveFrom(std::move(rhs));
279
+ }
280
+
281
+ Scalar(const Scalar& rhs) : tag(rhs.tag), v(rhs.v) {
282
+ if (isSymbolic()) {
283
+ c10::raw::intrusive_ptr::incref(v.p);
284
+ }
285
+ }
286
+
287
+ Scalar(c10::SymInt si) {
288
+ if (auto m = si.maybe_as_int()) {
289
+ tag = Tag::HAS_i;
290
+ v.i = *m;
291
+ } else {
292
+ tag = Tag::HAS_si;
293
+ v.p = std::move(si).release();
294
+ }
295
+ }
296
+
297
+ Scalar(c10::SymFloat sd) {
298
+ if (sd.is_symbolic()) {
299
+ tag = Tag::HAS_sd;
300
+ v.p = std::move(sd).release();
301
+ } else {
302
+ tag = Tag::HAS_d;
303
+ v.d = sd.as_float_unchecked();
304
+ }
305
+ }
306
+
307
+ Scalar(c10::SymBool sb) {
308
+ if (auto m = sb.maybe_as_bool()) {
309
+ tag = Tag::HAS_b;
310
+ v.i = *m;
311
+ } else {
312
+ tag = Tag::HAS_sb;
313
+ v.p = std::move(sb).release();
314
+ }
315
+ }
316
+
317
+ // We can't set v in the initializer list using the
318
+ // syntax v{ .member = ... } because it doesn't work on MSVC
319
+ private:
320
+ enum class Tag { HAS_d, HAS_i, HAS_z, HAS_b, HAS_sd, HAS_si, HAS_sb };
321
+
322
+ // NB: assumes that self has already been cleared
323
+ C10_ALWAYS_INLINE void moveFrom(Scalar&& rhs) noexcept {
324
+ v = rhs.v;
325
+ tag = rhs.tag;
326
+ if (rhs.tag == Tag::HAS_si || rhs.tag == Tag::HAS_sd ||
327
+ rhs.tag == Tag::HAS_sb) {
328
+ // Move out of scalar
329
+ rhs.tag = Tag::HAS_i;
330
+ rhs.v.i = 0;
331
+ }
332
+ }
333
+
334
+ Tag tag;
335
+
336
+ union v_t {
337
+ double d{};
338
+ int64_t i;
339
+ c10::complex<double> z;
340
+ c10::intrusive_ptr_target* p;
341
+ v_t() {} // default constructor
342
+ } v;
343
+
344
+ template <
345
+ typename T,
346
+ typename std::enable_if<
347
+ std::is_integral<T>::value && !std::is_same<T, bool>::value,
348
+ bool>::type* = nullptr>
349
+ Scalar(T vv, bool) : tag(Tag::HAS_i) {
350
+ v.i = convert<decltype(v.i), T>(vv);
351
+ }
352
+
353
+ template <
354
+ typename T,
355
+ typename std::enable_if<
356
+ !std::is_integral<T>::value && !c10::is_complex<T>::value,
357
+ bool>::type* = nullptr>
358
+ Scalar(T vv, bool) : tag(Tag::HAS_d) {
359
+ v.d = convert<decltype(v.d), T>(vv);
360
+ }
361
+
362
+ template <
363
+ typename T,
364
+ typename std::enable_if<c10::is_complex<T>::value, bool>::type* = nullptr>
365
+ Scalar(T vv, bool) : tag(Tag::HAS_z) {
366
+ v.z = convert<decltype(v.z), T>(vv);
367
+ }
368
+ };
369
+
370
+ using OptionalScalarRef = c10::OptionalRef<Scalar>;
371
+
372
+ // define the scalar.to<int64_t>() specializations
373
+ #define DEFINE_TO(T, name) \
374
+ template <> \
375
+ inline T Scalar::to<T>() const { \
376
+ return to##name(); \
377
+ }
378
+ AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(DEFINE_TO)
379
+ #undef DEFINE_TO
380
+
381
+ } // namespace c10
382
+
383
+ C10_CLANG_DIAGNOSTIC_POP()
videollama2/lib/python3.10/site-packages/torch/include/c10/core/SingletonSymNodeImpl.h ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <c10/core/ConstantSymNodeImpl.h>
2
+ #include <c10/core/SymBool.h>
3
+ #include <c10/core/SymNodeImpl.h>
4
+ #include <iostream>
5
+
6
+ namespace c10 {
7
+
8
+ // The motivating usecase for this is to represent the ragged size structure
9
+ // of a jagged tensor [B, [s_0, s_1, s_2], D] as a single integer j0. This
10
+ // allows us to simply return [B, j0, D] if someone queries for the size of our
11
+ // tensor.
12
+ //
13
+ // Morally we define comparison between two singleton ints to return true if
14
+ // that comparison holds for all corresponding elements of the arrays they
15
+ // represent. Comparison between a singleton int and a plain int is defined
16
+ // similarly.
17
+ //
18
+ // To simulate this desired behavior but also avoid the O(N) cost of checking,
19
+ // we associate each raggedness pattern with an integer "id" that can be used as
20
+ // a proxy to evaluate equality. We also constrain the range of values for this
21
+ // as to enable inequality checks.
22
+ //
23
+ // We also support a positive integer scalar "coeff" that is used for computing
24
+ // strides. For example given, a [B, j0, D] tensor, it can be strided in two
25
+ // different ways: [D * j0, D, 1] and [j0, 1, sum(j0)]. The coeff is used to
26
+ // differentiate the two cases.
27
+ //
28
+ // During tracing the strides of the outputs need to be a function of the size
29
+ // and strides of the inputs so it is important that SingletonSymNode itself is
30
+ // able to express this.
31
+ class C10_API SingletonSymNodeImpl : public SymNodeImpl {
32
+ public:
33
+ // CAUTION: you should probably not be constructing these directly; please
34
+ // the higher-level API in python instead (TODO: actually introduce that).
35
+ explicit SingletonSymNodeImpl(int64_t val, int64_t coeff)
36
+ : val_(val), coeff_(coeff) {}
37
+
38
+ bool bool_() override {
39
+ return false;
40
+ }
41
+
42
+ bool is_int() override {
43
+ return true;
44
+ }
45
+
46
+ bool is_float() override {
47
+ return false;
48
+ }
49
+
50
+ bool is_bool() override {
51
+ return false;
52
+ }
53
+
54
+ bool has_hint() override {
55
+ return true;
56
+ }
57
+
58
+ c10::SymNode wrap_int(int64_t num) override {
59
+ return SymNode(c10::make_intrusive<ConstantSymNodeImpl<int64_t>>(num));
60
+ };
61
+
62
+ int64_t guard_int(const char* file, int64_t line) override {
63
+ TORCH_CHECK(false);
64
+ }
65
+
66
+ double guard_float(const char* file, int64_t line) override {
67
+ TORCH_CHECK(false, "not a float");
68
+ }
69
+
70
+ bool guard_bool(const char* file, int64_t line) override {
71
+ TORCH_CHECK(false, "not a bool");
72
+ }
73
+
74
+ int64_t int_() override {
75
+ TORCH_CHECK(false);
76
+ }
77
+
78
+ std::string str() override {
79
+ if (coeff_ == 1) {
80
+ return "j" + std::to_string(val_);
81
+ }
82
+ return std::to_string(coeff_) + "*j" + std::to_string(val_);
83
+ }
84
+
85
+ // NOTE [ Inequalities with SingletonInt ]
86
+ //
87
+ // The semantics of SingletonInt when it comes to relations is that it is
88
+ // treated as integer known to be within a certain range,
89
+ //
90
+ // j0 \in [2, int64_t::max]
91
+ //
92
+ // allowing us to answer queries like j0 >= 1 (True), and j0 == 0 (False).
93
+ // This is a useful default range for the raggedness pattern of a jagged
94
+ // tensor (1) since sizes are non-negative, and (2) we need to get past 0/1
95
+ // specialization checks.
96
+ //
97
+ // [ Indeterminate inequalities error out ]
98
+ //
99
+ // Given the semantic defined above, certain relations like j0 < 3 are thus
100
+ // indeterminable. In our impl today, evaluating such relations error
101
+ //
102
+ // It may seem convenient to just define indeterminate relations to return
103
+ // False, but the implementation we maintain in parallel using sympy does not
104
+ // allow this.
105
+ //
106
+ // Sympy only allows overriding of Ge. The other relations (Lt, Gt, Le) are,
107
+ // by consequence, all derived from Ge e.g., Lt(a, b) := !Ge(a, b). This
108
+ // would mean that means that if we define the indeterminate j0 >= 3 to be
109
+ // False, the also indeterminate j0 < 3 will be evaluated to be True!
110
+ //
111
+ // [ Coefficient are assumed positive ]
112
+ //
113
+ // For the purpose of computing inequalities, we consider the coefficient of
114
+ // the SingletonInt to be a positive integer.
115
+ //
116
+ // Thus, no modifications are needed to the logic since
117
+ // j0 >= k implies coeff * j0 >= k
118
+ //
119
+ c10::SymNode eq(const c10::SymNode& other) override;
120
+ c10::SymNode ne(const c10::SymNode& other) override;
121
+ c10::SymNode ge(const c10::SymNode& other) override;
122
+ c10::SymNode gt(const c10::SymNode& other) override;
123
+ c10::SymNode lt(const c10::SymNode& other) override;
124
+ c10::SymNode le(const c10::SymNode& other) override;
125
+ c10::SymNode mul(const c10::SymNode& other) override;
126
+
127
+ c10::optional<int64_t> singleton_int() override {
128
+ return val_;
129
+ }
130
+
131
+ c10::optional<int64_t> singleton_coeff() override {
132
+ return coeff_;
133
+ }
134
+
135
+ bool is_symbolic() override {
136
+ return false;
137
+ }
138
+
139
+ #define DEFINE_BINARY_NOT_SUPPORTED(name) \
140
+ c10::SymNode name(const c10::SymNode& other) override { \
141
+ TORCH_CHECK(false, #name " not supported by SingletonSymNode"); \
142
+ }
143
+
144
+ DEFINE_BINARY_NOT_SUPPORTED(add)
145
+ DEFINE_BINARY_NOT_SUPPORTED(sub)
146
+ DEFINE_BINARY_NOT_SUPPORTED(truediv)
147
+ DEFINE_BINARY_NOT_SUPPORTED(pow)
148
+ DEFINE_BINARY_NOT_SUPPORTED(floordiv)
149
+ DEFINE_BINARY_NOT_SUPPORTED(mod)
150
+ DEFINE_BINARY_NOT_SUPPORTED(sym_min)
151
+ DEFINE_BINARY_NOT_SUPPORTED(sym_max)
152
+ DEFINE_BINARY_NOT_SUPPORTED(sym_and)
153
+ DEFINE_BINARY_NOT_SUPPORTED(sym_or)
154
+
155
+ #undef DEFINE_BINARY_NOT_SUPPORTED
156
+
157
+ #define DEFINE_NOT_SUPPORTED(name) \
158
+ c10::SymNode name() override { \
159
+ TORCH_CHECK(false, #name " is not supported by SingletonSymNode"); \
160
+ }
161
+
162
+ DEFINE_NOT_SUPPORTED(sym_not)
163
+ DEFINE_NOT_SUPPORTED(ceil)
164
+ DEFINE_NOT_SUPPORTED(floor)
165
+ DEFINE_NOT_SUPPORTED(neg)
166
+ DEFINE_NOT_SUPPORTED(clone)
167
+ DEFINE_NOT_SUPPORTED(sym_float)
168
+
169
+ #undef DEFINE_NOT_SUPPORTED
170
+
171
+ private:
172
+ int64_t val_;
173
+ int64_t coeff_;
174
+ };
175
+
176
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/StorageImpl.h ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Allocator.h>
4
+ #include <c10/core/SymInt.h>
5
+ #include <c10/core/impl/PyObjectSlot.h>
6
+
7
+ #include <c10/util/intrusive_ptr.h>
8
+
9
+ namespace c10 {
10
+
11
+ // A storage represents the underlying backing data buffer for a
12
+ // tensor. This concept was inherited from the original Torch7
13
+ // codebase; we'd kind of like to get rid of the concept
14
+ // (see https://github.com/pytorch/pytorch/issues/14797) but
15
+ // it's hard work and no one has gotten around to doing it.
16
+ //
17
+ // NB: storage is supposed to uniquely own a data pointer; e.g.,
18
+ // two non-null data pointers alias if and only if they are from
19
+ // the same storage. Technically you can violate this invariant
20
+ // (e.g., you can create a non-owning StorageImpl with at::from_blob)
21
+ // but a lot of things won't work correctly, including:
22
+ //
23
+ // - An ordinary deleter on such a storage is wrong, because normal deleters
24
+ // assume unique ownership, but if you have two storages at the same data,
25
+ // that implies there is some sort of shared ownership. So your deleter would
26
+ // have to actually be internally doing some sort of refcount thing
27
+ // - Deepcopy in Python side relies on storage equality and not data pointer
28
+ // equality; so if there are two separate storages pointing to the same data,
29
+ // the data will actually get duplicated in that case (one data ptr before,
30
+ // two data ptrs after)
31
+ // - Version counts won't work correctly, because we do all VC tracking at the
32
+ // level of storages (unless you explicitly disconnect the VC with detach);
33
+ // mutation because data pointers are the same are totally untracked
34
+ struct C10_API StorageImpl : public c10::intrusive_ptr_target {
35
+ public:
36
+ struct use_byte_size_t {};
37
+
38
+ StorageImpl(
39
+ use_byte_size_t /*use_byte_size*/,
40
+ SymInt size_bytes,
41
+ at::DataPtr data_ptr,
42
+ at::Allocator* allocator,
43
+ bool resizable)
44
+ : data_ptr_(std::move(data_ptr)),
45
+ size_bytes_(std::move(size_bytes)),
46
+ size_bytes_is_heap_allocated_(size_bytes_.is_heap_allocated()),
47
+ resizable_(resizable),
48
+ received_cuda_(false),
49
+ allocator_(allocator) {
50
+ if (resizable) {
51
+ TORCH_INTERNAL_ASSERT(
52
+ allocator_, "For resizable storage, allocator must be provided");
53
+ }
54
+ }
55
+
56
+ StorageImpl(
57
+ use_byte_size_t /*use_byte_size*/,
58
+ const SymInt& size_bytes,
59
+ at::Allocator* allocator,
60
+ bool resizable)
61
+ : StorageImpl(
62
+ use_byte_size_t(),
63
+ size_bytes,
64
+ size_bytes.is_heap_allocated()
65
+ ? allocator->allocate(0)
66
+ : allocator->allocate(size_bytes.as_int_unchecked()),
67
+ allocator,
68
+ resizable) {}
69
+
70
+ StorageImpl& operator=(StorageImpl&& other) = delete;
71
+ StorageImpl& operator=(const StorageImpl&) = delete;
72
+ StorageImpl() = delete;
73
+ StorageImpl(StorageImpl&& other) = delete;
74
+ StorageImpl(const StorageImpl&) = delete;
75
+ ~StorageImpl() override = default;
76
+
77
+ void reset() {
78
+ data_ptr_.clear();
79
+ size_bytes_ = 0;
80
+ size_bytes_is_heap_allocated_ = false;
81
+ }
82
+
83
+ // Destructor doesn't call release_resources because it's
84
+ // unnecessary; don't forget to change that if needed!
85
+ void release_resources() override {
86
+ data_ptr_.clear();
87
+ }
88
+
89
+ size_t nbytes() const {
90
+ // OK to do this instead of maybe_as_int as nbytes is guaranteed positive
91
+ TORCH_CHECK(!size_bytes_is_heap_allocated_);
92
+ return size_bytes_.as_int_unchecked();
93
+ }
94
+
95
+ SymInt sym_nbytes() const {
96
+ return size_bytes_;
97
+ }
98
+
99
+ // TODO: remove later
100
+ void set_nbytes(size_t size_bytes) {
101
+ size_bytes_ = size_bytes;
102
+ size_bytes_is_heap_allocated_ = false;
103
+ }
104
+
105
+ void set_nbytes(c10::SymInt size_bytes) {
106
+ size_bytes_ = std::move(size_bytes);
107
+ }
108
+
109
+ bool resizable() const {
110
+ return resizable_;
111
+ }
112
+
113
+ at::DataPtr& mutable_data_ptr() {
114
+ return data_ptr_;
115
+ }
116
+
117
+ const at::DataPtr& data_ptr() const {
118
+ return data_ptr_;
119
+ }
120
+
121
+ // Returns the previous data_ptr
122
+ at::DataPtr set_data_ptr(at::DataPtr&& data_ptr) {
123
+ at::DataPtr old_data_ptr(std::move(data_ptr_));
124
+ data_ptr_ = std::move(data_ptr);
125
+ return old_data_ptr;
126
+ }
127
+
128
+ void set_data_ptr_noswap(at::DataPtr&& data_ptr) {
129
+ data_ptr_ = std::move(data_ptr);
130
+ }
131
+
132
+ const void* data() const {
133
+ return data_ptr_.get();
134
+ }
135
+
136
+ void* mutable_data() {
137
+ return data_ptr_.mutable_get();
138
+ }
139
+
140
+ at::DeviceType device_type() const {
141
+ return data_ptr_.device().type();
142
+ }
143
+
144
+ at::Allocator* allocator() {
145
+ return allocator_;
146
+ }
147
+
148
+ const at::Allocator* allocator() const {
149
+ return allocator_;
150
+ }
151
+
152
+ // You generally shouldn't use this method, but it is occasionally
153
+ // useful if you want to override how a tensor will be reallocated,
154
+ // after it was already allocated (and its initial allocator was
155
+ // set)
156
+ void set_allocator(at::Allocator* allocator) {
157
+ allocator_ = allocator;
158
+ }
159
+
160
+ Device device() const {
161
+ return data_ptr_.device();
162
+ }
163
+
164
+ void set_resizable(bool resizable) {
165
+ if (resizable) {
166
+ // We need an allocator to be resizable
167
+ AT_ASSERT(allocator_);
168
+ }
169
+ resizable_ = resizable;
170
+ }
171
+
172
+ /**
173
+ * Can only be called when use_count is 1
174
+ */
175
+ void UniqueStorageShareExternalPointer(
176
+ void* src,
177
+ size_t size_bytes,
178
+ DeleterFnPtr d = nullptr) {
179
+ UniqueStorageShareExternalPointer(
180
+ at::DataPtr(src, src, d, data_ptr_.device()), size_bytes);
181
+ }
182
+
183
+ /**
184
+ * Can only be called when use_count is 1
185
+ */
186
+ void UniqueStorageShareExternalPointer(
187
+ at::DataPtr&& data_ptr,
188
+ size_t size_bytes) {
189
+ data_ptr_ = std::move(data_ptr);
190
+ size_bytes_ = size_bytes;
191
+ size_bytes_is_heap_allocated_ = false;
192
+ allocator_ = nullptr;
193
+ resizable_ = false;
194
+ }
195
+
196
+ // This method can be used only after storage construction and cannot be used
197
+ // to modify storage status
198
+ void set_received_cuda(bool received_cuda) {
199
+ received_cuda_ = received_cuda;
200
+ }
201
+
202
+ bool received_cuda() {
203
+ return received_cuda_;
204
+ }
205
+
206
+ impl::PyObjectSlot* pyobj_slot() {
207
+ return &pyobj_slot_;
208
+ }
209
+
210
+ const impl::PyObjectSlot* pyobj_slot() const {
211
+ return &pyobj_slot_;
212
+ }
213
+
214
+ private:
215
+ DataPtr data_ptr_;
216
+ SymInt size_bytes_;
217
+ bool size_bytes_is_heap_allocated_;
218
+ bool resizable_;
219
+ // Identifies that Storage was received from another process and doesn't have
220
+ // local to process cuda memory allocation
221
+ bool received_cuda_;
222
+ Allocator* allocator_;
223
+ impl::PyObjectSlot pyobj_slot_;
224
+ };
225
+
226
+ // Declare StorageImpl create function pointer types.
227
+ using StorageImplCreateHelper = intrusive_ptr<StorageImpl> (*)(
228
+ StorageImpl::use_byte_size_t,
229
+ SymInt size_bytes,
230
+ Allocator* allocator,
231
+ bool resizable);
232
+
233
+ C10_API void SetStorageImplCreate(DeviceType t, StorageImplCreateHelper fptr);
234
+
235
+ C10_API StorageImplCreateHelper GetStorageImplCreate(DeviceType t);
236
+
237
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/SymBool.h ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/SymNodeImpl.h>
4
+ #include <c10/macros/Macros.h>
5
+ #include <c10/util/Exception.h>
6
+ #include <c10/util/intrusive_ptr.h>
7
+
8
+ namespace c10 {
9
+
10
+ class C10_API SymBool {
11
+ public:
12
+ /*implicit*/ SymBool(bool b) : data_(b){};
13
+ SymBool(SymNode ptr) : data_(false), ptr_(std::move(ptr)) {
14
+ TORCH_CHECK(ptr_->is_bool());
15
+ };
16
+ SymBool() : data_(false) {}
17
+
18
+ SymNodeImpl* toSymNodeImplUnowned() const {
19
+ return ptr_.get();
20
+ }
21
+
22
+ SymNodeImpl* release() && {
23
+ return std::move(ptr_).release();
24
+ }
25
+
26
+ // Only valid if is_heap_allocated()
27
+ SymNode toSymNodeImpl() const;
28
+
29
+ // Guaranteed to return a SymNode, wrapping using base if necessary
30
+ SymNode wrap_node(const SymNode& base) const;
31
+
32
+ bool expect_bool() const {
33
+ c10::optional<bool> c = maybe_as_bool();
34
+ TORCH_CHECK(c.has_value());
35
+ return *c;
36
+ }
37
+
38
+ SymBool sym_and(const SymBool&) const;
39
+ SymBool sym_or(const SymBool&) const;
40
+ SymBool sym_not() const;
41
+
42
+ SymBool operator&(const SymBool& other) const {
43
+ return sym_and(other);
44
+ }
45
+ SymBool operator|(const SymBool& other) const {
46
+ return sym_or(other);
47
+ }
48
+ SymBool operator~() const {
49
+ return sym_not();
50
+ }
51
+
52
+ // Insert a guard for the bool to be its concrete value, and then return
53
+ // that value. Note that C++ comparison operations default to returning
54
+ // bool, so it's not so common to have to call this
55
+ bool guard_bool(const char* file, int64_t line) const;
56
+ bool expect_true(const char* file, int64_t line) const;
57
+
58
+ bool has_hint() const;
59
+
60
+ bool as_bool_unchecked() const {
61
+ return data_;
62
+ }
63
+
64
+ c10::optional<bool> maybe_as_bool() const {
65
+ if (!is_heap_allocated()) {
66
+ return c10::make_optional(data_);
67
+ }
68
+ return toSymNodeImplUnowned()->constant_bool();
69
+ }
70
+
71
+ bool is_heap_allocated() const {
72
+ return ptr_;
73
+ }
74
+
75
+ private:
76
+ // TODO: optimize to union
77
+ bool data_;
78
+ SymNode ptr_;
79
+ };
80
+
81
+ C10_API std::ostream& operator<<(std::ostream& os, const SymBool& s);
82
+
83
+ #define TORCH_SYM_CHECK(cond, ...) \
84
+ TORCH_CHECK((cond).expect_true(__FILE__, __LINE__), __VA_ARGS__)
85
+ #define TORCH_SYM_INTERNAL_ASSERT(cond, ...) \
86
+ TORCH_INTERNAL_ASSERT((cond).expect_true(__FILE__, __LINE__), __VA_ARGS__)
87
+
88
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/SymFloat.h ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/SymBool.h>
4
+ #include <c10/core/SymNodeImpl.h>
5
+ #include <c10/macros/Macros.h>
6
+ #include <c10/util/Exception.h>
7
+ #include <c10/util/intrusive_ptr.h>
8
+
9
+ #include <limits>
10
+
11
+ namespace c10 {
12
+
13
+ // NB: this is actually double precision; we're using the Python naming here
14
+ class C10_API SymFloat {
15
+ public:
16
+ /*implicit*/ SymFloat(double d) : data_(d){};
17
+ SymFloat(SymNode ptr)
18
+ : data_(std::numeric_limits<double>::quiet_NaN()), ptr_(std::move(ptr)) {
19
+ TORCH_CHECK(ptr_->is_float());
20
+ };
21
+ SymFloat() : data_(0.0) {}
22
+
23
+ SymNodeImpl* toSymNodeImplUnowned() const {
24
+ return ptr_.get();
25
+ }
26
+
27
+ SymNodeImpl* release() && {
28
+ return std::move(ptr_).release();
29
+ }
30
+
31
+ // Only valid if is_symbolic()
32
+ SymNode toSymNodeImpl() const;
33
+
34
+ // Guaranteed to return a SymNode, wrapping using base if necessary
35
+ SymNode wrap_node(const SymNode& base) const;
36
+
37
+ double expect_float() const {
38
+ TORCH_CHECK(!is_symbolic());
39
+ return data_;
40
+ }
41
+
42
+ SymFloat operator+(const SymFloat&) const;
43
+ SymFloat operator-(const SymFloat&) const;
44
+ SymFloat operator*(const SymFloat&) const;
45
+ SymFloat operator/(const SymFloat&) const;
46
+
47
+ SymBool sym_eq(const SymFloat&) const;
48
+ SymBool sym_ne(const SymFloat&) const;
49
+ SymBool sym_lt(const SymFloat&) const;
50
+ SymBool sym_le(const SymFloat&) const;
51
+ SymBool sym_gt(const SymFloat&) const;
52
+ SymBool sym_ge(const SymFloat&) const;
53
+
54
+ bool operator==(const SymFloat& o) const {
55
+ return sym_eq(o).guard_bool(__FILE__, __LINE__);
56
+ }
57
+ bool operator!=(const SymFloat& o) const {
58
+ return sym_ne(o).guard_bool(__FILE__, __LINE__);
59
+ }
60
+ bool operator<(const SymFloat& o) const {
61
+ return sym_lt(o).guard_bool(__FILE__, __LINE__);
62
+ }
63
+ bool operator<=(const SymFloat& o) const {
64
+ return sym_le(o).guard_bool(__FILE__, __LINE__);
65
+ }
66
+ bool operator>(const SymFloat& o) const {
67
+ return sym_gt(o).guard_bool(__FILE__, __LINE__);
68
+ }
69
+ bool operator>=(const SymFloat& o) const {
70
+ return sym_ge(o).guard_bool(__FILE__, __LINE__);
71
+ }
72
+
73
+ SymFloat min(const SymFloat& sci) const;
74
+ SymFloat max(const SymFloat& sci) const;
75
+
76
+ // Need guidance on where to put this code
77
+ SymFloat sqrt() const;
78
+
79
+ // Insert a guard for the float to be its concrete value, and then return
80
+ // that value. This operation always works, even if the float is symbolic,
81
+ // so long as we know what the underlying value is. Don't blindly put this
82
+ // everywhere; you can cause overspecialization of PyTorch programs with
83
+ // this method.
84
+ //
85
+ // It should be called as guard_float(__FILE__, __LINE__). The file and line
86
+ // number can be used to diagnose overspecialization.
87
+ double guard_float(const char* file, int64_t line) const;
88
+
89
+ bool has_hint() const;
90
+
91
+ // N.B. It's important to keep this definition in the header
92
+ // as we expect if checks to be folded for mobile builds
93
+ // where `is_symbolic` is always false
94
+ C10_ALWAYS_INLINE bool is_symbolic() const {
95
+ return ptr_;
96
+ }
97
+
98
+ double as_float_unchecked() const {
99
+ return data_;
100
+ }
101
+
102
+ private:
103
+ // TODO: optimize to union
104
+ double data_;
105
+ SymNode ptr_;
106
+ };
107
+
108
+ C10_API std::ostream& operator<<(std::ostream& os, const SymFloat& s);
109
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/SymInt.h ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/SymBool.h>
4
+ #include <c10/core/SymNodeImpl.h>
5
+ #include <c10/macros/Macros.h>
6
+ #include <c10/util/Exception.h>
7
+ #include <c10/util/Optional.h>
8
+
9
+ #include <numeric>
10
+ #include <type_traits>
11
+
12
+ namespace c10 {
13
+
14
+ class SymFloat;
15
+
16
+ // SymInt represents either a regular int64_t, or a symbolic integer
17
+ // (represented in a type erased way as SymNode). The intention is for SymInt
18
+ // to represent symbolic sizes that arise when doing shape computation in
19
+ // operator kernels. This allows for tracing through programs without baking in
20
+ // concrete sizes into kernel calls.
21
+ //
22
+ // SymInt has an API equivalent to int64_t. In particular, it is a value type.
23
+ // Internally, SymInt is represented in a clever packed way, so that it only
24
+ // occupies one word of space; but morally, it is a union between an int64_t
25
+ // and an intrusive pointer to SymNodeImpl.
26
+ //
27
+ // Invariant: the referenced SymNodeImpl is guaranteed to be a SymNode where
28
+ // is_int() returns true
29
+
30
+ class C10_API SymInt {
31
+ public:
32
+ enum Unchecked {
33
+ UNCHECKED,
34
+ };
35
+
36
+ /*implicit*/ SymInt(int64_t d) : data_(d) {
37
+ if (is_heap_allocated()) {
38
+ // Large negative number, heap allocate it
39
+ promote_to_negative();
40
+ }
41
+ };
42
+ SymInt() : data_(0) {}
43
+ SymInt(SymNode n);
44
+
45
+ // unchecked c-tor accepting raw `data_`
46
+ // One appropriate use for this is when you are constructing a symint
47
+ // in a situation where you know it is non-negative (or, if it is negative,
48
+ // the negative value is -1; i.e., not user controlled)
49
+ SymInt(Unchecked, int64_t d) : data_(d) {}
50
+
51
+ // TODO: these implementations are not optimal because they allocate a
52
+ // temporary and then use the move constructor/assignment
53
+ SymInt(const SymInt& s) : data_(0) {
54
+ if (s.is_heap_allocated()) {
55
+ *this = SymInt(s.toSymNode());
56
+ } else {
57
+ data_ = s.data_;
58
+ }
59
+ }
60
+ SymInt(SymInt&& s) noexcept : data_(s.data_) {
61
+ s.data_ = 0;
62
+ }
63
+
64
+ SymInt& operator=(const SymInt& s) {
65
+ if (this != &s) {
66
+ if (s.is_heap_allocated()) {
67
+ *this = SymInt(s.toSymNode());
68
+ } else {
69
+ data_ = s.data_;
70
+ }
71
+ }
72
+ return *this;
73
+ }
74
+ SymInt& operator=(SymInt&& s) noexcept {
75
+ if (this != &s) {
76
+ release_(); // release the current SymNode if any
77
+ data_ = s.data_;
78
+ if (s.is_heap_allocated())
79
+ s.data_ = 0;
80
+ };
81
+ return *this;
82
+ }
83
+
84
+ SymNodeImpl* toSymNodeImplUnowned() const {
85
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(is_heap_allocated());
86
+ uint64_t unextended_bits = static_cast<uint64_t>(data_) & ~MASK;
87
+ uint64_t sign_bit_mask = 1ULL << (62 - 1);
88
+ // https://stackoverflow.com/questions/42534749/signed-extension-from-24-bit-to-32-bit-in-c
89
+ uint64_t extended_bits = (unextended_bits ^ sign_bit_mask) - sign_bit_mask;
90
+ return static_cast<SymNodeImpl*>(
91
+ reinterpret_cast<void*>(static_cast<uintptr_t>(extended_bits)));
92
+ }
93
+
94
+ void release_() {
95
+ if (is_heap_allocated()) {
96
+ SymNode::reclaim(toSymNodeImplUnowned()); // steal
97
+ }
98
+ }
99
+
100
+ SymNodeImpl* release() && {
101
+ #ifndef C10_MOBILE
102
+ TORCH_INTERNAL_ASSERT(is_heap_allocated());
103
+ auto* r = toSymNodeImplUnowned();
104
+ data_ = 0; // transfer ownership
105
+ return r;
106
+ #else
107
+ TORCH_INTERNAL_ASSERT(false);
108
+ #endif
109
+ }
110
+
111
+ // Only valid if is_heap_allocated()
112
+ SymNode toSymNode() const;
113
+
114
+ // Guaranteed to return a SymNode, wrapping using base if necessary
115
+ SymNode wrap_node(const SymNode& base) const;
116
+
117
+ ~SymInt() {
118
+ release_();
119
+ }
120
+
121
+ // Require the int to be non-symbolic, and if it is symbolic raise an
122
+ // error. This is safe to use for C++ code that doesn't work for symbolic
123
+ // shapes, and you don't have time to fix it immediately, as if we
124
+ // try to trigger the path in C++ you'll appropriately get an error
125
+ int64_t expect_int() const {
126
+ if (auto r = maybe_as_int()) {
127
+ return *r;
128
+ }
129
+ TORCH_CHECK_ALWAYS_SHOW_CPP_STACKTRACE(
130
+ false, "when unpacking SymInt, expected int but got ", *this);
131
+ }
132
+
133
+ // Test if we have a hint for this int (e.g., guard_int would work).
134
+ // Most of the time this is true; it is only false when you have
135
+ // an unbacked SymInt.
136
+ bool has_hint() const;
137
+
138
+ // Insert a guard for the int to be its concrete value, and then return
139
+ // that value. This operation always works, even if the int is symbolic,
140
+ // so long as we know what the underlying value is (e.g., this won't work
141
+ // if you call it on the size of nonzero output). Don't blindly put this
142
+ // everywhere; you can cause overspecialization of PyTorch programs with
143
+ // this method.
144
+ //
145
+ // It should be called as guard_int(__FILE__, __LINE__). The file and line
146
+ // number can be used to diagnose overspecialization.
147
+ int64_t guard_int(const char* file, int64_t line) const;
148
+
149
+ // Insert a guard that this SymInt must be size-like, returning true if
150
+ // the integer actually is >= 0. Unlike manually performing a >= 0 test,
151
+ // if the SymInt in question is an unbacked SymInt (or, potentially in the
152
+ // future, if it contains unbacked SymInts), we will also treat the
153
+ // unbacked SymInt as statically testing >= 2 (which will prevent us from
154
+ // choking on, e.g., contiguity checks.)
155
+ bool expect_size(const char* file, int64_t line) const;
156
+
157
+ // Distinguish actual symbolic values from constants stored on the heap
158
+ bool is_symbolic() const {
159
+ return is_heap_allocated() &&
160
+ !toSymNodeImplUnowned()->constant_int().has_value();
161
+ }
162
+
163
+ // N.B. It's important to keep this definition in the header
164
+ // as we expect if checks to be folded for mobile builds
165
+ // where `is_heap_allocated` is always false and optimize dead code paths
166
+ C10_ALWAYS_INLINE bool is_heap_allocated() const {
167
+ #ifdef C10_MOBILE
168
+ return false;
169
+ #else
170
+ return !check_range(data_);
171
+ #endif
172
+ }
173
+
174
+ SymInt operator+(const SymInt& sci) const;
175
+ SymInt operator-(const SymInt& sci) const;
176
+ SymInt operator*(const SymInt& sci) const;
177
+ SymInt operator/(const SymInt& sci) const;
178
+ SymInt operator%(const SymInt& sci) const;
179
+ void operator*=(const SymInt& sci);
180
+ void operator+=(const SymInt& sci);
181
+ void operator/=(const SymInt& sci);
182
+
183
+ SymInt clone() const;
184
+
185
+ SymBool sym_eq(const SymInt&) const;
186
+ SymBool sym_ne(const SymInt&) const;
187
+ SymBool sym_lt(const SymInt&) const;
188
+ SymBool sym_le(const SymInt&) const;
189
+ SymBool sym_gt(const SymInt&) const;
190
+ SymBool sym_ge(const SymInt&) const;
191
+
192
+ bool operator==(const SymInt& o) const {
193
+ return sym_eq(o).guard_bool(__FILE__, __LINE__);
194
+ }
195
+ bool operator!=(const SymInt& o) const {
196
+ return sym_ne(o).guard_bool(__FILE__, __LINE__);
197
+ }
198
+ bool operator<(const SymInt& o) const {
199
+ return sym_lt(o).guard_bool(__FILE__, __LINE__);
200
+ }
201
+ bool operator<=(const SymInt& o) const {
202
+ return sym_le(o).guard_bool(__FILE__, __LINE__);
203
+ }
204
+ bool operator>(const SymInt& o) const {
205
+ return sym_gt(o).guard_bool(__FILE__, __LINE__);
206
+ }
207
+ bool operator>=(const SymInt& o) const {
208
+ return sym_ge(o).guard_bool(__FILE__, __LINE__);
209
+ }
210
+
211
+ SymInt min(const SymInt& sci) const;
212
+ SymInt max(const SymInt& sci) const;
213
+
214
+ // If both are symbolic, this checks if
215
+ // they share the same node.
216
+ // If both are not symbolic this just checks normal equality.
217
+ bool is_same(const SymInt& other) const;
218
+
219
+ operator SymFloat() const;
220
+
221
+ // Don't use this. Prefer maybe_as_int instead
222
+ int64_t as_int_unchecked() const {
223
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!is_heap_allocated());
224
+ return data_;
225
+ }
226
+
227
+ c10::optional<int64_t> maybe_as_int() const {
228
+ if (!is_heap_allocated()) {
229
+ return c10::make_optional(data_);
230
+ }
231
+ auto* node = toSymNodeImplUnowned();
232
+ if (auto c = node->constant_int()) {
233
+ return c;
234
+ }
235
+ return node->maybe_as_int();
236
+ }
237
+
238
+ // Return whether the integer is directly coercible to a SymInt
239
+ // without requiring heap allocation. You don't need to use this
240
+ // to check if you can pass an integer to SymInt; this is guaranteed
241
+ // to work (it just might heap allocate!)
242
+ static bool check_range(int64_t i) {
243
+ return i > MAX_UNREPRESENTABLE_INT;
244
+ }
245
+
246
+ // Return the min representable integer as a SymInt without
247
+ // heap allocation. For quantities that count bytes (or larger),
248
+ // this is still much larger than you need, so you may consider
249
+ // using this as a more efficient version of MIN_INT
250
+ static constexpr int64_t min_representable_int() {
251
+ return MAX_UNREPRESENTABLE_INT + 1;
252
+ }
253
+
254
+ private:
255
+ void promote_to_negative();
256
+
257
+ // Constraints on the internal representation:
258
+ //
259
+ // - Should represent positive and small negative ints
260
+ // - No conversion necessary for operations on ints
261
+ // - Must represent valid 64-bit pointers
262
+ // - Is symbolic test should be FAST (two arithmetic instructions is too
263
+ // much).
264
+ // This code being a hotpath is based on Strobelight profiles of
265
+ // is_heap_allocated(). FB only: https://fburl.com/strobelight/5l50ncxd
266
+ // (you will need to change the time window).
267
+ //
268
+ // So, the scheme is to reserve large negative numbers (assuming
269
+ // two's complement):
270
+ //
271
+ // - 0b0.... means we are a positive int
272
+ // - 0b11... means we are a small negative int
273
+ // - 0b10... means we are are a pointer. This means that
274
+ // [-2^63, -2^62-1] are not representable as ints.
275
+ // We don't actually need all of this space as on x86_64
276
+ // as the top 16bits aren't used for anything
277
+ static constexpr uint64_t MASK = 1ULL << 63 | 1ULL << 62 | 1ULL << 61;
278
+ static constexpr uint64_t IS_SYM = 1ULL << 63 | 1ULL << 61;
279
+ // We must manually translate the bit pattern test into a greater
280
+ // than test because compiler doesn't figure it out:
281
+ // https://godbolt.org/z/356aferaW
282
+ static constexpr int64_t MAX_UNREPRESENTABLE_INT =
283
+ -1LL & static_cast<int64_t>(~(1ULL << 62));
284
+ int64_t data_;
285
+ };
286
+
287
+ /// Sum of a list of SymInt; accumulates into the c10::SymInt expression
288
+ template <
289
+ typename C,
290
+ typename std::enable_if<
291
+ std::is_same<typename C::value_type, c10::SymInt>::value,
292
+ int>::type = 0>
293
+ inline c10::SymInt multiply_integers(const C& container) {
294
+ return std::accumulate(
295
+ container.begin(),
296
+ container.end(),
297
+ c10::SymInt(1),
298
+ [](const c10::SymInt& a, const c10::SymInt& b) { return a * b; });
299
+ }
300
+
301
+ template <
302
+ typename Iter,
303
+ typename = std::enable_if_t<std::is_same<
304
+ typename std::iterator_traits<Iter>::value_type,
305
+ c10::SymInt>::value>>
306
+ inline c10::SymInt multiply_integers(Iter begin, Iter end) {
307
+ return std::accumulate(
308
+ begin,
309
+ end,
310
+ c10::SymInt(1),
311
+ [](const c10::SymInt& a, const c10::SymInt& b) { return a * b; });
312
+ }
313
+
314
+ #define DECLARE_SYMINT_OP_INTONLY(scalar_t, RetTy) \
315
+ C10_API RetTy operator%(const SymInt& a, scalar_t b); \
316
+ C10_API RetTy operator%(scalar_t a, const SymInt& b);
317
+
318
+ #define DECLARE_SYMINT_OP(scalar_t, RetTy) \
319
+ C10_API RetTy operator+(const SymInt& a, scalar_t b); \
320
+ C10_API RetTy operator-(const SymInt& a, scalar_t b); \
321
+ C10_API RetTy operator*(const SymInt& a, scalar_t b); \
322
+ C10_API RetTy operator/(const SymInt& a, scalar_t b); \
323
+ C10_API RetTy operator+(scalar_t a, const SymInt& b); \
324
+ C10_API RetTy operator-(scalar_t a, const SymInt& b); \
325
+ C10_API RetTy operator*(scalar_t a, const SymInt& b); \
326
+ C10_API RetTy operator/(scalar_t a, const SymInt& b); \
327
+ C10_API bool operator==(const SymInt& a, scalar_t b); \
328
+ C10_API bool operator!=(const SymInt& a, scalar_t b); \
329
+ C10_API bool operator<(const SymInt& a, scalar_t b); \
330
+ C10_API bool operator<=(const SymInt& a, scalar_t b); \
331
+ C10_API bool operator>(const SymInt& a, scalar_t b); \
332
+ C10_API bool operator>=(const SymInt& a, scalar_t b); \
333
+ C10_API bool operator==(scalar_t a, const SymInt& b); \
334
+ C10_API bool operator!=(scalar_t a, const SymInt& b); \
335
+ C10_API bool operator<(scalar_t a, const SymInt& b); \
336
+ C10_API bool operator<=(scalar_t a, const SymInt& b); \
337
+ C10_API bool operator>(scalar_t a, const SymInt& b); \
338
+ C10_API bool operator>=(scalar_t a, const SymInt& b);
339
+
340
+ DECLARE_SYMINT_OP_INTONLY(int64_t, SymInt)
341
+ DECLARE_SYMINT_OP_INTONLY(int32_t, SymInt)
342
+ DECLARE_SYMINT_OP_INTONLY(uint64_t, SymInt)
343
+ DECLARE_SYMINT_OP_INTONLY(uint32_t, SymInt)
344
+ DECLARE_SYMINT_OP(int64_t, SymInt)
345
+ DECLARE_SYMINT_OP(int32_t, SymInt) // make sure constants work
346
+ DECLARE_SYMINT_OP(uint64_t, SymInt)
347
+ DECLARE_SYMINT_OP(uint32_t, SymInt)
348
+ DECLARE_SYMINT_OP(double, SymFloat)
349
+ DECLARE_SYMINT_OP(float, SymFloat) // just for completeness
350
+
351
+ // On OSX size_t is different than uint64_t so we have to
352
+ // define it separately
353
+ #if defined(__APPLE__)
354
+ DECLARE_SYMINT_OP_INTONLY(size_t, SymInt)
355
+ DECLARE_SYMINT_OP(size_t, SymInt)
356
+ #endif
357
+
358
+ #undef DECLARE_SYMINT_OP
359
+
360
+ C10_API std::ostream& operator<<(std::ostream& os, const SymInt& s);
361
+ C10_API SymInt operator-(const SymInt& s);
362
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/SymIntArrayRef.h ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/SymInt.h>
4
+ #include <c10/util/ArrayRef.h>
5
+ #include <c10/util/Exception.h>
6
+ #include <c10/util/Optional.h>
7
+
8
+ namespace c10 {
9
+ using SymIntArrayRef = ArrayRef<SymInt>;
10
+
11
+ inline at::IntArrayRef asIntArrayRefUnchecked(c10::SymIntArrayRef ar) {
12
+ return IntArrayRef(reinterpret_cast<const int64_t*>(ar.data()), ar.size());
13
+ }
14
+
15
+ // TODO: a SymIntArrayRef containing a heap allocated large negative integer
16
+ // can actually technically be converted to an IntArrayRef... but not with
17
+ // the non-owning API we have here. We can't reinterpet cast; we have to
18
+ // allocate another buffer and write the integers into it. If you need it,
19
+ // we can do it. But I don't think you need it.
20
+
21
+ inline c10::optional<at::IntArrayRef> asIntArrayRefSlowOpt(
22
+ c10::SymIntArrayRef ar) {
23
+ for (const c10::SymInt& sci : ar) {
24
+ if (sci.is_heap_allocated()) {
25
+ return c10::nullopt;
26
+ }
27
+ }
28
+
29
+ return {asIntArrayRefUnchecked(ar)};
30
+ }
31
+
32
+ inline at::IntArrayRef asIntArrayRefSlow(
33
+ c10::SymIntArrayRef ar,
34
+ const char* file,
35
+ int64_t line) {
36
+ for (const c10::SymInt& sci : ar) {
37
+ TORCH_CHECK(
38
+ !sci.is_heap_allocated(),
39
+ file,
40
+ ":",
41
+ line,
42
+ ": SymIntArrayRef expected to contain only concrete integers");
43
+ }
44
+ return asIntArrayRefUnchecked(ar);
45
+ }
46
+
47
+ #define C10_AS_INTARRAYREF_SLOW(a) c10::asIntArrayRefSlow(a, __FILE__, __LINE__)
48
+
49
+ // Prefer using a more semantic constructor, like
50
+ // fromIntArrayRefKnownNonNegative
51
+ inline SymIntArrayRef fromIntArrayRefUnchecked(IntArrayRef array_ref) {
52
+ return SymIntArrayRef(
53
+ reinterpret_cast<const SymInt*>(array_ref.data()), array_ref.size());
54
+ }
55
+
56
+ inline SymIntArrayRef fromIntArrayRefKnownNonNegative(IntArrayRef array_ref) {
57
+ return fromIntArrayRefUnchecked(array_ref);
58
+ }
59
+
60
+ inline SymIntArrayRef fromIntArrayRefSlow(IntArrayRef array_ref) {
61
+ for (long i : array_ref) {
62
+ TORCH_CHECK(
63
+ SymInt::check_range(i),
64
+ "IntArrayRef contains an int that cannot be represented as a SymInt: ",
65
+ i);
66
+ }
67
+ return SymIntArrayRef(
68
+ reinterpret_cast<const SymInt*>(array_ref.data()), array_ref.size());
69
+ }
70
+
71
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/SymNodeImpl.h ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Export.h>
4
+ #include <c10/util/ArrayRef.h>
5
+ #include <c10/util/Exception.h>
6
+ #include <c10/util/Optional.h>
7
+ #include <c10/util/intrusive_ptr.h>
8
+
9
+ namespace c10 {
10
+
11
+ class SymNodeImpl;
12
+ using SymNode = c10::intrusive_ptr<SymNodeImpl>;
13
+
14
+ // When you add a method, you also need to edit
15
+ // torch/csrc/jit/python/init.cpp
16
+ // torch/csrc/utils/python_symnode.h
17
+ // c10/core/ConstantSymNodeImpl.h
18
+ class C10_API SymNodeImpl : public c10::intrusive_ptr_target {
19
+ public:
20
+ ~SymNodeImpl() override = default;
21
+
22
+ template <typename T>
23
+ c10::intrusive_ptr<T> dyn_cast() const {
24
+ return c10::intrusive_ptr<T>::reclaim_copy(dynamic_cast<T*>(this));
25
+ }
26
+
27
+ // these could be pure virtual when we implement LTC versions
28
+ virtual bool is_int() {
29
+ TORCH_CHECK(false, "NYI");
30
+ };
31
+ virtual bool is_bool() {
32
+ TORCH_CHECK(false, "NYI");
33
+ };
34
+ virtual bool is_float() {
35
+ TORCH_CHECK(false, "NYI");
36
+ };
37
+ virtual SymNode add(const SymNode& other) {
38
+ TORCH_CHECK(false, "NYI");
39
+ };
40
+ virtual SymNode sub(const SymNode& other) {
41
+ TORCH_CHECK(false, "NYI");
42
+ };
43
+ virtual SymNode mul(const SymNode& other) {
44
+ TORCH_CHECK(false, "NYI");
45
+ };
46
+ virtual SymNode truediv(const SymNode& other) {
47
+ TORCH_CHECK(false, "NYI");
48
+ };
49
+ virtual SymNode pow(const SymNode& other) {
50
+ TORCH_CHECK(false, "NYI");
51
+ };
52
+ virtual SymNode floordiv(const SymNode& other) {
53
+ TORCH_CHECK(false, "NYI");
54
+ };
55
+ virtual SymNode mod(const SymNode& other) {
56
+ TORCH_CHECK(false, "NYI");
57
+ };
58
+ virtual SymNode eq(const SymNode& other) {
59
+ TORCH_CHECK(false, "NYI");
60
+ };
61
+ virtual SymNode ne(const SymNode& other) {
62
+ TORCH_CHECK(false, "NYI");
63
+ };
64
+ virtual SymNode gt(const SymNode& other) {
65
+ TORCH_CHECK(false, "NYI");
66
+ };
67
+ virtual SymNode lt(const SymNode& other) {
68
+ TORCH_CHECK(false, "NYI");
69
+ };
70
+ virtual SymNode le(const SymNode& other) {
71
+ TORCH_CHECK(false, "NYI");
72
+ };
73
+ virtual SymNode ge(const SymNode& other) {
74
+ TORCH_CHECK(false, "NYI");
75
+ };
76
+ virtual SymNode ceil() {
77
+ TORCH_CHECK(false, "NYI");
78
+ };
79
+ virtual SymNode floor() {
80
+ TORCH_CHECK(false, "NYI");
81
+ };
82
+ virtual SymNode neg() {
83
+ TORCH_CHECK(false, "NYI");
84
+ };
85
+ virtual SymNode sym_min(const SymNode& other) {
86
+ TORCH_CHECK(false, "NYI");
87
+ };
88
+ virtual SymNode sym_max(const SymNode& other) {
89
+ TORCH_CHECK(false, "NYI");
90
+ };
91
+ virtual SymNode sym_or(const SymNode& other) {
92
+ TORCH_CHECK(false, "NYI");
93
+ };
94
+ virtual SymNode sym_and(const SymNode& other) {
95
+ TORCH_CHECK(false, "NYI");
96
+ };
97
+ virtual SymNode sym_not() {
98
+ TORCH_CHECK(false, "NYI");
99
+ };
100
+ virtual SymNode sym_ite(const SymNode& then_val, const SymNode& else_val) {
101
+ TORCH_CHECK(false, "NYI");
102
+ };
103
+ // NB: self is ignored here, only the arguments are used
104
+ virtual SymNode is_contiguous(
105
+ ArrayRef<SymNode> sizes,
106
+ ArrayRef<SymNode> strides) {
107
+ TORCH_CHECK(false, "NYI");
108
+ };
109
+ virtual SymNode is_channels_last_contiguous_2d(
110
+ ArrayRef<SymNode> sizes,
111
+ ArrayRef<SymNode> strides) {
112
+ TORCH_CHECK(false, "NYI");
113
+ };
114
+ virtual SymNode is_channels_last_contiguous_3d(
115
+ ArrayRef<SymNode> sizes,
116
+ ArrayRef<SymNode> strides) {
117
+ TORCH_CHECK(false, "NYI");
118
+ };
119
+ virtual SymNode is_channels_last_strides_2d(
120
+ ArrayRef<SymNode> sizes,
121
+ ArrayRef<SymNode> strides) {
122
+ TORCH_CHECK(false, "NYI");
123
+ };
124
+ virtual SymNode is_channels_last_strides_3d(
125
+ ArrayRef<SymNode> sizes,
126
+ ArrayRef<SymNode> strides) {
127
+ TORCH_CHECK(false, "NYI");
128
+ };
129
+ virtual SymNode is_non_overlapping_and_dense(
130
+ ArrayRef<SymNode> sizes,
131
+ ArrayRef<SymNode> strides) {
132
+ TORCH_CHECK(false, "NYI");
133
+ };
134
+ virtual SymNode clone() {
135
+ TORCH_CHECK(false, "NYI");
136
+ };
137
+ virtual SymNode sym_float() {
138
+ TORCH_CHECK(false, "NYI");
139
+ }
140
+ virtual SymNode wrap_int(int64_t num) {
141
+ TORCH_CHECK(false, "NYI");
142
+ };
143
+ virtual SymNode wrap_float(double num) {
144
+ TORCH_CHECK(false, "NYI");
145
+ };
146
+ virtual SymNode wrap_bool(bool num) {
147
+ TORCH_CHECK(false, "NYI");
148
+ };
149
+ virtual int64_t guard_int(const char* file, int64_t line) {
150
+ TORCH_CHECK(false, "NYI");
151
+ };
152
+ virtual bool guard_bool(const char* file, int64_t line) {
153
+ TORCH_CHECK(false, "NYI");
154
+ };
155
+ virtual double guard_float(const char* file, int64_t line) {
156
+ TORCH_CHECK(false, "NYI");
157
+ };
158
+ virtual bool expect_true(const char* file, int64_t line) {
159
+ // No improvement for unbacked SymBools by default, replace this
160
+ // with a better implementation!
161
+ return guard_bool(file, line);
162
+ };
163
+ virtual bool expect_size(const char* file, int64_t line) {
164
+ // No improvement for unbacked SymInts by default, replace this
165
+ // with a better implementation!
166
+ return ge(wrap_int(0))->guard_bool(file, line);
167
+ };
168
+ virtual int64_t int_() {
169
+ TORCH_CHECK(false, "NYI");
170
+ };
171
+ virtual bool bool_() {
172
+ TORCH_CHECK(false, "NYI");
173
+ };
174
+ virtual bool has_hint() {
175
+ TORCH_CHECK(false, "NYI");
176
+ };
177
+ virtual std::string str() {
178
+ TORCH_CHECK(false, "NYI");
179
+ };
180
+ virtual c10::optional<int64_t> singleton_int() {
181
+ return c10::nullopt;
182
+ }
183
+ virtual c10::optional<int64_t> singleton_coeff() {
184
+ return c10::nullopt;
185
+ }
186
+ virtual c10::optional<int64_t> constant_int() {
187
+ return c10::nullopt;
188
+ }
189
+ virtual c10::optional<bool> constant_bool() {
190
+ return c10::nullopt;
191
+ }
192
+ virtual c10::optional<int64_t> maybe_as_int() {
193
+ return c10::nullopt;
194
+ }
195
+ virtual bool is_constant() {
196
+ return false;
197
+ }
198
+ virtual bool is_symbolic() {
199
+ return true;
200
+ }
201
+ std::ostream& operator<<(std::ostream& os) {
202
+ os << str();
203
+ return os;
204
+ }
205
+ };
206
+
207
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/core/TensorOptions.h ADDED
@@ -0,0 +1,773 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Backend.h>
4
+ #include <c10/core/DefaultDtype.h>
5
+ #include <c10/core/Device.h>
6
+ #include <c10/core/Layout.h>
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/ScalarType.h>
9
+ #include <c10/core/ScalarTypeToTypeMeta.h>
10
+
11
+ #include <c10/macros/Macros.h>
12
+ #include <c10/util/Optional.h>
13
+
14
+ #include <iosfwd>
15
+ #include <utility>
16
+
17
+ namespace c10 {
18
+
19
+ DispatchKey computeDispatchKey(
20
+ c10::optional<ScalarType> dtype,
21
+ c10::optional<Layout> layout,
22
+ c10::optional<Device> device);
23
+
24
+ inline ScalarType dtype_or_default(c10::optional<ScalarType> dtype) {
25
+ return value_or_else(dtype, [] { return get_default_dtype_as_scalartype(); });
26
+ }
27
+
28
+ inline caffe2::TypeMeta dtype_or_default(
29
+ c10::optional<caffe2::TypeMeta> dtype) {
30
+ return value_or_else(dtype, [] { return get_default_dtype(); });
31
+ }
32
+
33
+ inline Layout layout_or_default(c10::optional<Layout> layout) {
34
+ return layout.value_or(kStrided);
35
+ }
36
+
37
+ inline Device device_or_default(c10::optional<Device> device) {
38
+ return value_or_else(device, [] { return Device(kCPU); });
39
+ }
40
+
41
+ inline bool pinned_memory_or_default(c10::optional<bool> pinned_memory) {
42
+ return pinned_memory.value_or(false);
43
+ }
44
+
45
+ /// A class to encapsulate construction axes of an Tensor. TensorOptions was
46
+ /// designed to support the Python style API for specifying construction options
47
+ /// on factory functions, e.g.,
48
+ ///
49
+ /// torch.zeros(2, 3, dtype=torch.int32)
50
+ ///
51
+ /// Because C++ doesn't natively support keyword arguments, there must be
52
+ /// another way of specifying keyword-like arguments. TensorOptions is a
53
+ /// builder class which can be used to construct this "dictionary" of keyword
54
+ /// arguments: functions which support TensorOptions conventionally take this
55
+ /// argument optionally as their last argument.
56
+ ///
57
+ /// WARNING: In PyTorch, there are `torch::` variants of factory functions,
58
+ /// e.g., torch::zeros for at::zeros. These return Variables (while the
59
+ /// stock ATen functions return plain Tensors). If you mix these functions
60
+ /// up, you WILL BE SAD.
61
+ ///
62
+ /// Rather than use the constructor of this class directly, you should prefer to
63
+ /// use the constructor functions, and then chain setter methods on top of them.
64
+ ///
65
+ /// at::device(at::kCUDA).dtype(kInt)
66
+ /// at::dtype(at::kInt)
67
+ ///
68
+ /// Additionally, anywhere a TensorOptions is expected, you can directly
69
+ /// pass at::kCUDA / at::kInt, and it will implicitly convert to a
70
+ /// TensorOptions.
71
+ ///
72
+ /// Here are some recommended ways to create a 2x2 tensor of zeros
73
+ /// with certain properties. These all *implicitly* make use of
74
+ /// TensorOptions, even if they don't mention the class explicitly:
75
+ ///
76
+ /// at::zeros({2,2}, at::kCUDA);
77
+ /// at::zeros({2,2}, at::kLong);
78
+ /// at::zeros({2,2}, at::device(at::kCUDA).dtype(at::kLong()));
79
+ /// at::zeros({2,2}, at::device({at::kCUDA, 1})); // place on device 1
80
+ /// at::zeros({2,2}, at::requires_grad());
81
+ ///
82
+
83
+ /// NOTE [ TensorOptions Constructors ]
84
+ ///
85
+ /// TensorOptions is like a dictionary with entries from the set:
86
+ /// {requires_grad, device, dtype, layout}, where each entry may be
87
+ /// unspecified (i.e., is optional). It is used to specify the properties of
88
+ /// tensors in many places both in C++ internal and API, e.g., tensor factory
89
+ /// methods like `at::empty({10}, options)`, tensor conversions like
90
+ /// `tensor.to(...)`, etc.
91
+ ///
92
+ /// To provide a simple API that is consistent with Python, where one can do
93
+ /// `torch.empty(sizes, X)` with `X` being a `torch.device`, `torch.dtype`, or a
94
+ /// `torch.layout`, we want TensorOptions to be implicitly convertible from
95
+ /// `ScalarType dtype`, `Layout layout` and `Device device`. Therefore, we have
96
+ /// three implicit constructors from each of these three types.
97
+ ///
98
+ /// This is sufficient for `ScalarType` and `Layout` as they are simple Enum
99
+ /// classes. However, `Device` is an ordinary class with implicit constructors
100
+ /// `Device(DeviceType, DeviceIndex = -1)` and `Device(std::string)` to be
101
+ /// consistent with Python API, where strings are treated as equivalent with a
102
+ /// `torch.device` object (e.g., "cuda:1" can be passed to everywhere a
103
+ /// `torch.device("cuda:1")` is accepted). To support the syntax
104
+ /// `at::empty({10}, {kCUDA, 1})` and `tensor.to(kCUDA)`, we need to make sure
105
+ /// that `TensorOptions` is implicitly constructible with any arguments that a
106
+ /// `Device` can constructed from. So we have,
107
+ ///
108
+ /// /* implicit */ TensorOptions(T&& device) : TensorOptions() {
109
+ /// this->set_device(device);
110
+ /// }
111
+ ///
112
+ /// template <typename... Args,
113
+ /// typename = std::enable_if_t<std::is_constructible<Device,
114
+ /// Args&&...>::value>>
115
+ /// /* implicit */ TensorOptions(Args&&... args)
116
+ /// : TensorOptions(Device(std::forward<Args>(args)...)) {}
117
+ ///
118
+ ///
119
+ /// But this will be problematic. Consider this: `TensorOptions({kCUDA, 1})`.
120
+ /// Compiler will complain about ambiguity between the copy constructor and the
121
+ /// `Device` constructor because `{kCUDA, 1}` can be converted to both a
122
+ /// `TensorOption` and a `Device`.
123
+ ///
124
+ /// To get around this, we templatize the `Device` constructor. Since overload
125
+ /// resolution is done before template resolution, our problem is solved.
126
+
127
+ DispatchKey computeDispatchKey(
128
+ optional<ScalarType> dtype,
129
+ optional<Layout> layout,
130
+ optional<Device> device);
131
+
132
+ struct C10_API TensorOptions {
133
+ TensorOptions()
134
+ : requires_grad_(false),
135
+ pinned_memory_(false),
136
+ has_device_(false),
137
+ has_dtype_(false),
138
+ has_layout_(false),
139
+ has_requires_grad_(false),
140
+ has_pinned_memory_(false),
141
+ has_memory_format_(false) {}
142
+
143
+ /// Constructs a `TensorOptions` object with the given layout.
144
+ /* implicit */ TensorOptions(Layout layout) : TensorOptions() {
145
+ this->set_layout(layout);
146
+ }
147
+
148
+ /// Constructs a `TensorOptions` object with the given device.
149
+ /// See NOTE [ TensorOptions Constructors ] on why this is templatized.
150
+ template <
151
+ typename T,
152
+ typename = std::enable_if_t<std::is_same<std::decay_t<T>, Device>::value>>
153
+ /* implicit */ TensorOptions(T&& device) : TensorOptions() {
154
+ this->set_device(std::forward<T>(device));
155
+ }
156
+
157
+ /// Constructs a `TensorOptions` object from arguments allowed in `Device`
158
+ /// constructors.
159
+ ///
160
+ /// See NOTE [ TensorOptions Constructors ].
161
+ ///
162
+ /// NB: Ideally we only allow implicit constructors here. But there is no easy
163
+ /// way to detect them. So we have this one that allows explicit
164
+ /// constructors too.
165
+ template <
166
+ typename... Args,
167
+ typename =
168
+ std::enable_if_t<std::is_constructible<Device, Args&&...>::value>>
169
+ /* implicit */ TensorOptions(Args&&... args)
170
+ : TensorOptions(Device(std::forward<Args>(args)...)) {}
171
+
172
+ /// Constructs a `TensorOptions` object with the given dtype.
173
+ /* implicit */ TensorOptions(caffe2::TypeMeta dtype) : TensorOptions() {
174
+ this->set_dtype(dtype);
175
+ }
176
+
177
+ /// legacy constructor to support ScalarType
178
+ /* implicit */ TensorOptions(ScalarType dtype) : TensorOptions() {
179
+ this->set_dtype(dtype);
180
+ }
181
+
182
+ /// Constructs a `TensorOptions` object with the given memory format.
183
+ /* implicit */ TensorOptions(MemoryFormat memory_format) : TensorOptions() {
184
+ set_memory_format(memory_format);
185
+ }
186
+
187
+ /// Return a copy of `TensorOptions` with `device` set to the given one, or
188
+ /// cleared if `device` is `nullopt`.
189
+ C10_NODISCARD TensorOptions
190
+ device(c10::optional<Device> device) const noexcept {
191
+ TensorOptions r = *this;
192
+ r.set_device(device);
193
+ return r;
194
+ }
195
+
196
+ /// Return a copy of `TensorOptions` with `device` set to the given one.
197
+ /// (This overload ensures that variadic template c10::optional constructor
198
+ /// for Device work correctly.)
199
+ template <typename... Args>
200
+ C10_NODISCARD TensorOptions device(Args&&... args) const noexcept {
201
+ return device(
202
+ c10::optional<Device>(c10::in_place, std::forward<Args>(args)...));
203
+ }
204
+
205
+ /// Return a copy of `TensorOptions`, but with device set to CUDA, and the
206
+ /// device index set to the given one.
207
+ ///
208
+ /// TODO: This function encourages bad behavior (assuming CUDA is
209
+ /// the only device that matters). Get rid of it / rename it.
210
+ C10_NODISCARD TensorOptions
211
+ device_index(c10::DeviceIndex device_index) const noexcept {
212
+ return device(Device::Type::CUDA, device_index);
213
+ }
214
+
215
+ /// Return a copy of `TensorOptions` with `dtype` set to the given one.
216
+ C10_NODISCARD TensorOptions
217
+ dtype(c10::optional<caffe2::TypeMeta> dtype) const noexcept {
218
+ TensorOptions r = *this;
219
+ r.set_dtype(dtype);
220
+ return r;
221
+ }
222
+
223
+ // legacy function to support ScalarType
224
+ C10_NODISCARD TensorOptions
225
+ dtype(c10::optional<ScalarType> dtype) const noexcept {
226
+ TensorOptions r = *this;
227
+ r.set_dtype(dtype);
228
+ return r;
229
+ }
230
+
231
+ // Since dtype is taken...
232
+ template <typename T>
233
+ TensorOptions& dtype() {
234
+ dtype_ = caffe2::TypeMeta::Make<T>();
235
+ has_dtype_ = true;
236
+ return *this;
237
+ }
238
+
239
+ /// Sets the layout of the `TensorOptions`.
240
+ C10_NODISCARD TensorOptions
241
+ layout(c10::optional<Layout> layout) const noexcept {
242
+ TensorOptions r = *this;
243
+ r.set_layout(layout);
244
+ return r;
245
+ }
246
+
247
+ /// Sets the `requires_grad` property of the `TensorOptions`.
248
+ C10_NODISCARD TensorOptions
249
+ requires_grad(c10::optional<bool> requires_grad) const noexcept {
250
+ TensorOptions r = *this;
251
+ r.set_requires_grad(requires_grad);
252
+ return r;
253
+ }
254
+
255
+ /// Sets the `pinned_memory` property on the `TensorOptions`.
256
+ C10_NODISCARD TensorOptions
257
+ pinned_memory(c10::optional<bool> pinned_memory) const noexcept {
258
+ TensorOptions r = *this;
259
+ r.set_pinned_memory(pinned_memory);
260
+ return r;
261
+ }
262
+
263
+ /// Sets the `memory_format` property on `TensorOptions`.
264
+ C10_NODISCARD TensorOptions
265
+ memory_format(c10::optional<MemoryFormat> memory_format) const noexcept {
266
+ TensorOptions r = *this;
267
+ r.set_memory_format(memory_format);
268
+ return r;
269
+ }
270
+
271
+ /// Returns the device of the `TensorOptions`.
272
+ Device device() const noexcept {
273
+ return device_or_default(device_opt());
274
+ }
275
+
276
+ /// Returns whether the device is specified.
277
+ bool has_device() const noexcept {
278
+ return has_device_;
279
+ }
280
+
281
+ /// Returns the device of the `TensorOptions`, or `c10::nullopt` if
282
+ /// device is not specified.
283
+ c10::optional<Device> device_opt() const noexcept {
284
+ return has_device_ ? c10::make_optional(device_) : c10::nullopt;
285
+ }
286
+
287
+ /// Returns the device index of the `TensorOptions`.
288
+ int32_t device_index() const noexcept {
289
+ return device().index();
290
+ }
291
+
292
+ /// Returns the dtype of the `TensorOptions`.
293
+ caffe2::TypeMeta dtype() const noexcept {
294
+ return dtype_or_default(dtype_opt());
295
+ }
296
+
297
+ /// Returns whether the dtype is specified.
298
+ bool has_dtype() const noexcept {
299
+ return has_dtype_;
300
+ }
301
+
302
+ /// Returns the dtype of the `TensorOptions`, or `c10::nullopt` if
303
+ /// device is not specified.
304
+ c10::optional<caffe2::TypeMeta> dtype_opt() const noexcept {
305
+ return has_dtype_ ? c10::make_optional(dtype_) : c10::nullopt;
306
+ }
307
+
308
+ /// Returns the layout of the `TensorOptions`.
309
+ Layout layout() const noexcept {
310
+ return layout_or_default(layout_opt());
311
+ }
312
+
313
+ /// Returns whether the layout is specified.
314
+ bool has_layout() const noexcept {
315
+ return has_layout_;
316
+ }
317
+
318
+ /// Returns the layout of the `TensorOptions`, or `c10::nullopt` if
319
+ /// layout is not specified.
320
+ c10::optional<Layout> layout_opt() const noexcept {
321
+ return has_layout_ ? c10::make_optional(layout_) : c10::nullopt;
322
+ }
323
+
324
+ /// Returns the `requires_grad` property of the `TensorOptions`.
325
+ bool requires_grad() const noexcept {
326
+ return has_requires_grad_ ? requires_grad_ : false;
327
+ }
328
+
329
+ /// Returns whether the `requires_grad` is specified.
330
+ bool has_requires_grad() const noexcept {
331
+ return has_requires_grad_;
332
+ }
333
+
334
+ /// Returns the `requires_grad` property of the `TensorOptions`, or
335
+ /// `c10::nullopt` if `requires_grad` is not specified.
336
+ c10::optional<bool> requires_grad_opt() const noexcept {
337
+ return has_requires_grad_ ? c10::make_optional(requires_grad_)
338
+ : c10::nullopt;
339
+ }
340
+
341
+ /// Returns the `pinned_memory` property of the `TensorOptions`.
342
+ bool pinned_memory() const noexcept {
343
+ return pinned_memory_or_default(pinned_memory_opt());
344
+ }
345
+
346
+ /// Returns whether the `pinned_memory` is specified.
347
+ bool has_pinned_memory() const noexcept {
348
+ return has_pinned_memory_;
349
+ }
350
+
351
+ /// Returns if the layout is sparse
352
+ bool is_sparse() const {
353
+ return layout_ == c10::Layout::Sparse;
354
+ }
355
+
356
+ bool is_sparse_csr() const {
357
+ return layout_ == c10::Layout::SparseCsr;
358
+ }
359
+
360
+ // For compatibility with legacy tensor.type() comparisons
361
+ bool type_equal(const TensorOptions& other) const {
362
+ return computeDispatchKey() == other.computeDispatchKey() &&
363
+ typeMetaToScalarType(dtype_) == typeMetaToScalarType(other.dtype());
364
+ }
365
+
366
+ /// Returns the `pinned_memory` property of the `TensorOptions`, or
367
+ /// `c10::nullopt` if `pinned_memory` is not specified.
368
+ c10::optional<bool> pinned_memory_opt() const noexcept {
369
+ return has_pinned_memory_ ? c10::make_optional(pinned_memory_)
370
+ : c10::nullopt;
371
+ }
372
+
373
+ /// Returns whether the `memory_layout` is specified
374
+ bool has_memory_format() const noexcept {
375
+ return has_memory_format_;
376
+ }
377
+
378
+ // NB: memory_format() getter is PURPOSELY not defined, as the default
379
+ // behavior of memory_format varies from function to function.
380
+
381
+ /// Returns the `memory_layout` property of `TensorOptions, or
382
+ /// `c10::nullopt` if `memory_format` is not specified.
383
+ c10::optional<MemoryFormat> memory_format_opt() const noexcept {
384
+ return has_memory_format_ ? c10::make_optional(memory_format_)
385
+ : c10::nullopt;
386
+ }
387
+
388
+ // Resolves the ATen backend specified by the current construction axes.
389
+ // TODO: Deprecate this
390
+ Backend backend() const {
391
+ return at::dispatchKeyToBackend(computeDispatchKey());
392
+ }
393
+
394
+ /// Return the right-biased merge of two TensorOptions. This has the
395
+ /// effect of overwriting settings from self with specified options
396
+ /// of options.
397
+ ///
398
+ /// NB: This merging operation does NOT respect device merges.
399
+ /// For example, if you device({kCUDA, 1}).merge_in(kCUDA)
400
+ /// you will get kCUDA in the end! Functions like Tensor.new_empty
401
+ /// ensure the right device is selected anyway by way of a
402
+ /// device guard.
403
+ ///
404
+ TensorOptions merge_in(TensorOptions options) const noexcept {
405
+ TensorOptions merged = *this;
406
+ if (options.has_device())
407
+ merged.set_device(options.device_opt());
408
+ if (options.has_dtype())
409
+ merged.set_dtype(options.dtype_opt());
410
+ if (options.has_layout())
411
+ merged.set_layout(options.layout_opt());
412
+ // NB: requires grad is right biased; not a logical AND/OR!
413
+ if (options.has_requires_grad())
414
+ merged.set_requires_grad(options.requires_grad_opt());
415
+ if (options.has_pinned_memory())
416
+ merged.set_pinned_memory(options.pinned_memory_opt());
417
+ if (options.has_memory_format())
418
+ merged.set_memory_format(options.memory_format_opt());
419
+ return merged;
420
+ }
421
+
422
+ // TODO remove after TensorOptions rationalization
423
+ TensorOptions merge_memory_format(
424
+ c10::optional<MemoryFormat> optional_memory_format) const noexcept {
425
+ TensorOptions merged = *this;
426
+ if (optional_memory_format.has_value()) {
427
+ merged.set_memory_format(*optional_memory_format);
428
+ }
429
+ return merged;
430
+ }
431
+
432
+ // INVARIANT: computeDispatchKey returns only the subset of dispatch keys for
433
+ // which dispatchKeyToBackend is injective, if it is defined at all (for
434
+ // the most part, this just means that this function never returns an
435
+ // Autograd key)
436
+ DispatchKey computeDispatchKey() const {
437
+ return c10::computeDispatchKey(
438
+ optTypeMetaToScalarType(dtype_opt()), layout_opt(), device_opt());
439
+ }
440
+
441
+ private:
442
+ // These methods are currently private because I'm not sure if it's wise
443
+ // to actually publish them. They are methods because I need them in
444
+ // the constructor and the functional API implementation.
445
+ //
446
+ // If you really, really need it, you can make these public, but check if you
447
+ // couldn't just do what you need with the functional API. Similarly, these
448
+ // methods are not chainable, because if you wanted chaining, you probably
449
+ // want to use the functional API instead. (It's probably OK to make
450
+ // these chainable, because these functions are all explicitly annotated
451
+ // with a ref-qualifier, the trailing &, that makes them illegal to call
452
+ // on temporaries.)
453
+
454
+ /// Mutably set the device of `TensorOptions`.
455
+ void set_device(c10::optional<Device> device) & noexcept {
456
+ if (device) {
457
+ device_ = *device;
458
+ has_device_ = true;
459
+ } else {
460
+ has_device_ = false;
461
+ }
462
+ }
463
+
464
+ /// Mutably set the dtype of `TensorOptions`.
465
+ void set_dtype(c10::optional<caffe2::TypeMeta> dtype) & noexcept {
466
+ if (dtype) {
467
+ dtype_ = *dtype;
468
+ has_dtype_ = true;
469
+ } else {
470
+ has_dtype_ = false;
471
+ }
472
+ }
473
+
474
+ // legacy function to support ScalarType
475
+ void set_dtype(c10::optional<ScalarType> dtype) & noexcept {
476
+ if (dtype) {
477
+ dtype_ = scalarTypeToTypeMeta(*dtype);
478
+ has_dtype_ = true;
479
+ } else {
480
+ has_dtype_ = false;
481
+ }
482
+ }
483
+
484
+ /// Mutably set the layout of `TensorOptions`.
485
+ void set_layout(c10::optional<Layout> layout) & noexcept {
486
+ if (layout) {
487
+ layout_ = *layout;
488
+ has_layout_ = true;
489
+ } else {
490
+ has_layout_ = false;
491
+ }
492
+ }
493
+
494
+ /// Mutably set the `requires_grad` property of `TensorOptions`.
495
+ void set_requires_grad(c10::optional<bool> requires_grad) & noexcept {
496
+ if (requires_grad) {
497
+ requires_grad_ = *requires_grad;
498
+ has_requires_grad_ = true;
499
+ } else {
500
+ has_requires_grad_ = false;
501
+ }
502
+ }
503
+
504
+ /// Mutably set the `pinned_memory` property of `TensorOptions`.
505
+ void set_pinned_memory(c10::optional<bool> pinned_memory) & noexcept {
506
+ if (pinned_memory) {
507
+ pinned_memory_ = *pinned_memory;
508
+ has_pinned_memory_ = true;
509
+ } else {
510
+ has_pinned_memory_ = false;
511
+ }
512
+ }
513
+
514
+ /// Mutably set the `memory_Format` property of `TensorOptions`.
515
+ void set_memory_format(c10::optional<MemoryFormat> memory_format) & noexcept {
516
+ if (memory_format) {
517
+ memory_format_ = *memory_format;
518
+ has_memory_format_ = true;
519
+ } else {
520
+ has_memory_format_ = false;
521
+ }
522
+ }
523
+
524
+ // WARNING: If you edit TensorOptions to add more options, you
525
+ // may need to adjust the implementation of Tensor::options.
526
+ // The criteria for whether or not Tensor::options must be adjusted
527
+ // is whether or not the new option you added should preserved
528
+ // by functions such as empty_like(); if it should be preserved,
529
+ // you must adjust options().
530
+ //
531
+ // TODO: MemoryFormat is not implemented in this way
532
+
533
+ // NB: We didn't use c10::optional here, because then we can't pack
534
+ // the has_***_ boolean fields.
535
+
536
+ Device device_ = at::kCPU; // 16-bit
537
+ caffe2::TypeMeta dtype_ = caffe2::TypeMeta::Make<float>(); // 16-bit
538
+ Layout layout_ = at::kStrided; // 8-bit
539
+ MemoryFormat memory_format_ = MemoryFormat::Contiguous; // 8-bit
540
+
541
+ // Bitmask required here to get this to fit inside 32 bits (or even 64 bits,
542
+ // for that matter)
543
+
544
+ bool requires_grad_ : 1;
545
+ bool pinned_memory_ : 1;
546
+
547
+ bool has_device_ : 1;
548
+ bool has_dtype_ : 1;
549
+ bool has_layout_ : 1;
550
+ bool has_requires_grad_ : 1;
551
+ bool has_pinned_memory_ : 1;
552
+ bool has_memory_format_ : 1;
553
+ };
554
+
555
+ // We should aspire to fit in one machine-size word; but a size greater than two
556
+ // words is too much. (We are doing terribly on 32-bit archs, where we require
557
+ // three machine size words to store tensor options. Eek!)
558
+ static_assert(
559
+ sizeof(TensorOptions) <= sizeof(int64_t) * 2,
560
+ "TensorOptions must fit in 128-bits");
561
+
562
+ /// Convenience function that returns a `TensorOptions` object with the `dtype`
563
+ /// set to the given one.
564
+ inline TensorOptions dtype(caffe2::TypeMeta dtype) {
565
+ return TensorOptions().dtype(dtype);
566
+ }
567
+
568
+ // legacy function to support ScalarType
569
+ inline TensorOptions dtype(ScalarType dtype) {
570
+ return TensorOptions().dtype(scalarTypeToTypeMeta(dtype));
571
+ }
572
+
573
+ /// Convenience function that returns a `TensorOptions` object with the `layout`
574
+ /// set to the given one.
575
+ inline TensorOptions layout(Layout layout) {
576
+ return TensorOptions().layout(layout);
577
+ }
578
+
579
+ /// Convenience function that returns a `TensorOptions` object with the `device`
580
+ /// set to the given one.
581
+ inline TensorOptions device(Device device) {
582
+ return TensorOptions().device(device);
583
+ }
584
+
585
+ /// Convenience function that returns a `TensorOptions` object with the
586
+ /// `device` set to CUDA and the `device_index` set to the given one.
587
+ inline TensorOptions device_index(int16_t device_index) {
588
+ return TensorOptions().device_index(
589
+ static_cast<c10::DeviceIndex>(device_index));
590
+ }
591
+
592
+ /// Convenience function that returns a `TensorOptions` object with the
593
+ /// `requires_grad` set to the given one.
594
+ inline TensorOptions requires_grad(bool requires_grad = true) {
595
+ return TensorOptions().requires_grad(requires_grad);
596
+ }
597
+
598
+ /// Convenience function that returns a `TensorOptions` object with the
599
+ /// `memory_format` set to the given one.
600
+ inline TensorOptions memory_format(MemoryFormat memory_format) {
601
+ return TensorOptions().memory_format(memory_format);
602
+ }
603
+
604
+ C10_API std::ostream& operator<<(
605
+ std::ostream& stream,
606
+ const TensorOptions& options);
607
+
608
+ template <typename T>
609
+ inline TensorOptions dtype() {
610
+ return dtype(caffe2::TypeMeta::Make<T>());
611
+ }
612
+
613
+ inline std::string toString(const TensorOptions& options) {
614
+ std::ostringstream stream;
615
+ stream << options;
616
+ return stream.str();
617
+ }
618
+
619
+ // This is intended to be a centralized location by which we can determine
620
+ // what an appropriate DispatchKey for a tensor is.
621
+ inline DispatchKey computeDispatchKey(
622
+ c10::optional<ScalarType> dtype,
623
+ c10::optional<Layout> layout,
624
+ c10::optional<Device> device) {
625
+ const auto layout_ = layout_or_default(layout);
626
+ const auto device_ = device_or_default(device);
627
+ switch (layout_) {
628
+ case Layout::Jagged:
629
+ case Layout::Strided: {
630
+ const auto dtype_ = dtype_or_default(dtype);
631
+ switch (device_.type()) {
632
+ #define DO_CASE(device, _) \
633
+ case c10::DeviceType::device: { \
634
+ if (isQIntType(dtype_)) { \
635
+ return DispatchKey::Quantized##device; \
636
+ } \
637
+ return DispatchKey::device; \
638
+ }
639
+ C10_FORALL_BACKEND_DEVICE_TYPES(DO_CASE, unused)
640
+ #undef DO_CASE
641
+ case c10::DeviceType::FPGA:
642
+ return DispatchKey::FPGA;
643
+ case c10::DeviceType::ORT:
644
+ return DispatchKey::ORT;
645
+ case c10::DeviceType::Vulkan:
646
+ return DispatchKey::Vulkan;
647
+ case c10::DeviceType::Metal:
648
+ return DispatchKey::Metal;
649
+ case c10::DeviceType::MKLDNN:
650
+ case c10::DeviceType::OPENGL:
651
+ case c10::DeviceType::OPENCL:
652
+ case c10::DeviceType::IDEEP:
653
+ TORCH_INTERNAL_ASSERT(
654
+ 0,
655
+ "This is a grandfathered Caffe2 device type ",
656
+ device_.type(),
657
+ ", it shouldn't ever convert to a DispatchKey. File a bug describing what you were doing if you think this is in error.");
658
+ default:
659
+ TORCH_CHECK_NOT_IMPLEMENTED(
660
+ false,
661
+ "Unsupported device type for dense layout: ",
662
+ device_.type());
663
+ }
664
+ }
665
+ case Layout::Sparse:
666
+ switch (device_.type()) {
667
+ #define DO_CASE(device, _) \
668
+ case c10::DeviceType::device: { \
669
+ return DispatchKey::Sparse##device; \
670
+ }
671
+ C10_FORALL_BACKEND_DEVICE_TYPES(DO_CASE, unused)
672
+ #undef DO_CASE
673
+ default:
674
+ TORCH_CHECK_NOT_IMPLEMENTED(
675
+ false,
676
+ "Unsupported device type for sparse layout: ",
677
+ device_.type());
678
+ }
679
+ case Layout::Mkldnn:
680
+ switch (device_.type()) {
681
+ case c10::DeviceType::CPU:
682
+ return DispatchKey::MkldnnCPU;
683
+ default:
684
+ TORCH_CHECK_NOT_IMPLEMENTED(
685
+ false,
686
+ "Unsupported device type for mkldnn layout: ",
687
+ device_.type());
688
+ }
689
+ case Layout::SparseCsr:
690
+ case Layout::SparseCsc:
691
+ case Layout::SparseBsr:
692
+ case Layout::SparseBsc:
693
+ switch (device_.type()) {
694
+ case c10::DeviceType::CPU:
695
+ return DispatchKey::SparseCsrCPU;
696
+ case c10::DeviceType::CUDA:
697
+ return DispatchKey::SparseCsrCUDA;
698
+ default:
699
+ AT_ERROR(
700
+ "Unsupported device type for ",
701
+ layout_,
702
+ " layout: ",
703
+ device_.type());
704
+ }
705
+ default:
706
+ TORCH_CHECK(false, "Unsupported layout: ", layout_);
707
+ }
708
+ }
709
+
710
+ inline Layout dispatchKeyToLayout(DispatchKey dispatch_key) {
711
+ switch (dispatch_key) {
712
+ #define DO_CASE(bc, _) case DispatchKey::Sparse##bc:
713
+ C10_FORALL_BACKEND_COMPONENTS(DO_CASE, unused)
714
+ #undef DO_CASE
715
+ return Layout::Sparse;
716
+ case DispatchKey::SparseCsrCPU:
717
+ case DispatchKey::SparseCsrCUDA:
718
+ TORCH_CHECK(
719
+ false,
720
+ "Cannot map DispatchKey ",
721
+ dispatch_key,
722
+ " to a unique layout.");
723
+ case DispatchKey::MkldnnCPU:
724
+ return Layout::Mkldnn;
725
+ default:
726
+ return Layout::Strided;
727
+ }
728
+ }
729
+
730
+ inline c10::DeviceType dispatchKeyToDeviceType(DispatchKey dispatch_key) {
731
+ switch (dispatch_key) {
732
+ // stuff that's real
733
+ #define DO_CASE(suffix, prefix) \
734
+ case DispatchKey::prefix##suffix: \
735
+ return c10::DeviceType::suffix;
736
+ #define DO_CASES(_, prefix) C10_FORALL_BACKEND_DEVICE_TYPES(DO_CASE, prefix)
737
+ C10_FORALL_FUNCTIONALITY_KEYS(DO_CASES)
738
+ #undef DO_CASES
739
+ #undef DO_CASE
740
+
741
+ case DispatchKey::MkldnnCPU:
742
+ return c10::DeviceType::CPU;
743
+ case DispatchKey::Vulkan:
744
+ return c10::DeviceType::Vulkan;
745
+
746
+ case DispatchKey::ORT:
747
+ return c10::DeviceType::ORT;
748
+ default:
749
+ TORCH_CHECK(
750
+ false,
751
+ "DispatchKey ",
752
+ dispatch_key,
753
+ " doesn't correspond to a device");
754
+ }
755
+ }
756
+
757
+ inline TensorOptions dispatchKeyToTensorOptions(DispatchKey dispatch_key) {
758
+ return TensorOptions()
759
+ .layout(dispatchKeyToLayout(dispatch_key))
760
+ .device(dispatchKeyToDeviceType(dispatch_key));
761
+ }
762
+
763
+ namespace detail {
764
+ inline bool backend_supports_empty_operator(const TensorOptions& options) {
765
+ // Quantized backends don't support at::empty().
766
+ // They have separate operators like at::empty_quantized() that take in
767
+ // extra information about how to quantize the tensor.
768
+ return !isQIntType(typeMetaToScalarType(options.dtype()));
769
+ }
770
+
771
+ } // namespace detail
772
+
773
+ } // namespace c10
videollama2/lib/python3.10/site-packages/torch/include/c10/macros/Export.h ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_MACROS_EXPORT_H_
2
+ #define C10_MACROS_EXPORT_H_
3
+
4
+ /* Header file to define the common scaffolding for exported symbols.
5
+ *
6
+ * Export is by itself a quite tricky situation to deal with, and if you are
7
+ * hitting this file, make sure you start with the background here:
8
+ * - Linux: https://gcc.gnu.org/wiki/Visibility
9
+ * - Windows:
10
+ * https://docs.microsoft.com/en-us/cpp/cpp/dllexport-dllimport?view=vs-2017
11
+ *
12
+ * Do NOT include this file directly. Instead, use c10/macros/Macros.h
13
+ */
14
+
15
+ // You do not need to edit this part of file unless you are changing the core
16
+ // pytorch export abstractions.
17
+ //
18
+ // This part defines the C10 core export and import macros. This is controlled
19
+ // by whether we are building shared libraries or not, which is determined
20
+ // during build time and codified in c10/core/cmake_macros.h.
21
+ // When the library is built as a shared lib, EXPORT and IMPORT will contain
22
+ // visibility attributes. If it is being built as a static lib, then EXPORT
23
+ // and IMPORT basically have no effect.
24
+
25
+ // As a rule of thumb, you should almost NEVER mix static and shared builds for
26
+ // libraries that depend on c10. AKA, if c10 is built as a static library, we
27
+ // recommend everything dependent on c10 to be built statically. If c10 is built
28
+ // as a shared library, everything dependent on it should be built as shared. In
29
+ // the PyTorch project, all native libraries shall use the macro
30
+ // C10_BUILD_SHARED_LIB to check whether pytorch is building shared or static
31
+ // libraries.
32
+
33
+ // For build systems that do not directly depend on CMake and directly build
34
+ // from the source directory (such as Buck), one may not have a cmake_macros.h
35
+ // file at all. In this case, the build system is responsible for providing
36
+ // correct macro definitions corresponding to the cmake_macros.h.in file.
37
+ //
38
+ // In such scenarios, one should define the macro
39
+ // C10_USING_CUSTOM_GENERATED_MACROS
40
+ // to inform this header that it does not need to include the cmake_macros.h
41
+ // file.
42
+
43
+ #ifndef C10_USING_CUSTOM_GENERATED_MACROS
44
+ #include <c10/macros/cmake_macros.h>
45
+ #endif // C10_USING_CUSTOM_GENERATED_MACROS
46
+
47
+ #ifdef _WIN32
48
+ #define C10_HIDDEN
49
+ #if defined(C10_BUILD_SHARED_LIBS)
50
+ #define C10_EXPORT __declspec(dllexport)
51
+ #define C10_IMPORT __declspec(dllimport)
52
+ #else
53
+ #define C10_EXPORT
54
+ #define C10_IMPORT
55
+ #endif
56
+ #else // _WIN32
57
+ #if defined(__GNUC__)
58
+ #define C10_EXPORT __attribute__((__visibility__("default")))
59
+ #define C10_HIDDEN __attribute__((__visibility__("hidden")))
60
+ #else // defined(__GNUC__)
61
+ #define C10_EXPORT
62
+ #define C10_HIDDEN
63
+ #endif // defined(__GNUC__)
64
+ #define C10_IMPORT C10_EXPORT
65
+ #endif // _WIN32
66
+
67
+ #ifdef NO_EXPORT
68
+ #undef C10_EXPORT
69
+ #define C10_EXPORT
70
+ #endif
71
+
72
+ // Definition of an adaptive XX_API macro, that depends on whether you are
73
+ // building the library itself or not, routes to XX_EXPORT and XX_IMPORT.
74
+ // Basically, you will need to do this for each shared library that you are
75
+ // building, and the instruction is as follows: assuming that you are building
76
+ // a library called libawesome.so. You should:
77
+ // (1) for your cmake target (usually done by "add_library(awesome, ...)"),
78
+ // define a macro called AWESOME_BUILD_MAIN_LIB using
79
+ // target_compile_options.
80
+ // (2) define the AWESOME_API macro similar to the one below.
81
+ // And in the source file of your awesome library, use AWESOME_API to
82
+ // annotate public symbols.
83
+
84
+ // Here, for the C10 library, we will define the macro C10_API for both import
85
+ // and export.
86
+
87
+ // This one is being used by libc10.so
88
+ #ifdef C10_BUILD_MAIN_LIB
89
+ #define C10_API C10_EXPORT
90
+ #else
91
+ #define C10_API C10_IMPORT
92
+ #endif
93
+
94
+ // This one is being used by libtorch.so
95
+ #ifdef CAFFE2_BUILD_MAIN_LIB
96
+ #define TORCH_API C10_EXPORT
97
+ #else
98
+ #define TORCH_API C10_IMPORT
99
+ #endif
100
+
101
+ // You may be wondering: Whose brilliant idea was it to split torch_cuda into
102
+ // two pieces with confusing names?
103
+ // Once upon a time, there _was_ only TORCH_CUDA_API. All was happy until we
104
+ // tried to compile PyTorch for CUDA 11.1, which ran into relocation marker
105
+ // issues when linking big binaries.
106
+ // (https://github.com/pytorch/pytorch/issues/39968) We had two choices:
107
+ // (1) Stop supporting so many GPU architectures
108
+ // (2) Do something else
109
+ // We chose #2 and decided to split the behemoth that was torch_cuda into two
110
+ // smaller libraries, one with most of the core kernel functions (torch_cuda_cu)
111
+ // and the other that had..well..everything else (torch_cuda_cpp). The idea was
112
+ // this: instead of linking our static libraries (like the hefty
113
+ // libcudnn_static.a) with another huge library, torch_cuda, and run into pesky
114
+ // relocation marker issues, we could link our static libraries to a smaller
115
+ // part of torch_cuda (torch_cuda_cpp) and avoid the issues.
116
+
117
+ // libtorch_cuda_cu.so
118
+ #ifdef TORCH_CUDA_CU_BUILD_MAIN_LIB
119
+ #define TORCH_CUDA_CU_API C10_EXPORT
120
+ #elif defined(BUILD_SPLIT_CUDA)
121
+ #define TORCH_CUDA_CU_API C10_IMPORT
122
+ #endif
123
+
124
+ // libtorch_cuda_cpp.so
125
+ #ifdef TORCH_CUDA_CPP_BUILD_MAIN_LIB
126
+ #define TORCH_CUDA_CPP_API C10_EXPORT
127
+ #elif defined(BUILD_SPLIT_CUDA)
128
+ #define TORCH_CUDA_CPP_API C10_IMPORT
129
+ #endif
130
+
131
+ // libtorch_cuda.so (where torch_cuda_cu and torch_cuda_cpp are a part of the
132
+ // same api)
133
+ #ifdef TORCH_CUDA_BUILD_MAIN_LIB
134
+ #define TORCH_CUDA_CPP_API C10_EXPORT
135
+ #define TORCH_CUDA_CU_API C10_EXPORT
136
+ #elif !defined(BUILD_SPLIT_CUDA)
137
+ #define TORCH_CUDA_CPP_API C10_IMPORT
138
+ #define TORCH_CUDA_CU_API C10_IMPORT
139
+ #endif
140
+
141
+ #if defined(TORCH_HIP_BUILD_MAIN_LIB)
142
+ #define TORCH_HIP_API C10_EXPORT
143
+ #else
144
+ #define TORCH_HIP_API C10_IMPORT
145
+ #endif
146
+
147
+ // Enums only need to be exported on windows for non-CUDA files
148
+ #if defined(_WIN32) && defined(__CUDACC__)
149
+ #define C10_API_ENUM C10_API
150
+ #else
151
+ #define C10_API_ENUM
152
+ #endif
153
+
154
+ #endif // C10_MACROS_MACROS_H_
videollama2/lib/python3.10/site-packages/torch/include/c10/macros/Macros.h ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_MACROS_MACROS_H_
2
+ #define C10_MACROS_MACROS_H_
3
+ #include <cassert>
4
+
5
+ /* Main entry for c10/macros.
6
+ *
7
+ * In your code, include c10/macros/Macros.h directly, instead of individual
8
+ * files in this folder.
9
+ */
10
+
11
+ // For build systems that do not directly depend on CMake and directly build
12
+ // from the source directory (such as Buck), one may not have a cmake_macros.h
13
+ // file at all. In this case, the build system is responsible for providing
14
+ // correct macro definitions corresponding to the cmake_macros.h.in file.
15
+ //
16
+ // In such scenarios, one should define the macro
17
+ // C10_USING_CUSTOM_GENERATED_MACROS
18
+ // to inform this header that it does not need to include the cmake_macros.h
19
+ // file.
20
+
21
+ #ifndef C10_USING_CUSTOM_GENERATED_MACROS
22
+ #include <c10/macros/cmake_macros.h>
23
+ #endif // C10_USING_CUSTOM_GENERATED_MACROS
24
+
25
+ #include <c10/macros/Export.h>
26
+
27
+ #if defined(__clang__)
28
+ #define __ubsan_ignore_float_divide_by_zero__ \
29
+ __attribute__((no_sanitize("float-divide-by-zero")))
30
+ #define __ubsan_ignore_undefined__ __attribute__((no_sanitize("undefined")))
31
+ #define __ubsan_ignore_signed_int_overflow__ \
32
+ __attribute__((no_sanitize("signed-integer-overflow")))
33
+ #define __ubsan_ignore_pointer_overflow__ \
34
+ __attribute__((no_sanitize("pointer-overflow")))
35
+ #define __ubsan_ignore_function__ __attribute__((no_sanitize("function")))
36
+ #else
37
+ #define __ubsan_ignore_float_divide_by_zero__
38
+ #define __ubsan_ignore_undefined__
39
+ #define __ubsan_ignore_signed_int_overflow__
40
+ #define __ubsan_ignore_pointer_overflow__
41
+ #define __ubsan_ignore_function__
42
+ #endif
43
+
44
+ // Detect address sanitizer as some stuff doesn't work with it
45
+ #undef C10_ASAN_ENABLED
46
+
47
+ // for clang
48
+ #if defined(__has_feature)
49
+ #if ((__has_feature(address_sanitizer)))
50
+ #define C10_ASAN_ENABLED 1
51
+ #endif
52
+ #endif
53
+
54
+ // for gcc
55
+ #if defined(__SANITIZE_ADDRESS__)
56
+ #if __SANITIZE_ADDRESS__
57
+ #if !defined(C10_ASAN_ENABLED)
58
+ #define C10_ASAN_ENABLED 1
59
+ #endif
60
+ #endif
61
+ #endif
62
+
63
+ #if !defined(C10_ASAN_ENABLED)
64
+ #define C10_ASAN_ENABLED 0
65
+ #endif
66
+
67
+ // Disable the copy and assignment operator for a class. Note that this will
68
+ // disable the usage of the class in std containers.
69
+ #define C10_DISABLE_COPY_AND_ASSIGN(classname) \
70
+ classname(const classname&) = delete; \
71
+ classname& operator=(const classname&) = delete
72
+
73
+ #define C10_CONCATENATE_IMPL(s1, s2) s1##s2
74
+ #define C10_CONCATENATE(s1, s2) C10_CONCATENATE_IMPL(s1, s2)
75
+
76
+ #define C10_MACRO_EXPAND(args) args
77
+
78
+ #define C10_STRINGIZE_IMPL(x) #x
79
+ #define C10_STRINGIZE(x) C10_STRINGIZE_IMPL(x)
80
+
81
+ /**
82
+ * C10_ANONYMOUS_VARIABLE(str) introduces an identifier starting with
83
+ * str and ending with a number that varies with the line.
84
+ */
85
+ #ifdef __COUNTER__
86
+ #define C10_UID __COUNTER__
87
+ #define C10_ANONYMOUS_VARIABLE(str) C10_CONCATENATE(str, __COUNTER__)
88
+ #else
89
+ #define C10_UID __LINE__
90
+ #define C10_ANONYMOUS_VARIABLE(str) C10_CONCATENATE(str, __LINE__)
91
+ #endif
92
+
93
+ #ifdef __has_cpp_attribute
94
+ #define C10_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
95
+ #else
96
+ #define C10_HAS_CPP_ATTRIBUTE(x) (0)
97
+ #endif
98
+
99
+ /// C10_NODISCARD - Warn if a type or return value is discarded.
100
+
101
+ // Technically, we should check if __cplusplus > 201402L here, because
102
+ // [[nodiscard]] is only defined in C++17. However, some compilers
103
+ // we care about don't advertise being C++17 (e.g., clang), but
104
+ // support the attribute anyway. In fact, this is not just a good idea,
105
+ // it's the law: clang::warn_unused_result doesn't work on nvcc + clang
106
+ // and the best workaround for this case is to use [[nodiscard]]
107
+ // instead; see https://github.com/pytorch/pytorch/issues/13118
108
+ //
109
+ // Note to future editors: if you have noticed that a compiler is
110
+ // misbehaving (e.g., it advertises support, but the support doesn't
111
+ // actually work, or it is emitting warnings). Some compilers which
112
+ // are strict about the matter include MSVC, which will complain:
113
+ //
114
+ // error C2429: attribute 'nodiscard' requires compiler flag '/std:c++latest'
115
+ //
116
+ // Exhibits:
117
+ // - MSVC 19.14: https://godbolt.org/z/Dzd7gn (requires /std:c++latest)
118
+ // - Clang 8.0.0: https://godbolt.org/z/3PYL4Z (always advertises support)
119
+ // - gcc 8.3: https://godbolt.org/z/4tLMQS (always advertises support)
120
+ #if C10_HAS_CPP_ATTRIBUTE(nodiscard)
121
+ #define C10_NODISCARD [[nodiscard]]
122
+ // Workaround for llvm.org/PR23435, since clang 3.6 and below emit a spurious
123
+ // error when __has_cpp_attribute is given a scoped attribute in C mode.
124
+ #elif __cplusplus && C10_HAS_CPP_ATTRIBUTE(clang::warn_unused_result)
125
+ // TODO: It's possible this is still triggering
126
+ // https://github.com/pytorch/pytorch/issues/13118 on Windows; if it is, better
127
+ // fix it.
128
+ #define C10_NODISCARD [[clang::warn_unused_result]]
129
+ #else
130
+ #define C10_NODISCARD
131
+ #endif
132
+
133
+ // suppress an unused variable.
134
+ #if defined(_MSC_VER) && !defined(__clang__)
135
+ #define C10_UNUSED __pragma(warning(suppress : 4100 4101))
136
+ #else
137
+ #define C10_UNUSED __attribute__((__unused__))
138
+ #endif //_MSC_VER
139
+
140
+ #if !defined(__has_attribute)
141
+ #define __has_attribute(x) 0
142
+ #endif
143
+
144
+ // Direct port of LLVM_ATTRIBUTE_USED.
145
+ #if __has_attribute(used)
146
+ #define C10_USED __attribute__((__used__))
147
+ #else
148
+ #define C10_USED
149
+ #endif
150
+
151
+ #define C10_RESTRICT __restrict
152
+
153
+ // Simply define the namespace, in case a dependent library want to refer to
154
+ // the c10 namespace but not any nontrivial files.
155
+ namespace c10 {} // namespace c10
156
+ namespace c10 {
157
+ namespace cuda {}
158
+ } // namespace c10
159
+ namespace c10 {
160
+ namespace hip {}
161
+ } // namespace c10
162
+
163
+ // Since C10 is the core library for caffe2 (and aten), we will simply reroute
164
+ // all abstractions defined in c10 to be available in caffe2 as well.
165
+ // This is only for backwards compatibility. Please use the symbols from the
166
+ // c10 namespace where possible.
167
+ namespace caffe2 {
168
+ using namespace c10;
169
+ }
170
+ namespace at {
171
+ using namespace c10;
172
+ }
173
+ namespace at {
174
+ namespace cuda {
175
+ using namespace c10::cuda;
176
+ }
177
+ } // namespace at
178
+
179
+ // WARNING!!! THIS IS A GIANT HACK!!!
180
+ // This line means you cannot simultaneously include c10/hip
181
+ // and c10/cuda and then use them from the at::cuda namespace.
182
+ // This is true in practice, because HIPIFY works inplace on
183
+ // files in ATen/cuda, so it assumes that c10::hip is available
184
+ // from at::cuda. This namespace makes that happen. When
185
+ // HIPIFY is no longer out-of-place, we can switch the cuda
186
+ // here to hip and everyone is happy.
187
+ namespace at {
188
+ namespace cuda {
189
+ using namespace c10::hip;
190
+ }
191
+ } // namespace at
192
+
193
+ // C10_LIKELY/C10_UNLIKELY
194
+ //
195
+ // These macros provide parentheses, so you can use these macros as:
196
+ //
197
+ // if C10_LIKELY(some_expr) {
198
+ // ...
199
+ // }
200
+ //
201
+ // NB: static_cast to boolean is mandatory in C++, because __builtin_expect
202
+ // takes a long argument, which means you may trigger the wrong conversion
203
+ // without it.
204
+ //
205
+ #if defined(__GNUC__) || defined(__ICL) || defined(__clang__)
206
+ #define C10_LIKELY(expr) (__builtin_expect(static_cast<bool>(expr), 1))
207
+ #define C10_UNLIKELY(expr) (__builtin_expect(static_cast<bool>(expr), 0))
208
+ #else
209
+ #define C10_LIKELY(expr) (expr)
210
+ #define C10_UNLIKELY(expr) (expr)
211
+ #endif
212
+
213
+ /// C10_NOINLINE - Functions whose declaration is annotated with this will not
214
+ /// be inlined.
215
+ #ifdef __GNUC__
216
+ #define C10_NOINLINE __attribute__((noinline))
217
+ #elif _MSC_VER
218
+ #define C10_NOINLINE __declspec(noinline)
219
+ #else
220
+ #define C10_NOINLINE
221
+ #endif
222
+
223
+ #if defined(_MSC_VER)
224
+ #define C10_ALWAYS_INLINE __forceinline
225
+ #elif __has_attribute(always_inline) || defined(__GNUC__)
226
+ #define C10_ALWAYS_INLINE __attribute__((__always_inline__)) inline
227
+ #else
228
+ #define C10_ALWAYS_INLINE inline
229
+ #endif
230
+
231
+ #if defined(_MSC_VER)
232
+ #define C10_ATTR_VISIBILITY_HIDDEN
233
+ #elif defined(__GNUC__)
234
+ #define C10_ATTR_VISIBILITY_HIDDEN __attribute__((__visibility__("hidden")))
235
+ #else
236
+ #define C10_ATTR_VISIBILITY_HIDDEN
237
+ #endif
238
+
239
+ #define C10_ERASE C10_ALWAYS_INLINE C10_ATTR_VISIBILITY_HIDDEN
240
+
241
+ // C10_FALLTHROUGH - Annotate fallthrough to the next case in a switch.
242
+ #if C10_HAS_CPP_ATTRIBUTE(fallthrough)
243
+ #define C10_FALLTHROUGH [[fallthrough]]
244
+ #else
245
+ #define C10_FALLTHROUGH
246
+ #endif
247
+
248
+ #include <cstdint>
249
+
250
+ #ifdef __HIPCC__
251
+ // Unlike CUDA, HIP requires a HIP header to be included for __host__ to work.
252
+ // We do this #include here so that C10_HOST_DEVICE and friends will Just Work.
253
+ // See https://github.com/ROCm-Developer-Tools/HIP/issues/441
254
+ #include <hip/hip_runtime.h>
255
+ #endif
256
+
257
+ #if defined(__CUDACC__) || defined(__HIPCC__)
258
+ // Designates functions callable from the host (CPU) and the device (GPU)
259
+ #define C10_HOST_DEVICE __host__ __device__
260
+ #define C10_DEVICE __device__
261
+ #define C10_HOST __host__
262
+ // constants from
263
+ // (https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#features-and-technical-specifications)
264
+ // The maximum number of threads per multiprocessor is 1024 for Turing
265
+ // architecture (7.5), 1536 for Geforce Ampere (8.6)/Jetson Orin (8.7), and
266
+ // 2048 for all other architectures. You'll get warnings if you exceed these
267
+ // constants. Hence, the following macros adjust the input values from the user
268
+ // to resolve potential warnings.
269
+ #if __CUDA_ARCH__ == 750
270
+ constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 1024;
271
+ #elif __CUDA_ARCH__ == 860 || __CUDA_ARCH__ == 870 || __CUDA_ARCH__ == 890
272
+ constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 1536;
273
+ #else
274
+ constexpr uint32_t CUDA_MAX_THREADS_PER_SM = 2048;
275
+ #endif
276
+ // CUDA_MAX_THREADS_PER_BLOCK is same for all architectures currently
277
+ constexpr uint32_t CUDA_MAX_THREADS_PER_BLOCK = 1024;
278
+ // CUDA_THREADS_PER_BLOCK_FALLBACK is the "canonical fallback" choice of block
279
+ // size. 256 is a good number for this fallback and should give good occupancy
280
+ // and versatility across all architectures.
281
+ constexpr uint32_t CUDA_THREADS_PER_BLOCK_FALLBACK = 256;
282
+ // NOTE: if you are thinking of constexpr-ify the inputs to launch bounds, it
283
+ // turns out that although __launch_bounds__ can take constexpr, it
284
+ // can't take a constexpr that has anything to do with templates.
285
+ // Currently we use launch_bounds that depend on template arguments in
286
+ // Loops.cuh, Reduce.cuh and LossCTC.cuh. Hence, C10_MAX_THREADS_PER_BLOCK
287
+ // and C10_MIN_BLOCKS_PER_SM are kept as macros.
288
+ // Suppose you were planning to write __launch_bounds__(a, b), based on your
289
+ // performance tuning on a modern GPU. Instead, you should write
290
+ // __launch_bounds__(C10_MAX_THREADS_PER_BLOCK(a), C10_MIN_BLOCKS_PER_SM(a, b)),
291
+ // which will also properly respect limits on old architectures.
292
+ #define C10_MAX_THREADS_PER_BLOCK(val) \
293
+ (((val) <= CUDA_MAX_THREADS_PER_BLOCK) ? (val) \
294
+ : CUDA_THREADS_PER_BLOCK_FALLBACK)
295
+ #define C10_MIN_BLOCKS_PER_SM(threads_per_block, blocks_per_sm) \
296
+ ((((threads_per_block) * (blocks_per_sm) <= CUDA_MAX_THREADS_PER_SM) \
297
+ ? (blocks_per_sm) \
298
+ : ((CUDA_MAX_THREADS_PER_SM + (threads_per_block)-1) / \
299
+ (threads_per_block))))
300
+ // C10_LAUNCH_BOUNDS is analogous to __launch_bounds__
301
+ #define C10_LAUNCH_BOUNDS_0 \
302
+ __launch_bounds__( \
303
+ 256, 4) // default launch bounds that should give good occupancy and
304
+ // versatility across all architectures.
305
+ #define C10_LAUNCH_BOUNDS_1(max_threads_per_block) \
306
+ __launch_bounds__((C10_MAX_THREADS_PER_BLOCK((max_threads_per_block))))
307
+ #define C10_LAUNCH_BOUNDS_2(max_threads_per_block, min_blocks_per_sm) \
308
+ __launch_bounds__( \
309
+ (C10_MAX_THREADS_PER_BLOCK((max_threads_per_block))), \
310
+ (C10_MIN_BLOCKS_PER_SM((max_threads_per_block), (min_blocks_per_sm))))
311
+ #else
312
+ #define C10_HOST_DEVICE
313
+ #define C10_HOST
314
+ #define C10_DEVICE
315
+ #endif
316
+
317
+ #if defined(USE_ROCM)
318
+ #define C10_HIP_HOST_DEVICE __host__ __device__
319
+ #else
320
+ #define C10_HIP_HOST_DEVICE
321
+ #endif
322
+
323
+ #if defined(USE_ROCM)
324
+ #define C10_WARP_SIZE warpSize // = 64 or 32 (Defined in hip_runtime.h)
325
+ #else
326
+ #define C10_WARP_SIZE 32
327
+ #endif
328
+
329
+ #if defined(_MSC_VER) && _MSC_VER <= 1900
330
+ #define __func__ __FUNCTION__
331
+ #endif
332
+
333
+ // CUDA_KERNEL_ASSERT checks the assertion
334
+ // even when NDEBUG is defined. This is useful for important assertions in CUDA
335
+ // code that would otherwise be suppressed when building Release.
336
+ #if defined(__ANDROID__) || defined(__APPLE__) || defined(__FreeBSD__) || \
337
+ (defined(USE_ROCM) && ROCM_VERSION < 40100)
338
+ // Those platforms do not support assert()
339
+ #define CUDA_KERNEL_ASSERT(cond)
340
+ #define SYCL_KERNEL_ASSERT(cond)
341
+ #elif defined(_MSC_VER)
342
+ #if defined(NDEBUG)
343
+ extern "C" {
344
+ C10_IMPORT
345
+ #if defined(__SYCL_DEVICE_ONLY__)
346
+ extern SYCL_EXTERNAL void _wassert(
347
+ const wchar_t* wexpr,
348
+ const wchar_t* wfile,
349
+ unsigned line);
350
+ #else
351
+ #if defined(__CUDA_ARCH__)
352
+ __host__ __device__
353
+ #endif // __CUDA_ARCH__
354
+ void
355
+ _wassert(wchar_t const* _Message, wchar_t const* _File, unsigned _Line);
356
+ #endif // __SYCL_DEVICE_ONLY__
357
+ }
358
+ #endif // NDEBUG
359
+ #define CUDA_KERNEL_ASSERT(cond) \
360
+ if (C10_UNLIKELY(!(cond))) { \
361
+ (void)(_wassert(_CRT_WIDE(#cond), _CRT_WIDE(__FILE__), static_cast<unsigned>(__LINE__)), 0); \
362
+ }
363
+ #define SYCL_KERNEL_ASSERT(cond) \
364
+ if (C10_UNLIKELY(!(cond))) { \
365
+ (void)(_wassert(_CRT_WIDE(#cond), _CRT_WIDE(__FILE__), static_cast<unsigned>(__LINE__)), 0); \
366
+ }
367
+ #else // __APPLE__, _MSC_VER
368
+ #if defined(NDEBUG)
369
+ extern "C" {
370
+ #if defined(__SYCL_DEVICE_ONLY__)
371
+ extern SYCL_EXTERNAL void __assert_fail(
372
+ const char* expr,
373
+ const char* file,
374
+ unsigned int line,
375
+ const char* func);
376
+ #else // __SYCL_DEVICE_ONLY__
377
+ #if (defined(__CUDA_ARCH__) && !(defined(__clang__) && defined(__CUDA__)))
378
+ // CUDA supports __assert_fail function which are common for both device
379
+ // and host side code.
380
+ __host__ __device__
381
+ #endif
382
+
383
+ // This forward declaration matching the declaration of __assert_fail
384
+ // exactly how it is in glibc in case parts of the program are compiled with
385
+ // different NDEBUG settings. Otherwise we might get 'ambiguous declaration'
386
+ // error. Note: On ROCm - this declaration serves for host side compilation.
387
+ void
388
+ __assert_fail(
389
+ const char* assertion,
390
+ const char* file,
391
+ unsigned int line,
392
+ const char* function) noexcept __attribute__((__noreturn__));
393
+
394
+ #endif // __SYCL_DEVICE_ONLY__
395
+ }
396
+ #endif // NDEBUG
397
+ // ROCm disable kernel assert by default
398
+ #if !defined(C10_USE_ROCM_KERNEL_ASSERT) and defined(USE_ROCM)
399
+ #define CUDA_KERNEL_ASSERT(cond)
400
+ #define SYCL_KERNEL_ASSERT(cond)
401
+ #else
402
+ #define CUDA_KERNEL_ASSERT(cond) \
403
+ if (C10_UNLIKELY(!(cond))) { \
404
+ __assert_fail( \
405
+ #cond, __FILE__, static_cast<unsigned int>(__LINE__), __func__); \
406
+ }
407
+ #define SYCL_KERNEL_ASSERT(cond) \
408
+ if (C10_UNLIKELY(!(cond))) { \
409
+ __assert_fail( \
410
+ #cond, __FILE__, static_cast<unsigned int>(__LINE__), __func__); \
411
+ }
412
+ #endif // C10_USE_ROCM_KERNEL_ASSERT and USE_ROCM
413
+ #endif // __APPLE__
414
+
415
+ #ifdef __APPLE__
416
+ #include <TargetConditionals.h>
417
+ #endif
418
+
419
+ #if defined(__ANDROID__)
420
+ #define C10_ANDROID 1
421
+ #define C10_MOBILE 1
422
+ #elif ( \
423
+ defined(__APPLE__) && \
424
+ (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE))
425
+ #define C10_IOS 1
426
+ #define C10_MOBILE 1
427
+ #endif // ANDROID / IOS
428
+
429
+ #if defined(C10_MOBILE) && C10_MOBILE
430
+ #define C10_ALWAYS_INLINE_UNLESS_MOBILE inline
431
+ #else
432
+ #define C10_ALWAYS_INLINE_UNLESS_MOBILE C10_ALWAYS_INLINE
433
+ #endif
434
+
435
+ // Portable determination of whether type T is trivially copyable.
436
+ // Warning: __has_trivial_copy for GCC may not always detect the non-POD
437
+ // correctly. For example, T = std::unique_ptr may evaluate to true and be
438
+ // treated as POD. This can cause unexpected behavior.
439
+ #if defined(__GNUG__) && __GNUC__ < 5 && !defined(__clang__)
440
+ #define C10_IS_TRIVIALLY_COPYABLE(T) __has_trivial_copy(T)
441
+ #else
442
+ #define C10_IS_TRIVIALLY_COPYABLE(T) std::is_trivially_copyable<T>::value
443
+ #endif
444
+
445
+ #if defined(__CUDA_ARCH__)
446
+ #if defined(_MSC_VER) && defined(__CUDACC__)
447
+ #define CONSTEXPR_EXCEPT_WIN_CUDA const
448
+ #define C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA __host__
449
+
450
+ // Note [static constexpr char* members for windows NVCC]
451
+ // The Windows NVCC compiler doesn't handle static constexpr class members,
452
+ // although it's fixed in a later version.
453
+ // (see
454
+ // https://developercommunity.visualstudio.com/t/intellisense-error-c11-static-constexpr-member-ini/245425)
455
+ //
456
+ // If we want to ensure that our field is static under all builds, then we need
457
+ // to work around it specifically for windows NVCC by making it (a) const, (b)
458
+ // defined outside of the class definition We need to define it outside of the
459
+ // class definition because of the C++ standard; char* is not an integral type
460
+ // (see
461
+ // https://stackoverflow.com/questions/24278473/intellisense-a-member-of-type-const-char-const-cannot-have-an-in-class-in)
462
+ //
463
+ // So instead of this:
464
+ // struct Foo {
465
+ // static constexpr const char* name = "foo";
466
+ // }
467
+ // In Windows NVCC, we end up with this:
468
+ // struct Foo {
469
+ // static const char* name;
470
+ // }
471
+ // const char* Foo::name = "foo";
472
+ //
473
+ // This gives us a small perf hit for any code that wants to access these field
474
+ // members, but right now it isn't used in any perf-critical code paths.
475
+ #define STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(field, val) \
476
+ static const char* field;
477
+ #define STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA(cls, field, val) \
478
+ const char* cls::field = val;
479
+ #else
480
+ #define CONSTEXPR_EXCEPT_WIN_CUDA constexpr
481
+ #define C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA __host__
482
+
483
+ #define STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(field, val) \
484
+ static constexpr const char* field = val;
485
+ #define STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA(cls, field, val)
486
+ #endif
487
+ #else
488
+ #if defined(_MSC_VER) && defined(__CUDACC__)
489
+ #define CONSTEXPR_EXCEPT_WIN_CUDA const
490
+ #define C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA
491
+
492
+ #define STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(field, val) \
493
+ static const char* field;
494
+ #define STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA(cls, field, val) \
495
+ const char* cls::field = val;
496
+ #else
497
+ #define CONSTEXPR_EXCEPT_WIN_CUDA constexpr
498
+ #define C10_HOST_CONSTEXPR_EXCEPT_WIN_CUDA constexpr
499
+
500
+ #define STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(field, val) \
501
+ static constexpr const char* field = val;
502
+ #define STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA(cls, field, val)
503
+ #endif
504
+ #endif
505
+
506
+ #ifndef HAS_DEMANGLE
507
+ #if defined(__ANDROID__) || defined(_WIN32) || defined(__EMSCRIPTEN__)
508
+ #define HAS_DEMANGLE 0
509
+ #elif defined(__APPLE__) && \
510
+ (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE)
511
+ #define HAS_DEMANGLE 0
512
+ #else
513
+ #define HAS_DEMANGLE 1
514
+ #endif
515
+ #endif // HAS_DEMANGLE
516
+
517
+ #define _C10_PRAGMA__(string) _Pragma(#string)
518
+ #define _C10_PRAGMA_(string) _C10_PRAGMA__(string)
519
+
520
+ #ifdef __clang__
521
+ #define C10_CLANG_DIAGNOSTIC_PUSH() _Pragma("clang diagnostic push")
522
+ #define C10_CLANG_DIAGNOSTIC_POP() _Pragma("clang diagnostic pop")
523
+ #define C10_CLANG_DIAGNOSTIC_IGNORE(flag) \
524
+ _C10_PRAGMA_(clang diagnostic ignored flag)
525
+ #define C10_CLANG_HAS_WARNING(flag) __has_warning(flag)
526
+ #else
527
+ #define C10_CLANG_DIAGNOSTIC_PUSH()
528
+ #define C10_CLANG_DIAGNOSTIC_POP()
529
+ #define C10_CLANG_DIAGNOSTIC_IGNORE(flag)
530
+ #define C10_CLANG_HAS_WARNING(flag) 0
531
+ #endif
532
+
533
+ #ifdef __clang__
534
+
535
+ #define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) \
536
+ _C10_PRAGMA_(clang diagnostic push) \
537
+ _C10_PRAGMA_(clang diagnostic ignored "-Wunknown-warning-option") \
538
+ _C10_PRAGMA_(clang diagnostic ignored warning)
539
+
540
+ #define C10_DIAGNOSTIC_POP() _C10_PRAGMA_(clang diagnostic pop)
541
+
542
+ #elif __GNUC__
543
+
544
+ #define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning) \
545
+ _C10_PRAGMA_(GCC diagnostic push) \
546
+ _C10_PRAGMA_(GCC diagnostic ignored "-Wpragmas") \
547
+ _C10_PRAGMA_(GCC diagnostic ignored warning)
548
+
549
+ #define C10_DIAGNOSTIC_POP() _C10_PRAGMA_(GCC diagnostic pop)
550
+
551
+ #else
552
+
553
+ #define C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(warning)
554
+ #define C10_DIAGNOSTIC_POP()
555
+
556
+ #endif
557
+
558
+ #endif // C10_MACROS_MACROS_H_
videollama2/lib/python3.10/site-packages/torch/include/c10/macros/cmake_macros.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef C10_MACROS_CMAKE_MACROS_H_
2
+ #define C10_MACROS_CMAKE_MACROS_H_
3
+
4
+ // Automatically generated header file for the C10 library.
5
+ // Do not include this file directly. Instead, include c10/macros/Macros.h.
6
+
7
+ #define C10_BUILD_SHARED_LIBS
8
+ /* #undef C10_USE_GLOG */
9
+ /* #undef C10_USE_GFLAGS */
10
+ /* #undef C10_USE_NUMA */
11
+ /* #undef C10_USE_MSVC_STATIC_RUNTIME */
12
+ /* #undef C10_USE_ROCM_KERNEL_ASSERT */
13
+
14
+ #endif // C10_MACROS_CMAKE_MACROS_H_
videollama2/lib/python3.10/site-packages/torch/include/clog.h ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <stdarg.h>
4
+ #include <stdlib.h>
5
+ #include <inttypes.h>
6
+
7
+ #define CLOG_NONE 0
8
+ #define CLOG_FATAL 1
9
+ #define CLOG_ERROR 2
10
+ #define CLOG_WARNING 3
11
+ #define CLOG_INFO 4
12
+ #define CLOG_DEBUG 5
13
+
14
+ #ifndef CLOG_VISIBILITY
15
+ #if defined(__ELF__)
16
+ #define CLOG_VISIBILITY __attribute__((__visibility__("internal")))
17
+ #elif defined(__MACH__)
18
+ #define CLOG_VISIBILITY __attribute__((__visibility__("hidden")))
19
+ #else
20
+ #define CLOG_VISIBILITY
21
+ #endif
22
+ #endif
23
+
24
+ #ifndef CLOG_ARGUMENTS_FORMAT
25
+ #if defined(__GNUC__)
26
+ #define CLOG_ARGUMENTS_FORMAT __attribute__((__format__(__printf__, 1, 2)))
27
+ #else
28
+ #define CLOG_ARGUMENTS_FORMAT
29
+ #endif
30
+ #endif
31
+
32
+ #ifdef __cplusplus
33
+ extern "C" {
34
+ #endif
35
+
36
+ CLOG_VISIBILITY void clog_vlog_debug(const char* module, const char* format, va_list args);
37
+ CLOG_VISIBILITY void clog_vlog_info(const char* module, const char* format, va_list args);
38
+ CLOG_VISIBILITY void clog_vlog_warning(const char* module, const char* format, va_list args);
39
+ CLOG_VISIBILITY void clog_vlog_error(const char* module, const char* format, va_list args);
40
+ CLOG_VISIBILITY void clog_vlog_fatal(const char* module, const char* format, va_list args);
41
+
42
+ #define CLOG_DEFINE_LOG_DEBUG(log_debug_function_name, module, level) \
43
+ CLOG_ARGUMENTS_FORMAT \
44
+ inline static void log_debug_function_name(const char* format, ...) { \
45
+ if (level >= CLOG_DEBUG) { \
46
+ va_list args; \
47
+ va_start(args, format); \
48
+ clog_vlog_debug(module, format, args); \
49
+ va_end(args); \
50
+ } \
51
+ }
52
+
53
+ #define CLOG_DEFINE_LOG_INFO(log_info_function_name, module, level) \
54
+ CLOG_ARGUMENTS_FORMAT \
55
+ inline static void log_info_function_name(const char* format, ...) { \
56
+ if (level >= CLOG_INFO) { \
57
+ va_list args; \
58
+ va_start(args, format); \
59
+ clog_vlog_info(module, format, args); \
60
+ va_end(args); \
61
+ } \
62
+ }
63
+
64
+ #define CLOG_DEFINE_LOG_WARNING(log_warning_function_name, module, level) \
65
+ CLOG_ARGUMENTS_FORMAT \
66
+ inline static void log_warning_function_name(const char* format, ...) { \
67
+ if (level >= CLOG_WARNING) { \
68
+ va_list args; \
69
+ va_start(args, format); \
70
+ clog_vlog_warning(module, format, args); \
71
+ va_end(args); \
72
+ } \
73
+ }
74
+
75
+ #define CLOG_DEFINE_LOG_ERROR(log_error_function_name, module, level) \
76
+ CLOG_ARGUMENTS_FORMAT \
77
+ inline static void log_error_function_name(const char* format, ...) { \
78
+ if (level >= CLOG_ERROR) { \
79
+ va_list args; \
80
+ va_start(args, format); \
81
+ clog_vlog_error(module, format, args); \
82
+ va_end(args); \
83
+ } \
84
+ }
85
+
86
+ #define CLOG_DEFINE_LOG_FATAL(log_fatal_function_name, module, level) \
87
+ CLOG_ARGUMENTS_FORMAT \
88
+ inline static void log_fatal_function_name(const char* format, ...) { \
89
+ if (level >= CLOG_FATAL) { \
90
+ va_list args; \
91
+ va_start(args, format); \
92
+ clog_vlog_fatal(module, format, args); \
93
+ va_end(args); \
94
+ } \
95
+ abort(); \
96
+ }
97
+
98
+ #ifdef __cplusplus
99
+ } /* extern "C" */
100
+ #endif
videollama2/lib/python3.10/site-packages/torch/include/cpuinfo.h ADDED
@@ -0,0 +1,1939 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #ifndef CPUINFO_H
3
+ #define CPUINFO_H
4
+
5
+ #ifndef __cplusplus
6
+ #include <stdbool.h>
7
+ #endif
8
+
9
+ #ifdef __APPLE__
10
+ #include <TargetConditionals.h>
11
+ #endif
12
+
13
+ #include <stdint.h>
14
+
15
+ /* Identify architecture and define corresponding macro */
16
+
17
+ #if defined(__i386__) || defined(__i486__) || defined(__i586__) || defined(__i686__) || defined(_M_IX86)
18
+ #define CPUINFO_ARCH_X86 1
19
+ #endif
20
+
21
+ #if defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64)
22
+ #define CPUINFO_ARCH_X86_64 1
23
+ #endif
24
+
25
+ #if defined(__arm__) || defined(_M_ARM)
26
+ #define CPUINFO_ARCH_ARM 1
27
+ #endif
28
+
29
+ #if defined(__aarch64__) || defined(_M_ARM64)
30
+ #define CPUINFO_ARCH_ARM64 1
31
+ #endif
32
+
33
+ #if defined(__PPC64__) || defined(__powerpc64__) || defined(_ARCH_PPC64)
34
+ #define CPUINFO_ARCH_PPC64 1
35
+ #endif
36
+
37
+ #if defined(__asmjs__)
38
+ #define CPUINFO_ARCH_ASMJS 1
39
+ #endif
40
+
41
+ #if defined(__wasm__)
42
+ #if defined(__wasm_simd128__)
43
+ #define CPUINFO_ARCH_WASMSIMD 1
44
+ #else
45
+ #define CPUINFO_ARCH_WASM 1
46
+ #endif
47
+ #endif
48
+
49
+ /* Define other architecture-specific macros as 0 */
50
+
51
+ #ifndef CPUINFO_ARCH_X86
52
+ #define CPUINFO_ARCH_X86 0
53
+ #endif
54
+
55
+ #ifndef CPUINFO_ARCH_X86_64
56
+ #define CPUINFO_ARCH_X86_64 0
57
+ #endif
58
+
59
+ #ifndef CPUINFO_ARCH_ARM
60
+ #define CPUINFO_ARCH_ARM 0
61
+ #endif
62
+
63
+ #ifndef CPUINFO_ARCH_ARM64
64
+ #define CPUINFO_ARCH_ARM64 0
65
+ #endif
66
+
67
+ #ifndef CPUINFO_ARCH_PPC64
68
+ #define CPUINFO_ARCH_PPC64 0
69
+ #endif
70
+
71
+ #ifndef CPUINFO_ARCH_ASMJS
72
+ #define CPUINFO_ARCH_ASMJS 0
73
+ #endif
74
+
75
+ #ifndef CPUINFO_ARCH_WASM
76
+ #define CPUINFO_ARCH_WASM 0
77
+ #endif
78
+
79
+ #ifndef CPUINFO_ARCH_WASMSIMD
80
+ #define CPUINFO_ARCH_WASMSIMD 0
81
+ #endif
82
+
83
+ #if CPUINFO_ARCH_X86 && defined(_MSC_VER)
84
+ #define CPUINFO_ABI __cdecl
85
+ #elif CPUINFO_ARCH_X86 && defined(__GNUC__)
86
+ #define CPUINFO_ABI __attribute__((__cdecl__))
87
+ #else
88
+ #define CPUINFO_ABI
89
+ #endif
90
+
91
+ #define CPUINFO_CACHE_UNIFIED 0x00000001
92
+ #define CPUINFO_CACHE_INCLUSIVE 0x00000002
93
+ #define CPUINFO_CACHE_COMPLEX_INDEXING 0x00000004
94
+
95
+ struct cpuinfo_cache {
96
+ /** Cache size in bytes */
97
+ uint32_t size;
98
+ /** Number of ways of associativity */
99
+ uint32_t associativity;
100
+ /** Number of sets */
101
+ uint32_t sets;
102
+ /** Number of partitions */
103
+ uint32_t partitions;
104
+ /** Line size in bytes */
105
+ uint32_t line_size;
106
+ /**
107
+ * Binary characteristics of the cache (unified cache, inclusive cache, cache with complex indexing).
108
+ *
109
+ * @see CPUINFO_CACHE_UNIFIED, CPUINFO_CACHE_INCLUSIVE, CPUINFO_CACHE_COMPLEX_INDEXING
110
+ */
111
+ uint32_t flags;
112
+ /** Index of the first logical processor that shares this cache */
113
+ uint32_t processor_start;
114
+ /** Number of logical processors that share this cache */
115
+ uint32_t processor_count;
116
+ };
117
+
118
+ struct cpuinfo_trace_cache {
119
+ uint32_t uops;
120
+ uint32_t associativity;
121
+ };
122
+
123
+ #define CPUINFO_PAGE_SIZE_4KB 0x1000
124
+ #define CPUINFO_PAGE_SIZE_1MB 0x100000
125
+ #define CPUINFO_PAGE_SIZE_2MB 0x200000
126
+ #define CPUINFO_PAGE_SIZE_4MB 0x400000
127
+ #define CPUINFO_PAGE_SIZE_16MB 0x1000000
128
+ #define CPUINFO_PAGE_SIZE_1GB 0x40000000
129
+
130
+ struct cpuinfo_tlb {
131
+ uint32_t entries;
132
+ uint32_t associativity;
133
+ uint64_t pages;
134
+ };
135
+
136
+ /** Vendor of processor core design */
137
+ enum cpuinfo_vendor {
138
+ /** Processor vendor is not known to the library, or the library failed to get vendor information from the OS. */
139
+ cpuinfo_vendor_unknown = 0,
140
+
141
+ /* Active vendors of modern CPUs */
142
+
143
+ /**
144
+ * Intel Corporation. Vendor of x86, x86-64, IA64, and ARM processor microarchitectures.
145
+ *
146
+ * Sold its ARM design subsidiary in 2006. The last ARM processor design was released in 2004.
147
+ */
148
+ cpuinfo_vendor_intel = 1,
149
+ /** Advanced Micro Devices, Inc. Vendor of x86 and x86-64 processor microarchitectures. */
150
+ cpuinfo_vendor_amd = 2,
151
+ /** ARM Holdings plc. Vendor of ARM and ARM64 processor microarchitectures. */
152
+ cpuinfo_vendor_arm = 3,
153
+ /** Qualcomm Incorporated. Vendor of ARM and ARM64 processor microarchitectures. */
154
+ cpuinfo_vendor_qualcomm = 4,
155
+ /** Apple Inc. Vendor of ARM and ARM64 processor microarchitectures. */
156
+ cpuinfo_vendor_apple = 5,
157
+ /** Samsung Electronics Co., Ltd. Vendir if ARM64 processor microarchitectures. */
158
+ cpuinfo_vendor_samsung = 6,
159
+ /** Nvidia Corporation. Vendor of ARM64-compatible processor microarchitectures. */
160
+ cpuinfo_vendor_nvidia = 7,
161
+ /** MIPS Technologies, Inc. Vendor of MIPS processor microarchitectures. */
162
+ cpuinfo_vendor_mips = 8,
163
+ /** International Business Machines Corporation. Vendor of PowerPC processor microarchitectures. */
164
+ cpuinfo_vendor_ibm = 9,
165
+ /** Ingenic Semiconductor. Vendor of MIPS processor microarchitectures. */
166
+ cpuinfo_vendor_ingenic = 10,
167
+ /**
168
+ * VIA Technologies, Inc. Vendor of x86 and x86-64 processor microarchitectures.
169
+ *
170
+ * Processors are designed by Centaur Technology, a subsidiary of VIA Technologies.
171
+ */
172
+ cpuinfo_vendor_via = 11,
173
+ /** Cavium, Inc. Vendor of ARM64 processor microarchitectures. */
174
+ cpuinfo_vendor_cavium = 12,
175
+ /** Broadcom, Inc. Vendor of ARM processor microarchitectures. */
176
+ cpuinfo_vendor_broadcom = 13,
177
+ /** Applied Micro Circuits Corporation (APM). Vendor of ARM64 processor microarchitectures. */
178
+ cpuinfo_vendor_apm = 14,
179
+ /**
180
+ * Huawei Technologies Co., Ltd. Vendor of ARM64 processor microarchitectures.
181
+ *
182
+ * Processors are designed by HiSilicon, a subsidiary of Huawei.
183
+ */
184
+ cpuinfo_vendor_huawei = 15,
185
+ /**
186
+ * Hygon (Chengdu Haiguang Integrated Circuit Design Co., Ltd), Vendor of x86-64 processor microarchitectures.
187
+ *
188
+ * Processors are variants of AMD cores.
189
+ */
190
+ cpuinfo_vendor_hygon = 16,
191
+
192
+ /* Active vendors of embedded CPUs */
193
+
194
+ /** Texas Instruments Inc. Vendor of ARM processor microarchitectures. */
195
+ cpuinfo_vendor_texas_instruments = 30,
196
+ /** Marvell Technology Group Ltd. Vendor of ARM processor microarchitectures. */
197
+ cpuinfo_vendor_marvell = 31,
198
+ /** RDC Semiconductor Co., Ltd. Vendor of x86 processor microarchitectures. */
199
+ cpuinfo_vendor_rdc = 32,
200
+ /** DM&P Electronics Inc. Vendor of x86 processor microarchitectures. */
201
+ cpuinfo_vendor_dmp = 33,
202
+ /** Motorola, Inc. Vendor of PowerPC and ARM processor microarchitectures. */
203
+ cpuinfo_vendor_motorola = 34,
204
+
205
+ /* Defunct CPU vendors */
206
+
207
+ /**
208
+ * Transmeta Corporation. Vendor of x86 processor microarchitectures.
209
+ *
210
+ * Now defunct. The last processor design was released in 2004.
211
+ * Transmeta processors implemented VLIW ISA and used binary translation to execute x86 code.
212
+ */
213
+ cpuinfo_vendor_transmeta = 50,
214
+ /**
215
+ * Cyrix Corporation. Vendor of x86 processor microarchitectures.
216
+ *
217
+ * Now defunct. The last processor design was released in 1996.
218
+ */
219
+ cpuinfo_vendor_cyrix = 51,
220
+ /**
221
+ * Rise Technology. Vendor of x86 processor microarchitectures.
222
+ *
223
+ * Now defunct. The last processor design was released in 1999.
224
+ */
225
+ cpuinfo_vendor_rise = 52,
226
+ /**
227
+ * National Semiconductor. Vendor of x86 processor microarchitectures.
228
+ *
229
+ * Sold its x86 design subsidiary in 1999. The last processor design was released in 1998.
230
+ */
231
+ cpuinfo_vendor_nsc = 53,
232
+ /**
233
+ * Silicon Integrated Systems. Vendor of x86 processor microarchitectures.
234
+ *
235
+ * Sold its x86 design subsidiary in 2001. The last processor design was released in 2001.
236
+ */
237
+ cpuinfo_vendor_sis = 54,
238
+ /**
239
+ * NexGen. Vendor of x86 processor microarchitectures.
240
+ *
241
+ * Now defunct. The last processor design was released in 1994.
242
+ * NexGen designed the first x86 microarchitecture which decomposed x86 instructions into simple microoperations.
243
+ */
244
+ cpuinfo_vendor_nexgen = 55,
245
+ /**
246
+ * United Microelectronics Corporation. Vendor of x86 processor microarchitectures.
247
+ *
248
+ * Ceased x86 in the early 1990s. The last processor design was released in 1991.
249
+ * Designed U5C and U5D processors. Both are 486 level.
250
+ */
251
+ cpuinfo_vendor_umc = 56,
252
+ /**
253
+ * Digital Equipment Corporation. Vendor of ARM processor microarchitecture.
254
+ *
255
+ * Sold its ARM designs in 1997. The last processor design was released in 1997.
256
+ */
257
+ cpuinfo_vendor_dec = 57,
258
+ };
259
+
260
+ /**
261
+ * Processor microarchitecture
262
+ *
263
+ * Processors with different microarchitectures often have different instruction performance characteristics,
264
+ * and may have dramatically different pipeline organization.
265
+ */
266
+ enum cpuinfo_uarch {
267
+ /** Microarchitecture is unknown, or the library failed to get information about the microarchitecture from OS */
268
+ cpuinfo_uarch_unknown = 0,
269
+
270
+ /** Pentium and Pentium MMX microarchitecture. */
271
+ cpuinfo_uarch_p5 = 0x00100100,
272
+ /** Intel Quark microarchitecture. */
273
+ cpuinfo_uarch_quark = 0x00100101,
274
+
275
+ /** Pentium Pro, Pentium II, and Pentium III. */
276
+ cpuinfo_uarch_p6 = 0x00100200,
277
+ /** Pentium M. */
278
+ cpuinfo_uarch_dothan = 0x00100201,
279
+ /** Intel Core microarchitecture. */
280
+ cpuinfo_uarch_yonah = 0x00100202,
281
+ /** Intel Core 2 microarchitecture on 65 nm process. */
282
+ cpuinfo_uarch_conroe = 0x00100203,
283
+ /** Intel Core 2 microarchitecture on 45 nm process. */
284
+ cpuinfo_uarch_penryn = 0x00100204,
285
+ /** Intel Nehalem and Westmere microarchitectures (Core i3/i5/i7 1st gen). */
286
+ cpuinfo_uarch_nehalem = 0x00100205,
287
+ /** Intel Sandy Bridge microarchitecture (Core i3/i5/i7 2nd gen). */
288
+ cpuinfo_uarch_sandy_bridge = 0x00100206,
289
+ /** Intel Ivy Bridge microarchitecture (Core i3/i5/i7 3rd gen). */
290
+ cpuinfo_uarch_ivy_bridge = 0x00100207,
291
+ /** Intel Haswell microarchitecture (Core i3/i5/i7 4th gen). */
292
+ cpuinfo_uarch_haswell = 0x00100208,
293
+ /** Intel Broadwell microarchitecture. */
294
+ cpuinfo_uarch_broadwell = 0x00100209,
295
+ /** Intel Sky Lake microarchitecture (14 nm, including Kaby/Coffee/Whiskey/Amber/Comet/Cascade/Cooper Lake). */
296
+ cpuinfo_uarch_sky_lake = 0x0010020A,
297
+ /** DEPRECATED (Intel Kaby Lake microarchitecture). */
298
+ cpuinfo_uarch_kaby_lake = 0x0010020A,
299
+ /** Intel Palm Cove microarchitecture (10 nm, Cannon Lake). */
300
+ cpuinfo_uarch_palm_cove = 0x0010020B,
301
+ /** Intel Sunny Cove microarchitecture (10 nm, Ice Lake). */
302
+ cpuinfo_uarch_sunny_cove = 0x0010020C,
303
+
304
+ /** Pentium 4 with Willamette, Northwood, or Foster cores. */
305
+ cpuinfo_uarch_willamette = 0x00100300,
306
+ /** Pentium 4 with Prescott and later cores. */
307
+ cpuinfo_uarch_prescott = 0x00100301,
308
+
309
+ /** Intel Atom on 45 nm process. */
310
+ cpuinfo_uarch_bonnell = 0x00100400,
311
+ /** Intel Atom on 32 nm process. */
312
+ cpuinfo_uarch_saltwell = 0x00100401,
313
+ /** Intel Silvermont microarchitecture (22 nm out-of-order Atom). */
314
+ cpuinfo_uarch_silvermont = 0x00100402,
315
+ /** Intel Airmont microarchitecture (14 nm out-of-order Atom). */
316
+ cpuinfo_uarch_airmont = 0x00100403,
317
+ /** Intel Goldmont microarchitecture (Denverton, Apollo Lake). */
318
+ cpuinfo_uarch_goldmont = 0x00100404,
319
+ /** Intel Goldmont Plus microarchitecture (Gemini Lake). */
320
+ cpuinfo_uarch_goldmont_plus = 0x00100405,
321
+
322
+ /** Intel Knights Ferry HPC boards. */
323
+ cpuinfo_uarch_knights_ferry = 0x00100500,
324
+ /** Intel Knights Corner HPC boards (aka Xeon Phi). */
325
+ cpuinfo_uarch_knights_corner = 0x00100501,
326
+ /** Intel Knights Landing microarchitecture (second-gen MIC). */
327
+ cpuinfo_uarch_knights_landing = 0x00100502,
328
+ /** Intel Knights Hill microarchitecture (third-gen MIC). */
329
+ cpuinfo_uarch_knights_hill = 0x00100503,
330
+ /** Intel Knights Mill Xeon Phi. */
331
+ cpuinfo_uarch_knights_mill = 0x00100504,
332
+
333
+ /** Intel/Marvell XScale series. */
334
+ cpuinfo_uarch_xscale = 0x00100600,
335
+
336
+ /** AMD K5. */
337
+ cpuinfo_uarch_k5 = 0x00200100,
338
+ /** AMD K6 and alike. */
339
+ cpuinfo_uarch_k6 = 0x00200101,
340
+ /** AMD Athlon and Duron. */
341
+ cpuinfo_uarch_k7 = 0x00200102,
342
+ /** AMD Athlon 64, Opteron 64. */
343
+ cpuinfo_uarch_k8 = 0x00200103,
344
+ /** AMD Family 10h (Barcelona, Istambul, Magny-Cours). */
345
+ cpuinfo_uarch_k10 = 0x00200104,
346
+ /**
347
+ * AMD Bulldozer microarchitecture
348
+ * Zambezi FX-series CPUs, Zurich, Valencia and Interlagos Opteron CPUs.
349
+ */
350
+ cpuinfo_uarch_bulldozer = 0x00200105,
351
+ /**
352
+ * AMD Piledriver microarchitecture
353
+ * Vishera FX-series CPUs, Trinity and Richland APUs, Delhi, Seoul, Abu Dhabi Opteron CPUs.
354
+ */
355
+ cpuinfo_uarch_piledriver = 0x00200106,
356
+ /** AMD Steamroller microarchitecture (Kaveri APUs). */
357
+ cpuinfo_uarch_steamroller = 0x00200107,
358
+ /** AMD Excavator microarchitecture (Carizzo APUs). */
359
+ cpuinfo_uarch_excavator = 0x00200108,
360
+ /** AMD Zen microarchitecture (12/14 nm Ryzen and EPYC CPUs). */
361
+ cpuinfo_uarch_zen = 0x00200109,
362
+ /** AMD Zen 2 microarchitecture (7 nm Ryzen and EPYC CPUs). */
363
+ cpuinfo_uarch_zen2 = 0x0020010A,
364
+ /** AMD Zen 3 microarchitecture. */
365
+ cpuinfo_uarch_zen3 = 0x0020010B,
366
+
367
+ /** NSC Geode and AMD Geode GX and LX. */
368
+ cpuinfo_uarch_geode = 0x00200200,
369
+ /** AMD Bobcat mobile microarchitecture. */
370
+ cpuinfo_uarch_bobcat = 0x00200201,
371
+ /** AMD Jaguar mobile microarchitecture. */
372
+ cpuinfo_uarch_jaguar = 0x00200202,
373
+ /** AMD Puma mobile microarchitecture. */
374
+ cpuinfo_uarch_puma = 0x00200203,
375
+
376
+ /** ARM7 series. */
377
+ cpuinfo_uarch_arm7 = 0x00300100,
378
+ /** ARM9 series. */
379
+ cpuinfo_uarch_arm9 = 0x00300101,
380
+ /** ARM 1136, ARM 1156, ARM 1176, or ARM 11MPCore. */
381
+ cpuinfo_uarch_arm11 = 0x00300102,
382
+
383
+ /** ARM Cortex-A5. */
384
+ cpuinfo_uarch_cortex_a5 = 0x00300205,
385
+ /** ARM Cortex-A7. */
386
+ cpuinfo_uarch_cortex_a7 = 0x00300207,
387
+ /** ARM Cortex-A8. */
388
+ cpuinfo_uarch_cortex_a8 = 0x00300208,
389
+ /** ARM Cortex-A9. */
390
+ cpuinfo_uarch_cortex_a9 = 0x00300209,
391
+ /** ARM Cortex-A12. */
392
+ cpuinfo_uarch_cortex_a12 = 0x00300212,
393
+ /** ARM Cortex-A15. */
394
+ cpuinfo_uarch_cortex_a15 = 0x00300215,
395
+ /** ARM Cortex-A17. */
396
+ cpuinfo_uarch_cortex_a17 = 0x00300217,
397
+
398
+ /** ARM Cortex-A32. */
399
+ cpuinfo_uarch_cortex_a32 = 0x00300332,
400
+ /** ARM Cortex-A35. */
401
+ cpuinfo_uarch_cortex_a35 = 0x00300335,
402
+ /** ARM Cortex-A53. */
403
+ cpuinfo_uarch_cortex_a53 = 0x00300353,
404
+ /** ARM Cortex-A55 revision 0 (restricted dual-issue capabilities compared to revision 1+). */
405
+ cpuinfo_uarch_cortex_a55r0 = 0x00300354,
406
+ /** ARM Cortex-A55. */
407
+ cpuinfo_uarch_cortex_a55 = 0x00300355,
408
+ /** ARM Cortex-A57. */
409
+ cpuinfo_uarch_cortex_a57 = 0x00300357,
410
+ /** ARM Cortex-A65. */
411
+ cpuinfo_uarch_cortex_a65 = 0x00300365,
412
+ /** ARM Cortex-A72. */
413
+ cpuinfo_uarch_cortex_a72 = 0x00300372,
414
+ /** ARM Cortex-A73. */
415
+ cpuinfo_uarch_cortex_a73 = 0x00300373,
416
+ /** ARM Cortex-A75. */
417
+ cpuinfo_uarch_cortex_a75 = 0x00300375,
418
+ /** ARM Cortex-A76. */
419
+ cpuinfo_uarch_cortex_a76 = 0x00300376,
420
+ /** ARM Cortex-A77. */
421
+ cpuinfo_uarch_cortex_a77 = 0x00300377,
422
+ /** ARM Cortex-A78. */
423
+ cpuinfo_uarch_cortex_a78 = 0x00300378,
424
+
425
+ /** ARM Neoverse N1. */
426
+ cpuinfo_uarch_neoverse_n1 = 0x00300400,
427
+ /** ARM Neoverse E1. */
428
+ cpuinfo_uarch_neoverse_e1 = 0x00300401,
429
+ /** ARM Neoverse V1. */
430
+ cpuinfo_uarch_neoverse_v1 = 0x00300402,
431
+ /** ARM Neoverse N2. */
432
+ cpuinfo_uarch_neoverse_n2 = 0x00300403,
433
+
434
+ /** ARM Cortex-X1. */
435
+ cpuinfo_uarch_cortex_x1 = 0x00300501,
436
+ /** ARM Cortex-X2. */
437
+ cpuinfo_uarch_cortex_x2 = 0x00300502,
438
+
439
+ /** ARM Cortex-A510. */
440
+ cpuinfo_uarch_cortex_a510 = 0x00300551,
441
+ /** ARM Cortex-A710. */
442
+ cpuinfo_uarch_cortex_a710 = 0x00300571,
443
+
444
+ /** Qualcomm Scorpion. */
445
+ cpuinfo_uarch_scorpion = 0x00400100,
446
+ /** Qualcomm Krait. */
447
+ cpuinfo_uarch_krait = 0x00400101,
448
+ /** Qualcomm Kryo. */
449
+ cpuinfo_uarch_kryo = 0x00400102,
450
+ /** Qualcomm Falkor. */
451
+ cpuinfo_uarch_falkor = 0x00400103,
452
+ /** Qualcomm Saphira. */
453
+ cpuinfo_uarch_saphira = 0x00400104,
454
+
455
+ /** Nvidia Denver. */
456
+ cpuinfo_uarch_denver = 0x00500100,
457
+ /** Nvidia Denver 2. */
458
+ cpuinfo_uarch_denver2 = 0x00500101,
459
+ /** Nvidia Carmel. */
460
+ cpuinfo_uarch_carmel = 0x00500102,
461
+
462
+ /** Samsung Exynos M1 (Exynos 8890 big cores). */
463
+ cpuinfo_uarch_exynos_m1 = 0x00600100,
464
+ /** Samsung Exynos M2 (Exynos 8895 big cores). */
465
+ cpuinfo_uarch_exynos_m2 = 0x00600101,
466
+ /** Samsung Exynos M3 (Exynos 9810 big cores). */
467
+ cpuinfo_uarch_exynos_m3 = 0x00600102,
468
+ /** Samsung Exynos M4 (Exynos 9820 big cores). */
469
+ cpuinfo_uarch_exynos_m4 = 0x00600103,
470
+ /** Samsung Exynos M5 (Exynos 9830 big cores). */
471
+ cpuinfo_uarch_exynos_m5 = 0x00600104,
472
+
473
+ /* Deprecated synonym for Cortex-A76 */
474
+ cpuinfo_uarch_cortex_a76ae = 0x00300376,
475
+ /* Deprecated names for Exynos. */
476
+ cpuinfo_uarch_mongoose_m1 = 0x00600100,
477
+ cpuinfo_uarch_mongoose_m2 = 0x00600101,
478
+ cpuinfo_uarch_meerkat_m3 = 0x00600102,
479
+ cpuinfo_uarch_meerkat_m4 = 0x00600103,
480
+
481
+ /** Apple A6 and A6X processors. */
482
+ cpuinfo_uarch_swift = 0x00700100,
483
+ /** Apple A7 processor. */
484
+ cpuinfo_uarch_cyclone = 0x00700101,
485
+ /** Apple A8 and A8X processor. */
486
+ cpuinfo_uarch_typhoon = 0x00700102,
487
+ /** Apple A9 and A9X processor. */
488
+ cpuinfo_uarch_twister = 0x00700103,
489
+ /** Apple A10 and A10X processor. */
490
+ cpuinfo_uarch_hurricane = 0x00700104,
491
+ /** Apple A11 processor (big cores). */
492
+ cpuinfo_uarch_monsoon = 0x00700105,
493
+ /** Apple A11 processor (little cores). */
494
+ cpuinfo_uarch_mistral = 0x00700106,
495
+ /** Apple A12 processor (big cores). */
496
+ cpuinfo_uarch_vortex = 0x00700107,
497
+ /** Apple A12 processor (little cores). */
498
+ cpuinfo_uarch_tempest = 0x00700108,
499
+ /** Apple A13 processor (big cores). */
500
+ cpuinfo_uarch_lightning = 0x00700109,
501
+ /** Apple A13 processor (little cores). */
502
+ cpuinfo_uarch_thunder = 0x0070010A,
503
+ /** Apple A14 / M1 processor (big cores). */
504
+ cpuinfo_uarch_firestorm = 0x0070010B,
505
+ /** Apple A14 / M1 processor (little cores). */
506
+ cpuinfo_uarch_icestorm = 0x0070010C,
507
+ /** Apple A15 / M2 processor (big cores). */
508
+ cpuinfo_uarch_avalanche = 0x0070010D,
509
+ /** Apple A15 / M2 processor (little cores). */
510
+ cpuinfo_uarch_blizzard = 0x0070010E,
511
+
512
+ /** Cavium ThunderX. */
513
+ cpuinfo_uarch_thunderx = 0x00800100,
514
+ /** Cavium ThunderX2 (originally Broadcom Vulkan). */
515
+ cpuinfo_uarch_thunderx2 = 0x00800200,
516
+
517
+ /** Marvell PJ4. */
518
+ cpuinfo_uarch_pj4 = 0x00900100,
519
+
520
+ /** Broadcom Brahma B15. */
521
+ cpuinfo_uarch_brahma_b15 = 0x00A00100,
522
+ /** Broadcom Brahma B53. */
523
+ cpuinfo_uarch_brahma_b53 = 0x00A00101,
524
+
525
+ /** Applied Micro X-Gene. */
526
+ cpuinfo_uarch_xgene = 0x00B00100,
527
+
528
+ /* Hygon Dhyana (a modification of AMD Zen for Chinese market). */
529
+ cpuinfo_uarch_dhyana = 0x01000100,
530
+
531
+ /** HiSilicon TaiShan v110 (Huawei Kunpeng 920 series processors). */
532
+ cpuinfo_uarch_taishan_v110 = 0x00C00100,
533
+ };
534
+
535
+ struct cpuinfo_processor {
536
+ /** SMT (hyperthread) ID within a core */
537
+ uint32_t smt_id;
538
+ /** Core containing this logical processor */
539
+ const struct cpuinfo_core* core;
540
+ /** Cluster of cores containing this logical processor */
541
+ const struct cpuinfo_cluster* cluster;
542
+ /** Physical package containing this logical processor */
543
+ const struct cpuinfo_package* package;
544
+ #if defined(__linux__)
545
+ /**
546
+ * Linux-specific ID for the logical processor:
547
+ * - Linux kernel exposes information about this logical processor in /sys/devices/system/cpu/cpu<linux_id>/
548
+ * - Bit <linux_id> in the cpu_set_t identifies this logical processor
549
+ */
550
+ int linux_id;
551
+ #endif
552
+ #if defined(_WIN32) || defined(__CYGWIN__)
553
+ /** Windows-specific ID for the group containing the logical processor. */
554
+ uint16_t windows_group_id;
555
+ /**
556
+ * Windows-specific ID of the logical processor within its group:
557
+ * - Bit <windows_processor_id> in the KAFFINITY mask identifies this logical processor within its group.
558
+ */
559
+ uint16_t windows_processor_id;
560
+ #endif
561
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
562
+ /** APIC ID (unique x86-specific ID of the logical processor) */
563
+ uint32_t apic_id;
564
+ #endif
565
+ struct {
566
+ /** Level 1 instruction cache */
567
+ const struct cpuinfo_cache* l1i;
568
+ /** Level 1 data cache */
569
+ const struct cpuinfo_cache* l1d;
570
+ /** Level 2 unified or data cache */
571
+ const struct cpuinfo_cache* l2;
572
+ /** Level 3 unified or data cache */
573
+ const struct cpuinfo_cache* l3;
574
+ /** Level 4 unified or data cache */
575
+ const struct cpuinfo_cache* l4;
576
+ } cache;
577
+ };
578
+
579
+ struct cpuinfo_core {
580
+ /** Index of the first logical processor on this core. */
581
+ uint32_t processor_start;
582
+ /** Number of logical processors on this core */
583
+ uint32_t processor_count;
584
+ /** Core ID within a package */
585
+ uint32_t core_id;
586
+ /** Cluster containing this core */
587
+ const struct cpuinfo_cluster* cluster;
588
+ /** Physical package containing this core. */
589
+ const struct cpuinfo_package* package;
590
+ /** Vendor of the CPU microarchitecture for this core */
591
+ enum cpuinfo_vendor vendor;
592
+ /** CPU microarchitecture for this core */
593
+ enum cpuinfo_uarch uarch;
594
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
595
+ /** Value of CPUID leaf 1 EAX register for this core */
596
+ uint32_t cpuid;
597
+ #elif CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
598
+ /** Value of Main ID Register (MIDR) for this core */
599
+ uint32_t midr;
600
+ #endif
601
+ /** Clock rate (non-Turbo) of the core, in Hz */
602
+ uint64_t frequency;
603
+ };
604
+
605
+ struct cpuinfo_cluster {
606
+ /** Index of the first logical processor in the cluster */
607
+ uint32_t processor_start;
608
+ /** Number of logical processors in the cluster */
609
+ uint32_t processor_count;
610
+ /** Index of the first core in the cluster */
611
+ uint32_t core_start;
612
+ /** Number of cores on the cluster */
613
+ uint32_t core_count;
614
+ /** Cluster ID within a package */
615
+ uint32_t cluster_id;
616
+ /** Physical package containing the cluster */
617
+ const struct cpuinfo_package* package;
618
+ /** CPU microarchitecture vendor of the cores in the cluster */
619
+ enum cpuinfo_vendor vendor;
620
+ /** CPU microarchitecture of the cores in the cluster */
621
+ enum cpuinfo_uarch uarch;
622
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
623
+ /** Value of CPUID leaf 1 EAX register of the cores in the cluster */
624
+ uint32_t cpuid;
625
+ #elif CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
626
+ /** Value of Main ID Register (MIDR) of the cores in the cluster */
627
+ uint32_t midr;
628
+ #endif
629
+ /** Clock rate (non-Turbo) of the cores in the cluster, in Hz */
630
+ uint64_t frequency;
631
+ };
632
+
633
+ #define CPUINFO_PACKAGE_NAME_MAX 48
634
+
635
+ struct cpuinfo_package {
636
+ /** SoC or processor chip model name */
637
+ char name[CPUINFO_PACKAGE_NAME_MAX];
638
+ /** Index of the first logical processor on this physical package */
639
+ uint32_t processor_start;
640
+ /** Number of logical processors on this physical package */
641
+ uint32_t processor_count;
642
+ /** Index of the first core on this physical package */
643
+ uint32_t core_start;
644
+ /** Number of cores on this physical package */
645
+ uint32_t core_count;
646
+ /** Index of the first cluster of cores on this physical package */
647
+ uint32_t cluster_start;
648
+ /** Number of clusters of cores on this physical package */
649
+ uint32_t cluster_count;
650
+ };
651
+
652
+ struct cpuinfo_uarch_info {
653
+ /** Type of CPU microarchitecture */
654
+ enum cpuinfo_uarch uarch;
655
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
656
+ /** Value of CPUID leaf 1 EAX register for the microarchitecture */
657
+ uint32_t cpuid;
658
+ #elif CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
659
+ /** Value of Main ID Register (MIDR) for the microarchitecture */
660
+ uint32_t midr;
661
+ #endif
662
+ /** Number of logical processors with the microarchitecture */
663
+ uint32_t processor_count;
664
+ /** Number of cores with the microarchitecture */
665
+ uint32_t core_count;
666
+ };
667
+
668
+ #ifdef __cplusplus
669
+ extern "C" {
670
+ #endif
671
+
672
+ bool CPUINFO_ABI cpuinfo_initialize(void);
673
+
674
+ void CPUINFO_ABI cpuinfo_deinitialize(void);
675
+
676
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
677
+ /* This structure is not a part of stable API. Use cpuinfo_has_x86_* functions instead. */
678
+ struct cpuinfo_x86_isa {
679
+ #if CPUINFO_ARCH_X86
680
+ bool rdtsc;
681
+ #endif
682
+ bool rdtscp;
683
+ bool rdpid;
684
+ bool sysenter;
685
+ #if CPUINFO_ARCH_X86
686
+ bool syscall;
687
+ #endif
688
+ bool msr;
689
+ bool clzero;
690
+ bool clflush;
691
+ bool clflushopt;
692
+ bool mwait;
693
+ bool mwaitx;
694
+ #if CPUINFO_ARCH_X86
695
+ bool emmx;
696
+ #endif
697
+ bool fxsave;
698
+ bool xsave;
699
+ #if CPUINFO_ARCH_X86
700
+ bool fpu;
701
+ bool mmx;
702
+ bool mmx_plus;
703
+ #endif
704
+ bool three_d_now;
705
+ bool three_d_now_plus;
706
+ #if CPUINFO_ARCH_X86
707
+ bool three_d_now_geode;
708
+ #endif
709
+ bool prefetch;
710
+ bool prefetchw;
711
+ bool prefetchwt1;
712
+ #if CPUINFO_ARCH_X86
713
+ bool daz;
714
+ bool sse;
715
+ bool sse2;
716
+ #endif
717
+ bool sse3;
718
+ bool ssse3;
719
+ bool sse4_1;
720
+ bool sse4_2;
721
+ bool sse4a;
722
+ bool misaligned_sse;
723
+ bool avx;
724
+ bool fma3;
725
+ bool fma4;
726
+ bool xop;
727
+ bool f16c;
728
+ bool avx2;
729
+ bool avx512f;
730
+ bool avx512pf;
731
+ bool avx512er;
732
+ bool avx512cd;
733
+ bool avx512dq;
734
+ bool avx512bw;
735
+ bool avx512vl;
736
+ bool avx512ifma;
737
+ bool avx512vbmi;
738
+ bool avx512vbmi2;
739
+ bool avx512bitalg;
740
+ bool avx512vpopcntdq;
741
+ bool avx512vnni;
742
+ bool avx512bf16;
743
+ bool avx512fp16;
744
+ bool avx512vp2intersect;
745
+ bool avx512_4vnniw;
746
+ bool avx512_4fmaps;
747
+ bool hle;
748
+ bool rtm;
749
+ bool xtest;
750
+ bool mpx;
751
+ #if CPUINFO_ARCH_X86
752
+ bool cmov;
753
+ bool cmpxchg8b;
754
+ #endif
755
+ bool cmpxchg16b;
756
+ bool clwb;
757
+ bool movbe;
758
+ #if CPUINFO_ARCH_X86_64
759
+ bool lahf_sahf;
760
+ #endif
761
+ bool fs_gs_base;
762
+ bool lzcnt;
763
+ bool popcnt;
764
+ bool tbm;
765
+ bool bmi;
766
+ bool bmi2;
767
+ bool adx;
768
+ bool aes;
769
+ bool vaes;
770
+ bool pclmulqdq;
771
+ bool vpclmulqdq;
772
+ bool gfni;
773
+ bool rdrand;
774
+ bool rdseed;
775
+ bool sha;
776
+ bool rng;
777
+ bool ace;
778
+ bool ace2;
779
+ bool phe;
780
+ bool pmm;
781
+ bool lwp;
782
+ };
783
+
784
+ extern struct cpuinfo_x86_isa cpuinfo_isa;
785
+ #endif
786
+
787
+ static inline bool cpuinfo_has_x86_rdtsc(void) {
788
+ #if CPUINFO_ARCH_X86_64
789
+ return true;
790
+ #elif CPUINFO_ARCH_X86
791
+ #if defined(__ANDROID__)
792
+ return true;
793
+ #else
794
+ return cpuinfo_isa.rdtsc;
795
+ #endif
796
+ #else
797
+ return false;
798
+ #endif
799
+ }
800
+
801
+ static inline bool cpuinfo_has_x86_rdtscp(void) {
802
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
803
+ return cpuinfo_isa.rdtscp;
804
+ #else
805
+ return false;
806
+ #endif
807
+ }
808
+
809
+ static inline bool cpuinfo_has_x86_rdpid(void) {
810
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
811
+ return cpuinfo_isa.rdpid;
812
+ #else
813
+ return false;
814
+ #endif
815
+ }
816
+
817
+ static inline bool cpuinfo_has_x86_clzero(void) {
818
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
819
+ return cpuinfo_isa.clzero;
820
+ #else
821
+ return false;
822
+ #endif
823
+ }
824
+
825
+ static inline bool cpuinfo_has_x86_mwait(void) {
826
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
827
+ return cpuinfo_isa.mwait;
828
+ #else
829
+ return false;
830
+ #endif
831
+ }
832
+
833
+ static inline bool cpuinfo_has_x86_mwaitx(void) {
834
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
835
+ return cpuinfo_isa.mwaitx;
836
+ #else
837
+ return false;
838
+ #endif
839
+ }
840
+
841
+ static inline bool cpuinfo_has_x86_fxsave(void) {
842
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
843
+ return cpuinfo_isa.fxsave;
844
+ #else
845
+ return false;
846
+ #endif
847
+ }
848
+
849
+ static inline bool cpuinfo_has_x86_xsave(void) {
850
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
851
+ return cpuinfo_isa.xsave;
852
+ #else
853
+ return false;
854
+ #endif
855
+ }
856
+
857
+ static inline bool cpuinfo_has_x86_fpu(void) {
858
+ #if CPUINFO_ARCH_X86_64
859
+ return true;
860
+ #elif CPUINFO_ARCH_X86
861
+ #if defined(__ANDROID__)
862
+ return true;
863
+ #else
864
+ return cpuinfo_isa.fpu;
865
+ #endif
866
+ #else
867
+ return false;
868
+ #endif
869
+ }
870
+
871
+ static inline bool cpuinfo_has_x86_mmx(void) {
872
+ #if CPUINFO_ARCH_X86_64
873
+ return true;
874
+ #elif CPUINFO_ARCH_X86
875
+ #if defined(__ANDROID__)
876
+ return true;
877
+ #else
878
+ return cpuinfo_isa.mmx;
879
+ #endif
880
+ #else
881
+ return false;
882
+ #endif
883
+ }
884
+
885
+ static inline bool cpuinfo_has_x86_mmx_plus(void) {
886
+ #if CPUINFO_ARCH_X86_64
887
+ return true;
888
+ #elif CPUINFO_ARCH_X86
889
+ #if defined(__ANDROID__)
890
+ return true;
891
+ #else
892
+ return cpuinfo_isa.mmx_plus;
893
+ #endif
894
+ #else
895
+ return false;
896
+ #endif
897
+ }
898
+
899
+ static inline bool cpuinfo_has_x86_3dnow(void) {
900
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
901
+ return cpuinfo_isa.three_d_now;
902
+ #else
903
+ return false;
904
+ #endif
905
+ }
906
+
907
+ static inline bool cpuinfo_has_x86_3dnow_plus(void) {
908
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
909
+ return cpuinfo_isa.three_d_now_plus;
910
+ #else
911
+ return false;
912
+ #endif
913
+ }
914
+
915
+ static inline bool cpuinfo_has_x86_3dnow_geode(void) {
916
+ #if CPUINFO_ARCH_X86_64
917
+ return false;
918
+ #elif CPUINFO_ARCH_X86
919
+ #if defined(__ANDROID__)
920
+ return false;
921
+ #else
922
+ return cpuinfo_isa.three_d_now_geode;
923
+ #endif
924
+ #else
925
+ return false;
926
+ #endif
927
+ }
928
+
929
+ static inline bool cpuinfo_has_x86_prefetch(void) {
930
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
931
+ return cpuinfo_isa.prefetch;
932
+ #else
933
+ return false;
934
+ #endif
935
+ }
936
+
937
+ static inline bool cpuinfo_has_x86_prefetchw(void) {
938
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
939
+ return cpuinfo_isa.prefetchw;
940
+ #else
941
+ return false;
942
+ #endif
943
+ }
944
+
945
+ static inline bool cpuinfo_has_x86_prefetchwt1(void) {
946
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
947
+ return cpuinfo_isa.prefetchwt1;
948
+ #else
949
+ return false;
950
+ #endif
951
+ }
952
+
953
+ static inline bool cpuinfo_has_x86_daz(void) {
954
+ #if CPUINFO_ARCH_X86_64
955
+ return true;
956
+ #elif CPUINFO_ARCH_X86
957
+ #if defined(__ANDROID__)
958
+ return true;
959
+ #else
960
+ return cpuinfo_isa.daz;
961
+ #endif
962
+ #else
963
+ return false;
964
+ #endif
965
+ }
966
+
967
+ static inline bool cpuinfo_has_x86_sse(void) {
968
+ #if CPUINFO_ARCH_X86_64
969
+ return true;
970
+ #elif CPUINFO_ARCH_X86
971
+ #if defined(__ANDROID__)
972
+ return true;
973
+ #else
974
+ return cpuinfo_isa.sse;
975
+ #endif
976
+ #else
977
+ return false;
978
+ #endif
979
+ }
980
+
981
+ static inline bool cpuinfo_has_x86_sse2(void) {
982
+ #if CPUINFO_ARCH_X86_64
983
+ return true;
984
+ #elif CPUINFO_ARCH_X86
985
+ #if defined(__ANDROID__)
986
+ return true;
987
+ #else
988
+ return cpuinfo_isa.sse2;
989
+ #endif
990
+ #else
991
+ return false;
992
+ #endif
993
+ }
994
+
995
+ static inline bool cpuinfo_has_x86_sse3(void) {
996
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
997
+ #if defined(__ANDROID__)
998
+ return true;
999
+ #else
1000
+ return cpuinfo_isa.sse3;
1001
+ #endif
1002
+ #else
1003
+ return false;
1004
+ #endif
1005
+ }
1006
+
1007
+ static inline bool cpuinfo_has_x86_ssse3(void) {
1008
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1009
+ #if defined(__ANDROID__)
1010
+ return true;
1011
+ #else
1012
+ return cpuinfo_isa.ssse3;
1013
+ #endif
1014
+ #else
1015
+ return false;
1016
+ #endif
1017
+ }
1018
+
1019
+ static inline bool cpuinfo_has_x86_sse4_1(void) {
1020
+ #if CPUINFO_ARCH_X86_64
1021
+ #if defined(__ANDROID__)
1022
+ return true;
1023
+ #else
1024
+ return cpuinfo_isa.sse4_1;
1025
+ #endif
1026
+ #elif CPUINFO_ARCH_X86
1027
+ return cpuinfo_isa.sse4_1;
1028
+ #else
1029
+ return false;
1030
+ #endif
1031
+ }
1032
+
1033
+ static inline bool cpuinfo_has_x86_sse4_2(void) {
1034
+ #if CPUINFO_ARCH_X86_64
1035
+ #if defined(__ANDROID__)
1036
+ return true;
1037
+ #else
1038
+ return cpuinfo_isa.sse4_2;
1039
+ #endif
1040
+ #elif CPUINFO_ARCH_X86
1041
+ return cpuinfo_isa.sse4_2;
1042
+ #else
1043
+ return false;
1044
+ #endif
1045
+ }
1046
+
1047
+ static inline bool cpuinfo_has_x86_sse4a(void) {
1048
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1049
+ return cpuinfo_isa.sse4a;
1050
+ #else
1051
+ return false;
1052
+ #endif
1053
+ }
1054
+
1055
+ static inline bool cpuinfo_has_x86_misaligned_sse(void) {
1056
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1057
+ return cpuinfo_isa.misaligned_sse;
1058
+ #else
1059
+ return false;
1060
+ #endif
1061
+ }
1062
+
1063
+ static inline bool cpuinfo_has_x86_avx(void) {
1064
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1065
+ return cpuinfo_isa.avx;
1066
+ #else
1067
+ return false;
1068
+ #endif
1069
+ }
1070
+
1071
+ static inline bool cpuinfo_has_x86_fma3(void) {
1072
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1073
+ return cpuinfo_isa.fma3;
1074
+ #else
1075
+ return false;
1076
+ #endif
1077
+ }
1078
+
1079
+ static inline bool cpuinfo_has_x86_fma4(void) {
1080
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1081
+ return cpuinfo_isa.fma4;
1082
+ #else
1083
+ return false;
1084
+ #endif
1085
+ }
1086
+
1087
+ static inline bool cpuinfo_has_x86_xop(void) {
1088
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1089
+ return cpuinfo_isa.xop;
1090
+ #else
1091
+ return false;
1092
+ #endif
1093
+ }
1094
+
1095
+ static inline bool cpuinfo_has_x86_f16c(void) {
1096
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1097
+ return cpuinfo_isa.f16c;
1098
+ #else
1099
+ return false;
1100
+ #endif
1101
+ }
1102
+
1103
+ static inline bool cpuinfo_has_x86_avx2(void) {
1104
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1105
+ return cpuinfo_isa.avx2;
1106
+ #else
1107
+ return false;
1108
+ #endif
1109
+ }
1110
+
1111
+ static inline bool cpuinfo_has_x86_avx512f(void) {
1112
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1113
+ return cpuinfo_isa.avx512f;
1114
+ #else
1115
+ return false;
1116
+ #endif
1117
+ }
1118
+
1119
+ static inline bool cpuinfo_has_x86_avx512pf(void) {
1120
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1121
+ return cpuinfo_isa.avx512pf;
1122
+ #else
1123
+ return false;
1124
+ #endif
1125
+ }
1126
+
1127
+ static inline bool cpuinfo_has_x86_avx512er(void) {
1128
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1129
+ return cpuinfo_isa.avx512er;
1130
+ #else
1131
+ return false;
1132
+ #endif
1133
+ }
1134
+
1135
+ static inline bool cpuinfo_has_x86_avx512cd(void) {
1136
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1137
+ return cpuinfo_isa.avx512cd;
1138
+ #else
1139
+ return false;
1140
+ #endif
1141
+ }
1142
+
1143
+ static inline bool cpuinfo_has_x86_avx512dq(void) {
1144
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1145
+ return cpuinfo_isa.avx512dq;
1146
+ #else
1147
+ return false;
1148
+ #endif
1149
+ }
1150
+
1151
+ static inline bool cpuinfo_has_x86_avx512bw(void) {
1152
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1153
+ return cpuinfo_isa.avx512bw;
1154
+ #else
1155
+ return false;
1156
+ #endif
1157
+ }
1158
+
1159
+ static inline bool cpuinfo_has_x86_avx512vl(void) {
1160
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1161
+ return cpuinfo_isa.avx512vl;
1162
+ #else
1163
+ return false;
1164
+ #endif
1165
+ }
1166
+
1167
+ static inline bool cpuinfo_has_x86_avx512ifma(void) {
1168
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1169
+ return cpuinfo_isa.avx512ifma;
1170
+ #else
1171
+ return false;
1172
+ #endif
1173
+ }
1174
+
1175
+ static inline bool cpuinfo_has_x86_avx512vbmi(void) {
1176
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1177
+ return cpuinfo_isa.avx512vbmi;
1178
+ #else
1179
+ return false;
1180
+ #endif
1181
+ }
1182
+
1183
+ static inline bool cpuinfo_has_x86_avx512vbmi2(void) {
1184
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1185
+ return cpuinfo_isa.avx512vbmi2;
1186
+ #else
1187
+ return false;
1188
+ #endif
1189
+ }
1190
+
1191
+ static inline bool cpuinfo_has_x86_avx512bitalg(void) {
1192
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1193
+ return cpuinfo_isa.avx512bitalg;
1194
+ #else
1195
+ return false;
1196
+ #endif
1197
+ }
1198
+
1199
+ static inline bool cpuinfo_has_x86_avx512vpopcntdq(void) {
1200
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1201
+ return cpuinfo_isa.avx512vpopcntdq;
1202
+ #else
1203
+ return false;
1204
+ #endif
1205
+ }
1206
+
1207
+ static inline bool cpuinfo_has_x86_avx512vnni(void) {
1208
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1209
+ return cpuinfo_isa.avx512vnni;
1210
+ #else
1211
+ return false;
1212
+ #endif
1213
+ }
1214
+
1215
+ static inline bool cpuinfo_has_x86_avx512bf16(void) {
1216
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1217
+ return cpuinfo_isa.avx512bf16;
1218
+ #else
1219
+ return false;
1220
+ #endif
1221
+ }
1222
+
1223
+ static inline bool cpuinfo_has_x86_avx512fp16(void) {
1224
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1225
+ return cpuinfo_isa.avx512fp16;
1226
+ #else
1227
+ return false;
1228
+ #endif
1229
+ }
1230
+
1231
+ static inline bool cpuinfo_has_x86_avx512vp2intersect(void) {
1232
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1233
+ return cpuinfo_isa.avx512vp2intersect;
1234
+ #else
1235
+ return false;
1236
+ #endif
1237
+ }
1238
+
1239
+ static inline bool cpuinfo_has_x86_avx512_4vnniw(void) {
1240
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1241
+ return cpuinfo_isa.avx512_4vnniw;
1242
+ #else
1243
+ return false;
1244
+ #endif
1245
+ }
1246
+
1247
+ static inline bool cpuinfo_has_x86_avx512_4fmaps(void) {
1248
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1249
+ return cpuinfo_isa.avx512_4fmaps;
1250
+ #else
1251
+ return false;
1252
+ #endif
1253
+ }
1254
+
1255
+ static inline bool cpuinfo_has_x86_hle(void) {
1256
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1257
+ return cpuinfo_isa.hle;
1258
+ #else
1259
+ return false;
1260
+ #endif
1261
+ }
1262
+
1263
+ static inline bool cpuinfo_has_x86_rtm(void) {
1264
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1265
+ return cpuinfo_isa.rtm;
1266
+ #else
1267
+ return false;
1268
+ #endif
1269
+ }
1270
+
1271
+ static inline bool cpuinfo_has_x86_xtest(void) {
1272
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1273
+ return cpuinfo_isa.xtest;
1274
+ #else
1275
+ return false;
1276
+ #endif
1277
+ }
1278
+
1279
+ static inline bool cpuinfo_has_x86_mpx(void) {
1280
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1281
+ return cpuinfo_isa.mpx;
1282
+ #else
1283
+ return false;
1284
+ #endif
1285
+ }
1286
+
1287
+ static inline bool cpuinfo_has_x86_cmov(void) {
1288
+ #if CPUINFO_ARCH_X86_64
1289
+ return true;
1290
+ #elif CPUINFO_ARCH_X86
1291
+ return cpuinfo_isa.cmov;
1292
+ #else
1293
+ return false;
1294
+ #endif
1295
+ }
1296
+
1297
+ static inline bool cpuinfo_has_x86_cmpxchg8b(void) {
1298
+ #if CPUINFO_ARCH_X86_64
1299
+ return true;
1300
+ #elif CPUINFO_ARCH_X86
1301
+ return cpuinfo_isa.cmpxchg8b;
1302
+ #else
1303
+ return false;
1304
+ #endif
1305
+ }
1306
+
1307
+ static inline bool cpuinfo_has_x86_cmpxchg16b(void) {
1308
+ #if CPUINFO_ARCH_X86_64
1309
+ return cpuinfo_isa.cmpxchg16b;
1310
+ #else
1311
+ return false;
1312
+ #endif
1313
+ }
1314
+
1315
+ static inline bool cpuinfo_has_x86_clwb(void) {
1316
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1317
+ return cpuinfo_isa.clwb;
1318
+ #else
1319
+ return false;
1320
+ #endif
1321
+ }
1322
+
1323
+ static inline bool cpuinfo_has_x86_movbe(void) {
1324
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1325
+ return cpuinfo_isa.movbe;
1326
+ #else
1327
+ return false;
1328
+ #endif
1329
+ }
1330
+
1331
+ static inline bool cpuinfo_has_x86_lahf_sahf(void) {
1332
+ #if CPUINFO_ARCH_X86
1333
+ return true;
1334
+ #elif CPUINFO_ARCH_X86_64
1335
+ return cpuinfo_isa.lahf_sahf;
1336
+ #else
1337
+ return false;
1338
+ #endif
1339
+ }
1340
+
1341
+ static inline bool cpuinfo_has_x86_lzcnt(void) {
1342
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1343
+ return cpuinfo_isa.lzcnt;
1344
+ #else
1345
+ return false;
1346
+ #endif
1347
+ }
1348
+
1349
+ static inline bool cpuinfo_has_x86_popcnt(void) {
1350
+ #if CPUINFO_ARCH_X86_64
1351
+ #if defined(__ANDROID__)
1352
+ return true;
1353
+ #else
1354
+ return cpuinfo_isa.popcnt;
1355
+ #endif
1356
+ #elif CPUINFO_ARCH_X86
1357
+ return cpuinfo_isa.popcnt;
1358
+ #else
1359
+ return false;
1360
+ #endif
1361
+ }
1362
+
1363
+ static inline bool cpuinfo_has_x86_tbm(void) {
1364
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1365
+ return cpuinfo_isa.tbm;
1366
+ #else
1367
+ return false;
1368
+ #endif
1369
+ }
1370
+
1371
+ static inline bool cpuinfo_has_x86_bmi(void) {
1372
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1373
+ return cpuinfo_isa.bmi;
1374
+ #else
1375
+ return false;
1376
+ #endif
1377
+ }
1378
+
1379
+ static inline bool cpuinfo_has_x86_bmi2(void) {
1380
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1381
+ return cpuinfo_isa.bmi2;
1382
+ #else
1383
+ return false;
1384
+ #endif
1385
+ }
1386
+
1387
+ static inline bool cpuinfo_has_x86_adx(void) {
1388
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1389
+ return cpuinfo_isa.adx;
1390
+ #else
1391
+ return false;
1392
+ #endif
1393
+ }
1394
+
1395
+ static inline bool cpuinfo_has_x86_aes(void) {
1396
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1397
+ return cpuinfo_isa.aes;
1398
+ #else
1399
+ return false;
1400
+ #endif
1401
+ }
1402
+
1403
+ static inline bool cpuinfo_has_x86_vaes(void) {
1404
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1405
+ return cpuinfo_isa.vaes;
1406
+ #else
1407
+ return false;
1408
+ #endif
1409
+ }
1410
+
1411
+ static inline bool cpuinfo_has_x86_pclmulqdq(void) {
1412
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1413
+ return cpuinfo_isa.pclmulqdq;
1414
+ #else
1415
+ return false;
1416
+ #endif
1417
+ }
1418
+
1419
+ static inline bool cpuinfo_has_x86_vpclmulqdq(void) {
1420
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1421
+ return cpuinfo_isa.vpclmulqdq;
1422
+ #else
1423
+ return false;
1424
+ #endif
1425
+ }
1426
+
1427
+ static inline bool cpuinfo_has_x86_gfni(void) {
1428
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1429
+ return cpuinfo_isa.gfni;
1430
+ #else
1431
+ return false;
1432
+ #endif
1433
+ }
1434
+
1435
+ static inline bool cpuinfo_has_x86_rdrand(void) {
1436
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1437
+ return cpuinfo_isa.rdrand;
1438
+ #else
1439
+ return false;
1440
+ #endif
1441
+ }
1442
+
1443
+ static inline bool cpuinfo_has_x86_rdseed(void) {
1444
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1445
+ return cpuinfo_isa.rdseed;
1446
+ #else
1447
+ return false;
1448
+ #endif
1449
+ }
1450
+
1451
+ static inline bool cpuinfo_has_x86_sha(void) {
1452
+ #if CPUINFO_ARCH_X86 || CPUINFO_ARCH_X86_64
1453
+ return cpuinfo_isa.sha;
1454
+ #else
1455
+ return false;
1456
+ #endif
1457
+ }
1458
+
1459
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1460
+ /* This structure is not a part of stable API. Use cpuinfo_has_arm_* functions instead. */
1461
+ struct cpuinfo_arm_isa {
1462
+ #if CPUINFO_ARCH_ARM
1463
+ bool thumb;
1464
+ bool thumb2;
1465
+ bool thumbee;
1466
+ bool jazelle;
1467
+ bool armv5e;
1468
+ bool armv6;
1469
+ bool armv6k;
1470
+ bool armv7;
1471
+ bool armv7mp;
1472
+ bool armv8;
1473
+ bool idiv;
1474
+
1475
+ bool vfpv2;
1476
+ bool vfpv3;
1477
+ bool d32;
1478
+ bool fp16;
1479
+ bool fma;
1480
+
1481
+ bool wmmx;
1482
+ bool wmmx2;
1483
+ bool neon;
1484
+ #endif
1485
+ #if CPUINFO_ARCH_ARM64
1486
+ bool atomics;
1487
+ bool bf16;
1488
+ bool sve;
1489
+ bool sve2;
1490
+ bool i8mm;
1491
+ #endif
1492
+ bool rdm;
1493
+ bool fp16arith;
1494
+ bool dot;
1495
+ bool jscvt;
1496
+ bool fcma;
1497
+ bool fhm;
1498
+
1499
+ bool aes;
1500
+ bool sha1;
1501
+ bool sha2;
1502
+ bool pmull;
1503
+ bool crc32;
1504
+ };
1505
+
1506
+ extern struct cpuinfo_arm_isa cpuinfo_isa;
1507
+ #endif
1508
+
1509
+ static inline bool cpuinfo_has_arm_thumb(void) {
1510
+ #if CPUINFO_ARCH_ARM
1511
+ return cpuinfo_isa.thumb;
1512
+ #else
1513
+ return false;
1514
+ #endif
1515
+ }
1516
+
1517
+ static inline bool cpuinfo_has_arm_thumb2(void) {
1518
+ #if CPUINFO_ARCH_ARM
1519
+ return cpuinfo_isa.thumb2;
1520
+ #else
1521
+ return false;
1522
+ #endif
1523
+ }
1524
+
1525
+ static inline bool cpuinfo_has_arm_v5e(void) {
1526
+ #if CPUINFO_ARCH_ARM
1527
+ return cpuinfo_isa.armv5e;
1528
+ #else
1529
+ return false;
1530
+ #endif
1531
+ }
1532
+
1533
+ static inline bool cpuinfo_has_arm_v6(void) {
1534
+ #if CPUINFO_ARCH_ARM
1535
+ return cpuinfo_isa.armv6;
1536
+ #else
1537
+ return false;
1538
+ #endif
1539
+ }
1540
+
1541
+ static inline bool cpuinfo_has_arm_v6k(void) {
1542
+ #if CPUINFO_ARCH_ARM
1543
+ return cpuinfo_isa.armv6k;
1544
+ #else
1545
+ return false;
1546
+ #endif
1547
+ }
1548
+
1549
+ static inline bool cpuinfo_has_arm_v7(void) {
1550
+ #if CPUINFO_ARCH_ARM
1551
+ return cpuinfo_isa.armv7;
1552
+ #else
1553
+ return false;
1554
+ #endif
1555
+ }
1556
+
1557
+ static inline bool cpuinfo_has_arm_v7mp(void) {
1558
+ #if CPUINFO_ARCH_ARM
1559
+ return cpuinfo_isa.armv7mp;
1560
+ #else
1561
+ return false;
1562
+ #endif
1563
+ }
1564
+
1565
+ static inline bool cpuinfo_has_arm_v8(void) {
1566
+ #if CPUINFO_ARCH_ARM64
1567
+ return true;
1568
+ #elif CPUINFO_ARCH_ARM
1569
+ return cpuinfo_isa.armv8;
1570
+ #else
1571
+ return false;
1572
+ #endif
1573
+ }
1574
+
1575
+ static inline bool cpuinfo_has_arm_idiv(void) {
1576
+ #if CPUINFO_ARCH_ARM64
1577
+ return true;
1578
+ #elif CPUINFO_ARCH_ARM
1579
+ return cpuinfo_isa.idiv;
1580
+ #else
1581
+ return false;
1582
+ #endif
1583
+ }
1584
+
1585
+ static inline bool cpuinfo_has_arm_vfpv2(void) {
1586
+ #if CPUINFO_ARCH_ARM
1587
+ return cpuinfo_isa.vfpv2;
1588
+ #else
1589
+ return false;
1590
+ #endif
1591
+ }
1592
+
1593
+ static inline bool cpuinfo_has_arm_vfpv3(void) {
1594
+ #if CPUINFO_ARCH_ARM64
1595
+ return true;
1596
+ #elif CPUINFO_ARCH_ARM
1597
+ return cpuinfo_isa.vfpv3;
1598
+ #else
1599
+ return false;
1600
+ #endif
1601
+ }
1602
+
1603
+ static inline bool cpuinfo_has_arm_vfpv3_d32(void) {
1604
+ #if CPUINFO_ARCH_ARM64
1605
+ return true;
1606
+ #elif CPUINFO_ARCH_ARM
1607
+ return cpuinfo_isa.vfpv3 && cpuinfo_isa.d32;
1608
+ #else
1609
+ return false;
1610
+ #endif
1611
+ }
1612
+
1613
+ static inline bool cpuinfo_has_arm_vfpv3_fp16(void) {
1614
+ #if CPUINFO_ARCH_ARM64
1615
+ return true;
1616
+ #elif CPUINFO_ARCH_ARM
1617
+ return cpuinfo_isa.vfpv3 && cpuinfo_isa.fp16;
1618
+ #else
1619
+ return false;
1620
+ #endif
1621
+ }
1622
+
1623
+ static inline bool cpuinfo_has_arm_vfpv3_fp16_d32(void) {
1624
+ #if CPUINFO_ARCH_ARM64
1625
+ return true;
1626
+ #elif CPUINFO_ARCH_ARM
1627
+ return cpuinfo_isa.vfpv3 && cpuinfo_isa.fp16 && cpuinfo_isa.d32;
1628
+ #else
1629
+ return false;
1630
+ #endif
1631
+ }
1632
+
1633
+ static inline bool cpuinfo_has_arm_vfpv4(void) {
1634
+ #if CPUINFO_ARCH_ARM64
1635
+ return true;
1636
+ #elif CPUINFO_ARCH_ARM
1637
+ return cpuinfo_isa.vfpv3 && cpuinfo_isa.fma;
1638
+ #else
1639
+ return false;
1640
+ #endif
1641
+ }
1642
+
1643
+ static inline bool cpuinfo_has_arm_vfpv4_d32(void) {
1644
+ #if CPUINFO_ARCH_ARM64
1645
+ return true;
1646
+ #elif CPUINFO_ARCH_ARM
1647
+ return cpuinfo_isa.vfpv3 && cpuinfo_isa.fma && cpuinfo_isa.d32;
1648
+ #else
1649
+ return false;
1650
+ #endif
1651
+ }
1652
+
1653
+ static inline bool cpuinfo_has_arm_fp16_arith(void) {
1654
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1655
+ return cpuinfo_isa.fp16arith;
1656
+ #else
1657
+ return false;
1658
+ #endif
1659
+ }
1660
+
1661
+ static inline bool cpuinfo_has_arm_bf16(void) {
1662
+ #if CPUINFO_ARCH_ARM64
1663
+ return cpuinfo_isa.bf16;
1664
+ #else
1665
+ return false;
1666
+ #endif
1667
+ }
1668
+
1669
+ static inline bool cpuinfo_has_arm_wmmx(void) {
1670
+ #if CPUINFO_ARCH_ARM
1671
+ return cpuinfo_isa.wmmx;
1672
+ #else
1673
+ return false;
1674
+ #endif
1675
+ }
1676
+
1677
+ static inline bool cpuinfo_has_arm_wmmx2(void) {
1678
+ #if CPUINFO_ARCH_ARM
1679
+ return cpuinfo_isa.wmmx2;
1680
+ #else
1681
+ return false;
1682
+ #endif
1683
+ }
1684
+
1685
+ static inline bool cpuinfo_has_arm_neon(void) {
1686
+ #if CPUINFO_ARCH_ARM64
1687
+ return true;
1688
+ #elif CPUINFO_ARCH_ARM
1689
+ return cpuinfo_isa.neon;
1690
+ #else
1691
+ return false;
1692
+ #endif
1693
+ }
1694
+
1695
+ static inline bool cpuinfo_has_arm_neon_fp16(void) {
1696
+ #if CPUINFO_ARCH_ARM64
1697
+ return true;
1698
+ #elif CPUINFO_ARCH_ARM
1699
+ return cpuinfo_isa.neon && cpuinfo_isa.fp16;
1700
+ #else
1701
+ return false;
1702
+ #endif
1703
+ }
1704
+
1705
+ static inline bool cpuinfo_has_arm_neon_fma(void) {
1706
+ #if CPUINFO_ARCH_ARM64
1707
+ return true;
1708
+ #elif CPUINFO_ARCH_ARM
1709
+ return cpuinfo_isa.neon && cpuinfo_isa.fma;
1710
+ #else
1711
+ return false;
1712
+ #endif
1713
+ }
1714
+
1715
+ static inline bool cpuinfo_has_arm_neon_v8(void) {
1716
+ #if CPUINFO_ARCH_ARM64
1717
+ return true;
1718
+ #elif CPUINFO_ARCH_ARM
1719
+ return cpuinfo_isa.neon && cpuinfo_isa.armv8;
1720
+ #else
1721
+ return false;
1722
+ #endif
1723
+ }
1724
+
1725
+ static inline bool cpuinfo_has_arm_atomics(void) {
1726
+ #if CPUINFO_ARCH_ARM64
1727
+ return cpuinfo_isa.atomics;
1728
+ #else
1729
+ return false;
1730
+ #endif
1731
+ }
1732
+
1733
+ static inline bool cpuinfo_has_arm_neon_rdm(void) {
1734
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1735
+ return cpuinfo_isa.rdm;
1736
+ #else
1737
+ return false;
1738
+ #endif
1739
+ }
1740
+
1741
+ static inline bool cpuinfo_has_arm_neon_fp16_arith(void) {
1742
+ #if CPUINFO_ARCH_ARM
1743
+ return cpuinfo_isa.neon && cpuinfo_isa.fp16arith;
1744
+ #elif CPUINFO_ARCH_ARM64
1745
+ return cpuinfo_isa.fp16arith;
1746
+ #else
1747
+ return false;
1748
+ #endif
1749
+ }
1750
+
1751
+ static inline bool cpuinfo_has_arm_fhm(void) {
1752
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1753
+ return cpuinfo_isa.fhm;
1754
+ #else
1755
+ return false;
1756
+ #endif
1757
+ }
1758
+
1759
+ static inline bool cpuinfo_has_arm_neon_dot(void) {
1760
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1761
+ return cpuinfo_isa.dot;
1762
+ #else
1763
+ return false;
1764
+ #endif
1765
+ }
1766
+
1767
+ static inline bool cpuinfo_has_arm_neon_bf16(void) {
1768
+ #if CPUINFO_ARCH_ARM64
1769
+ return cpuinfo_isa.bf16;
1770
+ #else
1771
+ return false;
1772
+ #endif
1773
+ }
1774
+
1775
+ static inline bool cpuinfo_has_arm_jscvt(void) {
1776
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1777
+ return cpuinfo_isa.jscvt;
1778
+ #else
1779
+ return false;
1780
+ #endif
1781
+ }
1782
+
1783
+ static inline bool cpuinfo_has_arm_fcma(void) {
1784
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1785
+ return cpuinfo_isa.fcma;
1786
+ #else
1787
+ return false;
1788
+ #endif
1789
+ }
1790
+
1791
+ static inline bool cpuinfo_has_arm_i8mm(void) {
1792
+ #if CPUINFO_ARCH_ARM64
1793
+ return cpuinfo_isa.i8mm;
1794
+ #else
1795
+ return false;
1796
+ #endif
1797
+ }
1798
+
1799
+ static inline bool cpuinfo_has_arm_aes(void) {
1800
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1801
+ return cpuinfo_isa.aes;
1802
+ #else
1803
+ return false;
1804
+ #endif
1805
+ }
1806
+
1807
+ static inline bool cpuinfo_has_arm_sha1(void) {
1808
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1809
+ return cpuinfo_isa.sha1;
1810
+ #else
1811
+ return false;
1812
+ #endif
1813
+ }
1814
+
1815
+ static inline bool cpuinfo_has_arm_sha2(void) {
1816
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1817
+ return cpuinfo_isa.sha2;
1818
+ #else
1819
+ return false;
1820
+ #endif
1821
+ }
1822
+
1823
+ static inline bool cpuinfo_has_arm_pmull(void) {
1824
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1825
+ return cpuinfo_isa.pmull;
1826
+ #else
1827
+ return false;
1828
+ #endif
1829
+ }
1830
+
1831
+ static inline bool cpuinfo_has_arm_crc32(void) {
1832
+ #if CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64
1833
+ return cpuinfo_isa.crc32;
1834
+ #else
1835
+ return false;
1836
+ #endif
1837
+ }
1838
+
1839
+ static inline bool cpuinfo_has_arm_sve(void) {
1840
+ #if CPUINFO_ARCH_ARM64
1841
+ return cpuinfo_isa.sve;
1842
+ #else
1843
+ return false;
1844
+ #endif
1845
+ }
1846
+
1847
+ static inline bool cpuinfo_has_arm_sve_bf16(void) {
1848
+ #if CPUINFO_ARCH_ARM64
1849
+ return cpuinfo_isa.sve && cpuinfo_isa.bf16;
1850
+ #else
1851
+ return false;
1852
+ #endif
1853
+ }
1854
+
1855
+ static inline bool cpuinfo_has_arm_sve2(void) {
1856
+ #if CPUINFO_ARCH_ARM64
1857
+ return cpuinfo_isa.sve2;
1858
+ #else
1859
+ return false;
1860
+ #endif
1861
+ }
1862
+
1863
+ const struct cpuinfo_processor* CPUINFO_ABI cpuinfo_get_processors(void);
1864
+ const struct cpuinfo_core* CPUINFO_ABI cpuinfo_get_cores(void);
1865
+ const struct cpuinfo_cluster* CPUINFO_ABI cpuinfo_get_clusters(void);
1866
+ const struct cpuinfo_package* CPUINFO_ABI cpuinfo_get_packages(void);
1867
+ const struct cpuinfo_uarch_info* CPUINFO_ABI cpuinfo_get_uarchs(void);
1868
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1i_caches(void);
1869
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1d_caches(void);
1870
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l2_caches(void);
1871
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l3_caches(void);
1872
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l4_caches(void);
1873
+
1874
+ const struct cpuinfo_processor* CPUINFO_ABI cpuinfo_get_processor(uint32_t index);
1875
+ const struct cpuinfo_core* CPUINFO_ABI cpuinfo_get_core(uint32_t index);
1876
+ const struct cpuinfo_cluster* CPUINFO_ABI cpuinfo_get_cluster(uint32_t index);
1877
+ const struct cpuinfo_package* CPUINFO_ABI cpuinfo_get_package(uint32_t index);
1878
+ const struct cpuinfo_uarch_info* CPUINFO_ABI cpuinfo_get_uarch(uint32_t index);
1879
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1i_cache(uint32_t index);
1880
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l1d_cache(uint32_t index);
1881
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l2_cache(uint32_t index);
1882
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l3_cache(uint32_t index);
1883
+ const struct cpuinfo_cache* CPUINFO_ABI cpuinfo_get_l4_cache(uint32_t index);
1884
+
1885
+ uint32_t CPUINFO_ABI cpuinfo_get_processors_count(void);
1886
+ uint32_t CPUINFO_ABI cpuinfo_get_cores_count(void);
1887
+ uint32_t CPUINFO_ABI cpuinfo_get_clusters_count(void);
1888
+ uint32_t CPUINFO_ABI cpuinfo_get_packages_count(void);
1889
+ uint32_t CPUINFO_ABI cpuinfo_get_uarchs_count(void);
1890
+ uint32_t CPUINFO_ABI cpuinfo_get_l1i_caches_count(void);
1891
+ uint32_t CPUINFO_ABI cpuinfo_get_l1d_caches_count(void);
1892
+ uint32_t CPUINFO_ABI cpuinfo_get_l2_caches_count(void);
1893
+ uint32_t CPUINFO_ABI cpuinfo_get_l3_caches_count(void);
1894
+ uint32_t CPUINFO_ABI cpuinfo_get_l4_caches_count(void);
1895
+
1896
+ /**
1897
+ * Returns upper bound on cache size.
1898
+ */
1899
+ uint32_t CPUINFO_ABI cpuinfo_get_max_cache_size(void);
1900
+
1901
+ /**
1902
+ * Identify the logical processor that executes the current thread.
1903
+ *
1904
+ * There is no guarantee that the thread will stay on the same logical processor for any time.
1905
+ * Callers should treat the result as only a hint, and be prepared to handle NULL return value.
1906
+ */
1907
+ const struct cpuinfo_processor* CPUINFO_ABI cpuinfo_get_current_processor(void);
1908
+
1909
+ /**
1910
+ * Identify the core that executes the current thread.
1911
+ *
1912
+ * There is no guarantee that the thread will stay on the same core for any time.
1913
+ * Callers should treat the result as only a hint, and be prepared to handle NULL return value.
1914
+ */
1915
+ const struct cpuinfo_core* CPUINFO_ABI cpuinfo_get_current_core(void);
1916
+
1917
+ /**
1918
+ * Identify the microarchitecture index of the core that executes the current thread.
1919
+ * If the system does not support such identification, the function returns 0.
1920
+ *
1921
+ * There is no guarantee that the thread will stay on the same type of core for any time.
1922
+ * Callers should treat the result as only a hint.
1923
+ */
1924
+ uint32_t CPUINFO_ABI cpuinfo_get_current_uarch_index(void);
1925
+
1926
+ /**
1927
+ * Identify the microarchitecture index of the core that executes the current thread.
1928
+ * If the system does not support such identification, the function returns the user-specified default value.
1929
+ *
1930
+ * There is no guarantee that the thread will stay on the same type of core for any time.
1931
+ * Callers should treat the result as only a hint.
1932
+ */
1933
+ uint32_t CPUINFO_ABI cpuinfo_get_current_uarch_index_with_default(uint32_t default_uarch_index);
1934
+
1935
+ #ifdef __cplusplus
1936
+ } /* extern "C" */
1937
+ #endif
1938
+
1939
+ #endif /* CPUINFO_H */
videollama2/lib/python3.10/site-packages/torch/include/dnnl.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * Copyright 2020 Intel Corporation
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *******************************************************************************/
16
+
17
+ #ifndef DNNL_H
18
+ #define DNNL_H
19
+
20
+ #include "oneapi/dnnl/dnnl.h"
21
+
22
+ #endif /* DNNL_H */
videollama2/lib/python3.10/site-packages/torch/include/dnnl_config.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * Copyright 2020 Intel Corporation
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *******************************************************************************/
16
+
17
+ #ifndef DNNL_CONFIG_H
18
+ #define DNNL_CONFIG_H
19
+
20
+ #include "oneapi/dnnl/dnnl_config.h"
21
+
22
+ #endif /* DNNL_CONFIG_H */
videollama2/lib/python3.10/site-packages/torch/include/dnnl_debug.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * Copyright 2020 Intel Corporation
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *******************************************************************************/
16
+
17
+ #ifndef DNNL_DEBUG_H
18
+ #define DNNL_DEBUG_H
19
+
20
+ #include "oneapi/dnnl/dnnl_debug.h"
21
+
22
+ #endif /* DNNL_DEBUG_H */
videollama2/lib/python3.10/site-packages/torch/include/dnnl_ocl.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * Copyright 2020 Intel Corporation
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *******************************************************************************/
16
+
17
+ #ifndef DNNL_OCL_H
18
+ #define DNNL_OCL_H
19
+
20
+ #include "oneapi/dnnl/dnnl_ocl.h"
21
+
22
+ #endif /* DNNL_OCL_H */
videollama2/lib/python3.10/site-packages/torch/include/dnnl_sycl.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * Copyright 2020 Intel Corporation
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *******************************************************************************/
16
+
17
+ #ifndef DNNL_SYCL_H
18
+ #define DNNL_SYCL_H
19
+
20
+ #include "oneapi/dnnl/dnnl_sycl.h"
21
+
22
+ #endif /* DNNL_SYCL_H */
videollama2/lib/python3.10/site-packages/torch/include/dnnl_sycl_types.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * Copyright 2020 Intel Corporation
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *******************************************************************************/
16
+
17
+ #ifndef DNNL_SYCL_TYPES_H
18
+ #define DNNL_SYCL_TYPES_H
19
+
20
+ #include "oneapi/dnnl/dnnl_sycl_types.h"
21
+
22
+ #endif /* DNNL_SYCL_TYPES_H */
videollama2/lib/python3.10/site-packages/torch/include/fxdiv.h ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #ifndef FXDIV_H
3
+ #define FXDIV_H
4
+
5
+ #if defined(__cplusplus) && (__cplusplus >= 201103L)
6
+ #include <cstddef>
7
+ #include <cstdint>
8
+ #include <climits>
9
+ #elif !defined(__OPENCL_VERSION__)
10
+ #include <stddef.h>
11
+ #include <stdint.h>
12
+ #include <limits.h>
13
+ #endif
14
+
15
+ #if defined(_MSC_VER)
16
+ #include <intrin.h>
17
+ #if defined(_M_IX86) || defined(_M_X64)
18
+ #include <immintrin.h>
19
+ #endif
20
+ #endif
21
+
22
+ #ifndef FXDIV_USE_INLINE_ASSEMBLY
23
+ #define FXDIV_USE_INLINE_ASSEMBLY 0
24
+ #endif
25
+
26
+ static inline uint64_t fxdiv_mulext_uint32_t(uint32_t a, uint32_t b) {
27
+ #if defined(_MSC_VER) && defined(_M_IX86)
28
+ return (uint64_t) __emulu((unsigned int) a, (unsigned int) b);
29
+ #else
30
+ return (uint64_t) a * (uint64_t) b;
31
+ #endif
32
+ }
33
+
34
+ static inline uint32_t fxdiv_mulhi_uint32_t(uint32_t a, uint32_t b) {
35
+ #if defined(__OPENCL_VERSION__)
36
+ return mul_hi(a, b);
37
+ #elif defined(__CUDA_ARCH__)
38
+ return (uint32_t) __umulhi((unsigned int) a, (unsigned int) b);
39
+ #elif defined(_MSC_VER) && defined(_M_IX86)
40
+ return (uint32_t) (__emulu((unsigned int) a, (unsigned int) b) >> 32);
41
+ #elif defined(_MSC_VER) && defined(_M_ARM)
42
+ return (uint32_t) _MulUnsignedHigh((unsigned long) a, (unsigned long) b);
43
+ #else
44
+ return (uint32_t) (((uint64_t) a * (uint64_t) b) >> 32);
45
+ #endif
46
+ }
47
+
48
+ static inline uint64_t fxdiv_mulhi_uint64_t(uint64_t a, uint64_t b) {
49
+ #if defined(__OPENCL_VERSION__)
50
+ return mul_hi(a, b);
51
+ #elif defined(__CUDA_ARCH__)
52
+ return (uint64_t) __umul64hi((unsigned long long) a, (unsigned long long) b);
53
+ #elif defined(_MSC_VER) && defined(_M_X64)
54
+ return (uint64_t) __umulh((unsigned __int64) a, (unsigned __int64) b);
55
+ #elif defined(__GNUC__) && defined(__SIZEOF_INT128__)
56
+ return (uint64_t) (((((unsigned __int128) a) * ((unsigned __int128) b))) >> 64);
57
+ #else
58
+ const uint32_t a_lo = (uint32_t) a;
59
+ const uint32_t a_hi = (uint32_t) (a >> 32);
60
+ const uint32_t b_lo = (uint32_t) b;
61
+ const uint32_t b_hi = (uint32_t) (b >> 32);
62
+
63
+ const uint64_t t = fxdiv_mulext_uint32_t(a_hi, b_lo) +
64
+ (uint64_t) fxdiv_mulhi_uint32_t(a_lo, b_lo);
65
+ return fxdiv_mulext_uint32_t(a_hi, b_hi) + (t >> 32) +
66
+ ((fxdiv_mulext_uint32_t(a_lo, b_hi) + (uint64_t) (uint32_t) t) >> 32);
67
+ #endif
68
+ }
69
+
70
+ static inline size_t fxdiv_mulhi_size_t(size_t a, size_t b) {
71
+ #if SIZE_MAX == UINT32_MAX
72
+ return (size_t) fxdiv_mulhi_uint32_t((uint32_t) a, (uint32_t) b);
73
+ #elif SIZE_MAX == UINT64_MAX
74
+ return (size_t) fxdiv_mulhi_uint64_t((uint64_t) a, (uint64_t) b);
75
+ #else
76
+ #error Unsupported platform
77
+ #endif
78
+ }
79
+
80
+ struct fxdiv_divisor_uint32_t {
81
+ uint32_t value;
82
+ uint32_t m;
83
+ uint8_t s1;
84
+ uint8_t s2;
85
+ };
86
+
87
+ struct fxdiv_result_uint32_t {
88
+ uint32_t quotient;
89
+ uint32_t remainder;
90
+ };
91
+
92
+ struct fxdiv_divisor_uint64_t {
93
+ uint64_t value;
94
+ uint64_t m;
95
+ uint8_t s1;
96
+ uint8_t s2;
97
+ };
98
+
99
+ struct fxdiv_result_uint64_t {
100
+ uint64_t quotient;
101
+ uint64_t remainder;
102
+ };
103
+
104
+ struct fxdiv_divisor_size_t {
105
+ size_t value;
106
+ size_t m;
107
+ uint8_t s1;
108
+ uint8_t s2;
109
+ };
110
+
111
+ struct fxdiv_result_size_t {
112
+ size_t quotient;
113
+ size_t remainder;
114
+ };
115
+
116
+ static inline struct fxdiv_divisor_uint32_t fxdiv_init_uint32_t(uint32_t d) {
117
+ struct fxdiv_divisor_uint32_t result = { d };
118
+ if (d == 1) {
119
+ result.m = UINT32_C(1);
120
+ result.s1 = 0;
121
+ result.s2 = 0;
122
+ } else {
123
+ #if defined(__OPENCL_VERSION__)
124
+ const uint32_t l_minus_1 = 31 - clz(d - 1);
125
+ #elif defined(__CUDA_ARCH__)
126
+ const uint32_t l_minus_1 = 31 - __clz((int) (d - 1));
127
+ #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM) || defined(_M_ARM64))
128
+ unsigned long l_minus_1;
129
+ _BitScanReverse(&l_minus_1, (unsigned long) (d - 1));
130
+ #elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) && FXDIV_USE_INLINE_ASSEMBLY
131
+ uint32_t l_minus_1;
132
+ __asm__("BSRL %[d_minus_1], %[l_minus_1]"
133
+ : [l_minus_1] "=r" (l_minus_1)
134
+ : [d_minus_1] "r" (d - 1)
135
+ : "cc");
136
+ #elif defined(__GNUC__)
137
+ const uint32_t l_minus_1 = 31 - __builtin_clz(d - 1);
138
+ #else
139
+ /* Based on Algorithm 2 from Hacker's delight */
140
+
141
+ uint32_t l_minus_1 = 0;
142
+ uint32_t x = d - 1;
143
+ uint32_t y = x >> 16;
144
+ if (y != 0) {
145
+ l_minus_1 += 16;
146
+ x = y;
147
+ }
148
+ y = x >> 8;
149
+ if (y != 0) {
150
+ l_minus_1 += 8;
151
+ x = y;
152
+ }
153
+ y = x >> 4;
154
+ if (y != 0) {
155
+ l_minus_1 += 4;
156
+ x = y;
157
+ }
158
+ y = x >> 2;
159
+ if (y != 0) {
160
+ l_minus_1 += 2;
161
+ x = y;
162
+ }
163
+ if ((x & 2) != 0) {
164
+ l_minus_1 += 1;
165
+ }
166
+ #endif
167
+ uint32_t u_hi = (UINT32_C(2) << (uint32_t) l_minus_1) - d;
168
+
169
+ /* Division of 64-bit number u_hi:UINT32_C(0) by 32-bit number d, 32-bit quotient output q */
170
+ #if defined(__GNUC__) && defined(__i386__) && FXDIV_USE_INLINE_ASSEMBLY
171
+ uint32_t q;
172
+ __asm__("DIVL %[d]"
173
+ : "=a" (q), "+d" (u_hi)
174
+ : [d] "r" (d), "a" (0)
175
+ : "cc");
176
+ #elif (defined(_MSC_VER) && _MSC_VER >= 1920) && !defined(__clang__) && !defined(__INTEL_COMPILER) && (defined(_M_IX86) || defined(_M_X64))
177
+ unsigned int remainder;
178
+ const uint32_t q = (uint32_t) _udiv64((unsigned __int64) ((uint64_t) u_hi << 32), (unsigned int) d, &remainder);
179
+ #else
180
+ const uint32_t q = ((uint64_t) u_hi << 32) / d;
181
+ #endif
182
+
183
+ result.m = q + UINT32_C(1);
184
+ result.s1 = 1;
185
+ result.s2 = (uint8_t) l_minus_1;
186
+ }
187
+ return result;
188
+ }
189
+
190
+ static inline struct fxdiv_divisor_uint64_t fxdiv_init_uint64_t(uint64_t d) {
191
+ struct fxdiv_divisor_uint64_t result = { d };
192
+ if (d == 1) {
193
+ result.m = UINT64_C(1);
194
+ result.s1 = 0;
195
+ result.s2 = 0;
196
+ } else {
197
+ #if defined(__OPENCL_VERSION__)
198
+ const uint32_t nlz_d = clz(d);
199
+ const uint32_t l_minus_1 = 63 - clz(d - 1);
200
+ #elif defined(__CUDA_ARCH__)
201
+ const uint32_t nlz_d = __clzll((long long) d);
202
+ const uint32_t l_minus_1 = 63 - __clzll((long long) (d - 1));
203
+ #elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64))
204
+ unsigned long l_minus_1;
205
+ _BitScanReverse64(&l_minus_1, (unsigned __int64) (d - 1));
206
+ unsigned long bsr_d;
207
+ _BitScanReverse64(&bsr_d, (unsigned __int64) d);
208
+ const uint32_t nlz_d = bsr_d ^ 0x3F;
209
+ #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_ARM))
210
+ const uint64_t d_minus_1 = d - 1;
211
+ const uint8_t d_is_power_of_2 = (d & d_minus_1) == 0;
212
+ unsigned long l_minus_1;
213
+ if ((uint32_t) (d_minus_1 >> 32) == 0) {
214
+ _BitScanReverse(&l_minus_1, (unsigned long) d_minus_1);
215
+ } else {
216
+ _BitScanReverse(&l_minus_1, (unsigned long) (uint32_t) (d_minus_1 >> 32));
217
+ l_minus_1 += 32;
218
+ }
219
+ const uint32_t nlz_d = ((uint8_t) l_minus_1 ^ UINT8_C(0x3F)) - d_is_power_of_2;
220
+ #elif defined(__GNUC__) && defined(__x86_64__) && FXDIV_USE_INLINE_ASSEMBLY
221
+ uint64_t l_minus_1;
222
+ __asm__("BSRQ %[d_minus_1], %[l_minus_1]"
223
+ : [l_minus_1] "=r" (l_minus_1)
224
+ : [d_minus_1] "r" (d - 1)
225
+ : "cc");
226
+ #elif defined(__GNUC__)
227
+ const uint32_t l_minus_1 = 63 - __builtin_clzll(d - 1);
228
+ const uint32_t nlz_d = __builtin_clzll(d);
229
+ #else
230
+ /* Based on Algorithm 2 from Hacker's delight */
231
+ const uint64_t d_minus_1 = d - 1;
232
+ const uint32_t d_is_power_of_2 = (d & d_minus_1) == 0;
233
+ uint32_t l_minus_1 = 0;
234
+ uint32_t x = (uint32_t) d_minus_1;
235
+ uint32_t y = d_minus_1 >> 32;
236
+ if (y != 0) {
237
+ l_minus_1 += 32;
238
+ x = y;
239
+ }
240
+ y = x >> 16;
241
+ if (y != 0) {
242
+ l_minus_1 += 16;
243
+ x = y;
244
+ }
245
+ y = x >> 8;
246
+ if (y != 0) {
247
+ l_minus_1 += 8;
248
+ x = y;
249
+ }
250
+ y = x >> 4;
251
+ if (y != 0) {
252
+ l_minus_1 += 4;
253
+ x = y;
254
+ }
255
+ y = x >> 2;
256
+ if (y != 0) {
257
+ l_minus_1 += 2;
258
+ x = y;
259
+ }
260
+ if ((x & 2) != 0) {
261
+ l_minus_1 += 1;
262
+ }
263
+ const uint32_t nlz_d = (l_minus_1 ^ UINT32_C(0x3F)) - d_is_power_of_2;
264
+ #endif
265
+ uint64_t u_hi = (UINT64_C(2) << (uint32_t) l_minus_1) - d;
266
+
267
+ /* Division of 128-bit number u_hi:UINT64_C(0) by 64-bit number d, 64-bit quotient output q */
268
+ #if defined(__GNUC__) && defined(__x86_64__) && FXDIV_USE_INLINE_ASSEMBLY
269
+ uint64_t q;
270
+ __asm__("DIVQ %[d]"
271
+ : "=a" (q), "+d" (u_hi)
272
+ : [d] "r" (d), "a" (UINT64_C(0))
273
+ : "cc");
274
+ #elif 0 && defined(__GNUC__) && defined(__SIZEOF_INT128__)
275
+ /* GCC, Clang, and Intel Compiler fail to inline optimized implementation and call into support library for 128-bit division */
276
+ const uint64_t q = (uint64_t) (((unsigned __int128) u_hi << 64) / ((unsigned __int128) d));
277
+ #elif (defined(_MSC_VER) && _MSC_VER >= 1920) && !defined(__clang__) && !defined(__INTEL_COMPILER) && defined(_M_X64)
278
+ unsigned __int64 remainder;
279
+ const uint64_t q = (uint64_t) _udiv128((unsigned __int64) u_hi, 0, (unsigned __int64) d, &remainder);
280
+ #else
281
+ /* Implementation based on code from Hacker's delight */
282
+
283
+ /* Normalize divisor and shift divident left */
284
+ d <<= nlz_d;
285
+ u_hi <<= nlz_d;
286
+ /* Break divisor up into two 32-bit digits */
287
+ const uint64_t d_hi = (uint32_t) (d >> 32);
288
+ const uint32_t d_lo = (uint32_t) d;
289
+
290
+ /* Compute the first quotient digit, q1 */
291
+ uint64_t q1 = u_hi / d_hi;
292
+ uint64_t r1 = u_hi - q1 * d_hi;
293
+
294
+ while ((q1 >> 32) != 0 || fxdiv_mulext_uint32_t((uint32_t) q1, d_lo) > (r1 << 32)) {
295
+ q1 -= 1;
296
+ r1 += d_hi;
297
+ if ((r1 >> 32) != 0) {
298
+ break;
299
+ }
300
+ }
301
+
302
+ /* Multiply and subtract. */
303
+ u_hi = (u_hi << 32) - q1 * d;
304
+
305
+ /* Compute the second quotient digit, q0 */
306
+ uint64_t q0 = u_hi / d_hi;
307
+ uint64_t r0 = u_hi - q0 * d_hi;
308
+
309
+ while ((q0 >> 32) != 0 || fxdiv_mulext_uint32_t((uint32_t) q0, d_lo) > (r0 << 32)) {
310
+ q0 -= 1;
311
+ r0 += d_hi;
312
+ if ((r0 >> 32) != 0) {
313
+ break;
314
+ }
315
+ }
316
+ const uint64_t q = (q1 << 32) | (uint32_t) q0;
317
+ #endif
318
+ result.m = q + UINT64_C(1);
319
+ result.s1 = 1;
320
+ result.s2 = (uint8_t) l_minus_1;
321
+ }
322
+ return result;
323
+ }
324
+
325
+ static inline struct fxdiv_divisor_size_t fxdiv_init_size_t(size_t d) {
326
+ #if SIZE_MAX == UINT32_MAX
327
+ const struct fxdiv_divisor_uint32_t uint_result = fxdiv_init_uint32_t((uint32_t) d);
328
+ #elif SIZE_MAX == UINT64_MAX
329
+ const struct fxdiv_divisor_uint64_t uint_result = fxdiv_init_uint64_t((uint64_t) d);
330
+ #else
331
+ #error Unsupported platform
332
+ #endif
333
+ struct fxdiv_divisor_size_t size_result = {
334
+ (size_t) uint_result.value,
335
+ (size_t) uint_result.m,
336
+ uint_result.s1,
337
+ uint_result.s2
338
+ };
339
+ return size_result;
340
+ }
341
+
342
+ static inline uint32_t fxdiv_quotient_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t divisor) {
343
+ const uint32_t t = fxdiv_mulhi_uint32_t(n, divisor.m);
344
+ return (t + ((n - t) >> divisor.s1)) >> divisor.s2;
345
+ }
346
+
347
+ static inline uint64_t fxdiv_quotient_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t divisor) {
348
+ const uint64_t t = fxdiv_mulhi_uint64_t(n, divisor.m);
349
+ return (t + ((n - t) >> divisor.s1)) >> divisor.s2;
350
+ }
351
+
352
+ static inline size_t fxdiv_quotient_size_t(size_t n, const struct fxdiv_divisor_size_t divisor) {
353
+ #if SIZE_MAX == UINT32_MAX
354
+ const struct fxdiv_divisor_uint32_t uint32_divisor = {
355
+ (uint32_t) divisor.value,
356
+ (uint32_t) divisor.m,
357
+ divisor.s1,
358
+ divisor.s2
359
+ };
360
+ return fxdiv_quotient_uint32_t((uint32_t) n, uint32_divisor);
361
+ #elif SIZE_MAX == UINT64_MAX
362
+ const struct fxdiv_divisor_uint64_t uint64_divisor = {
363
+ (uint64_t) divisor.value,
364
+ (uint64_t) divisor.m,
365
+ divisor.s1,
366
+ divisor.s2
367
+ };
368
+ return fxdiv_quotient_uint64_t((uint64_t) n, uint64_divisor);
369
+ #else
370
+ #error Unsupported platform
371
+ #endif
372
+ }
373
+
374
+ static inline uint32_t fxdiv_remainder_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t divisor) {
375
+ const uint32_t quotient = fxdiv_quotient_uint32_t(n, divisor);
376
+ return n - quotient * divisor.value;
377
+ }
378
+
379
+ static inline uint64_t fxdiv_remainder_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t divisor) {
380
+ const uint64_t quotient = fxdiv_quotient_uint64_t(n, divisor);
381
+ return n - quotient * divisor.value;
382
+ }
383
+
384
+ static inline size_t fxdiv_remainder_size_t(size_t n, const struct fxdiv_divisor_size_t divisor) {
385
+ const size_t quotient = fxdiv_quotient_size_t(n, divisor);
386
+ return n - quotient * divisor.value;
387
+ }
388
+
389
+ static inline uint32_t fxdiv_round_down_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t granularity) {
390
+ const uint32_t quotient = fxdiv_quotient_uint32_t(n, granularity);
391
+ return quotient * granularity.value;
392
+ }
393
+
394
+ static inline uint64_t fxdiv_round_down_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t granularity) {
395
+ const uint64_t quotient = fxdiv_quotient_uint64_t(n, granularity);
396
+ return quotient * granularity.value;
397
+ }
398
+
399
+ static inline size_t fxdiv_round_down_size_t(size_t n, const struct fxdiv_divisor_size_t granularity) {
400
+ const size_t quotient = fxdiv_quotient_size_t(n, granularity);
401
+ return quotient * granularity.value;
402
+ }
403
+
404
+ static inline struct fxdiv_result_uint32_t fxdiv_divide_uint32_t(uint32_t n, const struct fxdiv_divisor_uint32_t divisor) {
405
+ const uint32_t quotient = fxdiv_quotient_uint32_t(n, divisor);
406
+ const uint32_t remainder = n - quotient * divisor.value;
407
+ struct fxdiv_result_uint32_t result = { quotient, remainder };
408
+ return result;
409
+ }
410
+
411
+ static inline struct fxdiv_result_uint64_t fxdiv_divide_uint64_t(uint64_t n, const struct fxdiv_divisor_uint64_t divisor) {
412
+ const uint64_t quotient = fxdiv_quotient_uint64_t(n, divisor);
413
+ const uint64_t remainder = n - quotient * divisor.value;
414
+ struct fxdiv_result_uint64_t result = { quotient, remainder };
415
+ return result;
416
+ }
417
+
418
+ static inline struct fxdiv_result_size_t fxdiv_divide_size_t(size_t n, const struct fxdiv_divisor_size_t divisor) {
419
+ const size_t quotient = fxdiv_quotient_size_t(n, divisor);
420
+ const size_t remainder = n - quotient * divisor.value;
421
+ struct fxdiv_result_size_t result = { quotient, remainder };
422
+ return result;
423
+ }
424
+
425
+ #endif /* FXDIV_H */
videollama2/lib/python3.10/site-packages/torch/include/nnpack.h ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <stddef.h>
4
+ #include <stdint.h>
5
+ #include <stdbool.h>
6
+
7
+ #include <pthreadpool.h>
8
+
9
+ #ifdef __cplusplus
10
+ extern "C" {
11
+ #endif
12
+
13
+ /**
14
+ * @brief Status code for any NNPACK function call.
15
+ */
16
+ enum nnp_status {
17
+ /** The call succeeded, and all output arguments now contain valid data. */
18
+ nnp_status_success = 0,
19
+ /** NNPACK function was called with batch_size == 0. */
20
+ nnp_status_invalid_batch_size = 2,
21
+ /** NNPACK function was called with channels == 0. */
22
+ nnp_status_invalid_channels = 3,
23
+ /** NNPACK function was called with input_channels == 0. */
24
+ nnp_status_invalid_input_channels = 4,
25
+ /** NNPACK function was called with output_channels == 0. */
26
+ nnp_status_invalid_output_channels = 5,
27
+ /** NNPACK function was called with input_size.height == 0 or input_size.width == 0 */
28
+ nnp_status_invalid_input_size = 10,
29
+ /** NNPACK function was called with input_stride.height == 0 or input_stride.width == 0 */
30
+ nnp_status_invalid_input_stride = 11,
31
+ /** NNPACK function was called with input_padding not less than respective kernel (or pooling) size, i.e.:
32
+ *
33
+ * - input_padding.left >= kernel_size.width (>= pooling_size.width)
34
+ * - input_padding.right >= kernel_size.width (>= pooling_size.width)
35
+ * - input_padding.top >= kernel_size.height (>= pooling_size.height)
36
+ * - input_padding.bottom >= kernel_size.height (>= pooling_size.height)
37
+ */
38
+ nnp_status_invalid_input_padding = 12,
39
+ /** NNPACK function was called with kernel_size.height == 0 or kernel_size.width == 0 */
40
+ nnp_status_invalid_kernel_size = 13,
41
+ /** NNPACK function was called with pooling_size.height == 0 or pooling_size.width == 0 */
42
+ nnp_status_invalid_pooling_size = 14,
43
+ /** NNPACK function was called with pooling_stride.height == 0 or pooling_stride.width == 0 */
44
+ nnp_status_invalid_pooling_stride = 15,
45
+ /** NNPACK function was called with convolution algorithm not in nnp_convolution_algorithm enumeration */
46
+ nnp_status_invalid_algorithm = 16,
47
+ /** NNPACK function was called with convolution transform strategy not in nnp_convolution_transform_strategy enum */
48
+ nnp_status_invalid_transform_strategy = 17,
49
+ /** NNPACK function was called with output_subsampling.height == 0 or output_subsampling.width == 0 */
50
+ nnp_status_invalid_output_subsampling = 13,
51
+ /** NNPACK function was called with activation not in nnp_activation enum */
52
+ nnp_status_invalid_activation = 14,
53
+ /** NNPACK function was called with invalid activation parameters */
54
+ nnp_status_invalid_activation_parameters = 15,
55
+
56
+ /** NNPACK does not support the particular input size for the function */
57
+ nnp_status_unsupported_input_size = 20,
58
+ /** NNPACK does not support the particular input stride for the function */
59
+ nnp_status_unsupported_input_stride = 21,
60
+ /** NNPACK does not support the particular input padding for the function */
61
+ nnp_status_unsupported_input_padding = 22,
62
+ /** NNPACK does not support the particular kernel size for the function */
63
+ nnp_status_unsupported_kernel_size = 23,
64
+ /** NNPACK does not support the particular pooling size for the function */
65
+ nnp_status_unsupported_pooling_size = 24,
66
+ /** NNPACK does not support the particular pooling stride for the function */
67
+ nnp_status_unsupported_pooling_stride = 25,
68
+ /** NNPACK does not support the particular convolution algorithm for the function */
69
+ nnp_status_unsupported_algorithm = 26,
70
+ /** NNPACK does not support the particular convolution transform strategy for the algorithm */
71
+ nnp_status_unsupported_transform_strategy = 27,
72
+ /** NNPACK does not support the particular activation function for the function */
73
+ nnp_status_unsupported_activation = 28,
74
+ /** NNPACK does not support the particular activation function parameters for the function */
75
+ nnp_status_unsupported_activation_parameters = 29,
76
+
77
+ /** NNPACK function was called before the library was initialized */
78
+ nnp_status_uninitialized = 50,
79
+ /** NNPACK does not implement this function for the host CPU */
80
+ nnp_status_unsupported_hardware = 51,
81
+ /** NNPACK failed to allocate memory for temporary buffers */
82
+ nnp_status_out_of_memory = 52,
83
+ /** Scratch space buffer is too small */
84
+ nnp_status_insufficient_buffer = 53,
85
+ /** Scratch space buffer is not properly aligned */
86
+ nnp_status_misaligned_buffer = 54
87
+ };
88
+
89
+ /**
90
+ * @brief Activation applied applied after a convolutional or fully-connected layer.
91
+ */
92
+ enum nnp_activation {
93
+ /** Identity activation f(x) := x, i.e. no transformation */
94
+ nnp_activation_identity = 0,
95
+ /** ReLU activation f(x) := max(0, x) */
96
+ nnp_activation_relu = 1,
97
+ };
98
+
99
+ /**
100
+ * @brief Algorithm for computing convolutional layers.
101
+ */
102
+ enum nnp_convolution_algorithm {
103
+ /** Let NNPACK choose the algorithm depending on layer parameters */
104
+ nnp_convolution_algorithm_auto = 0,
105
+ /** Tiled convolution based on 2D Fourier transform with 8x8 blocks. Supports kernels up to 8x8. */
106
+ nnp_convolution_algorithm_ft8x8 = 1,
107
+ /** Tiled convolution based on 2D Fourier transform with 16x16 blocks. Supports kernels up to 16x16. */
108
+ nnp_convolution_algorithm_ft16x16 = 2,
109
+ /** Tiled convolution based on 2D Winograd transform F(3x3, 6x6) with 8x8 blocks. Supports only 3x3 kernels. */
110
+ nnp_convolution_algorithm_wt8x8 = 3,
111
+ /** Direct convolution via implicit GEMM. */
112
+ nnp_convolution_algorithm_implicit_gemm = 4,
113
+ /** Direct convolution implementation. */
114
+ nnp_convolution_algorithm_direct = 5,
115
+ /**
116
+ * Tiled convolution based on 2D Winograd transform F(3x3, 6x6) with 8x8 blocks in FP16.
117
+ * Supports only 3x3 kernels. Implemented only for new ARM processors (with NEON-HP),
118
+ * on non-supported processors falls back to nnp_convolution_algorithm_wt8x8.
119
+ */
120
+ nnp_convolution_algorithm_wt8x8_fp16 = 6,
121
+ };
122
+
123
+ enum nnp_convolution_transform_strategy {
124
+ nnp_convolution_transform_strategy_compute = 1,
125
+ nnp_convolution_transform_strategy_precompute = 2,
126
+ nnp_convolution_transform_strategy_reuse = 3
127
+ };
128
+
129
+ /* For backward compatibility */
130
+ #define nnp_convolution_transform_strategy_block_based nnp_convolution_transform_strategy_compute
131
+ #define nnp_convolution_transform_strategy_tuple_based nnp_convolution_transform_strategy_compute
132
+
133
+ /**
134
+ * @brief Size of images, kernels, and pooling filters in NNPACK.
135
+ */
136
+ struct nnp_size {
137
+ /** Width (horizontal size) of an image, kernel, or pooling filter. */
138
+ size_t width;
139
+ /** Height (vertical size) of an image, kernel, or pooling filter. */
140
+ size_t height;
141
+ };
142
+
143
+ /**
144
+ * @brief Padding of images in NNPACK.
145
+ */
146
+ struct nnp_padding {
147
+ /** Padding above the image data */
148
+ size_t top;
149
+ /** Padding on the right of image data */
150
+ size_t right;
151
+ /** Padding below the image data */
152
+ size_t bottom;
153
+ /** Padding on the left of image data */
154
+ size_t left;
155
+ };
156
+
157
+ /**
158
+ * @brief Profiling information about time spent in different phases of a function call.
159
+ */
160
+ struct nnp_profile {
161
+ /** Time spent inside the function call, in seconds. */
162
+ double total;
163
+ /** Time spend on transformation of the input or input gradient tensor, in seconds. */
164
+ double input_transform;
165
+ /** Time spend on transformation of the kernel or kernel gradient tensor, in seconds. */
166
+ double kernel_transform;
167
+ /** Time spend on transformation of the output or output gradient tensor, in seconds. */
168
+ double output_transform;
169
+ /** Time spend on multiplication-accumulation of transformed coefficients, in seconds. */
170
+ double block_multiplication;
171
+ };
172
+
173
+ enum nnp_status nnp_initialize(void);
174
+
175
+ enum nnp_status nnp_deinitialize(void);
176
+
177
+ /**
178
+ * @brief Computes output of a 2D convolutional layer from input and kernel tensors.
179
+ * @details This function targets training of convolutional neural networks and performs forward propagation.
180
+ * It is optimized for moderate minibatch sizes (64-128) and can be inefficient on a small minibatch.
181
+ * For minibatch size 1, use nnp_convolution_inference for optimal performance.
182
+ * @param algorithm The type of algorithm to use for convolution. Possible values are:
183
+ *
184
+ * - nnp_convolution_algorithm_auto -- let the function choose the algorithm.
185
+ * - nnp_convolution_algorithm_ft8x8 -- tiled convolution based on 2D Fourier transform with 8x8 blocks.
186
+ * Supports kernels up to 8x8.
187
+ * - nnp_convolution_algorithm_ft16x16 -- tiled convolution based on 2D Fourier transform with 16x16 blocks.
188
+ * Supports kernels up to 16x16.
189
+ * - nnp_convolution_algorithm_wt8x8 -- tiled convolution based on 2D Winograd transform F(3x3, 6x6).
190
+ * Supports only 3x3 kernels.
191
+ *
192
+ * @param batch_size The number of images on the input and output of the convolutional layer.
193
+ * @param input_channels The number of channels (AKA features, dimensions) in the input images.
194
+ * @param output_channels The number of channels (AKA features, dimensions) in the output images.
195
+ * @param input_size Size of input images, excluding implicit zero-padding.
196
+ * @param input_padding Implicit zero-padding of input images.
197
+ * @param kernel_size Kernel size.
198
+ * @param[in] input A 4D tensor input[batch_size][input_channels][input_size.height][input_size.width].
199
+ * @param[in] kernel A 4D tensor kernel[output_channels][input_channels][kernel_size.height][kernel_size.width].
200
+ * @param[in] bias A 1D array bias[output_channels].
201
+ * @param[out] output A 4D tensor output[batch_size][output_channels][output_size.height][output_size.width] where
202
+ * output_size.height = (input_padding.top + input_size.height + input_padding.bottom) -
203
+ * (kernel_size.height - 1)
204
+ * output_size.width = (input_padding.left + input_size.width + input_padding.right) -
205
+ * (kernel_size.width - 1)
206
+ * @param threadpool A thread pool for parallelization of the computation.
207
+ * If threadpool is NULL, the computation would run on the caller thread without parallelization.
208
+ * @param[out] profile An optional pointer to profiling structure.
209
+ * If provided, the structure would record time spent in different phases of the computation.
210
+ */
211
+
212
+ enum nnp_status nnp_convolution_output(
213
+ enum nnp_convolution_algorithm algorithm,
214
+ size_t batch_size,
215
+ size_t input_channels,
216
+ size_t output_channels,
217
+ struct nnp_size input_size,
218
+ struct nnp_padding input_padding,
219
+ struct nnp_size kernel_size,
220
+ const float* input,
221
+ const float* kernel,
222
+ const float* bias,
223
+ float* output,
224
+ void* workspace_buffer,
225
+ size_t* workspace_size,
226
+ enum nnp_activation activation,
227
+ const void* activation_parameters,
228
+ pthreadpool_t threadpool,
229
+ struct nnp_profile* profile);
230
+
231
+ /**
232
+ * @brief Computes gradient of input of a 2D convolutional layer from gradient of output and kernel tensors.
233
+ * @details This function targets training of convolutional neural networks and performs backward propagation.
234
+ * It is optimized for moderate minibatch sizes (64-128) and can be inefficient on a small minibatch.
235
+ * @param algorithm The type of algorithm to use for convolution. Possible values are:
236
+ *
237
+ * - nnp_convolution_algorithm_auto -- let the function choose the algorithm.
238
+ * - nnp_convolution_algorithm_ft8x8 -- tiled convolution based on 2D Fourier transform with 8x8 blocks.
239
+ * Supports kernels up to 8x8.
240
+ * - nnp_convolution_algorithm_ft16x16 -- tiled convolution based on 2D Fourier transform with 16x16 blocks.
241
+ * Supports kernels up to 16x16.
242
+ * - nnp_convolution_algorithm_wt8x8 -- tiled convolution based on 2D Winograd transform F(3x3, 6x6).
243
+ * Supports only 3x3 kernels.
244
+ *
245
+ * @param batch_size The number of images (and their gradients) on the input and output of the convolutional layer.
246
+ * @param input_channels The number of channels (AKA features, dimensions) in the input images (and gradients).
247
+ * @param output_channels The number of channels (AKA features, dimensions) in the output images (and gradients).
248
+ * @param input_size Size of input images and their gradients, excluding implicit zero-padding.
249
+ * @param input_padding Implicit zero-padding of input images.
250
+ * @param kernel_size Kernel size.
251
+ * @param[in] grad_output A 4D tensor grad_output[batch_size][output_channels][output_size.height][output_size.width]
252
+ * where
253
+ * output_size.height = (input_padding.top + input_size.height + input_padding.bottom) -
254
+ * (kernel_size.height - 1)
255
+ * output_size.width = (input_padding.left + input_size.width + input_padding.right) -
256
+ * (kernel_size.width - 1)
257
+ * @param[in] kernel A 4D tensor kernel[output_channels][input_channels][kernel_size.height][kernel_size.width].
258
+ * @param[out] grad_input A 4D tensor grad_input[batch_size][input_channels][input_size.height][input_size.width].
259
+ * @param threadpool A thread pool for parallelization of the computation.
260
+ * If threadpool is NULL, the computation would run on the caller thread without parallelization.
261
+ * @param[out] profile An optional pointer to profiling structure.
262
+ * If provided, the structure would record time spent in different phases of the computation.
263
+ */
264
+ enum nnp_status nnp_convolution_input_gradient(
265
+ enum nnp_convolution_algorithm algorithm,
266
+ size_t batch_size,
267
+ size_t input_channels,
268
+ size_t output_channels,
269
+ struct nnp_size input_size,
270
+ struct nnp_padding input_padding,
271
+ struct nnp_size kernel_size,
272
+ const float* grad_output,
273
+ const float* kernel,
274
+ float* grad_input,
275
+ void* workspace_buffer,
276
+ size_t* workspace_size,
277
+ enum nnp_activation activation,
278
+ const void* activation_parameters,
279
+ pthreadpool_t threadpool,
280
+ struct nnp_profile* profile);
281
+
282
+ /**
283
+ * @brief Computes gradient of kernel of a 2D convolutional layer from gradient of output and input tensors.
284
+ * @details This function targets training of convolutional neural networks and performs backward propagation.
285
+ * It is optimized for moderate minibatch sizes (64-128) and can be inefficient on a small minibatch.
286
+ * @param algorithm The type of algorithm to use for convolution. Possible values are:
287
+ *
288
+ * - nnp_convolution_algorithm_auto -- let the function choose the algorithm.
289
+ * - nnp_convolution_algorithm_ft8x8 -- tiled convolution based on 2D Fourier transform with 8x8 blocks.
290
+ * Supports kernels up to 8x8.
291
+ * - nnp_convolution_algorithm_ft16x16 -- tiled convolution based on 2D Fourier transform with 16x16 blocks.
292
+ * Supports kernels up to 16x16.
293
+ *
294
+ * @param batch_size The number of images (and their gradients) on the input and output of the convolutional layer.
295
+ * @param input_channels The number of channels (AKA features, dimensions) in the input images.
296
+ * @param output_channels The number of channels (AKA features, dimensions) in the output images (and gradients).
297
+ * @param input_size Size of input images and their gradients, excluding implicit zero-padding.
298
+ * @param input_padding Implicit zero-padding of input images.
299
+ * @param kernel_size Kernel size.
300
+ * @param[in] input A 4D tensor input[batch_size][input_channels][input_size.height][input_size.width].
301
+ * @param[in] grad_output A 4D tensor grad_output[batch_size][output_channels][output_size.height][output_size.width]
302
+ * where
303
+ * output_size.height = (input_padding.top + input_size.height + input_padding.bottom) -
304
+ * (kernel_size.height - 1)
305
+ * output_size.width = (input_padding.left + input_size.width + input_padding.right) -
306
+ * (kernel_size.width - 1)
307
+ * @param[out] grad_kernel A 4D tensor
308
+ * grad_kernel[output_channels][input_channels][kernel_size.height][kernel_size.width].
309
+ * @param threadpool A thread pool for parallelization of the computation.
310
+ * If threadpool is NULL, the computation would run on the caller thread without parallelization.
311
+ * @param[out] profile An optional pointer to profiling structure.
312
+ * If provided, the structure would record time spent in different phases of the computation.
313
+ */
314
+ enum nnp_status nnp_convolution_kernel_gradient(
315
+ enum nnp_convolution_algorithm algorithm,
316
+ size_t batch_size,
317
+ size_t input_channels,
318
+ size_t output_channels,
319
+ struct nnp_size input_size,
320
+ struct nnp_padding input_padding,
321
+ struct nnp_size kernel_size,
322
+ const float* input,
323
+ const float* grad_output,
324
+ float* grad_kernel,
325
+ void* workspace_buffer,
326
+ size_t* workspace_size,
327
+ enum nnp_activation activation,
328
+ const void* activation_parameters,
329
+ pthreadpool_t threadpool,
330
+ struct nnp_profile* profile);
331
+
332
+ /**
333
+ * @brief Computes output of a 2D convolutional layer for a single input image and a kernel tensor.
334
+ * @details This function targets prediction with convolutional neural networks and performs forward propagation.
335
+ * @param algorithm The type of algorithm to use for convolution. Possible values are:
336
+ *
337
+ * - nnp_convolution_algorithm_auto -- let the function choose the algorithm.
338
+ * - nnp_convolution_algorithm_ft8x8 -- tiled convolution based on 2D Fourier transform with 8x8 blocks.
339
+ * Supports kernels up to 8x8.
340
+ * - nnp_convolution_algorithm_ft16x16 -- tiled convolution based on 2D Fourier transform with 16x16 blocks.
341
+ * Supports kernels up to 16x16.
342
+ * - nnp_convolution_algorithm_wt8x8 -- tiled convolution based on 2D Winograd transform F(3x3, 6x6).
343
+ * Supports only 3x3 kernels.
344
+ *
345
+ * @param transform_strategy A strategy that guides computation of kernel transforms coefficients.
346
+ * Possible values are:
347
+ *
348
+ * - nnp_convolution_transform_strategy_block_based -- do multiplication-accumulations on blocks of transformed
349
+ * coefficients.
350
+ * - nnp_convolution_transform_strategy_tuple_based -- do multiplication-accumulations on tuples of transformed
351
+ * coefficients.
352
+ *
353
+ * @param input_channels The number of channels (AKA features, dimensions) in the input image.
354
+ * @param output_channels The number of channels (AKA features, dimensions) in the output image.
355
+ * @param input_size Size of input image, excluding implicit zero-padding.
356
+ * @param input_padding Implicit zero-padding of input image.
357
+ * @param kernel_size Kernel size.
358
+ * @param output_subsampling Subsample region for output, also known as convolution stride.
359
+ * @param[in] input A 3D tensor input[input_channels][input_size.height][input_size.width].
360
+ * @param[in] kernel A 4D tensor kernel[output_channels][input_channels][kernel_size.height][kernel_size.width].
361
+ * @param[in] bias A 1D array bias[output_channels].
362
+ * @param[out] output A 3D tensor output[output_channels][output_size.height][output_size.width] where
363
+ * output_size.height = (input_padding.top + input_size.height + input_padding.bottom) -
364
+ * (kernel_size.height - 1)
365
+ * output_size.width = (input_padding.left + input_size.width + input_padding.right) -
366
+ * (kernel_size.width - 1)
367
+ * @param[in] workspace_buffer Buffer for scratch memory used during computation. Buffer must be aligned on 64 bytes.
368
+ * If workspace_buffer is NULL and workspace_size is non-NULL, NNPACK would store the size
369
+ * of required workspace memory at the workspace_size location, and exit without
370
+ * computations.
371
+ * If workspace_buffer is NULL and workspace_size is NULL, NNPACK would allocate memory
372
+ * before and deallocate after this computation, potentially at significant runtime cost.
373
+ * @param[in,out] workspace_size Pointer to the size of workspace buffer.
374
+ * If workspace_buffer is NULL, NNPACK will write the size of required scratch memory to
375
+ * the location specified by this pointer.
376
+ * If workspace_buffer is non-NULL, NNPACK expects workspace_size to specify the size of
377
+ * the buffer, in bytes.
378
+ * If workspace_size is NULL, workspace_buffer must be NULL as well. In this case NNPACK
379
+ * would allocate memory before and deallocate after this computation, potentially at
380
+ * significant runtime cost.
381
+ * @param threadpool A thread pool for parallelization of the computation.
382
+ * If threadpool is NULL, the computation would run on the caller thread without parallelization.
383
+ * @param[out] profile An optional pointer to profiling structure.
384
+ * If provided, the structure would record time spent in different phases of the computation.
385
+ */
386
+ enum nnp_status nnp_convolution_inference(
387
+ enum nnp_convolution_algorithm algorithm,
388
+ enum nnp_convolution_transform_strategy transform_strategy,
389
+ size_t input_channels,
390
+ size_t output_channels,
391
+ struct nnp_size input_size,
392
+ struct nnp_padding input_padding,
393
+ struct nnp_size kernel_size,
394
+ struct nnp_size output_subsampling,
395
+ const float* input,
396
+ const float* kernel,
397
+ const float* bias,
398
+ float* output,
399
+ void* workspace_buffer,
400
+ size_t* workspace_size,
401
+ enum nnp_activation activation,
402
+ const void* activation_parameters,
403
+ pthreadpool_t threadpool,
404
+ struct nnp_profile* profile);
405
+
406
+ /**
407
+ * @brief Computes output of a fully connected layer from input and kernel matrices.
408
+ * @details This function targets training of convolutional neural networks and performs forward propagation.
409
+ * It is optimized for moderate minibatch sizes (64-128) and can be inefficient on a small minibatch.
410
+ * For minibatch size 1, use nnp_fully_connected_inference for optimal performance.
411
+ * @param batch_size The number of vectors on the input and output of the fully connected layer.
412
+ * @param input_channels The number of channels (AKA features, dimensions) in the input matrix.
413
+ * @param output_channels The number of channels (AKA features, dimensions) in the output matrix.
414
+ * @param[in] input A 2D matrix input[batch_size][input_channels].
415
+ * @param[in] kernel A 2D matrix kernel[output_channels][input_channels].
416
+ * @param[out] output A 2D matrix output[batch_size][output_channels].
417
+ * @param threadpool A thread pool for parallelization of the computation.
418
+ * If threadpool is NULL, the computation would run on the caller thread without parallelization.
419
+ */
420
+ enum nnp_status nnp_fully_connected_output(
421
+ size_t batch_size,
422
+ size_t input_channels,
423
+ size_t output_channels,
424
+ const float input[],
425
+ const float kernel[],
426
+ float output[],
427
+ pthreadpool_t threadpool,
428
+ struct nnp_profile* profile);
429
+
430
+ /**
431
+ * @brief Computes output of a fully connected layer for a single input vector and a kernel matrix.
432
+ * @details This function targets prediction with convolutional neural networks and performs forward propagation.
433
+ * @param input_channels The number of channels (AKA features, dimensions) in the input vector.
434
+ * @param output_channels The number of channels (AKA features, dimensions) in the output vector.
435
+ * @param[in] input A 1D array input[input_channels] of FP32 elements.
436
+ * @param[in] kernel A 2D matrix kernel[output_channels][input_channels] of FP32 elements.
437
+ * @param[out] output A 1D array output[output_channels] of FP32 elements.
438
+ * @param threadpool A thread pool for parallelization of the computation.
439
+ * If threadpool is NULL, the computation would run on the caller thread without parallelization.
440
+ */
441
+ enum nnp_status nnp_fully_connected_inference(
442
+ size_t input_channels,
443
+ size_t output_channels,
444
+ const float* input,
445
+ const float* kernel,
446
+ float* output,
447
+ pthreadpool_t threadpool);
448
+
449
+ /**
450
+ * @brief Computes output of a fully connected layer for a single input vector and a kernel matrix.
451
+ * @details This function targets prediction with convolutional neural networks and performs forward propagation.
452
+ * @param input_channels The number of channels (AKA features, dimensions) in the input vector.
453
+ * @param output_channels The number of channels (AKA features, dimensions) in the output vector.
454
+ * @param[in] input A 1D array input[input_channels] of FP32 elements.
455
+ * @param[in] kernel A 2D matrix kernel[output_channels][input_channels] of FP16 (ARM alternative format) elements.
456
+ * @param[out] output A 1D array output[output_channels] of FP32 elements.
457
+ * @param threadpool A thread pool for parallelization of the computation.
458
+ * If threadpool is NULL, the computation would run on the caller thread without parallelization.
459
+ */
460
+ enum nnp_status nnp_fully_connected_inference_f16f32(
461
+ size_t input_channels,
462
+ size_t output_channels,
463
+ const float* input,
464
+ const void* kernel,
465
+ float* output,
466
+ pthreadpool_t threadpool);
467
+
468
+ /**
469
+ * @brief Computes output of a max-pooling layer for an input tensor.
470
+ * @details This function targets both prediction and training of convolutional neural networks and performs forward
471
+ * propagation. Is is optimized for both large and small minibatch sizes.
472
+ * @param batch_size The number of images on the input and output of the max-pooling layer.
473
+ * @param channels The number of channels (AKA features, dimensions) in both input and output images.
474
+ * @param input_size Size of input images, excluding implicit zero-padding.
475
+ * @param input_padding Implicit padding of input images. The padding pixels are ignored by the pooling filter, but
476
+ * affect the output size.
477
+ * @param pooling_size Size of the pooling filter. Only 2x2 filter are currently supported.
478
+ * @param pooling_stride Stride of the pooling filter. Only 2x2 strides are currently supported.
479
+ * @param[in] input A 4D tensor input[batch_size][channels][input_size.height][input_size.width].
480
+ * @param[out] output A 4D tensor output[batch_size][channels][output_size.height][output_size.width] where
481
+ * output_size.height = ceil(
482
+ * (input_padding.top + input_size.height + input_padding.bottom - pooling_size.height) /
483
+ * pooling_stride.height) + 1
484
+ * output_size.width = ceil(
485
+ * (input_padding.left + input_size.width + input_padding.right - pooling_size.width) /
486
+ * pooling_stride.width) + 1
487
+ * @param threadpool A thread pool for parallelization of the computation.
488
+ * If threadpool is NULL, the computation would run on the caller thread without parallelization.
489
+ */
490
+ enum nnp_status nnp_max_pooling_output(
491
+ size_t batch_size,
492
+ size_t channels,
493
+ struct nnp_size input_size,
494
+ struct nnp_padding input_padding,
495
+ struct nnp_size pooling_size,
496
+ struct nnp_size pooling_stride,
497
+ const float input[],
498
+ float output[],
499
+ pthreadpool_t threadpool);
500
+
501
+ /**
502
+ * @brief Computes output of a softmax layer for an input matrix.
503
+ * @details This function targets both prediction and training of convolutional neural networks and performs forward
504
+ * propagation. Is is optimized for both large and small minibatch sizes.
505
+ * @param batch_size The number of vectors on the input and output of the softmax layer.
506
+ * @param channels The number of channels (AKA features, dimensions) in both input and output vectors.
507
+ * @param[in] input A 2D matrix input[batch_size][channels].
508
+ * @param[out] output A 2D matrix output[batch_size][channels].
509
+ * @param threadpool A thread pool for parallelization of the computation.
510
+ * If threadpool is NULL, the computation would run on the caller thread without parallelization.
511
+ */
512
+ enum nnp_status nnp_softmax_output(
513
+ size_t batch_size,
514
+ size_t channels,
515
+ const float input[],
516
+ float output[],
517
+ pthreadpool_t threadpool);
518
+
519
+ /**
520
+ * @brief Computes output of a rectified linear unit (ReLU) layer for an input matrix.
521
+ * @details This function targets both prediction and training of convolutional neural networks and performs forward
522
+ * propagation. Is is optimized for both large and small minibatch sizes.
523
+ * @param batch_size The number of vectors on the input and output of the ReLU layer.
524
+ * @param channels The number of channels (AKA features, dimensions) in both input and output matrices.
525
+ * @param[in] input A 2D matrix input[batch_size][channels].
526
+ * @param[out] output A 2D matrix output[batch_size][channels].
527
+ * @param threadpool A thread pool for parallelization of the computation.
528
+ * If threadpool is NULL, the computation would run on the caller thread without parallelization.
529
+ */
530
+ enum nnp_status nnp_relu_output(
531
+ size_t batch_size,
532
+ size_t channels,
533
+ const float input[],
534
+ float output[],
535
+ float negative_slope,
536
+ pthreadpool_t threadpool);
537
+
538
+ /**
539
+ * @brief Computes gradient of input of a rectified linear unit (ReLU) layer from gradient of output and input matrices.
540
+ * @details This function targets training of convolutional neural networks and performs backward propagation.
541
+ * Is is optimized for both large and small minibatch sizes.
542
+ * @param batch_size The number of vectors on the input and output of the ReLU layer.
543
+ * @param channels The number of channels (AKA features, dimensions) in both input and output matrices.
544
+ * @param[in] input A 2D matrix input[batch_size][channels].
545
+ * @param[out] output A 2D matrix output[batch_size][channels].
546
+ * @param threadpool A thread pool for parallelization of the computation.
547
+ * If threadpool is NULL, the computation would run on the caller thread without parallelization.
548
+ */
549
+ enum nnp_status nnp_relu_input_gradient(
550
+ size_t batch_size,
551
+ size_t channels,
552
+ const float grad_output[],
553
+ const float input[],
554
+ float grad_input[],
555
+ float negative_slope,
556
+ pthreadpool_t threadpool);
557
+
558
+ #ifdef __cplusplus
559
+ } /* extern "C" */
560
+ #endif
561
+
562
+ #ifdef __cplusplus
563
+ // Backward compatible implementations for nnp_convolution_*, if we are in C++
564
+ // mode.
565
+ inline enum nnp_status nnp_convolution_output(
566
+ enum nnp_convolution_algorithm algorithm,
567
+ size_t batch_size,
568
+ size_t input_channels,
569
+ size_t output_channels,
570
+ struct nnp_size input_size,
571
+ struct nnp_padding input_padding,
572
+ struct nnp_size kernel_size,
573
+ const float input[],
574
+ const float kernel[],
575
+ const float bias[],
576
+ float output[],
577
+ pthreadpool_t threadpool,
578
+ struct nnp_profile* profile)
579
+ {
580
+ return nnp_convolution_output(
581
+ algorithm,
582
+ batch_size, input_channels, output_channels,
583
+ input_size, input_padding, kernel_size,
584
+ input, kernel, bias, output,
585
+ NULL, NULL,
586
+ nnp_activation_identity, NULL, threadpool, profile);
587
+ }
588
+
589
+ inline enum nnp_status nnp_convolution_input_gradient(
590
+ enum nnp_convolution_algorithm algorithm,
591
+ size_t batch_size,
592
+ size_t input_channels,
593
+ size_t output_channels,
594
+ struct nnp_size input_size,
595
+ struct nnp_padding input_padding,
596
+ struct nnp_size kernel_size,
597
+ const float grad_output[],
598
+ const float kernel[],
599
+ float grad_input[],
600
+ pthreadpool_t threadpool,
601
+ struct nnp_profile* profile)
602
+ {
603
+ return nnp_convolution_input_gradient(
604
+ algorithm,
605
+ batch_size, input_channels, output_channels,
606
+ input_size, input_padding, kernel_size,
607
+ grad_output, kernel, grad_input,
608
+ NULL, NULL,
609
+ nnp_activation_identity, NULL, threadpool, profile);
610
+ }
611
+
612
+ inline enum nnp_status nnp_convolution_kernel_gradient(
613
+ enum nnp_convolution_algorithm algorithm,
614
+ size_t batch_size,
615
+ size_t input_channels,
616
+ size_t output_channels,
617
+ struct nnp_size input_size,
618
+ struct nnp_padding input_padding,
619
+ struct nnp_size kernel_size,
620
+ const float input[],
621
+ const float grad_output[],
622
+ float grad_kernel[],
623
+ pthreadpool_t threadpool,
624
+ struct nnp_profile* profile)
625
+ {
626
+ return nnp_convolution_kernel_gradient(
627
+ algorithm,
628
+ batch_size, input_channels, output_channels,
629
+ input_size, input_padding, kernel_size,
630
+ input, grad_output, grad_kernel,
631
+ NULL, NULL,
632
+ nnp_activation_identity, NULL, threadpool, profile);
633
+ }
634
+
635
+ inline enum nnp_status nnp_convolution_inference(
636
+ enum nnp_convolution_algorithm algorithm,
637
+ enum nnp_convolution_transform_strategy transform_strategy,
638
+ size_t input_channels,
639
+ size_t output_channels,
640
+ struct nnp_size input_size,
641
+ struct nnp_padding input_padding,
642
+ struct nnp_size kernel_size,
643
+ struct nnp_size output_subsampling,
644
+ const float input[],
645
+ const float kernel[],
646
+ const float bias[],
647
+ float output[],
648
+ pthreadpool_t threadpool,
649
+ struct nnp_profile* profile) {
650
+ return nnp_convolution_inference(
651
+ algorithm, transform_strategy,
652
+ input_channels, output_channels,
653
+ input_size, input_padding, kernel_size, output_subsampling,
654
+ input, kernel, bias, output, NULL, NULL,
655
+ nnp_activation_identity, NULL,
656
+ threadpool, profile);
657
+ }
658
+
659
+ #endif // __cplusplus
videollama2/lib/python3.10/site-packages/torch/include/pthreadpool.h ADDED
The diff for this file is too large to render. See raw diff
 
videollama2/lib/python3.10/site-packages/torch/include/qnnpack_func.h ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstdlib>
4
+ #include <qnnpack/operator.h>
5
+
6
+ namespace qnnpack {
7
+ class PrePackConvWeights final {
8
+ public:
9
+ PrePackConvWeights(
10
+ const pytorch_qnnp_operator_t convolution,
11
+ const uint8_t* kernel_zero_points,
12
+ const uint8_t* kernel,
13
+ const int32_t* bias);
14
+
15
+ void* getPackedWeights() const
16
+ {
17
+ return packed_weights_;
18
+ }
19
+
20
+ int64_t getOutputChannels() const
21
+ {
22
+ return output_channels_;
23
+ }
24
+
25
+ ~PrePackConvWeights()
26
+ {
27
+ if (packed_weights_ != nullptr) {
28
+ free(packed_weights_);
29
+ }
30
+ }
31
+
32
+ PrePackConvWeights() = delete;
33
+ PrePackConvWeights(const PrePackConvWeights&) = delete;
34
+ PrePackConvWeights& operator=(const PrePackConvWeights&) = delete;
35
+
36
+ private:
37
+ void* packed_weights_ = nullptr;
38
+ int64_t output_channels_;
39
+ };
40
+
41
+ class PackBMatrix final {
42
+ public:
43
+ PackBMatrix(
44
+ size_t input_channels,
45
+ size_t output_channels,
46
+ const uint8_t* kernel_zero_points,
47
+ const float* requantization_scale,
48
+ const uint8_t* kernel,
49
+ const int32_t* bias);
50
+
51
+ // This constructor is to be used for dynamic mode
52
+ // quantization. In dynamic mode, we dont yet support
53
+ // per channel quantization, and paying the cost of
54
+ // memory allocation for per channel zero point and
55
+ // requant scale will hurt performance.
56
+ PackBMatrix(
57
+ size_t input_channels,
58
+ size_t output_channels,
59
+ const uint8_t kernel_zero_point,
60
+ const float requantization_scale,
61
+ const uint8_t* kernel,
62
+ const int32_t* bias);
63
+
64
+ void* getPackedWeights() const
65
+ {
66
+ return packed_weights_;
67
+ }
68
+
69
+ void unpackWeights(
70
+ const uint8_t* kernel_zero_points,
71
+ int8_t* kernel
72
+ ) const;
73
+
74
+ size_t getInputChannels() const
75
+ {
76
+ return input_channels_;
77
+ }
78
+
79
+ size_t getOutputChannels() const
80
+ {
81
+ return output_channels_;
82
+ }
83
+
84
+ ~PackBMatrix()
85
+ {
86
+ if (packed_weights_ != nullptr) {
87
+ free(packed_weights_);
88
+ }
89
+ }
90
+
91
+ PackBMatrix() = delete;
92
+ PackBMatrix(const PackBMatrix&) = delete;
93
+ PackBMatrix& operator=(const PackBMatrix&) = delete;
94
+
95
+ private:
96
+ void* packed_weights_ = nullptr;
97
+ size_t input_channels_;
98
+ size_t output_channels_;
99
+ };
100
+
101
+ enum pytorch_qnnp_status qnnpackLinear(
102
+ const size_t batch_size,
103
+ const size_t input_channels,
104
+ const size_t output_channels,
105
+ const uint8_t input_zero_point,
106
+ const uint8_t* kernel_zero_points,
107
+ const float* requantization_scales,
108
+ const uint8_t output_zero_point,
109
+ const uint8_t output_min,
110
+ const uint8_t output_max,
111
+ const uint8_t* input,
112
+ const size_t input_stride,
113
+ void* packed_weights,
114
+ uint8_t* output,
115
+ const size_t output_stride,
116
+ pthreadpool_t threadpool);
117
+
118
+ enum pytorch_qnnp_status qnnpackConv(
119
+ const pytorch_qnnp_operator_t convolution,
120
+ void* packed_weights,
121
+ const size_t batch_size,
122
+ const size_t input_depth,
123
+ const size_t input_height,
124
+ const size_t input_width,
125
+ const uint8_t input_zero_point,
126
+ const uint8_t* input,
127
+ const uint8_t* kernel_zero_points,
128
+ const float* requantization_scales,
129
+ const uint8_t output_zero_point,
130
+ const uint8_t output_min,
131
+ const uint8_t output_max,
132
+ uint8_t* output,
133
+ pthreadpool_t threadpool);
134
+
135
+ enum pytorch_qnnp_status qnnpackDeConv(
136
+ const pytorch_qnnp_operator_t deconvolution,
137
+ void* packed_weights,
138
+ const size_t batch_size,
139
+ const size_t input_height,
140
+ const size_t input_width,
141
+ const uint8_t input_zero_point,
142
+ const uint8_t* input,
143
+ const uint8_t* kernel_zero_points,
144
+ const float* requantization_scales,
145
+ const uint8_t output_zero_point,
146
+ const uint8_t output_min,
147
+ const uint8_t output_max,
148
+ uint8_t* output,
149
+ pthreadpool_t threadpool);
150
+
151
+ enum pytorch_qnnp_status qnnpackLinearDynamic(
152
+ const size_t batch_size,
153
+ const size_t input_channels,
154
+ const size_t output_channels,
155
+ const uint8_t input_zero_point,
156
+ const uint8_t* kernel_zero_points,
157
+ const float* dequantization_scales,
158
+ const uint8_t* input,
159
+ const size_t input_stride,
160
+ void* packed_weights,
161
+ const float* bias,
162
+ float* output,
163
+ const size_t output_stride,
164
+ pthreadpool_t threadpool);
165
+
166
+ } // namespace qnnpack
videollama2/lib/python3.10/site-packages/torch/include/sleef.h ADDED
The diff for this file is too large to render. See raw diff
 
videollama2/lib/python3.10/site-packages/torch/include/xnnpack.h ADDED
The diff for this file is too large to render. See raw diff
 
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/array.h ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Kitchen-sink public API for arrow::Array data structures. C++ library code
19
+ // (especially header files) in Apache Arrow should use more specific headers
20
+ // unless it's a file that uses most or all Array types in which case using
21
+ // arrow/array.h is fine.
22
+
23
+ #pragma once
24
+
25
+ /// \defgroup numeric-arrays Concrete classes for numeric arrays
26
+ /// @{
27
+ /// @}
28
+
29
+ /// \defgroup binary-arrays Concrete classes for binary/string arrays
30
+ /// @{
31
+ /// @}
32
+
33
+ /// \defgroup nested-arrays Concrete classes for nested arrays
34
+ /// @{
35
+ /// @}
36
+
37
+ /// \defgroup run-end-encoded-arrays Concrete classes for run-end encoded arrays
38
+ /// @{
39
+ /// @}
40
+
41
+ #include "arrow/array/array_base.h" // IWYU pragma: keep
42
+ #include "arrow/array/array_binary.h" // IWYU pragma: keep
43
+ #include "arrow/array/array_decimal.h" // IWYU pragma: keep
44
+ #include "arrow/array/array_dict.h" // IWYU pragma: keep
45
+ #include "arrow/array/array_nested.h" // IWYU pragma: keep
46
+ #include "arrow/array/array_primitive.h" // IWYU pragma: keep
47
+ #include "arrow/array/array_run_end.h" // IWYU pragma: keep
48
+ #include "arrow/array/data.h" // IWYU pragma: keep
49
+ #include "arrow/array/util.h" // IWYU pragma: keep
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/buffer.h ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <cstring>
22
+ #include <memory>
23
+ #include <optional>
24
+ #include <string>
25
+ #include <string_view>
26
+ #include <utility>
27
+ #include <vector>
28
+
29
+ #include "arrow/device.h"
30
+ #include "arrow/status.h"
31
+ #include "arrow/type_fwd.h"
32
+ #include "arrow/util/macros.h"
33
+ #include "arrow/util/span.h"
34
+ #include "arrow/util/visibility.h"
35
+
36
+ namespace arrow {
37
+
38
+ // ----------------------------------------------------------------------
39
+ // Buffer classes
40
+
41
+ /// \class Buffer
42
+ /// \brief Object containing a pointer to a piece of contiguous memory with a
43
+ /// particular size.
44
+ ///
45
+ /// Buffers have two related notions of length: size and capacity. Size is
46
+ /// the number of bytes that might have valid data. Capacity is the number
47
+ /// of bytes that were allocated for the buffer in total.
48
+ ///
49
+ /// The Buffer base class does not own its memory, but subclasses often do.
50
+ ///
51
+ /// The following invariant is always true: Size <= Capacity
52
+ class ARROW_EXPORT Buffer {
53
+ public:
54
+ ARROW_DISALLOW_COPY_AND_ASSIGN(Buffer);
55
+
56
+ /// \brief Construct from buffer and size without copying memory
57
+ ///
58
+ /// \param[in] data a memory buffer
59
+ /// \param[in] size buffer size
60
+ ///
61
+ /// \note The passed memory must be kept alive through some other means
62
+ Buffer(const uint8_t* data, int64_t size)
63
+ : is_mutable_(false),
64
+ is_cpu_(true),
65
+ data_(data),
66
+ size_(size),
67
+ capacity_(size),
68
+ device_type_(DeviceAllocationType::kCPU) {
69
+ SetMemoryManager(default_cpu_memory_manager());
70
+ }
71
+
72
+ Buffer(const uint8_t* data, int64_t size, std::shared_ptr<MemoryManager> mm,
73
+ std::shared_ptr<Buffer> parent = NULLPTR,
74
+ std::optional<DeviceAllocationType> device_type_override = std::nullopt)
75
+ : is_mutable_(false),
76
+ data_(data),
77
+ size_(size),
78
+ capacity_(size),
79
+ parent_(std::move(parent)) {
80
+ // SetMemoryManager will also set device_type_
81
+ SetMemoryManager(std::move(mm));
82
+ // If a device type is specified, use that instead. Example of when this can be
83
+ // useful: the CudaMemoryManager can set device_type_ to kCUDA, but you can specify
84
+ // device_type_override=kCUDA_HOST as the device type to override it.
85
+ if (device_type_override != std::nullopt) {
86
+ device_type_ = *device_type_override;
87
+ }
88
+ }
89
+
90
+ Buffer(uintptr_t address, int64_t size, std::shared_ptr<MemoryManager> mm,
91
+ std::shared_ptr<Buffer> parent = NULLPTR)
92
+ : Buffer(reinterpret_cast<const uint8_t*>(address), size, std::move(mm),
93
+ std::move(parent)) {}
94
+
95
+ /// \brief Construct from string_view without copying memory
96
+ ///
97
+ /// \param[in] data a string_view object
98
+ ///
99
+ /// \note The memory viewed by data must not be deallocated in the lifetime of the
100
+ /// Buffer; temporary rvalue strings must be stored in an lvalue somewhere
101
+ explicit Buffer(std::string_view data)
102
+ : Buffer(reinterpret_cast<const uint8_t*>(data.data()),
103
+ static_cast<int64_t>(data.size())) {}
104
+
105
+ virtual ~Buffer() = default;
106
+
107
+ /// An offset into data that is owned by another buffer, but we want to be
108
+ /// able to retain a valid pointer to it even after other shared_ptr's to the
109
+ /// parent buffer have been destroyed
110
+ ///
111
+ /// This method makes no assertions about alignment or padding of the buffer but
112
+ /// in general we expected buffers to be aligned and padded to 64 bytes. In the future
113
+ /// we might add utility methods to help determine if a buffer satisfies this contract.
114
+ Buffer(const std::shared_ptr<Buffer>& parent, const int64_t offset, const int64_t size)
115
+ : Buffer(parent->data_ + offset, size) {
116
+ parent_ = parent;
117
+ SetMemoryManager(parent->memory_manager_);
118
+ }
119
+
120
+ uint8_t operator[](std::size_t i) const { return data_[i]; }
121
+
122
+ /// \brief Construct a new std::string with a hexadecimal representation of the buffer.
123
+ /// \return std::string
124
+ std::string ToHexString();
125
+
126
+ /// Return true if both buffers are the same size and contain the same bytes
127
+ /// up to the number of compared bytes
128
+ bool Equals(const Buffer& other, int64_t nbytes) const;
129
+
130
+ /// Return true if both buffers are the same size and contain the same bytes
131
+ bool Equals(const Buffer& other) const;
132
+
133
+ /// Copy a section of the buffer into a new Buffer.
134
+ Result<std::shared_ptr<Buffer>> CopySlice(
135
+ const int64_t start, const int64_t nbytes,
136
+ MemoryPool* pool = default_memory_pool()) const;
137
+
138
+ /// Zero bytes in padding, i.e. bytes between size_ and capacity_.
139
+ void ZeroPadding() {
140
+ #ifndef NDEBUG
141
+ CheckMutable();
142
+ #endif
143
+ // A zero-capacity buffer can have a null data pointer
144
+ if (capacity_ != 0) {
145
+ memset(mutable_data() + size_, 0, static_cast<size_t>(capacity_ - size_));
146
+ }
147
+ }
148
+
149
+ /// \brief Construct an immutable buffer that takes ownership of the contents
150
+ /// of an std::string (without copying it).
151
+ ///
152
+ /// \param[in] data a string to own
153
+ /// \return a new Buffer instance
154
+ static std::shared_ptr<Buffer> FromString(std::string data);
155
+
156
+ /// \brief Construct an immutable buffer that takes ownership of the contents
157
+ /// of an std::vector (without copying it). Only vectors of TrivialType objects
158
+ /// (integers, floating point numbers, ...) can be wrapped by this function.
159
+ ///
160
+ /// \param[in] vec a vector to own
161
+ /// \return a new Buffer instance
162
+ template <typename T>
163
+ static std::shared_ptr<Buffer> FromVector(std::vector<T> vec) {
164
+ static_assert(std::is_trivial_v<T>,
165
+ "Buffer::FromVector can only wrap vectors of trivial objects");
166
+
167
+ if (vec.empty()) {
168
+ return std::shared_ptr<Buffer>{new Buffer()};
169
+ }
170
+
171
+ auto* data = reinterpret_cast<uint8_t*>(vec.data());
172
+ auto size_in_bytes = static_cast<int64_t>(vec.size() * sizeof(T));
173
+ return std::shared_ptr<Buffer>{
174
+ new Buffer{data, size_in_bytes},
175
+ // Keep the vector's buffer alive inside the shared_ptr's destructor until after
176
+ // we have deleted the Buffer. Note we can't use this trick in FromString since
177
+ // std::string's data is inline for short strings so moving invalidates pointers
178
+ // into the string's buffer.
179
+ [vec = std::move(vec)](Buffer* buffer) { delete buffer; }};
180
+ }
181
+
182
+ /// \brief Create buffer referencing typed memory with some length without
183
+ /// copying
184
+ /// \param[in] data the typed memory as C array
185
+ /// \param[in] length the number of values in the array
186
+ /// \return a new shared_ptr<Buffer>
187
+ template <typename T, typename SizeType = int64_t>
188
+ static std::shared_ptr<Buffer> Wrap(const T* data, SizeType length) {
189
+ return std::make_shared<Buffer>(reinterpret_cast<const uint8_t*>(data),
190
+ static_cast<int64_t>(sizeof(T) * length));
191
+ }
192
+
193
+ /// \brief Create buffer referencing std::vector with some length without
194
+ /// copying
195
+ /// \param[in] data the vector to be referenced. If this vector is changed,
196
+ /// the buffer may become invalid
197
+ /// \return a new shared_ptr<Buffer>
198
+ template <typename T>
199
+ static std::shared_ptr<Buffer> Wrap(const std::vector<T>& data) {
200
+ return std::make_shared<Buffer>(reinterpret_cast<const uint8_t*>(data.data()),
201
+ static_cast<int64_t>(sizeof(T) * data.size()));
202
+ }
203
+
204
+ /// \brief Copy buffer contents into a new std::string
205
+ /// \return std::string
206
+ /// \note Can throw std::bad_alloc if buffer is large
207
+ std::string ToString() const;
208
+
209
+ /// \brief View buffer contents as a std::string_view
210
+ /// \return std::string_view
211
+ explicit operator std::string_view() const {
212
+ return {reinterpret_cast<const char*>(data_), static_cast<size_t>(size_)};
213
+ }
214
+
215
+ /// \brief Return a pointer to the buffer's data
216
+ ///
217
+ /// The buffer has to be a CPU buffer (`is_cpu()` is true).
218
+ /// Otherwise, an assertion may be thrown or a null pointer may be returned.
219
+ ///
220
+ /// To get the buffer's data address regardless of its device, call `address()`.
221
+ const uint8_t* data() const {
222
+ #ifndef NDEBUG
223
+ CheckCPU();
224
+ #endif
225
+ return ARROW_PREDICT_TRUE(is_cpu_) ? data_ : NULLPTR;
226
+ }
227
+
228
+ /// \brief Return a pointer to the buffer's data cast to a specific type
229
+ ///
230
+ /// The buffer has to be a CPU buffer (`is_cpu()` is true).
231
+ /// Otherwise, an assertion may be thrown or a null pointer may be returned.
232
+ template <typename T>
233
+ const T* data_as() const {
234
+ return reinterpret_cast<const T*>(data());
235
+ }
236
+
237
+ /// \brief Return the buffer's data as a span
238
+ template <typename T>
239
+ util::span<const T> span_as() const {
240
+ return util::span(data_as<T>(), static_cast<size_t>(size() / sizeof(T)));
241
+ }
242
+
243
+ /// \brief Return a writable pointer to the buffer's data
244
+ ///
245
+ /// The buffer has to be a mutable CPU buffer (`is_cpu()` and `is_mutable()`
246
+ /// are true). Otherwise, an assertion may be thrown or a null pointer may
247
+ /// be returned.
248
+ ///
249
+ /// To get the buffer's mutable data address regardless of its device, call
250
+ /// `mutable_address()`.
251
+ uint8_t* mutable_data() {
252
+ #ifndef NDEBUG
253
+ CheckCPU();
254
+ CheckMutable();
255
+ #endif
256
+ return ARROW_PREDICT_TRUE(is_cpu_ && is_mutable_) ? const_cast<uint8_t*>(data_)
257
+ : NULLPTR;
258
+ }
259
+
260
+ /// \brief Return a writable pointer to the buffer's data cast to a specific type
261
+ ///
262
+ /// The buffer has to be a mutable CPU buffer (`is_cpu()` and `is_mutable()`
263
+ /// are true). Otherwise, an assertion may be thrown or a null pointer may
264
+ /// be returned.
265
+ template <typename T>
266
+ T* mutable_data_as() {
267
+ return reinterpret_cast<T*>(mutable_data());
268
+ }
269
+
270
+ /// \brief Return the buffer's mutable data as a span
271
+ template <typename T>
272
+ util::span<T> mutable_span_as() {
273
+ return util::span(mutable_data_as<T>(), static_cast<size_t>(size() / sizeof(T)));
274
+ }
275
+
276
+ /// \brief Return the device address of the buffer's data
277
+ uintptr_t address() const { return reinterpret_cast<uintptr_t>(data_); }
278
+
279
+ /// \brief Return a writable device address to the buffer's data
280
+ ///
281
+ /// The buffer has to be a mutable buffer (`is_mutable()` is true).
282
+ /// Otherwise, an assertion may be thrown or 0 may be returned.
283
+ uintptr_t mutable_address() const {
284
+ #ifndef NDEBUG
285
+ CheckMutable();
286
+ #endif
287
+ return ARROW_PREDICT_TRUE(is_mutable_) ? reinterpret_cast<uintptr_t>(data_) : 0;
288
+ }
289
+
290
+ /// \brief Return the buffer's size in bytes
291
+ int64_t size() const { return size_; }
292
+
293
+ /// \brief Return the buffer's capacity (number of allocated bytes)
294
+ int64_t capacity() const { return capacity_; }
295
+
296
+ /// \brief Whether the buffer is directly CPU-accessible
297
+ ///
298
+ /// If this function returns true, you can read directly from the buffer's
299
+ /// `data()` pointer. Otherwise, you'll have to `View()` or `Copy()` it.
300
+ bool is_cpu() const { return is_cpu_; }
301
+
302
+ /// \brief Whether the buffer is mutable
303
+ ///
304
+ /// If this function returns true, you are allowed to modify buffer contents
305
+ /// using the pointer returned by `mutable_data()` or `mutable_address()`.
306
+ bool is_mutable() const { return is_mutable_; }
307
+
308
+ const std::shared_ptr<Device>& device() const { return memory_manager_->device(); }
309
+
310
+ const std::shared_ptr<MemoryManager>& memory_manager() const { return memory_manager_; }
311
+
312
+ DeviceAllocationType device_type() const { return device_type_; }
313
+
314
+ std::shared_ptr<Buffer> parent() const { return parent_; }
315
+
316
+ /// \brief Get a RandomAccessFile for reading a buffer
317
+ ///
318
+ /// The returned file object reads from this buffer's underlying memory.
319
+ static Result<std::shared_ptr<io::RandomAccessFile>> GetReader(std::shared_ptr<Buffer>);
320
+
321
+ /// \brief Get a OutputStream for writing to a buffer
322
+ ///
323
+ /// The buffer must be mutable. The returned stream object writes into the buffer's
324
+ /// underlying memory (but it won't resize it).
325
+ static Result<std::shared_ptr<io::OutputStream>> GetWriter(std::shared_ptr<Buffer>);
326
+
327
+ /// \brief Copy buffer
328
+ ///
329
+ /// The buffer contents will be copied into a new buffer allocated by the
330
+ /// given MemoryManager. This function supports cross-device copies.
331
+ static Result<std::shared_ptr<Buffer>> Copy(std::shared_ptr<Buffer> source,
332
+ const std::shared_ptr<MemoryManager>& to);
333
+
334
+ /// \brief Copy a non-owned buffer
335
+ ///
336
+ /// This is useful for cases where the source memory area is externally managed
337
+ /// (its lifetime not tied to the source Buffer), otherwise please use Copy().
338
+ static Result<std::unique_ptr<Buffer>> CopyNonOwned(
339
+ const Buffer& source, const std::shared_ptr<MemoryManager>& to);
340
+
341
+ /// \brief View buffer
342
+ ///
343
+ /// Return a Buffer that reflects this buffer, seen potentially from another
344
+ /// device, without making an explicit copy of the contents. The underlying
345
+ /// mechanism is typically implemented by the kernel or device driver, and may
346
+ /// involve lazy caching of parts of the buffer contents on the destination
347
+ /// device's memory.
348
+ ///
349
+ /// If a non-copy view is unsupported for the buffer on the given device,
350
+ /// nullptr is returned. An error can be returned if some low-level
351
+ /// operation fails (such as an out-of-memory condition).
352
+ static Result<std::shared_ptr<Buffer>> View(std::shared_ptr<Buffer> source,
353
+ const std::shared_ptr<MemoryManager>& to);
354
+
355
+ /// \brief View or copy buffer
356
+ ///
357
+ /// Try to view buffer contents on the given MemoryManager's device, but
358
+ /// fall back to copying if a no-copy view isn't supported.
359
+ static Result<std::shared_ptr<Buffer>> ViewOrCopy(
360
+ std::shared_ptr<Buffer> source, const std::shared_ptr<MemoryManager>& to);
361
+
362
+ virtual std::shared_ptr<Device::SyncEvent> device_sync_event() const { return NULLPTR; }
363
+
364
+ protected:
365
+ bool is_mutable_;
366
+ bool is_cpu_;
367
+ const uint8_t* data_;
368
+ int64_t size_;
369
+ int64_t capacity_;
370
+ DeviceAllocationType device_type_;
371
+
372
+ // null by default, but may be set
373
+ std::shared_ptr<Buffer> parent_;
374
+
375
+ private:
376
+ // private so that subclasses are forced to call SetMemoryManager()
377
+ std::shared_ptr<MemoryManager> memory_manager_;
378
+
379
+ protected:
380
+ Buffer();
381
+
382
+ void CheckMutable() const;
383
+ void CheckCPU() const;
384
+
385
+ void SetMemoryManager(std::shared_ptr<MemoryManager> mm) {
386
+ memory_manager_ = std::move(mm);
387
+ is_cpu_ = memory_manager_->is_cpu();
388
+ device_type_ = memory_manager_->device()->device_type();
389
+ }
390
+ };
391
+
392
+ /// \defgroup buffer-slicing-functions Functions for slicing buffers
393
+ ///
394
+ /// @{
395
+
396
+ /// \brief Construct a view on a buffer at the given offset and length.
397
+ ///
398
+ /// This function cannot fail and does not check for errors (except in debug builds)
399
+ static inline std::shared_ptr<Buffer> SliceBuffer(const std::shared_ptr<Buffer>& buffer,
400
+ const int64_t offset,
401
+ const int64_t length) {
402
+ return std::make_shared<Buffer>(buffer, offset, length);
403
+ }
404
+
405
+ /// \brief Construct a view on a buffer at the given offset, up to the buffer's end.
406
+ ///
407
+ /// This function cannot fail and does not check for errors (except in debug builds)
408
+ static inline std::shared_ptr<Buffer> SliceBuffer(const std::shared_ptr<Buffer>& buffer,
409
+ const int64_t offset) {
410
+ int64_t length = buffer->size() - offset;
411
+ return SliceBuffer(buffer, offset, length);
412
+ }
413
+
414
+ /// \brief Input-checking version of SliceBuffer
415
+ ///
416
+ /// An Invalid Status is returned if the requested slice falls out of bounds.
417
+ ARROW_EXPORT
418
+ Result<std::shared_ptr<Buffer>> SliceBufferSafe(const std::shared_ptr<Buffer>& buffer,
419
+ int64_t offset);
420
+ /// \brief Input-checking version of SliceBuffer
421
+ ///
422
+ /// An Invalid Status is returned if the requested slice falls out of bounds.
423
+ /// Note that unlike SliceBuffer, `length` isn't clamped to the available buffer size.
424
+ ARROW_EXPORT
425
+ Result<std::shared_ptr<Buffer>> SliceBufferSafe(const std::shared_ptr<Buffer>& buffer,
426
+ int64_t offset, int64_t length);
427
+
428
+ /// \brief Like SliceBuffer, but construct a mutable buffer slice.
429
+ ///
430
+ /// If the parent buffer is not mutable, behavior is undefined (it may abort
431
+ /// in debug builds).
432
+ ARROW_EXPORT
433
+ std::shared_ptr<Buffer> SliceMutableBuffer(const std::shared_ptr<Buffer>& buffer,
434
+ const int64_t offset, const int64_t length);
435
+
436
+ /// \brief Like SliceBuffer, but construct a mutable buffer slice.
437
+ ///
438
+ /// If the parent buffer is not mutable, behavior is undefined (it may abort
439
+ /// in debug builds).
440
+ static inline std::shared_ptr<Buffer> SliceMutableBuffer(
441
+ const std::shared_ptr<Buffer>& buffer, const int64_t offset) {
442
+ int64_t length = buffer->size() - offset;
443
+ return SliceMutableBuffer(buffer, offset, length);
444
+ }
445
+
446
+ /// \brief Input-checking version of SliceMutableBuffer
447
+ ///
448
+ /// An Invalid Status is returned if the requested slice falls out of bounds.
449
+ ARROW_EXPORT
450
+ Result<std::shared_ptr<Buffer>> SliceMutableBufferSafe(
451
+ const std::shared_ptr<Buffer>& buffer, int64_t offset);
452
+ /// \brief Input-checking version of SliceMutableBuffer
453
+ ///
454
+ /// An Invalid Status is returned if the requested slice falls out of bounds.
455
+ /// Note that unlike SliceBuffer, `length` isn't clamped to the available buffer size.
456
+ ARROW_EXPORT
457
+ Result<std::shared_ptr<Buffer>> SliceMutableBufferSafe(
458
+ const std::shared_ptr<Buffer>& buffer, int64_t offset, int64_t length);
459
+
460
+ /// @}
461
+
462
+ /// \class MutableBuffer
463
+ /// \brief A Buffer whose contents can be mutated. May or may not own its data.
464
+ class ARROW_EXPORT MutableBuffer : public Buffer {
465
+ public:
466
+ MutableBuffer(uint8_t* data, const int64_t size) : Buffer(data, size) {
467
+ is_mutable_ = true;
468
+ }
469
+
470
+ MutableBuffer(uint8_t* data, const int64_t size, std::shared_ptr<MemoryManager> mm)
471
+ : Buffer(data, size, std::move(mm)) {
472
+ is_mutable_ = true;
473
+ }
474
+
475
+ MutableBuffer(const std::shared_ptr<Buffer>& parent, const int64_t offset,
476
+ const int64_t size);
477
+
478
+ /// \brief Create buffer referencing typed memory with some length
479
+ /// \param[in] data the typed memory as C array
480
+ /// \param[in] length the number of values in the array
481
+ /// \return a new shared_ptr<Buffer>
482
+ template <typename T, typename SizeType = int64_t>
483
+ static std::shared_ptr<Buffer> Wrap(T* data, SizeType length) {
484
+ return std::make_shared<MutableBuffer>(reinterpret_cast<uint8_t*>(data),
485
+ static_cast<int64_t>(sizeof(T) * length));
486
+ }
487
+
488
+ protected:
489
+ MutableBuffer() : Buffer(NULLPTR, 0) {}
490
+ };
491
+
492
+ /// \class ResizableBuffer
493
+ /// \brief A mutable buffer that can be resized
494
+ class ARROW_EXPORT ResizableBuffer : public MutableBuffer {
495
+ public:
496
+ /// Change buffer reported size to indicated size, allocating memory if
497
+ /// necessary. This will ensure that the capacity of the buffer is a multiple
498
+ /// of 64 bytes as defined in Layout.md.
499
+ /// Consider using ZeroPadding afterwards, to conform to the Arrow layout
500
+ /// specification.
501
+ ///
502
+ /// @param new_size The new size for the buffer.
503
+ /// @param shrink_to_fit Whether to shrink the capacity if new size < current size
504
+ virtual Status Resize(const int64_t new_size, bool shrink_to_fit) = 0;
505
+ Status Resize(const int64_t new_size) {
506
+ return Resize(new_size, /*shrink_to_fit=*/true);
507
+ }
508
+
509
+ /// Ensure that buffer has enough memory allocated to fit the indicated
510
+ /// capacity (and meets the 64 byte padding requirement in Layout.md).
511
+ /// It does not change buffer's reported size and doesn't zero the padding.
512
+ virtual Status Reserve(const int64_t new_capacity) = 0;
513
+
514
+ template <class T>
515
+ Status TypedResize(const int64_t new_nb_elements, bool shrink_to_fit = true) {
516
+ return Resize(sizeof(T) * new_nb_elements, shrink_to_fit);
517
+ }
518
+
519
+ template <class T>
520
+ Status TypedReserve(const int64_t new_nb_elements) {
521
+ return Reserve(sizeof(T) * new_nb_elements);
522
+ }
523
+
524
+ protected:
525
+ ResizableBuffer(uint8_t* data, int64_t size) : MutableBuffer(data, size) {}
526
+ ResizableBuffer(uint8_t* data, int64_t size, std::shared_ptr<MemoryManager> mm)
527
+ : MutableBuffer(data, size, std::move(mm)) {}
528
+ };
529
+
530
+ /// \defgroup buffer-allocation-functions Functions for allocating buffers
531
+ ///
532
+ /// @{
533
+
534
+ /// \brief Allocate a fixed size mutable buffer from a memory pool, zero its padding.
535
+ ///
536
+ /// \param[in] size size of buffer to allocate
537
+ /// \param[in] pool a memory pool
538
+ ARROW_EXPORT
539
+ Result<std::unique_ptr<Buffer>> AllocateBuffer(const int64_t size,
540
+ MemoryPool* pool = NULLPTR);
541
+ ARROW_EXPORT
542
+ Result<std::unique_ptr<Buffer>> AllocateBuffer(const int64_t size, int64_t alignment,
543
+ MemoryPool* pool = NULLPTR);
544
+
545
+ /// \brief Allocate a resizeable buffer from a memory pool, zero its padding.
546
+ ///
547
+ /// \param[in] size size of buffer to allocate
548
+ /// \param[in] pool a memory pool
549
+ ARROW_EXPORT
550
+ Result<std::unique_ptr<ResizableBuffer>> AllocateResizableBuffer(
551
+ const int64_t size, MemoryPool* pool = NULLPTR);
552
+ ARROW_EXPORT
553
+ Result<std::unique_ptr<ResizableBuffer>> AllocateResizableBuffer(
554
+ const int64_t size, const int64_t alignment, MemoryPool* pool = NULLPTR);
555
+
556
+ /// \brief Allocate a bitmap buffer from a memory pool
557
+ /// no guarantee on values is provided.
558
+ ///
559
+ /// \param[in] length size in bits of bitmap to allocate
560
+ /// \param[in] pool memory pool to allocate memory from
561
+ ARROW_EXPORT
562
+ Result<std::shared_ptr<Buffer>> AllocateBitmap(int64_t length,
563
+ MemoryPool* pool = NULLPTR);
564
+
565
+ /// \brief Allocate a zero-initialized bitmap buffer from a memory pool
566
+ ///
567
+ /// \param[in] length size in bits of bitmap to allocate
568
+ /// \param[in] pool memory pool to allocate memory from
569
+ ARROW_EXPORT
570
+ Result<std::shared_ptr<Buffer>> AllocateEmptyBitmap(int64_t length,
571
+ MemoryPool* pool = NULLPTR);
572
+
573
+ ARROW_EXPORT
574
+ Result<std::shared_ptr<Buffer>> AllocateEmptyBitmap(int64_t length, int64_t alignment,
575
+ MemoryPool* pool = NULLPTR);
576
+
577
+ /// \brief Concatenate multiple buffers into a single buffer
578
+ ///
579
+ /// \param[in] buffers to be concatenated
580
+ /// \param[in] pool memory pool to allocate the new buffer from
581
+ ARROW_EXPORT
582
+ Result<std::shared_ptr<Buffer>> ConcatenateBuffers(const BufferVector& buffers,
583
+ MemoryPool* pool = NULLPTR);
584
+
585
+ /// @}
586
+
587
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/buffer_builder.h ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <algorithm>
21
+ #include <cstdint>
22
+ #include <cstring>
23
+ #include <memory>
24
+ #include <string>
25
+ #include <utility>
26
+
27
+ #include "arrow/buffer.h"
28
+ #include "arrow/status.h"
29
+ #include "arrow/util/bit_util.h"
30
+ #include "arrow/util/bitmap_generate.h"
31
+ #include "arrow/util/bitmap_ops.h"
32
+ #include "arrow/util/macros.h"
33
+ #include "arrow/util/ubsan.h"
34
+ #include "arrow/util/visibility.h"
35
+
36
+ namespace arrow {
37
+
38
+ // ----------------------------------------------------------------------
39
+ // Buffer builder classes
40
+
41
+ /// \class BufferBuilder
42
+ /// \brief A class for incrementally building a contiguous chunk of in-memory
43
+ /// data
44
+ class ARROW_EXPORT BufferBuilder {
45
+ public:
46
+ explicit BufferBuilder(MemoryPool* pool = default_memory_pool(),
47
+ int64_t alignment = kDefaultBufferAlignment)
48
+ : pool_(pool),
49
+ data_(/*ensure never null to make ubsan happy and avoid check penalties below*/
50
+ util::MakeNonNull<uint8_t>()),
51
+ capacity_(0),
52
+ size_(0),
53
+ alignment_(alignment) {}
54
+
55
+ /// \brief Constructs new Builder that will start using
56
+ /// the provided buffer until Finish/Reset are called.
57
+ /// The buffer is not resized.
58
+ explicit BufferBuilder(std::shared_ptr<ResizableBuffer> buffer,
59
+ MemoryPool* pool = default_memory_pool(),
60
+ int64_t alignment = kDefaultBufferAlignment)
61
+ : buffer_(std::move(buffer)),
62
+ pool_(pool),
63
+ data_(buffer_->mutable_data()),
64
+ capacity_(buffer_->capacity()),
65
+ size_(buffer_->size()),
66
+ alignment_(alignment) {}
67
+
68
+ /// \brief Resize the buffer to the nearest multiple of 64 bytes
69
+ ///
70
+ /// \param new_capacity the new capacity of the of the builder. Will be
71
+ /// rounded up to a multiple of 64 bytes for padding
72
+ /// \param shrink_to_fit if new capacity is smaller than the existing,
73
+ /// reallocate internal buffer. Set to false to avoid reallocations when
74
+ /// shrinking the builder.
75
+ /// \return Status
76
+ Status Resize(const int64_t new_capacity, bool shrink_to_fit = true) {
77
+ if (buffer_ == NULLPTR) {
78
+ ARROW_ASSIGN_OR_RAISE(buffer_,
79
+ AllocateResizableBuffer(new_capacity, alignment_, pool_));
80
+ } else {
81
+ ARROW_RETURN_NOT_OK(buffer_->Resize(new_capacity, shrink_to_fit));
82
+ }
83
+ capacity_ = buffer_->capacity();
84
+ data_ = buffer_->mutable_data();
85
+ return Status::OK();
86
+ }
87
+
88
+ /// \brief Ensure that builder can accommodate the additional number of bytes
89
+ /// without the need to perform allocations
90
+ ///
91
+ /// \param[in] additional_bytes number of additional bytes to make space for
92
+ /// \return Status
93
+ Status Reserve(const int64_t additional_bytes) {
94
+ auto min_capacity = size_ + additional_bytes;
95
+ if (min_capacity <= capacity_) {
96
+ return Status::OK();
97
+ }
98
+ return Resize(GrowByFactor(capacity_, min_capacity), false);
99
+ }
100
+
101
+ /// \brief Return a capacity expanded by the desired growth factor
102
+ static int64_t GrowByFactor(int64_t current_capacity, int64_t new_capacity) {
103
+ // Doubling capacity except for large Reserve requests. 2x growth strategy
104
+ // (versus 1.5x) seems to have slightly better performance when using
105
+ // jemalloc, but significantly better performance when using the system
106
+ // allocator. See ARROW-6450 for further discussion
107
+ return std::max(new_capacity, current_capacity * 2);
108
+ }
109
+
110
+ /// \brief Append the given data to the buffer
111
+ ///
112
+ /// The buffer is automatically expanded if necessary.
113
+ Status Append(const void* data, const int64_t length) {
114
+ if (ARROW_PREDICT_FALSE(size_ + length > capacity_)) {
115
+ ARROW_RETURN_NOT_OK(Resize(GrowByFactor(capacity_, size_ + length), false));
116
+ }
117
+ UnsafeAppend(data, length);
118
+ return Status::OK();
119
+ }
120
+
121
+ /// \brief Append the given data to the buffer
122
+ ///
123
+ /// The buffer is automatically expanded if necessary.
124
+ Status Append(std::string_view v) { return Append(v.data(), v.size()); }
125
+
126
+ /// \brief Append copies of a value to the buffer
127
+ ///
128
+ /// The buffer is automatically expanded if necessary.
129
+ Status Append(const int64_t num_copies, uint8_t value) {
130
+ ARROW_RETURN_NOT_OK(Reserve(num_copies));
131
+ UnsafeAppend(num_copies, value);
132
+ return Status::OK();
133
+ }
134
+
135
+ // Advance pointer and zero out memory
136
+ Status Advance(const int64_t length) { return Append(length, 0); }
137
+
138
+ // Advance pointer, but don't allocate or zero memory
139
+ void UnsafeAdvance(const int64_t length) { size_ += length; }
140
+
141
+ // Unsafe methods don't check existing size
142
+ void UnsafeAppend(const void* data, const int64_t length) {
143
+ memcpy(data_ + size_, data, static_cast<size_t>(length));
144
+ size_ += length;
145
+ }
146
+
147
+ void UnsafeAppend(std::string_view v) {
148
+ UnsafeAppend(v.data(), static_cast<int64_t>(v.size()));
149
+ }
150
+
151
+ void UnsafeAppend(const int64_t num_copies, uint8_t value) {
152
+ memset(data_ + size_, value, static_cast<size_t>(num_copies));
153
+ size_ += num_copies;
154
+ }
155
+
156
+ /// \brief Return result of builder as a Buffer object.
157
+ ///
158
+ /// The builder is reset and can be reused afterwards.
159
+ ///
160
+ /// \param[out] out the finalized Buffer object
161
+ /// \param shrink_to_fit if the buffer size is smaller than its capacity,
162
+ /// reallocate to fit more tightly in memory. Set to false to avoid
163
+ /// a reallocation, at the expense of potentially more memory consumption.
164
+ /// \return Status
165
+ Status Finish(std::shared_ptr<Buffer>* out, bool shrink_to_fit = true) {
166
+ ARROW_RETURN_NOT_OK(Resize(size_, shrink_to_fit));
167
+ if (size_ != 0) buffer_->ZeroPadding();
168
+ *out = buffer_;
169
+ if (*out == NULLPTR) {
170
+ ARROW_ASSIGN_OR_RAISE(*out, AllocateBuffer(0, alignment_, pool_));
171
+ }
172
+ Reset();
173
+ return Status::OK();
174
+ }
175
+
176
+ Result<std::shared_ptr<Buffer>> Finish(bool shrink_to_fit = true) {
177
+ std::shared_ptr<Buffer> out;
178
+ ARROW_RETURN_NOT_OK(Finish(&out, shrink_to_fit));
179
+ return out;
180
+ }
181
+
182
+ /// \brief Like Finish, but override the final buffer size
183
+ ///
184
+ /// This is useful after writing data directly into the builder memory
185
+ /// without calling the Append methods (basically, when using BufferBuilder
186
+ /// mostly for memory allocation).
187
+ Result<std::shared_ptr<Buffer>> FinishWithLength(int64_t final_length,
188
+ bool shrink_to_fit = true) {
189
+ size_ = final_length;
190
+ return Finish(shrink_to_fit);
191
+ }
192
+
193
+ void Reset() {
194
+ buffer_ = NULLPTR;
195
+ capacity_ = size_ = 0;
196
+ }
197
+
198
+ /// \brief Set size to a smaller value without modifying builder
199
+ /// contents. For reusable BufferBuilder classes
200
+ /// \param[in] position must be non-negative and less than or equal
201
+ /// to the current length()
202
+ void Rewind(int64_t position) { size_ = position; }
203
+
204
+ int64_t capacity() const { return capacity_; }
205
+ int64_t length() const { return size_; }
206
+ const uint8_t* data() const { return data_; }
207
+ uint8_t* mutable_data() { return data_; }
208
+ template <typename T>
209
+ const T* data_as() const {
210
+ return reinterpret_cast<const T*>(data_);
211
+ }
212
+ template <typename T>
213
+ T* mutable_data_as() {
214
+ return reinterpret_cast<T*>(data_);
215
+ }
216
+
217
+ private:
218
+ std::shared_ptr<ResizableBuffer> buffer_;
219
+ MemoryPool* pool_;
220
+ uint8_t* data_;
221
+ int64_t capacity_;
222
+ int64_t size_;
223
+ int64_t alignment_;
224
+ };
225
+
226
+ template <typename T, typename Enable = void>
227
+ class TypedBufferBuilder;
228
+
229
+ /// \brief A BufferBuilder for building a buffer of arithmetic elements
230
+ template <typename T>
231
+ class TypedBufferBuilder<
232
+ T, typename std::enable_if<std::is_arithmetic<T>::value ||
233
+ std::is_standard_layout<T>::value>::type> {
234
+ public:
235
+ explicit TypedBufferBuilder(MemoryPool* pool = default_memory_pool(),
236
+ int64_t alignment = kDefaultBufferAlignment)
237
+ : bytes_builder_(pool, alignment) {}
238
+
239
+ explicit TypedBufferBuilder(std::shared_ptr<ResizableBuffer> buffer,
240
+ MemoryPool* pool = default_memory_pool())
241
+ : bytes_builder_(std::move(buffer), pool) {}
242
+
243
+ explicit TypedBufferBuilder(BufferBuilder builder)
244
+ : bytes_builder_(std::move(builder)) {}
245
+
246
+ BufferBuilder* bytes_builder() { return &bytes_builder_; }
247
+
248
+ Status Append(T value) {
249
+ return bytes_builder_.Append(reinterpret_cast<uint8_t*>(&value), sizeof(T));
250
+ }
251
+
252
+ Status Append(const T* values, int64_t num_elements) {
253
+ return bytes_builder_.Append(reinterpret_cast<const uint8_t*>(values),
254
+ num_elements * sizeof(T));
255
+ }
256
+
257
+ Status Append(const int64_t num_copies, T value) {
258
+ ARROW_RETURN_NOT_OK(Reserve(num_copies + length()));
259
+ UnsafeAppend(num_copies, value);
260
+ return Status::OK();
261
+ }
262
+
263
+ void UnsafeAppend(T value) {
264
+ bytes_builder_.UnsafeAppend(reinterpret_cast<uint8_t*>(&value), sizeof(T));
265
+ }
266
+
267
+ void UnsafeAppend(const T* values, int64_t num_elements) {
268
+ bytes_builder_.UnsafeAppend(reinterpret_cast<const uint8_t*>(values),
269
+ num_elements * sizeof(T));
270
+ }
271
+
272
+ template <typename Iter>
273
+ void UnsafeAppend(Iter values_begin, Iter values_end) {
274
+ auto num_elements = static_cast<int64_t>(std::distance(values_begin, values_end));
275
+ auto data = mutable_data() + length();
276
+ bytes_builder_.UnsafeAdvance(num_elements * sizeof(T));
277
+ std::copy(values_begin, values_end, data);
278
+ }
279
+
280
+ void UnsafeAppend(const int64_t num_copies, T value) {
281
+ auto data = mutable_data() + length();
282
+ bytes_builder_.UnsafeAdvance(num_copies * sizeof(T));
283
+ std::fill(data, data + num_copies, value);
284
+ }
285
+
286
+ Status Resize(const int64_t new_capacity, bool shrink_to_fit = true) {
287
+ return bytes_builder_.Resize(new_capacity * sizeof(T), shrink_to_fit);
288
+ }
289
+
290
+ Status Reserve(const int64_t additional_elements) {
291
+ return bytes_builder_.Reserve(additional_elements * sizeof(T));
292
+ }
293
+
294
+ Status Advance(const int64_t length) {
295
+ return bytes_builder_.Advance(length * sizeof(T));
296
+ }
297
+
298
+ Status Finish(std::shared_ptr<Buffer>* out, bool shrink_to_fit = true) {
299
+ return bytes_builder_.Finish(out, shrink_to_fit);
300
+ }
301
+
302
+ Result<std::shared_ptr<Buffer>> Finish(bool shrink_to_fit = true) {
303
+ std::shared_ptr<Buffer> out;
304
+ ARROW_RETURN_NOT_OK(Finish(&out, shrink_to_fit));
305
+ return out;
306
+ }
307
+
308
+ /// \brief Like Finish, but override the final buffer size
309
+ ///
310
+ /// This is useful after writing data directly into the builder memory
311
+ /// without calling the Append methods (basically, when using TypedBufferBuilder
312
+ /// only for memory allocation).
313
+ Result<std::shared_ptr<Buffer>> FinishWithLength(int64_t final_length,
314
+ bool shrink_to_fit = true) {
315
+ return bytes_builder_.FinishWithLength(final_length * sizeof(T), shrink_to_fit);
316
+ }
317
+
318
+ void Reset() { bytes_builder_.Reset(); }
319
+
320
+ int64_t length() const { return bytes_builder_.length() / sizeof(T); }
321
+ int64_t capacity() const { return bytes_builder_.capacity() / sizeof(T); }
322
+ const T* data() const { return reinterpret_cast<const T*>(bytes_builder_.data()); }
323
+ T* mutable_data() { return reinterpret_cast<T*>(bytes_builder_.mutable_data()); }
324
+
325
+ private:
326
+ BufferBuilder bytes_builder_;
327
+ };
328
+
329
+ /// \brief A BufferBuilder for building a buffer containing a bitmap
330
+ template <>
331
+ class TypedBufferBuilder<bool> {
332
+ public:
333
+ explicit TypedBufferBuilder(MemoryPool* pool = default_memory_pool(),
334
+ int64_t alignment = kDefaultBufferAlignment)
335
+ : bytes_builder_(pool, alignment) {}
336
+
337
+ explicit TypedBufferBuilder(BufferBuilder builder)
338
+ : bytes_builder_(std::move(builder)) {}
339
+
340
+ BufferBuilder* bytes_builder() { return &bytes_builder_; }
341
+
342
+ Status Append(bool value) {
343
+ ARROW_RETURN_NOT_OK(Reserve(1));
344
+ UnsafeAppend(value);
345
+ return Status::OK();
346
+ }
347
+
348
+ Status Append(const uint8_t* valid_bytes, int64_t num_elements) {
349
+ ARROW_RETURN_NOT_OK(Reserve(num_elements));
350
+ UnsafeAppend(valid_bytes, num_elements);
351
+ return Status::OK();
352
+ }
353
+
354
+ Status Append(const int64_t num_copies, bool value) {
355
+ ARROW_RETURN_NOT_OK(Reserve(num_copies));
356
+ UnsafeAppend(num_copies, value);
357
+ return Status::OK();
358
+ }
359
+
360
+ void UnsafeAppend(bool value) {
361
+ bit_util::SetBitTo(mutable_data(), bit_length_, value);
362
+ if (!value) {
363
+ ++false_count_;
364
+ }
365
+ ++bit_length_;
366
+ }
367
+
368
+ /// \brief Append bits from an array of bytes (one value per byte)
369
+ void UnsafeAppend(const uint8_t* bytes, int64_t num_elements) {
370
+ if (num_elements == 0) return;
371
+ int64_t i = 0;
372
+ internal::GenerateBitsUnrolled(mutable_data(), bit_length_, num_elements, [&] {
373
+ bool value = bytes[i++];
374
+ false_count_ += !value;
375
+ return value;
376
+ });
377
+ bit_length_ += num_elements;
378
+ }
379
+
380
+ /// \brief Append bits from a packed bitmap
381
+ void UnsafeAppend(const uint8_t* bitmap, int64_t offset, int64_t num_elements) {
382
+ if (num_elements == 0) return;
383
+ internal::CopyBitmap(bitmap, offset, num_elements, mutable_data(), bit_length_);
384
+ false_count_ += num_elements - internal::CountSetBits(bitmap, offset, num_elements);
385
+ bit_length_ += num_elements;
386
+ }
387
+
388
+ void UnsafeAppend(const int64_t num_copies, bool value) {
389
+ bit_util::SetBitsTo(mutable_data(), bit_length_, num_copies, value);
390
+ false_count_ += num_copies * !value;
391
+ bit_length_ += num_copies;
392
+ }
393
+
394
+ template <bool count_falses, typename Generator>
395
+ void UnsafeAppend(const int64_t num_elements, Generator&& gen) {
396
+ if (num_elements == 0) return;
397
+
398
+ if (count_falses) {
399
+ internal::GenerateBitsUnrolled(mutable_data(), bit_length_, num_elements, [&] {
400
+ bool value = gen();
401
+ false_count_ += !value;
402
+ return value;
403
+ });
404
+ } else {
405
+ internal::GenerateBitsUnrolled(mutable_data(), bit_length_, num_elements,
406
+ std::forward<Generator>(gen));
407
+ }
408
+ bit_length_ += num_elements;
409
+ }
410
+
411
+ Status Resize(const int64_t new_capacity, bool shrink_to_fit = true) {
412
+ const int64_t old_byte_capacity = bytes_builder_.capacity();
413
+ ARROW_RETURN_NOT_OK(
414
+ bytes_builder_.Resize(bit_util::BytesForBits(new_capacity), shrink_to_fit));
415
+ // Resize() may have chosen a larger capacity (e.g. for padding),
416
+ // so ask it again before calling memset().
417
+ const int64_t new_byte_capacity = bytes_builder_.capacity();
418
+ if (new_byte_capacity > old_byte_capacity) {
419
+ // The additional buffer space is 0-initialized for convenience,
420
+ // so that other methods can simply bump the length.
421
+ memset(mutable_data() + old_byte_capacity, 0,
422
+ static_cast<size_t>(new_byte_capacity - old_byte_capacity));
423
+ }
424
+ return Status::OK();
425
+ }
426
+
427
+ Status Reserve(const int64_t additional_elements) {
428
+ return Resize(
429
+ BufferBuilder::GrowByFactor(bit_length_, bit_length_ + additional_elements),
430
+ false);
431
+ }
432
+
433
+ Status Advance(const int64_t length) {
434
+ ARROW_RETURN_NOT_OK(Reserve(length));
435
+ bit_length_ += length;
436
+ false_count_ += length;
437
+ return Status::OK();
438
+ }
439
+
440
+ Status Finish(std::shared_ptr<Buffer>* out, bool shrink_to_fit = true) {
441
+ // set bytes_builder_.size_ == byte size of data
442
+ bytes_builder_.UnsafeAdvance(bit_util::BytesForBits(bit_length_) -
443
+ bytes_builder_.length());
444
+ bit_length_ = false_count_ = 0;
445
+ return bytes_builder_.Finish(out, shrink_to_fit);
446
+ }
447
+
448
+ Result<std::shared_ptr<Buffer>> Finish(bool shrink_to_fit = true) {
449
+ std::shared_ptr<Buffer> out;
450
+ ARROW_RETURN_NOT_OK(Finish(&out, shrink_to_fit));
451
+ return out;
452
+ }
453
+
454
+ /// \brief Like Finish, but override the final buffer size
455
+ ///
456
+ /// This is useful after writing data directly into the builder memory
457
+ /// without calling the Append methods (basically, when using TypedBufferBuilder
458
+ /// only for memory allocation).
459
+ Result<std::shared_ptr<Buffer>> FinishWithLength(int64_t final_length,
460
+ bool shrink_to_fit = true) {
461
+ const auto final_byte_length = bit_util::BytesForBits(final_length);
462
+ bytes_builder_.UnsafeAdvance(final_byte_length - bytes_builder_.length());
463
+ bit_length_ = false_count_ = 0;
464
+ return bytes_builder_.FinishWithLength(final_byte_length, shrink_to_fit);
465
+ }
466
+
467
+ void Reset() {
468
+ bytes_builder_.Reset();
469
+ bit_length_ = false_count_ = 0;
470
+ }
471
+
472
+ int64_t length() const { return bit_length_; }
473
+ int64_t capacity() const { return bytes_builder_.capacity() * 8; }
474
+ const uint8_t* data() const { return bytes_builder_.data(); }
475
+ uint8_t* mutable_data() { return bytes_builder_.mutable_data(); }
476
+ int64_t false_count() const { return false_count_; }
477
+
478
+ private:
479
+ BufferBuilder bytes_builder_;
480
+ int64_t bit_length_ = 0;
481
+ int64_t false_count_ = 0;
482
+ };
483
+
484
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/chunk_resolver.h ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <atomic>
21
+ #include <cassert>
22
+ #include <cstdint>
23
+ #include <limits>
24
+ #include <type_traits>
25
+ #include <vector>
26
+
27
+ #include "arrow/type_fwd.h"
28
+ #include "arrow/util/macros.h"
29
+
30
+ namespace arrow {
31
+
32
+ class ChunkResolver;
33
+
34
+ template <typename IndexType>
35
+ struct ARROW_EXPORT TypedChunkLocation {
36
+ /// \brief Index of the chunk in the array of chunks
37
+ ///
38
+ /// The value is always in the range `[0, chunks.size()]`. `chunks.size()` is used
39
+ /// to represent out-of-bounds locations.
40
+ IndexType chunk_index = 0;
41
+
42
+ /// \brief Index of the value in the chunk
43
+ ///
44
+ /// The value is UNDEFINED if `chunk_index >= chunks.size()`
45
+ IndexType index_in_chunk = 0;
46
+
47
+ TypedChunkLocation() = default;
48
+
49
+ TypedChunkLocation(IndexType chunk_index, IndexType index_in_chunk)
50
+ : chunk_index(chunk_index), index_in_chunk(index_in_chunk) {
51
+ static_assert(sizeof(TypedChunkLocation<IndexType>) == 2 * sizeof(IndexType));
52
+ static_assert(alignof(TypedChunkLocation<IndexType>) == alignof(IndexType));
53
+ }
54
+
55
+ bool operator==(TypedChunkLocation other) const {
56
+ return chunk_index == other.chunk_index && index_in_chunk == other.index_in_chunk;
57
+ }
58
+ };
59
+
60
+ using ChunkLocation = TypedChunkLocation<int64_t>;
61
+
62
+ /// \brief An utility that incrementally resolves logical indices into
63
+ /// physical indices in a chunked array.
64
+ class ARROW_EXPORT ChunkResolver {
65
+ private:
66
+ /// \brief Array containing `chunks.size() + 1` offsets.
67
+ ///
68
+ /// `offsets_[i]` is the starting logical index of chunk `i`. `offsets_[0]` is always 0
69
+ /// and `offsets_[chunks.size()]` is the logical length of the chunked array.
70
+ std::vector<int64_t> offsets_;
71
+
72
+ /// \brief Cache of the index of the last resolved chunk.
73
+ ///
74
+ /// \invariant `cached_chunk_ in [0, chunks.size()]`
75
+ mutable std::atomic<int32_t> cached_chunk_;
76
+
77
+ public:
78
+ explicit ChunkResolver(const ArrayVector& chunks) noexcept;
79
+
80
+ explicit ChunkResolver(const std::vector<const Array*>& chunks) noexcept;
81
+
82
+ explicit ChunkResolver(const RecordBatchVector& batches) noexcept;
83
+
84
+ explicit ChunkResolver(std::vector<int64_t> offsets) noexcept
85
+ : offsets_(std::move(offsets)), cached_chunk_(0) {
86
+ #ifndef NDEBUG
87
+ assert(offsets_.size() >= 1);
88
+ assert(offsets_[0] == 0);
89
+ for (size_t i = 1; i < offsets_.size(); i++) {
90
+ assert(offsets_[i] >= offsets_[i - 1]);
91
+ }
92
+ assert(offsets_.size() - 1 <=
93
+ static_cast<size_t>(std::numeric_limits<int32_t>::max()));
94
+ #endif
95
+ }
96
+
97
+ ChunkResolver(ChunkResolver&& other) noexcept;
98
+ ChunkResolver& operator=(ChunkResolver&& other) noexcept;
99
+
100
+ ChunkResolver(const ChunkResolver& other) noexcept;
101
+ ChunkResolver& operator=(const ChunkResolver& other) noexcept;
102
+
103
+ int64_t logical_array_length() const { return offsets_.back(); }
104
+ int32_t num_chunks() const { return static_cast<int32_t>(offsets_.size() - 1); }
105
+
106
+ int64_t chunk_length(int64_t chunk_index) const {
107
+ return offsets_[chunk_index + 1] - offsets_[chunk_index];
108
+ }
109
+
110
+ /// \brief Resolve a logical index to a ChunkLocation.
111
+ ///
112
+ /// The returned ChunkLocation contains the chunk index and the within-chunk index
113
+ /// equivalent to the logical index.
114
+ ///
115
+ /// \pre `index >= 0`
116
+ /// \post `location.chunk_index` in `[0, chunks.size()]`
117
+ /// \param index The logical index to resolve
118
+ /// \return ChunkLocation with a valid chunk_index if index is within
119
+ /// bounds, or with `chunk_index == chunks.size()` if logical index is
120
+ /// `>= chunked_array.length()`.
121
+ inline ChunkLocation Resolve(int64_t index) const {
122
+ const auto cached_chunk = cached_chunk_.load(std::memory_order_relaxed);
123
+ const auto chunk_index =
124
+ ResolveChunkIndex</*StoreCachedChunk=*/true>(index, cached_chunk);
125
+ return ChunkLocation{chunk_index, index - offsets_[chunk_index]};
126
+ }
127
+
128
+ /// \brief Resolve a logical index to a ChunkLocation.
129
+ ///
130
+ /// The returned ChunkLocation contains the chunk index and the within-chunk index
131
+ /// equivalent to the logical index.
132
+ ///
133
+ /// \pre `index >= 0`
134
+ /// \post `location.chunk_index` in `[0, chunks.size()]`
135
+ /// \param index The logical index to resolve
136
+ /// \param hint ChunkLocation{} or the last ChunkLocation returned by
137
+ /// this ChunkResolver.
138
+ /// \return ChunkLocation with a valid chunk_index if index is within
139
+ /// bounds, or with `chunk_index == chunks.size()` if logical index is
140
+ /// `>= chunked_array.length()`.
141
+ inline ChunkLocation ResolveWithHint(int64_t index, ChunkLocation hint) const {
142
+ assert(hint.chunk_index < static_cast<uint32_t>(offsets_.size()));
143
+ const auto chunk_index = ResolveChunkIndex</*StoreCachedChunk=*/false>(
144
+ index, static_cast<int32_t>(hint.chunk_index));
145
+ return ChunkLocation{chunk_index, index - offsets_[chunk_index]};
146
+ }
147
+
148
+ /// \brief Resolve `n_indices` logical indices to chunk indices.
149
+ ///
150
+ /// \pre 0 <= logical_index_vec[i] < logical_array_length()
151
+ /// (for well-defined and valid chunk index results)
152
+ /// \pre out_chunk_location_vec has space for `n_indices` locations
153
+ /// \pre chunk_hint in [0, chunks.size()]
154
+ /// \post out_chunk_location_vec[i].chunk_index in [0, chunks.size()] for i in [0, n)
155
+ /// \post if logical_index_vec[i] >= chunked_array.length(), then
156
+ /// out_chunk_location_vec[i].chunk_index == chunks.size()
157
+ /// and out_chunk_location_vec[i].index_in_chunk is UNDEFINED (can be
158
+ /// out-of-bounds)
159
+ /// \post if logical_index_vec[i] < 0, then both values in out_chunk_index_vec[i]
160
+ /// are UNDEFINED
161
+ ///
162
+ /// \param n_indices The number of logical indices to resolve
163
+ /// \param logical_index_vec The logical indices to resolve
164
+ /// \param out_chunk_location_vec The output array where the locations will be written
165
+ /// \param chunk_hint 0 or the last chunk_index produced by ResolveMany
166
+ /// \return false iff chunks.size() > std::numeric_limits<IndexType>::max()
167
+ template <typename IndexType>
168
+ [[nodiscard]] bool ResolveMany(int64_t n_indices, const IndexType* logical_index_vec,
169
+ TypedChunkLocation<IndexType>* out_chunk_location_vec,
170
+ IndexType chunk_hint = 0) const {
171
+ if constexpr (sizeof(IndexType) < sizeof(uint32_t)) {
172
+ // The max value returned by Bisect is `offsets.size() - 1` (= chunks.size()).
173
+ constexpr int64_t kMaxIndexTypeValue = std::numeric_limits<IndexType>::max();
174
+ // A ChunkedArray with enough empty chunks can make the index of a chunk
175
+ // exceed the logical index and thus the maximum value of IndexType.
176
+ const bool chunk_index_fits_on_type = num_chunks() <= kMaxIndexTypeValue;
177
+ if (ARROW_PREDICT_FALSE(!chunk_index_fits_on_type)) {
178
+ return false;
179
+ }
180
+ // Since an index-in-chunk cannot possibly exceed the logical index being
181
+ // queried, we don't have to worry about these values not fitting on IndexType.
182
+ }
183
+ if constexpr (std::is_signed_v<IndexType>) {
184
+ // We interpret signed integers as unsigned and avoid having to generate double
185
+ // the amount of binary code to handle each integer width.
186
+ //
187
+ // Negative logical indices can become large values when cast to unsigned, and
188
+ // they are gracefully handled by ResolveManyImpl, but both the chunk index
189
+ // and the index in chunk values will be undefined in these cases. This
190
+ // happend because int8_t(-1) == uint8_t(255) and 255 could be a valid
191
+ // logical index in the chunked array.
192
+ using U = std::make_unsigned_t<IndexType>;
193
+ ResolveManyImpl(n_indices, reinterpret_cast<const U*>(logical_index_vec),
194
+ reinterpret_cast<TypedChunkLocation<U>*>(out_chunk_location_vec),
195
+ static_cast<int32_t>(chunk_hint));
196
+ } else {
197
+ static_assert(std::is_unsigned_v<IndexType>);
198
+ ResolveManyImpl(n_indices, logical_index_vec, out_chunk_location_vec,
199
+ static_cast<int32_t>(chunk_hint));
200
+ }
201
+ return true;
202
+ }
203
+
204
+ private:
205
+ template <bool StoreCachedChunk>
206
+ inline int64_t ResolveChunkIndex(int64_t index, int32_t cached_chunk) const {
207
+ // It is common for algorithms sequentially processing arrays to make consecutive
208
+ // accesses at a relatively small distance from each other, hence often falling in the
209
+ // same chunk.
210
+ //
211
+ // This is guaranteed when merging (assuming each side of the merge uses its
212
+ // own resolver), and is the most common case in recursive invocations of
213
+ // partitioning.
214
+ const auto num_offsets = static_cast<uint32_t>(offsets_.size());
215
+ const int64_t* offsets = offsets_.data();
216
+ if (ARROW_PREDICT_TRUE(index >= offsets[cached_chunk]) &&
217
+ (static_cast<uint32_t>(cached_chunk + 1) == num_offsets ||
218
+ index < offsets[cached_chunk + 1])) {
219
+ return cached_chunk;
220
+ }
221
+ // lo < hi is guaranteed by `num_offsets = chunks.size() + 1`
222
+ const auto chunk_index = Bisect(index, offsets, /*lo=*/0, /*hi=*/num_offsets);
223
+ if constexpr (StoreCachedChunk) {
224
+ assert(static_cast<uint32_t>(chunk_index) < static_cast<uint32_t>(offsets_.size()));
225
+ cached_chunk_.store(chunk_index, std::memory_order_relaxed);
226
+ }
227
+ return chunk_index;
228
+ }
229
+
230
+ /// \pre all the pre-conditions of ChunkResolver::ResolveMany()
231
+ /// \pre num_offsets - 1 <= std::numeric_limits<IndexType>::max()
232
+ void ResolveManyImpl(int64_t, const uint8_t*, TypedChunkLocation<uint8_t>*,
233
+ int32_t) const;
234
+ void ResolveManyImpl(int64_t, const uint16_t*, TypedChunkLocation<uint16_t>*,
235
+ int32_t) const;
236
+ void ResolveManyImpl(int64_t, const uint32_t*, TypedChunkLocation<uint32_t>*,
237
+ int32_t) const;
238
+ void ResolveManyImpl(int64_t, const uint64_t*, TypedChunkLocation<uint64_t>*,
239
+ int32_t) const;
240
+
241
+ public:
242
+ /// \brief Find the index of the chunk that contains the logical index.
243
+ ///
244
+ /// Any non-negative index is accepted. When `hi=num_offsets`, the largest
245
+ /// possible return value is `num_offsets-1` which is equal to
246
+ /// `chunks.size()`. Which is returned when the logical index is greater or
247
+ /// equal the logical length of the chunked array.
248
+ ///
249
+ /// \pre index >= 0 (otherwise, when index is negative, hi-1 is returned)
250
+ /// \pre lo < hi
251
+ /// \pre lo >= 0 && hi <= offsets_.size()
252
+ static inline int32_t Bisect(int64_t index, const int64_t* offsets, int32_t lo,
253
+ int32_t hi) {
254
+ return Bisect(static_cast<uint64_t>(index),
255
+ reinterpret_cast<const uint64_t*>(offsets), static_cast<uint32_t>(lo),
256
+ static_cast<uint32_t>(hi));
257
+ }
258
+
259
+ static inline int32_t Bisect(uint64_t index, const uint64_t* offsets, uint32_t lo,
260
+ uint32_t hi) {
261
+ // Similar to std::upper_bound(), but slightly different as our offsets
262
+ // array always starts with 0.
263
+ auto n = hi - lo;
264
+ // First iteration does not need to check for n > 1
265
+ // (lo < hi is guaranteed by the precondition).
266
+ assert(n > 1 && "lo < hi is a precondition of Bisect");
267
+ do {
268
+ const uint32_t m = n >> 1;
269
+ const uint32_t mid = lo + m;
270
+ if (index >= offsets[mid]) {
271
+ lo = mid;
272
+ n -= m;
273
+ } else {
274
+ n = m;
275
+ }
276
+ } while (n > 1);
277
+ return lo;
278
+ }
279
+ };
280
+
281
+ // Explicitly instantiate template base struct, for DLL linking on Windows
282
+ template struct TypedChunkLocation<int32_t>;
283
+ template struct TypedChunkLocation<int16_t>;
284
+ template struct TypedChunkLocation<int8_t>;
285
+ template struct TypedChunkLocation<uint8_t>;
286
+ template struct TypedChunkLocation<uint16_t>;
287
+ template struct TypedChunkLocation<uint32_t>;
288
+ template struct TypedChunkLocation<int64_t>;
289
+ template struct TypedChunkLocation<uint64_t>;
290
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/compare.h ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Functions for comparing Arrow data structures
19
+
20
+ #pragma once
21
+
22
+ #include <cstdint>
23
+ #include <iosfwd>
24
+
25
+ #include "arrow/util/macros.h"
26
+ #include "arrow/util/visibility.h"
27
+
28
+ namespace arrow {
29
+
30
+ class Array;
31
+ class DataType;
32
+ class Tensor;
33
+ class SparseTensor;
34
+ struct Scalar;
35
+
36
+ static constexpr double kDefaultAbsoluteTolerance = 1E-5;
37
+
38
+ /// A container of options for equality comparisons
39
+ class EqualOptions {
40
+ public:
41
+ /// Whether or not NaNs are considered equal.
42
+ bool nans_equal() const { return nans_equal_; }
43
+
44
+ /// Return a new EqualOptions object with the "nans_equal" property changed.
45
+ EqualOptions nans_equal(bool v) const {
46
+ auto res = EqualOptions(*this);
47
+ res.nans_equal_ = v;
48
+ return res;
49
+ }
50
+
51
+ /// Whether or not zeros with differing signs are considered equal.
52
+ bool signed_zeros_equal() const { return signed_zeros_equal_; }
53
+
54
+ /// Return a new EqualOptions object with the "signed_zeros_equal" property changed.
55
+ EqualOptions signed_zeros_equal(bool v) const {
56
+ auto res = EqualOptions(*this);
57
+ res.signed_zeros_equal_ = v;
58
+ return res;
59
+ }
60
+
61
+ /// The absolute tolerance for approximate comparisons of floating-point values.
62
+ double atol() const { return atol_; }
63
+
64
+ /// Return a new EqualOptions object with the "atol" property changed.
65
+ EqualOptions atol(double v) const {
66
+ auto res = EqualOptions(*this);
67
+ res.atol_ = v;
68
+ return res;
69
+ }
70
+
71
+ /// The ostream to which a diff will be formatted if arrays disagree.
72
+ /// If this is null (the default) no diff will be formatted.
73
+ std::ostream* diff_sink() const { return diff_sink_; }
74
+
75
+ /// Return a new EqualOptions object with the "diff_sink" property changed.
76
+ /// This option will be ignored if diff formatting of the types of compared arrays is
77
+ /// not supported.
78
+ EqualOptions diff_sink(std::ostream* diff_sink) const {
79
+ auto res = EqualOptions(*this);
80
+ res.diff_sink_ = diff_sink;
81
+ return res;
82
+ }
83
+
84
+ static EqualOptions Defaults() { return {}; }
85
+
86
+ protected:
87
+ double atol_ = kDefaultAbsoluteTolerance;
88
+ bool nans_equal_ = false;
89
+ bool signed_zeros_equal_ = true;
90
+
91
+ std::ostream* diff_sink_ = NULLPTR;
92
+ };
93
+
94
+ /// Returns true if the arrays are exactly equal
95
+ ARROW_EXPORT bool ArrayEquals(const Array& left, const Array& right,
96
+ const EqualOptions& = EqualOptions::Defaults());
97
+
98
+ /// Returns true if the arrays are approximately equal. For non-floating point
99
+ /// types, this is equivalent to ArrayEquals(left, right)
100
+ ARROW_EXPORT bool ArrayApproxEquals(const Array& left, const Array& right,
101
+ const EqualOptions& = EqualOptions::Defaults());
102
+
103
+ /// Returns true if indicated equal-length segment of arrays are exactly equal
104
+ ARROW_EXPORT bool ArrayRangeEquals(const Array& left, const Array& right,
105
+ int64_t start_idx, int64_t end_idx,
106
+ int64_t other_start_idx,
107
+ const EqualOptions& = EqualOptions::Defaults());
108
+
109
+ /// Returns true if indicated equal-length segment of arrays are approximately equal
110
+ ARROW_EXPORT bool ArrayRangeApproxEquals(const Array& left, const Array& right,
111
+ int64_t start_idx, int64_t end_idx,
112
+ int64_t other_start_idx,
113
+ const EqualOptions& = EqualOptions::Defaults());
114
+
115
+ ARROW_EXPORT bool TensorEquals(const Tensor& left, const Tensor& right,
116
+ const EqualOptions& = EqualOptions::Defaults());
117
+
118
+ /// EXPERIMENTAL: Returns true if the given sparse tensors are exactly equal
119
+ ARROW_EXPORT bool SparseTensorEquals(const SparseTensor& left, const SparseTensor& right,
120
+ const EqualOptions& = EqualOptions::Defaults());
121
+
122
+ /// Returns true if the type metadata are exactly equal
123
+ /// \param[in] left a DataType
124
+ /// \param[in] right a DataType
125
+ /// \param[in] check_metadata whether to compare KeyValueMetadata for child
126
+ /// fields
127
+ ARROW_EXPORT bool TypeEquals(const DataType& left, const DataType& right,
128
+ bool check_metadata = true);
129
+
130
+ /// Returns true if scalars are equal
131
+ /// \param[in] left a Scalar
132
+ /// \param[in] right a Scalar
133
+ /// \param[in] options comparison options
134
+ ARROW_EXPORT bool ScalarEquals(const Scalar& left, const Scalar& right,
135
+ const EqualOptions& options = EqualOptions::Defaults());
136
+
137
+ /// Returns true if scalars are approximately equal
138
+ /// \param[in] left a Scalar
139
+ /// \param[in] right a Scalar
140
+ /// \param[in] options comparison options
141
+ ARROW_EXPORT bool ScalarApproxEquals(
142
+ const Scalar& left, const Scalar& right,
143
+ const EqualOptions& options = EqualOptions::Defaults());
144
+
145
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/config.h ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <optional>
21
+ #include <string>
22
+
23
+ #include "arrow/status.h"
24
+ #include "arrow/util/config.h" // IWYU pragma: export
25
+ #include "arrow/util/visibility.h"
26
+
27
+ namespace arrow {
28
+
29
+ struct BuildInfo {
30
+ /// The packed version number, e.g. 1002003 (decimal) for Arrow 1.2.3
31
+ int version;
32
+ /// The "major" version number, e.g. 1 for Arrow 1.2.3
33
+ int version_major;
34
+ /// The "minor" version number, e.g. 2 for Arrow 1.2.3
35
+ int version_minor;
36
+ /// The "patch" version number, e.g. 3 for Arrow 1.2.3
37
+ int version_patch;
38
+ /// The version string, e.g. "1.2.3"
39
+ std::string version_string;
40
+ std::string so_version;
41
+ std::string full_so_version;
42
+
43
+ /// The CMake compiler identifier, e.g. "GNU"
44
+ std::string compiler_id;
45
+ std::string compiler_version;
46
+ std::string compiler_flags;
47
+
48
+ /// The git changeset id, if available
49
+ std::string git_id;
50
+ /// The git changeset description, if available
51
+ std::string git_description;
52
+ std::string package_kind;
53
+
54
+ /// The uppercase build type, e.g. "DEBUG" or "RELEASE"
55
+ std::string build_type;
56
+ };
57
+
58
+ struct RuntimeInfo {
59
+ /// The enabled SIMD level
60
+ ///
61
+ /// This can be less than `detected_simd_level` if the ARROW_USER_SIMD_LEVEL
62
+ /// environment variable is set to another value.
63
+ std::string simd_level;
64
+
65
+ /// The SIMD level available on the OS and CPU
66
+ std::string detected_simd_level;
67
+
68
+ /// Whether using the OS-based timezone database
69
+ /// This is set at compile-time.
70
+ bool using_os_timezone_db;
71
+
72
+ /// The path to the timezone database; by default None.
73
+ std::optional<std::string> timezone_db_path;
74
+ };
75
+
76
+ /// \brief Get runtime build info.
77
+ ///
78
+ /// The returned values correspond to exact loaded version of the Arrow library,
79
+ /// rather than the values frozen at application compile-time through the `ARROW_*`
80
+ /// preprocessor definitions.
81
+ ARROW_EXPORT
82
+ const BuildInfo& GetBuildInfo();
83
+
84
+ /// \brief Get runtime info.
85
+ ///
86
+ ARROW_EXPORT
87
+ RuntimeInfo GetRuntimeInfo();
88
+
89
+ struct GlobalOptions {
90
+ /// Path to text timezone database. This is only configurable on Windows,
91
+ /// which does not have a compatible OS timezone database.
92
+ std::optional<std::string> timezone_db_path;
93
+ };
94
+
95
+ ARROW_EXPORT
96
+ Status Initialize(const GlobalOptions& options) noexcept;
97
+
98
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/csv/converter.h ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <memory>
22
+
23
+ #include "arrow/csv/options.h"
24
+ #include "arrow/result.h"
25
+ #include "arrow/type_fwd.h"
26
+ #include "arrow/util/macros.h"
27
+ #include "arrow/util/visibility.h"
28
+
29
+ namespace arrow {
30
+ namespace csv {
31
+
32
+ class BlockParser;
33
+
34
+ class ARROW_EXPORT Converter {
35
+ public:
36
+ Converter(const std::shared_ptr<DataType>& type, const ConvertOptions& options,
37
+ MemoryPool* pool);
38
+ virtual ~Converter() = default;
39
+
40
+ virtual Result<std::shared_ptr<Array>> Convert(const BlockParser& parser,
41
+ int32_t col_index) = 0;
42
+
43
+ std::shared_ptr<DataType> type() const { return type_; }
44
+
45
+ // Create a Converter for the given data type
46
+ static Result<std::shared_ptr<Converter>> Make(
47
+ const std::shared_ptr<DataType>& type, const ConvertOptions& options,
48
+ MemoryPool* pool = default_memory_pool());
49
+
50
+ protected:
51
+ ARROW_DISALLOW_COPY_AND_ASSIGN(Converter);
52
+
53
+ virtual Status Initialize() = 0;
54
+
55
+ // CAUTION: ConvertOptions can grow large (if it customizes hundreds or
56
+ // thousands of columns), so avoid copying it in each Converter.
57
+ const ConvertOptions& options_;
58
+ MemoryPool* pool_;
59
+ std::shared_ptr<DataType> type_;
60
+ };
61
+
62
+ class ARROW_EXPORT DictionaryConverter : public Converter {
63
+ public:
64
+ DictionaryConverter(const std::shared_ptr<DataType>& value_type,
65
+ const ConvertOptions& options, MemoryPool* pool);
66
+
67
+ // If the dictionary length goes above this value, conversion will fail
68
+ // with Status::IndexError.
69
+ virtual void SetMaxCardinality(int32_t max_length) = 0;
70
+
71
+ // Create a Converter for the given dictionary value type.
72
+ // The dictionary index type will always be Int32.
73
+ static Result<std::shared_ptr<DictionaryConverter>> Make(
74
+ const std::shared_ptr<DataType>& value_type, const ConvertOptions& options,
75
+ MemoryPool* pool = default_memory_pool());
76
+
77
+ protected:
78
+ std::shared_ptr<DataType> value_type_;
79
+ };
80
+
81
+ } // namespace csv
82
+ } // namespace arrow