vllm - ✅(Solved) Fix [Bug]: Inaccurate available memory for KV cache when sleep mode is enabled likely due to custom allocators [1 pull requests, 1 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#40256Fetched 2026-04-19 15:04:43
View on GitHub
Comments
0
Participants
1
Timeline
2
Reactions
0
Author
Participants
Timeline (top)
cross-referenced ×1labeled ×1

Error Message

Estimated available memory for the KV cache differs 1.99 GiB when --enable-sleep-mode is set (5.16 GiB) as compare to unset (3.17 GiB)

Root Cause

Reproduction steps

  1. Install/configure vllm (e.g., from commit bfde49e28)
  2. Run the launch script below (on a dual-4090 system; may need to adapt the script to a single GPU, and, if so, use a smaller model that will fit in VRAM)
  3. Observe out of memory error occurs and that launch reports "Available KV cache memory: 5.16 GiB" prior to crash" (This estimate is incorrect and the root cause of the crash.)
  4. Run the same launch script without --enable-sleep-mode
  5. Observe it loads correctly and that launch reports "Available KV cache memory: 3.17 GiB" (this is correct).

Fix Action

Fix / Workaround

============================== CPU Info

Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 28 On-line CPU(s) list: 0-27 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i7-14700K CPU family: 6 Model: 183 Thread(s) per core: 2 Core(s) per socket: 20 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 46% CPU max MHz: 5600.0000 CPU min MHz: 800.0000 BogoMIPS: 6835.20 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_lbr ibt flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 768 KiB (20 instances) L1i cache: 1 MiB (20 instances) L2 cache: 28 MiB (11 instances) L3 cache: 33 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-27 Vulnerability Gather data sampling: Not affected Vulnerability Ghostwrite: Not affected Vulnerability Indirect target selection: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Old microcode: Not affected Vulnerability Reg file data sampling: Mitigation; Clear Register File Vulnerability Retbleed: Not affected 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 BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Mitigation; IBPB before exit to userspace

PR fix notes

PR #40258: [Bugfix] Corrects estimate of torch memory use causing OOM due to incorrect KV cache space estimation when sleep mode on (Fixes #40256)

Description (problem / solution / changelog)

[Bugfix] Correct torch memory measurement during profiling that was invalid when custom allocators were used.

Co-authored-by: GitHub Copilot Co-authored-by: ChatGPT 5.4 Thinking Co-authored-by: ChatGPT 5.4 Pro Co-authored-by: Claude Opus 4.6 Co-authored-by: Claude Opus 4.7

Purpose

This PR repairs an erroneous memory estimation that arises during profiling when custom CUDA allocators are in use (e.g., sleep mode). This Fixes

To calculate how much memory is available for the KV cache vLLM profiles memory usage (gpu_worker.py calling mem_utils.py's measure() function).

The strategy vllm has been using is outlined in MemoryShapshot.measure(), which profiles the memory usage in terms of torch-related memory and non-torch memory. (This is because it also needs to keep track of peak torch memory, which may be transiently higher during the forward pass of a model).

The strategy vllm had been using is to measure torch memory using torch.accelerator.memory.memory_reserved. However, there were changes accepted to enable sleep mode recently. To support sleep mode, this uses a custom CUDA allocator that allows vllm to selectively discard some parts of GPU memory during sleep.

Unfortunately, when custom allocators are used, this causes the measure() method to over-estimate torch memory use. This is because torch.accelerator.memory.memory_reserved becomes an unreliable estimate of torch-related memory once custom allocaters are being used.

In some cases, this estimate can exceed all CUDA memory use, causing measure() to incorrectly report that non-torch memory is negative. This is obviously incorrect and can lead to out of memory errors because vllm believes it has more memory to allocate to the KV cache than is truly available.

More details are shown in a related bug.

This PR makes one surgical change to the measure function, replacing the estimate of torch memory with

stats.get("allocated_bytes.all.current", 0)

Where stats is:

stats = torch.accelerator.memory_stats(device)

The problem can be illustrated by observing the intermediate variables in measure() on one CUDA device during

MeasurementSleep off old codeSleep on old code
Torch Peak19.7319.73
Total memory23.5223.52
Free memory3.984.02
Cuda memory19.5419.5
Torch memory (old: memory_reserved)18.9220.87 ←
Torch memory (new: allocated_bytes.all.current)18.7118.71
Non-torch memory0.62-1.36 ←

A table in testing results, below, shows the correction of this problem with the proposed code change.

Test Plan

I observed the measured memory calculated in the mem_utils.py MemoryShapshot.measure() function using the old calculation method (memory_reserved()) and then new method stats.get("allocated_bytes.all.peak", 0). Results from a load of quantized Llama 70B on a 2x 4090 system are shown in the table (test result). Arrows and bold indicates the erroneous quantities using the memory_reserve

The command used to run was:

VLLM_SERVER_DEV_MODE=1 python -m vllm.entrypoints.openai.api_server \
  --model hugging-quants/Meta-Llama-3.1-70B-Instruct-AWQ-INT4 \
  --tensor-parallel-size 2 \
  --dtype half \
  --quantization awq_marlin \
  --kv-cache-dtype fp8 \
  --max-model-len 36000 \
  --max-num-seqs 1 \
  --gpu-memory-utilization 0.97 \
  --host 0.0.0.0 \
  --port 5555 \
  --enable-chunked-prefill --max-num-batched-tokens 8192 \
  --enforce-eager \
  --enable-sleep-mode

For the no sleep tests, the --enable-sleep-mode flag was disabled.

Test Result

The table below shows intermediate calculations in MemorySnapshot.measure() when sleep (and therefore custom allocators) are on/off and in the old code as compared to the new code. When sleep is on, memory_reserved reports more memory use by torch than is being used in total by CUDA, which is not a correct estimate of the torch memory use (bolded cells with arrows). This leads to non-torch memory being estimated to be negataive. The downstream result of this

Sleep offSleep offSleep onSleep on
Measurement (GiB)Old codeNew codeOld codeNew code
Torch Peak19.7319.7319.7319.73
Total memory23.5223.5223.5223.52
Free memory3.983.984.024.02
Cuda memory19.5419.5419.519.5
Torch memory (old: memory_reserved)18.9218.9220.87 ←20.87 ←
Torch memory (new: bytes_allocated)18.7118.7118.7118.71
Non-torch memory0.620.83-1.36 ←0.79

On the testing machine sleep on / old code lead to OOM because vllm overestimates how much space it can allocate to the KV cache, whereas sleep on / new code resolves the OOM.

Additionally, we can directly observe the KV cache estimates:

Sleep offSleep offSleep onSleep on
Measurement (GiB)Old codeNew codeOld codeNew code
Estimate Available KV Cache3.172.965.16 ← Wrong3.0

This the correction prevents discordance in the estimated available KV cache when sleep mode is enabled as compared to disabled, as expected by issue #40256.

Contact

Please do not hesitant to contact me about remaining issues with this PR. Thank you for considering this change.

AI Contributors

I consulted extensively with Github Copilot, ChatGPT Thinking/Pro, Claude 4.6/4.7 to understand the codebase and discuss possible solutions. I considered at length these recommendations, explored possible solutions myself, and personally verified the solution arrived at and proposed in this PR. I take responsibility for its proposal.


<details> <summary> Essential Elements of an Effective PR Description Checklist </summary>
  • The purpose of the PR, such as "Fix some issue (link existing issues this PR will resolve)".
  • The test plan, such as providing test command.
  • The test results, such as pasting the results comparison before and after, or e2e results
  • (Optional) The necessary documentation update, such as updating supported_models.md and examples for a new model.
</details>

Changed files

  • vllm/utils/mem_utils.py (modified, +13/-7)

Code Example

==============================
        System Info
==============================
OS                           : Ubuntu 24.04.4 LTS (x86_64)
GCC version                  : (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0
Clang version                : Could not collect
CMake version                : version 3.28.3
Libc version                 : glibc-2.39

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

==============================
      Python Environment
==============================
Python version               : 3.12.13 (main, Apr  7 2026, 20:45:25) [Clang 22.1.1 ] (64-bit runtime)
Python platform              : Linux-6.17.0-20-generic-x86_64-with-glibc2.39
    
==============================
       CUDA / GPU Info
==============================
Is CUDA available            : True
CUDA runtime version         : Could not collect
CUDA_MODULE_LOADING set to   : 
GPU models and configuration : 
GPU 0: NVIDIA GeForce RTX 4090
GPU 1: NVIDIA GeForce RTX 4090

Nvidia driver version        : 590.48.01
cuDNN version                : Could not collect
HIP runtime version          : N/A
MIOpen runtime version       : N/A
Is XNNPACK available         : True

==============================
          CPU Info
==============================
Architecture:                            x86_64
CPU op-mode(s):                          32-bit, 64-bit
Address sizes:                           46 bits physical, 48 bits virtual
Byte Order:                              Little Endian
CPU(s):                                  28
On-line CPU(s) list:                     0-27
Vendor ID:                               GenuineIntel
Model name:                              Intel(R) Core(TM) i7-14700K
CPU family:                              6
Model:                                   183
Thread(s) per core:                      2
Core(s) per socket:                      20
Socket(s):                               1
Stepping:                                1
CPU(s) scaling MHz:                      46%
CPU max MHz:                             5600.0000
CPU min MHz:                             800.0000
BogoMIPS:                                6835.20
Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_lbr ibt flush_l1d arch_capabilities
Virtualization:                          VT-x
L1d cache:                               768 KiB (20 instances)
L1i cache:                               1 MiB (20 instances)
L2 cache:                                28 MiB (11 instances)
L3 cache:                                33 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-27
Vulnerability Gather data sampling:      Not affected
Vulnerability Ghostwrite:                Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Old microcode:             Not affected
Vulnerability Reg file data sampling:    Mitigation; Clear Register File
Vulnerability Retbleed:                  Not affected
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 BHI_DIS_S
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Mitigation; IBPB before exit to userspace

==============================
Versions of relevant libraries
==============================
[pip3] flashinfer-python==0.6.7
[pip3] numpy==2.2.6
[pip3] nvidia-cublas==13.1.0.3
[pip3] nvidia-cuda-cupti==13.0.85
[pip3] nvidia-cuda-nvrtc==13.0.88
[pip3] nvidia-cuda-runtime==13.0.96
[pip3] nvidia-cudnn-cu13==9.19.0.56
[pip3] nvidia-cudnn-frontend==1.18.0
[pip3] nvidia-cufft==12.0.0.61
[pip3] nvidia-cufile==1.15.1.6
[pip3] nvidia-curand==10.4.0.35
[pip3] nvidia-cusolver==12.0.4.66
[pip3] nvidia-cusparse==12.6.3.3
[pip3] nvidia-cusparselt-cu13==0.8.0
[pip3] nvidia-cutlass-dsl==4.4.2
[pip3] nvidia-cutlass-dsl-libs-base==4.4.2
[pip3] nvidia-ml-py==13.595.45
[pip3] nvidia-nccl-cu13==2.28.9
[pip3] nvidia-nvjitlink==13.0.88
[pip3] nvidia-nvshmem-cu13==3.4.5
[pip3] nvidia-nvtx==13.0.85
[pip3] pyzmq==27.1.0
[pip3] torch==2.11.0
[pip3] torch_c_dlpack_ext==0.1.5
[pip3] torchaudio==2.11.0
[pip3] torchvision==0.26.0
[pip3] transformers==4.57.6
[pip3] triton==3.6.0
[conda] Could not collect

==============================
         vLLM Info
==============================
ROCM Version                 : Could not collect
vLLM Version                 : 0.19.1rc1.dev309+gf2145efcb (git sha: f2145efcb)
vLLM Build Flags:
  CUDA Archs: Not Set; ROCm: Disabled; XPU: Disabled
GPU Topology:
  	GPU0	GPU1	CPU Affinity	NUMA Affinity	GPU NUMA ID
GPU0	 X 	PHB	0-27	0		N/A
GPU1	PHB	 X 	0-27	0		N/A

Legend:

  X    = Self
  SYS  = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
  NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
  PHB  = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
  PXB  = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
  PIX  = Connection traversing at most a single PCIe bridge
  NV#  = Connection traversing a bonded set of # NVLinks

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

---

VLLM_SERVER_DEV_MODE=1 python -m vllm.entrypoints.openai.api_server \
  --model hugging-quants/Meta-Llama-3.1-70B-Instruct-AWQ-INT4 \
  --tensor-parallel-size 2 \
  --dtype half \
  --quantization awq_marlin \
  --kv-cache-dtype fp8 \
  --max-model-len 36000 \
  --max-num-seqs 1 \
  --gpu-memory-utilization 0.97 \
  --host 0.0.0.0 \
  --port 5555 \
  --enable-chunked-prefill --max-num-batched-tokens 8192 \
  --enforce-eager \
  --enable-sleep-mode

---

stats.get("allocated_bytes.all.current", 0)

---

stats = torch.accelerator.memory_stats(device)
RAW_BUFFERClick to expand / collapse

Your current environment

<details> <summary>The output of <code>python collect_env.py</code></summary>
==============================
        System Info
==============================
OS                           : Ubuntu 24.04.4 LTS (x86_64)
GCC version                  : (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0
Clang version                : Could not collect
CMake version                : version 3.28.3
Libc version                 : glibc-2.39

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

==============================
      Python Environment
==============================
Python version               : 3.12.13 (main, Apr  7 2026, 20:45:25) [Clang 22.1.1 ] (64-bit runtime)
Python platform              : Linux-6.17.0-20-generic-x86_64-with-glibc2.39
    
==============================
       CUDA / GPU Info
==============================
Is CUDA available            : True
CUDA runtime version         : Could not collect
CUDA_MODULE_LOADING set to   : 
GPU models and configuration : 
GPU 0: NVIDIA GeForce RTX 4090
GPU 1: NVIDIA GeForce RTX 4090

Nvidia driver version        : 590.48.01
cuDNN version                : Could not collect
HIP runtime version          : N/A
MIOpen runtime version       : N/A
Is XNNPACK available         : True

==============================
          CPU Info
==============================
Architecture:                            x86_64
CPU op-mode(s):                          32-bit, 64-bit
Address sizes:                           46 bits physical, 48 bits virtual
Byte Order:                              Little Endian
CPU(s):                                  28
On-line CPU(s) list:                     0-27
Vendor ID:                               GenuineIntel
Model name:                              Intel(R) Core(TM) i7-14700K
CPU family:                              6
Model:                                   183
Thread(s) per core:                      2
Core(s) per socket:                      20
Socket(s):                               1
Stepping:                                1
CPU(s) scaling MHz:                      46%
CPU max MHz:                             5600.0000
CPU min MHz:                             800.0000
BogoMIPS:                                6835.20
Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_lbr ibt flush_l1d arch_capabilities
Virtualization:                          VT-x
L1d cache:                               768 KiB (20 instances)
L1i cache:                               1 MiB (20 instances)
L2 cache:                                28 MiB (11 instances)
L3 cache:                                33 MiB (1 instance)
NUMA node(s):                            1
NUMA node0 CPU(s):                       0-27
Vulnerability Gather data sampling:      Not affected
Vulnerability Ghostwrite:                Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Old microcode:             Not affected
Vulnerability Reg file data sampling:    Mitigation; Clear Register File
Vulnerability Retbleed:                  Not affected
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 BHI_DIS_S
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Not affected
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Mitigation; IBPB before exit to userspace

==============================
Versions of relevant libraries
==============================
[pip3] flashinfer-python==0.6.7
[pip3] numpy==2.2.6
[pip3] nvidia-cublas==13.1.0.3
[pip3] nvidia-cuda-cupti==13.0.85
[pip3] nvidia-cuda-nvrtc==13.0.88
[pip3] nvidia-cuda-runtime==13.0.96
[pip3] nvidia-cudnn-cu13==9.19.0.56
[pip3] nvidia-cudnn-frontend==1.18.0
[pip3] nvidia-cufft==12.0.0.61
[pip3] nvidia-cufile==1.15.1.6
[pip3] nvidia-curand==10.4.0.35
[pip3] nvidia-cusolver==12.0.4.66
[pip3] nvidia-cusparse==12.6.3.3
[pip3] nvidia-cusparselt-cu13==0.8.0
[pip3] nvidia-cutlass-dsl==4.4.2
[pip3] nvidia-cutlass-dsl-libs-base==4.4.2
[pip3] nvidia-ml-py==13.595.45
[pip3] nvidia-nccl-cu13==2.28.9
[pip3] nvidia-nvjitlink==13.0.88
[pip3] nvidia-nvshmem-cu13==3.4.5
[pip3] nvidia-nvtx==13.0.85
[pip3] pyzmq==27.1.0
[pip3] torch==2.11.0
[pip3] torch_c_dlpack_ext==0.1.5
[pip3] torchaudio==2.11.0
[pip3] torchvision==0.26.0
[pip3] transformers==4.57.6
[pip3] triton==3.6.0
[conda] Could not collect

==============================
         vLLM Info
==============================
ROCM Version                 : Could not collect
vLLM Version                 : 0.19.1rc1.dev309+gf2145efcb (git sha: f2145efcb)
vLLM Build Flags:
  CUDA Archs: Not Set; ROCm: Disabled; XPU: Disabled
GPU Topology:
  	GPU0	GPU1	CPU Affinity	NUMA Affinity	GPU NUMA ID
GPU0	 X 	PHB	0-27	0		N/A
GPU1	PHB	 X 	0-27	0		N/A

Legend:

  X    = Self
  SYS  = Connection traversing PCIe as well as the SMP interconnect between NUMA nodes (e.g., QPI/UPI)
  NODE = Connection traversing PCIe as well as the interconnect between PCIe Host Bridges within a NUMA node
  PHB  = Connection traversing PCIe as well as a PCIe Host Bridge (typically the CPU)
  PXB  = Connection traversing multiple PCIe bridges (without traversing the PCIe Host Bridge)
  PIX  = Connection traversing at most a single PCIe bridge
  NV#  = Connection traversing a bonded set of # NVLinks

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

🐛 Describe the bug

Key Problem

When sleep mode is enabled (and therefore custom CUDA allocators become part of the memory storage pathway), VLLM incorrectly estimates the amount of memory available for the KV cache and this can lead to OOM.

Reproduction steps

  1. Install/configure vllm (e.g., from commit bfde49e28)
  2. Run the launch script below (on a dual-4090 system; may need to adapt the script to a single GPU, and, if so, use a smaller model that will fit in VRAM)
  3. Observe out of memory error occurs and that launch reports "Available KV cache memory: 5.16 GiB" prior to crash" (This estimate is incorrect and the root cause of the crash.)
  4. Run the same launch script without --enable-sleep-mode
  5. Observe it loads correctly and that launch reports "Available KV cache memory: 3.17 GiB" (this is correct).

Launch script:

VLLM_SERVER_DEV_MODE=1 python -m vllm.entrypoints.openai.api_server \
  --model hugging-quants/Meta-Llama-3.1-70B-Instruct-AWQ-INT4 \
  --tensor-parallel-size 2 \
  --dtype half \
  --quantization awq_marlin \
  --kv-cache-dtype fp8 \
  --max-model-len 36000 \
  --max-num-seqs 1 \
  --gpu-memory-utilization 0.97 \
  --host 0.0.0.0 \
  --port 5555 \
  --enable-chunked-prefill --max-num-batched-tokens 8192 \
  --enforce-eager \
  --enable-sleep-mode

Observed behavior

Estimated available memory for the KV cache differs 1.99 GiB when --enable-sleep-mode is set (5.16 GiB) as compare to unset (3.17 GiB)

Expected behavior

Estimated available memory for the KV cache should be very similar (although perhaps not completely identical) when --enable-sleep-mode is set or unset.

Underlying error and possible solution

To calculate how much memory is available for the KV cache vLLM profiles memory usage (gpu_worker.py calling mem_utils.py's measure() function).

The strategy vllm has been using is outlined in MemoryShapshot.measure(), which profiles the memory usage in terms of torch-related memory and non-torch memory. (This is because it also needs to keep track of peak torch memory, which may be transiently higher during the forward pass of a model).

The strategy vllm had been using is to measure torch memory using torch.accelerator.memory.memory_reserved. However, there were changes accepted to enable sleep mode recently. To support sleep mode, this uses a custom CUDA allocator that allows vllm to selectively discard some parts of GPU memory during sleep.

Unfortunately, when custom allocators are used, this causes the measure() method to over-estimate torch memory use. This is because torch.accelerator.memory.memory_reserved becomes an unreliable estimate of torch-related memory once custom allocaters are being used.

In some cases, this estimate can exceed all CUDA memory use, causing measure() to incorrectly report that non-torch memory is negative. This is obviously incorrect and can lead to out of memory errors because vllm believes it has more memory to allocate to the KV cache than is truly available.

I think this can be remedied by changing, within MemoryShapshot.measure() the estimate of torch memory to be given by:

stats.get("allocated_bytes.all.current", 0)

Where stats is:

stats = torch.accelerator.memory_stats(device)

The problem can be illustrated by observing the intermediate variables in measure() on one CUDA device during

MeasurementSleep off old codeSleep on old code
Torch Peak19.7319.73
Total memory23.5223.52
Free memory3.984.02
Cuda memory19.5419.5
Torch memory (old: memory_reserved)18.9220.87 ←
Torch memory (new: allocated_bytes.all.current)18.7118.71
Non-torch memory0.62-1.36 ←

Implementing this fix leads to the following result:

Sleep offSleep offSleep onSleep on
Measurement (GiB)Old codeNew codeOld codeNew code
Torch Peak19.7319.7319.7319.73
Total memory23.5223.5223.5223.52
Free memory3.983.984.024.02
Cuda memory19.5419.5419.519.5
Torch memory (old: memory_reserved)18.9218.9220.87 ←20.87 ←
Torch memory (new: bytes_allocated)18.7118.7118.7118.71
Non-torch memory0.620.83-1.36 ←0.79

I will file a PR proposing this change shortly.

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.

extent analysis

TL;DR

The most likely fix for the incorrect memory estimation issue when sleep mode is enabled is to update the MemoryShapshot.measure() method to use torch.accelerator.memory_stats(device).get("allocated_bytes.all.current", 0) instead of torch.accelerator.memory.memory_reserved to estimate torch memory usage.

Guidance

  • Identify the MemoryShapshot.measure() method in the vLLM codebase and update the torch memory estimation to use torch.accelerator.memory_stats(device).get("allocated_bytes.all.current", 0).
  • Verify that the updated method correctly estimates the available memory for the KV cache when sleep mode is enabled.
  • Test the updated code with the provided launch script to ensure that the out of memory error is resolved.
  • Review the documentation and code comments to ensure that the update is properly documented and easy to understand.

Example

The updated MemoryShapshot.measure() method could look like this:

stats = torch.accelerator.memory_stats(device)
torch_memory = stats.get("allocated_bytes.all.current", 0)

Replace the existing torch memory estimation with this updated code.

Notes

This fix assumes that the torch.accelerator.memory_stats(device).get("allocated_bytes.all.current", 0) method provides an accurate estimate of torch memory usage. If this is not the case, further investigation may be needed to determine the correct method for estimating torch memory usage.

Recommendation

Apply the workaround by updating the MemoryShapshot.measure() method to use the new torch memory estimation method. This should resolve the out of memory error and provide a more accurate estimate of available memory for the KV cache.

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…

FAQ

Expected behavior

Estimated available memory for the KV cache should be very similar (although perhaps not completely identical) when --enable-sleep-mode is set or unset.

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]: Inaccurate available memory for KV cache when sleep mode is enabled likely due to custom allocators [1 pull requests, 1 participants]