NOTES — flashinfer-decode-attention-optimization
Construction notes, calibration debts and validation boundary. Not shipped to the agent.
1. Design intent
This task sits one layer below inference-system-optimization (the family reference task, which
optimizes a whole serving stack). Here the agent optimizes one kernel: paged batch-decode
attention. The structural pattern is copied from granite-mamba2-inference-optimization:
fixed API + frozen naive reference + paired geometric-mean speedup against a production baseline.
The thing that makes this task hard, and the reason it was chosen, is the baseline. It is not a
strawman PyTorch loop — it is FlashInfer's own production kernel, invoked exactly the way
FlashInfer's own microbenchmark invokes it:
# tests/baseline_decode.py, mirroring benchmarks/bench_batch_decode.py:55-57
flashinfer.BatchDecodeWithPagedKVCacheWrapper(
workspace_buffer, "NHD", use_tensor_cores=True, backend="auto"
)
So the score scale is calibrated to reality: 1.0 = matched FlashInfer, >1.0 = beat FlashInfer.
use_tensor_cores=True was a deliberate and load-bearing choice. The default is False
(flashinfer/decode.py:911-914: self._use_tensor_cores = use_tensor_cores or backend in ("trtllm-gen","cute-dsl")),
and a use_tensor_cores=False baseline would have been a weaker configuration than the one
FlashInfer itself benchmarks — 1.0 would then have meant "matched a suboptimal FlashInfer call", which
is a dishonest scale. Setting it to True costs us some easy oracle headroom and buys an honest bar.
Why the task is not already saturated
At the pinned SHA the actively developed area is Blackwell. git log at
553c2280a88581c7ede39aa571a54d1232854b81 has HEAD at
feat: optimize gated SM12x dynamic NVFP4 MoE (#4329) — SM100/SM12x MoE and GEMM paths are where the
recent work went, and gpu_types = ["B200"] puts the agent on exactly that hardware. The decode
attention path has not been squeezed as hard on SM100 as prefill/GEMM/MoE have. Concretely, the
headroom the oracle demonstrates (per-shape template selection) is trivially available, and the
headroom above the oracle (split-KV tuning, launch-path elimination at batch 1, work balancing for
ragged batches, TMA/DSMEM on SM100) is real.
2. Validation boundary — READ THIS FIRST
Per SPEC.md §11, this delivery is static validation plus CPU-only numerical validation. This box
has H20-3e (Hopper) GPUs, not B200; the base python3 is 3.6 with no torch; the Docker image was
not built.
No GPU benchmark was run. No timing number in this task tree was measured. Every performance-related
constant is a TODO(calibrate) placeholder (§12).
What was genuinely executed (output in §11):
bash -n on all four .sh files
python3.11 -m py_compile on all eleven .py files
tomllib parse of task.toml, yaml.safe_load of job.yaml / oracle.yaml
- the mandatory
compute_reward.py --fail "smoke" smoke test → valid reward.json + reward.txt, exit 0
- four end-to-end
tests/test.sh runs against a simulated /app (clean, tampered frozen file,
missing submission, verifier-internal reference) — all four produced a correct reward.json and exit 0
- leak self-checks (
instruction.md, the shipped /app tree, the oracle submission)
- three-way frozen-hash verification (§11.3)
- a real numerical validation of
reference_decode.py on CPU: torch 2.10.0+cpu was installed into
a scratch dir, and the frozen reference was checked against an independently written dense
gather-and-softmax implementation across all five visible configs, plus out= honouring, the
2-tuple KV form, padding-slot insensitivity, valid-token sensitivity and determinism. All passed.
This is a CPU correctness check of the oracle, not a benchmark.
3. File map
| path |
role |
frozen |
instruction.md |
agent-facing brief |
— |
task.toml |
Harbor task config |
— |
job.yaml / oracle.yaml |
6-agent run / oracle run |
— |
environment/Dockerfile |
image: CUDA 12.8.1 + py3.11.13 + torch 2.10.0cu128 + FlashInfer @ pinned SHA + AOT pre-warm |
— |
environment/.dockerignore |
keeps __pycache__/*.pyc/scratch out of the image |
— |
environment/workspace/ → /app/ |
agent-visible tree |
— |
environment/workspace/reference_decode.py |
naive fp32 correctness oracle and the API contract |
yes |
environment/workspace/task_fixtures.py |
config schema, tolerances, page-table builder, visible configs |
yes |
environment/workspace/submission/candidate_decode.py |
the stub the agent edits |
no |
environment/workspace/verify_decode.py |
public correctness self-check |
no |
environment/workspace/run_dev_bench.py |
public speed check vs the same FlashInfer wrapper |
no |
environment/workspace/optimize.py |
verify + bench driver |
no |
environment/workspace/entrypoint.sh |
clean-FlashInfer snapshot + timer bootstrap |
no |
environment/workspace/timer.sh |
verbatim copy from the reference task |
— |
environment/workspace/pyproject.toml |
uv project marker |
no |
tests/test.sh |
prechecks, anti-cheat, dependency restore, cache clearing, then score |
— |
tests/compute_reward.py |
the scorer (hidden config matrix lives here) |
— |
tests/worker.py |
per-implementation subprocess (crash isolation) |
— |
tests/baseline_decode.py |
the SPEED baseline (FlashInfer production wrapper) |
yes |
tests/{reference_decode,task_fixtures,baseline_decode}_hash.txt |
SHA-256 freezes |
— |
solution/{solve.sh,solve.py,oracle_candidate_decode.py} |
the modest oracle |
— |
timer.sh is byte-identical to the reference task's:
sha256 284b14ae3c668df7ee0b83fe3e5c8500618a0c223a2fbba5aa2580d9102cf1c1.
4. The fixed API, and the real FlashInfer API it mirrors
/app/submission/candidate_decode.py must expose class CandidateDecode with
__init__(workspace_buffer, kv_layout="NHD") / plan(...) / run(q, paged_kv_cache, *, out=None).
Every element is grounded in the real wrapper at the pinned SHA:
| our API element |
FlashInfer source |
note |
| class role |
flashinfer/decode.py:710 class BatchDecodeWithPagedKVCacheWrapper |
exported at flashinfer/__init__.py:53 |
__init__(workspace_buffer, kv_layout="NHD") |
decode.py:777-787 |
we drop the CUDA-graph / use_tensor_cores / backend kwargs from the contract (the agent may use them internally) |
plan(indptr, indices, last_page_len, num_qo_heads, num_kv_heads, head_dim, page_size, ...) |
decode.py:1239-1250 |
positional order identical |
sm_scale=None, pos_encoding_mode="NONE", window_left=-1, logits_soft_cap=None, q_data_type, kv_data_type |
decode.py:1376-1403 (_plan_impl defaults) |
sm_scale defaults to 1/sqrt(head_dim) |
run(q, paged_kv_cache, *, out=None) |
decode.py:1810-1831 |
|
begin_forward = plan, forward = run |
decode.py:1738, decode.py:1740 |
deprecated aliases, mirrored so a drop-in wrapper works |
reset_workspace_buffer |
decode.py:827-836 |
|
| 5-D single-tensor / 2-tuple paged KV |
flashinfer/utils.py:186 unpack_paged_kv_cache |
reference_decode.unpack_paged_kv_cache re-implements it with .unbind(dim=1) |
| workspace buffer 128 MiB uint8 |
benchmarks/bench_batch_decode.py:52-54 |
same size the FlashInfer benchmark uses |
Deviations from the real API, all deliberate: o_data_type is a required keyword (FlashInfer infers it;
we pass it explicitly so the correctness gate can assert the output dtype), and the exercised surface is
restricted to pos_encoding_mode="NONE", window_left=-1, no soft cap — anything else raises
NotImplementedError in the reference, because a naive fp32 reference for RoPE-fused or
soft-capped decode is a second correctness liability with no pedagogical payoff.
5. Config matrix
SPEC.md §4.3 requires opposing regimes on every axis. Visible configs live in
task_fixtures.PUBLIC_CORRECTNESS_CONFIGS; hidden configs live in
compute_reward.HIDDEN_BENCHMARK_CONFIGS. Name sets are disjoint and no hidden config duplicates a
visible one on all axes (verified in §11.4).
Visible (/app, 5 configs)
| name |
batch |
KV |
qo/kv heads |
head_dim |
page |
q/kv dtype |
dev_b1_short_gqa |
1 |
512 uniform |
32/4 |
128 |
16 |
fp16/fp16 |
dev_b64_long_gqa |
64 |
4096 uniform |
32/4 |
128 |
16 |
bf16/bf16 |
dev_b32_ragged_page1 |
32 |
ragged 64..8192 |
32/8 |
128 |
1 |
fp16/fp16 |
dev_b8_mha_d256 |
8 |
2048 uniform |
8/8 (MHA) |
256 |
64 |
fp16/fp16 |
dev_b16_fp8kv |
16 |
2048 uniform |
32/4 |
128 |
16 |
fp16/fp8_e4m3 |
Hidden (verifier, 7 configs)
| name |
batch |
KV |
qo/kv |
head_dim |
page |
dtypes |
KV pool |
inner_reps |
h_b1_short_gqa |
1 |
384 |
32/4 |
128 |
16 |
fp16 |
~0 GiB |
50 |
h_b1_long_gqa |
1 |
16384 |
32/4 |
128 |
16 |
bf16 |
0.03 GiB |
30 |
h_bmax_short |
224 |
96 |
32/8 |
128 |
16 |
fp16 |
0.08 GiB |
30 |
h_blarge_long |
96 |
4096 |
32/4 |
128 |
32 |
bf16 |
0.75 GiB |
15 |
h_ragged_page1 |
64 |
ragged 96..12288 |
32/8 |
128 |
1 |
fp16 |
0.57 GiB |
15 |
h_mha_d256_p64 |
32 |
2048 |
8/8 (MHA) |
256 |
64 |
fp16 |
0.51 GiB |
20 |
h_fp8kv |
96 |
4096 |
32/4 |
128 |
16 |
fp16 q/o, fp8_e4m3 kv |
0.38 GiB |
15 |
Axis coverage (measured, §11.4): batch ∈ {1, 32, 64, 96, 224}; GQA ratio ∈ {1, 4, 8}; head_dim ∈ {128, 256};
page_size ∈ {1, 16, 32, 64}; KV-length mode ∈ {uniform, ragged}; dtype pairs ∈
{(fp16,fp16), (bf16,bf16), (fp16,fp8_e4m3fn)}. Opposing-regime pairs: h_b1_short_gqa (pure launch
overhead, ~50 KiB of KV) vs h_blarge_long (0.75 GiB, pure bandwidth); h_bmax_short (224 tiny requests,
scheduling bound) vs h_b1_long_gqa (1 request, 16 K tokens, split-KV bound); h_mha_d256_p64 (MHA,
no group dimension to fill an MMA tile, huge pages) vs everything else.
Peak KV pool across the hidden matrix is 0.75 GiB, so memory_mb = 131072 is comfortable even with a
candidate that allocates aggressively; the constraint that actually binds is storage_mb for the image.
Notes on the axis choices
page_size support. Verified at the pinned SHA that the default fa2 decode path imposes no
page-size whitelist. Only cute-dsl (8/16/32/64) and xqa (16/32/64/128) restrict it. So page_size=1
is legal and is the interesting adversarial case (maximal page-table indirection). It also means a
candidate that switches to cute-dsl must handle page_size=1 by falling back.
- fp8 KV for decode is supported.
flashinfer/aot.py:231-340 generates the FA2 decode kernels over
product(fa2_head_dim, f16_dtype, f16_dtype + f8_dtype, ...), i.e. fp8 KV with fp16/bf16 Q is a
first-class generated combination, and benchmarks/bench_batch_decode.py:82-95 sweeps
kv_dtype ∈ [bfloat16, float8_e4m3fn]. Only one hidden config uses it, weighted equally with the rest.
kv_layout is "NHD" only. Both layouts are supported by the library, but exercising both would
double the correctness surface for no additional optimization insight — the interesting axes are shape
and dtype. task_fixtures.KV_LAYOUT = "NHD" is the single source of truth.
- Ragged distribution is log-uniform with the two extremes forced into the batch
(
task_fixtures.make_kv_lens), so a 64-request batch really does contain both a 96-token and a
12288-token request — a 128× spread that punishes uniform tiling. Measured on the hidden ragged config:
min 96, max 12288, mean 1914, median 939.
- Page pool is shuffled (
task_fixtures.build_page_table, PAGE_POOL_SLACK = 16) so indices is
neither contiguous nor sorted. A candidate that assumes contiguous pages fails correctness.
6. Tolerances
task_fixtures.TOLERANCES, applied as torch.testing.assert_close(rtol=..., atol=...) against the fp32
reference. tolerance_for(cfg) takes the loosest tolerance among the config's q/kv/o dtypes.
| dtype |
rtol = atol |
status |
float16 |
2e-2 |
TODO(calibrate) |
bfloat16 |
4e-2 |
TODO(calibrate) |
float8_e4m3fn |
5e-2 |
TODO(calibrate) |
Provenance and why they are not simply FlashInfer's own numbers. FlashInfer's decode tests use
rtol=1e-3, atol=1e-3 — tests/attention/test_batch_decode_kernels.py:223,228,386,391,529,716. But that
is a kernel-vs-kernel tolerance: it compares the batched paged kernel against another FlashInfer
kernel computing in the same reduced precision, so the two share nearly all of their rounding. This task
compares a reduced-precision kernel against an fp32 PyTorch reference, where the error is dominated
by the accumulation precision of the kernel and by the mantissa of the storage dtype. 1e-3 would fail
FlashInfer's own kernel on bf16, so it cannot be used directly.
The values above are scaled by mantissa precision (fp16 has 10 explicit mantissa bits, bf16 has 7, so bf16
gets ~2× the fp16 slack; fp8_e4m3 KV adds quantization error on top of that). They are placeholders and
are marked as such.
The safety property that makes a mis-set tolerance loud rather than silent: the verifier runs the
baseline against the same frozen reference at the same tolerances before it grades the candidate
(Phase 1, "baseline-vs-reference harness self-check"). If a tolerance is too tight, FlashInfer's own
kernel fails it and the run reports a harness error, not a candidate failure. If a tolerance is too
loose, it is bounded by the anti-degeneracy checks in §7, which do not depend on tolerance at all.
Observed CPU-side headroom from the §11.5 validation (reference vs an independent dense implementation, so
this bounds the reference's own error, not a kernel's): max abs diff 1.2e-4 (fp16 configs), 9.7e-4
(bf16 config).
7. Scoring
Correctness is a hard gate evaluated before any timing; failing it emits score 0.
speedup_i = baseline_ms_i / candidate_ms_i (per hidden config i)
reward = geometric_mean(speedup_i) over all 7 configs
fast_1 = |{i : speedup_i > 1.0}| / 7 (REQUIRED by SPEC §4)
geometric_mean() returns 0.0 if any value is ≤ 0, so a single dead config zeroes the score — copied
verbatim from the reference task's compute_reward.py:796. fast_1_2 (>1.2×) and fast_2 (>2×) are also
reported, plus per-config min/max/median and the full all_ms sample vector.
Measurement methodology, taken from FlashInfer's own microbenchmark
(benchmarks/bench_batch_decode.py:58-71) so the baseline is measured the way its authors measure it:
plan() is called once, outside the timed region — only run() is timed. This is both what
FlashInfer's benchmark does and what removes the plan-caching ambiguity from the task: there is no way
to "win" by caching plans, because planning is not on the clock at all.
- ≥10 warmup and ≥10 measured iterations (
WARMUP_ITERATIONS = 20, MEASURE_ITERATIONS = 25;
normalize_config rejects any config below 10/10), median of the per-round times.
- Each measured round runs
inner_reps back-to-back run() calls inside one CUDA-event pair and divides,
so a 20 µs kernel is not measured against event overhead.
torch.cuda.synchronize() around every round; CUDA-event time is the score, and host wall time is
recorded alongside as a sanity ratio (TIMING_SANITY_RATIO = 0.5 — CUDA time must not be implausibly
smaller than host time).
- L2 is thrashed with a 256 MB bf16 buffer between rounds so a small KV cache is not read out of L2.
- Q is re-randomized in place between rounds (
buf.copy_(build_query(...)), so data_ptr() never
changes) — a candidate cannot memoize on the input pointer.
- Baseline is measured twice (before and after the candidate).
VARIANCE_THRESHOLD = 0.30
(SPEC §4.4): relative drift beyond 30% raises a variance_flags entry, so thermal/clock drift is
visible in the reward JSON rather than silently inflating or deflating the score.
- All three implementations run in separate subprocesses (
tests/worker.py, JSON-lines over
stdin/stdout). A candidate that segfaults, hangs or corrupts the CUDA context kills only its own worker;
the verifier still emits a reward.
gen_len floor: not applicable, and what replaced it
The family's gen_len floor exists to stop a generative baseline from being "sped up" by generating
fewer tokens. This task is non-generative — a single decode step over a fixed KV cache, with a fixed
output shape — so there is no length to shorten and the literal rule has no referent. Substituted
anti-degeneracy checks, all enforced in worker.py / compute_reward.py:
- Fresh random Q and KV per correctness trial (
CORRECTNESS_TRIALS = 3), seeded from os.urandom,
so no output can be precomputed.
- Structural assertions on every output: shape
[batch, num_qo_heads, head_dim], dtype o_data_type,
contiguous, correct device, all-finite, not aliasing q or the KV cache.
out= honoured: same data_ptr() in, same data_ptr() out.
responds_to_new_q: a new Q written into the same buffer must change the output — kills a cached
return tensor.
deterministic: two run() calls on unchanged inputs must be bit-identical.
- KV-range probes (
kv_probe, the direct substitute for the gen_len floor): perturbing a valid
token in a late page of one request must change that request's output by at least
KV_SENSITIVITY_MIN_DELTA and must not change the others; perturbing a padding slot past
last_page_len must change nothing. Together these prove the candidate reads exactly the KV range
implied by kv_indptr / kv_last_page_len — no truncation, no over-read.
- Post-benchmark value re-check with an
os.urandom seed drawn after timing, so a candidate cannot
be correct during the gate and degenerate during measurement.
- Physical-plausibility floor:
floor_ms = kv_bytes_referenced / HBM_PEAK_BYTES_PER_SEC * 1000 / PHYSICAL_FLOOR_FACTOR
(factor 10, i.e. a 10× margin below theoretical peak). A time below the floor means bytes were not
read; it is reported as a failure, not a win.
The verifier's own reward-JSON surface
additional_data carries: geomean_speedup, fast_1, fast_1_2, fast_2, min/max/median_speedup,
per_config (baseline/candidate ms summaries with count/median/mean/trimmed_mean/stdev/cv/min/max/all_ms,
plus host-time samples and nvidia-smi SM clock), correctness (per-config per-trial max abs/rel/mean
diff, always recorded even on pass), variance_flags, diagnostics, and constants (every threshold, so a
score can be reinterpreted after the fact without re-running).
8. JIT pre-warm — the operational trap, and how it is handled
FlashInfer JIT-compiles kernels on first use. In the family's reference task this is what forced an 1800 s
startup timeout. Here it would be worse: the verifier touches 7 shapes × 3 implementations, and a cold JIT
compile inside the timed phase would both blow the verifier budget and corrupt the first measured round.
Solution: compile ahead of time at image build, into the exact directory the JIT loader checks first.
The mechanism, verified by reading the pinned SHA:
flashinfer/aot.py has a CLI (python -m flashinfer.aot, main() at aot.py:1100-1215) with flags
--out-dir --build-dir --fa2-head-dim --f16-dtype --f8-dtype --use-sliding-window --use-logits-soft-cap --add-comm --add-gemma --add-oai-oss --add-moe --add-act --add-misc --add-xqa.
copy_built_kernels() (aot.py:856-867) writes each module as out_dir/<name>/<name>.so.
JitSpec.aot_path is jit_env.FLASHINFER_AOT_DIR / self.name / f"{self.name}.so" (jit/core.py:363-364),
is_aot at :367-368, and build_and_load prefers the AOT path at :401-403.
_get_aot_dir() (jit/env.py) returns the flashinfer_jit_cache package dir if that package is
installed, else <package_root>/data/aot.
So the Dockerfile runs python -m flashinfer.aot --out-dir ${FLASHINFER_SRC}/flashinfer/data/aot with the
generation space narrowed to exactly this task's surface — --fa2-head-dim 128,128 256,256,
--f16-dtype float16 bfloat16, --f8-dtype float8_e4m3fn, sliding window off, soft cap off, and every
--add-* extra off. FLASHINFER_CUDA_ARCH_LIST=10.0a is set because compile_and_package_modules()
requires it (aot.py:895-896). This compiles with nvcc and needs no GPU, which is why it can run in
the build.
Design decisions taken deliberately here:
- Source AOT, not the
flashinfer-jit-cache wheel. Installing that wheel would make _get_aot_dir()
prefer the package and silently ignore flashinfer/data/aot — the two approaches conflict, so only one
can be used. Source AOT wins because it is version-consistent with the pinned SHA by construction and
needs no wheel index at build time.
python -m flashinfer download-cubin is also run (flashinfer/__main__.py:430-560) to populate
FLASHINFER_CUBIN_DIR=/opt/flashinfer-cubins for the cubin-shipped backends, guarded with || true —
it needs network at build time, which the build has and the run does not.
FLASHINFER_WORKSPACE_BASE=/app/.flashinfer so the derived JIT cache root is inside /app and
writable. Note for future maintainers: there is no FLASHINFER_CACHE_DIR env var.
FLASHINFER_CACHE_DIR is a derived constant, FLASHINFER_BASE_DIR/".cache"/"flashinfer"
(jit/env.py:62); the only env knobs are FLASHINFER_WORKSPACE_BASE (env.py:59) and
FLASHINFER_CUBIN_DIR (env.py:74). tests/test.sh clears
${FLASHINFER_WORKSPACE_BASE:-$HOME}/.cache/flashinfer accordingly — and specifically not the cubin
dir (network-fetched, unreproducible at verify time) and not flashinfer/data/aot.
- The build writes a SHA-256 manifest of the AOT tree to
/opt/flashinfer-aot-manifest.sha256;
test.sh verifies rather than restores it (the tree is large), and a mismatch fails the run. The
agent is told in instruction.md not to touch it and that destroying it will not help.
FLASHINFER_DISABLE_VERSION_CHECK=1 because the editable install's version string and the AOT
metadata can disagree in a source checkout.
- The verifier also warms up before timing:
worker.py's prepare command builds the fixture, plans,
and makes JIT_WARM_CALLS = 3 warm run() calls, reporting first_call_seconds in the diagnostics so a
surprise compile is visible in the reward JSON. JIT_WARM_TIMEOUT_S = 1200 covers a cold compile for a
shape outside the AOT set (e.g. an agent that switched backend).
build_timeout_sec = 14400 (4 h) and environment_build_timeout_multiplier: 6.0 in job.yaml.
The AOT layer is the long pole; this is a TODO(calibrate).
9. Anti-cheat (SPEC §5)
§5.1 frozen files. reference_decode.py, task_fixtures.py (the fixture module) and
baseline_decode.py are SHA-256 frozen via tests/*_hash.txt, checked in test.sh before anything else.
Verified three ways in §11.3.
§5.2 source scan. test.sh walks every .py/.sh/.json/.txt/.toml/.yaml/.yml/.cfg under /app
(pruning dotdirs, assets/, results/, .venv/) with a find -print0 | while read -r -d '' loop and
fails on SUSPICIOUS_PATTERNS. Note it deliberately does not include a bare /tests/:
instruction.md tells the agent to run
pytest /opt/flashinfer/tests/attention/test_batch_decode_kernels.py, so that substring legitimately
appears in agent code and a bare /tests/ would false-positive. The pattern list is
/app/tests|compute_reward|baseline_decode|*_hash|flashinfer-aot-manifest|/logs/verifier|reward.json|reward.txt|.oracle_solution|HARBOR_ORACLE_MODE|HIDDEN_BENCHMARK_CONFIGS|FI_DECODE_CONFIG_OVERRIDE.
Tested positive and negative (§11.2, cases D and E).
§5.3 clean-dependency snapshot. entrypoint.sh tars the pristine flashinfer csrc include trees out
of /opt/flashinfer into /app/.flashinfer-baseline.tar before the agent gets the shell, recording the
source path in /app/.flashinfer-src-path. test.sh untars it back before scoring, so the baseline runs
on unmodified FlashInfer even if the agent patched the library — patching helps the candidate and cannot
weaken the bar. It then clears, in order: __pycache__ and *.pyc under the FlashInfer tree, under
site-packages and under /app; ~/.triton/cache and stale Triton lock files; and FlashInfer's derived JIT
cache. The AOT tree and the cubin dir are preserved (both are build products, both are integrity-checked or
unreproducible offline).
§5.4 process/VRAM hygiene. pkill on narrow patterns, sleep 2, torch.cuda.empty_cache(),
sleep 2, then an nvidia-smi snapshot of used/total memory and SM clock into the log.
Bug found and fixed during validation: the first version of this used
pkill -f "flashinfer". Because the task directory name contains "flashinfer", that pattern matched
the verifier's own shell and killed it (observed exit 144). Broad pkill -f patterns that can match the
task's own path are a live footgun; the patterns are now all narrow and anchored to script basenames.
Oracle detection. Both -f /app/.oracle_solution (written by solve.py) and HARBOR_ORACLE_MODE=1
(set in oracle.yaml) are accepted; either adds --oracle to compute_reward.py.
Failure contract. Every failure path — missing submission, frozen-file tamper, source-scan hit, import
error, worker crash, correctness failure, implausible timing — writes score = 0 into reward.json and
exits 0. Harbor reads reward.json, not exit codes.
10. The oracle
solution/oracle_candidate_decode.py, deliberately modest per SPEC §10. It keeps two live
BatchDecodeWithPagedKVCacheWrappers over two disjoint 64 MiB halves of the caller's 128 MiB workspace —
one with use_tensor_cores=True, one with False — plans on the chosen one, and dispatches per
configuration using a static heuristic computed in plan() (free, since plan() is not timed):
group = num_qo_heads // num_kv_heads
if group < 4: use_tensor_cores = False # MHA wastes the MMA tile
elif mean_kv < 512 and batch < 64: use_tensor_cores = False # launch-overhead bound
else: use_tensor_cores = True
with a plan()-time fallback to the other wrapper if the chosen template refuses the shape. This is a
real win against a baseline pinned at use_tensor_cores=True — it should take h_mha_d256_p64 and
h_b1_short_gqa — while being nowhere near optimal: it writes no kernel, tunes no tile, does nothing about
ragged load imbalance, and uses no Blackwell-specific path. Expected to clear 1.0 by a small margin.
The three thresholds are TODO(calibrate); if they turn out to be wrong on real hardware the oracle
degenerates to "equal to baseline" (geomean ≈ 1.0), which is a soft failure, not a broken pipeline.
11. Static validation — actual output
Run on this box: /usr/bin/python3.11 (3.11.13). The base python3 is 3.6.8 and cannot even parse
from __future__ import annotations, which is why 3.11 is used explicitly. Bytecode was redirected to
/tmp so py_compile could not leave __pycache__ inside the task tree (PYTHONDONTWRITEBYTECODE does
not stop py_compile, which writes on purpose — this was caught and fixed).
11.1 Syntax / config parse
### 1) bash -n on all .sh
./environment/workspace/entrypoint.sh OK
./environment/workspace/timer.sh OK
./solution/solve.sh OK
./tests/test.sh OK
### 2) py_compile on all .py (bytecode redirected to /tmp)
./environment/workspace/optimize.py OK
./environment/workspace/reference_decode.py OK
./environment/workspace/run_dev_bench.py OK
./environment/workspace/submission/candidate_decode.py OK
./environment/workspace/task_fixtures.py OK
./environment/workspace/verify_decode.py OK
./solution/oracle_candidate_decode.py OK
./solution/solve.py OK
./tests/baseline_decode.py OK
./tests/compute_reward.py OK
./tests/worker.py OK
### 2b) __pycache__ / *.pyc in the task tree (must be 0)
count = 0
### 3) task.toml
OK agent.timeout_sec=28800.0 verifier.timeout_sec=3600.0 build_timeout_sec=14400.0 gpu_types=['B200']
TASK_BUDGET_SECS in Dockerfile: TASK_BUDGET_SECS=28800
### 4) job.yaml / oracle.yaml
OK job.yaml keys=9 agents=6 override_timeout_sec=[28800]
OK oracle.yaml keys=5
task.toml's agent.timeout_sec = 28800.0, the Dockerfile's TASK_BUDGET_SECS=28800 and all six
override_timeout_sec: 28800 in job.yaml agree.
11.2 The mandatory reward smoke test, and the four test.sh failure paths
$ python3.11 tests/compute_reward.py --fail "smoke" --output-dir /tmp/fi_smoke --total-time-ms 0
exit=0
ls: reward.json reward.txt
reward.txt = 0.0
reward.json:
{
"score": 0.0,
"reward": 0.0,
"subscores": [],
"additional_data": {
"correctness": {},
"precheck_failure": "smoke",
"reason": "precheck failed: smoke",
"total_time_ms": 0
}
}
json schema OK (score/reward/subscores/additional_data present, score==0.0)
tests/test.sh was then run end to end four times against a simulated /app (no GPU, no torch in the
interpreter, so it necessarily bottoms out in an import error — that is the point: it must still emit a
reward). All four exited 0 with a valid reward.json:
| case |
outcome |
| A — clean prechecks |
prechecks all passed, reached compute_reward.py, reason: "cannot import task_fixtures from /tmp/fi_app: No module named 'torch'", score 0.0 |
B — reference_decode.py tampered (one comment appended) |
precheck_failure: "frozen file reference_decode.py was modified (sha256 666f8114... != eac88946...)", score 0.0 |
| C — submission deleted |
precheck_failure: "missing /app/submission/candidate_decode.py", score 0.0 |
D — submission contains # from compute_reward import geometric_mean |
precheck_failure: "submission references verifier internals: .../candidate_decode.py: 37:# from compute_reward import geometric_mean", score 0.0 |
E — submission contains # see /opt/flashinfer/tests/attention/test_batch_decode_kernels.py |
did not trip the scan (correct: the instructions tell the agent to run exactly that file), fell through to the same import error as case A |
11.3 Frozen-hash verification, three ways
Roots matter: the Dockerfile does COPY workspace/ /app/, so reference_decode.py and
task_fixtures.py are hashed at /app/... while baseline_decode.py is hashed at <tests>/....
test.sh:56-58 passes $APP_DIR for the first two and $SCRIPT_DIR for the third. Verified against a
simulated container layout:
| file |
path actually hashed |
digest on disk |
digest in _hash.txt |
verdict |
reference_decode.py |
/app/reference_decode.py |
eac88946a1d9df91cb2c138352e2831d7ff5008c0ae133306080bf620bf8d9e0 |
same |
MATCH |
task_fixtures.py |
/app/task_fixtures.py |
d4c1e5ac94d3ad0316cfbd7273d8b1a5f7e2218031bf361a30f3bd92183f3e7b |
same |
MATCH |
baseline_decode.py |
<tests>/baseline_decode.py |
888a4afcbb4653955fd67d899c1bfe85d64275bf7210b955dab2c6169ccf4330 |
same |
MATCH |
Duplicate-copy check (cmp -s between environment/workspace/ and tests/): no file exists in both
roots, so the two-copies-drift failure mode is structurally impossible here —
reference_decode.py and task_fixtures.py exist only in workspace/, baseline_decode.py only in
tests/. compute_reward.py performs no independent hash check, so test.sh is the single gate.
11.4 Leak self-checks and matrix coverage
instruction.md leak check (compute_reward|baseline_decode|/app/tests|reward.json|reward.txt|
HIDDEN_BENCHMARK|worker.py|.oracle_solution|HARBOR_ORACLE_MODE|/logs/verifier)
CLEAN
SUSPICIOUS_PATTERNS scan of the shipped /app workspace
CLEAN
oracle submission scan
CLEAN
files referenced by tests/ , solution/ and the Dockerfile
14 checked, MISSING COUNT: 0
hidden configs: 7 visible configs: 5 name overlap: set()
axis batch [1, 32, 64, 96, 224]
axis gqa [1, 4, 8]
axis hd [128, 256]
axis ps [1, 16, 32, 64]
axis mode ['ragged', 'uniform']
axis dt [('bfloat16','bfloat16',None), ('float16','float16',None), ('float16','float8_e4m3fn','float16')]
peak KV pool GiB: 0.75
ragged lens: n=64 min=96 max=12288 mean=1914 p50=939
geomean([1,1,1]) = 1.0 geomean([0.5,2.0]) = 1.0 geomean([1,0,2]) = 0.0
fastp([0.9,1.1,1.3], 1.0) = 0.667 fastp(..., 1.2) = 0.333
VARIANCE_THRESHOLD 0.3 | warmup/measure 20/25 | recheck 10/12
11.5 CPU numerical validation of the frozen reference (real, not a benchmark)
torch==2.10.0+cpu was installed into a scratch directory and reference_decode.ReferenceDecode was
checked against an independently written dense gather-and-softmax implementation on all five visible
configs (batch and KV length shrunk so fp32 CPU is tractable):
torch 2.10.0+cpu
dev_b1_short_gqa b=1 shape=(1, 32, 128) dt=torch.float16 contig=True maxdiff=1.16e-04 tol=(0.02,0.02) OK
dev_b64_long_gqa b=4 shape=(4, 32, 128) dt=torch.bfloat16 contig=True maxdiff=9.74e-04 tol=(0.04,0.04) OK
dev_b32_ragged_page1 b=4 shape=(4, 32, 128) dt=torch.float16 contig=True maxdiff=2.42e-04 tol=(0.02,0.02) OK
dev_b8_mha_d256 b=4 shape=(4, 8, 256) dt=torch.float16 contig=True maxdiff=1.20e-04 tol=(0.02,0.02) OK
dev_b16_fp8kv b=4 shape=(4, 32, 128) dt=torch.float16 contig=True maxdiff=1.22e-04 tol=(0.05,0.05) OK
FAILS: 0
Each config additionally asserted: 2-tuple (k_cache, v_cache) form accepted and bit-identical to the 5-D
form; out= returns the caller's exact data_ptr(); writing garbage into padding slots past
last_page_len leaves the output bit-identical; perturbing the last valid token changes the output
(observed delta 2.74, vs KV_SENSITIVITY_MIN_DELTA = 1e-3); repeated calls bit-identical.
task_fixtures.build_query(cfg, q_seed, dev) was verified bit-identical to
build_fixture(cfg, ..., q_seed=q_seed)["q"] — this matters because the timing loop re-randomizes Q
through build_query to avoid re-allocating a gigabyte of KV per round.
This validates the reference and fixtures. It says nothing about FlashInfer, the baseline, the oracle, or
any timing.
12. TODO(calibrate) — the complete list
Every one of these is a placeholder that needs real B200 hardware. They are all marked
TODO(calibrate) in the source (grep -rn "TODO(calibrate)").
| # |
constant |
file |
value |
how to calibrate |
| 1 |
TOLERANCES["float16"] |
task_fixtures.py:68 |
(2e-2, 2e-2) |
run the frozen baseline against the frozen reference on all 7 hidden configs, take the observed max abs/rel diff, set rtol/atol to ~5× it |
| 2 |
TOLERANCES["bfloat16"] |
task_fixtures.py:69 |
(4e-2, 4e-2) |
same |
| 3 |
TOLERANCES["float8_e4m3fn"] |
task_fixtures.py:70 |
(5e-2, 5e-2) |
same; fp8 KV quantization error dominates and may need more slack |
| 4 |
KV_SENSITIVITY_MIN_DELTA |
task_fixtures.py:76 |
1e-3 |
measure the actual output delta from perturbing one valid KV token on the longest hidden config (dilution is worst there: 1 token out of 16384) and set well below it. This is the one most likely to be wrong — at kv_len 16384 a single-token perturbation is heavily diluted by softmax |
| 5 |
HBM_PEAK_BYTES_PER_SEC |
compute_reward.py:65 |
8.0e12 |
B200 HBM3e is ~8 TB/s; confirm the actual SKU and set from nvidia-smi/spec. Used only for the physical floor with a 10× margin, so a 2× error is harmless |
| 6 |
JIT_WARM_TIMEOUT_S |
compute_reward.py:59 |
1200.0 |
time a genuinely cold JIT compile of one decode module in the built image |
| 7 |
build_timeout_sec |
task.toml:21 |
14400.0 |
time a real cold docker build; the flashinfer.aot layer is the long pole |
| 8 |
oracle heuristic thresholds _TC_MIN_GROUP=4, _TC_MIN_KV_LEN=512, _TC_MIN_BATCH_FOR_SHORT_KV=64 |
oracle_candidate_decode.py:53-55 |
as shown |
sweep use_tensor_cores True/False across the hidden matrix and read off the crossover |
Not marked in code but equally unvalidated, and worth a pass on real hardware:
inner_reps per hidden config (15–50). Chosen so each timed round is roughly 0.5–2 ms; if a kernel turns
out much faster than assumed, h_b1_short_gqa at inner_reps=50 may still be event-overhead dominated.
WARMUP_ITERATIONS=20 / MEASURE_ITERATIONS=25. Above the SPEC §4 floor of 10/10, but the right number
is whatever makes the per-config cv (already recorded in per_config) land under ~0.05.
VARIANCE_THRESHOLD = 0.30 is taken from SPEC §4.4 unchanged; whether B200 clock behaviour actually
stays inside 30% across a full run is unmeasured.
memory_mb = 131072 / storage_mb = 81920. Memory is generous relative to the 0.75 GiB peak KV pool;
storage is a guess at CUDA devel + torch + FlashInfer source + the AOT .so set + the agent CLIs.
- Whether the narrowed
flashinfer.aot flag set actually covers every module the baseline touches on
SM100. If it misses one, the first baseline call JIT-compiles — which the warmup phase absorbs and
first_call_seconds in the diagnostics will make obvious, but it would cost verifier wall clock.
13. Not validated / known risks
Ordered by how much they would hurt.
- The image was never built. Every Dockerfile layer is unexecuted. The highest-risk layer is the
python -m flashinfer.aot invocation: the flags were read off aot.py:1100-1215 at the pinned SHA and
the output path was traced through copy_built_kernels → JitSpec.aot_path, but the command has not
been run. If --fa2-head-dim 128,128 256,256 or the --add-* false spellings are rejected, the build
fails loudly (good), and if the generated set is merely incomplete it degrades to JIT-on-first-use
(survivable, absorbed by the warmup phase).
- Nothing has touched a GPU. No FlashInfer call, no baseline, no oracle, no timing. The entire speed
half of the task is unexercised. In particular: whether
BatchDecodeWithPagedKVCacheWrapper accepts
page_size=1 and head_dim=256 on SM100 in practice (no whitelist blocks them in the source, but
backend="auto" dispatch on real hardware is untested), and whether the oracle's two-wrapper
workspace split (two 64 MiB halves) is large enough for batch=224.
- The oracle's margin is unmeasured. It should clear 1.0 on
h_mha_d256_p64 and h_b1_short_gqa and
tie elsewhere, giving a geomean a little above 1.0. If the use_tensor_cores crossover is elsewhere
than assumed, the oracle ties the baseline at ~1.0. That is a weak oracle, not a broken task — but it
should be re-fitted before the task is used for real.
use_tensor_cores=True on a page_size=1 / head_dim=256 config is the specific combination most
likely to hit an unsupported-configuration error inside FlashInfer. If the baseline raises there, the
run reports a harness error (correctly — that is what the baseline-vs-reference self-check is for), but
it would need the baseline configuration reconsidered for that config.
KV_SENSITIVITY_MIN_DELTA at long context (item 4 in §12) could produce a false correctness
failure on h_b1_long_gqa for an entirely correct candidate. It is the single most likely source of a
spurious zero.
entrypoint.sh's snapshot depends on /opt/flashinfer being the install root. It records the path
to /app/.flashinfer-src-path and test.sh reads it back, so a moved checkout is handled — but if the
agent installs a second FlashInfer into site-packages that shadows the editable install, the restore
would not undo that. test.sh clears site-packages bytecode but does not reinstall the package.
nvidia-smi fields (memory.used,memory.total,clocks.current.sm) are read for diagnostics only and
guarded with || true; the field names were not verified against the driver in the image.
download-cubin needs build-time network. Guarded with || true, so a network-less build produces
an image without cubins. Backends that require cubins (trtllm-gen, some cute-dsl paths) would then
be unavailable to both the agent and the oracle. The graded baseline is backend="auto" with
use_tensor_cores=True, which does not need them, so the bar is unaffected — but the agent's design
space would silently shrink. Worth asserting on rather than swallowing once a real build is attempted.