Skip to main content

memra_engine/
vision_gemma.rs

1//! Vision tower for the gemma-4 family (lane/gemma-vision, 2026-08-16).
2//!
3//! Gemma-4 is its OWN semantic program — nothing here is inherited from the qwen3_5
4//! tower by analogy; every law below was derived from the family's reference
5//! implementation (llama.cpp `clip_graph_gemma4v`, the vendor-blessed consumer of the
6//! official `google/gemma-4-*-qat-q4_0-gguf` mmproj packaging) and the mmproj tensor
7//! census (`research/gemma-vision-20260816/REPORT.md` carries the receipts):
8//!
9//! - ViT: 27 blocks, hidden 1152, 16 heads (head_dim 72), ffn 4304 — but RMS norms
10//!   (not LayerNorm), NO biases anywhere, per-head RMS q/k norms (72), a WEIGHTLESS
11//!   RMS on V before attention, and sandwich post-norms (attn_post / ffn_post) applied
12//!   BEFORE each residual add. Attention runs UNSCALED: kq_scale = 1.0, not 1/sqrt(d).
13//! - FFN is GEGLU-quick: gelu_quick(gate(x)) * up(x), gelu_quick(x) = x*sigmoid(1.702x)
14//!   (llama.cpp default when the mmproj carries neither use_gelu nor use_silu).
15//! - Positions: FACTORED ADDITIVE tables (one x-table, one y-table, 10240 rows each,
16//!   `v.position_embd.weight` logical [2, 10240, 1152]) added to the patch embeddings,
17//!   PLUS a per-layer 2D rope on q/k: first 36 dims rotate by pos_x, last 36 by pos_y,
18//!   neox pairing (d, d+18) inside each half, theta = 100.0 (hardcoded in the
19//!   reference, not a metadata key).
20//! - Input: pixels in [0,1], NO mean/std normalization (image_mean 0 / std 1 in the
21//!   census); the graph applies 2x-1. Patch embed is a bias-less conv16, flattened
22//!   here to a Linear over (c, ky, kx)-ordered 768-float patch rows.
23//! - Head: 3x3 avg-pool over the patch grid (n_merge 3), scale by sqrt(1152),
24//!   (x - std_bias) * std_scale, WEIGHTLESS RMS, then a single 1152 -> 5376 projection
25//!   (`mm.input_projection`; this file ships no ClippableLinear clamp scalars).
26//! - Preprocessing: native resolution — smart-resize to a 48-aligned grid with the
27//!   token budget 40..280 (token = 48x48 px block), bilinear.
28//!
29//! Serving-law note (derived, NOT wired here): gemma-4 image spans decode with
30//! NON-CAUSAL attention inside the LM (`mtmd_decode_use_non_causal` = true for this
31//! family). memra's prime path is causal, so serving gemma vision through it would be
32//! silently wrong — the serving gate must refuse until a masked-prefill arm exists.
33//!
34//! v1 posture matches the qwen tower: correctness-first — f32 GEMMs, `sdpa_naive`,
35//! host-side permutes/rope/geglu; parity gate before any serving path.
36
37use crate::Engine;
38use cudarc::driver::CudaSlice;
39use memra_gguf::dequant::bf16_to_f32;
40use memra_gguf::{GgmlType, GgufFile};
41use std::path::Path;
42
43pub const GV_HIDDEN: usize = 1152;
44pub const GV_HEADS: usize = 16;
45pub const GV_HEAD_DIM: usize = GV_HIDDEN / GV_HEADS; // 72
46pub const GV_INTER: usize = 4304;
47pub const GV_DEPTH: usize = 27;
48pub const GV_PATCH: usize = 16;
49pub const GV_MERGE: usize = 3; // pooling kernel (n_merge)
50pub const GV_POS_ROWS: usize = 10240; // per-axis position table rows
51pub const GV_OUT: usize = 5376; // gemma-4-31B n_embd
52pub const GV_PATCH_IN: usize = 3 * GV_PATCH * GV_PATCH; // 768
53pub const GV_ALIGN: usize = GV_PATCH * GV_MERGE; // 48
54/// Output-token budget (llama.cpp gemma4v: set_limit_image_tokens(40, 280)); a token
55/// is one pooled 48x48-pixel block, so the pixel budget is tokens * 48*48.
56pub const GV_MIN_TOKENS: usize = 40;
57pub const GV_MAX_TOKENS: usize = 280;
58const RMS_EPS: f32 = 1e-6;
59const ROPE_THETA: f32 = 100.0;
60
61/// Begin/end delimiters + the soft token that occupies image positions in the token
62/// stream (gemma-4-31B vocab; the soft token embedding is REPLACED by tower rows).
63pub const GV_TOK_BEGIN: u32 = 255999; // <|image>
64pub const GV_TOK_SOFT: u32 = 258880; // <|image|>
65pub const GV_TOK_END: u32 = 258882; // <image|>
66
67struct GLin {
68    w: CudaSlice<f32>,
69    in_f: usize,
70    out_f: usize,
71}
72
73struct GBlock {
74    ln1: CudaSlice<f32>,
75    ln2: CudaSlice<f32>,
76    attn_post: CudaSlice<f32>,
77    ffn_post: CudaSlice<f32>,
78    q_norm: Vec<f32>,
79    k_norm: Vec<f32>,
80    wq: GLin,
81    wk: GLin,
82    wv: GLin,
83    wo: GLin,
84    gate: GLin,
85    up: GLin,
86    down: GLin,
87}
88
89pub struct GemmaVisionTower {
90    patch_w: GLin, // conv16 flattened: 768 -> 1152, no bias
91    /// Host copies of the factored position tables, [10240, 1152] each.
92    pos_x: Vec<f32>,
93    pos_y: Vec<f32>,
94    blocks: Vec<GBlock>,
95    std_bias: Vec<f32>,
96    std_scale: Vec<f32>,
97    proj: GLin, // 1152 -> 5376
98}
99
100fn read_f32(g: &GgufFile, name: &str) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
101    let t = g
102        .find(name)
103        .ok_or_else(|| format!("gemma vision tensor missing: {name}"))?;
104    let raw = g.tensor_data(t);
105    match t.ggml_type {
106        GgmlType::BF16 => Ok(raw
107            .chunks_exact(2)
108            .map(|c| bf16_to_f32(u16::from_le_bytes([c[0], c[1]])))
109            .collect()),
110        GgmlType::F32 => Ok(raw
111            .chunks_exact(4)
112            .map(|c| f32::from_le_bytes(c.try_into().unwrap()))
113            .collect()),
114        other => Err(format!("gemma vision tensor {name}: unsupported type {other:?}").into()),
115    }
116}
117
118fn load_lin(
119    e: &Engine,
120    g: &GgufFile,
121    name: &str,
122    in_f: usize,
123    out_f: usize,
124) -> Result<GLin, Box<dyn std::error::Error>> {
125    let w = read_f32(g, name)?;
126    assert_eq!(w.len(), in_f * out_f, "{name} shape");
127    Ok(GLin {
128        w: e.htod(&w)?,
129        in_f,
130        out_f,
131    })
132}
133
134/// The dyn-size resize law (llama.cpp `calc_size_preserved_ratio`, "smart_resize"):
135/// round each side to the 48 grid, then rescale into the [min,max] pixel budget with
136/// floor/ceil-to-48 — identical arithmetic, so the grid memra feeds the tower is the
137/// grid the reference implementation would feed it.
138pub fn gemma_target_size(w: u32, h: u32) -> (u32, u32) {
139    let align = GV_ALIGN as f32;
140    let min_px = (GV_MIN_TOKENS * GV_ALIGN * GV_ALIGN) as f32;
141    let max_px = (GV_MAX_TOKENS * GV_ALIGN * GV_ALIGN) as f32;
142    let round = |x: f32| ((x / align).round() * align).max(align) as u32;
143    let ceilf = |x: f32| ((x / align).ceil() * align).max(align) as u32;
144    let floorf = |x: f32| ((x / align).floor() * align).max(align) as u32;
145    let (wf, hf) = (w as f32, h as f32);
146    let mut w_bar = round(wf);
147    let mut h_bar = round(hf);
148    if (w_bar * h_bar) as f32 > max_px {
149        let beta = (wf * hf / max_px).sqrt();
150        w_bar = floorf(wf / beta);
151        h_bar = floorf(hf / beta);
152    } else if ((w_bar * h_bar) as f32) < min_px {
153        let beta = (min_px / (wf * hf)).sqrt();
154        w_bar = ceilf(wf * beta);
155        h_bar = ceilf(hf * beta);
156    }
157    (w_bar, h_bar)
158}
159
160/// One preprocessed gemma image, server-carried from the HTTP layer to the GPU worker.
161/// `patches` is the tower input (dropped after the tower forward); `n_soft` is the pooled
162/// token count = (gw/3)(gh/3), i.e. the number of `<|image|>` soft tokens the prompt run
163/// must carry for this unit.
164pub struct GemmaVisionUnit {
165    pub patches: Vec<f32>,
166    pub gw: usize,
167    pub gh: usize,
168}
169
170impl GemmaVisionUnit {
171    pub fn n_soft(&self) -> usize {
172        n_soft_for_grid(self.gw, self.gh)
173    }
174}
175
176/// Soft tokens a `(gw, gh)` grid pools to — the planned twin of
177/// `GemmaVisionUnit::n_soft`, usable from `gemma_plan_image` BEFORE any decode.
178pub fn n_soft_for_grid(gw: usize, gh: usize) -> usize {
179    (gw / GV_MERGE) * (gh / GV_MERGE)
180}
181
182/// Decode a base64 `data:` URI to raw image bytes (mirrors vision_pre::decode_data_uri;
183/// http(s) fetch stays off for SSRF).
184pub fn gemma_decode_data_uri(uri: &str) -> Result<Vec<u8>, String> {
185    let comma = uri.find(',').ok_or("data URI has no comma")?;
186    let meta = &uri[..comma];
187    let body = &uri[comma + 1..];
188    if !meta.contains(";base64") {
189        return Err("only base64 data URIs are supported".into());
190    }
191    use base64::Engine as _;
192    base64::engine::general_purpose::STANDARD
193        .decode(body.as_bytes())
194        .map_err(|e| format!("base64 decode: {e}"))
195}
196
197/// Prep a data-URI image into a GemmaVisionUnit (decode + smart-resize + patchify).
198pub fn gemma_prep_data_uri(uri: &str) -> Result<GemmaVisionUnit, String> {
199    let bytes = gemma_decode_data_uri(uri)?;
200    let (patches, gw, gh) = gemma_prep_image(&bytes).map_err(|e| e.to_string())?;
201    Ok(GemmaVisionUnit { patches, gw, gh })
202}
203
204/// PRE-DECODE admission (hermes decode-bomb finding, fixed 2026-08-23 — same law as
205/// `vision_pre::plan_image_bytes`): header dims -> decode-budget check -> target grid.
206/// Returns `(gw, gh)` so `n_soft` (thus the pad run and the request's token price) is
207/// known before any canvas expands.
208pub fn gemma_plan_image(bytes: &[u8]) -> Result<(usize, usize), String> {
209    let (w, h) = crate::vision_pre::image_header_dims(bytes)?;
210    if w.saturating_mul(h) > crate::vision_pre::IMG_MAX_DECODE_PIXELS {
211        return Err(format!(
212            "image {w}x{h} exceeds the decode budget ({} px) — refused before decode",
213            crate::vision_pre::IMG_MAX_DECODE_PIXELS
214        ));
215    }
216    let (tw, th) = gemma_target_size(w as u32, h as u32);
217    Ok(((tw as usize) / GV_PATCH, (th as usize) / GV_PATCH))
218}
219
220/// Decode + resize + patchify one image: bytes -> (patch rows [n, 768] in the conv's
221/// (c, ky, kx) flat order with the graph's 2x-1 scaling baked in, grid_w, grid_h).
222/// Admission runs FIRST (`gemma_plan_image`, header-only); the decoder is capped to the
223/// admitted dimensions so a header lying small cannot expand past them.
224pub fn gemma_prep_image(
225    bytes: &[u8],
226) -> Result<(Vec<f32>, usize, usize), Box<dyn std::error::Error>> {
227    gemma_plan_image(bytes)?;
228    let (hw, hh) = crate::vision_pre::image_header_dims(bytes)?;
229    let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?;
230    let mut limits = image::Limits::default();
231    limits.max_image_width = Some(hw as u32);
232    limits.max_image_height = Some(hh as u32);
233    reader.limits(limits);
234    let img = reader.decode()?.to_rgb8();
235    let (w0, h0) = img.dimensions();
236    let (tw, th) = gemma_target_size(w0, h0);
237    // Bilinear per the reference (RESIZE_ALGO_BILINEAR); image's Triangle filter is the
238    // bilinear kernel. Resize kernels are allowed to differ by a hair from llama.cpp's
239    // own bilinear — the parity oracle feeds FIXED pixels so the tower is gated
240    // independently of resampling.
241    let resized = image::imageops::resize(&img, tw, th, image::imageops::FilterType::Triangle);
242    let (gw, gh) = ((tw as usize) / GV_PATCH, (th as usize) / GV_PATCH);
243    let mut patches = vec![0f32; gw * gh * GV_PATCH_IN];
244    for py in 0..gh {
245        for px in 0..gw {
246            let dst = &mut patches[(py * gw + px) * GV_PATCH_IN..(py * gw + px + 1) * GV_PATCH_IN];
247            for c in 0..3 {
248                for ky in 0..GV_PATCH {
249                    for kx in 0..GV_PATCH {
250                        let p = resized
251                            .get_pixel((px * GV_PATCH + kx) as u32, (py * GV_PATCH + ky) as u32);
252                        // [0,1] then the graph's 2x-1
253                        dst[(c * GV_PATCH + ky) * GV_PATCH + kx] =
254                            (p[c] as f32) / 255.0 * 2.0 - 1.0;
255                    }
256                }
257            }
258        }
259    }
260    Ok((patches, gw, gh))
261}
262
263impl GemmaVisionTower {
264    /// Load the tower from a gemma-4 mmproj GGUF (`general.type = mmproj`,
265    /// `clip.vision.projector_type = gemma4v`).
266    pub fn load(e: &Engine, path: &Path) -> Result<Self, Box<dyn std::error::Error>> {
267        let g = GgufFile::open(path)?;
268        let proj_type = g
269            .metadata
270            .get("clip.vision.projector_type")
271            .and_then(|v| v.as_str())
272            .unwrap_or_default();
273        if proj_type != "gemma4v" {
274            return Err(format!(
275                "mmproj {path:?} projector_type {proj_type:?} is not gemma4v — this loader \
276                 refuses other families by design (no generic support claims)",
277                path = path
278            )
279            .into());
280        }
281        let patch_w = {
282            // conv weight logical [1152, 3, 16, 16] row-major == Linear rows over the
283            // (c, ky, kx) patch order gemma_prep_image emits.
284            let w = read_f32(&g, "v.patch_embd.weight")?;
285            assert_eq!(
286                w.len(),
287                GV_HIDDEN * GV_PATCH_IN,
288                "v.patch_embd.weight shape"
289            );
290            GLin {
291                w: e.htod(&w)?,
292                in_f: GV_PATCH_IN,
293                out_f: GV_HIDDEN,
294            }
295        };
296        let pos = read_f32(&g, "v.position_embd.weight")?;
297        assert_eq!(
298            pos.len(),
299            2 * GV_POS_ROWS * GV_HIDDEN,
300            "position table shape"
301        );
302        let (pos_x, pos_y) = {
303            let half = GV_POS_ROWS * GV_HIDDEN;
304            (pos[..half].to_vec(), pos[half..].to_vec())
305        };
306        let mut blocks = Vec::with_capacity(GV_DEPTH);
307        for il in 0..GV_DEPTH {
308            let bp = format!("v.blk.{il}");
309            blocks.push(GBlock {
310                ln1: e.htod(&read_f32(&g, &format!("{bp}.ln1.weight"))?)?,
311                ln2: e.htod(&read_f32(&g, &format!("{bp}.ln2.weight"))?)?,
312                attn_post: e.htod(&read_f32(&g, &format!("{bp}.attn_post_norm.weight"))?)?,
313                ffn_post: e.htod(&read_f32(&g, &format!("{bp}.ffn_post_norm.weight"))?)?,
314                q_norm: read_f32(&g, &format!("{bp}.attn_q_norm.weight"))?,
315                k_norm: read_f32(&g, &format!("{bp}.attn_k_norm.weight"))?,
316                wq: load_lin(e, &g, &format!("{bp}.attn_q.weight"), GV_HIDDEN, GV_HIDDEN)?,
317                wk: load_lin(e, &g, &format!("{bp}.attn_k.weight"), GV_HIDDEN, GV_HIDDEN)?,
318                wv: load_lin(e, &g, &format!("{bp}.attn_v.weight"), GV_HIDDEN, GV_HIDDEN)?,
319                wo: load_lin(
320                    e,
321                    &g,
322                    &format!("{bp}.attn_out.weight"),
323                    GV_HIDDEN,
324                    GV_HIDDEN,
325                )?,
326                gate: load_lin(e, &g, &format!("{bp}.ffn_gate.weight"), GV_HIDDEN, GV_INTER)?,
327                up: load_lin(e, &g, &format!("{bp}.ffn_up.weight"), GV_HIDDEN, GV_INTER)?,
328                down: load_lin(e, &g, &format!("{bp}.ffn_down.weight"), GV_INTER, GV_HIDDEN)?,
329            });
330        }
331        let std_bias = read_f32(&g, "v.std_bias")?;
332        let std_scale = read_f32(&g, "v.std_scale")?;
333        assert_eq!(std_bias.len(), GV_HIDDEN);
334        assert_eq!(std_scale.len(), GV_HIDDEN);
335        let proj = load_lin(e, &g, "mm.input_projection.weight", GV_HIDDEN, GV_OUT)?;
336        eprintln!(
337            "[gemma-vision] tower loaded from {} ({GV_DEPTH} blocks, f32-resident)",
338            path.display()
339        );
340        Ok(Self {
341            patch_w,
342            pos_x,
343            pos_y,
344            blocks,
345            std_bias,
346            std_scale,
347            proj,
348        })
349    }
350
351    fn linear(
352        &self,
353        e: &Engine,
354        x: &CudaSlice<f32>,
355        l: &GLin,
356        m: usize,
357    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
358        e.linear(x, &l.w, m, l.in_f, l.out_f)
359    }
360
361    /// Forward one image's patch rows -> [gh*gw/9, 5376] embeddings (device).
362    pub fn forward(
363        &self,
364        e: &Engine,
365        patches: &[f32],
366        gw: usize,
367        gh: usize,
368    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
369        let n = gw * gh;
370        assert_eq!(patches.len(), n * GV_PATCH_IN, "patch buffer shape");
371        assert_eq!(gw % GV_MERGE, 0, "grid width must be 3-aligned");
372        assert_eq!(gh % GV_MERGE, 0, "grid height must be 3-aligned");
373        if n > 12288 {
374            return Err(format!(
375                "gemma vision segment {n} patches exceeds the sdpa shared-memory ceiling (12288)"
376            )
377            .into());
378        }
379        let dbg = std::env::var("MEMRA_VISION_DEBUG").ok();
380        let dump = |tag: &str, buf: &[f32]| {
381            if let Some(dir) = dbg.as_deref() {
382                let raw: Vec<u8> = buf.iter().flat_map(|v| v.to_le_bytes()).collect();
383                let _ = std::fs::write(format!("{dir}/rust_{tag}.bin"), raw);
384            }
385        };
386
387        // patch embed + factored additive position tables (row-major grid: x = col, y = row)
388        let xd = e.htod(patches)?;
389        let embedded = self.linear(e, &xd, &self.patch_w, n)?;
390        let mut pos = vec![0f32; n * GV_HIDDEN];
391        for t in 0..n {
392            let (py, px) = (t / gw, t % gw);
393            let dst = &mut pos[t * GV_HIDDEN..(t + 1) * GV_HIDDEN];
394            let tx = &self.pos_x[px * GV_HIDDEN..(px + 1) * GV_HIDDEN];
395            let ty = &self.pos_y[py * GV_HIDDEN..(py + 1) * GV_HIDDEN];
396            for c in 0..GV_HIDDEN {
397                dst[c] = tx[c] + ty[c];
398            }
399        }
400        let pos_d = e.htod(&pos)?;
401        let mut x = e.zeros(n * GV_HIDDEN)?;
402        e.add(&embedded, &pos_d, &mut x, n * GV_HIDDEN)?;
403        if dbg.is_some() {
404            dump("pre_blocks", &e.dtoh(&x)?);
405        }
406
407        // 2D rope tables: FIRST 36 dims rotate by pos_x, LAST 36 by pos_y (the reference
408        // order — opposite of qwen3_5's y-first); neox pairing (d, d+18) inside each
409        // half; inv_freq[i] = theta^(-2i/36), theta 100.
410        let half = GV_HEAD_DIM / 2; // 36
411        let quarter = half / 2; // 18
412        let inv_freq: Vec<f32> = (0..quarter)
413            .map(|i| ROPE_THETA.powf(-2.0 * (i as f32) / half as f32))
414            .collect();
415        let mut cos_x = vec![0f32; n * quarter];
416        let mut sin_x = vec![0f32; n * quarter];
417        let mut cos_y = vec![0f32; n * quarter];
418        let mut sin_y = vec![0f32; n * quarter];
419        for t in 0..n {
420            let (py, px) = (t / gw, t % gw);
421            for i in 0..quarter {
422                let ax = px as f32 * inv_freq[i];
423                let ay = py as f32 * inv_freq[i];
424                cos_x[t * quarter + i] = ax.cos();
425                sin_x[t * quarter + i] = ax.sin();
426                cos_y[t * quarter + i] = ay.cos();
427                sin_y[t * quarter + i] = ay.sin();
428            }
429        }
430        // per-head RMS over head_dim with weight (q/k) or weightless (v)
431        let head_rms = |row: &mut [f32], w: Option<&[f32]>| {
432            let mut ss = 0f32;
433            for v in row.iter() {
434                ss += v * v;
435            }
436            let inv = 1.0 / (ss / GV_HEAD_DIM as f32 + RMS_EPS).sqrt();
437            for (d, v) in row.iter_mut().enumerate() {
438                *v *= inv * w.map_or(1.0, |w| w[d]);
439            }
440        };
441
442        for (ib, blk) in self.blocks.iter().enumerate() {
443            // attn: rms(ln1) -> q/k/v -> per-head norms -> 2D rope -> sdpa(scale=1) ->
444            //       o_proj -> rms(attn_post) -> +residual
445            let mut h = e.zeros(n * GV_HIDDEN)?;
446            e.rms_norm(&x, &blk.ln1, &mut h, GV_HIDDEN, n, RMS_EPS)?;
447            let q = self.linear(e, &h, &blk.wq, n)?;
448            let k = self.linear(e, &h, &blk.wk, n)?;
449            let v = self.linear(e, &h, &blk.wv, n)?;
450            let (mut qh, mut kh, mut vh) = (e.dtoh(&q)?, e.dtoh(&k)?, e.dtoh(&v)?);
451            for t in 0..n {
452                for hd in 0..GV_HEADS {
453                    let o = t * GV_HIDDEN + hd * GV_HEAD_DIM;
454                    head_rms(&mut qh[o..o + GV_HEAD_DIM], Some(&blk.q_norm));
455                    head_rms(&mut kh[o..o + GV_HEAD_DIM], Some(&blk.k_norm));
456                    head_rms(&mut vh[o..o + GV_HEAD_DIM], None);
457                    // rope: first half by x, second half by y, pairs (d, d+18) per half
458                    for (base, cos, sin) in [(0, &cos_x, &sin_x), (half, &cos_y, &sin_y)] {
459                        for i in 0..quarter {
460                            let (c, s) = (cos[t * quarter + i], sin[t * quarter + i]);
461                            for buf in [&mut qh, &mut kh] {
462                                let a = buf[o + base + i];
463                                let b = buf[o + base + i + quarter];
464                                buf[o + base + i] = a * c - b * s;
465                                buf[o + base + i + quarter] = b * c + a * s;
466                            }
467                        }
468                    }
469                }
470            }
471            let (qd, kd, vd) = (e.htod(&qh)?, e.htod(&kh)?, e.htod(&vh)?);
472            let mut od = e.zeros(n * GV_HIDDEN)?;
473            // UNSCALED attention (kq_scale = 1.0 in the reference graph), full/non-causal.
474            e.sdpa_naive(
475                &qd,
476                &kd,
477                &vd,
478                &mut od,
479                GV_HEAD_DIM,
480                GV_HEADS,
481                GV_HEADS,
482                n,
483                n,
484                1.0,
485                false,
486            )?;
487            let attn = self.linear(e, &od, &blk.wo, n)?;
488            let mut post = e.zeros(n * GV_HIDDEN)?;
489            e.rms_norm(&attn, &blk.attn_post, &mut post, GV_HIDDEN, n, RMS_EPS)?;
490            let mut xr = e.zeros(n * GV_HIDDEN)?;
491            e.add(&x, &post, &mut xr, n * GV_HIDDEN)?;
492
493            // ffn: rms(ln2) -> gelu_quick(gate) * up -> down -> rms(ffn_post) -> +residual
494            let mut h2 = e.zeros(n * GV_HIDDEN)?;
495            e.rms_norm(&xr, &blk.ln2, &mut h2, GV_HIDDEN, n, RMS_EPS)?;
496            let gate = self.linear(e, &h2, &blk.gate, n)?;
497            let up = self.linear(e, &h2, &blk.up, n)?;
498            let (gh_, uh) = (e.dtoh(&gate)?, e.dtoh(&up)?);
499            let mut act = vec![0f32; n * GV_INTER];
500            for i in 0..n * GV_INTER {
501                let g = gh_[i];
502                // gelu_quick(x) = x * sigmoid(1.702 x) — NOT the tanh approximation.
503                act[i] = g / (1.0 + (-1.702 * g).exp()) * uh[i];
504            }
505            let ad = e.htod(&act)?;
506            let down = self.linear(e, &ad, &blk.down, n)?;
507            let mut fpost = e.zeros(n * GV_HIDDEN)?;
508            e.rms_norm(&down, &blk.ffn_post, &mut fpost, GV_HIDDEN, n, RMS_EPS)?;
509            let mut xn = e.zeros(n * GV_HIDDEN)?;
510            e.add(&xr, &fpost, &mut xn, n * GV_HIDDEN)?;
511            x = xn;
512            if dbg.is_some() && ib == 0 {
513                dump("blk0", &e.dtoh(&x)?);
514            }
515        }
516        if dbg.is_some() {
517            dump("post_blocks", &e.dtoh(&x)?);
518        }
519
520        // head: 3x3 avg-pool over the grid -> *sqrt(1152) -> (x - std_bias)*std_scale
521        //       -> weightless RMS -> project 1152 -> 5376
522        let xh = e.dtoh(&x)?;
523        let (mw, mh) = (gw / GV_MERGE, gh / GV_MERGE);
524        let nm = mw * mh;
525        let scale = (GV_HIDDEN as f32).sqrt();
526        let mut pooled = vec![0f32; nm * GV_HIDDEN];
527        for my in 0..mh {
528            for mx in 0..mw {
529                let dst = &mut pooled[(my * mw + mx) * GV_HIDDEN..(my * mw + mx + 1) * GV_HIDDEN];
530                for sy in 0..GV_MERGE {
531                    for sx in 0..GV_MERGE {
532                        let t = (my * GV_MERGE + sy) * gw + (mx * GV_MERGE + sx);
533                        for c in 0..GV_HIDDEN {
534                            dst[c] += xh[t * GV_HIDDEN + c];
535                        }
536                    }
537                }
538                for (c, d) in dst.iter_mut().enumerate() {
539                    *d = (*d / (GV_MERGE * GV_MERGE) as f32 * scale - self.std_bias[c])
540                        * self.std_scale[c];
541                }
542            }
543        }
544        // weightless RMS then projection
545        for row in pooled.chunks_exact_mut(GV_HIDDEN) {
546            let mut ss = 0f32;
547            for v in row.iter() {
548                ss += v * v;
549            }
550            let inv = 1.0 / (ss / GV_HIDDEN as f32 + RMS_EPS).sqrt();
551            for v in row.iter_mut() {
552                *v *= inv;
553            }
554        }
555        if dbg.is_some() {
556            dump("pre_proj", &pooled);
557        }
558        let pd = e.htod(&pooled)?;
559        let out = self.linear(e, &pd, &self.proj, nm)?;
560        if dbg.is_some() {
561            dump("projected", &e.dtoh(&out)?);
562        }
563        Ok(out)
564    }
565}