gloss-utils 0.9.0

Small library for utility functions in gloss
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
use burn::{
    prelude::Backend,
    tensor::{Float, Int, Tensor, TensorKind},
};
use nalgebra as na;
use ndarray as nd;

// TODO: Take another look at these conversions with the burn update
// ================ Tensor to Data Functions ================
// Handle Float tensors for both 1D and 2D
/// Convert a burn float tensor to a Vec on wasm
#[cfg(target_arch = "wasm32")]
pub fn tensor_to_data_float<B: Backend, const D: usize>(tensor: &Tensor<B, D, Float>) -> Vec<f32> {
    tensor.to_data().to_vec::<f32>().unwrap()
}

/// Convert a burn float tensor to a Vec
#[cfg(not(target_arch = "wasm32"))]
pub fn tensor_to_data_float<B: Backend, const D: usize>(tensor: &Tensor<B, D, Float>) -> Vec<f32> {
    tensor.to_data().to_vec::<f32>().unwrap()
}

// Handle Int tensors for both 1D and 2D
/// Convert a burn int tensor to a Vec on wasm
#[cfg(target_arch = "wasm32")]
#[allow(clippy::cast_possible_truncation)]
pub fn tensor_to_data_int<B: Backend, const D: usize>(tensor: &Tensor<B, D, Int>) -> Vec<i32> {
    if let Ok(data) = tensor.to_data().to_vec::<i32>() {
        return data;
    }

    // Fallback: Attempt `i64` conversion and downcast to `i32` if `i32` fails
    let data_i64: Vec<i64> = tensor.to_data().to_vec::<i64>().unwrap();
    data_i64.into_iter().map(|x| x as i32).collect()
}

/// Convert a burn int tensor to a Vec
#[cfg(not(target_arch = "wasm32"))]
#[allow(clippy::cast_possible_truncation)]
pub fn tensor_to_data_int<B: Backend, const D: usize>(tensor: &Tensor<B, D, Int>) -> Vec<i32> {
    // tensor.to_data().to_vec::<i32>().unwrap()
    if let Ok(data) = tensor.to_data().to_vec::<i32>() {
        return data;
    }

    // Fallback: Attempt `i64` conversion and downcast to `i32` if `i32` fails
    let data_i64: Vec<i64> = tensor.to_data().to_vec::<i64>().unwrap();
    data_i64.into_iter().map(|x| x as i32).collect()
}

// ================ To and Into Burn Conversions ================

/// Trait for converting ndarray to burn tensor (generic over Float/Int and
/// dimensionality)
pub trait ToBurn<B: Backend, const D: usize, T: TensorKind<B>> {
    fn to_burn(&self, device: &B::Device) -> Tensor<B, D, T>;
    fn into_burn(self, device: &B::Device) -> Tensor<B, D, T>;
}

/// Implementation of the trait for 2D Float ndarray
impl<B: Backend> ToBurn<B, 2, Float> for nd::Array2<f32> {
    fn to_burn(&self, device: &B::Device) -> Tensor<B, 2, Float> {
        let vec: Vec<f32>;
        let bytes = if self.is_standard_layout() {
            self.as_slice().unwrap()
        } else {
            vec = self.iter().copied().collect();
            vec.as_slice()
        };
        let shape = [self.nrows(), self.ncols()];
        Tensor::<B, 1, Float>::from_floats(bytes, device).reshape(shape)
    }

    fn into_burn(self, device: &B::Device) -> Tensor<B, 2, Float> {
        let vec: Vec<f32>;
        let bytes = if self.is_standard_layout() {
            self.as_slice().expect("Array should have a slice if it's in standard layout")
        } else {
            vec = self.iter().copied().collect();
            vec.as_slice()
        };
        let shape = [self.nrows(), self.ncols()];
        Tensor::<B, 1, Float>::from_floats(bytes, device).reshape(shape)
    }
}

/// Trait implementation for 1D Float ndarray
impl<B: Backend> ToBurn<B, 1, Float> for nd::Array1<f32> {
    fn to_burn(&self, device: &B::Device) -> Tensor<B, 1, Float> {
        let vec: Vec<f32> = self.iter().copied().collect();
        Tensor::<B, 1, Float>::from_floats(&vec[..], device)
    }

    fn into_burn(self, device: &B::Device) -> Tensor<B, 1, Float> {
        let vec: Vec<f32>;
        let bytes = if self.is_standard_layout() {
            self.as_slice().expect("Array should have a slice if it's in standard layout")
        } else {
            vec = self.iter().copied().collect();
            vec.as_slice()
        };
        Tensor::<B, 1, Float>::from_floats(bytes, device)
    }
}

/// Trait implementation for 2D Int ndarray
impl<B: Backend> ToBurn<B, 2, Int> for nd::Array2<u32> {
    #[allow(clippy::cast_possible_wrap)]
    fn to_burn(&self, device: &B::Device) -> Tensor<B, 2, Int> {
        let array_i32 = self.mapv(|x| x as i32);
        let vec: Vec<i32> = array_i32.into_raw_vec();
        // let vec: Vec<i32> = array_i32.into_raw_vec();
        let shape = [self.nrows(), self.ncols()];
        Tensor::<B, 1, Int>::from_ints(&vec[..], device).reshape(shape)

        //for torch the dtype is i64 only so we need to handle that case
        // since the multibackend has a fixed dtype of i32 for int tensors we cannot use  B::IntElem::dtype() since it would just return i32
        // we need to check if the device is torch or libtorch and cast to i64 in this case
        // let backend_name = B::name(device);
        // if backend_name.contains("torch") {
        //     let array = self.mapv(i64::from);
        //     let vec: Vec<i64> = array.into_raw_vec();
        //     let shape = [self.nrows(), self.ncols()];
        //     // Tensor::<B, 1, Int>::from_ints(&vec[..], device).reshape(shape) //internally it does a conversion to i32, sad :(
        //     let data: TensorData = vec.as_slice().into();
        //     Tensor::<B, 1, Int>::from_data(data, device).reshape(shape)
        // } else {
        //     let array = self.mapv(|x| x as i32);
        //     let vec: Vec<i32> = array.into_raw_vec();
        //     let shape = [self.nrows(), self.ncols()];
        //     Tensor::<B, 1, Int>::from_ints(&vec[..], device).reshape(shape)
        // }
    }

    #[allow(clippy::cast_possible_wrap)]
    fn into_burn(self, device: &B::Device) -> Tensor<B, 2, Int> {
        let array_i32 = self.mapv(|x| x as i32);
        let vec: Vec<i32> = array_i32.into_raw_vec();
        // let vec: Vec<i32> = array_i32.into_raw_vec();
        let shape = [self.nrows(), self.ncols()];
        Tensor::<B, 1, Int>::from_ints(&vec[..], device).reshape(shape)
    }
}

/// Trait implementation for 1D Int ndarray
impl<B: Backend> ToBurn<B, 1, Int> for nd::Array1<u32> {
    #[allow(clippy::cast_possible_wrap)]
    fn to_burn(&self, device: &B::Device) -> Tensor<B, 1, Int> {
        let array_i32 = self.mapv(|x| x as i32);
        let vec: Vec<i32> = array_i32.into_raw_vec();
        // let vec: Vec<i32> = array_i32.into_raw_vec();
        Tensor::<B, 1, Int>::from_ints(&vec[..], device)
    }

    #[allow(clippy::cast_possible_wrap)]
    fn into_burn(self, device: &B::Device) -> Tensor<B, 1, Int> {
        let array_i32 = self.mapv(|x| x as i32);
        let vec: Vec<i32> = array_i32.into_raw_vec();
        // let vec: Vec<i32> = array_i32.into_raw_vec();
        Tensor::<B, 1, Int>::from_ints(&vec[..], device)
    }
}
impl<B: Backend> ToBurn<B, 3, Float> for nd::Array3<f32> {
    fn to_burn(&self, device: &B::Device) -> Tensor<B, 3, Float> {
        let vec: Vec<f32>;
        let bytes = if self.is_standard_layout() {
            self.as_slice().unwrap()
        } else {
            vec = self.iter().copied().collect();
            vec.as_slice()
        };
        let shape = [self.shape()[0], self.shape()[1], self.shape()[2]];
        Tensor::<B, 1, Float>::from_floats(bytes, device).reshape(shape)
    }

    fn into_burn(self, device: &B::Device) -> Tensor<B, 3, Float> {
        let vec: Vec<f32>;
        let bytes = if self.is_standard_layout() {
            self.as_slice().expect("Array should have a slice if it's in standard layout")
        } else {
            vec = self.iter().copied().collect();
            vec.as_slice()
        };
        let shape = [self.shape()[0], self.shape()[1], self.shape()[2]];
        Tensor::<B, 1, Float>::from_floats(bytes, device).reshape(shape)
    }
}

/// Trait implementation for 3D Int ndarray
impl<B: Backend> ToBurn<B, 3, Int> for nd::Array3<u32> {
    #[allow(clippy::cast_possible_wrap)]
    fn to_burn(&self, device: &B::Device) -> Tensor<B, 3, Int> {
        let array_i32 = self.mapv(|x| x as i32);
        let vec: Vec<i32> = array_i32.into_raw_vec();
        // let vec: Vec<i32> = array_i32.into_raw_vec();
        let shape = [self.shape()[0], self.shape()[1], self.shape()[2]];
        Tensor::<B, 1, Int>::from_ints(&vec[..], device).reshape(shape)
    }

    #[allow(clippy::cast_possible_wrap)]
    fn into_burn(self, device: &B::Device) -> Tensor<B, 3, Int> {
        let array_i32 = self.mapv(|x| x as i32);
        let vec: Vec<i32> = array_i32.into_raw_vec();
        // let vec: Vec<i32> = array_i32.into_raw_vec();
        let shape = [self.shape()[0], self.shape()[1], self.shape()[2]];
        Tensor::<B, 1, Int>::from_ints(&vec[..], device).reshape(shape)
    }
}
/// Implement `ToBurn` for converting `nalgebra::DMatrix<f32>` to a burn tensor
/// (Float type)
impl<B: Backend> ToBurn<B, 2, Float> for na::DMatrix<f32> {
    fn to_burn(&self, device: &B::Device) -> Tensor<B, 2, Float> {
        let num_rows = self.nrows();
        let num_cols = self.ncols();
        let flattened: Vec<f32> = self.transpose().as_slice().to_vec();
        Tensor::<B, 1, Float>::from_floats(&flattened[..], device).reshape([num_rows, num_cols])
    }

    fn into_burn(self, device: &B::Device) -> Tensor<B, 2, Float> {
        let num_rows = self.nrows();
        let num_cols = self.ncols();
        let flattened: Vec<f32> = self.transpose().as_slice().to_vec();
        Tensor::<B, 1, Float>::from_floats(&flattened[..], device).reshape([num_rows, num_cols])
    }
}

/// Implement `ToBurn` for converting `nalgebra::DMatrix<u32>` to a burn tensor
/// (Int type)
impl<B: Backend> ToBurn<B, 2, Int> for na::DMatrix<u32> {
    fn to_burn(&self, device: &B::Device) -> Tensor<B, 2, Int> {
        let num_rows = self.nrows();
        let num_cols = self.ncols();
        let flattened: Vec<i32> = self
            .transpose()
            .as_slice()
            .iter()
            .map(|&x| i32::try_from(x).expect("Value out of range for i32"))
            .collect();
        Tensor::<B, 1, Int>::from_ints(&flattened[..], device).reshape([num_rows, num_cols])
    }

    fn into_burn(self, device: &B::Device) -> Tensor<B, 2, Int> {
        let num_rows = self.nrows();
        let num_cols = self.ncols();
        let flattened: Vec<i32> = self
            .transpose()
            .as_slice()
            .iter()
            .map(|&x| i32::try_from(x).expect("Value out of range for i32"))
            .collect();
        Tensor::<B, 1, Int>::from_ints(&flattened[..], device).reshape([num_rows, num_cols])
    }
}

// ================ To and Into NdArray Conversions ================

/// Trait for converting burn tensor to ndarray (generic over Float/Int and
/// dimensionality)
pub trait ToNdArray<B: Backend, const D: usize, T> {
    fn to_ndarray(&self) -> nd::Array<T, nd::Dim<[usize; D]>>;
    fn into_ndarray(self) -> nd::Array<T, nd::Dim<[usize; D]>>;
}

/// Trait implementation for converting 3D Float burn tensor to ndarray
impl<B: Backend> ToNdArray<B, 3, f32> for Tensor<B, 3, Float> {
    fn to_ndarray(&self) -> nd::Array3<f32> {
        let tensor_data = tensor_to_data_float(self);
        let shape = self.dims();
        nd::Array3::from_shape_vec((shape[0], shape[1], shape[2]), tensor_data).unwrap()
    }

    fn into_ndarray(self) -> nd::Array3<f32> {
        let tensor_data = tensor_to_data_float(&self);
        let shape = self.dims();
        nd::Array3::from_shape_vec((shape[0], shape[1], shape[2]), tensor_data).unwrap()
    }
}

/// Trait implementation for converting 2D Float burn tensor to ndarray
impl<B: Backend> ToNdArray<B, 2, f32> for Tensor<B, 2, Float> {
    fn to_ndarray(&self) -> nd::Array2<f32> {
        let tensor_data = tensor_to_data_float(self);
        let shape = self.dims();
        nd::Array2::from_shape_vec((shape[0], shape[1]), tensor_data).unwrap()
    }

    fn into_ndarray(self) -> nd::Array2<f32> {
        let tensor_data = tensor_to_data_float(&self);
        let shape = self.dims();
        nd::Array2::from_shape_vec((shape[0], shape[1]), tensor_data).unwrap()
    }
}

/// Trait implementation for converting 1D Float burn tensor to ndarray
impl<B: Backend> ToNdArray<B, 1, f32> for Tensor<B, 1, Float> {
    fn to_ndarray(&self) -> nd::Array1<f32> {
        let tensor_data = tensor_to_data_float(self);
        nd::Array1::from_vec(tensor_data)
    }

    fn into_ndarray(self) -> nd::Array1<f32> {
        let tensor_data = tensor_to_data_float(&self);
        nd::Array1::from_vec(tensor_data)
    }
}

/// Trait implementation for converting 3D Int burn tensor to ndarray
#[allow(clippy::cast_sign_loss)]
impl<B: Backend> ToNdArray<B, 3, u32> for Tensor<B, 3, Int> {
    fn to_ndarray(&self) -> nd::Array3<u32> {
        let tensor_data = tensor_to_data_int(self);
        let tensor_data_u32: Vec<u32> = tensor_data.into_iter().map(|x| x as u32).collect();
        let shape = self.dims();
        nd::Array3::from_shape_vec((shape[0], shape[1], shape[2]), tensor_data_u32).unwrap()
    }

    fn into_ndarray(self) -> nd::Array3<u32> {
        let tensor_data = tensor_to_data_int(&self);
        let tensor_data_u32: Vec<u32> = tensor_data.into_iter().map(|x| x as u32).collect();
        let shape = self.dims();
        nd::Array3::from_shape_vec((shape[0], shape[1], shape[2]), tensor_data_u32).unwrap()
    }
}

/// Trait implementation for converting 2D Int burn tensor to ndarray
#[allow(clippy::cast_sign_loss)]
impl<B: Backend> ToNdArray<B, 2, u32> for Tensor<B, 2, Int> {
    fn to_ndarray(&self) -> nd::Array2<u32> {
        let tensor_data = tensor_to_data_int(self);
        let tensor_data_u32: Vec<u32> = tensor_data.into_iter().map(|x| x as u32).collect();
        let shape = self.dims();
        nd::Array2::from_shape_vec((shape[0], shape[1]), tensor_data_u32).unwrap()
    }

    fn into_ndarray(self) -> nd::Array2<u32> {
        let tensor_data = tensor_to_data_int(&self);
        let tensor_data_u32: Vec<u32> = tensor_data.into_iter().map(|x| x as u32).collect();
        let shape = self.dims();
        nd::Array2::from_shape_vec((shape[0], shape[1]), tensor_data_u32).unwrap()
    }
}

/// Trait implementation for converting 1D Int burn tensor to ndarray
#[allow(clippy::cast_sign_loss)]
impl<B: Backend> ToNdArray<B, 1, u32> for Tensor<B, 1, Int> {
    fn to_ndarray(&self) -> nd::Array1<u32> {
        let tensor_data = tensor_to_data_int(self);
        let tensor_data_u32: Vec<u32> = tensor_data.into_iter().map(|x| x as u32).collect();
        nd::Array1::from_vec(tensor_data_u32)
    }

    fn into_ndarray(self) -> nd::Array1<u32> {
        let tensor_data = tensor_to_data_int(&self);
        let tensor_data_u32: Vec<u32> = tensor_data.into_iter().map(|x| x as u32).collect();
        nd::Array1::from_vec(tensor_data_u32)
    }
}

// ================ To and Into Nalgebra Conversions ================

/// Trait for converting `burn` tensor to `nalgebra::DMatrix` or
/// `nalgebra::DVector` (Float type)
pub trait ToNalgebraFloat<B: Backend, const D: usize> {
    fn to_nalgebra(&self) -> na::DMatrix<f32>;
    fn into_nalgebra(self) -> na::DMatrix<f32>;
}

/// Trait for converting `burn` tensor to `nalgebra::DMatrix` or
/// `nalgebra::DVector` (Int type)
pub trait ToNalgebraInt<B: Backend, const D: usize> {
    fn to_nalgebra(&self) -> na::DMatrix<u32>;
    fn into_nalgebra(self) -> na::DMatrix<u32>;
}

/// Implement trait to convert `burn` tensor to `nalgebra::DMatrix<f32>` (Float
/// type)
impl<B: Backend> ToNalgebraFloat<B, 2> for Tensor<B, 2, Float> {
    fn to_nalgebra(&self) -> na::DMatrix<f32> {
        let data = tensor_to_data_float(self);
        let shape = self.shape().dims;
        na::DMatrix::from_vec(shape[1], shape[0], data).transpose()
    }

    fn into_nalgebra(self) -> na::DMatrix<f32> {
        let data = tensor_to_data_float(&self);
        let shape = self.shape().dims;
        na::DMatrix::from_vec(shape[1], shape[0], data).transpose()
    }
}

/// Implement trait to convert `burn` tensor to `nalgebra::DMatrix<u32>` (Int
/// type)
impl<B: Backend> ToNalgebraInt<B, 2> for Tensor<B, 2, Int> {
    #[allow(clippy::cast_sign_loss)]
    fn to_nalgebra(&self) -> na::DMatrix<u32> {
        let data = tensor_to_data_int(self);
        let shape = self.shape().dims;
        let data_u32: Vec<u32> = data.into_iter().map(|x| x as u32).collect();
        na::DMatrix::from_vec(shape[1], shape[0], data_u32).transpose()
    }
    #[allow(clippy::cast_sign_loss)]
    fn into_nalgebra(self) -> na::DMatrix<u32> {
        let data = tensor_to_data_int(&self);
        let shape = self.shape().dims;
        let data_u32: Vec<u32> = data.into_iter().map(|x| x as u32).collect();
        na::DMatrix::from_vec(shape[1], shape[0], data_u32).transpose()
    }
}