Skip to main content

memra_engine/
vision_pre.rs

1//! Host preprocessor for vision input (lane/vision): bytes -> ViT patch rows.
2//!
3//! Qwen2VLImageProcessorFast semantics: smart_resize to multiples of
4//! factor = patch(16) * merge(2) = 32 with the pixel-area budget, rescale 1/255,
5//! normalize mean/std 0.5 -> [-1, 1], patchify to [gh*gw, 3*2*16*16 = 1536] rows in
6//! row-major grid order with (c, t, ph, pw) inner order — the flatten of the conv
7//! weight [1152, 3, 2, 16, 16], so `VisionTower::forward` consumes rows directly.
8//! Images duplicate their frame across temporal_patch 2; videos fill the pair with
9//! consecutive sampled frames.
10//!
11//! Resize filter: CatmullRom (Keys bicubic a=-0.5, PIL-BICUBIC family). The HF fast
12//! processor runs torch bicubic (a=-0.75) antialias — close but not bit-equal; the
13//! merger-cosine parity gate arbitrates whether the difference matters.
14
15use crate::vision::{V_MERGE, V_PATCH, V_PATCH_IN, V_TEMPORAL};
16use base64::Engine as _;
17use image::RgbImage;
18use image::imageops::FilterType;
19
20/// Area budget (pixels) from preprocessor_config: shortest_edge / longest_edge.
21pub const MIN_PIXELS: usize = 65536;
22pub const MAX_PIXELS: usize = 16_777_216;
23const FACTOR: usize = V_PATCH * V_MERGE; // 32
24
25pub struct PreppedImage {
26    /// [gh*gw, 1536] row-major grid order.
27    pub patches: Vec<f32>,
28    pub gh: usize,
29    pub gw: usize,
30}
31
32impl PreppedImage {
33    /// Trunk tokens this image occupies (after 2x2 merge).
34    pub fn n_tokens(&self) -> usize {
35        self.gh * self.gw / (V_MERGE * V_MERGE)
36    }
37}
38
39/// smart_resize (HF): round each side to a multiple of 32 preserving aspect ratio,
40/// then scale into the [MIN_PIXELS, MAX_PIXELS] area budget.
41pub fn smart_resize(h: usize, w: usize) -> Result<(usize, usize), String> {
42    if h < 2 || w < 2 {
43        return Err(format!("image too small: {w}x{h}"));
44    }
45    let ar = h.max(w) as f64 / h.min(w) as f64;
46    if ar > 200.0 {
47        return Err(format!("aspect ratio {ar:.0} exceeds 200"));
48    }
49    let f = FACTOR as f64;
50    let (hf, wf) = (h as f64, w as f64);
51    let mut h_bar = ((hf / f).round() * f).max(f);
52    let mut w_bar = ((wf / f).round() * f).max(f);
53    if h_bar * w_bar > MAX_PIXELS as f64 {
54        let beta = (hf * wf / MAX_PIXELS as f64).sqrt();
55        h_bar = ((hf / beta / f).floor() * f).max(f);
56        w_bar = ((wf / beta / f).floor() * f).max(f);
57    } else if h_bar * w_bar < MIN_PIXELS as f64 {
58        let beta = (MIN_PIXELS as f64 / (hf * wf)).sqrt();
59        h_bar = (hf * beta / f).ceil() * f;
60        w_bar = (wf * beta / f).ceil() * f;
61    }
62    Ok((h_bar as usize, w_bar as usize))
63}
64
65/// Decode + resize one image to its target grid. Returns the resized RGB frame and
66/// the patch grid (gh, gw) in 16px patches (both even — factor 32 guarantees it).
67fn decode_frame(bytes: &[u8]) -> Result<(RgbImage, usize, usize), String> {
68    let img = image::load_from_memory(bytes).map_err(|e| format!("image decode: {e}"))?;
69    let rgb = img.to_rgb8();
70    let (w, h) = (rgb.width() as usize, rgb.height() as usize);
71    let (rh, rw) = smart_resize(h, w)?;
72    let resized = image::imageops::resize(&rgb, rw as u32, rh as u32, FilterType::CatmullRom);
73    Ok((resized, rh / V_PATCH, rw / V_PATCH))
74}
75
76/// Fill patch rows for one temporal slot `t` from a frame. Rows are row-major over
77/// the (gh, gw) grid; inner order (c, t, ph, pw).
78fn fill_slot(rows: &mut [f32], frame: &RgbImage, gh: usize, gw: usize, t: usize) {
79    let inv = 1.0f32 / 127.5;
80    for py in 0..gh {
81        for px in 0..gw {
82            let row = &mut rows[(py * gw + px) * V_PATCH_IN..(py * gw + px + 1) * V_PATCH_IN];
83            for c in 0..3 {
84                let base = c * V_TEMPORAL * V_PATCH * V_PATCH + t * V_PATCH * V_PATCH;
85                for ph in 0..V_PATCH {
86                    for pw in 0..V_PATCH {
87                        let p =
88                            frame.get_pixel((px * V_PATCH + pw) as u32, (py * V_PATCH + ph) as u32);
89                        row[base + ph * V_PATCH + pw] = p.0[c] as f32 * inv - 1.0;
90                    }
91                }
92            }
93        }
94    }
95}
96
97/// Image bytes (png/jpeg/webp/gif/bmp) -> patch rows. The single frame fills both
98/// temporal slots (HF: images are tiled to temporal_patch_size).
99pub fn prep_image_bytes(bytes: &[u8]) -> Result<PreppedImage, String> {
100    let (frame, gh, gw) = decode_frame(bytes)?;
101    let mut patches = vec![0f32; gh * gw * V_PATCH_IN];
102    for t in 0..V_TEMPORAL {
103        fill_slot(&mut patches, &frame, gh, gw, t);
104    }
105    Ok(PreppedImage { patches, gh, gw })
106}
107
108/// `data:image/...;base64,<payload>` -> patch rows.
109pub fn prep_data_uri(uri: &str) -> Result<PreppedImage, String> {
110    let bytes = decode_data_uri(uri)?;
111    prep_image_bytes(&bytes)
112}
113
114/// One pad-run unit crossing the API boundary: a standalone image, or one temporal
115/// group of a video. Units with the same `video` index are consecutive and forward
116/// TOGETHER through `forward_seq` (one attention span per video).
117pub struct VisionUnit {
118    pub prep: PreppedImage,
119    /// Some(video_idx) for video groups; None for standalone images.
120    pub video: Option<usize>,
121}
122
123/// One prepared VIDEO: temporal groups as PreppedImage units (each = one pad run of
124/// `gh*gw/4` tokens) + per-group timestamps for the HF placeholder format
125/// (`<t.t seconds>` before each group's pad run). Groups forward TOGETHER through
126/// `VisionTower::forward_seq` — one attention span per video, the HF cu_seqlens law.
127pub struct PreppedVideo {
128    pub groups: Vec<PreppedImage>,
129    pub timestamps: Vec<f32>,
130}
131
132/// Serving cap on total video patches (groups*gh*gw): sdpa_naive keys the whole span in
133/// shared memory, so the pixel budget stays well under the HF default. Env-tunable.
134pub fn video_max_pixels() -> usize {
135    std::env::var("MEMRA_VIDEO_MAX_PIXELS")
136        .ok()
137        .and_then(|v| v.parse().ok())
138        .unwrap_or(2_097_152)
139}
140pub const VID_MIN_PIXELS: usize = 4096;
141/// Sampled frame cap (2 frames per temporal group).
142pub const VID_MAX_FRAMES: usize = 32;
143
144/// HF Qwen3VL video smart_resize: the pixel budget covers t_bar*h*w — ALL frames.
145fn smart_resize_video(frames: usize, h: usize, w: usize) -> Result<(usize, usize), String> {
146    if h < 2 || w < 2 {
147        return Err(format!("frame too small: {w}x{h}"));
148    }
149    let ar = h.max(w) as f64 / h.min(w) as f64;
150    if ar > 200.0 {
151        return Err(format!("aspect ratio {ar:.0} exceeds 200"));
152    }
153    let f = FACTOR as f64;
154    let (hf, wf) = (h as f64, w as f64);
155    let t_bar = ((frames as f64 / V_TEMPORAL as f64).round() * V_TEMPORAL as f64).max(2.0);
156    let mut h_bar = ((hf / f).round() * f).max(f);
157    let mut w_bar = ((wf / f).round() * f).max(f);
158    let (min_px, max_px) = (VID_MIN_PIXELS as f64, video_max_pixels() as f64);
159    if t_bar * h_bar * w_bar > max_px {
160        let beta = (frames as f64 * hf * wf / max_px).sqrt();
161        h_bar = ((hf / beta / f).floor() * f).max(f);
162        w_bar = ((wf / beta / f).floor() * f).max(f);
163    } else if t_bar * h_bar * w_bar < min_px {
164        let beta = (min_px / (frames as f64 * hf * wf)).sqrt();
165        h_bar = (hf * beta / f).ceil() * f;
166        w_bar = (wf * beta / f).ceil() * f;
167    }
168    Ok((h_bar as usize, w_bar as usize))
169}
170
171/// Animated GIF -> prepared video: decode frames + delays, uniform-sample to an even
172/// count <= VID_MAX_FRAMES, resize on the total-pixel budget, patchify CONSECUTIVE
173/// frame pairs into temporal groups (frame 2g fills t=0, 2g+1 fills t=1). Timestamps
174/// come from the GIF's own delays at the sampled indices (HF `_calculate_timestamps`).
175pub fn prep_video_gif(bytes: &[u8]) -> Result<PreppedVideo, String> {
176    use image::AnimationDecoder;
177    let dec = image::codecs::gif::GifDecoder::new(std::io::Cursor::new(bytes))
178        .map_err(|e| format!("gif decode: {e}"))?;
179    let mut frames: Vec<(RgbImage, f32)> = Vec::new(); // (frame, start_seconds)
180    let mut t = 0f32;
181    for fr in dec.into_frames() {
182        let fr = fr.map_err(|e| format!("gif frame: {e}"))?;
183        let (num, den) = fr.delay().numer_denom_ms();
184        let dt = if den == 0 {
185            100.0
186        } else {
187            num as f32 / den as f32
188        } / 1000.0;
189        frames.push((
190            image::DynamicImage::ImageRgba8(fr.into_buffer()).to_rgb8(),
191            t,
192        ));
193        t += dt.max(0.01);
194    }
195    if frames.is_empty() {
196        return Err("gif has no frames".into());
197    }
198    // still gif: duplicate the frame so one temporal group forms
199    if frames.len() == 1 {
200        let f0 = frames[0].clone();
201        frames.push((f0.0, f0.1));
202    }
203    // uniform sample to an even count <= VID_MAX_FRAMES
204    let total = frames.len();
205    let take = total.min(VID_MAX_FRAMES) & !1;
206    let picked: Vec<usize> = (0..take)
207        .map(|i| i * total / take) // floor spacing, strictly increasing for take <= total
208        .collect();
209    let (h, w) = (frames[0].0.height() as usize, frames[0].0.width() as usize);
210    let (rh, rw) = smart_resize_video(take, h, w)?;
211    let (gh, gw) = (rh / V_PATCH, rw / V_PATCH);
212    let mut groups = Vec::with_capacity(take / 2);
213    let mut timestamps = Vec::with_capacity(take / 2);
214    for g in 0..take / 2 {
215        let (a, b) = (picked[2 * g], picked[2 * g + 1]);
216        let mut patches = vec![0f32; gh * gw * V_PATCH_IN];
217        for (slot, idx) in [(0usize, a), (1usize, b)] {
218            let resized = image::imageops::resize(
219                &frames[idx].0,
220                rw as u32,
221                rh as u32,
222                FilterType::CatmullRom,
223            );
224            fill_slot(&mut patches, &resized, gh, gw, slot);
225        }
226        groups.push(PreppedImage { patches, gh, gw });
227        timestamps.push(frames[a].1);
228    }
229    Ok(PreppedVideo { groups, timestamps })
230}
231
232/// Parse a base64 data URI into raw bytes (any `data:*;base64,` media type).
233pub fn decode_data_uri(uri: &str) -> Result<Vec<u8>, String> {
234    let rest = uri
235        .strip_prefix("data:")
236        .ok_or_else(|| "expected data: URI (http fetch requires MEMRA_FETCH_URLS=1)".to_string())?;
237    let (meta, payload) = rest
238        .split_once(',')
239        .ok_or_else(|| "malformed data URI: no comma".to_string())?;
240    if !meta.ends_with(";base64") {
241        return Err("data URI must be base64-encoded".into());
242    }
243    base64::engine::general_purpose::STANDARD
244        .decode(payload.trim())
245        .map_err(|e| format!("base64 decode: {e}"))
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    #[test]
253    fn smart_resize_multiples_and_budget() {
254        // typical photo
255        let (h, w) = smart_resize(1080, 1920).unwrap();
256        assert_eq!(h % 32, 0);
257        assert_eq!(w % 32, 0);
258        assert!(h * w >= MIN_PIXELS && h * w <= MAX_PIXELS);
259        // tiny icon scales UP to the floor
260        let (h, w) = smart_resize(64, 64).unwrap();
261        assert!(h * w >= MIN_PIXELS);
262        // huge pano scales DOWN under the cap
263        let (h, w) = smart_resize(8000, 12000).unwrap();
264        assert!(h * w <= MAX_PIXELS);
265        assert!(smart_resize(10, 4000).is_err()); // ar > 200
266    }
267
268    #[test]
269    fn patchify_shape_and_order() {
270        // 2x2-patch (32x32 px) synthetic image, distinct channel values
271        let mut img = RgbImage::new(64, 64);
272        for (x, y, p) in img.enumerate_pixels_mut() {
273            *p = image::Rgb([x as u8, y as u8, 200]);
274        }
275        let mut buf = std::io::Cursor::new(Vec::new());
276        img.write_to(&mut buf, image::ImageFormat::Png).unwrap();
277        let prep = prep_image_bytes(buf.get_ref()).unwrap();
278        assert_eq!(prep.patches.len(), prep.gh * prep.gw * V_PATCH_IN);
279        assert_eq!(prep.gh % V_MERGE, 0);
280        assert_eq!(prep.gw % V_MERGE, 0);
281        // temporal slots identical for still images
282        let row = &prep.patches[0..V_PATCH_IN];
283        let slot = V_PATCH * V_PATCH;
284        for c in 0..3 {
285            let b = c * V_TEMPORAL * slot;
286            assert_eq!(row[b..b + slot], row[b + slot..b + 2 * slot]);
287        }
288        // values in [-1, 1]
289        assert!(prep.patches.iter().all(|v| (-1.0..=1.0).contains(v)));
290    }
291
292    #[test]
293    fn data_uri_roundtrip() {
294        let png = {
295            let img = RgbImage::new(32, 32);
296            let mut buf = std::io::Cursor::new(Vec::new());
297            img.write_to(&mut buf, image::ImageFormat::Png).unwrap();
298            buf.into_inner()
299        };
300        let uri = format!(
301            "data:image/png;base64,{}",
302            base64::engine::general_purpose::STANDARD.encode(&png)
303        );
304        let prep = prep_data_uri(&uri).unwrap();
305        assert_eq!(prep.n_tokens(), prep.gh * prep.gw / 4);
306        assert!(decode_data_uri("http://x/y.png").is_err());
307    }
308}