Repository navigation
feat: add native linear-attention batched decode - #2686
Merged
Merged
Conversation
Add native model-owned batched decode for Qwen3-Next, Qwen 3.5, Bailing Linear, Kimi Linear, and Kimi K3. Reuse shared recurrent-state stacking, preserve per-row attention and MRoPE semantics, and delegate VLM wrappers through their text towers. Add strict isolation, mixed-state, paged-accounting, and capability regression coverage.
Qwen3.5 keeps gated-delta recurrence in model-owned state, so its paged shadow must reserve blocks only for full-attention K/V. Report zero length for recurrent layers and pin the hybrid test expectation to the real `[GDN, attention]` layout. Validated with the 14 batched-decode coverage tests, focused Qwen3.5 test compilation, scoped clippy, and formatting. Refs #2572
Member
Author
Implementation Review SummaryIntent
Findings Addressed
Verification
Remaining Items
|
Member
Author
|
Security and performance review complete.
Real-checkpoint throughput and output-equivalence measurements remain part of the parent epic benchmark gate. |
Member
Author
|
PR finalization complete.
The parent epic workflow retains the release build, real-checkpoint parity, storage-backend measurements, integrated suite, and benchmark evidence gates before merge. |
Record explicit decode storage selection and driver identity, preserve original runtime manifests through repeated archival, and distinguish active listeners from closed TCP connections when reserving benchmark ports. Ten focused CPU tests pass, including metadata byte preservation and occupied-port rejection. Refs #2574.
Archive six configurations across four checkpoints, Qwen3.5 text/image replay, release provenance and bilingual reports. Retain Ring-mini's production decided-position disagreement and a separate unfused diagnostic; disclose the baseline and candidate VLM reasoning drift. All B1 text and image trace rows match baseline exactly, all serving ladders succeed, and focused coverage tests pass. Combined workspace verification follows sibling integration. Refs #2572 and #2574.
inureyes
marked this pull request as ready for review
October 27, 2026 12:08
inureyes
added a commit
that referenced
this pull request
Oct 27, 2026
Mamba1/Falcon-Mamba, Jamba, LFM2/LFM2-MoE, RecurrentGemma and RWKV7 now decode independent sequence state in native batches. LFM2-VL delegates to its tower, including atomic rejection of non-ID multi-row calls. Scalar routing, mixed-state fallback, recurrent ownership and paged attention accounting are preserved. Four real checkpoints retain byte-identical B1 greedy text and all 256 recorded B1 trace rows. Metal concurrency-four aggregate throughput improves 2.22–3.27x; B4 has zero decided-position disagreements. LFM2-VL matches all three full solo/concurrent messages. RecurrentGemma and RWKV7 have synthetic coverage only. Results, raw traces, serving ladders, exact VLM inputs and runtime hashes are recorded in [the benchmark summary](https://github.com/lablup/mlxcel/blob/main/benchmarks/epic-2574/README.md), with bilingual reports under `TECHNICAL_REPORTS/2685-*`. A VLM replay runner makes the workload reproducible. The remaining class D clamp reasons are documented. Implementation/security reviews, focused Metal regressions, typecheck, scoped clippy and formatting pass. Benchmark tools pass 18 CPU tests and evidence hashes are verified. After integration with #2686, the complete workspace suite passes 14,251 tests with zero failures and 457 ignored; full workspace Clippy and formatting also pass. Two Metal tests needed a shared default-device lock to avoid parallel CPU-test interference; production runtime is unchanged. Measurements identify their actual source revisions separately from later wrapper/test/documentation changes. Closes #2573
This was referenced Oct 27, 2026
inureyes
added a commit
that referenced
this pull request
Oct 27, 2026
…AD (#2684) ## Summary Every frame on an authenticated cluster connection is now encrypted and authenticated with AES-256-GCM under per-connection keys derived from the handshake (HKDF-SHA256, IKM = cluster secret, salt = client nonce || server nonce, info `mlxcel-cluster-frame-v1/<channel>/{c2s,s2c}`, where the channel label separates the transport core from the stage-assignment channel), with an implicit per-direction 64-bit sequence as the nonce (never sent, never wraps) and the clear `kind || len` header as associated data, so an oversize frame is refused before any decryption. A frame that fails to open closes the connection and is logged through the handshake rate limiter without payload bytes. Handshake `PROTOCOL_VERSION` is 3 (suite byte in both authenticated hellos; a suite mismatch gets an explicit rejection record). Nothing new to configure: the existing secret sources are the only input and there is no opt-out; `TcpTransportConfig::frame_suite` exists only so the benchmark can measure the alternatives. Protected channels: pooled outbound connections, `send`, `send_stream`, RPC requests and responses, the inbound reader (one `ProtectedStream` path, no second framing copy), the Thunderbolt and RDMA wrappers and the disaggregated router, prefill and decode roles through the shared TCP core, and the `--pp-auto` stage assignment channel (now `Control` frames of the same codec instead of its own u32 + JSON frames). RDMA has no data path that bypasses the TCP core. The assignment channel uses `client_handshake_on`/`server_handshake_on` with `FrameChannel::Assignment`, so its keys differ from transport keys even under the same secret; `client_handshake`/`server_handshake` keep their signatures and use `FrameChannel::Transport`. Residuals: an on-path attacker can still drop or delay frames, and frame lengths, kinds and timing stay visible; a member holding the secret is a full member; a frame within `max_frame_size` (256 MiB by default) is allocated and read before its tag is checked, which only an authenticated peer can reach (same allocation as main). Pre-existing on main and unchanged here: the TCP `rpc_call` reply is written back on the pooled outbound stream, which nothing reads. ## Measurements (loopback, GB10 spark-102, quiet box, 2026-10-27) One-way latency = half the round trip of a `TensorData` message echoed over a second authenticated connection (both ends' frame work included); `cargo test --test cluster_frame_bench -- --ignored --nocapture`. | Mode | 8 KiB p50/p95/p99 | 64 KiB p50/p95/p99 | 1 MiB p50 | 2 MiB p50 | 16 MiB p50/p95/p99 | |------|-------------------|--------------------|----------:|----------:|--------------------| | unprotected (main) | 5.5 / 5.6 / 6.2 us | 11.1 / 11.2 / 12.0 us | 411 us | 1.040 ms | 16.39 / 16.52 / 16.62 ms | | 1: HMAC-SHA256 | 12.2 / 12.4 / 12.9 us | 64.1 / 64.8 / 65.3 us | 1.008 ms | 2.115 ms | 27.22 / 27.56 / 28.29 ms | | 2: AES-256-GCM (chosen) | 7.4 / 7.6 / 8.2 us | 27.4 / 27.9 / 28.5 us | 422 us | 0.926 ms | 17.93 / 18.09 / 18.38 ms | | 2: ChaCha20-Poly1305 | 14.0 / 14.4 / 14.9 us | 75.4 / 76.2 / 76.8 us | 1.192 ms | 2.479 ms | 30.16 / 30.55 / 30.65 ms | | two-node link (Thunderbolt / 10-25 GbE) | not measured on this run | not measured on this run | not measured | not measured | not measured on this run | Full p95/p99 for every row are in docs/distributed.md. The 1 and 2 MiB rows bracket the JSON-encoded per-token logits reply; there AES-256-GCM is inside loopback noise of the unprotected rows while HMAC-SHA256 adds 0.6 and 1.2 ms per one-way transfer. ## Attribution of the first e2e result The first interleaved run (5 rounds) showed -11 percent (71.3 vs 63.5 tok/s). Attribution with throwaway instrumentation (not committed): - Frame trace of one bench run (8 repeats, 1032 forward steps): 4196 frames, 4 per decoded token: a 275-byte `RunEntry`, a 7.5 KB forward activation (hidden state, JSON), and two frames of about 1.1 MB each, because the final stage returns the logits to the entry stage as a reverse activation and the entry stage forwards them to the coordinator as `RunResult`. Both carry 304 KB of f16 logits as a JSON array of numbers (3.6 characters per byte), so 2.2 MB per token were sealed and opened. - In-process AES-256-GCM on a 2.2 MB buffer: seal 275 us + open 268 us = 0.54 ms per token (HMAC-SHA256: 1.77 ms). Predicted cost about 4 percent of a 14 ms step. - Framing-only variant (`ProtectedStream` with a null codec, same handshake and plumbing) interleaved with main and the protected branch, 3 rounds: main 69.1 (65.8 to 73.4), protected 65.6 (56.1 to 66.0), framing-only 63.5 (61.1 to 66.1) tok/s. Framing-only is not faster than protected, so the plumbing costs nothing measurable and the remaining gap beyond the AEAD cost is run-to-run noise on this box (main itself spans 66 to 75 across rounds). A main-HEAD baseline rebuilt with the exact flags produced the orchestrator's binary hash, ruling out a build-flag difference. ## Final end-to-end decode (qwen3-0.6b-4bit, two stages, 128 tokens, 7 repeats + warm-up, 5 interleaved rounds, quiet GB10) | Binary | Median of medians | Per-run medians | |--------|------------------:|-----------------| | main 4144ecf, unprotected, array-encoded tensors (orchestrator build) | 68.3 tok/s | 72.7, 67.9, 68.3, 65.4, 72.5 | | main cfa14e7 (HEAD), unprotected, same flags | 68.7 tok/s | 69.5, 69.7, 68.2, 68.7, 60.7 | | branch, compact tensors, codec disabled (throwaway, attribution only) | 138.8 tok/s | 138.8, 138.2, 146.7, 141.6, 136.5 | | branch final: compact tensors, AES-256-GCM | 133.2 tok/s | 141.0, 122.2, 126.2, 133.2, 145.1 | Against the main baseline the combined change is +94 percent, but most of that gain comes from the compact tensor encoding, not from protection, so the protection-only delta is reported separately: compact unprotected vs compact protected is -4.0 percent of a 7.3 ms step (about 0.3 ms per token for two 405 KB frames), with overlapping spreads. Judged on protection alone that is above 2 percent, but the rule's fallback (HMAC-SHA256) is slower than AES-256-GCM at every payload size, so it would cost more throughput and give up confidentiality; no opt-out was added. Decision: AES-256-GCM, no opt-out. This deviates from the rule's 2 percent clause read on protection alone (see above), because the rule's fallback is slower at every size. At 8 KiB it is 4.8 us faster than the HMAC candidate and 1.9 us above the unprotected baseline (inside the 20 us / 5 percent clause), it is the cheapest candidate at every payload size (HMAC-SHA256 costs 0.6 and 1.2 ms more per 1 and 2 MiB transfer, ChaCha20-Poly1305 0.8 and 1.4 ms), and end-to-end decode against main improves. Candidate 3 (TLS 1.3 via tokio-rustls with an exporter-bound handshake) was not prototyped: its record layer runs the same AEAD primitives plus 16 KiB record framing, a second handshake per connection and certificate generation, so it cannot be faster than candidate 2, which the rule prefers unless 3 is no slower; it would also make `rcgen` a runtime dependency. ## Wire change: compact tensor bytes in the stage protocol (second commit) `pipeline::wire_bytes` adds serde `with` modules that encode the bulk `Vec<u8>` fields of `RunEntry` (`input_ids`, `attention_mask`), `RunResult` (`logits`) and `ActivationMessage` (`tensor_data`, `attention_mask`, `position_ids`) as one base64 string in JSON (1.33 characters per byte) and as raw bytes in a non-human-readable format. One encoding path; round-trip unit tests for the modules and for the three message types, including the typed error for invalid base64 and the refusal of the old array form. A build with this encoding does not interoperate with one without it; mixed versions were already unsupported and `PROTOCOL_VERSION` moved to 3 in this PR. Documented in docs/distributed.md. ## Test-first evidence The five proxy tests in `src/distributed/tcp_transport_frame_tests.rs` (declared from `tcp_transport_tests.rs`) use only APIs that exist on main and learn the frame trailer length from a calibration frame, so the same code ran against the unmodified transport first: all five failed (`tampered_frame_is_rejected`: the frame arrived as `inuegrity`; `replayed_frame_is_rejected`, `reordered_frames_are_rejected`, `frame_from_other_connection_is_rejected`: the frames reached `recv()`; `activation_bytes_are_not_visible_on_the_wire`: the pattern was readable). They pass on this branch. Two more tests cover the oversize header: `protected_stream_refuses_oversize_header_before_body` and `transport_closes_connection_on_oversize_header` (the frame is refused from the header, nothing reaches `recv()`, the connection closes). ## Verification - Full `distributed::` lib module on the final head (includes `distributed::pipeline::`, the `wire_bytes` tests and the oversize-header tests): 1433 passed, 0 failed, 4 ignored (CUDA, `--test-threads=1`, gpu-lock). - Real-model remote pipeline parity on GB10 (`MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1`, under gpu-lock): `pipeline_remote_runtime_qwen3_real_model_parity_and_cleanup` and `pipeline_remote_runtime_qwen35_real_model_parity_and_cleanup` pass. The unit did not run llama/gemma3/gemma4; the pre-merge check below did. - Microbench: `cluster_frame_bench::frame_protection_candidates_loopback` (ignored, run under gpu-lock); e2e: `pipeline_remote_decode_bench` interleaved base/cand, 5 runs each. - `cargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings`, `cargo fmt --check`: clean. No env var added. ## Pre-merge check (main merged in, head 69a32b2) - `make verify-fmt`, `make verify-env-var-docs`, `cargo clippy --features cuda,test-utils -p mlxcel --lib --tests -- -D warnings`: clean. - `--lib distributed:: server::startup server::router_front`: 1560 passed, 0 failed. - Real-model remote pipeline (`MLXCEL_REQUIRE_MODELS=1 MLXCEL_SDPA_DETERMINISTIC=1`): `pipeline_remote_real_models` llama/gemma3/gemma4/qwen3/qwen35 parity plus llama drain 6/6, `pipeline_server_remote_real_models` 5/5, `pipeline_ci_multi_stage_real_models` two-host smoke 1/1. - `--test zero_config_cluster_init --include-ignored`: 7/7 (the stage-assignment channel now runs over the frame codec). `--test disaggregated_e2e`: 51/51. - `--test disaggregated_serving_e2e` (1 failure, client handshake "secret mismatch") and `--test disaggregated_router_e2e` (4 of 7 fail: node-failure 500, two `prompt_tokens_details` body mismatches, one byte-fallback usage count) fail identically on main 5dfbfb3, so they predate this PR and are tracked separately. - After merging main 5dfbfb3 (#2686, model code only), fmt, clippy and the same lib selectors were re-run. ## Changes during review - Stale claims that the cluster secret does not encrypt traffic or that frames are not authenticated were fixed in the `--cluster-secret-file` help, the disaggregated trust-model section of docs/distributed.md, and a router comment. - Frame keys are separated per channel (`FrameChannel` in the HKDF info), so a connection redirected between the stage transport listener and the assignment listener cannot reuse keys across them. - Authentication failures on the assignment channel are logged through the same rate limiter as the transport core, without payload bytes. - The raw-bytes `visit_seq` path in `wire_bytes` caps its preallocation at 64 KiB instead of trusting `size_hint`. - These changes touch key derivation, logging and tests only; the per-frame seal/open path and the tensor encoding hot path are unchanged since the measurements, so the numbers above stand. ## Follow-up candidate The stage protocol still ships the logits twice per token (final stage to entry stage, entry stage to coordinator) and as JSON; a binary frame or a direct final-stage reply would halve the remaining per-token bytes. Closes #2656
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Qwen3-Next, Qwen3.5, Bailing MoE Linear, Kimi Linear and Kimi K3 now batch decode across isolated recurrent sequence state. Qwen3.5 and Kimi K3 VLM wrappers delegate to their towers. Qwen3.5 paged accounting counts attention KV storage and excludes recurrent GDN slots, avoiding fictitious page reservations.
All six measured configurations retain byte-identical B1 greedy text and all 256 recorded B1 trace rows. Metal serving aggregate tokens/s at concurrency 1/2/4:
Ring-mini has 22/256 total top-1 disagreements, including one reference gap of 2.312; corpus PPL changes 58.3837→57.1854 (-2.052%). Disabling fused MoE in a separate diagnostic removes decided disagreements (0/114), consistent with width-dependent quantized-kernel arithmetic; production numbers remain unchanged. This is not full numerical equivalence. Qwen3.5 image B1 matches baseline exactly; B4 has 2/64 top-1 and 0/15 decided disagreements. Free-form VLM solo/concurrent messages match 2/3 in both baseline and candidate: counting-prompt reasoning drifts in both versions, while solo messages across revisions match 3/3. Kimi Linear/K3 remain synthetic-only.
Implementation/security review, seven focused GPU tests, fourteen coverage checks, scoped clippy and formatting pass. Release build and all serving ladders pass. Raw evidence, runtime hashes, reproducible inputs and bilingual reports are recorded under
benchmarks/epic-2574/andTECHNICAL_REPORTS/2686-*. Final combined workspace verification follows integration with #2685 under epic #2574.Closes #2572