Skip to content

Fix the case where r.prefix_indices is None - #1031

Merged
merrymercy merged 1 commit into
mainfrom
fix-indices
Aug 11, 2024
Merged

merrymercy merged 1 commit into
mainfrom
fix-indices

Conversation

@merrymercy

@merrymercy merrymercy commented Aug 11, 2024 •

Copy link
Copy Markdown
Collaborator

Hotfix for #1023.
This creates some perf regression, but @hnyls2002 will fix it later.

@merrymercy
merrymercy enabled auto-merge (squash) August 11, 2024 11:53
@merrymercy
merrymercy disabled auto-merge August 11, 2024 11:53
@merrymercy
merrymercy merged commit 4080e82 into main Aug 11, 2024
@merrymercy
merrymercy deleted the fix-indices branch August 11, 2024 11:53
timethink pushed a commit to timethink/sglang that referenced this pull request Mar 9, 2025
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 30, 2026
…ONGRUENT ZUGELASSEN -- meine "nie angekommen"-Erklaerung ist FALSCH

S1-Durchgang, Schritt 1. Die rid-genaue Timeline aus dem Strandungs-Log
kippt meine eigene Diagnose, und zwar in die praezisere Richtung.

== DIE TIMELINE (logindex, boot_855_fix1027_..._112900, voll ingested) ==
Nach 11:57:30 nennt das Log GENAU EINEN rid: 2fe8dab34ab1.
  admission   n=18   11:56:14 .. 11:58:05
  flip_event  n=100  11:56:17 .. 12:02:21
Die 18 Admission-Zeilen sind SECHS Runden zu je drei Raengen, und JEDE ist
  "sgl-project#788 PP-ADMISSION verdict=ADMIT n_reqs=1 rids=2fe8dab34ab14d"
auf Rang 0 UND 1 UND 2. Die Raenge waren sich EINIG. Letzte Zulassung
11:58:05; letzter Prefill 11:58:07; danach nichts mehr.
Und der Flip-Apparat nennt denselben rid noch bis 12:02:21 in
FLIP EXTENT PROBE auf allen drei Raengen -- der Request ist also die ganze
Strandung ueber RESIDENT, nicht verschwunden.

== SELBSTKORREKTUR (fuenfte, und sie stand im CODE) ==
Mein Commit 70d85ed schloss: "DER REQUEST IST OBERHALB DER PHASE-POLICY
VERLORENGEGANGEN", und ich hatte diese Erklaerung in die sgl-project#1028-Log-Zeile
geschrieben ("its request never reached this scheduler"). Das ist
FALSIFIZIERT: er hat den Scheduler erreicht, wurde sechsmal von allen drei
Raengen zugelassen und blieb danach resident. Die Zeile haette den naechsten
Leser genau so fehlgeleitet, wie mich "decoding in tp" fehlgeleitet hat --
also derselbe Fehler, den ich am selben Tag viermal katalogisiert habe, von
mir selbst begangen und in den Baum committet. Text korrigiert auf
"admitted and then stopped progressing somewhere DOWNSTREAM of admission".
Der Grund, dass ich es fand: die rid-Timeline, nicht erneutes Nachdenken.

== FOLGE: DER VERLUSTPUNKT LIEGT NICHT AUF S0 UND NICHT AUF S1 ==
Intake (S0) war bereits ausgeschlossen. Admission (S1) ist hiermit ebenfalls
ausgeschlossen -- sie hat kongruent ADMIT gesprochen. Der Defekt liegt
ZWISCHEN Zulassung/Prefill und dem laufenden Batch, also auf der MERGE-Bahn
(S2). Damit ist die Station benannt, an der weitergesucht wird.

== EIN KANDIDAT, AUSDRUECKLICH NOCH NICHT ALS URSACHE BEHAUPTET ==
Am Strandungspunkt feuert auf allen drei Raengen
  "SELF-MERGE REFUSED: last_batch is running_batch (bs=1)"
(scheduler.py:7427-7457). Formal ist das genau die vom Gesetz verbotene
Form: ein Guard, der einen Zustand erkennt, den sein eigener Kommentar
"the resident set is corrupted" nennt, und dann REFUSAL-UND-WEITER macht
statt die Gruppe zu stoppen -- und der Kommentar sagt selbst "a detector
that only declines to act cannot stop a doubling -- the instance still
died". Nach Upstream-Minimal ist ein Defekt in einer Kompensationsschicht
ein LOESCH-KANDIDATEN-Befund; die eigentliche Frage ist, warum
`last_batch is running_batch` ueberhaupt gilt (Aliasing).
ABER, INDIKATOR-GESETZ: der Marker feuert 166.173-mal auf diesem Boot,
also auch waehrend der ~26 Minuten, in denen alles funktionierte. Er ist
damit NICHT hinreichend fuer die Strandung und wird hier als
KO-OKKURRENZ gefuehrt, nicht als Ursache. Wer ihn ohne diese Zahl zitiert,
berichtet eine Korrelation als Wurzel.

== NAECHSTER SCHRITT (nicht mehr in diesem Zug) ==
S2/Merge-Bahn mit derselben Disziplin: Zeilen per emittiertem Literal am Pin
relokalisieren, per trapsafe zaehlen, und die Frage stellen, die die
sgl-project#1031-MERGE-PATH-PROBE (scheduler.py:7462ff) bereits woertlich formuliert --
"`#running-req: 0` heisst entweder der Prefill hat NIE gemerged, oder er
merged und sgl-project#856-no-carry hat ihn vor der Decode-Runde retracted; nichts
Gemessenes trennt die beiden". Genau diese Trennung ist jetzt die Aufgabe,
und die Probe dafuer liegt schon im Baum.

BELEG-STUFE: BOOT-BEWIESEN (rid-Timeline aus dem voll ingesteten Log).
Kandidat SELF-MERGE: BEOBACHTET, ausdruecklich nicht kausal belegt.
efschu pushed a commit to efschu/htsglang that referenced this pull request Aug 30, 2026
…gl-project#1027 einen Aufruf frueher -- mein eigener Fix war halb. Merge-Frage: NULL.

Reproduktions-Budget eingehalten: EINE Sequenz Pack4->Pack5. Sie strandete
nach ~13 Minuten, bei DE-07 -- derselben Frage wie beim Original.
UND DIESMAL WURDE VOR DEM RAEUMEN GEERNTET (die Regel, die ich letztes Mal
gebrochen habe). Specimen /spinning/gpu-arb/W1028-LIVE-CATCH/.

== DREI STACKS, EIN MOMENT ==
  PP0  active       all_reduce <- _update_uniform_pool_budget (scheduler.py:6186)
  PP2  active       all_reduce <- _update_uniform_pool_budget (scheduler.py:6186)
  PP1  active+gil   memory_stats <- memory_reserved
                    <- _allocator_cache_bytes (corridor_admission.py:715)
                    <- _takeable_cache_bytes:734 <- spendable_bytes:620
                    <- granted_width:635 <- _local_corridor_width_ceiling:8343
                    <- _update_uniform_pool_budget (scheduler.py:6121)
Zwei Raenge warten im Kollektiv, der dritte hat es nicht erreicht. Exakt die
sgl-project#1027-Form, anderer Aufruf. Eine fruehere Probe derselben Episode fand PP0 bei
`available_size (memory_pool.py:383)` <- `get_num_allocatable_reqs`
<- `_local_admit_limit (scheduler.py:6612)` -- die Straggler-ROLLE ROTIERT,
die Region ist fuer mehr als einen Aufrufer langsam.

== SELBSTKORREKTUR (sechste): MEIN sgl-project#1027-FIX WAR HALB ==
sgl-project#1027 legte `torch.cuda.memory_snapshot()` (:748-750) hinter eine Kadenz.
Aber `_takeable_cache_bytes` ruft EINE ZEILE FRUEHER (:734)
`_allocator_cache_bytes()`, und das geht ueber `memory_reserved()` /
`memory_allocated()` ebenfalls durch `torch.cuda.memory_stats()`. Ich habe die
innere teure Haelfte gedeckelt und die aeussere auf dem Pro-Runde-Pfad
gelassen. Der Fix war ECHT (die sgl-project#1027-Signatur ist weg: kein Rang steht mehr
im Snapshot-Zweig) und UNVOLLSTAENDIG. Jetzt ist der GANZE Wert cadenced.

== DIE MERGE-FRAGE IST BEANTWORTET, UND ZWAR MIT NULL ==
Die sgl-project#1031-Probe war erschoepft, nicht stumm: sie verbrauchte ihren 200er-
Deckel in 37 s (11:32:16-11:32:53) und schwieg 25 min vor der Strandung; der
gestrandete rid kam in NULL Probe-Zeilen vor. Nachgeschaerft: Kopf-Stichprobe
BEHALTEN plus ein Arm, der immer feuert, wenn ein Extend-Batch Requests trug
und der Running-Batch danach leer ist (`why=NEVER-MERGED-CANDIDATE`) -- genau
die Diskriminante, die der Proben-Docstring als ungetrennt benennt.
Ergebnis ueber die ganze Episode: head 600, NEVER-MERGED-CANDIDATE **0**.
Also: nichts wurde zugelassen-und-am-Merge-fallengelassen. S2 faellt als
Verlustort aus.

== DAMIT IST sgl-project#1028 VON ANFANG AN FALSCH GERAHMT GEWESEN ==
S0 ausgeschlossen, S1 ausgeschlossen (kongruentes ADMIT), S2 ausgeschlossen
(Merge-Null). Es gibt keinen verlorenen Request: der Request ist da, und die
GRUPPE STEHT, bevor sie ihn bedienen kann. sgl-project#1028 ist kein Intake-Verlust,
sondern ein Liveness-Stall derselben Familie wie sgl-project#1027. Meine eigene
Rahmung "der Request ging oberhalb der Policy verloren" ist damit zum
zweiten Mal korrigiert -- erst zu "downstream of admission", jetzt zu
"gar kein Verlust".

== KLASSE, EINE EBENE HOEHER -- und das ist die sgl-project#968-Aussage ==
Nicht "ein langsamer Aufruf", sondern: `_update_uniform_pool_budget` leistet
UNBESCHRAENKT teure lokale Arbeit in der Region zwischen Rundenbeginn und
einem Kollektiv, das jeder Rang erreichen muss. Jeder Aufruf dort kann die
Gruppe aushungern, und einen zu deckeln befoerdert den naechsten:
sgl-project#1027 = memory_snapshot, dies = memory_stats, und
`available_size`/`get_num_allocatable_reqs` (:6174) ist der naechste
Kandidat. Der dauerhafte Fix ist KEINE dritte Kadenz, sondern die Region
konstruktiv kostenfrei zu machen -- keine Allocator-Introspektion zwischen
Rundenbeginn und Barriere. Das IST die sgl-project#968-Form: das Budget-Verdikt gehoert
zu PP0 und wird verteilt, statt von jedem Rang vor der Barriere lokal neu
gerechnet zu werden. Als Kommentar an der Fix-Stelle hinterlegt, damit der
naechste Leser die Kadenz nicht fuer das Ziel haelt.

== BELEG-STUFE ==
BOOT-BEWIESEN: drei Live-Stacks eines Moments, Straggler-Rotation, Proben-
Zensus ueber die volle Episode, Reproduktion bei derselben Frage.
NICHT BEWIESEN: dass dieser Fix die Strandung verhindert. Er ist gebaut,
kompiliert, gebootet (Instrument feuert: "WHOLE value cadenced at 30s"),
health 200, greedy kohaerent -- eine zweite Reproduktions-Sequenz zum
Gegenbeweis ist NICHT gefahren. Wer "behoben" sagt, ueberschreitet die Daten.
randgun added a commit to randgun/sglang that referenced this pull request Nov 15, 2026
Track sgl-kernel-npu 2fd12542, which renames the seven DSV4.1 DSL
operator APIs with a _dsl suffix (the plain Torch names stay reserved
for the DSV4 ops restored by sgl-project#1031). Update _ds41_ops() and every
ds41.* call site so V4.1 goes through quant_lightning_indexer_dsl,
mixed_quant_sparse_flash_mla_dsl, indexer_prologue_k_dsl and friends,
while the V4 fused paths keep their legacy names.
sherdavincl9 pushed a commit to sherdavincl9/sglang that referenced this pull request Nov 27, 2026
…cend A5 PD (sgl-project#1484)

* [Feat] [NPU] dsv4.1: Support DeepSeek-V4.1 on Ascend A5 with CANN ops

Add the DeepSeek-V4.1 low-ratio (1/2) path on Ascend A5: fused compressor, two-level indexer (QLI/QSLI), mixed-quant sparse MLA attention, the ds41 KV/index pools and their PD/HiCache descriptors, plus the A5 graph replay and DSpark verify dispatch. Covered by CPU-runnable unit tests.

* fix lint

* ops

* fix

* fix

* [Fix] [NPU] Disable import-time torch.compile in triton fused_moe helpers

The dsv4.1 model import chain reaches these module-level decorators via fused_moe_triton/__init__ -> moe_runner.triton_utils, so on the Ascend torch build the dynamo rule-map failure poisons deepseek_v4's own import even after the rotary/topk/waterfill sites were guarded, keeping the native dsv4 class unregistered and forcing the fatal Transformers fallback. Follow the same disable=_is_npu pattern used across the other NPU guard sites.

* [Fix] [NPU] Guard remaining dsv4.1-chain import-time torch.compile sites

The registry traceback pinned the next offenders reachable from deepseek_v4 -> deepseek_v2: the class-body decorators in dsa/dsa_indexer (found via dsa_indexer import), dsa/dsa_indexer_kpool (imported at module level by deepseek_v2), the kvfp4 kv-quant helpers (reached via mem_cache memory_pool -> fp4_kv_cache_quant_method), and moe/kt_ep_wrapper (imported at module level by deepseek_v2). All run eager on NPU via the same disable=_is_npu pattern; note class-body (indented) decorators also execute at import time, which the earlier column-anchored sweep missed.

* [Refactor] [NPU] dsv4: centralize KV row formats into NPUDSV4KVLayout

Pools arrive pre-tagged with their row layout (window/compressed tagging) instead of sniffing the generation from compression ratios, and the NPU-only compressed kwarg is dropped from the shared _make_kv_pool signature. Also fixes kernel_page_size being forwarded to the CUDA base __init__ (TypeError at NPU pool construction) and promotes the V4.1 low-ratio index page tables to shared graph buffers with per-bucket row slices.

* revert combine_premix

* refactor(npu): pair DSv4.1 backend with migrated kernel APIs

Resolve the seven DSL operators through sgl_kernel_npu.operators, retaining
the existing AscendC compressor registration and cached resolver. Remove
legacy ops-wheel preloading. This pairs the backend with sgl-kernel-npu
PR sgl-project#964, including its K projection-tail allocation fix.

Size the candidate metadata probe by query rows (batch * tokens_per_req),
so verify buckets provide one candidate length per query. Add a regression
covering decode and verify widths, and replace the stubbed vendor-signature
check with a focused public-route/compressor/cache regression.

Validation: source syntax and lint checks; all seven real call-site APIs
bind against PR964 public signatures; actual metadata allocation method
passes shape-model checks at (B,W)=(1,1),(1,2),(2,6), with negative controls.
These are offline contracts, not a new A5 model or graph-execution test.

* refactor(npu): clarify DSv4.1 metadata probe and resolver tests

Name the candidate metadata probe for its per-query lengths, and explain
that verify tokens each require a record. Reuse the module-level
SimpleNamespace import in the cached resolver.

Name the real resolver, stub modules and expected entries explicitly in the
routing regression, and rename its class to describe the tested contract.
Keep all public entry points, compressor routing, metadata capacity and
cache behavior unchanged.

Validation: normalized AST scope checks, seven-entry routing and actual
call-site signature binding, shape-model metadata checks, Python syntax
and changed-block formatting passed. No new A5 execution or model test.

* fix lint

* fix

* fix

* [Refactor] [NPU] dsv4: name KV row formats by generation and dtype

Rename the NPUDSV4KVLayout V4 members from chip names to row content (A3_BF16 -> V4_BF16, A5_FP8 -> V4_FP8) and give every member a dtype-suffixed value, so the enum reads as (generation, layout). Only v41_fp4 keeps the shared KVLayout spelling; the rest are NPU-only and are always consumed by identity, never by value.

* [Refactor] [NPU] attention: route the DSv4.1 compressor through sgl_kernel_npu

Resolve it as sgl_kernel_npu.operators.attention.compressor_v2 instead of torch.ops.cann_ops_transformer.ds41, so the kernel package owns generation dispatch and its generation/ABI checks. The wrapper takes the same keyword arguments, so the call site is unchanged; the global vendor registration stays in the NPU backend init.

* [Fix] [NPU] Guard dsv4.1-chain torch.compile sites newly reachable after upstream merge

deepseek_v2.py now module-imports dsa_fp4_indexer (dsa_indexer_cls) and deepseek_common.attention_forward_methods (whose forward_mla imports dsa_backend), so the class-body decorators in dsa_fp4_indexer and the bare _compiled_cat decorator in dsa_backend fire during the model registry's bulk import and re-trigger the Ascend dynamo rule-map duplicate. Apply the same disable=_is_npu guard used across the other chain sites.

* [Refactor] [NPU] dsv4: gate per-generation graph metadata allocation

_init_dsv4_graph_buffers and _init_dsv4_graph_metadata unconditionally allocated the V4-only fields (c4/c128 page tables, c4_loc/c128_loc, positions_cmp_padding_c4/c128, the c1a/c4a/c128a/li_quant kernel-metadata buffers and dict keys, c4_topk_indices) and the V4.1-only dsv41_live_mask_buf, so each generation paid for the other's dead buffers on every capture bucket. Gate both sides on _dsv4_has_c4 / _dsv4_has_low_ratio; kernel_metadata starts empty and each generation fills its own keys (the V4.1 dispatch tables already extend it in _init_dsv41_graph_metadata). All consumers were audited to be generation-gated: the CP path reads via getattr(None) defaults with has_c4/has_c128 guards, the refreshers are ratio-gated, and _forward_npu_fused/li_quant only run on the c4 path.

Zero behavior change: the removed fields were never read by the other generation.

* fix

* fix

* [Refactor] [NPU] dsv4: dedupe shared seq scalars and name per-generation replay refresh

start_pos/seqused formulas were duplicated across the V4/V4.1 mode branches;
extract them into _build_seq_metadata_{decode,prefill,verify} and centralize
replay row planning in _refresh_graph_{decode,verify}_rows, renaming the
*_direct helpers to _v4_* so each generation''s owner is explicit.

* [NPU] Align DSV4.1 rebase with upstream quantization and cache contracts

* fix(npu): recognize DSV4 ModelSlim exports without hc_head entries

* feat(npu): add A3 BF16 support for DSV4.1 W8A8

* fix(npu): align aliased seed tracing rules with PyTorch Dynamo

transfer_to_npu aliases CUDA seed functions to NPU functions, which can conflict with PyTorch 2.13 SkipFunctionVariable rules during model import.

Align only manual_seed and manual_seed_all when their objects are aliased and the tracing rules conflict. Update the source NPU rule table for both eager and lazy registration, and invalidate Dynamo rule caches only when changed. Keep torch.compile and NPU graph capture enabled; leave older non-conflicting environments unchanged.

Tests: 7 seed-rule regression tests and 24 A3 backend/cache CPU tests passed. Ascend hardware validation remains pending.

* fix(npu): handle cuda.random aliases in Dynamo seed rules

Check both CUDA seed entry points against their own Skip rules and NPU function identities. This fixes torch_npu 2.13 environments where only cuda.random aliases npu.random, without changing RNG functions or disabling torch.compile.

Add regression coverage for random-only aliases and mismatched rule/alias pairs; retain top-level-only and older-rule coverage. Verified 33 CPU seed, A3 cache and backend tests.

* fix(npu): load DSV4.1 A3 operators from vendor wheels

Resolve selected ops-transformer providers through installed entrypoints while keeping the full-package fallback. Reuse and preload the vendor CompressorV2 kernel without changing state-cache mutation or A5 dispatch.

Add CPU contract tests for vendor imports, failure handling, and cached compressor loading.

* fix(npu): size DSV4.1 A3 C2 state for TP-padded batches

Cover the padded execution batch in the A3 CompressorV2 state bank while preserving real request capacity, bank IDs and A5 allocation. Align the actual request-pool capacity so preallocated request slots remain covered.

Add CPU regressions for TP8 decode padding, state initialization and mapping, preallocated capacity, unchanged A5 storage, and zero-length dummy metadata. Targeted tests: 35 passed. A3 device validation remains required.

* fix(npu): restore QuaRot basis for ModelSlim Engram gates

Load the validated global_rotation sidecar once per rank for explicitly rotated NPU ModelSlim checkpoints. Use the inverse-rotated query only for Engram gating and keep the residual and exported value in their rotated basis.

Preserve native A5 and GPU dispatch when no gate basis is enabled. Add CPU regression coverage for the gate math, sidecar loading, sharing, config normalization, and unchanged paths.

* refactor(npu): use sgl-kernel-npu for DSV4.1 A3 operators

Route SparseFlashMla and its metadata, lightning indexers, and CompressorV2 through the public APIs from sgl-kernel-npu PRs sgl-project#965 and sgl-project#958. Keep the compressor mutation/fake contract and existing A5 dispatch. Avoid standalone ops-transformer registration on A3 to prevent bundled-binding conflicts.

* fix(npu): align DSV4.1 A3 with mainline cache contracts

Omit the nonexistent BF16 index scale region from the new paged buffer descriptors. Keep A5 packed key and scale regions unchanged.

Adapt graph guard tests to the rebased metadata API and cover capture batch propagation plus INT8, FP8 and MXFP4 Engram storage after conflict resolution. Keep these mainline compatibility changes separate from the operator source migration.

* fix(npu): make Engram gate compatible with graph capture

Avoid copysign CPU fallback on NPU by reading the FP32 sign bit through an integer view. Add an Engram gate graph capture and replay regression test.

Validation: verified on Ascend A3 by the user; local Python syntax and diff checks passed. Skipped check-registered-tests because it reports three unrelated existing files without CI registration.
(cherry picked from commit fb4bded)

* feat(npu): support bundled DSpark drafts on DSV4.1 A3

Route A3 draft attention through sgl-kernel-npu with logical sparse indices and BF16 execution. Add C1/C2 target verification metadata refresh and TP padding handling for eager and graph paths, while retaining A5/GPU dispatch.

Map bundled ModelSlim Markov weights and account for each draft stage in the A3 SWA cache budget. Reject unsupported compact verification.

Validation: 94 CPU tests and 1715 subtests passed; Ruff E9/F and git diff --check passed. NPU execution and graph replay require hardware validation.

* fix(npu): unify DSV4.1 DSpark replay across A3 and A5

Share fixed-width verification metadata refresh while retaining A3 TP padding and generation-specific operator/cache contracts. Initialize draft SWA metadata independently of compressed pools, and avoid clearing absent C4 buffers. Preserve packed MXFP4 Engram lookup after the upstream rebase.

Add CPU lifecycle tests for A3/A5 capture, replay, idle/padded batches, stable metadata pointers, and PD cache descriptors. Validated 175 tests and 1719 subtests; NPU and end-to-end PD validation remain pending.

* fix(npu): scope DSpark rebase adjustments to A3

Preserve upstream A5 draft metadata initialization, C4 refresh and verify-row behavior. Keep standalone draft metadata and padding guards only for A3. Defer the unverified A5 MXFP4 Engram lookup change; A3 INT8 storage does not depend on it.

Retain the shared verify pipeline and update CPU contracts to distinguish A3 adaptations from unchanged A5 behavior. Validation: 174 tests and 1719 subtests passed; device validation remains pending.

* [Refactor] [NPU] dsv4: unify verify/seq metadata builders and centralize spec gating

* [Misc] registry: drop exc_info from model import warning

* fix(npu): correct DSV4.1 ModelSlim W4A8 inference

* fix(npu): allow Ascend DeepSeek V4.1 DSpark PD with CP=1

* [Refactor] [NPU] dsv4.1: call the _dsl-suffixed DSL operator APIs

Track sgl-kernel-npu 2fd12542, which renames the seven DSV4.1 DSL
operator APIs with a _dsl suffix (the plain Torch names stay reserved
for the DSV4 ops restored by sgl-project#1031). Update _ds41_ops() and every
ds41.* call site so V4.1 goes through quant_lightning_indexer_dsl,
mixed_quant_sparse_flash_mla_dsl, indexer_prologue_k_dsl and friends,
while the V4 fused paths keep their legacy names.

* fix

* fix

* fix

* [Fix] [NPU] dsv4.1 dspark: pin the draft SWA pool to the V4 row format

A draft worker's rows are read by the V4 sparse-attention op, whose arch35
encoding is chosen at runtime, but the pool inferred its generation from
`compression_ratios` after the builder had emptied that list. The two only
agreed by accident, so a V4.1 target could hand the draft a V4.1 window row
and fail inside the op with "ori_kv must use the selected 608B KV encoding"
at the first graph capture.

Pass the generation explicitly from the NPU draft branch, let the pool prefer
that pin over the ratio list, and validate the resolved row at backend init so
a mismatch names both sides instead of surfacing as a kernel check.

* [Refactor] [NPU] dsv4: resolve the arch35 V4 row width through the kv layout

Rename npu_kv_layout.py to dsv4_kv_layout.py to match the sibling dsv4_*
module names, and let NPUDSV4KVLayout.V4_FP8.kv_info return the runtime
quant path's packed width directly: the pool buffer and the draft-window
validation now share one definition instead of each importing
get_npu_kv_quant_path on its own. Null out V4_FP8's quant_group /
quant_mode / row_alignment -- the runtime owns the V4 encoding, and those
fields were only consumed by the V4.1 epilog-v2 write path.

_validate_draft_window_rows now raises ValueError (assert vanishes under
python -O) and reads the expected width from the SWA pool's own
dsv4_arch35_packed_kv_dim. The rest is comment cleanup across the DSV4
backend and memory pool, and _dsv4_free calls clear_request_scoped_state
directly now that the V4.1 pool always provides it.

* [Fix] ernie55: drop the duplicate add_prefix import

The import appeared twice: once in its alphabetical slot among the sglang.srt.layers imports and once right after the ernie55 import block. Keep the first and drop the second.

* fix

* fix(npu): support unquantized ModelSlim DSpark MoE layers

* fix ci

* fix ci

* [Fix] [NPU] dsv4.1: restrict speculative decoding to DSpark on the static verify layout

DeepSeek-V4.1's low-ratio verify rows are a STATIC request-major rectangle:
_refresh_graph_dsv41_verify_1d derives n = bs * tokens_per_bs and refuses a
batch that does not match. The pre-refactor guard only rejected COMPACT, and
only on arch35; the refactored gate exempted DSpark (the one algorithm V4.1
can actually run) while letting EAGLE through under STATIC. Gate on the
generation instead: V4.1 now requires DSpark and
SGLANG_RAGGED_VERIFY_MODE=static, rejecting every other spec algorithm and
every ragged mode at startup with a message that names both constraints.
_dsv4_is_v41_model carries the generation past a draft worker's emptied ratio
list, which _dsv4_has_low_ratio cannot.

Cover the contract: DSpark under STATIC passes, non-DSpark and DFLASH raise,
DSpark under CAP_ACCEPT/COMPACT raises (matched on the env-var message so the
mode check is pinned as the one that fired), and decode-only runs and V4
models skip the gate. Replace the tautological decode-replay case with
assertions on the real buffers -- decode writes the shared scalars and the c1
rows and leaves the verify-only topk lengths untouched -- and fix the stale
TestVerifyGraphRefresh docstring plus a duplicated assertion.

* [Fix] [NPU] dsv4.1 test: build the cache params the registry expects

TestC128ComponentGating stubbed `params` as a plain namespace carrying
`tree_components=()`, but the registry has not filled that name for a while:
create_unified_radix_cache reads `params.token_to_kv_pool_allocator`, writes
the slots onto `params.tree_slots`, and `tree_components` is a derived property
of that field on CacheInitParams. The stub raised AttributeError on the
allocator, and with `tree_components` pinned to `()` the three cases would have
asserted on an empty tuple anyway -- they have not run since the file landed,
so neither failure was introduced by the DSpark gate.

Build the real CacheInitParams around a static allocator stub
(`storage=None`, so kv_storage_of takes the StaticKVStorage path) and the
window `_static_tree_shape` reads from `params.sliding_window_size`. The
gating is then exercised against the production contract: V4 keeps C128, V4.1
keeps FULL + SWA only, and a req pool without the sidecar never registers the
component.

* fix

* fix ci

* fix

* fix

* use ops from sgl-kernel-npu

* fix ci

* fix(npu): restore architecture helper import in DeepSeek V4 mHC

* [NPU] dsv4.1: div_argmax delegates to the sgl_kernel_npu native op

Replace the two NPU-only Triton kernels (Ascend triton-mlir-opt cannot
parse the two-operand tt.reduce) with the vendor sample op and drop the
CUDA_ONLY registry flag so the metadata matches; the docstring records
the NPU NaN rule. Also fix the A5 mhc combine kernel reference in the
deepseek_v4_mhc docstring (mhc_pre_dpskv4 / cann_recipes_infer_cann920).

* fix lint

* fix ci

* fix

* fix(npu): transfer DeepSeek V4.1 A5 QSLI index cache in PD

* Omit disabled DSpark logit options for the legacy NPU sampler

* Remove branch-only NPU test modules before upstreaming

* Drop unrelated graph capture and MoE test changes

* Use common DSpark PD CP validation for Ascend

---------

Co-authored-by: Kailong Lu <[email protected]>
Co-authored-by: Aki Yang <[email protected]>
Co-authored-by: HEX1A0A <[email protected]>
Co-authored-by: AndyLi429 <[email protected]>
Co-authored-by: HEX1A0A <[email protected]>
Co-authored-by: Even Zhou <[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.

1 participant