Skip to content

Support v1/chat/completions - #50

Merged
merrymercy merged 6 commits into
mainfrom
cody/openai-chat
Jan 19, 2024
Merged

merrymercy merged 6 commits into
mainfrom
cody/openai-chat

Conversation

@comaniac

Copy link
Copy Markdown
Contributor

Close #26

  • Support OpenAI compatible chat API with and without streaming.
  • Support builtin and dynamic registered chat templates.

@comaniac
comaniac requested a review from merrymercy January 19, 2024 01:07
@merrymercy

Copy link
Copy Markdown
Collaborator

@comaniac

Copy link
Copy Markdown
Contributor Author

For the chat template, can we use the hugging face tokenizer by default? https://huggingface.co/docs/transformers/main/en/chat_templating#how-do-i-use-chat-templates

Good idea. Let me add this.

@comaniac

comaniac commented Jan 19, 2024 •

Copy link
Copy Markdown
Contributor Author

Now if --chat-template is not specified, we use the tokenizer build-in chat template. Thus, most users should not worry about the chat template for HF models. Meanwhile, I found that some tokenizers such as TinyLlama does not have chat template, so we will get the following when calling apply_chat_template(messages, tokenize=False, add_generation_prompt=True):

No chat template is defined for this tokenizer - using the default template for the LlamaTokenizerFast class. If the default is not appropriate for your model
, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information.

'<s>[INST] <<SYS>>\nYou are a helpful AI assistant\n<</SYS>>\n\nList 3 countries and their capitals. [/INST]'

And this template is actually incorrect for this model, so you will get the following response in the unit test:

 <<SYS>>
You are a helpful AI assistant
<</SYS>>

List 4 cities with more than 100,000 people. [/INST] <<SYS>>
You are a helpful AI assistant
<</SYS>>

List 5

The following response is expected with ChatML template:

Here are three countries and their capitals:

1. Canada - Ottawa
2. Australia - Canberra
3. South Korea - Seoul

Another issue is apply_chat_template doesn't provide stop strings, so the response may be undesired. For example, Llama-2 template should have stop string "[INST]", "[/INST]", "<<SYS>>", "<</SYS>>". In general, I would still suggest specify chat template explicitly, but maybe we could put this issue in the troubleshooting.

@@ -0,0 +1,381 @@
# Adapted from
# https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can consider importing instead of copying later.

Comment thread python/sglang/srt/server_args.py Resolved
@merrymercy
merrymercy merged commit 23471f9 into main Jan 19, 2024
@merrymercy
merrymercy deleted the cody/openai-chat branch January 19, 2024 07:43
timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
blzheng pushed a commit to blzheng/sglang that referenced this pull request Apr 11, 2025
NorthmanPKU pushed a commit to NorthmanPKU/sglang that referenced this pull request May 16, 2025
…roject#50)

* [Transpiler] Add config class and interface for the transpiler

* [Misc] Add a static checking for STensor::num_elements

* [Transpiler] Implement all kernel operators and their runtime

* Format code

* Add support for broadcast in ElemwiseBinaryKernel

* Refine Python interface for transpiler & Add layout resolve for DTensor

* Finish layout resolution for threadblock level ops

* Add basic support for threadblock level transpiling

* Merge Python JIT frontend (sgl-project#40). Add support for Python JIT frontend

* temp frontend

* bug fix

* bug fix

* frontend with output shapes/strides

* add jit demo

* Add checking for MIRAGE_ROOT

---------

Co-authored-by: Shengyu Liu <[email protected]>

* Add unit test for the transpiler

* Add document for the transpiler

* Add threadblock level matmul operator

* Add threadblock-level reduction op

* clang format

* nits

* Remove nonexist examples

* Merge from main

* Add tb scheduling & Add support for forloop accumulator

* Add support for tb operator fusion

* TB_FORLOOP_ACCUM_OP->TB_FORLOOP_ACCUM_NO_RED_OP

* Refine documents

* nits

* nits

* Add support for chunked copy and async copy

* fix Python JIT compilation errors

* [CUDA Transpiler] Fix Python JIT compilation errors (sgl-project#51)

* fix Python JIT compilation errors

* Remove __getattr__ from wrapper

---------

Co-authored-by: SpiritedAwayCN <[email protected]>

* checkpoint

* Bugfix in async copy

* Optimize matmul

* Add support for output chunked copy

* Python interface for creating threadblock graph

* rename python objects

* Optimize ClearAccumulatorKernel

* Add testcases for IO

* Optimize threadblock input ops

* support customized

* Small optimization

* Change memory alignment to 128B for dtensor and stensors

* bug fixes

* remove the Py prefix for tensor objects in Python

* fix typo

* fix typo

* Modify lib.h to adapt to PR sgl-project#53

* Bugfix in testcase

* Support in-register accumulation for matmul

* Rewrite tb scheduling

* Add support for advanced memory planning interface & algos

* Allocate software pipeline buffers in memory planner too

* Code formatting

* Fix test script

* Add doc for TB scheduling and memory planning

* Add doc for register-backed accumulator

* Refine tb elementwise binary operator for broadcast support

* Add test for tb elementwise binary operator with broadcast

* Fix a subtle bug in matmul

* Add some comments

* Refine TB input and output ops (do not rely on stride)

* Refine TB reduction kernel to avoid using stride

* nits

* Refine matmul operator: do not rely on stride

* Slightly reorganize procedure in Transpiler

* Change matmul perf args to align with tb matmul perf

* Rename a file

* Add support for swizzling (XOR and SHIFT) (has a bug)

* Add doc for swizzling

* Add a test for the SHIFT swizzling

* Fix issue (sgl-project#56)

* Format boolean variable as `true` and `false` for better readability

* nits

* nits

* Hotfix CuTe's bug

Ref: NVIDIA/cutlass#1766

* Bump Cutlass's version and remove the workaround in the last commit

* Remove debug info

* Update doc

* Bugfix

* [Transpiler] Add more Python examples for transpiler testing (sgl-project#57)

* bug fixes

* fix compile issue

* minor updates

---------

Co-authored-by: interestingLSY <[email protected]>
Co-authored-by: Chun'an Shi <[email protected]>
Co-authored-by: SpiritedAwayCN <[email protected]>
chunyuan-w added a commit to chunyuan-w/sglang that referenced this pull request May 28, 2025
chunyuan-w added a commit to chunyuan-w/sglang that referenced this pull request Jun 6, 2025
pi314ever added a commit to pi314ever/sglang that referenced this pull request Jun 21, 2025
* remove vllm as a dependency

revert registry

* Isort format

Signed-off-by: Daniel Huang <[email protected]>

* Fix isort

Signed-off-by: Daniel Huang <[email protected]>

* Fix skip vllm import logic

Signed-off-by: Daniel Huang <[email protected]>

* Fix more vllm imports

Signed-off-by: Daniel Huang <[email protected]>

* Update to a newer vllm-hpu-extension version that does not rely on vllm

Signed-off-by: Daniel Huang <[email protected]>

* Add ray dep

Signed-off-by: Daniel Huang <[email protected]>

* Add einops

Signed-off-by: Daniel Huang <[email protected]>

---------

Signed-off-by: Daniel Huang <[email protected]>
Co-authored-by: Yang Wang <[email protected]>
chunyuan-w added a commit to chunyuan-w/sglang that referenced this pull request Jun 25, 2025
blzheng pushed a commit to blzheng/sglang that referenced this pull request Jul 31, 2025
apinge referenced this pull request in apinge/sglang Dec 3, 2025
[Feature] [ROCM] Support Add & LayerNorm fused for Qwen3-VL VIT
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
…d ratchet

Completes the rank-consistency sync of 4a8332e (round 7 of the sgl-project#50
campaign). That commit synced the in-loop draft picks and the verify
results, but two decision points still ran per-rank argmax/topk/sample
unsynced:

* the step-0 pick assembled from the draft-extend-for-prefill output
  (first draft round after prefill), and
* the step-0 pick for the NEXT draft round computed from the
  draft-extend-for-decode output — this one runs EVERY decode iteration
  (the selected-row topk is owned by the worker, outside any cuda graph).

On heterogeneous GPUs under uneven TP a near-tie flip in either pick
feeds rank-divergent chain inputs into the next draft round and thereby
rank-divergent KV during target verify. Refactor the broadcast into
_broadcast_draft_picks (also covers draft_probs for the rejection-
sampling path, which feeds the accept decision) and call it at all
pick sites.

Tests (CPU, (local venv) sgl_kernel stub):
- test_draft_pick_rank_sync.py: helper semantics (broadcast list, src=0,
  world_size==1 no-op) + AST ratchet: every fast_topk/fast_sample/
  sample_draft_proposal/torch.argmax site in eagle_worker_v2.py must be
  followed by _broadcast_draft_picks in the same function. 3 passed;
  RED on the pre-fix stand (verified via stash roundtrip: collection
  error — helper absent; the two step-0 sites would be flagged).

GPU verification pending (coordinator): eager NEXTN run-to-run diff was
redefined by rounds 7c/7d as deterministic per-run-index state evolution,
so this commit is a correctness hardening for the rank-sync class, not
necessarily the Rest-B root cause.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
Locator for the redefined Rest B of the sgl-project#50 campaign (rounds 7b/7c/7d):
with NEXTN the eager pipeline is fully deterministic PER RUN INDEX (run1
always 1285 chars, run2 always 1309, run3 1333 — bit-exact across boots,
poison-clean pools), i.e. some process-persistent state OUTSIDE the pools
is mutated by every request and feeds the next request's math. Under CUDA
graphs the same evolution lives in static replay buffers and converges to
the degenerate 41-char attractor (Rest A) — one locator serves both.

SGLANG_SPEC_STATE_HASH=1: at the end of process_batch_result for every
batch that finished a request, walk all objects reachable from
scheduler.draft_worker / scheduler.tp_worker (sglang/torch.nn types,
containers; cycles and shared tensors deduped) and log one line per
tensor (sha256 of raw bytes, bf16/fp8/bool safe via uint8 views, chunked
device->host) and per plain int/float/bool attribute:

  SPEC_STATE_HASH tag=req_end_<N> rank=<r> path=<attr.path> kind=tensor
      shape=... dtype=... dev=... hash=<16hex>
  ... kind=scalar value=<repr>
framed by 'SPEC_STATE_HASH BEGIN/END tag=req_end_<N> rank=<r>' (END
carries entries/tensors/params_skipped/elapsed). Lines are path-sorted,
so diffing the tag=req_end_1 block against tag=req_end_2 lists exactly
the state that evolved between two identical requests.

nn.Parameter tensors (weights) are skipped; module buffers, graph-runner
static buffers, attn-backend state, pool tensors and cursors are all
covered. SGLANG_SPEC_STATE_HASH_MAX_MB=N fingerprints tensors above N
MiB from a strided sample instead of hashing fully (faster, still
change-sensitive). Default-off; the hook costs one env check per batch.

Tests (CPU): test_spec_state_hash.py — hash determinism + change
sensitivity (incl. bf16/bool/uint8, noncontiguous, sampled fingerprint),
nested/list/dict traversal, string/routine skip, exactly-one-hash-changes
on mutation, cycle+dedup safety, Parameter-skip/buffer-keep, foreign-type
leaf rule, finish-hook gating and dump counting: 11 passed. Spec suite:
159 passed / 2 pre-existing CUDA-env failures (identical on 4a8332e).
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
Root-cause candidate fix for Rest A of the sgl-project#50 campaign (degenerate
41-char attractor from run 2 on under cuda graphs; vanishes with
--disable-cuda-graph).

Replay input contract audit of EAGLEDraftExtendCudaGraphRunner.execute:
the captured graph always reads the FULL bs*num_tokens_per_bs token rows
(constant padded tree width), while a replay only rewrites [:num_tokens]
where num_tokens = accepted tokens of THIS iteration (1..draft_tokens,
varies). The partial-replay reset branch covered seq_lens, out_cache_loc,
positions, req_pool_indices, num_correct_drafts, num_accept_tokens and
extend_seq_lens — but NOT buffers.input_ids and NOT
buffers.hidden_states. Their tail rows therefore kept the PREVIOUS
replay's (i.e. potentially the previous REQUEST's) token ids and target
hidden states, and the graph fed them into every subsequent draft-extend
forward.

Coupling into the real rows: the tail rows are masked for attention and
never selected for logits, but the NEXTN/MTP draft layer is MoE — stale
tail tokens join expert routing, change per-expert group sizes and hence
grouped-GEMM tiling/split configs, which perturbs the REAL rows' logits
in the last bits. Greedy verify flips on near-ties (especially on
heterogeneous GPUs), so the token trajectory depends deterministically on
buffer history: cross-request contamination that converges to a
self-reproducing degenerate fixed point. Eager mode builds draft-extend
batches at the real token count without padded tails — exactly why the
attractor disappears with --disable-cuda-graph.

Fix: reset input_ids and hidden_states together with the other buffers in
the partial-replay branch (extracted into reset_replay_tail_buffers for
unit testing). Falsifier SGLANG_POISON_GRAPH_PAD=1 fills the tails with
loud junk (token 100 / hidden 1024.0) instead of zeros: if outputs differ
from a zero-fill boot, the tail->real-row coupling is proven; either fill
makes replays history-independent.

Tests (CPU): test_draft_extend_graph_tail_reset.py — reset is bitwise
residue-independent across different simulated previous-request contents,
the two previously-missed buffers are neutral after reset, poison mode is
loud but deterministic, hidden_states=None supported: 4 passed. RED on
the pre-fix stand (reset helper absent; the residue-independence and
neutral-tail assertions target exactly the missed buffers).

GPU verification (coordinator): NEXTN + radix off + overlap off + graphs
ON; expectation: run 1..N bit-identical and healthy lengths from run 1,
no 41-char attractor; SGLANG_POISON_GRAPH_PAD=1 boot for the coupling
proof.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
… wrappers

Round 8 follow-up of the sgl-project#50 campaign. The request-to-request hash diff
flagged the eager registry slot buffers (input_ids/positions/seq_lens/
out_cache_loc/req_pool_indices/mrope_positions) of the target prefill and
draft decode EagerRunners as changed between requests. Audit result:

* Eager NEVER pads: EagerRunner.load_batch passes padded_bs==raw_bs and
  padded_num_tokens==raw_num_tokens, reset_padding early-returns, and
  extract_buffer hands the forward [:raw] slices. The changed bytes are
  last-batch remnants beyond the active slice — dead by contract
  (KEEP_PAD/FOREACH_COPY carry an explicit 'tail is never read' proof
  obligation). The 37d0e53 fix class (stale padded rows entering an MoE
  forward) therefore does NOT structurally apply to the eager path; with
  graphs on, bs=1 pads to bucket 1, so the general decode/verify replays
  are tail-free too (verify input is constant full tree width).

* Instead of an unfounded 'fix', make the proof obligation empirically
  testable: SGLANG_POISON_GRAPH_PAD=1 now ALSO poisons, on every
  CudaGraphBufferRegistry.fill_from, each slot buffer beyond the current
  iteration's raw region (floats NaN, uint8 0xFF, ints 100) BEFORE the
  semantic pad reset (ZERO/FILL_SENTINEL windows are restored) and the
  head copy. A poisoned boot that produces different output than a clean
  boot proves a beyond-the-active-region reader and localizes it; a
  bit-identical run exonerates the stale-tail class wholesale — eager and
  graph mode alike.

* Hash-walker coverage hole closed: flashinfer/sgl_kernel wrapper objects
  were skipped as foreign modules, hiding their persistent plan/workspace
  buffers (partially rewritten per plan, read by every kernel run) from
  the dump. DEFAULT_TRAVERSE_PREFIXES now includes them.

Also documented from the round-8 dump itself: k/v_buffer dtype is
torch.uint8 => the repro boots with fp8 KV cache, so the round-7c poison
run was a FALSE PASS for every MHA-KV read path (gap fixed in a358834);
a poison re-run is required before stale-KV reads can be ruled out.

Tests (CPU): test_registry_pad_poison.py — fill contract pinned (eager
unpadded FOREACH_COPY keeps stale tail; padded semantic resets), poison
covers inactive regions while ZERO/FILL_SENTINEL windows win, poison is
bitwise history-independent, off-by-default is behavior-neutral: 5 passed.
test_spec_state_hash.py: flashinfer-like wrapper traversal: 12 passed.
model_executor suite: 75 passed (incl. pre-existing
test_cuda_graph_buffer_registry.py — no regression).
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
Round 10 (GPU): SGLANG_SPEC_RESET_PROBE=flashinfer FLATTENS the request-
ordinal output sequence (4/4 bit-identical, 1245 chars; wrapper_objs=12,
wrapper_tensors=62) — the carrier of the sgl-project#50 eager cross-request state
lives in the flashinfer-wrapper tensor family. Run 1 dropped from 1285 to
1245 because the probe also fires after the server WARMUP request (the
old 'reference run 1' was warmup-contaminated; warmup is request 0 of the
ordinal series).

Two follow-ups this commit enables:

* CONFOUND documented and controlled: in non-graph mode plan() stores
  _qo_indptr_buf/_paged_kv_indptr_buf/_paged_kv_indices_buf/_paged_kv_
  last_page_len_buf as REFERENCES to sglang-owned buffer slices
  (Tensor.to(device) is a no-op on the same device), so the unfiltered
  round-10 wipe also zeroed sglang backend buffers — kv_last_page_len is
  init-ones and NEVER refilled, so part of the flat/1245 result may be
  perturbation rather than pure stale-state wipe. The audited wrapper-
  OWNED cross-plan persistents are exactly: _float_workspace_buffer,
  _int_workspace_buffer, _pin_memory_int_workspace_buffer,
  _kv_lens_buffer (everything else run() consumes is re-derived or
  re-referenced by the same forward's plan()).

* SGLANG_SPEC_RESET_PROBE_FILTER: comma-separated fnmatch globs on the
  wrapper ATTRIBUTE name; only matching tensors are zeroed, and the probe
  log line now carries per-name zero counts (names=_int_workspace_
  buffer:12,...), so a ~2-3-boot binary search over the four owned
  persistents pins the single carrier tensor. The root fix then targets
  that tensor's plan()/run() contract — the probe remains a debug tool,
  not the fix.

Mechanism audit so far: every spec forward plans (all
mark_forward_metadata_ready sites plan immediately before marking; the
eager runner plans when unmarked), plan-list == run-list wrapper
dispatch (verify->prefill_wrappers_verify, extend->prefill_wrappers_
paged, decode->decode_wrappers). With plan() proven batch-pure, the
stale consumption must be a region run()/the kernel reads that the
current plan() did not (re)write inside one of the four persistents —
the filter bisection identifies which.

Tests (CPU): filter restricts the wipe (aliased-name protection) and the
log carries per-name counts; suite: 17 passed.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
…ject#50 root fix)

Root cause of the sgl-project#50 cross-request nondeterminism (NEXTN, greedy,
heterogeneous-GPU uneven TP), closing the round-6..11 evidence chain:

The fa2 split-KV attention path reads float-workspace regions the current
forward did not write. All flashinfer wrappers (target prefill/verify/
decode, draft, per-step spec backends) share one persistent
torch.empty workspace, so those reads return: on a fresh boot first-touch
zeros (fresh cudaMalloc pages — the de-facto contract the kernels were
validated against, which is why run 1 is bit-stable across boots), and
afterwards the PREVIOUS request's partials. The residue perturbs the next
request's logits in the last bits; greedy near-ties flip; outputs become a
pure function of the request ordinal (1285/1309/1333/... chars for an
identical prompt). Under cuda graphs the same mechanism converges to the
degenerate short-answer attractor. This explains every prior finding:
flush/scrub/poison-invariant (the workspace belongs to the wrappers, not
the pools/allocator), spec-path-only (spec multiplies attention forwards
sharing the workspace), warmup counts as request 0.

Proof (GPU rounds 10/11, coordinator): request-end zeroing of ALL wrapper
tensors flattens the ordinal sequence; the four-way bisection over the
wrapper-OWNED persistents shows zeroing exactly _float_workspace_buffer is
flat at the natural run-1 value (4x1285) while _int_workspace_buffer(+pin)
and _kv_lens_buffer wipes still advance. The 10a value 1245 was the
aliased-buffer confound (kv_last_page_len), as predicted.

Fix: restore the boot contract at request boundaries. Every flashinfer
float-workspace allocation (shared global, init_new_workspace-private,
dedicated full-CG prefill) registers in a WeakSet;
zero_flashinfer_workspaces() memsets them, and the scheduler calls it when
a request finishes — enqueued on the worker forward stream when one exists
(overlap scheduling: stream order lands the memset between forwards, never
inside one), lazily and only if the flashinfer backend module is loaded.
Cost: one ~384 MiB memset (~0.5 ms) per finished request. Within-request
residue remains, but is a deterministic function of the request itself.
Default ON; SGLANG_FLASHINFER_ZERO_WORKSPACE_PER_REQUEST=0 restores the
old behavior. The upstream fix (bounding the reads or zeroing the consumed
region in plan()) is filed with flashinfer; see the campaign report for
the issue text.

Tests (CPU): test_flashinfer_workspace_zeroing.py — miniature split-KV
merge simulation exhibits the read-beyond-write coupling (request B result
depends on request A residue; falsifier RED by construction without the
fix) and zero_flashinfer_workspaces() restores bitwise fresh-boot equality
plus ordinal-independence over 4 simulated requests; registry is weak (no
lifetime extension) and the zero call covers all registered buffers:
5 passed. Combined spec/model_executor/layers regression: 249 passed / 2
pre-existing CUDA-env failures.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
The EMA (k) axis has hysteresis, but the BS axis switched slots instantly on
any batch-size change, so a concurrency level oscillating across a slot
boundary (e.g. a 4-stream load flapping around a CUDA-graph bs edge) would
thrash graph swaps every decode step. A BS-slot switch now requires
bs_debounce (default 3, top-level config key, 1 = old instant behavior)
CONSECUTIVE decode steps routed to the new slot; returning to the active
slot resets the pending run. Verify feeds (on_verify_complete) read the
active slot without advancing the debounce and feed ITS EMA — the batch
actually ran with that slot's step count. The debounce state is a pure
function of the batch_size sequence, identical on all TP/DCP ranks, so
rank-determinism is preserved (no sgl-project#50-class divergence).

Tests: 7 new TestBsDebounce cases (flap suppression, consecutive-occupancy
switch, pending reset, debounce=1 passthrough, verify-feed isolation) in
test_adaptive_spec_params.py — 36 OK; test_frozen_mtp_adaptive_init.py 7 OK;
test_draft_pick_rank_sync.py 3 OK on CPU.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
G4 (M16/sgl-project#50 invariant, now enforced): AdaptiveController.init_states runs
assert_runtime_state_isolation() after building all runtime states — no
attention backend object and no flashinfer workspace buffer (data_ptr of
workspace_buffer / full_cg_prefill_workspace_buffer, hybrid prefill/decode
wrappers unwrapped) may be reachable from two different states. Sharing
within one state stays allowed (the registered static/initial state
legitimately aliases the process-global workspace across its own backends).
A state built without init_new_workspace=True now fails fast at init instead
of corrupting captured graphs at the first swap.

G5 (sgl-project#50 determinism ratchet): the EMA feed must be the rank-0-broadcast
accept count, never a local statistic. Three AST checks pin the chain:
eagle_sample broadcasts num_correct_drafts from src=0; the
on_verify_complete_cpu feed is exactly result.num_correct_drafts_per_req_cpu
derived elementwise from result.accept_lens.tolist(); and every
adaptive_controller.on_verify_complete call site in the speculative package
lives inside an on_verify_complete_cpu hook. Invariant documented on
AdaptiveController.on_verify_complete.

Tests (CPU): test_adaptive_spec_params.py 42 OK (6 new isolation cases),
test_draft_pick_rank_sync.py 6 OK (3 new ratchet cases),
test_frozen_mtp_adaptive_init.py 7 OK, test_spec_state_hash.py 17 OK,
test_draft_extend_graph_tail_reset.py 4 OK,
test_eagle_draft_cuda_graph_runner.py 3 OK; py_compile clean.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
…heck (G4 refinement)

GPU validation finding: the G4 isolation assert correctly fired on the very
first adaptive EAGLE boot — every built state's draft-extend backend aliases
the PROCESS-GLOBAL flashinfer workspace (DraftBackendFactory constructs it
without init_new_workspace), exactly like the registered static-path state
and every non-adaptive forward do. That aliasing is the documented status
quo (time-multiplexed, re-planned before each use, zero-state maintained by
zero_flashinfer_workspaces), not the M16/sgl-project#50 private-share corruption class,
and forcing a private workspace per state per draft-extend backend would
cost ~0.4GB x states per rank on an already tight rig.

Refinement: AdaptiveController tracks externally registered (static-path)
states; workspace pointers reachable from them form the process-global
family. Built states may alias THAT family (rank-0 info log). Any workspace
pointer shared between two states outside the baseline family, and any
shared backend object, remain hard RuntimeErrors.

Tests: 3 new cases (baseline alias allowed, private share still raises,
strict default without baseline) — test_adaptive_spec_params.py 45 OK,
test_frozen_mtp_adaptive_init.py 7 OK, test_draft_pick_rank_sync.py 6 OK.
Boot evidence: t75 boot_adaptive3.log (assert fired), next boot validates
the exemption.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
…um (sgl-project#93)

Add --speculative-adaptive-graph-memory {auto,resident,offload}. In offload
mode the per-k-state scratch buffers (private flashinfer float workspaces,
cuda-graph kv_indices/custom_mask) are tagged via torch_memory_saver so
inactive states hold no physical VRAM: pause(tag) unmaps their pages at
stable virtual addresses, resume(tag) remaps + zeroes them (the sgl-project#50 boot
contract; plan data is host-side and re-planned per forward). A k-swap is
sync -> pause(old) -> resume(new)+zero -> pointer swap, ms-scale at the
measured ~0.1/s swap rate.

Guarantees:
- states built largest-first and paused right after build (boot peak ~ one
  state); finalize_boot verifies free VRAM >= max-state footprint with all
  states paused => a swap can never OOM (no lazy growth).
- segment-isolation audit: every tagged buffer must lie in its own tag's
  build-window segment; only individually-noted MiB-scale never-freed
  allocations are tagged, so tags cannot share allocator segments.
- request-boundary workspace zeroing skips paused workspaces (their zero
  happens at resume).
- G4 data_ptr isolation assert unchanged: managed aliasing multiplexes
  physical pages under distinct virtual addresses, so unmanaged sharing
  stays exactly as fatal as before (docstring updated).
- resident mode is first-class and byte-identical to the previous behavior
  (sum-of-states reserve, ~us pointer swaps); auto resolves to offload only
  when CUDA + flashinfer + torch_memory_saver prerequisites hold.
- rank determinism: swap driven by the rank-invariant step decision;
  SGLANG_ADAPTIVE_ALIAS_VERIFY_RANK_SYNC=1 all-gathers (ordinal, steps)
  per swap as a stress check. SGLANG_ADAPTIVE_FORCE_SWAP_INTERVAL=N is a
  test-only knob cycling states every N verifies.

Launcher injects the torch_memory_saver LD_PRELOAD hook for offload even
without --enable-memory-saver (the hook is inert outside tagged regions).

CPU tests: existing adaptive suites green (46+7+6); GPU validation follows
in the T93 window.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
…ls + int workspaces (sgl-project#102)

Shrink the untagged per-state VRAM residue of adaptive offload states:

* Per-state CUDA-graph capture pools: every adaptive build captures into a
  private torch.cuda.graph_pool_handle() with the state's torch_memory_saver
  region active (same mechanism as TorchMemorySaver.cuda_graph), so
  capture-time allocations are unmapped with the state. Private per tag for
  the same cross-tag free-list-isolation reason as the sgl-project#93 per-tag MemPools.
* flashinfer wrapper int workspaces (8 MiB each; graph-mode wrappers exist
  per captured shape) are swapped for tagged, zero-on-resume buffers via the
  public reset_workspace_buffer API. Safe because flashinfer re-plans every
  forward (host state -> pinned -> device copy) and their boot contract is
  fresh-cudaMalloc zero pages (sgl-project#50).
* Reserve check now uses the measured pause-released bytes per state
  (mem_get_info delta) instead of the sum of noted tensors; per-state logs
  itemize scratch / int-ws / capture-pool bytes.
* Mode surface: 'offload' is now Stage 2; new 'offload-scratch' keeps the
  exact Stage-1 (sgl-project#93) behavior as a fallback knob; 'auto' degrades
  offload -> offload-scratch -> resident (Stage-2 prereqs: 'full' decode
  cuda-graph backend, no SGLANG_MEMORY_SAVER_CUDA_GRAPH).
* SGLANG_ADAPTIVE_CAPTURE_CPU_BACKUP=1: exact byte restoration of capture
  pools through host RAM (fallback falsifier knob).

Resident mode and the static path are untouched (all new behavior is gated
on an active Stage-2 build scope).

Tests: test_adaptive_graph_memory.py 44/44 (17 new: Stage-2 mode ladder,
per-tag pool routing, capture region reentrancy guard, measured-footprint
reserve check, capture-pool-only swap path, int-ws retagging); full CPU
unit/spec suite 242 passed. GPU validation to follow (T102).
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
…dwell, noise deadzone)

Fixes the k-controller flapping found 2026-07-22 (12 switches in 18 s =
40/min, median dwell 1.0 s, perfect 3<->2 alternation): the lifetime EMA
of (accept_len - 1) swings 0.93-1.80, wider than the 0.25 hysteresis band,
and no dwell guard existed.

- Decision signal: mean over a trailing window of per-round batch-average
  accept counts (window_size, default 16) instead of the lifetime EMA;
  ema_accept_len remains as observability gauge only.
- Minimum dwell between switches, counted in verify ROUNDS (min_dwell_rounds,
  default 64 ~ 2 s at bs=1), not wall time: rank-uniform per sgl-project#50 invariant.
- Noise-scaled deadzone: thresholds must be cleared by deadzone_sigma
  (default 1.0) standard errors of the window mean.
- Window cleared on every applied switch; decisions need a half-full window
  of data from the active rung.
- Stage-4 prep: RungMetrics EMA per rung of accept length and round wall
  time, attributed via the result's draft-token stride (steps kwarg through
  on_verify_complete_cpu). Observability only; wall clock never enters the
  rank-replicated step decision.
- Defaults active under --speculative-adaptive; config format backward
  compatible (new optional keys). Non-adaptive path unchanged.

Tests:
- Unit: 112 passed (spec adaptive suites incl. sgl-project#50 AST ratchets) plus 98
  passed in touched-interface suites (batch_result_processor, server_args).
- GPU tp3 uneven DCP, NEXTN + --speculative-adaptive, Qwen3.6-27B-FP8:
  flap rate 40/min (12 switches/18 s, median dwell 1.0 s) before ->
  0 switches across boot + 4 bench runs after (controller held k=3).
- Bench ctx=4096, 4 runs (nextn_ctrlfix): 122.12/120.93/99.16/114.93 tok/s,
  median 117.9 vs controls nextn_recheck 104.09/96.03, nextn_nocap
  99.06/118.65 -> non-regression. Note: run 1 had max_line_repeat=105
  (degenerate output), median carried by clean runs 2-4. Accept length
  3.0-3.5, verify steps/s 33.1-34.6 on control level.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
…and DFLASH rungs (forced schedule)

--speculative-cross-algorithm-force schedule:N switches the ACTIVE rung
every N verify rounds, at round boundaries only (after the previous
round's commit, before the next round's prepare_for_decode). The static
force=nextn|dflash stage-2 modes are byte-identical to before; the
stage-4 bandit will replace the fixed plan with a reward objective.

Key deviation from the design assumption "both drafts are stateless":
NEITHER draft is stateless in this topology. The NEXTN/MTP draft owns a
1-layer draft KV pool fed by its per-round draft-extend; the solo DFLASH
draft (no compact cache under solo placement) owns a pool fed with the
target's aux hidden states per round. Naive switching would leave a
permanent KV gap in the inactive draft for every token committed during
a foreign segment. Stage 3 therefore adds:

- DUAL HIDDEN CAPTURE (schedule mode only): the target stores the FINAL
  hidden states in logits_output.hidden_states (EAGLE convention, all
  EAGLE consumers untouched) AND the DFLASH aux concat in the new
  cross_aux_hidden_states field (LogitsProcessor + both graph runners'
  replay reconstruction). Both rungs' graph sets are captured in this
  one mode; the stage-2 aux-capture runtime toggle does not exist under
  schedule mode.
- PER-ROUND WARM-KEEPING of the inactive rung: during NEXTN rounds the
  DFLASH draft KV gets the verify block's aux hidden appended
  (prefix-valid, ~0.8 ms/round on rank 0); during DFLASH rounds the MTP
  draft-extend runs over the 16-wide verify block through a DEDICATED
  width-16 draft-extend CUDA graph (own extend backend, adaptive-ladder
  isolation pattern), writing MTP draft KV AND producing next-round
  draft seeds (~0.8 ms/round; the eager path blocked the CPU ~40 ms per
  round in the flashinfer plan and is kept only as fallback). Dual
  prefill runs BOTH rungs' draft-prefill paths off one target forward,
  so every request is born warm in both drafts.
- SWITCH MECHANICS: scheduler hook (update_running_batch, pre-prep)
  consults CrossAlgoWorker.maybe_switch_rung; a switch runs graph-memory
  ensure_active (DFLASH tag resumed/paused; NEXTN rung is the untagged
  resident baseline), swaps the target model runner's verify
  attn-backend/graph-runner/spec_algorithm pointers, atomically
  re-points the numeric spec-shape server args (audited runtime readers:
  DFLASH decode prep block size etc.; the algorithm STRING stays EAGLE
  so the FutureMap relay type is stable), and converts batch.spec_info
  between EagleDraftInput and DFlashDraftInputV2 (relay identity via
  future_indices; seeds relayed through the FutureMap by attaching them
  to every DFLASH round's draft input, so the first post-switch NEXTN
  round drafts at full k).
- Rank uniformity: the decision is a pure function of the executed
  verify-round counter (identical on all ranks; accept counts broadcast
  src=0 per sgl-project#50), so no decision broadcast is needed for the fixed plan.
  Documented in maybe_switch_rung; the stage-4 wall-clock objective will
  need rank-0-decides + broadcast (design 4c).
- FutureMap: per-field lazy extras bufs + None-tolerant stash (mixed
  bonus-only and full payloads under cross-algo).
- Mamba fix: the intermediate SSM/conv verify caches and req_to_token
  headroom are sized with max_speculative_num_draft_tokens (16 under the
  cross gate) instead of the boot shape's value (4) -- the step axis was
  OOB for every DFLASH verify (and latently for adaptive k5). Budget
  estimates updated accordingly.
- validate_dflash_request applies at ingest under schedule mode (any
  request may hit a DFLASH segment).

Tests (Qwen3.6-27B-FP8, tp3 uneven DCP, rig 5090+2x3080; bench =
xover_bench_nat.py AFTER the 2026-07-22 read1 fix, 4 runs/arm, ctx 4096,
fresh same-day controls):
- Unit: 597 passed (spec + server_args suites incl. 13 new cross-algo
  schedule tests: force parsing, switch cadence, shape-swap atomicity,
  spec_info conversion, FutureMap mixed-payload stash).
- (a) schedule:64 boots; switches logged on all 3 ranks at identical
  rounds; 4/4 bench runs complete, no hang/crash:
  111.02/90.69/120.80/88.41 tok/s, median 100.9; blended accept_length
  3.95-5.57 (NEXTN ~3.5 / DFLASH ~10 segments).
- (b) Controls, same boot day: force=nextn 95.36/82.62/85.85/85.60,
  median 85.7 (accept 3.1-3.6); force=dflash 79.80/68.07/116.72/119.13,
  median 98.3 (accept 3.3-5.8, content bimodality). schedule:64 median
  100.9 lies ABOVE both controls.
- (c) Quality gate schedule:16, greedy, 4 fixed prompts x 512 tokens:
  all 4 coherent (max_line_repeat 1/1/1/1, distinct-token ratio
  0.35-0.47, accept 3.3-3.8 at ~85 switches/1358 rounds); determinism
  probe 5x same prompt: 5 variants (GPU nondeterminism on the mixed-arch
  rig, first divergence at tokens 17/17/169/17), every variant coherent
  (rep=1, distinct 0.41-0.47) -- no switch-correlated break; post-switch
  accept (first 4 rounds after each switch vs segment steady state,
  rank-0 trace): NEXTN +0.5%, DFLASH -4.0% (~1.3 sigma at n=168) -- no
  systematic post-switch degradation.
- (d) Switch cost: ensure_active 31-35 ms (nextn->dflash, resume+zero of
  the 662 MiB rung tag) / 44 ms (dflash->nextn, quiesce+pause); total
  switch overhead ~1 verify round. Warm-keep steady cost 46-59 ms per
  64-round segment (~0.8 ms/round) in BOTH directions.
- (e) Regression flag OFF (original nextn arm, adaptive on): boots;
  bench ctx4096 89.11 tok/s, accept_length 3.26 -- inside the same-day
  nextn control band (82.6-95.4). Default path untouched.
- Clean teardown; GPUs at 3/3/3 MiB.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 23, 2026
…ator

QoS goal "device fast, spill best-effort". The spill tick runs INSTEAD of the
device decode batch on the iterations it fires (serial S1 path), so its cost is
one stolen device iteration per tick. Rather than a static cadence, drive the
minimum device-iterations-between-ticks with a rank-uniform control loop off
device demand:

- signal: DEVICE running decode-batch occupancy (len(running_batch.reqs)),
  sampled once per scheduler iteration in pre_schedule. Replicated scheduler
  state -> bit-identical on every DCP rank (the sgl-project#50 rank-uniform-scheduling
  invariant), so the cadence decision needs NO broadcast/communicator and every
  rank agrees on whether a tick fires (a spill tick is a rank-uniform collective
  event; disagreement would NCCL-hang). Wall-clock device RATE is deliberately
  NOT used (not rank-uniform).
- controller (SpillTickController): device under demand -> effective interval
  RISES (spill less often, protect device near no-spill baseline); device
  light/idle -> interval FALLS toward 1 (spilled session advances faster).
  Fast-lane pressure hard-pins to the adaptive max (fast > FCFS).
- anti-flap (mirrors the cross-algo k-controller bdc1714551): trailing window
  (16), min dwell in ITERATIONS not seconds (64, rank-uniform), noise-scaled
  sigma deadzone, one interval step per decision, bounds [1, max].

Gated: --kv-session-offload-tick-adaptive (default OFF -> the cadence gate reads
the STATIC --kv-session-offload-tick-interval, byte-identical). New
--kv-session-offload-tick-adaptive-max (default 8) bounds the interval. A
regulator tick is functionally the SAME spill tick; only its FREQUENCY changes,
so S5 machine-zero / determinism are untouched.

Tests (CPU): 62 passed in test_kv_session_offload_unit.py incl. 8 new
SpillTickController cases -- up/down characteristic, intermediate-demand
landing, dwell spacing, deadzone flap-suppression, stable-demand zero-flap,
fast-pressure pin, rank-uniform determinism (two instances, identical demand
seq -> bit-identical output at every step), bound clamping. server_args flag
parse + adaptive-max validation checked.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 26, 2026
MultiLayerEagleWorkerV2 ran a fixed draft length; the (upstream) adaptive
controller explicitly rejected it. Wire the controller into that worker.

Structural divergence from EAGLE that shapes the design: multi-layer EAGLE
runs ONE DRAFT MODEL PER CHAIN POSITION (tp_worker loads one ModelRunner per
step, each holding a different MTP layer), and it runs NO model at draft time
-- draft() only reshapes chain columns that the PREVIOUS round's draft-extend
produced. Two consequences:

1. k cannot grow past the number of loaded MTP layers, only select a prefix.
   Boot therefore loads max(candidate_steps) layers; --speculative-num-steps
   becomes the initial rung, consistent with EAGLE.
2. A k switch lands between rounds, so the first round at a new k sees carried
   columns of the OLD width. adapt_draft_columns() slices on downshift (exact:
   column i is MTP layer i's prediction for position i) and repeats the last
   column on upshift. Padding cannot break correctness -- the target verifies
   every draft token -- and it keeps the rung set on the diagonal, so no extra
   graph states and no eager rounds are needed. Under rejection sampling the
   padded token was really drawn from the duplicated q, so the Leviathan accept
   test stays exact.

Graph strategy is EAGLE's: one fully pre-captured composite draft-extend runner
plus one target decode graph per candidate k, built at boot, never re-captured
at runtime. SpecRuntimeState gains draft_extend_attn_backend_list so the M16/sgl-project#50
isolation guard walks the per-step backends -- without it rungs could silently
share them, which is the exact stale-buffer class that guard exists to catch.

The k decision stays a GROUP decision without any broadcast of its own: this
worker's verify() uses eagle_sample, whose accept counts are broadcast from
rank 0, and the policy layer is pure Python over rank-uniform inputs. The width
adaptation is deliberately unconditional, including on idle batches, so an idle
rank cannot draft at a different k than the rest of the group.

New default config MULTI_LAYER_EAGLE (bs1 [1,2,3], bs8 [1,2], bs32 [1]): no
step-0 rung (this worker has no nospec branch) and ceiling 3, which matches what
_auto_choose_speculative_params already picks for the multi-layer archs -- so
turning adaptive on costs zero extra draft weights at the default shape.
Selected via adaptive_algorithm_key(), so every resolver call site agrees.

Adaptive stays OFF by default; the static path is unchanged (every new sizing
term collapses to the old expression when adaptive_max_candidate_steps is None).

Design, rejected alternatives and the GPU recipe:
docs_new/multi_layer_eagle_adaptive_len.md

Tests (CPU, no GPU available this session):
- new test/registered/unit/spec/test_multi_layer_eagle_adaptive.py, 43 tests:
  config resolution and gates, adapt_draft_columns slice/pad/edge cases,
  per-step backend isolation, apply_runtime_state rebinds, _override_worker_state
  round-trip and exception restore, draft-runner count + MTP-layer guard,
  rank-replay uniformity of the k trajectory, graph-bucket pruning.
  RED before this change (import error; boot-constructor ratchet failed on the
  missing adaptive_controller), GREEN after.
- regression: unit/spec + server_args + planner + managers + model_executor +
  boot_constructor_integrity + model_overrides + cpu/test_spec_kernels.
  Failure set identical to the base commit (42 + 21 pre-existing environment
  failures: missing libnvrtc / deep_gemm, and the pre-existing
  test_decode_bookkeeping_ownership kv_session_offload allowlist drift).
  Zero regressions.

Not validated on GPU: no multi-layer EAGLE checkpoint (MiMoV2 / Step3p5) is in
the local model cache, so the path cannot be booted here. GPU A/B recipe and the
required checkpoint properties are in the design doc.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 26, 2026
…t picks (sgl-project#50 family)

MultiLayerEagleDraftWorker drew its chain picks per rank and never synced
them, unlike every pick site in eagle_worker_v2 (which routes them through
_broadcast_draft_picks, the sgl-project#50 fix against heterogeneous-GPU sampling
divergence). On mixed cards the per-rank logits differ in the last bits, so a
near-tie flips on one rank; the pick is then rotated into the NEXT MTP rung's
input_ids, so that rung's forward writes divergent KV and the TP group is
desynchronized for the rest of the sequence.

Three pick paths, all fixed, one sync per rung placed BEFORE the chain
rotation (not once per round -- the rotation is what makes a late sync
useless):
  - _draft_extend_for_prefill: per-step sample_draft_proposal / fast_topk
  - _draft_extend_for_decode, graph branch: the topk computed IN-graph and
    returned by cgr.replay(step) (plus the worker-side rejection-sampling
    re-pick)
  - _draft_extend_for_decode, eager branch: sample_draft_proposal / fast_topk

Entry condition is rank-uniform: both functions are called unconditionally
from forward_batch_generation's extend / decode branch, and both loop over
speculative_num_steps, which is rank-identical (the adaptive k decision is a
pure function of the rank-0-broadcast accept counts). world_size == 1 returns
before touching the group, so the non-TP path is byte-identical.

_broadcast_draft_picks moved from eagle_worker_v2.py to spec_utils.py (next
to capture_safe_tp_broadcast, which it wraps) and is re-imported under the
same name in both workers, so existing call sites, tests and the AST ratchet
are unchanged.

draft_forward's torch.topk over the carried columns is deliberately NOT
synced and now says so: multi-layer EAGLE runs no model at draft time, so
that is a deterministic re-ranking of already-broadcast columns, the same
position as organize_draft_results in eagle_worker_v2.

Tests (CPU, no GPU used):
  - test_multi_layer_eagle_draft_extend_decode.py: drives the real eager
    _draft_extend_for_decode twice with fake MTP rungs whose logits differ by
    a tie-breaking epsilon, replaying rank 0's broadcast payloads into rank 1.
    Pre-fix: 0 broadcasts, divergent chains. Post-fix: 6 payloads (2 tensors x
    3 rungs), identical picks AND identical chain rotations. A guard test
    asserts the fixture really diverges without the sync, plus a world_size-1
    test that fails if any collective runs.
  - test_draft_pick_rank_sync.py: AST ratchet extended to the multi-layer
    worker, stricter than the eagle one -- the sync must sit in the pick's OWN
    rung loop and before that loop's rotate_input_ids, so one broadcast at the
    end of a function cannot vacuously cover k rungs. Counts cgr.replay as a
    pick site since the graph does the topk in-graph.
    Pre-fix red on all 6 pick sites.
  - test/registered/unit/spec/ + test_boot_constructor_integrity.py:
    607 passed, 1 failed. The failure
    (test_decode_bookkeeping_ownership::test_bookkeeping_sites_match_owner_allowlist,
    kv_session_offload.try_spill) is pre-existing: it fails identically on the
    untouched base commit.

Open without hardware: no heterogeneous-GPU run. The multi-layer worker needs
a MiMo-V2 / Step-3.5 checkpoint, which is not in the local cache.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 27, 2026
…ive-len + pre-existing bugs into integration/r3-probe

feat/mleagle-adaptive-len is an ANCESTOR of fix/mleagle-preexisting-bugs, so
this single merge carries the ordered pair the plan asked for:
  a8af70e sgl-project#138 adaptive draft length for multi-layer EAGLE
  d29a13e sgl-project#185 rank-0-broadcast the multi-layer EAGLE draft picks (sgl-project#50 family)
  3fb8884 sgl-project#184 plan per-rung attention metadata in the eager draft extend

Semantic pre-check on the doubly-touched server_args.py: regions are disjoint.
The tip's hunks sit at 1562 (sgl-project#202 --rank-tp-ratio x --pp-size guard) and 5691
(sgl-project#197 GGUF dense vocab); this branch's sit at 9552-9583, introducing the
adaptive_max_candidate_steps cached_property and routing the existing
draft-buffer sizing through it. No shared symbol, no shared validation path.

No file overlap at all with merge 4 (fix/spec-upstream-followups): that branch
is eagle_utils.py / multi_layer_eagle_draft_extend_cuda_graph_runner.py, this
one is multi_layer_eagle_utils.py / multi_layer_eagle_worker_v2.py /
eagle_worker_v2.py / spec_utils.py.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 29, 2026
…urzel war doppelt: (1) RuntimeContext.get_buffer nur name-keyed (Lane bekam den 384-MiB-Serving-Workspace; Desk-Probe bewies beides ohne Boot), (2) zero_flashinfer_workspaces lane-unaware; Fix (lane,name)-keyed + per-Gruppe sgl-project#50-Kontrakt-Restore, +412 MiB auf der 5090 (Rezept traegt); Falsifikator ueber Lane-Output-Determinismus: bewaffnet nicht-reproduzierbar unter Last, gefixt byte-identisch ueber 2 Boots trotz >50% Last-Differenz; Gegenbeweis 3/3 Boots 0 Asserts (P2 29,200/29,200/29,197 tok/s); LaneShareMeter bleibt default-aus mit ZWEI NEUEN Gruenden (Scheduler-Kosten unvermessen, Rest-Differenz solo-vs-loaded unerklaert) — alter Grund beerdigt; Lane-Prefill-Chunking als Design §13.10
efschu added a commit to efschu/htsglang that referenced this pull request Aug 3, 2026
… correct the §1.3 model, and make the sgl-project#431 guard non-blocking

Two commits:

test(sgl-project#483,sgl-project#459): sgl-project#483 ("check_regressions prices prefill on stale rates")
is REFUTED -- check_regressions already prices on the RESOLVED rates
(landed with sgl-project#475). What was actually missing was the PIN: the only test
calling the function is checkpoint-gated and skips in every hermetic run,
so a revert would be invisible. test_check_regressions_pricing_483.py is
the hermetic falsifier. Also makes the s12 harness honest: an absent
measurement is None, never 0.0 (a spec-off tick has no accept length, and
0.0 silently survives every arithmetic it enters); and any procedural
property a verdict rests on (warm-up discarded, draws back-to-back, gap
between draws) is recorded as a measured number in the artifact, not taken
on the harness's word -- the s12 warm-up draw ran for months and was
discarded silently, so a warmed-up point and a cold one wrote the same
file.

perf(sgl-project#517): names the actual decode-loop BAR1 collectives and corrects the
catalog's round model -- a decode round is NOT free of host-path
collectives (the belief the old model rested on). Per NEXTN round there
are 3 replay boundaries (the draft chain is one captured graph, not one
per step) and 5 host-path BAR1 broadcasts, all sgl-project#50 speculative
rank-agreement syncs, reaching barlink because a barlink boot never
constructs pynccl. Measured cost: the sgl-project#431 blocking status-word read costs
-9.22% decode TPS against the same-tree NCCL baseline; removing it
recovers +2.68%. Fix: the abort-guard status word is now read
asynchronously (non-blocking D2H + cudaEventQuery, returning what an
earlier check staged), trading reporting LATENCY for zero stream
synchronization per check -- detection is unaffected because ctlStatus is
sticky. SGLANG_BARLINK_BAR1_ABORT_MAX_LAG (default 4) bounds the
deferral with a can-fail proof; ..._ABORT_DEFER=0 restores the exact
pre-sgl-project#517 blocking behavior. NOTE_517_bar1_guard_desk.md has the full
model, desk-only (no GPU arm run yet -- ticketed).

Two real conflicts, both resolved by combining rather than choosing a
side:
- FEATURE_CATALOG.md §12 (same insertion-point pattern as every merge
  today): HEAD's "Verified carve-outs (sgl-project#514)" paragraph kept, this
  branch's two sgl-project#459 paragraphs ("absent measurement is None" /
  "procedural property must be in the artifact") appended after. Two
  OTHER hunks (the sgl-project#483-REFUTED note near §2, the "Guard cost" note near
  §7) landed with no conflict at all -- neither region had been touched
  since this branch's base.
- test/registered/unit/distributed/_bar1_marker_source.py: both HEAD (via
  sgl-project#514's earlier edits) and this branch carry DIFFERENT LINE_* pins into
  barlink.py/barlink_bar1.py, because each was written against its own
  version of those files. Neither side's numbers are correct once both
  sets of source edits are combined. Resolved by reading the ACTUAL
  post-merge source: grepped the real logger.info/logger.warning/raise
  RuntimeError call-start lines in the merged barlink.py and
  barlink_bar1.py (2236/2250/3207/810) and verified all four renderers
  execute correctly against them before committing -- not a textual
  merge of the two guesses.

All 17 catalog sections and every other additive paragraph verified
present.

Tests (CUDA_VISIBLE_DEVICES=99, PYTHONPATH pinned to this worktree):
- The five directly touched/new test files (_bar1_marker_source.py's
  renderers verified live against the real merged source, plus
  test_barlink_bar1_abort_431.py, test_barlink_bar1_abort_deferred_517.py,
  test_s12_harness_459.py, test_check_regressions_pricing_483.py): 67 + 7
  passed, 0 failed.
- test_s12_log_analyse.py specifically (s12_log_analyse.py is touched):
  same 4 pre-existing failures, unchanged (fixture-data-dependent, not
  source-code-dependent).
- test/registered/unit/distributed/ (full): 24 failed, 2206 passed,
  8 skipped, 723 subtests -- same 24 failing IDs as the established
  baseline, byte-identical.
- ruff check --select=F401,F821,UP037: clean.
- codespell: 7 hits, all confirmed pre-existing (a German prose sample
  string already in scripts/gpu_battery/s12_prefill_kurve.py and
  s14_decode_punkt.py at this branch's base, untouched by its diff).
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 8, 2026
…ated FINISH-TRACE

Two divergence specimens narrowed the family injury to divergent
FINISH_MATCHED_TOKEN decisions (specimen 1: rank 0 drops early; specimen
2: ranks 1+2 drop and rank 0 misses the match — rank 0 odd both times,
refuting a 5090-vs-3080 arch split). The on-device accept path is rank-0
broadcast (sgl-project#50/#616c fused), so the divergent input is CPU-side or
temperature-dependent; the greedy A/B arm is running.

- filter_batch drop tags now carry the matched token/str and output_ids
  length: the diverging VALUE lands in the sentinel dump itself.
- SGLANG_FINISH_TRACE=1 logs one line per finish transition (rid, reason,
  matched, accept window len, output tail) so the three ranks' lines for
  the same rid diff to show WHICH finish input diverged.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 8, 2026
…rst-token divergence root

ROOT. Upstream's base sampler skips the cross-rank token-id sync by default
(_sync_token_ids_across_tp, opt-in env), resting on "the last all-reduce,
the last lm_head matmul, and all sampling kernels" being cross-rank
deterministic. On this fork that assumption is violated three ways at once:
mixed GPU architectures (5090+3080: near-tie argmax flips), uneven-TP shard
geometry (per-rank reduction order -> per-rank logit bits even between
same-arch ranks), and per-rank sampling RNG at temperature > 0. The verify
accepts (sgl-project#50) and draft picks (sgl-project#185) already have rank-0 broadcasts; the
base sampler — which produces exactly the FIRST token of every request —
did not.

PROOF (crash farm, 2026-08-08, /spinning/622-farm rounds 0523..0548). Six
lockstep-sentinel divergence specimens: ranks read DIFFERENT first-token
values for the same request, always surfacing at output length 1 with a
genuine EOS id (248046, generation_config eos [248046, 248044], vocab
248320) on exactly one side — the only single-token flip that changes batch
membership. Membership divergence (bs N vs N-1) then yields divergent
graph-tier selection and the group wedges when the tiers' barlink round
counts differ — tens of thousands of replays after the injury, which is the
sgl-project#622 replay-abort signature. Axes: reproduced under barlink AND NCCL
(transport-independent, n=2 each), at temperature 0.7 AND 0.0 (greedy does
not suppress), MTTD 60-180 s under amplified load. Falsifier arm:
SYNC_TOKEN_IDS_ACROSS_TP=1 on the unfixed tree ran ≥30 min clean under the
same load (≥10x baseline MTTD).

Explains sgl-project#649's shape (bs-divergent verify -> DCP owner bool-mask sync at
owner.py:566 parks before the group collective) and plausibly sgl-project#634 (same
wait-for-peer abort at an eager host-path all_reduce); both confirmed only
by their absence in the acceptance soak. NOT explained: the sub-op
flag-level wedge with chain-identical rings (specimen 20260808T052850Z) —
stays open as a separate defect.

DESIGN DECISION. Sync is ON by default for every tp>1 group, not only
mixed-arch groups: the farm's odd rank was NOT arch-predicted (rank 0 odd
twice against an agreeing 5090+3080 pair; an arch split would isolate
rank 1), i.e. uneven-TP reduction order breaks the determinism assumption
even between same-arch ranks, so an arch-gated default would leave the
proven injury reachable. Opt-out: SGLANG_SYNC_SAMPLED_TOKENS=0 (the legacy
opt-in MIN-allreduce and the grammar-forced sync are preserved under
opt-out). Mechanism: rank-0 broadcast via capture_safe_tp_broadcast — the
established hetero pattern (sgl-project#50/sgl-project#185), authoritative sample semantics
(rank 0's true distribution, unlike the MIN-allreduce), works under barlink
(coordinator dispatch; census/sentinel-visible) and pynccl, capture-safe.

COST. One bs-sized int broadcast per base-sampler call (extend/prefill
under spec_v2; spec decode rounds use the verify broadcast and are
unaffected). Priced via CollectiveClock in the acceptance soak
(ms/round compute-vs-wait per rank), reference: pre-fix farm prefill lines.

Falsifier-first test: test/registered/unit/distributed/
test_sampler_token_sync_622.py — red on the unfixed tree (default path
leaves an injected rank-2 EOS flip divergent / fix function absent), green
on the fixed one (all ranks end with rank 0's tokens), over 3 real gloo
processes.
fan-wenjie added a commit to fan-wenjie/sglang that referenced this pull request Aug 23, 2026
sgl-project#50 asked to wire the unified read/update interface into the span and the protocol. Nothing in the
runtime calls it, and wiring it in would UNDO the split: the pool forms the query coefficient
itself, asks for one reading, and defers the advance, which is what lets a caller carry on without
waiting for its own state to be written.

It stays because the cases around it pin the recurrence against the reference step, and a
reference implementation exercised by tests is not dead code. But its docstring claimed to be 'the
host's whole job' long after it stopped being one, which is how a task to wire it in came to
exist.
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 20, 2026
…kend, not a real one

fnFA24 (20.09. 21:30Z): with --speculative-adaptive on Form A (host,worker,worker;
draft solo on the host) TP1/TP2 died at boot -- build_adaptive_runtime_state
called target_model_runner._get_attention_backend(init_new_workspace=True) on
a rank whose kv-head share is 0, and flashinfer's should_use_tensor_core divides
by it (ZeroDivisionError). The static path never builds a real backend on a
worker (model_runner.init_attention_backend -> FormAWorkerAttnBackend, fnFA7).
adaptive_target_attn_backend() now hands a worker state a fresh
FormAWorkerAttnBackend (one object per state, so the M16/sgl-project#50 isolation check
sees no shared backend) and every other rank the private-workspace backend as
before, restoring init_new_workspace either way.

Tests: test_adaptive_form_a_worker_0920 (3) + adaptive spec files 113 passed;
tests/moe_offload 43 failed = baseline (comm -13 empty).
yangxin-mx pushed a commit to MetaX-MACA/sglang that referenced this pull request Dec 2, 2026
将 mx/dev-0.5.19 中与 GLM5Next 相关的迁移及必要修复合并到一个提交,
基于 mx/dev-0.5.21 的 9b491a645e,保留 target 新 CP/API 架构。
按原迁移表顺序核对62条:35条迁移/适配/必要依赖,27条已有覆盖或按表跳过。

迁移/适配明细(编号为原表序号;Source 为真实 source commit):

- #1 Source: 90fc47afb93b52ee2e17db94ff81c70ca355c510
  内容:为 DSA/MHA 分支补 idle 守卫,避免 DP idle batch 误入 MHA 路径。

- #7 Source: ede708204940def467c753ab97f22b098104c8d8
  内容:移植 prefill attention 的 FA2 在线 softmax 归一化和 MACA 非因果128x32调度;按实测
    将大 head_dim 的 MACA tile 缩为32x32,保留非MACA调度。

- #8 Source: 251667008296ead929e477c3d31acfcaaea3822d
  内容:MACA 非因果 attention 的 num_stages 从2降为1,与 FA2 tile 调度配套,降低共享内存需
    求。

- #9 Source: 04827865d580a1bb9b64815fab861e03f2eb2666
  内容:迁移 Hadamard/INT8 GEMM 自定义算子注册;修正 fake out_shape、C 写入声明及 Optional
    bias,保留平台守卫。

- #13 Source: f9d0b9622970734bba00fd3a44aff1a0394bb060
  内容:为 GLM5Next CUDA/XPU 路径补默认模型 dtype;使用 target config view 读取 hf_config
    ,保留用户显式 dtype。

- sgl-project#26 Source: 8a6ae864a3cebad6e272fd2541459a8510eb12f4
  内容:补齐 INT8 MQA 的 triton/tilelang/maca_c 后端选择器及校验,接入 paged、ragged、
    chunked prefill 和 CP 调用;补 GEMM_BF16 开关。

- sgl-project#27 Source: 7b58f8233d38e5469ae211cbf1176e4721817c47
  内容:迁移 W8A8 fused RMSNorm tuple 输入兼容,按 tuple 首项区分旧元数据;保留三维输入支
    持及 MQA 后端校验。

- sgl-project#28 Source: 74505cf936776c09f0786d4b301e1467b031a3d6
  内容:修正 MLA/q_lora 的 fused tuple 元数据识别,补 BF16 passthrough 解包,避免 tuple 进
    入 Tensor 投影路径。

- sgl-project#30 Source: 150bc2fdd022abf7684fc848043f2f0c7d4d45da
  内容:适配 GLM5Next W8A8 ignore mapper 与主模型/vision/NextN prefix;移植 KDA CP×
    attention-TP head 分片和 Mooncake 状态范围/stride/PP-layer 映射。修复新版 KPool
    full-key/local-query 接线、padding、FP8 dtype 及未初始化变量,保留复制状态 CP0 去重。

- sgl-project#31 Source: daf920081d8f65ca1925ccbefc39b6708fcdae02
  内容:迁移 GLM5Next/NextN fused RMSNorm、packed quant 与 mHC input 守卫;packed mHC 无
    residual 时补零并保留返回契约。

- sgl-project#32 Source: 3b81f1f4bc7ae595076ac31c777838ceaa14fc65
  内容:迁移 C500/C550 SplitKV、MACA smem 调度、mcoplib DSA/KDA、CPU token count、ln/log2
    转换、grouped_topk/fake 与 varlen SiLU;适配新增 track_state/inplace_update,修复
    SplitKV 三参数调用兼容。

- sgl-project#33 Source: e24ab0bb93eac50f134466c309b18a76108e8efb
  内容:迁移 FP8 fused norm/activation quant;修复 column_major_scales 传递与 TMA 对齐守卫
    、MLP 融合资格门控和 FP8 consumer tuple 选择,保留目标回退。

- sgl-project#35 Source: 126685db6e84f81eb337df29a06ae47efcb4ab0c
  内容:核验 KPool mcoplib 特性使用模块级 torch 导入,不引入 source 的局部 import 作用域错
    误。

- sgl-project#37 Source: c47a8a23daa1e5779a81ca5172021e582450f7f6
  内容:迁移 logits 显存预算刷新和 empty_cache;补 CUDA graph capture 守卫,避免捕获期间执
    行主机同步/缓存清理,保留 HIP 上限。

- sgl-project#38 Source: 891b2eda664e3a4dbae0f81ffa028087caf0be29
  内容:迁移 mcoplib AOT KPool 路径到 target kernels 目录,完整保留参数;用 EnvBool 处理开
    关,避免值0仍启用。

- sgl-project#39 Source: 9e74fa0504e402507671b703ec6e365728ee3f41
  内容:迁移 MTP metadata glue/seed merge,缺失行补零;保留 DSA/KPool/page/topk 等资格限制
    、静态图输入、eager fallback 及 target future_indices 接口。

- sgl-project#40 Source: 049fc02d18940d4c021281b1b54d4843b3ea0d57
  内容:迁移 MoE sum-add 从 shared_output 到 dispatch/runner/kernel 的接线及 INT8
    quant-once;保留 EP/TP/LoRA/no_combine/graph 回退,修正 shared_experts 属性守卫。

- sgl-project#41 Source: 8f5580f02634c1e6536e6925559f8a2a8f7b9b75
  内容:迁移 KDA BF16 投影融合资格、local N 对齐、加载后 padding 清零及 forward slice;初
    始化非融合分支属性,避免权重加载崩溃。

- sgl-project#43 Source: 1297d124af95d1df6f8c28ee20ee8b7c40177a26
  内容:迁移 optimized FP8 KV QDQ 及 STORE 开关;对 INT8、NoPE、非标准行宽和 rope=None 保
    留通用算子回退,避免全局别名误路由。

- sgl-project#45 Source: b48329742ca890d6d00692d4ea03160db56b661e
  内容:补齐 ragged/prefix-hit selected dequant:新增 GPU mark_selected_kv_rows 和 helper
    ;非法索引置-1,保持静态 shape、row mask、INT8/FP8 支持且无 host sync。

- sgl-project#46 Source: 033598e00ca324e084cdff89a4107f4d3e8e009e
  内容:迁移 TileLang FP8 KV 的 selected-dequant→BF16-kernel 路径,以 pool dtype 判断并保
    留 INT8/TopK 对齐;补显式 MACA FP8 反量化参数例外,保留 NVIDIA/HIP/sink 限制。

- sgl-project#47 Source: 78d6a6d53bf52d938bea469f658be8c561addc6b
  内容:补齐 optimized QDQ 必需的 NoPE 依赖:rope=None/空 rope、528B/656B 行宽派生及
    DIM_ROPE 条件;保留 INT8/其他布局通用回退。

- sgl-project#49 Source: bcca3bc2a68e0e7fab28f826652d14be0118ffd7
  内容:补迁 MX_USE_INDEXER_LOGITS_OPT(默认True)及 MACA FP8 logits 的 maca_c/triton 路由
    ,覆盖 paged、ragged、chunked prefill/CP,保留 INT8 和非MACA行为。

- sgl-project#50 Source: e15a1dd543c0d724b5af3221bde8465d95dfacf1
  内容:迁移 alt-stream 开关、MLA norm consumer 门控和 BF16 passthrough;补齐
    _weights_proj/x_for_gate 旁路,避免多余 FP8 反量化。

- sgl-project#51 Source: 24824a0a86f8e0036ea770377a4a4068b9dbf23e
  内容:按原表移植上游5733bcaad32的 HiCache host-pool 声明,保留 target
    StackStrategy/unified 扩展;补实际 index buffer dtype/宽度探测,修正 BF16 元素/字节
    stride。

- sgl-project#52 Source: caa3b73f5fbd061f19db5d01b422fe727299413e
  内容:迁移 hybrid KV+INDEXER+MAMBA host 栈、owned-layer/PP stage-local 映射、packed draft/sidecar 登记和声明覆盖校验,适配 target controller API。

- sgl-project#53 Source: 69b77095f7141e60070bfe7e53180ab82163574c
  内容:迁移六个 C500 KDA/conv kernel 及包装器;对 target 新
    track_state/inplace_update/beta 语义设置资格守卫与回退,保留 mcoplib 互斥。

- sgl-project#54 Source: 30bedf83aaa4c7127a6caa454cc859bf14d7805e
  内容:迁移 request-shared selected dequant;修正同请求所有 query 共用相同槽的假设,相同
    槽复用、不同 KPool tail 保留独立行,以静态容量/row mask 保证正确性。

- sgl-project#55 Source: eaf4cf1ab6e050e57b1601ba9c81b83ddaede089
  内容:延迟导入 KDA,仅在 Kimi 非NPU或 GLM5Next 路径加载,保留 Ascend 及其他
    linear-attention 后端。

- sgl-project#56 Source: 3687cf0cca0dcb84e031b3ab9565eb71eacaa6c0
  内容:抽出 C500 KDA 轻量配置和延迟导入开关;配套 optional-import 验证材料独立保存在仓库外。

- sgl-project#57 Source: fc708361eee03357f665bc09836a5477d218e2e8
  内容:迁移 mcoplib per_token_cast AOT 注册和 MLP SiLU 列主序 FP8 scale;与#33合并修复列
    主序/TMA 守卫,保留动态/融合/UE8M0 回退。

- sgl-project#58 Source: 9a8d3013dbfce88b219661d8798c7486a8a03a3a
  内容:迁移 MACA 3.10 的 FP8-MMA 能力判定(sm87/88/89 与80/86区分);非原生设备使用
    selected dequant 并补齐 page64,限制在 MACA FlashMLA 路径。

- sgl-project#59 Source: 49b8de76fbdc929bda5c03869c29bdfe37f97cdc
  内容:补迁 config-driven W4A8 QuaRot:主干末端/NextN shared_head 先完成 residual stream
    归约与清理,再 rotation→norm;登记两套 NextN rotation 权重,复用已有算子。

- sgl-project#61 Source: 039732e9a01ad42eba7c04c06c731d344708da1d
  内容:迁移 masked SiLU FP8 mcoplib 算子、FP32 scales 和列主序选项;保留特殊 activation、
    UE8M0 及目标 JIT 回退。

- sgl-project#62 Source: cada5f0f72e860376168544b3ce33ea660317147
  内容:迁移两个 GLM/KPool alt-stream kill-switch;旧 draft handoff wait 已无落点,保留
    target verify plan-stream 的正确性等待,不删除有效同步。

已核验但不重复迁移的条目(不计为新增移植):

- #2 Source: 22cf8d913ac1483bf6fa4b422b4a324b8aacc27a
  处理:target 已有 INT8/FP8/BF16 index cache dtype 配置、存储映射和环境变量,不重复移植。

- #3 Source: 24fd61059835d20f9e0dcd9d1a1cd454c76fe726
  处理:target 新 CP 的 world_group 广播统一解包已覆盖旧 scheduler 修复。

- #4 Source: 18771c6405169ba6a7d0b25f28c467bb47b1321b
  处理:target 通过 extend_seq_lens/input_ids 构建 CP metadata,不恢复旧 global
    token-count 逻辑。

- #5 Source: 2a209dffdd6d19466fb01428c541ab5fff513576
  处理:保留 target GDN chunk-H num_stages 默认2;C550 部署脚本设置为1,避免共享内存超限。

- #6 Source: c54a1a09ebe3f6e025f665a22e1ab6a78053bc05
  处理:target 已有 DSA update_verify_buffers_to_fill_after_draft 钩子。

- #10 Source: 68bfa76e0edbaf39b095e4271ba5d92faa2fe0e7
  处理:target 已有正规 MACA/mcoplib AOT 注册,跳过 source 的临时 sampling 导入注释。

- #11 Source: 385411126ba4a03c28a4c543184374b817fa5bc9
  处理:原表禁止迁移的 bring-up hack 不迁入;保留真实量化、layernorm 和正规 MACA 支持。

- #12 Source: 19061bd747bdb716f750b7fcf293decc915a30bf
  处理:target 已重放 W8A8/KPool dtype 及模型 prefix 基础支持;后续 mapper 兼容修复计入sgl-project#30
    。

- #14 Source: 6e5cf1875bbba5f7bc37118a990f6d60a9ab6146
  处理:target 已有 GLM5.3 主模型/NextN 架构识别、层名与 prefix 适配。

- #15 Source: bb18010c11efdc38c52f14030d1bdd3a11e5592f
  处理:target 已有 INT8 ragged KPool logits 和 dtype 分派,保留新版 CP 实现。

- #16 Source: 0bbba0f8d9261f83f56e901b67be5a0fa9906aa9
  处理:target 已覆盖 MACA head_tile=16 及 INT8/FP8 CP/paged/ragged 分派。

- sgl-project#17 Source: 3ff8eca05fb3830e3fafa7c49ae9a63c03b1dd49
  处理:target 已完成相关 API 重构、KPool dtype 修复与 grouped_topk fallback,不迁回旧接口
    。

- sgl-project#18 Source: 97bac43d8cb9f21f660ea8eb89f5a63edbe597c4
  处理:target 已直接读取 enable_dp_lm_head,消除旧 get_parallel().config 访问。

- sgl-project#19 Source: d5833f123353343c2204d8c0f9953859906c2392
  处理:target 已有 mamba_chunk_size 懒读取,并去除重复 initial_state_indices 参数。

- sgl-project#20 Source: a59e91e76a4207566de6ecf4594de1139364e920
  处理:按原表明确不迁移图像预处理提交;本次 CP 多模态边界修复独立列在适配说明中。

- sgl-project#21 Source: ec70e92a479ea8f1f2ce4bfc32c7f31bf045fd5a
  处理:target 已有 norm_weight=None 时的 mhc_pre_vllm 回退。

- sgl-project#22 Source: 4deb87b34229438f0382687e2ed22f6f8c875227
  处理:target 已覆盖 layernorm AOT bytes、残差别名和 fake 注册,保留其 MACA metadata 守卫
    。

- sgl-project#23 Source: 5feccf7f43420e3db9c40599b8eabc7fed3f0e38
  处理:target W8A8 已支持三维 VLM 输入展平及输出形状恢复。

- sgl-project#24 Source: fb8a2c30228735ce68ba8a90feaefddddad96ee0
  处理:target 已有 INT8 KV 量化/反量化、packed layout、memory pool 及 rope0/64 全栈支持。

- sgl-project#25 Source: 705896cb9e098ecf4778b5d5d2850a9e5e7442fe
  处理:保留 target 更精细的 MACA flashmla_kv 默认选择及 GLM5.3 INT8 例外。

- sgl-project#29 Source: b2bc0c0a198bd7b4eaac14b1d3071a305986f0ac
  处理:target 已有 INT8 属性保护,旧 mamba_branching_seqlen 清理落点已删除。

- sgl-project#34 Source: e9ce0de76ecacb6c3d867b90f9bf1120d2c3d974
  处理:target 不再向只读 logical_size/logical_page_size 赋值,已覆盖 source 修复。

- sgl-project#36 Source: 9e2d4fa7b9657dc8c5bb24e0bfbd302456885d10
  处理:target 已在访问 dtype 前判断 tuple,覆盖 FP8 MoE 崩溃;原表 full hash 有误,本列表
    使用唯一前缀解析后的真实 source commit。

- sgl-project#42 Source: a1a845df4b8f281b243d542ab39b46e754463cc2
  处理:保留 target 新 CP/prefix-cache 框架,不恢复旧 CP-V2/radix bypass;缺口随#30修复并
    验证前缀命中。

- sgl-project#44 Source: 2b20e9a0312dadc751b14ffe4bba7736750bd5b1
  处理:target 新 CP 仅在 context-parallel extend 生效,verify/draft 不进入 CP;保留现有
    padding 框架。

- sgl-project#48 Source: 18b3a7260ed85c95c1a6be87f652b7f89a75c91b
  处理:target 已由 hybrid_kda_config 和 cache_params.is_kda 覆盖模型识别、state
    ring/intermediate_ssm,保留 ReplaySSM。

- sgl-project#60 Source: 7c37c8ed18e9cea67e4a3f7eb564571226d0583b
  处理:target 已重放 GLM5.3 INT8 架构、528B/rope0/64、ragged/paged 和 selected-dequant 支
    持,保留新 metadata/HiCache 接口。

0.5.21 接口适配补充:
- 补 GLM prepare_cp_inputs:CP分片前复用完整多模态embedding,
  runner使用hook返回的positions并保留kwargs,后续PP stage消费proxy。

Change-Id: I5bda468525cc09d9f74598fcdd69d07764b6ecf3
Liwansi pushed a commit to Liwansi/sglang_vans that referenced this pull request Dec 3, 2026
…oject#50)

* Add the DeepGEMM-Ascend MegaMoE Prefill provider

* docs: specify the static expert layout for the MegaMoE prefill benchmark

* Add reproducible Ascend 950 Prefill benchmarks

* Simplify the Prefill benchmark launcher

* Keep only active Prefill preset settings

* Adapt the CANN 9.3.0 kit to the real eight-card run

- aclnnGemmSyrkGetWorkspaceSize grew an int8_t cubeMathType argument
  between 9.3.0-beta.1 and the 9.3.0 release; apply the call-site
  adaptation to the DeepGEMM worktree as cann93-release-syrk.patch.
- Record the patched-file digests in their Linux line-ending view and
  cover csrc/apis/aclnn.hpp as well; the previous digests were taken
  from a CRLF checkout and never matched a Linux prepare.
- Prebuild the cann_ops_transformer ops and the triton Ascend
  npu_utils host extension during prepare with the default toolchain
  headers: their g++-13 -std=c++20 builds fail at runtime against the
  GCC 11 include path kept for the device JIT.

* Make the eight-card release run pass end to end

Validated on 141.61.45.121, CANN 9.3.0 release, 8 x Ascend950DT:
offline 4096 finished=80, new_tokens=327680, measured_steps=10.

- Drop CPLUS_INCLUDE_PATH from the run-time vendor environment: the
  device JIT has not needed the GCC 11 headers on the 9.3.0 release,
  while they break the cann_ops_transformer ops and the triton Ascend
  npu_utils host builds (g++-13 -std=c++20). Opt back in with
  DEVICE_JIT_GCC11=1.
- Prepend the pip site-packages in vendor_env so the pinned pip
  cannbot-dsl 0.8.0 (tensor.reinterpret) shadows the cannbotdsl bundled
  with the host CANN release.
- Extend the adapter's mHC runtime gate to the 9.3.0 release after
  extraction; the beta.1 pilot kernel runs on it.
- Add run_all.sh: one-click offline tiers and the native vs DeepGEMM
  serve comparison with readiness polling and short smoke mode.

* Invoke check_idle.py through python3 in run_all.sh

* Fix clean CANN 9.3 release preparation and default benchmark launch

* Fix the serve arm on the 9.3.0 release host

- runtime_libraries preloads the system libstdc++: the hcc toolchain
  dir first in LD_LIBRARY_PATH shadows it with a build missing the
  GLIBCXX_3.4.29 futex symbols, and mooncake (the default PD transfer
  backend) fails to import in the serve arm.
- run_all.sh wait_ready exits as soon as the server process dies
  instead of polling for the full 40 minutes.

* Simplify run_all.sh

Drop the defensive layers: model-path candidate scanning, precondition
re-checks, and duplicate idle checking (repro.sh already fails loudly on
all of those). Keep the one-line defaults, the readiness poll that dies
with the server, the SHORT smoke flag, and the per-tier summary print.

* Move V4.1 Prefill benchmarks to randgun#43

* [Bench] Add offline steady-state decode benchmark for DeepSeek V4.1

* Enable target DeepGEMM MegaMoE decode for Ascend DP8 and DP32

---------

Co-authored-by: Aki Yang <[email protected]>
Co-authored-by: AkiYangDev <[email protected]>
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.

OpenAI Chat Completion Endpoint

2 participants