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
7 changes: 6 additions & 1 deletion python/tessera/compiler/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@ def _is_apple_cpu_accelerate_executable(cpu_plan: CPUPlan | None) -> bool:

_APPLE_GPU_MSL_OPS: frozenset[str] = frozenset({
"tessera.rope",
"tessera.flash_attn",
})

_APPLE_GPU_RUNTIME_OPS: frozenset[str] = _APPLE_GPU_MPS_OPS | _APPLE_GPU_MSL_OPS
Expand Down Expand Up @@ -397,10 +398,14 @@ def _backend_artifact_for(target_kind: str, cpu_plan: CPUPlan | None) -> Lowerin
symbol = "tessera_apple_gpu_mps_matmul_f32"
framework = "MetalPerformanceShaders"
abi = "MPSMatrixMultiplication"
elif only_op in _APPLE_GPU_MSL_OPS:
elif only_op == "tessera.rope":
symbol = "tessera_apple_gpu_rope_f32"
framework = "Metal"
abi = "MSLComputePipelineState"
elif only_op == "tessera.flash_attn":
symbol = "tessera_apple_gpu_flash_attn_f32"
framework = "Metal"
abi = "MSLComputePipelineState"
else:
symbol = "tessera_apple_gpu_unknown"
framework = "Metal"
Expand Down
106 changes: 100 additions & 6 deletions python/tessera/compiler/target_ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,63 @@ def _sha256_short(text: str) -> str:
_APPLE_GPU_ROPE_MSL_CACHE_KEY = _sha256_short(_APPLE_GPU_ROPE_MSL_SOURCE)


# Phase 8.4.1 — embedded MSL source for the flash-attention forward kernel.
# Same online-softmax algorithm as the runtime's apple_gpu_runtime.mm shim;
# carrying it inline here keeps the Target IR module a self-contained,
# replayable record of what the runtime will actually compile and execute.
_APPLE_GPU_FLASH_ATTN_MSL_SOURCE = (
"#include <metal_stdlib>\n"
"using namespace metal;\n"
"kernel void flash_attn_f32(\n"
" device const float* Q [[buffer(0)]],\n"
" device const float* K [[buffer(1)]],\n"
" device const float* V [[buffer(2)]],\n"
" device float* O [[buffer(3)]],\n"
" constant int& B [[buffer(4)]],\n"
" constant int& Sq [[buffer(5)]],\n"
" constant int& Sk [[buffer(6)]],\n"
" constant int& D [[buffer(7)]],\n"
" constant float& scale [[buffer(8)]],\n"
" constant int& causal [[buffer(9)]],\n"
" uint2 gid [[thread_position_in_grid]])\n"
"{\n"
" if (gid.y >= (uint)B || gid.x >= (uint)Sq) return;\n"
" int batch = (int)gid.y;\n"
" int q_row = (int)gid.x;\n"
" if (D > 256) return;\n"
" int q_off = batch * Sq * D + q_row * D;\n"
" int kv_base = batch * Sk * D;\n"
" float m = -INFINITY;\n"
" float l = 0.0f;\n"
" float o[256];\n"
" for (int d = 0; d < D; ++d) o[d] = 0.0f;\n"
" for (int k_row = 0; k_row < Sk; ++k_row) {\n"
" if (causal != 0 && k_row > q_row) break;\n"
" int k_off = kv_base + k_row * D;\n"
" float score = 0.0f;\n"
" for (int d = 0; d < D; ++d) score += Q[q_off + d] * K[k_off + d];\n"
" score *= scale;\n"
" float new_m = max(m, score);\n"
" float exp_old = exp(m - new_m);\n"
" float exp_score = exp(score - new_m);\n"
" float new_l = l * exp_old + exp_score;\n"
" for (int d = 0; d < D; ++d) o[d] = o[d] * exp_old + V[k_off + d] * exp_score;\n"
" m = new_m;\n"
" l = new_l;\n"
" }\n"
" if (l == 0.0f) {\n"
" for (int d = 0; d < D; ++d) O[q_off + d] = 0.0f;\n"
" } else {\n"
" float inv_l = 1.0f / l;\n"
" for (int d = 0; d < D; ++d) O[q_off + d] = o[d] * inv_l;\n"
" }\n"
"}\n"
)


_APPLE_GPU_FLASH_ATTN_MSL_CACHE_KEY = _sha256_short(_APPLE_GPU_FLASH_ATTN_MSL_SOURCE)


def _diagnostic_level(severity: str) -> DiagnosticLevel:
return {
"fatal": DiagnosticLevel.FATAL,
Expand Down Expand Up @@ -335,7 +392,12 @@ def _apple_gpu_module_is_mps_runtime(tile_module: TileIRModule) -> bool:
if len(sources) != 1:
return False
(source,) = sources
return source in {"tessera.matmul", "tessera.gemm", "tessera.rope"}
return source in {
"tessera.matmul",
"tessera.gemm",
"tessera.rope",
"tessera.flash_attn",
}


def _lower_tile_ops(
Expand All @@ -345,10 +407,15 @@ def _lower_tile_ops(
apple_gpu_mps_runtime: bool = False,
) -> list[TargetOp]:
lowered: list[TargetOp] = []
# Phase 8.4 — when in runtime mode some Graph IR ops (e.g. rope) decompose
# into multiple Tile IR ops sharing the same (source, ordinal). The
# artifact-only path emits both for inspection/diagnostics; the runtime
# Phase 8.4 — when in runtime mode some Graph IR ops (e.g. rope, flash_attn)
# decompose into multiple Tile IR ops sharing the same (source, ordinal).
# The artifact-only path emits both for inspection/diagnostics; the runtime
# path must emit exactly one func.call site, so we suppress duplicates.
#
# The dedup key is only consumed when the op actually produces a runtime
# emission. Filter ops (tile.async_copy, tessera.queue.*, tile.wait_async,
# debug_barriers) carry the same source/ordinal but emit nothing — if we
# consumed the key for them, the real compute op would be skipped.
seen_runtime_keys: set[tuple[str, object]] = set()
for tile_op in _flatten_tile_ops(ops):
if target_kind == ROCM_TARGET:
Expand All @@ -363,8 +430,12 @@ def _lower_tile_ops(
)
if key in seen_runtime_keys:
continue
seen_runtime_keys.add(key)
lowered.extend(_lower_apple_gpu_op(tile_op, mps_runtime=apple_gpu_mps_runtime))
emitted = _lower_apple_gpu_op(tile_op, mps_runtime=apple_gpu_mps_runtime)
if emitted:
seen_runtime_keys.add(key)
lowered.extend(emitted)
else:
lowered.extend(_lower_apple_gpu_op(tile_op, mps_runtime=apple_gpu_mps_runtime))
elif target_kind == CPU_TARGET:
lowered.extend(_lower_cpu_op(tile_op))
elif target_kind in NVIDIA_TARGETS:
Expand Down Expand Up @@ -559,6 +630,29 @@ def _lower_apple_gpu_op(op: TileOp, *, mps_runtime: bool = False) -> list[Target
"execution_mode": "metal_runtime",
}),
]
# Phase 8.4.1 custom MSL path: a single-flash_attn module is lowered to
# msl_kernel + mps_dispatch carrying the flash-attention MSL source as a
# StringAttr. The FlashAttnToAppleGPU pass and the apple_gpu_runtime.mm
# shim consume this op.
if mps_runtime and source == "tessera.flash_attn":
return [
TargetOp("tessera_apple.gpu.msl_kernel", {
**base,
"framework": "Metal",
"dtype": "f32",
"entry_point": "flash_attn_f32",
"msl_source": _APPLE_GPU_FLASH_ATTN_MSL_SOURCE,
"cache_key": _APPLE_GPU_FLASH_ATTN_MSL_CACHE_KEY,
"grid": "batch_query_rows",
"threadgroup": "32x?",
}),
TargetOp("tessera_apple.gpu.mps_dispatch", {
"ordinal": base["ordinal"],
"queue": "MTLCommandQueue",
"framework": "Metal",
"execution_mode": "metal_runtime",
}),
]
kernel, framework, extra = _apple_gpu_kernel_contract(source)
return [
TargetOp("tessera_apple.gpu.metal_kernel", {**base, "kernel": kernel, "framework": framework, "dtype": "f32", **extra}),
Expand Down
90 changes: 86 additions & 4 deletions python/tessera/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1644,7 +1644,7 @@ def _load_apple_cpu_runtime() -> ctypes.CDLL:


_APPLE_GPU_MPS_OPS = frozenset({"tessera.matmul", "tessera.gemm"})
_APPLE_GPU_MSL_OPS = frozenset({"tessera.rope"})
_APPLE_GPU_MSL_OPS = frozenset({"tessera.rope", "tessera.flash_attn"})
_APPLE_GPU_RUNTIME_OPS = _APPLE_GPU_MPS_OPS | _APPLE_GPU_MSL_OPS


Expand Down Expand Up @@ -1689,10 +1689,17 @@ def _execute_apple_gpu_mps_metadata(metadata: Mapping[str, Any], args: Any) -> A
values[str(result)] = _apple_gpu_dispatch_matmul(
op_name, [_as_numpy(values[name]) for name in operand_names], np
)
elif op_name in _APPLE_GPU_MSL_OPS:
elif op_name == "tessera.rope":
values[str(result)] = _apple_gpu_dispatch_rope(
op_name, [_as_numpy(values[name]) for name in operand_names], np
)
elif op_name == "tessera.flash_attn":
values[str(result)] = _apple_gpu_dispatch_flash_attn(
op_name,
[_as_numpy(values[name]) for name in operand_names],
kwargs,
np,
)
else:
# Phase 8.4.x will broaden further; today single-op gating in
# driver.py is the authoritative envelope. A non-MPS, non-MSL op
Expand Down Expand Up @@ -1814,6 +1821,80 @@ def _apple_gpu_rope_f32() -> Any:
return sym


def _apple_gpu_dispatch_flash_attn(op_name: str, operands: list[Any],
kwargs: Mapping[str, Any], np: Any) -> Any:
"""Phase 8.4.1: dispatch a single rank-3 f32 flash-attention forward
through the apple_gpu runtime shim's custom MSL kernel. Inputs outside
the supported envelope (rank, dtype, head_dim > 256) fall back to the
numpy reference path used by the default `cpu` target.
"""

if len(operands) < 3:
raise ValueError(f"{op_name!r} requires Q, K, V operands")
q = np.asarray(operands[0])
k = np.asarray(operands[1])
v = np.asarray(operands[2])

rank3_fast_path = (
q.dtype == np.float32 and k.dtype == np.float32 and v.dtype == np.float32
and q.ndim == 3 and k.ndim == 3 and v.ndim == 3
and q.shape[0] == k.shape[0] == v.shape[0] # B
and k.shape[1] == v.shape[1] # Sk
and q.shape[2] == k.shape[2] == v.shape[2] # D
and q.shape[2] <= 256
)
if not rank3_fast_path:
return _runtime_flash_attn(np, q, k, v, kwargs)

if not q.flags.c_contiguous:
q = np.ascontiguousarray(q, dtype=np.float32)
if not k.flags.c_contiguous:
k = np.ascontiguousarray(k, dtype=np.float32)
if not v.flags.c_contiguous:
v = np.ascontiguousarray(v, dtype=np.float32)

B, Sq, D = q.shape
Sk = k.shape[1]
scale = kwargs.get("scale", None)
scale = (1.0 / float(np.sqrt(D))) if scale is None else float(scale)
causal = 1 if bool(kwargs.get("causal", False)) else 0

out = np.zeros((B, Sq, D), dtype=np.float32)
flash_attn = _apple_gpu_flash_attn_f32()
flash_attn(
q.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
k.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
v.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
out.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
ctypes.c_int32(B),
ctypes.c_int32(Sq),
ctypes.c_int32(Sk),
ctypes.c_int32(D),
ctypes.c_float(scale),
ctypes.c_int32(causal),
)
return out


def _apple_gpu_flash_attn_f32() -> Any:
runtime = _load_apple_gpu_runtime()
sym = runtime.tessera_apple_gpu_flash_attn_f32
sym.argtypes = [
ctypes.POINTER(ctypes.c_float), # Q
ctypes.POINTER(ctypes.c_float), # K
ctypes.POINTER(ctypes.c_float), # V
ctypes.POINTER(ctypes.c_float), # O
ctypes.c_int32, # B
ctypes.c_int32, # Sq
ctypes.c_int32, # Sk
ctypes.c_int32, # D
ctypes.c_float, # scale
ctypes.c_int32, # causal
]
sym.restype = None
return sym


def _load_apple_gpu_runtime() -> ctypes.CDLL:
"""Phase 8.3: locate or compile the apple_gpu runtime shared library.

Expand All @@ -1840,10 +1921,11 @@ def _load_apple_gpu_runtime() -> ctypes.CDLL:
try:
lib = ctypes.CDLL(str(candidate))
# Only accept the prebuilt library when it exports the full
# Phase 8.4 envelope. Older builds (Phase 8.3) lack the rope
# symbol; falling through forces a rebuild.
# Phase 8.4.1 envelope. Older builds lack the flash_attn
# (or rope) symbol; falling through forces a rebuild.
getattr(lib, "tessera_apple_gpu_mps_matmul_f32")
getattr(lib, "tessera_apple_gpu_rope_f32")
getattr(lib, "tessera_apple_gpu_flash_attn_f32")
_apple_gpu_runtime = lib
return _apple_gpu_runtime
except (OSError, AttributeError):
Expand Down
5 changes: 4 additions & 1 deletion python/tessera/testing/compiler_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,10 @@ def _common_artifact_stages(*, runtime: bool = False) -> tuple[str, ...]:
CompilerExample(
"flash_attn_contract",
flash_attn_path,
{target: _common_artifact_stages(runtime=target == "x86") for target in FOUNDATION_TARGETS},
# Phase 8.4.1: apple_gpu single-flash_attn programs are now executable
# via the custom MSL kernel. x86 has the AMX runtime path; the
# remaining targets stay artifact-only.
{target: _common_artifact_stages(runtime=target in {"x86", "apple_gpu"}) for target in FOUNDATION_TARGETS},
runtime_args=(
np.ones((1, 2, 4), dtype=np.float32),
np.ones((1, 2, 4), dtype=np.float32),
Expand Down
1 change: 1 addition & 0 deletions src/compiler/codegen/Tessera_Apple_Backend/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ add_library(TesseraApple STATIC
lib/Target/Apple/Lowering/MatmulToAppleCPU.cpp
lib/Target/Apple/Lowering/MatmulToAppleGPU.cpp
lib/Target/Apple/Lowering/RopeToAppleGPU.cpp
lib/Target/Apple/Lowering/FlashAttnToAppleGPU.cpp
)

# mlir_tablegen emits .h.inc / .cpp.inc into CMAKE_CURRENT_BINARY_DIR/Tessera/Target/Apple/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ std::unique_ptr<::mlir::Pass> createLowerMatmulToAppleGPUPass();
/// concrete custom kernel emitted via the gpu.msl_kernel op contract.
std::unique_ptr<::mlir::Pass> createLowerRopeToAppleGPUPass();

/// tessera.flash_attn (rank-3, f32, head_dim <= 256) → func.call into the
/// Apple GPU runtime shim's custom-MSL flash-attention kernel. Phase 8.4.1.
std::unique_ptr<::mlir::Pass> createLowerFlashAttnToAppleGPUPass();

/// Register the Apple Silicon dialect into a DialectRegistry. Convenience
/// wrapper that forwards to registerAppleDialect from TesseraAppleDialect.h.
void registerTesseraAppleBackendDialects(::mlir::DialectRegistry &registry);
Expand Down
Loading
Loading