|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | import functools |
| 4 | +import math |
4 | 5 | import statistics |
5 | 6 | from typing import Callable |
6 | 7 |
|
|
9 | 10 | from .progress_bar import iter_with_progress |
10 | 11 |
|
11 | 12 |
|
| 13 | +def compute_repeat( |
| 14 | + fn: Callable[[], object], |
| 15 | + *, |
| 16 | + target_ms: float = 100.0, |
| 17 | + min_repeat: int = 10, |
| 18 | + max_repeat: int = 1000, |
| 19 | + estimate_runs: int = 5, |
| 20 | +) -> int: |
| 21 | + """ |
| 22 | + Estimate how many repetitions are needed to collect a stable benchmark for a |
| 23 | + single function call, mirroring Triton's ``do_bench`` heuristic while |
| 24 | + clamping the result between ``min_repeat`` and ``max_repeat``. |
| 25 | + """ |
| 26 | + di = runtime.driver.active.get_device_interface() # type: ignore[attr-defined] |
| 27 | + cache = runtime.driver.active.get_empty_cache_for_benchmark() # type: ignore[attr-defined] |
| 28 | + |
| 29 | + # Warm the pipeline once before collecting timing samples. |
| 30 | + fn() |
| 31 | + di.synchronize() |
| 32 | + |
| 33 | + start_event = di.Event(enable_timing=True) |
| 34 | + end_event = di.Event(enable_timing=True) |
| 35 | + start_event.record() |
| 36 | + for _ in range(estimate_runs): |
| 37 | + runtime.driver.active.clear_cache(cache) # type: ignore[attr-defined] |
| 38 | + fn() |
| 39 | + end_event.record() |
| 40 | + di.synchronize() |
| 41 | + |
| 42 | + estimate_ms = start_event.elapsed_time(end_event) / max(estimate_runs, 1) |
| 43 | + if not math.isfinite(estimate_ms) or estimate_ms <= 0: |
| 44 | + return max_repeat |
| 45 | + |
| 46 | + repeat = int(target_ms / estimate_ms) |
| 47 | + return max(min_repeat, min(max_repeat, max(1, repeat))) |
| 48 | + |
| 49 | + |
12 | 50 | def interleaved_bench( |
13 | 51 | fns: list[Callable[[], object]], *, repeat: int, desc: str | None = None |
14 | 52 | ) -> list[float]: |
|
0 commit comments