From 5a1e0437846be9b71cfe177bbeb8e82244f129bf Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 11 Nov 2026 16:44:17 -0800 Subject: [PATCH] A driver cache record names its pass without the attachments' formats A render making's record of the driver's data, and the libraries of its pre-rasterization and fragment shader parts, were named by the pass shape whole, formats included. A program that makes one state against passes that differ only in a colour attachment's format (RGBA8Unorm, RGBA16Float, BGRA8Unorm) so got one VkPipelineCache per format, and the driver compiled the same fragment module once in each: on the Iris Xe (ANV, Mesa 26.2.6) 3.3 to 3.7 s per compile for one large module, three times over at a cold start. No stage's conversion reads an attachment's format through the pass: a format the translation reads is in the stage's own words and constants, which name the part's record too. So a part's record now names the pass by PassShape::without_formats (which attachments it has, its samples, fetch inputs, unread inputs, storage attachments, view mask and locations), and the depth bias is left out of it as before. The library names the runtime keys its own library objects by keep the formats (the libraries are made against VkRenderPasses, which must be compatible); only the driver cache record is shared. A driver that does key a stage by format keys that entry apart in the one cache: a compile, never a wrong pipeline. The record-naming version (shader_cache/driver.rs VERSION) goes to 3. METAL2VULKAN_LOG_PIPELINES now says, per library, whether its record was loaded, missed or its cache shared with an earlier making, and whether the driver found it in that cache or compiled it (from VK_EXT_pipeline_creation_feedback). Measured before the change (a harness making the module's fragment library against three passes on the Iris Xe, MESA_SHADER_CACHE_DISABLE): a cache per format, 3.5 s, 3.7 s, 3.3 s; one shared cache, 3.5 s then 0.0 ms and 0.0 ms, the second and third APPLICATION_PIPELINE_CACHE_HIT. Tests: record_pass_formats (a pass's record name drops formats, keeps presence, samples, fetch inputs and view mask); driver_pipeline_compile::creations_over_colour_formats_take_the_first_s_records (two makings over BGRA8Unorm and RGBA16Float share the first's record, caches_shared grows by the makings, one fragment library compiled, while a constant that changes the module keeps its own record); creation_log's text test. --- .../src/pipeline/creation_log.rs | 127 ++++++++--- .../src/pipeline/graphics.rs | 198 ++++++++++++------ .../src/pipeline/libraries.rs | 12 +- .../metal2vulkan-runtime/src/render_target.rs | 42 ++++ .../src/shader_cache/driver.rs | 59 ++++-- .../src/tests/driver_pipeline_compile.rs | 109 ++++++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 1 + .../src/tests/record_pass_formats.rs | 62 ++++++ crates/metal2vulkan/src/env_vars.rs | 4 +- docs/API.md | 10 +- 10 files changed, 503 insertions(+), 121 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/record_pass_formats.rs diff --git a/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs b/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs index 884aff6e0..940b802f3 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs @@ -143,9 +143,9 @@ thread_local! { /// The split of the making whose line this thread times now ([`Line::made`]), if any: each /// part noted, with how long it took. static SPLIT: RefCell>> = const { RefCell::new(None) }; - /// Whether the cache the driver making this thread ran last was handed holds its record - /// ([`record_loaded`]), while a split is noted. - static RECORD: Cell> = const { Cell::new(None) }; + /// What the driver making this thread ran last noted of its record ([`record_handed`], + /// [`driver_found`]), while a split is noted. + static RECORD: Cell> = const { Cell::new(None) }; } /// Whether this thread notes the split of a making's time now: its line is timed @@ -166,18 +166,50 @@ pub(crate) fn note(part: impl FnOnce() -> String, took: Duration) { }); } -/// The cache the driver making this thread runs was handed was made from its record, or not -/// (`shader_cache/driver.rs`): a making of a record whose cache the device already holds live says -/// what the making that made it said. While a split is noted. -pub(crate) fn record_loaded(loaded: bool) { +/// What a driver making noted of its record (`shader_cache/driver.rs`): how the cache it was +/// handed came to be, and what the driver reported it found there. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct RecordNote { + /// The cache was made from its record. A making handed a cache an earlier one made says what + /// that making said. + pub(crate) loaded: bool, + /// The device held the cache before this making: an earlier making of the record made it, so + /// what that making's driver compiled is there to find. + pub(crate) earlier: bool, + /// What the driver reported of the making (`shader_cache::found_in_cache`): found in the + /// cache, compiled, or `None`, unreported. + pub(crate) found: Option, +} + +/// The driver making this thread runs was handed its record's cache: made from the record, or +/// not (`loaded`), and held by the device before it, or not (`earlier`). While a split is noted. +pub(crate) fn record_handed(loaded: bool, earlier: bool) { if splitting() { - RECORD.with(|record| record.set(Some(loaded))); + RECORD.with(|record| { + record.set(Some(RecordNote { + loaded, + earlier, + found: None, + })) + }); } } -/// What [`record_loaded`] last noted on this thread, read and reset: `None` where the making -/// kept no record. -pub(crate) fn take_record() -> Option { +/// What the driver reported of the making [`record_handed`] noted last on this thread: found in +/// the cache it was handed, compiled, or `None`, unreported. While a split is noted. +pub(crate) fn driver_found(found: Option) { + if splitting() { + RECORD.with(|record| { + if let Some(note) = record.get() { + record.set(Some(RecordNote { found, ..note })); + } + }); + } +} + +/// What [`record_handed`] and [`driver_found`] last noted on this thread, read and reset: `None` +/// where the making kept no record. +pub(crate) fn take_record() -> Option { RECORD.take() } @@ -211,13 +243,24 @@ fn split_text(parts: &[(String, Duration)]) -> String { format!("; parts: {}", parts.join(", ")) } -/// How a part made through its record names it in the split. -pub(crate) fn record_text(record: Option) -> &'static str { - match record { - Some(true) => ", record loaded", - Some(false) => ", record missed", +/// How a part made through its record names it in the split: how its cache came to be (loaded +/// from the record, made empty, or an earlier making's, shared), and what its driver reported +/// (found in that cache, or compiled) where it reports. +pub(crate) fn record_text(record: Option) -> String { + let Some(note) = record else { + return String::new(); + }; + let cache = match (note.earlier, note.loaded) { + (true, _) => ", record's cache shared", + (false, true) => ", record loaded", + (false, false) => ", record missed", + }; + let found = match note.found { + Some(true) => ", found in cache", + Some(false) => ", compiled", None => "", - } + }; + format!("{cache}{found}") } /// The hash a line names a stage's SPIR-V `words` by: `DefaultHasher`'s (SipHash-1-3, its zero @@ -878,15 +921,16 @@ fn find_statistics_function() -> Option { #[cfg(test)] mod tests { use super::{ - describe, elided, note, record_loaded, record_text, split_of, split_text, splitting, - take_record, Fields, + describe, driver_found, elided, note, record_handed, record_text, split_of, split_text, + splitting, take_record, Fields, RecordNote, }; use std::collections::VecDeque; use std::time::Duration; /// A making's split holds the parts noted while its line is timed, in order, and nothing /// outside one; a line timed inside another keeps its own parts, and the enclosing line's - /// go on after it. A record's load is noted only while a split is. + /// go on after it. A record's load, and what the driver found, are noted only while a split + /// is. #[test] fn a_making_s_split_holds_its_own_parts_in_order() { assert!(!splitting()); @@ -894,13 +938,15 @@ mod tests { || panic!("a part is named where no line is timed"), Duration::ZERO, ); - record_loaded(true); + record_handed(true, false); + driver_found(Some(true)); assert_eq!(take_record(), None, "no record noted outside a split"); let ((inner, record), outer) = split_of(|| { assert!(splitting()); note(|| "content".to_owned(), Duration::from_micros(300)); let inner = split_of(|| note(|| "link".to_owned(), Duration::from_millis(2))); - record_loaded(false); + record_handed(false, false); + driver_found(Some(false)); let record = take_record(); note( || format!("fragment shader library (made{})", record_text(record)), @@ -909,15 +955,48 @@ mod tests { (inner, record) }); assert!(!splitting()); - assert_eq!(record, Some(false)); + assert_eq!( + record, + Some(RecordNote { + loaded: false, + earlier: false, + found: Some(false) + }) + ); assert_eq!(inner.1, [("link".to_owned(), Duration::from_millis(2))]); assert_eq!( split_text(&outer), - "; parts: content 0.3 ms, fragment shader library (made, record missed) 6812.0 ms" + "; parts: content 0.3 ms, fragment shader library (made, record missed, compiled) \ + 6812.0 ms" ); assert_eq!(split_text(&[]), ""); } + /// A part made through its record names how its cache came to be and what the driver found + /// there: a library made against a pass that differs from an earlier making's only in a + /// format is handed that making's cache and found in it. + #[test] + fn a_record_s_text_names_its_cache_and_what_the_driver_found() { + let text = |loaded, earlier, found| { + record_text(Some(RecordNote { + loaded, + earlier, + found, + })) + }; + assert_eq!(text(false, false, Some(false)), ", record missed, compiled"); + assert_eq!( + text(true, false, Some(true)), + ", record loaded, found in cache" + ); + assert_eq!( + text(false, true, Some(true)), + ", record's cache shared, found in cache" + ); + assert_eq!(text(true, true, None), ", record's cache shared"); + assert_eq!(record_text(None), ""); + } + fn fields(pairs: &[(&str, &str)]) -> Fields { pairs .iter() diff --git a/crates/metal2vulkan-runtime/src/pipeline/graphics.rs b/crates/metal2vulkan-runtime/src/pipeline/graphics.rs index 3890cd125..b4c38c909 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/graphics.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/graphics.rs @@ -484,6 +484,37 @@ impl<'a> Infos<'a> { } } +/// What a part's digest names (`GraphicsContent::part_named`). +#[derive(Clone, Copy)] +enum Naming { + /// Its library (`libraries.rs`), made against the pass: the pass whole, and the depth bias the + /// content holds. + Library, + /// The record of the driver's data a making of its shaders is made under + /// (`GraphicsContent::record_parts`): the pass without its attachments' formats, and no depth + /// bias, neither of which reaches a stage's conversion. + Record, +} + +/// The record names of a making's two parts that hold shaders +/// (`GraphicsContent::record_parts`). +pub(crate) struct PartRecords { + pre_rasterization: Hash256, + fragment_shader: Hash256, +} + +impl PartRecords { + /// The record a library of `part` is made under; `None` for a part that holds no shader, + /// whose library is made with no cache. + fn of(&self, part: Part) -> Option<&Hash256> { + match part { + Part::PreRasterization => Some(&self.pre_rasterization), + Part::FragmentShader => Some(&self.fragment_shader), + Part::VertexInput | Part::FragmentOutput => None, + } + } +} + impl GraphicsContent { /// Whether its pipeline links from the four libraries: one with vertex input that rasterizes /// (a mesh pipeline, or one that discards every primitive, is made whole), and that reads no @@ -506,37 +537,24 @@ impl GraphicsContent { pipeline: &RenderPipeline, key: &GraphicsKey, ) -> [Hash256; 4] { - self.named(objects, pipeline, key, Some(self.depth_bias)) + Part::ALL.map(|part| self.part_named(part, objects, pipeline, key, Naming::Library)) } - /// [`names`](Self::names), with `depth_bias` named in the pre-rasterization part's state in - /// place of this content's: a library names its own (`Some`), a record names none - /// (`None`, [`record`](Self::record)). - fn named( - &self, - objects: &VariantObjects, - pipeline: &RenderPipeline, - key: &GraphicsKey, - depth_bias: Option, - ) -> [Hash256; 4] { - Part::ALL.map(|part| self.part_named(part, objects, pipeline, key, depth_bias)) - } - - /// The digest of `part`'s state alone, as [`named`](Self::named) describes every part's: one - /// part, so a caller that wants two of the four names the two. + /// The digest of `part`'s state alone, as `naming` names it: as [`names`](Self::names) + /// describes every part's for its library, or for the record of a making of its shaders + /// ([`Naming::Record`]). One part, so a caller that wants two of the four names the two. /// - /// A record is two of them ([`record`](Self::record)) and computing all four cost it the two - /// it throws away -- six `Debug` formats of fifteen, the vertex input's and the colour - /// attachments' among them -- at every making of every pipeline. Each part's digest starts - /// its own [`Making`], so naming one says nothing about another and the two a record keeps - /// are byte for byte what the whole array held. + /// A record is two of them ([`record_parts`](Self::record_parts)) and computing all four + /// cost it the two it throws away -- six `Debug` formats of fifteen, the vertex input's and + /// the colour attachments' among them -- at every making of every pipeline. Each part's + /// digest starts its own [`Making`], so naming one says nothing about another. fn part_named( &self, part: Part, objects: &VariantObjects, pipeline: &RenderPipeline, key: &GraphicsKey, - depth_bias: Option, + naming: Naming, ) -> Hash256 { use metal2vulkan::vk::ShaderStage; let graphics = &pipeline.graphics; @@ -585,10 +603,20 @@ impl GraphicsContent { ) }; let named = Making::new(part.kind()).text(&graphics.dynamic_states); - // The vertex input part takes no pass; the others are made against it. - let named = match part { - Part::VertexInput => named, - _ => named.text(&key.pass), + // The vertex input part takes no pass; the others are made against it, and a record + // names it without its attachments' formats, which reach no stage's conversion through + // it (`PassShape::without_formats`). + let named = match (part, naming) { + (Part::VertexInput, _) => named, + (_, Naming::Library) => named.text(&key.pass), + (_, Naming::Record) => named.text(&key.pass.without_formats()), + }; + // A library names the depth bias it holds; a record names none ([`record_parts`]). + // + // [`record_parts`]: Self::record_parts + let depth_bias = match naming { + Naming::Library => Some(self.depth_bias), + Naming::Record => None, }; match part { Part::VertexInput => named @@ -634,28 +662,65 @@ impl GraphicsContent { } } - /// What names the record of a making of `pipeline` (the variant's compiled pipeline) for - /// `key` (`shader_cache/driver.rs`): everything that reaches the driver's conversion of one - /// of its stages, and nothing else. + /// The names of the records of its two parts that hold shaders, its pre-rasterization and + /// fragment shader parts ([`Naming::Record`]): what names the record a library of either is + /// made under, where the device links its pipelines (`link`), and with them the record of a + /// whole pipeline's making ([`record`](Self::record)). /// - /// That is the names of the two parts that hold shaders, its pre-rasterization and fragment - /// shader libraries ([`names`](Self::names)) -- each of them the layout's description, its own - /// stages' SPIR-V with the constants they declare and their values, the pass, the dynamic - /// states and its part's state -- with the vertex input, which reaches MoltenVK's conversion - /// configuration as its vertex stage's inputs, and whether the pipeline rasterizes points - /// ([`renders_points`], the one way the topology reaches that configuration). + /// Each is its part's name as its library's ([`names`](Self::names)) but for two things that + /// reach no stage's conversion. Each is the layout's description, its own stages' SPIR-V with + /// the constants they declare and their values, the dynamic states and its part's state, and + /// the pass without its attachments' formats (`PassShape::without_formats`): a format the + /// translation reads is in the stage's words and constants already. So a state's pipelines + /// over passes that differ only in an attachment's format share one record and one cache, + /// where each format's making compiled the stages again (3.3 to 3.7 s each for a 203,016-word + /// fragment module on ANV, the Iris Xe), and its library made against each pass is found in + /// that cache. /// /// The depth bias is left out of the pre-rasterization part's state here, where a library /// names it: Metal biases triangles alone, so a state's line pipeline has the bias off where /// its triangle sibling has it on, and the bias reaches no stage's conversion. So the two /// share one record and one cache, where naming it made the line pipeline convert its stages /// again (120 ms and more for a 271k-word fragment module). + fn record_parts( + &self, + objects: &VariantObjects, + pipeline: &RenderPipeline, + key: &GraphicsKey, + ) -> PartRecords { + PartRecords { + pre_rasterization: self.part_named( + Part::PreRasterization, + objects, + pipeline, + key, + Naming::Record, + ), + fragment_shader: self.part_named( + Part::FragmentShader, + objects, + pipeline, + key, + Naming::Record, + ), + } + } + + /// What names the record of a whole making of `pipeline` (the variant's compiled pipeline) + /// for `key` (`shader_cache/driver.rs`), its parts' records `parts` + /// ([`record_parts`](Self::record_parts)): everything that reaches the driver's conversion of + /// one of its stages, and nothing else. + /// + /// That is the records of the two parts that hold shaders, with the vertex input, which + /// reaches MoltenVK's conversion configuration as its vertex stage's inputs, and whether the + /// pipeline rasterizes points ([`renders_points`], the one way the topology reaches that + /// configuration). /// /// So a state's sweep over blend factors, write masks, the logic operation, the fragment - /// output interface or the topology's class but points is one record and one cache: on - /// MoltenVK a cache per blend state converted every stage of every making, 64 over 32 states - /// of one vertex-and-fragment pair where one shared cache converts 2 - /// (`shader_cache/driver.rs`). Each part's name still holds its part's own fixed-function + /// output interface, its attachments' formats or the topology's class but points is one + /// record and one cache: on MoltenVK a cache per blend state converted every stage of every + /// making, 64 over 32 states of one vertex-and-fragment pair where one shared cache converts + /// 2 (`shader_cache/driver.rs`). Each part's name still holds its part's own fixed-function /// state, cull mode and front face among it, which reaches no conversion either, so such a /// sweep keeps records apart where it need not: that costs a conversion, never a wrong /// pipeline, since the driver keys each pipeline by everything its creation reads. @@ -664,16 +729,12 @@ impl GraphicsContent { objects: &VariantObjects, pipeline: &RenderPipeline, key: &GraphicsKey, + parts: &PartRecords, ) -> Making { - // Its two parts that hold shaders, and not the two it would throw away - // ([`part_named`](Self::part_named)). - let pre_rasterization = - self.part_named(Part::PreRasterization, objects, pipeline, key, None); - let fragment = self.part_named(Part::FragmentShader, objects, pipeline, key, None); objects .making("graphics") - .digest(&pre_rasterization) - .digest(&fragment) + .digest(&parts.pre_rasterization) + .digest(&parts.fragment_shader) .text(&(&pipeline.vertex_input, renders_points(key.topology))) } @@ -1168,11 +1229,11 @@ impl VariantObjects { let mut stages = [vk::PipelineCreationFeedback::default(); REPORTED_STAGES]; let mut reported_stages = 0; let driver_reports = shared.shader_cache.driver_reports() && libraries.is_none(); - // Its record is named by what reaches the driver's conversion of one of its stages - // (`GraphicsContent::record`), so a sweep over blend state or the fragment output - // interface is one record and one cache. + // Its records are named by what reaches the driver's conversion of one of its stages + // (`GraphicsContent::record_parts`), so a sweep over blend state, the fragment output + // interface or the attachments' formats is one record and one cache. let named = split.then(std::time::Instant::now); - let making = content.record(self, pipeline, key); + let parts = content.record_parts(self, pipeline, key); if let Some(at) = named { creation_log::note(|| "record".to_owned(), at.elapsed()); } @@ -1210,10 +1271,11 @@ impl VariantObjects { let names = content.names(self, pipeline, key); let linked = claimed .unwrap_or_else(|| libraries.claim(shared, &names, self.shared_layout())); - self.linked(infos, &names, linked) + self.linked(infos, &parts, linked) .map(|(raw, linked, made)| (raw, Some(linked), made)) } None => { + let making = content.record(self, pipeline, key, &parts); let info = infos.whole(); let count = info.stage_count as usize; reported_stages = if count <= REPORTED_STAGES { count } else { 0 }; @@ -1306,15 +1368,15 @@ impl VariantObjects { } /// The pipeline of `infos` linked, without link-time optimization, from `linked`'s libraries, - /// those of its parts named `names`, with whether it was linked here: the device's linked + /// with whether it was linked here: the device's linked /// pipeline of that link (`libraries.rs`), linked here where no caller linked it or is /// linking it, else the one another variant of the same link linked, waited for. Linking it - /// makes each library where no caller made it or is making it, through the device's shader - /// cache under its name, else waits for it. + /// makes each library where no caller made it or is making it, a library of shaders through + /// the device's shader cache under its part's record in `records`, else waits for it. fn linked( &self, infos: &Infos<'_>, - names: &[Hash256; 4], + records: &PartRecords, linked: Linked, ) -> Result<(vk::Pipeline, Linked, bool), Error> { let split = creation_log::splitting(); @@ -1322,7 +1384,7 @@ impl VariantObjects { let mut made = false; let raw = linked.pipeline().made(|| { made = true; - self.link(infos, names, &linked) + self.link(infos, records, &linked) })?; if let (false, Some(at)) = (made, asked) { creation_log::note(|| "link (another caller's)".to_owned(), at.elapsed()); @@ -1330,21 +1392,21 @@ impl VariantObjects { Ok((raw, linked, made)) } - /// Link the pipeline of `infos` from `linked`'s libraries, named `names`, as - /// [`linked`](Self::linked) says. + /// Link the pipeline of `infos` from `linked`'s libraries, those of shaders made under their + /// parts' records `records`, as [`linked`](Self::linked) says. fn link( &self, infos: &Infos<'_>, - names: &[Hash256; 4], + records: &PartRecords, linked: &Linked, ) -> Result { let shared = self.device.shared(); let split = creation_log::splitting(); let mut raws = [vk::Pipeline::null(); 4]; - for ((part, library), (raw, name)) in Part::ALL + for ((part, library), raw) in Part::ALL .into_iter() .zip(linked.parts()) - .zip(raws.iter_mut().zip(names)) + .zip(raws.iter_mut()) { // The creation log's split: how long the part took, and whether this making made it. let asked = split.then(std::time::Instant::now); @@ -1353,18 +1415,18 @@ impl VariantObjects { let mut flag = vk::GraphicsPipelineLibraryCreateInfoEXT::default().flags(part.flag()); let info = infos.part(part, &mut flag); - // A part with shaders is made through the device's shader cache, under a record - // of its own, with what its driver reports of it; one without holds nothing a - // record would keep. - let made = match part.holds_shaders() { - true => { + // A part with shaders is made through the device's shader cache, under its + // part's record (`GraphicsContent::record_parts`), with what its driver reports + // of it; one without holds nothing a record would keep. + let made = match records.of(part) { + Some(record) => { let _ = creation_log::take_record(); let made = shared - .make_graphics_pipeline(Making::new(part.kind()).digest(name), info); + .make_graphics_pipeline(Making::new(part.kind()).digest(record), info); made_here = Some(creation_log::take_record()); made? } - false => { + None => { made_here = Some(None); // SAFETY: every pointer in `info` outlives the call. let made = unsafe { diff --git a/crates/metal2vulkan-runtime/src/pipeline/libraries.rs b/crates/metal2vulkan-runtime/src/pipeline/libraries.rs index 4b8dbb567..4b2253042 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/libraries.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/libraries.rs @@ -40,9 +40,13 @@ //! library only after every pipeline it linked, at a program's settle or the device's teardown, //! so no variant destroys one another variant draws with. //! - **Cached across processes.** Each library of shaders (pre-rasterization, fragment shader) is -//! made through the device's shader cache under a record named by its part -//! (`shader_cache/driver.rs`), as a whole pipeline is; the vertex input and fragment output -//! libraries hold no shader and keep no record. +//! made through the device's shader cache under its part's record (`shader_cache/driver.rs`), +//! as a whole pipeline is: its part's name but for what reaches no stage's conversion, the +//! pass's attachment formats and the depth bias (`GraphicsContent::record_parts`). So a part's +//! libraries made against passes that differ only in an attachment's format, each a library of +//! its own, share one record and one `VkPipelineCache`, where the driver finds the stages the +//! first compiled. The vertex input and fragment output libraries hold no shader and keep no +//! record. use super::budget; use super::content_keyed::{program_call, ContentKeyed, Owned}; @@ -83,7 +87,7 @@ impl Part { } /// Whether its library compiles shaders: the pre-rasterization and fragment shader parts. - /// Only those are made through the device's shader cache, each under a record of its own + /// Only those are made through the device's shader cache, each under its part's record /// (`shader_cache/driver.rs`); the vertex input and fragment output libraries hold no shader, /// and are made without a pipeline cache. pub(crate) fn holds_shaders(self) -> bool { diff --git a/crates/metal2vulkan-runtime/src/render_target.rs b/crates/metal2vulkan-runtime/src/render_target.rs index ec22e62ee..d204675e3 100644 --- a/crates/metal2vulkan-runtime/src/render_target.rs +++ b/crates/metal2vulkan-runtime/src/render_target.rs @@ -296,6 +296,48 @@ impl PassShape { && *locations == keyed.locations } + /// This shape as the record of the driver's data of a pipeline made against it names it + /// (`GraphicsContent::record` in `pipeline/graphics.rs`), to be read as `Debug` text: each + /// attachment's presence in place of its format (whether each color index and the + /// depth/stencil attachment has one), and the rest of the shape whole. Its resolves are left + /// out, as a key's shape holds none ([`keyed`](PassShape::keyed)). + /// + /// A stage's conversion reads no attachment format through the pass: a format the translation + /// reads (a channel it rounds itself, a fetch in its storage form) is in the stage's own + /// words and constants, which name its record too. So makings that differ only in an + /// attachment's format share one record and one `VkPipelineCache`, where the driver finds the + /// stages it compiled for the first: ANV's fragment shader library of a module of some + /// 200,000 words made against `RGBA8Unorm`, `RGBA16Float` and `BGRA8Unorm` passes, 3.3 to + /// 3.7 s each with a cache of its own, is found in the first's shared cache in under a + /// millisecond (Mesa 26.2.6, Iris Xe, its creation feedback `APPLICATION_PIPELINE_CACHE_HIT`). + /// A driver whose + /// conversion does read a format keys that making's entry apart in the one cache: a compile, + /// never another pipeline. + pub(super) fn without_formats(&self) -> impl std::fmt::Debug + '_ { + let PassShape { + colors, + depth_stencil, + samples, + color_resolves: _, + depth_stencil_resolve: _, + fetch_inputs, + no_inputs, + storage, + view_mask, + locations, + } = self; + ( + colors.iter().map(Option::is_some).collect::>(), + depth_stencil.is_some(), + *samples, + *fetch_inputs, + no_inputs, + storage, + *view_mask, + locations, + ) + } + /// This shape with `storage` (ascending) left out of the draws' subpass; refused (an /// invariant) past a pass's color attachments. pub(super) fn with_storage(self, storage: &[u32]) -> Result { diff --git a/crates/metal2vulkan-runtime/src/shader_cache/driver.rs b/crates/metal2vulkan-runtime/src/shader_cache/driver.rs index 602e9a0ee..84934f120 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/driver.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/driver.rs @@ -46,13 +46,16 @@ //! with; and by the device's profile fingerprint (`store::entry_name`). A program's pipeline is //! described by its variant's stages (SPIR-V words, entry points, stage flags, required subgroup //! sizes, specialization), its layout (its immutable samplers among it), and the state its -//! making adds. A render making adds the names of the two pipeline parts that hold shaders, its -//! pre-rasterization and fragment shader libraries (`GraphicsContent::record` in -//! `pipeline/graphics.rs`), its vertex input, and whether it rasterizes points; it adds no -//! blend state, no write mask, no fragment output interface and no topology besides the point -//! class, none of which reaches the driver's conversion of a stage, so a state's sweep over -//! them is one record and one cache. A compute making adds its specialization and flags, which -//! do reach it. A helper of the runtime's is named by its SPIR-V and its parameters. +//! making adds. A render making adds the records of the two pipeline parts that hold shaders, +//! its pre-rasterization and fragment shader parts (`GraphicsContent::record_parts` in +//! `pipeline/graphics.rs`: each part's state with the pass's attachments' presence in place of +//! their formats), its vertex input, and whether it rasterizes points; it adds no blend state, +//! no write mask, no fragment output interface, no attachment format and no topology besides +//! the point class, none of which reaches the driver's conversion of a stage, so a state's +//! sweep over them is one record and one cache. A library of either part is made under that +//! part's record alone, so its libraries made against passes that differ only in a format +//! share one too. A compute making adds its specialization and flags, which do reach it. A +//! helper of the runtime's is named by its SPIR-V and its parameters. //! Records live in the content directory, which no build owns (`store.rs`): a new build of the //! runtime or the translator that leaves a pipeline's SPIR-V and state as they were finds its //! record. The driver keys each pipeline by everything its creation reads, so a description @@ -114,7 +117,7 @@ const MAGIC: [u8; 8] = *b"M2VPPLC\0"; /// bumps it, so no build opens a record another build names or frames otherwise. A record of an /// older version is named otherwise, so it is never found and never read: a bump costs a family /// its records, never a misread. -pub(crate) const VERSION: u32 = 2; +pub(crate) const VERSION: u32 = 3; /// The most `VkPipelineCache`es a device keeps live, one per record name. Past it a making of a /// further name is handed a cache of its own, destroyed once the making returned, so a program @@ -356,10 +359,11 @@ pub(crate) struct LiveCaches { } impl LiveCaches { - /// The device's cache of the record of `key`, and whether the device holds it (so a later - /// making of the name is handed this one and its caller destroys nothing). A cache is made - /// here, from the record where one loads, when the device holds none of that name; `None` - /// where the driver made none, when the making is handed a null cache. + /// The device's cache of the record of `key`, and how the making is handed it ([`Handed`]: + /// held by the device before it, or made now and kept, so a later making of the name is + /// handed this one and its caller destroys nothing, or made now for this making alone). A + /// cache is made here, from the record where one loads, when the device holds none of that + /// name; `None` where the driver made none, when the making is handed a null cache. /// /// The record is read and the cache made with no lock of the map held, so one making's load /// does not hold up another's: two makings of one name at once may each make a cache, and the @@ -370,10 +374,10 @@ impl LiveCaches { records: &Records, raw: &ash::Device, key: &Hash256, - ) -> Option<(Arc, bool)> { + ) -> Option<(Arc, Handed)> { if let Some(live) = lock(&self.caches).get(key) { count(&store.counters.driver_caches_shared); - return Some((Arc::clone(live), true)); + return Some((Arc::clone(live), Handed::Earlier)); } let name = records.name(key); let made = Arc::new(make_live(store, &records.identity, raw, name)?); @@ -384,13 +388,13 @@ impl LiveCaches { // SAFETY: nothing was ever handed this cache, and the device is live. unsafe { made.destroy(raw) }; count(&store.counters.driver_caches_shared); - return Some((live, true)); + return Some((live, Handed::Earlier)); } if caches.len() >= LIVE { - return Some((made, false)); + return Some((made, Handed::Own)); } caches.insert(*key, Arc::clone(&made)); - Some((made, true)) + Some((made, Handed::Kept)) } /// Destroy every cache: the device's teardown, with the device live and every pipeline of @@ -407,6 +411,17 @@ impl LiveCaches { } } +/// How a making is handed its record's cache ([`LiveCaches::of`]). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Handed { + /// The device held it before the making: an earlier making of the record made it. + Earlier, + /// Made for this making and kept by the device for later ones. + Kept, + /// Made for this making alone, past [`LIVE`]: destroyed once it returned. + Own, +} + /// The `VkPipelineCache` of the record `name` on the device of `raw`, made from that record's /// data where it loads and the driver takes it, else empty; `None` where the driver made none. fn make_live(store: &Store, identity: &Identity, raw: &ash::Device, name: String) -> Option { @@ -490,12 +505,14 @@ pub(crate) fn make( return create(vk::PipelineCache::null()).0; } let key = records.key(making); - let Some((held, shared)) = live.of(store, records, raw, &key) else { + let Some((held, handed)) = live.of(store, records, raw, &key) else { return create(vk::PipelineCache::null()).0; }; - // The creation log's split names whether the cache the making was handed holds its record. - crate::pipeline::creation_log::record_loaded(held.loaded); + // The creation log's split names whether the cache the making was handed holds its record, + // whether an earlier making made it, and what the driver found in it. + crate::pipeline::creation_log::record_handed(held.loaded, handed == Handed::Earlier); let (made, found) = create(held.cache); + crate::pipeline::creation_log::driver_found(found); let exited = exiting(); if made.is_ok() && !exited { match (held.loaded, found) { @@ -503,7 +520,7 @@ pub(crate) fn make( _ => keep(store, &records.identity, raw, &held), } } - if !shared && !exited { + if handed == Handed::Own && !exited { // SAFETY: the making returned, and no map holds this cache, so nothing else can be // handed it. unsafe { held.destroy(raw) }; diff --git a/crates/metal2vulkan-runtime/src/tests/driver_pipeline_compile.rs b/crates/metal2vulkan-runtime/src/tests/driver_pipeline_compile.rs index 076a1482f..c4f1d0f0b 100644 --- a/crates/metal2vulkan-runtime/src/tests/driver_pipeline_compile.rs +++ b/crates/metal2vulkan-runtime/src/tests/driver_pipeline_compile.rs @@ -52,6 +52,12 @@ //! library of shaders, so nothing of its stages is converted or compiled again; and no making //! asks for a cache, so none is shared. //! +//! **A pass's attachment formats name no record**: creations of one pair whose passes differ only +//! in their colour format each make their libraries of shaders against their own pass, handed the +//! first's caches, so a driver that keys a stage's compile without the format (ANV) finds it +//! there; a format the translation reads changes the fragment module, which keeps a record of +//! its own (`creations_over_colour_formats_take_the_first_s_records`). +//! //! **A library of shaders reports what its driver found**, as a whole pipeline's making does: a //! later device over the directory an earlier one wrote counts one report per library of shaders //! it makes, and reads no data back for one found in its record @@ -310,3 +316,106 @@ fn the_runtime_s_own_kernels_found_in_their_records_write_nothing() { assert_eq!(saves, 0, "kernels found in their records write nothing"); } } + +/// Render creations of one function pair whose passes differ only in their colour attachment's +/// format take the first creation's records: a pass's attachment formats reach no stage's +/// conversion, so they name no record (`GraphicsContent::record_parts`), and each making of +/// shaders is handed the cache the first made. Where the device links from libraries, each such +/// creation makes its own pre-rasterization and fragment shader libraries, against its own pass, +/// and both are handed the first's caches; a whole making is handed the first's one. A format +/// the translation reads keeps a record of its own: under `TextureWriteRoundingMode::NearestEven` +/// the fragment function rounds a half-float channel itself (`pipeline/color_writes.rs`), so its +/// module for an `RGBA16Float` attachment is another, and only its pre-rasterization part, whose +/// stages are the same, takes the first's. +/// +/// The counts are this crate's own arrangement and hold on every device. What the driver +/// reports it found is the driver's: ANV finds a fragment shader library of one module made +/// against another format's pass in the shared cache (Mesa 26.2.6, Iris Xe: +/// `APPLICATION_PIPELINE_CACHE_HIT`, where a cache of its own compiled it again, 3.3 to 3.7 s for +/// a 203,016-word module), so the run prints it and asserts only that a reporting device reports +/// one answer per making of shaders. +#[test] +fn creations_over_colour_formats_take_the_first_s_records() { + use metal2vulkan::metal::{PixelFormat, TextureWriteRoundingMode}; + use metal2vulkan::pipeline::ColorAttachmentDescriptor; + let scratch = Scratch::new("driver-pipeline-formats"); + let device = device(&scratch.0); + let base = descriptor(&device); + let options = PipelineOptions::default(); + let links = device.shared().libraries.is_some(); + let with = |format: PixelFormat, rounding: TextureWriteRoundingMode| { + let mut d = base.clone(); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new(format)); + d.texture_write_rounding_mode = rounding; + d + }; + // What a creation of `d` did: the caches it was handed that an earlier making made, the + // libraries it made of a fragment shader, and what its driver reported. + let create = |d: &metal2vulkan::pipeline::RenderPipelineDescriptor| { + let shared_before = device.shared().shader_cache.caches_shared(); + let before = device.shader_cache_statistics(); + let counts_before = device.work_counts(); + let state = device.new_render_pipeline_state(d, &options).unwrap(); + let after = device.shader_cache_statistics(); + let shared = device.shared().shader_cache.caches_shared() - shared_before; + let fragment_shaders = device.work_counts().fragment_shader_libraries_made + - counts_before.fragment_shader_libraries_made; + let hits = after.driver_pipeline_hits - before.driver_pipeline_hits; + let misses = after.driver_pipeline_misses - before.driver_pipeline_misses; + (state, shared, fragment_shaders, hits, misses) + }; + let _first = create(&with( + PixelFormat::RGBA8Unorm, + TextureWriteRoundingMode::TowardZero, + )); + // Each making of shaders a creation over another format makes: where the device links, its + // two libraries of shaders, each against its own pass; else its one whole pipeline. + let makings = if links { 2 } else { 1 }; + let mut kept = Vec::new(); + for format in [PixelFormat::BGRA8Unorm, PixelFormat::RGBA16Float] { + let (state, shared, fragment_shaders, hits, misses) = + create(&with(format, TextureWriteRoundingMode::TowardZero)); + println!( + "DRIVER-PIPELINE-FORMATS: {format:?}: {shared} of {makings} makings took an earlier \ + making's cache, {fragment_shaders} fragment shader libraries made, {hits} hits and \ + {misses} misses reported" + ); + assert_eq!( + shared, makings, + "a creation whose pass differs from the first's only in its colour format ({format:?}) \ + must be handed the first's cache for each of its {makings} makings of shaders, the \ + format naming no record: {shared} were" + ); + if links { + assert_eq!( + fragment_shaders, 1, + "a pass of another format takes a fragment shader library of its own" + ); + } + if hits + misses > 0 { + assert_eq!( + hits + misses, + makings, + "a device that reports what it found reports one answer per making of shaders" + ); + } + kept.push(state); + } + // A format the translation reads: the rounding module is another, so its fragment shader's + // making names a record of its own, and only the pre-rasterization part's, where the device + // links, takes the first's. + let (_rounded, shared, _, hits, misses) = create(&with( + PixelFormat::RGBA16Float, + TextureWriteRoundingMode::NearestEven, + )); + let expected = if links { 1 } else { 0 }; + println!( + "DRIVER-PIPELINE-FORMATS: RGBA16Float rounded to nearest even: {shared} makings took an \ + earlier making's cache, {hits} hits and {misses} misses reported" + ); + assert_eq!( + shared, expected, + "a fragment module the format changes keeps a record of its own: {shared} makings took an \ + earlier making's cache, {expected} expected" + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 48de9fc09..5f7d7cad3 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -446,6 +446,7 @@ mod rebind_descriptor_slip; mod rebind_making_wait; #[cfg(all(m2v_gpu, target_os = "linux"))] mod reclaim_submit_bench; +mod record_pass_formats; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod recorded_at_the_call; mod recorder_shards; diff --git a/crates/metal2vulkan-runtime/src/tests/record_pass_formats.rs b/crates/metal2vulkan-runtime/src/tests/record_pass_formats.rs new file mode 100644 index 000000000..4e09bd404 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/record_pass_formats.rs @@ -0,0 +1,62 @@ +//! A record of the driver's data names a pass without its attachments' formats +//! (`PassShape::without_formats`, `GraphicsContent::record_parts`): two passes that differ only +//! in a colour or depth/stencil attachment's format name one record, and two that differ in which +//! attachments they have, their samples, their fetch inputs or their view mask name two. + +use crate::color_list::ColorList; +use crate::render_target::PassShape; +use metal2vulkan::vk::Format; + +/// A pass of `samples` samples with `colors` and the depth/stencil attachment `depth`. +fn shape(samples: u32, colors: &[Option], depth: Option) -> PassShape { + PassShape { + colors: ColorList::of(colors.iter().copied()).unwrap(), + depth_stencil: depth, + samples, + color_resolves: ColorList::of(colors.iter().map(|_| None)).unwrap(), + depth_stencil_resolve: None, + fetch_inputs: false, + no_inputs: ColorList::new(), + storage: ColorList::new(), + view_mask: 0, + locations: ColorList::new(), + } +} + +/// How a record names `shape`. +fn named(shape: &PassShape) -> String { + format!("{:?}", shape.without_formats()) +} + +#[test] +fn a_record_names_a_pass_without_its_formats() { + let rgba8 = Some(Format::R8G8B8A8_UNORM); + let bgra8 = Some(Format::B8G8R8A8_UNORM); + let half = Some(Format::R16G16B16A16_SFLOAT); + let first = shape(1, &[rgba8], None); + for other in [bgra8, half] { + assert_eq!(named(&first), named(&shape(1, &[other], None)), "{other:?}"); + } + assert_eq!( + named(&shape(4, &[rgba8, None, half], Some(Format::D32_SFLOAT))), + named(&shape( + 4, + &[bgra8, None, rgba8], + Some(Format::D24_UNORM_S8_UINT) + )), + "every attachment's format left out, its presence kept" + ); + for apart in [ + shape(1, &[rgba8, rgba8], None), + shape(1, &[None, rgba8], None), + shape(1, &[rgba8], Some(Format::D32_SFLOAT)), + shape(4, &[rgba8], None), + PassShape { + fetch_inputs: true, + ..shape(1, &[rgba8], None) + }, + shape(1, &[rgba8], None).with_view_mask(0b11), + ] { + assert_ne!(named(&first), named(&apart), "{apart:?}"); + } +} diff --git a/crates/metal2vulkan/src/env_vars.rs b/crates/metal2vulkan/src/env_vars.rs index 7d409c658..e00498f3c 100644 --- a/crates/metal2vulkan/src/env_vars.rs +++ b/crates/metal2vulkan/src/env_vars.rs @@ -46,7 +46,9 @@ pub const REGISTRY: &[EnvVar] = &[ name, the SHA-256 of its bitcode and the constant values it was made with, each \ color attachment's format, blend and write mask, the depth and stencil formats \ and the raster samples), and the creation's time, split by the making's parts (the digests, each library made \ - with its record loaded or missed or another caller's, the link) and by \ + with its record loaded, missed or its cache shared with an earlier making, and \ + what its driver reported, found in that cache or compiled, or another caller's, \ + the link) and by \ MoltenVK's activities where its performance tracking is on \ (MVK_CONFIG_PERFORMANCE_TRACKING=1); and once per reason, why a draw \ that reads its own pass's color attachment after a barrier took the split rather \ diff --git a/docs/API.md b/docs/API.md index 4ba30b862..40ff4e44c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1762,9 +1762,13 @@ makes (id name `metal2vulkan-pipeline-creation`, `Info` severity): its kernel, i and its length), each specialization constant, the precision notes the stage holds under that specialization and the creation's time. And one line per render `VkPipeline` it makes (the same id name and severity), with where its time went: the -wait for its turn, the digests that name its parts, each library (made by this making, from its -driver cache record or not, or another caller's) and the link; a state's first line also names -the descriptor it was made from (each function's name, the SHA-256 of its bitcode and the constant +wait for its turn, the digests that name its parts, each library (made by this making, its +driver cache record loaded, missed or shared with an earlier making in this process, and whether +its driver found it in that cache or compiled it, or another caller's) and the link (a record +names its pass by which attachments it has, its samples and its inputs, not their formats; a +format a stage's translation reads names the record through that stage's module, so makings that +differ only in formats no translation reads share one); a state's first line also names the +descriptor it was made from (each function's name, the SHA-256 of its bitcode and the constant values it was made with, each color attachment's format, blend and write mask, the depth and stencil formats and the raster samples). With `METAL2VULKAN_DUMP_PIPELINES` naming a directory, a device writes each such pipeline's SPIR-V modules there, one file per module named by the hash