From 55b1eeffcc9c74c87a0bb5cab41d1dd6dc7972e4 Mon Sep 17 00:00:00 2001 From: Oliver Fuhrer Date: Fri, 23 Oct 2026 22:20:57 +0200 Subject: [PATCH] Add mixed-precision fp16 inference to Metal --- .github/workflows/cpu-portability.yml | 2 +- CMakeLists.txt | 2 +- README.md | 3 +- docs/apple-silicon.md | 2 +- docs/metal.md | 75 +++++++++++--- python/tests/test_metal.py | 104 +++++++++++++------ src/varda/metal/backend_metal.mm | 144 ++++++++++++++++++++------ src/varda/metal/kernels.metal | 71 +++++++++---- src/varda/model.cpp | 2 - tests/metal/test_metal_kernels.mm | 87 +++++++++------- tests/run_synthetic.sh | 5 +- varda | 5 +- 12 files changed, 356 insertions(+), 146 deletions(-) diff --git a/.github/workflows/cpu-portability.yml b/.github/workflows/cpu-portability.yml index 5cfaad9..b148cc9 100644 --- a/.github/workflows/cpu-portability.yml +++ b/.github/workflows/cpu-portability.yml @@ -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 \ diff --git a/CMakeLists.txt b/CMakeLists.txt index f27f9d1..0271f28 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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) diff --git a/README.md b/README.md index 4a5d1a1..73ab384 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/apple-silicon.md b/docs/apple-silicon.md index c0a1636..a3e46ac 100644 --- a/docs/apple-silicon.md +++ b/docs/apple-silicon.md @@ -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. diff --git a/docs/metal.md b/docs/metal.md index 7c63430..87267f4 100644 --- a/docs/metal.md +++ b/docs/metal.md @@ -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. @@ -19,6 +21,8 @@ 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. @@ -26,15 +30,15 @@ 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. @@ -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 @@ -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 @@ -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. @@ -111,6 +153,13 @@ 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 @@ -118,8 +167,8 @@ 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 diff --git a/python/tests/test_metal.py b/python/tests/test_metal.py index 5203218..c252489 100644 --- a/python/tests/test_metal.py +++ b/python/tests/test_metal.py @@ -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 @@ -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"): @@ -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) @@ -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__": diff --git a/src/varda/metal/backend_metal.mm b/src/varda/metal/backend_metal.mm index 94c07d5..ca60b6f 100644 --- a/src/varda/metal/backend_metal.mm +++ b/src/varda/metal/backend_metal.mm @@ -1,4 +1,4 @@ -// Native Metal fp32 inference. MPS handles dense GEMMs; graph attention and all +// Native Metal fp32/mixed-fp16 inference. MPS handles dense GEMMs; graph attention and all // elementwise operations run as Metal compute kernels. No CPU compute fallback. #import #import @@ -52,14 +52,26 @@ uint32_t u(int64_t n) { struct Tensor { id buffer = nil; NSUInteger offset = 0; - Tensor sub(int64_t floats) const { + NSUInteger element_size = sizeof(float); + Tensor sub(int64_t elements) const { Tensor t = *this; - t.offset += static_cast(floats) * sizeof(float); + t.offset += static_cast(elements) * element_size; return t; } - float* data() const { return reinterpret_cast(static_cast(buffer.contents) + offset); } + float* data() const { + if (element_size != sizeof(float)) throw std::runtime_error("expected an fp32 host tensor"); + return reinterpret_cast(static_cast(buffer.contents) + offset); + } + void read(float* out, size_t n) const { + const char* p = static_cast(buffer.contents) + offset; + if (element_size == sizeof(float)) std::memcpy(out, p, n * sizeof(float)); + else { + const auto* half = reinterpret_cast(p); + for (size_t i = 0; i < n; ++i) out[i] = static_cast(half[i]); + } + } }; -struct Linear { Tensor w, b; int64_t out = 0, in = 0; }; +struct Linear { Tensor w, b; int64_t out = 0, in = 0; NSUInteger row_bytes = 0; }; struct Norm { Tensor w, b; }; struct Block { Linear q, k, v, self, edge, proj, mlp1, mlp2; @@ -78,10 +90,10 @@ Tensor sub(int64_t floats) const { private: Tensor bytes(size_t n, const void* source = nullptr); - Tensor floats(int64_t n) { u(n); return bytes(static_cast(n) * sizeof(float)); } template Tensor upload(const std::vector& v) { return bytes(v.size() * sizeof(T), v.data()); } - Tensor arena(const std::string& name, int64_t n); - Linear load_linear(SafeTensorsFile& f, const std::string& name, int64_t out, int64_t in); + Tensor half_data(const float* source, int64_t rows, int64_t cols, int64_t stride); + Tensor arena(const std::string& name, int64_t n, bool half = false); + Linear load_linear(SafeTensorsFile& f, const std::string& name, int64_t out, int64_t in, bool edge = false); Norm load_norm(SafeTensorsFile& f, const std::string& name); Block load_block(SafeTensorsFile& f, const std::string& name, bool mapper); Graph load_graph(SafeTensorsFile& f, const std::string& name, int64_t src, int64_t dst); @@ -101,6 +113,7 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, void run(const float* x, float* y, const ActivationHook* hook); Config cfg_; + bool fp16_; int64_t C_, G_, H_, F_, chunk_; id device_; id queue_; @@ -111,6 +124,7 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, std::map arena_; Tensor mul_in_, add_in_, mul_out_, add_out_, data_attr_, hidden_attr_, residual_in_, residual_out_; Tensor keys_, values_, scores_, ln_, q_, self_, attention_, residual_, hidden_; + Tensor gemm_input_, gemm_result_; Linear enc_src_, enc_dst_, dec_dst_, out_proj_; Norm out_norm_; Block enc_, dec_; @@ -120,7 +134,7 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, }; Tensor MetalBackend::bytes(size_t n, const void* source) { - u(n / sizeof(float)); // every GPU buffer stores 32-bit floats or indices + u(n / sizeof(float)); // element counts are checked separately for fp16 storage const size_t size = std::max(n, sizeof(float)); if (size > device_.maxBufferLength) throw std::runtime_error("Metal buffer exceeds this GPU's maxBufferLength"); @@ -134,19 +148,38 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, return {buffer, 0}; } -Tensor MetalBackend::arena(const std::string& name, int64_t n) { +Tensor MetalBackend::half_data(const float* source, int64_t rows, int64_t cols, int64_t stride) { + const int64_t n = rows * stride; + u(n); + Tensor t = bytes(static_cast(n) * sizeof(_Float16)); + t.element_size = sizeof(_Float16); + auto* dest = static_cast<_Float16*>(t.buffer.contents); + std::fill_n(dest, n, _Float16(0)); + for (int64_t r = 0; r < rows; ++r) + for (int64_t c = 0; c < cols; ++c) dest[r * stride + c] = static_cast<_Float16>(source[r * cols + c]); + return t; +} + +Tensor MetalBackend::arena(const std::string& name, int64_t n, bool half) { Tensor& t = arena_[name]; u(n); - if (!t.buffer || t.buffer.length < static_cast(n) * sizeof(float)) t = floats(n); + const size_t element_size = half ? sizeof(_Float16) : sizeof(float); + if (!t.buffer || t.buffer.length < static_cast(n) * element_size || t.element_size != element_size) { + t = bytes(static_cast(n) * element_size); + t.element_size = element_size; + } return t; } -Linear MetalBackend::load_linear(SafeTensorsFile& f, const std::string& name, int64_t out, int64_t in) { +Linear MetalBackend::load_linear(SafeTensorsFile& f, const std::string& name, int64_t out, int64_t in, bool edge) { const TensorView& w = f.take(name + ".weight", DType::F32, {out, in}); - Linear l{bytes(w.nbytes, w.data), {}, out, in}; + const NSUInteger row_bytes = fp16_ ? (edge ? in * sizeof(_Float16) : + [MPSMatrixDescriptor rowBytesFromColumns:in dataType:MPSDataTypeFloat16]) : in * sizeof(float); + Linear l{fp16_ ? half_data(w.as(), out, in, row_bytes / sizeof(_Float16)) : bytes(w.nbytes, w.data), + {}, out, in, row_bytes}; if (!cfg_.is_absent(name + ".bias")) { const TensorView& b = f.take(name + ".bias", DType::F32, {out}); - l.b = bytes(b.nbytes, b.data); + l.b = fp16_ ? half_data(b.as(), 1, out, out) : bytes(b.nbytes, b.data); } return l; } @@ -167,7 +200,7 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, b.k = load_linear(f, name + ".k", C_, C_); b.v = load_linear(f, name + ".v", C_, C_); b.self = load_linear(f, name + ".self", C_, C_); - b.edge = load_linear(f, name + ".edge", C_, cfg_.edge_attr_dim); + b.edge = load_linear(f, name + ".edge", C_, cfg_.edge_attr_dim, true); b.proj = load_linear(f, name + ".proj", C_, C_); b.mlp1 = load_linear(f, name + ".mlp1", cfg_.mlp_hidden, C_); b.mlp2 = load_linear(f, name + ".mlp2", C_, cfg_.mlp_hidden); @@ -190,15 +223,15 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, g.rows = upload(g.host.row_ptr); g.sources = upload(g.host.src); g.destinations = upload(dest); - g.attrs = upload(g.host.attr); + g.attrs = fp16_ ? half_data(g.host.attr.data(), 1, g.host.attr.size(), g.host.attr.size()) : upload(g.host.attr); return g; } MetalBackend::MetalBackend(const Config& cfg, SafeTensorsFile& f, const Options& opts) - : cfg_(cfg), C_(cfg.num_channels), G_(cfg.n_data_nodes), H_(cfg.n_hidden_nodes), F_(cfg.src_features()), + : cfg_(cfg), fp16_(opts.precision == Precision::FP16), C_(cfg.num_channels), G_(cfg.n_data_nodes), + H_(cfg.n_hidden_nodes), F_(cfg.src_features()), chunk_(8192) { @autoreleasepool { - if (opts.precision != Precision::FP32) throw std::runtime_error("the Metal backend runs fp32 only"); device_ = MTLCreateSystemDefaultDevice(); if (!device_ || !device_.hasUnifiedMemory) throw std::runtime_error("no unified-memory Metal GPU is available; use --device cpu"); @@ -221,12 +254,16 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, #endif compile.languageVersion = MTLLanguageVersion2_3; NSError* error = nil; - id library = [device_ newLibraryWithSource:[NSString stringWithUTF8String:metal::kernel_source] + const std::string source = std::string(fp16_ ? "#define VARDA_METAL_FP16\n" : "") + metal::kernel_source; + id library = [device_ newLibraryWithSource:[NSString stringWithUTF8String:source.c_str()] options:compile error:&error]; if (!library) throw std::runtime_error("Metal shader compilation: " + std::string(error.localizedDescription.UTF8String)); for (const char* name : {"normalise", "assemble", "bias_add", "add_arrays", "copy_array", "layernorm", "gelu", "attention_scores", "attention_softmax", "attention_values", "residual", - "bound_clamp", "bound_product", "bound_assign", "denormalise"}) { + "bound_clamp", "bound_product", "bound_assign", "denormalise", + "pack_half_from_float", "pack_half_from_half", "linear_store_half"}) { + if (!fp16_ && (std::strncmp(name, "pack_half", 9) == 0 || std::strcmp(name, "linear_store_half") == 0)) + continue; id function = [library newFunctionWithName:[NSString stringWithUTF8String:name]]; id pipeline = [device_ newComputePipelineStateWithFunction:function error:&error]; if (!pipeline) throw std::runtime_error("Metal pipeline " + std::string(name) + ": " + error.localizedDescription.UTF8String); @@ -275,19 +312,27 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, max_bound = std::max(max_bound, static_cast(b.index.size())); } const int64_t max_nodes = std::max(G_, H_); - keys_ = arena("keys", max_nodes * C_); values_ = arena("values", max_nodes * C_); + keys_ = arena("keys", max_nodes * C_, fp16_); values_ = arena("values", max_nodes * C_, fp16_); scores_ = arena("scores", std::max({enc_graph_.host.n_edges, proc_graph_.host.n_edges, dec_graph_.host.n_edges}) * cfg.num_heads); - ln_ = arena("ln", chunk_ * C_); q_ = arena("q", chunk_ * C_); - self_ = arena("self", chunk_ * C_); attention_ = arena("attention", chunk_ * C_); - residual_ = arena("residual", chunk_ * C_); hidden_ = arena("hidden", chunk_ * cfg.mlp_hidden); + ln_ = arena("ln", chunk_ * C_, fp16_); q_ = arena("q", chunk_ * C_, fp16_); + self_ = arena("self", chunk_ * C_, fp16_); attention_ = arena("attention", chunk_ * C_, fp16_); + residual_ = arena("residual", chunk_ * C_, fp16_); hidden_ = arena("hidden", chunk_ * cfg.mlp_hidden, fp16_); arena("input", cfg.n_input_steps * G_ * cfg.n_input_vars); arena("xn", cfg.n_input_steps * G_ * cfg.n_input_vars); arena("features", G_ * F_); - for (const char* name : {"z", "latent", "proc.a", "proc.b", "encoder.dest"}) arena(name, H_ * C_); - for (const char* name : {"embed", "block"}) arena(name, chunk_ * C_); - for (const char* name : {"decoder", "output"}) arena(name, G_ * cfg.n_output_vars); + for (const char* name : {"z", "latent", "proc.a", "proc.b", "encoder.dest"}) arena(name, H_ * C_, fp16_); + for (const char* name : {"embed", "block"}) arena(name, chunk_ * C_, fp16_); + arena("decoder", G_ * cfg.n_output_vars, fp16_); + arena("output", G_ * cfg.n_output_vars); arena("products", G_ * max_bound); + if (fp16_) { + const int64_t width = std::max({C_, cfg.mlp_hidden, F_, cfg.node_attr_dim, cfg.n_output_vars}); + const NSUInteger in_stride = [MPSMatrixDescriptor rowBytesFromColumns:width dataType:MPSDataTypeFloat16]; + const NSUInteger out_stride = [MPSMatrixDescriptor rowBytesFromColumns:width dataType:MPSDataTypeFloat32]; + gemm_input_ = arena("gemm.input", chunk_ * (in_stride / sizeof(_Float16)), true); + gemm_result_ = arena("gemm.result", chunk_ * (out_stride / sizeof(float))); + } } } @@ -331,9 +376,15 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, } void MetalBackend::linear(const Linear& l, const Tensor& x, int64_t rows, const Tensor& out) { - auto matrix = [](const Tensor& t, int64_t r, int64_t c) { + if (fp16_ && rows > chunk_) { + for (int64_t row = 0; row < rows; row += chunk_) + linear(l, x.sub(row * l.in), std::min(chunk_, rows - row), out.sub(row * l.out)); + return; + } + auto matrix = [](const Tensor& t, int64_t r, int64_t c, NSUInteger row_bytes = 0) { MPSMatrixDescriptor* descriptor = [MPSMatrixDescriptor matrixDescriptorWithRows:r columns:c - rowBytes:c * sizeof(float) dataType:MPSDataTypeFloat32]; + rowBytes:row_bytes ? row_bytes : c * t.element_size + dataType:t.element_size == sizeof(_Float16) ? MPSDataTypeFloat16 : MPSDataTypeFloat32]; return [[MPSMatrix alloc] initWithBuffer:t.buffer offset:t.offset descriptor:descriptor]; }; const auto key = std::make_tuple(rows, l.out, l.in); @@ -341,6 +392,26 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, if (!gemm) gemm = [[MPSMatrixMultiplication alloc] initWithDevice:device_ transposeLeft:NO transposeRight:YES resultRows:rows resultColumns:l.out interiorColumns:l.in alpha:1.0 beta:0.0]; if (!gemm) throw std::runtime_error("cannot create an MPS matrix multiplication"); + if (fp16_) { + const NSUInteger in_bytes = [MPSMatrixDescriptor rowBytesFromColumns:l.in dataType:MPSDataTypeFloat16]; + const NSUInteger out_bytes = [MPSMatrixDescriptor rowBytesFromColumns:l.out dataType:MPSDataTypeFloat32]; + const int64_t in_stride = in_bytes / sizeof(_Float16), out_stride = out_bytes / sizeof(float); + Tensor operand = x; + // Common channel widths already have MPS-compatible packed half rows. + // FP32 inputs and odd/unaligned rows use the reusable conversion arena. + if (x.element_size != sizeof(_Float16) || in_bytes != l.in * sizeof(_Float16) || x.offset % 16) { + dispatch(x.element_size == sizeof(float) ? "pack_half_from_float" : "pack_half_from_half", + {u(rows * in_stride), u(l.in), u(in_stride)}, {x, gemm_input_}); + operand = gemm_input_; + } + [gemm encodeToCommandBuffer:command() leftMatrix:matrix(operand, rows, l.in, in_bytes) + rightMatrix:matrix(l.w, l.out, l.in, l.row_bytes) + resultMatrix:matrix(gemm_result_, rows, l.out, out_bytes)]; + finish_op(); + dispatch("linear_store_half", {u(rows * l.out), u(l.out), u(out_stride), l.b.buffer ? 1u : 0u}, + {gemm_result_, l.b.buffer ? l.b : l.w, out}); + return; + } [gemm encodeToCommandBuffer:command() leftMatrix:matrix(x, rows, l.in) rightMatrix:matrix(l.w, l.out, l.in) resultMatrix:matrix(out, rows, l.out)]; finish_op(); @@ -390,7 +461,14 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, std::vector shape) { if (!hook) return; flush(); - (*hook)(key, t.data(), shape); + if (t.element_size == sizeof(float)) (*hook)(key, t.data(), shape); + else { + size_t count = 1; + for (int64_t n : shape) count *= n; + std::vector values(count); + t.read(values.data(), count); // diagnostic upcast; production computation remains on the GPU + (*hook)(key, values.data(), shape); + } } void MetalBackend::run(const float* x, float* y, const ActivationHook* hook) { @@ -410,7 +488,7 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, for (int64_t row = 0; row < G_; row += chunk_) { const int64_t n = std::min(chunk_, G_ - row); linear(enc_src_, features.sub(row * F_), n, embed); - if (hook) { flush(); std::memcpy(enc_full.data() + row * C_, embed.data(), n * C_ * sizeof(float)); } + if (hook) { flush(); embed.read(enc_full.data() + row * C_, n * C_); } source(enc_, embed, n, row); if (hook) flush(); } @@ -448,8 +526,8 @@ void report(const ActivationHook* hook, const std::string& key, const Tensor& t, linear(out_proj_, ln_, n, decoded.sub(row * Vo)); if (hook) flush(); if (hook) { - std::memcpy(dec_embed.data() + row * C_, embed.data(), n * C_ * sizeof(float)); - std::memcpy(dec_block.data() + row * C_, block.data(), n * C_ * sizeof(float)); + embed.read(dec_embed.data() + row * C_, n * C_); + block.read(dec_block.data() + row * C_, n * C_); } } if (hook) { diff --git a/src/varda/metal/kernels.metal b/src/varda/metal/kernels.metal index fba9fa3..f38d4b1 100644 --- a/src/varda/metal/kernels.metal +++ b/src/varda/metal/kernels.metal @@ -2,12 +2,39 @@ using namespace metal; #pragma clang fp contract(off) +#ifdef VARDA_METAL_FP16 +using Activation = half; +#else +using Activation = float; +#endif + // Matches Args in backend_metal.mm. All indexing is checked to fit uint at load. struct Args { uint n, a, b, c, d, e, f, g; float x, y; }; +// Dense mixed precision uses padded half operands and a float result. In +// particular, never request an all-half MPS GEMM: its intermediate range can +// overflow even when cancellation would leave a representable final result. +kernel void pack_half_from_float(device const float* in [[buffer(0)]], device half* out [[buffer(1)]], + constant Args& p [[buffer(8)]], uint i [[thread_position_in_grid]]) { + if (i < p.n) out[i] = i % p.b < p.a ? half(in[(i / p.b) * p.a + i % p.b]) : half(0); +} +kernel void pack_half_from_half(device const half* in [[buffer(0)]], device half* out [[buffer(1)]], + constant Args& p [[buffer(8)]], uint i [[thread_position_in_grid]]) { + if (i < p.n) out[i] = i % p.b < p.a ? in[(i / p.b) * p.a + i % p.b] : half(0); +} +kernel void linear_store_half(device const float* in [[buffer(0)]], device const half* bias [[buffer(1)]], + device half* out [[buffer(2)]], constant Args& p [[buffer(8)]], + uint i [[thread_position_in_grid]]) { + if (i < p.n) { + float value = in[(i / p.a) * p.b + i % p.a]; + if (p.c) value += float(bias[i % p.a]); + out[i] = half(value); // one rounding after fp32 accumulation and bias + } +} + kernel void normalise(device const float* in [[buffer(0)]], device const float* mul [[buffer(1)]], device const float* add [[buffer(2)]], device float* out [[buffer(3)]], constant Args& p [[buffer(8)]], uint i [[thread_position_in_grid]]) { @@ -28,13 +55,13 @@ kernel void bias_add(device float* out [[buffer(0)]], device const float* bias [ if (i < p.n) out[i] = out[i] + bias[i % p.a]; } -kernel void add_arrays(device const float* a [[buffer(0)]], device const float* b [[buffer(1)]], - device float* out [[buffer(2)]], constant Args& p [[buffer(8)]], +kernel void add_arrays(device const Activation* a [[buffer(0)]], device const Activation* b [[buffer(1)]], + device Activation* out [[buffer(2)]], constant Args& p [[buffer(8)]], uint i [[thread_position_in_grid]]) { - if (i < p.n) out[i] = a[i] + b[i]; + if (i < p.n) out[i] = float(a[i]) + float(b[i]); } -kernel void copy_array(device const float* in [[buffer(0)]], device float* out [[buffer(1)]], +kernel void copy_array(device const Activation* in [[buffer(0)]], device Activation* out [[buffer(1)]], constant Args& p [[buffer(8)]], uint i [[thread_position_in_grid]]) { if (i < p.n) out[i] = in[i]; } @@ -42,8 +69,8 @@ kernel void copy_array(device const float* in [[buffer(0)]], device float* out [ // One SIMD group per row, including widths that are not multiples of its size. // Metal has no fp64: center on a common origin before compensated fp32 moments, // then normalize centered values directly to avoid cancellation in x*rstd+shift. -kernel void layernorm(device const float* in [[buffer(0)]], device const float* w [[buffer(1)]], - device const float* b [[buffer(2)]], device float* out [[buffer(3)]], +kernel void layernorm(device const Activation* in [[buffer(0)]], device const float* w [[buffer(1)]], + device const float* b [[buffer(2)]], device Activation* out [[buffer(3)]], constant Args& p [[buffer(8)]], uint tid [[thread_position_in_grid]], uint lane [[thread_index_in_simdgroup]], uint simd_width [[threads_per_simdgroup]]) { uint row = tid / simd_width; @@ -79,7 +106,7 @@ float erf_fp32(float x) { return copysign(1.0f - q * exp(-a * a), x); } -kernel void gelu(device float* values [[buffer(0)]], constant Args& p [[buffer(8)]], +kernel void gelu(device Activation* values [[buffer(0)]], constant Args& p [[buffer(8)]], uint i [[thread_position_in_grid]]) { if (i >= p.n) return; float v = values[i]; @@ -91,19 +118,19 @@ kernel void gelu(device float* values [[buffer(0)]], constant Args& p [[buffer(8 } } -float edge_value(device const float* attrs, device const float* w, device const float* b, +float edge_value(device const Activation* attrs, device const Activation* w, device const Activation* b, uint edge, uint channel, constant Args& p) { - float value = attrs[edge * p.d] * w[channel * p.d]; - for (uint a = 1; a < p.d; ++a) value += attrs[edge * p.d + a] * w[channel * p.d + a]; - return p.e ? value + b[channel] : value; + float value = float(attrs[edge * p.d]) * float(w[channel * p.d]); + for (uint a = 1; a < p.d; ++a) value += float(attrs[edge * p.d + a]) * float(w[channel * p.d + a]); + return float(Activation(p.e ? value + float(b[channel]) : value)); } // One score per (edge, head). This stores E*heads values, never an E*channels // projected-edge tensor. d0 and nd restrict the dispatch to complete CSR rows. -kernel void attention_scores(device const float* q [[buffer(0)]], device const float* k [[buffer(1)]], +kernel void attention_scores(device const Activation* q [[buffer(0)]], device const Activation* k [[buffer(1)]], device const int* sources [[buffer(2)]], device const int* dests [[buffer(3)]], - device const float* attrs [[buffer(4)]], device const float* w [[buffer(5)]], - device const float* b [[buffer(6)]], device float* scores [[buffer(7)]], + device const Activation* attrs [[buffer(4)]], device const Activation* w [[buffer(5)]], + device const Activation* b [[buffer(6)]], device float* scores [[buffer(7)]], constant Args& p [[buffer(8)]], uint i [[thread_position_in_grid]]) { if (i >= p.n) return; uint edge = p.g + i / p.b, head = i % p.b; @@ -114,12 +141,12 @@ kernel void attention_scores(device const float* q [[buffer(0)]], device const f for (uint j = 0; j < 8; ++j) { uint channel = offset + c + j; float e = edge_value(attrs, w, b, edge, channel, p); - acc[j] += q[dst * p.a + channel] * (k[src * p.a + channel] + e); + acc[j] += float(q[dst * p.a + channel]) * (float(k[src * p.a + channel]) + e); } float sum = ((acc[0]+acc[1])+(acc[2]+acc[3])) + ((acc[4]+acc[5])+(acc[6]+acc[7])); for (; c < p.c; ++c) { uint channel = offset + c; - sum += q[dst * p.a + channel] * (k[src * p.a + channel] + edge_value(attrs,w,b,edge,channel,p)); + sum += float(q[dst * p.a + channel]) * (float(k[src * p.a + channel]) + edge_value(attrs,w,b,edge,channel,p)); } scores[edge * p.b + head] = sum / sqrt(float(p.c)); } @@ -141,22 +168,22 @@ kernel void attention_softmax(device const int* rows [[buffer(0)]], device float for (int e = lo; e < hi; ++e) scores[uint(e) * p.b + head] /= sum; } -kernel void attention_values(device const float* v [[buffer(0)]], device const int* rows [[buffer(1)]], - device const int* sources [[buffer(2)]], device const float* attrs [[buffer(3)]], - device const float* w [[buffer(4)]], device const float* b [[buffer(5)]], - device const float* scores [[buffer(6)]], device float* out [[buffer(7)]], +kernel void attention_values(device const Activation* v [[buffer(0)]], device const int* rows [[buffer(1)]], + device const int* sources [[buffer(2)]], device const Activation* attrs [[buffer(3)]], + device const Activation* w [[buffer(4)]], device const Activation* b [[buffer(5)]], + device const float* scores [[buffer(6)]], device Activation* out [[buffer(7)]], constant Args& p [[buffer(8)]], uint i [[thread_position_in_grid]]) { if (i >= p.n) return; uint dst = p.f + i / p.a, channel = i % p.a, head = channel / p.c; float sum = 0; for (int e = rows[dst]; e < rows[dst + 1]; ++e) { - float value = v[uint(sources[e]) * p.a + channel] + edge_value(attrs,w,b,uint(e),channel,p); + float value = float(v[uint(sources[e]) * p.a + channel]) + edge_value(attrs,w,b,uint(e),channel,p); sum += value * scores[uint(e) * p.b + head]; } out[i] = sum; // also defines zero-in-degree destinations } -kernel void residual(device const float* in [[buffer(0)]], device const float* dec [[buffer(1)]], +kernel void residual(device const float* in [[buffer(0)]], device const Activation* dec [[buffer(1)]], device const int* ins [[buffer(2)]], device const int* outs [[buffer(3)]], device float* out [[buffer(4)]], constant Args& p [[buffer(8)]], uint row [[thread_position_in_grid]]) { diff --git a/src/varda/model.cpp b/src/varda/model.cpp index db264be..2340b1b 100644 --- a/src/varda/model.cpp +++ b/src/varda/model.cpp @@ -66,8 +66,6 @@ std::unique_ptr Model::load(const std::string& path, const Options& opts) #endif } else if (opts.device == Device::Metal) { #ifdef VARDA_WITH_METAL - if (opts.precision != Precision::FP32) - throw std::runtime_error("the Metal backend runs fp32 only"); m->backend_ = make_metal_backend(m->cfg_, *m->file_, opts); #else throw std::runtime_error("varda.cpp was built without Metal (VARDA_METAL=OFF)"); diff --git a/tests/metal/test_metal_kernels.mm b/tests/metal/test_metal_kernels.mm index 1c74b94..9bfc971 100644 --- a/tests/metal/test_metal_kernels.mm +++ b/tests/metal/test_metal_kernels.mm @@ -24,7 +24,7 @@ Result layernorm_case(id device, id queue, id pipeline, int channels, int rows, - int pattern, bool bias, std::mt19937& rng) { + int pattern, bool bias, bool half, std::mt19937& rng) { std::normal_distribution normal(0, 1); const size_t count = size_t(channels) * rows; std::vector x(count), w(channels), b(channels); @@ -40,6 +40,7 @@ Result layernorm_case(id device, id queue, w[c] = 0.5f + std::abs(normal(rng)); b[c] = normal(rng) * 0.2f; } + if (half) for (float& v : x) v = float(_Float16(v)); const Args args{uint32_t(rows), uint32_t(channels), uint32_t(bias)}; std::vector reference(count); for (int r = 0; r < rows; ++r) { @@ -56,17 +57,25 @@ Result layernorm_case(id device, id queue, std::sqrt(variance + args.x) * w[c] + (bias ? b[c] : 0); } - auto upload = [&](const std::vector& v) { + auto upload = [&](const std::vector& v, bool use_half = false) { + if (use_half) { + std::vector<_Float16> packed(v.begin(), v.end()); + return [device newBufferWithBytes:packed.data() length:packed.size() * sizeof(_Float16) + options:MTLResourceStorageModeShared]; + } return [device newBufferWithBytes:v.data() length:v.size() * sizeof(float) options:MTLResourceStorageModeShared]; }; - id input = upload(x), weight = upload(w), offset = upload(b); - id output = [device newBufferWithLength:(count + 32) * sizeof(float) + id input = upload(x, half), weight = upload(w), offset = upload(b); + const size_t element_size = half ? sizeof(_Float16) : sizeof(float); + id output = [device newBufferWithLength:(count + 32) * element_size options:MTLResourceStorageModeShared]; if (!input || !weight || !offset || !output) throw std::runtime_error("Metal test allocation failed"); - float* values = static_cast(output.contents); - constexpr float guard = 1234567.0f; - std::fill_n(values, count + 32, guard); + const float guard = half ? float(_Float16(12345)) : 1234567.0f; + if (half) std::fill_n(static_cast<_Float16*>(output.contents), count + 32, _Float16(guard)); + else std::fill_n(static_cast(output.contents), count + 32, guard); + auto value = [&](size_t i) { return half ? float(static_cast<_Float16*>(output.contents)[i]) : + static_cast(output.contents)[i]; }; id command = [queue commandBuffer]; id encoder = [command computeCommandEncoder]; if (!command || !encoder) throw std::runtime_error("Metal test encoding failed"); @@ -74,7 +83,7 @@ Result layernorm_case(id device, id queue, [encoder setBuffer:input offset:0 atIndex:0]; [encoder setBuffer:weight offset:0 atIndex:1]; [encoder setBuffer:offset offset:0 atIndex:2]; - [encoder setBuffer:output offset:16 * sizeof(float) atIndex:3]; + [encoder setBuffer:output offset:16 * element_size atIndex:3]; [encoder setBytes:&args length:sizeof(args) atIndex:8]; const NSUInteger simd = pipeline.threadExecutionWidth; const NSUInteger width = std::min(256, pipeline.maxTotalThreadsPerThreadgroup) / simd * simd; @@ -88,12 +97,12 @@ Result layernorm_case(id device, id queue, double scale = 0, error = 0; bool valid = true; for (size_t i = 0; i < count; ++i) { - valid &= std::isfinite(values[i + 16]); + valid &= std::isfinite(value(i + 16)); scale = std::max(scale, std::abs(reference[i])); - error = std::max(error, std::abs(double(values[i + 16]) - reference[i])); + error = std::max(error, std::abs(double(value(i + 16)) - reference[i])); } for (int i = 0; i < 16; ++i) - valid &= values[i] == guard && values[count + 16 + i] == guard; + valid &= value(i) == guard && value(count + 16 + i) == guard; return {scale > 0 ? error / scale : error, error, valid}; } } // namespace @@ -123,34 +132,40 @@ int main() { options.fastMathEnabled = NO; #endif options.languageVersion = MTLLanguageVersion2_3; - NSError* error = nil; - id library = [device newLibraryWithSource:[NSString stringWithUTF8String:varda::metal::kernel_source] - options:options error:&error]; - if (!library) throw std::runtime_error(error.localizedDescription.UTF8String); - id pipeline = [device newComputePipelineStateWithFunction: - [library newFunctionWithName:@"layernorm"] error:&error]; - if (!pipeline) throw std::runtime_error(error.localizedDescription.UTF8String); + int failures = 0; + for (bool half : {false, true}) { + NSError* error = nil; + const std::string source = std::string(half ? "#define VARDA_METAL_FP16\n" : "") + varda::metal::kernel_source; + id library = [device newLibraryWithSource:[NSString stringWithUTF8String:source.c_str()] + options:options error:&error]; + if (!library) throw std::runtime_error(error.localizedDescription.UTF8String); + id pipeline = [device newComputePipelineStateWithFunction: + [library newFunctionWithName:@"layernorm"] error:&error]; + if (!pipeline) throw std::runtime_error(error.localizedDescription.UTF8String); - std::mt19937 rng(731); - int cases = 0, failures = 0; - double worst = 0, worst_abs = 0; - for (int channels : {1, 7, 31, 32, 33, 35, 63, 64, 65, 255, 256, 257, 768, 1024, 2048, 4097}) - for (int rows : {1, 9, 37}) - for (int pattern = 0; pattern < 4; ++pattern) - for (bool bias : {false, true}) { - @autoreleasepool { - const Result r = layernorm_case(device, queue, pipeline, channels, rows, pattern, bias, rng); - ++cases; - if (r.rel > worst) { worst = r.rel; worst_abs = r.abs; } - if (!r.valid || r.rel > 1e-5) { - ++failures; - std::printf("FAIL C=%d rows=%d pattern=%d bias=%d rel_absmax=%.3e max_abs=%.3e\n", - channels, rows, pattern, int(bias), r.rel, r.abs); + std::mt19937 rng(731); + int cases = 0, mode_failures = 0; + const double tolerance = half ? 3e-3 : 1e-5; + double worst = 0, worst_abs = 0; + for (int channels : {1, 7, 31, 32, 33, 35, 63, 64, 65, 255, 256, 257, 768, 1024, 2048, 4097}) + for (int rows : {1, 9, 37}) + for (int pattern = 0; pattern < 4; ++pattern) + for (bool bias : {false, true}) { + @autoreleasepool { + const Result r = layernorm_case(device, queue, pipeline, channels, rows, pattern, bias, half, rng); + ++cases; + if (r.rel > worst) { worst = r.rel; worst_abs = r.abs; } + if (!r.valid || r.rel > tolerance) { + ++mode_failures; + std::printf("FAIL C=%d rows=%d pattern=%d bias=%d rel_absmax=%.3e max_abs=%.3e\n", + channels, rows, pattern, int(bias), r.rel, r.abs); + } } } - } - std::printf("%s fp32 LayerNorm: %d cases, %d failures; worst rel_absmax %.3e max_abs %.3e tol 1e-5\n", - device.name.UTF8String, cases, failures, worst, worst_abs); + std::printf("%s %s LayerNorm: %d cases, %d failures; worst rel_absmax %.3e max_abs %.3e tol %.1e\n", + device.name.UTF8String, half ? "fp16" : "fp32", cases, mode_failures, worst, worst_abs, tolerance); + failures += mode_failures; + } return failures ? 1 : 0; } catch (const std::exception& e) { std::fprintf(stderr, "%s\n", e.what()); diff --git a/tests/run_synthetic.sh b/tests/run_synthetic.sh index 69eb5c8..edc1d2c 100755 --- a/tests/run_synthetic.sh +++ b/tests/run_synthetic.sh @@ -14,7 +14,8 @@ # SKIP_CUDA=1 forces the CUDA part to be skipped (it is also skipped, with a note, when # no GPU is visible). # Runs per model: CPU fp32 at 1 and 8 threads, CPU fp32 with VARDA_CPU_CHUNK_ROWS=37 (8 -# threads); CUDA fp32, CUDA fp32 with VARDA_DEC_CHUNK_ROWS=128, CUDA fp16. +# threads); CUDA fp32, CUDA fp32 with VARDA_DEC_CHUNK_ROWS=128, CUDA fp16. Metal +# fp32 and mixed fp16 each run with default chunking and VARDA_METAL_CHUNK_ROWS=37. # Prints a summary (worst rel_absmax and ratio to the tolerance per run) and exits non-zero # if any run fails or errors. The varda-parity check includes the hook-inertness check. set -u @@ -115,6 +116,8 @@ for m in $MODELS; do if [ "$have_metal" = 1 ]; then run "$m" metal-fp32 synthetic-fp32 "" --device metal --precision fp32 run "$m" metal-fp32-chunk37 synthetic-fp32 "VARDA_METAL_CHUNK_ROWS=37" --device metal --precision fp32 + run "$m" metal-fp16 synthetic-fp16 "" --device metal --precision fp16 + run "$m" metal-fp16-chunk37 synthetic-fp16 "VARDA_METAL_CHUNK_ROWS=37" --device metal --precision fp16 fi ;; esac done diff --git a/varda b/varda index 4c1e294..190ccd8 100755 --- a/varda +++ b/varda @@ -82,7 +82,7 @@ cmd_setup() { die "the build has no varda-forecast: ecCodes not found? set ECCODES_HOME (log: $BUILD/varda-build.log)" if ! grep -q '^CMAKE_CUDA_COMPILER:.*nvcc' "$BUILD/CMakeCache.txt"; then if [[ -x "$BUILD/varda-metal-info" ]]; then - say "note: built without CUDA; Metal enabled (--device metal --precision fp32)" + say "note: built without CUDA; Metal enabled (--device metal --precision fp32|fp16)" else say "note: built without CUDA (no nvcc found): only --device cpu will work" fi @@ -154,9 +154,6 @@ cmd_forecast() { done case "$precision" in fp16|fp32) ;; *) die "--precision must be fp16 or fp32" ;; esac case "$device" in cuda|cpu|metal) ;; *) die "--device must be cuda, cpu or metal" ;; esac - if [[ "$device" == metal && "$precision" != fp32 ]]; then - die "the Metal backend runs fp32 only: pass --precision fp32" - fi if [[ -n "$lead" ]]; then case "$lead" in *d) lead=$(( ${lead%d} * 24 )) ;;