Repository navigation
C3 tail + C1b + D1-core: WMMA/AOCL-DLP Tier-3 candidates + arbiter #289
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| 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) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.