Skip to content

[mm] sglang-mm: server vision pipeline core (fetch/driver/pipeline) + Qwen VL - #32364

Merged
hnyls2002 merged 19 commits into
mainfrom
kan/rust-mm-qwen-vl-native
Aug 4, 2026
Merged

hnyls2002 merged 19 commits into
mainfrom
kan/rust-mm-qwen-vl-native

Conversation

@sherlockwu

@sherlockwu sherlockwu commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

First of a two-PR stack letting the Rust tokenizer manager (SGLANG_RUST_SERVER=1, #29799) serve Qwen VL models with image preprocessing done entirely in Rust.

This PR is the model-semantics half: it grows rust/sglang-mm (added with Inkling, #31681) from a PyO3-only helper into an end-to-end multimodal pipeline that sglang-server links as a pure-Rust rlib. Self-contained on main; no Python runtime changes.

Stacked PR 2 (integration + NativeMmHost, based on rainj-me/rust-server): #32365

Modifications

Crate shape

Two builds from one crate, both features non-default so neither leaks through cargo's per-invocation feature unification. The rlib links no pyo3, no libpython, no rayon — zero threads, everything inline on the caller, since the server supplies concurrency across requests and pins its own cores.

Build Features Consumer
PyO3 ext sglang.srt.multimodal._core python,parallel Python processors, parity tests
Pure-Rust rlib none sglang-server MM worker

Server pipeline core

The model-independent request skeleton — see the README for the architecture and why the seam is shaped this way.

  • pipeline.rs — family seam MmFamilyProcessor (capabilities/process_item/layout/positions). Families emit NamedTensors and describe prompt geometry as a TokenLayout; positions are a scheme (Rope1D | MRope).
  • driver.rs — fetch (inline, sequential — blocking I/O never enters the CPU pool) → decode fan-out → process_item → layout → positions → Output. Owns all control flow and failure semantics, so families cannot alter accept/reject behavior. Takes a typed MmInput; the msgpack wire payload belongs to sglang-server in PR 2, so this crate needs no rmpv.
  • common/token_layout.rs — applies a layout mechanically, validating each item is placed once and that segments cover every source token exactly once.
  • common/fetch.rs — data:/base64/file/http via rustls (never system OpenSSL); honors REQUEST_TIMEOUT and the proxy vars incl. NO_PROXY; adds a 64 MiB cap.
  • common/par.rs — the crate's only fan-out seam: a rayon impl and an inline impl, bit-identical because every fan-out is an order-preserving map or a disjoint-slice write, never a reduction.

Qwen VL family

qwen_vl/ serves qwen2_vl, qwen2_5_vl, qwen3_vl, qwen3_vl_moe, qwen3_5, qwen3_5_moe as one MmFamilyProcessor: smart_resize → bicubic → LUT normalize → HF-order patchify, plus an M-RoPE scheme. pack_drain maps the generic output to today's scheduler-drain shape.

Inkling rework

A pure relocation of the PyO3 bindings into the feature-gated module (verified token-level against main), plus one deliberate change to the shared decode: decode_rgb rejects >8-bit images (e.g. 16-bit PNG) rather than silently diverging from PIL's clipping. Crate-local dev suites, stale since the Inkling merge, are repaired.

Testing

Each native component is pinned against the Python/HF component it replaces, under test/registered/unit/multimodal/rust/ (CPU CI, base-a-test-cpu) — 19 tests / 58 subtests:

Native component Python/HF counterpart Parity test
fetch::fetch_bytes srt.utils.common.get_image_bytes shared/test_fetch.py
common::decode_rgb PIL.Image.open(...).convert("RGB") shared/test_image_decode.py
qwen_vl::process_item, smart_resize HF Qwen2VLImageProcessor / …Pil; processors/qwen_vl.py::smart_resize qwen/test_preprocess.py
token_layout::{layout_by_placeholder, apply_layout} BaseMultimodalProcessor._expand_input_ids, get_mm_items_offset qwen/test_token_layout_mrope.py
qwen_vl::mrope_image_only MRotaryEmbedding.get_rope_index (4 model types) qwen/test_token_layout_mrope.py
driver::process rejection contract none — no Python fallback exists qwen/test_driver.py
_core.inkling bindings regression guard for the relocation inkling/test_bindings.py

Preprocessing parity is asserted at two strengths, since the HF processors resample differently and only one is what a server runs: bit-exact vs the PIL processor, and a measured envelope (max 0.030, mean 6.7e-5) vs the torchvision one AutoImageProcessor returns by default.

Pure-Rust core — cargo test in both feature shapes (18 tests each), since common::par has two implementations that must agree; wired into CI via the new .github/workflows/pr-test-rust-exts.yml. tests/rlib_is_single_threaded.rs asserts the rlib spawns no worker threads, via process thread count so it survives refactors of the seam.

Inkling regression — crate goldens (22 tests), the rust-vs-python integration script (8/8 bit-exact), and GPU e2e test/registered/models/test_inkling.py (4 tests) all pass against the reworked extension.

Integration-seam tests (drain adapter, scheduler-input parity) and e2e VLM runs live in the stacked PR.


CI States

Latest PR Test (Base): 🚫 Run #30884817232
Latest PR Test (Extra): ❌ Run #30884817059

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@github-actions github-actions Bot added documentation Improvements or additions to documentation dependencies Pull requests that update a dependency file labels Jul 25, 2026
sherlockwu added a commit that referenced this pull request Jul 25, 2026
Brings the stacked sglang-mm PR's review pass into this branch (env-proxy
fetch, stricter guards, suite renames, typed driver input) and completes the
payload-ownership move: parse + value_present relocate from sglang-mm to
message/mm_payload.rs, next to the to_mm_payload_msgpack encoder, so the
wire contract has one owner. The mm worker parses the payload and hands the
typed MmInput to sglang_mm::driver::process; the scheduler-input parity test
drives the typed process_native_mm binding.

Co-Authored-By: Claude Fable 5 <[email protected]>
sherlockwu added a commit that referenced this pull request Jul 25, 2026
@sherlockwu
sherlockwu force-pushed the kan/rust-mm-qwen-vl-native branch from 663a2ad to e787def Compare July 26, 2026 07:08
sherlockwu added a commit that referenced this pull request Jul 26, 2026
… shape

The crate's model-family seam is now MmFamilyProcessor (capabilities /
process_item / layout / positions) with typed carriers; the worker holds a
Box<dyn MmFamilyProcessor>, and MmResult (the qwen scheduler-drain shape,
extracted via sglang_mm::qwen_vl::pack_drain from the generic driver output)
now lives here — it generalizes to a named-tensor handoff when a family
needs a different shape. NATIVE_MM.md's add-a-family walkthrough follows the
new hooks.

Co-Authored-By: Claude Fable 5 <[email protected]>
@sherlockwu
sherlockwu force-pushed the kan/rust-mm-qwen-vl-native branch 2 times, most recently from a01e6e0 to c66ae3e Compare July 26, 2026 07:20
@sherlockwu sherlockwu changed the title [mm] sglang-mm: native vision pipeline core (fetch/payload/tokens/driver) + Qwen VL [mm] sglang-mm: server vision pipeline core (fetch/tokens/driver/pipeline) + Qwen VL Jul 26, 2026
@sherlockwu
sherlockwu force-pushed the kan/rust-mm-qwen-vl-native branch from c66ae3e to a12e597 Compare July 26, 2026 07:26
@sherlockwu
sherlockwu force-pushed the kan/rust-mm-qwen-vl-native branch from a12e597 to d8a0732 Compare July 26, 2026 07:38
@sherlockwu sherlockwu changed the title [mm] sglang-mm: server vision pipeline core (fetch/tokens/driver/pipeline) + Qwen VL [mm] sglang-mm: server vision pipeline core (fetch/driver/pipeline) + Qwen VL Jul 26, 2026
sherlockwu added a commit that referenced this pull request Jul 26, 2026
PR-boundary dedup vs the scaffold base: the shared fixture module and the
suites already reviewed on #32364 come from the base; this adds only the
integration-seam tests (scheduler-input parity, drain adapter) and the GPU
e2e/MMMU gates.

Co-Authored-By: Claude Fable 5 <[email protected]>
sherlockwu added a commit that referenced this pull request Jul 26, 2026
…ost)

test_scheduler_input_parity -> qwen/test_native_mm_host (full-driver parity
through NativeMmHost); test_drain_adapter -> shared/test_build_native_mm
(the drain method's zero-copy / precomputed-hash contracts), matching the
module-named convention of the sglang-mm suites (#32364).

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread rust/sglang-mm/src/pipeline.rs Resolved
@sherlockwu
sherlockwu force-pushed the kan/rust-mm-qwen-vl-native branch 2 times, most recently from 77ca4e4 to 5fff03a Compare July 28, 2026 06:07
@sherlockwu
sherlockwu marked this pull request as ready for review July 28, 2026 09:56
sherlockwu and others added 10 commits August 4, 2026 05:04
… flow

Reshape the model-family seam so the pipeline can eventually carry every
family the Python multimodal processors serve, not just qwen-shaped ones:

- pipeline.rs: the native-pipeline contract. MmFamilyProcessor = {capabilities, process_item,
  layout, positions}. Families emit NamedTensors (the model-kwargs analogue
  of MultimodalDataItem + model_specific_data) and describe prompt geometry
  as a TokenLayout value — Text/Media segments with Repeat or Explicit token
  patterns — instead of the driver hardwiring single-placeholder expansion.
  Positions become a scheme (Rope1D default | MRope), so M-RoPE stops being
  a mandatory hook. Each carrier is an enum that grows a variant when a real
  family needs it (DecodedMedia per modality, Geometry per family style,
  TensorData per dtype).
- tokens.rs: layout mechanics — apply_layout (validates bounds, exactly-once
  placement, nonzero spans) + layout_by_placeholder; expansion, offsets, and
  position inputs all derive from the one layout value.
- driver.rs: generic Output {input_ids, items: [{tensors, hash}], offsets,
  positions}; item hash covers all tensor buffers.
- qwen_vl: ported onto the trait (spec now carries image_token_id);
  pack_drain extracts the current qwen scheduler-drain shape from the
  generic Output — shared by the parity binding and the server worker until
  a second family forces the generic named-tensor handoff.
- README: architecture introduction (design rule, hook semantics, growth
  path, what stays in Python).

Parity surface unchanged: process_native_mm returns the same tuple; all
suites pass unmodified.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tion, I/O pool split

Review pass over the sglang-mm server pipeline.

Correctness:
- smart_resize floors without a lower clamp (as Python does), so a thin image
  against a small max_pixels could floor a side to 0. Python then fails inside
  PIL's resize; here it reached the resize coefficient math and panicked on a
  worker thread ("attempt to multiply with overflow" in debug, garbage in
  release). Reject it as a request error instead, plus a grid check before
  patchify, and pin both from Rust and across the FFI boundary.
- The `python` feature is no longer default. Cargo unifies a package's features
  across everything selected in one invocation, so a default-on `python` leaked
  pyo3 back into sglang-server's copy of the crate under `cargo build
  --workspace` despite `default-features = false`:
      before:  pyo3 -> numpy -> sglang-mm -> sglang-server
      after:   pyo3 -> sglang-grpc, sglang-server
  The wheel asks for the feature via [package.metadata.sglang] features, plumbed
  through setup.py. The pre-commit clippy hook gains a python-feature step,
  since `--workspace` no longer compiles the bindings.
- fetch honors NO_PROXY (requests semantics) via a second non-proxied agent.
  Without it, an internal image host that works on the Python path would
  silently start routing through a configured proxy.
- Blocking fetch moves to a dedicated 16-thread I/O pool, so one request's slow
  URLs can no longer occupy all 8 CPU workers and stall other requests'
  decode/resize — the split the Python processors make with
  auto_mm_io_worker_num vs auto_mm_processor_worker_num.
- apply_layout now enforces the contract it documents: text ranges must be
  ascending, non-overlapping, and jointly cover every source token exactly once.
  A family dropping a tail segment used to silently truncate the prompt.

Naming:
- sha256_u64 -> content_hash_u64 (it is blake3); the binding is `content_hash`,
  not `data_hash`, so it cannot be read as parity with mm_utils.data_hash
  (which really is SHA-256).
- common/tokens.rs -> common/token_layout.rs, after the TokenLayout it
  implements; its suite follows to test_token_layout_mrope.py.

Tests/CI:
- Image parity splits into a bit-exact assertion against the PIL processor
  (measured max diff 0.000000) and an explicit envelope against the torchvision
  processor a default server actually runs (measured max 0.030 / mean 6.7e-5).
  On transformers 5.x Qwen2VLImageProcessor is the torchvision one and
  Qwen2VLImageProcessorPil the PIL one.
- capabilities() is pinned images-only so a family gaining video cannot
  silently inherit the default; dead resize_bicubic_rgb dropped.
- test_fetch asserts the Python reference *raises* on file://, documenting the
  divergence instead of implying an omission.
- pr-test-rust-exts is scoped to rust/sglang-mm and adds test-target clippy;
  fmt and non-test clippy stay with the always-on pre-commit gate.
- _utils.py -> _mm_rust_utils.py so the sys.path helper cannot shadow another
  suite's module.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
sglang-server links this crate as a pure-Rust rlib and supplies concurrency
across requests while pinning its own cores (core_affinity), so a library that
silently spawns rayon pools behind its back fights it. Measured: one request on
the rlib build took the process from 2 threads to 26.

- rayon becomes an optional dependency behind a new non-default `parallel`
  feature, so the rlib does not link it at all (`cargo tree` shows zero rayon).
  Preprocessing runs inline on the calling thread; the server's own request-level
  parallelism is what scales. Sizing a pool to 1 would NOT be equivalent —
  `install` blocks the caller, so 4 concurrent 200ms requests take 800ms on a
  1-thread pool vs 200ms on a 4-thread one.
- Every fan-out now routes through `common::par` (try_map / try_map_io /
  for_chunks_mut / in_pool), the crate's only parallelism seam, with a rayon impl
  and an inline impl. All #[cfg] lives in that one file; the 15 former call sites
  across driver/qwen_vl/resize/inkling just call the helpers. This also removes
  the pointless nesting where the driver installed on the pool and then
  process_item/resize re-installed on the same pool.
- The wheel asks for `python,parallel`, so the PyO3 extension keeps exactly its
  previous pooling and performance (verified within 0.6% of baseline; the naive
  conversion cost ~2% by splitting one pool entry per resize into two, which
  `par::in_pool` restores).
- The I/O pool now only engages when a request actually carries a URL: a
  pre-fetched (ImageSource::Bytes) request spawned 16 idle I/O threads to fan out
  a no-op, which is precisely the shape a server hands over.

Output is bit-identical across both shapes — the fan-outs are order-preserving
maps and writes into disjoint slices, never reductions. Verified by hashing
qwen preprocess + the full driver output + inkling patchify across 5 image sizes
in both builds. `tests/rlib_is_single_threaded.rs` guards the thread count from
the outside so it survives refactors of the seam, and CI runs `cargo test` in
both shapes since the seam has two implementations that must agree.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ly fan-out

The 16-thread io pool was only ever reachable from the pyo3 test binding:
the rlib build inlines try_map_io anyway, and the server's request shape is
pre-fetched bytes. Fetch now runs sequentially inline in driver::process
(still never on the CPU pool); an I/O pool can return behind the par seam
if a consumer ever needs per-request parallel fetch.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review follow-up (mrain): the POD slice reinterpretation is exactly what
bytemuck encodes in the type system, so encode it there — no unsafe block,
no hand-written Safety argument. bytemuck adds no transitive deps to the
rlib. Also corrects the doc: the bytes are native-endian (unchanged
behavior — the old comment claimed little-endian).

Co-Authored-By: Claude Opus 5 <[email protected]>
Review suggestion on #32364: the driver hashed the feature tensor
(~50-200 MB for 1080p/4K images, 8-32 ms of blake3) where Inkling
already hashes the raw encoded source (~0.5-2 MB, <0.5 ms). Source
bytes are an equivalent identity — processing is deterministic — so
hash them instead, unifying the crate's two conventions.

TensorData::as_bytes loses its only caller; remove it and the bytemuck
dependency that existed solely for it.

Co-Authored-By: Claude Fable 5 <[email protected]>
…, webp/gif/bmp

- fetch: bounded reads for files (a /dev/zero path can no longer exhaust
  memory) and an encoded-length pre-check for base64; the 64 MiB cap now
  covers every owned-byte source, not just HTTP.
- driver: per-request budgets (64 items, 256 MiB aggregate) and an explicit
  contract comment — string sources resolve inline, fixed-pool callers must
  prefetch on their own I/O layer and pass Bytes.
- NO_PROXY: match IPv4 CIDR and host:port entries as requests does.
- image: enable webp/gif/bmp (pure-Rust decoders); 16-bit stays rejected.
- README: item hash is over raw source bytes; document the fetch contract,
  caps, and format coverage.
- tests: /dev/zero cap, oversized base64, cidr/port matching, per-request
  caps, new-format decode, and http-URL/file:///bare-path sources through
  the full driver pipeline against a local one-shot HTTP server.

Co-Authored-By: Claude Fable 5 <[email protected]>
File paths block a worker just like URLs — worse on a hanging network
mount, which has no timeout. State the contract as: fixed-pool callers
resolve URLs and file paths off-worker; data:/base64 stay (pure CPU).

Co-Authored-By: Claude Fable 5 <[email protected]>
…ment

The review-fix commit widened the native decoder but the registered
suites still asserted the old reject contract, failing base-a-test-cpu.
GIF now pins the accept side through the full driver pipeline; gif/bmp/
lossless-webp join the PIL parity assertions at zero tolerance; corrupt
bytes and >8-bit depths keep the reject coverage.

Co-Authored-By: Claude Fable 5 <[email protected]>
@sherlockwu
sherlockwu force-pushed the kan/rust-mm-qwen-vl-native branch from f65867d to 0d6d09c Compare August 4, 2026 05:10
@sherlockwu sherlockwu added run-ci-extra CI: also run the extra suite (requires run-ci) and removed run-ci-extra CI: also run the extra suite (requires run-ci) labels Aug 4, 2026
sherlockwu added a commit that referenced this pull request Aug 4, 2026
PR-boundary dedup vs the scaffold base: the shared fixture module and the
suites already reviewed on #32364 come from the base; this adds only the
integration-seam tests (scheduler-input parity, drain adapter) and the GPU
e2e/MMMU gates.

Co-Authored-By: Claude Fable 5 <[email protected]>
sherlockwu added a commit that referenced this pull request Aug 4, 2026
…ost)

test_scheduler_input_parity -> qwen/test_native_mm_host (full-driver parity
through NativeMmHost); test_drain_adapter -> shared/test_build_native_mm
(the drain method's zero-copy / precomputed-hash contracts), matching the
module-named convention of the sglang-mm suites (#32364).

Co-Authored-By: Claude Fable 5 <[email protected]>
@hnyls2002
hnyls2002 merged commit 17d1908 into main Aug 4, 2026
137 of 175 checks passed
@hnyls2002
hnyls2002 deleted the kan/rust-mm-qwen-vl-native branch August 4, 2026 07:47
sherlockwu added a commit that referenced this pull request Aug 4, 2026
PR-boundary dedup vs the scaffold base: the shared fixture module and the
suites already reviewed on #32364 come from the base; this adds only the
integration-seam tests (scheduler-input parity, drain adapter) and the GPU
e2e/MMMU gates.

Co-Authored-By: Claude Fable 5 <[email protected]>
sherlockwu added a commit that referenced this pull request Aug 4, 2026
…ost)

test_scheduler_input_parity -> qwen/test_native_mm_host (full-driver parity
through NativeMmHost); test_drain_adapter -> shared/test_build_native_mm
(the drain method's zero-copy / precomputed-hash contracts), matching the
module-named convention of the sglang-mm suites (#32364).

Co-Authored-By: Claude Fable 5 <[email protected]>
sherlockwu added a commit that referenced this pull request Aug 4, 2026
PR-boundary dedup vs the scaffold base: the shared fixture module and the
suites already reviewed on #32364 come from the base; this adds only the
integration-seam tests (scheduler-input parity, drain adapter) and the GPU
e2e/MMMU gates.

Co-Authored-By: Claude Fable 5 <[email protected]>
sherlockwu added a commit that referenced this pull request Aug 4, 2026
…ost)

test_scheduler_input_parity -> qwen/test_native_mm_host (full-driver parity
through NativeMmHost); test_drain_adapter -> shared/test_build_native_mm
(the drain method's zero-copy / precomputed-hash contracts), matching the
module-named convention of the sglang-mm suites (#32364).

Co-Authored-By: Claude Fable 5 <[email protected]>
sherlockwu added a commit that referenced this pull request Aug 5, 2026
PR-boundary dedup vs the scaffold base: the shared fixture module and the
suites already reviewed on #32364 come from the base; this adds only the
integration-seam tests (scheduler-input parity, drain adapter) and the GPU
e2e/MMMU gates.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bypass-fastfail dependencies Pull requests that update a dependency file documentation Improvements or additions to documentation high priority Multi-modal multi-modal language model run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants