Skip to content

Fix after QWen support - #82

Merged
merrymercy merged 2 commits into
mainfrom
fix
Jan 23, 2024
Merged

merrymercy merged 2 commits into
mainfrom
fix

Conversation

@merrymercy

Copy link
Copy Markdown
Collaborator

Fix some bugs and forma the code
The chat template is still wrong. Will fix it in a follow-up PR.

@merrymercy
merrymercy merged commit 94e0577 into main Jan 23, 2024
@merrymercy
merrymercy deleted the fix branch January 23, 2024 05:17
timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
pengchengneo pushed a commit to pengchengneo/sglang that referenced this pull request Jun 17, 2025
chunyuan-w added a commit to chunyuan-w/sglang that referenced this pull request Jun 19, 2025
chunyuan-w added a commit to chunyuan-w/sglang that referenced this pull request Jun 19, 2025
chunyuan-w added a commit to chunyuan-w/sglang that referenced this pull request Jun 30, 2025
blzheng pushed a commit to blzheng/sglang that referenced this pull request Oct 10, 2025
jayzlee147 pushed a commit to jayzlee147/sglang that referenced this pull request Dec 30, 2025
GDN Module: Add missing causal_conv1d_split_qkv.py for decode phase
cen121212 pushed a commit to cen121212/sglang that referenced this pull request Mar 10, 2026
efschu added a commit to efschu/htsglang that referenced this pull request Jul 18, 2026
…ash — vec-aligned, quant-symmetric tp_units

Under an installed uneven shard plan (--rank-tp-ratio), Qwen2MoeMLP (the
dense MLP of the qwen3.5/3.6 hybrid models, also the MoE shared expert)
passed ELEMENT-granular tp_units (units == intermediate_size) to
gate_up_proj/down_proj. Two distinct failures followed, observed live at
the task-sgl-project#82 TP=3 GGUF oracle boot of Qwen3.6-27B Q4_K_M
(intermediate_size 17408, auto weights [29607, 18280, 18280]):

1. KERNEL-FATAL SHARDS: the largest-remainder element split produced
   per-rank shards [7790, 4809, 4809]; the jit activation kernel
   (elementwise/activation.cuh) rejects shards not divisible by its
   vector width (8 bf16 elems on Ampere, 16 on Blackwell):
     "RuntimeError: ... activation.cuh:168: hidden size must be
      divisible by vector size"
   -> all 3 ranks crashed on the FIRST forward pass.
2. LATENT PARTITION DISAGREEMENT (hidden behind crash 1): linear.py's
   _quant_block_aligned_units coarsens ONLY down_proj's INPUT dim for
   GGUF (ggml blocks lie along the input dim; output-dim coarsening is
   deliberately skipped to keep GDN head units intact). Left per-layer,
   down_proj partitioned the same intermediate dim as [7680, 4864, 4864]
   while gate_up used [7790, 4809, 4809] — a weight/activation shape
   mismatch that would have crashed down_proj next.

Fix (mirrors task sgl-project#100 / 1244d1b LlamaMLP plus qwen3_5's model-level
gdn_tp_units derivation — no new mechanism):
- units = intermediate_size // gcd(intermediate_size, 16): 16-element
  activation-vector units, the SAFE (Blackwell) granularity, per the
  sgl-project#100 precedent.
- units = _quant_block_aligned_units(intermediate, units, quant_config, 1):
  caller-side INPUT-dim quant-block coarsening, so both layers receive
  identical, already-block-aligned units (GGUF: 68 units of 256 -> both
  layers split [7680, 4864, 4864]); the layer-level coarsening becomes an
  idempotent pass-through. For FP8 block-quant the effective units are
  unchanged vs pre-fix (lcm path yields the same 128-block units on both
  sides), keeping validated uneven-TP FP8 boots identical.
- Construction-time guards (fail at boot, not first forward):
  gate_up.tp_units == down.tp_units, and the new
  assert_activation_aligned_shards() in distributed/utils.py rejects any
  plan whose per-rank MLP shard is not a multiple of the widest
  activation vector (ACTIVATION_VEC_ELEMS = 16). Both only bite under an
  active uneven plan.
- The shared-expert replication heuristic
  (_shared_expert_uneven_misaligned) is intentionally untouched: GGUF
  shared experts stay REPLICATED as validated in sgl-project#80/sgl-project#81; revisiting it
  to allow sharded shared experts under the new aligned units is future
  work.

This resolves the standing "HTSGLang-GGUF uneven-TP blocked" limitation
for dense GGUF models: uneven TP over mismatched GPUs now boots and
generates coherently from a K-quant GGUF checkpoint.

Inertness (default/even-TP path unchanged): without an installed plan
tp_partition_sizes falls back to the classic even split before consulting
units — pinned by unit test (even splits for tp 1/2/4 identical pre/post,
divisibility assert preserved).

Test results:
- NEW test/registered/unit/distributed/test_qwen2_moe_mlp_uneven_tp_units.py:
  13/13 pass (inertness, both live failure modes pinned as repros, fixed
  alignment at TP=3 and TP=5 incl. the sgl-project#82 3+1+1 co-location weight
  vector, guard accept/reject, sweep over intermediates x tp x quant).
- Regression: test_llama_mlp_uneven_tp_units.py 7/7,
  test_uneven_tp_partition.py 21/21, test_uneven_tp_family_plans.py 18/18.
- LIVE: Qwen3.6-27B Q4_K_M GGUF, TP=3 --rank-gpu-id 0,1,2
  --rank-tp-ratio auto (previously crashed on first token): boots, 8-prompt
  temp-0 battery coherent (Paris / Guten Morgen translation / Shakespeare),
  15k-token needle retrieval HIT.
- py_compile clean on both touched modules.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 18, 2026
…n-TP expert sharding

fused_moe_gguf's MMQ path (prefill / M>64) passes expert_ids from
moe_align_block_size straight to the sgl-kernel ggml_moe_a8. That buffer
is torch.empty-allocated and the align kernel only fills blocks up to
num_tokens_post_padded — the TRAILING block entries are UNINITIALIZED
garbage. The MMQ device kernel (sgl-kernel moe.cuh moe_q) guards expert
ids with a HARDCODED `exp_idx > 255 || exp_idx < 0`. That is exact for a
full 256-row expert table (garbage >= 256 is rejected), but under
uneven-TP EXPERT-DIM sharding (sgl-project#80/sgl-project#81) each rank's LOCAL weight table
has only n_local+1 rows (owned experts + the trailing zero-pad expert).
Garbage ids in [E_local, 255] pass the 256 guard, and the kernel reads
`vx + exp_idx * exp_stride` beyond the local weight tensor -> illegal
memory access.

Observed live (task sgl-project#82 emulation): Qwen3.6-35B-A3B UD-Q4_K_XL GGUF,
TP=3 --rank-gpu-id 0,1,2 --rank-tp-ratio auto (expert-dim sharding, rank
owns ~114 of 256 experts), crashes on the FIRST prefill > 64 tokens:
  RuntimeError: Triton Error [CUDA]: an illegal memory access
Diagnosis was initially misattributed to the GDN/cumsum kernel (the async
IMA surfaced at the next kernel launch); CUDA_LAUNCH_BLOCKING=1 relocated
the true fault to fused_moe_gguf -> ggml_moe_a8 -> activation.cuh. The
MMVQ decode path (M<=64) takes no expert_ids blocks and was unaffected,
which is why decode/short prompts looked fine.

Fix: sanitize out-of-range block ids to -1 before ggml_moe_a8 —
`expert_ids = expert_ids.masked_fill(expert_ids >= E, -1)` — so the
kernel's own `exp_idx < 0` guard rejects trailing garbage. Every VALID
block id is < E by construction, so only garbage/trailing blocks are
touched; the result is byte-identical for the full-table (E=256, TP=1)
path. masked_fill with a SCALAR is a device-only op with no host->device
copy, so it is CUDA-graph-capture safe (a torch.where against a freshly
constructed host scalar tensor is NOT — it aborts MTP/NEXTN graph
capture with "Cannot copy between CPU and CUDA tensors during CUDA graph
capture"). Python-side deliberately: sgl_kernel ships prebuilt, and this
mirrors the existing _ggml_moe_get_block_size fallback (usable without a
kernel rebuild). The durable kernel-side bound (exp_idx < nrows(W_local)
instead of the hardcoded 255) is filed as backlog sgl-project#112.

Pre-existing bug (moe.cuh, gguf.py, moe_align_block_size — none touched
by task sgl-project#82; reproduced on the plain uneven-TP GGUF MoE path). Also a
latent OOB for ANY GGUF MoE with < 256 experts even without sharding.

Test results:
- NEW test/registered/unit/quantization/test_gguf_moe_expert_ids_sanitize.py:
  5/5 pass (sharded-garbage sanitized to -1; full-table E=256 byte-identical
  no-op; boundary id == E excluded; dtype/shape preserved).
- LIVE (eager): Qwen3.6-35B-A3B GGUF TP=3 uneven, previously crashed on
  first prefill>64: now boots and generates coherently — temp-0 battery
  correct (17*23=391, next-after-16=32, Paris, Shakespeare, German
  translation), and the 15k-token needle prefill (the exact MMQ path that
  crashed) completes without IMA.
- Graph-safety: full-perf boot (CUDA graphs + NEXTN) passes MoE + target-
  verify graph capture with masked_fill (the torch.where/new_tensor form
  aborted capture; that is why masked_fill is used).
- py_compile clean.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 18, 2026
…n probe + emulation docs

The multi-rank-per-GPU co-location preflight warned based on os.path.exists()
of the CUDA MPS pipe DIRECTORY (/tmp/nvidia-mps). That directory lingers after
a crashed/killed daemon (seen live on this rig) and can be a custom path for a
healthy one, so it is not a liveness signal — the warning both false-negatived
(stale dir, no daemon) and false-positived.

Replace it with _mps_control_daemon_responsive(): probe nvidia-cuda-mps-control
directly (pipe a read-only query on stdin; clean exit + non-empty reply =
responsive). Pure subprocess/stdlib, unit-testable on CPU. Added
test_mps_control_probe.py (6 cases: responsive, binary-missing, daemon-down,
empty-stdout, timeout, oserror).

Docs: docs/advanced_features/multi_rank_emulation.md documents the feature as
an EMULATION (co-located ranks time-slice one card via MPS; not real N-card
perf), the NCCL>=2.30 requirement + how to LD_PRELOAD a newer libnccl without
touching the shared venv (torch pins libnccl via DT_RPATH so LD_LIBRARY_PATH
loses; torch.cuda.nccl.version() is a build-time constant so verify uptake via
/proc maps / NCCL_DEBUG / the communicator building), the per-GPU reserve
tuning for N-way capture headroom, and the enforced physical-impossibility
check.

Validated live: dense Qwen3.6-27B GGUF, TP=5 --rank-gpu-id 0,0,0,1,2 (3 ranks
on a 5090 + 1 per 3080), full-perf graphs+NEXTN/MTP, NCCL 2.30.7 side-loaded.
All 5 ranks build the co-located communicator + capture graphs + serve;
coherent temp-0, 15k-token needle HIT, bit-identical across 2 boots. MPS probe
unit test: 6 passed.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 19, 2026
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
…ash — vec-aligned, quant-symmetric tp_units

Under an installed uneven shard plan (--rank-tp-ratio), Qwen2MoeMLP (the
dense MLP of the qwen3.5/3.6 hybrid models, also the MoE shared expert)
passed ELEMENT-granular tp_units (units == intermediate_size) to
gate_up_proj/down_proj. Two distinct failures followed, observed live at
the task-sgl-project#82 TP=3 GGUF oracle boot of Qwen3.6-27B Q4_K_M
(intermediate_size 17408, auto weights [29607, 18280, 18280]):

1. KERNEL-FATAL SHARDS: the largest-remainder element split produced
   per-rank shards [7790, 4809, 4809]; the jit activation kernel
   (elementwise/activation.cuh) rejects shards not divisible by its
   vector width (8 bf16 elems on Ampere, 16 on Blackwell):
     "RuntimeError: ... activation.cuh:168: hidden size must be
      divisible by vector size"
   -> all 3 ranks crashed on the FIRST forward pass.
2. LATENT PARTITION DISAGREEMENT (hidden behind crash 1): linear.py's
   _quant_block_aligned_units coarsens ONLY down_proj's INPUT dim for
   GGUF (ggml blocks lie along the input dim; output-dim coarsening is
   deliberately skipped to keep GDN head units intact). Left per-layer,
   down_proj partitioned the same intermediate dim as [7680, 4864, 4864]
   while gate_up used [7790, 4809, 4809] — a weight/activation shape
   mismatch that would have crashed down_proj next.

Fix (mirrors task sgl-project#100 / 32b972f LlamaMLP plus qwen3_5's model-level
gdn_tp_units derivation — no new mechanism):
- units = intermediate_size // gcd(intermediate_size, 16): 16-element
  activation-vector units, the SAFE (Blackwell) granularity, per the
  sgl-project#100 precedent.
- units = _quant_block_aligned_units(intermediate, units, quant_config, 1):
  caller-side INPUT-dim quant-block coarsening, so both layers receive
  identical, already-block-aligned units (GGUF: 68 units of 256 -> both
  layers split [7680, 4864, 4864]); the layer-level coarsening becomes an
  idempotent pass-through. For FP8 block-quant the effective units are
  unchanged vs pre-fix (lcm path yields the same 128-block units on both
  sides), keeping validated uneven-TP FP8 boots identical.
- Construction-time guards (fail at boot, not first forward):
  gate_up.tp_units == down.tp_units, and the new
  assert_activation_aligned_shards() in distributed/utils.py rejects any
  plan whose per-rank MLP shard is not a multiple of the widest
  activation vector (ACTIVATION_VEC_ELEMS = 16). Both only bite under an
  active uneven plan.
- The shared-expert replication heuristic
  (_shared_expert_uneven_misaligned) is intentionally untouched: GGUF
  shared experts stay REPLICATED as validated in sgl-project#80/sgl-project#81; revisiting it
  to allow sharded shared experts under the new aligned units is future
  work.

This resolves the standing "HTSGLang-GGUF uneven-TP blocked" limitation
for dense GGUF models: uneven TP over mismatched GPUs now boots and
generates coherently from a K-quant GGUF checkpoint.

Inertness (default/even-TP path unchanged): without an installed plan
tp_partition_sizes falls back to the classic even split before consulting
units — pinned by unit test (even splits for tp 1/2/4 identical pre/post,
divisibility assert preserved).

Test results:
- NEW test/registered/unit/distributed/test_qwen2_moe_mlp_uneven_tp_units.py:
  13/13 pass (inertness, both live failure modes pinned as repros, fixed
  alignment at TP=3 and TP=5 incl. the sgl-project#82 3+1+1 co-location weight
  vector, guard accept/reject, sweep over intermediates x tp x quant).
- Regression: test_llama_mlp_uneven_tp_units.py 7/7,
  test_uneven_tp_partition.py 21/21, test_uneven_tp_family_plans.py 18/18.
- LIVE: Qwen3.6-27B Q4_K_M GGUF, TP=3 --rank-gpu-id 0,1,2
  --rank-tp-ratio auto (previously crashed on first token): boots, 8-prompt
  temp-0 battery coherent (Paris / Guten Morgen translation / Shakespeare),
  15k-token needle retrieval HIT.
- py_compile clean on both touched modules.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
…n-TP expert sharding

fused_moe_gguf's MMQ path (prefill / M>64) passes expert_ids from
moe_align_block_size straight to the sgl-kernel ggml_moe_a8. That buffer
is torch.empty-allocated and the align kernel only fills blocks up to
num_tokens_post_padded — the TRAILING block entries are UNINITIALIZED
garbage. The MMQ device kernel (sgl-kernel moe.cuh moe_q) guards expert
ids with a HARDCODED `exp_idx > 255 || exp_idx < 0`. That is exact for a
full 256-row expert table (garbage >= 256 is rejected), but under
uneven-TP EXPERT-DIM sharding (sgl-project#80/sgl-project#81) each rank's LOCAL weight table
has only n_local+1 rows (owned experts + the trailing zero-pad expert).
Garbage ids in [E_local, 255] pass the 256 guard, and the kernel reads
`vx + exp_idx * exp_stride` beyond the local weight tensor -> illegal
memory access.

Observed live (task sgl-project#82 emulation): Qwen3.6-35B-A3B UD-Q4_K_XL GGUF,
TP=3 --rank-gpu-id 0,1,2 --rank-tp-ratio auto (expert-dim sharding, rank
owns ~114 of 256 experts), crashes on the FIRST prefill > 64 tokens:
  RuntimeError: Triton Error [CUDA]: an illegal memory access
Diagnosis was initially misattributed to the GDN/cumsum kernel (the async
IMA surfaced at the next kernel launch); CUDA_LAUNCH_BLOCKING=1 relocated
the true fault to fused_moe_gguf -> ggml_moe_a8 -> activation.cuh. The
MMVQ decode path (M<=64) takes no expert_ids blocks and was unaffected,
which is why decode/short prompts looked fine.

Fix: sanitize out-of-range block ids to -1 before ggml_moe_a8 —
`expert_ids = expert_ids.masked_fill(expert_ids >= E, -1)` — so the
kernel's own `exp_idx < 0` guard rejects trailing garbage. Every VALID
block id is < E by construction, so only garbage/trailing blocks are
touched; the result is byte-identical for the full-table (E=256, TP=1)
path. masked_fill with a SCALAR is a device-only op with no host->device
copy, so it is CUDA-graph-capture safe (a torch.where against a freshly
constructed host scalar tensor is NOT — it aborts MTP/NEXTN graph
capture with "Cannot copy between CPU and CUDA tensors during CUDA graph
capture"). Python-side deliberately: sgl_kernel ships prebuilt, and this
mirrors the existing _ggml_moe_get_block_size fallback (usable without a
kernel rebuild). The durable kernel-side bound (exp_idx < nrows(W_local)
instead of the hardcoded 255) is filed as backlog sgl-project#112.

Pre-existing bug (moe.cuh, gguf.py, moe_align_block_size — none touched
by task sgl-project#82; reproduced on the plain uneven-TP GGUF MoE path). Also a
latent OOB for ANY GGUF MoE with < 256 experts even without sharding.

Test results:
- NEW test/registered/unit/quantization/test_gguf_moe_expert_ids_sanitize.py:
  5/5 pass (sharded-garbage sanitized to -1; full-table E=256 byte-identical
  no-op; boundary id == E excluded; dtype/shape preserved).
- LIVE (eager): Qwen3.6-35B-A3B GGUF TP=3 uneven, previously crashed on
  first prefill>64: now boots and generates coherently — temp-0 battery
  correct (17*23=391, next-after-16=32, Paris, Shakespeare, German
  translation), and the 15k-token needle prefill (the exact MMQ path that
  crashed) completes without IMA.
- Graph-safety: full-perf boot (CUDA graphs + NEXTN) passes MoE + target-
  verify graph capture with masked_fill (the torch.where/new_tensor form
  aborted capture; that is why masked_fill is used).
- py_compile clean.
efschu added a commit to efschu/htsglang that referenced this pull request Jul 22, 2026
…n probe + emulation docs

The multi-rank-per-GPU co-location preflight warned based on os.path.exists()
of the CUDA MPS pipe DIRECTORY (/tmp/nvidia-mps). That directory lingers after
a crashed/killed daemon (seen live on this rig) and can be a custom path for a
healthy one, so it is not a liveness signal — the warning both false-negatived
(stale dir, no daemon) and false-positived.

Replace it with _mps_control_daemon_responsive(): probe nvidia-cuda-mps-control
directly (pipe a read-only query on stdin; clean exit + non-empty reply =
responsive). Pure subprocess/stdlib, unit-testable on CPU. Added
test_mps_control_probe.py (6 cases: responsive, binary-missing, daemon-down,
empty-stdout, timeout, oserror).

Docs: docs/advanced_features/multi_rank_emulation.md documents the feature as
an EMULATION (co-located ranks time-slice one card via MPS; not real N-card
perf), the NCCL>=2.30 requirement + how to LD_PRELOAD a newer libnccl without
touching the shared venv (torch pins libnccl via DT_RPATH so LD_LIBRARY_PATH
loses; torch.cuda.nccl.version() is a build-time constant so verify uptake via
/proc maps / NCCL_DEBUG / the communicator building), the per-GPU reserve
tuning for N-way capture headroom, and the enforced physical-impossibility
check.

Validated live: dense Qwen3.6-27B GGUF, TP=5 --rank-gpu-id 0,0,0,1,2 (3 ranks
on a 5090 + 1 per 3080), full-perf graphs+NEXTN/MTP, NCCL 2.30.7 side-loaded.
All 5 ranks build the co-located communicator + capture graphs + serve;
coherent temp-0, 15k-token needle HIT, bit-identical across 2 boots. MPS probe
unit test: 6 passed.
efschu added a commit to efschu/htsglang that referenced this pull request Aug 1, 2026
…ope the TP>kv window

The durable outcome of the validation arc is a rule about WHERE this layout
pays, so it goes where an operator reads it.

FLAG HELP. --draft-kv-layout now states the measured trade rather than only the
mechanism: dcp saves draft VRAM only where the kv-heads cannot be sharded
further (TP > num_kv_heads), and there the saving is the full token-shard
factor ratio_r/S. On a head-shardable rig the token-shard and head-replication
factors CANCEL, so the layout is VRAM-byte-neutral while still costing
speculation efficiency -- measured on Qwen3.6-27B-FP8, TP=3 over 4 kv-heads,
vector [30,17,17]: output token ids byte-identical (64/64 on both probe
prompts) but verify rounds 16->19 and 19->21, accept -10..-16%. The text names
that cost as benign LSE reassociation in the DRAFT, not a correctness defect,
and tells the reader to leave the flag at 'replicated' on rigs whose heads
split evenly. Guidance text only: no gate changed, no auto-flip -- the choice
stays the user's.

One trap caught by the existing suite while writing it: a literal '%' in an
argparse help string makes --help raise for EVERY option, not just that one
(test_help_text_renders). Escaped as '%%'.

VEHICLE INVENTORY for the TP > num_kv_heads window, from a scan of the model
cache. The trigger is attn_kv_replicated(attn_tp_size, total_kv), i.e. strictly
TP > num_key_value_heads. TWO vehicles reach it at NATIVE TP=3, so the sgl-project#82
co-location axis is not needed at all:

  Qwen3.5-2B            2 kv /  8 q | 3.5 G | bf16 dense | MTP present
  Qwen3.6-35B-A3B-FP8   2 kv / 16 q |  31 G | FP8 MoE    | MTP present
  (also 2 kv: 35B-A3B GPTQ-Int4 20 G, AWQ-4bit 22 G; 122B-A10B needs sgl-project#77
   expert offload and is too heavy for this question)

The 27B family is 4 kv and would need TP=5 co-location -- deliberately not
used, one lever per window. Recommended pair: the 2B as the mechanism vehicle
(boots in seconds) and the 35B-A3B-FP8 as the realistic one.

PREDICTION TO TEST: under replication every rank holds all total_kv heads, so
the head factor is 1 on both sides and no longer cancels the token shard --
the saving should be the FULL shard factor, 47/27/27 % of the replicated draft
pool for a [30,17,17] vector.

WINDOW PROPOSAL: 2 questions, 4 boots ({2B, 35B-A3B-FP8} x {replicated, dcp}),
~25 min, standard reserve, no bar1, local CT999. Q1 does the VRAM win
materialize at the predicted factor (read the KV-allocated lines as before).
Q2 does accept hold and does H2 behave -- with two sub-checks that only exist
on this hardware: assert dcp_kv_replicated_heads is actually True (otherwise
the window measured nothing), and include a SHORT prompt in the probe set
because _replicated_kv_ragged_reindex is now on the live path and its
documented failure shape is corrupted short-prompt / first-chunk generation
while the gathered-q paged path stays correct. Out of scope: the H3 context
sweep (optional confirmation, not a blocker), throughput, TP=5.

Four expected outcomes are written out with what each would mean, including
the one that turns H2 from inapplicable into a real defect.

distributed + spec + server_args: zero failures unique to this branch, +446
passed. ruff/codespell/black clean. Docs and help text only; no cards touched.
efschu added a commit to efschu/htsglang that referenced this pull request Aug 2, 2026
…rator (sgl-project#391)

With SGLANG_OPT_FP8_WO_A_GEMM off -- the only reachable setting on a GGUF
checkpoint, since forcing it on raises NotImplementedError in
DeepseekV4AttentionMHC, and server_args auto-disables it below sm100 --
load_weights opened with

    weights = list(weights)
    exists_wo_a_scale = any(n.endswith(".wo_a.scale") for n, t in weights)

draining the entire weight stream to answer one boolean. On DeepSeek-V4-Flash
GGUF that materializes every post-repack tensor in host RAM before the first
weight loader runs: boot 6 measured a linear 0.63-0.73 GiB/s climb to 74.8 GiB
with no weight_loader and no _load_gguf_weight frame in any rank's py-spy
stack, and zero staging-trace lines. Every downstream streaming step (#391c
expert staging) and the sgl-project#82 per-rank expert-dim shard drop sits below that
list, so each rank held the FULL post-repack set, not its shard.

The boolean is also a constant on that route: a packed GGUF wo_a carries no
separate block-scale tensor by construction, which is exactly what the
NotImplementedError above states. The export confirms it -- the only "scale"
names it ships are hc_attn_scale, hc_ffn_scale and output_hc_scale.

So the GGUF branch skips the lookahead entirely and checks the claim per
tensor as the stream flows (_reject_wo_a_scale_on_gguf). The skip must not
silently swallow a real dequant input, so a planted .wo_a.scale is refused by
name rather than loaded with its scale unapplied.

The non-GGUF route is untouched and still takes the list: it holds mmapped
tensors, the list is cheap there, and the flag can genuinely be true.

Tests: test/registered/unit/model_loader/test_dsv4_gguf_load_weights_stream.py
(7 tests, CPU only, meta tensors, no checkpoint), 8.3 s.

Can-fail matrix, same file against the unfixed and the fixed source:

  unfixed: 4 failed, 3 passed   fixed: 7 passed
    FAIL->PASS  gguf_stream_is_consumed_one_tensor_at_a_time
                  calls [64]*64 -> [1..64]; peak live tensors 64 -> 2
    FAIL->PASS  planted_wo_a_scale_is_refused_by_name
                  "ValueError not raised" -> refused
    FAIL->PASS  refusal_fires_mid_stream_not_after_a_drain
                  stream stops at item 5 of 65, 4 tensors already loaded
    FAIL->PASS  clean_gguf_stream_loads
    PASS->PASS  can_fail_arm_the_lookahead_route_does_materialize (pinned)
    PASS->PASS  fp8_stream_with_wo_a_scale_still_triggers_the_dequant (pinned)
    PASS->PASS  unquantized_route_also_keeps_the_lookahead (pinned)

The three pinned tests pass on both sources, which is the evidence that the
non-GGUF behaviour is unchanged; the committed can-fail arm drives the same
probe down the lookahead route and asserts it still drains, so the streaming
assertions above stay able to fail.

Regression: test/registered/unit/model_loader/ 177 passed, 9 skipped, 6 failed
-- all 6 in test_modelopt_loader.py with "No accelerator", pre-existing on a
CUDA_VISIBLE_DEVICES=99 desk run.

Drain audit of the reachable loader chain (only same-class drains fixed):
  deepseek_v4.py:2742          list(weights) lookahead -- FIXED
  deepseek_v4.py:3147          _dequant_fp8_wo_a dict(weights) -- unreachable
                               on GGUF (only called from the fixed branch)
  deepseek_weight_loader.py:785 _maybe_quant_weights_to_fp8_ue8m0 dict(weights)
                               -- already guarded by an empty-partial_names
                               early return, and gated on
                               SGLANG_NVFP4_CKPT_FP8_GEMM_IN_ATTN (default
                               False) or a modelopt_fp4 quant config; also not
                               on the V4 route at all, since
                               DeepseekV4ForCausalLM does not inherit
                               DeepseekV2WeightLoaderMixin
  loader.py:1286               QuantizedRLModelLoader.rebinding_and_load_weights
                               list(weights) -- VERL RL reload path, not the
                               GGUF boot route
  gguf_deepseek4.transform_stream and gguf_quant_weights_iterator hold no
  list/dict over the stream; both are clean generators.

ruff check clean, ruff format introduces no new hunks, codespell clean.
efschu added a commit to efschu/htsglang that referenced this pull request Aug 17, 2026
…ensus mark

The worst census segment on every rank, gdn_state->weights_refill, is the
WEIGHTS REFILL and not the GDN move: marks are taken after each pre-cutover
mover returns, so the segment runs from the GDN leg finishing to the refill
finishing. refill() is one contiguous H2D of the target layout image --
rank-local, no collective.

That retracts this note's first revision, which read the segment as the GDN
exchange and its spread as a rendezvous wait with rank 2 arriving last.
Corrected reading: every rank copies the same 9614.9 MiB TP image, and the
per-rank times track PCIe link width, resolved via the NVML canon rather
than by rank index (sgl-project#82 device-order trap):

  rank 1 -> phys 0, 3080, x4 -> 1903.0 ms -> 4.93 GB/s
  rank 0 -> phys 1, 5090, x8 -> 1327.1 ms -> 7.08 GB/s
  rank 2 -> phys 2, 3080, x8 -> 1057.0 ms -> 8.88 GB/s

So it is the x4 card, but that is rank 1; rank 2 is the fastest of the
three. Equal per-rank totals (within 0.7%) with an 846 ms segment spread
put rank 1's refill on the flip's critical path -- ~27% of a ~3.1 s flip
attributable to one card in an x4 slot.

Unexplained and named as such: two x8 cards differ 7.08 vs 8.88 GB/s, and
the 1.80x x4/x8 ratio falls short of the 2.00x pure-link prediction. Both
are the size of a fixed cost sharing the segment with the copy -- the arena
commit, which grows on ranks 1 and 2 but not on rank 0.

The mark separates them: one site in _commit_refill_high_water, firing on
both directions, splitting the leg into commit and copy. Marked outside the
carrier guard so a no-carrier rank reports a zero-width step instead of
dropping the boundary and changing what its remaining bar means.

No behaviour change: mark() is a no-op with no census open and swallows its
own exceptions, so it cannot be why a flip dies (sgl-project#631 no-return contract,
re-pinned here rather than inherited).

Tests (hermetic, CUDA_VISIBLE_DEVICES=""):
  test/registered/unit/managers/test_refill_highwater_mark_690.py 8 passed
    red-first: 5 of 8 fail without the mark
  test/registered/unit/managers/ 2119 passed, 18 skipped, 130 subtests
  ruff clean on both changed files (the pre-existing unused pack_into_arena
    import at HEAD is left alone as out of scope)
efschu added a commit to efschu/htsglang that referenced this pull request Aug 17, 2026
…ensus mark

The worst census segment on every rank, gdn_state->weights_refill, is the
WEIGHTS REFILL and not the GDN move: marks are taken after each pre-cutover
mover returns, so the segment runs from the GDN leg finishing to the refill
finishing. refill() is one contiguous H2D of the target layout image --
rank-local, no collective.

That retracts this note's first revision, which read the segment as the GDN
exchange and its spread as a rendezvous wait with rank 2 arriving last.
Corrected reading: every rank copies the same 9614.9 MiB TP image, and the
per-rank times track PCIe link width, resolved via the NVML canon rather
than by rank index (sgl-project#82 device-order trap):

  rank 1 -> phys 0, 3080, x4 -> 1903.0 ms -> 4.93 GB/s
  rank 0 -> phys 1, 5090, x8 -> 1327.1 ms -> 7.08 GB/s
  rank 2 -> phys 2, 3080, x8 -> 1057.0 ms -> 8.88 GB/s

So it is the x4 card, but that is rank 1; rank 2 is the fastest of the
three. Equal per-rank totals (within 0.7%) with an 846 ms segment spread
put rank 1's refill on the flip's critical path -- ~27% of a ~3.1 s flip
attributable to one card in an x4 slot.

Unexplained and named as such: two x8 cards differ 7.08 vs 8.88 GB/s, and
the 1.80x x4/x8 ratio falls short of the 2.00x pure-link prediction. Both
are the size of a fixed cost sharing the segment with the copy -- the arena
commit, which grows on ranks 1 and 2 but not on rank 0.

The mark separates them: one site in _commit_refill_high_water, firing on
both directions, splitting the leg into commit and copy. Marked outside the
carrier guard so a no-carrier rank reports a zero-width step instead of
dropping the boundary and changing what its remaining bar means.

No behaviour change: mark() is a no-op with no census open and swallows its
own exceptions, so it cannot be why a flip dies (sgl-project#631 no-return contract,
re-pinned here rather than inherited).

Tests (hermetic, CUDA_VISIBLE_DEVICES=""):
  test/registered/unit/managers/test_refill_highwater_mark_690.py 8 passed
    red-first: 5 of 8 fail without the mark
  test/registered/unit/managers/ 2119 passed, 18 skipped, 130 subtests
  ruff clean on both changed files (the pre-existing unused pack_into_arena
    import at HEAD is left alone as out of scope)
efschu pushed a commit to efschu/htsglang that referenced this pull request Sep 16, 2026
…non-GGUF MoE paths (SGLANG_UNEVEN_MOE_EXPERT_SHARD=1)

The sgl-project#82 GGUF expert-dim shard generalized: with an uneven plan every rank
owns a plan-proportional range of WHOLE experts (Qwen3.8-Flash-Next 39:13:12
-> 312/104/96 of 512), keeps the full 640 intermediate (no Marlin tile cut
to 384/128/128), and runs its own expert set through the offload -- the
form the D phase needs (residents by VRAM, cold traffic by link).

- FusedMoE.__init__: generic shard for quant paths other than gguf when the
  plan is active, EP=1 and the env is set; local layout [pad(0), owned
  1..n_local] -- the pad expert at LOCAL INDEX 0 so the static residency
  plan [0, R) always holds it (GGUF keeps its trailing pad).
- _map_global_expert_id_to_local_expert_id drops foreign experts at load;
  _build_expert_shard_topk_remap (shared with GGUF) sends foreign topk ids
  to the pad; zero_expert_shard_pad() zeroes the pad rows (scales 0 =>
  contribution 0) and the CT WNA16 MoE scheme calls it before its repack;
  the per-layer stream presplit counts only the OWNED experts.
- forward_local builds the remap lazily (GGUF path unchanged).
Tests: tests/moe_offload/test_expert_index_shard_generic.py 6 passed;
presplit/awq/shard suites 81 passed, 9 CUDA-skipped.
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.

1 participant