Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 37 additions & 13 deletions docs/audit/compiler/COMPILER_REFACTOR_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,13 @@ table is the single skim surface. `✅` done · `🟡` partial · `⬜` not star
| **3** | C0 backend-plugin handoff + non-Apple F4 gate | ✅ (PR #285) | — | — |
| **3** | C1 x86 plugin (`emit/x86_llvm.py`: emitter + `cc` compile + ctypes runner) | ✅ emit host-free | ✅ execute on Zen 5 | — |
| **3** | Oracle accuracy budget (`KernelRunner.accuracy_atol`, D2 seed) | ✅ | — | — |
| **3** | C1b x86 AOCL-DLP Tier-3 candidate (opt-in) | — | ⬜ | — |
| **3** | C1b x86 AOCL-DLP Tier-3 candidate (opt-in) | 🟡 candidate wired host-free | 🟡 generic Tier-1 proven on Zen; AOCL lane library-gated | — |
| **4** | C2 NVIDIA emit pipeline + launch bridge | ⬜ | — | ⬜ |
| **5** | C3 ROCm generic synth → HIP (`emit/rocm_hip.py`: emitter + `hipcc` + runner) | ✅ emit host-free | ✅ gfx1151 FusedRegion | — |
| **5** | C3 tail — drive WMMA/MFMA `Generate*` passes through the loop | ⬜ | ⬜ | — |
| **5** | C3 tail — drive WMMA/MFMA `Generate*` passes through the loop | ✅ WMMA host-free | ✅ gfx1151 fused WMMA F4-gated (MFMA=CDNA-gated) | — |
| **3.5** | ROCm shipped-kernel → F4 gate (flash-attn, f16 budget) + shared scalar body | ✅ | ✅ gfx1151 attn | — |
| **6** | D1–D3 arbitration + measured autotune | ⬜ | ⬜ | ⬜ |
| **6** | D1 candidate registry + F4-gate + tier-priority arbiter + `force` (E3) | ✅ (`emit/candidate.py`) | ✅ gfx1151 enumerate+select | — |
| **6** | D2 measured autotune loop · D3 fallback log | ⬜ | ⬜ | ⬜ |

**Gate reality (softens §4/§9.2):** "Phase 0 gates everything" holds only for the
*lead-execution* proofs. The Mac-side E1 gate is green and gfx1151 E2 is recorded,
Expand Down Expand Up @@ -246,6 +247,14 @@ chains, small attention). Crown-jewel GEMM stays Tier 2/3.
Accelerate — Decision #23-clean, behind the hardware-free Target IR). The
arbiter selects it only where it measures faster than the generic kernels on
Zen; **check its license before it becomes a shipped/linked lane.**
**Landed 2026-07-07 (arbiter-facing seam, host-free):** `emit/x86_aocl_dlp.py`
registers `X86AoclDlpCandidate` (Tier-3) alongside the new `X86GenericCCandidate`
(Tier-1) under `target="x86"`. `available()` probes `$TESSERA_AOCL_DLP_LIB` +
`$TESSERA_AOCL_DLP_SGEMM`; absent here, so it is arbiter-visible but never
mis-selects (arbitration falls to the generic C lane, proven on Zen 5). **Still
open (needs a licensed aocl-dlp install):** bind the concrete GEMM post-op ctypes
ABI against real headers (deliberately *not* guessed — `_aocl_dlp_gemm` declines
until wired), run the license review, then F4-gate + measure on Zen.
- **C2 · NVIDIA in-process emit pipeline** `[MAC]` authoring → `[NV]` proof —
`tessera-opt --tessera-emit-nvidia`: Tile IR → `ptx_emit.py` (keep sm_120
`mma.sync`; extend `wgmma` for sm_90a; stub sm_100 tcgen05) → serialize →
Expand All @@ -266,12 +275,19 @@ chains, small attention). Crown-jewel GEMM stays Tier 2/3.
launches on gfx1151 (`"rocm_hip"`), F4-gated. The per-row scalar body is
**shared with the x86 C lane** (`emit/_fused_scalar_body.py`) so both stay
locked to the one `fusion_core` reference. Same NULL-buffer guard as x86.
**C3 tail (still open):** wire the existing gfx1151 WMMA + CDNA MFMA
`Generate*` passes (the hand-tuned MLIR kernel generators) through the shared
loop as Tier-3 arbiter candidates, reusing the async-token SSA model in
`ROCMWaveLdsPipeline` — the generic scalar HIP kernel above is a correctness-
first middle-ground candidate, NOT a replacement for those crown-jewel lanes
(lead-safety; the D1 arbiter picks per measured latency + accuracy budget).
**C3 tail (WMMA landed 2026-07-07):** the gfx1151 WMMA `generate-wmma-gemm-kernel`
`Generate*` pass is now a **Tier-3 D1 candidate** (`RocmWmmaGemmCandidate` in
`emit/rocm_hip.py`) driven through the shared loop: `runtime._rocm_wmma_fused_2d`
runs the compiler-generated fused GEMM+bias+{relu,gelu,silu} on matrix cores
(f16 storage / f32 accum), gated by the *same* universal F4 oracle as the generic
lane and registered alongside it under `target="rocm"`. The generic scalar HIP
kernel stays the Tier-1 middle-ground candidate; the flash-attn lane is the Tier-3
attention candidate. Default (tier-priority) arbitration picks WMMA where it
applies and falls to the generic lane for a reduction it cannot fuse; the E3
escape hatch forces either. Live-proven on gfx1151 (`test_rocm_plugin.py` §4).
**Still open:** CDNA **MFMA** `Generate*` passes as candidates (analytical-only
until CDNA silicon — gfx1151 is RDNA3.5/WMMA, no MFMA); D2 measured selection
replaces tier-priority with real on-device latency per shape-bucket.
- **C3-precursor (landed 2026-07-06): ROCm runner → F4 gate + oracle accuracy
budget** `[MAC]` author → `[AMD]` proof. Ahead of the full emit pipeline, the
*shipped* gfx1151 kernels are now wired into the universal F4 oracle:
Expand All @@ -291,10 +307,18 @@ chains, small attention). Crown-jewel GEMM stays Tier 2/3.

### Workstream D — Candidate arbitration + measured autotune

- **D1 · Candidate registry** `[MAC]` — per `(op, shape-bucket, dtype, target)`
enumerate `{synthesized, tier2_emitted, hand_tuned_1..n}`; generalize Apple's
`select_variant` + `best_record`. The key is **shape-bucket, not exact shape**
(dynamic-shapes decision) so one tuned kernel serves a bucket of runtime shapes.
- **D1 · Candidate registry** `[MAC]` — **core landed 2026-07-07**
(`emit/candidate.py`). A `Candidate` ABC (`tier`/`target`/`op`/`available()`/
`applies_to()`/`run()`) + a registry keyed per `(target, op)` enumerates
`{synthesized (Tier 1), emitted (Tier 2), hand_tuned (Tier 3)}`. `arbitrate()`
filters by applicability + availability, F4-gates each candidate through the
*same* universal oracle (a `KernelRunner` adapter reuses
`verify_synthesized_*`), then selects by **tier priority** (crown-jewel first —
lead-safe, Decision #28) with a pluggable `measure` hook (the D2 seam) and a
`force` escape hatch (E3). Wired for ROCm (generic HIP / WMMA / flash) and x86
(generic C / AOCL-DLP). **Still open:** the shape-bucket key on selection (today
keyed per `(target, op)`; `bucket_key` exists and threads in when D2 lands) and
generalizing Apple's `select_variant` + `best_record` into it.
- **D2 · Measured autotune loop** — `[AMD]` on gfx1151, `[NV]` on sm_120 run
live; CDNA/sm_90/sm_100 fall back to analytical roofline + `MmaDescriptor` cost
model until silicon. Measure-at-first-miss + cache keyed by
Expand Down
249 changes: 249 additions & 0 deletions python/tessera/compiler/emit/candidate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
"""Workstream D1 (core) — the candidate registry + accuracy-budgeted arbiter.

Decision #28's three-tier / measured-arbiter model says a kernel for a given
``(op, shape-bucket, dtype, target)`` may come from three tiers:

* **Tier 1 — synthesized** (:attr:`Tier.SYNTHESIZED`): the arch-agnostic generic
synthesizer (region-IR → source → compile → cache → launch), e.g. the ROCm
one-thread-per-row HIP lane / the x86 scalar-C lane.
* **Tier 2 — emitted** (:attr:`Tier.EMITTED`): a per-arch codegen plugin's tuned
emit (PTX ``mma.sync`` / AMDGCN WMMA generated by a `Generate*` pass).
* **Tier 3 — hand-tuned** (:attr:`Tier.HAND_TUNED`): the crown-jewel shipped
kernels (ROCm WMMA GEMM / compiled FA-2 flash-attn, NVIDIA ``wgmma``, authored
MSL). **Lead-safety: these stay first-class candidates, displaced only when a
compiled kernel measures both faster and in accuracy budget.**

This module is the **candidate registry** (plan D1) + a minimal **arbiter**. It is
additive: nothing routes through it until a backend registers candidates and a
caller invokes :func:`arbitrate` / :func:`run_arbitrated`. Every registered
candidate is gated by the *same* universal F4 oracle
(`fusion_core.verify_synthesized_*`) via a :class:`KernelRunner` adapter, so a
faster-but-wrong candidate is refused before it can ever be selected — the
cross-backend differential-equivalence superpower (Theory §7.5), now per
candidate rather than per backend.

**Scope boundary (what is D1 vs later):** this is the registry + F4-gate + a
selection rule. The *default* selection is **tier priority** (crown-jewel first —
lead-safe by construction) with a pluggable ``measure`` hook and a ``force``
escape hatch (plan E3). The **measured autotune loop** that replaces tier
priority with real on-device latency per shape-bucket is **D2** — deliberately
not built here; the ``measure`` parameter is the seam it drops into with no API
change. Fallback logging is **D3**.
"""
from __future__ import annotations

from abc import ABC, abstractmethod
from enum import IntEnum
from typing import Any, Callable


class Tier(IntEnum):
"""Kernel provenance tier (Decision #28). Ordered so a larger value is a more
hand-tuned / lead candidate — the default arbiter prefers the highest tier
(lead-safety) until D2's measured loop overrides with real latency."""

SYNTHESIZED = 1
EMITTED = 2
HAND_TUNED = 3


#: Canonical op-kind tags — one per ``fusion_core`` region class. A candidate
#: declares which it serves; the arbiter enumerates candidates per ``(target, op)``.
OP_FUSED_REGION = "fused_region"
OP_ATTENTION = "attention"
OP_GATED_MATMUL = "gated_matmul"
OP_POINTWISE = "pointwise"

#: op-kind → (verify function name, KernelRunner method) — the seam that lets the
#: arbiter reuse the exact universal F4 oracle for each candidate.
_OP_VERIFY = {
OP_FUSED_REGION: ("verify_synthesized_region", "run_fused_region"),
OP_ATTENTION: ("verify_synthesized_attention", "run_fused_attention"),
OP_GATED_MATMUL: ("verify_synthesized_gated", "run_gated_matmul_region"),
OP_POINTWISE: ("verify_synthesized_pointwise", "run_pointwise_graph"),
}


class ArbiterError(RuntimeError):
"""A forced candidate does not exist / is unavailable — names the gap so the
caller can report rather than silently pick something else (Decision #21)."""


class Candidate(ABC):
"""One kernel candidate for an ``(op, target)`` — a single tier's way to run a
region. The arbiter enumerates candidates, F4-gates each, and selects one.

A candidate is narrower than a :class:`KernelRunner` (which bundles every
op-kind for a backend): it is bound to one ``op`` and one ``tier``, so the
same backend can register a Tier-1 synthesized lane and a Tier-3 hand-tuned
lane for the *same* op and let the arbiter choose. :meth:`available` probes
the device/library at call time (a hand-tuned lane may be present only on real
silicon); :meth:`applies_to` narrows by region shape/features (the WMMA fused
GEMM serves only bias/relu/gelu/silu epilogues, not a softmax reduction)."""

#: Human-readable identity, unique within an ``(op, target)`` bucket — the key
#: the ``force`` escape hatch (E3) selects by.
name: str = ""
#: Provenance tier — drives the default (tier-priority) selection.
tier: Tier = Tier.SYNTHESIZED
#: Backend id, e.g. ``"rocm"`` / ``"x86"`` / ``"nvidia"``.
target: str = ""
#: Which op-kind this candidate serves (one of the ``OP_*`` tags).
op: str = OP_FUSED_REGION
#: Precision budget vs the f32 reference (see ``KernelRunner.accuracy_atol``):
#: a half-precision lead candidate (f16 WMMA) sets a looser value so its
#: rounding is not misread as a miscompile. ``None`` = the oracle default.
accuracy_atol: float | None = None

def available(self) -> bool:
"""Whether this candidate can execute here *right now* (device/toolchain/
library probe). Default ``True``; hand-tuned lanes override with a probe so
they simply drop out of the enumeration off their silicon."""
return True

def applies_to(self, region: Any) -> bool:
"""Whether this candidate can serve ``region`` (by region type / features).
Default ``True``; narrow in subclasses (e.g. a GEMM candidate declines a
region with a reduction epilogue it cannot fuse)."""
return True

@abstractmethod
def run(self, region: Any, *inputs: Any, **kwargs: Any) -> tuple[Any, str]:
"""Execute ``region`` on ``inputs`` → ``(output, execution_tag)``. The tag
follows the runner contract: a real-execution tag (``"rocm_wmma"``, …) when
a device kernel ran, or a :data:`REFERENCE_EXECUTIONS` tag when it declined
to the numpy reference (then the F4 oracle trusts it by construction)."""


# --- registry ----------------------------------------------------------------
_CANDIDATES: dict[tuple[str, str], list[Candidate]] = {}


def register_candidate(candidate: Candidate) -> None:
"""Register ``candidate`` under ``(target, op)``. Re-registering the same
``name`` in a bucket replaces it (idempotent under module re-import — the hook
each backend uses to plug its lanes in alongside the others)."""
if not candidate.target or not candidate.name:
raise ValueError("Candidate.target and Candidate.name must be non-empty")
if candidate.op not in _OP_VERIFY:
raise ValueError(f"unknown Candidate.op {candidate.op!r}")
bucket = _CANDIDATES.setdefault((candidate.target, candidate.op), [])
for i, existing in enumerate(bucket):
if existing.name == candidate.name:
bucket[i] = candidate
return
bucket.append(candidate)


def candidates_for(target: str, op: str) -> list[Candidate]:
"""All registered candidates for ``(target, op)`` (a copy; registration order)."""
return list(_CANDIDATES.get((target, op), ()))


# --- F4-gate adapter: reuse the universal oracle per candidate ----------------
def _as_runner(candidate: Candidate) -> Any:
"""Wrap a :class:`Candidate` as a :class:`KernelRunner` so the existing
``fusion_core.verify_synthesized_*`` oracle gates it unchanged — the whole
point of D1's F4 reuse. Only the candidate's own op method is wired; the other
three raise (the oracle never calls them for this op)."""
from tessera.compiler.emit.kernel_emitter import KernelRunner

_, method = _OP_VERIFY[candidate.op]

class _CandidateRunner(KernelRunner):
target = candidate.target
Comment thread
gstoner marked this conversation as resolved.
Resolved
accuracy_atol = candidate.accuracy_atol

def run_fused_region(self, region, *a, **k):
return self._route("run_fused_region", region, a, k)

def run_fused_attention(self, region, *a, **k):
return self._route("run_fused_attention", region, a, k)

def run_gated_matmul_region(self, region, *a, **k):
return self._route("run_gated_matmul_region", region, a, k)

def run_pointwise_graph(self, region, *a, **k):
return self._route("run_pointwise_graph", region, a, k)

def _route(self, called, region, a, k):
if called != method:
raise NotImplementedError(
f"candidate {candidate.name!r} serves {method}, not {called}")
return candidate.run(region, *a)

return _CandidateRunner()


def verify_candidate(candidate: Candidate, region: Any, *, atol: float = 1e-3,
seed: int = 0) -> bool:
"""F4-gate ``candidate`` on ``region``: run the universal numpy-reference oracle
for the candidate's op-kind, honoring its ``accuracy_atol`` budget. ``True`` iff
a real kernel ran and matched (or it declined to the trusted reference)."""
from tessera.compiler import fusion_core

verify_name, _ = _OP_VERIFY[candidate.op]
verify = getattr(fusion_core, verify_name)
return bool(verify(region, runner=_as_runner(candidate), force=True,
atol=atol, seed=seed))


# --- the arbiter -------------------------------------------------------------
MeasureFn = Callable[[Candidate], float]


def arbitrate(region: Any, op: str, target: str, *, verify: bool = True,
force: str | None = None,
measure: MeasureFn | None = None) -> Candidate | None:
"""Pick the winning candidate for ``region`` among those registered for
``(target, op)``, or ``None`` if none apply/verify (caller uses the reference).

Selection pipeline: keep candidates that **apply** to the region and are
**available** here; if ``force`` is given, restrict to that name (E3 escape
hatch — raises :class:`ArbiterError` if it is not present/available); if
``verify`` (default), drop any that fail the **F4 oracle**; then choose —
by ``measure`` (a latency callback, plan D2's seam: lowest wins) if given,
else by **tier priority** (highest tier — crown-jewel first, lead-safe)."""
cands = [c for c in candidates_for(target, op)
if c.applies_to(region) and c.available()]
if force is not None:
forced = [c for c in cands if c.name == force]
if not forced:
all_names = [c.name for c in candidates_for(target, op)]
raise ArbiterError(
f"forced candidate {force!r} not available for ({target}, {op}); "
f"registered: {all_names or '<none>'}")
cands = forced
if verify:
cands = [c for c in cands if verify_candidate(c, region)]
if not cands:
return None
if measure is not None:
return min(cands, key=measure)
# Default: highest tier wins (Decision #28 lead-safety) — a hand-tuned lane is
# only displaced once D2's measured loop proves a lower tier faster + in budget.
return max(cands, key=lambda c: (int(c.tier), -_reg_index(c)))


def _reg_index(candidate: Candidate) -> int:
"""Registration order within the bucket — a stable tie-break so equal-tier
candidates resolve deterministically (first-registered wins)."""
bucket = _CANDIDATES.get((candidate.target, candidate.op), [])
for i, c in enumerate(bucket):
if c is candidate:
return i
return len(bucket)


def run_arbitrated(region: Any, op: str, target: str, *inputs: Any,
verify: bool = True, force: str | None = None,
measure: MeasureFn | None = None) -> tuple[Any, str]:
"""Arbitrate then execute: pick the winning candidate and run it on
``inputs`` → ``(output, tag)``. When no candidate applies/verifies, fall back
to ``region.reference(*inputs)`` tagged ``"reference"`` (Decision #21: honest —
never a mislabeled kernel)."""
winner = arbitrate(region, op, target, verify=verify, force=force,
measure=measure)
if winner is None:
return region.reference(*inputs), "reference"
return winner.run(region, *inputs)
Loading
Loading