Repository navigation
Description
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:DecoderLayeralready has the dual dense-MLP + MoE branch withpost_feedforward_layernorm_1/_2,pre_feedforward_layernorm_2, per-layerlayer_scalar,Routerwithper_expert_scale,Experts/SwitchGeGLU,AttentionProjection::KvShared(full-attention layers have nov_proj; values are RMSNormNoScale of keys), per-layer-type RoPE including the proportional type, and softcap viamlxcel_core::compiled_softcap.DecoderLayer::from_weightstakes a key prefix (gemma4.rs:2636), so loading frommodel.decoder.layers.Nis direct.src/vision/encoders/gemma4.rs:Gemma4VisionModelmatches 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. RotatingKVCacheexists in mlxcel-core for sliding-window layers.- Chat template: checkpoint ships
chat_template.jinja; existing minijinja path applies.
What is new
- 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_scalarapplies. 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).
- 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 (
- 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. - 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 forstability_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_configembedded inconfig.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.
- 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.
- Vision input (phase 2): image features via the existing Gemma 4 vision tower at prefix
model.encoder.vision_tower,model.encoder.embed_vision.embedding_projectionfor projection, 280 soft tokens per image, boi/eoi/image token ids from the top-level config, masked scatter into the embedding sequence, and theuse_bidirectional_attention: "vision"overlay (tokens within one contiguous image block attend bidirectionally in encoder mode; mlxcel already has equivalent overlay machinery insrc/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_scalaroverride parameter onDecoderLayer::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_diffusionengine (location: mlxcel-core generate orsrc/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 quantizedembed_tokens(as_linear for logits + softcap 30.0), 30x gemma4DecoderLayerloaded frommodel.decoder.layers.N,encoder_layer_scalars: Vec<MlxArray>frommodel.encoder.language_model.layers.N.layer_scalar,SelfConditioningmodule, optional vision tower + embedder.- Sanitize: drop
lm_head.weightand rotary embedding buffers if present, skip clipping calibration tensors whenuse_clipped_linearsis false, map.experts.{gate_up,down}_projkeys 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::DiffusionGemmainsrc/models/detection.rskeyed onmodel_type == "diffusion_gemma", entry in thefor_each_model_registration!macro (src/model_metadata.rs),LoadedModelvariant.- CLI (
src/main.rs+src/execution/): when the loaded model is the diffusion family, routegenerate/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
- Phase 1: text-only model + CLI generation (the bulk). Done in PR feat: DiffusionGemma block-diffusion text generation (phase 1 of #217) #218 (merged c0a40b8). Backbone load + dual-mode forward + self-conditioning + diffusion engine + generation_config parsing + CLI flags + streaming output. Definition of done includes integration:
mlxcel generate -m models/diffusiongemma-26B-A4B-it-4bit -p "..."produces coherent text end to end. - Phase 2: image input. Done in PR feat: DiffusionGemma image input (phase 2 of #217) #219. Vision tower wiring at the new prefix, embed_vision projection, 280-token image expansion with boi/eoi, bidirectional vision-block overlay in encoder mode, CLI
--image. DoD: image description prompt works end to end. - Phase 3: server integration. Batch-1 only: either a dedicated single-stream serving path with block-by-block SSE streaming, or an explicit clear rejection in the batched scheduler with docs. Decide scope when phase 1 lands (may be split into a follow-up issue).
- Docs: model support table + a short doc on diffusion generation flags and throughput characteristics. (
docs/block-diffusion.md, supported-models, environment-variables; updated through PRs feat: DiffusionGemma block-diffusion text generation (phase 1 of #217) #218/feat: DiffusionGemma image input (phase 2 of #217) #219/feat: serve DiffusionGemma block diffusion in mlxcel-server (phase 3 of #217) #220)
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-4bitfollowing the existingtests/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.rsis 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
inureyes commentedon Jun 11, 2026
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.
feat: DiffusionGemma block-diffusion text generation (phase 1 of #217) (
feat: DiffusionGemma image input (phase 2 of #217) (#219)
docs: document DiffusionGemma server mode (phase 3 of #217)
feat: serve DiffusionGemma block diffusion in mlxcel-server (phase 3 of
inureyes commentedon Jun 11, 2026
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.
feat(models): add Databricks DBRX (dbrx) text model support (#1036)
feat: DiffusionGemma block-diffusion text generation (phase 1 of labl…
feat: DiffusionGemma image input (phase 2 of lablup#217) (lablup#219)
feat: serve DiffusionGemma block diffusion in mlxcel-server (phase 3 of
feat(models): add Databricks DBRX (dbrx) text model support (lablup#1036