TensorRT-LLM icon indicating copy to clipboard operation
TensorRT-LLM copied to clipboard

[PyTorch backend][encoder-decoder] KvCacheConfig(dtype="fp8") overruns the cross-attention KV pool: illegal memory access or silently wrong output unless the pool is 2x the required size

Open lminer opened this issue 1 month ago • 2 comments

Summary

With an encoder-decoder model on the PyTorch backend, setting the KV cache dtype to fp8 makes the cross-attention cache access memory beyond its pool. A request only succeeds when the cross-attention pool holds at least twice the blocks the in-flight requests need. Below that the process either dies with CUDA error: an illegal memory access was encountered or, when the stray access lands in other mapped memory, returns wrong tokens with no error. The same pool sizes work with the default cache dtype.

Environment

  • Images: nvcr.io/nvidia/tensorrt-llm/release:1.3.0rc29 and nvcr.io/nvidia/tensorrt-llm/release:1.4.0rc0.dev202610040000 (both reproduce)
  • GPU: NVIDIA L4 (24 GB), driver 595.91.07; AWS g6.2xlarge
  • Model: google/flan-t5-base, weights loaded as bf16
  • LLM(backend="pytorch", ...), block reuse off, no CUDA graphs

Reproduction

The prompt is 483 tokens, i.e. 16 blocks of 32 tokens in the cross-attention pool. With cross_kv_cache_fraction=0.5, max_tokens=768 gives a 24-block pool and max_tokens=1024 a 32-block pool (the log line Max KV cache blocks per sequence: 16 [window size=512], tokens per block=32, primary blocks=24 confirms the sizes).

docker run --rm --gpus all --ipc=host -v $PWD:/w nvcr.io/nvidia/tensorrt-llm/release:1.3.0rc29 \
  python3 /w/fp8_cross_kv_repro_t5.py fp8 768     # crashes on the first request
docker run ... python3 /w/fp8_cross_kv_repro_t5.py fp8 1024    # decodes
docker run ... python3 /w/fp8_cross_kv_repro_t5.py auto 768    # decodes (default cache dtype, same pool)
KV dtype max_tokens cross pool blocks blocks needed result
fp8 768 24 16 CUDA error: an illegal memory access was encountered
fp8 1024 32 16 OK
auto 768 24 16 OK

After the error the process does not exit by itself; it has to be killed.

fp8_cross_kv_repro_t5.py:

"""Encoder-decoder model on the PyTorch backend: an FP8 KV cache overruns the cross-attention pool.

    python3 fp8_cross_kv_repro_t5.py <kv dtype: fp8|auto> <kv max_tokens>

The prompt is ~480 tokens, i.e. 16 blocks of 32 tokens in the cross-attention pool.
"""
import json
import os
import sys

from huggingface_hub import snapshot_download

from tensorrt_llm import LLM, SamplingParams
from tensorrt_llm.llmapi import KvCacheConfig


def main():
    kv_dtype, kv_tokens = sys.argv[1], int(sys.argv[2])
    # The backend takes the weight dtype from the checkpoint's config.json, so write a bf16 copy.
    src = snapshot_download("google/flan-t5-base", allow_patterns=["*.json", "*.model", "model.safetensors"])
    ckpt = "/tmp/flan-t5-base-bf16"
    os.makedirs(ckpt, exist_ok=True)
    for name in os.listdir(src):
        if name != "config.json" and not os.path.exists(f"{ckpt}/{name}"):
            os.symlink(os.path.realpath(f"{src}/{name}"), f"{ckpt}/{name}")
    config = json.load(open(f"{src}/config.json"))
    config["torch_dtype"] = config["dtype"] = "bfloat16"
    json.dump(config, open(f"{ckpt}/config.json", "w"))

    llm = LLM(
        model=ckpt,
        backend="pytorch",
        max_batch_size=1,
        max_beam_width=1,
        max_input_len=512,
        max_seq_len=2048,
        kv_cache_config=KvCacheConfig(
            enable_block_reuse=False, max_tokens=kv_tokens, cross_kv_cache_fraction=0.5, dtype=kv_dtype
        ),
        cuda_graph_config=None,
    )
    prompt = "summarize: " + "The quick brown fox jumps over the lazy dog near the river bank. " * 30
    print("prompt tokens:", len(llm.tokenizer.encode(prompt)), flush=True)
    params = SamplingParams(max_tokens=32)
    for i in range(3):
        out = llm.generate(prompt, params)
        print(f"request {i}: {list(out.outputs[0].token_ids)[:12]} {out.outputs[0].text[:60]!r}", flush=True)
    print("OK", kv_dtype, kv_tokens)
    llm.shutdown()


if __name__ == "__main__":
    main()

More than one request in flight

The same rule holds with several requests submitted together. Measured on rc29 with a second, larger encoder-decoder model, a batch of requests that needs 752 blocks in total:

cross pool blocks result
768 illegal memory access (also on the 1.4.0 nightly)
896 illegal memory access
1,024 no error, wrong output: every request runs to max_tokens, none matches the same request decoded alone
1,280 illegal memory access
1,536 OK

So the threshold is 2 x 752 = 1,504 blocks. With the default cache dtype, 768 blocks are enough. Admitting the requests one at a time only helps because fewer are then in flight together.

With CUDA_LAUNCH_BLOCKING=1 that run reports the failure in the cross-attention context pass:

  File ".../tensorrt_llm/_torch/attention/cross_attention.py", line 268, in forward
  File ".../tensorrt_llm/_torch/attention/backends/trtllm.py", line 2330, in forward
  File ".../tensorrt_llm/_torch/attention/backends/fmha/fallback.py", line 122, in forward
    thop.attention(
RuntimeError: [TensorRT-LLM][ERROR] CUDA runtime error in cudaStreamIsCapturing(stream, &status): an illegal memory access was encountered (../include/tensorrt_llm/common/cudaUtils.h:157)
  tensorrt_llm::common::op::AttentionOp::enqueueContext<__half, tensorrt_llm::kernels::KVBlockArray>(...)

Expected

Either the FP8 cross-attention cache stays inside a pool sized for the requests (as the default dtype does), or the configuration is rejected for encoder-decoder models. An out-of-range access should not be able to return wrong tokens silently.

Guess at the cause

The 2x factor suggests the cross-attention pool is allocated at one byte per element (FP8) while the cross-attention kernel addresses it with a two-byte element size. Not verified in the source.

Also seen

With the FP8 cache and a large enough pool, on the larger model the first request after start-up returns different tokens from the identical request sent again (every run). This does not happen with the default cache dtype.

lminer avatar Oct 05 '26 15:10 lminer

Hi @lminer , I’d like to investigate this issue. I’ll first look into how the FP8 cross-attention KV-cache pool is allocated and how it is accessed by the PyTorch attention backend, and try to understand the reported 2x memory behavior. If I can reproduce or confirm the root cause, I’ll work on a regression test and a focused fix.

navenavelimargam avatar Oct 05 '26 16:10 navenavelimargam

The 2× factor comes from the cross-attention module, not the pool allocator.

CrossAttention.__init__ (tensorrt_llm/_torch/attention/cross_attention.py) builds its attention backend with create_attention(...) but does not pass quant_config, and create_weights never calls update_quant_config. The self-attention module does both. So the cross-attention op's quant mode has no FP8-KV bit, getKvCacheElemSizeInBits returns 16, and the op addresses the cross pool at two bytes per element, while _create_cross_kv_cache_manager allocated it at one byte per element from the same model config. Reads and writes use the same doubled stride, which is why the output is right whenever the pool holds at least twice the blocks a request needs and overruns below that.

Passing the config through fixes the overrun (the fp8, 768-token row in the table above decodes on an L4 with release:1.4.0rc1). It exposes a second problem on 16-bit models: the fused context FMHA for cross attention always reads K/V back from the paged cross cache (Q_PAGED_KV), but fmhaParams.dataTypeKv is switched to E4M3 only when paged-context FMHA is on, so it reads the now correctly sized FP8 pool as bf16 and decodes garbage. Forcing paged-context FMHA is not an option on sm89: the E4M3 context kernels with 16-bit output exist only for head size 192. Routing cross attention with a quantized cache to the unfused context path (which reads K/V from the 16-bit workspace and writes the cache through the quantizing transpose) gives output identical to the default cache dtype at the tight pool size; this was checked by running flan-t5-base in fp32, where every layer already takes the unfused path.

The linked PR carries the module fix, that fallback in AttentionOp::initialize, and a test that builds CrossAttention with an FP8 KV quant config. With both changes rebuilt for sm89, the bf16 flan-t5-base fp8/768 run decodes the same token ids as the default cache, all three requests agree, and the 14 FP8 cross cases of the attention backend matrix (previously filtered out) pass.

lminer avatar Oct 25 '26 04:10 lminer