Llm Kv Cache Paged Attentionのロゴ

Llm Kv Cache Paged Attention

コミュニティ
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).

概要

公開者j4flmao
リポジトリagent-skills
スキル名llm-kv-cache-paged-attention
スター
41
フォーク
6
同梱ファイル
指示のみ
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 指示だけで完結

    モデルに必要なものはすべて指示に含まれているため、別途同期するファイルはありません。

  • オープンソース

    j4flmaoがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Llm Kv Cache Paged Attention」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-engineering/kv-cache
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

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
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでLlm Kv Cache Paged Attentionを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にLlm Kv Cache Paged Attentionを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Llm Kv Cache Paged Attentionは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

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.

よくある質問

AIスキル「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).

TypingMindでLlm Kv Cache Paged Attentionを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Llm Kv Cache Paged Attentionはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにLlm Kv Cache Paged Attentionをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/j4flmao/agent-skills/tree/main/skills/ai/llm-engineering/kv-cacheを貼り付けてください。TypingMindがSKILL.mdを読み込み、チャットごとに有効にできるスキルとしてインストールします。

Llm Kv Cache Paged Attentionを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Llm Kv Cache Paged Attentionで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもLlm Kv Cache Paged Attentionを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Llm Kv Cache Paged Attention」は無料ですか?

はい。j4flmaoがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇