Repository navigation
Add support for VertexAI safety settings - #624
Merged
Merged
Conversation
Enables user to configure VertexAI safety settings. Example usage:
```python
import sglang as sgl
from vertexai.preview.generative_models import HarmBlockThreshold, HarmCategory
client = sgl.VertexAI(
"gemini-pro",
safety_settings={
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
},
)
```
merrymercy
force-pushed
the
main
branch
2 times, most recently
from
July 16, 2024 03:44
7eda0c8 to
41d1f67
Compare
Merged
timethink
pushed a commit
to timethink/sglang
that referenced
this pull request
Mar 9, 2025
Jiminator
added a commit
to Jiminator/sglang
that referenced
this pull request
May 28, 2026
Adds an investigation report for the nightly-test-perf-4-gpu-b200 failure of test_a_gsm8k under TestDeepseekV3FP4CuteDSLMoE. The regression is traced to commit 044649c (PR sgl-project#22669) which under-sizes the CuteDslMoEWrapper buffer for the EP=1, TP=4, no-DP-attention DeepSeek V3 FP4 configuration. The report includes: - pass/fail boundary (run sgl-project#624 pass -> sgl-project#625 fail on main) - bisection across the 50 commits in 7f154ba..c4a7d12 - root-cause diff in flashinfer_cutedsl.py:ensure_cutedsl_wrapper - direct repro at offending and parent SHAs (GPU 4 only) - a four-line recommended patch and short-term workarounds Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Aug 8, 2026
…t stubs The abort tests build BarlinkBar1Transport via __new__ and hand-set the attributes under test; that list silently diverges from the real __init__ every time the transport gains state (the historically recorded 7-fail drift of the deferred-517 file; sgl-project#622's ack barrier repeated the mechanism and was hand-patched again). At audit time __init__ assigns 103 attributes, the stub sets ~30. Fix shape: not a bigger stub — an exact two-way audit. Every __init__ attribute must be stub-set or listed in a reviewed exclusion table with a reason (bring-up plumbing, byte-proof/sensor state, dispatch thresholds, result-relay slots, log-dedupe flags, the None-guarded poll mirror); a new attribute turns the audit RED naming it, a removed one turns its stale exclusion RED, and an attribute both set and excluded is rejected. Red-first record: the first run with the example-only table failed naming all 59 uncovered attributes; the table was populated from that output. Battery: 42 test items green across drift-audit + deferred-517 + abort-431; ruff clean.
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Aug 8, 2026
…-way drift audit + test hygiene Red-first audit naming all uncovered transport attributes; reviewed exclusion table; any future new/removed/double-booked attribute turns the audit red by name. 42 battery test items green (drift-audit + deferred-517 + abort-431).
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
…t stops THE THIRD TIME THIS EXACT DRIFT LANDED. `BudgetHarness` binds a hand-written subset of `Scheduler`, and three times the reduce has grown a member the subset did not: #616g added `_publish_uniform_evict_floor`, sgl-project#639 the HOST pair, and now #639b the MAMBA pair. Each was found the same way -- both admission cases red with an `AttributeError` naming ONE attribute -- and each was fixed by binding that one name. WHICH IS WHY IT KEPT COMING BACK. An AttributeError reports the FIRST missing member, not the set. Binding only the reported name leaves the next one queued, and that is exactly the state this tree was in: the red named `_local_mamba_avail`, while `_publish_uniform_mamba_floor` was ALSO missing and `_MAMBA_AVAIL_ABSENT` with it. A fourth incident was already loaded. So the harness is now checked against the real method rather than against the last incident. `TheHarnessTracksTheProductionSurface` extracts the `self.X` names `Scheduler._update_uniform_pool_budget` READS (assignment targets excluded -- `_uniform_min_avail` and `_uniform_budget_deficit` are written by the reduce and must NOT be bound), follows one level through the Scheduler helpers it calls (which is what carries sentinel constants like `_MAMBA_AVAIL_ABSENT`), and asserts every one is present on the harness. A member added and not bound now fails THAT case with the FULL LIST, before it can fail the admission cases with a single name. Source-level on purpose: the drift is "someone added a `self.X` and did not bind it", which is a property of the method's text. Executing the method to find out would need the very stand-in whose completeness is in question. SCOPE, STATED RATHER THAN IMPLIED. Direct members of the reduce plus one level through its callees. Deeper transitive reads are not covered: all three incidents were direct members, and a guard chasing the whole transitive surface would demand bindings the harness legitimately never needs. CAN-FAIL, PROVEN AGAINST THE REAL DRIFT, not a synthetic name: with the three new bindings removed the guard reports `['_MAMBA_AVAIL_ABSENT', '_local_mamba_avail', '_publish_uniform_mamba_floor']` in one message. A second case plants a member nothing binds, and a third pins that the extractor separates reads from writes. RESULT. The two PrefillAdmissionBudgetTest cases exercise the real contract again: test/registered/unit/managers 2058 passed, 2 failed, down from 4. NO PRODUCT CODE. This commit touches one test file. REMAINING, NOT FIXED HERE AND WORTH NAMING: the two failures left in that directory are the SAME class in a different harness -- `test_first_chunk_dynamic_chunking.py` fails with `AttributeError: '_Sched' object has no attribute '_log_dynamic_chunk_engaged'`. Same stub-drift shape, same one-name-at-a-time signal, and the guard idiom above would close it the same way.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
…s one thing FOURTH INSTANCE OF THE SAME SHAPE, and the last one in this directory. sgl-project#656 added an engagement-proof call to `dynamic_chunked_prefill_size` and nothing bound it on `_Sched`, so both sizing cases failed with `AttributeError: '_Sched' object has no attribute '_log_dynamic_chunk_engagement'` -- the same one-name-at-a-time signal that let `BudgetHarness` drift three times running. `_log_dynamic_chunk_engagement` is bound off the real class for the same reason `size_for` is: a stand-in that reimplements it stops pinning it. It writes `_dyn_chunk_last_logged` on the instance and reads `chunked_prefill_size`, both of which this harness already had. THE REFINEMENT THIS HARNESS FORCED, and it makes the idiom correct rather than merely repeated. The sgl-project#610 guard descends one level into the callees of the method under test. Applied naively here it demands `length_predictor`, `model_config`, `ps` and `max_prefill_tokens` -- all reachable only through `predict_next_chunk_size`, which `_Sched` OVERRIDES with its own recording stub. That is the whole point of the harness, the production predictor is never reached, and a guard demanding its state would fail on bindings the harness legitimately does not need -- exactly the over-reach the sgl-project#610 docstring warned about but did not yet encode. So `_required_surface` descends only through callees the harness actually INHERITS (`getattr(harness_cls, name) is getattr(Scheduler, name)`). The requirement then equals what the code path really touches. Two cases pin both halves: an overridden callee is not descended into, an inherited one is. The sgl-project#610 guard is retrofitted to the same rule in this commit. It changes nothing there -- every helper that harness uses IS bound off `Scheduler` -- and is done so the two guards are one idiom rather than two that drifted at birth. CAN-FAIL, PROVEN AGAINST THE REAL DRIFT: removing the new binding makes the guard report `['_log_dynamic_chunk_engagement']` in its own message, before the sizing cases can fail with an AttributeError. A second case plants a member nothing binds. RESULT: test/registered/unit/managers is FULLY GREEN -- 2064 passed, 0 failed, 18 skipped. It was 4 failures when this thread of work started and 2 after the `BudgetHarness` fix. NO PRODUCT CODE. Two test files.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
…-project#681 ceiling is bound CAUSED BY MY OWN FIX, WHICH IS THE POINT. Cherry-picking sgl-project#681 onto this branch added `fundable_extend_floor` to `PrefillAdder`, and `test_collective_family_siblings_610` builds its adder with `PrefillAdder.__new__` and hand-sets every field the predicate reads. The new one was absent, so both admission cases raised `AttributeError: 'PrefillAdder' object has no attribute 'fundable_extend_floor'` -- the same stub-drift shape as the three that came before it, this time introduced by a fix rather than by a reduce. Bound in the stub, and the stub extracted into `_budget_state_stub` so there is one place to bind rather than a literal inside a loop. GUARDED, SCOPED TO WHAT THE PATH ACTUALLY READS. The guard checks the stub against `rem_total_tokens` and NOT against the whole `budget_state` surface: the stub pins `is_hybrid_swa` / `is_all_swa` False, so the SWA members (`rem_swa_token_offset`, `rem_swa_tokens`) are never reached and demanding them would fail the guard on state this harness legitimately does not need -- the same over-reach the sibling guards are scoped to avoid. `rem_total_tokens` is the term the uneven-DCP budget is about and where the sgl-project#681 ceiling landed. CAN-FAIL, against the real drift: removing the binding makes the guard report `['fundable_extend_floor']` in its own message, and it goes red BESIDE the two admission cases rather than after them. test/registered/unit/managers: 2084 passed, 0 failed -- green again with the sgl-project#681 fix on the branch. Test file only; the production behaviour is correct and it was the stub that was incomplete.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
…e two commits to hold MERGE_NOTES_602.md rewritten to cover all 18 commits: what each fixes, its test evidence, whether it touches runtime, and whether an equivalent patch is already on the serving line (verified with `git cherry`, not by message matching -- four are: c41645c, ce60358, 658ea3a, 84b0171). DRY RUN: clean. Merged into `integration/r2` -- the live line, since the serving tree descends from its tip a73a0d8 -- in a throwaway worktree, `--no-commit --no-ff`, then aborted and the worktree dropped. Zero conflicts, zero unmerged paths, so nothing was pre-resolved because nothing needed it. Verified semantically as well as textually: on the MERGED tree, managers 2093 passed / 0 failed and planner 2574 passed / 2 failed, the two being the same pre-existing test_rejected_evidence_pins pair that is already red on the base. THE FACT THE OPERATOR NEEDS, and it is not in the commit count: `7936bc4850` is NOT an ancestor of integration/r2, so merging this branch drags in its whole base lineage -- 115 commits, of which 18 are mine and 97 are the hotfix/677 work (sgl-project#662 x20, [PhasePolicy] x18, sgl-project#677 x8, sgl-project#678 x7, sgl-project#679 x6, ...), 129 files, +22731/-762. Approving this merge is approving that lineage, most of which is not mine to vouch for. If only this work is wanted it must be cherry-picked rather than merged. NOT ATOMIC, and it splits cleanly into four groups with an order: (1) the four already on serving -- merging them only reconciles integration with what is already running; (2) the three sgl-project#624 test-only drift guards, which take managers from 4 failures to 0 and should land early so the line stays green during review; (3) desk tool + docs, all planner/pp_cut.py and markdown, imported by no serving path; (4) hold. HOLD, two commits, both runtime and neither on the serving line: * e21e87f (sgl-project#690) touches the seam hot path and changes the PHASE-FLIP DONE format. Already queued to land on deploy WITH the W=8/W=4 probe after the sgl-project#694 soak verdict; merging it into integration first puts it in front of the soak meant to measure it. * 5301b94 (sgl-project#685) touches the boot sizing path. Announce-only today and abstention-guarded, but unsoaked, and the R' decision it waits on is not made. Nothing else in the chain can move serving behaviour. Docs only; no merge performed, no deploy, scratch worktree removed.
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
…th collective sgl-project#517 named five BAR1 broadcasts on the HOST path per NEXTN decode round. Verified against the current tree, that inventory is now THREE, not five: the three verify-result syncs were fused into one by pack_accept_payload (#616c). The remaining two are the draft-pick sync in _draft_extend_for_decode, which capture_safe_tp_broadcast still issues one collective PER tensor from its loop. This fuses that pair into one buffer. The picks have mixed dtypes (topk_index integer, topk_p float32 at the SAME shape), so unlike the int32 accept payload the fusion is byte-level. Contiguity is required rather than coerced: reshape(-1) on a non-contiguous tensor returns a copy, so an in-place unpack through it would silently drop the broadcast. fuse is opt-in per call site and defaults OFF. _broadcast_draft_picks is also called from inside the draft CUDA-graph capture (draft_forward), and enabling fusion globally would change what a captured region allocates -- a capture change. Only the site that is both per-decode-round and outside any captured region opts in; the prefill, catchup and in-loop sites stay byte-identical. Not claimed here: a ms/round figure. sgl-project#476's 6.64 pp Seam A cost was measured with the pre-sgl-project#517 guard, which synchronised once per collective; sgl-project#517 removed that sync, so the per-collective price must be re-measured on metal rather than carried over. The A/B is window-gated. Tests: test_draft_pick_fusion_524.py, 7 passed (red first: the three symbols did not exist). Regression over test/registered/unit/debug -k "616 or spec_util or draft_pick or eagle or broadcast": 351 passed, 4 failed. Those 4 are pre-existing and unrelated -- verified by reverting both source files and re-running: test_barlink_bar1_abort_poll_616f.py fails identically on the clean tree (SimpleNamespace missing _round_dev, a sgl-project#624-class stub drift). ruff check clean on both changed files (the one F401 in eagle_worker_v2.py is pre-existing on HEAD); ruff format applied.
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
… percent at L=16 Desk halves of sgl-project#700. Paused mid-ticket for the sgl-project#702 priority insert; part 3 (the identity arm) is specified but no arm has been run. (1) Wiring contradiction resolved: the KERNEL HEADER is stale, not the wiring. fused_recurrent_linear_replayssm.py:10-12 claims the feature is "NOT yet wired into the memory pool / radix cache / scheduler / backend dispatch". It is wired in all four: ring allocation and documented layout (memory_pool.py:469-477, 611-633), cursor reset on slot alloc (:1530), copy_from with a stated invariant and dst reset (:941-968), flush/clear (:908), write_pos carried in the offload/restore blob (:1017, :1049, :1075), the radix donate capped to the last flush boundary (mamba_radix_cache.py:599-608), its unified-cache mirror (mamba_component.py:409-417), backend plus CUDA-graph static buffers (hybrid_linear_attn_backend.py, 54 refs), and dispatch (gdn_backend.py:497-537). So sgl-project#700 does NOT close as refused-until-fixed: the seam hazard the ticket anticipated -- a donate or copy mid-window against an unflushed ring -- is addressed head-on and documented at both sites. No correctness hole found. Two findings remain. (a) The copy_from invariant is enforced only under debug_memory_pool, off by default, so in production it rests on caller discipline in a docstring; a fourth caller would violate it silently. That is the sgl-project#624 drift class -- hardening candidate, not a bug today. (b) _build_tree's docstring says the pools are built "on CPU", but construction reaches utils/common.py:1322 and raises "No accelerator ... is available" under CUDA_VISIBLE_DEVICES="". A second comment that does not match its code. Execution status, stated plainly: the ticket asked to settle this BY EXECUTION and that is blocked hermetically by (b) -- the pre-existing TestFlushResetsMambaPool fails identically, so this is not introduced here. The determination above is therefore made by reading. The executable proof is committed and waiting for a GPU window: TestReplaySsmRadixSeam, four tests covering ring allocation, dst-cursor reset, the can-fail proof that the documented invariant trips under the debug guard, and one that pins (a) as a fact by showing an unflushed source is copied silently with the guard off. THESE TESTS HAVE NEVER RUN AND ARE NOT REPORTED GREEN. (2) The net count left open in sgl-project#325: total(L) = S + R + ((L-1)/2)R + S/L with S = 3,145,728 B and ring append R = 32,960 B/step (d 24,576 + k 8,192 + g 192; note replayssm_k is per K-head, 16, not per V-head). At the default L=16 the saving is 40.4 percent of chain bytes, a 1.68x reduction -- below the header's "roughly halved" because the reconstruction re-read is priced at zero there. The optimum is L* = sqrt(2S/R) = 13.8, so the shipped default sits within 0.1 percentage points of optimal and the curve is flat from L=8 to L=24. L=1 comes out worse than baseline at -0.5 percent, the sanity result a correct count must reproduce. Against sgl-project#325's >10 percent gate this clears by 4x versus 0.99 percent for the best fusion. (3) Identity arm specified, not run: CPU-sampled inputs, A-vs-A floor first, probe kept under the ~109-token GDN prefill non-determinism ceiling, GDN scalar-gate only, and the identity result gates whether the perf arm is worth running at all. Docs plus one window-gated test class. No enable-flip, no deploy.
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
Builds the instrument this ticket has now needed three times (budget posts, then available_bytes, now the post's own parts), and closes the recurring reconciliation blocker. The post has been labelled "mamba state pool + speculative intermediate state + prefill activation reserve" all along while emitting ONE number. That lump is why the illegitimate gap could not be attributed: the post nominally covers a SUPERSET of the "Mamba Cache is allocated" line -- it adds the prefill activation reserve -- yet measures 0.155 / 0.111 / 0.089 GiB LESS on PP0/PP1/PP2. A term covering more cannot legitimately measure less, but with a single number there is no way to say which of the three carries it. Next boot there will be. decompose_mamba_budget_post is a pure function, so it is testable without a boot. Two properties are pinned separately: the parts SUM to the lump exactly (a decomposition that changed the total would silently move the KV budget), and the residual is NAMED as the state pool rather than left anonymous. A negative residual is reported, not clamped -- a negative state pool is precisely the error this instrument exists to surface, and clamping would hide it. With no components the lump is returned unchanged, so the other budget branches are untouched. Wired at all five sites that actually move the number: four speculative- intermediate subtractions across the branches, plus the prefill activation reserve. One self-inflicted defect caught and fixed before push. The accumulator started as a bound method, which broke eleven ceiling-fit tests immediately: their SimpleNamespace doubles bind handle_max_mamba_cache as a plain function and cannot resolve self._note_mamba_component. That is the sgl-project#624 stub-drift class with me on the wrong side of it. Fixed by making the helper module-level and duck-typed -- production must not demand more of a stand-in than the behaviour under test needs -- and the reason is recorded in its docstring so it does not get "tidied" back into a method. Tests: 6, red first. model_executor suite 600 passed / 15 failed, and the 15 are the SAME pre-existing set as before this change (594 + the 6 new = 600). ruff clean.
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
Builds the instrument this ticket has now needed three times (budget posts, then available_bytes, now the post's own parts), and closes the recurring reconciliation blocker. The post has been labelled "mamba state pool + speculative intermediate state + prefill activation reserve" all along while emitting ONE number. That lump is why the illegitimate gap could not be attributed: the post nominally covers a SUPERSET of the "Mamba Cache is allocated" line -- it adds the prefill activation reserve -- yet measures 0.155 / 0.111 / 0.089 GiB LESS on PP0/PP1/PP2. A term covering more cannot legitimately measure less, but with a single number there is no way to say which of the three carries it. Next boot there will be. decompose_mamba_budget_post is a pure function, so it is testable without a boot. Two properties are pinned separately: the parts SUM to the lump exactly (a decomposition that changed the total would silently move the KV budget), and the residual is NAMED as the state pool rather than left anonymous. A negative residual is reported, not clamped -- a negative state pool is precisely the error this instrument exists to surface, and clamping would hide it. With no components the lump is returned unchanged, so the other budget branches are untouched. Wired at all five sites that actually move the number: four speculative- intermediate subtractions across the branches, plus the prefill activation reserve. One self-inflicted defect caught and fixed before push. The accumulator started as a bound method, which broke eleven ceiling-fit tests immediately: their SimpleNamespace doubles bind handle_max_mamba_cache as a plain function and cannot resolve self._note_mamba_component. That is the sgl-project#624 stub-drift class with me on the wrong side of it. Fixed by making the helper module-level and duck-typed -- production must not demand more of a stand-in than the behaviour under test needs -- and the reason is recorded in its docstring so it does not get "tidied" back into a method. Tests: 6, red first. model_executor suite 600 passed / 15 failed, and the 15 are the SAME pre-existing set as before this change (594 + the 6 new = 600). ruff clean.
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
…s the ledger the host had ROOT. evict_from_tree_cache gates the eviction on uniform_avail_for_evict(...) < num_tokens. That reads tree_cache.uniform_avail_floor, published ONCE per iteration (scheduler.py:4142-4144) as the group MIN of available_size(). Allocations made later in the same iteration were never charged against it, so late in an iteration the number is stale-OPTIMISTIC: with floor >= num_tokens the eviction is SKIPPED entirely, the alloc then fails against the live pool, and the raise reports a tree full of evictable tokens nothing ever asked for. Not a new class -- the HOST sibling already had this fixed. Its own comment states the reasoning: "a stale floor over-admits ... charging admissions against the floor removes the staleness without a second collective". The DEVICE sibling never got the ledger. This adds it, mirroring sgl-project#645 exactly: uniform_admitted_since_floor, charged on the success path of alloc_token_slots, reset by the scheduler in the same call that publishes the next floor so it never outlives the number it corrects. Sufficient, by sgl-project#645's argument: live availability is at least avail_at_publish - admitted, and avail_at_publish >= floor, so a request clearing floor - admitted fits the real pool. Rank-uniform by construction: num_tokens comes from the replicated batch, so every rank charges the same amount at the same allocation and the predicate stays identical across ranks -- the #616g invariant this must not break, pinned by a test. fundable_extend_tokens reads the same predicate, so admission inherits the correction for free. OVERLAP VERDICT vs sgl-project#701(a), checked in code rather than assumed: NOT one defect, on the available evidence. * evictable and protected are DISJOINT by construction -- inc_lock_ref moves tokens out of evictable_size_ into protected_size_ (radix_cache.py:605-606) and dec_lock_ref moves them back (:622-623). So a reported evictable count never includes protected-prefix pages. * The only specimen present in any accessible log is 66039 (available=273 + full_evictable=65766, 512 requested). Its "Full LRU list evictable size: 65766" matches full_evictable_size EXACTLY. That sanity check is an independent traversal of the eviction list, and divergence is precisely what it exists to detect -- so this specimen's evictable was genuinely reachable, refuting the paper-evictable hypothesis for it. It is also the specimen sgl-project#681 already diagnosed (mamba tombstone leaf) and paid in MambaRadixCache. evict_full. * The "167k evictable" specimen is NOT in any log I can reach, so its decomposition into mamba-recoverable vs paper-only cannot be done and is not inferred. If F4-r4's 1f594e7 instrument catches a recurrence, its skipped-vs-ran line decides it directly. So the staleness defect is proven STRUCTURALLY (the host/device asymmetry) and fixed with a can-fail falsifier; it is not claimed as the cause of a specimen whose instrument output does not exist. One self-inflicted defect caught by the suite: getattr(tree_cache, "uniform_admitted_since_floor", 0) yields a Mock on an unconfigured double, and int(Mock()) is 1, not 0 -- silently shaving a token off the floor and breaking test_a_published_floor_is_returned (499 != 500). Guarded by an isinstance check, with the reason recorded. Third appearance of the sgl-project#624 stub-drift class. The host sibling carries the identical latent exposure and is left untouched here to keep the blast radius small; worth a follow-up. Tests: 7, red first, including the can-fail proof that an uncharged stale floor really does skip. managers 2113 passed / 0 failed. mem_cache is 944 failed / 772 passed both before and after this change -- a large PRE-EXISTING red suite, verified by patch round-trip on the clean tree (945/2870 baseline across managers+mem_cache without the new file). ruff clean on all three files, compared against HEAD.
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
…s the ledger the host had ROOT. evict_from_tree_cache gates the eviction on uniform_avail_for_evict(...) < num_tokens. That reads tree_cache.uniform_avail_floor, published ONCE per iteration (scheduler.py:4142-4144) as the group MIN of available_size(). Allocations made later in the same iteration were never charged against it, so late in an iteration the number is stale-OPTIMISTIC: with floor >= num_tokens the eviction is SKIPPED entirely, the alloc then fails against the live pool, and the raise reports a tree full of evictable tokens nothing ever asked for. Not a new class -- the HOST sibling already had this fixed. Its own comment states the reasoning: "a stale floor over-admits ... charging admissions against the floor removes the staleness without a second collective". The DEVICE sibling never got the ledger. This adds it, mirroring sgl-project#645 exactly: uniform_admitted_since_floor, charged on the success path of alloc_token_slots, reset by the scheduler in the same call that publishes the next floor so it never outlives the number it corrects. Sufficient, by sgl-project#645's argument: live availability is at least avail_at_publish - admitted, and avail_at_publish >= floor, so a request clearing floor - admitted fits the real pool. Rank-uniform by construction: num_tokens comes from the replicated batch, so every rank charges the same amount at the same allocation and the predicate stays identical across ranks -- the #616g invariant this must not break, pinned by a test. fundable_extend_tokens reads the same predicate, so admission inherits the correction for free. OVERLAP VERDICT vs sgl-project#701(a), checked in code rather than assumed: NOT one defect, on the available evidence. * evictable and protected are DISJOINT by construction -- inc_lock_ref moves tokens out of evictable_size_ into protected_size_ (radix_cache.py:605-606) and dec_lock_ref moves them back (:622-623). So a reported evictable count never includes protected-prefix pages. * The only specimen present in any accessible log is 66039 (available=273 + full_evictable=65766, 512 requested). Its "Full LRU list evictable size: 65766" matches full_evictable_size EXACTLY. That sanity check is an independent traversal of the eviction list, and divergence is precisely what it exists to detect -- so this specimen's evictable was genuinely reachable, refuting the paper-evictable hypothesis for it. It is also the specimen sgl-project#681 already diagnosed (mamba tombstone leaf) and paid in MambaRadixCache. evict_full. * The "167k evictable" specimen is NOT in any log I can reach, so its decomposition into mamba-recoverable vs paper-only cannot be done and is not inferred. If F4-r4's 1f594e7 instrument catches a recurrence, its skipped-vs-ran line decides it directly. So the staleness defect is proven STRUCTURALLY (the host/device asymmetry) and fixed with a can-fail falsifier; it is not claimed as the cause of a specimen whose instrument output does not exist. One self-inflicted defect caught by the suite: getattr(tree_cache, "uniform_admitted_since_floor", 0) yields a Mock on an unconfigured double, and int(Mock()) is 1, not 0 -- silently shaving a token off the floor and breaking test_a_published_floor_is_returned (499 != 500). Guarded by an isinstance check, with the reason recorded. Third appearance of the sgl-project#624 stub-drift class. The host sibling carries the identical latent exposure and is left untouched here to keep the blast radius small; worth a follow-up. Tests: 7, red first, including the can-fail proof that an uncharged stale floor really does skip. managers 2113 passed / 0 failed. mem_cache is 944 failed / 772 passed both before and after this change -- a large PRE-EXISTING red suite, verified by patch round-trip on the clean tree (945/2870 baseline across managers+mem_cache without the new file). ruff clean on all three files, compared against HEAD.
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
…ling included Third appearance of the stub-drift class earns the consolidation now. Both floor correctors read a per-iteration ledger off the tree cache: the DEVICE one in uniform_avail_for_evict (sgl-project#694) and the HOST one in uniform_host_avail_for_backup (sgl-project#645). Real caches declare the attribute on BasePrefixCache with a 0 default; a test double usually does not, and int(Mock()) is 1, not 0 -- so an unconfigured stand-in silently shaved one token off whichever floor it fed. Measured on both: 499 != 500 against the device ledger (test_a_published_floor_is_returned), and reproduced against the host ledger by a new test that leaves uniform_host_admitted_since_floor unconfigured. The host exposure was real, not theoretical. Rather than a second isinstance check that would drift from the first, both sites now go through _ledger_tokens, whose docstring IS the named list the audit asked for -- there is no separate registry doc to add them to, and a helper both callers must use is a stronger guarantee than a list someone has to remember to read. bool is excluded deliberately: it is an int subclass, so a truthy flag landing there would charge 1 token for exactly the reason a Mock did. Tests: 5 more, red first -- the host case failed with the identical 499 != 500 signature before the fix, which is the can-fail proof that the sibling shared the defect rather than being fixed by coincidence. managers + the sgl-project#645 host suite + the sgl-project#694 suite: 2131 passed, 0 failed. ruff clean.
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Aug 16, 2026
…faster A permanently-red suite hides every new regression (sgl-project#380/sgl-project#585 test-honesty class). Hermetic mem_cache stood at 944 failed / 777 passed / 707 skipped in 248 s. It now runs 777 passed / 1651 skipped / 0 failed in 32 s. CLASSIFICATION, and it is simpler than the count suggested: (a) GPU-required under CVD="" ...... 944 of 944 (100%) (b) stub-drift / sgl-project#624-class ........ 0 (c) genuinely broken code paths .... 0 (d) obsolete tests ................. 0 Every one of the 944 shared a single root: get_device() raising "No accelerator (CUDA, XPU, HPU, NPU, MUSA, MPS) or platform plugin is available". Red meant "no GPU here", never "broken". Verified by taking the non-GPU remainder of the FAILED lines, which is EMPTY. Two secondary findings, both of which made this worse than it had to be: * CustomTestCase._callTestMethod wraps every test in utils.common.retry, which re-raises a bare Exception("retry() exceed maximum number of retries.") WITHOUT chaining the cause (no `from e`). The real one-line reason was discarded, so 841 of 944 reported an opaque retry message. That is why a single environmental cause looked like a suite-wide catastrophe. * the same wrapper retried a DETERMINISTIC environment failure several times each, which was most of the runtime -- hence 248 s -> 32 s. FIX. retry() honours exactly one exception: SkipTest is re-raised immediately and never retried. So a directory conftest converts the environmental error into a skip AT ITS SOURCE, which fixes the masking and the retry storm together and needs no edit to any test. It patches get_device on both the defining module and the package namespace, because the tests bind the name at import time and conftest is imported first. Installed ONLY when there is genuinely no accelerator, so a GPU run is unchanged and any real failure stays red; it fires only for tests that actually call get_device, so the 777 that already pass keep running -- the passing count is identical before and after, which is the check that no green test was silenced into a skip. One test needed an individual marker: test_memory_allocated calls torch.cuda.memory_allocated() directly and never goes through get_device. Marked with skipUnless and the reason, rather than widening the patch to cover torch.cuda. PHANTOM MOCK removed (mine, from the sgl-project#701 harness): tc.mamba_recoverable_size was mocked and NO SUCH ACCESSOR EXISTS -- the real one is mamba_evictable_size (mamba_radix_cache.py:1177, unified_radix_cache.py:3189). Nothing read it, so it never produced a false green, but a mock of a non-existent API teaches the next reader an interface the tree does not have, which is the same sgl-project#380 shape. Both it and its unused `recoverable` parameter are gone, with a comment naming the real accessor. mem_cache + managers together: 2883 passed, 0 failed (baseline 945 failed / 2870 passed). ruff clean.
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Aug 17, 2026
…e they raise ROOT, and it is not a new one. free_group_begin is called from the event loop (batch_result_processor.py:92 and :741). While that window is open, PagedTokenToKVPoolAllocator.free appends to free_group instead of extending free_pages (allocator/paged.py:293-308), so the pages sit in neither free_pages nor release_pages and available_size cannot see them -- while the tree has already counted them as evicted. That is sgl-project#681's third root, and flush_free_group (allocator/base.py:208) is its remedy. WHY IT CRASHED AGAIN ANYWAY. The remedy was wired into alloc_token_slots only. The paged twins reached their raise without ever asking whether the pages they needed were already freed and merely staged. The relief NET was carried across to the extend path under "sgl-project#681 RULE 3: every alloc path reachable from prefill admission gets the same net"; the third root was not carried with it, and the decode path had no net of any kind. So: one root, wired on one of the three paths that need it. That is the 02:18 crash -- 512 tokens refused with 147,456 counted evictable. The receipt-checking added in sgl-project#681 cannot catch it, because the eviction's receipt is HONEST: the tokens really were freed. THE LABELLED CANDIDATE IS REFUTED. The proposal was that _evict_leaf_node's allocator.free(x.value) might route rows to one sub-pool of a HybridLinearKVPool while available_size/alloc read another. It cannot produce this divergence: the accounting is entirely allocator-side over index bookkeeping (free_pages / release_pages / free_group), and available_size is computed from those two lists alone (base.py:187-188), so a free and the available_size after it read the same structure however the pool splits its tensors underneath. Pinned in TestAccountingLivesInTheAllocator, including a run with kvcache=None throughout. This says only that the hybrid pool cannot cause THIS divergence, not that it is defect-free. FIX: flush staged frees and retry, on both paged paths, before the relief ladder -- same ordering as alloc_token_slots and for the same reason, that it is not relief. It gives up nothing: it applies frees already performed and already counted. Cold path only, reached after an allocation has already failed. The raises are unchanged, so fail-loud keeps the last word. Tests (hermetic, CUDA_VISIBLE_DEVICES="", no GPU, no serving contact): test/registered/unit/mem_cache/test_paged_staged_frees_715.py 9 passed can-fail proof: the two fix-pins fail without the fix, with the exact production messages ("Prefill out of memory" / "Decode out of memory"); the other 7 hold either way test/registered/unit/mem_cache/ 797 passed, 1651 skipped, 124 subtests test/registered/unit/managers/ 2119 passed, 18 skipped, 130 subtests ruff clean on both changed files The pins drive the REAL PagedTokenToKVPoolAllocator on CPU, inheriting the whole group protocol unmodified; only alloc_extend/alloc_decode are overridden, because the production ones dispatch to CUDA kernels (sgl-project#624: the stub stays off the load-bearing path).
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Aug 17, 2026
…ribution, rank-2 root 1. RESTORE, NEVER REBUILD -- the pin (test_restore_never_rebuild_677.py). A fence patches the BUILD entry points (weights_arena.allocate_arena, weights_arena.pack_into_arena, torch.cuda.CUDAGraph) to raise, and the REAL production mover PhaseFlipStacks.refill runs under it on both legs, including the checksum-mismatch restore arm -- the one branch that touches the arena twice and is likeliest to reach for a rebuild. arena_refill is deliberately NOT fenced: it is the copy the flip exists to perform, and a pin that fenced it would pass by forbidding the work. Can-fail arms: every entry point is shown to actually raise, and a planted mover calling allocate_arena is caught. Pinning production rather than a re-implemented loop is the point -- a re-implementation keeps passing while production drifts (sgl-project#624). 2. PEAK-INSTANT ATTRIBUTION -- PhaseFlipRuntime._record_seam_peak, emitted on the sgl-project#605 flight-recorder channel (not a new one: it already carries the torch view, the NVML view and the boot id, and is append-only). Placed at _staging_affordable, the instant the flip's demand is weighed against free VRAM -- earlier the buffers do not exist, later the decision is already taken. Carries staging_bytes, refill_destination_bytes, graph_workspace_bytes, the reserve, driver free, allocator cached free, and a SIGNED unattributed_bytes. Two choices, both pinned and both mutation-proven: unmeasured components are None and never 0 (a zero reads as "costs nothing" -- the sgl-project#606 defaulted- measurement defect), and the residual is signed, because a negative one means the named terms OVER-count, a different defect that max(0, ...) would hide. Guarded end to end: an instrument on the seam path may cost a line, never a cutover. 3. THE RANK-2 ANOMALY -- the sgl-project#685 candidate is REFUTED. sgl-project#685 (0e50e48, f1774d7) is an UnboundLocalError use-before-bind on a variable named 'cell' in the cold seam-pricing branch; it has no arena-tail content and no 1456 MiB figure exists anywhere in source or records. The live candidate is arena GROWTH, from the sgl-project#690 image sizes: rank 0 PP 12619.6 TP 9614.9 growth 0.0 seam draw 909 rank 1 PP 9014.0 TP 9614.9 growth 600.9 seam draw 1006 rank 2 PP 7211.2 TP 9614.9 growth 2403.7 seam draw 1648 Rank 0's PP layout is the larger, so it never grows; rank 2 grows four times what rank 1 does. The ordering matches the draws exactly and no other per-rank term does. Stated as a CANDIDATE, not a finding: the excess over rank 0 is 16% of the growth on rank 1 and 31% on rank 2, so growth explains the order and not the size. Instrument 2 settles it without a dedicated experiment -- it emits exactly this quantity at the peak instant. FILED, NOT BUILT: TICKET_718_contiguous_destination_extent.md -- making a peer's destination extent contiguous so a BAR1 write lands in place and the receive buffer stops existing. The largest structural reduction available, and the only one that removes a buffer rather than relocating it; it touches the reshard wire format and the pool allocator together, so it belongs to a deliberate design pass. The ticket names what must be decided, what must not be assumed (it trades allocator freedom for staging bytes, and that freedom is what keeps admission working under fragmentation), and makes a live reading from instrument 2 its prerequisite. Tests, hermetic (CUDA_VISIBLE_DEVICES="", no GPU, no serving contact): test_restore_never_rebuild_677.py 7 passed + 3 subtests test_seam_peak_attribution_677.py 8 passed MUTATION PROOF: null->0 and signed->floored fails 3 of 8 FULL SUITE compared by failing NODE ID against base b786858, ANSI stripped (counts alone hid a real regression earlier in this branch): base 13 failed / 2181 passed; now 13 failed / 2208 passed regressions: NONE. The 13 are pre-existing. ruff + codespell clean on all changed files. Desk only. Live readings ride the later review boot.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Aug 17, 2026
…de a solved phase layout Builds the piece the remainder determination (af2b34e) rescoped: solve the layout ONCE per phase and say where each family lands inside it. The runtime per-family flip stays closed -- it needs ~17,500 rounds to repay a whole-arena refill -- but placement inside a flip that is already happening is free. ## No second solver, which was the acceptance condition planner/boot_layout.py does not search, price or re-derive anything. It consumes a PPCutSolution that solve_pp_cut already produced and re-presents it per family. A test pins that the module's source contains no call to solve_pp_cut and no _price_stage, so the cut can only change if the SOLVER changed. The composition was cheap because the solver already carried the family axis: PPCutSolution.attention_counts is a per-stage family placement in all but name, and layer_families tags every layer. What was missing was a named shape, the other families, and one authority for the emitted flags. ## One authority for the printed remedy server_args already computes the paste-ready --pp-attn-stage-ratio when a snapped cut needs announcing (sgl-project#713, 88a0d78): "the full-attention counts of the operator's own requested ranges ARE the --pp-attn-stage-ratio that realizes them". The chooser emits that SAME quantity from the SAME field (solution.attention_counts), so the printed remedy and the solved layout cannot drift. --pp-layer-ratio comes from as_layer_ratio() VERBATIM; a test pins it byte-identical, and the mutation that re-derives it as an even split turns exactly that pin red. ## The enumeration gap: closed where funded, NAMED where not (sgl-project#253) PPCutInputs carries measured terms for exactly TWO families -- attention (attn_layer_weight_bytes, attn_layer_flops_per_token, attn_core_flops_per_token_pair) and linear (linear_layer_weight_bytes, linear_layer_flops_per_token). Both are now emitted as placements. Every other family in the sgl-project#485 law has NO input in this cost model, so none got one invented. UNFUNDED_FAMILIES records each with the measurement that would fund it, in the module that omits them rather than in a doc: kv_heads not a PP-layer family at all -- a TP-axis quantity, so per-STAGE placement is the wrong shape vocab embed/lm_head are not per-layer, so layer_families never tags them; needs measured bytes AND stage affinity experts no MoE family in this checkpoint's layer_types nonlinear_kernels folded into per-family layer FLOPs; needs a decomposed measurement linear_per_quant_lane linear_layer_weight_bytes is ONE scalar for the family; needs per-lane bytes measured from the checkpoint A test asserts every entry names a measurement, and another asserts no speculative term (expert_layer_weight_bytes, vocab_weight_bytes, ...) appears in the source. ## ABSENT is not ZERO (sgl-project#606) Families are derived from layer_families, so a family the checkpoint lacks produces no entry -- and asking for it RAISES with that reason rather than returning a zero vector. The mutation that pre-seeds both families (zero-filling a model that has only one) turns exactly that pin red. ## Refusals An INFEASIBLE solution emits no flags at all ("do not paste this layout") -- flags for a cut the solver already rejected are how an operator pastes a boot that cannot come up. A layer_families vector that does not match the cut's depth is refused as describing a different model. The phase is NAMED (PHASE_PP_PREFILL), not assumed: sgl-project#485's matrix has a decode column and this solver does not solve it. ## Tests test/registered/unit/planner/test_boot_layout_485.py -- 18, driven by the REAL solver through the existing sgl-project#485 fixture rather than a stand-in, because a stub would let chooser and solver drift (sgl-project#624). mutations, one per contract: zero-fill absent families -> 1 red (the sgl-project#606 pin) re-derive the layer ratio as an even split -> 1 red (the byte-identity pin) restored -> 18 passed test/registered/unit/planner: 2 failed / 2529 passed. Both failures are PpWithSpecEvidenceTest, the stale-register drift I diagnosed and fixed in 54ffc4d, which has not reached this base -- pre-existing and unrelated, and a merge-train item. A vacuous assertion of my own, caught by re-reading rather than by a failure: the gap-funding test asserted `assertIn("Would need", why + "would need")`, concatenating the needle onto the haystack so it could never fail. Fixed to check the actual value.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Aug 24, 2026
The user asked why a tp_to_pp flip takes 11.6 s, and whether 16 waves over
116502 live slots could not just be moved in one parallel shot. The capture
answers the first half and refutes the premise of the second.
THE 116502 LIVE SLOTS AND THE 16 WAVES ARE NOT THE COST. W25's own seam
census names one segment:
seam-census] timing tp_to_pp rank 0: 10466.8 ms across 448 segment(s),
worst 'refill_highwater->weights_refill' 9516.2 ms (91% of the walk)
kv_write->gdn_state 174.3 | cutover->done 152.4 |
flip_writeback->hicache_quiesce 74.8 | kv_pack->kv_local_read 57.4
Three consecutive tp_to_pp flips: 9516.2 / 9496.5 / 12108.2 ms in that one
segment, against totals of 10466.8 / 10568.0 / 13181.2. Meanwhile the ENTIRE
KV movement at the largest observed reshard (epoch 11, 116502 live slots,
995.31 MiB sent / 825.03 MiB received) is read 19.9 + exchange 486.0 + write
394.8 = 901 ms, and the GDN blob is 11.69-18.70 MiB. Across the window live
slots grew 947x (123 -> 116502) while the flip grew 1.26x (5077.9 -> 6416.0
ms). The ranks are already parallel: totals agree within ~40 ms while movers
legs differ by ~600 ms, and the peers absorb PP0's overrun as CUTOVER WAIT
(1313.3 / 1220.8 ms vs PP0's 225.3). A rendezvous, exactly as sgl-project#690 recorded.
SO THE SEAM IS A WEIGHTS-REFILL RATE PROBLEM, and the rate is direction-
asymmetric for reasons nothing in the tree explains. Same rank, within 2.7%
of the same bytes:
pp_to_tp 15925.8 MiB 3214-3915 MiB/s 4.07-4.96 s
tp_to_pp 16362.7 MiB 1351-1723 MiB/s 9.50-12.11 s
FOUR CANDIDATE EXPLANATIONS WERE CHECKED AND ALL FOUR FAIL, and they are
recorded so nobody re-derives them:
* not a path fallback -- SGLANG_PHASE_FLIP_REFILL_STAGED defaults True
(environ.py:348), unset in the boot, and arena_refill dispatches on the
image being file-backed, not on direction. Both take _staged_file_refill.
* not a missing fd -- both sgl-project#802 warning paths ("could not open a read fd",
"O_DIRECT unavailable") appear ZERO times in the 3.45 MB capture, against
9 "flip host image FILE-BACKED" registrations.
* not the O_DIRECT alignment cliff (sgl-project#809's 8304 -> 2595 MiB/s) -- the loop
only issues aligned offsets: chunks are 32 MiB multiples of
_DIRECT_ALIGN=4096 and `want` is rounded down to it; only the trailing
checksum tail is buffered, by design.
* not the pre-sgl-project#802 fault path -- on sgl-project#802's own discriminator the fault path
makes rank rates CONVERGE (821/775 MiB/s on links differing 1.80x). W25
DIVERGES with the link in both directions (1.59x and 1.40x).
THE INSTRUMENT IS WHAT IS MISSING, NOT THE MECHANISM. The leg reports ONE
aggregate MiB/s. The read (os.preadv) and the H2D (copy_ on a stream, depth
2) are pipelined, so that aggregate is min(read_rate, h2d_rate) with no way
to see which bound it hit. That is the sgl-project#851 class -- one number with several
meanings -- sitting inside the term that is 91% of the seam, which is why two
independent readers could not attribute the gap from code.
WHAT SHIPPED. `RefillLegTiming` accumulates, on the existing path:
read_s wall time inside preadv -- storage/ARC bound
h2d_wait_s wall time blocked on a prior DMA -- PCIe/link bound
drain_s the pipeline tail, counted apart so it can never be mistaken
for either bound
They are near-exclusive by construction: the ring only waits on a buffer
whose copy has not landed, so a read-bound leg never blocks there and a
link-bound leg blocks almost every turn.
`refill_bound_phrase` is a PURE function over that record -- no GPU -- so
both directions are falsifiable off metal, the same split sgl-project#852 used for the
allocator-cache estimator and for the same reason: a rule that can only be
exercised on metal is one this corpus has repeatedly shipped inert.
THE CAN-FAIL DIRECTION IS THE WHOLE RISK and is pinned. A phrase that always
named a bound would satisfy every "it says something" assertion while being
exactly as useless as the aggregate it replaces. So "unattributed" (not
instrumented, or no time accounted) and "MIXED" (neither half dominates) are
first-class outcomes, asserted directly, and a 101-point sweep across the
whole read-share range proves the three verdicts neither overlap nor leave a
hole.
NO BEHAVIOUR CHANGE: the timing record is optional and defaults to None, so
every caller that does not pass one runs byte-identically.
ONE PINNING TEST HAD TO MOVE, and it is worth naming because widening it
blindly was the tempting wrong answer. `test_arena_high_water_631.py`'s
`fake_arena_refill` stub replaces `arena_refill` to prove the arena is
committed before it is copied into; it did not accept the new kwarg and all
six of its refill tests failed with TypeError -- the sgl-project#624 stub-drift shape.
The stub now accepts `timing=None` (which is the whole adaptation, since the
record is an instrument with no semantics the test pins), AND it captures
what it was handed, with a new `test_the_refill_leg_is_instrumented`
asserting the caller really does pass a `RefillLegTiming`. Without that, the
signature widening would have silently tolerated the instrument being
unwired again -- a stub that accepts anything proves nothing.
TESTS (hermetic, CUDA_VISIBLE_DEVICES=""):
test_refill_bound_856.py 9 passed, 101 subtests
test/registered/unit/model_executor/ 15 failed / 763 passed, against a
VERIFIED HEAD baseline of 15 failed / 754 passed -- identical failure
set, pre-existing, unrelated to this path (bf16 vendor fallback,
coresidence budget, expert-offload kv regain). Checked by reverting this
change and re-running, not asserted.
ruff format clean; the one F401 in phase_flip_boot.py is pre-existing at
HEAD (verified against git show HEAD:...).
Full ledger, with every figure and every failed search set:
docs/dev/NOTE_856_seam_cost_ledger.md
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Sep 2, 2026
… (905 double, 1035c stub) Two test stand-ins that the branch's new production contracts outgrew (sgl-project#624/sgl-project#978 stand-in-drift class). Production is the reviewed, accepted contract in both cases and is NOT touched; only the stand-ins move. DRIFT 1 -- the sgl-project#905 census-scheduler double missed the A12.2 cutover clearer. test/registered/scheduler/seam_census_double.py:417 (FaithfulCensusScheduler) binds the REAL Scheduler.readmit_seam_residents, which since the slice-3 fix calls self._clear_prefetch_deferral_for_reissue(population) at python/sglang/srt/managers/scheduler.py:5810 (definition :6292, lifecycle CLEARER (c) in the table at :5969). The double bound the caller but not the helper -> AttributeError, surfacing as "retry() exceed maximum number of retries". Fix: bind BOTH real methods (_clear_prefetch_deferral_for_reissue and the _clear_prefetch_deferral_fields it calls) from the real class, not a no-op. A no-op stand-in would be the W29 direction again: the double would pass a cutover that never cleared, i.e. exactly the defect the clearer exists for. The A12.2 fields are deliberately NOT pre-planted on FaithfulReq -- the real Req does not declare them either (no occurrence in schedule_batch.py); they are planted dynamically by _apply_prefetch_deferral and every reader uses getattr(..., default). Absence is the faithful state. This is the same edit the slice-3 fix already made in the two sibling doubles (test/registered/unit/managers/test_seam_readmission_w31.py:87-89 and test_prefetch_deferral_1068.py:195-197); the 905 double was the one instance missed by that sweep. DRIFT 2 -- the #1035c stub missed the termination protocol. python/sglang/srt/mem_cache/hybrid_cache/hybrid_cache_controller.py:752 reads operation.is_terminated() DIRECTLY (branch commit 846c679, slice 2 fix 4). That override is a FULL replacement of the base probe -- one batch_exists call over the whole span, no per-batch loop -- so the base class's per-batch guard never reaches it, and the class-agnostic getattr form at managers/cache_controller.py:851 is a different pass and does not apply here. The stub at test/registered/unit/mem_cache/test_zero_answer_partition_1035c.py:172 built the operation without the protocol. Fix: the stub answers is_terminated() -> False (a live operation, which is what all four fixtures are about), modelling StorageOperation.is_terminated at managers/cache_controller.py:287. mark_terminate is deliberately NOT added: this path never calls it, and a stub method nothing drives is surface without a contract behind it. hybrid_cache_controller.py:752 is NOT weakened to a getattr. TALLY (hermetic: CUDA_VISIBLE_DEVICES="", PYTHONPATH=<worktree>/python, pytest -q -p no:cacheprovider, per file, run once each) test_seam_census_double_905.py before 6 failed / 14 passed after 0 failed / 20 passed test_zero_answer_partition_1035c.py before 4 failed / 5 passed after 0 failed / 9 passed THE FOUR 905 REDS THAT PRE-DATE THIS BRANCH test_every_resident_is_retracted_readmitted_and_off_the_live_set, test_no_row_belongs_to_nobody_afterwards, test_the_drop_evicted_before_it_ reset, test_the_seam_stamped_its_own_retractions were already RED at the pin 228a66d, so the branch gate counted only the other two as truly new. They go GREEN here with the same stand-in fix and no further edit. Their pin-era cause is therefore not present on this branch: the sgl-project#1068 slice work rewrote the production seam and this suite together (git diff 228a66d..HEAD touches seam_census_double.py +47/-33 and test_seam_census_double_905.py +60), and the clearer binding was the last piece missing. Not carried forward as debt -- the file is 20/20. Checks: both files run once each (above); import smoke of sglang.srt.managers.scheduler and sglang.srt.mem_cache.hybrid_cache.hybrid_cache_controller OK; ruff check and ruff format --check clean on both files. No production file touched.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Sep 14, 2026
…ole class Coordinator finding: `_weg2_xchg_draft_plan_or_none` = 0 hits in the script, 4 in weight_updater.py -- sgl-project#1394 added a new call from `_weg2_shadow_plan` that `_Stub` never borrowed, so section [1] of xchg_provider_smoke.py has been silently degraded (a real AttributeError caught by _weg2_shadow_plan's own `except BaseException` and returned as an ordinary "derivation failed" string) since sgl-project#1394 landed, with nobody noticing except by reading the output. This is the sgl-project#624/sgl-project#978 stub-drift class. (1) THE FIX: borrowed the real `_weg2_xchg_draft_plan_or_none` onto `_Stub`, the same doctrine as the four names already there -- not a hand-written neutral stub. Justified in code: the real method's own body already answers "no draft worker in this process" gracefully (`getattr(self, "draft_worker", None)`, returns `(None, "")`, never raises) -- exactly the state a `_Stub` instance is in, since it never sets `draft_worker`. A fabricated neutral stub would be a second, hand-maintained copy of a judgement call the real method already makes for itself, and would violate this file's own stated rule ("what runs here is byte-for-byte the code the flip leg runs"). (2) THE RATCHET: `test_weg2_1363_smoke_stub_drift.py` + `weg2_smoke_stub_support.py`. Read the sgl-project#624 precedent first (27c1791, barlink_stub_support.py) and adapted its shape rather than reinventing it -- but the mechanism differs on purpose: sgl-project#624 audits `__init__`-ASSIGNED ATTRIBUTES via one non-transitive AST walk; this audits `self.<name>` READS via a walk that is TRANSITIVE (a production entry point calls other production methods on the same class, and those may call further ones -- `self_reads_reachable` follows any discovered name that is itself a method defined on the real class). A `getattr(self, "name", default)`-style read is deliberately invisible to this audit: it passes the name as a string argument, never as `self.name` AST syntax, and the real code already tolerates its absence by construction. Prerequisite refactor (behaviour-preserving): `_LegStub`, `_Sems`, `_Region` were local classes inside `main()`, so the ratchet test could not import and introspect them. Hoisted to module level; `_Region` picked up an explicit `boot_nonce` constructor argument instead of closing over `main()`'s local `SMOKE_NONCE`. `_Stub` was already module-level. Computed the real, transitive requirement empirically rather than guessing: `_Stub`/`_weg2_shadow_plan` needs exactly 5 names (4 already borrowed/set, the one gap this commit closes) -- exclusion table starts EMPTY, as ordered. `_LegStub`/`_weg2_xchg_bounce_leg` needs 2 names (`_weg2_xchg_tag_seen`, `_weg2_xchg_undrained_lanes`) that this smoke's own call never reaches (guarded by `tag is not None` / `rank is not None`, and this script passes neither) -- both excluded with a reason naming the guard, per weg2_smoke_stub_support.py. (3) RED-FIRST, against today's tip: with the `_weg2_xchg_draft_plan_or_ none` borrow line removed by hand, test_stub_covers_or_excludes_every_reachable_name failed naming exactly that one attribute -- the calibration proof, verified by temporarily reverting the fix and reapplying it (git diff / git apply), not merely asserted. Mutant test_M_removing_a_borrowed_method_the_stub_needs_goes_ red drives a deliberately incomplete double (`_weg2_join_src_addr` removed) through the identical audit logic and asserts it is caught. Metal proof, same form as round 1: two consecutive real runs on this exact base (train tip includes sgl-project#1334's unrelated doc corrections, no functional change to the audited methods), 19/19 PASS both times, /dev/shm checked before and after both runs -- no weg2-xchg-bnc-smoke* residue. Structural verdict on the coordinator's fallback question (is this script's stub approach ratchet-capable at all?): yes -- `_Stub`/ `_LegStub` are ordinary classes with a finite, fixed set of borrowed methods and constructor-set attributes, never `__new__`-built with hand-set fields the way sgl-project#624's BAR1 transport is, and (after the hoist) both are module-level and import cleanly. Pinned as its own test (TheScriptItselfIsRatchetable) so this finding does not have to be re-derived from the ratchet's mere existence. File boundary: scripts/weg2/xchg_provider_smoke.py (now mine, since sgl-project#1363 round 1) plus two new test-directory files. No change to any DESK9/DESK10-owned file; weight_updater.py was read only, to compute the real transitive requirement and to confirm the unrelated sgl-project#1334 diff between my two verification points touches no audited method body.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Sep 24, 2026
…ec ring 27B ReplaySSM package, slice S3 of REPLAYSSM_PLAN.md. With the flag off every path is unchanged (no rows planned -> recurrent route, intermediate commit). Ported: upstream GDNAttnBackend._replayssm_target_verify (same kernel call, launch_mode="verify", null block -1, request rows as replay indices) and the compact commit sequence of upstream's spec_utils (commit_gdn_replayssm_spec + commit_gdn_replayssm_circular + conv-window rollback). Adapted (this line's own wiring; upstream refuses GDN + DFLASH): - ForwardMetadata.replayssm_spec_rows: the verify metadata plans the request rows (req_pool_indices) in all three builders (eager, graph capture, graph replay -- there the static buffer with padded rows zeroed). The commit reads the rows the verify used from the metadata, like mamba_cache_indices, so no caller changes: DFLASH (dflash_worker_v2 untouched), the EAGLE/MTP commit and the lane all go through update_mamba_state_after_mtp_verify. - The commit sits in that shared hook (ring branch when intermediate_ssm is None). Linear chain -> accepted = last step + 1 (bonus included); -1 folds nothing, like the masked scatter. - FOLD EVERY COMMIT for any SSM dtype (upstream defers the fold for fp32): radix insert, HiCache backup, tail adopt and the flip all read `temporal` and assume it is the committed state after every verify, as the recurrent route makes it. The ring is then per-step scratch (write_pos 0 at every verify). - Heal: outside a capture the verify metadata re-states write_pos = is_flush = 0 for the step's rows (true by construction after every commit), so a verify never trusts cursor bytes from an earlier step (TMS restore, flip, reused row). cache_base is circular and harmless at write_pos 0. - forward_extend routes the verify to the ring when rows are planned; a draft tree on the ring, or a pool with neither intermediate state nor planned rows, is refused. The ring kernel honours token strides, so the verify split stays torch.split views (sgl-project#33778). - Advance cursor null block 0 (request row 0 is the ReqToTokenPool padding row); the widest verify window is kept on the pool as the advance's constant (one compiled variant across the adaptive ladder). - Ring length must be >= 16 (the compact commit's tl.dot) -- pool and static check; S2 test moved to L=16. - _replayssm_spec_for: a draft-KV-only producer (no verify workspace, sgl-project#1233 FIX 4) treats the flag as a no-op instead of hitting the pool's missing-window refusal. - getattr on the new metadata field in the two readers (sgl-project#624 stub drift: test_gdn_verify_strided_qkv_33778 doubles predate it). Tests (CPU, incg cgroup, one file at a time): test/registered/unit/layers/attention/test_replayssm_spec_route_s3.py: 10 passed. Hermetic: rows planned + healed (eager, replay; not in capture; padded row -> row 0), flag off / decode plan nothing, the three refusals, producer no-op. Interpreter (production route functions on real CPU pools, ring vs intermediate, 2 layers, head ratio 3, 2 requests + padded row, track crossing, second step after garbage cursors + heal): fp32 verify rel 3.7e-7 / 2.4e-7, commit (incl. track slot) 2.9e-7 / 3.1e-7 vs the recurrent route; fp16 (bf16 stand-in) verify 5.0e-4 vs recurrent 3.8e-4 of the fp32 truth, commit 3.6e-4 == recurrent 3.6e-4; conv rollback equal; untouched slots bit-exact; cursors 0 after every commit. On the S2 sources: 7 failed + 3 errors. Regression: test_replayssm_spec_ring_pool_s2 10, test_mamba_checkpoint_interval 58, test_dflash_mamba_track_post_verify_37818 5, test_conv_verify_private_ window_444 13, test_prefill_graph_stale_track_rows_34184 2, test_weg2_prefill_only_capture_1233 15, test_forward_metadata_plan_record 9, test_fused_replay_state_indices_32219 3, test_gdn_verify_strided_qkv_33778 4, test_verify_intermediate_row_ownership_450 12, test_mamba2_conv_verify_ private_window_450 10, test_dual_group_concurrency 159 -- all passed. ruff F: no new findings.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Sep 24, 2026
…e D planner 27B ReplaySSM package, slice S5 of REPLAYSSM_PLAN.md -- where the D-KV gain materializes. Flag off: byte-identical (the unit below is D itself, the same object; the planner pad is d itself). - configs/mamba_utils: spec_ring_workspace_bytes_per_req(D, L) -- what the pool allocates per request row under the flag: the deduplicated conv verify windows ([conv_dim, D + K - 2] per layer; the layout of every ring-eligible verify) plus replayssm_ring_bytes_per_req(L). Pinned equal to a real MambaPool's allocation at the 27B D ranks' heads (18/6, 15/5). - mixin: _spec_workspace_draft_units(runner, config, D) (module-level, duck-typed like _note_mamba_component, sgl-project#624) returns D on the recurrent route and workspace / per_req under the flag -- a fractional D, so the four handle_max_mamba_cache branches, the demand path's fit and budget cost and the "speculative intermediate state" post all price the real allocation without a second formula; the freed bytes stay in total_rest_memory for the KV pool. One boot-log line names the new per-row price. A draft-KV producer keeps D (no verify workspace). - uneven_perf: PlanInputs.linear_replayssm_spec_ring_len (appended last; set by from_server_args only under the flag) and PerfCostModel's mamba pool pad priced by the same terms per GDN unit (_spec_pad_draft_units), so --rank-tp-ratio auto and the weg2 launcher's D pricing agree with the boot. - server_args: the flag is refused with --enable-unified-memory (that pool builds its own intermediate state; the budget would price a ring). Numbers (desk, 27B D rank HV 18 / H 6, 48 GDN layers, bf16, D=8, L=16): per request row 224.4 MiB (8 per-draft states) -> 12.57 MiB (ring 9.05 + conv windows 3.52); rank 15/5: 187.0 -> 10.47 MiB. Demand branch at --max-running-requests 2: pool 13 slots either way, post 0.438 -> 0.025 GiB, KV budget +0.414 GiB per rank. Convention kept, named: the post counts capped_reqs rows (not the pool's spec_state_size + 1) exactly like the recurrent post did; for the ring that is one row (~13 MiB) instead of ~224 MiB. planner/mrr_balance (advisory mrr report) still pads with the integer draft count -- it only suggests, never sizes; follow-up if the flag becomes the D default. Tests (CPU, incg cgroup, one file at a time): test/registered/unit/model_executor/test_replayssm_spec_post_s5.py: 8 passed (allocation == formula for both uneven ranks, units identity / producer / ratio, demand-branch post + freed bytes -> KV, planner unit == runtime unit byte for byte, PlanInputs carries L only under the flag). test_replayssm_spec_ring_pool_s2 (+ unified-memory refusal) 10. Regression passed: test_ceiling_mamba_fit 36, test_gdn_ladder_decouple 12, test_gdn_cap_flip_two_stacks_631 11, test_mamba_pool_r7_prediction_773 4, test_pp_world_sizing 18, test_mrr_balance 12, test_weg2_spec_form_dflash 7, test_weg2_group_flags_1236 15, test_planner_core 33, test_mamba_checkpoint_interval 58. Pre-existing failures, identical on the S4 sources: test_coresidence_budget_mapping (5, _FakeRunner lacks _read_corridor_card_free_bytes), test_weg2_d_operating_points_1241 (1, NEXTN literal count), test_pp_cut_boot_sizing_1286 (1, the base's own 'prefill transient (measured)' post). ruff F: no new findings.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Sep 24, 2026
…ec ring 27B ReplaySSM package, slice S3 of REPLAYSSM_PLAN.md. With the flag off every path is unchanged (no rows planned -> recurrent route, intermediate commit). Ported: upstream GDNAttnBackend._replayssm_target_verify (same kernel call, launch_mode="verify", null block -1, request rows as replay indices) and the compact commit sequence of upstream's spec_utils (commit_gdn_replayssm_spec + commit_gdn_replayssm_circular + conv-window rollback). Adapted (this line's own wiring; upstream refuses GDN + DFLASH): - ForwardMetadata.replayssm_spec_rows: the verify metadata plans the request rows (req_pool_indices) in all three builders (eager, graph capture, graph replay -- there the static buffer with padded rows zeroed). The commit reads the rows the verify used from the metadata, like mamba_cache_indices, so no caller changes: DFLASH (dflash_worker_v2 untouched), the EAGLE/MTP commit and the lane all go through update_mamba_state_after_mtp_verify. - The commit sits in that shared hook (ring branch when intermediate_ssm is None). Linear chain -> accepted = last step + 1 (bonus included); -1 folds nothing, like the masked scatter. - FOLD EVERY COMMIT for any SSM dtype (upstream defers the fold for fp32): radix insert, HiCache backup, tail adopt and the flip all read `temporal` and assume it is the committed state after every verify, as the recurrent route makes it. The ring is then per-step scratch (write_pos 0 at every verify). - Heal: outside a capture the verify metadata re-states write_pos = is_flush = 0 for the step's rows (true by construction after every commit), so a verify never trusts cursor bytes from an earlier step (TMS restore, flip, reused row). cache_base is circular and harmless at write_pos 0. - forward_extend routes the verify to the ring when rows are planned; a draft tree on the ring, or a pool with neither intermediate state nor planned rows, is refused. The ring kernel honours token strides, so the verify split stays torch.split views (sgl-project#33778). - Advance cursor null block 0 (request row 0 is the ReqToTokenPool padding row); the widest verify window is kept on the pool as the advance's constant (one compiled variant across the adaptive ladder). - Ring length must be >= 16 (the compact commit's tl.dot) -- pool and static check; S2 test moved to L=16. - _replayssm_spec_for: a draft-KV-only producer (no verify workspace, sgl-project#1233 FIX 4) treats the flag as a no-op instead of hitting the pool's missing-window refusal. - getattr on the new metadata field in the two readers (sgl-project#624 stub drift: test_gdn_verify_strided_qkv_33778 doubles predate it). Tests (CPU, incg cgroup, one file at a time): test/registered/unit/layers/attention/test_replayssm_spec_route_s3.py: 10 passed. Hermetic: rows planned + healed (eager, replay; not in capture; padded row -> row 0), flag off / decode plan nothing, the three refusals, producer no-op. Interpreter (production route functions on real CPU pools, ring vs intermediate, 2 layers, head ratio 3, 2 requests + padded row, track crossing, second step after garbage cursors + heal): fp32 verify rel 3.7e-7 / 2.4e-7, commit (incl. track slot) 2.9e-7 / 3.1e-7 vs the recurrent route; fp16 (bf16 stand-in) verify 5.0e-4 vs recurrent 3.8e-4 of the fp32 truth, commit 3.6e-4 == recurrent 3.6e-4; conv rollback equal; untouched slots bit-exact; cursors 0 after every commit. On the S2 sources: 7 failed + 3 errors. Regression: test_replayssm_spec_ring_pool_s2 10, test_mamba_checkpoint_interval 58, test_dflash_mamba_track_post_verify_37818 5, test_conv_verify_private_ window_444 13, test_prefill_graph_stale_track_rows_34184 2, test_weg2_prefill_only_capture_1233 15, test_forward_metadata_plan_record 9, test_fused_replay_state_indices_32219 3, test_gdn_verify_strided_qkv_33778 4, test_verify_intermediate_row_ownership_450 12, test_mamba2_conv_verify_ private_window_450 10, test_dual_group_concurrency 159 -- all passed. ruff F: no new findings. 27B line (desk/27b-up-replayssm-line-0924): cherry-picked from 7d69bd8 (desk/27b-up-replayssm-0924, on the NF-based staging line fa757eb), clean. gdn_backend.py and mamba2_metadata.py are identical on both lines; dflash_worker_v2 differs here (sgl-project#31468, sgl-project#33459/sgl-project#30096 ports) but not in _update_target_mamba_state_after_verify, so the DFLASH commit reaches the shared hook exactly as on NF. One adaptation, text only: the commit docstring listed "tail adopt" among the readers of `temporal` -- that is the NF line's H21 install (weg2.tail_adopt), absent here; the 27B readers are the radix insert, the HiCache backup (the weg2 L2 arena write, xsn351) and the P/D flip. Tests on this line (CPU, incg cgroup, S3 tree, one file at a time): test_replayssm_spec_route_s3.py 10 passed -- interpreter, production route vs the recurrent route: fp32 verify rel 3.74e-7 / 2.40e-7 (step 1 / step 2 after garbage cursors + heal), commit incl. the track slot 2.94e-7 / 3.10e-7 (all < 4e-7); fp16 (bf16 stand-in) verify 5.03e-4 / 2.72e-4 vs recurrent 3.84e-4 / 2.55e-4 of the fp32 truth, commit 3.61e-4 / 3.27e-4 == recurrent; conv rollback equal, padded outputs zero, untouched slots bit-exact, cursors 0 after every commit; test_replayssm_spec_ring_pool_s2.py 10 passed (8 subtests). Regression (package tip = S6 tree, same cgroup, one file at a time): test_dflash_mamba_track_post_verify_37818 5, test_conv_verify_private_window_444 13, test_prefill_graph_stale_track_rows_34184 2, test_weg2_prefill_only_capture_1233 15, test_forward_metadata_plan_record 9, test_fused_replay_state_indices_32219 3, test_gdn_verify_strided_qkv_33778 4, test_verify_intermediate_row_ownership_450 12, test_mamba2_conv_verify_private_window_450 10, test_dual_group_concurrency 159, test_mamba_checkpoint_interval 58 -- all passed.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Sep 24, 2026
…e D planner 27B ReplaySSM package, slice S5 of REPLAYSSM_PLAN.md -- where the D-KV gain materializes. Flag off: byte-identical (the unit below is D itself, the same object; the planner pad is d itself). - configs/mamba_utils: spec_ring_workspace_bytes_per_req(D, L) -- what the pool allocates per request row under the flag: the deduplicated conv verify windows ([conv_dim, D + K - 2] per layer; the layout of every ring-eligible verify) plus replayssm_ring_bytes_per_req(L). Pinned equal to a real MambaPool's allocation at the 27B D ranks' heads (18/6, 15/5). - mixin: _spec_workspace_draft_units(runner, config, D) (module-level, duck-typed like _note_mamba_component, sgl-project#624) returns D on the recurrent route and workspace / per_req under the flag -- a fractional D, so the four handle_max_mamba_cache branches, the demand path's fit and budget cost and the "speculative intermediate state" post all price the real allocation without a second formula; the freed bytes stay in total_rest_memory for the KV pool. One boot-log line names the new per-row price. A draft-KV producer keeps D (no verify workspace). - uneven_perf: PlanInputs.linear_replayssm_spec_ring_len (appended last; set by from_server_args only under the flag) and PerfCostModel's mamba pool pad priced by the same terms per GDN unit (_spec_pad_draft_units), so --rank-tp-ratio auto and the weg2 launcher's D pricing agree with the boot. - server_args: the flag is refused with --enable-unified-memory (that pool builds its own intermediate state; the budget would price a ring). Numbers (desk, 27B D rank HV 18 / H 6, 48 GDN layers, bf16, D=8, L=16): per request row 224.4 MiB (8 per-draft states) -> 12.57 MiB (ring 9.05 + conv windows 3.52); rank 15/5: 187.0 -> 10.47 MiB. Demand branch at --max-running-requests 2: pool 13 slots either way, post 0.438 -> 0.025 GiB, KV budget +0.414 GiB per rank. Convention kept, named: the post counts capped_reqs rows (not the pool's spec_state_size + 1) exactly like the recurrent post did; for the ring that is one row (~13 MiB) instead of ~224 MiB. planner/mrr_balance (advisory mrr report) still pads with the integer draft count -- it only suggests, never sizes; follow-up if the flag becomes the D default. Tests (CPU, incg cgroup, one file at a time): test/registered/unit/model_executor/test_replayssm_spec_post_s5.py: 8 passed (allocation == formula for both uneven ranks, units identity / producer / ratio, demand-branch post + freed bytes -> KV, planner unit == runtime unit byte for byte, PlanInputs carries L only under the flag). test_replayssm_spec_ring_pool_s2 (+ unified-memory refusal) 10. Regression passed: test_ceiling_mamba_fit 36, test_gdn_ladder_decouple 12, test_gdn_cap_flip_two_stacks_631 11, test_mamba_pool_r7_prediction_773 4, test_pp_world_sizing 18, test_mrr_balance 12, test_weg2_spec_form_dflash 7, test_weg2_group_flags_1236 15, test_planner_core 33, test_mamba_checkpoint_interval 58. Pre-existing failures, identical on the S4 sources: test_coresidence_budget_mapping (5, _FakeRunner lacks _read_corridor_card_free_bytes), test_weg2_d_operating_points_1241 (1, NEXTN literal count), test_pp_cut_boot_sizing_1286 (1, the base's own 'prefill transient (measured)' post). ruff F: no new findings. 27B line (desk/27b-up-replayssm-line-0924): cherry-picked from 0faf279 (desk/27b-up-replayssm-0924, on the NF-based staging line fa757eb), clean. configs/mamba_utils.py is identical on both lines. What the NF line has in the touched functions and this line does not, stays out: the Form-A worker guards in _fit_mamba_pool_to_budget / handle_max_mamba_cache (per_slot_bytes <= 0, this_rank_is_form_a_worker) and PerfCostModel's expert-offload terms (moe_resident_fraction / moe_scratch_slots, sgl-project#62); the ring pad is priced only in the spec term of _mamba_pool_bytes, as on NF. The group P pricing (pp_cut's speculative_intermediate_mib, zero on P, acknowledged in the launcher) is untouched: P runs no target verify. Tests on this line (CPU, incg cgroup, S5 tree, one file at a time): test_replayssm_spec_post_s5.py 8 passed (2 subtests); test_replayssm_spec_ring_pool_s2.py 10 passed (9 subtests). Regression (package tip = S6 tree, same cgroup, one file at a time): test_gdn_ladder_decouple 12, test_gdn_cap_flip_two_stacks_631 11, test_mamba_pool_r7_prediction_773 4, test_pp_world_sizing 18, test_mrr_balance 12 (1 skipped), test_planner_core 33, test_mamba_checkpoint_interval 58, test_ceiling_mamba_fit 36 -- passed. Pre-existing, identical on the base e15e760: test_coresidence_budget_mapping (5, _FakeRunner lacks _read_corridor_card_free_bytes), test_pp_cut_boot_sizing_1286 (1, the 'prefill transient (measured)' post has no PhasePoolModel field).
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Sep 25, 2026
…ec ring 27B ReplaySSM package, slice S3 of REPLAYSSM_PLAN.md. With the flag off every path is unchanged (no rows planned -> recurrent route, intermediate commit). Ported: upstream GDNAttnBackend._replayssm_target_verify (same kernel call, launch_mode="verify", null block -1, request rows as replay indices) and the compact commit sequence of upstream's spec_utils (commit_gdn_replayssm_spec + commit_gdn_replayssm_circular + conv-window rollback). Adapted (this line's own wiring; upstream refuses GDN + DFLASH): - ForwardMetadata.replayssm_spec_rows: the verify metadata plans the request rows (req_pool_indices) in all three builders (eager, graph capture, graph replay -- there the static buffer with padded rows zeroed). The commit reads the rows the verify used from the metadata, like mamba_cache_indices, so no caller changes: DFLASH (dflash_worker_v2 untouched), the EAGLE/MTP commit and the lane all go through update_mamba_state_after_mtp_verify. - The commit sits in that shared hook (ring branch when intermediate_ssm is None). Linear chain -> accepted = last step + 1 (bonus included); -1 folds nothing, like the masked scatter. - FOLD EVERY COMMIT for any SSM dtype (upstream defers the fold for fp32): radix insert, HiCache backup, tail adopt and the flip all read `temporal` and assume it is the committed state after every verify, as the recurrent route makes it. The ring is then per-step scratch (write_pos 0 at every verify). - Heal: outside a capture the verify metadata re-states write_pos = is_flush = 0 for the step's rows (true by construction after every commit), so a verify never trusts cursor bytes from an earlier step (TMS restore, flip, reused row). cache_base is circular and harmless at write_pos 0. - forward_extend routes the verify to the ring when rows are planned; a draft tree on the ring, or a pool with neither intermediate state nor planned rows, is refused. The ring kernel honours token strides, so the verify split stays torch.split views (sgl-project#33778). - Advance cursor null block 0 (request row 0 is the ReqToTokenPool padding row); the widest verify window is kept on the pool as the advance's constant (one compiled variant across the adaptive ladder). - Ring length must be >= 16 (the compact commit's tl.dot) -- pool and static check; S2 test moved to L=16. - _replayssm_spec_for: a draft-KV-only producer (no verify workspace, sgl-project#1233 FIX 4) treats the flag as a no-op instead of hitting the pool's missing-window refusal. - getattr on the new metadata field in the two readers (sgl-project#624 stub drift: test_gdn_verify_strided_qkv_33778 doubles predate it). Tests (CPU, incg cgroup, one file at a time): test/registered/unit/layers/attention/test_replayssm_spec_route_s3.py: 10 passed. Hermetic: rows planned + healed (eager, replay; not in capture; padded row -> row 0), flag off / decode plan nothing, the three refusals, producer no-op. Interpreter (production route functions on real CPU pools, ring vs intermediate, 2 layers, head ratio 3, 2 requests + padded row, track crossing, second step after garbage cursors + heal): fp32 verify rel 3.7e-7 / 2.4e-7, commit (incl. track slot) 2.9e-7 / 3.1e-7 vs the recurrent route; fp16 (bf16 stand-in) verify 5.0e-4 vs recurrent 3.8e-4 of the fp32 truth, commit 3.6e-4 == recurrent 3.6e-4; conv rollback equal; untouched slots bit-exact; cursors 0 after every commit. On the S2 sources: 7 failed + 3 errors. Regression: test_replayssm_spec_ring_pool_s2 10, test_mamba_checkpoint_interval 58, test_dflash_mamba_track_post_verify_37818 5, test_conv_verify_private_ window_444 13, test_prefill_graph_stale_track_rows_34184 2, test_weg2_prefill_only_capture_1233 15, test_forward_metadata_plan_record 9, test_fused_replay_state_indices_32219 3, test_gdn_verify_strided_qkv_33778 4, test_verify_intermediate_row_ownership_450 12, test_mamba2_conv_verify_ private_window_450 10, test_dual_group_concurrency 159 -- all passed. ruff F: no new findings. 27B line (desk/27b-up-replayssm-line-0924): cherry-picked from 7d69bd8 (desk/27b-up-replayssm-0924, on the NF-based staging line fa757eb), clean. gdn_backend.py and mamba2_metadata.py are identical on both lines; dflash_worker_v2 differs here (sgl-project#31468, sgl-project#33459/sgl-project#30096 ports) but not in _update_target_mamba_state_after_verify, so the DFLASH commit reaches the shared hook exactly as on NF. One adaptation, text only: the commit docstring listed "tail adopt" among the readers of `temporal` -- that is the NF line's H21 install (weg2.tail_adopt), absent here; the 27B readers are the radix insert, the HiCache backup (the weg2 L2 arena write, xsn351) and the P/D flip. Tests on this line (CPU, incg cgroup, S3 tree, one file at a time): test_replayssm_spec_route_s3.py 10 passed -- interpreter, production route vs the recurrent route: fp32 verify rel 3.74e-7 / 2.40e-7 (step 1 / step 2 after garbage cursors + heal), commit incl. the track slot 2.94e-7 / 3.10e-7 (all < 4e-7); fp16 (bf16 stand-in) verify 5.03e-4 / 2.72e-4 vs recurrent 3.84e-4 / 2.55e-4 of the fp32 truth, commit 3.61e-4 / 3.27e-4 == recurrent; conv rollback equal, padded outputs zero, untouched slots bit-exact, cursors 0 after every commit; test_replayssm_spec_ring_pool_s2.py 10 passed (8 subtests). Regression (package tip = S6 tree, same cgroup, one file at a time): test_dflash_mamba_track_post_verify_37818 5, test_conv_verify_private_window_444 13, test_prefill_graph_stale_track_rows_34184 2, test_weg2_prefill_only_capture_1233 15, test_forward_metadata_plan_record 9, test_fused_replay_state_indices_32219 3, test_gdn_verify_strided_qkv_33778 4, test_verify_intermediate_row_ownership_450 12, test_mamba2_conv_verify_private_window_450 10, test_dual_group_concurrency 159, test_mamba_checkpoint_interval 58 -- all passed. NF line (H64, onto 88dec66): one conflict, resolved line by line in gdn_backend.forward_extend. This line carries no sgl-project#33778 port (no kernel_dispatcher.target_verify_supports_strided_qkv), so the 27B hunk that widens use_strided_verify_qkv for the ring has nothing to widen. Kept the NF condition `(is_cuda() or is_hip()) and qkv_dim <= MAX_FUSED_QKV_SPLIT_DIM`: the ring verify gets the same q/k/v preparation as the recurrent verify on this line (dense [1, T, H, D] from fused_qkv_split_gdn_prefill on CUDA, torch.split views elsewhere); _replayssm_target_verify flattens both layouts by numel. Text only: the commit docstring names the NF H21 tail adopt (weg2/tail_adopt.py reads and installs cache.temporal) among the readers of temporal again -- the 27B line had dropped it because it lacks H21. Tests (CPU, incg cgroup, one file at a time): test_replayssm_spec_route_s3.py 10 passed; test_replayssm_spec_ring_pool_s2.py 10 passed (8 subtests). (cherry picked from commit 974254d)
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Sep 25, 2026
…e D planner 27B ReplaySSM package, slice S5 of REPLAYSSM_PLAN.md -- where the D-KV gain materializes. Flag off: byte-identical (the unit below is D itself, the same object; the planner pad is d itself). - configs/mamba_utils: spec_ring_workspace_bytes_per_req(D, L) -- what the pool allocates per request row under the flag: the deduplicated conv verify windows ([conv_dim, D + K - 2] per layer; the layout of every ring-eligible verify) plus replayssm_ring_bytes_per_req(L). Pinned equal to a real MambaPool's allocation at the 27B D ranks' heads (18/6, 15/5). - mixin: _spec_workspace_draft_units(runner, config, D) (module-level, duck-typed like _note_mamba_component, sgl-project#624) returns D on the recurrent route and workspace / per_req under the flag -- a fractional D, so the four handle_max_mamba_cache branches, the demand path's fit and budget cost and the "speculative intermediate state" post all price the real allocation without a second formula; the freed bytes stay in total_rest_memory for the KV pool. One boot-log line names the new per-row price. A draft-KV producer keeps D (no verify workspace). - uneven_perf: PlanInputs.linear_replayssm_spec_ring_len (appended last; set by from_server_args only under the flag) and PerfCostModel's mamba pool pad priced by the same terms per GDN unit (_spec_pad_draft_units), so --rank-tp-ratio auto and the weg2 launcher's D pricing agree with the boot. - server_args: the flag is refused with --enable-unified-memory (that pool builds its own intermediate state; the budget would price a ring). Numbers (desk, 27B D rank HV 18 / H 6, 48 GDN layers, bf16, D=8, L=16): per request row 224.4 MiB (8 per-draft states) -> 12.57 MiB (ring 9.05 + conv windows 3.52); rank 15/5: 187.0 -> 10.47 MiB. Demand branch at --max-running-requests 2: pool 13 slots either way, post 0.438 -> 0.025 GiB, KV budget +0.414 GiB per rank. Convention kept, named: the post counts capped_reqs rows (not the pool's spec_state_size + 1) exactly like the recurrent post did; for the ring that is one row (~13 MiB) instead of ~224 MiB. planner/mrr_balance (advisory mrr report) still pads with the integer draft count -- it only suggests, never sizes; follow-up if the flag becomes the D default. Tests (CPU, incg cgroup, one file at a time): test/registered/unit/model_executor/test_replayssm_spec_post_s5.py: 8 passed (allocation == formula for both uneven ranks, units identity / producer / ratio, demand-branch post + freed bytes -> KV, planner unit == runtime unit byte for byte, PlanInputs carries L only under the flag). test_replayssm_spec_ring_pool_s2 (+ unified-memory refusal) 10. Regression passed: test_ceiling_mamba_fit 36, test_gdn_ladder_decouple 12, test_gdn_cap_flip_two_stacks_631 11, test_mamba_pool_r7_prediction_773 4, test_pp_world_sizing 18, test_mrr_balance 12, test_weg2_spec_form_dflash 7, test_weg2_group_flags_1236 15, test_planner_core 33, test_mamba_checkpoint_interval 58. Pre-existing failures, identical on the S4 sources: test_coresidence_budget_mapping (5, _FakeRunner lacks _read_corridor_card_free_bytes), test_weg2_d_operating_points_1241 (1, NEXTN literal count), test_pp_cut_boot_sizing_1286 (1, the base's own 'prefill transient (measured)' post). ruff F: no new findings. 27B line (desk/27b-up-replayssm-line-0924): cherry-picked from 0faf279 (desk/27b-up-replayssm-0924, on the NF-based staging line fa757eb), clean. configs/mamba_utils.py is identical on both lines. What the NF line has in the touched functions and this line does not, stays out: the Form-A worker guards in _fit_mamba_pool_to_budget / handle_max_mamba_cache (per_slot_bytes <= 0, this_rank_is_form_a_worker) and PerfCostModel's expert-offload terms (moe_resident_fraction / moe_scratch_slots, sgl-project#62); the ring pad is priced only in the spec term of _mamba_pool_bytes, as on NF. The group P pricing (pp_cut's speculative_intermediate_mib, zero on P, acknowledged in the launcher) is untouched: P runs no target verify. Tests on this line (CPU, incg cgroup, S5 tree, one file at a time): test_replayssm_spec_post_s5.py 8 passed (2 subtests); test_replayssm_spec_ring_pool_s2.py 10 passed (9 subtests). Regression (package tip = S6 tree, same cgroup, one file at a time): test_gdn_ladder_decouple 12, test_gdn_cap_flip_two_stacks_631 11, test_mamba_pool_r7_prediction_773 4, test_pp_world_sizing 18, test_mrr_balance 12 (1 skipped), test_planner_core 33, test_mamba_checkpoint_interval 58, test_ceiling_mamba_fit 36 -- passed. Pre-existing, identical on the base e15e760: test_coresidence_budget_mapping (5, _FakeRunner lacks _read_corridor_card_free_bytes), test_pp_cut_boot_sizing_1286 (1, the 'prefill transient (measured)' post has no PhasePoolModel field). NF line (H64, onto 88dec66): one conflict, resolved line by line in uneven_perf.PlanInputs. On the 27B line the new field follows that line's group-fact fields (mamba_ssm_dtype, dflash_window_pool, speculative_draft_window_size, overhead_mib_by_rank -- 159333c, not part of this package, absent here); on this line it is appended after kv_token_vector, still the last field. Everything else merged unchanged. The NF Form-A worker guards the 27B note names stay in place and are consistent with the new unit: a Form A worker (--rank-role host,worker,worker, --rank-tp-ratio 1,0,0) has mamba_cache_per_req == 0, so _spec_workspace_draft_units returns D unchanged there (per_req_global <= 0) and the worker's post stays 0; the host (TP0) holds every GDN head and gets the ring price. Tests (CPU, incg cgroup, one file at a time): test_replayssm_spec_post_s5.py 8 passed (2 subtests); test_replayssm_spec_ring_pool_s2.py 10 passed (9 subtests). (cherry picked from commit 6147890)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Enables user to configure VertexAI safety settings. Example usage:
Exposing these safety configurations is valuable as Gemini's default safety settings can be easily triggered (e.g., if you work with data in the medical domain).