Repository navigation
Added the ability to Modify the Context Length - #210
Merged
Merged
Conversation
timethink
pushed a commit
to timethink/sglang
that referenced
this pull request
Mar 9, 2025
EdwardXuy
pushed a commit
to shun8686/sglang
that referenced
this pull request
Apr 6, 2026
Add MambaCache features testcases and Configuration file support and Forward hooks features testcases
rucnyz
added a commit
to rucnyz/sglang
that referenced
this pull request
Jun 7, 2026
… sglang's 3 leaf guards)
Root cause of the daemon being net-negative under HBM pressure (A3): the
unit dump from sglang carried no leaf/evictability status, so
migrate_candidates proposed remove-HBM migrates for non-leaf units that
sglang then rejected (remove_hbm_not_device_leaf) — ~86k apply_failed per
cycle, zero relief, daemon thrash, agents timing out.
sglang's apply site has THREE structural leaf guards (unified_radix_cache.py
2673/2684/2687), and the audit showed all three leak, not just the HBM one:
- remove_not_leaf (full-drop needs len(children)==0)
- remove_hbm_not_device_leaf (remove-HBM needs a device leaf)
- remove_dram_not_host_leaf (remove-DRAM needs a host leaf; in the same
t42 run this was the LARGER leak: 780 vs 101)
Make the daemon's candidate generator a faithful mirror of those guards so a
reject-guaranteed migrate is never emitted:
- dump is_device_leaf / is_host_leaf / is_tree_leaf on BOTH /aginfer/state
paths (dict + HTTP bytes buffer). is_host_leaf implies is_tree_leaf, but
is_device_leaf does NOT (disk-only children), so all three are carried.
- ReuseUnit gains the three flags (default True = pre-sgl-project#210 fixtures valid;
daemon and sglang co-ship so the live dump always fills them).
- migrate_candidates applies the three guards in sglang's order.
verify/joint_decide stage A-leaf pins each guard with a matched
leaf/non-leaf pair plus an over-filtering control; mutation-tested
(deleting any one guard turns the stage RED).
rucnyz
added a commit
to rucnyz/sglang
that referenced
this pull request
Jun 7, 2026
…esume (un-starve) A PAUSED program emits no events and can only leave the proxy gate via a Resume in the headroom phase. If its KV units were DROPped while it was gated (a routine outcome — pausing does not pin units, and sglang's overlay emits an explicit empty-residue PAUSED entry), then: - expected_peak_hbm_after_resume returns empty re_use (no units to size), - shared_aware_prog_scores iterates state.units, so its gain is 0. The headroom phase filtered Resumes by _has_reuse (re_use>0) → the Resume was dropped; and even unfiltered, the knapsack won't pick a gain=0 zero-weight item (it ties the take-none cell and loses). Net: the program can NEVER be resumed → it starves to an AgentTimeout. This was masked in the campaign logs by sgl-project#209 (occ=0 zeroed the headroom gate) and sgl-project#210 (apply_failed storm); both now fixed, this is the residual starvation channel. Fix (the design intent: detected headroom must never idle while a program starves — DESIGN §8): - joint_decide headroom: stop filtering zero-re_use Resumes. A zero-HBM resume is a FREE un-starve (just release the gate), not a no-op; resume_candidates already gated each on capacity_fits and the knapsack enforces free_room. (_has_reuse helper deleted — sole consumer.) - resume_candidates: floor the gain at _RESUME_LIVENESS_FLOOR=1e-9 so a zero-value paused program is still granted when it fits. The floor is a weight-0 item that can never reorder a real V_u-bearing resume (any cached value dwarfs 1e-9). verify/joint_decide stage D-starve pins it (dropped-units + empty-unit_hashes both resume; multi-subpool gate + valuable-vs-floored co-grant ordering). Mutation-tested: removing either fix part turns it RED.
rucnyz
added a commit
to rucnyz/sglang
that referenced
this pull request
Jun 7, 2026
The holistic audit of sgl-project#210+sgl-project#211 found a residual leak: _flatten_per_rank dedupes a hash seen on multiple TP ranks by unioning residence and agreeing-or-fatal on n_bytes, but it never reconciled the three new leaf flags — the merged unit kept rank-0's values verbatim. In the mid-migration window the residence-union comment already calls out (one rank device-resident, another evicted), the leaf predicates diverge too: _is_host_leaf requires node.evicted, so the same hash is is_device_leaf=True on one rank and False on another. Keeping rank-0's permissive True lets migrate_candidates propose a remove the disagreeing rank rejects — re-arming the sgl-project#210 apply_failed leak in exactly that window (partial/transient, only under TP>1, hence not the full pre-sgl-project#210 storm). Fix: AND-reconcile is_device_leaf/is_host_leaf/is_tree_leaf in the collision branch. A remove is structurally safe only if EVERY rank agrees the node is the relevant leaf — the stricter mirror of the (colder-superset) residence union. verify/kv_scheduler_value_rule stage A1b pins it (diverging ranks must AND to False, order-independent). Went RED before the fix, GREEN after; all 21 stages green. Follow-ons filed: sgl-project#212 (sglang dump-emission of leaf flags untested) and sgl-project#213 (headroom all(r>0) gate strands zero-re_use resumes when any subpool full — residual multi-subpool starvation channel).
rucnyz
added a commit
to rucnyz/sglang
that referenced
this pull request
Jun 7, 2026
…-wins + union) Second holistic audit pass on the cross-rank (TP>1) aggregation in _flatten_per_rank found two more bugs of the same class as the sgl-project#210 leaf-flag merge — a per-program/per-unit field that diverges across ranks in a transient window, where the merge picked the WRONG side. PUT /aginfer/program_paused and per-rank session tagging both fan out per-rank non-atomically, so a state dump can land mid-fan-out with ranks disagreeing. 1. per_program_usage[pid].state used most-active-wins (REASONING>ACTING>PAUSED>ENDED). If a lagging rank still reported a just-paused program as REASONING, the merge masked the pause → resume_candidates (which only considers state=="PAUSED") dropped it → the program (emits no events of its own) STARVED to AgentTimeout. The sgl-project#211 starvation class, here via cross-rank merge instead of dropped units. pre_pause_state followed the wrong (REASONING→None) rank too, which would restore a resumed program to the wrong state. Fix: PAUSED:4 > REASONING:3 > ACTING:2 > ENDED:0. PAUSED wins (the liveness-safe side, mirroring residence-union / leaf-AND); ENDED still loses so a lagging co-holder rank isn't driven to a premature ENDED that drops session_scoped KV. 2. holders/session_ids kept rank-0's set verbatim in the unit-dedupe collision branch → order-dependent. shared_aware_prog_scores' V_u divisor len(holders) and session_scoped_units' holders=={session} predicate skewed by rank ordering. Fix: UNION session_ids (colder superset, order-independent) alongside the existing residence-union / leaf-AND reconciliation. verify/kv_scheduler_value_rule stages A1c (PAUSED-wins + pre_pause survives + ENDED-loses, order-independent) and A1d (holders union, order-independent) pin both; mutation-tested RED→GREEN; suite 23/23. joint_decide + admission_controller still green. Follow-ons filed (not fixed here): decode_per_program SUM-vs-DESIGN-mean (dormant until T11/T26); resume double-fire dedup on overlay lag (benign waste); partial-drop resume HBM under-estimate; t21 verify stale vs sgl-project#200's _aginfer_runtime_metrics.
rucnyz
added a commit
to rucnyz/sglang
that referenced
this pull request
Jun 7, 2026
…; KEEP throughput SUM (not mean) Systematic field-by-field audit of _flatten_per_rank's cross-rank merge. Net result after human review: one fix kept, one proposed change reverted. KEPT — units last_access_time / hit_count: rank-0-verbatim → MAX in the collision branch. Same transient-divergence class as the residence/holders merge: a stale rank-0 last_access inflates age=max(1,now-last_access) → deflates p_hat=min(1,hits/age) → spuriously demotes a warm unit in _top_k_by_regret. MAX (warmest) is order-independent and liveness- preserving, mirroring residence-union / holders-union. Pin A1g, mutation-tested RED→GREEN. REVERTED — throughput_ema.prefill_bps / decode_per_program: a subagent changed SUM→MEAN citing DESIGN §6 L766/L767. That is WRONG here: the daemon runs in a UNIFORM N×-scaled byte space. units' n_bytes are agree-or-fatal across ranks ⇒ KV bytes are MIRRORED (replicated MLA latent), not sharded; pool_usage + committed + inflight are all SUMmed ⇒ every absolute byte AND byte-rate is N×. Uniform scaling means every consumer cancels (occ ratio; N× budget vs N× weight; (N× inflight)/(N× prefill_bps); N× growth vs N× cap). MEAN-ing ONLY the two rates while bytes stay SUMmed would BREAK the cancellation and inject a real N× error. DESIGN's "mean" assumes a true-scale/sharded regime this impl doesn't use; true-scale conversion = de-N×-ing ALL byte fields together, deferred to sgl-project#214 — moot today since the forecast consumer is dormant (T11/T26) and the whole multi-rank path is dead code until sgl-project#174 wires per-rank dumps (sglang returns a single pre-aggregated dump → _flatten_per_rank returns it unchanged). Reverted the SUM→MEAN code, docstring, and the A1e/A1f pin stages; documented the SUM rationale inline. Field-reconciliation contract now complete in the docstring + inline. Suite 24/24 (A1c/A1d/A1g green); joint_decide + admission green.
rucnyz
added a commit
to rucnyz/sglang
that referenced
this pull request
Jun 7, 2026
The live ours_full A3 arm produced ~956 remove_hbm_not_device_leaf/cycle with migrate_applied=0. Debug-log probe in _dispatch_plan showed every dispatched remove-HBM had daemon_leaf=True, residence=[HBM], add=[] remove=[HBM] (a DROP). It is NOT a filter bypass (the sgl-project#210 filter correctly passes them — they ARE device leaves at dump time): it's a dump-vs-apply TOCTOU. A device-leaf popular-prefix node gains a device-KV child before the migrate applies (a concurrent request extends that prefix), so the remove is rejected at apply. The dump keeps reporting it as a leaf, so it is re-proposed every event → a systematic reject storm. (The age distribution refuted a "hot session-tail" hypothesis — the DROP targets are mid-age popular prefixes, so the right fix is reactive, not a recency guard.) Fix: on a leaf-reject APPLY_FAILED (remove_*_not_*_leaf / remove_not_leaf) the handler cools the failed hash down (router.evict_cooldown, wall-clock backoff, AGINFER_EVICT_COOLDOWN_S=5s). kv_scheduler.handle drops any REMOVE migrate for a cooled hash before dispatch (pure-ADD migrates for the same hash still pass — only the failing op is backed off) and prunes expired entries. So a doomed remove is proposed at most once per cooldown window instead of every event; when the node stabilises (gains a host backup) or sglang evicts it itself, the cooldown expires and it can be migrated again. Backoff, not value math — wall-clock is acceptable (DESIGN §10 forbids time.* only in the V_u transition path). verify/kv_scheduler_value_rule stage G0 pins _filter_cooled_evicts (cooled REMOVE dropped, cooled pure-ADD kept, non-cooled/expired kept). 25/25 + joint_decide + admission green. Pairs with sgl-project#213 (decouple resume from pressure). Next: real-stack smoke to confirm resume>0 + apply_failed≈0 + agents progress (A3 do-no-harm).
rucnyz
added a commit
to rucnyz/sglang
that referenced
this pull request
Jun 9, 2026
…ding holders Kills the TP=4 A3 remove_hbm_not_device_leaf reject storm (1384/cycle, 187 hot units re-failing ~15x). Root cause is persistent TOCTOU, not a mis-identification: a session-tail leaf is a device-leaf *at dump time* only in the brief gap between an active program's forward passes (its lock_ref oscillates per pass; the dump samples a released instant). By apply time the state is up to ~840ms stale and the holder has re-locked its tail, so sglang rejects. Fix: gate on the program-level signal, which is STABLE across the per-pass oscillation. _holder_actively_decoding(u, state) returns True iff any holder pid has T26 per_program_usage[pid].hbm.inflight > 0 (a request in the running batch). migrate_candidates skips remove-HBM for such units, after the existing sgl-project#210 structural leaf guards. Node-level lock_ref is the wrong signal (0 at the dump instant). Tool-parked holders (inflight empty) keep their idle tail evictable -- the core demote-during-the-tool-gap relief. Absent/cold-start inflight never suppresses. Layers cleanly with sgl-project#223 (reactive post-reject cooldown) and sgl-project#210 (structural leaf guards); sgl-project#224 is the proactive complement. Audit (sgl-project#225 follow-ups): holders come from add-only session_ids, so the guard slightly over-approximates (safe direction -- forgoes a valid demote, never proposes an invalid one); bounded small under temp-0 linear agentic decode. Re-run must confirm migrate_applied>0 + HBM occ drops, not merely that rejects fell to zero. Tests: verify/joint_decide A-inflight (active blocked, parked/zero/ no-hbm/cold preserved, shared + multi-subpool blocked). DESIGN.md §7/§9 apply-feasibility pre-filter subsection. All pure suites green.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Jul 27, 2026
…it (sgl-project#210) SPLIT-BALANCE re-run with a content-pinned harness, and the mode it gates. WHY THE PREVIOUS MEASUREMENT COULD NOT ANSWER THIS The Window-4 A/B was inconclusive by construction: its independent variable (the KV-token ownership vector) perturbs its dependent variable's content. Moving a token's home rank moves the LSE-merge partition, hence the numerics, hence -- at greedy -- the sampled token at the first near-tie. All six points produced different text and throughput follows content on this rig (r = 0.90). HOW CONTENT WAS REMOVED RATHER THAN AVERAGED OVER Speculation off, ignore_eos with a fixed max_new_tokens, and a DENSE model (no MoE routing) together make a decode step's cost a function of (batch size, resident context) only -- not of which token was produced. The work is then identical between the arms by construction. Measured quantity is the DEPTH TERM step_ms(deep) - step_ms(shallow) inside one boot, which cancels the ~26 ms constant (weights, 128 collectives, 48 GDN layers) that the split cannot touch. RESULT (27B FP8, TP=3, uneven DCP, flashinfer, bs=1, identical weight plan in every boot, arms interleaved A,B,A,B,A,B, every boot cold per sgl-project#188) noise floor, A-vs-A boot-to-boot depth term: 1.07 % depth term [2,3,3] 2.2955 -> [2,1,1] 1.7324 ms = -24.5 %, t = -17.85 end to end at 120420 resident tokens: -2.51 % step time spec-ON cross-check (time per verify round, accept and verify_ct identical in both arms at the deep point): -26.7 % depth term, -4.12 % round time max_total_num_tokens 393228 in BOTH arms -- the hybrid mamba cap binds first, so on this configuration the shift is free. WHAT THIS ADDS --rank-kv-ratio speed walks from the capacity share vector to the per-rank memory-bandwidth share vector and takes the most bandwidth-shifted point that still funds the allowed context, bounded by the existing --rank-perf-loose-ctx-percent. The floor is evaluated against the EFFECTIVE budget min(kv_budget, hybrid mamba/SWA cap): while that cap binds, the shift costs nothing and is taken in full even at the default 0 % -- without which the mode would refuse every free gain on exactly the models where it is largest. Derivation is a deterministic pure function of the all-gathered per-rank capacities and server args, installed at the same phase-2 point as 'capacity', so the rank-uniformity invariant is unchanged. No bandwidth scores (no hardware profile) => explicit warning and fallback to the capacity vector. --rank-perf-tune dec stops being a no-op: it now selects --rank-kv-ratio speed. The help text is corrected accordingly -- the weight split is what is flat for decode, not decode itself. New target 'maxkv' selects 'capacity' (naming coherence, no new capability). Both promotions fire only when --rank-kv-ratio was left at its default, so an explicit mode or pinned vector always wins and 'both'/'enc' keep the default path byte-identical. TESTS 137 passed: 22 new CPU tests (flag surface, promotion precedence, derivation direction, loose-ctx floor, hybrid-cap free window, determinism, gcd reduction) plus the existing rank_kv_ratio, planner-flags and boot-token-vector-guard suites, no regressions. VALIDATING BOOT (27B FP8 TP=3 uneven DCP, MTP on, ctx 32768, --rank-perf-tune dec, no --rank-kv-ratio): promotion fires, bandwidth weights 7,3,3, speed vector [34,15,15] installed at 100 % of the shift, KV rows 52258/23055/23055 against the reference capacity boot's 24584/36876/36876, and max_total_num_tokens 98328 -- identical to the reference. Coherent generation, accept 3.44. Full report incl. raw per-boot/per-rank data with clocks and temperatures: RESULT_210_splitbalance_gepinnt.md
efschu
added a commit
to efschu/htsglang
that referenced
this pull request
Jul 27, 2026
…s available Rebase onto integration/r3-probe made two things stale at once. Naming. Three unrelated things were called "profile" in one surface: planner.flags.Profile (a launchable server preset), planner.profiles (the GPU nameplate catalog) and the five directions here. The directions are now Levers -- LeverProfile -> Lever, LeverSuggestion.profile -> .lever, and no lever text says "profile" any more. The decode lever. It was written on a branch where --rank-kv-ratio did not exist, and said so. sgl-project#210 shipped it (a564aaf), so the build gate now resolves it to a real flag. Consequences carried into the data: * decode_speed emits --rank-kv-ratio speed and, with it, --rank-tp-ratio auto-performance: 'speed' reads the per-rank bandwidth scores that only the auto-performance plan resolves, and without them the mode degrades to 'capacity' -- the opposite direction. * decode_speed carries sgl-project#210's measured worth (27B FP8, TP=3 uneven DCP, 120 k resident tokens, bs=1: [2,3,3] -> [2,1,1] cut the context-dependent part of the decode step by 24.5 % against a 1.07 % boot-to-boot noise floor). * context emits --rank-kv-ratio capacity, the counterpart that maximises max_total_num_tokens. The build-gate test no longer asserts that a specific flag is absent -- that made the test a claim about the branch rather than about the gate. It now exercises the gate on a synthetic lever, and a second test asserts the decode lever resolves on this build. Tests: test/registered/unit/planner/test_levers.py -- 20 passed.
WhiteCmile
added a commit
to WhiteCmile/sglang
that referenced
this pull request
Nov 3, 2026
…om PR sgl-project#210's review - accepted/duplicate Coordinator ACKs now drop the publish-time _remote_ring_sessions marker (new _ack_confirmed_remote_rounds), which otherwise grew without bound on the normal path (p0) - _retire_unaccepted_transfer classifies remote rounds by the publish-time session marker instead of _remote_ring_records, which the successful submit consumes before the ACK: a submitted-but-backpressured remote round no longer misclassifies as local and strands its source lease (p1) - the proof/cache/retirement handshake is serialized with a dedicated lock between the RDMA completion thread (_consume_remote_source_proof) and the scheduler thread (retirement, ACK cleanup, owner revocation), so a landed proof cannot be lost between the waiter check and the cache insert, recorded after ACK cleanup, or retired twice (p1)
WhiteCmile
added a commit
to WhiteCmile/sglang
that referenced
this pull request
Nov 3, 2026
…races from PR sgl-project#210's review - _plan_direct_ring now installs the unconfirmed-round bookkeeping (_direct_sent + the publish-time _remote_ring_sessions marker) BEFORE writer.write(): the ctypes post releases the GIL, so a Draft can consume the record, abandon, and land its authenticated tombstone inside the write window; a proof landing with neither waiter nor unconfirmed marker was dropped and the source lease leaked. A failed write rolls the bookkeeping back so the round classifies local (p1) - _ring_revoked_sessions now caches the quiescence proof per revoked session; _retire_unaccepted_transfer consumes it instead of registering a waiter when the Draft was revoked while the round's Coordinator copy sat backpressured - no push or revocation could follow, so the waiter never completed and the lease leaked (p1) - drop the test-only _NULL_CONTEXT lock fallback: production controllers always run __init__, and the doubles initialize _remote_source_lock themselves (p2) - drop the three registry counters from the lifecycle status marker: its schema is a frozen contract of the exact-token acceptance gate (dt-runtime DT_LIFECYCLE_COUNTER_SCHEMA), which both gate compositions pin
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.
Fixes issue #159
You can now specify how much context you want the model to have.
For example Mixtral 8x7b AWQ:
python -m sglang.launch_server --model-path /path/to/bagel_mixtral_AWQ --port 30000 --tp 2With the adjustment
python -m sglang.launch_server --model-path /path/to/bagel_mixtral_AWQ --port 30000 --tp 2 --context-length 8192