Skip to content

Commit 33a4214

Browse files
committed
feat: PyTorch parity, diagnostics, Rust lapack/numeric/optim kernels, and bug-hunt fixes
1 parent b9b7871 commit 33a4214

38 files changed

Lines changed: 30492 additions & 21323 deletions

‎CHANGELOG.md‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,43 @@
22

33
## 0.1.0 - 2026-11-23
44

5+
### Added
6+
- `oxideon.tensor_utils`: 71 PyTorch-named tensor utilities, all exported at the top level and covered by `tests/test_tensor_utils.py`
7+
(compared against NumPy and PyTorch): `ravel`, `movedim` / `moveaxis`, `swapaxes` / `swapdims`, `tensor_split`, `hsplit` / `vsplit` /
8+
`dsplit`, `broadcast_shapes` / `broadcast_to` / `broadcast_tensors`, `combinations`, `msort`, `lerp`, `float_power`, `addcmul`, `addcdiv`,
9+
`signbit`, `gcd`, `lcm`, `ldexp`, `frexp`, `nextafter`, `sgn`, `positive`, `negative`, `trunc` / `fix`, `frac`, `square`, `lgamma`,
10+
`mvlgamma`, `logspace`, `vander`, `isnan` / `isinf` / `isfinite` / `isposinf` / `isneginf` / `isreal`, `is_tensor`, `numel`, `result_type`,
11+
`logsumexp`, `cumulative_logsumexp`, `var_mean`, `std_mean`, `aminmax`, `count_nonzero`, `renorm`, `scatter_reduce`, `histogramdd`,
12+
`chain_matmul`, `matrix_power`, `matrix_exp`, `pinverse`, `cholesky_solve`, `lu`, `det`, `inverse`, `slogdet`, `ger`, the logical
13+
(`and` / `or` / `xor` / `not`) and bitwise operators. See [docs/PYTHON_API.md](docs/PYTHON_API.md) section 21.
14+
- `oxideon.tensor_methods`: 149 PyTorch-style `Tensor` methods, every one checked against PyTorch: method forms (`x.logsumexp(1)`,
15+
`x.amax(0)`, `x.movedim(0, -1)`, `x.unique()`, `x.trace()`, ...), comparison and division aliases (`x.gt(y)`, `x.true_divide(y)`,
16+
`x.divide(y, rounding_mode="floor")`, `x.dist(y, p)`, ...), and 75 in-place forms (`x.exp_()`, `x.clamp_min_(0)`, `x.lerp_(y, w)`,
17+
`x.addcdiv_(a, b, value=)`, ...) that refuse shape changes, float results in integer tensors, tensors that require grad outside
18+
`no_grad`, and views (`tests/test_tensor_methods.py`).
19+
- `oxideon.distributions`: 19 distributions (`Chi2`, `InverseGamma`, `Pareto`, `Kumaraswamy`, `FisherSnedecor`, `GeneralizedPareto`,
20+
`NegativeBinomial`, `OneHotCategorical`, `OneHotCategoricalStraightThrough`, `LogitRelaxedBernoulli`, `RelaxedBernoulli`,
21+
`ExpRelaxedCategorical`, `RelaxedOneHotCategorical`, `LogisticNormal`, `MixtureSameFamily`, `VonMises`, `Wishart`, `LKJCholesky`,
22+
`ExponentialFamily`) and 18 transforms (`Exp`, `Affine`, `Sigmoid`, `Tanh`, `Softplus`, `Abs`, `Power`, `Softmax`, `StickBreaking`,
23+
`Compose`, `Independent`, `Reshape`, `Cat`, `Stack`, `CumulativeDistribution`, `CorrCholesky`, `LowerCholesky`, `PositiveDefinite`);
24+
`TransformedDistribution` gains `log_prob` and `cdf`; `mean` / `variance` / `stddev` on every distribution with a closed form. All
25+
checked against `torch.distributions` (`tests/test_distributions_ext.py`).
26+
- `oxideon.diagnostics`: `detect_anomaly(model)` (the layer that first produces NaN / Inf, forward or backward), `precision_audit`
27+
(float32 error added by each layer, against a float64 run), `estimate_memory`, `lr_find` (learning-rate range test),
28+
`check_determinism`, `diff_checkpoints`, `TrainingMonitor` (gradient norms, update ratios, activation statistics, warnings),
29+
`hessian_top_eigenvalue` and `hessian_trace` (sharpness). `tests/test_diagnostics.py`.
30+
- More PyTorch parity, each checked against PyTorch (`tests/test_torch_parity_extra.py`): max pooling with `dilation`, `ceil_mode`
31+
and `return_indices` (functional and `nn`, 1-3 D, plus the `*_with_indices` forms; one gather-based implementation replaces the
32+
Python window loops: a Rust kernel, parallel over planes, finds the maxima and the values are gathered, so they stay
33+
differentiable), `lp_pool3d` / `LPPool3d`, `multi_margin_loss`,
34+
`multilabel_margin_loss`, `multilabel_soft_margin_loss`, `triplet_margin_with_distance_loss`, `linear_cross_entropy` /
35+
`LinearCrossEntropyLoss`, in-place functional activations, `upsample*`; `linalg.cholesky_ex`, `inv_ex`, `solve_ex`,
36+
`lu_factor_ex`, `ldl_factor(_ex)`, `ldl_solve` (new Rust module `oxideon-core/src/lapack.rs`: getrf / getrs / potrf /
37+
Bunch-Kaufman sytrf / sytrs with LAPACK's info codes), `matrix_sqrth`, `polar`, `matmul`; `special.hermite_polynomial_he`,
38+
`shifted_chebyshev_polynomial_t/u/v/w`, `modified_bessel_i0/i1`; `fft.hfft2/hfftn/ihfft2/ihfftn`; `nn.LazyConv1d/3d`,
39+
`LazyConvTranspose1d/2d/3d`, `CrossMapLRN2d`, `Buffer`, `UninitializedParameter`, `UninitializedBuffer`, `RNNCellBase`,
40+
`NLLLoss2d`, `Container`; `optim.SparseAdam` (its step runs in Rust); `data.DistributedSampler`, `data.StackDataset`.
41+
542
### Speed (accuracy unchanged unless noted)
643
- Balanced `gelu` 150 -> 135 us per 1M elements (PyTorch 111 us): the tail exponent `poly - z^2` is never positive, so it uses an `exp` without the
744
upper clamp and the NaN restore (a NaN input still gives NaN through `x * cdf`), the 0.5 of the cdf folds into the quotient factor, and
@@ -11,7 +48,35 @@
1148
(PyTorch 1529 us); 8x16x64x64 665 -> 640-660 us (PyTorch 512 us). Accuracy vs PyTorch (worst / mean): 16 channels 3.05x / 1.55x -> 2.69x /
1249
1.54x, 64 channels 4.64x / 2.99x -> 4.58x / 2.67x.
1350

51+
### Changed
52+
- Compute moved from NumPy to Rust: the Python optimizers (`RMSprop`, `Adagrad`, `Adadelta`, `Adamax`, `NAdam`, `RAdam`, `ASGD`,
53+
`Lion`, `Lamb`, `Adafactor`, `Rprop`, `SparseAdam`) run their updates in `oxideon-core/src/optim_kernels.rs` and keep their
54+
state as tensors (NumPy state from older checkpoints is converted on load), `LBFGS` does its two-loop recursion with tensor
55+
operations; `linalg.qr` (any shape, both modes), `svd(full_matrices=True)`, `lu`, `norm`, `pinv`, `eig`, `eigvals` no longer call
56+
NumPy; `tensor_utils.gcd` / `lcm` / `frexp` / `ldexp` / `nextafter` / `signbit` / `isposinf` / `isneginf` / `histogramdd` /
57+
`logspace`, all orthogonal polynomials (`special.*_polynomial_*`, now also with a tensor degree), the Hermitian FFTs, and the
58+
sampling and densities of the new distributions use Rust kernels (`numeric_kernels.rs`, `lapack.rs`, samplers in
59+
`distributions_ext.rs`); distribution samples now come from the oxideon generator, so `oxideon.manual_seed` makes them
60+
reproducible.
61+
1462
### Fixes
63+
- Optimizers that disagreed with PyTorch: `RMSprop` added `eps` inside the square root (`sqrt(v + eps)` instead of
64+
`sqrt(v) + eps`), `RAdam` switched to the rectified update at rho > 4 instead of 5 and scaled `eps` differently, `ASGD` never
65+
applied its decay `lambd` to the parameters, `Adamax` added `eps` after the max instead of inside it; `Rprop` keyed its state by
66+
the tensor instead of its id, so `state_dict` / `load_state_dict` lost it. All now match `torch.optim` step for step
67+
(`tests/test_rust_kernels.py`).
68+
- `linalg.lu_factor` returned LAPACK's 0-based swaps when SciPy was installed and a plain row permutation when it was not, and
69+
`lu_solve` guessed which one it got from whether SciPy imports; neither matched PyTorch. Both now use PyTorch's 1-based pivots
70+
in every environment (no SciPy needed), work on batches, and accept factors computed by `torch.linalg.lu_factor`.
71+
- `ox.autograd.grad` ran a backward pass and returned the inputs' `.grad`, so it added to (and returned) gradients left by
72+
earlier calls, left `.grad` changed, and made every second derivative wrong (`grad` of `w * w` with `create_graph=True`, then
73+
`grad` again, gave 2 + 2w instead of 2). It now uses the native graph traversal: the gradients are returned and `.grad` is not
74+
touched, like `torch.autograd.grad` (custom `autograd.Function` outputs keep the old path, now with `.grad` saved and restored).
75+
- `ox.save(state_dict, "model.weights")`: a file name without a checkpoint extension was written with pickle, which `ox.load`
76+
refuses to read from such a name, so the file could never be loaded. Tensor dicts are now written as safetensors; other objects
77+
raise an error that names the extensions to use.
78+
- `oxideon.distributions`: a distribution with scalar parameters (`Normal(0.0, 1.0)`, `HalfNormal(1.0)`, ...) failed in `sample()`
79+
(`np.random.randn()` returns a Python float), and scalar results came back with shape `[1]` instead of `[]`.
1580
- CUDA: `where_cond` with a broadcast mask (kernel declined) returned a host-backed tensor labelled `cuda:0`, so the next matmul failed with
1681
`device mismatch (cuda:0 vs cuda:0)` (attention with a causal mask on the composed path); it now returns CUDA storage.
1782
- NVRTC is loaded with the wide-character Windows loader, so it is found under a user directory with non-ASCII characters

‎crates/oxideon-core/src/distributions_ext.rs‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1099,6 +1099,61 @@ impl Distribution for Laplace {
10991099
}
11001100

11011101

1102+
// ---------------------------------------------------------------------------------------------------------------
1103+
// Sampling primitives for the Python distributions (drawn from the global, `manual_seed`-able generator)
1104+
// ---------------------------------------------------------------------------------------------------------------
1105+
1106+
/// Standard gamma draws `Gamma(alpha, 1)` for every element of `alpha`, differentiable in `alpha` (implicit
1107+
/// reparameterization).
1108+
pub fn sample_standard_gamma(alpha: &Tensor) -> Result<Tensor> {
1109+
standard_gamma(&alpha.contiguous()?)
1110+
}
1111+
1112+
/// Poisson draws with the given (non-negative) rates, as floats.
1113+
pub fn sample_poisson(rate: &Tensor) -> Result<Tensor> {
1114+
let lam = rate.to_vec::<f64>()?;
1115+
if lam.iter().any(|&l| l.is_nan() || l < 0.0) {
1116+
return Err(Error::Msg("sample_poisson: rates must be non-negative".into()));
1117+
}
1118+
let out: Vec<f64> = rng::with_rng(|r| lam.iter().map(|&l| poisson_draw(r, l)).collect());
1119+
Tensor::from_slice_on(&out, rate.shape(), &rate.device())?.to_dtype(if rate.dtype().is_floating_point() { rate.dtype() } else { crate::dtype::DType::F32 })
1120+
}
1121+
1122+
/// Von Mises draws (Best & Fisher 1979) with the given means and concentrations (one shape), wrapped to [-pi, pi).
1123+
pub fn sample_von_mises(loc: &Tensor, concentration: &Tensor) -> Result<Tensor> {
1124+
if loc.shape() != concentration.shape() {
1125+
return Err(Error::Msg("sample_von_mises: loc and concentration must have one shape".into()));
1126+
}
1127+
let (mu, k) = (loc.to_vec::<f64>()?, concentration.to_vec::<f64>()?);
1128+
let out: Vec<f64> = rng::with_rng(|r| {
1129+
mu.iter()
1130+
.zip(&k)
1131+
.map(|(&m, &kappa)| {
1132+
let theta = if kappa < 1e-8 {
1133+
std::f64::consts::PI * (2.0 * r.next_f64() - 1.0)
1134+
} else {
1135+
let tau = 1.0 + (1.0 + 4.0 * kappa * kappa).sqrt();
1136+
let rho = (tau - (2.0 * tau).sqrt()) / (2.0 * kappa);
1137+
let rr = (1.0 + rho * rho) / (2.0 * rho);
1138+
loop {
1139+
let (u1, u2, u3) = (r.next_f64(), r.next_f64(), r.next_f64());
1140+
let z = (std::f64::consts::PI * u1).cos();
1141+
let f = (1.0 + rr * z) / (rr + z);
1142+
let c = kappa * (rr - f);
1143+
if c * (2.0 - c) - u2 > 0.0 || (c / u2).ln() + 1.0 - c >= 0.0 {
1144+
let sign = if u3 > 0.5 { 1.0 } else { -1.0 };
1145+
break sign * f.clamp(-1.0, 1.0).acos();
1146+
}
1147+
}
1148+
};
1149+
let x = theta + m + std::f64::consts::PI;
1150+
x - (x / std::f64::consts::TAU).floor() * std::f64::consts::TAU - std::f64::consts::PI
1151+
})
1152+
.collect()
1153+
});
1154+
Tensor::from_slice_on(&out, loc.shape(), &loc.device())?.to_dtype(if loc.dtype().is_floating_point() { loc.dtype() } else { crate::dtype::DType::F32 })
1155+
}
1156+
11021157
#[cfg(test)]
11031158
mod tests {
11041159
use super::*;

0 commit comments

Comments
 (0)