Skip to content

Commit 9914b48

Browse files
voidstackloopclaude
andcommitted
transforms: value_and_grad / grad_argnums / jacrev over several inputs, jacfwd, per_sample_grads, functional_call; match torch.func
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent a34d1fd commit 9914b48

5 files changed

Lines changed: 334 additions & 0 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ pub mod serving;
111111
pub mod signal;
112112
pub mod sparse;
113113
pub mod structured;
114+
pub mod transforms;
114115
pub mod sparse_ext;
115116
pub mod ops_stats;
116117
pub mod samplers_ext;
Lines changed: 238 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,238 @@
1+
//! Function transforms over several inputs (the `torch.func` surface beyond the single-input helpers of [`crate::functional`]):
2+
//! [`value_and_grad`], [`grad_argnums`], [`jacrev`] (reverse mode, any number of inputs), [`jacfwd`] (forward mode),
3+
//! [`per_sample_grads`] and [`functional_call`].
4+
5+
use crate::error::{Error, Result};
6+
use crate::functional::jvp;
7+
use crate::nn::Module;
8+
use crate::tensor::{Tensor, enable_grad, grad, no_grad};
9+
use std::collections::HashMap;
10+
11+
fn leaves(inputs: &[Tensor], argnums: &[usize]) -> Result<Vec<Tensor>> {
12+
if let Some(&bad) = argnums.iter().find(|&&a| a >= inputs.len()) {
13+
return Err(Error::Msg(format!("transforms: argnum {bad} is out of range for {} inputs", inputs.len())));
14+
}
15+
Ok(inputs.iter().enumerate().map(|(i, t)| if argnums.contains(&i) { t.detach().requires_grad_(true) } else { t.detach() }).collect())
16+
}
17+
18+
/// `f(inputs)` (a scalar) and its gradients with respect to the inputs listed in `argnums`, in that order.
19+
pub fn value_and_grad<F>(f: F, inputs: &[Tensor], argnums: &[usize]) -> Result<(Tensor, Vec<Tensor>)>
20+
where
21+
F: Fn(&[Tensor]) -> Result<Tensor>,
22+
{
23+
let xs = leaves(inputs, argnums)?;
24+
let y = enable_grad(|| f(&xs))?;
25+
if y.numel() != 1 {
26+
return Err(Error::Msg(format!("value_and_grad: the function must return a scalar, got shape {:?}", y.shape())));
27+
}
28+
let wrt: Vec<Tensor> = argnums.iter().map(|&a| xs[a].clone()).collect();
29+
let gs = grad(std::slice::from_ref(&y), &wrt, None, false)?;
30+
let grads = gs.into_iter().zip(&wrt).map(|(g, w)| match g {
31+
Some(g) => Ok(g),
32+
None => w.zeros_like(),
33+
}).collect::<Result<Vec<_>>>()?;
34+
Ok((y.detach(), grads))
35+
}
36+
37+
/// Gradients of the scalar `f(inputs)` with respect to the inputs listed in `argnums`.
38+
pub fn grad_argnums<F>(f: F, inputs: &[Tensor], argnums: &[usize]) -> Result<Vec<Tensor>>
39+
where
40+
F: Fn(&[Tensor]) -> Result<Tensor>,
41+
{
42+
value_and_grad(f, inputs, argnums).map(|(_, g)| g)
43+
}
44+
45+
/// Reverse-mode Jacobians: for every input in `argnums`, a tensor of shape `[out_shape..., in_shape...]`.
46+
pub fn jacrev<F>(f: F, inputs: &[Tensor], argnums: &[usize]) -> Result<Vec<Tensor>>
47+
where
48+
F: Fn(&[Tensor]) -> Result<Tensor>,
49+
{
50+
let xs = leaves(inputs, argnums)?;
51+
let y = enable_grad(|| f(&xs))?;
52+
let wrt: Vec<Tensor> = argnums.iter().map(|&a| xs[a].clone()).collect();
53+
let m = y.numel();
54+
let mut rows: Vec<Vec<Tensor>> = vec![Vec::with_capacity(m); wrt.len()];
55+
for i in 0..m {
56+
let mut onehot = vec![0.0f64; m];
57+
onehot[i] = 1.0;
58+
let seed = Tensor::from_slice(&onehot, &[m])?.to_dtype(y.dtype())?.reshape(y.shape())?;
59+
let gs = grad(std::slice::from_ref(&y), &wrt, Some(std::slice::from_ref(&seed)), true)?;
60+
for (k, (g, w)) in gs.into_iter().zip(&wrt).enumerate() {
61+
rows[k].push(match g {
62+
Some(g) => g.detach(),
63+
None => w.zeros_like()?,
64+
});
65+
}
66+
}
67+
rows.into_iter()
68+
.zip(&wrt)
69+
.map(|(r, w)| {
70+
let mut shape = y.shape().to_vec();
71+
shape.extend_from_slice(w.shape());
72+
Tensor::stack(&r, 0)?.reshape(&shape)
73+
})
74+
.collect()
75+
}
76+
77+
/// Forward-mode Jacobian of a single-input function: one Jacobian-vector product per input element; shape
78+
/// `[out_shape..., in_shape...]`.
79+
pub fn jacfwd<F>(f: F, x: &Tensor) -> Result<Tensor>
80+
where
81+
F: Fn(&Tensor) -> Result<Tensor>,
82+
{
83+
let n = x.numel();
84+
let mut cols = Vec::with_capacity(n);
85+
let mut out_shape = Vec::new();
86+
for j in 0..n {
87+
let mut basis = vec![0.0f64; n];
88+
basis[j] = 1.0;
89+
let v = Tensor::from_slice(&basis, &[n])?.to_dtype(x.dtype())?.reshape(x.shape())?;
90+
let (y, t) = jvp(&f, x, &v)?;
91+
out_shape = y.shape().to_vec();
92+
cols.push(t.detach());
93+
}
94+
let mut shape = out_shape;
95+
shape.extend_from_slice(x.shape());
96+
// columns are indexed by the input element: stack along a trailing axis, then restore the input shape
97+
let jac = Tensor::stack(&cols, -1)?;
98+
let lead: Vec<usize> = jac.shape()[..jac.ndim() - 1].to_vec();
99+
let mut full = lead;
100+
full.extend_from_slice(x.shape());
101+
let _ = shape;
102+
jac.reshape(&full)
103+
}
104+
105+
/// Per-example gradients: `loss_of(i)` builds the scalar loss of example `i`; the result holds, for every parameter, a tensor
106+
/// `[batch, ...param shape]` of the gradients of the individual losses (what `vmap(grad(...))` returns in `torch.func`).
107+
pub fn per_sample_grads<F>(params: &[Tensor], batch: usize, loss_of: F) -> Result<Vec<Tensor>>
108+
where
109+
F: Fn(usize) -> Result<Tensor>,
110+
{
111+
let mut per_param: Vec<Vec<Tensor>> = vec![Vec::with_capacity(batch); params.len()];
112+
for i in 0..batch {
113+
for p in params {
114+
p.zero_grad();
115+
}
116+
let loss = enable_grad(|| loss_of(i))?;
117+
loss.backward()?;
118+
for (k, p) in params.iter().enumerate() {
119+
per_param[k].push(match p.grad() {
120+
Some(g) => g.detach().contiguous()?,
121+
None => p.zeros_like()?,
122+
});
123+
}
124+
}
125+
for p in params {
126+
p.zero_grad();
127+
}
128+
per_param.into_iter().map(|g| Tensor::stack(&g, 0)).collect()
129+
}
130+
131+
/// Runs `module` with the parameters named in `params` temporarily replaced by the given values (`torch.func.functional_call`
132+
/// for evaluation: ensembles, model averaging, what-if weights). Unlisted parameters keep their values; the originals are
133+
/// restored afterwards, also when the forward pass fails. Gradients of the result flow to the module's own parameter
134+
/// tensors, not to the supplied values.
135+
pub fn functional_call(module: &dyn Module, params: &HashMap<String, Tensor>, input: &Tensor) -> Result<Tensor> {
136+
let named = module.named_parameters();
137+
for k in params.keys() {
138+
if !named.iter().any(|(n, _)| n == k) {
139+
return Err(Error::Msg(format!("functional_call: the module has no parameter named {k:?}")));
140+
}
141+
}
142+
let saved: Vec<(Tensor, Tensor)> = named.iter().filter(|(n, _)| params.contains_key(n)).map(|(_, t)| (t.clone(), t.to_dtype(crate::dtype::DType::F64).and_then(|c| c.contiguous()).and_then(|c| c.to_vec::<f64>()).and_then(|v| Tensor::from_slice(&v, t.shape())).and_then(|c| c.to_dtype(t.dtype())))).map(|(t, c)| c.map(|c| (t, c))).collect::<Result<_>>()?;
143+
let swap = |pairs: Vec<(&Tensor, &Tensor)>| -> Result<()> {
144+
no_grad(|| pairs.into_iter().try_for_each(|(dst, src)| dst.assign(src)))
145+
};
146+
let target: Vec<(&Tensor, &Tensor)> = named.iter().filter_map(|(n, t)| params.get(n).map(|v| (t, v))).collect();
147+
swap(target)?;
148+
let out = module.forward(input);
149+
swap(saved.iter().map(|(t, c)| (t, c)).collect())?;
150+
out
151+
}
152+
153+
#[cfg(test)]
154+
mod tests {
155+
use super::*;
156+
use crate::nn::Linear;
157+
158+
fn v(t: &Tensor) -> Vec<f64> {
159+
t.to_vec::<f64>().unwrap()
160+
}
161+
fn t64(x: &[f64], shape: &[usize]) -> Tensor {
162+
Tensor::from_slice(x, shape).unwrap()
163+
}
164+
165+
#[test]
166+
fn gradients_and_jacobians_over_several_inputs() {
167+
let (x, y) = (t64(&[0.3, -0.7, 1.1], &[3]), t64(&[2.0, 0.5, -1.0], &[3]));
168+
// f = sum(sin(x) * y) + mean(x^2)
169+
let f = |a: &[Tensor]| a[0].sin()?.mul(&a[1])?.sum()?.add(&a[0].square()?.mean()?);
170+
let (val, g) = value_and_grad(f, &[x.clone(), y.clone()], &[0, 1]).unwrap();
171+
let want_val: f64 = (0..3).map(|i| [0.3f64, -0.7, 1.1][i].sin() * [2.0, 0.5, -1.0][i]).sum::<f64>() + [0.09f64, 0.49, 1.21].iter().sum::<f64>() / 3.0;
172+
assert!((val.item::<f64>().unwrap() - want_val).abs() < 1e-12);
173+
let gx = v(&g[0]);
174+
for i in 0..3 {
175+
let (xi, yi) = ([0.3f64, -0.7, 1.1][i], [2.0f64, 0.5, -1.0][i]);
176+
assert!((gx[i] - (xi.cos() * yi + 2.0 * xi / 3.0)).abs() < 1e-12);
177+
assert!((v(&g[1])[i] - xi.sin()).abs() < 1e-12);
178+
}
179+
// reverse and forward Jacobians of a vector function agree with each other and with the analytic one
180+
let w = t64(&[0.5, -1.0, 0.25, 2.0, 1.0, -0.5], &[2, 3]);
181+
let h = |a: &[Tensor]| a[0].matmul(&w.t().unwrap())?.tanh();
182+
let xm = t64(&[0.1, 0.2, -0.3, 0.4, 0.0, 0.9], &[2, 3]);
183+
let jr = jacrev(h, std::slice::from_ref(&xm), &[0]).unwrap().remove(0);
184+
assert_eq!(jr.shape(), [2, 2, 2, 3]);
185+
let jf = jacfwd(|a| a.matmul(&w.t().unwrap())?.tanh(), &xm).unwrap();
186+
assert_eq!(jf.shape(), [2, 2, 2, 3]);
187+
assert!(jr.allclose(&jf, 1e-12, 1e-12).unwrap());
188+
// d out[b, o] / d x[b, k] = (1 - out^2) * w[o, k]
189+
let out = v(&h(std::slice::from_ref(&xm)).unwrap());
190+
let jv = v(&jr);
191+
for b in 0..2 {
192+
for o in 0..2 {
193+
for k in 0..3 {
194+
let want = (1.0 - out[b * 2 + o].powi(2)) * v(&w)[o * 3 + k];
195+
assert!((jv[((b * 2 + o) * 2 + b) * 3 + k] - want).abs() < 1e-12);
196+
}
197+
}
198+
}
199+
assert!(value_and_grad(|a| Ok(a[0].clone()), std::slice::from_ref(&xm), &[0]).is_err());
200+
assert!(grad_argnums(f, &[x, y], &[2]).is_err());
201+
}
202+
203+
#[test]
204+
fn per_sample_gradients_match_one_example_at_a_time_and_sum_to_the_batch_gradient() {
205+
crate::rng::manual_seed(6);
206+
let l = Linear::new(3, 2).unwrap();
207+
let x = Tensor::randn(&[5, 3]).unwrap();
208+
let y = Tensor::randn(&[5, 2]).unwrap();
209+
let params = vec![l.weight.clone(), l.bias.clone().unwrap()];
210+
let loss_i = |i: usize| l.forward(&x.narrow(0, i, 1)?)?.sub(&y.narrow(0, i, 1)?)?.square()?.sum();
211+
let g = per_sample_grads(&params, 5, loss_i).unwrap();
212+
assert_eq!(g[0].shape(), [5, 2, 3]);
213+
assert_eq!(g[1].shape(), [5, 2]);
214+
// the sum of per-sample gradients is the gradient of the summed loss
215+
for p in &params {
216+
p.zero_grad();
217+
}
218+
l.forward(&x).unwrap().sub(&y).unwrap().square().unwrap().sum().unwrap().backward().unwrap();
219+
for (k, p) in params.iter().enumerate() {
220+
let total = g[k].sum_axes(&[0], false).unwrap();
221+
assert!(total.allclose(&p.grad().unwrap(), 1e-4, 1e-4).unwrap());
222+
}
223+
}
224+
225+
#[test]
226+
fn functional_call_swaps_parameters_and_restores_them() {
227+
let l = Linear::new(2, 2).unwrap();
228+
let x = Tensor::from_slice(&[1.0f32, 2.0], &[1, 2]).unwrap();
229+
let before = l.forward(&x).unwrap().to_vec::<f32>().unwrap();
230+
let mut p = HashMap::new();
231+
p.insert("weight".to_string(), Tensor::from_slice(&[1.0f32, 0.0, 0.0, 1.0], &[2, 2]).unwrap());
232+
p.insert("bias".to_string(), Tensor::from_slice(&[10.0f32, 20.0], &[2]).unwrap());
233+
assert_eq!(functional_call(&l, &p, &x).unwrap().to_vec::<f32>().unwrap(), vec![11.0, 22.0]);
234+
assert_eq!(l.forward(&x).unwrap().to_vec::<f32>().unwrap(), before);
235+
p.insert("nope".to_string(), x.clone());
236+
assert!(functional_call(&l, &p, &x).is_err());
237+
}
238+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
//! Cross-validation batch 52: function transforms vs torch.func (tools/crossval/check_batch52.py).
2+
use oxideon_core::functional::{hessian, hvp, jvp, vjp};
3+
use oxideon_core::nn::{Linear, Module};
4+
use oxideon_core::tensor::Tensor;
5+
use oxideon_core::transforms::{jacfwd, jacrev, per_sample_grads, value_and_grad};
6+
7+
fn genv(n: usize, salt: f64) -> Vec<f64> {
8+
(0..n).map(|i| (0.37 * i as f64 + salt).sin() * 1.3 + 0.1 * (0.11 * i as f64 * salt).cos()).collect()
9+
}
10+
fn t(shape: &[usize], salt: f64) -> Tensor {
11+
Tensor::from_slice(&genv(shape.iter().product(), salt), shape).unwrap()
12+
}
13+
fn p(name: &str, x: &Tensor) {
14+
let v = x.to_vec::<f64>().unwrap();
15+
println!("{name} {}", v.iter().map(|a| format!("{a:e}")).collect::<Vec<_>>().join(" "));
16+
}
17+
18+
#[test]
19+
#[ignore]
20+
fn emit_transforms() {
21+
let (x, y) = (t(&[4], 0.4), t(&[4], 1.1));
22+
let f = |a: &[Tensor]| a[0].sin()?.mul(&a[1])?.sum()?.add(&a[0].square()?.mean()?.mul(&a[1].exp()?.mean()?)?);
23+
let (val, g) = value_and_grad(f, &[x.clone(), y.clone()], &[0, 1]).unwrap();
24+
p("value", &val);
25+
p("grad_x", &g[0]);
26+
p("grad_y", &g[1]);
27+
let w = t(&[3, 4], 2.0);
28+
let h = |a: &[Tensor]| a[0].matmul(&w.t().unwrap())?.tanh()?.mul(&a[0].sum_axes(&[1], true)?);
29+
let xm = t(&[2, 4], 0.9);
30+
let jr = jacrev(h, std::slice::from_ref(&xm), &[0]).unwrap().remove(0);
31+
p("jacrev", &jr);
32+
let jf = jacfwd(|a| a.matmul(&w.t().unwrap())?.tanh()?.mul(&a.sum_axes(&[1], true)?), &xm).unwrap();
33+
p("jacfwd", &jf);
34+
let scalar = |a: &Tensor| a.sin()?.mul(a)?.sum()?.add(&a.pow(&a.square()?.add_scalar(1.0)?)?.sum()?);
35+
p("hessian", &hessian(scalar, &x).unwrap());
36+
let v = t(&[4], 3.3);
37+
let (_, hv) = hvp(scalar, &x, &v).unwrap();
38+
p("hvp", &hv);
39+
let vec_f = |a: &Tensor| a.matmul(&w.t().unwrap())?.tanh();
40+
let xv = t(&[2, 4], 0.9);
41+
let (_, jv) = jvp(vec_f, &xv, &t(&[2, 4], 1.5)).unwrap();
42+
p("jvp", &jv);
43+
let (_, vf) = vjp(vec_f, &xv).unwrap();
44+
p("vjp", &vf(&t(&[2, 3], 0.2)).unwrap());
45+
// per-sample gradients of a linear regression loss
46+
let l = Linear::new(4, 3).unwrap();
47+
l.weight.assign(&t(&[3, 4], 0.6)).unwrap();
48+
l.bias.as_ref().unwrap().assign(&t(&[3], 1.4)).unwrap();
49+
let (xb, yb) = (t(&[5, 4], 2.2).to_dtype(oxideon_core::dtype::DType::F32).unwrap(), t(&[5, 3], 0.7).to_dtype(oxideon_core::dtype::DType::F32).unwrap());
50+
let params = vec![l.weight.clone(), l.bias.clone().unwrap()];
51+
let g = per_sample_grads(&params, 5, |i| l.forward(&xb.narrow(0, i, 1)?)?.sub(&yb.narrow(0, i, 1)?)?.square()?.sum()).unwrap();
52+
p("psg_w", &g[0]);
53+
p("psg_b", &g[1]);
54+
}

‎tools/crossval/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ py -3.11 tools/crossval/check_batch3.py rust_values3.txt
6262
| 49 | `crossval_emit49.rs` | `onnxruntime` | ONNX import and execution: five models built with `onnx.helper` at opset 17 (MLP with Gemm alpha / beta / transB, CNN with padded and grouped dilated Conv, BatchNormalization, MaxPool, AveragePool, GlobalAveragePool, a two-head transformer block with LayerNormalization, reshape / transpose attention, erf-GELU and residuals, an embedding model with Gather, LeakyRelu and three reductions, and a shape / elementwise grab bag with Slice, Squeeze, Unsqueeze, Concat, Cast, Clip, Where, Expand, Pow, Log, Tanh, Shape ...) run by the pure-Rust importer: 11 outputs equal onnxruntime's to under 1e-6. Models are built by `make_onnx_models.py` (venv with onnx + onnxruntime). Exporter output also round-trips through the importer in a unit test |
6363
| 50 | `crossval_emit50.rs` | `torch.autocast` / `torch.amp.GradScaler` (CPU) | Mixed precision: matmul under bf16 / f16 autocast agrees with torch to 5e-8 (the same rounding of float32 products to the half type), a float32 `Linear` under bf16 autocast to one bf16 ulp, and the dynamic loss-scale trajectory over 16 steps with overflows at steps 4, 5 and 11 (scale after every step, which steps were taken, final weights) is identical to `torch.amp.GradScaler`. Unit tests add bf16-autocast and pure bf16 / f16 + float32 master-weight training that converge like float32, and a float16 gradient underflow that loss scaling rescues (6 comparisons, no mismatches) |
6464
| 51 | `crossval_emit51.rs` | `torch` | The new `I8` / `I16` / `U16` / `U32` dtypes: float and int64 casts (wrapping through int64 like torch, including values outside the range), wrapping `add` / `sub` / `mul` / `neg` / `abs` of `i8` / `i16` (so `abs(-128) = -128`), `maximum`, `lt`, `ge`, and integer `sum` / `cumsum` accumulating in int64 (this also changes `u8` / `i32` / `bool` sums to torch's int64, which batches 37 and 38 still pass). 32 comparisons, no mismatches. `.npy`, safetensors and PyTorch-checkpoint I/O keep the narrow dtypes (`.npy` `int16` now loads as `I16`, not widened to `I32`) |
65+
| 52 | `crossval_emit52.rs` | `torch.func` | Function transforms: `value_and_grad` over two inputs, `jacrev` and `jacfwd` of a matrix function, `hessian`, `hvp`, `jvp`, `vjp` (the last four are the pre-existing single-input helpers) and per-sample gradients of a linear regression (`vmap(grad(functional_call ...))` in torch): 11 comparisons, no mismatches |
6566

6667
Deliberate differences (documented in the code, excluded from the checks): `std` adds `1e-12` under the square root so the gradient is finite at zero variance (a constant gives `1e-6`, PyTorch 0); `softmax` / `log_softmax` of a row containing `+inf` return the limiting distribution (PyTorch NaN).
6768

‎tools/crossval/check_batch52.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""Batch 52: function transforms (value_and_grad, jacrev, jacfwd, hessian, hvp, jvp, vjp, per-sample gradients) vs torch.func."""
2+
import math, re, sys, warnings
3+
import numpy as np, torch
4+
from torch.func import grad, jacrev, jacfwd, hessian, jvp, vjp, vmap, functional_call
5+
warnings.filterwarnings("ignore")
6+
arrs = {}
7+
for line in open(sys.argv[1], encoding="utf-8"):
8+
line = re.sub(r"^test \S+ \.\.\. ", "", line.strip())
9+
k, _, rest = line.partition(" ")
10+
try: arrs[k] = np.array([float(x) for x in rest.split()])
11+
except ValueError: pass
12+
def genv(n, salt): return [math.sin(0.37 * i + salt) * 1.3 + 0.1 * math.cos(0.11 * i * salt) for i in range(n)]
13+
def t(shape, salt): return torch.tensor(genv(int(np.prod(shape)), salt), dtype=torch.float64).reshape(shape)
14+
bad = n = 0
15+
def check(name, want, tol=1e-9):
16+
global bad, n
17+
n += 1
18+
want = want.detach().double().numpy().ravel(); got = arrs.get(name)
19+
if got is None or got.shape != want.shape: bad += 1; print("SHAPE/MISSING", name, None if got is None else got.shape, want.shape); return
20+
err = np.max(np.abs(got - want) / np.maximum(1, np.abs(want)))
21+
if not err <= tol: bad += 1; print("MISMATCH", name, err)
22+
x, y = t((4,), 0.4), t((4,), 1.1)
23+
f = lambda a, b: (torch.sin(a) * b).sum() + (a ** 2).mean() * torch.exp(b).mean()
24+
check("value", f(x, y)); gx, gy = grad(f, argnums=(0, 1))(x, y); check("grad_x", gx); check("grad_y", gy)
25+
w = t((3, 4), 2.0); xm = t((2, 4), 0.9)
26+
check("jacrev", jacrev(lambda a: torch.tanh(a @ w.T) * a.sum(1, keepdim=True))(xm))
27+
check("jacfwd", jacfwd(lambda a: torch.tanh(a @ w.T) * a.sum(1, keepdim=True))(xm))
28+
scalar = lambda a: (torch.sin(a) * a).sum() + (a ** (a ** 2 + 1.0)).sum()
29+
check("hessian", hessian(scalar)(x))
30+
v = t((4,), 3.3); check("hvp", jvp(grad(scalar), (x,), (v,))[1])
31+
vec_f = lambda a: torch.tanh(a @ w.T); xv = t((2, 4), 0.9)
32+
check("jvp", jvp(vec_f, (xv,), (t((2, 4), 1.5),))[1]); check("vjp", vjp(vec_f, xv)[1](t((2, 3), 0.2))[0])
33+
lin = torch.nn.Linear(4, 3).double()
34+
with torch.no_grad(): lin.weight.copy_(t((3, 4), 0.6)); lin.bias.copy_(t((3,), 1.4))
35+
xb, yb = t((5, 4), 2.2), t((5, 3), 0.7)
36+
params = {k: v.detach() for k, v in lin.named_parameters()}
37+
loss = lambda p, xi, yi: ((functional_call(lin, p, (xi.unsqueeze(0),)) - yi.unsqueeze(0)) ** 2).sum()
38+
g = vmap(grad(loss), in_dims=(None, 0, 0))(params, xb, yb)
39+
check("psg_w", g["weight"], 1e-5); check("psg_b", g["bias"], 1e-5)
40+
print(f"{n} comparisons, {bad} mismatches"); sys.exit(1 if bad else 0)

0 commit comments

Comments
 (0)