Skip to content

[CUDA][Muse-Glimmer] Explain KV capacity in startup errors, export output and docs - #25725

Open
Gasoonjia wants to merge 9 commits into
mainfrom
gasoonjia/kv-capacity-diagnostics
Open

Gasoonjia wants to merge 9 commits into
mainfrom
gasoonjia/kv-capacity-diagnostics

Conversation

@Gasoonjia

@Gasoonjia Gasoonjia commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Muse-Glimmer CUDA serving rejected a 128K cell-layout export with only "N sessions of T tokens exceed C cells", which made --max-seq-len easy to mistake for usable per-session context (#25648).

This PR reports KV capacity facts where users hit them:

  • Startup. CudaExecutor builds a structured, flag-neutral capacity report and logs it, and the caller can receive it through CudaExecutorConfig::capacity_report. It covers:

    • cell shortfalls: the live/prefix/capture breakdown, cells needed vs available (including the padding cell) and the tokens per session that pool holds;
    • the layout's session limit;
    • automatic context mode: the resolved per-session budget at INFO, or the minimum cells when no budget remains.

    Accept/reject behavior and error codes are unchanged, except that a reservation breakdown must add up to max_sessions.

  • Muse-Glimmer notes. The example layer adds factual notes: which pool refused (target or DFlash draft); the draft's cells, sessions and temporary block cells when the draft is the limit; the resident-session flags in both spellings; a pointer to the sizing docs; and a hint that the sequence layout, also available to DFlash exports, is recommended for long contexts with sliding-window models. No option values are prescribed.

  • Export. export_solo prints the context per session and the full K/V size, target plus draft, before lowering.

  • Docs. BATCHING_SERVING.md documents the cell and sequence layout budgets, min(--max-seq-len, floor((--max-cells - 1) / resident sessions)) per session, and DFlash draft sizing (sessions × tokens + owners × block + 1). It works a 128K example: 16 × 131072 cells is about 104 GiB of BF16 K/V in the cell layout, vs about 29 GiB in the sequence layout.

The arithmetic lives in a GPU-free header (backends/cuda/batching/kv_capacity.h). Unit tests are test_kv_capacity, added to CUDA CI, plus executor report tests on the toy program, Muse-Glimmer note tests and a Python test of the export summary.

Test plan (A100, CUDA 13.2): test_kv_capacity 20/20; test_cuda_executor 38/38, including a real toy program on the cell layout and a 4-column sequence-layout toy (session-limit reports and eager-matched generation); test_step_plan 8/8; test_cuda_kv_cache 61/61; extension_llm_batching_test 227/227; Muse-Glimmer ctest including the DFlash test (30 cases, 12 of them GPU-free capacity-note tests); pytest 11/11. No skips.

Behavior note: apart from the reservation-breakdown check, accept/reject behavior is unchanged. The one exception is a malformed DFlash draft program, whose packed tensors don't match the published owners and step width: it now fails with InvalidProgram and an ABI message, instead of the draft-capacity InvalidArgument. export_dflash warns that its off-graph export uses the checkpoint's native context and ignores --max-seq-len.

Fixes #25648

CudaExecutor rejected a cell-layout serving configuration with only
"N sessions of T tokens exceed the program's C cells". Break the resident
sessions down into live sessions, retained prefix entries and capture slots,
show the cells needed (sessions x tokens + 1 padding) against those
available, the largest per-session context that fits, and the --max-cells a
re-export would need with its K/V size. When the model has sliding-window
layers, point at --kv-layout sequence. The resident-sequence check gets the
same breakdown, worded per layout: the sequence layout suggests a larger
--max-kv-seqs, the cell layout explains its 64-sequence limit. The DFlash
target receives the breakdown too, and a too-small DFlash draft cell pool
reports its histories plus temporary draft-block cells against
--draft-max-cells. Error codes are unchanged.

The arithmetic lives in a pure header, kv_capacity.h, with unit tests that
CUDA CI now builds and runs. export_solo prints the implied per-session
context and full-size K/V before lowering, and BATCHING_SERVING.md
documents the cell budget, a worked 128K example and when the sequence
layout is preferable.

Fixes #25648
@pytorch-bot

pytorch-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/25725

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (1 Unrelated Failure)

As of commit 927019b with merge base 2bb454f (image):

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 25, 2026
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review this PR (head d2c167557c, base main 2bb454f2e4). It addresses #25648: startup KV-capacity errors with a live/prefix/capture breakdown and sizing advice, an export-time per-session context summary, and BATCHING_SERVING.md sizing docs. The arithmetic lives in the GPU-free kv_capacity.h and is unit-tested. Error codes are unchanged. Scope is diagnostics and docs only; no capacity behavior changes.

@github-actions

Copy link
Copy Markdown

This PR needs a release notes: label

If your change should be included in the release notes (i.e. would users of this library care about this change?), please use a label starting with release notes:. This helps us keep track and include your important work in the next release notes.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "release notes: none"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 21m 27s —— View job


Request Changes: in reachable setups the new KV-capacity advice is wrong (more than 64 resident sessions, DFlash draft pools) or missing (the default automatic-context mode), and kv_capacity.h puts Muse-Glimmer export flags into a public backend header. Details below.

Detailed review

PR Review: #25725

Summary

This PR explains CudaExecutor and DFlash KV-capacity startup failures, prints a per-session context summary at export time, and documents KV sizing in BATCHING_SERVING.md. In reachable configurations the advice or the printed context is wrong:

  • the startup advice ignores the cell layout's 64-session cap and the DFlash draft pool;
  • the export summary and the docs formula ignore the DFlash draft pool;
  • the native worker's default automatic-context mode still gets no explanation.

The backend's public header also hard-codes one example's export flags. This review comes from reading the code; nothing was built or run.

Code Quality

  • The cell-shortfall advice ignores the cell layout's 64-session cap.
    • Where: backends/cuda/batching/kv_capacity.h:138-161, called at cuda_executor.cpp:539-553. The cell check runs before the cache exists. The resident-sequence check (CellCache::kMaxSeqs = 64, extension/llm/cache/cell_cache.h:66) only runs later, at cuda_executor.cpp:587-594. So cell_shortfall_lines cannot see the cap.
    • Example: 16 live + 48 prefix + 16 capture = 80 resident sessions of 8192 tokens on 131072 cells. This is the same 16/48/16 breakdown CellLayoutSequenceLimit uses. The error says "at most 1638 tokens per session fit; lower the session token limit…" and "or re-export with --max-cells >= 655361 (32.5 GiB of K/V…)". Either fix then fails with "80 resident sessions requested, but the cell layout tracks at most 64".
    • The sequence-layout hint is too weak: the --kv-layout sequence line reads like an optional memory saving, and it only appears for models with sliding-window layers.
    • The zero-budget branch (:143-147) also ignores the token limit: CellShortfallWithNoTokenPerSession pins "reserve at most 7 sessions" for 8 sessions × 4 tokens on 8 cells, but 7 × 4 + 1 = 29 cells still exceeds 8.
    • Fix: pass the cap into cell_shortfall_lines. When the sessions exceed it, lead with fewer reservations or --kv-layout sequence. In the zero-budget branch, suggest min(cap, (max_cells - 1) / session_tokens) sessions. Fix this →
  • The export summary, the docs formula and the target-pool advice ignore the DFlash draft pool.
    • Where: examples/models/muse-glimmer/export/export_solo.py:595-605 and BATCHING_SERVING.md:487.
    • Why it matters: export_cuda_batching is also the DFlash export path. export_dflash.py:289-303 calls it with draft_max_cells, and the draft pool defaults to --max-cells (export_solo.py:548). The runtime caps each session at min(target, (draft cells - 1 - max_owners × block) / sessions) (cuda_dflash_executor.cpp:671-676). The summary and the documented max --max-context formula use only the target pool, and the summary's K/V total leaves out the draft pool.
    • Example: 4 owners × 16-token blocks and 16 resident sessions.
      • A --max-cells 131072 DFlash export prints 16 -> 8191, but the runtime serves 8187.
      • With --draft-max-cells 32768, a flag BATCHING_SERVING.md:416 tells DFlash users to add, it still prints 8191, but the runtime serves 2043.
      • Passing the printed value as --max-context makes the DFlash executor refuse to start.
    • The runtime target-pool advice has the same gap: capacity_note (cuda_dflash_executor.cpp:555-557) names the draft pool but gives no number. Following "at most 8191 tokens per session fit" with the default draft pool fails again at the draft check.
    • Fix: when dflash_draft is set, print the draft-limited context and the draft K/V size, and add the DFlash term to the docs formula. Fix this →
  • Automatic context mode, the native worker's default, still gets no explanation.
    • Where: cuda_executor.cpp:427-434. With max_session_tokens == 0 (the default, batching_bootstrap.cpp:29-32), the budget becomes min(context, (max_cells - 1) / sessions).
    • No failure diagnostics: that budget always fits, so the new cell diagnostics can never fire. The only failure left is the unchanged one-liner "no cell budget remains for each resident session".
    • The cap is silent: 16 resident sessions on a 128K, 131072-cell export serve 8191 tokens each with no log line, which is the confusion behind [CUDA][Muse-Glimmer] Clarify KV capacity and memory requirements for 128K serving #25648. I found no log of the resolved budget in cuda_executor.cpp, backend_factory.cpp or batching_bootstrap.cpp.
    • Docs: the new sentence at BATCHING_SERVING.md:498-500 ("When a configuration does not fit, the worker's startup error shows this breakdown…") holds only when a context limit is set explicitly.
    • Fix: log the resolved budget with describe_sessions when it is below the model context, and send the zero-budget error through cell_shortfall_lines. Fix this →
  • draft_shortfall_lines gives a wrong reason and advice that cannot work in reachable cases (kv_capacity.h:218-230).
    • Wrong reason: the else-branch says "the draft pool cannot hold its temporary blocks" whenever (max_cells - 1 - temporary) / sessions == 0. The caller already rejects programs without room for the blocks (cuda_dflash_executor.cpp:597: max_cells > max_write > max_owners * block). So the branch can only be reached when the blocks fit but one token per session does not. For example, draft_shortfall_lines(4, 10, 68, 64, {}) leaves 3 free cells and still prints that message.
    • Unreachable test: the branch's only test, DraftShortfallWithoutRoomForBlocks (50 cells, 64 temporary), uses an input the caller can never pass.
    • Advice that cannot work: "at most X tokens per session fit the draft pool; lower the session token limit" fires for any X > 0. But cuda_dflash_executor.cpp:677 rejects any context ≤ block, and the header never receives block.
    • Fix: pass block, reword the zero-budget reason to match the case, and drop the token-limit advice when X ≤ block. Fix this →
  • cell_pool_facts hand-rolls element sizes.
    • Where: cuda_executor.cpp:58-73 sizes only Half, BFloat16 and Float.
    • Mismatch with the cache: the cache also accepts Byte, Char, Short, Int, Long and Bool (cuda_kv_cache.cpp:48-60). An int8 K/V program silently loses the memory estimate, and the two mappings can drift apart.
    • Fix: the same file already uses ::executorch::runtime::elementSize (cuda_executor.cpp:1160). Use it here, guarded by isValid, because this runs before the cache is built. Fix this →

API Design

  • Muse-Glimmer export wording lives in the backend's public API.
    • Hard-coded flags: kv_capacity.h is installed (CMakeLists.txt:34) and PUBLIC in Buck. Its messages (:149, :159, :182, :194, :222, :228) hard-code --max-cells, --kv-layout sequence, --max-kv-seqs and --draft-max-cells.
    • Those flags only exist in one example: examples/models/muse-glimmer/export/export_{solo,dflash}.py. The backend's own exporter, backends/cuda/batching/test/export_toy_decoder.py, has none of them. Any other CudaExecutor user is told to pass flags that do not exist.
    • Example-only code in the backend: draft_shortfall_lines (:202) has a single caller, examples/models/muse-glimmer/runtime/cuda_dflash_executor.cpp:687.
    • Side channel: CudaExecutorConfig::capacity_note (cuda_executor.h:89-91) is a free-form string with one setter. It is logged only on the cell path (cuda_executor.cpp:549), not on the 64-session or "no cell budget" paths.
    • Fix: keep the flag-neutral arithmetic in the backend, and move the flag advice and DFlash lines into examples/models/muse-glimmer/runtime/. The DFlash executor can log its own note when the target's create returns InvalidArgument. Fix this →
  • reservations is an unchecked second source of truth for max_sessions (cuda_executor.h:87-88).
    • What goes wrong: describe_sessions (kv_capacity.h:77-92) silently drops a breakdown that claims too many sessions, and calls any shortfall "other". Three call sites keep these fields in sync by hand: backend_factory.cpp:47-49, cuda_dflash_executor.cpp:552-558 and batching_bootstrap.cpp:128-131. Nothing reports an error when they drift apart.
    • Fix: check reservations.total() == max_sessions when a breakdown is given. Separately, KvReservations::known() is a single-use one-liner, which CLAUDE.md asks to avoid. Fix this →

Testing

  • The executor-level tests cannot detect the change (test_cuda_executor.cpp:586-595).
    • Only the error code is checked: the new assertions check Error::InvalidArgument, which the base code also returns for both configurations. So they pass with or without this PR, and cannot tell the cell path from the 64-session path.
    • Untested claim: the comment "changes only the diagnostics" describes something the test does not observe.
    • No coverage: cell_pool_facts (bytes per cell, sliding-window detection) and the DFlash diagnostic condition (cuda_dflash_executor.cpp:683-697) have no tests.
    • Fix: moving cell_pool_facts into a GPU-free header would let test_kv_capacity cover it. Fix this →
  • The Python test checks a hand-copied model geometry (examples/models/muse-glimmer/tests/test_kv_capacity_summary.py:17-22).
    • Problem: test_geometry (:46-48) only asserts the test's own constants, so the model and the doc numbers can drift apart unnoticed. Nothing checks the docstring's claim ("matches the runtime's admission rules").
    • Fix: build the lists from MuseGlimmerConfig() and its layer_window_size (model/model.py:65). Fix this →

Recommendation

Request Changes

What this PR adds is the advice and numbers it prints. In reachable configurations (more than 64 resident sessions, any DFlash export, the native worker's default automatic-context mode) they are wrong or missing. The fixes are small and stay in kv_capacity.h, cuda_executor.cpp, export_solo.py and the docs. Before more callers depend on it, also decide whether Muse-Glimmer flag names belong in a public backend header.

…nd automatic-context advice

Backend (backends/cuda/batching):
- kv_capacity.h keeps only flag-neutral arithmetic and wording: the cell
  budget, the session breakdown, memory formatting, cell_pool_facts (now
  sized with elementSize for every valid dtype, and GPU-free) and a
  structured KvCapacityReport whose describe_capacity() explains layout
  limits without naming any export or serving option.
- CudaExecutorConfig::capacity_report replaces capacity_note: the executor
  logs and hands every report to the caller -- automatic context mode's
  resolved budget (INFO), a budget of zero, a cell shortfall and a session
  limit. The cell layout's 64-session limit is reported in preference to a
  cell shortfall, whose advice no longer suggests a token limit or cell
  count that cannot work; the zero-budget advice respects the token limit.
- reservations must total max_sessions (or be empty); a mismatch is an
  InvalidArgument instead of being silently dropped.
- test_cuda_executor observes the reports, telling the cell-pool and
  session-limit paths apart, and the automatic budget.

Muse Glimmer (examples/models/muse-glimmer):
- runtime/kv_capacity_advice.h owns the flag-specific advice (--max-cells,
  --kv-layout sequence, --max-kv-seqs, --draft-max-cells, the worker's
  reservation and token-limit flags) and the DFlash draft admission rule,
  which the DFlash executor now uses for its check unchanged.
- The DFlash executor caps the target advice by the draft pool's
  per-session budget, explains a draft shortfall by its actual reason
  (target budget, draft budget at or below the block, or a requested limit),
  and logs the resolved DFlash context in automatic mode.
- export_solo's summary includes the DFlash draft pool's per-session limit
  and K/V; BATCHING_SERVING.md documents the draft term, the 64-session cap
  and automatic-mode logging.
- The Python test derives the geometry from MuseGlimmerConfig and checks
  DFlash pools on synthetic inputs.

No capacity behavior changes beyond rejecting an inconsistent breakdown.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the current head 27d5f61fa0 (one new commit on top of d2c167557c). It addresses the last review (Request Changes):

  • Layering: the backend's kv_capacity.h now holds only flag-neutral arithmetic and a structured KvCapacityReport (automatic budget, no budget, cell shortfall, session limit). CudaExecutorConfig::capacity_report replaces the free-form capacity_note. Flag-specific advice and the DFlash draft rules live in examples/models/muse-glimmer/runtime/kv_capacity_advice.h. A reservation breakdown must sum to max_sessions or be empty; otherwise startup fails with InvalidArgument.
  • Advice correctness: the cell layout's 64-resident-session cap is reported first and never paired with impossible fixes. The zero-budget advice respects the token limit. DFlash target advice is capped by the draft pool's per-session budget, and draft shortfalls name their actual cause. The export summary and docs include the draft limit and draft K/V.
  • Automatic context mode: the resolved per-session budget is logged at startup, and the "no cell budget" failure carries the breakdown.
  • Element sizes: taken from elementSize for every valid dtype.
  • Tests: test_cuda_executor inspects the reports and distinguishes the cell-pool, session-limit and automatic paths. test_kv_capacity covers cell_pool_facts. The DFlash advice has 12 new boundary cases. The Python test takes geometry from MuseGlimmerConfig.

A100 (CUDA 13.2): test_kv_capacity 17, test_cuda_executor 33, muse_glimmer_cuda_dflash 40, test_step_plan 8, test_cuda_kv_cache 61, batching 227, Muse-Glimmer ctest, pytest 10, all passing.

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 22m 12s —— View job


Request Changes: the follow-up fixes most of the last review, but some of the new advice still ends in a second startup failure if a user follows it. The DFlash --max-cells advice leaves out the draft pool, and automatic context mode still logs a budget with re-export advice before it fails on the 64-session limit.

Detailed review

PR Review: #25725

Summary

This PR explains CudaExecutor and DFlash KV-capacity startup failures, prints a per-session context summary at export time, and documents KV sizing in BATCHING_SERVING.md. The follow-up commit 27d5f61 addresses most of the last review. In some reachable configurations, though, following the advice leads to another refusal:

  • the DFlash --max-cells advice covers only the target pool;
  • automatic context mode reports its budget, with re-export advice, before it checks the 64-session limit;
  • the session-limit advice ignores a cell shortfall it already knows about;
  • the draft-shortfall advice ignores a requested token limit.

Also, the reservation advice uses the native worker's flag spellings only. This review comes from reading the code. Nothing was built or run.

Code Quality

  • The DFlash target advice still sizes --max-cells for the target pool alone, so following it fails again.

    • Where: kv_capacity_advice.h:55-67 (automatic) and :99-107 (cell shortfall), called from cuda_dflash_executor.cpp:602 and :743. session_token_cap caps only the advised token count. required_cells() is the target formula, sessions × tokens + 1.
    • Cell shortfall: the draft pool defaults to --max-cells (export_solo.py:643), so a re-export at the advised minimum always leaves the draft max_owners × block cells short. draft_admission then refuses, because a requested limit must equal the draft's context (:190-191).
      • Example: 16 sessions with --max-context 131072 on a 131072-cell DFlash export, with 4 owners of 16-token blocks. The advice is "re-export with --max-cells >= 2097153 (104.0 GiB of K/V)".
      • After that ~104 GiB re-export, the draft serves (2097153 − 1 − 64) / 16 = 131068 tokens per session. Startup fails again and asks for --draft-max-cells >= 2097217.
    • Automatic mode: "the full context needs an export with --max-cells >= N" is printed even when the target already has N cells and only the draft limits the context.
      • With --max-cells 2097153 --draft-max-cells 32768, each session gets 2043 tokens, and the line asks for the 2097153 cells the export already has.
      • With --max-cells 2097153 and the default draft pool, each session gets 131068 tokens, and the line again asks for 2097153.
    • Other gaps:
      • The quoted K/V size omits the draft's K/V, which the export summary includes.
      • The capped token count can fall to or below the block, which DFlash refuses. For example, 64 sessions with a 1024-cell draft pool give "at most 14".
      • The zero-budget advice (:75-81) leads to one-token sessions, which DFlash also refuses.
    • Tests: TargetAdviceIsCappedByTheDraftPool and AutomaticContextExplainsTheFullContext (cuda_dflash_executor_test.cpp:434-442, :471-494) assert this output.
    • Fix:
      • Pass the DraftPool to serving_advice instead of a token cap.
      • Size a re-export for both pools: --draft-max-cells >= sessions × tokens + max_owners × block + 1. The default draft pool meets that only when --max-cells does.
      • Add the draft K/V, and never advise a limit at or below the block.
      • Add a test that feeds the advised values back into cell_budget and draft_admission.

    Fix this →

  • Automatic context mode still reports its budget and re-export advice before the 64-session limit, and the session-limit advice ignores the cells.

    • Where: cuda_executor.cpp:450-457.
      • The comment says "The layout's session limit is reported first: no cell count fixes it". But the ternary checks max_sessions > kMaxSeqs only when the budget is 0.
      • With a positive budget it reports kAutomatic and the cell check passes. Only the post-build seq_limit check (:613-616) then reports kSessionLimit.
    • Example:
      • Run the native worker at its default --max_session_tokens 0 with 32 live sessions, 32 prefix entries and 4 capture slots: 68 resident sessions on 131072 cells.
      • The Info lines say each session may hold 1927 tokens, and backend_factory.cpp:51 adds "the full context needs an export with --max-cells >= 8912897 (442.0 GiB of K/V)".
      • Startup then fails because 68 sessions exceed 64, which no cell count fixes. This contradicts "reported first and never paired with impossible fixes".
    • Sequence layout: the same happens at :425-431. The executor logs "each get N tokens", then rejects the program because it declares fewer sequence columns than there are sessions.
    • Session-limit advice ignores the cells: the explicit-limit check (:567-578) can find both too many sessions and too few cells. The advice is then "reserve at most 64 sessions" (kv_capacity.h:287-290) and "lower … to total at most 64" (kv_capacity_advice.h:122-126), and following it still fails on cells.
      • Example: the CellLayoutSessionLimitLeadsWithTheLimit fixture (test_kv_capacity.cpp:242-261) puts 80 sessions of 8192 tokens on 131072 cells. At 64 sessions it still needs 64 × 8192 + 1 = 524289 cells.
      • fitting_sessions(report), already capped at the limit, gives the count that fits: 15. The test pins the omission with EXPECT_FALSE(any_contains(lines, "cells would hold")).
    • Tests: test_cuda_executor has no automatic-mode case with more than 64 sessions and a positive budget. For example, 65 sessions on the toy's 256 cells get 3 tokens each and would produce two reports.
    • Fix:
      • Check the session limit before reporting kAutomatic, on both layouts.
      • In the cell-layout kSessionLimit advice, use fitting_sessions(report) when a token budget is known.

    Fix this →

  • The draft-shortfall advice ignores a requested token limit when the draft leaves the block or less.

    • Where: kv_capacity_advice.h:218-242. Both fixes are sized for block + 1 tokens per session:

      • needed = sessions × (block + 1) + temporary + 1;
      • "reserve at most (cells − 1 − temporary) / (block + 1)" sessions.

      But draft_admission (:190-191) also requires the context to equal a requested limit, and serve_batching always sends one, because --max-context is required.

    • Example:

      • draft_shortfall_lines(16, 4096, 4096, cell_pool(300), {}) uses the pool of DraftShortfallWhenTheDraftLeavesTheBlockOrLess with a 4096-token limit. It advises "reserve at most 13 sessions, or re-export with --draft-max-cells >= 337".
      • Either fix gives 18 or 17 tokens, not 4096, so startup is refused again. After the 337-cell re-export, the next message asks for 65601 cells.
    • Tests: that test (cuda_dflash_executor_test.cpp:371-387) covers only requested_tokens == 0.

    • Fix: when a limit was requested, size both fixes with it: cell_budget(sessions, requested_tokens, pool.cells, temporary).required_cells and (cells − 1 − temporary) / requested_tokens.

    Fix this →

  • The reservation advice uses the native worker's flag spellings only.

    • Where: kv_capacity_advice.h:28-31. kTokenLimitFlag includes the serve_batching alias (--max-context). kReservationFlags names only the worker's gflags: --max_sessions, --prefix_cache_entries and --prefix_capture_slots.
    • Why it matters: serve_batching takes --max-sessions, --prefix-cache-entries and --prefix-capture-slots (serve_batching.py:67-88). The new sizing section (BATCHING_SERVING.md:485) uses those spellings too.
    • Capture slots: the default --prefix-capture-slots 0 sizes itself automatically (serving_runtime.h:96-107). A user who sees "4 capture slots" has to set a smaller positive value, and the advice does not say so.
    • Fix: give both spellings, as kTokenLimitFlag does, and say that lowering the capture slots needs an explicit value.

    Fix this →

Recommendation

Request Changes

What this PR adds is advice users can follow. With the default draft pool, a DFlash cell-shortfall re-export at the advised --max-cells always fails again. Automatic mode still pairs the 64-session limit with a --max-cells fix, which the follow-up says can no longer happen. The fixes are local: serving_advice and draft_shortfall_lines in kv_capacity_advice.h, and the check order in cuda_executor.cpp.

· Branch: [`gasoonjia/kv-capacity-diagnostics`](https://github.com/pytorch/executorch/tree/gasoonjia/kv-capacity-diagnostics)

…check

Backend (backends/cuda/batching):
- check_admission() and automatic_session_tokens() are the executor's KV
  admission rule, shared with the advice. Automatic context mode checks the
  layout's session limit (64 cells or the declared sequence columns) before
  reporting a budget, and a session-limit rejection is reported once.
- An admitted explicit limit is reported too (kAdmitted, nothing logged), so
  callers always learn the target pool's limits; reports carry whether the
  context was automatic.
- The session-limit wording uses the sessions the cells actually hold when
  a token budget is known.

Muse Glimmer (examples/models/muse-glimmer):
- kv_capacity_advice.h models the startup checks with check_startup()
  (CudaExecutor's check_admission(), the factories' token checks and the
  DFlash draft_admission()) and builds structured fixes -- fewer sessions,
  a token-limit range, a cell re-export, more sequence columns, a sequence
  layout, longer draft sequences -- offering each only if, applied alone,
  it passes every check. A refusal no single option fixes is described.
- DFlash advice takes the DraftPool: re-exports size --draft-max-cells
  (sessions x tokens + owners x block + 1) as well as --max-cells, note the
  default draft pool, quote both pools' K/V, keep token limits above the
  block, never resolve to one-token sessions, and ask only for draft cells
  when only the draft limits an automatic context. Draft shortfalls with a
  requested limit are sized for that limit.
- Flags are named in both the worker's and serve_batching's spellings, with
  a note that capture slots size themselves unless set explicitly.
- The token and size rules are shared, not restated: CudaExecutor calls
  valid_session_limits(), within_context() and valid_cell_count()
  (kv_capacity.h), the factories call valid_requested_tokens() and
  holds_prompt_and_prediction() (kv_capacity_advice.h), and check_startup()
  calls the same functions, including the int limits on sessions x tokens
  and on target and draft cells.
- A GPU-free closure test applies every fix over a grid of 3136 layouts,
  DFlash pools, session counts, token limits, cells, splits and blocks, and
  checks each passes every capacity check at its least favorable value. It
  also reads the fixes back from the advice text alone and checks those, and
  checks that every candidate left out fails. On the backend toy program, the
  real CudaExecutor admits each advised serving change.
- test_cuda_executor checks that 65 automatic sessions with a positive
  budget yield exactly one session-limit report, and that an admitted
  explicit limit is reported.

Diagnostics and docs only; capacity behavior is unchanged.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the current head fd3a3af57c (one new commit on top of 27d5f61fa0). It addresses the second review:

  • DFlash advice sizes both pools. The advice takes the DraftPool. A re-export suggestion gives --max-cells and --draft-max-cells >= sessions × tokens + owners × block + 1, and notes what the default draft pool needs. Quoted sizes include draft K/V. Token limits are offered only above the block, and a zero budget never leads to one-token sessions. When only the draft limits an automatic context, the advice asks only for draft cells.
  • Session limit first. A shared check_admission() checks the layout's session limit (64 cells, or the declared sequence columns) before any automatic budget report, on both layouts. A session-limit rejection is reported once. Session-limit advice uses the sessions the cells actually hold (fitting_sessions).
  • Requested limits: draft-shortfall advice is sized for a requested token limit.
  • Flag spellings: both forms are given (--max_sessions/--max-sessions, etc.), with a note that capture slots default to automatic sizing.
  • Advice closure. The token rules are shared functions called by the runtime (CudaExecutor, the Muse-Glimmer factory, the DFlash executor) and by an advice model of the capacity checks (check_startup(), which also calls check_admission() and draft_admission()). A GPU-free grid test over 3136 configurations reads every fix back from the advice text alone and checks it passes every capacity check. Of 2014 refused configurations, 1670 get fixes that all pass, and 344 need more than one change, so they're described rather than prescribed. A toy-program test applies the advised serving changes, and the real CudaExecutor accepts each one. Runtime accept/reject conditions, messages and error codes are unchanged.

A100: test_kv_capacity 22, test_cuda_executor 36, muse_glimmer_cuda_dflash 41, test_step_plan 8, test_cuda_kv_cache 61, batching 227, Muse-Glimmer ctest, pytest 10, all passing.

…I check

- export_dflash's off-graph export (MLX or CUDA batching) uses the
  checkpoint's native context and ignores --max-seq-len. The sequence-layout
  DFlash note now says a session holds at most the program's context (the
  draft's rows) less the block, and names --max_session_tokens/--max-context.
  BATCHING_SERVING.md says so and gives the DFlash formula with the native
  context; export_dflash warns when --max-seq-len is set on that path.
- draft_notes() takes the DFlash executor's own DraftAdmission instead of
  recomputing it, and branches on the requested limit alone.
- The DFlash executor checks its draft packed-tensor shapes separately,
  before admission: a malformed program now fails with InvalidProgram ("DFlash
  draft packed tensors do not match the published owners and step width")
  instead of InvalidArgument, and gets no capacity notes. A draft pool too
  small for the sessions still fails with InvalidArgument, as before.
- The cell layout's session-limit line never reports "0 sessions ... fit";
  it says one session alone needs more cells.
- The session limit is the program's count throughout; the no-op update
  after the cache was built is gone, and the sequence report test is
  renamed accordingly. A new test generates on the toy's batched-sequence
  artifact and matches its expected continuations.

Runtime admission is otherwise unchanged.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the current head e897ba282e (one new commit on top of 3f8bffac80). It addresses the last review:

  • Sequence-layout DFlash note: it now says a session holds at most the program's context (the draft's rows) less the block, and names both flag spellings (--max_session_tokens/--max-context). BATCHING_SERVING.md says export_dflash's off-graph export (MLX or CUDA batching) uses the checkpoint's native context and ignores --max-seq-len, and the DFlash formula now starts from that context. export_dflash warns when --max-seq-len is set on that path. DraftNotesOnASequenceLayout uses a reachable input.
  • draft_notes() takes the DFlash executor's admission result instead of recomputing it; the constant branches are removed.
  • DFlash checks split: the draft tensor-shape check now runs first as InvalidProgram with an ABI message, and prints no capacity notes. A draft pool too small for the sessions still fails with InvalidArgument and the capacity message. This error-code change for malformed programs is the only behavior change.
  • No "0 sessions … fit": the cell-layout session-limit line now says one session of N tokens alone needs N+1 cells. There's a new test.
  • Minors:
    • the sequence artifact's expected.txt is checked by a new eager-matched generation test;
    • the dead post-build session-limit reassignment is removed;
    • the PR description's test counts are refreshed.

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 26m 49s —— View job


Request Changes: the new sequence-layout DFlash note and BATCHING_SERVING.md call the draft's rows the program's context, which is wrong on CUDA whenever the draft GGUF's dflash.context_length differs from the target's native context (the last automated review asked for that wording); three minor findings are in the details.

Detailed review

PR Review: #25725

Summary

This PR explains CudaExecutor and DFlash KV-capacity startup failures, prints the per-session context at export time, and documents KV sizing in BATCHING_SERVING.md.

At e897ba282e, the new sequence-layout wording says the draft's rows are the program's context. On CUDA they are the draft checkpoint's context. There are three minor findings:

  • draft_notes() still recomputes the budget it is given.
  • Draft refusals do not name --draft-max-cells.
  • The --max-seq-len docs and help for export_dflash are partly inaccurate.

This review comes from reading the code. Nothing was built or run. The new sequence generation test in test_cuda_executor.cpp and the export_toy_decoder.py sequence artifact were not checked in depth.

Code Quality

  • The sequence-layout DFlash note and docs say the draft's rows are the program's context, but on CUDA they are the draft checkpoint's context (major).

    • Where:
      • runtime/kv_capacity_notes.h:182-188: "a session holds at most the program's context (the draft's rows) less the block".
      • BATCHING_SERVING.md:531-533: "giving the draft a private column per sequence of the program's (native) context".
      • The comments at tests/cuda_dflash_executor_test.cpp:509-511 and :518-519.
    • Where the rows come from:
      • The draft's rows are get_draft_offgraph_kv_seq_capacity, which is the draft manifest's maximum_capacity (export/export_dflash.py:479-481, source_transformations/cuda.py:462). That value is the draft config's max_seq_len, which comes from the GGUF's dflash.context_length, default 131072 (model/dflash_model.py:143).
      • export_dflash passes the target's native context to load_dflash_gguf (:250, :264-269). That only sizes module buffers: "the config retains the checkpoint's context capacity" (loaders/dflash_loader.py:118-119).
      • Only the MLX loader takes the draft's context from the target (loaders/dflash_loader.py:200), and the CUDA CLI rejects MLX drafts (export_dflash.py:1220-1221). Nothing compares the draft's rows with the target's context.
      • The export summary already treats the two as independent (export/export_solo.py:466-467).
    • Trigger:
      • Take a target GGUF with a 262144-token native context and a draft GGUF whose dflash.context_length is 131072 (or missing).
      • Export with --kv-layout sequence. Serve with --max_session_tokens 200000 and no more resident sessions than --max-kv-seqs.
      • CudaExecutor admits 200000 tokens in the 262144-token program. The draft then refuses with "at most the program's context (the draft's rows) less the block, 131072 - 16 = 131056 draft tokens". The program's context is 262144, so the note names the wrong limit.
    • The last review was wrong: it said "the draft's rows are the target's context" and asked for this wording. It also said the original test input, a 4096-token request against 2048 draft rows, cannot happen. That input is reachable with a 2048-context draft.
    • Fix:
      • In the note, call the limit the draft's rows (the draft checkpoint's context).
      • In the doc, give each draft column dflash.context_length rows, and state the limit as min(program context, draft rows − block).
      • Fix both test comments, and add a request past the draft's rows.
      • If the rows are meant to equal the program's context, enforce that in prepare_cuda_packed_draft instead.

    Fix this →

  • draft_notes() still recomputes the budget behind the admission it is given (minor).

    • kv_capacity_notes.h:153 recomputes draft_session_budget(sessions, pool), and :155 branches on it.
    • admission.max_context is min(target_tokens, budget) (:68-69). So budget >= target_tokens exactly when admission.max_context == target_tokens, and otherwise the two are equal.
    • Fix: use admission.max_context and drop budget, so the notes have one source.

    Fix this →

  • Draft-pool refusals do not name the flag that sized the pool (minor).

    • The cell-layout draft lines (kv_capacity_notes.h:168-172 and :196-205) give the draft's cells but not --draft-max-cells (default --max-cells).
    • Only target_notes names that flag (:119-120), and only when the target refuses.
    • Trigger: KvNotes.DraftRefusingARequestedLimit (16 resident sessions, --max-context 8191, a 131072-cell export). The target admits and the draft refuses, but no line says which export flag set those 131072 draft cells.

    Fix this →

API Design

  • The export_dflash --max-seq-len docs and help are partly inaccurate (minor).

    • The warning: BATCHING_SERVING.md:510 says export_dflash warns "when the flag is set". export_dflash.py:1228-1235 only warns for a non-default value, so an explicit --max-seq-len 131072 is ignored with no warning. The same page describes the matching MLX check correctly (:31-33, "Nondefault values emit a warning").
    • The help: the help text (export_dflash.py:1176-1180, "KV cache size for target model.") does not say that off-graph export ignores the flag.
    • The sequence-layout paragraph: it now covers export_dflash (BATCHING_SERVING.md:528-547), but it still sizes columns and bytes by --max-seq-len, which export_dflash ignores. Its bytes formula also leaves out the draft's columns. The cell-layout section adds the draft's K/V (:523), and the export prints both for the sequence layout (export_solo.py:481-486).
    • Fix:
      • Say the warning fires when the value differs from the default.
      • Update the help text.
      • In the sequence paragraph, say export_dflash sizes the target columns by the native context, and add the draft columns' K/V.

    Fix this →

Recommendation

Request Changes

The point of this PR is to say where a KV limit comes from. On a DFlash sequence export whose draft and target contexts differ, the new note and doc name the program's context as the limit. The limit is actually the draft checkpoint's context. Fixing it means rewording three places, and the export summary already gets it right. The other findings are minor.

· Branch: [`gasoonjia/kv-capacity-diagnostics`](https://github.com/pytorch/executorch/tree/gasoonjia/kv-capacity-diagnostics)

- The sequence-layout DFlash refusal now states only figures the runtime
  reads from the program: the draft program holds N rows per session; with a
  B-token block a session can hold at most N - B tokens; R were requested
  (--max_session_tokens/--max-context). It no longer claims where N comes
  from.
- draft_notes() takes every figure from the DFlash executor's admission
  (max_context, fits) and the program's pool; it no longer recomputes the
  draft budget.
- Cell-layout draft-pool notes name the export flag that sized the pool:
  --draft-max-cells, default --max-cells. The sequence layout's per-session
  rows have no flag.
- BATCHING_SERVING.md: export_dflash's off-graph export loads the target with
  the checkpoint's native context and warns only when --max-seq-len differs
  from its default; on the sequence layout a CUDA batching export gives the
  draft the draft GGUF's dflash.context_length rows per session (default
  131072), whatever the target's context, so a DFlash session holds at most
  min(program context, draft rows - block). export_dflash's --max-seq-len help
  says off-graph export ignores it.

Runtime behavior is unchanged.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

@claude /pr-review

Please review the current head 7ee1cd19ba (one new commit on top of e897ba282e). It addresses the last review. Every factual claim in the notes and docs was traced to the code; the file:line references are below.

  • Sequence-layout DFlash refusal note: it states only figures read from the program, e.g. "the draft program holds 2048 rows per session; with a 16-token block, a session can hold at most 2032 tokens; 2040 were requested (--max_session_tokens/--max-context)". It no longer claims where the rows come from. The rows are read from get_draft_offgraph_kv_seq_capacity (cuda_dflash_executor.cpp:587).
  • draft_notes() takes every figure from the caller's DraftAdmission (max_context, fits) and the program's pool; it no longer recomputes the budget.
  • Cell-layout draft notes name --draft-max-cells (default --max-cells; export_dflash.py:1203-1204, export_solo.py:644, published at export_dflash.py:483). The sequence layout names no flag, because none sets the draft's rows.
  • Docs and help:
    • export_dflash's off-graph export loads the target with the native context and ignores --max-seq-len (export_dflash.py:234,241,250; export_solo.py:852). It warns only when the value differs from the default (export_dflash.py:1230-1236).
    • On a CUDA batching export, the draft's per-session rows are the draft GGUF's dflash.context_length, default 131072 (dflash_model.py:143; dflash_loader.py:95,119,129; cuda.py:462; export_dflash.py:479-481).
    • The sequence-layout limit is min(program context, draft rows − block), with N + 1 draft columns.

Runtime behavior is unchanged; only notes, docs, help text and tests changed. A100: test_kv_capacity 20, test_cuda_executor 38, test_step_plan 8, test_cuda_kv_cache 61, batching 227, Muse-Glimmer ctest (DFlash 40), pytest 11, all passing.

@claude

claude Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Claude finished @Gasoonjia's task in 22m 6s —— View job


Approve: at 7ee1cd19ba the rewritten DFlash notes, draft_notes() and the export_dflash docs and help match the code; two minor, non-blocking items remain (a docs sentence calls 131072 cells the default draft pool, and no test covers the sequence-layout draft note in automatic context mode).

Detailed review

PR Review: #25725

Summary

This PR explains KV capacity in the startup errors of CudaExecutor and the DFlash executor, in the export summary and in BATCHING_SERVING.md. The new commit:

  • rewrites the sequence-layout DFlash note;
  • makes draft_notes() take its figures from the caller's DraftAdmission;
  • names --draft-max-cells in the cell-layout notes;
  • updates the export_dflash docs and help.

Nothing blocks; two minor items follow. I reviewed by reading the code at 7ee1cd19ba and did not build or run anything.

API Design

  • BATCHING_SERVING.md:523-525 says the default draft pool is 131072 cells.
    • The sentence reads "the default draft pool of 131072 cells serves 8187 tokens per session".
    • Both exporters default --max-cells to 65536 (export_dflash.py:1203, export_solo.py:1391-1393), and --draft-max-cells defaults to --max-cells (export_dflash.py:1204).
    • So a default export_dflash has a draft pool of 65536 cells. That gives 16 resident sessions (65536 − 1 − 4 × 16) // 16 = 4091 tokens each, not 8187.
    • 131072 is only right with the earlier example's explicit --max-cells 131072 (line 493). Someone sizing a DFlash export from this paragraph would expect twice the draft cells they get.
    • A wording that ties the figure to that flag: "With --max-cells 131072, 4 owners of 16-token blocks and 16 resident sessions, the draft pool at its default size (131072 cells) serves 8187 tokens per session".
    • Fix this →

Testing

  • No test covers the sequence-layout draft note in automatic context mode (kv_capacity_notes.h:166-182).
    • DraftNotesOnASequenceLayout (cuda_dflash_executor_test.cpp:511) only covers requested limits (2040 and 4096).
    • This commit rewrote the requested_tokens == 0 path, which appends the outcome and adds the "target pool holds" line. No test checks its text.
    • A sequence-layout DFlash export takes this path at every automatic-context startup where the draft's rows minus the block are fewer than the target's context.
      • Example: 131072 draft rows (the documented dflash.context_length default) with a 131072-token target.
      • It logs at Info: "DFlash: the draft program holds 131072 rows per session; with a 16-token block, a session can hold at most 131056 tokens, which limits them".
    • In that line "them" has no antecedent, unlike the cell variant, which says "for each of N sessions".
    • A case like draft_notes_for(4, 0, 131072, {true, 131072, 4, 16}) would check that text and its length.
    • Fix this →

Recommendation

Approve. Nothing blocks. Both items are small (one sentence of docs wording, one test case) and can land in this PR or a follow-up.

· Branch: [`gasoonjia/kv-capacity-diagnostics`](https://github.com/pytorch/executorch/tree/gasoonjia/kv-capacity-diagnostics)

…word the limit

- BATCHING_SERVING.md: the default --max-cells is 65536 and --draft-max-cells
  defaults to it, so the 8187-token draft example now states its
  --max-cells 131072 and the arithmetic, floor((131072 - 1 - 64) / 16).
- The sequence-layout automatic-mode draft note says the draft "limits each
  session" rather than "limits them", which had no antecedent; a new test
  pins the line.
@Gasoonjia

Copy link
Copy Markdown
Contributor Author

Thanks for the approval. I pushed 927019b2a7, which fixes both minor items:

  • Draft pool example in BATCHING_SERVING.md: the example now states its explicit --max-cells 131072. With it, the draft pool at its default size (131072 cells) serves floor((131072 − 1 − 64) / 16) = 8187 tokens per session, and --draft-max-cells 32768 serves 2043. Both exporters default --max-cells to 65536 (export_dflash.py:1203, export_solo.py:1391-1393), and --draft-max-cells falls back to it (export_solo.py:644).
  • Sequence-layout automatic-mode draft note: it now reads "..., which limits each session". New test: DraftLimitingAnAutomaticContextOnASequenceLayout (draft_notes_for(4, 0, 131072, {true, 131072, 4, 16})) pins the text and checks every line stays under the log limit.

This branch was successfully deployed

1 active and 1 inactive deployments
upload-benchmark-results — 927019b2 Deployed Nov 25, 2026 by Gasoonjia via upload-benchmark-results #23512
cadence — 927019b2 Deployed Nov 25, 2026 by Gasoonjia via hifi-op-test / hifi4 #41014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[CUDA][Muse-Glimmer] Clarify KV capacity and memory requirements for 128K serving

1 participant