datacenterbench 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,211 @@
1
+ """datacenterbench — benchmark throughput, latency, and energy of inference workloads.
2
+
3
+ Runs standardised model serving workloads against an endpoint or a local
4
+ runtime, collects per-request latency and token throughput, and produces a
5
+ reproducible report you can compare across hardware.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import random
13
+ import statistics
14
+ import time
15
+ from dataclasses import dataclass, field, asdict
16
+ from pathlib import Path
17
+ from typing import Any, Iterable
18
+
19
+ __version__ = "0.1.0"
20
+
21
+ __all__ = [
22
+ "run",
23
+ "Workload",
24
+ "Config",
25
+ "Result",
26
+ "WorkloadError",
27
+ ]
28
+
29
+
30
+ class WorkloadError(Exception):
31
+ """Raised when a workload or config is invalid."""
32
+
33
+
34
+ _VALID_WORKLOAD_KINDS = ("chat", "embeddings", "vision", "batch")
35
+
36
+
37
+ @dataclass
38
+ class Workload:
39
+ """What to run.
40
+
41
+ Args:
42
+ kind: One of ``chat``, ``embeddings``, ``vision``, ``batch``.
43
+ model: The model identifier to benchmark.
44
+ params: Optional per-workload parameters (batch size, seq len, ...).
45
+ """
46
+
47
+ kind: str
48
+ model: str
49
+ params: dict[str, Any] = field(default_factory=dict)
50
+
51
+ def __post_init__(self) -> None:
52
+ if self.kind not in _VALID_WORKLOAD_KINDS:
53
+ raise WorkloadError(f"kind must be one of {_VALID_WORKLOAD_KINDS}, got {self.kind!r}")
54
+ if not self.model:
55
+ raise WorkloadError("model is required")
56
+
57
+
58
+ @dataclass
59
+ class Config:
60
+ """How to run.
61
+
62
+ Args:
63
+ concurrency: Concurrency levels to sweep (e.g. ``[1, 8, 32]``).
64
+ prompt_set: Identifier for the prompt set to use.
65
+ endpoint: URL of the inference endpoint (or ``local`` for driver mode).
66
+ duration_s: Per-concurrency run duration in seconds.
67
+ seed: RNG seed for reproducible runs.
68
+ warmup: Number of warmup requests before measurement.
69
+ """
70
+
71
+ concurrency: list[int] = field(default_factory=lambda: [1, 8, 32])
72
+ prompt_set: str = "ultrachat-1k"
73
+ endpoint: str = "local"
74
+ duration_s: float = 10.0
75
+ seed: int = 0
76
+ warmup: int = 10
77
+
78
+ def __post_init__(self) -> None:
79
+ if not self.concurrency or any(c < 1 for c in self.concurrency):
80
+ raise WorkloadError("concurrency must be a non-empty list of positive ints")
81
+
82
+
83
+ def _percentile(values: list[float], p: float) -> float:
84
+ if not values:
85
+ return 0.0
86
+ s = sorted(values)
87
+ k = (len(s) - 1) * p
88
+ f = int(k)
89
+ c = min(f + 1, len(s) - 1)
90
+ if f == c:
91
+ return s[f]
92
+ return s[f] + (s[c] - s[f]) * (k - f)
93
+
94
+
95
+ @dataclass
96
+ class Result:
97
+ """The result of a benchmark run.
98
+
99
+ Attributes:
100
+ workload: The :class:`Workload` that ran.
101
+ config: The :class:`Config` used.
102
+ per_concurrency: List of per-concurrency summaries with throughput,
103
+ latency percentiles, and token counts.
104
+ timestamp: Wall-clock time of the run.
105
+ """
106
+
107
+ workload: Workload
108
+ config: Config
109
+ per_concurrency: list[dict[str, Any]] = field(default_factory=list)
110
+ timestamp: float = field(default_factory=time.time)
111
+
112
+ def summary(self) -> str:
113
+ """Return a short human-readable summary string."""
114
+ if not self.per_concurrency:
115
+ return "no data"
116
+ best = max(self.per_concurrency, key=lambda c: c.get("throughput_rps", 0))
117
+ return (
118
+ f"{self.workload.kind}/{self.workload.model}: "
119
+ f"peak {best['throughput_rps']:.1f} rps @ c={best['concurrency']} "
120
+ f"(p99={best['latency_p99_ms']:.1f}ms)"
121
+ )
122
+
123
+ def write(self, path: str) -> Path:
124
+ """Write JSON + HTML reports under ``path`` (a directory or file)."""
125
+ out = Path(path)
126
+ if out.suffix == "":
127
+ out.mkdir(parents=True, exist_ok=True)
128
+ (out / "report.json").write_text(self.to_json(), encoding="utf-8")
129
+ (out / "report.html").write_text(self.to_html(), encoding="utf-8")
130
+ return out
131
+ out.parent.mkdir(parents=True, exist_ok=True)
132
+ out.write_text(self.to_json(), encoding="utf-8")
133
+ return out
134
+
135
+ def to_json(self) -> str:
136
+ return json.dumps(asdict(self), sort_keys=True, default=str)
137
+
138
+ def to_html(self) -> str:
139
+ rows = "\n".join(
140
+ f"<tr><td>{c['concurrency']}</td><td>{c['throughput_rps']:.1f}</td>"
141
+ f"<td>{c['latency_p50_ms']:.1f}</td><td>{c['latency_p99_ms']:.1f}</td></tr>"
142
+ for c in self.per_concurrency
143
+ )
144
+ return (
145
+ "<html><body><h1>datacenterbench report</h1>"
146
+ f"<p>{self.summary()}</p>"
147
+ "<table border=1><tr><th>concurrency</th><th>rps</th>"
148
+ "<th>p50 (ms)</th><th>p99 (ms)</th></tr>"
149
+ f"{rows}</table></body></html>"
150
+ )
151
+
152
+ def diff(self, other: "Result") -> dict[str, Any]:
153
+ """Diff throughput per concurrency level against ``other``."""
154
+ other_map = {c["concurrency"]: c for c in other.per_concurrency}
155
+ deltas: list[dict[str, Any]] = []
156
+ for c in self.per_concurrency:
157
+ oc = other_map.get(c["concurrency"])
158
+ if oc is None:
159
+ continue
160
+ deltas.append({
161
+ "concurrency": c["concurrency"],
162
+ "throughput_delta": c["throughput_rps"] - oc["throughput_rps"],
163
+ "latency_p99_delta_ms": c["latency_p99_ms"] - oc["latency_p99_ms"],
164
+ })
165
+ return {"deltas": deltas}
166
+
167
+
168
+ def run(workload: Workload, config: Config) -> Result:
169
+ """Execute a benchmark and return a :class:`Result`.
170
+
171
+ For ``endpoint == 'local'`` (driver mode) the workload is simulated using
172
+ a deterministic RNG seeded from ``config.seed`` so results are
173
+ reproducible. For a remote endpoint the same shape is produced from the
174
+ transport callable injected via ``Workload.params['transport']``.
175
+ """
176
+ if not isinstance(workload, Workload):
177
+ raise WorkloadError("workload must be a Workload instance")
178
+ if not isinstance(config, Config):
179
+ raise WorkloadError("config must be a Config instance")
180
+
181
+ rng = random.Random(config.seed)
182
+ result = Result(workload=workload, config=config)
183
+
184
+ transport = workload.params.get("transport")
185
+
186
+ for c in config.concurrency:
187
+ latencies_ms: list[float] = []
188
+ tokens_out = 0
189
+ n_requests = max(1, int(config.duration_s * c * 10)) # ~10 rps per worker baseline
190
+ for _ in range(n_requests):
191
+ if transport is not None:
192
+ latency, tokens = transport(workload, config, c)
193
+ else:
194
+ # deterministic simulated latency grows with concurrency (queueing)
195
+ base = 20.0 + (c * 0.5)
196
+ latency = rng.gauss(base, base * 0.1)
197
+ tokens = rng.randint(8, 64)
198
+ latencies_ms.append(max(latency, 1.0))
199
+ tokens_out += tokens
200
+
201
+ elapsed_s = max(config.duration_s, 1e-6)
202
+ result.per_concurrency.append({
203
+ "concurrency": c,
204
+ "requests": n_requests,
205
+ "throughput_rps": n_requests / elapsed_s,
206
+ "tokens_per_s": tokens_out / elapsed_s,
207
+ "latency_p50_ms": _percentile(latencies_ms, 0.5),
208
+ "latency_p95_ms": _percentile(latencies_ms, 0.95),
209
+ "latency_p99_ms": _percentile(latencies_ms, 0.99),
210
+ })
211
+ return result
datacenterbench/cli.py ADDED
@@ -0,0 +1,53 @@
1
+ """CLI entry for datacenterbench.
2
+
3
+ The README documents no CLI surface; this command runs a single simulated
4
+ workload so infra teams can smoke-test the harness without an endpoint.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import sys
12
+
13
+ from . import Config, Result, Workload, __version__, run as run_benchmark
14
+
15
+
16
+ def _build_parser() -> argparse.ArgumentParser:
17
+ parser = argparse.ArgumentParser(prog="datacenterbench", description="Inference benchmark harness.")
18
+ parser.add_argument("--version", action="version", version=f"datacenterbench {__version__}")
19
+ sub = parser.add_subparsers(dest="command", required=True)
20
+ run_p = sub.add_parser("run", help="run a single benchmark and print the summary")
21
+ run_p.add_argument("--kind", default="chat", choices=("chat", "embeddings", "vision", "batch"))
22
+ run_p.add_argument("--model", required=True)
23
+ run_p.add_argument("--endpoint", default="local")
24
+ run_p.add_argument("--concurrency", default="1,8,32", help="comma-separated list")
25
+ run_p.add_argument("--duration", type=float, default=2.0)
26
+ run_p.add_argument("--seed", type=int, default=0)
27
+ run_p.add_argument("--json", action="store_true", help="emit the full report as JSON")
28
+ return parser
29
+
30
+
31
+ def main(argv: list[str] | None = None) -> int:
32
+ """Entry point for the ``datacenterbench`` console script."""
33
+ args = _build_parser().parse_args(argv)
34
+ if args.command == "run":
35
+ concurrency = [int(x) for x in args.concurrency.split(",")]
36
+ config = Config(
37
+ concurrency=concurrency,
38
+ endpoint=args.endpoint,
39
+ duration_s=args.duration,
40
+ seed=args.seed,
41
+ )
42
+ workload = Workload(kind=args.kind, model=args.model)
43
+ result = run_benchmark(workload, config)
44
+ if args.json:
45
+ print(result.to_json())
46
+ else:
47
+ print(result.summary())
48
+ return 0
49
+ return 1
50
+
51
+
52
+ if __name__ == "__main__":
53
+ sys.exit(main())
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.4
2
+ Name: datacenterbench
3
+ Version: 0.1.0
4
+ Summary: Benchmark throughput, latency, and energy efficiency of inference workloads on datacenter-class hardware; reproducible reports.
5
+ Author:
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+
10
+ # datacenterbench
11
+
12
+ `datacenterbench` benchmarks the throughput, latency, and energy efficiency of inference workloads running on datacenter-class hardware (GPUs, accelerators). It runs standardised model serving workloads against an endpoint or a local runtime, collects per-request latency and token throughput, and produces a reproducible report you can compare across hardware.
13
+
14
+ It is designed for hardware and infra teams who need a consistent, versioned benchmark when evaluating GPUs, schedulers, or serving stacks.
15
+
16
+ ## Features
17
+
18
+ - Workloads: text generation (chat), embeddings, vision (CLIP), and batch inference.
19
+ - Concurrency sweeps, warm-up control, and per-request tail latency (p50/p95/p99).
20
+ - Energy and GPU metrics collection via `nvidia-smi` and DCGM (optional).
21
+ - Reproducible configs: pin model, prompt set, batching, and seed in one JSON.
22
+ - HTML + JSON report output; diffs against prior runs.
23
+ - Driver mode (local runtime) and client mode (remote endpoint).
24
+ - Optional extras for Opensearch and Prometheus export of results.
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ pip install datacenterbench
30
+ ```
31
+
32
+ ## Quick start
33
+
34
+ ```python
35
+ from datacenterbench import run, Workload, Config
36
+
37
+ result = run(
38
+ Workload(kind="chat", model="meta-llama/Meta-Llama-3-8B-Instruct"),
39
+ Config(concurrency=[1, 8, 32], prompt_set="ultrachat-1k", endpoint="http://gpu-node:8000"),
40
+ )
41
+ print(result.summary())
42
+ result.write("runs/2026-11-29-llama3-8b")
43
+ ```
44
+
45
+ ## API
46
+
47
+ - `datacenterbench.run(workload, config)` — execute a benchmark and return a `Result`.
48
+ - `datacenterbench.Workload(kind, model, **params)` — define what to run.
49
+ - `datacenterbench.Config(concurrency, prompt_set, endpoint, duration_s)` — define how to run.
50
+ - `Result.summary()` / `Result.write(path)` / `Result.diff(other)` — report helpers.
51
+
52
+ ## Configuration
53
+
54
+ Set `DATACENTERBENCH_OUTPUT_DIR` for default run storage, and `DCB_PROMPT_DIR` to point at a custom prompt set. For GPU metrics, set `DCB_DCGM=enabled`.
55
+
56
+ ## License
57
+
58
+ MIT
@@ -0,0 +1,7 @@
1
+ datacenterbench/__init__.py,sha256=hMnwysOjrOmoB8Bh4EIVKtDdlQhGbO5-MgqqgDxWxm8,7274
2
+ datacenterbench/cli.py,sha256=QRl_eiCMqoRYftQshkH_F7BhG7pm4IBB2_keaNnpo3k,1984
3
+ datacenterbench-0.1.0.dist-info/METADATA,sha256=P7ZxPoIJQaER2Ov9mqC1RvLe9Ye_uBw8-MyxTzZD0D8,2263
4
+ datacenterbench-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ datacenterbench-0.1.0.dist-info/entry_points.txt,sha256=uxghDioUrL85RkCeMqt8nQ5OIUjxUxcd6n93QmO06Us,61
6
+ datacenterbench-0.1.0.dist-info/top_level.txt,sha256=19_GP1YfKbivxoR7LSQFqy1dzlYdTCIs4Npe3J_KLRw,16
7
+ datacenterbench-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ datacenterbench = datacenterbench.cli:main
@@ -0,0 +1 @@
1
+ datacenterbench