Skip to content

feat: serve DiffusionGemma block diffusion in mlxcel-server (phase 3 of #217) - #220

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

inureyes merged 5 commits into
mainfrom
feat/issue-217-diffusion-gemma-server

Conversation

@inureyes

@inureyes inureyes commented Jun 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 3 (final) of #217: a dedicated single-stream (batch-1) serving path for DiffusionGemma inside the existing model worker thread. DiffusionGemma generates by model-owned block diffusion (supports_batching() == false) and cannot join the BatchScheduler, so the worker loads the model normally and, when it is a DiffusionGemma checkpoint, branches into a new block-diffusion serving loop instead of constructing the scheduler. The loop serves /v1/chat/completions and /v1/completions for text and image requests, both streaming (SSE) and non-streaming, with request cancellation and accurate usage stats. Requests queue on the existing mpsc channel and are served serially: that is the design (no in-flight concurrency > 1).

What changed

  • src/server/diffusion_worker.rs (new): the batch-1 worker loop (run_diffusion_worker_loop) plus the testable pure helpers it uses (diffusion_options_from_server / build_diffusion_options for server-to-engine option mapping, reject_audio_video, parse_diffusion_sampler, and diffusion_finish_reason_str). The loop tokenizes the already chat-templated prompt, optionally runs the phase-2 vision prefill, denoises through generate_diffusion_streaming, streams each committed token via the server's incremental detokenizer (StreamingDecodeState), polls the cancellation flag in the engine callback, and emits a final Done with real usage/timings and a mapped finish reason. One bad request emits Error and the loop keeps serving.
  • src/server/model_worker.rs: removed the load-time rejection helper server_unsupported_model_error and both its call sites; the batched and legacy (--no-batch) workers now branch into the diffusion loop after the model loads. Added the three serve-level diffusion fields to WorkerSchedulerConfig.
  • src/models/diffusion_gemma/mod.rs: extracted the CLI vision-prep into shared DiffusionGemmaModel::prepare_image_prompt / build_image_processor (+ PreparedDiffusionImagePrompt), and re-exported DiffusionFinishReason. The CLI generate driver (src/commands/generate_diffusion.rs) now delegates to this helper and keeps working identically.
  • Serve-level flags --max-denoising-steps, --diffusion-sampler, --diffusion-threshold threaded from ServeArgs (new DiffusionServeOptions group) and the mlxcel-server binary through ServerStartupInput -> ServerStartupConfig -> ServerConfig -> WorkerSchedulerConfig -> the worker loop. Help text documents that they only affect diffusion models.

Options mapping (server -> engine)

server param engine option
options.max_tokens max_new_tokens
options.sampling.temperature temperature
--diffusion-sampler sampler
--diffusion-threshold confidence_threshold
--max-denoising-steps max_denoising_steps
options.sampling.stop_token_ids + config EOS (deduped) extra_eos_token_ids
options.sampling.seed mlxcel_core::random_seed(seed) before generation
(not exposed at serve level) min/max canvas, full_canvas, prefill_chunk_size keep engine defaults

Limitations (documented)

  • No in-flight concurrency > 1: requests are served serially off the shared channel (by design).
  • Audio/video requests are rejected per-request with a clear Error event.
  • Logprobs are not produced (served without them); the diffusion engine has no per-token logprob surface.
  • Finish reason maps to the server's existing strings: Length -> "length", Stop -> "stop", Aborted -> "stop" (the server response surface has no distinct cancelled-reason string).
  • Scheduler-specific endpoints (cache stats, batch metrics) degrade to empty/zero for the diffusion worker; GET /v1/models and health endpoints are unchanged.

Test plan

  • cargo fmt
  • cargo check --lib --tests --bins --features metal,accelerate
  • cargo clippy --lib --tests --bins --features metal,accelerate -- -D warnings
  • cargo test --lib --features metal,accelerate server::diffusion_worker (7 passed: options mapping, EOS union/dedup, audio/video rejection, sampler parse, finish-reason mapping, defaults)
  • cargo test --lib --features metal,accelerate models::diffusion_gemma (32 passed, no regressions)
  • cargo test --lib --features metal,accelerate server::cli_input and cargo test --bin mlxcel ... serve and cargo test --bin mlxcel-server (config threading + arg parsing green)
  • Live-server E2E on models/diffusiongemma-26B-A4B-it-4bit (orchestrator runs this; see Real-model verification below)

Real-model verification (phase 3)

Live server on models/diffusiongemma-26B-A4B-it-4bit:

  • GET /v1/models returns the model entry correctly.
  • Chat completions non-streaming: reasoning to content channel transition confirmed, finish_reason: stop, usage token counts correct.
  • Chat completions streaming (SSE): delta.reasoning_content carries the thinking channel; delta.content carries the final reply; finish_reason: stop on the closing chunk; usage counts match non-streaming.
  • Base64 image_url request: 256 soft tokens expanded, model answered "a red square and a blue circle" correctly.
  • Serve-level flags: --diffusion-sampler confidence-threshold --diffusion-threshold 0.6 verified effective (178 tokens generated in 7.8 s wall clock).
  • POST /v1/completions: mechanical-OK; raw un-templated prompts degrade as documented (the model depends on its chat structure), so chat completions are the recommended path.
  • CLI deterministic text regression: output byte-identical across all three phases (md5 c38559cc).

Closes #217

Phase 3 of issue #217: a dedicated single-stream (batch-1) serving path for DiffusionGemma inside the existing model worker thread. The worker now loads the model normally and, when the loaded model is DiffusionGemma, branches into a new block-diffusion serving loop instead of constructing the BatchScheduler (DiffusionGemma is model-owned and supports_batching() == false). The loop serves /v1/chat/completions and /v1/completions for text and image requests with SSE streaming and non-streaming, request cancellation, and accurate usage stats; audio/video requests are rejected per-request with a clear error. Requests queue on the existing mpsc channel and are served serially by design.

Key changes: new src/server/diffusion_worker.rs (worker loop + server->engine options mapping + audio/video rejection + sampler parsing + finish-reason mapping); the CLI vision-prep path moved into DiffusionGemmaModel::prepare_image_prompt / build_image_processor so the CLI generate driver and the server worker share one image path; the load-time rejection helper (server_unsupported_model_error) and its call sites were removed; three serve-level diffusion flags (--max-denoising-steps, --diffusion-sampler, --diffusion-threshold) were threaded from ServeArgs / the mlxcel-server binary through ServerStartupInput, ServerStartupConfig, ServerConfig, and WorkerSchedulerConfig to the worker loop. Both the batched and legacy (--no-batch) workers branch to the diffusion loop.
@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

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Phase 3 (final) of #217: serve DiffusionGemma block-diffusion in mlxcel-server via a dedicated single-stream (batch-1) worker loop, with serve-level diffusion flags threaded through, while leaving autoregressive serving byte-identical.

Findings Addressed

None requiring changes. Implementation is correct, complete, and well integrated.

Verification

  • All stated requirements implemented: diffusion worker loop, options mapping, flag threading, model_worker branching, CLI vision refactor all present and functional
  • No placeholder/mock code remaining
  • Integrated into project code flow: both spawn paths (spawn_model_worker_with_batch_config + spawn_legacy_model_worker) branch into run_diffusion_worker_loop after load; flags thread ServeArgs.diffusion -> ServerStartupInput -> ServerStartupConfig -> ServerConfig -> WorkerSchedulerConfig -> worker, plus the standalone mlx_server binary
  • Project conventions followed: pure helpers split out for unit testing, doc comments, no em dashes, Apache headers
  • Existing modules reused: StreamingDecodeState, decode_request_images, build_generation_result_with_cache, shared prepare_image_prompt
  • No unintended structural changes: the AR path is preserved byte-identical (match model { DiffusionGemma => {...; return}, other => other } rebinds the same value for every non-diffusion variant; the removed server_unsupported_model_error had no other callers)
  • Tests pass

Detail

  • Regression surface (model_worker.rs): the match/return restructuring keeps the existing flow unchanged for AR models. model is rebound to the identical value; nothing between load and the branch consumes it differently. config_eos is read before the branch and passed through. Verified.
  • GenerateEvent sequencing: every path emits exactly one terminal event. Early failures (audio/video, tokenize, image decode, no-vision, empty prompt) send a single Error. Success streams Tokens then one Done. A mid-run engine Err yields Tokens then one Error. Send failures to a gone receiver are harmless.
  • Cancellation: the callback polls cancelled even when the byte-fallback decoder emits no text this token, and aborts on a closed receiver. Granularity is per committed token (block boundary), which is the engine's natural unit.
  • Stats accuracy: completion_tokens counts actually-streamed tokens (incremented in on_token), prompt_tokens = engine_prompt.len() (post image-expansion), timing from first_token_time/start. The build_generation_result finish_reason is overridden with the diffusion engine verdict.
  • Options mapping: max_tokens/temperature/sampler/threshold/max_denoising_steps map correctly; extra_eos_token_ids is the dedup union of request stop ids then config EOS (engine unions embedded EOS on top); seed applied via random_seed before generation. Serve default threshold 0.9 is in the engine-validated [0,1] range and only used by the confidence-threshold sampler.
  • CLI refactor: prepare_image_prompt/build_image_processor moved onto DiffusionGemmaModel; generate_diffusion.rs delegates and prints the same output. Behavior unchanged.

Checks run (no real model / no server, per constraints)

  • cargo check --lib --tests --bins --features metal,accelerate: clean
  • cargo clippy --lib --tests --features metal,accelerate -- -D warnings: clean
  • cargo test --lib server::diffusion_worker: 7 passed
  • cargo test --lib models::diffusion_gemma: 32 passed (2 ignored real-model)
  • cargo test --lib server::cli_input: 93 passed
  • cargo test --bin mlxcel serve: 13 passed

Non-blocking observations (no change made)

  • The legacy --no-batch worker uses DiffusionServeDefaults::default() and ignores the serve-level diffusion flags. This is documented in the code comment and is an intentional limitation.
  • --diffusion-threshold is not range-validated at the CLI layer; an out-of-range value surfaces as a per-request Error only when a confidence-threshold request arrives. The default is valid, so this is a minor UX nit, not a defect.

inureyes added 2 commits June 12, 2026 00:04
The confidence threshold was only checked inside the engine per request,
so an out-of-range serve-level value surfaced as a per-request error under
the confidence sampler instead of failing fast at startup. Both binaries
now reject it at parse time (pr-reviewer observation).
…nterval

The phase-3 diffusion serving change inserted parse_unit_interval (and its doc comment) directly between the top-level mlxcel-server doc block and the #[derive(Parser)] Cli struct. With no blank line or intervening item, the whole doc block (the "Usage modes" long help) merged onto parse_unit_interval and detached from Cli, so the binary lost its long --help text, and clippy's doc_lazy_continuation fired on the merged comment under --tests --bins.

Move parse_unit_interval below the Cli struct (matching the placement in src/main.rs) so the doc comment re-attaches to Cli. Behavior of the parser itself is unchanged.
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review (network-facing surface)

Reviewed the phase-3 diffusion serving path with a focus on untrusted request fields, DoS/queue behaviour, channel hygiene, AR-model regression vectors, and per-request overhead. Net result: one fixed regression, two non-blocking observations, no CRITICAL/HIGH.

Fixed (committed 4f96efe6f)

  • MEDIUM (regression): the new parse_unit_interval and its doc comment were inserted in src/bin/mlx_server.rs directly between the top-level doc block and the #[derive(Parser)] Cli struct. With no intervening item the whole "Usage modes" long-help block merged onto the function and detached from Cli, so mlxcel-server --help lost its long help, and clippy doc_lazy_continuation failed under --tests --bins. Moved the function below Cli (matching src/main.rs); parser behaviour unchanged. Warm clippy --lib --tests --bins and the server::diffusion_worker / models::diffusion_gemma suites are green.

Verified safe (no action)

  • Image decode bombs: decode_request_images applies the shared current_image_input_limits() (max alloc 512 MiB, max dims, payload/count caps) identical to the AR VLM path. No bypass.
  • max_tokens / request size: the AR path itself does not clamp max_tokens upward (overrides.max_tokens.unwrap_or(default)); the diffusion loop bounds work by max_new_tokens the same way. No new uncapped vector and no AR cap is bypassed.
  • Channel hygiene: every response_tx.send is let _ =; a dropped receiver makes the streaming callback return false, which aborts the denoise loop cleanly. No panic/wedge on client disconnect.
  • Shutdown / loaded flag: ModelRequest::Shutdown breaks the loop, channel close ends it; loaded.store(true) runs before both the batched and legacy diffusion branches, so readiness is still signalled. The non-diffusion match { other => other } rebind is behaviour-neutral for AR models.
  • Per-request error paths: all failure paths emit a single Error and continue. No catch_unwind exists anywhere in the worker layer today, so the diffusion loop correctly matches existing behaviour (an engine panic kills the worker thread regardless of model type).
  • Usage accounting: completion_tokens is counted in StreamingDecodeState::on_token for every streamed token; EOS is not streamed/counted (standard). Prompt count uses the expanded (image-inclusive) prompt. Finish reason is overridden by the engine verdict.
  • Memory: the ~1.4 GiB dequantized embedding table is built once per generate call (not per step) and clear_memory_cache() runs after each request and between blocks.

Non-blocking observations (no fix; design-level follow-ups)

  • MEDIUM — cancellation granularity: the cancel flag and client-disconnect are polled only per committed token, i.e. at block boundaries. denoise_block takes no cancel hook, so a cancelled request still finishes its current block (up to max_denoising_steps, default 48, forward passes over a 256-token canvas) before stopping. Bounded and consistent with the documented "no in-flight concurrency > 1" design, but on a 26B MoE that is a few seconds of wasted GPU work after cancel. Optional follow-up: thread a lightweight cancel poll into the denoise step loop.
  • LOW — per-request processor rebuild: prepare_image_prompt -> build_image_processor re-reads and parses processor_config.json from disk on every image request. Negligible next to the diffusion forward passes; could be cached on the model if image throughput ever matters.

No merge performed.

inureyes added 2 commits June 12, 2026 00:14
A cancelled or disconnected server request previously kept denoising until
the current block finished (up to max_denoising_steps forwards over a
256-token canvas, roughly 30 seconds), because the engine only honored the
callback verdict between committed tokens. DiffusionGenerateOptions gains
an optional cancel flag the server worker wires to its request cancellation
AtomicBool; the denoise loop polls it at every step so an abort lands
within one forward pass. The aborted partial block is never emitted. The
CLI passes no flag and is unchanged (pr-security-checker observation).
Add a "Server mode" section to block-diffusion.md covering mlxcel-server usage, the three serve-level flags (--diffusion-sampler, --diffusion-threshold, --max-denoising-steps), image_url support, and operational caveats (thinking channel, max_tokens budget, streaming vs non-streaming reasoning, /v1/completions raw-prompt degradation, cancellation resolution). Remove "server mode not yet supported" from the limitations section; retain only the TP placeholder caveat. Update the DiffusionGemma row in supported-models.md from "Server mode is not yet supported" to note serial batch-1 serving via /v1/chat/completions and /v1/completions.
@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 11, 2026
@inureyes
inureyes merged commit e099821 into main Jun 11, 2026
4 checks passed
@inureyes
inureyes deleted the feat/issue-217-diffusion-gemma-server branch June 11, 2026 15:33
@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
lablup#217) (lablup#220)

* feat: serve DiffusionGemma block diffusion in mlxcel-server (lablup#217)

Phase 3 of issue lablup#217: a dedicated single-stream (batch-1) serving path for DiffusionGemma inside the existing model worker thread. The worker now loads the model normally and, when the loaded model is DiffusionGemma, branches into a new block-diffusion serving loop instead of constructing the BatchScheduler (DiffusionGemma is model-owned and supports_batching() == false). The loop serves /v1/chat/completions and /v1/completions for text and image requests with SSE streaming and non-streaming, request cancellation, and accurate usage stats; audio/video requests are rejected per-request with a clear error. Requests queue on the existing mpsc channel and are served serially by design.

Key changes: new src/server/diffusion_worker.rs (worker loop + server->engine options mapping + audio/video rejection + sampler parsing + finish-reason mapping); the CLI vision-prep path moved into DiffusionGemmaModel::prepare_image_prompt / build_image_processor so the CLI generate driver and the server worker share one image path; the load-time rejection helper (server_unsupported_model_error) and its call sites were removed; three serve-level diffusion flags (--max-denoising-steps, --diffusion-sampler, --diffusion-threshold) were threaded from ServeArgs / the mlxcel-server binary through ServerStartupInput, ServerStartupConfig, ServerConfig, and WorkerSchedulerConfig to the worker loop. Both the batched and legacy (--no-batch) workers branch to the diffusion loop.

* fix: validate --diffusion-threshold to [0, 1] at argument parse time

The confidence threshold was only checked inside the engine per request,
so an out-of-range serve-level value surfaced as a per-request error under
the confidence sampler instead of failing fast at startup. Both binaries
now reject it at parse time (pr-reviewer observation).

* fix: restore mlxcel-server Cli long-help doc detached by parse_unit_interval

The phase-3 diffusion serving change inserted parse_unit_interval (and its doc comment) directly between the top-level mlxcel-server doc block and the #[derive(Parser)] Cli struct. With no blank line or intervening item, the whole doc block (the "Usage modes" long help) merged onto parse_unit_interval and detached from Cli, so the binary lost its long --help text, and clippy's doc_lazy_continuation fired on the merged comment under --tests --bins.

Move parse_unit_interval below the Cli struct (matching the placement in src/main.rs) so the doc comment re-attaches to Cli. Behavior of the parser itself is unchanged.

* perf: poll the cancellation flag once per denoising step

A cancelled or disconnected server request previously kept denoising until
the current block finished (up to max_denoising_steps forwards over a
256-token canvas, roughly 30 seconds), because the engine only honored the
callback verdict between committed tokens. DiffusionGenerateOptions gains
an optional cancel flag the server worker wires to its request cancellation
AtomicBool; the denoise loop polls it at every step so an abort lands
within one forward pass. The aborted partial block is never emitted. The
CLI passes no flag and is unchanged (pr-security-checker observation).

* docs: document DiffusionGemma server mode (phase 3 of lablup#217)

Add a "Server mode" section to block-diffusion.md covering mlxcel-server usage, the three serve-level flags (--diffusion-sampler, --diffusion-threshold, --max-denoising-steps), image_url support, and operational caveats (thinking channel, max_tokens budget, streaming vs non-streaming reasoning, /v1/completions raw-prompt degradation, cancellation resolution). Remove "server mode not yet supported" from the limitations section; retain only the TP placeholder caveat. Update the DiffusionGemma row in supported-models.md from "Server mode is not yet supported" to note serial batch-1 serving via /v1/chat/completions and /v1/completions.
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.

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

1 participant