burn-std 0.22.0-pre.3

Core types and utilities shared across the Burn ecosystem.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use alloc::boxed::Box;
use alloc::vec;
use alloc::vec::Vec;

use bytemuck::{AnyBitPattern, CheckedBitPattern, Zeroable, cast_mut};

use crate::element::{Element, ElementConversion};
use crate::tensor::DType;
use crate::{
    BoolStore, QuantMode, QuantScheme, QuantValue, QuantizedBytes, Reader, Writer, bf16, f16,
};

use super::{DataError, TensorData};

impl TensorData {
    /// Copies and converts the data to a [`Vec<E>`].
    ///
    /// By contract, this is equivalent to:
    /// `data.clone().try_into_vec_as::<E>()`
    ///
    /// Particular conversions may provide more efficient implementations.
    ///
    /// # Errors
    ///
    /// Returns an error if storage access fails, the conversion isn't supported, or the stored
    /// representation or element count is invalid.
    pub fn try_to_vec_as<E: Element>(&self) -> Result<Vec<E>, DataError> {
        self.clone().try_into_vec_as::<E>()
    }

    /// Converts the data to a [`Vec<E>`].
    ///
    /// By contract, this is equivalent to:
    /// `data.try_cast_as::<E>()?.try_into_vec::<E>()`
    ///
    /// Particular conversions may provide more efficient implementations.
    ///
    /// # Errors
    ///
    /// Returns an error if storage access fails, the conversion isn't supported, or the stored
    /// representation or element count is invalid.
    pub fn try_into_vec_as<E: Element>(self) -> Result<Vec<E>, DataError> {
        self.try_cast_as::<E>()?.into_vec_unchecked::<E>()
    }

    /// Copies the stored values to a vector without dtype conversion.
    #[deprecated(since = "0.22.0", note = "use try_to_vec::<E>()")]
    pub fn to_vec<E: Element>(&self) -> Result<Vec<E>, DataError> {
        self.try_to_vec::<E>()
    }

    /// Converts the stored values into a vector without dtype conversion.
    #[deprecated(since = "0.22.0", note = "use try_into_vec::<E>()")]
    pub fn into_vec<E: Element>(self) -> Result<Vec<E>, DataError> {
        self.try_into_vec::<E>()
    }

    /// Copies the stored values to a vector without dtype conversion.
    ///
    /// # Errors
    ///
    /// Returns an error if storage access fails, the stored dtype doesn't match `E`, or the byte
    /// representation is invalid for `E`.
    pub fn try_to_vec<E: Element>(&self) -> Result<Vec<E>, DataError> {
        Ok(self.as_slice()?.to_vec())
    }

    /// Converts the stored values into a vector without dtype conversion.
    ///
    /// This may reuse the underlying allocation when its layout and ownership permit it.
    ///
    /// # Errors
    ///
    /// Returns an error if storage access fails, the stored dtype doesn't match `E`, or the byte
    /// representation is invalid for `E`.
    pub fn try_into_vec<E: Element>(self) -> Result<Vec<E>, DataError> {
        // This means we cannot call `into_vec` for QFloat
        if !self.matches_target_dtype::<E>() {
            return Err(DataError::dtype_mismatch_as::<E>(self.dtype));
        }

        self.into_vec_unchecked()
    }

    /// Returns the tensor data as a vector of scalar values. Does not check dtype.
    fn into_vec_unchecked<E: Element>(self) -> Result<Vec<E>, DataError> {
        let mut me = self;
        me.bytes.read(Reader::new())?;
        me.bytes = match me.bytes.try_into_vec::<E>() {
            Ok(elems) => return Ok(elems),
            Err(bytes) => bytes,
        };

        // The bytes might have been deserialized and allocated with a different align.
        // In that case, we have to memcopy the data into a new vector, more suitably allocated
        Ok(
            bytemuck::checked::try_cast_slice(me.bytes.read(Reader::new())?)
                .map_err(DataError::InvalidRepresentation)?
                .to_vec(),
        )
    }

    /// Returns an iterator over the values of the tensor data.
    pub fn iter<E: Element>(&self) -> Box<dyn Iterator<Item = E> + '_> {
        if E::dtype() == self.dtype {
            Box::new(bytemuck::checked::cast_slice(&self.bytes).iter().copied())
        } else {
            match self.dtype {
                DType::I8 => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &i8| e.elem::<E>()),
                ),
                DType::I16 => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &i16| e.elem::<E>()),
                ),
                DType::I32 => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &i32| e.elem::<E>()),
                ),
                DType::I64 => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &i64| e.elem::<E>()),
                ),
                DType::U8 => Box::new(self.bytes.iter().map(|e| e.elem::<E>())),
                DType::U16 => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &u16| e.elem::<E>()),
                ),
                DType::U32 => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &u32| e.elem::<E>()),
                ),
                DType::U64 => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &u64| e.elem::<E>()),
                ),
                DType::BF16 => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &bf16| e.elem::<E>()),
                ),
                DType::F16 => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &f16| e.elem::<E>()),
                ),
                DType::F32 | DType::Flex32 => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &f32| e.elem::<E>()),
                ),
                DType::F64 => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &f64| e.elem::<E>()),
                ),
                // bool is a byte value equal to either 0 or 1
                DType::Bool(BoolStore::Native) | DType::Bool(BoolStore::U8) => {
                    Box::new(self.bytes.iter().map(|e| e.elem::<E>()))
                }
                DType::Bool(BoolStore::U32) => Box::new(
                    bytemuck::checked::cast_slice(&self.bytes)
                        .iter()
                        .map(|e: &u32| e.elem::<E>()),
                ),
                DType::QFloat(scheme) => match scheme {
                    QuantScheme {
                        mode: QuantMode::Symmetric,
                        value:
                            QuantValue::Q8F
                            | QuantValue::Q8S
                            // Represent sub-byte values as i8
                            | QuantValue::Q4F
                            | QuantValue::Q4S
                            | QuantValue::Q2F
                            | QuantValue::Q2S,
                        ..
                    } => {
                        // Quantized int8 values
                        let q_bytes = QuantizedBytes {
                            bytes: self.bytes.clone(),
                            scheme,
                            shape: self.shape.clone(),
                        };
                        let (values, _) = q_bytes.into_vec_i8();

                        Box::new(
                            values
                                .iter()
                                .map(|e: &i8| e.elem::<E>())
                                .collect::<Vec<_>>()
                                .into_iter(),
                        )
                    }
                    QuantScheme {
                        mode: QuantMode::Symmetric,
                        value:
                            QuantValue::E4M3 | QuantValue::E5M2 | QuantValue::E2M1,
                        ..
                    } => {
                        unimplemented!("Not yet implemented for iteration");
                    }
                    QuantScheme {
                        mode: QuantMode::Lookup,
                        ..
                    } => {
                        unimplemented!("lookup quantization is not supported for iteration");
                    }
                },
            }
        }
    }

    /// Converts the data to the dtype represented by `E`.
    ///
    /// # Panics
    ///
    /// Panics if storage access fails, the conversion isn't supported, or the stored
    /// representation or element count is invalid.
    #[track_caller]
    pub fn convert<E: Element>(self) -> Self {
        // TODO: deprecate?
        self.try_cast_as::<E>()
            .unwrap_or_else(|err| panic!("Failed to convert TensorData: {err}"))
    }

    /// Converts the data to `dtype`.
    ///
    /// # Panics
    ///
    /// Panics if storage access fails, the conversion isn't supported, or the stored
    /// representation or element count is invalid.
    #[track_caller]
    pub fn convert_dtype(self, dtype: DType) -> Self {
        // TODO: deprecate?
        self.try_cast(dtype)
            .unwrap_or_else(|err| panic!("Failed to convert TensorData to {dtype:?}: {err}"))
    }

    /// Converts the data to the dtype represented by `E`.
    ///
    /// By contract, this is equivalent to:
    /// `data.try_cast(E::dtype())`
    ///
    /// # Errors
    ///
    /// Returns an error if storage access fails, the conversion isn't supported, or the stored
    /// representation or element count is invalid.
    pub fn try_cast_as<E: Element>(self) -> Result<TensorData, DataError> {
        self.try_cast(E::dtype())
    }

    /// Converts the data to `dtype`.
    ///
    /// # Errors
    ///
    /// Returns an error if storage access fails, the conversion isn't supported, or the stored
    /// representation or element count is invalid.
    pub fn try_cast(self, dtype: DType) -> Result<TensorData, DataError> {
        if dtype == self.dtype {
            Ok(self)
        } else if dtype.size() == self.dtype.size()
            && !matches!(
                self.dtype,
                DType::Bool(BoolStore::Native) | DType::QFloat(_)
            )
            && !matches!(dtype, DType::Bool(BoolStore::Native) | DType::QFloat(_))
        {
            self.try_cast_inplace(dtype)
        } else {
            self.try_cast_clone(dtype)
        }
    }

    // Self-to-Self casts should be stripped before this point.
    fn try_cast_inplace(self, dtype: DType) -> Result<TensorData, DataError> {
        // Convert self.dtype to generic parameter:
        match self.dtype {
            DType::F64 => self.try_cast_inplace_from::<f64>(dtype),
            DType::F32 | DType::Flex32 => self.try_cast_inplace_from::<f32>(dtype),
            DType::F16 => self.try_cast_inplace_from::<f16>(dtype),
            DType::BF16 => self.try_cast_inplace_from::<bf16>(dtype),
            DType::I64 => self.try_cast_inplace_from::<i64>(dtype),
            DType::I32 => self.try_cast_inplace_from::<i32>(dtype),
            DType::I16 => self.try_cast_inplace_from::<i16>(dtype),
            DType::I8 => self.try_cast_inplace_from::<i8>(dtype),
            DType::U64 => self.try_cast_inplace_from::<u64>(dtype),
            DType::U32 => self.try_cast_inplace_from::<u32>(dtype),
            DType::U16 => self.try_cast_inplace_from::<u16>(dtype),
            DType::U8 => self.try_cast_inplace_from::<u8>(dtype),
            DType::Bool(BoolStore::U8) => self.try_cast_inplace_from::<u8>(dtype),
            DType::Bool(BoolStore::U32) => self.try_cast_inplace_from::<u32>(dtype),
            DType::Bool(BoolStore::Native) | DType::QFloat(_) => Err(DataError::DTypeMismatch {
                expected: dtype,
                actual: self.dtype,
            }),
        }
    }

    fn try_cast_inplace_from<Current>(self, dtype: DType) -> Result<TensorData, DataError>
    where
        Current: Element + AnyBitPattern,
    {
        // Convert target dtype to generic parameter.
        match dtype {
            DType::F64 => self.try_convert_inplace::<Current, f64>(),
            DType::F32 | DType::Flex32 => self.try_convert_inplace::<Current, f32>(),
            DType::F16 => self.try_convert_inplace::<Current, f16>(),
            DType::BF16 => self.try_convert_inplace::<Current, bf16>(),
            DType::I64 => self.try_convert_inplace::<Current, i64>(),
            DType::I32 => self.try_convert_inplace::<Current, i32>(),
            DType::I16 => self.try_convert_inplace::<Current, i16>(),
            DType::I8 => self.try_convert_inplace::<Current, i8>(),
            DType::U64 => self.try_convert_inplace::<Current, u64>(),
            DType::U32 => self.try_convert_inplace::<Current, u32>(),
            DType::U16 => self.try_convert_inplace::<Current, u16>(),
            DType::U8 => self.try_convert_inplace::<Current, u8>(),
            DType::Bool(BoolStore::U8) => self
                .try_convert_inplace_bool::<Current, u8>()
                .map(TensorData::into_bool_u8),
            DType::Bool(BoolStore::U32) => self
                .try_convert_inplace_bool::<Current, u32>()
                .map(TensorData::into_bool_u32),
            DType::Bool(BoolStore::Native) | DType::QFloat(_) => Err(DataError::DTypeMismatch {
                expected: dtype,
                actual: Current::dtype(),
            }),
        }
    }

    fn try_convert_inplace<Current, Target>(self) -> Result<TensorData, DataError>
    where
        Current: Element + AnyBitPattern,
        Target: Element + AnyBitPattern,
    {
        self.try_convert_inplace_with::<Current, Target>(|x| x.elem())
    }

    fn try_convert_inplace_bool<Current, Target>(self) -> Result<TensorData, DataError>
    where
        Current: Element + AnyBitPattern,
        Target: Element + AnyBitPattern,
    {
        self.try_convert_inplace_with::<Current, Target>(|x| x.to_bool().elem())
    }

    fn try_convert_inplace_with<Current, Target>(
        mut self,
        transform: impl Fn(&Current) -> Target,
    ) -> Result<TensorData, DataError>
    where
        Current: Element + AnyBitPattern,
        Target: Element + AnyBitPattern,
    {
        let expected = self.num_elements();
        let values =
            bytemuck::checked::try_cast_slice_mut::<_, Current>(self.bytes.write(Writer::new())?)
                .map_err(DataError::InvalidRepresentation)?;
        let actual = values.len();
        if actual != expected {
            return Err(DataError::ElementCountMismatch { expected, actual });
        }

        for x in values {
            let t = transform(x);
            let x = cast_mut::<_, Target>(x);
            *x = t;
        }

        self.dtype = Target::dtype();

        Ok(self)
    }

    fn try_cast_clone(self, dtype: DType) -> Result<TensorData, DataError> {
        // Convert self.dtype to generic parameter:
        match self.dtype {
            DType::F64 => self.try_cast_clone_from::<f64>(dtype),
            DType::F32 | DType::Flex32 => self.try_cast_clone_from::<f32>(dtype),
            DType::F16 => self.try_cast_clone_from::<f16>(dtype),
            DType::BF16 => self.try_cast_clone_from::<bf16>(dtype),
            DType::I64 => self.try_cast_clone_from::<i64>(dtype),
            DType::I32 => self.try_cast_clone_from::<i32>(dtype),
            DType::I16 => self.try_cast_clone_from::<i16>(dtype),
            DType::I8 => self.try_cast_clone_from::<i8>(dtype),
            DType::U64 => self.try_cast_clone_from::<u64>(dtype),
            DType::U32 => self.try_cast_clone_from::<u32>(dtype),
            DType::U16 => self.try_cast_clone_from::<u16>(dtype),
            DType::U8 => self.try_cast_clone_from::<u8>(dtype),
            DType::Bool(BoolStore::Native) => self.try_cast_clone_from::<bool>(dtype),
            DType::Bool(BoolStore::U8) => self.try_cast_clone_from::<u8>(dtype),
            DType::Bool(BoolStore::U32) => self.try_cast_clone_from::<u32>(dtype),
            DType::QFloat(_) => Err(DataError::UnsupportedConversion {
                to: dtype,
                from: self.dtype,
            }),
        }
    }

    fn try_cast_clone_from<Current>(self, dtype: DType) -> Result<TensorData, DataError>
    where
        Current: Element + CheckedBitPattern,
    {
        // Convert target dtype to generic parameter.
        match dtype {
            DType::F64 => self.try_convert_clone::<Current, f64>(),
            DType::F32 | DType::Flex32 => self.try_convert_clone::<Current, f32>(),
            DType::F16 => self.try_convert_clone::<Current, f16>(),
            DType::BF16 => self.try_convert_clone::<Current, bf16>(),
            DType::I64 => self.try_convert_clone::<Current, i64>(),
            DType::I32 => self.try_convert_clone::<Current, i32>(),
            DType::I16 => self.try_convert_clone::<Current, i16>(),
            DType::I8 => self.try_convert_clone::<Current, i8>(),
            DType::U64 => self.try_convert_clone::<Current, u64>(),
            DType::U32 => self.try_convert_clone::<Current, u32>(),
            DType::U16 => self.try_convert_clone::<Current, u16>(),
            DType::U8 => self.try_convert_clone::<Current, u8>(),
            DType::Bool(BoolStore::Native) => self.try_convert_clone::<Current, bool>(),
            DType::Bool(BoolStore::U8) => self
                .try_convert_clone_bool::<Current, u8>()
                .map(TensorData::into_bool_u8),
            DType::Bool(BoolStore::U32) => self
                .try_convert_clone_bool::<Current, u32>()
                .map(TensorData::into_bool_u32),
            DType::QFloat(_) => Err(DataError::UnsupportedConversion {
                to: dtype,
                from: self.dtype,
            }),
        }
    }

    fn try_convert_clone<Current, Target>(self) -> Result<TensorData, DataError>
    where
        Current: Element + CheckedBitPattern,
        Target: Element + Zeroable,
    {
        self.try_convert_clone_with::<Current, Target>(|x| x.elem())
    }

    fn try_convert_clone_bool<Current, Target>(self) -> Result<TensorData, DataError>
    where
        Current: Element + CheckedBitPattern,
        Target: Element + Zeroable,
    {
        self.try_convert_clone_with::<Current, Target>(|x| x.to_bool().elem())
    }

    fn try_convert_clone_with<Current, Target>(
        self,
        transform: impl Fn(&Current) -> Target,
    ) -> Result<TensorData, DataError>
    where
        Current: Element + CheckedBitPattern,
        Target: Element + Zeroable,
    {
        let expected = self.num_elements();
        let values =
            bytemuck::checked::try_cast_slice::<_, Current>(self.bytes.read(Reader::new())?)
                .map_err(DataError::InvalidRepresentation)?;
        let actual = values.len();
        if actual != expected {
            return Err(DataError::ElementCountMismatch { expected, actual });
        }
        let mut out: Vec<Target> = vec![Zeroable::zeroed(); expected];

        for (value, out) in values.iter().zip(&mut out) {
            *out = transform(value);
        }

        Ok(TensorData::new(out, self.shape))
    }
}