Skip to content

feat: support DiffusionGemma (diffusiongemma-26B-A4B-it) block-diffusion generation #217

Closed

Description

@inureyes

Summary

Add support for Google DiffusionGemma (google/diffusiongemma-26B-A4B-it, model_type: "diffusion_gemma"), a block-diffusion language model built on the Gemma 4 26B-A4B MoE backbone. Instead of autoregressive decoding it denoises a 256-token canvas over up to 48 steps per block, commits the block to the KV-cached prefix, and repeats. The checkpoint also ships the Gemma 4 vision tower for image input.

Reference implementation: mlx-vlm (cloned at references/mlx-vlm), commits 8f80dcd (Add Gemma 4 Diffusion, PR #1347) and 5a4222a (Fix DiffusionGemma long-context prefill, PR #1348). Key files:

  • mlx_vlm/models/diffusion_gemma/language.py (backbone, dual encoder/decoder modes, self-conditioning)
  • mlx_vlm/models/diffusion_gemma/config.py, diffusion_gemma.py (config, sanitize, model wrapper)
  • mlx_vlm/generate/diffusion.py (block-diffusion generation engine: canvas loop, entropy-bound sampler, stopping)
  • mlx_vlm/models/diffusion_gemma/processing_diffusion_gemma.py (VLM processing)
  • mlx_vlm/models/diffusion_gemma/README.md (architecture notes, numerics: max abs diff ~1.3e-7 vs the bundled Transformers reference)

Local test checkpoint: models/diffusiongemma-26B-A4B-it-4bit (4-bit, with per-layer 8-bit overrides for mlp.{gate,up,down}_proj and router.proj; includes vision tower and chat_template.jinja).

Architecture analysis: what is already in mlxcel

The text backbone is structurally identical to gemma-4-26b-a4b-it which mlxcel already runs. A config diff of text_config between gemma-4-26b-a4b-it-4bit and diffusiongemma-26B-A4B-it-4bit shows only model_type (gemma4_text vs diffusion_gemma_text) and a few presence-only flags differ; every shape parameter matches (hidden 2816, 30 layers, 5:1 sliding:full layer pattern, sliding window 1024, head_dim 256 / global_head_dim 512, kv heads 8 / global 2, 128 experts top-8, moe_intermediate 704, dense intermediate 2112, vocab 262144, final_logit_softcapping 30.0, rope: default theta 1e4 on sliding, proportional with partial_rotary_factor 0.25 and theta 1e6 on full attention).

Reusable mlxcel components (verified):

  • src/models/gemma4.rs: DecoderLayer already has the dual dense-MLP + MoE branch with post_feedforward_layernorm_1/_2, pre_feedforward_layernorm_2, per-layer layer_scalar, Router with per_expert_scale, Experts/SwitchGeGLU, AttentionProjection::KvShared (full-attention layers have no v_proj; values are RMSNormNoScale of keys), per-layer-type RoPE including the proportional type, and softcap via mlxcel_core::compiled_softcap. DecoderLayer::from_weights takes a key prefix (gemma4.rs:2636), so loading from model.decoder.layers.N is direct.
  • src/vision/encoders/gemma4.rs: Gemma4VisionModel matches the checkpoint vision tower exactly (patch_embedder, position_embedding_table, std_scale/std_bias, pooling_kernel_size 3, .linear. infix keys from clipped-linear wrappers; same layout as the gemma-4-31b VLM tower).
  • Per-layer mixed-bit quantization already loads correctly: infer_quantization_bits (src/lib/mlxcel-core/src/layers.rs:567) infers actual bits per tensor from weight/scales shapes, so the 4/8-bit mixed checkpoint needs no new quantization plumbing.
  • RotatingKVCache exists in mlxcel-core for sliding-window layers.
  • Chat template: checkpoint ships chat_template.jinja; existing minijinja path applies.

What is new

  1. Dual-mode backbone. The same 30 decoder layers run in two modes:
    • Encoder mode: causal prefill of the prompt and of each committed block. Standard causal + sliding-window masks, RoPE offset from cache, KV cache write. Uses per-layer encoder scalars stored separately in the checkpoint (model.encoder.language_model.layers.N.layer_scalar, 30 scalars; everything else is weight-tied to the decoder).
    • Canvas (decoder) mode: the noisy canvas (up to 256 tokens) attends bidirectionally within itself and to the encoder KV cache as a read-only prefix. Canvas K/V are concatenated to the cached encoder K/V, the cache is NOT updated, all canvas positions use RoPE offset = encoder length, SDPA scale 1.0, and the stored decoder layer_scalar applies. Sliding layers only need the last (sliding_window - 1) encoder positions, so the reference trims encoder K/V before SDPA to keep sliding layers O(window).
  2. Self-conditioning module (model.decoder.self_conditioning.*): a GeGLU MLP (pre RMSNorm, gate/up/down projections, post RMSNormNoScale) that adds a signal derived from the previous denoising step's soft embeddings (softmax(logits) @ embedding table, scaled by sqrt(hidden)) to the canvas embeddings.
  3. Block-diffusion generation engine (the core new code, mirroring mlx_vlm/generate/diffusion.py):
    • Per block: canvas length = min(canvas_length, max(remaining_tokens, min_canvas 64)); canvas initialized with uniform random token ids.
    • Up to max_denoising_steps (48) iterations: decoder-mode forward (with self-conditioning embeddings after step 1), divide logits by a linear temperature schedule (t_min 0.4 to t_max 0.8 over steps), compute per-position entropy, accept positions via the entropy-bound rule (sort entropies ascending, accept the prefix where cumsum(entropy) - cummax(entropy) <= entropy_bound 0.1, scatter back), re-randomize rejected positions, and early-stop when the argmax canvas has been stable for stability_threshold (1) consecutive steps AND mean token entropy < confidence_threshold (0.005).
    • Commit the argmax canvas, stream its tokens until an EOS id ([1, 106, 50]) stops the request, then run an encoder pass over the committed block to extend the KV cache and start the next block.
    • Optional second sampler from the reference: confidence-threshold (commit high-confidence positions early). Entropy-bound is the checkpoint default.
    • All knobs come from generation_config embedded in config.json (max_denoising_steps, max_new_tokens, t_min/t_max, sampler entropy_bound, confidence/stability thresholds, eos ids); mlxcel does not currently parse generation config, so add parsing for this model.
  4. Chunked prefill for long prompts (the PR feat(embeddings): native embedding and reranking subsystem (epic) #1348 fix): chunk only when there is no padding, no vision input, and no static cache; eval cache state and clear the MLX cache between chunks.
  5. Vision input (phase 2): image features via the existing Gemma 4 vision tower at prefix model.encoder.vision_tower, model.encoder.embed_vision.embedding_projection for projection, 280 soft tokens per image, boi/eoi/image token ids from the top-level config, masked scatter into the embedding sequence, and the use_bidirectional_attention: "vision" overlay (tokens within one contiguous image block attend bidirectionally in encoder mode; mlxcel already has equivalent overlay machinery in src/vision/gemma4_unified_mask.rs).

Design

New module src/models/diffusion_gemma.rs that composes gemma4 building blocks instead of forking them. Additive hooks in src/models/gemma4.rs where needed (this is a hot shared file used by MTP/unified/VLM; changes must be additive and keep existing gemma4 tests green):

  • an optional layer_scalar override parameter on DecoderLayer::forward (encoder mode passes the encoder scalar; default None keeps current behavior),
  • a canvas-mode attention path: compute canvas Q/K/V (q_norm/k_norm/v_norm + RoPE at offset = encoder_len), read cached encoder K/V without updating, trim to the sliding window on sliding layers, concat, SDPA with a per-layer-type mask.

mlxcel-core additions:

  • a read-only "visible K/V state" accessor on the dense KV cache and a temporal-order view on RotatingKVCache (decoder mode concatenates cached K/V without writing).
  • generate_diffusion engine (location: mlxcel-core generate or src/execution/), implementing the loop above with streaming callbacks per committed token and diffusion stats (canvas tokens, denoising steps, work tokens = canvas x steps) for verbose output.

Model struct:

  • DiffusionGemmaModel: tied quantized embed_tokens (as_linear for logits + softcap 30.0), 30x gemma4 DecoderLayer loaded from model.decoder.layers.N, encoder_layer_scalars: Vec<MlxArray> from model.encoder.language_model.layers.N.layer_scalar, SelfConditioning module, optional vision tower + embedder.
  • Sanitize: drop lm_head.weight and rotary embedding buffers if present, skip clipping calibration tensors when use_clipped_linears is false, map .experts.{gate_up,down}_proj keys onto the SwitchGeGLU layout (same handling as the existing 26b-a4b loader).
  • Caches: per layer, full-attention -> dense KV cache, sliding -> RotatingKVCache(max_size=sliding_window).
  • supports_batching() = false (model-owned sequence state), which keeps it out of the batched/paged scheduler automatically.
  • Self-conditioning soft embeddings need a float view of the embedding table: dequantize once per generation call (the reference measured quantized_matmul(transpose=false) as several times slower at this shape). Note the cost: 262144 x 2816 fp16 is about 1.4 GiB transient.

Registration/dispatch:

  • ModelType::DiffusionGemma in src/models/detection.rs keyed on model_type == "diffusion_gemma", entry in the for_each_model_registration! macro (src/model_metadata.rs), LoadedModel variant.
  • CLI (src/main.rs + src/execution/): when the loaded model is the diffusion family, route generate/run/REPL to the diffusion engine. New flags mirroring the reference: --max-denoising-steps, --diffusion-sampler {entropy-bound,confidence-threshold}, --diffusion-threshold, --diffusion-min-canvas-length, --diffusion-max-canvas-length, --diffusion-full-canvas. Seed plumbing is required for reproducible runs (canvas starts from random noise).

Phased plan

Acceptance Criteria

  • mlxcel generate -m models/diffusiongemma-26B-A4B-it-4bit -p "..." produces coherent text end to end (Phase 1)
  • Image description prompt works end to end via --image (Phase 2)
  • Server behavior decided and implemented: batch-1 serving path or documented rejection (Phase 3)
  • Forward-pass parity vs mlx-vlm within thresholds; existing gemma4 tests unchanged
  • Docs updated: model support table + diffusion generation flags

Verification plan

  • Unit tests: entropy-bound transfer mask against hand-computed cases, linear temperature schedule, stable-and-confident stopping, generation_config parsing, mixed 4/8-bit load.
  • Forward-pass parity vs mlx-vlm with exported fixtures (fixed canvas ids and fixed self-conditioning input): encoder logits and decoder-mode logits, max abs / RMS thresholds. Byte-level end-to-end parity with Python is NOT expected because canvas initialization consumes RNG and the RNG sequences differ; the parity gate is forward numerics plus an end-to-end smoke quality check at temperature 0 with a fixed seed.
  • Real-model E2E on models/diffusiongemma-26B-A4B-it-4bit following the existing tests/ real-model pattern (#[ignore], soft-skip when the checkpoint is absent, --test-threads=1).
  • Cold clippy on both CI feature sets, fmt, full lib test suite, and existing gemma4 tests unchanged.

Risks and notes

  • src/models/gemma4.rs is shared with Gemma 4 MTP/unified/VLM paths; all hooks must be additive.
  • Throughput is dominated by the repeated MoE canvas forwards (256 tokens x up to 48 steps per block); the reference reports roughly 24 tok/s generation for the bf16 checkpoint on Apple silicon, with the stable-and-confident criterion usually converging well before the step cap.
  • The KV cache cannot help inside the denoising loop (the canvas is bidirectional and changes every step); it only caches the committed prefix.
  • Peak memory: the bf16 reference reports ~51 GB; the 4-bit checkpoint should be far lower, plus the ~1.4 GiB dequantized embedding table during generation.

Activity

  1. added
    status:ready
    type:enhancement
    priority:medium
    area:models
    area:inference
    area:cli
    status:in-progress
    status:review
    and removed
    status:ready
    status:in-progress
    status:review
    on Jun 11, 2026
  2. inureyes commented on Jun 11, 2026

    @inureyes
    MemberAuthor

    Phase 1 (text-only block-diffusion generation, CLI integration, server-mode rejection) is implemented and ready in PR #218 (status:done, not merged yet). Real-model verification on models/diffusiongemma-26B-A4B-it-4bit passed: byte-deterministic temperature-0 runs, token-level parity with the mlx-vlm reference up to one near-tie whitespace token, and per-denoising-step time at 96-103% of the Python implementation. The verification also uncovered and fixed two pre-existing bugs (an upstream MLX steel GEMM safe-load typo, carried as an overlay until the next MLX bump, and an unsound graph-level slice+copy weight split feeding gather_qmm); details in the PR body. Phases 2 (image input) and 3 (server serving) remain, so this issue stays open and in progress.

  3. added
    status:review
    and removed
    status:in-progress
    on Jun 11, 2026
  4. inureyes commented on Jun 11, 2026

    @inureyes
    MemberAuthor

    All three phases are implemented, verified on the real checkpoint, and merged: phase 1 text-only block-diffusion engine + CLI (PR #218, c0a40b8), phase 2 image input (PR #219, 9c93627), phase 3 mlxcel-server serving (PR #220, e099821, auto-closed this issue).

    Highlights beyond the original scope: the real-model gate surfaced and fixed two pre-existing base-layer bugs (the pinned-MLX steel GEMM safe-load typo, carried as an overlay until the next MLX bump, and an unsound graph-level slice+copy weight split feeding gather_qmm, now split on host bytes); throughput was characterized against the same-backbone AR model (entropy-bound default 15 tok/s vs AR 71 tok/s on M1 Ultra; the confidence-threshold sampler narrows the gap to 1.7x at threshold 0.6 with clean quality) and against the mlx-vlm reference (per-denoising-step parity within 0.5% on both text and image paths). Determinism is regression-tested (buffer-cache-warmed byte-determinism test) and the temperature-0 CLI output stayed byte-identical across all three phases.

  5. added this to the 0.2 milestone on Jun 21, 2026
  6. self-assigned this
    on Aug 31, 2026
  7. added
    status:done
    and removed
    status:review
    on Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area:cliarea:inferencearea:modelspriority:mediumstatus:donetype:enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions