はじめに
Intel MacのようなCPU推論環境では、推論速度とメモリ消費の調整が重要になります。
Ollamaには、num_thread、num_ctx、num_batch といった実行時オプションと、OLLAMA_KV_CACHE_TYPE、OLLAMA_FLASH_ATTENTION といった環境変数があります。
4物理コア / 8論理スレッドのIntel Macで、これらを変えながらOllamaのログと推論速度を測り、CPU推論の設定を調べました。
1. 検証環境と使用モデル
検証環境は以下のとおりです。
| 項目 | スペック / バージョン | 補足 |
|---|---|---|
| CPU | Intel Core i5-1038NG7 @ 2.00GHz | 4コア / 8スレッド(Ice Lake世代) |
| SIMD命令 | AVX2, AVX-512F, AVX-512BW, AVX-512VNNI | 8bit整数積和算命令をサポート |
| キャッシュ | L1d: 32KB/コア, L2: 512KB/コア, L3: 6MB共有 | キャッシュ階層構造 |
| RAM | 16 GB LPDDR4X 3733MHz | 帯域幅 約59.7 GB/s |
| OS | macOS Sonoma (x86_64) | Darwin Kernel |
| ランタイム | Ollama v0.40.12 | 内部で llama.cpp b4000+ が動作 |
| 使用モデル | qwen2.5-coder:0.5b (Q4_K_M) | パラメータ数 494M, 24層, GQA対応 |
Ollamaはモデルを実行する際、内部で独立した llama-server プロセスを起動しています。
ps aux | grep llama-server を実行すると、リクエストされたパラメータがCLI引数として渡されていることが確認できます。
ps aux | grep llama-server
llama-server の起動引数
/Applications/Ollama.app/Contents/Resources/llama-server \
--model /Users/xxxxx/.ollama/models/blobs/sha256-20693aeb02c63304e263a72453b6ab89e1c700a87c6948cac523ac1e6f7cade0 \
--port 56567 --host 127.0.0.1 --no-webui --offline \
-c 4096 -np 1 --log-verbosity 4 --no-log-prefix --no-log-timestamps \
--no-jinja --chat-template chatml --load-mode none --flash-attn auto \
-b 512 -ub 512 -t 4 --context-shift --keep 4
OllamaのAPIリクエストで options(num_ctx, num_thread, num_batch など)を変えると、Ollamaは新しい引数で llama-server を立ち上げ直して推論を実行します。
2. スレッド数(num_thread)の科学: 物理4コア vs 論理8コア
2.1 実測ベンチマーク(1〜12スレッド)
検証機は4つの物理コアを持ち、Hyper-Threading(SMT)によってOSからは8個の論理コアとして認識されています。
論理コア数(8)と物理コア数(4)のどちらに合わせるべきかを確認するため、num_thread を 1 から 12 まで変化させて実測しました。
- Prefill: 84トークンの入力プロンプトを行列積(GEMM)で一括処理するフェーズ
- Decode: 100トークンを1つずつ逐次生成(GEMV)するフェーズ
測定結果は以下のとおりです。
| num_thread | Prefill速度 (tok/s) | Prefill時間 (ms) | Decode速度 (tok/s) | Decode時間 (ms) | 備考 |
|---|---|---|---|---|---|
| 1 | 162.55 | 516.8 | 23.62 | 4233.3 | 単一スレッド(ベースライン) |
| 2 | 186.35 | 450.8 | 43.76 | 2285.3 | コア2基稼働 |
| 3 | 188.93 | 444.6 | 57.33 | 1744.2 | 順調にスケール |
| 4 | 199.14 | 421.8 | 64.57 | 1548.7 | 物理コア数(Prefill最速) |
| 5 | 192.26 | 436.9 | 73.72 | 1356.6 | SMT突入 |
| 6 | 184.24 | 455.9 | 75.24 | 1329.2 | Decodeピーク |
| 8 | 167.80 | 500.6 | 56.69 | 1764.1 | 論理コア数(速度低下) |
| 10 | 34.74 | 2418.0 | 0.36 | 275180.5 | 深刻な速度崩壊(-99.5%) |
| 12 | 16.59 | 5063.8 | 0.17 | 587309.3 | 大幅低下(1秒に0.17トークン) |
2.2 なぜ物理コア数付近が最速で、8を超えると崩壊するのか?
実測データから、次の3点がわかります。
① Prefill(GEMM)は物理コア数(4)が最速
Prefill処理は複数トークンをまとめて処理するため、演算強度が高く、CPUの浮動小数点・ベクトル演算器(AVX2 / AVX-512)がフル稼働します。
しかし、物理コア1つに対してAVX-512のFPU演算器は1セットしか存在しません。
SMTで論理スレッドを割り当てても演算パイプラインは共有されるため、計算能力は2倍になりません。
それどころか、5スレッド以上になるとスレッド同期のロック競合とコンテキストスイッチが発生し、199.14 tok/s から 167.80 tok/s へと速度が低下しました。
② Decode(GEMV)は6スレッドで頭打ち、8スレッドで急落
1トークンずつ生成するDecode処理はメモリ帯域律速です。
演算器の空き時間を利用して別スレッドのメモリアクセスを隠蔽できるため、4スレッドから5〜6スレッドにかけて速度が微増(64.57 $\to$ 75.24 tok/s)しました。
しかし、論理コア数である8スレッドに達すると、L1/L2キャッシュの追い出しとメモリアクセス競合が激化し、56.69 tok/s まで約25%低下しました。
③ コア数を超える過剰スレッド(10〜12)による速度崩壊
論理コア数(8)を超える10スレッドや12スレッドを設定した途端、Decode速度は0.36 tok/s、0.17 tok/sへと急落しました。
これは、OSのスケジューラが限られた8個の論理コア上で多数のスレッドを頻繁にプリエンプションし、キャッシュラインが無効化され、スレッド間同期のスピンロックでCPUが空回りしたためです。
結論(スレッド数の黄金律):
4物理コア / 8論理スレッドのCPU環境では、num_thread = 4(物理コア数)または num_thread = 5〜6 がもっとも高速です。
論理コア数の「8」やそれ以上を指定すると速度が低下します。
3. コンテキストウィンドウ(num_ctx)とKVキャッシュのメモリ科学
3.1 KVキャッシュの理論計算式
LLMが過去のトークンの計算結果を保持する「KVキャッシュ(Key-Value Cache)」は、コンテキスト長 num_ctx に比例してメモリを消費します。
TransformerにおけるKVキャッシュのメモリサイズ(バイト)は、以下の数式で厳密に計算できます。
$$
\text{KV Cache Size (Bytes)} = 2 \times n_{\text{layers}} \times n_{\text{heads_kv}} \times d_{\text{head}} \times n_{\text{ctx}} \times b_{\text{elem}}
$$
ここで、使用した qwen2.5-coder:0.5b の構造パラメータを代入してみます。
- $2$: KeyテンソルとValueテンソルの2面分
- $n_{\text{layers}} = 24$: トランスフォーマーのレイヤー数
- $n_{\text{heads_kv}} = 2$: GQA(Grouped Query Attention)におけるKVヘッド数
- $d_{\text{head}} = 64$: ヘッドあたりの次元数($n_{\text{embd}} / n_{\text{heads}} = 896 / 14 = 64$)
- $b_{\text{elem}} = 2$: float16(デフォルト)のバイト数(1要素2バイト)
$$
\text{KV Cache Size} = 2 \times 24 \times 2 \times 64 \times n_{\text{ctx}} \times 2 = 12,288 \times n_{\text{ctx}} \text{ (Bytes)}
$$
これを MiB($1024 \times 1024$ バイト)単位に換算すると、
- $n_{\text{ctx}} = 2048 \implies \frac{12,288 \times 2048}{1,048,576} = 24.00 \text{ MiB}$
- $n_{\text{ctx}} = 4096 \implies \frac{12,288 \times 4096}{1,048,576} = 48.00 \text{ MiB}$
- $n_{\text{ctx}} = 16384 \implies \frac{12,288 \times 16384}{1,048,576} = 192.00 \text{ MiB}$
となります。
3.2 理論値 vs 実測ログ vs プロセス実メモリ(RSS)
実際に num_ctx を 512 から 16,384 まで変化させてリクエストを送り、Ollamaのサーバーログに出力されるKVキャッシュ確保量と、OSの ps コマンドから取得した実物理メモリ(RSS)を比較しました。
# Qwen2.5-0.5B のKVキャッシュサイズ計算
def calc_kv_cache_mib(num_ctx: int) -> float:
return (2 * 24 * 2 * 64 * num_ctx * 2) / (1024 * 1024)
for ctx in [512, 1024, 2048, 4096, 8192, 16384]:
print(f"num_ctx={ctx:5d} -> {calc_kv_cache_mib(ctx):6.2f} MiB")
比較結果は以下のとおりです。
| num_ctx | 理論KVキャッシュ (MiB) | ログ出力値 (MiB) | プロセスRSS (MiB) | Prefill (tok/s) | Decode (tok/s) |
|---|---|---|---|---|---|
| 512 | 6.00 | 6.0 | 466.95 | 169.24 | 74.32 |
| 1024 | 12.00 | 12.0 | 473.04 | 177.95 | 76.04 |
| 2048 | 24.00 | 24.0 | 485.06 | 177.51 | 77.60 |
| 4096 | 48.00 | 48.0 | 509.00 | 174.68 | 75.06 |
| 8192 | 96.00 | 96.0 | 557.32 | 170.46 | 76.46 |
| 16384 | 192.00 | 192.0 | 653.65 | 176.47 | 78.49 |
Ollamaのサーバーログ(~/.ollama/logs/server.log)を確認すると、理論値と一致する記録が出力されていました。
llama_kv_cache: CPU KV buffer size = 48.00 MiB
llama_kv_cache: size = 48.00 MiB ( 4096 cells, 24 layers, 1/1 seqs), K (f16): 24.00 MiB, V (f16): 24.00 MiB
また、プロセスの物理メモリ(RSS)は512から16384にかけて $466.95 \to 653.65$ MiB と約 186.7 MiB 増加しており、KVキャッシュの差分($192 - 6 = 186$ MiB)と一致しました。
なお、コンテキスト長を16,384まで広げても、入力トークン数が短い間はPrefill速度(約175 tok/s)やDecode速度(約76 tok/s)に劣化は見られませんでした。
4. バッチサイズ(num_batch)とキャッシュ局所性
4.1 プロンプト処理におけるバッチサイズの影響
num_batch は、入力プロンプト(Prefill時)を一度に何トークンずつまとめてGEMM演算器に投入するかを制御するパラメータです(デフォルトは512)。
長文テキスト(約250トークン)を入力し、num_batch を 32 から 2048 まで変化させて Prompt Eval 速度を実測しました。
| num_batch | Prompt Eval 速度 (tok/s) | 処理時間 (ms) | 速度比(vs 32) |
|---|---|---|---|
| 32 | 142.82 | 1694.4 | 1.00x |
| 64 | 176.44 | 1371.5 | 1.24x |
| 128 | 232.64 | 1040.2 | 1.63x |
| 256 | 254.56 | 950.7 | 1.78x (ピーク) |
| 512 | 244.98 | 987.8 | 1.71x |
| 1024 | 250.36 | 966.6 | 1.75x |
| 2048 | 255.22 | 948.2 | 1.79x |
バッチサイズが小さすぎる(32〜64)と、行列積を小さく分割しすぎるためSIMD命令(AVX-512)の並列計算効率が落ち、142.82 tok/s と遅くなりました。
しかし、128から256あたりでスループットが254.56 tok/sまで上がり、それ以上(512や1024)に増やしても速度は横ばいになりました。
CPUのL2キャッシュ(コアあたり512KB)や共有L3キャッシュ(6MB)のサイズから、作業バッファがキャッシュ内に収まる256〜512がCPUにとっての最適値になります。
5. KVキャッシュ量子化(OLLAMA_KV_CACHE_TYPE)の検証
5.1 f16 vs q8_0 vs q4_0 のメモリ削減率
コンテキスト長が数千〜数万トークンに及ぶ長文対話やRAGでは、KVキャッシュが数GB単位でメモリを圧迫します。
llama.cppにはKVキャッシュ自体を量子化する機能があり、Ollamaでも環境変数 OLLAMA_KV_CACHE_TYPE を通じて利用可能です。
- f16: デフォルト(1要素2バイト)
- q8_0: 8bit整数量子化
- q4_0: 4bit整数量子化
それぞれのタイプでOllamaを起動し、同一モデル(qwen2.5-coder:0.5b, num_ctx = 4096)でのKVキャッシュサイズと推論速度を比較しました。
# 8bit量子化でOllamaを起動
OLLAMA_KV_CACHE_TYPE=q8_0 ollama serve
# 4bit量子化でOllamaを起動
OLLAMA_KV_CACHE_TYPE=q4_0 ollama serve
実測データは以下の通りです。
| キャッシュ型 | 理論KVサイズ (MiB) | 実測KVサイズ (MiB) | 削減率 | Prefill速度 (tok/s) | Decode速度 (tok/s) |
|---|---|---|---|---|---|
| f16 | 48.00 | 48.0 | 基準 (0%) | 141.74 | 70.20 |
| q8_0 | 25.50 | 25.5 | -46.9% | 127.59 | 59.56 |
| q4_0 | 13.50 | 13.5 | -71.9% | 127.30 | 53.55 |
なぜ q8_0 が 24 MiB(半分)ではなく25.5 MiBなのか、q4_0 が 12 MiB(4分の1)ではなく13.5 MiBなのかというと、量子化ブロック(32要素単位)ごとに2バイトのfloat16スケール係数が付加されるためです。
- $q8_0$: $(32 \times 1\text{ byte} + 2\text{ bytes}) / 32 = 1.0625 \text{ bytes/elem} \implies 24 \times 1.0625 = 25.50 \text{ MiB}$
- $q4_0$: $(32 \times 0.5\text{ bytes} + 2\text{ bytes}) / 32 = 0.5625 \text{ bytes/elem} \implies 24 \times 0.5625 = 13.50 \text{ MiB}$
理論式と実測ログが小数点以下まで一致しています。
5.2 メモリ削減の代償: CPUにおける逆量子化オーバーヘッド
KVキャッシュを q4_0 にすることで、メモリ使用量を71.9%削減(48MB $\to$ 13.5MB)できました。
しかし、速度面では明確なトレードオフが発生しました。
CPU推論環境では、アテンション計算のたびに量子化されたKVキャッシュを展開するCPU命令が発生します。
その結果、Decode速度は70.20 tok/s $\to$ 53.55 tok/s(約24%低下)となりました。
なお、生成されたPythonコードの構文について ast.parse で確認したところ、q8_0 や q4_0 でも構文エラーはなく、正常なコードが出力されていました。
KVキャッシュ量子化の使いどころ:
- メモリに余裕がある場合: デフォルトの f16 で70 tok/sを維持できる。
- 長文RAGや大きなコンテキスト(8k〜32k)でRAMが不足する場合: OLLAMA_KV_CACHE_TYPE=q8_0 または q4_0 を指定すると、RAM消費を3分の1以下に抑えてOOMを回避できる。
6. 検証用スクリプト全文
本記事の計測・検証に使用したスクリプトの全文です。
- num_thread を 1〜12 で変化させてPrefillとDecodeのスループットを計測するスクリプトです。
scripts/bench_threads.py の全文を展開する
"""CPUスレッド数(num_thread)による推論スループット比較スクリプト.
4物理コア / 8論理スレッドのIntel CPU環境でnum_threadを1〜12に変化させ、
Prefill(Prompt Processing)およびGeneration(Token Decode)速度を実測。
"""
import json
import os
import time
import urllib.error
import urllib.request
from typing import Any, Dict, List
# Ollama APIエンドポイントのURL
OLLAMA_API_URL: str = "http://127.0.0.1:11434/api/generate"
# ベンチマーク対象モデル(軽量で推論オーバーヘッドが少ないモデル)
BENCHMARK_MODEL: str = "qwen2.5-coder:0.5b"
# 検証対象のスレッド数リスト(物理4 / 論理8の境界をカバー)
TEST_THREADS: List[int] = [1, 2, 3, 4, 5, 6, 8, 10, 12]
# Prompt Eval測定用の長文プロンプト(約300〜400トークン)
PREFILL_PROMPT: str = (
"Please provide a comprehensive and detailed explanation of the "
"differences between multithreading and multiprocessing in modern "
"operating systems, specifically focusing on CPU cache locality, "
"context switching overhead, memory sharing, IPC mechanisms, "
"and hardware-level hyper-threading (SMT) behavior on x86 architectures."
)
def call_ollama(
prompt: str,
num_thread: int,
num_predict: int,
num_ctx: int = 2048,
) -> Dict[str, Any]:
"""指定されたスレッド数とパラメータでOllama APIを呼び出し、計測値を返す.
Args:
prompt: 入力プロンプト文字列
num_thread: 使用スレッド数
num_predict: 生成最大トークン数
num_ctx: コンテキスト長
Returns:
OllamaのAPIレスポンス辞書
"""
payload = {
"model": BENCHMARK_MODEL,
"prompt": prompt,
"stream": False,
"options": {
"num_thread": num_thread,
"num_predict": num_predict,
"num_ctx": num_ctx,
"temperature": 0.0, # 決定論的な挙動にするため0に固定
},
}
req_data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
OLLAMA_API_URL,
data=req_data,
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req) as resp:
res_text = resp.read().decode("utf-8")
result: Dict[str, Any] = json.loads(res_text)
return result
def run_benchmark() -> List[Dict[str, Any]]:
"""各スレッド数でPrefillとGenerationの速度を測定する."""
results: List[Dict[str, Any]] = []
print(f"=== スレッド数ベンチマーク開始 (Model: {BENCHMARK_MODEL}) ===")
# 事前ウォームアップ実行(初回のモデルロード・ページフォールト排除)
print("モデルウォームアップ中...")
call_ollama("Hello", num_thread=4, num_predict=5)
time.sleep(2.0)
for th in TEST_THREADS:
print(f"\n--- 計測中: num_thread = {th} ---")
# 1. Prefill(Prompt Processing)計測: 長文入力・短文出力
prefill_res = call_ollama(PREFILL_PROMPT, num_thread=th, num_predict=1)
p_count = prefill_res.get("prompt_eval_count", 0)
p_duration_ns = prefill_res.get("prompt_eval_duration", 1)
p_tok_sec = (p_count / p_duration_ns) * 1e9 if p_duration_ns > 0 else 0
# CPU冷却のためのインターバル
time.sleep(1.0)
# 2. Generation(Token Decode)計測: 短文入力・100トークン生成
prompt_code = (
"Write a Python function to sort a list using quicksort."
)
gen_res = call_ollama(
prompt_code,
num_thread=th,
num_predict=100,
)
g_count = gen_res.get("eval_count", 0)
g_duration_ns = gen_res.get("eval_duration", 1)
g_tok_sec = (g_count / g_duration_ns) * 1e9 if g_duration_ns > 0 else 0
record = {
"num_thread": th,
"prompt_eval_count": p_count,
"prompt_eval_duration_ms": round(p_duration_ns / 1e6, 2),
"prompt_eval_tok_per_sec": round(p_tok_sec, 2),
"eval_count": g_count,
"eval_duration_ms": round(g_duration_ns / 1e6, 2),
"eval_tok_per_sec": round(g_tok_sec, 2),
}
results.append(record)
print(
f" Prefill: {p_tok_sec:.2f} tok/s ({p_count} tokens in "
f"{p_duration_ns / 1e6:.1f} ms)"
)
print(
f" Decode: {g_tok_sec:.2f} tok/s ({g_count} tokens in "
f"{g_duration_ns / 1e6:.1f} ms)"
)
# サーマルスロットリング防止のためのクールダウン
time.sleep(2.0)
return results
def main() -> None:
"""メイン実行関数."""
script_dir = os.path.dirname(os.path.abspath(__file__))
output_path = os.path.join(
script_dir, "..", "threads_benchmark_results.json"
)
benchmark_data = run_benchmark()
# 結果をJSONとして保存
with open(output_path, "w", encoding="utf-8") as f:
json.dump(benchmark_data, f, indent=2, ensure_ascii=False)
print(f"\n結果を保存しました: {os.path.abspath(output_path)}")
if __name__ == "__main__":
main()
- num_ctx(512〜16384)ごとの理論KVキャッシュサイズ、llama-server のKVバッファ確保量(server.log)、およびプロセス実メモリ(RSS)を計測するスクリプトです。
scripts/bench_context_and_kv.py の全文を展開する
"""コンテキストウィンドウ(num_ctx)とKVキャッシュのメモリ&速度測定スクリプト.
num_ctxを512から16384まで変化させ、KVキャッシュの理論メモリサイズと
Ollama/llama.cppのログおよびプロセス実メモリ(RSS)、推論速度を比較検証する。
"""
import json
import os
import re
import subprocess
import time
import urllib.error
import urllib.request
from typing import Any, Dict, List, Optional
OLLAMA_API_URL: str = "http://127.0.0.1:11434/api/generate"
BENCHMARK_MODEL: str = "qwen2.5-coder:0.5b"
# 検証対象のコンテキストサイズ
TEST_CONTEXT_SIZES: List[int] = [512, 1024, 2048, 4096, 8192, 16384]
# Qwen2.5-0.5B のモデル構造定数
MODEL_LAYERS: int = 24
MODEL_KV_HEADS: int = 2
MODEL_HEAD_DIM: int = 64
BYTES_PER_FP16: int = 2 # f16 は 1要素あたり2バイト
LOG_PATH: str = os.path.expanduser("~/.ollama/logs/server.log")
def calculate_theoretical_kv_cache_mib(num_ctx: int) -> float:
"""KVキャッシュの理論サイズ(MiB)を算出する.
式: 2 (KとV) * layers * kv_heads * head_dim * num_ctx * 2 (f16 bytes)
"""
total_bytes = (
2 * MODEL_LAYERS * MODEL_KV_HEADS * MODEL_HEAD_DIM * num_ctx * 2
)
return total_bytes / (1024 * 1024)
def get_llama_server_rss_kb() -> Optional[int]:
"""現在稼働しているllama-serverプロセスのRSS(物理メモリKB)を取得する."""
try:
cmd = ["ps", "-eo", "rss,comm"]
res = subprocess.run(
cmd, capture_output=True, text=True, check=True
)
for line in res.stdout.splitlines():
if "llama-server" in line:
parts = line.strip().split()
if parts:
return int(parts[0])
except Exception:
pass
return None
def parse_latest_kv_log() -> Optional[float]:
"""server.logの末尾から直近のKVキャッシュサイズ(MiB)を正規表現で抽出."""
if not os.path.exists(LOG_PATH):
return None
try:
with open(LOG_PATH, "r", encoding="utf-8", errors="ignore") as f:
lines = f.readlines()[-150:] # 末尾150行を走査
for line in reversed(lines):
# 例: llama_kv_cache: CPU KV buffer size = 48.00 MiB
m = re.search(r"CPU KV buffer size\s*=\s*([\d\.]+)\s*MiB", line)
if m:
return float(m.group(1))
except Exception:
pass
return None
def call_ollama_ctx(
prompt: str,
num_ctx: int,
num_predict: int = 10,
) -> Dict[str, Any]:
"""指定されたnum_ctxでOllama APIを呼び出す."""
payload = {
"model": BENCHMARK_MODEL,
"prompt": prompt,
"stream": False,
"options": {
"num_ctx": num_ctx,
"num_thread": 4, # 物理コア4に固定
"num_predict": num_predict,
"temperature": 0.0,
},
}
req_data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
OLLAMA_API_URL,
data=req_data,
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req) as resp:
res_text = resp.read().decode("utf-8")
result: Dict[str, Any] = json.loads(res_text)
return result
def run_context_benchmark() -> List[Dict[str, Any]]:
"""各num_ctxでKVキャッシュと推論レイテンシを実測する."""
results: List[Dict[str, Any]] = []
print(f"=== コンテキスト長ベンチマーク (Model: {BENCHMARK_MODEL}) ===")
test_prompt = (
"Analyze the performance characteristics of memory caching "
"hierarchies, including L1 data cache, L2 unified cache, L3 cache, "
"and Main Memory bandwidth constraints during matrix multiplication."
)
for ctx in TEST_CONTEXT_SIZES:
print(f"\n--- 計測中: num_ctx = {ctx} ---")
theoretical_mib = calculate_theoretical_kv_cache_mib(ctx)
# API呼び出し(llama-serverが指定num_ctxで再起動・更新される)
res = call_ollama_ctx(test_prompt, num_ctx=ctx, num_predict=20)
# サーバーログおよびプロセスRSSの取得
time.sleep(0.5)
log_kv_mib = parse_latest_kv_log()
server_rss_kb = get_llama_server_rss_kb()
server_rss_mib = (
round(server_rss_kb / 1024, 2) if server_rss_kb else None
)
p_count = res.get("prompt_eval_count", 0)
p_dur_ms = round(res.get("prompt_eval_duration", 0) / 1e6, 2)
p_tok_sec = (
round((p_count / (p_dur_ms / 1000)), 2) if p_dur_ms > 0 else 0
)
e_count = res.get("eval_count", 0)
e_dur_ms = round(res.get("eval_duration", 0) / 1e6, 2)
e_tok_sec = (
round((e_count / (e_dur_ms / 1000)), 2) if e_dur_ms > 0 else 0
)
record = {
"num_ctx": ctx,
"theoretical_kv_mib": round(theoretical_mib, 2),
"logged_kv_mib": log_kv_mib,
"process_rss_mib": server_rss_mib,
"prompt_eval_count": p_count,
"prompt_eval_duration_ms": p_dur_ms,
"prompt_eval_tok_per_sec": p_tok_sec,
"eval_count": e_count,
"eval_duration_ms": e_dur_ms,
"eval_tok_per_sec": e_tok_sec,
}
results.append(record)
print(f" 理論KVキャッシュ: {theoretical_mib:.2f} MiB")
print(f" ログKVキャッシュ: {log_kv_mib} MiB")
print(f" プロセス実メモリ: {server_rss_mib} MiB")
print(f" Prefill速度: {p_tok_sec:.2f} tok/s")
print(f" Decode速度: {e_tok_sec:.2f} tok/s")
time.sleep(2.0)
return results
def main() -> None:
"""メイン実行関数."""
script_dir = os.path.dirname(os.path.abspath(__file__))
output_path = os.path.join(
script_dir, "..", "context_kv_benchmark_results.json"
)
data = run_context_benchmark()
with open(output_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"\n結果を保存しました: {os.path.abspath(output_path)}")
if __name__ == "__main__":
main()
- num_batch 別のプロンプト処理(Prefill)速度の推移を計測するスクリプトです。
scripts/bench_batch_size.py の全文を展開する
"""バッチサイズ(num_batch)によるPrompt Eval処理速度ベンチマーク.
長文プロンプト(数百〜1000トークン)処理時において、num_batchを32から2048まで
変化させ、CPUキャッシュ効率とPrefillスループット(tok/s)の関係を実測する。
"""
import json
import os
import time
import urllib.error
import urllib.request
from typing import Any, Dict, List
OLLAMA_API_URL: str = "http://127.0.0.1:11434/api/generate"
BENCHMARK_MODEL: str = "qwen2.5-coder:0.5b"
# 検証対象のバッチサイズ
TEST_BATCH_SIZES: List[int] = [32, 64, 128, 256, 512, 1024, 2048]
# 長文プロンプト(約600〜700トークン)
LONG_PROMPT: str = """
Below is an essay about computer architecture:
In modern superscalar processors, the memory hierarchy plays a critical
role in determining overall instruction throughput. The latency gap between
CPU registers and main dynamic RAM (DRAM) has historically widened,
a phenomenon commonly referred to as the memory wall. To alleviate this
bottleneck, hardware designers introduced multi-level caching architectures
comprising L1 instruction and data caches, unified L2 caches, and shared L3
caches.
When executing matrix multiplications (GEMM) in deep neural networks,
computational kernels must carefully partition matrices into tiles that
fit snugly into the fastest cache levels. For single-token decoding,
the arithmetic intensity is notoriously low because every parameter tensor
must be fetched from memory for each token. In contrast, prompt processing
(prefill) achieves significantly higher arithmetic intensity by grouping
multiple tokens into batch dimensions, enabling high-performance SIMD
instructions such as AVX-512 and VNNI to achieve peak throughput.
Explain the trade-offs of batch sizing in CPU inference engines.
"""
def call_ollama_batch(
prompt: str,
num_batch: int,
num_thread: int = 4,
) -> Dict[str, Any]:
"""指定されたnum_batchでOllama APIを呼び出す."""
payload = {
"model": BENCHMARK_MODEL,
"prompt": prompt,
"stream": False,
"options": {
"num_batch": num_batch,
"num_thread": num_thread,
"num_predict": 5, # Prefill測定が主目的のため生成は最小限
"num_ctx": 4096,
"temperature": 0.0,
},
}
req_data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
OLLAMA_API_URL,
data=req_data,
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req) as resp:
res_text = resp.read().decode("utf-8")
result: Dict[str, Any] = json.loads(res_text)
return result
def run_batch_benchmark() -> List[Dict[str, Any]]:
"""各バッチサイズでPrefill速度を実測する."""
results: List[Dict[str, Any]] = []
print(f"=== バッチサイズ検証 (Model: {BENCHMARK_MODEL}) ===")
for batch in TEST_BATCH_SIZES:
print(f"\n--- 計測中: num_batch = {batch} ---")
res = call_ollama_batch(LONG_PROMPT, num_batch=batch)
p_count = res.get("prompt_eval_count", 0)
p_dur_ns = res.get("prompt_eval_duration", 1)
p_dur_ms = round(p_dur_ns / 1e6, 2)
p_tok_sec = (
round((p_count / p_dur_ns) * 1e9, 2) if p_dur_ns > 0 else 0
)
record = {
"num_batch": batch,
"prompt_eval_count": p_count,
"prompt_eval_duration_ms": p_dur_ms,
"prompt_eval_tok_per_sec": p_tok_sec,
}
results.append(record)
print(
f" Prompt Eval: {p_tok_sec:.2f} tok/s ({p_count} tokens in "
f"{p_dur_ms:.1f} ms)"
)
time.sleep(2.0)
return results
def main() -> None:
"""メイン実行関数."""
script_dir = os.path.dirname(os.path.abspath(__file__))
output_path = os.path.join(
script_dir, "..", "batch_size_benchmark_results.json"
)
data = run_batch_benchmark()
with open(output_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"\n結果を保存しました: {os.path.abspath(output_path)}")
if __name__ == "__main__":
main()
- OLLAMA_KV_CACHE_TYPE(f16 / q8_0 / q4_0)によるメモリ削減と応答品質を比較するスクリプトです。
scripts/bench_kv_cache_types.py の全文を展開する
"""OLLAMA_KV_CACHE_TYPE(f16, q8_0, q4_0)の比較検証スクリプト.
OllamaのKVキャッシュ量子化環境変数を切り替え、KVキャッシュメモリ確保量、
ブロック構造の理論計算値との一致、および推論スループット・精度を実測する。
"""
import json
import os
import re
import subprocess
import time
import urllib.error
import urllib.request
from typing import Any, Dict, List, Optional
BENCHMARK_MODEL: str = "qwen2.5-coder:0.5b"
TEST_TYPES: List[str] = ["f16", "q8_0", "q4_0"]
TEST_PORT: int = 11438
TEST_URL: str = f"http://127.0.0.1:{TEST_PORT}/api/generate"
TEMP_LOG: str = "/tmp/ollama_kv_bench.log"
# Qwen2.5-0.5B のモデル構造パラメータ
NUM_LAYERS: int = 24
KV_HEADS: int = 2
HEAD_DIM: int = 64
NUM_CTX: int = 4096
def calculate_kv_cache_theoretical(
cache_type: str, num_ctx: int = NUM_CTX
) -> float:
"""各キャッシュタイプの1要素あたりのバイト数から理論MiBを算出.
- f16: 1要素2バイト
- q8_0: 32要素あたり (32バイト + 2バイトスケール) = 34/32 = 1.0625バイト
- q4_0: 32要素あたり (16バイト + 2バイトスケール) = 18/32 = 0.5625バイト
"""
total_elements = 2 * NUM_LAYERS * KV_HEADS * HEAD_DIM * num_ctx
if cache_type == "f16":
bytes_per_elem = 2.0
elif cache_type == "q8_0":
bytes_per_elem = 34.0 / 32.0
elif cache_type == "q4_0":
bytes_per_elem = 18.0 / 32.0
else:
bytes_per_elem = 2.0
return (total_elements * bytes_per_elem) / (1024 * 1024)
def parse_kv_size_from_log(log_file: str) -> Optional[float]:
"""サーバーログからCPU KV buffer sizeを抽出する."""
if not os.path.exists(log_file):
return None
try:
with open(log_file, "r", encoding="utf-8", errors="ignore") as f:
for line in reversed(f.readlines()):
m = re.search(
r"CPU KV buffer size\s*=\s*([\d\.]+)\s*MiB", line
)
if m:
return float(m.group(1))
except Exception:
pass
return None
def run_benchmark_for_type(cache_type: str) -> Dict[str, Any]:
"""特定のKVキャッシュタイプでOllamaを起動し、計測を行う."""
print(f"\n--- 計測中: OLLAMA_KV_CACHE_TYPE = {cache_type} ---")
# 既存のテスト用ログを初期化
if os.path.exists(TEMP_LOG):
os.remove(TEMP_LOG)
env = os.environ.copy()
env["OLLAMA_HOST"] = f"127.0.0.1:{TEST_PORT}"
env["OLLAMA_KV_CACHE_TYPE"] = cache_type
# Ollamaサーバーをサブプロセスとして起動
ollama_bin = "/Applications/Ollama.app/Contents/Resources/ollama"
with open(TEMP_LOG, "w") as log_f:
proc = subprocess.Popen(
[ollama_bin, "serve"],
env=env,
stdout=log_f,
stderr=subprocess.STDOUT,
)
try:
# 起動待機
time.sleep(2.0)
# 推論リクエスト送信
prompt = (
"Write a Python function to compute the fibonacci numbers "
"using memoization."
)
payload = {
"model": BENCHMARK_MODEL,
"prompt": prompt,
"stream": False,
"options": {
"num_ctx": NUM_CTX,
"num_thread": 4,
"num_predict": 60,
"temperature": 0.0,
},
}
req_data = json.dumps(payload).encode("utf-8")
req = urllib.request.Request(
TEST_URL,
data=req_data,
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
# サーバーログからKVサイズを取得
time.sleep(0.5)
logged_kv_mib = parse_kv_size_from_log(TEMP_LOG)
theoretical_mib = calculate_kv_cache_theoretical(cache_type)
p_count = data.get("prompt_eval_count", 0)
p_dur_ns = data.get("prompt_eval_duration", 1)
p_tok_sec = (
round((p_count / p_dur_ns) * 1e9, 2) if p_dur_ns > 0 else 0
)
e_count = data.get("eval_count", 0)
e_dur_ns = data.get("eval_duration", 1)
e_tok_sec = (
round((e_count / e_dur_ns) * 1e9, 2) if e_dur_ns > 0 else 0
)
response_text = data.get("response", "")
record = {
"cache_type": cache_type,
"num_ctx": NUM_CTX,
"theoretical_kv_mib": round(theoretical_mib, 2),
"logged_kv_mib": logged_kv_mib,
"prompt_eval_tok_per_sec": p_tok_sec,
"eval_tok_per_sec": e_tok_sec,
"response_sample": response_text[:120].strip(),
}
print(f" 理論KVサイズ: {theoretical_mib:.2f} MiB")
print(f" 実測KVサイズ: {logged_kv_mib} MiB")
print(f" Prefill速度: {p_tok_sec:.2f} tok/s")
print(f" Decode速度: {e_tok_sec:.2f} tok/s")
return record
finally:
# プロセスの終了処理
proc.terminate()
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
proc.kill()
# 残存llama-serverのクリーンアップ
subprocess.run(["killall", "-9", "llama-server"], capture_output=True)
time.sleep(1.0)
def main() -> None:
"""メイン実行関数."""
script_dir = os.path.dirname(os.path.abspath(__file__))
output_path = os.path.join(
script_dir, "..", "kv_cache_type_results.json"
)
print(f"=== KVキャッシュ量子化検証 (Model: {BENCHMARK_MODEL}) ===")
results: List[Dict[str, Any]] = []
for c_type in TEST_TYPES:
rec = run_benchmark_for_type(c_type)
results.append(rec)
time.sleep(2.0)
with open(output_path, "w", encoding="utf-8") as f:
json.dump(results, f, indent=2, ensure_ascii=False)
print(f"\n結果を保存しました: {os.path.abspath(output_path)}")
if __name__ == "__main__":
main()
まとめ
実測結果をまとめます。
- スレッド数(num_thread):
- 原則は物理コア数(検証環境では4)に設定するのが安全かつ高速。
- Decode速度をさらに引き上げたい場合でも、物理コア数 + 1〜2(検証環境では6)にとどめる。
- 論理コア数(8)やそれ以上を設定すると、キャッシュ競合とスレッド競合で遅くなり、コア数超過では速度が急落する。
- コンテキスト長(num_ctx):
- 必要な長さに応じて設定して問題ない。入力プロンプトが短い間は速度低下は起きない。
- メモリ消費量は理論式($2 \times \text{layers} \times \text{kv_heads} \times \text{head_dim} \times \text{num_ctx} \times 2$)の通りに線形増加する。
- バッチサイズ(num_batch):
- 256 または 512 が最適。32などの小さい値はプロンプト処理が遅くなるが、1024以上にしてもCPUキャッシュの制約で頭打ちになる。
- KVキャッシュ量子化(OLLAMA_KV_CACHE_TYPE):
- メモリ優先なら q4_0(約72%削減)、速度優先ならデフォルトの f16、バランス型なら q8_0。
Modelfileでこれらを恒久設定したい場合は、以下のように記述して ollama create で登録できます。
FROM qwen2.5-coder:0.5b
# CPU推論に最適化したパラメータ設定
PARAMETER num_thread 4
PARAMETER num_ctx 4096
PARAMETER num_batch 256