Anees Iqbal cdc09276f3 Emit fast-math arithmetic in the AIR's order and let the device group and fuse it
One work packet, landed as 4 commits (c81ea84c14..41bbe0f1c2 on archive/development-linear-2026-10-28), in order:

* Emit fast-math arithmetic in the AIR's order and let the device group and fuse it

What. The translator no longer reproduces Metal's compiler's grouping, pairing and fusion of
fast-math arithmetic. Each float operation is emitted in the AIR's order, decorated by its own
fast-math flags: an operation whose flags hold `contract` and `reassoc` is undecorated, so the
device's compiler may group and fuse it; every other one is `NoContraction` (an undecorated
SPIR-V operation would also allow reassociation, which a `contract`-only operation does not), and
a precise module's operations keep their order. `llvm.fmuladd` keeps its fused route: one AIR
operation, answered by the device's fused instruction.

Deleted: lower/arith/regroup.rs (648 lines), reassoc.rs (1469), contract.rs (585) and
contract/chain.rs (1204); the Folded and Fused strategies, ArithPlan's `contract` and `unrounded`
fields and select.rs's CONTRACTED read bit; output_precision's `plan` (the `unrounded` marking of
half output chains, Metal's choice of where not to round) and the plumbing that existed only for
it: LoweringInputs::half_output_lanes, the public HalfOutputLane, StageIo::half_output_lanes,
color_writes' half_output_lanes check, its cache-key hashing and codec entry; Fma::on (tests
only). Tests engine_reassoc (318), engine_regroup (134), engine_settled_sums (572), three
engine_arith tests, three half-output-lane engine_stage_io tests and the fused_sync lockstep case,
whose premises were Metal's grouping. Fixtures regroup_chain, sum_regroup, sum_regroup_precise,
fmx2_contract_fast, fmx2_contract_precise and unm_contract_chain (.metal, .ll, .air.ll, their
TOOLCHAIN lines and air_input printouts). Validation lanes sum_regroup (308) and settled_sums
(394), and the three authored cases whose expected values were Metal's fusions
(multiply-add-contraction-shapes-under-fast-math, multiply-add-contraction-flags-without-fast-math,
multiply-add-chains-under-fast-math) with their observations.

Kept: the contraction rule itself (AIR semantics); output_precision's notes (half_output_note,
note_half_output, note_extended_range_sources), which state where Metal may differ rather than
reproduce it; the F16 strategy's per-operation rounding.

The note. The existing FastMathRewrites covers it: it is now recorded where an operation's
operand comes from an operation the two operations' flags let a compiler regroup (both `reassoc`)
or fuse (a product into a sum, both `contract`), looking through negation, widening, shuffles and
element moves. No new kind. It moves from the ledger's elsewhere class to a device gap
(docs/FAST-PATHS.md row; tests::fast_paths), joins the conformance replay's NATIVE_NOTES, and the
cases' own declarations of it are gone (depth_texel_reads, half_read_nans, host_page_writes,
mesh_draws, sample_positions, snorm_tile_store, visibility, topology_classes).

New tests. tests::engine_fast_math_order: a fast `((d+c)+b)+a`, its precise twin, fast and
contract-only `a*a+c`, and a fast vector product, on every committed profile: spirv-val, no fused
instruction, one instruction per AIR operation, NoContraction exactly where the flags forbid
contraction, the interpreter's answer in the AIR's order, and the note on every form but the
precise sum. runtime_lane::kept_apart (reworks settled_sums): strict and contract-only mul-adds
store two roundings, a precise sum stores the AIR's order, a fast mul-add stores either rounding,
and the layer reports nothing.

Versions: SEMANTICS_VERSION 1900; ARTIFACT_FORMAT_VERSION 469 (StageIo lost a field).
Docs: FAST-PATHS.md, API.md (catalogue entry and policy), ARCHITECTURE.md (module map),
artifact.rs's FastMathRewrites doc. api_signatures.tsv re-blessed.

Verified (this machine unless named):
- Negative control: on the parent tree both new core tests fail (a fast sum regrouped to
  0x34000000 where the AIR order stores 0, the mul-adds fused, the product paired, no note);
  with the change they pass.
- cargo check, clippy --workspace --all-targets --all-features -D warnings, plain and with
  --cfg m2v_gpu; rustdoc -D warnings; refusal_surface --check; conformance and metal coverage
  current.
- Core tests: engine_fast_math_order, engine_arith, arith::tests, engine_stage_io,
  engine_simd*, engine_native_*, engine_metal_math, engine_fetch_*blend, engine_bicubic,
  engine_rotated_weights, engine_extended_range, engine_float_call_notes, color_write,
  api_tests, compile tests, fast_paths: 469 + 83 passed.
- The engine inventory bless (not committed) compiled every public fixture on all 19 profiles:
  43593 ok cells, each through spirv-val; only the deleted fixtures' 28 rows went.
- Conformance replay on lavapipe (linux-gate arm64): exit 0, the 723 rows are exactly
  known-gaps.tsv's, 0 unlisted.
- Validation lanes on lavapipe (linux-gate arm64, --cfg m2v_cpu_icd): kept_apart and the lanes
  that assert notice sets (blits, degrade_notices, gpu_times, half_slice_nans, heap_metal_sizes,
  heap_textures, provoking, provoking_mesh, sparse_textures, ycbcr_passes): 93 passed. llvmpipe
  kept all 4096 fast mul-adds as written and all 4096 fast sums in the AIR's order.
- kept_apart on MoltenVK (Apple M3 Max, --cfg m2v_gpu, under maclock): passed; the device's
  compiler fused 2370 of 4096 fast mul-adds and kept all 4096 fast sums in the AIR's order.
- Release CLI before and after, back to back, on the deleted and most affected fixtures over
  moltenvk-m3, gate-lavapipe, nvidia-rtx5080-laptop and intel-irisxe-anv: wall within noise
  (about 8 ms of process start, +-3 ms on a loaded host). Words: hfb_filter_bank 148284 ->
  162420 on moltenvk-m3 (half chains feeding a half output now round at each operation as the
  AIR says: +1408 OpFConvert, +1408 NoContraction; 289 OpFmaKHR became a multiply and an add),
  unm_contract_chain 33666 -> 35167, fmx2_contract_fast 18557 -> 18908, the rest within +-200.

Not in this commit: the golden tables (6028 cells move in 347 subjects, 5707 of them under an
unchanged key, 28 subjects go with the fixtures) and the engine inventory (28 rows go, none
moves) are re-blessed on development; corpus/authored-compile.tsv keeps three lines for the
deleted cases until its re-bless.

* Read 16-bit operands directly and hold half chains at float without float16

What. Two forms of `half` arithmetic that were neither the device's native one nor the fast one:

- Where a profile takes the device's 16-bit `+ - *` and `fma` (moltenvk-m3 on the measured fact,
  RADV and ANV under the 16-bit float controls), every `half` is held widened in an `f32`, so each
  16-bit operation narrowed both operands and widened its result: three conversions an operation,
  the next operation narrowing what the last had just widened. `FunctionBuilder::convert` now
  answers a narrowing of a value it widened from a 16-bit float with that float (exact), and a
  narrowing of a plain constant whose lanes are zeros, infinities or normal halves with the 16-bit
  constant; the widenings nothing else reads leave with the dead code. A rounding's own pair (a
  narrowing widened back) is never taken apart, so `narrow::rounds_by_conversion`, which decides
  `NativeHalfConversion` and the controlled modes, still sees every rounding. A chain of 16-bit
  operations is now 16-bit instructions on 16-bit values, converted only where a value enters or
  leaves it.
- Without `shaderFloat16` (vk12-floor, SwiftShader, Pascal) the module emulates `half` arithmetic
  in `float`, rounding each result by the device's quantize. New `DevicePolicy::half_chains`:
  `HalfChainPolicy::AtExits` (the default, the fast form) holds a `half` `+ - *` whose flags hold
  `contract` and `reassoc` and whose result only such operations read at `float` precision
  (`lower::arith::half_chain`), so a chain rounds where a value leaves it, one quantize per exit;
  `HalfChainPolicy::EachOperation`, which `exact_answers()` selects, rounds every operation. The
  profile carries it, so its fingerprint covers it. Recorded as `FastMathRewrites` (its doc and
  API.md's catalogue entry extended); a FAST-PATHS.md fast-default row; API.md's policy list.

The forms by profile (unchanged, for the record): moltenvk-m3 takes the measured 16-bit
arithmetic; RADV and ANV the controlled one; NVIDIA (the conversion pair folded,
`HalfConversionPairFolded`) and lavapipe (no `DenormPreserve` for 16 bits) have `shaderFloat16`
but compute `half` in `float` and round by the device's conversion pair, which this commit leaves
as it is; the profiles without `shaderFloat16` quantize.

Tests: tests::engine_fast_math_order::half_operations_read_their_16_bit_operands_directly (no
narrowing of a widened half or a constant on any profile, the rounded chain stored, some profile
takes 16-bit arithmetic) and ::half_chains_without_float16_round_at_their_exits_by_default (one
quantize against two, the held and rounded answers, both policies on every profile, distinct
fingerprints); runtime_lane::kept_apart::half_chains_without_float16_round_at_their_exits on the
device. Updated, as the conversions they counted are gone (the half agent's files, minimal):
lower::arith::tests::narrow::half_arithmetic_on_the_device_is_one_16_bit_instruction (at most two
operand narrowings), tests::engine_arith::half_rounding_follows_the_operation (the chain's
conversion count), tests::engine_arith::a_measured_half_sum_requires_the_arithmetic_fact_alone (a
kernel whose halves only the 16-bit `fma` reads widens nothing, so needs no measured widening).

Versions: SEMANTICS_VERSION 1901. ARTIFACT_FORMAT_VERSION unchanged (no encoded type changed).
api_signatures.tsv re-blessed (the enum and the field).

Words, release CLI, every module spirv-val'd (before = development 7b5cf8328d, then 622b388830,
then this commit):
- moltenvk-m3: hfb_filter_bank 148284, 162420, 140672; grd_half_many_samples 99039, 99330, 96710;
  nan_half_fast 10042, 10057, 9961.
- nvidia-rtx5080-laptop: hfb 147962, 155474, 155474; grd 110944, 111163, 111163; nan 9888, 9882,
  9882.
- gate-lavapipe: hfb 148530, 155470, 155470; grd 111018, 111163, 111163; nan 9888, 9882, 9882.
- vk12-floor: hfb 124826, 131766, 121270; grd 84482, 84627, 82019; nan 9838, 9832, 9808
  (EachOperation reproduces 622b388830's: 131766, 84627, 9832).

Verified:
- Negative controls: with the narrowing fold off, the 16-bit test fails (amd-780m-hawkpoint-radv
  narrows a widened half); with the plan off, the chain test fails (two quantizes on
  lunarg-desktop-baseline-2023). Both pass with them on.
- Core tests on this Mac: 1133 passed (arith, engine_arith, engine_native*, engine_stage_io,
  engine_fetch*, engine_simd*, spirv::*, device::*, cache::*, compile tests, api_tests,
  air_input, fast_paths, engine_fast_math_order, api_signatures, api_surface); conformance
  filtered tests 26 passed; clippy --workspace --all-targets --all-features -D warnings, plain and
  with --cfg m2v_gpu; rustdoc -D warnings; refusal_surface --check.
- The engine inventory bless (not committed) over every public fixture on all 19 profiles: only
  the deleted fixtures' 28 rows go, every other cell as before (spirv-val on each `ok`).
- runtime_lane::kept_apart on SwiftShader (linux-gate arm64, --icd swiftshader): the `fast` chain
  4096 of 4096 held under AtExits and 4096 rounded under EachOperation, the strict chain rounded
  under both; on lavapipe (whose compiler drops the undecorated conversion pairs: the `fast` chain
  4096 held under both, the strict one rounded) and on MoltenVK (Apple M3 Max, under maclock:
  every chain rounded at each sum, the 16-bit arithmetic) both tests pass.
- Lavapipe (linux-gate arm64): the conformance replay exits 0, its 763 rows exactly
  known-gaps.tsv's, 0 unlisted, the verdicts as at 622b388830; runtime_lane kept_apart,
  native_maths, half_* and degrade_notices: 28 passed. MoltenVK: the half_* lanes and
  native_maths' half rounding pass; native_maths_answers_within_its_recorded_bounds fails on
  NativeDivision (`divide::precise` records it everywhere; code this commit does not touch).

Not in this commit: the golden tables (with 622b388830, 7652 cells move in 672 subjects; 28
subjects go) and the engine inventory (28 rows go) are re-blessed on development.

* Number ARTIFACT_FORMAT_VERSION 470, after development's 469

What. development's own commit took 469 for its encoding change while this branch's first commit
took 469 for StageIo losing half_output_lanes; the rebase merged the two equal lines silently, so
two layouts shared one value. 470 keeps an artifact of either from decoding as the other.

Verified: cargo check -p metal2vulkan --all-features --all-targets on the rebased tree.

* Re-pin the runtime sources at the landing tip

The landed packet changed a runtime-sources input, so the committed digest no

longer described the sources and `the_runtime_sources_are_the_committed_ones`

would fail. Recomputed over the same inputs and committed by land-pkt.sh.
2026-10-28 17:24:22 +02:00
2026-07-22 13:15:24 +03:00

metal2vulkan

License: GPL-2.0-or-later OR LGPL-3.0-or-later

metal2vulkan runs Metal shaders and Metal programs on Vulkan. It reads Metal AIR (a metallib, or AIR bitcode) and compiles it into Vulkan pipelines, and it offers the Metal API itself on top of a Vulkan device.

Beta. The API, the command line, the pipeline JSON and the emitted SPIR-V may change during the 0.x series. Version your cached outputs.

The crates

Crate Directory What it is
metal2vulkan crates/metal2vulkan The translator. A Metal-shaped API (device, library, pipeline descriptors, binding plans) that compiles compute, render, tessellation, tile and mesh pipelines for a described Vulkan device: SPIR-V per stage, one pipeline layout, fixed-function state, and per-draw descriptor writes and push constants. The cli feature builds the metal2vulkan command.
metal2vulkan-runtime crates/metal2vulkan-runtime The Metal API on Vulkan: devices, command queues and buffers, encoders, buffers, textures, heaps, pipeline states and events, run on a Vulkan device through ash. It uses only the translator's public API.
metal2vulkan-air crates/metal2vulkan-air The AIR front end: the metallib container, the bitcode reader, a typed IR, AIR's metadata ABI, intrinsics and canonicalization. For tools that read AIR without translating it.
metal2vulkan-validation crates/metal2vulkan-validation Not published. Authored cases run on Metal and on Vulkan and compared, and bounded audits over a private corpus.
metal2vulkan-devtools crates/metal2vulkan-devtools Not published. The external-tool runner and fixture assemblers the tests share.

The three published crates share one version and are released together; metal2vulkan pins metal2vulkan-air exactly.

What the translator promises:

  • Typed refusals. Input the device cannot run exactly fails with an error that names the Metal feature and what would make it work. It never returns a module that computes something else.
  • Recorded differences. Where a pipeline gives a near-equivalent of Metal's answer, its artifact records a precision note, and the runtime announces it once with a stable code.
  • The GPU's native arithmetic. Where the device has a native form (its maths, rounding, conversions and sampler), that form gives the answer, its difference from Metal's recorded; the runtime's speed-for-accuracy choices default to the fast form, each with an opt-in exact switch (docs/FAST-PATHS.md).
  • Bounded work. Every compile runs under a deadline, a cancellation token and deterministic work and memory caps.

Install

0.2.0 is not on crates.io yet (crates.io has 0.1.0, an unrelated earlier design). Depend on a git revision:

[dependencies]
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "<sha>" }
# For the Metal API on Vulkan:
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "<sha>" }

Features of metal2vulkan, none needed by the library:

  • serde: serialization of the API's plain-data values.
  • ash: conversions to and from ash::vk, and DeviceDescription::query, which reads a physical device.
  • cli: the metal2vulkan command (enables serde).

Requirements: Rust 1.98 or newer. The libraries run no external tool. The runtime opens the Vulkan loader at run time and needs a Vulkan 1.2 device.

Command line

cargo install --git https://github.com/steelbrain/metal2vulkan metal2vulkan --features cli

The command compiles one pipeline of a metallib, an AIR bitcode module or an LLVM text module (.ll) for the device a Khronos profiles JSON describes, and writes its SPIR-V:

# A kernel: one module.
metal2vulkan library.metallib kernel.spv --profile device.json --function my_kernel

# A render pipeline: one module per stage (pipeline.vert.spv, pipeline.frag.spv).
metal2vulkan shaders.air pipeline.spv --profile device.json \
  --function vertex_main --fragment fragment_main --vertex-descriptor vertex.json \
  --color-format 0:BGRA8Unorm --depth-format Depth32Float

# The pipeline's layout, interface, dependencies and stages as JSON.
metal2vulkan kernel.ll kernel.spv --profile device.json --emit-meta kernel.json
  • --profile is required: the crate ships no device description. Any Khronos profiles JSON works; crates/metal2vulkan-validation/profiles/ has examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK.
  • Without --function it compiles the library's only kernel or vertex function. A kernel with --color-format compiles as a tile pipeline. A post-tessellation vertex function adds .tesc.spv and .tese.spv modules on a device with tessellationShader; on one without, it is the .vert.spv module itself, which draws the tessellator's triangles.
  • A compile that needs a pipeline input fails naming it and the option that supplies it: --constant ID:TYPE:VALUE for a function constant, --stage-input FILE or --vertex-descriptor FILE for a stage-input or vertex descriptor (as JSON).
  • A .ll input is assembled with llvm-as (LLVM 21 or newer). Each module written is checked with spirv-val when it is found, under the environments the library states for the device; --no-spirv-val skips it. Both tools come from PATH, or from METAL2VULKAN_LLVM_AS and METAL2VULKAN_SPIRV_VAL.
  • Success prints a line with PASS and exits 0. Failure prints metal2vulkan: FALLBACK (<why>), writes nothing, and exits 2; a failure after the inputs are read also writes a repro bundle under $TMPDIR/metal2vulkan-repros (or METAL2VULKAN_REPRO_DIR).
  • metal2vulkan --help lists every option.

Library

The flow follows Metal's object lifecycle: describe the device, parse a library, compile a pipeline, then plan and instantiate each dispatch or draw.

use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy};
use metal2vulkan::library::Library;
use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource};
use metal2vulkan::Budget;

let description = DeviceDescription::from_khronos_json(&profile_json, None)?;
let device = Device::new(description, DevicePolicy::default())?;
let library = Library::parse(&metallib_bytes)?;
let kernel = FunctionDescriptor::new(library.function("my_kernel")?);
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(kernel));
let pipeline = device.compile_compute_pipeline(&descriptor, &Budget::standard())?;
// pipeline.stage.spirv, pipeline.layout, pipeline.interface: create the Vulkan objects from these,
// then pipeline.plan(...) and plan.instantiate_dispatch(...) per dispatch.

docs/API.md walks the whole flow on a runnable example, examples/api_preview.rs:

cargo run -p metal2vulkan --example api_preview   # needs llvm-as on PATH

For the runtime, start at its README.

Documentation

Document Read it when
docs/API.md You use the translator's API: devices, libraries, pipelines, binding, caching, errors; and the runtime's degrade notices
Runtime README You use the Metal API on Vulkan
docs/HOWTO.md You integrate: tools, caching, failures, isolation, the runtime's shader cache
docs/RUNTIME-PORTING.md You port Metal calls (Objective-C or metal-rs) to the runtime
docs/FAST-PATHS.md You need every speed-for-accuracy default and its exact switch
docs/METAL-COVERAGE.md You ask whether a Metal API item is covered
docs/REFUSALS.md You ask what Metal accepts that the code refuses
docs/ARCHITECTURE.md You change the translator
docs/VALIDATION.md You check behavior against Metal
CONTRIBUTING.md You build and test the repository

The rustdoc of each crate (cargo doc --workspace --all-features --open) documents every public item; each runtime item names its Metal counterpart.

Shaders in this repository

The repository ships no third-party shaders. Tests use synthetic fixtures written for it. Passing spirv-val shows a module is valid, not that it computes what Metal computes; that claim needs the authored validation cases (docs/VALIDATION.md).

License

metal2vulkan is dual-licensed: you can redistribute it and/or modify it under the terms of either of these licenses, at your choice (LICENSE):

As an SPDX expression: GPL-2.0-or-later OR LGPL-3.0-or-later. Each published crate carries the notice and the three texts.

Metal is a trademark of Apple Inc. metal2vulkan is an independent project and is not affiliated with, sponsored by, or endorsed by Apple Inc.

S
Description
No description provided
Readme
1.7 GiB
0 Stars 1 Watchers 0 Forks
Languages
Rust 61.3%
LLVM 31.7%
Metal 3%
Objective-C 2.2%
Python 1.2%
Other 0.5%