/home/runner/work/LabNeura/LabNeura/src/labneura/tensor.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | #include "labneura/tensor.h" |
2 | | #include "labneura/backends/cpu/generic.h" |
3 | | #include "labneura/backends/cpu/neon.h" |
4 | | #include "labneura/backends/cpu/avx2.h" |
5 | | #include "labneura/backends/common/backend_factory.h" |
6 | | #include "labneura/backends/common/dtype_validation.h" |
7 | | #include "labneura/detail/broadcast.h" |
8 | | #include "labneura/types.hpp" |
9 | | #include <cstring> |
10 | | #include <algorithm> |
11 | | #include <cmath> |
12 | | #include <iostream> |
13 | | #include <limits> |
14 | | #include <typeinfo> |
15 | | |
16 | | namespace labneura { |
17 | | |
18 | | namespace { |
19 | 4.60k | std::size_t dtype_size(QuantizationMode mode) { |
20 | 4.60k | switch (mode) { |
21 | 1.80k | case QuantizationMode::FP32: |
22 | 1.80k | return sizeof(float); |
23 | 1.04k | case QuantizationMode::FP16: |
24 | 1.76k | case QuantizationMode::INT16: |
25 | 1.76k | return sizeof(int16_t); |
26 | 1.02k | case QuantizationMode::INT8: |
27 | 1.02k | return sizeof(int8_t); |
28 | 15 | case QuantizationMode::BOOL: |
29 | 15 | return sizeof(std::uint8_t); |
30 | 0 | case QuantizationMode::FP64: |
31 | 0 | throw std::invalid_argument("Unsupported tensor dtype: FP64"); |
32 | 0 | case QuantizationMode::INT32: |
33 | 0 | throw std::invalid_argument("Unsupported tensor dtype: INT32"); |
34 | 0 | default: |
35 | 0 | throw std::invalid_argument("Unsupported tensor dtype: unknown"); |
36 | 4.60k | } |
37 | 4.60k | } |
38 | | |
39 | 3.13k | std::size_t checked_shape_numel(const std::vector<std::size_t>& shape) { |
40 | 3.13k | if (std::find(shape.begin(), shape.end(), std::size_t{0}) != shape.end()) { |
41 | 135 | return 0; |
42 | 135 | } |
43 | | |
44 | 3.00k | std::size_t element_count = 1; |
45 | 3.85k | for (const std::size_t dimension : shape) { |
46 | 3.85k | if (element_count > |
47 | 3.85k | std::numeric_limits<std::size_t>::max() / dimension) { |
48 | 3 | throw std::overflow_error( |
49 | 3 | "Tensor shape element count overflows size_t"); |
50 | 3 | } |
51 | 3.84k | element_count *= dimension; |
52 | 3.84k | } |
53 | 3.00k | return element_count; |
54 | 3.00k | } |
55 | | |
56 | 4.60k | void check_allocation_size(std::size_t size, QuantizationMode mode) { |
57 | 4.60k | validate_tensor_dtype_supported(mode); |
58 | 4.60k | const std::size_t element_bytes = dtype_size(mode); |
59 | 4.60k | if (size > std::numeric_limits<std::size_t>::max() / element_bytes) { |
60 | 2 | throw std::overflow_error("Tensor allocation byte size overflows size_t"); |
61 | 2 | } |
62 | 4.60k | } |
63 | | |
64 | | std::size_t checked_offset_advance(std::size_t index, |
65 | 104 | std::size_t stride) { |
66 | 104 | if (stride != 0 && |
67 | 104 | index > std::numeric_limits<std::size_t>::max() / stride) { |
68 | 0 | throw std::overflow_error("Tensor storage offset overflows size_t"); |
69 | 0 | } |
70 | 104 | return index * stride; |
71 | 104 | } |
72 | | |
73 | 104 | std::size_t checked_offset_add(std::size_t offset, std::size_t advance) { |
74 | 104 | if (offset > std::numeric_limits<std::size_t>::max() - advance) { |
75 | 0 | throw std::overflow_error("Tensor storage offset overflows size_t"); |
76 | 0 | } |
77 | 104 | return offset + advance; |
78 | 104 | } |
79 | | |
80 | | std::vector<float> flatten_rows(const std::vector<std::vector<float>>& rows, |
81 | 6 | QuantizationMode mode) { |
82 | 6 | validate_tensor_dtype_supported(mode); |
83 | 6 | std::vector<float> flat; |
84 | 6 | if (rows.empty()) return flat; |
85 | 6 | const std::size_t cols = rows.front().size(); |
86 | 6 | const std::vector<std::size_t> shape{rows.size(), cols}; |
87 | 6 | const std::size_t element_count = checked_shape_numel(shape); |
88 | 6 | check_allocation_size(element_count, mode); |
89 | 6 | flat.reserve(element_count); |
90 | 12 | for (const auto& row : rows) { |
91 | 12 | if (row.size() != cols) { |
92 | 1 | throw std::invalid_argument( |
93 | 1 | "2-D Tensor rows must all have the same length"); |
94 | 1 | } |
95 | 11 | flat.insert(flat.end(), row.begin(), row.end()); |
96 | 11 | } |
97 | 5 | return flat; |
98 | 6 | } |
99 | | } // namespace |
100 | | |
101 | | // Tensor implementation |
102 | | Tensor::Tensor() |
103 | 30 | : quantization_mode_(QuantizationMode::FP32), |
104 | 30 | shape_{0}, |
105 | 30 | strides_(checked_contiguous_strides(shape_)) { |
106 | 30 | init_backend(0); |
107 | 30 | } |
108 | | |
109 | | Tensor::Tensor(QuantizationMode mode, std::unique_ptr<TensorBackend> backend, std::vector<std::size_t> shape) |
110 | 789 | : quantization_mode_(mode), |
111 | 789 | backend_(std::move(backend)), |
112 | 789 | storage_(backend_ ? backend_->storage_ : nullptr), |
113 | 789 | shape_(std::move(shape)), |
114 | 789 | strides_(checked_contiguous_strides(shape_)) {} |
115 | | |
116 | | Tensor::Tensor(const std::vector<std::vector<float>>& rows, QuantizationMode mode) |
117 | 6 | : Tensor(flatten_rows(rows, mode), mode) { |
118 | 6 | shape_ = {rows.size(), rows.empty() ? std::size_t{0} : rows.front().size()}; |
119 | 6 | strides_ = checked_contiguous_strides(shape_); |
120 | 6 | } |
121 | | |
122 | | Tensor::Tensor(const std::vector<float>& data, QuantizationMode mode) |
123 | 2.55k | : quantization_mode_(mode), |
124 | 2.55k | shape_{data.size()}, |
125 | 2.55k | strides_(checked_contiguous_strides(shape_)) { |
126 | 2.55k | init_backend(data.size()); |
127 | 2.55k | if (!data.empty()) { |
128 | 2.54k | if (mode == QuantizationMode::FP32) { |
129 | 1.21k | float* fp32_data = data_fp32(); |
130 | 205M | for (std::size_t i = 0; i < data.size(); ++i) { |
131 | 205M | fp32_data[i] = data[i]; |
132 | 205M | } |
133 | 1.32k | } else if (mode == QuantizationMode::FP16) { |
134 | 631 | int16_t* fp16_data = data_fp16(); |
135 | 20.6k | for (std::size_t i = 0; i < data.size(); ++i) { |
136 | | // Proper FP16 encoding (stored in int16_t for NEON compatibility) |
137 | 20.0k | uint16_t encoded = quantize_fp16(data[i]); |
138 | 20.0k | std::memcpy(&fp16_data[i], &encoded, sizeof(uint16_t)); |
139 | 20.0k | } |
140 | 698 | } else if (mode == QuantizationMode::INT8) { |
141 | 492 | int8_t* int8_data = data_int8(); |
142 | 200M | for (std::size_t i = 0; i < data.size(); ++i) { |
143 | 200M | int v = static_cast<int>(std::lrintf(data[i])); |
144 | 200M | int8_data[i] = static_cast<int8_t>(std::max(-128, std::min(127, v))); |
145 | 200M | } |
146 | 492 | } else if (mode == QuantizationMode::INT16) { |
147 | 206 | int16_t* int16_data = data_int16(); |
148 | 23.7k | for (std::size_t i = 0; i < data.size(); ++i) { |
149 | 23.4k | int v = static_cast<int>(std::lrintf(data[i])); |
150 | 23.4k | int16_data[i] = static_cast<int16_t>(std::max(-32768, std::min(32767, v))); |
151 | 23.4k | } |
152 | 206 | } else if (mode == QuantizationMode::BOOL) { |
153 | 0 | std::uint8_t* bool_data = data_bool(); |
154 | 0 | for (std::size_t i = 0; i < data.size(); ++i) { |
155 | 0 | bool_data[i] = data[i] != 0.0f ? 1 : 0; |
156 | 0 | } |
157 | 0 | } else { |
158 | 0 | throw std::invalid_argument("Unsupported tensor dtype"); |
159 | 0 | } |
160 | 2.54k | } |
161 | 2.55k | } |
162 | | |
163 | | Tensor::Tensor(const std::vector<int>& data, QuantizationMode mode) |
164 | 668 | : quantization_mode_(mode), |
165 | 668 | shape_{data.size()}, |
166 | 668 | strides_(checked_contiguous_strides(shape_)) { |
167 | 668 | init_backend(data.size()); |
168 | 668 | if (mode == QuantizationMode::FP32) { |
169 | 98 | float* fp32_data = data_fp32(); |
170 | 404 | for (std::size_t i = 0; i < data.size(); ++i) { |
171 | 306 | fp32_data[i] = static_cast<float>(data[i]); |
172 | 306 | } |
173 | 570 | } else if (mode == QuantizationMode::FP16) { |
174 | 64 | int16_t* fp16_data = data_fp16(); |
175 | 238 | for (std::size_t i = 0; i < data.size(); ++i) { |
176 | | // Proper FP16 encoding from int (convert to float first, then quantize) |
177 | 174 | uint16_t encoded = quantize_fp16(static_cast<float>(data[i])); |
178 | 174 | std::memcpy(&fp16_data[i], &encoded, sizeof(uint16_t)); |
179 | 174 | } |
180 | 506 | } else if (mode == QuantizationMode::INT8) { |
181 | 257 | int8_t* int8_data = data_int8(); |
182 | 5.16k | for (std::size_t i = 0; i < data.size(); ++i) { |
183 | 4.91k | int8_data[i] = static_cast<int8_t>( |
184 | 4.91k | std::max(-128, std::min(127, data[i])) |
185 | 4.91k | ); |
186 | 4.91k | } |
187 | 257 | } else if (mode == QuantizationMode::INT16) { |
188 | 249 | int16_t* int16_data = data_int16(); |
189 | 3.10k | for (std::size_t i = 0; i < data.size(); ++i) { |
190 | 2.85k | int16_data[i] = static_cast<int16_t>( |
191 | 2.85k | std::max(-32768, std::min(32767, data[i])) |
192 | 2.85k | ); |
193 | 2.85k | } |
194 | 249 | } else if (mode == QuantizationMode::BOOL) { |
195 | 0 | std::uint8_t* bool_data = data_bool(); |
196 | 0 | for (std::size_t i = 0; i < data.size(); ++i) { |
197 | 0 | bool_data[i] = data[i] != 0 ? 1 : 0; |
198 | 0 | } |
199 | 0 | } |
200 | 668 | } |
201 | | |
202 | | Tensor::Tensor(const std::vector<std::uint8_t>& data, QuantizationMode mode) |
203 | 10 | : quantization_mode_(mode), |
204 | 10 | shape_{data.size()}, |
205 | 10 | strides_(checked_contiguous_strides(shape_)) { |
206 | 10 | if (mode != QuantizationMode::BOOL) { |
207 | 0 | throw std::invalid_argument( |
208 | 0 | "std::uint8_t sequence construction requires BOOL dtype"); |
209 | 0 | } |
210 | 10 | init_backend(data.size()); |
211 | 10 | std::uint8_t* bool_data = data_bool(); |
212 | 33 | for (std::size_t i = 0; i < data.size(); ++i) { |
213 | 23 | bool_data[i] = data[i] != 0 ? 1 : 0; |
214 | 23 | } |
215 | 10 | } |
216 | | |
217 | | Tensor Tensor::from_flat(const std::vector<float>& data, |
218 | | const std::vector<std::size_t>& shape, |
219 | 571 | QuantizationMode mode) { |
220 | 571 | const std::size_t element_count = checked_numel(shape); |
221 | 571 | validate_allocation_size(element_count, mode); |
222 | 571 | if (element_count != data.size()) { |
223 | 2 | throw std::invalid_argument( |
224 | 2 | "Tensor shape element count does not match data length"); |
225 | 2 | } |
226 | | |
227 | 569 | const std::vector<std::size_t> strides = |
228 | 569 | checked_contiguous_strides(shape); |
229 | 569 | Tensor tensor(data, mode); |
230 | 569 | tensor.shape_ = shape; |
231 | 569 | tensor.strides_ = strides; |
232 | 569 | return tensor; |
233 | 571 | } |
234 | | |
235 | | Tensor Tensor::from_flat(const std::vector<std::uint8_t>& data, |
236 | | const std::vector<std::size_t>& shape, |
237 | 5 | QuantizationMode mode) { |
238 | 5 | const std::size_t element_count = checked_numel(shape); |
239 | 5 | validate_allocation_size(element_count, mode); |
240 | 5 | if (element_count != data.size()) { |
241 | 0 | throw std::invalid_argument( |
242 | 0 | "Tensor shape element count does not match data length"); |
243 | 0 | } |
244 | 5 | if (mode != QuantizationMode::BOOL) { |
245 | 0 | throw std::invalid_argument( |
246 | 0 | "std::uint8_t sequence construction requires BOOL dtype"); |
247 | 0 | } |
248 | | |
249 | 5 | Tensor tensor(data, mode); |
250 | 5 | tensor.shape_ = shape; |
251 | 5 | tensor.strides_ = checked_contiguous_strides(shape); |
252 | 5 | return tensor; |
253 | 5 | } |
254 | | |
255 | | Tensor Tensor::from_flat(const std::vector<int>& data, |
256 | | const std::vector<std::size_t>& shape, |
257 | 674 | QuantizationMode mode) { |
258 | 674 | const std::size_t element_count = checked_numel(shape); |
259 | 674 | validate_allocation_size(element_count, mode); |
260 | 674 | if (element_count != data.size()) { |
261 | 2 | throw std::invalid_argument( |
262 | 2 | "Tensor shape element count does not match data length"); |
263 | 2 | } |
264 | | |
265 | 672 | const std::vector<std::size_t> strides = |
266 | 672 | checked_contiguous_strides(shape); |
267 | 672 | Tensor tensor(data, mode); |
268 | 672 | tensor.shape_ = shape; |
269 | 672 | tensor.strides_ = strides; |
270 | 672 | return tensor; |
271 | 674 | } |
272 | | |
273 | 20 | Tensor Tensor::reshape(const std::vector<std::size_t>& shape) const { |
274 | 20 | if (!backend_) { |
275 | 0 | throw std::runtime_error("Tensor backend not initialized"); |
276 | 0 | } |
277 | | |
278 | 20 | const std::size_t requested_numel = checked_numel(shape); |
279 | 20 | if (requested_numel != size()) { |
280 | 2 | throw std::invalid_argument( |
281 | 2 | "reshape requires the new shape to have the same number of elements"); |
282 | 2 | } |
283 | 18 | validate_allocation_size(requested_numel, quantization_mode_); |
284 | 18 | const std::vector<std::size_t> strides = |
285 | 18 | checked_contiguous_strides(shape); |
286 | | |
287 | 18 | Tensor result(*this); |
288 | 18 | result.shape_ = shape; |
289 | 18 | result.strides_ = strides; |
290 | 18 | result.storage_offset_ = 0; |
291 | 18 | return result; |
292 | 20 | } |
293 | | |
294 | 11 | Tensor Tensor::reshape_view(const std::vector<std::size_t>& shape) const { |
295 | 11 | if (!backend_ || !storage_) { |
296 | 0 | throw std::runtime_error("Tensor backend not initialized"); |
297 | 0 | } |
298 | 11 | if (!is_contiguous()) { |
299 | 0 | throw std::invalid_argument( |
300 | 0 | "reshape_view requires a contiguous source tensor"); |
301 | 0 | } |
302 | | |
303 | 11 | const std::size_t requested_numel = checked_numel(shape); |
304 | 11 | if (requested_numel != numel()) { |
305 | 1 | throw std::invalid_argument( |
306 | 1 | "reshape_view requires the new shape to have the same number of elements"); |
307 | 1 | } |
308 | 10 | validate_allocation_size(requested_numel, quantization_mode_); |
309 | 10 | const std::vector<std::size_t> strides = |
310 | 10 | checked_contiguous_strides(shape); |
311 | | |
312 | 10 | Tensor result(quantization_mode_, |
313 | 10 | backend_->create_storage_alias(requested_numel, |
314 | 10 | storage_offset_), |
315 | 10 | shape); |
316 | 10 | result.strides_ = strides; |
317 | 10 | result.storage_offset_ = storage_offset_; |
318 | 10 | return result; |
319 | 11 | } |
320 | | |
321 | 95 | Tensor Tensor::slice_first_axis(std::size_t start, std::size_t stop) const { |
322 | 95 | if (!backend_ || !storage_) { |
323 | 0 | throw std::runtime_error("Tensor backend not initialized"); |
324 | 0 | } |
325 | 95 | if (shape_.empty()) { |
326 | 1 | throw std::invalid_argument( |
327 | 1 | "slice_first_axis requires a tensor with at least one dimension"); |
328 | 1 | } |
329 | 94 | if (!is_contiguous()) { |
330 | 0 | throw std::invalid_argument( |
331 | 0 | "slice_first_axis requires a contiguous source tensor"); |
332 | 0 | } |
333 | 94 | if (start > stop) { |
334 | 1 | throw std::invalid_argument( |
335 | 1 | "slice_first_axis requires start <= stop"); |
336 | 1 | } |
337 | 93 | if (stop > shape_[0]) { |
338 | 2 | throw std::out_of_range( |
339 | 2 | "slice_first_axis range exceeds the first dimension"); |
340 | 2 | } |
341 | | |
342 | 91 | std::vector<std::size_t> shape = shape_; |
343 | 91 | shape[0] = stop - start; |
344 | 91 | const std::size_t logical_size = checked_numel(shape); |
345 | 91 | const std::size_t offset = checked_offset_add( |
346 | 91 | storage_offset_, checked_offset_advance(start, strides_[0])); |
347 | | |
348 | 91 | Tensor result(quantization_mode_, |
349 | 91 | backend_->create_storage_alias(logical_size, offset), |
350 | 91 | std::move(shape)); |
351 | 91 | result.storage_offset_ = offset; |
352 | 91 | return result; |
353 | 93 | } |
354 | | |
355 | 16 | Tensor Tensor::select_first_axis(std::size_t index) const { |
356 | 16 | if (!backend_ || !storage_) { |
357 | 0 | throw std::runtime_error("Tensor backend not initialized"); |
358 | 0 | } |
359 | 16 | if (shape_.empty()) { |
360 | 1 | throw std::invalid_argument( |
361 | 1 | "select_first_axis requires a tensor with at least one dimension"); |
362 | 1 | } |
363 | 15 | if (!is_contiguous()) { |
364 | 0 | throw std::invalid_argument( |
365 | 0 | "select_first_axis requires a contiguous source tensor"); |
366 | 0 | } |
367 | 15 | if (index >= shape_[0]) { |
368 | 2 | throw std::out_of_range( |
369 | 2 | "select_first_axis index exceeds the first dimension"); |
370 | 2 | } |
371 | | |
372 | 13 | std::vector<std::size_t> shape(shape_.begin() + 1, shape_.end()); |
373 | 13 | const std::size_t logical_size = checked_numel(shape); |
374 | 13 | const std::size_t offset = checked_offset_add( |
375 | 13 | storage_offset_, checked_offset_advance(index, strides_[0])); |
376 | | |
377 | 13 | Tensor result(quantization_mode_, |
378 | 13 | backend_->create_storage_alias(logical_size, offset), |
379 | 13 | std::move(shape)); |
380 | 13 | result.storage_offset_ = offset; |
381 | 13 | return result; |
382 | 15 | } |
383 | | |
384 | 6 | Tensor Tensor::flatten() const { |
385 | 6 | return reshape({size()}); |
386 | 6 | } |
387 | | |
388 | | Tensor::Tensor(float scalar, QuantizationMode mode) |
389 | 54 | : quantization_mode_(mode), |
390 | 54 | shape_{1}, |
391 | 54 | strides_(checked_contiguous_strides(shape_)) { |
392 | 54 | init_backend(1); |
393 | 54 | if (mode == QuantizationMode::FP32) { |
394 | 28 | data_fp32()[0] = scalar; |
395 | 28 | } else if (mode == QuantizationMode::FP16) { |
396 | 5 | uint16_t encoded = quantize_fp16(scalar); |
397 | 5 | std::memcpy(&data_fp16()[0], &encoded, sizeof(uint16_t)); |
398 | 21 | } else if (mode == QuantizationMode::INT8) { |
399 | 11 | int v = static_cast<int>(std::lrintf(scalar)); |
400 | 11 | data_int8()[0] = static_cast<int8_t>(std::max(-128, std::min(127, v))); |
401 | 11 | } else if (mode == QuantizationMode::INT16) { |
402 | 10 | int v = static_cast<int>(std::lrintf(scalar)); |
403 | 10 | data_int16()[0] = static_cast<int16_t>(std::max(-32768, std::min(32767, v))); |
404 | 10 | } else if (mode == QuantizationMode::BOOL) { |
405 | 0 | data_bool()[0] = scalar != 0.0f ? 1 : 0; |
406 | 0 | } else { |
407 | 0 | throw std::invalid_argument("Unsupported tensor dtype"); |
408 | 0 | } |
409 | 54 | } |
410 | | |
411 | | Tensor::Tensor(int scalar, QuantizationMode mode) |
412 | 0 | : quantization_mode_(mode), |
413 | 0 | shape_{1}, |
414 | 0 | strides_(checked_contiguous_strides(shape_)) { |
415 | 0 | init_backend(1); |
416 | 0 | if (mode == QuantizationMode::FP32) { |
417 | 0 | data_fp32()[0] = static_cast<float>(scalar); |
418 | 0 | } else if (mode == QuantizationMode::FP16) { |
419 | 0 | uint16_t encoded = quantize_fp16(static_cast<float>(scalar)); |
420 | 0 | std::memcpy(&data_fp16()[0], &encoded, sizeof(uint16_t)); |
421 | 0 | } else if (mode == QuantizationMode::INT8) { |
422 | 0 | data_int8()[0] = static_cast<int8_t>( |
423 | 0 | std::max(-128, std::min(127, scalar)) |
424 | 0 | ); |
425 | 0 | } else if (mode == QuantizationMode::INT16) { |
426 | 0 | data_int16()[0] = static_cast<int16_t>( |
427 | 0 | std::max(-32768, std::min(32767, scalar)) |
428 | 0 | ); |
429 | 0 | } else if (mode == QuantizationMode::BOOL) { |
430 | 0 | data_bool()[0] = scalar != 0 ? 1 : 0; |
431 | 0 | } |
432 | 0 | } |
433 | | |
434 | 6.71k | Tensor::~Tensor() = default; |
435 | | |
436 | | Tensor::Tensor(const Tensor& other) |
437 | 285 | : quantization_mode_(other.quantization_mode_), |
438 | 285 | backend_(other.backend_ ? other.backend_->clone() : nullptr), |
439 | 285 | storage_(backend_ ? backend_->storage_ : nullptr), |
440 | 285 | shape_(other.shape_), |
441 | 285 | strides_(other.strides_), |
442 | 285 | storage_offset_(0) {} |
443 | | |
444 | 0 | Tensor& Tensor::operator=(const Tensor& other) { |
445 | 0 | if (this != &other) { |
446 | 0 | std::unique_ptr<TensorBackend> copied_backend = |
447 | 0 | other.backend_ ? other.backend_->clone() : nullptr; |
448 | 0 | std::vector<std::size_t> copied_shape = other.shape_; |
449 | 0 | std::vector<std::size_t> copied_strides = other.strides_; |
450 | 0 | quantization_mode_ = other.quantization_mode_; |
451 | 0 | backend_ = std::move(copied_backend); |
452 | 0 | storage_ = backend_ ? backend_->storage_ : nullptr; |
453 | 0 | shape_ = std::move(copied_shape); |
454 | 0 | strides_ = std::move(copied_strides); |
455 | 0 | storage_offset_ = 0; |
456 | 0 | } |
457 | 0 | return *this; |
458 | 0 | } |
459 | | |
460 | | Tensor::Tensor(Tensor&& other) noexcept |
461 | 2.32k | : quantization_mode_(other.quantization_mode_), |
462 | 2.32k | backend_(std::move(other.backend_)), |
463 | 2.32k | storage_(std::move(other.storage_)), |
464 | 2.32k | shape_(std::move(other.shape_)), |
465 | 2.32k | strides_(std::move(other.strides_)), |
466 | 2.32k | storage_offset_(other.storage_offset_) { |
467 | 2.32k | other.storage_offset_ = 0; |
468 | 2.32k | } |
469 | | |
470 | 0 | Tensor& Tensor::operator=(Tensor&& other) noexcept { |
471 | 0 | if (this != &other) { |
472 | 0 | quantization_mode_ = other.quantization_mode_; |
473 | 0 | backend_ = std::move(other.backend_); |
474 | 0 | storage_ = std::move(other.storage_); |
475 | 0 | shape_ = std::move(other.shape_); |
476 | 0 | strides_ = std::move(other.strides_); |
477 | 0 | storage_offset_ = other.storage_offset_; |
478 | 0 | other.storage_offset_ = 0; |
479 | 0 | } |
480 | 0 | return *this; |
481 | 0 | } |
482 | | |
483 | 178k | std::size_t Tensor::size() const { |
484 | 178k | return backend_ ? backend_->size() : 0; |
485 | 178k | } |
486 | | |
487 | 701 | bool Tensor::is_contiguous() const { |
488 | 701 | return strides_ == checked_contiguous_strides(shape_); |
489 | 701 | } |
490 | | |
491 | 15.9k | float* Tensor::data_fp32() { |
492 | 15.9k | return backend_ ? backend_->data_fp32() : nullptr; |
493 | 15.9k | } |
494 | | |
495 | 0 | const float* Tensor::data_fp32() const { |
496 | 0 | return backend_ ? backend_->data_fp32() : nullptr; |
497 | 0 | } |
498 | | |
499 | 3.65k | int8_t* Tensor::data_int8() { |
500 | 3.65k | return backend_ ? backend_->data_int8() : nullptr; |
501 | 3.65k | } |
502 | | |
503 | 0 | const int8_t* Tensor::data_int8() const { |
504 | 0 | return backend_ ? backend_->data_int8() : nullptr; |
505 | 0 | } |
506 | | |
507 | 1.87k | int16_t* Tensor::data_fp16() { |
508 | 1.87k | return backend_ ? backend_->data_fp16() : nullptr; |
509 | 1.87k | } |
510 | | |
511 | 0 | const int16_t* Tensor::data_fp16() const { |
512 | 0 | return backend_ ? backend_->data_fp16() : nullptr; |
513 | 0 | } |
514 | | |
515 | 1.46k | int16_t* Tensor::data_int16() { |
516 | 1.46k | return backend_ ? backend_->data_int16() : nullptr; |
517 | 1.46k | } |
518 | | |
519 | 0 | const int16_t* Tensor::data_int16() const { |
520 | 0 | return backend_ ? backend_->data_int16() : nullptr; |
521 | 0 | } |
522 | | |
523 | 955 | std::uint8_t* Tensor::data_bool() { |
524 | 955 | return backend_ ? backend_->data_bool() : nullptr; |
525 | 955 | } |
526 | | |
527 | 0 | const std::uint8_t* Tensor::data_bool() const { |
528 | 0 | return backend_ |
529 | 0 | ? static_cast<const TensorBackend&>(*backend_).data_bool() |
530 | 0 | : nullptr; |
531 | 0 | } |
532 | | |
533 | 109 | Tensor Tensor::add(const Tensor& other) const { |
534 | 109 | return binary_op(other, OperationType::ADD); |
535 | 109 | } |
536 | | |
537 | 11 | void Tensor::add_into(const Tensor& other, Tensor& out) const { |
538 | 11 | if (quantization_mode_ != QuantizationMode::FP32 || |
539 | 11 | other.quantization_mode_ != QuantizationMode::FP32 || |
540 | 11 | out.quantization_mode_ != QuantizationMode::FP32) { |
541 | 2 | throw std::invalid_argument("add_into requires FP32 tensors"); |
542 | 2 | } |
543 | 9 | if (!backend_ || !other.backend_ || !out.backend_) { |
544 | 0 | throw std::runtime_error("Tensor backend not initialized"); |
545 | 0 | } |
546 | 9 | if (shape_ != other.shape_ || shape_ != out.shape_) { |
547 | 2 | throw std::invalid_argument("add_into requires identical tensor shapes"); |
548 | 2 | } |
549 | 7 | const TensorBackend& input_backend = *backend_; |
550 | 7 | const TensorBackend& other_backend = *other.backend_; |
551 | 7 | const TensorBackend& output_backend = *out.backend_; |
552 | 7 | if (typeid(input_backend) != typeid(other_backend) || |
553 | 7 | typeid(input_backend) != typeid(output_backend)) { |
554 | 0 | throw std::invalid_argument( |
555 | 0 | "add_into requires all tensors to use the same backend"); |
556 | 0 | } |
557 | 13 | const auto partially_overlaps = [](const Tensor& lhs, const Tensor& rhs) { |
558 | 13 | if (lhs.storage_.get() != rhs.storage_.get() || |
559 | 13 | lhs.storage_offset_ == rhs.storage_offset_) { |
560 | 12 | return false; |
561 | 12 | } |
562 | 1 | const std::size_t lhs_offset = lhs.storage_offset_; |
563 | 1 | const std::size_t rhs_offset = rhs.storage_offset_; |
564 | 1 | return lhs_offset < rhs_offset |
565 | 1 | ? rhs_offset - lhs_offset < lhs.numel() |
566 | 1 | : lhs_offset - rhs_offset < lhs.numel(); |
567 | 13 | }; |
568 | 7 | if (partially_overlaps(*this, out) || |
569 | 7 | partially_overlaps(other, out)) { |
570 | 1 | throw std::invalid_argument( |
571 | 1 | "add_into does not support partially overlapping storage ranges"); |
572 | 1 | } |
573 | 6 | if (!backend_->operation_into(*other.backend_, *out.backend_, OperationType::ADD)) { |
574 | 0 | throw std::runtime_error( |
575 | 0 | "FP32 ADD into an existing output is not supported by this backend"); |
576 | 0 | } |
577 | 6 | } |
578 | | |
579 | 58 | Tensor Tensor::mul(const Tensor& other) const { |
580 | 58 | return binary_op(other, OperationType::MUL); |
581 | 58 | } |
582 | | |
583 | 56 | Tensor Tensor::sub(const Tensor& other) const { |
584 | 56 | return binary_op(other, OperationType::SUB); |
585 | 56 | } |
586 | | |
587 | 140 | Tensor Tensor::div(const Tensor& other) const { |
588 | 140 | return binary_op(other, OperationType::DIV); |
589 | 140 | } |
590 | | |
591 | 95 | Tensor Tensor::eq(const Tensor& other) const { |
592 | 95 | return comparison_op(other, ComparisonType::EQ); |
593 | 95 | } |
594 | | |
595 | 92 | Tensor Tensor::ne(const Tensor& other) const { |
596 | 92 | return comparison_op(other, ComparisonType::NE); |
597 | 92 | } |
598 | | |
599 | 93 | Tensor Tensor::lt(const Tensor& other) const { |
600 | 93 | return comparison_op(other, ComparisonType::LT); |
601 | 93 | } |
602 | | |
603 | 92 | Tensor Tensor::le(const Tensor& other) const { |
604 | 92 | return comparison_op(other, ComparisonType::LE); |
605 | 92 | } |
606 | | |
607 | 92 | Tensor Tensor::gt(const Tensor& other) const { |
608 | 92 | return comparison_op(other, ComparisonType::GT); |
609 | 92 | } |
610 | | |
611 | 92 | Tensor Tensor::ge(const Tensor& other) const { |
612 | 92 | return comparison_op(other, ComparisonType::GE); |
613 | 92 | } |
614 | | |
615 | 556 | Tensor Tensor::comparison_op(const Tensor& other, ComparisonType comparison) const { |
616 | 556 | if (!backend_ || !other.backend_) { |
617 | 0 | throw std::runtime_error("Tensor backend not initialized"); |
618 | 0 | } |
619 | 556 | if (quantization_mode_ != other.quantization_mode_) { |
620 | 1 | throw std::runtime_error("Quantization mode mismatch"); |
621 | 1 | } |
622 | 555 | if (quantization_mode_ == QuantizationMode::BOOL) { |
623 | 1 | throw std::runtime_error( |
624 | 1 | "Tensor comparisons are not supported for BOOL tensors"); |
625 | 1 | } |
626 | 554 | if (quantization_mode_ != QuantizationMode::FP32 && |
627 | 554 | quantization_mode_ != QuantizationMode::FP16 && |
628 | 554 | quantization_mode_ != QuantizationMode::INT16 && |
629 | 554 | quantization_mode_ != QuantizationMode::INT8) { |
630 | 0 | throw std::runtime_error( |
631 | 0 | "Tensor comparisons support FP32, FP16, INT16, and INT8 tensors"); |
632 | 0 | } |
633 | | |
634 | 554 | const auto* lhs_generic = |
635 | 554 | dynamic_cast<const GenericBackend*>(backend_.get()); |
636 | 554 | const auto* rhs_generic = |
637 | 554 | dynamic_cast<const GenericBackend*>(other.backend_.get()); |
638 | | #if defined(LABNEURA_ENABLE_NEON) |
639 | | const auto* lhs_neon = dynamic_cast<const NEONBackend*>(backend_.get()); |
640 | | const auto* rhs_neon = |
641 | | dynamic_cast<const NEONBackend*>(other.backend_.get()); |
642 | | #endif |
643 | 554 | #if defined(LABNEURA_ENABLE_AVX2) |
644 | 554 | const auto* lhs_avx2 = dynamic_cast<const AVX2Backend*>(backend_.get()); |
645 | 554 | const auto* rhs_avx2 = |
646 | 554 | dynamic_cast<const AVX2Backend*>(other.backend_.get()); |
647 | 554 | #endif |
648 | 554 | const bool generic_pair = lhs_generic && rhs_generic; |
649 | | #if defined(LABNEURA_ENABLE_NEON) |
650 | | const bool neon_pair = lhs_neon && rhs_neon; |
651 | | #endif |
652 | 554 | #if defined(LABNEURA_ENABLE_AVX2) |
653 | 554 | const bool avx2_pair = lhs_avx2 && rhs_avx2; |
654 | 554 | #endif |
655 | 554 | if (!generic_pair |
656 | | #if defined(LABNEURA_ENABLE_NEON) |
657 | | && !neon_pair |
658 | | #endif |
659 | 554 | #if defined(LABNEURA_ENABLE_AVX2) |
660 | 554 | && !avx2_pair |
661 | 554 | #endif |
662 | 554 | ) { |
663 | 0 | throw std::runtime_error( |
664 | 0 | "Tensor comparisons are only supported when both tensors use the same Generic, NEON, or AVX2 backend"); |
665 | 0 | } |
666 | | |
667 | 554 | detail::BroadcastPlan plan; |
668 | 554 | try { |
669 | 554 | plan = detail::make_broadcast_plan( |
670 | 554 | shape_, strides_, other.shape_, other.strides_); |
671 | 554 | } catch (const std::invalid_argument& error) { |
672 | 1 | throw std::runtime_error( |
673 | 1 | std::string("Tensor shape mismatch: ") + error.what()); |
674 | 1 | } |
675 | 553 | const std::size_t output_numel = |
676 | 553 | detail::checked_broadcast_numel(plan.shape); |
677 | 553 | std::unique_ptr<TensorBackend> output_backend; |
678 | 553 | if (generic_pair) { |
679 | 325 | auto generic_output = |
680 | 325 | std::make_unique<GenericBackend>(output_numel, |
681 | 325 | QuantizationMode::BOOL); |
682 | 325 | lhs_generic->compare_broadcast( |
683 | 325 | *rhs_generic, *generic_output, plan, comparison, numel(), |
684 | 325 | other.numel()); |
685 | 325 | output_backend = std::move(generic_output); |
686 | | #if defined(LABNEURA_ENABLE_NEON) |
687 | | } else if (neon_pair) { |
688 | | auto neon_output = |
689 | | std::make_unique<NEONBackend>(output_numel, QuantizationMode::BOOL); |
690 | | lhs_neon->compare_broadcast(*rhs_neon, *neon_output, plan, comparison, |
691 | | numel(), other.numel()); |
692 | | output_backend = std::move(neon_output); |
693 | | #endif |
694 | 325 | #if defined(LABNEURA_ENABLE_AVX2) |
695 | 325 | } else if (avx2_pair) { |
696 | 228 | auto avx2_output = |
697 | 228 | std::make_unique<AVX2Backend>(output_numel, QuantizationMode::BOOL); |
698 | 228 | lhs_avx2->compare_broadcast(*rhs_avx2, *avx2_output, plan, comparison, |
699 | 228 | numel(), other.numel()); |
700 | 228 | output_backend = std::move(avx2_output); |
701 | 228 | #endif |
702 | 228 | } |
703 | 553 | return Tensor(QuantizationMode::BOOL, std::move(output_backend), |
704 | 553 | std::move(plan.shape)); |
705 | 554 | } |
706 | | |
707 | 363 | Tensor Tensor::binary_op(const Tensor& other, OperationType op) const { |
708 | 363 | if (backend_ && other.backend_) { |
709 | 363 | const auto* lhs_generic = |
710 | 363 | dynamic_cast<const GenericBackend*>(backend_.get()); |
711 | 363 | const auto* rhs_generic = |
712 | 363 | dynamic_cast<const GenericBackend*>(other.backend_.get()); |
713 | 363 | const bool generic_broadcast = |
714 | 363 | shape_ != other.shape_ && |
715 | 363 | quantization_mode_ == other.quantization_mode_ && |
716 | 363 | (quantization_mode_ == QuantizationMode::FP32 || |
717 | 21 | quantization_mode_ == QuantizationMode::FP16 || |
718 | 21 | quantization_mode_ == QuantizationMode::INT8 || |
719 | 21 | quantization_mode_ == QuantizationMode::INT16) && |
720 | 363 | lhs_generic && rhs_generic; |
721 | 363 | if (shape_ != other.shape_ && !generic_broadcast) { |
722 | 5 | check_same_shape(other); |
723 | 5 | } |
724 | 363 | if (generic_broadcast) { |
725 | 16 | detail::BroadcastPlan plan; |
726 | 16 | try { |
727 | 16 | plan = detail::make_broadcast_plan( |
728 | 16 | shape_, strides_, other.shape_, other.strides_); |
729 | 16 | } catch (const std::invalid_argument& error) { |
730 | 0 | throw std::runtime_error( |
731 | 0 | std::string("Tensor shape mismatch: ") + error.what()); |
732 | 0 | } |
733 | 16 | if (quantization_mode_ != other.quantization_mode_) { |
734 | 0 | throw std::runtime_error("Quantization mode mismatch"); |
735 | 0 | } |
736 | 16 | const std::size_t output_numel = |
737 | 16 | detail::checked_broadcast_numel(plan.shape); |
738 | 16 | auto output_backend = |
739 | 16 | std::make_unique<GenericBackend>(output_numel, |
740 | 16 | quantization_mode_); |
741 | 16 | lhs_generic->operation_broadcast( |
742 | 16 | *rhs_generic, *output_backend, plan, op, numel(), other.numel()); |
743 | 16 | return Tensor(quantization_mode_, std::move(output_backend), |
744 | 16 | std::move(plan.shape)); |
745 | 16 | } |
746 | 347 | if (auto out = backend_->operation_new(*other.backend_, op)) { |
747 | 107 | return Tensor(quantization_mode_, std::move(out), shape_); |
748 | 107 | } |
749 | 347 | } |
750 | | |
751 | 240 | Tensor result(*this); |
752 | 240 | switch (op) { |
753 | 52 | case OperationType::ADD: result.add_inplace(other); break; |
754 | 41 | case OperationType::SUB: result.sub_inplace(other); break; |
755 | 41 | case OperationType::MUL: result.mul_inplace(other); break; |
756 | 100 | default: result.div_inplace(other); break; |
757 | 240 | } |
758 | 234 | return result; |
759 | 240 | } |
760 | | |
761 | 480 | void Tensor::add_inplace(const Tensor& other) { |
762 | 480 | binary_inplace(other, OperationType::ADD); |
763 | 480 | } |
764 | | |
765 | 228 | void Tensor::mul_inplace(const Tensor& other) { |
766 | 228 | binary_inplace(other, OperationType::MUL); |
767 | 228 | } |
768 | | |
769 | 176 | void Tensor::sub_inplace(const Tensor& other) { |
770 | 176 | binary_inplace(other, OperationType::SUB); |
771 | 176 | } |
772 | | |
773 | 165 | void Tensor::div_inplace(const Tensor& other) { |
774 | 165 | binary_inplace(other, OperationType::DIV); |
775 | 165 | } |
776 | | |
777 | 1.04k | void Tensor::binary_inplace(const Tensor& other, OperationType op) { |
778 | 1.04k | if (!backend_ || !other.backend_) { |
779 | 0 | throw std::runtime_error("Tensor backend not initialized"); |
780 | 0 | } |
781 | 1.04k | auto* lhs_backend = dynamic_cast<GenericBackend*>(backend_.get()); |
782 | 1.04k | const auto* rhs_backend = |
783 | 1.04k | dynamic_cast<const GenericBackend*>(other.backend_.get()); |
784 | 1.04k | const bool generic_broadcast = |
785 | 1.04k | shape_ != other.shape_ && |
786 | 1.04k | quantization_mode_ == other.quantization_mode_ && |
787 | 1.04k | (quantization_mode_ == QuantizationMode::FP32 || |
788 | 24 | quantization_mode_ == QuantizationMode::FP16 || |
789 | 24 | quantization_mode_ == QuantizationMode::INT8 || |
790 | 24 | quantization_mode_ == QuantizationMode::INT16) && |
791 | 1.04k | lhs_backend && rhs_backend; |
792 | 1.04k | if (shape_ == other.shape_ || !generic_broadcast) { |
793 | 1.03k | check_same_shape(other); |
794 | 1.03k | backend_->operation(*other.backend_, op); |
795 | 1.03k | return; |
796 | 1.03k | } |
797 | | |
798 | 12 | detail::BroadcastPlan plan; |
799 | 12 | try { |
800 | 12 | plan = detail::make_broadcast_plan( |
801 | 12 | shape_, strides_, other.shape_, other.strides_); |
802 | 12 | } catch (const std::invalid_argument& error) { |
803 | 0 | throw std::runtime_error( |
804 | 0 | std::string("Tensor shape mismatch: ") + error.what()); |
805 | 0 | } |
806 | 12 | if (plan.shape != shape_) { |
807 | 4 | throw std::runtime_error( |
808 | 4 | "Tensor shape mismatch: in-place broadcasting cannot expand the destination"); |
809 | 4 | } |
810 | 8 | if (quantization_mode_ != other.quantization_mode_) { |
811 | 0 | throw std::runtime_error("Quantization mode mismatch"); |
812 | 0 | } |
813 | 8 | const bool shares_storage = storage_.get() == other.storage_.get(); |
814 | 8 | if (shares_storage && size() != 0 && other.size() != 0) { |
815 | 0 | const std::size_t lhs_offset = storage_offset_; |
816 | 0 | const std::size_t rhs_offset = other.storage_offset_; |
817 | 0 | const bool overlaps = |
818 | 0 | lhs_offset <= rhs_offset |
819 | 0 | ? rhs_offset - lhs_offset < size() |
820 | 0 | : lhs_offset - rhs_offset < other.size(); |
821 | 0 | const bool exact_elementwise_alias = |
822 | 0 | lhs_offset == rhs_offset && |
823 | 0 | plan.lhs_strides == plan.rhs_strides; |
824 | 0 | if (overlaps && !exact_elementwise_alias) { |
825 | 0 | throw std::invalid_argument( |
826 | 0 | "In-place operation does not support partially overlapping tensor views"); |
827 | 0 | } |
828 | 0 | } |
829 | | |
830 | 8 | lhs_backend->operation_broadcast( |
831 | 8 | *rhs_backend, *lhs_backend, plan, op, numel(), other.numel()); |
832 | 8 | } |
833 | | |
834 | 1.04k | void Tensor::check_same_shape(const Tensor& other) const { |
835 | | // Different element counts are reported by the backend as a size mismatch. |
836 | 1.04k | if (size() == other.size() && shape_ != other.shape_) { |
837 | 3 | throw std::runtime_error("Tensor shape mismatch"); |
838 | 3 | } |
839 | 1.04k | } |
840 | | |
841 | 3.31k | void Tensor::init_backend(std::size_t size) { |
842 | 3.31k | validate_tensor_dtype_supported(quantization_mode_); |
843 | 3.31k | validate_allocation_size(size, quantization_mode_); |
844 | 3.31k | backend_ = create_best_backend(size, quantization_mode_); |
845 | 3.31k | storage_ = backend_ ? backend_->storage_ : nullptr; |
846 | 3.31k | } |
847 | | |
848 | 3.13k | std::size_t Tensor::checked_numel(const std::vector<std::size_t>& shape) { |
849 | 3.13k | return checked_shape_numel(shape); |
850 | 3.13k | } |
851 | | |
852 | | std::vector<std::size_t> Tensor::checked_contiguous_strides( |
853 | 6.08k | const std::vector<std::size_t>& shape) { |
854 | 6.08k | std::vector<std::size_t> strides(shape.size()); |
855 | 6.08k | std::size_t stride = 1; |
856 | 13.2k | for (std::size_t axis = shape.size(); axis > 0; --axis) { |
857 | 7.21k | const std::size_t index = axis - 1; |
858 | 7.21k | strides[index] = stride; |
859 | 7.21k | if (shape[index] != 0 && |
860 | 7.21k | stride > std::numeric_limits<std::size_t>::max() / shape[index]) { |
861 | 1 | throw std::overflow_error( |
862 | 1 | "Tensor row-major stride overflows size_t"); |
863 | 1 | } |
864 | 7.21k | stride *= shape[index]; |
865 | 7.21k | } |
866 | 6.08k | return strides; |
867 | 6.08k | } |
868 | | |
869 | | void Tensor::validate_allocation_size(std::size_t size, |
870 | 4.59k | QuantizationMode mode) { |
871 | 4.59k | check_allocation_size(size, mode); |
872 | 4.59k | } |
873 | | |
874 | | } // namespace labneura |