| myst |
|
|---|
AgentKernelArena uses graph-first device timing for Python-callable GPU kernels,
regardless of whether the kernel is implemented in Triton, HIP, FlyDSL, or
PyTorch. The canonical implementation is
src/tools/perf/aka_benchmark.py. PyTorch exposes CUDA and ROCm through the
same torch.cuda namespace, so benchmark_method: cuda_graph means CUDA Graph
on a CUDA build and HIP Graph on a ROCm build.
Kernel tasks (see the task contract) use one
timing method in every language. Each call to run() is captured into a CUDA
graph and timed per replay after a 1 GiB cache flush
(benchmark_cuda_graph_cold_cache_samples: 10 warmups, 100 samples, median).
The two framework input draws alternate between samples, and every timed
sample's outputs are checked. There is no Event fallback for these tasks: a
baseline that cannot be captured on the current stream fails the QA audit
(QA-TIMING-METHOD), and each performance case must take the baseline at least
10 us (QA-TIMING-FLOOR). The final evaluation remeasures the baseline
interleaved with the candidate, and the task's speedup is the geometric mean of
the per-case speedups (baseline time over candidate time). The remaining
sections of this page describe the shared helper and the older fallback and
cold-weight policies, which apply to the end-to-end and legacy helper paths.
The canonical implementation is src/tools/perf/aka_benchmark.py, which the
schema-v3 evaluator uses for kernel tasks. Its ReadOnlyCacheFlush uses a reusable initialized 1 GiB read sweep, after input
preparation and before the start Event of every single-operator graph replay.
The resulting cuda_graph_cold_cache metric is an Event graph span with eviction
excluded. It is distinct from the legacy warm cuda_graph method below, profiler
kernel-duration sums and cuda_graph_cold_weights rotation. Explicit migrations
need fresh paired measurements and GPU qualification; this addition does not
change historical task policies or scores.
Cold-cache performance case rows must put the returned timing metadata under
metadata, with benchmark_method and execution_time_ms on the case row.
The protocol checks the cache policy, metric, one invocation per replay and
eviction byte count; comparison rejects differing or missing cache identities.
The reference's paired utility preserves raw samples and reports a geometric
mean speedup with a paired-round 95% percentile-bootstrap interval. It is a
diagnostic comparison, not a replacement for task correctness or Arena scoring.
The common mean-time interface is:
mean_ms, metadata = benchmark_cuda_graph_or_events(
fn,
prepare_fn=None,
warmup=10,
repetition=100,
target_ms=1.0,
estimate_reps=5,
max_graph_repeats=1000,
)mean_ms is device milliseconds per invocation of fn. Suites whose scoring
contract uses a median or percentile call
benchmark_cuda_graph_or_events_samples() instead. It returns the same
metadata and a list of per-invocation millisecond samples.
The callable must launch already-compiled device work. JIT compilation, module construction, and scratch/workspace sizing belong before the benchmark call. If the public operation returns newly allocated outputs, both sides must retain that same contract; otherwise both sides use caller-owned output buffers.
Stateful in-place kernels may provide prepare_fn. It runs on the active
benchmark stream before each warmup and measured sample, but before the start
event, so input restoration is ordered correctly and excluded from the kernel
time. In this mode each graph replay contains one logical fn call; this
prevents a later captured call from consuming state mutated by an earlier one.
Output resets follow the same rule: they belong in prepare_fn, not in the
captured/timed callable.
For each fixed test case, the helper:
- Refuses to score when
torch.cuda.is_available()is false. CPU wall-clock time is never substituted for kernel device time. - Runs the requested warmup calls and synchronizes them.
- Captures and primes a small estimate graph, then measures one replay with GPU events.
- Rejects PyTorch's explicit empty-graph warning and independently rejects an effectively empty replay rather than reporting a fabricated near-zero time.
- Selects a bounded number of calls per graph so one replay targets roughly
target_ms. This amortizes host launch overhead for short kernels. - Captures and primes the final graph outside the reported sample set, replays
it
repetitiontimes, and divides each replay's event time by the calls captured in that graph. - For tasks that request a timed-run handle, exposes the exact captured output buffers and an additional replay of the same graph executable. Correctness checks poison or perturb those buffers, replay, and compare them with the eager/reference result. Automatic graph-to-Event fallback with a collector fails closed. Explicit Event observation is described below.
The start event, graph replay, and end event all run on the same side stream. This ordering is important: recording events on one stream while replaying on another can appear to time an empty stream.
Successful samples record at least:
benchmark_method: cuda_graph
benchmark_samples: 100
benchmark_effective_repeats: 80
benchmark_target_ms: 1.0
benchmark_max_repeats: 1000
benchmark_warmup: 10Some callables cannot be captured, for example because they synchronize the device, read a device scalar on the host, allocate capture-unsafe memory, or launch work on an incompatible stream. Capture failure, empty capture, and invalid replay timing fall back explicitly to eager GPU-event measurement:
benchmark_method: cuda_event_fallback
benchmark_fallback_reason: "cuda_graph_failed: RuntimeError: ..."
benchmark_effective_repeats: 1Tasks may select Event timing for a known graph-capture incompatibility, or
when the declared measured unit requires a fresh invocation of the public
Python callable on every sample (for example, a wrapper that allocates and
returns a new output). Pass use_cuda_graph=False with a stable
fallback_reason, document why graph replay is not equivalent, and apply the
same method and callable to baseline and candidate. A result is never silently
changed to Event timing merely because graph timing is slower.
Graph after_sample receives the captured output after each reported replay.
When one graph contains multiple calls, capture retains only the last returned
output; graph replay also does not rerun Python dispatch or allocation. A
single-call graph can make every replay's captured output observable, but it
still measures graph replay rather than a fresh public call. Choose the method
from the task contract, not from the apparent speedup. Disclose a method change
and compare its before/after device times only under matched hardware, image,
runtime, inputs and sampling settings. Device Events report GPU elapsed time;
they do not turn host allocation or dispatch into CPU wall-clock timing.
Before accepting fallback, task harnesses should hoist host-side shape work,
pointer-table creation, temporary allocation, and JIT setup out of fn, then
directly launch the underlying kernel where that is part of the task's stable
API. Do not remove a public wrapper's required allocation or dispatch merely
to make its declared measured unit graph-capturable. A legacy HIP extension
that hard-codes stream 0 is a legitimate example of an incompatible launch:
CUDA/HIP Graph capture begins on a non-default side
stream, while capturable PyTorch allocation/fill nodes can otherwise make a
graph look non-empty even when the target kernel escaped to stream zero. HIP
task harnesses therefore run a conservative source preflight. Every visible
launch must use a stream obtained from PyTorch's current CUDA/HIP stream; a
literal legacy stream, capture-unsafe synchronization/allocation, or an
unverifiable launch construct classifies the baseline case as Event-only. For
comparisons against a HIP reference, the reference source fixes this policy; candidate source
cannot downgrade a graph-capable reference to Events.
Fallback still uses device events; it does not use Python, subprocess, or CPU wall-clock timing. Host and wall-time-only fields are rejected by the central performance parser.
For an explicit Event path, timed_run=TimedRun() exposes the return value from
the last measured sample, after its ending GPU Event completes. It does not
run a new untimed invocation to obtain that value. Its rerun() invokes the
same eager callable on the measured stream, with prepare_fn before the call.
This can allocate a new output and execute different Python dispatch decisions;
it is not captured graph replay. The task must validate the measured output
first and then validate the returned re-invocation output. Output observation
alone is not a correctness verdict.
Collector metadata records benchmark_timed_run_kind: eager_callable for
explicit Events and captured_graph for graph replay. The existing
benchmark_method: cuda_event_fallback and fallback reason are unchanged.
Automatic fallback from a failed/empty/invalid graph still rejects a requested
collector; it does not silently switch the validation contract. Event timing
must be selected explicitly when that is the task's declared methodology.
benchmark_cuda_graph_cold_weights_samples() is an opt-in method for operators whose cost in a decode step comes from reading a weight from HBM. Under the default timing every sample reads the same weight, so after the first sample the weight sits in the L2 and the MALL. When prepare_fn restores or rotates inputs, each replay also holds a single call, so a decode-size operator that runs for a few microseconds is charged the whole fixed cost of a graph replay.
The task passes one zero-argument callable per weight copy. cold_weight_copy_count(weight_bytes) gives enough copies to pass 1 GiB in total, and at least 8:
from _aka_benchmark import (
TimedRun, benchmark_cuda_graph_cold_weights_samples, cold_weight_copy_count,
)
copies = cold_weight_copy_count(weight_bytes, rotate_bytes=1 << 30, min_copies=8)
calls = [make_call(weights[i]) for i in range(copies)]
samples, metadata = benchmark_cuda_graph_cold_weights_samples(
calls, warmup=20, repetition=100, prepare_fn=rotation, timed_run=TimedRun())One CUDA graph calls every callable once, in order. Each sample is the replay time divided by the number of calls, so every call reads its weight from HBM and the fixed replay cost is shared by all calls. TimedRun.outputs is the list of per-call outputs, after_sample receives that list, and rerun_ms() returns the per-call time of one more replay. The metadata reports benchmark_method: cuda_graph_cold_weights, benchmark_calls_per_replay and benchmark_cold_weight_copies. The method has no event fallback, and AKA_BENCHMARK_FORCE_EVENT=1 makes it raise.
Every call needs its own weight copy and its own input buffer. Each weight copy is a separate draw from the task's initializer and stays fixed. prepare_fn runs once before the start event of each replay and draws a fresh, independent input into every call's buffer. With identical copies an implementation could read one copy for every call, so the weight stays in the caches. With identical copies and one shared input it could also compute one result and copy it to the other outputs. Both shortcuts pass the output checks.
A task that uses this method keeps the integrity checks of its default timing. It checks the output of every call against a reference for that call's input and weight copy, in the timed replays and in replays with fresh unseen inputs for every call. It also holds the reported time to the cost of the unseen inputs and checks that no weight copy changed.
Task sources do not import AgentKernelArena's src package and do not carry
copies of the canonical helper. For a schema-v3 kernel task,
src/task_contract.py::render_workspace writes the evaluator and the timing
helper into the run workspace as _aka_eval/_aka_benchmark.py, beside the
resolved contract; solution/ is the only editable tree. The end-to-end serving
tasks receive their serving client helpers from
src/perf_helper_materialization.py. The materialized workspace is
self-contained: the Python timing helper depends only on the standard library and
PyTorch.
Generated helpers and protected evaluation inputs are covered by the harness
integrity guard. A kernel task's candidate is the solution/ tree; every other
file, including _aka_eval/, the contract, baseline and reference, is protected.
See the task guide for the exact rules.
Normal optimization runs and quality_loop also snapshot the original task
package's non-editable inputs before launching the optimizer. This includes
case data such as session_cases.json, reference implementations, and helper
files outside test directories. The snapshot is kept in framework memory and
checked before evaluation and again before writing the final result. Editing,
deleting, or renaming an original input rejects the run for every agent.
The candidate boundary (solution/ for kernel tasks) identifies the implementation. Runtime outputs under build/, logs/, and
perf/, environment caches, and generated result reports are not task inputs.
New preparation files are allowed unless they match protected harness patterns,
in which case the existing scratch-file removal policy applies. Cloned or
image-seeded dependency trees retain the existing harness-pattern protection;
this input snapshot is not a blanket source allowlist for those repositories.
The evaluator matches baseline and optimized cases by unique explicit ID first,
then by unique parameters or shape. An ID establishes a pair but does not prove
equal work: each pair must also have identical reported shape, params, and
dtype fields. Changing or removing any of those fields prevents performance
scoring, including for singleton/index-matched cases. Fields absent on both
sides remain supported for legacy producers, with task inputs protected by the
snapshot above. Nested metadata.params and metadata.dtype are normalized
and these fields survive performance YAML round trips. Other diagnostic fields
and adaptive timing repeat counts are not workload identity.
Workload mismatches retain measured timings, produce zero speedup, suppress
comparison plots, and are recorded in workload_consistent and
workload_mismatches in task_result.yaml.
Benchmark methods are then compared per matched case:
- graph versus graph is comparable;
- event fallback versus event fallback is comparable;
- graph versus event fallback is retained as timing data but produces no speedup;
- cold-weight graph (
cuda_graph_cold_weights) is comparable only with cold-weight graph; - cold-cache graph (
cuda_graph_cold_cache) is comparable only with the same cold-cache method, metric, eviction policy and eviction byte count; - different shapes may use different methods, provided each matched baseline/optimized pair uses the same exact method.
The baseline result fixes the timing policy before candidate measurement. If a baseline case succeeds with Graph but the candidate falls back to Events, the candidate timing remains visible for diagnosis but earns no performance score. Only a case that the baseline itself classified as Event-only can be scored as Event versus Event. The evaluator never collects or selects a candidate-driven alternate Event baseline.
Missing or unknown method metadata is not comparable and produces no speedup;
every scored case must explicitly identify cuda_graph,
cuda_event_fallback, cuda_graph_cold_weights or cuda_graph_cold_cache.
An aggregate mixed:... method string is never scored, even when the baseline
and optimized strings are identical. It records only a set of methods and loses
the shape-to-method mapping, so equality cannot prove that the same shapes used
the same timer. The timing is retained with an
ambiguous_mixed_aggregate mismatch reason.
This means a task can legitimately use graph timing for one shape and event
fallback for another. The evaluator records method sets, per-case mismatch
details, and benchmark_method_consistent in task_result.yaml. All
benchmark_* metadata survives the baseline/optimized YAML round trip.
Tasks that declare evaluation.measurement.kind: serving do not time a kernel.
Their unit of work is a fixed request set completed by a pinned benchmark
client against a freshly started model server; the reported
benchmark_method is serving_wall_clock, execution_time_ms is the client's
wall duration, and metrics.output_tokens_per_s is the scored quantity. The
protocol rejects a case whose completed requests, output tokens or input tokens
differ from the manifest, or whose throughput does not equal tokens divided by
duration. Graph-replay checks do not apply to this timer.
Final evaluation alternates baseline and candidate for at least three fresh
pairs, each in its own clean container from the trusted task template. The
per-case ratio is the median of the paired throughput ratios; several cases
combine by geometric mean. serving_measurement.uncertainty keeps the ratio
range and each side's repeat variation so a small median is not read as a
gain. Before each performance action the container verifies the device is idle,
and before final evaluation the worker container is swept of agent leftovers;
both records are part of the result. Kernel tasks keep the device-timing rules
above; mixed runs report the two groups separately with no combined average.
See the e2e guide for the task-side contract.
Run:
make check-perf-helperssrc/tools/sync_perf_helpers.py audits committed task sources; it is not a GPU
qualification. Schema-v3 kernel tasks (task.yaml) carry no benchmark code and
are only counted. Every remaining schema-v2 task (config.yaml) must be a
serving recipe (the exact bootstrap stub plus a hash-pinned workload) or a
serving client whose scripts/evaluate.py imports _aka_serving; anything else
fails the check instead of quietly using an undocumented timer. The check also
fails when a generated helper copy (_aka_benchmark.py, _aka_serving*.py,
_aka_eval/) is committed under tasks/.
Pull requests also run the CPU/mock unit suite and Python compilation audit in CI.
On 2026-09-15, Slurm job 139392 ran the three
tests/test_gpu_graph_smoke.py checks on an MI355X (gfx950) with the pinned
SGLang 0.5.19 qualification image on node crsuse2-m2m-001: all three
passed, none skipped. Before qualification, the allocated device had 99.8% of
its memory free and AMD-SMI reported no running processes. The previous
helper rejected an explicit Event collector on the same GPU; the updated helper
observed the actual measured output and validated eager re-invocation. See the
runtime qualification record for image identities.
The HGEMM task also exercised all five original cases with the existing pinned
SGLang 0.5.14 runtime (FlyDSL 0.2.2). Original and updated harnesses both passed
baseline compile, correctness and performance actions using the same canonical
helper. Each retained 100 Event samples, one call per sample and the original
capture-unsafe reference reason. Updated results additionally recorded
eager_callable, timed_output_correctness: PASS and replay_correctness: PASS
for all five cases. These sequential runs verify timing boundaries and output
checks; they do not establish a performance improvement. Action-level evidence
is distinct from a full validator report (the predecessor of the QA auditor's qa_report.yaml). That separate HGEMM report
was subsequently framework-finalized as PASS in the same job, with an
implemented frozen initial candidate and no baseline diagnostic exemption.
Earlier job 139346 on node crsuse2-m2m-217 also produced successful functional
reports, but a subsequent audit found external process/memory occupancy and
other tasks failed with allocation/launch resource errors. Preserve those
reports as historical functional evidence; all performance from that node is
unqualified. Job 139392 explicitly excluded node217 and repeated the smoke,
HGEMM boundary checks and the full task validator run (the predecessor of the QA audit) on the available-memory allocation
described above. Neither sequential run establishes an optimization gain.