From 781c5b96229c628114a99292249f8547b1400c4a Mon Sep 17 00:00:00 2001 From: dongxinwen Date: Fri, 27 Nov 2026 12:36:19 +0800 Subject: [PATCH] Preserve two Engine guides required by inference benchmark design Keep the original DeepInfer and vLLM-RLT guides, provenance and evidence state. Verify installed group budgets, permissions and revision failures against the released benchmark dependencies. Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation) Signed-off-by: dongxinwen --- ...it-recurrent-kv-finalization.original.json | 130 ++++++++++++++ ...get-speculative-verification.original.json | 105 +++++++++++ .../budget-speculative-verification.md | 168 ++++++++++++++++++ .../audit-recurrent-kv-finalization.md | 134 ++++++++++++++ .../test_atomic_benchmark_engine_originals.py | 93 ++++++++++ 5 files changed, 630 insertions(+) create mode 100644 src/inferrsi/knowledge/atoms/audit-recurrent-kv-finalization.original.json create mode 100644 src/inferrsi/knowledge/atoms/budget-speculative-verification.original.json create mode 100644 src/inferrsi/knowledge/atoms/engines/deepinfer/budget-speculative-verification.md create mode 100644 src/inferrsi/knowledge/atoms/engines/vllm-rlt/audit-recurrent-kv-finalization.md create mode 100644 tests/knowledge/test_atomic_benchmark_engine_originals.py diff --git a/src/inferrsi/knowledge/atoms/audit-recurrent-kv-finalization.original.json b/src/inferrsi/knowledge/atoms/audit-recurrent-kv-finalization.original.json new file mode 100644 index 000000000..5d98a68b9 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/audit-recurrent-kv-finalization.original.json @@ -0,0 +1,130 @@ +{ + "authority": "checkout", + "metadata": { + "id": "audit-recurrent-kv-finalization.original", + "kind": "knowledge", + "entrypoint": "guide.md", + "title": "Audit vLLM-RLT synchronous early-exit KV propagation, later depth-specific attention reads, and request storage retirement. Use when shallow token exits leave deeper history or release order in question.", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/systems/engines/vllm-rlt/audit-recurrent-kv-finalization/SKILL.md", + "sha256": "fb59f58e1c1ee9490f9c933b9c5ac7788bff367511e6f947c96f53939fc8f521" + }, + { + "type": "git", + "url": "https://github.com/InferMatrixLab/vllm-rlt", + "commit": "4a350344027960a48384626aa646f1765fda6d4f", + "paths": [ + "README.md", + "LICENSE", + "NOTICE", + "vllm_rlt/core/kv_cache_manager.py", + "vllm_rlt/worker/model_runner.py", + "tests/test_kv_cache.py", + "pyproject.toml", + "vllm_rlt/config.py", + "vllm_rlt/engine/stage_engine.py", + "vllm_rlt/core/scheduler.py", + "vllm_rlt/worker/executor.py", + "vllm_rlt/attention/__init__.py", + "vllm_rlt/attention/backend.py", + "vllm_rlt/models/ouro.py", + "vllm_rlt/layers/__init__.py", + "vllm_rlt/__init__.py", + "tests/conftest.py", + "vllm_rlt/request.py", + "vllm_rlt/worker/metadata.py", + "vllm_rlt/kernels/paged_attention.py", + "vllm_rlt/worker/buffers.py" + ], + "readset": "references/source-notes.md", + "identity": "references/source-identity.json", + "license": "Apache-2.0", + "third_party_notices": "references/NOTICE.md", + "revision_precision": "full" + } + ], + "applicability": { + "scope": "Pinned vLLM-RLT native Ouro synchronous scheduling with host KVMetadata: LAST_EXITED propagation versus SHARED, later depth-specific Torch-reference attention and normal release/wait/free order. No speculation, connector, preemption, prefix sharing, split/packed prefill or graph/static-buffer path qualification.", + "prerequisites": "The selected native Ouro synchronous path uses host KVMetadata, no speculation/connector/preemption, atomic prefill and disabled graph/static-buffer/packed-prefill paths; changed execution conditions need a new bounded check.", + "input_contract": "Repository revision, model/configuration, recurrent-layer set, loop count, cache layout and block size, dtype/device, attention backend and effective flags, plus the traced token/depth/layer and its next consumer.", + "produced_artifact": "A bounded token/finalization/consumer/retirement trace separating source call order, observed data and written validity, completion evidence and remaining native model/backend/performance gaps.", + "failure_modes": "Substituting mark_finalized for K/V propagation, accepting allocated pages as a complete written prefix, applying LAST_EXITED copy expectations to SHARED, or treating event recording as completion can invalidate the ownership diagnosis.", + "refusal_point": "On a failed prerequisite or complete-prefix check, retain the first failing token/depth/layer and trace the missing operation. Stop the conclusion when flags or metadata ownership leave the selected path." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; native CPU/CUDA, model correctness/quality, performance and agent efficacy are not validated.", + "Allocated capacity, host written-position validity, copied K/V bytes, event recording and completed device work are distinct; host-row checks do not qualify DeviceKVMetadata.", + "Repository Apache-2.0 and retained model/configuration NOTICE attribution do not constitute a whole-tree or model-weight license audit.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "attribution": [ + { + "type": "git", + "url": "https://github.com/InferMatrixLab/vllm-rlt", + "commit": "4a350344027960a48384626aa646f1765fda6d4f", + "paths": [ + "README.md", + "LICENSE", + "NOTICE", + "vllm_rlt/core/kv_cache_manager.py", + "vllm_rlt/worker/model_runner.py", + "tests/test_kv_cache.py", + "pyproject.toml", + "vllm_rlt/config.py", + "vllm_rlt/engine/stage_engine.py", + "vllm_rlt/core/scheduler.py", + "vllm_rlt/worker/executor.py", + "vllm_rlt/attention/__init__.py", + "vllm_rlt/attention/backend.py", + "vllm_rlt/models/ouro.py", + "vllm_rlt/layers/__init__.py", + "vllm_rlt/__init__.py", + "tests/conftest.py", + "vllm_rlt/request.py", + "vllm_rlt/worker/metadata.py", + "vllm_rlt/kernels/paged_attention.py", + "vllm_rlt/worker/buffers.py" + ], + "readset": "references/source-notes.md", + "identity": "references/source-identity.json", + "license": "Apache-2.0", + "third_party_notices": "references/NOTICE.md" + } + ], + "empirical_validation": "not_run", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/systems/engines/vllm-rlt/audit-recurrent-kv-finalization/SKILL.md", + "byte_range": [ + 0, + 11778 + ], + "sha256": "fb59f58e1c1ee9490f9c933b9c5ac7788bff367511e6f947c96f53939fc8f521" + } + } + }, + "content": { + "guide.md": { + "path": "engines/vllm-rlt/audit-recurrent-kv-finalization.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/budget-speculative-verification.original.json b/src/inferrsi/knowledge/atoms/budget-speculative-verification.original.json new file mode 100644 index 000000000..86d43d4c5 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/budget-speculative-verification.original.json @@ -0,0 +1,105 @@ +{ + "authority": "checkout", + "metadata": { + "id": "budget-speculative-verification.original", + "kind": "knowledge", + "entrypoint": "guide.md", + "title": "Decide how many draft tokens to verify per decode step when acceptance varies by request and position. Use when an engine already runs a draft head with multi-token speculation and verification cost grows with query rows. Separates draft cost from verify cost, builds a cumulative-acceptance rate vector, fits a cost model, and allocates a per-step row budget.", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/systems/engines/deepinfer/budget-speculative-verification/SKILL.md", + "sha256": "6e0dfacc7aa59b383761798656fd52e99b66fc7794c65dc3fc4f1c180b73072c" + }, + { + "type": "git", + "url": "https://github.com/deepseek-ai/DeepInfer", + "commit": "8b16149741a4935e1dec8cea27853f273b374c5b", + "paths": [ + "csrc/engine/mtp_varlen.hpp", + "csrc/engine/scheduler.hpp", + "deepinfer/worker/worker.py", + "deepinfer/environ.py", + "deepinfer/sampling_params.py", + "deepinfer/model_executor/models/mtp/dflash.py", + "deepinfer/model_executor/layers/sampler.py", + "deepinfer/model_executor/layers/tilelang_ops/fused_sample.py", + "LICENSE" + ], + "readset": "references/source-notes.md", + "revision_precision": "full" + } + ], + "applicability": { + "scope": "Engines with multi-token speculative decoding whose verification forward cost grows with query rows", + "prerequisites": "A calibrated per-position acceptance signal; a measured (rows, step_time) curve; a handle on metadata construction", + "hardware": "Backend-independent procedure; the reference implementation targets NVIDIA SM100 and Ascend 950 only", + "input_contract": "Draft width and row representation, the defined individual/conditional versus cumulative acceptance semantics, verify rows/time curve, sampler cost and acceptance round actually available at schedule time.", + "produced_artifact": "A per-step verification row budget, per-request query lengths from one through draft_width plus one, cumulative acceptance vectors and predicted-versus-realized acceptance error logs.", + "failure_modes": "Confusing verification savings with reduced drafting, misreading confidence semantics or available rounds, allowing later-position confidence to select an earlier token, or generating non-prefix grants can invalidate the budget or sampling claim.", + "refusal_point": "Stop if unthrottled drafting or sampler cost dominates, the signal cannot be made cumulative, or no round supplies acceptance estimates; the procedure also does not apply without a per-step cost model." + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation and no reproduced gain.", + "The reference budgets verification rows only; draft compute is unchanged.", + "The budgeted path is off by default in the reference source.", + "Budgeting can lower accepted length; equal accepted length is not an acceptance criterion.", + "Per-position independence of the confidence used for verification is a correctness requirement, not only a scheduling convenience.", + "Cross-backend rejection-comparison parity is unproven; the reference has no equality assertion.", + "Numeric acceptance rates and warmup curves are deployment-specific and are not carried here.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "attribution": [ + { + "type": "git", + "url": "https://github.com/deepseek-ai/DeepInfer", + "commit": "8b16149741a4935e1dec8cea27853f273b374c5b", + "paths": [ + "csrc/engine/mtp_varlen.hpp", + "csrc/engine/scheduler.hpp", + "deepinfer/worker/worker.py", + "deepinfer/environ.py", + "deepinfer/sampling_params.py", + "deepinfer/model_executor/models/mtp/dflash.py", + "deepinfer/model_executor/layers/sampler.py", + "deepinfer/model_executor/layers/tilelang_ops/fused_sample.py", + "LICENSE" + ], + "readset": "references/source-notes.md" + } + ], + "empirical_validation": "not_run", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/systems/engines/deepinfer/budget-speculative-verification/SKILL.md", + "byte_range": [ + 0, + 15070 + ], + "sha256": "6e0dfacc7aa59b383761798656fd52e99b66fc7794c65dc3fc4f1c180b73072c" + } + } + }, + "content": { + "guide.md": { + "path": "engines/deepinfer/budget-speculative-verification.md" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/engines/deepinfer/budget-speculative-verification.md b/src/inferrsi/knowledge/atoms/engines/deepinfer/budget-speculative-verification.md new file mode 100644 index 000000000..fda422f49 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/engines/deepinfer/budget-speculative-verification.md @@ -0,0 +1,168 @@ +--- +name: budget-speculative-verification +description: Decide how many draft tokens to verify per decode step when acceptance varies by request and position. Use when an engine already runs a draft head with multi-token speculation and verification cost grows with query rows. Separates draft cost from verify cost, builds a cumulative-acceptance rate vector, fits a cost model, and allocates a per-step row budget. +metadata: + inferrsi: | + { + "tags": [ + "deepinfer", + "speculative-decoding", + "mtp", + "verification", + "cost-model", + "scheduling" + ], + "status": "candidate", + "empirical_validation": "not_run", + "profile": "local-skill-v1", + "schema_version": 1, + "kind": "skill", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "url": "https://github.com/deepseek-ai/DeepInfer", + "commit": "8b16149741a4935e1dec8cea27853f273b374c5b", + "paths": [ + "csrc/engine/mtp_varlen.hpp", + "csrc/engine/scheduler.hpp", + "deepinfer/worker/worker.py", + "deepinfer/environ.py", + "deepinfer/sampling_params.py", + "deepinfer/model_executor/models/mtp/dflash.py", + "deepinfer/model_executor/layers/sampler.py", + "deepinfer/model_executor/layers/tilelang_ops/fused_sample.py", + "LICENSE" + ], + "readset": "references/source-notes.md" + } + ], + "applicability": { + "scope": "Engines with multi-token speculative decoding whose verification forward cost grows with query rows", + "prerequisites": "A calibrated per-position acceptance signal; a measured (rows, step_time) curve; a handle on metadata construction", + "hardware": "Backend-independent procedure; the reference implementation targets NVIDIA SM100 and Ascend 950 only", + "input_contract": "Draft width and row representation, the defined individual/conditional versus cumulative acceptance semantics, verify rows/time curve, sampler cost and acceptance round actually available at schedule time.", + "produced_artifact": "A per-step verification row budget, per-request query lengths from one through draft_width plus one, cumulative acceptance vectors and predicted-versus-realized acceptance error logs.", + "failure_modes": "Confusing verification savings with reduced drafting, misreading confidence semantics or available rounds, allowing later-position confidence to select an earlier token, or generating non-prefix grants can invalidate the budget or sampling claim.", + "refusal_point": "Stop if unthrottled drafting or sampler cost dominates, the signal cannot be made cumulative, or no round supplies acceptance estimates; the procedure also does not apply without a per-step cost model." + }, + "limitations": [ + "Source-derived candidate; no local efficacy validation and no reproduced gain.", + "The reference budgets verification rows only; draft compute is unchanged.", + "The budgeted path is off by default in the reference source.", + "Budgeting can lower accepted length; equal accepted length is not an acceptance criterion.", + "Per-position independence of the confidence used for verification is a correctness requirement, not only a scheduling convenience.", + "Cross-backend rejection-comparison parity is unproven; the reference has no equality assertion.", + "Numeric acceptance rates and warmup curves are deployment-specific and are not carried here." + ], + "provenance_readsets": [ + "references/source-notes.md", + "references/validation.md" + ], + "consumption_mode": "packaged", + "recommendations": [ + "Measure draft, verify and sampler costs separately and fit the verify curve for graph sizes that will actually replay.", + "Preserve the one-row floor and prefix grants, and audit CPU/GPU allocation timing against the per-position decision-independence contract.", + "Report verification rows, accepted tokens, total step time and throughput separately; use an independently specified sampling oracle rather than requiring unchanged accepted length." + ] + } +--- + +# Budget speculative verification + +## Trigger and boundary + +Use when all of the following hold: + +- The engine performs multi-token speculative decoding with a draft head. +- Verification is a batched forward whose cost grows with the number of query rows. +- Acceptance probability varies materially by request and by draft position. +- A per-position acceptance signal exists, or can be trained and exported. + +Do **not** use when: + +- The draft head is a separate model whose forward cost is proportional to the number of drafts requested. Then the budget must also throttle drafting, and many implementations cannot. The procedure below budgets verification only. +- There is no per-step cost model at all, because the budget decision needs a cost-versus-rows estimate. + +## Status and source + +Status: **candidate**. Empirical validation: **not_run**. + +Source: `deepseek-ai/DeepInfer` @ `8b16149741a4935e1dec8cea27853f273b374c5b` (Apache-2.0), read statically. Nothing was built or executed, and no gain was reproduced. Evidence labels follow the readset convention: **F** is a fact observed in the pinned source; **P** is a proposed procedure. + +Read [source-notes.md](references/source-notes.md) for the evidence ledger and [validation.md](references/validation.md) for checks that have not been run. + +## Required inputs + +1. Draft width and how the engine represents a request's rows — typically one fresh row plus `k` verification rows. +2. A per-position acceptance estimate with known semantics: individual/conditional confidence estimates, or already cumulative. This distinction decides step 2 and cannot be inferred from a field name or treated as proof of statistical independence. +3. A table of `(batch_rows, step_time)` for the verify forward, or a way to collect it at warmup. +4. A sampler cost estimate per batch, because the total step includes sampling. +5. Which step's acceptance values are available at schedule time. If the scheduler runs ahead of sampling, the current step's values do not exist yet. + +## Procedure + +1. **Separate the two costs.** Measure the draft forward and the verify forward independently. The inspected DFlash decode path produces drafts at its configured width: the sampler calls `decode_forward`, which builds fixed-width DFlash metadata and samples all `max_MTP_value` positions (`F`: `deepinfer/model_executor/layers/sampler.py:225-251`; `models/mtp/dflash.py:103,141,308-336,367-387`). The variable-length scheduler budgets verification rows; its non-budgeted `1 + draft_tokens.size()` branch alone is not evidence about the draft producer. If a different draft model's cost scales with requested width, include that cost in the decision. + +2. **Normalize the acceptance signal to a cumulative rate.** Convert individual/conditional per-position confidence estimates according to their defined contract into a non-increasing cumulative vector. The reference multiplies its estimates (`F`: `csrc/engine/scheduler.hpp:1243-1250`); that implementation does not prove the underlying random variables are statistically independent. A cumulative vector makes grants of additional verification rows follow a prefix over draft positions. + +3. **Fit a cost model.** `time(rows) ≈ baseline(rows) + slope × rows + sampler(requests)`. Collect the curve at warmup under the graph sizes you will actually replay. Clamp the slope at zero so extrapolation cannot produce a negative or non-positive time (`F`: `mtp_varlen.hpp:226`, `std::max(0.0, _forward_time_slope.get())`). + +4. **Choose the global row budget.** Maximize `expected_accepted_tokens / time(rows)` over the sorted candidate rows. Seed the expectation with one token per request, because every request always samples at least one (`F`: `mtp_varlen.hpp:231`, `cur_expected = static_cast(num_seqs)`). + +5. **Allocate per request.** Walk the cumulative rates in descending order and grant one extra row at a time until the global budget is spent. Break ties by request index so the result is deterministic (`F`: `mtp_varlen.hpp:204-214`). + +6. **Enforce the floor.** Every scheduled request needs at least one row. Assert that the total is no smaller than the number of requests rather than trusting the search (`F`: `mtp_varlen.hpp:260`, `TORCH_CHECK(best_bsz >= num_seqs)`). This is an allocation contract, not a measured comparison with plain decode. + +7. **Preserve the proposal's per-position decision independence when choosing which round's confidence to read.** At a fixed historical global budget and otherwise fixed allocation state, confidence at later positions `i+1 … n` of the same proposal must not decide whether draft position `i` is verified. Later confidence may depend on an already sampled earlier draft token; letting it select that token for verification may bias the complete emitted distribution and requires a causal and sampling-correctness check. The reference states the intended requirement directly (`F`: `mtp_varlen.hpp:160`, translated from the source comment: "confidence for positions `i+1, …, nextn` must not affect whether `draft_token_i` is verified"). This is not an invariance requirement for arbitrary historical rates: changing the N−2 cost-estimation queue may legitimately change the global row budget. + + The two-round protocol exists to satisfy that requirement under a pipelined scheduler. CPU scheduling takes the global row budget from N−2; its per-request queue always reads `accept_rates`, which is N−1 when schedule/process are paired and N−2 when one forward is still in flight (`F`: `mtp_varlen.hpp:160-207`). In the overlapping ZOS path, the worker uses the previous step's GPU confidence to redistribute the fixed total row budget before the current main forward, then synchronizes corrected metadata back before sampling (`F`: `deepinfer/worker/worker.py:118-152,191-219`). Do not describe the CPU queue alone as the final N−1 allocation. A different timing is a new design and must establish the same decision-independence contract; source comments alone are not a sampling-correctness proof. + +8. **Propagate the allocation to the metadata.** The verify kernels read per-request query length and the per-position row map. Both must be built from the budget, not from the draft width. + +## Expected outputs + +- A per-step row budget and a per-request query length in `[1, draft_width + 1]`. +- A cumulative acceptance vector per request. +- Log fields: predicted acceptance, realized acceptance, and their error. + +## Evidence to collect + +Verification rows and accepted tokens measure different things, so report them separately rather than as one before/after pair: + +- **Allocation invariants**: every grant is a prefix over draft positions, and no request receives fewer than one row. +- **Sampling correctness**, against an independently specified oracle: does the accepted-prefix decision match the rejection rule you intend, under explicitly stated assumptions about the draft and target distributions. +- **Cost and throughput**: verification rows per step, accepted tokens per step, total step time, and end-to-end throughput, all with the draft forward included. +- **Realized-versus-predicted acceptance error**, aggregated per step. + +A lower accepted length is a legitimate outcome of budgeting, not a failure: the objective is expected accepted tokens per unit time, and verifying fewer drafts can lose accepted tokens while gaining more. Do not use unchanged accepted length as the acceptance criterion. Deterministic token comparison is a valid check only where the decoding path is deterministic and the sampling semantics justify it; under stochastic sampling, two runs that consume random draws in different orders do not have to agree token for token. + +## Preconditions and caveats + +- **The draft forward is unchanged.** Quoting a throughput gain without saying so overstates the effect: the reference saves verification rows only. +- **Two different temperatures, and neither implies the other.** The confidence-head temperature (`DEEPINFER_DFLASH_CONFIDENCE_HEAD_TEMPERATURE`) scales the confidence head's output; it calibrates the acceptance estimate (`F`: `deepinfer/model_executor/models/mtp/dflash.py:62-64,76`). A request's sampling temperature is a separate per-request parameter that is clamped at the low end with `top_p`/`top_k` reset (`F`: `deepinfer/sampling_params.py:76-79`). Do not infer sampling behaviour from confidence calibration, or the reverse. +- **Rejection is gated on draft logprobs, not on temperature.** The reject path runs when draft logprobs are supplied (`F`: `deepinfer/model_executor/layers/tilelang_ops/fused_sample.py:200`), and request temperature is clamped rather than allowed to reach zero. Together these support the reading that a request configured as greedy still goes through verification; this is a reading of the gating logic, not a measured end-to-end result. +- **Low acceptance still reserves state.** KV blocks are reserved at maximum width and trimmed later, so a request that accepts nothing still pins extra slots until the next scheduling pass. +- **Wide top-k pools scale badly.** Verification logprob pools scale as `rows × topk × positions`; a full-vocabulary top-k can dominate memory before it dominates time. +- **Cross-platform parity is unproven.** The reference has different rejection-comparison arithmetic on its two backends and no cross-platform equality assertion. + +## Stop conditions + +- Stop if the draft forward cost dominates and cannot be throttled; then the verification saving is a small share of the step. +- Stop if sampler cost dominates verify cost at your occupancy. +- Stop if the acceptance signal cannot be made cumulative; a non-prefix grant breaks the row map. +- Stop if the scheduler can see no acceptance estimate at all, from any round. + +Uniform acceptance is **not** by itself a stop condition. A population with near-zero acceptance can still make one row per request the best choice, because it avoids paying for verification that would be discarded. Whether the budget helps depends on the actual cost model and the fixed overhead, not on how uniform the rates are. Measure it rather than excluding the case in advance. + +## Configuration in the reference source + +| Variable | Default | Effect | +|---|---|---| +| `DEEPINFER_USE_NEXTN_DECODE` | `5` | Maximum speculative width; `0` disables speculation entirely | +| `DEEPINFER_ENABLE_MTP_VARLEN` | unset → false | Enables the budgeted path; without it the draft width is fixed | +| `DEEPINFER_DFLASH_CONFIDENCE_HEAD_TEMPERATURE` | `1.0` | Per-position scale applied inside the confidence head; clamped above zero. It does not set the request sampling temperature. | + +The budget is **off by default** in the reference. Do not describe it as the engine's default behaviour. diff --git a/src/inferrsi/knowledge/atoms/engines/vllm-rlt/audit-recurrent-kv-finalization.md b/src/inferrsi/knowledge/atoms/engines/vllm-rlt/audit-recurrent-kv-finalization.md new file mode 100644 index 000000000..210cf8997 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/engines/vllm-rlt/audit-recurrent-kv-finalization.md @@ -0,0 +1,134 @@ +--- +name: audit-recurrent-kv-finalization +description: Audit vLLM-RLT synchronous early-exit KV propagation, later depth-specific attention reads, and request storage retirement. Use when shallow token exits leave deeper history or release order in question. +metadata: + inferrsi: | + { + "profile": "local-skill-v1", + "schema_version": 1, + "kind": "skill", + "origin": [ + "external" + ], + "status": "candidate", + "empirical_validation": "not_run", + "license": "Apache-2.0", + "tags": [ + "vllm-rlt", + "recurrent", + "kv-cache", + "early-exit", + "last-exited", + "shared", + "validity", + "completion", + "lifetime" + ], + "sources": [ + { + "type": "git", + "url": "https://github.com/InferMatrixLab/vllm-rlt", + "commit": "4a350344027960a48384626aa646f1765fda6d4f", + "paths": [ + "README.md", + "LICENSE", + "NOTICE", + "vllm_rlt/core/kv_cache_manager.py", + "vllm_rlt/worker/model_runner.py", + "tests/test_kv_cache.py", + "pyproject.toml", + "vllm_rlt/config.py", + "vllm_rlt/engine/stage_engine.py", + "vllm_rlt/core/scheduler.py", + "vllm_rlt/worker/executor.py", + "vllm_rlt/attention/__init__.py", + "vllm_rlt/attention/backend.py", + "vllm_rlt/models/ouro.py", + "vllm_rlt/layers/__init__.py", + "vllm_rlt/__init__.py", + "tests/conftest.py", + "vllm_rlt/request.py", + "vllm_rlt/worker/metadata.py", + "vllm_rlt/kernels/paged_attention.py", + "vllm_rlt/worker/buffers.py" + ], + "readset": "references/source-notes.md", + "identity": "references/source-identity.json", + "license": "Apache-2.0", + "third_party_notices": "references/NOTICE.md" + } + ], + "applicability": { + "scope": "Pinned vLLM-RLT native Ouro synchronous scheduling with host KVMetadata: LAST_EXITED propagation versus SHARED, later depth-specific Torch-reference attention and normal release/wait/free order. No speculation, connector, preemption, prefix sharing, split/packed prefill or graph/static-buffer path qualification.", + "prerequisites": "The selected native Ouro synchronous path uses host KVMetadata, no speculation/connector/preemption, atomic prefill and disabled graph/static-buffer/packed-prefill paths; changed execution conditions need a new bounded check.", + "input_contract": "Repository revision, model/configuration, recurrent-layer set, loop count, cache layout and block size, dtype/device, attention backend and effective flags, plus the traced token/depth/layer and its next consumer.", + "produced_artifact": "A bounded token/finalization/consumer/retirement trace separating source call order, observed data and written validity, completion evidence and remaining native model/backend/performance gaps.", + "failure_modes": "Substituting mark_finalized for K/V propagation, accepting allocated pages as a complete written prefix, applying LAST_EXITED copy expectations to SHARED, or treating event recording as completion can invalidate the ownership diagnosis.", + "refusal_point": "On a failed prerequisite or complete-prefix check, retain the first failing token/depth/layer and trace the missing operation. Stop the conclusion when flags or metadata ownership leave the selected path." + }, + "limitations": [ + "Source-derived candidate; native CPU/CUDA, model correctness/quality, performance and agent efficacy are not validated.", + "Allocated capacity, host written-position validity, copied K/V bytes, event recording and completed device work are distinct; host-row checks do not qualify DeviceKVMetadata.", + "Repository Apache-2.0 and retained model/configuration NOTICE attribution do not constitute a whole-tree or model-weight license audit." + ], + "provenance_readsets": [ + "references/source-notes.md", + "references/source-identity.json" + ], + "consumption_mode": "packaged", + "recommendations": [ + "Distinguish copied K/V values, logical written positions and allocated capacity; follow the later depth-specific attention consumer.", + "Preserve executed shallower values during LAST_EXITED propagation and use SHARED as a separate one-plane control.", + "Follow the latest request event through runner release before scheduler cache release; page reuse is not evidence of erased old bytes." + ] + } +--- + +# Audit recurrent KV finalization + +Use this procedure to distinguish copied KV contents, logical written positions and completion ownership in the pinned vLLM-RLT implementation. This is candidate source guidance; backend correctness, model quality, performance and agent efficacy remain unverified. + +## Select the supported path + +Record the repository revision, model/configuration, recurrent-layer set, total loops, cache layout, block size, dtype/device, selected attention backend and effective execution flags. The [source map](references/source-notes.md) pins the inspected implementation and its assumptions. + +The bounded path is native Ouro with synchronous scheduling, host-owned `KVMetadata`, no speculation or connector, preemption disabled, atomic prefill, and graphs/static buffers/packed prefill disabled. The Torch reference consumer is traced. CUDA event operations are source observations; they do not qualify a native kernel or a different backend. `common` catalog placement is discovery scope. + +Use another investigation for `DeviceKVMetadata`, asynchronous preemption/speculation, split/packed prefill, boundary-KV models, transfers, prefix sharing or memory-capacity planning. Record a changed condition before extending this procedure. + +## Two invariants + +1. For LAST_EXITED, copy the final executed recurrent-layer K/V into only the skipped deeper planes before later attention consumes that history. Preserve values already computed at shallower/executed depths. Allocated pages, written-position validity and copied data are different facts. SHARED has one plane for every depth and performs no deeper-plane propagation. +2. Keep completion ownership through finalization and later consumers, then retire runner resources before releasing cache references. A recorded event provides an ordering handle; only the appropriate wait establishes the completion needed by its consumer or reclaimer. + +## Trace one token and its next consumer + +1. **Resolve the exit boundary.** Follow the completed recurrent output into the scheduler. It increments `loops_done`, applies the selected exit policy and enqueues CODA when exiting. The cache exit depth is zero-based `loops_done - 1`; CODA's execution descriptor uses zero for boundary addressing and is not the token's actual completed-loop count. +2. **Follow the copying caller.** The engine applies `finalize_many(exited)` before returning the update. With synchronous execution, the runner has no async state and selects ordinary `finalize`. If a CUDA boundary stream and preceding request event exist, it waits for that predecessor, calls `finalize_token`, then records the new request event. Recording is not a host wait. +3. **Separate data from validity.** Identify the source plane/page/offset at the exit depth and destinations strictly deeper than it. The manager first requires the configured recurrent layers to have written the exit position. LAST_EXITED copies those layers' K/V to each skipped plane, then records their written positions. `mark_finalized` updates bookkeeping without copying and cannot replace this synchronous path. SHARED maps every depth to plane zero and returns without a propagation copy. +4. **Check the complete history.** The host tracker maintains a contiguous prefix plus sparse pending positions. A position in a later gap does not make the whole prefix readable. The selected host-row attention path requires all positions through the current query; reserved capacity is not evidence of that history. Do not infer these host checks for device-owned metadata. +5. **Follow a later deeper token.** CODA appends the generated token; the next PRELUDE resets loop progress. Immutable execution spans bind the new position and recurrence depth. Metadata retains the allocation identity and selects that depth's block table. Ouro's recurrent layers write current K/V before calling prepared attention. The traced Torch consumer gathers K/V through the selected table and context length, including finalized earlier tokens. Confirm the request's next submission waits on its preceding recorded event when a separate stream is used. +6. **Follow normal retirement.** The engine calls runner `release` before scheduler `finish`. Runner release synchronizes the latest recorded event when present, then recycles its slot and drops request RNG ownership. Scheduler finish calls cache `free`, removes request state, and drops allocation references. A block becomes reusable when its reference count reaches zero. This does not erase stale physical bytes, free the whole tensor pool, or establish transfer/prefix-sharing retirement. + +## Decisive observations + +| Observation | Interpretation / next check | +|---|---| +| Deeper plane still holds a sentinel after `mark_finalized` | Bookkeeping was observed; copying has not been established. Locate the actual copying producer. | +| Allocated pages exist but the written prefix has a hole | The later read is not established. Trace the missing write/finalization; do not manufacture validity flags. | +| Executed shallower data changes during deeper propagation | Compare source/destination depth and recurrent-layer selection against the copy contract. | +| SHARED reports one plane for every depth | Do not apply LAST_EXITED's physical-copy or per-depth-isolation expectations. | +| Event was recorded but release/wait ordering is unknown | Completion/reuse remains unestablished. Follow the last consumer and event owner before attributing stale data to allocation. | +| New request reuses old pages | Old bytes are not logical history. Check fresh allocation identity and written state before attention. | + +## Verify and recover within scope + +For an authorized native CPU check, use real Torch tensors with the original manager and Torch attention path. Exercise distinct values at executed and skipped depths, a later deeper token across a page boundary, SHARED as a control, premature finalization, an unwritten prefix and reused pages. A bookkeeping-only sentinel case must distinguish marking from copying. Preserve the exact input/layout/dtype tuple and outputs. + +If a prerequisite or complete-prefix check fails, retain the first failing token/depth/layer and producer/consumer identities. Trace the missing operation instead of bypassing the check, substituting `mark_finalized`, or releasing pages early. If the execution flags or metadata owner leave the selected path, stop the conclusion and obtain a new bounded source/runtime check. + +Report separately: source call order, actual data/validity observations, actual completion evidence, and unrun model/backend/performance checks. CPU manager checks cannot prove CUDA completion, end-to-end output equivalence or a speedup. + +## Sources and notices + +Read the owner-local [source observations and exact anchors](references/source-notes.md) and [immutable file ledger](references/source-identity.json) as needed. The retained [Apache-2.0 license](LICENSE) and [NOTICE](references/NOTICE.md) preserve upstream model/configuration attribution. These are source provenance, not a model-weight license audit. diff --git a/tests/knowledge/test_atomic_benchmark_engine_originals.py b/tests/knowledge/test_atomic_benchmark_engine_originals.py new file mode 100644 index 000000000..123ace9ca --- /dev/null +++ b/tests/knowledge/test_atomic_benchmark_engine_originals.py @@ -0,0 +1,93 @@ +"""The two Engine guides the released inference benchmark requires explicitly.""" +import hashlib +import json +import shutil +from pathlib import Path + +from inferrsi.knowledge.atomic_build import build_generation +from inferrsi.knowledge.atomic_generation import InstalledGeneration +from inferrsi.knowledge.atomic_reader import AtomicReader, AtomPin, AtomUse +from tests.knowledge.test_atomic_generation import RELEASE_ROOT, make_author_root +from tests.knowledge.test_atomic_reader import RELEASE, allow + +ROOT = Path(__file__).resolve().parents[2] +LIBRARY = "src/inferrsi/knowledge/data/skill_library/" +# Released declaration order, owner revision, and digest of the native owner's metadata. +GUIDES = ( + ("deepinfer", "budget-speculative-verification", + "sha256:2bc62cda2beff7dd3898e81f9c5eda756e860577d5f63321e548febab965977c", + "8a63e9ec266fdd498ad9fdcb0f1a72e2d009a091d6a20746446d4aeb1bc767df"), + ("vllm-rlt", "audit-recurrent-kv-finalization", + "sha256:a6e56602b29202af5478389dd0514af221e6e28868c439596ced22c82ce85629", + "97782f08b3d733e43a40a68eac64ca87d5658ce58bae6bc0b60cff28c5fc616f"), +) + + +def test_installed_benchmark_engine_guides_retain_owner_and_read_together(tmp_path): + fixture = ROOT / "tests/fixtures/atomic-reader/playbook-domain-v0.3.4.json" + baseline = json.loads(fixture.read_bytes()) + assert baseline["source_commit"] == RELEASE + benchmark = baseline["refs"]["checkout:inference-benchmark-design"] + authors = make_author_root(tmp_path) + originals = ROOT / "src/inferrsi/knowledge/atoms" + release = tmp_path / "release" + shutil.copytree(RELEASE_ROOT, release) + expected = [] + for engine, name, old_revision, metadata_digest in GUIDES: + path = f"systems/engines/{engine}/{name}/SKILL.md" + descriptor = name + ".original.json" + shutil.copyfile(originals / descriptor, authors / "atoms" / descriptor) + location = f"engines/{engine}/{name}.md" + body = (originals / location).read_bytes() + checksum = hashlib.sha256(body).hexdigest() + assert benchmark["required_resources"][path] == checksum + assert benchmark["dependencies"][path] == "sha256:" + checksum + for destination in (authors / "atoms" / location, release / LIBRARY / path): + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(body) + ref = "checkout:" + name + ".original" + expected.append((ref, path, body, old_revision, metadata_digest)) + + target = tmp_path / "installation" + generation = build_generation(authors, target, source_roots={RELEASE: release}, permits=allow) + installed = InstalledGeneration(target, expected=generation) + uses = [] + for ref, _, _, _, metadata_digest in expected: + pin = AtomPin(ref, installed.catalog[ref]["revision"]) + uses.append(AtomUse(pin, (ref,))) + _, bundle = installed.read_resolved(ref, revision=pin.revision) + fields = ("title", "origin", "applicability", "state", "limitations", "attribution", + "empirical_validation") + inherited = {key: bundle.metadata[key] for key in fields} + inherited["sources"] = bundle.metadata["sources"][1:] + serialized = json.dumps(inherited, sort_keys=True, ensure_ascii=False, + separators=(",", ":")) + assert hashlib.sha256(serialized.encode()).hexdigest() == metadata_digest + + reader = AtomicReader(installed, permits=allow) + bodies = tuple(row[2] for row in expected) + budget = sum(map(len, bodies)) + request = dict(context={}, max_bytes=budget, operations=("retain", "redistribute")) + delivery = reader.read_group(uses, **request) + assert delivery.bodies == bodies and delivery.receipt["body_bytes"] == budget == 26848 + for row, use, item in zip(expected, uses, delivery.receipt["delivered"], strict=True): + ref, path, body, _, _ = row + assert (item["ref"], item["revision"], item["layer"]) == (ref, use.pin.revision, "L3") + assert item["source_range_verification"] == "verified_at_build" + assert item["source_path"] == LIBRARY + path and item["source"]["commit"] == RELEASE + assert item["source_byte_range"] == [0, len(body)] + assert item["sha256"] == item["source"]["sha256"] == benchmark["required_resources"][path] + + short = reader.read_group(uses, **{**request, "max_bytes": budget - 1}) + assert short.bodies == () + assert short.receipt == {"status": "over_budget", "required_bytes": budget, + "body_bytes": 0, "delivered": []} + for index, (ref, _, _, old_revision, _) in enumerate(expected): + denied = AtomicReader(installed, permits=lambda pin, op: pin.ref != ref or op != "retain") + stale_uses = uses.copy() + stale_uses[index] = AtomUse(AtomPin(ref, old_revision), (ref,)) + for result, reason in ((denied.read_group(uses, **request), "permission_denied"), + (reader.read_group(stale_uses, **request), "unavailable_revision")): + assert result.receipt["status"] == reason + assert result.receipt["body_bytes"] == 0 and result.receipt["delivered"] == [] + assert result.bodies == ()