蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

测量 CPU 上的上下文、KV 缓存和输出速度

PYTHONWindows、CPython 3.12、Ollama 0.40.15,另有固定版 Python 和 Node Ollama 客户端。performance_lab.py
performance_lab.py69 行
"""Compare CPU placement, token timings and runner diagnostics on loopback."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import re
from threading import Barrier
from time import perf_counter

from local_http import exchange

SAMPLE = "mbsky-measure:sample"


def generate(port, context, threads, token_limit=12):
    status, reply = exchange(port, "/api/generate", dict(model=SAMPLE, prompt="ping", raw=True, stream=False,
        options=dict(num_ctx=context, num_thread=threads, num_predict=token_limit, seed=42, temperature=0.3)))
    result = {"context_input": context, "thread_input": threads, "status": status}
    if status != 200:
        return {**result, "error": reply["error"]}
    timings = {name: reply[name] for name in ("eval_count", "eval_duration", "load_duration", "prompt_eval_duration",
               "prompt_eval_count", "total_duration")}
    return {**result, **timings, "text": reply["response"].strip(), "done": reply["done_reason"],
            "decode_tokens_per_second": round(reply["eval_count"] * 1e9 / reply["eval_duration"], 3) if reply["eval_duration"] > 0 else None}


def observe(port, log, burst):
    model_rows = []
    for context, threads in [(128, 1), (128, 2), (256, 1)]:
        result = generate(port, context, threads)
        _, active = exchange(port, "/api/ps")
        result["active"] = [{name: row[name] for name in ("name", "size", "size_vram", "context_length")}
                            | {"weights": row["details"]["quantization_level"]} for row in active["models"]]
        _, unloaded = exchange(port, "/api/generate", dict(model=SAMPLE, stream=False, keep_alive=0))
        result["unload"] = unloaded["done_reason"]
        model_rows.append(result)

    measured = {}
    if burst:
        gate = Barrier(4)

        def worker(_):
            gate.wait(timeout=10)
            return generate(port, 128, 1, 24)

        start = perf_counter()
        with ThreadPoolExecutor(max_workers=4) as executor:
            replies = list(executor.map(worker, range(4)))
        seconds = perf_counter() - start
        measured = dict(seconds=seconds, statuses=[row["status"] for row in replies],
                        completed_tokens=sum(row.get("eval_count", 0) for row in replies))
        measured["end_to_end_tokens_per_second"] = measured["completed_tokens"] / seconds

    native = log.read_text(encoding="utf8", errors="replace")
    return dict(rows=model_rows, burst=measured,
        native_threads=[int(value) for value in re.findall(r"llama threadpool init, n_threads = (\d+)", native)],
        flash=re.findall(r"llama_context: flash_attn\s*=\s*(\w+)", native),
        cache_mib=[float(value) for value in re.findall(r"CPU KV buffer size =\s*([\d.]+) MiB", native)],
        missing_flash="quantized V cache requires flash_attn to be enabled" in native)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--port", type=int, required=True)
    parser.add_argument("--log", type=Path, required=True)
    parser.add_argument("--burst", action="store_true")
    args = parser.parse_args()
    print(json.dumps(observe(args.port, args.log, args.burst)))
本例需在 Windows、CPython 3.12、Ollama 0.40.15,另有固定版 Python 和 Node Ollama 客户端。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、CPython 3.12、Ollama 0.40.15,另有固定版 Python 和 Node Ollama 客户端。

入口文件:projects/ollama-gpu-cloud/performance_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 performance_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、CPython 3.12、Ollama 0.40.15,另有固定版 Python 和 Node Ollama 客户端。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Ollama

课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202612a225.zip

下载课程关联工程包:Ollama

课程关联工程包(登记关联29章) · 含当前章节或实例 · mbskycom202612a217.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习