Elffuss BraidHub

kikocis/coco public

main · 6.0 KiBRawPermalink
1// gdn_ref — ORACLE validation for the GatedDeltaNet port (candle 0.11).
2//
3// Loads the golden fixture (tests/fixtures/gdn_oracle/oracle.safetensors: input + the 7
4// weights + the reference output from HF Qwen3NextGatedDeltaNet) and re-computes the layer
5// forward with candle Tensor ops, following the numpy-verified BLUEPRINT.md (matched the HF
6// oracle to 4e-7). Prints `max abs err` vs golden — the port is correct when this is < 1e-4.
7//
8// cargo run --release --bin gdn_ref
9use anyhow::{anyhow, Result};
10use candle_core::{DType, Device, IndexOp, Tensor, D};
11
12fn silu(x: &Tensor) -> Result<Tensor> {
13 Ok((x * candle_nn::ops::sigmoid(x)?)?)
14}
15fn softplus(x: &Tensor) -> Result<Tensor> {
16 // ln(1 + exp(x)); oracle magnitudes are small, the naive form is fine here.
17 Ok(((x.exp()? + 1.0)?).log()?)
18}
19fn l2norm(x: &Tensor, eps: f64) -> Result<Tensor> {
20 let denom = (x.sqr()?.sum_keepdim(D::Minus1)? + eps)?.sqrt()?;
21 Ok(x.broadcast_div(&denom)?)
22}
23
24fn main() -> Result<()> {
25 let dev = Device::Cpu; // validate in f32 on CPU (the oracle is f32)
26 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/gdn_oracle");
27 let t = candle_core::safetensors::load(format!("{dir}/oracle.safetensors"), &dev)?;
28 let g = |k: &str| -> Result<Tensor> {
29 Ok(t.get(k).ok_or_else(|| anyhow!("missing {k}"))?.to_dtype(DType::F32)?)
30 };
31 let x = g("input")?.squeeze(0)?; // [s,256]
32 let w_qkvz = g("in_proj_qkvz__weight")?; // [768,256]
33 let w_ba = g("in_proj_ba__weight")?; // [16,256]
34 let conv_w = g("conv1d__weight")?; // [512,1,4]
35 let a_log = g("A_log")?; // [nv]
36 let dt = g("dt_bias")?; // [nv]
37 let norm_w = g("norm__weight")?; // [hv]
38 let w_out = g("out_proj__weight")?; // [256,256]
39 let gold = g("output")?.squeeze(0)?; // [s,256]
40
41 let (s, nk, nv, hk, hv, ck) = (x.dim(0)?, 4usize, 8usize, 32usize, 32usize, 4usize);
42 let (kd, vd, rep) = (nk * hk, nv * hv, nv / nk);
43
44 // 1. projections
45 let qkvz = x.matmul(&w_qkvz.t()?)?; // [s,768]
46 let ba = x.matmul(&w_ba.t()?)?; // [s,16]
47
48 // 2. fix_query_key_value_ordering
49 let qkvz = qkvz.reshape((s, nk, 2 * hk + 2 * hv * rep))?;
50 let q = qkvz.narrow(2, 0, hk)?.contiguous()?; // [s,nk,hk]
51 let k = qkvz.narrow(2, hk, hk)?.contiguous()?;
52 let v = qkvz.narrow(2, 2 * hk, rep * hv)?.reshape((s, nv, hv))?;
53 let z = qkvz.narrow(2, 2 * hk + rep * hv, rep * hv)?.reshape((s, nv, hv))?;
54 let ba = ba.reshape((s, nk, 2 * rep))?;
55 let b = ba.narrow(2, 0, rep)?.reshape((s, nv))?;
56 let a = ba.narrow(2, rep, rep)?.reshape((s, nv))?;
57
58 // 3. q,k,v -> [s,-1]; 4. conv (causal depthwise k=4) + silu
59 let q = q.reshape((s, kd))?;
60 let k = k.reshape((s, kd))?;
61 let v3 = v.reshape((s, vd))?;
62 let mixed = Tensor::cat(&[&q, &k, &v3], 1)?; // [s,512]
63 let conv_dim = kd + kd + vd; // 512
64 let mixed_t = mixed.t()?.unsqueeze(0)?.contiguous()?; // [1,512,s]
65 // depthwise causal: pad left (ck-1), conv1d groups=conv_dim, take first s, silu
66 let convd = mixed_t.conv1d(&conv_w, ck - 1, 1, 1, conv_dim)?; // [1,512,s+ck-1]
67 let convd = convd.narrow(2, 0, s)?; // causal: first s
68 let convd = silu(&convd)?;
69 let mixed = convd.squeeze(0)?.t()?.contiguous()?; // [s,512]
70
71 // 5. split -> q,k [s,nk,hk], v [s,nv,hv]
72 let q = mixed.narrow(1, 0, kd)?.reshape((s, nk, hk))?;
73 let k = mixed.narrow(1, kd, kd)?.reshape((s, nk, hk))?;
74 let v = mixed.narrow(1, 2 * kd, vd)?.reshape((s, nv, hv))?;
75
76 // 6. beta = sigmoid(b); g = -exp(A_log) * softplus(a + dt)
77 let beta = candle_nn::ops::sigmoid(&b)?; // [s,nv]
78 let gate = a.broadcast_add(&dt)?;
79 let gate = softplus(&gate)?;
80 let neg_exp_alog = a_log.exp()?.neg()?; // [nv]
81 let gdecay = gate.broadcast_mul(&neg_exp_alog)?; // [s,nv]
82
83 // 7. repeat_interleave q,k by rep along head dim -> [s,nv,hk]
84 let ri = |x: &Tensor| -> Result<Tensor> {
85 Ok(x.reshape((s, nk, 1, hk))?
86 .broadcast_as((s, nk, rep, hk))?
87 .reshape((s, nv, hk))?)
88 };
89 let q = ri(&q)?;
90 let k = ri(&k)?;
91
92 // 8. recurrence (f32): l2norm q,k; q *= 1/sqrt(hk); S[nv,hk,hv]
93 let q = (l2norm(&q, 1e-6)? * (1.0 / (hk as f64).sqrt()))?;
94 let k = l2norm(&k, 1e-6)?;
95 let mut sstate = Tensor::zeros((nv, hk, hv), DType::F32, &dev)?;
96 let mut outs: Vec<Tensor> = Vec::with_capacity(s);
97 for i in 0..s {
98 let q_t = q.i(i)?; // [nv,hk]
99 let k_t = k.i(i)?;
100 let v_t = v.i(i)?; // [nv,hv]
101 let g_t = gdecay.i(i)?.exp()?.reshape((nv, 1, 1))?;
102 let beta_t = beta.i(i)?.reshape((nv, 1))?;
103 sstate = sstate.broadcast_mul(&g_t)?;
104 let k_col = k_t.reshape((nv, hk, 1))?;
105 let kv = sstate.broadcast_mul(&k_col)?.sum(1)?; // [nv,hv]
106 let delta = (v_t - kv)?.broadcast_mul(&beta_t)?; // [nv,hv]
107 let upd = k_col.broadcast_mul(&delta.reshape((nv, 1, hv))?)?; // [nv,hk,hv]
108 sstate = (sstate + upd)?;
109 let out_t = sstate.broadcast_mul(&q_t.reshape((nv, hk, 1))?)?.sum(1)?; // [nv,hv]
110 outs.push(out_t.unsqueeze(0)?);
111 }
112 let out = Tensor::cat(&outs, 0)?; // [s,nv,hv]
113
114 // 9. RMSNormGated(out, z)
115 let oc = out.reshape((s * nv, hv))?;
116 let zc = z.reshape((s * nv, hv))?;
117 let var = oc.sqr()?.mean_keepdim(D::Minus1)?;
118 let oc = oc.broadcast_div(&(var + 1e-6)?.sqrt()?)?;
119 let oc = oc.broadcast_mul(&norm_w)?;
120 let oc = (oc * silu(&zc)?)?;
121 let oc = oc.reshape((s, vd))?;
122
123 // 10. out_proj
124 let y = oc.matmul(&w_out.t()?)?; // [s,256]
125
126 let err = (&y - &gold)?.abs()?;
127 let maxerr = err.max(D::Minus1)?.max(D::Minus1)?.to_scalar::<f32>()?;
128 let meanerr = err.mean_all()?.to_scalar::<f32>()?;
129 println!("GDN candle port vs oracle: max_abs_err = {maxerr:.3e} mean_abs_err = {meanerr:.3e}");
130 let y0: Vec<f32> = y.i(0)?.narrow(0, 0, 5)?.to_vec1()?;
131 let g0: Vec<f32> = gold.i(0)?.narrow(0, 0, 5)?.to_vec1()?;
132 println!(" y[0,:5] = {y0:?}");
133 println!(" gold[0,:5] = {g0:?}");
134 if maxerr < 1e-4 {
135 println!(" ✅ PASS (< 1e-4) — GatedDeltaNet forward matches the HF oracle.");
136 } else {
137 println!(" ❌ mismatch — debug the port.");
138 }
139 Ok(())
140}