From 3e28f68331a1c4484e914a2d27f15c1be74e93d0 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 2 Nov 2026 11:32:02 -0800 Subject: [PATCH] Carve MoltenVK on the M3 Max's identity out of NativeNanEncoding for NaN moves reims-vgpu treats precision notes as fatal on Apple GPUs; NativeNanEncoding was its largest group of Mac-only failures. Measured on the M3 Max (MoltenVK 1.4.2, macOS 27.0.1), the device's widening of a half to float, its narrowing back, and float fneg/fabs and half fabs answer Metal's NaN bits, so the note was recorded where nothing differs. What: a new DriverDeviation::MetalNanMoves (VkProperty::MetalNanMoves), taken by the APPLE9 MoltenVK row alone. Where taken: - a float fneg or fabs records no NativeNanEncoding and the module requires the property (SPIRV-Cross writes -x and abs(x), Metal's own operators on the same operand); - a half's widening to float (fpext, air.convert) and a half fabs, and a module's reads and encodes of a half's bits, record no note and require the property, but only where the module moves its halves through the registers as measured. narrow::moves_unfolded keeps the note where a widened half is stored anywhere but a buffer, workgroup memory or a function's float variable, passes through a call, return, group, atomic or image operation, has its bits read (a bitcast that is not stored, frexp/modf/ldexp: the frexp routines stay noted), or where the module holds a float NaN constant other than 0x7fc00000. - A half fneg stays noted on every profile: the measured shapes matched only because the driver's compiler moved the negation onto the half. By construction: MoltenVK's MSL writes float(as_type(x)) and half(f); Metal's compiler folds half(float(h)) across selects, phis and a function's local float variable, so moved halves keep their bits as Metal's do. Verified (all runs on this M3 Max): - Plain Metal running the lane's own AIR (8 kernels; every one of the 65,536 half patterns, 98,368 float words including 65,536 structured NaNs) matches the lane's model in every word. - runtime_lane::nan_moves on MoltenVK: the note is absent from every kernel but the half fneg, and 0 lanes differ from Metal in all 8 kernels. - Earlier MSL probe, fast and precise math: the same equalities over 262,144 float words. - New core tests: half_moves_are_metals_only_where_the_device_folds_them (a payload NaN constant keeps the note), the frexp negative control in engine_metal_routines, float_sign_operations and the class C/D NaN tests with a moves argument, and the driver-facts lists. - Core nextest (metal2vulkan, air, runtime, devtools, --all-features): 4,989 passed. Docs: API.md (native-nan-encoding exemption), HOWTO.md, the PrecisionNote and deviation rustdoc. SEMANTICS_VERSION 1946, ARTIFACT_FORMAT_VERSION 483 (a new VkProperty in the codec); these bumps cover the rest of this branch. api_signatures blessed (two variants); the moltenvk-m3 profile's golden hash re-blessed. (cherry picked from commit 93ae66b6ddb46b4d0d3db1944a4b043c40911592) (Note on the development copy: this message names SEMANTICS_VERSION 1946; the commit sets 1948, after a rebase.) --- .../src/runtime_lane.rs | 2 + .../src/runtime_lane/nan_moves.rs | 327 ++++++++++++++++++ crates/metal2vulkan/src/cache/codec.rs | 1 + crates/metal2vulkan/src/cache/mod.rs | 4 +- crates/metal2vulkan/src/device/derive.rs | 3 + .../metal2vulkan/src/device/driver_facts.rs | 22 ++ crates/metal2vulkan/src/device/profile.rs | 3 + .../metal2vulkan/src/device/requirements.rs | 9 + .../src/device/tests/driver_facts.rs | 6 +- crates/metal2vulkan/src/error/mod.rs | 24 +- crates/metal2vulkan/src/lower/arith/mod.rs | 71 +++- crates/metal2vulkan/src/lower/arith/nan.rs | 15 +- crates/metal2vulkan/src/lower/arith/narrow.rs | 304 +++++++++++++--- crates/metal2vulkan/src/lower/arith/tests.rs | 1 + crates/metal2vulkan/src/pipeline/artifact.rs | 8 +- crates/metal2vulkan/src/pipeline/compile.rs | 23 +- crates/metal2vulkan/src/pipeline/testing.rs | 11 + .../metal2vulkan/src/tests/engine_access.rs | 37 +- crates/metal2vulkan/src/tests/engine_arith.rs | 146 ++++++-- .../src/tests/engine_cross_class.rs | 34 +- .../src/tests/engine_float_call_notes.rs | 39 ++- .../src/tests/engine_metal_routines.rs | 7 +- .../src/tests/engine_native_half.rs | 20 +- .../src/tests/engine_typed_threadgroup.rs | 12 +- crates/metal2vulkan/tests/api_signatures.tsv | 2 + crates/metal2vulkan/tests/golden_hashes.tsv | 2 +- docs/API.md | 14 +- docs/HOWTO.md | 8 +- 28 files changed, 1006 insertions(+), 149 deletions(-) create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/nan_moves.rs diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index fa107593d..2cb3308a1 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -605,6 +605,8 @@ mod msaa_32bit; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod msaa_depth_moves; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod nan_moves; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod nan_resolves; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod narrow_clamps; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/nan_moves.rs b/crates/metal2vulkan-validation/src/runtime_lane/nan_moves.rs new file mode 100644 index 000000000..6fa29e06c --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/nan_moves.rs @@ -0,0 +1,327 @@ +//! The NaNs a kernel moves rather than computes, on the device the cfg selects, under the +//! validation layer: a `half` widened to `float` from its bits, a `half` moved through a branch's +//! merge and to a later block and stored, a `float` negated and its magnitude taken, and a `half`'s +//! magnitude taken (`DriverDeviation::MetalNanMoves`). A merge's `half` the module holds in a +//! function's `float` variable, which the driver's compiler keeps in the registers. +//! +//! What plain Metal answers (our probe on the Apple M3 Max under macOS 27.0.1, with and without +//! fast math, the same AIR as this lane's): a `half` widened to `float` is its exact value, every +//! NaN `0x7fc00000`; a `half` moved and stored keeps its bits, a signalling or negative NaN's +//! included; a `float` `fneg` and `fabs` flip and clear the sign of every word, a NaN's payload +//! kept; a `half` `fabs` clears the sign, every NaN `0x7e00`. A `half` `fneg` answers every NaN as +//! `0x7e00` too, which a `float` read of it widens to `0x7fc00000`. +//! +//! The module holds each `half` widened to `float` and moves its NaN by the device's widening, +//! narrowing, negation and magnitude. Where the profile takes the deviation (MoltenVK on the Apple +//! M3 Max's macOS 27 identity), each kernel but the `half` `fneg`'s records no +//! `PrecisionNote::NativeNanEncoding` and every lane is Metal's word. Elsewhere a kernel that +//! converts records the note and its NaN lanes are the device's, which the test prints as +//! `NAN-MOVES` lines; its other +//! lanes are Metal's but a `float` denormal the device flushes where the stage records +//! `PrecisionNote::DeviceDenormals`. The `half` `fneg` read as `float` (`neg16w`) records the note +//! on every profile: the device negates the held `float`, whose NaN keeps its flipped sign unless +//! the driver's compiler moves the negation onto the `half` before the widening, as MoltenVK's did +//! here (every lane Metal's), which nothing states. + +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}; + +/// A kernel of the lane: its entry, whether it reads `half` words (else `float` ones), whether it +/// writes `half` words, and its body between the load of `%x` and the store of `%r`. +struct Kernel { + entry: &'static str, + reads_half: bool, + writes_half: bool, + body: &'static str, +} + +/// The kernels. `phi16` and `phi16x2` (a `half2`'s merge) read their second operand at `gid ^ 1`, +/// and they and `late16` branch on bit 1 of `gid`, so the `half` crosses a block before its store. +const KERNELS: [Kernel; 8] = [ + Kernel { + entry: "widen16", + reads_half: true, + writes_half: false, + body: " %r = fpext half %x to float\n", + }, + Kernel { + entry: "phi16", + reads_half: true, + writes_half: true, + body: " %g1 = xor i32 %gid, 1\n %i1 = zext i32 %g1 to i64\n %q = getelementptr inbounds half, ptr addrspace(1) %in, i64 %i1\n %y = load half, ptr addrspace(1) %q, align 2\n %c = and i32 %gid, 2\n %z = icmp eq i32 %c, 0\n br i1 %z, label %left, label %right\nleft:\n br label %join\nright:\n br label %join\njoin:\n %r = phi half [ %y, %left ], [ %x, %right ]\n", + }, + Kernel { + entry: "phi16x2", + reads_half: true, + writes_half: true, + body: " %g1 = xor i32 %gid, 1\n %i1 = zext i32 %g1 to i64\n %q = getelementptr inbounds half, ptr addrspace(1) %in, i64 %i1\n %y = load half, ptr addrspace(1) %q, align 2\n %va = insertelement <2 x half> undef, half %x, i32 0\n %vb = insertelement <2 x half> %va, half %y, i32 1\n %wa = insertelement <2 x half> undef, half %y, i32 0\n %wb = insertelement <2 x half> %wa, half %x, i32 1\n %c = and i32 %gid, 2\n %z = icmp eq i32 %c, 0\n br i1 %z, label %left, label %right\nleft:\n br label %join\nright:\n br label %join\njoin:\n %v = phi <2 x half> [ %wb, %left ], [ %vb, %right ]\n %r = extractelement <2 x half> %v, i32 0\n", + }, + Kernel { + entry: "late16", + reads_half: true, + writes_half: true, + body: " %c = and i32 %gid, 2\n %z = icmp eq i32 %c, 0\n br i1 %z, label %left, label %join\nleft:\n br label %join\njoin:\n %r = bitcast half %x to half\n", + }, + Kernel { + entry: "abs16", + reads_half: true, + writes_half: true, + body: " %r = call half @air.fabs.f16(half %x)\n", + }, + Kernel { + entry: "neg16w", + reads_half: true, + writes_half: false, + body: " %n = fneg half %x\n %r = fpext half %n to float\n", + }, + Kernel { + entry: "neg32", + reads_half: false, + writes_half: false, + body: " %r = fneg float %x\n", + }, + Kernel { + entry: "abs32", + reads_half: false, + writes_half: false, + body: " %r = call float @air.fabs.f32(float %x)\n", + }, +]; + +/// The lane's AIR: every kernel of [`KERNELS`], buffer 0 its input words, buffer 1 its results. +fn library() -> String { + let mut defs = String::new(); + let mut metas = String::new(); + let mut refs = Vec::new(); + for (k, kernel) in KERNELS.iter().enumerate() { + let (inty, insize) = match kernel.reads_half { + true => ("half", 2), + false => ("float", 4), + }; + let (outty, outsize) = match kernel.writes_half { + true => ("half", 2), + false => ("float", 4), + }; + defs.push_str(&format!( + "define void @{e}(ptr addrspace(1) %in, ptr addrspace(1) %out, i32 %gid) {{\nentry:\n %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{body} %o = getelementptr inbounds {outty}, ptr addrspace(1) %out, i64 %i\n store {outty} %r, ptr addrspace(1) %o, align {outsize}\n ret void\n}}\n\n", + e = kernel.entry, + body = kernel.body, + )); + let n = 10 + 4 * k; + refs.push(format!("!{n}")); + 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\", !\"{inty}\", !\"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\", !\"{outty}\", !\"air.arg_name\", !\"out\"}}\n", + e = kernel.entry, + a = n + 1, + b = n + 2, + c = n + 3, + )); + } + format!( + "; Owned synthetic kernels.\nsource_filename = \"nan_moves.metal\"\n\n{defs}declare half @air.fabs.f16(half)\ndeclare float @air.fabs.f32(float)\n\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 `float` words the `float` kernels read: every `half` value widened exactly, NaNs of both +/// signs over every top-12 payload bits and four low patterns, and the specials. +fn float_words() -> Vec { + let mut words: Vec = (0..=u16::MAX).map(widened).collect(); + for sign in [0, 0x8000_0000] { + for high in 0..4096u32 { + for low in [0, 1, 0x400, 0x7ff] { + let payload = match high << 11 | low { + 0 => 1 << 22, + p => p, + }; + words.push(sign | 0x7f80_0000 | payload); + } + } + } + words.extend([ + 0, + 0x8000_0000, + 1, + 0x8000_0001, + 0x007f_ffff, + 0x0080_0000, + 0x7f7f_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, + } +} + +/// Whether half `h` is a NaN. +fn half_nan(h: u32) -> bool { + h & 0x7c00 == 0x7c00 && h & 0x3ff != 0 +} + +/// Whether `float` word `w` is a NaN. +fn float_nan(w: u32) -> bool { + w & 0x7f80_0000 == 0x7f80_0000 && w & 0x007f_ffff != 0 +} + +/// Metal's word for input word `x` of `kernel` (the module docs). +fn metal(kernel: &str, x: u32) -> u32 { + match kernel { + "widen16" if half_nan(x) => 0x7fc0_0000, + "widen16" => widened(x as u16), + "phi16" | "phi16x2" | "late16" => x, + "abs16" if half_nan(x) => 0x7e00, + "abs16" => x & 0x7fff, + "neg16w" if half_nan(x) => 0x7fc0_0000, + "neg16w" => widened(x as u16 ^ 0x8000), + "neg32" => x ^ 0x8000_0000, + "abs32" => x & 0x7fff_ffff, + _ => unreachable!("{kernel}"), + } +} + +/// The input word lane `i` of `kernel` stores: a merge's lanes whose bit 1 is clear take their +/// neighbour's. +fn source(kernel: &str, i: usize) -> usize { + match kernel { + "phi16" | "phi16x2" if i & 2 == 0 => i ^ 1, + _ => i, + } +} + +/// `kernel`'s words on `device` for `input`. +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.reads_half { + true => input + .iter() + .flat_map(|&w| (w as u16).to_le_bytes()) + .collect(), + false => input.iter().flat_map(|w| w.to_le_bytes()).collect(), + }; + let out_size: u64 = if kernel.writes_half { 2 } else { 4 }; + let n = input.len() as u64; + let input = buffer_with(device, &bytes).unwrap(); + let out = buffer_with(device, &vec![0x5a; (n * out_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 * out_size).unwrap(); + match kernel.writes_half { + true => got + .as_chunks::<2>() + .0 + .iter() + .map(|b| u32::from(u16::from_le_bytes(*b))) + .collect(), + false => got + .as_chunks::<4>() + .0 + .iter() + .map(|b| u32::from_le_bytes(*b)) + .collect(), + } +} + +/// Every kernel answers Metal's word on every lane where its stage records no +/// `PrecisionNote::NativeNanEncoding`, and its NaN lanes are the device's where it records the +/// note; where the profile takes `DriverDeviation::MetalNanMoves` (`VkProperty::MetalNanMoves`) +/// no stage records it but the `half` `fneg` read as `float`, which records it on every profile. +/// Every `half` bit pattern, and 98,368 `float` words (the module docs). +#[test] +fn moved_nans_are_metals_where_measured_and_noted_elsewhere() { + let air = llvm_assemble_text(&library()).unwrap(); + let halves: Vec = (0..=u32::from(u16::MAX)).collect(); + let floats = float_words(); + on_device(|device, _| { + let moves = device + .compile_device() + .profile() + .enabled() + .properties + .contains(&VkProperty::MetalNanMoves); + let mut report = Vec::new(); + for kernel in &KERNELS { + let notes = stage_notes(device, &air, kernel.entry); + let noted = notes.contains(&PrecisionNote::NativeNanEncoding); + let flushes = notes.contains(&PrecisionNote::DeviceDenormals); + // The `half` `fneg` is noted on every profile; nothing else where the moves are + // measured. + let always = kernel.entry == "neg16w"; + assert!(!always || noted, "{}: {notes:?}", kernel.entry); + assert!( + !moves || noted == always, + "{}: NativeNanEncoding recorded {noted} where the profile takes MetalNanMoves", + kernel.entry + ); + let input = if kernel.reads_half { &halves } else { &floats }; + let got = run(device, kernel, &air, input); + let nan = |x: u32| match kernel.reads_half { + true => half_nan(x), + false => float_nan(x), + }; + let denormal = + |x: u32| !kernel.reads_half && x & 0x7f80_0000 == 0 && x & 0x7f_ffff != 0; + let mut nan_differ = 0; + for (i, &g) in got.iter().enumerate() { + let x = input[source(kernel.entry, i)]; + let want = metal(kernel.entry, x); + if g == want { + continue; + } + if nan(x) && noted { + nan_differ += 1; + continue; + } + assert!( + flushes && denormal(x), + "{}: input {x:#x} answered {g:#x}, Metal's {want:#x} (notes {notes:?})", + kernel.entry + ); + } + report.push(format!( + "NAN-MOVES {} on {}: {nan_differ} NaN lanes of {} 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 8fadb8f38..3b6990a19 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1033,6 +1033,7 @@ codec_enum! { MetalDepth16Stores, MetalDepth16BiasedStores, MetalInterpolation, MetalFirstVertexIndices, MetalFullQuads, ProvokingVertexModePerPipeline, DepthImageKeepsValuesOutsideUnitRange, MetalNormalizedVertexFetch, MetalAlphaCoverage, InterpolateAtOffsetFromSevenSixteenths, + MetalNanMoves, } VkLimit { MaxComputeWorkGroupSize(f0), MaxComputeWorkGroupCount(f0), MaxComputeWorkGroupInvocations, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index c018da1b1..41c9eb6db 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 1947; +pub const SEMANTICS_VERSION: u32 = 1948; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1947; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 482; +pub const ARTIFACT_FORMAT_VERSION: u32 = 483; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index 49b9a7c12..0538f9d3c 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -809,6 +809,9 @@ fn enabled_caps(desc: &DeviceDescription, deviations: &BTreeSet if deviations.contains(&DriverDeviation::MetalAlphaCoverage) { properties.insert(VkProperty::MetalAlphaCoverage); } + if deviations.contains(&DriverDeviation::MetalNanMoves) { + properties.insert(VkProperty::MetalNanMoves); + } 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 cf9a99e5e..b504a82da 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -396,6 +396,24 @@ pub(crate) fn among( /// RTX 5080 Laptop GPU, which stores a fragment of alpha 1/2 at one sample (the conformance case /// `a2c-on-1-alpha-50`). /// +/// `MetalNanMoves`: MoltenVK 1.4.2 (its SPIRV-Cross `6c09849f`) writes a 16-bit float's widening +/// as Metal's `float(half)`, the narrowing as `half(float)`, `OpFNegate` as `-x` and `FAbs` as +/// `abs(x)`, Metal's own conversions and operators, and the driver's compiler folds a narrowing of +/// a widening moved through the registers (a select, a branch's merge, a function's `float` +/// variable) into the `half` itself, as Metal moves a `half` unwidened. Measured on the M3 Max +/// under macOS 27.0.1 (2026-11-02), word for word against plain Metal: every one of the 65,536 +/// `half` bit patterns widened (every NaN `0x7FC00000`), moved through a `select`, a branch's +/// merge (a `half` and a `half2`) and to a later block and stored (each its own bits), and its +/// `half` `fabs` (every NaN `0x7E00`); and 262,144 `float` words (every `half` value widened, +/// 65,536 NaNs of both signs over every top-12 payload bits and four low patterns, 32,768 random +/// NaNs, 131,072 random words) narrowed to `half`, negated and their magnitude taken: none +/// differs, with and without fast math (the AIR of `runtime_lane::nan_moves`, which checks the +/// runtime against Metal's answers, run on Metal too). The `half` `fneg` matched too, but by the +/// driver's compiler moving the +/// negation onto the `half`, which nothing states, so it stays noted; and a module that carries a +/// widened `half` elsewhere or reads its bits is outside the measurement +/// (`narrow::moves_unfolded`). 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`). @@ -582,6 +600,10 @@ pub(crate) const DEVIATIONS: &[Measured] = &[ device: Some(APPLE9), ..moltenvk_on_apple(DriverDeviation::MetalAlphaCoverage) }, + Measured { + device: Some(APPLE9), + ..moltenvk_on_apple(DriverDeviation::MetalNanMoves) + }, ]; /// NVIDIA's `vendorID`. diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index d452d081b..eef378820 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -336,6 +336,9 @@ impl DeviceProfile { .enabled .properties .contains(&VkProperty::MetalAlphaCoverage), + DriverDeviation::MetalNanMoves => { + f.enabled.properties.contains(&VkProperty::MetalNanMoves) + } } } diff --git a/crates/metal2vulkan/src/device/requirements.rs b/crates/metal2vulkan/src/device/requirements.rs index 9d222515c..3a83dc72a 100644 --- a/crates/metal2vulkan/src/device/requirements.rs +++ b/crates/metal2vulkan/src/device/requirements.rs @@ -832,6 +832,15 @@ pub enum VkProperty { /// requires it, where no module does (the coverage is the pipeline's multisample state); /// without it, the pipeline's fragment stage records that note. MetalAlphaCoverage, + /// The device's widening and narrowing between 16- and 32-bit floats, and its `OpFNegate` + /// and `FAbs`, answer Metal's NaN bits (the driver's measured deviation + /// [`DriverDeviation::MetalNanMoves`](crate::error::DriverDeviation::MetalNanMoves)). No Vulkan + /// query reports it: Vulkan states no NaN's bits. A module that reads a `half` from its bits or + /// encodes one to them, widens a `half` to `float`, negates a `float` or takes the magnitude + /// of a `float` or `half`, and records no + /// [`PrecisionNote::NativeNanEncoding`](crate::pipeline::PrecisionNote::NativeNanEncoding) + /// for it requires it. + MetalNanMoves, /// `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 df33247bf..5a7a5a244 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -155,6 +155,7 @@ fn taken(p: &crate::device::DeviceProfile) -> Vec D::MetalAlphaCoverage, property(VkProperty::MetalAlphaCoverage), ), + (D::MetalNanMoves, property(VkProperty::MetalNanMoves)), ] .into_iter() .inspect(|&(d, taken)| { @@ -169,7 +170,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 and alpha to coverage, and every Apple GPU's 16-bit unorm depth stores, interpolation +/// storage writes, full quads, normalized vertex fetch, alpha to coverage and moved NaNs, 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 @@ -227,10 +228,11 @@ 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 and alpha to coverage, measured on the M3 Max under it. + // fetch, alpha to coverage and moved NaNs, 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); 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 e7081f3ba..8d5b64af4 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -670,7 +670,9 @@ pub enum DriverDeviation { /// widening (`x + -0` of every `x`), exact but for a NaN, denormals included: a module that /// reads a `half` from its bits by that widening (every profile with `shaderFloat16` does) /// requires the property for its denormals, and records `PrecisionNote::NativeNanEncoding` - /// for its NaNs' bits. + /// for its NaNs' bits but where the profile takes [`MetalNanMoves`]. + /// + /// [`MetalNanMoves`]: DriverDeviation::MetalNanMoves MetalHalfArithmetic, /// The device stores every `float` but a NaN that a shader writes to a half-float storage /// image (`R16Float`, `RG16Float`, `RGBA16Float`; a storage texel buffer of one too) as Metal @@ -814,6 +816,26 @@ pub enum DriverDeviation { /// alpha records no `PrecisionNote::DeviceAlphaCoverage` and requires the property. /// Unmeasured, such a pipeline's fragment stage records the note. MetalAlphaCoverage, + /// The device's operations that move a `float` or `half` NaN, rather than compute one, answer + /// Metal's bits (`VkProperty::MetalNanMoves`): its widening of a 16-bit float to 32 bits + /// (`OpFConvert`) answers `0x7FC00000` for every `half` NaN, as Metal's `float(half)` does; + /// its narrowing of a 32-bit float to 16 bits answers Metal's `half` NaN, and its narrowing of + /// such a widening, moved through the registers (selects, phis, a function's `float` + /// variable), which the driver's compiler folds, the `half`'s own bits, as Metal's moves of a + /// `half` keep them; its `OpFNegate` and `FAbs` of a `float` keep a NaN's payload with the sign + /// flipped or cleared, as Metal's `fneg` and `fabs` do; and its `FAbs` of a `half` held + /// widened answers the canonical NaN, as Metal's `half` `fabs` does. Where the profile takes + /// it, a module that reads a `half` from its bits or encodes one to them, a `half`'s widening + /// to `float` and a `half` `fabs` record no `PrecisionNote::NativeNanEncoding` and the module + /// requires the property, but where the module carries a widened `half` out of the registers + /// (a store to a stage output or another variable, a call, a group, atomic or image operation) + /// or reads its bits before narrowing it, or holds a `float` NaN constant other than + /// `0x7FC00000`, which the measurement does not cover (`narrow::moves_unfolded`): there each + /// records the note. A `float` `fneg` and `fabs` record none and require the property. A `half` + /// `fneg` records the note on every profile: the device negates the held `float`, whose NaN + /// keeps its flipped sign unless the driver's compiler moves the negation onto the `half`. + /// Unmeasured, each records it. + MetalNanMoves, } /// 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 372663640..bf796e384 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -713,6 +713,16 @@ pub struct ArithPlan { /// ([`ArithStrategy::F16`]), measured to be Metal's (`DriverDeviation::MetalHalfArithmetic`), /// recorded at selection: the module then requires `VkProperty::MetalHalfArithmetic`. pub f16_arith: bool, + /// Whether the NaN a `float` `fneg` or `fabs` moves is left to the device because it is + /// measured to answer Metal's (`DriverDeviation::MetalNanMoves`, [`nan::moves_answered`]), + /// recorded at selection: the module then requires `VkProperty::MetalNanMoves`. + pub nan_moves: bool, + /// Whether the NaN of a `half` held widened that a widening to `float` or a `half` `fabs` + /// moves is left to the device because it is measured to answer Metal's + /// ([`nan::moves_answered`]), recorded at selection: the module then requires + /// `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, /// 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`]); @@ -1226,6 +1236,26 @@ fn with_nan( s } +/// `answer`, the NaN Metal answers for an operation that moves a NaN (a `half`'s widening to +/// `float`, a `float` `fneg`), where the device is not measured to answer it: `None` on a profile +/// whose device's moves are measured to be Metal's ([`nan::moves_answered`]), which the plan +/// records ([`ArithPlan::held_nan_moves`] for a `half` held widened, else +/// [`ArithPlan::nan_moves`]). +fn moved_nan( + cx: &mut SelectCx<'_>, + answer: Option, + held: bool, +) -> Option { + if answer.is_some() && nan::moves_answered(cx.profile) { + match held { + true => cx.families.arith.held_nan_moves = true, + false => cx.families.arith.nan_moves = true, + } + return None; + } + answer +} + /// Record `NativeNanEncoding` where Metal answers a NaN (`answer`) the device is not measured to /// answer ([`nan::NanAnswer::device_answers`]). fn note_native_nan(cx: &mut SelectCx<'_>, answer: Option) { @@ -1430,6 +1460,12 @@ fn select_in( device_float(cx, f, true, false); fp_env(cx, *fmf, f); let nan = f.float_fmt().and_then(nan::fneg_answer); + // A `float` one's NaN is Metal's where the device's negation is measured to be + // ([`moved_nan`]); a `half` one's held result keeps the flipped sign, noted. + let nan = match f.float_fmt() { + Some(FloatFmt::F32) => moved_nan(cx, nan, false), + _ => nan, + }; with_nan(cx, S::FNeg { form: f }, nan) } InstKind::ICmp { pred, a, .. } => { @@ -1540,8 +1576,13 @@ fn select_cast( from, to, }; - // A `float` narrowed to `half` answers Metal's canonical `half` NaN. + // A `float` narrowed to `half` answers Metal's canonical `half` NaN; a `half` widened + // to `float` is the widening it was read with ([`moved_nan`]). let answer = match (from.float_fmt(), to.float_fmt()) { + (Some(FloatFmt::Half), Some(FloatFmt::F32)) => { + let answer = nan::cast_answer(op, FloatFmt::Half, FloatFmt::F32); + moved_nan(cx, answer, true) + } (Some(a), Some(b)) => nan::cast_answer(op, a, b), _ => None, }; @@ -1906,6 +1947,12 @@ fn select_float_fn( arith.fmod_uses |= fmod; arith.device_min_max |= device_min_max(cx.profile, op, f); } + if facts.nan_moves && moves_nan(lowered.how, f) { + match f.float_fmt() { + Some(FloatFmt::Half) => cx.families.arith.held_nan_moves = true, + _ => cx.families.arith.nan_moves = true, + } + } if let FloatLowering::Fma(fma) | FloatLowering::FastFmod(fma) = lowered.how { cx.families.arith.take_fma(fma); } @@ -2071,6 +2118,9 @@ struct FloatFacts { /// Whether Metal's minimum and maximum functions are the device's not measured to be Metal's: /// the profile does not take `DriverDeviation::MetalMinMax` ([`native_min_max`]). native_min_max: bool, + /// Whether the device's `fabs` answers Metal's NaN, `float` and `half` + /// ([`nan::moves_answered`]). + nan_moves: bool, } impl FloatFacts { @@ -2082,6 +2132,7 @@ impl FloatFacts { device_denormals: denormal::device_flushes(p), nans: nan::encoding(p), native_min_max: !p.takes_driver_deviation(crate::error::DriverDeviation::MetalMinMax), + nan_moves: nan::moves_answered(p), } } } @@ -2223,6 +2274,10 @@ fn float_call( facts: FloatFacts, ) -> Option { let mut call = float_call_of(op, fast, fmf, f, facts)?; + // The device's `fabs` moves the NaN Metal's does where that is measured ([`moves_nan`]). + if facts.nan_moves && moves_nan(call.how, f) { + call.nan = None; + } let mut native = BTreeSet::new(); if call.nan.is_some_and(|a| !a.device_answers(facts.nans)) { native.insert(PrecisionNote::NativeNanEncoding); @@ -2241,6 +2296,14 @@ fn float_call( Some(call) } +/// Whether a float call lowered as `how` on form `f` moves its operand's NaN rather than computes +/// one, so that a device measured to move it as Metal does answers Metal's NaN +/// ([`nan::moves_answered`]): `fabs` on `float` and `half`. +fn moves_nan(how: FloatLowering, f: Form) -> bool { + matches!(how, FloatLowering::Fn(FloatFn::Abs)) + && matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half)) +} + /// [`float_call`] before the device's NaN and minimum and maximum notes. fn float_call_of( op: FloatFn, @@ -2652,8 +2715,12 @@ fn select_convert( return Err(cx.invariant("an air.convert whose kinds disagree with its types")); } let s = ArithStrategy::Convert { kind, from, to }; - // Metal's widening of a `half` NaN, as `fpext`'s. + // Metal's widening of a `half` NaN, as `fpext`'s ([`moved_nan`]). let nan = match (kind, from.float_fmt(), to.float_fmt()) { + (ConvertKind::Float, Some(FloatFmt::Half), Some(FloatFmt::F32)) => { + let answer = nan::convert_answer(FloatFmt::Half, FloatFmt::F32); + moved_nan(cx, answer, true) + } (ConvertKind::Float, Some(a), Some(b)) => nan::convert_answer(a, b), _ => None, }; diff --git a/crates/metal2vulkan/src/lower/arith/nan.rs b/crates/metal2vulkan/src/lower/arith/nan.rs index eb3a55013..3110d86d9 100644 --- a/crates/metal2vulkan/src/lower/arith/nan.rs +++ b/crates/metal2vulkan/src/lower/arith/nan.rs @@ -51,7 +51,9 @@ pub enum NanAnswer { /// `0x7FC00000` for a result the device computes exactly, passing its operand's NaN on: the /// widening of a `half` to `float`, which a `half` held widened leaves no device operation at /// all, and `half` `fneg` and `fabs`, which a device computes on the sign alone. No device's - /// arithmetic answers it, so no device fact leaves it to the device. + /// arithmetic answers it, so the canonical-NaN fact does not leave it to the device; where the + /// device's moves of a NaN are measured ([`moves_answered`]), the held `half` is its widening's + /// canonical NaN, so the widening and `fabs` answer it. CanonicalExact, /// The canonical NaN with a NaN first operand's sign, and `+` for a NaN of another origin (a /// domain error): precise `asin`, `atan`, `asinh`, `atanh`. @@ -463,3 +465,14 @@ fn flagged_precise(op: FloatFn) -> bool { pub fn encoding(p: &DeviceProfile) -> NanEncoding { p.fields().nan_encoding } + +/// Whether profile `p`'s device is measured to answer Metal's NaN where an operation moves a NaN +/// rather than computes one (`DriverDeviation::MetalNanMoves`): its widening of a `half` to +/// `float` ([`NanAnswer::CanonicalExact`]), its `float` `fneg` and `fabs` +/// ([`NanAnswer::Operand`]) and its `half` `fabs` ([`NanAnswer::CanonicalExact`]), each where the +/// module moves its `half` values only as measured (`narrow::moves_unfolded`). A `half` `fneg`, +/// whose held result keeps the operand's NaN with its sign flipped unless the driver's compiler +/// moves the negation onto the `half`, is not among them. +pub fn moves_answered(p: &DeviceProfile) -> bool { + p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves) +} diff --git a/crates/metal2vulkan/src/lower/arith/narrow.rs b/crates/metal2vulkan/src/lower/arith/narrow.rs index a6fdb79da..9f0721da4 100644 --- a/crates/metal2vulkan/src/lower/arith/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/narrow.rs @@ -57,8 +57,8 @@ use crate::spirv::builder::{FunctionBuilder, NarrowFmt, QuantizeForm}; use crate::spirv::error::{BResult, BuildError, TypeRule}; use crate::spirv::ids::Value; use crate::spirv::ir::{ - BinOp, ConstBits, ConstKind, Constant, ConvOp, ExecMode, GlslOp, Inst, Type, TypedModule, UnOp, - ValueOrigin, + BinOp, ConstBits, ConstKind, Constant, ConvOp, ExecMode, GlslOp, Inst, StorageClass, + Terminator, Type, TypedModule, UnOp, ValueOrigin, }; /// The unsigned 32-bit integer form with `f`'s lanes. @@ -1301,25 +1301,27 @@ fn device_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult< /// [`QuantizeForm::Device`]), or an `OpFConvert` to 32 bits of an `OpBitcast` to a 16-bit float or /// a vector of them, or of 16-bit floats taken from one by a component extract or a shuffle /// ([`device_from_bits`]). The module then records `PrecisionNote::NativeNanEncoding` (a NaN's -/// bits the device's); under the float controls ([`QuantizeForm::Controlled`]) its entry declares -/// [`controlled_modes`], and elsewhere its denormals are the measured fact's +/// bits the device's) unless the device's moves of a NaN are measured to be Metal's +/// ([`moves_unfolded`]); under the float controls ([`QuantizeForm::Controlled`]) its entry +/// declares [`controlled_modes`], and elsewhere its denormals are the measured fact's /// (`DriverDeviation::MetalHalfArithmetic`, which measures the conversion, not the unpack) or the /// device's (`PrecisionNote::NativeHalfConversion`). The device's 16-bit arithmetic and /// conversions widen what they compute, which no bitcast gives. At most four passes over the -/// instructions, with two bits per value of the module charged to `meter` while they run. +/// instructions, with three bits per value of the module charged to `meter` while they run. pub fn widens_bits(m: &TypedModule, meter: &mut Meter) -> Result { - let unpacks = m.blocks().iter().flat_map(|b| &b.insts).any(|n| { - matches!( - n.inst, - Inst::Glsl { - op: GlslOp::UnpackHalf2x16, - .. - } - ) - }); - if unpacks { - return Ok(true); - } + let words = m.values().len().div_ceil(64); + meter.charge(8 * words)?; + let found = widenings(m, meter).map(|w| w.iter().any(|&w| w != 0)); + meter.release(8 * words); + found +} + +/// The values of module `m` that widen a `half` from its bits by the device ([`widens_bits`]), +/// one bit per value: each `UnpackHalf2x16` and each such `OpFConvert`. Two more bits per value +/// charged to `meter` while it runs. +fn widenings(m: &TypedModule, meter: &mut Meter) -> Result, Error> { + let words = m.values().len().div_ceil(64); + let mut found = vec![0u64; words]; // Whether `ty` is a 16-bit float or a vector of them (`halves`), or a 32-bit one. let is = |ty, halves: bool| -> bool { let lane = match m.types().get(ty) { @@ -1330,59 +1332,269 @@ pub fn widens_bits(m: &TypedModule, meter: &mut Meter) -> Result { matches!(m.types().get(lane), Ok(Type::Float { width: w }) if *w == width) }; let insts = || m.blocks().iter().flat_map(|b| &b.insts); - let words = m.values().len().div_ceil(64); meter.charge(16 * words)?; let mut halves = vec![0u64; words]; let mut lanes = vec![0u64; words]; - let set = |bits: &mut [u64], v: Value| { - if let Some(w) = bits.get_mut(v.index() / 64) { - *w |= 1 << (v.index() % 64); - } - }; - let has = |bits: &[u64], v: Value| { - bits.get(v.index() / 64) - .is_some_and(|w| w & (1 << (v.index() % 64)) != 0) - }; for n in insts() { - if let ( - Inst::Convert { - op: ConvOp::Bitcast, - .. - }, - Some(r), - ) = (&n.inst, n.result) - { - if m.value(r).is_ok_and(|v| is(v.ty, true)) { - set(&mut halves, r); - } + match (&n.inst, n.result) { + ( + Inst::Glsl { + op: GlslOp::UnpackHalf2x16, + .. + }, + Some(r), + ) => set_bit(&mut found, r), + ( + Inst::Convert { + op: ConvOp::Bitcast, + .. + }, + Some(r), + ) if m.value(r).is_ok_and(|v| is(v.ty, true)) => set_bit(&mut halves, r), + _ => {} } } for n in insts() { let taken = match &n.inst { - Inst::CompositeExtract { composite, .. } => has(&halves, *composite), - Inst::VectorShuffle { a, b, .. } => has(&halves, *a) || has(&halves, *b), + Inst::CompositeExtract { composite, .. } => has_bit(&halves, *composite), + Inst::VectorShuffle { a, b, .. } => has_bit(&halves, *a) || has_bit(&halves, *b), _ => false, }; if let (true, Some(r)) = (taken, n.result) { - set(&mut lanes, r); + set_bit(&mut lanes, r); } } - let found = insts().any(|n| match (&n.inst, n.result) { - ( + for n in insts() { + if let ( Inst::Convert { op: ConvOp::FConvert, a, .. }, Some(r), - ) => (has(&lanes, *a) || has(&halves, *a)) && m.value(r).is_ok_and(|v| is(v.ty, false)), - _ => false, - }); + ) = (&n.inst, n.result) + { + let from = has_bit(&lanes, *a) || has_bit(&halves, *a); + if from && m.value(r).is_ok_and(|v| is(v.ty, false)) { + set_bit(&mut found, r); + } + } + } drop((halves, lanes)); meter.release(16 * words); Ok(found) } +/// Set value `v`'s bit in `bits`. +fn set_bit(bits: &mut [u64], v: Value) { + if let Some(w) = bits.get_mut(v.index() / 64) { + *w |= 1 << (v.index() % 64); + } +} + +/// Whether value `v`'s bit is set in `bits`. +fn has_bit(bits: &[u64], v: Value) -> bool { + bits.get(v.index() / 64) + .is_some_and(|w| w & (1 << (v.index() % 64)) != 0) +} + +/// Whether module `m` moves a `half` NaN where the device's compiler is not measured to fold the +/// widening and the narrowing that hold it (`DriverDeviation::MetalNanMoves`), so that its bits +/// stay the device's. A value a `half` read from its bits widens to ([`widens_bits`]), moved +/// through phis, selects, copies, composites and a function's scalar or vector `float` variable +/// (stored and loaded, which the driver's compiler keeps in the registers), may reach a +/// conversion (its bits, by a bitcast, only as stored to a buffer or to workgroup memory), an +/// arithmetic or comparison instruction, a fused multiply-add, a derivative, a `GLSL.std.450` +/// function other than `FrexpStruct`, `ModfStruct` and `Ldexp`, each of which computes a value +/// whose NaN Metal answers from the widened value's or its own note records, and a store to a +/// buffer or to workgroup memory, which holds a `float` there; anything else (a store to another +/// class, a call, a return, an atomic, a group or image operation, or its bits read) carries the +/// widened `float` out of the registers or reads its bits before any narrowing. The +/// module holding a 32-bit float constant that is a NaN other than `0x7FC00000`, such as a `half` +/// NaN constant held widened with its payload, which no conversion of the device made, is unfolded +/// too. The measurement covers moves through the registers, and `half` values held as the device's +/// conversions made them. One pass over the constants, then a pass over the instructions per round +/// of the moves' closure and one more, with four bits per value of the module charged to `meter` +/// while it runs. +pub fn moves_unfolded(m: &TypedModule, meter: &mut Meter) -> Result { + let float32 = |ty| matches!(m.types().get(ty), Ok(Type::Float { width: 32 })); + let payload = m.consts().iter().any(|(_, c)| match &c.kind { + ConstKind::Plain(Constant::Scalar { ty, bits }) if float32(*ty) => { + let b = bits.0 as u32; + b & 0x7F80_0000 == 0x7F80_0000 && b & 0x007F_FFFF != 0 && b != 0x7FC0_0000 + } + _ => false, + }); + if payload { + return Ok(true); + } + let words = m.values().len().div_ceil(64); + // The class of pointer `ptr`, and the type it points to. + let pointer = |ptr| { + m.value(ptr).ok().and_then(|v| match m.types().get(v.ty) { + Ok(Type::Pointer { class, pointee }) => Some((*class, *pointee)), + _ => None, + }) + }; + // Whether pointer `ptr` is to a function's scalar or vector `float` variable. + let local_float = |ptr| match pointer(ptr) { + Some((StorageClass::Function, pointee)) => { + let lane = match m.types().get(pointee) { + Ok(Type::Vector { elem, .. }) => *elem, + _ => pointee, + }; + float32(lane) + } + _ => false, + }; + meter.charge(16 * words)?; + let carried = widenings(m, meter).map(|mut widened| { + // The widened values' bits, by a bitcast and the moves. + let mut bits = vec![0u64; words]; + // The moves' closure: a phi, a select, a copy or a composite of a widened value is one, + // and of its bits. + let mut grew = true; + while grew { + grew = false; + for b in m.blocks() { + for phi in &b.phis { + for set in [&mut widened, &mut bits] { + if !has_bit(set, phi.result) + && phi.incoming.iter().any(|(v, _)| has_bit(set, *v)) + { + set_bit(set, phi.result); + grew = true; + } + } + } + for n in &b.insts { + // A function's `float` variable a widened value is stored to holds one. + if let Inst::Store { ptr, value, .. } = &n.inst { + if has_bit(&widened, *value) + && local_float(*ptr) + && !has_bit(&widened, *ptr) + { + set_bit(&mut widened, *ptr); + grew = true; + } + continue; + } + let Some(r) = n.result else { continue }; + if let Inst::Load { ptr, .. } = &n.inst { + if has_bit(&widened, *ptr) && !has_bit(&widened, r) { + set_bit(&mut widened, r); + grew = true; + } + continue; + } + if let Inst::Convert { + op: ConvOp::Bitcast, + a, + .. + } = &n.inst + { + if has_bit(&widened, *a) && !has_bit(&bits, r) { + set_bit(&mut bits, r); + grew = true; + } + continue; + } + if !moves(&n.inst) { + continue; + } + for set in [&mut widened, &mut bits] { + let mut from = false; + n.inst.for_each_value(|v| from |= has_bit(set, v)); + if from && !has_bit(set, r) { + set_bit(set, r); + grew = true; + } + } + } + } + } + // Whether pointer `ptr` is to a buffer or to workgroup memory. + let held_as_float = |ptr| { + matches!( + pointer(ptr), + Some(( + StorageClass::StorageBuffer + | StorageClass::PhysicalStorageBuffer + | StorageClass::Workgroup, + _ + )) + ) + }; + m.blocks().iter().any(|b| { + let returned = matches!( + b.term, + Terminator::ReturnValue(v) if has_bit(&widened, v) || has_bit(&bits, v) + ); + returned + || b.insts.iter().filter(|n| !moves(&n.inst)).any(|n| { + let (mut from, mut read) = (false, false); + n.inst.for_each_value(|v| { + from |= has_bit(&widened, v); + read |= has_bit(&bits, v); + }); + match &n.inst { + Inst::Store { ptr, value, .. } => { + has_bit(&bits, *ptr) + || (has_bit(&widened, *value) + && !held_as_float(*ptr) + && !local_float(*ptr)) + || (has_bit(&bits, *value) && !held_as_float(*ptr)) + } + Inst::Load { .. } => false, + Inst::AtomicStore { ptr, .. } => { + from || has_bit(&widened, *ptr) || has_bit(&bits, *ptr) + } + Inst::Convert { + op: ConvOp::Bitcast, + .. + } => read, + inst => read || (from && !computes(inst)), + } + }) + }) + }); + meter.release(16 * words); + carried +} + +/// Whether `inst` moves its operands' values into its result unchanged ([`moves_unfolded`]). +fn moves(inst: &Inst) -> bool { + matches!( + inst, + Inst::Select { .. } + | Inst::Unary { + op: UnOp::CopyObject, + .. + } + | Inst::CompositeConstruct { .. } + | Inst::CompositeExtract { .. } + | Inst::CompositeInsert { .. } + | Inst::VectorExtractDynamic { .. } + | Inst::VectorInsertDynamic { .. } + | Inst::VectorShuffle { .. } + ) +} + +/// Whether `inst` computes a value from its operands' in the registers, whose NaN Metal answers +/// from the widened value's or its own note records ([`moves_unfolded`]). +fn computes(inst: &Inst) -> bool { + match inst { + Inst::Convert { op, .. } => *op != ConvOp::Bitcast, + Inst::Glsl { op, .. } => { + !matches!(op, GlslOp::FrexpStruct | GlslOp::ModfStruct | GlslOp::Ldexp) + } + Inst::Unary { .. } | Inst::Binary { .. } | Inst::Fma { .. } | Inst::Derivative { .. } => { + true + } + _ => false, + } +} + /// Whether module `m` computes in 16-bit floats: an `OpFAdd`, `OpFSub` or `OpFMul`, an `OpFmaKHR` /// or a `GLSL.std.450 Fma` whose result is a 16-bit float or a vector of them, the device's own /// `half` arithmetic (`super::ops::f16_binary`, `super::fma`). Under the 16-bit float controls diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index f4d5d9fc6..fa5b8df27 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -2462,6 +2462,7 @@ const KHR_FACTS: super::FloatFacts = super::FloatFacts { device_denormals: false, nans: crate::device::profile::NanEncoding::Native, native_min_max: false, + nan_moves: false, }; /// Precise `pow` on `float` leaves its NaNs to the device (the device's `Pow`, and the device's sum diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index b3f076583..a74d7d82e 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1800,8 +1800,12 @@ pub enum PrecisionNote { /// (an `OpFConvert` to 16 bits with `shaderFloat16`, `PackHalf2x16` without it), and a NaN /// narrows to a NaN whose bits are the device's, where Metal keeps a `half` NaN's sign and /// payload. Every other `half` widens to its value and narrows to its bits, but a denormal on a - /// device that may flush 16-bit ones ([`PrecisionNote::NativeHalfConversion`]). Validation - /// derives no tolerance from it. + /// device that may flush 16-bit ones ([`PrecisionNote::NativeHalfConversion`]). Not recorded, + /// on a device whose moves of a NaN are measured to be Metal's (MoltenVK on the Apple M3 Max's + /// macOS 27 identity, `DriverDeviation::MetalNanMoves`), for a `float` `fneg` or `fabs`, a + /// `half`'s widening to `float` or `fabs`, or a module's reads and encodes of a `half`'s bits + /// where it moves its `half` values through the registers alone. Validation derives no + /// tolerance from it. NativeNanEncoding, /// Native device maths: Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` (its /// `clamp(x, +0, 1)`) on `float` or `half` is the device's `GLSL.std.450` `NMin`, `NMax` or diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 90e6b01f2..01fc9e73f 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -2683,6 +2683,17 @@ fn compile_kept( && p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic); let native_widening = widens && quantize != crate::spirv::builder::QuantizeForm::Controlled && !measured_widening; + // Its NaN's bits, and those of a `half` held widened that a widening to `float` or a `half` + // `fabs` moves: Metal's where the device's widening and narrowing are measured to answer + // them (`DriverDeviation::MetalNanMoves`) and the module moves its `half` values only as + // measured, which it then requires; the device's, recorded, elsewhere. + let held_moves = plan.families.arith.held_nan_moves; + let unfolded = (widens || held_moves) + && p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves) + && crate::lower::arith::narrow::moves_unfolded(&module, m)?; + let moved_nans = widens + && p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves) + && !unfolded; // A `half` rounded through the device's conversion and its widening, each decorated // `NoContraction`, under the float controls that make it Metal's, computed by the device's // 16-bit arithmetic, which they make Metal's too, or read from its bits by the device's @@ -2700,7 +2711,10 @@ fn compile_kept( // conversion, or widens a `half` by the device where that is not measured or controlled to be // Metal's, records each kind, and requires no fact. let native_half = [ - (widens, PrecisionNote::NativeNanEncoding), + ( + (widens && !moved_nans) || (held_moves && unfolded), + PrecisionNote::NativeNanEncoding, + ), (device_quantize, PrecisionNote::NativeHalfQuantize), ( converts || native_widening, @@ -2787,6 +2801,13 @@ fn compile_kept( .properties .insert(crate::device::requirements::VkProperty::MetalHalfFma); } + // A NaN's bits left to the device's widening, narrowing, negation or magnitude because they + // are Metal's. + if plan.families.arith.nan_moves || moved_nans || (held_moves && !unfolded) { + requirements + .properties + .insert(crate::device::requirements::VkProperty::MetalNanMoves); + } // 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/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index 256fdb9a6..4384b3b95 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -149,6 +149,17 @@ pub fn storage_buffers(a: &FunctionArtifact) -> u32 { .sum() } +/// Whether artifact `a` leaves a NaN's bits to the device, which the interpreter does not model: +/// it records `PrecisionNote::NativeNanEncoding`, or it requires `VkProperty::MetalNanMoves`, whose +/// measured device answers Metal's bits where the interpreter's conversions answer their own. +pub fn device_nan_bits(a: &FunctionArtifact) -> bool { + a.precision + .contains(&crate::pipeline::artifact::PrecisionNote::NativeNanEncoding) + || a.requirements + .properties + .contains(&crate::device::requirements::VkProperty::MetalNanMoves) +} + /// The default policy with Metal's answers wherever a choice still offers them /// ([`DevicePolicy::exact_answers`]). pub fn exact_maths() -> DevicePolicy { diff --git a/crates/metal2vulkan/src/tests/engine_access.rs b/crates/metal2vulkan/src/tests/engine_access.rs index 4e1d3aa12..a78d5a079 100644 --- a/crates/metal2vulkan/src/tests/engine_access.rs +++ b/crates/metal2vulkan/src/tests/engine_access.rs @@ -36,7 +36,6 @@ use crate::library::FunctionConstantValues; use crate::lower::emit::emit_module; use crate::lower::select::{select, LowerInputs, Plan}; use crate::memory::static_root::analyze_memory; -use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::compile::{compile_bitcode, plan_bitcode, EntryRef}; use crate::pipeline::facts::{RuntimeFact, UniformViewChoice}; use crate::pipeline::interface::{BufferForm, DescriptorView, PushLoc, SlotInterface, Window}; @@ -44,7 +43,8 @@ use crate::pipeline::sym::{ PushField, ResourceKind, ResourceSlot, SlotClass, SlotRef, SpecKey, Stage, Symbol, }; use crate::pipeline::testing::{ - compile, engine_dir, link_and_validate, llvm_assemble, meter, typed_module, AssembleError, + compile, device_nan_bits, engine_dir, link_and_validate, llvm_assemble, meter, typed_module, + AssembleError, }; use crate::spirv::interp::{run, Buffer, Config, InterpError, Resources}; use crate::spirv::ir::{GlobalKind, TypedModule}; @@ -749,7 +749,8 @@ fn offsets(size: u64) -> Vec { /// bounds. Probes are skipped where the offset breaks the access's stated alignment (undefined in /// Metal). A `half` NaN loaded, or stored from a constant, need only come back a NaN where the /// module reads a `half` from its bits by the device's widening or encodes one by its narrowing -/// (`PrecisionNote::NativeNanEncoding`), whose NaN encoding is the device's. +/// (`PrecisionNote::NativeNanEncoding`, or `VkProperty::MetalNanMoves`, measured on a device the +/// interpreter is not: `device_nan_bits`), whose NaN encoding is the device's. #[test] fn every_leaf_path_is_exact_in_bounds_and_contained_out_of_bounds() { let size = 32u64; @@ -762,10 +763,9 @@ fn every_leaf_path_is_exact_in_bounds_and_contained_out_of_bounds() { }; check_l3(&bc, k.name, &p, &what); let native_halves = k.ty.contains("half") - && compile(&bc, k.name, &p) - .unwrap_or_else(|e| panic!("{what}: {e}")) - .precision - .contains(&PrecisionNote::NativeNanEncoding); + && device_nan_bits( + &compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e}")), + ); let (plan, m) = typed_module(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e}")); for r in [0u32, 4] { for off in offsets(size) { @@ -1058,8 +1058,8 @@ fn push_with_table(plan: &Plan) -> Vec { /// and leaves the allocation unchanged. Robust buffer access does not cover device addresses, so /// the check is emitted on a robust profile too. A `half` NaN loaded, or stored from a constant, /// need only come back a NaN where the module reads a `half` from its bits by the device's -/// widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`), whose NaN -/// encoding is the device's. +/// widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`, or +/// `VkProperty::MetalNanMoves`: `device_nan_bits`), whose NaN encoding is the device's. #[test] fn a_device_address_slot_is_exact_and_contained() { let size = 32u64; @@ -1083,8 +1083,7 @@ fn a_device_address_slot_is_exact_and_contained() { ) .unwrap_or_else(|e| panic!("{what}: {e}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let native_halves = - k.ty.contains("half") && a.precision.contains(&PrecisionNote::NativeNanEncoding); + let native_halves = k.ty.contains("half") && device_nan_bits(&a); let (plan, m) = typed_module_with(&bc, k.name, &p, &inputs); for bind in [0u64, 8] { for off in offsets(size) { @@ -1769,8 +1768,8 @@ fn profile_without(stem: &str, features: &[VkFeature]) -> DeviceProfile { /// follows the binder contract (descriptor base congruent to the Metal address modulo 4), and a /// sub-word store through a unit leaves its neighbours unchanged. A `half` NaN loaded, or stored /// from a constant, need only come back a NaN where the module reads a `half` from its bits by the -/// device's widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`), whose -/// NaN encoding is the device's. +/// device's widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`, or +/// `VkProperty::MetalNanMoves`: `device_nan_bits`), whose NaN encoding is the device's. #[test] fn narrow_units_are_exact_at_every_bind_residual() { let size = 32u64; @@ -1789,10 +1788,9 @@ fn narrow_units_are_exact_at_every_bind_residual() { }; check_l3(&bc, k.name, &p, &what); let native_halves = k.ty.contains("half") - && compile(&bc, k.name, &p) - .unwrap_or_else(|e| panic!("{what}: {e}")) - .precision - .contains(&PrecisionNote::NativeNanEncoding); + && device_nan_bits( + &compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e}")), + ); let (plan, m) = typed_module(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e}")); let mut probes: Vec = (0..=9).collect(); probes.extend(size as u32 - 9..=size as u32 + 1); @@ -2114,7 +2112,7 @@ const VEC4_RESIDUALS: [u32; 6] = [0, 4, 12, 16, 36, 0xFFFF_FFF0]; /// tested profile; aligned to 4 it moves word by word (four stores, no `uvec4` view of the slot it /// stores to). At every residual a descriptor offset that is a multiple of 16 reads and writes /// exactly the leaf's 16 bytes of a 48-byte range (a `half` NaN stored from a constant a NaN where -/// the module encodes it by the device's narrowing, `PrecisionNote::NativeNanEncoding`), and with +/// the module encodes it by the device's narrowing, `device_nan_bits`), and with /// the in-shader check the offset past the range reads 0 and writes nothing. #[test] fn sixteen_byte_leaves_move_as_one_uvec4() { @@ -2147,8 +2145,7 @@ fn sixteen_byte_leaves_move_as_one_uvec4() { "{what}: views of out" ); let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e}")); - let native_halves = - k.ty.contains("half") && a.precision.contains(&PrecisionNote::NativeNanEncoding); + let native_halves = k.ty.contains("half") && device_nan_bits(&a); let stores = opcodes(&a.module.words) .iter() .filter(|o| **o == OP_STORE) diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index 3692d5cea..4d7a1aac0 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -1721,7 +1721,7 @@ fn a_fast_division_leaves_its_nans_to_the_device() { let Some(bitcode) = assemble("fast-divide-specials", &module(&ks)) else { return; }; - nans_are_the_device_s(&bitcode, &ks, false, &[], &|_, fact| !fact); + nans_are_the_device_s(&bitcode, &ks, false, &[], &|_, fact, _| !fact); for stem in every_profile() { let p = profile(&stem, exact_maths()).expect("profile"); let device_nans = @@ -3124,18 +3124,21 @@ fn stores_nan(bits: u32, half: bool) -> bool { /// Kernels `ks` of `bitcode` (each storing a NaN's bits, `half` ones zero-extended where `half`) /// on `lavapipe` and `moltenvk-m3`, each with its driver's deviation `MetalCanonicalNans` taken /// and not: the module selects no NaN, so it is the same word for word on both sides of the fact; -/// it records `PrecisionNote::NativeNanEncoding` exactly where `noted(kernel, fact)` or it reads a -/// `half` from its bits by the device's widening or encodes one by its narrowing -/// (`narrow::widens_bits`, `narrow::encodes_bits`: both profiles have `shaderFloat16`), and never -/// `DeviceNanEncoding`; and the interpreter's answer is the kernel's -/// `want`, or a NaN, its bits the device's, where it has none, but for the kernels `unread` names, -/// whose device instruction the interpreter does not evaluate. +/// it records `PrecisionNote::NativeNanEncoding` exactly where `noted(kernel, fact, moves)` or it +/// reads a `half` from its bits by the device's widening or encodes one by its narrowing +/// (`narrow::widens_bits`, `narrow::encodes_bits`: both profiles have `shaderFloat16`) on a profile +/// whose moves of a NaN are not measured (`moves`, `DriverDeviation::MetalNanMoves`: the M3 Max's +/// identity on MoltenVK), and never `DeviceNanEncoding`; it requires `VkProperty::MetalNanMoves` +/// exactly where `moves` and it reads or encodes a `half` so, or `noted` drops the note for the +/// moves; and the interpreter's answer is the kernel's `want`, or a NaN, its bits the device's, +/// where it has none, but for the kernels `unread` names, whose device instruction the interpreter +/// does not evaluate. fn nans_are_the_device_s( bitcode: &[u8], ks: &[Kernel], half: bool, unread: &[&str], - noted: &dyn Fn(&str, bool) -> bool, + noted: &dyn Fn(&str, bool, bool) -> bool, ) { for stem in ["lavapipe", "moltenvk-m3"] { for kk in ks { @@ -3153,12 +3156,21 @@ fn nans_are_the_device_s( Ok(w || crate::lower::arith::narrow::encodes_bits(&m, &mut meter())?) }) .unwrap_or_else(|e| panic!("{what}: {e:?}")); + let moves = p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves); assert_eq!( a.precision.contains(&PrecisionNote::NativeNanEncoding), - noted(kk.name, fact) || widens, + noted(kk.name, fact, moves) || (widens && !moves), "{what}: {:?}", a.precision ); + let moved = noted(kk.name, fact, false) && !noted(kk.name, fact, true); + assert_eq!( + a.requirements + .properties + .contains(&crate::device::requirements::VkProperty::MetalNanMoves), + moves && (widens || moved), + "{what}" + ); assert!( !a.precision.contains(&PrecisionNote::DeviceNanEncoding), "{what}: {:?}", @@ -3207,7 +3219,7 @@ fn a_float_nan_is_the_device_s_on_every_profile() { let Some(bitcode) = assemble("nan-fact", &module(&ks)) else { return; }; - nans_are_the_device_s(&bitcode, &ks, false, &[], &|name, fact| { + nans_are_the_device_s(&bitcode, &ks, false, &[], &|name, fact, _| { name == "nan_round" || !fact }); // The committed profiles state the fact for the measured device only. @@ -3441,7 +3453,7 @@ fn sincos_answers_the_device_s_nan() { return; }; let unread = ["sincos_nan_sine", "sincos_nan_cosine"]; - nans_are_the_device_s(&bitcode, &ks, false, &unread, &|_, fact| !fact); + nans_are_the_device_s(&bitcode, &ks, false, &unread, &|_, fact, _| !fact); } /// A NaN test (Metal's saturating conversion's) is `OpIsNan` only in an entry that declares @@ -3648,15 +3660,16 @@ fn half_nans_answer_the_device_s_nan() { let Some(bitcode) = assemble("nan-half", &text) else { return; }; - nans_are_the_device_s(&bitcode, &ks, true, &[], &|_, fact| !fact); + nans_are_the_device_s(&bitcode, &ks, true, &[], &|_, fact, _| !fact); } /// Class C: Metal widens a `half` NaN to the canonical `float` NaN `0x7FC00000`, sign and payload /// dropped, by `fpext` and by its intrinsic form `air.convert`. A `half` is held widened, so /// `fpext` emits no device operation: the NaN is the device's widening of the `half`'s bits where /// the profile has `shaderFloat16` (both profiles here), and the module selects nothing and notes -/// `PrecisionNote::NativeNanEncoding` whatever the device fact states. The interpreter's widening -/// keeps the payload, as a device may. +/// `PrecisionNote::NativeNanEncoding` whatever the device fact states, but where the device's +/// widening is measured to answer Metal's (`DriverDeviation::MetalNanMoves`, on `moltenvk-m3`), +/// where it requires that. The interpreter's widening keeps the payload, as a device may. #[test] fn a_widened_half_nan_keeps_its_payload_on_every_profile() { let hx = oh("hx", 0xFE01); @@ -3688,15 +3701,17 @@ fn a_widened_half_nan_keeps_its_payload_on_every_profile() { let Some(bitcode) = assemble("nan-widen", &text) else { return; }; - nans_are_the_device_s(&bitcode, &ks, false, &[], &|_, _| true); + nans_are_the_device_s(&bitcode, &ks, false, &[], &|_, _, moves| !moves); } /// Class D: Metal's `half` `fneg` and `fabs` answer the canonical `half` NaN `0x7E00`, with or /// without fast-math flags. A device computes both exactly on the held value's sign, so a NaN's /// payload is kept on every profile: the module selects nothing and notes /// `PrecisionNote::NativeNanEncoding` whatever the device fact states, as for an `fadd` whose only -/// use is the `fneg`. The interpreter keeps a `half` NaN's payload through the held value, as a -/// device does (the value stored unchanged is `0xFE01`, and notes nothing). +/// use is the `fneg`; but `fabs` where the device's is measured to answer Metal's +/// (`DriverDeviation::MetalNanMoves`, on `moltenvk-m3`: the held value is its widening's canonical +/// NaN there), where it requires that. The interpreter keeps a `half` NaN's payload through the +/// held value, as a device may (the value stored unchanged is `0xFE01`, and notes nothing). #[test] fn half_sign_operations_keep_a_nan_s_payload_on_every_profile() { let hx = oh("hx", 0xFE01); @@ -3732,7 +3747,83 @@ fn half_sign_operations_keep_a_nan_s_payload_on_every_profile() { let Some(bitcode) = assemble("nan-half-sign", &text) else { return; }; - nans_are_the_device_s(&bitcode, &ks, true, &[], &|name, _| name != "half_kept"); + nans_are_the_device_s(&bitcode, &ks, true, &[], &|name, _, moves| { + name != "half_kept" && !(moves && name.starts_with("half_fabs")) + }); +} + +/// A `half` read from its bits by the device's widening and moved through the registers to a +/// narrowing (a select of it, a phi of it, which the module holds in a function's `float` +/// variable, a select with Metal's canonical `half` NaN constant; a `half` stored as itself is not +/// widened at all) is Metal's bits where the +/// device's compiler is measured to fold that widening and narrowing +/// (`DriverDeviation::MetalNanMoves`, `moltenvk-m3`): the module records no +/// `PrecisionNote::NativeNanEncoding` there and requires `VkProperty::MetalNanMoves`, and records +/// the note on `lavapipe`, which is not measured. A select with a `half` NaN constant of another +/// payload (held widened as a `float` NaN that no conversion of the device made) is not in the +/// measurement, and records the note on both, requiring nothing (`narrow::moves_unfolded`). +#[test] +fn half_moves_are_metals_only_where_the_device_folds_them() { + let hx = oh("hx", 0xFE01); + let nan = " %c = fcmp uno half %hx, 0xH0000\n"; + let ks = [ + half_nan_kernel("kept", format!("{hx} %s = freeze half %hx\n"), Some(0xFE01)), + half_nan_kernel( + "selected", + format!("{hx}{nan} %s = select i1 %c, half %hx, half 0xH3C00\n"), + None, + ), + half_nan_kernel( + "joined", + format!( + "{hx}{nan} br i1 %c, label %l, label %u\nl:\n br label %j\nu:\n br label %j\nj:\n %s = phi half [ %hx, %l ], [ 0xH3C00, %u ]\n" + ), + None, + ), + half_nan_kernel( + "canonical_constant", + format!("{hx}{nan} %s = select i1 %c, half 0xH7E00, half %hx\n"), + Some(0x7E00), + ), + half_nan_kernel( + "payload_constant", + format!("{hx}{nan} %s = select i1 %c, half 0xH7E01, half %hx\n"), + None, + ), + ]; + let Some(bitcode) = assemble("nan-half-moves", &module(&ks)) else { + return; + }; + for stem in ["lavapipe", "moltenvk-m3"] { + let p = profile(stem, DevicePolicy::default()).expect("profile"); + let moves = p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves); + assert_eq!(moves, stem == "moltenvk-m3", "{stem}"); + for kk in &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 (_, m) = crate::pipeline::testing::typed_module(&bitcode, kk.name, &p) + .unwrap_or_else(|e| panic!("{what}: {e:?}")); + let widens = crate::lower::arith::narrow::widens_bits(&m, &mut meter()) + .unwrap_or_else(|e| panic!("{what}: {e:?}")); + // A `half` stored as itself is never widened; each select reads it by the widening. + assert_eq!(widens, kk.name != "kept", "{what}"); + let folded = moves && kk.name != "payload_constant"; + assert_eq!( + a.precision.contains(&PrecisionNote::NativeNanEncoding), + widens && !folded, + "{what}: {:?}", + a.precision + ); + assert_eq!( + a.requirements + .properties + .contains(&crate::device::requirements::VkProperty::MetalNanMoves), + widens && folded, + "{what}" + ); + } + } } /// Class E: Metal's `float` `fneg` and `fabs` (`air.fabs`, `air.fast_fabs`, and `llvm.fabs`, which @@ -3740,8 +3831,10 @@ fn half_sign_operations_keep_a_nan_s_payload_on_every_profile() { /// NaN keeps its payload, signaling or not, and a denormal stays. The lowering is the device's /// `OpFNegate` and `FAbs` on every profile (RADV's `fneg` keeps a NaN's sign, NVIDIA's `fabs` /// answers `0x7FFFFFFF`, RADV and ANV flush a denormal): no NaN is selected and nothing moves on -/// the bits, the NaN noted `NativeNanEncoding` and `fneg`'s denormal `DeviceDenormals`. The -/// interpreter keeps the payload and the denormal, as a device may. +/// the bits, the NaN noted `NativeNanEncoding` but where the device's are measured to be Metal's +/// (`DriverDeviation::MetalNanMoves`, on `moltenvk-m3`), where the module requires that, and +/// `fneg`'s denormal `DeviceDenormals`. The interpreter keeps the payload and the denormal, as a +/// device may. #[test] fn float_sign_operations_are_the_devices_on_every_profile() { let snan = ob("x", 0x7F80_0001); @@ -3825,11 +3918,20 @@ fn float_sign_operations_are_the_devices_on_every_profile() { assert_eq!(fabs(&words) > 0, abs, "{what}"); assert_eq!(nan_tests(&words), (0, 0), "{what}"); if neg || abs { - assert!( + let moves = p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves); + assert_eq!( a.precision.contains(&PrecisionNote::NativeNanEncoding), + !moves, "{what}: {:?}", a.precision ); + assert_eq!( + a.requirements + .properties + .contains(&crate::device::requirements::VkProperty::MetalNanMoves), + moves, + "{what}" + ); } if neg { assert!( @@ -4278,7 +4380,7 @@ fn half_functions_answer_the_device_s_nan() { let Some(bitcode) = assemble("nan-half-functions", &text) else { return; }; - nans_are_the_device_s(&bitcode, &ks, true, &["half_asin"], &|name, fact| { + nans_are_the_device_s(&bitcode, &ks, true, &["half_asin"], &|name, fact, _| { name.starts_with("half_round") || name.starts_with("half_fract") || name == "half_asin" diff --git a/crates/metal2vulkan/src/tests/engine_cross_class.rs b/crates/metal2vulkan/src/tests/engine_cross_class.rs index 63bbd91bd..b97b1aacc 100644 --- a/crates/metal2vulkan/src/tests/engine_cross_class.rs +++ b/crates/metal2vulkan/src/tests/engine_cross_class.rs @@ -37,7 +37,8 @@ use crate::pipeline::sym::{ Axis, ResourceKind, ResourceSlot, SampledType, SlotClass, SlotRef, SpecKey, Stage, }; use crate::pipeline::testing::{ - link_and_validate, llvm_assemble, meter, profile, typed_module_with, AssembleError, + device_nan_bits, link_and_validate, llvm_assemble, meter, profile, typed_module_with, + AssembleError, }; use crate::pipeline::StageSource; use crate::pipeline::{ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor}; @@ -342,9 +343,10 @@ fn run( /// Every read through a slot of another class gives the words the slot of the texture's own /// class gives, a `half` result their low 16 bits: Metal's rule. A `ushort` result of an integer /// texture is the low 16 bits too, of a float texture the `half` read's bits. Where the module -/// widens a `half` from its bits by the device and records `PrecisionNote::NativeNanEncoding` (both -/// profiles here, which have `shaderFloat16`), a `half` result's NaN is the device's widening's, -/// so a NaN pattern need only come back a NaN. +/// widens a `half` from its bits by the device and records `PrecisionNote::NativeNanEncoding` or +/// requires `VkProperty::MetalNanMoves` (both profiles here, which have `shaderFloat16`; +/// `device_nan_bits`), a `half` result's NaN is the device's widening's, which the interpreter is +/// not, so a NaN pattern need only come back a NaN. #[test] fn accesses_through_another_class_are_the_native_words() { use SampledType as S; @@ -392,18 +394,18 @@ fn accesses_through_another_class_are_the_native_words() { let want = run(&own, native, &inputs(None), p, class, &what); let consts = FunctionConstantValues::defaults(); let device_nans = ty == Ty::Half - && compile_bitcode( - &cross, - EntryRef::Name("k"), - &consts, - p, - &inputs(Some(class)), - &mut meter(), - SPIRV_WORDS, - ) - .unwrap_or_else(|e| panic!("{what}: {e}")) - .precision - .contains(&PrecisionNote::NativeNanEncoding); + && device_nan_bits( + &compile_bitcode( + &cross, + EntryRef::Name("k"), + &consts, + p, + &inputs(Some(class)), + &mut meter(), + SPIRV_WORDS, + ) + .unwrap_or_else(|e| panic!("{what}: {e}")), + ); let nan = |h: u32| h & 0x7C00 == 0x7C00 && h & 0x3FF != 0; let lanes = (SIDE * SIDE * 4) as usize; let lane_of = |b: &[u8], t: Ty, lane: usize| match t { diff --git a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs index 631c45006..17d7e4eb7 100644 --- a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs +++ b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs @@ -7,13 +7,14 @@ //! and without the `fast_` prefix and with and without fast-math flags, and every float binary //! operator, is compiled alone (its operands loaded from a buffer and its result stored) on one //! committed profile per class of the facts the notes read: the `float` fused multiply-add route, -//! whether the `float` functions are Metal's, and whether the device reads `f32` denormals as -//! Metal does. Each artifact's notes are exactly what the exported function answers for that call +//! whether the `float` functions are Metal's, whether the device reads `f32` denormals as Metal +//! does, and whether its moves of a NaN are Metal's (`nan::moves_answered`). Each artifact's notes are exactly what the exported function answers for that call //! in that entry's math mode. The loads and stores around it record none, but a `half` kernel's //! widening and rounding, which the module records once by the profile's own form: its rounding's //! note (`narrow::native_rounding`), which the test sets aside, and a module's widening of a //! `half` from its bits or narrowing of one to them by the device (every profile), whose NaN's -//! bits are the device's (`narrow::widens_bits`, `narrow::encodes_bits`, `NativeNanEncoding`), and +//! bits are the device's (`narrow::widens_bits`, `narrow::encodes_bits`, `NativeNanEncoding`) but +//! where the device's moves of a NaN are measured to be Metal's (`narrow::moves_unfolded`), and //! without `shaderFloat16` its denormals too (`UnpackHalf2x16`, `PackHalf2x16`, //! `NativeHalfConversion`), which the test adds to the operation's notes. //! @@ -287,9 +288,9 @@ fn assemble(token: &str, chunk: usize, text: &str) -> Option> { } /// What the notes of a float operation read of a profile: its `float` fused multiply-add route, -/// whether its `float` functions are Metal's, and whether the device reads `f32` denormals as Metal -/// does. -type NoteClass = (Route, bool, bool); +/// whether its `float` functions are Metal's, whether the device reads `f32` denormals as Metal +/// does, and whether its moves of a NaN are Metal's. +type NoteClass = (Route, bool, bool, bool); /// The note class of profile `p`. fn note_class(p: &DeviceProfile) -> NoteClass { @@ -297,6 +298,7 @@ fn note_class(p: &DeviceProfile) -> NoteClass { fma::float_route(p), p.fields().float_functions == FloatFunctions::Metal, denormal::device_flushes(p), + nan::moves_answered(p), ) } @@ -306,14 +308,14 @@ fn one_profile_per_class() -> BTreeMap { for (stem, p) in committed_profiles_with(exact_maths()).expect("profiles") { out.entry(note_class(&p)).or_insert((stem, p)); } - let routes: BTreeSet = out.keys().map(|(route, _, _)| *route).collect(); + let routes: BTreeSet = out.keys().map(|(route, _, _, _)| *route).collect(); assert_eq!( routes, BTreeSet::from([Route::Khr, Route::Native]), "every float route is some committed profile's" ); assert!( - out.keys().any(|(_, metal, _)| *metal), + out.keys().any(|(_, metal, _, _)| *metal), "a committed profile's float functions are Metal's" ); out @@ -372,11 +374,16 @@ fn exported_float_notes_are_the_ones_a_compile_records() { let crosses = narrow::widens_bits(&m, &mut meter()) .and_then(|w| Ok(w || narrow::encodes_bits(&m, &mut meter())?)) .unwrap_or_else(|e| panic!("{what}: {e:?}")); - if crosses { + // Its NaN's bits Metal's where the device's moves are measured to be and + // the module moves its `half` values only so. + let moved = nan::moves_answered(p) + && !narrow::moves_unfolded(&m, &mut meter()) + .unwrap_or_else(|e| panic!("{what}: {e:?}")); + if crosses && !moved { want.insert(PrecisionNote::NativeNanEncoding); - if form == crate::spirv::builder::QuantizeForm::Device { - want.insert(PrecisionNote::NativeHalfConversion); - } + } + if crosses && form == crate::spirv::builder::QuantizeForm::Device { + want.insert(PrecisionNote::NativeHalfConversion); } } assert_eq!(got, want, "{what}"); @@ -405,7 +412,7 @@ fn exported_float_notes_are_the_ones_a_compile_records() { #[test] fn a_float_division_is_the_devices_arithmetic_unless_it_is_metals_precise_one() { for (class, (stem, p)) in one_profile_per_class() { - let (_, metal_functions, _) = class; + let (_, metal_functions, _, _) = class; let flushes = p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals); let native_nans = nan::encoding(&p) == NanEncoding::Native; for (_, _, _, fmt) in ELEMS { @@ -505,7 +512,7 @@ fn precise_fmod_records_no_precision_note_and_the_roots_the_devices() { Some(AirIntrinsic::Math(call)) => call, _ => panic!("{name} is a math call"), }; - for ((_, metal_functions, _), (stem, p)) in one_profile_per_class() { + for ((_, metal_functions, _, _), (stem, p)) in one_profile_per_class() { for name in ["air.fmod.f32", "air.fmod.f16"] { for fmf in [FastMath::NONE, every_flag()] { for math in [EntryMath::Fast, EntryMath::Precise] { @@ -678,7 +685,7 @@ fn a_fast_math_entry_on_moltenvk_records_no_note_for_metals_own_operations() { { let stem = "moltenvk-m3"; let p = by_stem(stem); - assert_eq!(note_class(p), (Route::Khr, true, true), "{stem}"); + assert_eq!(note_class(p), (Route::Khr, true, true, true), "{stem}"); let (fast, _) = notes_of(p, "fdiv_fast"); assert!(fast.is_empty(), "fdiv_fast on {stem}: {fast:?}"); let (preserving, _) = notes_of(p, "fdiv_preserving"); @@ -719,7 +726,7 @@ fn a_fast_math_entry_on_moltenvk_records_no_note_for_metals_own_operations() { // and the fast division keeps its note. for denormals in [true, false] { let Some((stem, p)) = profiles.iter().find(|(_, p)| { - let (_, metal, flushes) = note_class(p); + let (_, metal, flushes, _) = note_class(p); !metal && flushes == denormals }) else { panic!("no committed profile of the device's functions, Metal's denormals {denormals}"); diff --git a/crates/metal2vulkan/src/tests/engine_metal_routines.rs b/crates/metal2vulkan/src/tests/engine_metal_routines.rs index 34fd5b381..234b398c0 100644 --- a/crates/metal2vulkan/src/tests/engine_metal_routines.rs +++ b/crates/metal2vulkan/src/tests/engine_metal_routines.rs @@ -424,7 +424,9 @@ fn half_nan(bits: u32) -> bool { /// `INT_MIN`), `half` denormals normalized, zeros `(+0, 0)` and `INT_MIN` whatever their sign, /// infinities and NaNs returned with their bits and exponent 0, `ilogb` `INT_MAX` for an infinity /// and `INT_MIN` for a NaN, lane by lane. The one exception: a module that records -/// `NativeNanEncoding` answers a `half` NaN's mantissa with a NaN of the device's bits. +/// `NativeNanEncoding` answers a `half` NaN's mantissa with a NaN of the device's bits; every +/// `half` kernel records it, on a profile whose moves of a NaN are measured to be Metal's +/// (`DriverDeviation::MetalNanMoves`) too, since the routines read the widened value's bits. #[test] fn frexp_and_ilogb_answer_as_metals_routines() { let Some(bc) = assemble() else { @@ -437,6 +439,9 @@ fn frexp_and_ilogb_answer_as_metals_routines() { let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); let device_nans = a.precision.contains(&PrecisionNote::NativeNanEncoding); + // The routines read a `half`'s widened bits, which the device's measured moves of a + // NaN do not cover (`narrow::moves_unfolded`): noted on every profile. + assert!(!k.half || device_nans, "{what}: {:?}", a.precision); let got = interpret(&bc, k, &p, &what); for (i, &(x, mantissa, exponent, ilogb)) in k.inputs().iter().enumerate() { let got = &got[3 * i..3 * i + 3]; diff --git a/crates/metal2vulkan/src/tests/engine_native_half.rs b/crates/metal2vulkan/src/tests/engine_native_half.rs index 0272042e0..aa49a802c 100644 --- a/crates/metal2vulkan/src/tests/engine_native_half.rs +++ b/crates/metal2vulkan/src/tests/engine_native_half.rs @@ -22,7 +22,8 @@ use crate::lower::select::{select, LowerInputs}; use crate::memory::static_root::analyze_memory; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; use crate::pipeline::testing::{ - compile, compile_kept, link_and_validate, llvm_assemble, meter, profile, AssembleError, Scratch, + compile, compile_kept, device_nan_bits, link_and_validate, llvm_assemble, meter, profile, + AssembleError, Scratch, }; use crate::pipeline::PrecisionNote; use crate::spirv::builder::QuantizeForm; @@ -368,7 +369,9 @@ fn decodes(m: &TypedModule) -> (usize, usize) { /// fact; on the floor (no `shaderFloat16`) it is `UnpackHalf2x16` of each word, recording both /// notes and requiring no fact. A `half4` widens as one vector (two words unpacked and shuffled /// where the device unpacks). Each module passes L3 and answers the `half`s' values on the -/// interpreter (whose widening is exact). +/// interpreter (whose widening is exact). Where the device's moves of a NaN are measured to be +/// Metal's (`DriverDeviation::MetalNanMoves`, MoltenVK on the M3 Max's identity), a module that +/// moves its `half`s only so requires that in place of the NaN's note (`device_nan_bits`). #[test] fn a_half_decode_is_the_devices_widening_inside_loops_and_out() { let Some(bc) = assemble("native-half-decode", &decode_module()) else { @@ -413,7 +416,7 @@ fn a_half_decode_is_the_devices_widening_inside_loops_and_out() { }; let (device, integer) = decodes(&kept); assert_eq!((device, integer), (reads, 0), "{what}: the decodes"); - assert!(a.precision.contains(&nan), "{what}: {:?}", a.precision); + assert!(device_nan_bits(&a), "{what}: {:?}", a.precision); assert_eq!( a.precision.contains(&conversion), native, @@ -830,7 +833,9 @@ fn half_load_module() -> String { /// widens exactly) and it records no other note; where the measured `MetalHalfArithmetic` reads /// every `half` through that widening as Metal's (MoltenVK) it requires the fact; elsewhere /// (NVIDIA, lavapipe: the device's conversion, no float controls) it records -/// `NativeHalfConversion`, whose bound holds a denormal the device flushes. Without it (Pascal, +/// `NativeHalfConversion`, whose bound holds a denormal the device flushes; where the device's +/// moves of a NaN are measured to be Metal's (`DriverDeviation::MetalNanMoves`, MoltenVK on the +/// M3 Max's identity) it requires that in place of `NativeNanEncoding`. Without it (Pascal, /// the LunarG baseline, SwiftShader, the floor) the widening is one `UnpackHalf2x16` of the word, /// a 16-bit unit's zero extension where the profile has 16-bit storage, with no 16-bit float type, /// recording `NativeHalfConversion` too and requiring no fact. Each passes L3; on the interpreter @@ -858,6 +863,11 @@ fn a_half_read_from_memory_is_the_devices_widening_on_every_profile() { .properties .contains(&VkProperty::MetalHalfArithmetic); let nan = a.precision.contains(&PrecisionNote::NativeNanEncoding); + let moves = p.takes_driver_deviation(DriverDeviation::MetalNanMoves); + let moved = a + .requirements + .properties + .contains(&VkProperty::MetalNanMoves); let conversion = a.precision.contains(&PrecisionNote::NativeHalfConversion); match form { QuantizeForm::Device => { @@ -876,7 +886,7 @@ fn a_half_read_from_memory_is_the_devices_widening_on_every_profile() { } QuantizeForm::Converted => { assert_eq!((r.widenings, r.unpacks), (1, 0), "{what}: {r:?}"); - assert!(nan, "{what}: {:?}", a.precision); + assert_eq!((nan, moved), (!moves, moves), "{what}: {:?}", a.precision); assert_eq!(conversion, !measured, "{what}: {:?}", a.precision); assert_eq!(fact, measured, "{what}: {:?}", a.requirements.properties); } diff --git a/crates/metal2vulkan/src/tests/engine_typed_threadgroup.rs b/crates/metal2vulkan/src/tests/engine_typed_threadgroup.rs index b09498a09..89eb912f9 100644 --- a/crates/metal2vulkan/src/tests/engine_typed_threadgroup.rs +++ b/crates/metal2vulkan/src/tests/engine_typed_threadgroup.rs @@ -21,11 +21,11 @@ use std::sync::atomic::{AtomicU64, Ordering}; use crate::device::profile::DeviceProfile; use crate::device::DevicePolicy; use crate::lower::select::Plan; -use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::interface::PushLoc; use crate::pipeline::sym::{Axis, PushField, ResourceKind, ResourceSlot, SpecKey, Stage}; use crate::pipeline::testing::{ - compile, link_and_validate, llvm_assemble, profile, typed_module, AssembleError, + compile, device_nan_bits, link_and_validate, llvm_assemble, profile, typed_module, + AssembleError, }; use crate::spirv::interp::{run, Buffer, Config, Order, Resources, SubgroupSize}; use crate::spirv::ir::{StorageClass, TypedModule}; @@ -179,12 +179,10 @@ fn run_both(m: &TypedModule, res: &Resources) -> Vec { } /// Whether entry `entry` of `bc` on `prof` reads a `half` from its bits by the device's widening -/// (`PrecisionNote::NativeNanEncoding`), whose reinterpretation of a NaN's bits is the device's. +/// (`PrecisionNote::NativeNanEncoding`, or `VkProperty::MetalNanMoves` on a device the interpreter +/// is not: `device_nan_bits`), whose reinterpretation of a NaN's bits is the device's. fn native_halves(bc: &[u8], entry: &str, prof: &DeviceProfile) -> bool { - compile(bc, entry, prof) - .expect("compile") - .precision - .contains(&PrecisionNote::NativeNanEncoding) + device_nan_bits(&compile(bc, entry, prof).expect("compile")) } /// `got` against the bit patterns `want`. Where the module reads a `half` from its bits by the diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index c0a497616..af32b3a9f 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -12970,6 +12970,7 @@ variant metal2vulkan::device::VkProperty::MetalHalfStorageWrites MetalHalfStorag variant metal2vulkan::device::VkProperty::MetalHalfTexelWrites MetalHalfTexelWrites variant metal2vulkan::device::VkProperty::MetalInterpolation MetalInterpolation variant metal2vulkan::device::VkProperty::MetalMinMax MetalMinMax +variant metal2vulkan::device::VkProperty::MetalNanMoves MetalNanMoves variant metal2vulkan::device::VkProperty::MetalNorm16ColorWrites MetalNorm16ColorWrites variant metal2vulkan::device::VkProperty::MetalNormStorageWrites MetalNormStorageWrites variant metal2vulkan::device::VkProperty::MetalNormalizedVertexFetch MetalNormalizedVertexFetch @@ -13127,6 +13128,7 @@ variant metal2vulkan::error::DriverDeviation::MetalHalfStorageWrites MetalHalfSt variant metal2vulkan::error::DriverDeviation::MetalHalfTexelWrites MetalHalfTexelWrites variant metal2vulkan::error::DriverDeviation::MetalInterpolation MetalInterpolation variant metal2vulkan::error::DriverDeviation::MetalMinMax MetalMinMax +variant metal2vulkan::error::DriverDeviation::MetalNanMoves MetalNanMoves variant metal2vulkan::error::DriverDeviation::MetalNorm16ColorWrites MetalNorm16ColorWrites variant metal2vulkan::error::DriverDeviation::MetalNormStorageWrites MetalNormStorageWrites variant metal2vulkan::error::DriverDeviation::MetalNormalizedVertexFetch MetalNormalizedVertexFetch diff --git a/crates/metal2vulkan/tests/golden_hashes.tsv b/crates/metal2vulkan/tests/golden_hashes.tsv index 9b238e442..20930de65 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 02aaf62ca4746a31 +profile moltenvk-m3 bd83009ea35a5b23 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 d6fd14a93..b38a0eb9d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3458,7 +3458,19 @@ bound. widen with its bits. And wherever a `half` is encoded to its bits (a store, a reinterpretation, a texel's bits) where they are not the bits it was read from, on every device, since the encode is the device's narrowing (its conversion with `shaderFloat16`, `PackHalf2x16` without): a NaN's - bits the device's, where Metal keeps a `half` NaN's sign and payload. + bits the device's, where Metal keeps a `half` NaN's sign and payload. **Exempt:** on a profile + that takes `DriverDeviation::MetalNanMoves`, MoltenVK on Apple's GPUs of the Apple M3 Max's + macOS 27 identity, whose widening, narrowing, `float` `fneg` and `fabs` and `half` `fabs` were + measured to answer Metal's bits (every `half` widened, moved through a select, a phi of a + `half` and of a `half2`, a later block and `fabs`, and 98,368 `float` words negated and taken + the magnitude of, on Metal and on the runtime, `runtime_lane::nan_moves`), a `float` `fneg` or + `fabs`, a `half`'s widening to `float`, a `half` `fabs`, and a module's reads and encodes of a + `half`'s bits record no note and require `VkProperty::MetalNanMoves`. The exemption stops where + the module carries a widened `half` out of the registers before narrowing it (a store to a stage + output or a variable other than a function's `float` one, a call, a return, a group, atomic or + image operation), reads its widened bits (a bitcast but to store them to memory, `frexp`, + `modf`, `ldexp`), or holds a `float` NaN constant other than `0x7fc00000`: such a module + records the note there too. A `half` `fneg` records it on every device. - `metal2vulkan-degrade-native-min-max` (precision). `PrecisionNote::NativeMinMax`: Native device maths: Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` (its `clamp(x, +0, 1)`) on `float` or `half` is the device's `GLSL.std.450` `NMin`, `NMax` or `NClamp`, on a device not diff --git a/docs/HOWTO.md b/docs/HOWTO.md index d05fce894..47619d3e2 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -51,9 +51,11 @@ A `half` read from memory or from its bits is the device's widening on every dev `OpFConvert` of the bits read as a 16-bit float with `shaderFloat16`, `GLSL.std.450 UnpackHalf2x16` without it), and a `half` stored or reinterpreted as bits, unless they are the bits it was loaded from, the device's narrowing (an `OpFConvert` to 16 bits, `GLSL.std.450 -PackHalf2x16` without `shaderFloat16`); the pipeline records `NativeNanEncoding` (a NaN's bits) -and, where that conversion is neither under the float controls nor measured to be Metal's, -`NativeHalfConversion` (a denormal the device may flush). +PackHalf2x16` without `shaderFloat16`); the pipeline records `NativeNanEncoding` (a NaN's bits; +not on MoltenVK on the Apple M3 Max's macOS 27 identity, `DriverDeviation::MetalNanMoves`, where +the `half` moves through the registers alone) and, where that conversion is neither under the +float controls nor measured to be Metal's, `NativeHalfConversion` (a denormal the device may +flush). To read AIR without translating it (list a metallib's functions, decode a module into typed IR, read its entry points' bindings, canonicalize an entry under function-constant values), depend on