Skip to content

fix(qwen): mask native KV attention for FP16 and BF16 - #1035

Merged
chaofengw-nv merged 2 commits into
NVIDIA:mainfrom
yifeif-nv:fix/qwen-native-kv-explicit-mask
Aug 26, 2026
Merged

chaofengw-nv merged 2 commits into
NVIDIA:mainfrom
yifeif-nv:fix/qwen-native-kv-explicit-mask

Conversation

@yifeif-nv

@yifeif-nv yifeif-nv commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

Background

PR #959 fixed Qwen3 native-KV routing and precision plumbing, but it did not change the TensorRT attention input contract. FP16 still reached IAttention with Q/K/V plus key_value_lengths (four live inputs). On the affected TensorRT 11.1/11.2 kernels, that FP16 wrapper rejects the graph with Expected 3 live inputs, got 4.

The same native length input has a separate BF16 failure mode on SM86/SM121: a bounded Qwen3 build can succeed but attend into the inactive fixed-cache suffix and silently generate wrong tokens.

This PR supplies a builder/runtime workaround for both supported native Qwen precisions while retaining fixed-capacity IKVCacheUpdate, aliased cache storage, and fused attention.

Refs #955 and #959.

Exit Criteria

  • Qwen3 BF16 with cache capacity 16384 masks the inactive cache suffix and produces correct text on an affected target.
  • Qwen3 FP16 with cache capacity 16384 builds and produces correct text on an affected target.
  • Both paths retain non-decomposable fused prefill/decode attention and native cache aliasing.
  • Mixed FP16 bundles declare their actual cache dtype so the runtime allocates and validates the correct storage.
  • Existing same-precision native bundles retain the v1 runtime contract.
  • Unqualified affected-target capacities above 16384 fail before TensorRT with an actionable error.
  • FP8 stays on its qualified quantized route, and FP32 continues to fail closed for native KV.
  • Exact BF16 and FP16 full-model validation on SM86 passes before the draft is marked ready.

Implementation

  • Build one shared additive [1, 1, Sq, K] causal active-prefix mask and omit attention.key_value_lengths on affected SM86/SM121 + TensorRT 11.1/11.2 builds.
  • Keep BF16 entirely BF16 on that path.
  • For FP16, keep embeddings, projections, MLPs, logits, and the surrounding residual stream FP16, but:
    • cast RoPE-processed Q and the current K/V updates to BF16;
    • store the native KV cache in BF16;
    • execute explicit-mask fused attention in BF16;
    • cast the attention context back to FP16 before the output projection.
  • Emit native-KV contract v2 with native_kv_cache_dtype=bf16 only when cache precision differs from model precision. The runtime resolves, allocates, and validates that declared dtype. Same-precision FP16/BF16 bundles remain contract v1.
  • Cap affected prefill chunks at 64 tokens to retain the validated fused prefill tactic.
  • Reject affected-target cache capacities above 16384 with: Rebuild with --max-cache-length 16384.
  • Leave FP8, FP32, other SMs, and other TensorRT releases on their existing routing policies.

Validation

Automated validation:

  • PYTHONPATH=python python3 -m pytest -q tests/e2e/models/qwen/test_qwen_builder_policy.py tests/builder/test_qwen_llama_native_kv_attention.py tests/builder/test_graph_ops_native_attn.py: 76 passed. This covers policy, routing, real TensorRT topology, explicit-mask numerics, and graph ops. The numeric regression executes both pure BF16 and FP16-model/BF16-attention graphs with a poisoned inactive cache suffix and verifies the causal active-prefix result.
  • PYTHONPATH=python python3 -m pytest -q tests/e2e/models/qwen/test_qwen_builder_engine.py: 22 passed, including real FP16/BF16 x prefill/decode split engines.
  • ./build-sm86/test_qwen_native_kv_cache && ./build-sm86/test_qwen_native_kv_cache_dtype && ./build-sm86/test_qwen_sampler && ./build-sm86/test_qwen_tensor_names: passed. The new dtype test covers v1 FP16/BF16 fallback, v2 explicit FP16/BF16 selection, and missing/invalid v2 declarations.
  • git diff --check origin/main...HEAD: passed.
  • Community CPU runs source quality, ownership/impact, docs, and selected C++/Python units against the exact pull-request merge revision; its current-head result is the source-quality evidence for this PR.

SM86 + TensorRT 11.1.0.106 full-model FP16 validation:

  • Built Qwen/Qwen3-0.6B --precision fp16 --max-cache-length 16384 successfully.
  • Split bundle: 2593.8 MB total (1441.1 MB prefill, 1152.8 MB decode).
  • Bundle metadata: model precision FP16, native-KV contract v2, cache dtype BF16.
  • README prompt returned Paris; plain prompt continued with Paris. The capital of France is also.
  • A prompt spanning three 64-token prefill chunks produced the same correct completion as the BF16 baseline.
  • Engine inspection found all 28 decode layers using _gemv_mha_v1 and all 28 prefill layers using _gemm_mha_v2.
  • Warm benchmark: 50.50 ms prefill, 15.75 ms decode, 126.97 token/s.
  • BF16 baseline from the same setup: 49.93 ms prefill, 15.08 ms decode, 132.59 token/s. Repeated mixed-FP16 runs ranged across both sides of that baseline, so no material steady-state regression was observed.
  • The default 40960 build now fails before TRT with the requested --max-cache-length 16384 guidance.

Targeted SM86 TensorRT 11.1/11.2 attention probes also built and executed correctly with fused tactics. SM120/SM121 was not directly exercised for this PR; its applicability there is guarded by the same release/SM allowlist and covered by the topology and numeric regression tests.

Notes For Future Readers

  • “All precisions” here means both supported unquantized native-KV precisions: FP16 and BF16. FP8 uses a separate qualified quantized graph; FP32 is unsupported for native KV and remains fail-closed.
  • The affected FP16 workaround is intentionally mixed precision. The model remains FP16, but native attention and its cache are BF16 because the affected FP16 wrapper cannot accept the required fourth mask input.
  • This qualifies cache capacities through 16384, not the model-default 40960 capacity. The latter has no validated dedicated fused tactic on these releases and now fails with an actionable message.
  • One cold first-prefill run on SM86 showed roughly 50-60 ms additional setup/tactic cost; warm steady-state timings were comparable.
  • CUDA graph capture falls back on this SM86/TRT setup for both the existing BF16 explicit-mask engine and the mixed FP16 engine, so that behavior is not introduced by the FP16 boundary.
  • The workaround is release/SM allowlisted and should be requalified or removed when a public TensorRT release fixes the native kernels.

TensorRT 11.1 and 11.2 can apply key_value_lengths to the inactive cache suffix on SM86 and SM121, so bounded Qwen3 builds succeed but generate incorrect tokens.

On affected BF16 targets, construct an explicit active-prefix causal mask, preserve IKVCacheUpdate and fused-only attention, and cap prefill chunks at 64 tokens. Other TensorRT releases, SMs, and FP16 remain unchanged.

Refs NVIDIA#955

Signed-off-by: yifeif-nv <[email protected]>
Run affected FP16 models through a BF16 native attention and KV-cache boundary while preserving FP16 model projections and outputs. Version the mixed cache contract, retain v1 for same-precision bundles, and fail closed above the qualified cache capacity.

Signed-off-by: yifeif-nv <[email protected]>
@yifeif-nv
yifeif-nv force-pushed the fix/qwen-native-kv-explicit-mask branch from 152ac4a to 19729fb Compare August 26, 2026 00:44
@yifeif-nv yifeif-nv changed the title fix(qwen): mask native KV attention explicitly fix(qwen): mask native KV attention for FP16 and BF16 Aug 26, 2026
@yifeif-nv yifeif-nv added the run-internal-ci Maintainer-approved dispatch to internal CI label Aug 26, 2026 — with ChatGPT Codex Connector
@github-actions github-actions Bot removed the run-internal-ci Maintainer-approved dispatch to internal CI label Aug 26, 2026
@yifeif-nv
yifeif-nv marked this pull request as ready for review August 26, 2026 01:09
@chaofengw-nv
chaofengw-nv merged commit 32ec66b into NVIDIA:main Aug 26, 2026
9 checks passed
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.

2 participants