Skip to content

feat: DiffusionGemma block-diffusion text generation (phase 1 of #217) - #218

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

inureyes merged 6 commits into
mainfrom
feat/issue-217-diffusion-gemma-text

Conversation

@inureyes

@inureyes inureyes commented Jun 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds phase 1 of DiffusionGemma support: text-only block-diffusion generation for google/diffusiongemma-26B-A4B-it (model_type: "diffusion_gemma"), integrated into the CLI generate flow. Phases 2 (image input) and 3 (server serving) remain open.

Part of #217

What changed

  • src/models/diffusion_gemma/ (new): model module composing gemma4 building blocks. Encoder mode runs the standard causal Gemma 4 forward into dense Fp16 KV caches with each layer scaled by the checkpoint's per-layer ENCODER scalar (model.encoder.language_model.layers.N.layer_scalar); canvas mode embeds the noisy canvas, always applies the self-conditioning module (GeGLU MLP + RMSNormNoScale post-norm, zero-signal fast path on the first step), and attends bidirectionally to the read-only cached prefix with the upstream O(window) sliding-layer trim. Fused experts.gate_up_proj tensors are split along the output axis (gate rows first) onto the existing SwitchGeGLU key layout at load time; vision-tower weights are skipped without error.
  • Generation engine (diffusion_gemma/generate.rs): mirrors mlx-vlm stream_diffusion_generate for batch-1 dynamic-cache generation: per-block canvas sizing min(max_canvas, max(remaining, min_canvas)), uniform-random canvas init, linear temperature schedule t_min..t_max over descending steps, entropy-bound sampler (host-side prefix rule over sorted entropies, equivalent to the reference (cumsum - cummax) <= bound) and confidence-threshold sampler (reveal mask + forced best position), stable-and-confident early stop with the reference's check-before-push history order, self-conditioning soft embeddings via a once-per-call dequantized embedding table, full-canvas commit and append, chunked prefill for long prompts, EOS stop without emission, and diffusion work stats. A deterministic debug mode (MLXCEL_DIFFUSION_DEBUG_CANVAS=1) replaces every canvas randomization with a fixed pattern and prints DIFFUSION_COMMIT block=<n> ids=... per block for cross-implementation parity gating at temperature 0.
  • src/models/gemma4.rs (additive seams only; hot path byte-identical): DecoderLayer::ffn_branch extraction reused verbatim by forward_with_profile, new DecoderLayer::forward_encoder_with_scalar, new DecoderLayer::forward_canvas, new Attention::forward_canvas (same compiled proportional Q/K kernels as the encoder path, k-eq-v values on full-attention layers, maskless SDPA at scale 1.0), parse_eos_ids widened to pub(crate).
  • src/lib/mlxcel-core/src/cache.rs: read-only KVCache::visible_state() accessor returning the live dense Fp16 K/V window without writing.
  • src/lib/mlxcel-core/src/layers.rs: UnifiedEmbedding::dequantized_weight() for the soft-embedding matmul table.
  • Registration: ModelType::DiffusionGemma keyed on diffusion_gemma / diffusion_gemma_text in detection, nonstandard directory loader, LoadedModel::DiffusionGemma variant + delegate arm, metadata/arch entries, TP planner placeholder arm. The LanguageModel impl is honest but minimal: encoder forward + norm + tied logits, dense Fp16 make_caches, supports_batching() = false.
  • CLI (src/main.rs, src/commands/): new Diffusion Options flag group (--max-denoising-steps, --diffusion-sampler entropy-bound|confidence-threshold, --diffusion-threshold, --diffusion-min-canvas-length, --diffusion-max-canvas-length, --diffusion-full-canvas) plus --seed (seeds MLX's global RNG, also wired into the autoregressive sampling config). run_generate_once routes LoadedModel::DiffusionGemma to the new generate_diffusion driver (streaming via the shared incremental detokenizer, tail flush, stats output) BEFORE the autoregressive loop; the chat REPL rejects the family with a one-shot usage hint; image/audio/video inputs are rejected as phase 2.
  • Server (src/server/model_worker.rs): both worker spawn paths reject the family at load time with "DiffusionGemma (block diffusion) is not supported in server mode yet; use the CLI: mlxcel generate -m -p "..."".

Test plan

  • cargo test --lib models::diffusion_gemma (23 new unit tests: entropy-bound acceptance count and mask incl. ties, confidence transfer mask incl. forced-best and force_all, temperature schedule endpoints, stability-tracker history-order semantics, canvas length rule, deterministic debug pattern, literal real-config parsing asserting the forced attention_k_eq_v / enable_moe_block flags, gate_up split arithmetic on synthetic shapes, dense windowed mask correctness for L>1 at offset>0)
  • cargo test --lib models::gemma4 (existing gemma4 tests unchanged and green)
  • cargo check --lib --tests and cargo check --bins
  • cargo clippy --lib --tests -- -D warnings and cargo clippy --bins -- -D warnings
  • cargo fmt
  • cargo test --test cli_help_consistency and cargo test --bin mlxcel (flag defaults lock-step test included)

Real-model end-to-end verification on models/diffusiongemma-26B-A4B-it-4bit (coherent text + temperature-0 cross-implementation parity via the deterministic debug canvas mode) is performed by the orchestrator after this PR.

Root cause work uncovered by the real-model gate (added after review of the first implementation)

The orchestrator's real-model verification found the canvas output garbled and nondeterministic (identical commands produced different tokens run to run), while the mlx-vlm Python reference was deterministic and correct on the same machine with the same checkpoint and even with the same MLX commit built from source. Bisection isolated two independent bugs, both fixed in this PR:

  1. Upstream MLX steel GEMM safe-load typo (cherry-picked overlay). The pinned MLX commit (2026-05-09) indexes edge-tile columns with off_x instead of off_y in BaseMMAFrag<T, 8, 8>::load_safe, fixed upstream on 2026-05-18/19 (ml-explore/mlx PRs perf(cuda): charge MLX Gather and GatherQMM for the rows they read #3560/chore(webui): drop the unused lab dependency and trim the README #3565). Every non-tile-aligned steel GEMM read wrong rows, and through strided views could read uninitialized parent-buffer regions, turning nondeterministic under allocator churn. DiffusionGemma hits this constantly: head_dim 256/512 SDPA routes around the fused attention kernel into steel GEMM with ragged key lengths. Carried as patches/mlx/backend/metal/kernels/steel/gemm/mma.h; drop on the next MLX bump. A new mlxcel-core unit test (steel_gemm_edge_tile_safe_load_matches_reference) pins the behavior.

  2. Graph-level slice+copy of fused expert weights is unsound as gather_qmm input. With router indices, weights, and inputs byte-identical across runs, the first expert gather_qmm diverged run to run when the gate/up tensors came from slice + copy; rebuilding the same bytes into pristine dense arrays made the identical call byte-deterministic. Since every one of the 30 layers runs the MoE branch each denoising step, this single issue accounted for most of the canvas corruption. split_gate_up_tensor now splits on host bytes (per-expert row blocks, dtype-size aware, 16-bit dtypes through from_bytes_f16) once at load time. The Python reference never hits this because mlx-vlm keeps the fused gate_up projection and slices activations instead of weights.

The investigation also ruled out (with isolated experiments): the maskless fused SDPA kernel, in-graph KV-cache slices and concatenation, the compiled-op chains (MLX_DISABLE_COMPILE unchanged the symptom), mx eval/read-back synchronization, and threadgroup-limit violations reported by the Metal validation layer (validation instrumentation lowers pipeline limits; not a production defect). Production text models (qwen2.5, gemma-4-31b, gemma-4-26b-a4b) were re-verified deterministic and coherent after both fixes.

Real-model verification results (M1 Ultra, models/diffusiongemma-26B-A4B-it-4bit)

  • Determinism: three identical temperature-0 runs with the deterministic debug canvas produce byte-identical commit streams; the new real_model_forward_determinism regression test (with buffer-cache warmup, since the historical failure modes only appear under allocator churn) asserts byte-determinism of encoder and canvas forwards.
  • Cross-implementation parity: with the same deterministic canvas pattern monkeypatched into mlx-vlm, the emitted token stream matches the Python reference exactly up to one near-tie whitespace token at position 14 (after which the sequences realign and continue identically); output text is the same Rayleigh-scattering explanation.
  • Quality: coherent long-form output on multiple prompts (TCP/UDP explanation, haiku) at temperature 0 with seeded RNG.
  • Performance: per-denoising-step time is at parity with the Python reference: 254 ms/step vs 261 ms/step on a 64-token canvas (103%), 651 ms/step vs 626 ms/step on a 256-token canvas (96%). Tokens/sec varies with the stable-and-confident early stop's trajectory (e.g. 20.0 tok/s for a 64-token answer converging in 12 steps; 8.2 tok/s for a 256-token canvas running the full 48 steps). Model load: 13.5 GiB resident.

Add text-only support for google/diffusiongemma-26B-A4B-it (model_type "diffusion_gemma"), a block-diffusion language model on the Gemma 4 26B-A4B MoE backbone, integrated into the CLI generate flow.

New module src/models/diffusion_gemma composes the existing gemma4 building blocks: encoder mode (causal prefill into dense Fp16 KV caches with per-layer ENCODER scalars), canvas decoder mode (bidirectional canvas attention against the read-only cached prefix with the upstream sliding-window trim), the self-conditioning GeGLU module, fused expert gate_up splitting onto the SwitchGeGLU key layout, and generation_config parsing. The generation engine mirrors mlx-vlm stream_diffusion_generate: linear temperature schedule, entropy-bound (default) and confidence-threshold samplers, stable-and-confident early stopping, chunked prefill, full-canvas commit and append, and a deterministic debug canvas mode (MLXCEL_DIFFUSION_DEBUG_CANVAS=1) for cross-implementation parity gating.

gemma4.rs changes are additive seams only: ffn_branch extraction (byte-identical hot path), DecoderLayer::forward_encoder_with_scalar, DecoderLayer::forward_canvas, Attention::forward_canvas, and parse_eos_ids visibility. mlxcel-core gains KVCache::visible_state (read-only dense Fp16 window) and UnifiedEmbedding::dequantized_weight (once-per-call soft-embedding table).

CLI: new diffusion flag group (--max-denoising-steps, --diffusion-sampler, --diffusion-threshold, --diffusion-min-canvas-length, --diffusion-max-canvas-length, --diffusion-full-canvas) and --seed; generate routes the family to the diffusion engine with streaming detokenization before the autoregressive loop; interactive chat rejects it with a clear one-shot hint. The server model worker rejects DiffusionGemma at load time with a clear "use the CLI" error until phase 3 lands. Image/video input remains phase 2.
@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 added 2 commits June 11, 2026 16:43
…verlay

The pinned MLX commit (2026-05-09) carries a one-character bug in
BaseMMAFrag<T, 8, 8>::load_safe (mlx/backend/metal/kernels/steel/gemm/mma.h):
edge-tile loads index columns with off_x instead of off_y, so every
non-tile-aligned steel GEMM reads the wrong rows, and through strided views
it can read uninitialized parent-buffer regions. Upstream fixed it on
2026-05-18/19 (ml-explore/mlx PRs #3560 and #3565); this overlay carries the
fix until the next MLX bump and can be dropped then.

On M1-generation GPUs this corrupted the DiffusionGemma canvas SDPA fallback
(head_dim 256/512 routes around the fused kernel into steel GEMM with ragged
key lengths), nondeterministically under allocator churn. A new
steel_gemm_edge_tile_safe_load_matches_reference unit test pins a
non-tile-aligned GEMM against a composite multiply+sum reference so a future
MLX bump cannot silently reintroduce the bug.
…soundness

Building the gate/up halves with graph-level slice + copy produced arrays
that gather_qmm read incorrectly on the pinned MLX: with router indices,
weights, and inputs byte-identical across runs, the first expert projection
diverged run to run once the Metal buffer cache carried churn, which is what
turned every DiffusionGemma canvas denoise into nondeterministic garbage
(all 30 layers run the MoE branch). Rebuilding the same bytes into pristine
dense arrays makes the identical gather_qmm call byte-deterministic, so
split_gate_up_tensor now performs the output-axis split on host bytes
(per-expert row blocks, dtype-size aware, 16-bit dtypes through
from_bytes_f16) and evaluates the halves once at load time.

Also folds the real-model debug battery into one regression test:
real_model_forward_determinism warms the buffer cache first (the historical
failure modes only show under allocator churn) and asserts byte-determinism
of both the encoder and canvas forwards.

Verified on models/diffusiongemma-26B-A4B-it-4bit: three identical
temperature-0 runs (byte-identical commits), output matches the mlx-vlm
reference up to one near-tie whitespace token, per-step denoise time at
96-103% of the Python implementation.
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Phase 1 of #217: text-only DiffusionGemma block-diffusion generation wired into the CLI generate flow, mirroring mlx-vlm stream_diffusion_generate / diffusion_gemma.language.

Verification (independent review + targeted build/tests)

  • Reference parity (default path): entropy-bound accept rule ((cumsum-cummax)<=bound prefix), linear temperature schedule, stability-tracker history order, self-conditioning soft embeddings (probs@table*embed_scale), zero-signal post-norm fast path, full-canvas commit/append, EOS-without-emission, chunked prefill all match the reference.
  • Canvas attention (gemma4::Attention::forward_canvas): sliding-layer O(window) trim to last sliding_window-1, k-eq-v values on full-attention layers, RoPE at offset=encoder_len through the same compiled kernels, maskless SDPA at scale 1.0 — matches decoder=True reference incl. the implicit-None decoder mask for batch-1/no-padding.
  • Hot path byte-identical: DecoderLayer::ffn_branch is a verbatim extraction from forward_with_profile (diff confirms only &after_attn→after_attn plumbing); forward_encoder_with_scalar/forward_canvas are additive and unreachable from existing gemma4 model paths. cargo test --lib models::gemma4: 41 passed, 0 failed.
  • Soundness: split_gate_up_tensor host-byte split is dtype-size aware and routes 16-bit dtypes through from_bytes_f16 (avoids the Distributed block-table serialization (kv_cache_serde) #125 half-byte corruption); the single unsafe (null-key global RNG) is documented.
  • KVCache::visible_state() and UnifiedEmbedding::dequantized_weight() are mode-guarded (Fp16-only, non-paged) and read-only; slicing [0..buffer_idx()) correctly returns the live window even after head-trim (slot 0 == live_start).
  • MLX overlay steel/gemm/mma.h is byte-identical to pristine upstream @ 84961223 except the one-line off_x→off_y fix (verified against the upstream raw file): src[(off_x+i)*str_x + (off_y+j)*str_y]. CMake overlay list + drop-on-bump note correct.
  • Integration complete: detection (diffusion_gemma/diffusion_gemma_text), nonstandard loader, LoadedModel::DiffusionGemma + delegate arm, metadata/arch/TP-placeholder entries, vision-weight skip in sanitize, CLI Diffusion Options flag group + --seed, run_generate_once routes to the diffusion driver before the AR loop, server (both worker spawn paths) + chat REPL reject with actionable CLI hints. No orphaned/placeholder code.
  • cargo check --lib --tests clean; cargo clippy --lib --tests -- -D warnings clean; cargo test --lib models::diffusion_gemma: 23 passed (1 real-model #[ignore]).

Findings

  • MEDIUM (report-only): confidence-threshold all-revealed commit diverges from the reference. In generate.rs::denoise_block, when every position is revealed the engine commits draft_canvas (commit = copy(&draft_canvas); break), but the reference unconditionally commits the final-step argmax_canvas in every exit path (diffusion.py:1037 overrides current_canvas = argmax_canvas after the loop; the accepted_canvas = draft_canvas at 1017 is dead). The other Rust exit paths (cur_step==1, stable-and-confident) already commit argmax, so this branch is also internally inconsistent. Not auto-fixed: the confidence-threshold sampler is non-default and was not part of the temperature-0 cross-implementation parity gate, and "draft vs final argmax" is arguably ambiguous in intent. To match the reference, drop the commit = copy(&draft_canvas) line and just break (leaving commit = this step's argmax).

Remaining Items

  • None blocking. Phases 2 (image) and 3 (server) are explicitly out of scope and correctly rejected.

inureyes added 2 commits June 11, 2026 17:10
The confidence sampler's all-revealed early exit committed the revealed
draft canvas, but the reference unconditionally commits the last executed
step's argmax canvas after the loop (its draft assignment is dead code),
and the engine's other exit paths already did the same. Aligns the branch
for exact reference parity and internal consistency (pr-reviewer finding).
The entropy-bound acceptance mask sorted entropies with partial_cmp().unwrap_or(Equal), an inconsistent comparator when a NaN entropy is present (which modern Rust slice sorts may treat as a hard error). A NaN entropy can only arise from a degenerate temperature schedule that drives logits to inf, but the host-side acceptance path should never be able to panic on it. total_cmp is a total order with identical ordering for the finite, non-negative entropies of the normal path, and sorts NaN last so a maximally uncertain position is never accepted.
@inureyes

Copy link
Copy Markdown
Member Author

Security & performance review (automated)

Reviewed the focus areas; no CRITICAL or HIGH findings. One LOW defensive fix applied and pushed.

Fixed (committed to this branch)

  • LOW (robustness): entropy_bound_acceptance_mask sorted entropies with partial_cmp().unwrap_or(Equal), an inconsistent comparator if a NaN entropy ever appears (modern Rust slice sorts can treat this as a hard error). Switched to f32::total_cmp: identical ordering for the finite, non-negative entropies of the normal path, NaN sorts last (never accepted). A NaN can only arise from a degenerate t_min == t_max == 0 schedule driving logits to inf, but the host-side acceptance path should not be able to panic on it. 26cffcd03.

Verified safe

  • Config parsing (mod.rs): split_gate_up_tensor validates rank, output-dim == 2*moe_dim, and byte length before slicing; per-expert byte offsets stay in bounds (base + 2*half_bytes == next expert base); element size is dtype-checked and unsupported dtypes error cleanly (no corruption). canvas_length/max_denoising_steps are .max(1)-guarded before any division.
  • Generation loop (generate.rs): max_denoising_steps, model_canvas, max_new_tokens all floored to >= 1; canvas_len >= 1; mean-entropy divisor is len().max(1). Counters are usize and cannot overflow at realistic 64-bit magnitudes. The MLXCEL_DIFFUSION_DEBUG_CANVAS knob is opt-in (== "1"), only swaps canvas randomization for a fixed pattern and writes DIFFUSION_COMMIT to stderr; it does not alter the production code path otherwise.
  • CLI (generate_diffusion.rs, flags): threshold validated to [0,1], canvas lengths and prefill chunk validated > 0 with clear messages; usize/u64 flags cannot be negative. with_capacity(max_new_tokens) matches the existing autoregressive paths.
  • cache.rs::visible_state: read-only lazy slices, guarded to Fp16 non-paged caches, returns None on empty/incompatible state; no mutation, no aliasing/UB. layers.rs::dequantized_weight: non-quantized is a cheap share, quantized uses the same FFI unsafe pattern as the rest of the file.
  • model_worker.rs: both spawn paths (spawn_model_worker_with_batch_config, spawn_legacy_model_worker) reject the family as the first branch, before load_model/load_model_with_tensor_parallel; no bypass, no panic (returns an anyhow::Error).
  • Performance: the per-step entropy host pull is inherent to the host-side acceptance rule and is at parity with the Python reference per the PR's measurements; the ~1.4 GiB dequantized embedding table is built once per call as documented; clear_memory_cache after each committed block bounds cross-block growth.
  • MLX overlay (mma.h): the off_y/str_y fix is present (load_safe), CMake applies it deterministically (configure_file ... COPYONLY, existence-gated), and steel_gemm_edge_tile_safe_load_matches_reference pins the behavior.

Note (no action required now)

  • The 1146-line mma.h overlay could not be byte-diffed against the pinned upstream (GIT_TAG 8496122...) within the review sandbox. The behavior test plus the PR's re-verification of production models (qwen2.5, gemma-4-31b/26b-a4b) cover regression risk; suggest a one-time diff of the overlay against the upstream file at the next MLX bump to confirm the delta is only the safe-load fix.

cargo check --lib --tests, cargo test --lib models::diffusion_gemma (23 passed), and warm cargo clippy --lib --tests -- -D warnings are green after the fix.

Adds docs/block-diffusion.md with a full description of the block-diffusion generation model: canvas denoising vs autoregressive, the entropy-bound and confidence-threshold samplers, all CLI flags with defaults, throughput measurements from M1 Ultra (8-20 tok/s depending on canvas convergence, at per-step parity with the mlx-vlm reference), reproducibility via --seed, and phase 1 limitations (text-only CLI, no image input, no server mode).

Updates docs/supported-models.md to list DiffusionGemma in a new block-diffusion section with detection keys and load notes, and bumps the variant count to 93/71.

Adds MLXCEL_DIFFUSION_DEBUG_CANVAS to docs/environment-variables.md in its own diagnostic section.

Adds the block-diffusion.md entry to docs/README.md.

All existing tests pass: 23 diffusion_gemma unit tests, 117 bin tests, 10 cli_help_consistency tests, cargo fmt clean, cargo clippy clean.
@inureyes

Copy link
Copy Markdown
Member Author

PR finalization complete

Tests

All pre-existing tests verified passing: 23 diffusion_gemma unit tests (1 real-model #[ignore]), 117 bin tests, 10 cli_help_consistency tests.

No new pure-unit tests added: test coverage for all host-side helpers (entropy-bound sampler, confidence-threshold sampler, temperature schedule, stability tracker, canvas length rule, debug canvas pattern, config parsing, gate_up split, dense windowed mask) was already comprehensive in the PR.

Documentation (English only -- no Korean doc convention in this repo)

  • docs/block-diffusion.md (new): explains canvas denoising vs autoregressive decoding, the two samplers (entropy-bound and confidence-threshold), all CLI flags with defaults, M1 Ultra throughput measurements (8-20 tok/s, per-step parity with the mlx-vlm reference), reproducibility via --seed, and phase 1 limitations (text-only CLI, no image input, no server mode).
  • docs/supported-models.md: new "Block-diffusion text models" section listing DiffusionGemma with detection keys, load notes, and a link to the new guide. Variant count updated from 92 to 93.
  • docs/environment-variables.md: new "Block-diffusion diagnostic variables" section documenting MLXCEL_DIFFUSION_DEBUG_CANVAS.
  • docs/README.md: added block-diffusion.md to the docs listing.

Lint/format

cargo fmt --check clean, cargo clippy --lib --tests --features metal,accelerate -- -D warnings clean. No code changes needed.

@inureyes

Copy link
Copy Markdown
Member Author

Throughput comparison on the same 26B-A4B backbone (M1 Ultra, 4-bit, temperature 0, identical long-form prompt, 2 runs each):

Output length AR gemma-4-26b-a4b-it (decode tok/s) dLLM diffusiongemma (tok/s) dLLM blocks / denoise steps AR / dLLM ratio
512 71.3 / 71.2 15.06 / 15.16 2 / 53 4.7x
1024 68.3 / 68.4 14.28 / 15.38 4 / 111, 103 4.6x

Notes: dLLM throughput is roughly flat with output length (each 256-token block converges in about 26-28 denoising steps on this prompt, so cost scales linearly with blocks), while AR decode decays slightly with context (71.3 to 68.3 tok/s). The dLLM denoise work rate is stable at ~396-402 canvas-position visits per second; each emitted token costs ~26 denoise visits at this convergence rate, which is where the 4.6-4.7x gap comes from. Prefill is comparable (AR ~220 tok/s, dLLM ~250 tok/s). Short answers that converge early (e.g. 12 steps for one 64-token block) narrow the gap to ~3.5x.

@inureyes

Copy link
Copy Markdown
Member Author

dLLM throughput tuning sweep (same backbone comparison continued; M1 Ultra, 4-bit, temp 0, 512-token essay prompt, 2 runs each):

Config tok/s denoise steps vs baseline vs AR (71.3)
entropy-bound, canvas 256 (default) 15.0 53 1.0x 4.8x slower
canvas 128 13.9-15.2 89-98 ~1.0x ~4.7x slower
canvas 64 10.3-10.7 178-185 0.7x 6.8x slower
confidence-threshold 0.8 30.4-32.9 24-26 2.1x 2.3x slower
confidence-threshold 0.6 39.6-41.9 19-20 2.7x 1.7x slower
canvas 64 + confidence 0.8 28.0-29.1 63-65 1.9x 2.5x slower

Findings: shrinking the canvas does not help on Apple silicon (steps per block stay roughly constant while the GPU work rate drops from ~397 to ~238 canvas-position visits per second at canvas 64, so it is a net loss). The effective lever is the confidence-threshold sampler, which commits high-confidence positions early and cuts steps per 256-token block from ~27 to ~10: 2.1x at threshold 0.8 and 2.7x at 0.6, narrowing the AR gap from 4.8x to 1.7x. A quality spot check of the 0.6 output on the long-form essay showed no visible degradation (coherent structure, accurate content). The checkpoint default stays entropy-bound for reference fidelity; the sampler is exposed via --diffusion-sampler / --diffusion-threshold.

@inureyes
inureyes merged commit c0a40b8 into main Jun 11, 2026
4 checks passed
@inureyes
inureyes deleted the feat/issue-217-diffusion-gemma-text branch June 11, 2026 12:35
@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
…up#217) (lablup#218)

* feat: DiffusionGemma block-diffusion text generation (phase 1 of lablup#217)

Add text-only support for google/diffusiongemma-26B-A4B-it (model_type "diffusion_gemma"), a block-diffusion language model on the Gemma 4 26B-A4B MoE backbone, integrated into the CLI generate flow.

New module src/models/diffusion_gemma composes the existing gemma4 building blocks: encoder mode (causal prefill into dense Fp16 KV caches with per-layer ENCODER scalars), canvas decoder mode (bidirectional canvas attention against the read-only cached prefix with the upstream sliding-window trim), the self-conditioning GeGLU module, fused expert gate_up splitting onto the SwitchGeGLU key layout, and generation_config parsing. The generation engine mirrors mlx-vlm stream_diffusion_generate: linear temperature schedule, entropy-bound (default) and confidence-threshold samplers, stable-and-confident early stopping, chunked prefill, full-canvas commit and append, and a deterministic debug canvas mode (MLXCEL_DIFFUSION_DEBUG_CANVAS=1) for cross-implementation parity gating.

gemma4.rs changes are additive seams only: ffn_branch extraction (byte-identical hot path), DecoderLayer::forward_encoder_with_scalar, DecoderLayer::forward_canvas, Attention::forward_canvas, and parse_eos_ids visibility. mlxcel-core gains KVCache::visible_state (read-only dense Fp16 window) and UnifiedEmbedding::dequantized_weight (once-per-call soft-embedding table).

CLI: new diffusion flag group (--max-denoising-steps, --diffusion-sampler, --diffusion-threshold, --diffusion-min-canvas-length, --diffusion-max-canvas-length, --diffusion-full-canvas) and --seed; generate routes the family to the diffusion engine with streaming detokenization before the autoregressive loop; interactive chat rejects it with a clear one-shot hint. The server model worker rejects DiffusionGemma at load time with a clear "use the CLI" error until phase 3 lands. Image/video input remains phase 2.

* fix: cherry-pick the upstream steel GEMM safe-load fix into the MLX overlay

The pinned MLX commit (2026-05-09) carries a one-character bug in
BaseMMAFrag<T, 8, 8>::load_safe (mlx/backend/metal/kernels/steel/gemm/mma.h):
edge-tile loads index columns with off_x instead of off_y, so every
non-tile-aligned steel GEMM reads the wrong rows, and through strided views
it can read uninitialized parent-buffer regions. Upstream fixed it on
2026-05-18/19 (ml-explore/mlx PRs lablup#3560 and lablup#3565); this overlay carries the
fix until the next MLX bump and can be dropped then.

On M1-generation GPUs this corrupted the DiffusionGemma canvas SDPA fallback
(head_dim 256/512 routes around the fused kernel into steel GEMM with ragged
key lengths), nondeterministically under allocator churn. A new
steel_gemm_edge_tile_safe_load_matches_reference unit test pins a
non-tile-aligned GEMM against a composite multiply+sum reference so a future
MLX bump cannot silently reintroduce the bug.

* fix: split fused gate_up expert weights on host bytes for gather_qmm soundness

Building the gate/up halves with graph-level slice + copy produced arrays
that gather_qmm read incorrectly on the pinned MLX: with router indices,
weights, and inputs byte-identical across runs, the first expert projection
diverged run to run once the Metal buffer cache carried churn, which is what
turned every DiffusionGemma canvas denoise into nondeterministic garbage
(all 30 layers run the MoE branch). Rebuilding the same bytes into pristine
dense arrays makes the identical gather_qmm call byte-deterministic, so
split_gate_up_tensor now performs the output-axis split on host bytes
(per-expert row blocks, dtype-size aware, 16-bit dtypes through
from_bytes_f16) and evaluates the halves once at load time.

Also folds the real-model debug battery into one regression test:
real_model_forward_determinism warms the buffer cache first (the historical
failure modes only show under allocator churn) and asserts byte-determinism
of both the encoder and canvas forwards.

Verified on models/diffusiongemma-26B-A4B-it-4bit: three identical
temperature-0 runs (byte-identical commits), output matches the mlx-vlm
reference up to one near-tie whitespace token, per-step denoise time at
96-103% of the Python implementation.

* fix: commit the final-step argmax canvas in every denoise exit path

The confidence sampler's all-revealed early exit committed the revealed
draft canvas, but the reference unconditionally commits the last executed
step's argmax canvas after the loop (its draft assignment is dead code),
and the engine's other exit paths already did the same. Aligns the branch
for exact reference parity and internal consistency (pr-reviewer finding).

* fix: use total_cmp for entropy-bound sort to avoid NaN comparator

The entropy-bound acceptance mask sorted entropies with partial_cmp().unwrap_or(Equal), an inconsistent comparator when a NaN entropy is present (which modern Rust slice sorts may treat as a hard error). A NaN entropy can only arise from a degenerate temperature schedule that drives logits to inf, but the host-side acceptance path should never be able to panic on it. total_cmp is a total order with identical ordering for the finite, non-negative entropies of the normal path, and sorts NaN last so a maximally uncertain position is never accepted.

* docs: add DiffusionGemma to supported-models and a block-diffusion guide

Adds docs/block-diffusion.md with a full description of the block-diffusion generation model: canvas denoising vs autoregressive, the entropy-bound and confidence-threshold samplers, all CLI flags with defaults, throughput measurements from M1 Ultra (8-20 tok/s depending on canvas convergence, at per-step parity with the mlx-vlm reference), reproducibility via --seed, and phase 1 limitations (text-only CLI, no image input, no server mode).

Updates docs/supported-models.md to list DiffusionGemma in a new block-diffusion section with detection keys and load notes, and bumps the variant count to 93/71.

Adds MLXCEL_DIFFUSION_DEBUG_CANVAS to docs/environment-variables.md in its own diagnostic section.

Adds the block-diffusion.md entry to docs/README.md.

All existing tests pass: 23 diffusion_gemma unit tests, 117 bin tests, 10 cli_help_consistency tests, cargo fmt clean, cargo clippy clean.
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