Anees Iqbal d1eb2b8ccd Merge a run of passes over one linear attachment once, after its last pass
A linear attachment rendered apart (a texture over a buffer's bytes beside a depth or stencil
attachment on NVIDIA, VK_NV_linear_color_attachment's rule) copied its box into the kept image,
kept it, rendered, and merged the changed words back, every pass, each step between barriers
from every command to every command. A WebGPU frame split at every indexed draw (stencilprobe
-P: 706 passes over one surface in one command buffer) paid that 706 times.

Now consecutive passes over one attachment form a run (linear_run.rs) under a conservative rule:
the run's first pass copies in and keeps as before; each later pass whose box lies in the run's
renders over what the pass before left in the kept image, with no copy in and no keep; and each
pass leaves its merge to its batch's submission (Deferred::LinearMerge, a segment after its own
command buffers), which the next pass of the run takes over, so only the last pass's merge is
recorded, in that pass's place, between the same barriers. The merge compares the first keep
with the image the last pass left, so it writes every word one of the passes changed. Its uses
are noted as each pass ends (EncoderCore::note_left_uses), so the tracker orders later work
after a write of the bytes as before.

A run ends (its merge recorded where its last pass left it, its scratch lent on) at:
- any encoder between its passes but a render encoder (blit, compute, resource state);
- a render encoder whose commands name the surface's buffer or its host range, reach memory they
  do not name (root or handle tables, heaps, executions, a barrier inside the pass), wait for or
  update a fence, resolve, write visibility results, record later (pending draws, tile
  dispatches, later color groups), or that attaches those bytes or renders that kept image;
- an event or semaphore wait or signal, or a host step (any new batch, RunPoint);
- a pass whose box reaches past the run's (the next run then covers the whole render area);
- the command buffer's end.
A pass joins only where it is encoded once: neither its commands nor its attachments name a
buffer over host pages (which a rebind encodes again), no rasterization-rate map, no execution,
outside a predicated loop's laying. An encoder encoded again changes no run, and its linear
merges borrow no scratch from the pool, since its place may lie inside a run's span. The 1x1
attachmentless encoders of stencilprobe -P name nothing of the surface and pass a run.

LinearMerge::lend is now once only (a run's merge is lent when the run ends). Counted:
WorkCounts::linear_merges_recorded and linear_merges_taken_over (new; api_signatures blessed).

Touched pass-end and submission code (kept small): render.rs end_pass (the run decision before
the copies in, the keep skipped for a pass going on, the merge left to submission),
encoder.rs (RecordedSegment::submitted, note_left_uses, encodes_again), command_buffer/submit.rs
record_scrubs (records a run's merge, a taken-over one records nothing), deferred.rs (the
variant), command_buffer/mod.rs (State::run_point, linear_runs), tracker.rs (EncoderUses::fenced).

Tests (device, --cfg m2v_gpu):
- tests::linear_runs (runtime crate, new): one command buffer of 26 steps over a linear target
  (Shared and Private buffers, packed rows of 1024 bytes), the rule forced: passes over it beside
  a cleared depth attachment, 1x1 attachmentless encoders, passes over another texture, a pass
  binding the target's buffer, blits reading its texels mid-sequence, an event signal, and a
  pass whose box reaches past its run's. 17 passes, 7 runs: 7 merges recorded and 10 taken
  over; with a blit between every two encoders (every pass merging after itself) 17 and 0; the
  texels each blit read and those left at the end equal a private texture's under the same
  steps, both ways. Passed on the M3 Max (MoltenVK 1.4.2) and the RTX 5080 Laptop GPU.
- tests::merge_scratch (runtime crate): 240 passes over Shared and Private targets now one run
  each on both devices (1 merge recorded, 239 taken over, one scratch made); texels equal the
  private texture's. Passed on the M3 and the 5080 (8/8 with the next commit's test).
- Negative control (this tree with the run decision off, run_point always None, on the M3):
  both linear_runs tests fail (17 merges recorded, 7 expected) and the three linear
  merge_scratch cases fail (240 recorded).
- runtime_lane::linear_attachments::many_passes_* (validation): assertions moved to runs.
- clippy --all-targets --all-features -D warnings, plain and --cfg m2v_gpu (runtime and
  validation); the runtime's plain unit tests (1213 passed); api_surface and api_signatures.

Measured:
RTX 5080 Laptop GPU (msi-laptop, release, the stencilprobe -P harness: one command buffer, a
clearing pass and 706 passes loading colour and stencil beside a Depth32Float_Stencil8
attachment, a 1x1 attachmentless encoder between them, 1400 encoders; target over a Private
buffer, 1024x1024 BGRA8Unorm, rows 4096; three runs a process; SCHED_OTHER under the GPU locks),
base 896214a5b0 against this commit: commit to completion 81.9, 74.4, 71.2 ms before; 18.1,
11.2, 9.5 ms after (3 runs then 1 run a command buffer: 3 then 1 merge recorded, 703 then 705
taken over); encoding 63.0, 22.5, 21.2 ms before, 50.2, 19.5, 19.1 ms after. The M3 renders
this target in place (no rule), so it has no such passes to measure.

(cherry picked from commit 5d2b237e1a561153b3bcce58c459768e2a83e38a)
(cherry picked from commit 0bf36f1a1cad63fe37da128db30d86580fcd4528)
2026-11-03 11:48:35 -08: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%