bunsen 0.34.1

bunsen is a batteries included common library for burn
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
use std::ops::Range;

use burn::{
    Tensor,
    prelude::{
        Backend,
        ElementConversion,
        SliceArg,
        TensorData,
    },
    tensor::{
        AsIndex,
        BasicOps,
        Bool,
        DType,
        DataError,
        Element,
        Float,
        Int,
    },
};

/// Operation Extensions for `Tensor<B, D, K>`.
pub trait TensorOpExt<B, const D: usize, K>
where
    B: Backend,
    K: BasicOps<B>,
{
    /// Swap this tensor with another.
    fn swap(
        &mut self,
        other: &mut Self,
    );

    /// Drop the current value, and replace it with `Tensor::empty([0; D])`.
    /// Backport of: <https://github.com/tracel-ai/burn/pull/5207>
    ///
    /// Returns the previous value.
    fn extract(&mut self) -> Self;

    /// Select (and Squeeze) a dimension.
    fn select_dim<const D2: usize>(
        self,
        dim: impl AsIndex,
        index: impl AsIndex,
    ) -> Tensor<B, D2, K>;

    /// Copy an internal slice from `from` to `to`.
    fn copy_slice<S1: SliceArg, S2: SliceArg>(
        self,
        to: S1,
        from: S2,
    ) -> Tensor<B, D, K>;
}

impl<B, const D: usize, K> TensorOpExt<B, D, K> for Tensor<B, D, K>
where
    B: Backend,
    K: BasicOps<B>,
{
    fn swap(
        &mut self,
        other: &mut Self,
    ) {
        core::mem::swap(self, other);
    }

    fn extract(&mut self) -> Self {
        let mut z = Tensor::empty([0; D], &self.device());
        self.swap(&mut z);
        z
    }

    fn select_dim<const D2: usize>(
        self,
        dim: impl AsIndex,
        index: impl AsIndex,
    ) -> Tensor<B, D2, K> {
        let dim = dim.expect_dim_index(D);
        let index = index.as_index();
        self.slice_dim(dim, index).squeeze_dim::<D2>(dim)
    }

    fn copy_slice<S1: SliceArg, S2: SliceArg>(
        self,
        to: S1,
        from: S2,
    ) -> Tensor<B, D, K> {
        let tmp = self.clone().slice(from);
        self.slice_assign(to, tmp)
    }
}

/// [`Tensor`] element-type aware extension operations.
pub trait TensorElemOpExt<B, const D: usize, K>
where
    B: Backend,
    K: BasicOps<B>,
    K::Elem: Element,
{
    /// Copies the current `Tensor` into a `TensorData`; converts the dtype.
    ///
    /// By contract, this will yield the same result as
    /// `tensor.to_data().convert::<E>(dtype)`.
    ///
    /// The conversion is a no-op if the dtype is the same as the current dtype.
    fn to_data_as<E: Element>(&self) -> TensorData;

    /// Copies the current `Tensor` into `TensorData`; converts the dtype.
    ///
    /// By contract, this will yield the same result as
    /// `tensor.to_data().convert_dtype(dtype)`.
    ///
    /// The conversion is a no-op if the dtype is the same as the current dtype.
    fn to_data_cast(
        &self,
        dtype: DType,
    ) -> TensorData;

    /// Converts the current `Tensor` into `TensorData`; converts the dtype.
    ///
    /// By contract, this will yield the same result as
    /// `tensor.into_data().convert::<E>(dtype)`.
    ///
    /// The conversion is a no-op if the dtype is the same as the current dtype.
    fn into_data_as<E: Element>(self) -> TensorData;

    /// Converts the current `Tensor` into `TensorData`; converts the dtype.
    ///
    /// By contract, this will yield the same result as
    /// `tensor.into_data().convert_dtype(dtype)`.
    ///
    /// The conversion is a no-op if the dtype is the same as the current dtype.
    fn into_data_cast(
        self,
        dtype: DType,
    ) -> TensorData;
}

impl<B, const D: usize, K> TensorElemOpExt<B, D, K> for Tensor<B, D, K>
where
    B: Backend,
    K: BasicOps<B>,
    K::Elem: Element,
{
    fn to_data_as<E: Element>(&self) -> TensorData {
        self.to_data_cast(E::dtype())
    }

    fn to_data_cast(
        &self,
        dtype: DType,
    ) -> TensorData {
        self.to_data().convert_dtype(dtype)
    }

    fn into_data_as<E: Element>(self) -> TensorData {
        self.into_data_cast(E::dtype())
    }

    fn into_data_cast(
        self,
        dtype: DType,
    ) -> TensorData {
        self.into_data().convert_dtype(dtype)
    }
}

/// Tensor Extension trait for ordered operations.
pub trait TensorOrderedOpExt<B, const D: usize, K>
where
    B: Backend,
    K: BasicOps<B>,
{
    /// Elementwise check if the value is in the `[start, end)` range.
    fn in_range_scalar<E: ElementConversion>(
        self,
        range: Range<E>,
    ) -> Tensor<B, D, Bool>;

    /// Elementwise check if the value is in the `[start, end)` range.
    fn in_range(
        self,
        start: Tensor<B, D, K>,
        end: Tensor<B, D, K>,
    ) -> Tensor<B, D, Bool>;
}

// Impls duplicated because burn doesn't expose Ordered<B>
impl<B, const D: usize> TensorOrderedOpExt<B, D, Float> for Tensor<B, D>
where
    B: Backend,
{
    fn in_range_scalar<E: ElementConversion>(
        self,
        range: Range<E>,
    ) -> Tensor<B, D, Bool> {
        self.clone()
            .greater_equal_elem(range.start)
            .bool_and(self.lower_elem(range.end))
    }

    fn in_range(
        self,
        start: Tensor<B, D>,
        end: Tensor<B, D>,
    ) -> Tensor<B, D, Bool> {
        assert_eq!(self.shape(), start.shape());
        assert_eq!(self.shape(), end.shape());
        self.clone().greater_equal(start).bool_and(self.lower(end))
    }
}

// Impls duplicated because burn doesn't expose Ordered<B>
impl<B, const D: usize> TensorOrderedOpExt<B, D, Int> for Tensor<B, D, Int>
where
    B: Backend,
{
    fn in_range_scalar<E: ElementConversion>(
        self,
        range: Range<E>,
    ) -> Tensor<B, D, Bool> {
        self.clone()
            .greater_equal_elem(range.start)
            .bool_and(self.lower_elem(range.end))
    }

    fn in_range(
        self,
        start: Tensor<B, D, Int>,
        end: Tensor<B, D, Int>,
    ) -> Tensor<B, D, Bool> {
        assert_eq!(self.shape(), start.shape());
        assert_eq!(self.shape(), end.shape());
        self.clone().greater_equal(start).bool_and(self.lower(end))
    }
}

/// Operation Extensions for `Tensor<B, D, Int>`.
pub trait TensorIntOpExt<B, const D: usize>
where
    B: Backend,
{
    /// Returns the square of the tensor.
    /// Backport of: <https://github.com/tracel-ai/burn/pull/5224>
    fn square(self) -> Self;
}

impl<B, const D: usize> TensorIntOpExt<B, D> for Tensor<B, D, Int>
where
    B: Backend,
{
    fn square(self) -> Self {
        self.powi_scalar(2)
    }
}

/// Operation Extensions for `Tensor<B, D, Bool>`.
pub trait TensorBoolOpExt<B, const D: usize>
where
    B: Backend,
{
    /// Aggregate a count of all true elements along the given *dimension* or
    /// *axis* in the tensor.
    ///
    /// # Arguments
    ///
    /// * `dim` - The dimension or axis along which to aggregate the elements;
    ///   supports negative indexing.
    fn count_dim<I: AsIndex>(
        self,
        dim: I,
    ) -> Tensor<B, D, Int>;

    /// Aggregate a count of all true elements along the given *axes* in the
    /// tensor.
    ///
    /// # Arguments
    ///
    /// * `dims` - the dimensions to aggregate; supports negative indexing.
    ///
    /// # Returns
    ///
    /// The returned tensor will have the same rank,
    /// but the aggregated dimensions will have size 1.
    fn count_dims<I: AsIndex>(
        self,
        dims: &[I],
    ) -> Tensor<B, D, Int>;
}

impl<B, const D: usize> TensorBoolOpExt<B, D> for Tensor<B, D, Bool>
where
    B: Backend,
{
    fn count_dim<I: AsIndex>(
        self,
        dim: I,
    ) -> Tensor<B, D, Int> {
        self.int().sum_dim(dim)
    }

    fn count_dims<I: AsIndex>(
        self,
        dims: &[I],
    ) -> Tensor<B, D, Int> {
        self.int().sum_dims(dims)
    }
}

/// Extension trait for `TensorData` that provides additional methods.
pub trait TensorDataToVecAsExt {
    /// Cast the data to a new dtype.
    ///
    /// TODO: Implement proper error handling in `TensorData`.
    ///
    /// # Returns
    /// Ok(data) on success, (Currently) panics on failure.
    fn try_cast(
        self,
        dtype: DType,
    ) -> Result<TensorData, DataError>;

    /// Convert the data to a new dtype.
    ///
    /// TODO: Implement proper error handling in `TensorData`.
    ///
    /// By contract, this is equivalent to:
    /// `data.try_cast(E::dtype())`
    ///
    /// # Returns
    /// Ok(data) on success, (Currently) panics on failure.
    fn try_convert<E: Element>(self) -> Result<TensorData, DataError>;

    /// Copy and convert the data to a [`Vec<E>`].
    ///
    /// By contract, this is equivalent to:
    /// `data.clone().into_vec_as::<E>()`
    ///
    /// Particular conversions may provide more efficient implementations.
    ///
    /// # Returns
    /// `Ok(vec)` on success, or an error if the conversion fails.
    fn to_vec_as<E: Element>(&self) -> Result<Vec<E>, DataError>;

    /// Convert the data to [`Vec<E>`].
    ///
    /// By contract, this is equivalent to:
    /// `data.try_convert::<E>()?.to_vec::<E>()`
    ///
    /// Particular conversions may provide more efficient implementations.
    ///
    /// # Returns
    /// `Ok(vec)` on success, or an error if the conversion fails.
    fn into_vec_as<E: Element>(self) -> Result<Vec<E>, DataError>;
}

impl TensorDataToVecAsExt for TensorData {
    fn try_cast(
        self,
        dtype: DType,
    ) -> Result<TensorData, DataError> {
        Ok(self.convert_dtype(dtype))
    }

    fn try_convert<E: Element>(self) -> Result<TensorData, DataError> {
        self.try_cast(E::dtype())
    }

    fn to_vec_as<E: Element>(&self) -> Result<Vec<E>, DataError> {
        self.clone().into_vec_as::<E>()
    }

    fn into_vec_as<E: Element>(self) -> Result<Vec<E>, DataError> {
        self.try_convert::<E>()?.to_vec::<E>()
    }
}

#[cfg(test)]
mod tests {
    use burn::tensor::{
        Tensor,
        TensorData,
    };

    use super::*;
    use crate::support::testing::{
        CpuBackend,
        default_device,
    };
    type B = CpuBackend;

    #[test]
    fn test_release_swap() {
        let device = default_device();
        let mut tensor: Tensor<B, 1> =
            Tensor::<B, 1>::from_data(TensorData::from([0.0, 1.0, 2.0, 3.0]), &device);
        assert_eq!(tensor.dims(), [4]);

        let mut old: Tensor<B, 1> = tensor.extract();
        assert_eq!(tensor.dims(), [0]);
        assert_eq!(old.dims(), [4]);

        tensor.swap(&mut old);
        assert_eq!(tensor.dims(), [4]);
        assert_eq!(old.dims(), [0]);
    }

    #[test]
    fn test_select_dim() {
        let device = default_device();
        let tensor: Tensor<B, 2> =
            Tensor::from_data(TensorData::from([[0.0, 1.0], [2.0, 3.0]]), &device);

        let r1: Tensor<B, 1> = tensor.clone().select_dim(0, 1);
        r1.to_data().assert_eq(&TensorData::from([2.0, 3.0]), false);

        let c1: Tensor<B, 1> = tensor.clone().select_dim(1, 1);
        c1.to_data().assert_eq(&TensorData::from([1.0, 3.0]), false);
    }

    #[test]
    fn test_in_range_scalar() {
        let device = default_device();
        let x: Tensor<B, 1, Int> = Tensor::from_data([0, 1, 2, 3], &device);

        let b = x.in_range_scalar(1..3);

        b.to_data()
            .assert_eq(&TensorData::from([false, true, true, false]), false);
    }

    #[test]
    fn test_in_range() {
        let device = default_device();
        let x: Tensor<B, 1, Int> = Tensor::from_data([0, 0, 0, 0], &device);

        let start: Tensor<B, 1, Int> = Tensor::from_data([-1, 0, 0, 3], &device);
        let end: Tensor<B, 1, Int> = Tensor::from_data([0, 0, 2, 3], &device);

        let b = x.in_range(start, end);

        b.to_data()
            .assert_eq(&TensorData::from([false, false, true, false]), false);
    }

    #[test]
    fn test_int_square() {
        let device = default_device();
        let x: Tensor<B, 1, Int> = Tensor::from_data([0, 1, 2, 3], &device);

        x.square()
            .to_data()
            .assert_eq(&TensorData::from([0, 1, 4, 9]), false);
    }

    #[test]
    fn test_bool_count_dim() {
        let device = default_device();
        let x: Tensor<B, 2, Bool> =
            Tensor::from_data([[true, true, false], [true, false, false]], &device);

        x.clone()
            .count_dim(0)
            .squeeze_dim::<1>(0)
            .to_data()
            .assert_eq(&TensorData::from([2, 1, 0]), false);
        x.clone()
            .count_dim(1)
            .squeeze_dim::<1>(1)
            .to_data()
            .assert_eq(&TensorData::from([2, 1]), false);

        x.clone()
            .count_dims(&[0])
            .squeeze_dim::<1>(0)
            .to_data()
            .assert_eq(&TensorData::from([2, 1, 0]), false);
        x.clone()
            .count_dims(&[0, 1])
            .squeeze_dim::<1>(0)
            .to_data()
            .assert_eq(&TensorData::from([3]), false);
    }

    #[test]
    fn test_to_vec_as() {
        let data = TensorData::from([0.0f32, 1.0, 2.5]);

        // Same-dtype copy.
        assert_eq!(data.to_vec_as::<f32>().unwrap(), vec![0.0f32, 1.0, 2.5]);

        // Widening cast (different element size).
        assert_eq!(data.to_vec_as::<f64>().unwrap(), vec![0.0f64, 1.0, 2.5]);

        // Float to int cast (same element size) truncates.
        assert_eq!(data.to_vec_as::<i32>().unwrap(), vec![0i32, 1, 2]);

        // The source data is borrowed, not consumed.
        data.assert_eq(&TensorData::from([0.0f32, 1.0, 2.5]), true);
    }

    #[test]
    fn test_into_vec_as() {
        let data = TensorData::from([0i32, 1, 2, 3]);

        // Same-dtype conversion.
        assert_eq!(
            data.clone().into_vec_as::<i32>().unwrap(),
            vec![0i32, 1, 2, 3]
        );

        // Int to float cast.
        assert_eq!(
            data.clone().into_vec_as::<f32>().unwrap(),
            vec![0.0f32, 1.0, 2.0, 3.0]
        );

        // Narrowing int cast.
        assert_eq!(data.into_vec_as::<u8>().unwrap(), vec![0u8, 1, 2, 3]);
    }
}