From 665afd9c2efce76a3d8502cd0c95933880d35c99 Mon Sep 17 00:00:00 2001 From: Vincent Ouyang Date: Tue, 10 Nov 2026 20:17:46 -0800 Subject: [PATCH 1/9] Run sanitizers by default on schema-v3 kernel tasks A run config without an evaluation_tools section now runs the page-fault guard, PyTorch CSAN, TileLens, rocJITsu Waitcheck, the rocJITsu race detector and Triton FpSan on every schema-v3 task on gfx950, for any target language and with no task configuration. GPU ASan is supported for HIP, Triton and Gluon but stays opt-in: it needs a bare-metal host. - The v3 runner gains `evaluate {baseline|candidate} sanitize LANE`. Each lane checks the environment its sidecar set and runs the role on the task's correctness cases. A capture lane records the dispatched kernels for Waitcheck and rocJITsu replay capsules. - Every tool gets a framework-owned v3 adapter, so task.yaml needs no adapter fields. - The new gated policy gives each tool a gate or signal role. A gate blocks performance only on a definite finding that the baseline, rechecked with the same tool, does not share. Unverified results are recorded but never count as clean. A blocked tool gate scores zero. - The runner resolves the default set, builds missing default images and gives the Waitcheck sidecar the worker's GPU. --- AGENTS.md | 9 +- docker/eval-tools/csan/Dockerfile | 13 + docker/eval-tools/page-fault-guard/Dockerfile | 12 + docker/eval-tools/tilelens/Dockerfile | 21 + docker/eval-tools/tilelens/requirements.lock | 10 + docs/how-to/add-task.md | 8 + docs/how-to/run-evaluation.md | 11 +- docs/how-to/use-evaluation-tools.md | 186 ++++- docs/reference/api-reference.md | 39 +- docs/reference/mi355x-runtime.md | 15 +- docs/reference/release-notes.md | 27 + .../evaluation_tools_advisory_mi355x.yaml | 13 +- src/eval_tools/README.md | 9 +- src/eval_tools/adapters/aka_v3_capsules.py | 143 ++++ src/eval_tools/adapters/aka_v3_entrypoint.py | 198 +++++ src/eval_tools/config.py | 41 +- src/eval_tools/contracts.py | 19 + src/eval_tools/defaults.py | 91 +++ src/eval_tools/manager.py | 95 ++- src/eval_tools/plugins/aka_v3.py | 138 ++++ src/eval_tools/plugins/gpu_asan.py | 26 +- src/eval_tools/plugins/registry.py | 4 + src/eval_tools/plugins/rocjitsu.py | 22 +- src/eval_tools/plugins/triton_fpsan.py | 25 +- src/eval_tools/plugins/v3_lanes.py | 233 ++++++ src/eval_tools/plugins/v3_tools.py | 263 ++++++ src/eval_tools/plugins/waitcheck.py | 22 +- src/eval_tools/probes/csan_probe.py | 30 + src/eval_tools/probes/page_fault_probe.py | 41 + src/eval_tools/probes/tilelens_probe.py | 39 + src/eval_tools/worker.py | 99 +++ src/score.py | 4 + src/scripts/docker_benchmark.sh | 98 +-- src/task_contract.py | 7 + src/tools/arena_eval/evaluate.py | 28 +- src/tools/arena_eval/loader.py | 38 +- src/tools/arena_eval/sanitize.py | 762 ++++++++++++++++++ tests/eval_tools/test_config_merge.py | 5 +- tests/eval_tools/test_gluon_support.py | 7 +- tests/eval_tools/test_plugins.py | 6 + tests/eval_tools/test_reporting.py | 1 + tests/eval_tools/test_v3_sanitizers.py | 487 +++++++++++ tests/test_arena_eval_sanitize.py | 122 +++ tests/test_docker_benchmark.sh | 20 +- tests/test_score.py | 10 + 45 files changed, 3350 insertions(+), 147 deletions(-) create mode 100644 docker/eval-tools/csan/Dockerfile create mode 100644 docker/eval-tools/page-fault-guard/Dockerfile create mode 100644 docker/eval-tools/tilelens/Dockerfile create mode 100644 docker/eval-tools/tilelens/requirements.lock create mode 100644 src/eval_tools/adapters/aka_v3_capsules.py create mode 100644 src/eval_tools/adapters/aka_v3_entrypoint.py create mode 100644 src/eval_tools/defaults.py create mode 100644 src/eval_tools/plugins/aka_v3.py create mode 100644 src/eval_tools/plugins/v3_lanes.py create mode 100644 src/eval_tools/plugins/v3_tools.py create mode 100644 src/eval_tools/probes/csan_probe.py create mode 100644 src/eval_tools/probes/page_fault_probe.py create mode 100644 src/eval_tools/probes/tilelens_probe.py create mode 100644 src/tools/arena_eval/sanitize.py create mode 100644 tests/eval_tools/test_v3_sanitizers.py create mode 100644 tests/test_arena_eval_sanitize.py diff --git a/AGENTS.md b/AGENTS.md index c1369f7b7..9faebdb29 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -190,9 +190,12 @@ prompt/post-processing routing, configuration, docs, and tests. A `src/module_registration.py` as the registry source of truth. Evaluation tools belong to the trusted evaluator control plane, not to agent -skills or prompts. Keep them opt-in, isolated, capability-checked, attested, and -fail-closed as described in `docs/how-to/use-evaluation-tools.md`. Do not claim -that a candidate was analyzed merely because a tool exists or its sidecar ran. +skills or prompts. Keep them isolated, capability-checked, attested, and +fail-closed as described in `docs/how-to/use-evaluation-tools.md`. Schema-v3 +runs enable the default set in `src/eval_tools/defaults.py`; a tool joins it +only after its positive controls and a baseline campaign pass on hardware, and +anything else stays opt-in. Do not claim that a candidate was analyzed merely +because a tool exists or its sidecar ran. ## Verification guide diff --git a/docker/eval-tools/csan/Dockerfile b/docker/eval-tools/csan/Dockerfile new file mode 100644 index 000000000..418fbfbfe --- /dev/null +++ b/docker/eval-tools/csan/Dockerfile @@ -0,0 +1,13 @@ +ARG BASE_IMAGE=lmsysorg/sglang:v0.5.20-rocm10-mi35x@sha256:e20849665c105d389ef91d23c0dc73931aaa6f02056dd10e7b43e4f16c79df69 +FROM ${BASE_IMAGE} + +LABEL org.opencontainers.image.title="AgentKernelArena PyTorch CUDA Sanitizer tool runtime" \ + org.opencontainers.image.base.digest="sha256:e20849665c105d389ef91d23c0dc73931aaa6f02056dd10e7b43e4f16c79df69" + +# CSAN ships with the base image's PyTorch (torch.cuda._sanitizer). +RUN python -c "import torch.cuda._sanitizer as s; assert callable(s.enable_cuda_sanitizer)" + +COPY src/eval_tools /opt/aka-eval-tools/src/eval_tools + +ENV AKA_EVAL_TOOL_FRAMEWORK_ROOT=/opt/aka-eval-tools \ + PYTHONPATH=/opt/aka-eval-tools diff --git a/docker/eval-tools/page-fault-guard/Dockerfile b/docker/eval-tools/page-fault-guard/Dockerfile new file mode 100644 index 000000000..a43e17485 --- /dev/null +++ b/docker/eval-tools/page-fault-guard/Dockerfile @@ -0,0 +1,12 @@ +ARG BASE_IMAGE=lmsysorg/sglang:v0.5.20-rocm10-mi35x@sha256:e20849665c105d389ef91d23c0dc73931aaa6f02056dd10e7b43e4f16c79df69 +FROM ${BASE_IMAGE} + +LABEL org.opencontainers.image.title="AgentKernelArena page-fault guard tool runtime" \ + org.opencontainers.image.base.digest="sha256:e20849665c105d389ef91d23c0dc73931aaa6f02056dd10e7b43e4f16c79df69" + +# The guard needs nothing beyond the scoring base: it reruns correctness with +# PyTorch's caching allocator and ROCr's fragment allocator turned off. +COPY src/eval_tools /opt/aka-eval-tools/src/eval_tools + +ENV AKA_EVAL_TOOL_FRAMEWORK_ROOT=/opt/aka-eval-tools \ + PYTHONPATH=/opt/aka-eval-tools diff --git a/docker/eval-tools/tilelens/Dockerfile b/docker/eval-tools/tilelens/Dockerfile new file mode 100644 index 000000000..e9ffe0a6e --- /dev/null +++ b/docker/eval-tools/tilelens/Dockerfile @@ -0,0 +1,21 @@ +ARG BASE_IMAGE=lmsysorg/sglang:v0.5.20-rocm10-mi35x@sha256:e20849665c105d389ef91d23c0dc73931aaa6f02056dd10e7b43e4f16c79df69 +FROM ${BASE_IMAGE} + +LABEL org.opencontainers.image.title="AgentKernelArena TileLens tool runtime" \ + org.opencontainers.image.base.digest="sha256:e20849665c105d389ef91d23c0dc73931aaa6f02056dd10e7b43e4f16c79df69" \ + org.opencontainers.image.version="tilelens-3.1.1" + +# TileLens lives beside, not inside, the base environment: only the sanitizer +# lane puts /opt/tilelens/site-packages on its import path. +COPY docker/eval-tools/tilelens/requirements.lock /opt/tilelens/requirements.lock +RUN /opt/venv/bin/python -m pip install --no-cache-dir --no-deps --require-hashes --only-binary=:all: \ + --target /opt/tilelens/site-packages -r /opt/tilelens/requirements.lock \ + && PYTHONPATH=/opt/tilelens/site-packages /opt/venv/bin/python -c \ + "import tilelens, z3; from tilelens.clients import Sanitizer; print('tilelens', z3.get_version_string())" + +COPY src/eval_tools /opt/aka-eval-tools/src/eval_tools + +ENV AKA_EVAL_TOOL_FRAMEWORK_ROOT=/opt/aka-eval-tools \ + PYTHONPATH=/opt/aka-eval-tools \ + AKA_TILELENS_ROOT=/opt/tilelens/site-packages \ + AKA_TILELENS_VERSION=3.1.1 diff --git a/docker/eval-tools/tilelens/requirements.lock b/docker/eval-tools/tilelens/requirements.lock new file mode 100644 index 000000000..d16eb04b6 --- /dev/null +++ b/docker/eval-tools/tilelens/requirements.lock @@ -0,0 +1,10 @@ +# TileLens and the modules its sanitizer imports, installed with --no-deps +# into /opt/tilelens/site-packages: the base image's PyTorch, Triton and NumPy +# stay authoritative. Hashes are the PyPI wheels for CPython 3.12 / x86_64. +tilelens==3.1.1 --hash=sha256:25f281f3fd7df260fe0689162d550a747b8cbb264b0e6107ce415b746a9bc9a7 +z3-solver==4.15.3.0 --hash=sha256:a9afd9ceb290482097474d43f08415bcc1874f433189d1449f6c1508e9c68384 +anytree==2.13.0 --hash=sha256:4cbcf10df36b1f1cba131b7e487ff3edafc9d6e932a3c70071b5b768bab901ff +tqdm==4.70.1 --hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73 +ml-dtypes==0.6.0 --hash=sha256:3b4a480aa8fd54a1805b8ac10f3f91763926a74f73c0c364c10f9231854f4170 +pyarrow==26.0.1 --hash=sha256:c718bf97a92a6dea97fd1062c3b9f9e2e83cb9cc926e752289fa4ffff41738f9 +flask==3.1.3 --hash=sha256:f4bcbefc124291925f1a26446da31a5178f9483862233b23c0c96a20701f670c diff --git a/docs/how-to/add-task.md b/docs/how-to/add-task.md index 1c388ae5d..d65491e66 100644 --- a/docs/how-to/add-task.md +++ b/docs/how-to/add-task.md @@ -344,6 +344,14 @@ python3 -m _aka_eval.evaluate candidate {compile|correctness|performance} - **Scoring.** The per-case speedup is baseline time over candidate time; the task's speedup is their geometric mean. Any failed correctness case scores 0. The final evaluation remeasures the baseline next to the candidate. +- **Sanitizers.** On MI355X the final evaluation also runs the default + sanitizers between correctness and performance (see + [Default sanitizers for schema-v3 tasks](use-evaluation-tools.md#default-sanitizers-for-schema-v3-tasks)). + A gate's definite finding stops performance, so the candidate scores 0, + unless the baseline shares it. Keep the baseline clean in every lane: a + finding the baseline shares leaves that lane unable to protect the task. + The framework runs `python3 -m _aka_eval.evaluate {baseline|candidate} + sanitize LANE` itself. ## Run configuration diff --git a/docs/how-to/run-evaluation.md b/docs/how-to/run-evaluation.md index c8e4f4726..b14971705 100644 --- a/docs/how-to/run-evaluation.md +++ b/docs/how-to/run-evaluation.md @@ -26,7 +26,7 @@ ships quickstarts and specialized examples, including: | `example_configs/quickstart_claude_mi300a.yaml` | Claude Code RMSNorm task with the MI300A hardware profile (`gfx942`). | | `example_configs/quickstart_claude_mi355x.yaml` | One Claude Code RMSNorm task on MI355X (`gfx950`). | | `example_configs/benchmark_cursor_mi355x.yaml` | Cursor Agent over a whole task category on MI355X; use only after installing and authenticating Cursor Agent. | -| `example_configs/evaluation_tools_advisory_mi355x.yaml` | Default-disabled template for experimental `gfx950` evaluation-tool sidecars. It still requires task-specific adapters before opt-in. | +| `example_configs/evaluation_tools_advisory_mi355x.yaml` | Template with an explicit, disabled `evaluation_tools` section for task-declared adapters on `gfx950`. Schema-v3 runs need no section: the default sanitizers run without one. | | `example_configs/qa_audit_all_mi355x.yaml` | [QA audit](qa-auditor.md) of every task on MI355X. | | `example_configs/e2e_*_qa_mi355x.yaml` | QA audit of an end-to-end serving task. | @@ -111,10 +111,11 @@ is missing fails the run before it starts. See the See [Configuration and API reference](../reference/api-reference.md) for the full set of run-configuration fields. -Optional sanitizer and analysis sidecars run after ordinary correctness and -before performance. They are disabled by default, verified only on `gfx950`, -and require language/task-specific adapters. See [Check kernels with evaluation -tools](use-evaluation-tools.md) before enabling them. +Sanitizer sidecars run after ordinary correctness and before performance. On +MI355X (`gfx950`) a run configuration without an `evaluation_tools` section +runs the default schema-v3 set; the runner builds any missing sidecar image on +first use. Set `evaluation_tools: false` to turn it off. See [Check kernels +with evaluation tools](use-evaluation-tools.md#default-sanitizers-for-schema-v3-tasks). ## Start a run diff --git a/docs/how-to/use-evaluation-tools.md b/docs/how-to/use-evaluation-tools.md index cd5565dbf..0fdd273c4 100644 --- a/docs/how-to/use-evaluation-tools.md +++ b/docs/how-to/use-evaluation-tools.md @@ -1,16 +1,21 @@ --- myst: html_meta: - "description": "Run Triton FpSan, ROCm GPU AddressSanitizer, rocJITsu Race Detector, Waitcheck, ConSan, and HIP-FpSan as isolated AgentKernelArena evaluation tools." - "keywords": "AgentKernelArena, sanitizer, Triton FpSan, GPU ASan, rocJITsu, Waitcheck, ConSan, HIP-FpSan, ROCm, gfx950" + "description": "Run the default schema-v3 sanitizers (page-fault guard, PyTorch CSAN, TileLens, Waitcheck, rocJITsu, Triton FpSan) and opt-in GPU AddressSanitizer, ConSan and HIP-FpSan as isolated AgentKernelArena evaluation tools." + "keywords": "AgentKernelArena, sanitizer, page-fault guard, CSAN, TileLens, Triton FpSan, GPU ASan, rocJITsu, Waitcheck, ConSan, HIP-FpSan, ROCm, gfx950" --- # Check kernels with evaluation tools -AgentKernelArena can run optional kernel-analysis tools after ordinary -compilation and correctness checks and before performance measurement. The -initial tool set is: +AgentKernelArena runs kernel-analysis tools after ordinary compilation and +correctness checks and before performance measurement. Schema-v3 kernel tasks +on MI355X run a default set with no configuration; see +[Default sanitizers for schema-v3 tasks](#default-sanitizers-for-schema-v3-tasks). +The tool set is: +- A page-fault guard that reruns correctness with the caching allocators off. +- PyTorch's CUDA Sanitizer (CSAN) for cross-stream races. +- TileLens for symbolic out-of-bounds checks of Triton and Gluon kernels. - Triton FpSan for reference-versus-candidate floating-point semantic comparison. - ROCm GPU AddressSanitizer (GPU ASan) for invalid device-memory accesses. @@ -21,23 +26,110 @@ initial tool set is: exact code object launched by a focused native harness. - HIP-FpSan for explicitly ported HIP/C++ floating-point comparisons. -This feature is experimental and opt-in. Capability and evidence checks fail -closed; whether an incomplete result blocks performance is controlled by the -`advisory` or `required` policy. It is not a general sanitizer suite: +Capability and evidence checks fail closed; whether a finding or an +incomplete result blocks performance is controlled by the `advisory`, +`required` or `gated` policy. It is not a general sanitizer suite: every result is qualified by the kernel language, generated artifact, adapter, tool image, GPU architecture, and evidence that the intended kernel was actually instrumented or dispatched. > **Current validation boundary:** sidecar build locks, integrated startup -> controls, and end-to-end fixtures exist only for MI355X (`gfx950`). The ROCm 10 -> migration has passed five runtime startup controls; GPU ASan qualification is -> blocked by failing safe probes on the tested hosts. See the +> controls, and end-to-end fixtures exist only for MI355X (`gfx950`). GPU ASan +> passes its safe and out-of-bounds probes on bare-metal MI355X hosts and fails +> on virtualized hosts, whose GPUs cannot service recoverable page faults on +> host memory (XNACK); it is therefore not a default. See the > [runtime compatibility guide](../reference/mi355x-runtime.md). > Candidate readiness still depends on language, artifact, adapter, and attestation. > `gfx942` is unverified, and the Docker runner currently rejects > evaluation-tool sidecars on that architecture. Do not interpret normal > MI300/MI325 task support as sanitizer support. +## Default sanitizers for schema-v3 tasks + +A run configuration without an `evaluation_tools` section runs the tools below +on every schema-v3 kernel task when the host is a `gfx950` MI355X. A task +declares nothing: each tool runs the generated workspace runner's +`python3 -m _aka_eval.evaluate ROLE sanitize LANE` action +(`src/tools/arena_eval/sanitize.py`) in its own sidecar, on the task's own +correctness cases, for whatever `target_language` the run selected. +`src/eval_tools/defaults.py` is the single source of truth for the set, the +roles and the policy; the Docker runner builds any missing default image on +first use. + +| Tool | Default | Role | What it checks | Languages | +| --- | --- | --- | --- | --- | +| `page_fault_guard` | on | gate | Every correctness case with PyTorch's caching allocator and ROCr's fragment allocator off. An access past an allocation then reaches an unmapped page and the GPU faults instead of landing silently in a neighbouring tensor; an output that passed correctness but changes with the allocator is also a finding. | Triton, Gluon, HIP, FlyDSL | +| `csan` | on | gate | Every correctness case under PyTorch's CUDA Sanitizer: unsynchronized access to a tensor from two streams by PyTorch-visible work, which includes a HIP candidate's custom op. Raw Triton, Gluon and FlyDSL launches are not visible to it. | all four | +| `tilelens` | on | gate | The smallest case with every Triton or Gluon kernel run by TileLens 3.1.1 in Triton's CPU interpreter; each load and store address is checked against its tensor symbolically (z3 over program id, mask and loop bounds). Uses no GPU time. | Triton, Gluon | +| `rocjitsu_waitcheck` | on | gate | Static missing or too-weak wait detection on every kernel the role dispatched. One call on the smallest case captures the final code objects (Triton/Gluon cache, the HIP extension's embedded bundle, FlyDSL's embedded HSACO). | all four | +| `rocjitsu` | on | gate | rocJITsu's simulated LDS/register race detector. Each captured Triton or Gluon launch becomes a replay capsule (code object, lowered ABI, launch geometry, memory before and after) replayed once in the simulator. | Triton, Gluon | +| `triton_fpsan` | on | signal | The smallest case through Triton FpSan for the candidate and the baseline. A different digest means a different floating-point expression, which a correct rewrite (online softmax, another reduction order or precision) also produces, so this never blocks. | Triton or Gluon candidate with a Triton or Gluon baseline | +| `gpu_asan` | **off** | gate | Every correctness case with GPU AddressSanitizer instrumentation: HIP rebuilt with `-fsanitize=address -shared-libsan --offload-arch=gfx950:xnack+`, Triton and Gluon compiled with `TRITON_ENABLE_ASAN=1` and buffer ops off. | HIP, Triton, Gluon; bare-metal hosts only | + +Turn the stage off with `evaluation_tools: false` (or `enabled: []`). Any +explicit `evaluation_tools` section is used exactly as written instead of the +defaults. To add GPU ASan on a bare-metal host, list the defaults plus +`gpu_asan`: + +```yaml +evaluation_tools: + policy: gated + enabled: [page_fault_guard, csan, tilelens, triton_fpsan, rocjitsu_waitcheck, rocjitsu, gpu_asan] +``` + +### Gate and signal roles + +The default `gated` policy reads each tool's `role` (`gate` unless the tool is +a semantic comparison; set `evaluation_tools.tools..role` to override): + +- A `gate` blocks performance, and therefore the score, only on a definite + finding: a fault, a sanitizer report, a race or hazard record, or an output + that changes with the allocator. +- After a candidate finding the manager reruns the same tool on the task's + baseline. A finding the baseline shares is recorded with + `baseline_also_found: true` and does not block: the reference + implementation does the same thing. +- Anything that is not a definite finding — an unsupported construct, a + kernel TileLens cannot interpret, a tool error, a timeout, a capture that + recorded nothing — is recorded as unverified (`policy_satisfied: false`) and + does not block. +- A `signal` never blocks. + +`decision.blocking` lists the findings that stopped performance; a gated +report's `decision.reasons` still lists every unverified tool. Monitor the +unverified rate per language: a candidate that a lane cannot analyze (for +example inline assembly that TileLens approximates) shows up there, not as clean. The +default per-tool deadline is 1200 seconds. + +### What each lane covers and misses + +- The page-fault guard catches an access only when it leaves the mapped + allocation; a small overrun inside an allocation's rounding slack is missed. + A buffer instruction whose descriptor carries the tensor's real size clamps + instead of faulting. The FlyDSL baselines tested build descriptors that do + not clamp at the tensor end, so their out-of-bounds stores fault under the + guard. +- GPU ASan does not see Triton buffer operations (the lane turns them off, + so it checks a slightly different kernel than the one timed) or Gluon's + explicit `gl.amd.cdna4.buffer_load`/`buffer_store`, which the page-fault + guard covers instead. An ASan-built HIP extension loads only in a process + with the ASan runtime preloaded, so the lane is always a separate process. +- TileLens approximates inline assembly and cannot run a Gluon kernel that + calls a `@triton.jit` helper; both are unverified, not clean. +- rocJITsu replays only what the capture recorded: up to 16 launches and + 256 MiB of reachable memory per call. Tensor-descriptor arguments and + non-zero global scratch cannot be lowered yet, and HIP and FlyDSL launches + expose no lowered ABI to capture, so those are unverified. +- CSAN sees PyTorch dispatches only; AKA's static policy already forbids + candidates from switching streams. + +Not enabled for v3 candidates: ConSan (it needs a focused native loader and an +independent oracle per code object; rocJITsu covers LDS races on the same +captures), HIP-FpSan (each candidate must be hand-ported to `fpsan::Value`), +and Triton's own `consan`/`gsan` instrumentation modes (`consan` is +implemented only for `gfx1250` and is a silent no-op on `gfx950` even though +the compile metadata records it; `gsan` is NVIDIA-only). + ## Keep the scoring runtime unchanged Evaluation tools do not get installed into the agent or scoring container. @@ -122,6 +214,9 @@ The pinned sidecar dependencies are recorded in | `rocjitsu_waitcheck` | rocJITsu Waitcheck C API and CLI from pinned `rocm-systems` commit `ed35c0b...`; zstd source is separately checksum-locked. | | `rocjitsu_consan` | rocJITsu ConSan HSA hook from the same pinned `ed35c0b...` source, forced to strict record/replay mode. | | `hip_fpsan` | HIP-FpSan headers/source from pinned commit `0ac9be8a...`. | +| `page_fault_guard` | None: the scoring base unchanged (the lane only switches allocators off). | +| `csan` | None: PyTorch's bundled `torch.cuda._sanitizer`. | +| `tilelens` | TileLens `3.1.1` and the wheels its sanitizer imports, hash-locked in `docker/eval-tools/tilelens/requirements.lock` and installed with `--no-deps` into `/opt/tilelens/site-packages`, which only the TileLens lane imports. | ## Understand support levels @@ -167,6 +262,11 @@ remain experimental. ### Strict support matrix +For schema-v3 tasks the framework supplies every adapter itself; see +[Default sanitizers for schema-v3 tasks](#default-sanitizers-for-schema-v3-tasks), +which supersedes the Gluon row and the "adapter required" entries below for +those tasks. The matrix describes task-declared adapters. + The following table describes the current end-to-end evaluator, not just a successful standalone experiment. “Ready with adapter” means the task must provide the dedicated argv/harness and required attestation described later; @@ -242,7 +342,8 @@ Additional boundaries: Building requires Docker and network access to the pinned package and source locations. Runtime sidecars themselves start with networking disabled. -Build all six local `gfx950` images from the repository root: +Build all nine local `gfx950` images from the repository root (a run builds +any missing default image on first use): ```bash src/scripts/docker_benchmark.sh build-eval-tool-images @@ -257,6 +358,9 @@ agent-kernel-arena/eval-tool-rocjitsu:gfx950-rocm10 agent-kernel-arena/eval-tool-rocjitsu-waitcheck:gfx950-rocm10 agent-kernel-arena/eval-tool-rocjitsu-consan:gfx950-rocm10 agent-kernel-arena/eval-tool-hip-fpsan:gfx950-rocm10 +agent-kernel-arena/eval-tool-page-fault-guard:gfx950-rocm10 +agent-kernel-arena/eval-tool-csan:gfx950-rocm10 +agent-kernel-arena/eval-tool-tilelens:gfx950-rocm10 ``` Check that the workers start and report their pinned assets: @@ -292,6 +396,9 @@ worker: | `rocjitsu_waitcheck` | Compile unbundled `gfx950` code objects and run the production entrypoint, inventory, C API, and parser on the correct-wait and missing-wait fixtures; retain a direct CLI hazard check as an independent engine control. | | `rocjitsu_consan` | Compile raw safe/racy HSACOs plus an image-owned module launcher, run the production entrypoint with separate instrumented/oracle argv, require the oracle environment to be scrubbed, and make the production parser return clean/finding with exact FNV attribution. | | `hip_fpsan` | Require explicitly ported equivalent expressions to match and a known-wrong expression to produce a different digest. | +| `page_fault_guard` | With the caching allocators off, a safe Triton copy must pass and a store 256 MiB past its output must fault. | +| `csan` | A side-stream read followed by `wait_stream` must pass; without the wait CSAN must report a race. | +| `tilelens` | Through the lane's programmatic API (a `Sanitizer` with `abort_on_error` off), an in-bounds Triton copy must record no violation and an off-by-one copy at least one. | `eval-tools-smoke` prints this evidence and exits nonzero if a worker reports `degraded`, including a failed nested positive control. Inspect and retain the @@ -338,11 +445,12 @@ global milestone. | 6. Narrow required gates | Change only individually qualified task/tool pairs to `required`; leave unsupported and not-yet-qualified paths advisory or disabled. | Required gates block seeded findings and infrastructure failures without changing ordinary correctness semantics or the scoring performance baseline. | | 7. Add `gfx942` separately | Build architecture-specific images/configs and rerun every startup, adapter, security, and workload fixture on MI300X/MI325X. | Only mark `gfx942` supported after independent qualification; do not infer it from `gfx950`. | -Phase 0, the six integrated startup controls, complete plan serialization, the -narrower runner mounts, and the trusted AOT replay core exist. No bundled task -has completed production qualification through phases 2–6. Automatic capsule -capture, exact candidate/dispatch provenance, top-level resume freshness, and -the same-phase agent/evaluator boundary remain blockers. +This plan governs task-declared adapters. Schema-v3 tasks follow the default +set instead: framework adapters replace phase 2, the v3 capture closes phase 3 +for Triton and Gluon launches (FlyDSL and HIP code objects are captured for +Waitcheck, not replay), and the `gated` policy with baseline rechecks replaces +the advisory/required choice of phases 5–6. Top-level resume freshness and the +same-phase agent/evaluator boundary of phase 4 remain open for every path. ## Start from the disabled example @@ -373,7 +481,7 @@ evaluation_tools: options: {} ``` -Do not enable all six tools merely because all six images exist. On a +Do not enable every tool merely because every image exists. On a heterogeneous task set, irrelevant tools become `not_applicable`, unsupported paths remain visible as unsupported, and missing adapters remain `adapter_required`. @@ -398,8 +506,10 @@ make docker-run CONFIG=my_sanitized_run.yaml RUN_ARGS='--run-suffix asan_advisor The override names are `AKA_EVAL_TOOL_IMAGE_TRITON_FPSAN`, `AKA_EVAL_TOOL_IMAGE_GPU_ASAN`, `AKA_EVAL_TOOL_IMAGE_ROCJITSU`, `AKA_EVAL_TOOL_IMAGE_ROCJITSU_WAITCHECK`, -`AKA_EVAL_TOOL_IMAGE_ROCJITSU_CONSAN`, and -`AKA_EVAL_TOOL_IMAGE_HIP_FPSAN`. +`AKA_EVAL_TOOL_IMAGE_ROCJITSU_CONSAN`, +`AKA_EVAL_TOOL_IMAGE_HIP_FPSAN`, `AKA_EVAL_TOOL_IMAGE_PAGE_FAULT_GUARD`, +`AKA_EVAL_TOOL_IMAGE_CSAN`, and `AKA_EVAL_TOOL_IMAGE_TILELENS`. An overridden +image must already exist; only the default tags are built on demand. After selecting a tool-image reference, the runner resolves its local immutable image ID with `docker image inspect`, launches the sidecar by that bare @@ -432,14 +542,15 @@ capability limits. For a schema-v3 kernel task the candidate is the `solution/` tree (the only editable tree; its entry is the host function `run()`, so no GPU dispatch symbol is declared), and the protected set includes `_aka_eval/` and `task.yaml`. The -language is the run's `target_language`: `triton`, `hip` and `flydsl` map to the -tool lanes below, while `gluon` and any unknown language report `unsupported`, -so a `required` tool cannot pass silently. The `task.yaml` schema has no -`evaluation_profile` or `evaluation_tools` fields, and the execution config the -framework generates contains none, so a v3 task cannot register task-level -adapters; the `evaluation_profile` and task-level `evaluation_tools` examples in -this section describe task kinds whose execution config carries them and are not -verified against a v3 kernel task. +language is the run's `target_language`. The `task.yaml` schema has no +`evaluation_profile` or `evaluation_tools` fields and needs none: every tool +uses the framework's own v3 adapter (the workspace runner's `sanitize` lanes +and the image-owned `aka_v3_entrypoint` capture for Waitcheck and rocJITsu), +described in +[Default sanitizers for schema-v3 tasks](#default-sanitizers-for-schema-v3-tasks). +A language a tool cannot handle reports `unsupported` or `not_applicable` +there. The `evaluation_profile` and task-level `evaluation_tools` examples in +this section describe task kinds whose execution config carries them. Run-level configuration chooses tools, policy, optional image-identity assertions, and maximum timeout. A task may register adapters for known tools, @@ -663,6 +774,7 @@ rewrite `pass_correctness`. | --- | --- | --- | | `advisory` | Recorded; `policy_satisfied: false` | Continues (`allowed: true`) | | `required` | Recorded with a reason | Skipped (`allowed: false`) | +| `gated` | Recorded; only a `gate` tool's definite finding that the baseline does not share is listed in `decision.blocking` | Skipped only when `decision.blocking` is non-empty | An explicitly `not_applicable` tool is ignored by the gate. Under `required`, every other selected tool must have effective capability `ready`, execution @@ -1006,11 +1118,12 @@ the following: - Only `gfx950` has pinned sidecar locks, passing integrated startup controls, and end-to-end fixtures; `gfx942` is unverified and rejected by the host runner. -- Every useful task still needs a reviewed adapter command. Tool installation - alone usually produces `adapter_required`. -- Five startup controls pass for the ROCm 10 profile. GPU ASan remains - unqualified on the tested hosts. Passing controls qualify tool installation, - not candidate coverage. +- Schema-v3 tasks need no adapter. Every other task kind still needs a + reviewed adapter command; tool installation alone usually produces + `adapter_required`. +- GPU ASan's startup control passes only on bare-metal hosts; on virtualized + hosts the tool is `unavailable_runtime`. Passing controls qualify tool + installation, not candidate coverage. - Runtime-internal asset paths are injected from verified sidecar health and cannot be supplied by task configuration. - Build-attestation artifact paths must be relative to the attestation file; @@ -1038,8 +1151,11 @@ the following: submission evidence or explicit digests. The report serializes the complete tool plan. - Triton/FlyDSL AOT replay is implemented for validated, single-dispatch - `gfx950` capsules and forbids arbitrary launchers. Automatic evaluator-owned - capsule extraction and correctness-run provenance are not implemented. + `gfx950` capsules and forbids arbitrary launchers. For schema-v3 Triton and + Gluon candidates the image-owned entry point captures each launch of one + call on the smallest case and builds its capsule; the capture runs in the + same process as the candidate, guarded by the evaluator's integrity + snapshot, so it is evaluator-recorded but not independent of the candidate. - FlyDSL GPU ASan and Triton FpSan instrumentation are unavailable. - Precompiled AITER, rocBLAS, RCCL, and other library kernels are not covered unless the exact source is rebuilt through a supported and attested path. diff --git a/docs/reference/api-reference.md b/docs/reference/api-reference.md index 78da97622..347d2b562 100644 --- a/docs/reference/api-reference.md +++ b/docs/reference/api-reference.md @@ -63,17 +63,23 @@ workspace_directory_prefix: workspace ## Evaluation tools -`evaluation_tools` configures optional, isolated kernel-analysis sidecars. The -section is disabled when it is absent, `null`, or `false`. A configured mapping -with no enabled tools is also disabled unless the host runner supplies +`evaluation_tools` configures isolated kernel-analysis sidecars. When the +section is absent, the Docker runner starts the default set from +`src/eval_tools/defaults.py` on `gfx950` (`page_fault_guard`, `csan`, +`tilelens`, `triton_fpsan`, `rocjitsu_waitcheck`, `rocjitsu`) and the scoring +process plans it under the `gated` policy with a 1200-second per-tool deadline; +elsewhere, or without the runner, an absent section is disabled. `null`, +`false` and an empty `enabled` list disable the stage. A configured mapping with +no enabled tools is also disabled unless the host runner supplies `AKA_EVAL_TOOLS`; for a mapping, that host subset replaces its `enabled` value. The built-in IDs are `triton_fpsan`, `gpu_asan`, `rocjitsu`, -`rocjitsu_waitcheck`, `rocjitsu_consan`, and `hip_fpsan`. +`rocjitsu_waitcheck`, `rocjitsu_consan`, `hip_fpsan`, `page_fault_guard`, +`csan`, and `tilelens`. Sidecar build locks, integrated positive controls, and end-to-end fixtures -currently exist only for `gfx950`. The ROCm 10 migration has five passing -startup controls; GPU ASan remains unqualified, as recorded in the -[runtime compatibility guide](mi355x-runtime.md). Each applicable candidate still needs a task-specific +currently exist only for `gfx950`. GPU ASan's controls pass only on bare-metal +hosts, as recorded in the [runtime compatibility guide](mi355x-runtime.md). +Schema-v3 tasks use framework adapters; other task kinds need a task-specific adapter and attestation, and enabling an image alone does not imply that a kernel was analyzed. See [Check kernels with evaluation tools](../how-to/use-evaluation-tools.md) for the support matrix and operational @@ -91,14 +97,15 @@ submount remains writable when the quality-loop repository root is read-only. | Field | Type | Default | Description | | --- | --- | --- | --- | -| `evaluation_tools.enabled` | boolean, string, or list of strings | empty | Tool IDs to plan. `true` expands to all six built-ins; `false` disables the feature. A single string is accepted. Hyphens are normalized to underscores. When the host sets `AKA_EVAL_TOOLS`, its normalized subset is authoritative for both started sidecars and the in-container plan. | -| `evaluation_tools.policy` | `advisory` or `required` | `advisory` | `advisory` always permits performance but records an unsatisfied policy. `required` permits performance only when every applicable selected tool is ready, completes, and reports `clean`. | +| `evaluation_tools.enabled` | boolean, string, or list of strings | empty | Tool IDs to plan. `true` expands to all nine built-ins; `false` disables the feature. A single string is accepted. Hyphens are normalized to underscores. When the host sets `AKA_EVAL_TOOLS`, its normalized subset is authoritative for both started sidecars and the in-container plan. | +| `evaluation_tools.policy` | `advisory`, `required` or `gated` | `advisory` for an explicit section; `gated` for the default set | `advisory` always permits performance but records an unsatisfied policy. `required` permits performance only when every applicable selected tool is ready, completes, and reports `clean`. `gated` blocks only on a `gate` tool's definite finding that the task's baseline, rechecked with the same tool, does not share. | | `evaluation_tools.positive_control` | `required`, `optional`, `disabled`, or boolean | `required` | Requires the applicable synthetic known-bug startup control to pass before runtime capability is ready. `optional`, `disabled`, and `false` normalize to not required; the worker still runs and reports its control. | | `evaluation_tools.timeout_s` | exact integer from 1 through 3600 | `3600` | Default maximum execution time for each selected tool. Booleans, floats, and numeric strings are rejected. | | `evaluation_tools.runtime_profile` | string or `null` | `null` | Fallback runtime-identity assertion for plans whose tool has no `runtime_ref`. It does not select an image and must exactly match worker health when set. | | `evaluation_tools.tools` | mapping | `{}` | Per-tool configuration keyed by normalized tool ID. Entries do not enable tools. | | `evaluation_tools.tools..runtime_ref` | string or `null` | automatic host image ID | Exact bare local Docker image ID (`sha256:...`) asserted by the plan and compared with worker health. The `image_digest` key is an alias. This field does not select an image; omit it when using automatic host injection. | | `evaluation_tools.tools..timeout_s` | exact integer from 1 through 3600 | top-level timeout | Per-tool timeout; it cannot exceed the top-level timeout. | +| `evaluation_tools.tools..role` | `gate` or `signal` | `signal` for `triton_fpsan` and `hip_fpsan`, otherwise `gate` | How the `gated` policy treats the tool's findings. Part of the plan and its fingerprint. | | `evaluation_tools.tools..options` | mapping | `{}` | Adapter options, including argv lists and candidate-evidence paths. Reserved framework keys are rejected at run and task level: `positive_control_required`; GPU ASan runtime/preload/library keys; rocJITsu binary/config keys; Waitcheck CLI/C API keys; ConSan hook keys; and HIP-FpSan include/header keys. | The exact reserved option keys are `positive_control_required` for every tool; @@ -232,11 +239,11 @@ ignored, so use only the documented keys. ### Task-level tool adapters -Schema-v3 kernel tasks cannot declare `evaluation_profile` or `evaluation_tools`: the -`task.yaml` contract has no such fields, the candidate is the `solution/` tree and -the language is the run's `target_language` (not verified against a v3 task). The -rest of this section applies to task kinds whose execution config carries these -sections. +Schema-v3 kernel tasks declare neither `evaluation_profile` nor `evaluation_tools`: +the `task.yaml` contract has no such fields, and every tool uses the framework's +own v3 adapter. The candidate is the `solution/` tree and the language is the +run's `target_language`. The rest of this section applies to task kinds whose +execution config carries these sections. A task can register adapters for known tools, including tools the current run does not enable. Disabled adapters are validated and remain dormant. The only @@ -325,11 +332,11 @@ Each task produces a `task_result.yaml` in its workspace: | `schema_version` | Evaluation-tool result schema version. | | `plan_fingerprint` | SHA-256 over normalized configuration, resolved task profile, plugin versions, captured original/candidate evidence for declared paths, verified scoring-image reference/ID, and the content digest of a configured replay capsule. | | `plan` | Complete immutable plan: schema, policy, profile, ordered tool records (runtime reference, plugin version, timeout, and options), fingerprint, and source evidence. | -| `policy` | `advisory` or `required`. | +| `policy` | `advisory`, `required` or `gated`. | | `overall_status` | `clean`, `finding`, `incomplete`, or `not_applicable`. | | `resolved_task_profile` | Inferred profile plus auditable explicit overrides. | | `source_evidence` | Captured-original and candidate fingerprints plus manifest metadata, including `metadata.scoring_runtime.image_id` and `.reference` when tools run. | -| `decision` | `allowed`, `policy_satisfied`, and machine-readable reason strings. | +| `decision` | `allowed`, `policy_satisfied`, machine-readable reason strings, and under `gated` the `blocking` findings that stopped performance. | | `tools..capability` | Separate `engine`, `adapter`, `runtime`, and resolved `effective` checks. | | `tools..result.execution` | `not_run`, `completed`, `tool_error`, or `timeout`. | | `tools..result.finding` | `not_evaluated`, `clean`, `found`, or `inconclusive`. | diff --git a/docs/reference/mi355x-runtime.md b/docs/reference/mi355x-runtime.md index f0de2a33a..33d692089 100644 --- a/docs/reference/mi355x-runtime.md +++ b/docs/reference/mi355x-runtime.md @@ -3,12 +3,17 @@ The MI355X default is the immutable SGLang 0.5.20 / ROCm 10 manifest selected in [`docker_benchmark.sh`](https://github.com/AMD-AGI/AgentKernelArena/blob/main/src/scripts/docker_benchmark.sh). The `gfx942` and `gfx1201` defaults are unchanged. Explicit image overrides and -task-specific runtime requirements still apply. GPU ASan is **unqualified** on -the tested hosts and remains unavailable when its required controls fail. The -scoring-runtime migration does not qualify this optional analysis tool. Earlier -image qualifications do not qualify a changed source/image combination. +task-specific runtime requirements still apply. GPU ASan passes its safe and +out-of-bounds HIP, HIP-extension, Triton and Gluon probes with this image on +bare-metal MI355X hosts, under ordinary and hardened container flags. It fails +on virtualized MI355X hosts: there the GPU reports `xnack+` and pageable +memory access with `HSA_XNACK=1`, yet a kernel touching `malloc()` memory +faults, and so does the ASan runtime's heap-initialization kernel. GPU ASan is +therefore opt-in, for bare-metal hosts, and stays unavailable wherever its +startup controls fail. Earlier image qualifications do not qualify a changed +source/image combination. -All six optional tool runtimes use the same scoring base and distinct +All nine evaluation-tool runtimes use the same scoring base and distinct `gfx950-rocm10` tags. The scoring-image verifier rejects mismatched images and freezes accepted aliases to their local image IDs. See the maintained [tool capability matrix](../how-to/use-evaluation-tools.md) for startup and diff --git a/docs/reference/release-notes.md b/docs/reference/release-notes.md index 5e5c96ab7..c82046e97 100644 --- a/docs/reference/release-notes.md +++ b/docs/reference/release-notes.md @@ -53,6 +53,33 @@ This topic summarizes the features available in each AgentKernelArena release. F `Aiter-task-mi300`, `image_kernel`) are replaced by the new tasks; no compatibility layer is provided. The end-to-end serving tasks keep schema v2. +### Default sanitizers for schema-v3 tasks + +- A run configuration without an `evaluation_tools` section now runs sanitizers + on every schema-v3 kernel task on MI355X (`gfx950`), for any target language + and with no task configuration. `src/eval_tools/defaults.py` defines the set: + - the new page-fault guard (correctness with the caching allocators off); + - PyTorch CSAN; + - TileLens (symbolic out-of-bounds checks of Triton and Gluon kernels); + - rocJITsu Waitcheck and the rocJITsu race detector, fed by an automatic + capture of the kernels each call dispatches; + - Triton FpSan. +- The new `gated` policy gives each tool a role: + - A `gate` blocks performance only on a definite finding that the task's + baseline, rechecked with the same tool, does not share. + - A `signal` (FpSan) never blocks. + - Unverified results (unsupported, tool error, timeout, inconclusive) are + recorded and never count as clean. +- GPU ASan supports HIP (including the torch-extension build), Triton and + Gluon. It needs a bare-metal host and stays opt-in: virtualized GPU hosts + cannot run its runtime. +- Gluon candidates are supported by FpSan, GPU ASan, TileLens, Waitcheck and + rocJITsu through the v3 path. +- The runner builds missing default sidecar images on first use, and the + Waitcheck sidecar now gets the worker's GPU for capture. +- `evaluation_tools: false` disables the stage. See + [Check kernels with evaluation tools](../how-to/use-evaluation-tools.md#default-sanitizers-for-schema-v3-tasks). + ## AgentKernelArena 0.4.0 AgentKernelArena 0.4.0 makes Arena an RL-ready environment with bounded, diff --git a/example_configs/evaluation_tools_advisory_mi355x.yaml b/example_configs/evaluation_tools_advisory_mi355x.yaml index 9a4596971..329dd6404 100644 --- a/example_configs/evaluation_tools_advisory_mi355x.yaml +++ b/example_configs/evaluation_tools_advisory_mi355x.yaml @@ -1,8 +1,11 @@ -# Experimental evaluation-tool template for MI355X (gfx950). +# Evaluation-tool template for MI355X (gfx950) with task-declared adapters. # -# This example is intentionally disabled. With host AKA_EVAL_TOOLS unset, it can -# be copied and run without building or starting any sanitizer sidecars. Before -# opting in: +# A run configuration WITHOUT an evaluation_tools section runs the default +# schema-v3 sanitizers (src/eval_tools/defaults.py); see +# docs/how-to/use-evaluation-tools.md. This example sets the section explicitly +# and disables it, so with host AKA_EVAL_TOOLS unset it can be copied and run +# without building or starting any sanitizer sidecars. Before opting in to the +# task-adapter path: # 1. build and validate the pinned sidecar images; # 2. configure task-specific argv adapters and attestations; # 3. enable only applicable tools; and @@ -29,7 +32,7 @@ workspace_directory_prefix: workspace evaluation_tools: # Replace false with a list such as [gpu_asan, rocjitsu] only after the - # selected tasks define matching adapters. `true` enables all six tools and + # selected tasks define matching adapters. `true` enables every built-in tool and # is rarely appropriate for a heterogeneous run. Host AKA_EVAL_TOOLS, when # set, authoritatively replaces this subset for both sidecar startup and plan. enabled: false diff --git a/src/eval_tools/README.md b/src/eval_tools/README.md index 4c44cf9e5..f7f2c764e 100644 --- a/src/eval_tools/README.md +++ b/src/eval_tools/README.md @@ -5,9 +5,12 @@ analysis tools. Operator configuration, the capability matrix, and the full isolation model are documented in [`docs/how-to/use-evaluation-tools.md`](../../docs/how-to/use-evaluation-tools.md). -The built-in registry currently contains Triton FpSan, ROCm GPU -AddressSanitizer, the rocJITsu race detector, rocJITsu Waitcheck, rocJITsu -ConSan, and HIP-FpSan. Waitcheck and ConSan require explicit final-code-object +The built-in registry currently contains the page-fault guard, PyTorch's CUDA +Sanitizer (CSAN), TileLens, Triton FpSan, ROCm GPU AddressSanitizer, the +rocJITsu race detector, rocJITsu Waitcheck, rocJITsu ConSan, and HIP-FpSan. +Schema-v3 tasks run the default set in `defaults.py` through framework-owned +adapters (`plugins/aka_v3.py`, `plugins/v3_lanes.py`, `plugins/v3_tools.py`, +`adapters/aka_v3_entrypoint.py`) with no task configuration. Waitcheck and ConSan require explicit final-code-object adapters and are currently qualified only for advisory use; enabling them does not automatically inspect every optimized kernel. A tool name being listed in a roadmap is not evidence that an optimized kernel was analyzed. A supported tool diff --git a/src/eval_tools/adapters/aka_v3_capsules.py b/src/eval_tools/adapters/aka_v3_capsules.py new file mode 100644 index 000000000..99baef997 --- /dev/null +++ b/src/eval_tools/adapters/aka_v3_capsules.py @@ -0,0 +1,143 @@ +"""Build rocJITsu replay capsules from a schema-v3 capture. + +The workspace runner's ``sanitize capture`` lane records each Triton/Gluon +launch of one call: the compiled kernel's HSACO and metadata, the launch grid, +every argument, and each allocation the launch can reach before and after it +ran. This module turns one launch record into a validated +:class:`~.replay_capsule.ReplayCapsule` using the same ABI lowering as the +``triton_aot`` adapter, so a replay reconstructs that exact dispatch. +""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path +from types import SimpleNamespace +from typing import Any, Mapping + +from .replay_capsule import ( + AllocationSpec, + CapsuleValidationError, + CaseSpec, + CodeObjectSpec, + ProducerSpec, + ReplayCapsule, + TargetSpec, +) +from .triton_aot import extract_triton_aot + +CAPTURE_SCHEMA = 1 +# Code object ABI version byte (ELF e_ident[EI_ABIVERSION]) -> AMDHSA version. +_ABI_TO_CODE_OBJECT = {2: 4, 3: 5, 4: 6} +_EF_AMDGPU_FEATURE_XNACK = 0x300 +_EF_AMDGPU_FEATURE_XNACK_ON = 0x300 + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def code_object_target(data: bytes) -> tuple[int, bool]: + """(AMDHSA code object version, xnack-on) from an AMDGPU ELF header.""" + + if data[:4] != b"\x7fELF": + raise CapsuleValidationError("code object is not an ELF file") + version = _ABI_TO_CODE_OBJECT.get(data[8]) + if version is None: + raise CapsuleValidationError(f"unsupported AMDHSA ABI version byte {data[8]}") + flags = int.from_bytes(data[0x30:0x34], "little") + return version, (flags & _EF_AMDGPU_FEATURE_XNACK) == _EF_AMDGPU_FEATURE_XNACK_ON + + +def load_manifest(capture_dir: Path) -> dict: + manifest = json.loads((capture_dir / "capture.json").read_text(encoding="utf-8")) + if not isinstance(manifest, dict) or manifest.get("schema_version") != CAPTURE_SCHEMA: + raise CapsuleValidationError("capture.json has an unsupported schema") + return manifest + + +def _constant_key(raw: str) -> Any: + value = json.loads(raw) + return tuple(value) if isinstance(value, list) else value + + +def build_capsule( + launch_dir: Path, + *, + manifest: Mapping[str, Any], + task_id: str, + image_digest: str, + rocm_version: str, + framework_version: str, + gpu_arch: str = "gfx950", +) -> Path: + """Write ``capsule.json`` beside one launch record and return its path.""" + + record = json.loads((launch_dir / "launch.json").read_text(encoding="utf-8")) + hsaco = launch_dir / record["hsaco"] + data = hsaco.read_bytes() + if hashlib.sha256(data).hexdigest() != record["hsaco_sha256"]: + raise CapsuleValidationError("captured HSACO hash does not match its record") + code_object_version, xnack = code_object_target(data) + pointer_bindings: dict[int, tuple[str, int]] = {} + scalar_values: dict[int, Any] = {} + for argument in record["arguments"]: + index = int(argument["index"]) + if argument["kind"] == "tensor": + pointer_bindings[index] = (str(argument["allocation"]), int(argument["byte_offset"])) + elif argument["kind"] == "value": + value = argument["value"] + scalar_values[index] = int(value) if isinstance(value, bool) else value + compiled = SimpleNamespace( + asm={"hsaco": data}, + name=record["kernel_name"], + metadata=dict(record["metadata"]), + src=SimpleNamespace( + signature=dict(record["signature"]), + constants={_constant_key(key): value for key, value in record["constants"].items()}, + fn=SimpleNamespace(arg_names=list(record["arg_names"])), + ), + ) + staging = launch_dir / "aot" + artifact = extract_triton_aot(compiled, staging, grid=record["grid"], pointer_bindings=pointer_bindings, + scalar_values=scalar_values) + if artifact.hsaco_sha256 != record["hsaco_sha256"]: + raise CapsuleValidationError("lowered HSACO differs from the captured one") + referenced = {argument.ref for argument in artifact.abi if argument.kind == "pointer"} + allocations = [] + for item in record["allocations"]: + if item["id"] not in referenced: + continue + before = launch_dir / item["before_blob"] + expected = launch_dir / item["expected_blob"] + allocations.append(AllocationSpec( + id=item["id"], byte_size=int(item["byte_size"]), before_blob=item["before_blob"], + before_sha256=_sha256(before), expected_blob=item["expected_blob"], + expected_sha256=_sha256(expected), alignment=256)) + if not allocations: + raise CapsuleValidationError("the launch reaches no captured allocation") + capsule = ReplayCapsule( + schema_version=1, + producer=ProducerSpec(adapter="triton_aot", adapter_version="1", framework_version=framework_version, + image_digest=image_digest, rocm_version=rocm_version), + target=TargetSpec(gpu_arch=gpu_arch, xnack=xnack, code_object_version=code_object_version), + case=CaseSpec(task_id=task_id, case_id=str(manifest.get("case")), seed=manifest.get("seed"), + candidate_scope=str(manifest.get("role", "candidate"))), + code_object=CodeObjectSpec(path=record["hsaco"], sha256=record["hsaco_sha256"], + kernel_name=record["kernel_name"]), + launch=artifact.launch, + abi=artifact.abi, + allocations=tuple(allocations), + scratch=artifact.scratch, + dispatch_count=1, + base_dir=launch_dir, + ) + capsule.validate() + path = launch_dir / "capsule.json" + capsule.dump(path) + ReplayCapsule.load(path, verify_files=True) + return path + + +__all__ = ["CAPTURE_SCHEMA", "build_capsule", "code_object_target", "load_manifest"] diff --git a/src/eval_tools/adapters/aka_v3_entrypoint.py b/src/eval_tools/adapters/aka_v3_entrypoint.py new file mode 100644 index 000000000..e36ec05a8 --- /dev/null +++ b/src/eval_tools/adapters/aka_v3_entrypoint.py @@ -0,0 +1,198 @@ +"""Image-owned schema-v3 entry point for Waitcheck and rocJITsu race detection. + + python -I aka_v3_entrypoint.py {waitcheck|rocjitsu} --workspace W --role R --output-dir O ... + +1. Runs the workspace runner's ``ROLE sanitize capture`` lane on the GPU, + which records the role's dispatched kernels (code objects, and for + Triton/Gluon a replay record per launch) under ``O/capture``. +2. Waitcheck: lists every kernel of each captured code object, then runs the + image-owned single-kernel bridge on each one recorded as dispatched (all of + them for a HIP extension or FlyDSL module, whose code object holds only the + role's own kernels). + rocJITsu: builds one replay capsule per recorded launch and replays it + under the race detector through the image-owned trusted replay helper. +3. Writes ``O/index.json``: one entry per analysed kernel or capsule with the + exact log the plugin parses, plus what the capture skipped. + +Like the other image-owned entry points it imports framework code only from +the tree that contains this file. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Sequence + +_ENTRYPOINT = Path(__file__).resolve(strict=True) +_FRAMEWORK_ROOT = _ENTRYPOINT.parents[3] +_ADAPTERS = _FRAMEWORK_ROOT / "src" / "eval_tools" / "adapters" +INDEX_SCHEMA = 1 + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _capture(args, output: Path) -> tuple[dict | None, str | None]: + capture_dir = output / "capture" + capture_dir.mkdir(parents=True, exist_ok=True) + cache = output / "capture-triton-cache" + cache.mkdir(parents=True, exist_ok=True) + env = {**os.environ, "PYTHONPATH": "", "PYTHONDONTWRITEBYTECODE": "1", + "AKA_SANITIZE_OUTPUT_DIR": str(capture_dir), "TRITON_CACHE_DIR": str(cache)} + completed = subprocess.run( + [args.python, "-m", "_aka_eval.evaluate", args.role, "sanitize", "capture"], + cwd=args.workspace, env=env, capture_output=True, text=True, timeout=args.capture_timeout, check=False) + (output / "capture.stdout.log").write_text(completed.stdout, encoding="utf-8") + (output / "capture.stderr.log").write_text(completed.stderr, encoding="utf-8") + report = None + for line in completed.stdout.splitlines(): + if line.startswith("ARENA_EVAL_RESULT="): + report = json.loads(line[len("ARENA_EVAL_RESULT="):]) + if completed.returncode != 0 or not report or report.get("status") != "PASS": + reason = (report or {}).get("reason") or completed.stderr[-2000:] or f"rc={completed.returncode}" + return None, f"capture failed: {reason}" + from src.eval_tools.adapters.aka_v3_capsules import load_manifest + + return load_manifest(capture_dir), None + + +def _inventory(waitcheck: Path, code_object: Path, target: str) -> list[dict]: + completed = subprocess.run([str(waitcheck), str(code_object), "--target", target, "--list-kernels"], + capture_output=True, text=True, check=False, timeout=300) + if completed.returncode != 0: + raise RuntimeError(completed.stderr.strip() or completed.stdout.strip() or "inventory failed") + records = [] + for line in completed.stdout.splitlines(): + value = json.loads(line) + if isinstance(value, dict) and "kernel_name" in value: + records.append(value) + return records + + +def _waitcheck(args, output: Path, manifest: dict) -> list[dict]: + capture_dir = output / "capture" + entries = [] + for number, item in enumerate(manifest.get("code_objects", [])): + code_object = (capture_dir / item["code_object"]).resolve(strict=True) + if not code_object.is_relative_to(capture_dir.resolve()) or _sha256(code_object) != item["sha256"]: + entries.append({"code_object": item["code_object"], "error": "captured code object changed"}) + continue + try: + inventory = _inventory(args.waitcheck, code_object, args.target) + except (OSError, RuntimeError, ValueError, subprocess.TimeoutExpired) as error: + entries.append({"code_object": item["code_object"], "error": f"inventory: {error}"}) + continue + wanted = item.get("kernels") + selected = inventory if wanted is None else [r for r in inventory if r.get("kernel_name") in wanted] + if wanted is not None and {r.get("kernel_name") for r in selected} != set(wanted): + entries.append({"code_object": item["code_object"], "error": f"dispatched kernels {wanted} are not " + "all in the code object's inventory"}) + for record in selected: + log = output / "kernels" / f"{number:02d}-{len(entries):03d}.log" + log.parent.mkdir(parents=True, exist_ok=True) + completed = subprocess.run( + [args.python, "-I", str(_ADAPTERS / "waitcheck_entrypoint.py"), "--waitcheck", str(args.waitcheck), + "--capi-wrapper", str(args.capi_wrapper), "--code-object", str(code_object), + "--expected-sha256", item["sha256"], "--target", args.target, + "--expected-kernel", str(record["kernel_name"]), "--kernel-entry", str(record["kernel_entry"])], + capture_output=True, text=True, check=False, timeout=args.kernel_timeout) + log.write_text(completed.stdout + ("\n" + completed.stderr if completed.stderr else ""), encoding="utf-8") + entries.append({"code_object": item["code_object"], "code_object_sha256": item["sha256"], + "kernel_name": record["kernel_name"], "kernel_entry": record["kernel_entry"], + "returncode": completed.returncode, "log": log.relative_to(output).as_posix()}) + return entries + + +def _task_id(args) -> str: + if args.task_id: + return args.task_id + try: + return str(json.loads((args.workspace / "_aka_eval" / "contract.json").read_text())["task_id"]) + except (OSError, ValueError, KeyError, TypeError): + return args.workspace.name or "unknown" + + +def _rocjitsu(args, output: Path, manifest: dict) -> list[dict]: + from src.eval_tools.adapters.aka_v3_capsules import build_capsule + + task_id = _task_id(args) + capture_dir = output / "capture" + entries = [] + for launch in manifest.get("launches", []): + launch_dir = (capture_dir / launch["directory"]).resolve(strict=True) + entry = {"directory": launch["directory"], "kernel_name": launch["kernel_name"]} + try: + capsule = build_capsule(launch_dir, manifest=manifest, task_id=task_id, + image_digest=os.environ.get("AKA_EVAL_TOOL_RUNTIME_REF") or "unrecorded", + rocm_version=args.rocm_version, framework_version=args.framework_version) + except Exception as error: # an unbuildable capsule is that launch's unverified result + entries.append({**entry, "error": f"capsule: {type(error).__name__}: {error}"[:2000]}) + continue + replay_dir = output / "replay" / launch["directory"] + report_dir = replay_dir / "rocjitsu-report" + report_dir.mkdir(parents=True, exist_ok=True) + env = {**os.environ, "RJ_RACE": "1", "RJ_LOG": "1", "RJ_SINKS": "stderr,file", "RJ_SINK_DIR": str(report_dir)} + completed = subprocess.run( + [args.python, "-I", str(_ADAPTERS / "rocjitsu_replay_entrypoint.py"), "--capsule", str(capsule), + "--output-dir", str(replay_dir / "launcher"), "--rocjitsu", str(args.rocjitsu), "--config", + str(args.config), "--hipcc", args.hipcc, "--expected-adapter", "triton_aot", "--expected-arch", + args.target, "--expected-kernel", launch["kernel_name"], "--expected-capsule-sha256", + _sha256(capsule)], + capture_output=True, text=True, env=env, check=False, timeout=args.kernel_timeout) + log = replay_dir / "replay.log" + log.write_text(completed.stdout + "\n" + completed.stderr, encoding="utf-8") + race_log = report_dir / "race.log" + entries.append({**entry, "capsule": capsule.relative_to(output).as_posix(), "capsule_sha256": _sha256(capsule), + "returncode": completed.returncode, "log": log.relative_to(output).as_posix(), + "race_log": race_log.relative_to(output).as_posix() if race_log.is_file() else None}) + return entries + + +def main(argv: Sequence[str] | None = None) -> int: + sys.path.insert(0, str(_FRAMEWORK_ROOT)) + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("tool", choices=("waitcheck", "rocjitsu")) + parser.add_argument("--workspace", required=True, type=Path) + parser.add_argument("--role", required=True, choices=("candidate", "baseline")) + parser.add_argument("--output-dir", required=True, type=Path) + parser.add_argument("--python", default="/opt/venv/bin/python") + parser.add_argument("--target", default="gfx950") + parser.add_argument("--task-id", default="") + parser.add_argument("--capture-timeout", type=float, default=900) + parser.add_argument("--kernel-timeout", type=float, default=900) + parser.add_argument("--waitcheck", type=Path) + parser.add_argument("--capi-wrapper", type=Path) + parser.add_argument("--rocjitsu", type=Path) + parser.add_argument("--config", type=Path) + parser.add_argument("--hipcc", default="/opt/rocm/bin/hipcc") + parser.add_argument("--rocm-version", default="10.0.0") + parser.add_argument("--framework-version", default="unknown") + args = parser.parse_args(argv) + output = args.output_dir + output.mkdir(parents=True, exist_ok=True) + index = {"schema_version": INDEX_SCHEMA, "tool": args.tool, "role": args.role, "entries": [], "skipped": []} + try: + manifest, error = _capture(args, output) + except (OSError, ValueError, subprocess.TimeoutExpired) as exc: + manifest, error = None, f"capture failed: {type(exc).__name__}: {exc}" + if manifest is None: + index["error"] = error + else: + index["language"] = manifest.get("language") + index["skipped"] = list(manifest.get("skipped") or []) + index["entries"] = _waitcheck(args, output, manifest) if args.tool == "waitcheck" else \ + _rocjitsu(args, output, manifest) + (output / "index.json").write_text(json.dumps(index, indent=2, sort_keys=True), encoding="utf-8") + print("AKA_V3_INDEX " + json.dumps({"entries": len(index["entries"]), "error": index.get("error")}), flush=True) + return 0 if manifest is not None else 3 + + +if __name__ == "__main__": # pragma: no cover - exercised by sidecar tests. + raise SystemExit(main()) diff --git a/src/eval_tools/config.py b/src/eval_tools/config.py index ec8d9e4ed..16c5a3a14 100644 --- a/src/eval_tools/config.py +++ b/src/eval_tools/config.py @@ -15,16 +15,19 @@ TaskProfile, ToolName, ToolPlan, + ToolRole, ) +from .defaults import DEFAULT_POLICY, DEFAULT_TIMEOUT_S, default_role -PLAN_SCHEMA_VERSION = 2 +# Version 3 added the per-tool role and the ``gated`` policy. +PLAN_SCHEMA_VERSION = 3 MAX_TOOL_TIMEOUT_SECONDS = 3600 _RUN_SECTION_KEYS = frozenset( {"enabled", "policy", "runtime_profile", "positive_control", "timeout_s", "tools"} ) _TOOL_CONFIG_KEYS = frozenset( - {"runtime_ref", "image_digest", "timeout_s", "options"} + {"runtime_ref", "image_digest", "timeout_s", "options", "role"} ) # These values are discovered and attested by the selected sidecar image. They @@ -90,6 +93,10 @@ def _timeout(value: Any, *, field: str, maximum: int = MAX_TOOL_TIMEOUT_SECONDS) "rocjitsu": frozenset({"command", "launcher", "capsule", "race_report", "expected_kernel"}), "rocjitsu_waitcheck": frozenset({"code_object", "expected_kernel", "kernel_entry"}), "rocjitsu_consan": frozenset({"code_object", "command", "oracle_command"}), + # Schema-v3 lanes take no task adapter: the framework builds their argv. + "page_fault_guard": frozenset(), + "csan": frozenset(), + "tilelens": frozenset({"num_sms"}), } _ARGV_OPTIONS = frozenset({"command", "comparison_command", "launcher", "oracle_command"}) @@ -129,17 +136,27 @@ def _canonical(value: Any) -> Any: return {str(key): _canonical(value[key]) for key in sorted(value, key=str)} if isinstance(value, (tuple, list)): return [_canonical(item) for item in value] - if isinstance(value, EvaluationPolicy): + if isinstance(value, (EvaluationPolicy, ToolRole)): return value.value return value +def _role(value: Any, *, tool: str) -> ToolRole: + if value is None: + return ToolRole(default_role(tool)) + try: + return ToolRole(str(value).strip().lower()) + except ValueError as error: + raise ValueError(f"evaluation_tools.tools.{tool}.role must be gate or signal") from error + + @dataclass(frozen=True) class ToolConfig: name: str runtime_ref: str | None = None timeout_s: int = 3600 options: Mapping[str, Any] = field(default_factory=dict) + role: ToolRole | str | None = None def __post_init__(self) -> None: object.__setattr__(self, "name", _tool_name(self.name)) @@ -149,6 +166,7 @@ def __post_init__(self) -> None: _timeout(self.timeout_s, field=f"timeout_s for {self.name}"), ) object.__setattr__(self, "options", dict(self.options or {})) + object.__setattr__(self, "role", _role(self.role, tool=self.name)) def to_dict(self) -> dict[str, Any]: return { @@ -156,6 +174,7 @@ def to_dict(self) -> dict[str, Any]: "runtime_ref": self.runtime_ref, "timeout_s": self.timeout_s, "options": _canonical(self.options), + "role": self.role.value, } @@ -198,10 +217,14 @@ def from_mapping(cls, config: Mapping[str, Any] | None) -> "EvalToolsConfig": elif not config or _RUN_SECTION_KEYS.intersection(str(key) for key in config): section = config else: - # A full run configuration with no evaluation_tools section keeps - # this optional stage disabled. Unknown fields are rejected once a - # section is explicitly present, where typos can weaken policy. - return cls.disabled() + # A full run configuration with no evaluation_tools section runs + # the default sanitizers that the host runner started (and + # published in AKA_EVAL_TOOLS_SELECTED); without that runner the + # stage stays off. Unknown fields are rejected once a section is + # explicitly present, where typos can weaken policy. + if not os.environ.get("AKA_EVAL_TOOLS_SELECTED", "").strip(): + return cls.disabled() + section = {"policy": DEFAULT_POLICY, "timeout_s": DEFAULT_TIMEOUT_S} if section in (None, False): return cls.disabled() if not isinstance(section, Mapping): @@ -278,6 +301,7 @@ def from_mapping(cls, config: Mapping[str, Any] | None) -> "EvalToolsConfig": and raw_item["runtime_ref"] != raw_item["image_digest"] ): raise ValueError(f"evaluation_tools.tools.{name} has conflicting runtime identities") + _role(raw_item.get("role"), tool=name) canonical_tool_config[name] = raw_item default_timeout = _timeout( section.get("timeout_s", MAX_TOOL_TIMEOUT_SECONDS), @@ -344,6 +368,7 @@ def from_mapping(cls, config: Mapping[str, Any] | None) -> "EvalToolsConfig": maximum=default_timeout, ), options=merged_options, + role=item.get("role"), ) ) @@ -412,6 +437,7 @@ def build_evaluation_plan( plugin_version=str(plugin_versions[item.name]), timeout_s=item.timeout_s, options=item.options, + role=item.role, ) for item in config.tools ) @@ -488,6 +514,7 @@ def merge_task_tool_config( runtime_ref=base.runtime_ref, timeout_s=timeout, options={**dict(base.options), **dict(override.get("options", {}))}, + role=base.role, ) ) return EvalToolsConfig( diff --git a/src/eval_tools/contracts.py b/src/eval_tools/contracts.py index da987f621..471c012f3 100644 --- a/src/eval_tools/contracts.py +++ b/src/eval_tools/contracts.py @@ -29,6 +29,9 @@ class ToolName(_StringEnum): ROCJITSU_WAITCHECK = "rocjitsu_waitcheck" ROCJITSU_CONSAN = "rocjitsu_consan" HIP_FPSAN = "hip_fpsan" + PAGE_FAULT_GUARD = "page_fault_guard" + CSAN = "csan" + TILELENS = "tilelens" class KernelLanguage(_StringEnum): @@ -84,6 +87,14 @@ class FindingSeverity(_StringEnum): class EvaluationPolicy(_StringEnum): ADVISORY = "advisory" REQUIRED = "required" + # Per-tool roles decide: a ``gate`` tool blocks performance only on a + # definite finding the baseline does not share; a ``signal`` never blocks. + GATED = "gated" + + +class ToolRole(_StringEnum): + GATE = "gate" + SIGNAL = "signal" def _tool_value(value: str | ToolName) -> str: @@ -647,6 +658,7 @@ class ToolPlan: plugin_version: str = "unknown" timeout_s: int = 3600 options: Mapping[str, Any] = field(default_factory=dict) + role: ToolRole = ToolRole.GATE def __post_init__(self) -> None: object.__setattr__(self, "tool", _tool_value(self.tool)) @@ -654,6 +666,7 @@ def __post_init__(self) -> None: raise ValueError("tool timeout_s must be positive") object.__setattr__(self, "timeout_s", int(self.timeout_s)) object.__setattr__(self, "options", dict(self.options or {})) + object.__setattr__(self, "role", _enum_value(ToolRole, self.role)) def to_dict(self) -> dict[str, Any]: return { @@ -662,6 +675,7 @@ def to_dict(self) -> dict[str, Any]: "plugin_version": self.plugin_version, "timeout_s": self.timeout_s, "options": _plain(self.options), + "role": self.role.value, } @@ -700,10 +714,13 @@ class PolicyDecision: allowed: bool policy_satisfied: bool reasons: tuple[str, ...] = () + # Under the gated policy: the gate findings that stopped performance. + blocking: tuple[str, ...] = () def __post_init__(self) -> None: object.__setattr__(self, "policy", _enum_value(EvaluationPolicy, self.policy)) object.__setattr__(self, "reasons", _string_tuple(self.reasons)) + object.__setattr__(self, "blocking", _string_tuple(self.blocking)) def to_dict(self) -> dict[str, Any]: return { @@ -711,6 +728,7 @@ def to_dict(self) -> dict[str, Any]: "allowed": self.allowed, "policy_satisfied": self.policy_satisfied, "reasons": list(self.reasons), + "blocking": list(self.blocking), } @@ -827,6 +845,7 @@ def parse(self, context: ToolContext, execution: ExecutionRecord) -> ToolRunResu "ToolName", "ToolPlan", "ToolPlugin", + "ToolRole", "ToolRunResult", "effective_capability", ] diff --git a/src/eval_tools/defaults.py b/src/eval_tools/defaults.py new file mode 100644 index 000000000..9ddfc702e --- /dev/null +++ b/src/eval_tools/defaults.py @@ -0,0 +1,91 @@ +"""Default evaluation-tool selection: the single source of truth. + +A run configuration without an ``evaluation_tools`` section runs the default +sanitizers. The Docker runner starts ``DEFAULT_ENABLED`` on a default +architecture and publishes the started set as ``AKA_EVAL_TOOLS_SELECTED``; +the scoring process then plans that set under ``DEFAULT_POLICY`` with each +tool's default role. ``evaluation_tools: false`` (or ``enabled: []``) turns +the stage off, and an explicit section keeps full control. + +GPU AddressSanitizer is supported but not a default: its runtime needs XNACK +host-memory access, which virtualized GPU hosts do not provide. Enable it on +bare-metal hosts with ``enabled: [..., gpu_asan]``. + +This module has no package imports so the host-side runner can execute it as +a script before any container starts:: + + python3 src/eval_tools/defaults.py select CONFIG.yaml GPU_ARCH +""" + +from __future__ import annotations + +import sys + +# Every built-in tool, in the order the runner starts them. +ALL_TOOLS = ( + "triton_fpsan", + "gpu_asan", + "rocjitsu", + "rocjitsu_waitcheck", + "rocjitsu_consan", + "hip_fpsan", + "page_fault_guard", + "csan", + "tilelens", +) +DEFAULT_ENABLED = ( + "page_fault_guard", + "csan", + "tilelens", + "triton_fpsan", + "rocjitsu_waitcheck", + "rocjitsu", +) +# Semantic comparisons report a changed floating-point expression, which a +# correct rewrite (another reduction order or precision) also produces. +SIGNAL_TOOLS = frozenset({"triton_fpsan", "hip_fpsan"}) +DEFAULT_POLICY = "gated" +# Per-tool deadline on the default path; a timeout is recorded as unverified. +DEFAULT_TIMEOUT_S = 1200 +DEFAULT_ARCHITECTURES = frozenset({"gfx950"}) + + +def default_role(tool: str) -> str: + return "signal" if tool in SIGNAL_TOOLS else "gate" + + +def runner_selection(config: object, gpu_arch: str) -> tuple[str, ...]: + """The tools the runner starts for a parsed run configuration.""" + if not isinstance(config, dict) or "evaluation_tools" not in config: + return DEFAULT_ENABLED if gpu_arch in DEFAULT_ARCHITECTURES else () + section = config["evaluation_tools"] + if section in (None, False): + return () + if not isinstance(section, dict): + raise ValueError("evaluation_tools must be a mapping or false") + enabled = section.get("enabled", ()) + if enabled is True: + return ALL_TOOLS + if enabled in (None, False): + return () + if isinstance(enabled, str): + return (enabled,) + if not isinstance(enabled, (list, tuple)): + raise ValueError("evaluation_tools.enabled must be a list of tool names") + return tuple(str(item) for item in enabled) + + +def main(argv: list[str]) -> int: + if len(argv) != 3 or argv[0] != "select": + print("usage: defaults.py select CONFIG.yaml GPU_ARCH", file=sys.stderr) + return 2 + import yaml + + with open(argv[1], encoding="utf-8") as stream: + config = yaml.safe_load(stream) or {} + print(" ".join(runner_selection(config, argv[2]))) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/src/eval_tools/manager.py b/src/eval_tools/manager.py index faf0fa6df..2f811d3a8 100644 --- a/src/eval_tools/manager.py +++ b/src/eval_tools/manager.py @@ -27,20 +27,43 @@ ToolContext, ToolEvaluation, ToolInvocation, + ToolRole, ToolRunResult, ) from .registry import ToolRegistry from .task_profile import resolve_task_profile +BASELINE_ALSO_FOUND = "baseline_also_found" + + def evaluate_policy( policy: EvaluationPolicy, evaluations: tuple[ToolEvaluation, ...], + roles: Mapping[str, ToolRole] | None = None, ) -> PolicyDecision: - """Resolve whether performance may proceed under advisory/required policy.""" + """Resolve whether performance may proceed. + + ``advisory`` never blocks and ``required`` blocks on anything but a + completed clean result. ``gated`` blocks only on a ``gate`` tool's + definite finding that the task's own baseline does not share; an + unverified gate (unsupported path, tool error, timeout, inconclusive + output) and every ``signal`` tool are recorded without blocking. + """ reasons: list[str] = [] + blocking: list[str] = [] for evaluation in evaluations: + result = evaluation.result + if ( + policy == EvaluationPolicy.GATED + and (roles or {}).get(evaluation.capability.tool, ToolRole.GATE) == ToolRole.GATE + and evaluation.capability.ready + and result is not None + and result.finding == FindingStatus.FOUND + and not result.metadata.get(BASELINE_ALSO_FOUND) + ): + blocking.append(f"{evaluation.capability.tool}:finding:found") capability = evaluation.capability assert capability.effective is not None if capability.effective.state == CapabilityState.NOT_APPLICABLE: @@ -60,12 +83,18 @@ def evaluate_policy( reasons.append(f"{capability.tool}:finding:{result.finding.value}") satisfied = not reasons - allowed = True if policy == EvaluationPolicy.ADVISORY else satisfied + if policy == EvaluationPolicy.ADVISORY: + allowed = True + elif policy == EvaluationPolicy.GATED: + allowed = not blocking + else: + allowed = satisfied return PolicyDecision( policy=policy, allowed=allowed, policy_satisfied=satisfied, reasons=tuple(reasons), + blocking=tuple(blocking), ) @@ -439,16 +468,74 @@ def evaluate( f"failed to parse tool output: {exc}", execution_record=execution, ) + if ( + plan.policy == EvaluationPolicy.GATED + and tool_plan.role == ToolRole.GATE + and result.finding == FindingStatus.FOUND + and getattr(plugin, "baseline_check", False) + ): + result = self._baseline_check(plugin, tool_plan, context, root, plan.fingerprint, result) evaluations.append(ToolEvaluation(capability=capability, result=result)) frozen_evaluations = tuple(evaluations) - decision = evaluate_policy(plan.policy, frozen_evaluations) + decision = evaluate_policy( + plan.policy, + frozen_evaluations, + {item.tool: item.role for item in plan.tools}, + ) return EvaluationReport( plan=plan, evaluations=frozen_evaluations, decision=decision, ) + def _baseline_check( + self, + plugin: Any, + tool_plan: Any, + context: ToolContext, + root: Path, + fingerprint: str, + result: ToolRunResult, + ) -> ToolRunResult: + """Rerun a gate tool on the task's baseline after a candidate finding. + + A finding the baseline shares is a property of the task (its reference + implementation does the same), so it is recorded but does not block + the candidate. The baseline run is otherwise identical: same tool, + runtime, options and timeout, in a fresh artifact directory. + """ + + artifact_dir = root / tool_plan.tool / fingerprint / f"baseline-{uuid.uuid4().hex}" + artifact_dir.mkdir(parents=True, exist_ok=False) + baseline_context = replace( + context, + artifact_dir=str(artifact_dir), + options={**dict(context.options), "aka_role": "baseline"}, + ) + try: + invocation = replace( + plugin.build_invocation(baseline_context), + timeout_s=tool_plan.timeout_s, + artifact_dir=str(artifact_dir), + ) + execution = self.runtime_client.execute(invocation, baseline_context) + baseline = plugin.parse(baseline_context, execution) + check = { + "execution": baseline.execution.value, + "finding": baseline.finding.value, + "findings_count": baseline.findings_count, + "summary": baseline.summary, + "artifact_dir": str(artifact_dir), + } + except Exception as exc: # an unrunnable baseline check leaves the finding blocking + baseline = None + check = {"execution": "tool_error", "error": f"{type(exc).__name__}: {exc}"[:2000]} + metadata = {**dict(result.metadata), "baseline_check": check} + if baseline is not None and baseline.finding == FindingStatus.FOUND: + metadata[BASELINE_ALSO_FOUND] = True + return replace(result, metadata=metadata) + # ``execute`` reads naturally at evaluator integration sites and remains an # alias rather than a second orchestration implementation. execute = evaluate @@ -457,4 +544,4 @@ def evaluate( ToolManager = EvalToolManager -__all__ = ["EvalToolManager", "ToolManager", "evaluate_policy"] +__all__ = ["BASELINE_ALSO_FOUND", "EvalToolManager", "ToolManager", "evaluate_policy"] diff --git a/src/eval_tools/plugins/aka_v3.py b/src/eval_tools/plugins/aka_v3.py new file mode 100644 index 000000000..931bd10a3 --- /dev/null +++ b/src/eval_tools/plugins/aka_v3.py @@ -0,0 +1,138 @@ +"""Framework-owned adapters for schema-v3 kernel tasks. + +A schema-v3 ``task.yaml`` declares no evaluation-tool adapters. The framework +does not need any: every v3 workspace carries the generated runner +(``_aka_eval``), whose ``sanitize LANE`` action runs the role's implementation +on the task's own correctness cases under one lane's environment. A plugin on +this path only chooses the lane, sets the lane's environment, and judges the +process it ran. ``aka_role`` (``candidate`` by default) lets the manager rerun +a gate on the baseline after a candidate finding. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Any, Mapping, Optional + +from ..contracts import KernelLanguage, ToolContext, ToolInvocation +from ..task_declarations import is_v3_task + +SIDECAR_PYTHON = "/opt/venv/bin/python" +ADAPTER = "aka_v3" +REPORT_PREFIX = "ARENA_EVAL_RESULT=" +ROLES = ("candidate", "baseline") +V3_LANGUAGES = frozenset({"triton", "gluon", "hip", "flydsl"}) +NO_CACHING = { + "PYTORCH_NO_HIP_MEMORY_CACHING": "1", + "AMD_PYTORCH_NO_CUDA_MEMORY_CACHING": "1", + "HSA_DISABLE_FRAGMENT_ALLOCATOR": "1", +} +# Signatures of a device memory fault surfacing through ROCr, HIP or PyTorch. +FAULT_RE = re.compile( + r"Memory access fault by GPU|HSA_STATUS_ERROR_MEMORY_FAULT|Memory Fault Error|" + r"illegal memory access|hipErrorIllegalAddress", + re.I, +) + + +def is_v3(context: ToolContext) -> bool: + return is_v3_task(context.task_config) + + +def role(context: ToolContext) -> str: + value = str(context.options.get("aka_role", "candidate")) + if value not in ROLES: + raise ValueError(f"aka_role must be one of {ROLES}, not {value!r}") + return value + + +def _contract(context: ToolContext) -> Mapping[str, Any]: + return context.task_config.get("contract") or {} + + +def target_language(context: ToolContext) -> str: + return str(_contract(context).get("target_language") or context.profile.language.value) + + +def baseline_language(context: ToolContext) -> str: + return str(_contract(context).get("baseline_language") or "") + + +def role_language(context: ToolContext) -> str: + return baseline_language(context) if role(context) == "baseline" else target_language(context) + + +def language_enum(value: str) -> KernelLanguage: + return {item.value: item for item in KernelLanguage}.get(value, KernelLanguage.UNKNOWN) + + +def lane_invocation( + tool: str, + context: ToolContext, + lane: str, + *, + env: Mapping[str, str] | None = None, + timeout_s: int = 1800, + metadata: Mapping[str, Any] | None = None, +) -> ToolInvocation: + """Run ``python -m _aka_eval.evaluate ROLE sanitize LANE`` in the workspace.""" + + command = (SIDECAR_PYTHON, "-m", "_aka_eval.evaluate", role(context), "sanitize", lane) + environment = { + **dict(context.env), + # The lane process imports only the workspace runner and the candidate; + # the sidecar's own framework tree stays off its import path. + "PYTHONPATH": "", + "PYTHONDONTWRITEBYTECODE": "1", + "AKA_EVAL_TOOL": tool, + **dict(env or {}), + } + return ToolInvocation( + tool=tool, + command=command, + cwd=context.workspace, + env=environment, + timeout_s=timeout_s, + artifact_dir=context.artifact_dir, + metadata={"adapter": ADAPTER, "lane": lane, "role": role(context), **dict(metadata or {})}, + ) + + +def lane_report(stdout: str, *, lane: str) -> tuple[Optional[dict], Optional[str]]: + """The lane's single ``ARENA_EVAL_RESULT`` report, or why it is unusable. + + The report must be the last line: the runner prints it after the role's + code has run, so output the role prints cannot follow it. + """ + + lines = [line for line in stdout.splitlines() if line.strip()] + reports = [line for line in lines if line.startswith(REPORT_PREFIX)] + if not reports: + return None, "lane_report_missing" + if len(reports) > 1 or lines[-1] != reports[0]: + return None, "lane_report_ambiguous" + try: + report = json.loads(reports[0][len(REPORT_PREFIX):]) + except json.JSONDecodeError: + return None, "lane_report_invalid_json" + if not isinstance(report, dict) or report.get("action") != "sanitize": + return None, "lane_report_wrong_action" + if (report.get("metadata") or {}).get("lane") != lane and report.get("status") == "PASS": + return None, "lane_report_wrong_lane" + return report, None + + +def fault_excerpt(text: str) -> Optional[str]: + match = FAULT_RE.search(text) + if not match: + return None + start = max(0, match.start() - 400) + return text[start:match.end() + 800] + + +def artifact_subdir(context: ToolContext, name: str) -> Path: + path = Path(context.artifact_dir) / name + path.mkdir(parents=True, exist_ok=True) + return path diff --git a/src/eval_tools/plugins/gpu_asan.py b/src/eval_tools/plugins/gpu_asan.py index a71c750d2..6ac072bec 100644 --- a/src/eval_tools/plugins/gpu_asan.py +++ b/src/eval_tools/plugins/gpu_asan.py @@ -55,11 +55,33 @@ def hip_asan_build_flags(target_arch: str) -> tuple[str, ...]: return ("-fsanitize=address", "-shared-libsan", f"--offload-arch={arch}:xnack+") +from . import aka_v3, v3_tools + class GpuAsanPlugin: name = ToolName.GPU_ASAN.value version = "2" + baseline_check = True def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: + if not aka_v3.is_v3(context): + return self._legacy_assess(context, runtime) + engine = v3_tools.asan_engine(context) + if engine.state != CapabilityState.READY: + return ToolCapability(self.name, engine, ready_check(adapter=aka_v3.ADAPTER), runtime) + adapted = v3_tools._with_command(v3_tools._triton_profile(context), "command", "gpu_asan") + return self._legacy_assess(adapted, runtime) + + def build_invocation(self, context: ToolContext) -> ToolInvocation: + if aka_v3.is_v3(context): + return v3_tools.asan_invocation(self, context) + return self._legacy_build_invocation(context) + + def parse(self, context: ToolContext, execution) -> ToolRunResult: + if aka_v3.is_v3(context): + return v3_tools.asan_parse(self, context, execution) + return self._legacy_parse(context, execution) + + def _legacy_assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: profile = context.profile is_triton = profile.language == KernelLanguage.TRITON or profile.framework == "triton" is_hip = profile.language == KernelLanguage.HIP @@ -137,7 +159,7 @@ def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapabili ) return ToolCapability(self.name, engine, adapter, runtime) - def build_invocation(self, context: ToolContext) -> ToolInvocation: + def _legacy_build_invocation(self, context: ToolContext) -> ToolInvocation: command = command_from_context(context, "command") profile = context.profile is_triton = profile.language == KernelLanguage.TRITON or profile.framework == "triton" @@ -201,7 +223,7 @@ def build_invocation(self, context: ToolContext) -> ToolInvocation: }, ) - def parse(self, context: ToolContext, execution) -> ToolRunResult: + def _legacy_parse(self, context: ToolContext, execution) -> ToolRunResult: profile = context.profile is_triton = profile.language == KernelLanguage.TRITON or profile.framework == "triton" attestation_path = artifact_path( diff --git a/src/eval_tools/plugins/registry.py b/src/eval_tools/plugins/registry.py index 122612799..2c8d701a4 100644 --- a/src/eval_tools/plugins/registry.py +++ b/src/eval_tools/plugins/registry.py @@ -9,6 +9,7 @@ from .consan import ConSanPlugin from .rocjitsu import RocJitsuPlugin from .triton_fpsan import TritonFpSanPlugin +from .v3_lanes import CsanPlugin, PageFaultGuardPlugin, TileLensPlugin from .waitcheck import WaitcheckPlugin @@ -21,6 +22,9 @@ WaitcheckPlugin(), ConSanPlugin(), HipFpSanPlugin(), + PageFaultGuardPlugin(), + CsanPlugin(), + TileLensPlugin(), ) } diff --git a/src/eval_tools/plugins/rocjitsu.py b/src/eval_tools/plugins/rocjitsu.py index fafb76cd3..de8b58d3a 100644 --- a/src/eval_tools/plugins/rocjitsu.py +++ b/src/eval_tools/plugins/rocjitsu.py @@ -109,11 +109,29 @@ def _race_report_path(context: ToolContext) -> Path: ) +from . import aka_v3, v3_tools + class RocJitsuPlugin: name = ToolName.ROCJITSU.value version = "3" + baseline_check = True def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: + if aka_v3.is_v3(context): + return v3_tools.capability(self, context, runtime, v3_tools.rocjitsu_engine(context)) + return self._legacy_assess(context, runtime) + + def build_invocation(self, context: ToolContext) -> ToolInvocation: + if aka_v3.is_v3(context): + return v3_tools.rocjitsu_invocation(self, context) + return self._legacy_build_invocation(context) + + def parse(self, context: ToolContext, execution) -> ToolRunResult: + if aka_v3.is_v3(context): + return v3_tools.rocjitsu_parse(self, context, execution) + return self._legacy_parse(context, execution) + + def _legacy_assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: profile = context.profile unsupported = unsupported_language_check(profile.language, "rocjitsu") if unsupported is not None: @@ -187,7 +205,7 @@ def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapabili ) return ToolCapability(self.name, engine, adapter, runtime) - def build_invocation(self, context: ToolContext) -> ToolInvocation: + def _legacy_build_invocation(self, context: ToolContext) -> ToolInvocation: binary = sidecar_path(context, "rocjitsu_binary", required=True) config = sidecar_path(context, "config_path", required=True) assert binary is not None and config is not None @@ -261,7 +279,7 @@ def build_invocation(self, context: ToolContext) -> ToolInvocation: metadata=metadata, ) - def parse(self, context: ToolContext, execution) -> ToolRunResult: + def _legacy_parse(self, context: ToolContext, execution) -> ToolRunResult: aot_adapter = _expected_aot_adapter(context) report_path = _race_report_path(context) report = report_path.read_text(encoding="utf-8", errors="replace") if report_path.is_file() else "" diff --git a/src/eval_tools/plugins/triton_fpsan.py b/src/eval_tools/plugins/triton_fpsan.py index 05aad351d..fda80cc55 100644 --- a/src/eval_tools/plugins/triton_fpsan.py +++ b/src/eval_tools/plugins/triton_fpsan.py @@ -27,11 +27,32 @@ from .parsers import parse_fpsan_comparison +from . import aka_v3, v3_tools + class TritonFpSanPlugin: name = ToolName.TRITON_FPSAN.value version = "2" + # A signal: never a blocking gate, so no baseline rerun. + baseline_check = False def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: + if not aka_v3.is_v3(context): + return self._legacy_assess(context, runtime) + adapted = v3_tools._with_command(v3_tools._triton_profile(context), "comparison_command", "fpsan") + legacy = self._legacy_assess(adapted, runtime) + engine = v3_tools.fpsan_engine(context) + return ToolCapability(self.name, legacy.engine if engine.state == CapabilityState.READY else engine, + legacy.adapter, legacy.runtime) + + def build_invocation(self, context: ToolContext) -> ToolInvocation: + if aka_v3.is_v3(context): + return v3_tools.fpsan_invocation(self, context) + return self._legacy_build_invocation(context) + + def parse(self, context: ToolContext, execution) -> ToolRunResult: + return self._legacy_parse(context, execution) + + def _legacy_assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: profile = context.profile unsupported = unsupported_language_check(profile.language, "triton_fpsan") if unsupported is not None: @@ -76,7 +97,7 @@ def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapabili ) return ToolCapability(self.name, engine, adapter, runtime) - def build_invocation(self, context: ToolContext) -> ToolInvocation: + def _legacy_build_invocation(self, context: ToolContext) -> ToolInvocation: command = command_from_context(context, "comparison_command", "command") artifact_dir = Path(context.artifact_dir) cache_dir = artifact_dir / "triton-fpsan-cache" @@ -103,7 +124,7 @@ def build_invocation(self, context: ToolContext) -> ToolInvocation: metadata={"attestation_path": str(attestation_path)}, ) - def parse(self, context: ToolContext, execution) -> ToolRunResult: + def _legacy_parse(self, context: ToolContext, execution) -> ToolRunResult: attestation_path = artifact_path( context, "attestation_path", "build_attestation.json" ) diff --git a/src/eval_tools/plugins/v3_lanes.py b/src/eval_tools/plugins/v3_lanes.py new file mode 100644 index 000000000..f2c8a8984 --- /dev/null +++ b/src/eval_tools/plugins/v3_lanes.py @@ -0,0 +1,233 @@ +"""Sanitizer lanes that exist only for schema-v3 tasks. + +``page_fault_guard``, ``csan`` and ``tilelens`` run the generated workspace +runner's ``sanitize`` action (see ``src/tools/arena_eval/sanitize.py``) in +their own sidecar. Each judges the lane process from its exit status, stderr +and single report together; a clean verdict needs a completed report whose +environment evidence matches what this plugin set. +""" + +from __future__ import annotations + +from pathlib import Path + +from ..contracts import ( + CapabilityCheck, + CapabilityState, + ToolCapability, + ToolContext, + ToolInvocation, + ToolName, + ToolRunResult, +) +from . import aka_v3 +from .base import ( + FINDING, + INCONCLUSIVE, + PASS, + TOOL_ERROR, + FindingRecord, + ParseResult, + blocked_check, + parsed_to_run_result, + ready_check, +) + + +def _v3_engine(context: ToolContext, tool: str, languages: frozenset[str]) -> CapabilityCheck: + if not aka_v3.is_v3(context): + return blocked_check( + CapabilityState.NOT_APPLICABLE, + f"{tool}_requires_v3_runner", + f"{tool} runs the generated schema-v3 workspace runner; this task has none.", + ) + language = aka_v3.role_language(context) + if language not in aka_v3.V3_LANGUAGES: + return blocked_check( + CapabilityState.UNSUPPORTED, + f"{tool}_language_unsupported", + f"{tool} supports triton, gluon, hip and flydsl, not {language!r}.", + ) + if language not in languages: + return blocked_check( + CapabilityState.NOT_APPLICABLE, + f"{tool}_language_not_applicable", + f"{tool} does not apply to {language} kernels.", + ) + return ready_check(adapter=aka_v3.ADAPTER, language=language) + + +def _runtime(runtime: CapabilityCheck) -> CapabilityCheck: + control = runtime.evidence.get("positive_control") if runtime.evidence else None + if runtime.state == CapabilityState.READY and isinstance(control, dict) and control.get("passed") is False: + return blocked_check( + CapabilityState.UNAVAILABLE_RUNTIME, + "positive_control_failed", + f"the sidecar's startup control failed: {control.get('detail')}", + **dict(runtime.evidence), + ) + return runtime + + +def _report_or_error(execution, lane: str) -> tuple[dict | None, ParseResult | None]: + if execution.timed_out: + return None, ParseResult(TOOL_ERROR, reason_code=f"{lane}_timeout", details=execution.stderr[-4000:]) + report, problem = aka_v3.lane_report(execution.stdout, lane=lane) + if report is None: + return None, ParseResult(TOOL_ERROR, reason_code=f"{lane}_{problem}", details=execution.stderr[-4000:]) + return report, None + + +def _failure_text(report: dict) -> str: + rows = report.get("cases") or [] + errors = [str((row.get("metadata") or {}).get("error", "")) for row in rows] + return "\n".join([str(report.get("reason", ""))] + errors) + + +class _LanePlugin: + lane = "" + languages: frozenset[str] = aka_v3.V3_LANGUAGES + timeout_s = 1800 + # The manager may rerun this gate on the baseline after a finding. + baseline_check = True + + def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: + engine = _v3_engine(context, self.name, self.languages) + adapter = ready_check(adapter=aka_v3.ADAPTER) if engine.state == CapabilityState.READY else ready_check() + return ToolCapability(self.name, engine, adapter, _runtime(runtime)) + + def lane_env(self, context: ToolContext) -> dict[str, str]: + return {} + + def build_invocation(self, context: ToolContext) -> ToolInvocation: + return aka_v3.lane_invocation( + self.name, context, self.lane, env=self.lane_env(context), + timeout_s=int(context.options.get("timeout_s", self.timeout_s)), + ) + + def judge(self, context: ToolContext, execution) -> ParseResult: + raise NotImplementedError + + def parse(self, context: ToolContext, execution) -> ToolRunResult: + parsed = self.judge(context, execution) + return parsed_to_run_result(self.name, parsed, execution, metadata={"adapter": aka_v3.ADAPTER, + "role": aka_v3.role(context)}) + + +class PageFaultGuardPlugin(_LanePlugin): + """Correctness cases with the caching allocators off. + + With caching on, an access past a tensor's end usually lands silently in a + neighbouring allocation. Off, it reaches an unmapped page and the GPU + faults; a result that changes with the allocator also means the role + reads memory it does not own. Accesses inside an allocation's rounding + slack, and buffer instructions whose descriptor carries the real size + (they clamp instead of faulting), are outside this check. + """ + + name = ToolName.PAGE_FAULT_GUARD.value + version = "1" + lane = "page_fault_guard" + + def lane_env(self, context: ToolContext) -> dict[str, str]: + return dict(aka_v3.NO_CACHING) + + def judge(self, context: ToolContext, execution) -> ParseResult: + fault = aka_v3.fault_excerpt(execution.stderr) or aka_v3.fault_excerpt(execution.stdout) + if fault: + finding = FindingRecord(kind="gpu-memory-fault", message="the GPU faulted on an address outside every " + "allocation while the caching allocators were off", raw=fault) + return ParseResult(FINDING, (finding,), "page_fault_guard_fault", attested=True) + report, error = _report_or_error(execution, self.lane) + if error is not None: + return error + environment = (report.get("metadata") or {}).get("environment") or {} + if report.get("status") == "PASS": + if any(environment.get(key) != value for key, value in aka_v3.NO_CACHING.items()): + return ParseResult(INCONCLUSIVE, reason_code="page_fault_guard_environment_not_attested") + return ParseResult(PASS, reason_code="page_fault_guard_clean", attested=True) + kind = report.get("failure_kind") + text = _failure_text(report) + if aka_v3.FAULT_RE.search(text): + finding = FindingRecord(kind="gpu-memory-fault", message="an illegal device memory access was reported " + "while the caching allocators were off", raw=text[:4000]) + return ParseResult(FINDING, (finding,), "page_fault_guard_fault", attested=True) + if kind in ("numerical_mismatch", "input_mutation", "mixed"): + finding = FindingRecord(kind="allocator-sensitive-output", message="outputs that passed correctness " + "changed when the caching allocators were off: the role reads memory it does " + "not own", raw=text[:4000]) + return ParseResult(FINDING, (finding,), "page_fault_guard_allocator_sensitive", attested=True) + return ParseResult(TOOL_ERROR, reason_code=f"page_fault_guard_{kind or 'failed'}", details=text[:4000]) + + +class CsanPlugin(_LanePlugin): + """Correctness cases under PyTorch's CUDA Sanitizer. + + CSAN tracks PyTorch dispatches on each stream, including a HIP + candidate's custom op; raw Triton, Gluon and FlyDSL launches are not + visible to it, so on those paths it checks the PyTorch work around them. + """ + + name = ToolName.CSAN.value + version = "1" + lane = "csan" + + def judge(self, context: ToolContext, execution) -> ParseResult: + report, error = _report_or_error(execution, self.lane) + if error is not None: + return error + metadata = report.get("metadata") or {} + if report.get("failure_kind") == "data_race": + finding = FindingRecord(kind="stream-data-race", message="CSAN reported an unsynchronized access " + "between streams", raw="\n".join(metadata.get("races") or [])[:4000]) + return ParseResult(FINDING, (finding,), "csan_race", attested=True) + if report.get("status") == "PASS": + if metadata.get("enabled") is not True: + return ParseResult(INCONCLUSIVE, reason_code="csan_not_enabled") + return ParseResult(PASS, reason_code="csan_clean", attested=True) + return ParseResult(TOOL_ERROR, reason_code=f"csan_{report.get('failure_kind') or 'failed'}", + details=_failure_text(report)[:4000]) + + +class TileLensPlugin(_LanePlugin): + """TileLens's symbolic out-of-bounds check of each Triton/Gluon kernel. + + The smallest correctness case runs in Triton's CPU interpreter, where + every load and store address is checked against its tensor (z3 over the + symbolic program id, mask and loop bounds). No GPU time is used. + """ + + name = ToolName.TILELENS.value + version = "1" + lane = "tilelens" + languages = frozenset({"triton", "gluon"}) + timeout_s = 3600 + TILELENS_ROOT = "/opt/tilelens/site-packages" + + def lane_env(self, context: ToolContext) -> dict[str, str]: + return {"PYTHONPATH": self.TILELENS_ROOT, "TILELENS_NUM_SMS": str(context.options.get("num_sms", 4))} + + def judge(self, context: ToolContext, execution) -> ParseResult: + report, error = _report_or_error(execution, self.lane) + if error is not None: + return error + metadata = report.get("metadata") or {} + if report.get("failure_kind") == "out_of_bounds": + findings = tuple( + FindingRecord(kind="out-of-bounds", message=f"{item.get('op')} on {item.get('tensor')} at " + f"{item.get('address')}", location="; ".join(item.get("location") or [])[:600] or None) + for item in (metadata.get("violations") or [])[:16] + ) or (FindingRecord(kind="out-of-bounds", message="TileLens reported an out-of-bounds access"),) + return ParseResult(FINDING, findings, "tilelens_out_of_bounds", attested=True) + if report.get("failure_kind") == "unanalyzable": + return ParseResult(INCONCLUSIVE, reason_code="tilelens_unanalyzable", details=_failure_text(report)[:4000]) + if report.get("status") == "PASS": + if metadata.get("approximations"): + return ParseResult(INCONCLUSIVE, reason_code="tilelens_approximated", + details="; ".join(metadata["approximations"])[:4000]) + return ParseResult(PASS, reason_code="tilelens_clean", attested=True) + return ParseResult(TOOL_ERROR, reason_code=f"tilelens_{report.get('failure_kind') or 'failed'}", + details=_failure_text(report)[:4000]) + + +__all__ = ["CsanPlugin", "PageFaultGuardPlugin", "TileLensPlugin"] diff --git a/src/eval_tools/plugins/v3_tools.py b/src/eval_tools/plugins/v3_tools.py new file mode 100644 index 000000000..e07d4267f --- /dev/null +++ b/src/eval_tools/plugins/v3_tools.py @@ -0,0 +1,263 @@ +"""Schema-v3 paths of the original sanitizer plugins. + +The original plugins take a task-declared adapter (an argv, a code object, a +replay capsule). A v3 task declares none, so on that path: + +* Triton FpSan and GPU ASan keep their own environment and attestation rules + and receive the workspace runner's ``sanitize`` lane as their command. +* Waitcheck and the rocJITsu race detector run the image-owned + ``aka_v3_entrypoint`` that captures the role's dispatched kernels on the GPU + and analyses each one; the verdict aggregates one parse per kernel/capsule. +""" + +from __future__ import annotations + +import json +from dataclasses import replace +from pathlib import Path + +from ..adapters.aka_v3_capsules import load_manifest +from ..adapters.replay_capsule import CapsuleValidationError, ReplayCapsule +from ..contracts import ( + CapabilityCheck, + CapabilityState, + KernelLanguage, + ToolCapability, + ToolContext, + ToolInvocation, +) +from . import aka_v3 +from .base import ( + FINDING, + INCONCLUSIVE, + PASS, + TOOL_ERROR, + ParseResult, + blocked_check, + parsed_to_run_result, + ready_check, + sidecar_path, +) +from .parsers import parse_rocjitsu, parse_waitcheck, rocjitsu_dispatch_kernels + +V3_ENTRYPOINT = "/opt/aka-eval-tools/src/eval_tools/adapters/aka_v3_entrypoint.py" +SUPPORTED_ARCH = "gfx950" + + +def _engine(context: ToolContext, tool: str, ready_languages: set[str], reasons: dict[str, str]) -> CapabilityCheck: + language = aka_v3.role_language(context) + if language in ready_languages: + if context.gpu_arch and context.gpu_arch != SUPPORTED_ARCH: + return blocked_check(CapabilityState.UNSUPPORTED, f"{tool}_gfx950_not_selected", + f"{tool} is qualified only for {SUPPORTED_ARCH}.", + observed_gpu_arch=context.gpu_arch) + return ready_check(adapter=aka_v3.ADAPTER, language=language) + if language in reasons: + return blocked_check(CapabilityState.UNSUPPORTED, f"{tool}_{language}_unsupported", reasons[language]) + return blocked_check(CapabilityState.NOT_APPLICABLE, f"{tool}_language_not_applicable", + f"{tool} does not apply to {language} kernels.") + + +def capability(plugin, context: ToolContext, runtime: CapabilityCheck, engine: CapabilityCheck) -> ToolCapability: + adapter = ready_check(adapter=aka_v3.ADAPTER) + return ToolCapability(plugin.name, engine, adapter, runtime) + + +def _with_command(context: ToolContext, key: str, lane: str) -> ToolContext: + invocation = aka_v3.lane_invocation("_", context, lane) + return replace(context, options={**dict(context.options), key: list(invocation.command)}) + + +def _triton_profile(context: ToolContext) -> ToolContext: + """Gluon compiles through Triton; its ASan and FpSan rules are Triton's.""" + language = aka_v3.role_language(context) + target = KernelLanguage.TRITON if language in ("triton", "gluon") else aka_v3.language_enum(language) + return replace(context, profile=replace(context.profile, language=target)) + + +# ---------------------------------------------------------------- triton_fpsan + + +def fpsan_engine(context: ToolContext) -> CapabilityCheck: + languages = {aka_v3.target_language(context), aka_v3.baseline_language(context)} + if not languages <= {"triton", "gluon"}: + return blocked_check(CapabilityState.NOT_APPLICABLE, "triton_fpsan_needs_triton_pair", + "FpSan compares the candidate with a Triton or Gluon baseline; " + f"this task pairs {sorted(languages)}.") + return ready_check(adapter=aka_v3.ADAPTER, instrumentation_mode="fpsan") + + +def fpsan_invocation(plugin, context: ToolContext) -> ToolInvocation: + if aka_v3.role(context) != "candidate": + raise ValueError("FpSan is a candidate-versus-baseline comparison") + invocation = plugin._legacy_build_invocation(_with_command(_triton_profile(context), "comparison_command", "fpsan")) + return replace(invocation, cwd=context.workspace, + env={**dict(invocation.env), "PYTHONPATH": "", "PYTHONDONTWRITEBYTECODE": "1"}) + + +# -------------------------------------------------------------------- gpu_asan + + +def asan_engine(context: ToolContext) -> CapabilityCheck: + return _engine(context, "gpu_asan", {"hip", "triton", "gluon"}, + {"flydsl": "No FlyDSL release inserts AMD GPU ASan instrumentation."}) + + +def asan_invocation(plugin, context: ToolContext) -> ToolInvocation: + language = aka_v3.role_language(context) + if language not in ("hip", "triton", "gluon"): + raise ValueError(f"GPU ASan does not instrument {language}") + invocation = plugin._legacy_build_invocation(_with_command(_triton_profile(context), "command", "gpu_asan")) + env = {**dict(invocation.env), **aka_v3.NO_CACHING, "PYTHONPATH": "", "PYTHONDONTWRITEBYTECODE": "1"} + if language == "hip": + arch = (context.gpu_arch or SUPPORTED_ARCH).split(":", 1)[0] + env.update({"AKA_HIP_SANITIZER_CFLAGS": "-fsanitize=address -shared-libsan", + "AKA_HIP_OFFLOAD_ARCH": f"{arch}:xnack+"}) + return replace(invocation, cwd=context.workspace, env=env) + + +def asan_parse(plugin, context: ToolContext, execution): + return plugin._legacy_parse(_triton_profile(context), execution) + + +# ------------------------------------------------------ waitcheck and rocjitsu + + +def waitcheck_engine(context: ToolContext) -> CapabilityCheck: + return _engine(context, "rocjitsu_waitcheck", {"triton", "gluon", "hip", "flydsl"}, {}) + + +def rocjitsu_engine(context: ToolContext) -> CapabilityCheck: + return _engine(context, "rocjitsu", {"triton", "gluon"}, { + "hip": "HIP candidates have no automatic replay capture: a launch needs its lowered ABI and memory.", + "flydsl": "FlyDSL launches expose no lowered ABI to capture, so no replay capsule can be built.", + }) + + +def _output_dir(context: ToolContext, tool: str) -> Path: + return Path(context.artifact_dir) / f"v3-{tool}" + + +def entrypoint_invocation(plugin, context: ToolContext, tool: str, extra: list[str]) -> ToolInvocation: + output = _output_dir(context, tool) + output.mkdir(parents=True, exist_ok=True) + command = (aka_v3.SIDECAR_PYTHON, "-I", V3_ENTRYPOINT, tool, "--workspace", context.workspace, + "--role", aka_v3.role(context), "--output-dir", str(output), "--target", SUPPORTED_ARCH, + "--task-id", str(context.task_config.get("task_id") or context.task_config.get("name") or ""), + # Bound each step inside the tool's own deadline. + "--capture-timeout", "600", "--kernel-timeout", "600", *extra) + return ToolInvocation(tool=plugin.name, command=command, cwd=context.workspace, + env={**dict(context.env), "AKA_EVAL_TOOL": plugin.name}, + timeout_s=int(context.options.get("timeout_s", 1800)), + artifact_dir=context.artifact_dir, + metadata={"adapter": aka_v3.ADAPTER, "role": aka_v3.role(context)}) + + +def waitcheck_invocation(plugin, context: ToolContext) -> ToolInvocation: + binary = sidecar_path(context, "waitcheck_binary", required=True) + wrapper = sidecar_path(context, "waitcheck_capi_wrapper", required=True) + return entrypoint_invocation(plugin, context, "waitcheck", + ["--waitcheck", str(binary), "--capi-wrapper", str(wrapper)]) + + +def rocjitsu_invocation(plugin, context: ToolContext) -> ToolInvocation: + binary = sidecar_path(context, "rocjitsu_binary", required=True) + config = sidecar_path(context, "config_path", required=True) + return entrypoint_invocation(plugin, context, "rocjitsu", + ["--rocjitsu", str(binary), "--config", str(config)]) + + +def _load_index(context: ToolContext, tool: str) -> tuple[dict | None, dict | None, ParseResult | None]: + output = _output_dir(context, tool) + try: + index = json.loads((output / "index.json").read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + return None, None, ParseResult(TOOL_ERROR, reason_code=f"{tool}_v3_index_missing", details=str(error)) + if index.get("error"): + return index, None, ParseResult(INCONCLUSIVE, reason_code=f"{tool}_v3_capture_failed", + details=str(index["error"])[:4000]) + try: + manifest = load_manifest(output / "capture") + except (OSError, ValueError, CapsuleValidationError) as error: + return index, None, ParseResult(TOOL_ERROR, reason_code=f"{tool}_v3_capture_invalid", details=str(error)) + return index, manifest, None + + +def aggregate(tool: str, parsed: list[ParseResult], unverified: list[str]) -> ParseResult: + findings = tuple(item for result in parsed if result.status == FINDING for item in result.findings) + if findings: + return ParseResult(FINDING, findings, f"{tool}_v3_finding", attested=True) + problems = [result.reason_code or result.status for result in parsed if result.status != PASS] + unverified + if not parsed: + return ParseResult(INCONCLUSIVE, reason_code=f"{tool}_v3_nothing_analyzed", + details="; ".join(unverified)[:4000] or "no dispatched kernel was captured") + if problems: + return ParseResult(INCONCLUSIVE, reason_code=f"{tool}_v3_partial", + details="; ".join(str(item) for item in problems)[:4000], attested=True) + return ParseResult(PASS, reason_code=f"{tool}_v3_clean", attested=True) + + +def _metadata(index: dict | None, parsed: list[ParseResult]) -> dict: + return {"adapter": aka_v3.ADAPTER, "analyzed": len(parsed), + "skipped": list((index or {}).get("skipped") or [])[:8], + "language": (index or {}).get("language")} + + +def waitcheck_parse(plugin, context: ToolContext, execution): + if execution.timed_out: + return parsed_to_run_result(plugin.name, ParseResult(TOOL_ERROR, reason_code="waitcheck_v3_timeout"), + execution) + index, manifest, problem = _load_index(context, "waitcheck") + if problem is not None: + return parsed_to_run_result(plugin.name, problem, execution, metadata=_metadata(index, [])) + output = _output_dir(context, "waitcheck") + captured = {item["code_object"]: item["sha256"] for item in manifest.get("code_objects", [])} + parsed, unverified = [], list(index.get("skipped") or []) + for entry in index.get("entries", []): + if "error" in entry: + unverified.append(f"{entry.get('code_object')}: {entry['error']}") + continue + if captured.get(entry["code_object"]) != entry["code_object_sha256"]: + unverified.append(f"{entry['code_object']}: not the captured code object") + continue + log = (output / entry["log"]).read_text(encoding="utf-8", errors="replace") + parsed.append(parse_waitcheck(log, "", entry["returncode"], expected_sha256=entry["code_object_sha256"], + expected_target=SUPPORTED_ARCH, expected_kernel=entry["kernel_name"], + expected_entry=int(entry["kernel_entry"]))) + return parsed_to_run_result(plugin.name, aggregate("waitcheck", parsed, unverified), execution, + metadata=_metadata(index, parsed)) + + +def rocjitsu_parse(plugin, context: ToolContext, execution): + if execution.timed_out: + return parsed_to_run_result(plugin.name, ParseResult(TOOL_ERROR, reason_code="rocjitsu_v3_timeout"), + execution) + index, manifest, problem = _load_index(context, "rocjitsu") + if problem is not None: + return parsed_to_run_result(plugin.name, problem, execution, metadata=_metadata(index, [])) + output = _output_dir(context, "rocjitsu") + captured = {item["directory"]: item["hsaco_sha256"] for item in manifest.get("launches", [])} + parsed, unverified = [], list(index.get("skipped") or []) + for entry in index.get("entries", []): + if "error" in entry: + unverified.append(f"{entry.get('directory')}: {entry['error']}") + continue + try: + capsule = ReplayCapsule.load(output / entry["capsule"], verify_files=True) + except (OSError, ValueError, CapsuleValidationError) as error: + unverified.append(f"{entry['directory']}: capsule revalidation failed: {error}") + continue + if captured.get(entry["directory"]) != capsule.code_object.sha256: + unverified.append(f"{entry['directory']}: capsule code object is not the captured one") + continue + log = (output / entry["log"]).read_text(encoding="utf-8", errors="replace") + report = (output / entry["race_log"]).read_text(encoding="utf-8", errors="replace") \ + if entry.get("race_log") else "" + combined = "\n".join((log, report)) + kernel = capsule.code_object.kernel_name + attested = (kernel in rocjitsu_dispatch_kernels(combined) and "AKA_REPLAY_RESULT pass" in combined + and f"AKA_REPLAY_CAPSULE sha256={entry['capsule_sha256']} code_sha256={capsule.code_object.sha256} " + f"adapter=triton_aot arch={SUPPORTED_ARCH} kernel={kernel}" in combined) + parsed.append(parse_rocjitsu(log, "", entry["returncode"], attested=attested, report_text=report)) + return parsed_to_run_result(plugin.name, aggregate("rocjitsu", parsed, unverified), execution, + metadata=_metadata(index, parsed)) diff --git a/src/eval_tools/plugins/waitcheck.py b/src/eval_tools/plugins/waitcheck.py index d88c5a425..fb9362d4a 100644 --- a/src/eval_tools/plugins/waitcheck.py +++ b/src/eval_tools/plugins/waitcheck.py @@ -47,11 +47,29 @@ def _expected_kernel(context: ToolContext) -> str: return value +from . import aka_v3, v3_tools + class WaitcheckPlugin: name = ToolName.ROCJITSU_WAITCHECK.value version = "1" + baseline_check = True def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: + if aka_v3.is_v3(context): + return v3_tools.capability(self, context, runtime, v3_tools.waitcheck_engine(context)) + return self._legacy_assess(context, runtime) + + def build_invocation(self, context: ToolContext) -> ToolInvocation: + if aka_v3.is_v3(context): + return v3_tools.waitcheck_invocation(self, context) + return self._legacy_build_invocation(context) + + def parse(self, context: ToolContext, execution) -> ToolRunResult: + if aka_v3.is_v3(context): + return v3_tools.waitcheck_parse(self, context, execution) + return self._legacy_parse(context, execution) + + def _legacy_assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: profile = context.profile unsupported = unsupported_language_check(profile.language, "waitcheck") if unsupported is not None: @@ -97,7 +115,7 @@ def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapabili ) return ToolCapability(self.name, engine, adapter, runtime) - def build_invocation(self, context: ToolContext) -> ToolInvocation: + def _legacy_build_invocation(self, context: ToolContext) -> ToolInvocation: code_object = resolve_workspace_file(context, "code_object") code_sha256 = sha256_file(code_object) expected_kernel = _expected_kernel(context) @@ -140,7 +158,7 @@ def build_invocation(self, context: ToolContext) -> ToolInvocation: }, ) - def parse(self, context: ToolContext, execution) -> ToolRunResult: + def _legacy_parse(self, context: ToolContext, execution) -> ToolRunResult: code_object = resolve_workspace_file(context, "code_object") code_sha256 = sha256_file(code_object) expected_kernel = _expected_kernel(context) diff --git a/src/eval_tools/probes/csan_probe.py b/src/eval_tools/probes/csan_probe.py new file mode 100644 index 000000000..f88f35e92 --- /dev/null +++ b/src/eval_tools/probes/csan_probe.py @@ -0,0 +1,30 @@ +"""PyTorch CUDA Sanitizer control: a side-stream read, with or without a stream wait. + +Usage: csan_probe.py [safe|race] +""" + +from __future__ import annotations + +import sys + +import torch +import torch.cuda._sanitizer as cuda_sanitizer + + +def main() -> int: + race = len(sys.argv) > 1 and sys.argv[1] == "race" + cuda_sanitizer.enable_cuda_sanitizer() + a = torch.ones(1 << 16, device="cuda") + side = torch.cuda.Stream() + with torch.cuda.stream(side): + total = a.sum() + if not race: + torch.cuda.current_stream().wait_stream(side) + a.add_(1) + torch.cuda.synchronize() + print("CSAN_RUN_COMPLETED", "race" if race else "safe", float(total), flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/eval_tools/probes/page_fault_probe.py b/src/eval_tools/probes/page_fault_probe.py new file mode 100644 index 000000000..183a535cb --- /dev/null +++ b/src/eval_tools/probes/page_fault_probe.py @@ -0,0 +1,41 @@ +"""Page-fault guard control: a Triton copy, optionally storing far past its output. + +Usage: page_fault_probe.py [safe|far] + +Run with PyTorch's caching allocator and ROCr's fragment allocator off; the +far store then reaches an unmapped page and the GPU faults. +""" + +from __future__ import annotations + +import sys + +import torch +import triton +import triton.language as tl + + +@triton.jit +def copy_kernel(source, destination, n, shift, BLOCK: tl.constexpr): + offsets = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) + mask = offsets < n + values = tl.load(source + offsets, mask=mask) + tl.store(destination + offsets, values, mask=mask) + if shift > 0: + tl.store(destination + offsets + shift, values, mask=mask) + + +def main() -> int: + far = len(sys.argv) > 1 and sys.argv[1] == "far" + n = 4096 + source = torch.arange(n, device="cuda", dtype=torch.float32) + destination = torch.empty_like(source) + copy_kernel[(triton.cdiv(n, 1024),)](source, destination, n, (1 << 26) if far else 0, BLOCK=1024) + torch.cuda.synchronize() + torch.testing.assert_close(source, destination) + print("FAR_RUN_COMPLETED" if far else "SAFE_RUN_COMPLETED", flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/eval_tools/probes/tilelens_probe.py b/src/eval_tools/probes/tilelens_probe.py new file mode 100644 index 000000000..adad6356f --- /dev/null +++ b/src/eval_tools/probes/tilelens_probe.py @@ -0,0 +1,39 @@ +"""TileLens control: a Triton copy, optionally off by one element, checked symbolically. + +Usage: tilelens_probe.py [safe|oob] + +Uses the same programmatic API as the schema-v3 lane: a Sanitizer client with +abort_on_error off, whose records are read after the launch. +""" + +from __future__ import annotations + +import json +import sys + +import torch +import triton +import triton.language as tl +import tilelens +from tilelens.clients import Sanitizer + + +@triton.jit +def copy_kernel(source, destination, shift: tl.constexpr, BLOCK: tl.constexpr): + offsets = tl.arange(0, BLOCK) + shift + tl.store(destination + offsets, tl.load(source + offsets)) + + +def main() -> int: + shift = 1 if len(sys.argv) > 1 and sys.argv[1] == "oob" else 0 + client = Sanitizer(abort_on_error=False) + kernel = tilelens.trace(client=client)(copy_kernel) + source = torch.arange(1024, device="cuda", dtype=torch.float32) + destination = torch.empty_like(source) + kernel[(1,)](source, destination, shift, BLOCK=1024) + print("TILELENS_RESULT " + json.dumps({"shift": shift, "records": len(client.records)}), flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/eval_tools/worker.py b/src/eval_tools/worker.py index 5ec994046..59220fa81 100644 --- a/src/eval_tools/worker.py +++ b/src/eval_tools/worker.py @@ -915,6 +915,89 @@ def _hip_fpsan_positive( ) +_NO_CACHING = { + "PYTORCH_NO_HIP_MEMORY_CACHING": "1", + "AMD_PYTORCH_NO_CUDA_MEMORY_CACHING": "1", + "HSA_DISABLE_FRAGMENT_ALLOCATOR": "1", +} +_FAULT_RE = re.compile( + r"Memory access fault by GPU|HSA_STATUS_ERROR_MEMORY_FAULT|Memory Fault Error|illegal memory access", + re.I, +) + + +def _python() -> str: + return shutil.which("python") or os.sys.executable + + +def _page_fault_guard_positive(probe_root: Path, work_dir: Path, artifact_dir: Path) -> dict[str, Any]: + steps = {} + for name in ("safe", "far"): + steps[name] = _run_probe_step( + name, [_python(), str(probe_root / "page_fault_probe.py"), name], cwd=work_dir, + environment={**_NO_CACHING, "PYTHONDONTWRITEBYTECODE": "1", + "TRITON_CACHE_DIR": str(work_dir / "triton-cache")}, + artifact_dir=artifact_dir, + ) + safe, far = steps["safe"], steps["far"] + safe_ok = safe["returncode"] == 0 and "SAFE_RUN_COMPLETED" in safe["_stdout"] + far_ok = far["returncode"] not in (0, None) and not far["timed_out"] and bool( + _FAULT_RE.search(str(far["_stderr"]) + str(far["_stdout"]))) + return _positive_result( + passed=safe_ok and far_ok, + kind="page_fault_guard_safe_and_far_store", + detail="a safe copy must pass and a store 256 MiB past its output must fault with the caching " + "allocators off", + artifact_dir=artifact_dir, steps=steps, + controls={"safe": {"passed": safe_ok}, "far_store": {"passed": far_ok}}, + ) + + +def _csan_positive(probe_root: Path, work_dir: Path, artifact_dir: Path) -> dict[str, Any]: + steps = {} + for name in ("safe", "race"): + steps[name] = _run_probe_step( + name, [_python(), str(probe_root / "csan_probe.py"), name], cwd=work_dir, + environment={"PYTHONDONTWRITEBYTECODE": "1"}, artifact_dir=artifact_dir, + ) + safe, race = steps["safe"], steps["race"] + safe_ok = safe["returncode"] == 0 and "CSAN_RUN_COMPLETED safe" in safe["_stdout"] + race_ok = race["returncode"] not in (0, None) and "CSAN detected a possible data race" in race["_stderr"] + return _positive_result( + passed=safe_ok and race_ok, + kind="csan_stream_wait_and_race", + detail="a side-stream read followed by wait_stream must pass; without the wait CSAN must report a race", + artifact_dir=artifact_dir, steps=steps, + controls={"safe": {"passed": safe_ok}, "race": {"passed": race_ok}}, + ) + + +def _tilelens_positive(evidence: Mapping[str, Any], probe_root: Path, work_dir: Path, + artifact_dir: Path) -> dict[str, Any]: + root = str(evidence.get("tilelens_root") or "") + steps, records = {}, {} + for name in ("safe", "oob"): + steps[name] = _run_probe_step( + name, [_python(), str(probe_root / "tilelens_probe.py"), name], cwd=work_dir, + environment={"PYTHONPATH": root, "PYTHONDONTWRITEBYTECODE": "1"}, artifact_dir=artifact_dir, + ) + for line in str(steps[name]["_stdout"]).splitlines(): + if line.startswith("TILELENS_RESULT "): + try: + records[name] = int(json.loads(line[len("TILELENS_RESULT "):])["records"]) + except (ValueError, KeyError, TypeError): + pass + safe_ok = steps["safe"]["returncode"] == 0 and records.get("safe") == 0 + oob_ok = steps["oob"]["returncode"] == 0 and (records.get("oob") or 0) > 0 + return _positive_result( + passed=bool(root) and safe_ok and oob_ok, + kind="tilelens_safe_and_off_by_one", + detail="TileLens must record no violation for an in-bounds copy and at least one for an off-by-one copy", + artifact_dir=artifact_dir, steps=steps, + controls={"safe": {"passed": safe_ok}, "off_by_one": {"passed": oob_ok}}, + ) + + def positive_control_evidence( tool: str, evidence: Mapping[str, Any], @@ -958,6 +1041,12 @@ def positive_control_evidence( return _consan_positive(evidence, probe_root, work_dir, artifact_dir) if tool == "hip_fpsan": return _hip_fpsan_positive(evidence, probe_root, work_dir, artifact_dir) + if tool == "page_fault_guard": + return _page_fault_guard_positive(probe_root, work_dir, artifact_dir) + if tool == "csan": + return _csan_positive(probe_root, work_dir, artifact_dir) + if tool == "tilelens": + return _tilelens_positive(evidence, probe_root, work_dir, artifact_dir) except Exception as error: return _positive_result( passed=False, @@ -1111,6 +1200,16 @@ def runtime_evidence( "hip_fpsan_headers": public_header.is_file(), "hip_fpsan_commit": os.environ.get("AKA_HIP_FPSAN_COMMIT"), }) + elif tool in ("page_fault_guard", "csan"): + evidence.update({"torch_version": _package_version("torch"), "triton_version": _package_version("triton")}) + evidence.update(_gpu_evidence()) + elif tool == "tilelens": + root = Path(os.environ.get("AKA_TILELENS_ROOT", "/opt/tilelens/site-packages")) + evidence.update({ + "tilelens_root": str(root) if (root / "tilelens").is_dir() else None, + "tilelens_version": os.environ.get("AKA_TILELENS_VERSION"), + "triton_version": _package_version("triton"), + }) evidence["positive_control"] = positive_control_evidence( tool, evidence, diff --git a/src/score.py b/src/score.py index 053f9a215..faa63bf9c 100755 --- a/src/score.py +++ b/src/score.py @@ -141,6 +141,10 @@ def task_result_scoring(workspace_path: str) -> float: if result_data.get('pass_verification') is False: speedup_ratio = 0.0 + # A blocking sanitizer finding skips performance; never let a stale or + # partial measurement score it. + if result_data.get('pass_tool_gate') is False: + speedup_ratio = 0.0 # Calculate score calculated_score = score( pass_compilation=pass_compilation, diff --git a/src/scripts/docker_benchmark.sh b/src/scripts/docker_benchmark.sh index 4ad365045..19a693d9b 100755 --- a/src/scripts/docker_benchmark.sh +++ b/src/scripts/docker_benchmark.sh @@ -53,6 +53,8 @@ EVAL_TOOL_ARTIFACT_HOST_ROOT="" EVAL_TOOL_ARTIFACT_SCORING_ROOT="" EVAL_TOOL_SELECTED="" eval_tool_docker_args=() +# Every built-in evaluation tool (src/eval_tools/defaults.py ALL_TOOLS). +EVAL_TOOL_ALL="triton_fpsan gpu_asan rocjitsu rocjitsu_waitcheck rocjitsu_consan hip_fpsan page_fault_guard csan tilelens" eval_tool_container_names=() eval_tool_ids=() @@ -830,7 +832,7 @@ normalize_eval_tool_id() { local tool="${1//-/_}" tool="$(printf '%s' "$tool" | tr '[:upper:]' '[:lower:]')" case "$tool" in - triton_fpsan|gpu_asan|rocjitsu|rocjitsu_waitcheck|rocjitsu_consan|hip_fpsan) printf '%s\n' "$tool" ;; + triton_fpsan|gpu_asan|rocjitsu|rocjitsu_waitcheck|rocjitsu_consan|hip_fpsan|page_fault_guard|csan|tilelens) printf '%s\n' "$tool" ;; *) die "Unsupported evaluation tool '$1'" ;; esac } @@ -841,28 +843,10 @@ resolve_eval_tools() { if [[ -n "${AKA_EVAL_TOOLS:-}" ]]; then raw="${AKA_EVAL_TOOLS//,/ }" elif [[ -n "$config" && -f "$config" ]]; then - raw="$(python3 - "$config" <<'PY' -import sys -import yaml - -value = (yaml.safe_load(open(sys.argv[1], encoding="utf-8")) or {}).get("evaluation_tools") -if not value: - raise SystemExit(0) -enabled = value.get("enabled", ()) if isinstance(value, dict) else () -if enabled is True: - enabled = ( - "triton_fpsan", - "gpu_asan", - "rocjitsu", - "rocjitsu_waitcheck", - "rocjitsu_consan", - "hip_fpsan", - ) -elif isinstance(enabled, str): - enabled = (enabled,) -print(" ".join(str(item) for item in enabled or ())) -PY -)" + # A config without an evaluation_tools section runs the default + # sanitizers on a default architecture (src/eval_tools/defaults.py). + raw="$(python3 "$HOST_ROOT/src/eval_tools/defaults.py" select "$config" "${SELECTED_GPU_ARCH:-}")" \ + || die "Cannot resolve evaluation tools from $config" fi local seen=" " tool normalized @@ -1042,7 +1026,9 @@ build_eval_tool_docker_args() { ) fi - if [[ "$tool" != "rocjitsu_waitcheck" ]]; then + # Every sidecar, Waitcheck included, gets the worker's GPU: schema-v3 tasks + # capture the dispatched kernels on the device before analysing them. + if true; then local gpu_grp gpu_gid for gpu_grp in render video; do gpu_gid="$(getent group "$gpu_grp" 2>/dev/null | cut -d: -f3 || true)" @@ -1107,6 +1093,7 @@ start_eval_tool_sidecars() { local tool image name scratch socket socket_host_dir attempt runtime_ref runtime_env passwd_host_file for tool in "${eval_tool_ids[@]}"; do image="$(eval_tool_image "$tool")" + ensure_eval_tool_image "$tool" "$image" runtime_ref="$(docker image inspect --format '{{.Id}}' "$image")" [[ "$runtime_ref" == sha256:* ]] \ || die "Could not resolve immutable image ID for $tool image $image" @@ -1163,7 +1150,7 @@ stop_eval_tool_sidecars() { unset AKA_SCORING_IMAGE_RUNTIME_REF unset AKA_SCORING_IMAGE_REFERENCE local tool runtime_env - for tool in triton_fpsan gpu_asan rocjitsu rocjitsu_waitcheck rocjitsu_consan hip_fpsan; do + for tool in $EVAL_TOOL_ALL; do runtime_env="AKA_EVAL_TOOL_RUNTIME_REF_$(printf '%s' "$tool" | tr '[:lower:]' '[:upper:]')" unset "$runtime_env" done @@ -1180,28 +1167,43 @@ stop_eval_tool_sidecars() { EVAL_TOOL_SELECTED="" } +build_eval_tool_image() { + local tool="$1" image="$2" dockerfile target="" + case "$tool" in + rocjitsu_waitcheck|rocjitsu_consan) + dockerfile="$HOST_ROOT/docker/eval-tools/rocjitsu-sanitizers/Dockerfile" + target="${tool//_/-}-runtime" + ;; + *) + dockerfile="$HOST_ROOT/docker/eval-tools/${tool//_/-}/Dockerfile" + ;; + esac + if [[ -n "$target" ]]; then + docker build --pull=false --target "$target" -f "$dockerfile" -t "$image" "$HOST_ROOT" + else + docker build --pull=false -f "$dockerfile" -t "$image" "$HOST_ROOT" + fi +} + +ensure_eval_tool_image() { + # Default tools run without a separate build step: a missing default image + # is built once per host. An overridden image must already exist. + local tool="$1" image="$2" tool_upper + docker image inspect "$image" >/dev/null 2>&1 && return 0 + tool_upper="$(printf '%s' "$tool" | tr '[:lower:]' '[:upper:]')" + local env_name="AKA_EVAL_TOOL_IMAGE_${tool_upper}" + [[ -z "${!env_name:-}" ]] || die "Evaluation-tool image $image ($env_name) is not present on this host" + echo "Building missing evaluation-tool image $image" >&2 + build_eval_tool_image "$tool" "$image" >&2 || die "Failed to build evaluation-tool image $image" +} + build_eval_tool_images() { select_runtime_for_host [[ "$SELECTED_GPU_ARCH" == "gfx950" ]] \ || die "Tool images currently have verified build locks only for gfx950" - local tool image dockerfile target - for tool in triton_fpsan gpu_asan rocjitsu rocjitsu_waitcheck rocjitsu_consan hip_fpsan; do - image="$(eval_tool_image "$tool")" - target="" - case "$tool" in - rocjitsu_waitcheck|rocjitsu_consan) - dockerfile="$HOST_ROOT/docker/eval-tools/rocjitsu-sanitizers/Dockerfile" - target="${tool//_/-}-runtime" - ;; - *) - dockerfile="$HOST_ROOT/docker/eval-tools/${tool//_/-}/Dockerfile" - ;; - esac - if [[ -n "$target" ]]; then - docker build --pull=false --target "$target" -f "$dockerfile" -t "$image" "$HOST_ROOT" - else - docker build --pull=false -f "$dockerfile" -t "$image" "$HOST_ROOT" - fi + local tool + for tool in $EVAL_TOOL_ALL; do + build_eval_tool_image "$tool" "$(eval_tool_image "$tool")" done } @@ -1502,7 +1504,7 @@ build_docker_args() { docker_args+=(-e "AKA_EVAL_TOOLS_SELECTED=${AKA_EVAL_TOOLS_SELECTED}") fi local eval_tool runtime_env - for eval_tool in triton_fpsan gpu_asan rocjitsu rocjitsu_waitcheck rocjitsu_consan hip_fpsan; do + for eval_tool in $EVAL_TOOL_ALL; do runtime_env="AKA_EVAL_TOOL_RUNTIME_REF_$(printf '%s' "$eval_tool" | tr '[:lower:]' '[:upper:]')" if [[ -n "${!runtime_env:-}" ]]; then docker_args+=(-e "$runtime_env=${!runtime_env}") @@ -2370,7 +2372,7 @@ case "${1:-}" in ;; eval-tools-smoke) select_runtime_for_host - export AKA_EVAL_TOOLS="${AKA_EVAL_TOOLS:-triton_fpsan,gpu_asan,rocjitsu,rocjitsu_waitcheck,rocjitsu_consan,hip_fpsan}" + export AKA_EVAL_TOOLS="${AKA_EVAL_TOOLS:-${EVAL_TOOL_ALL// /,}}" trap stop_eval_tool_sidecars EXIT start_eval_tool_sidecars "" "smoke-${BASHPID}" for eval_tool in "${eval_tool_ids[@]}"; do @@ -2437,6 +2439,12 @@ case "${1:-}" in build_eval_tool_docker_args "$@" printf '%s\n' "${eval_tool_docker_args[@]}" ;; + _resolve_eval_tools) + shift + [[ "$#" -eq 2 ]] || die "_resolve_eval_tools expects CONFIG ARCH" + SELECTED_GPU_ARCH="$2" + resolve_eval_tools "$1" + ;; _verify_eval_tool_scoring_image) shift [[ "$#" -eq 2 ]] \ diff --git a/src/task_contract.py b/src/task_contract.py index 874e1ff84..feba61d2d 100644 --- a/src/task_contract.py +++ b/src/task_contract.py @@ -751,10 +751,17 @@ def _candidate_document(contract: TaskContract, language: str) -> str: "the current stream.", "- Correctness: each output must stay within the declared error bound of the high-precision " "reference on every workload, for two input draws and a repeated call on the same buffers.", + "- The final evaluation also runs sanitizers on the correctness cases: PyTorch's caching " + "allocator off (an access past a tensor faults), PyTorch's CUDA Sanitizer, a symbolic " + "bounds check of Triton/Gluon kernels, and static wait-hazard and simulated race checks of the " + "kernels you launch. A definite finding the baseline does not share stops performance scoring.", "", "## Commands", "", "```sh", f"python3 -m {EVAL_DIR}.evaluate candidate compile", f"python3 -m {EVAL_DIR}.evaluate candidate correctness", f"python3 -m {EVAL_DIR}.evaluate candidate performance", + "# out-of-bounds self-check with the caching allocators off", + "PYTORCH_NO_HIP_MEMORY_CACHING=1 AMD_PYTORCH_NO_CUDA_MEMORY_CACHING=1 HSA_DISABLE_FRAGMENT_ALLOCATOR=1 \\", + f" python3 -m {EVAL_DIR}.evaluate candidate sanitize page_fault_guard", "```", ""] return "\n".join(lines) diff --git a/src/tools/arena_eval/evaluate.py b/src/tools/arena_eval/evaluate.py index 81f3253a3..45428b772 100644 --- a/src/tools/arena_eval/evaluate.py +++ b/src/tools/arena_eval/evaluate.py @@ -5,6 +5,10 @@ python3 -m _aka_eval.evaluate validate-task python3 -m _aka_eval.evaluate {baseline|candidate} {compile|correctness|performance} + python3 -m _aka_eval.evaluate {baseline|candidate} sanitize LANE + +``sanitize`` is run by an evaluation-tool sidecar, never by the agent loop; +see sanitize.py for its lanes. Every action prints exactly one ``ARENA_EVAL_RESULT=`` arena-eval-v1 line and exits nonzero on failure. The framework, not this script, decides acceptance, @@ -122,6 +126,8 @@ def _load(contract: Contract, role: str, *, audit: bool, integrity=None): evidence["package"] = loaded.package if loaded.hip_op: evidence["hip_op"] = loaded.hip_op + if loaded.library: + evidence["library"] = loaded.library return call, evidence @@ -260,11 +266,11 @@ def _role_calls(contract: Contract, role: str): return call, baseline_call, need_baseline, check -def correctness_action(contract: Contract, role: str) -> dict: - device = _device() - call, baseline_call, need_baseline, check = _role_calls(contract, role) +def check_cases(contract: Contract, role: str, call, baseline_call, need_baseline: bool, device, + cases=None) -> tuple[list, list, set]: + """Run and check each case; a crash in one case is that case's failure.""" rows, failures, kinds = [], [], set() - for case in contract.cases: + for case in contract.cases if cases is None else cases: row = case.identity() try: data = _CaseData(contract, case, device, baseline_call, need_baseline) @@ -284,6 +290,13 @@ def correctness_action(contract: Contract, role: str) -> dict: failures.append(row["test_case_id"]) kinds.add(row["failure_kind"]) rows.append(row) + return rows, failures, kinds + + +def correctness_action(contract: Contract, role: str) -> dict: + device = _device() + call, baseline_call, need_baseline, check = _role_calls(contract, role) + rows, failures, kinds = check_cases(contract, role, call, baseline_call, need_baseline, device) if failures: kind = kinds.pop() if len(kinds) == 1 else "mixed" if kind == "mixed": @@ -374,16 +387,23 @@ def after_sample(_outputs) -> None: def run(argv: list[str]) -> tuple[dict, int]: + from . import sanitize + + lane = None if argv == ["validate-task"]: role, action = "task", "validate-task" elif len(argv) == 2 and argv[0] in ("baseline", "candidate") and argv[1] in ("compile", "correctness", "performance"): role, action = argv + elif len(argv) == 3 and argv[0] in ("baseline", "candidate") and argv[1] == "sanitize" and argv[2] in sanitize.LANES: + role, action, lane = argv else: return _report("task", "validate-task", "FAIL", [], f"Unknown action {argv}", "usage"), 2 try: contract = load_contract() if action == "validate-task": report = validate_task(contract) + elif action == "sanitize": + report = sanitize.run_lane(contract, role, lane) elif action == "compile": report = compile_action(contract, role) elif action == "correctness": diff --git a/src/tools/arena_eval/loader.py b/src/tools/arena_eval/loader.py index 150fdb4c5..3f67a2034 100644 --- a/src/tools/arena_eval/loader.py +++ b/src/tools/arena_eval/loader.py @@ -27,6 +27,7 @@ import inspect import json import os +import re import sys import types from dataclasses import dataclass @@ -41,6 +42,14 @@ HIP_SOURCE_SUFFIXES = (".hip",) HIP_HEADER_SUFFIXES = (".h", ".hpp", ".cuh", ".inc") _FLAGS = ("-O3",) +# A sanitizer lane (see sanitize.py) rebuilds HIP with instrumentation. Only +# this allowlist crosses from the environment into the compiler command, and +# both values enter the build hash so an instrumented build never reuses, or +# is reused as, an ordinary one. +SANITIZER_CFLAGS_ENV = "AKA_HIP_SANITIZER_CFLAGS" +SANITIZER_ARCH_ENV = "AKA_HIP_OFFLOAD_ARCH" +_SANITIZER_FLAGS = frozenset({"-fsanitize=address", "-shared-libsan"}) +_OFFLOAD_ARCH = re.compile(r"gfx[0-9a-f]+(:(sramecc|xnack)[+-])*") class BuildError(RuntimeError): @@ -54,6 +63,7 @@ class Loaded: package: str sources: dict[str, str] hip_op: str | None = None + library: str | None = None def implementation_sources(implementation: Implementation) -> dict[str, str]: @@ -151,13 +161,32 @@ def _cache_root() -> Path: return root +def hip_build_flags() -> tuple[str, ...]: + """The HIP compiler flags: ``-O3`` plus any allowlisted sanitizer flags.""" + extra = tuple(os.environ.get(SANITIZER_CFLAGS_ENV, "").split()) + unknown = sorted(set(extra) - _SANITIZER_FLAGS) + if unknown: + raise BuildError(f"{SANITIZER_CFLAGS_ENV} accepts only {sorted(_SANITIZER_FLAGS)}, not {unknown}") + return _FLAGS + extra + + +def hip_build_arch() -> str: + """The offload architecture: the device's, or a sanitizer lane's feature-qualified override.""" + override = os.environ.get(SANITIZER_ARCH_ENV, "").strip() + if not override: + return current_arch() + if not _OFFLOAD_ARCH.fullmatch(override) or override.split(":")[0] != current_arch(): + raise BuildError(f"{SANITIZER_ARCH_ENV}={override!r} is not a feature-qualified {current_arch()}") + return override + + def _toolchain() -> str: from torch.utils import cpp_extension version = Path(cpp_extension.ROCM_HOME or "", ".info", "version") return json.dumps({"torch": torch.__version__, "rocm": version.read_text().strip() if version.is_file() else None, - "flags": _FLAGS}) + "flags": hip_build_flags()}) def current_arch() -> str: @@ -189,7 +218,7 @@ def _load_hip(contract: Contract, implementation: Implementation) -> Loaded: for path in sources: if not path.endswith(HIP_SOURCE_SUFFIXES + HIP_HEADER_SUFFIXES): raise BuildError(f"HIP implementation file {path} is neither a .hip source nor a header") - arch = current_arch() + arch = hip_build_arch() if current_arch() else "" if not arch: raise BuildError("No GPU architecture to build HIP for") package = f"aka_hip_{implementation.role}_{_content_hash(sources, _toolchain() + arch)}" @@ -211,7 +240,7 @@ def _load_hip(contract: Contract, implementation: Implementation) -> Loaded: try: cpp_extension.load(name=package, sources=[str(source_dir / p) for p in sorted(sources) if p.endswith(".hip")], - extra_include_paths=[str(source_dir)], extra_cuda_cflags=list(_FLAGS), + extra_include_paths=[str(source_dir)], extra_cuda_cflags=list(hip_build_flags()), build_directory=str(build), is_python_module=False, verbose=False) except Exception as exc: raise BuildError(f"HIP build failed: {type(exc).__name__}: {exc}") from exc @@ -227,7 +256,8 @@ def _load_hip(contract: Contract, implementation: Implementation) -> Loaded: raise BuildError(f"{implementation.entry_file} registers no op {implementation.symbol} in " "TORCH_LIBRARY_EXPAND(TORCH_EXTENSION_NAME, m)") from exc _check_op_schema(f"{implementation.entry_file}::{implementation.symbol}", op._schema, contract) - return Loaded(implementation, lambda **call: op(**call), package, sources, f"{package}::{implementation.symbol}") + return Loaded(implementation, lambda **call: op(**call), package, sources, f"{package}::{implementation.symbol}", + str(library)) def load_implementation(contract: Contract, role: str) -> Loaded: diff --git a/src/tools/arena_eval/sanitize.py b/src/tools/arena_eval/sanitize.py new file mode 100644 index 000000000..68e52cf41 --- /dev/null +++ b/src/tools/arena_eval/sanitize.py @@ -0,0 +1,762 @@ +# Copyright(C) [2026] Advanced Micro Devices, Inc. All rights reserved. +"""Framework-owned sanitizer lanes for schema-v3 tasks. + + python3 -m _aka_eval.evaluate {baseline|candidate} sanitize LANE + +An evaluation-tool sidecar (src/eval_tools) runs each lane in a fresh process +and sets the lane's environment first: allocator switches, compiler +instrumentation and runtime preloads only take effect before PyTorch, HIP and +Triton initialize. A lane checks that environment instead of trusting it, runs +the role's implementation on the task's own correctness cases and prints one +``ARENA_EVAL_RESULT=`` report whose action is ``sanitize``. + +The report is evidence, not the verdict. A hardware memory fault or a GPU +AddressSanitizer report terminates the process before any report is printed, +so the sidecar's plugin judges each lane from the exit status, stderr and the +report together. + +Lanes: + +``page_fault_guard`` + Every correctness case with the caching allocators off, so an access past + a tensor's allocation reaches an unmapped page and faults instead of + landing silently in a neighbouring tensor. +``csan`` + Every correctness case under PyTorch's CUDA Sanitizer (stream races between + PyTorch-visible operations, including a HIP candidate's custom op). +``tilelens`` + The smallest case with each Triton or Gluon kernel run by TileLens's + symbolic out-of-bounds checker in Triton's CPU interpreter. +``fpsan`` + The smallest case through Triton FpSan for the candidate and the baseline + (both Triton or Gluon); a differing digest means a different floating-point + expression. A signal only: correct rewrites also change the digest. +``gpu_asan`` + Every correctness case with GPU AddressSanitizer instrumentation + (bare-metal hosts only: the ASan runtime needs XNACK host-memory access). +``capture`` + One call on the smallest case that records each kernel the role dispatched: + its final code object and, for Triton and Gluon, a replay record (launch + geometry, arguments and memory before and after) from which the framework + builds rocJITsu replay capsules. +""" +from __future__ import annotations + +import hashlib +import json +import math +import os +import shutil +import subprocess +import sys +import warnings +from pathlib import Path + +LANES = ("page_fault_guard", "csan", "tilelens", "fpsan", "gpu_asan", "capture") + +# The allocator switches a lane requires; the sidecar sets them before start-up. +NO_CACHING = {"PYTORCH_NO_HIP_MEMORY_CACHING": "1", "AMD_PYTORCH_NO_CUDA_MEMORY_CACHING": "1", + "HSA_DISABLE_FRAGMENT_ALLOCATOR": "1"} +ATTESTATION_ENV = "AKA_BUILD_ATTESTATION_PATH" +OUTPUT_ENV = "AKA_SANITIZE_OUTPUT_DIR" +FPSAN_PREFIX = "AKA_FPSAN_RESULT " +CAPTURE_SCHEMA = 1 +# Capture is bounded: a replay record holds every allocation a launch touches. +CAPTURE_MAX_LAUNCHES = 16 +CAPTURE_MAX_BYTES = 256 << 20 + + +def _evaluate(): + from . import evaluate + + return evaluate + + +def _require_env(required: dict) -> dict: + evaluate = _evaluate() + missing = {key: value for key, value in required.items() if os.environ.get(key) != value} + if missing: + raise evaluate.ActionFailure(f"The sanitizer environment is not set: {sorted(missing)}", "environment") + return dict(required) + + +def _case_size(contract, case) -> int: + symbols = contract.symbols(case) + total = 0 + for declaration in list(contract.inputs.values()) + list(contract.outputs.values()): + if declaration.get("kind", "tensor") == "tensor" or "shape" in declaration: + total += math.prod(contract.shape(declaration, symbols)) + return total + + +def smallest_case(contract): + return min(contract.cases, key=lambda case: (_case_size(contract, case), case.case_id)) + + +def _load_role(contract, role: str, *, enforce: bool): + """The role's audited call; ``enforce=False`` keeps the integrity check but skips launch auditing.""" + evaluate = _evaluate() + from .audit import PolicyError + from .loader import BuildError + + if role == "candidate" and evaluate.candidate_state(contract) == "unimplemented": + raise evaluate.ActionFailure("The candidate is still the unimplemented template", "unimplemented") + check = evaluate._integrity(role) + try: + call, evidence = evaluate._load(contract, role, audit=enforce and evaluate._policy_enforced(role), + integrity=check) + except PolicyError as exc: + raise evaluate.ActionFailure(str(exc), "policy_violation") + except BuildError as exc: + raise evaluate.ActionFailure(str(exc), "compile_error") + return call, evidence, check + + +def _run_once(contract, call, case, device, seed_index: int = 0) -> dict: + """One call on fresh inputs; returns the written tensors.""" + from . import values + + inputs = values.make_inputs(contract, case, case.seeds[seed_index], device) + kernel = values.clone_inputs(inputs.kernel) + outputs = values.allocate_outputs(contract, case, device) + values.poison(outputs, 31 + seed_index) + _synchronize() + call(**kernel, **outputs) + _synchronize() + return values.checked_values(contract, kernel, outputs) + + +def _synchronize() -> None: + import torch + + torch.cuda.synchronize() + + +def _report(role: str, status: str, rows: list, lane: str, metadata: dict, reason=None, kind=None) -> dict: + evaluate = _evaluate() + return evaluate._report(role, "sanitize", status, rows, reason, kind, metadata={"lane": lane, **metadata}) + + +def _crash_rows(contract, role, call, device, cases) -> tuple[list, list]: + """Run each case once without checking values; return rows and errors.""" + rows, errors = [], [] + for case in cases: + row = case.identity() + try: + _run_once(contract, call, case, device) + row["status"] = "PASS" + except Exception as exc: + row.update(status="FAIL", failure_kind="execution_error", + metadata={"error": f"{type(exc).__name__}: {exc}"[:2000]}) + errors.append(row["metadata"]["error"]) + rows.append(row) + return rows, errors + + +# --------------------------------------------------------------------------- +# page_fault_guard + + +def page_fault_guard(contract, role: str) -> dict: + evaluate = _evaluate() + environment = _require_env(NO_CACHING) + device = evaluate._device() + call, baseline_call, need_baseline, check = evaluate._role_calls(contract, role) + rows, failures, kinds = evaluate.check_cases(contract, role, call, baseline_call, need_baseline, device) + if check is not None: + check("sanitize") + metadata = {"environment": environment, "cases": len(rows)} + if failures: + return _report(role, "FAIL", rows, "page_fault_guard", metadata, + f"{len(failures)} case(s) failed with the caching allocators off: {failures[:8]}", + kinds.pop() if len(kinds) == 1 else "mixed") + return _report(role, "PASS", rows, "page_fault_guard", metadata) + + +# --------------------------------------------------------------------------- +# csan + + +def csan(contract, role: str) -> dict: + evaluate = _evaluate() + import torch.cuda._sanitizer as cuda_sanitizer + + device = evaluate._device() + call, _, check = _load_role(contract, role, enforce=True) + cuda_sanitizer.enable_cuda_sanitizer() + rows, errors = _crash_rows(contract, role, call, device, contract.cases) + if check is not None: + check("sanitize") + races = [error for error in errors if error.startswith("CUDASanitizerErrors")] + metadata = {"cases": len(rows), "races": races[:8], + "enabled": bool(getattr(cuda_sanitizer.cuda_sanitizer, "enabled", False))} + if races: + return _report(role, "FAIL", rows, "csan", metadata, f"CSAN reported a stream race in {len(races)} case(s)", + "data_race") + if errors: + return _report(role, "FAIL", rows, "csan", metadata, f"{len(errors)} case(s) failed: {errors[:2]}", + "execution_error") + return _report(role, "PASS", rows, "csan", metadata) + + +# --------------------------------------------------------------------------- +# tilelens + + +def _tilelens_patch(sanitizers: list): + """Patch triton.jit/autotune and gluon.jit as TileLens's CLI does, with abort_on_error off.""" + import triton + import triton.runtime.interpreter as interpreter + import tilelens + from tilelens.clients import Sanitizer + from tilelens.core.config import config + from triton.experimental import gluon + + original = {"jit": triton.jit, "autotune": triton.autotune, "gluon": gluon.jit} + + def wrap(kernel, *, frontend="triton"): + client = Sanitizer(abort_on_error=False) + sanitizers.append(client) + return tilelens.trace(client=client, frontend=frontend)(kernel) + + def patched_jit(base, frontend): + def jit(fn=None, **options): + if fn is None: + return lambda function: wrap(base(**options)(function), frontend=frontend) + return wrap(base(fn), frontend=frontend) + return jit + + def autotune(fn=None, **options): + if fn is None: + return lambda function: wrap(original["autotune"](**options)(function)) + return wrap(original["autotune"](fn)) + + config.cli_active = True + triton.jit = triton.language.jit = interpreter.jit = patched_jit(original["jit"], "triton") + triton.autotune = autotune + gluon.jit = patched_jit(original["gluon"], "gluon") + + +def _tilelens_record(record) -> dict: + def text(value, limit=400): + return str(value)[:limit] if value is not None else None + + tracebacks = getattr(record, "user_code_tracebacks", None) or [] + return {"op": getattr(getattr(record, "op_type", None), "__name__", text(getattr(record, "op_type", None))), + "tensor": text(getattr(record, "tensor_name", None)), + "address": text(getattr(record, "violation_address", None)), + "location": [text(item, 300) for item in list(tracebacks)[:3]]} + + +def tilelens(contract, role: str) -> dict: + evaluate = _evaluate() + implementation = contract.implementation(role) + if implementation.language not in ("triton", "gluon"): + raise evaluate.ActionFailure(f"TileLens checks Triton and Gluon, not {implementation.language}", + "unsupported") + device = evaluate._device() + sanitizers: list = [] + try: + _tilelens_patch(sanitizers) + except ImportError as exc: + raise evaluate.ActionFailure(f"TileLens is not installed: {exc}", "environment") + # Kernels execute in the CPU interpreter, which the GPU launch audit cannot + # observe; the call keeps its integrity check and ran audited in correctness. + call, _, check = _load_role(contract, role, enforce=False) + case = smallest_case(contract) + row = case.identity() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + try: + _run_once(contract, call, case, device) + row["status"] = "PASS" + error = None + except SystemExit as exc: # abort_on_error is off; any exit is unexpected + error = f"SystemExit: {exc.code}" + except Exception as exc: + error = f"{type(exc).__name__}: {exc}"[:2000] + if check is not None: + check("sanitize") + violations = [_tilelens_record(record) for client in sanitizers for record in getattr(client, "records", [])] + approximations = sorted({str(item.message)[:200] for item in caught + if "approximat" in str(item.message).lower()}) + metadata = {"case": case.case_id, "kernels": len(sanitizers), "violations": violations[:16], + "violation_count": len(violations), "approximations": approximations} + if violations: + row.update(status="FAIL", failure_kind="out_of_bounds") + return _report(role, "FAIL", [row], "tilelens", metadata, + f"TileLens found {len(violations)} out-of-bounds access(es)", "out_of_bounds") + if error is not None: + row.update(status="FAIL", failure_kind="unanalyzable", metadata={"error": error}) + return _report(role, "FAIL", [row], "tilelens", metadata, f"TileLens could not analyze the call: {error}", + "unanalyzable") + if not sanitizers: + return _report(role, "FAIL", [row], "tilelens", metadata, "No Triton or Gluon kernel was traced", + "unanalyzable") + return _report(role, "PASS", [row], "tilelens", metadata) + + +# --------------------------------------------------------------------------- +# fpsan + + +def _launch_names(): + """Kernel names launched through Triton while the context is active.""" + from triton import knobs + + names: list[str] = [] + previous = knobs.runtime.launch_enter_hook + + def hook(metadata): + data = getattr(metadata, "data", metadata) + name = data.get("name") if isinstance(data, dict) else None + if name: + names.append(str(name)) + if previous is not None: + previous(metadata) + + return names, previous, hook + + +def _cache_kernels(cache: Path) -> dict: + """Compiled kernels in a Triton cache: name -> (metadata, hsaco path).""" + kernels = {} + for metadata_path in sorted(cache.rglob("*.json")): + try: + metadata = json.loads(metadata_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + name = metadata.get("name") if isinstance(metadata, dict) else None + hsaco = metadata_path.with_name(f"{name}.hsaco") if name else None + if name and hsaco is not None and hsaco.is_file(): + kernels.setdefault(name, []).append((metadata, hsaco)) + return kernels + + +def _digest(written: dict) -> str: + import torch + + digest = hashlib.sha256() + for name in sorted(written): + tensor = written[name].detach().contiguous() + digest.update(name.encode() + b"\0" + str(tensor.dtype).encode() + str(tuple(tensor.shape)).encode()) + digest.update(tensor.view(torch.uint8).cpu().numpy().tobytes() if tensor.numel() else b"") + return digest.hexdigest() + + +def fpsan(contract, role: str) -> dict: + evaluate = _evaluate() + from triton import knobs + + environment = _require_env({"TRITON_INSTRUMENTATION_MODE": "fpsan"}) + if role != "candidate": + raise evaluate.ActionFailure("FpSan compares the candidate with the baseline", "usage") + languages = {contract.baseline.language, contract.candidate.language} + if not languages <= {"triton", "gluon"}: + raise evaluate.ActionFailure(f"FpSan compares Triton/Gluon implementations, not {sorted(languages)}", + "unsupported") + cache = Path(os.environ.get("TRITON_CACHE_DIR", "")) + if not cache.is_dir(): + raise evaluate.ActionFailure("FpSan needs a fresh TRITON_CACHE_DIR", "environment") + device = evaluate._device() + case = smallest_case(contract) + baseline_call = evaluate._load(contract, "baseline", audit=False)[0] + call, _, check = _load_role(contract, "candidate", enforce=True) + launched = {} + for label, function in (("baseline", baseline_call), ("candidate", call)): + names, previous, hook = _launch_names() + knobs.runtime.launch_enter_hook = hook + try: + written = _run_once(contract, function, case, device) + finally: + knobs.runtime.launch_enter_hook = previous + launched[label] = {"names": sorted(set(names)), "digest": _digest(written)} + if check is not None: + check("sanitize") + compiled = _cache_kernels(cache) + instrumented = {} + for label, record in launched.items(): + modes = [entry[0].get("instrumentation_mode") for name in record["names"] for entry in compiled.get(name, [])] + instrumented[label] = bool(record["names"]) and bool(modes) and all(mode == "fpsan" for mode in modes) and all( + name in compiled for name in record["names"]) + payload = {"instrumented": all(instrumented.values()), "reference_digest": launched["baseline"]["digest"], + "candidate_digest": launched["candidate"]["digest"], "case": case.case_id, + "reference_kernels": launched["baseline"]["names"], "candidate_kernels": launched["candidate"]["names"]} + attestation = os.environ.get(ATTESTATION_ENV) + if attestation and instrumented.get("candidate"): + name = launched["candidate"]["names"][0] + _write_attestation(Path(attestation), tool="triton_fpsan", artifact=compiled[name][0][1], + build_command=("triton", "TRITON_INSTRUMENTATION_MODE=fpsan"), + environment=environment, + evidence={"reference_instrumented": instrumented["baseline"], + "candidate_instrumented": instrumented["candidate"], + "kernels": payload["candidate_kernels"]}) + print(FPSAN_PREFIX + json.dumps(payload, sort_keys=True), flush=True) + return _report(role, "PASS", [case.identity() | {"status": "PASS"}], "fpsan", + {"environment": environment, **payload}) + + +# --------------------------------------------------------------------------- +# gpu_asan + + +def _write_attestation(path: Path, *, tool: str, artifact: Path, build_command, environment: dict, + evidence: dict, compiler: str = "", compiler_version: str = "", target_arch: str = "") -> None: + """A src/eval_tools BuildAttestation, written without importing the framework.""" + path.parent.mkdir(parents=True, exist_ok=True) + copy = path.parent / f"attested-{artifact.name}" + shutil.copyfile(artifact, copy) + payload = {"tool": tool, "instrumented": True, "compiler": compiler, "compiler_version": compiler_version, + "target_arch": target_arch, "build_command": [str(item) for item in build_command], + "artifact_path": copy.name, "artifact_sha256": hashlib.sha256(copy.read_bytes()).hexdigest(), + "environment": dict(environment), "evidence": dict(evidence)} + path.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8") + + +def _offload_bundler() -> Path | None: + from torch.utils import cpp_extension + + roots = [Path(cpp_extension.ROCM_HOME or "/opt/rocm")] + hipcc = shutil.which("hipcc") + if hipcc: + roots.append(Path(hipcc).resolve().parent.parent) + for root in roots: + for relative in ("llvm/bin/clang-offload-bundler", "lib/llvm/bin/clang-offload-bundler"): + if (root / relative).is_file(): + return root / relative + found = shutil.which("clang-offload-bundler") + return Path(found) if found else None + + +def _elf_section(path: Path, wanted: str) -> bytes | None: + """The bytes of one section of a 64-bit little-endian ELF file.""" + import struct + + data = path.read_bytes() + if data[:4] != b"\x7fELF" or data[4] != 2 or data[5] != 1: + return None + shoff, = struct.unpack_from(" list[Path]: + """Unbundle the device code objects embedded in a HIP torch extension.""" + fatbin = _elf_section(library, ".hip_fatbin") + bundler = _offload_bundler() + if not fatbin or bundler is None: + return [] + output.mkdir(parents=True, exist_ok=True) + bundle = output / f"{library.stem}.hip_fatbin" + bundle.write_bytes(fatbin) + listed = subprocess.run([str(bundler), "--list", "--type=o", f"--input={bundle}"], capture_output=True, + text=True, check=False, timeout=120) + objects = [] + for index, target in enumerate(line.strip() for line in listed.stdout.splitlines()): + if not target.startswith("hip") or "gfx" not in target: + continue + code_object = output / f"{library.stem}-{index}.co" + unbundled = subprocess.run([str(bundler), "--unbundle", "--type=o", f"--input={bundle}", + f"--targets={target}", f"--output={code_object}"], + capture_output=True, text=True, check=False, timeout=120) + if unbundled.returncode == 0 and code_object.is_file() and code_object.read_bytes()[:4] == b"\x7fELF": + objects.append(code_object) + return objects + + +def gpu_asan(contract, role: str) -> dict: + evaluate = _evaluate() + from .loader import SANITIZER_ARCH_ENV, SANITIZER_CFLAGS_ENV, hip_build_arch, hip_build_flags + + language = contract.implementation(role).language + required = {"HSA_XNACK": "1", **NO_CACHING} + if language == "hip": + required.update({SANITIZER_CFLAGS_ENV: "-fsanitize=address -shared-libsan"}) + elif language in ("triton", "gluon"): + required.update({"TRITON_ENABLE_ASAN": "1", "AMDGCN_USE_BUFFER_OPS": "0"}) + else: + raise evaluate.ActionFailure(f"GPU ASan does not instrument {language}", "unsupported") + environment = _require_env(required) + device = evaluate._device() + call, implementation, check = _load_role(contract, role, enforce=True) + rows, errors = _crash_rows(contract, role, call, device, contract.cases) + if check is not None: + check("sanitize") + evidence: dict = {"language": language} + artifact = None + command: tuple = () + arch = "" + if language == "hip": + arch = hip_build_arch() + command = ("hipcc", *hip_build_flags(), f"--offload-arch={arch}") + environment[SANITIZER_ARCH_ENV] = arch + library = Path(implementation.get("library") or "") + objects = hip_code_objects(library, Path(os.environ.get("TMPDIR", "/tmp")) / "aka-asan-co") \ + if library.is_file() else [] + evidence["device_code_objects"] = len(objects) + evidence["device_instrumented"] = bool(objects) and all(b"__asan" in item.read_bytes() for item in objects) + artifact = library if library.is_file() else None + else: + cache = Path(os.environ.get("TRITON_CACHE_DIR", "")) + compiled = [entry for entries in _cache_kernels(cache).values() for entry in entries] if cache.is_dir() else [] + evidence["kernels"] = len(compiled) + evidence["device_instrumented"] = bool(compiled) and all(b"__asan" in entry[1].read_bytes() + for entry in compiled) + artifact = compiled[0][1] if compiled else None + command = ("triton", "TRITON_ENABLE_ASAN=1", "AMDGCN_USE_BUFFER_OPS=0") + attestation = os.environ.get(ATTESTATION_ENV) + if attestation and artifact is not None and evidence["device_instrumented"]: + _write_attestation(Path(attestation), tool="gpu_asan", artifact=artifact, build_command=command, + environment=environment, evidence=evidence, target_arch=arch) + metadata = {"environment": environment, "cases": len(rows), **evidence} + if errors: + return _report(role, "FAIL", rows, "gpu_asan", metadata, f"{len(errors)} case(s) failed: {errors[:2]}", + "execution_error") + return _report(role, "PASS", rows, "gpu_asan", metadata) + + +# --------------------------------------------------------------------------- +# capture + + +class _Capture: + """Records Triton/Gluon launches: compiled kernel, grid, arguments, memory before and after.""" + + def __init__(self, output: Path): + self.output = output + self.launches: list[dict] = [] + self.skipped: list[str] = [] + self.bytes = 0 + self.active = False + + def _storage(self, tensor): + storage = tensor.untyped_storage() + return storage.data_ptr(), storage.nbytes(), storage + + def record(self, jit, args, kwargs, grid, run): + import torch + + if not self.active: + return run() + if len(self.launches) >= CAPTURE_MAX_LAUNCHES: + self.skipped.append(f"launch limit {CAPTURE_MAX_LAUNCHES}") + return run() + try: + # Launch options (num_warps, num_stages, ...) are not kernel parameters. + parameters = jit.signature.parameters + bound = jit.signature.bind(*args, **{k: v for k, v in kwargs.items() if k in parameters}) + bound.apply_defaults() + except TypeError as exc: + self.skipped.append(f"cannot bind arguments: {exc}") + return run() + storages, arguments = {}, [] + for index, (name, value) in enumerate(bound.arguments.items()): + if isinstance(value, torch.Tensor): + base, nbytes, storage = self._storage(value) + key = f"a{base:x}" + storages.setdefault(key, (base, nbytes, storage)) + arguments.append({"index": index, "name": name, "kind": "tensor", "allocation": key, + "byte_offset": value.data_ptr() - base}) + elif isinstance(value, bool) or isinstance(value, (int, float)) or value is None: + arguments.append({"index": index, "name": name, "kind": "value", "value": value}) + else: + arguments.append({"index": index, "name": name, "kind": "opaque", "type": type(value).__name__}) + total = sum(entry[1] for entry in storages.values()) + if self.bytes + 2 * total > CAPTURE_MAX_BYTES: + self.skipped.append(f"memory limit {CAPTURE_MAX_BYTES} bytes") + return run() + torch.cuda.synchronize() + before = {key: self._bytes(storage, nbytes) for key, (_, nbytes, storage) in storages.items()} + kernel = run() + torch.cuda.synchronize() + if kernel is None or not hasattr(kernel, "asm"): + self.skipped.append(f"{getattr(jit, '__name__', '?')}: the launch returned no compiled kernel") + return kernel + after = {key: self._bytes(storage, nbytes) for key, (_, nbytes, storage) in storages.items()} + self.bytes += 2 * total + meta = dict(bound.arguments) + launch_grid = grid(meta) if callable(grid) else grid + launch_grid = tuple(int(item) for item in launch_grid) + (1,) * (3 - len(tuple(launch_grid))) + self._save(kernel, launch_grid, arguments, before, after) + return kernel + + @staticmethod + def _bytes(storage, nbytes: int) -> bytes: + import torch + + if nbytes == 0: + return b"" + view = torch.empty(0, dtype=torch.uint8, device=storage.device).set_(storage, 0, (nbytes,), (1,)) + return view.cpu().numpy().tobytes() + + def _save(self, kernel, grid, arguments, before, after) -> None: + index = len(self.launches) + directory = self.output / f"launch-{index:02d}" + directory.mkdir(parents=True, exist_ok=True) + hsaco = kernel.asm.get("hsaco") if hasattr(kernel, "asm") else None + if not isinstance(hsaco, (bytes, bytearray)): + self.skipped.append(f"{getattr(kernel, 'name', '?')}: no hsaco") + return + name = str(kernel.name) + (directory / f"{name}.hsaco").write_bytes(bytes(hsaco)) + allocations = [] + for key in before: + (directory / f"{key}.before.bin").write_bytes(before[key]) + (directory / f"{key}.after.bin").write_bytes(after[key]) + allocations.append({"id": key, "byte_size": len(before[key]), "before_blob": f"{key}.before.bin", + "expected_blob": f"{key}.after.bin", "changed": before[key] != after[key]}) + metadata = getattr(kernel, "metadata", None) + + def field(name, default=0): + value = metadata.get(name, default) if isinstance(metadata, dict) else getattr(metadata, name, default) + return value if isinstance(value, (int, float, str, bool)) or value is None else str(value) + + source = getattr(kernel, "src", None) + signature = {str(key): str(value) for key, value in dict(getattr(source, "signature", {}) or {}).items()} + constants = {} + for key, value in dict(getattr(source, "constants", {}) or {}).items(): + constants[json.dumps(key if not isinstance(key, tuple) else list(key))] = ( + value if isinstance(value, (int, float, str, bool)) or value is None else str(value)) + record = {"kernel_name": name, "hsaco": f"{name}.hsaco", + "hsaco_sha256": hashlib.sha256(bytes(hsaco)).hexdigest(), "grid": list(grid), + "metadata": {key: field(key, default) for key, default in ( + ("num_warps", 4), ("warp_size", 64), ("shared", 0), ("profile_scratch_size", 0), + ("profile_scratch_align", 1), ("global_scratch_size", 0), ("global_scratch_align", 1), + ("target", ""))}, + "signature": signature, "constants": constants, + "arg_names": list(getattr(getattr(source, "fn", None), "arg_names", []) or []), + "arguments": arguments, "allocations": allocations} + (directory / "launch.json").write_text(json.dumps(record, indent=2, sort_keys=True), encoding="utf-8") + self.launches.append({"directory": directory.name, "kernel_name": name, + "hsaco": f"{directory.name}/{name}.hsaco", "hsaco_sha256": record["hsaco_sha256"]}) + + def install(self): + from triton.runtime.jit import JITFunction + + original = JITFunction.run + capture = self + + def run(self, *args, grid, warmup, **kwargs): + if warmup: + return original(self, *args, grid=grid, warmup=warmup, **kwargs) + return capture.record(self, args, kwargs, grid, + lambda: original(self, *args, grid=grid, warmup=warmup, **kwargs)) + + JITFunction.run = run + return original + + +def _flydsl_code_objects(observed: list, output: Path) -> list[dict]: + """Embedded HSACO of each FlyDSL compiled artifact observed during the call.""" + import re + + objects, seen = [], set() + for index, artifact in enumerate(observed): + text = getattr(artifact, "_ir_text", None) or getattr(artifact, "_source_ir", None) + if not isinstance(text, str): + continue + for match in re.finditer(r'bin\s*=\s*"((?:[^"\\]|\\.)*)"', text): + raw = re.sub(r"\\([0-9A-Fa-f]{2})", lambda m: chr(int(m.group(1), 16)), match.group(1)) + data = raw.encode("latin-1", errors="ignore") + if data[:4] != b"\x7fELF": + continue + digest = hashlib.sha256(data).hexdigest() + if digest in seen: + continue + seen.add(digest) + path = output / f"flydsl-{index:02d}.hsaco" + path.write_bytes(data) + objects.append({"code_object": path.name, "sha256": digest, "kernels": None}) + return objects + + +def capture(contract, role: str) -> dict: + evaluate = _evaluate() + output = Path(os.environ.get(OUTPUT_ENV, "")) + if not output.is_dir(): + raise evaluate.ActionFailure(f"{OUTPUT_ENV} must name an existing directory", "environment") + language = contract.implementation(role).language + if language not in ("triton", "gluon", "hip", "flydsl"): + raise evaluate.ActionFailure(f"Capture does not support {language}", "unsupported") + device = evaluate._device() + case = smallest_case(contract) + manifest = {"schema_version": CAPTURE_SCHEMA, "role": role, "language": language, "case": case.case_id, + "seed": case.seeds[0], "code_objects": [], "launches": [], "skipped": []} + # The recording hooks go in before the integrity snapshot that _load_role + # takes and stay until after its last check, so the evaluator's bindings + # are identical at every comparison. + recorder, original, observed, previous_profile = None, None, [], None + if language in ("triton", "gluon"): + recorder = _Capture(output) + original = recorder.install() + elif language == "flydsl": + previous_profile = sys.getprofile() + + def profile(frame, event, arg): + if event == "call" and frame.f_code.co_name == "__call__": + owner = frame.f_locals.get("self") + if owner is not None and (getattr(owner, "_ir_text", None) or getattr(owner, "_source_ir", None)): + if all(owner is not item for item in observed): + observed.append(owner) + + sys.setprofile(profile) + try: + # FlyDSL's launch audit would replace this lane's profile hook; the + # call keeps its integrity check and ran audited in correctness. + call, implementation, check = _load_role(contract, role, enforce=language != "flydsl") + if recorder is not None: + _run_once(contract, call, case, device) # warm-up: compile and finish any autotuning + recorder.active = True + _run_once(contract, call, case, device) + recorder.active = False + manifest["launches"] = recorder.launches + manifest["skipped"] = recorder.skipped + manifest["code_objects"] = [{"code_object": item["hsaco"], "sha256": item["hsaco_sha256"], + "kernels": [item["kernel_name"]]} for item in recorder.launches] + elif language == "hip": + _run_once(contract, call, case, device) + library = Path(implementation.get("library") or "") + objects = hip_code_objects(library, output) if library.is_file() else [] + manifest["code_objects"] = [{"code_object": item.name, + "sha256": hashlib.sha256(item.read_bytes()).hexdigest(), + "kernels": None} for item in objects] + if not objects: + manifest["skipped"].append("no device code object could be unbundled from the HIP extension") + else: + _run_once(contract, call, case, device) + manifest["code_objects"] = _flydsl_code_objects(observed, output) + if not manifest["code_objects"]: + manifest["skipped"].append("no FlyDSL code object was observed") + if check is not None: + check("sanitize") + finally: + if original is not None: + from triton.runtime.jit import JITFunction + + JITFunction.run = original + if language == "flydsl": + sys.setprofile(previous_profile) + (output / "capture.json").write_text(json.dumps(manifest, indent=2, sort_keys=True), encoding="utf-8") + metadata = {"code_objects": len(manifest["code_objects"]), "launches": len(manifest["launches"]), + "skipped": manifest["skipped"][:8]} + return _report(role, "PASS", [case.identity() | {"status": "PASS"}], "capture", metadata) + + +_LANES = {"page_fault_guard": page_fault_guard, "csan": csan, "tilelens": tilelens, "fpsan": fpsan, + "gpu_asan": gpu_asan, "capture": capture} + + +def run_lane(contract, role: str, lane: str) -> dict: + # A sidecar's /tmp may be mounted noexec; build HIP extensions in its + # scratch tree instead, where a built library can be loaded. + extensions = os.environ.get("TORCH_EXTENSIONS_DIR") + if extensions and not os.environ.get("AKA_KERNEL_CACHE_DIR"): + os.environ["AKA_KERNEL_CACHE_DIR"] = str(Path(extensions) / "aka-kernel-cache") + return _LANES[lane](contract, role) diff --git a/tests/eval_tools/test_config_merge.py b/tests/eval_tools/test_config_merge.py index fd982acd7..3e3033239 100644 --- a/tests/eval_tools/test_config_merge.py +++ b/tests/eval_tools/test_config_merge.py @@ -135,7 +135,7 @@ def test_native_sanitizer_runtime_assets_are_reserved(tool, key) -> None: ) -def test_enabled_true_expands_to_all_six_builtin_tools() -> None: +def test_enabled_true_expands_to_every_builtin_tool() -> None: parsed = EvalToolsConfig.from_mapping( {"evaluation_tools": {"enabled": True}} ) @@ -146,6 +146,9 @@ def test_enabled_true_expands_to_all_six_builtin_tools() -> None: "rocjitsu_waitcheck", "rocjitsu_consan", "hip_fpsan", + "page_fault_guard", + "csan", + "tilelens", ) diff --git a/tests/eval_tools/test_gluon_support.py b/tests/eval_tools/test_gluon_support.py index f0c4950e1..33efbe80d 100644 --- a/tests/eval_tools/test_gluon_support.py +++ b/tests/eval_tools/test_gluon_support.py @@ -65,8 +65,13 @@ def test_builtin_matrix_reports_unsupported_not_not_applicable(language): assert capability.engine.reason_code.endswith("_GLUON_UNSUPPORTED" if language == "gluon" else "_LANGUAGE_UNSUPPORTED") +# page_fault_guard, csan and tilelens exist only through the schema-v3 runner; +# test_v3_sanitizers covers their language handling. +V3_ONLY_TOOLS = {"page_fault_guard", "csan", "tilelens"} + + @pytest.mark.parametrize("language", [KernelLanguage.GLUON, KernelLanguage.UNKNOWN]) -@pytest.mark.parametrize("tool", sorted(plugin_ids())) +@pytest.mark.parametrize("tool", sorted(set(plugin_ids()) - V3_ONLY_TOOLS)) def test_plugins_fail_closed_for_gluon_and_unknown(tmp_path, tool, language): # Even a profile that claims framework=triton cannot revive a Gluon candidate. capability = get_plugin(tool).assess( diff --git a/tests/eval_tools/test_plugins.py b/tests/eval_tools/test_plugins.py index 1d1b43018..5309205a2 100644 --- a/tests/eval_tools/test_plugins.py +++ b/tests/eval_tools/test_plugins.py @@ -122,11 +122,14 @@ def replay_capsule(tmp_path: Path, adapter: str, *, arch: str = "gfx950") -> Pat def test_registry_uses_core_plugin_contracts(tmp_path): assert plugin_ids() == ( + "csan", "gpu_asan", "hip_fpsan", + "page_fault_guard", "rocjitsu", "rocjitsu_consan", "rocjitsu_waitcheck", + "tilelens", "triton_fpsan", ) plugin = get_plugin("triton-fpsan") @@ -143,11 +146,14 @@ def test_builtins_register_in_core_registry(): registry = register_builtin_plugins(requested) assert registry is requested assert tuple(registry) == ( + "csan", "gpu_asan", "hip_fpsan", + "page_fault_guard", "rocjitsu", "rocjitsu_consan", "rocjitsu_waitcheck", + "tilelens", "triton_fpsan", ) diff --git a/tests/eval_tools/test_reporting.py b/tests/eval_tools/test_reporting.py index c50abbb06..75d31a3b0 100644 --- a/tests/eval_tools/test_reporting.py +++ b/tests/eval_tools/test_reporting.py @@ -96,6 +96,7 @@ def test_summary_serialization_omits_raw_output_by_default(tmp_path): "plugin_version": "1.0", "timeout_s": 3600, "options": {}, + "role": "gate", } verbose = serialize_report(report, include_output=True) diff --git a/tests/eval_tools/test_v3_sanitizers.py b/tests/eval_tools/test_v3_sanitizers.py new file mode 100644 index 000000000..efd8db95e --- /dev/null +++ b/tests/eval_tools/test_v3_sanitizers.py @@ -0,0 +1,487 @@ +"""Schema-v3 sanitizer lanes: defaults, gate/signal roles, baseline rechecks and v3 adapters.""" +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass, replace +from pathlib import Path + +import pytest + +from src.eval_tools import defaults +from src.eval_tools.adapters.aka_v3_capsules import build_capsule, code_object_target +from src.eval_tools.adapters.replay_capsule import CapsuleValidationError, ReplayCapsule +from src.eval_tools.config import PLAN_SCHEMA_VERSION, EvalToolsConfig, build_evaluation_plan +from src.eval_tools.contracts import ( + CapabilityCheck, + CapabilityState, + EvaluationPolicy, + ExecutionRecord, + ExecutionStatus, + Finding, + FindingSeverity, + FindingStatus, + ToolCapability, + ToolContext, + ToolEvaluation, + ToolInvocation, + ToolRole, + ToolRunResult, +) +from src.eval_tools.manager import BASELINE_ALSO_FOUND, EvalToolManager, evaluate_policy +from src.eval_tools.plugins import aka_v3, get_plugin, v3_tools +from src.eval_tools.registry import ToolRegistry +from src.eval_tools.task_profile import resolve_task_profile + +PREFIX = "ARENA_EVAL_RESULT=" + + +def v3_config(target: str = "triton", baseline: str = "triton") -> dict: + entry = "solution/kernel.hip" if target == "hip" else "solution/kernel.py" + return { + "schema_version": 2, + "task_id": "activation/silu/f32", + "candidate": {"language": target, "initial_state": "implemented", + "editable": [{"path": "solution", "scope": "tree"}], + "entrypoints": [{"file": entry, "kind": "function", "symbol": "run"}]}, + "baseline": {"kind": "provided", "language": baseline, "source_files": ["baseline/kernel.py"]}, + "evaluation": {"workloads": "workloads.json"}, + "contract": {"schema_version": 3, "task_file": "task.yaml", "target_language": target, + "baseline_language": baseline, "operator": {"name": "silu", "category": "activation"}}, + } + + +def v3_context(tmp_path: Path, target="triton", baseline="triton", options=None, gpu_arch="gfx950") -> ToolContext: + config = v3_config(target, baseline) + (tmp_path / "artifacts").mkdir(parents=True, exist_ok=True) + return ToolContext(workspace=str(tmp_path), task_config=config, profile=resolve_task_profile(config), + artifact_dir=str(tmp_path / "artifacts"), gpu_arch=gpu_arch, options=options or {}) + + +def report(lane: str, status: str = "PASS", **fields) -> str: + body = {"protocol": "arena-eval-v1", "role": "candidate", "action": "sanitize", "status": status, + "cases": fields.pop("cases", []), "metadata": {"lane": lane, **fields.pop("metadata", {})}, **fields} + return PREFIX + json.dumps(body) + + +def execution(stdout="", stderr="", returncode=0, timed_out=False) -> ExecutionRecord: + return ExecutionRecord(command=("python",), returncode=returncode, stdout=stdout, stderr=stderr, + timed_out=timed_out) + + +# ------------------------------------------------------------------ defaults + + +def test_runner_starts_defaults_only_without_a_section_on_a_default_architecture(): + assert defaults.runner_selection({}, "gfx950") == defaults.DEFAULT_ENABLED + assert defaults.runner_selection({"agent": {}}, "gfx942") == () + assert defaults.runner_selection({"evaluation_tools": False}, "gfx950") == () + assert defaults.runner_selection({"evaluation_tools": {"enabled": []}}, "gfx950") == () + assert defaults.runner_selection({"evaluation_tools": {"enabled": ["gpu_asan"]}}, "gfx950") == ("gpu_asan",) + assert defaults.runner_selection({"evaluation_tools": {"enabled": True}}, "gfx950") == defaults.ALL_TOOLS + assert "gpu_asan" not in defaults.DEFAULT_ENABLED + + +def test_defaults_name_every_registered_tool(): + from src.eval_tools.contracts import ToolName + + assert set(defaults.ALL_TOOLS) == {tool.value for tool in ToolName} + assert set(defaults.DEFAULT_ENABLED) <= set(defaults.ALL_TOOLS) + + +def test_missing_section_plans_the_runner_started_set_under_the_gated_policy(monkeypatch): + monkeypatch.delenv("AKA_EVAL_TOOLS_SELECTED", raising=False) + assert EvalToolsConfig.from_mapping({"agent": {"template": "x"}}).enabled == () + monkeypatch.setenv("AKA_EVAL_TOOLS_SELECTED", ",".join(defaults.DEFAULT_ENABLED)) + parsed = EvalToolsConfig.from_mapping({"agent": {"template": "x"}}) + assert parsed.enabled == defaults.DEFAULT_ENABLED + assert parsed.policy == EvaluationPolicy.GATED + roles = {tool.name: tool.role for tool in parsed.tools} + assert roles["triton_fpsan"] == ToolRole.SIGNAL + assert roles["page_fault_guard"] == roles["rocjitsu"] == ToolRole.GATE + + +def test_role_is_configurable_validated_and_part_of_the_plan(): + parsed = EvalToolsConfig.from_mapping({"evaluation_tools": { + "policy": "gated", "enabled": ["csan", "triton_fpsan"], + "tools": {"csan": {"role": "signal"}}}}) + assert {tool.name: tool.role for tool in parsed.tools} == {"csan": ToolRole.SIGNAL, + "triton_fpsan": ToolRole.SIGNAL} + plan = build_evaluation_plan(config=parsed, profile=resolve_task_profile(v3_config()), + plugin_versions={"csan": "1", "triton_fpsan": "2"}) + assert plan.schema_version == PLAN_SCHEMA_VERSION == 3 + assert [item.to_dict()["role"] for item in plan.tools] == ["signal", "signal"] + with pytest.raises(ValueError, match="role must be gate or signal"): + EvalToolsConfig.from_mapping({"evaluation_tools": {"enabled": ["csan"], "tools": {"csan": {"role": "x"}}}}) + + +# -------------------------------------------------------------------- policy + + +def _evaluation(tool: str, finding: FindingStatus, *, metadata=None, ready=True) -> ToolEvaluation: + runtime = CapabilityCheck.ready() if ready else CapabilityCheck.blocked( + CapabilityState.UNAVAILABLE_RUNTIME, "down", "down") + capability = ToolCapability(tool, CapabilityCheck.ready(), CapabilityCheck.ready(), runtime) + if not ready: + return ToolEvaluation(capability=capability) + findings = (Finding(kind="x", severity=FindingSeverity.ERROR, message="x"),) \ + if finding == FindingStatus.FOUND else () + execution_status = ExecutionStatus.COMPLETED if finding != FindingStatus.INCONCLUSIVE else ExecutionStatus.TOOL_ERROR + return ToolEvaluation(capability=capability, result=ToolRunResult( + tool=tool, execution=execution_status, finding=finding, findings=findings, metadata=metadata or {})) + + +def test_gated_policy_blocks_only_on_an_unshared_gate_finding(): + roles = {"page_fault_guard": ToolRole.GATE, "triton_fpsan": ToolRole.SIGNAL, "csan": ToolRole.GATE} + clean = evaluate_policy(EvaluationPolicy.GATED, (_evaluation("page_fault_guard", FindingStatus.CLEAN),), roles) + assert clean.allowed and clean.policy_satisfied + found = evaluate_policy(EvaluationPolicy.GATED, (_evaluation("page_fault_guard", FindingStatus.FOUND),), roles) + assert not found.allowed and found.blocking == ("page_fault_guard:finding:found",) + shared = evaluate_policy(EvaluationPolicy.GATED, (_evaluation( + "page_fault_guard", FindingStatus.FOUND, metadata={BASELINE_ALSO_FOUND: True}),), roles) + assert shared.allowed and not shared.policy_satisfied + signal = evaluate_policy(EvaluationPolicy.GATED, (_evaluation("triton_fpsan", FindingStatus.FOUND),), roles) + assert signal.allowed and not signal.policy_satisfied + unverified = evaluate_policy(EvaluationPolicy.GATED, ( + _evaluation("csan", FindingStatus.INCONCLUSIVE), _evaluation("page_fault_guard", FindingStatus.CLEAN, + ready=False)), roles) + assert unverified.allowed and not unverified.policy_satisfied and unverified.blocking == () + assert "csan:execution:tool_error" in unverified.reasons + + +@dataclass +class RolePlugin: + """Finds a bug for each role in ``found_for``.""" + + found_for: tuple = ("candidate",) + name: str = "page_fault_guard" + version: str = "1" + baseline_check: bool = True + + def assess(self, context, runtime): + return ToolCapability(self.name, CapabilityCheck.ready(), CapabilityCheck.ready(), runtime) + + def build_invocation(self, context): + return ToolInvocation(tool=self.name, command=("lane", aka_v3.role(context)), cwd=context.workspace, + timeout_s=5) + + def parse(self, context, execution): + role = execution.command[-1] + if role in self.found_for: + return ToolRunResult(tool=self.name, execution=ExecutionStatus.COMPLETED, finding=FindingStatus.FOUND, + findings=(Finding(kind="fault", severity=FindingSeverity.ERROR, message=role),)) + return ToolRunResult(tool=self.name, execution=ExecutionStatus.COMPLETED, finding=FindingStatus.CLEAN) + + +class EchoRuntime: + def __init__(self): + self.commands = [] + + def probe(self, tool, context): + return CapabilityCheck.ready() + + def execute(self, invocation, context): + self.commands.append(invocation.command) + return ExecutionRecord(command=invocation.command, returncode=0) + + +@pytest.mark.parametrize("found_for,allowed,shared", [ + (("candidate",), False, False), + (("candidate", "baseline"), True, True), + ((), True, False), +]) +def test_a_gate_finding_is_rechecked_on_the_baseline(tmp_path, found_for, allowed, shared): + registry = ToolRegistry() + registry.register(RolePlugin(found_for=found_for)) + runtime = EchoRuntime() + config = EvalToolsConfig.from_mapping({"evaluation_tools": {"policy": "gated", "enabled": ["page_fault_guard"]}}) + report = EvalToolManager(registry, runtime).evaluate( + workspace=tmp_path, task_config=v3_config(), config=config, gpu_arch="gfx950", + artifact_root=tmp_path / "reports") + assert report.decision.allowed is allowed + result = report.evaluations[0].result + if found_for: + assert runtime.commands == [("lane", "candidate"), ("lane", "baseline")] + assert bool(result.metadata.get(BASELINE_ALSO_FOUND)) is shared + assert result.metadata["baseline_check"]["finding"] == ("found" if shared else "clean") + else: + assert runtime.commands == [("lane", "candidate")] + + +# ----------------------------------------------------------- v3 lane plugins + + +@pytest.mark.parametrize("tool,language,state", [ + ("page_fault_guard", "flydsl", CapabilityState.READY), + ("page_fault_guard", "gluon", CapabilityState.READY), + ("csan", "hip", CapabilityState.READY), + ("tilelens", "gluon", CapabilityState.READY), + ("tilelens", "hip", CapabilityState.NOT_APPLICABLE), + ("tilelens", "flydsl", CapabilityState.NOT_APPLICABLE), + ("csan", "tilelang", CapabilityState.UNSUPPORTED), +]) +def test_v3_lane_capability_by_language(tmp_path, tool, language, state): + capability = get_plugin(tool).assess(v3_context(tmp_path, target=language), CapabilityCheck.ready()) + assert capability.effective.state == state + + +def test_v3_lanes_do_not_apply_without_the_v3_runner(tmp_path): + plain = replace(v3_context(tmp_path), task_config={"schema_version": 2}) + capability = get_plugin("page_fault_guard").assess(plain, CapabilityCheck.ready()) + assert capability.effective.state == CapabilityState.NOT_APPLICABLE + + +def test_lane_invocation_runs_the_workspace_runner_with_the_lane_environment(tmp_path): + invocation = get_plugin("page_fault_guard").build_invocation(v3_context(tmp_path)) + assert invocation.command[1:] == ("-m", "_aka_eval.evaluate", "candidate", "sanitize", "page_fault_guard") + assert invocation.cwd == str(tmp_path) + assert invocation.env["PYTHONPATH"] == "" + assert all(invocation.env[key] == value for key, value in aka_v3.NO_CACHING.items()) + baseline = get_plugin("page_fault_guard").build_invocation(v3_context(tmp_path, options={"aka_role": "baseline"})) + assert baseline.command[3] == "baseline" + with pytest.raises(ValueError): + aka_v3.role(v3_context(tmp_path, options={"aka_role": "reference"})) + + +def _parse(tool, tmp_path, record): + return get_plugin(tool).parse(v3_context(tmp_path), record) + + +def test_page_fault_guard_verdicts(tmp_path): + fault = _parse("page_fault_guard", tmp_path, execution(stderr="Memory access fault by GPU node-2 on address 0x7f", + returncode=-6)) + assert fault.finding == FindingStatus.FOUND and fault.findings[0].kind == "gpu-memory-fault" + environment = dict(aka_v3.NO_CACHING) + clean = _parse("page_fault_guard", tmp_path, execution(report("page_fault_guard", + metadata={"environment": environment}))) + assert clean.finding == FindingStatus.CLEAN + unattested = _parse("page_fault_guard", tmp_path, execution(report("page_fault_guard"))) + assert unattested.finding == FindingStatus.INCONCLUSIVE + sensitive = _parse("page_fault_guard", tmp_path, execution(report( + "page_fault_guard", "FAIL", failure_kind="numerical_mismatch", reason="1 case failed"), returncode=1)) + assert sensitive.finding == FindingStatus.FOUND and sensitive.findings[0].kind == "allocator-sensitive-output" + crashed = _parse("page_fault_guard", tmp_path, execution(report( + "page_fault_guard", "FAIL", failure_kind="execution_error", reason="x", + cases=[{"metadata": {"error": "AcceleratorError: CUDA error: an illegal memory access was encountered"}}]), + returncode=1)) + assert crashed.finding == FindingStatus.FOUND + + +@pytest.mark.parametrize("stdout", [ + "", + report("page_fault_guard") + "\nprinted after the report", + report("page_fault_guard") + "\n" + report("page_fault_guard"), + PREFIX + "{not json", +]) +def test_an_unusable_lane_report_is_never_clean(tmp_path, stdout): + result = _parse("page_fault_guard", tmp_path, execution(stdout)) + assert result.finding == FindingStatus.INCONCLUSIVE + assert result.execution == ExecutionStatus.TOOL_ERROR + + +def test_csan_verdicts(tmp_path): + race = _parse("csan", tmp_path, execution(report("csan", "FAIL", failure_kind="data_race", + metadata={"races": ["CUDASanitizerErrors: detected 1 errors"]}), + returncode=1)) + assert race.finding == FindingStatus.FOUND and race.findings[0].kind == "stream-data-race" + assert _parse("csan", tmp_path, execution(report("csan", metadata={"enabled": True}))).finding == \ + FindingStatus.CLEAN + assert _parse("csan", tmp_path, execution(report("csan", metadata={"enabled": False}))).finding == \ + FindingStatus.INCONCLUSIVE + + +def test_tilelens_verdicts(tmp_path): + violation = {"op": "Load", "tensor": "x", "address": "0x10", "location": ["kernel.py:18"]} + found = _parse("tilelens", tmp_path, execution(report("tilelens", "FAIL", failure_kind="out_of_bounds", + metadata={"violations": [violation]}), returncode=1)) + assert found.finding == FindingStatus.FOUND and "kernel.py:18" in found.findings[0].locations[0] + unanalyzable = _parse("tilelens", tmp_path, execution(report("tilelens", "FAIL", failure_kind="unanalyzable"), + returncode=1)) + assert unanalyzable.finding == FindingStatus.INCONCLUSIVE + approximated = _parse("tilelens", tmp_path, execution(report("tilelens", metadata={ + "approximations": ["Triton inline assembly is approximated"]}))) + assert approximated.finding == FindingStatus.INCONCLUSIVE + assert _parse("tilelens", tmp_path, execution(report("tilelens"))).finding == FindingStatus.CLEAN + + +# -------------------------------------------------- original tools on v3 + + +@pytest.mark.parametrize("target,baseline,state", [ + ("triton", "triton", CapabilityState.READY), + ("gluon", "triton", CapabilityState.READY), + ("triton", "hip", CapabilityState.NOT_APPLICABLE), + ("hip", "hip", CapabilityState.NOT_APPLICABLE), +]) +def test_fpsan_compares_only_triton_or_gluon_pairs(tmp_path, target, baseline, state): + capability = get_plugin("triton_fpsan").assess(v3_context(tmp_path, target, baseline), + CapabilityCheck.ready(triton_fpsan=True)) + assert capability.effective.state == state + + +def test_fpsan_v3_invocation_is_the_fpsan_lane(tmp_path): + invocation = get_plugin("triton_fpsan").build_invocation(v3_context(tmp_path, "gluon", "triton")) + assert invocation.command[-3:] == ("candidate", "sanitize", "fpsan") + assert invocation.env["TRITON_INSTRUMENTATION_MODE"] == "fpsan" + assert invocation.env["AKA_BUILD_ATTESTATION_PATH"].endswith("build_attestation.json") + + +_ASAN_RUNTIME = {"host_asan_preload": "/opt/rocm-asan/lib/libclang_rt.asan-x86_64.so", + "hip_asan_runtime": "/opt/rocm-asan/lib/libamdhip64.so", + "hsa_asan_runtime": "/opt/rocm-asan/lib/libhsa-runtime64.so", + "asan_runtime_dir": "/opt/rocm-asan/lib"} + + +@pytest.mark.parametrize("language,state", [("hip", CapabilityState.READY), ("gluon", CapabilityState.READY), + ("flydsl", CapabilityState.UNSUPPORTED)]) +def test_gpu_asan_v3_languages(tmp_path, language, state): + capability = get_plugin("gpu_asan").assess(v3_context(tmp_path, language, language), + CapabilityCheck.ready(xnack_supported=True, triton_asan=True)) + assert capability.effective.state == state + + +def test_gpu_asan_v3_invocations(tmp_path): + hip = get_plugin("gpu_asan").build_invocation(v3_context(tmp_path, "hip", "hip", options=_ASAN_RUNTIME)) + assert hip.command[-3:] == ("candidate", "sanitize", "gpu_asan") + assert hip.env["AKA_HIP_SANITIZER_CFLAGS"] == "-fsanitize=address -shared-libsan" + assert hip.env["AKA_HIP_OFFLOAD_ARCH"] == "gfx950:xnack+" + assert hip.env["HSA_XNACK"] == "1" and "libamdhip64.so" in hip.env["LD_PRELOAD"] + gluon = get_plugin("gpu_asan").build_invocation(v3_context(tmp_path, "gluon", "gluon", options=_ASAN_RUNTIME)) + assert gluon.env["TRITON_ENABLE_ASAN"] == "1" and gluon.env["AMDGCN_USE_BUFFER_OPS"] == "0" + assert all(gluon.env[key] == value for key, value in aka_v3.NO_CACHING.items()) + + +@pytest.mark.parametrize("language,state", [("triton", CapabilityState.READY), ("gluon", CapabilityState.READY), + ("hip", CapabilityState.UNSUPPORTED), + ("flydsl", CapabilityState.UNSUPPORTED)]) +def test_rocjitsu_v3_replays_only_captured_triton_and_gluon_launches(tmp_path, language, state): + assert get_plugin("rocjitsu").assess(v3_context(tmp_path, language, language), + CapabilityCheck.ready()).effective.state == state + + +def test_waitcheck_v3_runs_on_every_language_and_only_on_gfx950(tmp_path): + for language in ("triton", "gluon", "hip", "flydsl"): + assert get_plugin("rocjitsu_waitcheck").assess(v3_context(tmp_path, language, language), + CapabilityCheck.ready()).ready + other = get_plugin("rocjitsu_waitcheck").assess(v3_context(tmp_path, gpu_arch="gfx942"), CapabilityCheck.ready()) + assert other.effective.state == CapabilityState.UNSUPPORTED + + +def _waitcheck_payload(sha: str, kernel: str, diagnostics=()): + payload = {"schema_version": 1, "code_object_sha256": sha, "target": "gfx950", "expected_kernel": kernel, + "kernel_entry": 64, "inventory_attested": True, "api_status": 0, "analysis_complete": True, + "diagnostics_truncated": False, "stopped_early": False, "kernels_discovered": 1, + "kernels_analyzed": 1, "instructions_analyzed": 10, "memory_events_tracked": 2, + "diagnostics_observed": len(diagnostics), "diagnostics_reported": len(diagnostics), + "diagnostics": list(diagnostics), "passed": not diagnostics} + return "AKA_WAITCHECK_RESULT " + json.dumps(payload) + + +def _waitcheck_artifacts(tmp_path, entries, *, sha="a" * 64): + context = v3_context(tmp_path) + output = Path(context.artifact_dir) / "v3-waitcheck" + (output / "capture").mkdir(parents=True) + (output / "capture" / "capture.json").write_text(json.dumps({ + "schema_version": 1, "code_objects": [{"code_object": "k.hsaco", "sha256": sha, "kernels": ["k"]}], + "launches": [], "skipped": []})) + index = {"schema_version": 1, "entries": [], "skipped": []} + for number, text in enumerate(entries): + log = output / "kernels" / f"{number}.log" + log.parent.mkdir(parents=True, exist_ok=True) + log.write_text(text) + index["entries"].append({"code_object": "k.hsaco", "code_object_sha256": sha, "kernel_name": "k", + "kernel_entry": 64, "returncode": 0, "log": f"kernels/{number}.log"}) + (output / "index.json").write_text(json.dumps(index)) + return context + + +def test_waitcheck_v3_aggregates_one_parse_per_kernel(tmp_path): + sha = "a" * 64 + clean = get_plugin("rocjitsu_waitcheck").parse( + _waitcheck_artifacts(tmp_path / "clean", [_waitcheck_payload(sha, "k")]), execution()) + assert clean.finding == FindingStatus.CLEAN + hazard = {"kernel_name": "k", "kernel_entry": 64, "code": "missing_wait", "message": "s_waitcnt missing", + "section_name": ".text", "section_offset": 32} + found = get_plugin("rocjitsu_waitcheck").parse( + _waitcheck_artifacts(tmp_path / "found", [_waitcheck_payload(sha, "k"), + _waitcheck_payload(sha, "k", [hazard])]), execution()) + assert found.finding == FindingStatus.FOUND and found.findings[0].kind == "wait-hazard-missing_wait" + nothing = get_plugin("rocjitsu_waitcheck").parse(_waitcheck_artifacts(tmp_path / "none", []), execution()) + assert nothing.finding == FindingStatus.INCONCLUSIVE + + +def test_waitcheck_v3_rejects_a_code_object_that_was_not_captured(tmp_path): + context = _waitcheck_artifacts(tmp_path, [_waitcheck_payload("b" * 64, "k")]) + index_path = Path(context.artifact_dir) / "v3-waitcheck" / "index.json" + index = json.loads(index_path.read_text()) + index["entries"][0]["code_object_sha256"] = "b" * 64 + index_path.write_text(json.dumps(index)) + assert get_plugin("rocjitsu_waitcheck").parse(context, execution()).finding == FindingStatus.INCONCLUSIVE + + +# ----------------------------------------------------------------- capsules + + +def _hsaco(abi_version: int = 3, xnack_on: bool = False) -> bytes: + header = bytearray(64) + header[:4] = b"\x7fELF" + header[8] = abi_version + header[0x30:0x34] = (0x300 if xnack_on else 0x200).to_bytes(4, "little") + return bytes(header) + + +def _launch_dir(tmp_path: Path) -> Path: + directory = tmp_path / "launch-00" + directory.mkdir() + hsaco = _hsaco() + (directory / "copy_kernel.hsaco").write_bytes(hsaco) + before, after = bytes(range(16)), bytes(range(16, 32)) + for key in ("a1", "a2"): + (directory / f"{key}.before.bin").write_bytes(before) + (directory / f"{key}.after.bin").write_bytes(after if key == "a2" else before) + record = { + "kernel_name": "copy_kernel", "hsaco": "copy_kernel.hsaco", "hsaco_sha256": hashlib.sha256(hsaco).hexdigest(), + "grid": [4, 1, 1], "metadata": {"num_warps": 4, "warp_size": 64, "shared": 0, "profile_scratch_size": 0, + "profile_scratch_align": 1, "global_scratch_size": 0}, + "signature": {"source": "*fp32", "destination": "*fp32", "n": "i32", "BLOCK": "constexpr"}, + "constants": {json.dumps(["BLOCK"]): 1024}, "arg_names": ["source", "destination", "n", "BLOCK"], + "arguments": [{"index": 0, "kind": "tensor", "allocation": "a1", "byte_offset": 0}, + {"index": 1, "kind": "tensor", "allocation": "a2", "byte_offset": 0}, + {"index": 2, "kind": "value", "value": 4}, {"index": 3, "kind": "value", "value": 1024}], + "allocations": [{"id": key, "byte_size": 16, "before_blob": f"{key}.before.bin", + "expected_blob": f"{key}.after.bin", "changed": key == "a2"} for key in ("a1", "a2")], + } + (directory / "launch.json").write_text(json.dumps(record)) + return directory + + +def test_a_captured_launch_becomes_a_validated_replay_capsule(tmp_path): + directory = _launch_dir(tmp_path) + path = build_capsule(directory, manifest={"case": "t1", "seed": 7, "role": "candidate"}, task_id="t", + image_digest="sha256:image", rocm_version="10.0.0", framework_version="3.8.0") + capsule = ReplayCapsule.load(path, verify_files=True) + assert capsule.code_object.kernel_name == "copy_kernel" + assert capsule.launch.grid == (4, 1, 1) and capsule.launch.block == (256, 1, 1) + assert [arg.kind for arg in capsule.abi] == ["pointer", "pointer", "scalar", "implicit", "implicit"] + assert capsule.target.code_object_version == 5 and capsule.target.xnack is False + + +def test_a_changed_captured_hsaco_is_rejected(tmp_path): + directory = _launch_dir(tmp_path) + (directory / "copy_kernel.hsaco").write_bytes(_hsaco(abi_version=4)) + with pytest.raises(CapsuleValidationError, match="hash"): + build_capsule(directory, manifest={}, task_id="t", image_digest="d", rocm_version="r", framework_version="f") + + +def test_code_object_target_reads_the_elf_header(): + assert code_object_target(_hsaco(2, True)) == (4, True) + with pytest.raises(CapsuleValidationError): + code_object_target(b"\x00" * 64) + + +def test_v3_aggregate_is_partial_when_any_kernel_is_unverified(): + from src.eval_tools.plugins.base import PASS, ParseResult + + clean = ParseResult(PASS, reason_code="ok", attested=True) + assert v3_tools.aggregate("x", [clean], []).status == PASS + assert v3_tools.aggregate("x", [clean], ["launch-01: capsule: tensor descriptor"]).status == "inconclusive" diff --git a/tests/test_arena_eval_sanitize.py b/tests/test_arena_eval_sanitize.py new file mode 100644 index 000000000..8b1d67432 --- /dev/null +++ b/tests/test_arena_eval_sanitize.py @@ -0,0 +1,122 @@ +"""CPU checks of the v3 runner's sanitizer lanes: build flags, routing, environment and helpers.""" +from __future__ import annotations + +import struct + +import pytest + +from src.tools.arena_eval import evaluate, loader, sanitize +from src.tools.arena_eval.contract import Contract + + +def test_sanitizer_build_flags_are_an_allowlist(monkeypatch): + monkeypatch.delenv(loader.SANITIZER_CFLAGS_ENV, raising=False) + assert loader.hip_build_flags() == ("-O3",) + monkeypatch.setenv(loader.SANITIZER_CFLAGS_ENV, "-fsanitize=address -shared-libsan") + assert loader.hip_build_flags() == ("-O3", "-fsanitize=address", "-shared-libsan") + monkeypatch.setenv(loader.SANITIZER_CFLAGS_ENV, "-fsanitize=address -mllvm -x") + with pytest.raises(loader.BuildError, match="accepts only"): + loader.hip_build_flags() + + +def test_offload_arch_override_must_qualify_the_device(monkeypatch): + monkeypatch.setattr(loader, "current_arch", lambda: "gfx950") + monkeypatch.delenv(loader.SANITIZER_ARCH_ENV, raising=False) + assert loader.hip_build_arch() == "gfx950" + monkeypatch.setenv(loader.SANITIZER_ARCH_ENV, "gfx950:xnack+") + assert loader.hip_build_arch() == "gfx950:xnack+" + for bad in ("gfx942:xnack+", "gfx950 -O0", "gfx950:xnack"): + monkeypatch.setenv(loader.SANITIZER_ARCH_ENV, bad) + with pytest.raises(loader.BuildError): + loader.hip_build_arch() + + +def test_the_build_hash_changes_with_the_sanitizer_flags(monkeypatch): + monkeypatch.delenv(loader.SANITIZER_CFLAGS_ENV, raising=False) + plain = loader._toolchain() + monkeypatch.setenv(loader.SANITIZER_CFLAGS_ENV, "-fsanitize=address -shared-libsan") + assert loader._toolchain() != plain + + +def test_sanitize_is_routed_only_for_known_lanes(monkeypatch): + monkeypatch.setattr(evaluate, "load_contract", lambda: object()) + called = {} + monkeypatch.setattr(sanitize, "run_lane", lambda contract, role, lane: called.setdefault( + "args", (role, lane)) and evaluate._report(role, "sanitize", "PASS", [], metadata={"lane": lane})) + report, code = evaluate.run(["candidate", "sanitize", "page_fault_guard"]) + assert code == 0 and report["action"] == "sanitize" and called["args"] == ("candidate", "page_fault_guard") + report, code = evaluate.run(["candidate", "sanitize", "valgrind"]) + assert code == 2 and report["failure_kind"] == "usage" + + +def test_a_lane_refuses_to_run_without_its_environment(monkeypatch): + for key in sanitize.NO_CACHING: + monkeypatch.delenv(key, raising=False) + with pytest.raises(evaluate.ActionFailure) as error: + sanitize.page_fault_guard(object(), "candidate") + assert error.value.kind == "environment" + + +def _contract() -> Contract: + return Contract({ + "version": 1, "task_id": "t", "axes": {"n": {"kind": "var"}}, "derived_axes": {}, + "inputs": {"x": {"kind": "tensor", "shape": ["n"], "dtype": "float32"}}, + "outputs": {"out": {"shape": ["n"], "dtype": "float32"}}, + "compare": {"out": {}}, "timing": {}, "reference": {"file": "reference.py", "symbol": "reference"}, + "baseline": {"language": "triton", "root": "baseline", "entry_file": "baseline/kernel.py", "symbol": "run"}, + "candidate": {"language": "triton", "root": "solution", "entry_file": "solution/kernel.py", "symbol": "run"}, + "cases": [{"id": "big", "axes": {"n": 4096}, "checks": ["correctness"], "seeds": [1, 2]}, + {"id": "small", "axes": {"n": 3}, "checks": ["correctness"], "seeds": [3, 4]}, + {"id": "mid", "axes": {"n": 64}, "checks": ["correctness"], "seeds": [5, 6]}], + }) + + +def test_the_smallest_case_is_chosen_by_element_count(): + assert sanitize.smallest_case(_contract()).case_id == "small" + + +def _elf(sections: dict[str, bytes]) -> bytes: + """A minimal 64-bit little-endian ELF holding ``sections`` and a string table.""" + names = b"\0" + b"".join(name.encode() + b"\0" for name in [*sections, ".shstrtab"]) + body, offsets = b"", {} + for name, data in sections.items(): + offsets[name] = 64 + len(body) + body += data + shstr_offset = 64 + len(body) + body += names + shoff = 64 + len(body) + header = bytearray(64) + header[:6] = b"\x7fELF\x02\x01" + struct.pack_into("> "$DEEPSEEK_CONFIG" +# Image selection only: keep the default sanitizer sidecars out of this argv. +printf 'evaluation_tools: false\n' >> "$DEEPSEEK_CONFIG" IMAGE_TEST_HOME="$TEST_HOME/image-home" IMAGE_TEST_PREFIX="$TEST_HOME/image-node" mkdir -p "$IMAGE_TEST_HOME/.claude" "$IMAGE_TEST_PREFIX/bin" @@ -1283,7 +1285,7 @@ fi # the scoring container: no network, no credentials, no privileged mode, and # only immutable input plus explicit scratch/artifact/socket writes. EVAL_FRAMEWORK_ROOT="/opt/aka-eval-tools" -for eval_image in triton-fpsan gpu-asan rocjitsu hip-fpsan; do +for eval_image in triton-fpsan gpu-asan rocjitsu hip-fpsan page-fault-guard csan tilelens; do eval_dockerfile="$ROOT/docker/eval-tools/$eval_image/Dockerfile" grep -Fq "COPY src/eval_tools $EVAL_FRAMEWORK_ROOT/src/eval_tools" "$eval_dockerfile" \ || fail "$eval_dockerfile does not bake the evaluation framework" @@ -1292,6 +1294,22 @@ for eval_image in triton-fpsan gpu-asan rocjitsu hip-fpsan; do grep -Fq "PYTHONPATH=$EVAL_FRAMEWORK_ROOT" "$eval_dockerfile" \ || fail "$eval_dockerfile does not default imports to its baked framework" done +# A config without an evaluation_tools section starts the default sanitizers on +# gfx950 only; false or an explicit list keeps full control. +EVAL_DEFAULT_CONFIG="$TEST_HOME/eval-defaults.yaml" +printf 'tasks: []\n' > "$EVAL_DEFAULT_CONFIG" +defaults_gfx950="$(bash "$RUNNER" _resolve_eval_tools "$EVAL_DEFAULT_CONFIG" gfx950 | tr '\n' ' ')" +[[ "$defaults_gfx950" == "page_fault_guard csan tilelens triton_fpsan rocjitsu_waitcheck rocjitsu " ]] \ + || fail "default evaluation tools on gfx950 were: $defaults_gfx950" +[[ -z "$(bash "$RUNNER" _resolve_eval_tools "$EVAL_DEFAULT_CONFIG" gfx942)" ]] \ + || fail "default evaluation tools must stay off on gfx942" +printf 'tasks: []\nevaluation_tools: false\n' > "$EVAL_DEFAULT_CONFIG" +[[ -z "$(bash "$RUNNER" _resolve_eval_tools "$EVAL_DEFAULT_CONFIG" gfx950)" ]] \ + || fail "evaluation_tools: false must disable the default sanitizers" +printf 'tasks: []\nevaluation_tools:\n enabled: [gpu_asan, csan]\n' > "$EVAL_DEFAULT_CONFIG" +[[ "$(bash "$RUNNER" _resolve_eval_tools "$EVAL_DEFAULT_CONFIG" gfx950 | tr '\n' ' ')" == "gpu_asan csan " ]] \ + || fail "an explicit evaluation_tools.enabled list must be used as given" + framework_record="$( env -u AKA_EVAL_TOOL_FRAMEWORK_ROOT PYTHONDONTWRITEBYTECODE=1 python3 - <<'PY' from pathlib import Path diff --git a/tests/test_score.py b/tests/test_score.py index 87b72fdf9..613d1ddb6 100644 --- a/tests/test_score.py +++ b/tests/test_score.py @@ -141,3 +141,13 @@ def test_task_result_scores_explicit_mean_speedup_and_preserves_measurements(tmp assert calculated == pytest.approx(0.3) assert yaml.safe_load(result_file.read_text()) == {**result, "score": calculated} + + +def test_a_blocking_tool_gate_scores_zero_even_with_a_recorded_speedup(tmp_path): + result = { + "pass_compilation": True, "pass_correctness": True, "pass_tool_gate": False, + "base_execution_time": 50.5, "best_optimized_execution_time": 25.5, + "speedup_ratio": 1.5, "benchmark_method_consistent": True, + } + (tmp_path / "task_result.yaml").write_text(yaml.safe_dump(result)) + assert task_result_scoring(str(tmp_path)) == 0.0 From 7117dcda52f6cc6cedddc66715aeac4ba199366d Mon Sep 17 00:00:00 2001 From: Vincent Ouyang Date: Tue, 10 Nov 2026 20:54:43 -0800 Subject: [PATCH 2/9] Pull tool-image bases through the daemon and fix probe users - Before building an evaluation-tool image, pull each pinned BASE_IMAGE and BUILDER_IMAGE through the Docker daemon, which BuildKit then uses locally. On hosts whose registry TLS only the daemon trusts, BuildKit otherwise fails to fetch the rocJITsu builder image. - The CSAN startup control imports torch._dynamo, whose cache path calls getpass. Give the new probes and lanes USER, LOGNAME and an inductor cache directory, because a sidecar UID need not exist in passwd. --- src/eval_tools/plugins/aka_v3.py | 3 +++ src/eval_tools/worker.py | 15 +++++++++++---- src/scripts/docker_benchmark.sh | 8 ++++++++ 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/eval_tools/plugins/aka_v3.py b/src/eval_tools/plugins/aka_v3.py index 931bd10a3..9172bb452 100644 --- a/src/eval_tools/plugins/aka_v3.py +++ b/src/eval_tools/plugins/aka_v3.py @@ -86,6 +86,9 @@ def lane_invocation( # the sidecar's own framework tree stays off its import path. "PYTHONPATH": "", "PYTHONDONTWRITEBYTECODE": "1", + # The sidecar UID need not exist in passwd; PyTorch's getpass needs these. + "USER": context.env.get("USER", "aka"), + "LOGNAME": context.env.get("LOGNAME", "aka"), "AKA_EVAL_TOOL": tool, **dict(env or {}), } diff --git a/src/eval_tools/worker.py b/src/eval_tools/worker.py index 59220fa81..4cc062371 100644 --- a/src/eval_tools/worker.py +++ b/src/eval_tools/worker.py @@ -930,13 +930,20 @@ def _python() -> str: return shutil.which("python") or os.sys.executable +def _probe_environment(work_dir: Path, **extra: str) -> dict[str, str]: + # A sidecar's UID need not exist in the image's passwd database; PyTorch's + # cache paths call getpass, which then needs USER/LOGNAME. + return {"PYTHONDONTWRITEBYTECODE": "1", "USER": "aka", "LOGNAME": "aka", + "TORCHINDUCTOR_CACHE_DIR": str(work_dir / "inductor"), **extra} + + def _page_fault_guard_positive(probe_root: Path, work_dir: Path, artifact_dir: Path) -> dict[str, Any]: steps = {} for name in ("safe", "far"): steps[name] = _run_probe_step( name, [_python(), str(probe_root / "page_fault_probe.py"), name], cwd=work_dir, - environment={**_NO_CACHING, "PYTHONDONTWRITEBYTECODE": "1", - "TRITON_CACHE_DIR": str(work_dir / "triton-cache")}, + environment=_probe_environment(work_dir, **_NO_CACHING, + TRITON_CACHE_DIR=str(work_dir / "triton-cache")), artifact_dir=artifact_dir, ) safe, far = steps["safe"], steps["far"] @@ -958,7 +965,7 @@ def _csan_positive(probe_root: Path, work_dir: Path, artifact_dir: Path) -> dict for name in ("safe", "race"): steps[name] = _run_probe_step( name, [_python(), str(probe_root / "csan_probe.py"), name], cwd=work_dir, - environment={"PYTHONDONTWRITEBYTECODE": "1"}, artifact_dir=artifact_dir, + environment=_probe_environment(work_dir), artifact_dir=artifact_dir, ) safe, race = steps["safe"], steps["race"] safe_ok = safe["returncode"] == 0 and "CSAN_RUN_COMPLETED safe" in safe["_stdout"] @@ -979,7 +986,7 @@ def _tilelens_positive(evidence: Mapping[str, Any], probe_root: Path, work_dir: for name in ("safe", "oob"): steps[name] = _run_probe_step( name, [_python(), str(probe_root / "tilelens_probe.py"), name], cwd=work_dir, - environment={"PYTHONPATH": root, "PYTHONDONTWRITEBYTECODE": "1"}, artifact_dir=artifact_dir, + environment=_probe_environment(work_dir, PYTHONPATH=root), artifact_dir=artifact_dir, ) for line in str(steps[name]["_stdout"]).splitlines(): if line.startswith("TILELENS_RESULT "): diff --git a/src/scripts/docker_benchmark.sh b/src/scripts/docker_benchmark.sh index 19a693d9b..1ca68ba1f 100755 --- a/src/scripts/docker_benchmark.sh +++ b/src/scripts/docker_benchmark.sh @@ -1178,6 +1178,14 @@ build_eval_tool_image() { dockerfile="$HOST_ROOT/docker/eval-tools/${tool//_/-}/Dockerfile" ;; esac + # Pull each pinned FROM image through the daemon first. BuildKit resolves a + # missing base itself and, on hosts whose registry TLS only the daemon + # trusts, fails; with --pull=false it uses the local copy instead. + local base + while IFS= read -r base; do + docker image inspect "$base" >/dev/null 2>&1 || docker pull -q "$base" >&2 \ + || die "Cannot pull $base for evaluation-tool image $image" + done < <(sed -nE 's/^ARG (BASE_IMAGE|BUILDER_IMAGE)=(.+)$/\2/p' "$dockerfile") if [[ -n "$target" ]]; then docker build --pull=false --target "$target" -f "$dockerfile" -t "$image" "$HOST_ROOT" else From 83aa3c86ca1a989c561a2f522f87b2b86eca20ae Mon Sep 17 00:00:00 2001 From: Vincent Ouyang Date: Tue, 10 Nov 2026 21:12:51 -0800 Subject: [PATCH 3/9] Fix sanitizer parsing found by the MI355X campaign A first hardware campaign over 24 schema-v3 baselines and seeded out-of-bounds variants showed five ways the v3 lanes misreported: - rocJITsu reported LDS races on two clean baselines from replays that did not reproduce the GPU's output. A race from a replay that was not attested (dispatch, capsule and golden output) is now inconclusive. - Waitcheck required a code object to hold exactly one kernel, so every HIP extension with two kernels was partial. The entry point now records the inventory size and the parser expects it. - FpSan and the Triton GPU ASan check looked up `.hsaco`, which does not exist for `@triton.jit(repr=...)` kernels: Triton names the cache files after the Python function. The code object is now the metadata file's sibling. - FlyDSL capture recorded nothing: a launch reaches the compiled artifact through executor methods, not `__call__`. The observer now watches FlyDSL compiler frames, and MLIR string literals are decoded with all their escapes. - TileLens 3.1.1 failed on all Gluon kernels tried, so Gluon is now reported unsupported instead of being run. --- docs/how-to/use-evaluation-tools.md | 15 ++-- docs/reference/release-notes.md | 6 +- src/eval_tools/adapters/aka_v3_entrypoint.py | 1 + src/eval_tools/plugins/parsers.py | 10 ++- src/eval_tools/plugins/v3_lanes.py | 22 ++++- src/eval_tools/plugins/v3_tools.py | 12 ++- src/tools/arena_eval/sanitize.py | 86 ++++++++++++++------ tests/eval_tools/test_v3_sanitizers.py | 73 +++++++++++++++-- tests/test_arena_eval_sanitize.py | 56 +++++++++++++ 9 files changed, 236 insertions(+), 45 deletions(-) diff --git a/docs/how-to/use-evaluation-tools.md b/docs/how-to/use-evaluation-tools.md index 0fdd273c4..fa9608927 100644 --- a/docs/how-to/use-evaluation-tools.md +++ b/docs/how-to/use-evaluation-tools.md @@ -15,7 +15,7 @@ The tool set is: - A page-fault guard that reruns correctness with the caching allocators off. - PyTorch's CUDA Sanitizer (CSAN) for cross-stream races. -- TileLens for symbolic out-of-bounds checks of Triton and Gluon kernels. +- TileLens for symbolic out-of-bounds checks of Triton kernels. - Triton FpSan for reference-versus-candidate floating-point semantic comparison. - ROCm GPU AddressSanitizer (GPU ASan) for invalid device-memory accesses. @@ -60,7 +60,7 @@ first use. | --- | --- | --- | --- | --- | | `page_fault_guard` | on | gate | Every correctness case with PyTorch's caching allocator and ROCr's fragment allocator off. An access past an allocation then reaches an unmapped page and the GPU faults instead of landing silently in a neighbouring tensor; an output that passed correctness but changes with the allocator is also a finding. | Triton, Gluon, HIP, FlyDSL | | `csan` | on | gate | Every correctness case under PyTorch's CUDA Sanitizer: unsynchronized access to a tensor from two streams by PyTorch-visible work, which includes a HIP candidate's custom op. Raw Triton, Gluon and FlyDSL launches are not visible to it. | all four | -| `tilelens` | on | gate | The smallest case with every Triton or Gluon kernel run by TileLens 3.1.1 in Triton's CPU interpreter; each load and store address is checked against its tensor symbolically (z3 over program id, mask and loop bounds). Uses no GPU time. | Triton, Gluon | +| `tilelens` | on | gate | The smallest case with every Triton kernel run by TileLens 3.1.1 in Triton's CPU interpreter; each load and store address is checked against its tensor symbolically (z3 over program id, mask and loop bounds). Uses no GPU time. Gluon is reported unsupported. | Triton | | `rocjitsu_waitcheck` | on | gate | Static missing or too-weak wait detection on every kernel the role dispatched. One call on the smallest case captures the final code objects (Triton/Gluon cache, the HIP extension's embedded bundle, FlyDSL's embedded HSACO). | all four | | `rocjitsu` | on | gate | rocJITsu's simulated LDS/register race detector. Each captured Triton or Gluon launch becomes a replay capsule (code object, lowered ABI, launch geometry, memory before and after) replayed once in the simulator. | Triton, Gluon | | `triton_fpsan` | on | signal | The smallest case through Triton FpSan for the candidate and the baseline. A different digest means a different floating-point expression, which a correct rewrite (online softmax, another reduction order or precision) also produces, so this never blocks. | Triton or Gluon candidate with a Triton or Gluon baseline | @@ -114,10 +114,15 @@ default per-tool deadline is 1200 seconds. explicit `gl.amd.cdna4.buffer_load`/`buffer_store`, which the page-fault guard covers instead. An ASan-built HIP extension loads only in a process with the ASan runtime preloaded, so the lane is always a separate process. -- TileLens approximates inline assembly and cannot run a Gluon kernel that - calls a `@triton.jit` helper; both are unverified, not clean. +- TileLens approximates inline assembly, which is unverified, not clean. + Its interpreter failed on every schema-v3 Gluon kernel tried (symbolic + program ids, tuple values, `@triton.jit` helpers called from Gluon), so a + Gluon role is reported `unsupported` rather than run. - rocJITsu replays only what the capture recorded: up to 16 launches and - 256 MiB of reachable memory per call. Tensor-descriptor arguments and + 256 MiB of reachable memory per call. A replay counts only when the + simulator reproduced the outputs the GPU wrote; a race reported by a replay + that did not (for example where emulated MFMA or FP8 arithmetic differs) is + recorded as inconclusive, not as a finding. Tensor-descriptor arguments and non-zero global scratch cannot be lowered yet, and HIP and FlyDSL launches expose no lowered ABI to capture, so those are unverified. - CSAN sees PyTorch dispatches only; AKA's static policy already forbids diff --git a/docs/reference/release-notes.md b/docs/reference/release-notes.md index c82046e97..91d72ab24 100644 --- a/docs/reference/release-notes.md +++ b/docs/reference/release-notes.md @@ -60,7 +60,7 @@ This topic summarizes the features available in each AgentKernelArena release. F and with no task configuration. `src/eval_tools/defaults.py` defines the set: - the new page-fault guard (correctness with the caching allocators off); - PyTorch CSAN; - - TileLens (symbolic out-of-bounds checks of Triton and Gluon kernels); + - TileLens (symbolic out-of-bounds checks of Triton kernels); - rocJITsu Waitcheck and the rocJITsu race detector, fed by an automatic capture of the kernels each call dispatches; - Triton FpSan. @@ -73,8 +73,8 @@ This topic summarizes the features available in each AgentKernelArena release. F - GPU ASan supports HIP (including the torch-extension build), Triton and Gluon. It needs a bare-metal host and stays opt-in: virtualized GPU hosts cannot run its runtime. -- Gluon candidates are supported by FpSan, GPU ASan, TileLens, Waitcheck and - rocJITsu through the v3 path. +- Gluon candidates are supported by FpSan, GPU ASan, Waitcheck and rocJITsu + through the v3 path; TileLens 3.1.1 reports Gluon unsupported. - The runner builds missing default sidecar images on first use, and the Waitcheck sidecar now gets the worker's GPU for capture. - `evaluation_tools: false` disables the stage. See diff --git a/src/eval_tools/adapters/aka_v3_entrypoint.py b/src/eval_tools/adapters/aka_v3_entrypoint.py index e36ec05a8..798c4ce23 100644 --- a/src/eval_tools/adapters/aka_v3_entrypoint.py +++ b/src/eval_tools/adapters/aka_v3_entrypoint.py @@ -106,6 +106,7 @@ def _waitcheck(args, output: Path, manifest: dict) -> list[dict]: log.write_text(completed.stdout + ("\n" + completed.stderr if completed.stderr else ""), encoding="utf-8") entries.append({"code_object": item["code_object"], "code_object_sha256": item["sha256"], "kernel_name": record["kernel_name"], "kernel_entry": record["kernel_entry"], + "kernels_in_code_object": len(inventory), "returncode": completed.returncode, "log": log.relative_to(output).as_posix()}) return entries diff --git a/src/eval_tools/plugins/parsers.py b/src/eval_tools/plugins/parsers.py index 389381d8e..be01cfb1e 100644 --- a/src/eval_tools/plugins/parsers.py +++ b/src/eval_tools/plugins/parsers.py @@ -304,9 +304,15 @@ def parse_waitcheck( expected_target: str, expected_kernel: str, expected_entry: int, + expected_discovered: int = 1, timed_out: bool = False, ) -> ParseResult: - """Parse the single JSON record emitted by the image-owned C API bridge.""" + """Parse the single JSON record emitted by the image-owned C API bridge. + + ``expected_discovered`` is the number of kernels in the code object's + inventory: the bridge analyzes one selected kernel of a multi-kernel code + object, so ``kernels_discovered`` counts them all. + """ combined = "\n".join(part for part in (stdout, stderr) if part) if timed_out: @@ -373,7 +379,7 @@ def parse_waitcheck( payload.get("analysis_complete") is not True or payload.get("diagnostics_truncated") is not False or payload.get("stopped_early") is not False - or payload.get("kernels_discovered") != 1 + or payload.get("kernels_discovered") != expected_discovered or payload.get("kernels_analyzed") != 1 ): return ParseResult( diff --git a/src/eval_tools/plugins/v3_lanes.py b/src/eval_tools/plugins/v3_lanes.py index f2c8a8984..4d0aa4b3f 100644 --- a/src/eval_tools/plugins/v3_lanes.py +++ b/src/eval_tools/plugins/v3_lanes.py @@ -10,6 +10,7 @@ from __future__ import annotations from pathlib import Path +from typing import Mapping from ..contracts import ( CapabilityCheck, @@ -34,7 +35,9 @@ ) -def _v3_engine(context: ToolContext, tool: str, languages: frozenset[str]) -> CapabilityCheck: +def _v3_engine(context: ToolContext, tool: str, languages: frozenset[str], + unsupported: Mapping[str, str] | None = None) -> CapabilityCheck: + unsupported = unsupported or {} if not aka_v3.is_v3(context): return blocked_check( CapabilityState.NOT_APPLICABLE, @@ -48,6 +51,8 @@ def _v3_engine(context: ToolContext, tool: str, languages: frozenset[str]) -> Ca f"{tool}_language_unsupported", f"{tool} supports triton, gluon, hip and flydsl, not {language!r}.", ) + if language in unsupported: + return blocked_check(CapabilityState.UNSUPPORTED, f"{tool}_{language}_unsupported", unsupported[language]) if language not in languages: return blocked_check( CapabilityState.NOT_APPLICABLE, @@ -87,12 +92,14 @@ def _failure_text(report: dict) -> str: class _LanePlugin: lane = "" languages: frozenset[str] = aka_v3.V3_LANGUAGES + # Languages the tool applies to but cannot check yet, with the reason. + unsupported_languages: Mapping[str, str] = {} timeout_s = 1800 # The manager may rerun this gate on the baseline after a finding. baseline_check = True def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: - engine = _v3_engine(context, self.name, self.languages) + engine = _v3_engine(context, self.name, self.languages, self.unsupported_languages) adapter = ready_check(adapter=aka_v3.ADAPTER) if engine.state == CapabilityState.READY else ready_check() return ToolCapability(self.name, engine, adapter, _runtime(runtime)) @@ -190,17 +197,24 @@ def judge(self, context: ToolContext, execution) -> ParseResult: class TileLensPlugin(_LanePlugin): - """TileLens's symbolic out-of-bounds check of each Triton/Gluon kernel. + """TileLens's symbolic out-of-bounds check of each Triton kernel. The smallest correctness case runs in Triton's CPU interpreter, where every load and store address is checked against its tensor (z3 over the symbolic program id, mask and loop bounds). No GPU time is used. + + Gluon is reported unsupported: TileLens 3.1.1's interpreter failed on + every Gluon task kernel tried (symbolic program ids, tuple values and + ``@triton.jit`` helpers called from Gluon). """ name = ToolName.TILELENS.value version = "1" lane = "tilelens" - languages = frozenset({"triton", "gluon"}) + languages = frozenset({"triton"}) + unsupported_languages = { + "gluon": "TileLens 3.1.1's interpreter cannot run schema-v3 Gluon kernels; Gluon is unchecked by TileLens.", + } timeout_s = 3600 TILELENS_ROOT = "/opt/tilelens/site-packages" diff --git a/src/eval_tools/plugins/v3_tools.py b/src/eval_tools/plugins/v3_tools.py index e07d4267f..d1d83ae7e 100644 --- a/src/eval_tools/plugins/v3_tools.py +++ b/src/eval_tools/plugins/v3_tools.py @@ -223,7 +223,8 @@ def waitcheck_parse(plugin, context: ToolContext, execution): log = (output / entry["log"]).read_text(encoding="utf-8", errors="replace") parsed.append(parse_waitcheck(log, "", entry["returncode"], expected_sha256=entry["code_object_sha256"], expected_target=SUPPORTED_ARCH, expected_kernel=entry["kernel_name"], - expected_entry=int(entry["kernel_entry"]))) + expected_entry=int(entry["kernel_entry"]), + expected_discovered=int(entry.get("kernels_in_code_object", 1)))) return parsed_to_run_result(plugin.name, aggregate("waitcheck", parsed, unverified), execution, metadata=_metadata(index, parsed)) @@ -258,6 +259,13 @@ def rocjitsu_parse(plugin, context: ToolContext, execution): attested = (kernel in rocjitsu_dispatch_kernels(combined) and "AKA_REPLAY_RESULT pass" in combined and f"AKA_REPLAY_CAPSULE sha256={entry['capsule_sha256']} code_sha256={capsule.code_object.sha256} " f"adapter=triton_aot arch={SUPPORTED_ARCH} kernel={kernel}" in combined) - parsed.append(parse_rocjitsu(log, "", entry["returncode"], attested=attested, report_text=report)) + result = parse_rocjitsu(log, "", entry["returncode"], attested=attested, report_text=report) + if result.status == FINDING and not attested: + # A replay that did not reproduce the GPU's output (or whose dispatch + # and capsule were not attested) is not the launch the GPU ran, so + # its race reports say nothing definite about the role's kernel. + result = ParseResult(INCONCLUSIVE, reason_code="rocjitsu_v3_race_on_unattested_replay", + details="; ".join(f"{item.kind} {item.location}" for item in result.findings)[:4000]) + parsed.append(result) return parsed_to_run_result(plugin.name, aggregate("rocjitsu", parsed, unverified), execution, metadata=_metadata(index, parsed)) diff --git a/src/tools/arena_eval/sanitize.py b/src/tools/arena_eval/sanitize.py index 68e52cf41..d6b6e016f 100644 --- a/src/tools/arena_eval/sanitize.py +++ b/src/tools/arena_eval/sanitize.py @@ -44,6 +44,7 @@ import hashlib import json +import re import math import os import shutil @@ -319,7 +320,13 @@ def hook(metadata): def _cache_kernels(cache: Path) -> dict: - """Compiled kernels in a Triton cache: name -> (metadata, hsaco path).""" + """Compiled kernels in a Triton cache: name -> (metadata, hsaco path). + + Triton names a cache entry's files after the Python function, truncated to + 150 characters, while ``metadata["name"]`` is the kernel symbol, which a + ``@triton.jit(repr=...)`` kernel extends with its constants. The code + object is therefore the metadata file's sibling, not ``.hsaco``. + """ kernels = {} for metadata_path in sorted(cache.rglob("*.json")): try: @@ -327,8 +334,8 @@ def _cache_kernels(cache: Path) -> dict: except (OSError, ValueError): continue name = metadata.get("name") if isinstance(metadata, dict) else None - hsaco = metadata_path.with_name(f"{name}.hsaco") if name else None - if name and hsaco is not None and hsaco.is_file(): + hsaco = metadata_path.with_suffix(".hsaco") + if name and hsaco.is_file(): kernels.setdefault(name, []).append((metadata, hsaco)) return kernels @@ -653,30 +660,71 @@ def run(self, *args, grid, warmup, **kwargs): return original -def _flydsl_code_objects(observed: list, output: Path) -> list[dict]: - """Embedded HSACO of each FlyDSL compiled artifact observed during the call.""" - import re +_MLIR_STRING_RE = re.compile(r'"((?:[^"\\]|\\.)*)"', re.S) + + +def _mlir_bytes(body: str) -> bytes: + """Decode the body of an MLIR string literal: ``\\XX`` hex escapes, ``\\\\`` and ``\\"``.""" + out, position = bytearray(), 0 + while position < len(body): + char = body[position] + if char == "\\" and position + 1 < len(body): + pair = body[position + 1:position + 3] + if len(pair) == 2 and all(c in "0123456789abcdefABCDEF" for c in pair): + out.append(int(pair, 16)) + position += 3 + continue + out.extend(body[position + 1].encode("utf-8")) + position += 2 + continue + out.extend(char.encode("utf-8")) + position += 1 + return bytes(out) + +def _flydsl_code_objects(observed: list, output: Path) -> list[dict]: + """The HSACO embedded in each FlyDSL compiled artifact's ``gpu.binary`` op.""" objects, seen = [], set() - for index, artifact in enumerate(observed): - text = getattr(artifact, "_ir_text", None) or getattr(artifact, "_source_ir", None) - if not isinstance(text, str): + for artifact in observed: + text = vars(artifact).get("_ir_text") + if not isinstance(text, str) or "gpu.binary" not in text: continue - for match in re.finditer(r'bin\s*=\s*"((?:[^"\\]|\\.)*)"', text): - raw = re.sub(r"\\([0-9A-Fa-f]{2})", lambda m: chr(int(m.group(1), 16)), match.group(1)) - data = raw.encode("latin-1", errors="ignore") - if data[:4] != b"\x7fELF": + for match in _MLIR_STRING_RE.finditer(text): + if match.group(1)[:6].upper() != "\\7FELF": continue + data = _mlir_bytes(match.group(1)) digest = hashlib.sha256(data).hexdigest() if digest in seen: continue seen.add(digest) - path = output / f"flydsl-{index:02d}.hsaco" + path = output / f"flydsl-{len(objects):02d}.hsaco" path.write_bytes(data) objects.append({"code_object": path.name, "sha256": digest, "kernels": None}) return objects +def _flydsl_observer(observed: list): + """A profile hook that records each FlyDSL compiled artifact the call uses. + + FlyDSL's ``CompiledArtifact`` holds the lowered module (with its embedded + code object) in ``_ir_text``; a launch reaches it through its executor + methods (``_get_func_exe``, ``_ensure_engine``), not ``__call__``. Only + FlyDSL compiler frames are inspected, through the instance dictionary, so + no property or ``__getattr__`` of the role's objects runs. + """ + + def profile(frame, event, arg): + if event != "call" or not (frame.f_globals.get("__name__") or "").startswith("flydsl.compiler"): + return + owner = frame.f_locals.get("self") + state = getattr(owner, "__dict__", None) if owner is not None else None + if isinstance(state, dict) and isinstance(state.get("_ir_text"), str): + if all(owner is not item for item in observed): + observed.append(owner) + + return profile + + def capture(contract, role: str) -> dict: evaluate = _evaluate() output = Path(os.environ.get(OUTPUT_ENV, "")) @@ -698,15 +746,7 @@ def capture(contract, role: str) -> dict: original = recorder.install() elif language == "flydsl": previous_profile = sys.getprofile() - - def profile(frame, event, arg): - if event == "call" and frame.f_code.co_name == "__call__": - owner = frame.f_locals.get("self") - if owner is not None and (getattr(owner, "_ir_text", None) or getattr(owner, "_source_ir", None)): - if all(owner is not item for item in observed): - observed.append(owner) - - sys.setprofile(profile) + sys.setprofile(_flydsl_observer(observed)) try: # FlyDSL's launch audit would replace this lane's profile hook; the # call keeps its integrity check and ran audited in correctness. diff --git a/tests/eval_tools/test_v3_sanitizers.py b/tests/eval_tools/test_v3_sanitizers.py index efd8db95e..72d88acfe 100644 --- a/tests/eval_tools/test_v3_sanitizers.py +++ b/tests/eval_tools/test_v3_sanitizers.py @@ -215,7 +215,8 @@ def test_a_gate_finding_is_rechecked_on_the_baseline(tmp_path, found_for, allowe ("page_fault_guard", "flydsl", CapabilityState.READY), ("page_fault_guard", "gluon", CapabilityState.READY), ("csan", "hip", CapabilityState.READY), - ("tilelens", "gluon", CapabilityState.READY), + ("tilelens", "triton", CapabilityState.READY), + ("tilelens", "gluon", CapabilityState.UNSUPPORTED), ("tilelens", "hip", CapabilityState.NOT_APPLICABLE), ("tilelens", "flydsl", CapabilityState.NOT_APPLICABLE), ("csan", "tilelang", CapabilityState.UNSUPPORTED), @@ -367,17 +368,17 @@ def test_waitcheck_v3_runs_on_every_language_and_only_on_gfx950(tmp_path): assert other.effective.state == CapabilityState.UNSUPPORTED -def _waitcheck_payload(sha: str, kernel: str, diagnostics=()): +def _waitcheck_payload(sha: str, kernel: str, diagnostics=(), discovered=1): payload = {"schema_version": 1, "code_object_sha256": sha, "target": "gfx950", "expected_kernel": kernel, "kernel_entry": 64, "inventory_attested": True, "api_status": 0, "analysis_complete": True, - "diagnostics_truncated": False, "stopped_early": False, "kernels_discovered": 1, + "diagnostics_truncated": False, "stopped_early": False, "kernels_discovered": discovered, "kernels_analyzed": 1, "instructions_analyzed": 10, "memory_events_tracked": 2, "diagnostics_observed": len(diagnostics), "diagnostics_reported": len(diagnostics), "diagnostics": list(diagnostics), "passed": not diagnostics} return "AKA_WAITCHECK_RESULT " + json.dumps(payload) -def _waitcheck_artifacts(tmp_path, entries, *, sha="a" * 64): +def _waitcheck_artifacts(tmp_path, entries, *, sha="a" * 64, inventory_size=None): context = v3_context(tmp_path) output = Path(context.artifact_dir) / "v3-waitcheck" (output / "capture").mkdir(parents=True) @@ -389,8 +390,11 @@ def _waitcheck_artifacts(tmp_path, entries, *, sha="a" * 64): log = output / "kernels" / f"{number}.log" log.parent.mkdir(parents=True, exist_ok=True) log.write_text(text) - index["entries"].append({"code_object": "k.hsaco", "code_object_sha256": sha, "kernel_name": "k", - "kernel_entry": 64, "returncode": 0, "log": f"kernels/{number}.log"}) + entry = {"code_object": "k.hsaco", "code_object_sha256": sha, "kernel_name": "k", + "kernel_entry": 64, "returncode": 0, "log": f"kernels/{number}.log"} + if inventory_size is not None: + entry["kernels_in_code_object"] = inventory_size + index["entries"].append(entry) (output / "index.json").write_text(json.dumps(index)) return context @@ -410,6 +414,22 @@ def test_waitcheck_v3_aggregates_one_parse_per_kernel(tmp_path): assert nothing.finding == FindingStatus.INCONCLUSIVE +def test_waitcheck_v3_accepts_one_analyzed_kernel_of_a_multi_kernel_code_object(tmp_path): + # A HIP extension's code object holds every kernel of the source file; the + # bridge analyzes the selected one and counts them all as discovered. + sha = "a" * 64 + two = [_waitcheck_payload(sha, "k", discovered=2)] + clean = get_plugin("rocjitsu_waitcheck").parse(_waitcheck_artifacts(tmp_path / "two", two, inventory_size=2), + execution()) + assert clean.finding == FindingStatus.CLEAN + # Without the entry point's inventory size, the count must be exactly one. + legacy = get_plugin("rocjitsu_waitcheck").parse(_waitcheck_artifacts(tmp_path / "legacy", two), execution()) + assert legacy.finding == FindingStatus.INCONCLUSIVE + short = get_plugin("rocjitsu_waitcheck").parse( + _waitcheck_artifacts(tmp_path / "short", two, inventory_size=3), execution()) + assert short.finding == FindingStatus.INCONCLUSIVE + + def test_waitcheck_v3_rejects_a_code_object_that_was_not_captured(tmp_path): context = _waitcheck_artifacts(tmp_path, [_waitcheck_payload("b" * 64, "k")]) index_path = Path(context.artifact_dir) / "v3-waitcheck" / "index.json" @@ -473,6 +493,47 @@ def test_a_changed_captured_hsaco_is_rejected(tmp_path): build_capsule(directory, manifest={}, task_id="t", image_digest="d", rocm_version="r", framework_version="f") +_RACE_REPORT = "RACE type=LDS reg=508 wave=0 lane=0 wg=0,0,0 conflict=unknown\n write ds_write_b32\nEND_RACE\n" + + +def _rocjitsu_artifacts(tmp_path: Path, *, replay_passed: bool): + context = v3_context(tmp_path) + output = Path(context.artifact_dir) / "v3-rocjitsu" + capture = output / "capture" + capture.mkdir(parents=True) + directory = _launch_dir(capture) + capsule = build_capsule(directory, manifest={"case": "t1", "seed": 7, "role": "candidate"}, task_id="t", + image_digest="sha256:image", rocm_version="10.0.0", framework_version="3.8.0") + loaded = ReplayCapsule.load(capsule, verify_files=True) + capsule_sha = hashlib.sha256(capsule.read_bytes()).hexdigest() + (capture / "capture.json").write_text(json.dumps({ + "schema_version": 1, "code_objects": [], + "launches": [{"directory": "launch-00", "kernel_name": "copy_kernel", + "hsaco_sha256": loaded.code_object.sha256}], "skipped": []})) + log_lines = ['[rocjitsu] Kernel dispatch: "copy_kernel"', + f"AKA_REPLAY_CAPSULE sha256={capsule_sha} code_sha256={loaded.code_object.sha256} " + "adapter=triton_aot arch=gfx950 kernel=copy_kernel", + "AKA_REPLAY_RESULT pass" if replay_passed + else "AKA_REPLAY_RESULT fail: output allocation a2 mismatched golden blob"] + (output / "replay.log").write_text("\n".join(log_lines) + "\n") + (output / "race.log").write_text(_RACE_REPORT) + (output / "index.json").write_text(json.dumps({"schema_version": 1, "skipped": [], "entries": [{ + "directory": "launch-00", "kernel_name": "copy_kernel", "capsule": capsule.relative_to(output).as_posix(), + "capsule_sha256": capsule_sha, "returncode": 1, "log": "replay.log", "race_log": "race.log"}]})) + return context + + +def test_rocjitsu_v3_reports_a_race_only_from_a_replay_that_reproduced_the_gpu_output(tmp_path): + faithful = get_plugin("rocjitsu").parse(_rocjitsu_artifacts(tmp_path / "pass", replay_passed=True), execution()) + assert faithful.finding == FindingStatus.FOUND and faithful.findings[0].kind == "lds-race" + # A replay whose outputs differ from the captured GPU outputs is not the + # launch the GPU ran: its race report is recorded as inconclusive. + unfaithful = get_plugin("rocjitsu").parse(_rocjitsu_artifacts(tmp_path / "fail", replay_passed=False), + execution()) + assert unfaithful.finding == FindingStatus.INCONCLUSIVE + assert "rocjitsu_v3_race_on_unattested_replay" in unfaithful.summary + + def test_code_object_target_reads_the_elf_header(): assert code_object_target(_hsaco(2, True)) == (4, True) with pytest.raises(CapsuleValidationError): diff --git a/tests/test_arena_eval_sanitize.py b/tests/test_arena_eval_sanitize.py index 8b1d67432..e8352de3f 100644 --- a/tests/test_arena_eval_sanitize.py +++ b/tests/test_arena_eval_sanitize.py @@ -120,3 +120,59 @@ class Record: reduced = sanitize._tilelens_record(Record()) assert reduced == {"op": "Load", "tensor": "x", "address": "16", "location": ["kernel.py:18 in copy", "b", "c"]} + + +def test_cache_kernels_finds_a_repr_named_kernel_by_its_metadata_file(tmp_path): + # Triton names the files after the Python function; a repr kernel's symbol + # carries its constants, so ``.hsaco`` does not exist. + entry = tmp_path / "ABC" + entry.mkdir() + symbol = "_gemm_kernel_BLOCK_SIZE_M_64_BLOCK_SIZE_N_128" + (entry / "_gemm_kernel.json").write_text('{"name": "%s", "instrumentation_mode": "fpsan"}' % symbol) + (entry / "_gemm_kernel.hsaco").write_bytes(b"\x7fELF") + (entry / "__grp___gemm_kernel.json").write_text('{"child_paths": {}}') + kernels = sanitize._cache_kernels(tmp_path) + assert list(kernels) == [symbol] + assert kernels[symbol][0][1] == entry / "_gemm_kernel.hsaco" + + +def _escaped(data: bytes) -> str: + # MLIR prints printable ASCII as is and every other byte as \XX. + return "".join(chr(b) if 32 <= b < 127 and chr(b) not in '"\\' else f"\\{b:02X}" for b in data) + + +class _Artifact: + def __init__(self, text): + self._ir_text = text + + +def test_flydsl_capture_extracts_the_code_object_from_the_lowered_module(tmp_path): + elf = b"\x7fELF\x02\x01\x01" + bytes(range(256)) + b'"\\tail' + text = ('module attributes {gpu.container_module} {\n gpu.binary @kernels [#gpu.object<#rocdl.target<' + 'chip = "gfx950">, kernels = <[#gpu.kernel_metadata<"k", !llvm.func>]>, bin = "' + + _escaped(elf) + '">]\n}') + objects = sanitize._flydsl_code_objects([_Artifact(text), _Artifact(text)], tmp_path) + assert len(objects) == 1 and objects[0]["kernels"] is None + assert (tmp_path / objects[0]["code_object"]).read_bytes() == elf + # A module that holds no binary yields nothing rather than a wrong object. + assert sanitize._flydsl_code_objects([_Artifact('gpu.binary @k [#gpu.object<#rocdl.target, "abc">]')], + tmp_path / "x") == [] + + +def test_flydsl_observer_records_artifacts_reached_through_executor_methods(): + import sys + import types + + observed = [] + module = types.ModuleType("flydsl.compiler.jit_executor") + exec("class CompiledArtifact:\n def __init__(self, text):\n self._ir_text = text\n" + " def _get_func_exe(self):\n return 1\n", module.__dict__) + artifact = module.CompiledArtifact("gpu.binary") + previous = sys.getprofile() + sys.setprofile(sanitize._flydsl_observer(observed)) + try: + artifact._get_func_exe() + artifact._get_func_exe() + finally: + sys.setprofile(previous) + assert observed == [artifact] From b52b828c9fbdad2093310257f14e17c375096a64 Mon Sep 17 00:00:00 2001 From: Vincent Ouyang Date: Tue, 10 Nov 2026 22:22:21 -0800 Subject: [PATCH 4/9] Order the CSAN control's safe read after the write The safe step read a tensor on a side stream without waiting for the default-stream write that produced it, which is a real race, so CSAN correctly rejected it and the sidecar never became ready. The side stream now waits for the default stream before the read, as the default stream already waited for the side stream after it. On MI355X the safe step now exits 0 with no report and the race step reports the race. --- docs/how-to/use-evaluation-tools.md | 2 +- src/eval_tools/probes/csan_probe.py | 8 ++++++-- src/eval_tools/worker.py | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/how-to/use-evaluation-tools.md b/docs/how-to/use-evaluation-tools.md index fa9608927..638a0e1a1 100644 --- a/docs/how-to/use-evaluation-tools.md +++ b/docs/how-to/use-evaluation-tools.md @@ -402,7 +402,7 @@ worker: | `rocjitsu_consan` | Compile raw safe/racy HSACOs plus an image-owned module launcher, run the production entrypoint with separate instrumented/oracle argv, require the oracle environment to be scrubbed, and make the production parser return clean/finding with exact FNV attribution. | | `hip_fpsan` | Require explicitly ported equivalent expressions to match and a known-wrong expression to produce a different digest. | | `page_fault_guard` | With the caching allocators off, a safe Triton copy must pass and a store 256 MiB past its output must fault. | -| `csan` | A side-stream read followed by `wait_stream` must pass; without the wait CSAN must report a race. | +| `csan` | A side-stream read ordered with `wait_stream` in both directions (after the write, before the next default-stream use) must pass; without the waits CSAN must report a race. | | `tilelens` | Through the lane's programmatic API (a `Sanitizer` with `abort_on_error` off), an in-bounds Triton copy must record no violation and an off-by-one copy at least one. | `eval-tools-smoke` prints this evidence and exits nonzero if a worker reports diff --git a/src/eval_tools/probes/csan_probe.py b/src/eval_tools/probes/csan_probe.py index f88f35e92..6b49829bc 100644 --- a/src/eval_tools/probes/csan_probe.py +++ b/src/eval_tools/probes/csan_probe.py @@ -1,6 +1,8 @@ -"""PyTorch CUDA Sanitizer control: a side-stream read, with or without a stream wait. +"""PyTorch CUDA Sanitizer control: a side-stream read, with or without stream waits. -Usage: csan_probe.py [safe|race] +``safe`` orders the side stream after the write that produced the tensor and +the default stream after the side-stream read; ``race`` omits both waits, so +the read races the write. Usage: csan_probe.py [safe|race] """ from __future__ import annotations @@ -16,6 +18,8 @@ def main() -> int: cuda_sanitizer.enable_cuda_sanitizer() a = torch.ones(1 << 16, device="cuda") side = torch.cuda.Stream() + if not race: + side.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(side): total = a.sum() if not race: diff --git a/src/eval_tools/worker.py b/src/eval_tools/worker.py index 4cc062371..79f8a1756 100644 --- a/src/eval_tools/worker.py +++ b/src/eval_tools/worker.py @@ -973,7 +973,7 @@ def _csan_positive(probe_root: Path, work_dir: Path, artifact_dir: Path) -> dict return _positive_result( passed=safe_ok and race_ok, kind="csan_stream_wait_and_race", - detail="a side-stream read followed by wait_stream must pass; without the wait CSAN must report a race", + detail="a side-stream read ordered by wait_stream in both directions must pass; without the waits CSAN must report a race", artifact_dir=artifact_dir, steps=steps, controls={"safe": {"passed": safe_ok}, "race": {"passed": race_ok}}, ) From de77e18fc0dfcdec83e63cfc1bc8403dbd2f513a Mon Sep 17 00:00:00 2001 From: Vincent Ouyang Date: Wed, 11 Nov 2026 01:07:50 -0800 Subject: [PATCH 5/9] Stop the page-fault guard and baseline recheck from blocking clean code The campaign over all 385 schema-v3 entries blocked one clean baseline: the page-fault guard reported a FlyDSL split-K GEMM as allocator sensitive because one element of one case came out 14% over its baseline-relative bound. That is ordinary run-to-run variation, and the same check passed on the baseline recheck. - The guard now reports an output change only when it is gross: a non-finite value, an error over 10 times the bound, or more than 1% of elements outside it. Reading memory the role does not own produces values like that. A smaller excess is recorded as unverified. - The baseline recheck now excuses a candidate finding only when the baseline reports the same kinds. A baseline finding of another kind no longer hides, for example, a candidate fault. - The docs say that the first run builds the default images over the network and stops if a build fails. --- docs/how-to/run-evaluation.md | 3 +- docs/how-to/use-evaluation-tools.md | 18 ++++++++---- src/eval_tools/manager.py | 8 +++++- src/eval_tools/plugins/v3_lanes.py | 39 +++++++++++++++++++++++++ tests/eval_tools/test_v3_sanitizers.py | 40 ++++++++++++++++++++------ 5 files changed, 92 insertions(+), 16 deletions(-) diff --git a/docs/how-to/run-evaluation.md b/docs/how-to/run-evaluation.md index b14971705..9fa8e6c3c 100644 --- a/docs/how-to/run-evaluation.md +++ b/docs/how-to/run-evaluation.md @@ -114,7 +114,8 @@ set of run-configuration fields. Sanitizer sidecars run after ordinary correctness and before performance. On MI355X (`gfx950`) a run configuration without an `evaluation_tools` section runs the default schema-v3 set; the runner builds any missing sidecar image on -first use. Set `evaluation_tools: false` to turn it off. See [Check kernels +first use, which needs network access, and stops the run if a build fails. +Set `evaluation_tools: false` to turn it off. See [Check kernels with evaluation tools](use-evaluation-tools.md#default-sanitizers-for-schema-v3-tasks). ## Start a run diff --git a/docs/how-to/use-evaluation-tools.md b/docs/how-to/use-evaluation-tools.md index 638a0e1a1..0e4caaaca 100644 --- a/docs/how-to/use-evaluation-tools.md +++ b/docs/how-to/use-evaluation-tools.md @@ -54,11 +54,14 @@ declares nothing: each tool runs the generated workspace runner's correctness cases, for whatever `target_language` the run selected. `src/eval_tools/defaults.py` is the single source of truth for the set, the roles and the policy; the Docker runner builds any missing default image on -first use. +first use. That build needs network access to the pinned package and source +locations; if it fails the run stops before any task starts, rather than run +without a default tool. Build the images ahead of time on hosts with limited +network access (see below), or set `evaluation_tools: false`. | Tool | Default | Role | What it checks | Languages | | --- | --- | --- | --- | --- | -| `page_fault_guard` | on | gate | Every correctness case with PyTorch's caching allocator and ROCr's fragment allocator off. An access past an allocation then reaches an unmapped page and the GPU faults instead of landing silently in a neighbouring tensor; an output that passed correctness but changes with the allocator is also a finding. | Triton, Gluon, HIP, FlyDSL | +| `page_fault_guard` | on | gate | Every correctness case with PyTorch's caching allocator and ROCr's fragment allocator off. An access past an allocation then reaches an unmapped page and the GPU faults instead of landing silently in a neighbouring tensor; an output that passed correctness but then fails it far outside its bound (a non-finite value, more than 10 times the bound, or more than 1% of elements over it) is also a finding; a smaller excess is recorded as unverified, since split-K and atomic kernels vary that much from run to run. | Triton, Gluon, HIP, FlyDSL | | `csan` | on | gate | Every correctness case under PyTorch's CUDA Sanitizer: unsynchronized access to a tensor from two streams by PyTorch-visible work, which includes a HIP candidate's custom op. Raw Triton, Gluon and FlyDSL launches are not visible to it. | all four | | `tilelens` | on | gate | The smallest case with every Triton kernel run by TileLens 3.1.1 in Triton's CPU interpreter; each load and store address is checked against its tensor symbolically (z3 over program id, mask and loop bounds). Uses no GPU time. Gluon is reported unsupported. | Triton | | `rocjitsu_waitcheck` | on | gate | Static missing or too-weak wait detection on every kernel the role dispatched. One call on the smallest case captures the final code objects (Triton/Gluon cache, the HIP extension's embedded bundle, FlyDSL's embedded HSACO). | all four | @@ -84,11 +87,14 @@ a semantic comparison; set `evaluation_tools.tools..role` to override): - A `gate` blocks performance, and therefore the score, only on a definite finding: a fault, a sanitizer report, a race or hazard record, or an output - that changes with the allocator. + far outside its bound with the allocator changed. - After a candidate finding the manager reruns the same tool on the task's - baseline. A finding the baseline shares is recorded with - `baseline_also_found: true` and does not block: the reference - implementation does the same thing. + baseline. When the baseline reports every kind of finding the candidate + does, the finding is recorded with `baseline_also_found: true` and does not + block: the reference implementation does the same thing. A finding of a + kind the baseline does not report still blocks. On a task whose baseline + has a finding of some kind, that tool therefore cannot block a candidate + for that kind; the page-fault guard and the other gates still apply. - Anything that is not a definite finding — an unsupported construct, a kernel TileLens cannot interpret, a tool error, a timeout, a capture that recorded nothing — is recorded as unverified (`policy_satisfied: false`) and diff --git a/src/eval_tools/manager.py b/src/eval_tools/manager.py index 2f811d3a8..23152f59b 100644 --- a/src/eval_tools/manager.py +++ b/src/eval_tools/manager.py @@ -532,8 +532,14 @@ def _baseline_check( baseline = None check = {"execution": "tool_error", "error": f"{type(exc).__name__}: {exc}"[:2000]} metadata = {**dict(result.metadata), "baseline_check": check} + # Shared means the baseline reports every kind of finding the candidate + # does; a candidate fault is not excused by an unrelated baseline report. if baseline is not None and baseline.finding == FindingStatus.FOUND: - metadata[BASELINE_ALSO_FOUND] = True + candidate_kinds = {item.kind for item in result.findings} + baseline_kinds = {item.kind for item in baseline.findings} + check["kinds"] = sorted(baseline_kinds) + if candidate_kinds <= baseline_kinds: + metadata[BASELINE_ALSO_FOUND] = True return replace(result, metadata=metadata) # ``execute`` reads naturally at evaluator integration sites and remains an diff --git a/src/eval_tools/plugins/v3_lanes.py b/src/eval_tools/plugins/v3_lanes.py index 4d0aa4b3f..c475a903f 100644 --- a/src/eval_tools/plugins/v3_lanes.py +++ b/src/eval_tools/plugins/v3_lanes.py @@ -160,6 +160,11 @@ def judge(self, context: ToolContext, execution) -> ParseResult: "while the caching allocators were off", raw=text[:4000]) return ParseResult(FINDING, (finding,), "page_fault_guard_fault", attested=True) if kind in ("numerical_mismatch", "input_mutation", "mixed"): + if kind == "numerical_mismatch" and not _gross_mismatch(report): + # A small excess over the case's bound is indistinguishable from + # the task's own run-to-run variation (split-K, atomics). + return ParseResult(INCONCLUSIVE, reason_code="page_fault_guard_marginal_mismatch", + details=text[:4000], attested=True) finding = FindingRecord(kind="allocator-sensitive-output", message="outputs that passed correctness " "changed when the caching allocators were off: the role reads memory it does " "not own", raw=text[:4000]) @@ -167,6 +172,40 @@ def judge(self, context: ToolContext, execution) -> ParseResult: return ParseResult(TOOL_ERROR, reason_code=f"page_fault_guard_{kind or 'failed'}", details=text[:4000]) +# Reading memory the role does not own yields values unrelated to the result. +GROSS_BOUND_MULTIPLE = 10.0 +GROSS_VIOLATION_FRACTION = 0.01 + + +def _gross_mismatch(report: dict) -> bool: + """Whether a failed output is far outside its bound, not a marginal miss. + + Gross: a non-finite value where the reference is finite, an error over + ``GROSS_BOUND_MULTIPLE`` times the case's bound, more than + ``GROSS_VIOLATION_FRACTION`` of the elements outside it, or a failure + without these metrics. + """ + + failing = [row for row in report.get("cases") or [] if row.get("status") != "PASS"] + if not failing: + return True + for row in failing: + calls = ((row.get("metrics") or {}).get("calls")) or [] + failed = [output for call in calls for output in (call.get("outputs") or {}).values() + if isinstance(output, dict) and output.get("passed") is False] + if not failed: + return True + for output in failed: + try: + if (int(output.get("nonfinite_mismatches") or 0) > 0 + or float(output.get("peak_bound_multiple", float("inf"))) > GROSS_BOUND_MULTIPLE + or float(output.get("violation_fraction", 1.0)) > GROSS_VIOLATION_FRACTION): + return True + except (TypeError, ValueError): + return True + return False + + class CsanPlugin(_LanePlugin): """Correctness cases under PyTorch's CUDA Sanitizer. diff --git a/tests/eval_tools/test_v3_sanitizers.py b/tests/eval_tools/test_v3_sanitizers.py index 72d88acfe..7e4de86ee 100644 --- a/tests/eval_tools/test_v3_sanitizers.py +++ b/tests/eval_tools/test_v3_sanitizers.py @@ -154,6 +154,7 @@ class RolePlugin: """Finds a bug for each role in ``found_for``.""" found_for: tuple = ("candidate",) + baseline_kind: str = "fault" name: str = "page_fault_guard" version: str = "1" baseline_check: bool = True @@ -168,8 +169,9 @@ def build_invocation(self, context): def parse(self, context, execution): role = execution.command[-1] if role in self.found_for: + kind = self.baseline_kind if role == "baseline" else "fault" return ToolRunResult(tool=self.name, execution=ExecutionStatus.COMPLETED, finding=FindingStatus.FOUND, - findings=(Finding(kind="fault", severity=FindingSeverity.ERROR, message=role),)) + findings=(Finding(kind=kind, severity=FindingSeverity.ERROR, message=role),)) return ToolRunResult(tool=self.name, execution=ExecutionStatus.COMPLETED, finding=FindingStatus.CLEAN) @@ -185,14 +187,16 @@ def execute(self, invocation, context): return ExecutionRecord(command=invocation.command, returncode=0) -@pytest.mark.parametrize("found_for,allowed,shared", [ - (("candidate",), False, False), - (("candidate", "baseline"), True, True), - ((), True, False), +@pytest.mark.parametrize("found_for,baseline_kind,allowed,shared", [ + (("candidate",), "fault", False, False), + (("candidate", "baseline"), "fault", True, True), + # A baseline finding of another kind does not excuse the candidate's. + (("candidate", "baseline"), "allocator-sensitive-output", False, False), + ((), "fault", True, False), ]) -def test_a_gate_finding_is_rechecked_on_the_baseline(tmp_path, found_for, allowed, shared): +def test_a_gate_finding_is_rechecked_on_the_baseline(tmp_path, found_for, baseline_kind, allowed, shared): registry = ToolRegistry() - registry.register(RolePlugin(found_for=found_for)) + registry.register(RolePlugin(found_for=found_for, baseline_kind=baseline_kind)) runtime = EchoRuntime() config = EvalToolsConfig.from_mapping({"evaluation_tools": {"policy": "gated", "enabled": ["page_fault_guard"]}}) report = EvalToolManager(registry, runtime).evaluate( @@ -203,7 +207,7 @@ def test_a_gate_finding_is_rechecked_on_the_baseline(tmp_path, found_for, allowe if found_for: assert runtime.commands == [("lane", "candidate"), ("lane", "baseline")] assert bool(result.metadata.get(BASELINE_ALSO_FOUND)) is shared - assert result.metadata["baseline_check"]["finding"] == ("found" if shared else "clean") + assert result.metadata["baseline_check"]["finding"] == ("found" if "baseline" in found_for else "clean") else: assert runtime.commands == [("lane", "candidate")] @@ -248,6 +252,26 @@ def _parse(tool, tmp_path, record): return get_plugin(tool).parse(v3_context(tmp_path), record) +def _mismatch_case(**output): + metrics = {"passed": False, "peak_bound_multiple": 1.14, "violation_fraction": 3e-05, "nonfinite_mismatches": 0} + metrics.update(output) + return {"test_case_id": "m512", "status": "FAIL", "failure_kind": "numerical_mismatch", + "metrics": {"calls": [{"outputs": {"out": {"passed": True}}}, {"outputs": {"out": metrics}}]}} + + +@pytest.mark.parametrize("output,finding", [ + ({}, FindingStatus.INCONCLUSIVE), # one element 14% over a baseline-relative bound + ({"peak_bound_multiple": 50.0}, FindingStatus.FOUND), + ({"violation_fraction": 0.2}, FindingStatus.FOUND), + ({"nonfinite_mismatches": 3}, FindingStatus.FOUND), +]) +def test_page_fault_guard_flags_only_gross_output_changes(tmp_path, output, finding): + result = _parse("page_fault_guard", tmp_path, execution(report( + "page_fault_guard", "FAIL", failure_kind="numerical_mismatch", reason="1 case failed", + cases=[_mismatch_case(**output)]), returncode=1)) + assert result.finding == finding + + def test_page_fault_guard_verdicts(tmp_path): fault = _parse("page_fault_guard", tmp_path, execution(stderr="Memory access fault by GPU node-2 on address 0x7f", returncode=-6)) From 58138b277640f057eb79f3c5151ace12a63e2d20 Mon Sep 17 00:00:00 2001 From: Vincent Ouyang Date: Wed, 11 Nov 2026 03:52:06 -0800 Subject: [PATCH 6/9] Count a TileLens finding only when a concrete run reproduces it TileLens checks Triton kernels symbolically and over-approximates loop-carried pointer updates and loaded indices. On the MI355X campaign it reported out-of-bounds accesses on clean production baselines, for example the cyclic K loop of ff_a16w16_fused_gated, which stays in bounds. As a gate it would block a correct candidate that uses the same pattern on a task whose baseline does not. A TileLens violation now triggers the new `bounds` lane in a fresh process: the same smallest case runs concretely in Triton's CPU interpreter (TRITON_INTERPRET=1), and every active load, store and atomic address is checked against the argument buffers of its launch. A stray access is recorded and masked off instead of performed. Only a reproduced access is a finding; otherwise the result is unverified (tilelens_unconfirmed). The TileLens startup control also runs the concrete check on the safe and off-by-one copies, so a broken check fails the control instead of silently disabling the gate. The image copies the lane module for that. --- .dockerignore | 4 + docker/eval-tools/tilelens/Dockerfile | 3 + docs/how-to/use-evaluation-tools.md | 9 +- docs/reference/release-notes.md | 3 +- src/eval_tools/plugins/v3_lanes.py | 29 +++- src/eval_tools/probes/tilelens_probe.py | 39 ++++- src/eval_tools/worker.py | 33 +++- src/tools/arena_eval/sanitize.py | 221 +++++++++++++++++++++++- tests/eval_tools/test_v3_sanitizers.py | 21 ++- tests/test_arena_eval_sanitize.py | 112 ++++++++++++ 10 files changed, 441 insertions(+), 33 deletions(-) diff --git a/.dockerignore b/.dockerignore index b2c01fa9d..285c6fb0e 100644 --- a/.dockerignore +++ b/.dockerignore @@ -9,5 +9,9 @@ !src/ !src/eval_tools/ !src/eval_tools/** +# The TileLens image's startup control runs the lane's concrete bounds check. +!src/tools/ +!src/tools/arena_eval/ +!src/tools/arena_eval/sanitize.py **/__pycache__/ **/*.py[cod] diff --git a/docker/eval-tools/tilelens/Dockerfile b/docker/eval-tools/tilelens/Dockerfile index e9ffe0a6e..478dd255e 100644 --- a/docker/eval-tools/tilelens/Dockerfile +++ b/docker/eval-tools/tilelens/Dockerfile @@ -14,6 +14,9 @@ RUN /opt/venv/bin/python -m pip install --no-cache-dir --no-deps --require-hashe "import tilelens, z3; from tilelens.clients import Sanitizer; print('tilelens', z3.get_version_string())" COPY src/eval_tools /opt/aka-eval-tools/src/eval_tools +# The startup control exercises the lane's concrete bounds check, which +# confirms a TileLens finding before it counts. +COPY src/tools/arena_eval/sanitize.py /opt/aka-eval-tools/src/tools/arena_eval/sanitize.py ENV AKA_EVAL_TOOL_FRAMEWORK_ROOT=/opt/aka-eval-tools \ PYTHONPATH=/opt/aka-eval-tools \ diff --git a/docs/how-to/use-evaluation-tools.md b/docs/how-to/use-evaluation-tools.md index 0e4caaaca..3c20f457c 100644 --- a/docs/how-to/use-evaluation-tools.md +++ b/docs/how-to/use-evaluation-tools.md @@ -63,7 +63,7 @@ network access (see below), or set `evaluation_tools: false`. | --- | --- | --- | --- | --- | | `page_fault_guard` | on | gate | Every correctness case with PyTorch's caching allocator and ROCr's fragment allocator off. An access past an allocation then reaches an unmapped page and the GPU faults instead of landing silently in a neighbouring tensor; an output that passed correctness but then fails it far outside its bound (a non-finite value, more than 10 times the bound, or more than 1% of elements over it) is also a finding; a smaller excess is recorded as unverified, since split-K and atomic kernels vary that much from run to run. | Triton, Gluon, HIP, FlyDSL | | `csan` | on | gate | Every correctness case under PyTorch's CUDA Sanitizer: unsynchronized access to a tensor from two streams by PyTorch-visible work, which includes a HIP candidate's custom op. Raw Triton, Gluon and FlyDSL launches are not visible to it. | all four | -| `tilelens` | on | gate | The smallest case with every Triton kernel run by TileLens 3.1.1 in Triton's CPU interpreter; each load and store address is checked against its tensor symbolically (z3 over program id, mask and loop bounds). Uses no GPU time. Gluon is reported unsupported. | Triton | +| `tilelens` | on | gate | The smallest case with every Triton kernel run by TileLens 3.1.1 in Triton's CPU interpreter; each load and store address is checked against its tensor symbolically (z3 over program id, mask and loop bounds). A reported access is a finding only when a concrete rerun of the same case in the interpreter, with every active load, store and atomic address checked against the launch's argument buffers, reproduces an out-of-bounds access; otherwise it is unverified. Uses no GPU time. Gluon is reported unsupported. | Triton | | `rocjitsu_waitcheck` | on | gate | Static missing or too-weak wait detection on every kernel the role dispatched. One call on the smallest case captures the final code objects (Triton/Gluon cache, the HIP extension's embedded bundle, FlyDSL's embedded HSACO). | all four | | `rocjitsu` | on | gate | rocJITsu's simulated LDS/register race detector. Each captured Triton or Gluon launch becomes a replay capsule (code object, lowered ABI, launch geometry, memory before and after) replayed once in the simulator. | Triton, Gluon | | `triton_fpsan` | on | signal | The smallest case through Triton FpSan for the candidate and the baseline. A different digest means a different floating-point expression, which a correct rewrite (online softmax, another reduction order or precision) also produces, so this never blocks. | Triton or Gluon candidate with a Triton or Gluon baseline | @@ -121,6 +121,11 @@ default per-tool deadline is 1200 seconds. guard covers instead. An ASan-built HIP extension loads only in a process with the ASan runtime preloaded, so the lane is always a separate process. - TileLens approximates inline assembly, which is unverified, not clean. + Its symbolic model also over-approximates loop-carried pointer updates and + loaded indices, so it can report an access that no execution reaches; the + concrete rerun decides. That rerun checks only the smallest case's actual + execution, and only against whole argument storages: an access outside a + view but inside the storage it was sliced from is not caught. Its interpreter failed on every schema-v3 Gluon kernel tried (symbolic program ids, tuple values, `@triton.jit` helpers called from Gluon), so a Gluon role is reported `unsupported` rather than run. @@ -409,7 +414,7 @@ worker: | `hip_fpsan` | Require explicitly ported equivalent expressions to match and a known-wrong expression to produce a different digest. | | `page_fault_guard` | With the caching allocators off, a safe Triton copy must pass and a store 256 MiB past its output must fault. | | `csan` | A side-stream read ordered with `wait_stream` in both directions (after the write, before the next default-stream use) must pass; without the waits CSAN must report a race. | -| `tilelens` | Through the lane's programmatic API (a `Sanitizer` with `abort_on_error` off), an in-bounds Triton copy must record no violation and an off-by-one copy at least one. | +| `tilelens` | Through the lane's programmatic API (a `Sanitizer` with `abort_on_error` off), an in-bounds Triton copy must record no violation and an off-by-one copy at least one; the lane's concrete interpreter check, which confirms TileLens findings, must agree on both copies. | `eval-tools-smoke` prints this evidence and exits nonzero if a worker reports `degraded`, including a failed nested positive control. Inspect and retain the diff --git a/docs/reference/release-notes.md b/docs/reference/release-notes.md index 91d72ab24..7d603011b 100644 --- a/docs/reference/release-notes.md +++ b/docs/reference/release-notes.md @@ -60,7 +60,8 @@ This topic summarizes the features available in each AgentKernelArena release. F and with no task configuration. `src/eval_tools/defaults.py` defines the set: - the new page-fault guard (correctness with the caching allocators off); - PyTorch CSAN; - - TileLens (symbolic out-of-bounds checks of Triton kernels); + - TileLens (symbolic out-of-bounds checks of Triton kernels; a reported access + counts only when a concrete interpreter rerun reproduces it); - rocJITsu Waitcheck and the rocJITsu race detector, fed by an automatic capture of the kernels each call dispatches; - Triton FpSan. diff --git a/src/eval_tools/plugins/v3_lanes.py b/src/eval_tools/plugins/v3_lanes.py index c475a903f..d6e381945 100644 --- a/src/eval_tools/plugins/v3_lanes.py +++ b/src/eval_tools/plugins/v3_lanes.py @@ -242,6 +242,13 @@ class TileLensPlugin(_LanePlugin): every load and store address is checked against its tensor (z3 over the symbolic program id, mask and loop bounds). No GPU time is used. + A symbolic violation is a finding only when the lane's concrete rerun + (the ``bounds`` lane: the same case in Triton's interpreter, every active + address checked against the launch's argument buffers) reproduces an + out-of-bounds access. TileLens over-approximates loop-carried pointer + updates and loaded indices, so it can report an access that no execution + reaches. An unreproduced violation is recorded as unverified. + Gluon is reported unsupported: TileLens 3.1.1's interpreter failed on every Gluon task kernel tried (symbolic program ids, tuple values and ``@triton.jit`` helpers called from Gluon). @@ -265,13 +272,27 @@ def judge(self, context: ToolContext, execution) -> ParseResult: if error is not None: return error metadata = report.get("metadata") or {} + confirmation = metadata.get("confirmation") or {} if report.get("failure_kind") == "out_of_bounds": + if confirmation.get("status") != "confirmed": + return ParseResult(INCONCLUSIVE, reason_code="tilelens_unconfirmed", + details="out-of-bounds report without a concrete confirmation") findings = tuple( - FindingRecord(kind="out-of-bounds", message=f"{item.get('op')} on {item.get('tensor')} at " - f"{item.get('address')}", location="; ".join(item.get("location") or [])[:600] or None) - for item in (metadata.get("violations") or [])[:16] - ) or (FindingRecord(kind="out-of-bounds", message="TileLens reported an out-of-bounds access"),) + FindingRecord(kind="out-of-bounds", + message=f"{item.get('op')} of {item.get('bytes')} byte(s) at {item.get('address')} " + f"({item.get('lanes')} lane(s)) outside every argument buffer of " + f"{item.get('kernel')}", + location="; ".join(item.get("location") or [])[:600] or None) + for item in (confirmation.get("violations") or [])[:16] + ) or (FindingRecord(kind="out-of-bounds", message="An interpreter run accessed outside every buffer"),) return ParseResult(FINDING, findings, "tilelens_out_of_bounds", attested=True) + if report.get("failure_kind") == "unconfirmed": + symbolic = "; ".join(f"{item.get('op')} on {item.get('tensor')}" + for item in (metadata.get("violations") or [])[:8]) + return ParseResult(INCONCLUSIVE, reason_code="tilelens_unconfirmed", + details=(f"concrete rerun: {confirmation.get('status')}" + f"{' (' + str(confirmation.get('error')) + ')' if confirmation.get('error') else ''}" + f"; symbolic: {symbolic}")[:4000]) if report.get("failure_kind") == "unanalyzable": return ParseResult(INCONCLUSIVE, reason_code="tilelens_unanalyzable", details=_failure_text(report)[:4000]) if report.get("status") == "PASS": diff --git a/src/eval_tools/probes/tilelens_probe.py b/src/eval_tools/probes/tilelens_probe.py index adad6356f..6e95d35e4 100644 --- a/src/eval_tools/probes/tilelens_probe.py +++ b/src/eval_tools/probes/tilelens_probe.py @@ -1,9 +1,12 @@ -"""TileLens control: a Triton copy, optionally off by one element, checked symbolically. +"""TileLens control: a Triton copy, optionally off by one element. -Usage: tilelens_probe.py [safe|oob] +Usage: tilelens_probe.py [safe|oob|bounds_safe|bounds_oob] -Uses the same programmatic API as the schema-v3 lane: a Sanitizer client with -abort_on_error off, whose records are read after the launch. +``safe``/``oob`` use the same programmatic API as the schema-v3 lane: a +Sanitizer client with abort_on_error off, whose records are read after the +launch. ``bounds_safe``/``bounds_oob`` run the copy concretely in Triton's +interpreter (``TRITON_INTERPRET=1``) under the lane's own bounds check, which +must confirm a TileLens finding before it counts. """ from __future__ import annotations @@ -14,8 +17,12 @@ import torch import triton import triton.language as tl -import tilelens -from tilelens.clients import Sanitizer + +MODE = sys.argv[1] if len(sys.argv) > 1 else "safe" +if not MODE.startswith("bounds"): + # Imported before the kernel is defined, as in the lane. + import tilelens + from tilelens.clients import Sanitizer @triton.jit @@ -25,11 +32,25 @@ def copy_kernel(source, destination, shift: tl.constexpr, BLOCK: tl.constexpr): def main() -> int: - shift = 1 if len(sys.argv) > 1 and sys.argv[1] == "oob" else 0 - client = Sanitizer(abort_on_error=False) - kernel = tilelens.trace(client=client)(copy_kernel) + mode = MODE + shift = 1 if mode in ("oob", "bounds_oob") else 0 source = torch.arange(1024, device="cuda", dtype=torch.float32) destination = torch.empty_like(source) + if mode.startswith("bounds"): + from src.tools.arena_eval.sanitize import _bounds_patch + + state = {"violations": [], "violation_count": 0, "launches": 0, "kernel": None, "starts": None, + "ends": None} + unpatch = _bounds_patch(state) + try: + copy_kernel[(1,)](source, destination, shift, BLOCK=1024) + finally: + unpatch() + print("BOUNDS_RESULT " + json.dumps({"shift": shift, "launches": state["launches"], + "violations": state["violation_count"]}), flush=True) + return 0 + client = Sanitizer(abort_on_error=False) + kernel = tilelens.trace(client=client)(copy_kernel) kernel[(1,)](source, destination, shift, BLOCK=1024) print("TILELENS_RESULT " + json.dumps({"shift": shift, "records": len(client.records)}), flush=True) return 0 diff --git a/src/eval_tools/worker.py b/src/eval_tools/worker.py index 79f8a1756..4bfdfe780 100644 --- a/src/eval_tools/worker.py +++ b/src/eval_tools/worker.py @@ -982,26 +982,41 @@ def _csan_positive(probe_root: Path, work_dir: Path, artifact_dir: Path) -> dict def _tilelens_positive(evidence: Mapping[str, Any], probe_root: Path, work_dir: Path, artifact_dir: Path) -> dict[str, Any]: root = str(evidence.get("tilelens_root") or "") + # The lane's concrete bounds check (src/tools/arena_eval/sanitize.py) is + # copied beside src/eval_tools in the image. + framework = str(probe_root.parents[2]) steps, records = {}, {} - for name in ("safe", "oob"): + for name, marker, field, extra in ( + ("safe", "TILELENS_RESULT ", "records", {}), + ("oob", "TILELENS_RESULT ", "records", {}), + ("bounds_safe", "BOUNDS_RESULT ", "violations", {"TRITON_INTERPRET": "1"}), + ("bounds_oob", "BOUNDS_RESULT ", "violations", {"TRITON_INTERPRET": "1"}), + ): steps[name] = _run_probe_step( name, [_python(), str(probe_root / "tilelens_probe.py"), name], cwd=work_dir, - environment=_probe_environment(work_dir, PYTHONPATH=root), artifact_dir=artifact_dir, + environment=_probe_environment(work_dir, PYTHONPATH=os.pathsep.join(filter(None, (root, framework))), + **extra), + artifact_dir=artifact_dir, ) for line in str(steps[name]["_stdout"]).splitlines(): - if line.startswith("TILELENS_RESULT "): + if line.startswith(marker): try: - records[name] = int(json.loads(line[len("TILELENS_RESULT "):])["records"]) + records[name] = int(json.loads(line[len(marker):])[field]) except (ValueError, KeyError, TypeError): pass - safe_ok = steps["safe"]["returncode"] == 0 and records.get("safe") == 0 - oob_ok = steps["oob"]["returncode"] == 0 and (records.get("oob") or 0) > 0 + ok = {name: steps[name]["returncode"] == 0 and name in records for name in steps} + safe_ok = ok["safe"] and records["safe"] == 0 + oob_ok = ok["oob"] and records["oob"] > 0 + bounds_safe_ok = ok["bounds_safe"] and records["bounds_safe"] == 0 + bounds_oob_ok = ok["bounds_oob"] and records["bounds_oob"] > 0 return _positive_result( - passed=bool(root) and safe_ok and oob_ok, + passed=bool(root) and safe_ok and oob_ok and bounds_safe_ok and bounds_oob_ok, kind="tilelens_safe_and_off_by_one", - detail="TileLens must record no violation for an in-bounds copy and at least one for an off-by-one copy", + detail=("TileLens must record no violation for an in-bounds copy and at least one for an off-by-one copy, " + "and the concrete interpreter check that confirms its findings must agree on both"), artifact_dir=artifact_dir, steps=steps, - controls={"safe": {"passed": safe_ok}, "off_by_one": {"passed": oob_ok}}, + controls={"safe": {"passed": safe_ok}, "off_by_one": {"passed": oob_ok}, + "concrete_safe": {"passed": bounds_safe_ok}, "concrete_off_by_one": {"passed": bounds_oob_ok}}, ) diff --git a/src/tools/arena_eval/sanitize.py b/src/tools/arena_eval/sanitize.py index d6b6e016f..561bd4f9a 100644 --- a/src/tools/arena_eval/sanitize.py +++ b/src/tools/arena_eval/sanitize.py @@ -26,7 +26,14 @@ PyTorch-visible operations, including a HIP candidate's custom op). ``tilelens`` The smallest case with each Triton or Gluon kernel run by TileLens's - symbolic out-of-bounds checker in Triton's CPU interpreter. + symbolic out-of-bounds checker in Triton's CPU interpreter. A reported + access counts only after the ``bounds`` lane reproduces it. +``bounds`` + The smallest case with every Triton kernel run concretely in Triton's CPU + interpreter (``TRITON_INTERPRET=1``), each active load, store and atomic + address checked against the argument buffers of its launch. The + ``tilelens`` lane runs it to confirm a symbolic finding: TileLens + over-approximates loop-carried pointer updates and loaded indices. ``fpsan`` The smallest case through Triton FpSan for the candidate and the baseline (both Triton or Gluon); a differing digest means a different floating-point @@ -53,7 +60,7 @@ import warnings from pathlib import Path -LANES = ("page_fault_guard", "csan", "tilelens", "fpsan", "gpu_asan", "capture") +LANES = ("page_fault_guard", "csan", "tilelens", "bounds", "fpsan", "gpu_asan", "capture") # The allocator switches a lane requires; the sidecar sets them before start-up. NO_CACHING = {"PYTORCH_NO_HIP_MEMORY_CACHING": "1", "AMD_PYTORCH_NO_CUDA_MEMORY_CACHING": "1", @@ -284,9 +291,19 @@ def tilelens(contract, role: str) -> dict: metadata = {"case": case.case_id, "kernels": len(sanitizers), "violations": violations[:16], "violation_count": len(violations), "approximations": approximations} if violations: - row.update(status="FAIL", failure_kind="out_of_bounds") + # TileLens's model can place an access out of bounds that no execution + # reaches; only a concrete run of the same case decides. + confirmation = _confirm_bounds(role) + metadata["confirmation"] = confirmation + if confirmation["status"] == "confirmed": + row.update(status="FAIL", failure_kind="out_of_bounds") + return _report(role, "FAIL", [row], "tilelens", metadata, + f"TileLens found {len(violations)} out-of-bounds access(es); a concrete interpreter run " + f"reproduced {confirmation['violation_count']}", "out_of_bounds") + row.update(status="FAIL", failure_kind="unconfirmed") return _report(role, "FAIL", [row], "tilelens", metadata, - f"TileLens found {len(violations)} out-of-bounds access(es)", "out_of_bounds") + f"TileLens reported {len(violations)} out-of-bounds access(es) that a concrete interpreter " + f"run did not reproduce ({confirmation['status']})", "unconfirmed") if error is not None: row.update(status="FAIL", failure_kind="unanalyzable", metadata={"error": error}) return _report(role, "FAIL", [row], "tilelens", metadata, f"TileLens could not analyze the call: {error}", @@ -297,6 +314,200 @@ def tilelens(contract, role: str) -> dict: return _report(role, "PASS", [row], "tilelens", metadata) +# --------------------------------------------------------------------------- +# bounds + +BOUNDS_TIMEOUT_S = 1200 +BOUNDS_MAX_RECORDS = 16 + + +class _BoundsStop(Exception): + """An access the interpreter cannot mask (atomic CAS) left every buffer; stop the run.""" + + +def _bounds_location() -> list: + import traceback + + frames = [frame for frame in traceback.extract_stack()[:-2] if "/solution/" in frame.filename.replace("\\", "/")] + return [f"{frame.filename}:{frame.lineno} {frame.name}: {(frame.line or '').strip()}"[:300] + for frame in frames[-3:]] + + +def _bounds_patch(state: dict): + """Check every active access of Triton's interpreter against its launch's argument buffers. + + The interpreter copies each argument's whole storage to the host and the + kernel addresses those copies, so an access is in bounds when it lies in + one of them. An access outside every buffer is recorded and masked off + (never performed). Returns a function that removes the patch. + """ + import inspect + + import numpy as np + import triton.language as tl + import triton.runtime.interpreter as interpreter + + restore = [] + unwrap = getattr(interpreter, "_unwrap_tensor", lambda value: value) + try: + from triton.tools.tensor_descriptor import TensorDescriptor + except ImportError: # pragma: no cover - older Triton + TensorDescriptor = () + + executor = interpreter.GridExecutor + original_init = executor._init_args_hst + + def init_args_hst(self, args_dev, kwargs): + args_hst, kwargs_hst = original_init(self, args_dev, kwargs) + buffers = {} + + def walk(value): + if isinstance(value, (tuple, list)): + for item in value: + walk(item) + elif TensorDescriptor and isinstance(value, TensorDescriptor): + walk(value.base) + elif hasattr(value, "data_ptr"): + storage = unwrap(value).untyped_storage() + buffers[storage.data_ptr()] = storage.data_ptr() + storage.nbytes() + + walk(list(args_hst)) + walk(list(kwargs_hst.values())) + ordered = sorted(buffers.items()) + state["starts"] = np.array([start for start, _ in ordered], dtype=np.uint64) + state["ends"] = np.array([end for _, end in ordered], dtype=np.uint64) + state["kernel"] = getattr(getattr(self, "fn", None), "__name__", None) + state["launches"] += 1 + return args_hst, kwargs_hst + + executor._init_args_hst = init_args_hst + restore.append((executor, "_init_args_hst", original_init)) + + def keep_mask(op, ptrs, mask): + """None when every active access is in bounds, else the mask without the stray accesses.""" + addresses = np.asarray(ptrs.data).astype(np.uint64, copy=False) + active = (np.ones(addresses.shape, dtype=bool) if mask is None + else np.broadcast_to(np.asarray(mask.data, dtype=bool), addresses.shape)) + element = ptrs.dtype + while hasattr(element, "element_ty"): + element = element.element_ty + size = np.uint64(max(1, int(getattr(element, "primitive_bitwidth", 8)) // 8)) + starts, ends = state["starts"], state["ends"] + inside = np.zeros(addresses.shape, dtype=bool) + if starts.size: + index = np.searchsorted(starts, addresses, side="right").astype(np.int64) - 1 + inside = (index >= 0) & (addresses + size <= ends[np.clip(index, 0, None)]) + stray = active & ~inside + if not stray.any(): + return None + state["violation_count"] += int(stray.sum()) + if len(state["violations"]) < BOUNDS_MAX_RECORDS: + address = int(addresses[stray].flat[0]) + below = int(np.searchsorted(starts, np.uint64(address), side="right")) - 1 if starts.size else -1 + nearest = ({"buffer_bytes": int(ends[below]) - int(starts[below]), "offset": address - int(starts[below])} + if below >= 0 else None) + state["violations"].append({"op": op, "kernel": state["kernel"], "address": hex(address), + "bytes": int(size), "lanes": int(stray.sum()), "nearest_buffer": nearest, + "location": _bounds_location()}) + return np.ascontiguousarray(active & inside) + + builder = type(interpreter.interpreter_builder) + for name, op in (("create_masked_load", "load"), ("create_masked_store", "store"), + ("create_atomic_rmw", "atomic_rmw"), ("create_atomic_cas", "atomic_cas")): + original = getattr(builder, name, None) + if original is None: + continue + params = list(inspect.signature(original).parameters)[1:] + pointer = "ptrs" if "ptrs" in params else "ptr" + + def checked(self, *args, _original=original, _params=params, _pointer=pointer, _op=op, **kwargs): + bound = dict(zip(_params, args), **kwargs) + keep = keep_mask(_op, bound[_pointer], bound.get("mask")) + if keep is None: + return _original(self, *args, **kwargs) + if "mask" not in _params: + raise _BoundsStop(_op) + bound["mask"] = interpreter.TensorHandle(keep, tl.int1) + return _original(self, **bound) + + setattr(builder, name, checked) + restore.append((builder, name, original)) + + def unpatch(): + for owner, name, original in reversed(restore): + setattr(owner, name, original) + + return unpatch + + +def bounds(contract, role: str) -> dict: + evaluate = _evaluate() + implementation = contract.implementation(role) + if implementation.language != "triton": + raise evaluate.ActionFailure(f"The bounds lane checks Triton, not {implementation.language}", "unsupported") + _require_env({"TRITON_INTERPRET": "1"}) + device = evaluate._device() + state = {"violations": [], "violation_count": 0, "launches": 0, "kernel": None, "starts": None, "ends": None} + unpatch = _bounds_patch(state) + # Kernels execute in the CPU interpreter, which the GPU launch audit cannot + # observe; the call keeps its integrity check and ran audited in correctness. + call, _, check = _load_role(contract, role, enforce=False) + case = smallest_case(contract) + row = case.identity() + error = None + try: + _run_once(contract, call, case, device) + row["status"] = "PASS" + except _BoundsStop: + pass + except Exception as exc: + error = f"{type(exc).__name__}: {exc}"[:2000] + finally: + unpatch() + if check is not None: + check("sanitize") + metadata = {"case": case.case_id, "launches": state["launches"], "violations": state["violations"], + "violation_count": state["violation_count"]} + if state["violation_count"]: + row.update(status="FAIL", failure_kind="out_of_bounds") + return _report(role, "FAIL", [row], "bounds", metadata, + f"{state['violation_count']} access(es) outside every argument buffer", "out_of_bounds") + if error is not None: + row.update(status="FAIL", failure_kind="unanalyzable", metadata={"error": error}) + return _report(role, "FAIL", [row], "bounds", metadata, f"The interpreter run failed: {error}", + "unanalyzable") + if not state["launches"]: + return _report(role, "FAIL", [row], "bounds", metadata, "No Triton kernel ran in the interpreter", + "unanalyzable") + return _report(role, "PASS", [row], "bounds", metadata) + + +def _confirm_bounds(role: str) -> dict: + """Run the ``bounds`` lane in a fresh interpreter-mode process; summarize its verdict.""" + evaluate = _evaluate() + environment = {**os.environ, "TRITON_INTERPRET": "1"} + try: + process = subprocess.run([sys.executable, "-m", "_aka_eval.evaluate", role, "sanitize", "bounds"], + cwd=str(evaluate.WORKSPACE), env=environment, capture_output=True, text=True, + timeout=BOUNDS_TIMEOUT_S) + except subprocess.TimeoutExpired: + return {"status": "timeout", "violation_count": 0, "violations": [], + "error": f"no verdict within {BOUNDS_TIMEOUT_S} s"} + lines = [line for line in process.stdout.splitlines() if line.startswith(evaluate.PREFIX)] + try: + report = json.loads(lines[-1][len(evaluate.PREFIX):]) + except (IndexError, ValueError): + return {"status": "error", "violation_count": 0, "violations": [], + "error": f"exit {process.returncode}: {process.stderr.strip()[-1500:]}"} + metadata = report.get("metadata") or {} + status = {"out_of_bounds": "confirmed"}.get(report.get("failure_kind"), + "reproduced_nothing" if report.get("status") == "PASS" else "error") + return {"status": status, "violation_count": int(metadata.get("violation_count") or 0), + "violations": (metadata.get("violations") or [])[:BOUNDS_MAX_RECORDS], + "launches": metadata.get("launches"), + "error": None if status in ("confirmed", "reproduced_nothing") else (report.get("reason") or "")[:1500]} + + # --------------------------------------------------------------------------- # fpsan @@ -789,7 +1000,7 @@ def capture(contract, role: str) -> dict: return _report(role, "PASS", [case.identity() | {"status": "PASS"}], "capture", metadata) -_LANES = {"page_fault_guard": page_fault_guard, "csan": csan, "tilelens": tilelens, "fpsan": fpsan, +_LANES = {"page_fault_guard": page_fault_guard, "csan": csan, "tilelens": tilelens, "bounds": bounds, "fpsan": fpsan, "gpu_asan": gpu_asan, "capture": capture} diff --git a/tests/eval_tools/test_v3_sanitizers.py b/tests/eval_tools/test_v3_sanitizers.py index 7e4de86ee..8509e23fd 100644 --- a/tests/eval_tools/test_v3_sanitizers.py +++ b/tests/eval_tools/test_v3_sanitizers.py @@ -317,9 +317,24 @@ def test_csan_verdicts(tmp_path): def test_tilelens_verdicts(tmp_path): violation = {"op": "Load", "tensor": "x", "address": "0x10", "location": ["kernel.py:18"]} - found = _parse("tilelens", tmp_path, execution(report("tilelens", "FAIL", failure_kind="out_of_bounds", - metadata={"violations": [violation]}), returncode=1)) - assert found.finding == FindingStatus.FOUND and "kernel.py:18" in found.findings[0].locations[0] + concrete = {"op": "store", "kernel": "k", "address": "0x2000", "bytes": 4, "lanes": 1, + "location": ["solution/kernel.py:21 k: tl.store(out_ptrs + 1, o)"]} + found = _parse("tilelens", tmp_path, execution(report("tilelens", "FAIL", failure_kind="out_of_bounds", metadata={ + "violations": [violation], + "confirmation": {"status": "confirmed", "violation_count": 1, "violations": [concrete]}}), returncode=1)) + assert found.finding == FindingStatus.FOUND and "kernel.py:21" in found.findings[0].locations[0] + # A symbolic violation that a concrete interpreter run does not reproduce + # (TileLens over-approximates loop-carried pointers) is unverified. + for status in ("reproduced_nothing", "error", "timeout"): + unconfirmed = _parse("tilelens", tmp_path, execution(report("tilelens", "FAIL", failure_kind="unconfirmed", + metadata={"violations": [violation], + "confirmation": {"status": status}}), + returncode=1)) + assert unconfirmed.finding == FindingStatus.INCONCLUSIVE + assert unconfirmed.metadata["reason_code"] == "tilelens_unconfirmed" + unattested = _parse("tilelens", tmp_path, execution(report("tilelens", "FAIL", failure_kind="out_of_bounds", + metadata={"violations": [violation]}), returncode=1)) + assert unattested.finding == FindingStatus.INCONCLUSIVE unanalyzable = _parse("tilelens", tmp_path, execution(report("tilelens", "FAIL", failure_kind="unanalyzable"), returncode=1)) assert unanalyzable.finding == FindingStatus.INCONCLUSIVE diff --git a/tests/test_arena_eval_sanitize.py b/tests/test_arena_eval_sanitize.py index e8352de3f..466080f8b 100644 --- a/tests/test_arena_eval_sanitize.py +++ b/tests/test_arena_eval_sanitize.py @@ -1,7 +1,10 @@ """CPU checks of the v3 runner's sanitizer lanes: build flags, routing, environment and helpers.""" from __future__ import annotations +import json import struct +import subprocess +import sys import pytest @@ -176,3 +179,112 @@ def test_flydsl_observer_records_artifacts_reached_through_executor_methods(): finally: sys.setprofile(previous) assert observed == [artifact] + + +def _fake_interpreter(monkeypatch, calls): + """A stand-in for triton.runtime.interpreter with the methods the bounds lane wraps.""" + import types + + class TensorHandle: + def __init__(self, data, dtype): + self.data, self.dtype = data, dtype + + class Builder: + def create_masked_load(self, ptrs, mask, other, cache_policy, is_volatile): + calls.append(("load", list(mask.data))) + return "loaded" + + def create_masked_store(self, ptrs, value, mask, cache_policy): + calls.append(("store", list(mask.data))) + + def create_atomic_cas(self, ptr, cmp, val, sem, scope): + calls.append(("cas",)) + + class GridExecutor: + def __init__(self, fn): + self.fn = fn + + def _init_args_hst(self, args_dev, kwargs): + return list(args_dev), dict(kwargs) + + interpreter = types.ModuleType("triton.runtime.interpreter") + interpreter.TensorHandle, interpreter.GridExecutor = TensorHandle, GridExecutor + interpreter.interpreter_builder = Builder() + language = types.ModuleType("triton.language") + language.int1 = "int1" + runtime = types.ModuleType("triton.runtime") + runtime.interpreter = interpreter + triton = types.ModuleType("triton") + triton.language, triton.runtime = language, runtime + for name, module in (("triton", triton), ("triton.language", language), ("triton.runtime", runtime), + ("triton.runtime.interpreter", interpreter)): + monkeypatch.setitem(sys.modules, name, module) + pointer = types.SimpleNamespace(element_ty=types.SimpleNamespace(primitive_bitwidth=32)) + return interpreter, pointer + + +def test_bounds_checks_active_accesses_against_the_launch_buffers(monkeypatch): + import numpy as np + import torch + + calls = [] + interpreter, pointer = _fake_interpreter(monkeypatch, calls) + builder_type = type(interpreter.interpreter_builder) + original_load = builder_type.create_masked_load + state = {"violations": [], "violation_count": 0, "launches": 0, "kernel": None, "starts": None, "ends": None} + unpatch = sanitize._bounds_patch(state) + try: + buffer = torch.zeros(4, dtype=torch.float32) # 16 bytes: the only argument buffer + interpreter.GridExecutor(sanitize)._init_args_hst([buffer, 3], {}) + base = buffer.data_ptr() + builder = interpreter.interpreter_builder + ptrs = interpreter.TensorHandle(np.array([base, base + 12, base + 16], dtype=np.uint64), pointer) + + # A masked-off lane may hold any address: it is never accessed. + builder.create_masked_load(ptrs, interpreter.TensorHandle(np.array([True, True, False]), "int1"), + None, None, False) + assert state["violation_count"] == 0 and calls[-1] == ("load", [True, True, False]) + + # An active lane one element past the buffer is recorded and masked off. + assert builder.create_masked_load(ptrs, interpreter.TensorHandle(np.array([True, True, True]), "int1"), + None, None, False) == "loaded" + assert calls[-1] == ("load", [True, True, False]) + assert state["violation_count"] == 1 + record = state["violations"][0] + assert record["op"] == "load" and record["bytes"] == 4 and record["address"] == hex(base + 16) + assert record["nearest_buffer"] == {"buffer_bytes": 16, "offset": 16} + + builder.create_masked_store(ptrs, None, interpreter.TensorHandle(np.array([False, False, True]), "int1"), None) + assert calls[-1] == ("store", [False, False, False]) and state["violation_count"] == 2 + + # An atomic CAS has no mask to clear: the run stops at the stray access. + with pytest.raises(sanitize._BoundsStop): + builder.create_atomic_cas(ptrs, None, None, None, None) + assert state["launches"] == 1 + finally: + unpatch() + assert type(interpreter.interpreter_builder).create_masked_load is original_load + + +@pytest.mark.parametrize("stdout,returncode,status,count", [ + (evaluate.PREFIX + json.dumps({"status": "FAIL", "failure_kind": "out_of_bounds", + "metadata": {"violation_count": 3, "violations": [{"op": "store"}]}}), + 1, "confirmed", 3), + (evaluate.PREFIX + json.dumps({"status": "PASS", "metadata": {"violation_count": 0, "launches": 2}}), + 0, "reproduced_nothing", 0), + (evaluate.PREFIX + json.dumps({"status": "FAIL", "failure_kind": "unanalyzable", "reason": "boom"}), + 1, "error", 0), + ("Segmentation fault", -11, "error", 0), +]) +def test_a_tilelens_finding_is_confirmed_only_by_a_concrete_violation(monkeypatch, stdout, returncode, status, + count): + seen = {} + + def run(argv, **kwargs): + seen.update(argv=argv, env=kwargs["env"]) + return subprocess.CompletedProcess(argv, returncode, stdout=stdout + "\n", stderr="") + + monkeypatch.setattr(sanitize.subprocess, "run", run) + confirmation = sanitize._confirm_bounds("candidate") + assert seen["argv"][-3:] == ["candidate", "sanitize", "bounds"] and seen["env"]["TRITON_INTERPRET"] == "1" + assert confirmation["status"] == status and confirmation["violation_count"] == count From 55e4e5471c486104fe42f086ce48ba3556d3a096 Mon Sep 17 00:00:00 2001 From: Vincent Ouyang Date: Wed, 11 Nov 2026 04:43:12 -0800 Subject: [PATCH 7/9] Judge the page-fault guard's violation fraction only on enough elements The full MI355X campaign blocked one clean baseline, Triton layer_norm bf16_d256: its per-row mean for a one-row case missed the bound by 11% once with the allocators off. One element is a 100% violation fraction, so the gross-mismatch rule took it for a finding, and the baseline recheck happened to pass. The fraction rule now also needs at least 8 elements outside the bound. Non-finite values and errors over 10 times the bound stay gross at any size. The recorded lane report of that run is now judged unverified. --- docs/how-to/use-evaluation-tools.md | 2 +- src/eval_tools/plugins/v3_lanes.py | 11 ++++++++--- tests/eval_tools/test_v3_sanitizers.py | 3 +++ 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/how-to/use-evaluation-tools.md b/docs/how-to/use-evaluation-tools.md index 3c20f457c..097567791 100644 --- a/docs/how-to/use-evaluation-tools.md +++ b/docs/how-to/use-evaluation-tools.md @@ -61,7 +61,7 @@ network access (see below), or set `evaluation_tools: false`. | Tool | Default | Role | What it checks | Languages | | --- | --- | --- | --- | --- | -| `page_fault_guard` | on | gate | Every correctness case with PyTorch's caching allocator and ROCr's fragment allocator off. An access past an allocation then reaches an unmapped page and the GPU faults instead of landing silently in a neighbouring tensor; an output that passed correctness but then fails it far outside its bound (a non-finite value, more than 10 times the bound, or more than 1% of elements over it) is also a finding; a smaller excess is recorded as unverified, since split-K and atomic kernels vary that much from run to run. | Triton, Gluon, HIP, FlyDSL | +| `page_fault_guard` | on | gate | Every correctness case with PyTorch's caching allocator and ROCr's fragment allocator off. An access past an allocation then reaches an unmapped page and the GPU faults instead of landing silently in a neighbouring tensor; an output that passed correctness but then fails it far outside its bound (a non-finite value, more than 10 times the bound, or more than 1% of elements, and at least 8, over it) is also a finding; a smaller excess is recorded as unverified, since split-K and atomic kernels vary that much from run to run. | Triton, Gluon, HIP, FlyDSL | | `csan` | on | gate | Every correctness case under PyTorch's CUDA Sanitizer: unsynchronized access to a tensor from two streams by PyTorch-visible work, which includes a HIP candidate's custom op. Raw Triton, Gluon and FlyDSL launches are not visible to it. | all four | | `tilelens` | on | gate | The smallest case with every Triton kernel run by TileLens 3.1.1 in Triton's CPU interpreter; each load and store address is checked against its tensor symbolically (z3 over program id, mask and loop bounds). A reported access is a finding only when a concrete rerun of the same case in the interpreter, with every active load, store and atomic address checked against the launch's argument buffers, reproduces an out-of-bounds access; otherwise it is unverified. Uses no GPU time. Gluon is reported unsupported. | Triton | | `rocjitsu_waitcheck` | on | gate | Static missing or too-weak wait detection on every kernel the role dispatched. One call on the smallest case captures the final code objects (Triton/Gluon cache, the HIP extension's embedded bundle, FlyDSL's embedded HSACO). | all four | diff --git a/src/eval_tools/plugins/v3_lanes.py b/src/eval_tools/plugins/v3_lanes.py index d6e381945..190aa3179 100644 --- a/src/eval_tools/plugins/v3_lanes.py +++ b/src/eval_tools/plugins/v3_lanes.py @@ -175,6 +175,9 @@ def judge(self, context: ToolContext, execution) -> ParseResult: # Reading memory the role does not own yields values unrelated to the result. GROSS_BOUND_MULTIPLE = 10.0 GROSS_VIOLATION_FRACTION = 0.01 +# The fraction counts only with enough elements: one marginal miss in a +# one-element output (a per-row mean of one row) is a 100% fraction. +GROSS_MIN_ELEMENTS = 8 def _gross_mismatch(report: dict) -> bool: @@ -182,8 +185,8 @@ def _gross_mismatch(report: dict) -> bool: Gross: a non-finite value where the reference is finite, an error over ``GROSS_BOUND_MULTIPLE`` times the case's bound, more than - ``GROSS_VIOLATION_FRACTION`` of the elements outside it, or a failure - without these metrics. + ``GROSS_VIOLATION_FRACTION`` of the elements (and at least + ``GROSS_MIN_ELEMENTS``) outside it, or a failure without these metrics. """ failing = [row for row in report.get("cases") or [] if row.get("status") != "PASS"] @@ -197,9 +200,11 @@ def _gross_mismatch(report: dict) -> bool: return True for output in failed: try: + mismatched = output.get("mismatched_elements") + many = mismatched is None or int(mismatched) >= GROSS_MIN_ELEMENTS if (int(output.get("nonfinite_mismatches") or 0) > 0 or float(output.get("peak_bound_multiple", float("inf"))) > GROSS_BOUND_MULTIPLE - or float(output.get("violation_fraction", 1.0)) > GROSS_VIOLATION_FRACTION): + or (many and float(output.get("violation_fraction", 1.0)) > GROSS_VIOLATION_FRACTION)): return True except (TypeError, ValueError): return True diff --git a/tests/eval_tools/test_v3_sanitizers.py b/tests/eval_tools/test_v3_sanitizers.py index 8509e23fd..2b8bb7029 100644 --- a/tests/eval_tools/test_v3_sanitizers.py +++ b/tests/eval_tools/test_v3_sanitizers.py @@ -263,6 +263,9 @@ def _mismatch_case(**output): ({}, FindingStatus.INCONCLUSIVE), # one element 14% over a baseline-relative bound ({"peak_bound_multiple": 50.0}, FindingStatus.FOUND), ({"violation_fraction": 0.2}, FindingStatus.FOUND), + ({"violation_fraction": 0.2, "mismatched_elements": 100}, FindingStatus.FOUND), + # A one-row mean 11% over its bound: one element is a 100% fraction, not gross. + ({"violation_fraction": 1.0, "mismatched_elements": 1, "peak_bound_multiple": 1.11}, FindingStatus.INCONCLUSIVE), ({"nonfinite_mismatches": 3}, FindingStatus.FOUND), ]) def test_page_fault_guard_flags_only_gross_output_changes(tmp_path, output, finding): From aa5b0ea435a891b15400f9526ca39badf0924be7 Mon Sep 17 00:00:00 2001 From: Vincent Ouyang Date: Thu, 19 Nov 2026 21:19:20 -0800 Subject: [PATCH 8/9] Address review: multi-GPU, mixed reports, stale images, QA defaults - Every v3 tool reports a multi-GPU task (a contract world_size above 1) as unsupported: a lane calls the operator once in one process without a rank. CANDIDATE.md now says the sanitizers run on single-GPU tasks. - The page-fault guard judges a mixed report by its failed cases. An execution error no longer makes a marginal mismatch gross. - A baseline check lists the baseline's findings and, when it excuses the candidate, the excused findings; the evaluator logs the excused kinds. - A tool image is labelled with a digest of its Dockerfile and the checkout files it copies. The runner rebuilds a default image whose label differs and warns about an overridden one. - A qa_auditor run starts no default tools. - Waitcheck, rocJITsu and GPU ASan report a language no tool is qualified on (asm) as unsupported instead of not applicable, like the other lanes. - Style: plugins declare baseline_check (now part of ToolPlugin); the GPU ASan constants move to adapters/hip_source.py, which removes the import cycle that forced mid-module imports; the sidecar worker uses the shared fault pattern and allocator settings; the runner drops an always-true conditional; the gated log names its policy and blocking findings. --- docs/how-to/use-evaluation-tools.md | 23 ++++- docs/reference/release-notes.md | 7 +- src/eval_tools/adapters/hip_source.py | 19 +++- src/eval_tools/contracts.py | 3 + src/eval_tools/defaults.py | 9 +- src/eval_tools/manager.py | 18 +++- src/eval_tools/plugins/aka_v3.py | 24 +++++- src/eval_tools/plugins/consan.py | 3 + src/eval_tools/plugins/gpu_asan.py | 21 +---- src/eval_tools/plugins/hip_fpsan.py | 2 + src/eval_tools/plugins/rocjitsu.py | 3 +- src/eval_tools/plugins/triton_fpsan.py | 3 +- src/eval_tools/plugins/v3_lanes.py | 27 ++++-- src/eval_tools/plugins/v3_tools.py | 11 +++ src/eval_tools/plugins/waitcheck.py | 3 +- src/eval_tools/worker.py | 16 +--- src/evaluator.py | 16 +++- src/scripts/docker_benchmark.sh | 115 ++++++++++++++++++------- src/task_contract.py | 8 +- tests/eval_tools/test_manager.py | 1 + tests/eval_tools/test_v3_sanitizers.py | 60 ++++++++++++- tests/test_docker_benchmark.sh | 35 ++++++++ 22 files changed, 331 insertions(+), 96 deletions(-) diff --git a/docs/how-to/use-evaluation-tools.md b/docs/how-to/use-evaluation-tools.md index 097567791..1fb2d8d5a 100644 --- a/docs/how-to/use-evaluation-tools.md +++ b/docs/how-to/use-evaluation-tools.md @@ -71,8 +71,12 @@ network access (see below), or set `evaluation_tools: false`. Turn the stage off with `evaluation_tools: false` (or `enabled: []`). Any explicit `evaluation_tools` section is used exactly as written instead of the -defaults. To add GPU ASan on a bare-metal host, list the defaults plus -`gpu_asan`: +defaults. A `qa_auditor` run starts no default tools, because it never +evaluates a candidate. The default tools do not run on a multi-GPU task (a +contract with `world_size` above 1): each lane calls the operator in one +process on one GPU, so every tool records the task as `unsupported`. No tool +is qualified on `asm` candidates yet; each records them as `unsupported`. To +add GPU ASan on a bare-metal host, list the defaults plus `gpu_asan`: ```yaml evaluation_tools: @@ -91,8 +95,11 @@ a semantic comparison; set `evaluation_tools.tools..role` to override): - After a candidate finding the manager reruns the same tool on the task's baseline. When the baseline reports every kind of finding the candidate does, the finding is recorded with `baseline_also_found: true` and does not - block: the reference implementation does the same thing. A finding of a - kind the baseline does not report still blocks. On a task whose baseline + block: the reference implementation does the same thing. The record's + `baseline_check` lists the baseline's findings (`findings`) and the + candidate findings this excused (`excused`), each with its kind, kernel and + locations, and the run log names the excused kinds. A finding of a kind the + baseline does not report still blocks. On a task whose baseline has a finding of some kind, that tool therefore cannot block a candidate for that kind; the page-fault guard and the other gates still apply. - Anything that is not a definite finding — an unsupported construct, a @@ -365,6 +372,14 @@ any missing default image on first use): src/scripts/docker_benchmark.sh build-eval-tool-images ``` +Each image runs its own copy of `src/eval_tools`. A build labels the image +with a SHA-256 of its Dockerfile and every checkout file the Dockerfile copies +(`com.amd.agent-kernel-arena.eval-tool-source`). Before it starts a sidecar, +the runner compares that label with the current checkout and rebuilds a +default image built from other sources. An image named by +`AKA_EVAL_TOOL_IMAGE_` is used as given, with a warning when its label +differs. + The default local tags are: ```text diff --git a/docs/reference/release-notes.md b/docs/reference/release-notes.md index bb97b4ddd..7e52ffda6 100644 --- a/docs/reference/release-notes.md +++ b/docs/reference/release-notes.md @@ -81,8 +81,11 @@ This topic summarizes the features available in each AgentKernelArena release. F cannot run its runtime. - Gluon candidates are supported by FpSan, GPU ASan, Waitcheck and rocJITsu through the v3 path; TileLens 3.1.1 reports Gluon unsupported. -- The runner builds missing default sidecar images on first use, and the - Waitcheck sidecar now gets the worker's GPU for capture. +- The runner builds missing default sidecar images on first use and rebuilds + one whose recorded tool sources differ from the checkout. The Waitcheck + sidecar now gets the worker's GPU for capture. +- The defaults do not start for a `qa_auditor` run, and every default tool + records a multi-GPU task or an `asm` candidate as `unsupported`. - `evaluation_tools: false` disables the stage. See [Check kernels with evaluation tools](../how-to/use-evaluation-tools.md#default-sanitizers-for-schema-v3-tasks). diff --git a/src/eval_tools/adapters/hip_source.py b/src/eval_tools/adapters/hip_source.py index a9ba0c1b1..721f2400c 100644 --- a/src/eval_tools/adapters/hip_source.py +++ b/src/eval_tools/adapters/hip_source.py @@ -5,7 +5,24 @@ from dataclasses import dataclass from pathlib import Path -from ..plugins.gpu_asan import GPU_ASAN_ENV, hip_asan_build_flags + +# GPU ASan's runtime environment and HIP build flags, shared by the gpu_asan +# plugin and its HIP rebuild recipe. +GPU_ASAN_ENV = { + "HSA_XNACK": "1", + "HSA_DISABLE_FRAGMENT_ALLOCATOR": "1", + "AMD_PYTORCH_NO_CUDA_MEMORY_CACHING": "1", + "PYTORCH_NO_HIP_MEMORY_CACHING": "1", + "AMDGCN_USE_BUFFER_OPS": "0", + "ASAN_OPTIONS": "detect_leaks=0,alloc_dealloc_mismatch=0", +} + + +def hip_asan_build_flags(target_arch: str) -> tuple[str, ...]: + arch = target_arch.split(":", 1)[0].strip() + if not arch.startswith("gfx"): + raise ValueError(f"invalid AMD GPU architecture: {target_arch!r}") + return ("-fsanitize=address", "-shared-libsan", f"--offload-arch={arch}:xnack+") @dataclass(frozen=True) diff --git a/src/eval_tools/contracts.py b/src/eval_tools/contracts.py index 471c012f3..87a2aca8c 100644 --- a/src/eval_tools/contracts.py +++ b/src/eval_tools/contracts.py @@ -806,6 +806,9 @@ def execute(self, invocation: ToolInvocation, context: ToolContext) -> Execution class ToolPlugin(Protocol): name: str version: str + # Whether the manager reruns this tool on the task's baseline after a + # candidate finding under the ``gated`` policy. + baseline_check: bool def assess( self, context: ToolContext, runtime: CapabilityCheck diff --git a/src/eval_tools/defaults.py b/src/eval_tools/defaults.py index 9ddfc702e..cc77fef7c 100644 --- a/src/eval_tools/defaults.py +++ b/src/eval_tools/defaults.py @@ -5,7 +5,8 @@ architecture and publishes the started set as ``AKA_EVAL_TOOLS_SELECTED``; the scoring process then plans that set under ``DEFAULT_POLICY`` with each tool's default role. ``evaluation_tools: false`` (or ``enabled: []``) turns -the stage off, and an explicit section keeps full control. +the stage off, and an explicit section keeps full control. A QA-auditor run +starts no defaults: it never evaluates a candidate. GPU AddressSanitizer is supported but not a default: its runtime needs XNACK host-memory access, which virtualized GPU hosts do not provide. Enable it on @@ -48,6 +49,9 @@ # Per-tool deadline on the default path; a timeout is recorded as unverified. DEFAULT_TIMEOUT_S = 1200 DEFAULT_ARCHITECTURES = frozenset({"gfx950"}) +# Agents whose tasks never reach the final candidate evaluation, where the +# tools run; the defaults would only start idle sidecars for them. +NO_CANDIDATE_EVALUATION_AGENTS = frozenset({"qa_auditor"}) def default_role(tool: str) -> str: @@ -57,6 +61,9 @@ def default_role(tool: str) -> str: def runner_selection(config: object, gpu_arch: str) -> tuple[str, ...]: """The tools the runner starts for a parsed run configuration.""" if not isinstance(config, dict) or "evaluation_tools" not in config: + agent = config.get("agent") if isinstance(config, dict) else None + if isinstance(agent, dict) and agent.get("template") in NO_CANDIDATE_EVALUATION_AGENTS: + return () return DEFAULT_ENABLED if gpu_arch in DEFAULT_ARCHITECTURES else () section = config["evaluation_tools"] if section in (None, False): diff --git a/src/eval_tools/manager.py b/src/eval_tools/manager.py index 23152f59b..069cbc0f4 100644 --- a/src/eval_tools/manager.py +++ b/src/eval_tools/manager.py @@ -35,6 +35,19 @@ BASELINE_ALSO_FOUND = "baseline_also_found" +# Findings listed per side in a baseline check record. +_LISTED_FINDINGS = 16 + + +def _finding_identity(finding: Any) -> dict[str, Any]: + """A finding's kind, kernel and locations, as recorded in a baseline check.""" + identity: dict[str, Any] = {"kind": finding.kind} + kernel = (finding.metadata or {}).get("kernel") + if kernel: + identity["kernel"] = str(kernel) + if finding.locations: + identity["locations"] = list(finding.locations) + return identity def evaluate_policy( @@ -472,7 +485,7 @@ def evaluate( plan.policy == EvaluationPolicy.GATED and tool_plan.role == ToolRole.GATE and result.finding == FindingStatus.FOUND - and getattr(plugin, "baseline_check", False) + and plugin.baseline_check ): result = self._baseline_check(plugin, tool_plan, context, root, plan.fingerprint, result) evaluations.append(ToolEvaluation(capability=capability, result=result)) @@ -538,8 +551,11 @@ def _baseline_check( candidate_kinds = {item.kind for item in result.findings} baseline_kinds = {item.kind for item in baseline.findings} check["kinds"] = sorted(baseline_kinds) + check["findings"] = [_finding_identity(item) for item in baseline.findings[:_LISTED_FINDINGS]] if candidate_kinds <= baseline_kinds: metadata[BASELINE_ALSO_FOUND] = True + # The candidate findings this excuses, so a report shows them. + check["excused"] = [_finding_identity(item) for item in result.findings[:_LISTED_FINDINGS]] return replace(result, metadata=metadata) # ``execute`` reads naturally at evaluator integration sites and remains an diff --git a/src/eval_tools/plugins/aka_v3.py b/src/eval_tools/plugins/aka_v3.py index 9172bb452..7de1460a6 100644 --- a/src/eval_tools/plugins/aka_v3.py +++ b/src/eval_tools/plugins/aka_v3.py @@ -16,7 +16,7 @@ from pathlib import Path from typing import Any, Mapping, Optional -from ..contracts import KernelLanguage, ToolContext, ToolInvocation +from ..contracts import CapabilityCheck, CapabilityState, KernelLanguage, ToolContext, ToolInvocation from ..task_declarations import is_v3_task SIDECAR_PYTHON = "/opt/venv/bin/python" @@ -64,6 +64,28 @@ def role_language(context: ToolContext) -> str: return baseline_language(context) if role(context) == "baseline" else target_language(context) +def world_size(context: ToolContext) -> int: + """The number of GPUs (ranks) the task's operator runs on; 1 for a single-GPU task.""" + return int(_contract(context).get("world_size") or 1) + + +def multi_gpu_check(context: ToolContext, tool: str) -> Optional[CapabilityCheck]: + """``unsupported`` for a multi-GPU task, else None. + + Every v3 lane calls the operator once in one process without a rank, so + it cannot run an operator that spans several ranks. + """ + + ranks = world_size(context) + if ranks <= 1: + return None + return CapabilityCheck.blocked( + CapabilityState.UNSUPPORTED, f"{tool}_multi_gpu_unsupported", + f"{tool} runs the operator in one process on one GPU; this task's operator runs on {ranks} ranks.", + world_size=ranks, + ) + + def language_enum(value: str) -> KernelLanguage: return {item.value: item for item in KernelLanguage}.get(value, KernelLanguage.UNKNOWN) diff --git a/src/eval_tools/plugins/consan.py b/src/eval_tools/plugins/consan.py index 828bc1155..0485d9de4 100644 --- a/src/eval_tools/plugins/consan.py +++ b/src/eval_tools/plugins/consan.py @@ -50,6 +50,9 @@ def _commands(context: ToolContext) -> tuple[tuple[str, ...], tuple[str, ...]]: class ConSanPlugin: name = ToolName.ROCJITSU_CONSAN.value version = "1" + # The task-declared adapter names only the candidate's code object, so + # there is no baseline to rerun. + baseline_check = False def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: profile = context.profile diff --git a/src/eval_tools/plugins/gpu_asan.py b/src/eval_tools/plugins/gpu_asan.py index 6ac072bec..eec9f0cc1 100644 --- a/src/eval_tools/plugins/gpu_asan.py +++ b/src/eval_tools/plugins/gpu_asan.py @@ -4,6 +4,7 @@ from pathlib import Path +from ..adapters.hip_source import GPU_ASAN_ENV, hip_asan_build_flags from ..contracts import ( ArtifactKind, CapabilityCheck, @@ -16,6 +17,7 @@ ToolName, ToolRunResult, ) +from . import aka_v3, v3_tools from .attestation import BuildAttestation from .base import ( artifact_path, @@ -29,16 +31,6 @@ from .parsers import parse_gpu_asan -GPU_ASAN_ENV = { - "HSA_XNACK": "1", - "HSA_DISABLE_FRAGMENT_ALLOCATOR": "1", - "AMD_PYTORCH_NO_CUDA_MEMORY_CACHING": "1", - "PYTORCH_NO_HIP_MEMORY_CACHING": "1", - "AMDGCN_USE_BUFFER_OPS": "0", - "ASAN_OPTIONS": "detect_leaks=0,alloc_dealloc_mismatch=0", -} - - def _prepend_paths(*values: str | None, inherited: str = "") -> str: paths: list[str] = [] for value in (*values, inherited): @@ -48,15 +40,6 @@ def _prepend_paths(*values: str | None, inherited: str = "") -> str: return ":".join(paths) -def hip_asan_build_flags(target_arch: str) -> tuple[str, ...]: - arch = target_arch.split(":", 1)[0].strip() - if not arch.startswith("gfx"): - raise ValueError(f"invalid AMD GPU architecture: {target_arch!r}") - return ("-fsanitize=address", "-shared-libsan", f"--offload-arch={arch}:xnack+") - - -from . import aka_v3, v3_tools - class GpuAsanPlugin: name = ToolName.GPU_ASAN.value version = "2" diff --git a/src/eval_tools/plugins/hip_fpsan.py b/src/eval_tools/plugins/hip_fpsan.py index f0feca2ea..0048e754f 100644 --- a/src/eval_tools/plugins/hip_fpsan.py +++ b/src/eval_tools/plugins/hip_fpsan.py @@ -31,6 +31,8 @@ class HipFpSanPlugin: name = ToolName.HIP_FPSAN.value version = "2" + # A signal: never a blocking gate, so no baseline rerun. + baseline_check = False def assess(self, context: ToolContext, runtime: CapabilityCheck) -> ToolCapability: profile = context.profile diff --git a/src/eval_tools/plugins/rocjitsu.py b/src/eval_tools/plugins/rocjitsu.py index de8b58d3a..544f4de60 100644 --- a/src/eval_tools/plugins/rocjitsu.py +++ b/src/eval_tools/plugins/rocjitsu.py @@ -21,6 +21,7 @@ ToolName, ToolRunResult, ) +from . import aka_v3, v3_tools from .base import ( INCONCLUSIVE, ParseResult, @@ -109,8 +110,6 @@ def _race_report_path(context: ToolContext) -> Path: ) -from . import aka_v3, v3_tools - class RocJitsuPlugin: name = ToolName.ROCJITSU.value version = "3" diff --git a/src/eval_tools/plugins/triton_fpsan.py b/src/eval_tools/plugins/triton_fpsan.py index fda80cc55..1f722b8c4 100644 --- a/src/eval_tools/plugins/triton_fpsan.py +++ b/src/eval_tools/plugins/triton_fpsan.py @@ -15,6 +15,7 @@ ToolName, ToolRunResult, ) +from . import aka_v3, v3_tools from .attestation import BuildAttestation from .base import ( artifact_path, @@ -27,8 +28,6 @@ from .parsers import parse_fpsan_comparison -from . import aka_v3, v3_tools - class TritonFpSanPlugin: name = ToolName.TRITON_FPSAN.value version = "2" diff --git a/src/eval_tools/plugins/v3_lanes.py b/src/eval_tools/plugins/v3_lanes.py index 190aa3179..79c01164a 100644 --- a/src/eval_tools/plugins/v3_lanes.py +++ b/src/eval_tools/plugins/v3_lanes.py @@ -44,6 +44,9 @@ def _v3_engine(context: ToolContext, tool: str, languages: frozenset[str], f"{tool}_requires_v3_runner", f"{tool} runs the generated schema-v3 workspace runner; this task has none.", ) + multi_gpu = aka_v3.multi_gpu_check(context, tool) + if multi_gpu is not None: + return multi_gpu language = aka_v3.role_language(context) if language not in aka_v3.V3_LANGUAGES: return blocked_check( @@ -159,16 +162,18 @@ def judge(self, context: ToolContext, execution) -> ParseResult: finding = FindingRecord(kind="gpu-memory-fault", message="an illegal device memory access was reported " "while the caching allocators were off", raw=text[:4000]) return ParseResult(FINDING, (finding,), "page_fault_guard_fault", attested=True) - if kind in ("numerical_mismatch", "input_mutation", "mixed"): - if kind == "numerical_mismatch" and not _gross_mismatch(report): - # A small excess over the case's bound is indistinguishable from - # the task's own run-to-run variation (split-K, atomics). - return ParseResult(INCONCLUSIVE, reason_code="page_fault_guard_marginal_mismatch", - details=text[:4000], attested=True) + # A ``mixed`` report is judged by the kinds of its failed cases. + kinds = _failed_kinds(report) if kind == "mixed" else {kind} + if "input_mutation" in kinds or ("numerical_mismatch" in kinds and _gross_mismatch(report)): finding = FindingRecord(kind="allocator-sensitive-output", message="outputs that passed correctness " "changed when the caching allocators were off: the role reads memory it does " "not own", raw=text[:4000]) return ParseResult(FINDING, (finding,), "page_fault_guard_allocator_sensitive", attested=True) + if "numerical_mismatch" in kinds: + # A small excess over the case's bound is indistinguishable from + # the task's own run-to-run variation (split-K, atomics). + return ParseResult(INCONCLUSIVE, reason_code="page_fault_guard_marginal_mismatch", + details=text[:4000], attested=True) return ParseResult(TOOL_ERROR, reason_code=f"page_fault_guard_{kind or 'failed'}", details=text[:4000]) @@ -180,16 +185,22 @@ def judge(self, context: ToolContext, execution) -> ParseResult: GROSS_MIN_ELEMENTS = 8 +def _failed_kinds(report: dict) -> set: + return {row.get("failure_kind") for row in report.get("cases") or [] if row.get("status") != "PASS"} + + def _gross_mismatch(report: dict) -> bool: - """Whether a failed output is far outside its bound, not a marginal miss. + """Whether a numerically failed output is far outside its bound, not a marginal miss. Gross: a non-finite value where the reference is finite, an error over ``GROSS_BOUND_MULTIPLE`` times the case's bound, more than ``GROSS_VIOLATION_FRACTION`` of the elements (and at least ``GROSS_MIN_ELEMENTS``) outside it, or a failure without these metrics. + Cases that failed another way (an execution error) are not judged here. """ - failing = [row for row in report.get("cases") or [] if row.get("status") != "PASS"] + failing = [row for row in report.get("cases") or [] if row.get("status") != "PASS" + and row.get("failure_kind", "numerical_mismatch") == "numerical_mismatch"] if not failing: return True for row in failing: diff --git a/src/eval_tools/plugins/v3_tools.py b/src/eval_tools/plugins/v3_tools.py index d1d83ae7e..aad68dd58 100644 --- a/src/eval_tools/plugins/v3_tools.py +++ b/src/eval_tools/plugins/v3_tools.py @@ -45,6 +45,9 @@ def _engine(context: ToolContext, tool: str, ready_languages: set[str], reasons: dict[str, str]) -> CapabilityCheck: + multi_gpu = aka_v3.multi_gpu_check(context, tool) + if multi_gpu is not None: + return multi_gpu language = aka_v3.role_language(context) if language in ready_languages: if context.gpu_arch and context.gpu_arch != SUPPORTED_ARCH: @@ -54,6 +57,11 @@ def _engine(context: ToolContext, tool: str, ready_languages: set[str], reasons: return ready_check(adapter=aka_v3.ADAPTER, language=language) if language in reasons: return blocked_check(CapabilityState.UNSUPPORTED, f"{tool}_{language}_unsupported", reasons[language]) + if language not in aka_v3.V3_LANGUAGES: + # A target language no v3 tool is qualified on (asm) is unverified, + # not skipped as not applicable. + return blocked_check(CapabilityState.UNSUPPORTED, f"{tool}_language_unsupported", + f"{tool} supports triton, gluon, hip and flydsl, not {language!r}.") return blocked_check(CapabilityState.NOT_APPLICABLE, f"{tool}_language_not_applicable", f"{tool} does not apply to {language} kernels.") @@ -79,6 +87,9 @@ def _triton_profile(context: ToolContext) -> ToolContext: def fpsan_engine(context: ToolContext) -> CapabilityCheck: + multi_gpu = aka_v3.multi_gpu_check(context, "triton_fpsan") + if multi_gpu is not None: + return multi_gpu languages = {aka_v3.target_language(context), aka_v3.baseline_language(context)} if not languages <= {"triton", "gluon"}: return blocked_check(CapabilityState.NOT_APPLICABLE, "triton_fpsan_needs_triton_pair", diff --git a/src/eval_tools/plugins/waitcheck.py b/src/eval_tools/plugins/waitcheck.py index fb9362d4a..0b12f5392 100644 --- a/src/eval_tools/plugins/waitcheck.py +++ b/src/eval_tools/plugins/waitcheck.py @@ -13,6 +13,7 @@ ToolName, ToolRunResult, ) +from . import aka_v3, v3_tools from .base import ( blocked_check, unsupported_language_check, @@ -47,8 +48,6 @@ def _expected_kernel(context: ToolContext) -> str: return value -from . import aka_v3, v3_tools - class WaitcheckPlugin: name = ToolName.ROCJITSU_WAITCHECK.value version = "1" diff --git a/src/eval_tools/worker.py b/src/eval_tools/worker.py index 4bfdfe780..1b4faff6f 100644 --- a/src/eval_tools/worker.py +++ b/src/eval_tools/worker.py @@ -28,6 +28,7 @@ execute_command, ) from .config import MAX_TOOL_TIMEOUT_SECONDS +from .plugins import aka_v3 from .plugins.base import FINDING, PASS from .plugins.parsers import parse_consan, parse_waitcheck @@ -915,17 +916,6 @@ def _hip_fpsan_positive( ) -_NO_CACHING = { - "PYTORCH_NO_HIP_MEMORY_CACHING": "1", - "AMD_PYTORCH_NO_CUDA_MEMORY_CACHING": "1", - "HSA_DISABLE_FRAGMENT_ALLOCATOR": "1", -} -_FAULT_RE = re.compile( - r"Memory access fault by GPU|HSA_STATUS_ERROR_MEMORY_FAULT|Memory Fault Error|illegal memory access", - re.I, -) - - def _python() -> str: return shutil.which("python") or os.sys.executable @@ -942,14 +932,14 @@ def _page_fault_guard_positive(probe_root: Path, work_dir: Path, artifact_dir: P for name in ("safe", "far"): steps[name] = _run_probe_step( name, [_python(), str(probe_root / "page_fault_probe.py"), name], cwd=work_dir, - environment=_probe_environment(work_dir, **_NO_CACHING, + environment=_probe_environment(work_dir, **aka_v3.NO_CACHING, TRITON_CACHE_DIR=str(work_dir / "triton-cache")), artifact_dir=artifact_dir, ) safe, far = steps["safe"], steps["far"] safe_ok = safe["returncode"] == 0 and "SAFE_RUN_COMPLETED" in safe["_stdout"] far_ok = far["returncode"] not in (0, None) and not far["timed_out"] and bool( - _FAULT_RE.search(str(far["_stderr"]) + str(far["_stdout"]))) + aka_v3.FAULT_RE.search(str(far["_stderr"]) + str(far["_stdout"]))) return _positive_result( passed=safe_ok and far_ok, kind="page_fault_guard_safe_and_far_store", diff --git a/src/evaluator.py b/src/evaluator.py index 83b45eee4..547a3dee6 100644 --- a/src/evaluator.py +++ b/src/evaluator.py @@ -134,6 +134,7 @@ def evaluate_kernel( # The policy decides only whether performance may proceed. if eval_tools_config is not None: from .eval_tools.config import EvalToolsConfig, merge_task_tool_config + from .eval_tools.manager import BASELINE_ALSO_FOUND parsed_tool_config = ( eval_tools_config @@ -158,12 +159,23 @@ def evaluate_kernel( original_evidence=tool_source_evidence, ) results['tool_evaluation'] = report.to_dict() + for evaluation in report.evaluations: + tool_result = evaluation.result + if tool_result is not None and tool_result.metadata.get(BASELINE_ALSO_FOUND): + log.warning( + "Evaluation tool %s: %d finding(s) not blocking because the baseline reports " + "the same kind: %s", + tool_result.tool, tool_result.findings_count, + ", ".join(sorted({item.kind for item in tool_result.findings})), + ) results['pass_tool_gate'] = report.decision.allowed results['tool_policy_satisfied'] = report.decision.policy_satisfied if not report.decision.allowed: log.warning( - "Evaluation-tool required policy rejected performance: %s", - ", ".join(report.decision.reasons) or "unspecified tool failure", + "Evaluation-tool %s policy blocked performance: %s", + report.decision.policy.value, + ", ".join(report.decision.blocking or report.decision.reasons) + or "unspecified tool failure", ) return results diff --git a/src/scripts/docker_benchmark.sh b/src/scripts/docker_benchmark.sh index 1ca68ba1f..7e61a9c64 100755 --- a/src/scripts/docker_benchmark.sh +++ b/src/scripts/docker_benchmark.sh @@ -1028,23 +1028,21 @@ build_eval_tool_docker_args() { # Every sidecar, Waitcheck included, gets the worker's GPU: schema-v3 tasks # capture the dispatched kernels on the device before analysing them. - if true; then - local gpu_grp gpu_gid - for gpu_grp in render video; do - gpu_gid="$(getent group "$gpu_grp" 2>/dev/null | cut -d: -f3 || true)" - [[ -z "$gpu_gid" ]] || eval_tool_docker_args+=(--group-add "$gpu_gid") - done - [[ ! -e /dev/kfd ]] || eval_tool_docker_args+=(--device=/dev/kfd) - [[ ! -e /dev/dri ]] || eval_tool_docker_args+=(--device=/dev/dri) - - if [[ -n "${AKA_VISIBLE_GPU:-}" ]]; then - eval_tool_docker_args+=( - -e "ROCR_VISIBLE_DEVICES=${AKA_VISIBLE_GPU}" - -e "HIP_VISIBLE_DEVICES=${AKA_LOGICAL_GPU:-0}" - -e "CUDA_VISIBLE_DEVICES=${AKA_LOGICAL_GPU:-0}" - -e "GPU_DEVICE_ORDINAL=${AKA_LOGICAL_GPU:-0}" - ) - fi + local gpu_grp gpu_gid + for gpu_grp in render video; do + gpu_gid="$(getent group "$gpu_grp" 2>/dev/null | cut -d: -f3 || true)" + [[ -z "$gpu_gid" ]] || eval_tool_docker_args+=(--group-add "$gpu_gid") + done + [[ ! -e /dev/kfd ]] || eval_tool_docker_args+=(--device=/dev/kfd) + [[ ! -e /dev/dri ]] || eval_tool_docker_args+=(--device=/dev/dri) + + if [[ -n "${AKA_VISIBLE_GPU:-}" ]]; then + eval_tool_docker_args+=( + -e "ROCR_VISIBLE_DEVICES=${AKA_VISIBLE_GPU}" + -e "HIP_VISIBLE_DEVICES=${AKA_LOGICAL_GPU:-0}" + -e "CUDA_VISIBLE_DEVICES=${AKA_LOGICAL_GPU:-0}" + -e "GPU_DEVICE_ORDINAL=${AKA_LOGICAL_GPU:-0}" + ) fi eval_tool_docker_args+=( @@ -1167,17 +1165,48 @@ stop_eval_tool_sidecars() { EVAL_TOOL_SELECTED="" } -build_eval_tool_image() { - local tool="$1" image="$2" dockerfile target="" - case "$tool" in +# The label that records which checkout files an evaluation-tool image was +# built from (see eval_tool_source_digest). +EVAL_TOOL_SOURCE_LABEL="com.amd.agent-kernel-arena.eval-tool-source" + +eval_tool_dockerfile() { + case "$1" in rocjitsu_waitcheck|rocjitsu_consan) - dockerfile="$HOST_ROOT/docker/eval-tools/rocjitsu-sanitizers/Dockerfile" - target="${tool//_/-}-runtime" + printf '%s\n' "$HOST_ROOT/docker/eval-tools/rocjitsu-sanitizers/Dockerfile" ;; *) - dockerfile="$HOST_ROOT/docker/eval-tools/${tool//_/-}/Dockerfile" + printf '%s\n' "$HOST_ROOT/docker/eval-tools/${1//_/-}/Dockerfile" ;; esac +} + +eval_tool_source_digest() { + # SHA-256 over the Dockerfile and every checkout path it COPYs. Each image + # runs its own copy of src/eval_tools, so an image built from other sources + # would run old tool code. + local dockerfile="$1" line word + local -a words sources=() + while IFS= read -r line; do + read -r -a words <<<"$line" + for word in "${words[@]:1:${#words[@]}-2}"; do + [[ "$word" == --* ]] || sources+=("$word") + done + done < <(grep -E '^COPY[[:space:]]' "$dockerfile" | grep -v -- '--from=') + ( + cd "$HOST_ROOT" || exit 1 + find "${dockerfile#"$HOST_ROOT"/}" "${sources[@]}" -type f \ + ! -name '*.py[cod]' ! -path '*/__pycache__/*' -print0 \ + | LC_ALL=C sort -z | xargs -0 sha256sum + ) | sha256sum | cut -d' ' -f1 +} + +build_eval_tool_image() { + local tool="$1" image="$2" dockerfile target="" source_digest + dockerfile="$(eval_tool_dockerfile "$tool")" + case "$tool" in + rocjitsu_waitcheck|rocjitsu_consan) target="${tool//_/-}-runtime" ;; + esac + source_digest="$(eval_tool_source_digest "$dockerfile")" # Pull each pinned FROM image through the daemon first. BuildKit resolves a # missing base itself and, on hosts whose registry TLS only the daemon # trusts, fails; with --pull=false it uses the local copy instead. @@ -1186,22 +1215,32 @@ build_eval_tool_image() { docker image inspect "$base" >/dev/null 2>&1 || docker pull -q "$base" >&2 \ || die "Cannot pull $base for evaluation-tool image $image" done < <(sed -nE 's/^ARG (BASE_IMAGE|BUILDER_IMAGE)=(.+)$/\2/p' "$dockerfile") - if [[ -n "$target" ]]; then - docker build --pull=false --target "$target" -f "$dockerfile" -t "$image" "$HOST_ROOT" - else - docker build --pull=false -f "$dockerfile" -t "$image" "$HOST_ROOT" - fi + local -a build_args=(build --pull=false --label "$EVAL_TOOL_SOURCE_LABEL=$source_digest" -f "$dockerfile" -t "$image") + [[ -z "$target" ]] || build_args+=(--target "$target") + docker "${build_args[@]}" "$HOST_ROOT" } ensure_eval_tool_image() { # Default tools run without a separate build step: a missing default image - # is built once per host. An overridden image must already exist. - local tool="$1" image="$2" tool_upper - docker image inspect "$image" >/dev/null 2>&1 && return 0 + # is built once per host, and one built from other tool sources is rebuilt. + # An overridden image must already exist and is used as given. + local tool="$1" image="$2" tool_upper expected actual tool_upper="$(printf '%s' "$tool" | tr '[:lower:]' '[:upper:]')" local env_name="AKA_EVAL_TOOL_IMAGE_${tool_upper}" - [[ -z "${!env_name:-}" ]] || die "Evaluation-tool image $image ($env_name) is not present on this host" - echo "Building missing evaluation-tool image $image" >&2 + if docker image inspect "$image" >/dev/null 2>&1; then + expected="$(eval_tool_source_digest "$(eval_tool_dockerfile "$tool")")" + actual="$(docker image inspect --format "{{ index .Config.Labels \"$EVAL_TOOL_SOURCE_LABEL\" }}" "$image" \ + 2>/dev/null || true)" + [[ "$actual" != "$expected" ]] || return 0 + if [[ -n "${!env_name:-}" ]]; then + warn "Evaluation-tool image $image ($env_name) was not built from this checkout's tool sources" + return 0 + fi + echo "Rebuilding evaluation-tool image $image: it was built from other tool sources" >&2 + else + [[ -z "${!env_name:-}" ]] || die "Evaluation-tool image $image ($env_name) is not present on this host" + echo "Building missing evaluation-tool image $image" >&2 + fi build_eval_tool_image "$tool" "$image" >&2 || die "Failed to build evaluation-tool image $image" } @@ -2462,6 +2501,16 @@ case "${1:-}" in verify_eval_tool_scoring_image printf '%s\n' "$SELECTED_IMAGE" "$AKA_SCORING_IMAGE_RUNTIME_REF" "$AKA_SCORING_IMAGE_REFERENCE" ;; + _ensure_eval_tool_image) + shift + [[ "$#" -eq 2 ]] || die "_ensure_eval_tool_image expects TOOL IMAGE" + ensure_eval_tool_image "$1" "$2" + ;; + _eval_tool_source_digest) + shift + [[ "$#" -eq 1 ]] || die "_eval_tool_source_digest expects TOOL" + eval_tool_source_digest "$(eval_tool_dockerfile "$1")" + ;; _prepare_eval_tool_artifact_dir) shift [[ "$#" -eq 2 ]] \ diff --git a/src/task_contract.py b/src/task_contract.py index 6af6679a8..223a619dd 100644 --- a/src/task_contract.py +++ b/src/task_contract.py @@ -825,10 +825,10 @@ def _candidate_document(contract: TaskContract, language: str) -> str: "the current stream.", "- Correctness: each output must stay within the declared error bound of the high-precision " "reference on every workload, for two input draws and a repeated call on the same buffers.", - "- The final evaluation also runs sanitizers on the correctness cases: PyTorch's caching " - "allocator off (an access past a tensor faults), PyTorch's CUDA Sanitizer, a symbolic " - "bounds check of Triton/Gluon kernels, and static wait-hazard and simulated race checks of the " - "kernels you launch. A definite finding the baseline does not share stops performance scoring.", + "- On a single-GPU task, the final evaluation also runs sanitizers on the correctness cases: " + "PyTorch's caching allocator off (an access past a tensor faults), PyTorch's CUDA Sanitizer, a " + "symbolic bounds check of Triton/Gluon kernels, and static wait-hazard and simulated race checks " + "of the kernels you launch. A definite finding the baseline does not share stops performance scoring.", "", "## Commands", "", "```sh", f"python3 -m {EVAL_DIR}.evaluate candidate compile", f"python3 -m {EVAL_DIR}.evaluate candidate correctness", diff --git a/tests/eval_tools/test_manager.py b/tests/eval_tools/test_manager.py index 508052cea..b1d8694c6 100644 --- a/tests/eval_tools/test_manager.py +++ b/tests/eval_tools/test_manager.py @@ -24,6 +24,7 @@ @dataclass class FakePlugin: + baseline_check = False name: str = "gpu_asan" version: str = "1.0" parse_mode: str = "clean" diff --git a/tests/eval_tools/test_v3_sanitizers.py b/tests/eval_tools/test_v3_sanitizers.py index 2b8bb7029..5e876b2e9 100644 --- a/tests/eval_tools/test_v3_sanitizers.py +++ b/tests/eval_tools/test_v3_sanitizers.py @@ -80,6 +80,10 @@ def test_runner_starts_defaults_only_without_a_section_on_a_default_architecture assert defaults.runner_selection({"evaluation_tools": {"enabled": ["gpu_asan"]}}, "gfx950") == ("gpu_asan",) assert defaults.runner_selection({"evaluation_tools": {"enabled": True}}, "gfx950") == defaults.ALL_TOOLS assert "gpu_asan" not in defaults.DEFAULT_ENABLED + # A QA audit never evaluates a candidate; an explicit section still applies. + qa = {"agent": {"template": "qa_auditor"}} + assert defaults.runner_selection(qa, "gfx950") == () + assert defaults.runner_selection({**qa, "evaluation_tools": {"enabled": ["csan"]}}, "gfx950") == ("csan",) def test_defaults_name_every_registered_tool(): @@ -207,7 +211,12 @@ def test_a_gate_finding_is_rechecked_on_the_baseline(tmp_path, found_for, baseli if found_for: assert runtime.commands == [("lane", "candidate"), ("lane", "baseline")] assert bool(result.metadata.get(BASELINE_ALSO_FOUND)) is shared - assert result.metadata["baseline_check"]["finding"] == ("found" if "baseline" in found_for else "clean") + check = result.metadata["baseline_check"] + assert check["finding"] == ("found" if "baseline" in found_for else "clean") + if "baseline" in found_for: + assert check["findings"] == [{"kind": baseline_kind}] + # The excused candidate findings are listed only when they are excused. + assert check.get("excused") == ([{"kind": "fault"}] if shared else None) else: assert runtime.commands == [("lane", "candidate")] @@ -230,6 +239,37 @@ def test_v3_lane_capability_by_language(tmp_path, tool, language, state): assert capability.effective.state == state +def _multi_gpu_context(tmp_path, target="triton"): + context = v3_context(tmp_path, target=target) + config = {**context.task_config, "contract": {**context.task_config["contract"], "world_size": 4}} + return replace(context, task_config=config) + + +@pytest.mark.parametrize("tool", [*defaults.DEFAULT_ENABLED, "gpu_asan"]) +def test_every_v3_tool_reports_a_multi_gpu_task_unsupported(tmp_path, tool): + # Each lane calls the operator in one process without a rank. + capability = get_plugin(tool).assess(_multi_gpu_context(tmp_path), CapabilityCheck.ready()) + assert capability.effective.state == CapabilityState.UNSUPPORTED + assert capability.effective.reason_code == f"{tool}_multi_gpu_unsupported" + assert get_plugin(tool).assess(v3_context(tmp_path), CapabilityCheck.ready()).effective.state \ + == CapabilityState.READY + + +@pytest.mark.parametrize("tool", ["page_fault_guard", "csan", "tilelens", "rocjitsu_waitcheck", "rocjitsu", + "gpu_asan"]) +def test_an_unqualified_target_language_is_unsupported_not_skipped(tmp_path, tool): + capability = get_plugin(tool).assess(v3_context(tmp_path, target="asm"), CapabilityCheck.ready()) + assert capability.effective.state == CapabilityState.UNSUPPORTED + + +def test_a_multi_gpu_task_is_unverified_but_not_blocked_by_the_gated_policy(tmp_path): + capability = get_plugin("page_fault_guard").assess(_multi_gpu_context(tmp_path), CapabilityCheck.ready()) + decision = evaluate_policy(EvaluationPolicy.GATED, (ToolEvaluation(capability=capability),), + {"page_fault_guard": ToolRole.GATE}) + assert decision.allowed and not decision.policy_satisfied + assert decision.reasons == ("page_fault_guard:capability:unsupported",) + + def test_v3_lanes_do_not_apply_without_the_v3_runner(tmp_path): plain = replace(v3_context(tmp_path), task_config={"schema_version": 2}) capability = get_plugin("page_fault_guard").assess(plain, CapabilityCheck.ready()) @@ -295,6 +335,24 @@ def test_page_fault_guard_verdicts(tmp_path): assert crashed.finding == FindingStatus.FOUND +def test_page_fault_guard_judges_a_mixed_report_by_its_cases(tmp_path): + crash = {"test_case_id": "m1", "status": "FAIL", "failure_kind": "execution_error", + "metadata": {"error": "RuntimeError: launch failed"}} + + def judge(*cases): + return _parse("page_fault_guard", tmp_path, execution(report( + "page_fault_guard", "FAIL", failure_kind="mixed", reason=f"{len(cases)} cases failed", + cases=list(cases)), returncode=1)) + + # A marginal mismatch and an error without a fault are each unverified, so together too. + assert judge(_mismatch_case(), crash).finding == FindingStatus.INCONCLUSIVE + assert judge(_mismatch_case(peak_bound_multiple=50.0), crash).finding == FindingStatus.FOUND + mutated = {"test_case_id": "m2", "status": "FAIL", "failure_kind": "input_mutation"} + assert judge(mutated, crash).finding == FindingStatus.FOUND + errors = judge(crash, {**crash, "failure_kind": "policy_violation"}) + assert errors.finding == FindingStatus.INCONCLUSIVE and errors.execution == ExecutionStatus.TOOL_ERROR + + @pytest.mark.parametrize("stdout", [ "", report("page_fault_guard") + "\nprinted after the report", diff --git a/tests/test_docker_benchmark.sh b/tests/test_docker_benchmark.sh index 73622bdb3..b836c7c6a 100755 --- a/tests/test_docker_benchmark.sh +++ b/tests/test_docker_benchmark.sh @@ -79,6 +79,10 @@ docker() { image) [[ -f "$FAKE_RUNTIME_DIR/image-present" ]] || return 1 ;; esac fi + if [[ "${1:-}" == "image" && "${2:-}" == "inspect" && " $* " == *".Config.Labels"* ]]; then + printf '%s\n' "${FAKE_EVAL_TOOL_LABEL:-}" + return 0 + fi if [[ "${1:-}" == "image" && "${2:-}" == "inspect" ]]; then local reference="${!#}" if [[ "$reference" == "$PINNED_GFX950_IMMUTABLE_IMAGE" ]]; then @@ -1309,6 +1313,37 @@ printf 'tasks: []\nevaluation_tools: false\n' > "$EVAL_DEFAULT_CONFIG" printf 'tasks: []\nevaluation_tools:\n enabled: [gpu_asan, csan]\n' > "$EVAL_DEFAULT_CONFIG" [[ "$(bash "$RUNNER" _resolve_eval_tools "$EVAL_DEFAULT_CONFIG" gfx950 | tr '\n' ' ')" == "gpu_asan csan " ]] \ || fail "an explicit evaluation_tools.enabled list must be used as given" +printf 'tasks: []\nagent:\n template: qa_auditor\n' > "$EVAL_DEFAULT_CONFIG" +[[ -z "$(bash "$RUNNER" _resolve_eval_tools "$EVAL_DEFAULT_CONFIG" gfx950)" ]] \ + || fail "a QA-auditor run must not start the default sanitizers" + +# Each image runs its own copy of the tool sources: a default image whose +# source label differs from this checkout is rebuilt, and an overridden one is +# used as given with a warning. +eval_digest="$(bash "$RUNNER" _eval_tool_source_digest page_fault_guard)" +[[ "$eval_digest" =~ ^[0-9a-f]{64}$ ]] || fail "evaluation-tool source digest was: $eval_digest" +[[ "$eval_digest" != "$(bash "$RUNNER" _eval_tool_source_digest tilelens)" ]] \ + || fail "images with different Dockerfiles must have different source digests" +EVAL_IMAGE_DIR="$TEST_HOME/eval-image" +mkdir -p "$EVAL_IMAGE_DIR" +touch "$EVAL_IMAGE_DIR/image-present" +FAKE_RUNTIME_DIR="$EVAL_IMAGE_DIR" FAKE_EVAL_TOOL_LABEL="$eval_digest" \ + bash "$RUNNER" _ensure_eval_tool_image page_fault_guard example.invalid/pfg:test >/dev/null 2>&1 \ + || fail "a current evaluation-tool image was rejected" +[[ ! -e "$EVAL_IMAGE_DIR/build-args" ]] || fail "a current evaluation-tool image was rebuilt" +FAKE_RUNTIME_DIR="$EVAL_IMAGE_DIR" FAKE_EVAL_TOOL_LABEL="0000" \ + bash "$RUNNER" _ensure_eval_tool_image page_fault_guard example.invalid/pfg:test >/dev/null 2>&1 \ + || fail "a stale evaluation-tool image was not rebuilt" +grep -Fxq "com.amd.agent-kernel-arena.eval-tool-source=$eval_digest" "$EVAL_IMAGE_DIR/build-args" \ + || fail "a rebuilt evaluation-tool image does not carry its source label" +rm -f "$EVAL_IMAGE_DIR/build-args" +stale_warning="$(FAKE_RUNTIME_DIR="$EVAL_IMAGE_DIR" FAKE_EVAL_TOOL_LABEL="0000" \ + AKA_EVAL_TOOL_IMAGE_PAGE_FAULT_GUARD=example.invalid/pfg:mine \ + bash "$RUNNER" _ensure_eval_tool_image page_fault_guard example.invalid/pfg:mine 2>&1 >/dev/null)" \ + || fail "an overridden evaluation-tool image was rejected" +[[ ! -e "$EVAL_IMAGE_DIR/build-args" ]] || fail "an overridden evaluation-tool image was rebuilt" +[[ "$stale_warning" == *"not built from this checkout's tool sources"* ]] \ + || fail "a stale overridden evaluation-tool image gave no warning: $stale_warning" framework_record="$( env -u AKA_EVAL_TOOL_FRAMEWORK_ROOT PYTHONDONTWRITEBYTECODE=1 python3 - <<'PY' From 52b905ca5e896e73713071849865d9b621dbd4c8 Mon Sep 17 00:00:00 2001 From: Vincent Ouyang Date: Thu, 19 Nov 2026 22:37:11 -0800 Subject: [PATCH 9/9] Match baseline findings by location, run asm lanes, state the gate - A baseline recheck excuses a candidate finding only when the baseline reports it in the same kernel at the same location. Findings with neither (a page fault, an allocator-sensitive output, a CSAN race) still match by kind. - The bounds lane records TileLens locations relative to the role's directory, so a candidate that copies the baseline reports the baseline's location; before, a baseline rerun recorded none. - asm candidates get the page-fault guard, CSAN and Waitcheck: capture writes every code object aka_asm handed to HIP. rocJITsu (no capsule capture for asm launches) and GPU ASan (no instrumentation) report asm unsupported. - CANDIDATE.md states that an out-of-bounds address in the Triton source blocks, even on a load the compiler removes. - The docs and the advisory example config state that the gated default is a scoring gate: a finding can withhold a score but never raise one. --- docs/how-to/use-evaluation-tools.md | 52 ++++++++++++------- docs/reference/release-notes.md | 6 ++- .../evaluation_tools_advisory_mi355x.yaml | 11 ++-- src/eval_tools/manager.py | 41 +++++++++++---- src/eval_tools/plugins/aka_v3.py | 2 +- src/eval_tools/plugins/v3_lanes.py | 3 +- src/eval_tools/plugins/v3_tools.py | 12 +++-- src/eval_tools/probes/tilelens_probe.py | 2 +- src/task_contract.py | 4 +- src/tools/arena_eval/asm.py | 10 ++++ src/tools/arena_eval/sanitize.py | 44 +++++++++++++--- tests/eval_tools/test_v3_sanitizers.py | 51 +++++++++++++++++- tests/test_arena_eval_asm.py | 13 +++++ tests/test_arena_eval_sanitize.py | 26 +++++++++- 14 files changed, 225 insertions(+), 52 deletions(-) diff --git a/docs/how-to/use-evaluation-tools.md b/docs/how-to/use-evaluation-tools.md index 1fb2d8d5a..6026f24a9 100644 --- a/docs/how-to/use-evaluation-tools.md +++ b/docs/how-to/use-evaluation-tools.md @@ -61,22 +61,21 @@ network access (see below), or set `evaluation_tools: false`. | Tool | Default | Role | What it checks | Languages | | --- | --- | --- | --- | --- | -| `page_fault_guard` | on | gate | Every correctness case with PyTorch's caching allocator and ROCr's fragment allocator off. An access past an allocation then reaches an unmapped page and the GPU faults instead of landing silently in a neighbouring tensor; an output that passed correctness but then fails it far outside its bound (a non-finite value, more than 10 times the bound, or more than 1% of elements, and at least 8, over it) is also a finding; a smaller excess is recorded as unverified, since split-K and atomic kernels vary that much from run to run. | Triton, Gluon, HIP, FlyDSL | -| `csan` | on | gate | Every correctness case under PyTorch's CUDA Sanitizer: unsynchronized access to a tensor from two streams by PyTorch-visible work, which includes a HIP candidate's custom op. Raw Triton, Gluon and FlyDSL launches are not visible to it. | all four | -| `tilelens` | on | gate | The smallest case with every Triton kernel run by TileLens 3.1.1 in Triton's CPU interpreter; each load and store address is checked against its tensor symbolically (z3 over program id, mask and loop bounds). A reported access is a finding only when a concrete rerun of the same case in the interpreter, with every active load, store and atomic address checked against the launch's argument buffers, reproduces an out-of-bounds access; otherwise it is unverified. Uses no GPU time. Gluon is reported unsupported. | Triton | -| `rocjitsu_waitcheck` | on | gate | Static missing or too-weak wait detection on every kernel the role dispatched. One call on the smallest case captures the final code objects (Triton/Gluon cache, the HIP extension's embedded bundle, FlyDSL's embedded HSACO). | all four | -| `rocjitsu` | on | gate | rocJITsu's simulated LDS/register race detector. Each captured Triton or Gluon launch becomes a replay capsule (code object, lowered ABI, launch geometry, memory before and after) replayed once in the simulator. | Triton, Gluon | +| `page_fault_guard` | on | gate | Every correctness case with PyTorch's caching allocator and ROCr's fragment allocator off. An access past an allocation then reaches an unmapped page and the GPU faults instead of landing silently in a neighbouring tensor; an output that passed correctness but then fails it far outside its bound (a non-finite value, more than 10 times the bound, or more than 1% of elements, and at least 8, over it) is also a finding; a smaller excess is recorded as unverified, since split-K and atomic kernels vary that much from run to run. | Triton, Gluon, HIP, FlyDSL, asm | +| `csan` | on | gate | Every correctness case under PyTorch's CUDA Sanitizer: unsynchronized access to a tensor from two streams by PyTorch-visible work, which includes a HIP candidate's custom op. Raw Triton, Gluon, FlyDSL and asm launches are not visible to it. | all five | +| `tilelens` | on | gate | The smallest case with every Triton kernel run by TileLens 3.1.1 in Triton's CPU interpreter; each load and store address is checked against its tensor symbolically (z3 over program id, mask and loop bounds). A reported access is a finding only when a concrete rerun of the same case in the interpreter, with every active load, store and atomic address checked against the launch's argument buffers, reproduces an out-of-bounds access; otherwise it is unverified. Uses no GPU time. The check reads the source, so an out-of-bounds address blocks even on a load whose value is unused or that the compiler removes; `CANDIDATE.md` says so. Gluon is reported unsupported. | Triton | +| `rocjitsu_waitcheck` | on | gate | Static missing or too-weak wait detection on every kernel the role dispatched. One call on the smallest case captures the final code objects (Triton/Gluon cache, the HIP extension's embedded bundle, FlyDSL's embedded HSACO, every code object `aka_asm` loaded). | all five | +| `rocjitsu` | on | gate | rocJITsu's simulated LDS/register race detector. Each captured Triton or Gluon launch becomes a replay capsule (code object, lowered ABI, launch geometry, memory before and after) replayed once in the simulator. Assembly launches are not captured as capsules yet, so `asm` is unsupported. | Triton, Gluon | | `triton_fpsan` | on | signal | The smallest case through Triton FpSan for the candidate and the baseline. A different digest means a different floating-point expression, which a correct rewrite (online softmax, another reduction order or precision) also produces, so this never blocks. | Triton or Gluon candidate with a Triton or Gluon baseline | -| `gpu_asan` | **off** | gate | Every correctness case with GPU AddressSanitizer instrumentation: HIP rebuilt with `-fsanitize=address -shared-libsan --offload-arch=gfx950:xnack+`, Triton and Gluon compiled with `TRITON_ENABLE_ASAN=1` and buffer ops off. | HIP, Triton, Gluon; bare-metal hosts only | +| `gpu_asan` | **off** | gate | Every correctness case with GPU AddressSanitizer instrumentation: HIP rebuilt with `-fsanitize=address -shared-libsan --offload-arch=gfx950:xnack+`, Triton and Gluon compiled with `TRITON_ENABLE_ASAN=1` and buffer ops off. | HIP, Triton, Gluon; bare-metal hosts only (hand-written `asm` carries no instrumentation) | Turn the stage off with `evaluation_tools: false` (or `enabled: []`). Any explicit `evaluation_tools` section is used exactly as written instead of the defaults. A `qa_auditor` run starts no default tools, because it never evaluates a candidate. The default tools do not run on a multi-GPU task (a contract with `world_size` above 1): each lane calls the operator in one -process on one GPU, so every tool records the task as `unsupported`. No tool -is qualified on `asm` candidates yet; each records them as `unsupported`. To -add GPU ASan on a bare-metal host, list the defaults plus `gpu_asan`: +process on one GPU, so every tool records the task as `unsupported`. To add +GPU ASan on a bare-metal host, list the defaults plus `gpu_asan`: ```yaml evaluation_tools: @@ -93,21 +92,35 @@ a semantic comparison; set `evaluation_tools.tools..role` to override): finding: a fault, a sanitizer report, a race or hazard record, or an output far outside its bound with the allocator changed. - After a candidate finding the manager reruns the same tool on the task's - baseline. When the baseline reports every kind of finding the candidate - does, the finding is recorded with `baseline_also_found: true` and does not - block: the reference implementation does the same thing. The record's - `baseline_check` lists the baseline's findings (`findings`) and the - candidate findings this excused (`excused`), each with its kind, kernel and - locations, and the run log names the excused kinds. A finding of a kind the - baseline does not report still blocks. On a task whose baseline - has a finding of some kind, that tool therefore cannot block a candidate - for that kind; the page-fault guard and the other gates still apply. + baseline. When the baseline reports every candidate finding, the finding is + recorded with `baseline_also_found: true` and does not block: the reference + implementation does the same thing. A finding that names a kernel or a + location (Waitcheck, rocJITsu, TileLens) must match a baseline finding in + kind, kernel and location; one with neither (a page fault, an + allocator-sensitive output, a CSAN race) matches by kind. TileLens locations + are relative to the role's directory, so a candidate that copies the + baseline reports the same location. The record's `baseline_check` lists the + baseline's findings (`findings`) and the candidate findings this excused + (`excused`), each with its kind, kernel and locations, and the run log names + the excused kinds. Any other finding blocks, including a new race or + out-of-bounds access in a kernel whose baseline already has one elsewhere. + On a task whose baseline has an unlocated finding (it faults with the + caching allocators off), that tool cannot block a candidate's finding of + the same kind; the other gates still apply. - Anything that is not a definite finding — an unsupported construct, a kernel TileLens cannot interpret, a tool error, a timeout, a capture that recorded nothing — is recorded as unverified (`policy_satisfied: false`) and does not block. - A `signal` never blocks. +The `gated` default is a scoring gate, not a security boundary. A gate can +only withhold performance scoring: a candidate that evades or interferes +with a tool scores no higher than it would with the stage off, and what it +can hide is a finding. That makes the stage safe to run by default even +though, as described under the phase boundary below, its sidecars run in the +same phase as the agent and its results are not tamper-resistant evidence +about an adversarial candidate. + `decision.blocking` lists the findings that stopped performance; a gated report's `decision.reasons` still lists every unverified tool. Monitor the unverified rate per language: a candidate that a lane cannot analyze (for @@ -1117,7 +1130,8 @@ generate attestations and AOT capsules there. Per-tool socket directories and a narrow per-worker artifact mount are already implemented, but the current single-container runner does not automate this phase boundary, so its tool results should be treated as diagnostic evidence rather than tamper-resistant -rewards. +rewards. The default `gated` policy fits within that limit: it uses a finding +only to withhold a score, never to raise one. ### Held-out integrity diff --git a/docs/reference/release-notes.md b/docs/reference/release-notes.md index 7e52ffda6..15762af6d 100644 --- a/docs/reference/release-notes.md +++ b/docs/reference/release-notes.md @@ -85,7 +85,11 @@ This topic summarizes the features available in each AgentKernelArena release. F one whose recorded tool sources differ from the checkout. The Waitcheck sidecar now gets the worker's GPU for capture. - The defaults do not start for a `qa_auditor` run, and every default tool - records a multi-GPU task or an `asm` candidate as `unsupported`. + records a multi-GPU task as `unsupported`. +- `asm` candidates get the page-fault guard, CSAN and Waitcheck (on every code + object `aka_asm` loaded); rocJITsu and GPU ASan report them unsupported. +- A baseline recheck excuses a finding only when the baseline reports it in + the same kernel at the same location (unlocated findings: the same kind). - `evaluation_tools: false` disables the stage. See [Check kernels with evaluation tools](../how-to/use-evaluation-tools.md#default-sanitizers-for-schema-v3-tasks). diff --git a/example_configs/evaluation_tools_advisory_mi355x.yaml b/example_configs/evaluation_tools_advisory_mi355x.yaml index 329dd6404..febc1de31 100644 --- a/example_configs/evaluation_tools_advisory_mi355x.yaml +++ b/example_configs/evaluation_tools_advisory_mi355x.yaml @@ -14,10 +14,13 @@ # The runner already uses one writable socket directory per tool and a narrow # repository-root `.eval-tool-artifacts/