From d8d76438cda1368db620f47dc9550a6e647ffecb Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 3 Nov 2026 03:20:57 -0800 Subject: [PATCH] Hold the extended-range lanes to DevicePackConversion's bound, against Metal's answers The eleven extended-range and padded lane tests compared the device's texels, reads and samples digest for digest with Metal's. A shader's conversion of such a texel is the device's own (no Vulkan format holds them), which PrecisionNote::DevicePackConversion records and the runtime announces. Its documented bound allows a code within one of Metal's (two for R10Unorm_X6_sRGB's and RGB10A2Unorm_sRGB's colour below 0.0031308), a linear read within one f32 ulp, an sRGB twin's decoded value within half a 2^-13 step of Metal's table (1.64 steps for those two formats) beyond the Pow's bound, a half within one half ulp, and a NaN's code the device's. So the digests did not match on the M3 Max (MoltenVK) or the RTX 5080, and these tests stayed red on both. Each test now checks every value within that bound of Metal's own answer, and each bit Metal does not read equal to Metal's. It asserts that the note was announced wherever a value moved, and it still pins Metal's answer by its digest: - xr_codes (new): the shared helpers. It splits a texel into codes and the bits Metal does not read, holds codes, reads, sRGB steps and halves to the bound, gives Metal's half rounding (ties away from zero), and loads Metal's M3 Max macOS 27.0.1 answer from a conformance recording. as_metal_reads replaces the device's lanes that are within the bound by Metal's values, so a digest of the rest can still be compared. - extended_range_targets: draws compared code by code, two-plane reads through the nearest code of Metal's read; clears' reads through the cleared codes. A CPU test holds the models to Metal's digests. - extended_range_planes: joined and split texels within a code. - extended_range_blends: one-zero blends against a model of Metal's blend, which clamps the source to its range, alpha to [0, 1] and a NaN to the low end. A CPU test holds the model to Metal's digests. - padded_loads: every drawn word within a code of a model of Metal's store (a float output rounded to half toward zero, then the write code), held to Metal's digests by a CPU test. - rgb10a2_srgb: reads, writes, nearest samples and stores compared with the rgb10a2-srgb-* recordings, whose digests are asserted equal to the test's constants. Linear samples run and are counted, their blend being the unbounded BicubicFilterArithmetic, which is asserted to be announced. - two_plane_samples: nearest cases against the xr-two-plane-samples-* recordings, a half case against the float recording. - extended_range_two_planes: plane reads and in-view buffer words within the bound, through as_metal_reads. No note set changes. Test code only; no version bump. Verified on the Apple M3 Max (MoltenVK 1.4.2, macOS 27.0.1): every test in the seven files passes (34 of 34), including the eleven that were red. In the run before the bound was corrected, both rgb10a2_srgb tests failed at exactly three words each, the shape the bound now states. Clippy (all targets, all features, --cfg m2v_gpu) is clean. (cherry picked from commit f097486e7a84a116c2c119114db4b665eb045600) (cherry picked from commit 4c972dab0c58ef908b7ac6c826afb8a5e07f1732) --- .../src/runtime_lane.rs | 2 + .../src/runtime_lane/extended_range_blends.rs | 121 +++++-- .../src/runtime_lane/extended_range_planes.rs | 43 ++- .../runtime_lane/extended_range_targets.rs | 203 ++++++++++-- .../runtime_lane/extended_range_two_planes.rs | 220 ++++++++++--- .../src/runtime_lane/padded_loads.rs | 97 +++++- .../src/runtime_lane/rgb10a2_srgb.rs | 283 ++++++++++++---- .../src/runtime_lane/two_plane_samples.rs | 63 +++- .../src/runtime_lane/xr_codes.rs | 303 ++++++++++++++++++ 9 files changed, 1155 insertions(+), 180 deletions(-) create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/xr_codes.rs diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index dd1a23873..e285c815b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -889,6 +889,8 @@ mod word_samples_msaa; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod wrapped_buffers; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod xr_codes; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod ycbcr_device_reads; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod ycbcr_in_place; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/extended_range_blends.rs b/crates/metal2vulkan-validation/src/runtime_lane/extended_range_blends.rs index c6a45b8ea..767c452a3 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/extended_range_blends.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/extended_range_blends.rs @@ -28,6 +28,7 @@ use super::extended_range_targets::{ }; use super::resolves::{lane, lane_with, quiet, Lane, FULL, WHITE}; use super::two_plane_copies::Rng; +use super::xr_codes::{assert_announced, texel_within}; use super::{buffer_with, read_buffer}; use crate::candidate::runtime_samples::{library, shape}; use metal2vulkan::metal::format::{ClearRoute, ExtendedRange}; @@ -386,8 +387,10 @@ fn first_texels(got: &[u8], size: usize) -> String { /// Each format's blends of the probe's `half` outputs over its random texels, of source factor /// one, added, with destination factor zero, one, and one minus the source's alpha. Where the -/// blend computes nothing (one and zero) every format stores Metal's bytes, which is asserted. -/// Under one and one minus the source's alpha the function blends in the device's arithmetic, +/// blend computes nothing (one and zero) every format stores the source as a write encodes it, +/// which is asserted: each code within one of Metal's ([`one_zero_model`], which gives Metal's +/// digests), the bits Metal does not read Metal's, the device's encode +/// (`PrecisionNote::DevicePackConversion`, announced). Under one and one minus the source's alpha the function blends in the device's arithmetic, /// where Metal's compiler rounds each step to `half` (`extended-range-blend-source`): how many /// outputs differ from Metal's is printed, not asserted; the conformance suite's `xr-blend-*` /// cases hold Metal's bytes and each site the device's arithmetic moves. @@ -400,6 +403,8 @@ fn blends_of_half_outputs_into_extended_range_texels() { let size = (WIDTH as u64, HEIGHT as u64); let mut wrong = Vec::new(); let mut moved = Vec::new(); + // The texels and alpha bytes of the blends of one and zero within a code of Metal's. + let mut near = 0; let mut checked = 0; for (pf, probe) in FORMATS { let form = ExtendedRange::of(pf).expect("an extended-range format"); @@ -415,29 +420,53 @@ fn blends_of_half_outputs_into_extended_range_texels() { draw(&lane, &t, &halves, color).unwrap_or_else(|e| panic!("{case}: the pipeline: {e}")); let got = lane.read(&t, (0, 0), texel as u64, BlitOption::None); checked += 1; - // The device's arithmetic answers a blend that computes something. - let differs = match dst { - BlendFactor::Zero => &mut wrong, - _ => &mut moved, + let bytes: Vec = match alpha.is_empty() { + true => Vec::new(), + false => reads(&lane, &read, &t, size) + .chunks(16) + .map(|v| { + let a = f32::from_le_bytes([v[12], v[13], v[14], v[15]]); + (a * 255.0).round_ties_even() as u8 + }) + .collect(), }; + // A blend of one and zero stores the source, encoded by the device's conversion: each + // code within one of Metal's (the model's, which gives Metal's digests). + if dst == BlendFactor::Zero { + let (want, want_alpha) = one_zero_model(form, &halves); + let mut differ = 0; + for (g, w) in got.chunks(texel).zip(want.chunks(texel)) { + match (g == w, texel_within(form, g, w)) { + (true, _) => {} + (false, true) => near += 1, + (false, false) => differ += 1, + } + } + for (g, w) in bytes.iter().zip(&want_alpha) { + match (g == w, g.abs_diff(*w) <= 1) { + (true, _) => {} + (false, true) => near += 1, + (false, false) => differ += 1, + } + } + if differ > 0 { + wrong.push(format!( + "{case}: {differ} texels and alpha bytes past a code of Metal's, the first \ + texels {}", + first_texels(&got, texel) + )); + } + continue; + } + // The device's arithmetic answers a blend that computes something. if digest(&got) != metal(&format!("{case}.out0")) { - differs.push(format!( + moved.push(format!( "{case}.out0: the first texels {}", first_texels(&got, texel) )); } - if alpha.is_empty() { - continue; - } - let bytes: Vec = reads(&lane, &read, &t, size) - .chunks(16) - .map(|v| { - let a = f32::from_le_bytes([v[12], v[13], v[14], v[15]]); - (a * 255.0).round_ties_even() as u8 - }) - .collect(); - if digest(&bytes) != metal(&format!("{case}.outa")) { - differs.push(format!( + if !alpha.is_empty() && digest(&bytes) != metal(&format!("{case}.outa")) { + moved.push(format!( "{case}.outa: the first alpha bytes {:02x?}", &bytes[..8] )); @@ -449,7 +478,8 @@ fn blends_of_half_outputs_into_extended_range_texels() { } println!( "XR-BLENDS {name}: {checked} blends of {COUNT} texels checked, {} outputs of one and zero \ - and {} of the device's arithmetic differ from Metal", + past a code of Metal's ({near} texels and alpha bytes within one) and {} of the device's \ + arithmetic differ from Metal", wrong.len(), moved.len() ); @@ -458,6 +488,7 @@ fn blends_of_half_outputs_into_extended_range_texels() { "{} outputs differ from Metal", wrong.len() ); + assert_announced(&messages, near, "the blends of one and zero"); quiet(lane, &messages); } @@ -1118,3 +1149,53 @@ fn a_fetched_two_plane_attachment_written_unblended_stores_metals_write() { assert!(kept, "colors 1 and 2 changed on {name}"); quiet(lane, &messages); } + +/// Metal's texels after a blend of source factor one and destination factor zero of the probe's +/// `half` outputs `halves` into a target of `form`: each output clamped first as Metal's blend +/// clamps its source (a color lane to the codes 0 and 1022's values rounded to `half`, +/// `-0.7529296875` and `1.2509765625`, `BGRA10_XR_sRGB`'s to their tile values `-0.52734375` and +/// `1.6689453125`; alpha to `[0, 1]`; a NaN to the low end; `lower::arith::extended_range`'s +/// measured source range), then stored as a kernel write stores it, the destination's codes and +/// unread bits gone: plane 0's bytes and a two-plane form's alpha bytes. +fn one_zero_model(form: ExtendedRange, halves: &[u8]) -> (Vec, Vec) { + let (lo, hi) = match form { + ExtendedRange::Bgra10 { srgb: true } => (-1080.0 / 2048.0, 1709.0 / 1024.0), + _ => (-1542.0 / 2048.0, 1281.0 / 1024.0), + }; + let (mut plane, mut alpha) = (Vec::new(), Vec::new()); + for texel in halves.as_chunks::<8>().0 { + let color = [0, 1, 2, 3].map(|c| { + let x = half_value(u16::from_le_bytes([texel[2 * c], texel[2 * c + 1]])); + let (lo, hi) = if c == 3 { (0.0, 1.0) } else { (lo, hi) }; + f64::from(if x.is_nan() { lo } else { x.clamp(lo, hi) }) + }); + let raw = form.clear_texel(color, ClearRoute::ThroughHalf); + match form { + ExtendedRange::Bgra10 { .. } => { + plane.extend(raw.iter().flat_map(|&f| (f as u16).to_le_bytes())); + } + ExtendedRange::Planes { .. } => { + plane.extend(raw[0].to_le_bytes()); + alpha.push(raw[1] as u8); + } + _ => plane.extend(raw[0].to_le_bytes()), + } + } + (plane, alpha) +} + +/// The model of a blend of one and zero gives Metal's digests of each format's texels and alpha +/// bytes. +#[test] +fn the_one_zero_model_gives_metal_s_digests() { + let halves = halves(); + for (pf, probe) in FORMATS { + let form = ExtendedRange::of(pf).expect("an extended-range format"); + let (plane, alpha) = one_zero_model(form, &halves); + let case = format!("rt.{probe}.h.one_zero"); + assert_eq!(digest(&plane), metal(&format!("{case}.out0")), "{case}"); + if !alpha.is_empty() { + assert_eq!(digest(&alpha), metal(&format!("{case}.outa")), "{case}"); + } + } +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/extended_range_planes.rs b/crates/metal2vulkan-validation/src/runtime_lane/extended_range_planes.rs index 670124fc3..1c5be3861 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/extended_range_planes.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/extended_range_planes.rs @@ -19,8 +19,10 @@ //! of the 1,024 alpha values whose product lies just above a half). use super::degrade_notices::on_device; +use super::xr_codes::{assert_announced, texel_within}; use crate::air_library::AirLibrary; use metal2vulkan::error::DriverDeviation; +use metal2vulkan::metal::format::ExtendedRange; use metal2vulkan::metal::{PixelFormat, TextureUsage}; use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; @@ -305,8 +307,14 @@ fn metal( panic!("no Metal bytes of {kernel} {color:?} {joined:?} {texture}") } -/// The texel `got` and Metal's `want` part at, both as hex, or `None` where they are alike. -fn unlike_metal(got: &[u8], want: &[u8], texel: usize) -> Option { +/// The first texel (of `texel` bytes) of `got` that does not hold as Metal's `want` by `held`, both +/// as hex, or `None` where every texel holds. +fn unlike_metal( + got: &[u8], + want: &[u8], + texel: usize, + held: impl Fn(&[u8], &[u8]) -> bool, +) -> Option { if got == want { return None; } @@ -317,8 +325,7 @@ fn unlike_metal(got: &[u8], want: &[u8], texel: usize) -> Option { let at = got .chunks(texel) .zip(want.chunks(texel)) - .position(|(a, b)| a != b) - .expect("a differing texel"); + .position(|(a, b)| !held(a, b))?; let (a, b) = (at * texel, (at + 1) * texel); Some(format!( "texel ({}, {}) is {}, Metal's {}", @@ -356,10 +363,12 @@ fn the_inputs_and_the_outputs_are_the_harness_s() { /// Every output texture of both kernels, for every pairing of plane 0's and the joined texture's /// formats, holds Metal's bytes, the split's alpha plane where the device is measured to store -/// Metal's codes (the module docs). +/// Metal's codes (the module docs). The extended-range textures' codes are the device's conversion +/// of the `half`s the kernels move (`PrecisionNote::DevicePackConversion`, announced): each within +/// one of Metal's, the bits Metal does not read Metal's. #[test] fn two_extended_range_planes_join_and_split_as_metal_does() { - on_device(|device, _| { + on_device(|device, messages| { let measured = device .compile_device() .profile() @@ -367,7 +376,7 @@ fn two_extended_range_planes_join_and_split_as_metal_does() { let queue = device.new_command_queue().unwrap(); let join = state(device, "xr_planes_join"); let split = state(device, "xr_planes_split"); - let mut wrong = Vec::new(); + let (mut wrong, mut moved) = (Vec::new(), 0); for color in [PixelFormat::BGR10XR, PixelFormat::BGR10XRSRGB] { for joined in [PixelFormat::BGRA10XR, PixelFormat::BGRA10XRSRGB] { let plane = texture(device, color, &color_bytes()); @@ -388,7 +397,20 @@ fn two_extended_range_planes_join_and_split_as_metal_does() { "color" => texel_bytes(color), _ => texel_bytes(ALPHA), }; - if let Some(unlike) = unlike_metal(&bytes, want, texel as usize) { + let form = match what { + "joined" => ExtendedRange::of(joined), + "color" => ExtendedRange::of(color), + _ => None, + }; + let held = |g: &[u8], w: &[u8]| { + g == w || form.is_some_and(|form| texel_within(form, g, w)) + }; + moved += bytes + .chunks(texel as usize) + .zip(want.chunks(texel as usize)) + .filter(|(g, w)| g != w && held(g, w)) + .count(); + if let Some(unlike) = unlike_metal(&bytes, want, texel as usize, held) { let line = format!("{kernel} {color:?} {joined:?} {what}: {unlike}"); match what == "alpha" && !measured { true => { @@ -403,10 +425,15 @@ fn two_extended_range_planes_join_and_split_as_metal_does() { for line in &wrong { println!("XR-PLANES-DIFFERS {}: {line}", device.name()); } + println!( + "XR-PLANES {}: {moved} texels within the device's conversion of Metal's", + device.name() + ); assert!( wrong.is_empty(), "{} outputs differ from Metal", wrong.len() ); + assert_announced(messages, moved, "the joined and split planes"); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/extended_range_targets.rs b/crates/metal2vulkan-validation/src/runtime_lane/extended_range_targets.rs index 6a4d0bb35..a4bc3e488 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/extended_range_targets.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/extended_range_targets.rs @@ -34,6 +34,9 @@ //! their inputs, the stored texel and the model's. use super::resolves::{lane, quiet, Lane}; +use super::xr_codes::{ + assert_announced, codes, metal_read, nearest_code, read_within, texel_within, +}; use super::{buffer_with, read_buffer, WAIT}; use crate::air_library::AirLibrary; use crate::candidate::runtime_samples::{library, shape}; @@ -459,7 +462,11 @@ fn differences(got: &[u8], want: &[u8], size: usize, inputs: &[[f32; 4]]) -> Vec .collect() } -/// Each format's draws of the probe's outputs, `float` and `half`, store Metal's texels. +/// Each format's draws of the probe's outputs, `float` and `half`, store Metal's texels: each code +/// within one of Metal's and the bits Metal does not read Metal's, a two-plane target's codes +/// (through its kernel reads, each the code whose Metal read is nearest it) within one of Metal's +/// and each read within its bound of Metal's read of that code, where the conversion is the +/// device's (`PrecisionNote::DevicePackConversion`, announced). #[test] fn draws_store_metals_extended_range_texels() { let (messages, _cache, lane) = lane(); @@ -473,11 +480,8 @@ fn draws_store_metals_extended_range_texels() { let half_bytes: Vec = halves.iter().flat_map(|h| h.to_le_bytes()).collect(); assert_eq!(digest(&floats), SOURCE_FLOAT, "the probe's float outputs"); assert_eq!(digest(&half_bytes), SOURCE_HALF, "the probe's half outputs"); - let (write, read) = ( - kernel(&lane, "xr2p_write_half"), - kernel(&lane, "xr2p_read_float"), - ); - let mut wrong = Vec::new(); + let read = kernel(&lane, "xr2p_read_float"); + let (mut wrong, mut moved) = (Vec::new(), 0); for f in &FORMATS { // The model's texels, of the `half` each output rounds to. let (mut plane, mut bytes) = (Vec::new(), Vec::new()); @@ -495,33 +499,61 @@ fn draws_store_metals_extended_range_texels() { let what = format!("{:?} from {}", f.pf, if half { "half" } else { "float" }); let values = if half { &half_bytes } else { &floats }; let target = draw(&lane, f, values, half); + let size = texel_size(f.form); if f.alpha.is_none() { - let size = texel_size(f.form); let got = lane.read(&target, (0, 0), size as u64, BlitOption::None); - if digest(&got) != f.drawn { - for line in differences(&got, &plane, size, &inputs) { - wrong.push(format!("{what}: {line}")); + let mut differ = Vec::new(); + for (i, (g, w)) in got.chunks(size).zip(plane.chunks(size)).enumerate() { + match (g == w, texel_within(f.form, g, w)) { + (true, _) => {} + (false, true) => moved += 1, + (false, false) => differ.push(i), } } + for &i in differ.iter().take(6) { + let at = i * size..(i + 1) * size; + let bits = inputs[i].map(f32::to_bits); + wrong.push(format!( + "{what}: texel {i} of {bits:08x?}: {:02x?}, Metal's {:02x?}", + &got[at.clone()], + &plane[at] + )); + } continue; } - // A two-plane target against a texture written from the `half` values. - let size = (WIDTH as u64, HEIGHT as u64); - let reference = texture( - &lane, - f.pf, - size, - TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE, - ); - let input = buffer_with(&lane.device, &half_bytes).unwrap(); - dispatch(&lane, &write, &reference, (&input, 0), size); - let (got, want) = ( - reads(&lane, &read, &target, size), - reads(&lane, &read, &reference, size), - ); - if got != want { - for line in differences(&got, &want, 16, &inputs) { - wrong.push(format!("{what} (reads): {line}")); + // A two-plane target through its kernel reads: the codes they came from, and the reads. + let got = reads(&lane, &read, &target, (WIDTH as u64, HEIGHT as u64)); + let mut differ = 0; + for (i, texel) in got.as_chunks::<16>().0.iter().enumerate() { + let (want, _) = codes(f.form, &plane[i * size..(i + 1) * size]); + let want = [want[0], want[1], want[2], u32::from(bytes[i])]; + let lanes = texel + .as_chunks::<4>() + .0 + .iter() + .map(|b| f32::from_le_bytes(*b)); + let (mut same, mut held) = (true, true); + for (c, (v, code)) in lanes.zip(want).enumerate() { + let alpha = c == 3; + let read_code = nearest_code(f.form, v, alpha); + same &= read_code == code && v == metal_read(f.form, code, alpha); + held &= + read_code.abs_diff(code) <= 1 && read_within(f.form, v, read_code, alpha); + } + match (same, held) { + (true, _) => {} + (false, true) => moved += 1, + (false, false) => { + differ += 1; + if differ <= 6 { + let bits = inputs[i].map(f32::to_bits); + wrong.push(format!( + "{what} (reads): texel {i} of {bits:08x?}: {:02x?}, Metal's codes \ + {want:?}", + &texel[..] + )); + } + } } } } @@ -529,11 +561,13 @@ fn draws_store_metals_extended_range_texels() { for line in &wrong { println!("XR-TARGETS-DIFFERS {name}: {line}"); } + println!("XR-TARGETS {name}: {moved} drawn texels within the device's conversion of Metal's"); assert!( wrong.is_empty(), "{} texels differ from Metal's", wrong.len() ); + assert_announced(&messages, moved, "the draws"); quiet(lane, &messages); } @@ -589,7 +623,7 @@ fn clears_store_metals_extended_range_texels() { let values = clear_values(); assert_eq!(values.len(), 484, "the clear colors"); let read = kernel(&lane, "xr2p_read_float"); - let mut wrong = Vec::new(); + let (mut wrong, mut moved) = (Vec::new(), 0); for f in &FORMATS { let size = texel_size(f.form) as u64; let n = values.len() as u64; @@ -664,27 +698,132 @@ fn clears_store_metals_extended_range_texels() { } } } + // Metal's reads of the clears' codes, which give Metal's digest; the device's are its + // conversion of the same codes. + let (codes, model) = cleared_reads(f.form, &values); + assert_eq!( + digest(&model), + f.cleared_reads, + "{:?}: the model's clears' reads", + f.pf + ); let got = read_buffer(&floats, 0, 16 * n).unwrap(); - if digest(&got) != f.cleared_reads { + let lanes = got + .as_chunks::<4>() + .0 + .iter() + .map(|b| f32::from_le_bytes(*b)); + let mut differ = Vec::new(); + for (i, (v, want)) in lanes.zip(model.as_chunks::<4>().0).enumerate() { + let (texel, c) = (i / 4, i % 4); + let held = match codes[texel][c] { + Some(code) => read_within(f.form, v, code, c == 3), + None => v == 1.0, + }; + match (v.to_bits() == u32::from_le_bytes(*want), held) { + (true, _) => {} + (false, true) => moved += 1, + (false, false) => differ.push(i), + } + } + for &i in differ.iter().take(6) { + let want = f32::from_le_bytes(model.as_chunks::<4>().0[i]); + let got = f32::from_le_bytes(got.as_chunks::<4>().0[i]); wrong.push(format!( - "{:?} clears' reads: {}, Metal's {}", + "{:?} clear {} of {}: channel {} reads {got:e}, Metal's {want:e}", f.pf, - digest(&got), - f.cleared_reads + i / 4, + values[i / 4], + i % 4 )); } } for line in &wrong { println!("XR-TARGETS-DIFFERS {name}: {line}"); } + println!("XR-TARGETS {name}: {moved} clears' reads within the device's conversion of Metal's"); assert!( wrong.is_empty(), "{} clears differ from Metal's", wrong.len() ); + assert_announced(&messages, moved, "the clears' reads"); quiet(lane, &messages); } +/// The codes of each clear of `values` into a texel of `form` (Metal's, `clear_texel`'s), and the +/// bytes of Metal's `float4` reads of them: its read of each code ([`metal_read`]), `BGR10_XR`'s +/// alpha 1. +fn cleared_reads(form: ExtendedRange, values: &[f64]) -> (Vec<[Option; 4]>, Vec) { + let codes: Vec<[Option; 4]> = values + .iter() + .map(|&v| rgba_codes(form, form.clear_texel([v; 4], ClearRoute::ThroughHalf))) + .collect(); + let reads = codes + .iter() + .flat_map(|texel| { + (0..4).map(|c| texel[c].map_or(1.0, |code| metal_read(form, code, c == 3))) + }) + .flat_map(f32::to_le_bytes) + .collect(); + (codes, reads) +} + +/// The models give Metal's digests: each format's draws of the probe's `half` outputs, a two-plane +/// format's alpha bytes, its clears' bytes and its `float` reads of them. +#[test] +fn the_models_give_metal_s_digests() { + let halves: Vec = outputs().iter().flat_map(|v| v.map(half_bits)).collect(); + let values = clear_values(); + for f in &FORMATS { + let (mut plane, mut bytes) = (Vec::new(), Vec::new()); + for v in halves.chunks(4) { + let color = [0, 1, 2, 3].map(|c| f64::from(half_value(v[c]))); + let (p, a) = metal_bytes(f.form, f.form.clear_texel(color, ClearRoute::ThroughHalf)); + plane.extend(p); + bytes.extend(a); + } + assert_eq!(digest(&plane), f.drawn, "{:?}: the drawn texels", f.pf); + if let Some(alpha) = f.alpha { + assert_eq!(digest(&bytes), alpha, "{:?}: the drawn alpha bytes", f.pf); + } + if let Some(cleared) = f.cleared { + let model: Vec = values + .iter() + .flat_map(|&v| { + metal_bytes(f.form, f.form.clear_texel([v; 4], ClearRoute::ThroughHalf)).0 + }) + .collect(); + assert_eq!(digest(&model), cleared, "{:?}: the clears' bytes", f.pf); + } + let (_, reads) = cleared_reads(f.form, &values); + assert_eq!( + digest(&reads), + f.cleared_reads, + "{:?}: the clears' reads", + f.pf + ); + } +} + +/// The red, green, blue and alpha codes of the raw texel `raw` of `form` (`clear_texel`'s); none +/// for `BGR10_XR`'s alpha, which reads 1. +fn rgba_codes(form: ExtendedRange, raw: [u32; 4]) -> [Option; 4] { + match form { + ExtendedRange::Bgra10 { .. } => [2, 1, 0, 3].map(|f| Some(raw[f] >> 6)), + _ => { + let w = raw[0]; + let alpha = matches!(form, ExtendedRange::Planes { .. }).then_some(raw[1]); + [ + Some(w >> 20 & 0x3ff), + Some(w >> 10 & 0x3ff), + Some(w & 0x3ff), + alpha, + ] + } + } +} + /// Colors whose texels differ between Metal's two clear routes: ties between codes, which the /// straight route takes up (`0.25` there `float` steps below a tie, down), NaN (code 0 straight, /// 384 through `half`; alpha 384 on both), and `_sRGB` values each side of an encode threshold diff --git a/crates/metal2vulkan-validation/src/runtime_lane/extended_range_two_planes.rs b/crates/metal2vulkan-validation/src/runtime_lane/extended_range_two_planes.rs index 419c08a87..354b2724c 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/extended_range_two_planes.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/extended_range_two_planes.rs @@ -30,9 +30,11 @@ use super::degrade_notices::{counts, on_device}; use super::extended_range_targets::{half_bits, half_value}; use super::pixel_samplers::metal_sampler; +use super::xr_codes::{as_metal_reads, assert_announced, assert_counted, codes, texel_within}; use super::{buffer_with, converted_holds, half_within, read_buffer}; use crate::air_library::AirLibrary; use metal2vulkan::error::Feature; +use metal2vulkan::metal::format::ExtendedRange; use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; @@ -556,6 +558,61 @@ fn floats(n: usize, step: usize) -> Vec { .collect() } +/// The codes Metal's kernel write of `values` (`half4`s where `half`, else `float4`s, one a grid +/// thread `w` wide) stores in a texture of `form`, by thread: those of the threads within the +/// `width` x `height` texture (`ExtendedRange::write_code`), `None` past it and for a channel the +/// form lacks (`BGR10_XR`'s alpha). +fn written_codes( + form: ExtendedRange, + (values, half): (&[u8], bool), + w: usize, + (width, height): (usize, usize), +) -> Vec<[Option; 4]> { + let lanes: Vec = match half { + true => values + .as_chunks::<2>() + .0 + .iter() + .map(|h| half_value(u16::from_le_bytes(*h))) + .collect(), + false => values + .as_chunks::<4>() + .0 + .iter() + .map(|f| f32::from_le_bytes(*f)) + .collect(), + }; + let alpha = matches!(form, ExtendedRange::Planes { .. }); + lanes + .as_chunks::<4>() + .0 + .iter() + .enumerate() + .map(|(t, v)| { + let inside = t % w < width && t / w < height; + std::array::from_fn(|c| { + (inside && (c < 3 || alpha)).then(|| form.write_code(v[c], c == 3).unwrap()) + }) + }) + .collect() +} + +/// Checks the reads `h` and `f` of a texture of `form` that holds Metal's codes `codes` against +/// Metal's digests of output `what` (`{what}H` and `{what}F` by `metal`), each lane the device's +/// conversion within its bound replaced by Metal's read first ([`as_metal_reads`]), and counts the +/// texels it moved into `moved`. +fn check_reads( + (wrong, moved): (&mut Vec, &mut usize), + (form, codes): (ExtendedRange, &[[Option; 4]]), + (what, metal): (String, impl Fn(&str) -> &'static str), + [h, f]: [Vec; 2], +) { + let (f, h, n) = as_metal_reads(form, (&f, &h), codes); + *moved += n; + check(wrong, format!("{what}H"), metal("H"), &h); + check(wrong, format!("{what}F"), metal("F"), &f); +} + /// The SHA-256 of `bytes`, in hex. pub(super) fn digest(bytes: &[u8]) -> String { Sha256::digest(bytes) @@ -599,40 +656,38 @@ pub(super) fn texture(device: &Device, format: PixelFormat, width: u64, height: /// `half` pattern and of a dense `float` grid, and in the consumer's shape. #[test] fn two_plane_textures_read_and_write_as_metal_does() { - on_device(|device, _| { + on_device(|device, messages| { let queue = device.new_command_queue().unwrap(); let kernels = Kernels::new(device); - let mut wrong = Vec::new(); + let (mut wrong, mut moved) = (Vec::new(), 0); let side = 256; let texels = Dispatch::Texels(side, side); let count = texels.threads(); for format in [PixelFormat::RGB10A82PXR10, PixelFormat::RGB10A82PXR10SRGB] { - let metal = |tag: &str| { - TEXTURES - .iter() - .find(|m| m.0 == format && m.1 == tag) - .map(|m| m.2) - .unwrap() + let form = ExtendedRange::of(format).expect("a two-plane format"); + let metal = |tag: String| { + move |lanes: &str| { + TEXTURES + .iter() + .find(|m| m.0 == format && m.1 == format!("{tag}{lanes}")) + .map(|m| m.2) + .unwrap() + } }; let t = texture(device, format, side, side); let steps = [ ("HR", halves(count, |n, c| n + 16384 * c), true), ("FR", floats(count, 1), false), ]; + let all = (side as usize, side as usize); for (tag, values, half) in steps { write(device, &queue, &kernels, &t, (&values, half), texels); - let [h, f] = reads(device, &queue, &kernels, &t, texels); - check( - &mut wrong, - format!("{format:?} {tag}H"), - metal(&format!("{tag}H")), - &h, - ); - check( - &mut wrong, - format!("{format:?} {tag}F"), - metal(&format!("{tag}F")), - &f, + let codes = written_codes(form, (&values, half), side as usize, all); + check_reads( + (&mut wrong, &mut moved), + (form, &codes), + (format!("{format:?} {tag}"), metal(tag.to_owned())), + reads(device, &queue, &kernels, &t, texels), ); } let t = texture(device, format, 64, 4); @@ -645,11 +700,20 @@ fn two_plane_textures_read_and_write_as_metal_does() { (&values, true), Dispatch::Consumer, ); - let [h, f] = reads(device, &queue, &kernels, &t, Dispatch::Consumer); - check(&mut wrong, format!("{format:?} ORH"), metal("ORH"), &h); - check(&mut wrong, format!("{format:?} ORF"), metal("ORF"), &f); + let codes = written_codes(form, (&values, true), GRID_WIDTH as usize, (64, 4)); + check_reads( + (&mut wrong, &mut moved), + (form, &codes), + (format!("{format:?} OR"), metal("OR".to_owned())), + reads(device, &queue, &kernels, &t, Dispatch::Consumer), + ); } + println!( + "XR-TWO-PLANES {}: {moved} texels' reads within the device's conversion of Metal's", + device.name() + ); report(device, &wrong); + assert_announced(messages, moved, "the two-plane textures' reads"); }); } @@ -672,12 +736,13 @@ fn two_plane_heap_textures_read_and_write_as_metal_does() { on_device(|device, messages| { let queue = device.new_command_queue().unwrap(); let kernels = Kernels::new(device); - let mut wrong = Vec::new(); + let (mut wrong, mut moved) = (Vec::new(), 0); for format in [PixelFormat::RGB10A82PXR10, PixelFormat::RGB10A82PXR10SRGB] { - let metal = |tag: &str| { + let form = ExtendedRange::of(format).expect("a two-plane format"); + let metal = |lanes: &str| { TEXTURES .iter() - .find(|m| m.0 == format && m.1 == tag) + .find(|m| m.0 == format && m.1 == format!("OR{lanes}")) .map(|m| m.2) .unwrap() }; @@ -716,15 +781,19 @@ fn two_plane_heap_textures_read_and_write_as_metal_does() { (&values, true), Dispatch::Consumer, ); - let [h, f] = reads(device, &queue, &kernels, &t, Dispatch::Consumer); - let what = format!("{format:?} {options:?} {heap_type:?}"); - check(&mut wrong, format!("{what} ORH"), metal("ORH"), &h); - check(&mut wrong, format!("{what} ORF"), metal("ORF"), &f); + let codes = written_codes(form, (&values, true), GRID_WIDTH as usize, (64, 4)); + check_reads( + (&mut wrong, &mut moved), + (form, &codes), + (format!("{format:?} {options:?} {heap_type:?} OR"), metal), + reads(device, &queue, &kernels, &t, Dispatch::Consumer), + ); } } } report(device, &wrong); let notices = counts(&messages.take_notices()); + assert_counted(¬ices, moved, "the heap textures' reads"); assert_eq!(notices.get(&HEAP_PLANES[0]), None, "{notices:?}"); assert_eq!( notices.get(&HEAP_PLANES[1]).copied(), @@ -1953,13 +2022,15 @@ fn plane_views_over_a_buffer_read_and_write_as_metal_does() { let kernels = Kernels::new(device); let exact = metal_sampler(device); let mut converted = Vec::new(); - let mut wrong = Vec::new(); + let (mut wrong, mut moved) = (Vec::new(), 0); let steps = [ (halves(GRID, |n, c| 32 * n + 16384 * c + 7 * c), true), (floats(GRID, 32), false), ]; for plane0 in [PixelFormat::BGR10XR, PixelFormat::BGR10XRSRGB] { + let form = ExtendedRange::of(plane0).expect("an extended-range format"); for (g, (width, height, row)) in GEOMETRIES.into_iter().enumerate() { + let view_texels = (width as usize, height as usize); let metal = |tag: &str| { VIEWS .iter() @@ -1980,11 +2051,32 @@ fn plane_views_over_a_buffer_read_and_write_as_metal_does() { }; let planes = [view(plane0, 0), view(PixelFormat::ARGB8Unorm, PLANE_1)]; let mut outputs = Vec::new(); - for (p, plane) in planes.iter().enumerate() { - let [h, f] = reads(device, &queue, &kernels, plane, Dispatch::Consumer); - outputs.push((format!("R0P{p}H"), h)); - outputs.push((format!("R0P{p}F"), f)); - } + // Plane 0's reads, each lane the device's conversion within its bound of Metal's + // codes `codes` replaced by Metal's read (`as_metal_reads`); plane 1's as read. The + // texels the bound moved. + let push_reads = + |outputs: &mut Vec<(String, Vec)>, s: usize, codes: &[[Option; 4]]| { + let mut moved = 0; + for (p, plane) in planes.iter().enumerate() { + let [h, f] = reads(device, &queue, &kernels, plane, Dispatch::Consumer); + let (f, h) = match p { + 0 => { + let (f, h, n) = as_metal_reads(form, (&f, &h), codes); + moved += n; + (f, h) + } + _ => (f, h), + }; + outputs.push((format!("R{s}P{p}H"), h)); + outputs.push((format!("R{s}P{p}F"), f)); + } + moved + }; + moved += push_reads( + &mut outputs, + 0, + &view_codes(form, &initial, view_texels, row), + ); for (s, (values, half)) in steps.iter().enumerate() { let s = s + 1; for plane in &planes { @@ -1997,15 +2089,26 @@ fn plane_views_over_a_buffer_read_and_write_as_metal_does() { Dispatch::Consumer, ); } - outputs.push(( - format!("W{s}BUF"), - read_buffer(&buffer, 0, VIEW_BUFFER).unwrap(), - )); - for (p, plane) in planes.iter().enumerate() { - let [h, f] = reads(device, &queue, &kernels, plane, Dispatch::Consumer); - outputs.push((format!("R{s}P{p}H"), h)); - outputs.push((format!("R{s}P{p}F"), f)); + // Metal's codes of plane 0 after the write; the buffer's plane 0 words each the + // device's encode within a code of Metal's replaced by Metal's word. + let codes = + written_codes(form, (values, *half), GRID_WIDTH as usize, view_texels); + let mut bytes = read_buffer(&buffer, 0, VIEW_BUFFER).unwrap(); + for (t, texel) in codes.iter().enumerate() { + let [Some(r), Some(g), Some(b), _] = *texel else { + continue; + }; + let (x, y) = (t as u64 % GRID_WIDTH, t as u64 / GRID_WIDTH); + let at = (y * row + 4 * x) as usize; + let metal = (0xc000_0000 | r << 20 | g << 10 | b).to_le_bytes(); + let word = &mut bytes[at..at + 4]; + if *word != metal && texel_within(form, word, &metal) { + word.copy_from_slice(&metal); + moved += 1; + } } + outputs.push((format!("W{s}BUF"), bytes)); + moved += push_reads(&mut outputs, s, &codes); } for (tag, bytes) in outputs { let plane_1_read = tag.contains("P1"); @@ -2031,17 +2134,44 @@ fn plane_views_over_a_buffer_read_and_write_as_metal_does() { device.name(), converted.len() ); + println!( + "XR-TWO-PLANES {}: {moved} plane 0 texels within the device's conversion of Metal's", + device.name() + ); + let notices = counts(&messages.take_notices()); if !converted.is_empty() { - let notices = counts(&messages.take_notices()); assert!( notices.contains_key(&Degradation::DeviceTexelConversion), "{notices:?}" ); } report(device, &wrong); + assert_counted(¬ices, moved, "the plane views"); }); } +/// The codes of a `BGR10_XR` (or `_sRGB`) view of `width` x `height` texels over `bytes` with rows +/// `row` bytes apart, by grid thread (`GRID_WIDTH` wide): red, green and blue of the texel a thread +/// within the view reads, `None` past it and for alpha. +fn view_codes( + form: ExtendedRange, + bytes: &[u8], + (width, height): (usize, usize), + row: u64, +) -> Vec<[Option; 4]> { + (0..GRID) + .map(|t| { + let (x, y) = (t % GRID_WIDTH as usize, t / GRID_WIDTH as usize); + if x >= width || y >= height { + return [None; 4]; + } + let at = y * row as usize + 4 * x; + let (c, _) = codes(form, &bytes[at..at + 4]); + [Some(c[0]), Some(c[1]), Some(c[2]), None] + }) + .collect() +} + /// `bytes`, a read of an 8-bit normalized view (`half4`s where `half`, else `float4`s), with each /// value in `[0, 1]` that lies within the device's conversion's bound of a code `c`'s Metal value /// (`converted_holds` of `c / 255`, and `half_within` of its `half`) replaced by that value: what diff --git a/crates/metal2vulkan-validation/src/runtime_lane/padded_loads.rs b/crates/metal2vulkan-validation/src/runtime_lane/padded_loads.rs index 1c2e9f751..e401061ab 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/padded_loads.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/padded_loads.rs @@ -29,14 +29,18 @@ //! no vertices and its scissored draw have it too, as the probes' did.) use super::degrade_notices::counts; -use super::extended_range_targets::digest; +use super::extended_range_targets::{digest, half_bits, half_value}; use super::resolves::{lane_with, quiet, Lane}; +use super::xr_codes::texel_within; use super::{buffer_with, read_buffer}; use crate::candidate::runtime_samples::{library, shape}; +use metal2vulkan::metal::format::ExtendedRange; use metal2vulkan::metal::{ ColorWriteMask, IndirectCommandType, PixelFormat, PrimitiveType, TextureType, TextureUsage, }; -use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, PrecisionNote, RenderPipelineDescriptor, StageSource, +}; use metal2vulkan_runtime::{ Buffer, Degradation, IndirectCommandBufferDescriptor, LoadAction, PipelineOptions, RenderPassDescriptor, ResourceOptions, ScissorRect, StoreAction, TextureDescriptor, @@ -471,6 +475,57 @@ fn the_inputs_are_the_probes() { assert_eq!(sha(&values()), VALUES_SHA, "the values"); } +/// The words Metal's pass stores where its draw writes every word of `pf`: each channel's drawn +/// value ([`values`]) rounded to `half` toward zero, as Metal's store rounds a `float` output, +/// then stored as a kernel write stores it (`ExtendedRange::write_code`), its low six bits zero. +fn drawn_words(pf: PixelFormat) -> Vec { + let form = ExtendedRange::of(pf).expect("a padded format"); + let channels = match pf { + PixelFormat::R10UnormX6 | PixelFormat::R10UnormX6SRGB => 1, + _ => 2, + }; + // The `half` of `x` (in `[0, 1]`) toward zero. + let toward_zero = |x: f32| { + let h = half_bits(x); + match half_value(h) > x { + true => half_value(h - 1), + false => half_value(h), + } + }; + values() + .as_chunks::<16>() + .0 + .iter() + .flat_map(|texel| { + (0..channels).map(move |c| { + let v = f32::from_le_bytes(texel[4 * c..4 * c + 4].try_into().unwrap()); + let code = form.write_code(toward_zero(v), false).expect("a code"); + (code << 6) as u16 + }) + }) + .flat_map(u16::to_le_bytes) + .collect() +} + +/// [`drawn_words`] gives Metal's digest of every case whose draw writes every word. +#[test] +fn the_drawn_model_gives_metal_s_digests() { + let mut checked = 0; + for (pf, bits, pass, metal) in METAL { + let channels = match pf { + PixelFormat::R10UnormX6 | PixelFormat::R10UnormX6SRGB => 1, + _ => 2, + }; + let every = (0..WIDTH * HEIGHT) + .all(|t| (0..channels).all(|c| writes((bits, pass), (t % WIDTH, t / WIDTH), c))); + if every { + checked += 1; + assert_eq!(digest(&drawn_words(pf)), metal, "{pf:?} {bits} {pass:?}"); + } + } + assert!(checked > 0, "no case draws every word"); +} + /// The probe's `float4` values, one a texel. fn values() -> Vec { (0..WIDTH * HEIGHT) @@ -658,8 +713,13 @@ fn a_loading_pass_that_draws_keeps_the_padded_words_it_does_not_write() { lane_with(|options| options.announce_each = [kept].into_iter().collect()); let mut differ = Vec::new(); let (mut whole, mut kept_words) = (0, 0); + // The drawn words within a code of Metal's, the device's encode. + let mut near = 0; + // Whether the runtime announced the device's conversion (`device-pack-conversion`), whose + // announcement each case's notices take. + let mut packs = false; for case in METAL { - let (pf, bits, pass, metal) = case; + let (pf, bits, pass, _) = case; let channels = match pf { PixelFormat::R10UnormX6 | PixelFormat::R10UnormX6SRGB => 1, _ => 2, @@ -687,10 +747,25 @@ fn a_loading_pass_that_draws_keeps_the_padded_words_it_does_not_write() { differ.push(case); } if every { + // Each word the device's encode of the drawn value: its code within one of Metal's + // (the model's, which gives Metal's digest), its low six bits Metal's. whole += 1; - let got = digest(&got); - if got != metal { - eprintln!("PADDED-LOADS-DIFFERS {pf:?} mask {bits} {pass:?}: {got}"); + let form = ExtendedRange::of(pf).expect("a padded format"); + let model = drawn_words(pf); + let mut past = 0; + for (g, w) in got.chunks(2).zip(model.chunks(2)) { + match (g == w, texel_within(form, g, w)) { + (true, _) => {} + (false, true) => near += 1, + (false, false) => past += 1, + } + } + if past > 0 { + eprintln!( + "PADDED-LOADS-DIFFERS {pf:?} mask {bits} {pass:?}: {past} words past a code of \ + Metal's, {}", + digest(&got) + ); differ.push(case); } } @@ -700,13 +775,19 @@ fn a_loading_pass_that_draws_keeps_the_padded_words_it_does_not_write() { pass != Pass::Undrawn, "{pf:?} {bits} {pass:?}: {announced:?}" ); + let pack = Degradation::from_precision_note(PrecisionNote::DevicePackConversion); + packs |= announced.contains_key(&pack); } eprintln!( - "PADDED-LOADS {} cases, {} differ: {whole} drawn whole against Metal's, {kept_words} \ - words kept", + "PADDED-LOADS {} cases, {} differ: {whole} drawn whole against Metal's ({near} words \ + within a code), {kept_words} words kept", METAL.len(), differ.len() ); + assert!( + near == 0 || packs, + "{near} drawn words within the device's conversion, device-pack-conversion unannounced" + ); assert!(whole > 0 && kept_words > 0, "no case of either kind ran"); assert!( differ.is_empty(), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rgb10a2_srgb.rs b/crates/metal2vulkan-validation/src/runtime_lane/rgb10a2_srgb.rs index e1c4f7216..5e86c880b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rgb10a2_srgb.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rgb10a2_srgb.rs @@ -34,23 +34,33 @@ //! The device's `isRGB10A2GammaSupported` answers as the texture's linear filter does. A //! difference is printed on an `RGB10A2-SRGB-DIFFERS` line. -use super::degrade_notices::on_device; +use super::degrade_notices::{counts, on_device}; use super::extended_range_samples::state_of; +use super::extended_range_targets::half_value; use super::resolves::{lane_with, quiet, Lane}; +use super::xr_codes::{ + assert_announced, assert_counted, half_within, recorded, value_within, written_within, +}; use super::{buffer_with, read_buffer, WAIT}; use crate::candidate::runtime_samples::{library, shape}; use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::metal::format::ExtendedRange; use metal2vulkan::metal::{PixelFormat, PrimitiveType, SamplerMinMagFilter, TextureUsage}; -use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, PrecisionNote, RenderPipelineDescriptor, StageSource, +}; use metal2vulkan_runtime::{ - BlitOption, Buffer, ClearColor, CommandBufferStatus, ComputePipelineState, Device, LoadAction, - Origin, PipelineOptions, PrivateFlag, Region, RenderPassDescriptor, RenderPipelineState, - ResourceOptions, SamplerState, Size, StoreAction, Texture, TextureDescriptor, + BlitOption, Buffer, ClearColor, CommandBufferStatus, ComputePipelineState, Degradation, Device, + LoadAction, Origin, PipelineOptions, PrivateFlag, Region, RenderPassDescriptor, + RenderPipelineState, ResourceOptions, SamplerState, Size, StoreAction, Texture, + TextureDescriptor, }; use sha2::{Digest, Sha256}; use std::fmt::Write as _; const PF: PixelFormat = PixelFormat::RGB10A2UnormSRGB; +/// Its form. +const FORM: ExtendedRange = ExtendedRange::Rgb10A2Srgb; /// Metal's digests: reads, writes, samples (nearest `float`, nearest `half`, linear `float`, /// linear `half`), clears (1 x 1, 64 x 64), stores (`float`, `half`) and loads. @@ -260,8 +270,10 @@ fn xorshift(s: &mut u64) -> u64 { /// Reads, writes and samples of a 586 texture by a kernel are Metal's. #[test] fn kernels_read_write_and_sample_rgb10a2_srgb_as_metal_does() { - on_device(|device, _| { + on_device(|device, messages| { let mut wrong = Vec::new(); + // The values within the device's conversion of Metal's, and the linear samples apart. + let (mut moved, mut filtered) = (0, 0); let shared = ResourceOptions::shared(); // Reads. let fetch = state_of(device, "fpv_bfloat_textures", "fpv_bfloat_fetch"); @@ -276,18 +288,29 @@ fn kernels_read_write_and_sample_rgb10a2_srgb_as_metal_does() { let width = buffer_with(device, &1024u32.to_le_bytes()).unwrap(); dispatch(device, &fetch, &t, (None, &[&out, &width]), (1024, 1)); let got = words(&read_buffer(&out, 0, 1024 * 16).unwrap()); - let mut text = String::new(); - for (c, w) in got.as_chunks::<4>().0.iter().enumerate() { - writeln!( - text, - "read {c} {:08x} {:08x} {:08x} {:08x}", - w[0], w[1], w[2], w[3] - ) - .unwrap(); - } - covers(&text, got.len() / 4, "reads"); - if digest(&text) != READS { - wrong.push(format!("reads {} (Metal's {READS})", digest(&text))); + let metal = words(&recorded("rgb10a2-srgb-reads", &["output", "codes"])); + let text = |words: &[u32]| { + let mut text = String::new(); + for (c, w) in words.as_chunks::<4>().0.iter().enumerate() { + writeln!( + text, + "read {c} {:08x} {:08x} {:08x} {:08x}", + w[0], w[1], w[2], w[3] + ) + .unwrap(); + } + text + }; + assert_eq!(digest(&text(&metal)), READS, "the recorded reads"); + covers(&text(&got), got.len() / 4, "reads"); + let (near, past) = lanes_within(&got, &metal, |g, w, c| { + value_within(FORM, f32::from_bits(g), f32::from_bits(w), c == 3) + }); + moved += near; + if past > 0 { + wrong.push(format!( + "reads: {past} lanes past the device's conversion of Metal's" + )); } // Writes. let write = state_of(device, "fpv_bfloat_textures", "fpv_bfloat_write"); @@ -309,13 +332,23 @@ fn kernels_read_write_and_sample_rgb10a2_srgb_as_metal_does() { (4096, height), ); let got = words_of(&t, (4096, height)); - let mut text = String::new(); - for (k, w) in got.iter().enumerate() { - writeln!(text, "write {k} {w:08x}").unwrap(); - } - covers(&text, got.len(), "writes"); - if digest(&text) != WRITES { - wrong.push(format!("writes {} (Metal's {WRITES})", digest(&text))); + let metal = words(&recorded("rgb10a2-srgb-writes", &["output", "words"])); + let text = |words: &[u32]| { + let mut text = String::new(); + for (k, w) in words.iter().enumerate() { + writeln!(text, "write {k} {w:08x}").unwrap(); + } + text + }; + assert_eq!(digest(&text(&metal)), WRITES, "the recorded writes"); + covers(&text(&got), got.len(), "writes"); + let written = values(&WRITE_SPECIALS, got.len()); + let (near, past, first) = words_within(&got, &metal, &written); + moved += near; + if past > 0 { + wrong.push(format!( + "writes: {past} words past the device's encode of Metal's: {first:?}" + )); } // Samples. let mut s = 0x243f_6a88_85a3_08d3u64; @@ -337,6 +370,8 @@ fn kernels_read_write_and_sample_rgb10a2_srgb_as_metal_does() { .flat_map(f32::to_le_bytes) .collect(); let coords = buffer_with(device, &coords).unwrap(); + // Metal's nearest `float` samples, which its `half` ones narrow. + let mut nearest_floats = Vec::new(); for (linear, filter) in [SamplerMinMagFilter::Nearest, SamplerMinMagFilter::Linear] .into_iter() .enumerate() @@ -360,38 +395,90 @@ fn kernels_read_write_and_sample_rgb10a2_srgb_as_metal_does() { (4096, 1), ); let bytes = read_buffer(&out, 0, 4096 * size as u64).unwrap(); - let mut text = String::new(); - for (&(n, m), v) in positions.iter().zip(bytes.chunks_exact(size)) { - match half { - 1 => { - let h = |c: usize| u16::from_le_bytes([v[2 * c], v[2 * c + 1]]); - writeln!( - text, - "s {linear} h {n} {m} {:04x} {:04x} {:04x} {:04x}", - h(0), - h(1), - h(2), - h(3) - ) - } - _ => { - let w = words(v); - writeln!( - text, - "s {linear} f {n} {m} {:08x} {:08x} {:08x} {:08x}", - w[0], w[1], w[2], w[3] - ) + let case = format!( + "rgb10a2-srgb-samples-{}-{}", + ["nearest", "linear"][linear], + ["f", "h"][half] + ); + let metal = recorded(&case, &["output", "samples"]); + let text = |bytes: &[u8]| { + let mut text = String::new(); + for (&(n, m), v) in positions.iter().zip(bytes.chunks_exact(size)) { + match half { + 1 => { + let h = |c: usize| u16::from_le_bytes([v[2 * c], v[2 * c + 1]]); + writeln!( + text, + "s {linear} h {n} {m} {:04x} {:04x} {:04x} {:04x}", + h(0), + h(1), + h(2), + h(3) + ) + } + _ => { + let w = words(v); + writeln!( + text, + "s {linear} f {n} {m} {:08x} {:08x} {:08x} {:08x}", + w[0], w[1], w[2], w[3] + ) + } } + .unwrap(); } - .unwrap(); + text + }; + assert_eq!( + digest(&text(&metal)), + SAMPLES[linear][half], + "{case}: recorded" + ); + covers(&text(&bytes), bytes.len() / size, "samples"); + // A nearest sample is a texel's read; a linear one filters the device's reads by + // its own arithmetic (`bicubic-filter-arithmetic`, whose class is unbounded), so it + // runs and is counted, its values the conformance suite's `rgb10a2-srgb-samples-*` + // cases'. + let lanes = |b: &[u8]| -> Vec { + match half { + 1 => b + .as_chunks::<2>() + .0 + .iter() + .map(|h| half_value(u16::from_le_bytes(*h))) + .collect(), + _ => words(b).into_iter().map(f32::from_bits).collect(), + } + }; + let (got, want) = (lanes(&bytes), lanes(&metal)); + if linear == 1 { + filtered += got + .iter() + .zip(&want) + .filter(|(g, w)| g.to_bits() != w.to_bits()) + .count(); + continue; } - covers(&text, bytes.len() / size, "samples"); - let want = SAMPLES[linear][half]; - if digest(&text) != want { + if half == 0 { + nearest_floats = want.clone(); + } + let mut past = 0; + for (i, (g, w)) in got.iter().zip(&want).enumerate() { + let alpha = i % 4 == 3; + let held = match half { + 1 => half_within(FORM, *g, nearest_floats[i], alpha), + _ => value_within(FORM, *g, *w, alpha), + }; + match (g.to_bits() == w.to_bits(), held) { + (true, _) => {} + (false, true) => moved += 1, + (false, false) => past += 1, + } + } + if past > 0 { wrong.push(format!( - "samples linear {linear} half {half}: {} (Metal's {want}); first: {}", - digest(&text), - text.lines().next().unwrap_or_default() + "samples nearest half {half}: {past} lanes past the device's conversion \ + of Metal's" )); } } @@ -399,11 +486,23 @@ fn kernels_read_write_and_sample_rgb10a2_srgb_as_metal_does() { for line in &wrong { println!("RGB10A2-SRGB-DIFFERS {}: {line}", device.name()); } + println!( + "RGB10A2-SRGB {}: {moved} values within the device's conversion of Metal's, {filtered} \ + linear sample lanes apart", + device.name() + ); assert!( wrong.is_empty(), "{} answers differ from Metal's", wrong.len() ); + let announced = counts(&messages.take_notices()); + assert_counted(&announced, moved, "the kernels' reads, writes and samples"); + let note = Degradation::from_precision_note(PrecisionNote::BicubicFilterArithmetic); + assert!( + filtered == 0 || announced.contains_key(¬e), + "{filtered} linear sample lanes apart, bicubic-filter-arithmetic unannounced" + ); let gamma = device .private_properties() .flag(PrivateFlag::IsRgb10a2GammaSupported); @@ -465,6 +564,8 @@ fn blit_words(lane: &Lane, target: &Texture, (width, height): (u64, u64)) -> Vec fn passes_clear_store_and_load_rgb10a2_srgb_as_metal_does() { let (messages, _cache, lane) = lane_with(|_| {}); let mut wrong = Vec::new(); + // The stored words within a code of Metal's, the device's encode. + let mut moved = 0; // Clears. let colors: Vec<[f64; 4]> = (0..2049 + RENDER_SPECIALS.len()) .map(|k| match k { @@ -585,16 +686,29 @@ fn passes_clear_store_and_load_rgb10a2_srgb_as_metal_does() { .unwrap_or_else(|e| panic!("{fragment}: the pass: {e}")); let got = blit_words(&lane, &target, (4096, height)); let kind = if half == 1 { "half" } else { "float" }; - let mut text = String::new(); - for (k, w) in got.iter().enumerate() { - writeln!(text, "store {kind} {k} {w:08x}").unwrap(); - } - covers(&text, got.len(), "stores"); - if digest(&text) != STORES[half] { + let case = format!("rgb10a2-srgb-stores-{}", ["f", "h"][half]); + let metal = words(&recorded(&case, &["output", "words"])); + let text = |words: &[u32]| { + let mut text = String::new(); + for (k, w) in words.iter().enumerate() { + writeln!(text, "store {kind} {k} {w:08x}").unwrap(); + } + text + }; + assert_eq!(digest(&text(&metal)), STORES[half], "{case}: recorded"); + covers(&text(&got), got.len(), "stores"); + let stored: Vec<[f32; 4]> = match half { + 1 => all + .iter() + .map(|v| v.map(|c| half_value(half_bits(c)))) + .collect(), + _ => all.clone(), + }; + let (near, past, first) = words_within(&got, &metal, &stored); + moved += near; + if past > 0 { wrong.push(format!( - "stores {kind}: {} (Metal's {})", - digest(&text), - STORES[half] + "stores {kind}: {past} words past the device's encode of Metal's: {first:?}" )); } } @@ -664,14 +778,59 @@ fn passes_clear_store_and_load_rgb10a2_srgb_as_metal_does() { for line in &wrong { println!("RGB10A2-SRGB-DIFFERS {}: {line}", lane.device.name()); } + println!( + "RGB10A2-SRGB {}: {moved} stored words within a code of Metal's", + lane.device.name() + ); assert!( wrong.is_empty(), "{} answers differ from Metal's", wrong.len() ); + assert_announced(&messages, moved, "the stores"); quiet(lane, &messages); } +/// The words of `got`, writes of `values`, that are not `want`'s but hold within the device's +/// encode's bound of each ([`written_within`]), and those past it, with the first few of those. +fn words_within(got: &[u32], want: &[u32], values: &[[f32; 4]]) -> (usize, usize, Vec) { + let (mut near, mut past, mut first) = (0, 0, Vec::new()); + for (k, ((g, w), v)) in got.iter().zip(want).zip(values).enumerate() { + match ( + g == w, + written_within(FORM, &g.to_le_bytes(), &w.to_le_bytes(), v), + ) { + (true, _) => {} + (false, true) => near += 1, + (false, false) => { + past += 1; + if first.len() < 4 { + first.push(format!("{k} of {v:?}: {g:08x}, Metal's {w:08x}")); + } + } + } + } + (near, past, first) +} + +/// The lanes (`float` bits, four a texel) of `got` that are not `want`'s but hold by `held` (the +/// device's, Metal's and the lane's channel), and those that do not. +fn lanes_within( + got: &[u32], + want: &[u32], + held: impl Fn(u32, u32, usize) -> bool, +) -> (usize, usize) { + let (mut near, mut past) = (0, 0); + for (i, (&g, &w)) in got.iter().zip(want).enumerate() { + match (g == w, held(g, w, i % 4)) { + (true, _) => {} + (false, true) => near += 1, + (false, false) => past += 1, + } + } + (near, past) +} + /// The lane's `half` conversion is MSL's round to nearest even. #[test] fn half_bits_round_to_nearest_even() { diff --git a/crates/metal2vulkan-validation/src/runtime_lane/two_plane_samples.rs b/crates/metal2vulkan-validation/src/runtime_lane/two_plane_samples.rs index 1b1671715..d285338db 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/two_plane_samples.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/two_plane_samples.rs @@ -12,7 +12,10 @@ //! //! Metal's answer: the SHA-256 of each case's 4,096 results ([`METAL`]; an Apple //! M4 under macOS 27.0.1, through the probe's constexpr samplers, plain and under Metal's -//! validation layer alike), which the probe keeps. A nearest case is Metal's bytes; a linear one +//! validation layer alike), which the probe keeps. A nearest case is Metal's results, each a +//! texel's read, which the device converts (`PrecisionNote::DevicePackConversion`, announced): each +//! within its bound of Metal's result in Metal's recording of the case (the conformance suite's +//! `xr-two-plane-samples-*`, which gives the digest), a `half` one of Metal's `float`; a linear one //! runs, its blend the device's `FMix` of the decoded taps (`bicubic-filter-arithmetic`), which a //! digest cannot bound, so its values are compared by the conformance suite's //! `xr-two-plane-samples` cases. A differing case is printed with its first results, on one @@ -23,11 +26,14 @@ use super::degrade_notices::on_device; use super::extended_range_samples::state; +use super::extended_range_targets::half_value; use super::extended_range_two_planes::digest; use super::read_through_views::{draw, sampling_state, Sampled}; use super::two_plane_copies::{lane, planes, Rng, FORMATS}; +use super::xr_codes::{assert_announced, half_within, recorded, value_within}; use super::{buffer_with, read_buffer}; use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::metal::format::ExtendedRange; use metal2vulkan::metal::{PixelFormat, SamplerAddressMode, SamplerMinMagFilter, TextureUsage}; use metal2vulkan_runtime::{CommandBufferStatus, Size, TextureDescriptor}; use std::time::Duration; @@ -158,7 +164,7 @@ fn sampler(name: &str) -> SamplerDescriptor { /// device's, module docs). #[test] fn two_plane_samples_are_metal_s() { - on_device(|device, _| { + on_device(|device, messages| { let lane = lane(device); let coords: Vec = coordinates() .into_iter() @@ -168,7 +174,11 @@ fn two_plane_samples_are_metal_s() { let coords = buffer_with(device, &coords).unwrap(); let mut wrong = Vec::new(); let mut checked = 0; + // The results within the device's conversion of Metal's, and Metal's `float` results of a + // case, which its `half` ones narrow. + let (mut moved, mut floats) = (0, Vec::new()); for (format, name) in FORMATS { + let form = ExtendedRange::of(format).expect("a two-plane format"); let (texture, _, _) = lane.filled(format, 4, (SIDE, SIDE)); for s in ["nc", "lc", "nr", "lr"] { let runtime = device.new_sampler_state(&sampler(s)).unwrap(); @@ -212,13 +222,54 @@ fn two_plane_samples_are_metal_s() { continue; } checked += 1; - if got != want { + // Metal's results, whole, from its recording of the case, which give its + // digest; each the device's read of the texel within its bound. + let recording = + format!("xr-two-plane-samples-{}", case[4..].replace('.', "-")); + let metal = recorded(&recording, &["output", "runtime-sampler"]); + assert_eq!(digest(&metal), want, "{recording}: the recorded results"); + let lanes = |b: &[u8]| -> Vec { + match half { + true => b + .as_chunks::<2>() + .0 + .iter() + .map(|h| half_value(u16::from_le_bytes(*h))) + .collect(), + false => b + .as_chunks::<4>() + .0 + .iter() + .map(|f| f32::from_le_bytes(*f)) + .collect(), + } + }; + let (got_lanes, want_lanes) = (lanes(&bytes), lanes(&metal)); + if !half { + floats = want_lanes.clone(); + } + let mut past = 0; + for (i, (g, w)) in got_lanes.iter().zip(&want_lanes).enumerate() { + let alpha = i % 4 == 3; + let held = match half { + true => half_within(form, *g, floats[i], alpha), + false => value_within(form, *g, *w, alpha), + }; + match (g.to_bits() == w.to_bits(), held) { + (true, _) => {} + (false, true) => moved += 1, + (false, false) => past += 1, + } + } + if past > 0 { let first: String = bytes[..(16 * size) as usize] .iter() .map(|b| format!("{b:02x}")) .collect(); wrong.push(format!( - "{case} through {kernel}: {got}, Metal {want}; the first 16 results {first}" + "{case} through {kernel}: {past} results past the device's \ + conversion of Metal's ({got}, Metal {want}); the first 16 results \ + {first}" )); } } @@ -229,11 +280,13 @@ fn two_plane_samples_are_metal_s() { println!("XR-TWO-PLANE-SAMPLES-DIFFERS {}: {line}", device.name()); } println!( - "XR-TWO-PLANE-SAMPLES {}: {checked} cases of {SAMPLES} samples checked, {} differ from Metal", + "XR-TWO-PLANE-SAMPLES {}: {checked} cases of {SAMPLES} samples checked, {} differ from \ + Metal past the device's conversion, {moved} results within it", device.name(), wrong.len() ); assert!(wrong.is_empty(), "{} cases differ from Metal", wrong.len()); + assert_announced(messages, moved, "the nearest samples"); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/xr_codes.rs b/crates/metal2vulkan-validation/src/runtime_lane/xr_codes.rs new file mode 100644 index 000000000..b73070d10 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/xr_codes.rs @@ -0,0 +1,303 @@ +//! The codes of Apple's extended-range and padded texels, and the bound within which the device's +//! conversion of them answers Metal's: `PrecisionNote::DevicePackConversion`, which every module +//! converting such a texel records and the runtime announces (`docs/FAST-PATHS.md`, the +//! `air.pack` row). A write's code lies within one of Metal's; a read is within one `f32` unit in +//! the last place of Metal's quotient, an `_sRGB` twin's colour within half a `2^-13` step of +//! Metal's table (`R10Unorm_X6_sRGB`'s and `RGB10A2Unorm_sRGB`'s 1.64 steps) beyond the device +//! `Pow`'s bound; a `half` result within one `half` unit in the last place. The lanes that hold +//! such texels to Metal's compare them through these, the bits Metal does not read exactly, against +//! Metal's values: a model (`ExtendedRange::write_code` and `read_value`) the lane holds to Metal's +//! digests, or Metal's recording of the same case ([`recorded`]). + +use super::degrade_notices::counts; +use super::extended_range_targets::{half_bits, half_value}; +use super::Messages; +use metal2vulkan::metal::format::ExtendedRange; +use metal2vulkan::pipeline::PrecisionNote; +use metal2vulkan_runtime::Degradation; +use std::collections::BTreeMap; + +/// The channel codes of one raw texel `bytes` of `form` as Metal's texture holds plane 0 (a +/// two-plane form's word alone, its alpha byte apart), in the field order of the bytes, and the +/// bits of it Metal does not read. +pub(super) fn codes(form: ExtendedRange, bytes: &[u8]) -> (Vec, u64) { + let word = || u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]); + match form { + ExtendedRange::Bgr10 { .. } | ExtendedRange::Planes { .. } => { + let w = word(); + ( + vec![w >> 20 & 0x3ff, w >> 10 & 0x3ff, w & 0x3ff], + u64::from(w >> 30), + ) + } + ExtendedRange::Rgb10A2Srgb => { + let w = word(); + ( + vec![w & 0x3ff, w >> 10 & 0x3ff, w >> 20 & 0x3ff, w >> 30], + 0, + ) + } + // A code in each 16-bit field's top 10 bits, its low 6 bits unread. + ExtendedRange::Bgra10 { .. } + | ExtendedRange::R10X6 + | ExtendedRange::R10X6Srgb + | ExtendedRange::Rg10X12 + | ExtendedRange::Rg10X12Srgb => { + let fields: Vec = bytes + .as_chunks::<2>() + .0 + .iter() + .map(|f| u16::from_le_bytes(*f)) + .collect(); + let unread = fields + .iter() + .fold(0u64, |m, &f| m << 6 | u64::from(f & 0x3f)); + (fields.iter().map(|&f| u32::from(f >> 6)).collect(), unread) + } + _ => panic!("{form:?} holds no codes"), + } +} + +/// Whether the texels `got` and `want` of `form` (`got` the device's, `want` Metal's) hold the same +/// bits Metal does not read and each code within one of the other's: a write's bound under +/// `PrecisionNote::DevicePackConversion`. +pub(super) fn texel_within(form: ExtendedRange, got: &[u8], want: &[u8]) -> bool { + let ((g, g_unread), (w, w_unread)) = (codes(form, got), codes(form, want)); + g_unread == w_unread && g.iter().zip(&w).all(|(a, b)| a.abs_diff(*b) <= 1) +} + +/// How many codes apart the device's write of the value `v` to a channel of `form` (alpha where +/// `alpha`) may store from Metal's code under `PrecisionNote::DevicePackConversion`'s bound: one; +/// two for an `R10Unorm_X6_sRGB` or `RGB10A2Unorm_sRGB` colour below `0.0031308`, the transfer's +/// linear segment, where Metal rounds the value to `2^-13` before its table and a step spans 1.6 +/// codes; any for a NaN, whose code is the device's. +pub(super) fn write_apart(form: ExtendedRange, v: f32, alpha: bool) -> u32 { + let coarse = matches!(form, ExtendedRange::R10X6Srgb | ExtendedRange::Rgb10A2Srgb); + match () { + _ if v.is_nan() => u32::MAX, + _ if coarse && !alpha && v < 0.003_130_8 => 2, + _ => 1, + } +} + +/// [`texel_within`] of a write of `values` (in the order of [`codes`]' fields): each code within +/// [`write_apart`] of Metal's. +pub(super) fn written_within(form: ExtendedRange, got: &[u8], want: &[u8], values: &[f32]) -> bool { + let ((g, g_unread), (w, w_unread)) = (codes(form, got), codes(form, want)); + let alpha = |c: usize| matches!(form, ExtendedRange::Rgb10A2Srgb) && c == 3; + g_unread == w_unread + && (0..g.len()).all(|c| g[c].abs_diff(w[c]) <= write_apart(form, values[c], alpha(c))) +} + +/// The largest code of a channel of `form`, alpha where `alpha`: a two-plane form's alpha byte's +/// 255, else 1023. +fn largest_code(form: ExtendedRange, alpha: bool) -> u32 { + match (form, alpha) { + (ExtendedRange::Planes { .. }, true) => 255, + _ => 1023, + } +} + +/// Metal's `float` read of `code` of a channel of `form`, alpha where `alpha`. +pub(super) fn metal_read(form: ExtendedRange, code: u32, alpha: bool) -> f32 { + form.read_value(code, alpha) + .unwrap_or_else(|| panic!("{form:?}: no Metal read of code {code}")) +} + +/// The code of a channel of `form` (alpha where `alpha`) whose Metal read lies nearest `v`, the +/// value a read answered: Metal's reads rise with the code, so the code a device's read within +/// its bound came from. +pub(super) fn nearest_code(form: ExtendedRange, v: f32, alpha: bool) -> u32 { + let top = largest_code(form, alpha); + let read = |c: u32| f64::from(metal_read(form, c, alpha)); + let v = f64::from(v); + // The first code whose read is at least `v` (`top + 1` where none is). + let (mut low, mut high) = (0, top + 1); + while low < high { + let mid = (low + high) / 2; + match read(mid) < v { + true => low = mid + 1, + false => high = mid, + } + } + let above = low; + [above.checked_sub(1), (above <= top).then_some(above)] + .into_iter() + .flatten() + .min_by(|&a, &b| (read(a) - v).abs().total_cmp(&(read(b) - v).abs())) + .unwrap_or(0) +} + +/// The device `Pow`'s bound at the `_sRGB` transfer's operands, relative to its result: Vulkan's +/// `exp2(y · log2(x))` with `y` 2.4 and `x` in `[0.052, 1.24]` (codes up to 1023), `log2`'s three +/// units in the last place at most `3 · 2^-21` of `|log2 x|` below 4.3, times 2.4, `exp2`'s +/// `3 + 2 · |z|` units at `|z|` up to 10.3, and the `OpFDiv` before it, rounded up. +const POW_RELATIVE: f64 = 8e-6; + +/// Whether `got`, the device's `float` read of the code `code` of a channel of `form` (alpha where +/// `alpha`), holds as Metal's read of it ([`value_within`]). +pub(super) fn read_within(form: ExtendedRange, got: f32, code: u32, alpha: bool) -> bool { + value_within(form, got, metal_read(form, code, alpha), alpha) +} + +/// The steps of `2^-13` an `_sRGB` colour channel of `form` may lie from Metal's table under +/// `PrecisionNote::DevicePackConversion`'s bound, beyond the `Pow`'s: half a step for the +/// extended-range twins, 1.64 for `R10Unorm_X6_sRGB`'s and `RGB10A2Unorm_sRGB`'s colours (which +/// convert as `R10Unorm_X6_sRGB`'s); none for a channel read linearly. +fn srgb_steps(form: ExtendedRange, alpha: bool) -> Option { + match form { + _ if alpha => None, + ExtendedRange::R10X6Srgb | ExtendedRange::Rgb10A2Srgb => Some(1.64), + _ if form.srgb() => Some(0.5), + _ => None, + } +} + +/// Whether `got`, the device's `float` read of a channel of `form` (alpha where `alpha`), holds as +/// Metal's read `want` of the same code under `PrecisionNote::DevicePackConversion`'s bound: a +/// linear value or alpha within one `f32` unit in the last place, an `_sRGB` colour within its +/// steps of `2^-13` ([`srgb_steps`]) beyond the `Pow`'s bound ([`POW_RELATIVE`]). +pub(super) fn value_within(form: ExtendedRange, got: f32, want: f32, alpha: bool) -> bool { + if got.to_bits() == want.to_bits() || (got == 0.0 && want == 0.0) { + return true; + } + if !got.is_finite() || !want.is_finite() { + return false; + } + if let Some(steps) = srgb_steps(form, alpha) { + let off = (f64::from(got) - f64::from(want)).abs(); + return off <= steps * 2f64.powi(-13) + f64::from(want).abs() * POW_RELATIVE; + } + got.is_sign_negative() == want.is_sign_negative() && got.to_bits().abs_diff(want.to_bits()) <= 1 +} + +/// Whether `got`, the device's `half` result of a channel of `form` (alpha where `alpha`), holds +/// as Metal's `float` read `want` of the same code narrowed: the device's narrowing of a `float` +/// within [`value_within`] of `want`, so within that bound and one `half` unit in the last place at +/// `got` (`PrecisionNote::DevicePackConversion`'s `half` result within one unit). +pub(super) fn half_within(form: ExtendedRange, got: f32, want: f32, alpha: bool) -> bool { + if !got.is_finite() || !want.is_finite() { + return got.to_bits() == want.to_bits(); + } + // A `half`'s unit in the last place at `got`: 2^-24 among the denormals. + let ulp = match got.abs() { + g if g < 2f32.powi(-14) => 2f64.powi(-24), + g => 2f64.powi(g.log2().floor() as i32 - 10), + }; + let reach = match srgb_steps(form, alpha) { + Some(steps) => steps * 2f64.powi(-13) + f64::from(want).abs() * POW_RELATIVE, + // One `f32` unit in the last place. + None => f64::from(want.abs()) * 2f64.powi(-23), + }; + (f64::from(got) - f64::from(want)).abs() <= reach + ulp +} + +/// The `PrecisionNote::DevicePackConversion` announcement the lanes require where `moved` of their +/// values hold within its bound but not as Metal's: the runtime announced it (`what` names the +/// lane's values), among the notices `messages` holds, which it takes. +pub(super) fn assert_announced(messages: &Messages, moved: usize, what: &str) { + assert_counted(&counts(&messages.take_notices()), moved, what); +} + +/// [`assert_announced`] of the notices `announced` counts, for a lane that reads other kinds of +/// the same notices. +pub(super) fn assert_counted(announced: &BTreeMap, moved: usize, what: &str) { + let note = Degradation::from_precision_note(PrecisionNote::DevicePackConversion); + assert!( + moved == 0 || announced.contains_key(¬e), + "{what}: {moved} values within the device's conversion, unannounced: {announced:?}" + ); +} + +/// The bytes Metal's recording of the conformance case `case` (the Apple M3 Max, macOS 27.0.1) +/// holds at the site `path` below the case's root (`["output", "codes"]`): Metal's own outputs, +/// whole, which the lanes compare value by value. +pub(super) fn recorded(case: &str, path: &[&str]) -> Vec { + use base64::Engine as _; + let file = format!( + "{}/../metal2vulkan-conformance/recordings/{case}.json", + env!("CARGO_MANIFEST_DIR") + ); + let text = std::fs::read_to_string(&file).unwrap_or_else(|e| panic!("{file}: {e}")); + let recording: serde_json::Value = serde_json::from_str(&text).unwrap(); + let answer = recording["answers"] + .as_array() + .unwrap() + .iter() + .find(|a| a["key"]["chip"] == "apple-m3-max" && a["key"]["os_version"] == "27.0.1") + .unwrap_or_else(|| panic!("{case}: no answer of the M3 Max under macOS 27.0.1")); + let mut node = &answer["outcomes"][0]["transcript"]["root"]; + for name in path { + node = node["children"] + .as_array() + .unwrap() + .iter() + .find(|n| n["name"] == *name) + .unwrap_or_else(|| panic!("{case}: no site {path:?}")); + } + base64::engine::general_purpose::STANDARD + .decode(node["observed"]["value"]["bytes"].as_str().unwrap()) + .unwrap() +} + +/// Metal's `half` read of an extended-range code whose `float` read is `v`: `v` rounded to the +/// nearest `half`, ties away from zero (`PrecisionNote::DevicePackConversion`'s statement of +/// Metal's rounding; it gives Metal's digests of every `half` pattern and `float` grid written to +/// and read from a two-plane texture). +pub(super) fn metal_half(v: f32) -> u16 { + let h = half_bits(v); + let (sign, magnitude) = (h & 0x8000, h & 0x7fff); + let a = f64::from(v.abs()); + let at = |m: u16| f64::from(half_value(m)); + // The `half` on the other side of `|v|` from the nearest one. + let other = match at(magnitude) > a { + true => magnitude.saturating_sub(1), + false => magnitude + 1, + }; + match a == (at(magnitude) + at(other)) / 2.0 { + true => sign | magnitude.max(other), + false => h, + } +} + +/// The `float4` reads `floats` and `half4` reads `halves` of a texture of `form`, one a grid +/// thread, with each lane whose thread reads a texel Metal holds the codes `metal` of (red, green, +/// blue and alpha; `None` for a channel the form lacks, or a thread past the texture) replaced by +/// Metal's reads of Metal's code where the device's lanes hold within +/// `PrecisionNote::DevicePackConversion`'s bound: the code the device's `float` read came from +/// ([`nearest_code`]) within one of Metal's (a write's bound), that read within its bound of +/// Metal's read of that code ([`read_within`]) and the `half` read within its bound of it +/// ([`half_within`]). What Metal's reads give where the device held the bound, so their digests +/// are Metal's; a lane past it stays as the device read it. Also how many texels the bound moved. +pub(super) fn as_metal_reads( + form: ExtendedRange, + (floats, halves): (&[u8], &[u8]), + metal: &[[Option; 4]], +) -> (Vec, Vec, usize) { + let (mut f, mut h) = (floats.to_vec(), halves.to_vec()); + let mut moved = 0; + for (t, codes) in metal.iter().enumerate() { + let mut changed = false; + for (c, code) in codes.iter().enumerate() { + let Some(code) = *code else { continue }; + let alpha = c == 3; + let (fi, hi) = (16 * t + 4 * c, 8 * t + 2 * c); + let v = f32::from_le_bytes(f[fi..fi + 4].try_into().unwrap()); + let hv = half_value(u16::from_le_bytes([h[hi], h[hi + 1]])); + let read = nearest_code(form, v, alpha); + let held = read.abs_diff(code) <= 1 + && read_within(form, v, read, alpha) + && half_within(form, hv, metal_read(form, read, alpha), alpha); + if !held { + continue; + } + let want = metal_read(form, code, alpha); + changed |= v.to_bits() != want.to_bits() + || hv.to_bits() != half_value(metal_half(want)).to_bits(); + f[fi..fi + 4].copy_from_slice(&want.to_le_bytes()); + h[hi..hi + 2].copy_from_slice(&metal_half(want).to_le_bytes()); + } + moved += usize::from(changed); + } + (f, h, moved) +}