Skip to content

prefill: pipeline a prompt's chunks over the parts of a --device split - #243

Merged
Vasyl-Trefilov merged 6 commits into
RustingStudio:mainfrom
SubgridAI:pipelined-prefill
Dec 6, 2026
Merged

Vasyl-Trefilov merged 6 commits into
RustingStudio:mainfrom
SubgridAI:pipelined-prefill

Conversation

@SubgridAI

Copy link
Copy Markdown
Contributor

What changed and why

With --device a,b,c,d, prefill ran each prompt chunk through every part in turn, so only one card worked at a time. On a 4-card split that leaves about three quarters of the GPU time idle during long prefills. Five commits:

  1. Pipelined prefill (src/gpu_model/prefill.rs): each part runs on its own thread and starts chunk k+1 as soon as it has handed chunk k on. Each part touches only its own layers' state and takes chunks in order, so the result equals the sequential loop's.
    • Used for one request (--parallel 1), text prompts of 2+ chunks, no STRATA_PF_ADAPT, no DFlash draft. Everything else keeps the sequential loop.
    • STRATA_PF_PIPE=0 restores the sequential loop.
  2. STRATA_PF_PROF=1 (src/gpu_model/pf_prof.rs): per-part, per-chunk component timing (in / pre / delta / attn_proj / qsa_idx / qsa_sel / attn / post / moe / tail / out) plus pipeline waits. Off by default, no cost when off.
  3. Pinned hand-off: two reused portable pinned buffers per hop (Backend::alloc_shared_host) instead of a fresh pageable Vec, so both copies of a hop are direct DMA. STRATA_PF_PINNED=0 switches back.
  4. Profiler gap / lead: time since the part's previous chunk line, and setup/embedding before the timed window. This is what exposed (5).
  5. Parallel head embedding: the head part dequantized (and un-rotated) each chunk's embedding rows on one thread, about 300 ms per 4096 tokens, outside its GPU work. That paced the whole pipeline at ~1346 ms per chunk while the slowest card needed ~1215 ms. It now runs on the rayon pool in ~68 ms.

Independent of #207. If #207 merges first, STRATA_PF_PROF's qsa marks also need to cover its gather branch (a one-hunk rebase I can do).

Verification

Setup: 4× RTX 3060 12 GB on two PLX PEX 8747 switches (no P2P; all hand-offs go through host memory), Qwen4-35B-A3B UD-Q5_K_M, ctx 1M, KV q8, --device split 27,25,27,21, chunk 4096, release build. Needle retrieval 3/3 in every run.

First result, pipelining alone on stock v1.5.1 (commit 1 only, same model, flags and prompts; no other patches):

Prompt Stock v1.5.1 + pipelined prefill Speedup
194K 624 tok/s, 311 s 2042 tok/s, 95 s 3.3×
992K 212 tok/s, 4683 s (78 min) 683 tok/s, 1452 s (24 min) 3.2×

The answer text was identical to the unpatched run at 194K, needles 3/3 at both lengths, no errors in the log.

Pipeline A/B (STRATA_PF_PIPE=0 vs default): same binary and flags, fresh server per mode, the env var is the only difference. Each 194K row is two runs with different needle texts (no prefix-cache hits).

Prompt Mode Prefill tok/s Prefill time (≈TTFT) Decode tok/s Needles
194K sequential 938 / 938 207 s / 207 s 78.6 / 78.4 3/3, 3/3
194K pipelined 3287 / 3289 59 s / 59 s 78.5 / 78.3 3/3, 3/3
992K sequential 752 1319 s 46.9 3/3
992K pipelined 2679 370 s 46.9 3/3

Pipelining makes prefill 3.5× faster at 194K and 3.56× at 992K on 4 parts; a 1M-token prompt drops from 22 min to about 6. Decode and needle accuracy are unchanged.

End to end on this box (for context only; it also includes the separate #206 and #207 CUDA follow-ups):

Prompt Stock v1.5.1 v1.5.2 + this PR + #206/#207 with CUDA follow-ups Gain
980K prefill 212 tok/s, 78 min 2693 tok/s, about 6 min 12.7×
194K prefill 624 tok/s, 311 s 3274 tok/s, 59 s 5.2×
Decode ~45 (980K) / ~75 (194K) tok/s 46.8 / 73.9–78.4 tok/s unchanged

Individual commits:

Change Measurement
Pinned hand-off (3) 980K prefill 2227 → 2339 tok/s
Parallel head embedding (5) 194K prefill 2939 → 3124 tok/s; head CPU time 295 → 68 ms per chunk
Hand-off cost per hop ~33 ms dtoh + ~14 ms htod per chunk; crossing the PCIe switch costs nothing extra

To reproduce: run a prompt of 100K+ tokens on a multi-GPU --device split with --parallel 1, once with STRATA_PF_PIPE=0 and once without, and compare the prefill: tok/s line. STRATA_PF_PROF=1 prints the per-part, per-chunk breakdown.

Notes for review

  • The gain scales with the number of parts and how evenly they are loaded. With the profiler you can see which part gates the pipeline (on our box, the card with non-resident experts).
  • Requests that don't meet the conditions in (1) keep the sequential path unchanged.
  • No automated test was added. The path needs a multi-GPU box and long prompts, so it was verified by the A/B above, with identical needle results and decode speed in both modes.

Checklist

  • I followed this repository's contribution guide and required checks.
  • I updated documentation or examples where needed.
  • I added regression coverage where it helps verify the change.
  • I have the right to contribute the included code and assets under this repository's contribution terms.

This work was done with Claude Code.

🤖 Generated with Claude Code

SubgridAI and others added 5 commits December 6, 2026 01:04
… split

A --device split ran prefill chunk by chunk through every part in turn, so with N cards each was busy about 1/N of
the time. Now each part runs on its own thread and starts chunk k + 1 as soon as it has handed chunk k on, so the cards
work on different chunks at once. Each part reads only its own layers' state from the chunks before, and takes the
chunks in order, so the result is the sequential loop's.

Taken for one request (--parallel 1), a text prompt of two or more chunks, no STRATA_PF_ADAPT, no DFlash draft.
STRATA_PF_PIPE=0 keeps the sequential loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One line per part per chunk: total and in / pre / delta / attn_proj / qsa_idx / qsa_sel (score) / attn / post / moe /
tail / out, and the pipeline waits for the part before and after. Each mark syncs the part's streams, so it removes
the overlap inside a part (not between parts); profiling runs come out a few percent slower. Off: no syncs, no cost.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s (STRATA_PF_PINNED=0: Vecs)

Each hop's hidden rows went device -> fresh Vec -> device, both copies through the pageable path. Two portable pinned
buffers per hop, owned by the receiving part and passed back once its upload is done, make both copies direct DMA
(Backend::alloc_shared_host; host_is_pinned sees them on every device).

4x RTX 3060 (two PLX switches): 980K prefill 2227 -> 2339 tok/s, same answer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
gap: the time since the part's previous chunk line, i.e. the waits plus any work outside the timed window; lead: the
setup and input embedding before it. Unaccounted gap on a part with no waits is work that paces the pipeline unseen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One thread dequantized (and un-rotated) each 4096-token chunk's embedding rows in ~300 ms before the head part's GPU
work: the head's cycle was 1046 ms of GPU work + ~300 ms of this, which paced every part of the pipeline (the others
showed it as waits). Now ~68 ms.

4x RTX 3060, Qwen4-35B-A3B UD-Q5_K_M, ctx 1M: 194K prefill 2939 -> 3124 tok/s, 3/3 needles, decode unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@aletheore

aletheore Bot commented Dec 6, 2026 •

Copy link
Copy Markdown

🔍 Aletheore evidence diff

graph LR
    n0["src/backend.rs"]
    n1["src/cuda/mod.rs"]
    n2["src/gpu_model.rs"]
    n3["cpu_worker.rs"]
    n4["src/cuda/host_share.rs"]
    n5["chat.rs"]
    n6["mat.rs"]
    n7["expert_cache.rs"]
    n8["src/gpu_model/host_share.rs"]
    n9["src/hip/mod.rs"]
    n10["dspark.rs"]
    n11["forward.rs"]
    n12["device.rs"]
    n13["pool.rs"]
    n14["worker.rs"]
    n15["lib.rs"]
    n16["main.rs"]
    n17["model.rs"]
    n18["projector.rs"]
    n19["src/vulkan/mod.rs"]
    n20["preflight.rs"]
    n21["tests/backend.rs"]
    n22["tests/common/mod.rs"]
    n23["tests/gpu_model.rs"]
    n24["inkling2_attn_kv.rs"]
    n25["inkling2_q8_attention.rs"]
    n26["kernels.rs"]
    n27["kv_q8.rs"]
    n28["kv_turbo.rs"]
    n29["llama_numerics.rs"]
    n30["tq_probe.rs"]
    n31["vision.rs"]
    n32["vision_gpu.rs"]
    n33["vulkan_split_kv.rs"]
    n0 --> n3
    n0 --> n6
    n0 --> n7
    n0 --> n8
    n0 --> n9
    n0 --> n10
    n0 --> n11
    n0 --> n12
    n0 --> n13
    n0 --> n14
    n0 --> n15
    n0 --> n16
    n0 --> n17
    n0 --> n18
    n0 --> n19
    n0 --> n21
    n0 --> n22
    n0 --> n23
    n0 --> n24
    n0 --> n25
    n0 --> n26
    n0 --> n27
    n0 --> n28
    n0 --> n29
    n0 --> n30
    n0 --> n32
    n0 --> n33
    n1 --> n4
    n1 --> n5
    n1 --> n9
    n1 --> n12
    n1 --> n15
    n1 --> n16
    n1 --> n19
    n1 --> n20
    n1 --> n22
    n1 --> n23
    n1 --> n24
    n1 --> n27
    n1 --> n28
    n1 --> n29
    n1 --> n33
    n2 --> n15
    n2 --> n16
    n2 --> n17
    n2 --> n19
    n2 --> n21
    n2 --> n23
    n2 --> n31
    classDef changed fill:#d9772c,color:#fff,stroke:#b85f1c;
    classDef changedFinding fill:#c0392b,color:#fff,stroke:#922b21;
    classDef dependent fill:#f2f0ec,color:#18140f,stroke:#d6d0c5;
    class n0 changed
    class n1 changed
    class n2 changed
    class n3 dependent
    class n4 dependent
    class n5 dependent
    class n6 dependent
    class n7 dependent
    class n8 dependent
    class n9 dependent
    class n10 dependent
    class n11 dependent
    class n12 dependent
    class n13 dependent
    class n14 dependent
    class n15 dependent
    class n16 dependent
    class n17 dependent
    class n18 dependent
    class n19 dependent
    class n20 dependent
    class n21 dependent
    class n22 dependent
    class n23 dependent
    class n24 dependent
    class n25 dependent
    class n26 dependent
    class n27 dependent
    class n28 dependent
    class n29 dependent
    class n30 dependent
    class n31 dependent
    class n32 dependent
    class n33 dependent
Loading

What changed
Deterministic, computed from this commit's real scan and import graph - posted on every run, whether or not Flash Review found anything.

  • src/backend.rs · modified · +9/-0 · +2 functions, +1 class · 27 other dependents
  • src/cuda/mod.rs · modified · +26/-1 · +3 functions, +1 class · 15 other dependents
  • src/gpu_model.rs · modified · +5/-1 · 7 other dependents
  • src/gpu_model/pf_prof.rs · +113/-0 · new file, 10 symbols
  • src/gpu_model/prefill.rs · modified · +192/-8 · +4 functions, +1 class

Aggregate deltas

  • Modules: +1
  • Dependency graph edges: +5
  • Commits: 6

Comment thread src/gpu_model/prefill.rs
}
if part.hand.is_empty() { pools.push((None, None)); continue; }
let (rtx, rrx) = sync_channel::<Pool>(part.hand.len());
for b in part.hand.drain(..) { rtx.send(b).expect("hand-off pool"); }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 1 of 4

alloc_shared_host error returns before reattaching detached parts, losing self.next prefill_pipelined takes self.next into rest, then part.gpu.alloc_shared_host(cap)? returns Err (not Ok(None)); function returns immediately, rest is dropped and self.next stays None, so all later prefills run only the head part with wrong/missing layers.

Prompt for your AI agent
File: src/gpu_model/prefill.rs
Line: 285
Symbol: adapt_experts
Issue: alloc_shared_host error returns before reattaching detached parts, losing self.next prefill_pipelined takes self.next into rest, then part.gpu.alloc_shared_host(cap)? returns Err (not Ok(None)); function returns immediately, rest is dropped and self.next stays None, so all later prefills run only the head part with wrong/missing layers.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

1 of 4 (High): alloc_shared_host error returns before reattaching — FIXED

Fixed in the latest push. A failed allocation now falls back to Vecs for that hop instead of returning with ?, so the detached parts are always reattached.

Comment thread src/gpu_model/prefill.rs
// The upload from the buffer is asynchronous: done before the buffer goes back.
if hin.buf.is_some() { part.gpu.sync()?; }
crate::term::prefilled(ch.len());
true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 2 of 4

Panic on head thread unwinds past reattachment of rest, leaving model detached A panic in head send_chunk/prefill_chunk_to (e.g. slice out-of-bounds in dtoh to a too-small hand buffer) unwinds through thread::scope before the reattach loop runs; self.next remains None and rest is dropped, corrupting the model for every subsequent call, unlike part-thread panics which are caught via join.

Prompt for your AI agent
File: src/gpu_model/prefill.rs
Line: 330
Symbol: cache_begin
Issue: Panic on head thread unwinds past reattachment of rest, leaving model detached A panic in head send_chunk/prefill_chunk_to (e.g. slice out-of-bounds in dtoh to a too-small hand buffer) unwinds through thread::scope before the reattach loop runs; self.next remains None and rest is dropped, corrupting the model for every subsequent call, unlike part-thread panics which are caught via join.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

2 of 4 (High): head panic skips reattachment — FIXED

Fixed. The server catches a request's panic (catch_unwind around handle in main.rs) and keeps the model. The scope now runs under catch_unwind, the parts are reattached, and then the panic resumes.

Comment thread src/gpu_model/prefill.rs
let free = frees.get_mut(i + 1).and_then(Option::take);
handles.push(sc.spawn(move || -> anyhow::Result<Option<(usize, Receiver<Pool>)>> {
let mut rx = rx.into_iter();
loop {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Correctness · 3 of 4

Intermediate parts return hand buffer to pool without syncing their GPU upload Only the last part calls gpu.sync() before back.send(b); intermediate parts return hin.buf immediately after prefill_chunk_to. The previous part can then recv that buffer and dtoh-overwrite it while the intermediate GPU's asynchronous htod from it is still in flight, corrupting the next chunk nondeterministically.

Prompt for your AI agent
File: src/gpu_model/prefill.rs
Line: 315
Symbol: prefill_cached_with
Issue: Intermediate parts return hand buffer to pool without syncing their GPU upload Only the last part calls gpu.sync() before back.send(b); intermediate parts return hin.buf immediately after prefill_chunk_to. The previous part can then recv that buffer and dtoh-overwrite it while the intermediate GPU's asynchronous htod from it is still in flight, corrupting the next chunk nondeterministically.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

3 of 4 (High): intermediate parts return the buffer without syncing — /dismiss

/dismiss A part with a next part ends prefill_chunk_to with a blocking dtoh of its slab into the outgoing hand-off (wait() followed by a stream sync). That runs on the same stream as the chunk's upload put, after it, so the upload from the incoming buffer has finished before the buffer goes back. Only the last part has no dtoh, which is why only it calls sync(). I added a comment there saying so.

Comment thread src/gpu_model/pf_prof.rs
let on = on();
if on {
g.sync_freed()?;
SCORE.with(|c| c.set(0.0));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Correctness · 4 of 4

Pp error paths skip report, leaving WAIT_IN/WAIT_OUT stale for next chunk Pp::new resets SCORE but not WAIT_IN/WAIT_OUT; report() is the only place that clears them. Any ? error inside prefill_chunk_to drops Pp without report, so the next chunk's line includes the failed chunk's pipeline waits, and LAST is not updated so gap is also wrong.

Prompt for your AI agent
File: src/gpu_model/pf_prof.rs
Line: 70
Issue: Pp error paths skip report, leaving WAIT_IN/WAIT_OUT stale for next chunk Pp::new resets SCORE but not WAIT_IN/WAIT_OUT; report() is the only place that clears them. Any ? error inside prefill_chunk_to drops Pp without report, so the next chunk's line includes the failed chunk's pipeline waits, and LAST is not updated so gap is also wrong.
Make the smallest change that fixes this, add a test, and change nothing unrelated.

Reply /dismiss (optionally with a reason) if this isn't helpful - Aletheore won't raise it again on this repo.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

4 of 4 (Medium): Pp error path leaves WAIT_IN/WAIT_OUT stale — FIXED

Fixed. If a chunk drops its Pp without reporting, it clears its score and pipeline waits, so they no longer land on the next chunk's line. This only affects the STRATA_PF_PROF=1 output.

@aletheore

aletheore Bot commented Dec 6, 2026 •

Copy link
Copy Markdown

Aletheore Flash Lite review

Merge confidence Review effort Merge risk
2 / 5 1 / 5 Medium
Area Files Lines
src/gpu_model 2 +22 −6

No issues held up under independent verification (7 grounded, 0 confirmed by a second model). 4 earlier finding(s) from previous pushes still open.

# Severity Category Where
- 🟠 High Correctness prefill.rs:285 Earlier finding, still open
- 🟠 High Correctness prefill.rs:330 Earlier finding, still open
- 🟠 High Correctness prefill.rs:315 Earlier finding, still open
- 🟡 Medium Correctness pf_prof.rs:70 Earlier finding, still open
Review details

Reviewed 2 file(s); skipped 0. Dismissed 0; outside PR diff 0. Grounding: 7 of 9 proposed finding(s).

Blast radius: 64 other file(s) depend on what this PR changes (2 directly, 62 indirectly)

Computed from the import graph of this exact commit, not guessed by a model. It sees imports only, so dynamic imports, reflection and non-code references are not counted.

  • src/gpu_model/pf_prof.rs is imported by src/cuda/mod.rs, src/gpu_model.rs
  • src/gpu_model/prefill.rs is imported by src/gpu_model.rs

Indirectly affected: examples/dotn_bench.rs, examples/moe_cpu_layer_bench.rs, src/backend.rs, src/calibrate.rs, src/cpu_moe.rs, src/cpu_worker.rs (+56 more)

The graph is large; this list is capped and not exhaustive.

… head panic

- A failed alloc_shared_host falls back to Vecs for that hop instead of returning
  before the detached parts are reattached.
- The scope runs under catch_unwind: the server catches a request's panic and keeps
  the model, so the parts are reattached before the panic resumes.
- pf_prof: a chunk that fails before its line clears its score and pipeline waits,
  so they don't land on the next chunk's line.
- Comment: a part with a next part ends prefill_chunk_to with a blocking dtoh, so its
  upload from the hand-off buffer is done before the buffer goes back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@SubgridAI

Copy link
Copy Markdown
Contributor Author

Pushed a follow-up commit: review items 1, 2 and 4 are fixed, and item 3 is answered inline (the dtoh at the end of an intermediate part's chunk is blocking). cargo check passes.
Heads-up for merging: this PR and #242 both touch host_is_pinned and add statics at the same spot in src/cuda/mod.rs. Whichever merges second has a small conflict (keep both sides), and I'll rebase it as soon as the first one lands.

@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Hi, ty for this, nice work.

I have only one card here, so I tested the split with the same 3060 opened twice (--device 0,0) on Qwen4 with a 4K token prompt and chunk 1024. Greedy output is the same on main, on this branch, and on this branch with STRATA_PF_PIPE=0. Single device output is also unchanged, and split_matches_single, split_batch_matches_one_part and qwen4_slots_match_single pass.

One small thing, not a blocker: in prefill_pipelined the alloc_shared_host(cap)? runs after self.next was taken. If that alloc fails, the function returns before the parts are put back, so the model loses its later parts. Doing the alloc before the detach (or putting the parts back on that error) would fix it.

It is merged now.

@Vasyl-Trefilov
Vasyl-Trefilov merged commit 949e484 into RustingStudio:main Dec 6, 2026
3 checks passed
@Vasyl-Trefilov

Copy link
Copy Markdown
Member

Your follow-up commit (keeping the parts on an alloc error or a panic) is merged too, ty.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants