Repository navigation
misc: add compute capability in check_env - #965
Merged
Merged
Conversation
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 28, 2026
…te the group, and let the guard speak sgl-project#965 -- THE CO-DERIVED MATCH TUPLE. `Req.init_next_round_input` reads the radix tree ONCE and unpacks that single `match_result` into EIGHT attributes in one tuple assignment: prefix_indices, last_node, last_host_node, best_match_node, host_hit_length, swa_host_hit_length, mamba_host_hit_length, mamba_branching_seqlen. One reading of one geometry wearing eight names. `truncate_prefix_to` moves the prefix they were derived from. Its own docstring says why that matters -- "the geometry was DERIVED from the prefix that just moved, so it is now a stale reading rather than a report" -- and that sentence is true, word for word, of every field in the tuple. It wrote prefix_indices, and over two separate windows, each discovered by a boot, cache_protected_len (sgl-project#930) and extend_range (sgl-project#958). Six were left standing. This is the complete sibling sweep those two never got. NOTHING RE-DERIVES IN BETWEEN. scheduler.py calls init_next_round_input (all eight derived), both arms of the `pp_size > 1` fork call truncate_prefix_to, then adder.add_one_req reads them. No match_prefix on that path. WHAT THE STALE READINGS DO, at PrefillAdder.add_one_req: * `real_input_tokens = cand_extend_input_len - req.host_hit_length` subtracts a host hit no longer part of this prefix, under-counting against the budget; * `needs_host_load_back()` is still true, so init_load_back runs on a stale best_match_node/host_hit_length and does `prefix_indices = torch.cat([prefix_indices, new_indices])` -- leaving `[0, told)` then `[L_dev, L_dev+H)` with a HOLE between, while prepare_for_extend sizes the cross-stage tensor off len(prefix_indices) as though it were contiguous. The silently-wrong-context class; * that branch then sets `cache_protected_len = prefix_len`, re-raising the exact value the truncation lowered nine lines earlier -- undoing sgl-project#930. FIXED AS ONE CONTRACT, not a seventh one-field patch, because two of the eight were already bought one at a time by two boots. The ratchet (`test_every_co_derived_field_is_accounted_for`) reads the producer tuples from the AST -- not by grep, since a grep needs a name and the whole point is a field nobody has thought of yet -- and FAILS when a ninth joins, telling the author to decide TRUNCATED / CLEARED / HANDLE. Planted-ninth-field proof: it names `newly_added_ninth_reading`. `last_node` IS NOT NULLED, and that asymmetry is deliberate: it is not a reading but a RESOURCE HANDLE holding an outstanding inc_lock_ref, and this attribute is the only surviving reference to it. Nulling it would leak the ref and make the node permanently unevictable -- a defect that already exists on the PP void path (`_release_dynamic_chunk_probe` frees rows without cache_finished_req / dec_lock_ref, unlike schedule_batch.py:2170-2175 and disaggregation/prefill.py :1159-1161, which do). Registered, NOT fixed here. A NO-OP TRUNCATION STILL INVALIDATES NOTHING. My first test asserted the opposite; the invalidator's own documented rule -- "a no-op truncation leaves a valid geometry valid, clearing it there would void healthy passes for nothing" -- is right, and clearing there would discard a host hit every rank still holds. The test was inverted to pin the documented behaviour instead of contradicting it. sgl-project#967 -- THE sgl-project#959 GUARD WAS UNMEASURABLE. It is closed by two bare `return AddReqResult.OTHER` statements. A refusal that leaves no trace is indistinguishable from a scheduler that simply built nothing, which is precisely the state the sgl-project#963 investigation spent a boot separating by hand out of per-rank coverage databases. Unconditional per-site counter plus a rate-limited `[sgl-project#967] SECOND CONTINUATION REFUSED` line, following the neighbour that already got this right (`_note_seam_chunk_refused`: first three, then every thousandth). Module-level, because PrefillAdder is rebuilt every pass and an instance counter would reset before anyone could read it. THE TWO GUARDS ARE IN DIFFERENT METHODS -- add_one_req_ignore_eos:1692 and add_one_req:1935 -- and my first wiring pin inspected only add_one_req, so it measured nothing and failed on the UNMUTATED tree. That is how the mistake was caught. Rewritten to walk the module AST, and it now names the offending line number when a guard's counter is stripped (proof: "guard(s) at line(s) [1935] return without counting"). The site labels are the method names. CAN-FAIL, read rather than asserted: sgl-project#965 clearing withdrawn -> 8 failed, one per field, each naming its own field sgl-project#965 ninth field planted -> ratchet names it sgl-project#967 one guard's note stripped -> wiring pin names line 1935 NUMBERS, scripts/gate_tier2_partitioned.py, CVD="" : BEFORE 2 genuine (test_collective_family_siblings_610.py x2), 685.00 s AFTER 2 genuine (the same two), 580.49 s, 358 modules count probe 2 named == 2 summary, SUBFAILED and ERRORS included truncation family + prefill adder + schedule_policy suites: 54 passed ruff: schedule_batch.py 45 before / 45 after, schedule_policy.py 21 / 21, both new test files clean TICKET_961_WINDOW.md gains section 8: the "race" of section 7 is NOT a race (ServerArgs byte-identical, the LOAD ARM differed -- 8422 chunked vs 2822 sub-chunk, and an over-one-chunk prompt forces a chunked_req onto every rank, so Arm A masks the defect), and the acceptance now counts flip EPOCHS and phase=tp BATCHES SEPARATELY: 3+3 "both directions" was 3 RANKS confirming ONE epoch, and no batch ever ran phase=tp, so every post-flip guard's green was vacuous. NOT CLAIMED: no boot, no metal, no effect measurement.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Aug 28, 2026
…, not at the exits Boot 8 died 25s into load: prepare_for_extend's sgl-project#965 invariant (len(prefix_indices) == extend_range.start, asserted at schedule_batch.py:3262) failed on PP0. R11 rooted the writer pair, refuting both suspects (neither the sgl-project#944 told=0 terminator -- it took its report-only branch -- nor the sgl-project#987 adopt, which moves only the fill): the host load-back in PrefillAdder.add_one_req grows prefix_indices in place and is followed by budget/align/sgl-project#967 early returns that never reach set_extend_range; reachable because the waiting_queue loop carried no membership guard, so a request already resident in can_run_list (the void family's deliberately preserved co-residency) was visited a second time, its prefix moved, and the bail-out left the first visit's extend_range behind it. Fix, the sgl-project#965 lesson (one junction, never per-branch bail patches): re-derive Range(prefix, prefix) IMMEDIATELY at the mutation -- every current and future early return inherits a consistent parked shape automatically; the success paths overwrite it with the real range as before. Plus the identity membership guard at the loop head (skip census 'already_in_batch'; identity not rid -- two objects with one rid are a different defect and must not be masked). Plus the sgl-project#988 LOADBACK instrument line (module-level, rate-limited). Sibling class registered as ONE posten, not fifteen: 11 further prefix_indices reassignments without same-function re-derive across the cache stash paths (R11 sweep; they run where the next admission re-derives, so not reachable as this crash). Execution proof: import smoke green; the load-back ran on every cache-hit admission in boot 8 (FILL-ADOPT and cached_pos=8 prove the hit path hot); the guard sits in the loop that produced boot 8's crash batch. Boot 8's collapse numbers stand: unexec 513 -> 10, abort net 6x bounded, batches and cached at family bests -- this closes the last named layer of that boot.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Aug 28, 2026
…boot 8, at the mutation sgl-project#988 shipped 56 lines with no tests. Unlike sgl-project#980 this one admits a genuine behavioural red-first: the arms name no symbol it introduces (set_extend_range predates it) and assert sgl-project#965's co-derived invariant itself -- extend_range.start == len(prefix_indices), which prepare_for_extend asserts at the batch boundary. The specimen is boot 8's: PrefillAdder's host load-back grows prefix_indices in place, and before sgl-project#988 went on to the budget checks without touching extend_range, so every early return below that line left the previous visit's range behind a moved prefix. The arms drive a bail-out that happens AFTER the load-back and assert the invariant on the way out, deliberately not pinned to one specific return -- the fix's argument is that re-deriving at the mutation makes every current AND FUTURE exit inherit a consistent shape, and per-branch patches are how sgl-project#965 was paid for twice. An arm pinned to one exit goes stale the moment another is added. PICKING THAT BAIL-OUT TOOK A WRONG TURN, recorded in the file. add_one_req carries TWO near-identical 'rem_chunk_tokens is None and input_tokens >= rem_input_tokens' returns, one before the _lock_node block and one after. Configuring for the input budget hits the FIRST, so the prefix never moves and the file measures nothing -- caught only by the precondition assert, which is exactly what it is for. Nor can budget separate them: the post-load-back input_tokens is SMALLER than the pre one, so any budget tripping the second has already tripped the first. The truncation path (chunk budget 0) is reachable only after the load-back, and that is the one used. MEASURED, same file: 4ea93b8 (pre-sgl-project#988): 2 failed, 2 passed 8380555 (post) : 4 passed The reds read 'the prefix advanced to 4096 and extend_range still starts at 0' and '(0, 8422) != (4096, 4096)'. The two pre-fix PASSES are load-bearing: the prefix-preservation arm and the can-fail hold on the old tree too, so the failures are the defect and not a broken harness. Chain at 8380555: 164 defs / 164 passed across eleven suites.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Aug 29, 2026
`set_extend_range(prefix, prefix + new_len)` means
`extend_range.start == len(prefix_indices)`, and `prepare_for_extend` slices
`fill[len(prefix) : extend_range.end]`. So
len(input_ids) = end - len(prefix) = end - start = new_len
holds ONLY while `start == len(prefix_indices)`. That is one condition, and
`prepare_for_extend` is the one place that reads both halves.
WHY THIS REPLACES THE ENUMERATION. There are 24 writers of `extend_range`
and 27 of `prefix_indices` across five directories. Two were read -- the
sgl-project#791 truncation and the #797b park -- and both carry the group; the park
does so precisely because it derives its shape FROM the prefix in the same
call. But 2 of 24 is not a basis, and reading the other 22 still could not
show the case where every writer is individually correct and their ORDER
breaks the pair. A condition at the consumer covers all 51 writers and that
case as well. Third time today that checking the consumer beat enumerating
the producers.
IT IS ALSO THE MEASUREMENT. The guard reports 254 rows against 301 tokens;
this decomposes the 301 into its two terms, per rid, on every rank. If
`end` or `len(prefix)` stands differently on the sender, the root is read
rather than inferred -- and the rid then names which writer touched it last,
so the enumeration survives as a fallback reduced to one entry.
Discipline unchanged, and each clause was paid for in this window: counter
at the event, emission in `pp_ring_note` (independent of this probe, its
execution on this config established), no hit filter, `seen` and `breaks`
always printed so a zero is distinguishable from a never-run, and -1 as a
sentinel because 0 is a legitimate break value.
Predictions recorded before the boot, both directions. A: `break == 0`
everywhere, which puts the divergence in the READ or the TIMING rather than
the setting -- the first question of this window an enumeration cannot
reach. B: `break != 0` somewhere, which is the root. I expect A weakly, and
say why: the coupling is deliberately built at the truncation junction
("sgl-project#965 THE WHOLE CO-DERIVED GROUP, AS A GROUP"), but that is an argument
from 2 of 24, and I have been wrong twice in this window reasoning from a
subset.
The 47 will not be computed into anything either way. The question is
whether the invariant breaks.
Evidence: desk. py_compile on both files; the module bridge imports; the
invariant arithmetic checked on a holding and a broken case. Belegstufe:
DESK-BEWIESEN.
efschu
pushed a commit
to efschu/htsglang
that referenced
this pull request
Aug 31, 2026
…old decide HOW MUCH, not whether Three corrections, two of them to defects in my own slice that boot 2 exposed. PREFIX-KEY KEYING (the reason boot 2 returned 0 applied load-backs). The fact was keyed by rid, but a request reaches the load-back site EXACTLY ONCE and only learns the extent during that visit -- measured: 5 rids x 3 ranks, every rid deferring once (occurrence=1..5 per rank). So a rid-keyed fact is always one visit too late for the rid that named it. And the warm hit is by definition a DIFFERENT request: the cell's mid_cold/mid_warm/mid_warm2 carry identical content under three distinct rids. Keyed by offered_prefix_key the extent travels across rids, across cutovers and across the one-lap lag at once. Keyed on the FULL FILL, not the device match, because offered_prefix_key returns None for prefix_len<=0 and the device match is measured as 0 on exactly the warm path this serves. S1 -- TOLD DECIDED *WHETHER*, NOT *HOW MUCH* (silently wrong, would have reintroduced the death class one layer down). init_load_back consumes host_hit_length only as a boolean trigger (unified_radix_cache.py:4981-4988); the amount returned is this rank's LOCAL node run at :4990, and load_back() never sees the number. Without a clamp, "every rank applies the same number" was unbacked -- each rank grew by its own local amount, which is the 1815081d46 divergence. And the skew is the NORMAL case, not an edge: the extent is published one lap before use and keyed by content, so it is stale-low by construction (same rid measured 1215 -> 1216 -> 2114). Now clamped at the caller to exactly told, with a loud refusal when a rank cannot even reach it. Clamp rather than refuse because stale-low is the safe direction: fewer revived tokens is more recompute, never more memory. Gated on pp_load_back_told, so pp_size<=1 stays byte-for-byte upstream. F1 -- A DOCSTRING CLAIM THAT THE CODE DID NOT BACK, retracted rather than left to be read as a guarantee. It said "the first chunk computes without the prefix and every later chunk honours it". The only consumer is in add_one_req; add_chunked_req has no load-back site, so later chunks of an already-admitted request do NOT consume it. Deliberately not mirrored there: that would put a second prefix mutation on the chunked path, the seam sgl-project#965/sgl-project#988 record as having already cost a boot. What is actually paid is now stated: the request that discovers an extent never benefits from it; the next request over the same content does. Plus the success instrument the chain was missing (sgl-project#968 LOAD-BACK PROMOTED at the promote site). Until now there was only a failure marker and an application marker, so "0 applied" could not be attributed to a missing publish, a missing hop or a missing consume. Desk checks: imports; clamp present, gated, and ordered before the prefix growth; clamp arithmetic yields exactly told; prefix key content-stable, length-sensitive, None at prefix_len=0, and STABLE ACROSS PYTHONHASHSEED (ranks are separate processes, so a builtin hash would disagree only on multi-process runs); codec round-trip and width tolerance at row widths 12/11/10. Lifecycle table recorded for all seven new states incl. deleters and their separating events -- effective is deleted by the SPEND, not by a clock or an epoch. Ruff finding set unchanged (172/172).
AndyLi429
pushed a commit
to AndyLi429/sglang
that referenced
this pull request
Nov 12, 2026
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.
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
inspired by flashinfer-ai/flashinfer#426 (comment)
Modification
as titled
Checklist
pre-commit run --all-filesor other linting tools are used to fix potential lint issues.