diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index a6bb0131b..579f9313c 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2111,26 +2111,35 @@ degradations! { DeviceVertexConversion = "device-vertex-conversion"; /// Class: native half rounding. The device's own conversion of a `float` to 16 bits /// rounds the pipeline's `half` results, on a device with `shaderFloat16` whose float - /// controls do not make that conversion Metal's `half(float)`. Recorded bound: a finite result within one - /// unit in the last place of the `half` (to nearest even on NVIDIA's RTX 5080 Laptop - /// GPU, toward zero on its RTX 3090 and lavapipe); where the device rounds toward zero, - /// 65504 from 65520 up where Metal answers infinity; a result below `2^-14` the zero of - /// its sign on a device that flushes 16-bit denormals; a NaN's encoding (`0x7FFF` on the - /// RTX 5080, where Metal answers `0x7E00`) and the sign of a zero result the device's. + /// controls do not make that conversion Metal's `half(float)`; and the device's widening + /// reads a `half` from its bits (a load, a reinterpretation, a texel's bits) where it is + /// neither under those controls nor measured to be Metal's: NVIDIA's and lavapipe's + /// conversion, and `UnpackHalf2x16` on every device without `shaderFloat16`. Recorded + /// bound: a finite result within one unit in the last place of the `half` (to nearest + /// even on NVIDIA's RTX 5080 Laptop GPU, toward zero on its RTX 3090 and lavapipe); where + /// the device rounds toward zero, 65504 from 65520 up where Metal answers infinity; a + /// result below `2^-14`, or a `half` denormal read, the zero of its sign on a device that + /// flushes 16-bit denormals; a NaN's encoding (`0x7FFF` on the RTX 5080, where Metal + /// answers `0x7E00`) and the sign of a zero result the device's. NativeHalfConversion = "native-half-conversion"; - /// Class: native half rounding. The device's `OpQuantizeToF16` rounds the pipeline's - /// `half` results on a device without `shaderFloat16` whose quantize is not measured to - /// be Metal's. Recorded bound: a finite - /// result within one unit in the last place of the `half`; 65504 to 65520 possibly - /// infinity where Metal answers 65504; a NaN's encoding the device's. + /// Class: native half rounding. The device's `OpQuantizeToF16` alone rounds the + /// pipeline's `half` results computed in `float` on every device without `shaderFloat16`, + /// its quantize measured or not; an integer's `half` rounds exactly. Recorded bound: a + /// finite result within one unit in the last place of the `half`; 65504 to 65520 possibly + /// infinity where Metal answers 65504; a value below `2^-14` possibly a zero of either + /// sign where Metal answers the `half` denormal, or `2^-14` from just below it; a NaN's + /// encoding the device's. NativeHalfQuantize = "native-half-quantize"; /// Class: native device maths. The device's NaN answers a `float` or `half` operation's /// NaN result where Metal answers a NaN the device is not measured to answer (every NaN - /// but the canonical one on a device measured to answer Metal's canonical NaN). Recorded - /// bound: where Metal answers a NaN the device answers a - /// NaN, its sign and payload the device's own, where Metal answers `0x7fc00000` - /// (`0x7e00` as `half`), an operand's bits, or the canonical NaN with an operand's sign; - /// every other result unchanged. + /// but the canonical one on a device measured to answer Metal's canonical NaN); and every + /// pipeline that reads a `half` from its bits, on every device, widens it by the device + /// (`OpFConvert` with `shaderFloat16`, `UnpackHalf2x16` without), a NaN to a NaN of the + /// device's bits. Recorded bound: where Metal answers a NaN the device answers a NaN, its + /// sign and payload the device's own, where Metal answers `0x7fc00000` (`0x7e00` as + /// `half`), an operand's bits, or the canonical NaN with an operand's sign, and where + /// Metal widens a `half` NaN to `0x7fc00000`; a `half` stored back unchanged keeps its + /// bits; every other result unchanged. NativeNanEncoding = "native-nan-encoding"; /// Class: native device maths. The device's `NMin`, `NMax` or `NClamp` answers Metal's /// `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` (its `clamp(x, +0, 1)`) on diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 51478fc9f..df43dbb77 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -10cb4b76a4eacbc7fac1741116671ed03e8211a5b76b10e8e66a91011810cbf1 +7546e8c005449229df98622699fc5c8911eed95126d86d9fbdfa7889e739c3bf diff --git a/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs b/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs index 175cb5a6d..726643d52 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/driver_deviations.rs @@ -49,11 +49,13 @@ //! where the profile takes `MetalCanonicalNans`, and a NaN of the device's bits elsewhere //! (`NativeNanEncoding`). //! - **The `half` quantize** (`MetalHalfQuantize`): the NaN model's narrowing, conversion and -//! `half` cases. Where the profile takes the deviation, a `half` rounding is the device's -//! `OpQuantizeToF16` alone and the kernels require `VkProperty::MetalHalfQuantize`; under the -//! float controls it is the device's conversion, Metal's by the Vulkan spec. Both give Metal's -//! largest `half` there, so those words are checked; elsewhere the device's own form rounds -//! (`NativeHalfConversion` or `NativeHalfQuantize`), whose words the test prints. +//! `half` cases. No kernel requires `VkProperty::MetalHalfQuantize`: a `half` rounding through +//! the device's `OpQuantizeToF16` (a profile without `shaderFloat16`) records +//! `NativeHalfQuantize` whether the profile takes the deviation or not, its result below the +//! smallest normal `half` the device's. Under the float controls a rounding is the device's +//! conversion, Metal's by the Vulkan spec, which gives Metal's largest `half`, so those words +//! are checked; elsewhere the device's own form rounds (`NativeHalfConversion` or +//! `NativeHalfQuantize`), whose words the test prints. //! - **The `half` conversion**: the same cases, and the owned `half` edge fixtures. A profile with //! `shaderFloat16` and without the float controls that make the device's conversion Metal's //! rounds through that conversion and records `PrecisionNote::NativeHalfConversion`: the device's @@ -73,15 +75,16 @@ //! a NaN's bits (`NativeNanEncoding`), or the device's own conversion or quantize, noted //! (`NativeHalfConversion`, `NativeHalfQuantize`), whose words the test prints. //! - **The `half` widening** (`MetalHalfArithmetic` again, whose measurement reads every `half` -//! through the device's widening): the owned fixture `hwd_half_reads` reads back every `half` -//! bit pattern, one thread each, through threadgroup words and a buffer, and uses some reads only -//! in a sum, a product, a widening to `float` and a compare, and moves another through a select -//! to memory. Every read is the module's decode for the profile (`lower::arith::narrow::from_bits`): -//! the device's widening of the bits wherever the profile has `shaderFloat16`, else the integer -//! decode, exact. Each of the 65,536 patterns is held to Metal's answer but within the stage's -//! notes' bound: a NaN's bits the device's (`NativeNanEncoding`), and where the widening is not -//! measured to be Metal's (`NativeHalfConversion`) a denormal the zero of its sign; where the -//! profile takes the deviation the module requires it, and every denormal is Metal's. +//! through the device's widening): the owned fixture `hwd_half_reads` reads back every `half` bit +//! pattern, one thread each, through threadgroup words and a buffer, and uses some reads only in +//! a sum, a product, a widening to `float` and a compare, and moves another through a select to +//! memory. Every read is the module's decode for the profile (`lower::arith::narrow::from_bits`): +//! the device's widening of the bits on every profile (its conversion with `shaderFloat16`, +//! `UnpackHalf2x16` without). Each of the 65,536 patterns is held to Metal's answer but within +//! the stage's notes' bound: a NaN's bits the device's (`NativeNanEncoding`), and where the +//! widening is neither under the 16-bit float controls nor measured to be Metal's +//! (`NativeHalfConversion`) a denormal the zero of its sign; where the profile takes the +//! deviation the module requires it, and every denormal is Metal's. //! - **The fragment simdgroups** (`MetalFragmentSimdgroups`): the owned fixture //! `gsm2_fragment_lanes` writes a fragment's `[[thread_index_in_simdgroup]]`, read as a `uint` //! and a `ushort` parameter and as a program-scope `uint`, over three draws into a 32x32 target: @@ -943,10 +946,10 @@ const HALF_EDGE_CASES: [&str; 6] = [ /// `0xFBFF` in either half, or the `float` 65504 of either sign) is the Metal row's of the same /// chip where the kernel rounds as Metal does: the device's conversion to 16 bits and back under /// the float controls that make it Metal's where the profile has them (the kernels then declare -/// them and require no fact), else the device's quantize where the profile takes -/// `MetalHalfQuantize` (the kernels then require `VkProperty::MetalHalfQuantize`). A kernel that -/// rounds by the device's own form (`rounds_natively`) answers the device's words, which the test -/// prints. +/// them and require no fact). A kernel that rounds by the device's own form (`rounds_natively`: +/// its conversion, or its quantize, whether the profile takes `MetalHalfQuantize` or not) answers +/// the device's words, which the test prints, and no kernel requires +/// `VkProperty::MetalHalfQuantize`. #[test] fn half_quantize_rounds_as_metal_at_the_edge() { let messages = Messages::default(); @@ -969,13 +972,9 @@ fn half_quantize_rounds_as_metal_at_the_edge() { let case = public_case(case_name).unwrap(); let controlled = rounds_under_float_controls(&device, &case); let native = rounds_natively(&device, &case); - // A profile that rounds through the device's conversion holds no quantize to rely on. - let metals = quantizes && !native && !controlled; - assert_eq!( - requires_property(&device, &case, VkProperty::MetalHalfQuantize), - metals, - "{case_name} on {name}: the kernel takes the device's quantize alone exactly \ - where the profile takes the deviation and has not the float controls" + assert!( + !requires_property(&device, &case, VkProperty::MetalHalfQuantize), + "{case_name} on {name}: a kernel's quantize records its note and requires no fact" ); let run = run_case(&device, &case).unwrap(); let metal = metal_row(&case, METAL_ENVIRONMENT); @@ -989,9 +988,9 @@ fn half_quantize_rounds_as_metal_at_the_edge() { .filter(|(_, a, b)| a != b) .collect(); eprintln!( - "half quantize {case_name} on {name} (the device's: {metals}, the device's own \ - rounding: {native}, under float controls: {controlled}): {} of {} edge words \ - differ from Metal", + "half quantize {case_name} on {name} (measured quantize: {quantizes}, the \ + device's own rounding: {native}, under float controls: {controlled}): {} of {} \ + edge words differ from Metal", differ.len(), edge.len() ); @@ -1048,9 +1047,9 @@ const DFL_TRIG_CASE: &str = "precise-trigonometric-functions-at-nan-operands-und /// `DriverDeviation::MetalFloatDenormals` (elsewhere a denormal is the device's own, and the test /// prints how many words differ), the kernels requiring `VkProperty::MetalFloatDenormals` exactly /// where the profile takes the deviation; in the `half` -/// edge cases every word where the kernel rounds as Metal does (under the float controls, or -/// through the quantize, requiring `VkProperty::MetalHalfQuantize`, exactly where the profile takes -/// that one), the device's words printed where it rounds by its own form; +/// edge cases every word where the kernel rounds as Metal does (under the float controls), the +/// device's words printed where it rounds by its own form (its conversion, or its quantize, for +/// which no kernel requires `VkProperty::MetalHalfQuantize`); /// and in [`DFL_TRIG_CASE`] every word whose Metal answer is a NaN (the functions' other words are /// the math library's precision, not their NaNs). A NaN's bits are Metal's only where the profile /// takes `DriverDeviation::MetalCanonicalNans` and Metal answers its canonical NaN; elsewhere the @@ -1120,18 +1119,15 @@ fn owned_float_fixtures_answer_metal() { let case = public_case(case_name).unwrap(); let controlled = rounds_under_float_controls(&device, &case); let native = rounds_natively(&device, &case); - let quantize = quantizes && !native && !controlled; - assert_eq!( - requires_property(&device, &case, VkProperty::MetalHalfQuantize), - quantize, - "{case_name} on {name}: the kernel takes the device's quantize alone exactly \ - where the profile takes the deviation and has not the float controls" + assert!( + !requires_property(&device, &case, VkProperty::MetalHalfQuantize), + "{case_name} on {name}: a kernel's quantize records its note and requires no fact" ); let run = run_case(&device, &case).unwrap(); let metal = metal_row(&case, METAL_ENVIRONMENT); let differ = differing_of(&run.output, &metal, 16, &(0..16).collect::>()); eprintln!( - "owned half edge {case_name} on {name} (the device's quantize: {quantize}, own \ + "owned half edge {case_name} on {name} (measured quantize: {quantizes}, own \ rounding: {native}, under float controls: {controlled}): {} of {} words differ \ from Metal", differ.len(), @@ -1587,12 +1583,13 @@ fn half_denormal(h: u16) -> bool { } /// Every word `hwd_half_reads` writes, for every `half` bit pattern, is held to Metal's but within -/// the notes its stage records. Each read is the module's decode (`lower::arith::narrow::from_bits`): -/// on a profile with `shaderFloat16` the device's widening, exact but for a NaN's bits -/// (`PrecisionNote::NativeNanEncoding`) and, where that widening is not measured to be Metal's +/// the notes its stage records. Each read is the module's decode (`lower::arith::narrow::from_bits`), +/// the device's widening on every profile (its conversion with `shaderFloat16`, `UnpackHalf2x16` +/// without), exact but for a NaN's bits (`PrecisionNote::NativeNanEncoding`) and, where that +/// widening is neither under the 16-bit float controls nor measured to be Metal's /// (`DriverDeviation::MetalHalfArithmetic`, whose fact the module then requires), a denormal, -/// which may be the zero of its sign (`NativeHalfConversion`); elsewhere the integer decode, -/// exact. So every thread whose pattern is neither is held to Metal's, a NaN pattern's word to a +/// which may be the zero of its sign (`NativeHalfConversion`). So every thread whose pattern is +/// neither is held to Metal's, a NaN pattern's word to a /// NaN where the stage records the NaN note, and a denormal's to Metal's or the zero of its sign /// where it records the conversion; the compares are Metal's on every device. The runtime /// announces the notes the stage records, and the test prints how many words of each are the diff --git a/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs b/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs index 0debeaf6b..a33e14462 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/native_maths.rs @@ -226,8 +226,11 @@ fn excess(what: &str, got: f32, want: f64, bound: f64) -> Option { /// Metal answers its canonical `0x7fc00000`), of two numbers correctly rounded, a two-lane `dot` /// within `5 * 2^-24 * sum |a_i * b_i|`, a `mix` within `2^-21 * (|x * (1 - t)| + |y * t|)`, and /// `fast::sqrt` within Vulkan's `1 / InverseSqrt`, 4.5 ulp, and `saturate` (Metal's -/// `clamp(x, +0, 1)`) of a NaN zero and of a number that number clamped exactly. -fn broken(x: &[f32; IN], r: &[f32; OUT]) -> Vec { +/// `clamp(x, +0, 1)`) of a NaN zero and of a number that number clamped exactly. A `half` fused +/// multiply-add is within one `half` ulp, or, where the stage rounds `half` natively +/// (`native_half`: `NativeHalfQuantize` or `NativeHalfConversion`), the zero of its sign below +/// `2^-14`. +fn broken(x: &[f32; IN], r: &[f32; OUT], native_half: bool) -> Vec { let [s, e, l, a, b, c, hx, hy, hz, n] = x.map(f64::from); let products = (c * e).abs() + (s * c).abs(); let blend = (s * (1.0 - hx)).abs() + (c * hx).abs(); @@ -256,7 +259,10 @@ fn broken(x: &[f32; IN], r: &[f32; OUT]) -> Vec { ), excess("a / b", r[4], a / b, 2.5 * ulp(a / b)), excess("fma", r[5], fused, 0.5 * ulp(product) + 0.5 * ulp(fused)), - excess("half fma", r[6], half_fused, half_ulp(half_fused)), + match native_half && half_fused.abs() < 2f64.powi(-14) && r[6] == 0.0 { + true => None, + false => excess("half fma", r[6], half_fused, half_ulp(half_fused)), + }, excess("fmin", r[7], if n.is_nan() { a } else { a.min(n) }, 0.0), excess("fmax", r[8], if n.is_nan() { c } else { c.max(n) }, 0.0), match n.is_nan() { @@ -278,8 +284,8 @@ fn broken(x: &[f32; IN], r: &[f32; OUT]) -> Vec { .collect() } -/// The native kinds of the notes `nm`'s stage records on `device`'s compile device. -fn stage_kinds(device: &Device, bitcode: &[u8]) -> BTreeSet { +/// The notes `nm`'s stage records on `device`'s compile device. +fn stage_notes(device: &Device, bitcode: &[u8]) -> Vec { let compile = device.compile_device(); let budget = Budget::standard(); let library = Library::from_air(bitcode).unwrap(); @@ -293,8 +299,12 @@ fn stage_kinds(device: &Device, bitcode: &[u8]) -> BTreeSet { .compile_compute_pipeline(&descriptor, &budget) .unwrap() .stage; - stage - .precision_notes + stage.precision_notes.to_vec() +} + +/// The native kinds of [`stage_notes`]. +fn stage_kinds(notes: &[PrecisionNote]) -> BTreeSet { + notes .iter() .copied() .filter(|note| NATIVE.contains(note)) @@ -341,7 +351,15 @@ fn native_maths_answers_within_its_recorded_bounds() { /// [`native_maths_answers_within_its_recorded_bounds`] on `device`. fn answers_under(device: &Device, messages: &Messages, bitcode: &[u8]) { let name = device.name().to_string(); - let expected = stage_kinds(device, bitcode); + let notes = stage_notes(device, bitcode); + let expected = stage_kinds(¬es); + // A `half` the device rounds natively may be the zero of its sign below `2^-14`. + let native_half = notes.iter().any(|note| { + matches!( + note, + PrecisionNote::NativeHalfQuantize | PrecisionNote::NativeHalfConversion + ) + }); let compile = device.compile_device(); let takes = |d| compile.profile().takes_driver_deviation(d); let metals = takes(DriverDeviation::MetalFloatFunctions); @@ -431,7 +449,11 @@ fn answers_under(device: &Device, messages: &Messages, bitcode: &[u8]) { .zip(results.as_chunks::().0.iter()) .enumerate() { - failures.extend(broken(x, r).into_iter().map(|f| format!("thread {i}: {f}"))); + failures.extend( + broken(x, r, native_half) + .into_iter() + .map(|f| format!("thread {i}: {f}")), + ); let [_, _, _, a, b, ..] = x.map(f64::from); correctly_rounded += u32::from(r[4] == (a / b) as f32); } @@ -489,6 +511,37 @@ entry: .to_owned() } +/// Whether `got` is within the native half rounding's recorded bound of Metal's `half` of `x`: one +/// unit in the last place of the `half`, 65504 for an infinity, or a zero for an `x` below `2^-14` +/// (the quantize tests the value it rounds, so Metal's `2^-14` from just below may be a zero too). +fn half_within(got: f32, x: f64) -> bool { + let want = metal_half(x); + (want.is_finite() && (f64::from(got) - want).abs() <= half_ulp(want)) + || (want.is_infinite() && f64::from(got) == 65504f64.copysign(want)) + || (x.abs() < 2f64.powi(-14) && got == 0.0) +} + +/// Whether `got` is within the bound ([`half_within`]) of the `half` sum of `a` and `b` each first +/// rounded to `half` within it: the bound is each rounding's, so a sum of operands the device +/// rounded an ulp off, or flushed, is the device's sum of those. +fn half_within_sum(got: f32, a: f64, b: f64) -> bool { + let near = |x: f64| -> Vec { + let want = metal_half(x); + if want.is_infinite() { + return vec![want, 65504f64.copysign(want)]; + } + let ulp = half_ulp(want); + let mut v = vec![want, want - ulp, want + ulp]; + if x.abs() < 2f64.powi(-14) { + v.push(0f64.copysign(x)); + } + v + }; + near(a) + .iter() + .any(|ha| near(b).iter().any(|hb| half_within(got, ha + hb))) +} + /// Metal's `half(float)` of `x`: to nearest even on the `half` grid, half denormals kept, /// infinity from 65520 up. fn metal_half(x: f64) -> f64 { @@ -517,20 +570,19 @@ fn half_operands() -> Vec<[f32; 2]> { } /// On a device whose float controls do not make its conversion to 16 bits Metal's, the stage -/// records `NativeHalfConversion` (or `NativeHalfQuantize` without `shaderFloat16`, which its sum, -/// a bare quantize, records even where the quantize is measured to round as Metal's does) and the -/// pipeline state announces it, and each +/// records `NativeHalfConversion` (or `NativeHalfQuantize` without `shaderFloat16`, whose narrowing +/// and sum are the bare quantize, measured or not) and the pipeline state announces it, and each /// `half` narrowing and sum is within the bound the note records: one unit in the last place of the /// `half`, 65504 where Metal answers infinity from 65520 up on a device that rounds toward zero, -/// and the zero of its sign below `2^-14` on one that flushes 16-bit denormals; or the `float` +/// and the zero of its sign below `2^-14` on one that flushes 16-bit denormals (or whose quantize +/// does), the sum's of operands each so rounded ([`half_within_sum`]); or the `float` /// computation itself, each rounding the device dropped left out: NVIDIA's (RTX 3090) and /// lavapipe's (Mesa 26.2.4 with LLVM 23.1.1; 2526 of 8192 sums Metal's) compilers drop the /// conversion pair, so `half(a)` is `a` and the sum `a + b` rounded to `float` once (or of the /// operands rounded, or rounded itself), exactly. CI's lavapipe (Mesa 26.0.8 with LLVM 21.1.8) /// rounds here (8192 of 8192). A device whose float controls make its conversion Metal's (the /// module declares `RoundingModeRTE`, `DenormPreserve` and `SignedZeroInfNanPreserve` for 16 -/// bits: ANV and RADV), or whose quantize is measured to be Metal's, records neither and answers -/// Metal's exactly. +/// bits: ANV and RADV) records neither and answers Metal's exactly. #[test] fn half_rounding_answers_within_its_recorded_bound() { let bitcode = llvm_assemble_text(&half_kernel()).unwrap(); @@ -543,8 +595,7 @@ fn half_rounding_answers_within_its_recorded_bound() { |device, messages| { let name = format!("{} half rounding", device.name()); // A module rounding under the float controls that make the device's conversion - // Metal's declares `DenormPreserve` for 16 bits, and so requires its property; one - // rounding through a quantize measured to be Metal's requires that fact. + // Metal's declares `DenormPreserve` for 16 bits, and so requires its property. let required = { let library = Library::from_air(&bitcode).unwrap(); let function = FunctionDescriptor::new(library.function("hr").unwrap()); @@ -561,7 +612,6 @@ fn half_rounding_answers_within_its_recorded_bound() { FloatControl::DenormPreserve, FloatWidth::F16, )); - let measured = required.contains(&VkProperty::MetalHalfQuantize); let library = device.new_library_with_air(&bitcode).unwrap(); let function = library.new_function_with_name("hr").unwrap(); let descriptor = ComputePipelineDescriptor::new(StageSource::Function( @@ -575,14 +625,14 @@ fn half_rounding_answers_within_its_recorded_bound() { .filter_map(|kind| kind.precision_note()) .filter(|note| kinds.contains(note)) .collect(); - // A sum by the bare quantize leaves a result below the smallest normal `half` to the - // device, measured quantize or not. - let metal_s = - (measured || controlled) && !announced.contains(&PrecisionNote::NativeHalfQuantize); - eprintln!( - "{name}: measured {measured}, float controls {controlled}; announced \ - {announced:?}" + // A rounding by the bare quantize leaves a result below the smallest normal `half` to + // the device, measured quantize or not: only the float controls answer Metal's. + let metal_s = controlled; + assert!( + !required.contains(&VkProperty::MetalHalfQuantize), + "{name}: a quantize requires no fact" ); + eprintln!("{name}: float controls {controlled}; announced {announced:?}"); assert_eq!(announced.len(), usize::from(!metal_s), "{name}"); let operands = half_operands(); let bytes: Vec = operands @@ -634,11 +684,12 @@ fn half_rounding_answers_within_its_recorded_bound() { ] { let same = got.to_bits() == (want as f32).to_bits(); exact += u32::from(same); - let within = same - || (want.is_finite() && (f64::from(got) - want).abs() <= half_ulp(want)) - || (want.is_infinite() && f64::from(got) == 65504f64.copysign(want)) - || (want.abs() < 2f64.powi(-14) && got == 0.0) - || unrounded.iter().any(|u| u.to_bits() == got.to_bits()); + let rounded = match what { + "half(a)" => half_within(got, f64::from(a)), + _ => half_within_sum(got, f64::from(a), f64::from(b)), + }; + let within = + same || rounded || unrounded.iter().any(|u| u.to_bits() == got.to_bits()); if !((!metal_s && within) || same) { failures.push(format!( "thread {i}: {what} of {a:e}, {b:e}: {got:e} for Metal's {want:e}" diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 56efbacdf..3ac182c09 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 = 1888; +pub const SEMANTICS_VERSION: u32 = 1889; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/device/requirements.rs b/crates/metal2vulkan/src/device/requirements.rs index 10bba1840..26128cfc9 100644 --- a/crates/metal2vulkan/src/device/requirements.rs +++ b/crates/metal2vulkan/src/device/requirements.rs @@ -655,9 +655,10 @@ pub enum VkProperty { /// The device's `OpQuantizeToF16` rounds as Metal's conversion to `half` does, to nearest /// even below 65520 (the driver's measured deviation /// [`DriverDeviation::MetalHalfQuantize`](crate::error::DriverDeviation::MetalHalfQuantize)). - /// No Vulkan query reports it: the quantize's rounding mode is the device's. A module that - /// rounds to `half` through the quantize requires it; without it, the module records - /// `PrecisionNote::NativeHalfQuantize`. + /// No Vulkan query reports it: the quantize's rounding mode is the device's. No module + /// requires it: a module that rounds to `half` through the quantize records + /// `PrecisionNote::NativeHalfQuantize` on every profile, its result below the smallest normal + /// `half` the device's. MetalHalfQuantize, /// The device reads a center-sampled varying of a multisampled pipeline at the pixel center /// in every fragment invocation, a sample-rate one's included, as Metal does (the driver's diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index c0c9bc7be..46bd39fec 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -616,8 +616,9 @@ pub enum DriverDeviation { /// as Metal's conversion to `half` does, so that a value from 65504 up to 65520 is 65504, not /// infinity (`VkProperty::MetalHalfQuantize`). Vulkan leaves the quantize's rounding mode to /// the device. A module that rounds to `half` through the quantize (`QuantizeForm::Device`, a - /// profile without `shaderFloat16`) requires the property where the profile takes it; - /// unmeasured, it records `PrecisionNote::NativeHalfQuantize`. + /// profile without `shaderFloat16`) records `PrecisionNote::NativeHalfQuantize` whether the + /// profile takes it or not, and requires no property: the measurement covers the quantize's + /// normal results, and its result below the smallest normal `half` is the device's. MetalHalfQuantize, /// The device reads a center-sampled varying (a smooth input decorated neither `Centroid` /// nor `Sample`) of a multisampled pipeline at the pixel center in every fragment diff --git a/crates/metal2vulkan/src/lower/arith/math.rs b/crates/metal2vulkan/src/lower/arith/math.rs index 7a74c5427..0ba875fc3 100644 --- a/crates/metal2vulkan/src/lower/arith/math.rs +++ b/crates/metal2vulkan/src/lower/arith/math.rs @@ -1328,9 +1328,6 @@ pub fn float_fn( // Rounded per step below. F::Mix | F::MulAdd | F::Fract | F::FastFract { .. } | F::FlaggedFract => r, F::Dot => narrow::round(fb, f.scalar_form(), r)?, - // The square root of a narrow value is a zero or at least `2^-12`: the device's rounding - // alone rounds it as Metal does. - F::Sqrt => narrow::device_round(fb, f, r)?, F::Fmod => { let r = narrow::round(fb, f, r)?; half_fmod_zero(fb, f, arg(args, 0)?, r)? @@ -1621,28 +1618,26 @@ fn float_fn_core( F::Mix => { // The blend `x * (1 - t) + y * t` on `bfloat` and `double`, which Metal's fused form is // not measured on: its multiplies and add carry the call's contraction, and each step - // rounds to a narrow format. `1 - t` and the final sum add two values of the format, - // which take the device's rounding alone (`narrow::device_round`). + // rounds to a narrow format by the device's rounding (`narrow::round`). let (y, t) = (arg(args, 1)?, arg(args, 2)?); let one = fsplat(fb, f, 1.0)?; let w = fb.binary_with(BinOp::FSub, one, t, contract)?; - let w = narrow::device_round(fb, f, w)?; + let w = narrow::round(fb, f, w)?; let p = fb.binary_with(BinOp::FMul, a, w, contract)?; let p = narrow::round(fb, f, p)?; let q = fb.binary_with(BinOp::FMul, y, t, contract)?; let q = narrow::round(fb, f, q)?; let r = fb.binary_with(BinOp::FAdd, p, q, contract)?; - narrow::device_round(fb, f, r) + narrow::round(fb, f, r) } F::Ldexp => ldexp(fb, f, a, arg(args, 1)?), F::CopySign => copysign(fb, f, a, arg(args, 1)?), F::MulAdd => { - // A narrow form takes the unfused choice, each step rounded once by the device (the - // sum adds two values of the format, `narrow::device_round`). + // A narrow form takes the unfused choice, each step rounded once by the device. let p = bin(fb, BinOp::FMul, a, arg(args, 1)?)?; let p = narrow::round(fb, f, p)?; let r = bin(fb, BinOp::FAdd, p, arg(args, 2)?)?; - narrow::device_round(fb, f, r) + narrow::round(fb, f, r) } F::Sqrt => g1(fb, GlslOp::Sqrt), F::Fma if f.float_fmt() == Some(FloatFmt::BFloat) => { @@ -2194,11 +2189,10 @@ fn metal_fract( bounded: bool, infinite_nan: bool, ) -> BResult { - // `floor(x)` of a narrow value is a value of the format: the difference takes the device's - // rounding alone, as a sum does. + // The difference of a narrow value and its floor takes the device's rounding. let fl = glsl(fb, GlslOp::Floor, &[x])?; let d = bin(fb, BinOp::FSub, x, fl)?; - let d = narrow::device_round(fb, f, d)?; + let d = narrow::round(fb, f, d)?; let r = if bounded { let below_one = splat(fb, f, below_one_bits(f))?; glsl(fb, GlslOp::NMin, &[d, below_one])? diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index 89eb79438..7ae0e6d4c 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -789,10 +789,8 @@ pub struct ArithPlan { /// the profile ([`narrow::quantize_form`]): the device's conversion to 16 bits and its /// widening under the float controls that make it Metal's, else that conversion as it is /// where the profile has `shaderFloat16` (noted `NativeHalfConversion`), else the device's - /// `OpQuantizeToF16` (noted `NativeHalfQuantize`, but where it is measured to round as Metal - /// does, `DriverDeviation::MetalHalfQuantize`: a module that quantizes then requires - /// `VkProperty::MetalHalfQuantize`; a sum or difference the bare quantize, noted - /// `NativeHalfQuantize` either way, `narrow::device_round`). + /// `OpQuantizeToF16` alone (noted `NativeHalfQuantize` on every such profile: a result below + /// the smallest normal half may be a zero). pub quantize: QuantizeForm, /// Whether [`ArithPlan::quantize`] is the device's own rounding (native half rounding, /// [`narrow::native_rounding`]), decided with it by [`finish`]. @@ -905,8 +903,7 @@ pub const FOLDED: &str = "arith.float.folded"; pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { cx.families.arith.wide = legal::holds_wide(cx.profile); cx.families.arith.quantize = narrow::quantize_form(cx.profile); - cx.families.arith.native_half = - narrow::native_rounding(cx.profile, cx.families.arith.quantize).is_some(); + cx.families.arith.native_half = narrow::native_rounding(cx.families.arith.quantize).is_some(); // Under the float controls a `half`'s NaN is the device's conversion's. cx.families.arith.native_half_nans = cx.families.arith.quantize == QuantizeForm::Controlled; cx.families.arith.mask = if cx diff --git a/crates/metal2vulkan/src/lower/arith/narrow.rs b/crates/metal2vulkan/src/lower/arith/narrow.rs index c3fbdf291..c6ae9466b 100644 --- a/crates/metal2vulkan/src/lower/arith/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/narrow.rs @@ -11,15 +11,11 @@ //! `DriverWorkaround::HalfConversionPairFolded`), with no fact and no note. Elsewhere, where the //! profile has `shaderFloat16`, it is the device's conversion to 16 bits and its widening //! ([`QuantizeForm::Converted`]), recording `PrecisionNote::NativeHalfConversion`; without it, the -//! device's `OpQuantizeToF16`, a result it flushes to zero rounded to the half denormal grid -//! ([`QuantizeForm::Device`]), recording `PrecisionNote::NativeHalfQuantize` unless the device's -//! quantize is measured to round as Metal's conversion does (`DriverDeviation::MetalHalfQuantize`: -//! the module then requires the fact). A sum or difference, and the results like it, take the -//! device's rounding alone ([`device_round`]): in [`QuantizeForm::Device`] the quantize with no -//! denormal arm, whose result below the smallest normal half is the device's (noted -//! `NativeHalfQuantize`, [`flushes_below_normal`]); a texel's `half` takes [`round`] and keeps the -//! NaN the device decoded ([`round_texel`]) unless the profile leaves NaN bits to the device under -//! native half rounding or the float controls; `bfloat` rounds through an +//! device's `OpQuantizeToF16` alone ([`QuantizeForm::Device`]), whose result below the smallest +//! normal half may be a zero, recording `PrecisionNote::NativeHalfQuantize` on every such profile +//! ([`quantizes`]); a texel's `half` takes [`round`] and keeps the NaN the device decoded +//! ([`round_texel`]) unless the profile leaves NaN bits to the device under native half rounding +//! or the float controls; `bfloat` rounds through an //! exact integer round-to-nearest-even of the `f32` bits. Where the device's 16-bit `+ - *`, kept //! apart, is Metal's `half` arithmetic and the profile has `shaderFloat16`, a `half` `+ - *` is //! that instruction between exact conversions instead, with no rounding here (`ops::f16_binary`): @@ -31,13 +27,15 @@ //! not, so it is the device's 16-bit one where that is Metal's, and else the device's `f32` one //! rounded to `half`, noted (`super::fma`), and a `bfloat` one is corrected ([`bf16_fma`]). //! -//! A `half` read from its bits is the device's widening of them wherever the module can hold a -//! 16-bit float ([`from_bits`], [`device_from_bits`]): exact but for a NaN's bits and, on a device -//! that may flush 16-bit denormals, a denormal, each recorded ([`widens_bits`]). Every other -//! crossing is exact: [`to_bits`], the integer decode of a `half` without `shaderFloat16` and a -//! `bfloat`'s move between a value and its format bits with integer sequences and, for a half -//! denormal, one exact scaling by `2^±24` between an integer and a normal `f32` (denormals, -//! infinities, and NaN payloads included); an integer converts to `half` through `f32` without +//! A `half` read from its bits is the device's widening of them on every profile ([`from_bits`]): +//! the bits read as a 16-bit float and converted where the module can hold one +//! ([`device_from_bits`]), else `GLSL.std.450 UnpackHalf2x16` of the bits as the low half of a +//! word ([`unpacked_from_bits`]), which needs no 16-bit type: the device's value of every `half` +//! but a NaN's bits and, on a device that may flush 16-bit denormals, a denormal, each recorded +//! ([`widens_bits`]). Every other crossing is exact: [`to_bits`] and a `bfloat`'s move between a +//! value and its format bits with integer sequences and, for a half denormal, one exact scaling by +//! `2^24` of a normal `f32` to an integer (denormals, infinities, and NaN payloads included); an +//! integer converts to `half` through `f32` without //! double rounding (any integer the `f32` step rounds is at least `2^24`, far above the largest //! half) and rounds by integer arithmetic, not `OpQuantizeToF16`, around a driver's defect //! ([`round_integer`]), an integer converts to `bfloat` through a round-to-odd `f32` @@ -48,7 +46,7 @@ use crate::budget::Meter; use crate::device::profile::{DriverWorkaround, Independence}; use crate::device::DeviceProfile; -use crate::error::{DriverDeviation, Error}; +use crate::error::Error; use crate::lower::arith::legal::{FloatFmt, Form, Held}; use crate::lower::arith::ops::{fsplat, splat, ty}; use crate::pipeline::artifact::PrecisionNote; @@ -79,9 +77,9 @@ pub fn round_words(f: Form) -> u32 { } /// An upper estimate of the SPIR-V words of one [`round`] on form `f` in quantize form `q`: for -/// `half`, the device's quantize with its denormal arm or its conversion, at most seven -/// instructions and their constants, the bound of 64 words and 4 per lane, in every form; a dozen -/// instructions for `bfloat`. +/// `half`, the device's quantize or its conversion and widening, at most two instructions with +/// their types and decorations, within the bound of 64 words and 4 per lane, in every form; a +/// dozen instructions for `bfloat`. pub fn round_words_in(q: QuantizeForm, f: Form) -> u32 { let lanes = u32::from(f.lanes); match (f.float_fmt(), q) { @@ -98,9 +96,11 @@ pub fn round_words_in(q: QuantizeForm, f: Form) -> u32 { /// `double` forms. /// /// `half`: the device's rounding to `half`, in the module's [`QuantizeForm`]. -/// [`QuantizeForm::Device`]: `q`, `OpQuantizeToF16(x)`, is the rounded value wherever it is not a -/// zero. It is a zero exactly when `|x|` rounds below the smallest normal half (or `x` is a zero), -/// and then the result is [`scaled`]'s. A NaN compares unequal to zero and keeps `q`. +/// [`QuantizeForm::Device`]: the device's `OpQuantizeToF16(x)` alone. The SPIR-V specification lets +/// the quantize answer a zero for a magnitude too small for a normal half, and a device may (NIR's +/// `fquantize2f16` flushes every one), where Metal answers the half denormal; Vulkan leaves its +/// rounding mode to the device. The module records `PrecisionNote::NativeHalfQuantize` +/// ([`quantizes`]). /// [`QuantizeForm::Converted`]: [`converted`]'s alone, the device's conversion. /// [`QuantizeForm::Controlled`]: [`controlled`]'s alone, Metal's value by the Vulkan spec. pub fn round(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { @@ -110,13 +110,7 @@ pub fn round(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult match fb.module().quantize_form() { QuantizeForm::Converted => converted(fb, wide, x), QuantizeForm::Controlled => controlled(fb, wide, x), - QuantizeForm::Device => { - let q = fb.unary(UnOp::QuantizeToF16, x)?; - let zero = fsplat(fb, wide, 0.0)?; - let flushed = bin(fb, BinOp::FOrdEqual, q, zero)?; - let d = scaled(fb, wide, x)?; - fb.select(flushed, d, q) - } + QuantizeForm::Device => fb.unary(UnOp::QuantizeToF16, x), } } Held::Float(FloatFmt::BFloat) => { @@ -147,44 +141,27 @@ pub fn quantize_form(p: &DeviceProfile) -> QuantizeForm { } } -/// The precision note of a module of profile `p` whose `half` roundings take `form`, the device's -/// own rounding: `NativeHalfConversion` for [`QuantizeForm::Converted`], `NativeHalfQuantize` for -/// [`QuantizeForm::Device`] where the profile does not take `DriverDeviation::MetalHalfQuantize`. -/// `None` where the form is Metal's: the measured quantize, whose fact the module then requires, -/// and the float controls' conversion. -pub fn native_rounding(p: &DeviceProfile, form: QuantizeForm) -> Option { +/// The precision note of a module whose `half` roundings take `form`, the device's own rounding: +/// `NativeHalfConversion` for [`QuantizeForm::Converted`], `NativeHalfQuantize` for +/// [`QuantizeForm::Device`] (a quantize's result below the smallest normal half is the device's on +/// every profile, which no measurement covers). `None` for the float controls' conversion, Metal's +/// by the Vulkan spec. +pub fn native_rounding(form: QuantizeForm) -> Option { match form { QuantizeForm::Converted => Some(PrecisionNote::NativeHalfConversion), - QuantizeForm::Device if !p.takes_driver_deviation(DriverDeviation::MetalHalfQuantize) => { - Some(PrecisionNote::NativeHalfQuantize) - } - _ => None, + QuantizeForm::Device => Some(PrecisionNote::NativeHalfQuantize), + QuantizeForm::Controlled => None, } } -/// `x` (`f32` lanes of form `wide`) rounded to the half denormal grid, `RoundEven(x · 2^24) · -/// 2^-24`: the half of an `|x|` below the smallest normal half. It is exact in every rounding mode: -/// both products scale by a power of two into the normal `f32` range, and `RoundEven` is exact. It -/// rounds to nearest even on the grid (`2^-24`), keeps the sign of a zero, and gives the smallest -/// normal half where `x` rounds up to it. (An `f32` denormal `x` may be flushed by the device's -/// multiply; its half is a signed zero either way.) -fn scaled(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult { - let up = fsplat(fb, wide, 16_777_216.0)?; - let down = fsplat(fb, wide, 1.0 / 16_777_216.0)?; - let s = bin(fb, BinOp::FMul, x, up)?; - let k = fb.glsl(GlslOp::RoundEven, &[s])?; - bin(fb, BinOp::FMul, k, down) -} - /// `x` (`f32` lanes of form `wide`) rounded to `half` by the device's conversion to 16 bits, /// `OpFConvert`, and widened back ([`QuantizeForm::Converted`]), recorded as -/// `PrecisionNote::NativeHalfConversion`: three instructions where the quantize with its denormal -/// arm takes six to twelve. The device's compiler may fold the conversion into the instruction -/// computing `x`: Metal's compiler then rounds toward zero (`a1_half_tanh_regimes`, case 27353187: -/// 1,204 of its 16,384 halves one ulp toward zero on MoltenVK). NVIDIA's compiler (RTX 3090) drops -/// the pair, and so does lavapipe's where measured, so there the value is not rounded at all (the -/// note's stated bound), and the store's bits saturate what passes `half`'s range -/// ([`f32_bits_to_half_bits`]). +/// `PrecisionNote::NativeHalfConversion`. The device's compiler may fold the conversion into the +/// instruction computing `x`: Metal's compiler then rounds toward zero (`a1_half_tanh_regimes`, +/// case 27353187: 1,204 of its 16,384 halves one ulp toward zero on MoltenVK). NVIDIA's compiler +/// (RTX 3090) drops the pair, and so does lavapipe's where measured, so there the value is not +/// rounded at all (the note's stated bound), and the store's bits saturate what passes `half`'s +/// range ([`f32_bits_to_half_bits`]). fn converted(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult { let e = fb.module().ty(Type::Float { width: 16 })?; let h = match wide.lanes { @@ -201,8 +178,7 @@ fn converted(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult, wide: Form, x: Value) -> BResult { let e = fb.module().ty(Type::Float { width: 16 })?; let h = match wide.lanes { @@ -338,9 +314,11 @@ pub fn round_texel_words(f: Form) -> u32 { /// Texel value `x` (`f32` lanes of form `f`: the device's decode of an image texel) as a texture /// access hands it to the function in `f`'s narrow format. A `half` is [`round`]ed, which keeps -/// half subnormals on their grid to nearest even, so a half-float texel, which the device decodes -/// to its exact `f32` value (a half subnormal is a normal `f32`), keeps its value: every subnormal, -/// both zeros, both infinities, and `65504`. A NaN is the device's decode itself, since +/// half subnormals on their grid to nearest even where the module converts (a device's quantize, +/// [`QuantizeForm::Device`], may answer one as its signed zero, +/// `PrecisionNote::NativeHalfQuantize`), so a half-float texel, which the device decodes to its +/// exact `f32` value (a half subnormal is a normal `f32`), keeps its value: every subnormal, both +/// zeros, both infinities, and `65504`. A NaN is the device's decode itself, since /// `OpQuantizeToF16` may return another NaN; it is told by its bits, so the test holds whatever /// float modes the device compiles the module under. Under native half rounding /// ([`native_rounding`]) the rounding's own NaN stands instead: the note the module records bounds @@ -367,110 +345,6 @@ pub fn round_texel(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult, f: Form, x: Value) -> BResult { - match f.held { - Held::Float(FloatFmt::Half) => { - let wide = f.with(Held::Float(FloatFmt::F32)); - match fb.module().quantize_form() { - QuantizeForm::Converted => converted(fb, wide, x), - QuantizeForm::Controlled => controlled(fb, wide, x), - QuantizeForm::Device => fb.unary(UnOp::QuantizeToF16, x), - } - } - _ => round(fb, f, x), - } -} - -/// Whether module `m` rounds to `half` by the device's `OpQuantizeToF16` with no denormal arm -/// ([`device_round`] in [`QuantizeForm::Device`]): a quantize that no select of [`round`]'s arm -/// replaces where it is a zero (the select's false operand the quantize, its condition the -/// quantize's `OpFOrdEqual`). Such a module records `PrecisionNote::NativeHalfQuantize` on every -/// profile: a result below the smallest normal half is the device's, which no measurement covers -/// (`DriverDeviation::MetalHalfQuantize` measures the quantize's rounding of normal results). -/// Three passes over the instructions, with one bit per value of the module and one pair per -/// quantize's test charged to `meter` while they run. -pub fn flushes_below_normal(m: &TypedModule, meter: &mut Meter) -> Result { - let insts = || m.blocks().iter().flat_map(|b| &b.insts); - let words = m.values().len().div_ceil(64); - meter.charge(16 * words)?; - let mut quantized = vec![0u64; words]; - let mut armed = 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) - }; - let mut any = false; - for n in insts() { - if let ( - Inst::Unary { - op: UnOp::QuantizeToF16, - .. - }, - Some(r), - ) = (&n.inst, n.result) - { - set(&mut quantized, r); - any = true; - } - } - let mut tests: Vec<(Value, Value)> = Vec::new(); - let r = (|| -> Result { - if !any { - return Ok(false); - } - // Each quantize's equality tests, by the test's result. - for n in insts() { - if let ( - Inst::Binary { - op: BinOp::FOrdEqual, - a, - .. - }, - Some(r), - ) = (&n.inst, n.result) - { - if has(&quantized, *a) { - meter.charge(std::mem::size_of::<(Value, Value)>())?; - tests.push((r, *a)); - } - } - } - tests.sort_unstable_by_key(|(t, _)| t.index()); - for n in insts() { - if let Inst::Select { cond, f, .. } = &n.inst { - let i = tests.binary_search_by_key(&cond.index(), |(t, _)| t.index()); - if i.is_ok_and(|i| tests.get(i).is_some_and(|(_, q)| q == f)) { - set(&mut armed, *f); - } - } - } - Ok(quantized.iter().zip(&armed).any(|(q, a)| q & !a != 0)) - })(); - meter.release(std::mem::size_of_val(tests.as_slice())); - drop((quantized, armed, tests)); - meter.release(16 * words); - r -} - /// An upper estimate of the SPIR-V words of one [`round_integer`] on form `f`: twelve instructions /// and eight constants for `half` (a vector's constants carry their lanes); [`round`]'s for every /// other form. @@ -529,11 +403,11 @@ pub fn round_integer(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult } } -/// Whether module `m` rounds to `half` through `OpQuantizeToF16` ([`round`], [`device_round`], -/// [`round_texel`] in [`QuantizeForm::Device`]): the module then records -/// `PrecisionNote::NativeHalfQuantize` ([`native_rounding`], [`flushes_below_normal`]) or, where -/// the device's quantize is measured to round as Metal's and every quantize keeps its denormal arm, -/// requires `VkProperty::MetalHalfQuantize`. +/// Whether module `m` rounds to `half` through `OpQuantizeToF16` ([`round`] and [`round_texel`] +/// in [`QuantizeForm::Device`]): the module then records `PrecisionNote::NativeHalfQuantize` +/// ([`native_rounding`]) on every profile, whose quantize's result below the smallest normal half +/// is the device's (`DriverDeviation::MetalHalfQuantize` measures its rounding of normal results +/// alone). pub fn quantizes(m: &TypedModule) -> bool { m.blocks().iter().any(|b| { b.insts.iter().any(|n| { @@ -884,9 +758,9 @@ fn encode(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { } /// The format bits of `x` (form `f`) when `x` is a plain constant every lane of which is a -/// value of the format, computed at translation time by the transliterations -/// [`half_bits_of_f32`] and [`f32_of_half_bits`] of the device sequences: `None` for anything -/// else (the device sequence then runs). A `null` is zero bits. +/// value of the format, computed at translation time by [`half_bits_of_f32`], the transliteration +/// of the device sequence, and checked by [`f32_of_half_bits`]: `None` for anything else (the +/// device sequence then runs). A `null` is zero bits. pub fn constant_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult> { match constant_lanes(fb, f, x)? { Some(k) => materialize(fb, f, &k).map(Some), @@ -975,8 +849,9 @@ pub fn half_bits_of_f32(b: u32) -> u32 { sign | r } -/// The host transliteration of `half_bits_to_f32_bits` on one lane: the `f32` bits of the half -/// with bits `h` (its low 16 bits). +/// The `f32` bits of the exact value of the half with bits `h` (its low 16 bits), on the host: a +/// half's exponent and fraction moved up and rebiased, a denormal's integer times `2^-24`, an +/// infinity's or NaN's payload moved up under the all-ones exponent. pub fn f32_of_half_bits(h: u32) -> u32 { let em = h & 0x7FFF; let bias = if em >= 0x7C00 { 224 << 23 } else { 112 << 23 }; @@ -1055,30 +930,26 @@ fn f32_bits_to_half_bits(fb: &mut FunctionBuilder<'_>, u: Form, b: Value) -> BRe /// The narrow value (an `f32` of form `f`) of format bits `h`, the low 16 bits of each `u32` /// lane; the bits above them are ignored, so a load need not clear them. /// -/// A `half` is the device's widening of its bits ([`device_from_bits`]) wherever the module can -/// hold a 16-bit float: every [`QuantizeForm`] but [`QuantizeForm::Device`], which only a profile -/// without `shaderFloat16` takes. There it is decoded in integer arithmetic, exact for every bit -/// pattern, NaN payloads included, as a `bfloat` is everywhere: such a module declares no 16-bit -/// float to read the bits as. +/// A `half` is the device's widening of its bits on every profile: wherever the module can hold a +/// 16-bit float (every [`QuantizeForm`] but [`QuantizeForm::Device`]) the bits read as one and +/// converted ([`device_from_bits`]), and in [`QuantizeForm::Device`], which only a profile without +/// `shaderFloat16` takes, `GLSL.std.450 UnpackHalf2x16` of each lane's word +/// ([`unpacked_from_bits`]), which needs no 16-bit type. A `bfloat` is its bits moved up, exact +/// for every bit pattern. /// /// The result's bits are noted: a later [`to_bits`] of the value, wherever the value is, returns -/// `h` (masked to its low 16 bits) without converting back, so a `half` stored unchanged keeps its -/// bits whatever the widening made of them. The integer decode and [`to_bits`]' sequence are -/// inverse on every bit pattern. +/// `h` (masked to its low 16 bits) without converting back, so a narrow value stored unchanged +/// keeps its bits whatever the widening made of them. pub fn from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult { - let x = match f.held { - Held::Float(FloatFmt::Half) if fb.module().quantize_form() != QuantizeForm::Device => { + let x = match (f.held, fb.module().quantize_form()) { + (Held::Float(FloatFmt::Half), QuantizeForm::Device) => unpacked_from_bits(fb, f, h)?, + (Held::Float(FloatFmt::Half), QuantizeForm::Converted | QuantizeForm::Controlled) => { device_from_bits(fb, f, h)? } _ => { let u = u32_form(f); - let b = match f.held { - Held::Float(FloatFmt::BFloat) => { - let k16 = splat(fb, u, 16)?; - bin(fb, BinOp::ShiftLeftLogical, h, k16)? - } - _ => half_bits_to_f32_bits(fb, u, h)?, - }; + let k16 = splat(fb, u, 16)?; + let b = bin(fb, BinOp::ShiftLeftLogical, h, k16)?; let ft = ty(fb, f)?; fb.convert(ConvOp::Bitcast, b, ft)? } @@ -1093,13 +964,15 @@ pub fn from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult, f: Form, @@ -1109,22 +982,36 @@ pub fn from_word_halves( ) -> BResult { let lanes = u32::from(f.lanes.max(1)); let n = (first + lanes).div_ceil(2) as usize; - let device = matches!(f.held, Held::Float(FloatFmt::Half)) - && fb.module().quantize_form() != QuantizeForm::Device - && first < 2 - && n <= 2; - let Some(words) = words.get(..n).filter(|_| device) else { + let fits = matches!(f.held, Held::Float(FloatFmt::Half)) && first < 2 && n <= 2; + let Some(words) = words.get(..n).filter(|_| fits) else { return from_bits(fb, f, h); }; + let x = match fb.module().quantize_form() { + QuantizeForm::Device => unpacked_words(fb, f, words, first)?, + QuantizeForm::Converted | QuantizeForm::Controlled => converted_words(fb, f, words, first)?, + }; + let all = u32::MAX >> (32 - lanes.clamp(1, 32)); + fb.note_bits(NarrowFmt::Half, x, h, all, true); + Ok(x) +} + +/// [`from_word_halves`]' widening where the module can hold a 16-bit float: `words` (one or two) +/// read as 16-bit floats, lanes `first..first + f.lanes` taken from them and converted to 32 bits; +/// a lone `half` of a 16-bit unit's zero extension, that unit read as a 16-bit float. +fn converted_words( + fb: &mut FunctionBuilder<'_>, + f: Form, + words: &[Value], + first: u32, +) -> BResult { + let lanes = u32::from(f.lanes.max(1)); let e = fb.module().ty(Type::Float { width: 16 })?; let wide = ty(fb, f)?; // A lone `half` loaded as a 16-bit unit: the unit itself read as a 16-bit float. if let ([w], 0, 1) = (words, first, lanes) { if let Some(unit) = fb.widened16_of(*w) { let x = fb.convert(ConvOp::Bitcast, unit, e)?; - let x = fb.convert(ConvOp::FConvert, x, wide)?; - fb.note_bits(NarrowFmt::Half, x, h, 1, true); - return Ok(x); + return fb.convert(ConvOp::FConvert, x, wide); } } let packed = match words { @@ -1134,7 +1021,7 @@ pub fn from_word_halves( fb.composite_construct(uv, words)? } }; - let comps = 2 * n as u32; + let comps = 2 * words.len() as u32; let halves = fb.module().ty(Type::Vector { elem: e, len: comps as u8, @@ -1148,10 +1035,63 @@ pub fn from_word_halves( fb.vector_shuffle(p, p, &picked)? } }; - let x = fb.convert(ConvOp::FConvert, taken, wide)?; - let all = u32::MAX >> (32 - lanes.clamp(1, 32)); - fb.note_bits(NarrowFmt::Half, x, h, all, true); - Ok(x) + fb.convert(ConvOp::FConvert, taken, wide) +} + +/// [`from_word_halves`]' widening in [`QuantizeForm::Device`]: each of `words` (one or two) +/// unpacked by `UnpackHalf2x16` into the pair of `f32`s its halves widen to (its low 16 bits the +/// first), and lanes `first..first + f.lanes` taken from the pairs. +fn unpacked_words( + fb: &mut FunctionBuilder<'_>, + f: Form, + words: &[Value], + first: u32, +) -> BResult { + let lanes = u32::from(f.lanes.max(1)); + let mut pairs = Vec::with_capacity(2); + for w in words { + pairs.push(fb.glsl(GlslOp::UnpackHalf2x16, &[*w])?); + } + match (pairs.as_slice(), first, lanes) { + ([p], 0, 2) => Ok(*p), + ([p, ..], _, 1) => fb.composite_extract(*p, &[first]), + ([a, b], _, _) => { + let picked: Vec = (first..first + lanes).collect(); + fb.vector_shuffle(*a, *b, &picked) + } + _ => Err(BuildError::Type(TypeRule::VectorShape)), + } +} + +/// The `half` values of bits `h` (the low 16 bits of each `u32` lane of form [`u32_form`]`(f)`) +/// widened by `GLSL.std.450 UnpackHalf2x16` ([`QuantizeForm::Device`], a profile without +/// `shaderFloat16`): each lane's word unpacked and its first component taken, whose value the +/// unpack reads from the word's low 16 bits, the bits above them ignored. Two instructions for a +/// lane, and a lane extract and the vector's construct for a vector. +/// +/// It needs no 16-bit type: the instruction is core to every Vulkan device. Vulkan gives it no +/// precision of its own ("implementation-defined"); every `half` is an `f32`, and the device's +/// widening is its answer. A NaN widens to a NaN whose bits are the device's, where Metal widens +/// every `half` NaN to `0x7FC00000` and moves one unwidened with its bits; the module records +/// `PrecisionNote::NativeNanEncoding` ([`widens_bits`]). A denormal "obtained via unpacking an +/// integer into a vector of values with smaller bit width" may be flushed to the zero of its sign +/// without `DenormPreserve` for 16 bits, which such a module does not declare, within +/// `PrecisionNote::NativeHalfConversion`'s bound, which the module records. +fn unpacked_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult { + let lane = |fb: &mut FunctionBuilder<'_>, word: Value| -> BResult { + let pair = fb.glsl(GlslOp::UnpackHalf2x16, &[word])?; + fb.composite_extract(pair, &[0]) + }; + if f.lanes <= 1 { + return lane(fb, h); + } + let mut lanes = Vec::with_capacity(usize::from(f.lanes)); + for i in 0..u32::from(f.lanes) { + let word = fb.composite_extract(h, &[i])?; + lanes.push(lane(fb, word)?); + } + let wide = ty(fb, f)?; + fb.composite_construct(wide, &lanes) } /// The `half` values of bits `h` (the low 16 bits of each `u32` lane of form [`u32_form`]`(f)`) @@ -1159,7 +1099,7 @@ pub fn from_word_halves( /// four (`OpBitcast` maps a word's lower-ordered bits to the lower-numbered component, so each /// lane's half is an even component), those components gathered, and the gathered 16-bit floats /// converted to 32 bits, one `OpFConvert`. Three instructions for one or two lanes, six for three -/// or four, where the integer decode takes about twenty. +/// or four. /// /// Every `half` but a NaN and a denormal widens to its exact value, by the Vulkan spec /// ("Precision and Operation of SPIR-V Instructions"): a conversion is "Correctly rounded", and @@ -1215,16 +1155,30 @@ fn device_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult< fb.convert(ConvOp::FConvert, gathered, wide) } -/// Whether module `m` widens a `half` from its bits by [`device_from_bits`] or -/// [`from_word_halves`]: 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. 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 (`DriverDeviation::MetalHalfArithmetic`) or the -/// device's (`PrecisionNote::NativeHalfConversion`). The device's 16-bit arithmetic and conversions widen what they compute, which no bitcast -/// gives. Three passes over the instructions, with two bits per value of the module charged to -/// `meter` while they run. +/// Whether module `m` widens a `half` from its bits by the device ([`from_bits`], +/// [`from_word_halves`]): a `GLSL.std.450 UnpackHalf2x16` ([`unpacked_from_bits`], in +/// [`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 +/// (`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. 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); + } // 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) { @@ -1315,40 +1269,6 @@ pub fn computes_in_16_bits(m: &TypedModule) -> bool { }) } -/// Half bits `h` (the low 16 bits of each lane) to the `f32` bits of the same value: the -/// magnitude's bits moved up by 13 and rebiased by `112 << 23`, or, for an infinity or NaN, by `224 -/// << 23`, which gives the `f32`'s all-ones exponent with the payload moved up (the half exponent -/// 31 moved up is `0x0F80_0000`); a denormal (or zero) `m · 2^-24` computed as the conversion of -/// the integer `m` times `2^-24`, which is exact: `m` is below `2^10`, and the product is a zero or -/// at least `2^-24`, a normal `f32`, so no device flushes it. -fn half_bits_to_f32_bits(fb: &mut FunctionBuilder<'_>, u: Form, h: Value) -> BResult { - let c = |fb: &mut FunctionBuilder<'_>, k: u64| splat(fb, u, k); - let mag_mask = c(fb, 0x7FFF)?; - let em = bin(fb, BinOp::BitwiseAnd, h, mag_mask)?; - let k13 = c(fb, 13)?; - let t = bin(fb, BinOp::ShiftLeftLogical, em, k13)?; - let exp_ones = c(fb, 0x7C00)?; - let is_special = bin(fb, BinOp::UGreaterThanEqual, em, exp_ones)?; - let (special_bias, bias) = (c(fb, 224 << 23)?, c(fb, 112 << 23)?); - let bias = fb.select(is_special, special_bias, bias)?; - let normal = bin(fb, BinOp::IAdd, t, bias)?; - let wide = u.with(Held::Float(FloatFmt::F32)); - let ft = ty(fb, wide)?; - let m = fb.convert(ConvOp::ConvertUToF, em, ft)?; - let scale = fsplat(fb, wide, 1.0 / 16_777_216.0)?; - let d = bin(fb, BinOp::FMul, m, scale)?; - let ut = ty(fb, u)?; - let den = fb.convert(ConvOp::Bitcast, d, ut)?; - let min_normal = c(fb, 0x0400)?; - let is_den = bin(fb, BinOp::ULessThan, em, min_normal)?; - let r = fb.select(is_den, den, normal)?; - let sm = c(fb, 0x8000)?; - let sign = bin(fb, BinOp::BitwiseAnd, h, sm)?; - let k16 = c(fb, 16)?; - let sign = bin(fb, BinOp::ShiftLeftLogical, sign, k16)?; - bin(fb, BinOp::BitwiseOr, sign, r) -} - /// `x` (`double` lanes of form `from`) converted to `f32` rounding to odd: the result is /// truncated toward zero and its lowest bit set when inexact, so one later rounding to a format /// of at most 22 significand bits is correctly rounded. Independent of the device's rounding diff --git a/crates/metal2vulkan/src/lower/arith/ops.rs b/crates/metal2vulkan/src/lower/arith/ops.rs index 5469a67ec..4c2447666 100644 --- a/crates/metal2vulkan/src/lower/arith/ops.rs +++ b/crates/metal2vulkan/src/lower/arith/ops.rs @@ -234,9 +234,8 @@ pub fn bool_binary( } /// A float binary operator on floats of form `f` (LLVM `frem` is C `fmod`, the sign of the -/// dividend: `OpFRem`). A narrow form rounds the `f32` result to its format; a sum or difference -/// takes the device's rounding alone, below the smallest normal half included -/// ([`narrow::device_round`]). +/// dividend: `OpFRem`). A narrow form rounds the `f32` result to its format by the device's +/// rounding ([`narrow::round`]). pub fn float_binary( fb: &mut FunctionBuilder<'_>, op: AirBin, @@ -253,10 +252,7 @@ pub fn float_binary( _ => BinOp::FRem, }; let r = fb.binary_with(o, a, b, contract)?; - match o { - BinOp::FAdd | BinOp::FSub => narrow::device_round(fb, f, r), - _ => narrow::round(fb, f, r), - } + narrow::round(fb, f, r) } /// The census name of a `half` operator on the device's 16-bit arithmetic diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index 3fe880173..a5f6bf060 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -7,6 +7,12 @@ //! CPU interpreter over every case whose reference result is defined (LLVM poison and undefined //! behavior are skipped, so an interpreter trap is a real failure). References are written from //! the LLVM and Metal definitions in plain Rust. +//! +//! A kernel rounds to `half` in `QuantizeForm::Controlled` unless its body sets another form: the +//! device's conversion under the 16-bit float controls, Metal's `half(float)` by the Vulkan spec, +//! which the interpreter rounds to nearest even with half denormals kept. A `half` operand is the +//! device's widening of its bits (`narrow::from_bits`), exact but for a NaN, which the +//! interpreter widens to its canonical NaN (`PrecisionNote::NativeNanEncoding`). use super::legal::{f16_to_f64, f64_to_f16, FloatFmt, Form, Held}; use super::libm::Lib; @@ -325,6 +331,7 @@ fn kernel_defs( lanes: bool, ) -> BResult { let mut b = ModuleBuilder::new(); + b.set_quantize_form(QuantizeForm::Controlled); let outb = buffer(&mut b, 0)?; let inb = buffer(&mut b, 1)?; let funcs = defs(&mut b)?; @@ -383,9 +390,8 @@ fn wide_profile() -> DeviceProfile { } /// The `half` roundings the blends' checks run under (`extended_range::blend::half_of`): the -/// device's quantize with its exact denormal arm, and the device's conversion under the 16-bit -/// float controls, each checked against Metal's arithmetic on the interpreter's nearest-even -/// quantize and conversion. +/// integer sequence, which every form but the controlled one takes, and the device's conversion +/// under the 16-bit float controls, each checked against Metal's arithmetic. const HALF_FORMS: [QuantizeForm; 2] = [QuantizeForm::Device, QuantizeForm::Controlled]; /// One case: per operand, per lane, the held bits. @@ -429,6 +435,15 @@ fn is_nan(f: Form, b: u64) -> bool { } } +/// Whether `f32` bits `got` are the device's quantize's answer for the `half` value `want` (`f32` +/// bits) below the smallest normal half: its signed zero. SPIR-V lets `OpQuantizeToF16` answer a +/// zero there, and the interpreter's does (as NIR's `fquantize2f16`), so a module rounding by +/// [`QuantizeForm::Device`] may answer it (`PrecisionNote::NativeHalfQuantize`). +fn quantize_flush_of(got: u64, want: u64) -> bool { + let w = f32::from_bits(want as u32); + w != 0.0 && w.abs() < 2f32.powi(-14) && got == want & 0x8000_0000 +} + fn is_zero(f: Form, b: u64) -> bool { f.is_float() && (b << 1) & mask(f.bits()) == 0 } @@ -1907,7 +1922,9 @@ fn float_ref(op: FloatFn, bits: u8, a: &[u64]) -> Option { /// `llvm.copysign` is the first operand's bits with the second's sign bit, exactly: NaN payloads, /// infinities, zeros, and denormals keep every other bit, on `float` and on the narrow formats held -/// widened (whose container's sign bit is the format's). +/// widened (whose container's sign bit is the format's). A `half` NaN's bits, its sign among them, +/// are the device's widening's (`PrecisionNote::NativeNanEncoding`): a `half` NaN's sign moves as +/// that NaN's, and a NaN first operand is a NaN. #[test] fn copysign_moves_exactly_the_sign_bit() { let mut f32s = f32_values(); @@ -1921,9 +1938,14 @@ fn copysign_moves_exactly_the_sign_bit() { let mut halves: Vec = vec![0, 0x8000, 0x0001, 0x8001, 0x3C00, 0xBC00, 0x7BFF]; halves.extend([0x7C00, 0xFC00, 0x7E00, 0x7C01, 0xFE01, 0x03FF]); let bfloats: Vec = vec![0, 0x8000, 0x0001, 0x3F80, 0xBF80, 0x7F80, 0xFF80, 0x7FC1]; + let numbers: Vec = halves + .iter() + .copied() + .filter(|&h| !is_nan(float(16), h)) + .collect(); for (what, f, vals, sign) in [ ("f32", float(32), f32s, 0x8000_0000u64), - ("half", float(16), halves, 0x8000), + ("half", float(16), numbers, 0x8000), ("bfloat", bfloat(), bfloats, 0x8000), ] { check_accept( @@ -1946,6 +1968,34 @@ fn copysign_moves_exactly_the_sign_bit() { &|g, w| g == w, ); } + // A `half` NaN operand, its bits the device's widening's. + let half = float(16); + let nans: Vec = halves + .iter() + .copied() + .filter(|&h| is_nan(half, h)) + .collect(); + let mut cases = pairs(&nans, &halves); + cases.extend(pairs(&halves, &nans)); + check_accept( + "copysign half NaN operands", + &[half, half], + half, + &|fb, x| { + math::float_fn( + fb, + FloatFn::CopySign, + half, + Contraction::Forbidden, + NanTest::IsNan, + x, + &Lib::instructions(), + ) + }, + &cases, + &|c| Some(vec![(arg(c, 0) & !0x8000) | (arg(c, 1) & 0x8000)]), + &|g, w| (is_nan(half, g) && is_nan(half, w)) || g & 0x7FFF == w & 0x7FFF, + ); } #[test] diff --git a/crates/metal2vulkan/src/lower/arith/tests/half_texel.rs b/crates/metal2vulkan/src/lower/arith/tests/half_texel.rs index 0e1682e2e..9185e9095 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/half_texel.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/half_texel.rs @@ -3,7 +3,8 @@ //! exact values (a normalized code's value `c / (2^b - 1)`, a grid step's `n / D`), and, for a //! value off its format's grid (a filter other than Metal's), the routine's own `f32` step //! `RoundEven(x · D)`. Each runs in every [`QuantizeForm`], whose rounding the routine shares where -//! it is Metal's. +//! it is Metal's; the device's quantize ([`QuantizeForm::Device`]) may answer a `half` denormal as +//! its signed zero ([`quantize_flush_of`]). use super::texel_round::half_of; use super::*; @@ -59,7 +60,8 @@ fn body_families( } /// Run the routine over `texels` at `class`, `form`, and `lanes`, against `reference` of each -/// lane's index and value, in every [`QuantizeForm`]. +/// lane's index and value, in every [`QuantizeForm`] (a `half` denormal the device's quantize's +/// zero or itself in [`QuantizeForm::Device`]). fn run_lanes( what: &str, class: u32, @@ -72,7 +74,7 @@ fn run_lanes( .map(|t| vec![t.to_vec(), vec![u64::from(class)]]) .collect(); for q in FORMS { - check( + check_accept( &format!("{what} {form:?} {lanes:?} {q:?}"), &[v4(), int(32)], v4(), @@ -86,11 +88,19 @@ fn run_lanes( .collect(), ) }, - false, + &|g, w| texel_answers(q, g, w), ); } } +/// Whether `f32` bits `got` answer the `half` value `want` in a module rounding by `q`: exactly, a +/// NaN for a NaN, or, by the device's quantize, a denormal's signed zero. +fn texel_answers(q: QuantizeForm, got: u64, want: u64) -> bool { + got == want + || (is_nan(v4(), got) && is_nan(v4(), want)) + || (q == QuantizeForm::Device && quantize_flush_of(got, want)) +} + /// Run the routine over `texels` (four lanes each, `f32` bits) at `class` and `form`, against /// `reference` lane by lane, in every [`QuantizeForm`]. fn run( @@ -346,9 +356,9 @@ fn a_float_texel_rounds_by_its_access() { ); } -/// A format whose conversion is not measured takes every other `half` texel's exact rounding -/// (`narrow::round_texel`): to nearest even, half denormals kept, a NaN or an infinity itself, in -/// either form. +/// A format whose conversion is not measured takes every other `half` texel's rounding +/// (`narrow::round_texel`): to nearest even, half denormals kept (but by the device's quantize), a +/// NaN or an infinity itself, in either form. #[test] fn an_unmeasured_format_takes_the_exact_rounding() { let texels = quads(&float_texels()); @@ -1042,7 +1052,9 @@ fn grid16_values(f: Norm, rng: &mut Rng) -> Vec { /// (`texel_round::ones_ratio_to_half`); the two answer alike, bit for bit, on every value of /// [`grid16_values`] (every step of both grids, both signs, and values off the grids), in both /// roundings the routine takes and in a read's and a filtered sample's forms. Under native half -/// rounding it keeps the integer form, which answers alike too. +/// rounding it keeps the integer form, which answers alike too; a module rounding by the device's +/// quantize is always under native half rounding (`narrow::native_rounding`), so it runs only so, +/// and there a `half` denormal may be the quantize's signed zero ([`texel_answers`]). fn grid16_forms_agree(part: usize, of: usize) { let mut rng = Rng(0x00b1_f0b1_f5ee_d016); let ins = [v4(), int(32)]; @@ -1080,7 +1092,11 @@ fn grid16_forms_agree(part: usize, of: usize) { }; let what = format!("{f:?} {form:?} {lanes:?} {q:?}"); let want = run_module(&what, build(HalfFamilies::Every, false), &ins, v4(), &cases); - for native in [false, true] { + let natives: &[bool] = match q { + QuantizeForm::Device => &[true], + QuantizeForm::Converted | QuantizeForm::Controlled => &[false, true], + }; + for &native in natives { let got = run_module( &what, build(HalfFamilies::MetalSampler, native), @@ -1091,7 +1107,13 @@ fn grid16_forms_agree(part: usize, of: usize) { let differ: Vec = cases .iter() .zip(got.iter().zip(&want)) - .filter(|(_, (g, w))| g != w) + .filter(|(_, (g, w))| { + g.len() != w.len() + || !g + .iter() + .zip(w.iter()) + .all(|(g, w)| texel_answers(q, *g, *w)) + }) .take(8) .map(|(c, (g, w))| format!("{:x?}: got {g:x?}, want {w:x?}", c[0])) .collect(); @@ -1201,8 +1223,8 @@ fn the_device_rounding_reads_the_texel_alone() { /// Metal-sampler routine does for every class that takes it: for each pixel format whose class /// `plain_on_metal_sampler` holds, the routine at that class, read and sample, one texel's lanes, a /// filtered value's and gathered channels', is the texel rounded to nearest even with its NaN -/// kept, as is the plain arm itself, in each form a device sampling through Metal's own texture -/// unit rounds in. +/// kept (a denormal the device's quantize's zero or itself), as is the plain arm itself, in each +/// form a device sampling through Metal's own texture unit rounds in. #[test] fn the_plain_arm_is_the_metal_sampler_routine_for_its_classes() { let mut texels: Vec = vec![ @@ -1271,14 +1293,14 @@ fn the_plain_arm_is_the_metal_sampler_routine_for_its_classes() { .collect(); for q in roundings { for (form, lanes) in accesses { - check( + check_accept( &format!("{pf:?} {form:?} {lanes:?} {q:?}"), &[v4(), int(32)], v4(), &body_families(form, lanes, q, HalfFamilies::MetalSampler), &cases, &|c| Some(c[0].iter().map(|x| rte(*x)).collect()), - false, + &|g, w| texel_answers(q, g, w), ); } } @@ -1290,7 +1312,7 @@ fn the_plain_arm_is_the_metal_sampler_routine_for_its_classes() { ); let cases: Vec = quads.iter().map(|t| vec![t.to_vec()]).collect(); for q in roundings { - check( + check_accept( &format!("the plain arm {q:?}"), &[v4()], v4(), @@ -1304,7 +1326,7 @@ fn the_plain_arm_is_the_metal_sampler_routine_for_its_classes() { }, &cases, &|c| Some(c[0].iter().map(|x| rte(*x)).collect()), - false, + &|g, w| texel_answers(q, g, w), ); } // The families the predicate leaves out: a 32-bit float texel (its samples round toward zero), diff --git a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs index e9f2c67da..f3c21d3af 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs @@ -61,17 +61,6 @@ fn nbits(f: Form, x: f64) -> u64 { } } -/// [`nbits`] of `x` as the device's rounding alone gives it in `QuantizeForm::Device`, the module -/// builder's default (`narrow::device_round`, a sum's or difference's): a `half` below the smallest -/// normal half is the interpreter's quantize's zero of its sign. -fn nbits_flushed(f: Form, x: f64) -> u64 { - let b = nbits(f, x); - match f.float_fmt() { - Some(FloatFmt::Half) if b & 0x7C00 == 0 => b & 0x8000, - _ => b, - } -} - /// Equal bits, or both NaN. fn exact_ok(out: Form) -> impl Fn(u64, u64) -> bool { move |g, w| g == w || (is_nan(out, g) && is_nan(out, w)) @@ -98,11 +87,14 @@ fn bf16_values() -> Vec { } /// Every half and bfloat bit pattern round-trips through its widened `f32` bit for bit (denormals, -/// infinities, and NaN payloads and signs included), and the widened value is the pattern's. +/// infinities, and NaN payloads and signs included) where the value is stored unchanged, and the +/// widened value is the pattern's. /// /// The store of a loaded value reuses the bits it was decoded from, so the round trip runs twice: /// once through that reuse, and once through a copy of the value, which has no noted bits, so -/// `to_bits` runs its sequence. +/// `to_bits` runs its sequence: there a half NaN is the device's widening's (here the interpreter's +/// canonical NaN, `PrecisionNote::NativeNanEncoding`), and every other half and every bfloat +/// pattern comes back exactly. #[test] fn narrow_bits_round_trip_every_pattern() { for f in [half(), bfloat()] { @@ -123,7 +115,7 @@ fn narrow_bits_round_trip_every_pattern() { &|fb, x| fb.unary(UnOp::CopyObject, x[0]), &cases, &|c| Some(vec![arg(c, 0)]), - &|g, w| g == w, + &|g, w| g == w || (f == half() && is_nan(f, g) && is_nan(f, w)), ); check( &format!("{f:?} widened value"), @@ -296,7 +288,10 @@ fn narrow_constant_bits_fold_exactly() { /// the harness loads above each lane's 16 bits cleared); so is a vector that keeps two lanes of a /// loaded vector and replaces the other two; so is a chain one lane of which has no known bits (a /// copy of a loaded lane), which runs the sequence; so is each lane stored alone, with and without -/// known vector bits; and the vector's widened lanes are the patterns' values. +/// known vector bits; and the vector's widened lanes are the patterns' values. Where the sequence +/// runs, a `half` NaN's bits are the device's widening's (`PrecisionNote::NativeNanEncoding`): so +/// in a copy's chain, and in the loaded vector's, which the harness builds from its lanes' decodes +/// (a construct, whose bits are not noted). #[test] fn narrow_lanes_move_as_bits_through_vectors() { use super::super::narrow::note_insert; @@ -326,6 +321,8 @@ fn narrow_lanes_move_as_bits_through_vectors() { .collect(); let ins = [f, f, f, f]; let lanes = |c: &Case| Some((0..4).map(|i| arg(c, i)).collect()); + // Bits the sequence computes: a `half` NaN is the device's widening's. + let sequenced = |g: u64, w: u64| g == w || (f == half() && is_nan(f, g) && is_nan(f, w)); for copy in [None, Some(2)] { check_accept( &format!("{f:?} lanes through a vector (copied lane: {copy:?})"), @@ -334,7 +331,10 @@ fn narrow_lanes_move_as_bits_through_vectors() { &|fb, x| assemble(fb, f, x, copy), &cases, &lanes, - &|g, w| g == w, + &|g, w| match copy { + Some(_) => sequenced(g, w), + None => g == w, + }, ); } check( @@ -355,8 +355,8 @@ fn narrow_lanes_move_as_bits_through_vectors() { }, false, ); - // Lanes 0 and 2 of a loaded vector replaced by two loaded lanes: the kept lanes' bits - // carry the harness's junk, which the store clears. + // Lanes 0 and 2 of a loaded vector replaced by two loaded lanes: the kept lanes' junk + // above their 16 bits is cleared. let mixed: Vec = (0..0x4000u64) .map(|b| { vec![ @@ -379,7 +379,7 @@ fn narrow_lanes_move_as_bits_through_vectors() { }, &mixed, &|c| Some(vec![c[0][0], c[2][1], c[1][0], c[2][3]]), - &|g, w| g == w, + &sequenced, ); // The first and the last lane (the other lanes extract the same way). for lane in [0u32, 3] { @@ -401,7 +401,10 @@ fn narrow_lanes_move_as_bits_through_vectors() { }, &cases, &|c| Some(vec![arg(c, lane as usize)]), - &|g, w| g == w, + &|g, w| match copied { + true => sequenced(g, w), + false => g == w, + }, ); } } @@ -477,9 +480,8 @@ fn narrow_lane_inserts_never_cost_words() { /// bfloat pattern, each in one lane of a vector built by `narrow::insert`, widens to the `f32` bits /// its own decode gives (`f32_of_half_bits` is checked against that decode in /// `narrow_constant_bits_fold_exactly`), and every pattern, each in one lane of a vector of -/// unknown bits stored lane by lane, is stored exactly; the first saves the lane decodes (more -/// than 100 words for halves), and the second costs no more than one vector encode and a copy -/// per lane. +/// unknown bits stored lane by lane, is stored exactly; the first is smaller than the lane +/// decodes, and the second costs no more than one vector encode and a copy per lane. #[test] fn narrow_vector_decodes_and_encodes_are_offered() { use super::super::narrow::insert; @@ -508,13 +510,10 @@ fn narrow_vector_decodes_and_encodes_are_offered() { let m = kernel_with(&ins, out, &built(true), true, false).expect("build"); let plain = kernel_with(&ins, out, &built(false), true, false).expect("build"); let (with, without) = (words(m.clone()), words(plain)); - // A bfloat decode is one shift, a half decode about twenty instructions. - let saved = if f == half() { 100 } else { 0 }; - assert!( - with + saved < without, - "{f:?}: {with} words offered, {without} not" - ); - // Bit for bit what each lane's own decode gives (a signaling NaN stays signaling). + // A bfloat decode is one shift, a half decode the device's widening of a few. + assert!(with < without, "{f:?}: {with} words offered, {without} not"); + // Bit for bit what each lane's own decode gives: a bfloat's every pattern (a signaling NaN + // stays signaling), a half's but a NaN, which is the device's widening's NaN. let widened = |h: u64| { let h = h as u32; u64::from(if f == half() { @@ -523,6 +522,7 @@ fn narrow_vector_decodes_and_encodes_are_offered() { h << 16 }) }; + let nan32 = |b: u64| f32::from_bits(b as u32).is_nan(); check_module( &format!("{f:?} lanes decoded once"), m, @@ -530,7 +530,7 @@ fn narrow_vector_decodes_and_encodes_are_offered() { out, &cases, &|c| Some((0..4).map(|i| widened(arg(c, i))).collect()), - &|g, w| g == w, + &|g, w| g == w || (f == half() && nan32(g) && nan32(w)), ); // A copy of a loaded vector has no known bits; its lanes are stored one by one. let v4 = vec(f, 4); @@ -552,7 +552,8 @@ fn narrow_vector_decodes_and_encodes_are_offered() { v4, &cases, &|c| Some(c[0].clone()), - &|g, w| g == w, + // A copy's half NaN is the device's widening's (`NativeNanEncoding`). + &|g, w| g == w || (f == half() && is_nan(f, g) && is_nan(f, w)), ); } } @@ -578,10 +579,11 @@ fn narrow_float_operators_are_named_by_format() { } /// A bitcast from or to narrow float vectors moves narrow patterns bit for bit (NaN payloads -/// included) under each plan: through one word (`Packed`), through words (`Words`), and lane by -/// lane (`Lanes`), where a narrow vector converts to and from its format bits once as a vector. The -/// word plan between `<4 x half>` and `<2 x i32>` moves every half pattern; the others move the -/// interesting values and pseudo-random patterns. +/// included, but for a `half` NaN whose loaded bits are not reused: its bits are the device's +/// widening's, `PrecisionNote::NativeNanEncoding`) under each plan: through one word (`Packed`), +/// through words (`Words`), and lane by lane (`Lanes`), where a narrow vector converts to and from +/// its format bits once as a vector. The word plan between `<4 x half>` and `<2 x i32>` moves every +/// half pattern; the others move the interesting values and pseudo-random patterns. #[test] fn narrow_vector_bitcasts_move_narrow_patterns() { let mut rng = Rng(11); @@ -640,15 +642,20 @@ fn narrow_vector_bitcasts_move_narrow_patterns() { .collect(), ) }, - &|g, w| g == w, + &|g, w| { + // Each 16-bit pattern alike, or a `half` NaN for a `half` NaN. + (0..4).all(|k| { + let (g, w) = ((g >> (16 * k)) & 0xFFFF, (w >> (16 * k)) & 0xFFFF); + g == w || (f == half() && is_nan(f, g) && is_nan(f, w)) + }) + }, ); } } } /// `+ - * / %` on widened narrow floats round once to the format (double rounding through `f32` is -/// innocuous for these), on scalars and vectors; in `QuantizeForm::Device` a `half` sum or -/// difference below the smallest normal half is the device's quantize's zero ([`nbits_flushed`]). +/// innocuous for these), on scalars and vectors. #[test] fn narrow_float_operators_round_once() { for (f, vals) in [(half(), half_values()), (bfloat(), bf16_values())] { @@ -669,8 +676,8 @@ fn narrow_float_operators_round_once() { &|c| { let (a, b) = (nval(f, arg(c, 0)), nval(f, arg(c, 1))); Some(vec![match op { - AirBin::FAdd => nbits_flushed(f, a + b), - AirBin::FSub => nbits_flushed(f, a - b), + AirBin::FAdd => nbits(f, a + b), + AirBin::FSub => nbits(f, a - b), AirBin::FMul => nbits(f, a * b), AirBin::FDiv => nbits(f, a / b), _ => nbits(f, a % b), @@ -709,8 +716,6 @@ fn narrow_float_operators_round_once() { /// The float functions on half and bfloat values: closed functions return values of the format, /// `fract` rounds its `f32` difference once (it is not closed: a negative non-integral input needs /// more bits), `mix` and `llvm.fmuladd` round per step (the unfused choice), `sqrt` rounds once. -/// In `QuantizeForm::Device` `fract`'s difference and `fmuladd`'s sum take the device's rounding -/// alone, which flushes a `half` below the smallest normal half ([`nbits_flushed`]). #[test] fn narrow_float_functions_match_their_definitions() { for (f, vals) in [(half(), half_values()), (bfloat(), bf16_values())] { @@ -793,9 +798,8 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) { &cases, &|c| { let x = |i: usize| nval(f, c[i][0]); - // An intermediate step's rounding, and a sum's or difference's. + // An intermediate step's rounding. let q = |v: f64| nval(f, nbits(f, v)); - let qs = |v: f64| nval(f, nbits_flushed(f, v)); let r = match op { FloatFn::Abs => x(0).abs(), FloatFn::Floor => x(0).floor(), @@ -803,13 +807,11 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) { FloatFn::Trunc => x(0).trunc(), FloatFn::Round => metal_round(is_half, x(0)), FloatFn::Rint => x(0).round_ties_even(), - // A half NaN is kept bit for bit, a bfloat one is `float`'s. - FloatFn::Fract if x(0).is_nan() && is_half => return Some(vec![c[0][0]]), FloatFn::Fract if x(0).is_nan() => f64::NAN, FloatFn::Fract if x(0).is_infinite() => 0.0, FloatFn::Fract => { let below = 1.0 - 2f64.powi(if is_half { -11 } else { -8 }); - qs(x(0) - x(0).floor()).min(below) + q(x(0) - x(0).floor()).min(below) } FloatFn::Sign if x(0) > 0.0 => 1.0, FloatFn::Sign if x(0) < 0.0 => -1.0, @@ -826,7 +828,7 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) { return Some(vec![median3_ref(b, &|v| nval(f, v), false)]); } FloatFn::Mix => q(x(0) * q(1.0 - x(2))) + q(x(1) * x(2)), - FloatFn::MulAdd => qs(q(x(0) * x(1)) + x(2)), + FloatFn::MulAdd => q(q(x(0) * x(1)) + x(2)), _ => x(0).sqrt(), }; Some(vec![nbits(f, r)]) @@ -838,9 +840,8 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) { /// Class K: Metal's `half` `fract` with every fast-math flag (`nan_half_fast`) answers the largest /// `half` below one, `0x3BFF`, for a NaN and for either infinity, where without flags (`nan_half`) -/// a NaN is itself and an infinity `+0`; every finite lane is the precise one's, its difference the -/// device's rounding alone (in `QuantizeForm::Device` a positive denormal's is the quantize's -/// zero). +/// a NaN is a NaN (its bits the device's widening's) and an infinity `+0`; every finite lane is the +/// precise one's, its difference rounded once. #[test] fn flagged_half_fract_answers_below_one_at_nans_and_infinities() { let mut halves: Vec = (0..0x10000u64).step_by(97).collect(); @@ -860,7 +861,7 @@ fn flagged_half_fract_answers_below_one_at_nans_and_infinities() { _ => 0, } } else { - let d = f16_to_f64(nbits_flushed(half(), x - x.floor()) as u16); + let d = f16_to_f64(nbits(half(), x - x.floor()) as u16); u64::from(f64_to_f16(d.min(1.0 - 2f64.powi(-11)))) }; Some(vec![r; n]) @@ -883,14 +884,16 @@ fn flagged_half_fract_answers_below_one_at_nans_and_infinities() { }, &cases, &|c| run(op, c), - &|g, w| g == w, + &exact_ok(f), ); } } } -/// The `f32` operands [`half_rounding_keeps_denormals`] rounds to `half`, in each of the -/// module's half roundings. +/// The `f32` operands [`converted_half_rounding_is_the_exactly_rounded_half`] rounds to `half`: +/// every 17th half pattern and every denormal one, each exactly and at its exact ties with both +/// neighbours, just inside and outside them, and the `f32` edge values (the ties at the smallest +/// normal half, `65504..65520`, signed zeros, `f32` denormals, NaN). fn half_rounding_operands() -> Vec { let mut xs: Vec = Vec::new(); for h in (0..0x7C00u16).step_by(17).chain(0..0x400) { @@ -937,60 +940,15 @@ fn half_rounding_operands() -> Vec { xs } -/// Rounding an `f32` to `half` keeps half denormals and rounds to nearest even on every part of the -/// half range: every 17th half pattern and every denormal one, each exactly and at its exact ties -/// with both neighbours, just inside and outside them, and the `f32` edge values (the ties at the -/// smallest normal half, `65504..65520`, signed zeros, `f32` denormals, NaN). Metal's readings of -/// A1's `half-denormal-results-of-arithmetic-and-conversions` (dd2cb644) and -/// `half-tanh-under-fast-math-at-every-sixteenth-pattern` (27353187) keep every half denormal a -/// result rounds to. -#[test] -fn half_rounding_keeps_denormals() { - let xs = half_rounding_operands(); - let (f32f, h) = (float(32), half()); - let cases: Vec = xs - .iter() - .filter(|x| x.is_nan() || x.is_finite() || x.is_infinite()) - .map(|x| vec![vec![u64::from(x.to_bits())]]) - .collect(); - check_accept( - "round f32 to half", - &[f32f], - h, - &|fb, x| crate::lower::arith::narrow::round(fb, h, x[0]), - &cases, - &|c| Some(vec![u64::from(f64_to_f16(f64::from(f32v(arg(c, 0)))))]), - &exact_ok(h), - ); - let v = vec(h, 3); - let vc: Vec = xs - .chunks(3) - .filter(|c| c.len() == 3) - .map(|c| vec![c.iter().map(|x| u64::from(x.to_bits())).collect()]) - .collect(); - check_accept( - "round <3 x float> to half", - &[vec(f32f, 3)], - v, - &|fb, x| crate::lower::arith::narrow::round(fb, v, x[0]), - &vc, - &|c| { - Some( - c[0].iter() - .map(|b| u64::from(f64_to_f16(f64::from(f32v(*b))))) - .collect(), - ) - }, - &exact_ok(v), - ); -} - /// In `QuantizeForm::Converted` and `Controlled` a `half` rounding is the conversion to 16 bits /// and its widening alone, which the interpreter rounds to nearest even with half denormals kept, /// as the Vulkan spec makes it under the controlled form's float controls: over -/// [`half_rounding_operands`], `round` and `device_round` give the exactly rounded half on scalars -/// and vectors, with no `OpQuantizeToF16` and no `RoundEven` in the module. In -/// `Controlled` each conversion is decorated `NoContraction`, and none in `Converted`. +/// [`half_rounding_operands`], `round` gives the exactly rounded half on scalars and vectors, with +/// no `OpQuantizeToF16` and no `RoundEven` in the module. In `Controlled` each conversion is +/// decorated `NoContraction`, and none in `Converted`. Metal's readings of A1's +/// `half-denormal-results-of-arithmetic-and-conversions` (dd2cb644) and +/// `half-tanh-under-fast-math-at-every-sixteenth-pattern` (27353187) keep every half denormal a +/// result rounds to, as this rounding does. #[test] fn converted_half_rounding_is_the_exactly_rounded_half() { let xs = half_rounding_operands(); @@ -1012,21 +970,14 @@ fn converted_half_rounding_is_the_exactly_rounded_half() { .collect::>(), ) }; - type Round = fn(&mut FunctionBuilder<'_>, Form, Value) -> BResult; - let rounds: [(&str, Round); 2] = [ - ("round", crate::lower::arith::narrow::round), - ("device_round", crate::lower::arith::narrow::device_round), - ]; use crate::spirv::builder::QuantizeForm; use crate::spirv::ir::Contraction; - for ((name, round), q) in rounds - .into_iter() - .flat_map(|r| [(r, QuantizeForm::Converted), (r, QuantizeForm::Controlled)]) - { + let name = "round"; + for q in [QuantizeForm::Converted, QuantizeForm::Controlled] { for (form, input, cs) in [(h, f32f, &cases), (v, vec(f32f, 3), &vc)] { let body = |fb: &mut FunctionBuilder<'_>, x: &[Value]| { fb.module().set_quantize_form(q); - round(fb, form, x[0]) + crate::lower::arith::narrow::round(fb, form, x[0]) }; let m = kernel_with(&[input], form, &body, true, false) .unwrap_or_else(|e| panic!("{name} {q:?}: build: {e:?}")); @@ -1142,78 +1093,66 @@ fn metal_half_operands() -> Vec { xs } -/// In `QuantizeForm::Device`, the default, through the interpreter's quantize (to nearest even, -/// flushing what is too small for a normal half to the zero of its sign), `round` is Metal's -/// conversion of a `float` to `half` ([`metal_half`]) over [`metal_half_operands`] (signed zeros -/// included, a NaN a NaN) on scalars and vectors, its quantize's flush to zero rounded onto the -/// half denormal grid, and keeps that arm (`narrow::flushes_below_normal` finds none); -/// `device_round` is the quantize alone: Metal's conversion of every operand from the smallest -/// normal half up, and the quantize's zero below it. +/// In `QuantizeForm::Device`, the default, a `half` rounding is the device's `OpQuantizeToF16` +/// alone, with no denormal arm (no `RoundEven`, no test of the quantize for a zero): through the +/// interpreter's quantize (to +/// nearest even, flushing what is too small for a normal half to the zero of its sign), `round` +/// over [`metal_half_operands`] (signed zeros included, a NaN a NaN), on scalars and vectors, is +/// Metal's conversion of a `float` to `half` ([`metal_half`]) from the smallest normal half up and +/// the quantize's zero of the operand's sign below it, where Metal answers the half denormal. #[test] -fn device_half_rounding_is_metals_conversion_on_a_nearest_even_quantize() { +fn device_half_rounding_is_the_quantize_alone() { use crate::spirv::builder::QuantizeForm; let xs = metal_half_operands(); let (f32f, h) = (float(32), half()); let v = vec(h, 3); - type Round = fn(&mut FunctionBuilder<'_>, Form, Value) -> BResult; - let rounds: [(&str, Round, bool); 2] = [ - ("round", crate::lower::arith::narrow::round, false), - ( - "device_round", - crate::lower::arith::narrow::device_round, - true, - ), - ]; // The quantize alone: Metal's conversion where it is a normal half, an infinity or a NaN, and // the zero of the operand's sign below the smallest normal half. let flushed = |b: u64| match metal_half(b) { h if h & 0x7C00 == 0 => h & 0x8000, h => h, }; - // The device form's quantize is the interpreter's: a quarter of the operands shows the - // routine around it. - for (form_name, form, step) in [("device", QuantizeForm::Device, 4)] { - for (name, round, bare) in rounds { - let want = |c: &Case| { - Some( - c[0].iter() - .map(|b| if bare { flushed(*b) } else { metal_half(*b) }) - .collect::>(), - ) - }; - let ops: Vec = xs.iter().copied().step_by(step).collect(); - let cases: Vec = ops.iter().map(|b| vec![vec![u64::from(*b)]]).collect(); - let vc: Vec = ops - .chunks(3) - .step_by(5) - .filter(|c| c.len() == 3) - .map(|c| vec![c.iter().map(|b| u64::from(*b)).collect()]) - .collect(); - for (lanes, input, cs) in [(h, f32f, &cases), (v, vec(f32f, 3), &vc)] { - let body = |fb: &mut FunctionBuilder<'_>, x: &[Value]| { - fb.module().set_quantize_form(form); - round(fb, lanes, x[0]) - }; - let what = format!("{form_name} {name} on {lanes:?}"); - let m = kernel_with(&[input], lanes, &body, true, false) - .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - assert!( - crate::lower::arith::narrow::quantizes(&m), - "{what}: OpQuantizeToF16" - ); - let mut meter = crate::budget::Meter::new(&crate::budget::Budget::default()); - let flushes = crate::lower::arith::narrow::flushes_below_normal(&m, &mut meter) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(flushes, bare, "{what}: a quantize with no denormal arm"); - // The interpreter's quantize keeps a NaN a NaN, its bits the device's. - let nan_loose = exact_ok(lanes); - check_module(&what, m, &[input], lanes, cs, &want, &nan_loose); - } - } + let want = |c: &Case| Some(c[0].iter().map(|b| flushed(*b)).collect::>()); + // The quantize is the interpreter's: a quarter of the operands shows the module around it. + let ops: Vec = xs.iter().copied().step_by(4).collect(); + let cases: Vec = ops.iter().map(|b| vec![vec![u64::from(*b)]]).collect(); + let vc: Vec = ops + .chunks(3) + .step_by(5) + .filter(|c| c.len() == 3) + .map(|c| vec![c.iter().map(|b| u64::from(*b)).collect()]) + .collect(); + for (lanes, input, cs) in [(h, f32f, &cases), (v, vec(f32f, 3), &vc)] { + let body = |fb: &mut FunctionBuilder<'_>, x: &[Value]| { + fb.module().set_quantize_form(QuantizeForm::Device); + crate::lower::arith::narrow::round(fb, lanes, x[0]) + }; + let what = format!("device round on {lanes:?}"); + let m = kernel_with(&[input], lanes, &body, true, false) + .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); + assert!( + crate::lower::arith::narrow::quantizes(&m), + "{what}: OpQuantizeToF16" + ); + let arm = m.blocks().iter().flat_map(|b| &b.insts).any(|n| { + matches!( + n.inst, + Inst::Glsl { + op: GlslOp::RoundEven, + .. + } | Inst::Binary { + op: BinOp::FOrdEqual, + .. + } + ) + }); + assert!(!arm, "{what}: a denormal arm"); + // The interpreter's quantize keeps a NaN a NaN, its bits the device's. + check_module(&what, m, &[input], lanes, cs, &want, &exact_ok(lanes)); } } -/// A `half` sum or difference takes the device's rounding alone (`narrow::device_round`): over +/// A `half` sum or difference takes the device's rounding (`narrow::round`): over /// every eleventh half pattern below `2^-13` and its negation, the patterns around the smallest /// normal half, and normal, infinite, and NaN operands, on scalars and vectors, every sum and /// difference is the exactly rounded half where that is a normal half, a zero, an infinity or a @@ -2924,15 +2863,15 @@ fn half_arithmetic_on_the_device_is_one_16_bit_instruction() { } } -/// Wherever the module can hold a 16-bit float (`QuantizeForm::Converted` and `Controlled`, a -/// profile with `shaderFloat16`), `from_bits` is the device's widening of the bits as 16-bit -/// floats, with no integer decode: every half bit pattern, with junk above its 16 bits, reads as -/// its exact `f32` value but a NaN, which reads as a NaN, on one to four lanes (one conversion of -/// the gathered lanes), and `narrow::widens_bits` finds the widening. In `QuantizeForm::Device` -/// (no `shaderFloat16`) the integer decode stands: every pattern exact, NaN payloads included, and -/// `widens_bits` finds none. +/// `from_bits` is the device's widening on every form, with no integer decode: wherever the module +/// can hold a 16-bit float (`QuantizeForm::Converted` and `Controlled`, a profile with +/// `shaderFloat16`), of the bits as 16-bit floats (one conversion of the gathered lanes); in +/// `QuantizeForm::Device` (no `shaderFloat16`), `GLSL.std.450 UnpackHalf2x16` of each lane's word +/// (one a lane, and no 16-bit type). Every half bit pattern, with junk above its 16 bits, reads as +/// its exact `f32` value but a NaN, which reads as a NaN, on one to four lanes, and +/// `narrow::widens_bits` finds the widening. #[test] -fn a_half_decode_with_float16_is_the_devices_widening() { +fn a_half_decode_is_the_devices_widening_in_every_form() { use super::super::narrow::{f32_of_half_bits, from_bits, widens_bits}; use crate::spirv::builder::QuantizeForm; let junk = |h: u32| u64::from(h | NARROW_JUNK); @@ -2954,7 +2893,7 @@ fn a_half_decode_with_float16_is_the_devices_widening() { QuantizeForm::Converted, QuantizeForm::Controlled, ] { - let native = q != QuantizeForm::Device; + let float16 = q != QuantizeForm::Device; for lanes in 1u8..=4 { let cases = lanes_of(u32::from(lanes)); let cases = &cases; @@ -2969,7 +2908,7 @@ fn a_half_decode_with_float16_is_the_devices_widening() { let budget = crate::budget::Budget::default(); let mut meter = crate::budget::Meter::new(&budget); let widens = widens_bits(&m, &mut meter).expect("widens_bits"); - assert_eq!(widens, native, "{what}: widens_bits"); + assert!(widens, "{what}: widens_bits"); let insts = || m.blocks().iter().flat_map(|b| &b.insts); let decodes = insts().any(|n| { matches!( @@ -2991,13 +2930,28 @@ fn a_half_decode_with_float16_is_the_devices_widening() { ) }) .count(); - assert_eq!(conversions, usize::from(native), "{what}: the conversions"); - assert_eq!(decodes, !native, "{what}: the integer decode"); + let unpacks = insts() + .filter(|n| { + matches!( + n.inst, + Inst::Glsl { + op: GlslOp::UnpackHalf2x16, + .. + } + ) + }) + .count(); + let halves = m + .types() + .iter() + .any(|(_, t)| matches!(t, Type::Float { width: 16 })); + assert_eq!(conversions, usize::from(float16), "{what}: the conversions"); + let want_unpacks = if float16 { 0 } else { usize::from(lanes) }; + assert_eq!(unpacks, want_unpacks, "{what}: the unpacks"); + assert_eq!(halves, float16, "{what}: a 16-bit float type"); + assert!(!decodes, "{what}: an integer decode"); check_accept(&what, &ins, out, &body, cases, &want, &|g, w| { - g == w - || (native - && f32::from_bits(g as u32).is_nan() - && f32::from_bits(w as u32).is_nan()) + g == w || (f32::from_bits(g as u32).is_nan() && f32::from_bits(w as u32).is_nan()) }); } } diff --git a/crates/metal2vulkan/src/lower/arith/tests/round_texel.rs b/crates/metal2vulkan/src/lower/arith/tests/round_texel.rs index 52ba181ef..8dd69f7cf 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/round_texel.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/round_texel.rs @@ -111,8 +111,9 @@ fn a_wider_texel_rounds_to_nearest_even_keeping_subnormals() { /// Under native half rounding (the device's conversion or quantize, where neither is measured to be /// Metal's) a texel's `half` is the form's own rounding: every half-float texel and every wider /// value but a NaN reads as before, to nearest even with half subnormals kept (the interpreter's -/// conversion rounds so, and the quantize form keeps them by the arm), and a NaN stays a NaN, its -/// bits the form's, without the keep's unsigned compare of the texel's bits. +/// conversion rounds so; its quantize answers a subnormal as its signed zero, which SPIR-V allows), +/// and a NaN stays a NaN, its bits the form's, without the keep's unsigned compare of the texel's +/// bits. #[test] fn a_texel_under_native_half_rounding_takes_its_forms_nan() { use crate::spirv::builder::QuantizeForm; @@ -154,7 +155,11 @@ fn a_texel_under_native_half_rounding_takes_its_forms_nan() { arg(c, 0) as u32, ))))]) }, - &|g, w| g == w || (is_nan(half(), g) && is_nan(half(), w)), + &|g, w| { + g == w + || (is_nan(half(), g) && is_nan(half(), w)) + || (q == QuantizeForm::Device && w & 0x7C00 == 0 && g == w & 0x8000) + }, ); } // The keep's one test of the texel's bits, left out under native half rounding. diff --git a/crates/metal2vulkan/src/lower/arith/tests/snapshot_codes.rs b/crates/metal2vulkan/src/lower/arith/tests/snapshot_codes.rs index 73a506146..820a5b5f5 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/snapshot_codes.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/snapshot_codes.rs @@ -126,8 +126,9 @@ fn signed_normalized_codes_come_back() { } } -/// Every half value widened comes back bit for bit: zeros, denormals, infinities, and each NaN -/// payload as the widening places it. +/// Every half value widened comes back bit for bit, zeros, denormals and infinities, and each NaN a +/// NaN: a read's widening of the code is the device's, whose NaN bits it records +/// (`PrecisionNote::NativeNanEncoding`). #[test] fn half_codes_come_back() { let values: Vec = (0..=u16::MAX) @@ -144,7 +145,7 @@ fn half_codes_come_back() { &body, &cases(&values), &|c| Some(c[0].clone()), - &same, + &|g, w| same(g, w) || (is_nan(float(32), g) && is_nan(float(32), w)), ); } diff --git a/crates/metal2vulkan/src/lower/arith/tests/specials.rs b/crates/metal2vulkan/src/lower/arith/tests/specials.rs index 0d12faf3b..325460860 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/specials.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/specials.rs @@ -605,7 +605,8 @@ const POW: [(u32, u32, u32, u32, u16, u16, u16); 90] = [ /// One lane: the operands' bits and Metal's answer. type Row = (Vec, u64); -/// Run `op` on form `f` over `rows` and require every answer bit for bit, NaN payloads included. +/// Run `op` on form `f` over `rows` and require every answer bit for bit, NaN payloads included but +/// a `half` NaN's, whose bits are the device's widening's (`PrecisionNote::NativeNanEncoding`). fn metal_answers(op: FloatFn, f: Form, rows: &[Row]) { let cases: Vec = rows .iter() @@ -633,7 +634,7 @@ fn metal_answers(op: FloatFn, f: Form, rows: &[Row]) { .find(|(o, _)| *o == ops) .map(|(_, want)| vec![*want]) }, - &|g, w| g == w, + &|g, w| g == w || (f == float(16) && is_nan(f, g) && is_nan(f, w)), ); } @@ -670,14 +671,11 @@ fn fract_and_saturate_answer_as_metal() { .filter(normal) .collect(); metal_answers(FloatFn::Saturate, f32_, &saturate); - // `half` `fract`'s difference is the device's quantize (`narrow::device_round`): a result - // below the smallest normal `half` is the zero of its sign (`PrecisionNote::NativeHalfQuantize`), - // every other lane Metal's. - let flushed: Vec = rows(|r| [u64::from(r.4), u64::from(r.5)]) - .into_iter() - .map(|(x, w)| (x, if w & 0x7C00 == 0 { w & 0x8000 } else { w })) - .collect(); - metal_answers(FloatFn::Fract, half, &flushed); + metal_answers( + FloatFn::Fract, + half, + &rows(|r| [u64::from(r.4), u64::from(r.5)]), + ); metal_answers( FloatFn::Saturate, half, diff --git a/crates/metal2vulkan/src/lower/arith/tests/texel_round.rs b/crates/metal2vulkan/src/lower/arith/tests/texel_round.rs index bdd1e362f..c72bf5458 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/texel_round.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/texel_round.rs @@ -138,8 +138,8 @@ fn every_tie_bits() -> Vec { /// `f32_to_half_from_even` rounds every half's tie and its neighbours, and every half, toward /// zero saturating and with ties away exactly, from the module's own rounding to nearest even -/// (`narrow::round_texel`) in every [`QuantizeForm`]: four lanes at a time, as the texel routine -/// calls it. +/// (`narrow::round_texel`) in every [`QuantizeForm`] (from the device's quantize, a half denormal +/// may be its signed zero): four lanes at a time, as the texel routine calls it. #[test] fn f32_to_half_from_even_is_exact_on_every_tie() { use crate::lower::arith::narrow; @@ -171,7 +171,7 @@ fn f32_to_half_from_even_is_exact_on_every_tie() { .iter() .map(|x| vec![x.clone(), vec![u64::from(tz)]]) .collect(); - check( + check_accept( &format!("f32_to_half_from_even {mode:?} {q:?}"), &[v, b], v, @@ -188,7 +188,11 @@ fn f32_to_half_from_even_is_exact_on_every_tie() { .collect(), ) }, - false, + &|g, w| { + g == w + || (is_nan(v, g) && is_nan(v, w)) + || (q == QuantizeForm::Device && quantize_flush_of(g, w)) + }, ); } } diff --git a/crates/metal2vulkan/src/lower/arith/tests/wide.rs b/crates/metal2vulkan/src/lower/arith/tests/wide.rs index dc749f5c5..8b194f577 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/wide.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/wide.rs @@ -3,8 +3,9 @@ //! Operands and results cross the kernel boundary as their two words per lane (the parent's //! `load`/`store` go through `wide::from_words`/`wide::to_words`), so the word composition is //! checked by every test. Every kernel also passes L3 on `vk12-floor`, which has no -//! `shaderInt64` (a float64 kernel only on the parent's 64-bit profile): the sequences need no -//! 64-bit integer. References are the parent's LLVM and Metal definitions. +//! `shaderInt64` (a float64 kernel only on the parent's 64-bit profile), built in the profile's +//! `half` rounding form (it has no `shaderFloat16`): the sequences need no 64-bit integer. +//! References are the parent's LLVM and Metal definitions. use super::super::wide::{self as w, WideOp}; use super::*; @@ -26,7 +27,8 @@ fn floor() -> DeviceProfile { .expect("vk12-floor") } -/// [`check_accept`] after L3 on `vk12-floor` (unless a form needs 64-bit floats). +/// [`check_accept`] after L3 on `vk12-floor` (unless a form needs 64-bit floats), the module there +/// built in the profile's `half` rounding form. fn check_wide( what: &str, ins: &[Form], @@ -40,8 +42,21 @@ fn check_wide( .chain(std::iter::once(&out)) .any(|f| f.float_fmt() == Some(FloatFmt::F64)); if !f64_used { - let m = kernel(ins, out, body).unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - assert_valid(m, &floor()); + let p = floor(); + let q = crate::lower::arith::narrow::quantize_form(&p); + let m = kernel_defs( + ins, + out, + &|b| { + b.set_quantize_form(q); + Ok(Vec::new()) + }, + &|fb, xs, _| body(fb, xs), + false, + false, + ) + .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); + assert_valid(m, &p); } check(what, ins, out, body, cases, reference, false); } @@ -506,9 +521,9 @@ fn wide_to_float_rounds_once() { } } -/// A wide integer converts to `half` by integer arithmetic on its `f32`, with no `OpQuantizeToF16`, -/// on the values `integers_for_half` gives a 64-bit integer, plus `2^32` and `2^39` and their -/// neighbours. +/// A wide integer converts to `half` by integer arithmetic on its `f32`, with no `OpQuantizeToF16` +/// even where the module rounds by the device's quantize ([`QuantizeForm::Device`]), on the values +/// `integers_for_half` gives a 64-bit integer, plus `2^32` and `2^39` and their neighbours. #[test] fn wide_integers_round_to_half_without_quantize() { for bits in [64u8, 40] { @@ -531,8 +546,18 @@ fn wide_integers_round_to_half_without_quantize() { let what = format!("{kind:?} wide i{bits} -> half"); let body = |fb: &mut FunctionBuilder<'_>, x: &[Value]| w::cast(fb, kind, f, float(16), x[0]); - let module = - kernel(&[f], float(16), &body).unwrap_or_else(|e| panic!("{what}: build: {e:?}")); + let module = kernel_defs( + &[f], + float(16), + &|b| { + b.set_quantize_form(QuantizeForm::Device); + Ok(Vec::new()) + }, + &|fb, xs, _| body(fb, xs), + false, + false, + ) + .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); assert!( !super::super::narrow::quantizes(&module), "{what}: the module holds OpQuantizeToF16" diff --git a/crates/metal2vulkan/src/lower/fragment/snapshot.rs b/crates/metal2vulkan/src/lower/fragment/snapshot.rs index 09e0bc057..23ac65ba8 100644 --- a/crates/metal2vulkan/src/lower/fragment/snapshot.rs +++ b/crates/metal2vulkan/src/lower/fragment/snapshot.rs @@ -91,9 +91,9 @@ //! takes the split), the value the fetch returned. //! - `Half`: each lane's half-float code (`narrow::to_bits`, exact for every half value, a NaN's //! payload included), in an `R16G16B16A16_UINT` image; a read widens it back as a `half` read -//! from memory widens (`narrow::from_bits`): the device's widening where the module holds 16-bit -//! floats, every code's value but a NaN's bits and, where the device may flush a 16-bit -//! denormal, a denormal, each recorded (`narrow::widens_bits`); elsewhere exactly. +//! from memory widens (`narrow::from_bits`): the device's widening on every device, every code's +//! value but a NaN's bits and, where the device may flush a 16-bit denormal, a denormal, each +//! recorded (`narrow::widens_bits`). //! - An integer form: each lane's code (the fetched integer lane, a code of the format), its low 8 //! or 16 bits in an `R8G8B8A8_UINT` or `R16G16B16A16_UINT` image; a read extends it, with its //! sign where signed. diff --git a/crates/metal2vulkan/src/lower/stage_io/fetch.rs b/crates/metal2vulkan/src/lower/stage_io/fetch.rs index c9e9505c1..afa8a4fda 100644 --- a/crates/metal2vulkan/src/lower/stage_io/fetch.rs +++ b/crates/metal2vulkan/src/lower/stage_io/fetch.rs @@ -41,17 +41,17 @@ //! could not align (and every attribute where the profile has no buffer robustness). They are //! contained like any descriptor access (the normative in-shader check when the profile has no //! buffer robustness, reading at offset 0 and yielding zero bytes out of bounds) and decoded -//! exactly ([`Encoding`]): integers zero- or sign-extended by the format's signedness, normalized -//! integers as Metal converts them (`c / (2^b - 1)`, signed `max(c / (2^(b-1) - 1), -1)`), `half` -//! bits exactly, and the packed 10:10:10:2, 11:11:10 float, and 9:9:9:5 shared-exponent formats by -//! their layouts. Missing components read as `(0, 0, 0, 1)` and extra ones are dropped. A float -//! format then rounds to a narrow float parameter; an integer format is masked to a narrow integer -//! parameter. Across the classes ([`class_match`]): an unnormalized 8- or 16-bit integer format -//! read into a float parameter converts each extended component to its value as a float (exact) and -//! rounds it to a narrow one, as Metal does; a 32-bit one is an invalid descriptor, as Metal -//! refuses the pipeline; and a float-class format read into an integer parameter is not a -//! conversion whose Metal meaning is established, so the projection refuses it (`NotImplemented`) -//! and the pulled read refuses it again for a hand-built projection. +//! ([`Encoding`]): integers zero- or sign-extended by the format's signedness, normalized integers +//! as Metal converts them (`c / (2^b - 1)`, signed `max(c / (2^(b-1) - 1), -1)`), `half` bits by +//! the device's widening (`narrow::from_bits`), and the packed 10:10:10:2, 11:11:10 float, and +//! 9:9:9:5 shared-exponent formats by their layouts. Missing components read as `(0, 0, 0, 1)` and +//! extra ones are dropped. A float format then rounds to a narrow float parameter; an integer +//! format is masked to a narrow integer parameter. Across the classes ([`class_match`]): an +//! unnormalized 8- or 16-bit integer format read into a float parameter converts each extended +//! component to its value as a float (exact) and rounds it to a narrow one, as Metal does; a 32-bit +//! one is an invalid descriptor, as Metal refuses the pipeline; and a float-class format read into +//! an integer parameter is not a conversion whose Metal meaning is established, so the projection +//! refuses it (`NotImplemented`) and the pulled read refuses it again for a hand-built projection. //! //! **Kernel stage inputs**. A kernel's `[[stage_in]]` attribute is fetched the same way, once at //! entry, from the kernel buffer slot `ResourceSlot{Kernel, Buffer, buffer_index}` its stage-input @@ -413,8 +413,8 @@ impl PulledRead { /// An upper estimate of the SPIR-V words the fetch emits, once per attribute at entry (its uses /// read the held value and add nothing): the byte-path leaf, the offset and containment /// (through a view or the root entry of a device address, whichever the access family chooses), - /// and the decode of four lanes at the cost of an exact half decode (the dearest one) plus the - /// conversion to the parameter's form. + /// and the decode of four lanes at the cost of the bound on a half's decode (the dearest one) + /// plus the conversion to the parameter's form. pub fn words(&self) -> u32 { let lane = 64 + narrow::bits_words(Form { @@ -688,7 +688,9 @@ fn normalized(fb: &mut FunctionBuilder<'_>, c: SValue, bits: u8, signed: bool) - fb.select(neg, nq, q) } -/// The `f32` of half bits `h`, exactly. +/// The `f32` of half bits `h`: the device's widening of them (`narrow::from_bits`), the `half`'s +/// value but for a NaN's bits and, on a device that may flush 16-bit denormals, a denormal, which +/// the module records (`PrecisionNote::NativeNanEncoding`, `NativeHalfConversion`). fn half(fb: &mut FunctionBuilder<'_>, h: SValue) -> BResult { narrow::from_bits( fb, @@ -790,9 +792,9 @@ fn components(fb: &mut FunctionBuilder<'_>, e: Encoding, raw: SValue) -> BResult /// Record `PrecisionNote::DeviceNanEncoding` for a read of an attribute of `encoding` as `float` /// lanes of `form` where the encoding is a narrow float's ([`Encoding::widens_narrow_float`]): -/// Metal's fetch answers its canonical NaN, sign and payload dropped, where the decode carries the -/// 16-, 11- or 10-bit field's bits up into the payload. A `half` read keeps the field's own bits, -/// as Metal's does. +/// Metal's fetch answers its canonical NaN, sign and payload dropped, where the decode, the +/// device's widening of the 16-, 11- or 10-bit field as a half's bits, answers a NaN of the +/// device's bits. A `half` read stored unchanged keeps the field's own bits, as Metal's does. pub(super) fn narrow_float_nans(cx: &mut SelectCx<'_>, encoding: Encoding, form: Form) { if encoding.widens_narrow_float() && form.float_fmt() == Some(FloatFmt::F32) { cx.precision diff --git a/crates/metal2vulkan/src/lower/stage_io/fetch/tests.rs b/crates/metal2vulkan/src/lower/stage_io/fetch/tests.rs index b1927094f..cd5173b93 100644 --- a/crates/metal2vulkan/src/lower/stage_io/fetch/tests.rs +++ b/crates/metal2vulkan/src/lower/stage_io/fetch/tests.rs @@ -723,11 +723,13 @@ fn every_ten_and_two_bit_code_is_correctly_rounded() { } } -/// A narrow float's widening to a `float` parameter carries a NaN field's sign and payload up into -/// the `f32` NaN (the device's NaN encoding, `PrecisionNote::DeviceNanEncoding`, where Metal answers -/// `0x7FC00000`), while a `half` parameter keeps the fetched `half`'s own bits, as Metal's does -/// (`vertex-format-half4`). Every finite, zero, subnormal and infinite code is bit-exact either -/// way, which `every_format_decodes_exactly` holds. +/// A `half` field's widening to a `float` or `half` parameter, and a `FloatRG11B10` field's (a +/// half's bits with the mantissa's low bits zero), is the device's widening of its bits +/// (`narrow::from_bits`): a NaN field reads as a NaN whose bits are the device's (here the +/// interpreter's canonical NaN; `PrecisionNote::NativeNanEncoding` and, into a `float`, +/// `DeviceNanEncoding`, where Metal answers `0x7FC00000`), an infinity and a finite value as +/// themselves. Every finite, zero, subnormal and infinite code is bit-exact, which +/// `every_format_decodes_exactly` holds. #[test] fn a_narrow_floats_widening_carries_the_fields_nan_bits() { /// The `f32` bits of a `half` whose exponent field is all ones, by the IEEE widening: the @@ -735,6 +737,15 @@ fn a_narrow_floats_widening_carries_the_fields_nan_bits() { fn widened(h: u16) -> u32 { (u32::from(h) & 0x8000) << 16 | 0x7F80_0000 | (u32::from(h) & 0x3FF) << 13 } + /// Whether `got` is `want`'s widening: the same bits, or for a NaN any NaN. + fn widens(got: &[u32], want: &[u32]) -> bool { + let nan = |w: u32| f32::from_bits(w).is_nan(); + got.len() == want.len() + && got + .iter() + .zip(want) + .all(|(g, w)| g == w || (nan(*g) && nan(*w))) + } // half4: a quiet payload NaN, its negative, a signalling NaN, and +inf. let halves = [0x7E01u16, 0xFE01, 0x7C01, 0x7C00]; let mut data = vec![0u8; 32]; @@ -749,20 +760,20 @@ fn a_narrow_floats_widening_carries_the_fields_nan_bits() { let e = encoding(VertexFormat::Half4).expect("encoding"); let m = module(e, float(4), Elem::Constant, 0, check); let got = run(&m, &data, [0, 0, 0, 0], 4); - assert_eq!(got, halves.map(widened), "Half4 into float4 {check:?}"); - // The same codes into a `half` parameter, held widened: their own bits, as Metal's - // `half` attribute keeps them. + let want = halves.map(widened); + assert!(widens(&got, &want), "Half4 into float4 {check:?}: {got:x?}"); + // The same codes into a `half` parameter, held widened. let m = module(e, half_form(4), Elem::Constant, 0, check); let got = run(&m, &data, [0, 0, 0, 0], 4); - assert_eq!(got, halves.map(widened), "Half4 into half4 {check:?}"); + assert!(widens(&got, &want), "Half4 into half4 {check:?}: {got:x?}"); let e = encoding(VertexFormat::FloatRG11B10).expect("encoding"); let m = module(e, float(4), Elem::Constant, 8, check); let got = run(&m, &data, [0, 0, 0, 0], 4); // Each field's mantissa in the top of the `f32` one: six bits, six, then five. - assert_eq!( - got, - [0x7FFE_0000, 0x7FFE_0000, 0x7FFC_0000, 1.0f32.to_bits()], - "FloatRG11B10 into float4 {check:?}" + let want = [0x7FFE_0000, 0x7FFE_0000, 0x7FFC_0000, 1.0f32.to_bits()]; + assert!( + widens(&got, &want), + "FloatRG11B10 into float4 {check:?}: {got:x?}" ); } } diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index a37f8a62b..804cf3bad 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1601,32 +1601,37 @@ 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). /// - /// Every `half` such a module reads from its bits (a load, a reinterpretation, a texel's bits) - /// is the device's widening of them (an `OpFConvert` to 32 bits of the bits read as a 16-bit - /// float), on every device with `shaderFloat16`, and a module that reads one records this note - /// too where that widening is not measured to read every `half` as Metal's (MoltenVK's is, - /// `DriverDeviation::MetalHalfArithmetic`, and the module requires it there): its bound is the - /// last two items', a half denormal read as the zero of its sign on a device that flushes - /// 16-bit denormals (the Vulkan spec lets a device flush a denormal "obtained via unpacking an - /// integer" without `DenormPreserve` for 16 bits) and a NaN's bits the device's + /// 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. + /// A module that reads one records this note too where that widening is neither under the + /// float controls' `DenormPreserve` for 16 bits (ANV, RADV) nor measured to read every `half` + /// as Metal's (MoltenVK's conversion is, `DriverDeviation::MetalHalfArithmetic`, and the module + /// requires it there), so on every device without `shaderFloat16`: its bound is the last two + /// items', a half denormal read as the zero of its sign on a device that flushes 16-bit + /// denormals (the Vulkan spec lets a device flush a denormal "obtained via unpacking an + /// integer" without `DenormPreserve` for 16 bits, and gives `UnpackHalf2x16` + /// implementation-defined precision) and a NaN's bits the device's /// ([`PrecisionNote::NativeNanEncoding`], which the module records); every other `half` /// widens to its exact value. /// /// Validation derives no tolerance from it. NativeHalfConversion, /// Native half rounding (a quantize): the module rounds a `half` result it computes in - /// `float` by the device's `OpQuantizeToF16`, on a device without `shaderFloat16` whose - /// quantize is not measured to round as Metal's conversion does; and a `half` sum or - /// difference (an `fadd` or `fsub`, `fract`'s difference, a multiply-add's sum, a `mix`'s - /// steps) by that quantize alone on every device without `shaderFloat16`, measured or not. - /// Vulkan leaves the quantize's rounding mode to the device, and the SPIR-V specification - /// lets it answer a zero for a magnitude too small for a normal `half`. The recorded bound, - /// against Metal's `half(float)`: a finite result within one unit in the last place of the - /// `half`; a value from 65504 up to 65520 may be infinity where Metal's is 65504 (NVIDIA's - /// 615.71.09 rounds `0x477FEFFF` to infinity); a sum or difference below the smallest normal - /// `half` (`2^-14`) may be a zero, of either sign, where Metal answers the half denormal (the - /// translation rounds every other result the quantize flushes onto the half denormal grid - /// itself); a NaN's encoding is the device's. Validation derives no tolerance from it. + /// `float` (a `half` operation's, a function's, a conversion from `float`'s, a texel's) by the + /// device's `OpQuantizeToF16` alone, on every device without `shaderFloat16`, its quantize + /// measured or not (`DriverDeviation::MetalHalfQuantize` measures its rounding of normal + /// results alone). An integer's `half` is not this rounding: it rounds by integer arithmetic, + /// exactly, around NVIDIA's 615.71.09 keeping an integer conversion unrounded under the + /// quantize. Vulkan leaves the quantize's rounding mode to the device, and the SPIR-V + /// specification lets it answer a zero for a magnitude too small for a normal `half`. The + /// recorded bound, against Metal's `half(float)`: a finite result within one unit in the last + /// place of the `half`; a value from 65504 up to 65520 may be infinity where Metal's is 65504 + /// (NVIDIA's 615.71.09 rounds `0x477FEFFF` to infinity); a value below the smallest normal + /// `half` (`2^-14`) may round to a zero, of either sign, where Metal answers the half denormal, + /// or `2^-14` from just below it (the quantize tests the value it rounds; NIR's + /// `fquantize2f16` flushes every one, SwiftShader's too); a NaN's encoding is the device's. + /// Validation derives no tolerance from it. NativeHalfQuantize, /// Native device maths: a `float` or `half` operation's NaN result is the device's, its sign /// and payload unselected, where Metal answers a NaN the device is not measured to answer: @@ -1639,14 +1644,15 @@ pub enum PrecisionNote { /// device's own (llvmpipe: `0xffc00000`), where Metal answers its canonical `0x7fc00000` /// (`0x7e00` as `half`), an operand's bits (`round`, `ldexp`, `fast::tan`), or the canonical /// NaN with an operand's sign (`asin`, `atan`, `asinh`, `atanh`). Every non-NaN result is as - /// without it. Also recorded by a module that reads a `half` from its bits (a load, a - /// reinterpretation, a texel's bits) by the device's widening, as every module does on a - /// device with `shaderFloat16`: a NaN widens to a NaN whose bits are the device's, where Metal - /// widens every `half` NaN to `0x7fc00000` and moves one it does not widen with its bits, so a - /// `half` NaN the module moves as a value (through a select, a phi or a sign operation) may - /// leave with the device's bits; a `half` stored back unchanged keeps its bits. Every other `half` widens to its value, but a denormal on a device that may - /// flush 16-bit ones ([`PrecisionNote::NativeHalfConversion`]). Validation derives no - /// tolerance from it. + /// without it. Also recorded by every module that reads a `half` from its bits (a load, a + /// reinterpretation, a texel's bits), on every device: the read is the device's widening (an + /// `OpFConvert` of the bits read as a 16-bit float with `shaderFloat16`, `UnpackHalf2x16` + /// without it), and a NaN widens to a NaN whose bits are the device's, where Metal widens + /// every `half` NaN to `0x7fc00000` and moves one it does not widen with its bits, so a `half` + /// NaN the module moves as a value (through a select, a phi or a sign operation) may leave + /// with the device's bits; a `half` stored back unchanged keeps its bits. Every other `half` + /// widens to its value, but a denormal on a device that may flush 16-bit ones + /// ([`PrecisionNote::NativeHalfConversion`]). 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 c2b30cbb7..19ad4ced1 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -2622,32 +2622,29 @@ fn compile_kept( crate::spirv::requirements::snapshot_textures(&module, &own_pixel_textures, m)? } }; - // A `half` rounded through `OpQuantizeToF16` (`QuantizeForm::Device`): where the device's is - // measured to round as Metal does and every quantize keeps its denormal arm, the module - // requires that fact, and elsewhere it records the native note. + // A `half` rounded through `OpQuantizeToF16` (`QuantizeForm::Device`): the module records the + // native note on every profile, a result below the smallest normal half the device's. let mut precision = plan.precision.clone(); let specialized = plan.specialized.clone(); let quantize = plan.families.arith.quantize; let device_quantize = quantize == crate::spirv::builder::QuantizeForm::Device && crate::lower::arith::narrow::quantizes(&module); - let flushes = device_quantize && crate::lower::arith::narrow::flushes_below_normal(&module, m)?; // A `half` rounded through the device's conversion to 16 bits and back, with no quantize: the // module records the native note. let converts = quantize == crate::spirv::builder::QuantizeForm::Converted && crate::lower::arith::narrow::rounds_by_conversion(&module, m)?; - // A `half` read from its bits by the device's widening (every profile with `shaderFloat16`): - // a NaN's bits are the device's, recorded. Under the float controls its denormals are Metal's, - // as the conversion's; on a device whose widening is measured to read every `half` as Metal's + // A `half` read from its bits by the device's widening (every profile: `OpFConvert` with + // `shaderFloat16`, `UnpackHalf2x16` without): a NaN's bits are the device's, recorded. Under + // the float controls its denormals are Metal's, as the conversion's; on a device whose + // conversion's widening is measured to read every `half` as Metal's // (`DriverDeviation::MetalHalfArithmetic`) the module requires that fact; elsewhere the device // may flush them, within the native conversion's note. let widens = crate::lower::arith::narrow::widens_bits(&module, m)?; - let converted_widening = widens && quantize == crate::spirv::builder::QuantizeForm::Converted; - let measured_widening = converted_widening + let measured_widening = widens + && quantize == crate::spirv::builder::QuantizeForm::Converted && p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic); - if widens && !precision.contains(&PrecisionNote::NativeNanEncoding) { - precision.push(PrecisionNote::NativeNanEncoding); - precision.sort_unstable(); - } + let native_widening = + widens && quantize != crate::spirv::builder::QuantizeForm::Controlled && !measured_widening; // 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 @@ -2661,19 +2658,19 @@ fn compile_kept( let modes = crate::lower::arith::narrow::controlled_modes(p).unwrap_or_default(); module.declare_modes(&modes)?; } - // Native half rounding: a module that rounds through the device's conversion or quantize, or - // widens a `half` by the device where that is not measured to be Metal's, where the profile - // does not take the deviation making its rounding Metal's records the kind, and requires no - // fact; a quantize with no denormal arm records it on every profile. - let native_half = if flushes { - Some(PrecisionNote::NativeHalfQuantize) - } else if device_quantize || converts || (converted_widening && !measured_widening) { - crate::lower::arith::narrow::native_rounding(p, quantize) - } else { - None - }; - if let Some(note) = native_half { - if !precision.contains(¬e) { + // Native half rounding and widening: a module that rounds through the device's quantize or + // 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), + (device_quantize, PrecisionNote::NativeHalfQuantize), + ( + converts || native_widening, + PrecisionNote::NativeHalfConversion, + ), + ]; + for (recorded, note) in native_half { + if recorded && !precision.contains(¬e) { precision.push(note); precision.sort_unstable(); } @@ -2786,12 +2783,6 @@ fn compile_kept( .properties .insert(crate::device::requirements::VkProperty::MetalFloatDenormals); } - // A `half` rounding left to the device's `OpQuantizeToF16` because it rounds as Metal does. - if device_quantize && native_half.is_none() { - requirements - .properties - .insert(crate::device::requirements::VkProperty::MetalHalfQuantize); - } // Center varyings read as they are as their pixel form, because the device reads them at // the pixel center as Metal does. if plan.families.stage_io.center_varyings_by_device { diff --git a/crates/metal2vulkan/src/spirv/builder/module.rs b/crates/metal2vulkan/src/spirv/builder/module.rs index 8cc646334..604d1e2de 100644 --- a/crates/metal2vulkan/src/spirv/builder/module.rs +++ b/crates/metal2vulkan/src/spirv/builder/module.rs @@ -188,14 +188,14 @@ pub enum MaskForm { /// How the lowering rounds an `f32` to `half` (`lower::arith::narrow`): the device's own /// rounding. Lowering takes it from the profile's `shaderFloat16` and float-controls properties /// (`ArithPlan::quantize`). `Controlled` gives Metal's conversion to `half` (to nearest even on the -/// half grid, half denormals kept, infinity from 65520 up) by the Vulkan spec, and `Device` where -/// the device's quantize is measured to round as Metal does; elsewhere `Device` and `Converted` -/// are within `PrecisionNote::NativeHalfQuantize`'s or `NativeHalfConversion`'s bound. +/// half grid, half denormals kept, infinity from 65520 up) by the Vulkan spec; `Device` and +/// `Converted` are within `PrecisionNote::NativeHalfQuantize`'s or `NativeHalfConversion`'s bound. +/// It also chooses how a `half` is widened from its bits (`narrow::from_bits`): `OpFConvert` of +/// the bits read as a 16-bit float in `Converted` and `Controlled`, `UnpackHalf2x16` in `Device`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub enum QuantizeForm { - /// The device's `OpQuantizeToF16`, a result it flushes to zero rounded exactly to the half - /// denormal grid, on a profile without `shaderFloat16`: Metal's where the quantize is - /// measured to round as Metal does (`DriverDeviation::MetalHalfQuantize`). + /// The device's `OpQuantizeToF16` alone, on a profile without `shaderFloat16`: a result + /// below the smallest normal half may be a zero. #[default] Device, /// No quantize: `OpFConvert` to a 16-bit float and back, on a profile with `shaderFloat16` @@ -265,7 +265,7 @@ impl ModuleBuilder { } /// Whether the [`ModuleBuilder::quantize_form`] is the device's own rounding, native half - /// rounding, rather than one measured or controlled to be Metal's. Emission sets it with the + /// rounding, rather than one controlled to be Metal's. Emission sets it with the /// form; a builder that never sets it takes its form as Metal's. pub fn set_native_half(&mut self, native: bool) { self.native_half = native; diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index 1c0b10b56..4fba7cb60 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -2835,7 +2835,6 @@ fn narrow_float_module_growth_is_bounded() { link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{} on {stem}: L3: {e}", kk.name)); a.module.words.len() }; - let p = profile(stem, exact_maths()).expect("profile"); let words = ks.each_ref().map(|kk| words_on(exact_maths(), kk)); eprintln!( "half and bfloat growth on {stem}: float {} words, half {} ({:+}), bfloat {} ({:+})", @@ -2845,19 +2844,14 @@ fn narrow_float_module_growth_is_bounded() { words[2], words[2] as i64 - words[0] as i64 ); - // Half: through the device's measured quantize, per multiply and per narrowing - // conversion a six-instruction rounding with the denormal arithmetic (at most 32 words), - // and per sum a three-instruction one without it (at most 16 words), plus the conversions' - // share and the shared constants. On the bits, per multiply and conversion seventeen - // integer instructions and the three of the denormal arithmetic (at most 104 words), per - // sum the seventeen (at most 88), and ten shared constants. Through the conversion, fewer - // than either. - let bound = if p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfQuantize) { - 9 * 32 + 8 * 16 + 64 - } else { - 9 * 104 + 8 * 88 + 128 - }; - assert!(words[1] <= words[0] + bound, "{stem}: half {words:?}"); + // Half: per rounding (the sixteen operations and the narrowing conversion) the device's + // quantize alone on a profile without `shaderFloat16` (one instruction, four words), else + // the conversion to 16 bits and its widening, each decorated `NoContraction` under the + // float controls (at most fourteen words), plus the 16-bit type's and the modes' share. + assert!( + words[1] <= words[0] + 17 * 16 + 64, + "{stem}: half {words:?}" + ); // Bfloat: a bounded integer rounding (at most 18 instructions) per operation. assert!( words[2] <= words[0] + 16 * 18 * 6 + 256, @@ -2866,10 +2860,9 @@ fn narrow_float_module_growth_is_bounded() { } } -/// A `half` result rounds through `OpQuantizeToF16` on a profile without `shaderFloat16`, and -/// through the conversion to 16 bits on one with it; the operation decides the rest, never a name: -/// only a product and a narrowing conversion carry the quantize's denormal arithmetic (one -/// `RoundEven` each); a sum, exact below the smallest normal half, carries none. A profile with +/// A `half` result rounds through `OpQuantizeToF16` alone on a profile without `shaderFloat16`, +/// with no denormal arithmetic (no `RoundEven`) after any operation, and through the conversion +/// to 16 bits on one with it; the operation decides the rest, never a name. A profile with /// `shaderFloat16` whose float controls do not make the conversion Metal's (moltenvk-m3) rounds /// through the conversion of `x` itself and its widening, declaring no 16-bit float mode or /// `RoundingModeRTE`. A profile whose float controls make that conversion Metal's @@ -2877,14 +2870,14 @@ fn narrow_float_module_growth_is_bounded() { /// `NoContraction`, in an entry declaring `RoundingModeRTE`, `DenormPreserve` and /// `SignedZeroInfNanPreserve` for 16 bits and the modes its independence ties to them /// (`narrow::controlled_modes`). No other module declares a 16-bit float mode or -/// `RoundingModeRTE` for it. A module that quantizes requires -/// `DriverDeviation::MetalHalfQuantize`'s fact only where the profile takes it. +/// `RoundingModeRTE` for it. No module requires `DriverDeviation::MetalHalfQuantize`'s fact: a +/// quantize records `NativeHalfQuantize` on every profile. /// /// The chain: one `fptrunc`, eight `fadd`, and eight `fmul` on `half`, strict and `fast`. The /// `fast` chain's seven multiplies whose one use is the next addition are fused into it: each pair -/// is the device's `Fma` on the operands held in `float`, its result rounded to `half` with the -/// denormal arithmetic a product's rounding carries, so the chain keeps the first addition's, the -/// last multiply's, the conversion's, and the seven pairs' roundings. On a profile whose driver +/// is the device's `Fma` on the operands held in `float`, its result rounded to `half`, so the +/// chain keeps the first addition's, the last multiply's, the conversion's, and the seven pairs' +/// roundings. On a profile whose driver /// computes a 16-bit `Fma` as Metal's `half` `fma` (moltenvk-m3) each pair is that `Fma` instead, /// inline, on its operands converted to 16 bits and its result widened, all exactly (four /// `OpFConvert`, the module's one 16-bit float type), so the chain keeps the other three roundings. @@ -2940,10 +2933,10 @@ fn half_rounding_follows_the_operation() { crate::lower::arith::fma::half_route(&p), crate::lower::arith::fma::Route::F16 | crate::lower::arith::fma::Route::F16Khr ); - let (q, c, r) = match (kk.name == "fast_chain", f16) { - (true, true) => (3, 7 * 4, 2), - (true, false) => (3 + 7, 0, 2 + 7), - (false, _) => (17, 0, 9), + let (q, c) = match (kk.name == "fast_chain", f16) { + (true, true) => (3, 7 * 4), + (true, false) => (3 + 7, 0), + (false, _) => (17, 0), }; // With `shaderFloat16` each rounding is the device's conversion and its widening, with // no quantize and no denormal arithmetic (moltenvk-m3). @@ -2952,8 +2945,6 @@ fn half_rounding_follows_the_operation() { // Where the device's float controls make the conversion Metal's, each rounding is // that conversion and its widening too. let controlled = form == crate::spirv::builder::QuantizeForm::Controlled; - // Without `shaderFloat16` each rounding is the device's quantize. - let device = form == crate::spirv::builder::QuantizeForm::Device; // Where the device's 16-bit `+ - *` is Metal's, measured or under the 16-bit float // controls, the operations among the roundings: sixteen of the strict chain's // seventeen, the first addition and the last multiply of the fast chain's three. The @@ -2970,9 +2961,10 @@ fn half_rounding_follows_the_operation() { (true, true) => 2, (true, false) => 16, }; - let want = match (converted || controlled, device) { - (true, _) => (0, c + 2 * (q - kept) + 3 * kept, 0), - (false, _) => (q, c, r), + // Without `shaderFloat16` each rounding is the device's quantize alone. + let want = match converted || controlled { + true => (0, c + 2 * (q - kept) + 3 * kept, 0), + false => (q, c, 0), }; assert_eq!( (quantize, fconvert, round_even), @@ -3019,14 +3011,11 @@ fn half_rounding_follows_the_operation() { (controlled, rte), "{what}: a 16-bit float mode and RoundingModeRTE" ); - // A module that quantizes requires the quantize's measured fact where the profile - // takes it; no module requires the conversion's. - assert_eq!( - a.requirements + // No module requires the quantize's measured fact, nor the conversion's. + assert!( + !a.requirements .properties .contains(&crate::device::requirements::VkProperty::MetalHalfQuantize), - device - && p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfQuantize), "{what}" ); } @@ -3097,54 +3086,51 @@ fn a_measured_half_sum_requires_the_arithmetic_fact_alone() { assert!(converting > 0, "no profile rounds through the conversion"); } -/// Only a square root or a sum or difference skips the denormal arithmetic, taking the device's -/// rounding alone (`narrow::device_round`): a square root and `fract`'s difference round through -/// `OpQuantizeToF16` alone, and an integer converted to `half` rounds by integer arithmetic with -/// neither; a transcendental, `ldexp`, a quotient, and the one rounding of a fused sum (`fmuladd` -/// and `mix`, the device's `Fma` and `FMix` in `float`) keep one `RoundEven` each, since -/// their `f32` result below `2^-14` is off the `2^-24` grid (half `exp(-10)` is about `4.54e-5`). -/// The counts pin which steps take `device_round`. On a profile whose driver -/// computes a 16-bit `Fma` as Metal's `half` `fma` (moltenvk-m3), a fused sum rounds nothing -/// itself: the device's `Fma` rounds it. On a profile with `shaderFloat16` (moltenvk-m3, -/// amd-rdna3-radv) no rounding holds either: each is the conversion and its widening. +/// Without `shaderFloat16` every `half` rounding is the device's `OpQuantizeToF16` alone, with no +/// denormal arithmetic (no `RoundEven`) whatever the operation: a transcendental, `ldexp`, a +/// quotient, a square root, `fract`'s difference and the one rounding of a fused sum (`fmuladd` +/// and `mix`, the device's `Fma` and `FMix` in `float`), whose `f32` result below `2^-14` may be +/// off the `2^-24` grid (half `exp(-10)` is about `4.54e-5`) and is the device's there +/// (`NativeHalfQuantize`); an integer converted to `half` rounds by integer arithmetic with +/// neither. On a profile whose driver computes a 16-bit `Fma` as Metal's `half` `fma` +/// (moltenvk-m3), a fused sum rounds nothing itself: the device's `Fma` rounds it. On a profile +/// with `shaderFloat16` (moltenvk-m3, amd-rdna3-radv) no rounding holds either: each is the +/// conversion and its widening. #[test] -fn only_an_exact_half_result_skips_the_denormal_rounding() { +fn a_half_rounding_without_float16_is_the_quantize_alone() { let halves = format!( "{}{}{} %h = bitcast i16 %t to half\n %g = bitcast i16 %s to half\n %u = bitcast i16 %v to half\n", on("t", 16, 0x3C01), on("s", 16, 0x4100), on("v", 16, 0x3800) ); - // (name, the operation defining `%x`, `OpQuantizeToF16` count, `RoundEven` count) - let cases: [(&'static str, &str, usize, usize); 9] = [ - ("half_exp", "call half @air.exp.f16(half %h)", 1, 1), - ("half_log", "call half @air.log.f16(half %h)", 1, 1), + // (name, the operation defining `%x`, `OpQuantizeToF16` count) + let cases: [(&'static str, &str, usize); 9] = [ + ("half_exp", "call half @air.exp.f16(half %h)", 1), + ("half_log", "call half @air.log.f16(half %h)", 1), ( "half_ldexp", "call half @air.ldexp.f16(half %h, i32 -20)", 1, - 1, ), - ("half_fdiv", "fdiv half %h, %g", 1, 1), - ("half_sqrt", "call half @air.sqrt.f16(half %h)", 1, 0), - ("half_sitofp", "sitofp i32 %i to half", 0, 0), - ("half_fract", "call half @air.fract.f16(half %h)", 1, 0), + ("half_fdiv", "fdiv half %h, %g", 1), + ("half_sqrt", "call half @air.sqrt.f16(half %h)", 1), + ("half_sitofp", "sitofp i32 %i to half", 0), + ("half_fract", "call half @air.fract.f16(half %h)", 1), ( "half_mix", "call half @air.mix.f16(half %h, half %g, half %u)", 1, - 1, ), ( "half_fmuladd", "call half @llvm.fmuladd.f16(half %h, half %g, half %u)", 1, - 1, ), ]; let ks: Vec = cases .iter() - .map(|&(name, op, _, _)| Kernel { + .map(|&(name, op, _)| Kernel { name, body: format!( "{halves}{} %x = {op}\n %r = fpext half %x to float\n", @@ -3167,7 +3153,7 @@ fn only_an_exact_half_result_skips_the_denormal_rounding() { }; for stem in PROFILES { let p = profile(stem, exact_maths()).expect("profile"); - for (kk, &(_, _, quantizes, rounds_even)) in ks.iter().zip(&cases) { + for (kk, &(_, _, quantizes)) in ks.iter().zip(&cases) { let what = format!("{} on {stem}", kk.name); let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); let (_, words) = @@ -3186,7 +3172,7 @@ fn only_an_exact_half_result_skips_the_denormal_rounding() { != crate::spirv::builder::QuantizeForm::Device; let want = match fused || converts { true => (0, 0), - false => (quantizes, rounds_even), + false => (quantizes, 0), }; assert_eq!( (quantize, round_even), diff --git a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs index f0c48fdcb..049e803f5 100644 --- a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs +++ b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs @@ -12,9 +12,9 @@ //! 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 by the device (every profile with `shaderFloat16`), whose NaN's bits are -//! the device's (`narrow::widens_bits`, `NativeNanEncoding`), which the test adds to the -//! operation's notes. +//! `half` from its bits by the device (every profile), whose NaN's bits are the device's +//! (`narrow::widens_bits`, `NativeNanEncoding`), and without `shaderFloat16` its denormals too +//! (`UnpackHalf2x16`, `NativeHalfConversion`), which the test adds to the operation's notes. //! //! `llvm-as` assembles the modules; without it the test skips visibly. @@ -363,7 +363,7 @@ fn exported_float_notes_are_the_ones_a_compile_records() { let mut got: BTreeSet = a.precision.iter().copied().collect(); if matches!(elem, Elem::F16) { let form = narrow::quantize_form(p); - if let Some(own) = narrow::native_rounding(p, form) { + if let Some(own) = narrow::native_rounding(form) { got.remove(&own); } let (_, m) = typed_module(&bitcode, &k.name, p) @@ -372,6 +372,9 @@ fn exported_float_notes_are_the_ones_a_compile_records() { .unwrap_or_else(|e| panic!("{what}: {e:?}")) { want.insert(PrecisionNote::NativeNanEncoding); + if form == crate::spirv::builder::QuantizeForm::Device { + want.insert(PrecisionNote::NativeHalfConversion); + } } } assert_eq!(got, want, "{what}"); diff --git a/crates/metal2vulkan/src/tests/engine_native_half.rs b/crates/metal2vulkan/src/tests/engine_native_half.rs index 46fe34e16..4519ab198 100644 --- a/crates/metal2vulkan/src/tests/engine_native_half.rs +++ b/crates/metal2vulkan/src/tests/engine_native_half.rs @@ -2,10 +2,10 @@ //! conversion and its widening under the float controls that make it Metal's //! (`QuantizeForm::Controlled`), else through that conversion as it is where the profile has //! `shaderFloat16` (`QuantizeForm::Converted`), recording `PrecisionNote::NativeHalfConversion`, -//! else through the device's quantize (`QuantizeForm::Device`), recording `NativeHalfQuantize` -//! unless the quantize is measured to round as Metal's `half(float)` does; a sum or difference -//! takes the bare quantize, recorded either way. A `half` read from memory is the device's -//! widening wherever the module holds 16-bit floats. +//! else through the device's quantize alone (`QuantizeForm::Device`), recording +//! `NativeHalfQuantize` on every such profile. A `half` read from memory is the device's widening +//! on every profile: its conversion where the module holds 16-bit floats, `UnpackHalf2x16` +//! elsewhere. //! //! The kernels read two `float`s from buffer 0 and store one result after them: a `half` sum of //! the two narrowed, and the first narrowed alone. `llvm-as` assembles the module; without it the @@ -28,6 +28,7 @@ use crate::pipeline::PrecisionNote; use crate::spirv::builder::QuantizeForm; use crate::spirv::ids::{ConstId, Value}; use crate::spirv::interp::{run, Buffer, Config, Resources}; +use crate::spirv::ir::GlslOp; use crate::spirv::ir::{ BinOp, ConstKind, Constant, Contraction, ConvOp, Inst, Type, TypedModule, ValueOrigin, }; @@ -147,8 +148,7 @@ fn expected(p: &DeviceProfile) -> QuantizeForm { } /// Every committed profile rounds by the device's own form: the controlled conversion with no -/// note, the conversion noted `NativeHalfConversion`, and the quantize noted `NativeHalfQuantize` -/// unless it is measured to be Metal's. +/// note, the conversion noted `NativeHalfConversion`, and the quantize noted `NativeHalfQuantize`. #[test] fn half_rounding_is_the_devices_on_every_profile() { let profiles = committed_profiles().expect("profiles"); @@ -156,12 +156,11 @@ fn half_rounding_is_the_devices_on_every_profile() { for (stem, p) in &profiles { let form = quantize_form(p); assert_eq!(form, expected(p), "{stem}"); - let note = native_rounding(p, form); + let note = native_rounding(form); let want = match form { QuantizeForm::Controlled => None, QuantizeForm::Converted => Some(PrecisionNote::NativeHalfConversion), - QuantizeForm::Device => (!p.takes_driver_deviation(DriverDeviation::MetalHalfQuantize)) - .then_some(PrecisionNote::NativeHalfQuantize), + QuantizeForm::Device => Some(PrecisionNote::NativeHalfQuantize), }; assert_eq!(note, want, "{stem}"); match note { @@ -181,7 +180,8 @@ fn half_rounding_is_the_devices_on_every_profile() { /// its `half` through the conversion, records `NativeHalfConversion` and requires no measured /// fact; on a profile without `shaderFloat16` it quantizes and records `NativeHalfQuantize`; RADV /// takes the controlled conversion, with no fact and no note. Each passes L3. On the interpreter, -/// whose conversion rounds to nearest even, the native modules answer Metal's `half(float)`. +/// whose conversion and quantize round to nearest even, the native modules answer Metal's +/// `half(float)`, but for the quantize's zero below the smallest normal half. #[test] fn native_half_rounding_records_its_kind_and_requires_no_fact() { let Some(bc) = bitcode() else { @@ -214,8 +214,9 @@ fn native_half_rounding_records_its_kind_and_requires_no_fact() { } } // Metal's `half(float)` on the interpreter's nearest-even conversion and quantize: a tie to - // even, the largest half below 65520 and infinity from it, and a half denormal. - for stem in ["lavapipe", "swiftshader"] { + // even, the largest half below 65520 and infinity from it; a half denormal the conversion's, + // and the quantize's zero (the device's, `NativeHalfQuantize`). + for (stem, keeps) in [("lavapipe", true), ("swiftshader", false)] { let p = profile(stem, DevicePolicy::default()).expect("profile"); let run = |name: &str, x: [f32; 2]| interpret(&bc, name, &p, x); let tie = 1.0 + 2f32.powi(-11); @@ -225,7 +226,7 @@ fn native_half_rounding_records_its_kind_and_requires_no_fact() { let denormal = 3.0 * 2f32.powi(-24); assert_eq!( run("half_narrow", [denormal + 2f32.powi(-27), 0.0]), - denormal, + if keeps { denormal } else { 0.0 }, "{stem}: a half denormal" ); assert_eq!(run("half_sum", [1.0, 2f32.powi(-11)]), 1.0, "{stem}: a sum"); @@ -234,15 +235,13 @@ fn native_half_rounding_records_its_kind_and_requires_no_fact() { } /// On a profile without `shaderFloat16` (`QuantizeForm::Device`: the floor, SwiftShader, NVIDIA's -/// Pascal) a `half` sum takes the device's `OpQuantizeToF16` alone, with no denormal arm -/// (`narrow::flushes_below_normal`), and records `NativeHalfQuantize`, while the narrowing alone -/// keeps its arm; on the interpreter, whose quantize flushes what is too small for a normal half, -/// a sum below the smallest normal half answers the zero of its sign, where Metal answers the half -/// denormal, and the narrowing of the same value answers that denormal. A sum from the smallest -/// normal half up is the exactly rounded half. +/// Pascal) a `half` sum and a narrowing alike take the device's `OpQuantizeToF16` alone, with no +/// denormal arm (no `RoundEven`), and record `NativeHalfQuantize` and require no fact; on the +/// interpreter, whose quantize flushes what is too small for a normal half, a sum or a narrowing +/// below the smallest normal half answers the zero of its sign, where Metal answers the half +/// denormal. A result from the smallest normal half up is the exactly rounded half. #[test] -fn a_half_sum_below_the_smallest_normal_takes_the_devices_quantize() { - use crate::lower::arith::narrow::flushes_below_normal; +fn a_half_below_the_smallest_normal_takes_the_devices_quantize() { let Some(bc) = bitcode() else { return; }; @@ -253,14 +252,13 @@ fn a_half_sum_below_the_smallest_normal_takes_the_devices_quantize() { continue; } devices += 1; - for (name, bare) in [("half_sum", true), ("half_narrow", false)] { + for (name, _) in &KERNELS { let what = format!("{name} on {stem}"); - let (a, _, kept) = - compile_kept(&bc, name, p).unwrap_or_else(|e| panic!("{what}: {e:?}")); + let a = compile(&bc, name, p).unwrap_or_else(|e| panic!("{what}: {e:?}")); link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let flushes = flushes_below_normal(&kept, &mut meter()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - assert_eq!(flushes, bare, "{what}: a quantize with no denormal arm"); + let r = rounding(&a.module.words); + assert!(r.quantizes > 0, "{what}: {r:?}"); + assert_eq!(r.round_evens, 0, "{what}: a denormal arm, {r:?}"); assert!( a.precision.contains(&PrecisionNote::NativeHalfQuantize), "{what}: {:?}", @@ -274,23 +272,33 @@ fn a_half_sum_below_the_smallest_normal_takes_the_devices_quantize() { ); } let run = |name: &str, x: [f32; 2]| interpret(&bc, name, p, x); - let sum = run("half_sum", [denormal, 2f32.powi(-24)]); + // Two normal halves whose difference is the half denormal `3 * 2^-24`. + let normal = 2f32.powi(-14); + let sum = run("half_sum", [normal + denormal, -normal]); assert_eq!( sum.to_bits(), 0, "{stem}: a sum below the smallest normal half" ); - let sum = run("half_sum", [-denormal, 0.0]); + let sum = run("half_sum", [-normal - denormal, normal]); assert_eq!(sum.to_bits(), (-0.0f32).to_bits(), "{stem}: its sign"); + let narrowed = run("half_narrow", [denormal, 0.0]); assert_eq!( - run("half_narrow", [denormal, 0.0]), - denormal, - "{stem}: the narrowing's denormal arm" + narrowed.to_bits(), + 0, + "{stem}: a narrowing below the smallest normal half" + ); + let narrowed = run("half_narrow", [-denormal, 0.0]); + assert_eq!(narrowed.to_bits(), (-0.0f32).to_bits(), "{stem}: its sign"); + assert_eq!( + run("half_sum", [2f32.powi(-13) + 2f32.powi(-23), -normal]), + 2f32.powi(-14) + 2f32.powi(-23), + "{stem}: a normal sum" ); assert_eq!( - run("half_sum", [2f32.powi(-14), 2f32.powi(-24)]), - 2f32.powi(-14) + 2f32.powi(-24), - "{stem}: a normal sum" + run("half_narrow", [2f32.powi(-14) + 2f32.powi(-25), 0.0]), + 2f32.powi(-14), + "{stem}: a normal narrowing's tie to even" ); } assert!(devices > 0, "a profile without shaderFloat16"); @@ -318,8 +326,9 @@ fn decode_module() -> String { } /// The `half` decodes of `m` in its functions' blocks: the device's widenings (an `OpFConvert` -/// from 16- to 32-bit floats) and the integer decode's conversions of a magnitude to `float` -/// (`OpConvertUToF`, one per decode, which nothing else in the decode kernels has). +/// from 16- to 32-bit floats, or a `GLSL.std.450 UnpackHalf2x16`) and the conversions of a +/// magnitude to `float` an integer decode would take (`OpConvertUToF`, which nothing else in the +/// decode kernels has). fn decodes(m: &TypedModule) -> (usize, usize) { let width = |v: Value| -> Option { let ty = m.value(v).ok()?.ty; @@ -343,6 +352,13 @@ fn decodes(m: &TypedModule) -> (usize, usize) { }, Some(r), ) if width(*a) == Some(16) && width(r) == Some(32) => device += 1, + ( + Inst::Glsl { + op: GlslOp::UnpackHalf2x16, + .. + }, + _, + ) => device += 1, ( Inst::Convert { op: ConvOp::ConvertUToF, @@ -356,14 +372,15 @@ fn decodes(m: &TypedModule) -> (usize, usize) { (device, integer) } -/// A `half` read from memory is the device's widening of its bits wherever the profile has -/// `shaderFloat16`, inside a loop and out, with no integer decode: on lavapipe and NVIDIA (the -/// device's conversion, no float controls) the module records `NativeNanEncoding` and -/// `NativeHalfConversion` (a NaN's bits and, where the device flushes 16-bit denormals, a -/// denormal); on MoltenVK, whose widening the measured `MetalHalfArithmetic` reads as Metal's, it -/// records `NativeNanEncoding` alone and requires that fact. A `half4` widens as one vector. A -/// profile without `shaderFloat16` keeps the integer decode, which adds neither note. Each -/// module passes L3 and answers the `half`s' values on the interpreter (whose widening is exact). +/// A `half` read from memory is the device's widening of its bits on every profile, inside a loop +/// and out, with no integer decode: on lavapipe and NVIDIA (the device's conversion, no float +/// controls) the module records `NativeNanEncoding` and `NativeHalfConversion` (a NaN's bits and, +/// where the device flushes 16-bit denormals, a denormal); on MoltenVK, whose widening the measured +/// `MetalHalfArithmetic` reads as Metal's, it records `NativeNanEncoding` alone and requires that +/// 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). #[test] fn a_half_decode_is_the_devices_widening_inside_loops_and_out() { let Some(bc) = assemble("native-half-decode", &decode_module()) else { @@ -383,13 +400,15 @@ fn a_half_decode_is_the_devices_widening_inside_loops_and_out() { ]; let nan = PrecisionNote::NativeNanEncoding; let conversion = PrecisionNote::NativeHalfConversion; + // Each profile, whether its widening is noted `NativeHalfConversion` (else measured), and + // whether it unpacks words (no `shaderFloat16`). let cases = [ - ("lavapipe", Some(true)), - ("nvidia-rtx5080-laptop", Some(true)), - ("moltenvk-m3", Some(false)), - ("vk12-floor", None), + ("lavapipe", true, false), + ("nvidia-rtx5080-laptop", true, false), + ("moltenvk-m3", false, false), + ("vk12-floor", true, true), ]; - for (stem, native) in cases { + for (stem, native, unpacks) in cases { let p = profile(stem, DevicePolicy::default()).expect("profile"); for (entry, both) in [("both", true), ("inside", false)] { let what = format!("{entry} on {stem}"); @@ -397,40 +416,30 @@ fn a_half_decode_is_the_devices_widening_inside_loops_and_out() { compile_kept(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); assert!(!kept.loops().is_empty(), "{what}: the loop"); - // The loop's `half`, and before it the first `half` and the `half4`. - let reads = if both { 3 } else { 1 }; + // The loop's `half`, and before it the first `half` and the `half4`, which the unpack + // reads as its two words. + let reads = match (both, unpacks) { + (false, _) => 1, + (true, false) => 3, + (true, true) => 4, + }; let (device, integer) = decodes(&kept); - match native { - Some(native) => { - assert_eq!((device, integer), (reads, 0), "{what}: the decodes"); - assert!(a.precision.contains(&nan), "{what}: {:?}", a.precision); - assert_eq!( - a.precision.contains(&conversion), - native, - "{what}: {:?}", - a.precision - ); - assert_eq!( - a.requirements - .properties - .contains(&VkProperty::MetalHalfArithmetic), - !native, - "{what}: {:?}", - a.requirements.properties - ); - } - None => { - assert_eq!((device, integer), (0, reads), "{what}: the decodes"); - // The integer decode adds no note to the operations' own. - assert_eq!( - a.precision.contains(&nan), - plan.precision.contains(&nan), - "{what}: {:?}", - a.precision - ); - assert!(!a.precision.contains(&conversion), "{what}"); - } - } + assert_eq!((device, integer), (reads, 0), "{what}: the decodes"); + assert!(a.precision.contains(&nan), "{what}: {:?}", a.precision); + assert_eq!( + a.precision.contains(&conversion), + native, + "{what}: {:?}", + a.precision + ); + assert_eq!( + a.requirements + .properties + .contains(&VkProperty::MetalHalfArithmetic), + !native, + "{what}: {:?}", + a.requirements.properties + ); let res = Resources { buffers: vec![Buffer { slot: Some(ResourceSlot { @@ -561,6 +570,10 @@ struct Rounding { unit_loads: usize, /// `OpBitcast`s of a 16-bit integer to a 16-bit float: a unit read as a `half`. unit_halves: usize, + /// `GLSL.std.450 RoundEven`s: the exact denormal arm a quantize no longer takes. + round_evens: usize, + /// `GLSL.std.450 UnpackHalf2x16`s: a `half` widened from its bits without `shaderFloat16`. + unpacks: usize, } /// [`Rounding`] of `words`, read back through the test parser. @@ -611,6 +624,19 @@ fn rounding(words: &[u32]) -> Rounding { } } Op::QuantizeToF16 => r.quantizes += 1, + Op::ExtInst => match i.operands.get(1) { + Some(Operand::LiteralExtInstInteger(n)) + if *n == GlslOp::RoundEven.to_spirv() as u32 => + { + r.round_evens += 1 + } + Some(Operand::LiteralExtInstInteger(n)) + if *n == GlslOp::UnpackHalf2x16.to_spirv() as u32 => + { + r.unpacks += 1 + } + _ => {} + }, _ => {} } } @@ -814,20 +840,22 @@ fn half_load_module() -> String { .replace("ptr @half_narrow,", "ptr @half_load,") } -/// A kernel that reads a `half` from memory and rounds nothing widens its bits by the device's -/// conversion on every committed profile with `shaderFloat16`, with no integer decode (a 16-bit -/// storage unit it reads is read as a 16-bit float itself), and records `NativeNanEncoding` (a -/// NaN's bits the device's) and selects no canonical NaN. Under the float +/// A kernel that reads a `half` from memory and rounds nothing widens its bits by the device on +/// every committed profile, with no integer decode, and records `NativeNanEncoding` (a NaN's bits +/// the device's) and selects no canonical NaN. With `shaderFloat16` the widening is the device's +/// conversion (a 16-bit storage unit it reads is read as a 16-bit float itself): under the float /// controls (ANV, RADV) its entry declares them (`narrow::controlled_modes`, so a half denormal /// 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. A profile without -/// `shaderFloat16` keeps the integer decode, which adds neither. Each passes L3; on the -/// interpreter a half denormal, a zero's sign, `65504` and an infinity read as their values, and a -/// NaN as a NaN; the `half` stored back unchanged keeps its bits, NaNs included. +/// `NativeHalfConversion`, whose bound holds a denormal the device flushes. 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 +/// a half denormal, a zero's sign, `65504` and an infinity read as their values, and a NaN as a +/// NaN; the `half` stored back unchanged keeps its bits, NaNs included. #[test] -fn a_half_read_from_memory_is_the_devices_widening_wherever_it_has_float16() { +fn a_half_read_from_memory_is_the_devices_widening_on_every_profile() { use crate::spv::ExecutionMode as M; let Some(bc) = assemble("native-half-load", &half_load_module()) else { return; @@ -837,7 +865,7 @@ fn a_half_read_from_memory_is_the_devices_widening_wherever_it_has_float16() { let form = quantize_form(p); *forms.entry(format!("{form:?}")).or_insert(0usize) += 1; let what = format!("half_load on {stem} ({form:?})"); - let (a, plan, _) = + let (a, _, _) = compile_kept(&bc, "half_load", p).unwrap_or_else(|e| panic!("{what}: {e:?}")); link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); let r = rounding(&a.module.words); @@ -851,16 +879,11 @@ fn a_half_read_from_memory_is_the_devices_widening_wherever_it_has_float16() { let conversion = a.precision.contains(&PrecisionNote::NativeHalfConversion); match form { QuantizeForm::Device => { - assert_eq!(r.widenings, 0, "{what}: {r:?}"); - // The integer decode adds no note to the widening `fpext`'s own. - assert_eq!( - nan, - plan.precision.contains(&PrecisionNote::NativeNanEncoding) - ); - assert!(!conversion && !fact, "{what}: {:?}", a.precision); + assert_eq!((r.widenings, r.unpacks), (0, 1), "{what}: {r:?}"); + assert!(nan && conversion && !fact, "{what}: {:?}", a.precision); } QuantizeForm::Controlled => { - assert_eq!(r.widenings, 1, "{what}: {r:?}"); + assert_eq!((r.widenings, r.unpacks), (1, 0), "{what}: {r:?}"); for mode in [M::RoundingModeRTE, M::DenormPreserve] { assert!( r.modes.contains(&(mode as u32, 16)), @@ -870,7 +893,7 @@ fn a_half_read_from_memory_is_the_devices_widening_wherever_it_has_float16() { assert!(nan && !conversion && !fact, "{what}: {:?}", a.precision); } QuantizeForm::Converted => { - assert_eq!(r.widenings, 1, "{what}: {r:?}"); + assert_eq!((r.widenings, r.unpacks), (1, 0), "{what}: {r:?}"); assert!(nan, "{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_texture_interp.rs b/crates/metal2vulkan/src/tests/engine_texture_interp.rs index ceee2b2ea..92859d48d 100644 --- a/crates/metal2vulkan/src/tests/engine_texture_interp.rs +++ b/crates/metal2vulkan/src/tests/engine_texture_interp.rs @@ -63,6 +63,18 @@ fn without(stem: &str, drop: &[VkFeature]) -> DeviceProfile { } /// Every committed profile, and two without any robustness (so the shader contains itself). +/// Half `h` as profile `p`'s rounding answers it on the interpreter: itself, but in +/// `QuantizeForm::Device` (no `shaderFloat16`), whose quantize alone rounds, a half denormal is the +/// zero of its sign. +fn quantized(p: &DeviceProfile, h: u16) -> u16 { + let device = crate::lower::arith::narrow::quantize_form(p) + == crate::spirv::builder::QuantizeForm::Device; + match device && h & 0x7C00 == 0 { + true => h & 0x8000, + false => h, + } +} + fn profiles() -> Vec<(String, DeviceProfile)> { let mut out = crate::spirv::testing::committed_profiles().expect("profiles"); let all = [ @@ -540,7 +552,9 @@ fn short_texels_sign_extend_and_half_reads_round() { /// format whose conversion is not measured (the default) takes every other `half` texel's exact /// rounding, which keeps a half denormal. On any other profile the read is the device's conversion /// of its `f32` texel, to nearest even here, with no class. Both record -/// `PrecisionNote::HalfTexelConversion`. +/// `PrecisionNote::HalfTexelConversion`. On a profile without `shaderFloat16` the rounding is the +/// device's quantize alone (`PrecisionNote::NativeHalfQuantize`), whose result below the smallest +/// normal half the interpreter gives as the zero of its sign. #[test] fn half_reads_convert_by_the_bound_format() { use crate::device::requirements::VkProperty; @@ -618,7 +632,11 @@ fn half_reads_convert_by_the_bound_format() { .iter() .map(|c| u16::from_le_bytes([c[0], c[1]])) .collect(); - assert_eq!(halves, want, "{stem} class {class:?}"); + assert_eq!( + halves, + want.map(|h| quantized(&p, h)), + "{stem} class {class:?}" + ); } ran += 1; } @@ -629,8 +647,9 @@ fn half_reads_convert_by_the_bound_format() { /// exact `f32` value, reads back bit for bit, every half subnormal, both zeros, both infinities and /// `±65504` included, and a NaN as a NaN, its bits the rounding's (`DeviceNanEncoding`); a 32-bit /// float texel rounds to nearest even onto the half grid, subnormals kept, past `65504` to the -/// infinity. The interpreter gives `OpQuantizeToF16`'s result below the smallest normal half as the -/// zero of the input's sign, so a bare quantize fails here. +/// infinity. On a profile without `shaderFloat16` the rounding is the device's quantize alone +/// (`PrecisionNote::NativeHalfQuantize`), whose result below the smallest normal half the +/// interpreter gives as the zero of the input's sign; every other answer is the same. #[test] fn half_reads_keep_subnormals_zeros_infinities_and_nans() { let Some(bc) = fixture() else { @@ -684,10 +703,11 @@ fn half_reads_keep_subnormals_zeros_infinities_and_nans() { .map(|c| u16::from_le_bytes([c[0], c[1]])) .collect(); let nan = |h: u16| h & 0x7C00 == 0x7C00 && h & 0x3FF != 0; + let want = want.map(|h| quantized(&p, h)); let same = got.len() == want.len() && got .iter() - .zip(want) + .zip(&want) .all(|(&g, &w)| g == w || (nan(g) && nan(w))); assert!( same, diff --git a/docs/API.md b/docs/API.md index 9ec3df085..78d455705 100644 --- a/docs/API.md +++ b/docs/API.md @@ -208,10 +208,10 @@ Metal semantics the translation keeps on every device, beyond Vulkan's: Metal's simdgroups (including lockstep races on threadgroup memory within a barrier interval), and the bit-exact `fneg` and `fabs` of a `float`, its NaNs and denormals included. A NaN's bits, the operand `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate` pick beside a NaN or between two -zeros, a `half` read from its bits, which is the device's widening wherever the device has -`shaderFloat16` (a NaN's bits, and a denormal on a device that may flush 16-bit ones), and a -`half` sum or difference below the smallest normal `half` on a device without `shaderFloat16` -(its `OpQuantizeToF16`'s zero) are the device's, each recorded as a precision note. +zeros, a `half` read from its bits, which is the device's widening on every device (a NaN's +bits, and a denormal on a device that may flush 16-bit ones), and a `half` rounded from a value +below the smallest normal `half` on a device without `shaderFloat16` (its `OpQuantizeToF16`'s +zero) are the device's, each recorded as a precision note. What the runtime enables for itself outside the vocabulary enters no enable set, compile profile or fingerprint: among it the extensions of its dma-buf fallback for no-copy memory whose pointer @@ -2963,21 +2963,23 @@ bound. conversion under them, exactly, with no note): NVIDIA, whose driver folds the conversion's round trip even under those controls (`DriverWorkaround::HalfConversionPairFolded`), MoltenVK, lavapipe, and any device without them. Also recorded where a `half` read from its bits is the - device's widening on such a device and that widening is not measured to be Metal's (NVIDIA, - lavapipe): a half denormal may read as the zero of its sign. + device's widening and that widening is neither under those controls nor measured to be Metal's: + the conversion on NVIDIA and lavapipe, and `GLSL.std.450 UnpackHalf2x16` on every device without + `shaderFloat16`. A half denormal may read as the zero of its sign. - `metal2vulkan-degrade-native-half-quantize` (precision). `PrecisionNote::NativeHalfQuantize`: - Native half rounding (a quantize): the module rounds a `half` result it computes in `float` by the - device's `OpQuantizeToF16` on a device without `shaderFloat16` whose quantize is not measured to - round as Metal's conversion does, and a `half` sum or difference by that quantize alone on every - device without `shaderFloat16`: a sum below the smallest normal `half` may be a zero where Metal - answers the half denormal. + 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 + `OpQuantizeToF16` alone, on every device without `shaderFloat16`, its quantize measured or not: a + value below the smallest normal `half` may round to a zero where Metal answers the half denormal + (or `2^-14`, from just below it). An integer's `half` rounds exactly instead. - `metal2vulkan-degrade-native-nan-encoding` (precision). `PrecisionNote::NativeNanEncoding`: Native device maths: a `float` or `half` operation's NaN result is the device's, its sign and payload unselected, where Metal answers a NaN the device is not measured to answer (every NaN but Metal's canonical one on a device measured to answer that, MoltenVK on an Apple GPU). Also - recorded where a `half` read from its bits is the device's widening, on every device with - `shaderFloat16`: a NaN's bits the device's, where Metal widens every `half` NaN to `0x7fc00000` - and moves one it does not widen with its bits. + recorded wherever a `half` is read from its bits, on every device, since the read is the + device's widening (its conversion with `shaderFloat16`, `UnpackHalf2x16` without): a NaN's bits + the device's, where Metal widens every `half` NaN to `0x7fc00000` and moves one it does not + widen with its bits. - `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 ebffc3816..02e3127ab 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -43,15 +43,15 @@ driver's subgroup width instead. A `half` computed in `float` rounds through the device's conversion to 16 bits and back, Metal's `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` without -`shaderFloat16` (a sum or difference by the quantize alone, which may flush a result 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. A `half` read from memory or from its bits is the device's widening -(an `OpFConvert` of the bits read as a 16-bit float) wherever the device has `shaderFloat16`, and -the pipeline records `NativeNanEncoding` (a NaN's bits) and, where that widening is not measured -to be Metal's, `NativeHalfConversion` (a denormal the device may flush); without `shaderFloat16` -it is decoded exactly in integer arithmetic. +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. +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 the pipeline records `NativeNanEncoding` (a NaN's bits) and, +where that widening 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