Skip to content

Add Qwen2 MoE support - #603

Merged
merrymercy merged 2 commits into
sgl-project:mainfrom
M0gician:qwen2-moe
Jul 9, 2024
Merged

merrymercy merged 2 commits into
sgl-project:mainfrom
M0gician:qwen2-moe

Conversation

@M0gician

@M0gician M0gician commented Jul 8, 2024

Copy link
Copy Markdown
Contributor

Blocked by #598

Add Qwen2 MoE support to SGLang. Implementation is adopted from the current vLLM implementation.
I've tested this patch on my local environment with 8 * A800, and everything works gracefully.

The configurations I've tested so far are

  • CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python -m sglang.launch_server --model-path ~/Qwen2-57B-A14B-Instruct/ --port 30000 --mem-fraction-static 0.9 --tp-size 8
  • CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python -m sglang.launch_server --model-path ~/Qwen2-57B-A14B-Instruct/ --port 30000 --mem-fraction-static 0.9 --tp-size 4 --dp-size 2
  • CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python -m sglang.launch_server --model-path ~/Qwen2-57B-A14B-Instruct/ --port 30000 --mem-fraction-static 0.9 --tp-size 2 --dp-size 4

@merrymercy
merrymercy merged commit 740c46a into sgl-project:main Jul 9, 2024
@merrymercy

Copy link
Copy Markdown
Collaborator

@M0gician It is merged. Thanks for the contribution!

@M0gician
M0gician deleted the qwen2-moe branch March 5, 2025 05:35
timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 5, 2026
The stash gate tests build their Scheduler with __new__ and set only the
attributes get_next_batch_to_run needed on the day they were written. The
function has grown a prologue since; the stub drifted red on
enable_hierarchical_cache long before reaching the gate under test, so the
gate itself had not actually been exercised for some time.

Carries the prologue's inputs, all in the "feature off" configuration, which
is what this test wants: it isolates the stash gate from the phase-boundary
actuators that share the prologue. The bare MagicMock server_args needed the
same treatment -- it made every flag truthy, which armed kv-reshard until it
raised on its own precondition.

test_scheduler_chunked_req_gate.py: 3 passed, was 3 failed. Managers suite
7 failed / 492 passed, was 10 failed / 489 passed. The remaining 7
(test_prefill_adder preemption) are a separate pre-existing family and are
untouched here.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 5, 2026
…eemption tests

Same drift as the chunked-req-gate stub, one file over. These cases assert
PRIORITY preemption ordering and build server_args as a bare MagicMock,
which answers every flag truthily. The fast lane, added after they were
written, therefore armed itself inside the preemption loop and compared its
mocked fast_lane_reserved_heavy_slots against an int -- a TypeError that had
nothing to do with the ordering under test.

Pins enable_fast_lane off, which is the configuration the assertions
describe; the heavy-slot cap has its own coverage.

test_prefill_adder.py: 12 passed, was 7 failed. The managers suite is now
499 passed / 0 failed, from 10 failed / 489 passed at the start of sgl-project#603.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 5, 2026
…t as a failure

Neither was a code defect; both reported a missing precondition as red.

test_vmm_utils: the file is a MULTI-PROCESS test -- its group helper pins
the device from LOCAL_RANK, which a launcher sets. A plain pytest run
collects it anyway and it died with a bare KeyError: 'LOCAL_RANK'. Now skips
with the reason named, and also skips without CUDA. 4 skipped, was 4 failed.

test_uneven_tp_nccl_env: test_no_mps_warning_when_pipe_dir_exists asserted
"pipe directory exists -> no warning", which was the contract when it was
written. The check has since been hardened to PROBE the control daemon
(_mps_control_daemon_responsive), explicitly because a directory left behind
by a dead daemon proves nothing. The test therefore demanded silence in the
case the code now correctly warns about, and was red on every host without a
live MPS daemon. Renamed to the contract it now tests, with the probe
stubbed on both answers so the gate is shown able to fire as well as to stay
quiet. 9 passed, was 8 passed / 1 failed.

With these, the distributed and managers unit suites carry no
environment-dependent failures left over from before sgl-project#603.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 5, 2026
The install gate reads server_args.uneven_kv_derived_mode(), the wrapper
ServerArgs grew for "either derived mode, i.e. the vector is computed after
profiling rather than pinned". The SimpleNamespace stub still answered only
the older uneven_kv_capacity_mode, so all 11 install cases died on an
AttributeError before reaching anything they assert. rank_kv_ratio was
missing for the same reason.

The derived-mode relation is reproduced (capacity or speed) rather than
hardcoded to the capacity flag, so a future speed-mode case cannot silently
take the wrong branch.

test_dcp_token_vector_collective.py: 16 passed, was 11 failed / 5 passed.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 5, 2026
…ys honest

Precondition for arming SGLANG_VRAM_FLIGHT_DIR on every production boot. The
mark file is APPENDED -- that is what lets a crashed boot keep the boundaries
it did reach -- so a permanently armed recorder makes one file hold many
boots, and a reader that returns the whole file returns marks from several
process lifetimes. phase_deltas over that computes a difference from one
boot's last mark to the next boot's first: a number that describes nothing,
printed in the same table and the same units as the real posts. Left alone,
permanent arming would have made the instrument's output less trustworthy the
longer it ran.

- Every mark carries boot_id, derived from the LAUNCHER (this process's
  parent pid + start time) rather than from this process, so all ranks of one
  boot agree on it without a collective. A per-process uuid would tag each
  rank's file differently and make cross-rank reading impossible.
- read_marks returns the latest boot by default, a named boot on request, and
  the whole file only when explicitly asked with boot="all".
- phase_deltas SKIPS the seam and logs it, rather than reporting it.
- list_boots + `attribute_flight.py boots` say which boots a directory holds;
  `phases --boot` selects one.

MEASURED, for the retention question: one rank's boot is 8 marks / 5800 bytes
(725 B per mark), so a 3-rank boot costs 17 KiB and 1000 boots cost 16.6 MiB.
No rotation policy is proposed for the marks, because at that size the
condition does not bind and an unused knob is one more thing to get wrong.
Snapshots are the opposite case (~18 MB each) and are only written when the
trace is armed, which stays window-only.

TESTS
- 241 green across the mem_ledger suite (was 236; six boot-scoping tests).
- CAN-FAIL PROVEN twice: making phase_deltas span the seam -> 1 red (4 deltas
  where 3 are real); making read_marks return the whole file -> 2 red.
- attribute_flight.py smoked end to end against a two-boot directory: `boots`
  lists both, `phases` shows only the latest.
- Rebased onto 7044be2 (production tree: sgl-project#602 ledger + sgl-project#603 hoist) before
  all of the above; the rebase was clean and every call site survived it.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 5, 2026
…t skipped

Crashes 9, 10 and 11 (2026-08-05) all ended in the same unhelpful shape:
ranks 0 and 1 standing in one collective, rank 2 standing in a different
one, and nothing anywhere saying which collective rank 2 had SKIPPED. The
tracebacks report where each rank was STANDING, which is downstream of the
defect. The per-rank counts already existed -- the prefill line prints
"tp.all_reduce 243.4/129x" -- they were simply never compared ACROSS ranks.

This adds that comparison as a standing instrument. It is measurement, not
mitigation: it changes nothing about what the ranks do and cannot repair a
divergence. It reports, so the next crash arrives with its cause attached.

Counting: one dict increment per collective, at the four GroupCoordinator
dispatch sites, keyed by the family names the collective clock already
derives (tp.all_reduce, dcp.all_gather, ...). Placed AFTER the clock's
re-entry guard so each collective is counted exactly once. Guarded by a
module-level bool resolved at import, so the hot path costs one bool read
plus one dict increment.

Two reporting paths, for two different failure states:

1. Scheduler._census_tick -- the detector. Runs on tp_cpu_group (gloo),
   NEVER the device/BAR1 path, so a wedged device group cannot silence the
   instrument meant to explain it. Rides the same unconditional
   once-per-iteration point as the sgl-project#603 reduce, so its round counter is
   replicated and the cadence gate opens on the same round for every rank.
   Default every 50 iterations (~2 s in production), an order of magnitude
   inside the ~30 s spin deadline: the divergence is named while the ranks
   are still healthy, long before the abort.

2. format_local_census, called from barlink_bar1.check_aborted before it
   raises -- the wedge-proof half. Takes NO collective on purpose: by abort
   time a peer is very likely dead (in all three crashes the third rank
   aborted ~30 s after the first two), so a cross-rank exchange would hang
   exactly when the evidence is wanted. Each rank logs its own counts; the
   three lines are diffed afterwards.

Warn-never-raise throughout: a failed comparison is logged and dropped, and
the abort-path dump can never mask the real error.

ARMED BY DEFAULT, like the sgl-project#605 flight-recorder marks -- an instrument that
must be switched on before a crash explains no crashes.
SGLANG_COLLECTIVE_CENSUS=0 disables counting;
SGLANG_COLLECTIVE_CENSUS_INTERVAL tunes or (<=0) disables only the periodic
comparison, leaving the abort dump armed.

Tests: test/registered/unit/distributed/test_collective_census_583.py
Hermetic (no CUDA, no process group, no model). The injected divergence is
crashes 9/11 in numbers: [129, 129, 128] on tp.all_reduce.
  * 14 passed
  * can-fail proof: breaking only the count comparison in _diff turns 4 of
    them red
  * pins the missing-key case (a rank that skipped a family's ONLY
    collective has no key at all -> must read as zero, not drop the family)
  * pins armed-by-default, the kill switch, the replicated cadence gate,
    and warn-never-raise on a wedged/absent group
  * regression: census + retract-583 + 603 + retract-fcfs = 35 passed
  * ruff: 0 new findings (parallel_state 0/0, barlink_bar1 2/2,
    scheduler 89/89, schedule_batch 40/40); new files ruff-clean and
    formatted; codespell clean

Crash 11 (21:26, boot 11, tree WITHOUT the retraction fix) is byte-for-byte
crash 9's shape and NOT crash 10's: all three ranks are inside run_batch
(scheduler.py:2032), ranks 0/1 at communicator.py:1179 and rank 2 at
linear.py:2340, with check windows 1 and 4. So the `if batch:` fork is not
involved there, and crashes 9/11 are a site INSIDE the forward, distinct
from the retraction site closed for crash 10. The census is what will name
it.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 5, 2026
…o local

sgl-project#603 and the sgl-project#583 retraction fix both decide from a once-per-iteration
MIN-reduced pool headroom instead of the rank-local `available_size()`.
Both kept a fallback for "reduced value not available":

  * `Scheduler.uniform_min_avail` -- getattr(self, "_uniform_min_avail",
    None), returning the local pool when the reduce had not run
  * `ScheduleBatch.decode_mem_avail` -- returning the local pool when
    `uniform_avail_floor` was unset

Justified as "correct for a single rank and for tests", which is true and
beside the point: on a MULTI-RANK boot they hand back exactly the
rank-local predicate both fixes removed. Any path reaching a decode-mem
decision without setting the floor silently restores the desync, with the
protection still plainly visible in the source. That is the
getattr-default trap (sgl-project#606) -- a guard that reads as armed and is absent at
runtime, the same shape as a fixture string nobody ever printed (sgl-project#380).

Fix: single rank keeps the local value (nothing to diverge from); a group
raises with a message naming the ordering that was violated. The world-size
probe (`_group_world_size`) never raises -- a probe that could fail would
just move the silent-default problem one level down.

Tests: test/registered/unit/distributed/test_uniform_floor_fallbacks_583.py
  * falsifier: pins the pre-fix silent-local behaviour first, then asserts
    both paths refuse on a group
  * single-rank behaviour preserved on both paths (else this is a
    regression, not a fix)
  * a present reduced value always wins; a ZERO floor is honoured and not
    treated as missing (`if not floor` would be the same bug in disguise)
  * 10 passed; can-fail proof: reverting either guard turns the two
    refusal tests red

Also updates the sgl-project#603 and sgl-project#583 stubs to model `self.ps.tp_size` rather than
inventing a flat `self.tp_size` -- a stub inventing a surface the real class
lacks is precisely what let the census ship dead.

Full run: test/registered/unit/distributed + unit/managers = 2875 passed,
30 skipped, 735 subtests passed. Remaining failures are pre-existing and
not from this branch: 3 subtests in test_dcp_context_ceiling.py (verified
identical at 38e7c69) and test_bar1_host_cleanup.py's pgrep self-match
test, which passes in isolation (28/28) and is sensitive to concurrently
running processes. Directory ruff count unchanged at 4.
efschu added a commit to efschu/htsglang that referenced this pull request Aug 6, 2026
…g JIT at boot, not inside a serving forward)

Root cause of six of today's ten production Bar1CollectiveAborted crashes
(py-spy-proven, wedge_20260806_104250_*): flashinfer.sampling JIT-builds
its CUDA module lazily on the first top-k/top-p request, a 60-90 s nvcc
compile inside Sampler.forward. On this heterogeneous rig the arch-keyed
cache makes the 5090 (120f) build alone while both 3080s (86) serialize
on one FileLock; ranks leave the stall at different times and the first
one out exceeds the barlink spin deadline in the next collective. Fix is
placement: build on every rank inside the boot cold-build window, then
barrier -- wrapping the lazy build is structurally insufficient (the
aborting rank is the one NOT building). 7 hermetic falsifier tests green
(can-fail proven both ways); sweep distributed+managers 14 failed / 2923
passed with both failing files identical at the unmodified branch point;
GPU smoke: 53.4 s / 57.6 s cold per arch vs 0.6-0.8 s warm.
Shape B (symmetric graph-replay wait) remains OPEN and is tracked in
task sgl-project#603; production tree advances only after both shapes are fixed.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 6, 2026
The 21:52:25 specimen names itself once the stacks are read next to the sizes.
All three ranks are parked in the SAME all_reduce
(_gather_hidden_states_and_residual) at the SAME layer_idx, and the second
py-spy round has them advanced to layers 9/9/8 with each rank's nbytes
UNCHANGED. The size is therefore a property of the rank's whole forward, not
of one collective, and the collective SEQUENCE is aligned: this is not a rank
running one collective ahead. It is one logical collective whose shape differs
per rank -- 1690 tokens on rank 0 against 1818 on its peers, every one of them
an exact (num_tokens, 5120) bf16 payload.

prepare_for_extend builds that axis as sum(seq_len - len(prefix_indices)).
Everything there is replicated except the matched prefix, which comes from
this rank's radix cache. Two triggers mutated those caches from rank-local
state while the pools are rank-sized by construction (179825 / 143860 / 136667
tokens on the crashing boot):

  * evict_from_tree_cache fired on `available_size() < num_tokens`, where the
    DEMAND is replicated (batch.extend_num_tokens) and the AVAILABILITY is
    this rank's own shard, so the roomy rank declined an eviction the tight
    ranks took;
  * load_back EXTENDS the device prefix and succeeded only where local free
    space allowed -- no eviction needed to diverge the trees at all.

Both push the same way, and it is the direction the specimen shows: rank 0
owns the largest pool, evicts least, loads back most, matches the longest
prefix and computes the fewest tokens. The 21:08 specimen has the same
asymmetry (334 against 1229). Once the replicas drift, every per-layer TP
all_reduce of the next extend is entered with mismatched shapes and BAR1 spins
on a contribution that cannot arrive -- abort word CLEAN on all three ranks.

sgl-project#603 and sgl-project#610 pinned the decode-mem and prefill-admission DECISIONS with a
MIN-reduce and both explicitly left eviction as a local side effect ("Still
evict locally for the space"). The decisions were uniform; the cache CONTENT
they decided against was not.

The fix publishes the group MIN of available_size() on the tree cache once per
iteration and lets both triggers decide from it. No new collective: the value
rides the reduce _update_uniform_pool_budget already performs unconditionally
and pre-branch, with one extra element (-local_avail) yielding the group MAX
from the same MIN all_reduce. Direction is safe by construction -- min <=
local, so the floor fires whenever the local test did and sometimes when it
did not, which makes under-eviction (an allocator OOM) arithmetically
impossible; slack ranks pay for uniformity by dropping cache they did not
personally need. Activation is collective-derived and exact: the floor is
withheld precisely when every rank reports the same availability, and then the
local test is already uniform.

The pin had to be written in both cache classes. This rig runs
UnifiedRadixCache, not HiRadixCache, and each carries its own load_back with
its own local gate; the first cut pinned only the class the validated boot
never instantiates.

Test results (debug + distributed, one run): 2827 passed, 20 failed, 12
skipped. Those 20 are the SAME 20 the unfixed tree produces at HEAD, compared
name-by-name against a clean worktree at 3752da3 -- zero fix-only
regressions. Of the total, 354 are test/registered/unit/debug/ (unchanged) and
13 are new in
test/registered/unit/distributed/test_uniform_evict_floor_616g.py.

Two sibling stubs in test_uniform_decode_mem_603.py did regress on the first
cut -- a stub that models less surface than the real class -- and now bind the
new method. ruff: no new errors; the added code is format-clean.

The falsifier is proven able to fail: reverting evict_from_tree_cache to
allocator.available_size() turns the eviction verdict from [True, True, True]
back into [False, True, True] and fails
test_the_eviction_trigger_agrees_across_ranks.

On card: the fix binds on a real boot (PYTHONPATH pinned to this tree, pools
179825 / 143860 / 136667, i.e. the wedging geometry). Under the 4-way stress
harness the fixed tree produced ZERO Bar1CollectiveStalled events. The
graph-replay Bar1CollectiveAborted family (host-path collective counts
AGREEING, one-generation block skew) is a different shape, predates this
change, and is still open -- it is not claimed fixed here.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 16, 2026
…roject#677 to compose against

The sgl-project#679 close-out said the retry net's registry is empty because the reliefs
that could genuinely pay are collective and belong at admission. This is that
claim made concrete, written so sgl-project#677's hysteresis-drain design can consume it
without re-deriving anything.

WHAT IT ESTABLISHES.

Four reliefs exist and only four: radix eviction, the sgl-project#287 ladder's
admission_cap, kvso try_spill, and retract_decode. For each: what it frees at
the admission decision point, what it costs, and how it is invoked without
splitting the group. Two of them are not what one would guess:

  the sgl-project#287 ladder is TOO SLOW to be a rung. Its consensus boundary is every 8
  rounds; a chunked-prefill burst exhausts the pool in fewer. It is the slow
  outer loop -- and the decode path already uses it that way, throttling before
  retraction to stop the freed slots being handed straight back.

  kvso try_spill is the BEST rung, not retraction. It frees a bounded, chosen
  amount (the victim's block-aligned tail overhang), is already driven from the
  reduced value, and costs no request's progress. Its bound is the host region
  supply, and exhaustion is a reachable state the decode path already documents.

THE ITERATION ORDER, VERIFIED, AND IT IS FAVOURABLE. The reduce runs at
scheduler.py:4777, unconditional and pre-branch by its own comment; admission
at 5089; retraction at 5950 inside update_running_batch (5818). So a ladder at
admission reads an ALREADY-AGREED number and needs no collective of its own,
while retraction is genuinely downstream -- which is why sgl-project#679's crash had
nothing to fall back on, and what rung 3 must work around.

THE ORDER, mirroring the decode-OOM branch rather than inventing a second
shape: evict (baseline) -> try_spill -> throttle -> retract_decode -> PARK.
Parking stays the floor of the ladder, not its replacement.

THE COMPOSITION CONTRACT WITH sgl-project#677, stated in three rules because both
mechanisms decide admission from pool headroom:

  1. The park guard is the FINAL authority, the drain gate the prior one. A
     phase gate cannot make memory exist; it may narrow what the park guard
     allows, never widen it.
  2. Any headroom quantity sgl-project#677 branches on must be the GROUP-PUBLISHED floor.
     A rank-local reading in the drain gate reintroduces the sgl-project#603/sgl-project#583
     divergence class upstream of every safeguard sgl-project#679 added -- and a park
     guard reading the reduced floor does not protect a gate that reads a
     local one.
  3. Parking must be reachable from every path that reaches alloc_for_extend.

AND THE LIKELIEST COMPOSITION FAILURE, called out so it can be tested on both
sides before it is met on metal: hysteresis and parking can beat against each
other. A parked chunk schedules ZERO tokens, so a drain that counts admission
ATTEMPTS rather than SCHEDULED TOKENS will believe work was taken, hold its
hysteresis, and deadlock against the park at exactly the pressure where both
are needed.

Section 5 lists what this note does NOT close: the ladder is unbuilt, rung 3 is
a real refactor, and rung 1's host-region bound has never been measured under
the 5-lane load that produced the crash.

No code change. Every claim carries its file:line.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 16, 2026
…l; the new-request gate never did

sgl-project#679 taught `add_chunked_req` not to schedule a chunk the pool cannot fund, and
it made that decision GROUP-UNIFORMLY: `fundable_extend_tokens` reads the
published group MIN through `uniform_avail_for_evict`. Its sibling gate -- the
one every FRESH request passes -- was left reading this rank's own pool:

    PrefillAdder.rem_total_tokens
        available_size() + evictable_size() - offset - dcp_avail_deficit

That is the same over-promise one door further along, and it fails twice over:

  * A rank roomier than the binding rank admits work the GROUP cannot fund, and
    the batch dies where it is allocated -- `alloc_for_extend`, 2026-08-16
    01:46:10, all three ranks together.
  * It is a rank-local BRANCH upstream of a collective. Two ranks can build
    different batches and enter the next extend with different token axes,
    which is a HANG rather than a stall -- the family sgl-project#583/sgl-project#603/#616g/sgl-project#639 was
    paid for.

`fundable_extend_tokens`' own docstring names the first half. It was written
for the chunked gate and never wired to this one; `fundable_extend_tokens`
appeared nowhere in scheduler.py, which the red-first run confirms.

WHAT THIS IS NOT. It is not the cause of the 01:46 traceback. That was
e778276 -- an unlocked mamba tombstone leaf the eviction frontier selected
and `_evict_leaf_node` could not consume, so eviction under-delivered while the
counter honestly promised 65766 evictable. THE COUNTER AND THE ACTUATOR NOW
AGREE; this commit is about the second consumer of that counter, which reads a
rank-local copy of it and can over-promise even when it is honest.

A CEILING, NOT A SUBSTITUTE. `rem_total_tokens` also subtracts reservations the
floor knows nothing about (the running batch's hold, mamba gap, page overhead),
so replacing the local term would talk a rank that is ITSELF short back UP. The
budget is the MIN of the two. Both spend down the same `rem_total_token_offset`
-- a floor consulted per request without that shared accounting is not a bound
at all, since every request in the round would compare itself against the same
untouched pool. `dcp_avail_deficit` is deliberately NOT subtracted from the
floor term: the floor is already the group MIN, and the deficit is the other
mechanism for pinning a local number to the binding rank.

WHY THE MIN RESOLVES TO THE FLOOR IN PRODUCTION, and it is a test, not a claim:
`floor = uniform_avail + evictable` and `local = local_avail + evictable -
offset` with `uniform_avail <= local_avail` by definition of a MIN, so
`floor - offset <= local` on every rank. A rank BELOW the floor is not a state
the reduce can produce; the clamp's behaviour there is pinned separately
because refusing to be talked up by a stale floor is the wanted behaviour.

THE CEILING MUST NOT BE ABLE TO WEDGE THE INSTANCE, and this is why the wiring
goes through `published_fundable_floor` rather than calling
`fundable_extend_tokens` directly. That helper returns 0 for BOTH "the pool is
empty" and "the pool could not be read". The chunked gate can live with the
ambiguity -- 0 parks a chunk and the next round retries, a self-clearing state.
As a budget ceiling a mis-read 0 admits NOTHING, for every request, on every
subsequent round: a harder wedge than the crash it prevents. So the ceiling is
applied only where a floor was actually PUBLISHED, which is the one state
(uneven rank pools) it exists for. A published floor of genuine zero still
binds -- the distinction is "was a floor published", not "is it non-zero", or
the ticket's own crash state would be exempt from its own fix.

DEFAULT PATH UNTOUCHED, BY CONSTRUCTION AND BY ASSERTION. With no floor
published -- single rank, or pools that agree -- `fundable_extend_floor` is
None and `rem_total_tokens` returns exactly what it returned before.

TESTS. RED-FIRST against 7936bc4: 12 of the 18 fail there, including the
01:46 shape itself (a rank holding 100000 tokens admitting against a group that
holds none) and all three wiring pins. The guard against the wedge was
falsified separately by removing it -- 2 of its 4 cases go red -- because an
instrument that cannot fail is not evidence.

Covered: the cap; the floor spent down by admissions; group agreement across
ranks with different local pools; the floor binding before the local term
whenever the reduce's invariant holds; the local term still binding when it is
the smaller one; inertness with no floor and with a roomy floor; the
published-vs-readable distinction including a genuine zero; and three pins that
this stays wired (the scheduler constructs with a floor, it comes through the
guarded helper, and that helper still delegates to the group-uniform one).

NO REGRESSIONS, measured against the same subset on the unpatched tree:
944 failed / 2776 passed / 725 skipped before, 944 failed / 2794 passed / 725
skipped after -- identical failures (all CUDA-gated collection, hermetic run
with CUDA_VISIBLE_DEVICES=""), +18 = exactly the new cases.

NOT BOOTED. Desk-only; READY-FOR-BOOT. The metal arm that would exercise it is
a multi-rank boot with uneven pools under max fill -- the arm that produced the
01:46 specimen -- watching for the admission ceiling binding without a wedge.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 16, 2026
…l; the new-request gate never did

sgl-project#679 taught `add_chunked_req` not to schedule a chunk the pool cannot fund, and
it made that decision GROUP-UNIFORMLY: `fundable_extend_tokens` reads the
published group MIN through `uniform_avail_for_evict`. Its sibling gate -- the
one every FRESH request passes -- was left reading this rank's own pool:

    PrefillAdder.rem_total_tokens
        available_size() + evictable_size() - offset - dcp_avail_deficit

That is the same over-promise one door further along, and it fails twice over:

  * A rank roomier than the binding rank admits work the GROUP cannot fund, and
    the batch dies where it is allocated -- `alloc_for_extend`, 2026-08-16
    01:46:10, all three ranks together.
  * It is a rank-local BRANCH upstream of a collective. Two ranks can build
    different batches and enter the next extend with different token axes,
    which is a HANG rather than a stall -- the family sgl-project#583/sgl-project#603/#616g/sgl-project#639 was
    paid for.

`fundable_extend_tokens`' own docstring names the first half. It was written
for the chunked gate and never wired to this one; `fundable_extend_tokens`
appeared nowhere in scheduler.py, which the red-first run confirms.

WHAT THIS IS NOT. It is not the cause of the 01:46 traceback. That was
e778276 -- an unlocked mamba tombstone leaf the eviction frontier selected
and `_evict_leaf_node` could not consume, so eviction under-delivered while the
counter honestly promised 65766 evictable. THE COUNTER AND THE ACTUATOR NOW
AGREE; this commit is about the second consumer of that counter, which reads a
rank-local copy of it and can over-promise even when it is honest.

A CEILING, NOT A SUBSTITUTE. `rem_total_tokens` also subtracts reservations the
floor knows nothing about (the running batch's hold, mamba gap, page overhead),
so replacing the local term would talk a rank that is ITSELF short back UP. The
budget is the MIN of the two. Both spend down the same `rem_total_token_offset`
-- a floor consulted per request without that shared accounting is not a bound
at all, since every request in the round would compare itself against the same
untouched pool. `dcp_avail_deficit` is deliberately NOT subtracted from the
floor term: the floor is already the group MIN, and the deficit is the other
mechanism for pinning a local number to the binding rank.

WHY THE MIN RESOLVES TO THE FLOOR IN PRODUCTION, and it is a test, not a claim:
`floor = uniform_avail + evictable` and `local = local_avail + evictable -
offset` with `uniform_avail <= local_avail` by definition of a MIN, so
`floor - offset <= local` on every rank. A rank BELOW the floor is not a state
the reduce can produce; the clamp's behaviour there is pinned separately
because refusing to be talked up by a stale floor is the wanted behaviour.

THE CEILING MUST NOT BE ABLE TO WEDGE THE INSTANCE, and this is why the wiring
goes through `published_fundable_floor` rather than calling
`fundable_extend_tokens` directly. That helper returns 0 for BOTH "the pool is
empty" and "the pool could not be read". The chunked gate can live with the
ambiguity -- 0 parks a chunk and the next round retries, a self-clearing state.
As a budget ceiling a mis-read 0 admits NOTHING, for every request, on every
subsequent round: a harder wedge than the crash it prevents. So the ceiling is
applied only where a floor was actually PUBLISHED, which is the one state
(uneven rank pools) it exists for. A published floor of genuine zero still
binds -- the distinction is "was a floor published", not "is it non-zero", or
the ticket's own crash state would be exempt from its own fix.

DEFAULT PATH UNTOUCHED, BY CONSTRUCTION AND BY ASSERTION. With no floor
published -- single rank, or pools that agree -- `fundable_extend_floor` is
None and `rem_total_tokens` returns exactly what it returned before.

TESTS. RED-FIRST against 7936bc4: 12 of the 18 fail there, including the
01:46 shape itself (a rank holding 100000 tokens admitting against a group that
holds none) and all three wiring pins. The guard against the wedge was
falsified separately by removing it -- 2 of its 4 cases go red -- because an
instrument that cannot fail is not evidence.

Covered: the cap; the floor spent down by admissions; group agreement across
ranks with different local pools; the floor binding before the local term
whenever the reduce's invariant holds; the local term still binding when it is
the smaller one; inertness with no floor and with a roomy floor; the
published-vs-readable distinction including a genuine zero; and three pins that
this stays wired (the scheduler constructs with a floor, it comes through the
guarded helper, and that helper still delegates to the group-uniform one).

NO REGRESSIONS, measured against the same subset on the unpatched tree:
944 failed / 2776 passed / 725 skipped before, 944 failed / 2794 passed / 725
skipped after -- identical failures (all CUDA-gated collection, hermetic run
with CUDA_VISIBLE_DEVICES=""), +18 = exactly the new cases.

NOT BOOTED. Desk-only; READY-FOR-BOOT. The metal arm that would exercise it is
a multi-rank boot with uneven pools under max fill -- the arm that produced the
01:46 specimen -- watching for the admission ceiling binding without a wedge.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants