Skip to content

feat: DiffusionGemma image input (phase 2 of #217) - #219

Merged
inureyes merged 4 commits into
mainfrom
feat/issue-217-diffusion-gemma-image
Jun 11, 2026
Merged

inureyes merged 4 commits into
mainfrom
feat/issue-217-diffusion-gemma-image

Conversation

@inureyes

@inureyes inureyes commented Jun 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 2 of #217: single and multi image input for DiffusionGemma via mlxcel generate -m <diffusion-model> --image <path> -p "...". Composes the existing Gemma 4 vision tower, multimodal embedder, and bidirectional vision-block overlay rather than forking them. The text-only phase-1 path stays byte-identical.

What changed

  • src/models/sanitize.rs: keep_diffusion_gemma_weight now retains model.encoder.vision_tower.* and model.encoder.embed_vision.*, dropping the clipped-linear calibration tensors (*.input_max / *.input_min / *.output_max / *.output_min) when vision_config.use_clipped_linears is false. New load_diffusion_gemma_weights_with_backing(model_dir, use_clipped_linears) replaces the text-only loader.
  • src/models/diffusion_gemma/mod.rs: ModelArgs parses boi_token_id, eoi_token_id, image_token_id, video_token_id, vision_soft_tokens_per_image, vision_config. New optional DiffusionVision (vision tower at prefix model.encoder.vision_tower + Gemma4MultimodalEmbedder at model.encoder.embed_vision), built only when the tower weights and a parsed vision_config are present (text-only checkpoints load with vision = None). prepare_vision_prefill mirrors EncoderModel._embed_inputs (pad image positions for the lookup, scale text embeddings, masked-scatter the RAW unscaled projected features). forward_encoder now delegates to forward_encoder_embeds, which OR-es overlay_block_bidirectional onto the causal and dense sliding-window masks for every layer at prefill offset 0.
  • src/models/diffusion_gemma/generate.rs: generate_diffusion_streaming gains an optional DiffusionVisionPrefill; with an image present the prompt prefill is one embeddings pass with chunking disabled.
  • src/commands/generate_diffusion.rs: real image path (preprocess, expand prompt placeholders into boi + image_token*N + eoi, build prefill, pass to the engine). --video and audio still reject with clear messages.
  • src/models/gemma4.rs: overlay_block_bidirectional made pub(crate) (additive).

How text-only behavior is preserved

forward_encoder embeds + scales then calls forward_encoder_embeds(.., None) (no overlay), running the same op sequence as phase 1. The engine only diverges when a DiffusionVisionPrefill is supplied; with no image it takes the exact phase-1 token prefill path. supports_batching() stays false.

Test plan

  • cargo test --lib models::diffusion_gemma (32 pass, 2 #[ignore] real-model)
  • cargo check --lib --tests
  • cargo clippy --lib --tests -- -D warnings and cargo clippy --bin mlxcel -- -D warnings
  • cargo fmt
  • Real-model image-description run on models/diffusiongemma-26B-A4B-it-4bit (orchestrator)

Real-model verification (phase 2)

Verified on models/diffusiongemma-26B-A4B-it-4bit (M1 Ultra):

  • Solid-color image (plain blue JPEG): model correctly identified the color with no hallucinated content.
  • Structured image (red square overlaid on blue circle): mlxcel and the mlx-vlm Python reference both described both shapes and their colors correctly with matching outputs.
  • Multi-image prompt (two distinct images, one per --image flag): each image attributed to the correct position in the response; no cross-image confusion.
  • Token expansion: 256 soft tokens per image inserted between boi/eoi sentinels, 283-token total prompt, matches Python reference exactly.
  • Text-only deterministic run (same prompt, --seed 42, temperature 0): output byte-identical to the phase-1 build with no image flags.
  • Cold clippy (both metal,accelerate feature set and default): zero warnings.
  • Full serial lib suite (cargo test --lib models::diffusion_gemma): 32 pass, 0 fail.

Part of #217

Add single and multi image input to the DiffusionGemma block-diffusion CLI generate path, composing the existing Gemma 4 vision tower, multimodal embedder, and bidirectional vision-block overlay machinery. The text-only phase-1 path stays byte-identical: forward_encoder now delegates to a new forward_encoder_embeds with no overlay, so an all-text prompt runs the same ops.

Loading: keep_diffusion_gemma_weight now retains model.encoder.vision_tower.* and model.encoder.embed_vision.* (dropping the unused clipped-linear calibration tensors when vision_config.use_clipped_linears is false), and load_diffusion_gemma_weights_with_backing takes that flag. DiffusionGemmaModel builds an optional DiffusionVision (Gemma4VisionModel at prefix model.encoder.vision_tower + Gemma4MultimodalEmbedder at model.encoder.embed_vision) only when the tower weights and a parsed vision_config are present; text-only checkpoints load with vision = None.

Config: ModelArgs parses boi_token_id, eoi_token_id, image_token_id, video_token_id, vision_soft_tokens_per_image, and vision_config (into Gemma4VisionConfig).

Forward: prepare_vision_prefill mirrors EncoderModel._embed_inputs (pad image positions for the embedding lookup, scale text embeddings by embed_scale, masked-scatter the RAW unscaled projected image features into the image positions) and derives the per-position vision block ids via compute_vision_block_ids. forward_encoder_embeds OR-es overlay_block_bidirectional onto both the causal and the dense sliding-window masks for every layer at prefill offset 0, matching _vision_block_overlay / _make_encoder_masks. The overlay applies only to the prompt prefill; committed-block appends stay token-based and overlay-free.

Engine: generate_diffusion_streaming gains an optional DiffusionVisionPrefill. With an image present the prompt prefill runs as one embeddings pass (chunked prefill disabled, mirroring _diffusion_should_chunk_prefill); stats and the canvas loop are unchanged.

CLI: generate_diffusion replaces the image rejection with the real path (preprocess via the Gemma 4 image processor, expand the templated prompt's image placeholders into boi + image_token*N + eoi, build the prefill, pass to the engine); --video and audio still reject with clear messages.

Tests: vision config parsing, single and two image prompt expansion, mm_token_type_ids derivation, contiguous vision block ids, overlay mask correctness (image block bidirectional, text causal, sliding window preserved), sanitize keep/skip rules, and an #[ignore] real-model vision-load smoke test. All 32 unit tests pass; the phase-1 real_model_forward_determinism and 23 prior unit tests are unchanged.

Part of #217
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:models Model architectures, weights, loading, metadata area:inference Generation, sampling, decoding (incl. speculative, DRY) area:cli Command-line interface / CLI flags status:review Under review labels Jun 11, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Phase 2 of #217: single and multi image input for DiffusionGemma via the CLI generate path, composing the existing Gemma 4 vision tower, multimodal embedder, and bidirectional vision-block overlay, while keeping the phase-1 text-only path byte-identical.

Findings Addressed

None requiring code changes. The implementation matches the mlx-vlm reference at every point reviewed.

Verified against reference (diffusion_gemma/language.py, gemma4/gemma4.py, generate/diffusion.py)

  • prepare_vision_prefill mirrors EncoderModel._embed_inputs: image/video positions mapped to pad id for the lookup, text embeds scaled by embed_scale, RAW projected features (NOT scaled) masked-scattered into vision positions. boi/eoi stay text. Correct.
  • Vision-block overlay OR-ed onto BOTH the causal and dense sliding-window masks for every layer, and only when vision_block_ids is Some (set only on the offset-0 prompt prefill; continuation passes pass None). Matches _vision_block_overlay + _make_encoder_masks, including the key_len != N guard via the caller. Contiguous image-token runs become distinct bidirectional blocks (boi/eoi break runs), matching mm_token_type_ids == 1|2.
  • MultimodalEmbedder reuse: RMSNormNoScale then Linear, no scale on features. Correct.
  • Chunking disabled when vision present (single embeddings pass), matching _diffusion_should_chunk_prefill.
  • Sanitize: clipped-linear calibration tensors (*.input_max/min, *.output_max/min) dropped when use_clipped_linears is false; text backbone kept unconditionally; text-only checkpoints carry no vision keys and load with vision = None.
  • gemma4.rs change is additive (visibility widening of overlay_block_bidirectional to pub(crate)).
  • Text-only byte-preservation: forward_encoder embeds + scales then delegates to forward_encoder_embeds(.., None), running the identical mask build + per-layer op sequence as phase 1.
  • Engine plumbing in generate.rs: vision prefill is purely additive; the no-image branch takes the exact phase-1 token prefill path.
  • Integration complete: prepare_diffusion_vision -> prepare_vision_prefill -> generate_diffusion_streaming wired through the existing CLI driver; no orphaned code. Audio and video still rejected with clear messages.

Verification

  • All stated requirements implemented (single/multi image, overlay, sanitize, byte-preserved text path)
  • No placeholder/mock code remaining
  • Integrated into project code flow (CLI -> model -> engine)
  • Project conventions followed
  • Existing modules reused (vision tower, embedder, masked_scatter, expand_gemma4_image_tokens, overlay)
  • No unintended structural changes (gemma4 change additive)
  • Tests pass: cargo test --lib models::diffusion_gemma 32 pass / 2 ignored; models::gemma4 41 pass (no regression); cargo check --lib --tests and warm cargo clippy --lib --tests -- -D warnings clean

Non-blocking note (LOW)

prepare_vision_prefill hardcodes lookup pad id 0 where the reference uses text_config.pad_token_id. Harmless here: those rows are overwritten by the masked scatter, so the looked-up value is discarded, and Gemma's pad id is 0. No change recommended unless pad_token_id parsing is added later.

inureyes added 2 commits June 11, 2026 22:31
…emma prefill

prepare_vision_prefill scattered projected vision features into image-token positions via masked_scatter, which wraps source indices modulo the feature count. A mismatch between the number of image-token positions and the projected feature count (for example a config.json that points image_token_id at a common text token id, or a tower/processor soft-token disagreement) was silently scattering the wrong rows instead of failing. Add an explicit count check that returns a clear error before the scatter.
@inureyes

Copy link
Copy Markdown
Member Author

Security & performance review (phase 2: image input)

Reviewed the changed files with focus on untrusted image/config handling, index arithmetic, the vision filter, and hot-path performance. One MEDIUM defensive gap fixed; two pre-existing, project-wide hardening items reported for awareness (not fixed in this PR to avoid scope creep / inconsistent partial fixes).

Fixed (MEDIUM) — a056ba2fb

prepare_vision_prefill scattered projected vision features into image-token positions via masked_scatter, which wraps source indices modulo the feature count (remainder). A mismatch between image-token positions and projected feature count silently scattered the wrong rows instead of faulting. This matters because image_token_id comes from an untrusted config.json: if it points at a common text token id, many text positions get flagged as vision and the embeddings are silently corrupted (never OOB, but wrong). Added an explicit count check (vision_positions == feature_count) returning a clear error before the scatter. Matches the review goal "feature count vs position count mismatches must error, not OOB." cargo check --lib --tests, warm cargo clippy --lib --tests -- -D warnings, and cargo test --lib models::diffusion_gemma (32 pass) all green.

Reported, not fixed (pre-existing, project-wide)

  1. LOW/MEDIUM DoS — unbounded vision_soft_tokens_per_image / max_soft_tokens drives image-buffer allocation. build_image_processor resolves the soft-token budget from processor_config.json then falls back to the config's vision_soft_tokens_per_image. That value flows into Gemma4Processor::aspect_ratio_preserving_resize_dims (target_px = max_soft_tokens * pool^2 * patch^2) and then vec![0.0f32; 3*H*W], so an absurd config value can OOM. This is not specific to this PR — it lives in the shared Gemma4Processor used by the existing Gemma 4 VLM family, which has the identical unclamped behavior. The video path already has a VideoLimits pixel cap; the image path has none anywhere. Recommend a project-wide clamp (cap max_soft_tokens to a sane bound and warn, or reject absurd values) rather than a diffusion-only patch, so the VLM path is covered too.

  2. LOW DoS — bare image::open (no decode pixel limit) and no bound on --image count. generate_diffusion.rs loads each --image via image::open(path) with no decompression-bomb guard, and there is no cap on the number of --image flags. This exactly mirrors the established convention in generate_vlm.rs (all five image sites there use the same bare image::open), so it is a consistent pre-existing pattern, not a regression. Lower severity for a local CLI where the user supplies their own paths. Worth a follow-up to add ImageReader limits uniformly (the server path at model_worker.rs:827 already uses with_guessed_format but also lacks an explicit pixel cap).

Verified clean

  • Performance placement: vision tower runs once per generate (prepare_diffusion_vision -> prepare_vision_prefill), not per denoise step; inputs_embeds is built once and reused. Overlay masks (overlay_block_bidirectional) are built once at prefill offset 0.
  • Text-only hot path unchanged: forward_encoder delegates to forward_encoder_embeds(.., None) with vision_block_ids = None, so no overlay allocation and the same op sequence as phase 1. No extra copy on the text path.
  • sanitize.rs vision filter: prefix-anchored (model.encoder.vision_tower. / model.encoder.embed_vision.) with suffix-matched calibration-tensor drops; no key-injection surprises, text-only checkpoints carry no vision keys and are unaffected.
  • Index/mask arithmetic: compute_vision_block_ids and the overlay assume prefill offset 0 (no-chunk for vision), block ids align with query/key axes; video_token_id defaults to -1 and never collides with real ids.
  • Multi-image: concatenation order matches expansion order, so feature/position alignment holds in normal operation (now also enforced by the new check).

Not merging. No status-label changes made.

Update block-diffusion.md: replace the phase 1 "Image input not supported"
limitation with a new Image input section covering --image <path> usage,
768x768 preprocessing, 256 soft tokens per image, bidirectional attention
during prefill, and the video/audio rejection. Rename the limitations
section to "Remaining limitations (phase 2)" covering server mode and TP.

Update supported-models.md: revise the DiffusionGemma row to reflect
text + image CLI support, and correct the weight-loading note (vision-tower
weights are now loaded when present; text-only checkpoints fall back silently).
@inureyes

Copy link
Copy Markdown
Member Author

PR Finalization Complete

Summary

  • Tests: verified clean (32 lib tests pass, clippy zero warnings on both feature sets)
  • Documentation: updated docs/block-diffusion.md and docs/supported-models.md
  • Lint/Format: cargo fmt --check and warm cargo clippy --lib --tests --features metal,accelerate -- -D warnings both pass with no issues
  • PR body: appended Real-model verification (phase 2) section; last test plan item marked complete

All checks passing. Ready for merge.

@inureyes

Copy link
Copy Markdown
Member Author

Generation speed vs the mlx-vlm Python reference (M1 Ultra, 4-bit, temperature 0, deterministic canvas, identical prompts, 2 runs each):

Path mlxcel mlx-vlm (Python) per-step time
Image (detail description, EOS-stopped) 7.46 tok/s (74 tok, 16 steps) 6.37 tok/s (67 tok, 17 steps) 620 ms vs 619 ms
Text (256-token essay) 11.9 tok/s (34 steps) 11.3 tok/s (36 steps) 634 ms vs 636 ms

Per-denoising-step cost is identical within noise (within 0.5% on both paths, vision prefill included: 289-token image prompt prefills at ~280 tok/s through the vision tower). The tokens/sec deltas (+5 to +17% for mlxcel here) come from convergence-trajectory differences (different canvas noise paths reach the stable-and-confident stop in slightly different step counts), not from implementation speed.

@inureyes
inureyes merged commit 9c93627 into main Jun 11, 2026
4 checks passed
@inureyes
inureyes deleted the feat/issue-217-diffusion-gemma-image branch June 11, 2026 14:09
@inureyes inureyes added this to the 0.2 milestone Jun 21, 2026
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
* feat: DiffusionGemma image input (phase 2 of lablup#217)

Add single and multi image input to the DiffusionGemma block-diffusion CLI generate path, composing the existing Gemma 4 vision tower, multimodal embedder, and bidirectional vision-block overlay machinery. The text-only phase-1 path stays byte-identical: forward_encoder now delegates to a new forward_encoder_embeds with no overlay, so an all-text prompt runs the same ops.

Loading: keep_diffusion_gemma_weight now retains model.encoder.vision_tower.* and model.encoder.embed_vision.* (dropping the unused clipped-linear calibration tensors when vision_config.use_clipped_linears is false), and load_diffusion_gemma_weights_with_backing takes that flag. DiffusionGemmaModel builds an optional DiffusionVision (Gemma4VisionModel at prefix model.encoder.vision_tower + Gemma4MultimodalEmbedder at model.encoder.embed_vision) only when the tower weights and a parsed vision_config are present; text-only checkpoints load with vision = None.

Config: ModelArgs parses boi_token_id, eoi_token_id, image_token_id, video_token_id, vision_soft_tokens_per_image, and vision_config (into Gemma4VisionConfig).

Forward: prepare_vision_prefill mirrors EncoderModel._embed_inputs (pad image positions for the embedding lookup, scale text embeddings by embed_scale, masked-scatter the RAW unscaled projected image features into the image positions) and derives the per-position vision block ids via compute_vision_block_ids. forward_encoder_embeds OR-es overlay_block_bidirectional onto both the causal and the dense sliding-window masks for every layer at prefill offset 0, matching _vision_block_overlay / _make_encoder_masks. The overlay applies only to the prompt prefill; committed-block appends stay token-based and overlay-free.

Engine: generate_diffusion_streaming gains an optional DiffusionVisionPrefill. With an image present the prompt prefill runs as one embeddings pass (chunked prefill disabled, mirroring _diffusion_should_chunk_prefill); stats and the canvas loop are unchanged.

CLI: generate_diffusion replaces the image rejection with the real path (preprocess via the Gemma 4 image processor, expand the templated prompt's image placeholders into boi + image_token*N + eoi, build the prefill, pass to the engine); --video and audio still reject with clear messages.

Tests: vision config parsing, single and two image prompt expansion, mm_token_type_ids derivation, contiguous vision block ids, overlay mask correctness (image block bidirectional, text causal, sliding window preserved), sanitize keep/skip rules, and an #[ignore] real-model vision-load smoke test. All 32 unit tests pass; the phase-1 real_model_forward_determinism and 23 prior unit tests are unchanged.

Part of lablup#217

* docs: note the DiffusionGemma image-prefill caller on overlay_block_bidirectional

* fix: reject image-token / vision-feature count mismatch in DiffusionGemma prefill

prepare_vision_prefill scattered projected vision features into image-token positions via masked_scatter, which wraps source indices modulo the feature count. A mismatch between the number of image-token positions and the projected feature count (for example a config.json that points image_token_id at a common text token id, or a tower/processor soft-token disagreement) was silently scattering the wrong rows instead of failing. Add an explicit count check that returns a clear error before the scatter.

* docs: document DiffusionGemma image input (phase 2)

Update block-diffusion.md: replace the phase 1 "Image input not supported"
limitation with a new Image input section covering --image <path> usage,
768x768 preprocessing, 256 soft tokens per image, bidirectional attention
during prefill, and the video/audio rejection. Rename the limitations
section to "Remaining limitations (phase 2)" covering server mode and TP.

Update supported-models.md: revise the DiffusionGemma row to reflect
text + image CLI support, and correct the weight-loading note (vision-tower
weights are now loaded when present; text-only checkpoints fall back silently).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Command-line interface / CLI flags area:inference Generation, sampling, decoding (incl. speculative, DRY) area:models Model architectures, weights, loading, metadata priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant