Skip to content

core + cuda: one KV admission ledger; a request reserves its prompt and reply, not a whole window (#1943) - #1945

Merged
ashhart merged 8 commits into
ashhart:mainfrom
laudney:pr-kv-ledger
Nov 2, 2026
Merged

ashhart merged 8 commits into
ashhart:mainfrom
laudney:pr-kv-ledger

Conversation

@laudney

@laudney laudney commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Implements the first change proposed in #1943. That issue stays open for the family conversions that follow, one per family.

What this does

Unpaged CUDA families reserve a whole --context window per --parallel stream at load, while paged families reserve each request's prompt and reply when they admit it. This PR adds one admission model that any family can use: a byte ledger in the lane host, where a request promises what it can use and waits when it does not fit.

It converts no family. Every current family keeps its exact stream count, prompt cache and tokens. A family opts in later, in its own PR, once its streams allocate per request.

Commit What it does
fix(lanes): release a stream that finishes on its first token Fixes a leak in every family today. On the default open path, a stream that finished on its first token ran its trace before releasing its lane, so a failed trace left the backend's caches held (the host only discards unfinished streams). The release now runs deferred around the trace, as open_first.zig already does.
feat(core): add the KV admission ledger core/kv_ledger.zig: a byte total and one lease per holder, shaped like kv_pool.Pool's promise, finish and idle.
feat(core): admit lane jobs against a byte ledger Info.ledger. takeJob promises a job's bytes in the same locked step that takes it from the queue, so staged fills and batched jobs are counted before the next choice. A job that does not fit stays queued; one past the whole budget fails in words. finish and requeue return the lease. With a ledger, the "nothing running" shortcut in choose tests outstanding leases. stop warns if a lease never came back. A round planner, which admits past takeJob, is refused beside a ledger.
refactor(cuda): decide the stream count in cuda_streams.zig native/cuda.zig was at 599 lines. Its stream-count decision moves into cuda_streams.zig unchanged, with the refusal texts byte-identical.
feat(cuda): serve per-request families from the KV ledger A family sets Loaded.per_request to its kv_pool.Layout (the type the paged families declare), its lookahead rows and its scratch. The host prices every request as fixed_bytes + token_bytes × (min(prompt + max_tokens, context) + lookahead), sizes the prompt cache after --parallel full-window requests (as the window plan's held does, so streams come first on a small card), serves the rest as the ledger, and names it in the startup line. --parallel becomes a cap. The ledger is refused with a warm pass, a lone driver, a reserve field, a page layout or a drafter wrap.
fix(cuda): size the ledger's prompt cache after every stream From review: the plan sized the prompt cache beside one full-window request, so on a 24–32 GB card the default cache could take everything past one window. It now sizes the cache after --parallel full-window requests, as the window plan does. A small-room test with --parallel 4 pins it.

The reply limit is unchanged: --max-tokens keeps its 4096 default.

Why

#1943 has the full case. In short:

Checks

  • zig build test-cuda-host test-shared-lane-regressions-host test-kv-pool pass.
  • zig fmt --check is clean.
  • python3 tools/zig/lean_check.py: 424 problems on this branch and 424 on its base. Every one is inherited, none added.
  • New host tests:
    • core/lanes/open_trace_test.zig: a first-token finish releases its lane when its trace cannot resolve and when any trace allocation fails. Both tests failed before the fix.
    • core/kv_ledger.zig: the ledger type.
    • core/lane_host_ledger_test.zig on the fake backend: waiting without refusal, the head-of-line bound, LaneMemory returning its lease, a request past the budget refused in words, cancellation while queued and while running, batched admission never exceeding the budget, and a round planner refused.
    • native/cuda_ledger.zig: the cost formula, cache placement after --parallel full-window requests (a large room and a small one), a host cache, the refusal at the boundary, and a saturated cost.
  • Device: GLM-5.3-Flash NVFP4 at TP=2 on two DGX Spark (GB10), against main, paged (the default) and unpaged (TF_KV_PAGES=0). The startup line (streams, budget, prompt cache) and the reply hashes of four greedy requests (prose, code, a 512-token reply, and one without max_tokens) are identical in both modes. On GB10 the free room at load moves with page-list memory between runs, so each pair was compared in the same host state.

Overlap

atc overlap finds one textual conflict that this PR adds: native/cuda.zig against #1522, #1445 and #1446 (@BlivionIaG's EXL3 Flash Next stack). Those PRs change the grow line of the stream-count block (preallocates_lanes), and this PR moves that block unchanged into cuda_streams.zig count. So that change becomes the same two lines in count. I can carry it, or rebase onto whichever lands first. Their stack already conflicts with current main in four files of its own, which this PR does not touch.

@jschmied

jschmied commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Read through all six commits. The ledger itself looks right to me:

  • the promise happens in takeJob under the lock, before the job leaves the queue, so batched admission (many goes through takeJob) counts each job before the next;
  • every way out returns the lease: finish (including the admitted.append OOM path and cancels), and requeue;
  • choose keeps the head-of-line rule, with "alone" meaning no lease outstanding instead of no live stream, which is the right test for a byte budget.

The open.zig fix is right too: defer e.release(s) covers both resolve and finish failing, and the host still discards only unfinished streams, so there is no double release.

One thing to settle before the first family converts: the order of the prompt cache and the streams. plan reserves one full-window request, then lets kv_pages.kept give the prompt cache up to 16 GiB of the rest (cacheBytes(..., room, one_full)), and the ledger gets what is left. Today's arithmetic is the other way round: held is every stream's window, so the streams come first and the cache gets the remainder. On a GB10 the room is large enough that this doesn't show. On a 24–32 GB card, though, the default cache can take everything past one window, and a converted family would then run one long request at a time where today it runs --parallel of them. The plan test states this directly (p.total == p.one_full beside a full cache).

Until the cache can be reclaimed inside the budget (your Reclaim follow-up), I'd size the cache beside min(--parallel × one_full, room), as held does today. The ledger then never gives a converted family fewer full-window requests than the window plan would have, and short requests still get the extra concurrency. A test with a small room and --parallel 4 would pin it down.

Two small notes, no change needed:

  • never() can't trigger under the CUDA plan, since Cost.of caps rows at the context and total >= one_full. It's still a fine guard for a host whose total is set another way.
  • LedgerWithRounds is a start-time error, but no CUDA host sets rounds today (only DeepSeek V4.1 on Metal does), so it can't reach a CUDA user.

For #1943's Qwen line: on today's main, Qwen 3.5/3.6 on pages (TF_QWEN_KV_PAGES=256, _ALL=1) give the same replies and first-row logits as windows on the 27B (DFlash2, drafted and plain) and the 35B-A3B (MTP), at c=1, 2, 4 and 8 equal to solo. So the default switch looks clear on identity, and I'm measuring speed now.

@laudney

laudney commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @jschmied, good catch on the order. Fixed in 426dec7: plan now sizes the prompt cache beside --parallel × one_full (saturating; cacheBytes caps it at the room), so streams come first as with held, and short requests still get the extra concurrency. The plan test now pins both sides with --parallel 4: a large room keeps all four full windows and the cache takes the rest, and a room of two full windows gets no cache and the ledger keeps all of it. One nuance: with free_streams > 0 the window plan does not charge the prepaid stream, so the two can still differ by that stream. No current family sets both, and I'd settle it with the reclaimable cache in the byte-budget follow-up.

Agreed on both notes. And thanks for the Qwen identity results at c=1–8; that clears the way for the paged default.

@ashhart

ashhart commented Nov 2, 2026

Copy link
Copy Markdown
Owner

Thanks @laudney, reviewed independently: this lands once its CI is green. With no family opted in, stream counts, plans and refusal bytes are main's across 2,304 comparison cells in both host modes. The first-token release regressions fail on main's open.zig and pass with your fix. Reservations clean up on cancellation, prefill and round errors, an active halt and allocation failure, and the sums hold at u64 limits. Each family's conversion keeps its own gate.

laudney and others added 8 commits November 2, 2026 20:52
On the default open path a stream that finishes on its first token
ran its trace before releasing its lane, so a failed trace left the
backend's caches held: the host discards only unfinished streams,
and nothing released them again. The release now runs deferred
around the trace, as the first-before-draft path already does, and
two tests cover an unresolvable trace and every trace allocation
failure on that path.
Unpaged streams need one byte budget that admitted requests promise
from, so the lane host can admit by a request's own cost instead of
a full window per stream. The ledger holds a total and the promised
bytes with one lease per holder; a promise that does not fit fails
with LaneMemory and changes nothing, and finishing a lease returns
its bytes once. Nothing uses it yet.
An engine can now hand the lane host a byte budget and a per-request
cost instead of a fixed stream count. The host promises a job's
bytes in the same locked step that takes it from the queue, so
staged fills and batched jobs are counted before a later choice;
a job that does not fit stays queued, one past the whole budget
fails in words, and finish and requeue return the lease. The
ledger lives with the lane host, so its export moves out of core.
The CUDA host's openWith sat at 599 lines, too close to the limit
for the ledger's admission branch to join it. The stream count, the
page plan or whole windows the room holds with its no-stream and
too-many refusals, moves unchanged into cuda_streams.zig, so the
next change adds a branch there instead of in cuda.zig, which drops
to 569 lines.
The CUDA host can now serve a family whose streams allocate a
request's rows at open from one KV budget, instead of counting
whole windows. Such a family sets Loaded.per_request to its
kv_pool.Layout, lookahead rows and scratch; the host prices every
request with one formula, places the prompt cache beside one
full-window request and serves the rest as the ledger. No family
sets it yet, so every current load is unchanged.
A family that sets Loaded.per_request reads these fields, not the
issue, so the two rules its cost must keep belong on them, as the
pool's author asked in ashhart#1943: fixed_bytes holds every byte the open
path allocates for a request beyond its rows, and lookahead covers
the widest drafted or verify pass the family runs, not one decode
step. No code changes.
The ledger plan sized the prompt cache beside one full-window
request, so on a 24-32 GB card the default 16 GiB cache could take
everything past one window and a converted family would serve one
long request at a time where whole windows serve --parallel. The
plan now sizes the cache beside --parallel full-window requests, as
the window plan's held bytes do, so streams come first and short
requests still get the extra concurrency; a small-room test pins it.
@ashhart
ashhart merged commit 33429c3 into ashhart:main Nov 2, 2026
0 of 7 checks passed
@ashhart

ashhart commented Nov 2, 2026

Copy link
Copy Markdown
Owner

Thank you @laudney. This is merged into main with your commits under your own name, so you're listed as a TensorFold contributor. It ships in the next release, credited to you in the changelog and the release notes.

@laudney
laudney deleted the pr-kv-ledger branch November 2, 2026 21:03
@ashhart

ashhart commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Thanks @laudney! This is in TensorFold 1.2.2, out now: https://github.com/ashhart/TensorFold/releases/tag/v1.2.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants