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        (self.gw / GV_MERGE) * (self.gh / GV_MERGE)
173    }
174}
175
176/// Decode a base64 `data:` URI to raw image bytes (mirrors vision_pre::decode_data_uri;
177/// http(s) fetch stays off for SSRF).
178pub fn gemma_decode_data_uri(uri: &str) -> Result<Vec<u8>, String> {
179    let comma = uri.find(',').ok_or("data URI has no comma")?;
180    let meta = &uri[..comma];
181    let body = &uri[comma + 1..];
182    if !meta.contains(";base64") {
183        return Err("only base64 data URIs are supported".into());
184    }
185    use base64::Engine as _;
186    base64::engine::general_purpose::STANDARD
187        .decode(body.as_bytes())
188        .map_err(|e| format!("base64 decode: {e}"))
189}
190
191/// Prep a data-URI image into a GemmaVisionUnit (decode + smart-resize + patchify).
192pub fn gemma_prep_data_uri(uri: &str) -> Result<GemmaVisionUnit, String> {
193    let bytes = gemma_decode_data_uri(uri)?;
194    let (patches, gw, gh) = gemma_prep_image(&bytes).map_err(|e| e.to_string())?;
195    Ok(GemmaVisionUnit { patches, gw, gh })
196}
197
198/// Decode + resize + patchify one image: bytes -> (patch rows [n, 768] in the conv's
199/// (c, ky, kx) flat order with the graph's 2x-1 scaling baked in, grid_w, grid_h).
200pub fn gemma_prep_image(
201    bytes: &[u8],
202) -> Result<(Vec<f32>, usize, usize), Box<dyn std::error::Error>> {
203    let img = image::load_from_memory(bytes)?.to_rgb8();
204    let (w0, h0) = img.dimensions();
205    let (tw, th) = gemma_target_size(w0, h0);
206    // Bilinear per the reference (RESIZE_ALGO_BILINEAR); image's Triangle filter is the
207    // bilinear kernel. Resize kernels are allowed to differ by a hair from llama.cpp's
208    // own bilinear — the parity oracle feeds FIXED pixels so the tower is gated
209    // independently of resampling.
210    let resized = image::imageops::resize(&img, tw, th, image::imageops::FilterType::Triangle);
211    let (gw, gh) = ((tw as usize) / GV_PATCH, (th as usize) / GV_PATCH);
212    let mut patches = vec![0f32; gw * gh * GV_PATCH_IN];
213    for py in 0..gh {
214        for px in 0..gw {
215            let dst = &mut patches[(py * gw + px) * GV_PATCH_IN..(py * gw + px + 1) * GV_PATCH_IN];
216            for c in 0..3 {
217                for ky in 0..GV_PATCH {
218                    for kx in 0..GV_PATCH {
219                        let p = resized
220                            .get_pixel((px * GV_PATCH + kx) as u32, (py * GV_PATCH + ky) as u32);
221                        // [0,1] then the graph's 2x-1
222                        dst[(c * GV_PATCH + ky) * GV_PATCH + kx] =
223                            (p[c] as f32) / 255.0 * 2.0 - 1.0;
224                    }
225                }
226            }
227        }
228    }
229    Ok((patches, gw, gh))
230}
231
232impl GemmaVisionTower {
233    /// Load the tower from a gemma-4 mmproj GGUF (`general.type = mmproj`,
234    /// `clip.vision.projector_type = gemma4v`).
235    pub fn load(e: &Engine, path: &Path) -> Result<Self, Box<dyn std::error::Error>> {
236        let g = GgufFile::open(path)?;
237        let proj_type = g
238            .metadata
239            .get("clip.vision.projector_type")
240            .and_then(|v| v.as_str())
241            .unwrap_or_default();
242        if proj_type != "gemma4v" {
243            return Err(format!(
244                "mmproj {path:?} projector_type {proj_type:?} is not gemma4v — this loader \
245                 refuses other families by design (no generic support claims)",
246                path = path
247            )
248            .into());
249        }
250        let patch_w = {
251            // conv weight logical [1152, 3, 16, 16] row-major == Linear rows over the
252            // (c, ky, kx) patch order gemma_prep_image emits.
253            let w = read_f32(&g, "v.patch_embd.weight")?;
254            assert_eq!(
255                w.len(),
256                GV_HIDDEN * GV_PATCH_IN,
257                "v.patch_embd.weight shape"
258            );
259            GLin {
260                w: e.htod(&w)?,
261                in_f: GV_PATCH_IN,
262                out_f: GV_HIDDEN,
263            }
264        };
265        let pos = read_f32(&g, "v.position_embd.weight")?;
266        assert_eq!(
267            pos.len(),
268            2 * GV_POS_ROWS * GV_HIDDEN,
269            "position table shape"
270        );
271        let (pos_x, pos_y) = {
272            let half = GV_POS_ROWS * GV_HIDDEN;
273            (pos[..half].to_vec(), pos[half..].to_vec())
274        };
275        let mut blocks = Vec::with_capacity(GV_DEPTH);
276        for il in 0..GV_DEPTH {
277            let bp = format!("v.blk.{il}");
278            blocks.push(GBlock {
279                ln1: e.htod(&read_f32(&g, &format!("{bp}.ln1.weight"))?)?,
280                ln2: e.htod(&read_f32(&g, &format!("{bp}.ln2.weight"))?)?,
281                attn_post: e.htod(&read_f32(&g, &format!("{bp}.attn_post_norm.weight"))?)?,
282                ffn_post: e.htod(&read_f32(&g, &format!("{bp}.ffn_post_norm.weight"))?)?,
283                q_norm: read_f32(&g, &format!("{bp}.attn_q_norm.weight"))?,
284                k_norm: read_f32(&g, &format!("{bp}.attn_k_norm.weight"))?,
285                wq: load_lin(e, &g, &format!("{bp}.attn_q.weight"), GV_HIDDEN, GV_HIDDEN)?,
286                wk: load_lin(e, &g, &format!("{bp}.attn_k.weight"), GV_HIDDEN, GV_HIDDEN)?,
287                wv: load_lin(e, &g, &format!("{bp}.attn_v.weight"), GV_HIDDEN, GV_HIDDEN)?,
288                wo: load_lin(
289                    e,
290                    &g,
291                    &format!("{bp}.attn_out.weight"),
292                    GV_HIDDEN,
293                    GV_HIDDEN,
294                )?,
295                gate: load_lin(e, &g, &format!("{bp}.ffn_gate.weight"), GV_HIDDEN, GV_INTER)?,
296                up: load_lin(e, &g, &format!("{bp}.ffn_up.weight"), GV_HIDDEN, GV_INTER)?,
297                down: load_lin(e, &g, &format!("{bp}.ffn_down.weight"), GV_INTER, GV_HIDDEN)?,
298            });
299        }
300        let std_bias = read_f32(&g, "v.std_bias")?;
301        let std_scale = read_f32(&g, "v.std_scale")?;
302        assert_eq!(std_bias.len(), GV_HIDDEN);
303        assert_eq!(std_scale.len(), GV_HIDDEN);
304        let proj = load_lin(e, &g, "mm.input_projection.weight", GV_HIDDEN, GV_OUT)?;
305        eprintln!(
306            "[gemma-vision] tower loaded from {} ({GV_DEPTH} blocks, f32-resident)",
307            path.display()
308        );
309        Ok(Self {
310            patch_w,
311            pos_x,
312            pos_y,
313            blocks,
314            std_bias,
315            std_scale,
316            proj,
317        })
318    }
319
320    fn linear(
321        &self,
322        e: &Engine,
323        x: &CudaSlice<f32>,
324        l: &GLin,
325        m: usize,
326    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
327        e.linear(x, &l.w, m, l.in_f, l.out_f)
328    }
329
330    /// Forward one image's patch rows -> [gh*gw/9, 5376] embeddings (device).
331    pub fn forward(
332        &self,
333        e: &Engine,
334        patches: &[f32],
335        gw: usize,
336        gh: usize,
337    ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
338        let n = gw * gh;
339        assert_eq!(patches.len(), n * GV_PATCH_IN, "patch buffer shape");
340        assert_eq!(gw % GV_MERGE, 0, "grid width must be 3-aligned");
341        assert_eq!(gh % GV_MERGE, 0, "grid height must be 3-aligned");
342        if n > 12288 {
343            return Err(format!(
344                "gemma vision segment {n} patches exceeds the sdpa shared-memory ceiling (12288)"
345            )
346            .into());
347        }
348        let dbg = std::env::var("MEMRA_VISION_DEBUG").ok();
349        let dump = |tag: &str, buf: &[f32]| {
350            if let Some(dir) = dbg.as_deref() {
351                let raw: Vec<u8> = buf.iter().flat_map(|v| v.to_le_bytes()).collect();
352                let _ = std::fs::write(format!("{dir}/rust_{tag}.bin"), raw);
353            }
354        };
355
356        // patch embed + factored additive position tables (row-major grid: x = col, y = row)
357        let xd = e.htod(patches)?;
358        let embedded = self.linear(e, &xd, &self.patch_w, n)?;
359        let mut pos = vec![0f32; n * GV_HIDDEN];
360        for t in 0..n {
361            let (py, px) = (t / gw, t % gw);
362            let dst = &mut pos[t * GV_HIDDEN..(t + 1) * GV_HIDDEN];
363            let tx = &self.pos_x[px * GV_HIDDEN..(px + 1) * GV_HIDDEN];
364            let ty = &self.pos_y[py * GV_HIDDEN..(py + 1) * GV_HIDDEN];
365            for c in 0..GV_HIDDEN {
366                dst[c] = tx[c] + ty[c];
367            }
368        }
369        let pos_d = e.htod(&pos)?;
370        let mut x = e.zeros(n * GV_HIDDEN)?;
371        e.add(&embedded, &pos_d, &mut x, n * GV_HIDDEN)?;
372        if dbg.is_some() {
373            dump("pre_blocks", &e.dtoh(&x)?);
374        }
375
376        // 2D rope tables: FIRST 36 dims rotate by pos_x, LAST 36 by pos_y (the reference
377        // order — opposite of qwen3_5's y-first); neox pairing (d, d+18) inside each
378        // half; inv_freq[i] = theta^(-2i/36), theta 100.
379        let half = GV_HEAD_DIM / 2; // 36
380        let quarter = half / 2; // 18
381        let inv_freq: Vec<f32> = (0..quarter)
382            .map(|i| ROPE_THETA.powf(-2.0 * (i as f32) / half as f32))
383            .collect();
384        let mut cos_x = vec![0f32; n * quarter];
385        let mut sin_x = vec![0f32; n * quarter];
386        let mut cos_y = vec![0f32; n * quarter];
387        let mut sin_y = vec![0f32; n * quarter];
388        for t in 0..n {
389            let (py, px) = (t / gw, t % gw);
390            for i in 0..quarter {
391                let ax = px as f32 * inv_freq[i];
392                let ay = py as f32 * inv_freq[i];
393                cos_x[t * quarter + i] = ax.cos();
394                sin_x[t * quarter + i] = ax.sin();
395                cos_y[t * quarter + i] = ay.cos();
396                sin_y[t * quarter + i] = ay.sin();
397            }
398        }
399        // per-head RMS over head_dim with weight (q/k) or weightless (v)
400        let head_rms = |row: &mut [f32], w: Option<&[f32]>| {
401            let mut ss = 0f32;
402            for v in row.iter() {
403                ss += v * v;
404            }
405            let inv = 1.0 / (ss / GV_HEAD_DIM as f32 + RMS_EPS).sqrt();
406            for (d, v) in row.iter_mut().enumerate() {
407                *v *= inv * w.map_or(1.0, |w| w[d]);
408            }
409        };
410
411        for (ib, blk) in self.blocks.iter().enumerate() {
412            // attn: rms(ln1) -> q/k/v -> per-head norms -> 2D rope -> sdpa(scale=1) ->
413            //       o_proj -> rms(attn_post) -> +residual
414            let mut h = e.zeros(n * GV_HIDDEN)?;
415            e.rms_norm(&x, &blk.ln1, &mut h, GV_HIDDEN, n, RMS_EPS)?;
416            let q = self.linear(e, &h, &blk.wq, n)?;
417            let k = self.linear(e, &h, &blk.wk, n)?;
418            let v = self.linear(e, &h, &blk.wv, n)?;
419            let (mut qh, mut kh, mut vh) = (e.dtoh(&q)?, e.dtoh(&k)?, e.dtoh(&v)?);
420            for t in 0..n {
421                for hd in 0..GV_HEADS {
422                    let o = t * GV_HIDDEN + hd * GV_HEAD_DIM;
423                    head_rms(&mut qh[o..o + GV_HEAD_DIM], Some(&blk.q_norm));
424                    head_rms(&mut kh[o..o + GV_HEAD_DIM], Some(&blk.k_norm));
425                    head_rms(&mut vh[o..o + GV_HEAD_DIM], None);
426                    // rope: first half by x, second half by y, pairs (d, d+18) per half
427                    for (base, cos, sin) in [(0, &cos_x, &sin_x), (half, &cos_y, &sin_y)] {
428                        for i in 0..quarter {
429                            let (c, s) = (cos[t * quarter + i], sin[t * quarter + i]);
430                            for buf in [&mut qh, &mut kh] {
431                                let a = buf[o + base + i];
432                                let b = buf[o + base + i + quarter];
433                                buf[o + base + i] = a * c - b * s;
434                                buf[o + base + i + quarter] = b * c + a * s;
435                            }
436                        }
437                    }
438                }
439            }
440            let (qd, kd, vd) = (e.htod(&qh)?, e.htod(&kh)?, e.htod(&vh)?);
441            let mut od = e.zeros(n * GV_HIDDEN)?;
442            // UNSCALED attention (kq_scale = 1.0 in the reference graph), full/non-causal.
443            e.sdpa_naive(
444                &qd,
445                &kd,
446                &vd,
447                &mut od,
448                GV_HEAD_DIM,
449                GV_HEADS,
450                GV_HEADS,
451                n,
452                n,
453                1.0,
454                false,
455            )?;
456            let attn = self.linear(e, &od, &blk.wo, n)?;
457            let mut post = e.zeros(n * GV_HIDDEN)?;
458            e.rms_norm(&attn, &blk.attn_post, &mut post, GV_HIDDEN, n, RMS_EPS)?;
459            let mut xr = e.zeros(n * GV_HIDDEN)?;
460            e.add(&x, &post, &mut xr, n * GV_HIDDEN)?;
461
462            // ffn: rms(ln2) -> gelu_quick(gate) * up -> down -> rms(ffn_post) -> +residual
463            let mut h2 = e.zeros(n * GV_HIDDEN)?;
464            e.rms_norm(&xr, &blk.ln2, &mut h2, GV_HIDDEN, n, RMS_EPS)?;
465            let gate = self.linear(e, &h2, &blk.gate, n)?;
466            let up = self.linear(e, &h2, &blk.up, n)?;
467            let (gh_, uh) = (e.dtoh(&gate)?, e.dtoh(&up)?);
468            let mut act = vec![0f32; n * GV_INTER];
469            for i in 0..n * GV_INTER {
470                let g = gh_[i];
471                // gelu_quick(x) = x * sigmoid(1.702 x) — NOT the tanh approximation.
472                act[i] = g / (1.0 + (-1.702 * g).exp()) * uh[i];
473            }
474            let ad = e.htod(&act)?;
475            let down = self.linear(e, &ad, &blk.down, n)?;
476            let mut fpost = e.zeros(n * GV_HIDDEN)?;
477            e.rms_norm(&down, &blk.ffn_post, &mut fpost, GV_HIDDEN, n, RMS_EPS)?;
478            let mut xn = e.zeros(n * GV_HIDDEN)?;
479            e.add(&xr, &fpost, &mut xn, n * GV_HIDDEN)?;
480            x = xn;
481            if dbg.is_some() && ib == 0 {
482                dump("blk0", &e.dtoh(&x)?);
483            }
484        }
485        if dbg.is_some() {
486            dump("post_blocks", &e.dtoh(&x)?);
487        }
488
489        // head: 3x3 avg-pool over the grid -> *sqrt(1152) -> (x - std_bias)*std_scale
490        //       -> weightless RMS -> project 1152 -> 5376
491        let xh = e.dtoh(&x)?;
492        let (mw, mh) = (gw / GV_MERGE, gh / GV_MERGE);
493        let nm = mw * mh;
494        let scale = (GV_HIDDEN as f32).sqrt();
495        let mut pooled = vec![0f32; nm * GV_HIDDEN];
496        for my in 0..mh {
497            for mx in 0..mw {
498                let dst = &mut pooled[(my * mw + mx) * GV_HIDDEN..(my * mw + mx + 1) * GV_HIDDEN];
499                for sy in 0..GV_MERGE {
500                    for sx in 0..GV_MERGE {
501                        let t = (my * GV_MERGE + sy) * gw + (mx * GV_MERGE + sx);
502                        for c in 0..GV_HIDDEN {
503                            dst[c] += xh[t * GV_HIDDEN + c];
504                        }
505                    }
506                }
507                for (c, d) in dst.iter_mut().enumerate() {
508                    *d = (*d / (GV_MERGE * GV_MERGE) as f32 * scale - self.std_bias[c])
509                        * self.std_scale[c];
510                }
511            }
512        }
513        // weightless RMS then projection
514        for row in pooled.chunks_exact_mut(GV_HIDDEN) {
515            let mut ss = 0f32;
516            for v in row.iter() {
517                ss += v * v;
518            }
519            let inv = 1.0 / (ss / GV_HIDDEN as f32 + RMS_EPS).sqrt();
520            for v in row.iter_mut() {
521                *v *= inv;
522            }
523        }
524        if dbg.is_some() {
525            dump("pre_proj", &pooled);
526        }
527        let pd = e.htod(&pooled)?;
528        let out = self.linear(e, &pd, &self.proj, nm)?;
529        if dbg.is_some() {
530            dump("projected", &e.dtoh(&out)?);
531        }
532        Ok(out)
533    }
534}