Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/cpu-portability.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ jobs:
if ! MTL_DEBUG_LAYER=1 MTL_SHADER_VALIDATION=0 \
BIN="$PWD/build-ci" SYN_DIR="$RUNNER_TEMP/varda-synthetic" \
OUT="$RUNNER_TEMP/varda-metal-parity" bash tests/run_synthetic.sh metal; then
cat "$RUNNER_TEMP/varda-metal-parity/a.metal-fp32.log"
cat "$RUNNER_TEMP/varda-metal-parity"/a.metal-fp*.log
exit 1
fi
MTL_DEBUG_LAYER=1 MTL_SHADER_VALIDATION=0 \
Expand Down
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.24)
project(varda LANGUAGES CXX)

option(VARDA_CUDA "Build the CUDA backend" ON)
option(VARDA_METAL "Build the Apple Silicon Metal fp32 backend" ${APPLE})
option(VARDA_METAL "Build the Apple Silicon Metal fp32/mixed-fp16 backend" ${APPLE})
option(VARDA_NATIVE "Tune CPU code for the build host (-march=native)" OFF)
option(VARDA_GRIB "Build the GRIB input/output layer (needs ecCodes, ECCODES_HOME)" ON)

Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ anemoi-inference does); it needs ecCodes (`-DVARDA_GRIB=ON`, `tools/env.sh`): `d
Apple Silicon: the CPU fp32 backend builds natively on macOS arm64 with OpenMP and OpenBLAS.
Build, GRIB dependencies and verification: [docs/apple-silicon.md](docs/apple-silicon.md).
The optional [Metal/MPS backend](docs/metal.md) runs on the Apple GPU with
`--device metal --precision fp32`; CUDA requires an NVIDIA GPU.
`--device metal --precision fp32` or `--precision fp16` (mixed precision);
CUDA requires an NVIDIA GPU.

## Licence and disclaimer

Expand Down
2 changes: 1 addition & 1 deletion docs/apple-silicon.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Apple Silicon (macOS arm64)

The existing CPU fp32 backend runs natively on Apple Silicon using Apple Clang,
OpenMP and OpenBLAS. The optional native Metal/MPS backend runs fp32 inference on
OpenMP and OpenBLAS. The optional native Metal/MPS backend runs fp32 and mixed-fp16 inference on
the Apple GPU; see [metal.md](metal.md). CUDA remains NVIDIA-only. CPU arithmetic
and numerical tolerances are unchanged.

Expand Down
75 changes: 62 additions & 13 deletions docs/metal.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# Apple Silicon Metal backend

`--device metal --precision fp32` runs the forecaster on a unified-memory Metal
GPU. It uses MPS matrix multiplication and native Metal compute shaders. There
`--device metal --precision fp32` or `--precision fp16` runs the forecaster on a
unified-memory Metal GPU. FP16 uses mixed precision: low precision storage with
FP32 accumulation and sensitive calculations. It uses MPS matrix multiplication
and native Metal compute shaders. There
is no PyTorch dependency and no silent CPU fallback. CPU and CUDA numerical
kernels, precision settings and tolerance files are unchanged.

Expand All @@ -19,22 +21,24 @@ cmake --build build-metal -j 4
build-metal/varda-metal-info
build-metal/varda-run --model MODEL.safetensors --input INPUT.safetensors \
--device metal --precision fp32 --steps 3
build-metal/varda-run --model MODEL.safetensors --input INPUT.safetensors \
--device metal --precision fp16 --steps 3
```

The build links Apple's Foundation, Metal and MetalPerformanceShaders frameworks.
Shader source is embedded at configure time and compiled by Metal at model load;
the executable does not need the source tree or an external `.metallib` at run
time. The normal parity app still needs its reference/tolerance files.

`varda-rollout --device metal --precision fp32` uses the existing host rollout
`varda-rollout --device metal --precision fp32|fp16` uses the existing host rollout
loop: predictions run on the GPU, while feedback and computed forcings run on
the host. `--engine device` remains CUDA-only. With an assets bundle,
`./varda forecast latest --device metal --precision fp32` runs locally and probes
`./varda forecast latest --device metal --precision fp16` runs locally and probes
the Metal GPU before downloading inputs; it does not invoke Slurm.

## Implementation and numerics

- Dense layers: `MPSMatrixMultiplication`, float32 inputs, weights and outputs,
- FP32 dense layers: `MPSMatrixMultiplication`, float32 inputs, weights and outputs,
with a separate bias addition and one cached multiplication object per shape.
- Graph attention: destination-sorted CSR, explicit edge projection inside the
score/value kernels, per-edge/head scores and softmax, and stored-order sums.
Expand All @@ -59,6 +63,33 @@ the Metal GPU before downloading inputs; it does not invoke Slurm.
retaining a final completion wait before reading output. This bounds queued
operation count and resource retention, not elapsed GPU time.

### Mixed FP16 precision policy

| Stage | Storage and calculation |
|---|---|
| Normalization and feature assembly | FP32, including public inputs and hook values |
| Dense layers | FP16 operands/weights/bias; MPS **FP32 result**; FP32 bias addition, then one FP16 rounding |
| LayerNorm | FP32 affine parameters, centered FP32 moments and affine arithmetic; FP16 output (the next Linear's input cast) |
| Attention | FP16 q/k/v and edge operands upcast for FP32 dot products, softmax and weighted sums; FP16 attention output |
| Edge projection | FP16 attributes/weights/bias, FP32 sum, then FP16 projection rounding before use in attention |
| Residual stream and GELU | FP32 arithmetic with FP16 rounding at each stored operation |
| Physical output | Decoder's FP16 prediction upcast; residual, bounding and inverse normalization in FP32; public outputs FP32 |

MPS gets padded FP16 weight rows. Already compatible FP16 activations are used
directly; FP32 inputs and odd/unaligned rows use a reusable packing buffer.
GEMMs write a bounded FP32 scratch result, rather than asking MPS for an all-half
GEMM, which can overflow intermediate values before cancellation. Ordered,
tracked Metal accesses preserve scratch dependencies. Large embedding GEMMs
are also chunked in FP16 mode so scratch size stays bounded.

Activation hooks upcast stored FP16 values for inspection after synchronization;
they read the same production results. FP32 retains the original GEMM path and
is bitwise equal to PR #2 for all six synthetic outputs. CPU remains FP32-only;
CUDA precision choices are unchanged. FP32 accumulation does not prevent
overflow when a genuinely large result is stored in FP16, nor recover input
quantization losses. The policy follows autocast rounding boundaries but does
not promise bitwise equality with CUDA's fused/folded attention implementation.

`VARDA_METAL_CHUNK_ROWS` controls complete destination-row chunks (default 8192).
It bounds dense/attention workspace; it does not split a destination's softmax.
All buffers are planned at load. Allocations are checked against the device's
Expand All @@ -82,13 +113,21 @@ normalisation and assembly are bitwise equal to the reference; hook-free and
hooked outputs are bitwise equal. A small-chunk run also passes with the Metal
API validation layer enabled.

All 12 FP16 synthetic runs also pass unchanged `synthetic-fp16` tolerances
(3e-3; 1e-6 for input stages). Worst activation in model e is `proc.3.out`:
`rel_absmax` 1.40e-3, `max_abs` 2.49e-2, ratio to tolerance 0.465 (8 host
threads). FP16 hooks are inert, input stages match bitwise, and repeated
inference is bitwise stable. No tolerance files were changed.

The integration suite checks repeated inference, a four-step host rollout with
computed forcings/feedback against CPU at the existing synthetic fp32 tolerance,
completely empty graphs, FP16 rejection and invalid chunk sizes. These are
computed forcings/feedback against CPU at existing FP32/FP16 tolerances,
completely empty graphs, CPU FP16 rejection and invalid chunk sizes. A dense
cancellation regression drives the real FP16 embedding GEMM with products
of +/-65536 and an exactly zero sum, catching intermediate overflow. These are
synthetic correctness checks, not meteorological forecast qualification.
It also generates three independent golden models with 7/35/96 channels,
including one hidden node, incomplete SIMD groups, 1/7/37-row chunks, and 8,201
data nodes crossing the default chunk boundary: ten further parity checks,
data nodes crossing the default chunk boundary: ten further checks per precision,
including hook inertness. CI runs GPU parity and integration with Metal API
validation. The direct kernel test below also enables GPU Shader Validation.
Global shader instrumentation changes MPS GEMM results on the hosted Apple
Expand All @@ -98,10 +137,13 @@ instrumentation in hosted CI; the full suite additionally passes with both
validation layers enabled on the physical M1.

The macOS-only `test_metal_kernels` CTest target directly checks the production
LayerNorm shader against double-precision mathematical references: 384 cases
LayerNorm shader against double-precision mathematical references: 384 cases per
precision (768 total),
with widths 1 through 4097, random/constant/nearly constant/cancellation-prone
inputs, optional bias and output guards. All pass at 1e-5; measured worst
`rel_absmax` 3.39e-7 and `max_abs` 1.62e-6. The old serial shader fails 90 of
inputs, optional bias and output guards. FP32 cases pass at 1e-5; measured worst
`rel_absmax` 3.39e-7 and `max_abs` 1.62e-6 in FP32. FP16 inputs are quantized
before constructing the reference; worst `rel_absmax` is 4.81e-4 and `max_abs`
1.95e-3 at tolerance 3e-3. The old FP32 serial shader fails 90 of
these cases (worst relative error 1.07e-2). This test enables Metal API/shader
validation and returns skip code 77 when no GPU is available.

Expand All @@ -111,15 +153,22 @@ measured mean warm forward times of 40.8 -> 25.9 ms and 53.2 -> 31.1 ms after
parallel LayerNorm and bounded batching. Repeats are bitwise stable; Metal has
no CUDA graph path. These synthetic timings do not establish full-model speed.

In a separate mixed-precision comparison on M1 (two alternating FP32/FP16 rounds
of 20 predictions, discard the first three, eight host threads), model e measured
27.1 -> 23.0 ms and model d 32.6 -> 27.8 ms: about 1.18x faster with FP16.
Repeats are bitwise stable. FP16 halves selected weights/activation storage;
indices, input features, scores and FP32 GEMM scratch remain full width, so total
memory usage does not halve. No full-model speed or memory qualification is implied.

`varda-metal-info` exits 77 if no unified-memory Metal device is present. An
explicit synthetic `metal` run also exits 77 rather than reporting a GPU pass
when execution was skipped. CI compiles the backend on macOS arm64 and runs the
GPU checks when a device is exposed; a GPU-less hosted runner reports the skip.

## Limits

FP32 only; no mixed precision, Metal graph capture, or GPU-resident rollout
window yet. The first call includes MPS kernel setup. Large-model performance
No Metal graph capture or GPU-resident rollout window yet. The first call
includes MPS kernel setup. Large-model performance
has not been measured; synthetic timings must not be extrapolated to Varda.

The full Varda checkpoint and real-data GRIB forecasts have not been qualified
Expand Down
104 changes: 73 additions & 31 deletions python/tests/test_metal.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,11 @@ def run_app(self, name, *args, ok=True, env=None):
return result

def test_repeated_inference(self):
result = self.run_app("varda-run", "--model", self.model, "--input", self.inputs,
"--device", "metal", "--precision", "fp32", "--steps", 3)
self.assertIn("repeats bitwise equal", result.stdout)
for precision in ("fp32", "fp16"):
with self.subTest(precision=precision):
result = self.run_app("varda-run", "--model", self.model, "--input", self.inputs,
"--device", "metal", "--precision", precision, "--steps", 3)
self.assertIn("repeats bitwise equal", result.stdout)

def test_irregular_shapes_and_chunk_boundaries(self):
# Fresh independent golden data exercises incomplete SIMD groups and
Expand All @@ -64,20 +66,58 @@ def test_irregular_shapes_and_chunk_boundaries(self):
tolerance.write_text(json.dumps(synthetic.tolerance_file(name)))
finally:
del synthetic.CONFIGS[name]
for chunk in ((37, 8192) if name == "cross" else (1, 7, 37, 8192)):
with self.subTest(model=name, chunk=chunk):
report = self.root / f"{name}.{chunk}.report.json"
self.run_app("varda-parity", "--model", self.root / f"{name}.model.safetensors",
"--check", f"{self.root}/{name}.golden.safetensors=synthetic-fp32",
"--tolerances", tolerance, "--report", report,
"--device", "metal", "--precision", "fp32", "--threads", 2,
env=dict(os.environ, VARDA_METAL_CHUNK_ROWS=str(chunk)))
self.assertTrue(json.loads(report.read_text())["hook_inert"])

def test_fp16_rejected(self):
for precision in ("fp32", "fp16"):
for chunk in ((37, 8192) if name == "cross" else (1, 7, 37, 8192)):
with self.subTest(model=name, chunk=chunk, precision=precision):
report = self.root / f"{name}.{chunk}.{precision}.report.json"
self.run_app("varda-parity", "--model", self.root / f"{name}.model.safetensors",
"--check", f"{self.root}/{name}.golden.safetensors=synthetic-{precision}",
"--tolerances", tolerance, "--report", report,
"--device", "metal", "--precision", precision, "--threads", 2,
env=dict(os.environ, VARDA_METAL_CHUNK_ROWS=str(chunk)))
self.assertTrue(json.loads(report.read_text())["hook_inert"])

def test_cpu_fp16_rejected(self):
result = self.run_app("varda-run", "--model", self.model, "--input", self.inputs,
"--device", "metal", "--precision", "fp16", ok=False)
self.assertIn("Metal backend runs fp32 only", result.stdout)
"--device", "cpu", "--precision", "fp16", ok=False)
self.assertIn("CPU backend runs fp32 only", result.stdout)

def test_fp16_dense_cancellation(self):
# Products +/-65536 exceed fp16 range; the fp32 sum is exactly zero.
# Test the real embedding GEMM, conversion and bias path, not a probe
# that could accidentally use a different MPS precision configuration.
tensors, metadata = synthetic.read_st(self.model)
cfg = json.loads(metadata["config"])
cfg["source"]["uuid"] += "-dense-cancellation"
tensors = {k: v.copy() for k, v in tensors.items()}
tensors["norm.mul"][:] = 1
tensors["norm.add"][:] = 0
tensors["enc.emb_src.weight"][:] = 0
tensors["enc.emb_src.weight"][:, :4] = [256, 256, -256, -256]
tensors["enc.emb_src.bias"][:] = 0
original, golden_metadata = synthetic.read_st(self.inputs)
x = original["in.x"].copy()
x[:, 0, :, :4] = 256
reference = {k: v.astype(np.float32) for k, v in synthetic.reference(cfg, tensors, x).items()}
self.assertTrue(np.array_equal(reference["enc.emb_src"], np.zeros_like(reference["enc.emb_src"])))
model = self.root / "cancellation.model.safetensors"
golden = self.root / "cancellation.golden.safetensors"
tolerance = self.root / "cancellation.tolerances.json"
synthetic.write_st(str(model), tensors, {"varda_format": "1", "config": json.dumps(cfg)})
golden_metadata = dict(golden_metadata, tag="cancellation", checkpoint_uuid=cfg["source"]["uuid"])
manifest = json.loads(golden_metadata["manifest"])
manifest["checkpoint_identity"]["uuid"] = cfg["source"]["uuid"]
manifest["tag"] = "cancellation"
golden_metadata["manifest"] = json.dumps(manifest)
synthetic.write_st(str(golden), reference, golden_metadata)
table = synthetic.tolerance_file("a")
table["checkpoint"]["uuid"] = cfg["source"]["uuid"]
tolerance.write_text(json.dumps(table))
for chunk in (37, 8192):
with self.subTest(chunk=chunk):
self.run_app("varda-parity", "--model", model, "--check", f"{golden}=synthetic-fp16",
"--tolerances", tolerance, "--device", "metal", "--precision", "fp16", "--threads", 2,
env=dict(os.environ, VARDA_METAL_CHUNK_ROWS=str(chunk)))

def test_invalid_chunk_rejected(self):
for value in ("0", "not-a-number"):
Expand Down Expand Up @@ -112,17 +152,18 @@ def test_host_rollout(self):
model = self.root / "rollout.model.safetensors"
synthetic.write_st(str(model), tensors, {"varda_format": "1", "config": json.dumps(cfg)})
results = {}
for device in ("cpu", "metal"):
output = self.root / f"rollout.{device}.safetensors"
for device, precision in (("cpu", "fp32"), ("metal", "fp32"), ("metal", "fp16")):
output = self.root / f"rollout.{device}.{precision}.safetensors"
result = self.run_app("varda-rollout", "--model", model, "--input", self.inputs,
"--device", device, "--precision", "fp32", "--threads", 2,
"--device", device, "--precision", precision, "--threads", 2,
"--date", "2024-06-01T00:00:00", "--steps", 4, "--out", output)
self.assertIn("engine host", result.stdout)
results[device] = synthetic.read_st(output)[0]["y"].astype(np.float64)
self.assertTrue(np.isfinite(results["metal"]).all())
for step, (actual, reference) in enumerate(zip(results["metal"], results["cpu"])):
error = np.max(np.abs(actual - reference)) / np.max(np.abs(reference))
self.assertLessEqual(error, synthetic.FP32_TOL, f"step {step}: rel_absmax={error}")
results[device, precision] = synthetic.read_st(output)[0]["y"].astype(np.float64)
for precision, tolerance in (("fp32", synthetic.FP32_TOL), ("fp16", synthetic.FP16_TOL)):
self.assertTrue(np.isfinite(results["metal", precision]).all())
for step, (actual, reference) in enumerate(zip(results["metal", precision], results["cpu", "fp32"])):
error = np.max(np.abs(actual - reference)) / np.max(np.abs(reference))
self.assertLessEqual(error, tolerance, f"{precision} step {step}: rel_absmax={error}")

def test_empty_graphs(self):
tensors, metadata = synthetic.read_st(self.model)
Expand All @@ -134,14 +175,15 @@ def test_empty_graphs(self):
model = self.root / "empty-graphs.model.safetensors"
synthetic.write_st(str(model), tensors, {"varda_format": "1", "config": json.dumps(cfg)})
results = {}
for device in ("cpu", "metal"):
output = self.root / f"empty-graphs.{device}.safetensors"
for device, precision in (("cpu", "fp32"), ("metal", "fp32"), ("metal", "fp16")):
output = self.root / f"empty-graphs.{device}.{precision}.safetensors"
self.run_app("varda-run", "--model", model, "--input", self.inputs,
"--device", device, "--precision", "fp32", "--threads", 2, "--out", output)
results[device] = synthetic.read_st(output)[0]["out.y"].astype(np.float64)
self.assertTrue(np.isfinite(results["metal"]).all())
error = np.max(np.abs(results["metal"] - results["cpu"])) / np.max(np.abs(results["cpu"]))
self.assertLessEqual(error, synthetic.FP32_TOL)
"--device", device, "--precision", precision, "--threads", 2, "--out", output)
results[device, precision] = synthetic.read_st(output)[0]["out.y"].astype(np.float64)
for precision, tolerance in (("fp32", synthetic.FP32_TOL), ("fp16", synthetic.FP16_TOL)):
self.assertTrue(np.isfinite(results["metal", precision]).all())
error = np.max(np.abs(results["metal", precision] - results["cpu", "fp32"])) / np.max(np.abs(results["cpu", "fp32"]))
self.assertLessEqual(error, tolerance)


if __name__ == "__main__":
Expand Down
Loading
Loading