From 697c55d5141256739ec639d611b18f2faebf9780 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 19 Oct 2026 00:15:59 +0300 Subject: [PATCH] Announce a loaded snorm or RGB9E5 attachment's kept codes, and store them as Metal's tile store does under TileStorePolicy::Exact Metal's pass, once it draws, writes each 32x32 tile a draw reaches back through its texels' values: a signed normalized channel's minimum code (-128, -32768) reads as -1.0 and is stored as the code above it, and an RGB9E5Float word whose largest mantissa is below 256 under an exponent above 0 is stored normalized. A Vulkan pass's load and store keep those bytes. What changes: - New degradation kind snorm-minimum-kept (Precision), announced at every draw and indirect execution in a pass that loads a single-sampled R8, RG8, RGBA8, R16, RG16 or RGBA16 Snorm colour attachment and keeps it, naming each such attachment. It joins shared-exponent-kept for RGB9E5. - New DevicePolicy::tile_store, TileStorePolicy { Device (default), Exact }; exact_answers() selects Exact. It is the runtime's choice alone and keys no profile. Under Exact the load pass that already rewrites extended-range, padded and bfloat attachments also takes a single-sampled snorm or RGB9E5Float attachment in the tiles the pass's draws reach, with two new bind::unused_bits_module rules (SnormMinimum, SharedExponent; the module is keyed by PixelFormat), and nothing is announced. An attachment the load pass cannot take keeps the device's load and store, announced. - New answer fact DriverFact::TileStoreIsMetals for MoltenVK 1.4.1 on Apple's GPUs: its render pass is a Metal render pass, so its tile store is Metal's for both kinds. There neither value adds a load pass or a notice. - Docs: one FAST-PATHS row for the switch, its cost the load pass's measured GPU time; a known gap for lavapipe, which states no blend for any snorm format, so a blending snorm pipeline is refused there; API.md's policy bullet and catalogue entries; the unreached-tiles-rewritten text. Why: a code no Metal write leaves, but uploaded or copied bytes may hold, reads back differently after a drawing pass. The exact form costs a copy of the render area through a dispatch before every such pass, so the device's store stays the default, announced, and Metal's store is a switch away. Verified: - Metal's behaviour probed on an M3 Max under macOS 27.0.1 (70x40 targets of five snorm formats): a pass that draws nothing moves no code; a tiny triangle moves every minimum code of its first 32x32 tile and none elsewhere; a blended full-target draw moves all of them; a blit there and back moves none. The guest's sweep showed the same on R8Snorm and RG8Snorm. - Unit tests: unused_bits (both rules against CPU models over every code, the M3's example RGB9E5 word, the masked-tile rewrite), fast_paths (the row, no profile key), driver_facts, api_surface, owned_divisions: 38 passed on gem10. - runtime_lane::snorm_tile_store under Device and Exact for both kinds, asserting load-pass counts, bytes and notices: on lavapipe with padded_loads, extended_range_blends and the notice site check, 15 passed (Exact took the load pass, Device announced); on the M3 Max under MoltenVK 1.4.1, 4 passed through the fact (no load pass, no notice) and 11 more beside them. - The load pass's cost (FAST-PATHS): on the Radeon 780M, a 1080p pass per frame of BGRA10_XR 1958.8 us against RGBA16Float's 135.3 us; the snorm and RGB9E5 cases take the same pass, not timed alone. - clippy -D warnings (plain, m2v_gpu, m2v_cpu_icd) and rustdoc. --- .../metal2vulkan-runtime/src/degradation.rs | 33 ++- .../metal2vulkan-runtime/src/owned_kernel.rs | 24 +- crates/metal2vulkan-runtime/src/render.rs | 17 ++ .../src/render/unused_bits_load.rs | 128 ++++++-- .../metal2vulkan-runtime/src/work_counts.rs | 7 +- .../src/runtime_lane.rs | 2 + .../src/runtime_lane/degrade_notices.rs | 1 + .../src/runtime_lane/snorm_tile_store.rs | 263 ++++++++++++++++ crates/metal2vulkan/src/bind/mod.rs | 9 +- crates/metal2vulkan/src/bind/unused_bits.rs | 142 ++++++++- .../src/bind/unused_bits/tests.rs | 280 ++++++++++++++---- .../metal2vulkan/src/device/driver_facts.rs | 35 +++ crates/metal2vulkan/src/device/policy.rs | 39 ++- .../src/device/tests/driver_facts.rs | 10 +- crates/metal2vulkan/src/tests/fast_paths.rs | 20 ++ .../metal2vulkan/src/tests/owned_divisions.rs | 34 ++- crates/metal2vulkan/tests/api_surface.rs | 1 + docs/API.md | 39 ++- docs/FAST-PATHS.md | 6 + 19 files changed, 951 insertions(+), 139 deletions(-) create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/snorm_tile_store.rs diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index a19974e8d..5c88ddbe4 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1119,6 +1119,29 @@ degradations! { zeros, the two-plane color word's top two bits to zeros) and clamps BGRA10_XR's \ alpha code to [384, 894]: a texel whose bytes no Metal write left (uploaded bytes, \ or an alpha code past 894) keeps bytes Metal's pass would change"; + /// A draw in a render pass that loads a single-sampled color attachment of a signed + /// normalized format (`R8Snorm`, `RG8Snorm`, `RGBA8Snorm`, `R16Snorm`, `RG16Snorm`, + /// `RGBA16Snorm`) and does not discard it at the store (`render.rs`). Metal's pass, once + /// it draws, writes each 32 x 32 tile a draw reaches back through its channels' values, + /// so a channel's minimum code (-128, or -32768), which reads as -1.0 as the code above + /// it does, is stored as that code (-127, or -32767), in the texels no fragment writes + /// too (measured on an Apple M3 Max under macOS 27.0.1: every such code of each tile a + /// draw reaches, none in other tiles, none in a pass that draws nothing or through a + /// blit), where the device's pass keeps the bytes its draws do not write. Announced at + /// every draw, an indirect command buffer's executed commands' too, naming every such + /// attachment of the pass. Not where `DriverFact::TileStoreIsMetals` holds (MoltenVK's + /// pass is a Metal pass, whose tile store rewrites the codes as Metal's does), nor under + /// [`metal2vulkan::device::TileStorePolicy::Exact`] for an attachment the load pass + /// (`render/unused_bits_load.rs`) rewrites. + SnormMinimumKept = "snorm-minimum-kept", Precision, + "the texels the pass's draws do not write keep their bytes; Metal's pass rewrites a \ + channel's minimum code (-128, or -32768 for 16 bits) as the code above it (-127, \ + -32767) in each tile a draw reaches: a texel whose bytes no Metal write left \ + (uploaded or copied bytes) keeps a code Metal's pass would change"; + /// too, naming every such attachment of the pass. Not where `DriverFact::TileStoreIsMetals` + /// holds (MoltenVK's pass is a Metal pass), nor under + /// [`metal2vulkan::device::TileStorePolicy::Exact`] for an attachment the load pass + /// (`render/unused_bits_load.rs`) rewrites. /// A blit between a buffer and a level of `RGB10A8_2P_XR10` or its sRGB twin whose width /// is not a multiple of 4 (`two_planes.rs`): it moves the texels at the rows the texture /// holds them in, where Metal's blit addresses the level's rows `⌊4 w / 16⌋ · 16` bytes @@ -1238,7 +1261,8 @@ degradations! { stops"; /// A render pass that loads a color attachment of an extended-range or padded 10-bit /// format (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`, `RG10Unorm_X12` and - /// their sRGB twins), stores it and draws, whose load pass + /// their sRGB twins), or under [`metal2vulkan::device::TileStorePolicy::Exact`] of a + /// signed normalized format or `RGB9E5Float`, stores it and draws, whose load pass /// (`render/unused_bits_load.rs`) rewrites every 32 x 32 tile of its render area: Metal's /// pass rewrites only the tiles a draw's primitives reach (EVs XRR2-xrb2 and XRR2-xrb3 on /// an Apple M4 and an Apple M3 Max, alike), and every tile only where a color @@ -1249,9 +1273,10 @@ degradations! { "in tiles no draw reaches the pass rewrites what Metal keeps: the unused bits made \ canonical (BGR10_XR's bits 30 and 31 ones, BGRA10_XR's low six bits of each field \ and the two-plane color word's top two bits zeros) and BGRA10_XR alpha codes \ - clamped to [384, 894], so an out-of-range raw alpha reads back changed, and a padded \ - word's low six bits zeroed (an sRGB twin's code moved through Metal's table); the \ - tiles a draw reaches are Metal's"; + clamped to [384, 894], so an out-of-range raw alpha reads back changed, a padded \ + word's low six bits zeroed (an sRGB twin's code moved through Metal's table) and, \ + under the exact tile store, a signed normalized minimum code raised and an \ + RGB9E5Float word normalized; the tiles a draw reaches are Metal's"; /// A draw in a render pass over a rasterization-rate map of no layers that was made after /// the device released a map of one or more layers (`rate_mapped_pass.rs`). The draw /// writes nothing, where Metal draws: an Apple M4 and an Apple M3 Max drew a 64-pixel diff --git a/crates/metal2vulkan-runtime/src/owned_kernel.rs b/crates/metal2vulkan-runtime/src/owned_kernel.rs index 3265ce308..1e5c560d6 100644 --- a/crates/metal2vulkan-runtime/src/owned_kernel.rs +++ b/crates/metal2vulkan-runtime/src/owned_kernel.rs @@ -27,6 +27,7 @@ use metal2vulkan::bind::{ TessellationScanKernel, TexelWords, YCbCrOutput, }; use metal2vulkan::metal::format::ExtendedRange; +use metal2vulkan::metal::PixelFormat; use std::collections::HashMap; /// A crate-owned module the runtime dispatches. @@ -95,10 +96,11 @@ pub(super) enum OwnedModule { /// `bind::ycbcr_write_module`: a 4:4:4 YCbCr texture's written texels encoded into its /// surface's two planes (`ycbcr.rs`), its write shadow bound as a storage image. YCbCrWrite, - /// `bind::unused_bits_module` of one form held as one kind of words: an extended-range or - /// padded 10-bit texture's words in the tiles a mask names rewritten as Metal's tile store - /// leaves them, before a pass that loads it and draws (`render/unused_bits_load.rs`). - UnusedBits(ExtendedRange, TexelWords), + /// `bind::unused_bits_module` of one format held as one kind of words: an extended-range, + /// padded 10-bit or bfloat texture's words (or, under `TileStorePolicy::Exact`, a signed + /// normalized or `RGB9E5Float` one's) in the tiles a mask names rewritten as Metal's tile + /// store leaves them, before a pass that loads it and draws (`render/unused_bits_load.rs`). + UnusedBits(PixelFormat, TexelWords), /// `bind::tiled_texels_module`: a heap texture's elements moved between its image's tight /// copy and Metal's tiles in the heap's bytes (`texture/heap_tiled.rs`). TiledTexels, @@ -269,9 +271,9 @@ impl OwnedModule { .map_err(Error::Compile)?; Ok((module.spirv.to_vec(), 3, 0)) } - OwnedModule::UnusedBits(form, words) => { + OwnedModule::UnusedBits(format, words) => { let device = device.compile_device(); - let module = metal2vulkan::bind::unused_bits_module(device, form, words) + let module = metal2vulkan::bind::unused_bits_module(device, format, words) .map_err(Error::Compile)?; Ok((module.spirv.to_vec(), 3, 0)) } @@ -375,7 +377,7 @@ pub(super) struct OwnedKernels { two_plane_texels: Option, plane_bytes_copy: Option, ycbcr_write: Option, - unused_bits: HashMap<(ExtendedRange, TexelWords), OwnedKernel>, + unused_bits: HashMap<(PixelFormat, TexelWords), OwnedKernel>, tiled_texels: Option, compressed_blits: HashMap, capture_assembly: Option, @@ -437,7 +439,9 @@ impl OwnedKernels { self.index_rewrites.get(&(program, phase)).copied() } OwnedModule::YCbCrConvert(output) => self.ycbcr_converts.get(&output).copied(), - OwnedModule::UnusedBits(form, words) => self.unused_bits.get(&(form, words)).copied(), + OwnedModule::UnusedBits(format, words) => { + self.unused_bits.get(&(format, words)).copied() + } OwnedModule::CompressedBlit(rule) => self.compressed_blits.get(&rule).copied(), OwnedModule::ExtendedShadowLoad(form) => self.extended_shadow_loads.get(&form).copied(), OwnedModule::TwinDecode(decode) => self.twin_decodes.get(&decode).copied(), @@ -461,8 +465,8 @@ impl OwnedKernels { OwnedModule::YCbCrConvert(output) => { self.ycbcr_converts.insert(output, kernel); } - OwnedModule::UnusedBits(form, words) => { - self.unused_bits.insert((form, words), kernel); + OwnedModule::UnusedBits(format, words) => { + self.unused_bits.insert((format, words), kernel); } OwnedModule::CompressedBlit(rule) => { self.compressed_blits.insert(rule, kernel); diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index a4a1b6369..8ad682843 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -6236,6 +6236,9 @@ impl RenderCommandEncoder { ) }); } + + /// Announce `snorm-minimum-kept` at a draw in a pass that loads a single-sampled color + /// attachment of a signed normalized format (and does not discard it at the store), whatever /// the draw's state, naming every such attachment, `kept` /// (`unused_bits_load::snorm_minimum_kept`): Metal's pass, once it draws, writes each tile a /// draw reaches back through the channels' values, so a minimum code (-128, or -32768) the @@ -6243,6 +6246,20 @@ impl RenderCommandEncoder { /// on a driver whose pass stores it so too (`DriverFact::TileStoreIsMetals`: MoltenVK's pass /// is a Metal pass), nor for an attachment the load pass rewrites (`TileStorePolicy::Exact`). fn degrade_snorm_minimum(device: &Device, kept: &[String]) { + if kept.is_empty() { + return; + } + device.degrade(Degradation::SnormMinimumKept, || { + ( + format!("a draw in a render pass that loads {}", kept.join(" and ")), + "the texels the pass's draws do not write keep a channel's minimum code (-128, \ + or -32768), which Metal's pass stores as the code above it (-127, -32767) in \ + each tile a draw reaches" + .to_owned(), + ) + }); + } + /// state, naming every such attachment, `kept` (`unused_bits_load::shared_exponent_kept`): /// Metal's pass, once it draws, writes each tile a draw reaches back through its texels' /// values, so a word the draws do not write whose largest mantissa is below 256 under an diff --git a/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs b/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs index 84828e279..6723842a3 100644 --- a/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs +++ b/crates/metal2vulkan-runtime/src/render/unused_bits_load.rs @@ -1,4 +1,5 @@ -//! The load pass of an extended-range, padded 10-bit or bfloat color attachment. +//! The load pass of an extended-range, padded 10-bit or bfloat color attachment, and under the +//! exact tile store of a signed normalized or `RGB9E5Float` one. //! //! - **Metal's answer** (EVs XRR2-xrb2 and -xrb3 on an Apple M4 under macOS 27.0.1 and on the //! consumer's Apple M3 Max under macOS 26.7, alike; EVs XRR2-x6g to -x6k, -x6is on both). @@ -53,6 +54,17 @@ //! tiles there no draw reaches are rewritten here where Metal keeps them; but where capture //! replay found the tiles the draws' primitives reach (`render/capture.rs`, Metal's, announced by //! the command buffer where a primitive's reach was not measured). +//! - **The exact tile store** (`TileStorePolicy::Exact`). The same pass, once it draws, writes a +//! single-sampled signed normalized or `RGB9E5Float` attachment's tiles back through their +//! values (an Apple M3 Max under macOS 27.0.1): a channel's minimum code (-128, or -32768) is +//! stored as the code above it, and a word whose largest mantissa is below 256 under an exponent +//! above 0 normalized (`bind::unused_bits_module` of the format). Under the exact tile store the +//! load pass takes such an attachment as it takes an extended-range one, where the driver's pass +//! does not store them so already (`DriverFact::TileStoreIsMetals`: MoltenVK's pass is a Metal +//! pass); under the default, `TileStorePolicy::Device`, it leaves them to the device's load and +//! store, and a draw announces `snorm-minimum-kept` or `shared-exponent-kept` +//! ([`snorm_minimum_kept`], [`shared_exponent_kept`]), as it does for one the load pass does not +//! take. //! - **Not here** (`degrade_unused_bits` announces `extended-range-bits-kept` at each draw): a //! multisampled attachment (no copy reaches its samples), a texture held as a shadow of another //! image or of a heap's bytes, a sparse one, and one whose image the device does not copy both @@ -63,18 +75,21 @@ use super::capture::CapturedReach; use crate::buffer_texture::Texels; use crate::clear_reach::{DrawnTiles, PassReach}; use crate::degradation::Degradation; +use crate::device::Device; use crate::encoder::EncoderCore; use crate::error::{internal, Error}; use crate::owned_kernel::{OwnedModule, OwnedSets}; use crate::render_pass::{ColorTarget, PassLayout, Target}; use crate::render_values::{LoadAction, StoreAction}; use crate::shadow::ShadowTarget; +use crate::texture::Texture; use crate::tracker::{Access, Barrier, Use, UseRange}; use crate::values::ResourceOptions; use ash::vk; use metal2vulkan::bind::{TexelWords, UnusedBitsModule}; +use metal2vulkan::device::{DriverFact, TileStorePolicy}; use metal2vulkan::metal::format::ExtendedRange; -use metal2vulkan::metal::TextureType; +use metal2vulkan::metal::{PixelFormat, TextureType}; use metal2vulkan::vk::{ImageType, ImageUsageFlags}; /// The side, in texels, of the tiles Metal stores. @@ -230,10 +245,10 @@ enum Source<'a> { Frame, } -/// A color attachment the load pass takes: its form, the target whose texels it rewrites (the +/// A color attachment the load pass takes: its format, the target whose texels it rewrites (the /// texture's own, where a stand-in renders for it), and where it finds them. struct Taken<'a> { - form: ExtendedRange, + format: PixelFormat, target: &'a Target, source: Source<'a>, } @@ -244,12 +259,37 @@ fn own(color: &ColorTarget) -> &Target { color.stand_in.as_ref().map_or(&color.target, |s| &s.own) } -/// Whether `color` is of an extended-range, padded or bfloat format, loaded and not discarded -/// at the store; `late` counts a store action the encoder decides later as storing. +/// Whether the load pass rewrites a texture of `texture`'s format: an extended-range, padded or +/// bfloat one's always, and a signed normalized ([`SNORM_MINIMUM`]) or `RGB9E5Float` one's under +/// the exact tile store (`TileStorePolicy::Exact`) on a driver whose store is not Metal's already +/// (`DriverFact::TileStoreIsMetals`). +fn rewrites(texture: &Texture) -> bool { + let format = texture.pixel_format(); + if ExtendedRange::of(format).is_some() { + return true; + } + let device = texture.device(); + let stored = SNORM_MINIMUM.contains(&format) || format == PixelFormat::RGB9E5Float; + stored + && device.compile_device().policy().tile_store == TileStorePolicy::Exact + && !metals_store(device) +} + +/// Whether `device`'s render pass stores a signed normalized minimum code and an `RGB9E5Float` +/// word as Metal's tile store does (`DriverFact::TileStoreIsMetals`: MoltenVK's pass is a Metal +/// pass). +pub(super) fn metals_store(device: &Device) -> bool { + device + .properties() + .driver_facts + .contains(&DriverFact::TileStoreIsMetals) +} + +/// Whether `color` is of a format the load pass rewrites ([`rewrites`]), loaded and not +/// discarded at the store; `late` counts a store action the encoder decides later as storing. fn loaded(color: &ColorTarget, late: bool) -> bool { - let format = own(color).texture.pixel_format(); let discarded = color.store == StoreAction::DontCare && !(late && color.late_store); - ExtendedRange::of(format).is_some() + rewrites(&own(color).texture) && color.load == LoadAction::Load && !color.memoryless && !discarded @@ -263,7 +303,7 @@ fn takes(color: &ColorTarget, late: bool) -> Option> { } let target = own(color); let texture = &target.texture; - let form = ExtendedRange::of(texture.pixel_format())?; + let format = texture.pixel_format(); let turned = texture .shadow() .is_some_and(|copies| matches!(copies.target(), Some(ShadowTarget::Rotated { .. }))); @@ -279,31 +319,31 @@ fn takes(color: &ColorTarget, late: bool) -> Option> { // A rotated texture's frame, which its shadow's copy in fills. if turned { return copies_both_ways().then_some(Taken { - form, + format, target, source: Source::Frame, }); } if let Some(texels) = texture.buffer_texels() { - let words = match form { - ExtendedRange::Planes { .. } => TexelWords::ColorPlane, + let words = match ExtendedRange::of(format) { + Some(ExtendedRange::Planes { .. }) => TexelWords::ColorPlane, _ => TexelWords::Raw, }; let flat = matches!( texture.texture_type(), TextureType::Type2D | TextureType::Type2DArray ) && target.layers == 1; - let texel = u64::from(UnusedBitsModule::texel_bytes(form, words)?); + let texel = u64::from(UnusedBitsModule::texel_bytes(format, words)?); let rows_of_texels = texels.layout.row_bytes == u64::from(target.extent[0]) * texel; return (flat && rows_of_texels).then_some(Taken { - form, + format, target, source: Source::Bytes(texels, words), }); } let image = texture.shadow().is_none() && !texture.is_sparse() && copies_both_ways(); image.then_some(Taken { - form, + format, target, source: Source::Image, }) @@ -326,9 +366,52 @@ pub(super) fn consumes_capture(layout: &PassLayout, ended: bool) -> bool { taken.peek().is_some() && taken.all(|taken| !matches!(taken.source, Source::Frame)) } -/// Whether `color` is of an extended-range or padded format, loaded and not discarded at the -/// store, where the load pass does not take it (`degrade_unused_bits`). +/// Whether `color` is of an extended-range, padded or bfloat format, loaded and not discarded at +/// the store, where the load pass does not take it (`degrade_unused_bits`). pub(super) fn untaken(color: &ColorTarget) -> bool { + ExtendedRange::of(own(color).texture.pixel_format()).is_some() + && loaded(color, true) + && takes(color, true).is_none() +} + +/// The signed normalized color formats whose minimum code Metal's tile store rewrites, as +/// measured on an Apple M3 Max (`snorm-minimum-kept`). +const SNORM_MINIMUM: [PixelFormat; 6] = [ + PixelFormat::R8Snorm, + PixelFormat::RG8Snorm, + PixelFormat::RGBA8Snorm, + PixelFormat::R16Snorm, + PixelFormat::RG16Snorm, + PixelFormat::RGBA16Snorm, +]; + +/// Whether `color` is a single-sampled attachment of a signed normalized format +/// ([`SNORM_MINIMUM`]), loaded and not discarded at the store, where the load pass does not take +/// it: Metal's pass, once it draws, writes each tile a draw reaches back through the channels' +/// values, so a minimum code (-128, or -32768) is stored as the code above it, where the device's +/// pass keeps the bytes its draws do not write (`degrade_snorm_minimum`, which reads +/// `DriverFact::TileStoreIsMetals`: a driver whose pass stores them as Metal's). The load pass +/// rewrites them under the exact tile store (`TileStorePolicy::Exact`) where it takes the +/// attachment. +pub(super) fn snorm_minimum_kept(color: &ColorTarget) -> bool { + let target = own(color); + let discarded = color.store == StoreAction::DontCare && !color.late_store; + SNORM_MINIMUM.contains(&target.texture.pixel_format()) + && target.samples == 1 + && color.load == LoadAction::Load + && !color.memoryless + && !discarded + && takes(color, true).is_none() +} + +/// store, where the load pass does not take it: Metal's pass, once it draws, writes each tile a +/// draw reaches back through its texels' values, so a word whose largest mantissa is below 256 +/// under an exponent above 0 (one no Metal write leaves) is stored normalized, its mantissas +/// shifted up as its exponent steps down, where the device's pass keeps the bytes its draws do +/// not write (`degrade_shared_exponent`, which reads `DriverFact::TileStoreIsMetals`). The load +/// pass rewrites them under the exact tile store (`TileStorePolicy::Exact`) where it takes the +/// attachment. + && takes(color, true).is_none() /// The color attachments of a pass's layout that each of a draw's kept-attachment notices names, as /// `color {index}, {format:?}`: the extended-range or padded ones the load pass does not take /// ([`untaken`], `degrade_unused_bits`) and, on a driver whose pass does not store as Metal's @@ -428,9 +511,10 @@ pub(super) fn record( "the pass rewrites every 32x32 tile of its render area, where Metal's \ rewrites only the tiles a draw's primitives reach (or every tile where a \ color attachment is cleared): in tiles no draw reaches the unused bits are \ - made canonical and BGRA10_XR alpha codes clamped to [384, 894], and a \ - padded word's low six bits zeroed (an _sRGB twin's code through Metal's \ - table), where Metal keeps those texels' bytes" + made canonical and BGRA10_XR alpha codes clamped to [384, 894], a padded \ + word's low six bits zeroed (an _sRGB twin's code through Metal's table) and, \ + under the exact tile store, a signed normalized minimum code raised and an \ + RGB9E5Float word normalized, where Metal keeps those texels' bytes" .to_owned(), ) }); @@ -472,7 +556,7 @@ fn record_taken( Source::Bytes(_, words) => words, Source::Image | Source::Frame => TexelWords::Raw, }; - let texel = UnusedBitsModule::texel_bytes(taken.form, words) + let texel = UnusedBitsModule::texel_bytes(taken.format, words) .ok_or_else(|| internal("an unused bits attachment without its words"))?; let columns = u64::from(layout.extent[0].next_multiple_of(TILE).min(width)); let rows = u64::from(layout.extent[1].next_multiple_of(TILE).min(height)); @@ -554,7 +638,7 @@ fn rewrite( if !at.is_multiple_of(align) { return Err(internal("an unused bits scratch off its alignment")); } - let kernel = device.owned_kernel(OwnedModule::UnusedBits(taken.form, words))?; + let kernel = device.owned_kernel(OwnedModule::UnusedBits(taken.format, words))?; let ranges: Vec<_> = bands .iter() .enumerate() diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 753837370..d7d71682c 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -1255,9 +1255,10 @@ pub struct WorkCounts { /// Nanoseconds commits spent making ahead for their render passes' host steps, kept /// backings included. pub ahead_nanos: u64, - /// Load passes render encoders recorded: one per extended-range or padded 10-bit color - /// attachment that a pass which draws loads and stores, whose unused bits a dispatch made - /// canonical in the tiles the pass's draws reach before the pass, as Metal's pass does + /// Load passes render encoders recorded: one per extended-range, padded 10-bit or bfloat + /// color attachment (and under `TileStorePolicy::Exact` signed normalized or `RGB9E5Float` + /// one) that a pass which draws loads and stores, whose words a dispatch rewrote in the tiles + /// the pass's draws reach before the pass, as Metal's tile store leaves them /// (`render/unused_bits_load.rs`). pub unused_bits_load_passes: u64, /// The texels of those passes' regions (the render area rounded up to 32 texels a side, diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 03cedc471..7fb6c2a4d 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -642,6 +642,8 @@ mod single_sample_passes; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod snapshot_reads; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod snorm_tile_store; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod sparse_textures; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod srgb_storage; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index aa6964fe4..fce91b2ef 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -509,6 +509,7 @@ fn every_kind_has_a_site_a_lane_test_takes() { &TWO_PLANE_COPIES, &EXTENDED_RANGE_BITS, &UNREACHED_TILES, + &SNORM_MINIMUM, &STORED_CODES, &UNADVERTISED_VERTEX_SIMDGROUPS, &YCBCR_FILTERS, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/snorm_tile_store.rs b/crates/metal2vulkan-validation/src/runtime_lane/snorm_tile_store.rs new file mode 100644 index 000000000..72a62997b --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/snorm_tile_store.rs @@ -0,0 +1,263 @@ +//! A signed normalized color attachment's minimum codes through a render pass that loads it and +//! draws, on the device the cfg selects, under the validation layer. +//! +//! Metal's pass, once it draws, writes each 32 x 32 tile a draw reaches back through its channels' +//! values, so a channel's minimum code (-128, or -32768), which reads as -1.0 as the code above it +//! does, is stored as that code (-127, -32767) in every texel of the tile, those no fragment writes +//! too (measured on an Apple M3 Max under macOS 27.0.1). An `RGB9E5Float` attachment's tiles are +//! written back the same way, through their values, so a word whose largest mantissa is below 256 +//! under an exponent above 0 is stored normalized (its mantissas shifted up as its exponent steps +//! down; measured there too). +//! Under `TileStorePolicy::Device`, the default, the runtime keeps the device's load and store +//! (docs/FAST-PATHS.md), so the texels keep their codes and words, and a draw in such a pass +//! announces `snorm-minimum-kept` or `shared-exponent-kept`, naming the attachment. Under +//! `TileStorePolicy::Exact` the load pass (`render/unused_bits_load.rs`) rewrites them as Metal's +//! store leaves them before the pass, and nothing is announced. On a driver whose pass stores them +//! as Metal's (`DriverFact::TileStoreIsMetals`: MoltenVK, whose pass is a Metal pass) the texels +//! take Metal's codes and words under either value, with no load pass and nothing announced. + +use super::degrade_notices::counts; +use super::resolves::{lane_with, quiet, Lane, Shape, FULL, SIZE, WHITE}; +use metal2vulkan::device::{DriverFact, TileStorePolicy}; +use metal2vulkan::metal::{ColorWriteMask, PixelFormat, TextureUsage}; +use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use metal2vulkan_runtime::{ +}; + +/// The kind a draw in a pass that loads a single-sampled signed normalized color announces. +pub(super) const SNORM_MINIMUM: [Degradation; 1] = [Degradation::SnormMinimumKept]; + +/// The signed normalized formats Metal's tile store rewrites: each one's bytes a texel, the bytes +/// of a channel's minimum code and those of the code above it, which Metal's pass stores. +const FORMATS: [(PixelFormat, u64, &[u8], &[u8]); 6] = [ + (PixelFormat::R8Snorm, 1, &[0x80], &[0x81]), + (PixelFormat::RG8Snorm, 2, &[0x80], &[0x81]), + (PixelFormat::RGBA8Snorm, 4, &[0x80], &[0x81]), + (PixelFormat::R16Snorm, 2, &[0x00, 0x80], &[0x01, 0x80]), + (PixelFormat::RG16Snorm, 4, &[0x00, 0x80], &[0x01, 0x80]), + (PixelFormat::RGBA16Snorm, 8, &[0x00, 0x80], &[0x01, 0x80]), +]; + +/// A pipeline of the fixture's full-screen triangle and white into `pf` under a write mask of +/// none of its channels: its draws write no texel. +fn unwritten(lane: &Lane, pf: PixelFormat) -> RenderPipelineDescriptor { + let function = |name| { + StageSource::Function( + lane.library + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + }; + let mut descriptor = RenderPipelineDescriptor::new(function(FULL)); + descriptor.fragment = Some(function(WHITE)); + let mut color = ColorAttachmentDescriptor::new(pf); + color.write_mask = ColorWriteMask::NONE; + descriptor.color_attachments[0] = Some(color); + descriptor +} + +/// The bytes of a 4² texture of `texel` bytes a texel whose every channel holds `code`. +fn filled(texel: u64, code: &[u8]) -> Vec { + code.repeat((texel * SIZE * SIZE) as usize / code.len()) +} + +/// Write `bytes` (`texel` bytes a texel) to every texel of the 4² texture `t`. +fn upload(t: &Texture, texel: u64, bytes: &[u8]) { + t.replace_region( + Region::new_2d(0, 0, SIZE, SIZE), + 0, + 0, + bytes, + texel * SIZE, + 0, + ) + .unwrap(); +} + +/// A shared 4² render target of `pf` (`texel` bytes a texel) whose every channel holds the +/// minimum code `code`, and its bytes. +fn minimum_codes(lane: &Lane, pf: PixelFormat, texel: u64, code: &[u8]) -> (Texture, Vec) { + let shape = Shape { + size: SIZE, + samples: 1, + slices: 1, + levels: 1, + shared: true, + }; + let t = lane.texture(pf, shape, TextureUsage::RENDER_TARGET); + let bytes = filled(texel, code); + upload(&t, texel, &bytes); + (t, bytes) +} + +/// A pass that loads `t` by `load` and stores it. +fn pass(t: &Texture, load: LoadAction) -> RenderPassDescriptor { + let mut descriptor = RenderPassDescriptor::new(); + let attachment = &mut descriptor.color_attachments[0]; + attachment.texture = Some(t.clone()); + attachment.load_action = load; + attachment.store_action = StoreAction::Store; + descriptor +} + +/// What a drawing pass of the lane's device leaves under `tile_store`: whether the device's store +/// is Metal's (`DriverFact::TileStoreIsMetals`), and whether the load pass rewrites the texels. +fn expected(lane: &Lane, tile_store: TileStorePolicy) -> (bool, bool) { + let metals = lane + .device + .properties() + .driver_facts + .contains(&DriverFact::TileStoreIsMetals); + (metals, tile_store == TileStorePolicy::Exact && !metals) +} + +/// The load passes the lane's device recorded so far. +fn load_passes(lane: &Lane) -> u64 { + lane.device.work_counts().unused_bits_load_passes +} + +/// A pass that loads a 4² target of each signed normalized format holding the minimum code in +/// every channel and draws under a write mask of none of its channels, under `tile_store`: where +/// the device's store is Metal's or the load pass rewrites the codes (one load pass), every +/// texel takes the code above and nothing is announced; else every code stays and +/// `snorm-minimum-kept` is announced once (the device asks for it at each occurrence), naming +/// color 0 and its format. A pass that loads the minimum codes again and draws nothing keeps +/// every one, records no load pass and announces nothing, as Metal's keeps every texel. +fn snorm_minimum_codes(tile_store: TileStorePolicy) { + let (messages, _cache, lane) = lane_with(|options| { + options.announce_each = SNORM_MINIMUM.into_iter().collect(); + options.policy.tile_store = tile_store; + }); + let (metals, rewritten) = expected(&lane, tile_store); + eprintln!("{tile_store:?}: Metal's store {metals}, rewritten {rewritten}"); + for (pf, texel, code, above) in FORMATS { + let pipeline = lane + .device + .new_render_pipeline_state(&unwritten(&lane, pf), &PipelineOptions::default()) + .unwrap(); + let (t, bytes) = minimum_codes(&lane, pf, texel, code); + let before = load_passes(&lane); + lane.run(&pass(&t, LoadAction::Load), |l, e, h| { + l.draw(e, h, &pipeline, 0.5) + }) + .unwrap(); + let loads = load_passes(&lane) - before; + let got = lane.read(&t, (0, 0), texel, BlitOption::None); + let notices = messages.take_notices(); + assert_eq!( + loads, + u64::from(rewritten), + "{pf:?} {tile_store:?}: load passes" + ); + if metals || rewritten { + let raised = filled(texel, above); + assert!( + got == raised, + "{pf:?} {tile_store:?}: not Metal's codes: {got:02x?}" + ); + assert!( + !counts(¬ices).contains_key(&SNORM_MINIMUM[0]), + "{pf:?} {tile_store:?}: announced where the codes are Metal's" + ); + } else { + assert!(got == bytes, "{pf:?}: the codes moved: {got:02x?}"); + assert_eq!(counts(¬ices).get(&SNORM_MINIMUM[0]), Some(&1), "{pf:?}"); + let named = notices.iter().any(|m| { + m.degradation.as_ref().is_some_and(|n| { + n.degradation == SNORM_MINIMUM[0] + && n.object.contains(&format!("color 0, {pf:?}")) + }) + }); + assert!(named, "{pf:?}: the notice names no color 0"); + } + upload(&t, texel, &bytes); + let before = load_passes(&lane); + lane.run(&pass(&t, LoadAction::Load), |_, _, _| {}).unwrap(); + assert_eq!( + load_passes(&lane), + before, + "{pf:?}: a pass of no draw's load pass" + ); + let got = lane.read(&t, (0, 0), texel, BlitOption::None); + assert!( + got == bytes, + "{pf:?}: a pass of no draw moved the codes: {got:02x?}" + ); + let notices = messages.take_notices(); + assert!( + !counts(¬ices).contains_key(&SNORM_MINIMUM[0]), + "{pf:?}: a pass of no draw" + ); + } + quiet(lane, &messages); +} +/// [`snorm_minimum_codes`] under the default, the device's load and store. +#[test] +fn a_drawing_pass_keeps_a_snorm_minimum_code_and_says_so() { + snorm_minimum_codes(TileStorePolicy::Device); +} + +/// [`snorm_minimum_codes`] under the exact tile store, the load pass's rewrite. +#[test] +fn the_exact_tile_store_raises_a_snorm_minimum_code() { + snorm_minimum_codes(TileStorePolicy::Exact); +} + +/// none of its channels, under `tile_store`: where the device's store is Metal's or the load pass +/// rewrites the words (one load pass), every word takes Metal's (mantissas 128, 256 and 384 under +/// the exponent 13) and nothing is announced; else every word stays and `shared-exponent-kept` is +/// announced once (the device asks for it at each occurrence), naming color 0 and its format. A +/// pass that loads it and draws nothing announces nothing. A device that renders no +fn shared_exponent_words(tile_store: TileStorePolicy) { + let (messages, _cache, lane) = lane_with(|options| { + options.announce_each = SHARED_EXPONENT.into_iter().collect(); + options.policy.tile_store = tile_store; + }); + let (metals, rewritten) = expected(&lane, tile_store); + let metal: u32 = 128 | 256 << 9 | 384 << 18 | 13 << 27; + let before = load_passes(&lane); + let loads = load_passes(&lane) - before; + loads, + u64::from(rewritten), + "{pf:?} {tile_store:?} on {name}: load passes" + if metals || rewritten { + let normalized = metal.to_le_bytes().repeat((SIZE * SIZE) as usize); + assert!( + got == normalized, + "{pf:?} {tile_store:?} on {name}: not Metal's words: {got:02x?}" + ); + assert!( + !counts(¬ices).contains_key(&SHARED_EXPONENT[0]), + "{pf:?} {tile_store:?} on {name}: announced where the words are Metal's" + ); + } else { + assert!( + got == bytes, + "{pf:?} on {name}: the words moved: {got:02x?}" + ); + assert_eq!( + counts(¬ices).get(&SHARED_EXPONENT[0]), + Some(&1), + "{pf:?} on {name}" + ); + let named = notices.iter().any(|m| { + m.degradation.as_ref().is_some_and(|n| { + n.degradation == SHARED_EXPONENT[0] + && n.object.contains(&format!("color 0, {pf:?}")) + }) + }); + assert!(named, "{pf:?} on {name}: the notice names no color 0"); + } + +/// [`shared_exponent_words`] under the default, the device's load and store. +#[test] +fn a_drawing_pass_keeps_an_unnormalized_shared_exponent_word_and_says_so() { + shared_exponent_words(TileStorePolicy::Device); +} + +/// [`shared_exponent_words`] under the exact tile store, the load pass's rewrite. +#[test] +fn the_exact_tile_store_normalizes_a_shared_exponent_word() { + shared_exponent_words(TileStorePolicy::Exact); +} diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index de9617427..f519a981a 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -82,10 +82,11 @@ //! [`two_plane_texels_module`]; a blit into such a texture of a heap writes the heap's bytes at //! Metal's rows through [`plane_bytes_copy_module`]. A heap texture over host pages keeps its //! elements in the heap's bytes in Metal's tiled layout, moved between its image and those bytes -//! through [`tiled_texels_module`]. A render pass that loads an extended-range or padded 10-bit -//! color attachment and draws first rewrites the bits its codes leave unused through -//! [`unused_bits_module`] of its form, in the 32 x 32 tiles a mask names, as Metal's tile store -//! does. The tiles a pass's draws reach, which Metal's tile store writes back, are the mask one +//! through [`tiled_texels_module`]. A render pass that loads an extended-range, padded 10-bit or +//! bfloat color attachment and draws first rewrites the bits its codes leave unused through +//! [`unused_bits_module`] of its format, in the 32 x 32 tiles a mask names, as Metal's tile store +//! does; under the exact tile store it also raises a signed normalized attachment's minimum codes +//! and normalizes an `RGB9E5Float` attachment's words there. The tiles a pass's draws reach, which Metal's tile store writes back, are the mask one //! dispatch of [`tile_reach_module`] bins its captured primitives into: [`capture_assembly_module`] //! assembles them from a pass's capture draws' records, and [`capture_settle_module`] widens the //! mask to every tile where the binning counted a primitive it cannot answer. A GPU blit that reads diff --git a/crates/metal2vulkan/src/bind/unused_bits.rs b/crates/metal2vulkan/src/bind/unused_bits.rs index 0741848dd..69cc6bc7d 100644 --- a/crates/metal2vulkan/src/bind/unused_bits.rs +++ b/crates/metal2vulkan/src/bind/unused_bits.rs @@ -20,12 +20,23 @@ //! (`ExtendedRange::load_code`; EV FRT-bfp1-m4 on an Apple M4 under macOS 27.0.1: 56,829 of the //! 65,536 codes move, in every tile a draw reaches). //! +//! The same store writes a single-sampled signed normalized or `RGB9E5Float` attachment's tiles +//! back through their values (an Apple M3 Max under macOS 27.0.1), which a consumer's exact tile +//! store takes (`TileStorePolicy::Exact`): +//! +//! - a signed normalized format's code (`R8Snorm`, `RG8Snorm`, `RGBA8Snorm`, `R16Snorm`, +//! `RG16Snorm`, `RGBA16Snorm`): a channel's minimum code (-128, or -32768), which reads as -1.0 +//! as the code above it does, raised to that code (-127, -32767); +//! - an `RGB9E5Float` word whose largest mantissa is below 256 under an exponent above 0: +//! normalized, its three mantissas shifted up one bit as its exponent steps down one, until the +//! largest reaches 256 or the exponent 0 (the word Metal's encoding of its value gives). +//! //! A consumer copies the region's texels, row after row, into a buffer of words, one dispatch of //! [`unused_bits_module`] of the texture's form rewrites the words of the tiles a mask names, and //! it copies them back before the pass: the pass's write masks, discards, tests and uncovered //! texels then keep Metal's words. //! -//! **The module** (one per device, form and [`TexelWords`]). One `GLCompute` entry `main` with +//! **The module** (one per device, format and [`TexelWords`]). One `GLCompute` entry `main` with //! local size ([`UnusedBitsModule::LOCAL_SIZE`], 1, 1), no push constants, and three storage //! buffers of 4-byte words in set 0: //! @@ -54,6 +65,7 @@ use crate::device::requirements::Requirements; use crate::device::Device; use crate::error::{Error, Feature, InternalError, InternalKind, Unsupported}; use crate::metal::format::ExtendedRange; +use crate::metal::PixelFormat; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage, Symbol}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; @@ -64,8 +76,8 @@ use crate::spirv::ir::{ MemAccess, StorageClass, Type, TypedModule, }; -/// The crate-owned unused bits module of one device, form and [`TexelWords`], validated like -/// any output. +/// The crate-owned unused bits module of one device, format and [`TexelWords`], validated like +/// any output: the words of the texels Metal's tile store rewrites (the module docs). #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq)] pub struct UnusedBitsModule { @@ -105,11 +117,21 @@ impl UnusedBitsModule { bytes } - /// The bytes of one texel of `form` held as `words`: the raw texel - /// (`ExtendedRange::raw_format`), or a two-plane format's color word alone. `None` where - /// `form` has no such words ([`TexelWords::ColorPlane`] of another form). - pub fn texel_bytes(form: ExtendedRange, words: TexelWords) -> Option { - Some(match (rule(form, words)?, form) { + /// The bytes of one texel of `format` held as `words`: an extended-range, padded or bfloat + /// format's raw texel (`ExtendedRange::raw_format`) or a two-plane format's color word + /// alone, or a signed normalized or `RGB9E5Float` texel. `None` where `format` has no such + /// words: another format, or [`TexelWords::ColorPlane`] of a format but a two-plane one. + pub fn texel_bytes(format: PixelFormat, words: TexelWords) -> Option { + let rule = rule(format, words)?; + let Some(form) = ExtendedRange::of(format) else { + return match format { + PixelFormat::R8Snorm => Some(1), + PixelFormat::RG8Snorm | PixelFormat::R16Snorm => Some(2), + PixelFormat::RGBA16Snorm => Some(8), + _ => Some(4), + }; + }; + Some(match (rule, form) { (Rule::Padded(_), ExtendedRange::R10X6 | ExtendedRange::R10X6Srgb) => 2, (Rule::Bfloat, ExtendedRange::R16Bfloat) => 2, (Rule::Bfloat, ExtendedRange::Rgba16Bfloat) => 8, @@ -151,10 +173,34 @@ enum Rule { /// A bfloat form's two 16-bit codes: each one's value through `half` and back /// (`ExtendedRange::load_code`, [`bfloat_load`]). Bfloat, + /// A signed normalized format's codes, each byte (each 16-bit half where `wide`): one at the + /// minimum code (`0x80`, `0x8000`) raised to the code above it ([`snorm_minimum`]). + SnormMinimum { wide: bool }, + /// An `RGB9E5Float` word, normalized ([`shared_exponent`]). + SharedExponent, } -/// The rule of `form`'s texels held as `words`, or `None` where it has none. -fn rule(form: ExtendedRange, words: TexelWords) -> Option { +/// The rule of `format`'s texels held as `words`, or `None` where it has none. +fn rule(format: PixelFormat, words: TexelWords) -> Option { + if let Some(form) = ExtendedRange::of(format) { + return extended_rule(form, words); + } + Some(match (format, words) { + (_, TexelWords::ColorPlane) => return None, + (PixelFormat::R8Snorm | PixelFormat::RG8Snorm | PixelFormat::RGBA8Snorm, _) => { + Rule::SnormMinimum { wide: false } + } + (PixelFormat::R16Snorm | PixelFormat::RG16Snorm | PixelFormat::RGBA16Snorm, _) => { + Rule::SnormMinimum { wide: true } + } + (PixelFormat::RGB9E5Float, _) => Rule::SharedExponent, + _ => return None, + }) +} + +/// The rule of an extended-range, padded or bfloat `form`'s texels held as `words`, or `None` +/// where it has none. +fn extended_rule(form: ExtendedRange, words: TexelWords) -> Option { Some(match (form, words) { (ExtendedRange::Bgr10 { .. }, TexelWords::Raw) => Rule::OnesOnTop, (ExtendedRange::Bgra10 { .. }, TexelWords::Raw) => Rule::Fields, @@ -300,9 +346,75 @@ fn rewritten( let hi = f.binary(BinOp::ShiftLeftLogical, hi, k16)?; f.binary(BinOp::BitwiseOr, lo, hi)? } + Rule::SnormMinimum { wide } => snorm_minimum(f, word, *wide)?, + Rule::SharedExponent => shared_exponent(f, word)?, }) } +/// `word`'s signed normalized codes, each byte (each 16-bit half where `wide`) at the minimum +/// code (`0x80`, `0x8000`) raised by one to the code above it: no carry leaves its lane. +fn snorm_minimum(f: &mut FunctionBuilder<'_>, word: Value, wide: bool) -> BResult { + let (bits, minimum) = match wide { + true => (16, 0x8000), + false => (8, 0x80), + }; + let (zero, mask, minimum) = ( + u32_value(f, 0)?, + u32_value(f, (1 << bits) - 1)?, + u32_value(f, minimum)?, + ); + let mut out = word; + for shift in (0..32).step_by(bits) { + let k = u32_value(f, shift)?; + let lane = f.binary(BinOp::ShiftRightLogical, word, k)?; + let lane = f.binary(BinOp::BitwiseAnd, lane, mask)?; + let least = f.binary(BinOp::IEqual, lane, minimum)?; + let one = u32_value(f, 1 << shift)?; + let raise = f.select(least, one, zero)?; + out = f.binary(BinOp::IAdd, out, raise)?; + } + Ok(out) +} + +/// The `RGB9E5Float` word `word` normalized: its three 9-bit mantissas (red at bit 0, green at +/// 9, blue at 18) shifted up by `s` and its exponent (bits 27 to 31) lowered by `s`, `s` the +/// fewest shifts that bring the largest mantissa to 256 or more, at most the exponent (all of it +/// for three zero mantissas). A word whose largest mantissa is 256 or more, or whose exponent is +/// 0, stays. +fn shared_exponent(f: &mut FunctionBuilder<'_>, word: Value) -> BResult { + let c = |f: &mut FunctionBuilder<'_>, v: u32| u32_value(f, v); + let mantissa = c(f, 0x1ff)?; + let (k9, k18, k27) = (c(f, 9)?, c(f, 18)?, c(f, 27)?); + let r = f.binary(BinOp::BitwiseAnd, word, mantissa)?; + let g = f.binary(BinOp::ShiftRightLogical, word, k9)?; + let g = f.binary(BinOp::BitwiseAnd, g, mantissa)?; + let b = f.binary(BinOp::ShiftRightLogical, word, k18)?; + let b = f.binary(BinOp::BitwiseAnd, b, mantissa)?; + let e = f.binary(BinOp::ShiftRightLogical, word, k27)?; + let largest = f.glsl(GlslOp::UMax, &[g, b])?; + let largest = f.glsl(GlslOp::UMax, &[r, largest])?; + // The shifts that bring the largest to 256: `8 - msb` below it, none at or above it, and the + // whole exponent for a zero. + let msb = f.glsl(GlslOp::FindUMsb, &[largest])?; + let (zero, k8, k31, k256) = (c(f, 0)?, c(f, 8)?, c(f, 31)?, c(f, 256)?); + let need = f.binary(BinOp::ISub, k8, msb)?; + let full = f.binary(BinOp::UGreaterThanEqual, largest, k256)?; + let need = f.select(full, zero, need)?; + let none = f.binary(BinOp::IEqual, largest, zero)?; + let need = f.select(none, k31, need)?; + let shift = f.glsl(GlslOp::UMin, &[need, e])?; + let r = f.binary(BinOp::ShiftLeftLogical, r, shift)?; + let g = f.binary(BinOp::ShiftLeftLogical, g, shift)?; + let b = f.binary(BinOp::ShiftLeftLogical, b, shift)?; + let e = f.binary(BinOp::ISub, e, shift)?; + let g = f.binary(BinOp::ShiftLeftLogical, g, k9)?; + let b = f.binary(BinOp::ShiftLeftLogical, b, k18)?; + let e = f.binary(BinOp::ShiftLeftLogical, e, k27)?; + let out = f.binary(BinOp::BitwiseOr, r, g)?; + let out = f.binary(BinOp::BitwiseOr, out, b)?; + f.binary(BinOp::BitwiseOr, out, e) +} + /// `x >> k` rounded to nearest, ties to even (`k` at most 31, `x` below `2^30`). fn shift_nearest_even(f: &mut FunctionBuilder<'_>, x: Value, k: Value) -> BResult { let (zero, one) = (u32_value(f, 0)?, u32_value(f, 1)?); @@ -528,19 +640,19 @@ fn binding_of(sym: &Symbol) -> Option { } } -/// The unused bits module of `device` for textures of `form` held as `words`: built with the +/// The unused bits module of `device` for textures of `format` held as `words`: built with the /// typed builder, checked by the owned verifier against the device's profile (requirements -/// included), serialized, and numbered with the fixed bindings of [`UnusedBitsModule`]. A form +/// included), serialized, and numbered with the fixed bindings of [`UnusedBitsModule`]. A format /// that has no such words ([`UnusedBitsModule::texel_bytes`] is `None`) is /// `NotImplemented(Format)`. pub fn unused_bits_module( device: &Device, - form: ExtendedRange, + format: PixelFormat, words: TexelWords, ) -> Result { let (Some(rule), Some(texel_bytes)) = ( - rule(form, words), - UnusedBitsModule::texel_bytes(form, words), + rule(format, words), + UnusedBitsModule::texel_bytes(format, words), ) else { return Err(Unsupported::not_implemented(Feature::Format).into()); }; diff --git a/crates/metal2vulkan/src/bind/unused_bits/tests.rs b/crates/metal2vulkan/src/bind/unused_bits/tests.rs index 0cd273de8..94cd46165 100644 --- a/crates/metal2vulkan/src/bind/unused_bits/tests.rs +++ b/crates/metal2vulkan/src/bind/unused_bits/tests.rs @@ -1,65 +1,127 @@ use super::{rule, typed_module, TexelWords, UnusedBitsModule, SHAPE, TILES, WORDS}; use crate::metal::format::ExtendedRange; +use crate::metal::PixelFormat; use crate::spirv::interp::{run, Buffer, Config, Order, Resources}; use crate::spirv::testing::{assert_valid, committed_profiles}; -/// Every form and the words it is held in. -fn forms() -> Vec<(ExtendedRange, TexelWords)> { +/// The signed normalized formats Metal's tile store rewrites. +const SNORM: [PixelFormat; 6] = [ + PixelFormat::R8Snorm, + PixelFormat::RG8Snorm, + PixelFormat::RGBA8Snorm, + PixelFormat::R16Snorm, + PixelFormat::RG16Snorm, + PixelFormat::RGBA16Snorm, +]; + +/// Every format and the words it is held in. +fn formats() -> Vec<(PixelFormat, TexelWords)> { let mut all = Vec::new(); - for srgb in [false, true] { - all.push((ExtendedRange::Bgr10 { srgb }, TexelWords::Raw)); - all.push((ExtendedRange::Bgra10 { srgb }, TexelWords::Raw)); - all.push((ExtendedRange::Planes { srgb }, TexelWords::Raw)); - all.push((ExtendedRange::Planes { srgb }, TexelWords::ColorPlane)); - } - for form in [ - ExtendedRange::R10X6, - ExtendedRange::Rg10X12, - ExtendedRange::R10X6Srgb, - ExtendedRange::Rg10X12Srgb, - ExtendedRange::R16Bfloat, - ExtendedRange::Rg16Bfloat, - ExtendedRange::Rgba16Bfloat, + for (plain, srgb) in [ + (PixelFormat::BGR10XR, PixelFormat::BGR10XRSRGB), + (PixelFormat::BGRA10XR, PixelFormat::BGRA10XRSRGB), + (PixelFormat::RGB10A82PXR10, PixelFormat::RGB10A82PXR10SRGB), ] { - all.push((form, TexelWords::Raw)); + all.push((plain, TexelWords::Raw)); + all.push((srgb, TexelWords::Raw)); + } + for format in [PixelFormat::RGB10A82PXR10, PixelFormat::RGB10A82PXR10SRGB] { + all.push((format, TexelWords::ColorPlane)); + } + for format in [ + PixelFormat::R10UnormX6, + PixelFormat::RG10UnormX12, + PixelFormat::R10UnormX6SRGB, + PixelFormat::RG10UnormX12SRGB, + PixelFormat::R16Bfloat, + PixelFormat::RG16Bfloat, + PixelFormat::RGBA16Bfloat, + PixelFormat::RGB9E5Float, + ] + .into_iter() + .chain(SNORM) + { + all.push((format, TexelWords::Raw)); } all } -/// The module of `form` held as `words`. -fn module(form: ExtendedRange, words: TexelWords) -> crate::spirv::ir::TypedModule { - let rule = rule(form, words).expect("a rule"); - let bytes = UnusedBitsModule::texel_bytes(form, words).expect("texel bytes"); +/// The module of `format` held as `words`. +fn module(format: PixelFormat, words: TexelWords) -> crate::spirv::ir::TypedModule { + let rule = rule(format, words).expect("a rule"); + let bytes = UnusedBitsModule::texel_bytes(format, words).expect("texel bytes"); typed_module(&rule, bytes).expect("module") } #[test] fn the_unused_bits_kernel_is_valid_on_every_committed_profile() { for (_, p) in committed_profiles().expect("profiles") { - for (form, words) in forms() { - assert_valid(module(form, words), &p); + for (format, words) in formats() { + assert_valid(module(format, words), &p); } } } -/// Only a two-plane format has color-plane words. +/// Only a two-plane format has color-plane words, and a format Metal's tile store keeps has no +/// rule. #[test] fn only_a_two_plane_format_has_color_plane_words() { - for (form, words) in forms() { - assert!(rule(form, words).is_some(), "{form:?} {words:?}"); - let plane = rule(form, TexelWords::ColorPlane).is_some(); - assert_eq!( - plane, - matches!(form, ExtendedRange::Planes { .. }), - "{form:?}" + for (format, words) in formats() { + assert!(rule(format, words).is_some(), "{format:?} {words:?}"); + let plane = rule(format, TexelWords::ColorPlane).is_some(); + let two_planes = matches!( + ExtendedRange::of(format), + Some(ExtendedRange::Planes { .. }) ); + assert_eq!(plane, two_planes, "{format:?}"); + } + for format in [ + PixelFormat::RGBA8Unorm, + PixelFormat::RGBA16Float, + PixelFormat::RG11B10Float, + ] { + assert!(rule(format, TexelWords::Raw).is_none(), "{format:?}"); + assert!(UnusedBitsModule::texel_bytes(format, TexelWords::Raw).is_none()); } } -/// Metal's store of `word`, the `odd` word of its texel, of `form` held as `words` (the module +/// Metal's store of an `RGB9E5Float` word (the module docs), computed here apart from the +/// kernel: its value's own encoding, the exponent the least that holds the largest mantissa +/// below 512, at least 0. +fn shared_exponent(word: u32) -> u32 { + let m = [word & 0x1ff, (word >> 9) & 0x1ff, (word >> 18) & 0x1ff]; + let mut e = word >> 27; + let mut m = m; + while e > 0 && m.iter().all(|&x| x < 256) { + m = m.map(|x| x << 1); + e -= 1; + } + m[0] | m[1] << 9 | m[2] << 18 | e << 27 +} + +/// Metal's store of `word`, the `odd` word of its texel, of `format` held as `words` (the module /// docs), computed here apart from the kernel. -fn stored(form: ExtendedRange, words: TexelWords, word: u32, odd: bool) -> u32 { +fn stored(format: PixelFormat, words: TexelWords, word: u32, odd: bool) -> u32 { let codes = 0x3fff_ffff; + let Some(form) = ExtendedRange::of(format) else { + if format == PixelFormat::RGB9E5Float { + return shared_exponent(word); + } + let lane = match format { + PixelFormat::R16Snorm | PixelFormat::RG16Snorm | PixelFormat::RGBA16Snorm => 16, + _ => 8, + }; + let mask = (1u32 << lane) - 1; + return (0..32).step_by(lane).fold(0, |out, shift| { + let code = (word >> shift) & mask; + let code = if code == 1 << (lane - 1) { + code + 1 + } else { + code + }; + out | code << shift + }); + }; match (form, words) { (ExtendedRange::Bgr10 { .. }, _) => word | !codes, (ExtendedRange::Planes { .. }, TexelWords::Raw) if odd => word, @@ -90,16 +152,16 @@ impl Rng { } } -/// Run the kernel of `form` held as `words` over `bytes` with the mask `tiles` and the shape +/// Run the kernel of `format` held as `words` over `bytes` with the mask `tiles` and the shape /// `shape`, in `groups` workgroups, both invocation orders. fn rewritten( - (form, words): (ExtendedRange, TexelWords), + (format, words): (PixelFormat, TexelWords), bytes: &[u8], tiles: &[u32], shape: [u8; 16], groups: u32, ) -> Vec { - let m = module(form, words); + let m = module(format, words); let mut out = Vec::new(); for order in [Order::Forward, Order::Reverse] { let res = Resources { @@ -136,7 +198,7 @@ fn rewritten( /// A region of 70 texels a row (rows padded to a word), 40 rows a layer, 2 layers, bound from /// row 3 on, under a mask of every third tile: each word of a set tile's texel takes Metal's -/// store, every other word stays, for every form, and invocations past the words write nothing. +/// store, every other word stays, for every format, and invocations past the words write nothing. #[test] fn each_word_of_a_masked_tile_takes_metals_store_and_no_other_changes() { let (columns, layer_rows, layers, first_row) = (70u32, 40u32, 2u32, 3u32); @@ -151,16 +213,25 @@ fn each_word_of_a_masked_tile_takes_metals_store_and_no_other_changes() { }) .collect(); let set = |tile: u32| tile < tiles && mask[(tile / 32) as usize] >> (tile % 32) & 1 == 1; - for (form, words) in forms() { - let texel = UnusedBitsModule::texel_bytes(form, words).unwrap(); + for (format, words) in formats() { + let texel = UnusedBitsModule::texel_bytes(format, words).unwrap(); let row_words = (columns * texel).div_ceil(4); let rows = layers * layer_rows - first_row; let mut rng = Rng(u64::from(texel) << 32 | u64::from(row_words)); - let before: Vec = (0..rows * row_words).map(|_| rng.next()).collect(); + // Random words, a few holding a signed normalized minimum code in a lane, which random + // bits rarely give a 16-bit lane. + let before: Vec = (0..rows * row_words) + .map(|i| match (i % 7, rng.next()) { + (0, w) => w & 0xffff_0000 | 0x8000, + (1, w) => w & 0x0000_ffff | 0x8000_0000, + (2, w) => w & 0xffff_ff00 | 0x80, + (_, w) => w, + }) + .collect(); let bytes: Vec = before.iter().flat_map(|w| w.to_le_bytes()).collect(); let groups = (before.len() as u32).div_ceil(UnusedBitsModule::LOCAL_SIZE) + 1; let shape = UnusedBitsModule::shape(row_words, first_row, layer_rows, tiles_per_row); - let after = rewritten((form, words), &bytes, &mask, shape, groups); + let after = rewritten((format, words), &bytes, &mask, shape, groups); let (mut changed, mut kept) = (0, 0); for (i, (&word, got)) in before.iter().zip(after.chunks(4)).enumerate() { let i = i as u32; @@ -170,20 +241,20 @@ fn each_word_of_a_masked_tile_takes_metals_store_and_no_other_changes() { let x = 4 * w / texel; let tile = (layer * tile_rows + y / 32) * tiles_per_row + x / 32; let want = match set(tile) { - true => stored(form, words, word, w % 2 == 1), + true => stored(format, words, word, w % 2 == 1), false => word, }; let got = u32::from_le_bytes([got[0], got[1], got[2], got[3]]); assert_eq!( got, want, - "{form:?} {words:?} word {i} (row {row}, word {w}, tile {tile}): {word:08x}" + "{format:?} {words:?} word {i} (row {row}, word {w}, tile {tile}): {word:08x}" ); match got == word { true => kept += 1, false => changed += 1, } } - assert!(changed > 0 && kept > 0, "{form:?} {words:?}"); + assert!(changed > 0 && kept > 0, "{format:?} {words:?}"); } } @@ -197,12 +268,13 @@ fn every_padded_word_takes_its_code_s_load_code_with_its_low_six_bits_zeroed() { let bytes: Vec = halves.iter().flat_map(|h| h.to_le_bytes()).collect(); let words = (bytes.len() / 4) as u32; let groups = words.div_ceil(UnusedBitsModule::LOCAL_SIZE) + 1; - for form in [ - ExtendedRange::R10X6, - ExtendedRange::Rg10X12, - ExtendedRange::R10X6Srgb, - ExtendedRange::Rg10X12Srgb, + for format in [ + PixelFormat::R10UnormX6, + PixelFormat::RG10UnormX12, + PixelFormat::R10UnormX6SRGB, + PixelFormat::RG10UnormX12SRGB, ] { + let form = ExtendedRange::of(format).expect("a padded form"); let moved = (0..1024).filter(|&c| form.load_code(c) != Some(c)).count(); let want_moved = match form { ExtendedRange::R10X6Srgb => 23, @@ -218,12 +290,12 @@ fn every_padded_word_takes_its_code_s_load_code_with_its_low_six_bits_zeroed() { }) .collect(); // One row of every word: its texels' tiles all set. - let texel = UnusedBitsModule::texel_bytes(form, TexelWords::Raw).unwrap(); + let texel = UnusedBitsModule::texel_bytes(format, TexelWords::Raw).unwrap(); let tiles_per_row = (4 * words / texel).div_ceil(32); let mask = vec![u32::MAX; tiles_per_row.div_ceil(32) as usize]; let shape = UnusedBitsModule::shape(words, 0, 1, tiles_per_row); assert_eq!( - rewritten((form, TexelWords::Raw), &bytes, &mask, shape, groups), + rewritten((format, TexelWords::Raw), &bytes, &mask, shape, groups), want, "{form:?}" ); @@ -240,11 +312,12 @@ fn every_bfloat_code_takes_its_load_code() { let bytes: Vec = codes.iter().flat_map(|h| h.to_le_bytes()).collect(); let words = (bytes.len() / 4) as u32; let groups = words.div_ceil(UnusedBitsModule::LOCAL_SIZE) + 1; - for form in [ - ExtendedRange::R16Bfloat, - ExtendedRange::Rg16Bfloat, - ExtendedRange::Rgba16Bfloat, + for format in [ + PixelFormat::R16Bfloat, + PixelFormat::RG16Bfloat, + PixelFormat::RGBA16Bfloat, ] { + let form = ExtendedRange::of(format).expect("a bfloat form"); let load = |c: u16| form.load_code(u32::from(c)).expect("a bfloat code"); let moved = codes.iter().filter(|&&c| load(c) != u32::from(c)).count(); assert_eq!(moved, 56_829, "{form:?}"); @@ -267,22 +340,113 @@ fn every_bfloat_code_takes_its_load_code() { .iter() .flat_map(|&c| (u16::try_from(load(c)).expect("a code")).to_le_bytes()) .collect(); - let texel = UnusedBitsModule::texel_bytes(form, TexelWords::Raw).unwrap(); + let texel = UnusedBitsModule::texel_bytes(format, TexelWords::Raw).unwrap(); let tiles_per_row = (4 * words / texel).div_ceil(32); let mask = vec![u32::MAX; tiles_per_row.div_ceil(32) as usize]; let shape = UnusedBitsModule::shape(words, 0, 1, tiles_per_row); assert_eq!( - rewritten((form, TexelWords::Raw), &bytes, &mask, shape, groups), + rewritten((format, TexelWords::Raw), &bytes, &mask, shape, groups), want, "{form:?}" ); } } +/// Every 16-bit value of a signed normalized format's word takes Metal's store under a mask of +/// every tile: a lane at the minimum code (`0x80` of an 8-bit format's byte, `0x8000` of a 16-bit +/// one's half) becomes the code above it, every other lane stays (an 8-bit format's 256 minimum +/// pairs of bytes move, a 16-bit one's one value). +#[test] +fn every_signed_normalized_minimum_code_is_raised_to_the_code_above_it() { + let halves: Vec = (0..=u16::MAX).collect(); + let bytes: Vec = halves.iter().flat_map(|h| h.to_le_bytes()).collect(); + let words = (bytes.len() / 4) as u32; + let groups = words.div_ceil(UnusedBitsModule::LOCAL_SIZE) + 1; + for format in SNORM { + let wide = matches!( + format, + PixelFormat::R16Snorm | PixelFormat::RG16Snorm | PixelFormat::RGBA16Snorm + ); + let want: Vec = halves + .iter() + .flat_map(|&h| { + let raised = match wide { + true if h == 0x8000 => 0x8001, + true => h, + false => u16::from_le_bytes(h.to_le_bytes().map(|b| match b { + 0x80 => 0x81, + b => b, + })), + }; + raised.to_le_bytes() + }) + .collect(); + let moved = halves + .iter() + .zip(want.chunks(2)) + .filter(|(h, w)| h.to_le_bytes() != [w[0], w[1]]) + .count(); + assert_eq!(moved, if wide { 1 } else { 511 }, "{format:?}"); + let texel = UnusedBitsModule::texel_bytes(format, TexelWords::Raw).unwrap(); + let tiles_per_row = (4 * words / texel).div_ceil(32); + let mask = vec![u32::MAX; tiles_per_row.div_ceil(32) as usize]; + let shape = UnusedBitsModule::shape(words, 0, 1, tiles_per_row); + assert_eq!( + rewritten((format, TexelWords::Raw), &bytes, &mask, shape, groups), + want, + "{format:?}" + ); + } +} + +/// Each `RGB9E5Float` word of every exponent and every largest mantissa (each mantissa's own +/// value, the others random below it) takes Metal's store under a mask of every tile: normalized +/// where its largest mantissa is below 256 under an exponent above 0, as the word Metal's pass left +/// for `1 | 2 << 9 | 3 << 18 | 20 << 27` (an Apple M3 Max under macOS 27.0.1), kept otherwise. +#[test] +fn every_unnormalized_shared_exponent_word_is_normalized() { + // The M3 Max's answer: the largest mantissa 3 shifted up seven times, the exponent 13. + let metal = 1 << 7 | 2 << 16 | 3 << 25 | 13 << 27; + assert_eq!(shared_exponent(1 | 2 << 9 | 3 << 18 | 20 << 27), metal); + let mut rng = Rng(0x9e5); + let mut words = Vec::new(); + for e in 0..32u32 { + for largest in 0..512u32 { + let lane = rng.next() % 3; + let m: [u32; 3] = std::array::from_fn(|k| { + if k as u32 == lane { + largest + } else { + rng.next() % (largest + 1) + } + }); + words.push(m[0] | m[1] << 9 | m[2] << 18 | e << 27); + } + } + let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let want: Vec = words + .iter() + .flat_map(|&w| shared_exponent(w).to_le_bytes()) + .collect(); + let moved = words.iter().filter(|&&w| shared_exponent(w) != w).count(); + assert_eq!( + moved, + 31 * 256, + "every word below 256 under an exponent above 0" + ); + let n = words.len() as u32; + let groups = n.div_ceil(UnusedBitsModule::LOCAL_SIZE) + 1; + let tiles_per_row = n.div_ceil(32); + let mask = vec![u32::MAX; tiles_per_row.div_ceil(32) as usize]; + let shape = UnusedBitsModule::shape(n, 0, 1, tiles_per_row); + let format = (PixelFormat::RGB9E5Float, TexelWords::Raw); + assert_eq!(rewritten(format, &bytes, &mask, shape, groups), want); +} + /// A mask of no word leaves every word, and a tile past the mask's words reads as unset. #[test] fn a_tile_past_the_mask_is_not_rewritten() { - let form = (ExtendedRange::Bgr10 { srgb: false }, TexelWords::Raw); + let form = (PixelFormat::BGR10XR, TexelWords::Raw); // Two layers of one row of 64 texels, 40 tiles a row: the first row's tiles 0 and 1 are the // mask's one word's bits 0 and 1 (tile 0 set), and the second's, 40 and 41, lie past it. let bytes = vec![0u8; 4 * 128]; diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index 92963135c..c6a30253d 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -1416,6 +1416,19 @@ pub enum DriverFact { /// against 2.56 to 2.58 ms at one. Measured no faster, so not listed: NVIDIA's 615.71.09 on /// the RTX 3090 (0.112 against 0.113 ms at 32 layers, 0.028 against 0.030 at one). MultisampledDepthFasterOutOfGeneral, + /// A render pass that loads a single-sampled colour attachment of a signed normalized format + /// or of `E5B9G9R9_UFLOAT_PACK32` and draws stores each 32x32 tile a draw reaches back through + /// its texels' values, as Metal's pass does, the texels no fragment writes too: a channel's + /// minimum code (-128, or -32768), which reads as -1.0 as the code above it does, is stored as + /// that code (-127, -32767), and a shared-exponent word whose largest mantissa is below 256 + /// under an exponent above 0 is stored normalized. Vulkan's load and store keep the bytes no + /// draw writes. MoltenVK records the render pass as a Metal render pass whose attachments + /// Metal's own load and store actions load and store + /// (`MVKAttachmentDescription::getMTLStoreAction` at 1.4.1), so the GPU's tile store is + /// Metal's by construction. On a driver with it the runtime announces no `snorm-minimum-kept` + /// or `shared-exponent-kept`, and its exact tile store (`TileStorePolicy::Exact`) adds no load + /// pass for such an attachment. + TileStoreIsMetals, } impl DriverFact { @@ -1821,6 +1834,20 @@ const DYNAMIC_RESTART_WARNING: DriverDiagnostic = DriverDiagnostic { /// 38. MoltenVK's code on every GPU, so the row names no vendor; a defect fact, taken at every /// release. /// +/// `TileStoreIsMetals`, measured by +/// `runtime_lane::snorm_tile_store::a_drawing_pass_keeps_a_snorm_minimum_code_and_says_so` (a +/// 4x4 target of each of the six signed normalized colour formats holding a channel's minimum code +/// in every channel, loaded and drawn over by a full-screen triangle that writes no channel): +/// MoltenVK 1.4.1 on the M3 Max under macOS 27.0.1 ([`APPLE_M4`]'s identity) stored the code +/// above it in every texel, as plain Metal's pass does on that GPU. Its `RGB9E5Float` twin +/// (`a_drawing_pass_keeps_an_unnormalized_shared_exponent_word_and_says_so`: the word `1 | 2 << 9 +/// | 3 << 18 | 20 << 27` in every texel) is Metal's by the same construction: MoltenVK renders +/// `E5B9G9R9_UFLOAT_PACK32` as a Metal `RGB9E5Float` attachment, whose pass plain Metal measured +/// normalizing such a word on that GPU. One row for Apple's GPUs, by +/// construction (the fact's docs). Measured not to have it, so not listed (every texel kept its +/// code): RADV, Mesa 26.0.8, on the Radeon 780M and the RX 7900 XTX; ANV, Mesa 26.2.4, on the +/// Iris Xe (RPL-P). +/// /// `DontCareStoreIsOneOfMetals`: measured by `runtime_lane::dont_care_stores`, every texel of each /// of its twelve kept cases the earlier one or the stored one, none other: at 66ffe6775, RADV, Mesa /// row, ANV, Mesa 26.2.4, on the Iris Xe (RPL-P). Not listed: NVIDIA's 615.71.09, whose RTX 3080 @@ -2311,6 +2338,14 @@ pub(crate) const MEASURED: &[Measured] = &[ device: Some(INTEL_IRIS_XE_RPL_P), first: mesa(26, 2, 4), last: mesa(26, 2, 4), + }, + Measured { + fact: DriverFact::TileStoreIsMetals, + driver: DriverId::MOLTENVK, + vendor: Some(APPLE_VENDOR_ID), + device: None, + first: moltenvk(1, 4, 1), + last: moltenvk(1, 4, 1), }, device: Some(INTEL_IRIS_XE_RPL_P), first: mesa(26, 2, 4), diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs index 655a3758d..280ea5c88 100644 --- a/crates/metal2vulkan/src/device/policy.rs +++ b/crates/metal2vulkan/src/device/policy.rs @@ -63,7 +63,11 @@ pub struct DevicePolicy { /// values exactly. The runtime's choice alone: no emitted code changes. pub decoded_texels: DecodedTexelsPolicy, /// emitted code changes. - pub padded_reads: PaddedReadsPolicy, + /// Whether a render pass that loads a signed normalized or `RGB9E5Float` color attachment and + /// draws keeps the texels its draws do not write as the device's load and store leave them + /// (the default), or as Metal's tile store writes them back in the tiles a draw reaches. The + /// runtime's choice alone: no emitted code changes. + pub tile_store: TileStorePolicy, } impl DevicePolicy { @@ -90,6 +94,7 @@ impl DevicePolicy { rounding_order: RoundingOrderPolicy::Native, half_blend: HalfBlendPolicy::Device, decoded_texels: DecodedTexelsPolicy::Compact, + tile_store: TileStorePolicy::Device, }; /// This policy with Metal's answer wherever the choices offer it: its maths functions, @@ -98,8 +103,7 @@ impl DevicePolicy { /// NaN and minimum and maximum ([`NanMinMaxPolicy::Exact`]), its rounding order /// ([`RoundingOrderPolicy::Exact`]), its 16-bit float blend of a `half` output /// ([`HalfBlendPolicy::Exact`]), its filter of a two-plane YCbCr texture - /// ([`YCbCrFilterPolicy::Exact`]), and the bytes between a texture's rows that no first move - /// of an image over them reaches ([`PaddedReadsPolicy::Shadow`]). Sampling and every other + /// as written ([`HeapCompressionPolicy::Uncompressed`]), each command buffer seen complete /// field are kept. pub const fn exact_answers(self) -> DevicePolicy { DevicePolicy { @@ -111,6 +115,7 @@ impl DevicePolicy { rounding_order: RoundingOrderPolicy::Exact, half_blend: HalfBlendPolicy::Exact, decoded_texels: DecodedTexelsPolicy::Exact, + tile_store: TileStorePolicy::Exact, ..self } } @@ -412,4 +417,32 @@ pub enum DecodedTexelsPolicy { /// device samples, filters and copies into the format (else the compact texels, announced). Exact, } + +/// What a render pass that loads a single-sampled color attachment of a signed normalized format +/// (`R8Snorm`, `RG8Snorm`, `RGBA8Snorm`, `R16Snorm`, `RG16Snorm`, `RGBA16Snorm`) or of +/// `RGB9E5Float`, stores it and draws leaves in the texels its draws do not write. An Apple GPU +/// writes each 32 x 32 tile a draw reaches back through its texels' values (an Apple M3 Max under +/// macOS 27.0.1): a channel's minimum code (-128, or -32768), which reads as -1.0 as the code above +/// it does, is stored as that code (-127, -32767), and an `RGB9E5Float` word whose largest +/// mantissa is below 256 under an exponent above 0 is stored normalized (its mantissas shifted up +/// as its exponent steps down, to 0 at most). No Metal write leaves such a code or word: only +/// uploaded or copied bytes hold one. The extended-range, padded 10-bit and bfloat attachments' +/// tile store, the runtime's load pass, runs under either value. The runtime's choice alone: no +/// emitted code changes. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum TileStorePolicy { + /// The device's load and store (the default): such a texel keeps its code or word, announced + /// `snorm-minimum-kept` or `shared-exponent-kept` at each draw in such a pass. + #[default] + Device, + /// The runtime's load pass rewrites such an attachment's texels in the tiles the pass's draws + /// reach, as Metal's tile store leaves them, before the pass (as it does an extended-range + /// attachment's): a copy of the render area into a scratch buffer and back, with a dispatch. + /// An attachment the load pass cannot take (a texture held as a shadow, a sparse one, or one + /// whose image the device does not copy both ways) keeps the device's, announced as under + /// [`Device`](Self::Device). + Exact, +} } diff --git a/crates/metal2vulkan/src/device/tests/driver_facts.rs b/crates/metal2vulkan/src/device/tests/driver_facts.rs index 1b15f41a7..6b7758960 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -531,6 +531,7 @@ const LINEAR_UNINITIALIZED: DriverFact = DriverFact::LinearTilingFeaturesUniniti const STALL: DriverFact = DriverFact::SemaphoreOperationsStallSubmits; const SAMPLED_HIZ: DriverFact = DriverFact::SampledDepthKeepsHiZ; const MSAA_DEPTH: DriverFact = DriverFact::MultisampledDepthFasterOutOfGeneral; +const TILE_STORE: DriverFact = DriverFact::TileStoreIsMetals; /// Every committed profile's driver has exactly its measured facts (on a measured identity those /// its rows name, on any other its driver's defects alone). A profile of a measured identity: the @@ -544,10 +545,9 @@ const MSAA_DEPTH: DriverFact = DriverFact::MultisampledDepthFasterOutOfGeneral; /// test keeps denormals and compares magnitudes as Metal's (the M4's identity: the latter measured /// on the M3 Max, the M4's by construction); ANV's compressed images hide aliased writes and its /// host-transfer images keep their bytes; a pass the interlock would split runs -/// faster whole on the RPL-S and no slower split on the M3 Max (under macOS 26.7, and under 27 the -/// M4's identity), the 780M, the RPL-P and the RTX 5080 Laptop GPU; MoltenVK warns of a dynamic -/// restart, compiles its fill per command pool, stores `DONT_CARE` as Metal's own and orders its -/// timestamps across queues; BC1 to BC3 decode as Metal's on the 780M and MoltenVK, BC4 and BC5 on +/// restart, compiles its fill per command pool, stores `DONT_CARE` as Metal's own, orders its +/// timestamps across queues and stores a signed normalized minimum code and an `E5B9G9R9` word as +/// Metal's tile store does; BC1 to BC3 decode as Metal's on the 780M and MoltenVK, BC4 and BC5 on /// MoltenVK; NVIDIA's reads a depth rendered at custom sample positions at the standard ones; ANV's /// first sparse resource waits for every queue; BC6H decodes as Metal's on the 780M, the RPL-P, /// lavapipe 26.0.8, both MoltenVK GPUs and the RTX 5080 Laptop GPU, and BC7 on the same but @@ -631,6 +631,7 @@ fn the_committed_profiles_drivers_have_their_facts() { BC7, SCARCE_POOLS, LINEAR_UNINITIALIZED, + TILE_STORE, ], ), ( @@ -655,6 +656,7 @@ fn the_committed_profiles_drivers_have_their_facts() { BC7, SCARCE_POOLS, LINEAR_UNINITIALIZED, + TILE_STORE, ], ), ("nvidia-pascal-linux", vec![PLANES]), diff --git a/crates/metal2vulkan/src/tests/fast_paths.rs b/crates/metal2vulkan/src/tests/fast_paths.rs index e11929abe..4097914a2 100644 --- a/crates/metal2vulkan/src/tests/fast_paths.rs +++ b/crates/metal2vulkan/src/tests/fast_paths.rs @@ -70,6 +70,7 @@ fn choices() -> Vec { rounding_order: _, half_blend: _, decoded_texels: _, + tile_store: _, } = p; vec![ choice!(p.framebuffer_fetch: FramebufferFetchPolicy { RequireOrdered, AcceptUnordered }), @@ -83,6 +84,7 @@ fn choices() -> Vec { choice!(p.rounding_order: RoundingOrderPolicy { Native, Exact }), choice!(p.half_blend: HalfBlendPolicy { Device, Exact }), choice!(p.decoded_texels: DecodedTexelsPolicy { Compact, Exact }), + choice!(p.tile_store: TileStorePolicy { Device, Exact }), ] } @@ -394,6 +396,24 @@ fn the_runtime_s_padded_reads_choice_keys_no_profile() { assert_eq!(alias.len(), shadow.len()); for ((stem, a), (other, s)) in alias.iter().zip(&shadow) { assert_eq!(stem, other); +/// The runtime's choice of a loaded attachment's tile store (`tile_store`) moves no committed +/// profile's fingerprint: no profile carries it, so no translation follows it. +#[test] +fn the_runtime_s_tile_store_choice_keys_no_profile() { + use crate::spirv::testing::committed_profiles_with; + let device = committed_profiles_with(DevicePolicy::UNTRUSTED).expect("profiles"); + let exact = committed_profiles_with(DevicePolicy { + tile_store: TileStorePolicy::Exact, + ..DevicePolicy::UNTRUSTED + }) + .expect("profiles"); + assert_eq!(device.len(), exact.len()); + for ((stem, d), (other, e)) in device.iter().zip(&exact) { + assert_eq!(stem, other); + assert_eq!(d.fingerprint(), e.fingerprint(), "{stem}"); + } +} + /// The runtime's choice of a carried texture's decoded twin (`decoded_texels`) moves no committed /// profile's fingerprint: no profile carries it, so no translation follows it. #[test] diff --git a/crates/metal2vulkan/src/tests/owned_divisions.rs b/crates/metal2vulkan/src/tests/owned_divisions.rs index 958a418de..9162e181b 100644 --- a/crates/metal2vulkan/src/tests/owned_divisions.rs +++ b/crates/metal2vulkan/src/tests/owned_divisions.rs @@ -18,7 +18,8 @@ use crate::device::{Device, DevicePolicy}; use crate::error::{Error, Feature}; use crate::metal::format::ExtendedRange; use crate::metal::{ - TessellationFactorStepFunction as Step, TessellationPartitionMode as Partition, Winding, + PixelFormat, TessellationFactorStepFunction as Step, TessellationPartitionMode as Partition, + Winding, }; use crate::pipeline::interface::PatchDomain; use crate::spirv::testing::{all_ones_divisions, committed_descriptions}; @@ -46,6 +47,31 @@ const EXTENDED: [ExtendedRange; 13] = [ ExtendedRange::Rgba16Bfloat, ]; +/// Every format a render pass's load pass rewrites (`bind::unused_bits_module`): the +/// extended-range, padded and bfloat formats, the signed normalized formats and `RGB9E5Float`. +const UNUSED_BITS: [PixelFormat; 20] = [ + PixelFormat::BGR10XR, + PixelFormat::BGR10XRSRGB, + PixelFormat::BGRA10XR, + PixelFormat::BGRA10XRSRGB, + PixelFormat::RGB10A82PXR10, + PixelFormat::RGB10A82PXR10SRGB, + PixelFormat::R10UnormX6, + PixelFormat::RG10UnormX12, + PixelFormat::R10UnormX6SRGB, + PixelFormat::RG10UnormX12SRGB, + PixelFormat::R16Bfloat, + PixelFormat::RG16Bfloat, + PixelFormat::RGBA16Bfloat, + PixelFormat::R8Snorm, + PixelFormat::RG8Snorm, + PixelFormat::RGBA8Snorm, + PixelFormat::R16Snorm, + PixelFormat::RG16Snorm, + PixelFormat::RGBA16Snorm, + PixelFormat::RGB9E5Float, +]; + fn modules() -> Vec { let mut out: Vec = Vec::new(); macro_rules! plain { @@ -101,10 +127,12 @@ fn modules() -> Vec { format!("extended_shadow_module({form:?})"), Box::new(move |d| Ok(bind::extended_shadow_module(d, form)?.spirv)), ); + } + for format in UNUSED_BITS { for words in [TexelWords::Raw, TexelWords::ColorPlane] { push( - format!("unused_bits_module({form:?}, {words:?})"), - Box::new(move |d| Ok(bind::unused_bits_module(d, form, words)?.spirv)), + format!("unused_bits_module({format:?}, {words:?})"), + Box::new(move |d| Ok(bind::unused_bits_module(d, format, words)?.spirv)), ); } } diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 171aa3d0c..498b2863a 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -230,6 +230,7 @@ surface! { enum RoundingOrderPolicy N; enum HalfBlendPolicy N; enum DecodedTexelsPolicy N; + enum TileStorePolicy N; struct DeviceProfile O; struct SpirvValidation N; struct EnabledCaps N; diff --git a/docs/API.md b/docs/API.md index 89a01ca50..0d8841226 100644 --- a/docs/API.md +++ b/docs/API.md @@ -95,15 +95,14 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: [FAST-PATHS.md](FAST-PATHS.md) lists every choice, its bound and the measured cost of its exact form. On MoltenVK on an Apple GPU, whose sampler and `float` functions are Metal's own, most of these choices change nothing. -- **An image over a padded texture that only reads** (`PaddedReadsPolicy::Alias`, the runtime's - choice; no pipeline differs). A texture over a buffer whose rows lie with bytes between them, - and whose usage holds no `RenderTarget`, `ShaderWrite`, `ShaderAtomic` or block writes, is an - image over the buffer's bytes at its row pitch where the device lays one there. Its subresources - hold the bytes between the rows, which its first move may rewrite: the host keeps them across it - with the texels (below), so a CPU write to them while it keeps them is undone, once per image - (FAST-PATHS.md's known gaps). - `padded_reads = PaddedReadsPolicy::Shadow`, which - `exact_answers()` selects, makes it the runtime's shadow, copied in before each use. +- **The device's load and store of a signed normalized or `RGB9E5Float` attachment** + (`TileStorePolicy::Device`, the runtime's choice; no pipeline differs). A render pass that loads + one and draws keeps the texels its draws do not write as they were, where Metal's tile store + writes a channel's minimum code back as the code above it and an unnormalized shared-exponent + word normalized, announced as `snorm-minimum-kept` and `shared-exponent-kept`. + `tile_store = TileStorePolicy::Exact`, which `exact_answers()` selects, rewrites them before + the pass as Metal's store leaves them, through the extended-range attachments' load pass. On + MoltenVK the pass is a Metal pass and stores them as Metal's under either value. Loops run as written: no execution bound is translated in. @@ -1581,6 +1580,18 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. BGRA10_XR's low six bits of each field to zeros, the two-plane color word's top two bits to zeros) and clamps BGRA10_XR's alpha code to [384, 894]: a texel whose bytes no Metal write left (uploaded bytes, or an alpha code past 894) keeps bytes Metal's pass would change. +- `metal2vulkan-degrade-snorm-minimum-kept` (precision). `SnormMinimumKept`: A draw in a render pass + that loads a single-sampled color attachment of a signed normalized format (`R8Snorm`, `RG8Snorm`, + `RGBA8Snorm`, `R16Snorm`, `RG16Snorm`, `RGBA16Snorm`) and does not discard it at the store. Cost: + the texels the pass's draws do not write keep their bytes; Metal's pass rewrites a channel's + minimum code (-128, or -32768 for 16 bits) as the code above it (-127, -32767) in each tile a draw + reaches: a texel whose bytes no Metal write left (uploaded or copied bytes) keeps a code Metal's + pass would change. Not on a driver whose pass stores the codes as Metal's + (`DriverFact::TileStoreIsMetals`: MoltenVK on Apple's GPUs, whose pass is a Metal pass), nor under + `TileStorePolicy::Exact` for an attachment the load pass rewrites as Metal's store leaves it. + change, of the same value. Not on a driver whose pass stores the words as Metal's + (`DriverFact::TileStoreIsMetals`), nor under `TileStorePolicy::Exact` for an attachment the load + pass rewrites as Metal's store leaves it. - `metal2vulkan-degrade-two-plane-buffer-blit` (precision). `TwoPlaneBufferBlit`: A blit between a buffer and a level of `RGB10A8_2P_XR10` or its sRGB twin whose width is not a multiple of 4: it moves the texels at the rows the texture holds them in, where Metal's blit addresses the level's @@ -1654,15 +1665,17 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. older release stops. - `metal2vulkan-degrade-unreached-tiles-rewritten` (precision). `UnreachedTilesRewritten`: A render pass that loads a color attachment of an extended-range or padded 10-bit format (`BGR10_XR`, - `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`, `RG10Unorm_X12` and their sRGB twins), stores it - and draws, whose load pass rewrites every 32 x 32 tile of its render area: Metal's pass rewrites + `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`, `RG10Unorm_X12` and their sRGB twins), or under + `TileStorePolicy::Exact` of a signed normalized format or `RGB9E5Float`, stores it and draws, + whose load pass rewrites every 32 x 32 tile of its render area: Metal's pass rewrites only the tiles a draw's primitives reach, and every tile only where a color attachment of the pass is cleared and stored (announced where none is, or where the pass renders more than one layer). Cost: in tiles no draw reaches the pass rewrites what Metal keeps: the unused bits made canonical (BGR10_XR's bits 30 and 31 ones, BGRA10_XR's low six bits of each field and the two-plane color word's top two bits zeros) and BGRA10_XR alpha codes clamped to [384, 894], so an out-of-range raw - alpha reads back changed, and a padded word's low six bits zeroed (an sRGB twin's code moved - through Metal's table); the tiles a draw reaches are Metal's. + alpha reads back changed, a padded word's low six bits zeroed (an sRGB twin's code moved through + Metal's table) and, under the exact tile store, a signed normalized minimum code raised and an + RGB9E5Float word normalized; the tiles a draw reaches are Metal's. - `metal2vulkan-degrade-zero-layer-map-after-release` (precision). `ZeroLayerMapAfterRelease`: A draw in a render pass over a rasterization-rate map of no layers that was made after the device released a map of one or more layers. Cost: the draws write nothing, where Metal draws rows of the diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 597f2f5de..713a0592c 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -347,6 +347,12 @@ driver's. Each is open work. A source-over survey on the M3 fits the 8-bit model to the 10-bit unorm and 8-bit snorm formats (with their clamps), and shows the 16-bit norms and `RGBA32Float` blending in `float` even for a `half4` output; their factor sets are not measured. +- **A blended signed normalized attachment on lavapipe.** lavapipe blends no snorm format + (`R8Snorm`, `RG8Snorm`, `RGBA8Snorm`, `R16Snorm`, `RG16Snorm`, `RGBA16Snorm`: no + `COLOR_ATTACHMENT_BLEND`), so a pipeline that blends one is refused as the device lacking the + format. The function's own blend over the attachment's input attachment, as an extended-range + attachment takes there, is not built: Metal's snorm blend is measured for source-over alone + (the row above). - **Format-less storage reads on a device without `shaderStorageImageReadWithoutFormat` (ANV).** A fetch through the pixel interlock of a 16-bit packed color attachment (`B5G6R5Unorm`, `A1BGR5Unorm`, `ABGR4Unorm`, `BGR5A1Unorm`), which no SPIR-V format names, is refused