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).
This commit is contained in:
Anees Iqbal committed 2026-12-03 03:27:51 -08:00
1 parent 1c68dd10f4
commit e31bc61172
27 files changed
+3226 -387

No files matched your search

@@ -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);
@@ -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<ReviewedList, String>,
) -> Result<(CandidateStatus, Option<AnswerGap>), 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(
@@ -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, &noted), 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, &noted), 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
@@ -667,6 +667,7 @@ pub(super) fn ran(
restricted_to: identity.restricted_to.clone(),
modules: vec![module],
artifact: None,
output_words: None,
};
ComputeRun {
output,
@@ -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;
@@ -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<super::output_words::Stores>,
}
/// 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,
}
}
}
File diff suppressed because it is too large. Load diff
@@ -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::<Vec<_>>();
shards.sort();
shards
.iter()
.flat_map(|shard| {
std::fs::read_to_string(shard)
.expect("a committed shard")
.lines()
.map(|line| serde_json::from_str::<AuthoredCase>(line).expect("a case"))
.collect::<Vec<_>>()
})
.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<OutputWords> {
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,
})
);
}
+84 -2
View File
@@ -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<ExecutedArtifact>,
/// 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<OutputWords>,
}
/// 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<RecordedNote> {
let mut notes = self
.modules
.iter()
.flat_map(|module| {
let writer = module.stage == case.stage;
module
.precision
.iter()
.map(move |&note| RecordedNote { note, writer })
})
.chain(self.rate_map_pass.iter().flat_map(|pass| {
pass.precision.iter().map(|&note| RecordedNote {
note,
writer: false,
})
}))
.collect::<Vec<_>>();
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<Item = PrecisionNote> + '_ {
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<Item = &str> + '_ {
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 {
@@ -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();
@@ -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
@@ -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: `<medium>:<check>`.
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,
@@ -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
};
@@ -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<crate::c3::AnswerGap>,
}
/// 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);
@@ -1,4 +1,5 @@
mod comparison;
pub mod words;
pub use comparison::{
allowance, census_names, lane_within, reduction_table, reorder_ulps, value_difference,
@@ -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<Item = PrecisionNote>,
strategies: impl IntoIterator<Item = &'a str>,
@@ -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<Item = &str> {
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.
@@ -16,14 +16,6 @@ fn class(notes: &[PrecisionNote], strategies: &[&str]) -> ComparisonClass {
ComparisonClass::derive(notes.iter().copied(), strategies.iter().copied())
}
fn halves(lanes: &[u16]) -> Vec<u8> {
lanes.iter().flat_map(|lane| lane.to_le_bytes()).collect()
}
fn floats(lanes: &[u32]) -> Vec<u8> {
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())
);
}
@@ -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<Item = Family> {
Family::ALL
.into_iter()
.filter(move |family| self.contains(*family))
}
}
impl Serialize for Families {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(self.iter())
}
}
impl<'de> Deserialize<'de> for Families {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let families = Vec::<Family>::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<WordFacts>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub written_words: Option<u64>,
}
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<PrecisionNote, usize>,
/// The differing words only a note with no bound excuses, by the note that excused the first
/// lane it excused.
pub noted: BTreeMap<PrecisionNote, usize>,
/// 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<UlpTable>,
words: &OutputWords,
golden: &[u8],
candidate: &[u8],
) -> Judgement {
let notes = notes.iter().copied().collect::<BTreeSet<_>>();
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(&notes, 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<RecordedNote>,
reduction: Option<UlpTable>,
fed_by: Families,
lane: Lane,
metal: u32,
device: u32,
) -> Option<Excuse> {
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;
@@ -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<RecordedNote> {
notes
.iter()
.map(|&note| 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<u8> {
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(
&note,
WordShape::Float,
&[Family::FloatArithmetic, Family::Dot],
metal,
device
),
Verdict::Mismatch
);
assert_eq!(
verdict(
&note,
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(&note, WordShape::Float, &fed, 0x7fc0_0000, 0xffc0_0000),
Verdict::Match
);
assert_eq!(
verdict(&note, WordShape::Float, &fed, 0x7fc0_0000, 0x7f80_0000),
Verdict::Mismatch
);
assert_eq!(
verdict(&note, WordShape::Float, &fed, 0x3f80_0000, 0x3f80_0001),
Verdict::Mismatch
);
assert_eq!(
verdict(&note, 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(&note, halves, &[], 0x3c00_7e01, 0x3c00_7e00),
Verdict::Match
);
assert_eq!(
verdict(&note, 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(&note, halves, &fed, 0x3c00_3c00, 0x3c01_3bff),
Verdict::Match
);
assert_eq!(
verdict(&note, halves, &fed, 0x0000_7bff, 0x0000_7c00),
Verdict::Match
);
assert_eq!(
verdict(&note, halves, &fed, 0x0000_fbff, 0x0000_7c00),
Verdict::Mismatch
);
assert_eq!(
verdict(&note, 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(&notes, 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(&notes, None, &output, &golden, &candidate).verdict(),
Verdict::Match
);
// Lengths that differ are a mismatch.
assert_eq!(
judge(&notes, 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(&notes, None, &output, &golden, &first).verdict(),
Verdict::Noted
);
assert_eq!(
judge(&notes, 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::<Families>(&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(&note, halves, &fed, 0x4000_3c00, 0x4000_3c01),
Verdict::Match
);
assert_eq!(
verdict(&note, WordShape::Opaque, &fed, 0x4000_3c00, 0x4000_3c01),
Verdict::Mismatch
);
let integer_high = WordShape::Halves {
low: true,
high: false,
};
assert_eq!(
verdict(&note, integer_high, &fed, 0x4000_3c00, 0x4001_3c00),
Verdict::Mismatch
);
assert_eq!(
verdict(&note, WordShape::Float, &fed, 0x3f80_0000, 0x3f80_0001),
Verdict::Mismatch
);
let output = words(halves, &fed);
let notes = writer(&note);
assert_eq!(
judge(&notes, None, &output, &[0x00, 0x3c], &[0x01, 0x3c]).verdict(),
Verdict::Match
);
assert_eq!(
judge(
&notes,
None,
&output,
&[0x00, 0x3c, 0x00],
&[0x01, 0x3c, 0x00]
)
.verdict(),
Verdict::Mismatch
);
}
@@ -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
@@ -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 \
@@ -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<metal2vulkan::pipeline::PrecisionNote, usize>| {
notes
.iter()
.map(|(note, words)| format!("{note:?}:{words}"))
.collect::<Vec<_>>()
.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<metal2vulkan::pipeline::PrecisionNote, [usize; 4]>,
}
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<String> {
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.
@@ -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<crate::c3::AnswerGap>,
) -> 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",
@@ -84,6 +84,7 @@ fn run_restricted_to(restricted_to: Option<String>) -> DeviceRun {
restricted_to,
modules: Vec::new(),
artifact: None,
output_words: None,
},
}
}
+20 -8
View File
@@ -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
+7 -4
View File
@@ -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
+17 -6
View File
@@ -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