vllm - ✅(Solved) Fix [Bug]: ExampleConnector fails to inject KV cache on CPU [1 pull requests, 1 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
vllm-project/vllm#43059Fetched 2026-05-20 03:40:08
View on GitHub
Comments
1
Participants
2
Timeline
3
Reactions
0
Author
Participants
Timeline (top)
commented ×1cross-referenced ×1labeled ×1

Error Message

num_pages, page_size = layer.shape[1], layer.shape[2] # same error

Root Cause

The CPU attention backend (vllm/v1/attention/backends/cpu_attn.py:93) uses a 5D KV cache:

def get_kv_cache_shape(...):
    return 2, num_blocks, num_kv_heads, block_size, head_size

The else branch assumes 4D [2, num_pages, page_size, head_dim]. On CPU:

  • shape[2] = num_kv_heads (e.g., 2), NOT page_size (e.g., 16)
  • reshape(2, 128*2, -1) conflates blocks with heads
  • [:, slot_mapping, ...] writes to completely wrong positions

This corrupts the KV buffer. Even if Bug 1 is fixed, the loaded data lands in wrong memory locations → garbage output.

vllm-decode-logs-bug2.txt vllm-decode-logs-bug1.txt

Fix Action

Fix / Workaround

CPU Info

Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 40 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 32 On-line CPU(s) list: 0-31 Vendor ID: GenuineIntel Model name: Intel Xeon Processor (Cascadelake) CPU family: 6 Model: 85 Thread(s) per core: 2 Core(s) per socket: 8 Socket(s): 2 Stepping: 6 BogoMIPS: 4788.62 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch cpuid_fault ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves arat vnmi pku ospke avx512_vnni md_clear arch_capabilities Virtualization: VT-x Hypervisor vendor: KVM Virtualization type: full L1d cache: 1 MiB (32 instances) L1i cache: 1 MiB (32 instances) L2 cache: 64 MiB (16 instances) L3 cache: 32 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-15 NUMA node1 CPU(s): 16-31 Vulnerability Gather data sampling: Unknown: Dependent on hypervisor status Vulnerability Indirect target selection: Mitigation; Aligned branch/return thunks Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Mitigation; Enhanced IBRS Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Not affected

PR fix notes

PR #43088: [Bugfix] ExampleConnector fails to inject KV cache on CPU.

Description (problem / solution / changelog)

Purpose

This PR addresses two bugs in the ExampleConnector:

  • Fixes KV Injection Bypass on Zero Local Compute (attn_metadata is None): When a request's tokens are entirely available externally, kv_connector_no_forward intentionally passes a None context via set_forward_context(None, vllm_config). Previously, start_load_kv incorrectly treated this None value as an error condition and exited early. This prevented the prefill worker's KV data from being injected into the paged buffer, forcing the decode stage to generate from an empty context (leading to garbage output).

  • Fixes Attention State Corruption on CPU Backend (5D Layout Misalignment): The tensor manipulation logic in inject_kv_into_layer and extract_kv_from_layer assumed a 4D KV cache structure layout as its fallback. Its reshape logic (2, num_pages * page_size, -1) aligns correctly with standard 4D formats and 5D Flash/ROCm backends. However, it breaks on the CPU backend's native 5D layout: [2, num_blocks, num_kv_heads, block_size, head_size]. The current reshape pattern conflates memory blocks with attention heads, writing data to incorrect positions and corrupting the attention state.

Fix #43059

Changed files

  • vllm/distributed/kv_transfer/kv_connector/v1/example_connector.py (modified, +80/-14)

Code Example

ollecting environment information...
==============================
        System Info
==============================
OS                           : Ubuntu 22.04.5 LTS (x86_64)
GCC version                  : (Ubuntu 12.3.0-1ubuntu1~22.04.3) 12.3.0
Clang version                : Could not collect
CMake version                : Could not collect
Libc version                 : glibc-2.35

==============================
       PyTorch Info
==============================
PyTorch version              : 2.11.0+cpu
Is debug build               : False
CUDA used to build PyTorch   : None
ROCM used to build PyTorch   : N/A
XPU used to build PyTorch    : N/A

==============================
      Python Environment
==============================
Python version               : 3.12.13 (main, May  4 2026, 21:09:48) [Clang 22.1.3 ] (64-bit runtime)
Python platform              : Linux-5.14.0-611.54.1.el9_7.x86_64-x86_64-with-glibc2.35


          CPU Info
==============================
Architecture:                            x86_64
CPU op-mode(s):                          32-bit, 64-bit
Address sizes:                           40 bits physical, 48 bits virtual
Byte Order:                              Little Endian
CPU(s):                                  32
On-line CPU(s) list:                     0-31
Vendor ID:                               GenuineIntel
Model name:                              Intel Xeon Processor (Cascadelake)
CPU family:                              6
Model:                                   85
Thread(s) per core:                      2
Core(s) per socket:                      8
Socket(s):                               2
Stepping:                                6
BogoMIPS:                                4788.62
Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch cpuid_fault ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves arat vnmi pku ospke avx512_vnni md_clear arch_capabilities
Virtualization:                          VT-x
Hypervisor vendor:                       KVM
Virtualization type:                     full
L1d cache:                               1 MiB (32 instances)
L1i cache:                               1 MiB (32 instances)
L2 cache:                                64 MiB (16 instances)
L3 cache:                                32 MiB (2 instances)
NUMA node(s):                            2
NUMA node0 CPU(s):                       0-15
NUMA node1 CPU(s):                       16-31
Vulnerability Gather data sampling:      Unknown: Dependent on hypervisor status
Vulnerability Indirect target selection: Mitigation; Aligned branch/return thunks
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; Enhanced / Automatic IBRS; IBPB conditional; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected

==============================
Versions of relevant libraries
==============================
[pip3] numpy==2.3.5
[pip3] pyzmq==27.1.0
[pip3] torch==2.11.0+cpu
[pip3] torchaudio==2.11.0+cpu
[pip3] torchvision==0.26.0+cpu
[pip3] transformers==5.8.0
[pip3] triton==3.7.0
[conda] Could not collect


==============================
         vLLM Info
==============================
ROCM Version                 : Could not collect
vLLM Version                 : 0.20.2
vLLM Build Flags:
  CUDA Archs: Not Set; ROCm: Disabled; XPU: Disabled
GPU Topology:
  Could not collect

==============================
     Environment Variables
==============================
PYTORCH_NVML_BASED_CUDA_CHECK=1
TORCHINDUCTOR_COMPILE_THREADS=1
TORCHINDUCTOR_CACHE_DIR=/tmp/torchinductor_root

---

attn_metadata = forward_context.attn_metadata
if attn_metadata is None:
    logger.warning("In connector.start_load_kv, but the attn_metadata is None")
    return  # ← KV never injected

---

set_forward_context(None, vllm_config)

---

(Worker pid=308) WARNING 05-19 05:36:19 [.../example_connector.py:167] In connector.start_load_kv, but the attn_metadata is None
(APIServer pid=1) INFO [...] External prefix cache hit rate: 88.9%
(APIServer pid=1) INFO [...] Avg prompt throughput: 0.0 tokens/s

---

# Load:
num_pages = dst_kv_cache_layer_shape[1]
page_size = dst_kv_cache_layer_shape[2]   # ← WRONG on CPU: this is num_kv_heads, not page_size
dst_kv_cache_layer = dst_kv_cache_layer.reshape(2, num_pages * page_size, -1)
dst_kv_cache_layer[:, slot_mapping, ...] = src_kv_cache

# Save:
num_pages, page_size = layer.shape[1], layer.shape[2]  # same error
return layer.reshape(2, num_pages * page_size, -1)[:, slot_mapping, ...]

---

def get_kv_cache_shape(...):
    return 2, num_blocks, num_kv_heads, block_size, head_size
RAW_BUFFERClick to expand / collapse

Your current environment

<details> <summary>The output of <code>python collect_env.py</code></summary>
ollecting environment information...
==============================
        System Info
==============================
OS                           : Ubuntu 22.04.5 LTS (x86_64)
GCC version                  : (Ubuntu 12.3.0-1ubuntu1~22.04.3) 12.3.0
Clang version                : Could not collect
CMake version                : Could not collect
Libc version                 : glibc-2.35

==============================
       PyTorch Info
==============================
PyTorch version              : 2.11.0+cpu
Is debug build               : False
CUDA used to build PyTorch   : None
ROCM used to build PyTorch   : N/A
XPU used to build PyTorch    : N/A

==============================
      Python Environment
==============================
Python version               : 3.12.13 (main, May  4 2026, 21:09:48) [Clang 22.1.3 ] (64-bit runtime)
Python platform              : Linux-5.14.0-611.54.1.el9_7.x86_64-x86_64-with-glibc2.35


          CPU Info
==============================
Architecture:                            x86_64
CPU op-mode(s):                          32-bit, 64-bit
Address sizes:                           40 bits physical, 48 bits virtual
Byte Order:                              Little Endian
CPU(s):                                  32
On-line CPU(s) list:                     0-31
Vendor ID:                               GenuineIntel
Model name:                              Intel Xeon Processor (Cascadelake)
CPU family:                              6
Model:                                   85
Thread(s) per core:                      2
Core(s) per socket:                      8
Socket(s):                               2
Stepping:                                6
BogoMIPS:                                4788.62
Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch cpuid_fault ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves arat vnmi pku ospke avx512_vnni md_clear arch_capabilities
Virtualization:                          VT-x
Hypervisor vendor:                       KVM
Virtualization type:                     full
L1d cache:                               1 MiB (32 instances)
L1i cache:                               1 MiB (32 instances)
L2 cache:                                64 MiB (16 instances)
L3 cache:                                32 MiB (2 instances)
NUMA node(s):                            2
NUMA node0 CPU(s):                       0-15
NUMA node1 CPU(s):                       16-31
Vulnerability Gather data sampling:      Unknown: Dependent on hypervisor status
Vulnerability Indirect target selection: Mitigation; Aligned branch/return thunks
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow:      Not affected
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; Enhanced / Automatic IBRS; IBPB conditional; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Not affected

==============================
Versions of relevant libraries
==============================
[pip3] numpy==2.3.5
[pip3] pyzmq==27.1.0
[pip3] torch==2.11.0+cpu
[pip3] torchaudio==2.11.0+cpu
[pip3] torchvision==0.26.0+cpu
[pip3] transformers==5.8.0
[pip3] triton==3.7.0
[conda] Could not collect


==============================
         vLLM Info
==============================
ROCM Version                 : Could not collect
vLLM Version                 : 0.20.2
vLLM Build Flags:
  CUDA Archs: Not Set; ROCm: Disabled; XPU: Disabled
GPU Topology:
  Could not collect

==============================
     Environment Variables
==============================
PYTORCH_NVML_BASED_CUDA_CHECK=1
TORCHINDUCTOR_COMPILE_THREADS=1
TORCHINDUCTOR_CACHE_DIR=/tmp/torchinductor_root
</details>

🐛 Describe the bug

ExampleConnector.start_load_kv silently fails to write KV cache data into the paged buffer on CPU backends due to two underlying bugs. While the scheduler correctly detects externally-available tokens (logging e.g., External prefix cache hit rate: 88.9%) and bypasses the local prefill stage, the KV data is never actually injected. As a result, the decode worker evaluates an empty context and generates garbage output.

Steps to Reproduce

  • Set up a disaggregated Prefill-Decode architecture using ExampleConnector (shared storage) on CPU backends.

  • Run a prefill request (the prefill worker successfully saves the KV data to disk).

  • Route the decode request to the decode worker.

Expected Behavior: The decode worker successfully loads the KV files into the buffer and generates coherent output. Actual Behavior: The decode worker finds the files but fails to inject them. The model decodes from an empty context, producing repeated backtick characters.

Bug 1: Early return when attn_metadata is None

Location

vllm/distributed/kv_transfer/kv_connector/v1/example_connector.py, lines 166-168

Code

attn_metadata = forward_context.attn_metadata
if attn_metadata is None:
    logger.warning("In connector.start_load_kv, but the attn_metadata is None")
    return  # ← KV never injected

Root cause

kv_connector_no_forward (vllm/v1/worker/kv_connector_model_runner_mixin.py:42-43) intentionally passes attn_metadata=None:

set_forward_context(None, vllm_config)

This function is called on any platform when all tokens are externally available and no forward pass is needed (num_scheduled_tokens == 0). The connector must still inject KV in this case.

Evidence from decode logs

(Worker pid=308) WARNING 05-19 05:36:19 [.../example_connector.py:167] In connector.start_load_kv, but the attn_metadata is None
(APIServer pid=1) INFO [...] External prefix cache hit rate: 88.9%
(APIServer pid=1) INFO [...] Avg prompt throughput: 0.0 tokens/s

The scheduler found 88.9% of tokens externally (skipped local prefill), but start_load_kv returned early without injecting. The model decoded from an empty KV buffer → garbage.

Bug 2: Incorrect KV cache layout assumption for CPU backend

Location

vllm/distributed/kv_transfer/kv_connector/v1/example_connector.py:

  • inject_kv_into_layer (load path, line ~154-159)
  • extract_kv_from_layer (save path, line ~257-258)

Code (else branch)

# Load:
num_pages = dst_kv_cache_layer_shape[1]
page_size = dst_kv_cache_layer_shape[2]   # ← WRONG on CPU: this is num_kv_heads, not page_size
dst_kv_cache_layer = dst_kv_cache_layer.reshape(2, num_pages * page_size, -1)
dst_kv_cache_layer[:, slot_mapping, ...] = src_kv_cache

# Save:
num_pages, page_size = layer.shape[1], layer.shape[2]  # same error
return layer.reshape(2, num_pages * page_size, -1)[:, slot_mapping, ...]

Root cause

The CPU attention backend (vllm/v1/attention/backends/cpu_attn.py:93) uses a 5D KV cache:

def get_kv_cache_shape(...):
    return 2, num_blocks, num_kv_heads, block_size, head_size

The else branch assumes 4D [2, num_pages, page_size, head_dim]. On CPU:

  • shape[2] = num_kv_heads (e.g., 2), NOT page_size (e.g., 16)
  • reshape(2, 128*2, -1) conflates blocks with heads
  • [:, slot_mapping, ...] writes to completely wrong positions

This corrupts the KV buffer. Even if Bug 1 is fixed, the loaded data lands in wrong memory locations → garbage output.

vllm-decode-logs-bug2.txt vllm-decode-logs-bug1.txt

Before submitting a new issue...

  • Make sure you already searched for relevant issues, and asked the chatbot living at the bottom right corner of the documentation page, which can answer lots of frequently asked questions.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

vllm - ✅(Solved) Fix [Bug]: ExampleConnector fails to inject KV cache on CPU [1 pull requests, 1 comments, 2 participants]