Skip to content

qwen3_5 cuda: merge-wide attention, MLP segment, cached warm start - #6065

Closed
jojomondag wants to merge 3 commits into
ashhart:mainfrom
jojomondag:pr-start-paths
Closed

jojomondag wants to merge 3 commits into
ashhart:mainfrom
jojomondag:pr-start-paths

Conversation

@jojomondag

@jojomondag jojomondag commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Three commits of default-off switches for the Qwen3.8 CUDA path, each measured on a 5090 and each able to be split into its own pull request if you prefer. (A fourth, TF_QWEN_STARTS_MERGE, was dropped from this branch: #6056 already carries it on its own.)

  1. TF_QWEN_MERGE_WIDE — the attention merge runs a thread per head value instead of a thread per row (5.7/13.9/34.9 µs → 3.3/6.6/12.7 µs at three widths), with a byte verify mode TF_QWEN_MERGE_WIDE_VERIFY=1.
  2. TF_X_MLP_SEG — decode MLP gate and up in one launch for windows of 16 rows or fewer (+1.5 % decode everywhere on the 170-SM class), and TF_X_GEMV_MANY as the GB10 grouped-GEMV experiment on other GPUs.
  3. The start-up switches TF_X_START_COPY, TF_X_DRAFT_CACHE, TF_X_EXE_PREHASH, TF_X_PROBE_CACHE (+ TF_X_START_LOG, TF_X_START_HASH, TF_X_DRAFT_CACHE_DIR, TF_X_PROBE_CACHE_DIR): a warm start goes 4.71 s → 2.49 s and time to first token −5.5 % by removing a threaded pinned weight copy, caching the drafter's quantized tables and the binary's hash, and caching the store-identity probe. TF_X_START_PREPIN from the same work is not here: it anchors on a pinned slab bank that does not exist upstream.
  • Issue: n/a. Default-off switches for this family; nothing here is requested by an issue.
  • Stacked on: main (3c492f733). Prepared on 51274de34, rebased; build and lean check re-run after the rebase.
  • atc overlap --json: not run on this head (the sibling run returned complete: false on its time limit). Say the word.

Checks on this head

  • Head commit: 7177bed68 on main 3c492f733 (three commits; the branch was force-updated to drop the merged-starts commit that qwen3_5 cuda: run neighbouring request-start chunks as one forward (TF_QWEN_STARTS_MERGE, default off) #6056 carries).
  • Lean checker, python3 tools/zig/lean_check.py: base 88 problems, head 88 problems — no new findings.
  • env_names.py: 845 variables read, 0 problems.
  • Tests run: zig build native -Dnvcc=/opt/cuda/bin/nvcc -Dsm=120 -Dversion=1.3.8 succeeds; host steps test-environment-host, test-environment-report-host and test-qwen35-merged-starts-host pass. zig build test is not usable here (29 binaries fail on unmodified main too, no CUDA device in the test run).
  • Not run, and why: no serving receipt on main-vs-branch, no kernel-contract records.
  • CI: not run on this head.

Receipt

  • Main against branch: not measured on main; the numbers above are from the fork build that carries these switches (plus the rest of that build's switches), measured with the recorded-traffic replay and synthetic cells named in the commit bodies.
  • Exactness: replies identical and kept-state files byte-equal where the commits claim it; the merge and verify modes above exist for the kernels themselves.
  • Boxes it reaches: Qwen3.8 CUDA on the 170-SM class; TF_X_GEMV_MANY only as a default-off experiment elsewhere.
  • New switches, read from the code: TF_QWEN_MERGE_WIDE 0|1 default 0, TF_QWEN_MERGE_WIDE_VERIFY 0|1|2 default 0, TF_X_MLP_SEG off, TF_X_GEMV_MANY off, TF_QWEN_STARTS_MERGE off, TF_X_START_COPY 0–32 default 0, TF_X_EXE_PREHASH/TF_X_DRAFT_CACHE/TF_X_PROBE_CACHE/TF_X_START_LOG/TF_X_START_HASH off, plus the two cache directories. All registered in environment.zig except the two gate-sweep test switches, which stay lenient like TF_CUDA_TEST_MLP128.
  • Environment: zig 0.17.0, CUDA 13, RTX 5090 (sm_120, 170 SMs), Qwen3.8-27B MLX 4-bit, DFlash2 drafter.
  • Licence of new weights or drafter: n/a.

I can run the full receipt on main against this branch on the 5090 (decode at 1 and 4 streams, cold prompt speed at 2k/8k/32k/64k, exactness, kernel contract) before review.

…ERGE_WIDE, default off)

The decode attention merge ran one warp a (row, query head), each lane
carrying 8 of the head's 256 values, so a row's 64 chunks were walked by 2-3
warps an SM at best. With TF_QWEN_MERGE_WIDE=1 a 256-thread block takes one
(row, query head) and a thread computes one of its values. Every thread runs
the same chunk loop as the warp kernel: the max over the row's chunk partials
in chunk order, then that value's exp, its fmaf into the running weight sum
and its fmaf into the running sum, the same operands in the same order, so
each output keeps the warp merge's bits. Only who computes it changes: 8 warps
a (head, row), coalesced partial reads.

TF_QWEN_MERGE_WIDE_VERIFY=1 also runs the warp merge into the logits scratch
(not written yet at that point) and compares the live rows with the wide
merge's output byte for byte, trapping on a difference; =2 plants one
difference in row 0's first value, so a run that does not trap proves nothing.

The two wide kernels sit in kernels/cuda/qwen35_merge_wide.cuh, included where
the warp merge is, since qwen35.cu is at the 600-line rule.
A GB10 card is the only one that runs the decode MLP gate and up as one
segmented launch and takes gemvMany, one dependent-launch grid with the K
slices kept in a CTA; every other card runs a launch a projection. The two
gate-sweep switches let another card take those paths unchanged, read once
from the environment at load and off by default:

TF_X_GEMV_MANY=1 lets decodeMany take gemvMany off GB10 too, so a window's
separate projections share one grid.
TF_X_MLP_SEG=1 sends a decode MLP's gate and up through projMany whenever the
window is at most max_rows (16) rows, the shape mlp128Shape allows.

Before: on any card but GB10 both paths were unreachable whatever the
environment said. After: exactly "1" enables one and logs it as it loads,
anything else leaves it off, and unset or off keeps the default launch a
projection.
Copilot AI balanced review requested due to automatic review settings December 2, 2026 21:16

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Stale worker state and premature pinned-buffer release can cause corruption or hangs, while failure-path resource leaks and missing kernel-contract coverage also remain unresolved.

4 open issues
What changed in this PR

Adds default-off performance options for Qwen’s CUDA inference path, targeting decode, prompt prefill and startup.

Changes:

  • Adds wide attention merging and grouped decode projections.
  • Combines eligible request-start chunks into larger prefill passes.
  • Adds startup caching, threaded weight uploads and diagnostics.
File Description
zig/​src/​server/​cli.zig Exposes the merged-starts switch.
zig/​src/​platform/​file_identity.zig Adds background executable hashing.
zig/​src/​platform/​environment.zig Registers new environment settings.
zig/​src/​platform/​environment_valid_cases.zig Adds valid-setting test cases.
zig/​src/​native/​xstart_probe_cache.zig Caches identity-probe results.
zig/​src/​native/​cuda_disk.zig Integrates probe caching and timing marks.
zig/​src/​families/​qwen3_5/​cuda.zig Includes merged-prefill tests.
zig/​src/​families/​qwen3_5/​cuda_xstart_hash.zig Adds loaded-weight hash diagnostics.
zig/​src/​families/​qwen3_5/​cuda_prompt_int8.zig Tracks merged projection boundaries.
zig/​src/​families/​qwen3_5/​cuda_projection.zig Handles fallback per original chunk.
zig/​src/​families/​qwen3_5/​cuda_prefill.zig Integrates merged prefill passes.
zig/​src/​families/​qwen3_5/​cuda_prefill_merge.zig Defines merge eligibility, boundaries and tests.
zig/​src/​families/​qwen3_5/​cuda_native.zig Starts the optimized loading window.
zig/​src/​families/​qwen3_5/​cuda_merge_wide.zig Resolves and verifies wide merging.
zig/​src/​families/​qwen3_5/​cuda_forward.zig Selects optional merge and MLP paths.
zig/​src/​families/​qwen3_5/​cuda_engine.zig Integrates kernels and startup diagnostics.
zig/​src/​families/​qwen3_5/​cuda_drafter_open.zig Ends upload optimization before calibration.
zig/​src/​families/​qwen3_5/​cuda_draft.zig Adds drafter loading diagnostics.
zig/​src/​families/​qwen3_5/​cuda_draft_weights.zig Integrates cached quantization tables.
zig/​src/​families/​qwen3_5/​cuda_draft_quant_cache.zig Persists and validates quantization tables.
zig/​src/​cuda/​xstart.zig Provides startup switches and metrics.
zig/​src/​cuda/​start_copy.zig Adds threaded pinned-buffer uploads.
zig/​src/​cuda/​root.zig Exports startup helpers.
zig/​src/​cuda/​driver.zig Marks driver initialization timing.
zig/​src/​cuda/​copy_source.zig Routes uploads through startup helpers.
zig/​src/​cuda/​context.zig Marks context initialization timing.
zig/​src/​cuda/​affine4_kernels.zig Adds grouped-projection experiment switches.
zig/​src/​core/​profile.zig Registers the merged-starts profile option.
zig/​src/​core/​lanes/​cost_identity.zig Reuses the executable prehash.
zig/​kernels/​cuda/​qwen35.cu Includes wide-merge kernels.
zig/​kernels/​cuda/​qwen35_merge_wide.cuh Implements wide merging and byte verification.
zig/​build/​cuda_family_host.zig Adds a merged-starts host-test target.
docs/​environment.md Documents new settings and behavior.
docs/​environment-names.md Updates the environment-variable inventory.

Review effort: Balanced

Comment on lines +115 to +116
fast_quit = false;
fast_count = 1;

/// Waits for the pinned buffers' last copies, frees them and stops the copy threads (the next upload sets up again).
pub fn fastRelease() void {
const d = fast_d orelse return;
@@ -0,0 +1,46 @@
// tf_q35_attn_merge with 256 threads a (head, row), a value each: the same chunk loop and fmaf operands, same bytes.
extern "C" __global__ void __launch_bounds__(256) tf_q35_attn_merge_wide(Geo geo, const float* __restrict__ PM, const float* __restrict__ PL,
Comment on lines +165 to +168
cuda.xstart.openStart(); // TF_X_START_LOG's first mark, TF_X_EXE_PREHASH's thread, TF_X_START_COPY's window
const clef = try decide.check(gpa, io, dir, .{ .drafter = o.drafter != null, .slide = o.slide, .vision = o.vision != null, .kv8 = o.kv8, .prompt_int8 = o.prompt_int8 });
var loaded = try openLanes(gpa, io, ctx, dir, kernels, o);
if (o.drafter == null) cuda.start_copy.end(); // no drafter load follows
…_START_HASH, TF_X_EXE_PREHASH, TF_X_DRAFT_CACHE and TF_X_PROBE_CACHE (default off)

A Qwen start spent most of its time in work no receipt showed: the weight
upload copied every byte twice on one thread, the drafter quantized 3.8 GB of
bf16 weights again, and the identity probe of --learn-conversations ran a
4,136-token prompt pass again. Five default-off switches, all registered and
refused if malformed, put those behind a choice and make the time visible:

TF_X_START_LOG=1 prints one line a start-up phase on stderr with the weight
copies so far, wall-clock stamped so a launcher's own stamp lines up.
TF_X_START_COPY=N uploads the weights through three 16 MiB pinned buffers that
N host threads fill while the device copy of the piece before runs; the same
bytes land in the same order before an upload returns, and the window ends
with the model load.
TF_X_EXE_PREHASH=1 hashes the running binary once on a thread of its own
beside the load, into the two SHA-256 streams a start needs later; each reader
takes the result only for the very file it would have hashed.
TF_X_START_HASH=1 hashes the loaded weights after the load: the engine arena,
the drafter's arena and its host codebooks.
TF_X_DRAFT_CACHE=1 keeps the drafter's quantized affine-4 tables on disk,
keyed on the quantizer's version, the drafter file's identity and its shape,
and verifies every block hash and every entry's shape before it uses a byte;
any miss or error quantizes as before. TF_X_DRAFT_CACHE_DIR moves the folder.
TF_X_PROBE_CACHE=1 keeps the kept-state identity probe's hash and its measured
rate in a small file keyed on the code, the checkpoint, the device, the
command line and the switches; =verify runs the probe anyway and logs whether
the kept hash equals the fresh one. TF_X_PROBE_CACHE_DIR moves the folder.

Before: every start paid those costs and neither could be measured or skipped.
After: unset, each one changes nothing; set, each one moves the same bytes or
runs the same passes, so tokens and output are unchanged.
@jojomondag jojomondag changed the title qwen3_5 cuda: merge-wide attention, MLP segment, merged request starts, cached warm start qwen3_5 cuda: merge-wide attention, MLP segment, cached warm start Dec 2, 2026
@ashhart ashhart added kind:perf Classified by Synthena as performance improvement synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run labels Dec 2, 2026
@ashhart

ashhart commented Dec 2, 2026

Copy link
Copy Markdown
Owner

Synthena Initial Review — Performance receipt required (kind:perf)

Adds three default-off CUDA start-up/decode switches for Qwen3.5/3.8 (merge-wide attention kernel, MLP segment decode, and warm-start copy/hash/probe caches) plus environment plumbing and docs. Claims decode and start-up speedups but the receipt is from a fork build, not measured against this branch's base.

  • Failing CI check(s): fmt, zig.
  • Performance claim detected without a verified tf-receipt-v1 receipt.

Performance PRs require a verifiable benchmark receipt before running project CI hardware. See CONTRIBUTING.md (Performance PRs: verifiable benchmark receipt) and attach the output of:

python3 tools/perf_receipt.py run --base-bin /path/to/base-tf --head-bin /path/to/head-tf --model /path/to/model.tfold --out receipt.json

Findings:

  • [BLOCKER] zig/src/cuda/start_copy.zig: The fast path records an event on the null (default) stream after each cuMemcpyHtoDAsync, but the next write to slot k only waits on that event. If any other work is queued on the default stream between the async copy and the next piece's host fill, the host may overwrite a pinned buffer the driver is still reading from (the event only orders against the copy itself, not against later default-stream work that could still be reading via a prior copy's source). Suggested fix: Synchronize the stream (or use per-slot events recorded after the copy and confirm no intervening default-stream work reads the buffer), or add a comment proving the default stream is otherwise idle during the load window. At minimum, document the invariant that no other default-stream work can read these buffers between record and reuse.
  • [BLOCKER] zig/src/cuda/start_copy.zig: If cuMemcpyHtoDAsync fails mid-loop, errdefer sets fast_poisoned but the loop's already-recorded events are never waited on and fastRelease is not called; the pinned buffers and events leak (fast_d stays set, fast_owner stays nonzero) and the next upload re-enters fastSetup which returns error.Invalid forever, permanently disabling the fast path for the process even though the failure may have been transient. Suggested fix: On error, wait on all recorded events (best-effort) before setting fast_poisoned, and either call fastRelease to clean up or reset fast_owner so a later begin() can retry setup from scratch.
  • [BLOCKER] zig/src/platform/file_identity.zig: prehashedFor joins the prehash thread on first call, but prehash() can be called again after that (pre_joined is true so it returns early, fine), yet if prehash() is called from multiple threads concurrently before the first join, both can see pre_thread != null and both call t.join() on the same thread handle, which is undefined behavior in Zig's std.Thread. Suggested fix: Guard the join (and the pre_thread null-out) with a mutex or an atomic compare-exchange so only one thread performs the join.
  • [WARNING] zig/src/cuda/xstart.zig: enabled() caches the env read into a non-atomic-ordered state (monotonic is fine for the flag itself), but markf reads copy_* counters with .monotonic ordering and prints them; on weakly-ordered architectures this is fine on x86 but the counters are updated by other threads with fetchAdd(.monotonic), so a mark line may show slightly stale copy totals. This is diagnostics-only so impact is low. Suggested fix: Acceptable as-is for diagnostics; if exact totals per mark matter, use .acq_rel or document the staleness.
  • [WARNING] zig/src/families/qwen3_5/cuda_merge_wide.zig: The verify path launches the original warp merge into e.logits after the wide merge already wrote e.y, but does not synchronize between the two launches; both are on the same stream so ordering is guaranteed, yet the check kernel reads e.y and e.logits with no fence between the second launch and the check launch, which is also same-stream and thus ordered. This is correct, but the verify path silently does nothing when e.logits == 0 (the caller guards this), so a user setting TF_QWEN_MERGE_WIDE_VERIFY=1 in a shape with no logits scratch gets no verification and no warning. Suggested fix: Log a warning when verify is requested but e.logits is null so the user knows verification was skipped.
  • [WARNING] zig/src/cuda/copy_source.zig: synchronousCopy now branches to the fast path when start_copy.mine() is true, but mine() only checks the thread key, not that fastSetup has succeeded or that the driver/context match the current thread's context; if the model-load thread's current context changes mid-load (e.g., a different device is set current), the fast path copies with a stale fast_context. Suggested fix: Have mine() also verify that the current thread's context matches fast_context, or re-check the context inside copy() before proceeding.
  • Synthena

@jojomondag

Copy link
Copy Markdown
Contributor Author

Closing this one. It bundles three unrelated changes and was opened before its checks were done (CI is red and the review's blockers stand). I will bring each change back on its own, as an issue with head measurements first, the way #6034, #6036 and #6059 went. Sorry for the noise.

@ashhart

ashhart commented Dec 5, 2026

Copy link
Copy Markdown
Owner

Thank you @jojomondag. We took the two warm-start caches from this PR as default-off switches, with your authorship kept on each commit:

Left out:

Both pass focused host tests: cache keys, corruption and fallback controls, and byte-for-byte comparisons against the unchanged quantizer. We run the device build, the equality checks on a real checkpoint and the startup A/B ourselves, so nothing is needed from you.

  • Synthena

ashhart pushed a commit that referenced this pull request Dec 5, 2026
Adopt the independent default-off slice from #6065. Keep the existing arithmetic and strict output checks; device compilation, exactness and performance qualification remain separate.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind:perf Classified by Synthena as performance improvement synthena:needs-receipt Speed PR awaiting verified perf_receipt.py hash run

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants