Skip to content

Refactor ChatTemplate for Enhanced Clarity and Efficiency - #201

Merged
hnyls2002 merged 1 commit into
sgl-project:mainfrom
cubxxw:patch-1
Mar 3, 2024
Merged

hnyls2002 merged 1 commit into
sgl-project:mainfrom
cubxxw:patch-1

Conversation

@cubxxw

@cubxxw cubxxw commented Feb 17, 2024

Copy link
Copy Markdown
Contributor

CHANGER

  • Simplification of conditional logic to reduce code duplication and increase clarity.
    Utilization of enumerate in loops for improved readability and direct access to both index and value.
  • Optimization of prefix and suffix retrieval by leveraging dict.get for more concise and safe access.
  • Streamlining if statements to decrease nesting depth and clarify logic.
    Adoption of f-strings for string concatenation, enhancing readability and maintainability.

@hnyls2002
hnyls2002 merged commit b0b722e into sgl-project:main Mar 3, 2024
timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
vschandramourya pushed a commit to vschandramourya/sglang that referenced this pull request Feb 3, 2026
IzacharyI pushed a commit to IzacharyI/sglang that referenced this pull request Mar 16, 2026
…ser (sgl-project#201)

* Add qwen3.5 readme and scripts

* [Bugfix]fix acc test eror that content after \n cannot account in anwser

---------

Co-authored-by: qichu <[email protected]>
liuxianglong17 pushed a commit to shun8686/sglang that referenced this pull request Apr 2, 2026
rucnyz added a commit to rucnyz/sglang that referenced this pull request Jun 9, 2026
… — un-clog the hints flood

Root cause of the residual migrate reject rate (post-sgl-project#224): the daemon
pushes a hints PUT every event (T40), so hints are ~99% of outbound
traffic (~11.7k vs ~130 migrate/cycle). The outbound channel is
single-flight at sglang, so every time-sensitive migrate waited ~1.8s
behind that idempotent flood in the FIFO queue, ageing until the radix
tree diverged and the apply-time leaf check rejected it. Transport is
not the bottleneck (localhost sub-ms) and daemon-side concurrency does
not help (sglang serialises apply via one communicator) -- the fix is
to stop the flood from blocking migrates.

sgl-project#228 (latency, the relief lever): the worker drains the queued burst
each wake and emits at most ONE dispatch per endpoint by temporal
semantics -- hints merge to one PUT (highest stamp per hash; sglang is
itself overwrite-by-stamp), migrates stay individual (rare; FIFO +
per-POST escalation preserved), program_paused coalesced by pid. Order:
program_paused -> migrate -> hints, so time-sensitive intents never
queue behind the flood. current_oldest_pending_age_ms() now also counts
the in-flight drained burst so /health backlog stays accurate.

sgl-project#227 (correctness bound, generous): a migrate decided on a state
snapshot is a prediction with a validity horizon; the worker drops one
aged past AGINFER_MIGRATE_FRESHNESS_MS (default 30s -- a pathological-
spike floor, NOT a tight knob; the coalescing removes normal-operation
latency). Proactive complement to the reactive APPLY_FAILED re-issue.

Latency proof (verify/outbound_coalesce B0/B1): with 200 hints queued
ahead of a migrate, the migrate is dispatch call #0 (not sgl-project#201) and the
200 hints collapse to 1 PUT; wall-clock migrate latency mean 0.2ms over
3 trials vs the N*apply serial floor of 1000ms.

Audit (no Critical/Major): hardened hints merge to max-stamp (order-
independent); documented that the sgl-project#164 stall backstop relies on the
always-on hints canary (a stale-dropped migrate emits no failure
signal). task_done accounting, escalation, /health live-peek all
preserved (t164/t36 green).

Tests: new verify/outbound_coalesce (7 stages: coalesce correctness +
latency proof). 17/17 touched suites green (t36 t164 t41 t187 t30 t22
t24 t23_t37 kv_scheduler_value_rule joint_decide admission_controller
t34 t16 dump_leaf_flags program_tracker t21). DESIGN §6 updated.
verify/t40 left as-is (pre-existing stub staleness, tracked sgl-project#229).
efschu added a commit to efschu/htsglang that referenced this pull request Jul 28, 2026
…e intra-rig smoke boots

Two cases were missing from the admission matrix: one rank per stage on its
own card (admitted, and the same MiB budget maps to different fractions on a
32 GiB and a 20 GiB card), and the same shape with both stages pointed at one
card (refused).
efschu added a commit to efschu/htsglang that referenced this pull request Jul 28, 2026
…dexing in the worker, and the intra-rig smoke

Boots and runs. pp_size=2, one rank per stage, 44 layers on the 5090 and 20 on
a 3080, Qwen3.6-27B-MTP-Q3_K_M-GGUF: 9313-token prefill plus 700 greedy decode
tokens in 16.6 s, 44.2 tok/s steady state, coherent output throughout, and
"cuda graph: True" -- full decode graphs work under a pipeline, and the graph
plan is negotiated per stage. The KV split follows the layer split exactly
(2.99 GB K against 1.36 GB, ratio 2.2 = 44/20). Recipe and caveats in
docs/rig-runbook.md 4.7.

Two things the smoke found.

--rank-gpu-memory-mib as a list required --rank-tp-ratio. That rule reads
"with even TP all ranks are structurally equal, so use a scalar", which is a
statement about a pure TP group. A pipeline is not one: stages hold different
layer counts by construction, deliberately so under --pp-layer-ratio, and
stage 0 additionally carries embed_tokens while the last carries lm_head. With
tp_size 1 per stage the demanded ratio could not even be expressed. A scalar
sized for the 3080 starves the 44-layer stage -- measured, it missed by 175
MiB at 15000. The gate is now limited to pp_size == 1.

Three worker-side sites still indexed the per-rank vectors by tp_rank
(budget selection, the GPU named in the shortfall message, the co-location
count). Under a pipeline every stage therefore read stage 0's entry: stage 1
checked its 3080 against the 5090's budget and rejected a configuration that
fits. They now go through _rank_vector_index(), which is world_rank() with a
fallback for stubbed server args.

Not fixed here, and not ours: booting the same topology with --base-gpu-id
instead of --rank-gpu-id dies on the 3080 with "Modifier '.launch_dependents'
requires .target sm_90 or higher". _ENABLE_PDL in
layers/fused_qk_rmsnorm_rope_gate.py is a module constant computed once from
cuda_sm_at_least(9), whose device_id defaults to 0 -- the sm_120 5090 here --
so an sm_86 stage emits a Hopper instruction. That is a mixed-architecture bug
independent of PP: it hits any process whose compute device is not device 0
and differs from it in architecture. --rank-gpu-id avoids it by forcing
SGLANG_ONE_VISIBLE_DEVICE_PER_PROCESS, which is why every existing recipe on
this rig is immune. Documented in the runbook, left for its own fix.

Tests: 37 cases in test/registered/unit/server_args/test_pp_layer_ratio_args.py,
all pass. test/registered/unit/server_args/ + test/registered/unit/distributed/
show the same 17 pre-existing failures before and after, none new.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 28, 2026
…e, PP=2 smoke 44.2 tok/s with graphs, slice-2/3 effort mapped
efschu added a commit to efschu/htsglang that referenced this pull request Jul 28, 2026
… boundary ~2 % of decode round, metadata>payload at bs=1, graphs on both stages
efschu added a commit to efschu/htsglang that referenced this pull request Jul 28, 2026
…validation

Appended, not renumbered, per row-number stability:
- Row 26, Prefill satellite (cross-host PD for hybrid GDN, task sgl-project#212):
  Block 2. Base cross-host PD disaggregation is already upstream; the
  fork's delta is the hybrid-GDN Mamba-slot-with-KV handoff (the HiCache
  L3 store alternative silently recomputes for GDN models) and an honest
  TTFT-vs-undisturbedness measurement. The method itself is hardware-
  symmetry-agnostic ("with a faster satellite card the trade flips; this
  is a statement about this 2080 Ti, not the method"), so an identical-
  GPU rig running hybrid-GDN models under PD gains the same correctness
  fix - hence Block 2, not Block 1 despite the mismatched test vehicle.
- Row 27, Cross-rig uneven pipeline parallelism (task sgl-project#201 slice 2):
  Block 1. Even/base PP is already upstream; the fork's delta is the
  per-stage layer ratio, which only matters when the two stages are not
  equally capable (mismatched cards or mismatched hosts) - an
  identical-GPU rig would use the existing even split and gain nothing
  extra from "uneven". Also notable as a hetero path that needs no
  HTCCL: PP keeps tp_size=1 per node, so no TP group spans hosts, and
  CUDA graphs stay on on both stages including the sm75 one.

Evidence exclusively from INTEGRATION_R3_VALIDATION.md (sgl-project#212 and sgl-project#201
slice-2 sections) and rig-runbook.md sections 4.8/4.9, with the same
Built/Boot-checked/Cross-checked vocabulary as the rest of the file -
both land as Boot-checked (real hardware, real model, coherent output,
honest A-vs-A/monolithic controls; no independent correctness oracle
was run, so neither qualifies as Cross-checked).
efschu added a commit to efschu/htsglang that referenced this pull request Aug 16, 2026
Defect I introduced in 84abeb7, caught by its own first metal output.

The instrument labelled each line with self.tp_rank. Under the flip's primary
topology (tp=1, pp=N) every PP stage has tp_rank 0, so all three stages name
stage 0's card. That is the sgl-project#201 defect, and the budget-exhausted path a few
lines below already guards against it in a comment that says so verbatim:
"tp_rank alone makes every PP stage name stage 0's card". I wrote the new line
without applying the warning sitting next to it.

Confirmed by the first boot to carry the line: PP0, PP1 and PP2 all emitted
"[rank 0]". A second boot in the same log happens to show 0/1/2 because that
configuration has distinct tp_ranks, which is exactly the kind of intermittent
correctness that makes the label untrustworthy rather than merely ugly.

Fixed to _rank_vector_index(), the accessor this module already uses for the
same purpose (it resolves server_args.world_rank(pp_rank, tp_rank) and falls
back to tp_rank only when server_args is stubbed). Field renamed to
world_rank so consumers cannot silently read the old meaning.

The already-captured data remains usable: the log prefix (PP0/PP1/PP2) carries
the true stage, so the six lines in docs/dev/DATA_704_budget_posts.txt are
correctly attributable despite the wrong bracket. Captured to the repo because
/root/current_boot.log is a symlink that moves on the next boot and this is the
retro-prediction gate's input data.

First metal values, [28,20,16] budget_mib branch (the branch my external
re-derivations kept missing): weights+runtime 15.688 / 9.826 / 10.449 GiB,
mamba+spec+activation reserve 0.895 / 0.639 / 0.511, GGUF scratch 0.000,
rest 14.472 / 7.894 / 8.375.

Verification: compiles, ruff clean, model_executor 594 passed / 15 failed with
the 15 already established as pre-existing by revert-and-rerun on the previous
commit. Still one log statement, no control flow.
efschu added a commit to efschu/htsglang that referenced this pull request Aug 16, 2026
Defect I introduced in 84abeb7, caught by its own first metal output.

The instrument labelled each line with self.tp_rank. Under the flip's primary
topology (tp=1, pp=N) every PP stage has tp_rank 0, so all three stages name
stage 0's card. That is the sgl-project#201 defect, and the budget-exhausted path a few
lines below already guards against it in a comment that says so verbatim:
"tp_rank alone makes every PP stage name stage 0's card". I wrote the new line
without applying the warning sitting next to it.

Confirmed by the first boot to carry the line: PP0, PP1 and PP2 all emitted
"[rank 0]". A second boot in the same log happens to show 0/1/2 because that
configuration has distinct tp_ranks, which is exactly the kind of intermittent
correctness that makes the label untrustworthy rather than merely ugly.

Fixed to _rank_vector_index(), the accessor this module already uses for the
same purpose (it resolves server_args.world_rank(pp_rank, tp_rank) and falls
back to tp_rank only when server_args is stubbed). Field renamed to
world_rank so consumers cannot silently read the old meaning.

The already-captured data remains usable: the log prefix (PP0/PP1/PP2) carries
the true stage, so the six lines in docs/dev/DATA_704_budget_posts.txt are
correctly attributable despite the wrong bracket. Captured to the repo because
/root/current_boot.log is a symlink that moves on the next boot and this is the
retro-prediction gate's input data.

First metal values, [28,20,16] budget_mib branch (the branch my external
re-derivations kept missing): weights+runtime 15.688 / 9.826 / 10.449 GiB,
mamba+spec+activation reserve 0.895 / 0.639 / 0.511, GGUF scratch 0.000,
rest 14.472 / 7.894 / 8.375.

Verification: compiles, ruff clean, model_executor 594 passed / 15 failed with
the 15 already established as pre-existing by revert-and-rerun on the previous
commit. Still one log statement, no control flow.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 26, 2026
… my 18 commits: two claims withdrawn

The sweep I named and had not run. Every citation of a log string or a borrowed
measurement across all 18 commits on this branch, checked against THE source it
cites -- not against any source. 31 citations, four states.

BELEGT -- 27. Everything drawn from
/spinning/evidence-665-f1/boot_w40_857strict_0826_0516.log verifies literally in
that file: the three segment times, the 75 % worst-share, `save 4.342`,
`gpu-span d2h 0.000s / h2d 0.000s` (21x), `checksum 0.319`,
`gdn_state->refill_highwater` 0.2 and 7.0, `weights_refill->cutover` 113.5 and
972.1, the 498/268 aliasing counts, `REFILL pp_to_tp took 3.961 s for 8573.8
MiB`, `pp_attn_stage_ratio=[8, 4, 4]`, `disaggregation_mode='null'`,
`rank_tp_ratio=None`, `uneven_token_vector='29,19,16'`, and the W40 specimen
details I repeated from the briefing (05:20:50, the rid, the IndexError,
`SEAM RESTORE ATTEMPT`, `FLIP EXTENT PROBE`, `extent=13`,
`transfer_layer_num=32`). The log is present; source not missing.

NIE-GEDRUCKT, CLAIM ALSO FELL -- 1. "the boot line at :3228 prints
`get_total_num_kv_heads()`": zero occurrences. Already retracted in 19b8177;
the sentence it supported was false and the true one is restored.

NIE-GEDRUCKT, CLAIM SURVIVES -- 1. "24 s after health 200". The string
`health 200` never printed. The log says `"GET /health HTTP/1.1" 200 OK` at
05:20:26, and the crash is at 05:20:50: exactly 24 s. The claim is right to the
second; only my citation form was ungreppable, so anyone verifying it would have
found nothing. The two cases are kept apart because their consequences differ.

MISATTRIBUTED, AND MISREAD -- 1. I priced sgl-project#875's DO-NOT-BUILD verdict with
"43.9 KiB per crossing, 166 us enqueue, 1777-9201 us receive", attributed to
sgl-project#656. It is not in sgl-project#656. It is in 13c55d7 "[PP] sgl-project#201 slice 2: the stage
boundary across two rigs" -- CROSS-RIG, two nodes, a 40G line, a different model
(Qwen3.5-4B fp16), timing PP microbatch crossings and not an intra-node
collective. And its own text refuses my reading: "`recv` is BLOCKING, i.e. bubble
plus wire -- 9.2 ms on stage 1 is that stage waiting for stage 0, NOT the 40G
line". I used a pipeline bubble as transport latency, from the wrong ticket, for
the wrong link. WITHDRAWN, with no substitute: I have no measured local
collective figure.

QUELLE-FEHLT -- 1. "sgl-project#721's measured cgroup peak (111.3 of 118 GiB,
oom_kill=17)", used in sgl-project#877 and in sgl-project#878's headroom. `oom_kill=17` has NO in-tree
source, and the only `111.3` is `111.3%` in a benchmark table
(docs/dev/631/PROD_BRINGUP_BENCH.md) -- an unrelated percentage. It came from a
briefing and I repeated it as measured, twice. WITHDRAWN. This is the shape the
operator hit this morning with the retracted "1833/1833 records".

WHAT THE TWO WITHDRAWALS COST, stated rather than smoothed:
  * sgl-project#875's verdict loses its timing leg entirely. It now rests on two terms that
    need no transport number: the HEAD axis is LOSSY (PP 4 kv-heads per layer,
    TP 1), so PP->TP is not a remap until someone decides which heads survive
    and no such rule exists; and a new collective in the no-return region is the
    sgl-project#630 wedge shape, an unbounded risk. Point one alone is decisive. DO NOT
    BUILD stands, on better ground than it had.
  * sgl-project#878's headroom argument is re-grounded on a figure I took myself: this box
    reports 128711 MB total / 76971 MB free, so +96 MiB of pinned host image is
    negligible by four orders of magnitude, needing nobody's peak.
  * sgl-project#877's conclusion is untouched: N <= 72 rows of a per-LAYER temporary is
    kilobytes, and separately none of its six sites is constructed on this rig.

THE CLASS: a citation is evidence only for the claim it is attached to, in the
source it names. Three of the four defects here were true-sounding numbers from
the right neighbourhood -- a real measurement of a different link, a real
percentage read as gigabytes, a real code branch that never executes.
Chosen-David pushed a commit to Chosen-David/sglang that referenced this pull request Oct 10, 2026
TL-E119-POINTER-SYMLINK-071(P2):resolve_generation_pointer 此前用
词法路径 + 跟随 symlink 的 isdir/isfile 判存在——gen 内预测/回执可为
指向目录外的 symlink,外部字节与 receipt 声明逐位自洽时 probe complete
/ audit OK / formal verified_same_generation=true,违反「不可变
generation 内物理同源」契约。修复(lstat+realpath 双查,取舍与 TOCTOU
残余风险声明见 _realpath_within docstring):指针本身 islink/lexists
门禁 + gen 目录/预测/回执终分量 islink 拒 + realpath+commonpath 闭包
(防中间分量逃逸,anchor 一致 realpath 不误伤 symlinked 部署);resolve
返回值附带 canonical realpath,formal 来源闭包比对锚改用它(不再只比
词法 dirname),逃逸代不可达 pointer-v1/verified=true。
TL-E119-PROBE-PRED-IO-072(P3):validate_committed_generation 预测
_file_sha256/_count_lines 的 OSError 统一转 [GATE-FAIL] SystemExit
(带路径+阶段);audit_directory 逐格 (SystemExit, OSError) 兜底捕获,
坏格计 invalid 后继续下一格(total/invalid 计数完整 rc=2);探针单格
路径同归一(四态 CLI 契约,无裸 traceback)。
测试(test_e119_pointer_consumer_068_069.py 新增 S1/S2/S3,python±-O):
S1 symlink 逃逸四负例(预测/回执/gen 目录/双文件外链自洽——审计 §1
复现场景)resolve/probe/audit/formal 全链拒收;S2 不可读预测夹两好格
→ 单格 STATE=invalid + audit total=3 invalid=1 rc=2 三格均有记录;
S3 symlinked 输出树零误伤(反向验收)。回归全绿:068/069 16/16、
binding 31/31、057 10/10、crossarm 20/20×64k/128k、E116f 12/12
(均 python±-O);E109 输出根 --audit-dir 只读复扫 total=0 维持零指针。

Co-Authored-By: Claude Opus 4.6 <[email protected]>
detain added a commit to detain/sglang that referenced this pull request Nov 11, 2026
…oot order -- maybe_init_router_registration moved back to __init__'s last step (upstream 4e5057a sgl-project#48119 placement)

Operator's real restart died at boot (era tip b069e6a):
  tokenizer_manager.py:623 __init__ -> :667 init_preprocess_executor ->
  :958 maybe_init_router_registration -> AttributeError:
  'TokenizerManager' object has no attribute 'tokenizer_ipc_name'

Root cause: upstream folded the registration in as the LAST statement of
__init__ (after init_ipc_channels assigns tokenizer_ipc_name/send_to_scheduler
and after the cuda_vmm transport construction); the fork (stack sgl-project#201, PR
sgl-project#39716) runs its init_preprocess_executor BEFORE init_ipc_channels, and the
b4 merge resolution wired the upstream call inside that earlier step -- so it
read attributes that are not assigned until the next step. Single-worker
servers crashed too: the read is unconditional in the method's guard.

Fix: move the call out of init_preprocess_executor to upstream's exact
position (final __init__ step). No guard, no hasattr -- the method's
semantics (dispatch over IPC) require the channels, which the fork builds
later; only the order was wrong. 2-line move + comment.

Regression test test_tokenizer_manager_init_order.py drives the REAL
__init__ sequence (only model/tokenizer loading, the SHM snapshot reader,
and sock_send stubbed), parameterized router OFF (tokenizer_worker_num=1:
construction completes, nothing dispatched) / ON (=2: exactly one
TokenizerWorkerRegistrationReq with the worker's IPC name, dispatched after
the attrs exist). RED at b069e6a: 2F (the verbatim AttributeError).
GREEN: 2P.

Family scan (window methods from 2a6c204..eb73a50 in
tokenizer_manager/detokenizer_manager, MRO-precise assignment check): no
other never-assigned attribute and no second init-order hazard; all other
window methods are post-init request handlers whose attrs init assigns
(detokenizer init chain verified). Uncertain-adjacent, report-only:
get_tokenizer_worker_class/entrypoints wiring untouched (outside managers
init zone).

Gates: ruff v0.15.1 F401,F821,F823,UP037 + format rc=0; check_registered_tests
/ check_no_bare_pytest_main / check_no_registered_tests_in_package rc=0;
import probe (CUDA_VISIBLE_DEVICES=9) rc=0; managers battery 1301P/2F/11s --
2F are the pre-existing test_mm_process_config pair, unchanged.
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