diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 2cb3308a1..b565bd38b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -625,6 +625,8 @@ mod normalized_vertex_fetch; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod numbered_samplers; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod pack_conversions; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod padded_loads; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod pass_start_reads; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/pack_conversions.rs b/crates/metal2vulkan-validation/src/runtime_lane/pack_conversions.rs new file mode 100644 index 000000000..6a8d90033 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/pack_conversions.rs @@ -0,0 +1,449 @@ +//! The packed normalized formats' conversions measured to be Metal's where the profile takes +//! `DriverDeviation::MetalPackConversions`, on the device the cfg selects, under the validation +//! layer: `unpack_unorm565_to_float` and `pack_float_to_unorm565`, and in `half` the unpacks of +//! `unorm4x8`, `snorm4x8`, `unorm10a2` and `unorm565` and the packs of those and of `unorm2x16` +//! and `snorm2x16`. +//! +//! What plain Metal answers (our probe on the Apple M3 Max under macOS 27.0.1, with and without +//! fast math, over these inputs and more): a `half` unpack is each field's exact quotient +//! `c / (2^N - 1)` (signed: `c / (2^(N-1) - 1)`, at least `-1`) rounded to `half` once; a `float` +//! `rgb565` unpack is the code times the `float` nearest `1 / (2^N - 1)`, rounded to `float`; a +//! pack from `half` rounds the exact product of the channel clamped to `[0, 1]` (`[-1, 1]` +//! signed) and `2^N - 1` (`2^(N-1) - 1`) to nearest even; a `float` `rgb565` pack rounds that +//! product rounded to `float` first, to nearest even; a NaN channel packs as code 0. +//! +//! Where the profile takes the deviation (MoltenVK on the Apple M3 Max's macOS 27 identity), no +//! kernel records `PrecisionNote::DevicePackConversion` and every lane is Metal's. Elsewhere each +//! records the note and its lanes are the device's, which the test prints as `PACK-CONVERSIONS` +//! lines. + +use super::degrade_notices::on_device; +use super::driver_deviations::stage_notes; +use super::{buffer_with, read_buffer, WAIT}; +use crate::air_library::AirLibrary; +use metal2vulkan::device::VkProperty; +use metal2vulkan::pipeline::{ComputePipelineDescriptor, PrecisionNote, StageSource}; +use metal2vulkan_devtools::llvm_assemble_text; +use metal2vulkan_runtime::{CommandBufferStatus, Device, PipelineOptions, Size}; + +/// The kind of a kernel's input word. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Input { + /// A packed word: every code of every field. + Packed, + /// A `half`, broadcast to every channel: every bit pattern. + Half, + /// A `float`, broadcast to every channel ([`float_words`]). + Float, +} + +/// A kernel of the lane: its entry, the AIR format name, its lanes, whether it packs, its input +/// and whether its floats are `half`. +struct Kernel { + entry: &'static str, + format: &'static str, + lanes: u32, + packs: bool, + input: Input, +} + +impl Kernel { + /// Whether the kernel's floats are `half`. + fn half(&self) -> bool { + match self.input { + Input::Half => true, + Input::Float => false, + Input::Packed => self.entry.starts_with("uh_"), + } + } + + /// The packed integer's width: 16 for `rgb565`, else 32. + fn width(&self) -> u32 { + match self.format { + "unorm.rgb565" => 16, + _ => 32, + } + } + + /// The format's fields: (offset, width, signed), in channel order. + fn fields(&self) -> &'static [(u32, u32, bool)] { + match self.format { + "unorm4x8" => &[(0, 8, false), (8, 8, false), (16, 8, false), (24, 8, false)], + "snorm4x8" => &[(0, 8, true), (8, 8, true), (16, 8, true), (24, 8, true)], + "unorm2x16" => &[(0, 16, false), (16, 16, false)], + "snorm2x16" => &[(0, 16, true), (16, 16, true)], + "unorm.rgb10a2" => &[ + (0, 10, false), + (10, 10, false), + (20, 10, false), + (30, 2, false), + ], + "unorm.rgb565" => &[(0, 5, false), (5, 6, false), (11, 5, false)], + f => unreachable!("{f}"), + } + } +} + +/// The kernels: every form `DriverDeviation::MetalPackConversions` covers. +const KERNELS: [Kernel; 12] = [ + unpack("u565f", "unorm.rgb565", 3), + unpack("uh_unorm4x8", "unorm4x8", 4), + unpack("uh_snorm4x8", "snorm4x8", 4), + unpack("uh_10a2", "unorm.rgb10a2", 4), + unpack("uh_565", "unorm.rgb565", 3), + pack("ph_unorm4x8", "unorm4x8", 4, Input::Half), + pack("ph_snorm4x8", "snorm4x8", 4, Input::Half), + pack("ph_unorm2x16", "unorm2x16", 2, Input::Half), + pack("ph_snorm2x16", "snorm2x16", 2, Input::Half), + pack("ph_10a2", "unorm.rgb10a2", 4, Input::Half), + pack("ph_565", "unorm.rgb565", 3, Input::Half), + pack("p565f", "unorm.rgb565", 3, Input::Float), +]; + +const fn unpack(entry: &'static str, format: &'static str, lanes: u32) -> Kernel { + Kernel { + entry, + format, + lanes, + packs: false, + input: Input::Packed, + } +} + +const fn pack(entry: &'static str, format: &'static str, lanes: u32, input: Input) -> Kernel { + Kernel { + entry, + format, + lanes, + packs: true, + input, + } +} + +/// The lane's AIR: every kernel of [`KERNELS`], buffer 0 its input words (`uint`, or `half` for +/// a `half` pack), buffer 1 its results: an unpack's four lanes per input (`float` or `half`, the +/// unused lanes left), a pack's `uint`. +fn library() -> String { + let mut defs = String::new(); + let mut decls = String::new(); + let mut metas = String::new(); + let mut refs = Vec::new(); + for (k, kernel) in KERNELS.iter().enumerate() { + let (fty, fname, fsize) = match kernel.half() { + true => ("half", "f16", 2), + false => ("float", "f32", 4), + }; + let lanes = kernel.lanes; + let vty = format!("<{lanes} x {fty}>"); + let iw = format!("i{}", kernel.width()); + let call = format!( + "air.{}.{}.v{lanes}{fname}", + if kernel.packs { "pack" } else { "unpack" }, + kernel.format + ); + let (inty, insize) = match kernel.input { + Input::Half => ("half", 2), + Input::Float => ("float", 4), + Input::Packed => ("i32", 4), + }; + let outsize = match kernel.packs { + true => 4, + false => fsize, + }; + let mut body = format!( + " %i = zext i32 %gid to i64\n %p = getelementptr inbounds {inty}, ptr addrspace(1) %in, i64 %i\n %x = load {inty}, ptr addrspace(1) %p, align {insize}\n" + ); + if kernel.packs { + decls.push_str(&format!("declare {iw} @{call}({vty})\n")); + let mut prev = "undef".to_string(); + for l in 0..lanes { + body.push_str(&format!( + " %v{l} = insertelement {vty} {prev}, {fty} %x, i32 {l}\n" + )); + prev = format!("%v{l}"); + } + body.push_str(&format!(" %w = call {iw} @{call}({vty} {prev})\n")); + body.push_str(match kernel.width() { + 16 => " %r = zext i16 %w to i32\n", + _ => " %r = add i32 %w, 0\n", + }); + body.push_str( + " %o = getelementptr inbounds i32, ptr addrspace(1) %out, i64 %i\n store i32 %r, ptr addrspace(1) %o, align 4\n", + ); + } else { + decls.push_str(&format!("declare {vty} @{call}({iw})\n")); + let w = match kernel.width() { + 16 => { + body.push_str(" %x16 = trunc i32 %x to i16\n"); + "%x16" + } + _ => "%x", + }; + body.push_str(&format!(" %v = call {vty} @{call}({iw} {w})\n")); + body.push_str(" %b = shl i64 %i, 2\n"); + for l in 0..lanes { + body.push_str(&format!( + " %e{l} = extractelement {vty} %v, i32 {l}\n %j{l} = or i64 %b, {l}\n %o{l} = getelementptr inbounds {fty}, ptr addrspace(1) %out, i64 %j{l}\n store {fty} %e{l}, ptr addrspace(1) %o{l}, align {fsize}\n" + )); + } + } + defs.push_str(&format!( + "define void @{e}(ptr addrspace(1) %in, ptr addrspace(1) %out, i32 %gid) {{\nentry:\n{body} ret void\n}}\n\n", + e = kernel.entry, + )); + let n = 10 + 4 * k; + refs.push(format!("!{n}")); + let inname = match kernel.input { + Input::Half => "half", + Input::Float => "float", + Input::Packed => "uint", + }; + let outname = match kernel.packs { + true => "uint", + false => fty, + }; + metas.push_str(&format!( + "!{n} = !{{ptr @{e}, !1, !{a}}}\n!{a} = !{{!{b}, !{c}, !2}}\n!{b} = !{{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 {insize}, !\"air.arg_type_align_size\", i32 {insize}, !\"air.arg_type_name\", !\"{inname}\", !\"air.arg_name\", !\"in\"}}\n!{c} = !{{i32 1, !\"air.buffer\", !\"air.location_index\", i32 1, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 {outsize}, !\"air.arg_type_align_size\", i32 {outsize}, !\"air.arg_type_name\", !\"{outname}\", !\"air.arg_name\", !\"out\"}}\n", + e = kernel.entry, + a = n + 1, + b = n + 2, + c = n + 3, + )); + } + format!( + "; Owned synthetic kernels.\nsource_filename = \"pack_conversions.metal\"\n\n{defs}{decls}\n!air.kernel = !{{{}}}\n!air.version = !{{!3}}\n!air.language_version = !{{!4}}\n!1 = !{{}}\n!2 = !{{i32 2, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}}\n!3 = !{{i32 2, i32 8, i32 0}}\n!4 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n{metas}", + refs.join(", ") + ) +} + +/// The packed words the unpacks read: every 16-bit value `i` spread as `i | i << 16`, which +/// gives every byte, every 10-bit field and every `rgb565` word every code. +fn packed_words() -> Vec { + (0..=u32::from(u16::MAX)).map(|i| i | i << 16).collect() +} + +/// The `float` words the `float` pack reads: every `half` value widened exactly, the 33 `float`s +/// around each tie of the 5- and 6-bit scales' products, NaNs and the specials. +fn float_words() -> Vec { + let mut words: Vec = (0..=u16::MAX).map(widened).collect(); + for scale in [31u32, 63] { + for k in 0..scale { + let tie = ((f64::from(k) + 0.5) / f64::from(scale)) as f32; + for d in -16i32..=16 { + words.push(tie.to_bits().wrapping_add_signed(d)); + } + } + } + words.extend([ + 0x7fc0_0000, + 0xffc0_0001, + 0x7f80_0001, + 0x7f80_0000, + 0xff80_0000, + 0x0000_0001, + 0x8000_0001, + 0x3f80_0001, + 0x3f7f_ffff, + ]); + while words.len() % 64 != 0 { + words.push(0x3f80_0000); + } + words +} + +/// The exact `f32` bits of half `h`. +fn widened(h: u16) -> u32 { + let sign = u32::from(h >> 15) << 31; + let exp = u32::from((h >> 10) & 0x1f); + let mant = u32::from(h & 0x3ff); + match exp { + 0x1f => sign | 0x7f80_0000 | mant << 13, + 0 => sign | (mant as f32 * 2f32.powi(-24)).to_bits(), + e => sign | (e + 112) << 23 | mant << 13, + } +} + +/// The IEEE binary16 bits of `x` (zero, or a normal `half` value in `[-1, 1]`) rounded to +/// nearest even once. +fn half_bits(x: f64) -> u16 { + if x == 0.0 { + return 0; + } + let sign = if x < 0.0 { 0x8000 } else { 0 }; + let a = x.abs(); + let e = ((a.to_bits() >> 52) & 0x7ff) as i32 - 1023; + assert!(e >= -14, "{x} is not a normal half"); + let n = (a * 2f64.powi(10 - e)).round_ties_even() as i32; + let (e, n) = if n == 2048 { (e + 1, 1024) } else { (e, n) }; + sign | (((e + 15) << 10) | (n - 1024)) as u16 +} + +/// A field's code of `x` (a NaN code 0): `x` clamped to `[0, 1]` (signed: `[-1, 1]`) times the +/// scale, rounded to nearest even, masked to the width; `product` rounds the product first. +fn code(x: f64, width: u32, signed: bool, product: impl Fn(f64) -> f64) -> u32 { + if x.is_nan() { + return 0; + } + let (lo, scale) = match signed { + true => (-1.0, f64::from((1u32 << (width - 1)) - 1)), + false => (0.0, f64::from((1u32 << width) - 1)), + }; + let c = product(x.clamp(lo, 1.0) * scale).round_ties_even() as i64; + (c & ((1i64 << width) - 1)) as u32 +} + +/// Metal's words for input word `x` of `kernel` (the module docs): an unpack's lanes, a pack's +/// one word. +fn metal(kernel: &Kernel, x: u32) -> Vec { + let fields = kernel.fields(); + match (kernel.packs, kernel.input) { + (false, _) => fields + .iter() + .map(|&(at, width, signed)| { + let raw = (x >> at) & ((1u32 << width) - 1); + match (kernel.half(), signed) { + (false, _) => { + // `float` `rgb565` alone: the code times the `float` reciprocal. + let scale = ((1u32 << width) - 1) as f32; + (raw as f32 * (1.0 / scale)).to_bits() + } + (true, false) => { + u32::from(half_bits(f64::from(raw) / f64::from((1u32 << width) - 1))) + } + (true, true) => { + let c = i64::from(raw) - i64::from(raw >> (width - 1)) * (1i64 << width); + let q = c as f64 / f64::from((1u32 << (width - 1)) - 1); + u32::from(half_bits(q.max(-1.0))) + } + } + }) + .collect(), + (true, Input::Half) => { + let h = f64::from(f32::from_bits(widened(x as u16))); + vec![fields + .iter() + .map(|&(at, width, signed)| code(h, width, signed, |p| p) << at) + .fold(0, |a, b| a | b)] + } + (true, _) => { + let f = f64::from(f32::from_bits(x)); + vec![fields + .iter() + .map(|&(at, width, signed)| code(f, width, signed, |p| f64::from(p as f32)) << at) + .fold(0, |a, b| a | b)] + } + } +} + +/// `kernel`'s words on `device` for `input`: an unpack's four lanes per input (the unused ones +/// left as filled), a pack's one. +fn run(device: &Device, kernel: &Kernel, air: &[u8], input: &[u32]) -> Vec { + let library = device.new_library_with_air(air).unwrap(); + let function = library.new_function_with_name(kernel.entry).unwrap(); + let pipeline = device + .new_compute_pipeline_state( + &ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())), + &PipelineOptions::default(), + ) + .unwrap(); + let bytes: Vec = match kernel.input { + Input::Half => input + .iter() + .flat_map(|&w| (w as u16).to_le_bytes()) + .collect(), + _ => input.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let (per, size): (u64, u64) = match (kernel.packs, kernel.half()) { + (true, _) => (1, 4), + (false, true) => (4, 2), + (false, false) => (4, 4), + }; + let n = input.len() as u64; + let input = buffer_with(device, &bytes).unwrap(); + let out = buffer_with(device, &vec![0x5a; (n * per * size) as usize]).unwrap(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&pipeline).unwrap(); + encoder.set_buffer(Some(&input), 0, 0).unwrap(); + encoder.set_buffer(Some(&out), 0, 1).unwrap(); + encoder + .dispatch_threads(Size::new(n, 1, 1), Size::new(64, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let got = read_buffer(&out, 0, n * per * size).unwrap(); + match size { + 2 => got + .as_chunks::<2>() + .0 + .iter() + .map(|b| u32::from(u16::from_le_bytes(*b))) + .collect(), + _ => got + .as_chunks::<4>() + .0 + .iter() + .map(|b| u32::from_le_bytes(*b)) + .collect(), + } +} + +/// Every kernel answers Metal's words on every lane, and records no +/// `PrecisionNote::DevicePackConversion`, where the profile takes +/// `DriverDeviation::MetalPackConversions` (`VkProperty::MetalPackConversions`); elsewhere each +/// records the note. Every code of every field, every `half` bit pattern, and 68,672 `float` +/// words (the module docs). +#[test] +fn measured_pack_conversions_are_metals_where_measured_and_noted_elsewhere() { + let air = llvm_assemble_text(&library()).unwrap(); + let packed = packed_words(); + let halves: Vec = (0..=u32::from(u16::MAX)).collect(); + let floats = float_words(); + on_device(|device, _| { + let measured = device + .compile_device() + .profile() + .enabled() + .properties + .contains(&VkProperty::MetalPackConversions); + let mut report = Vec::new(); + for kernel in &KERNELS { + let notes = stage_notes(device, &air, kernel.entry); + let noted = notes.contains(&PrecisionNote::DevicePackConversion); + assert_eq!(noted, !measured, "{}: {notes:?}", kernel.entry); + let input = match kernel.input { + Input::Packed => &packed, + Input::Half => &halves, + Input::Float => &floats, + }; + let got = run(device, kernel, &air, input); + let per = got.len() / input.len(); + let mut differ = 0; + for (i, &x) in input.iter().enumerate() { + let want = metal(kernel, x); + let lanes = &got[i * per..i * per + want.len()]; + if lanes == want.as_slice() { + continue; + } + assert!( + noted, + "{}: input {x:#x} answered {lanes:x?}, Metal's {want:x?}", + kernel.entry + ); + differ += 1; + } + report.push(format!( + "PACK-CONVERSIONS {} on {}: {differ} of {} inputs the device's, note {noted}", + kernel.entry, + device.name(), + input.len() + )); + } + for line in &report { + println!("{line}"); + } + }); +} diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 3b6990a19..63b34a633 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1033,7 +1033,7 @@ codec_enum! { MetalDepth16Stores, MetalDepth16BiasedStores, MetalInterpolation, MetalFirstVertexIndices, MetalFullQuads, ProvokingVertexModePerPipeline, DepthImageKeepsValuesOutsideUnitRange, MetalNormalizedVertexFetch, MetalAlphaCoverage, InterpolateAtOffsetFromSevenSixteenths, - MetalNanMoves, + MetalNanMoves, MetalPackConversions, } VkLimit { MaxComputeWorkGroupSize(f0), MaxComputeWorkGroupCount(f0), MaxComputeWorkGroupInvocations, diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index 0538f9d3c..5a899bf22 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -812,6 +812,9 @@ fn enabled_caps(desc: &DeviceDescription, deviations: &BTreeSet if deviations.contains(&DriverDeviation::MetalNanMoves) { properties.insert(VkProperty::MetalNanMoves); } + if deviations.contains(&DriverDeviation::MetalPackConversions) { + properties.insert(VkProperty::MetalPackConversions); + } if desc .driver_facts() .contains(&crate::device::DriverFact::DepthImageKeepsValuesOutsideUnitRange) diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index b504a82da..f6e160b58 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -414,6 +414,23 @@ pub(crate) fn among( /// widened `half` elsewhere or reads its bits is outside the measurement /// (`narrow::moves_unfolded`). One row per GPU, as measured. /// +/// `MetalPackConversions`: MoltenVK 1.4.2 hands `GLSL.std.450`'s `PackUnorm4x8`, `PackSnorm4x8`, +/// `PackUnorm2x16`, `PackSnorm2x16` and their unpacks to Metal's own `pack_float_to_*` and +/// `unpack_*_to_float`, and the other formats' definition to Metal's arithmetic; on the M3 Max +/// under macOS 27.0.1 (2026-11-02) the module's conversion answers Metal's, word for word against plain Metal with and without fast math, for +/// `unpack_unorm565_to_float` (every word: the code times the `float` nearest `1 / D`, as Metal's +/// does), `pack_float_to_unorm565` (3,083,776 `float`s and 385,152 around its products' ties: +/// Metal rounds the product to `float` first), the `half` unpacks of `unorm4x8`, `snorm4x8`, +/// `unorm10a2` and `unorm565` (every code: Metal's quotient rounded once to `half`), and the +/// `half` packs +/// of `unorm4x8`, `snorm4x8`, `unorm2x16`, `snorm2x16`, `unorm10a2` and `unorm565` (every `half` +/// in every channel). The AIR of `runtime_lane::pack_conversions`, which checks the runtime +/// against Metal's answers, run on Metal too, matches its model in every word. Measured to +/// differ, so outside it: the sRGB format (85,511 of 3,083,776 `float` packs, 3,286 `half` ones), +/// `unorm10a2` in `float` (9,163 of 131,072 unpacked words, 1,257 packed `float`s), and the `half` +/// unpacks of `unorm2x16` and `snorm2x16` (8 lanes, a `float` quotient rounded twice); +/// `snorm10a2` is unmeasured. One row per GPU, as measured. +/// /// Another driver has none of them, as Vulkan states, and a listed driver on another vendor's GPU /// (or another GPU than a row's) is unmeasured: the profile then takes each one's route without /// it, which the deviation's docs name (`derive.rs`). @@ -604,6 +621,10 @@ pub(crate) const DEVIATIONS: &[Measured] = &[ device: Some(APPLE9), ..moltenvk_on_apple(DriverDeviation::MetalNanMoves) }, + Measured { + device: Some(APPLE9), + ..moltenvk_on_apple(DriverDeviation::MetalPackConversions) + }, ]; /// NVIDIA's `vendorID`. diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index eef378820..e0d633b0a 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -339,6 +339,10 @@ impl DeviceProfile { DriverDeviation::MetalNanMoves => { f.enabled.properties.contains(&VkProperty::MetalNanMoves) } + DriverDeviation::MetalPackConversions => f + .enabled + .properties + .contains(&VkProperty::MetalPackConversions), } } diff --git a/crates/metal2vulkan/src/device/requirements.rs b/crates/metal2vulkan/src/device/requirements.rs index 3a83dc72a..7d04e69f8 100644 --- a/crates/metal2vulkan/src/device/requirements.rs +++ b/crates/metal2vulkan/src/device/requirements.rs @@ -841,6 +841,14 @@ pub enum VkProperty { /// [`PrecisionNote::NativeNanEncoding`](crate::pipeline::PrecisionNote::NativeNanEncoding) /// for it requires it. MetalNanMoves, + /// The device's conversions of the packed normalized formats measured to answer Metal's + /// (the driver's measured deviation + /// [`DriverDeviation::MetalPackConversions`](crate::error::DriverDeviation::MetalPackConversions)). + /// No Vulkan query reports it: Vulkan leaves the conversions' rounding to the device. A + /// module that converts one of those forms and records no + /// [`PrecisionNote::DevicePackConversion`](crate::pipeline::PrecisionNote::DevicePackConversion) + /// for it requires it. + MetalPackConversions, /// `GLSL.std.450 InterpolateAtOffset` at offset `v` reads Metal's `interpolate_at_offset` at /// `v + 7/16`, measured from the pixel's upper-left corner: a device whose description reports /// a MoltenVK driver, whose SPIRV-Cross hands the instruction to Metal so at any release diff --git a/crates/metal2vulkan/src/device/tests/driver_facts.rs b/crates/metal2vulkan/src/device/tests/driver_facts.rs index 5a7a5a244..9be35365b 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -156,6 +156,10 @@ fn taken(p: &crate::device::DeviceProfile) -> Vec property(VkProperty::MetalAlphaCoverage), ), (D::MetalNanMoves, property(VkProperty::MetalNanMoves)), + ( + D::MetalPackConversions, + property(VkProperty::MetalPackConversions), + ), ] .into_iter() .inspect(|&(d, taken)| { @@ -170,7 +174,7 @@ fn taken(p: &crate::device::DeviceProfile) -> Vec /// at every release: every Apple GPU's (MoltenVK's lockstep, `float` functions, canonical NaNs, /// sampler, compute cube route and the rest of the seventeen), with the graphics cube route and the /// per-sample depth of macOS 27's Apple9 identity, that identity's normalized -/// storage writes, full quads, normalized vertex fetch, alpha to coverage and moved NaNs, and every Apple GPU's 16-bit unorm depth stores, interpolation +/// storage writes, full quads, normalized vertex fetch, alpha to coverage, moved NaNs and pack conversions, and every Apple GPU's 16-bit unorm depth stores, interpolation /// and first-vertex indices; lavapipe's `float` color NaNs and half-float storage writes; RADV's on /// the Radeon 780M, ANV's on the Iris Xe of RPL-P and the UHD 770 of RPL-S, and NVIDIA's on the /// RTX 3090 and the RTX 5080 Laptop GPU, as measured there; the 8-bit linear filter's bound where @@ -228,11 +232,12 @@ fn the_profile_takes_the_deviations_its_driver_is_measured_with() { list.push(D::MetalFirstVertexIndices); } // macOS 27's full quads, measured on the M4's identity alone, and its normalized vertex - // fetch, alpha to coverage and moved NaNs, measured on the M3 Max under it. + // fetch, alpha to coverage, moved NaNs and pack conversions, measured on the M3 Max under it. m4_measured.push(D::MetalFullQuads); m4_measured.push(D::MetalNormalizedVertexFetch); m4_measured.push(D::MetalAlphaCoverage); m4_measured.push(D::MetalNanMoves); + m4_measured.push(D::MetalPackConversions); let all_of = |d: &DeviceDescription| match d.device_id { crate::device::driver_facts::APPLE9 => m4_measured.clone(), _ => apple_all.clone(), diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 8d5b64af4..b5ee3f127 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -836,6 +836,17 @@ pub enum DriverDeviation { /// keeps its flipped sign unless the driver's compiler moves the negation onto the `half`. /// Unmeasured, each records it. MetalNanMoves, + /// The device's conversions of Metal's packed normalized formats outside the four + /// `GLSL.std.450` names in `float` answer Metal's codes and values + /// (`VkProperty::MetalPackConversions`): `unpack_unorm565_to_float` and + /// `pack_float_to_unorm565`, and the `half` forms of `unorm4x8`, `snorm4x8` and `unorm10a2` + /// (both ways), `unorm565` (both ways) and `unorm2x16` and `snorm2x16` (packing). The module + /// takes each as it does on every profile (the format's `GLSL.std.450` instruction, or its + /// definition on the format's fields, around a `half`'s widening or rounding); where the + /// profile takes this deviation, each records no `PrecisionNote::DevicePackConversion` and + /// the module requires the property. The sRGB format, `unorm10a2` in `float`, `snorm10a2`, and + /// the `half` unpacks of `unorm2x16` and `snorm2x16` stay noted. Unmeasured, each records it. + MetalPackConversions, } /// A defect of a device's driver in a command the runtime records for itself, never in a diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index bf796e384..dc0ad4659 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -723,6 +723,11 @@ pub struct ArithPlan { /// `VkProperty::MetalNanMoves`, but where it holds a `half` the device's conversions did not /// make ([`narrow::moves_unfolded`]), where it records `PrecisionNote::NativeNanEncoding`. pub held_nan_moves: bool, + /// Whether an `air.pack` or `air.unpack` takes the device's conversion with no note because + /// its form is measured to answer Metal's (`DriverDeviation::MetalPackConversions`, + /// [`pack::measured`]), recorded at selection: the module then requires + /// `VkProperty::MetalPackConversions`. + pub metal_packs: bool, /// The precision notes the plan's operations record unless their entry's quotient and /// functions are Metal's own (the profile's `float` functions are Metal's and Metal compiles /// the entry with fast math), recorded at selection ([`OpNotes::unless_metal_fast`]); @@ -2619,11 +2624,21 @@ fn select_pack( // The device's conversion: GLSL.std.450's instruction for the format, or its multiply, // `RoundEven` and clamp, whose rounding Vulkan leaves to the device (`DevicePackConversion`). // Where the profile's `float` functions are Metal's, a `float` one of the four formats - // GLSL.std.450 names reaches Metal's own `pack_float_to_*` or `unpack_*_to_float`. + // GLSL.std.450 names reaches Metal's own `pack_float_to_*` or `unpack_*_to_float`. Where the + // profile takes `MetalPackConversions`, the forms measured to be Metal's (`pack::measured`) + // are, and the module requires that property. + let fmt = floats.float_fmt(); let own = FloatFacts::on(cx.profile).metal_functions - && floats.float_fmt() == Some(FloatFmt::F32) + && fmt == Some(FloatFmt::F32) && pack::instruction(p.format, p.dir).is_some(); - if !own { + let measured = !own + && cx + .profile + .takes_driver_deviation(crate::error::DriverDeviation::MetalPackConversions) + && fmt.is_some_and(|f| pack::measured(p.format, p.dir, f)); + if measured { + cx.families.arith.metal_packs = true; + } else if !own { cx.precision.insert(PrecisionNote::DevicePackConversion); } Ok(ArithStrategy::Pack { diff --git a/crates/metal2vulkan/src/lower/arith/pack.rs b/crates/metal2vulkan/src/lower/arith/pack.rs index c1b3f3a07..6a3fff243 100644 --- a/crates/metal2vulkan/src/lower/arith/pack.rs +++ b/crates/metal2vulkan/src/lower/arith/pack.rs @@ -40,6 +40,31 @@ pub fn instruction(format: PackFormat, dir: PackDir) -> Option { }) } +/// Whether the device's conversion of `format` in direction `dir` on float lanes of `fmt` is one +/// measured to answer Metal's where the profile takes `DriverDeviation::MetalPackConversions`: +/// `unorm.rgb565` in `float`, and in `half` `unorm4x8`, `snorm4x8`, `unorm.rgb10a2` and +/// `unorm.rgb565` both ways and `unorm2x16` and `snorm2x16` packed. +pub fn measured(format: PackFormat, dir: PackDir, fmt: FloatFmt) -> bool { + use PackFormat as F; + match (fmt, dir) { + (FloatFmt::F32, _) => format == F::UnormRgb565, + (FloatFmt::Half, PackDir::Pack) => matches!( + format, + F::Unorm4x8 + | F::Snorm4x8 + | F::Unorm2x16 + | F::Snorm2x16 + | F::UnormRgb10a2 + | F::UnormRgb565 + ), + (FloatFmt::Half, PackDir::Unpack) => matches!( + format, + F::Unorm4x8 | F::Snorm4x8 | F::UnormRgb10a2 | F::UnormRgb565 + ), + _ => false, + } +} + /// The error of a conversion whose format or lanes the emission cannot take (a packed float /// format to pack to, a lane count not the format's): selection rules both out. fn unpackable() -> BuildError { diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index a74d7d82e..819660f07 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1847,13 +1847,20 @@ pub enum PrecisionNote { /// `RoundEven` and conversion (a pack) or its multiply by the scale's reciprocal (an unpack); /// `unorm4x8_srgb`'s colour channels take the MSL transfer functions by the device's multiply, /// division and `Pow` around the 8-bit instruction. Metal rounds the exact product to its code - /// and divides correctly rounded, answers code 0 for a NaN channel, and takes an sRGB colour + /// and divides correctly rounded (`unorm565` in `float`: it rounds the product to `float` + /// first, and multiplies by the `float` nearest the reciprocal, as the definition does), + /// answers code 0 for a NaN channel, and takes an sRGB colour /// through its twelve-bit table: a decode answers its step `k / 4095` nearest the transfer, an /// encode the byte of that table's step. Also: a write of an 8-bit sRGB storage texture held /// through its UNORM alias (`StorageImageClass::SrgbEncode`, Vulkan having no sRGB storage /// view) encodes by `unorm4x8_srgb`'s pack. Recorded on every device but for /// a `float` conversion of the four named formats on a device whose functions are Metal's own - /// (MoltenVK: Metal's own `pack_float_to_*` and `unpack_*_to_float`). **Recorded bound:** + /// (MoltenVK: Metal's own `pack_float_to_*` and `unpack_*_to_float`), and but for the forms + /// measured to answer Metal's on a profile that takes + /// [`DriverDeviation::MetalPackConversions`](crate::error::DriverDeviation::MetalPackConversions) + /// (MoltenVK on the Apple M3 Max's macOS 27 identity: `unorm565` in `float`, and in `half` + /// `unorm4x8`, `snorm4x8`, `unorm10a2` and `unorm565` both ways and `unorm2x16` and + /// `snorm2x16` packed), which require `VkProperty::MetalPackConversions`. **Recorded bound:** /// Vulkan bounds the instructions by their definition (`round(clamp(c) * scale)` and /// `c / scale`): a packed code within one of Metal's, apart only where `clamp(c) * scale` lies /// within its `float` rounding of a half-integer (`Round` may tie either way); an unpacked diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 01fc9e73f..80b7c5d4b 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -2808,6 +2808,12 @@ fn compile_kept( .properties .insert(crate::device::requirements::VkProperty::MetalNanMoves); } + // A packed format's conversion left to the device with no note because it is Metal's. + if plan.families.arith.metal_packs { + requirements + .properties + .insert(crate::device::requirements::VkProperty::MetalPackConversions); + } // Metal's `float` and `half` minimum and maximum family left to the device's `NMin`, `NMax` // and `NClamp` because they are Metal's. if plan.families.arith.device_min_max { diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index 4d7a1aac0..6dae16aa9 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -468,18 +468,16 @@ fn kernels() -> Vec { note: Some(PrecisionNote::DeviceTranscendentals), }); // `rgb565` is the device's product rounded by `RoundEven` (0.5 * 63 = 31.5 -> 32, exact in - // f32), noted, and `rg11b10f` unpacks the half with the field's bits (0x3C0 -> red 1.0). - v.push(Kernel { - note: Some(PrecisionNote::DevicePackConversion), - ..k( - "rgb565_pack_rounds_the_float_product_to_even", - format!( - "{} %v = insertelement <3 x float> , float %a, i32 0\n %p = call i16 @air.pack.unorm.rgb565.v3f32(<3 x float> %v)\n %r = zext i16 %p to i32\n", - of("a", 1.0) - ), - 31 | (32 << 5), - ) - }); + // f32), noted but where measured (`pack_conversions_are_metals_where_measured`), and + // `rg11b10f` unpacks the half with the field's bits (0x3C0 -> red 1.0). + v.push(k( + "rgb565_pack_rounds_the_float_product_to_even", + format!( + "{} %v = insertelement <3 x float> , float %a, i32 0\n %p = call i16 @air.pack.unorm.rgb565.v3f32(<3 x float> %v)\n %r = zext i16 %p to i32\n", + of("a", 1.0) + ), + 31 | (32 << 5), + )); v.push(Kernel { name: "rg11b10f_unpacks_half_fields", body: format!( @@ -3826,6 +3824,148 @@ fn half_moves_are_metals_only_where_the_device_folds_them() { } } +/// Every normalized format's `air.pack` and `air.unpack`, in `float` and `half`: the device's +/// conversion, noted `DevicePackConversion` but where it reaches Metal's own function (a `float` +/// form `GLSL.std.450` names, where the profile's `float` functions are Metal's) or where the +/// profile takes `DriverDeviation::MetalPackConversions` and the form is one measured to be +/// Metal's (`moltenvk-m3`: `unorm.rgb565` in `float`; in `half` `unorm4x8`, `snorm4x8`, +/// `unorm.rgb10a2` and `unorm.rgb565` both ways and `unorm2x16` and `snorm2x16` packed), where +/// the module requires `VkProperty::MetalPackConversions`. The sRGB format, `unorm.rgb10a2` in +/// `float`, `snorm.rgb10a2` and the `half` unpacks of the 16-bit formats stay noted everywhere. +#[test] +fn pack_conversions_are_metals_where_measured() { + use crate::device::requirements::VkProperty; + // Each format's name, its lanes and its packed integer's width. + let formats = [ + ("unorm4x8", 4, 32), + ("unorm4x8.srgb", 4, 32), + ("snorm4x8", 4, 32), + ("unorm2x16", 2, 32), + ("snorm2x16", 2, 32), + ("unorm.rgb10a2", 4, 32), + ("snorm.rgb10a2", 4, 32), + ("unorm.rgb565", 3, 16), + ]; + // The forms measured on the M3 Max: (format, packs, half). + let measured = [ + ("unorm.rgb565", true, false), + ("unorm.rgb565", false, false), + ("unorm4x8", true, true), + ("snorm4x8", true, true), + ("unorm2x16", true, true), + ("snorm2x16", true, true), + ("unorm.rgb10a2", true, true), + ("unorm.rgb565", true, true), + ("unorm4x8", false, true), + ("snorm4x8", false, true), + ("unorm.rgb10a2", false, true), + ("unorm.rgb565", false, true), + ]; + let (mut forms, mut ks) = (Vec::new(), Vec::new()); + let mut decls = String::new(); + for (format, lanes, width) in formats { + for packs in [true, false] { + for half in [false, true] { + let (fty, fname) = if half { + ("half", "f16") + } else { + ("float", "f32") + }; + let vty = format!("<{lanes} x {fty}>"); + let call = format!( + "air.{}.{format}.v{lanes}{fname}", + if packs { "pack" } else { "unpack" } + ); + let iw = format!("i{width}"); + let decl = match packs { + true => format!("declare {iw} @{call}({vty})\n"), + false => format!("declare {vty} @{call}({iw})\n"), + }; + if !DECLS.contains(&decl) && !decls.contains(&decl) { + decls.push_str(&decl); + } + let body = if packs { + let mut b = of("a", 0.25); + if half { + b.push_str(" %h = fptrunc float %a to half\n"); + } + let x = if half { "%h" } else { "%a" }; + let mut prev = "undef".to_string(); + for i in 0..lanes { + b.push_str(&format!( + " %v{i} = insertelement {vty} {prev}, {fty} {x}, i32 {i}\n" + )); + prev = format!("%v{i}"); + } + b.push_str(&format!(" %p = call {iw} @{call}({vty} {prev})\n")); + b.push_str(&match width { + 16 => " %r = zext i16 %p to i32\n".to_string(), + _ => " %r = add i32 %p, 0\n".to_string(), + }); + b + } else { + let mut b = oi("w", 0x8901_37FF); + let w = match width { + 16 => { + b.push_str(" %w16 = trunc i32 %w to i16\n"); + "%w16" + } + _ => "%w", + }; + b.push_str(&format!(" %v = call {vty} @{call}({iw} {w})\n")); + b.push_str(&format!(" %x = extractelement {vty} %v, i32 0\n")); + b.push_str(&match half { + true => " %b = bitcast half %x to i16\n %r = zext i16 %b to i32\n", + false => " %r = bitcast float %x to i32\n", + }); + b + }; + let name = format!( + "{}_{}_{fname}", + if packs { "pack" } else { "unpack" }, + format.replace('.', "_") + ); + forms.push((format, packs, half)); + ks.push(Kernel { + want: None, + ..k(Box::leak(name.into_boxed_str()), body, 0) + }); + } + } + } + let text = module(&ks).replace(DECLS, &format!("{DECLS}{decls}")); + let Some(bitcode) = assemble("pack-conversions", &text) else { + return; + }; + for stem in ["lavapipe", "moltenvk-m3"] { + let p = profile(stem, DevicePolicy::default()).expect("profile"); + let takes = p.takes_driver_deviation(crate::error::DriverDeviation::MetalPackConversions); + assert_eq!(takes, stem == "moltenvk-m3", "{stem}"); + let metal_functions = p.fields().float_functions == FloatFunctions::Metal; + for (&(format, packs, half), kk) in forms.iter().zip(&ks) { + let what = format!("{} on {stem}", kk.name); + let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); + link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + let glsl = matches!(format, "unorm4x8" | "snorm4x8" | "unorm2x16" | "snorm2x16"); + let own = metal_functions && !half && glsl; + let metals = takes && measured.contains(&(format, packs, half)); + assert_eq!( + a.precision.contains(&PrecisionNote::DevicePackConversion), + !own && !metals, + "{what}: {:?}", + a.precision + ); + assert_eq!( + a.requirements + .properties + .contains(&VkProperty::MetalPackConversions), + metals, + "{what}" + ); + } + } +} + /// Class E: Metal's `float` `fneg` and `fabs` (`air.fabs`, `air.fast_fabs`, and `llvm.fabs`, which /// takes `air.fabs`'s answer) flip or clear the sign bit alone, with and without fast-math flags: a /// NaN keeps its payload, signaling or not, and a denormal stays. The lowering is the device's diff --git a/crates/metal2vulkan/src/tests/engine_native_half.rs b/crates/metal2vulkan/src/tests/engine_native_half.rs index aa49a802c..c6d6ef02e 100644 --- a/crates/metal2vulkan/src/tests/engine_native_half.rs +++ b/crates/metal2vulkan/src/tests/engine_native_half.rs @@ -389,7 +389,6 @@ fn a_half_decode_is_the_devices_widening_inside_loops_and_out() { 0x3800 | (0x3400 << 16), 0, ]; - let nan = PrecisionNote::NativeNanEncoding; let conversion = PrecisionNote::NativeHalfConversion; // Each profile, whether its widening is noted `NativeHalfConversion` (else measured), and // whether it unpacks words (no `shaderFloat16`). diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index af32b3a9f..8fb194c0d 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -12974,6 +12974,7 @@ variant metal2vulkan::device::VkProperty::MetalNanMoves MetalNanMoves variant metal2vulkan::device::VkProperty::MetalNorm16ColorWrites MetalNorm16ColorWrites variant metal2vulkan::device::VkProperty::MetalNormStorageWrites MetalNormStorageWrites variant metal2vulkan::device::VkProperty::MetalNormalizedVertexFetch MetalNormalizedVertexFetch +variant metal2vulkan::device::VkProperty::MetalPackConversions MetalPackConversions variant metal2vulkan::device::VkProperty::MetalSampler MetalSampler variant metal2vulkan::device::VkProperty::MetalSmallFloatColorWrites MetalSmallFloatColorWrites variant metal2vulkan::device::VkProperty::MetalVertexSimdgroups MetalVertexSimdgroups @@ -13132,6 +13133,7 @@ variant metal2vulkan::error::DriverDeviation::MetalNanMoves MetalNanMoves variant metal2vulkan::error::DriverDeviation::MetalNorm16ColorWrites MetalNorm16ColorWrites variant metal2vulkan::error::DriverDeviation::MetalNormStorageWrites MetalNormStorageWrites variant metal2vulkan::error::DriverDeviation::MetalNormalizedVertexFetch MetalNormalizedVertexFetch +variant metal2vulkan::error::DriverDeviation::MetalPackConversions MetalPackConversions variant metal2vulkan::error::DriverDeviation::MetalSampler MetalSampler variant metal2vulkan::error::DriverDeviation::MetalSmallFloatColorWrites MetalSmallFloatColorWrites variant metal2vulkan::error::DriverDeviation::MetalVertexSimdgroups MetalVertexSimdgroups diff --git a/crates/metal2vulkan/tests/golden_hashes.tsv b/crates/metal2vulkan/tests/golden_hashes.tsv index 20930de65..725a7b5b0 100644 --- a/crates/metal2vulkan/tests/golden_hashes.tsv +++ b/crates/metal2vulkan/tests/golden_hashes.tsv @@ -16,7 +16,7 @@ profile intel-irisxe-rplp-anv c57b380689e33e05 profile intel-uhd770-rpls-anv c57b380689e33e05 profile lavapipe 8b0e38e4b195da6b profile lunarg-desktop-baseline-2023 a4079dbb79661db5 -profile moltenvk-m3 bd83009ea35a5b23 +profile moltenvk-m3 b82837f9130215bf profile nvidia-pascal-linux ffe884de52decdda profile nvidia-rtx50-linux 55dfd90c715d7263 profile nvidia-rtx5080-laptop c017cadc61d61b42 diff --git a/docs/API.md b/docs/API.md index b38a0eb9d..afa6abf46 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3490,12 +3490,22 @@ bound. device's: `GLSL.std.450`'s `Pack`/`Unpack` `Unorm4x8`, `Snorm4x8`, `Unorm2x16` and `Snorm2x16`, their definition by the device's `NClamp`, multiply, `RoundEven` and reciprocal for `rgb10a2` and `rgb565`, and the MSL transfer functions by the device's `Pow` for `unorm4x8_srgb`'s colour. Metal - rounds the exact product and divides correctly rounded, answers code 0 for a NaN channel, and + rounds the exact product and divides correctly rounded (`unorm565` in `float`: the product + rounded to `float` first, and the code times the `float` nearest the reciprocal, as the + definition does), answers code 0 for a NaN channel, and takes an sRGB colour through its twelve-bit table; a packed code is within one of Metal's, an unpacked value within 2.5 ulp, a decoded sRGB colour within half a twelve-bit step (`1 / 8190`) of Metal's step beyond its `Pow`'s bound. Also a write of an 8-bit sRGB storage texture held through its UNORM alias, which encodes by `unorm4x8_srgb`'s pack. Not recorded for a - `float` conversion of the four named formats on MoltenVK, Metal's own there. The same conversions + `float` conversion of the four named formats on MoltenVK, Metal's own there. **Exempt:** on a + profile that takes `DriverDeviation::MetalPackConversions`, MoltenVK on Apple's GPUs of the + Apple M3 Max's macOS 27 identity, the forms measured to answer Metal's at every code and every + `half` (on Metal and on the runtime, `runtime_lane::pack_conversions`) record no note and + require `VkProperty::MetalPackConversions`: `unorm565` in `float`, and in `half` `unorm4x8`, + `snorm4x8`, `unorm10a2` and `unorm565` both ways and `unorm2x16` and `snorm2x16` packed. The + sRGB format, `unorm10a2` in `float` (9,163 of 131,072 unpacked words and 1,257 of 3,083,776 + packed `float`s differ), `snorm10a2`, and the `half` unpacks of `unorm2x16` and `snorm2x16` + (Metal's single rounding, 8 lanes differ) stay noted there. The same conversions serve an implicit imageblock access of a normalized attachment (a `half` load rounding the unpacked `float` once more), a fragment function's read and write of an 8-bit sRGB attachment in the interlocked storage form or through its word view, and a snapshot read's decode of a diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index cc8359277..d03a2c380 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -57,7 +57,7 @@ known. The rest of the differences are docs/API.md section 9's precision notes. | `dot`, `mix` and `fast::sqrt` are the device's `OpDot`, `FMix` and `Sqrt` on every device, not Metal's fused chain, its two fused multiply-adds and `x · rsqrt(x)`: a `float` one on MoltenVK reaches Metal's own `dot`, `mix` and `fast::sqrt`, a `half` one is the instruction on its `float` container, rounded once; a `dot` of other than two to four lanes sums the `OpDot` of each chunk of up to four lanes. | The device's order is the contract. | `float` `dot` of n lanes within (3n − 1)·2^-24·Σ\|aᵢbᵢ\|, `mix` within 2^-21 of its two terms, `fast::sqrt` 4.5 ulp. `NativeDot` (`native-dot`), `NativeMix` (`native-mix`), `NativeTranscendentals` (`native-transcendentals`); a `dot` of other than two to four lanes within Vulkan's precision of its chunks' `OpDot` and sum, `DeviceArithmetic` (`device-arithmetic`) | | A filter emulated by fetches sums its taps in the device's arithmetic on every device: Metal's bicubic filter on every format (the Catmull-Rom weights computed in `f32` from the fraction, the sixteen taps summed by the device's multiply and add, a 32-bit float format's or a level under four texels' bilinear filter by its `FMix`), and an extended-range texture's linear, 3D and linear-mip-filter samples (`FMix` of the decoded taps at the `f32` fractions); a `half` result is the device's narrowing. Metal's fixed-point weight table, its exact grid sums rounded half up, its float accumulators and its sixty-fourth level fractions are not reproduced. The footprint, the addressing, the filter each format selects, the level and the format's clamp stay Metal's. | The device's arithmetic is the contract (rule 1); the device has no cubic filter on any committed profile (`VK_EXT_filter_cubic`), and no format holds the extended-range codes. | A few grid steps (`1/4080` at 8 bits), up to `2.1e-3` on an extended-range sRGB bicubic sample (`xr_bicubic::WEIGHTS_BOUND`), up to `1/64` of the levels' difference under a linear mip filter. `BicubicFilterArithmetic` (`bicubic-filter-arithmetic`) | | Fast-math sums, differences and products group, and a multiply contracts into an addition, as the device's compiler groups and fuses them, on every device, MoltenVK included: each operation is emitted in the AIR's order, one carrying both `contract` and `reassoc` undecorated and any other `NoContraction`. Metal's compiler takes its own grouping (its rank order of a sum's leaves, its pairing of a product's lane-uniform factors) and its own fusion pairs. | The device's grouping is the contract: what the AIR's flags allow, the device's compiler chooses; nothing reproduces Metal's choice. | Unbounded relative to the result where a sum of mixed signs is grouped otherwise, or a multiply-add is fused on one side alone; each operation kept apart is exact as written. `FastMathRewrites` (`fast-math-rewrites`) | -| `air.pack` and `air.unpack` of a normalized format are the device's conversion: `GLSL.std.450`'s `Pack`/`Unpack` `Unorm4x8`, `Snorm4x8`, `Unorm2x16` and `Snorm2x16`, and for `rgb10a2` and `rgb565` their definition by the device's `NClamp`, multiply, `RoundEven` (a pack) and multiply by the reciprocal (an unpack); `unorm4x8_srgb`'s colour is the MSL transfer functions by the device's `Pow` around the 8-bit instruction, as is an 8-bit sRGB storage texture's write through its UNORM alias. A `float` one of the four named formats on MoltenVK reaches Metal's own. The same conversions serve an implicit imageblock access of a normalized attachment (a `half` load rounding the unpacked `float` once more), the interlocked storage form's 8-bit sRGB attachment and sRGB word, and a snapshot's normalized codes (`c` times the `f32` nearest `1/D`). So does every conversion of an extended-range, padded 10-bit or bfloat texel, which no Vulkan format holds (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`, `RG10Unorm_X12`, their sRGB twins, `RGB10A2Unorm_sRGB`, the bfloat formats; every device): a read `float(c - 384)` (a padded code's `float(c)`) times the `f32` nearest `1/510` (`1/1023`), a write `RoundEven` of the clamped value's `f32` product plus 384, an sRGB twin's colour the MSL transfer by the device's `Pow` on the magnitude, a `half` result the device's narrowing, a bfloat NaN as it is. | The device's conversion is the contract. | A packed code within one of Metal's, apart only where `clamp(c)·scale` lies within its rounding of a half-integer (`Round`'s tie is the device's); an unpacked value within 2.5 ulp of the correctly rounded quotient; a decoded sRGB colour within half a twelve-bit step (`1/8190`) of Metal's table step `k/4095`, beyond its `Pow`'s bound; a NaN channel's code the device's (Metal's: 0). An extended-range or padded value within one `f32` ulp of Metal's quotient, a code within one of Metal's exact product, an sRGB twin's decoded value within half a `2^-13` step of Metal's table (`R10Unorm_X6_sRGB`'s 1.64 steps) and its code within one, a `half` result within one `half` ulp (Metal rounds ties away from zero, a bfloat sample's `half` toward zero), a bfloat NaN the device's (Metal's: `0x7fc00000`, a write `0x7fc0`). `DevicePackConversion` (`device-pack-conversion`) | +| `air.pack` and `air.unpack` of a normalized format are the device's conversion: `GLSL.std.450`'s `Pack`/`Unpack` `Unorm4x8`, `Snorm4x8`, `Unorm2x16` and `Snorm2x16`, and for `rgb10a2` and `rgb565` their definition by the device's `NClamp`, multiply, `RoundEven` (a pack) and multiply by the reciprocal (an unpack); `unorm4x8_srgb`'s colour is the MSL transfer functions by the device's `Pow` around the 8-bit instruction, as is an 8-bit sRGB storage texture's write through its UNORM alias. A `float` one of the four named formats on MoltenVK reaches Metal's own; on MoltenVK on the Apple M3 Max's macOS 27 identity (`DriverDeviation::MetalPackConversions`) so do `rgb565` in `float` and, in `half`, `unorm4x8`, `snorm4x8`, `rgb10a2` and `rgb565` both ways and `unorm2x16` and `snorm2x16` packed, measured to answer Metal's at every code and every `half` (`runtime_lane::pack_conversions`). The same conversions serve an implicit imageblock access of a normalized attachment (a `half` load rounding the unpacked `float` once more), the interlocked storage form's 8-bit sRGB attachment and sRGB word, and a snapshot's normalized codes (`c` times the `f32` nearest `1/D`). So does every conversion of an extended-range, padded 10-bit or bfloat texel, which no Vulkan format holds (`BGR10_XR`, `BGRA10_XR`, `RGB10A8_2P_XR10`, `R10Unorm_X6`, `RG10Unorm_X12`, their sRGB twins, `RGB10A2Unorm_sRGB`, the bfloat formats; every device): a read `float(c - 384)` (a padded code's `float(c)`) times the `f32` nearest `1/510` (`1/1023`), a write `RoundEven` of the clamped value's `f32` product plus 384, an sRGB twin's colour the MSL transfer by the device's `Pow` on the magnitude, a `half` result the device's narrowing, a bfloat NaN as it is. | The device's conversion is the contract. | A packed code within one of Metal's, apart only where `clamp(c)·scale` lies within its rounding of a half-integer (`Round`'s tie is the device's); an unpacked value within 2.5 ulp of the correctly rounded quotient; a decoded sRGB colour within half a twelve-bit step (`1/8190`) of Metal's table step `k/4095`, beyond its `Pow`'s bound; a NaN channel's code the device's (Metal's: 0). An extended-range or padded value within one `f32` ulp of Metal's quotient, a code within one of Metal's exact product, an sRGB twin's decoded value within half a `2^-13` step of Metal's table (`R10Unorm_X6_sRGB`'s 1.64 steps) and its code within one, a `half` result within one `half` ulp (Metal rounds ties away from zero, a bfloat sample's `half` toward zero), a bfloat NaN the device's (Metal's: `0x7fc00000`, a write `0x7fc0`). `DevicePackConversion` (`device-pack-conversion`) | | Off MoltenVK a `float` multiply, a fused multiply-add by `OpFmaKHR`, and a `float` `ldexp` (whose result below `2^-126` is that multiply's product) round before Metal's flush: Metal flushes a result whose exact value lies below `2^-126` before rounding it, so a result whose exact value lies within half a unit below `2^-126` answers `2^-126` of its sign where Metal answers the zero of its sign. | Every device measured off MoltenVK (RADV, ANV, NVIDIA, lavapipe) rounds first; its multiply is the contract. | Announced once per device as it is made: `float-tininess-after-rounding` | | `f32` denormals in a `float` operation on a device not measured to read them as Metal does (`DriverDeviation::MetalFloatDenormals`: lavapipe, and every unmeasured device), in `floor`, `ceil` and `fneg` on every device (a nearest pixel sample's texel `floor(x)` among them, which Metal's sampler reads from a subnormal `x` itself, a negative one as texel -1, where MoltenVK's `floor` reads it as the zero of its sign: recorded through a constexpr sampler always, through a runtime slot only under a pipeline made for a nearest pixel state, through an argument buffer as `argument-pixel-sampler-scaling`), in the maths functions (`fabs`, `sign` and `fract` among them, and the zero and sign tests of `pow`, `powr` and `atan2`) and the device's order of the rows above, and in a conversion to or from `double`. Metal reads them as zero and flushes a denormal result. | The device's reading is the contract: Vulkan lets each device keep or flush them, and Metal runs no `double`, so its reading of a conversion is not measured. | `DeviceDenormals` (`device-denormals`) | | Samples, gathers, depth comparisons and level queries are the device's own sampler's on every device whose sampler is not Metal's (every device but MoltenVK): its filter, footprint, level, anisotropy, sRGB decode and comparison, its level clamp (the descriptor's as given, which Metal holds on a `1/64` grid) and its reading of a subnormal coordinate (which Metal reads as the zero of its sign before addressing). A sample's or gather's residency on a device with `shaderResourceResidency` is the device's `OpImageSparse*` word and non-resident value (`SparseResidency`); Metal's footprint rule answers it only where the device has no residency and the slot's tile map does. A two-plane YCbCr texture's linear sample is the device's filter of its texels (the device's own Y′CbCr conversion's where it converts the format, next row; Metal's reads exactly elsewhere); where the device's memory is the host's, a sample that reads the planes in place is Metal's filter exactly. An 8-bit sRGB format the device cannot sample (`R8_SRGB` on lavapipe, `R8G8_SRGB` on lavapipe, ANV and NVIDIA) is held as its UNORM twin, the device lacking its decode: a read, a sample, a fetch, a gather and a bicubic tap decode what the twin's view reads (one texel's codes, or the device's filter of them) by the MSL transfer through the device's `Pow`. | The device's sampler is the contract. | Linear filter within one code (1/255) on the measured devices, sRGB within 1.83, a two-plane YCbCr texture's within 1.183; levels, anisotropy, cubes, 3D, gathers and comparisons unmeasured. A twin's texel: the transfer within the device's `Pow` (MoltenVK's within 1.83e-7 through a storage alias, `runtime_lane::srgb_storage`) where Metal's table rounds it to a twelve-bit step (up to 1/8190 apart); a filtered sample decodes the filtered codes, up to 0.286 off for a blend of codes 0 and 255 (`SrgbTexelDecode`). `DeviceSampling` (`device-sampling`) |