One 40 GB GPU, Three AI Engines: KV Cache Maths and VRAM Collisions

Most "run an LLM locally" posts are about prompts. This one is about arithmetic. When you stretch a 27B-class model (a Qwen-sized model, say) towards its context limit on a single 40 GB GPU, the question is not "what should I ask it". The question is "where did my 40 GB go, and why did the process die at token 31,000". And once that works, someone always asks to run image generation and a voice assistant on the same card.

Here is the maths I use, and the setup that finally stopped my GPU from crashing.

Where the memory goes

A serving process holds four things on the GPU:

  1. Weights: fixed, set by parameter count and quantization.
  2. KV cache: grows with every token of every active sequence.
  3. Activations and workspace: temporary buffers for the forward pass, larger with bigger batches.
  4. CUDA context and allocator overhead: a few hundred MB per process, before you load anything.

Weights

weight bytes ≈ parameters × bits per weight / 8
27B model Bits (incl. scales) Weights
FP16 / BF16 16 ~54 GB (does not fit)
8-bit ~8.5 ~29 GB
4-bit (AWQ / GPTQ) ~4.5 ~15 GB

KV cache

Every token stores a key and a value vector in every layer, for every KV head:

KV bytes per token = 2 × layers × kv_heads × head_dim × bytes per value

Read the numbers from the model's config.json (num_hidden_layers, num_key_value_heads, head_dim). For a typical grouped-query config of this size (64 layers, 8 KV heads, head size 128):

2 × 64 × 8 × 128 × 2 bytes = 262,144 bytes = 256 KiB per token (FP16)
Context (one sequence) FP16 KV FP8 KV
8k tokens 2 GiB 1 GiB
32k tokens 8 GiB 4 GiB
64k tokens 16 GiB 8 GiB
128k tokens 32 GiB 16 GiB

These numbers are per sequence. Four users at 32k each need four times as much. Grouped-query attention is the reason any of this fits: with 64 KV heads instead of 8, every number in the table would be eight times larger.

Putting it together on 40 GB

With 4-bit weights (~15 GB) and about 3 GB for activations, the CUDA context and fragmentation, roughly 20 GiB is left for the cache:

  • FP16 KV: about 80k tokens in total across all active sequences.
  • FP8 KV: about 160k tokens.

With 8-bit weights (~29 GB), only about 8 GiB is left, which is about 32k tokens at FP16. That is why I run 4-bit weights with an FP8 cache for long-context work: the quality loss from FP8 KV is small, and it doubles the usable context. Also check the model's trained context length. A model trained for 32k does not become a 128k model just because the memory is there; extending it needs RoPE scaling (YaRN), and quality drops near the limit.

In vLLM, the knobs that matter are:

vllm serve <model> \
  --quantization awq \
  --kv-cache-dtype fp8 \
  --max-model-len 65536 \
  --gpu-memory-utilization 0.90 \
  --max-num-seqs 8

--max-model-len caps one sequence. --max-num-seqs caps how many share the cache. vLLM logs how many cache blocks it allocated at startup; divide by your context length to see how many full-length conversations really fit.

The collision: adding images and voice

Now the hard part. I wanted chat, image generation and voice on the same card. Rough peak memory for each:

Engine Typical choice Peak VRAM
Chat 27B, 4-bit, vLLM whatever you allow it
Image generation SDXL in FP16 at 1024 px ~8 to 10 GB
Speech to text faster-whisper large-v3, INT8 ~2 to 3 GB
Text to speech Kokoro (82M parameters) under 1 GB
CUDA context one per process ~0.3 to 0.5 GB each

The first attempt crashed instantly. vLLM claims 90% of the GPU by default, the moment it starts, and keeps it for its cache. There is nothing left for anything else, and it does not matter that the chat model is idle.

The setup that works

1. Give vLLM an explicit share. --gpu-memory-utilization 0.60 gives it 24 GB: 15 GB of weights and about 7 GB of cache. That is roughly 50k tokens with an FP8 cache, still plenty for chat.

2. Start vLLM first. It checks at startup that its share of memory is free. If the image model loaded first and grabbed memory, vLLM refuses to start, or starts with less cache than you planned.

3. Cap the PyTorch processes. Image and speech models run on PyTorch, whose caching allocator holds on to freed memory. Cap each process and reduce fragmentation:

import os
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"   # before importing torch

import torch
torch.cuda.set_per_process_memory_fraction(0.25)   # image service: at most 10 GB

The cap turns a crash of the whole card into a clean out-of-memory error in one service, which you can catch and retry.

4. Flatten the image spikes. In diffusers, pipe.enable_vae_tiling() stops the VAE decode at the end of generation from spiking memory. Render one image at a time and queue the rest. A queue is better than a crash.

5. Use the smallest voice models that sound right. faster-whisper with compute_type="int8_float16" and a small TTS model leave a lot more room than their FP16 versions.

6. Watch it. nvidia-smi --query-compute-apps=pid,used_memory --format=csv -l 5 shows each process's memory every five seconds. Alert well before 100%.

The final budget on the 40 GB card:

Process Budget
vLLM (chat) 24 GB
Image service 10 GB cap
Whisper + TTS 4 GB
Contexts and headroom ~2 GB

When sharing is not enough

If one service still pushes the others over, stop sharing a single memory pool. On an A100 or H100, MIG splits the card into hardware-isolated slices. On an A100 40 GB, for example, 4g.20gb for chat, 2g.10gb for images and 1g.5gb for voice. Each slice has its own memory, and a crash cannot spread. The cost is flexibility: an idle slice cannot lend memory to a busy one.

The other option is time-sharing: unload the image model when it has been idle for a few minutes and load it again on the next request. You pay a few seconds of cold start, but the chat model gets its cache back.

The general lesson is that GPU memory is a budget, not a pool. Write the budget down per process, enforce it with flags and caps, and do the KV maths before you promise anyone 128k context.