When you need this. A model profile contains many small normalization operations. Combining work may reduce intermediate tensors and dispatch overhead, but a shorter expression is not necessarily a faster kernel. Compare the numerical output and the synchronized timings on the backend you have.
What you run. Fresh Metal eager-versus-compiled tensor experiment. CUDA/Triton execution, kernel traffic, and whole-model acceleration are unmeasured.
This lesson builds on investigate host overhead before changing gpu settings.
Run the same normalization two ways
RMS normalization scales each row using the reciprocal root of its mean squared values, then applies learned weights. In a fused implementation, the residual addition can feed that calculation directly, so the sum does not have to be kept as a separate intermediate tensor.
The live program compares eager and compiled MLX expressions on Metal. Compilation may fuse operations, but only a device trace shows which kernels ran and how much memory they moved. The offline analyzer reads the saved run and checks numerical parity and the timing samples; it does not test any Triton kernel.
fusion_live.py creates random tensors for several shapes, including an irregular row width. For each shape, it first records the maximum absolute difference between the two outputs. Then it warms up each path and records repeated synchronized timings.
Start with the saved 1-row, 896-column tensor case. Both paths add the residual, compute the same RMS normalization and apply the same weights. Compare their output difference first, then their repeated synchronized timings; a faster expression with a different result would fail the comparison.
Compare the tensor execution paths
Download the lab from this page, extract it, and run these commands from its directory. lab.py reads the saved run in fusion-run.json. Neither command needs an MLX install, a model download or an API key.
python3 lab.py
python3 -m unittest -v test_lab.pyRead lab.py
"""Validate recorded numerical parity and summarize actual Metal expression timings."""
import json, math, statistics
from pathlib import Path
def compare_case(case, tolerance=1e-5):
if (
tolerance < 0
or not math.isfinite(case["max_abs_error"])
or case["max_abs_error"] > tolerance
):
raise ValueError("Numerical parity exceeds tolerance")
result = {
"rows": case["rows"],
"width": case["width"],
"max_abs_error": case["max_abs_error"],
}
for name in ["eager", "compiled"]:
samples = case["timings"][name]["samples_ms"]
if not samples or any(not math.isfinite(v) or v <= 0 for v in samples):
raise ValueError("Invalid timing samples")
result[name + "_median_ms"] = round(statistics.median(samples), 6)
return result
def main():
record = json.loads(Path("fusion-run.json").read_text())
print(
json.dumps(
{
"execution_mode": "offline analysis of fresh Metal eager and compiled expression runs",
"cases": [compare_case(c) for c in record["cases"]],
"limits": "Shape-specific tensor timings; no Triton/CUDA run, device-memory counter or whole-model speedup.",
},
indent=2,
)
)
if __name__ == "__main__":
main()Read fusion_live.py
"""Compare eager and compiled RMS normalization on Metal; no CUDA/Triton execution claimed."""
import argparse
import hashlib
import importlib.metadata
import json
import platform
import statistics
import time
from pathlib import Path
def main():
import mlx.core as mx
p = argparse.ArgumentParser()
p.add_argument("--output", required=True)
a = p.parse_args()
mx.random.seed(0)
def norm(x, r, w):
z = x + r
return z * mx.rsqrt(mx.mean(z * z, axis=-1, keepdims=True) + 1e-6) * w
compiled = mx.compile(norm)
cases = []
for rows, width in [(1, 896), (32, 896), (32, 1003)]:
x = mx.random.normal((rows, width))
r = mx.random.normal((rows, width))
w = mx.ones((width,))
mx.eval(x, r, w)
reference = norm(x, r, w)
candidate = compiled(x, r, w)
mx.eval(reference, candidate)
error = float(mx.max(mx.abs(reference - candidate)).item())
timings = {}
for name, fn in [("eager", norm), ("compiled", compiled)]:
for _ in range(3):
mx.eval(fn(x, r, w))
samples = []
for _ in range(20):
mx.synchronize()
start = time.perf_counter()
out = fn(x, r, w)
mx.eval(out)
mx.synchronize()
samples.append((time.perf_counter() - start) * 1000)
timings[name] = {
"median_ms": round(statistics.median(samples), 6),
"samples_ms": [round(s, 6) for s in samples],
}
cases.append(
{
"rows": rows,
"width": width,
"dtype": "float32",
"max_abs_error": error,
"timings": timings,
}
)
result = {
"execution_mode": "fresh Metal tensor execution; eager versus MLX compiled expression",
"environment": {
"python": platform.python_version(),
"platform": platform.platform(),
"mlx": importlib.metadata.version("mlx"),
},
"source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
"cases": cases,
"limits": "Expression compilation may fuse operations. No kernel trace or measured HBM byte count; no whole-model, CUDA or Triton speedup claim.",
}
Path(a.output).write_text(json.dumps(result, indent=2) + "\n")
if __name__ == "__main__":
main()The compiled expression and eager reference agree for these recorded shapes. Their timings include repeated synchronization and evaluation. Inspect the timing distributions, not a single speedup ratio. Read the raw samples before you trust a median gap: in the 1-row case, each path has a group of fast runs and a group of slow runs, so its median depends on how many of the 20 samples were slow.
Inspect the complete local result
{
"execution_mode": "offline analysis of fresh Metal eager and compiled expression runs",
"cases": [
{
"rows": 1,
"width": 896,
"max_abs_error": 0.0,
"eager_median_ms": 0.45025,
"compiled_median_ms": 0.290083
},
{
"rows": 32,
"width": 896,
"max_abs_error": 0.0,
"eager_median_ms": 0.222666,
"compiled_median_ms": 0.192312
},
{
"rows": 32,
"width": 1003,
"max_abs_error": 0.0,
"eager_median_ms": 0.228792,
"compiled_median_ms": 0.196583
}
],
"limits": "Shape-specific tensor timings; no Triton/CUDA run, device-memory counter or whole-model speedup."
}Inspect the actual execution record
{
"execution_mode": "fresh Metal tensor execution; eager versus MLX compiled expression",
"environment": {
"python": "3.12.8",
"platform": "macOS-27.0.1-arm64-arm-64bit",
"mlx": "0.32.4"
},
"source_sha256": "62653ea247e893a6c1b2a70709fa0e9a363e1b2ce25e6b522c0c8308fd230a05",
"cases": [
{
"rows": 1,
"width": 896,
"dtype": "float32",
"max_abs_error": 0.0,
"timings": {
"eager": {
"median_ms": 0.45025,
"samples_ms": [
0.507958,
0.464666,
0.450875,
0.45325,
0.449625,
0.503083,
0.501917,
0.456292,
0.472334,
0.473333,
0.516667,
0.401541,
0.393125,
0.401959,
0.222625,
0.180541,
0.174334,
0.180542,
0.175917,
0.1745
]
},
"compiled": {
"median_ms": 0.290083,
"samples_ms": [
0.174417,
0.1545,
0.160917,
0.161667,
0.161125,
0.412792,
0.464209,
0.464167,
0.509875,
0.450125,
0.459958,
0.473375,
0.533375,
0.470042,
0.38675,
0.187459,
0.175958,
0.176375,
0.183375,
0.193416
]
}
}
},
{
"rows": 32,
"width": 896,
"dtype": "float32",
"max_abs_error": 0.0,
"timings": {
"eager": {
"median_ms": 0.222667,
"samples_ms": [
0.254083,
0.229667,
0.22275,
0.194417,
0.196792,
0.204542,
0.21225,
0.204917,
0.198125,
0.216666,
0.216125,
0.470042,
0.483125,
0.5025,
0.475292,
0.515,
0.21125,
0.225208,
0.222583,
0.223292
]
},
"compiled": {
"median_ms": 0.192312,
"samples_ms": [
0.194792,
0.200791,
0.196542,
0.181,
0.189917,
0.192041,
0.200792,
0.20125,
0.195417,
0.192083,
0.187625,
0.178333,
0.178083,
0.179417,
0.183041,
0.196666,
0.192083,
0.192541,
0.212208,
0.23525
]
}
}
},
{
"rows": 32,
"width": 1003,
"dtype": "float32",
"max_abs_error": 0.0,
"timings": {
"eager": {
"median_ms": 0.228791,
"samples_ms": [
0.269583,
0.224083,
0.249292,
0.234417,
0.23475,
0.229583,
0.2335,
0.231584,
0.232292,
0.226375,
0.227375,
0.224875,
0.222291,
0.216875,
0.228,
0.222334,
0.235542,
0.223666,
0.230167,
0.223459
]
},
"compiled": {
"median_ms": 0.196583,
"samples_ms": [
0.196291,
0.208083,
0.211208,
0.214792,
0.203625,
0.191208,
0.196875,
0.181042,
0.190583,
0.187208,
0.190167,
0.192334,
0.194334,
0.192125,
0.246042,
0.191875,
0.231625,
0.269167,
0.23475,
0.208583
]
}
}
}
],
"limits": "Expression compilation may fuse operations. No kernel trace or measured HBM byte count; no whole-model, CUDA or Triton speedup claim."
}
This image is a report the application generated from the saved run; it is not a new run. Open the full-resolution report or read the raw result.
Compare numerical error and timing
Fusion can reduce dispatch and data movement but increase register pressure or compilation overhead. Small and large shapes can behave differently. Fewer tensor reads and writes do not give an equal drop in model latency, because normalization may be a small part of the critical path.
Numerical parity exceeds tolerance. compare_case rejects a compiled result outside the numerical tolerance before it reads any timings.
Invalid timing samples. compare_case rejects missing, nonfinite or nonpositive execution times. The analyzer allows equal timings; it never assumes compilation must win.
Read the executable checks
import unittest
from lab import compare_case
class FusionEvidenceTests(unittest.TestCase):
def case(self):
return {
"rows": 1,
"width": 3,
"max_abs_error": 0,
"timings": {
"eager": {"samples_ms": [1, 3, 2]},
"compiled": {"samples_ms": [2, 2, 2]},
},
}
def test_parity_is_required_before_timing(self):
case = self.case()
case["max_abs_error"] = 0.1
with self.assertRaises(ValueError):
compare_case(case)
def test_invalid_execution_timing_is_rejected(self):
case = self.case()
case["timings"]["compiled"]["samples_ms"] = [-1]
with self.assertRaises(ValueError):
compare_case(case)
def test_medians_are_compared_without_a_speedup_promise(self):
result = compare_case(self.case())
self.assertEqual(result["eager_median_ms"], 2)
self.assertEqual(result["compiled_median_ms"], 2)
if __name__ == "__main__":
unittest.main()The optional command below reruns the Metal tensor experiment and writes new-fusion-run.json. It does not start an HTTP server or load the language model from the first lesson.
python3 -m venv .venv
.venv/bin/python -m pip install mlx==0.32.4
.venv/bin/python fusion_live.py --output new-fusion-run.jsonTry a change and explain the result
Compare eager and compiled timing distributions for each shape. Check numerical error before choosing the faster path. Explain why neither a fixed speedup nor an exact HBM-access ratio follows from these results.
Read the explanation
Retain the shape, dtype, repetitions, backend, and error check. Whole-model impact requires a separate measurement.
Decide whether fusion belongs on the critical path
Use the kernels your runtime provides before you maintain custom device code. Consider a custom kernel only after a model profile shows normalization on the critical path. Time the warm steady state separately from compilation, and test dtype, shape and numerical tolerances. A CUDA/Triton port needs its own run on that hardware and its own bounds tests.
References
- MLX compilation and fusion.
- Triton normalization implementation patterns.
- RMSNorm authors’ formulation.
Sources checked October 24, 2026. Runtime-specific commands and results apply to the recorded versions; linked rolling documentation can change. The application scenarios are teaching examples, not claims about an author’s production incident.