diff --git a/.agents/engine-matrix.md b/.agents/engine-matrix.md index 8213ce1f30..88e809fa1b 100644 --- a/.agents/engine-matrix.md +++ b/.agents/engine-matrix.md @@ -281,7 +281,7 @@ claims it. | `ENG-LOAD-DIRECT-UPLOAD` | Cut the SECOND copy out of a safetensors load: a weight the device consumes VERBATIM VIEWS the read-only shard mmap (`OwnedBytes::Borrow`, keep-alive carried on `StTensor::mapping`) instead of being copied into an owned host buffer, so `ResidentWeight` uploads straight from the file mapping and the load moves those bytes ONCE. Backend- and arch-agnostic: it lives in the shared dense loader helpers, so every arch that routes through them inherits it. Additive leaf below `LOAD-SAFETENSORS`; the windowed source-page release is preserved and now also runs after the device upload. Non-verbatim paths (transpose, dtype conversion, dequant, concatenation, GGUF load-time repack) are unchanged and keep their copy. Also lands the measurement half of issue #150: per-phase load timing plus host-copy / borrowed / device-upload byte counters (`VT_LOAD_STATS`) | T1 | one move per byte: streamed shard iterator `vllm/model_executor/model_loader/weight_utils.py:905-954`; immediate copy into the destination parameter `vllm/model_executor/models/utils.py:252-279`; driver `vllm/model_executor/model_loader/base_loader.py:43-82` @ `555967922` | refcounted mapping `src/vllm/model_executor/model_loader/safetensors_reader.cpp:46-80,231-262`; byte counters `:337-400`; `BorrowStTensorBytes` + post-upload adoption/release `src/vllm/model_executor/models/qwen3_5_weights.cpp`; qualifying call sites `include/vllm/model_executor/models/dense_weight_loaders.h` (`LoadBf16Direct`, `LoadCtNvfp4W4A16`, `LoadCtMxfp4W4A16`), `src/vllm/model_executor/models/qwen3_5_dense_weights.cpp` (`LoadModelBf16Direct`, `LoadCtNvfp4Raw`), `src/vllm/model_executor/models/qwen3_5_weights.cpp` (35B `LoadBf16Direct`); upload counter `include/vllm/model_executor/models/dense_attn_block.h`; fp4 resident upload counter + post-upload residency `include/vllm/model_executor/models/dense_nvfp4_gemm.h` (`ResidentNvfp4`) and `src/vllm/model_executor/models/qwen3_5.cpp` (private `ResidentNvfp4`); shared checker text normalization `scripts/checker_text.py` | [mechanism gate](../tests/vllm/test_load_direct_upload.cpp#L1) 14/14, 183 assertions (178 through round 4) — the 6 borrow-mechanism cases, 4 post-upload residency cases that pin the adopt branch, its RELEASE-BEFORE-REASSIGN ordering and the `VT_ADOPT_DEVICE_BYTES` decoupling, 3 fp4-resident cases that pin `ResidentNvfp4`'s upload accounting, its `d_dev` publication, its adoption and the previously unexercised NON-borrowed/host-addressable regime, and 1 case that pins the GENERAL adopt branch's `MADV_DONTNEED` by OBSERVING RESIDENCY (`mincore()` over the host mirror's interior pages, glibc pinned to the sbrk arena so `free()` cannot return them by itself) — the RSS half of this row, which every value assertion was blind to. RED under eleven mutations, each applied alone with the binary rebuilt (a failed build aborts rather than re-running a stale one), tree md5-verified restored and re-GREEN after each. Mutations are named by the TEST CASE they land on, never by a line ref, because carried-forward line refs are how the counts below were twice recorded wrong: drop the size-identity check 1 case / 5 assertions; skip the borrow in `LoadBf16Direct` 2 / 7; delete the adopt branch 5 / 19; move the release after the `bytes` reassignment 5 / 7 (incl. the ordering assertions read from inside the munmap); move the release after the host-addressable early return but BEFORE the env one 2 / 3; move it after the `VT_ADOPT_DEVICE_BYTES` early return, i.e. after BOTH, 3 / 4; delete the general branch's `MADV_DONTNEED` 1 / 1; `ResidentNvfp4` drop both `AddDeviceUpload` 3 / 3; drop both `d_dev` publications 3 / 20; drop both `AdoptDeviceBytesAsHost` 3 / 16; all six at once 3 / 23. FOUR of those rows had been recorded wrong (1/1, 2/2, 3/7 and 3/3) — every one a count measured against an older suite and copied forward rather than re-measured; all eleven are measured on this tree. The `qwen3_5.cpp` duplicate of `ResidentNvfp4` is in an anonymous namespace no test can call, so it is held to the same invariant by [`scripts/check-fp4-resident-consistency.py`](../scripts/check-fp4-resident-consistency.py) (42-case mutation suite), which checks PER BUFFER inside each buffer's own `if (!w.d_)` upload block — body-wide matching let one surviving `AddDeviceUpload` satisfy both buffers, so dropping exactly one counter passed (reproduced against the real `qwen3_5.cpp` text: old checker exit 0, new exit 1). Nine drop-one/substitute-one mutations of the LIVE duplicate now go RED. Round 5 closed two holes in it. It matched RAW source, so a statement left behind as a COMMENT, inside `#if 0`, or inside `if (false)` read as present while the compiler saw a deletion; the clause matchers now run on [`scripts/checker_text.py`](../scripts/checker_text.py)'s `normalize_source`, which blanks all three IN PLACE so byte offsets and line numbers survive — `strip_comments` had existed as two byte-identical private copies (check-runner-routing-consistency.py, check-surface-coverage.py) and both now import the shared helper instead of a third copy being written. And the ordering clause required PUBLISH-before-ADOPT but not COPY-before-ADOPT, so a body whose adoption runs BEFORE its copy passed although the upload then reads pages the adoption already released; new clause (f) READ-FIRST covers it. WHICH MOTION produces that order is part of the claim, because the two are different mutations: SINKING `d.b.Copy(...)` to below `AdoptDeviceBytesAsHost` leaves the `d_dev` publication in place so ONLY clause (f) bites (MEASURED on the live duplicate, old exit 0 / new exit 1 — the 0/1 row below), whereas HOISTING the adoption above the copy also lifts it above the publication and trips the PRE-EXISTING clause (e), which the old checker already caught (MEASURED 1/1) and which is therefore no evidence for (f). The equivalent mutations of the SHARED `dense_nvfp4_gemm.h` copy are red at run time, MEASURED one at a time with the binary DELETED before each rebuild and the header md5-verified (`4665255f7af6f52254367f9118ad92ee`) before and after each: sink `packed`'s `Copy` 2 cases / 2 assertions, sink `scale`'s 2 / 2, sink BOTH 2 / 4 — the failures are `w..bytes.data()[0] == kSrcPattern` and `AllBytesMatchPattern(...)` in `fp4 resident: ResidentNvfp4 COUNTS its upload…` and `fp4 resident: a host-addressable device adopts an OWNED fp4 mirror too`, TWO per mutated buffer, so an ODD count is not obtainable; hoist `packed`'s adoption 3 / 8 and hoist both 3 / 16, wider because a null `d_dev` makes the adoption return immediately and also takes the NON-host-addressable case. This clause had been recorded as **2 cases / 3 assertions**, which is the count of the *release after the host-addressable early return, BEFORE the env one* row carried onto a different mutation — the same failure mode as the four rows above, found by a fifth reviewer and re-measured here rather than copied. MEASURED on the LIVE `qwen3_5.cpp` on disk, one mutation at a time, md5-verified restored after each (35b5ea250f490105d579f4ffb573aa36 before and after all eleven) — old checker exit / new checker exit: delete the packed adoption 1/1, `//` it out 0/1, `/* */` it out 0/1, `#if 0` around it 0/1, `if (false)` around it 0/1, `//` the packed upload counter 0/1, `//` the packed `d_dev` publication 0/1, `#if 0` around that publication 0/1, `if (false)` around it 0/1, SINK the packed `Copy` to below its adoption 0/1. That gate is STRUCTURAL: it guards the duplicate against DELETION — including deletion disguised as a comment, an `#if 0` or a never-taken branch — against gross substitution and against mis-ordering, NOT against corruption, and it does not model the preprocessor (extending it to arbitrary `#ifdef` conditions is DECLINED: `#ifdef VT_CUTLASS_NVFP4` around the live adoption stays exit 0 in both checkers, because a build configuration is not a disguised deletion). Run-time proof exists only for the shared copy. The `mincore()` residency case now also carries a RUNTIME allocator guard — `#if __GLIBC__` proves the headers, not that glibc's allocator is running — which goes red (1 case / 1 assertion) when a purging allocator is simulated; the `mallopt` calls leave glibc's `no_dyn_threshold` set for the process either way, MEASURED as not specific to `M_TRIM_THRESHOLD` (glibc 2.39, `mallinfo2().hblks` probe: no mallopt LIVE, `M_TRIM_THRESHOLD` DISABLED, `M_MMAP_MAX` DISABLED), so it is recorded rather than removed. Round-4 re-run on the dev box, CLEAN Vulkan/llvmpipe Release build: `test_load_direct_upload` 14/14 (178), `test_safetensors` 34/34 (79), `test_qwen36_weights` 7/7 (45), `test_vulkan_backend` 35/35 (2107), `test_backend_cross_device` 11/11 (132), `test_opt_paged_engine` **6/6 token-exact (96/96), 0 declines, device type 3**. Round-5 re-run on the same box, branch rebased onto `a0fa12c7`, all identical except `test_load_direct_upload` **14/14 (183)** — the five added assertions are the RSS-reclaim case's runtime allocator guard, no case-count change — plus `test_checker_text` 33/33 and `scripts/gen-vulkan-spirv.py --check` `committed SPIR-V is up to date` run with the pinned `~/tools/glslang-16.5.0/bin/glslang` (without it the script exits 1 on this tree, so the green is a real compile-and-compare and not a skip). Round 6 changed NO compiled file — this row, the spec, the `(f)` clause docstring and one checker-test name — and re-ran the whole battery on the branch rebased onto `e3cc4f64`, CLEAN Release Vulkan build, 0 warnings: every count above reproduces byte-for-byte, `check-fp4-resident-consistency` rc 0, its suite 42, `test_checker_text` 33, `test_check_surface_coverage` 46, `test_check_runner_routing_consistency` 31, SPIR-V check up to date, preflight all green. GB10 Vulkan gates on the changed tree: `test_vulkan_backend` 35/35 (2650), `test_backend_cross_device` 11/11 (132), `test_opt_paged_engine` **6/6 prompts token-exact (96/96), 0 declines, device type 3**. GB10 CUDA (cutlass+triton) full `ctest` **383/393**, BOTH SACRED gates PASS (`test_qwen36_paged_engine`, `test_qwen27_paged_engine`); all 10 failures reproduce with the same signature on a clean `origin/main` CUDA build. MEASURED 27B bf16 load **1.54x warm / 1.61x cold**, bytes moved **100.196 -> 81.260 GiB** | [specs/load-direct-upload.md](specs/load-direct-upload.md) | `ACTIVE` | `CLAIM-ENG-LOAD-DIRECT-UPLOAD` | | `LOAD-SAFETENSORS-DIRECT-DENSE` | Layer-bounded target-device loading for ordinary plain-BF16 Qwen3.5 dense safetensors on discrete CUDA; additive leaf below `LOAD-SAFETENSORS`, preserving windowed source release and owned-shard lifetime. Plain weights, stacked raw-NK owners, tied logits, logical resident state and same-queue layer staging are implemented and locally CUDA-gated. H32 Triton AOT, plain-BF16 decode graphs and ratio-4 FA2 repair the transplanted hot path; the broader row remains speed-gating | T1 | target-device model construction `vllm/model_executor/model_loader/base_loader.py:43-82`; incremental safetensors yield `vllm/model_executor/model_loader/weight_utils.py:820-954`; stacked/tied parameters `vllm/model_executor/models/qwen3_5.py:276-303,483-492` | load/dispatch `src/vllm/model_executor/models/qwen3_5_dense_weights.cpp:52-133,187-246,334-472`; discrete/unified classifier `src/vt/cuda/cuda_backend.cu:251-265`; plain execution/residency and graph selection `src/vllm/model_executor/models/qwen3_5.cpp`, `src/vllm/model_executor/models/qwen3_5_dense.cpp`; H32 recurrence `src/vt/cuda/cuda_gdn.cu`; ratio-4 FA2 `src/vt/cuda/cuda_flash_attn_fa2.cu`, `src/vt/cuda/cuda_paged_attn.cu`; exact benchmark corpus/output capture `examples/bench/bench_core.h:61-68,357-386,409-589`; reference metrics/token collector `tools/bench/vllm_closed_loop_metrics.py`; guarded driver and summarizer `tools/bench/run_qwen35_4b_compare.sh`, `tools/bench/summarize_qwen35_4b_compare.py` | [Real 4B graph/direct ON/OFF/eager gate](../tests/vllm/models/test_qwen35_plain_weights.cpp#L80) passes **3/3, 1672/1672**; [H32/GDN tests](../tests/vt/test_ops_gdn.cpp#L1) **10/10** flag and **66/66, 4242/4242** full; [paged-attention tests](../tests/vt/test_ops_paged_attn.cpp#L1354) **25/25, 454474/454474**. Final 18-leg root `/tmp/qwen35-main-final-fa2-20260725` plus stable vLLM confirmation: direct ON/OFF/vLLM-0.25 total **5769.99/5660.70/5849.80 tok/s**, output **638.03/625.94/646.85**, TPOT/ITL **43.72/43.84/38.55 ms**, peak PSS **2.406/8.592/7.662 GiB**, stable PSS **0.759/8.589/4.029 GiB**, VRAM **12850.7/12843.3/12942.7 MiB**. ON=OFF output IDs 128/128 every pair; ON is **+1.93%** total and cuts peak/stable PSS **72.0%/91.2%**. H32 AOT/graph/FA2 A/B gains are **+4.59%/+0.39%/+1.60%**. Graph-node trace has 453 launches and 200972 child kernels; local FA2 is 180.28 us/call vs vLLM 178.40, so the remaining **0.9864x** throughput and TPOT gap is host/engine-side. Sanitizer availability and external 27B/35B remain open | [plain-BF16 direct-load spike](specs/qwen35-plain-bf16-direct-load.md); [2026-07-25 evidence](../docs/bench-evidence/qwen35-4b-main-repair-20260725.md) | `GATING` | - | | `ENG-MOE-HOSTFREE` | MoE Marlin resident host-weight release: after `BuildMoeMarlinResident` uploads+repacks the routed experts to the device Marlin resident, free the per-expert fp4 HOST mirror (`OwnedTensor` packed+scale bytes) and `madvise(MADV_DONTNEED)` the pages back to the OS — returns the ~16.9 GiB steady 35B host double-store (`LoadNvfp4Raw` `MakeOwned` copies kept resident forever). Guarded to the committed Marlin path (`MarlinMoeEnabled()`; retained for the `VT_NVFP4_MARLIN=0` wmma fallback that re-reads them); `VT_MOE_HOST_FREE=0` A/B rollback. Realizes `release_host_weights_after_upload` for the dominant host consumer. **Item-2 (2026-07-19, `CLAIM-BACKEND-PLATFORM-2`): the host-free decision is now CONSUMED from `GetPlatform(d.q.device.type).residency_policy()` via `vllm::platforms::ShouldReleaseHostWeights(policy, MarlinMoeEnabled()/*kernel-path*/, VT_MOE_HOST_FREE/*env*/)` — `CudaPlatform` flag flipped false→true (reproduces today EXACTLY); `MarlinMoeEnabled()` stays the orthogonal KERNEL-PATH safety gate.** | T0 | streamed target-device weight construction `vllm/model_executor/model_loader/base_loader.py:43-82`; residency capability `vllm/platforms/interface.py:134-229`; Marlin MoE in-place repack (no host mirror) `vllm/model_executor/layers/quantization/utils/marlin_utils_fp4.py:375-434` | free region `src/vllm/model_executor/models/qwen3_5.cpp:3743-3781`; `OwnedTensor::ReleaseHost` decl `include/vllm/model_executor/models/qwen3_5_weights.h:65` + impl (madvise+swap) `src/vllm/model_executor/models/qwen3_5_weights.cpp:24`; public hook `Qwen3_5Model::PrepareMarlinResident` `src/vllm/model_executor/models/qwen3_5.cpp:9478` | `tests/vllm/test_qwen36_weights.cpp:283` (`ReleaseHost` frees buffer+capacity) + `:314` (`PrepareMarlinResident` release under Marlin / retention under `VT_NVFP4_MARLIN=0`, DGX release 27/27 + retention 15/15); DGX A/B (`VT_MOE_HOST_FREE`) 35B STEADY serving PSS **20.17→3.53 GiB** (root `dgx:~/work/mem35-hostfree`); token-neutral 315/315 + 235/235; c2 smoke clean; memcheck clean. Whole-window load-phase PEAK bounded by the `ENG-MOE-LOADSTREAM` follow-up. Ledger [parity-ledger.md#L521](parity-ledger.md#L521) | [moe-marlin-host-free.md](specs/moe-marlin-host-free.md) | `DONE` | `ac77bec` | -| `ENG-MOE-LOADSTREAM` | 35B load-phase PEAK-PSS interleave (follow-up to `ENG-MOE-HOSTFREE`): the steady free returns the routed-expert host mirror only AFTER the whole model loads, so whole-window `peak_pss`/`peak_rss` (~19.8 GiB) is still set by all N layers' ~256 experts host-coexisting at load. DEFER the routed-expert host copies (`LoadQwen3_5Moe` loads each layer WITHOUT experts + installs a per-layer `load_layer_experts` streaming closure that owns the mmap'd shards) and materialize ONE layer's experts inside `PrepareMarlinResident` immediately before that layer's device Marlin build + host free — so at most one layer's experts coexist on the host (peak ~ one layer, not all N). Device residents byte-identical (same source bytes, same per-layer build order). Non-CUDA/`VT_NVFP4_MARLIN=0`/no-Marlin build falls back to bulk host materialization (their forward reads the host bytes). 27B is a different loader (`LoadQwen3_5Dense`, true-W4A4) → unaffected; GGUF/synthetic/borrowed pass no shards owner → eager. **Item-2 (2026-07-19, `CLAIM-BACKEND-PLATFORM-2`): the per-layer interleave gate is now CONSUMED from `GetPlatform(queue.device.type).residency_policy()` via `vllm::platforms::ShouldInterleaveLoadStream(policy, MarlinMoeEnabled())` — reproduces the old `queue.device.type != kCUDA` OR `!MarlinMoeEnabled()` gate EXACTLY (unified/CPU retain-host ⇒ policy false ⇒ materialize-all fallback); the ~4 GiB load-peak win is preserved.** | T0 | streamed target-device construction `vllm/model_executor/model_loader/base_loader.py:43-82`; in-place Marlin repack, no host mirror `vllm/model_executor/layers/quantization/utils/marlin_utils_fp4.py:375-434`; residency capability `vllm/platforms/interface.py:134-229` | deferred field `include/vllm/model_executor/models/qwen3_5_weights.h:1163` (`Qwen3_5MoeWeights::load_layer_experts`); loader defer + closure `src/vllm/model_executor/models/qwen3_5_weights.cpp:331,399` (`LoadMoeExpertsInto`/`LoadQwen3_5Moe`); shared shards owner `include/vllm/model_executor/models/model_registry.h:60` + `src/vllm/model_executor/models/model_registry.cpp:219` (`ModelSource::FromSafetensorsOwned`) + `src/vllm/entrypoints/model_loader.cpp:2668` (`LoadedEngine::FromModelDir`); per-layer interleave + `MaterializeAllDeferredExperts` `src/vllm/model_executor/models/qwen3_5.cpp:4498,4508` (`PrepareMarlinResident`) | CPU coexistence-bound contract `tests/vllm/test_qwen36_weights.cpp:324` ("deferred routed-expert load: move-safe closure + bounded coexistence", peak==1 across the per-layer materialize→free loop, move-safe closure); clean `-Werror` CPU build 0 warn, full ctest (3 HTTP/engine-proc parallel-port flakes pass isolated), tools 164/164. **DGX PROVEN** (`~/work/vllm.cpp-mem35-loadstream` new vs `-parent` 7a1a6d6 eager, production flags CUTLASS sm120a+Marlin+FA2 sm_121a, one flock): 35B load-to-ready **peak RSS (VmHWM) 21.43 GiB → 4.19 GiB (−17.24 GiB / −80%, below vLLM 13.3 GiB)**; token BYTE-IDENTICAL both binaries — 35B `test_qwen36_paged_engine` 315/315 + 27B `test_qwen27_paged_engine` 235/235; **27B UNAFFECTED** (peak RSS 24.8 GiB, matches its baseline — dense loader, no deferral); `compute-sanitizer memcheck` on the deferred load path **0 errors / 315 assertions** (no use-after-free of the freed host bytes); weights unit 127 assertions (CPU coexistence peak==1 + DGX residency). `benchmark_binding=false` — the orchestrator re-grids the binding `peak_pss`/`peak_rss` axes to confirm the FAIL→PASS flip | [moe-expert-load-stream.md](specs/moe-expert-load-stream.md) | `ANCHOR-BACKFILL` | CLAIM-MEM35-LOADSTREAM | +| `ENG-MOE-LOADSTREAM` | 35B load-phase PEAK-PSS interleave (follow-up to `ENG-MOE-HOSTFREE`): the steady free returns the routed-expert host mirror only AFTER the whole model loads, so whole-window `peak_pss`/`peak_rss` (~19.8 GiB) is still set by all N layers' ~256 experts host-coexisting at load. DEFER the routed-expert host copies (`LoadQwen3_5Moe` loads each layer WITHOUT experts + installs a per-layer `load_layer_experts` streaming closure that owns the mmap'd shards) and materialize ONE layer's experts inside `PrepareMarlinResident` immediately before that layer's device Marlin build + host free — so at most one layer's experts coexist on the host (peak ~ one layer, not all N). Device residents byte-identical (same source bytes, same per-layer build order). Non-CUDA/`VT_NVFP4_MARLIN=0`/no-Marlin build falls back to bulk host materialization (their forward reads the host bytes). 27B is a different loader (`LoadQwen3_5Dense`, true-W4A4) → unaffected; GGUF/synthetic/borrowed pass no shards owner → eager. **Item-2 (2026-07-19, `CLAIM-BACKEND-PLATFORM-2`): the per-layer interleave gate is now CONSUMED from `GetPlatform(queue.device.type).residency_policy()` via `vllm::platforms::ShouldInterleaveLoadStream(policy, MarlinMoeEnabled())` — reproduces the old `queue.device.type != kCUDA` OR `!MarlinMoeEnabled()` gate EXACTLY (unified/CPU retain-host ⇒ policy false ⇒ materialize-all fallback); the ~4 GiB load-peak win is preserved.** | T0 | streamed target-device construction `vllm/model_executor/model_loader/base_loader.py:43-82`; in-place Marlin repack, no host mirror `vllm/model_executor/layers/quantization/utils/marlin_utils_fp4.py:375-434`; residency capability `vllm/platforms/interface.py:134-229` | deferred field `include/vllm/model_executor/models/qwen3_5_weights.h:1163` (`Qwen3_5MoeWeights::load_layer_experts`); loader defer + closure `src/vllm/model_executor/models/qwen3_5_weights.cpp:331,399` (`LoadMoeExpertsInto`/`LoadQwen3_5Moe`); shared shards owner `include/vllm/model_executor/models/model_registry.h:60` + `src/vllm/model_executor/models/model_registry.cpp:219` (`ModelSource::FromSafetensorsOwned`) + `src/vllm/entrypoints/model_loader.cpp:2672` (`LoadedEngine::FromModelDir`); per-layer interleave + `MaterializeAllDeferredExperts` `src/vllm/model_executor/models/qwen3_5.cpp:4498,4508` (`PrepareMarlinResident`) | CPU coexistence-bound contract `tests/vllm/test_qwen36_weights.cpp:324` ("deferred routed-expert load: move-safe closure + bounded coexistence", peak==1 across the per-layer materialize→free loop, move-safe closure); clean `-Werror` CPU build 0 warn, full ctest (3 HTTP/engine-proc parallel-port flakes pass isolated), tools 164/164. **DGX PROVEN** (`~/work/vllm.cpp-mem35-loadstream` new vs `-parent` 7a1a6d6 eager, production flags CUTLASS sm120a+Marlin+FA2 sm_121a, one flock): 35B load-to-ready **peak RSS (VmHWM) 21.43 GiB → 4.19 GiB (−17.24 GiB / −80%, below vLLM 13.3 GiB)**; token BYTE-IDENTICAL both binaries — 35B `test_qwen36_paged_engine` 315/315 + 27B `test_qwen27_paged_engine` 235/235; **27B UNAFFECTED** (peak RSS 24.8 GiB, matches its baseline — dense loader, no deferral); `compute-sanitizer memcheck` on the deferred load path **0 errors / 315 assertions** (no use-after-free of the freed host bytes); weights unit 127 assertions (CPU coexistence peak==1 + DGX residency). `benchmark_binding=false` — the orchestrator re-grids the binding `peak_pss`/`peak_rss` axes to confirm the FAIL→PASS flip | [moe-expert-load-stream.md](specs/moe-expert-load-stream.md) | `ANCHOR-BACKFILL` | CLAIM-MEM35-LOADSTREAM | | `LOAD-GGUF` | GGUF reader, dequantization, Qwen name transforms, embedded vocabulary | T0 | Pinned vLLM has no GGUF loader: `vllm/model_executor/model_loader/__init__.py:31-65`; compatibility reference is llama.cpp | `src/vllm/model_executor/model_loader/gguf_reader.cpp:302`; `src/vllm/model_executor/model_loader/gguf_dequant.cpp:223`; `src/vllm/model_executor/models/qwen3_5_gguf_weights.cpp:432`; `src/vllm/entrypoints/model_loader.cpp:240` | `tests/vllm/test_gguf.cpp:53`; `tests/vllm/test_gguf_dequant.cpp:25`; `tests/vllm/test_gguf_qwen36_loader.cpp:153`; real 35B `tests/parity/test_qwen36_gguf_engine.cpp:145` | `planned: specs/gguf-loader.md` | `PARTIAL` | - | | `LOAD-GGUF-MMPROJ` | A SECOND, `clip`-architecture GGUF projector file beside the language file, and the Qwen3-VL vision tower loaded out of it. **W1 LANDED (#821):** `EngineParams::mmproj_path` / `vllm_model_params.mmproj_path` (C ABI v22) / the server `--mmproj` flag name the file, `clip_mmproj_gguf.h` reads its `clip.*` metadata and `v.*` / `mm.*` tensors into the SHARED `multimodal::Qwen3VLVisionWeights`, and `LoadedEngine::vision_tower()` holds the result. The two-tensor temporal patch embedding (`v.patch_embd.weight` + `v.patch_embd.weight.1`) is INTERLEAVED per channel into the `[out, C*T*p*p]` conv3d operand the tower reads, and a file carrying only the first half is refused by name — the MuseGlimmer condition enforced rather than assumed. MuseGlimmer's own `MuseGlimmerRefuseMmproj` now has a PRODUCTION caller (routed on `clip.projector_type == "muse-glimmer"`), which is a change to MuseGlimmer's behaviour and is stated as one. **NOT supported:** no forward consumes the loaded tower yet — there is no multimodal request path on the C ABI and no GGUF image/video driver — and the COMMITTED 334-name manifest with its CI accounting is owed by `QUANT-QWEN38-27B-GGUF-ARM`, because the live confirmation below is env-gated on a NAS file and CI reads only the synthetic fixture. Auto-discovery of a sibling `mmproj*.gguf` is deliberately out of scope: a directory holding two unrelated models must not silently fuse them. First consumer is `Qwen3.8-27B` ([#821](https://github.com/mudler/vllm.cpp/issues/821)), whose `mmproj-BF16.gguf` (334 tensors, `clip.projector_type = qwen3vl_merger`, header-verified 2026-08-18: data end == file size 931,146,432) ships BOTH halves; MuseGlimmer's lacks the second | T0 | Pinned vLLM has no GGUF loader at all (`555967922`, `model_loader/__init__.py:33-49`), so the compatibility reference is llama.cpp `b10451` = `10bf611e5` (`PROJECTOR_TYPE_QWEN3VL`; the previously recorded `tools/mtmd/clip-impl.h:330` was read at the SUPERSEDED local fork `237ad9b96` and is owed re-anchoring, [#1003](https://github.com/mudler/vllm.cpp/issues/1003)) | the flag `EngineParams::mmproj_path` ([model_loader.h:1](../include/vllm/entrypoints/model_loader.h#L1)), the reader [clip_mmproj_gguf.cpp:1](../src/vllm/model_executor/models/clip_mmproj_gguf.cpp#L1), the open + refuse + read site `src/vllm/entrypoints/model_loader.cpp::LoadedEngine::FromModelDir` (the `.gguf` branch, after the device-fit refusal and BEFORE the tokenizer), the reader `src/vllm/model_executor/models/clip_mmproj_gguf.cpp::LoadQwen3VLVisionFromClipMmproj` + `::ClipMmprojVisionConfig` + `::RefuseUnsupportedClipMmproj`, the holder `include/vllm/entrypoints/model_loader.h::vision_tower` on `LoadedEngine`, the C face `include/vllm.h` `vllm_model_params.mmproj_path` (ABI v22) wired in `src/capi/vllm_c.cpp`, the server flag `src/vllm/entrypoints/openai/server_main.cpp` `--mmproj`, and the now-reached refusal `src/vllm/model_executor/models/muse_glimmer_gguf_weights.cpp::MuseGlimmerRefuseMmproj` | [test_clip_mmproj_gguf.cpp:1](../tests/vllm/models/test_clip_mmproj_gguf.cpp#L1) (9 cases / 272 assertions hermetic: the `clip.*` config mapping, the DeepStack discovery, the per-position patch-embedding interleave, every block/merger slot, and four refusals; the ninth is the LIVE confirmation, which skips loudly unless `VLLM_CPP_QWEN38_27B_MMPROJ` names the real `mmproj-BF16.gguf` and adds 43 assertions when it does — 334 consumed names == 334 shipped with nothing unread, the `clip.*` geometry, and the join checked at all 1,769,472 positions against F32 bytes read straight from the mmap. Renaming a tensor in the reader AND the fixture together leaves the hermetic gate green at 9/9 and reds only the live case, which is what the live case buys) and [test_gguf_mmproj_reach.cpp:1](../tests/vllm/entrypoints/test_gguf_mmproj_reach.cpp#L1) (6 cases / 19 assertions hermetic, all through `LoadedEngine::FromModelDir`; the sixth is the LIVE confirmation that the ENGINE holds the tower, and it skips loudly unless BOTH `VLLM_CPP_QWEN38_27B_GGUF` and `VLLM_CPP_QWEN38_27B_MMPROJ` name the real files, so the 19 assertions belong to the five hermetic cases). The two are separate targets on purpose: deleting the `LoadQwen3VLVisionFromClipMmproj` call site in `model_loader.cpp` reds the SECOND and leaves the FIRST fully green, which is the measured difference between gating a class and gating a capability. The port target for the vision config mapping is `src/vllm/model_executor/models/minimax_h3_vision_gguf.cpp::MiniMaxH3EncoderVisionConfig`, which builds the same `Qwen3VLVisionConfig` from `visual.*` | [quantized arms of Qwen3.8-27B](specs/qwen38-27b-quant-arms.md) | `PARTIAL` | - | | `LOAD-HF-BPE` | HF tokenizer.json byte-level BPE and incremental detokenization | T0 | `vllm/tokenizers/registry.py:176`; `vllm/tokenizers/hf.py:163`; `tests/tokenizers_/test_hf.py:18`; `tests/tokenizers_/test_detokenize.py:148` | `src/vllm/tokenizer/tokenizer.cpp:250,494,529`; `src/vllm/v1/engine/detokenizer.cpp:409` | `tests/vllm/test_bpe.cpp:226`; `tests/vllm/test_tokenizer_parity.cpp:66,74,82,90`; `tests/vllm/test_pretokenizer.cpp:130` | `planned: specs/hf-tokenizer.md` | `ANCHOR-BACKFILL` | - | diff --git a/.agents/evidence/eng-chunked-prefill-20261128/PROCESS.md b/.agents/evidence/eng-chunked-prefill-20261128/PROCESS.md new file mode 100644 index 0000000000..18af9290aa --- /dev/null +++ b/.agents/evidence/eng-chunked-prefill-20261128/PROCESS.md @@ -0,0 +1,273 @@ +# ENG-CHUNKED-PREFILL process record + +Status: BLOCKED — NEEDS_DECISION (reconciliation gate, spec §R1 / stop conditions) + +## 2026-11-29T05:02:07Z — reconciliation gate: source rule does not reproduce 1,2,6,4 + +- Verified llama.cpp pin: `abca6920035ed77c1d80eaf23d066e9d3a7c5b23` (matches + `oracle-revision.txt`). Upstream master of /home/lu_zero/Sources/llama.cpp is + `e300919cc`, so the rule was read from `git show abca69200:src/llama-batch.cpp` + (1629 lines extracted). +- Pinned rule, single-request prefill for a hybrid/recurrent model: + - `src/llama-context.cpp:351` — `cparams.n_ubatch = min(n_batch, n_ubatch or n_batch)` + → 16 with `-b 16 -ub 16`. + - `src/llama-memory-hybrid.cpp:70-100` (and recurrent twin + `src/llama-memory-recurrent.cpp:480-505`) — `init_batch` chooses + `split_seq(n_ubatch)` when all tokens are outputs, else + `split_equal(n_ubatch, sequential, n_keep_tail = n_rs_seq + 1)` + (`llama-memory-hybrid.cpp:81-92`). + - `src/llama-batch.cpp:665-834` (`split_equal`), `:836-876` (`split_seq`), + `:631-663` (`split_simple`), `:913` (`ubatch_add`). All three fill each + ubatch greedily up to `n_ubatch`; for one sequence and n_tokens(10) < + n_ubatch(16), every one of them yields exactly ONE ubatch of 10 tokens. + - Tap-build working tree diff (`/tmp/llamacpp-inkling-tap`, HEAD = abca69200) + touches only tap capture (`ggml-cpu`, `llama-graph.cpp` taps, + `llama-context.cpp:3131` post-compute dump). No split-path change. +- Both readings: + 1. Source rule: a 10-token prompt at `-b 16 -ub 16` forms ONE prefill + ubatch/graph of 10 tokens. No function in `llama-batch.cpp` at abca69200 + can emit the non-greedy sequence 1,2,6,4. + 2. Observed record (`focused.log` 2026-11-26): graphs of 1,2,6,4 tokens. + Note the sum is 13, not 10, and the record itself is internally tense + ("last graph holds positions 6..9" = 4 tokens, "6-token graph for 2..5" = + 4 positions), so the raw evidence for the sequence is a prose note, not + captured server output; no raw server log in the evidence directory shows + per-ubatch sizes. +- The live oracle (tap build, port 8100) was held by another agent's capture + (`/tmp/opencode/kdump2` flow) during this window, so it was not disturbed and + not probed. A decisive reproduction would be: fresh `llama-server` from the + tap build, `-b 16 -ub 16 --no-warmup`, the exact 10-token prompt, + `cache_prompt=false`, counting graph computes and their `n_tokens` with tap + logging of ubatch size. +- Per spec stop conditions ("The pinned llama.cpp split rule contradicts the + observed 1,2,6,4 sequence and no source-level explanation exists → stop, + report NEEDS_DECISION — never encode a fitted rule"), no split function was + implemented and no tests were written past the gate. T1–T4 remain RED-by- + absence; tree is unchanged from spec commit `462c25a16`. + +## 2026-11-29T09:40:00Z — decisive observation (coordinator-authorized experiment): multi-ubatch IS formed; mechanism is the SERVER checkpoint rule, not split_equal — returning NEEDS_DECISION + +Coordinator authorized one experiment on this host under `/tmp/bigmodel.lock` +(port 8177; the 8100 oracle of the other lane was untouched). One-line +`fprintf(stderr, "UBATCH_DBG n_tokens=...")` added at the ubatch consumption +point (`/tmp/llamacpp-inkling-tap/src/llama-context.cpp:2355`, `decode()` `do` +loop); later passes added capture-only fprintf in +`src/llama-memory-hybrid-iswa.cpp`, `src/llama-batch.cpp` (`split_equal`), and +`tools/server/server-context.cpp` (`FILL_DBG`/`DECODE_DBG`). Rebuilt +`/tmp/llamacpp-inkling-tap-build` CPU-only (`cmake --build -j16 --target +llama-server`). MemAvailable 190 GB before load. + +- Model: `/tmp/inkling-ref/Inkling-2-Mini-UD-Q4_K_M.mainline.gguf` (sha256 + matches the W1 golden record). Prompt: the EXACT raw golden + "Write a Python function that reverses a string." = the 10 prompt tokens + `[3711,149878,152743,150131,149890,156815,82,149878,150379,13]` from + `/tmp/inkling2-w1/tests/parity/goldens/inkling2_loop_gguf_q4km/llamacpp-abca69200.json`. +- Command (both passes identical): + `llama-server -m --host 127.0.0.1 --port 8177 --threads 1 --no-warmup + --ctx-size 256 --batch-size 16 --ubatch-size 16 --parallel 1 --no-webui` + then one POST `/completion` `{"prompt":..., "n_predict":1, + "temperature":0, "cache_prompt":false}`; server killed by PID after. +- **Observed ubatch sequence — IDENTICAL both passes: 2, 6, 4** + (`/tmp/ubatch-exp-pass1.log`, `/tmp/ubatch-exp-pass2.log`; passes 5-7 with + deeper instrumentation reproduce 6,4 for the request). `tokens_evaluated=10`; + server progress log: "prompt processing, n_tokens = 6, progress = 0.60". +- **Mechanism, pinned at abca69200 (NOT the batch splitter):** + 1. `tools/server/server-context.cpp` `pre_decode()` prompt-fill loop: with + checkpoints enabled (`do_checkpoint`; `n_ctx_checkpoints` default ON, + COMPLETION tasks) the loop breaks early via + `const int checkpoint_offsets[] = {4 + n_ubatch, 4};` when + `task->n_tokens() == prompt_n + min(n_batch, offset)` (ref upstream PR + #20288) — the server intentionally stops the batch 4 tokens before the + end so a checkpoint can be created. 10-token prompt at -b 16 -ub 16 → + first batch of 6 (10 = 6 + 4), second batch of 4. This is the 6,4. + 2. The 2-token graph happens BEFORE server init (log line 681 vs line 730 + "srv load_model: initializing"): a load-time probe compute in model load, + not a request graph. `--no-warmup` does not cover it. + 3. The old record's 1-token graph is the same class: a warmup/probe artifact + of the 2026-11-26 capture, not a prefill chunk. The "sums to 13, not 10" + tension is resolved — 1 and 2 were never prompt tokens. + 4. llama-side, `llama_memory_hybrid_iswa::init_batch` + (src/llama-memory-hybrid-iswa.cpp:92) selects + `split_equal(n_ubatch=16, !unified, n_keep_tail = n_rs_seq > 0 ? + n_rs_seq+1 : 0)` with **n_rs_seq = 0** for this model → n_keep_tail = 0 → + `split_equal` (src/llama-batch.cpp:665-833) fills greedily and NEVER splits + a 6- or 4-token batch: each server batch becomes exactly ONE ubatch + (instrumented: "SE_DBG break: exhausted"). +- **Why I stopped (dispatch branch rule):** reproducing the oracle's graph + boundaries requires encoding the SERVER checkpoint-offset rule + ({4+n_ubatch, 4}, gated on n_ctx_checkpoints and task type), while the + committed spec (`.agents/specs/chunked-prefill.md` Upstream anchors / + Design §3) pins the split rule to `llama-batch.cpp` and treats 1,2,6,4 as + prefill graph boundaries with warmup "excluded by --no-warmup" — which this + experiment falsifies (2 survives --no-warmup; 1 and 2 are probes). T1's + target sequence would encode probe artifacts + server segmentation policy, + semantics the spec does not authorize. Per the dispatch's contradiction + branch: STOP, NEEDS_DECISION. No T1-T4, no implementation, no commit. + Tree unchanged from spec commit 462c25a16 apart from this append. +- Tap tree state: capture-only fprintf at the sites named above; nothing + changed under the repo beyond this file. Experiment servers killed by PID; + bigmodel lock released. Logs: /tmp/ubatch-exp-pass1.log, pass2, pass5, + pass6, pass7. + +## 2026-11-29T07:20:00Z — implementation per the AMENDED spec (server checkpoint rule) + +Spec read WHOLE first (3a27457bf, the amended pin). The pinned rule is +UNAMBIGUOUS in source — no NEEDS_DECISION. Transcribed from +`git show abca69200:tools/server/server-context.cpp` `pre_decode()`: + +- **Design item 3 Outcome pin (file:line):** + `tools/server/server-context.cpp:4350-4360` — the `do_checkpoint` gate chain + (`n_ctx_checkpoints > 0` AND `task->type == SERVER_TASK_TYPE_COMPLETION` AND + the memory-shape condition `seq_rm_type FULL/RS || n_swa > 0`); + `tools/server/server-context.cpp:4479-4495` — the fill-loop early break: + `static const int checkpoint_offsets[] = {4 + n_ubatch, 4};` with + `const int n_last = std::min(n_batch, offset);` and the break when + `slot.task->n_tokens() == slot.prompt.n_tokens() + n_last` (upstream PR + #20288). `llama-batch.cpp` does NOT split here (n_rs_seq = 0 → greedy fill; + `src/llama-memory-hybrid-iswa.cpp:92`). +- **Mapping** (encoded in `include/vllm/v1/worker/gpu/prefill_chunks.h`): the + server batch (fill cap `n_batch`) is the scheduler step's scheduled range, so + `n_batch` maps to `max_num_batched_tokens` (the per-step budget); + `n_ubatch` maps to the new `EngineParams::prefill_ubatch` knob; the + `do_checkpoint` gate maps to `knob > 0` (0 = default = inert). +- T1 RED (verbatim, header absent): + `test_prefill_chunks.cpp:20:10: fatal error: vllm/v1/worker/gpu/prefill_chunks.h: + No such file or directory` — compilation terminated, ninja build stopped. +- T1–T4 GREEN: `test_prefill_chunks` 5 cases / 1274 assertions, 0 failed + (doctest Status: SUCCESS!), build Debug at /tmp/engcp-build. + - T1 table: (10,16,16)->{6,4}; (5,16,16)->{1,4}; (4)->{4}; (16,16,16)->{12,4}; + (20,16,16)->{4,12,4}; (40,16,16)->{16,8,12,4}; checkpoints off -> no split + (greedy n_batch caps only); 20x4x4 totals sweep summing exactly, no empty + chunk. One expected-vector slip ({12,12,6} for T=30) was corrected against + the RULE (break at 14 via offset 4+ub=20, then 12 via offset 4): {14,12,4}. + Never fitted to the observation; {6,4} falls out of the rule. + - T2: PlanPrefillChunks gates (knob/multi-req/decode/spec/mm/full-logits/ + live device ids) + SliceCommonAttentionMetadata row slices (query_start_loc, + num_computed = context before the chunk, seq_lens = context through it, + slot_mapping rows). + - T3: per-chunk GDN rebuild keeps the SAME compact state slot and flips + has_initial_state from context>0 — chunk k+1 addresses exactly the state + chunk k wrote (bit-exact by address identity; the GdnStateCache buffers are + persistent and written in place). + - T4: knob 0 -> empty plan -> exactly ONE forward per step. +- Production wiring (reachability): `EngineParams::prefill_ubatch` + (model_loader.h) -> `LoadedEngine` ctor body `runner_.set_prefill_ubatch` + (model_loader.cpp) -> `GPUModelRunner::prefill_ubatch_` (runner.h) -> + the forward site in `execute_model` (runner.cpp, the line that was + `ForwardLogits logits = ModelRegistry::Forward(*model_, forward_input);`): + plan computed BEFORE forward input; `chunk_plan.size() <= 1` takes the + existing single forward unchanged; otherwise one `ModelRegistry::Forward` + per chunk, in order, final chunk carrying the gathered last-prompt-token row. +- Focused gate: ctest + `^(test_prefill_chunks|test_runner|test_prepare_inputs|test_input_batch|test_engine_core|test_llm_engine|test_engine_types)$` + — 7/7 passed. +- Scope honesty (spec `## Owed`): the split is per the single-request prefill + population; multi-sequence mixed steps take the whole-step path (the range is + one stream to the rule — asserted in T1 so the boundary is pinned, not + accidental). Full-engine (synthetic-model) execution of T2/T3 was NOT run: + no synthetic-model engine fixture exists in-tree on CPU (the paged-engine + suites SKIP without real checkpoints), so T2/T3 are asserted at the + runner-slice/metadata level the production loop composes. Flagged for the + reviewer; the consuming model row's token gate remains the row's judge + (spec §Gates). +- Preflight `--staged` started in background after this entry. + +## 2026-11-29T07:55:00Z — preflight + commit + +- Preflight `--staged` run 1: FAIL check-agent-record — the 4-line loader + insertion shifted the ENG-MOE-LOADSTREAM record anchor + (`src/vllm/entrypoints/model_loader.cpp:2576` -> `:2580`, + `LoadedEngine::FromModelDir`). Repaired the anchor in + `.agents/engine-matrix.md` (record-staleness repair, checker untouched); + `check-agent-record --report` -> rot 0. +- Preflight `--staged` run 2: exit 0 ("ok 9 files changed, 680 insertions(+), + 3 deletions(-)"). +- Committed as `1f4069521` on `row/ENG-CHUNKED-PREFILL` (base spec commit + `3a27457bf`). No push. + +## 2026-11-29 (repair round) — F1 + F2 review findings repaired, commit 77472837c + +- F1 (reachability, critical): added + `TEST_CASE("ENG-CHUNKED-PREFILL: execute_model runs ONE forward PER CHUNK")` + in `tests/vllm/v1/worker/test_runner.cpp` (tail). It enters through the + PRODUCTION entry point `GPUModelRunner::execute_model` on CPU with a + counting synthetic model (`ChunkCountingModel` + `ModelFactory` whose + forward records call count and each call's token-row width; fixture + pattern from `test_device_token_ids_refusal.cpp`; the runner ctor routes + through `ModelRegistry::Prepare`, so the fixture also registers a no-op + prepare). 10-token single-request prefill, `max_num_batched_tokens=16`: + knob 0 → exactly 1 forward of 10 rows; `set_prefill_ubatch(16)` → exactly + 2 forwards, (6, 4) in order. This supersedes the earlier caveat that T2/T3 + were never exercised through full runner execution — the forward loop now + is. +- F1 mutation-RED (verbatim): with the PlanPrefillChunks call site neutered + at `src/vllm/v1/worker/gpu/runner.cpp:3302` (plan forced empty, exactly the + reviewer's mutation), the focused case REDs: + `ERROR: CHECK( g_chunk_forward_calls == 2 ) is NOT correct! values: CHECK( 1 == 2 )` + and `FATAL ERROR: REQUIRE( g_chunk_forward_token_counts.size() == 2 ) ... (1 == 2)` + (doctest, `Status: FAILURE!`, 1 failed / 1). After restoring runner.cpp the + case is GREEN (9/9 assertions, `Status: SUCCESS!`). +- F2 (T1 blind spot): two new subcases in + `tests/vllm/v1/worker/test_prefill_chunks.cpp` with n_batch >= n_ubatch + 4: + (T=12, b=16, ub=4) → {4, 4, 4} and (T=13, b=16, ub=8) → {1, 8, 4}; plus + (T=17, b=16, ub=32) → {1, 12, 4} pinning the min(n_batch, 4+n_ubatch) half. + NOTE: the finding's example value {8, 4} for (12,16,4) is wrong under the + pinned rule — offsets are iterated in {4 + n_ubatch, 4} order, first match + breaks (server-context.cpp:4480-4490 @ abca69200), so {4, 4, 4} is correct + and equally distinctive against the reviewer's {n_ubatch, 4} mutation. +- F2 mutation-RED: applying the reviewer's offset mutation + (`{n_ubatch, 4}` in `include/vllm/v1/worker/gpu/prefill_chunks.h:66`), + the new cases RED (`PrefillCheckpointChunks(12, 16, 4, true)` != {4, 4, 4} + and `(13, 16, 8, true)` != {1, 8, 4} — 1 failed / 5 cases); the min() case + stays green under that mutation by design (it pins the min() half, not the + order). Header restored byte-for-byte; GREEN (5/5 cases, 1277/1277). +- Focused set green after restore: test_prefill_chunks, test_runner (full + binary, 42 cases 1927 assertions), test_prepare_inputs — all + `Status: SUCCESS!`. +- Preflight `--staged` (PATH=/usr/share/pwsh-7.6): exit 0 after 1582 s. +- Committed as `77472837c` on `row/ENG-CHUNKED-PREFILL` + (`test(ENG-CHUNKED-PREFILL): reach the production chunk-forward loop and + pin the 4+ub offset order`). No push. + +## 2026-11-29 — consumer crash repair: hybrid empty slot_mapping in the slice + +- Consumer report: the Inkling-2-Mini exact-token gate SIGSEGVs inside + `vllm::v1::SliceCommonAttentionMetadata` on ce128190e with + `EngineParams::prefill_ubatch=16`; knob unset → gate green. gdb frame named + the slice, before any token comparison. +- ROOT CAUSE (source-level, no live gate run needed — the W1 tree + `/tmp/inkling2-w1` @ 25983a7bd carries the shape): `MakeInkling2LoopKVCache` + publishes the packed KV group as a `SlidingWindowSpec` (kind kSlidingWindow, + `inkling2_loop_registry.cpp:122`); the runner's group selector only takes + kFullAttention/kMlaAttention groups (`runner.cpp:846`), so + `full_attn_group_id_` stays the -1 sentinel; `MakeCommonAttentionMetadata` + casts the sentinel and the `group < step.slot_mapping.size()` guard is false + (`backend.cpp:86-89`), leaving the whole-step `slot_mapping` EMPTY. The + whole-step path passes it through untouched (the hybrid forward reads pages + through the runner's per-group tables); the chunk loop sliced + `cam.slot_mapping.begin() + begin` on the empty vector (`prefill_chunks.h:139` + pre-fix) — the consumer's SIGSEGV. T2's fixture populated slot_mapping, so + the shape was never covered: a fixture gap, not a transcription error. +- RED FIRST: new case `T2b: SliceCommonAttentionMetadata rides the empty + slot_mapping through` (`test_prefill_chunks.cpp:216`) builds the crashing + shape (10-token prefill, empty slot_mapping + empty block table). Verbatim + red on the pre-fix header (this build's allocator turned the UB into garbage + rather than a segfault; the consumer's binary died in the same assign): + `test_prefill_chunks.cpp:234: ERROR: CHECK( chunk.slot_mapping.empty() ) is + NOT correct! values: CHECK( false )` — 1 failed / 6 cases, `Status: FAILURE!`. +- FIX (`include/vllm/v1/worker/gpu/prefill_chunks.h:139-149`): guard the slice + on `!cam.slot_mapping.empty()`; an empty step-level slot_mapping rides + through empty — byte-identical to what the whole-step path hands the model. + Populated slot_mappings slice exactly as before (T2 unchanged, green). +- GREEN after: test_prefill_chunks 6/6 (1291/1291), test_prepare_inputs 9/9, + test_runner 42/42 (1927/1927) — all `Status: SUCCESS!`, CPU-only. +- Mutation checks (tree restored byte-for-byte after each, `cmp` verified): + 1. runner.cpp plan forced empty → F1 + (`ENG-CHUNKED-PREFILL: execute_model runs ONE forward PER CHUNK`) RED + (7 assertions, 2 failed, `Status: FAILURE!`); restored. + 2. header guard reverted (`if (true)`) → T2b RED (14 assertions, 2 failed, + `Status: FAILURE!`); restored. +- Focused gate re-run green after both restores. Preflight `--staged` + (PATH=/usr/share/pwsh-7.6) launched; result recorded below. +- Consumer re-verification of the staged W1 gate is OWED to the consumer + (no committed W1 config in this row). diff --git a/.agents/issues/ENG-CHUNKED-PREFILL/ISSUE-LOCAL-01M8FKEEA4VJBDK75035DR365J.md b/.agents/issues/ENG-CHUNKED-PREFILL/ISSUE-LOCAL-01M8FKEEA4VJBDK75035DR365J.md new file mode 100644 index 0000000000..65fa9b78c3 --- /dev/null +++ b/.agents/issues/ENG-CHUNKED-PREFILL/ISSUE-LOCAL-01M8FKEEA4VJBDK75035DR365J.md @@ -0,0 +1,19 @@ +ID: ISSUE-LOCAL-01M8FKEEA4VJBDK75035DR365J +Title: Prefill graph formation must follow the oracle server's ubatch chunking +Row: ENG-CHUNKED-PREFILL +State: CLOSED +Kind: bug +GitHub: - +Mirror: PENDING +Availability: FULL +Created: 2026-11-27 +Updated: 2026-11-29 +Closed: 2026-11-29 + +## Problem + +Our CPU prefill computes projections one token at a time (per-token matvec), so ggml-shape-dependent batched GEMM accumulation never matches a serving oracle that forms multi-token ubatches. Measured on Inkling-2-Mini W1: llama-server abca69200 with -b 16 -ub 16 forms prefill graphs of 1,2,6,4 tokens for a 10-token prompt; oracle Kcur differs from ours ~2e-4..4e-4 exactly at the positions the oracle's 6-token graph computes (evidence .agents/evidence of the W1 lane, focused.log 2026-11-27 per-position preconv/postconv table), and the exact token gate flips at raw j=5 (151663 vs 161721). Inputs match ULP; quantization matches byte-for-byte; the divergence is batch-shape-dependent matmul accumulation plus conv-state hand-off across graph boundaries. Our scheduler has token-budget chunking, but the prefill forward does not form ubatch-style multi-token graphs and --max-num-batched-tokens does not change graph formation. + +## Resolution + +Falsified by measurement (2026-11-28, consumer-measured): the premise that divergence comes from batch-shape-dependent matmul accumulation fixable by matching the oracle's graph boundaries does not hold on our side. The consuming Inkling-2-Mini W1 raw token gate ran with chunking ENGAGED at the oracle shape (knob=16): the runner's chunk plan was (1,4) for the 5-token prompt, two ModelRegistry::Forward calls, stderr-verified in the exact failing run (probe record, /tmp/inkling2-w1/docs/bench-evidence/new-candidate-inkling2-w1-20261125/focused.log lines 1041-1050, worktree a2fdde9f6), and the raw gate did NOT move (j=5 flips 151663 vs oracle 161721, unchanged), with the per-position pre/post-conv table byte-identical with and without chunking. Our quantized kernels compute each output row independently, so the oracle server's graph formation does not change per-row numerics here. CORRECTION (2026-11-30): the kernel-class hypothesis was ALSO falsified the same day — vt::cpu::QuantRepackMatmul proved bit-exact to ggml_gemm_q8_0_4x8_q8_0 on live rows (0/6400), and routing W1's Q8_0 projections through the repack class left the per-position table byte-for-byte unchanged. With inputs ULP, kernels bit-exact, and shapes engaged, the residue mechanism remains UNIDENTIFIED; the consuming row continues the hunt via a three-way against the oracle's own captured kproj inputs (fused-projection suspect), and owns the residue. The seam itself landed mutation-verified and inert-by-default; the falsification closes this issue per the falsified-by-the-tree rule. diff --git a/.agents/specs/chunked-prefill.md b/.agents/specs/chunked-prefill.md new file mode 100644 index 0000000000..db103f339e --- /dev/null +++ b/.agents/specs/chunked-prefill.md @@ -0,0 +1,242 @@ +# Row: ENG-CHUNKED-PREFILL — Prefill graph formation mirrors the serving oracle's ubatch chunking + +Status: DONE (spec committed before implementation; parity purpose falsified and closed 2026-11-29) + +## Now + +The seam landed mutation-verified and is inert by default (knob 0). The row's +parity purpose is falsified and closed: chunking does not change our per-row +numerics (see Outcome), so the W1 convergence gap is re-owned by the consuming +row's kernel-class wave (repacked vs vec_dot), not by graph formation. The +seam's remaining non-parity uses — mirroring oracle serving behavior for future +exact gates that pin `-b`/`-ub` — stand; no consumer currently depends on it. +Issue: `.agents/issues/ENG-CHUNKED-PREFILL/ISSUE-LOCAL-01M8FKEEA4VJBDK75035DR365J.md` +Base SHA: `891c4f27d` +Git integration: repository default — one pull request carries this spec and its +implementation (no recorded developer answer for this row, no split case). + +## Scope + +The engine's prefill path forms ONE forward per scheduler step: the runner packs +every scheduled token row into a single `ModelRegistry::Forward` call +(`src/vllm/v1/worker/gpu/runner.cpp:3273`, `prepare_inputs.cpp:2182`). A +whole-prompt prefill below the token budget therefore computes all positions in +one graph. A serving oracle that mirrors llama.cpp splits the same prompt into +ubatches (`-b`/`-ub`), and llama.cpp's batched GEMM accumulation is +shape-dependent: per-position results differ between one T=10 graph and the +ubatch sequence the oracle actually ran. + +This row adds the missing chunk dimension: a model-facing prefill ubatch +(`n_ubatch`) split at the runner/model boundary that mirrors llama.cpp's batch +splitting, so a gate that pins the oracle's serving batch shape can also match +its graph formation. `--max-num-batched-tokens` (the scheduler token budget) +stays the scheduler-level knob; this row adds the ubatch-level knob and its +split rules. + +In scope: + +- An engine-level prefill chunk size (the `-ub` analog), plumbed from + `EngineParams`/CLI through the runner to the forward boundary. +- The split rule that turns a scheduled token range into chunks, pinned from + llama.cpp source at the oracle revision (see Upstream anchors). The pinned + mechanism is the SERVER prompt-fill checkpoint policy, not `llama-batch.cpp` + splitting (amended 2026-11-29 after the decisive experiment, below). +- Conv/recurrent-state hand-off across chunk boundaries, mirroring how + llama.cpp carries hybrid state from one ubatch to the next. +- A focused test proving the chunk sequence for a fixed prompt shape. + +Out of scope: + +- Model-local rewrites of per-token loops (the consuming model port owns its + forward; the W1 Inkling-2-Mini row consumes this seam in its own change). +- Scheduler-level token-budget behavior (already landed, + `ResolveMaxNumBatchedTokens`, `model_loader.cpp:1365`). +- Partial-prefill concurrency (`max_num_partial_prefills`) — separate row. +- vLLM parity of the split rule itself: vLLM's CUDA path does not expose + llama.cpp's ubatch concept; this seam exists because our GGUF/CPU lane is + gated against llama.cpp. The vLLM-mirror obligation for scheduler chunking is + already discharged; this row is the llama.cpp-parity lane and states so + explicitly. + +## Upstream anchors + +Oracle: llama.cpp `abca69200` (pinned in the W1 row's evidence, +`docs/bench-evidence/new-candidate-inkling2-w1-20261125/oracle-revision.txt`). + +AMENDED 2026-11-29 — the decisive instrumented experiment (two clean passes, +exact 10-token golden prompt, `cache_prompt=false`, `--no-warmup`, `-b 16 +-ub 16`; logs `/tmp/ubatch-exp-pass{1,2,5,6,7}.log`; fprintf at the ubatch +consumption point `/tmp/llamacpp-inkling-tap/src/llama-context.cpp:2355`) +observed the oracle's real prefill graph formation and falsified the original +anchor: + +- The observed prefill sequence is **6, then 4** ubatches (`tokens_evaluated=10`). +- The 6/4 split is the **server prompt-fill checkpoint policy**: + `tools/server/server-context.cpp` `pre_decode()` breaks the fill early at + `checkpoint_offsets[] = {4 + n_ubatch, 4}` when + `task->n_tokens() == prompt_n + min(n_batch, offset)` (upstream PR #20288, + `n_ctx_checkpoints` default ON for completion tasks). It is NOT + `llama-batch.cpp` splitting: `llama_memory_hybrid_iswa::init_batch` + (`src/llama-memory-hybrid-iswa.cpp:92`) calls + `split_equal(n_ubatch, ..., n_keep_tail = n_rs_seq > 0 ? n_rs_seq+1 : 0)`; + with `n_rs_seq = 0` the fill is greedy — one ubatch per server batch + (`src/llama-batch.cpp:665-833`, `split_equal`, `split_seq`, `split_simple`, + `ubatch_add`). +- **The 1- and 2-token graphs in the old W1 record are LOAD-TIME PROBES**, not + prompt tokens: the 2-token graph fires before `srv load_model: initializing` + and survives `--no-warmup`. This resolves the record's internal contradiction + (1+2+6+4 = 13 ≠ 10). Probe graphs are excluded by CONSTRUCTION (they precede + serving), not by `--no-warmup` — the original spec's claim is falsified and + stands withdrawn. +- Server anchor: `tools/server/server-context.cpp` `pre_decode()` at + `abca69200` — the implementer pins the exact checkpoint-offset rule + (file:line) and encodes IT, not a fitted sequence. + +## Design + +1. `EngineParams` gains a prefill ubatch field (0 = default). CLI/server flag + follows the existing knob pattern (`--max-num-batched-tokens`, + `examples/bench/main.cpp:124`). Default preserves current behavior where the + whole scheduled range is one chunk (no silent gate change for existing + models). +2. The runner applies the split rule to the scheduled token range BEFORE + building forward input, producing an ordered chunk sequence. Each chunk is + one `ModelRegistry::Forward` call with the chunk's token rows. Conv/recurrent + state inputs (the model's cached-state slots) must be read and written at + chunk boundaries exactly as llama.cpp does: the state entering chunk k+1 is + the state chunk k wrote. +3. The split rule is transcribed, not invented: pin the llama.cpp rule from + source, record `file:line` in this spec's Outcome, and encode the rule in one + function with a table test. The observed 10-token/`-ub 16` sequence + (6, 4) is the concrete case; load-time probe graphs are excluded by + construction, not by `--no-warmup`. +4. Bit-parity contract: with the oracle's serving batch shape pinned + (`-b`/`-ub` equivalents) and this row's chunking enabled, a consuming model + port running the exact token gate must reproduce the oracle's graph + boundaries and its per-position arithmetic. The kernel-selection rule + (nrc by batch shape) is already landed in the tree + (`vt::cpu::QuantMmlaVecDot`, shape-selected). + +## Risks + +- R1: RESOLVED by the 2026-11-29 experiment — the observed sequence is server + checkpoint policy (`pre_decode()` `checkpoint_offsets`), which the original + reading missed; the 1/2-token graphs are load-time probes. The remaining risk + is checkpoint-policy gating (`n_ctx_checkpoints` defaults, task type): the + split rule must encode those gates, not a hard-coded {6,4}. If a gate is + ambiguous in source, stop and report `NEEDS_DECISION`. +- R2: Within-graph position dependence is not yet fully explained: in the W1 + per-position table, position 1 differs pre-conv at 2.0e-4 while position 0 + (same 6-token oracle graph; the old "2-token graph" attribution was a + load-time probe mislabel) matches at 9.1e-8. Chunking alone may not close the + residue. Mitigation: this row lands the seam + tests; + the consuming row's gate is the judge. If the gate stays red with boundaries + matched, the residue hunt returns to the consuming row with the new + instrument (planner-allocated wdata capture) — that is a stop condition for + THIS row's parity claim, not a failure of the seam. +- R3: Chunking the forward multiplies graph-build overhead per prefill. The + default (one chunk) must keep existing benchmarks byte-identical in behavior; + the enabled path is opt-in via the knob, and the consuming gate sets it to + the oracle's shape. +- R4: Conv-state hand-off across boundaries is where the postconv-only + differences (positions 2, 5, 6, 7 in the W1 table) live. The hand-off must be + proven state-exact, not approximately carried: the focused test asserts the + entering state of chunk k+1 equals the written state of chunk k bit-for-bit. + +## Tests + +Red-first, smallest failing test first: + +- T1: the split-rule function, table-driven: 10-token prompt with ub=16 yields + chunks (6, 4) under the pinned server checkpoint rule; boundary cases (prompt + <= ub, prompt == ub, prompt > ub with remainder, checkpoints disabled + (`n_ctx_checkpoints` off -> no split), multi-sequence ranges) each asserted + against the pinned rule. RED before the rule exists. +- T2: runner-level: with the knob set, one scheduled prefill step of N tokens + produces N_chunk forward calls with the pinned chunk sizes, in order. RED + before plumbing. +- T3: state hand-off: chunk k+1's input state equals chunk k's output state + (bit-for-bit on a synthetic model). RED before the hand-off exists. +- T4: default inertness: knob unset → exactly one forward call per step, + unchanged from today. Guards R3. + +## Gates + +- Full gate on the touched targets; preflight `--staged` before commit. +- The exact token gate that judges this row's parity is the consuming model + row's gate (Inkling-2-Mini W1: raw j=5 flips 151663 → 161721 with chunking + enabled at the oracle's shape). That flip is recorded here as evidence when + it lands; until then this row's own gates are T1–T4 plus the full suite. +- No tolerance change, no distributional gate. The gate is token-exact. + +## Evidence + +- W1 lane record: `/tmp/inkling2-w1/docs/bench-evidence/new-candidate-inkling2-w1-20261125/focused.log` + (2026-11-26 graph-boundary observation; 2026-11-27 per-position + preconv/postconv table; kernel four-way bit-identity; instrument attempts). +- Oracle server logs with `-b 16 -ub 16` behavior: same directory. +- Tap build: `/tmp/llamacpp-inkling-tap` (scratch worktree at `abca69200`), + captures under `/tmp/inkling-ref/master-abca69200/`. + +## Stop conditions + +- The pinned llama.cpp split rule contradicts the observed 1,2,6,4 sequence and + no source-level explanation exists → stop, report `NEEDS_DECISION` with both + readings. Never encode a fitted rule. +- Chunk boundaries match and the consuming gate stays red with a residue + explainable only by a new mechanism → this row lands its seam and tests, and + files the follow-up on the consuming row. Do not expand this row's scope into + kernel arithmetic (that lane is proven bit-identical already). +- Any change that would alter default-path behavior (knob unset) beyond the + declared inertness contract → stop, revise the spec first. + +## Owed + +- Split-rule mirror for multi-sequence mixed prefill/decode steps beyond the + single-request prefill case (T2 covers single-request; concurrency shapes are + a follow-up once a consuming gate needs them). +- vLLM-side anchor for the ubatch concept does not exist; if vLLM later gains a + matching surface, reconcile this seam onto it and record the change here. +- The seam's remaining NON-PARITY uses stand: mirroring oracle serving behavior + for future exact gates that pin `-b`/`-ub`. No consumer currently depends on + it; the parity use that motivated the row is closed (falsified, below). + +## Outcome + +What was built: the engine-level prefill chunk seam (`n_ubatch` analog), +plumbed from `EngineParams`/CLI through the runner to the forward boundary, +with the pinned server prompt-fill checkpoint split rule, conv/recurrent-state +hand-off across boundaries, and focused tests T1–T4. Mutation-verified (the +reviewer mutated each claimed guarantee and the focused gate detected every +mutation) and inert by default. + +What was measured (2026-11-28, consumer-measured): chunking does not change our +per-row numerics. The consuming Inkling-2-Mini W1 raw token gate ran with +chunking ENGAGED at the oracle shape (knob=16) — chunk plan (1,4), two +`ModelRegistry::Forward` calls, stderr-verified in the exact failing run +(probe record: `/tmp/inkling2-w1/docs/bench-evidence/new-candidate-inkling2-w1-20261125/focused.log` +lines 1041–1050, worktree `a2fdde9f6`) — and the raw gate did not move +(j=5 flips 151663 vs oracle 161721, unchanged), with the per-position +pre/post-conv table byte-identical with and without chunking. Our quantized +kernels compute each output row independently, so the oracle server's graph +formation does not change per-row numerics on our side. + +What was rejected and why: the row's parity premise — that divergence comes +from batch-shape-dependent matmul accumulation and exact parity needs our +prefill chunking to match the oracle's graph boundaries — is FALSIFIED by that +measurement. CORRECTION (2026-11-30): the kernel-class hypothesis was also +falsified the same day (QuantRepackMatmul bit-exact to the ggml repack gemm on +live rows; routing W1's Q8_0 projections through it left the table unchanged), +so the residue mechanism is UNIDENTIFIED and the consuming row continues via a +three-way against the oracle's own captured kproj inputs. Issue +`ISSUE-LOCAL-01M8FKEEA4VJBDK75035DR365J` closed on the falsification evidence +2026-11-29; this correction 2026-11-30. + +Why each default keeps its value: the knob defaults to 0 (inert) so the +declared default-path inertness contract holds — no existing gate or benchmark +changes behavior, which R3 required. The VT-style knob stays opt-in rather than +being removed: it is a faithful llama-server-behavior mirror (the pinned +checkpoint split rule), kept as the instrument for future llama.cpp-parity +gates that pin `-b`/`-ub`. The Gates section's expected W1 flip (151663 → +161721 with chunking) did not occur; that record stands as falsified evidence, +not a pending claim. diff --git a/include/vllm/entrypoints/model_loader.h b/include/vllm/entrypoints/model_loader.h index 68a7945b30..ad1f3e034e 100644 --- a/include/vllm/entrypoints/model_loader.h +++ b/include/vllm/entrypoints/model_loader.h @@ -189,6 +189,20 @@ struct EngineParams { // product let an 8x1024 (8192-token) prefill run in ONE step, blowing the GDN // prefill activation. int max_num_batched_tokens = 0; + // ENG-CHUNKED-PREFILL: the prefill ubatch (llama.cpp's `-ub` analog), the + // model-facing chunk size this row adds beside the scheduler token budget + // above. 0 = the DEFAULT and it is INERT: the whole scheduled range is one + // forward, byte-identical to before the field existed. >0 turns on the + // pinned llama.cpp server prompt-fill checkpoint split + // (`tools/server/server-context.cpp` `pre_decode()`, + // `checkpoint_offsets[] = {4 + n_ubatch, 4}` @ abca69200, upstream PR + // #20288): an eligible single-request prefill step runs one forward per + // checkpoint chunk, in order, so a gate pinning the oracle's serving batch + // shape (`-b budget -ub knob`) also matches its graph formation. See + // include/vllm/v1/worker/gpu/prefill_chunks.h for the transcribed rule and + // its gates. No CLI flag yet — the consuming model row sets it through the + // params struct. + int prefill_ubatch = 0; // Mirrors vLLM's tri-state --[no-]enable-prefix-caching resolution. Hybrid // and attention-free generation models default OFF at the parity pin; // decoder-only models default ON. An explicit value overrides the model diff --git a/include/vllm/v1/worker/gpu/prefill_chunks.h b/include/vllm/v1/worker/gpu/prefill_chunks.h new file mode 100644 index 0000000000..65da9b7470 --- /dev/null +++ b/include/vllm/v1/worker/gpu/prefill_chunks.h @@ -0,0 +1,158 @@ +// ENG-CHUNKED-PREFILL: the engine-level prefill chunking seam. +// +// Spec: `.agents/specs/chunked-prefill.md` (amended 2026-11-29). The pinned +// mechanism is llama.cpp `abca6920035ed77c1d80eaf23d066e9d3a7c5b23`'s SERVER +// prompt-fill checkpoint policy — `tools/server/server-context.cpp` +// `pre_decode()`, the `checkpoint_offsets[] = {4 + n_ubatch, 4}` early break +// of the fill loop (upstream PR #20288), NOT `llama-batch.cpp` splitting +// (with `n_rs_seq == 0` the fill is greedy; one ubatch per server batch). +// +// The rule, transcribed from the pinned source (server-context.cpp:4479-4495 +// @ abca69200): while filling a server batch up to `n_batch` tokens, AFTER +// each pushed token break early when +// +// task->n_tokens() == slot.prompt.n_tokens() + min(n_batch, offset) +// +// for any offset in `{4 + n_ubatch, 4}` — the server intentionally stops the +// batch 4 (or 4 + n_ubatch) tokens before the prompt end so a context +// checkpoint can be created. `do_checkpoint` gates the whole block: +// `n_ctx_checkpoints > 0` AND the task is a COMPLETION AND the memory shape +// admits checkpoints AND no mtmd chunk intervened. In this seam the knob is +// the gate: `prefill_ubatch == 0` (the default) leaves `do_checkpoint == false` +// and the whole scheduled range is ONE chunk — byte-identical to today. +// +// Mapping to our engine: the server batch (fill cap `n_batch`) is the +// SCHEDULER step's scheduled token range, so `n_batch` maps to the per-step +// token budget (`--max-num-batched-tokens`), which caps the range exactly as +// the server's fill cap does; `n_ubatch` maps to `EngineParams::prefill_ubatch` +// (the knob this row adds). A whole-prompt single-request prefill step with +// `T` scheduled tokens therefore splits exactly as a server task of `T` +// prompt tokens does at `-b budget -ub knob`. +#ifndef VLLM_V1_WORKER_GPU_PREFILL_CHUNKS_H_ +#define VLLM_V1_WORKER_GPU_PREFILL_CHUNKS_H_ + +#include +#include +#include + +#include "vllm/v1/attention/backend.h" // CommonAttentionMetadata + +namespace vllm::v1 { + +// THE SPLIT RULE, transcribed (see the file comment for the pinned source). +// Simulates the server's prompt-fill loop over one scheduled token range of +// `total_tokens` rows: fill greedily up to `n_batch`, break early at the +// checkpoint offsets when `checkpoints_enabled`. Each element is one chunk's +// token count; the chunks concatenate to `total_tokens` in order. Every chunk +// is >= 1 (the break is only evaluated after a token is pushed), so the +// simulation always terminates. +// +// With `checkpoints_enabled == false` the answer is exactly one chunk — the +// `n_ctx_checkpoints`-off gate of the pinned rule. +inline std::vector PrefillCheckpointChunks(int total_tokens, + int n_batch, int n_ubatch, + bool checkpoints_enabled) { + std::vector chunks; + int filled = 0; // slot.prompt.n_tokens() so far, range-local. + while (filled < total_tokens) { + const int cap = std::min(n_batch, total_tokens - filled); + int n = 0; // tokens pushed into THIS server batch. + while (n < cap) { + ++n; // the loop pushes a token, THEN evaluates the breaks. + if (!checkpoints_enabled) continue; + // server-context.cpp:4480 `static const int checkpoint_offsets[] = + // {4 + n_ubatch, 4};` — parameterized here because OUR n_ubatch is the + // knob, not a context constant. + const int checkpoint_offsets[2] = {4 + n_ubatch, 4}; + bool should_break = false; + for (const int offset : checkpoint_offsets) { + const int n_last = std::min(n_batch, offset); + if (total_tokens == filled + n + n_last) { + should_break = true; + break; + } + } + if (should_break) break; + } + chunks.push_back(n); + filled += n; + } + return chunks; +} + +// THE RUNNER'S PER-STEP DECISION (spec Design 2): whether this step's +// scheduled range splits into checkpoint chunks, and into which. Empty vector +// == no split == ONE forward over the whole range — the T4 inertness +// contract. The gate mirrors the pinned `do_checkpoint` chain plus this +// runner's OWN applicability limits (spec `## Owed` defers everything but the +// single-request prefill): +// - knob == 0 -> no split (default inert). +// - multi-request / pure-decode / speculative / multimodal steps -> no +// split (the split rule is pinned per server task = per request; mixed +// steps are owed). +// - gathered-logits steps only: the chunk loop hands the sampler the FINAL +// chunk's lm_head rows (the last prompt token's row). A step that owes +// prompt logits takes the full-logits route, whose [T, vocab] output the +// seam cannot concat per chunk — those steps do not split. +// - stale host ids (async combine) or a LIVE device-id buffer -> no split; +// the device-id channel is a whole-step invariant the chunk loop does not +// maintain. +inline std::vector PlanPrefillChunks( + int prefill_ubatch, int n_batch, int num_reqs, int num_actual_tokens, + bool spec, bool multimodal, bool gathered_logits, bool device_ids_live) { + if (prefill_ubatch <= 0) return {}; + if (num_reqs != 1) return {}; + if (num_actual_tokens <= num_reqs) return {}; // pure decode (or empty). + if (spec || multimodal || !gathered_logits || device_ids_live) return {}; + return PrefillCheckpointChunks(num_actual_tokens, n_batch, prefill_ubatch, + /*checkpoints_enabled=*/true); +} + +// ONE CHUNK'S CommonAttentionMetadata, sliced from the whole-step one. The +// chunk covers token rows [begin, end) of the single request's packed stream. +// Field semantics preserved (see the struct's comments): +// - seq_lens: context THROUGH the chunk's last token +// (num_computed + end), not the whole step's. +// - num_computed_tokens_cpu: context BEFORE the chunk's first token +// (num_computed + begin) — the continuation marker that makes chunk k+1 +// read the state chunk k wrote. +// - query_start_loc: rebuilt {0, end-begin}; num_actual_tokens/max_query_len +// the chunk's own width; slot_mapping sliced to the chunk's rows. +// - the block table is request-level and rides through unchanged. +inline CommonAttentionMetadata SliceCommonAttentionMetadata( + const CommonAttentionMetadata& cam, int begin, int end) { + CommonAttentionMetadata chunk; + chunk.query_start_loc = {0, end - begin}; + chunk.query_start_loc_cpu = chunk.query_start_loc; + const int computed0 = cam.num_computed_tokens_cpu.empty() + ? 0 + : cam.num_computed_tokens_cpu[0]; + chunk.seq_lens = {computed0 + end}; + chunk.seq_lens_cpu = chunk.seq_lens; + chunk.num_computed_tokens_cpu = {computed0 + begin}; + chunk.num_reqs = 1; + chunk.num_actual_tokens = end - begin; + chunk.max_query_len = end - begin; + chunk.max_seq_len = cam.max_seq_len; + chunk.block_table_tensor = cam.block_table_tensor; + chunk.block_table_num_cols = cam.block_table_num_cols; + // HYBRID NO-FULL-ATTN-GROUP SHAPE (consumer crash, inkling2_loop): when the + // model's target attention group is not kFullAttention/kMlaAttention + // (inkling2_loop publishes its packed KV group as a SlidingWindowSpec), the + // runner's full_attn_group_id_ stays the -1 sentinel and + // MakeCommonAttentionMetadata leaves the step's slot_mapping EMPTY — and the + // whole-step path passes that empty vector through untouched. Mirror it: an + // empty step-level slot_mapping rides through empty. Slicing + // `begin() + begin` on the empty vector was the SIGSEGV. + if (!cam.slot_mapping.empty()) { + chunk.slot_mapping.assign(cam.slot_mapping.begin() + begin, + cam.slot_mapping.begin() + end); + } + chunk.causal = cam.causal; + chunk.uniform_spec_query_len = 0; + return chunk; +} + +} // namespace vllm::v1 + +#endif // VLLM_V1_WORKER_GPU_PREFILL_CHUNKS_H_ diff --git a/include/vllm/v1/worker/gpu/runner.h b/include/vllm/v1/worker/gpu/runner.h index 4eb4182e47..98b85a90c2 100644 --- a/include/vllm/v1/worker/gpu/runner.h +++ b/include/vllm/v1/worker/gpu/runner.h @@ -561,6 +561,12 @@ class GPUModelRunner final : public ModelRunnerBase { void set_kv_connector(kv_offload::KVConnector* connector) { kv_connector_ = connector; } + + // ENG-CHUNKED-PREFILL: wire the prefill-ubatch knob (the -ub analog). + // 0 (the default) leaves every step ONE forward — byte-identical. Called by + // the loader from EngineParams::prefill_ubatch. + void set_prefill_ubatch(int n_ubatch) { prefill_ubatch_ = n_ubatch; } + int prefill_ubatch() const { return prefill_ubatch_; } kv_offload::KVConnector* kv_connector() const { return kv_connector_; } // SPEC-DFLASH D5 (DF-ENGINE-INTEGRATION): wire the separately-loaded z-lab @@ -880,6 +886,11 @@ class GPUModelRunner final : public ModelRunnerBase { int max_num_reqs_ = 0; // Flattened-token bound for one step; sizes the W4 device input_ids mirror. int max_num_batched_tokens_ = 0; + // ENG-CHUNKED-PREFILL: the prefill-ubatch knob (EngineParams::prefill_ubatch, + // the -ub analog). 0 = default = no split: every step is ONE forward, + // byte-identical. >0 = the n_ubatch of the pinned llama.cpp server + // checkpoint rule (include/vllm/v1/worker/gpu/prefill_chunks.h). + int prefill_ubatch_ = 0; int64_t gdn_state_slots_ = 0; // Compact GDN state-slot allocator: request identity (req_id) -> slot in // [0, gdn_state_slots_); free list of unused slots. Keyed on the sequence, not diff --git a/src/vllm/entrypoints/model_loader.cpp b/src/vllm/entrypoints/model_loader.cpp index ae4f8476ce..e73e34f61a 100644 --- a/src/vllm/entrypoints/model_loader.cpp +++ b/src/vllm/entrypoints/model_loader.cpp @@ -2557,6 +2557,10 @@ LoadedEngine::LoadedEngine(HfConfig config, dflash_draft_->k); } } + // ENG-CHUNKED-PREFILL: wire the prefill-ubatch knob onto the runner. 0 (the + // default) leaves the runner untouched — every step is ONE forward, + // byte-identical. + runner_.set_prefill_ubatch(params.prefill_ubatch); // KV-EXTERNAL-CACHE (LMCache): build + wire the external KV connector when the // caller selected one via EngineParams::kv_transfer_config. Default (unset) // leaves kv_connector_ null and BOTH the scheduler and the runner unchanged — diff --git a/src/vllm/v1/worker/gpu/runner.cpp b/src/vllm/v1/worker/gpu/runner.cpp index cda9270e1a..61f778f3c0 100644 --- a/src/vllm/v1/worker/gpu/runner.cpp +++ b/src/vllm/v1/worker/gpu/runner.cpp @@ -36,7 +36,8 @@ #include "vllm/v1/kv_cache_dtype.h" // ResolveKvCacheDType (VT_KV_CACHE_F32 A/B) #include "vllm/v1/kv_offload/lmcache/lmcache_connector.h" // KV-EXTERNAL-CACHE worker store/load #include "vllm/v1/sample/ops/bad_words.h" // apply_allowed_token_ids (-inf mask) -#include "vllm/v1/worker/gpu/async_runner_flag.h" // VT_ASYNC_RUNNER predicate +#include "vllm/v1/worker/gpu/async_runner_flag.h" +#include "vllm/v1/worker/gpu/prefill_chunks.h" // ENG-CHUNKED-PREFILL the split rule // VT_ASYNC_RUNNER predicate #include "vllm/v1/worker/gpu/cudagraph_dispatch.h" // W6 (#1374) the graph-eligibility predicate #include "vllm/v1/spec_decode/rejection_sampler.h" // SPEC-REJECTION I3 verify half #include "vllm/v1/worker/gpu/spec_decode/mtp/speculator.h" // SPEC-MTP I5d MtpProposePrefill @@ -2949,6 +2950,12 @@ std::optional GPUModelRunner::execute_model( // group (gdn_group_id_ >= 0), so this block runs exactly as before — // behavior-preserving / byte-identical for the hybrid path. GDNAttentionMetadata gdn_meta; + // ENG-CHUNKED-PREFILL: the base the chunk loop rebuilds per-chunk GDN + // metadata from (the same remapped state-slot table). Set only on the + // non-spec hybrid path, which is exactly the population the chunk gate + // admits (PlanPrefillChunks refuses spec steps). + CommonAttentionMetadata gdn_chunk_cam; + bool gdn_chunkable = false; if (gdn_group_id_ >= 0) { int gdn_cols = 0; std::vector gdn_bt = @@ -3008,6 +3015,8 @@ std::optional GPUModelRunner::execute_model( } else { GDNAttentionMetadataBuilder gdn_builder; gdn_meta = gdn_builder.build(/*common_prefix_len=*/0, gdn_cam); + gdn_chunk_cam = gdn_cam; + gdn_chunkable = true; } } @@ -3324,9 +3333,6 @@ std::optional GPUModelRunner::execute_model( ConnectorLoadExternalKv(); } - // TT-NONROUTED-ATTRIBUTION (VT_FLINT_PHASE_TIMING): bracket the forward and - // measure the inter-step wall from the previous execute_model entry - the - // gap is engine orchestration the forward's own phase line cannot cover. const auto step_entry = std::chrono::steady_clock::now(); double step_wall_ms = 0.0; if (step_phase_on) { @@ -3336,7 +3342,78 @@ std::optional GPUModelRunner::execute_model( have_prev_step_entry = true; } const auto fwd_t0 = std::chrono::steady_clock::now(); - ForwardLogits logits = ModelRegistry::Forward(*model_, forward_input); + // THE FORWARD. DEFAULT (gather ON): the *Device entry points keep the + // [num_reqs,vocab] logits ON DEVICE and hand them to the sampler with no + // full-logits D2H. VT_LOGITS_GATHER=0: the host Forward returns full + // [T,vocab] logits and sample_tokens re-gathers on host (unchanged path). + // ENG-CHUNKED-PREFILL: when the prefill-ubatch knob is set and the step is + // an eligible single-request prefill, PlanPrefillChunks applies the pinned + // llama.cpp server checkpoint rule (tools/server/server-context.cpp + // pre_decode(), checkpoint_offsets {4 + n_ubatch, 4} @ abca69200 — see + // include/vllm/v1/worker/gpu/prefill_chunks.h) BEFORE forward input is + // built, and the range runs as one ModelRegistry::Forward PER CHUNK, in + // order. Chunk k+1's recurrent state input is the state chunk k wrote: the + // GdnStateCache buffers are persistent and written in place, and each + // chunk's rebuilt GDN metadata addresses the SAME state slot with + // has_initial_state set from the chunk's own context, so the hand-off is + // bit-exact by address identity. Full attention is paged per token row + // (slot_mapping sliced per chunk), so the KV chain continues across the + // boundary the same way. The sampler sees the FINAL chunk's gathered rows + // (the last prompt token's row), which is the only row the whole-step path + // produced too. Default (knob 0): plan empty -> exactly ONE forward, + // byte-identical. + const std::vector chunk_plan = + v1::PlanPrefillChunks(prefill_ubatch_, max_num_batched_tokens_, num_reqs, + attn_meta.num_actual_tokens, spec_on(), + mm_buffers.has_value(), gather, + device_input_ids != nullptr); + ForwardLogits logits; + if (chunk_plan.size() <= 1) { + logits = ModelRegistry::Forward(*model_, forward_input); + } else { + const int total = static_cast(token_ids.size()); + GDNAttentionMetadataBuilder chunk_gdn_builder; + int begin = 0; + for (const int len : chunk_plan) { + const int end = begin + len; + const std::vector chunk_tokens(token_ids.begin() + begin, + token_ids.begin() + end); + const std::vector chunk_positions(positions.begin() + begin, + positions.begin() + end); + const CommonAttentionMetadata chunk_cam = + v1::SliceCommonAttentionMetadata(attn_meta, begin, end); + // Only the FINAL chunk owes an lm_head row (the last prompt token), at + // its own local index. + const std::vector chunk_logits_indices = + (gather && end == total) ? std::vector{len - 1} + : std::vector{}; + const GDNAttentionMetadata chunk_gdn = + gdn_chunkable ? chunk_gdn_builder.build( + /*common_prefix_len=*/0, + v1::SliceCommonAttentionMetadata(gdn_chunk_cam, + begin, end)) + : gdn_meta; + ModelForwardInput chunk_input{ + .token_ids = chunk_tokens, + .positions = chunk_positions, + .attn_meta = chunk_cam, + .gdn_meta = chunk_gdn, + .attn_kv = attn_kv_, + .gdn_state = gdn_state_, + .config = config_, + .queue = queue_, + .logits_indices = chunk_logits_indices, + .num_reqs = 1, + .gdn_state_slots = gdn_state_slots_, + .gather_logits = gather, + }; + if (multi_cache_topology_) chunk_input.multi_kv = &multi_kv_index_; + // The seam runs one forward per chunk, in order; the sampler consumes + // the FINAL chunk's logits (the only row the whole-step path owed). + logits = ModelRegistry::Forward(*model_, chunk_input); + begin = end; + } + } if (step_phase_on) std::fprintf(stderr, "[FLINT-STEP] batch=%lld fwd_ms=%.3f step_wall_ms=%.3f\n", diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 25d401d788..461e812e56 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -2528,6 +2528,9 @@ vllm_cpp_add_test(test_host_buffer_staging vllm/v1/sample/test_host_buffer_stagi vllm_cpp_add_test(test_logits_processor_host_addressable vllm/v1/sample/test_logits_processor_host_addressable.cpp) vllm_cpp_add_test(test_prepare_inputs vllm/v1/worker/test_prepare_inputs.cpp) +# ENG-CHUNKED-PREFILL: the server-checkpoint split rule (T1) and the chunk +# slicing / planning / state-hand-off gates (T2-T4). +vllm_cpp_add_test(test_prefill_chunks vllm/v1/worker/test_prefill_chunks.cpp) vllm_cpp_add_test(test_combine_tokens vllm/v1/worker/test_combine_tokens.cpp) vllm_cpp_add_test(test_combine_row_predicate vllm/v1/worker/test_combine_row_predicate.cpp) # SPEC-DFLASH2 A2-2 (#2802): the spec-decode VERIFY route predicate, and the diff --git a/tests/vllm/v1/worker/test_prefill_chunks.cpp b/tests/vllm/v1/worker/test_prefill_chunks.cpp new file mode 100644 index 0000000000..59880e9729 --- /dev/null +++ b/tests/vllm/v1/worker/test_prefill_chunks.cpp @@ -0,0 +1,309 @@ +// ENG-CHUNKED-PREFILL: the split-rule and chunk-seam tests (spec §Tests T1–T4). +// +// ORACLE. llama.cpp `abca6920035ed77c1d80eaf23d066e9d3a7c5b23`, +// `tools/server/server-context.cpp` `pre_decode()` prompt-fill checkpoint +// policy (upstream PR #20288): the fill loop breaks early at +// `checkpoint_offsets[] = {4 + n_ubatch, 4}` when +// `task->n_tokens() == slot.prompt.n_tokens() + min(n_batch, offset)`, +// gated on `do_checkpoint` (n_ctx_checkpoints ON for COMPLETION tasks). The +// decisive instrumented experiment (2026-11-29, two clean passes) measured a +// 10-token prompt at `-b 16 -ub 16` splitting into server batches of 6 then 4 +// — this suite pins that rule, not a fitted {6, 4}. +// +// CPU-only, no model: every case is a pure function of the rule. +#include + +#include +#include + +#include "vllm/v1/attention/backends/gdn_attn.h" +#include "vllm/v1/worker/gpu/prefill_chunks.h" + +namespace { + +using vllm::v1::CommonAttentionMetadata; +using vllm::v1::GDNAttentionMetadata; +using vllm::v1::GDNAttentionMetadataBuilder; +using vllm::v1::PlanPrefillChunks; +using vllm::v1::PrefillCheckpointChunks; + +int Total(const std::vector& chunks) { + int t = 0; + for (const int c : chunks) t += c; + return t; +} + +// ONE whole-step CommonAttentionMetadata for a single request whose prefill +// runs positions [computed0, computed0 + T), mirroring what +// MakeCommonAttentionMetadata builds for a prefill-only step. +CommonAttentionMetadata OneReqCam(int computed0, int t, int block_table_cols) { + CommonAttentionMetadata cam; + cam.query_start_loc = {0, t}; + cam.query_start_loc_cpu = cam.query_start_loc; + cam.seq_lens = {computed0 + t}; + cam.seq_lens_cpu = cam.seq_lens; + cam.num_computed_tokens_cpu = {computed0}; + cam.num_reqs = 1; + cam.num_actual_tokens = t; + cam.max_query_len = t; + cam.max_seq_len = computed0 + t; + cam.block_table_tensor.assign(static_cast(block_table_cols), 7); + cam.block_table_num_cols = block_table_cols; + for (int i = 0; i < t; ++i) cam.slot_mapping.push_back(computed0 + i); + cam.causal = true; + return cam; +} + +} // namespace + +// ── T1: the split rule, table-driven ───────────────────────────────────────── +TEST_CASE("T1: PrefillCheckpointChunks transcribes the pinned server rule") { + SUBCASE("the concrete oracle case: 10 tokens, -b 16 -ub 16 -> (6, 4)") { + // The observed prefill sequence (2026-11-29 experiment, two passes): + // first batch stops at 6 because 10 == 6 + min(16, 4), i.e. 4 before the + // prompt end, so the checkpoint can be created; the second batch fills + // the remaining 4. + CHECK(PrefillCheckpointChunks(10, 16, 16, true) == + std::vector{6, 4}); + } + + SUBCASE("prompt shorter than ub still splits 4-before-the-end") { + // offset 4 fires at prompt_n == 1: 5 == 1 + min(16, 4). + CHECK(PrefillCheckpointChunks(5, 16, 16, true) == + std::vector{1, 4}); + // Prompts at or under 4 tokens never reach an offset boundary. + CHECK(PrefillCheckpointChunks(4, 16, 16, true) == std::vector{4}); + CHECK(PrefillCheckpointChunks(1, 16, 16, true) == std::vector{1}); + } + + SUBCASE("prompt == ub (16 at -b 16 -ub 16)") { + // The greedy cap never binds; the offset-4 break fires at 12. + CHECK(PrefillCheckpointChunks(16, 16, 16, true) == + std::vector{12, 4}); + } + + SUBCASE("prompt > ub with remainder: cap + offsets interleave") { + // T=20, B=16, ub=16: offset 4+ub=20 fires (min(16,20)=16) at n=4 -> (4); + // then offset 4 fires at 16 -> (12); remainder 4. 4 + 12 + 4 = 20. + CHECK(PrefillCheckpointChunks(20, 16, 16, true) == + std::vector{4, 12, 4}); + // T=40: the n_batch cap binds first at 16, then offsets take over: + // (16, 8, 12, 4). + CHECK(PrefillCheckpointChunks(40, 16, 16, true) == + std::vector{16, 8, 12, 4}); + } + + SUBCASE("F2: n_batch >= n_ubatch + 4 — the 4 + n_ubatch offset fires FIRST") { + // offsets are iterated in `{4 + n_ubatch, 4}` order and the FIRST match + // breaks (server-context.cpp:4480-4490 @ abca69200). With ub=4 the 8 + // offset fires before the 4 offset can, so T=12 splits into three 4s — + // NOT {8, 4}, which is what swapping the array to {n_ubatch, 4} yields. + CHECK(PrefillCheckpointChunks(12, 16, 4, true) == + std::vector{4, 4, 4}); + // Same ordering at ub=8: the 12 offset breaks at 1, then the 4 offset at + // 9. The {n_ubatch, 4} reading gives {5, 4, 4} here instead. + CHECK(PrefillCheckpointChunks(13, 16, 8, true) == + std::vector{1, 8, 4}); + } + + SUBCASE("F2: 4 + n_ubatch exceeds n_batch — the min() half pins the cap") { + // With ub=32, b=16 the first offset is 36 and min(n_batch, 36) == 16: the + // break fires at n == T - 16 == 1, so the FIRST chunk is 1 and the rest + // follows the 4 offset. Without the min() this offset could never fire + // inside one batch. + CHECK(PrefillCheckpointChunks(17, 16, 32, true) == + std::vector{1, 12, 4}); + } + + SUBCASE("checkpoints disabled -> no split (n_ctx_checkpoints off)") { + CHECK(PrefillCheckpointChunks(10, 16, 16, false) == + std::vector{10}); + CHECK(PrefillCheckpointChunks(40, 16, 16, false) == + std::vector{16, 16, 8}); + } + + SUBCASE("a multi-sequence range is one range to the rule (spec ## Owed)") { + // The seam currently mirrors ONE server task per step; a multi-request + // step's scheduled range is therefore applied to the rule as a single + // stream — the documented Owed boundary, asserted here so the behavior is + // pinned rather than accidental. + // T=30: offset 4+ub=20 fires (min(16,20)=16) at n=14; then offset 4 at + // 26; remainder 4. 14 + 12 + 4 = 30. + CHECK(PrefillCheckpointChunks(30, 16, 16, true) == + std::vector{14, 12, 4}); + } + + SUBCASE("every chunking sums to the total and has no empty chunk") { + for (const int t : {1, 2, 3, 4, 5, 6, 7, 10, 12, 16, 17, 20, 23, 40, 64}) { + for (const int b : {4, 8, 16, 32}) { + for (const int u : {1, 4, 8, 16}) { + const auto chunks = PrefillCheckpointChunks(t, b, u, true); + REQUIRE(!chunks.empty()); + CHECK(Total(chunks) == t); + for (const int c : chunks) CHECK(c >= 1); + } + } + } + } +} + +// ── T1b/T2 planning gate: the runner's per-step decision ──────────────────── +TEST_CASE("T1b: PlanPrefillChunks gates the split on the runner's limits") { + SUBCASE("knob unset (0) -> no split, ever (T4 inertness)") { + CHECK(PlanPrefillChunks(0, 2048, 1, 10, false, false, true, false).empty()); + CHECK(PlanPrefillChunks(0, 16, 1, 40, false, false, true, false).empty()); + } + SUBCASE("multi-request, pure-decode, spec, mm, full-logits, live device ids") { + CHECK(PlanPrefillChunks(16, 16, 2, 10, false, false, true, false).empty()); + CHECK(PlanPrefillChunks(16, 16, 1, 1, false, false, true, false).empty()); + CHECK(PlanPrefillChunks(16, 16, 1, 10, true, false, true, false).empty()); + CHECK(PlanPrefillChunks(16, 16, 1, 10, false, true, true, false).empty()); + CHECK(PlanPrefillChunks(16, 16, 1, 10, false, false, false, false).empty()); + CHECK(PlanPrefillChunks(16, 16, 1, 10, false, false, true, true).empty()); + } + SUBCASE("an eligible single-request prefill splits per the rule") { + CHECK(PlanPrefillChunks(16, 16, 1, 10, false, false, true, false) == + std::vector{6, 4}); + } +} + +// ── T2: the chunk slices the step's token rows exactly ────────────────────── +TEST_CASE("T2: SliceCommonAttentionMetadata yields the chunk's token rows") { + const CommonAttentionMetadata cam = OneReqCam(/*computed0=*/100, /*t=*/10, + /*block_table_cols=*/4); + const auto plan = PlanPrefillChunks(16, 16, 1, 10, false, false, true, false); + REQUIRE(plan == std::vector{6, 4}); + + int begin = 0; + for (const int len : plan) { + const int end = begin + len; + const CommonAttentionMetadata chunk = + vllm::v1::SliceCommonAttentionMetadata(cam, begin, end); + CHECK(chunk.num_reqs == 1); + CHECK(chunk.num_actual_tokens == len); + CHECK(chunk.max_query_len == len); + CHECK(chunk.query_start_loc == std::vector{0, len}); + // Context before the chunk = computed0 + begin; through it = computed0 + end. + CHECK(chunk.num_computed_tokens_cpu == + std::vector{100 + begin}); + CHECK(chunk.seq_lens == std::vector{100 + end}); + // The chunk's KV slot ids are the step's rows [begin, end). + REQUIRE(chunk.slot_mapping.size() == static_cast(len)); + for (int i = 0; i < len; ++i) { + CHECK(chunk.slot_mapping[static_cast(i)] == 100 + begin + i); + } + // The block table is request-level and rides through. + CHECK(chunk.block_table_tensor == cam.block_table_tensor); + CHECK(chunk.block_table_num_cols == cam.block_table_num_cols); + begin = end; + } + CHECK(begin == 10); +} + +// ── T2b: the hybrid no-full-attn-group shape (the consumer crash) ──────────── +// +// The Inkling-2-Mini crash (ENG-CHUNKED-PREFILL, consumer report, gdb frame +// `vllm::v1::SliceCommonAttentionMetadata`): inkling2_loop publishes its packed +// KV group as a `SlidingWindowSpec` (kind kSlidingWindow), so the runner's +// `full_attn_group_id_` stays the -1 sentinel (runner.cpp only selects +// kFullAttention/kMlaAttention groups) and `MakeCommonAttentionMetadata` leaves +// the step's `slot_mapping` EMPTY (the `group < slot_mapping.size()` guard is +// false for the cast sentinel). The whole-step path passes that empty +// slot_mapping through untouched — the hybrid forward reads its pages through +// the runner's per-group tables, not through cam.slot_mapping. The chunk loop +// must mirror that: an empty step-level slot_mapping rides through empty, never +// sliced (slicing `begin()+begin` on an empty vector is the SIGSEGV). +TEST_CASE("T2b: SliceCommonAttentionMetadata rides the empty slot_mapping through") { + CommonAttentionMetadata cam = OneReqCam(/*computed0=*/0, /*t=*/10, + /*block_table_cols=*/0); + // MakeCommonAttentionMetadata with the -1 group sentinel: no slot rows, no + // block table — exactly the shape the whole-step path hands the model. + cam.slot_mapping.clear(); + cam.block_table_tensor.clear(); + cam.block_table_num_cols = 0; + const auto plan = PlanPrefillChunks(16, 16, 1, 10, false, false, true, false); + REQUIRE(plan == std::vector{6, 4}); + + int begin = 0; + for (const int len : plan) { + const int end = begin + len; + const CommonAttentionMetadata chunk = + vllm::v1::SliceCommonAttentionMetadata(cam, begin, end); + // THE WHOLE-STEP MIRROR: the step carried no slot rows, so the chunk + // carries none either — not a sliced-out-of-empty-vector read. + CHECK(chunk.slot_mapping.empty()); + CHECK(chunk.block_table_tensor.empty()); + CHECK(chunk.block_table_num_cols == 0); + // Everything the step DID carry is still sliced normally. + CHECK(chunk.num_actual_tokens == len); + CHECK(chunk.query_start_loc == std::vector{0, len}); + CHECK(chunk.seq_lens == std::vector{end}); + begin = end; + } + CHECK(begin == 10); +} + +// ── T3: the state hand-off across a chunk boundary ────────────────────────── +TEST_CASE("T3: chunk k+1 reads the state slot chunk k wrote") { + CommonAttentionMetadata cam = OneReqCam(0, 10, 4); + const auto plan = PlanPrefillChunks(16, 16, 1, 10, false, false, true, false); + REQUIRE(plan == std::vector{6, 4}); + + // Per chunk, the runner rebuilds the GDN metadata from the chunk's cam with + // the SAME remapped state-slot table (one compact slot per sequence; the + // GdnStateCache buffers are persistent and written in place). + std::vector gdn_state_slots = {42}; // req 0 -> slot 42. + // The remapped state-slot table rides the block table's column 0. + cam.block_table_tensor[0] = gdn_state_slots[0]; + vllm::v1::GDNAttentionMetadataBuilder builder; + int begin = 0; + int prev_slot = -1; + int prev_has_initial = -1; + for (const int len : plan) { + const int end = begin + len; + const CommonAttentionMetadata chunk = + vllm::v1::SliceCommonAttentionMetadata(cam, begin, end); + const vllm::v1::GDNAttentionMetadata gdn = builder.build(/*common_prefix_len=*/0, + chunk); + // The chunk's recurrent input state is the slot table's entry, unchanged + // across chunks: chunk k+1 addresses exactly what chunk k wrote. + REQUIRE(gdn.prefill_state_indices.has_value()); + REQUIRE(gdn.prefill_state_indices->size() == 1); + const int slot = (*gdn.prefill_state_indices)[0]; + CHECK(slot == gdn_state_slots[0]); + // has_initial_state == "context before this chunk > 0": chunk 0 starts + // fresh; every later chunk CONTINUES the previous chunk's written state. + REQUIRE(gdn.has_initial_state.has_value()); + REQUIRE(gdn.has_initial_state->size() == 1); + const int has_initial = (*gdn.has_initial_state)[0]; + CHECK(has_initial == (begin > 0 ? 1 : 0)); + if (begin > 0) { + // THE HAND-OFF: the entering state (slot + continuation) is the state + // the previous chunk addressed — no reallocation, no remap, no fresh + // slot. The cache buffer itself is runner-persistent (written in place + // by the GDN kernels), so bit-exactness holds by address identity. + CHECK(slot == prev_slot); + CHECK(has_initial == 1); + } + prev_slot = slot; + prev_has_initial = has_initial; + begin = end; + } + CHECK(prev_has_initial == 1); +} + +// ── T4: default inertness ──────────────────────────────────────────────────── +TEST_CASE("T4: knob unset plans exactly ONE forward per step") { + // The runner consults PlanPrefillChunks BEFORE building forward input; an + // empty plan takes the existing single-forward branch byte-identically. + for (const int t : {1, 10, 2048}) { + CHECK(PlanPrefillChunks(/*prefill_ubatch=*/0, 2048, 1, t, false, false, + true, false) + .empty()); + } + // And a knob whose rule yields one chunk also stays on the single-forward + // branch (plan.size() <= 1). + const auto plan = PlanPrefillChunks(16, 2048, 1, 3, false, false, true, false); + REQUIRE(plan.size() == 1); + CHECK(plan[0] == 3); +} diff --git a/tests/vllm/v1/worker/test_runner.cpp b/tests/vllm/v1/worker/test_runner.cpp index d5d7b7c188..690f50196f 100644 --- a/tests/vllm/v1/worker/test_runner.cpp +++ b/tests/vllm/v1/worker/test_runner.cpp @@ -3609,3 +3609,92 @@ TEST_CASE("A2-2: the verify download staging is page-locked and a grow RETAINS t staging.Get(backend, 256); CHECK(staging.live_blocks() == 3); } + +// ─── ENG-CHUNKED-PREFILL F1 (reachability): the PRODUCTION chunk loop ──────── +// The other ENG-CHUNKED-PREFILL cases gate the pure rule and the seam helpers; +// none of them could see the runner's own chunk-forward loop at +// runner.cpp (the PlanPrefillChunks consult + the per-chunk Forward). A +// reviewer mutation that forces the plan EMPTY left every one of those green. +// This case enters through `execute_model` — the production entry point — with +// a counting forward, and asserts the NUMBER of ModelRegistry::Forward calls: +// one per chunk, with the chunk sizes in order, when the knob is set; exactly +// one when it is 0. +namespace { + +// A registration whose forward COUNTS that it ran and records each call's +// token-row width. The runner sees only LoadedModel + the factory table, so a +// fake with a counting forward is the whole fixture. +int g_chunk_forward_calls = 0; +std::vector g_chunk_forward_token_counts; + +vllm::ForwardLogits ChunkCountingForward(vllm::LoadedModel& model, + const vllm::ModelForwardInput& input) { + (void)model; + ++g_chunk_forward_calls; + g_chunk_forward_token_counts.push_back( + static_cast(input.token_ids.size())); + return {}; +} + +// The runner's constructor routes through ModelRegistry::Prepare, which +// dispatches on the registration's table — a no-op for this probe. +void ChunkCountingPrepare(vllm::LoadedModel& model, const HfConfig& config, + vt::Queue& queue) { + (void)model; + (void)config; + (void)queue; +} + +class ChunkCountingModel : public vllm::LoadedModel { + public: + explicit ChunkCountingModel(const vllm::ModelRegistration& reg) + : vllm::LoadedModel(reg) {} +}; + +} // namespace + +TEST_CASE("ENG-CHUNKED-PREFILL: execute_model runs ONE forward PER CHUNK") { + vllm::ModelFactory factory; + factory.prepare = &ChunkCountingPrepare; + factory.forward = &ChunkCountingForward; + constexpr std::string_view kCountingArch = "ChunkCountProbeModel"; + const vllm::ModelRegistration reg{kCountingArch, &factory, vllm::ModelInfo{}}; + + const HfConfig c = MakeConfig(); + const int kNumBatched = 16; + // A single fresh 10-token prefill: the row shape the oracle split (6, 4). + const auto MakeStep = [] { + NewRequestData p = MakeNewReq("P", {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {}, + /*num_computed=*/0, /*fa_blocks=*/{2, 3}, + /*gdn_block=*/1, Greedy()); + return NewStep({p}, {{"P", 10}}); + }; + + // THE DEFAULT (knob 0): exactly ONE forward over the whole range. + { + ChunkCountingModel model(reg); + GPUModelRunner runner(c, model, MakeKvConfig(c), Q(), + /*max_num_reqs=*/8, kMaxModelLen, kNumBatched); + g_chunk_forward_calls = 0; + g_chunk_forward_token_counts.clear(); + CHECK_FALSE(runner.execute_model(MakeStep()).has_value()); + CHECK(g_chunk_forward_calls == 1); + REQUIRE(g_chunk_forward_token_counts.size() == 1); + CHECK(g_chunk_forward_token_counts[0] == 10); + } + + // THE KNOB (prefill_ubatch 16): ONE forward PER CHUNK, (6, 4) in order. + { + ChunkCountingModel model(reg); + GPUModelRunner runner(c, model, MakeKvConfig(c), Q(), + /*max_num_reqs=*/8, kMaxModelLen, kNumBatched); + runner.set_prefill_ubatch(16); + g_chunk_forward_calls = 0; + g_chunk_forward_token_counts.clear(); + CHECK_FALSE(runner.execute_model(MakeStep()).has_value()); + CHECK(g_chunk_forward_calls == 2); + REQUIRE(g_chunk_forward_token_counts.size() == 2); + CHECK(g_chunk_forward_token_counts[0] == 6); + CHECK(g_chunk_forward_token_counts[1] == 4); + } +}