From f2367d8956bb6ddfe4bdea4891e36bb15f620654 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 16 Nov 2026 16:42:53 -0800 Subject: [PATCH] SEMANTICS 2142 / RUNTIME 2495: View facts from the device's own check: the runtime's view check, measured workarounds in the description What: the two constant-window view cost facts no longer come from a GPU identity. - metal2vulkan: DeviceDescription::measured (a set of DriverWorkaround, serde default) is a profile input: the profile takes those workarounds beside its identity's, so the fingerprint and every cache key follow it. The identity rows of UniformBufferPerLaneReadsSerialize (RTX 3090, RTX 2080, RTX 5080 Laptop) and ExternalUniformReadsSkipACache (ANV on the Iris Xe RPL-P) are gone, and NVIDIA_RTX_2080 with them (nothing else used it). - The texel form now applies only to a slot with an indexed read (SlotPlan::indexed_read, from Provenance::indexed_constant_reads, marked on a profile with the texel fact): a slot read at constant offsets alone keeps its uniform buffer, whose ranges ANV pushes into registers (Mesa's brw_nir_analyze_ubo_ranges; read, not measured), as reims's Iris Geekbench pair 2 suggested. With both facts, view_kind gives a per-lane slot storage, an indexed-uniform slot the texel view, a constant-offset slot the uniform buffer: no conflict. - bind::view_check_module (CheckView x CheckReads): the check's kernels, built and verified like any crate module (push-constant window mask, uvec4 reads, uniform / per-lane / fields). - metal2vulkan-runtime: view_check.rs, a device check on its own thread, started as the device is made, once per driver + release + runtime, its medians kept in the shader cache's directory: 8 kernels x 1 KiB / 4 KiB windows in device memory, and UBO / texel uniform reads over imported host pages; 7 interleaved rounds after a warm-up, medians of timestamps x timestampPeriod. Facts: per-lane where storage/UBO per-lane < 0.3 at both windows (NVIDIA 0.011-0.107, RADV 0.96-1.00); texel where texel/UBO uniform over imported pages < 0.7 at both (Iris 0.40-0.49). Unchecked (no fact) without timestamps or on any refusal. Device::settle_view_check, view_costs (ViewCosts, ViewVerdict), view_check_report. - Timing: creation never waits. Device::compile_device returns the description's compile device until the check answers with a fact, then the one with the facts measured (made before the answer is published, held in the line's Invariant); a recorded answer applies from the first pipeline. pipeline::Sources reads the compile device once per creation or variant, so one compile and its link never straddle the answer. The runtime's own tests fix the facts (DeviceOptions::view_facts, cfg(test), default none) unless a test runs the check; it replaces compile_as. Tests: device::tests::profile view_facts_come_from_the_measured_set_alone (no committed profile nor the 3090/2080 IDs carries either fact by identity; each measured set its own fingerprint); engine_lane_reads (the fact from the measured set on NVIDIA's and RADV's captures; NVIDIA identities without it keep UniformWords; both facts compose: Storage / UniformTexel / UniformWords); engine_access (the texel form for an indexed read, a constant offset keeps the uniform buffer, nothing measured keeps it); bind::view_check validity on every committed profile; runtime view_check::tests (facts on both sides of each bound, the measured GPUs' ratios, the record round trip, the measured compile device and its fingerprint); view_check_device (lavapipe: settles Measured with its medians, the compile device carries exactly its facts, a later device reads the record); uniform_texels on indexed inline kernels under fixed facts. Docs: API.md (DeviceDescription::measured, the texel form's indexed-read rule), runtime README (the check, its cost, its verdicts, when translation takes them), FAST-PATHS known gap, api signatures blessed, api_surface entries, REFUSALS regenerated (unchanged). Verified so far: msi job m3-max-38239 at 5d493d44f7: clippy -p metal2vulkan -p metal2vulkan-runtime --all-targets --all-features -D warnings CLIPPY=0. With it (folded): View check: the inline kernels' module metadata llvm-as takes; the windows' descriptor alignment checked The engine_access and uniform_texels inline kernels named llvm.module.flags and air.version with the version tuples of air.version and air.language_version, which llvm-as rejects (msi job m3-max-38254: engine_access's texel test panicked in assemble_text). The view check refuses a window or out buffer whose VkBuffer offset lies off 256 bytes, the most any descriptor offset alignment Vulkan bounds may ask, rather than write such a descriptor. Verified: m3-max-38239 (msi) at 5d493d44f7: clippy -p metal2vulkan -p metal2vulkan-runtime --all-targets --all-features 0. m3-max-38262 at f941e38fab: clippy --cfg m2v_cpu_icd (runtime) 0; lavapipe 21/21 (uniform_texels, uniform_bind_offsets, view_check_device, view_check unit tests); lavapipe verdict Measured, no facts (per-lane storage/UBO 1.17-1.44, texel/UBO over imported pages 1.99-2.30, fields texel/UBO 1.99-2.09; the check took 267-487 ms; a second device read the record). m3-max-38254 at 46e4aaab03: translator 146/147 (engine_access's inline IR, fixed in the second commit). clippy --cfg m2v_gpu, rustdoc, the translator rerun and the device verdicts (2080, 780M, XTX, 3090, Iris) run after the merge. --- crates/metal2vulkan-runtime/README.md | 27 +- .../metal2vulkan-runtime/src/device/adopt.rs | 2 + .../metal2vulkan-runtime/src/device/create.rs | 42 +- .../metal2vulkan-runtime/src/device/holds.rs | 5 +- .../metal2vulkan-runtime/src/device/line.rs | 3 + crates/metal2vulkan-runtime/src/device/mod.rs | 32 +- crates/metal2vulkan-runtime/src/lib.rs | 2 + .../metal2vulkan-runtime/src/pipeline/mod.rs | 2 +- .../src/pipeline/render.rs | 4 +- .../src/pipeline/sources.rs | 21 +- crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/uniform_texels.rs | 88 +- .../src/tests/view_check_device.rs | 64 ++ .../metal2vulkan-runtime/src/tiling_check.rs | 6 +- crates/metal2vulkan-runtime/src/view_check.rs | 941 ++++++++++++++++++ .../src/view_check/tests.rs | 183 ++++ crates/metal2vulkan/src/bind/mod.rs | 2 + crates/metal2vulkan/src/bind/view_check.rs | 336 +++++++ crates/metal2vulkan/src/cache/mod.rs | 4 +- crates/metal2vulkan/src/device/derive.rs | 6 +- crates/metal2vulkan/src/device/description.rs | 12 +- .../metal2vulkan/src/device/driver_facts.rs | 45 +- crates/metal2vulkan/src/device/profile.rs | 84 +- .../metal2vulkan/src/device/tests/profile.rs | 124 +-- crates/metal2vulkan/src/lower/access/mod.rs | 18 +- crates/metal2vulkan/src/memory/plan.rs | 35 +- crates/metal2vulkan/src/memory/views.rs | 5 +- .../metal2vulkan/src/tests/engine_access.rs | 117 ++- .../src/tests/engine_lane_reads.rs | 78 +- crates/metal2vulkan/tests/api_signatures.tsv | 44 +- crates/metal2vulkan/tests/api_surface.rs | 4 + docs/API.md | 15 +- docs/FAST-PATHS.md | 10 +- 33 files changed, 2063 insertions(+), 300 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/view_check_device.rs create mode 100644 crates/metal2vulkan-runtime/src/view_check.rs create mode 100644 crates/metal2vulkan-runtime/src/view_check/tests.rs create mode 100644 crates/metal2vulkan/src/bind/view_check.rs diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index c5dd49bc2..a7c154f19 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -558,7 +558,8 @@ after it, and 0 of 80 with the device dropped first - **Constants over imported memory.** On ANV on the Iris Xe RPL-P a uniform buffer read of memory the device marks external (a no-copy buffer's host pages, a dma-buf) misses a cache: a kernel whose invocations read one word of a 1 KiB window took 2.0 to 2.5 times as long there as over - device memory, and 5.2 to 5.5 times where each read its own. There a `constant` slot whose + device memory, and 5.2 to 5.5 times where each read its own. Where the device's view check + finds that (`ExternalUniformReadsSkipACache`), a `constant` slot with an indexed read whose window the translation bounds to at most 4 KiB reads through a uniform texel buffer instead, measured at 0.98 to 1.04 times the time over device memory: the runtime makes a view of the bound range for each bind, counted in `WorkCounts::uniform_texels_bound`. A longer window keeps its uniform buffer and @@ -861,6 +862,30 @@ Calls Metal does not have, for a consumer that emulates a Metal device: `Device::settle_in_place_checks` starts the check and says when its verdicts are known (a zero timeout waits for nothing). `Buffer::tiled_texture_placement` answers it for `new_tiled_texture`'s arguments. +- `Device::settle_view_check`, `Device::view_costs` (with `ViewCosts` and `ViewVerdict`) and + `Device::view_check_report`: the device's view check, which decides the two view cost facts + translation takes (`DeviceDescription::measured`) from the device's own timings, never from its + driver or GPU identity. It starts as the device is made, on a thread of its own, and no call + waits for it but `settle_view_check`. Eight kernels of 256 workgroups of 64 invocations each read + a 1 KiB and a 4 KiB window 256 times through a uniform buffer, a storage buffer and a uniform + texel buffer, every invocation the same vector at each step, each its own, or two fixed ones; + the window lies in the device's memory, and the uniform reads run again over host pages the + device imported by their pointer. Seven rounds after a warm-up, the arms interleaved, medians of + timestamps. `UniformBufferPerLaneReadsSerialize` where the storage buffer's per-lane reads took + less than 0.3 of the uniform buffer's at both windows (NVIDIA's measured 0.011 to 0.107, RADV's + 0.96 to 1.00); `ExternalUniformReadsSkipACache` where the texel buffer's uniform reads over the + imported pages took less than 0.7 of the uniform buffer's there (ANV on the Iris Xe of RPL-P + 0.40 to 0.49). Both may hold: a slot with a per-lane read then keeps its storage view, one with + indexed reads all uniform takes the texel view, and one read at constant offsets alone keeps its + uniform buffer. `Unchecked`, never fatal, with no fact, where the device writes no timestamps + the host reads or refuses any part of it. It holds 4 KiB and 64 KiB of the device's memory and + 64 KiB of host pages while it runs. Until it answers, pipelines compile with the profile of the + device's identity alone (a uniform view stays a uniform buffer); once it answers with a fact, + every compile from then on takes the profile with those facts measured + (`Device::compile_device`), whose fingerprint, and so every shader cache key, differs; a + pipeline made before keeps its form. Its medians are kept in the shader cache's directory for the + driver, its release and the runtime's, so a later device of the same reads them as it is made + and compiles with its facts from its first pipeline. - `Device::settle_tiling_cost_check`, `Device::tiling_cost` (with `TilingCost` and `TilingVerdict`) and `Device::tiling_cost_check_report`: whether the device's GPU pays more for a texture in place over host pages (a linear image) than for a `Private` one (optimal), measured diff --git a/crates/metal2vulkan-runtime/src/device/adopt.rs b/crates/metal2vulkan-runtime/src/device/adopt.rs index 947f87417..78363970e 100644 --- a/crates/metal2vulkan-runtime/src/device/adopt.rs +++ b/crates/metal2vulkan-runtime/src/device/adopt.rs @@ -370,6 +370,8 @@ impl Device { load_no_dynamic_library_file: raw.load_no_dynamic_library_file, pipeline_records: raw.pipeline_records, fail_in_place_check: false, + #[cfg(test)] + view_facts: Some(std::collections::BTreeSet::new()), assume_submissions_merge: false, // On where `METAL2VULKAN_PENDING_AUDIT` is set (`assemble`). pending_audit: false, diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs index 976a2c3c0..b8cd3d313 100644 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ b/crates/metal2vulkan-runtime/src/device/create.rs @@ -372,27 +372,12 @@ pub struct DeviceOptions { /// `Device::queue_switch_check_report`) on a device whose queues the limits changed. No Metal /// counterpart: a Vulkan-side option, for tests and tools that make many devices. pub queue_limits: Option, - /// In the runtime's own tests, the identity (driver, vendor and device ID) each device's - /// compile device takes in place of the device's own, its features, limits and formats the - /// device's: a test's stand-in for a device whose driver facts it runs on another - /// (`tests/uniform_texels.rs`). `None`, the device's own. + /// In the runtime's own tests, the view check's facts (`view_check.rs`): `Some` fixes them, + /// with no check run, so a test's compiles take one profile from the device's first pipeline + /// to its last (none by default: a uniform view stays a uniform buffer, as on a device whose + /// check found no fact); `None` runs the check as a device outside the tests does. #[cfg(test)] - pub(crate) compile_as: Option<(metal2vulkan::vk::DriverId, u32, u32)>, -} - -/// In the runtime's own tests, `description` under the identity `identity` names -/// (`DeviceOptions::compile_as`): the description a device's compile device is made from. -#[cfg(test)] -fn compiled_as( - mut description: DeviceDescription, - identity: Option<(metal2vulkan::vk::DriverId, u32, u32)>, -) -> DeviceDescription { - if let Some((driver, vendor, device)) = identity { - description.driver_id = Some(driver); - description.vendor_id = vendor; - description.device_id = device; - } - description + pub(crate) view_facts: Option>, } /// The most `VkQueue`s a device takes for its command queues ([`DeviceOptions::queue_limits`]). @@ -450,7 +435,7 @@ impl std::fmt::Debug for DeviceOptions { reserved_queues, queue_limits, #[cfg(test)] - compile_as, + view_facts, } = self; let mut out = f.debug_struct("DeviceOptions"); out.field("policy", policy) @@ -496,7 +481,7 @@ impl std::fmt::Debug for DeviceOptions { .field("reserved_queues", reserved_queues) .field("queue_limits", queue_limits); #[cfg(test)] - out.field("compile_as", compile_as); + out.field("view_facts", view_facts); out.finish() } } @@ -537,7 +522,7 @@ impl Default for DeviceOptions { reserved_queues: Default::default(), queue_limits: default_queue_limits(), #[cfg(test)] - compile_as: None, + view_facts: Some(BTreeSet::new()), } } } @@ -2333,11 +2318,8 @@ pub(super) fn create_on( if !generated_commands { enabled.generated_commands = None; } - let compiled = enabled.clone(); - #[cfg(test)] - let compiled = compiled_as(compiled, options.compile_as); let compile = - metal2vulkan::device::Device::new(compiled, options.policy).map_err(device_error)?; + metal2vulkan::device::Device::new(enabled.clone(), options.policy).map_err(device_error)?; // SAFETY: as above. let listed: BTreeSet = unsafe { instance.raw.enumerate_device_extension_properties(physical) } @@ -2613,6 +2595,8 @@ pub(super) fn create_on( load_no_dynamic_library_file: options.load_no_dynamic_library_file, pipeline_records: options.pipeline_records.clone(), fail_in_place_check: options.fail_in_place_check, + #[cfg(test)] + view_facts: options.view_facts.clone(), assume_submissions_merge: options.assume_submissions_merge, pending_audit: options.pending_audit, encoder_trail: options.encoder_trail, @@ -2833,7 +2817,7 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool { reserved_queues, queue_limits, #[cfg(test)] - compile_as, + view_facts, } = a; let same = *policy == b.policy && *layers == b.layers @@ -2865,7 +2849,7 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool { && *reserved_queues == b.reserved_queues && *queue_limits == b.queue_limits; #[cfg(test)] - let same = same && *compile_as == b.compile_as; + let same = same && *view_facts == b.view_facts; same } diff --git a/crates/metal2vulkan-runtime/src/device/holds.rs b/crates/metal2vulkan-runtime/src/device/holds.rs index 7ea1904a6..5c2322a48 100644 --- a/crates/metal2vulkan-runtime/src/device/holds.rs +++ b/crates/metal2vulkan-runtime/src/device/holds.rs @@ -63,11 +63,14 @@ pub(crate) enum Holder { /// The check of what linear images cost against optimal ones, between its rounds /// (`tiling_check.rs`). TilingCheck, + /// The check of what a `constant` window's views cost, between its rounds + /// (`view_check.rs`). + ViewCheck, } /// The holders: one test hold each ([`Holds::held`]). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -const HOLDERS: usize = Holder::TilingCheck as usize + 1; +const HOLDERS: usize = Holder::ViewCheck as usize + 1; /// A device's registry of its handles and the runtime's own holds (the module docs). #[derive(Default)] diff --git a/crates/metal2vulkan-runtime/src/device/line.rs b/crates/metal2vulkan-runtime/src/device/line.rs index 2fdd9641a..c336f303e 100644 --- a/crates/metal2vulkan-runtime/src/device/line.rs +++ b/crates/metal2vulkan-runtime/src/device/line.rs @@ -90,6 +90,9 @@ pub(crate) struct Invariant { /// The shader cache's directory (`Device::shader_cache_directory`); `None` where it keeps /// none. pub(crate) cache_directory: Option, + /// The view check (`view_check.rs`): its answer, and the compile device of its measured + /// facts once it holds any, which every compile then takes (`Device::compile_device`). + pub(crate) views: Arc, } /// How the line makes its next `VkDevice`: what the first was made of (`create.rs`). None for a diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 895c3adf9..a405fba89 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -1743,9 +1743,19 @@ impl Device { WeakDevice(Arc::downgrade(shared), Arc::clone(&shared.holds)) } - /// The compile-and-plan device this device compiles and plans for. No Metal counterpart. + /// The compile-and-plan device this device compiles and plans for now. No Metal counterpart. + /// Its profile is the device description's until the device's view check answers with a fact + /// (`view_check.rs`); from then on, the description's with the check's facts measured + /// ([`Device::view_costs`]), whose profile fingerprint differs. Read it once for one compile + /// and its link. pub fn compile_device(&self) -> &metal2vulkan::device::Device { - &self.invariant().compile + let invariant = self.invariant(); + (invariant.views.measured()).unwrap_or(&invariant.compile) + } + + /// The device's view check (`view_check.rs`). + pub(crate) fn view_check(&self) -> &crate::view_check::ViewCheck { + &self.invariant().views } /// What the Vulkan device enabled, in the compile layer's vocabulary. No Metal counterpart. @@ -2158,6 +2168,10 @@ pub(super) struct Parts { /// Its check of the first move over host pages fails whatever the moves did /// (`DeviceOptions::fail_in_place_check`). pub(super) fail_in_place_check: bool, + /// In the runtime's own tests, its view check's facts, fixed (`DeviceOptions::view_facts`). + #[cfg(test)] + pub(super) view_facts: + Option>, /// Its submission check of merged submissions holds without its answer /// (`DeviceOptions::assume_submissions_merge`). pub(super) assume_submissions_merge: bool, @@ -2275,6 +2289,8 @@ impl Device { load_no_dynamic_library_file, pipeline_records, fail_in_place_check, + #[cfg(test)] + view_facts, assume_submissions_merge, pending_audit, encoder_trail, @@ -3119,12 +3135,17 @@ impl Device { // The device's line: a new one for a device made now, else the line this generation // recovers, whose address space, resource IDs, identifiers and counts it goes on with // (`line.rs`). + let views = Arc::new(crate::view_check::ViewCheck::new( + properties.description.clone(), + *compile.policy(), + )); let invariant = line::Invariant { properties, compile, enabled, extensions, cache_directory: shader_cache.directory_root(), + views, }; let line = match recovering { Some(line) => line, @@ -3411,6 +3432,13 @@ impl Device { // Its submission checks' verdicts, where a record holds them; else the checks start // (`submit_check.rs`). device.recall_submit_checks(); + // Its view check's facts, where a record holds them; else the check starts + // (`view_check.rs`). In the runtime's own tests, the options' facts. + #[cfg(test)] + let forced = view_facts; + #[cfg(not(test))] + let forced = None; + device.recall_view_check(forced); device.degrade_argument_buffers_unread(); device.degrade_float_tininess(); Ok(device) diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 7d81d1635..8cb8325e9 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -270,6 +270,7 @@ mod upload; mod used_resources; mod values; mod versioned; +mod view_check; mod view_placement; mod view_plan; mod visibility; @@ -419,6 +420,7 @@ pub use values::{ CommandBufferStatus, Coordinate2D, CpuCacheMode, HazardTrackingMode, Origin, Region, ResourceOptions, Size, StorageMode, }; +pub use view_check::{ViewCosts, ViewVerdict}; pub use view_placement::{ViewPlacement, ViewShadowReason}; pub use view_plan::ViewProblem; pub use visibility::{VisibilityProblem, VisibilityResultMode, VisibilityResultType}; diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index 5e6403715..d2121aa96 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -2242,7 +2242,7 @@ impl Variant { descriptor: &Kernel, key: &VariantKey, ) -> Result<(Remembered, Kernel), metal2vulkan::error::Error> { - let compile = sources.device().compile_device(); + let compile = sources.compile(); let budget = sources.budget(); // The kernel's specialized entry is the device's, as a render stage's is: a sibling // pipeline of the same kernel at the same call-stack depth decodes and specializes diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index 7a1b1e301..5251f4bfa 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -3030,7 +3030,7 @@ impl RenderVariant { entries: &StageEntries, descriptor_key: &PipelineKey, ) -> Result { - let compile = sources.device().compile_device(); + let compile = sources.compile(); let budget = sources.budget(); // The pipeline a creation of a descriptor of the same key learned for `key`, found // without asking its keys again; else its stages' functions, found by the keys that @@ -3125,7 +3125,7 @@ impl RenderVariant { key: &VariantKey, record: Option<(&PipelineKey, &VariantStages)>, ) -> Result { - let compile = sources.device().compile_device(); + let compile = sources.compile(); let budget = sources.budget(); let pipeline = compile.compile_render_variant(&linked, key, &budget)?; // The stages the link was given, whichever way they arrived: the ones this creation diff --git a/crates/metal2vulkan-runtime/src/pipeline/sources.rs b/crates/metal2vulkan-runtime/src/pipeline/sources.rs index 77d850297..c82803fe7 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/sources.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/sources.rs @@ -65,6 +65,10 @@ fn note_render_artifact_encoded() { /// Where one creation's (or one later variant's) compiles look, and its budget. pub(crate) struct Sources<'a> { device: &'a Device, + /// The compile device every compile and link of these sources takes: the device's as they + /// were made (`Device::compile_device`), so a view check answering meanwhile changes none of + /// one creation's or variant's compiles (`view_check.rs`). + compile: &'a metal2vulkan::device::Device, /// The creation's options: its archives and budget; `None` for a variant a dispatch or /// draw needs after creation, which no archive holds and which compiles under the standard /// budget. @@ -86,6 +90,7 @@ impl<'a> Sources<'a> { ) -> Sources<'a> { Sources { device, + compile: device.compile_device(), options: Some(options), used, refusal_kept: Cell::new(false), @@ -96,6 +101,7 @@ impl<'a> Sources<'a> { pub(crate) fn later(device: &'a Device) -> Sources<'a> { Sources { device, + compile: device.compile_device(), options: None, used: None, refusal_kept: Cell::new(false), @@ -106,6 +112,11 @@ impl<'a> Sources<'a> { self.device } + /// The compile device of every compile and link of these sources. + pub(crate) fn compile(&self) -> &'a metal2vulkan::device::Device { + self.compile + } + /// Whether a refusal the memo kept answered one of its asks of a function /// ([`function`](Self::function)), the compile layer not asked. pub(crate) fn refusal_kept(&self) -> bool { @@ -151,7 +162,7 @@ impl<'a> Sources<'a> { (key, entries): (&FunctionCompileKey, Option<&StageEntries>), budget: &Budget, ) -> Result { - let compile = self.device.compile_device(); + let compile = self.compile; let shared = self.device.shared(); let cache = &shared.shader_cache; let compiled = match self.found_function(key) { @@ -193,7 +204,7 @@ impl<'a> Sources<'a> { /// `None` where none holds it, translating nothing. A render creation that holds the keys a /// variant's record names links what this finds (`ShaderCache::variant_pipeline`). pub(crate) fn found_function(&self, key: &FunctionCompileKey) -> Option { - let compile = self.device.compile_device(); + let compile = self.compile; let shared = self.device.shared(); let cache = &shared.shader_cache; let compiled = match cache.memo.function(key) { @@ -235,7 +246,7 @@ impl<'a> Sources<'a> { descriptor: &Kernel, budget: &Budget, ) -> Result, metal2vulkan::error::Error> { - let compile = self.device.compile_device(); + let compile = self.compile; let cache = &self.device.shared().shader_cache; let key = match descriptor { Kernel::Compute(descriptor) => compile.compute_pipeline_key(descriptor), @@ -280,7 +291,7 @@ impl<'a> Sources<'a> { &self, key: &PipelineKey, ) -> Option> { - let compile = self.device.compile_device(); + let compile = self.compile; let cache = &self.device.shared().shader_cache; let found = match cache.memo.render(key) { Some(found) => found, @@ -332,7 +343,7 @@ impl<'a> Sources<'a> { pipeline: RenderPipeline, stage_keys: &[FunctionCompileKey], ) -> Arc { - let compile = self.device.compile_device(); + let compile = self.compile; let cache = &self.device.shared().shader_cache; let pipeline = Arc::new(pipeline); let functions_held = !stage_keys.is_empty() diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index b30d6403f..9b330245e 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -949,6 +949,8 @@ mod vertex_conversion_notices; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod video_interop; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod view_check_device; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod view_placement_device; mod view_plan; #[cfg(any(m2v_gpu, m2v_cpu_icd))] diff --git a/crates/metal2vulkan-runtime/src/tests/uniform_texels.rs b/crates/metal2vulkan-runtime/src/tests/uniform_texels.rs index f9e66c864..0ba76a525 100644 --- a/crates/metal2vulkan-runtime/src/tests/uniform_texels.rs +++ b/crates/metal2vulkan-runtime/src/tests/uniform_texels.rs @@ -1,25 +1,64 @@ //! A buffer slot's uniform view in its texel form (`DescriptorView::UniformTexel`, -//! `uniform_texels.rs`), on lavapipe under a compile device of the Iris Xe of RPL-P's identity -//! (`DeviceOptions::compile_as`), whose profile takes -//! `DriverWorkaround::ExternalUniformReadsSkipACache`: a kernel whose `constant` window is at most -//! 4 KiB reads it through a uniform texel buffer view made for each bind, and every read is the -//! bound bytes', at bind offsets the texel alignment divides (0, 16, 256) and does not (4, 260: -//! the residual pushed), from `set*Bytes` data, and for bytes written before the dispatch was -//! encoded, after it and before the commit, and by a blit before it. A window of 4100 bytes keeps -//! its uniform buffer. The counts are the evidence that each path ran +//! `uniform_texels.rs`), on lavapipe under a device whose view check's facts the test fixes +//! (`DeviceOptions::view_facts`) to `DriverWorkaround::ExternalUniformReadsSkipACache`: a kernel +//! whose `constant` window is at most 4 KiB, read at an index (`tid` and `tid + 1023`, the one +//! thread's `tid` 0), reads it through a uniform texel buffer view made for each bind, and every +//! read is the bound bytes', at bind offsets the texel alignment divides (0, 16, 256) and does +//! not (4, 260: the residual pushed), from `set*Bytes` data, and for bytes written before the +//! dispatch was encoded, after it and before the commit, and by a blit before it. A window of +//! 4100 bytes keeps its uniform buffer. The counts are the evidence that each path ran //! (`WorkCounts::uniform_texels_bound`, `uniform_buffers_bound_to_16k`). //! -//! A device test on the CPU ICD alone (`m2v_cpu_icd`): the identity is lavapipe's stand-in for the -//! Iris, where the fact holds of the device itself. The functions are those of the owned fixture -//! `validation/fixtures/public/engine/uniform_texel_windows.ll` (`llvm-as`). +//! A device test on the CPU ICD alone (`m2v_cpu_icd`): lavapipe stands in for a device whose +//! check found the fact. The kernels are [`WINDOWS`] (`llvm-as`). use super::blit_holds::{options, Scratch, WAIT}; use crate::{Buffer, ComputePipelineState, Device, PipelineOptions, ResourceOptions, Size}; use metal2vulkan::device::DriverWorkaround; -use metal2vulkan::vk::DriverId; -/// The Iris Xe of RPL-P's vendor and device ID, under ANV. -const IRIS: (DriverId, u32, u32) = (DriverId::INTEL_OPEN_SOURCE_MESA, 0x8086, 0xa7a0); +/// `utw_near` reads words `tid` and `tid + 1023` of a 4096-byte `constant` window into `out`; +/// `utw_far` words `tid` and `tid + 1024` of a 4100-byte one. +const WINDOWS: &str = r#"define void @utw_near(ptr addrspace(2) noundef "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1, i32 noundef %tid) { +entry: + %a = zext i32 %tid to i64 + %p = getelementptr inbounds [1024 x i32], ptr addrspace(2) %0, i64 0, i64 %a + %v = load i32, ptr addrspace(2) %p, align 4 + store i32 %v, ptr addrspace(1) %1, align 4 + %b = add nuw i64 %a, 1023 + %q = getelementptr inbounds [1024 x i32], ptr addrspace(2) %0, i64 0, i64 %b + %w = load i32, ptr addrspace(2) %q, align 4 + %o = getelementptr inbounds i32, ptr addrspace(1) %1, i64 1 + store i32 %w, ptr addrspace(1) %o, align 4 + ret void +} +define void @utw_far(ptr addrspace(2) noundef "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1, i32 noundef %tid) { +entry: + %a = zext i32 %tid to i64 + %p = getelementptr inbounds [1025 x i32], ptr addrspace(2) %0, i64 0, i64 %a + %v = load i32, ptr addrspace(2) %p, align 4 + store i32 %v, ptr addrspace(1) %1, align 4 + %b = add nuw i64 %a, 1024 + %q = getelementptr inbounds [1025 x i32], ptr addrspace(2) %0, i64 0, i64 %b + %w = load i32, ptr addrspace(2) %q, align 4 + %o = getelementptr inbounds i32, ptr addrspace(1) %1, i64 1 + store i32 %w, ptr addrspace(1) %o, align 4 + ret void +} +!air.kernel = !{!10, !20} +!air.version = !{!17} +!air.language_version = !{!18} +!10 = !{ptr @utw_near, !11, !12} +!11 = !{} +!12 = !{!13, !14, !15} +!13 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 4096, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4096, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"Near", !"air.arg_name", !"c"} +!14 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!15 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"tid"} +!20 = !{ptr @utw_far, !11, !21} +!21 = !{!22, !14, !15} +!22 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 4100, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 4100, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"Far", !"air.arg_name", !"c"} +!17 = !{i32 2, i32 8, i32 0} +!18 = !{!"Metal", i32 4, i32 0, i32 0} +"#; /// The constants' words: word `i` is `3 i + 1`, so each word read names its place. const WORDS: u32 = 4096; @@ -28,23 +67,24 @@ fn word(i: u64) -> u32 { 3 * i as u32 + 1 } -/// A device whose compile device takes the Iris's identity, and so its uniform texel buffers. +/// A device whose view check's facts the test fixes to the texel fact, and so its uniform texel +/// buffers. fn device(cache: &std::path::Path) -> Device { let mut options = options(cache); - options.compile_as = Some(IRIS); + let fact = DriverWorkaround::ExternalUniformReadsSkipACache; + options.view_facts = Some([fact].into()); let device = Device::system_default_with(&options).unwrap(); let workarounds = device.compile_device().profile().workarounds(); assert!( - workarounds.contains(&DriverWorkaround::ExternalUniformReadsSkipACache), + workarounds.contains(&fact), "the compile device's profile takes the texel form: {workarounds:?}" ); device } -/// The compute state of `name`, a kernel of fixture `stem`. -fn state(device: &Device, stem: &str, name: &str) -> ComputePipelineState { - let ll = metal2vulkan_devtools::engine_dir().join(format!("{stem}.ll")); - let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap(); +/// The compute state of `name`, a kernel of [`WINDOWS`]. +fn state(device: &Device, name: &str) -> ComputePipelineState { + let bitcode = metal2vulkan_devtools::llvm_assemble_text(WINDOWS).unwrap(); let library = metal2vulkan::library::Library::from_air(&bitcode).unwrap(); let function = device .new_library_with_compile_library(library) @@ -136,7 +176,7 @@ fn dispatch( fn a_short_window_reads_through_a_texel_view_at_every_bind_offset() { let scratch = Scratch::new("uniform-texels-offsets"); let device = device(&scratch.0); - let near = state(&device, "uniform_texel_windows", "utw_near"); + let near = state(&device, "utw_near"); let data = constants(256); let constants = holding(&device, &data); let offsets = [0, 4, 16, 256, 260]; @@ -176,7 +216,7 @@ fn a_short_window_reads_through_a_texel_view_at_every_bind_offset() { fn a_texel_view_reads_the_bytes_written_before_its_dispatch_runs() { let scratch = Scratch::new("uniform-texels-writes"); let device = device(&scratch.0); - let near = state(&device, "uniform_texel_windows", "utw_near"); + let near = state(&device, "utw_near"); let queue = device.new_command_queue().unwrap(); let data = constants(0); let constants = holding(&device, &data); @@ -245,7 +285,7 @@ fn a_texel_view_reads_the_bytes_written_before_its_dispatch_runs() { fn a_window_past_the_bound_keeps_its_uniform_buffer() { let scratch = Scratch::new("uniform-texels-far"); let device = device(&scratch.0); - let far = state(&device, "uniform_texel_windows", "utw_far"); + let far = state(&device, "utw_far"); let data = constants(256); let constants = holding(&device, &data); let offsets = [0, 4]; diff --git a/crates/metal2vulkan-runtime/src/tests/view_check_device.rs b/crates/metal2vulkan-runtime/src/tests/view_check_device.rs new file mode 100644 index 000000000..2c12e7a45 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/view_check_device.rs @@ -0,0 +1,64 @@ +//! The view check (`view_check.rs`) on a device: it starts as the device is made, settles with its +//! medians, and a later device of the same driver over the same shader cache reads its record as it +//! is made, before its first pipeline. +//! +//! - **Settles.** On lavapipe (`m2v_cpu_icd`), which writes timestamps, it is measured: a verdict, +//! the per-lane ratio, and the report naming every arm's median. On a GPU it is measured, or +//! unchecked with why; the report is printed either way. +//! - **Taken.** The compile device's profile carries exactly the answer's facts. +//! - **Kept.** Where it was measured, the next device over the same cache, made after the first +//! went, answers the same at once, from the record, running no check. + +use super::blit_holds::{options, Scratch}; +use crate::{Device, ViewVerdict}; +use std::time::Duration; + +/// How long a test waits for the check: lavapipe runs its kernels on the CPU. +const WAIT: Duration = Duration::from_secs(120); + +#[test] +fn the_check_settles_with_its_medians_and_a_later_device_reads_its_record() { + let scratch = Scratch::new("view-check"); + let mut options = options(&scratch.0); + options.view_facts = None; + let device = Device::system_default_with(&options).unwrap(); + assert!(device.settle_view_check(WAIT), "the check answered"); + let costs = device.view_costs(); + let report = device.view_check_report(); + println!("view check on {}: {report}", device.name()); + assert_ne!(costs.verdict, ViewVerdict::Pending); + if cfg!(m2v_cpu_icd) { + assert_eq!(costs.verdict, ViewVerdict::Measured, "{report}"); + } + let workarounds = device.compile_device().profile().workarounds().to_vec(); + for fact in [ + metal2vulkan::device::DriverWorkaround::UniformBufferPerLaneReadsSerialize, + metal2vulkan::device::DriverWorkaround::ExternalUniformReadsSkipACache, + ] { + assert_eq!( + workarounds.contains(&fact), + costs.facts.contains(&fact), + "{fact:?}: {report}" + ); + } + if costs.verdict == ViewVerdict::Unchecked { + assert!(costs.facts.is_empty(), "{report}"); + return; + } + assert!(costs.per_lane.is_some(), "{report}"); + for named in [ + "Uniform/PerLane/device/1KiB", + "Storage/PerLane/device/4KiB", + "ran", + ] { + assert!(report.contains(named), "{named}: {report}"); + } + drop(device); + let again = Device::system_default_with(&options).unwrap(); + assert_eq!(again.view_costs(), costs, "the record's answer, at once"); + let report = again.view_check_report(); + assert!( + report.contains("read from the shader cache's record"), + "{report}" + ); +} diff --git a/crates/metal2vulkan-runtime/src/tiling_check.rs b/crates/metal2vulkan-runtime/src/tiling_check.rs index 029e1d349..b4bd34041 100644 --- a/crates/metal2vulkan-runtime/src/tiling_check.rs +++ b/crates/metal2vulkan-runtime/src/tiling_check.rs @@ -638,14 +638,14 @@ impl Arms { } /// The check's query pool of two timestamps, which each timed command buffer resets and writes. -struct Stamps { +pub(crate) struct Stamps { device: Device, pool: vk::QueryPool, } impl Stamps { /// The pool on `device`; inside a section of the exit guard. - fn new(device: &Device) -> Result { + pub(crate) fn new(device: &Device) -> Result { let raw: &ash::Device = device.shared().vk(); let info = vk::QueryPoolCreateInfo::default() .query_type(vk::QueryType::TIMESTAMP) @@ -662,7 +662,7 @@ impl Stamps { /// submission of `device`'s waited for: the pool's queries reset, a barrier of every stage /// behind the work before, the first timestamp at the top of the pipe, the work, the second /// at its bottom; inside a section of the exit guard. - fn time( + pub(crate) fn time( &self, device: &Device, clock: &GpuClock, diff --git a/crates/metal2vulkan-runtime/src/view_check.rs b/crates/metal2vulkan-runtime/src/view_check.rs new file mode 100644 index 000000000..f6109e75d --- /dev/null +++ b/crates/metal2vulkan-runtime/src/view_check.rs @@ -0,0 +1,941 @@ +//! The device's check of what reading a short `constant` window costs through each view a uniform +//! view can take, on a thread of its own, once per driver, release and runtime: the measured answer +//! translation takes as the description's measured workarounds +//! (`DeviceDescription::measured`), in place of any driver or GPU identity. +//! +//! - **What it measures.** The translator's view check kernels (`bind::view_check_module`): 256 +//! workgroups of 64 invocations, each reading a window 256 times, the window's first 1 KiB or +//! all 4 KiB (a push-constant mask), through a uniform buffer, a storage buffer and a uniform +//! texel buffer of `R32G32B32A32_UINT` texels, every invocation the same vector at each step +//! (**uniform**), each its own (**per-lane**), or two vectors at constant offsets (**fields**). +//! Each window lies in the device's own memory (a `Private` buffer of the runtime's), and the +//! uniform reads through a uniform buffer and a uniform texel buffer again over host pages the +//! device imported by their pointer (the memory a no-copy buffer's view reads), where the device +//! imports them. Each arm is one dispatch between two timestamps in an internal submission +//! waited for; a round runs every arm once, the order turned by one each round; [`ROUNDS`] +//! rounds after one that warms the device, and each arm's answer is the median of its rounds, +//! its timestamps' ticks times `timestampPeriod`. +//! - **Its verdicts** ([`facts_of`]): `DriverWorkaround::UniformBufferPerLaneReadsSerialize` where +//! the storage buffer's per-lane reads took less than [`PER_LANE_COSTLY`] of the uniform +//! buffer's at both windows; `DriverWorkaround::ExternalUniformReadsSkipACache` where the +//! uniform texel buffer's uniform reads over the imported pages took less than +//! [`TEXEL_FASTER`] of the uniform buffer's there at both windows. Both may hold: translation +//! gives a slot with a per-lane read its storage view, one with indexed reads all uniform its +//! texel view, and one read at constant offsets alone its uniform buffer +//! (`lower::access::view_kind`). The fields arm decides nothing; the report states it. +//! [`ViewVerdict::Unchecked`] where the device writes no timestamps the host reads or answers +//! GPU times from the host, refuses any object or command, or its loader word was found +//! overwritten. No driver, vendor or device identity enters it. +//! - **Its thresholds**, from bare Vulkan sweeps of the same reads: NVIDIA's storage buffer read +//! per-lane words in 0.011 to 0.107 of the uniform buffer's time (RTX 3090, RTX 2080, RTX 5080 +//! Laptop GPU), RADV's in 0.96 to 1.00 (Radeon 780M, RX 7900 XTX): 0.3 lies about midway by +//! ratio. ANV's uniform texel buffer on the Iris Xe of RPL-P read one word for every invocation +//! over imported memory in 0.40 to 0.49 of the uniform buffer's time there (the uniform buffer +//! 2.0 to 2.5 times its own over device memory, the texel buffer 0.99 to 1.00), where a driver +//! whose uniform buffer keeps its cache over imported memory reads both alike: 0.7 lies between. +//! - **Its cost**: 4 KiB of the device's memory for the window, 64 KiB for the words the +//! invocations store, 64 KiB of host pages where the device imports them, eight kernels, their +//! pipelines, layouts and sets, two texel views and a two-timestamp query pool, while it runs; +//! the GPU time of [`ROUNDS`] + 1 rounds of its arms; and the host's wait for each arm. +//! - **When translation takes it.** Device creation never waits for it. Until it answers, the +//! device compiles with the profile of its identity alone (a uniform view stays a uniform +//! buffer); once it answers with a fact, every compile from then on takes the profile of the +//! description with those facts measured (`Device::compile_device`), whose fingerprint differs, +//! so the shader cache and the memo key what it compiles apart from what it compiled before. A +//! pipeline made before keeps its form. A compile in progress keeps the compile device it began +//! with (`pipeline::Sources`). An answer read from the record applies from the device's first +//! pipeline. +//! - **Kept.** A measured answer is written as one record in the shader cache's content directory +//! (`shader_cache/store.rs`), named by the driver's identity, the check's version and the +//! runtime's ([`record_name`]): its medians, from which the facts are worked out again as it is +//! read. A device of the same driver and release reads it as it is made and runs no check. An +//! unchecked answer is kept nowhere. +//! - **Out of the device's way, and its thread**, as the tiling-cost check's +//! (`tiling_check.rs`): it steps aside before each round for the device's allocations and frees +//! on other threads (`step_aside.rs`), at once while a call waits for its answer; each round's +//! Vulkan work runs inside a section of the exit guard; it holds its device through the registry +//! of the runtime's holds (`device/holds.rs`), reading the stop before each round; and its +//! submissions are counted as the checks' (`WorkCounts::device_checks`). + +use crate::buffer::Buffer; +use crate::device::holds::Holder; +use crate::device::{lock, Device, WeakDevice}; +use crate::error::{internal, vulkan, Error}; +use crate::gpu_time::GpuClock; +use crate::in_place::DriverIdentity; +use crate::shader_cache::store::{hex, Lookup}; +use crate::tiling_check::{median, Stamps}; +use crate::{exit_guard, release}; +use ash::vk; +use metal2vulkan::bind::{view_check_module, CheckReads, CheckView, ViewCheckModule}; +use metal2vulkan::device::{DeviceDescription, DevicePolicy, DriverWorkaround}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeSet; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::{Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +/// The measured rounds; one more warms the device first. +pub(crate) const ROUNDS: usize = 7; + +/// The storage buffer's per-lane time over the uniform buffer's below which the per-lane fact +/// holds (the module docs). +pub(crate) const PER_LANE_COSTLY: f64 = 0.3; + +/// The uniform texel buffer's uniform time over the uniform buffer's, over imported pages, below +/// which the texel fact holds (the module docs). +pub(crate) const TEXEL_FASTER: f64 = 0.7; + +/// The workgroups of each dispatch. +const GROUPS: u32 = 256; + +/// The reads of each invocation. +const READS: u32 = 256; + +/// The window's two lengths, in 16-byte vectors: 1 KiB and 4 KiB. +const WINDOWS: [u32; 2] = [64, ViewCheckModule::WINDOW_VECS]; + +/// The window's bytes, the longer length's. +const WINDOW_BYTES: u64 = ViewCheckModule::WINDOW_VECS as u64 * 16; + +/// The host pages the imported arms read: the window at their start. +const HOST_BYTES: u64 = 1 << 16; + +/// The bytes of the words the invocations store. +const OUT_BYTES: u64 = (GROUPS * ViewCheckModule::LOCAL_SIZE) as u64 * 4; + +/// The kernels the arms run, by view and pattern. +const KERNELS: [(CheckView, CheckReads); 8] = [ + (CheckView::Uniform, CheckReads::Uniform), + (CheckView::Uniform, CheckReads::PerLane), + (CheckView::Uniform, CheckReads::Fields), + (CheckView::Storage, CheckReads::Uniform), + (CheckView::Storage, CheckReads::PerLane), + (CheckView::Texel, CheckReads::Uniform), + (CheckView::Texel, CheckReads::PerLane), + (CheckView::Texel, CheckReads::Fields), +]; + +/// The kernels the imported pages' arms run. +const HOST_KERNELS: [(CheckView, CheckReads); 2] = [ + (CheckView::Uniform, CheckReads::Uniform), + (CheckView::Texel, CheckReads::Uniform), +]; + +/// One arm: its kernel (an index of [`KERNELS`]), whether its window lies in the imported pages, +/// and its window's vectors. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Arm { + kernel: usize, + host: bool, + vecs: u32, +} + +/// The arms in the order a record holds their medians: each window's device arms, then each +/// window's imported ones. +fn arms() -> Vec { + let device = WINDOWS.into_iter().flat_map(|vecs| { + (0..KERNELS.len()).map(move |kernel| Arm { + kernel, + host: false, + vecs, + }) + }); + let host = WINDOWS.into_iter().flat_map(|vecs| { + HOST_KERNELS.into_iter().map(move |pair| Arm { + kernel: KERNELS.iter().position(|k| *k == pair).unwrap_or(0), + host: true, + vecs, + }) + }); + device.chain(host).collect() +} + +/// The arms' count: a record's medians. +const ARMS: usize = 2 * KERNELS.len() + 2 * HOST_KERNELS.len(); + +/// What the device's view check answered ([`ViewCosts::verdict`]). No Metal counterpart: Metal +/// answers no such question. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ViewVerdict { + /// Not known yet: the check runs. + Pending, + /// Measured, in this process or read from the shader cache's record: its facts hold. + Measured, + /// No measurement: the device writes no timestamps the host reads, answers GPU times from the + /// host, refused an object or command, or the run did not end. Translation takes no fact. + /// [`Device::view_check_report`] says why. + Unchecked, +} + +/// The device's view check's answer ([`Device::view_costs`]): its verdict, the facts translation +/// takes from it, and the two ratios they come from. No Metal counterpart: Metal answers no such +/// question. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq)] +pub struct ViewCosts { + /// The verdict. + pub verdict: ViewVerdict, + /// The workarounds translation takes from it: `UniformBufferPerLaneReadsSerialize`, + /// `ExternalUniformReadsSkipACache`, both or neither. Empty unless measured. + pub facts: BTreeSet, + /// The storage buffer's per-lane time over the uniform buffer's, device memory, the larger of + /// the two windows'. `None` unless measured. + pub per_lane: Option, + /// The uniform texel buffer's uniform time over the uniform buffer's, imported pages, the + /// larger of the two windows'. `None` unless measured and the device imports host pages. + pub texel: Option, +} + +impl ViewCosts { + /// An answer of `verdict` with nothing measured. + fn unmeasured(verdict: ViewVerdict) -> ViewCosts { + ViewCosts { + verdict, + facts: BTreeSet::new(), + per_lane: None, + texel: None, + } + } +} + +/// The medians one run measured, in nanoseconds, in [`arms`]' order; 0 for an arm not run (the +/// imported ones, where the device imports no host pages). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Medians(pub(crate) [u64; ARMS]); + +impl Medians { + /// The median of the arm of `pair` over imported pages or not, at `vecs`; `None` where it was + /// not run. + fn of(&self, pair: (CheckView, CheckReads), host: bool, vecs: u32) -> Option { + let kernel = KERNELS.iter().position(|k| *k == pair)?; + let at = arms() + .iter() + .position(|arm| *arm == Arm { kernel, host, vecs })?; + self.0.get(at).copied().filter(|&nanos| nanos > 0) + } + + /// The larger of the two windows' ratios of `over`'s arm to `under`'s, `host` the memory. + fn ratio( + &self, + over: (CheckView, CheckReads), + under: (CheckView, CheckReads), + host: bool, + ) -> Option { + WINDOWS + .iter() + .map(|&vecs| { + let over = self.of(over, host, vecs)?; + let under = self.of(under, host, vecs)?; + Some(over as f64 / under as f64) + }) + .try_fold(0f64, |most, r| r.map(|r| most.max(r))) + } + + /// The answer they give. + pub(crate) fn costs(&self) -> ViewCosts { + let per_lane = self.ratio( + (CheckView::Storage, CheckReads::PerLane), + (CheckView::Uniform, CheckReads::PerLane), + false, + ); + let texel = self.ratio( + (CheckView::Texel, CheckReads::Uniform), + (CheckView::Uniform, CheckReads::Uniform), + true, + ); + ViewCosts { + verdict: ViewVerdict::Measured, + facts: facts_of(per_lane, texel), + per_lane, + texel, + } + } +} + +/// The facts of a run whose per-lane ratio is `per_lane` and texel ratio `texel` (the module +/// docs): each where its ratio was measured and is below its bound. +pub(crate) fn facts_of(per_lane: Option, texel: Option) -> BTreeSet { + let mut facts = BTreeSet::new(); + if per_lane.is_some_and(|r| r < PER_LANE_COSTLY) { + facts.insert(DriverWorkaround::UniformBufferPerLaneReadsSerialize); + } + if texel.is_some_and(|r| r < TEXEL_FASTER) { + facts.insert(DriverWorkaround::ExternalUniformReadsSkipACache); + } + facts +} + +/// A device's view check (`line::Invariant::views`): whether it started, its answer once known +/// with how it came and its medians, the calls waiting for it, and the compile device of the +/// measured facts once they are known. +pub(crate) struct ViewCheck { + started: AtomicBool, + settled: Mutex, String)>>, + wake: Condvar, + waiters: AtomicU32, + /// The description and policy the device's compile device was made of, which the measured + /// one is made of with its facts. + base: (DeviceDescription, DevicePolicy), + /// The compile device of the measured facts, set once where the answer holds any. + measured: OnceLock, +} + +impl ViewCheck { + /// A device's, not started, its compile device made of `description` under `policy`. + pub(crate) fn new(description: DeviceDescription, policy: DevicePolicy) -> ViewCheck { + ViewCheck { + started: AtomicBool::new(false), + settled: Mutex::new(None), + wake: Condvar::new(), + waiters: AtomicU32::new(0), + base: (description, policy), + measured: OnceLock::new(), + } + } + + /// The compile device of the measured facts, once the answer holds any. + pub(crate) fn measured(&self) -> Option<&metal2vulkan::device::Device> { + self.measured.get() + } + + /// Note the check started; whether it had not been before. + fn start(&self) -> bool { + !self.started.swap(true, Ordering::AcqRel) + } + + /// The answer now: pending until it is known. + fn costs(&self) -> ViewCosts { + (lock(&self.settled).as_ref()).map_or_else( + || ViewCosts::unmeasured(ViewVerdict::Pending), + |(costs, ..)| costs.clone(), + ) + } + + /// Settle the answer, `how` saying how it came: where it holds facts, the measured compile + /// device is made first, so every compile after the answer takes it. + pub(crate) fn settle(&self, costs: ViewCosts, medians: Option, how: String) { + let mut how = how; + if !costs.facts.is_empty() { + let (description, policy) = &self.base; + let mut description = description.clone(); + description.measured.extend(costs.facts.iter().copied()); + match metal2vulkan::device::Device::new(description, *policy) { + Ok(device) => { + let _ = self.measured.set(device); + } + Err(error) => how = format!("{how}; its compile device was refused: {error}"), + } + } + *lock(&self.settled) = Some((costs, medians, how)); + self.wake.notify_all(); + } + + /// Whether a call waits for the answer. + fn awaited(&self) -> bool { + self.waiters.load(Ordering::Acquire) > 0 + } + + /// Wait until the answer is known, or `timeout` passed: whether it is. + fn wait(&self, timeout: Duration) -> bool { + let deadline = Instant::now() + timeout; + self.waiters.fetch_add(1, Ordering::AcqRel); + let _waiting = Waiting(&self.waiters); + let mut settled = lock(&self.settled); + while settled.is_none() { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return false; + } + settled = match self.wake.wait_timeout(settled, left) { + Ok((settled, _)) => settled, + Err(poisoned) => poisoned.into_inner().0, + }; + } + true + } + + /// The answer in words: its verdict and facts, the two ratios, and every arm's median. + fn report(&self) -> String { + let settled = lock(&self.settled); + let Some((costs, medians, how)) = settled.as_ref() else { + return "verdict Pending".to_owned(); + }; + let mut out = format!("verdict {:?}, facts {:?}", costs.verdict, costs.facts); + let ratio = |r: Option| r.map_or("none".to_owned(), |r| format!("{r:.3}")); + if let Some(medians) = medians { + out += &format!( + "; storage/uniform per-lane {} (costly below {PER_LANE_COSTLY}), texel/uniform \ + uniform over imported pages {} (faster below {TEXEL_FASTER}), texel/uniform \ + fields {}; medians of {ROUNDS} rounds in us:", + ratio(costs.per_lane), + ratio(costs.texel), + ratio(medians.ratio( + (CheckView::Texel, CheckReads::Fields), + (CheckView::Uniform, CheckReads::Fields), + false + )), + ); + for (arm, nanos) in arms().iter().zip(medians.0) { + let (view, reads) = KERNELS[arm.kernel]; + let memory = if arm.host { "imported" } else { "device" }; + out += &format!( + " {view:?}/{reads:?}/{memory}/{}KiB {:.1}", + arm.vecs * 16 / 1024, + nanos as f64 / 1e3 + ); + } + } + out + "; " + how + } +} + +/// A call waiting for the answer ([`ViewCheck::wait`]), counted until it returns. +struct Waiting<'a>(&'a AtomicU32); + +impl Drop for Waiting<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::AcqRel); + } +} + +impl Device { + /// No Metal counterpart (Metal answers no such question): wait until the device's view check + /// answered or `timeout` passed: whether it did. The check starts as the device is made, on + /// a thread of its own, and no call but this one waits for it; its answer is kept in the + /// shader cache's directory for the driver, its release and the runtime's, so a later device + /// of the same reads it at once. It measures what reading a short `constant` window costs + /// through a uniform buffer, a storage buffer and a uniform texel buffer, and translation + /// takes its facts from then on ([`Device::view_costs`]). + pub fn settle_view_check(&self, timeout: Duration) -> bool { + self.current().view_check().wait(timeout) + } + + /// No Metal counterpart: the device's view check's answer now ([`Device::settle_view_check`]): + /// [`ViewVerdict::Pending`] with no fact until it is known. + pub fn view_costs(&self) -> ViewCosts { + self.current().view_check().costs() + } + + /// No Metal counterpart: the device's view check's answer in words: its verdict and facts, the + /// ratios they come from, every arm's median, and whether it ran in this process (how long) + /// or was read from the shader cache's record; why, where it is unchecked. + pub fn view_check_report(&self) -> String { + self.current().view_check().report() + } + + /// As the device is made: the check's answer from the record where one holds it, else its + /// thread. Where the thread cannot start, the answer is unchecked. In the runtime's own + /// tests a device made with `DeviceOptions::view_facts` takes those facts and runs no check. + pub(crate) fn recall_view_check(&self, forced: Option>) { + let check = self.view_check(); + if !check.start() { + return; + } + if let Some(facts) = forced { + let costs = ViewCosts { + verdict: ViewVerdict::Measured, + facts, + per_lane: None, + texel: None, + }; + check.settle(costs, None, "fixed by the test's options".to_owned()); + return; + } + let shared = self.shared(); + let identity = self.driver_identity(); + let looked = (shared.shader_cache.content_store()) + .load_content(&record_name(&identity), |bytes| decode(&identity, &bytes)); + if let Lookup::Hit(medians) = looked { + let how = "read from the shader cache's record".to_owned(); + check.settle(medians.costs(), Some(medians), how); + return; + } + let weak = self.downgrade(); + let builder = std::thread::Builder::new().name("m2v-view-check".to_owned()); + if exit_guard::spawn(builder, move || run(weak)).is_err() { + let unchecked = ViewCosts::unmeasured(ViewVerdict::Unchecked); + check.settle(unchecked, None, "its thread did not start".to_owned()); + } + } +} + +/// The check's thread: the run, then its answer settled and, where measured, recorded. +fn run(weak: WeakDevice) { + crate::in_place::mark_checking(); + crate::step_aside::mark_a_check_s_thread(crate::step_aside::Counted::Apart); + let began = Instant::now(); + let Some(device) = weak.hold() else { + return; + }; + let Some(measured) = measure(&device) else { + // The process is exiting, or the program let the device go: nothing is kept. + return; + }; + let check = device.view_check(); + match measured { + Ok(medians) => { + let store = device.shared().shader_cache.content_store(); + if store.has_directory() { + let identity = device.driver_identity(); + let _ = + store.write_record_soon(&record_name(&identity), encode(&identity, &medians)); + } + let took = began.elapsed().as_secs_f64() * 1e3; + let how = format!("ran {took:.1} ms in this process"); + check.settle(medians.costs(), Some(medians), how); + } + Err(why) => { + let unchecked = ViewCosts::unmeasured(ViewVerdict::Unchecked); + check.settle(unchecked, None, why); + } + } +} + +/// The run's medians; why not, where it measured none; `None` where the process is exiting or the +/// program's last drop stopped the device's holds. +fn measure(device: &Device) -> Option> { + let shared = device.shared(); + let clock = match (shared.timing.clock(), shared.timing.answers_from_host()) { + (Some(clock), false) => *clock, + _ => { + let why = "the device writes no timestamps the host reads, or answers GPU times from \ + the host"; + return Some(Err(why.to_owned())); + } + }; + if word_overwritten(device) { + let why = "the device's loader word was found overwritten (the driver names the device in \ + its messages)"; + return Some(Err(why.to_owned())); + } + let made = { + let _busy = exit_guard::enter()?; + Kernels::new(device) + }; + let kernels = match made { + Ok(kernels) => kernels, + Err(why) => return Some(Err(why)), + }; + let measured = rounds(device, &clock, &kernels); + let busy = exit_guard::enter(); + drop(kernels); + drop(busy); + measured +} + +/// The rounds of every arm over `kernels`, as [`measure`] answers them. +fn rounds(device: &Device, clock: &GpuClock, kernels: &Kernels) -> Option> { + let stamps = { + let _busy = exit_guard::enter()?; + Stamps::new(device) + }; + let stamps = match stamps { + Ok(stamps) => stamps, + Err(error) => return Some(Err(format!("its query pool was not made: {error}"))), + }; + let arms: Vec<(usize, Arm)> = (arms().into_iter().enumerate()) + .filter(|(_, arm)| !arm.host || kernels.host.is_some()) + .collect(); + let mut times: Vec> = vec![Vec::new(); ARMS]; + for round in 0..=ROUNDS { + if !device.holds_go_on(Holder::ViewCheck) { + return None; + } + step_aside(device); + if word_overwritten(device) { + let why = "the device's loader word was found overwritten during its rounds"; + return Some(Err(why.to_owned())); + } + for turn in 0..arms.len() { + let (at, arm) = arms[(turn + round) % arms.len()]; + let _busy = exit_guard::enter()?; + let timed = stamps.time(device, clock, |raw, command_buffer| { + // SAFETY: the internal command buffer is recording outside a render pass and only + // this records it; the kernels' objects live until they are dropped, after the + // rounds, and every submission is waited for. + unsafe { kernels.record(raw, command_buffer, arm) } + }); + match timed { + Ok(nanos) if round > 0 => times[at].push(nanos), + Ok(_) => {} + Err(error) => return Some(Err(format!("its {arm:?} round failed: {error}"))), + } + } + } + let mut medians = [0u64; ARMS]; + for (at, times) in times.iter_mut().enumerate() { + medians[at] = median(times); + } + Some(Ok(Medians(medians))) +} + +/// Before a round, step aside for the device's allocations and frees on other threads +/// (`step_aside.rs`): not while the program's last drop stops the check or a call waits for its +/// answer. Counted where it waited. +fn step_aside(device: &Device) { + let shared = device.shared(); + let activity = shared.allocations.allocations.activity(); + let stop = || shared.holds.stopping() || device.view_check().awaited(); + if let Some(waited) = activity.step_aside(stop) { + shared.counts.check_stepped_aside(waited); + } +} + +/// Whether the runtime found `device`'s loader word overwritten (`loader_word.rs`). +fn word_overwritten(device: &Device) -> bool { + // SAFETY: the device is live while `device` is. + unsafe { device.shared().loader_word.overwritten() } +} + +/// The descriptor type of the window through `view`. +fn descriptor_type(view: CheckView) -> Result { + match view { + CheckView::Uniform => Ok(vk::DescriptorType::UNIFORM_BUFFER), + CheckView::Storage => Ok(vk::DescriptorType::STORAGE_BUFFER), + CheckView::Texel => Ok(vk::DescriptorType::UNIFORM_TEXEL_BUFFER), + other => Err(format!("no descriptor for the view {other:?}")), + } +} + +/// The check's objects: the window and out buffers, the imported pages where the device imports +/// them, the kernels' pipelines, and one set for each view and memory. Released as they go. +struct Kernels { + device: Device, + window: Buffer, + out: Buffer, + /// The imported pages, where the device imports them. + host: Option, + modules: Vec, + set_layouts: Vec, + layouts: Vec, + pipelines: Vec, + pool: vk::DescriptorPool, + views: Vec, + /// The set of each kernel's view over the device window and over the imported pages. + sets: Vec<(vk::DescriptorSet, vk::DescriptorSet)>, +} + +impl Kernels { + /// The objects on `device`, inside a section of the exit guard; why not, where it refuses one. + fn new(device: &Device) -> Result { + let window = (device.scratch_buffer(WINDOW_BYTES)) + .map_err(|error| format!("its window was refused: {error}"))?; + let out = (device.scratch_buffer(OUT_BYTES)) + .map_err(|error| format!("its out buffer was refused: {error}"))?; + let host = crate::in_place_check::pointer_pages(device, HOST_BYTES).ok(); + let mut kernels = Kernels { + device: device.clone(), + window, + out, + host, + modules: Vec::new(), + set_layouts: Vec::new(), + layouts: Vec::new(), + pipelines: Vec::new(), + pool: vk::DescriptorPool::null(), + views: Vec::new(), + sets: Vec::new(), + }; + kernels + .make() + .map_err(|error| format!("its kernels were not made: {error}"))?; + Ok(kernels) + } + + /// Make every object; those made before a failure go with the drop. + fn make(&mut self) -> Result<(), Error> { + let raw: &ash::Device = self.device.shared().vk(); + let compile = self.device.compile_device(); + for (view, reads) in KERNELS { + let module = + view_check_module(compile, view, reads).map_err(crate::device::device_error)?; + let info = vk::ShaderModuleCreateInfo::default().code(&module.spirv); + // SAFETY: the code is live SPIR-V words for the call. + let made = unsafe { raw.create_shader_module(&info, None) }.map_err(vulkan)?; + self.modules.push(made); + let ty = descriptor_type(view).map_err(|why| internal(&why))?; + let bindings = [ + vk::DescriptorSetLayoutBinding::default() + .binding(ViewCheckModule::WINDOW_BINDING) + .descriptor_type(ty) + .descriptor_count(1) + .stage_flags(vk::ShaderStageFlags::COMPUTE), + vk::DescriptorSetLayoutBinding::default() + .binding(ViewCheckModule::OUT_BINDING) + .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) + .descriptor_count(1) + .stage_flags(vk::ShaderStageFlags::COMPUTE), + ]; + let info = vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings); + // SAFETY: `info` and its array are live for the call. + let set_layout = + unsafe { raw.create_descriptor_set_layout(&info, None) }.map_err(vulkan)?; + self.set_layouts.push(set_layout); + let ranges = [vk::PushConstantRange::default() + .stage_flags(vk::ShaderStageFlags::COMPUTE) + .offset(0) + .size(ViewCheckModule::PUSH_BYTES)]; + let set_layouts = [set_layout]; + let info = vk::PipelineLayoutCreateInfo::default() + .set_layouts(&set_layouts) + .push_constant_ranges(&ranges); + // SAFETY: `info` and its arrays are live for the call. + let layout = unsafe { raw.create_pipeline_layout(&info, None) }.map_err(vulkan)?; + self.layouts.push(layout); + let stage = vk::PipelineShaderStageCreateInfo::default() + .stage(vk::ShaderStageFlags::COMPUTE) + .module(made) + .name(c"main"); + let info = vk::ComputePipelineCreateInfo::default() + .stage(stage) + .layout(layout); + // SAFETY: every pointer in `info` outlives the call; no pipeline cache. + let pipelines = + unsafe { raw.create_compute_pipelines(vk::PipelineCache::null(), &[info], None) }; + let pipelines = pipelines.map_err(|(_, error)| vulkan(error))?; + let pipeline = (pipelines.first().copied()) + .ok_or_else(|| internal("the driver made no pipeline"))?; + self.pipelines.push(pipeline); + (self.device.shared()).name_pipeline(pipeline, || { + format!("metal2vulkan: view check {view:?} {reads:?}") + }); + } + let sets = 2 * KERNELS.len() as u32; + let sizes = [ + vk::DescriptorPoolSize { + ty: vk::DescriptorType::UNIFORM_BUFFER, + descriptor_count: sets, + }, + vk::DescriptorPoolSize { + ty: vk::DescriptorType::STORAGE_BUFFER, + descriptor_count: 2 * sets, + }, + vk::DescriptorPoolSize { + ty: vk::DescriptorType::UNIFORM_TEXEL_BUFFER, + descriptor_count: sets, + }, + ]; + let info = vk::DescriptorPoolCreateInfo::default() + .max_sets(sets) + .pool_sizes(&sizes); + // SAFETY: `info` and its array are live for the call. + self.pool = unsafe { raw.create_descriptor_pool(&info, None) }.map_err(vulkan)?; + let device_window = self.window.at(0); + let host_window = self.host.as_ref().map(|pages| pages.buffer.at(0)); + let out = self.out.at(0); + // Every descriptor offset Vulkan bounds is at most 256 bytes' alignment + // (`minUniformBufferOffsetAlignment`, `minStorageBufferOffsetAlignment`, + // `minTexelBufferOffsetAlignment`). + let placed = [Some(device_window), host_window, Some(out)]; + if placed + .into_iter() + .flatten() + .any(|(_, at)| !at.is_multiple_of(256)) + { + return Err(internal("a window lies off 256 bytes in its VkBuffer")); + } + let texel_view = |(buffer, offset): (vk::Buffer, u64)| { + let info = vk::BufferViewCreateInfo::default() + .buffer(buffer) + .format(vk::Format::R32G32B32A32_UINT) + .offset(offset) + .range(WINDOW_BYTES); + // SAFETY: the buffer is live, made with the uniform texel buffer usage. + unsafe { raw.create_buffer_view(&info, None) }.map_err(vulkan) + }; + let device_view = texel_view(device_window)?; + self.views.push(device_view); + let host_view = match host_window { + Some(window) => { + let view = texel_view(window)?; + self.views.push(view); + Some(view) + } + None => None, + }; + for (at, (view, _)) in KERNELS.iter().enumerate() { + let layouts = [self.set_layouts[at]; 2]; + let info = vk::DescriptorSetAllocateInfo::default() + .descriptor_pool(self.pool) + .set_layouts(&layouts); + // SAFETY: the pool holds the sets' descriptors (sized above). + let made = unsafe { raw.allocate_descriptor_sets(&info) }.map_err(vulkan)?; + let (on_device, on_host) = (made[0], made[1]); + self.sets.push((on_device, on_host)); + let ty = descriptor_type(*view).map_err(|why| internal(&why))?; + let windows = [ + (on_device, Some(device_window), Some(device_view)), + (on_host, host_window, host_view), + ]; + for (set, window, texels) in windows { + let Some((buffer, offset)) = window else { + continue; + }; + let infos = [vk::DescriptorBufferInfo { + buffer, + offset, + range: WINDOW_BYTES, + }]; + let outs = [vk::DescriptorBufferInfo { + buffer: out.0, + offset: out.1, + range: OUT_BYTES, + }]; + let texel_views: Vec = texels.into_iter().collect(); + let mut window_write = vk::WriteDescriptorSet::default() + .dst_set(set) + .dst_binding(ViewCheckModule::WINDOW_BINDING) + .descriptor_type(ty); + window_write = match ty { + vk::DescriptorType::UNIFORM_TEXEL_BUFFER => { + window_write.texel_buffer_view(&texel_views) + } + _ => window_write.buffer_info(&infos), + }; + let writes = [ + window_write, + vk::WriteDescriptorSet::default() + .dst_set(set) + .dst_binding(ViewCheckModule::OUT_BINDING) + .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) + .buffer_info(&outs), + ]; + // SAFETY: the set, buffers and view are live; no command uses the set yet. + unsafe { raw.update_descriptor_sets(&writes, &[]) }; + } + } + Ok(()) + } + + /// Record `arm`'s dispatch into `command_buffer`. + /// + /// # Safety + /// + /// The command buffer is recording outside a render pass, on this device. + unsafe fn record(&self, raw: &ash::Device, command_buffer: vk::CommandBuffer, arm: Arm) { + let (on_device, on_host) = self.sets[arm.kernel]; + let set = if arm.host { on_host } else { on_device }; + let push = ViewCheckModule::push(arm.vecs, READS); + let bind = vk::PipelineBindPoint::COMPUTE; + // SAFETY: the caller's; the pipeline, layout and set are live and match. + unsafe { + raw.cmd_bind_pipeline(command_buffer, bind, self.pipelines[arm.kernel]); + let layout = self.layouts[arm.kernel]; + raw.cmd_bind_descriptor_sets(command_buffer, bind, layout, 0, &[set], &[]); + let stages = vk::ShaderStageFlags::COMPUTE; + raw.cmd_push_constants(command_buffer, layout, stages, 0, &push); + raw.cmd_dispatch(command_buffer, GROUPS, 1, 1); + } + } +} + +impl Drop for Kernels { + fn drop(&mut self) { + // The Vulkan teardown is a section of the exit guard. + let Some(_busy) = exit_guard::enter() else { + return; + }; + let raw: &ash::Device = self.device.shared().vk(); + // SAFETY: every submission that used the objects completed (each was waited for). + unsafe { + for &pipeline in &self.pipelines { + release::object(raw, pipeline); + } + for &layout in &self.layouts { + release::object(raw, layout); + } + for &set_layout in &self.set_layouts { + release::object(raw, set_layout); + } + for &module in &self.modules { + release::object(raw, module); + } + for &view in &self.views { + release::object(raw, view); + } + if self.pool != vk::DescriptorPool::null() { + release::object(raw, self.pool); + } + } + } +} + +/// The version of what the check measures and of how its record is named and framed: a change to +/// either bumps it, and a record of another version is never read. +pub(crate) const CHECK_VERSION: u32 = 1; + +/// A record's first bytes. +const MAGIC: [u8; 8] = *b"M2VVIEW\0"; + +/// The domain tag of a record's name. +const NAME_TAG: &[u8] = b"metal2vulkan view check record\0"; + +/// What the check measures, in a record's name. +const CHECK_KIND: &[u8] = b"constant window views\0"; + +/// A record's length: magic, version, runtime, identity, the medians, checksum. +const RECORD_BYTES: usize = 8 + 4 + 4 + 32 + ARMS * 8 + 32; + +/// The digest of `identity` that names its record and that the record holds again. +fn digest(identity: &DriverIdentity) -> [u8; 32] { + identity.digest_for(NAME_TAG, CHECK_KIND, CHECK_VERSION) +} + +/// The name of the record of `identity`'s answer in the shader cache's content directory. +pub(crate) fn record_name(identity: &DriverIdentity) -> String { + hex(&digest(identity)) +} + +/// The bytes of a record of `medians` for `identity`: magic `"M2VVIEW\0"`, `CHECK_VERSION`, +/// `RUNTIME_VERSION` (each `u32`), the identity's digest for this check (32 bytes), each arm's +/// median in nanoseconds in [`arms`]' order (`u64`), and the SHA-256 of every byte before it. +/// Integers are little-endian. +pub(crate) fn encode(identity: &DriverIdentity, medians: &Medians) -> Vec { + let mut bytes = Vec::with_capacity(RECORD_BYTES); + bytes.extend_from_slice(&MAGIC); + bytes.extend_from_slice(&CHECK_VERSION.to_le_bytes()); + bytes.extend_from_slice(&metal2vulkan::cache::RUNTIME_VERSION.to_le_bytes()); + bytes.extend_from_slice(&digest(identity)); + for nanos in medians.0 { + bytes.extend_from_slice(&nanos.to_le_bytes()); + } + let checksum: [u8; 32] = Sha256::digest(&bytes).into(); + bytes.extend_from_slice(&checksum); + bytes +} + +/// The medians `bytes` record for `identity`: `None` for anything but a whole record of this +/// version and runtime, for this identity, whose checksum holds and whose device arms are not zero. +pub(crate) fn decode(identity: &DriverIdentity, bytes: &[u8]) -> Option { + if bytes.len() != RECORD_BYTES { + return None; + } + let (body, checksum) = bytes.split_at(RECORD_BYTES - 32); + let computed: [u8; 32] = Sha256::digest(body).into(); + if computed[..] != *checksum { + return None; + } + let (magic, rest) = body.split_at(8); + let (version, rest) = rest.split_at(4); + let (runtime, rest) = rest.split_at(4); + let (identity_digest, rest) = rest.split_at(32); + let word = |bytes: &[u8]| u32::from_le_bytes(bytes.try_into().unwrap_or([0xff; 4])); + if magic != MAGIC + || word(version) != CHECK_VERSION + || word(runtime) != metal2vulkan::cache::RUNTIME_VERSION + || identity_digest != digest(identity) + { + return None; + } + let mut medians = [0u64; ARMS]; + for (at, median) in medians.iter_mut().enumerate() { + *median = u64::from_le_bytes(rest.get(at * 8..at * 8 + 8)?.try_into().ok()?); + } + let device_arms = 2 * KERNELS.len(); + (medians[..device_arms].iter().all(|&nanos| nanos > 0)).then_some(Medians(medians)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/metal2vulkan-runtime/src/view_check/tests.rs b/crates/metal2vulkan-runtime/src/view_check/tests.rs new file mode 100644 index 000000000..3b14d4134 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/view_check/tests.rs @@ -0,0 +1,183 @@ +//! The view check (`view_check.rs`), the parts that need no device: its facts on fixed medians, on +//! both sides of each bound, and the record that keeps its answer. +//! +//! - **The facts.** The per-lane fact only where the storage buffer's per-lane reads took less +//! than `PER_LANE_COSTLY` of the uniform buffer's at both windows; the texel fact only where +//! the texel buffer's uniform reads over imported pages took less than `TEXEL_FASTER` of the +//! uniform buffer's at both; neither where its arms were not run. The medians of the GPUs the +//! bounds come from give their facts: NVIDIA's per-lane ratios, RADV's none, the Iris Xe's +//! texel ratio. +//! - **The record.** Its medians read back for its identity alone, whole and unchanged, and never +//! a record whose device arms were not run. + +use super::{ + arms, decode, encode, facts_of, record_name, Arm, Medians, ViewVerdict, ARMS, KERNELS, + PER_LANE_COSTLY, TEXEL_FASTER, +}; +use crate::in_place::DriverIdentity; +use metal2vulkan::bind::{CheckReads, CheckView}; +use metal2vulkan::device::DriverWorkaround; +use std::collections::BTreeSet; + +const LANES: DriverWorkaround = DriverWorkaround::UniformBufferPerLaneReadsSerialize; +const TEXELS: DriverWorkaround = DriverWorkaround::ExternalUniformReadsSkipACache; + +/// Medians of 1000 ns everywhere but the storage per-lane arms (`per_lane` times the uniform +/// buffer's) and the imported texel uniform arms (`texel` times the uniform buffer's there), +/// the imported arms all 0 where `host` is false. +fn medians(per_lane: [f64; 2], texel: [f64; 2], host: bool) -> Medians { + let mut out = [1000u64; ARMS]; + for (at, arm) in arms().iter().enumerate() { + let window = usize::from(arm.vecs != 64); + let pair = KERNELS[arm.kernel]; + out[at] = match (arm.host, pair) { + (true, _) if !host => 0, + (false, (CheckView::Storage, CheckReads::PerLane)) => { + (1000.0 * per_lane[window]) as u64 + } + (true, (CheckView::Texel, CheckReads::Uniform)) => (1000.0 * texel[window]) as u64, + _ => 1000, + }; + } + Medians(out) +} + +#[test] +fn the_facts_hold_only_below_their_bounds_at_both_windows() { + let below = PER_LANE_COSTLY - 0.01; + let above = PER_LANE_COSTLY + 0.01; + let texel_below = TEXEL_FASTER - 0.01; + let texel_above = TEXEL_FASTER + 0.01; + let facts = |m: Medians| m.costs().facts; + assert_eq!( + facts(medians([below; 2], [1.0; 2], true)), + BTreeSet::from([LANES]) + ); + assert_eq!( + facts(medians([below, above], [1.0; 2], true)), + BTreeSet::new(), + "one window past the bound" + ); + assert_eq!( + facts(medians([above; 2], [texel_below; 2], true)), + BTreeSet::from([TEXELS]) + ); + assert_eq!( + facts(medians([1.0; 2], [texel_below, texel_above], true)), + BTreeSet::new() + ); + assert_eq!( + facts(medians([below; 2], [texel_below; 2], true)), + BTreeSet::from([LANES, TEXELS]), + "both hold together" + ); + assert_eq!( + facts(medians([1.0; 2], [texel_below; 2], false)), + BTreeSet::new(), + "no imported pages, no texel fact" + ); + let costs = medians([0.5, 0.25], [1.0; 2], false).costs(); + assert_eq!(costs.verdict, ViewVerdict::Measured); + assert_eq!(costs.per_lane, Some(0.5), "the larger window's ratio"); + assert_eq!(costs.texel, None); +} + +/// The ratios the bounds come from give their facts: NVIDIA's storage per-lane reads at 0.011 to +/// 0.107 of the uniform buffer's (the per-lane fact), RADV's at 0.96 to 1.00 (none), and the Iris +/// Xe's texel uniform reads over imported memory at 0.40 to 0.49 of the uniform buffer's (the +/// texel fact), a driver reading both alike over imported memory none. +#[test] +fn the_measured_gpus_get_their_facts() { + assert_eq!(facts_of(Some(0.107), Some(1.0)), BTreeSet::from([LANES])); + assert_eq!(facts_of(Some(0.011), None), BTreeSet::from([LANES])); + assert_eq!(facts_of(Some(0.96), Some(0.98)), BTreeSet::new()); + assert_eq!(facts_of(Some(1.0), Some(0.49)), BTreeSet::from([TEXELS])); + assert_eq!(facts_of(None, None), BTreeSet::new()); +} + +/// The arms: each window's eight device arms, then each window's two imported ones. +#[test] +fn the_arms_are_each_kernel_at_each_window_then_the_imported_ones() { + let arms = arms(); + assert_eq!(arms.len(), ARMS); + assert_eq!(arms.iter().filter(|arm| arm.host).count(), 4); + assert!(arms[..16].iter().all(|arm| !arm.host)); + let distinct: BTreeSet<(usize, bool, u32)> = (arms.iter()) + .map(|&Arm { kernel, host, vecs }| (kernel, host, vecs)) + .collect(); + assert_eq!(distinct.len(), ARMS); +} + +fn identity() -> DriverIdentity { + DriverIdentity { + vendor_id: 0x10de, + device_id: 0x1e87, + driver_version: 0x9b11_8000, + driver_id: 4, + driver_name: "NVIDIA".to_owned(), + driver_info: "620.70.06".to_owned(), + device_uuid: [7; 16], + } +} + +#[test] +fn a_record_reads_back_for_its_identity_alone() { + let identity = identity(); + let kept = medians([0.05, 0.1], [0.9, 1.1], true); + let bytes = encode(&identity, &kept); + assert_eq!(decode(&identity, &bytes), Some(kept)); + let unimported = medians([0.05, 0.1], [0.9, 1.1], false); + let bytes_unimported = encode(&identity, &unimported); + assert_eq!(decode(&identity, &bytes_unimported), Some(unimported)); + let mut other = identity.clone(); + other.driver_version += 1; + assert_eq!(decode(&other, &bytes), None, "another release"); + assert_ne!(record_name(&identity), record_name(&other)); + let mut flipped = bytes.clone(); + flipped[60] ^= 1; + assert_eq!(decode(&identity, &flipped), None, "the checksum"); + assert_eq!( + decode(&identity, &bytes[..bytes.len() - 1]), + None, + "cut short" + ); + let mut unrun = kept; + unrun.0[0] = 0; + assert_eq!(decode(&identity, &encode(&identity, &unrun)), None); +} + +/// An answer with facts makes the compile device of the description with them measured, whose +/// fingerprint differs from the description's own; an answer without makes none, and the device +/// keeps compiling with its own. +#[test] +fn an_answer_with_facts_makes_the_measured_compile_device() { + use super::{ViewCheck, ViewCosts}; + use metal2vulkan::device::{Device as CompileDevice, DeviceDescription, DevicePolicy}; + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/profiles/lavapipe.json"); + let text = std::fs::read_to_string(path).unwrap(); + let description = DeviceDescription::from_khronos_json(&text, None).unwrap(); + let policy = DevicePolicy::default(); + let base = CompileDevice::new(description.clone(), policy).unwrap(); + let check = ViewCheck::new(description.clone(), policy); + check.settle( + medians([1.0; 2], [1.0; 2], true).costs(), + None, + "none".to_owned(), + ); + assert!( + check.measured().is_none(), + "no fact, no other compile device" + ); + let check = ViewCheck::new(description, policy); + let costs = ViewCosts { + facts: BTreeSet::from([LANES, TEXELS]), + ..medians([0.05; 2], [0.4; 2], true).costs() + }; + check.settle(costs, None, "both".to_owned()); + let measured = check.measured().expect("the measured compile device"); + let workarounds = measured.profile().workarounds(); + assert!(workarounds.contains(&LANES) && workarounds.contains(&TEXELS)); + assert!(!base.profile().workarounds().contains(&LANES)); + assert_ne!(measured.profile_fingerprint(), base.profile_fingerprint()); +} diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index 413d86612..99a9c62dc 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -189,6 +189,7 @@ pub(crate) mod texel_rows; pub(crate) mod tile_map; pub(crate) mod tiled_texels; pub(crate) mod two_plane_texels; +pub(crate) mod view_check; pub(crate) mod visibility_combine; pub(crate) mod ycbcr_convert; pub(crate) mod ycbcr_in_place; @@ -311,6 +312,7 @@ pub use state::{ TextureShape, TileThreadgroupArgument, TileThreadgroupMemory, UsedClass, UsedResource, UsedShape, VertexAmplification, ViewMapping, ZERO_OFFSET_CLASS, ZERO_OFFSET_TOLD, }; +pub use view_check::{view_check_module, CheckReads, CheckView, ViewCheckModule}; // How `BindState::shape` classes a buffer: the crate reads it from `state`, and a consumer takes // shapes from `BindState::shape`; only the crate's tests and validation reach it here. pub use dynamic_views::{dynamic_views_module, DynamicViewsModule}; diff --git a/crates/metal2vulkan/src/bind/view_check.rs b/crates/metal2vulkan/src/bind/view_check.rs new file mode 100644 index 000000000..b52f00a48 --- /dev/null +++ b/crates/metal2vulkan/src/bind/view_check.rs @@ -0,0 +1,336 @@ +//! The kernels of the runtime's view check ([`view_check_module`]): what reading a `constant` +//! window costs through each view a uniform view can take, measured on the device itself. Its +//! verdicts are the description's measured workarounds +//! ([`DeviceDescription::measured`](crate::device::DeviceDescription::measured)): +//! `DriverWorkaround::UniformBufferPerLaneReadsSerialize` and +//! `DriverWorkaround::ExternalUniformReadsSkipACache`. +//! +//! **The module** (one per [`CheckView`] and [`CheckReads`]). One `GLCompute` entry `main` with +//! local size ([`ViewCheckModule::LOCAL_SIZE`], 1, 1), [`ViewCheckModule::PUSH_BYTES`] of `COMPUTE` +//! push constants at offset 0 ([`ViewCheckModule::push`]), and two bindings in set 0: +//! +//! | Binding | Buffer | +//! |---|---| +//! | [`ViewCheckModule::WINDOW_BINDING`] | the window, [`ViewCheckModule::WINDOW_VECS`] `uvec4`s: a uniform buffer (`Uniform`, std140), a storage buffer (`StorageBuffer`, std430) or a uniform texel buffer (`Dim` `Buffer`, `Sampled` 1, `u32` texels, viewed as `R32G32B32A32_UINT`) | +//! | [`ViewCheckModule::OUT_BINDING`] | a storage buffer of 4-byte words, one an invocation | +//! +//! The push words, in order: `mask`, the window's vectors less one (a power of two less one, at +//! most [`ViewCheckModule::WINDOW_VECS`] less one), and `reads`, the steps of each invocation's +//! loop; two words of 0. The mask is a push word, not a literal: a driver that sees an index +//! bounded at compile time may compile the read otherwise (ANV, Mesa 26.2.6 on the Iris Xe of +//! RPL-P, read a uniform buffer's one word 4.8 times as long with a literal mask). Invocation `g` +//! (`GlobalInvocationId.x`) starts with `acc = g` and, for `i` from 0 below `reads`, reads: +//! +//! - [`CheckReads::Uniform`]: vector `(7 i) & mask`, one address for every invocation; +//! - [`CheckReads::PerLane`]: vector `(g + 7 i) & mask`, each invocation its own; +//! - [`CheckReads::Fields`]: vectors 0 and 1, the same two at constant offsets every step (a +//! struct's fields); +//! +//! folding each vector `v` read as `acc = (acc ^ v.x) + ((v.y + v.z) ^ v.w)`, then `acc + i`, and +//! stores `acc` as word `g` of the out binding. Nothing else is read or written. + +use std::sync::Arc; + +use crate::budget::{Budget, Meter}; +use crate::device::requirements::Requirements; +use crate::device::Device; +use crate::error::{Error, InternalError, InternalKind}; +use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, Symbol}; +use crate::spirv::builder::FunctionBuilder; +use crate::spirv::builder::ModuleBuilder; +use crate::spirv::error::BResult; +use crate::spirv::ids::{GlobalId, TypeId, Value}; +use crate::spirv::ir::{ + natural_layout, BinOp, ConstBits, Constant, Dim, ExecMode, ExecModel, ImageOperands, ImageType, + ImageUsage, IoDir, LayoutRule, MemAccess, StorageClass, Type, TypedModule, +}; + +use super::index_rewrite::for_range; +use super::shadow_merge::{u32_value, words_buffer}; + +/// The view a [`view_check_module`] reads its window through. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CheckView { + /// A uniform buffer (`UNIFORM_BUFFER`). + Uniform, + /// A storage buffer (`STORAGE_BUFFER`). + Storage, + /// A uniform texel buffer (`UNIFORM_TEXEL_BUFFER`) of `R32G32B32A32_UINT` texels. + Texel, +} + +impl CheckView { + /// Every view. + pub const ALL: [CheckView; 3] = [CheckView::Uniform, CheckView::Storage, CheckView::Texel]; +} + +/// Which vectors of the window a [`view_check_module`]'s invocations read (the module docs). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CheckReads { + /// One address for every invocation, a new one each step. + Uniform, + /// Each invocation its own address, a new one each step. + PerLane, + /// The same two vectors at constant offsets, every step. + Fields, +} + +impl CheckReads { + /// Every pattern. + pub const ALL: [CheckReads; 3] = [CheckReads::Uniform, CheckReads::PerLane, CheckReads::Fields]; +} + +/// A view check kernel of one device, validated like any output. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ViewCheckModule { + /// SPIR-V words, entry point `main`, bindings numbered as the module docs say in set 0. + pub spirv: Arc<[u32]>, + /// What the module needs from the device (within every Vulkan 1.2 device). + pub requirements: Requirements, +} + +impl ViewCheckModule { + /// Descriptor set of every binding. + pub const SET: u32 = 0; + /// The window: the view's binding. + pub const WINDOW_BINDING: u32 = 0; + /// The words the invocations store, a storage buffer. + pub const OUT_BINDING: u32 = 1; + /// The `uvec4`s the window's declaration holds: 4 KiB. A dispatch reads the first `mask + 1`. + pub const WINDOW_VECS: u32 = 256; + /// Invocations of one workgroup, along x. + pub const LOCAL_SIZE: u32 = 64; + /// Bytes of the `COMPUTE` push-constant range at offset 0. + pub const PUSH_BYTES: u32 = 16; + + /// The push bytes of a dispatch reading the window's first `vecs` vectors (a power of two, at + /// most [`WINDOW_VECS`](Self::WINDOW_VECS)) `reads` times in each invocation. + pub fn push(vecs: u32, reads: u32) -> [u8; 16] { + let words = [vecs.saturating_sub(1), reads, 0, 0]; + let mut bytes = [0; 16]; + for (chunk, word) in bytes.as_chunks_mut::<4>().0.iter_mut().zip(words) { + chunk.copy_from_slice(&word.to_le_bytes()); + } + bytes + } +} + +/// The binding symbol of the window in the typed module. +const WINDOW: ResourceSlot = ResourceSlot { + stage: Stage::Kernel, + kind: ResourceKind::Buffer, + index: 0, +}; +/// The binding symbol of the out words in the typed module. +const OUT: ResourceSlot = ResourceSlot { + stage: Stage::Kernel, + kind: ResourceKind::Buffer, + index: 1, +}; + +/// The push field the words are declared under: a crate-owned module's own, which no selection +/// places. +const SHAPE: PushField = PushField::DispatchRegion; + +/// The window's declaration through `view`. +fn window(b: &mut ModuleBuilder, view: CheckView, u32_: TypeId) -> BResult { + let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?; + let (class, rule, member) = match view { + CheckView::Texel => { + let image = b.ty(Type::Image(ImageType { + sampled_type: u32_, + dim: Dim::Buffer, + depth: false, + arrayed: false, + multisampled: false, + usage: ImageUsage::Sampled, + format: crate::spv::ImageFormat::Unknown, + }))?; + return b.resource(WINDOW, StorageClass::UniformConstant, image); + } + CheckView::Uniform => { + let len = b.constant(Constant::Scalar { + ty: u32_, + bits: ConstBits(u64::from(ViewCheckModule::WINDOW_VECS)), + })?; + let array = b.ty(Type::Array { + elem: uvec4, + len, + stride: Some(16), + })?; + (StorageClass::Uniform, LayoutRule::Std140, array) + } + CheckView::Storage => { + let array = b.ty(Type::RuntimeArray { + elem: uvec4, + stride: Some(16), + })?; + (StorageClass::StorageBuffer, LayoutRule::Std430, array) + } + }; + let layout = natural_layout(b.types(), rule, true, &[member])?; + let block = b.ty(Type::Struct { + members: [member].into(), + layout: Some(layout), + })?; + b.resource(WINDOW, class, block) +} + +/// Vector `index` of the window `global` through `view`: a `uvec4`. +fn read( + f: &mut FunctionBuilder<'_>, + view: CheckView, + global: GlobalId, + index: Value, +) -> BResult { + let base = f.module().global_value(global)?; + match view { + CheckView::Texel => { + let image = f.load(base, MemAccess::default())?; + f.fetch(image, index, &ImageOperands::default()) + } + CheckView::Uniform | CheckView::Storage => { + let zero = u32_value(f, 0)?; + let p = f.access_chain(base, &[zero, index])?; + f.load(p, MemAccess::default()) + } + } +} + +/// `acc` with the vector `v` folded in (the module docs). +fn fold(f: &mut FunctionBuilder<'_>, acc: Value, v: Value) -> BResult { + let x = f.composite_extract(v, &[0])?; + let y = f.composite_extract(v, &[1])?; + let z = f.composite_extract(v, &[2])?; + let w = f.composite_extract(v, &[3])?; + let a = f.binary(BinOp::BitwiseXor, acc, x)?; + let b = f.binary(BinOp::IAdd, y, z)?; + let b = f.binary(BinOp::BitwiseXor, b, w)?; + f.binary(BinOp::IAdd, a, b) +} + +/// The view check kernel of `view` and `reads` as a typed module, before serialization (the +/// module docs). +pub(crate) fn typed_module(view: CheckView, reads: CheckReads) -> BResult { + let mut b = ModuleBuilder::new(); + let u32_ = b.ty(Type::Int { + width: 32, + signed: false, + })?; + let uvec3 = b.ty(Type::Vector { elem: u32_, len: 3 })?; + let uvec4 = b.ty(Type::Vector { elem: u32_, len: 4 })?; + let m_shape = b.push_member(SHAPE, uvec4, 0)?; + let push = b.push_global()?; + let window = window(&mut b, view, u32_)?; + let out = words_buffer(&mut b, OUT, u32_)?; + let global = b.builtin(crate::spv::BuiltIn::GlobalInvocationId, IoDir::Input, uvec3)?; + let void = b.ty(Type::Void)?; + let mut f = b.function(void)?; + let zero = u32_value(&mut f, 0)?; + let one = u32_value(&mut f, 1)?; + let seven = u32_value(&mut f, 7)?; + let global = f.module().global_value(global)?; + let global = f.load(global, MemAccess::default())?; + let g = f.composite_extract(global, &[0])?; + let push = f.module().global_value(push)?; + let member = u32_value(&mut f, m_shape.index)?; + let shape = f.access_chain(push, &[member])?; + let shape = f.load(shape, MemAccess::default())?; + let mask = f.composite_extract(shape, &[0])?; + let steps = f.composite_extract(shape, &[1])?; + let acc = f.local_var(u32_, None)?; + let acc = f.var_ptr(acc)?; + f.store(acc, g, MemAccess::default())?; + for_range(&mut f, u32_, (zero, steps, one), move |f, i| { + let mut now = f.load(acc, MemAccess::default())?; + let step = f.binary(BinOp::IMul, i, seven)?; + let indices = match reads { + CheckReads::Uniform => vec![f.binary(BinOp::BitwiseAnd, step, mask)?], + CheckReads::PerLane => { + let at = f.binary(BinOp::IAdd, g, step)?; + vec![f.binary(BinOp::BitwiseAnd, at, mask)?] + } + CheckReads::Fields => vec![zero, one], + }; + for index in indices { + let v = read(f, view, window, index)?; + now = fold(f, now, v)?; + } + let now = f.binary(BinOp::IAdd, now, i)?; + f.store(acc, now, MemAccess::default()) + })?; + let out = f.module().global_value(out)?; + let done = f.load(acc, MemAccess::default())?; + let p = f.access_chain(out, &[zero, g])?; + f.store(p, done, MemAccess::default())?; + f.ret(None)?; + let id = f.finish()?; + b.entry( + ExecModel::GLCompute, + id, + vec![ExecMode::LocalSize { + x: ViewCheckModule::LOCAL_SIZE, + y: 1, + z: 1, + }], + )?; + b.finalize() +} + +/// The fixed binding numbers of the module's symbols. +fn binding_of(sym: &Symbol) -> Option { + match sym { + Symbol::DescriptorSet(_) => Some(ViewCheckModule::SET), + Symbol::Binding(s) if *s == WINDOW => Some(ViewCheckModule::WINDOW_BINDING), + Symbol::Binding(s) if *s == OUT => Some(ViewCheckModule::OUT_BINDING), + _ => None, + } +} + +/// The view check kernel of `device` reading its window through `view` as `reads` says: built +/// with the typed builder, checked by the owned verifier against the device's profile +/// (requirements included), serialized, and numbered with the fixed bindings of +/// [`ViewCheckModule`]. An internal error where the profile lacks what it needs. +pub fn view_check_module( + device: &Device, + view: CheckView, + reads: CheckReads, +) -> Result { + let profile = device.profile(); + let m = typed_module(view, reads)?; + let mut meter = Meter::new(&Budget::default()); + crate::spirv::verify::verify(&m, profile, &mut meter)?; + let r = crate::spirv::serialize::serialize(m)?; + profile.check(&r.requirements).map_err(|c| { + Error::Internal(InternalError::new( + InternalKind::RequirementsExceedProfile, + format!("the view check's kernel needs {c:?}"), + )) + })?; + let words = crate::spirv::serialize::relocate(&r, &binding_of)?; + Ok(ViewCheckModule { + spirv: words.into(), + requirements: r.requirements, + }) +} + +#[cfg(test)] +mod tests { + use super::{typed_module, CheckReads, CheckView}; + use crate::spirv::testing::{assert_valid, committed_profiles}; + + /// Every view and pattern is valid on every committed profile. + #[test] + fn the_view_check_kernels_are_valid_on_every_committed_profile() { + for (_, p) in committed_profiles().expect("profiles") { + for view in CheckView::ALL { + for reads in CheckReads::ALL { + assert_valid(typed_module(view, reads).expect("module"), &p); + } + } + } + } +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 321bf572f..6fce27c1a 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2141; +pub const SEMANTICS_VERSION: u32 = 2142; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 525; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2493; +pub const RUNTIME_VERSION: u32 = 2495; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index 6c788929c..0347871cb 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -377,8 +377,9 @@ fn derive_fields( } /// The driver workarounds of the driver `desc` names (`driver_id`), on its GPU (`vendor_id`, or its -/// generation's `device_id`s) where the defect is the GPU's, and those of the measured table -/// (`driver_facts::DEFECTS`), in order. +/// generation's `device_id`s) where the defect is the GPU's, those of the measured table +/// (`driver_facts::DEFECTS`), and those the consumer measured on the device itself +/// ([`DeviceDescription::measured`]), in order. fn workarounds(desc: &DeviceDescription) -> Vec { let mut found = by_identity(desc); // Every rasterizer but Apple's hands a clipped primitive's fragments their coverage by the @@ -389,6 +390,7 @@ fn workarounds(desc: &DeviceDescription) -> Vec { found.push(DriverWorkaround::TessellatorNotMetals); } found.extend(super::driver_facts::defects(desc)); + found.extend(desc.measured.iter().copied()); found.sort(); found.dedup(); found diff --git a/crates/metal2vulkan/src/device/description.rs b/crates/metal2vulkan/src/device/description.rs index dd6858840..4f73bbad5 100644 --- a/crates/metal2vulkan/src/device/description.rs +++ b/crates/metal2vulkan/src/device/description.rs @@ -10,7 +10,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use crate::device::profile::{FloatControls, Limits}; +use crate::device::profile::{DriverWorkaround, FloatControls, Limits}; use crate::device::requirements::{ApiVersion, FormatUsage, VkExtension, VkFeature}; use crate::vk; @@ -82,6 +82,15 @@ pub struct DeviceDescription { /// `maxBufferLength` and the runtime's heap sizes read them from the `Device`. #[cfg_attr(feature = "serde", serde(default))] pub allocation: AllocationLimits, + /// The driver workarounds the consumer measured on this device itself, which the profile + /// takes beside those its driver's identity names: the cost facts no identity decides, + /// [`DriverWorkaround::UniformBufferPerLaneReadsSerialize`] and + /// [`DriverWorkaround::ExternalUniformReadsSkipACache`], which the runtime's view check + /// measures once per driver and release. A profile field (its workarounds), so its fingerprint + /// and every cache key follow it. Empty unless the consumer fills it (`new`, `query` and + /// `from_khronos_json` leave it so). + #[cfg_attr(feature = "serde", serde(default))] + pub measured: BTreeSet, } /// A device's allocation sizes, [`DeviceDescription::allocation`]: device facts that size @@ -186,6 +195,7 @@ impl DeviceDescription { khr_format_feature_flags2: false, generated_commands: None, allocation: AllocationLimits::default(), + measured: BTreeSet::new(), } } diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index 51fa8830c..b9b7ff278 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -17,7 +17,9 @@ //! runtime's device checks measure it on each device, once per driver and release (whether its //! submissions that signal nothing merge, whether a held host-pointer import adds to each //! submission's cost: the runtime's `submit_check.rs`; textures in place over host pages, -//! `in_place_check.rs`; the GPU's idling between `VkQueue`s, `queue_switch_check.rs`). +//! `in_place_check.rs`; the GPU's idling between `VkQueue`s, `queue_switch_check.rs`; what a +//! `constant` window's reads cost through each view, `view_check.rs`, whose verdicts reach +//! translation as the description's measured workarounds, [`DeviceDescription::measured`]). use crate::device::description::APPLE_VENDOR_ID; use crate::device::profile::DriverWorkaround; @@ -743,9 +745,6 @@ const NVIDIA_VENDOR_ID: u32 = 0x10de; /// The `deviceID` of the GeForce RTX 3090. pub(crate) const NVIDIA_RTX_3090: u32 = 0x2204; -/// The `deviceID` of the GeForce RTX 2080 (Turing TU104). -pub(crate) const NVIDIA_RTX_2080: u32 = 0x1e87; - /// The `deviceID` of the GeForce RTX 5080 Laptop GPU (the committed capture /// `nvidia-rtx5080-laptop`). pub(crate) const NVIDIA_RTX_5080_LAPTOP: u32 = 0x2c19; @@ -898,27 +897,6 @@ const fn moltenvk_on_apple(fact: F) -> Measured { /// commonest bind, takes, and its general form, which one binding a storage view elsewhere takes /// at once; with the general form alone, every state's first command at offset 0 made a second /// pipeline. -/// - `UniformBufferPerLaneReadsSerialize`: NVIDIA's 620.70.06 on the RTX 3090 (job m3-max-37848) -/// and the RTX 2080 (job m3-max-37839) and 615.71.09 on the RTX 5080 Laptop GPU (job -/// m3-max-37858) read a 1 to 32 KiB window of device-local memory, each invocation its own word -/// or its own walk (256 workgroups of 64 invocations, 64 and 1024 `uvec4` reads each, the -/// uniform block declared at the window's size), through a storage buffer in 0.011 to 0.18 of -/// a uniform buffer's time, and with every invocation reading one word in 0.96 to 1.68 times -/// it. A cost fact: it only chooses between two exact encodings. RADV on the Radeon 780M and -/// the RX 7900 XTX is not listed (jobs m3-max-37803 and m3-max-37788: a uniform texel buffer -/// read each invocation's own word in 0.96 to 1.00 of the uniform buffer's time); the rows name -/// the three GPUs measured. -/// - `ExternalUniformReadsSkipACache`: ANV, Mesa 26.2.6 on the Iris Xe of RPL-P, read a 1 KiB -/// window through a uniform buffer over a host allocation or a udmabuf 2.0 to 2.5 times as long -/// as over its own memory with every invocation reading one word, and 5.2 to 5.5 times with each -/// reading its own (256 workgroups of 64 invocations, 64 and 1024 reads each; jobs m3-max-37703, -/// m3-max-37729 and m3-max-37780), and through a uniform texel buffer 0.98 to 1.04 times as -/// long. Over its own memory the texel buffer took 0.14 to 0.997 of the uniform buffer's time -/// for windows of 1 and 4 KiB in each of four patterns (the same word, a word each, a walk per -/// workgroup and one per invocation), one pattern 1.031 at 16 KiB, and the per-invocation -/// patterns 2.8 to 4.2 times from 32 KiB (jobs m3-max-37753 and m3-max-37780): the bound -/// (`memory::views::TEXEL_WINDOW_BYTES`) is 4 KiB. A cost fact: it only chooses between two -/// exact encodings, and the row names the GPU measured. pub(crate) const DEFECTS: &[Measured] = &[ Measured { fact: DriverWorkaround::BothBarycentricFormsRejected, @@ -993,23 +971,6 @@ pub(crate) const DEFECTS: &[Measured] = &[ DriverId::INTEL_OPEN_SOURCE_MESA, (INTEL_VENDOR_ID, INTEL_IRIS_XE_RPL_P), ), - nvidia_on( - DriverWorkaround::UniformBufferPerLaneReadsSerialize, - NVIDIA_RTX_3090, - ), - nvidia_on( - DriverWorkaround::UniformBufferPerLaneReadsSerialize, - NVIDIA_RTX_2080, - ), - nvidia_on( - DriverWorkaround::UniformBufferPerLaneReadsSerialize, - NVIDIA_RTX_5080_LAPTOP, - ), - mesa_on( - DriverWorkaround::ExternalUniformReadsSkipACache, - DriverId::INTEL_OPEN_SOURCE_MESA, - (INTEL_VENDOR_ID, INTEL_IRIS_XE_RPL_P), - ), ]; /// The defects translation works around on the driver `description` names, on its GPU. diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index bcba37f56..36f52d0d6 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -1195,11 +1195,17 @@ pub struct FormatTable { /// and Metal's differs from, which a module records as the precision note it names; or a measured /// cost of the driver's that chooses between two exact encodings. Each variant comes with a test. /// The profile derives them from the description's driver identity (`driver_id`, with the vendor -/// where the defect is the GPU's), never from a shader. +/// where the defect is the GPU's), never from a shader, and takes those the consumer measured on +/// the device itself ([`DeviceDescription::measured`]): the two view costs +/// [`UniformBufferPerLaneReadsSerialize`](Self::UniformBufferPerLaneReadsSerialize) and +/// [`ExternalUniformReadsSkipACache`](Self::ExternalUniformReadsSkipACache) come from such a +/// measurement alone (the runtime's view check), never from an identity. /// /// [`Needs::DriverDefect`]: crate::error::Needs::DriverDefect +/// [`DeviceDescription::measured`]: crate::device::DeviceDescription::measured #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum DriverWorkaround { /// The driver's `robustBufferAccess` does not keep a storage buffer's atomic inside the /// buffer: SwiftShader (`VK_DRIVER_ID_GOOGLE_SWIFTSHADER`) masks an atomic by the texel's @@ -1604,44 +1610,46 @@ pub enum DriverWorkaround { PushReadsLengthenThreadPayload, /// A uniform-buffer read whose address differs between the lanes that run it together takes /// many times as long as the same read of a storage buffer, while one address for every lane - /// is read faster through the uniform buffer. A measured cost fact (`device::driver_facts`) - /// that chooses between two exact encodings of a `constant` slot. - /// Measured with a bare Vulkan program (256 workgroups of 64 invocations, each adding 64 or - /// 1024 `uvec4` reads of a window of 1, 4, 16 or 32 KiB of device-local memory, the uniform - /// block declared at the window's size; median of 15 dispatches) on NVIDIA's driver - /// (`VK_DRIVER_ID_NVIDIA_PROPRIETARY`): with each invocation reading its own word, or walking - /// the window per invocation, the storage buffer took 0.011 to 0.16 of the uniform buffer's - /// time on the GeForce RTX 3090 (Ampere, 620.70.06, job m3-max-37848), 0.026 to 0.18 on the - /// RTX 2080 (Turing, 620.70.06, job m3-max-37839) and 0.012 to 0.12 on the RTX 5080 Laptop GPU - /// (Blackwell, 615.71.09, job m3-max-37858), and a uniform texel buffer took 0.37 to 3.1 times - /// the storage buffer's; with every invocation reading one word the storage buffer took 0.96 - /// to 1.68 times the uniform buffer's. Its rows name those three GPUs, the GPUs measured. - /// RADV on the Radeon 780M and the RX 7900 XTX read each invocation's own word through a - /// uniform texel buffer in 0.96 to 1.00 of the uniform buffer's time (jobs m3-max-37803 and - /// m3-max-37788), so AMD has no such fact. There a `constant` slot with a read whose address - /// may differ between the lanes that run it together (`memory::plan`'s lane reads) keeps its - /// storage view in place of a uniform view (`lower::access::view_kind`); a slot read at - /// uniform addresses alone keeps its uniform view. Compute was measured; the graphics stages - /// take the rule too, expected to read alike, not measured. It changes no answer. + /// is read faster through the uniform buffer: a measured cost fact that chooses between two + /// exact encodings of a `constant` slot. Never keyed on an identity: the profile takes it where + /// the description's [`measured`](crate::device::DeviceDescription::measured) set holds it, + /// which the runtime's view check decides on each driver (its storage view's time over its + /// uniform buffer's for per-lane reads below 0.3). Measured with a bare Vulkan program (256 + /// workgroups of 64 invocations, each adding 64 or 1024 `uvec4` reads of a window of 1 to + /// 32 KiB of device-local memory; median of 15 dispatches): with each invocation reading its + /// own word, or walking the window per invocation, the storage buffer took 0.011 to 0.16 of the + /// uniform buffer's time on NVIDIA's driver on the GeForce RTX 3090 (620.70.06, job + /// m3-max-37848), 0.026 to 0.18 on the RTX 2080 (620.70.06, m3-max-37839) and 0.012 to 0.12 on + /// the RTX 5080 Laptop GPU (615.71.09, m3-max-37858); with every invocation reading one word, + /// 0.96 to 1.68 times it. RADV on the Radeon 780M and the RX 7900 XTX read each invocation's + /// own word through either at 0.96 to 1.00 of the other (jobs m3-max-37803 and m3-max-37788). + /// Where the profile takes it, a `constant` slot with a read whose address may differ between + /// the lanes that run it together (`memory::plan`'s lane reads) keeps its storage view in + /// place of a uniform view (`lower::access::view_kind`); a slot read at uniform addresses alone + /// keeps its uniform view. Compute was measured; the graphics stages take the rule too, + /// expected to read alike, not measured. It changes no answer. UniformBufferPerLaneReadsSerialize, - /// Uniform-buffer reads of external memory skip a cache the same reads of the device's own - /// memory use: a measured cost fact (`device::driver_facts`) that chooses between two exact - /// encodings of a uniform view. ANV (`VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA`), Mesa 26.2.6, on - /// the Iris Xe of RPL-P gives the surface of memory imported or exported (a host allocation, a - /// dma-buf, an opaque fd) the memory object control state of a displayable surface, which - /// leaves out the data port's L1 cache that a uniform-buffer surface of the device's own memory - /// is given (Mesa's `isl_mocs` and `anv_device.c`, Linux i915's Gen12 MOCS table; read, not - /// measured). Measured (jobs m3-max-37703, m3-max-37729 and m3-max-37780): a kernel reading a - /// 1 KiB window through a uniform buffer over a host allocation or a udmabuf took 2.0 to 2.5 - /// times as long as over the device's own memory with every invocation reading one word, and - /// 5.2 to 5.5 times with each reading its own, on every memory type the imports allow; the - /// same reads through a uniform texel buffer, whose sampler reads keep their caches, took 0.98 - /// to 1.04 times as long as over the device's own memory, and for windows of up to 4 KiB no - /// longer than the uniform buffer there. Keyed on the driver and that GPU alone. There a - /// uniform view of a window of at most `memory::views::TEXEL_WINDOW_BYTES` is a uniform texel - /// buffer of `R32G32B32A32_UINT` texels read with `OpImageFetch` (`DescriptorView::UniformTexel`, - /// `lower::access::view_kind`), and a longer window keeps its uniform buffer. It changes no - /// answer. + /// Uniform-buffer reads of external memory skip a cache that the same reads through a uniform + /// texel buffer keep: a measured cost fact that chooses between two exact encodings of a + /// uniform view. Never keyed on an identity: the profile takes it where the description's + /// [`measured`](crate::device::DeviceDescription::measured) set holds it, which the runtime's + /// view check decides on each driver (a uniform texel buffer's time over a uniform buffer's, + /// every invocation reading one word of imported host memory, below 0.7). ANV, Mesa 26.2.6, on + /// the Iris Xe of RPL-P gives imported and exported memory the memory object control state of + /// a displayable surface, which leaves out the data port's L1 cache a uniform buffer of the + /// device's own memory is given (Mesa's `isl_mocs`, Linux i915's Gen12 MOCS table; read, not + /// measured). Measured there (jobs m3-max-37703, m3-max-37729 and m3-max-37780): a uniform + /// buffer over a host allocation or a udmabuf took 2.0 to 2.5 times as long as over the + /// device's own memory with every invocation reading one word of a 1 KiB window, and 5.2 to + /// 5.5 times with each reading its own; a uniform texel buffer 0.98 to 1.04 times, and for + /// windows of up to 4 KiB no longer than the uniform buffer there. Where the profile takes it, + /// the uniform view of a slot with an indexed read (`memory::plan`'s indexed reads) whose + /// window is at most `memory::views::TEXEL_WINDOW_BYTES` is a uniform texel buffer of + /// `R32G32B32A32_UINT` texels read with `OpImageFetch` (`DescriptorView::UniformTexel`, + /// `lower::access::view_kind`); a slot read at constant offsets alone, whose words a driver may + /// load ahead into registers as no texel fetch can be, and a longer window keep the uniform + /// buffer. With [`UniformBufferPerLaneReadsSerialize`](Self::UniformBufferPerLaneReadsSerialize) + /// too, a slot with a per-lane read keeps its storage view first. It changes no answer. ExternalUniformReadsSkipACache, } diff --git a/crates/metal2vulkan/src/device/tests/profile.rs b/crates/metal2vulkan/src/device/tests/profile.rs index 7af9eef50..fe617dfd0 100644 --- a/crates/metal2vulkan/src/device/tests/profile.rs +++ b/crates/metal2vulkan/src/device/tests/profile.rs @@ -365,8 +365,7 @@ fn streamed_fingerprint_equals_the_hash_of_the_rendering() { /// its allocation sizes, as two captures of one GPU under its two `deviceID`s do /// (`amd-780m-hawkpoint-radv` and `amd-780m-radv`, the Radeon 780M of Hawk Point and of Phoenix). /// `intel-irisxe-rplp-anv` and `intel-uhd770-rpls-anv`, one GPU family on one driver, differ by -/// workarounds measured on the Iris Xe alone (`DriverWorkaround::PushReadsLengthenThreadPayload`, -/// `DriverWorkaround::ExternalUniformReadsSkipACache`). +/// a workaround measured on the Iris Xe alone (`DriverWorkaround::PushReadsLengthenThreadPayload`). #[test] fn fingerprints_distinguish_committed_profiles() { let translated = |stem: &str| { @@ -1138,32 +1137,62 @@ fn large_module_defects_are_keyed_on_anv() { } } -/// `DriverWorkaround::ExternalUniformReadsSkipACache` is keyed on ANV on the Iris Xe of RPL-P, the -/// GPU it was measured on: that committed profile alone carries it, ANV on the UHD 770 of RPL-S -/// does not, and the Iris Xe's description under RADV's driver loses it. +/// The two view facts (`DriverWorkaround::UniformBufferPerLaneReadsSerialize` and +/// `DriverWorkaround::ExternalUniformReadsSkipACache`) come from the description's measured set +/// alone: no committed profile carries either by its identity, the GPUs they were first measured +/// on included (the RTX 5080 Laptop GPU's and the Iris Xe's captures, the RTX 3090's and the +/// RTX 2080's IDs), and any description that measured one carries it, its fingerprint another. #[test] -fn external_uniform_reads_fact_is_the_iris_xes_alone() { +fn view_facts_come_from_the_measured_set_alone() { use crate::device::profile::DriverWorkaround; - let fact = DriverWorkaround::ExternalUniformReadsSkipACache; - let takes = |desc: &DeviceDescription| { - Device::new(desc.clone(), DevicePolicy::default()) - .unwrap() - .profile() - .workarounds() - .contains(&fact) + let facts = [ + DriverWorkaround::UniformBufferPerLaneReadsSerialize, + DriverWorkaround::ExternalUniformReadsSkipACache, + ]; + let device = + |desc: &DeviceDescription| Device::new(desc.clone(), DevicePolicy::default()).unwrap(); + let carried = |desc: &DeviceDescription| { + let device = device(desc); + facts.map(|fact| device.profile().workarounds().contains(&fact)) }; - let mut carriers = Vec::new(); - for (stem, text) in committed_profiles() { - let desc = DeviceDescription::from_khronos_json(&text, None).unwrap(); - if takes(&desc) { - carriers.push(stem); + let mut nvidia = profile("nvidia-rtx5080-laptop"); + let mut identities = vec![nvidia.clone(), profile("intel-irisxe-rplp-anv")]; + for id in [0x2204, 0x1e87] { + nvidia.device_id = id; + identities.push(nvidia.clone()); + } + let committed = committed_profiles() + .into_iter() + .map(|(_, text)| DeviceDescription::from_khronos_json(&text, None).unwrap()); + for desc in identities.into_iter().chain(committed) { + assert_eq!(carried(&desc), [false, false], "{}", desc.device_name); + let unmeasured = device(&desc).profile_fingerprint(); + let mut fingerprints = vec![unmeasured]; + for (at, fact) in facts.into_iter().enumerate() { + let mut measured = desc.clone(); + measured.measured.insert(fact); + let mut expected = [false, false]; + expected[at] = true; + assert_eq!( + carried(&measured), + expected, + "{}: {fact:?}", + desc.device_name + ); + fingerprints.push(device(&measured).profile_fingerprint()); } + let mut both = desc.clone(); + both.measured.extend(facts); + assert_eq!(carried(&both), [true, true]); + fingerprints.push(device(&both).profile_fingerprint()); + let distinct: std::collections::BTreeSet<_> = fingerprints.iter().collect(); + assert_eq!( + distinct.len(), + 4, + "{}: each verdict its own fingerprint", + desc.device_name + ); } - assert_eq!(carriers, ["intel-irisxe-rplp-anv"]); - assert!(!takes(&profile("intel-uhd770-rpls-anv"))); - let mut desc = profile("intel-irisxe-rplp-anv"); - desc.driver_id = Some(vk::DriverId::MESA_RADV); - assert!(!takes(&desc)); } /// `DriverWorkaround::OppositeZeroProductsMerged` is keyed on ANV, whatever its GPU and release: @@ -1316,52 +1345,3 @@ fn nvidia_keeps_dont_inline_calls_on_its_measured_gpu() { assert!(!carries(&profile("amd-780m-radv"))); assert!(!carries(&profile("moltenvk-m3"))); } - -/// `DriverWorkaround::UniformBufferPerLaneReadsSerialize`, a cost fact, is keyed on the GPUs -/// measured with it: NVIDIA's driver on the RTX 3090, the RTX 2080 and the RTX 5080 Laptop GPU, at -/// every release. Another GPU of the vendor (the desktop RTX 50's committed profile, Pascal's), -/// another vendor's ID, another driver (NVK), and AMD's and Apple's committed profiles do not carry -/// it. -#[test] -fn nvidia_serializes_per_lane_uniform_reads_on_its_measured_gpus() { - use crate::device::driver_facts::{NVIDIA_RTX_2080, NVIDIA_RTX_3090}; - use crate::device::profile::DriverWorkaround; - let fact = DriverWorkaround::UniformBufferPerLaneReadsSerialize; - let carries = |desc: &DeviceDescription| { - Device::new(desc.clone(), DevicePolicy::default()) - .unwrap() - .profile() - .fields() - .workarounds - .contains(&fact) - }; - let mut desc = profile("nvidia-rtx5080-laptop"); - assert_eq!(desc.driver_id, Some(vk::DriverId::NVIDIA_PROPRIETARY)); - assert!( - carries(&desc), - "on the RTX 5080 Laptop GPU, where it was measured" - ); - for id in [NVIDIA_RTX_3090, NVIDIA_RTX_2080] { - desc.device_id = id; - assert!(carries(&desc), "on {id:#x}, where it was measured"); - } - desc.driver_version += 1 << 6; - assert!(carries(&desc), "at another release"); - desc.vendor_id = 0x1002; - assert!(!carries(&desc), "on another vendor's ID"); - desc.vendor_id = 0x10de; - desc.driver_id = Some(vk::DriverId::MESA_NVK); - assert!(!carries(&desc), "under NVK"); - for (stem, text) in committed_profiles() { - let desc = DeviceDescription::from_khronos_json(&text, None).unwrap(); - assert_eq!( - carries(&desc), - stem == "nvidia-rtx5080-laptop", - "{stem}: the RTX 5080 Laptop GPU's is the one committed profile of a measured GPU" - ); - } - assert!(!carries(&profile("nvidia-pascal-linux"))); - assert!(!carries(&profile("amd-780m-radv"))); - assert!(!carries(&profile("amd-rdna3-radv"))); - assert!(!carries(&profile("moltenvk-m3"))); -} diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index 87a4f2776..ff8e1f91d 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -999,8 +999,16 @@ pub fn param_value( /// `Bounded` window whose descriptor range fits `maxUniformBufferRange`, when the profile's /// containment encoding emits no check and the slot has no lane read; a storage view otherwise. /// The uniform view is a uniform texel buffer ([`texel_view`]) where the profile has -/// `DriverWorkaround::ExternalUniformReadsSkipACache` and the window is at most -/// [`views::TEXEL_WINDOW_BYTES`] long, a uniform buffer otherwise. +/// `DriverWorkaround::ExternalUniformReadsSkipACache`, the slot has an indexed read +/// ([`SlotPlan::indexed_read`]) and the window is at most [`views::TEXEL_WINDOW_BYTES`] long, a +/// uniform buffer otherwise: a slot read at constant offsets alone keeps its uniform buffer, whose +/// words a driver may load ahead into registers (ANV pushes such ranges: Mesa's +/// `brw_nir_analyze_ubo_ranges`; read, not measured), as no texel fetch can be. +/// +/// Both view facts compose: a lane read keeps its storage view whatever the texel fact, so on a +/// profile taking both, a slot with a per-lane read is a storage view, one whose indexed reads +/// are all uniform among the active lanes a uniform texel buffer (within the bound), and one read +/// at constant offsets alone a uniform buffer. /// /// Under the in-shader encoding a uniform view could not be contained: the bound range may be /// shorter than the view's declared size (the binder clamps it to the padded allocation), a uniform @@ -1031,9 +1039,9 @@ pub fn view_kind(p: &DeviceProfile, s: &SlotPlan) -> ViewKind { _ => None, }; match (uniform, s.window) { - (Some(bytes), Some(window)) => { - texel_view(p, window).unwrap_or_else(|| uniform_view(p, bytes)) - } + (Some(bytes), Some(window)) => (s.indexed_read.then(|| texel_view(p, window))) + .flatten() + .unwrap_or_else(|| uniform_view(p, bytes)), _ => ViewKind::Storage, } } diff --git a/crates/metal2vulkan/src/memory/plan.rs b/crates/metal2vulkan/src/memory/plan.rs index f06335f39..0ee2d4ff2 100644 --- a/crates/metal2vulkan/src/memory/plan.rs +++ b/crates/metal2vulkan/src/memory/plan.rs @@ -106,6 +106,13 @@ pub struct SlotPlan { /// read (`constant`, read-only, no atomic, a `Bounded` window): such a slot keeps its storage /// view (`lower::access::view_kind`). False on every other profile and slot. pub lane_read: bool, + /// Some read reaches the slot at an index the translation computes + /// ([`Provenance::indexed_constant_reads`]), on a profile taking + /// `DriverWorkaround::ExternalUniformReadsSkipACache`, for a slot a uniform view could read: + /// only such a slot's uniform view may take its texel form (`lower::access::texel_view`). A + /// slot read at constant offsets alone (a struct's fields) has none. False on every other + /// profile and slot. + pub indexed_read: bool, } /// An object in an arena. @@ -1005,6 +1012,7 @@ impl Planner<'_> { window: escaped_window(window::window(eu.extent, None, dynamic), eu), guest_base: eu.escapes || eu.cross_compare, lane_read: false, + indexed_read: false, }); } continue; @@ -1032,20 +1040,25 @@ impl Planner<'_> { window: escaped_window(window::window(u.extent, arg.buffer_size, dynamic), &u), guest_base: u.escapes || u.cross_compare, lane_read: false, + indexed_read: false, }); } Ok(slots) } - /// `slots` with [`SlotPlan::lane_read`] marked, on a profile taking - /// `DriverWorkaround::UniformBufferPerLaneReadsSerialize`: a slot a uniform view could read - /// with an indexed read ([`Provenance::indexed_constant_reads`]) whose pointer is not uniform - /// among the active lanes. The analysis runs once, only where such a slot has an indexed read - /// (a slot read at constant offsets alone, a struct's fields, has none), and its bytes are - /// released before return. + /// `slots` with [`SlotPlan::indexed_read`] and [`SlotPlan::lane_read`] marked: on a profile + /// taking `DriverWorkaround::ExternalUniformReadsSkipACache`, a slot a uniform view could read + /// with an indexed read ([`Provenance::indexed_constant_reads`]) is an indexed read's; on one + /// taking `DriverWorkaround::UniformBufferPerLaneReadsSerialize`, such a slot whose indexed + /// read's pointer is not uniform among the active lanes is a lane read's. The analysis runs + /// once, only on the latter profile and only where such a slot has an indexed read (a slot read + /// at constant offsets alone, a struct's fields, has none), and its bytes are released before + /// return. fn lane_reads(&self, mut slots: Vec, m: &mut Meter) -> Result, Error> { - let fact = DriverWorkaround::UniformBufferPerLaneReadsSerialize; - if !self.p.workarounds().contains(&fact) { + let workarounds = self.p.workarounds(); + let lanes = workarounds.contains(&DriverWorkaround::UniformBufferPerLaneReadsSerialize); + let texels = workarounds.contains(&DriverWorkaround::ExternalUniformReadsSkipACache); + if !lanes && !texels { return Ok(slots); } let candidate = |s: &SlotPlan, r: Root| { @@ -1065,12 +1078,12 @@ impl Planner<'_> { let mut any = false; for &(r, _) in reads { m.tick(1)?; - if slots.iter().any(|s| candidate(s, r)) { + if let Some(s) = slots.iter_mut().find(|s| candidate(s, r)) { + s.indexed_read = texels; any = true; - break; } } - if !any { + if !any || !lanes { return Ok(slots); } let body = self diff --git a/crates/metal2vulkan/src/memory/views.rs b/crates/metal2vulkan/src/memory/views.rs index 2a8f4f6f5..02db0a1cd 100644 --- a/crates/metal2vulkan/src/memory/views.rs +++ b/crates/metal2vulkan/src/memory/views.rs @@ -14,8 +14,9 @@ //! - [`ViewKind::UniformTexel`]: a uniform texel buffer (`UniformConstant`, an image of `Dim` //! `Buffer`, `Sampled` 1, `u32` texels) that the binder views as `R32G32B32A32_UINT`, read with //! `OpImageFetch`; a word is one lane of a fetched texel. A slot takes it in place of a uniform -//! buffer only where its profile has `DriverWorkaround::ExternalUniformReadsSkipACache` and its -//! window is at most [`TEXEL_WINDOW_BYTES`] long (`lower::access::view_kind`). +//! buffer only where its profile has `DriverWorkaround::ExternalUniformReadsSkipACache`, the +//! slot has an indexed read (`SlotPlan::indexed_read`) and its window is at most +//! [`TEXEL_WINDOW_BYTES`] long (`lower::access::view_kind`). //! //! Uniform views exist only for read-only slots with a `Bounded` window whose descriptor range //! fits `maxUniformBufferRange` ([`uniform_range`]), a texel one's also `maxTexelBufferElements` diff --git a/crates/metal2vulkan/src/tests/engine_access.rs b/crates/metal2vulkan/src/tests/engine_access.rs index 48c9cf280..3e475e298 100644 --- a/crates/metal2vulkan/src/tests/engine_access.rs +++ b/crates/metal2vulkan/src/tests/engine_access.rs @@ -349,9 +349,52 @@ fn a_uniform_view_read_at_its_bind_offset_drops_the_residual() { /// Xe RPL-P under ANV, where the row was measured. const AT_BIND_PROFILE: &str = "intel-irisxe-rplp-anv"; -/// The committed profile that takes `DriverWorkaround::ExternalUniformReadsSkipACache`: the Iris -/// Xe RPL-P under ANV, where the row was measured. -const TEXEL_PROFILE: &str = "intel-irisxe-rplp-anv"; +/// A committed profile, its description measuring `DriverWorkaround::ExternalUniformReadsSkipACache` +/// where `measured` (the fact comes from that set alone), with `uniformBufferStandardLayout` or +/// without. +fn texel_profile(stem: &str, measured: bool, standard_layout: bool) -> DeviceProfile { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/profiles") + .join(format!("{stem}.json")); + let text = std::fs::read_to_string(path).expect("profile"); + let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); + if !standard_layout { + desc.features + .remove(&VkFeature::UniformBufferStandardLayout); + } + if measured { + (desc.measured).insert(DriverWorkaround::ExternalUniformReadsSkipACache); + } + Device::new(desc, policy()) + .expect("device") + .profile() + .clone() +} + +/// A kernel reading byte `i` of a `constant` window of 6 bytes, `i` the first word of its +/// `device` buffer 2 (an indexed read: no constant offset), into word 0 of buffer 1. +const INDEXED_BYTE: &str = r#"define void @indexed_byte_load(ptr addrspace(2) noundef "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1, ptr addrspace(1) noundef "air-buffer-no-alias" %2) { +entry: + %i = load i32, ptr addrspace(1) %2, align 4 + %ix = zext i32 %i to i64 + %p = getelementptr inbounds [6 x i8], ptr addrspace(2) %0, i64 0, i64 %ix + %v = load i8, ptr addrspace(2) %p, align 1 + %w = zext i8 %v to i32 + store i32 %w, ptr addrspace(1) %1, align 4 + ret void +} +!air.kernel = !{!10} +!air.version = !{!17} +!air.language_version = !{!18} +!10 = !{ptr @indexed_byte_load, !11, !12} +!11 = !{} +!12 = !{!13, !14, !15} +!13 = !{i32 0, !"air.buffer", !"air.buffer_size", i32 6, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.arg_type_size", i32 6, !"air.arg_type_align_size", i32 1, !"air.arg_type_name", !"Six", !"air.arg_name", !"c"} +!14 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!15 = !{i32 2, !"air.buffer", !"air.location_index", i32 2, i32 1, !"air.read", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"at"} +!17 = !{i32 2, i32 8, i32 0} +!18 = !{!"Metal", i32 4, i32 0, i32 0} +"#; /// The bytes of a uniform texel buffer of `bytes` (a multiple of 16) as its `R32G32B32A32_UINT` /// texels, bound at slot `index`. @@ -366,23 +409,28 @@ fn texel_buffer(index: u32, bytes: &[u8]) -> Image { image } -/// On the profile that takes `DriverWorkaround::ExternalUniformReadsSkipACache`, a `constant` -/// slot of a short window reads through a uniform texel buffer: its form is -/// `DescriptorView::UniformTexel`, the slot's one variable is a `UniformConstant` sampled image of -/// `Dim` `Buffer` (no `Uniform` block), the module passes L3, and the read takes the last byte at -/// the residual pushed, at residuals 0, 4, 16 and 256, with `uniformBufferStandardLayout` and -/// without. ANV on the UHD 770 of RPL-S, which does not take the fact, keeps the uniform buffer. +/// On a profile whose description measured `DriverWorkaround::ExternalUniformReadsSkipACache`, a +/// `constant` slot of a short window with an indexed read reads through a uniform texel buffer: +/// its form is `DescriptorView::UniformTexel`, the slot's one variable is a `UniformConstant` +/// sampled image of `Dim` `Buffer` (no `Uniform` block), the module passes L3, and the read takes +/// the last byte at the residual pushed, at residuals 0, 4, 16 and 256, with +/// `uniformBufferStandardLayout` and without. A slot read at a constant offset alone +/// (`buffer_end_byte_load_constant`) keeps its uniform buffer there, and the same profile with +/// nothing measured (the Iris Xe's own identity included) keeps the uniform buffer for both. #[test] fn a_short_constant_window_reads_through_a_uniform_texel_buffer() { use crate::spirv::interp::run_with_images; use crate::spirv::ir::{Dim, ImageType, ImageUsage}; - let entry = "buffer_end_byte_load_constant"; - let Some(bc) = assemble_file(entry) else { + let entry = "indexed_byte_load"; + let Some(bc) = assemble_text(entry, INDEXED_BYTE) else { + return; + }; + let Some(constant) = assemble_file("buffer_end_byte_load_constant") else { return; }; let data = [9u8, 8, 7, 6, 5, 0xC3]; - let form_on = |p: &DeviceProfile, what: &str| { - let a = compile(&bc, entry, p).unwrap_or_else(|e| panic!("{what}: {e}")); + let form_of = |bc: &[u8], entry: &str, p: &DeviceProfile, what: &str| { + let a = compile(bc, entry, p).unwrap_or_else(|e| panic!("{what}: {e}")); link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); match a.interface.slots.get(&sref(0)) { Some(SlotInterface::Buffer(b)) => b.form, @@ -391,17 +439,27 @@ fn a_short_constant_window_reads_through_a_uniform_texel_buffer() { }; for standard in [true, false] { let what = format!("standard={standard}"); - let p = profile_with(TEXEL_PROFILE, true, standard); + let p = texel_profile("intel-irisxe-rplp-anv", true, standard); assert!( p.workarounds() .contains(&DriverWorkaround::ExternalUniformReadsSkipACache), "{what}" ); assert_eq!( - form_on(&p, &what), + form_of(&bc, entry, &p, &what), BufferForm::Descriptor(DescriptorView::UniformTexel), "{what}" ); + let plain = match standard { + true => DescriptorView::UniformWords, + false => DescriptorView::UniformVec4, + }; + let constant_entry = "buffer_end_byte_load_constant"; + assert_eq!( + form_of(&constant, constant_entry, &p, &what), + BufferForm::Descriptor(plain), + "{what}: a constant offset alone" + ); let (plan, m) = typed_module(&bc, entry, &p).expect("module"); let slot: Vec<_> = (m.globals().iter()) .filter(|g| g.kind == GlobalKind::Resource(kslot(0))) @@ -424,7 +482,7 @@ fn a_short_constant_window_reads_through_a_uniform_texel_buffer() { let mut bytes = bound(0, r, &data, 0x44).bytes; bytes.resize(bytes.len().max(512), 0x44); let res = Resources { - buffers: vec![bound(1, 0, &[0; 4], 0)], + buffers: vec![bound(1, 0, &[0; 4], 0), bound(2, 0, &5u32.to_le_bytes(), 0)], push: push_bytes(&plan, &[(0, r)]), spec: Default::default(), }; @@ -434,22 +492,22 @@ fn a_short_constant_window_reads_through_a_uniform_texel_buffer() { assert_eq!(out.buffers[0][..4], [0xC3, 0, 0, 0], "{what} r={r}"); } } - let p = profile_with("intel-uhd770-rpls-anv", true, true); + let p = texel_profile("intel-irisxe-rplp-anv", false, true); assert_eq!( - form_on(&p, "uhd770"), + form_of(&bc, entry, &p, "unmeasured"), BufferForm::Descriptor(DescriptorView::UniformWords) ); } /// A uniform view takes the texel form for a `Bounded` window of at most -/// `views::TEXEL_WINDOW_BYTES` alone, on the profile that takes +/// `views::TEXEL_WINDOW_BYTES` alone, on a profile whose description measured /// `DriverWorkaround::ExternalUniformReadsSkipACache`: 4096 bytes is one, 4097 keeps its uniform -/// buffer, as does every window on lavapipe's profile. +/// buffer, as does every window on lavapipe's profile, which measured nothing. #[test] fn only_a_window_within_the_bound_takes_the_texel_form() { use crate::lower::access::texel_view; use crate::memory::views::{ViewKind, TEXEL_WINDOW_BYTES}; - let iris = profile_with(TEXEL_PROFILE, true, true); + let iris = texel_profile("intel-irisxe-rplp-anv", true, true); let lavapipe = profile_with("lavapipe", true, true); let window = |len| Window::Bounded { start: 0, len }; assert!(matches!( @@ -646,13 +704,12 @@ fn a_storage_view_reads_its_residual_without_the_row() { } /// A kernel's `constant` slot reads through a uniform view, and its layout binds nothing for it -/// but that view: on the profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload` -/// (and `DriverWorkaround::ExternalUniformReadsSkipACache`, whose uniform texel buffer the slot's -/// short window takes there), with `uniformBufferStandardLayout` and without, the slot's form is -/// that uniform view, its `RangeAtBindOffset` key is read, and set 0 holds the slot's uniform +/// but that view: on the profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload`, +/// with `uniformBufferStandardLayout` (`u32[]`) and without (`uvec4[]`), the slot's form is the +/// plain uniform view, its `RangeAtBindOffset` key is read, and set 0 holds the slot's uniform /// binding and the written slot's storage binding alone, numbered densely; a plan of nothing -/// bound writes those two, a uniform texel buffer and a storage buffer, and nothing else in set -/// 0. On every other tested profile the plan writes the two slots alone as well. +/// bound writes those two, a uniform buffer and a storage buffer, and nothing else in set 0. On +/// every other tested profile the plan writes the two slots alone as well. #[test] fn a_kernel_constant_slot_binds_its_uniform_view_alone() { use crate::bind::{BindState, DescriptorWrite}; @@ -663,8 +720,8 @@ fn a_kernel_constant_slot_binds_its_uniform_view_alone() { return; }; for (standard, view) in [ - (true, DescriptorView::UniformTexel), - (false, DescriptorView::UniformTexel), + (true, DescriptorView::UniformWords), + (false, DescriptorView::UniformVec4), ] { let what = format!("standard={standard}"); let p = profile_with(AT_BIND_PROFILE, true, standard); @@ -728,7 +785,7 @@ fn a_kernel_constant_slot_binds_its_uniform_view_alone() { assert_eq!( set0.values().copied().collect::>(), [ - crate::vk::DescriptorType::UNIFORM_TEXEL_BUFFER, + crate::vk::DescriptorType::UNIFORM_BUFFER, crate::vk::DescriptorType::STORAGE_BUFFER ], "{stem}" diff --git a/crates/metal2vulkan/src/tests/engine_lane_reads.rs b/crates/metal2vulkan/src/tests/engine_lane_reads.rs index c187a510c..e80709be9 100644 --- a/crates/metal2vulkan/src/tests/engine_lane_reads.rs +++ b/crates/metal2vulkan/src/tests/engine_lane_reads.rs @@ -2,7 +2,8 @@ //! a `constant` slot a uniform view could read keeps its storage view where some read reaches it //! at an address that may differ between the lanes that run it together, and keeps its uniform //! view where every read is at a uniform address; a profile without the fact gives every such slot -//! its uniform view. +//! its uniform view. The fact comes from the description's measured set alone (the runtime's view +//! check), never from the GPU's identity. //! //! The kernels read a `constant` table of 64 words (`air.buffer_size` 256, a `Bounded` window): //! `lane_table` at the thread's position, `loop_table` in a loop over a bound read from the table, @@ -13,7 +14,6 @@ use std::path::Path; -use crate::device::driver_facts::{NVIDIA_RTX_2080, NVIDIA_RTX_3090}; use crate::device::profile::{DeviceProfile, DriverWorkaround}; use crate::device::{Device, DeviceDescription, DevicePolicy}; use crate::pipeline::interface::{BufferForm, DescriptorView, SlotInterface}; @@ -90,8 +90,9 @@ fn assemble() -> Option> { } } -/// The profile of the committed capture `stem`, under the device ID `id` where one is given. -fn profile(stem: &str, id: Option) -> DeviceProfile { +/// The profile of the committed capture `stem`, under the device ID `id` where one is given, its +/// description's measured set `measured`. +fn profile(stem: &str, id: Option, measured: &[DriverWorkaround]) -> DeviceProfile { let path = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../metal2vulkan-validation/profiles") .join(format!("{stem}.json")); @@ -100,6 +101,7 @@ fn profile(stem: &str, id: Option) -> DeviceProfile { if let Some(id) = id { desc.device_id = id; } + desc.measured.extend(measured.iter().copied()); Device::new(desc, DevicePolicy::default()) .expect("device") .profile() @@ -121,23 +123,19 @@ fn table_form(bc: &[u8], entry: &str, p: &DeviceProfile, what: &str) -> BufferFo } } -/// On the three NVIDIA GPUs measured with the fact, the table read at the thread's position keeps -/// its storage view; the loop's counter after an early return, and a constant offset, keep the -/// uniform view. +/// Where the description measured the fact, NVIDIA's capture or RADV's, the table read at the +/// thread's position keeps its storage view; the loop's counter after an early return, and a +/// constant offset, keep the uniform view. #[test] -fn a_per_lane_constant_read_keeps_its_storage_view_where_the_fact_holds() { +fn a_per_lane_constant_read_keeps_its_storage_view_where_the_fact_was_measured() { let Some(bc) = assemble() else { return; }; let fact = DriverWorkaround::UniformBufferPerLaneReadsSerialize; let storage = BufferForm::Descriptor(DescriptorView::Storage); let uniform = BufferForm::Descriptor(DescriptorView::UniformWords); - for (what, id) in [ - ("rtx5080-laptop", None), - ("rtx3090", Some(NVIDIA_RTX_3090)), - ("rtx2080", Some(NVIDIA_RTX_2080)), - ] { - let p = profile("nvidia-rtx5080-laptop", id); + for what in ["nvidia-rtx5080-laptop", "amd-780m-radv"] { + let p = profile(what, None, &[fact]); assert!(p.workarounds().contains(&fact), "{what}"); assert_eq!(table_form(&bc, "lane_table", &p, what), storage, "{what}"); assert_eq!(table_form(&bc, "loop_table", &p, what), uniform, "{what}"); @@ -145,21 +143,61 @@ fn a_per_lane_constant_read_keeps_its_storage_view_where_the_fact_holds() { } } -/// The negative control: on RADV, which has no such fact, every kernel's table is a uniform view, -/// the one read at the thread's position too. +/// The identity decides nothing: NVIDIA's captures under the IDs of the three GPUs the fact was +/// first measured on (the RTX 5080 Laptop GPU, the RTX 3090 and the RTX 2080), with nothing +/// measured, give every kernel's table its uniform view; and so does RADV, the negative control. #[test] -fn without_the_fact_a_per_lane_constant_read_keeps_its_uniform_view() { +fn without_the_measured_fact_a_per_lane_constant_read_keeps_its_uniform_view() { let Some(bc) = assemble() else { return; }; let uniform = BufferForm::Descriptor(DescriptorView::UniformWords); - for stem in ["amd-780m-radv", "amd-rdna3-radv"] { - let p = profile(stem, None); + for (stem, id) in [ + ("nvidia-rtx5080-laptop", None), + ("nvidia-rtx5080-laptop", Some(0x2204)), + ("nvidia-rtx5080-laptop", Some(0x1e87)), + ("amd-780m-radv", None), + ("amd-rdna3-radv", None), + ] { + let p = profile(stem, id, &[]); assert!(!p .workarounds() .contains(&DriverWorkaround::UniformBufferPerLaneReadsSerialize)); for entry in ["lane_table", "loop_table", "field_table"] { - assert_eq!(table_form(&bc, entry, &p, stem), uniform, "{stem} {entry}"); + assert_eq!( + table_form(&bc, entry, &p, stem), + uniform, + "{stem} {id:?} {entry}" + ); } } } + +/// Both view facts compose: the table read at the thread's position keeps its storage view (the +/// lane read first), the loop's indexed reads, uniform among the active lanes, take the uniform +/// texel buffer, and the constant offset alone keeps the uniform buffer. +#[test] +fn both_view_facts_compose() { + let Some(bc) = assemble() else { + return; + }; + let both = [ + DriverWorkaround::UniformBufferPerLaneReadsSerialize, + DriverWorkaround::ExternalUniformReadsSkipACache, + ]; + let p = profile("nvidia-rtx5080-laptop", None, &both); + let what = "both"; + let form = |entry| table_form(&bc, entry, &p, what); + assert_eq!( + form("lane_table"), + BufferForm::Descriptor(DescriptorView::Storage) + ); + assert_eq!( + form("loop_table"), + BufferForm::Descriptor(DescriptorView::UniformTexel) + ); + assert_eq!( + form("field_table"), + BufferForm::Descriptor(DescriptorView::UniformWords) + ); +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 72f91f3ae..8f930cdb1 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -72,6 +72,8 @@ assoc-const metal2vulkan::bind::BlockDecodeModule::SHAPE_BINDING pub const SHAPE assoc-const metal2vulkan::bind::BlockDecodeModule::SHAPE_WORDS pub const SHAPE_WORDS: u32 assoc-const metal2vulkan::bind::BlockDecodeModule::TEXELS_BINDING pub const TEXELS_BINDING: u32 assoc-const metal2vulkan::bind::CheckDrawModules::FETCH_BINDING pub const FETCH_BINDING: u32 +assoc-const metal2vulkan::bind::CheckReads::ALL pub const ALL: [CheckReads; 3] +assoc-const metal2vulkan::bind::CheckView::ALL pub const ALL: [CheckView; 3] assoc-const metal2vulkan::bind::ChromaConvertModule::BYTES_BINDING pub const BYTES_BINDING: u32 assoc-const metal2vulkan::bind::ChromaConvertModule::IMAGE_BINDING pub const IMAGE_BINDING: u32 assoc-const metal2vulkan::bind::ChromaConvertModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 @@ -395,6 +397,12 @@ assoc-const metal2vulkan::bind::TwoPlaneTexelsModule::SET pub const SET: u32 assoc-const metal2vulkan::bind::TwoPlaneTexelsModule::SHAPE_BINDING pub const SHAPE_BINDING: u32 assoc-const metal2vulkan::bind::TwoPlaneTexelsModule::SHAPE_WORDS pub const SHAPE_WORDS: u32 assoc-const metal2vulkan::bind::TwoPlaneTexelsModule::TEXELS_BINDING pub const TEXELS_BINDING: u32 +assoc-const metal2vulkan::bind::ViewCheckModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 +assoc-const metal2vulkan::bind::ViewCheckModule::OUT_BINDING pub const OUT_BINDING: u32 +assoc-const metal2vulkan::bind::ViewCheckModule::PUSH_BYTES pub const PUSH_BYTES: u32 +assoc-const metal2vulkan::bind::ViewCheckModule::SET pub const SET: u32 +assoc-const metal2vulkan::bind::ViewCheckModule::WINDOW_BINDING pub const WINDOW_BINDING: u32 +assoc-const metal2vulkan::bind::ViewCheckModule::WINDOW_VECS pub const WINDOW_VECS: u32 assoc-const metal2vulkan::bind::VisibilityCombine::ENTRY_WORDS pub const ENTRY_WORDS: usize assoc-const metal2vulkan::bind::VisibilityCombineModule::DEST_BINDING pub const DEST_BINDING: u32 assoc-const metal2vulkan::bind::VisibilityCombineModule::LOCAL_SIZE pub const LOCAL_SIZE: u32 @@ -584,6 +592,8 @@ assoc-const-value metal2vulkan::bind::BlockDecodeModule::SHAPE_BINDING 0 assoc-const-value metal2vulkan::bind::BlockDecodeModule::SHAPE_WORDS 5 assoc-const-value metal2vulkan::bind::BlockDecodeModule::TEXELS_BINDING 2 assoc-const-value metal2vulkan::bind::CheckDrawModules::FETCH_BINDING 0 +assoc-const-value metal2vulkan::bind::CheckReads::ALL [CheckReads::Uniform, CheckReads::PerLane, CheckReads::Fields] +assoc-const-value metal2vulkan::bind::CheckView::ALL [CheckView::Uniform, CheckView::Storage, CheckView::Texel] assoc-const-value metal2vulkan::bind::ChromaConvertModule::BYTES_BINDING 2 assoc-const-value metal2vulkan::bind::ChromaConvertModule::IMAGE_BINDING 0 assoc-const-value metal2vulkan::bind::ChromaConvertModule::LOCAL_SIZE 8 @@ -907,6 +917,12 @@ assoc-const-value metal2vulkan::bind::TwoPlaneTexelsModule::SET 0 assoc-const-value metal2vulkan::bind::TwoPlaneTexelsModule::SHAPE_BINDING 2 assoc-const-value metal2vulkan::bind::TwoPlaneTexelsModule::SHAPE_WORDS 13 assoc-const-value metal2vulkan::bind::TwoPlaneTexelsModule::TEXELS_BINDING 0 +assoc-const-value metal2vulkan::bind::ViewCheckModule::LOCAL_SIZE 64 +assoc-const-value metal2vulkan::bind::ViewCheckModule::OUT_BINDING 1 +assoc-const-value metal2vulkan::bind::ViewCheckModule::PUSH_BYTES 16 +assoc-const-value metal2vulkan::bind::ViewCheckModule::SET 0 +assoc-const-value metal2vulkan::bind::ViewCheckModule::WINDOW_BINDING 0 +assoc-const-value metal2vulkan::bind::ViewCheckModule::WINDOW_VECS 256 assoc-const-value metal2vulkan::bind::VisibilityCombine::ENTRY_WORDS 4 assoc-const-value metal2vulkan::bind::VisibilityCombineModule::DEST_BINDING 1 assoc-const-value metal2vulkan::bind::VisibilityCombineModule::LOCAL_SIZE 64 @@ -1450,6 +1466,7 @@ enum metal2vulkan-runtime::TilingVerdict #[derive(Clone, Copy, Debug, PartialEq, enum metal2vulkan-runtime::ViewPlacement #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ViewPlacement enum metal2vulkan-runtime::ViewProblem #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ViewProblem enum metal2vulkan-runtime::ViewShadowReason #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ViewShadowReason +enum metal2vulkan-runtime::ViewVerdict #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum ViewVerdict enum metal2vulkan-runtime::VisibilityProblem #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum VisibilityProblem enum metal2vulkan-runtime::VisibilityResultMode #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum VisibilityResultMode enum metal2vulkan-runtime::VisibilityResultType #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum VisibilityResultType @@ -1464,6 +1481,8 @@ enum metal2vulkan::bind::AstcTexels #[cfg_attr(feature = "serde", derive(serde:: enum metal2vulkan::bind::BoundBuffer #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum BoundBuffer enum metal2vulkan::bind::BoundTexture #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum BoundTexture enum metal2vulkan::bind::BufferShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum BufferShape +enum metal2vulkan::bind::CheckReads #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum CheckReads +enum metal2vulkan::bind::CheckView #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum CheckView enum metal2vulkan::bind::ChromaDecode #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ChromaDecode enum metal2vulkan::bind::CopySource #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum CopySource enum metal2vulkan::bind::DepthPick #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DepthPick @@ -1542,7 +1561,7 @@ enum metal2vulkan::device::Containment #[derive(Clone, Copy, Debug, PartialEq, E enum metal2vulkan::device::ContainmentPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ContainmentPolicy enum metal2vulkan::device::DontCareColorPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum DontCareColorPolicy enum metal2vulkan::device::DriverFact #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DriverFact -enum metal2vulkan::device::DriverWorkaround #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DriverWorkaround +enum metal2vulkan::device::DriverWorkaround #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DriverWorkaround enum metal2vulkan::device::Exposure #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum Exposure enum metal2vulkan::device::ExtendedRangeBlitPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum ExtendedRangeBlitPolicy enum metal2vulkan::device::FloatControl #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FloatControl @@ -2682,6 +2701,10 @@ field metal2vulkan-runtime::UsedResources.heaps pub heaps: Vec field metal2vulkan-runtime::UsedResources.textures pub textures: Vec field metal2vulkan-runtime::VertexAmplificationViewMapping.render_target_array_index_offset pub render_target_array_index_offset: u32 field metal2vulkan-runtime::VertexAmplificationViewMapping.viewport_array_index_offset pub viewport_array_index_offset: u32 +field metal2vulkan-runtime::ViewCosts.facts pub facts: BTreeSet +field metal2vulkan-runtime::ViewCosts.per_lane pub per_lane: Option +field metal2vulkan-runtime::ViewCosts.texel pub texel: Option +field metal2vulkan-runtime::ViewCosts.verdict pub verdict: ViewVerdict field metal2vulkan-runtime::Viewport.height pub height: f64 field metal2vulkan-runtime::Viewport.origin_x pub origin_x: f64 field metal2vulkan-runtime::Viewport.origin_y pub origin_y: f64 @@ -4538,6 +4561,8 @@ field metal2vulkan::bind::VertexAmplification.view_mappings pub view_mappings: V field metal2vulkan::bind::VertexBufferBind.binding pub binding: u32 field metal2vulkan::bind::VertexBufferBind.buffer_index pub buffer_index: u32 field metal2vulkan::bind::VertexBufferBind.per_bind_stride pub per_bind_stride: bool +field metal2vulkan::bind::ViewCheckModule.requirements pub requirements: Requirements +field metal2vulkan::bind::ViewCheckModule.spirv pub spirv: Arc<[u32]> field metal2vulkan::bind::ViewMapping.render_target_array_index_offset pub render_target_array_index_offset: u32 field metal2vulkan::bind::ViewMapping.viewport_array_index_offset pub viewport_array_index_offset: u32 field metal2vulkan::bind::ViewSetup.base_layer pub base_layer: u32 @@ -4684,6 +4709,7 @@ field metal2vulkan::device::DeviceDescription.formats pub formats: FormatSupport field metal2vulkan::device::DeviceDescription.generated_commands pub generated_commands: Option field metal2vulkan::device::DeviceDescription.khr_format_feature_flags2 pub khr_format_feature_flags2: bool field metal2vulkan::device::DeviceDescription.limits pub limits: Limits +field metal2vulkan::device::DeviceDescription.measured pub measured: BTreeSet field metal2vulkan::device::DeviceDescription.rgba4_opaque_black_swizzled pub rgba4_opaque_black_swizzled: bool field metal2vulkan::device::DeviceDescription.robust_buffer_access_update_after_bind pub robust_buffer_access_update_after_bind: bool field metal2vulkan::device::DeviceDescription.subgroup pub subgroup: SubgroupProperties @@ -5719,6 +5745,7 @@ fn metal2vulkan::bind::tessellation_scan_module pub fn tessellation_scan_module( fn metal2vulkan::bind::texel_buffer_parts pub fn texel_buffer_parts(limits: &Limits, texels: u64) -> u32 fn metal2vulkan::bind::tiled_texels_module pub fn tiled_texels_module(device: &Device) -> Result fn metal2vulkan::bind::two_plane_texels_module pub fn two_plane_texels_module(device: &Device) -> Result +fn metal2vulkan::bind::view_check_module pub fn view_check_module(device: &Device, view: CheckView, reads: CheckReads) -> Result fn metal2vulkan::bind::visibility_combine_module pub fn visibility_combine_module(device: &Device) -> Result fn metal2vulkan::bind::ycbcr_convert_floats_module pub fn ycbcr_convert_floats_module(device: &Device, conversion: YCbCrConversion) -> Result fn metal2vulkan::bind::ycbcr_convert_module pub fn ycbcr_convert_module(device: &Device, conversion: YCbCrConversion) -> Result @@ -8931,6 +8958,7 @@ method metal2vulkan-runtime::Device::settle_in_place_checks pub fn settle_in_pla method metal2vulkan-runtime::Device::settle_queue_switch_check pub fn settle_queue_switch_check(&self, timeout: Duration) -> bool method metal2vulkan-runtime::Device::settle_submit_checks pub fn settle_submit_checks(&self, timeout: Duration) -> bool method metal2vulkan-runtime::Device::settle_tiling_cost_check pub fn settle_tiling_cost_check(&self, timeout: Duration) -> bool +method metal2vulkan-runtime::Device::settle_view_check pub fn settle_view_check(&self, timeout: Duration) -> bool method metal2vulkan-runtime::Device::shader_cache_directory pub fn shader_cache_directory(&self) -> Option<&Path> method metal2vulkan-runtime::Device::shader_cache_statistics pub fn shader_cache_statistics(&self) -> ShaderCacheStatistics method metal2vulkan-runtime::Device::shares_vk_queues pub fn shares_vk_queues(&self) -> bool @@ -8949,6 +8977,8 @@ method metal2vulkan-runtime::Device::texture_level_info pub fn texture_level_inf method metal2vulkan-runtime::Device::tiling_cost pub fn tiling_cost(&self) -> TilingCost method metal2vulkan-runtime::Device::tiling_cost_check_report pub fn tiling_cost_check_report(&self) -> String method metal2vulkan-runtime::Device::use_host_ram pub fn use_host_ram(&self, ram: &Arc) -> Result +method metal2vulkan-runtime::Device::view_check_report pub fn view_check_report(&self) -> String +method metal2vulkan-runtime::Device::view_costs pub fn view_costs(&self) -> ViewCosts method metal2vulkan-runtime::Device::vk_buffer_usage pub fn vk_buffer_usage(&self) -> BufferUsageFlags method metal2vulkan-runtime::Device::warm pub fn warm(&self, records: Vec, byte_budget: u64) method metal2vulkan-runtime::Device::warm_statistics pub fn warm_statistics(&self) -> WarmStatistics @@ -9901,6 +9931,7 @@ method metal2vulkan::bind::UsedResource::new pub fn new(class: ResourceClass, to method metal2vulkan::bind::VertexAmplification::layer pub fn layer(&self, a: u32, length: u32, max: u32) -> u32 method metal2vulkan::bind::VertexAmplification::mapping pub fn mapping(&self, a: u32, max: u32) -> ViewMapping method metal2vulkan::bind::VertexAmplification::new pub fn new(count: u32, view_mappings: Vec) -> VertexAmplification +method metal2vulkan::bind::ViewCheckModule::push pub fn push(vecs: u32, reads: u32) -> [u8; 16] method metal2vulkan::bind::ViewMapping::new pub fn new(viewport_array_index_offset: u32, render_target_array_index_offset: u32) -> Self method metal2vulkan::bind::VisibilityCombine::plan pub fn plan(results: &[ContinuedResult], alignment: u64, max_range: u32, max_groups: u32) -> Option> method metal2vulkan::bind::VisibilityCombine::table_bytes pub fn table_bytes(&self) -> Vec @@ -10720,6 +10751,7 @@ struct metal2vulkan-runtime::TimedOut #[derive(Clone, Copy, Debug, PartialEq, Eq struct metal2vulkan-runtime::Unproven #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct Unproven struct metal2vulkan-runtime::UsedResources #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct UsedResources struct metal2vulkan-runtime::VertexAmplificationViewMapping #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct VertexAmplificationViewMapping +struct metal2vulkan-runtime::ViewCosts #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct ViewCosts struct metal2vulkan-runtime::Viewport #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct Viewport struct metal2vulkan-runtime::VisibleFunctionTable #[derive(Clone)] pub struct VisibleFunctionTable(Arc) struct metal2vulkan-runtime::VisibleFunctionTableDescriptor #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct VisibleFunctionTableDescriptor @@ -10895,6 +10927,7 @@ struct metal2vulkan::bind::UsedResource #[cfg_attr(feature = "serde", derive(ser struct metal2vulkan::bind::UsedShape #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct UsedShape struct metal2vulkan::bind::VertexAmplification #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct VertexAmplification struct metal2vulkan::bind::VertexBufferBind #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct VertexBufferBind +struct metal2vulkan::bind::ViewCheckModule #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct ViewCheckModule struct metal2vulkan::bind::ViewMapping #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct ViewMapping struct metal2vulkan::bind::ViewSetup #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ViewSetup struct metal2vulkan::bind::VisibilityCombine #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct VisibilityCombine @@ -13482,6 +13515,9 @@ variant metal2vulkan-runtime::ViewProblem::TypeIncompatible TypeIncompatible variant metal2vulkan-runtime::ViewShadowReason::CompatibilityClass CompatibilityClass variant metal2vulkan-runtime::ViewShadowReason::NotListed NotListed variant metal2vulkan-runtime::ViewShadowReason::Reinterpretation Reinterpretation +variant metal2vulkan-runtime::ViewVerdict::Measured Measured +variant metal2vulkan-runtime::ViewVerdict::Pending Pending +variant metal2vulkan-runtime::ViewVerdict::Unchecked Unchecked variant metal2vulkan-runtime::VisibilityProblem::NoBuffer NoBuffer variant metal2vulkan-runtime::VisibilityProblem::OffsetOutOfRange OffsetOutOfRange { offset: u64, length: u64 } variant metal2vulkan-runtime::VisibilityProblem::OffsetReused OffsetReused { offset: u64 } @@ -13558,6 +13594,12 @@ variant metal2vulkan::bind::BoundTexture::Buffer Buffer { pixel_format: metal::P variant metal2vulkan::bind::BoundTexture::Texture Texture { facts: TextureFacts, resource_id: Option } variant metal2vulkan::bind::BufferShape::Buffer Buffer { attribute_stride: Option, device_address: bool, length_class: u8, offset_alignment: u32 } variant metal2vulkan::bind::BufferShape::Bytes Bytes { attribute_stride: Option } +variant metal2vulkan::bind::CheckReads::Fields Fields +variant metal2vulkan::bind::CheckReads::PerLane PerLane +variant metal2vulkan::bind::CheckReads::Uniform Uniform +variant metal2vulkan::bind::CheckView::Storage Storage +variant metal2vulkan::bind::CheckView::Texel Texel +variant metal2vulkan::bind::CheckView::Uniform Uniform variant metal2vulkan::bind::ChromaDecode::Bgrg Bgrg variant metal2vulkan::bind::ChromaDecode::Gbgr Gbgr variant metal2vulkan::bind::CopySource::Aspect Aspect diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 86662fb9e..67a4a9bd8 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -781,6 +781,10 @@ surface! { struct PlanesSplitModule N; fn check_draw_modules; struct CheckDrawModules N; + fn view_check_module; + enum CheckView N; + enum CheckReads N; + struct ViewCheckModule N; fn interleave_merge_modules; fn interleave_split_module; struct InterleaveMergeModules N; diff --git a/docs/API.md b/docs/API.md index 418654ef4..478d70c33 100644 --- a/docs/API.md +++ b/docs/API.md @@ -353,6 +353,14 @@ println!(" Metal properties: {:?}", device.metal_properties()); includes it, so an artifact never serves another device. Facts that follow the machine's memory (`DeviceDescription::allocation`: `maxMemoryAllocationSize`, `maxBufferSize`) are not profile fields, so two machines that differ only there share artifacts. +- `DeviceDescription::measured`: the driver workarounds you measured on the device itself, which + the profile takes beside those its driver's identity names. Two cost facts come from such a + measurement alone, never from an identity: `DriverWorkaround::UniformBufferPerLaneReadsSerialize` + (a uniform buffer read at an address that differs between lanes costs many times a storage + buffer's) and `DriverWorkaround::ExternalUniformReadsSkipACache` (uniform reads of imported memory + are faster through a uniform texel buffer). The runtime's view check measures both + (`crates/metal2vulkan-runtime/README.md`); `bind::view_check_module` gives its kernels. The set is + a profile field, so the fingerprint and every cache key follow it. - `profile().spirv_validation()`: the `spirv-val` environments and relaxations every module for the device is valid under. The command line runs exactly these. - The profile's facts: `enabled()`, `limits()`, `images()`, `fragment()`, `descriptors()`, the @@ -1463,8 +1471,11 @@ for dependency in &pipeline.dependencies { dynamic buffer an entry point uses through more than one variable. - A buffer slot's uniform view is a `Uniform` block (`DescriptorView::UniformWords`, or `UniformVec4` without `uniformBufferStandardLayout`), but on a profile that takes - `DriverWorkaround::ExternalUniformReadsSkipACache` (ANV on the Iris Xe RPL-P) a slot whose window - is `Bounded` and at most 4 KiB long takes a uniform texel buffer instead + `DriverWorkaround::ExternalUniformReadsSkipACache` (measured: `DeviceDescription::measured`; on + the Iris Xe RPL-P under ANV the runtime's view check finds it) a slot with an indexed read whose + window is `Bounded` and at most 4 KiB long takes a uniform texel buffer instead; a slot read at + constant offsets alone keeps its `Uniform` block, whose words a driver may load ahead into + registers as it cannot a texel fetch (`DescriptorView::UniformTexel`: a `UniformConstant` image of `Dim` `Buffer`, `Sampled` 1, `u32` texels, read with `OpImageFetch`), its binding `VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER`. Write a view of the planned range in `R32G32B32A32_UINT`, from the range's buffer, offset and length, diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index df2b08ac1..f74f7ab5c 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -719,12 +719,14 @@ driver's. Each is open work. shadow wherever its first byte lies off a multiple of 4096 of the memory, or its image is larger than the bytes the placement holds from there. - **On ANV, constants read through a uniform buffer over imported memory take longer than over - the device's own** (`DriverWorkaround::ExternalUniformReadsSkipACache`, the Iris Xe RPL-P): + the device's own** (`DriverWorkaround::ExternalUniformReadsSkipACache`, which the runtime's view + check finds on the Iris Xe RPL-P): Mesa gives memory the device marks external (a host allocation, a dma-buf) the cache state of a displayable surface, and a uniform buffer read of it misses the data port's L1. A uniform view - whose window the translation bounds to at most 4 KiB reads through a uniform texel buffer there, - as fast as over device memory (`DescriptorView::UniformTexel`, `docs/API.md` section 5). Every - other uniform view keeps its uniform buffer: large constant working sets over imported memory + with an indexed read whose window the translation bounds to at most 4 KiB reads through a uniform + texel buffer there, as fast as over device memory (`DescriptorView::UniformTexel`, `docs/API.md` + section 5). Every other uniform view keeps its uniform buffer (one read at constant offsets + alone, whose words the driver may load ahead into registers, among them): large constant working sets over imported memory still run at 1.1 to 2.2 times their time over device memory on ANV (a uniform buffer over a host allocation or a udmabuf against one over device memory, 16 MiB windows, job m3-max-37729); only memory the device does not mark external reads at full speed there. The binds that keep the