diff --git a/crates/metal2vulkan-validation/build.rs b/crates/metal2vulkan-validation/build.rs index 32af3cad1..1f290106b 100644 --- a/crates/metal2vulkan-validation/build.rs +++ b/crates/metal2vulkan-validation/build.rs @@ -27,6 +27,29 @@ fn main() { hex(&validation_hash.finalize()) ); + // The runtime crate's sources (`metal2vulkan-runtime`: its manifest and the files its module + // tree compiles, `build_support::product_files`), through which the engine candidate runs a + // case: a row it ran is current only for this build of them + // (`candidate::engine::runtime_fingerprint`). + let runtime_crate = Path::new("../metal2vulkan-runtime"); + println!( + "cargo:rerun-if-changed={}", + runtime_crate.join("src").display() + ); + let mut runtime_crate_files = vec![runtime_crate.join("Cargo.toml")]; + runtime_crate_files.extend(build_support::product_files(runtime_crate)); + runtime_crate_files.sort(); + let mut runtime_crate_hash = Sha256::new(); + hash_files( + &mut runtime_crate_hash, + Path::new(".."), + &runtime_crate_files, + ); + println!( + "cargo:rustc-env=METAL2VULKAN_RUNTIME_CRATE_FINGERPRINT={}", + hex(&runtime_crate_hash.finalize()) + ); + // Authoring-capability classification (`triage::ANALYZER_ABI`) reads exactly these files of // this crate beside the product: its manifest (which selects the product's features) and the // modules its non-test code reaches. An edit to one invalidates the cached facts; an edit diff --git a/crates/metal2vulkan-validation/src/acceptance.rs b/crates/metal2vulkan-validation/src/acceptance.rs index d0e3f96e9..f37c6efee 100644 --- a/crates/metal2vulkan-validation/src/acceptance.rs +++ b/crates/metal2vulkan-validation/src/acceptance.rs @@ -1030,7 +1030,7 @@ fn compile_counted( /// the values of the constants its library declares and ignores the others, as Metal does. With /// them come their table handles ([`LinkedHandles`]): each function's /// `LinkedFunctions::function_handle` over the whole list. -fn linked_functions( +pub(crate) fn linked_functions( libraries: &[&[u8]], linked: &[LinkedLibrary], constants: &FunctionConstantValues, diff --git a/crates/metal2vulkan-validation/src/c3.rs b/crates/metal2vulkan-validation/src/c3.rs index fb8ad04b7..ad126cfc3 100644 --- a/crates/metal2vulkan-validation/src/c3.rs +++ b/crates/metal2vulkan-validation/src/c3.rs @@ -218,8 +218,10 @@ pub struct ReviewedObservation { /// The engine store slot (`ENV@engine`, with `+robustness-off` for that leg): host, /// engine, profile restriction, and leg. pub environment_id: String, - /// The candidate: the SHA-256 of the pipeline's SPIR-V the row executed. - pub spv_sha256: String, + /// The candidate: the SHA-256 of the pipeline's SPIR-V the row executed, where its row records + /// one (`None` for a row the runtime ran). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spv_sha256: Option, /// The reading reviewed: the candidate's output. pub candidate_output_sha256: String, /// Metal's reading it was compared with. @@ -505,14 +507,18 @@ impl List for ReviewedList { if !slots.insert(observation.environment_id.as_str()) { return Err(at("listed twice".into())); } - for (field, value) in [ - ("spv_sha256", &observation.spv_sha256), - ( - "candidate_output_sha256", - &observation.candidate_output_sha256, - ), - ("golden_output_sha256", &observation.golden_output_sha256), - ] { + for (field, value) in observation + .spv_sha256 + .iter() + .map(|spv| ("spv_sha256", spv)) + .chain([ + ( + "candidate_output_sha256", + &observation.candidate_output_sha256, + ), + ("golden_output_sha256", &observation.golden_output_sha256), + ]) + { validate_hash(field, value).map_err(at)?; } if observation.values.trim().is_empty() { diff --git a/crates/metal2vulkan-validation/src/c3/tests.rs b/crates/metal2vulkan-validation/src/c3/tests.rs index 154037e05..8aeb426c2 100644 --- a/crates/metal2vulkan-validation/src/c3/tests.rs +++ b/crates/metal2vulkan-validation/src/c3/tests.rs @@ -246,7 +246,7 @@ fn row( air_sha256: case.air_sha256.clone(), input_sha256: case.computed_input_sha256().unwrap(), golden_output_sha256: sha256_bytes(golden), - spv_sha256: "33".repeat(32), + spv_sha256: Some("33".repeat(32)), translator_fingerprint: String::new(), candidate_output_sha256: sha256_bytes(output), output_b64: b64(output), @@ -327,7 +327,7 @@ fn noting(mut row: CandidateObservation, notes: &[PrecisionNote]) -> CandidateOb leg: None, modules: vec![crate::coverage::ModuleCensus { stage: Stage::Kernel, - subgroup: crate::coverage::SubgroupShape::default(), + subgroup: Some(crate::coverage::SubgroupShape::default()), strategies: BTreeSet::new(), precision: notes.iter().copied().collect(), containment: None, @@ -506,7 +506,7 @@ fn a_listed_mismatch_at_its_candidate_is_reviewed_and_a_changed_candidate_is_not // A changed candidate leaves the list: the row is a mismatch again and the entry is stale, // whether the SPIR-V or the reading changed. let changes: [fn(&mut CandidateObservation); 2] = [ - |row| row.spv_sha256 = "55".repeat(32), + |row| row.spv_sha256 = Some("55".repeat(32)), |row| { let output = [2, 0, 0x80, 0x3f]; row.output_b64 = b64(&output); @@ -1399,10 +1399,10 @@ fn a_device_interpolation_row_stays_a_mismatch() { leg: None, modules: vec![ModuleCensus { stage: crate::case::Stage::Fragment, - subgroup: crate::coverage::SubgroupShape { + subgroup: Some(crate::coverage::SubgroupShape { full_subgroups: false, required_size: None, - }, + }), strategies: Default::default(), precision: [note].into(), containment: None, @@ -1497,10 +1497,10 @@ fn deferred_and_never_reviewed(note: PrecisionNote, label: &str) { leg: None, modules: vec![ModuleCensus { stage: crate::case::Stage::Kernel, - subgroup: crate::coverage::SubgroupShape { + subgroup: Some(crate::coverage::SubgroupShape { full_subgroups: false, required_size: None, - }, + }), strategies: Default::default(), precision: [note].into(), containment: None, @@ -2410,7 +2410,7 @@ fn a_regrouping_reading_is_keyed_by_its_cause_in_every_slot() { ] .map(|row| unbounded_by(row, ®roup)); for (at, row) in rows.iter_mut().enumerate() { - row.spv_sha256 = format!("{:02x}", 0x60 + at).repeat(32); + row.spv_sha256 = Some(format!("{:02x}", 0x60 + at).repeat(32)); } let input_of = |rows: &[CandidateObservation]| C3Input { cases: vec![fft.clone()], @@ -2446,7 +2446,7 @@ fn a_regrouping_reading_is_keyed_by_its_cause_in_every_slot() { // The reading's one observation is the lavapipe slot's row at an earlier candidate and output: // keyed by its cause, it reviews every slot's row that records the cause, and it holds. let mut earlier = reviewed(&rows[1], &METAL); - earlier.spv_sha256 = "99".repeat(32); + earlier.spv_sha256 = Some("99".repeat(32)); earlier.candidate_output_sha256 = sha256_bytes(&OTHER); let mut regrouping = reading(&fft, vec![earlier]); regrouping.cause = Cause::FastMathRegrouping; @@ -3470,10 +3470,10 @@ fn a_deferred_near_equivalent_stays_open_with_its_reason() { leg: None, modules: vec![ModuleCensus { stage: crate::case::Stage::Kernel, - subgroup: crate::coverage::SubgroupShape { + subgroup: Some(crate::coverage::SubgroupShape { full_subgroups: false, required_size: None, - }, + }), strategies: Default::default(), precision: [PrecisionNote::RasterizationRateMap].into(), containment: None, diff --git a/crates/metal2vulkan-validation/src/candidate.rs b/crates/metal2vulkan-validation/src/candidate.rs index 62d8d7248..579ace841 100644 --- a/crates/metal2vulkan-validation/src/candidate.rs +++ b/crates/metal2vulkan-validation/src/candidate.rs @@ -236,6 +236,17 @@ mod platform { )) } + pub fn execute_runtime( + _device: DeviceType, + _case_id: &str, + _case: &super::engine::ComputeCase, + _kernel: super::engine::RuntimeKernel<'_>, + ) -> super::engine::RunAttempt { + super::engine::RunAttempt::of(Err( + "candidate execution is supported only on Linux and macOS".into(), + )) + } + pub fn echo_validation_messages() {} pub fn requested_restriction() -> Option { diff --git a/crates/metal2vulkan-validation/src/candidate/engine.rs b/crates/metal2vulkan-validation/src/candidate/engine.rs index f8ed5a251..febeb456b 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine.rs @@ -69,7 +69,7 @@ use crate::literal::{LiteralResources, LiteralTexture}; use crate::metal::ORACLE_ABI; use crate::observation::{ Backend, CandidateDependencies, CandidateObservation, CandidateStatus, CaseTiming, - MetalObservation, TRANSLATOR_FINGERPRINT, + MetalObservation, RUNTIME_CRATE_FINGERPRINT, TRANSLATOR_FINGERPRINT, }; use crate::observation_contract::ComparisonClass; use crate::refusal::{Refusal, RefusalObservation}; @@ -123,7 +123,7 @@ use tables::{function_tables, table_buffers, FunctionTable, TableBuffers}; /// 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-v184"; +pub const ENGINE_EXECUTOR_ABI: &str = "vulkan-engine-v185"; /// One kernel case in the terms the binder takes: what this executor supports of an /// [`AuthoredCase`] (buffers, device buffer arrays, argument-buffer buffers and textures, command @@ -355,12 +355,17 @@ pub enum ComputeOutput { #[derive(Clone, Debug)] pub struct ComputeRun { pub output: Vec, - /// SHA-256 of the pipeline's SPIR-V bytes (before specialization). - pub spv_sha256: String, - /// [`engine_fingerprint`] of the profile the case compiled for. + /// SHA-256 of the pipeline's SPIR-V bytes (before specialization), where the executor + /// compiled it itself; `None` for a run through the runtime ([`runs_through_runtime`]), which + /// keeps its modules to itself. + pub spv_sha256: Option, + /// [`engine_fingerprint`] of the profile the case compiled for, or [`runtime_fingerprint`] + /// for a run through the runtime. pub translator_fingerprint: String, pub environment: serde_json::Value, - pub status: StatusReport, + /// The binder's execution status, read before the output; `None` for a run through the + /// runtime, whose shaders keep no status. + pub status: Option, /// Derived from the executed modules' precision notes and strategy census. pub comparison: ComparisonClass, /// The executed modules' census and the class of the device that ran them. @@ -1154,6 +1159,172 @@ pub fn engine_fingerprint_of(profile: &Hash256) -> String { sha256_bytes(&bytes) } +/// The translator fingerprint of a run through the runtime ([`runs_through_runtime`]): the +/// product, its semantics version and the runtime crate's sources +/// ([`RUNTIME_CRATE_FINGERPRINT`]). The runtime derives what it compiles for from the device it +/// opened and answers none of it, so no profile is part of it; the row's slot and its recorded +/// device are. +pub fn runtime_fingerprint() -> String { + let mut bytes = Vec::new(); + bytes.extend_from_slice(b"metal2vulkan-engine-runtime\0"); + bytes.extend_from_slice(TRANSLATOR_FINGERPRINT.as_bytes()); + bytes.push(0); + bytes.extend_from_slice(&metal2vulkan::cache::SEMANTICS_VERSION.to_le_bytes()); + bytes.extend_from_slice(RUNTIME_CRATE_FINGERPRINT.as_bytes()); + sha256_bytes(&bytes) +} + +/// Whether `case`, mapped from `authored`, runs through the runtime (`metal2vulkan-runtime`'s +/// public API, `platform::execute_runtime`) in place of the executor's own context: a kernel +/// case of buffers (each device buffer array's elements among them), threadgroup memory +/// lengths, function constants and linked functions, dispatched by `dispatchThreads` or +/// `dispatchThreadgroups`, and observing a buffer or nothing. Decided by the case's structure +/// alone: every field the mapping fills is named here, so a new one is decided when it is added. +pub fn runs_through_runtime(authored: &AuthoredCase, case: &ComputeCase) -> bool { + let ComputeCase { + entry: _, + constants: _, + buffers: _, + rate_maps, + argument_buffer_buffers, + argument_buffer_rate_maps, + argument_buffer_textures, + argument_buffer_samplers, + objects, + command_buffers, + textures, + samplers, + function_tables, + acceleration_structures, + threadgroup_lengths: _, + imageblock, + tile, + stage_input, + stage_in_region, + attribute_strides, + dispatch, + output, + out_of_bounds, + creation_bound: _, + } = case; + rate_maps.is_empty() + && argument_buffer_buffers.is_empty() + && argument_buffer_rate_maps.is_empty() + && argument_buffer_textures.is_empty() + && argument_buffer_samplers.is_empty() + && objects.is_empty() + && command_buffers.is_empty() + && textures.is_empty() + && samplers.is_empty() + && function_tables.is_empty() + && acceleration_structures.is_empty() + && imageblock.is_none() + && tile.is_none() + && stage_input.is_none() + && stage_in_region.is_none() + && attribute_strides.is_empty() + && out_of_bounds.is_empty() + && matches!( + dispatch, + Dispatch::Threads { .. } | Dispatch::Threadgroups { .. } + ) + && matches!(output, ComputeOutput::None | ComputeOutput::Buffer { .. }) + && authored.intersection_function_tables.is_empty() +} + +/// The bytes of each buffer a run through the runtime binds, by Metal index, as the Metal oracle +/// creates them (`metal::platform::buffers`): a bound buffer's authored bytes padded to the size +/// its argument declares ([`buffer_bytes_padded_to_declared_size`]), and a device buffer array's +/// element's as authored. +/// +/// [`buffer_bytes_padded_to_declared_size`]: crate::executor_contract::buffer_bytes_padded_to_declared_size +fn runtime_buffers( + authored: &AuthoredCase, + reflection: &crate::air::reflect::ShaderInterface, + case: &ComputeCase, +) -> BTreeMap> { + case.buffers + .iter() + .map(|(&index, bytes)| { + let bound = authored + .buffers + .iter() + .any(|buffer| buffer.binding == index); + let bytes = match bound { + true => crate::executor_contract::buffer_bytes_padded_to_declared_size( + bytes, + crate::executor_contract::reflected_buffer_declared_size(reflection, index), + ) + .into_owned(), + false => bytes.clone(), + }; + (index, bytes) + }) + .collect() +} + +/// The simdgroup float sums and products a run through the runtime executes +/// (`check::interface::float_reductions`): the case's entry's, which its check read, and those of +/// each function it links from `linked`, read from its module. +fn runtime_reductions( + interface: &AirInterface, + linked: &[LinkedModule], +) -> Result, ExecutorError> { + let mut reductions = interface.float_reductions.clone(); + for module in linked { + let decoded = crate::check::loop_free::DecodedModule::from_bitcode( + &module.module_sha256, + &module.bitcode, + ) + .map_err(|error| ExecutorError::Failed(format!("a linked module: {error}")))?; + let roots = + crate::check::interface::functions_named(decoded.module(), &module.library.functions); + reductions.extend(crate::check::interface::float_reductions( + decoded.module(), + roots, + )); + } + Ok(reductions) +} + +/// A run through the runtime ([`runs_through_runtime`]) of `prepared`'s kernel case `compute`: +/// the row's AIR and each module it links, its buffers as the oracle makes them +/// ([`runtime_buffers`]), and the float reductions it executes ([`runtime_reductions`]), run by +/// `platform::execute_runtime`. +fn run_on_runtime(prepared: &PreparedCase, compute: &ComputeCase) -> RunAttempt { + let primary = &prepared.checked.primary; + let kernel = match RowSource::of_row(&primary.source).bitcode() { + Ok(kernel) => kernel, + Err(error) => return RunAttempt::of(Err(ExecutorError::Failed(error.to_string()))), + }; + let reductions = match runtime_reductions(&primary.interface, &prepared.linked) { + Ok(reductions) => reductions, + Err(error) => return RunAttempt::of(Err(error)), + }; + let buffers = runtime_buffers(&primary.case, &primary.reflection, compute); + super::platform::execute_runtime( + prepared.device, + &primary.case.case_id, + compute, + RuntimeKernel { + bitcode: &kernel, + linked: &prepared.linked, + buffers: &buffers, + reductions: &reductions, + }, + ) +} + +/// What a run through the runtime makes its kernel and binds from, beside its mapped case: the +/// row's AIR, the modules it links, its buffers' bytes by Metal index ([`runtime_buffers`]), and +/// the float reductions it executes ([`runtime_reductions`]). +pub struct RuntimeKernel<'a> { + pub bitcode: &'a [u8], + pub linked: &'a [LinkedModule], + pub buffers: &'a BTreeMap>, + pub reductions: &'a std::collections::BTreeSet<&'static str>, +} + /// The suffix of an engine store slot. const ENGINE_SLOT_SUFFIX: &str = "@engine"; @@ -2826,6 +2997,18 @@ fn run_on_context(prepared: &PreparedCase, backend: Backend, worker: &CompileWor // The worker assembles a row that retains no bitcode (a public fixture), and a companion. let library = RowSource::of_row(&prepared.checked.primary.source); let linked = &prepared.linked; + // A case the runtime runs, run so in this process's default run: the native backend, no + // profiles-layer restriction, the stated leg. It records no artifact: the runtime keeps + // what it compiled to itself. + if let Mapped::Compute(compute) = &prepared.mapped { + if backend == Backend::Vulkan + && runs_through_runtime(case, compute) + && super::requested_restriction().is_none() + && super::requested_leg() == Leg::Stated + { + return run_on_runtime(prepared, compute); + } + } let artifact = RefCell::new(artifact::CaseArtifact::default()); // Each executed command's template, compiled for the command's bind shape and dispatch or // draw. @@ -3208,7 +3391,7 @@ pub fn execute_prepared( let dependencies = CandidateDependencies { case, metal: &metal, - spv_sha256: &run.spv_sha256, + spv_sha256: run.spv_sha256.as_deref(), translator_fingerprint: &run.translator_fingerprint, backend, environment_id: &slot, diff --git a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs index a30f362de..820549a51 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs @@ -2540,3 +2540,84 @@ fn addressed_allocations_take_metal_addresses() { assert!(BufferAddress::addressed(records_address(0) - BufferAddress::GUEST_OFFSET).is_err()); assert!(BufferAddress::addressed(records_address(1)).is_err()); } + +/// A kernel case of buffers and threadgroup memory, dispatched by threads and observing a buffer. +fn plain_kernel() -> ComputeCase { + ComputeCase { + out_of_bounds: Vec::new(), + creation_bound: crate::budgets::PIPELINE_CREATION_CEILING, + entry: "main".into(), + constants: FunctionConstantValues::defaults(), + buffers: BTreeMap::from([(0, vec![0; 4]), (1, vec![0; 16])]), + rate_maps: BTreeMap::new(), + argument_buffer_buffers: BTreeMap::new(), + argument_buffer_rate_maps: BTreeMap::new(), + argument_buffer_textures: BTreeMap::new(), + argument_buffer_samplers: BTreeMap::new(), + objects: BTreeMap::new(), + command_buffers: BTreeMap::new(), + textures: BTreeMap::new(), + samplers: BTreeMap::new(), + function_tables: BTreeMap::new(), + acceleration_structures: BTreeMap::new(), + threadgroup_lengths: BTreeMap::from([(0, 64)]), + imageblock: None, + tile: None, + stage_input: None, + stage_in_region: None, + attribute_strides: Default::default(), + dispatch: Dispatch::Threads { + threads: [5, 1, 1], + threads_per_group: [2, 1, 1], + }, + output: ComputeOutput::Buffer { + binding: 0, + offset: 0, + length: 4, + }, + } +} + +/// The runtime runs a kernel case of buffers, threadgroup memory and constants, dispatched by +/// threads or threadgroups and observing a buffer or nothing; a case with anything else (a +/// pipeline state in an argument buffer, an explicit imageblock, an indirect dispatch, a texture +/// output) stays on the executor's own context. +#[test] +fn a_plain_kernel_case_and_only_one_runs_through_the_runtime() { + let authored = kernel_case(); + let plain = plain_kernel(); + assert!(runs_through_runtime(&authored, &plain)); + let groups = ComputeCase { + dispatch: Dispatch::Threadgroups { + groups: [2, 1, 1], + threads_per_group: [2, 1, 1], + }, + output: ComputeOutput::None, + ..plain.clone() + }; + assert!(runs_through_runtime(&authored, &groups)); + let mut object = plain.clone(); + object.objects.insert((1, 0), 7); + let others = [ + object, + ComputeCase { + imageblock: Some([8, 8]), + ..plain.clone() + }, + ComputeCase { + dispatch: replay_dispatch([2, 1, 1]), + ..plain.clone() + }, + ComputeCase { + output: ComputeOutput::Texture { + binding: 0, + origin: [0; 3], + dimensions: [1; 3], + }, + ..plain.clone() + }, + ]; + for other in &others { + assert!(!runs_through_runtime(&authored, other), "{other:?}"); + } +} diff --git a/crates/metal2vulkan-validation/src/candidate/platform.rs b/crates/metal2vulkan-validation/src/candidate/platform.rs index 0e0b909c8..b34318004 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform.rs @@ -15,6 +15,7 @@ mod pipeline; mod plan_resources; mod profiles; mod render; +mod runtime; mod runtime_probe; mod sparse_images; pub use acceptance::create_acceptance_pipeline; @@ -25,6 +26,7 @@ pub use device::{capture_formats, echo_validation_messages, venue_check}; pub use device::{requested_leg, run_robustness_off}; pub use profiles::{requested_restriction, restrict_devices_to}; pub use render::execute_engine_render; +pub use runtime::execute_runtime; pub use runtime_probe::probe_runtime; /// Whether the profiles layer can present committed profile `stem` ([`profiles::presentable`]). diff --git a/crates/metal2vulkan-validation/src/candidate/platform/compute.rs b/crates/metal2vulkan-validation/src/candidate/platform/compute.rs index 2765d4884..f499fba55 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/compute.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/compute.rs @@ -356,10 +356,10 @@ fn run( command_replay(&mut environment, &replayed); Ok(ComputeRun { output, - spv_sha256, + spv_sha256: Some(spv_sha256), translator_fingerprint: engine_fingerprint(device.profile()), environment, - status, + status: Some(status), comparison: census.comparison_class(), census, }) diff --git a/crates/metal2vulkan-validation/src/candidate/platform/render.rs b/crates/metal2vulkan-validation/src/candidate/platform/render.rs index 3a642b8ed..79d06d881 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/render.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/render.rs @@ -250,10 +250,10 @@ fn run( command_replay(&mut environment, &replayed); Ok(ComputeRun { output, - spv_sha256, + spv_sha256: Some(spv_sha256), translator_fingerprint: engine_fingerprint(device.profile()), environment, - status, + status: Some(status), comparison: census.comparison_class(), census, }) diff --git a/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs b/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs new file mode 100644 index 000000000..13b8c8202 --- /dev/null +++ b/crates/metal2vulkan-validation/src/candidate/platform/runtime.rs @@ -0,0 +1,591 @@ +//! The engine compute executor through the runtime (`metal2vulkan-runtime`). +//! +//! A kernel case the engine routes here (`engine::runs_through_runtime`) runs as a consumer runs +//! it, on the runtime's public API alone: its instance, the loader's first physical device of the +//! requested kind (as the executor's own context selects one), a device with the default +//! options, a library and a function from the row's AIR with the case's constants and linked +//! functions, one compute pipeline state, one Shared buffer per bound buffer, and one command +//! buffer of one compute encoder and one dispatch, waited for under the hang protocol, then read +//! back. +//! +//! The process runs it under `VK_LAYER_KHRONOS_validation`, which the loader's and the layer's +//! own variables enable before the instance is made: core and synchronization validation, every +//! message reported, each error and warning written to the process's log, removed once read. A +//! device that lists no active validation tool fails the run; so does any message in the log once +//! the device is gone, as a message fails a row of the executor's own context. +//! +//! The pipeline's make (`new_compute_pipeline_state`) is held to the per-attempt ceilings: its +//! peak live allocations to 500 MiB (`worker::alloc::bounded`: an allocation past it ends the +//! process) and its wall time to 20 s. The driver's creation of its pipelines is held to the +//! case's bound (`budgets::creation_within`). Every pipeline the dispatch runs is made before the +//! submission (`ComputePipelineState::prepare_dispatch`). +//! +//! The row records what the runtime answers: the state's precision notes and the runtime's +//! fingerprint (`engine::runtime_fingerprint`). It records no SPIR-V, status, subgroup shape, +//! containment or artifact: the runtime keeps its modules to itself. Its census's strategies are +//! the float reductions the case's AIR calls (`check::interface::float_reductions`), which bound +//! `PrecisionNote::ReductionOrder` per operation, as the translator's census of the same +//! operations does. + +use crate::candidate::device_facts::{active_tools, ActiveTool, RECORDED_LAYERS}; +use crate::candidate::engine::{ + product_refusal, runtime_fingerprint, select_output, ComputeCase, ComputeRun, RefusedOn, + RunAttempt, RuntimeKernel, +}; +use crate::case::Stage; +use crate::check::admission::ExecutorError; +use crate::coverage::{ExecutedCensus, ExecutionClass, HostClass, Leg, ModuleCensus}; +use crate::gpu::wait::new_runtime::{wait_until_retired, Retired}; +use crate::gpu::wait::{with_submission_label, SubmissionBackend, SubmissionLabel}; +use crate::gpu::DeviceType; +use crate::hash::sha256_bytes; +use crate::observation::TRANSLATOR_FINGERPRINT; +use ash::vk; +use metal2vulkan::bind::Dispatch; +use metal2vulkan::library::Library; +use metal2vulkan::pipeline::{ + ComputePipelineDescriptor, FunctionDescriptor, NumberedSampler, StageSource, +}; +use metal2vulkan_runtime as rt; +use std::collections::BTreeMap; +use std::ffi::CStr; +use std::path::Path; +use std::time::{Duration, Instant}; + +/// The executor a row's environment names. +const EXECUTOR: &str = "runtime-compute"; + +/// The validation layer. +const VALIDATION_LAYER: &str = "VK_LAYER_KHRONOS_validation"; + +/// How long the run waits for the runtime's device to tear down once its last handle is gone, +/// before the validation log is read. +const TEARDOWN: Duration = Duration::from_secs(60); + +/// Run `case`, whose kernel and buffers are `kernel`'s, through the runtime on the device of +/// `device_type`, as the module documentation says. Every refusal the runtime types is typed: the +/// translator's refusal of the kernel as the product's ([`product_refusal`]), named with the +/// device it opened. A known gap of the runtime fails the run: the case's structure classified it +/// as one the runtime runs. Every other error, and any validation message, fails it. +pub fn execute_runtime( + device_type: DeviceType, + case_id: &str, + case: &ComputeCase, + kernel: RuntimeKernel<'_>, +) -> RunAttempt { + // One log per process, at one path, so the layer writes this run's messages there whether it + // reads its variables at each instance or once; a log of an earlier run is gone first. + let log = std::env::temp_dir().join(format!( + "metal2vulkan-validation-runtime-{}.log", + std::process::id() + )); + let _ = std::fs::remove_file(&log); + validate_process(&log); + let attempt = match on_device(device_type, case_id, case, &kernel) { + Ok(attempt) => attempt, + Err(error) => RunAttempt::of(Err(ExecutorError::Failed(error))), + }; + let messages = std::fs::read_to_string(&log); + let _ = std::fs::remove_file(&log); + match messages { + Ok(messages) if !messages.trim().is_empty() => { + let ran = match &attempt.result { + Ok(_) => String::new(), + Err(error) => format!(" (the run also failed: {error})"), + }; + RunAttempt::of(Err(ExecutorError::Failed(format!( + "{VALIDATION_LAYER} reported messages; the run is not evidence{ran}: {}", + crate::engine::bounded_detail(&messages) + )))) + } + _ => attempt, + } +} + +/// Enable the validation layer for this process's next instance, through the loader's and the +/// layer's variables (`docs/VALIDATION.md`), its messages logged to `log`: the loader and the +/// layer read them when an instance is made. A device worker makes one instance at a time, on +/// this thread, and no other thread reads the environment. +fn validate_process(log: &Path) { + for (name, value) in [ + ("VK_INSTANCE_LAYERS", VALIDATION_LAYER), + ("VK_KHRONOS_VALIDATION_REPORT_FLAGS", "error,warn"), + ( + "VK_KHRONOS_VALIDATION_DEBUG_ACTION", + "VK_DBG_LAYER_ACTION_LOG_MSG", + ), + ("VK_KHRONOS_VALIDATION_VALIDATE_SYNC", "true"), + ("VK_KHRONOS_VALIDATION_ENABLE_MESSAGE_LIMIT", "false"), + ] { + std::env::set_var(name, value); + } + std::env::set_var("VK_KHRONOS_VALIDATION_LOG_FILENAME", log); +} + +/// The run on the device of `device_type`, every object of it gone before this returns, and the +/// runtime's device torn down. `Err` where no device of the kind opens under the layer. +fn on_device( + device_type: DeviceType, + case_id: &str, + case: &ComputeCase, + kernel: &RuntimeKernel<'_>, +) -> Result { + if device_type == DeviceType::Gpu { + crate::gpu::tripwire::refuse_if_tripped()?; + } + let instance = + rt::Instance::new(&[]).map_err(|error| format!("the runtime's instance: {error}"))?; + let attempt = { + let (physical, identity) = select(&instance, device_type)?; + let (entry, vk_instance) = instance.raw(); + // SAFETY: `physical` is one of the instance's physical devices, and the instance is live. + let tools = unsafe { active_tools(entry, vk_instance, physical.raw()) }?; + if !tools.iter().any(|tool| tool.layer == VALIDATION_LAYER) { + return Err(format!( + "{} lists no active validation tool: the loader found no {VALIDATION_LAYER}, and \ + a run never proceeds without it", + identity.device + )); + } + let environment = environment(&identity, &tools); + let device = metal2vulkan_runtime::Device::new(&physical, rt::DeviceOptions::default()) + .map_err(|error| format!("the runtime's device on {}: {error}", identity.device))?; + let result = run( + &device, + device_type, + case_id, + case, + kernel, + &identity, + &environment, + ); + let refused_on = matches!(result, Err(ExecutorError::NotSupported(_))).then(|| RefusedOn { + environment: environment.clone(), + translator_fingerprint: runtime_fingerprint(), + artifact: None, + }); + RunAttempt { result, refused_on } + }; + if !instance.wait_until_devices_torn_down(TEARDOWN) { + return Err(format!( + "the runtime's device did not tear down within {} s", + TEARDOWN.as_secs() + )); + } + Ok(attempt) +} + +/// What a row records of the device that ran it. +struct Identity { + device: String, + device_id: u32, + vendor_id: u32, + driver_version: u32, + api_version: u32, + device_type: vk::PhysicalDeviceType, + driver_id: i32, + driver_name: String, + driver_info: String, +} + +/// The loader's first physical device of `device_type`'s kind, as the executor's own context +/// selects one: a CPU implementation for a CPU run, a discrete, integrated or virtual GPU for a +/// GPU run, never one for the other. +fn select( + instance: &rt::Instance, + device_type: DeviceType, +) -> Result<(rt::PhysicalDevice, Identity), String> { + let (_, vk_instance) = instance.raw(); + let physical_devices = instance + .physical_devices() + .map_err(|error| format!("the runtime's physical devices: {error}"))?; + for physical in physical_devices { + let mut driver = vk::PhysicalDeviceDriverProperties::default(); + let mut properties = vk::PhysicalDeviceProperties2::default().push_next(&mut driver); + // SAFETY: `physical` is one of the instance's physical devices, the instance is live and + // at the floor's version, which has `vkGetPhysicalDeviceProperties2`. + unsafe { vk_instance.get_physical_device_properties2(physical.raw(), &mut properties) }; + let device = properties.properties; + let text = |name: Result<&CStr, std::ffi::FromBytesUntilNulError>| { + name.map_or_else( + |_| String::new(), + |name| name.to_string_lossy().into_owned(), + ) + }; + let kind = match device_type { + DeviceType::Cpu => device.device_type == vk::PhysicalDeviceType::CPU, + DeviceType::Gpu => matches!( + device.device_type, + vk::PhysicalDeviceType::DISCRETE_GPU + | vk::PhysicalDeviceType::INTEGRATED_GPU + | vk::PhysicalDeviceType::VIRTUAL_GPU + ), + }; + if !kind { + continue; + } + let identity = Identity { + device: text(device.device_name_as_c_str()), + device_id: device.device_id, + vendor_id: device.vendor_id, + driver_version: device.driver_version, + api_version: device.api_version, + device_type: device.device_type, + driver_id: driver.driver_id.as_raw(), + driver_name: text(driver.driver_name_as_c_str()), + driver_info: text(driver.driver_info_as_c_str()), + }; + return Ok((physical, identity)); + } + Err(format!( + "no {device_type:?} device: the runtime's instance lists none of that kind, and another \ + kind is never substituted" + )) +} + +/// The environment of a row on the device `identity` names, with the tools active on it: its +/// identity as the executor's own context records it, the executor, the validation it ran under, +/// no profiles-layer restriction, and the stated leg. +fn environment(identity: &Identity, tools: &[ActiveTool]) -> serde_json::Value { + serde_json::json!({ + "device": identity.device, + "device_id": identity.device_id, + "vendor_id": identity.vendor_id, + "driver_version": identity.driver_version, + "api_version": identity.api_version, + "driver_id": identity.driver_id, + "driver_name": identity.driver_name, + "driver_info": identity.driver_info, + "architecture": std::env::consts::ARCH, + "os": std::env::consts::OS, + "tools": tools, + "executor": EXECUTOR, + "layers": RECORDED_LAYERS, + "synchronization_validation": true, + "profiles_layer": null, + "robustness": {"leg": Leg::Stated}, + }) +} + +/// The runtime's `error` as the executor's: the translator's refusal as the product's, every +/// other error a failure ([`execute_runtime`]). +fn runtime_error(what: &str, error: rt::Error) -> ExecutorError { + match error { + rt::Error::Translation(error) => product_refusal(&error), + rt::Error::Unsupported(gap) => ExecutorError::Failed(format!( + "{what}: the runtime refused a case its structure classifies as one it runs \ + ({gap:?})" + )), + error => ExecutorError::Failed(format!("{what}: {error}")), + } +} + +/// Make `case`'s pipeline state on `device`, bind its buffers, dispatch it once, wait, and read +/// its output back. +fn run( + device: &rt::Device, + device_type: DeviceType, + case_id: &str, + case: &ComputeCase, + kernel: &RuntimeKernel<'_>, + identity: &Identity, + environment: &serde_json::Value, +) -> Result { + // Each constexpr sampler the kernel numbers takes an index of the device's sampler range, + // one per state words, as Metal gives equal samplers one ID; a read's or a write's takes + // nothing at its index. + let range = rt::IndexClass::Sampler.range(); + let _grant = device + .grant_indices( + rt::IndexClass::Sampler, + range.start, + range.end - range.start, + ) + .map_err(|error| runtime_error("grant the sampler indices", error))?; + let descriptor = descriptor(case, kernel)?; + let (threads_per_group, dispatch) = match case.dispatch { + Dispatch::Threads { + threads, + threads_per_group, + } => (threads_per_group, rt::Dispatch::Threads(threads)), + Dispatch::Threadgroups { + groups, + threads_per_group, + } => (threads_per_group, rt::Dispatch::Threadgroups(groups)), + other => { + return Err(ExecutorError::Failed(format!( + "a run through the runtime dispatches by threads or threadgroups, not {other:?}" + ))) + } + }; + let lengths: Vec<(u32, u32)> = case + .threadgroup_lengths + .iter() + .map(|(&index, &length)| (index, length)) + .collect(); + let before = device.counters().metrics().pipeline_creation_nanos; + let state = make(device, &descriptor)?; + // Every pipeline the dispatch runs, made before anything is submitted. + state.prepare_dispatch(dispatch, threads_per_group, &lengths); + let created = device + .counters() + .metrics() + .pipeline_creation_nanos + .saturating_sub(before); + crate::budgets::creation_within( + "the case's pipelines", + Duration::from_nanos(created), + case.creation_bound, + ) + .map_err(ExecutorError::Failed)?; + let buffers = kernel + .buffers + .iter() + .map(|(&index, bytes)| Ok((index, Placed::new(device, index, bytes)?))) + .collect::, ExecutorError>>()?; + let label = SubmissionLabel { + case_id: case_id.into(), + module_sha256: sha256_bytes(kernel.bitcode), + }; + with_submission_label(label, || { + dispatched( + device, + device_type, + &state, + &buffers, + case, + dispatch, + threads_per_group, + ) + })?; + let finals = buffers + .iter() + .map(|(&index, placed)| (index, placed.bytes())) + .collect::>>(); + // A run through the runtime binds no argument buffer, texture or attachment. + let output = select_output( + case.output, + &finals, + &BTreeMap::new(), + &BTreeMap::new(), + &BTreeMap::new(), + &BTreeMap::new(), + ) + .map_err(ExecutorError::Failed)?; + let census = ExecutedCensus { + out_of_bounds: None, + rate_map_pass: None, + device: Some(match identity.device_type { + vk::PhysicalDeviceType::CPU => ExecutionClass::CpuIcd, + _ => ExecutionClass::Host(HostClass(metal2vulkan::vk::DriverId::from_raw( + identity.driver_id, + ))), + }), + product: TRANSLATOR_FINGERPRINT.into(), + restricted_to: None, + leg: Some(Leg::Stated), + modules: vec![ModuleCensus { + stage: Stage::Kernel, + subgroup: None, + strategies: kernel + .reductions + .iter() + .map(|&name| name.to_owned()) + .collect(), + precision: state.precision_notes().into_iter().collect(), + containment: None, + }], + artifact: None, + }; + Ok(ComputeRun { + output, + spv_sha256: None, + translator_fingerprint: runtime_fingerprint(), + environment: environment.clone(), + status: None, + comparison: census.comparison_class(), + census, + }) +} + +/// The case's `MTLComputePipelineDescriptor` as the Metal oracle makes it +/// (`metal::platform::pipelines`): its kernel from the row's library, specialized with the case's +/// constants (`newFunctionWithName:constantValues:`), linking each function of the modules it +/// links, each made with the same constants (`acceptance::linked_functions`). +fn descriptor( + case: &ComputeCase, + kernel: &RuntimeKernel<'_>, +) -> Result { + let function = Library::from_air(kernel.bitcode) + .and_then(|library| library.function(&case.entry)) + .map_err(|error| product_refusal(&error))?; + let libraries: Vec<&[u8]> = kernel + .linked + .iter() + .map(|module| module.bitcode.as_slice()) + .collect(); + let linked: Vec = kernel + .linked + .iter() + .map(|module| module.library.clone()) + .collect(); + let (linked, _) = crate::acceptance::linked_functions(&libraries, &linked, &case.constants) + .map_err(|error| product_refusal(&error))?; + let mut function = FunctionDescriptor::new(function) + .with_specialized(true) + .with_linked(linked); + function.constants = case.constants.clone(); + Ok(ComputePipelineDescriptor::new(StageSource::Function( + function, + ))) +} + +/// `descriptor`'s state on `device`, made within the per-attempt ceilings: its peak live +/// allocations within 500 MiB (an allocation past it ends the process), its wall time within +/// 20 s. +fn make( + device: &rt::Device, + descriptor: &ComputePipelineDescriptor, +) -> Result { + if !crate::worker::alloc::installed() { + return Err(ExecutorError::Failed( + "the counting allocator is not installed: the pipeline's make cannot be held to its \ + memory ceiling" + .into(), + )); + } + let mut constexprs: BTreeMap<[u64; 2], u32> = BTreeMap::new(); + let first = rt::IndexClass::Sampler.range().start; + let numbered = |samplers: &[NumberedSampler]| { + let ids = samplers.iter().map(|sampler| match sampler { + NumberedSampler::Constexpr(words) => { + let next = first + constexprs.len() as u32; + *constexprs.entry(*words).or_insert(next) + } + NumberedSampler::Read | NumberedSampler::Write => 0, + }); + Ok(ids.collect()) + }; + let started = Instant::now(); + let (made, peak) = crate::worker::alloc::bounded(crate::worker::MEMORY_LIMIT_BYTES, || { + device.new_compute_pipeline_state(descriptor, numbered) + }); + let took = started.elapsed(); + if took > crate::worker::DEADLINE { + return Err(ExecutorError::Failed(format!( + "the pipeline's make took {} ms, past the {} s ceiling (peak live allocations {} \ + bytes)", + took.as_millis(), + crate::worker::DEADLINE.as_secs(), + peak.unwrap_or(0) + ))); + } + made.map_err(|error| runtime_error("the pipeline's make", error)) +} + +/// A buffer of the run: a Shared block of its own, and the buffer over it holding the bytes. +struct Placed { + buffer: rt::Buffer, + _block: rt::Block, +} + +impl Placed { + /// A Shared buffer holding `bytes`, bound at Metal index `index`. + fn new(device: &rt::Device, index: u32, bytes: &[u8]) -> Result { + let what = format!("buffer {index}"); + let length = bytes.len() as u64; + let block = device + .take_block(rt::MemoryClass::Shared, length) + .map_err(|error| runtime_error(&what, error))?; + // Every byte is written below. + let buffer = device + .new_buffer(block.id, 0, length, None) + .map_err(|error| runtime_error(&what, error))?; + let contents = buffer + .contents() + .ok_or_else(|| ExecutorError::Failed(format!("{what} has no contents")))?; + // SAFETY: a Shared buffer's contents are its `length` bytes, mapped while it lives, and + // nothing else writes them: no work names it yet. + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), contents.as_ptr(), bytes.len()); + } + Ok(Placed { + buffer, + _block: block, + }) + } + + /// Its bytes now. + fn bytes(&self) -> Vec { + let length = self.buffer.length() as usize; + match self.buffer.contents() { + // SAFETY: as in `new`; the work that named it has retired. + Some(contents) => { + unsafe { std::slice::from_raw_parts(contents.as_ptr(), length) }.to_vec() + } + None => Vec::new(), + } + } +} + +/// Encode `case`'s dispatch of `state` over `buffers` in one command buffer, commit it and wait +/// until it has retired, under the hang protocol; a command buffer that did not complete fails +/// the run. +fn dispatched( + device: &rt::Device, + device_type: DeviceType, + state: &rt::ComputePipelineState, + buffers: &BTreeMap, + case: &ComputeCase, + dispatch: rt::Dispatch, + threads_per_group: [u32; 3], +) -> Result<(), ExecutorError> { + let fail = |what: &'static str| move |error: rt::Error| runtime_error(what, error); + let queue = device.new_command_queue(1).map_err(fail("the queue"))?; + let command_buffer = queue.command_buffer().map_err(fail("the command buffer"))?; + let retired = Retired::watch(&command_buffer).map_err(fail("the completed handler"))?; + let mut encoder = command_buffer + .compute_command_encoder(rt::DispatchType::Serial) + .map_err(fail("the compute encoder"))?; + encoder + .set_compute_pipeline_state(state) + .map_err(fail("the pipeline state"))?; + for (&index, placed) in buffers { + encoder + .set_buffer(Some(&placed.buffer), 0, index) + .map_err(fail("a buffer"))?; + } + for (&index, &length) in &case.threadgroup_lengths { + encoder + .set_threadgroup_memory_length(length, index) + .map_err(fail("a threadgroup memory length"))?; + } + match dispatch { + rt::Dispatch::Threads(threads) => encoder.dispatch_threads(threads, threads_per_group), + rt::Dispatch::Threadgroups(groups) => { + encoder.dispatch_threadgroups(groups, threads_per_group) + } + rt::Dispatch::Indirect => { + return Err(ExecutorError::Failed( + "a run through the runtime dispatches by threads or threadgroups".into(), + )) + } + } + .map_err(fail("the dispatch"))?; + encoder.end_encoding(); + command_buffer.commit().map_err(fail("the commit"))?; + wait_until_retired( + &queue, + &command_buffer, + &retired, + SubmissionBackend::vulkan(device_type), + "a dispatch through the runtime", + ); + match command_buffer.status() { + rt::CommandBufferStatus::Completed => Ok(()), + status => Err(ExecutorError::Failed(format!( + "the command buffer ended {status:?}: {:?}", + command_buffer.error() + ))), + } +} diff --git a/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs b/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs index b46bfbc33..93395fc1b 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/engine_compute.rs @@ -103,7 +103,10 @@ fn a_store_runs_through_the_binder_under_the_validation_layer() { let mut expected = vec![0xab; 8]; expected[..4].copy_from_slice(&42u32.to_le_bytes()); assert_eq!(run.output, expected); - assert_eq!(run.status, metal2vulkan::bind::StatusReport::default()); + assert_eq!( + run.status, + Some(metal2vulkan::bind::StatusReport::default()) + ); assert_eq!(run.environment["executor"], "engine-compute"); assert_eq!(run.translator_fingerprint.len(), 64); } @@ -498,3 +501,107 @@ fn an_oracle_instance_mask_is_refused_typed() { other => panic!("{other:?}"), } } + +/// [`run_linked`] through the runtime (`platform::execute_runtime`): the kernel and the modules it +/// links as the engine hands them over, its buffers as the case holds them, and no float +/// reduction. +#[cfg(target_os = "linux")] +fn run_on_runtime( + case: &ComputeCase, + bitcode: &[u8], + linked: &[LinkedModule], +) -> Result { + platform::execute_runtime( + crate::gpu::TEST_DEVICE, + "engine-test", + case, + crate::candidate::engine::RuntimeKernel { + bitcode, + linked, + buffers: &case.buffers, + reductions: &std::collections::BTreeSet::new(), + }, + ) + .result +} + +/// A store runs through the runtime under the validation layer, and its row records what the +/// runtime answers: the state's precision notes and the runtime's fingerprint, and no SPIR-V, +/// status, subgroup shape, containment or artifact. +#[cfg(target_os = "linux")] +#[test] +fn a_store_runs_through_the_runtime_under_the_validation_layer() { + let bitcode = llvm_assemble(&engine_dir().join("store_const.ll")).unwrap(); + let run = run_on_runtime( + &case("store_const", vec![0xab; 8], one_thread()), + &bitcode, + &[], + ) + .unwrap(); + let mut expected = vec![0xab; 8]; + expected[..4].copy_from_slice(&42u32.to_le_bytes()); + assert_eq!(run.output, expected); + assert_eq!(run.environment["executor"], "runtime-compute"); + assert_eq!( + run.translator_fingerprint, + crate::candidate::engine::runtime_fingerprint() + ); + assert_eq!((run.spv_sha256, run.status), (None, None)); + let [module] = &run.census.modules[..] else { + panic!("one module: {:?}", run.census.modules); + }; + assert_eq!((module.subgroup, module.containment), (None, None)); + assert_eq!(run.census.artifact, None); + assert_eq!(run.census.leg, Some(crate::coverage::Leg::Stated)); +} + +/// A kernel that calls visible functions it does not define runs through the runtime with the +/// functions its case links, as [`a_kernel_runs_with_its_linked_visible_functions`] runs it on the +/// executor's own context. +#[cfg(target_os = "linux")] +#[test] +fn a_kernel_runs_through_the_runtime_with_its_linked_visible_functions() { + let caller = llvm_assemble(&engine_dir().join("linked_visible_caller.ll")).unwrap(); + let functions = llvm_assemble(&engine_dir().join("linked_visible_functions.ll")).unwrap(); + let names = |names: &[&str]| LinkedLibrary { + functions: names.iter().map(|name| (*name).to_owned()).collect(), + }; + let linked = [ + LinkedModule { + module_sha256: "functions".into(), + bitcode: functions, + library: names(&["linked_blend", "linked_scale"]), + }, + LinkedModule { + module_sha256: "caller".into(), + bitcode: caller.clone(), + library: names(&["linked_offset"]), + }, + ]; + const THREADS: u32 = 16; + let bytes = vec![0; 4 * THREADS as usize]; + let mut kernel = case( + "linked_visible_caller", + bytes.clone(), + Dispatch::Threads { + threads: [THREADS, 1, 1], + threads_per_group: [THREADS, 1, 1], + }, + ); + kernel.buffers.insert(1, bytes.clone()); + let words = run_on_runtime(&kernel, &caller, &linked).unwrap().output; + let expected = (0..THREADS) + .flat_map(|tid| (3 * tid + (tid & 7)).to_le_bytes()) + .collect::>(); + assert_eq!(words, expected); + kernel.output = ComputeOutput::Buffer { + binding: 1, + offset: 0, + length: bytes.len() as u64, + }; + let floats = run_on_runtime(&kernel, &caller, &linked).unwrap().output; + let expected = (0..THREADS) + .flat_map(|tid| (tid as f32 * 0.5 + 1.0).to_le_bytes()) + .collect::>(); + assert_eq!(floats, expected); +} diff --git a/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs b/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs index e40634a80..2cbe114c2 100644 --- a/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs +++ b/crates/metal2vulkan-validation/src/candidate/tests/engine_render.rs @@ -142,7 +142,10 @@ fn a_constant_fragment_colors_the_quadrant_metal_draws() { ) .unwrap(); assert_eq!(run.output, top_right([0.25, 0.5, 0.75, 1.0])); - assert_eq!(run.status, metal2vulkan::bind::StatusReport::default()); + assert_eq!( + run.status, + Some(metal2vulkan::bind::StatusReport::default()) + ); assert_eq!(run.environment["executor"], "engine-render"); } @@ -226,7 +229,10 @@ fn a_fragment_case_draws_through_its_generated_passthrough_vertex() { .flat_map(|&v| centers.iter().flat_map(move |&u| [u, v, 0.5, 1.0])) .collect(); assert_eq!(run.output, floats(&expected)); - assert_eq!(run.status, metal2vulkan::bind::StatusReport::default()); + assert_eq!( + run.status, + Some(metal2vulkan::bind::StatusReport::default()) + ); } /// A fragment case with a depth/stencil attachment: `fragment_depth_stencil` writes depth 0.5 under @@ -276,7 +282,10 @@ fn a_fragment_case_writes_its_depth_and_stencil_attachment() { ) .unwrap(); assert_eq!(run.output, expected, "{:?}", authored.output); - assert_eq!(run.status, metal2vulkan::bind::StatusReport::default()); + assert_eq!( + run.status, + Some(metal2vulkan::bind::StatusReport::default()) + ); } } @@ -500,7 +509,10 @@ fn a_framebuffer_fetch_halves_its_attachment_once_per_overlapping_instance() { eprintln!( "ENGINE-FETCH {instances} instance(s): unordered within the draw: {unordered}" ); - assert_eq!(run.status, metal2vulkan::bind::StatusReport::default()); + assert_eq!( + run.status, + Some(metal2vulkan::bind::StatusReport::default()) + ); } Err(other) => panic!("{instances} instance(s): {other}"), } @@ -574,7 +586,10 @@ fn an_imageblock_member_gains_one_per_overlapping_instance() { ) { Ok(run) => { assert_eq!(run.output, expected, "{instances} instance(s)"); - assert_eq!(run.status, metal2vulkan::bind::StatusReport::default()); + assert_eq!( + run.status, + Some(metal2vulkan::bind::StatusReport::default()) + ); } Err(ExecutorError::NotSupported(NotSupported::Product { outcome: Outcome::DeviceCapabilityMissing { feature, .. }, diff --git a/crates/metal2vulkan-validation/src/check/interface.rs b/crates/metal2vulkan-validation/src/check/interface.rs index ea3715f75..29c035a30 100644 --- a/crates/metal2vulkan-validation/src/check/interface.rs +++ b/crates/metal2vulkan-validation/src/check/interface.rs @@ -321,6 +321,9 @@ pub struct AirInterface { /// How far a kernel entry's every thread accesses each buffer at the element its grid /// position names ([`GridReach`](super::grid_reach::GridReach)); empty for other stages. pub grid_reaches: Vec, + /// 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>, } /// How an entry reads its `[[vertex_id]]` argument. An indexed draw's index read past its buffer is @@ -443,6 +446,7 @@ impl AirInterface { thread_objects: Vec::new(), vertex_id: VertexIdUse::Unused, grid_reaches, + float_reductions: float_reductions(module, [ep.func]), }; interface.vertex_id = vertex_id_use(module, ep.func, &interface.params); Uses::scan(module, ep.func)?.record(&mut interface); @@ -1586,6 +1590,88 @@ impl<'m> Uses<'m> { } } +/// The simdgroup float sums and products (`air.simd_sum`, `air.simd_product`, and their prefix +/// forms, of a `half` or `float` type) that `roots` and every function they call directly in +/// `module`, transitively, call: each by the name the translator's strategy census gives the +/// operation (`simd.reduce.fadd.float`, `simd.scan.fmul.half`, ...), the names +/// [`REDUCTIONS`](crate::observation_contract::REDUCTIONS) bounds. A float sum's or +/// product's association order is the device's (`PrecisionNote::ReductionOrder`), so these are +/// the operations that note is recorded for: a comparison of a run whose modules the executor +/// cannot read (a run through the runtime) bounds each by its own operation, read from the AIR. +/// A quad's operations, which run in Metal's order, are not among them. +pub fn float_reductions( + module: &Module, + roots: impl IntoIterator, +) -> BTreeSet<&'static str> { + use metal2vulkan_air::intrinsics::{Elem, GroupOp as G, GroupScope}; + let mut found = BTreeSet::new(); + let mut pending: Vec = roots.into_iter().collect(); + let mut seen: BTreeSet = pending.iter().copied().collect(); + while let Some(func) = pending.pop() { + let Some(body) = module.func(func).and_then(|f| f.body.as_ref()) else { + continue; + }; + for (block, _) in body.blocks.iter() { + for (_, inst) in body.block_insts(block) { + let InstKind::Call(call) = &inst.kind else { + continue; + }; + let group = match &call.callee { + &Callee::Direct(callee) => { + if seen.insert(callee) { + pending.push(callee); + } + continue; + } + &Callee::Air { + op: AirIntrinsic::Group(group), + .. + } => group, + _ => continue, + }; + if group.scope != GroupScope::Simdgroup { + continue; + } + let format = match group.ty.map(|ty| ty.elem) { + Some(Elem::F16) => "half", + Some(Elem::F32) => "float", + _ => continue, + }; + let operation = match group.op { + G::Sum => "reduce.fadd", + G::Product => "reduce.fmul", + G::PrefixInclusiveSum | G::PrefixExclusiveSum => "scan.fadd", + G::PrefixInclusiveProduct | G::PrefixExclusiveProduct => "scan.fmul", + _ => continue, + }; + if let Some(&(name, ..)) = crate::observation_contract::REDUCTIONS + .iter() + .find(|(name, ..)| *name == format!("simd.{operation}.{format}")) + { + found.insert(name); + } + } + } + } + found +} + +/// The functions of `module` whose names are `names`, in `module`'s order: the roots of +/// [`float_reductions`] in a module a case links functions from. +pub fn functions_named<'m>( + module: &'m Module, + names: &'m [String], +) -> impl Iterator + 'm { + module + .parts() + .funcs + .iter() + .filter_map(move |(id, function)| { + let name = module.symbols().as_str(function.name)?; + names.iter().any(|wanted| wanted == name).then_some(id) + }) +} + /// How `entry` reads the arguments of `params` whose role is `[[vertex_id]]` ([`VertexIdUse`]). fn vertex_id_use(module: &Module, entry: FuncId, params: &[Param]) -> VertexIdUse { use metal2vulkan_air::abi::Builtin; @@ -1693,6 +1779,7 @@ impl AirInterface { thread_objects: Vec::new(), vertex_id: VertexIdUse::Unused, grid_reaches: Vec::new(), + float_reductions: BTreeSet::new(), } } } diff --git a/crates/metal2vulkan-validation/src/check/interface/tests.rs b/crates/metal2vulkan-validation/src/check/interface/tests.rs index 97801dafb..de3fba9d5 100644 --- a/crates/metal2vulkan-validation/src/check/interface/tests.rs +++ b/crates/metal2vulkan-validation/src/check/interface/tests.rs @@ -488,3 +488,40 @@ fn object_roles_bind_their_slots() { ); assert_eq!(interface.params[0].slots(), Some((3, 1))); } + +/// An entry's float reductions are the simdgroup float sums and products it calls, by the names +/// the translator's strategy census gives them: a product's and a prefix product's of `float` +/// and of `half` (their vector forms among them), a sum's and a prefix sum's. An integer one, +/// and a quad's, is none. +#[test] +fn an_entrys_float_reductions_are_its_simdgroup_float_sums_and_products() { + let reductions = |ll: &str, entry: &str| { + of_text(ll, entry, &BTreeMap::new()) + .unwrap() + .float_reductions + }; + let products = fixture("engine/gsm2_simd_products.ll"); + assert_eq!( + reductions(&products, "simd_float_products"), + BTreeSet::from(["simd.reduce.fmul.float", "simd.scan.fmul.float"]) + ); + assert_eq!( + reductions(&products, "simd_half_products"), + BTreeSet::from(["simd.reduce.fmul.half", "simd.scan.fmul.half"]) + ); + assert!(reductions(&products, "simd_int_products").is_empty()); + let ops = fixture("engine/simd_ops.ll"); + assert_eq!( + reductions(&ops, "simd_sum_k"), + BTreeSet::from(["simd.reduce.fadd.float"]) + ); + assert_eq!( + reductions(&ops, "simd_half_sum_k"), + BTreeSet::from(["simd.reduce.fadd.half"]) + ); + assert_eq!( + reductions(&ops, "simd_float_prefix_k"), + BTreeSet::from(["simd.scan.fadd.float"]) + ); + assert!(reductions(&ops, "quad_ops_k").is_empty()); +} diff --git a/crates/metal2vulkan-validation/src/coverage.rs b/crates/metal2vulkan-validation/src/coverage.rs index 2fee45f52..e68ce938b 100644 --- a/crates/metal2vulkan-validation/src/coverage.rs +++ b/crates/metal2vulkan-validation/src/coverage.rs @@ -261,8 +261,14 @@ impl Declared { #[serde(deny_unknown_fields)] pub struct ModuleCensus { pub stage: Stage, - pub subgroup: SubgroupShape, - /// `StrategyCensus` names. + /// The module's subgroup shape, where the executor compiled it itself: `None` for a run + /// through the runtime, which keeps its modules to itself. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subgroup: Option, + /// `StrategyCensus` names. A run through the runtime, which keeps the translator's census of + /// its modules to itself, records only the float sums and products the case's AIR calls, + /// under the names the translator's census gives them + /// (`check::interface::float_reductions`): what its comparison class is derived from. pub strategies: BTreeSet, /// The module's precision notes: with `strategies`, what its observations' comparison class /// is derived from. An executed module's are its notes under the specialization it ran with and @@ -300,7 +306,7 @@ impl ModuleCensus { .map(|(_, stage)| stage)?; Some(ModuleCensus { stage, - subgroup: SubgroupShape::of_stage_module(module), + subgroup: Some(SubgroupShape::of_stage_module(module)), strategies: module.strategies.entries.keys().cloned().collect(), precision: match plan { Some(plan) => module diff --git a/crates/metal2vulkan-validation/src/coverage/tests.rs b/crates/metal2vulkan-validation/src/coverage/tests.rs index b9236aa60..1b46d39e4 100644 --- a/crates/metal2vulkan-validation/src/coverage/tests.rs +++ b/crates/metal2vulkan-validation/src/coverage/tests.rs @@ -31,7 +31,7 @@ const ROBUST: Containment = Containment { fn module(stage: Stage, subgroup: SubgroupShape, strategies: &[&str]) -> ModuleCensus { ModuleCensus { stage, - subgroup, + subgroup: Some(subgroup), strategies: strategies.iter().map(|name| name.to_string()).collect(), precision: BTreeSet::new(), containment: Some(ROBUST), diff --git a/crates/metal2vulkan-validation/src/coverage/tier_table.rs b/crates/metal2vulkan-validation/src/coverage/tier_table.rs index 00880f979..18b62caa5 100644 --- a/crates/metal2vulkan-validation/src/coverage/tier_table.rs +++ b/crates/metal2vulkan-validation/src/coverage/tier_table.rs @@ -280,10 +280,10 @@ pub fn compile_module( Ok(CompiledModule { census: ModuleCensus { stage, - subgroup: SubgroupShape { + subgroup: Some(SubgroupShape { required_size: function.required_subgroup_size(), full_subgroups: function.requires_full_subgroups(), - }, + }), strategies: function.strategies().entries.keys().cloned().collect(), precision: function.precision_notes().iter().copied().collect(), containment: Some(Containment::of_compile(profile, &linked.words)), diff --git a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs index 910af8b45..59475129a 100644 --- a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs +++ b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs @@ -622,7 +622,7 @@ fn candidate_row( air_sha256: metal.air_sha256.clone(), input_sha256: metal.input_sha256.clone(), golden_output_sha256: metal.metal_output_sha256.clone(), - spv_sha256: SPV_SHA256.into(), + spv_sha256: Some(SPV_SHA256.into()), translator_fingerprint: TRANSLATOR.into(), candidate_output_sha256: crate::hash::sha256_bytes(output), output_b64: b64(output), @@ -652,7 +652,7 @@ fn dependencies<'a>( crate::observation::CandidateDependencies { case, metal, - spv_sha256: SPV_SHA256, + spv_sha256: Some(SPV_SHA256), translator_fingerprint: TRANSLATOR, backend: crate::observation::Backend::Vulkan, environment_id: "vk-env", diff --git a/crates/metal2vulkan-validation/src/gpu.rs b/crates/metal2vulkan-validation/src/gpu.rs index 10be01688..012b221aa 100644 --- a/crates/metal2vulkan-validation/src/gpu.rs +++ b/crates/metal2vulkan-validation/src/gpu.rs @@ -77,6 +77,8 @@ mod tests { // The runtime's device: the player's and the replay tests'. ("src/bin/command-replay.rs", opens[5], 1), ("src/replay/rt_replay.rs", opens[5], 1), + // The runtime's device: the engine executor's run through it. + ("src/candidate/platform/runtime.rs", opens[5], 1), ]; let checked = concat!("refuse_if", "_tripped("); for (file, open, _) in allowed.iter().filter(|(_, open, _)| *open == opens[5]) { diff --git a/crates/metal2vulkan-validation/src/index.rs b/crates/metal2vulkan-validation/src/index.rs index a02beccfd..ea834c50e 100644 --- a/crates/metal2vulkan-validation/src/index.rs +++ b/crates/metal2vulkan-validation/src/index.rs @@ -1761,7 +1761,7 @@ fn insert_compact_rows( transaction .execute( "INSERT INTO candidate_observations (case_id, backend, environment_id, input_sha256, golden_output_sha256, spv_sha256, translator_fingerprint, executor_abi, status) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", - params![observation.case_id, backend.directory(), observation.environment_id, observation.input_sha256, observation.golden_output_sha256, observation.spv_sha256, observation.translator_fingerprint, observation.executor_abi, format!("{:?}", observation.status).to_ascii_lowercase()], + params![observation.case_id, backend.directory(), observation.environment_id, observation.input_sha256, observation.golden_output_sha256, observation.spv_sha256.as_deref().unwrap_or_default(), observation.translator_fingerprint, observation.executor_abi, format!("{:?}", observation.status).to_ascii_lowercase()], ) .map_err(|error| format!("index {} observation: {error}", backend.directory()))?; } @@ -2144,6 +2144,15 @@ fn engine_translator_fingerprint(environment: &serde_json::Value) -> Option bool { + engine_translator_fingerprint(environment).as_deref() == Some(translator_fingerprint) + || translator_fingerprint == crate::candidate::engine::runtime_fingerprint() +} + /// The digest a lowercase 64-digit hexadecimal SHA-256 spells, or `None` for anything else. fn decode_hash256(hex: &str) -> Option<[u8; 32]> { let digits = hex.as_bytes(); @@ -2277,9 +2286,8 @@ pub(crate) fn candidate_staleness( .census .as_ref() .is_none_or(|census| census.product == crate::observation::TRANSLATOR_FINGERPRINT); - let same_build = census_product - && engine_translator_fingerprint(&candidate.environment).as_deref() - == Some(candidate.translator_fingerprint.as_str()); + let same_build = + census_product && this_build(&candidate.environment, &candidate.translator_fingerprint); let executed = candidate .census .as_ref() @@ -2310,7 +2318,7 @@ pub(crate) fn candidate_staleness( candidate.dependency_matches(&CandidateDependencies { case, metal, - spv_sha256: &candidate.spv_sha256, + spv_sha256: candidate.spv_sha256.as_deref(), translator_fingerprint: &candidate.translator_fingerprint, backend, environment_id: &candidate.environment_id, @@ -2359,8 +2367,7 @@ pub(crate) fn refusal_staleness( ), ( Dependency::Product, - engine_translator_fingerprint(&refusal.environment).as_deref() - == Some(refusal.translator_fingerprint.as_str()) + this_build(&refusal.environment, &refusal.translator_fingerprint) || venues.artifact_is_current( backend, &refusal.environment_id, @@ -2501,7 +2508,7 @@ mod tests { air_sha256: case.air_sha256.clone(), input_sha256, golden_output_sha256: output_sha256.clone(), - spv_sha256: "33".repeat(32), + spv_sha256: Some("33".repeat(32)), translator_fingerprint: engine_fingerprint_of(&[7; 32]), candidate_output_sha256: output_sha256, output_b64: output_b64.into(), diff --git a/crates/metal2vulkan-validation/src/observation.rs b/crates/metal2vulkan-validation/src/observation.rs index cb2632f55..e0cec2995 100644 --- a/crates/metal2vulkan-validation/src/observation.rs +++ b/crates/metal2vulkan-validation/src/observation.rs @@ -13,6 +13,11 @@ use serde::{Deserialize, Serialize}; /// (`candidate::engine::engine_fingerprint`), so a row is current only for this product. pub const TRANSLATOR_FINGERPRINT: &str = env!("METAL2VULKAN_PRODUCT_FINGERPRINT"); +/// The runtime crate's source fingerprint (`metal2vulkan-runtime`'s manifest and the files its +/// module tree compiles, `build.rs`): with [`TRANSLATOR_FINGERPRINT`], what a row the runtime ran +/// is current for (`candidate::engine::runtime_fingerprint`). +pub const RUNTIME_CRATE_FINGERPRINT: &str = env!("METAL2VULKAN_RUNTIME_CRATE_FINGERPRINT"); + /// `VK_LAYER_KHRONOS_profiles`, as an active tool's `layer` names it in a candidate environment's /// `tools`. pub const PROFILES_LAYER: &std::ffi::CStr = c"VK_LAYER_KHRONOS_profiles"; @@ -183,7 +188,10 @@ pub struct CandidateObservation { pub air_sha256: String, pub input_sha256: String, pub golden_output_sha256: String, - pub spv_sha256: String, + /// SHA-256 of the executed SPIR-V, where the executor compiled it itself: `None` for a row + /// the runtime ran, which keeps its modules to itself. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub spv_sha256: Option, pub translator_fingerprint: String, pub candidate_output_sha256: String, pub output_b64: String, @@ -340,7 +348,7 @@ impl MetalObservation { pub struct CandidateDependencies<'a> { pub case: &'a AuthoredCase, pub metal: &'a MetalObservation, - pub spv_sha256: &'a str, + pub spv_sha256: Option<&'a str>, pub translator_fingerprint: &'a str, pub backend: Backend, pub environment_id: &'a str, @@ -354,7 +362,6 @@ impl CandidateObservation { ("air_sha256", self.air_sha256.as_str()), ("input_sha256", self.input_sha256.as_str()), ("golden_output_sha256", self.golden_output_sha256.as_str()), - ("spv_sha256", self.spv_sha256.as_str()), ( "candidate_output_sha256", self.candidate_output_sha256.as_str(), @@ -362,6 +369,9 @@ impl CandidateObservation { ] { validate_hash(field, value)?; } + if let Some(spv_sha256) = &self.spv_sha256 { + validate_hash("spv_sha256", spv_sha256)?; + } validate_hash("translator_fingerprint", &self.translator_fingerprint)?; validate_slot_fields(&self.environment_id, &self.executor_abi)?; if !self.environment.is_object() { @@ -548,7 +558,7 @@ impl CandidateObservation { && self.air_sha256 == dependencies.case.air_sha256 && self.input_sha256 == dependencies.metal.input_sha256 && self.golden_output_sha256 == dependencies.metal.metal_output_sha256 - && self.spv_sha256 == dependencies.spv_sha256 + && self.spv_sha256.as_deref() == dependencies.spv_sha256 && self.translator_fingerprint == dependencies.translator_fingerprint && self.backend == dependencies.backend && self.environment_id == dependencies.environment_id @@ -828,7 +838,7 @@ mod tests { air_sha256: case.air_sha256.clone(), input_sha256, golden_output_sha256: metal.metal_output_sha256.clone(), - spv_sha256: "33".repeat(32), + spv_sha256: Some("33".repeat(32)), translator_fingerprint: "55".repeat(32), candidate_output_sha256: output_sha256, output_b64: metal.output_b64.clone(), @@ -856,7 +866,7 @@ mod tests { let dependencies = CandidateDependencies { case: &case, metal: &metal, - spv_sha256: &spv_sha256, + spv_sha256: Some(&spv_sha256), translator_fingerprint: &candidate.translator_fingerprint, backend: Backend::Vulkan, environment_id: "vk-env", @@ -866,7 +876,7 @@ mod tests { let changed_spv = "44".repeat(32); let changed = CandidateDependencies { - spv_sha256: &changed_spv, + spv_sha256: Some(&changed_spv), ..dependencies }; assert!(!candidate.dependency_matches(&changed)); @@ -921,7 +931,7 @@ mod tests { air_sha256: case.air_sha256.clone(), input_sha256: case.computed_input_sha256().unwrap(), golden_output_sha256: output_sha256.clone(), - spv_sha256: "33".repeat(32), + spv_sha256: Some("33".repeat(32)), translator_fingerprint: "55".repeat(32), candidate_output_sha256: output_sha256, output_b64: "AQAAAA==".into(), @@ -955,7 +965,7 @@ mod tests { air_sha256: case.air_sha256.clone(), input_sha256: case.computed_input_sha256().unwrap(), golden_output_sha256: output_sha256.clone(), - spv_sha256: "33".repeat(32), + spv_sha256: Some("33".repeat(32)), translator_fingerprint: "55".repeat(32), candidate_output_sha256: output_sha256.clone(), output_b64: "AQAAAA==".into(), @@ -1038,7 +1048,7 @@ mod tests { air_sha256: case.air_sha256.clone(), input_sha256: case.computed_input_sha256().unwrap(), golden_output_sha256: output_sha256.clone(), - spv_sha256: "33".repeat(32), + spv_sha256: Some("33".repeat(32)), translator_fingerprint: "55".repeat(32), candidate_output_sha256: output_sha256.clone(), output_b64: "AQAAAA==".into(), @@ -1153,7 +1163,7 @@ mod tests { air_sha256: case.air_sha256, input_sha256, golden_output_sha256: empty_sha256.clone(), - spv_sha256: "33".repeat(32), + spv_sha256: Some("33".repeat(32)), translator_fingerprint: "55".repeat(32), candidate_output_sha256: empty_sha256, output_b64: String::new(), @@ -1239,7 +1249,7 @@ mod tests { air_sha256: case.air_sha256.clone(), input_sha256: metal.input_sha256.clone(), golden_output_sha256: metal.metal_output_sha256.clone(), - spv_sha256: "33".repeat(32), + spv_sha256: Some("33".repeat(32)), translator_fingerprint: "55".repeat(32), candidate_output_sha256: sha256_bytes(output), output_b64: b64(output), @@ -1256,7 +1266,7 @@ mod tests { let dependencies = CandidateDependencies { case: &case, metal: &metal, - spv_sha256: &spv_sha256, + spv_sha256: Some(&spv_sha256), translator_fingerprint: &translator_fingerprint, backend: Backend::Vulkan, environment_id: "vk-env", @@ -1400,7 +1410,7 @@ mod tests { air_sha256: case.air_sha256.clone(), input_sha256: input_sha256.clone(), golden_output_sha256: output_sha256.clone(), - spv_sha256: "33".repeat(32), + spv_sha256: Some("33".repeat(32)), translator_fingerprint: "55".repeat(32), candidate_output_sha256: output_sha256.clone(), output_b64: "AQAAAA==".into(), @@ -1417,7 +1427,7 @@ mod tests { let dependencies = CandidateDependencies { case: &case, metal: &golden, - spv_sha256: &"33".repeat(32), + spv_sha256: Some(&"33".repeat(32)), translator_fingerprint: &"55".repeat(32), backend: Backend::Vulkan, environment_id: "vk-env", diff --git a/crates/metal2vulkan-validation/src/store.rs b/crates/metal2vulkan-validation/src/store.rs index 847b51d82..b74a1083c 100644 --- a/crates/metal2vulkan-validation/src/store.rs +++ b/crates/metal2vulkan-validation/src/store.rs @@ -1478,7 +1478,7 @@ mod tests { air_sha256: case.air_sha256.clone(), input_sha256: case.computed_input_sha256().unwrap(), golden_output_sha256: output_sha256.clone(), - spv_sha256: "33".repeat(32), + spv_sha256: Some("33".repeat(32)), translator_fingerprint: "44".repeat(32), candidate_output_sha256: output_sha256, output_b64: "KgAAAA==".into(), @@ -1887,7 +1887,7 @@ mod tests { let mut candidate = candidate(&case, Backend::Vulkan, "env"); store.upsert_candidate(candidate.clone()).unwrap(); - candidate.spv_sha256 = "44".repeat(32); + candidate.spv_sha256 = Some("44".repeat(32)); store.upsert_candidate(candidate.clone()).unwrap(); assert_eq!( store.read_candidates(Backend::Vulkan).unwrap(), diff --git a/crates/metal2vulkan-validation/src/vulkan_batch/tests.rs b/crates/metal2vulkan-validation/src/vulkan_batch/tests.rs index 834b49d5e..120c26891 100644 --- a/crates/metal2vulkan-validation/src/vulkan_batch/tests.rs +++ b/crates/metal2vulkan-validation/src/vulkan_batch/tests.rs @@ -119,7 +119,7 @@ fn row( air_sha256: case.air_sha256.clone(), input_sha256: case.computed_input_sha256().unwrap(), golden_output_sha256: sha256_bytes(golden), - spv_sha256: "33".repeat(32), + spv_sha256: Some("33".repeat(32)), translator_fingerprint: "44".repeat(32), candidate_output_sha256: sha256_bytes(output), output_b64: b64(output), diff --git a/crates/metal2vulkan-validation/src/worker/alloc.rs b/crates/metal2vulkan-validation/src/worker/alloc.rs index 1ed7cf24c..66ad57586 100644 --- a/crates/metal2vulkan-validation/src/worker/alloc.rs +++ b/crates/metal2vulkan-validation/src/worker/alloc.rs @@ -19,7 +19,7 @@ //! refused, uncounted, and aborts the worker. use std::alloc::{GlobalAlloc, Layout, System}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Mutex; static LIVE_BYTES: AtomicUsize = AtomicUsize::new(0); @@ -31,8 +31,14 @@ static HIGH_WATER_BYTES: AtomicUsize = AtomicUsize::new(0); /// the baseline [`peak_bytes`] is reported above (0 before any budget). static BUDGET_BASELINE_BYTES: AtomicUsize = AtomicUsize::new(0); static LIMIT_BYTES: AtomicUsize = AtomicUsize::new(usize::MAX); -/// One [`measure`] at a time: each resets the shared peak. +/// One [`measure`] or [`bounded`] at a time: each resets the shared peak. static MEASURING: Mutex<()> = Mutex::new(()); +/// Whether a [`bounded`] body runs: an allocation its limit refuses ends the process. +static BOUNDED: AtomicBool = AtomicBool::new(false); + +/// The exit status of a process an allocation took past a [`bounded`] budget: it ends at once +/// (`_exit`), every thread with it, after one line on stderr naming the breach. +pub const BOUNDED_EXIT_CODE: i32 = 87; /// A [`System`]-backed allocator that counts live bytes, tracks their peak, and enforces the /// limit set by [`enable_budget`]. @@ -99,10 +105,26 @@ fn reserve(bytes: usize) -> bool { HIGH_WATER_BYTES.fetch_max(previous + bytes, Ordering::Relaxed); true } + Err(_) if BOUNDED.load(Ordering::Relaxed) => breach(), Err(_) => false, } } +/// End the process for an allocation past a [`bounded`] budget: one line on stderr, then +/// `_exit(BOUNDED_EXIT_CODE)`, which allocates nothing and runs nothing more of any thread. +fn breach() -> ! { + const LINE: &[u8] = b"an allocation passed a bounded call's memory budget: the process ends\n"; + #[cfg(unix)] + // SAFETY: `write` of a static buffer to stderr and `_exit` are async-signal-safe and allocate + // nothing, so they are sound inside the allocator. + unsafe { + libc::write(2, LINE.as_ptr().cast(), LINE.len()); + libc::_exit(BOUNDED_EXIT_CODE) + } + #[cfg(not(unix))] + std::process::abort() +} + /// Live heap bytes counted so far (0 when the allocator is not installed). pub fn live_bytes() -> usize { LIVE_BYTES.load(Ordering::Relaxed) @@ -157,6 +179,48 @@ pub fn measure(body: impl FnOnce() -> R) -> (R, Option) { ) } +/// Run `body` with at most `bytes` live above what is live at its start, and return its result +/// with the peak live bytes attributable to it, as [`measure`] does (`None` when the allocator is +/// not installed, and then nothing is bounded). An allocation past the budget while `body` runs, +/// on any thread, ends the process ([`BOUNDED_EXIT_CODE`]): the device worker's pipeline makes run +/// under it, so a make past the 500-MiB ceiling ends the worker before the run submits its work. +/// The limit before the call, the process budget's, holds again once `body` returns, and holds +/// inside it where it is the lower. +pub fn bounded(bytes: u64, body: impl FnOnce() -> R) -> (R, Option) { + // A panic inside an earlier measurement poisons nothing this lock protects. + let _measuring = MEASURING + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + /// Puts the limit back however `body` ends. + struct Restore(usize); + impl Drop for Restore { + fn drop(&mut self) { + BOUNDED.store(false, Ordering::Relaxed); + LIMIT_BYTES.store(self.0, Ordering::Relaxed); + } + } + let installed = installed(); + let baseline = live_bytes(); + let before = LIMIT_BYTES.load(Ordering::Relaxed); + let bytes = usize::try_from(bytes).unwrap_or(usize::MAX); + let restore = Restore(before); + PEAK_BYTES.store(baseline, Ordering::Relaxed); + if installed { + LIMIT_BYTES.store( + before.min(baseline.saturating_add(bytes)), + Ordering::Relaxed, + ); + BOUNDED.store(true, Ordering::Relaxed); + } + let result = body(); + drop(restore); + let peak = PEAK_BYTES.load(Ordering::Relaxed); + ( + result, + installed.then(|| peak.saturating_sub(baseline) as u64), + ) +} + /// Make the system allocator give every large freed buffer back to the system. [`super::run_json`] /// calls it before a process supervises its first worker. /// @@ -269,6 +333,64 @@ mod tests { drop((held, fixed)); } + /// A bounded body measures what it holds, as `measure` does, and the limit it ran under goes + /// with it: an allocation larger than its budget succeeds once it has returned. + #[test] + fn a_bounded_body_measures_and_its_limit_goes_with_it() { + let (len, peak) = bounded(2 * HELD as u64, || { + let held = vec![0u8; HELD]; + std::hint::black_box(&held); + held.len() + }); + assert_eq!(len, HELD); + assert!(peak.unwrap() >= (HELD / 2) as u64, "{peak:?}"); + let after = vec![0u8; 4 * HELD]; + assert_eq!(std::hint::black_box(&after).len(), 4 * HELD); + } + + /// An allocation past a bounded body's budget ends the process with [`BOUNDED_EXIT_CODE`] + /// and the breach's line, in a fresh process: the fixture allocates twice its budget. + mod bounded_breach { + use super::*; + use std::process::Command; + + const FIXTURE: &str = "worker::alloc::tests::bounded_breach::breach_fixture"; + const MODE: &str = "M2V_TEST_BOUNDED_BREACH"; + + /// The fixture: no-op unless [`MODE`] is set. + #[test] + fn breach_fixture() { + if std::env::var_os(MODE).is_none() { + return; + } + let _ = bounded(HELD as u64, || { + std::hint::black_box(vec![1u8; 2 * HELD]).len() + }); + println!("the bounded body returned"); + } + + #[test] + fn an_allocation_past_the_budget_ends_the_process() { + let output = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", FIXTURE, "--nocapture"]) + .env(MODE, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!( + output.status.code(), + Some(BOUNDED_EXIT_CODE), + "{stdout}{stderr}" + ); + assert!(!stdout.contains("the bounded body returned"), "{stdout}"); + assert!( + stderr.contains("an allocation passed a bounded call's memory budget"), + "{stderr}" + ); + } + } + /// A supervisor's freed transient buffers go back to the system once it has supervised a /// worker, sweep after sweep. Each sweep is modelled as a census profile's parent: threads each /// holding a large buffer at once (a row, its worker's input or result), then freeing it, after diff --git a/crates/metal2vulkan-validation/src/worker/device.rs b/crates/metal2vulkan-validation/src/worker/device.rs index bf8facf33..bcef68b01 100644 --- a/crates/metal2vulkan-validation/src/worker/device.rs +++ b/crates/metal2vulkan-validation/src/worker/device.rs @@ -124,8 +124,9 @@ pub struct DeviceRun { /// The selected output bytes. #[serde(with = "base64_bytes")] pub output: Vec, - /// SHA-256 of the pipeline's SPIR-V bytes (before specialization). - pub spv_sha256: String, + /// SHA-256 of the pipeline's SPIR-V bytes (before specialization), where the executor compiled + /// it itself: `None` for a run through the runtime, which keeps its modules to itself. + pub spv_sha256: Option, pub translator_fingerprint: String, pub environment: serde_json::Value, pub comparison: ComparisonClass, diff --git a/crates/metal2vulkan-validation/src/worker/device/tests.rs b/crates/metal2vulkan-validation/src/worker/device/tests.rs index 3c4d6fa43..30156d5e4 100644 --- a/crates/metal2vulkan-validation/src/worker/device/tests.rs +++ b/crates/metal2vulkan-validation/src/worker/device/tests.rs @@ -75,7 +75,7 @@ fn run_restricted_to(restricted_to: Option) -> DeviceRun { DeviceRun { timing: crate::observation::test_timing(), output: vec![0, 1, 2, 0xff], - spv_sha256: "ab".repeat(32), + spv_sha256: Some("ab".repeat(32)), translator_fingerprint: "cd".repeat(32), environment: serde_json::json!({}), comparison: ComparisonClass::Exact, diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 6e8bbc5d1..03ce0e85e 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -454,6 +454,16 @@ cargo run -p metal2vulkan-validation --release --bin corpus-moltenvk -- \ and compares the observations with Metal's. Every context runs under the validation layer, in a robustness leg: the stated leg enables every robustness feature the device states, and the `robustness-off` leg none, so both containment encodings run. +- **Through the runtime.** On Linux, in the stated leg and without a profile restriction, a kernel + case of buffers (device buffer arrays included), threadgroup memory, function constants and + linked functions, dispatched by threads or threadgroups and observing a buffer, runs through + `metal2vulkan-runtime`'s public API instead, as a consumer runs it (`engine::runs_through_runtime` + decides it from the case's structure). Its device worker enables the validation layer through the + loader's and the layer's variables, and any message the layer logs fails the row. The pipeline + state's make is held to 500 MiB of peak live allocations and 20 s. Its row records the state's + precision notes and the runtime's fingerprint, and no SPIR-V, status, subgroup shape, + 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. - **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