From e31bc611720200f7233a353f1b4f062dbdf98f74 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 3 Dec 2026 01:45:19 -0800 Subject: [PATCH] Validation: a precision note excuses only the words its operations feed, within its bound What: a candidate's output is judged against Metal's one 32-bit word at a time (observation_contract::words). An equal word matches. A differing word is excused only by a recorded note that reaches it: a note with a bound makes a word within it a match, a note with no bound makes it a noted word, and a word no reaching note excuses is a mismatch. - Reach is read from the case's AIR (check::output_words): for each output word, the float lanes it holds and the operation families whose results feed it, followed byte by byte through bitcasts, lane moves and the zext/shl/or that pack two halves. A store placed at A * thread_position_in_grid + B bytes gives each thread's words their own facts. A note of the module that writes the output reaches the words its operations feed; a note of another module reaches every word, and so does every note of a word the scan cannot follow (a load of memory the entry writes, a call outside the intrinsic families). - Bounds a word can carry are checked there, and a word within one matches: DeviceDenormals only where Metal's and the device's lanes both lie at or below the smallest normal (2^-126, 2^-14 for half), of one sign unless one is a zero; NativeNanEncoding only two NaNs of the lane's format (it reaches every float lane: a half read from its bits is no operation); HalfTexelConversion its recorded one half ulp, or +-65504 beside the infinity; the lane tables and the reassociation bound as before. - NativeFma, NativeDot, NativeMix and NativeDivision keep no value bound (each states its bound over the operands, which a word does not carry) and reach only the words their operations feed. The fixture knows its inputs, so a per-case bound from the operands is a later form. - SimdgroupAccessOrder reaches only a word another thread of the kernel may write: one a store the scan cannot place in its own thread's bytes writes. - Rows record the output's word facts (census output_words). The batch report prints, per case and in total, the words matched exactly, within each note's bound and only noted, by note, the unexcused words, and the cases with a word on the fall-back. - DeviceDenormals's rustdoc states Metal's measured answer per operation: it flushes before rounding on some (a product, fma, dot and mix just below 2^-126 answer a zero) and keeps a denormal on others (sin, tan, asin, sinh, asinh, atanh of a denormal), from the public cases float-products-flushed-before-rounding and nan-model-float-denormals-per-operation. Its recording rule already covers plain multiplies; no rule changed. ENGINE_EXECUTOR_ABI is v215: how a match is decided changed and rows record word facts. Why: a noted difference was excused whole by any recorded note, so a note that could not cause a word's difference (a division's note beside a product, an access-order note on a kernel whose threads write disjoint words) hid it, and a bounded note never matched. Verified on lavapipe (Mesa 26.2.4, the lavapipe image), the 1,168 public cases, job m3-max-82854 (this tree with the next commit's doc text) against m3-max-82667 at b3d7464945: match 746 -> 773, noted_difference 188 -> 161, mismatch 5 -> 5 (each held open by clipped_primitive_split, as before); words 2,859,015 exact, 30,212 within a bound, 352,820 noted, 0 unexcused. Of the 188 cases noted before, 34 have an output word on the fall-back (26 every word) and 32 a differing one. Tests: the validation suite at an earlier tree, m3-max-82839 (1,331 passed, 3 failed; the three are fixed here), and the touched modules at the same tree as m3-max-82854, m3-max-82855 (136 passed). --- .../metal2vulkan-validation/src/c3/tests.rs | 4 + .../src/candidate/engine.rs | 51 +- .../src/candidate/engine/tests.rs | 32 +- .../src/candidate/platform/runtime.rs | 1 + crates/metal2vulkan-validation/src/check.rs | 1 + .../src/check/interface.rs | 6 + .../src/check/output_words.rs | 1455 +++++++++++++++++ .../src/check/output_words/tests.rs | 138 ++ .../metal2vulkan-validation/src/coverage.rs | 86 +- .../src/coverage/tests.rs | 2 + .../src/executor_contract/out_of_bounds.rs | 50 +- .../executor_contract/out_of_bounds/tests.rs | 169 +- crates/metal2vulkan-validation/src/index.rs | 2 + .../src/observation.rs | 92 +- .../src/observation_contract.rs | 1 + .../src/observation_contract/comparison.rs | 179 +- .../observation_contract/comparison/tests.rs | 89 +- .../src/observation_contract/words.rs | 610 +++++++ .../src/observation_contract/words/tests.rs | 392 +++++ crates/metal2vulkan-validation/src/store.rs | 1 + crates/metal2vulkan-validation/src/triage.rs | 5 + .../src/vulkan_batch.rs | 148 ++ .../src/vulkan_batch/tests.rs | 36 +- .../src/worker/device/tests.rs | 1 + crates/metal2vulkan/src/pipeline/artifact.rs | 28 +- docs/API.md | 11 +- docs/VALIDATION.md | 23 +- 27 files changed, 3226 insertions(+), 387 deletions(-) create mode 100644 crates/metal2vulkan-validation/src/check/output_words.rs create mode 100644 crates/metal2vulkan-validation/src/check/output_words/tests.rs create mode 100644 crates/metal2vulkan-validation/src/observation_contract/words.rs create mode 100644 crates/metal2vulkan-validation/src/observation_contract/words/tests.rs diff --git a/crates/metal2vulkan-validation/src/c3/tests.rs b/crates/metal2vulkan-validation/src/c3/tests.rs index 956052dd1..b964290e9 100644 --- a/crates/metal2vulkan-validation/src/c3/tests.rs +++ b/crates/metal2vulkan-validation/src/c3/tests.rs @@ -282,6 +282,7 @@ fn noting(mut row: CandidateObservation, notes: &[PrecisionNote]) -> CandidateOb out_of_bounds: None, rate_map_pass: None, artifact: None, + output_words: None, }); row } @@ -1115,6 +1116,7 @@ fn a_device_interpolation_row_stays_a_mismatch() { containment: None, }], artifact: None, + output_words: None, }); row.comparison = ComparisonClass::Unbounded([note].into()); row.status = noted_if_different(row.status); @@ -1223,6 +1225,7 @@ fn deferred_and_never_reviewed(note: PrecisionNote, label: &str) { containment: None, }], artifact: None, + output_words: None, }); row.comparison = ComparisonClass::Unbounded([note].into()); row.status = noted_if_different(row.status); @@ -3017,6 +3020,7 @@ fn a_deferred_near_equivalent_stays_open_with_its_reason() { containment: None, }], artifact: None, + output_words: None, }); row.comparison = ComparisonClass::Unbounded([PrecisionNote::SparseResidency].into()); row.status = noted_if_different(row.status); diff --git a/crates/metal2vulkan-validation/src/candidate/engine.rs b/crates/metal2vulkan-validation/src/candidate/engine.rs index f5dd7fd5a..ca89ec0ac 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine.rs @@ -51,9 +51,10 @@ use crate::library_module::{ResolvedFunctionTable, ResolvedLinkedFunctions}; use crate::literal::{LiteralDepthStencil, LiteralResources, LiteralTexture}; use crate::metal::ORACLE_ABI; use crate::observation::{ - may_be_noted, CandidateDependencies, CandidateObservation, CandidateStatus, CaseTiming, - MetalObservation, RUNTIME_CRATE_FINGERPRINT, TRANSLATOR_FINGERPRINT, + CandidateDependencies, CandidateObservation, CandidateStatus, CaseTiming, MetalObservation, + RUNTIME_CRATE_FINGERPRINT, TRANSLATOR_FINGERPRINT, }; +use crate::observation_contract::words::Verdict; use crate::observation_contract::ComparisonClass; use crate::refusal::{Refusal, RefusalObservation}; use crate::requirement::{Executor, ToolingRequirement}; @@ -94,7 +95,7 @@ pub mod variants; /// how it decides a match. A change no recorded row can observe (a case kind no earlier executor /// ran, or one it refused) needs no bump; its commit says why. The commit that bumps it says what /// changed; this comment keeps no history. -pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v214"; +pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v215"; /// One kernel case in the terms the runtime route takes: what this executor supports of an /// [`AuthoredCase`] (buffers, device buffer arrays, argument-buffer buffers and textures, @@ -1575,7 +1576,7 @@ pub fn execute_prepared( source_index: crate::source::source_index(), }; let DeviceOutcome { result, refused_on } = crate::worker::device::execute(worker, &input); - let run = match result { + let mut run = match result { Ok(run) => run, // A typed refusal on an opened device is evidence too: stored in the slot the row would // have taken, with that device's facts. @@ -1598,29 +1599,26 @@ pub fn execute_prepared( } Err(error) => return Err(error), }; + // Which notes reach each word of the output is the case's AIR's fact, read where the case was + // checked. + run.census.output_words = Some(checked.primary.interface.output_words(case)); let slot = engine_slot(environment_id, run.census.restricted_to.as_deref()); let candidate_output_sha256 = sha256_bytes(&run.output); let golden = base64::engine::general_purpose::STANDARD .decode(&metal.output_b64) .map_err(|error| format!("decode the Metal observation's output: {error}"))?; - // A case with out-of-bounds targets is judged by their containment property. - let (status, held_open_by) = if crate::executor_contract::out_of_bounds::matches( + // Each word is judged by the notes that reach it; a case with out-of-bounds targets first by + // their containment property. + let judgement = crate::executor_contract::out_of_bounds::judge( case, - &run.comparison, + Some(&run.census), &golden, &run.output, run.census.out_of_bounds.as_ref(), - ) { - (CandidateStatus::Match, None) - } else { - difference_status( - &checked, - candidate_output_sha256 != metal.metal_output_sha256, - &run.comparison, - run.census.out_of_bounds.as_ref(), - || ReviewedList::load(&ReviewedList::committed_path()), - )? - }; + ); + let (status, held_open_by) = difference_status(&checked, judgement.verdict(), || { + ReviewedList::load(&ReviewedList::committed_path()) + })?; let observation = CandidateObservation { case_id: case.case_id.clone(), air_sha256: case.air_sha256.clone(), @@ -1657,22 +1655,21 @@ pub fn execute_prepared( Ok(observation) } -/// The status of a run of `checked` whose output does not match Metal's under its class -/// `comparison` (`differs`: its bytes differ; `run`: its out-of-bounds facts), and the answer gap -/// that holds it open: a noted difference where it may be one ([`may_be_noted`]), unless the C3 -/// reviewed list (`list`, read only then) holds the case under an answer gap its structure meets +/// The status of a run of `checked` whose words were judged `verdict`, and the answer gap that +/// holds it open: a match, a mismatch, or a noted difference unless the C3 reviewed list (`list`, +/// read only then) holds the case under an answer gap its structure meets /// ([`AnswerGap::met_by`]), which keeps it a mismatch (the user's decision of 2026-10-06). Which /// venues' devices have the gap is C3's to judge; here the case's difference is a mismatch on every /// device, which hides none. pub fn difference_status( checked: &CheckedCase, - differs: bool, - comparison: &ComparisonClass, - run: Option<&OutOfBoundsRun>, + verdict: Verdict, list: impl FnOnce() -> Result, ) -> Result<(CandidateStatus, Option), String> { - if !may_be_noted(differs, comparison, run) { - return Ok((CandidateStatus::Mismatch, None)); + match verdict { + Verdict::Match => return Ok((CandidateStatus::Match, None)), + Verdict::Mismatch => return Ok((CandidateStatus::Mismatch, None)), + Verdict::Noted => {} } let case_id = &checked.primary.case.case_id; Ok( diff --git a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs index 576456329..77d7a95bb 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs @@ -17,24 +17,22 @@ fn device(stem: &str, policy: DevicePolicy) -> Device { Device::from_queries(description, policy).unwrap() } -/// A difference under notes is a noted difference unless the C3 reviewed list holds its case under -/// an answer gap the case's structure meets: then it stays a mismatch naming the gap. Judged over -/// the committed list's every answer gap over a public fixture and its committed case, and a -/// committed public case it does not hold; a difference no note can explain is a mismatch for -/// either. +/// A noted verdict is a noted difference unless the C3 reviewed list holds its case under an +/// answer gap the case's structure meets: then it stays a mismatch naming the gap. Judged over the +/// committed list's every answer gap over a public fixture and its committed case, and a committed +/// public case it does not hold; a mismatching verdict is a mismatch for either, and a matching +/// one a match. #[test] fn a_difference_under_notes_is_noted_unless_an_answer_gap_holds_its_case_open() { let root = crate::source::corpus_root(); let store = CorpusStore::new(&root); let list = ReviewedList::load(&ReviewedList::committed_path()).unwrap(); - let noted = ComparisonClass::Unbounded( - [metal2vulkan::pipeline::PrecisionNote::ClippedCoverageSplit].into(), - ); - let status = |case: &AuthoredCase, comparison: &ComparisonClass| { + let status = |case: &AuthoredCase, verdict: Verdict| { let checked = crate::check::check_case(&root, case.clone()) .unwrap_or_else(|errors| panic!("{}: {errors:?}", case.name)); - difference_status(&checked, true, comparison, None, || Ok(list.clone())).unwrap() + difference_status(&checked, verdict, || Ok(list.clone())).unwrap() }; + let unexplained = (CandidateStatus::Mismatch, None); let mut public = 0; for entry in &list.answer_gaps { let case = store.find_case(&entry.case_id).unwrap().unwrap(); @@ -42,9 +40,12 @@ fn a_difference_under_notes_is_noted_unless_an_answer_gap_holds_its_case_open() continue; } let held = (CandidateStatus::Mismatch, Some(entry.gap)); - assert_eq!(status(&case, ¬ed), held, "{}", case.name); - let unexplained = (CandidateStatus::Mismatch, None); - assert_eq!(status(&case, &ComparisonClass::Exact), unexplained); + assert_eq!(status(&case, Verdict::Noted), held, "{}", case.name); + assert_eq!(status(&case, Verdict::Mismatch), unexplained); + assert_eq!( + status(&case, Verdict::Match), + (CandidateStatus::Match, None) + ); public += 1; } assert!(public >= 5, "{public}"); @@ -57,9 +58,8 @@ fn a_difference_under_notes_is_noted_unless_an_answer_gap_holds_its_case_open() }) .unwrap(); let difference = (CandidateStatus::NotedDifference, None); - assert_eq!(status(&unheld, ¬ed), difference); - let unexplained = (CandidateStatus::Mismatch, None); - assert_eq!(status(&unheld, &ComparisonClass::Exact), unexplained); + assert_eq!(status(&unheld, Verdict::Noted), difference); + assert_eq!(status(&unheld, Verdict::Mismatch), unexplained); } /// [`compute_case`] of a case whose entry declares no stage input: every case here but the diff --git a/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs b/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs index 5ad4ea33c..fab0b0d27 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs @@ -667,6 +667,7 @@ pub(super) fn ran( restricted_to: identity.restricted_to.clone(), modules: vec![module], artifact: None, + output_words: None, }; ComputeRun { output, diff --git a/crates/metal2vulkan-validation/src/check.rs b/crates/metal2vulkan-validation/src/check.rs index 3debe6cd6..08e1b8a7b 100644 --- a/crates/metal2vulkan-validation/src/check.rs +++ b/crates/metal2vulkan-validation/src/check.rs @@ -15,6 +15,7 @@ mod conformance; pub mod grid_reach; pub mod interface; pub mod loop_free; +pub mod output_words; pub mod safety_census; pub mod table_index; diff --git a/crates/metal2vulkan-validation/src/check/interface.rs b/crates/metal2vulkan-validation/src/check/interface.rs index 4249aba3c..a41409ae7 100644 --- a/crates/metal2vulkan-validation/src/check/interface.rs +++ b/crates/metal2vulkan-validation/src/check/interface.rs @@ -324,6 +324,9 @@ pub struct AirInterface { /// The simdgroup float sums and products the entry and the functions it calls in its module /// call ([`float_reductions`]). pub float_reductions: BTreeSet<&'static str>, + /// What the entry's stores show of the buffers it writes + /// ([`super::output_words::Stores`]): `None` where the scan does not follow the entry. + pub stores: Option, } /// How an entry reads its `[[vertex_id]]` argument. An indexed draw's index read past its buffer is @@ -447,7 +450,9 @@ impl AirInterface { vertex_id: VertexIdUse::Unused, grid_reaches, float_reductions: float_reductions(module, [ep.func]), + stores: None, }; + interface.stores = super::output_words::scan(module, ep.func, &interface.params, ep.stage); interface.vertex_id = vertex_id_use(module, ep.func, &interface.params); Uses::scan(module, ep.func)?.record(&mut interface); Ok(interface) @@ -1810,6 +1815,7 @@ impl AirInterface { vertex_id: VertexIdUse::Unused, grid_reaches: Vec::new(), float_reductions: BTreeSet::new(), + stores: None, } } } diff --git a/crates/metal2vulkan-validation/src/check/output_words.rs b/crates/metal2vulkan-validation/src/check/output_words.rs new file mode 100644 index 000000000..abdd0e4a4 --- /dev/null +++ b/crates/metal2vulkan-validation/src/check/output_words.rs @@ -0,0 +1,1455 @@ +//! What an entry's stores show of the words of each buffer they write ([`Stores`]), and from it, +//! of each word of a case's output ([`output_words`]). +//! +//! The scan follows every value of the entry byte by byte: which float lane a byte belongs to (a +//! `float`'s or a `half`'s, kept through bitcasts, lane moves and the `zext`/`shl`/`or` that pack +//! two halves into a word), and which operation families ([`Family`]) may feed it, through every +//! operand, a `select`'s condition, a load's address, and the conditions of the branches a `phi` +//! or a store depends on. A load of memory the entry writes, a call outside the closed intrinsic +//! set, and an intrinsic family the scan does not model feed [`Family::Unknown`], which every note +//! reaches. +//! +//! A store is placed when its address is its buffer argument plus `A * g + B` bytes, `g` one +//! component of `[[thread_position_in_grid]]` and `A`, `B` constants. When every store to a +//! kernel's output buffer is so placed, at one `A` with each store's bytes inside `[0, A)`, and the +//! dispatch's grid has one thread along its other axes, every thread writes only its own `A` +//! bytes: the words repeat every `A` bytes, each with the facts of the stores that write it. +//! Otherwise every word takes the union of every store's facts, and in a kernel +//! [`Family::Unordered`]: another thread may write it. + +use super::interface::{AirInterface, Param}; +use crate::case::{AuthoredCase, OutputSelection}; +use crate::observation_contract::words::{Families, Family, OutputWords, WordFacts, WordShape}; +use crate::observation_contract::{FloatLane, ObservationLanes}; +use metal2vulkan::Budget; +use metal2vulkan_air::abi::{Builtin, ParamRole, Stage as AbiStage}; +use metal2vulkan_air::budget::Meter; +use metal2vulkan_air::graph::{Cfg, PostDomTree}; +use metal2vulkan_air::intrinsics::{AirIntrinsic, LlvmFloatOp, LlvmIntrinsic, MathFn, NumKind}; +use metal2vulkan_air::ir::{ + AddrSpace, BinOp, Body, Callee, CastOp, Const, ConstId, FuncId, Idx, Inst, InstKind, Module, + Type, TypeId, TypeLayouts, Value, +}; +use std::collections::{BTreeMap, BTreeSet}; + +/// The largest value, in bytes, the scan follows byte by byte; an entry with a larger one is not +/// scanned. +const LARGEST_VALUE: u64 = 4096; + +/// The most passes the scan's fixed point takes; an entry that needs more is not scanned. +const PASSES: usize = 64; + +/// What one byte of a value is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ByteKind { + /// Byte `n` of a `float`. + Float(u8), + /// Byte `n` of a `half`. + Half(u8), + /// A byte known to be zero. + Zero, + /// Anything else. + Other, +} + +/// One byte of a value: what it is, and the families that may feed it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ByteFact { + pub kind: ByteKind, + pub fed: Families, +} + +impl ByteFact { + fn join(self, other: ByteFact) -> ByteFact { + ByteFact { + kind: if self.kind == other.kind { + self.kind + } else { + ByteKind::Other + }, + fed: self.fed.union(other.fed), + } + } + + fn feed(self, fed: Families) -> ByteFact { + ByteFact { + kind: self.kind, + fed: self.fed.union(fed), + } + } +} + +/// Where a store's bytes land in its buffer: at `period * g + offset`, `g` component `axis` of +/// the writing thread's `[[thread_position_in_grid]]`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Place { + pub axis: u32, + pub period: u64, + pub offset: u64, +} + +/// One store into a buffer argument. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoreFacts { + /// `None`: the scan cannot place it. + pub place: Option, + /// The stored bytes, with the families of the branches the store depends on. + pub bytes: Vec, + /// Its address is a multiple of 4. + pub word_aligned: bool, +} + +/// Every write into one buffer argument. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct BufferWrites { + pub stores: Vec, + /// A write the scan cannot describe: an atomic, a call that writes through the argument. + pub opaque: bool, +} + +/// What an entry's stores show of the buffers it writes. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Stores { + /// By the entry's LLVM parameter index. + pub buffers: BTreeMap, + /// The entry writes device memory through a pointer no buffer argument roots: any buffer may + /// be written. + pub unrooted_device_write: bool, +} + +/// Where a pointer points. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Base { + Param(u32), + Global(metal2vulkan_air::ir::GlobalId), + Other, +} + +/// `A * g + B`, `g` a grid component (`axis`, or no component where `scale` is 0). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Affine { + axis: Option, + scale: i128, + offset: i128, +} + +impl Affine { + fn constant(offset: i128) -> Affine { + Affine { + axis: None, + scale: 0, + offset, + } + } + + fn add(self, other: Affine) -> Option { + let axis = match (self.axis, other.axis) { + (Some(a), Some(b)) if a != b => return None, + (a, b) => a.or(b), + }; + Some(Affine { + axis, + scale: self.scale.checked_add(other.scale)?, + offset: self.offset.checked_add(other.offset)?, + }) + } + + fn times(self, factor: i128) -> Option { + Some(Affine { + axis: self.axis, + scale: self.scale.checked_mul(factor)?, + offset: self.offset.checked_mul(factor)?, + }) + } +} + +/// Scan the entry `entry` of `module` (parameters `params`, stage `stage`). `None` when its body, +/// layouts or a value are past what the scan follows. +pub fn scan(module: &Module, entry: FuncId, params: &[Param], stage: AbiStage) -> Option { + let body = module.func(entry)?.body.as_ref()?; + let mut meter = Meter::new(&Budget::default()); + let layouts = TypeLayouts::new(module.data_layout(), module.types(), &mut meter).ok()?; + let mut scan = Scan { + module, + entry, + body, + layouts: &layouts, + params: params_facts(module, entry, params, stage), + positions: params + .iter() + .filter(|param| { + matches!( + param.binding.role, + ParamRole::Builtin(Builtin::ThreadPositionInGrid) + ) + }) + .map(|param| param.binding.param) + .collect(), + written: BTreeSet::new(), + facts: vec![None; body.insts.len()], + control: Families::NONE, + }; + let mut stores = Stores::default(); + scan.writes(&mut stores); + scan.fixed_point()?; + scan.collect(&mut stores, &mut meter)?; + Some(stores) +} + +/// The families each parameter feeds: a fragment function's inputs feed [`Family::StageInput`], +/// a thread's place in its simdgroup or quad [`Family::Group`], a kernel's other built-ins +/// nothing, and a non-kernel, non-fragment entry's inputs [`Family::Unknown`]. +fn params_facts( + module: &Module, + entry: FuncId, + params: &[Param], + stage: AbiStage, +) -> BTreeMap { + let count = module + .func(entry) + .map_or(0, |function| function.params.len()); + (0..count as u32) + .map(|index| { + let role = params + .iter() + .find(|param| param.binding.param == index) + .map(|param| ¶m.binding.role); + let group = matches!( + role, + Some(ParamRole::Builtin( + Builtin::ThreadIndexInSimdgroup + | Builtin::ThreadIndexInQuadgroup + | Builtin::SimdgroupIndexInThreadgroup + | Builtin::QuadgroupIndexInThreadgroup + | Builtin::ThreadsPerSimdgroup + | Builtin::SimdgroupsPerThreadgroup + | Builtin::QuadgroupsPerThreadgroup + | Builtin::DispatchSimdgroupsPerThreadgroup + )) + ); + let resource = matches!( + role, + Some( + ParamRole::Buffer(_) + | ParamRole::ArgumentBuffer(_) + | ParamRole::Threadgroup(_) + | ParamRole::Texture(_) + | ParamRole::Sampler { .. } + ) + ); + let families = if group { + Families::NONE.with(Family::Group) + } else if resource { + Families::NONE + } else { + match stage { + AbiStage::Kernel { .. } => match role { + Some(ParamRole::Builtin(_)) => Families::NONE, + _ => Families::NONE.with(Family::Unknown), + }, + AbiStage::Fragment { .. } => Families::NONE.with(Family::StageInput), + _ => Families::NONE.with(Family::Unknown), + } + }; + (index, families) + }) + .collect() +} + +struct Scan<'a> { + module: &'a Module, + entry: FuncId, + body: &'a Body, + layouts: &'a TypeLayouts, + params: BTreeMap, + /// The `[[thread_position_in_grid]]` parameters. + positions: BTreeSet, + /// The parameters the entry writes through. + written: BTreeSet, + /// Per instruction, its value's bytes; `None` before the scan reaches it, and for an + /// instruction with no value. + facts: Vec>>, + /// The families of every branch condition. + control: Families, +} + +impl Scan<'_> { + fn types(&self) -> &metal2vulkan_air::ir::TypeTable { + self.module.types() + } + + fn value_ty(&self, value: Value) -> Option { + self.module.value_ty(self.entry, value) + } + + fn inst(&self, value: Value) -> Option<&Inst> { + match value { + Value::Inst(id) => self.body.insts.get(id), + _ => None, + } + } + + /// The byte kinds of a value of type `ty`, each `fed`. + fn natural(&self, ty: TypeId, fed: Families) -> Option> { + let kinds = self.kinds(ty)?; + Some( + kinds + .into_iter() + .map(|kind| ByteFact { kind, fed }) + .collect(), + ) + } + + fn kinds(&self, ty: TypeId) -> Option> { + let size = self.layouts.alloc_size(ty)?; + if size > LARGEST_VALUE { + return None; + } + Some(match self.types().get(ty)? { + Type::Float => (0..4).map(ByteKind::Float).collect(), + Type::Half => (0..2).map(ByteKind::Half).collect(), + Type::Vector { elem, len } => { + let lane = self.kinds(*elem)?; + let width = self.layouts.store_size(*elem)? as usize; + let mut bytes = Vec::new(); + for _ in 0..*len { + bytes.extend(lane.iter().copied().take(width)); + } + bytes + } + Type::Array { elem, len } => { + let stride = self.layouts.alloc_size(*elem)? as usize; + let mut lane = self.kinds(*elem)?; + lane.resize(stride, ByteKind::Other); + let mut bytes = Vec::new(); + for _ in 0..*len { + bytes.extend(lane.iter().copied()); + } + bytes + } + Type::Struct { fields, .. } => { + let offsets = self.layouts.field_offsets(ty)?.to_vec(); + let mut bytes = vec![ByteKind::Other; size as usize]; + for (field, offset) in fields.iter().zip(offsets) { + for (at, kind) in self.kinds(*field)?.into_iter().enumerate() { + *bytes.get_mut(offset as usize + at)? = kind; + } + } + bytes + } + _ => vec![ByteKind::Other; size as usize], + }) + } + + /// The lane count and lane width of a value of type `ty`: a vector's, or one lane. + fn lanes(&self, ty: TypeId) -> Option<(usize, usize)> { + match self.types().get(ty)? { + Type::Vector { elem, len } => { + Some((*len as usize, self.layouts.store_size(*elem)? as usize)) + } + _ => Some((1, self.layouts.alloc_size(ty)? as usize)), + } + } + + /// The bytes of `value`; `None` for an instruction the scan has not reached. + fn value(&self, value: Value) -> Option> { + match value { + Value::Inst(id) => self.facts.get(id.index())?.clone(), + Value::Arg(arg) => { + let fed = self + .params + .get(&u32::try_from(arg.index()).ok()?) + .copied() + .unwrap_or(Families::NONE.with(Family::Unknown)); + self.natural(self.value_ty(value)?, fed) + } + Value::Const(id) => self.constant(id), + } + } + + fn constant(&self, id: ConstId) -> Option> { + let constant = self.module.consts().get(id)?; + let mut bytes = self.natural(constant.ty, Families::NONE)?; + let integer = |bits: u8| bits.is_multiple_of(8); + match (&constant.value, self.types().get(constant.ty)?) { + (Const::Int(raw), Type::Int(bits)) if integer(*bits) => { + for (at, byte) in bytes.iter_mut().enumerate() { + if (raw >> (8 * at)) & 0xff == 0 { + byte.kind = ByteKind::Zero; + } + } + } + (Const::Null, _) => { + for byte in &mut bytes { + if byte.kind == ByteKind::Other { + byte.kind = ByteKind::Zero; + } + } + } + (Const::Aggregate(elements), Type::Vector { elem, .. }) => { + let width = self.layouts.store_size(*elem)? as usize; + for (lane, element) in elements.iter().enumerate() { + let lane_bytes = self.constant(*element)?; + for (at, byte) in lane_bytes.into_iter().take(width).enumerate() { + *bytes.get_mut(lane * width + at)? = byte; + } + } + } + _ => {} + } + Some(bytes) + } + + /// The integer `value` holds: a constant, or a vector of one constant in every lane. + fn constant_int(&self, value: Value) -> Option { + let Value::Const(id) = value else { + return None; + }; + let constant = self.module.consts().get(id)?; + match &constant.value { + Const::Int(raw) => Some(*raw), + Const::Null => Some(0), + Const::Aggregate(elements) => { + let mut values = elements + .iter() + .map(|element| self.constant_int(Value::Const(*element))); + let first = values.next()??; + values.all(|value| value == Some(first)).then_some(first) + } + _ => None, + } + } + + /// Every family that feeds any byte of `bytes`. + fn fed(bytes: &[ByteFact]) -> Families { + bytes + .iter() + .fold(Families::NONE, |fed, byte| fed.union(byte.fed)) + } + + /// The families of each of `lanes` lanes of `value`: its own lane where it has as many, + /// every byte's otherwise. + fn lane_fed(&self, value: Value, lanes: usize) -> Option> { + let bytes = self.value(value)?; + let ty = self.value_ty(value)?; + let (own, width) = self.lanes(ty)?; + Some(if own == lanes && lanes > 1 { + bytes + .chunks(width.max(1)) + .map(Self::fed) + .chain(std::iter::repeat(Families::NONE)) + .take(lanes) + .collect() + } else { + vec![Self::fed(&bytes); lanes] + }) + } + + /// A value of type `ty` whose lane `l` is fed by lane `l` of each operand (or every byte of + /// an operand of another shape) and `extra`; its bytes are `ty`'s kinds, or `Other` where + /// `opaque`. + fn lanewise( + &self, + ty: TypeId, + operands: &[Value], + extra: Families, + opaque: bool, + ) -> Option> { + let (lanes, width) = self.lanes(ty)?; + let mut fed = vec![extra; lanes]; + for operand in operands { + for (lane, families) in self.lane_fed(*operand, lanes)?.into_iter().enumerate() { + fed[lane] = fed[lane].union(families); + } + } + let mut bytes = self.natural(ty, Families::NONE)?; + for (at, byte) in bytes.iter_mut().enumerate() { + byte.fed = fed[(at / width.max(1)).min(lanes - 1)]; + if opaque { + byte.kind = ByteKind::Other; + } + } + Some(bytes) + } + + /// Mark what each write writes: the parameters a store, an atomic or a writing call writes + /// through, the device pointers no parameter roots, and each buffer's writes the scan cannot + /// describe. + fn writes(&mut self, stores: &mut Stores) { + let mut targets = Vec::new(); + let body = self.body; + for (_, inst) in body.insts.iter() { + match &inst.kind { + InstKind::Store { ptr, .. } => targets.push((*ptr, false)), + InstKind::AtomicRmw { ptr, .. } | InstKind::CmpXchg { ptr, .. } => { + targets.push((*ptr, true)) + } + InstKind::Call(call) if writes_through(&call.callee) => { + for arg in call.args.iter() { + if self.value_ty(*arg).is_some_and(|ty| { + matches!(self.types().get(ty), Some(Type::Ptr { .. })) + }) { + targets.push((*arg, true)); + } + } + } + _ => {} + } + } + for (ptr, opaque) in targets { + match self.base(ptr, 0) { + Base::Param(param) => { + self.written.insert(param); + if opaque { + stores.buffers.entry(param).or_default().opaque = true; + } + } + Base::Global(_) => {} + Base::Other => { + let space = self + .value_ty(ptr) + .and_then(|ty| match self.types().get(ty) { + Some(Type::Ptr { space }) => Some(*space), + _ => None, + }); + if !matches!( + space, + Some(AddrSpace::Thread | AddrSpace::Threadgroup | AddrSpace::Constant) + ) { + stores.unrooted_device_write = true; + } + } + } + } + } + + /// The object `ptr` points into. + fn base(&self, ptr: Value, depth: usize) -> Base { + if depth > 64 { + return Base::Other; + } + match ptr { + Value::Arg(arg) => u32::try_from(arg.index()).map_or(Base::Other, Base::Param), + Value::Const(id) => match self.module.consts().get(id).map(|c| &c.value) { + Some(Const::GlobalAddr(global)) => Base::Global(*global), + _ => Base::Other, + }, + Value::Inst(_) => match self.inst(ptr).map(|inst| &inst.kind) { + Some(InstKind::Gep { base, .. }) => self.base(*base, depth + 1), + Some(InstKind::Cast { + op: CastOp::Bitcast | CastOp::AddrSpaceCast, + v, + }) => self.base(*v, depth + 1), + Some(InstKind::Select { t, f, .. }) => { + let (t, f) = (self.base(*t, depth + 1), self.base(*f, depth + 1)); + if t == f { + t + } else { + Base::Other + } + } + Some(InstKind::Phi { incoming, .. }) => { + let mut bases = incoming + .iter() + .map(|(value, _)| self.base(*value, depth + 1)); + let first = bases.next().unwrap_or(Base::Other); + if bases.all(|base| base == first) { + first + } else { + Base::Other + } + } + _ => Base::Other, + }, + } + } + + /// The families a load through `ptr` reads beyond its address: none from an input, constant + /// memory, or a global never written; [`Family::Unknown`] from memory the entry writes. + fn memory(&self, ptr: Value) -> Families { + match self.base(ptr, 0) { + Base::Param(param) if !self.written.contains(¶m) => Families::NONE, + Base::Global(global) + if self + .module + .global(global) + .is_some_and(|global| global.constant) => + { + Families::NONE + } + _ => Families::NONE.with(Family::Unknown), + } + } + + /// Run every instruction until no fact changes. + fn fixed_point(&mut self) -> Option<()> { + let body = self.body; + for _ in 0..PASSES { + let mut changed = false; + let mut control = self.control; + for (id, inst) in body.insts.iter() { + match &inst.kind { + InstKind::CondBr { c: value, .. } | InstKind::Switch { v: value, .. } => { + if let Some(bytes) = self.value(*value) { + control = control.union(Self::fed(&bytes)); + } + continue; + } + _ => {} + } + let Some(bytes) = self.transfer(inst) else { + continue; + }; + let slot = self.facts.get_mut(id.index())?; + let joined = match slot.take() { + Some(old) if old.len() == bytes.len() => { + let joined = old + .iter() + .zip(&bytes) + .map(|(old, new)| old.join(*new)) + .collect::>(); + changed |= joined != old; + joined + } + _ => { + changed = true; + bytes + } + }; + *slot = Some(joined); + } + changed |= control != self.control; + self.control = control; + if !changed { + return Some(()); + } + } + None + } + + /// The bytes of `inst`'s value from its operands' current facts; `None` for an instruction + /// with no value, or whose operands the scan has not reached. + fn transfer(&self, inst: &Inst) -> Option> { + let ty = inst.ty; + let unknown = Families::NONE.with(Family::Unknown); + match &inst.kind { + InstKind::BinOp { op, a, b, .. } => self.binop(ty, *op, *a, *b), + InstKind::FNeg { v, .. } => self.lanewise( + ty, + &[*v], + Families::NONE.with(Family::FloatArithmetic), + false, + ), + InstKind::Cast { op, v } => self.cast(ty, *op, *v), + InstKind::ICmp { a, b, .. } => self.lanewise(ty, &[*a, *b], Families::NONE, true), + InstKind::FCmp { a, b, .. } => self.lanewise( + ty, + &[*a, *b], + Families::NONE.with(Family::FloatArithmetic), + true, + ), + InstKind::Select { c, t, f, .. } => { + let (t, f) = (self.value(*t)?, self.value(*f)?); + let (lanes, width) = self.lanes(ty)?; + let condition = self.lane_fed(*c, lanes)?; + Some( + t.iter() + .zip(&f) + .enumerate() + .map(|(at, (t, f))| { + t.join(*f) + .feed(condition[(at / width.max(1)).min(lanes - 1)]) + }) + .collect(), + ) + } + InstKind::Freeze(v) => self.value(*v), + InstKind::ExtractElement { vec, idx } => { + let bytes = self.value(*vec)?; + let (lanes, width) = self.lanes(self.value_ty(*vec)?)?; + match self.constant_int(*idx) { + Some(lane) if (lane as usize) < lanes => { + let start = lane as usize * width; + bytes.get(start..start + width).map(<[ByteFact]>::to_vec) + } + _ => { + let index = Self::fed(&self.value(*idx)?); + let mut joined = bytes.get(..width)?.to_vec(); + for lane in bytes.chunks(width.max(1)) { + for (at, byte) in lane.iter().enumerate() { + joined[at] = joined[at].join(*byte); + } + } + Some(joined.into_iter().map(|byte| byte.feed(index)).collect()) + } + } + } + InstKind::InsertElement { vec, elt, idx } => { + let mut bytes = self.value(*vec)?; + let element = self.value(*elt)?; + let (lanes, width) = self.lanes(ty)?; + match self.constant_int(*idx) { + Some(lane) if (lane as usize) < lanes => { + let start = lane as usize * width; + for (at, byte) in element.into_iter().take(width).enumerate() { + *bytes.get_mut(start + at)? = byte; + } + } + _ => { + let index = Self::fed(&self.value(*idx)?); + for (at, byte) in bytes.iter_mut().enumerate() { + *byte = byte.join(*element.get(at % width.max(1))?).feed(index); + } + } + } + Some(bytes) + } + InstKind::ShuffleVector { a, b, mask } => { + let (left, right) = (self.value(*a)?, self.value(*b)?); + let (left_lanes, width) = self.lanes(self.value_ty(*a)?)?; + let undefined = self.natural(ty, Families::NONE)?; + let mut bytes = Vec::new(); + for (lane, pick) in mask.iter().enumerate() { + let source = match pick { + Some(pick) if (*pick as usize) < left_lanes => { + left.get(*pick as usize * width..(*pick as usize + 1) * width) + } + Some(pick) => { + let pick = *pick as usize - left_lanes; + right.get(pick * width..(pick + 1) * width) + } + None => undefined.get(lane * width..(lane + 1) * width), + }; + bytes.extend_from_slice(source?); + } + Some(bytes) + } + InstKind::ExtractValue { agg, indices } => { + let bytes = self.value(*agg)?; + let (offset, member) = self.member(self.value_ty(*agg)?, indices)?; + let size = self.kinds(member)?.len(); + bytes.get(offset..offset + size).map(<[ByteFact]>::to_vec) + } + InstKind::InsertValue { agg, val, indices } => { + let mut bytes = self.value(*agg)?; + let (offset, _) = self.member(ty, indices)?; + for (at, byte) in self.value(*val)?.into_iter().enumerate() { + *bytes.get_mut(offset + at)? = byte; + } + Some(bytes) + } + InstKind::Alloca { .. } => self.natural(ty, Families::NONE), + InstKind::Load { ptr, atomic, .. } => { + let mut fed = Self::fed(&self.value(*ptr)?).union(self.memory(*ptr)); + if atomic.is_some() { + fed = fed.with(Family::Unknown); + } + self.natural(ty, fed) + } + InstKind::Gep { base, indices, .. } => { + let mut fed = Self::fed(&self.value(*base)?); + for index in indices.iter() { + fed = fed.union(Self::fed(&self.value(*index)?)); + } + self.natural(ty, fed) + } + InstKind::AtomicRmw { .. } | InstKind::CmpXchg { .. } => self.natural(ty, unknown), + InstKind::Call(call) => { + if matches!(self.types().get(ty), Some(Type::Void)) { + return None; + } + let family = callee_families(&call.callee); + self.lanewise(ty, &call.args, family, false) + } + InstKind::Phi { incoming, .. } => { + let mut joined: Option> = None; + for (value, _) in incoming.iter() { + let Some(bytes) = self.value(*value) else { + continue; + }; + joined = Some(match joined { + Some(held) if held.len() == bytes.len() => held + .iter() + .zip(&bytes) + .map(|(held, new)| held.join(*new)) + .collect(), + Some(_) => self.natural(ty, unknown)?, + None => bytes, + }); + } + joined.map(|bytes| bytes.into_iter().map(|b| b.feed(self.control)).collect()) + } + InstKind::Store { .. } + | InstKind::Fence(_) + | InstKind::Ret(_) + | InstKind::Br { .. } + | InstKind::CondBr { .. } + | InstKind::Switch { .. } + | InstKind::Unreachable => None, + } + } + + fn binop(&self, ty: TypeId, op: BinOp, a: Value, b: Value) -> Option> { + let arithmetic = |family| self.lanewise(ty, &[a, b], Families::NONE.with(family), false); + match op { + BinOp::FAdd | BinOp::FSub | BinOp::FMul => arithmetic(Family::FloatArithmetic), + BinOp::FDiv | BinOp::FRem => arithmetic(Family::Division), + BinOp::Shl | BinOp::LShr => { + let shift = self.constant_int(b); + let (lanes, width) = self.lanes(ty)?; + match shift { + Some(shift) if shift % 8 == 0 && (shift / 8) < width as u64 => { + let by = (shift / 8) as usize; + let bytes = self.value(a)?; + let mut out = Vec::with_capacity(bytes.len()); + for lane in 0..lanes { + let lane = bytes.get(lane * width..(lane + 1) * width)?; + for at in 0..width { + let source = if op == BinOp::Shl { + at.checked_sub(by) + } else { + Some(at + by).filter(|from| *from < width) + }; + out.push(match source { + Some(from) => lane[from], + None => ByteFact { + kind: ByteKind::Zero, + fed: Families::NONE, + }, + }); + } + } + Some(out) + } + _ => self.lanewise(ty, &[a, b], Families::NONE, true), + } + } + BinOp::Or => { + let (left, right) = (self.value(a)?, self.value(b)?); + Some( + left.iter() + .zip(&right) + .map(|(l, r)| match (l.kind, r.kind) { + (ByteKind::Zero, _) => r.feed(l.fed), + (_, ByteKind::Zero) => l.feed(r.fed), + _ => ByteFact { + kind: ByteKind::Other, + fed: l.fed.union(r.fed), + }, + }) + .collect(), + ) + } + BinOp::And => match self.constant_int(b) { + Some(mask) => { + let (_, width) = self.lanes(ty)?; + let bytes = self.value(a)?; + Some( + bytes + .into_iter() + .enumerate() + .map(|(at, byte)| match (mask >> (8 * (at % width))) & 0xff { + 0 => ByteFact { + kind: ByteKind::Zero, + fed: Families::NONE, + }, + 0xff => byte, + _ => ByteFact { + kind: ByteKind::Other, + fed: byte.fed, + }, + }) + .collect(), + ) + } + None => self.lanewise(ty, &[a, b], Families::NONE, true), + }, + _ => self.lanewise(ty, &[a, b], Families::NONE, true), + } + } + + fn cast(&self, ty: TypeId, op: CastOp, v: Value) -> Option> { + let float = Families::NONE.with(Family::FloatArithmetic); + match op { + CastOp::Bitcast => { + let bytes = self.value(v)?; + let mut out = self.natural(ty, Families::NONE)?; + if out.len() != bytes.len() { + return self.lanewise(ty, &[v], Families::NONE, true); + } + let typed = out.iter().any(|byte| byte.kind != ByteKind::Other); + for (out, byte) in out.iter_mut().zip(bytes) { + *out = if typed { out.feed(byte.fed) } else { byte }; + } + Some(out) + } + CastOp::ZExt | CastOp::SExt | CastOp::Trunc => { + let bytes = self.value(v)?; + let (lanes, to) = self.lanes(ty)?; + let (from_lanes, from) = self.lanes(self.value_ty(v)?)?; + let whole = |ty: TypeId| match self.types().get(ty) { + Some(Type::Int(bits)) => bits.is_multiple_of(8), + Some(Type::Vector { elem, .. }) => { + matches!(self.types().get(*elem), Some(Type::Int(bits)) if bits.is_multiple_of(8)) + } + _ => false, + }; + if lanes != from_lanes || !whole(ty) || !whole(self.value_ty(v)?) { + return self.lanewise(ty, &[v], Families::NONE, true); + } + let mut out = Vec::with_capacity(lanes * to); + for lane in 0..lanes { + let source = bytes.get(lane * from..(lane + 1) * from)?; + let lane_fed = Self::fed(source); + for at in 0..to { + out.push(match source.get(at) { + Some(byte) => *byte, + None if op == CastOp::ZExt => ByteFact { + kind: ByteKind::Zero, + fed: Families::NONE, + }, + None => ByteFact { + kind: ByteKind::Other, + fed: lane_fed, + }, + }); + } + } + Some(out) + } + CastOp::FPTrunc | CastOp::FPExt | CastOp::UIToFP | CastOp::SIToFP => { + self.lanewise(ty, &[v], float, false) + } + CastOp::FPToUI | CastOp::FPToSI => self.lanewise(ty, &[v], float, true), + CastOp::PtrToInt | CastOp::IntToPtr | CastOp::AddrSpaceCast => { + self.lanewise(ty, &[v], Families::NONE, true) + } + } + } + + /// The byte offset and type of the member of an aggregate of type `ty` that `indices` name. + fn member(&self, ty: TypeId, indices: &[u32]) -> Option<(usize, TypeId)> { + let mut offset = 0u64; + let mut ty = ty; + for index in indices { + match self.types().get(ty)? { + Type::Struct { fields, .. } => { + offset += *self.layouts.field_offsets(ty)?.get(*index as usize)?; + ty = *fields.get(*index as usize)?; + } + Type::Array { elem, .. } | Type::Vector { elem, .. } => { + offset += u64::from(*index) * self.layouts.alloc_size(*elem)?; + ty = *elem; + } + _ => return None, + } + } + Some((usize::try_from(offset).ok()?, ty)) + } + + /// The stores into each buffer argument, with what they store. + fn collect(&self, stores: &mut Stores, meter: &mut Meter) -> Option<()> { + let unconditional = self.unconditional_blocks(meter); + for (block, _) in self.body.blocks.iter() { + let conditional = !unconditional.contains(&block); + for (_, inst) in self.body.block_insts(block) { + let InstKind::Store { + val, ptr, align, .. + } = &inst.kind + else { + continue; + }; + let Base::Param(param) = self.base(*ptr, 0) else { + continue; + }; + let size = self.layouts.store_size(self.value_ty(*val)?)? as usize; + let mut bytes = self.value(*val)?; + bytes.truncate(size); + let address = Self::fed(&self.value(*ptr)?); + let control = if conditional { + self.control + } else { + Families::NONE + }; + let bytes = bytes + .into_iter() + .map(|byte| byte.feed(address).feed(control)) + .collect(); + let place = self.place(*ptr); + let word_aligned = align.is_some_and(|align| align.bytes() >= 4) + && place.is_none_or(|place| place.offset % 4 == 0 && place.period % 4 == 0); + stores + .buffers + .entry(param) + .or_default() + .stores + .push(StoreFacts { + place, + bytes, + word_aligned, + }); + } + } + Some(()) + } + + /// The blocks every path from the entry's first block to its exit passes through: a store + /// there runs whatever a branch decides. + fn unconditional_blocks(&self, meter: &mut Meter) -> BTreeSet { + let Some((first, _)) = self.body.blocks.iter().next() else { + return BTreeSet::new(); + }; + let Ok(cfg) = Cfg::build(self.body, meter) else { + return BTreeSet::new(); + }; + let Ok(pdom) = PostDomTree::compute(&cfg, meter) else { + return BTreeSet::new(); + }; + self.body + .blocks + .iter() + .map(|(block, _)| block) + .filter(|block| pdom.post_dominates(*block, first)) + .collect() + } + + /// Where a store through `ptr` lands in its buffer argument. + fn place(&self, ptr: Value) -> Option { + let address = self.address(ptr, 0)?; + let axis = address.axis?; + (address.scale > 0 && address.offset >= 0).then_some(Place { + axis, + period: u64::try_from(address.scale).ok()?, + offset: u64::try_from(address.offset).ok()?, + }) + } + + /// `ptr`'s byte offset from its buffer argument, affine in a grid component. + fn address(&self, ptr: Value, depth: usize) -> Option { + if depth > 64 { + return None; + } + match ptr { + Value::Arg(_) => Some(Affine::constant(0)), + Value::Const(_) => None, + Value::Inst(_) => match &self.inst(ptr)?.kind { + InstKind::Cast { + op: CastOp::Bitcast | CastOp::AddrSpaceCast, + v, + } => self.address(*v, depth + 1), + InstKind::Gep { + src_ty, + base, + indices, + .. + } => { + let mut address = self.address(*base, depth + 1)?; + let (first, inner) = indices.split_first()?; + let stride = i128::from(self.layouts.alloc_size(*src_ty)?); + address = address.add(self.affine(*first, 0)?.times(stride)?)?; + let mut ty = *src_ty; + for index in inner { + match self.types().get(ty)? { + Type::Struct { fields, .. } => { + let field = usize::try_from(self.constant_int(*index)?).ok()?; + let offset = *self.layouts.field_offsets(ty)?.get(field)?; + address = address.add(Affine::constant(i128::from(offset)))?; + ty = *fields.get(field)?; + } + Type::Array { elem, .. } | Type::Vector { elem, .. } => { + let stride = i128::from(self.layouts.alloc_size(*elem)?); + address = address.add(self.affine(*index, 0)?.times(stride)?)?; + ty = *elem; + } + _ => return None, + } + } + Some(address) + } + _ => None, + }, + } + } + + /// The integer `value`, affine in a grid component. + fn affine(&self, value: Value, depth: usize) -> Option { + if depth > 64 { + return None; + } + match value { + Value::Const(id) => { + let constant = self.module.consts().get(id)?; + let Type::Int(bits) = self.types().get(constant.ty)? else { + return None; + }; + let raw = self.constant_int(value)?; + let shift = 64 - u32::from(*bits).min(64); + Some(Affine::constant(i128::from( + ((raw << shift) as i64) >> shift, + ))) + } + Value::Arg(arg) => { + let param = u32::try_from(arg.index()).ok()?; + let scalar = matches!(self.types().get(self.value_ty(value)?)?, Type::Int(_)); + (self.positions.contains(¶m) && scalar).then_some(Affine { + axis: Some(0), + scale: 1, + offset: 0, + }) + } + Value::Inst(_) => match &self.inst(value)?.kind { + InstKind::Cast { + op: CastOp::ZExt | CastOp::SExt, + v, + } => self.affine(*v, depth + 1), + InstKind::ExtractElement { + vec: Value::Arg(arg), + idx, + } => { + let param = u32::try_from(arg.index()).ok()?; + let lane = self.constant_int(*idx)?; + (self.positions.contains(¶m) && lane < 3).then_some(Affine { + axis: Some(lane as u32), + scale: 1, + offset: 0, + }) + } + InstKind::BinOp { op, a, b, .. } => { + let left = self.affine(*a, depth + 1); + let right = self.affine(*b, depth + 1); + let constant = |side: Option| { + side.filter(|side| side.scale == 0).map(|side| side.offset) + }; + match op { + BinOp::Add => left?.add(right?), + BinOp::Sub => left?.add(right?.times(-1)?), + BinOp::Mul => match (constant(left), constant(right)) { + (_, Some(factor)) => left?.times(factor), + (Some(factor), _) => right?.times(factor), + _ => None, + }, + BinOp::Shl => { + let shift = u32::try_from(constant(right)?).ok()?; + left?.times(1i128.checked_shl(shift)?) + } + BinOp::Or => { + // `x | c` is `x + c` where `c` lies below every set bit `x` can have. + let (x, c) = match (constant(left), constant(right)) { + (_, Some(c)) => (left?, c), + (Some(c), _) => (right?, c), + _ => return None, + }; + let zeros = |v: i128| if v == 0 { 127 } else { v.trailing_zeros() }; + let low = zeros(x.scale).min(zeros(x.offset)); + (c >= 0 && low < 127 && c < (1i128 << low)) + .then(|| x.add(Affine::constant(c))) + .flatten() + } + _ => None, + } + } + _ => None, + }, + } + } +} + +/// Whether a call to `callee` may write memory through a pointer it receives. +fn writes_through(callee: &Callee) -> bool { + match callee { + Callee::Air { op, .. } => !matches!( + op, + AirIntrinsic::Math(_) + | AirIntrinsic::Convert(_) + | AirIntrinsic::Pack(_) + | AirIntrinsic::Derivative(_) + | AirIntrinsic::BoolReduce(_) + | AirIntrinsic::Texture(_) + | AirIntrinsic::Sampler(_) + | AirIntrinsic::Sync(_) + | AirIntrinsic::Group(_) + | AirIntrinsic::IsUniform(_) + | AirIntrinsic::SimdgroupSize(_) + | AirIntrinsic::GlobalBuiltin(_) + | AirIntrinsic::WorkItem(_) + | AirIntrinsic::FunctionConstant(_) + | AirIntrinsic::Fragment(_) + | AirIntrinsic::Interpolate(_) + | AirIntrinsic::PointerSpace(_) + ), + Callee::Llvm { op, .. } => matches!( + op, + LlvmIntrinsic::Memset { .. } + | LlvmIntrinsic::Memcpy { .. } + | LlvmIntrinsic::Memmove { .. } + | LlvmIntrinsic::Agx(_) + ), + _ => true, + } +} + +/// The families a call's result adds to its arguments'. +fn callee_families(callee: &Callee) -> Families { + use Family as F; + let one = |family| Families::NONE.with(family); + match callee { + Callee::Air { op, .. } => match op { + AirIntrinsic::Math(math) => match math.f { + MathFn::Fma | MathFn::Mad => one(F::Fma), + MathFn::Dot => one(F::Dot), + MathFn::Mix => one(F::Mix), + MathFn::FMin + | MathFn::FMax + | MathFn::Min + | MathFn::Max + | MathFn::Clamp + | MathFn::FMin3 + | MathFn::FMax3 + | MathFn::FMedian3 + | MathFn::Saturate => one(F::MinMax), + MathFn::Abs(_) + | MathFn::AbsDiff(_) + | MathFn::IMin(_) + | MathFn::IMax(_) + | MathFn::IClamp(_) + | MathFn::IMin3(_) + | MathFn::IMax3(_) + | MathFn::IMedian3(_) + | MathFn::MulHi(_) + | MathFn::MadHi(_) + | MathFn::MadSat(_) + | MathFn::Mul24(_) + | MathFn::Mad24(_) + | MathFn::AddSat(_) + | MathFn::SubSat(_) + | MathFn::HAdd(_) + | MathFn::RHAdd(_) + | MathFn::ExtractBits(_) + | MathFn::InsertBits(_) + | MathFn::Popcount + | MathFn::ReverseBits + | MathFn::Bswap + | MathFn::Rotate + | MathFn::Clz { .. } + | MathFn::Ctz { .. } => Families::NONE, + _ => one(F::Function), + }, + AirIntrinsic::Convert(convert) => { + if convert.dst_kind == NumKind::Float || convert.src_kind == NumKind::Float { + one(F::FloatArithmetic) + } else { + Families::NONE + } + } + AirIntrinsic::Pack(_) => one(F::Pack), + AirIntrinsic::Texture(_) | AirIntrinsic::Sampler(_) => one(F::Texture), + AirIntrinsic::Derivative(_) + | AirIntrinsic::Group(_) + | AirIntrinsic::IsUniform(_) + | AirIntrinsic::SimdgroupSize(_) + | AirIntrinsic::SimdMatrix(_) + | AirIntrinsic::GlobalBuiltin(_) => one(F::Group), + AirIntrinsic::Interpolate(_) => one(F::StageInput), + AirIntrinsic::BoolReduce(_) + | AirIntrinsic::FunctionConstant(_) + | AirIntrinsic::WorkItem(_) + | AirIntrinsic::PointerSpace(_) => Families::NONE, + _ => one(F::Unknown), + }, + Callee::Llvm { op, .. } => match op { + LlvmIntrinsic::Float { op, .. } => match op { + LlvmFloatOp::FMulAdd | LlvmFloatOp::Fma => one(F::Fma), + LlvmFloatOp::MinNum | LlvmFloatOp::MaxNum => one(F::MinMax), + LlvmFloatOp::FAbs | LlvmFloatOp::CopySign => one(F::FloatArithmetic), + LlvmFloatOp::Exp2 | LlvmFloatOp::Log2 | LlvmFloatOp::Sqrt => one(F::Function), + }, + LlvmIntrinsic::Int { .. } + | LlvmIntrinsic::NarrowInt { .. } + | LlvmIntrinsic::Abs { .. } + | LlvmIntrinsic::Cttz { .. } + | LlvmIntrinsic::Ctlz { .. } => Families::NONE, + _ => one(F::Unknown), + }, + _ => one(F::Unknown), + } +} + +/// The shape of a word of four bytes. +fn shape(bytes: [ByteKind; 4]) -> WordShape { + use ByteKind as K; + if bytes == [K::Float(0), K::Float(1), K::Float(2), K::Float(3)] { + return WordShape::Float; + } + let half = |low: ByteKind, high: ByteKind| low == K::Half(0) && high == K::Half(1); + let (low, high) = (half(bytes[0], bytes[1]), half(bytes[2], bytes[3])); + if low || high { + WordShape::Halves { low, high } + } else { + WordShape::Opaque + } +} + +/// The looser of two words' shapes. +fn join_shape(left: WordShape, right: WordShape) -> WordShape { + match (left, right) { + (a, b) if a == b => a, + ( + WordShape::Halves { low, high }, + WordShape::Halves { + low: other_low, + high: other_high, + }, + ) if (low && other_low) || (high && other_high) => WordShape::Halves { + low: low && other_low, + high: high && other_high, + }, + _ => WordShape::Opaque, + } +} + +impl AirInterface { + /// What the entry's stores show of each word of `case`'s output ([`output_words`]). + pub fn output_words(&self, case: &AuthoredCase) -> OutputWords { + output_words(case, self) + } +} + +/// The words of `case`'s output as its declared format alone shows them +/// ([`ObservationLanes::of`]): every note reaches them. +pub fn output_words_by_format(case: &AuthoredCase) -> OutputWords { + let shape = match ObservationLanes::of(case) { + ObservationLanes::Float(FloatLane::Float) => WordShape::Float, + ObservationLanes::Float(FloatLane::Half) => WordShape::Halves { + low: true, + high: true, + }, + ObservationLanes::Integer | ObservationLanes::Untyped => WordShape::Opaque, + }; + OutputWords::uniform(WordFacts::unknown(shape)) +} + +/// What `interface`'s entry shows of each word of `case`'s output (the module documentation). An +/// output that is no buffer argument's range takes its lanes from its declared format +/// ([`ObservationLanes::of`]) and is fed by anything. +pub fn output_words(case: &AuthoredCase, interface: &AirInterface) -> OutputWords { + let typed = || output_words_by_format(case); + let OutputSelection::Buffer { + binding, offset, .. + } = case.output + else { + return typed(); + }; + let (Some(stores), Some(param)) = ( + interface.stores.as_ref(), + interface.params.iter().find(|param| { + !param.table + && matches!(param.binding.role, ParamRole::Buffer(_)) + && param.slots() == Some((binding, 1)) + }), + ) else { + return typed(); + }; + let kernel = matches!(interface.stage, AbiStage::Kernel { .. }); + let Some(writes) = stores.buffers.get(¶m.binding.param) else { + return OutputWords::uniform(if stores.unrooted_device_write { + WordFacts::unknown(WordShape::Opaque) + } else { + WordFacts::UNWRITTEN + }); + }; + if kernel && !writes.opaque && !stores.unrooted_device_write { + if let Some(words) = placed_words(case, writes, offset) { + return words; + } + } + let mut joined = None; + let mut fed = Families::NONE; + for store in &writes.stores { + let store_shape = if store.word_aligned && store.bytes.len() % 4 == 0 { + store + .bytes + .chunks(4) + .map(|word| shape([word[0].kind, word[1].kind, word[2].kind, word[3].kind])) + .reduce(join_shape) + .unwrap_or(WordShape::Opaque) + } else { + WordShape::Opaque + }; + joined = Some(joined.map_or(store_shape, |held| join_shape(held, store_shape))); + fed = fed.union(Scan::fed(&store.bytes)); + } + if kernel { + fed = fed.with(Family::Unordered); + } + if writes.opaque || stores.unrooted_device_write { + fed = fed.with(Family::Unknown); + } + OutputWords::uniform(WordFacts { + shape: joined.unwrap_or(WordShape::Opaque), + fed_by: fed, + }) +} + +/// The words of a kernel's output buffer whose every store is placed in its own thread's bytes +/// (the module documentation), from the output's byte `offset`; `None` where a store is not. +fn placed_words(case: &AuthoredCase, writes: &BufferWrites, offset: u64) -> Option { + let mut places = writes.stores.iter().map(|store| store.place); + let first = places.next()??; + let period = first.period; + if period % 4 != 0 || offset % 4 != 0 || period / 4 > LARGEST_VALUE { + return None; + } + for store in &writes.stores { + let place = store.place?; + if place.axis != first.axis + || place.period != period + || place.offset + store.bytes.len() as u64 > period + { + return None; + } + } + let grid = case.dispatch.as_ref()?.grid; + if (0..3).any(|axis| axis != first.axis as usize && grid[axis] != 1) { + return None; + } + let mut bytes: Vec> = vec![None; period as usize]; + for store in &writes.stores { + let start = store.place?.offset as usize; + for (at, byte) in store.bytes.iter().enumerate() { + let slot = bytes.get_mut(start + at)?; + *slot = Some(slot.map_or(*byte, |held| held.join(*byte))); + } + } + let words = bytes + .chunks(4) + .map(|word| { + if word.iter().all(Option::is_none) { + return WordFacts::UNWRITTEN; + } + let kind = |at: usize| word[at].map_or(ByteKind::Other, |byte| byte.kind); + WordFacts { + shape: shape([kind(0), kind(1), kind(2), kind(3)]), + fed_by: word + .iter() + .flatten() + .fold(Families::NONE, |fed, byte| fed.union(byte.fed)), + } + }) + .collect::>(); + let count = words.len(); + let skip = (offset / 4) as usize % count; + let rotated = words[skip..] + .iter() + .chain(&words[..skip]) + .copied() + .collect(); + let threads = u64::from(grid[first.axis as usize]); + let written = (threads * period).saturating_sub(offset).div_ceil(4); + Some(OutputWords { + words: rotated, + written_words: Some(written), + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/metal2vulkan-validation/src/check/output_words/tests.rs b/crates/metal2vulkan-validation/src/check/output_words/tests.rs new file mode 100644 index 000000000..284027d83 --- /dev/null +++ b/crates/metal2vulkan-validation/src/check/output_words/tests.rs @@ -0,0 +1,138 @@ +//! The output-word scan over public fixtures: placed stores and the families that feed each word. + +use super::*; +use crate::check::loop_free::DecodedModule; +use metal2vulkan_devtools::{ + fixtures_dir, llvm_assemble, validation_dir, workspace_dir, AssembleError, +}; + +/// The committed public case named `name`. +fn public_case(name: &str) -> AuthoredCase { + let cases = validation_dir().join("corpus").join("cases"); + let mut shards = std::fs::read_dir(&cases) + .expect("the committed cases") + .map(|entry| entry.expect("a shard").path()) + .collect::>(); + shards.sort(); + shards + .iter() + .flat_map(|shard| { + std::fs::read_to_string(shard) + .expect("a committed shard") + .lines() + .map(|line| serde_json::from_str::(line).expect("a case")) + .collect::>() + }) + .find(|case| case.name == name) + .unwrap_or_else(|| panic!("no committed case {name}")) +} + +/// The output words of the committed case `name` over its public fixture, or `None` where `llvm-as` +/// is missing. +fn public_words(name: &str) -> Option { + let case = public_case(name); + let source = case.public_source.clone().expect("a public source"); + let fixture = workspace_dir().join(&source); + assert!(fixture.starts_with(fixtures_dir()), "{source}"); + let bitcode = match llvm_assemble(&fixture) { + Ok(bitcode) => bitcode, + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + return None; + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {source}: {why}"), + }; + let decoded = DecodedModule::from_bitcode(name, &bitcode).expect("a decoded module"); + let abi = decoded.abi().expect("the AIR ABI"); + let interface = AirInterface::new(decoded.module(), abi, &case.entry, &BTreeMap::new()) + .expect("the interface"); + Some(interface.output_words(&case)) +} + +fn fed(families: &[Family]) -> Families { + Families::of(families) +} + +/// Every thread of `float-products-flushed-before-rounding` stores three `float4`s at +/// `48 * tid`, `+ 16` and `+ 32`: the words repeat every 12, each a `float`, the first eight fed by +/// products alone and the last four by `dot`; no word is another thread's, so the access-order note +/// reaches none, and past the 64 threads' words nothing is written. +#[test] +fn placed_stores_give_each_word_its_own_operations() { + let Some(words) = public_words("float-products-flushed-before-rounding") else { + return; + }; + let product = WordFacts { + shape: WordShape::Float, + fed_by: fed(&[Family::FloatArithmetic]), + }; + let dot = WordFacts { + shape: WordShape::Float, + fed_by: fed(&[Family::Dot]), + }; + let mut expected = vec![product; 8]; + expected.extend([dot; 4]); + assert_eq!(words.words, expected); + assert_eq!(words.written_words, Some(64 * 12)); + assert_eq!(words.word(64 * 12), WordFacts::UNWRITTEN); +} + +/// `fused-multiply-add-rounding-and-fmuladd-without-fast-math` stores one 16-byte vector a thread: +/// two `float` fused multiply-adds, a word of two `half` ones packed by `zext`, `shl` and `or`, and +/// a `float` product. +#[test] +fn packed_halves_keep_their_lanes_and_operations() { + let Some(words) = public_words("fused-multiply-add-rounding-and-fmuladd-without-fast-math") + else { + return; + }; + let fma = fed(&[Family::Fma]); + let float = |fed_by| WordFacts { + shape: WordShape::Float, + fed_by, + }; + let halves = WordFacts { + shape: WordShape::Halves { + low: true, + high: true, + }, + fed_by: fma, + }; + assert_eq!( + words.words, + vec![ + float(fma), + float(fma), + halves, + float(fed(&[Family::FloatArithmetic])) + ] + ); + assert_eq!(words.written_words, Some(1024 * 4)); +} + +/// An output that is no buffer argument's range takes its lanes from its declared format and is +/// fed by anything: every note reaches it. +#[test] +fn an_output_no_store_describes_is_reached_by_every_note() { + use crate::case::{RenderTargetResource, TextureFormat}; + let mut case = crate::case::attachmentless_fragment_test_case("11".repeat(32), "main".into()); + case.render_targets = vec![RenderTargetResource { + index: 0, + format: TextureFormat::Rgba16Float, + dimensions: [1, 1], + initial_bytes_b64: String::new(), + }]; + case.output = OutputSelection::RenderTarget { + index: 0, + origin: [0, 0], + dimensions: [1, 1], + }; + let words = output_words_by_format(&case); + assert_eq!( + words.word(5), + WordFacts::unknown(WordShape::Halves { + low: true, + high: true, + }) + ); +} diff --git a/crates/metal2vulkan-validation/src/coverage.rs b/crates/metal2vulkan-validation/src/coverage.rs index 3a0fe8003..cfcb952a5 100644 --- a/crates/metal2vulkan-validation/src/coverage.rs +++ b/crates/metal2vulkan-validation/src/coverage.rs @@ -19,8 +19,9 @@ //! selects the in-shader ones. Buffers are checked in the shader on both legs. use crate::candidate::engine::artifact::ExecutedArtifact; -use crate::case::Stage; -use crate::observation_contract::ComparisonClass; +use crate::case::{AuthoredCase, Stage}; +use crate::observation_contract::words::{judge, Judgement, OutputWords, RecordedNote}; +use crate::observation_contract::{allowance, reduction_table, Allowance, ComparisonClass}; use metal2vulkan::device::DeviceDescription; use metal2vulkan::device::VkFeature; use metal2vulkan::pipeline::PrecisionNote; @@ -204,6 +205,11 @@ pub struct ExecutedCensus { /// computes for that build. `None` for a run of an executor before ABI v129. #[serde(default, skip_serializing_if = "Option::is_none")] pub artifact: Option, + /// What the case's AIR shows of each word of its output (`check::output_words`): which notes + /// reach a differing word ([`ExecutedCensus::judge`]). `None` for a run of an executor before + /// ABI v215, whose words every note reaches. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_words: Option, } /// How a candidate drew a rate-mapped render pass: region by region (the option (a), on every @@ -225,6 +231,82 @@ pub struct RateMapPassRun { } impl ExecutedCensus { + /// Every note the run recorded, with whether its module is the entry of `case`'s stage, which + /// writes the output: the pass's notes and other stages' reach every word. + pub fn recorded_notes(&self, case: &AuthoredCase) -> Vec { + let mut notes = self + .modules + .iter() + .flat_map(|module| { + let writer = module.stage == case.stage; + module + .precision + .iter() + .map(move |¬e| RecordedNote { note, writer }) + }) + .chain(self.rate_map_pass.iter().flat_map(|pass| { + pass.precision.iter().map(|¬e| RecordedNote { + note, + writer: false, + }) + })) + .collect::>(); + notes.sort(); + notes.dedup(); + notes + } + + /// Whether a note the run recorded can excuse a difference within a bound, so a differing + /// output may match. + pub fn bounds_any(&self) -> bool { + self.all_notes().any(|note| allowance(note).is_bounded()) + } + + /// Whether a note the run recorded can explain a difference without a bound, so a differing + /// output may be a noted difference: an unbounded note, or a reduction no table bounds. + pub fn explains_any(&self) -> bool { + self.all_notes().any(|note| match allowance(note) { + Allowance::Unbounded => true, + Allowance::Reduction => reduction_table(self.strategy_names()).is_none(), + _ => false, + }) + } + + fn all_notes(&self) -> impl Iterator + '_ { + self.modules + .iter() + .flat_map(|module| module.precision.iter().copied()) + .chain( + self.rate_map_pass + .iter() + .flat_map(|pass| pass.precision.iter().copied()), + ) + } + + fn strategy_names(&self) -> impl Iterator + '_ { + self.modules + .iter() + .flat_map(|module| module.strategies.iter().map(String::as_str)) + } + + /// `candidate` judged against Metal's `golden` word by word ([`judge`]) for an observation of + /// `case`: by the notes the run recorded that reach each word, over the words its + /// [`ExecutedCensus::output_words`] describes, or, for a row without them, words of the + /// output's declared lanes that every note reaches. + pub fn judge(&self, case: &AuthoredCase, golden: &[u8], candidate: &[u8]) -> Judgement { + let words = self + .output_words + .clone() + .unwrap_or_else(|| crate::check::output_words::output_words_by_format(case)); + judge( + &self.recorded_notes(case), + reduction_table(self.strategy_names()), + &words, + golden, + candidate, + ) + } + /// The comparison class of an observation of these modules, derived from their notes and /// strategies: what a recorded class must equal. pub fn comparison_class(&self) -> ComparisonClass { diff --git a/crates/metal2vulkan-validation/src/coverage/tests.rs b/crates/metal2vulkan-validation/src/coverage/tests.rs index 7b76e8648..2555e846b 100644 --- a/crates/metal2vulkan-validation/src/coverage/tests.rs +++ b/crates/metal2vulkan-validation/src/coverage/tests.rs @@ -50,6 +50,7 @@ fn executed_census_round_trips() { restricted_to: None, modules: vec![module(Stage::Kernel, pinned(32, true), &["simd.reduce"])], artifact: None, + output_words: None, }; let json = serde_json::to_value(&census).unwrap(); assert_eq!(json["device"], serde_json::json!({"host": 3})); @@ -81,6 +82,7 @@ fn a_rate_mapped_pass_records_its_regions() { restricted_to: None, modules: vec![module(Stage::Fragment, FREE, &["arith.float"])], artifact: None, + output_words: None, }; assert_eq!(census.comparison_class(), ComparisonClass::Exact); let json = serde_json::to_value(&census).unwrap(); diff --git a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs index fce8dda5b..eff6690cb 100644 --- a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs +++ b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs @@ -46,12 +46,13 @@ //! alone. A thread-local array and a handle array have no guard: what their accesses past them //! reach is the case's own layout, whose output bytes witness it. //! - Every other output byte compares with Metal under the run's comparison class, as any case's -//! does ([`matches()`]). A form whose out-of-bounds result Metal defines (a texture or a texture +//! does ([`judge()`]). A form whose out-of-bounds result Metal defines (a texture or a texture //! buffer) has no read bytes: its whole output compares with Metal. use crate::case::out_of_bounds::{ContainmentForm, OutOfBoundsResource, OutOfBoundsTarget}; use crate::case::{AuthoredCase, OutputSelection}; -use crate::observation_contract::{ComparisonClass, ObservationLanes}; +use crate::coverage::ExecutedCensus; +use crate::observation_contract::words::{Judgement, WordFacts}; use base64::Engine as _; use metal2vulkan::device::{DevicePolicy, DeviceProfile, HandleDomain, PointerDomain}; use metal2vulkan::library::CompiledFunction; @@ -183,7 +184,7 @@ impl OutOfBoundsRun { /// Whether the run's output may differ from Metal's row and still match: a target whose /// out-of-bounds read may return a non-zero value ([`read_rule`]) where the row records zero /// ([`metal_recorded`]), or, under robust buffer access alone, which a write past an output - /// target may change. Which bytes may differ, and to what, [`matches()`] decides over the case. + /// target may change. Which bytes may differ, and to what, [`judge()`] decides over the case. pub fn tolerates_differences(&self) -> bool { self.targets .iter() @@ -192,7 +193,7 @@ impl OutOfBoundsRun { /// Whether the run changed memory around a target that its containment does not allow: a /// guard byte, or a padding byte under anything but robustness 1. Such a run is no match - /// ([`matches()`]) even when its output equals Metal's. + /// ([`judge()`]) even when its output equals Metal's. pub fn escapes(&self) -> bool { self.targets.iter().any(|target| { target.escaped.is_some_and(|bytes| bytes > 0) @@ -638,29 +639,40 @@ pub fn containment( } } -/// Whether a candidate observation `candidate` of `case` matches its Metal observation `golden` -/// under `class`, with the out-of-bounds facts `run` of the run for a case that declares targets. A -/// case without targets compares as every case does. -pub fn matches( +/// A candidate observation `candidate` of `case` judged against its Metal observation `golden` +/// word by word ([`ExecutedCensus::judge`]) under the run's census `census` (`None`: byte for +/// byte), with the out-of-bounds facts `run` of the run for a case that declares targets: a target +/// that escaped, or a read that took a value its rule forbids, refuses the judgement, and the bytes +/// a target may change are taken as Metal's. A case without targets is judged as every case is. +pub fn judge( case: &AuthoredCase, - class: &ComparisonClass, + census: Option<&ExecutedCensus>, golden: &[u8], candidate: &[u8], run: Option<&OutOfBoundsRun>, -) -> bool { - let lanes = ObservationLanes::of(case); +) -> Judgement { + let words = |compared: &[u8]| match census { + Some(census) => census.judge(case, golden, compared), + None => crate::observation_contract::words::judge( + &[], + None, + &crate::observation_contract::words::OutputWords::uniform(WordFacts::UNWRITTEN), + golden, + compared, + ), + }; let Some(declaration) = &case.out_of_bounds else { - return class.matches(lanes, golden, candidate); + return words(candidate); }; let Some(run) = run else { - return false; + return Judgement::refused(); }; if run.targets.len() != declaration.targets.len() || golden.len() != candidate.len() { - return false; + return Judgement::refused(); } for (declared, ran) in declaration.targets.iter().zip(&run.targets) { if declared.resource != ran.resource || !contained_in_guard(declared, ran) { - return false; + return Judgement::refused(); } } let mut compared = candidate.to_vec(); @@ -681,14 +693,14 @@ pub fn matches( usize::try_from(read.offset), usize::try_from(read.offset.saturating_add(read.length)), ) else { - return false; + return Judgement::refused(); }; let (Some(target), Some(declared), Some(bytes)) = ( run.targets.get(read.target as usize), declaration.targets.get(read.target as usize), candidate.get(start..end), ) else { - return false; + return Judgement::refused(); }; let allowed = match target.read_rule() { ReadRule::Zero => bytes.iter().all(|&byte| byte == 0), @@ -711,11 +723,11 @@ pub fn matches( } }; if !allowed { - return false; + return Judgement::refused(); } compared[start..end].copy_from_slice(&golden[start..end]); } - class.matches(lanes, golden, &compared) + words(&compared) } /// Whether the run's guard around `ran` shows nothing escaped: a guarded target ([`guarded`]) is diff --git a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs index d70b7cb9a..6d2ed40ec 100644 --- a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs +++ b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs @@ -1,5 +1,18 @@ use super::*; use crate::case::out_of_bounds::OutOfBounds; +use crate::observation_contract::words::Verdict; +use crate::observation_contract::ComparisonClass; + +/// Whether `candidate` matches `golden` for `case` under no note, with the out-of-bounds facts +/// `run`. +fn matches( + case: &AuthoredCase, + golden: &[u8], + candidate: &[u8], + run: Option<&OutOfBoundsRun>, +) -> bool { + judge(case, None, golden, candidate, run).verdict() == Verdict::Match +} /// A mechanism as the tests compare it: `:`. pub(crate) trait Label { @@ -158,80 +171,64 @@ fn the_read_rule_follows_the_mechanism_not_the_case() { #[test] fn a_contained_read_matches_and_an_escaped_one_does_not() { - let class = ComparisonClass::Exact; let form = ContainmentForm::StorageBuffer; let checked = run(form, Medium::DescriptorView, Check::Shader, false); let case = case(form); - assert!(matches(&case, &class, &golden(), &golden(), Some(&checked))); + assert!(matches(&case, &golden(), &golden(), Some(&checked))); // A read past the buffer that returned the next buffer's word is not contained. let leaked = with_reads([0, 0, 0xC000_0040, 0]); - assert!(!matches(&case, &class, &golden(), &leaked, Some(&checked))); + assert!(!matches(&case, &golden(), &leaked, Some(&checked))); // An in-bounds byte compares with Metal as always. let mut wrong = golden(); wrong[0] ^= 1; - assert!(!matches(&case, &class, &golden(), &wrong, Some(&checked))); + assert!(!matches(&case, &golden(), &wrong, Some(&checked))); // A run without its out-of-bounds facts, or with an escaped guard byte, is no match. - assert!(!matches(&case, &class, &golden(), &golden(), None)); + assert!(!matches(&case, &golden(), &golden(), None)); let mut escaped = checked.clone(); escaped.targets[0].escaped = Some(4); - assert!(!matches( - &case, - &class, - &golden(), - &golden(), - Some(&escaped) - )); + assert!(!matches(&case, &golden(), &golden(), Some(&escaped))); // A buffer target must have been guarded. let mut unguarded = checked.clone(); unguarded.targets[0].escaped = None; - assert!(!matches( - &case, - &class, - &golden(), - &golden(), - Some(&unguarded) - )); + assert!(!matches(&case, &golden(), &golden(), Some(&unguarded))); // The run's facts must be of the case's targets. let mut other = checked; other.targets[0].resource = OutOfBoundsResource::Buffer { binding: 1 }; - assert!(!matches(&case, &class, &golden(), &golden(), Some(&other))); + assert!(!matches(&case, &golden(), &golden(), Some(&other))); } #[test] fn robust_buffer_access_alone_allows_the_buffers_own_words() { - let class = ComparisonClass::Exact; let form = ContainmentForm::UniformBuffer; let robust = run(form, Medium::DescriptorView, Check::Robust, false); let case = case(form); // Zero, (0, 0, 0, 1.0), and words of the buffer itself are contained. let own = with_reads([0xA000_0003, 0, 0, 0x3f80_0000]); - assert!(matches(&case, &class, &golden(), &own, Some(&robust))); + assert!(matches(&case, &golden(), &own, Some(&robust))); // A word of no buffer of the case is not. let leaked = with_reads([0xA000_0005, 0, 0, 0]); - assert!(!matches(&case, &class, &golden(), &leaked, Some(&robust))); + assert!(!matches(&case, &golden(), &leaked, Some(&robust))); // Under the second level the read is zero only. let robust2 = run(form, Medium::DescriptorView, Check::Robust2, false); - assert!(!matches(&case, &class, &golden(), &own, Some(&robust2))); + assert!(!matches(&case, &golden(), &own, Some(&robust2))); } #[test] fn an_atomics_return_under_robustness_is_undefined_but_its_guard_is_not() { - let class = ComparisonClass::Exact; let form = ContainmentForm::BufferAtomic; let case = case(form); let any = with_reads([0x1234_5678, 0, 0, 0]); let robust2 = run(form, Medium::DescriptorView, Check::Robust2, true); - assert!(matches(&case, &class, &golden(), &any, Some(&robust2))); + assert!(matches(&case, &golden(), &any, Some(&robust2))); let checked = run(form, Medium::DescriptorView, Check::Shader, true); - assert!(!matches(&case, &class, &golden(), &any, Some(&checked))); + assert!(!matches(&case, &golden(), &any, Some(&checked))); let mut escaped = robust2; escaped.targets[0].escaped = Some(1); - assert!(!matches(&case, &class, &golden(), &any, Some(&escaped))); + assert!(!matches(&case, &golden(), &any, Some(&escaped))); } #[test] fn an_output_written_past_its_end_under_robustness_alone_is_not_compared() { - let class = ComparisonClass::Exact; let mut case = case(ContainmentForm::StorageBuffer); // The output is the target: a write past it may change any of its bytes under // `robustBufferAccess` alone, so only the guard decides. @@ -247,39 +244,20 @@ fn an_output_written_past_its_end_under_robustness_alone_is_not_compared() { robust.targets[0].resource = OutOfBoundsResource::Buffer { binding: 1 }; let mut clobbered = golden(); clobbered[0] = 0x55; - assert!(matches(&case, &class, &golden(), &clobbered, Some(&robust))); + assert!(matches(&case, &golden(), &clobbered, Some(&robust))); let mut robust2 = robust.clone(); robust2.targets[0].mechanism.check = Check::Robust2; - assert!(!matches( - &case, - &class, - &golden(), - &clobbered, - Some(&robust2) - )); + assert!(!matches(&case, &golden(), &clobbered, Some(&robust2))); robust.targets[0].escaped = Some(16); - assert!(!matches( - &case, - &class, - &golden(), - &clobbered, - Some(&robust) - )); + assert!(!matches(&case, &golden(), &clobbered, Some(&robust))); } #[test] fn a_case_without_targets_compares_as_every_case_does() { let mut case = case(ContainmentForm::StorageBuffer); case.out_of_bounds = None; - let class = ComparisonClass::Exact; - assert!(matches(&case, &class, &golden(), &golden(), None)); - assert!(!matches( - &case, - &class, - &golden(), - &with_reads([1, 0, 0, 0]), - None - )); + assert!(matches(&case, &golden(), &golden(), None)); + assert!(!matches(&case, &golden(), &with_reads([1, 0, 0, 0]), None)); } #[test] @@ -322,7 +300,6 @@ fn texture_case(ty: &str, form: ContainmentForm, reach_after: u32) -> AuthoredCa /// opaque: it has no guard. #[test] fn a_texel_buffer_target_is_judged_by_its_guard() { - let class = ComparisonClass::Exact; let case = texture_case("buffer", ContainmentForm::TexelBuffer, 16384); let ran = |check, escaped, past_end| OutOfBoundsRun { targets: vec![TargetRun { @@ -338,7 +315,7 @@ fn a_texel_buffer_target_is_judged_by_its_guard() { }], }; let output = golden(); - let judge = |run: OutOfBoundsRun| matches(&case, &class, &output, &output, Some(&run)); + let judge = |run: OutOfBoundsRun| matches(&case, &output, &output, Some(&run)); assert!(judge(ran(Check::Shader, Some(0), Some(0)))); // No guard around the texture buffer: nothing shows that its writes stayed inside it. assert!(!judge(ran(Check::Shader, None, None))); @@ -363,7 +340,7 @@ fn a_texel_buffer_target_is_judged_by_its_guard() { past_end, }], }; - let judge = |run: OutOfBoundsRun| matches(&image, &class, &output, &output, Some(&run)); + let judge = |run: OutOfBoundsRun| matches(&image, &output, &output, Some(&run)); assert!(judge(image_run(None, None))); assert!(!judge(image_run(Some(0), Some(0)))); } @@ -373,7 +350,6 @@ fn a_texel_buffer_target_is_judged_by_its_guard() { /// every access inside the buffer. #[test] fn only_robustness_1_may_reach_a_buffers_padding() { - let class = ComparisonClass::Exact; let form = ContainmentForm::StorageBuffer; let case = case(form); for (check, allowed) in [ @@ -384,7 +360,7 @@ fn only_robustness_1_may_reach_a_buffers_padding() { let mut padded = run(form, Medium::DescriptorView, check, false); padded.targets[0].past_end = Some(3); assert_eq!( - matches(&case, &class, &golden(), &golden(), Some(&padded)), + matches(&case, &golden(), &golden(), Some(&padded)), allowed, "{check:?}" ); @@ -394,20 +370,8 @@ fn only_robustness_1_may_reach_a_buffers_padding() { let padding = u32::from_ne_bytes([PAD_FILL; 4]); let guard = u32::from_ne_bytes([GUARD_FILL; 4]); let read = |word| with_reads([0, word, 0, 0]); - assert!(matches( - &case, - &class, - &golden(), - &read(padding), - Some(&robust) - )); - assert!(!matches( - &case, - &class, - &golden(), - &read(guard), - Some(&robust) - )); + assert!(matches(&case, &golden(), &read(padding), Some(&robust))); + assert!(!matches(&case, &golden(), &read(guard), Some(&robust))); } /// [`case`] whose one target is `resource` of `form`, reading bytes 16..32 of the output; an @@ -455,7 +419,6 @@ fn embedded_run( /// as a buffer, so a run without guard counts, or whose guard changed, is no match. #[test] fn a_loaded_pointers_buffer_reads_zero_and_is_guarded() { - let class = ComparisonClass::Exact; let resource = OutOfBoundsResource::ArgumentBufferBuffer { buffer_binding: 0, field_offset: 0, @@ -463,35 +426,11 @@ fn a_loaded_pointers_buffer_reads_zero_and_is_guarded() { let form = ContainmentForm::LoadedPointer; let case = embedded_case(resource, form, 0); let ran = |guard| embedded_run(resource, form, Medium::DeviceAddress, guard); - assert!(matches( - &case, - &class, - &golden(), - &golden(), - Some(&ran(Some(0))) - )); - assert!(!matches( - &case, - &class, - &golden(), - &golden(), - Some(&ran(None)) - )); - assert!(!matches( - &case, - &class, - &golden(), - &golden(), - Some(&ran(Some(4))) - )); + assert!(matches(&case, &golden(), &golden(), Some(&ran(Some(0))))); + assert!(!matches(&case, &golden(), &golden(), Some(&ran(None)))); + assert!(!matches(&case, &golden(), &golden(), Some(&ran(Some(4))))); let leaked = with_reads([0, 0xE7E7_E7E7, 0, 0]); - assert!(!matches( - &case, - &class, - &golden(), - &leaked, - Some(&ran(Some(0))) - )); + assert!(!matches(&case, &golden(), &leaked, Some(&ran(Some(0))))); assert_eq!( argument_buffer_reach(&case, (0, 0)), Some(( @@ -509,7 +448,6 @@ fn a_loaded_pointers_buffer_reads_zero_and_is_guarded() { /// of a texture the case binds, or zero (the null handle or descriptor), never another value. #[test] fn an_in_layout_target_has_no_guard_and_its_own_read_rule() { - let class = ComparisonClass::Exact; let texel = 0xE200_0000; for (resource, form, medium) in [ ( @@ -536,34 +474,16 @@ fn an_in_layout_target_has_no_guard_and_its_own_read_rule() { ] { let case = embedded_case(resource, form, texel); let ran = |guard| embedded_run(resource, form, medium, guard); - assert!(matches( - &case, - &class, - &golden(), - &golden(), - Some(&ran(None)) - )); - assert!(!matches( - &case, - &class, - &golden(), - &golden(), - Some(&ran(Some(0))) - )); + assert!(matches(&case, &golden(), &golden(), Some(&ran(None)))); + assert!(!matches(&case, &golden(), &golden(), Some(&ran(Some(0))))); let resident = with_reads([texel, 0, texel, 0]); assert_eq!( - matches(&case, &class, &golden(), &resident, Some(&ran(None))), + matches(&case, &golden(), &resident, Some(&ran(None))), medium != Medium::TypedObject, "{form}" ); let foreign = with_reads([0xA000_0005, 0, 0, 0]); - assert!(!matches( - &case, - &class, - &golden(), - &foreign, - Some(&ran(None)) - )); + assert!(!matches(&case, &golden(), &foreign, Some(&ran(None)))); } let rule = |medium, check| { read_rule( @@ -632,6 +552,7 @@ fn candidate_row( out_of_bounds: Some(run), rate_map_pass: None, artifact: None, + output_words: None, }), status, held_open_by: None, diff --git a/crates/metal2vulkan-validation/src/index.rs b/crates/metal2vulkan-validation/src/index.rs index 48ae20f42..7bc9bdc73 100644 --- a/crates/metal2vulkan-validation/src/index.rs +++ b/crates/metal2vulkan-validation/src/index.rs @@ -3365,6 +3365,7 @@ mod tests { out_of_bounds: None, rate_map_pass: None, artifact: None, + output_words: None, }; let mut censused = candidate.clone(); censused.census = Some(census(crate::observation::TRANSLATOR_FINGERPRINT)); @@ -3455,6 +3456,7 @@ mod tests { out_of_bounds: None, rate_map_pass: None, artifact, + output_words: None, }); row }; diff --git a/crates/metal2vulkan-validation/src/observation.rs b/crates/metal2vulkan-validation/src/observation.rs index 0049c7226..e8a2eb546 100644 --- a/crates/metal2vulkan-validation/src/observation.rs +++ b/crates/metal2vulkan-validation/src/observation.rs @@ -3,6 +3,7 @@ use crate::check::admission::{MetalGap, NeedsMetal}; use crate::coverage::ExecutedCensus; use crate::executor_contract::out_of_bounds::OutOfBoundsRun; use crate::hash::sha256_bytes; +use crate::observation_contract::words::{Judgement, Verdict}; use crate::observation_contract::ComparisonClass; use base64::Engine as _; use serde::{Deserialize, Serialize}; @@ -219,28 +220,29 @@ pub struct CandidateObservation { pub held_open_by: Option, } -/// How a candidate's output compares with Metal's: a difference is never a match. +/// How a candidate's output compares with Metal's, word by word +/// ([`crate::observation_contract::words::judge`]). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum CandidateStatus { + /// Every word equals Metal's, or differs within the bound of a note that reaches it. Match, - /// A difference no recorded note can explain (an exact class, or one past a bounded table), - /// an out-of-bounds target that escaped, or the difference of a case an answer gap holds open - /// ([`CandidateObservation::held_open_by`]): the user's decision of 2026-10-06 keeps an answer - /// gap's difference an open mismatch until an exact emulation exists. + /// A word no reaching note excuses, an out-of-bounds target that escaped, or the difference of + /// a case an answer gap holds open ([`CandidateObservation::held_open_by`]): the user's + /// decision of 2026-10-06 keeps an answer gap's difference an open mismatch until an exact + /// emulation exists. Mismatch, - /// The bytes differ under a class unbounded by precision notes - /// ([`ComparisonClass::Unbounded`]): the row's notes can explain a difference, which says - /// nothing of whether they explain this one. Never a match, and never accepted. + /// Every differing word is excused by a note that reaches it, at least one by a note with no + /// bound: the row's notes can explain the difference, which says nothing of whether they do. + /// Never a match, and never accepted. NotedDifference, } /// Whether a row whose output does not match Metal's may be a noted difference: its bytes differ, -/// its class is unbounded by notes, and no out-of-bounds target escaped, which no note explains. -pub fn may_be_noted(differs: bool, class: &ComparisonClass, run: Option<&OutOfBoundsRun>) -> bool { - differs - && matches!(class, ComparisonClass::Unbounded(_)) - && !run.is_some_and(OutOfBoundsRun::escapes) +/// a note it recorded explains a difference without a bound (`explains`), and no out-of-bounds +/// target escaped, which no note explains. +pub fn may_be_noted(differs: bool, explains: bool, run: Option<&OutOfBoundsRun>) -> bool { + differs && explains && !run.is_some_and(OutOfBoundsRun::escapes) } impl MetalObservation { @@ -398,16 +400,20 @@ impl CandidateObservation { .census .as_ref() .and_then(|census| census.out_of_bounds.as_ref()); - // Equal bytes match under every class; differing bytes match only under a class that - // tolerates a difference, or for a run whose out-of-bounds targets may read a value - // Metal's row records as zero. Equal bytes are a mismatch only for a run that changed a - // target's guard. `dependency_matches` re-decides each from the Metal bytes. - let tolerated = self.comparison.tolerates_differences() + // Equal bytes match whatever the notes; differing bytes match only where a recorded note + // bounds a difference, or for a run whose out-of-bounds targets may read a value Metal's + // row records as zero. Equal bytes are a mismatch only for a run that changed a target's + // guard. `dependency_matches` re-decides each from the Metal bytes. + let tolerated = self.census.as_ref().is_some_and(ExecutedCensus::bounds_any) || run.is_some_and(OutOfBoundsRun::tolerates_differences); // A noted difference is one that may be noted, and only such a difference is held open by // an answer gap. A mismatch under notes without a gap is a row of an executor before the // noted status, stale by its executor ABI. - let noted = may_be_noted(!hashes_match, &self.comparison, run); + let explains = self + .census + .as_ref() + .is_some_and(ExecutedCensus::explains_any); + let noted = may_be_noted(!hashes_match, explains, run); let contradicts = match self.status { CandidateStatus::Match => (!hashes_match && !tolerated) || self.held_open_by.is_some(), CandidateStatus::Mismatch => { @@ -489,23 +495,36 @@ impl CandidateObservation { Ok(()) } - /// Whether the recorded status is the verdict of the recorded class on `golden`, the Metal - /// output, for an observation of `case`: for a case with out-of-bounds targets, the verdict - /// of their containment property over the recorded census. + /// Whether the recorded status is the verdict on `golden`, the Metal output, for an + /// observation of `case`: each word judged by the recorded notes that reach it + /// ([`ExecutedCensus::judge`]), for a case with out-of-bounds targets after their containment + /// property over the recorded census; a noted verdict an answer gap holds open is a mismatch. pub fn status_holds(&self, case: &AuthoredCase, golden: &[u8]) -> bool { let Ok(output) = base64::engine::general_purpose::STANDARD.decode(&self.output_b64) else { return false; }; - let matches = crate::executor_contract::out_of_bounds::matches( + let verdict = self.judgement(case, golden, &output).verdict(); + match (self.status, verdict) { + (CandidateStatus::Match, Verdict::Match) => true, + (CandidateStatus::NotedDifference, Verdict::Noted) => self.held_open_by.is_none(), + (CandidateStatus::Mismatch, Verdict::Noted) => self.held_open_by.is_some(), + (CandidateStatus::Mismatch, Verdict::Mismatch) => true, + _ => false, + } + } + + /// The row's `output` judged against Metal's `golden` for an observation of `case`, word by + /// word under its census ([`crate::executor_contract::out_of_bounds::judge`]). + pub fn judgement(&self, case: &AuthoredCase, golden: &[u8], output: &[u8]) -> Judgement { + crate::executor_contract::out_of_bounds::judge( case, - &self.comparison, + self.census.as_ref(), golden, - &output, + output, self.census .as_ref() .and_then(|census| census.out_of_bounds.as_ref()), - ); - (self.status == CandidateStatus::Match) == matches + ) } /// Whether the recorded class is the one the recorded census derives: a row without a census @@ -942,6 +961,7 @@ mod tests { restricted_to: restricted_to.map(str::to_owned), modules: Vec::new(), artifact: None, + output_words: None, }), status: CandidateStatus::Match, held_open_by: None, @@ -1080,6 +1100,7 @@ mod tests { containment: None, }], artifact: None, + output_words: None, }; let one_ulp = census.comparison_class(); assert_eq!( @@ -1151,13 +1172,22 @@ mod tests { let equal = row(&golden, ComparisonClass::Exact, CandidateStatus::Mismatch); assert!(equal.validate_content().is_err()); - // Under an unbounded class a difference is a noted difference, never a match, and a - // mismatch where an answer gap holds it open (or in a row of an executor before the noted - // status); no other class or status is noted. - let unbounded = ComparisonClass::Unbounded([PrecisionNote::DeviceSampling].into()); + // Under a census whose notes explain a difference without a bound, a difference is a + // noted difference, never a match, and a mismatch where an answer gap holds it open (or in + // a row of an executor before the noted status); no other class or status is noted. + let mut sampled = census.clone(); + sampled.modules[0].precision = [PrecisionNote::DeviceSampling].into(); + let unbounded = sampled.comparison_class(); + assert_eq!( + unbounded, + ComparisonClass::Unbounded([PrecisionNote::DeviceSampling].into()) + ); let valid = |output: &[u8], comparison: &ComparisonClass, status, held| { let mut row = row(output, comparison.clone(), status); row.held_open_by = held; + if *comparison == unbounded { + row.census = Some(sampled.clone()); + } row.validate_content().is_ok() }; let gap = Some(crate::c3::AnswerGap::ClippedPrimitiveSplit); diff --git a/crates/metal2vulkan-validation/src/observation_contract.rs b/crates/metal2vulkan-validation/src/observation_contract.rs index 7145172b2..032ce1ff1 100644 --- a/crates/metal2vulkan-validation/src/observation_contract.rs +++ b/crates/metal2vulkan-validation/src/observation_contract.rs @@ -1,4 +1,5 @@ mod comparison; +pub mod words; pub use comparison::{ allowance, census_names, lane_within, reduction_table, reorder_ulps, value_difference, diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs index 45e335403..98825d89c 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs @@ -1,20 +1,19 @@ //! Comparison classes of authored observations. //! -//! A candidate observation is compared with its Metal observation under one -//! [`ComparisonClass`], derived mechanically from what the executed modules record: their -//! `precision_notes` and `StrategyCensus` ([`ComparisonClass::derive`]). Nothing authors or -//! chooses a class. Byte equality is a match under every class; a class only ever widens what -//! counts as a match on lanes of a structurally known float format ([`ObservationLanes`]), and -//! only by a bound that follows from the note ([`allowance`]). A note whose effect on a stored -//! value no table bounds makes the class [`ComparisonClass::Unbounded`]. A difference is never a -//! match: under such notes it is a noted difference, recorded with the notes that can explain it -//! and counted apart (unless a C3 answer gap holds its case open), else a mismatch +//! A candidate observation is compared with its Metal observation word by word +//! ([`super::words::judge`]): an equal word matches, and a differing word is excused only by a note +//! that reaches it and allows its difference. Each note's row of the derivation table +//! ([`allowance`]) says what it allows: a bound on a word of a structurally known float lane, within +//! which the word matches; no bound, under which the word is a noted difference, recorded with the +//! notes that can explain it and counted apart (unless a C3 answer gap holds its case open); or +//! nothing, the note being only recorded. A word no reaching note excuses is a mismatch //! (`crate::observation::CandidateStatus`). //! -//! The class is per observation, not per lane: every lane of the declared format gets the -//! tolerance, including lanes the noted operation did not produce, and a tolerance says nothing -//! about values computed further from the noted result. Both make a class looser than the note -//! for some lanes; neither is used to absorb a difference the table does not state. +//! The [`ComparisonClass`] summarizes the notes of an observation, derived mechanically from what +//! the executed modules record: their `precision_notes` and `StrategyCensus` +//! ([`ComparisonClass::derive`]). Nothing authors or chooses a class. A bound says nothing about +//! values computed further from the noted result: the bound is checked at the word, whatever +//! operations lie between the noted one and the store. use crate::case::{AuthoredCase, OutputSelection, TextureFormat}; use metal2vulkan::pipeline::{PrecisionNote, StrategyCensus}; @@ -58,22 +57,48 @@ pub struct LaneTolerance { pub ulps: u32, } -/// What one precision note allows on an observation: one row of the class derivation table. +/// What one precision note allows on a word it reaches: one row of the class derivation table. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Allowance { /// Lanes may differ as the table states. Lanes(UlpTable), /// A float reduction reassociates; the bound follows from the census ([`reduction_table`]). Reduction, - /// No bound on the stored value follows from the note. + /// A float lane may differ where Metal's lane and the device's are both a zero, a denormal or + /// the smallest normal of the lane's format (a magnitude of at most `2^-126` for `float`, + /// `2^-14` for `half`), of one sign unless one of them is a zero + /// ([`super::words::both_tiny`]). Nothing above that boundary is excused. + DenormalBoundary, + /// A float lane may differ where Metal's lane and the device's are both NaNs of the lane's + /// format: only the encoding differs. + BothNan, + /// A `half` lane may differ by one unit in its last place, or be the largest finite `half` + /// where the other is the infinity of its sign. + HalfTexel, + /// No bound on the stored value follows from the note: a word it reaches that differs is a + /// noted difference. Unbounded, - /// The note records a device behavior every computation of its format is exposed to: it - /// neither widens a lane nor explains a difference, and the class is derived as if it were - /// absent. Were it unbounded, every `float` observation would be explained by it and lose the - /// tolerance its other notes derive. + /// The note records a device behavior a word comparison does not excuse: it neither widens a + /// lane nor explains a difference, and the class is derived as if it were absent. A + /// difference stays a mismatch for review. Recorded, } +impl Allowance { + /// Whether the note bounds the words it excuses (a match within the bound), as opposed to + /// explaining them without a bound or not at all. + pub fn is_bounded(self) -> bool { + matches!( + self, + Allowance::Lanes(_) + | Allowance::Reduction + | Allowance::DenormalBoundary + | Allowance::BothNan + | Allowance::HalfTexel + ) + } +} + /// A little-endian IEEE lane format an observation can hold. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FloatLane { @@ -126,7 +151,8 @@ impl UlpTable { } } - fn lane(&self, format: FloatLane) -> LaneTolerance { + /// The tolerance of lanes of `format`. + pub fn lane(&self, format: FloatLane) -> LaneTolerance { match format { FloatLane::Half => self.half, FloatLane::Float => self.float, @@ -191,9 +217,10 @@ impl UlpTable { /// - `CubeGradientFootprint`: unbounded: Apple's approximate length and truncated level against the /// device's can select another level or filter near a boundary, which changes whole texels, not /// lanes. -/// - `HalfTexelConversion`: unbounded: a format whose conversion to `half` is not measured keeps -/// the device's quantize of its `f32` texel, so a lane can differ from Metal's by any amount (an -/// sRGB texel's decode). +/// - `HalfTexelConversion`: [`Allowance::HalfTexel`]: the note's recorded bound, the device's +/// `f32` texel rounded to nearest even within one `half` ulp of Metal's `half` result, and a +/// 32-bit float texel past `±65504`, which one side takes to the infinity of its sign and the +/// other keeps at `±65504`. /// - `SrgbTexelDecode`: unbounded: an 8-bit sRGB texel the device decodes where Metal decodes its /// raw code through a twelve-bit table; Vulkan bounds the device's decode only by its precision /// rules, and Metal's `float` gathers of sRGB texels are not measured. @@ -228,11 +255,21 @@ impl UlpTable { /// - `RotatedBlendRounding`: unbounded: an `ARGB8Unorm` attachment whose blend is not exact by /// construction may store a channel one code apart from Metal's, which moves every later word /// that reads it. -/// - `DeviceDenormals`, `DeviceNanEncoding`: [`Allowance::Recorded`]. Metal flushes `float` -/// denormals and canonicalizes NaNs, a device need not, and every `float` operation the device -/// performs is exposed to both; a `half` texel's NaN is the device's decode where Metal hands -/// back the texel's own: a difference they cause stays a mismatch for review, never accepted or -/// explained by the class. C3 tells which differing values they cause ([`value_difference`]). +/// - `DeviceDenormals`: [`Allowance::DenormalBoundary`]. The device's own arithmetic at the +/// denormal boundary (the owner's rule 1): Metal flushes before rounding on some operations (a +/// product, its negation and a fused multiply-add whose exact result lies just below `2^-126` +/// answer `+0`, where a device that rounds first answers `2^-126`) and keeps a denormal on +/// others (`sin`, `tan`, `asinh`), and the device may answer either. A word where both answers +/// lie at or below the smallest normal is excused; nothing above it is, though a flushed operand +/// can carry its difference to any later value. C3 tells which differing values it causes +/// ([`value_difference`]). +/// - `NativeNanEncoding`: [`Allowance::BothNan`]. A NaN result's sign and payload are the +/// device's: a word where both answers are NaNs is excused, and no other. +/// - `DeviceNanEncoding`: [`Allowance::Recorded`]. Metal canonicalizes NaNs, a device need not, and +/// every `float` operation the device performs is exposed to it; a `half` texel's NaN is the +/// device's decode where Metal hands back the texel's own: a difference it causes stays a +/// mismatch for review, never accepted or explained by the class. C3 tells which differing +/// values it causes ([`value_difference`]). /// - `FunctionStorageAssumed`: [`Allowance::Recorded`]. A vertex or fragment function's private /// memory passes the floor of a device not measured, resting on no measurement; a difference is /// a mismatch for review, never accepted or explained by the note. @@ -248,12 +285,18 @@ impl UlpTable { /// - `DeviceInterpolationOffset`: [`Allowance::Recorded`]. Recorded at every read at an offset, /// where only an offset past the device's range or off its grid reads otherwise than Metal; a /// difference is a mismatch for review, never accepted or explained by the note. -/// - Every other note, and any note this table does not know, bounds nothing on the stored -/// value: Vulkan's transcendental and arithmetic precision is stated per operation and input -/// range (absolute error for `sin`/`cos`, inherited bounds for `pow` and an unfused `Fma`, where -/// cancellation makes the relative error unbounded), a device may drop denormals, signed -/// zeros, infinities, and NaNs on inputs, and the sampling, footprint, and ordering notes have -/// no numeric bound at all. +/// - `NativeFma`, `NativeDot`, `NativeMix`, `NativeDivision`: unbounded at the word. Each states +/// a bound over its operands (half an ulp of the product `a * b` beside half an ulp of the +/// result, `sum |a_i * b_i|`, `|x * (1 - t)| + |y * t|`, a divisor in `[2^-126, 2^126]`), which a +/// word does not carry: with cancellation the result's own ulps say nothing of it. The fixture +/// knows its inputs, so a per-case bound from the operands is a later form. +/// - Every other note bounds nothing on the stored value: Vulkan's transcendental and +/// arithmetic precision is stated per operation and input range (absolute error for +/// `sin`/`cos`, inherited bounds for `pow`), a device may drop signed zeros, infinities, and +/// NaNs on inputs, and the sampling, footprint, and ordering notes have no numeric bound at all. +/// +/// A note reaches only the words its operations feed (`super::words::reach`): an unbounded note +/// explains nothing else. pub fn allowance(note: PrecisionNote) -> Allowance { use PrecisionNote as N; match note { @@ -261,10 +304,12 @@ pub fn allowance(note: PrecisionNote) -> Allowance { Allowance::Lanes(UlpTable::half(LaneTolerance { ulps: 1 })) } N::ReductionOrder => Allowance::Reduction, - N::DeviceDenormals - | N::DeviceNanEncoding - | N::FunctionStorageAssumed - | N::ViewBaseTexelOffset => Allowance::Recorded, + N::DeviceDenormals => Allowance::DenormalBoundary, + N::NativeNanEncoding => Allowance::BothNan, + N::HalfTexelConversion => Allowance::HalfTexel, + N::DeviceNanEncoding | N::FunctionStorageAssumed | N::ViewBaseTexelOffset => { + Allowance::Recorded + } N::DeviceColorConversion => Allowance::Recorded, N::LinkedSamplerNumbering => Allowance::Recorded, N::DeviceInterpolationOffset => Allowance::Recorded, @@ -290,7 +335,6 @@ pub fn allowance(note: PrecisionNote) -> Allowance { | N::SparseResidency | N::RestrictedDepthRange | N::CubeGradientFootprint - | N::HalfTexelConversion | N::SrgbTexelDecode | N::QuadsCountedBeforeDiscard | N::DeviceInterpolation @@ -316,7 +360,6 @@ pub fn allowance(note: PrecisionNote) -> Allowance { | N::DeviceVertexConversion | N::NativeHalfConversion | N::NativeHalfQuantize - | N::NativeNanEncoding | N::NativeMinMax | N::NativeDot | N::NativeMix @@ -465,7 +508,11 @@ pub fn reorder_ulps(terms: u32, format: FloatLane) -> u32 { impl ComparisonClass { /// The class of observations of modules that record `notes` and `strategies` (census - /// names): the union over every executed stage. + /// names): the union over every executed stage. `Exact` where no note excuses anything; + /// `Unbounded` naming every note that explains a difference without a bound; otherwise the + /// lane table of the bounded notes (equal bits for a note whose bound is structural, the + /// denormal boundary, a NaN's encoding or a `half` texel's conversion). The class summarizes: + /// a word is judged by the notes that reach it ([`super::words::judge`]). pub fn derive<'a>( notes: impl IntoIterator, strategies: impl IntoIterator, @@ -484,7 +531,10 @@ impl ComparisonClass { Allowance::Unbounded => { unbounded.insert(note); } - Allowance::Recorded => {} + Allowance::DenormalBoundary + | Allowance::BothNan + | Allowance::HalfTexel + | Allowance::Recorded => {} } } if reduction { @@ -506,45 +556,6 @@ impl ComparisonClass { ComparisonClass::UlpBounded(table) } } - - /// The lane table of a class that has one. - fn table(&self) -> Option<&UlpTable> { - match self { - ComparisonClass::UlpBounded(table) | ComparisonClass::ReductionOrderTolerant(table) => { - Some(table) - } - ComparisonClass::Exact | ComparisonClass::Unbounded(_) => None, - } - } - - /// Whether a class can accept bytes that differ (on typed float lanes). - pub fn tolerates_differences(&self) -> bool { - self.table().is_some() - } - - /// Whether `candidate` matches `golden` under this class for an observation of `lanes`: - /// equal bytes always do; otherwise every lane must be of a float format this class has a - /// table for, and within it. - pub fn matches(&self, lanes: ObservationLanes, golden: &[u8], candidate: &[u8]) -> bool { - if golden == candidate { - return true; - } - let (Some(table), ObservationLanes::Float(format)) = (self.table(), lanes) else { - return false; - }; - let width = match format { - FloatLane::Half => 2, - FloatLane::Float => 4, - }; - if golden.len() != candidate.len() || !golden.len().is_multiple_of(width) { - return false; - } - let tolerance = table.lane(format); - golden - .chunks_exact(width) - .zip(candidate.chunks_exact(width)) - .all(|(g, c)| lane_within(format, tolerance, bits(g), bits(c))) - } } /// The names of a census's strategies. @@ -552,12 +563,6 @@ pub fn census_names(census: &StrategyCensus) -> impl Iterator { census.entries.keys().map(String::as_str) } -fn bits(lane: &[u8]) -> u32 { - lane.iter() - .rev() - .fold(0, |bits, &byte| (bits << 8) | u32::from(byte)) -} - /// Whether candidate lane `c` is within `tolerance` of Metal lane `g`, both raw bits of /// `format`. Infinities and NaNs match only bit for bit, and a zero differs from the other signed /// zero. diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs index 53208c332..fe8719df5 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison/tests.rs @@ -16,14 +16,6 @@ fn class(notes: &[PrecisionNote], strategies: &[&str]) -> ComparisonClass { ComparisonClass::derive(notes.iter().copied(), strategies.iter().copied()) } -fn halves(lanes: &[u16]) -> Vec { - lanes.iter().flat_map(|lane| lane.to_le_bytes()).collect() -} - -fn floats(lanes: &[u32]) -> Vec { - lanes.iter().flat_map(|lane| lane.to_le_bytes()).collect() -} - /// Every note the product records today, with its row of the derivation table. A note added to /// the product without a row here derives `Unbounded` (the wildcard arm), never a tolerance. #[test] @@ -40,7 +32,12 @@ fn every_precision_note_has_its_table_row() { (N::ReductionOrder, Allowance::Reduction), (N::GradFromBias, Allowance::Unbounded), (N::DeviceTranscendentals, Allowance::Unbounded), - (N::DeviceDenormals, Allowance::Recorded), + (N::DeviceDenormals, Allowance::DenormalBoundary), + (N::NativeNanEncoding, Allowance::BothNan), + (N::NativeFma, Allowance::Unbounded), + (N::NativeDot, Allowance::Unbounded), + (N::NativeMix, Allowance::Unbounded), + (N::NativeDivision, Allowance::Unbounded), (N::PixelSamplerScaling, Allowance::Unbounded), (N::ArgumentPixelSamplerScaling, Allowance::Unbounded), (N::DeviceArithmetic, Allowance::Unbounded), @@ -59,7 +56,7 @@ fn every_precision_note_has_its_table_row() { (N::DeviceNanEncoding, Allowance::Recorded), (N::RestrictedDepthRange, Allowance::Unbounded), (N::CubeGradientFootprint, Allowance::Unbounded), - (N::HalfTexelConversion, Allowance::Unbounded), + (N::HalfTexelConversion, Allowance::HalfTexel), (N::SrgbTexelDecode, Allowance::Unbounded), (N::FunctionStorageAssumed, Allowance::Recorded), (N::ViewBaseTexelOffset, Allowance::Recorded), @@ -248,47 +245,6 @@ fn reassociation_bounds_follow_the_unit_roundoff() { assert_eq!(reduction_table(["arith.float", "access.load"]), None); } -#[test] -fn a_tolerance_applies_only_to_typed_float_lanes() { - let one_ulp = class(&[N::F16FmaDoubleRounding], &[]); - let (golden, candidate) = (halves(&[0x3c00, 0x4000]), halves(&[0x3c01, 0x4000])); - assert!(one_ulp.matches( - ObservationLanes::Float(FloatLane::Half), - &golden, - &candidate - )); - for lanes in [ObservationLanes::Untyped, ObservationLanes::Integer] { - assert!(!one_ulp.matches(lanes, &golden, &candidate), "{lanes:?}"); - assert!(one_ulp.matches(lanes, &golden, &golden)); - } - // The half table does not reach float lanes. - assert!(!one_ulp.matches( - ObservationLanes::Float(FloatLane::Float), - &floats(&[0x3f80_0000]), - &floats(&[0x3f80_0001]) - )); - // An unbounded class never accepts a difference. - let unbounded = class(&[N::DeviceTranscendentals], &[]); - assert!(!unbounded.tolerates_differences()); - assert!(!unbounded.matches( - ObservationLanes::Float(FloatLane::Half), - &golden, - &candidate - )); - assert!(unbounded.matches(ObservationLanes::Untyped, &golden, &golden)); - // Lengths that do not split into lanes, or differ, never match. - assert!(!one_ulp.matches( - ObservationLanes::Float(FloatLane::Half), - &[0x00, 0x3c, 0x00], - &[0x01, 0x3c, 0x00] - )); - assert!(!one_ulp.matches( - ObservationLanes::Float(FloatLane::Half), - &golden, - &candidate[..2] - )); -} - #[test] fn lanes_compare_by_distance_within_one_sign() { let two = LaneTolerance { ulps: 2 }; @@ -382,25 +338,40 @@ fn classes_serialize_compatibly_with_stored_observations() { } } -/// `DeviceDenormals` and `DeviceNanEncoding` are recorded, not allowances: a module that records -/// them derives the class it derives without them, so they neither explain a difference nor take -/// away the tolerance another note derives. +/// `DeviceNanEncoding` is only recorded: a module that records it derives the class it derives +/// without it. `DeviceDenormals` bounds a word by its structure alone: it widens no lane, so beside +/// another note the class is that note's, and alone it is `UlpBounded` with every lane exact. #[test] fn recorded_notes_leave_the_class_as_it_is() { - let recorded = [N::DeviceDenormals, N::DeviceNanEncoding]; + let strategies = ["simd.reduce.fadd.float"]; for others in [ vec![], vec![N::F16FmaDoubleRounding], vec![N::ReductionOrder], vec![N::DeviceArithmetic], ] { - let strategies = ["simd.reduce.fadd.float"]; let without = ComparisonClass::derive(others.iter().copied(), strategies); - let with = ComparisonClass::derive(others.iter().copied().chain(recorded), strategies); - assert_eq!(with, without, "{others:?}"); + let recorded = others.iter().copied().chain([N::DeviceNanEncoding]); + assert_eq!( + ComparisonClass::derive(recorded, strategies), + without, + "{others:?}" + ); + if !others.is_empty() { + let bounded = others.iter().copied().chain([N::DeviceDenormals]); + assert_eq!( + ComparisonClass::derive(bounded, strategies), + without, + "{others:?}" + ); + } } assert_eq!( - ComparisonClass::derive(recorded, std::iter::empty()), + ComparisonClass::derive([N::DeviceNanEncoding], std::iter::empty()), ComparisonClass::Exact ); + assert_eq!( + ComparisonClass::derive([N::DeviceDenormals], std::iter::empty()), + ComparisonClass::UlpBounded(UlpTable::default()) + ); } diff --git a/crates/metal2vulkan-validation/src/observation_contract/words.rs b/crates/metal2vulkan-validation/src/observation_contract/words.rs new file mode 100644 index 000000000..78ad06e84 --- /dev/null +++ b/crates/metal2vulkan-validation/src/observation_contract/words.rs @@ -0,0 +1,610 @@ +//! Word by word: which recorded notes reach each word of an observation, and within what bound. +//! +//! A candidate's output is judged one 32-bit little-endian word at a time against Metal's +//! ([`judge`]). An equal word matches. A word that differs is excused only by a note that reaches +//! it ([`reach`]) and allows its difference ([`super::allowance`]): a bounded note within its bound +//! makes the word a match; a note with no bound makes it a noted difference; with neither, the word +//! is a mismatch, and so is the observation. +//! +//! What reaches a word is read from the case's AIR ([`OutputWords`]): for each word of the output, +//! the float lanes it holds ([`WordShape`]) and the operation families whose results feed it +//! ([`Family`]). A note recorded by the module whose entry writes the output reaches the words its +//! operations feed; a note of any other module (another stage of a render pipeline, the pass) +//! reaches every word, as does any note of a word the scan could not follow +//! ([`Family::Unknown`]). + +use super::comparison::{allowance, lane_within, Allowance, FloatLane, LaneTolerance, UlpTable}; +use metal2vulkan::pipeline::PrecisionNote; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::collections::{BTreeMap, BTreeSet}; + +/// An operation family whose result can feed an output word, as the case's AIR shows it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Family { + /// `fadd`, `fsub`, `fmul`, `fneg`, `fcmp`, a conversion to or from a float format (a cast or + /// `air.convert`), `llvm.fabs` and `llvm.copysign`. + FloatArithmetic, + /// `fdiv` and `frem`. + Division, + /// `air.fma`, `air.mad`, `llvm.fma` and `llvm.fmuladd`. + Fma, + /// `air.dot`. + Dot, + /// `air.mix`. + Mix, + /// The minimum and maximum functions: `air.fmin`, `air.fmax`, `air.min`, `air.max`, + /// `air.clamp`, `air.fmin3`, `air.fmax3`, `air.fmedian3`, `air.saturate`, `llvm.minnum` and + /// `llvm.maxnum`. + MinMax, + /// Every other float function of the math family (`air.sqrt`, `air.sin`, `air.pow`, + /// `air.fract`, `air.ldexp`, ...), and `llvm.sqrt`, `llvm.exp2` and `llvm.log2`. + Function, + /// `air.pack` and `air.unpack`. + Pack, + /// A texture's or a sampler's operation. + Texture, + /// A simdgroup or quad operation, a derivative, a simdgroup matrix, and a thread's place in its + /// simdgroup or quad. + Group, + /// A fragment function's input: a varying, a fragment built-in, an interpolant's + /// interpolation. + StageInput, + /// Another thread of the kernel may write the word: a store the scan cannot place among the + /// bytes of its own thread. + Unordered, + /// Anything: a load of memory the function writes, a call outside the closed intrinsic set, an + /// intrinsic family the scan does not model, a write the scan cannot describe. + Unknown, +} + +impl Family { + const ALL: [Family; 13] = [ + Family::FloatArithmetic, + Family::Division, + Family::Fma, + Family::Dot, + Family::Mix, + Family::MinMax, + Family::Function, + Family::Pack, + Family::Texture, + Family::Group, + Family::StageInput, + Family::Unordered, + Family::Unknown, + ]; + + fn bit(self) -> u16 { + 1 << (self as u16) + } +} + +/// A set of [`Family`]s, serialized as the sorted list of its members. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Families(u16); + +impl Families { + /// No family: an input, a constant, or a byte nothing writes. + pub const NONE: Families = Families(0); + + /// The set of `families`. + pub fn of(families: &[Family]) -> Families { + families + .iter() + .fold(Families::NONE, |set, family| set.with(*family)) + } + + /// `self` and `family`. + pub fn with(self, family: Family) -> Families { + Families(self.0 | family.bit()) + } + + /// `self` and `other`. + pub fn union(self, other: Families) -> Families { + Families(self.0 | other.0) + } + + /// Whether `family` is a member. + pub fn contains(self, family: Family) -> bool { + self.0 & family.bit() != 0 + } + + /// Whether `self` and `other` share a member. + pub fn meets(self, other: Families) -> bool { + self.0 & other.0 != 0 + } + + /// The members, in order. + pub fn iter(self) -> impl Iterator { + Family::ALL + .into_iter() + .filter(move |family| self.contains(*family)) + } +} + +impl Serialize for Families { + fn serialize(&self, serializer: S) -> Result { + serializer.collect_seq(self.iter()) + } +} + +impl<'de> Deserialize<'de> for Families { + fn deserialize>(deserializer: D) -> Result { + let families = Vec::::deserialize(deserializer)?; + Ok(Families::of(&families)) + } +} + +/// The float lanes of one output word. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WordShape { + /// One `float`. + Float, + /// Two 16-bit halves, the low one first; each a `half` where `true`, and compared bit for bit + /// otherwise. + Halves { low: bool, high: bool }, + /// No float lane: compared bit for bit. + Opaque, +} + +/// What the case's AIR shows of one output word. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct WordFacts { + pub shape: WordShape, + /// The families whose results may feed the word. + pub fed_by: Families, +} + +impl WordFacts { + /// A word the scan could not follow: of `shape`, fed by anything. + pub fn unknown(shape: WordShape) -> WordFacts { + WordFacts { + shape, + fed_by: Families::NONE.with(Family::Unknown), + } + } + + /// A word nothing writes: compared bit for bit, reached by no note. + pub const UNWRITTEN: WordFacts = WordFacts { + shape: WordShape::Opaque, + fed_by: Families::NONE, + }; +} + +/// What the case's AIR shows of every word of an output: word `i` has the facts +/// `words[i % words.len()]`, until `written_words` (where set), from which on no thread writes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OutputWords { + pub words: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub written_words: Option, +} + +impl OutputWords { + /// Every word alike. + pub fn uniform(facts: WordFacts) -> OutputWords { + OutputWords { + words: vec![facts], + written_words: None, + } + } + + /// The facts of word `index`. + pub fn word(&self, index: usize) -> WordFacts { + if self + .written_words + .is_some_and(|written| index as u64 >= written) + { + return WordFacts::UNWRITTEN; + } + match self.words.len() { + 0 => WordFacts::unknown(WordShape::Opaque), + len => self.words[index % len], + } + } +} + +/// Which words a note reaches when its module writes the output. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reach { + /// Every word: the note is the pipeline's or the pass's, decides which invocations run, or + /// concerns a move no operation family marks. + Every, + /// The words these families feed. + Families(Families), +} + +/// Every float-valued family: the operations whose float results a float format's note can +/// concern. +const ANY_FLOAT: [Family; 10] = [ + Family::FloatArithmetic, + Family::Division, + Family::Fma, + Family::Dot, + Family::Mix, + Family::MinMax, + Family::Function, + Family::Pack, + Family::Texture, + Family::Group, +]; + +/// The operations whose results each note concerns, as its documentation names them: the +/// words a note recorded by the module whose entry writes the output reaches. +pub fn reach(note: PrecisionNote) -> Reach { + use Family as F; + use PrecisionNote as N; + let families = |families: &[Family]| Reach::Families(Families::of(families)); + match note { + N::F16FmaDoubleRounding | N::NativeFma => families(&[F::Fma]), + N::F16IntConvDoubleRounding | N::Fp8Value => families(&[F::FloatArithmetic]), + N::NativeDivision => families(&[F::Division]), + N::NativeDot => families(&[F::Dot]), + N::NativeMix => families(&[F::Mix]), + N::NativeMinMax => families(&[F::MinMax]), + N::NativeTranscendentals => families(&[F::Function]), + N::DeviceTranscendentals => { + families(&[F::Function, F::Division, F::Fma, F::Dot, F::Mix, F::MinMax]) + } + N::DeviceArithmetic => families(&[F::Division, F::Fma, F::Dot, F::Function, F::Group]), + N::FastMathRewrites => families(&[F::FloatArithmetic, F::Fma]), + N::DevicePackConversion => families(&[F::Pack, F::Texture]), + N::DeviceDenormals + | N::DeviceNanEncoding + | N::DeviceSignedZeroInfNan + | N::DeviceHalfDenormals + | N::NativeHalfConversion + | N::NativeHalfQuantize => families(&ANY_FLOAT), + N::GradFromBias + | N::PixelSamplerScaling + | N::ArgumentPixelSamplerScaling + | N::BicubicFilterArithmetic + | N::SparseResidency + | N::RestrictedDepthRange + | N::CubeGradientFootprint + | N::HalfTexelConversion + | N::SrgbTexelDecode + | N::ViewBaseTexelOffset + | N::LinkedSamplerNumbering + | N::AnisotropicFilter + | N::DeviceAnisotropicFilter + | N::DeviceSampling + | N::DeviceTexelConversion + | N::DeviceSampleLevel + | N::CappedLodBias + | N::CompressedTexelDecode + | N::SwizzledOpaqueBlackBorder => families(&[F::Texture]), + N::ReductionOrder + | N::QuadsCountedBeforeDiscard + | N::QuadsSplitByClipping + | N::FragmentSimdgroupGrouping + | N::VertexSimdgroupGrouping + | N::UnmeasuredGroupSpeculation => families(&[F::Group]), + N::DeviceReconvergence => families(&[F::Group, F::Texture]), + N::DeviceInterpolation + | N::ExtrapolatedInterpolation + | N::DeviceInterpolationOffset + | N::MultisamplePosition => families(&[F::StageInput]), + N::SimdgroupAccessOrder => families(&[F::Unordered]), + // A NaN's bits are the device's wherever it reads a `half` from its bits or moves a + // `float`, which no operation family marks: the note reaches every float lane, and its + // bound excuses only two NaNs there. + N::NativeNanEncoding => Reach::Every, + N::DeviceRayIntersection + | N::TessellationWinding + | N::TessellationFactorEdgeCases + | N::TessellationFactorScale + | N::TessellationFactorInstance + | N::TessellationFractionalSpacing + | N::TessellationTriangleOrder + | N::FunctionStorageAssumed + | N::DeviceColorConversion + | N::BlendedWriteRounding + | N::RotatedBlendRounding + | N::HalfOutputPrecision + | N::HalfOutputFastMathBlend + | N::DevicePointSize + | N::ClippedCoverageSplit + | N::LoopedSampleOutputs + | N::DeviceVertexConversion + | N::CoverageReadsRoundedAlpha + | N::DeviceAlphaCoverage + | N::UnorderedFetchWithinDraw + | N::NativeLogicOperation + | N::SnormMinimumKept + | N::DeviceDepthBias + | N::DepthDenormals + | N::DeviceFilteredMipmaps + | N::DeviceRoundedResolve + | N::SharedExponentKept + | N::DeviceLineRasterization + | N::DeviceFragmentRuns + | N::DeviceOcclusionCount + | N::RestrictedDepthUpload + | N::StencilOutputOverlap => Reach::Every, + } +} + +/// One recorded note as the judge reads it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct RecordedNote { + pub note: PrecisionNote, + /// The note's module writes the output: the word's families say whether it reaches it + /// ([`reach`]). A note of any other module reaches every word. + pub writer: bool, +} + +/// The verdict of an observation judged word by word. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Verdict { + /// Every word equals Metal's, or differs within a bounded note that reaches it. + Match, + /// Every differing word is excused, at least one only by a note with no bound. + Noted, + /// A word no reaching note excuses, or outputs of different lengths. + Mismatch, +} + +/// How each word of an observation compared with Metal's. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Judgement { + /// The words compared (a trailing partial word counts as one). + pub words: usize, + /// The words equal to Metal's. + pub exact: usize, + /// The differing words a bounded note excuses, by the note that excused the first differing + /// lane. + pub bounded: BTreeMap, + /// The differing words only a note with no bound excuses, by the note that excused the first + /// lane it excused. + pub noted: BTreeMap, + /// The differing words no reaching note excuses. + pub unexcused: usize, + /// The differing words the scan could not follow ([`Family::Unknown`]): every note reaches + /// them. + pub fallback: usize, + /// The first unexcused word: its index, Metal's word and the candidate's. + pub first_unexcused: Option<(usize, u32, u32)>, + /// The outputs' lengths differ. + pub lengths_differ: bool, +} + +impl Judgement { + /// The judgement of outputs that differ in a way no word can be judged: in length, or by a + /// rule outside the words (an out-of-bounds target's). + pub fn refused() -> Judgement { + Judgement { + lengths_differ: true, + ..Judgement::default() + } + } + + pub fn verdict(&self) -> Verdict { + if self.lengths_differ || self.unexcused > 0 { + Verdict::Mismatch + } else if !self.noted.is_empty() { + Verdict::Noted + } else { + Verdict::Match + } + } + + /// The differing words a bounded note excuses. + pub fn bounded_words(&self) -> usize { + self.bounded.values().sum() + } + + /// The differing words only a note with no bound excuses. + pub fn noted_words(&self) -> usize { + self.noted.values().sum() + } +} + +/// One lane of a word: its format, or bits compared exactly. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Lane { + Float(FloatLane), + Opaque, +} + +/// How a lane's difference is excused. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Excuse { + Bounded(PrecisionNote), + Noted(PrecisionNote), +} + +/// Judge `candidate` against Metal's `golden` word by word under the recorded `notes`, with +/// `reduction` the reassociation table of the float sums the census records (`None` where it names +/// none [`super::reduction_table`] bounds), over the words `words` describes. +pub fn judge( + notes: &[RecordedNote], + reduction: Option, + words: &OutputWords, + golden: &[u8], + candidate: &[u8], +) -> Judgement { + let notes = notes.iter().copied().collect::>(); + let mut judgement = Judgement { + words: golden.len().div_ceil(4), + ..Judgement::default() + }; + if golden.len() != candidate.len() { + judgement.lengths_differ = true; + return judgement; + } + for (index, (metal, device)) in golden.chunks(4).zip(candidate.chunks(4)).enumerate() { + if metal == device { + judgement.exact += 1; + continue; + } + let facts = words.word(index); + if facts.fed_by.contains(Family::Unknown) { + judgement.fallback += 1; + } + let mut bounded = None; + let mut noted = None; + let mut excused = true; + for (lane, start, end) in lanes(facts.shape, metal.len()) { + let (metal, device) = (bits(&metal[start..end]), bits(&device[start..end])); + if metal == device { + continue; + } + match excuse(¬es, reduction, facts.fed_by, lane, metal, device) { + Some(Excuse::Bounded(note)) => { + bounded.get_or_insert(note); + } + Some(Excuse::Noted(note)) => { + noted.get_or_insert(note); + } + None => excused = false, + } + } + match (excused, noted, bounded) { + (false, ..) => { + judgement.unexcused += 1; + if judgement.first_unexcused.is_none() { + judgement.first_unexcused = Some((index, bits(metal), bits(device))); + } + } + (true, Some(note), _) => *judgement.noted.entry(note).or_default() += 1, + (true, None, Some(note)) => *judgement.bounded.entry(note).or_default() += 1, + // A word whose bytes differ has a differing lane. + (true, None, None) => judgement.unexcused += 1, + } + } + judgement +} + +/// The lanes of a word of `shape` that holds `len` bytes (4, or fewer for a trailing word), with +/// their byte ranges. +fn lanes(shape: WordShape, len: usize) -> Vec<(Lane, usize, usize)> { + let half = |is_half: bool| { + if is_half { + Lane::Float(FloatLane::Half) + } else { + Lane::Opaque + } + }; + match (shape, len) { + (WordShape::Float, 4) => vec![(Lane::Float(FloatLane::Float), 0, 4)], + (WordShape::Halves { low, high }, 4) => vec![(half(low), 0, 2), (half(high), 2, 4)], + (WordShape::Halves { low, .. }, 2) => vec![(half(low), 0, 2)], + _ => vec![(Lane::Opaque, 0, len)], + } +} + +/// The little-endian value of up to four bytes. +fn bits(bytes: &[u8]) -> u32 { + bytes + .iter() + .rev() + .fold(0, |bits, &byte| (bits << 8) | u32::from(byte)) +} + +/// The first excuse a reaching note gives lane `lane` (Metal's bits `metal`, the device's +/// `device`) of a word `fed_by` feeds: a bounded note within its bound before any note with no +/// bound. +fn excuse( + notes: &BTreeSet, + reduction: Option, + fed_by: Families, + lane: Lane, + metal: u32, + device: u32, +) -> Option { + let float = match lane { + Lane::Float(format) => Some(format), + Lane::Opaque => None, + }; + let mut noted = None; + for recorded in notes { + let note = recorded.note; + if !reaches(*recorded, fed_by) { + continue; + } + let within = match (allowance(note), float) { + (Allowance::Lanes(table), Some(format)) => { + lane_within(format, table.lane(format), metal, device) + } + (Allowance::Reduction, format) => match (reduction, format) { + (Some(table), Some(format)) => { + lane_within(format, table.lane(format), metal, device) + } + // A reduction no table bounds explains a difference without bounding it. + (None, _) => { + noted.get_or_insert(note); + false + } + (Some(_), None) => false, + }, + (Allowance::DenormalBoundary, Some(format)) => both_tiny(format, metal, device), + (Allowance::BothNan, Some(format)) => is_nan(format, metal) && is_nan(format, device), + (Allowance::HalfTexel, Some(FloatLane::Half)) => { + lane_within(FloatLane::Half, LaneTolerance { ulps: 1 }, metal, device) + || largest_beside_infinity(metal, device) + } + (Allowance::Unbounded, _) => { + noted.get_or_insert(note); + false + } + _ => false, + }; + if within { + return Some(Excuse::Bounded(note)); + } + } + noted.map(Excuse::Noted) +} + +/// Whether `recorded` reaches a word `fed_by` feeds. +fn reaches(recorded: RecordedNote, fed_by: Families) -> bool { + if !recorded.writer || fed_by.contains(Family::Unknown) { + return true; + } + match reach(recorded.note) { + Reach::Every => true, + Reach::Families(families) => families.meets(fed_by), + } +} + +/// The magnitude bits of the smallest normal of `format`, and its sign bit. +fn smallest_normal(format: FloatLane) -> (u32, u32) { + match format { + FloatLane::Half => (0x0400, 0x8000), + FloatLane::Float => (0x0080_0000, 0x8000_0000), + } +} + +/// Whether both lanes are a zero, a denormal or the smallest normal of `format`, of one sign +/// unless one of them is a zero. +pub fn both_tiny(format: FloatLane, metal: u32, device: u32) -> bool { + let (normal, sign) = smallest_normal(format); + let magnitude = |bits: u32| bits & (sign - 1); + let tiny = |bits: u32| magnitude(bits) <= normal; + tiny(metal) + && tiny(device) + && (magnitude(metal) == 0 || magnitude(device) == 0 || metal & sign == device & sign) +} + +/// Whether `bits` is a NaN of `format`. +fn is_nan(format: FloatLane, bits: u32) -> bool { + let (exponent, mantissa) = match format { + FloatLane::Half => (0x7c00, 0x03ff), + FloatLane::Float => (0x7f80_0000, 0x007f_ffff), + }; + bits & exponent == exponent && bits & mantissa != 0 +} + +/// Whether one `half` is the largest finite value and the other the infinity, of one sign. +fn largest_beside_infinity(metal: u32, device: u32) -> bool { + let pair = [metal & 0x7fff, device & 0x7fff]; + metal & 0x8000 == device & 0x8000 && (pair == [0x7bff, 0x7c00] || pair == [0x7c00, 0x7bff]) +} + +#[cfg(test)] +mod tests; diff --git a/crates/metal2vulkan-validation/src/observation_contract/words/tests.rs b/crates/metal2vulkan-validation/src/observation_contract/words/tests.rs new file mode 100644 index 000000000..4692ac674 --- /dev/null +++ b/crates/metal2vulkan-validation/src/observation_contract/words/tests.rs @@ -0,0 +1,392 @@ +//! The word judge: reach, bounds, and what a word that no reaching note excuses is. + +use super::*; +use PrecisionNote as N; + +fn writer(notes: &[PrecisionNote]) -> Vec { + notes + .iter() + .map(|¬e| RecordedNote { note, writer: true }) + .collect() +} + +fn words(shape: WordShape, fed_by: &[Family]) -> OutputWords { + OutputWords::uniform(WordFacts { + shape, + fed_by: Families::of(fed_by), + }) +} + +fn floats(words: &[u32]) -> Vec { + words.iter().flat_map(|word| word.to_le_bytes()).collect() +} + +fn verdict( + notes: &[PrecisionNote], + shape: WordShape, + fed_by: &[Family], + metal: u32, + device: u32, +) -> Verdict { + judge( + &writer(notes), + None, + &words(shape, fed_by), + &floats(&[metal]), + &floats(&[device]), + ) + .verdict() +} + +/// `DeviceDenormals` excuses a `float` word only where both answers lie at or below `2^-126`: the +/// flush before rounding (`+0` against `2^-126`) and a kept denormal against a zero match within +/// its bound; a word above the boundary, a denormal of the other sign, and a word of no float +/// lane are mismatches. +#[test] +fn the_denormal_boundary_excuses_only_words_at_or_below_the_smallest_normal() { + let product = [Family::FloatArithmetic]; + let boundary = |metal, device| { + verdict( + &[N::DeviceDenormals], + WordShape::Float, + &product, + metal, + device, + ) + }; + // Metal flushed before rounding; the device rounded to the smallest normal. + assert_eq!(boundary(0x0000_0000, 0x0080_0000), Verdict::Match); + assert_eq!(boundary(0x8000_0000, 0x8080_0000), Verdict::Match); + // Metal kept a denormal; the device flushed it to a zero of either sign. + assert_eq!(boundary(0x0000_1234, 0x8000_0000), Verdict::Match); + // Two denormals of one sign. + assert_eq!(boundary(0x0000_0001, 0x007f_ffff), Verdict::Match); + // Two nonzero denormals of other signs. + assert_eq!(boundary(0x0000_0001, 0x8000_0001), Verdict::Mismatch); + // Above the boundary on either side. + assert_eq!(boundary(0x0080_0001, 0x0000_0000), Verdict::Mismatch); + assert_eq!(boundary(0x0100_0000, 0x0080_0000), Verdict::Mismatch); + // An integer word whose bits read as denormals is no float lane. + assert_eq!( + verdict( + &[N::DeviceDenormals], + WordShape::Opaque, + &product, + 0x0000_0003, + 0x0000_0005 + ), + Verdict::Mismatch + ); + // A `half` lane takes its own boundary, `2^-14`; the other half of the word is exact. + let halves = WordShape::Halves { + low: true, + high: true, + }; + assert_eq!( + verdict( + &[N::DeviceDenormals], + halves, + &product, + 0x3c00_0000, + 0x3c00_0400 + ), + Verdict::Match + ); + assert_eq!( + verdict( + &[N::DeviceDenormals], + halves, + &product, + 0x3c00_0000, + 0x3c00_0401 + ), + Verdict::Mismatch + ); + // A word the note does not reach: a copy of an input, fed by no operation. + assert_eq!( + verdict( + &[N::DeviceDenormals], + WordShape::Float, + &[], + 0x0000_0000, + 0x0080_0000 + ), + Verdict::Mismatch + ); +} + +/// A note with no bound excuses only the words its operations feed: a division's note does not +/// reach a product's word, a sampling note does not reach a word no sample feeds, and a word the +/// scan could not follow is reached by every note. A note of another stage reaches every word. +#[test] +fn an_unbounded_note_reaches_only_the_words_its_operations_feed() { + let (metal, device) = (0x3f80_0000, 0x3f80_0003); + let float = WordShape::Float; + assert_eq!( + verdict( + &[N::NativeDivision], + float, + &[Family::FloatArithmetic], + metal, + device + ), + Verdict::Mismatch + ); + assert_eq!( + verdict( + &[N::NativeDivision], + float, + &[Family::Division], + metal, + device + ), + Verdict::Noted + ); + assert_eq!( + verdict(&[N::DeviceSampling], WordShape::Opaque, &[], 3, 4), + Verdict::Mismatch + ); + assert_eq!( + verdict( + &[N::DeviceSampling], + WordShape::Opaque, + &[Family::Texture], + 3, + 4 + ), + Verdict::Noted + ); + assert_eq!( + verdict( + &[N::DeviceSampling], + WordShape::Opaque, + &[Family::Unknown], + 3, + 4 + ), + Verdict::Noted + ); + let other_stage = [RecordedNote { + note: N::DeviceSampling, + writer: false, + }]; + assert_eq!( + judge( + &other_stage, + None, + &words(WordShape::Opaque, &[]), + &floats(&[3]), + &floats(&[4]) + ) + .verdict(), + Verdict::Noted + ); +} + +/// `SimdgroupAccessOrder` excuses only a word another thread may write. +#[test] +fn the_access_order_note_reaches_only_words_another_thread_may_write() { + let (metal, device) = (0x3f80_0000, 0x4000_0000); + let note = [N::SimdgroupAccessOrder]; + assert_eq!( + verdict( + ¬e, + WordShape::Float, + &[Family::FloatArithmetic, Family::Dot], + metal, + device + ), + Verdict::Mismatch + ); + assert_eq!( + verdict( + ¬e, + WordShape::Float, + &[Family::FloatArithmetic, Family::Unordered], + metal, + device + ), + Verdict::Noted + ); +} + +/// `NativeNanEncoding` excuses a word only where both answers are NaNs of its lane's format. +#[test] +fn a_nan_encoding_excuses_only_two_nans() { + let fed = [Family::FloatArithmetic]; + let note = [N::NativeNanEncoding]; + assert_eq!( + verdict(¬e, WordShape::Float, &fed, 0x7fc0_0000, 0xffc0_0000), + Verdict::Match + ); + assert_eq!( + verdict(¬e, WordShape::Float, &fed, 0x7fc0_0000, 0x7f80_0000), + Verdict::Mismatch + ); + assert_eq!( + verdict(¬e, WordShape::Float, &fed, 0x3f80_0000, 0x3f80_0001), + Verdict::Mismatch + ); + assert_eq!( + verdict(¬e, WordShape::Opaque, &fed, 0x7fc0_0000, 0xffc0_0000), + Verdict::Mismatch + ); + // A `half` moved from its bits, fed by no operation: the device's read may quiet it. + let halves = WordShape::Halves { + low: true, + high: true, + }; + assert_eq!( + verdict(¬e, halves, &[], 0x3c00_7e01, 0x3c00_7e00), + Verdict::Match + ); + assert_eq!( + verdict(¬e, halves, &[], 0x3c00_7e01, 0x3c00_7c00), + Verdict::Mismatch + ); +} + +/// `HalfTexelConversion` excuses a `half` one ulp apart, or the largest finite `half` against the +/// infinity of its sign, and nothing further. +#[test] +fn a_half_texel_conversion_excuses_one_half_ulp() { + let fed = [Family::Texture]; + let note = [N::HalfTexelConversion]; + let halves = WordShape::Halves { + low: true, + high: true, + }; + assert_eq!( + verdict(¬e, halves, &fed, 0x3c00_3c00, 0x3c01_3bff), + Verdict::Match + ); + assert_eq!( + verdict(¬e, halves, &fed, 0x0000_7bff, 0x0000_7c00), + Verdict::Match + ); + assert_eq!( + verdict(¬e, halves, &fed, 0x0000_fbff, 0x0000_7c00), + Verdict::Mismatch + ); + assert_eq!( + verdict(¬e, halves, &fed, 0x3c00_0000, 0x3c02_0000), + Verdict::Mismatch + ); +} + +/// A bounded note's excuse is a match, and wins over a note with no bound; the judgement counts +/// each word once, by the note that excused it. +#[test] +fn a_judgement_counts_each_word_by_its_excuse() { + let notes = writer(&[N::DeviceDenormals, N::NativeTranscendentals]); + let output = words(WordShape::Float, &[Family::Function]); + let golden = floats(&[0x3f80_0000, 0x0000_0000, 0x3f80_0000, 0x3f80_0000]); + let candidate = floats(&[0x3f80_0000, 0x0080_0000, 0x3f80_0009, 0x3f80_0000]); + let judgement = judge(¬es, None, &output, &golden, &candidate); + assert_eq!(judgement.exact, 2); + assert_eq!(judgement.bounded, [(N::DeviceDenormals, 1)].into()); + assert_eq!(judgement.noted, [(N::NativeTranscendentals, 1)].into()); + assert_eq!(judgement.unexcused, 0); + assert_eq!(judgement.verdict(), Verdict::Noted); + // Only the bounded word differs: a match within the bound. + let candidate = floats(&[0x3f80_0000, 0x0080_0000, 0x3f80_0000, 0x3f80_0000]); + assert_eq!( + judge(¬es, None, &output, &golden, &candidate).verdict(), + Verdict::Match + ); + // Lengths that differ are a mismatch. + assert_eq!( + judge(¬es, None, &output, &golden, &candidate[..4]).verdict(), + Verdict::Mismatch + ); +} + +/// Words past those any thread writes are reached by no note. +#[test] +fn words_no_thread_writes_are_reached_by_no_note() { + let output = OutputWords { + words: vec![WordFacts::unknown(WordShape::Float)], + written_words: Some(1), + }; + let notes = writer(&[N::DeviceArithmetic]); + let golden = floats(&[0x3f80_0000, 0x3f80_0000]); + let first = floats(&[0x3f80_0001, 0x3f80_0000]); + let second = floats(&[0x3f80_0000, 0x3f80_0001]); + assert_eq!( + judge(¬es, None, &output, &golden, &first).verdict(), + Verdict::Noted + ); + assert_eq!( + judge(¬es, None, &output, &golden, &second).verdict(), + Verdict::Mismatch + ); +} + +/// Every precision note has its reach. +#[test] +fn reach_rows_follow_the_notes_operations() { + assert_eq!( + reach(N::NativeFma), + Reach::Families(Families::of(&[Family::Fma])) + ); + assert_eq!( + reach(N::SimdgroupAccessOrder), + Reach::Families(Families::of(&[Family::Unordered])) + ); + assert_eq!(reach(N::DeviceLineRasterization), Reach::Every); + assert_eq!(reach(N::NativeNanEncoding), Reach::Every); + let families = Families::of(&[Family::Texture, Family::Unknown]); + let json = serde_json::to_string(&families).unwrap(); + assert_eq!(json, r#"["texture","unknown"]"#); + assert_eq!(serde_json::from_str::(&json).unwrap(), families); +} + +/// A lane table bounds only the float lanes of its own format that a word holds: a `half` one ulp +/// apart matches under `F16FmaDoubleRounding`; the same bits in a word of no float lane, and a +/// `float` one ulp apart, are mismatches; a trailing partial word takes its low half. +#[test] +fn a_lane_table_bounds_only_its_own_float_lanes() { + let note = [N::F16FmaDoubleRounding]; + let fed = [Family::Fma]; + let halves = WordShape::Halves { + low: true, + high: true, + }; + assert_eq!( + verdict(¬e, halves, &fed, 0x4000_3c00, 0x4000_3c01), + Verdict::Match + ); + assert_eq!( + verdict(¬e, WordShape::Opaque, &fed, 0x4000_3c00, 0x4000_3c01), + Verdict::Mismatch + ); + let integer_high = WordShape::Halves { + low: true, + high: false, + }; + assert_eq!( + verdict(¬e, integer_high, &fed, 0x4000_3c00, 0x4001_3c00), + Verdict::Mismatch + ); + assert_eq!( + verdict(¬e, WordShape::Float, &fed, 0x3f80_0000, 0x3f80_0001), + Verdict::Mismatch + ); + let output = words(halves, &fed); + let notes = writer(¬e); + assert_eq!( + judge(¬es, None, &output, &[0x00, 0x3c], &[0x01, 0x3c]).verdict(), + Verdict::Match + ); + assert_eq!( + judge( + ¬es, + None, + &output, + &[0x00, 0x3c, 0x00], + &[0x01, 0x3c, 0x00] + ) + .verdict(), + Verdict::Mismatch + ); +} diff --git a/crates/metal2vulkan-validation/src/store.rs b/crates/metal2vulkan-validation/src/store.rs index 07ae64fb1..2e0f77e5e 100644 --- a/crates/metal2vulkan-validation/src/store.rs +++ b/crates/metal2vulkan-validation/src/store.rs @@ -1648,6 +1648,7 @@ mod tests { out_of_bounds: None, rate_map_pass: None, artifact: None, + output_words: None, }); store.upsert_candidate(old).unwrap(); store diff --git a/crates/metal2vulkan-validation/src/triage.rs b/crates/metal2vulkan-validation/src/triage.rs index 6a7509979..39d257fc6 100644 --- a/crates/metal2vulkan-validation/src/triage.rs +++ b/crates/metal2vulkan-validation/src/triage.rs @@ -1935,6 +1935,11 @@ entry: "src/executor_contract/out_of_bounds.rs", "the executors' out-of-bounds containment verdict; classification runs no case", ), + ( + "src/observation_contract/words.rs", + "the word judge of a candidate's output against Metal's; classification judges no \ + output", + ), ( "src/case/sparse.rs", "the authored sparse-texture schema and its checks; classification reads no case \ diff --git a/crates/metal2vulkan-validation/src/vulkan_batch.rs b/crates/metal2vulkan-validation/src/vulkan_batch.rs index 018a1fe45..19789aabc 100644 --- a/crates/metal2vulkan-validation/src/vulkan_batch.rs +++ b/crates/metal2vulkan-validation/src/vulkan_batch.rs @@ -59,6 +59,7 @@ use crate::metal::{ORACLE_ABI, REFERENCE_GAP_EXIT}; use crate::observation::{ CandidateObservation, CandidateStatus, MetalObservation, MetalStatus, TRANSLATOR_FINGERPRINT, }; +use crate::observation_contract::words::{Family, Judgement, Verdict}; use crate::refusal::RefusalObservation; use crate::source::shard_name_for_hash; use crate::store::{CorpusStore, CANDIDATE_DIRECTORY, REFUSAL_DIRECTORY}; @@ -1508,6 +1509,18 @@ pub fn family(case: &AuthoredCase) -> String { /// Metal row, and a typed refusal /// `refusal=CLASS` from its recorded refusal (`device`, `product`, `executor`), or /// `refusal=unrecorded` for one before a device opened; +/// - a mismatch or a noted difference adds `judged=E/B/N/U` from its row's word judgement +/// ([`CandidateObservation::judgement`]): the words equal to Metal's, excused within a bounded +/// note, excused only by a note with no bound, and excused by none; `bounded=NOTE:W,...` and +/// `noted=NOTE:W,...` name the notes, and `fallback=W` counts the differing words every note +/// reaches because the scan could not follow them; +/// - `batch-bounded case=ID judged=E/B/N/U bounded=NOTE:W,...` for every run that matched with a +/// word excused within a bounded note; +/// - `batch-words noted_cases=N bounded_only_cases=N mismatch_cases=N exact=W bounded=W noted=W +/// unexcused=W fallback_cases=N fallback_word_cases=N` over the judged rows: a case's +/// `fallback` when a word of its output is one the scan could not follow, `fallback_word` when +/// such a word differs; then `batch-note note=NOTE bounded_cases=N bounded_words=W +/// noted_cases=N noted_words=W` per note that excused a word; /// - `batch-slowest case=ID pass=P seconds=S outcome=O` for the slowest run. pub fn report( selected: &[AuthoredCase], @@ -1618,6 +1631,34 @@ pub fn report( lines.push(line); } let slot = engine_slot(environment_id, restricted_to); + let judged = |case_id: &str| { + let row = row_of.get(&(case_id, slot.as_str()))?; + let metal = metal_of.get(case_id)?; + let decode = |b64: &str| base64::engine::general_purpose::STANDARD.decode(b64).ok(); + let (golden, output) = (decode(&metal.output_b64)?, decode(&row.output_b64)?); + Some((*row, row.judgement(by_id[case_id], &golden, &output))) + }; + let mut words = WordTotals::default(); + for run in &runs { + if !matches!( + run.outcome, + Outcome::Match | Outcome::Mismatch | Outcome::NotedDifference + ) { + continue; + } + let Some((row, judgement)) = judged(run.case_id.as_str()) else { + continue; + }; + words.add(row, &judgement); + if run.outcome == Outcome::Match && judgement.bounded_words() > 0 { + lines.push(format!( + "batch-bounded case={} {}", + run.case_id, + judged_words(&judgement) + )); + } + } + lines.extend(words.lines()); for run in runs.iter().filter(|run| run.outcome != Outcome::Match) { let case = by_id[run.case_id.as_str()]; let mut line = format!( @@ -1645,6 +1686,9 @@ pub fn report( word_difference(&metal.output_b64, &row.output_b64) )); } + if let Some((_, judgement)) = judged(run.case_id.as_str()) { + line.push_str(&format!(" {}", judged_words(&judgement))); + } } None => line.push_str(" row=missing"), } @@ -1674,6 +1718,110 @@ pub fn report( lines } +/// `judged=E/B/N/U`, then `bounded=NOTE:W,...`, `noted=NOTE:W,...` and `fallback=W` where any. +fn judged_words(judgement: &Judgement) -> String { + let by = |notes: &BTreeMap| { + notes + .iter() + .map(|(note, words)| format!("{note:?}:{words}")) + .collect::>() + .join(",") + }; + let mut line = format!( + "judged={}/{}/{}/{}", + judgement.exact, + judgement.bounded_words(), + judgement.noted_words(), + judgement.unexcused + ); + if !judgement.bounded.is_empty() { + line.push_str(&format!(" bounded={}", by(&judgement.bounded))); + } + if !judgement.noted.is_empty() { + line.push_str(&format!(" noted={}", by(&judgement.noted))); + } + if judgement.fallback > 0 { + line.push_str(&format!(" fallback={}", judgement.fallback)); + } + line +} + +/// The word judgements of a batch's rows, summed ([`report`]'s `batch-words` and `batch-note`). +#[derive(Default)] +struct WordTotals { + noted_cases: usize, + bounded_only_cases: usize, + mismatch_cases: usize, + exact: usize, + bounded: usize, + noted: usize, + unexcused: usize, + fallback_cases: usize, + fallback_word_cases: usize, + /// Per note: the cases and words it excused within its bound, and without one. + notes: BTreeMap, +} + +impl WordTotals { + fn add(&mut self, row: &CandidateObservation, judgement: &Judgement) { + match judgement.verdict() { + Verdict::Noted => self.noted_cases += 1, + Verdict::Mismatch => self.mismatch_cases += 1, + Verdict::Match if judgement.bounded_words() > 0 => self.bounded_only_cases += 1, + Verdict::Match => {} + } + self.exact += judgement.exact; + self.bounded += judgement.bounded_words(); + self.noted += judgement.noted_words(); + self.unexcused += judgement.unexcused; + let fallback = row + .census + .as_ref() + .and_then(|census| census.output_words.as_ref()) + .is_none_or(|words| { + words + .words + .iter() + .any(|word| word.fed_by.contains(Family::Unknown)) + }); + self.fallback_cases += usize::from(fallback); + self.fallback_word_cases += usize::from(judgement.fallback > 0); + for (note, words) in &judgement.bounded { + let entry = self.notes.entry(*note).or_default(); + entry[0] += 1; + entry[1] += words; + } + for (note, words) in &judgement.noted { + let entry = self.notes.entry(*note).or_default(); + entry[2] += 1; + entry[3] += words; + } + } + + fn lines(&self) -> Vec { + let mut lines = vec![format!( + "batch-words noted_cases={} bounded_only_cases={} mismatch_cases={} exact={} \ + bounded={} noted={} unexcused={} fallback_cases={} fallback_word_cases={}", + self.noted_cases, + self.bounded_only_cases, + self.mismatch_cases, + self.exact, + self.bounded, + self.noted, + self.unexcused, + self.fallback_cases, + self.fallback_word_cases + )]; + for (note, [bounded_cases, bounded_words, noted_cases, noted_words]) in &self.notes { + lines.push(format!( + "batch-note note={note:?} bounded_cases={bounded_cases} \ + bounded_words={bounded_words} noted_cases={noted_cases} noted_words={noted_words}" + )); + } + lines + } +} + /// `words=DIFFERING/TOTAL first=I:METAL/CANDIDATE` over the 32-bit little-endian words of two /// base64 outputs (a trailing partial word counts as one), or `bytes=METAL/CANDIDATE` when /// their lengths differ. diff --git a/crates/metal2vulkan-validation/src/vulkan_batch/tests.rs b/crates/metal2vulkan-validation/src/vulkan_batch/tests.rs index b4467a6f5..bdfa16631 100644 --- a/crates/metal2vulkan-validation/src/vulkan_batch/tests.rs +++ b/crates/metal2vulkan-validation/src/vulkan_batch/tests.rs @@ -138,13 +138,30 @@ fn row( } } -/// `row` under a class unbounded by `note`, with the status the executor gives it: a difference -/// is a noted one unless the answer gap `held_open_by` keeps it a mismatch. +/// `row` of a run whose one module records `note`, under the class unbounded by it, with the +/// status the executor gives it: a difference is a noted one unless the answer gap `held_open_by` +/// keeps it a mismatch. fn under_note( mut row: CandidateObservation, note: PrecisionNote, held_open_by: Option, ) -> CandidateObservation { + row.census = Some(crate::coverage::ExecutedCensus { + out_of_bounds: None, + rate_map_pass: None, + device: None, + product: "44".repeat(32), + restricted_to: None, + modules: vec![crate::coverage::ModuleCensus { + stage: Stage::Kernel, + subgroup: Default::default(), + strategies: Default::default(), + precision: [note].into(), + containment: None, + }], + artifact: None, + output_words: None, + }); row.comparison = ComparisonClass::Unbounded([note].into()); row.status = match held_open_by { Some(_) => CandidateStatus::Mismatch, @@ -931,17 +948,28 @@ fn the_report_counts_by_family_and_class_and_names_each_non_match() { expect(&format!( "batch-run case={} scope=private family=kernel.buffers outcome=mismatch \ seconds=2.000 name=b detail=Mismatch comparison={} held_open_by=clipped_primitive_split \ - words=1/2 first=1:00000002/00000003", + words=1/2 first=1:00000002/00000003 judged=1/0/1/0 noted=ClippedCoverageSplit:1 \ + fallback=1", mismatching.case_id, class(&held) )); expect(&format!( "batch-run case={} scope=private family=kernel.buffers outcome=noted_difference \ seconds=1.500 name=e detail=NotedDifference comparison={} words=1/2 \ - first=1:00000002/00000003", + first=1:00000002/00000003 judged=1/0/1/0 noted=DeviceSampling:1 fallback=1", noted.case_id, class(&differs) )); + // The word judgements of the two rows: each output's second word differs, and the rows record + // no output words, so every note reaches both words. + expect( + "batch-words noted_cases=2 bounded_only_cases=0 mismatch_cases=0 exact=2 bounded=0 \ + noted=2 unexcused=0 fallback_cases=2 fallback_word_cases=2", + ); + expect( + "batch-note note=DeviceSampling bounded_cases=0 bounded_words=0 noted_cases=1 \ + noted_words=1", + ); expect(&format!( "batch-run case={} scope=public family=kernel.buffers \ outcome=not_supported seconds=0.500 name=c detail=not_supported{{x}} refusal=device", diff --git a/crates/metal2vulkan-validation/src/worker/device/tests.rs b/crates/metal2vulkan-validation/src/worker/device/tests.rs index e3b0ebdff..fbc7c37eb 100644 --- a/crates/metal2vulkan-validation/src/worker/device/tests.rs +++ b/crates/metal2vulkan-validation/src/worker/device/tests.rs @@ -84,6 +84,7 @@ fn run_restricted_to(restricted_to: Option) -> DeviceRun { restricted_to, modules: Vec::new(), artifact: None, + output_words: None, }, } } diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 3a784fb94..29c585ea4 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -525,10 +525,14 @@ pub enum PrecisionNote { /// it matches none of the `float` sum rounded once per lane, a lane-order chain of `half` /// additions, or a Hillis-Steele scan of them. ReductionOrder, - /// `float` denormals follow the device: Metal reads an `f32` denormal operand of its float - /// arithmetic, comparisons, and functions as the zero of its sign and flushes a denormal result - /// to one, where a Vulkan device keeps or flushes them by its own float controls (this - /// translation declares no `DenormFlushToZero`). Recorded where the module leaves an + /// `float` denormals follow the device. Metal's answer at the denormal boundary is per + /// operation (an Apple M3 Max, the public cases `float-products-flushed-before-rounding` and + /// `nan-model-float-denormals-per-operation`): it flushes before rounding on some (a product, + /// a fused multiply-add, `dot` and `mix` whose exact result lies just below `2^-126` answer a + /// zero, where a device that rounds first answers `2^-126`) and keeps a denormal on others + /// (`sin`, `tan`, `asin`, `sinh`, `asinh` and `atanh` of a denormal operand answer a + /// denormal), where a Vulkan device keeps or flushes denormals by its own float controls (this + /// translation declares no `DenormFlushToZero`): the device may answer either. Recorded where the module leaves an /// operation's denormals to the device: `+ - *`, the comparisons, `fma`, `dot`, `sqrt`, /// `rsqrt`, `trunc`, `rint` and `ldexp` on `float` (by the device's products), `fneg`, `fabs`, /// `floor` and `ceil` on `float`, the divisions and the remainder, the device's maths functions @@ -553,8 +557,13 @@ pub enum PrecisionNote { /// pixel coordinates) and its word states such a mode (`SpecKey::BoundSamplerWord`, which the /// runtime reads at each draw or dispatch), never under a normalized state; through an /// argument buffer's sampler [`PrecisionNote::ArgumentPixelSamplerScaling`] records it - /// instead. A pixel fetch under an offset records it outright. Validation derives no tolerance and no explanation from it: every - /// `float` computation is exposed to it. + /// instead. A pixel fetch under an offset records it outright. + /// + /// Validation bounds it at the word: a float lane its operations feed may differ only where + /// Metal's answer and the device's both lie at or below the smallest normal of the lane's + /// format (a zero, a denormal or `2^-126`; `2^-14` for `half`), of one sign unless one is a + /// zero, and matches there. Nothing above that boundary is excused, though a flushed operand + /// can carry its difference to any later value. DeviceDenormals, /// A pixel-coordinate sampler's coordinate reaches the device's normalized sampler divided by /// the texture's level-0 size in the shader, and the device's sampler reads its texels from @@ -865,7 +874,9 @@ pub enum PrecisionNote { /// slot bound in an 8-bit sRGB format the device holds as its UNORM twin decodes the code /// exactly instead, and a bicubic sample sums the codes' steps exactly, under the slot's /// `SrgbTexture` variant, and records nothing. What a filtered sample converts is the filter's - /// value. Validation derives no tolerance from it. + /// value. Validation bounds it at the word by its recorded bound below: a `half` lane a texture + /// access feeds matches within one `half` ulp of Metal's, or as `±65504` against the infinity + /// of its sign. /// /// Native device sampling (a texel conversion): every access with a `half` result records this /// note, a heap element's and a depth texture's included. The recorded bound: the device's @@ -1637,7 +1648,8 @@ pub enum PrecisionNote { /// module whose entry reaches a `float` constant whose bits are a signalling NaN, the /// program's own or one Metal's compiler leaves where a NaN operand decides an operation: /// Metal keeps its bits, and the device's move of it as a `float` may quiet it. Validation - /// derives no tolerance from it. + /// excuses a float lane its operations feed only where Metal's answer and the device's are + /// both NaNs of the lane's format, and matches it there. 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/docs/API.md b/docs/API.md index f396eaecb..01b4f20d7 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1805,10 +1805,13 @@ category, and says what makes an operation carry the note and what may differ. E `float` sum rounded once per lane, a lane-order chain of `half` additions, or a Hillis-Steele scan of them. - `metal2vulkan-degrade-device-denormals` (precision). `PrecisionNote::DeviceDenormals`: `float` - denormals follow the device: Metal reads an `f32` denormal operand of its float arithmetic, - comparisons, and functions as the zero of its sign and flushes a denormal result to one, where a - Vulkan device keeps or flushes them by its own float controls (this translation declares no - `DenormFlushToZero`). Recorded where the module leaves an operation's denormals to the device, + denormals follow the device. Metal's answer at the denormal boundary is per operation (an Apple + M3 Max): it flushes before rounding on some (a product, a fused multiply-add, `dot` and `mix` + whose exact result lies just below `2^-126` answer a zero, where a device that rounds first + answers `2^-126`) and keeps a denormal on others (`sin`, `tan`, `asin`, `sinh`, `asinh` and + `atanh` of a denormal operand answer a denormal), where a Vulkan device keeps or flushes + denormals by its own float controls (this translation declares no `DenormFlushToZero`): the + device may answer either. Recorded where the module leaves an operation's denormals to the device, on every device: `+ - *`, the comparisons, `fma`, `dot`, `sqrt`, `rsqrt`, `trunc`, `rint` and `ldexp` on `float` (by the device's products); `fneg`, `fabs`, `floor` and `ceil` on `float`; the divisions and the remainder, the device's maths functions (`fast::fmod`'s fused diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 90be40282..d0d507577 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -612,17 +612,28 @@ cargo run -p metal2vulkan-validation --release --bin corpus-vulkan -- \ case's facts, and no SPIR-V, status, subgroup shape, module containment or artifact. The comparison bounds `ReductionOrder` by the simdgroup float sums and products the case's AIR calls, the operations the translator's census names for that note. -- **The verdict.** A row whose bytes equal Metal's, or differ within its comparison class's - bound, is a `Match`. A difference is never a match: under a class unbounded by precision notes - it is a `NotedDifference` (the notes can explain a difference; whether they explain this one is - not checked), counted in its own `noted_difference` column, and otherwise a `Mismatch`. A - difference of a case the C3 reviewed list holds under an answer gap its structure meets stays a +- **The verdict.** A row's output is judged against Metal's one 32-bit little-endian word at a + time. An equal word matches. A differing word is excused only by a precision note that reaches + it. What reaches a word is read from the case's AIR: the float lanes the word holds, and the + operation families whose results feed it (float arithmetic, division, fused multiply-add, `dot`, + `mix`, minimum and maximum, other functions, packs, textures, group operations, stage inputs, + and a store another thread of the kernel may make there). A note of the module whose entry + writes the output reaches the words its operations feed; a note of any other module reaches + every word, and so does every note of a word the scan cannot follow (a load of memory the + function writes, a call outside the intrinsic families). A note with a bound (a lane table, the + reassociation bound, the denormal boundary, two NaNs, a `half` texel's ulp) makes a word within + it a match; a note with no bound makes it a noted word. A row whose differing words are all + within bounds is a `Match`; one with a noted word and no unexcused word is a `NotedDifference`, + counted in its own `noted_difference` column; a word no reaching note excuses makes it a + `Mismatch`. A difference of a case the C3 reviewed list holds under an answer gap its structure meets stays a `Mismatch`, its row and batch line naming the gap (`held_open_by`): the user's decision of 2026-10-06 keeps answer gaps open until an exact emulation exists. - **Batches.** `--batch --out OUT` runs every selected case, one process per case, each killed whole after `--run-timeout`, resuming from `OUT/done.tsv`; `--batch-report` and `--batch-install STORE` read and install the results. A batch starts no GPU run while the - tripwire exists. + tripwire exists. The report prints, per case and in total, the words matched exactly, within + each note's bound and only noted, by note, the unexcused words, and the cases with a differing + word the scan could not follow. - **What counts.** An observation is current only for the product, executor and runtime versions it was made with: a row records the product fingerprint, the executor ABI and `RUNTIME_VERSION`, and a change of any makes it stale until it is rerun. A stored observation, a valid module or a