|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +"""Pinned Helion selections for the MLX backend, per chip. |
| 8 | +
|
| 9 | +A ``HelionTarget`` lists, for one chip, the Helion variants chosen offline |
| 10 | +(by the pin tool) for the backend's interface ops. A variant states the |
| 11 | +op's call it serves (``Variant.call``: each tensor's exact shape and dtype, |
| 12 | +each scalar's value, an int's possibly as an ``IntRange``) and the launches, |
| 13 | +in order, that compute it: each a Helion kernel at a config on exact |
| 14 | +arguments, and where each of its tensor arguments comes from (``Arg``, |
| 15 | +``View``, ``Positions``, ``Output``). A call takes the variant whose call it |
| 16 | +matches; every other call runs the backend's own ops. Nothing here tunes or |
| 17 | +times anything. |
| 18 | +""" |
| 19 | + |
| 20 | +from __future__ import annotations |
| 21 | + |
| 22 | +import struct |
| 23 | +from collections.abc import Mapping |
| 24 | +from dataclasses import dataclass, replace |
| 25 | +from types import MappingProxyType |
| 26 | +from typing import Union |
| 27 | + |
| 28 | +import torch |
| 29 | + |
| 30 | + |
| 31 | +def dtype_name(d: torch.dtype) -> str: |
| 32 | + """``torch.float16`` -> ``"float16"``, as a ``TensorSpec`` names it.""" |
| 33 | + return str(d).removeprefix("torch.") |
| 34 | + |
| 35 | + |
| 36 | +DTYPES = { |
| 37 | + dtype_name(d): d |
| 38 | + for d in ( |
| 39 | + torch.float16, |
| 40 | + torch.bfloat16, |
| 41 | + torch.float32, |
| 42 | + torch.int64, |
| 43 | + torch.int32, |
| 44 | + torch.int16, |
| 45 | + torch.int8, |
| 46 | + torch.uint8, |
| 47 | + torch.bool, |
| 48 | + ) |
| 49 | +} |
| 50 | +_TARGETS: dict[str, "HelionTarget"] = {} |
| 51 | + |
| 52 | + |
| 53 | +@dataclass(frozen=True) |
| 54 | +class KernelRef: |
| 55 | + """A Helion kernel: ``function`` of ``module``, imported only to capture it.""" |
| 56 | + |
| 57 | + module: str |
| 58 | + function: str |
| 59 | + |
| 60 | + |
| 61 | +@dataclass(frozen=True) |
| 62 | +class IntRange: |
| 63 | + """Every value from ``lo`` to ``hi``, inclusive: an int argument a variant |
| 64 | + takes at any value in the range (attention's ``start``). Tensor sizes are |
| 65 | + always exact: a launch's grid and shapes are fixed when it is captured.""" |
| 66 | + |
| 67 | + lo: int |
| 68 | + hi: int |
| 69 | + |
| 70 | + |
| 71 | +@dataclass(frozen=True) |
| 72 | +class TensorSpec: |
| 73 | + shape: tuple[int, ...] |
| 74 | + dtype: str |
| 75 | + |
| 76 | + |
| 77 | +@dataclass(frozen=True) |
| 78 | +class Arg: |
| 79 | + """The op's argument ``name``, as the call has it.""" |
| 80 | + |
| 81 | + name: str |
| 82 | + |
| 83 | + |
| 84 | +@dataclass(frozen=True) |
| 85 | +class View: |
| 86 | + """The op's argument ``name`` read as ``shape`` and ``dtype``: the same |
| 87 | + bytes, row-major (a reshape, or a reinterpretation of its elements).""" |
| 88 | + |
| 89 | + name: str |
| 90 | + shape: tuple[int, ...] |
| 91 | + dtype: str |
| 92 | + |
| 93 | + |
| 94 | +@dataclass(frozen=True) |
| 95 | +class Positions: |
| 96 | + """int64 positions ``start .. start + length - 1`` of the op's int |
| 97 | + argument ``start``.""" |
| 98 | + |
| 99 | + start: str |
| 100 | + length: int |
| 101 | + |
| 102 | + |
| 103 | +@dataclass(frozen=True) |
| 104 | +class Output: |
| 105 | + """Output ``name`` of the variant's launch ``launch``.""" |
| 106 | + |
| 107 | + launch: int |
| 108 | + name: str |
| 109 | + |
| 110 | + |
| 111 | +Wire = Union[Arg, View, Positions, Output] |
| 112 | +CallArg = Union[TensorSpec, IntRange, int, float, bool] |
| 113 | + |
| 114 | + |
| 115 | +@dataclass(frozen=True) |
| 116 | +class PinnedLaunch: |
| 117 | + """One tuned kernel launch: kernel, config and exact arguments, in the |
| 118 | + kernel's parameter order (a ``TensorSpec`` per tensor, the value of each |
| 119 | + scalar). ``inputs`` wires each tensor parameter the launch reads, by |
| 120 | + name.""" |
| 121 | + |
| 122 | + kernel: KernelRef |
| 123 | + config: Mapping[str, object] |
| 124 | + args: tuple[Union[TensorSpec, int, float, bool], ...] |
| 125 | + inputs: tuple[tuple[str, Wire], ...] |
| 126 | + |
| 127 | + |
| 128 | +@dataclass(frozen=True) |
| 129 | +class Variant: |
| 130 | + """The launches that compute one pinned call of an op. |
| 131 | +
|
| 132 | + ``call`` holds the op's arguments by schema name; ``results`` the launch |
| 133 | + outputs that are the op's results, in order, each the bytes of its result.""" |
| 134 | + |
| 135 | + call: tuple[tuple[str, CallArg], ...] |
| 136 | + launches: tuple[PinnedLaunch, ...] |
| 137 | + results: tuple[Output, ...] |
| 138 | + |
| 139 | + |
| 140 | +@dataclass(frozen=True) |
| 141 | +class HelionOp: |
| 142 | + """The pinned variants of one interface op.""" |
| 143 | + |
| 144 | + op: torch._ops.OpOverload |
| 145 | + variants: tuple[Variant, ...] |
| 146 | + |
| 147 | + |
| 148 | +@dataclass(frozen=True) |
| 149 | +class HelionTarget: |
| 150 | + """Pinned variants for one chip: the runtime runs them only on a GPU |
| 151 | + whose Metal device name is ``chip`` (``"Apple M5 Max"``). Metal does not |
| 152 | + report a GPU's core count, so a part of the same name with fewer cores |
| 153 | + runs them too, correctly but possibly slower than its own pins would.""" |
| 154 | + |
| 155 | + name: str |
| 156 | + chip: str |
| 157 | + ops: tuple[HelionOp, ...] |
| 158 | + |
| 159 | + def variants_for(self, op: torch._ops.OpOverload) -> tuple[Variant, ...]: |
| 160 | + return next((o.variants for o in self.ops if o.op == op), ()) |
| 161 | + |
| 162 | + |
| 163 | +def float32(value): |
| 164 | + """A float scalar at the float32 precision a Metal kernel takes it.""" |
| 165 | + if isinstance(value, float): |
| 166 | + return struct.unpack("f", struct.pack("f", value))[0] |
| 167 | + return value |
| 168 | + |
| 169 | + |
| 170 | +def bounds(value) -> tuple[int, int]: |
| 171 | + """The values a pinned size or int takes, as an inclusive range.""" |
| 172 | + return (value.lo, value.hi) if isinstance(value, IntRange) else (value, value) |
| 173 | + |
| 174 | + |
| 175 | +def freeze(value): |
| 176 | + """A deeply immutable copy: mappings become read-only views, lists tuples.""" |
| 177 | + if isinstance(value, Mapping): |
| 178 | + return MappingProxyType({k: freeze(v) for k, v in value.items()}) |
| 179 | + if isinstance(value, (list, tuple)): |
| 180 | + return tuple(freeze(v) for v in value) |
| 181 | + return value |
| 182 | + |
| 183 | + |
| 184 | +def thaw(value): |
| 185 | + """JSON data for a frozen value (the inverse of ``freeze``).""" |
| 186 | + if isinstance(value, Mapping): |
| 187 | + return {k: thaw(v) for k, v in value.items()} |
| 188 | + if isinstance(value, tuple): |
| 189 | + return [thaw(v) for v in value] |
| 190 | + return value |
| 191 | + |
| 192 | + |
| 193 | +def _overlap(a: CallArg, b: CallArg) -> bool: |
| 194 | + if isinstance(a, TensorSpec) or isinstance(b, TensorSpec): |
| 195 | + if not (isinstance(a, TensorSpec) and isinstance(b, TensorSpec)): |
| 196 | + return False |
| 197 | + return a.dtype == b.dtype and tuple(a.shape) == tuple(b.shape) |
| 198 | + if isinstance(a, (int, IntRange)) and isinstance(b, (int, IntRange)): |
| 199 | + if isinstance(a, bool) or isinstance(b, bool): |
| 200 | + return a == b |
| 201 | + (lo1, hi1), (lo2, hi2) = bounds(a), bounds(b) |
| 202 | + return max(lo1, lo2) <= min(hi1, hi2) |
| 203 | + return float32(a) == float32(b) |
| 204 | + |
| 205 | + |
| 206 | +def _frozen(target: HelionTarget) -> HelionTarget: |
| 207 | + def exact(x): |
| 208 | + """Shapes as tuples, which compare equal to the calls matched against.""" |
| 209 | + if isinstance(x, (TensorSpec, View)): |
| 210 | + return replace(x, shape=tuple(x.shape)) |
| 211 | + return x |
| 212 | + |
| 213 | + def launch(p: PinnedLaunch) -> PinnedLaunch: |
| 214 | + return replace( |
| 215 | + p, |
| 216 | + config=freeze(p.config), |
| 217 | + args=tuple(exact(a) for a in p.args), |
| 218 | + inputs=tuple((n, exact(w)) for n, w in p.inputs), |
| 219 | + ) |
| 220 | + |
| 221 | + def variant(v: Variant) -> Variant: |
| 222 | + return replace( |
| 223 | + v, |
| 224 | + call=tuple((n, exact(a)) for n, a in v.call), |
| 225 | + launches=tuple(launch(p) for p in v.launches), |
| 226 | + results=tuple(v.results), |
| 227 | + ) |
| 228 | + |
| 229 | + return replace( |
| 230 | + target, |
| 231 | + ops=tuple( |
| 232 | + replace(o, variants=tuple(variant(v) for v in o.variants)) |
| 233 | + for o in target.ops |
| 234 | + ), |
| 235 | + ) |
| 236 | + |
| 237 | + |
| 238 | +def _check(name: str, entry: HelionOp) -> None: |
| 239 | + """Each variant pins the op's whole call and wires every launch; no two |
| 240 | + variants of an op match one call.""" |
| 241 | + for i, v in enumerate(entry.variants): |
| 242 | + _check_variant(f"{name}: variant {i} of {entry.op}", entry.op, v) |
| 243 | + for i, a in enumerate(entry.variants): |
| 244 | + for j in range(i + 1, len(entry.variants)): |
| 245 | + b = dict(entry.variants[j].call) |
| 246 | + if all(_overlap(arg, b[k]) for k, arg in a.call): |
| 247 | + raise ValueError( |
| 248 | + f"{name}: variants {i} and {j} of {entry.op} overlap; at most " |
| 249 | + "one may match a call" |
| 250 | + ) |
| 251 | + |
| 252 | + |
| 253 | +def _check_variant(where: str, op: torch._ops.OpOverload, v: Variant) -> None: |
| 254 | + schema = [a.name for a in op._schema.arguments] |
| 255 | + results = len(op._schema.returns) |
| 256 | + if [k for k, _ in v.call] != schema: |
| 257 | + raise ValueError(f"{where} pins {[k for k, _ in v.call]}, not {schema}") |
| 258 | + for k, arg in v.call: |
| 259 | + if isinstance(arg, TensorSpec) and any(type(d) is not int for d in arg.shape): |
| 260 | + raise ValueError(f"{where}: {k} is {arg.shape}; tensor sizes must be exact") |
| 261 | + if not v.launches or len(v.results) != results: |
| 262 | + raise ValueError(f"{where} has no launches or not {results} results") |
| 263 | + for j, p in enumerate(v.launches): |
| 264 | + for _, wire in p.inputs: |
| 265 | + if isinstance(wire, (Arg, View)) and wire.name not in schema: |
| 266 | + raise ValueError(f"{where}: launch {j} reads no argument {wire}") |
| 267 | + if isinstance(wire, Output) and not 0 <= wire.launch < j: |
| 268 | + raise ValueError(f"{where}: launch {j} reads a later launch") |
| 269 | + for r in v.results: |
| 270 | + if not 0 <= r.launch < len(v.launches): |
| 271 | + raise ValueError(f"{where}: result {r} of no launch") |
| 272 | + |
| 273 | + |
| 274 | +def register_helion_target(target: HelionTarget) -> None: |
| 275 | + """Register an immutable snapshot of ``target`` under its name.""" |
| 276 | + ops = [o.op for o in target.ops] |
| 277 | + if len(set(ops)) != len(ops): |
| 278 | + raise ValueError(f"{target.name}: two entries for one op") |
| 279 | + for entry in target.ops: |
| 280 | + _check(target.name, entry) |
| 281 | + target = _frozen(target) |
| 282 | + if _TARGETS.get(target.name, target) != target: |
| 283 | + raise ValueError( |
| 284 | + f"Helion target {target.name!r} already registered differently" |
| 285 | + ) |
| 286 | + _TARGETS[target.name] = target |
| 287 | + |
| 288 | + |
| 289 | +def helion_target(name: str) -> HelionTarget: |
| 290 | + if name not in _TARGETS: |
| 291 | + raise ValueError( |
| 292 | + f"Helion target {name!r} is not registered; import the module that " |
| 293 | + "registers it first" |
| 294 | + ) |
| 295 | + return _TARGETS[name] |
0 commit comments