use std::collections::HashMap; use std::sync::Arc; use ndarray::{s, Array1, Array2}; use crate::error::{Error, Result}; use crate::lora::{Adapter, LoraPair}; /// Model configuration (mirrors `training/kernels/train.py` `CFG["student"]`). #[derive(Debug, Clone)] pub struct SanConfig { pub vocab: usize, pub d_model: usize, pub n_layers: usize, pub ffn_ratio: usize, pub n_heads: usize, pub max_seq_len: usize, pub tied_embeddings: bool, } /// All trainable weights of the FROZEN base, stored as 2-D arrays. pub type ParamMap = HashMap>; pub const EPS: f32 = 1e-5; /// Simple Attention Network - the blank-slate student. /// The base is immutable after load; all learning happens in the attached /// LoRA adapter (`crate::lora`), composed transparently inside forward. pub struct San { pub cfg: SanConfig, pub params: ParamMap, pub adapter: Option>, } impl San { pub fn from_params(params: ParamMap, cfg: SanConfig) -> Result { let d = cfg.d_model; let v = cfg.vocab; let exp_emb = (v, d); if let Some(e) = params.get("tok_emb.weight") { if e.dim() != exp_emb { return Err(Error::Shape { name: "tok_emb.weight".into(), expected: vec![exp_emb.0, exp_emb.1], got: vec![e.dim().0, e.dim().1], }); } } else { return Err(Error::MissingTensor("tok_emb.weight".into())); } let check = |name: &str| -> Result<()> { if params.get(name).is_none() { return Err(Error::MissingTensor(name.into())); } Ok(()) }; for i in 0..cfg.n_layers { check(&format!("blocks.{i}.ln1.weight"))?; check(&format!("blocks.{i}.ln1.bias"))?; check(&format!("blocks.{i}.attn.qkv.weight"))?; check(&format!("blocks.{i}.attn.o.weight"))?; check(&format!("blocks.{i}.ln2.weight"))?; check(&format!("blocks.{i}.ln2.bias"))?; check(&format!("blocks.{i}.mlp.0.weight"))?; check(&format!("blocks.{i}.mlp.0.bias"))?; check(&format!("blocks.{i}.mlp.2.weight"))?; check(&format!("blocks.{i}.mlp.2.bias"))?; } check("ln_f.weight")?; check("ln_f.bias")?; Ok(Self { cfg, params, adapter: None }) } /// Attach the ACTIVE adapter snapshot (inference view). pub fn set_adapter(&mut self, a: Arc) { self.adapter = Some(a); } fn w(&self, name: &str) -> Result<&Array2> { self.params .get(name) .ok_or_else(|| Error::MissingTensor(name.into())) } fn bias_or_zero(&self, name: &str, cols: usize) -> Array2 { match self.params.get(name) { Some(a) => a.clone(), None => Array2::zeros((1, cols)), } } /// Logits for a single sequence (adapter-composed when attached). pub fn forward(&self, ids: &[u32]) -> Result> { self.forward_with(ids, self.adapter.as_deref()) } pub fn forward_with(&self, ids: &[u32], ad: Option<&Adapter>) -> Result> { let (logits, _cache) = self.forward_cached(ids, ad)?; Ok(logits) } /// Greedy autoregressive continuation. pub fn generate(&self, ids: &[u32], gen_len: usize) -> Result> { let mut seq = ids.to_vec(); for _ in 0..gen_len { if seq.len() >= self.cfg.max_seq_len { break; } let logits = self.forward(&seq)?; let t = logits.nrows(); let last = logits.row(t - 1); let next = (0..last.len()) .max_by(|&a, &b| last[a].partial_cmp(&last[b]).unwrap()) .unwrap_or(0); seq.push(next as u32); } Ok(seq[ids.len()..].to_vec()) } // ------------------------------------------------------------------ // cached forward + exact manual backward (LoRA grads only; base frozen) // ------------------------------------------------------------------ pub fn forward_cached( &self, ids: &[u32], ad: Option<&Adapter>, ) -> Result<(Array2, Cache)> { let d = self.cfg.d_model; let t = ids.len(); if t == 0 || t > self.cfg.max_seq_len { return Err(Error::Model(format!( "sequence length {t} out of range (1..={})", self.cfg.max_seq_len ))); } let emb = self.w("tok_emb.weight")?; let pos = self.w("pos")?; let mut x = Array2::::zeros((t, d)); for i in 0..t { let id = ids[i] as usize % emb.nrows(); x.row_mut(i).assign(&emb.row(id)); } x = &x + &pos.slice(s![0..t, ..]); let mut blocks: Vec = Vec::with_capacity(self.cfg.n_layers); for i in 0..self.cfg.n_layers { let (x2, bc) = self.block_cached(&x, i, ad)?; blocks.push(bc); x = x2; } let lnf_w = self.w("ln_f.weight")?; let lnf_b = self.w("ln_f.bias")?; let (xf, ln_stats) = layernorm_cached(&x, lnf_w, lnf_b); let logits = xf.dot(&emb.t()); Ok(( logits, Cache { blocks, final_x: x, final_stats: ln_stats, xf }, )) } /// CE loss at the last position + exact grads for the given adapter's /// A/B tensors. Base weights are NEVER updated by this path. pub fn loss_and_lora_grads( &self, ids: &[u32], target: u32, ad: &Adapter, ) -> Result<(f32, HashMap, Array2)>)> { let (logits, cache) = self.forward_cached(ids, Some(ad))?; let t = logits.nrows(); let v = logits.ncols(); let last = logits.row(t - 1).to_owned(); let mut m = f32::NEG_INFINITY; for &val in last.iter() { if val > m { m = val; } } let mut exps: Vec = last.iter().map(|x| (x - m).exp()).collect(); let sum: f32 = exps.iter().sum(); for e in exps.iter_mut() { *e /= sum; } let ti = (target as usize) % exps.len(); let loss = -exps[ti].max(1e-12).ln(); let mut dlogit = Array2::::zeros((t, v)); { let mut row = dlogit.row_mut(t - 1); for j in 0..v { row[j] = exps[j]; } row[ti] -= 1.0; } // final LN + tied-head backward (emb grad discarded: frozen) let emb = self.w("tok_emb.weight")?; let lnf_w = self.w("ln_f.weight")?; let lnf_b = self.w("ln_f.bias")?; let dxf = dlogit.dot(emb); let dx = layernorm_backward(&dxf, &cache.final_x, &cache.xf, lnf_w, lnf_b, &cache.final_stats); let mut grads: HashMap, Array2)> = ad.pairs.keys().map(|k| (k.clone(), (Array2::zeros((0, 0)), Array2::zeros((0, 0))))).collect(); let mut cur = dx; for i in (0..self.cfg.n_layers).rev() { let bc = &cache.blocks[i]; let prefix = format!("blocks.{i}."); // --- MLP branch --- let d_mlp = self.mlp_backward(&cur, i, bc)?; let dx2 = &cur + &d_mlp; // x2 = x + attn + mlp => split below // --- attention branch --- let (d_attn, mut g_qkv, mut g_o) = self.attn_backward(&dx2, i, bc, ad)?; // route adapter grads let ka = format!("{prefix}attn.qkv"); let ko = format!("{prefix}attn.o"); grads.insert(ka.clone(), g_qkv.take().unwrap()); grads.insert(ko.clone(), g_o.take().unwrap()); // x = x2 - attn contribution... residual: x2 = x + attn_out let dx_in = &dx2 + &d_attn; cur = dx_in; } Ok((loss, grads)) } /// Convenience trainer step on the STANDBY adapter clone. pub fn train_step_on( &self, ids: &[u32], target: u32, ad: &mut Adapter, lr: f32, ) -> Result { let (loss, grads) = self.loss_and_lora_grads(ids, target, ad)?; ad.sgd_step(&grads, lr); Ok(loss) } fn mlp_backward( &self, dout: &Array2, i: usize, bc: &BlockCache, ) -> Result> { let m2_w = self.w(&format!("blocks.{i}.mlp.2.weight"))?; let m2_b = self.w(&format!("blocks.{i}.mlp.2.bias"))?; let m0_w = self.w(&format!("blocks.{i}.mlp.0.weight"))?; let m0_b = self.w(&format!("blocks.{i}.mlp.0.bias"))?; let _ = m2_b; let _ = m0_b; let dg = dout.dot(m2_w); // t x ffn (y = g @ W2^T) let dff = gelu_backward(&dg, &bc.ffn_pre); let dh2 = dff.dot(m0_w); // t x d let (_, stats) = &bc.ln2; let w2 = self.w(&format!("blocks.{i}.ln2.weight"))?; let b2 = self.w(&format!("blocks.{i}.ln2.bias"))?; let dx2 = layernorm_backward(&dh2, &bc.x2, &bc.h2, w2, b2, stats); Ok(dx2) } #[allow(clippy::type_complexity)] fn attn_backward( &self, dout_total: &Array2, i: usize, bc: &BlockCache, ad: &Adapter, ) -> Result<(Array2, Option<(Array2, Array2)>, Option<(Array2, Array2)>)> { let d = self.cfg.d_model; let h = self.cfg.n_heads; let dh = d / h; let o_w = self.w(&format!("blocks.{i}.attn.o.weight"))?; // o projection backward FIRST (its dx feeds the head loop): // y = ctx@Wo^T + (ctx Ao^T) Bo^T // base path to ctx: dctx = dy @ Wo // adapter grads use RAW upstream dy: dB = dy^T @ u, du = dy @ Bo, // dA = du^T @ ctx, and ctx also receives du @ Ao. let key_o = format!("blocks.{i}.attn.o"); let mut g_o = None; let mut d_ctx_in = dout_total.dot(o_w); if let Some(p) = ad.pairs.get(&key_o) { let u = bc.ctx.dot(&p.a.t()); // t x r let db = dout_total.t().dot(&u); // out x r let du = dout_total.dot(&p.b); // t x r let da = du.t().dot(&bc.ctx); // r x in g_o = Some((da.clone(), db.clone())); d_ctx_in = &d_ctx_in + &du.dot(&p.a); } let mut dq = Array2::::zeros(d_ctx_in.dim()); let mut dk = Array2::::zeros(d_ctx_in.dim()); let mut dv = Array2::::zeros(d_ctx_in.dim()); for head in 0..h { let sl = |m: &Array2| m.slice(s![.., head * dh..(head + 1) * dh]).to_owned(); let qh = sl(&bc.q); let kh = sl(&bc.k); let vh = sl(&bc.v); let ph = &bc.p[head]; let dch = d_ctx_in.slice(s![.., head * dh..(head + 1) * dh]); let scale = 1.0 / (dh as f32).sqrt(); let dp = dch.dot(&vh.t()); // dP = dCtx V^T let dvh = ph.t().dot(&dch); // dV = P^T dCtx let pdp = ph * &dp; let rowsum = pdp.sum_axis(ndarray::Axis(1)).insert_axis(ndarray::Axis(1)); let ds = ph * (&dp - &rowsum) * scale; // softmax backward let dqh = ds.dot(&kh); let dkh = ds.t().dot(&qh); for r in 0..d_ctx_in.nrows() { for c in 0..dh { dq[[r, head * dh + c]] = dqh[[r, c]]; dk[[r, head * dh + c]] = dkh[[r, c]]; dv[[r, head * dh + c]] = dvh[[r, c]]; } } } // reassemble dq/dk/dv into d(t x 3d) let t = d_ctx_in.nrows(); let mut dqkv = Array2::::zeros((t, 3 * d)); for r in 0..t { for c in 0..d { dqkv[[r, c]] = dq[[r, c]]; dqkv[[r, d + c]] = dk[[r, c]]; dqkv[[r, 2 * d + c]] = dv[[r, c]]; } } let qkv_w = self.w(&format!("blocks.{i}.attn.qkv.weight"))?; let key_q = format!("blocks.{i}.attn.qkv"); let mut g_qkv = None; let d_h1 = match ad.pairs.get(&key_q) { Some(p) => { let u = bc.h1.dot(&p.a.t()); let db = dqkv.t().dot(&u); let du = dqkv.dot(&p.b); let da = du.t().dot(&bc.h1); g_qkv = Some((da, db)); dqkv.dot(qkv_w) + du.dot(&p.a) } None => dqkv.dot(qkv_w), }; let w1 = self.w(&format!("blocks.{i}.ln1.weight"))?; let b1 = self.w(&format!("blocks.{i}.ln1.bias"))?; let (xin, st) = &bc.ln1; let dx = layernorm_backward(&d_h1, xin, &bc.h1, w1, b1, st); // residual x2 = x + attn_out: base path gets dout_total directly Ok((dx + dout_total.to_owned(), g_qkv, g_o)) } } // --------------------------------------------------------------------------- // caches // --------------------------------------------------------------------------- pub struct Cache { pub blocks: Vec, pub final_x: Array2, pub final_stats: LnStats, pub xf: Array2, } pub struct BlockCache { pub ln1: (Array2, LnStats), // (x_in, stats) pub h1: Array2, pub q: Array2, pub k: Array2, pub v: Array2, pub p: Vec>, // per-head softmax probs [t,t] pub ctx: Array2, // concatenated head outputs (input to o proj) pub x2: Array2, pub ln2: (Array2, LnStats), pub h2: Array2, pub ffn_pre: Array2, } pub struct LnStats { pub mean: Array1, pub inv_std: Array1, } impl San { fn block_cached( &self, x: &Array2, i: usize, ad: Option<&Adapter>, ) -> Result<(Array2, BlockCache)> { let d = self.cfg.d_model; let h = self.cfg.n_heads; let dh = d / h; let t = x.nrows(); let w1 = self.w(&format!("blocks.{i}.ln1.weight"))?; let b1 = self.w(&format!("blocks.{i}.ln1.bias"))?; let (h1, st1) = layernorm_cached(x, w1, b1); let qkv_w = self.w(&format!("blocks.{i}.attn.qkv.weight"))?; let qkv_b = self.bias_or_zero(&format!("blocks.{i}.attn.qkv.bias"), 3 * d); let mut qkv = h1.dot(&qkv_w.t()) + qkv_b; if let Some(p) = ad.and_then(|a| a.pairs.get(&format!("blocks.{i}.attn.qkv"))) { qkv = &qkv + &h1.dot(&p.a.t()).dot(&p.b.t()); } let mut q = Array2::::zeros((t, d)); let mut k = Array2::::zeros((t, d)); let mut v = Array2::::zeros((t, d)); for r in 0..t { for c in 0..d { q[[r, c]] = qkv[[r, c]]; k[[r, c]] = qkv[[r, d + c]]; v[[r, c]] = qkv[[r, 2 * d + c]]; } } let scale = 1.0 / (dh as f32).sqrt(); let mut ps: Vec> = Vec::with_capacity(h); let mut ctx = Array2::::zeros((t, d)); for head in 0..h { let sl = |m: &Array2| m.slice(s![.., head * dh..(head + 1) * dh]).to_owned(); let qh = sl(&q); let kh = sl(&k); let vh = sl(&v); let sm = qh.dot(&kh.t()) * scale; let ph = softmax_rows(&sm); let ch = ph.dot(&vh); for r in 0..t { for c in 0..dh { ctx[[r, head * dh + c]] = ch[[r, c]]; } } ps.push(ph); } let o_w = self.w(&format!("blocks.{i}.attn.o.weight"))?; let o_b = self.bias_or_zero(&format!("blocks.{i}.attn.o.bias"), d); let mut attn = ctx.dot(&o_w.t()) + o_b; if let Some(p) = ad.and_then(|a| a.pairs.get(&format!("blocks.{i}.attn.o"))) { attn = &attn + &ctx.dot(&p.a.t()).dot(&p.b.t()); } let x2 = x + &attn; let w2 = self.w(&format!("blocks.{i}.ln2.weight"))?; let b2 = self.w(&format!("blocks.{i}.ln2.bias"))?; let (h2, st2) = layernorm_cached(&x2, w2, b2); let m0_w = self.w(&format!("blocks.{i}.mlp.0.weight"))?; let m0_b = self.w(&format!("blocks.{i}.mlp.0.bias"))?; let m2_w = self.w(&format!("blocks.{i}.mlp.2.weight"))?; let m2_b = self.w(&format!("blocks.{i}.mlp.2.bias"))?; let ff_pre = h2.dot(&m0_w.t()) + m0_b; let g = gelu(&ff_pre); let mlp = g.dot(&m2_w.t()) + m2_b; let x_out = &x2 + &mlp; let bc = BlockCache { ln1: (x.to_owned(), st1), h1, q, k, v, p: ps, ctx, x2: x2.clone(), ln2: (x2, st2), h2, ffn_pre: ff_pre, }; Ok((x_out, bc)) } } fn softmax_rows(m: &Array2) -> Array2 { let (t, _c) = m.dim(); let mut out = Array2::::zeros(m.dim()); for i in 0..t { let row = m.row(i); let mx = row.iter().cloned().fold(f32::NEG_INFINITY, f32::max); let ex: Vec = row.iter().map(|x| (x - mx).exp()).collect(); let s: f32 = ex.iter().sum(); for (j, e) in ex.iter().enumerate() { out[[i, j]] = e / s; } } out } fn layernorm_cached(x: &Array2, w: &Array2, b: &Array2) -> (Array2, LnStats) { let (t, d) = x.dim(); let mut out = Array2::zeros((t, d)); let mut mean = Array1::::zeros(t); let mut inv = Array1::::zeros(t); for i in 0..t { let row = x.row(i); let mu = row.sum() / d as f32; let var = row.iter().map(|v| (v - mu).powi(2)).sum::() / d as f32; let iv = 1.0 / (var + EPS).sqrt(); mean[i] = mu; inv[i] = iv; for j in 0..d { out[[i, j]] = (x[[i, j]] - mu) * iv * w[[0, j]] + b[[0, j]]; } } (out, LnStats { mean, inv_std: inv }) } /// dx given upstream dy; weight/bias grads discarded (frozen base). fn layernorm_backward( dy: &Array2, x_in: &Array2, _y: &Array2, w: &Array2, _b: &Array2, st: &LnStats, ) -> Array2 { let (t, d) = x_in.dim(); let mut dx = Array2::zeros((t, d)); for i in 0..t { let mu = st.mean[i]; let iv = st.inv_std[i]; // xhat recomputed cheaply let mut dxhat_sum = 0.0; let mut xdot = 0.0; let mut dxhat = vec![0.0f32; d]; for j in 0..d { let xh = (x_in[[i, j]] - mu) * iv; dxhat[j] = dy[[i, j]] * w[[0, j]]; dxhat_sum += dxhat[j]; xdot += dxhat[j] * xh; } let m1 = dxhat_sum / d as f32; let m2 = xdot / d as f32; for j in 0..d { let xh = (x_in[[i, j]] - mu) * iv; dx[[i, j]] = iv * (dxhat[j] - m1 - xh * m2); } } dx } fn gelu(x: &Array2) -> Array2 { x.mapv(|v| { 0.5 * v * (1.0 + ((2.0 / std::f32::consts::PI).sqrt() * (v + 0.044715 * v.powi(3))).tanh()) }) } fn gelu_backward(dy: &Array2, x: &Array2) -> Array2 { let c = (2.0 / std::f32::consts::PI).sqrt(); let mut out = Array2::zeros(x.dim()); for i in 0..x.len() { let xv = x.as_slice().unwrap()[i]; let u = c * (xv + 0.044715 * xv.powi(3)); let th = u.tanh(); let sech2 = 1.0 - th * th; let gp = 0.5 * (1.0 + th) + 0.5 * xv * sech2 * c * (1.0 + 3.0 * 0.044715 * xv * xv); out.as_slice_mut().unwrap()[i] = dy.as_slice().unwrap()[i] * gp; } out } // --------------------------------------------------------------------------- // tests // --------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; use std::collections::HashMap; fn rnd(r: usize, c: usize) -> Array2 { let n = r * c; let mut s: u64 = 0xA5A5_5A5A_1234_9876 ^ ((n as u64).rotate_left(13)); let mut v = Vec::with_capacity(n); for _ in 0..n { s ^= s << 13; s ^= s >> 7; s ^= s << 17; v.push((((s >> 33) as f32 / (u32::MAX as f32)) - 0.5) * 0.16); } Array2::from_shape_vec((r, c), v).unwrap() } fn tiny_cfg() -> SanConfig { SanConfig { vocab: 10, d_model: 4, n_layers: 1, ffn_ratio: 2, n_heads: 2, max_seq_len: 8, tied_embeddings: true, } } #[test] fn frozen_base_under_lora_training() { let cfg = tiny_cfg(); let mut p: ParamMap = HashMap::new(); let (dv, dd, df) = (10, 4, 8); p.insert("tok_emb.weight".into(), rnd(dv, dd)); p.insert("pos".into(), rnd(8, dd)); p.insert("head.weight".into(), rnd(dv, dd)); p.insert("blocks.0.ln1.weight".into(), rnd(1, dd)); p.insert("blocks.0.ln1.bias".into(), rnd(1, dd)); p.insert("blocks.0.attn.qkv.weight".into(), rnd(3 * dd, dd)); p.insert("blocks.0.attn.o.weight".into(), rnd(dd, dd)); p.insert("blocks.0.ln2.weight".into(), rnd(1, dd)); p.insert("blocks.0.ln2.bias".into(), rnd(1, dd)); p.insert("blocks.0.mlp.0.weight".into(), rnd(df, dd)); p.insert("blocks.0.mlp.0.bias".into(), rnd(1, df)); p.insert("blocks.0.mlp.2.weight".into(), rnd(dd, df)); p.insert("blocks.0.mlp.2.bias".into(), rnd(1, dd)); p.insert("ln_f.weight".into(), rnd(1, dd)); p.insert("ln_f.bias".into(), rnd(1, dd)); let san = San::from_params(p, cfg.clone()).unwrap(); let mut ad = Adapter::fresh(&cfg); let base_before = san.params["tok_emb.weight"].clone(); let ids = vec![1u32, 2, 3, 4]; for _ in 0..3 { let loss = san.train_step_on(&ids, 7, &mut ad, 0.05).unwrap(); assert!(loss.is_finite() && loss > 0.0); } assert_eq!( san.params["tok_emb.weight"], base_before, "base must stay frozen" ); let bsum: f32 = ad.pairs["blocks.0.attn.o"].b.iter().map(|x| x.abs()).sum(); assert!(bsum > 0.0, "adapter B must have moved"); } #[test] fn lora_grads_match_finite_differences() { let cfg = SanConfig { vocab: 12, d_model: 8, n_layers: 1, ffn_ratio: 2, n_heads: 2, max_seq_len: 6, tied_embeddings: true, }; let mut p: ParamMap = HashMap::new(); let (v, d, f, ml) = (12, 8, 16, 6); p.insert("tok_emb.weight".into(), rnd(v, d)); p.insert("pos".into(), rnd(ml, d)); p.insert("blocks.0.ln1.weight".into(), rnd(1, d)); p.insert("blocks.0.ln1.bias".into(), rnd(1, d)); p.insert("blocks.0.attn.qkv.weight".into(), rnd(3 * d, d)); p.insert("blocks.0.attn.o.weight".into(), rnd(d, d)); p.insert("blocks.0.ln2.weight".into(), rnd(1, d)); p.insert("blocks.0.ln2.bias".into(), rnd(1, d)); p.insert("blocks.0.mlp.0.weight".into(), rnd(f, d)); p.insert("blocks.0.mlp.0.bias".into(), rnd(1, f)); p.insert("blocks.0.mlp.2.weight".into(), rnd(d, f)); p.insert("blocks.0.mlp.2.bias".into(), rnd(1, d)); p.insert("ln_f.weight".into(), rnd(1, d)); p.insert("ln_f.bias".into(), rnd(1, d)); let san = San::from_params(p, cfg.clone()).unwrap(); let mut ad = Adapter::fresh(&cfg); // simulate a partially-trained adapter: non-zero B makes BOTH dA and // dB paths live, and lifts grads above f32 finite-difference noise. { let mut s: u64 = 0xC0FFEE_1234_5678; for pr in ad.pairs.values_mut() { for x in pr.b.iter_mut() { s ^= s << 13; s ^= s >> 7; s ^= s << 17; *x = (((s >> 40) as f32 / (1u32 << 24) as f32) - 0.5) * 0.08; } } } let ids = vec![1u32, 4, 2, 9, 3]; let target = 6u32; let (_l0, grads) = san.loss_and_lora_grads(&ids, target, &ad).unwrap(); // finite-difference check on the LARGEST-magnitude entries (robust // against f32 loss resolution) with entry-scaled step sizes. let check = |key: &str, is_a: bool| { let g = if is_a { &grads[key].0 } else { &grads[key].1 }; let mut pos = (0usize, 0usize); let mut best = 0.0f32; for i in 0..g.nrows() { for j in 0..g.ncols() { if g[[i, j]].abs() > best { best = g[[i, j]].abs(); pos = (i, j); } } } assert!(best > 1e-6, "analytic {key} grad too small to verify"); let eps = (1e-3 / best.max(1e-3)).min(0.25).max(1e-3); let mut adp = ad.clone(); let orig = if is_a { adp.pairs[key].a[pos] } else { adp.pairs[key].b[pos] }; if is_a { adp.pairs.get_mut(key).unwrap().a[pos] = orig + eps; } else { adp.pairs.get_mut(key).unwrap().b[pos] = orig + eps; } let (lp, _) = san.loss_and_lora_grads(&ids, target, &adp).unwrap(); if is_a { adp.pairs.get_mut(key).unwrap().a[pos] = orig - eps; } else { adp.pairs.get_mut(key).unwrap().b[pos] = orig - eps; } let (lm, _) = san.loss_and_lora_grads(&ids, target, &adp).unwrap(); let numeric = (lp - lm) / (2.0 * eps); let analytic = g[pos]; assert!(lp.is_finite() && lm.is_finite()); assert!( ((numeric - analytic).abs() / analytic.abs()) < 5e-2, "{key}{} numeric={numeric} analytic={analytic}", if is_a { ".A" } else { ".B" } ); }; check("blocks.0.attn.o", false); // dB check("blocks.0.attn.qkv", true); // dA check("blocks.0.attn.qkv", false); } }