Skip to content

feat(moe): prefill expert streaming, Stage 1a plumbing (--moe-prefill-stream, default off) - #161

Draft
ddvnguyen wants to merge 9 commits into
ci/perplexity-artifactfrom
feat/moe-prefill-stream
Draft

ddvnguyen wants to merge 9 commits into
ci/perplexity-artifactfrom
feat/moe-prefill-stream

Conversation

@ddvnguyen

@ddvnguyen ddvnguyen commented Oct 4, 2026 •

Copy link
Copy Markdown
Owner

Stage 1a = plumbing, no performance effect. With the flag on this binary executes the legacy path (G-P >=1.15x cannot be measured on this build). Stage 1b (pool fill + copy stream + grouped GEMM) is not implemented and needs rig iteration.

Stage 1a of Option C (epic hydra_vortex#811): prefill expert-streaming scaffolding behind a new fork-owned flag, default off. Spec: STAGE1-IMPL-SPEC.md sections 2-3. NOT to be merged (same rule as #160); exists so CI can build the rig artifact.

What this does

  • New flag --moe-prefill-stream (env LLAMA_ARG_MOE_PREFILL_STREAM, default OFF): common/arg.cpp, common_params, llama_model_params (+ default + pass-through), published to the CUDA backend at model load via the MoE-cache proc-address pattern. Flag off -> backend global stays false: same code paths, no new allocations, no decode change.
  • New graph outcome PREFILL_STREAMED (appended; PREFILL_LEGACY stays 0). All three compile_graph_plan decision points gated: flag off -> legacy, byte-identical. Flag on -> PREFILL_STREAMED only for a whitelist (host experts, no cache machinery, no group records, prefill-shaped graph); decode/mixed/cache-backed graphs stay legacy (G-K1). Every fallback logs once, never silently wrong.
  • Per-layer routed-union gather (host pass shaped like the sched used_ids loop; rejects out-of-range ids) + phase-scoped double-buffer pool descriptor with ensure/destroy (Stage 1b entry points, declared in moe-cache.cuh).
  • CI: new build_llama_server_artifact input emits {sm86-sm120, llama-server, cuda 13.2, arch 86;120, mode artifact} with the same guards/timeout as the perplexity artifact. No build-combo.sh change (binary name + target already parameterised; build-info.txt already records commit + cmake args).

IMPL-NOTES (deviations from the spec sketch, spec asked to record these)

  1. Decision point 2 (not 1) is the live one for --moe-expert-cache-size 0: cached_prefill requires cached buffers (moe-cache.cu inventory loop), so pure_prefill never fires there. All three points are still gated for agreement.
  2. resolve_streams / grouped predicates NOT un-gated in v1: without a pool consumer that yields null-stream success (unsafe shape); decode-gating stays until 1b.
  3. Capture path untouched: it already fails closed (force_moe_direct) for any non-GROUPED outcome; verified site by site (ggml-cuda.cu 6905-7029, moe-cache.cu 4540-4665, 10781-10816, 11356-11427, 11737-11744).
  4. Pool fill (copy-stream issue/wait) + grouped dispatch link are Stage 1b: v1 emits the outcome and executes the legacy path, so flag on vs off is numerically identical. Writing the dispatch integration blind (no local build, no GPU) risked silent numerics damage; stopped per the task STOP clause instead of improvising. --override-kv untouched, k stays 10.

Untested (everything runtime)

No local build, no GPU, no rig in this session. CI compile only. Flag-on prefill wall, link duty, G-K1/G-K2, G-V/G-L/G-G all need the rig session; the flag-on path currently validates unions + falls back to legacy compute, so G-P movement is NOT expected from this binary (Stage 1b wires the grouped GEMM). Top risks in this diff: (1) a missed outcome consumer that does not fail closed, (2) the prefill-shape heuristic misclassifying an exotic graph (falls back to legacy = safe direction), (3) a CUDA API slip in the uncalled pool helpers (covered by CI compile).

🤖 Generated with Claude Code

Add fork-owned boolean flag --moe-prefill-stream (env
LLAMA_ARG_MOE_PREFILL_STREAM, default off): common_params field,
llama_model_params field + default + pass-through, published to the
CUDA backend at model load via the MoE-cache proc-address pattern.
With the flag off the backend global stays false: same code paths,
no new allocations, no decode change.

Stage 1 of OPTION-C-DESIGN.md; spec STAGE1-IMPL-SPEC.md section 3.1.
Backend global + outcome gating follow in the next commit.
…ult off)

Backend half of --moe-prefill-stream (STAGE1-IMPL-SPEC.md section 3):

- New graph outcome PREFILL_STREAMED (appended; PREFILL_LEGACY stays 0).
  All existing outcome tests are if/else (no switch), so unhandled sites
  keep working; decode-grouped predicates and capture checks untouched.
- Process-wide enable flag (atomic) + proc-address setter, mirroring the
  expert-cache slot pattern. Published at model load, always (so a prior
  load cannot leak it on).
- All three compile_graph_plan decision points gated: flag off -> legacy,
  byte-identical. Flag on -> PREFILL_STREAMED only for a whitelist (host
  experts, no cache machinery, no group records, prefill-shaped graph);
  decode/mixed/cache-backed graphs stay legacy (G-K1). Every fallback logs
  once (never silently wrong).
- Per-layer routed-union gather (host pass shaped like the sched used_ids
  loop; rejects out-of-range ids) + phase-scoped double-buffer pool
  descriptor with ensure/destroy (Stage 1b entry points).

DEVIATIONS from the spec sketch (all flagged for IMPL-NOTES):
- Decision point 2 (not 1) is the live one for --moe-expert-cache-size 0:
  cached_prefill needs cached buffers, so pure_prefill never fires there.
- resolve_streams / grouped predicates NOT un-gated in v1: without a pool
  consumer that yields null-stream success; decode-gating stays until 1b.
- Capture path untouched: it already fails closed (force direct) for any
  non-GROUPED outcome; verified site by site.
- Pool fill (copy stream issue/wait) + grouped dispatch link are Stage 1b:
  v1 emits the outcome and executes the legacy path, so flag on vs off is
  numerically identical. Needs rig iteration, cannot be validated blind.
Extend the #160 artifact plumbing with build_llama_server_artifact:
emits {sm86-sm120, llama-server, cuda 13.2, arch 86;120, mode artifact}
with the same guards (needs arch_sm86_sm120 + execution_mode=matrix)
and the 120 min cloud timeout. Separate input (not reusing
build_llama_server) so image-mode server builds are untouched; no
build-combo.sh change needed (binary name + target already parameterised,
llama-server target exists; build-info.txt already records commit +
cmake args per spec section 6).
@ddvnguyen ddvnguyen changed the title feat(moe): prefill expert streaming (--moe-prefill-stream, default off) feat(moe): prefill expert streaming, Stage 1a plumbing (--moe-prefill-stream, default off) Oct 4, 2026
@ddvnguyen
ddvnguyen changed the base branch from hydra-fork to ci/perplexity-artifact October 4, 2026 03:56
ddv added 6 commits October 4, 2026 14:11
…b-R, part 1/2)

The scheduler's per-split used-expert H2D staging lands on the compute stream
(ggml_backend_cuda_set_tensor_async -> cudaMemcpyAsync(..., cuda_ctx->stream())),
so copy(L) and GEMM(L) cannot overlap, and the buffer-reuse guard in front of it is
a host-side ggml_backend_synchronize (ggml-backend.cpp:1797-1802) because events are
never allocated when n_copies == 1 (:2030-2034, tensor overrides force
pipeline_parallel=false). Measured cost on the 3060: 31-36 GiB per 2048-token chunk
at ~51% link duty, 188 host stalls per ubatch.

This commit adds only the backend-side machinery; nothing calls it yet, so behaviour
is unchanged with or without --moe-prefill-stream.

- ggml_backend_cuda_context gains a lazily created dedicated copy stream plus an
  8-slot round-robin event pool (so a wait already enqueued on the compute stream
  always refers to the capture it was enqueued against), both destroyed in the
  context destructor. Never touched unless the flag is on.
- ggml_backend_i gains two OPTIONAL slots, appended at the end of the struct on
  purpose: every backend in the tree initialises ggml_backend_i positionally, so new
  slots must never be inserted in the middle.
  * set_tensor_async_staged: H2D into a compute-buffer tensor on the copy stream,
    then cudaEventRecord + cudaStreamWaitEvent so the compute stream is ordered after
    the copy. Declines (false) when the flag is off, the buffer is not this device's
    compute buffer, or any CUDA call fails - the caller then falls back.
  * stage_stream_wait_event: cudaStreamWaitEvent(copy_stream, event) where the event
    was already recorded on the main stream. This is what lets the scheduler move the
    staging-buffer reuse dependency off the host and onto the copy stream.
- Declines are explicit and non-fatal (cudaGetLastError() clears, no CUDA_CHECK
  abort); every failure path returns false so the caller keeps the legacy blocking
  path. Never silently wrong.

Flag off: no code path reaches any of this, so behaviour is byte-identical.
Decode is untouched (no ne[2] condition is evaluated here).
…-R, part 2/2)

Wires the scheduler half of Stage 1b-R. Expert weights stay CPU-resident exactly as
today and the prefill expert MMID stays on CUDA0 exactly as today; only *how* the
per-split used-expert H2D is issued changes.

Why a second bank is required (not optional): the 141 MoE staging destinations are
not 141 buffers. need_new_split exists precisely so ggml-alloc recycles one region
(ggml-backend.cpp:1336-1337), and the numbers prove it - 45.5 GiB of declared staging
inside 6271 MiB of measured post-load VRAM. With one region, the host block at
:1797-1802 is load-bearing, because layer L+1's copy would overwrite the weights
layer L's GEMM is still reading. Deleting that block without a second bank is a
silent wrong-answer race, not a slowdown, so both halves land in the same commit.

- Two banks in one allocation, a plain GGML_TYPE_I8 tensor in the split backend's
  compute buffer, flipped per MoE-weight split. Deliberately NOT a view: a view sets
  view_src, and although bad_padding_clear (ggml-cuda.cu:1862, :1897) turns out NOT
  to be reachable from the mul_mat_id path (it is only used by should_fuse_mul_mat_vec_f,
  which already bails at :1845 for dst->ne[2] != 1, and by the non-ID ggml_cuda_mul_mat),
  keeping every tensor a plain dup means bad_padding_clear stays false by construction
  and the expert GEMM provably keeps the identical MMQ path it takes with the flag off.
- Each weight's staging tensor keeps its plain dup and has ->data redirected into the
  bank at EXECUTION time (inside compute_splits), not at split time, so it is re-applied
  on every replay after ggml-alloc reassigns ->data. Nothing else in the scheduler reads
  ->data after allocation, and buffers are owned by the buffer, not per tensor.
- Bank sizing uses ggml_backend_buft_get_alloc_size, NOT ggml_nbytes. blk.*.ffn_down_exps
  .weight is iq4_nl with ne[0]=640, so ne0 % 512 != 0 and the row-padding branch at
  ggml-cuda.cu:971-983 applies; that padding is exactly what MMQ reads instead of running
  off the end, and is the same slack copy_experts adds per run (:1859-1867). A
  ggml_nbytes-sized bank would drop it.
- The buffer-reuse barrier moves from the host to the copy stream: before staging, the copy
  stream waits on moe_stage_free[b][bank] (recorded on the main stream after the split that
  last read that bank, two splits ago); after dispatch_split, the event for each bank this
  split wrote is recorded. The host never blocks, and layer L+1's H2D is in flight on the
  copy stream while layer L's GEMM runs on the compute stream.
- Every decline falls back to the exact legacy sequence, PER SPLIT: no hooks, flag off,
  ne[2] <= 1, no bank, weight too large, or a mid-split refusal by set_tensor_async_staged
  (which restores the legacy barrier before the blocking copy). Never silently wrong.
- Decode is untouched three times over: the CUDA hooks decline when the flag is off; the
  ne[2] > 1 guard rejects 1-token graphs; and decode's expert MMIDs are CPU-resident with
  their weights, so they never produce a MoE weight split at all (split-parse.json
  block_kinds.decode weight_tensors = 0).
- graph_size and graph_copy account for the extra bank node.

Locally validated: ggml-backend.cpp with g++ -fsyntax-only, and ggml-cuda.cu with a real
nvcc -c against CUDA 13.2.1 (both exit 0). No binary produced, nothing written under
/mnt or /tmp beyond nvcc's own transient scratch.
…y on re-split

Review finding F1. moe_stage_bank_idx was reset only in ggml_backend_sched_split_graph,
but a reused graph reaches compute_splits WITHOUT re-splitting:
ggml_backend_sched_graph_compute_async_ext skips the reset+split+alloc path when the
graph is already allocated.

There are 141 MoE-weight splits - an ODD number - so the parity carried across replays
flipped on every ubatch. Each weight's input_cpy->data then alternated between bank 0 and
bank 1 between replays, so the CUDA-graph property check would see changed src0 pointers
and re-capture on every single prefill. That fails G-G ('graphs reused >= control') and,
worse, hides the re-capture cost inside the very wall being measured.

Resetting the counter at the top of ggml_backend_sched_compute_splits makes the bank a
deterministic function of the graph, so the captured pointers are stable across replays.
One line, and it removes the whole class regardless of which path reaches compute_splits.

Locally validated: g++ -fsyntax-only on ggml/src/ggml-backend.cpp exits 0.
…node src

Rig evidence (Stage 1b-R first measurement, artifact 13963d6): with
--moe-prefill-stream ON the measured behaviour was IDENTICAL to flag off -

  VRAM after load  6271 MiB both arms          (bank never allocated)
  graphs reused     760 both arms             (no re-capture)
  cold p4k prefill  167.70 off vs 167.83 on    (+0.08%)
  cold p12k prefill 167.66 off vs 169.08 on    (+0.85%)

i.e. the staged path never engaged at all, so those numbers measure nothing about
Stage 1b-R. VRAM being byte-identical is the tell: a 2 x 450 MiB bank cannot be free.

Cause: the bank pre-scan ran inside ggml_backend_sched_split_graph AFTER pass 5, which
rewrites every node's src pointers in place (node->src[j] = tensor_id_copy(...), :1423).
So by scan time node->src[0] is the CUDA compute-buffer staging copy, not the host weight,
and ggml_backend_buffer_is_host() on it is false for every candidate -> bank_bytes stayed 0
-> no bank -> ggml_backend_sched_moe_stage_ready() returned false on its
"bank == NULL" check -> every split fell back to the legacy path.

Fix: scan split->inputs[], which still holds the ORIGINAL host weight pointers - the very
tensors compute_splits reads from in the used-expert staging path. Same eligibility
conditions (first node is MUL_MAT_ID, ne[2] > 1, host WEIGHTS buffer).

Not verified on the rig yet - this commit is what CI cycle 4 will build.
…ters

The decisive rig check on 524a765 is VRAM after load: 6271 MiB flag off vs 7171 MiB
flag on, i.e. exactly the predicted +900 MiB for a 2 x 450 MiB bank. That single number
proves the staged path engages; a log line makes it legible without arithmetic.

Adds three cheap counters and one line per graph:
  moe-stage: bank=<bytes> staged=<n> declined=<n>

staged == 0 with declined > 0 is the diagnostic that distinguishes 'the flag never
reached the hooks' from 'the hooks refused a specific weight', which is exactly the
ambiguity that made the 13963d6 run look like a null rather than a bug. Graphs that
stage nothing - including every decode graph - log nothing at all, so the line's mere
presence is the signal.

Locally validated: g++ -fsyntax-only exits 0.
… existing

Rig evidence on artifact 524a765, flag OFF, same binary as the flag-ON run:

  S1OFF vram_after_load = 7171 MiB      <- WRONG, must be 6271
  S1ON  vram_after_load = 7171 MiB      <- correct
  flags actually passed to S1OFF contained no --moe-prefill-stream (verified, count 0)

Cause: the bank pre-scan and ggml_backend_sched_moe_stage_ready() both gated on
`iface.set_tensor_async_staged != NULL && iface.stage_stream_wait_event != NULL`.
Those are a COMPILE-TIME property of the CUDA backend - they are present in every
build whether or not --moe-prefill-stream is on. So once the 524a765 fix made the
scan find candidates at all, the bank was allocated on every single run.

With the flag off the results were still correct - set_tensor_async_staged declines
when the flag is off, so every split fell back to the legacy blocking copy - but the
run was NOT byte-identical: it carried a 900 MiB bank it never touched, plus one
extra ggml_backend_synchronize per split from the stage_stream_wait_event refusal
path. That violates the hard requirement that flag off stay byte-identical, and it
also handicaps the G-P control arm, biasing the paired ratio AGAINST the flag.

Fix: a third optional iface slot, moe_stage_enabled, appended at the end of
ggml_backend_i like the other two, implemented for CUDA as
ggml_backend_cuda_moe_get_prefill_stream(). The scheduler now asks the backend whether it
wants staged staging AT GRAPH-SPLIT TIME before allocating anything. Flag off => no bank
allocated, no redirect, no extra sync => byte-identical.

Locally validated: g++ -fsyntax-only on ggml-backend.cpp exits 0, and a real
nvcc -c against CUDA 13.2.1 on ggml-cuda.cu exits 0.
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