Repository navigation
feat: DiffusionGemma block-diffusion text generation (phase 1 of #217) - #218
Conversation
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.
…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.
Implementation Review SummaryIntentPhase 1 of #217: text-only DiffusionGemma block-diffusion generation wired into the CLI Verification (independent review + targeted build/tests)
Findings
Remaining Items
|
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.
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)
Verified safe
Note (no action required now)
|
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.
PR finalization completeTestsAll 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)
Lint/format
|
|
Throughput comparison on the same 26B-A4B backbone (M1 Ultra, 4-bit, temperature 0, identical long-form prompt, 2 runs each):
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. |
|
dLLM throughput tuning sweep (same backbone comparison continued; M1 Ultra, 4-bit, temp 0, 512-token essay prompt, 2 runs each):
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. |
…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.
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 CLIgenerateflow. 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. Fusedexperts.gate_up_projtensors 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.diffusion_gemma/generate.rs): mirrors mlx-vlmstream_diffusion_generatefor batch-1 dynamic-cache generation: per-block canvas sizingmin(max_canvas, max(remaining, min_canvas)), uniform-random canvas init, linear temperature schedulet_min..t_maxover 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 printsDIFFUSION_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_branchextraction reused verbatim byforward_with_profile, newDecoderLayer::forward_encoder_with_scalar, newDecoderLayer::forward_canvas, newAttention::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_idswidened to pub(crate).src/lib/mlxcel-core/src/cache.rs: read-onlyKVCache::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.ModelType::DiffusionGemmakeyed ondiffusion_gemma/diffusion_gemma_textin detection, nonstandard directory loader,LoadedModel::DiffusionGemmavariant + delegate arm, metadata/arch entries, TP planner placeholder arm. TheLanguageModelimpl is honest but minimal: encoder forward + norm + tied logits, dense Fp16make_caches,supports_batching() = false.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_onceroutesLoadedModel::DiffusionGemmato the newgenerate_diffusiondriver (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.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 forcedattention_k_eq_v/enable_moe_blockflags, 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 --testsandcargo check --binscargo clippy --lib --tests -- -D warningsandcargo clippy --bins -- -D warningscargo fmtcargo test --test cli_help_consistencyandcargo 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:
Upstream MLX steel GEMM safe-load typo (cherry-picked overlay). The pinned MLX commit (2026-05-09) indexes edge-tile columns with
off_xinstead ofoff_yinBaseMMAFrag<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 aspatches/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.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_qmmdiverged run to run when the gate/up tensors came fromslice+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_tensornow splits on host bytes (per-expert row blocks, dtype-size aware, 16-bit dtypes throughfrom_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_COMPILEunchanged 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)
real_model_forward_determinismregression test (with buffer-cache warmup, since the historical failure modes only appear under allocator churn) asserts byte-determinism of encoder and canvas forwards.