lmdeploy icon indicating copy to clipboard operation
lmdeploy copied to clipboard

[Bug] flash_attn_with_kvcache: wrong result with quantized cache and multiple query tokens

Open jeffchen006 opened this issue 2 weeks ago • 3 comments

Describe the bug

flash_attn_with_kvcache accepts multiple query tokens per request. With an int8 or int4 key/value cache, it associates query rows with the wrong requests and leaves later scratch rows unwritten. The reproduction uses two requests and four query tokens per request. Query row 1 returns 2.0 in its first coordinate. Its correct value is 0.0.

The launcher computes seq_len = num_tokens // batch and allocates scratch for every query token. However, the quantized kernel fixes q_seqlen to 1 and loads query row cur_batch. Its stores also address scratch row cur_batch. The final reduction processes every query row, including the unwritten rows.

This path is used by SDAR block decoding. The SDAR model sets the attention block size from dllm_block_length. The CUDA attention backend passes that query length and the selected quantization policy to this function. A configuration with --backend pytorch --dllm-block-length 4 --quant-policy 8 reaches the affected path.

The reproduction supplies exact quantized cache values. Its reference has no quantization error. The cited kernel lines are unchanged on main as of 2026-11-17.

Reproduce

import torch
from lmdeploy.pytorch.kernels.cuda.pagedattention import flash_attn_with_kvcache

dev = "cuda" if torch.cuda.is_available() else "cpu"
torch.set_default_device(dev)
torch.manual_seed(0)
B, S, H, HK, D, BS = 2, 4, 4, 2, 32, 16
q = torch.zeros(B * S, H, D, dtype=torch.float16)
kc = torch.randint(0, 255, (B, BS, HK, D), dtype=torch.uint8)
vc = torch.empty_like(kc)
vc[0] = torch.arange(D, dtype=torch.uint8)
vc[1] = torch.arange(D, dtype=torch.uint8) + 64
sz = torch.zeros(B, BS, HK, 2, dtype=torch.float16)
sz[..., 0] = 1 / 32
table = torch.tensor([[0], [1]], dtype=torch.int32)
lengths = torch.full((B,), BS, dtype=torch.int32)
out = flash_attn_with_kvcache(
    q, kc, vc, cache_seqlens=lengths, page_table=table,
    max_seqlen_q=S, k_scales_zeros=sz, v_scales_zeros=sz, quant_policy=8,
)
# Values are constant along the context. Attention must return that vector.
ref = vc[:, 0].float().div(32).repeat_interleave(H // HK, dim=1)
ref = ref.repeat_interleave(S, dim=0)
print("First coordinate, query rows 0 and 1:", out[:2, 0, 0].tolist())
print("Expected:", ref[:2, 0, 0].tolist())
print("Query row 1 max error:", (out[1].float() - ref[1]).abs().max().item())
assert torch.allclose(out[1].float(), ref[1], atol=1e-3, rtol=0), "Query row 1 uses request 1's cache instead of request 0's cache."

Output:

First coordinate, query rows 0 and 1: [0.0, 2.0]
Expected: [0.0, 0.0]
Query row 1 max error: 2.0
AssertionError: Query row 1 uses request 1's cache instead of request 0's cache.

Expected behavior

Each query token must attend to its own request. All four query rows of request 0 must return the same value vector. Its first coordinate is 0. The next four rows belong to request 1, whose first coordinate is 2. The reference dequantizes the supplied values with PyTorch.

Suggested fix

Pass seq_len to the quantized kernel. Derive each query token and request index as in the unquantized kernel. Use the token index for query loads and all scratch stores.

Versions / environment

Library commit: fc33f69. Source checked: 2026-11-17. torch 2.14.1, triton 3.8.0. Reproduced with Triton's interpreter mode (TRITON_INTERPRET=1). The defect is incorrect query and scratch indexing. CUDA uses the same indices; values read from unwritten scratch depend on the allocator.

jeffchen006 avatar Nov 17 '26 23:11 jeffchen006

Opened a fix: https://github.com/InternLM/lmdeploy/pull/5175

It ports the unquantized kernel's (kv_head, query_token) tiling into _fwd_grouped_split_quant_kernel and indexes query loads plus split-K scratch stores by cur_token instead of cur_batch. The regression test covers int8 and int4 with B=2, S=4 and checks that each query token returns its own request's value vector. Many thanks for the exact reproducer — it made the root cause unambiguous.

YuvrajSinghBhadoria2 avatar Nov 19 '26 15:11 YuvrajSinghBhadoria2

Thanks for picking this up so quickly! I appreciate you checking the token-to-head mapping and adding regression cases for both INT8 and INT4. I’m glad the reproducer helped narrow it down.

jeffchen006 avatar Nov 20 '26 13:11 jeffchen006

Thanks! The fix in #5175 is now marked ready for review. I caught a shape bug in my new regression test setup and pushed a correction in 9793305; CI is currently waiting on workflow approval for the fork PR. Once it lands, your reproducer should pass on both INT8 and INT4 — if you're able to retest against the updated head, that would be very helpful.

YuvrajSinghBhadoria2 avatar Nov 20 '26 13:11 YuvrajSinghBhadoria2