Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions .github/workflows/mlx.yml
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ jobs:
backends/mlx/test/test_slot_recycling.py \
backends/mlx/test/test_sample.py \
backends/mlx/test/test_run_all_tests.py \
backends/mlx/helion/test \
examples/models/gemma4_31b/tests/test_mlx_pipeline.py \
examples/models/muse-glimmer/tests/test_mlx_pipeline.py \
examples/models/muse-glimmer/tests/test_mlx_offgraph.py \
Expand Down
16 changes: 16 additions & 0 deletions backends/mlx/helion/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Helion kernels in the MLX backend

[Helion](https://github.com/pytorch/helion) compiles kernels written in a
PyTorch-like DSL to Metal. This directory holds the Helion kernels the MLX
backend can run in place of its own ops, picked per call from a **target**
pinned offline for one chip.

## Pieces

| File | What it holds |
|---|---|
| `registry.py` | The target model: `HelionTarget(name, chip, ops)`, each `HelionOp(op, variants)`; a `Variant` pins the call it serves (`call`: exact tensor shapes, an int argument possibly an `IntRange`), its `PinnedLaunch`es (kernel, config, exact arguments, and input wiring: `Arg`, `View`, `Positions`, `Output`), and its `results`. Registration checks every variant's wiring, that its tensor sizes are exact, and that no two variants of an op can serve the same call. |

## Tests

`test/test_helion.py` covers the registry with stub kernels.
47 changes: 47 additions & 0 deletions backends/mlx/helion/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

"""Helion-generated Metal kernels in the MLX backend.

A ``HelionTarget`` (``registry.py``) pins, for one chip, the Helion variants
chosen offline: for each op Helion can serve, the calls where Helion beat the
MLX ops, and the exact launches, with their wiring, that compute them. A target
is registered under its name, usually by importing its module::

register_helion_target(MY_TARGET)
"""

from executorch.backends.mlx.helion.registry import (
Arg,
helion_target,
HelionOp,
HelionTarget,
IntRange,
KernelRef,
Output,
PinnedLaunch,
Positions,
register_helion_target,
TensorSpec,
Variant,
View,
)

__all__ = [
"Arg",
"Output",
"Positions",
"IntRange",
"View",
"HelionOp",
"HelionTarget",
"KernelRef",
"PinnedLaunch",
"TensorSpec",
"Variant",
"helion_target",
"register_helion_target",
]
295 changes: 295 additions & 0 deletions backends/mlx/helion/registry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

"""Pinned Helion selections for the MLX backend, per chip.

A ``HelionTarget`` lists, for one chip, the Helion variants chosen offline
(by the pin tool) for the backend's interface ops. A variant states the
op's call it serves (``Variant.call``: each tensor's exact shape and dtype,
each scalar's value, an int's possibly as an ``IntRange``) and the launches,
in order, that compute it: each a Helion kernel at a config on exact
arguments, and where each of its tensor arguments comes from (``Arg``,
``View``, ``Positions``, ``Output``). A call takes the variant whose call it
matches; every other call runs the backend's own ops. Nothing here tunes or
times anything.
"""

from __future__ import annotations

import struct
from collections.abc import Mapping
from dataclasses import dataclass, replace
from types import MappingProxyType
from typing import Union

import torch


def dtype_name(d: torch.dtype) -> str:
"""``torch.float16`` -> ``"float16"``, as a ``TensorSpec`` names it."""
return str(d).removeprefix("torch.")


DTYPES = {
dtype_name(d): d
for d in (
torch.float16,
torch.bfloat16,
torch.float32,
torch.int64,
torch.int32,
torch.int16,
torch.int8,
torch.uint8,
torch.bool,
)
}
_TARGETS: dict[str, "HelionTarget"] = {}


@dataclass(frozen=True)
class KernelRef:
"""A Helion kernel: ``function`` of ``module``, imported only to capture it."""

module: str
function: str


@dataclass(frozen=True)
class IntRange:
"""Every value from ``lo`` to ``hi``, inclusive: an int argument a variant
takes at any value in the range (attention's ``start``). Tensor sizes are
always exact: a launch's grid and shapes are fixed when it is captured."""

lo: int
hi: int


@dataclass(frozen=True)
class TensorSpec:
shape: tuple[int, ...]
dtype: str


@dataclass(frozen=True)
class Arg:
"""The op's argument ``name``, as the call has it."""

name: str


@dataclass(frozen=True)
class View:
"""The op's argument ``name`` read as ``shape`` and ``dtype``: the same
bytes, row-major (a reshape, or a reinterpretation of its elements)."""

name: str
shape: tuple[int, ...]
dtype: str


@dataclass(frozen=True)
class Positions:
"""int64 positions ``start .. start + length - 1`` of the op's int
argument ``start``."""

start: str
length: int


@dataclass(frozen=True)
class Output:
"""Output ``name`` of the variant's launch ``launch``."""

launch: int
name: str


Wire = Union[Arg, View, Positions, Output]
CallArg = Union[TensorSpec, IntRange, int, float, bool]


@dataclass(frozen=True)
class PinnedLaunch:
"""One tuned kernel launch: kernel, config and exact arguments, in the
kernel's parameter order (a ``TensorSpec`` per tensor, the value of each
scalar). ``inputs`` wires each tensor parameter the launch reads, by
name."""

kernel: KernelRef
config: Mapping[str, object]
args: tuple[Union[TensorSpec, int, float, bool], ...]
inputs: tuple[tuple[str, Wire], ...]


@dataclass(frozen=True)
class Variant:
"""The launches that compute one pinned call of an op.

``call`` holds the op's arguments by schema name; ``results`` the launch
outputs that are the op's results, in order, each the bytes of its result."""

call: tuple[tuple[str, CallArg], ...]
launches: tuple[PinnedLaunch, ...]
results: tuple[Output, ...]


@dataclass(frozen=True)
class HelionOp:
"""The pinned variants of one interface op."""

op: torch._ops.OpOverload
variants: tuple[Variant, ...]


@dataclass(frozen=True)
class HelionTarget:
"""Pinned variants for one chip: the runtime runs them only on a GPU
whose Metal device name is ``chip`` (``"Apple M5 Max"``). Metal does not
report a GPU's core count, so a part of the same name with fewer cores
runs them too, correctly but possibly slower than its own pins would."""

name: str
chip: str
ops: tuple[HelionOp, ...]

def variants_for(self, op: torch._ops.OpOverload) -> tuple[Variant, ...]:
return next((o.variants for o in self.ops if o.op == op), ())


def float32(value):
"""A float scalar at the float32 precision a Metal kernel takes it."""
if isinstance(value, float):
return struct.unpack("f", struct.pack("f", value))[0]
return value


def bounds(value) -> tuple[int, int]:
"""The values a pinned size or int takes, as an inclusive range."""
return (value.lo, value.hi) if isinstance(value, IntRange) else (value, value)


def freeze(value):
"""A deeply immutable copy: mappings become read-only views, lists tuples."""
if isinstance(value, Mapping):
return MappingProxyType({k: freeze(v) for k, v in value.items()})
if isinstance(value, (list, tuple)):
return tuple(freeze(v) for v in value)
return value


def thaw(value):
"""JSON data for a frozen value (the inverse of ``freeze``)."""
if isinstance(value, Mapping):
return {k: thaw(v) for k, v in value.items()}
if isinstance(value, tuple):
return [thaw(v) for v in value]
return value


def _overlap(a: CallArg, b: CallArg) -> bool:
if isinstance(a, TensorSpec) or isinstance(b, TensorSpec):
if not (isinstance(a, TensorSpec) and isinstance(b, TensorSpec)):
return False
return a.dtype == b.dtype and tuple(a.shape) == tuple(b.shape)
if isinstance(a, (int, IntRange)) and isinstance(b, (int, IntRange)):
if isinstance(a, bool) or isinstance(b, bool):
return a == b
(lo1, hi1), (lo2, hi2) = bounds(a), bounds(b)
return max(lo1, lo2) <= min(hi1, hi2)
return float32(a) == float32(b)


def _frozen(target: HelionTarget) -> HelionTarget:
def exact(x):
"""Shapes as tuples, which compare equal to the calls matched against."""
if isinstance(x, (TensorSpec, View)):
return replace(x, shape=tuple(x.shape))
return x

def launch(p: PinnedLaunch) -> PinnedLaunch:
return replace(
p,
config=freeze(p.config),
args=tuple(exact(a) for a in p.args),
inputs=tuple((n, exact(w)) for n, w in p.inputs),
)

def variant(v: Variant) -> Variant:
return replace(
v,
call=tuple((n, exact(a)) for n, a in v.call),
launches=tuple(launch(p) for p in v.launches),
results=tuple(v.results),
)

return replace(
target,
ops=tuple(
replace(o, variants=tuple(variant(v) for v in o.variants))
for o in target.ops
),
)


def _check(name: str, entry: HelionOp) -> None:
"""Each variant pins the op's whole call and wires every launch; no two
variants of an op match one call."""
for i, v in enumerate(entry.variants):
_check_variant(f"{name}: variant {i} of {entry.op}", entry.op, v)
for i, a in enumerate(entry.variants):
for j in range(i + 1, len(entry.variants)):
b = dict(entry.variants[j].call)
if all(_overlap(arg, b[k]) for k, arg in a.call):
raise ValueError(
f"{name}: variants {i} and {j} of {entry.op} overlap; at most "
"one may match a call"
)


def _check_variant(where: str, op: torch._ops.OpOverload, v: Variant) -> None:
schema = [a.name for a in op._schema.arguments]
results = len(op._schema.returns)
if [k for k, _ in v.call] != schema:
raise ValueError(f"{where} pins {[k for k, _ in v.call]}, not {schema}")
for k, arg in v.call:
if isinstance(arg, TensorSpec) and any(type(d) is not int for d in arg.shape):
raise ValueError(f"{where}: {k} is {arg.shape}; tensor sizes must be exact")
if not v.launches or len(v.results) != results:
raise ValueError(f"{where} has no launches or not {results} results")
for j, p in enumerate(v.launches):
for _, wire in p.inputs:
if isinstance(wire, (Arg, View)) and wire.name not in schema:
raise ValueError(f"{where}: launch {j} reads no argument {wire}")
if isinstance(wire, Output) and not 0 <= wire.launch < j:
raise ValueError(f"{where}: launch {j} reads a later launch")
for r in v.results:
if not 0 <= r.launch < len(v.launches):
raise ValueError(f"{where}: result {r} of no launch")


def register_helion_target(target: HelionTarget) -> None:
"""Register an immutable snapshot of ``target`` under its name."""
ops = [o.op for o in target.ops]
if len(set(ops)) != len(ops):
raise ValueError(f"{target.name}: two entries for one op")
for entry in target.ops:
_check(target.name, entry)
target = _frozen(target)
if _TARGETS.get(target.name, target) != target:
raise ValueError(
f"Helion target {target.name!r} already registered differently"
)
_TARGETS[target.name] = target


def helion_target(name: str) -> HelionTarget:
if name not in _TARGETS:
raise ValueError(
f"Helion target {name!r} is not registered; import the module that "
"registers it first"
)
return _TARGETS[name]
5 changes: 5 additions & 0 deletions backends/mlx/helion/test/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
Loading
Loading