1use 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; pub const GV_INTER: usize = 4304;
47pub const GV_DEPTH: usize = 27;
48pub const GV_PATCH: usize = 16;
49pub const GV_MERGE: usize = 3; pub const GV_POS_ROWS: usize = 10240; pub const GV_OUT: usize = 5376; pub const GV_PATCH_IN: usize = 3 * GV_PATCH * GV_PATCH; pub const GV_ALIGN: usize = GV_PATCH * GV_MERGE; pub 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
61pub const GV_TOK_BEGIN: u32 = 255999; pub const GV_TOK_SOFT: u32 = 258880; pub const GV_TOK_END: u32 = 258882; struct 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, 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, }
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
134pub 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
160pub 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
176pub fn n_soft_for_grid(gw: usize, gh: usize) -> usize {
179 (gw / GV_MERGE) * (gh / GV_MERGE)
180}
181
182pub 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
197pub 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
204pub 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
220pub 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 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 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 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 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 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 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 let half = GV_HEAD_DIM / 2; let quarter = half / 2; 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 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 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 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 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 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 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 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 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}