Anees Iqbal fee371002c Copy only a logged host-page shadow's changed rows: HostMemory::with_dirty_pages
The dirty-page API (HostMemory::with_dirty_pages, DirtyPages, DirtyStamp) and the shadow path
that uses it: a tracked 2D texture's shadow over logged host pages copies in only the changed
row bands, at most one wait per log, whole where nothing earlier can be counted on.

One work packet, landed as 7 commit(s) (7a712be4b2..576768df43 on archive/development-linear-2026-10-28-evening), in order:

* API: HostMemory::with_dirty_pages, DirtyPages and DirtyStamp

Shape against the archive (archive/development-performance-2026-10-27,
crates/metal2vulkan-api/src/host_memory.rs): the trait is the archive's,
item for item (type Watch: Send + Sync; watch, request, wait, changed,
wrote, and wrote_as and changed_except defaulting to the plain ones), and
DirtyStamp(pub u64) is the same. Two differences:
- with_dirty_pages is generic, not `Arc<dyn DirtyPages>`:
  `pub fn with_dirty_pages<D>(self, source: Arc<D>) -> HostMemory
   where D: DirtyPages + ?Sized + 'static, D::Watch: 'static`.
  The associated Watch type keeps `dyn DirtyPages` from naming a type on
  its own; the archive solved that with HostMemory's associated type
  (`type DirtyPages: DirtyPages`), and a generic parameter is that on
  today's struct. A caller passes `Arc<MyLog>`, or a trait object that
  names its watch, `Arc<dyn DirtyPages<Watch = W>>`. The runtime boxes
  the watches inside.
- offsets are bytes from the memory's pointer (HostMemory::pointer), as
  the archive's runtime crate had them, not from a region: today's
  runtime names no regions. A page starting before the pointer is
  reported from 0; ranges past the bytes the runtime reads are cut.

What: the public trait and stamp (crates/metal2vulkan-runtime/src/
dirty_pages.rs, exported at the crate root), the HostMemory builder that
keeps the source, the runtime README's runtime-extension entry, and the
signature table (scripts/api-signatures --bless: 11 records). No
refusal changes (docs/REFUSALS.md unchanged). The runtime keeps the
source and calls nothing yet: the copy paths that use it follow, one
commit each.

Why: reims-vgpu codes its QEMU dirty-log source against this surface
now (owner-ordered round, 2026-10-28).

Verified: cargo fmt; cargo clippy -p metal2vulkan-runtime --all-targets
--all-features -D warnings; RUSTDOCFLAGS=-D warnings cargo doc -p
metal2vulkan-runtime --all-features --no-deps (on macOS).

* Copy a logged shadow's changed row bands in, leaving out its own copies back

READY: the texture-shadow copy-in path over logged host pages
(HostMemory::with_dirty_pages): a tracked 2D texture's shadow over a
no-copy buffer's pages (a surface's render target over guest pages
among them, dma-buf imports included) copies in only the full-width
row bands of the pages the log reports changed, and its own copy back
or merge is reported with wrote_as and left out of its copies in
through changed_except.

What:
- dirty_pages.rs: the source as the pages keep it (its pointer, a cache
  of the latest publication a wait found), a log per shadow (its writer,
  where its truth lies in the source, a watch over those bytes for the
  shadow's life, and its hold: the stamp as of which its image held
  every texel), the gate of each copy in, and the commit's bookkeeping.
- At a command buffer's commit, in commit order: each gated copy in
  takes its shadow's hold as it stands and a stamp (request, one per
  source and commit); the commit's writes (every command's write uses,
  noted where EncoderCore tracks them, the shadows' copies too) let go
  of the holds of the shadows they meet; the shadows its end leaves
  holding every texel, none stale (its final ShadowCarry), hold from
  the stamp on. A copy in after a write of the truth or the shadow in
  the same command buffer takes every row.
- The recorder logs a gated copy (Logged::GatedCopyBufferToImage); its
  replay, after the commit, waits for the stamp and asks
  changed_except(hold, writer): no hold or a wait answering false
  copies every region; else the changed byte runs become full-width row
  bands (merged 8 rows apart or less), every row at half the rows or
  more or past 1024 bands, nothing where nothing changed. A command
  buffer recorded straight into a driver's command buffer copies every
  region.
- Copies back and merges into logged pages are reported wrote_as at the
  commit; a replaceRegion of a texture over logged pages is reported
  wrote (the runtime's own CPU write, which the guest's log never sees).
- Gated only: a First copy in of every texel (or a rectangle covering
  every texel) of a tracked 2D texture's image straight from the
  buffer's pages (no staging buffer). Every other copy takes every byte
  as before. The tracker orders the gated copy as it ordered the whole
  one: the barriers are unchanged, only the regions shrink.
- WorkCounts::dirty_copies_in_gated, _whole, _skipped,
  dirty_copy_in_bytes_whole, dirty_copy_in_bytes_copied (signature
  table blessed: 5 records).

Why: reims-vgpu's 780M and RTX 5080 frames copy a 1920x1080 BGRA8
surface's shadow in whole before each use and back after each write;
most of each frame's copy was the shadow's own echo.

Verified (M3 Max, MoltenVK, RUSTFLAGS=--cfg m2v_gpu):
tests::dirty_pages_device::a_logged_shadow_copies_in_only_the_changed_rows
passes. A 64x64 RGBA8 shadow over logged pages, read by a kernel:
frame 1 copies 16384 of 16384 bytes; frame 2 (row 10 told to the log,
row 40 written but not told) copies 256 bytes, row 10 reads new, row 40
reads old (proof the skip happened); frame 3 skips (0 bytes); frame 4
(wait answers false) copies 16384, row 40 arrives; frame 5 writes
through the shadow, its merge reported wrote_as(writer 1); frame 6
copies 0 bytes, changed_except asked for writer 1. cargo clippy
-p metal2vulkan-runtime --all-targets --all-features -D warnings,
plain and --cfg m2v_gpu; rustdoc -D warnings.

* Report a logged shadow's copies back again at completion, and drop a failed commit's holds

What: a command buffer's completion reports its shadows' copies back
and merges into logged host pages to the log again (wrote_as, the
shadow its writer), now the GPU wrote them: a stamp asked between the
commit and the write still finds them. Where the command buffer
failed, the holds its gated copies in set are let go of (their copies
may not have run), so the next copy in takes every row.

Why: the commit's report alone stamps the pages before the GPU writes
them; the consumer's other readers of the pages (its own copies, other
devices) asking after that stamp would miss the write.

Verified (M3 Max, --cfg m2v_gpu): tests::dirty_pages_device passes,
frame 5 now reports writer 1 twice (commit and completion) and the
test asserts it; clippy -D warnings plain and --cfg m2v_gpu.

* Copy a logged shadow in whole, never cut to a pass's scissors, so it holds for the next frame

READY: render targets over logged guest pages loaded by passes whose
draws' scissors bound them (partial damage) now take the gated copy:
only the changed row bands of the whole surface, and the image keeps
every texel for the next command buffer's copy.

What: ShadowSync::before takes every texel as what a command needs of
a tracked shadow whose truth lies in logged host pages
(ShadowCopies::logged), where it cut the copy in to the rectangle the
draws' scissors bound. A cut copy in was never gated (the gate takes a
copy of every texel) and left the image holding a rectangle alone, so
no hold formed and every frame copied its rectangle whole. Whole, the
copy moves only the bands the log reports changed (first copy aside),
and the command buffer's end leaves it holding every texel.

Why: reims-vgpu's composited surfaces are drawn in damage rectangles.

Verified (M3 Max, --cfg m2v_gpu):
tests::dirty_pages_device::a_logged_render_target_loaded_in_a_scissor_copies_only_the_changed_rows:
a 64x64 RGBA8 render target over logged pages, a Load pass drawing in
a scissor of rows 0..8: frame 1 gated, 16384 bytes; frame 2 (row 40
told) 256 bytes, row 40 keeps the CPU's bytes, row 0 the new draw;
frame 3 skipped (its own copy back of rows 0..8 left out). Negative
control: without the change, frame 1 counts 0 gated copies and the
test fails. The first test still passes; clippy -D warnings plain and
--cfg m2v_gpu.

* Count a logged shadow's copy in on no hold where its command buffer waits for an event

What: a command buffer that waits for an event or a binary semaphore
(any batch's waits) takes no hold for its gated copies in: they copy
every row. Work committed after it (the event's signaler) may run
before it, and that work's writes of the truth are noted only at its
own later commit, so a hold read at this commit could miss them.

Verified (M3 Max, --cfg m2v_gpu): tests::dirty_pages_device frame 7, a
command buffer waiting for a shared event already signaled, copies
16384 of 16384 bytes (whole); both device tests pass; clippy -D
warnings plain and --cfg m2v_gpu. gem10 at addefbec27 (the commit
before): the two dirty-page device tests pass on the RX 7900 XTX and
the Radeon 780M with the M3's numbers; of the related set (shadow,
host_memory, dirty, dma_buf, rebind, host_aliases: 101 tests) 99 pass
on each GPU, and the two that fail
(pending_rebind::a_pending_dispatch_records_nothing_where_a_rebind_freed_what_its_descriptors_name,
tile_rebind_making_wait::a_tile_pass_records_nothing_where_a_rebind_freed_what_its_descriptors_name)
fail on loader error messages about gem10's unloadable
libGLX_nvidia.so.0 ICD, which their layer-message check counts; both
pass on the M3.

* Wait once per log for every commit before the wait, and never again for an unanswered stamp

READY: fewer DirtyPages::wait calls on the submission path.

Where the shadow path calls the log (unchanged): request() at a command
buffer's commit, on the committing thread, once per log and commit,
only where the command buffer has a gated copy in; wait() at the
replay of its commands, just before its submission (the recorder
thread, or the submitting thread where it replays the command buffer
itself), only for a gated copy in that counts on a hold.

What changed: a replay's wait asks for the latest stamp any commit
asked of that log so far, not its own, so one harvest serves every
command buffer committed before it and their replays find it
published; a stamp at or below one the log answered false for answers
false at once (every row copied) instead of waiting again for each
gated copy in. Counted: WorkCounts::dirty_stamps_asked, dirty_waits,
dirty_waits_unanswered, dirty_wait_nanos (signature table blessed).

Why: reims-vgpu's 780M A/B on 2552bd72c9 showed 17% less GPU time per
frame but a worse interval tail (p99 79 ms against 37), pointing at
waits on the submission path.

Verified (M3 Max, --cfg m2v_gpu):
tests::dirty_pages_device::one_wait_serves_every_gated_copy_in_of_a_commit:
two shadows over one log used by one command buffer: frame 1 asks 1
stamp and waits 0 times (no hold); frame 2 asks 1 stamp, waits once,
both gated copies move nothing; frame 3, the log answering false: 1
stamp, 1 wait (false), both copies whole. The other two dirty-page
device tests pass; clippy -D warnings plain and --cfg m2v_gpu.

* Say in HostMemory::with_dirty_pages when the logged copies ask, wait and copy whole

What: with_dirty_pages's doc now states the behaviour the last commits
made: one stamp per log and commit where a gated copy in exists, one
wait per log serving every earlier commit, no wait without a hold, a
false answer not waited for again, whole copies after an event or
semaphore wait or an earlier write in the command buffer, and the copy
back reported at the commit and again at the completion.

Verified: rustdoc -D warnings; clippy -D warnings; signatures --check
(docs only).
2026-10-28 21:19:27 +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%