|
| 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(¶ms, 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 ¶ms { |
| 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 | +} |
0 commit comments