use burn::{
prelude::{
Tensor,
TensorData,
},
tensor::{
Device,
Distribution,
},
};
use rand::{
SeedableRng,
rngs::StdRng,
};
pub fn seeded_tensor<const D: usize>(
seed: u64,
shape: [usize; D],
distribution: Distribution,
device: &Device,
) -> Tensor<D> {
let mut rng = StdRng::seed_from_u64(seed);
let data = TensorData::random::<f64, _, _>(shape, distribution, &mut rng);
Tensor::from_data(data, device)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
burner::tensor::device_float_dtype,
support::testing::cpu_device,
};
fn host<const D: usize>(tensor: &Tensor<D>) -> Vec<f64> {
tensor.to_data().try_into_vec_as::<f64>().unwrap()
}
#[test]
fn test_seeded_tensor_is_deterministic() {
let device = cpu_device();
let dist = Distribution::Uniform(-1.0, 1.0);
let a = seeded_tensor::<3>(7, [2, 3, 4], dist, &device);
let b = seeded_tensor::<3>(7, [2, 3, 4], dist, &device);
let c = seeded_tensor::<3>(8, [2, 3, 4], dist, &device);
assert_eq!(a.dtype(), device_float_dtype(&device));
assert_eq!(host(&a), host(&b));
assert_ne!(host(&a), host(&c));
assert!(host(&a).iter().all(|v| (-1.0..1.0).contains(v)));
}
}