From 217cc233f592a2b91fc0cd2d80d7645726fb9015 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 2 Nov 2026 15:29:09 -0800 Subject: [PATCH] Carve MoltenVK on the M3 Max's identity out of NativeHalfConversion for measured conversions reims-vgpu treats precision notes as fatal on Apple GPUs; NativeHalfConversion was its largest group of Mac-only failures (37 tests). The note says a half rounded through the device's conversion to 16 bits and back may differ from Metal's. On the M3 Max (MoltenVK 1.4.2, macOS 27.0.1), MoltenVK writes OpFConvert to 16 bits as MSL half(x), which is Metal's half(float), and Metal's compiler folds the conversion of an image instruction's float texel into the access. What: a new DriverDeviation::MetalHalfConversion (VkProperty::MetalHalfConversion), taken by the APPLE9 MoltenVK row alone. Where the profile takes it: - narrow::round_measured rounds a float the function holds (an AIR fptrunc or air.convert from float, through resize) by the conversion pair and records the pair's narrowing in a new module side table, measured_roundings (kept through edit.rs's retain and the roll pass's check); - narrow::rounds_unmeasured finds any other conversion pair: one neither recorded nor of a texel an image read, fetch, sample or gather hands back (directly, through a composite extract, or through a parameter every call passes such a texel); - the compile records NativeHalfConversion only where such an unmeasured pair exists, and otherwise requires the property. A half operation or function computed in float and rounded keeps the note: Metal's half tanh answers 7 of the 65,536 halves otherwise than the conversion of its float tanh. exp, sqrt and a reciprocal on half matched, but they are functions, not the conversion, so they stay noted. Verified on this M3 Max, word for word against plain Metal (an MSL probe, fast and safe math): - the conversion of a float loaded (425,216 words), of a sum, product and quotient (144,896 pairs each), of an fma (123,648) and of an integer's quotient (190,208): 0 words differ; - the half result of read, nearest sample at the centre, linear sample a quarter texel off and gather of every texel of ten formats (RGBA32Float, RGBA16Float, RGBA8Unorm and its sRGB twin, RGBA8Snorm, RGBA16Unorm, RGBA16Snorm, RGB10A2Unorm, RG11B10Float, RGB9E5Float): 0 differ. - New lane runtime_lane::half_conversions on MoltenVK: load, sum, product and fma kernels carry no note and 0 of 253,958 lanes per kernel differ from the half model; the half tanh kernel keeps the note. With measured_conversion forced false the lane fails. - New core test half_conversions_are_metals_where_measured: the four forms lose the note and require the property on moltenvk-m3 with the deviation, keep it without the deviation, and the half tanh keeps it on both; it fails with the carve disabled. - Notes of every public fixture on moltenvk-m3, lavapipe and nvidia-rtx5080-laptop before and after: NativeHalfConversion leaves 58 moltenvk-m3 rows, and no row gains a note. Consumer AIR on moltenvk-m3: 23 entries noted before, 2 after (a heap texture's held half read). Docs: API.md (native-half-conversion exemption), HOWTO.md, the PrecisionNote, VkProperty and deviation rustdoc, the driver-facts measurement record. SEMANTICS_VERSION 1949 and ARTIFACT_FORMAT_VERSION 484 (new VkProperty variants in the codec); these bumps cover the rest of this branch. api_signatures gains the two variants. (cherry picked from commit 266f7cd26327e408d9cd1f0d6ea5ba33e49e10b3) --- .../src/runtime_lane.rs | 2 + .../src/runtime_lane/half_conversions.rs | 289 ++++++++++++++++++ crates/metal2vulkan/src/cache/codec.rs | 2 +- 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 | 4 + .../metal2vulkan/src/device/requirements.rs | 10 + .../src/device/tests/driver_facts.rs | 10 +- crates/metal2vulkan/src/error/mod.rs | 14 + crates/metal2vulkan/src/lower/arith/narrow.rs | 133 +++++++- crates/metal2vulkan/src/pipeline/artifact.rs | 11 + crates/metal2vulkan/src/pipeline/compile.rs | 16 +- .../metal2vulkan/src/spirv/builder/module.rs | 14 + crates/metal2vulkan/src/spirv/ir/edit.rs | 1 + crates/metal2vulkan/src/spirv/ir/module.rs | 10 + crates/metal2vulkan/src/spirv/roll/mod.rs | 1 + crates/metal2vulkan/src/tests/engine_arith.rs | 95 ++++++ crates/metal2vulkan/tests/api_signatures.tsv | 2 + docs/API.md | 10 +- docs/HOWTO.md | 7 +- 21 files changed, 649 insertions(+), 11 deletions(-) create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/half_conversions.rs diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index b565bd38b..20d25c768 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -473,6 +473,8 @@ mod guarded_effects; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod guest_frame_costs; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod half_conversions; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod half_output_blends; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod half_read_nans; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/half_conversions.rs b/crates/metal2vulkan-validation/src/runtime_lane/half_conversions.rs new file mode 100644 index 000000000..c9bd89b16 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/half_conversions.rs @@ -0,0 +1,289 @@ +//! A `half` a kernel rounds from a `float` it holds, on the device the cfg selects, under the +//! validation layer: an AIR `fptrunc` of a loaded `float`, of a sum and a product of two and of a +//! fused multiply-add (`DriverDeviation::MetalHalfConversion`), and a `half` `tanh` of a `half`, +//! which the module computes in `float` and rounds. +//! +//! What plain Metal answers (our probe on the Apple M3 Max under macOS 27.0.1, with and without +//! fast math, over these inputs and more): `half(x)` of the `float` the function holds, to nearest +//! even on the `half` grid, `half` denormals kept, infinity from 65520 up; the `float` sum, +//! product and fused multiply-add are IEEE's, rounded to nearest even. Its `half` `tanh` is its own +//! function, which answers 7 of the 65,536 `half`s otherwise than the nearest even `half` of its +//! `float` `tanh`. +//! +//! The module rounds each `half` through the device's conversion of the `float` to 16 bits. Where +//! the profile takes the deviation (MoltenVK on the Apple M3 Max's macOS 27 identity) the +//! conversion kernels record no `PrecisionNote::NativeHalfConversion` and every lane is Metal's +//! word; the `tanh` kernel records it there, as a `half` function computed in `float`. Elsewhere a +//! kernel that rounds through the conversion records the note, and its lanes are the device's, +//! which the test prints as `HALF-CONVERSIONS` lines. + +use super::degrade_notices::on_device; +use super::driver_deviations::stage_notes; +use super::{buffer_with, read_buffer, WAIT}; +use crate::air_library::AirLibrary; +use metal2vulkan::device::VkProperty; +use metal2vulkan::pipeline::{ComputePipelineDescriptor, PrecisionNote, StageSource}; +use metal2vulkan_devtools::llvm_assemble_text; +use metal2vulkan_runtime::{CommandBufferStatus, Device, PipelineOptions, Size}; + +/// A kernel of the lane: its entry, how many `float` operands it reads per lane, and its body +/// between the loads of `%a`, `%b` and `%c` and the store of the `half` `%r`. +struct Kernel { + entry: &'static str, + operands: u64, + body: &'static str, +} + +/// The kernels. Each converts the `float` the function holds, but `tanh16`, whose `half` operand +/// is `%a` rounded. +const KERNELS: [Kernel; 5] = [ + Kernel { + entry: "load", + operands: 1, + body: " %r = fptrunc float %a to half\n", + }, + Kernel { + entry: "sum", + operands: 2, + body: " %s = fadd float %a, %b\n %r = fptrunc float %s to half\n", + }, + Kernel { + entry: "product", + operands: 2, + body: " %s = fmul float %a, %b\n %r = fptrunc float %s to half\n", + }, + Kernel { + entry: "fma", + operands: 3, + body: " %s = call float @air.fma.f32(float %a, float %b, float %c)\n %r = fptrunc float %s to half\n", + }, + Kernel { + entry: "tanh16", + operands: 1, + body: " %h = fptrunc float %a to half\n %r = call half @air.tanh.f16(half %h)\n", + }, +]; + +/// The lane's AIR: every kernel of [`KERNELS`], buffer 0 its lanes' `float` operands, buffer 1 +/// its `half` 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 mut loads = format!( + " %i = zext i32 %gid to i64\n %base = mul i64 %i, {}\n", + kernel.operands + ); + for (o, name) in ["a", "b", "c"] + .iter() + .enumerate() + .take(kernel.operands as usize) + { + loads.push_str(&format!( + " %j{name} = add i64 %base, {o}\n %p{name} = getelementptr inbounds float, ptr addrspace(1) %in, i64 %j{name}\n %{name} = load float, ptr addrspace(1) %p{name}, align 4\n" + )); + } + defs.push_str(&format!( + "define void @{e}(ptr addrspace(1) %in, ptr addrspace(1) %out, i32 %gid) {{\nentry:\n{loads}{body} %o = getelementptr inbounds half, ptr addrspace(1) %out, i64 %i\n store half %r, ptr addrspace(1) %o, align 2\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 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"float\", !\"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 2, !\"air.arg_type_align_size\", i32 2, !\"air.arg_type_name\", !\"half\", !\"air.arg_name\", !\"out\"}}\n", + e = kernel.entry, + a = n + 1, + b = n + 2, + c = n + 3, + )); + } + format!( + "; Owned synthetic kernels.\nsource_filename = \"half_conversions.metal\"\n\n{defs}declare float @air.fma.f32(float, float, float)\ndeclare half @air.tanh.f16(half)\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 value of half `h` (finite). +fn half_value(h: u16) -> f64 { + let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 }; + let exp = i32::from((h >> 10) & 0x1f); + let mant = f64::from(h & 0x3ff); + sign * match exp { + 0 => mant * 2f64.powi(-24), + e => (1024.0 + mant) * 2f64.powi(e - 25), + } +} + +/// The `float`s the conversions round: every finite `half`'s value, the `float` nearest each +/// midpoint between two adjacent finite `half`s and the `float`s one ulp either side of it, of +/// both signs, and the overflow edge. +fn tie_floats() -> Vec { + let mut v = Vec::new(); + for h in 0..0x7c00u16 { + let x = half_value(h); + v.push(x as f32); + if h < 0x7bff { + let m = ((x + half_value(h + 1)) / 2.0) as f32; + let b = m.to_bits(); + v.extend([m, f32::from_bits(b - 1), f32::from_bits(b + 1)]); + } + } + v.extend([65504.0, 65519.0, 65519.996, 65520.0, 65536.0, 1.0e5]); + let negated: Vec = v.iter().map(|x| -x).collect(); + v.extend(negated); + v +} + +/// Each kernel's lanes: its operands, with no `float` denormal among them or among the `float` +/// result (Metal reads and flushes them as zero, `PrecisionNote::DeviceDenormals`): a loaded +/// `float`, a tie with a small addend, a tie with a factor a few ulps from one, and a fused +/// multiply-add of a tie by one with a small addend. +fn operands(kernel: &Kernel, ties: &[f32]) -> Vec<[f32; 3]> { + let normal = |x: f32| x == 0.0 || x.abs() >= f32::MIN_POSITIVE; + ties.iter() + .enumerate() + .map(|(n, &t)| { + let k = (n % 7) as i32 - 3; + let small = t * 2f32.powi(-20) * k as f32; + let factor = 1.0 + k as f32 * f32::EPSILON; + match kernel.entry { + "sum" => [t, small, 0.0], + "product" => [t, factor, 0.0], + "fma" => [t, 1.0, small], + _ => [t, 0.0, 0.0], + } + }) + .filter(|o| o.iter().all(|&x| normal(x)) && normal(result(kernel.entry, o))) + .collect() +} + +/// The `float` a kernel converts: IEEE's operation, rounded to nearest even. +fn result(kernel: &str, o: &[f32; 3]) -> f32 { + match kernel { + "sum" => o[0] + o[1], + "product" => o[0] * o[1], + "fma" => o[0].mul_add(o[1], o[2]), + _ => o[0], + } +} + +/// Metal's `half(x)`: to nearest even on the `half` grid, `half` denormals kept, infinity from +/// 65520 up (`x` not a NaN). +fn half_of(x: f32) -> u16 { + let sign = if x.is_sign_negative() { 0x8000 } else { 0 }; + let a = f64::from(x.abs()); + if a >= 65520.0 { + return sign | 0x7c00; + } + if a < 2f64.powi(-14) { + return sign | (a * 2f64.powi(24)).round_ties_even() as u16; + } + let e = a.log2().floor() as i32; + let e = if 2f64.powi(e) > a { e - 1 } else { e }; + let m = (a / 2f64.powi(e - 10)).round_ties_even() as u32; + let (e, m) = if m == 2048 { (e + 1, 1024) } else { (e, m) }; + if e > 15 { + return sign | 0x7c00; + } + sign | ((e + 15) as u16) << 10 | (m - 1024) as u16 +} + +/// `kernel`'s `half` words on `device` for `lanes`. +fn run(device: &Device, kernel: &Kernel, air: &[u8], lanes: &[[f32; 3]]) -> 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 = lanes + .iter() + .flat_map(|o| o[..kernel.operands as usize].to_vec()) + .flat_map(f32::to_le_bytes) + .collect(); + let n = lanes.len() as u64; + let input = buffer_with(device, &bytes).unwrap(); + let out = buffer_with(device, &vec![0x5a; (n * 2) 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 * 2).unwrap(); + got.as_chunks::<2>() + .0 + .iter() + .map(|b| u16::from_le_bytes(*b)) + .collect() +} + +/// Every conversion kernel answers Metal's `half` on every lane and records no +/// `PrecisionNote::NativeHalfConversion` where the profile takes +/// `DriverDeviation::MetalHalfConversion` (`VkProperty::MetalHalfConversion`), and the `tanh` +/// kernel records it there; elsewhere a kernel's lanes may be the device's where it records the +/// note. Every finite `half`'s value and the `float`s at and beside each midpoint between two, +/// both signs (254,000 lanes or so a kernel; the module docs). +#[test] +fn half_conversions_are_metals_where_measured_and_noted_elsewhere() { + let air = llvm_assemble_text(&library()).unwrap(); + let ties = tie_floats(); + on_device(|device, _| { + let measured = device + .compile_device() + .profile() + .enabled() + .properties + .contains(&VkProperty::MetalHalfConversion); + let mut report = Vec::new(); + for kernel in &KERNELS { + let notes = stage_notes(device, &air, kernel.entry); + let noted = notes.contains(&PrecisionNote::NativeHalfConversion); + if kernel.entry == "tanh16" { + // A `half` function computed in `float`: noted where the conversion is measured. + assert!(!measured || noted, "tanh16: {notes:?}"); + continue; + } + assert!( + !measured || !noted, + "{}: NativeHalfConversion recorded where the profile takes MetalHalfConversion", + kernel.entry + ); + let lanes = operands(kernel, &ties); + let got = run(device, kernel, &air, &lanes); + let mut differ = 0; + for (o, &g) in lanes.iter().zip(&got) { + let want = half_of(result(kernel.entry, o)); + if g == want { + continue; + } + assert!( + noted, + "{}: operands {o:?} answered {g:#06x}, Metal's {want:#06x} (notes {notes:?})", + kernel.entry + ); + differ += 1; + } + report.push(format!( + "HALF-CONVERSIONS {} on {}: {differ} of {} lanes the device's, note {noted}", + kernel.entry, + device.name(), + lanes.len() + )); + } + for line in &report { + println!("{line}"); + } + }); +} diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 63b34a633..cc2346e4f 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1033,7 +1033,7 @@ codec_enum! { MetalDepth16Stores, MetalDepth16BiasedStores, MetalInterpolation, MetalFirstVertexIndices, MetalFullQuads, ProvokingVertexModePerPipeline, DepthImageKeepsValuesOutsideUnitRange, MetalNormalizedVertexFetch, MetalAlphaCoverage, InterpolateAtOffsetFromSevenSixteenths, - MetalNanMoves, MetalPackConversions, + MetalNanMoves, MetalPackConversions, MetalHalfConversion, } VkLimit { MaxComputeWorkGroupSize(f0), MaxComputeWorkGroupCount(f0), MaxComputeWorkGroupInvocations, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 3ce438e89..9d5e7014b 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 = 1948; +pub const SEMANTICS_VERSION: u32 = 1949; /// 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 = 1948; /// 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 = 483; +pub const ARTIFACT_FORMAT_VERSION: u32 = 484; /// 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 5a899bf22..b7ac6d625 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -815,6 +815,9 @@ fn enabled_caps(desc: &DeviceDescription, deviations: &BTreeSet if deviations.contains(&DriverDeviation::MetalPackConversions) { properties.insert(VkProperty::MetalPackConversions); } + if deviations.contains(&DriverDeviation::MetalHalfConversion) { + properties.insert(VkProperty::MetalHalfConversion); + } 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 f6e160b58..72f97a9d8 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -431,6 +431,24 @@ pub(crate) fn among( /// unpacks of `unorm2x16` and `snorm2x16` (8 lanes, a `float` quotient rounded twice); /// `snorm10a2` is unmeasured. One row per GPU, as measured. /// +/// `MetalHalfConversion`: MoltenVK 1.4.2 writes `OpFConvert` from 32 to 16 bits as Metal's +/// `half(x)`, and Metal's compiler folds the conversion of an image instruction's `float` texel +/// into the access. On the M3 Max under macOS 27.0.1 (2026-11-03), word for word against plain +/// Metal, with and without fast math: the conversion of a `float` loaded (425,216 words: every +/// `half`'s value, each midpoint between two `half`s and the `float`s either side of it, values +/// inside each interval, the overflow edge, the `half` denormals' range and below it, NaNs and +/// random words, both signs), of a sum, a product and a quotient of two (144,896 pairs each, built +/// to land on and beside the `half` ties), of a fused multiply-add (123,648) and of an integer's +/// quotient (190,208): none differs. Nor does the `half` result of a `read()`, a nearest sample at +/// the texel's centre, a linear sample a quarter texel off it and a gather of every texel of +/// `RGBA32Float` (every `float` word above), `RGBA16Float` (every `half`), `RGBA8Unorm`, its sRGB +/// twin, `RGBA8Snorm`, `RGBA16Unorm` and `RGBA16Snorm` (every code), `RGB10A2Unorm` (every code) +/// and `RG11B10Float` and `RGB9E5Float` (16,384 random words each). Measured to differ, so outside +/// it: Metal's `half` `tanh`, which answers 7 of the 65,536 `half`s otherwise than the nearest +/// even `half` of its `float` `tanh`; `exp`, `sqrt` and a reciprocal on `half` matched, but each is +/// a function or an operation computed otherwise than by the conversion, so it stays noted +/// (`narrow::rounds_unmeasured`). One row per GPU, as measured. +/// /// Another driver has none of them, as Vulkan states, and a listed driver on another vendor's GPU /// (or another GPU than a row's) is unmeasured: the profile then takes each one's route without /// it, which the deviation's docs name (`derive.rs`). @@ -625,6 +643,10 @@ pub(crate) const DEVIATIONS: &[Measured] = &[ device: Some(APPLE9), ..moltenvk_on_apple(DriverDeviation::MetalPackConversions) }, + Measured { + device: Some(APPLE9), + ..moltenvk_on_apple(DriverDeviation::MetalHalfConversion) + }, ]; /// NVIDIA's `vendorID`. diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index e0d633b0a..5785bc62a 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -343,6 +343,10 @@ impl DeviceProfile { .enabled .properties .contains(&VkProperty::MetalPackConversions), + DriverDeviation::MetalHalfConversion => f + .enabled + .properties + .contains(&VkProperty::MetalHalfConversion), } } diff --git a/crates/metal2vulkan/src/device/requirements.rs b/crates/metal2vulkan/src/device/requirements.rs index 7d04e69f8..5bb37fbd7 100644 --- a/crates/metal2vulkan/src/device/requirements.rs +++ b/crates/metal2vulkan/src/device/requirements.rs @@ -849,6 +849,16 @@ pub enum VkProperty { /// [`PrecisionNote::DevicePackConversion`](crate::pipeline::PrecisionNote::DevicePackConversion) /// for it requires it. MetalPackConversions, + /// The device's conversion of a 32-bit float to 16 bits answers Metal's `half(float)` where + /// the module converts a `float` it holds, and Metal's own `half` texel where the `float` is + /// an image instruction's texel (the driver's measured deviation + /// [`DriverDeviation::MetalHalfConversion`](crate::error::DriverDeviation::MetalHalfConversion)). + /// No Vulkan query reports it: without the float controls Vulkan leaves the conversion's + /// rounding to the device. A module that rounds a `half` through that conversion in those + /// forms alone records no + /// [`PrecisionNote::NativeHalfConversion`](crate::pipeline::PrecisionNote::NativeHalfConversion) + /// and requires it. + MetalHalfConversion, /// `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 9be35365b..ac622f6c2 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -160,6 +160,10 @@ fn taken(p: &crate::device::DeviceProfile) -> Vec D::MetalPackConversions, property(VkProperty::MetalPackConversions), ), + ( + D::MetalHalfConversion, + property(VkProperty::MetalHalfConversion), + ), ] .into_iter() .inspect(|&(d, taken)| { @@ -174,7 +178,7 @@ fn taken(p: &crate::device::DeviceProfile) -> Vec /// at every release: every Apple GPU's (MoltenVK's lockstep, `float` functions, canonical NaNs, /// sampler, compute cube route and the rest of the seventeen), with the graphics cube route and the /// per-sample depth of macOS 27's Apple9 identity, that identity's normalized -/// storage writes, full quads, normalized vertex fetch, alpha to coverage, moved NaNs and pack conversions, and every Apple GPU's 16-bit unorm depth stores, interpolation +/// storage writes, full quads, normalized vertex fetch, alpha to coverage, moved NaNs, pack conversions and half conversions, and every Apple GPU's 16-bit unorm depth stores, interpolation /// and first-vertex indices; lavapipe's `float` color NaNs and half-float storage writes; RADV's on /// the Radeon 780M, ANV's on the Iris Xe of RPL-P and the UHD 770 of RPL-S, and NVIDIA's on the /// RTX 3090 and the RTX 5080 Laptop GPU, as measured there; the 8-bit linear filter's bound where @@ -232,12 +236,14 @@ fn the_profile_takes_the_deviations_its_driver_is_measured_with() { list.push(D::MetalFirstVertexIndices); } // macOS 27's full quads, measured on the M4's identity alone, and its normalized vertex - // fetch, alpha to coverage, moved NaNs and pack conversions, measured on the M3 Max under it. + // fetch, alpha to coverage, moved NaNs, pack conversions and half conversions, measured on the + // M3 Max under it. m4_measured.push(D::MetalFullQuads); m4_measured.push(D::MetalNormalizedVertexFetch); m4_measured.push(D::MetalAlphaCoverage); m4_measured.push(D::MetalNanMoves); m4_measured.push(D::MetalPackConversions); + m4_measured.push(D::MetalHalfConversion); 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 b5ee3f127..dbdf286cc 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -847,6 +847,20 @@ pub enum DriverDeviation { /// the module requires the property. The sRGB format, `unorm10a2` in `float`, `snorm10a2`, and /// the `half` unpacks of `unorm2x16` and `snorm2x16` stay noted. Unmeasured, each records it. MetalPackConversions, + /// The device's conversion of a 32-bit float to 16 bits, `OpFConvert` (MSL's `half(x)` + /// through MoltenVK), answers Metal's (`VkProperty::MetalHalfConversion`): Metal's + /// `half(float)` (to nearest even on the `half` grid, `half` denormals kept, infinity from + /// 65520 up) of every `float` a function converts, whatever instruction computed it, and, + /// where the `float` is an image instruction's texel, Metal's own `half` result of that access, + /// into which Metal's compiler folds the conversion. Where the profile takes it, a module whose + /// every `half` rounding through that conversion (`QuantizeForm::Converted`) is a conversion of + /// a `float` the function holds (an AIR `fptrunc` or `air.convert` from `float`) or of a texel + /// an image instruction hands back records no `PrecisionNote::NativeHalfConversion` and + /// requires the property. A `half` a function or an operation computes in `float` and rounds + /// keeps the note on every profile: Metal computes it otherwise (its `half` `tanh` answers 7 + /// of the 65,536 `half`s otherwise than the nearest even `half` of its `float` `tanh`, which the + /// device's conversion answers). Unmeasured, each records it. + MetalHalfConversion, } /// 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/narrow.rs b/crates/metal2vulkan/src/lower/arith/narrow.rs index 9f0721da4..fa0bf1cf8 100644 --- a/crates/metal2vulkan/src/lower/arith/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/narrow.rs @@ -166,6 +166,11 @@ pub fn native_rounding(form: QuantizeForm) -> Option { /// rounded at all (the note's stated bound), and the store's conversion to bits rounds it /// ([`converted_bits`]). fn converted(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult { + converted_pair(fb, wide, x).map(|(_, w)| w) +} + +/// [`converted`]'s pair: the narrowing to 16 bits and its widening back. +fn converted_pair(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult<(Value, Value)> { let e = fb.module().ty(Type::Float { width: 16 })?; let h = match wide.lanes { 1 => e, @@ -173,7 +178,25 @@ fn converted(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult, f: Form, x: Value) -> BResult { + match (f.held, fb.module().quantize_form()) { + (Held::Float(FloatFmt::Half), QuantizeForm::Converted) => { + let (n, w) = converted_pair(fb, f.with(Held::Float(FloatFmt::F32)), x)?; + fb.module().note_measured_rounding(n); + Ok(w) + } + _ => round(fb, f, x), + } } /// `x` (`f32` lanes of form `wide`) rounded to `half` by the device's conversion to 16 bits and @@ -306,6 +329,112 @@ pub fn rounds_by_conversion(m: &TypedModule, meter: &mut Meter) -> Result Result { + let width = |v: Value| -> Option { + let ty = m.value(v).ok()?.ty; + let ty = match m.types().get(ty).ok()? { + Type::Vector { elem, .. } => *elem, + _ => ty, + }; + match m.types().get(ty).ok()? { + Type::Float { width } => Some(*width), + _ => None, + } + }; + let words = m.values().len().div_ceil(64); + let bytes = 8 * m.values().len() + 8 * words; + meter.charge(bytes)?; + // Each instruction result's definition. + let mut def: Vec> = vec![None; m.values().len()]; + for n in m.blocks().iter().flat_map(|b| &b.insts) { + if let Some(slot) = n.result.and_then(|r| def.get_mut(r.index())) { + *slot = Some(&n.inst); + } + } + let image = |v: Value| -> bool { + let at = |v: Value| def.get(v.index()).copied().flatten(); + let direct = |i: Option<&Inst>| { + matches!( + i, + Some( + Inst::ImageFetch { .. } + | Inst::ImageRead { .. } + | Inst::ImageSample { .. } + | Inst::ImageGather { .. } + | Inst::ImageDrefGather { .. } + ) + ) + }; + match at(v) { + Some(Inst::CompositeExtract { composite, .. }) => direct(at(*composite)), + i => direct(i), + } + }; + let texel = |v: Value| -> bool { + if image(v) { + return true; + } + let Ok(ValueOrigin::Param { func, index }) = m.value(v).map(|d| d.origin) else { + return false; + }; + let mut calls = m + .blocks() + .iter() + .flat_map(|b| &b.insts) + .filter_map(|n| match &n.inst { + Inst::Call { func: f, args } if *f == func => Some(args), + _ => None, + }) + .peekable(); + calls.peek().is_some() + && calls.all(|args| args.get(index as usize).is_some_and(|&a| image(a))) + }; + let fconverts = || { + m.blocks() + .iter() + .flat_map(|b| &b.insts) + .filter_map(|n| match (&n.inst, n.result) { + ( + Inst::Convert { + op: ConvOp::FConvert, + a, + .. + }, + Some(r), + ) => Some((*a, r)), + _ => None, + }) + }; + // The narrowings some conversion widens back. + let mut widened = vec![0u64; words]; + for (a, r) in fconverts() { + if width(a) == Some(16) && width(r) == Some(32) { + set_bit(&mut widened, a); + } + } + let found = fconverts().any(|(a, r)| { + width(a) == Some(32) + && width(r) == Some(16) + && has_bit(&widened, r) + && !m.measured_roundings().contains(&r) + && !texel(a) + }); + drop((def, widened)); + meter.release(bytes); + Ok(found) +} + /// An upper estimate of the SPIR-V words of one [`round_texel`] on form `f`: [`round`]'s, and the /// NaN test's four instructions with their two constants. pub fn round_texel_words(f: Form) -> u32 { @@ -1802,6 +1931,8 @@ pub fn resize(fb: &mut FunctionBuilder<'_>, from: Form, to: Form, x: Value) -> B ); if widening { Ok(x) + } else if (src, dst) == (FloatFmt::F32, FloatFmt::Half) { + round_measured(fb, to, x) } else { round(fb, to, x) } diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 819660f07..12c0150ac 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1742,6 +1742,17 @@ pub enum PrecisionNote { /// computed `half` NaN is `0x7FFF` (where 18 C3 cases differed in NaNs, signs of zero, /// `atan2` and `pow` at special operands, and `half` texel and pack conversions). /// + /// Not recorded for that rounding on a profile that takes + /// [`DriverDeviation::MetalHalfConversion`](crate::error::DriverDeviation::MetalHalfConversion) + /// (MoltenVK on the Apple M3 Max's macOS 27 identity) where every `half` the module rounds + /// through the conversion is a conversion of a `float` the function holds (an AIR `fptrunc` or + /// `air.convert` from `float`, whatever computed the `float`) or of a texel an image instruction + /// hands back, measured to answer Metal's there; the module then requires + /// `VkProperty::MetalHalfConversion`. A `half` operation or function the module computes in + /// `float` and rounds keeps it there too (Metal's `half` `tanh` answers 7 of the 65,536 + /// `half`s otherwise than the conversion of its `float` `tanh`), as do a texel the module + /// decodes itself and every other rounding (`lower::arith::narrow::rounds_unmeasured`). + /// /// Every `half` a module reads from its bits (a load, a reinterpretation, a texel's bits) is /// the device's widening of them, on every device: an `OpFConvert` to 32 bits of the bits read /// as a 16-bit float with `shaderFloat16`, `GLSL.std.450 UnpackHalf2x16` of them without it. diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 80b7c5d4b..96b28f687 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -2667,9 +2667,15 @@ fn compile_kept( let device_quantize = quantize == crate::spirv::builder::QuantizeForm::Device && crate::lower::arith::narrow::quantizes(&module); // A `half` rounded through the device's conversion to 16 bits and back, with no quantize: the - // module records the native note. + // module records the native note, but where the device's conversion is measured to answer + // Metal's (`DriverDeviation::MetalHalfConversion`) and every such rounding is of a form the + // measurement covers (a `float` the function converts, or an image instruction's texel), + // which the module then requires. let converts = quantize == crate::spirv::builder::QuantizeForm::Converted && crate::lower::arith::narrow::rounds_by_conversion(&module, m)?; + let measured_conversion = converts + && p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfConversion) + && !crate::lower::arith::narrow::rounds_unmeasured(&module, m)?; // A `half` read from its bits by the device's widening, or encoded to them by its narrowing // (every profile: `OpFConvert` with `shaderFloat16`, `UnpackHalf2x16` and `PackHalf2x16` // without): a NaN's bits are the device's, recorded. Under the float controls its denormals @@ -2717,7 +2723,7 @@ fn compile_kept( ), (device_quantize, PrecisionNote::NativeHalfQuantize), ( - converts || native_widening, + (converts && !measured_conversion) || native_widening, PrecisionNote::NativeHalfConversion, ), ]; @@ -2808,6 +2814,12 @@ fn compile_kept( .properties .insert(crate::device::requirements::VkProperty::MetalNanMoves); } + // A `half` rounded by the device's conversion with no note because it is Metal's. + if measured_conversion { + requirements + .properties + .insert(crate::device::requirements::VkProperty::MetalHalfConversion); + } // A packed format's conversion left to the device with no note because it is Metal's. if plan.families.arith.metal_packs { requirements diff --git a/crates/metal2vulkan/src/spirv/builder/module.rs b/crates/metal2vulkan/src/spirv/builder/module.rs index 3ccd051b6..247769d99 100644 --- a/crates/metal2vulkan/src/spirv/builder/module.rs +++ b/crates/metal2vulkan/src/spirv/builder/module.rs @@ -101,6 +101,11 @@ pub struct ModuleBuilder { /// Every result that carries a non-uniform descriptor element (`Inst::carries_non_uniform`): /// decorated `NonUniform`, and refused where it would reach an undecorated operand. pub(super) non_uniform: BTreeSet, + /// The narrowings to 16 bits of the conversion pairs that round a `half` in a form measured + /// to answer Metal's on the devices whose driver takes `DriverDeviation::MetalHalfConversion` + /// (`ModuleBuilder::note_measured_rounding`). Nothing emitted depends on it: the compile + /// reads it to decide `PrecisionNote::NativeHalfConversion`. + pub(super) measured_roundings: BTreeSet, /// The `Function` variables the emitter holds workgroup uniform by construction /// (`FunctionBuilder::note_uniform_var`). Nothing emitted depends on it: a record for the /// checks of `spirv::testing::barriers`, kept only where they build. @@ -281,6 +286,13 @@ impl ModuleBuilder { self.native_half = native; } + /// Record `narrowed`, the narrowing to 16 bits of a conversion pair that rounds a `half` in a + /// form measured to answer Metal's where the driver takes + /// `DriverDeviation::MetalHalfConversion` (`narrow::round_measured`). + pub fn note_measured_rounding(&mut self, narrowed: Value) { + self.measured_roundings.insert(narrowed); + } + /// Whether the module's `half` rounding is the device's own /// ([`ModuleBuilder::set_native_half`]). pub fn native_half(&self) -> bool { @@ -342,6 +354,7 @@ impl ModuleBuilder { std::mem::size_of::<(GlobalId, crate::spv::Capability)>(), ) + tree_bytes(self.non_uniform.len(), std::mem::size_of::()) + + tree_bytes(self.measured_roundings.len(), std::mem::size_of::()) + map_bytes(&self.bits) + map_bytes(&self.lanes) + map_bytes(&self.inserts) @@ -1346,6 +1359,7 @@ impl ModuleBuilder { volatile: self.volatile, enabling: self.enabling, non_uniform: self.non_uniform, + measured_roundings: self.measured_roundings, #[cfg(test)] uniform_vars: self.uniform_vars, }) diff --git a/crates/metal2vulkan/src/spirv/ir/edit.rs b/crates/metal2vulkan/src/spirv/ir/edit.rs index 84700ec97..4f9df4b18 100644 --- a/crates/metal2vulkan/src/spirv/ir/edit.rs +++ b/crates/metal2vulkan/src/spirv/ir/edit.rs @@ -405,6 +405,7 @@ impl TypedModule { }; let values = &self.values; self.non_uniform.retain(|v| !removed(v, values)); + self.measured_roundings.retain(|v| !removed(v, values)); self.loops.retain(|l| at(&bmap, l.header.index()).is_some()); for l in &mut self.loops { l.header = block(l.header); diff --git a/crates/metal2vulkan/src/spirv/ir/module.rs b/crates/metal2vulkan/src/spirv/ir/module.rs index cf9fb5cc6..f815f1a62 100644 --- a/crates/metal2vulkan/src/spirv/ir/module.rs +++ b/crates/metal2vulkan/src/spirv/ir/module.rs @@ -1434,6 +1434,10 @@ pub struct TypedModule { /// The values decorated `NonUniform`: every result that carries a non-uniform descriptor /// element ([`Inst::carries_non_uniform`]), recorded as the builder appends it. pub(in crate::spirv) non_uniform: std::collections::BTreeSet, + /// The narrowings to 16 bits of the conversion pairs that round a `half` in a form measured + /// to answer Metal's where the driver takes `DriverDeviation::MetalHalfConversion` + /// (`ModuleBuilder::measured_roundings`), recorded as the builder emits them. + pub(in crate::spirv) measured_roundings: std::collections::BTreeSet, /// The `Function` variables the emitter holds workgroup uniform by construction: the `cont` /// flag of a predicated loop that iterates together, which the lowering's uniformity analysis /// proved. An in-memory record for checks (`spirv::testing::barriers`), kept only where they @@ -1459,6 +1463,12 @@ impl TypedModule { &self.consts } + /// The narrowings to 16 bits of the conversion pairs that round a `half` in a form measured to + /// answer Metal's (`ModuleBuilder::note_measured_rounding`). + pub fn measured_roundings(&self) -> &std::collections::BTreeSet { + &self.measured_roundings + } + /// The SSA value of a constant. pub fn const_value(&self, c: ConstId) -> BResult { self.const_values diff --git a/crates/metal2vulkan/src/spirv/roll/mod.rs b/crates/metal2vulkan/src/spirv/roll/mod.rs index 9bcbba735..6c2e657b7 100644 --- a/crates/metal2vulkan/src/spirv/roll/mod.rs +++ b/crates/metal2vulkan/src/spirv/roll/mod.rs @@ -1854,6 +1854,7 @@ fn verify( for (x, y) in pairs { if m.value(x)?.ty != m.value(y)?.ty || m.non_uniform.contains(&x) != m.non_uniform.contains(&y) + || m.measured_roundings.contains(&x) != m.measured_roundings.contains(&y) { return Ok(None); } diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index 446622b49..d8993e272 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -3966,6 +3966,101 @@ fn pack_conversions_are_metals_where_measured() { } } +/// A `half` rounded from a `float` the function holds, by an AIR `fptrunc` of a sum, a product, a +/// quotient or a fused multiply-add, records no `NativeHalfConversion` on a profile that takes +/// `DriverDeviation::MetalHalfConversion` (`moltenvk-m3`), and the module requires +/// `VkProperty::MetalHalfConversion`; without the deviation (the same profile with it dropped) each +/// records the note and requires nothing. A `half` function the lowering computes in `float` and +/// rounds through the conversion keeps the note there, as on every profile: Metal computes it +/// otherwise. +#[test] +fn half_conversions_are_metals_where_measured() { + use crate::device::requirements::VkProperty; + use crate::error::DriverDeviation; + let halves = |x: &str| { + format!( + " %h = fptrunc float {x} to half\n %hb = bitcast half %h to i16\n %r = zext i16 %hb to i32\n" + ) + }; + let two = format!("{}{}", of("a", 0.3), of("b", 1.7)); + // (name, body, whether the rounding converts a `float` the function holds alone). + let cases = [ + ("conv_sum", format!("{two} %s = fadd float %a, %b\n{}", halves("%s")), true), + ("conv_product", format!("{two} %s = fmul float %a, %b\n{}", halves("%s")), true), + ("conv_quotient", format!("{two} %s = fdiv float %a, %b\n{}", halves("%s")), true), + ( + "conv_fma", + format!( + "{two} %s = call float @air.fma.f32(float %a, float %b, float %a)\n{}", + halves("%s") + ), + true, + ), + ( + "half_tanh", + format!( + "{} %g = fptrunc float %a to half\n %t = call half @air.tanh.f16(half %g)\n %tb = bitcast half %t to i16\n %r = zext i16 %tb to i32\n", + of("a", 0.3) + ), + false, + ), + ]; + let ks: Vec = cases + .iter() + .map(|(name, body, _)| Kernel { + want: None, + ..k(name, body.clone(), 0) + }) + .collect(); + let text = module(&ks).replace( + DECLS, + &format!( + "{DECLS}declare float @air.fma.f32(float, float, float)\ndeclare half @air.tanh.f16(half)\n" + ), + ); + let Some(bitcode) = assemble("half-conversions", &text) else { + return; + }; + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/profiles/moltenvk-m3.json"); + let text = std::fs::read_to_string(&path).expect("profile"); + for taken in [true, false] { + let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); + let p = Device::with_deviation( + desc, + DevicePolicy::default(), + DriverDeviation::MetalHalfConversion, + taken, + ) + .expect("device") + .profile() + .clone(); + assert_eq!( + p.takes_driver_deviation(DriverDeviation::MetalHalfConversion), + taken + ); + for ((name, _, measured), kk) in cases.iter().zip(&ks) { + let what = format!("{name}, the deviation taken: {taken}"); + 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 exempt = taken && *measured; + assert_eq!( + a.precision.contains(&PrecisionNote::NativeHalfConversion), + !exempt, + "{what}: {:?}", + a.precision + ); + assert_eq!( + a.requirements + .properties + .contains(&VkProperty::MetalHalfConversion), + exempt, + "{what}" + ); + } + } +} + /// Class E: Metal's `float` `fneg` and `fabs` (`air.fabs`, `air.fast_fabs`, and `llvm.fabs`, which /// takes `air.fabs`'s answer) flip or clear the sign bit alone, with and without fast-math flags: a /// NaN keeps its payload, signaling or not, and a denormal stays. The lowering is the device's diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index f97d39426..d4b2c9ab6 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -12988,6 +12988,7 @@ variant metal2vulkan::device::VkProperty::MetalFragmentSimdgroups MetalFragmentS variant metal2vulkan::device::VkProperty::MetalFullQuads MetalFullQuads variant metal2vulkan::device::VkProperty::MetalHalfArithmetic MetalHalfArithmetic variant metal2vulkan::device::VkProperty::MetalHalfColorNans MetalHalfColorNans +variant metal2vulkan::device::VkProperty::MetalHalfConversion MetalHalfConversion variant metal2vulkan::device::VkProperty::MetalHalfFma MetalHalfFma variant metal2vulkan::device::VkProperty::MetalHalfStorageNans MetalHalfStorageNans variant metal2vulkan::device::VkProperty::MetalHalfStorageWrites MetalHalfStorageWrites @@ -13147,6 +13148,7 @@ variant metal2vulkan::error::DriverDeviation::MetalFragmentSimdgroups MetalFragm variant metal2vulkan::error::DriverDeviation::MetalFullQuads MetalFullQuads variant metal2vulkan::error::DriverDeviation::MetalHalfArithmetic MetalHalfArithmetic variant metal2vulkan::error::DriverDeviation::MetalHalfColorNans MetalHalfColorNans +variant metal2vulkan::error::DriverDeviation::MetalHalfConversion MetalHalfConversion variant metal2vulkan::error::DriverDeviation::MetalHalfFma MetalHalfFma variant metal2vulkan::error::DriverDeviation::MetalHalfStorageNans MetalHalfStorageNans variant metal2vulkan::error::DriverDeviation::MetalHalfStorageWrites MetalHalfStorageWrites diff --git a/docs/API.md b/docs/API.md index 578560bcb..73d02eca0 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3456,7 +3456,15 @@ bound. is the device's narrowing, and that conversion is neither under those controls nor measured to be Metal's: the conversion on NVIDIA and lavapipe, and `GLSL.std.450 UnpackHalf2x16` and `PackHalf2x16` on every device without `shaderFloat16`. A half denormal may read or encode as the - zero of its sign. + zero of its sign. **Exempt:** on a profile that takes `DriverDeviation::MetalHalfConversion`, + MoltenVK on Apple's GPUs of the Apple M3 Max's macOS 27 identity, a module whose every `half` + rounded through the conversion converts a `float` the function holds (an AIR `fptrunc` or + `air.convert` from `float`) or an image instruction's texel records no note for that rounding and + requires `VkProperty::MetalHalfConversion`: measured word for word against plain Metal, with and + without fast math, over 1,173,760 `float`s loaded, summed, multiplied, divided and fused, an + integer's quotient, and every texel of ten formats read, sampled and gathered as `half`. A `half` + operation or function computed in `float` and rounded keeps the note (Metal's `half` `tanh` + answers 7 of the 65,536 `half`s otherwise). - `metal2vulkan-degrade-native-half-quantize` (precision). `PrecisionNote::NativeHalfQuantize`: Native half rounding (a quantize): the module rounds a `half` result it computes in `float` (a `half` operation's, a function's, a conversion from `float`'s, a texel's) by the device's diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 47619d3e2..c87c52ac3 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -45,8 +45,11 @@ A `half` computed in `float` rounds through the device's conversion to 16 bits a `half(float)` under the float controls the entry declares, where the driver keeps that pair (ANV, RADV). Elsewhere it rounds through the device's own conversion, or its `OpQuantizeToF16` alone without `shaderFloat16` (which may flush a value below the smallest normal `half`), and the -pipeline records `NativeHalfConversion` or `NativeHalfQuantize`. NVIDIA's driver (615.71.09) -folds the pair (`DriverWorkaround::HalfConversionPairFolded`), so it takes the native conversion. +pipeline records `NativeHalfConversion` or `NativeHalfQuantize`; not `NativeHalfConversion` on +MoltenVK on the Apple M3 Max's macOS 27 identity (`DriverDeviation::MetalHalfConversion`), where +every such `half` is a conversion of a `float` the function holds or of a texel, measured to be +Metal's. NVIDIA's driver (615.71.09) folds the pair +(`DriverWorkaround::HalfConversionPairFolded`), so it takes the native conversion. A `half` read from memory or from its bits is the device's widening on every device (an `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