Files
leleka/docs/schedule-design.md
T

32 KiB

Schedule design for the Leleka serve runtime

Branch claude/schedule. Companion of docs/roofline.md (the ceilings and the per-step floors this schedule is judged against). Scope: prefill chunk and decode round on the RTX 5090 server first, the 3080 laptop second. Analysis only: nothing here is implemented yet; every "measured" number is cited to a job or log, every other number is labelled A (assumption) or E (estimate) and has a measurement named that replaces it. The Original's source under engine/strata/src was read, not modified.

0. What "ideal" means here

A schedule is ideal when each hardware resource works whenever there is work for it that the data dependencies allow, and the only waits left are true data dependencies. The resources:

resource actor works on
GPU SMs / tensor cores / HBM compute stream(s) mixers, GEMMs, MMQ, norms, attention
H2D copy engine (PCIe 5.0 x16) copy stream expert blobs, KV staging, small uploads
D2H copy engine same or second copy stream status words, rows for the CPU leg
host DRAM CPU pool threads + the DMA reads of the copy engine expert weights (the CPU leg reads, the DMA reads)
CPU cores (AVX-512) pool workers CPU-computed experts, finite scans, staging copies for pageable banks
host control threads launcher, issuer, status reader, publisher kernel launches, event bookkeeping, sampling, token publish

Two facts from the ceilings decide where the schedule matters:

  1. Prefill is balanced between PCIe and the GPU (50 GB of experts per chunk against about 0.7 s of floor GPU work at 8192 tokens), so a schedule that loses overlap pays the sum, and one that keeps both busy pays the max. The port pays 1.8-2.1 s, the Original 1.5 s, the max is 1.0-1.09 s (stream-all, 51 / 46 GB/s) or 0.67-0.74 s (routed-only, see 2.4).
  2. Decode is bound by host DRAM bandwidth for the experts that miss VRAM (CPU leg and DMA read the same DRAM, sum capped at 74.5 GB/s measured in the mix, jobs 909 and 987-b), plus a GPU dependency chain that today is serialized with the miss path (12.9 ms GPU-reach wait + 17.2 ms miss phase per window in the Original). A schedule can hide part of the chain under the DRAM time, but not more than the chain is long, and it cannot beat bytes / DRAM bandwidth.

The correctness constraint on everything below: same bytes in, same kernels, same reduction order. Only the time at which a kernel starts or a byte moves may change, never which arithmetic runs. Each design item states what it reorders and why that is numerically inert.

1. Streams, events, threads (the vocabulary used below)

  • S_c the compute stream (everything arithmetic; one stream is enough, the GPU is full when it has work).
  • S_x the expert copy stream (H2D). One stream saturates the link in the microbenchmarks (docs/roofline.md 1.1: 45.2 GB/s with two or three streams against 46.3 with one); a second stream is kept only for small latency-sensitive uploads that must not wait behind queued expert copies.
  • S_k the KV / state stream (KV staging in and out for streamed KV, GDN state mirror), low priority, independent of S_x ordering.
  • Events: copied[s], used[s] per ring slot (exactly the Original's); route[L] (router ids of layer L are in host-visible memory); layer_done[L].
  • Host threads: launcher (enqueues kernels, never blocks except on route[L]), issuer (keeps the copy stream fed, paced by used events, no blocking calls on S_c), status reader (reads accumulated device status words off the critical path), stager (pageable banks only: copies into pinned bounce buffers), pool workers (decode CPU leg), publisher (token publish, sampling bookkeeping).

2. Prefill chunk

2.1 The Original's schedule (prefill.cpp, read)

Prefill::run (prefill.cpp 998-): one compute stream m.cs, one copy stream m.copy.

  • Per chunk, with stream_all (T >= 1024, pinned source): the whole expert sequence of the chunk (every non-resident expert of every layer, id order, routed or not) is issued by a dedicated issuer thread (D-5) into a ring of ring_slots (384 slots when at least 90 % of the bank is pinned, else 96): a_issued/a_consumed atomics, the copy of entry k waits (cudaStreamWaitEvent(copy, used[k % ring])) for the compute stream's used event of entry k - ring, then records copied[k % ring]. Comment at 76-93: 384 slots measured +12 % over 96 on Q2_0.
  • Per layer: hyper-connection read (norm, down GEMM, silu, up GEMM, inject GEMM, mix), then GDN or QSA mixer, then the MoE half: router GEMM + top-10, shared expert GEMMs, cudaMemcpyAsync ids D2H, cudaStreamSynchronize(cs), host counting sort of the 81,920 (token, k) pairs, H2D of slot/src/bounds tables (lines 1525-1555), then per expert in id order: wait copied, gather_native (D2D copy of the blob into a 16-expert MMQ group slot), record used, and every 16 experts the group's gate/up MMQ, swiglu, quantize, down MMQ.
  • So the Original has exactly one host synchronization per MoE layer (48 per chunk) and otherwise runs ahead; the copy stream runs continuously through the mixers (the point of stream_all).
  • Costs it carries: all experts copied whether routed or not (50.3 GB per chunk for a bank with no resident hits, against about 34 GB routed at 8192 tokens, job 705), a 2 MB D2D gather per expert (512 per layer, about 25 k per chunk), one host sort per layer.
  • Measured: 8192-token chunk about 1.5 s (5,400-5,900 tok/s, docs/prefill-throughput.md); 180k prompt 39.4 s in 30 chunks of 6000 (job 916), i.e. 1.31 s per chunk at 49.3 GB streamed per chunk = 37.6 GB/s.

2.2 The port today (cuda-driver, claude/prefill-overlap, read-only)

  • The port reproduces the Original's ordinary walk as host-built command lists (COMMAND_CAP 2048, mmq_original_ring.rs) and the stream_all order (mmq_original_chunk_stream.rs). With the stream on (job 958/960, 4,385-4,495 tok/s at 8192-token chunks, depth 2) a chunk takes 1.82-1.85 s; with the per-layer ring 2.13 s.
  • Barrier inventory (job 953 PREFILL-SITE, one 8192 chunk): about 1,130 blocking host-device calls (H2D copies and D2H readbacks), of which per chunk: 188 shared-layer uploads, 144+144 expert-layer preparation uploads, 93+93 GR read status round trips, 92+92 and 70+70 GR inject round trips, 70 GDN produce readbacks, 60+60 QSA projection round trips, 48 each of MoE prepare/finish/finite/ finish_statuses (the finite readback alone 25.7 ms per chunk, because it waits for the whole queued GPU work). Blocking host time about 45 ms per chunk, but the real cost is the pipeline bubble each one opens: the compute stream cannot be fed ahead past a readback, and the H2D copy engine is a FIFO that small uploads queue behind (the overlap agent therefore limits the issuer to depth 2).
  • Every stage also drains with cuCtxSynchronize unless the chunk stream is registered as background (compute_drain.rs), which is the overlap agent's scoped-drain fix.
  • Host spans (job 960, stream on): attn_read 73, gdn 565 (incl. state_in 124), qsa 420, ffn_read 70, moe 660 (ring 500, spans 20, prepare 49, finish 38), inject 89 = 1.82 s total; the expert DMA is mostly hidden but the compute stages stretched by 100-180 ms each (qsa 241 -> 420, gdn 471 -> 565, state_in 40 -> 124): they now share the PCIe/DRAM/HBM paths with the copy stream and wait behind it in the FIFO.

2.3 Target schedule (dependency graph)

Steady state of layer L, with the roofline numbers of an 8192-token chunk (E: floor kernels; A: assumptions listed in roofline.md):

S_c : [HC read][mixer(L): GDN|QSA ][inject][HC read][router+top10][shared exp][ group MMQ 0 .. 31 ][combine+inject]
host:                                              | route[L] -> plan(L): sort + tables
S_x : ====== copy experts of L+1 .. L+2 into ring (continuously, never idle) ==================================
event:                                  copied[k] ----------------------^           used[k] -----> S_x refills slot

Rules:

  1. Compute never waits for the host except on route[L]. Everything that is not the routing sort is enqueued ahead by at least one layer. The sort for layer L is hidden behind the shared-expert GEMMs and the next HC read of the same layer that are already queued (about 0.5 ms of GPU work against about 0.15-0.2 ms of host sort + launch, E).
  2. The copy stream is a pure producer paced only by used events (device-side cuStreamWaitEvent), issuing whole layers of work in one go. Because no small upload sits behind it any more (rule 4), the issue depth limit of 2 is dropped: the issuer enqueues up to the ring capacity (batched cuMemcpyBatchAsync per group of 16 experts, three pieces per expert).
  3. The ring is the MMQ group layout. The expert blob is three pieces (gate, up, down; 3 x ~682 KB) in the bank. The copy engine can place each piece at any device address, so the issuer copies gate and up into grp_gu + q*gub and down into grp_d + q*db of a group slot directly. The 16-expert group is then consumed by MMQ with no gather_native: this removes about 25 k D2D copies and about 100 GB of HBM traffic per chunk (E: 2 x 2 MB x 512 x 48, about 65 ms of HBM time at the measured bandwidth plus 25 k launches of 3-4 us). Numerics unchanged: the same GGUF blocks end up at the same group-slot offsets (gather_native is a byte permutation for native packs; gather_strata_q2 is not a pure copy and keeps its kernel). Copy shape (measured, roofline.md 1.3). The DMA rate depends on the piece size and on the alignment of the source start: 3 x 682 KB pieces from unaligned offsets run at 40.3 GB/s, the same size from 4 KiB-aligned offsets at 47.7, 2 MB at 46.3 / 50.0, 8 MB and more at 51.3. The bank is built at load from the GGUF/KAR bytes, so it can be repacked with every expert piece starting on a 4 KiB boundary (padding under 0.2 %), which is worth +7 to +18 % of PCIe rate for free, and, because consecutive experts of one role are contiguous in the bank, stream-all can issue runs of 8-16 consecutive experts per role as one 8-15 MB DMA (51 GB/s) if the receiving ring is planar per role (or a pitched cudaMemcpy2DAsync into the interleaved group layout). The choice among raw / aligned / runs / pitched / cudaMemcpyBatchAsync is the content of job 9051; the schedule only requires that the issuer works in units of one group (16 experts) with at most 3-6 DMA descriptors per group.
  4. No host-to-device traffic on the compute path. Small tables (token ids, QSA step records, slot/src/bounds) are either built on the device (token ids and steps: one batched upload per chunk before the copy stream starts; bounds: device counting sort, 2.3.1) or read by the kernels straight from mapped pinned host memory (zero-copy loads, no copy engine involved). Status words are written by kernels to mapped host memory (zero-copy stores) and read by the status reader later. Result: the copy FIFO has no latecomers.
  5. Deferred finite/validation guards. The ~1,130 readbacks are the guards' status words. They become atomicOr into one device status block per chunk, copied to host once per chunk (and once per N layers if early abort matters), checked before the chunk's rows are published. Fail-closed is kept (nothing downstream of a failed chunk is published or committed, the session is discarded like today); only the point of detection moves from "next stage" to "end of chunk", and a failing chunk wastes at most one chunk of GPU time.
  6. Chunk-to-chunk continuity. Chunk c+1's expert stream starts while chunk c's last layers still compute (layer 0's experts of c+1 do not depend on c). Saves the ring-fill bubble (about 15-20 ms per chunk, E) and nothing else changes: chunk c+1's layer l still waits for chunk c's layer l state through stream order.
  7. No tiny tail chunks. A chunk costs a full PCIe pass of the bank whatever its size (job 915: the 1,695-token tail of the 100k prompt took 1.41 s, 1,203 tok/s). Choose the chunk plan with equal sizes (ceil(N / T_max) chunks), subject to the numerics note in roofline.md 4 (chunk size changes rounding; the Original's ladder is the reference).

2.3.1 The one required host dependency: routing sort

The MMQ launches need the per-expert row counts and offsets. Options, in order of preference: (a) keep the Original's host sort, hidden as in rule 1 (one route[L] wait per layer, no GPU bubble if the shared-expert work is queued first); (b) device counting sort (histogram, scan, scatter, about 20-30 us, E) plus a persistent MMQ launch that loops over a device-built tile list, removing the wait. (b) needs a kernel change in the MMQ driver (owner: prefill-kernels), it is bit-exact (the tile order within an expert is the same) and is optional once (a) leaves no bubble.

2.4 Ring sizing, lookahead and speculative fetch

Ring capacity. Let E be the experts copied per layer, s the blob size, B the copy rate, A the non-MoE compute time of a layer, M its MoE consumption phase. During A nothing is consumed; the copy engine moves min(ring, B*A/s) entries and then blocks. In the MoE phase the consumer drains the ring faster than B and then waits for the copy. Layer time is A + max(M, (E - ring) * s / B), so the copy engine never limits the layer iff

ring >= E - B*M/s            (slots; bytes = slots * blob size)

With the current kernels (M about 7 ms, A about 16 ms, B = 46 GB/s, E = 512): ring >= 342 slots = 0.7 GB; with floor kernels (M 5 ms, A 9 ms): ring >= 395 slots. The Original's 384 is therefore the right size and the port's ring must not be smaller. Because blobs differ per layer (1.51-2.66 MB), the ring should be a byte ring of about 0.9 GB, not slots of the maximum blob (384 x 2.66 MB = 1.0 GB). When the link is the slower side (3080 laptop, B 3-6 GB/s as found, 13-26 GB/s nominal) the layer is copy-bound whatever the ring and a ring of 2-3 groups (100 MB) keeps the engine busy.

Lookahead depth = ring capacity in layers = 0.7-0.9 GB / 1.05 GB per layer = under one layer. The copy stream therefore never needs the routing of the layer it is copying for, which is why stream-all works without a predictor.

Stream-all versus routed-only. The expert stream copies 1.05 GB per layer; the routing uses on average 68 % of the experts at 8192 tokens (34 GB per chunk, job 705) and 60 % at 2048. Copying only the routed experts would cut the PCIe floor from 1.0 s to 0.68 s per chunk. The routing of layer L is known only after its mixer, i.e. at the point where the copy engine should already be well into layer L; so routed-only needs a prediction with a repair path:

  • Predictor P1: router_L(x_in(L)) where x_in(L) is the layer-L mixer input (available one mixer earlier than the true router input). This is the Original's own RouterLookahead idea (expert_source.cpp, "the residual stream changes little from one layer to the next"), already used there only to warm file pages. One extra [8192 x 2560] x [2560 x 512] GEMM per layer is 21 GFLOP (0.1 ms).
  • Predictor P2: the routed set of the same layer in the previous chunk (chunks of one prompt see similar experts; free).
  • Policy: the issuer copies predicted_set(L) (union over the chunk's tokens, so a high recall is plausible: only the tail experts that few tokens use can be missed). After route[L] the true set is known; experts routed but not predicted are copied on demand into the next free group slots (cost: 41 us each on the wire plus the FIFO wait; E: at 2 % miss of 350 experts = 7 experts = 0.3 ms per layer = 14 ms per chunk), experts predicted but not routed are simply never consumed and their slot is reclaimed (cost: wasted PCIe, 41 us each).
  • Gate: do not ship until recall and precision are measured on real routing (LELEKA_TRACE_ROUTE_PREDICT, to be added in deliverable 3: per layer, per chunk: |routed|, |predicted|, |routed \ predicted|, |predicted \ routed|). Decision rule: routed-only wins iff wasted + missed bytes cost less than the unrouted 32 %, i.e. iff (|pred \ routed| + |routed \ pred|) < 0.32 * 512 per layer, with the on-demand misses charged double for the FIFO wait. Expected to hold with a wide margin; it is not measured yet.
  • Numerics: the predicted/unpredicted split changes only when a blob lands; the consumer still processes exactly the routed experts in id order with the same kernels.

Resident hits during prefill. The Original skips copying experts resident in the VRAM cache (host_res >= 0) but lends cache slots for the prompt's buffers and refills them afterwards (docs/serve-step-costs.md: refill 1.4 GB at 34 GB/s, 42 ms per request). At 8192 tokens every resident GB saves 20 ms of PCIe; about 10 GB resident (4,900 experts, 20 % of the bank) makes the chunk GPU-bound instead of PCIe-bound (roofline.md 3). The memory-safety agent's budget governor decides how much VRAM the chunk workspace may take; the schedule only asks that the prefill workspace is sized for the largest chunk actually planned, not for 8192 by default.

2.5 Sync points: which are real

sync today kept? replaced by
routing ids -> host sort (1 per MoE layer, 48) yes (or device sort, 2.3.1) route[L] event wait on the launcher thread only
GR read / inject finite status (about 560 round trips) no accumulated status block, read once per chunk before publish
GDN produce readback (70), QSA projection round trips (120) no same
MoE prepare / finish / finite / finish_statuses (4 x 48) no same; finite currently 0.54 ms each
shared-layer weight uploads (188 per chunk) and expert-layer prepare uploads (288) no persistent device copies of the dense weights (they are re-uploaded per chunk today: 6.5 + 7 ms, plus a bubble each)
cuCtxSynchronize in compute producers no event dependencies; at most one cuStreamSynchronize(S_c) at the end of the chunk
chunk end: drain, publish yes one wait per chunk
first-chunk finite admission of the expert bank (0.7-0.85 s once per process) no background thread at load, off the request path

2.6 Memory and pinned bytes

  • Device: ring 0.9 GB (E), group slots included; chunk workspace for 8192 tokens as today (the region); nothing else new.
  • Pinned host: nothing new on the 5090 (the bank is already the registered read-only file mapping; it is the DMA source). On a pageable bank (laptop) the stager needs pinned bounce buffers: ring depth in flight x blob = 64 x 2.7 MB = 170 MB, fixed.
  • Status block and tables: a few MB mapped pinned.
  • The prefetch design adds no host memory and moves no extra DRAM traffic beyond the wasted predicted-but-unrouted blobs.

2.7 Correctness argument

  1. Bytes: every copy reads the same bank bytes as today and writes them to the same group-slot offsets the gather wrote. The finite admission of a bank byte happens before its first use (unchanged; it moves to load time).
  2. Kernels: no kernel is replaced or reordered within a stream. The only cross-stream orderings are copied -> MMQ(group) and MMQ(group) -> used -> copy overwrite, expressed as event dependencies, so a slot is never overwritten before its last reader and never read before its last writer completes. These are the Original's own copied/used rules.
  3. Reductions: all float reductions stay inside single kernels (cuBLAS, MMQ, recurrence); chunk size and expert order are unchanged, so the accumulation order of every output is unchanged. Greedy ids and LELEKA_TRACE_PREFILL_R hashes of the final residual are the gate (bit-identical to the pre-change build at the same chunking; already used for jobs 960-962).
  4. Guards: deferred guards detect the same conditions on the same data; the difference is only latency of detection, and publication is gated on the chunk-end check.
  5. Speculation: a wrong prediction costs time only, because the consumer never consumes an unrouted expert and always waits for each routed expert's copied event.

3. Decode round

3.1 The Original's schedule (verify.cpp, read)

One round = apply_pending, verify window (up to 6 rows), accept, begin_adaptation (swap thread), commit graph (async), emit, draft (MTP seed + chain, each a graph with a host sync), join adaptation.

The window is one CUDA graph of 48 layers (record_window), plus a host loop that serves each layer (verify.cpp 1085-1180):

  1. GPU: pre(l) = HC read, mixer, router GEMV + top-10, doorbell_publish (ids, x, weights to mapped host memory, seq word), then the VRAM-hit grouped GEMVs wait for flag A.
  2. Host (one core, spinning with _mm_pause on seq): pool(...): split the misses between the PCIe leg and the CPU leg (pcie_frac 0.55), publish the plan (flag A), submit the PCIe DMA (fetch_dma: cudaMemcpyAsync per expert on copy_ plus a host function raising flag B; the port: one cuMemcpyBatchAsync + cuStreamWriteValue32), run the CPU experts on the pool workers, raise flag M when the rows are in mapped memory.
  3. GPU: hits, then waits flag B (PCIe landed) and runs the staged experts, then waits flag M, copies the CPU rows and combines, next layer.
  4. With two row groups (G = 2 for larger windows) group 1's pre(l+1) overlaps group 0's expert wait: the only software pipelining present. It also makes some experts be read twice by the CPU leg (CPU entries / experts = 9.4 / 6.7 = 1.4 in job 984).

Per window (job 984, T = 2.68 rows, 2048 slots): 32.6 ms = GPU-reach wait 12.9 + per-layer host 17.2 (CPU 16.6) + stage 0.2 + draft 1.2. GPU wait and host miss phase are strictly alternating, layer after layer: the GPU idles during the miss phase and the host idles (spinning, 19 ms per round) during the GPU chain.

3.2 Target schedule

Per layer, with the numbers of roofline.md 4 (E for floors):

S_c : [pre(L): mixer, router, doorbell] [hits + staged-landed experts]      [wait M] [combine] [pre(L+1) ...
host:                    | plan(L): classify; CPU jobs for the unpredicted misses ; DMA for mispredicts
S_x :  prefetch(L+1) ===============================>   (issued at doorbell(L), lands before doorbell(L+1))
pool:                              [ CPU leg: unpredicted misses of L ]

Items, with their bounds:

  1. Cross-layer weight prefetch (the only way to put DRAM to work during the GPU chain). At doorbell(L) the GPU also publishes the predicted top-10 of layer L+1 (router_{L+1}(mixed_L), one more 2560 x 512 GEMV on the same rows, about 3 us, the Original's RouterLookahead predictor but computed on the GPU, not on a host thread). The host DMAs the predicted non-resident experts into a prefetch area at once; when doorbell(L+1) rings they count as hits, and only the unpredicted misses go to the CPU leg (or to an on-demand DMA when cheaper). Bound: the prefetch can only use PCIe time that would otherwise be idle, about P * tau_gpu_chain bytes per layer (34 GB/s contended x 0.10-0.27 ms = 3.5-9 MB = 2-4 experts per layer) plus whatever the CPU leg's own duration allows; the layer time becomes tau = (m*s + C*tau_g) / (P + C) instead of tau_g + m*s / (P + C) with P + C capped at the DRAM bandwidth. For U = 23, h = 0.41 (m*s = 27.8 MB): with the measured chain (0.27 ms) 0.52 ms against 0.65 ms (-6 ms per window); with a 0.10 ms chain 0.43 against 0.48 ms (-2.3 ms); at most P/(P+C) = 0.46 of the chain is hidden, and only as much as the DMA leg has bytes for (roofline.md 4.3). It is an upper bound with perfect prediction: multiply the saving by the recall. Worth about 2-6 ms of a 25-32 ms window; it must not be built before the GPU chain and the handoffs are trimmed, because it shrinks as the chain shrinks.
  2. Shorten the chain (the larger lever once the mix is DRAM-bound). GPU-reach wait is 8.0 + 1.6 per row ms (job 984/985 fit); the HBM floor is 3.5-4 ms per window (5.2 GB of dense weights), and 1,200 kernels at the measured graph-chain gap are 2-3 ms. Fusions that preserve per-kernel arithmetic (RoPE+norm, quantize+MMVQ prologues, router+top-10 are already fused) and a lower gap (graph node chain gap 0.51 us measured, roofline.md 1.2: 1,200 kernels cost 0.6 ms of gaps; the 12.9 ms is kernel time and tails, not gaps) take the chain from 12.9 to about 6-7 ms (E).
  3. Handoff latency. Observed layer time 0.63 ms against 0.50 ms from bytes plus chain: about 0.13 ms per layer (6 ms per window) is doorbell visibility, plan, submit, flag raise, flag observe (each a PCIe round trip, 1-2 us measured as the doorbell RTT, roofline.md 1.2) plus the spin loops. Remedies that keep the semantics: write the plan from the GPU for fully resident groups (E-6 device_plan_ does this already), submit the DMA batch before the CPU job setup, raise flag B from the stream (cuStreamWriteValue32, done in the port) so the host never wakes for it, and have the CPU leg poll rather than sleep. Staging buffers and their hazards (needed by items 1 and 3). The PCIe leg lands experts in a staging area that the GPU reads in the PCIe grp stage of the same layer. With a prefetch for layer L+1 in flight while layer L's staged experts are still being computed, one area is not enough: use two areas by layer parity (each sized for the largest PCIe set of a layer, at most 24 experts x 2.66 MB = 64 MB), and order the DMA into area (L+1) & 1 after the compute stream's event "PCIe grp of layer L-1 done" (a device-side cuStreamWaitEvent, 1.5 us, no host involvement). That is the entire write-after-read rule; the read-after-write rule is the landing flag (cuStreamWriteValue32 behind the batch, already in the port). With the groups of a split window (G = 2) the area is further halved per group exactly as today (kStagingBlobs / 2). The Original's end-of-window cudaStreamSynchronize(copy_) ("no host function may raise flag B in the next window") becomes an event wait at the first DMA of the next window.
  4. Split by measured frontier, not by a fixed fraction. The PCIe/CPU split that minimizes the miss phase is where both legs end together at the contended rates (roofline.md 4.2): x* = P/(P + C) with P, C the rates measured with both legs active (job 987-b: 32 and 42 GB/s -> x* = 0.43); when the sum is DRAM-capped any x in [1 - C/D, P/D] ties. 0.55 is on the wrong side for DMA; 0.35 was better for the Original's copy kernel (which steals SMs), consistent with the sweeps in docs/decode-parity.md (DMA: 0.45 best). LELEKA_PCIE_AUTO should converge to x*; make its target the equalization of leg completion times per layer, with the worker count as the second variable (the sum P(N) + C(N) is the curve to maximize; microbenchmark mb_dram_pcie).
  5. No duplicate CPU reads. With G = 2 the CPU leg reads an expert once per group that needs it (1.4x entries). Keep one group for T <= 3 rows, and for larger windows de-duplicate experts across groups inside the pool call (one weight pass, both groups' rows).
  6. CPU workers: few, on both CCDs, spinning only where latency matters. DRAM sum is flat from one reader on (roofline.md 1.4), one CCD alone caps the CPU leg at 51-54 GB/s, and 16 workers on one CCD take the DMA down to 31 GB/s. Use the smallest worker count that sustains 40 GB/s of expert weights with the real IQ3 kernel (to be read from cpu.compute; I expect 4-8), spread over both CCDs; the host thread that waits for the doorbell spins (_mm_pause, 0.6 us one way) because a futex wake costs 1.2 us one way and a blocking-sync event wait 26 us against 4.6 us spinning (job 905); everything not on the per-layer critical path (adaptation, publisher, status reader) may block.
  7. Round level. The draft chain is 4-5 sequential graphs, each dominated by the head read over the 106k-id draft vocabulary (about 0.3 GB, 0.25 ms of HBM, A) and a host sync (0.68 ms observed per graph): keep the whole chain on the device (argmax token feeds the next embedding gather device-side, one sync per round instead of one per step; the Original and port sync per graph). Host bookkeeping (emit, token publish, suffix-drafter append, controller, adaptation start) is under 0.05 ms per round (docs/serve-step-costs.md) and must simply run while the draft chain executes on the device, never after it; the suffix proposal of the next round needs the append, so the append stays before the next window's input build. Adaptive-tier swaps (begin_adaptation) stay concurrent with the draft as today. Floor of draft + commit about 1.5 ms (A); observed 2.2 (port) / 1.2 (Original) ms.

3.3 Sync points in the decode round

sync today needed? note
GPU -> host doorbell per layer (seq) yes the router output is the data dependency; a spinning host sees it 1-2 us after the GPU writes
host -> GPU flag A/B/M per layer yes for the CPU leg and the DMA landing flag B already device-written in the port; flag A can be device-written when the plan is fully resident
cudaStreamSynchronize(copy_) at window end no event on the next window's first use of the staging area
cudaStreamSynchronize(cs_) at window end yes the host needs the sampled tokens to build the next round (accept test, suffix drafter)
per-graph syncs in the MTP chain partly one at the chain end if tokens are consumed device-side
commit graph async already keep
per-request verifier assembly (63 ms) and teardown no persistent verifier (owner decode-parity)

3.4 Correctness argument

Prefetch moves a blob earlier; the expert is computed by the same kernel (GPU grouped GEMV for hits/staged, CPU kernel for the CPU leg) on the same bytes. Which kernel computes an expert (GPU or CPU) is already a degree of freedom the Original exposes (the split changes with timing; outputs of the two paths agree bit for bit: the CPU kernels are the exact PreparedJobs). The unrouted-prediction case is numerically inert. The deferred items (publisher thread, chain on device) read the same tokens in the same order.

4. Where the port should deliberately differ from the Original

topic Original port should why / bound
prefill expert order stream-all (50 GB per chunk) routed-only with predictor + repair (after recall is measured) 1.0 s -> 0.68 s PCIe floor
prefill gather D2D gather of every blob to the MMQ group slot DMA straight into the group layout -100 GB HBM, -25 k launches per chunk
prefill host sort D2H + sync + host sort + H2D per layer same but hidden behind queued work, later device sort 48 syncs
guards per stage device status + host readback accumulated block, one readback per chunk removes ~1,130 round trips
H2D on compute path small uploads queue behind expert copies (hence issue depth 2) none (device-built or zero-copy) allows full-depth copy queue
dense weights per chunk uploaded per chunk in the port (188 + 288 H2D) resident once 13 ms and 476 bubbles
decode PCIe/CPU split fixed 0.55 equalize measured leg completion (x* = P/(P+C)) 0.43 at the contended rates
decode layer chain strictly serial GPU chain then miss phase prefetch next layer's predicted experts + shorter chain bounded by DRAM; 3-6 ms from prefetch, 5-6 ms from chain
CPU leg duplicate reads (G = 2) 1.4x entries dedupe across groups DRAM is the ceiling
MTP chain graph + host sync per step device-resident chain 1 sync per round
first-chunk bank admission on the request path (0.8 s) at load TTFT

5. What this needs measured before it is built (feeds deliverable 3)

  1. Recall/precision of P1 and P2 on real routing at 2048/4096/8192-token chunks and for decode windows (LELEKA_TRACE_ROUTE_PREDICT); decision rules in 2.4 and 3.2.
  2. S_x with a second stream, batched submit vs per-piece, on the actual registered bank (not the synthetic buffers): the production copy rate versus the microbenchmark ceiling (the gap, 30 versus 49 GB/s, is the first item of the target table).
  3. The kernel-level timeline of port and Original (ledger agent): which of the 1,130 readbacks open a real bubble.
  4. Decode: layer-completion times of both legs under contention with the real pool (spans cpu.plan/open/zero/compute/sink), to calibrate x* and the handoff term.