use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha12Rng;
use serde::{Deserialize, Serialize};
use crate::{Device, Kind, Result, RustTorchError, Tensor, data::ResourceLimits};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuntimeConfig {
pub seed: i64,
pub threads: Option<i32>,
}
impl RuntimeConfig {
pub fn apply(self) -> Result<()> {
if self.threads.is_some_and(|threads| threads <= 0) {
return Err(invalid("runtime thread count must be positive"));
}
if let Some(threads) = self.threads {
tch::set_num_threads(threads);
}
crate::manual_seed(self.seed);
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TensorRngState {
version: u32,
seed: u64,
next_stream: u64,
}
#[derive(Debug, Clone)]
pub struct TensorRng {
state: TensorRngState,
limits: ResourceLimits,
}
impl TensorRng {
pub fn new(seed: u64) -> Self {
Self {
state: TensorRngState {
version: 1,
seed,
next_stream: 0,
},
limits: ResourceLimits::default(),
}
}
#[must_use]
pub const fn with_limits(mut self, limits: ResourceLimits) -> Self {
self.limits = limits;
self
}
pub fn state_dict(&self) -> TensorRngState {
self.state.clone()
}
pub fn from_state(state: TensorRngState) -> Result<Self> {
if state.version != 1 || state.next_stream == u64::MAX {
return Err(invalid(
"unsupported RNG state version or exhausted stream counter",
));
}
Ok(Self {
state,
limits: ResourceLimits::default(),
})
}
pub fn uniform(&mut self, shape: &[i64], options: (Kind, Device)) -> Result<Tensor> {
self.draw(shape, options, false)
}
pub fn normal(&mut self, shape: &[i64], options: (Kind, Device)) -> Result<Tensor> {
self.draw(shape, options, true)
}
fn draw(
&mut self,
shape: &[i64],
(kind, device): (Kind, Device),
normal: bool,
) -> Result<Tensor> {
if !matches!(kind, Kind::Float | Kind::Double) || shape.len() > 64 {
return Err(invalid(
"noise requires Float32/Float64 and at most 64 dimensions",
));
}
let next = self
.state
.next_stream
.checked_add(1)
.filter(|&value| value < u64::MAX)
.ok_or_else(|| invalid("RNG stream counter exhausted"))?;
let dimensions = shape
.iter()
.map(|&d| {
usize::try_from(d).map_err(|_| invalid("noise dimensions must be nonnegative"))
})
.collect::<Result<Vec<_>>>()?;
let count = self.limits.tensor_elements(&dimensions)?;
let bytes = count
.checked_mul(kind.elt_size_in_bytes())
.ok_or_else(|| invalid("noise byte size overflow"))?;
self.limits
.check("noise bytes", bytes, self.limits.max_decoded_bytes)?;
let mut rng = ChaCha12Rng::seed_from_u64(self.state.seed);
rng.set_stream(self.state.next_stream);
let mut sample = || {
let u = 1. - rng.r#gen::<f64>();
let angle = std::f64::consts::TAU * rng.r#gen::<f64>();
(-2. * u.ln()).sqrt() * angle.cos()
};
let tensor = if kind == Kind::Float {
let mut values = Vec::new();
values
.try_reserve_exact(count)
.map_err(|_| invalid("cannot reserve noise payload"))?;
if normal {
values.extend((0..count).map(|_| sample() as f32));
} else {
values.extend((0..count).map(|_| rng.r#gen::<f32>()));
}
Tensor::f_from_slice(&values)?
} else {
let mut values = Vec::new();
values
.try_reserve_exact(count)
.map_err(|_| invalid("cannot reserve noise payload"))?;
if normal {
values.extend((0..count).map(|_| sample()));
} else {
values.extend((0..count).map(|_| rng.r#gen::<f64>()));
}
Tensor::f_from_slice(&values)?
};
let result = tensor.f_reshape(shape)?.f_to_device(device)?;
self.state.next_stream = next;
Ok(result)
}
}
fn invalid(reason: &str) -> RustTorchError {
RustTorchError::InvalidConfiguration {
field: "reproducibility",
reason: reason.into(),
}
}