Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
name: CI

on:
push:
branches: [main]
pull_request:
workflow_dispatch:

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip

- name: Install dependencies
run: pip install -r requirements-dev.txt

# Fails if requirements.txt is missing a package that the script imports.
- name: Import check
run: python benchmark_serving.py --help

- name: Lint
run: ruff check .

- name: Test
run: pytest -q

docker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

# Builds the dependency layers only. The full image downloads the
# ShareGPT dataset, which is too large for every CI run.
- name: Build dependency layers
run: |
sed '/^RUN wget /,$d' Dockerfile > Dockerfile.ci
docker build -f Dockerfile.ci -t inference-benchmark:ci .
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
.idea/
__pycache__/
*.pyc
.pytest_cache/
.venv/
venv/
Dockerfile.ci
6 changes: 4 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM python:3.9.20-slim-bookworm as dev
FROM python:3.11-slim-bookworm AS dev

RUN apt-get update -y \
&& apt-get install -y python3-pip git vim curl wget
Expand All @@ -15,7 +15,9 @@ RUN wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfilter

COPY benchmark_serving.py benchmark_serving.py
COPY latency_throughput_curve.sh latency_throughput_curve.sh
COPY datasets/*.json /workspace/

# Custom datasets are not in this repository. Generate them with
# datasets/import_dataset.py, then mount or copy the JSON into /workspace.

RUN chmod +x latency_throughput_curve.sh
RUN chmod +x benchmark_serving.py
35 changes: 32 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,42 @@
> [!NOTE]
> This repository is no longer under active development. For inference benchmarking, use https://github.com/kubernetes-sigs/inference-perf instead.
>
## Archive Status

This repository is maintained by AI Software Commons.

Original project:
https://github.com/AI-Hypercomputer/inference-benchmark

Upstream status: Archived
Fork status: MAINTAINED FORK

This repository is not affiliated with or endorsed by Google or AI-Hypercomputer.

> [!IMPORTANT]
> **For new benchmarking work, use https://github.com/kubernetes-sigs/inference-perf.**
> It is the actively developed successor and the upstream project points to it.
>
> This fork exists for one reason: to keep the original harness installable and
> runnable, so benchmark numbers produced with it stay reproducible. Scope is
> limited to dependency health, packaging, and correctness fixes. No new features.

---

# Inference Benchmark

A model server agnostic inference benchmarking tool that can be used to
benchmark LLMs running on different infrastructure like GPUs and TPUs. It can also
be run on a GKE cluster as a container.

## Changes in this fork

- Fixed: TPOT statistics were printed but never written to the saved JSON results.
- Fixed: `docker build` failed because `COPY datasets/*.json` matched no files.
- `requirements.txt` now lists only what `benchmark_serving.py` imports. It no
longer installs `torch`, `xformers`, `ray`, `fastapi`, or `uvicorn`. This is a
benchmark client, not a model server.
- Development tools moved to `requirements-dev.txt`.
- Docker base image moved from Python 3.9 (end of life) to Python 3.11.
- Added CI and regression tests.

## Run the benchmark

1. Create a python virtualenv.
Expand Down
6 changes: 4 additions & 2 deletions analysis/analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,10 @@ def parse_and_plot(folder_path, instance_price_per_hour=None):
print(f" - Note: 'avg_normalized_time_per_output_token_ms' not found in {filename}.")
else:
missing_core = []
if throughput is None: missing_core.append("'throughput'")
if request_rate is None: missing_core.append("'request_rate'")
if throughput is None:
missing_core.append("'throughput'")
if request_rate is None:
missing_core.append("'request_rate'")
print(f"Warning: Missing core metric(s) ({', '.join(missing_core)}) in {filename}. Skipping this file for plots.")

except (json.JSONDecodeError, FileNotFoundError) as e:
Expand Down
3 changes: 2 additions & 1 deletion benchmark_serving.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import random
import requests
import time
from typing import AsyncGenerator, List, Optional, Tuple, Dict
from typing import AsyncGenerator, List, Tuple, Dict
from prometheus_client import start_http_server, Histogram, Gauge, Counter
import logging

Expand Down Expand Up @@ -873,6 +873,7 @@ async def print_and_save_result(args: argparse.Namespace, benchmark_duration_sec
])),
**ttft_stats,
**itls_stats,
**tpot_stats,
# NOTE: The latency below includes requests awaiting time on server side.
# It's not comparable with the model inference latency for batch size 1.
**(get_stats_for_set("latency_ms", "milliseconds/request (includes waiting time on server)" ,[latency for _, _, latency in request_latencies])),
Expand Down
3 changes: 1 addition & 2 deletions datasets/import_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import pandas as pd
from tqdm import tqdm
import matplotlib.pyplot as plt
import os
import subprocess
import csv

Expand Down Expand Up @@ -72,7 +71,7 @@ def calculate_token_stats(dataset, filename, tokenizer_name, max_samples=None, i
output_token_counts = []
prompts = []
responses = []
results, histogram_data, js = None, None, None
results, histogram_data = None, None

# Process each example
for example in tqdm(dataset, desc="sampling examples", unit="example"):
Expand Down
14 changes: 14 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Development dependencies. Not needed to run the benchmark.
-r requirements.txt

# formatting and linting
ruff==0.1.5

# type checking
mypy==0.991
types-requests
types-setuptools

# testing
pytest
pytest-asyncio
50 changes: 16 additions & 34 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,39 +1,21 @@
# formatting
yapf==0.32.0
toml==0.10.2
ruff==0.1.5
# Runtime dependencies for benchmark_serving.py.
# This tool is an HTTP client. It does not run a model, so it does not need
# torch, xformers, ray, or a server framework.
# Dev tools are in requirements-dev.txt.
# The dataset tool has its own file: datasets/requirements.txt.
# The analysis tool needs only matplotlib: see analysis/README.md.

# type checking
mypy==0.991
types-PyYAML
types-requests
types-setuptools

# testing
pytest
pytest-forked
pytest-asyncio
httpx
einops # required for MPT
openai
aiohttp
numpy
requests
transformers >= 4.42.0 # Required for Qwen2. Used for AutoTokenizer only.

# run
ninja # For faster builds.
psutil
ray >= 2.9
sentencepiece # Required for LLaMA tokenizer.
numpy < 2.0
torch
transformers >= 4.42.0 # Required for Qwen2
xformers
fastapi
uvicorn[standard]
pydantic >= 2.0 # Required for OpenAI server.
aioprometheus[starlette]
pynvml == 11.5.0
accelerate
aiohttp
# Metrics export
prometheus_client >= 0.21.0

# Google Cloud output upload and auth
google-auth
google-cloud-storage >= 2.18.2
prometheus_client >= 0.21.0
protobuf

# Add sentencepiece if your model uses a slow SentencePiece tokenizer.
79 changes: 79 additions & 0 deletions test_benchmark_serving.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""Regression checks for the result assembly in benchmark_serving.py.

Run with: pytest test_benchmark_serving.py
"""

import argparse
import asyncio

import benchmark_serving as bs


def _make_args():
return argparse.Namespace(
stream_request=True,
machine_cost=None,
scrape_server_metrics=False,
save_json_results=True,
num_prompts=3,
backend="vllm",
pm_namespace="",
pm_job="",
)


def _capture_result(monkeypatch):
"""Runs print_and_save_result once and returns the assembled result dict."""
captured = {}

def fake_save(args, benchmark_result, server_metrics, model, errors):
captured.update(benchmark_result)

monkeypatch.setattr(bs, "save_json_results", fake_save)

async def run():
# print_and_save_result reads the QPS counter, which needs _end_time set.
bs.AsyncRequestCounter._instance = None
counter = await bs.AsyncRequestCounter(target_requests=3)
for _ in range(3):
await counter.increment()

# (prompt_len, output_len, latency_ms) per request.
request_latencies = [(10, 5, 100.0), (20, 10, 200.0), (30, 15, 300.0)]
await bs.print_and_save_result(
args=_make_args(),
benchmark_duration_sec=10.0,
total_requests=3,
model="test-model",
request_latencies=request_latencies,
ttfts=[10.0, 20.0, 30.0],
itls=[1.0, 2.0, 3.0],
tpots=[5.0, 10.0, 15.0],
errors=bs.init_errors_map(),
)

asyncio.run(run())
return captured


def test_tpot_stats_reach_the_saved_result(monkeypatch):
"""TPOT was printed but dropped before the JSON save. Guard against that."""
result = _capture_result(monkeypatch)
assert result["avg_TPOT_ms"] == 10.0
assert result["median_TPOT_ms"] == 10.0
assert result["min_TPOT_ms"] == 5.0
assert result["max_TPOT_ms"] == 15.0


def test_streaming_latency_metrics_are_all_present(monkeypatch):
result = _capture_result(monkeypatch)
for name in ("TTFT_ms", "ITL_ms", "TPOT_ms"):
for stat in ("avg", "median", "sd", "min", "max", "p90", "p99"):
assert f"{stat}_{name}" in result, f"missing {stat}_{name}"


def test_throughput_totals(monkeypatch):
result = _capture_result(monkeypatch)
assert result["total_input_tokens"] == 60
assert result["total_output_token"] == 30
assert result["throughput"] == 3.0 # 30 output tokens over 10 seconds
Loading