Logo: Llm Kv Cache Paged Attention

Llm Kv Cache Paged Attention

Communautéit
j4flmao
llm-kv-cache-paged-attention

Use this skill when the user says 'KV cache', 'PagedAttention', 'vLLM memory', 'gpu_memory_utilization', 'prefix caching', 'max concurrent sequences', 'KV cache size', 'context length OOM'. Explains KV cache memory math and how paged allocation, prefix caching, KV quantization, and attention variants (MQA/GQA/MLA) change serving capacity, with vLLM configuration. Do NOT use for: weight quantization (ai/llm-engineering/model-quantization), local llama.cpp/Ollama setups (rnd/ai-agents/local-slm-inference), or general LLMOps (ai/llm-ops).

Iwwersiicht

Editeurj4flmao
Repositoryagent-skills
Skill-Nummllm-kv-cache-paged-attention
Stären
41
Forks
6
Matgeliwwert Dateien
Nëmmen Instruktiounen
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    j4flmao huet de Skill op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Llm Kv Cache Paged Attention an TypingMind, fir e mat all LLM ze benotzen, oder setzt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vu GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier, déi hei drënner steet, an a bestätegt d'Installatioun.
    https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-engineering/kv-cache
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill derbäisetzen → Iwwer eng GitHub-URL. Pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an d'Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/ai/llm-engineering/kv-cache .claude/skills/llm-kv-cache-paged-attention
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Llm Kv Cache Paged Attention an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Llm Kv Cache Paged Attention automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Llm Kv Cache Paged Attention net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Schlësselen.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

KV Cache & PagedAttention

Purpose

During decoding each new token attends to the keys and values of all previous tokens. Caching K and V avoids recomputing them, but the cache grows linearly with sequence length and batch size and usually becomes the binding constraint on concurrency. This skill gives the sizing math and the serving-engine levers (paging, prefix sharing, KV quantization, scheduling) to maximize throughput without OOM.

Agent Protocol

Trigger

"KV cache", "PagedAttention", "vLLM OOM", "gpu_memory_utilization", "max_num_seqs", "prefix caching", "long context memory", "KV cache quantization".

Input Context

  • Model architecture: layers, KV heads, head dim (from config.json), dtype.
  • GPU count/VRAM, target context length, expected concurrent requests.
  • Prompt shape: shared system prompts or few-shot prefixes?

Output Artifact

KV budget calculation and serving configuration (vLLM flags or equivalent) with expected max concurrency.

Response Format

Model: {name} L={layers} kv_heads={h} head_dim={d} dtype={bytes}
KV per token: 2*L*h*d*bytes = {KiB}
KV budget: {GiB} -> tokens in cache ≈ {n}
Max concurrency at {ctx} tokens ≈ {n}
Config: --max-model-len {..} --gpu-memory-utilization {..} --kv-cache-dtype {..} --max-num-seqs {..}

Completion Criteria

  • KV bytes/token computed from the real config (KV heads, not attention heads).
  • Budget accounts for weights and activation/workspace memory.
  • Concurrency estimate validated with a load test.
  • Prefix caching considered for shared prompts.

Sizing Math

KV bytes per token = 2 (K and V) × num_layers × num_kv_heads × head_dim × bytes_per_element

Model (config)Per-token KV (bf16)8k-token sequence
Llama-3-8B: 32 layers, 8 KV heads, head_dim 1282·32·8·128·2 = 128 KiB1 GiB
Same model with fp8 KV cache64 KiB0.5 GiB
Hypothetical MHA (32 KV heads)512 KiB4 GiB

Grouped-query attention (GQA) shares each KV head across several query heads, cutting the cache by the group factor; multi-query attention (MQA) uses one KV head; multi-head latent attention (MLA, DeepSeek-V2/V3) stores a compressed latent instead of full K/V.

python
def kv_bytes_per_token(layers: int, kv_heads: int, head_dim: int, dtype_bytes: int) -> int:
    return 2 * layers * kv_heads * head_dim * dtype_bytes


def max_concurrent_seqs(vram_gib: float, weights_gib: float, util: float,
                        overhead_gib: float, per_token: int, ctx_tokens: int) -> int:
    kv_budget = (vram_gib * util - weights_gib - overhead_gib) * 2**30
    if kv_budget <= 0:
        raise ValueError("weights + overhead exceed usable VRAM; quantize weights or add GPUs")
    return int(kv_budget // (per_token * ctx_tokens))

# 80 GiB GPU, 16 GiB bf16 8B weights, util 0.9, ~4 GiB overhead, 8k context:
# kv_budget ≈ 52 GiB -> ~52 sequences at full 8k length (more in practice: most are shorter)

PagedAttention

Contiguous per-request allocation sized for the maximum length wastes memory to internal and external fragmentation; the vLLM paper (Kwon et al., SOSP 2023) measured 60-80% of KV memory wasted in prior systems versus under 4% with paging.

  • Blocks: the KV cache is split into fixed-size blocks (vLLM default 16 tokens). A per-sequence block table maps logical blocks to physical blocks, so a sequence's cache need not be contiguous.
  • On-demand allocation: blocks are allocated as tokens are generated; waste is limited to the last partial block.
  • Sharing with copy-on-write: parallel samples or beams share prompt blocks; a block is copied only when a sequence writes to a shared block.
  • Preemption: when blocks run out, the scheduler preempts lower-priority sequences. The vLLM V1 engine recomputes preempted sequences; older V0 also supported swapping blocks to CPU memory.

Prefix Caching

Blocks are hashed by their token content (and prefix), so requests starting with the same tokens reuse cached blocks and skip prefill for that part. Enabled by default in the vLLM V1 engine (--enable-prefix-caching on older versions). Put stable content (system prompt, tools, few-shot examples) first and variable content last to maximize hits. Provider APIs expose the same idea as prompt caching.

vLLM Configuration

bash
vllm serve meta-llama/Llama-3.1-8B-Instruct \
  --max-model-len 16384 \
  --gpu-memory-utilization 0.90 \
  --kv-cache-dtype fp8 \
  --max-num-seqs 128 \
  --tensor-parallel-size 1
python
from vllm import LLM, SamplingParams

llm = LLM(model="meta-llama/Llama-3.1-8B-Instruct", max_model_len=16384,
          gpu_memory_utilization=0.90, kv_cache_dtype="fp8")
outs = llm.generate(["Summarize: ..."], SamplingParams(temperature=0.2, max_tokens=256))
FlagEffectTrade-off
--gpu-memory-utilizationFraction of VRAM vLLM may use (weights + KV + activations)Too high → OOM with other processes
--max-model-lenLongest allowed sequenceLower = more concurrency, rejects longer prompts
--kv-cache-dtype fp8Halves KV memory vs fp16/bf16Small accuracy risk; verify on evals
--max-num-seqsCap on concurrently scheduled sequencesHigher throughput vs latency
--tensor-parallel-sizeShard model across GPUsInterconnect overhead
chunked prefill (default on V1)Splits long prefills to interleave with decodesSmoother latency

On startup vLLM logs the number of KV cache blocks/tokens and the maximum concurrency for max_model_len; compare it against your calculation.

Diagnosing

SymptomCauseFix
OOM at startupNot enough memory for weights + minimal KVLower max_model_len, quantize weights, add TP
Frequent preemption warningsKV pool exhausted under loadfp8 KV, lower max_num_seqs, more GPUs
High TTFT with shared promptsPrefix not reusedStable prefix ordering; check prefix-cache hit rate metric
Throughput low, VRAM freeBatch limited by max_num_seqs or CPURaise cap; check tokenizer/CPU bottlenecks

Anti-Patterns

  • Using attention heads instead of KV heads in the math (overestimates GQA models by 4-8×).
  • Setting max_model_len to the model's maximum "just in case".
  • Putting per-request data (timestamps, user ids) at the start of prompts, defeating prefix caching.
  • Enabling fp8 KV without re-running quality evals.

Checklist

  • KV/token computed; concurrency estimated and load tested.
  • max_model_len matched to real traffic percentiles.
  • Prefix ordering optimized; hit rate monitored.
  • KV dtype decision backed by eval results.
  • Metrics: KV usage %, preemptions, TTFT, inter-token latency.

References

  • Kwon et al., "Efficient Memory Management for Large Language Model Serving with PagedAttention" (SOSP 2023).
  • Ainslie et al., "GQA" (2023); DeepSeek-AI, "DeepSeek-V2" (2024) for MLA.
  • vLLM documentation: engine arguments, automatic prefix caching, optimization guide.

Heefeg gestallte Froen

Wat mécht de KI-Skill Llm Kv Cache Paged Attention?

Use this skill when the user says 'KV cache', 'PagedAttention', 'vLLM memory', 'gpu_memory_utilization', 'prefix caching', 'max concurrent sequences', 'KV cache size', 'context length OOM'. Explains KV cache memory math and how paged allocation, prefix caching, KV quantization, and attention variants (MQA/GQA/MLA) change serving capacity, with vLLM configuration. Do NOT use for: weight quantization (ai/llm-engineering/model-quantization), local llama.cpp/Ollama setups (rnd/ai-agents/local-slm-inference), or general LLMOps (ai/llm-ops).

Firwat Llm Kv Cache Paged Attention op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Llm Kv Cache Paged Attention besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt, amplaz en Abonnement pro Benotzerplaz ze bezuelen. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Llm Kv Cache Paged Attention an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-engineering/kv-cache an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Llm Kv Cache Paged Attention benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Llm Kv Cache Paged Attention benotzen?

Esou vill wéi Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Llm Kv Cache Paged Attention domat benotzen – zum Beispill mat GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Llm Kv Cache Paged Attention gratis?

Jo. j4flmao huet de Skill ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbare Pak vun Instruktiounen, deen engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt e maache soll a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a kee Lafzäitëmfeld a funktionéiere mat all Modell.

Alleguer weisen

Elo Ären eegene KI-Aarbechtsberäich ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇