Repository navigation
feat: DiffusionGemma image input (phase 2 of #217) - #219
Conversation
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
Implementation Review SummaryIntentPhase 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 AddressedNone requiring code changes. The implementation matches the mlx-vlm reference at every point reviewed. Verified against reference (
|
…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.
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) —
|
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).
PR Finalization CompleteSummary
All checks passing. Ready for merge. |
|
Generation speed vs the mlx-vlm Python reference (M1 Ultra, 4-bit, temperature 0, deterministic canvas, identical prompts, 2 runs each):
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. |
* 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).
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_weightnow retainsmodel.encoder.vision_tower.*andmodel.encoder.embed_vision.*, dropping the clipped-linear calibration tensors (*.input_max/*.input_min/*.output_max/*.output_min) whenvision_config.use_clipped_linearsis false. Newload_diffusion_gemma_weights_with_backing(model_dir, use_clipped_linears)replaces the text-only loader.src/models/diffusion_gemma/mod.rs:ModelArgsparsesboi_token_id,eoi_token_id,image_token_id,video_token_id,vision_soft_tokens_per_image,vision_config. New optionalDiffusionVision(vision tower at prefixmodel.encoder.vision_tower+Gemma4MultimodalEmbedderatmodel.encoder.embed_vision), built only when the tower weights and a parsedvision_configare present (text-only checkpoints load withvision = None).prepare_vision_prefillmirrorsEncoderModel._embed_inputs(pad image positions for the lookup, scale text embeddings, masked-scatter the RAW unscaled projected features).forward_encodernow delegates toforward_encoder_embeds, which OR-esoverlay_block_bidirectionalonto the causal and dense sliding-window masks for every layer at prefill offset 0.src/models/diffusion_gemma/generate.rs:generate_diffusion_streaminggains an optionalDiffusionVisionPrefill; 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 intoboi + image_token*N + eoi, build prefill, pass to the engine).--videoand audio still reject with clear messages.src/models/gemma4.rs:overlay_block_bidirectionalmadepub(crate)(additive).How text-only behavior is preserved
forward_encoderembeds + scales then callsforward_encoder_embeds(.., None)(no overlay), running the same op sequence as phase 1. The engine only diverges when aDiffusionVisionPrefillis 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 --testscargo clippy --lib --tests -- -D warningsandcargo clippy --bin mlxcel -- -D warningscargo fmtmodels/diffusiongemma-26B-A4B-it-4bit(orchestrator)Real-model verification (phase 2)
Verified on
models/diffusiongemma-26B-A4B-it-4bit(M1 Ultra):--imageflag): each image attributed to the correct position in the response; no cross-image confusion.boi/eoisentinels, 283-token total prompt, matches Python reference exactly.--seed 42, temperature 0): output byte-identical to the phase-1 build with no image flags.metal,acceleratefeature set and default): zero warnings.cargo test --lib models::diffusion_gemma): 32 pass, 0 fail.Part of #217