Repository navigation
Add MLA gsm8k eval - #1484
Merged
Merged
Add MLA gsm8k eval#1484
Conversation
zhyncs
approved these changes
Sep 21, 2024
timethink
pushed a commit
to timethink/sglang
that referenced
this pull request
Mar 9, 2025
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
Add MLA gsm8k eval in pr test & nightly eval.