diff --git a/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs b/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs index f85725f09..cfe583073 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs @@ -260,6 +260,13 @@ impl Line { self } + /// The line of a pipeline its state's creation hands the pool after its predicted key's + /// general form, nothing waiting for it: the predicted key itself (`render/residual.rs`). + pub(crate) fn ahead_at_creation(mut self) -> Line { + self.note = "; begun at its state's creation after its general form, the predicted key"; + self + } + /// Make the pipeline with `make` on this thread, and deliver the line. pub(crate) fn made( self, diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index 0f549a8f4..795edc30a 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -84,6 +84,9 @@ pub(super) use making::Pending; pub(super) use objects::ShaderModules; pub(super) use objects::{create_set_layout, set_needs, RawPipeline, VariantObjects}; pub use options::{PipelineOption, PipelineOptions}; +/// The general form of a key (`render/residual.rs`), for `tests::general_form`. +#[cfg(test)] +pub(super) use render::general_form; /// The form a driver's facts choose, for the test that holds every committed profile to it /// (`tests::pipeline::every_committed_driver_reads_its_uniform_views_at_their_residuals`). #[cfg(test)] diff --git a/crates/metal2vulkan-runtime/src/pipeline/predicted.rs b/crates/metal2vulkan-runtime/src/pipeline/predicted.rs index f15d951a7..2b75b67cd 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/predicted.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/predicted.rs @@ -15,7 +15,13 @@ //! unbound one is. A draw that leaves those slots unbound takes this key itself; the draws that //! bind them do so at offsets the creation cannot know, and the residual form reads the same //! bytes at every one: a draw whose own key is not made takes it at once while its own is made. -//! On a device that reads every view at its residual (MoltenVK) it is their own key. +//! On a device that reads every view at its residual (MoltenVK) it is their own key. The key +//! made is the general form of that (`render/residual.rs`): each texture slot's +//! `SpecKey::PlainHalfTexels` at 0 too, the class routine that converts every bound class, and +//! its `SpecKey::UnmeasuredTexels` at 0, so a draw of any texture takes it at once while its own +//! key is made; the key with those slots' `PlainHalfTexels` at 1, as unbound ones take, which a +//! draw binding a plain, measured class takes, is handed to the pool right after, at the rank +//! nothing waits for, and nothing waits for it. //! - **The tests**: for a fragment function that stores a color through the interlocked storage //! form before its depth and stencil tests (`RuntimeFact::TestedStorageWrites`) in a pipeline //! with a depth or stencil attachment, tests that drop fragments but write neither attachment and @@ -51,9 +57,10 @@ //! A state the prediction cannot describe from itself alone (tessellated, a mesh pipeline, //! separate depth and stencil formats, a fragment function that writes depth) makes nothing here. //! The key is the draw's own key type: a draw that takes the same key takes the pipeline made, and -//! so does a draw whose key differs only where it reads a uniform-view slot at the bind offset -//! alone, until its own key's pipeline, made on the pool meanwhile, is made (`render/residual.rs`); -//! any other draw makes its own, as before. Nothing an answer depends on changes, only when the +//! so does a draw whose key differs only in constants the general form sets (a uniform-view slot +//! read at the bind offset alone, a texture slot's plain `half` arm or its unmeasured class), until +//! its own key's pipeline, made on the pool meanwhile, is made (`render/residual.rs`); any other +//! draw makes its own, as before. Nothing an answer depends on changes, only when the //! driver is called. A failed making is not kept and refuses nothing: the draw that needs the key //! meets it as before. //! @@ -68,11 +75,11 @@ //! state. A draw whose key the creation did not make makes its own, as before's records of the //! driver's data still serve that making where the same pipeline was made before. //! -//! Under `PipelineWaitPolicy::Exact` the predicted key's making runs on the creating thread, -//! joined before the creation returns (`RenderVariant::make_at_creation`), at the rank of a -//! making the program waits for. Under `PipelineWaitPolicy::Bounded` (the default) it is handed to -//! the device's pool, kept by the state as a draw's making is, and the creation returns: a host -//! that creates a state inside a command buffer's encoding (a guest's state looked up there +//! Under `PipelineWaitPolicy::Exact` the making of the predicted key's general form runs on the +//! creating thread, joined before the creation returns (`RenderVariant::make_at_creation`), at the +//! rank of a making the program waits for. Under `PipelineWaitPolicy::Bounded` (the default) it is +//! handed to the device's pool, kept by the state as a draw's making is, and the creation returns: +//! a host that creates a state inside a command buffer's encoding (a guest's state looked up there //! first) is not held by a driver's cold compile, measured at 11.6 s on MoltenVK with a cold //! Metal compiler service. The first draw takes the making in flight, and its command buffer //! waits a bound for it (`render/pending.rs`). A key predicted on the early-tests variant (above) @@ -100,15 +107,26 @@ use std::sync::Arc; impl GraphicsState { /// Make the `VkPipeline` of the key the state's first draw is predicted to take (the module - /// docs), now; a key whose pass is refused is left to its draw. + /// docs), now, in its general form, which a draw of every binding can take + /// (`render/residual.rs`); where the key differs from that form, hand the key itself to the + /// device's pool right after, at the rank nothing waits for, for the draws that bind what the + /// prediction names. A key whose pass is refused is left to its draw. pub(crate) fn make_at_creation(&self) { let Some((variant, key)) = self.predicted() else { return; }; - let Ok(pass) = render_target::compatible_pass(self.device(), &key.pass) else { + let device = self.device(); + let Ok(pass) = render_target::compatible_pass(device, &key.pass) else { return; }; - RenderVariant::make_at_creation(vec![(variant, key, pass)], self); + let (made, ahead) = match variant.general_key(&key) { + None => (key, Vec::new()), + Some(general) => match render_target::compatible_pass(device, &key.pass) { + Ok(own) => (general, vec![(Arc::clone(&variant), key, own)]), + Err(_) => (general, Vec::new()), + }, + }; + RenderVariant::make_at_creation(vec![(variant, made, pass)], ahead, self); } /// The key of the predicted first draw (the module docs), where the state alone describes diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index 641a8a580..d93b6ccb3 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -86,6 +86,9 @@ use std::time::Instant; mod residual; +/// The general form of a key, which `tests::general_form` reads from IDs and meanings alone. +#[cfg(test)] +pub(crate) use residual::general_form; #[cfg(test)] pub(crate) use residual::views_read_at_bind; pub(crate) use residual::{reads_views_at_bind, residual_form}; @@ -2698,7 +2701,7 @@ impl RenderVariant { /// The `VkPipeline` of `key`, from the memo or made now against `render_pass`, a pass of /// `key.pass`; made once, outside the memo's lock (`making.rs`), for a draw of `state` that /// binds `formats`, whose part of the pipeline creation log logs it. Where it is not made and - /// its residual form's is, the draw takes that one, and `key`'s is made on the device's pool + /// its general form's is, the draw takes that one, and `key`'s is made on the device's pool /// (`render/residual.rs`). A lookup by key (`WorkCounts::graphics_pipelines_looked_up`). pub(crate) fn graphics_pipeline( self: &Arc, @@ -2712,6 +2715,7 @@ impl RenderVariant { .counts .graphics_pipeline_looked_up(); self.made_or_make(key, render_pass, (state, formats)) + .map(|(made, _)| made) } /// The `VkPipeline` of `key` for an execution's settle at commit, which records nothing @@ -2743,17 +2747,18 @@ impl RenderVariant { }) } - /// [`graphics_pipeline`](Self::graphics_pipeline)'s finding or making, uncounted. + /// [`graphics_pipeline`](Self::graphics_pipeline)'s finding or making, uncounted, with + /// whether it is `key`'s own `VkPipeline`, not its general form's. fn made_or_make( self: &Arc, key: &GraphicsKey, render_pass: &Arc, (state, formats): (&GraphicsState, crate::degradation::BoundFormats<'_>), - ) -> Result, Error> { - if let Some(drawn) = self.residual_drawn(key, render_pass, (state, formats)) { + ) -> Result<(Arc, bool), Error> { + if let Some(drawn) = self.general_drawn(key, render_pass, (state, formats)) { return Ok(drawn); } - self.pipelines.get_or_make(key, || { + let made = self.pipelines.get_or_make(key, || { let make = || { self.objects.graphics_pipeline( &self.pipeline, @@ -2770,7 +2775,8 @@ impl RenderVariant { make, ), } - }) + })?; + Ok((made, true)) } /// The libraries of `key`'s parts (`libraries.rs`), claimed on this thread: the device's @@ -2802,10 +2808,13 @@ impl RenderVariant { /// thread, the others on the device's pool, joined (`Pool::join_all`, the owner's HITCH rules 1 /// and 3). Each piece settles its own key's memo entry as its pipeline is made, a failed one /// not kept, and the join returns once every piece settled. The concurrent part only calls the - /// driver and settles its entries. Their specialized notices wait for their first draws - /// ([`first_use`](Self::first_use)). Each key is its variant's. + /// driver and settles its entries. The makings of `ahead`'s keys (a predicted key whose general + /// form is among `keys`, `render/residual.rs`) are handed to the pool right after, under either + /// policy, at the rank nothing waits for, and not waited for. Their specialized notices wait + /// for their first draws ([`first_use`](Self::first_use)). Each key is its variant's. pub(crate) fn make_at_creation( keys: Vec<(Arc, GraphicsKey, RenderPassObject)>, + ahead: Vec<(Arc, GraphicsKey, RenderPassObject)>, state: &GraphicsState, ) { let device = &state.0.device; @@ -2871,6 +2880,24 @@ impl RenderVariant { drop(ticket.settle(made)); })); } + // Those made ahead of the draws that take them, right after: handed to the pool under + // either wait, at the rank nothing waits for until a draw does, and not waited for here. + for (variant, key, pass) in ahead { + let Begun::Yours(ticket) = variant.pipelines.begin(&key) else { + continue; + }; + let line = state.0.log.as_ref().map(|log| { + log.begin(( + &variant.key, + &variant.pipeline, + &key, + variant.logged_spirv(), + )) + .ahead_at_creation() + }); + let claimed = variant.claim_libraries(&key); + drop(variant.pooled(state, (key, Arc::new(pass), ticket), (line, claimed), true)); + } // Those handed to the pool, waited for a bound at most: a making still running then goes // on for the draws that take it. let deadline = Instant::now() + device.compile_device().policy().pipeline_creation_wait; @@ -2928,9 +2955,9 @@ impl RenderVariant { /// the pool where a specialized note tests them, `VariantObjects::tested_formats`), whose part /// of the pipeline creation log logs it as [`graphics_pipeline`](Self::graphics_pipeline) /// does. The draw goes on meanwhile; its command buffer's batch is submitted once it is made - /// (`render/pending.rs`). Where it is not made and its residual form's is, the draw takes that + /// (`render/pending.rs`). Where it is not made and its general form's is, the draw takes that /// one, and nothing waits for `key`'s making (`render/residual.rs`). With whether it is - /// `key`'s own `VkPipeline`, made: not a residual form, nor being made, which a render encoder + /// `key`'s own `VkPipeline`, made: not a general form, nor being made, which a render encoder /// keeps no draw's shape with (`render/draw_shape.rs`). pub(crate) fn begin_graphics_pipeline( self: &Arc, @@ -2951,9 +2978,9 @@ impl RenderVariant { } (DrawPipeline::Made(made), true) } - // A draw of a key another caller makes takes the key's residual form where it is made + // A draw of a key another caller makes takes the key's general form where it is made // (`render/residual.rs`). - (Begun::Pending(pending), _) => match self.residual_made(key) { + (Begun::Pending(pending), _) => match self.general_made(key) { Some(drawn) => { device.shared().counts.residual_form_drawn(); (DrawPipeline::Made(drawn), false) @@ -2962,9 +2989,9 @@ impl RenderVariant { }, (Begun::Yours(ticket), _) => { match self.make_drawn(device, key, compatible, (state, formats), ticket) { - // Handed to the pool: the draw takes the key's residual form where it is made, + // Handed to the pool: the draw takes the key's general form where it is made, // and nothing waits for the making (`render/residual.rs`). - DrawPipeline::Making(pending) => match self.residual_made(key) { + DrawPipeline::Making(pending) => match self.general_made(key) { Some(drawn) => { device.shared().counts.residual_form_making(); device.shared().counts.residual_form_drawn(); @@ -2983,21 +3010,25 @@ impl RenderVariant { /// a pass of custom sample positions), finding first, as /// [`begin_graphics_pipeline`](Self::begin_graphics_pipeline) does, an entry `state`'s last /// draws found made ([`last_made`](Self::last_made)), and keeping where one it looks up lies. + /// A key found neither way is made now, or, where its general form's is made, drawn with that + /// one while its own is made on the pool ([`general_drawn`](Self::general_drawn)). With + /// whether it is `key`'s own `VkPipeline`, not its general form's, as + /// [`begin_graphics_pipeline`](Self::begin_graphics_pipeline)'s. pub(crate) fn graphics_pipeline_now( self: &Arc, device: &Device, key: &DrawKey<'_>, render_pass: &Arc, (state, formats): (&GraphicsState, crate::degradation::BoundFormats<'_>), - ) -> Result, Error> { + ) -> Result<(Arc, bool), Error> { if let Some(made) = self.last_made(state, key) { - return Ok(made); + return Ok((made, true)); } device.shared().counts.graphics_pipeline_looked_up(); let key = &key.key(); if let Some((made, at)) = self.pipelines.made_with_at(key) { self.keep_last(state, key, at); - return Ok(made); + return Ok((made, true)); } self.made_or_make(key, render_pass, (state, formats)) } diff --git a/crates/metal2vulkan-runtime/src/pipeline/render/residual.rs b/crates/metal2vulkan-runtime/src/pipeline/render/residual.rs index 851e8b7c4..4909d3888 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render/residual.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render/residual.rs @@ -1,6 +1,9 @@ -//! A draw's key's residual form: a draw whose own `VkPipeline` is not made draws at once with its -//! residual form's where that one is made, and its own is made on the device's pool meanwhile, -//! nothing waiting for it. +//! A draw's key's general form: a draw whose own `VkPipeline` is not made draws at once with its +//! general form's where that one is made, and its own is made on the device's pool meanwhile, +//! nothing waiting for it. The general form is the key with each constant that has an arm valid +//! for every binding at that arm ([`general_form`]); its first such constant was the uniform +//! views' (the residual form, below), and the texel routes' are the others (the end of these +//! docs). //! //! A buffer slot a function reads through a uniform view declares the boolean specialization //! `SpecKey::RangeAtBindOffset`. A draw's plan sets it to 1 where the slot's descriptor range starts @@ -20,12 +23,13 @@ //! form reads byte `m` of. Only at a bind offset at or past the end of the bound buffer is the //! range widened down into it, the residual then not 0, and there either form reads only bytes //! outside the bound buffer. -//! - **Made at creation.** A state's creation makes its predicted key's residual form -//! (`predicted.rs`), which a draw at any bind offset can take; a compute state's creation, its -//! predicted region's (`dispatch_making.rs`), which a dispatch at any bind offset can take. +//! - **Made at creation.** A state's creation makes its predicted key's general form +//! (`predicted.rs`), each uniform-view slot read at its residual, which a draw at any bind offset +//! can take; a compute state's creation, its predicted region's residual form +//! (`dispatch_making.rs`), which a dispatch at any bind offset can take. //! - **Drawn while the key's own is made.** A draw whose key's `VkPipeline` is neither made nor -//! linked at once, and whose residual form's is made ([`residual_made`]), draws with the residual -//! form's at once ([`RenderVariant::begin_graphics_pipeline`], and [`residual_drawn`] for the +//! linked at once, and whose general form's is made ([`general_made`]), draws with the general +//! form's at once ([`RenderVariant::begin_graphics_pipeline`], and [`general_drawn`] for the //! draws that make their pipelines at once). The key's own making goes to the device's pool, //! where no caller began it, at the rank of a making nothing waits for (`budget::Urgency::Ahead`), //! and a later draw of the key takes it once made. Only that direction: a draw whose key has 0 @@ -48,14 +52,48 @@ //! - **Only GPU time moves.** Until the key's making lands, its draws' uniform reads take the //! residual: on ANV, loads where the key's form has pushed constants. `WorkCounts` counts the //! draws and dispatches recorded so (`residual_form_draws`) and the makings begun so -//! (`residual_form_makings`). +//! (`residual_form_makings`), whichever of the general form's constants moved. //! Such a making may outlast its draw's command buffer, which does not wait for it //! (`WorkCounts::pipeline_pool_busy` says when the pool holds none). //! +//! **The texel routes' general arms.** On a device that samples through Metal's own texture unit +//! (MoltenVK), a texture slot a function converts to `half` declares two booleans more, each with +//! an arm that serves every bound format exactly: +//! +//! - `SpecKey::PlainHalfTexels` at 0 converts each texel by the class routine, the bound class +//! read from push data, which for a plain class (`TexelFormat::plain_on_metal_sampler`: every +//! class but a YCbCr field on the grid `8192`) rounds the `float` texel to nearest even as the +//! plain arm (1) does; the plain arm lets Metal's compiler fold the conversion into the image +//! instruction (`lower::texture::half`). A slot bound to nothing, or to a plain class, takes 1, +//! and a draw binding a YCbCr field on the grid `8192` takes 0. +//! - `SpecKey::UnmeasuredTexels` names the bound class to the slot's precision note alone: no +//! instruction reads it, so both values run alike, and 0 is its general arm. A slot bound to +//! nothing takes 0, and a draw binding a class whose `half` conversion is not measured +//! (`TexelFormat::unmeasured_on_metal_sampler`: BC4 to BC7 and the linear ASTC formats among +//! them) 1. +//! +//! A state's creation predicts no texture bound, so a draw of the predicted variant binding a +//! class of either kind keys apart from the predicted key: with that key alone made, such a draw +//! would make a pipeline of its own at the draw, a compile its command buffer waits for (and past +//! its bound drops the draw, `PipelineWaitPolicy::Bounded`). So a state's creation makes its +//! predicted key's general form, which every draw of that variant can take, and hands its +//! predicted key itself, where it differs (its texture slots' `PlainHalfTexels` at 1, as unbound +//! slots take), to the pool right after, at the rank nothing waits for: a draw binding a plain, +//! measured class takes it once made, and every other draw of the variant takes the general form +//! at once while its own is made (`predicted.rs`). The cost: such a creation makes two pipelines, +//! the second on the pool, nothing waiting for it; and GPU time, until a draw's own key lands, of +//! the class routine at each `half` conversion of an image instruction's texel in place of the +//! device's own conversion. +//! +//! Constants with no arm that serves every binding stay as before, each value a pipeline of its +//! own: `SpecKey::SamplerState` (each sampler word a sampling emulation of its own) and +//! `SpecKey::BicubicTexels` (how Metal's bicubic filter treats each format's texels). +//! +//! [`general_form`]: RenderVariant::general_form //! [`residual_form`]: RenderVariant::residual_form //! [`reads_views_at_bind`]: reads_views_at_bind -//! [`residual_made`]: RenderVariant::residual_made -//! [`residual_drawn`]: RenderVariant::residual_drawn +//! [`general_made`]: RenderVariant::general_made +//! [`general_drawn`]: RenderVariant::general_drawn use super::{DrawPipeline, GraphicsState, RenderVariant}; use crate::degradation::BoundFormats; @@ -85,49 +123,72 @@ impl RenderVariant { residual_form(constants, specialization) } - /// The made `VkPipeline` of `key`'s residual form (the module docs), where `key` is not its - /// own residual form. - pub(super) fn residual_made(&self, key: &GraphicsKey) -> Option> { - let residual = GraphicsKey { - specialization: self.residual_form(&key.specialization)?, + /// `specialization` with each of the variant's constants that has an arm serving every binding + /// at that arm, its general form (the module docs): `SpecKey::RangeAtBindOffset`, + /// `SpecKey::PlainHalfTexels` and `SpecKey::UnmeasuredTexels` at 0; `None` where every one of + /// them is there already. + pub(crate) fn general_form( + &self, + specialization: &SpecializationKey, + ) -> Option { + let constants = self + .pipeline + .stages + .iter() + .flat_map(|module| &module.specialization.constants) + .map(|constant| (constant.id, constant.key)); + general_form(constants, specialization) + } + + /// `key` with its specialization's general form ([`general_form`](Self::general_form)), where + /// `key` is not its own general form. + pub(crate) fn general_key(&self, key: &GraphicsKey) -> Option { + Some(GraphicsKey { + specialization: self.general_form(&key.specialization)?, topology: key.topology, primitive_restart: key.primitive_restart, pass: key.pass.clone(), strides: key.strides.clone(), fixed: key.fixed, sample_positions: key.sample_positions.clone(), - }; - self.pipelines.made(&residual) + }) + } + + /// The made `VkPipeline` of `key`'s general form (the module docs), where `key` is not its + /// own general form. + pub(super) fn general_made(&self, key: &GraphicsKey) -> Option> { + self.pipelines.made(&self.general_key(key)?) } /// For a draw of `state` that binds `formats` and makes its pipeline at once /// ([`graphics_pipeline`](Self::graphics_pipeline)): where `key`'s `VkPipeline` is not made and - /// its residual form's is, the residual form's, `key`'s making handed to the device's pool + /// its general form's is, the general form's, `key`'s making handed to the device's pool /// against `compatible` where no caller began it (the module docs); `key`'s own where it was - /// made meanwhile or is linked at once. `None` where the draw makes or waits for `key`'s own. - pub(super) fn residual_drawn( + /// made meanwhile or is linked at once; with whether it is `key`'s own. `None` where the draw + /// makes or waits for `key`'s own. + pub(super) fn general_drawn( self: &Arc, key: &GraphicsKey, compatible: &Arc, (state, formats): (&GraphicsState, BoundFormats<'_>), - ) -> Option> { + ) -> Option<(Arc, bool)> { if self.pipelines.made(key).is_some() { return None; } - let drawn = self.residual_made(key)?; + let drawn = self.general_made(key)?; let device = &self.objects.device; match self.pipelines.begin(key) { - Begun::Made(made) => return Some(made), + Begun::Made(made) => return Some((made, true)), Begun::Pending(_) => {} Begun::Yours(ticket) => { match self.make_drawn(device, key, compatible, (state, formats), ticket) { - DrawPipeline::Made(made) => return Some(made), + DrawPipeline::Made(made) => return Some((made, true)), DrawPipeline::Making(_) => device.shared().counts.residual_form_making(), } } } device.shared().counts.residual_form_drawn(); - Some(drawn) + Some((drawn, false)) } } @@ -143,7 +204,40 @@ pub(crate) fn residual_form<'a>( constant.id == id && matches!(constant.key, SpecKey::RangeAtBindOffset(_)) }) }; - let mut residual: Option = None; + zeroed(specialization, at_bind) +} + +/// `specialization` with each constant of `constants` (a pipeline's stages', each its ID and its +/// meaning) that has an arm serving every binding at that arm (the module docs): +/// `SpecKey::RangeAtBindOffset` (the residual form's), `SpecKey::PlainHalfTexels` and +/// `SpecKey::UnmeasuredTexels`, each at 0; `None` where every one of them is 0 there already. A +/// constant `specialization` gives no entry takes the module's default: 0 for the first and last, +/// and a plan gives every `PlainHalfTexels` its value. +pub(crate) fn general_form( + constants: impl Iterator + Clone, + specialization: &SpecializationKey, +) -> Option { + let general = |id: u32| { + constants.clone().any(|(at, key)| { + at == id + && matches!( + key, + SpecKey::RangeAtBindOffset(_) + | SpecKey::PlainHalfTexels(_) + | SpecKey::UnmeasuredTexels(_) + ) + }) + }; + zeroed(specialization, general) +} + +/// `specialization` with the value of each constant `chosen` names zeroed, where one of them is +/// not 0 there; `None` where none is. +fn zeroed( + specialization: &SpecializationKey, + chosen: impl Fn(u32) -> bool, +) -> Option { + let mut zeroed: Option = None; for entry in &specialization.entries { let at = entry.offset as usize; let range = at..at + entry.size as usize; @@ -151,12 +245,12 @@ pub(crate) fn residual_form<'a>( .data .get(range.clone()) .is_some_and(|bytes| bytes.iter().any(|&byte| byte != 0)); - if set && at_bind(entry.constant_id) { - let residual = residual.get_or_insert_with(|| specialization.clone()); - residual.data[range].fill(0); + if set && chosen(entry.constant_id) { + let zeroed = zeroed.get_or_insert_with(|| specialization.clone()); + zeroed.data[range].fill(0); } } - residual + zeroed } /// Whether `device` reads a uniform view at its bind offset alone where the view's range starts diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 812f5d086..ddb93327b 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -8545,15 +8545,15 @@ impl RenderLowering { Some(Ok(made)) => (DrawPipeline::Made(made), true), // A failed making is made again here, as a caller after one // does (`making.rs`). - Some(Err(_)) => ( - DrawPipeline::Made(variant.graphics_pipeline_now( + Some(Err(_)) => { + let (made, own) = variant.graphics_pipeline_now( &device, &key, &compatible, (&pipeline, &formats), - )?), - true, - ), + )?; + (DrawPipeline::Made(made), own) + } // Still being made at the bound: the draw records nothing, // before anything of it is tracked, as a draw whose pipeline // a capture misses does; later command buffers draw with it. @@ -8566,17 +8566,17 @@ impl RenderLowering { made => made, } } - (false, None) => ( - DrawPipeline::Made(variant.graphics_pipeline_now( + (false, None) => { + let (made, own) = variant.graphics_pipeline_now( &device, &key, &compatible, (&pipeline, &formats), - )?), - true, - ), + )?; + (DrawPipeline::Made(made), own) + } }; - // Kept where it is the key's own, made: not a residual form; and where finding it + // Kept where it is the key's own, made: not its general form; and where finding it // announced nothing at each occurrence. if let (Some(token), DrawPipeline::Made(made), true, false) = (token, &draw_pipeline, own, watch.met()) diff --git a/crates/metal2vulkan-runtime/src/tests/general_form.rs b/crates/metal2vulkan-runtime/src/tests/general_form.rs new file mode 100644 index 000000000..4daa3c725 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/general_form.rs @@ -0,0 +1,74 @@ +//! A key's general form (`pipeline/render/residual.rs`): each constant with an arm that serves +//! every binding at that arm, the others as the key has them. + +use crate::pipeline::general_form; +use metal2vulkan::cache::SpecializationKey; +use metal2vulkan::pipeline::{SlotClass, SlotRef, SpecKey, Stage}; +use metal2vulkan::vk::SpecializationMapEntry; + +/// Fragment slot `index` of `class`. +fn slot(class: SlotClass, index: u32) -> SlotRef { + SlotRef { + stage: Stage::Fragment, + class, + index, + } +} + +/// The constants of a fragment function that reads a uniform view at buffer 0, converts texture +/// 0 to `half` (both its booleans), and samples it through sampler 0 and a bicubic filter: IDs 0 +/// to 4. +fn constants() -> Vec<(u32, SpecKey)> { + let texture = slot(SlotClass::Texture, 0); + vec![ + (0, SpecKey::RangeAtBindOffset(slot(SlotClass::Buffer, 0))), + (1, SpecKey::PlainHalfTexels(texture)), + (2, SpecKey::UnmeasuredTexels(texture)), + ( + 3, + SpecKey::SamplerState { + slot: slot(SlotClass::Sampler, 0), + fields: u32::MAX, + }, + ), + (4, SpecKey::BicubicTexels(texture)), + ] +} + +/// A key giving IDs 0 to 4 `values`, each four bytes, packed in order. +fn key(values: [u32; 5]) -> SpecializationKey { + let mut key = SpecializationKey::new(); + for (id, value) in (0..).zip(values) { + key.entries.push(SpecializationMapEntry { + constant_id: id, + offset: key.data.len() as u32, + size: 4, + }); + key.data.extend_from_slice(&value.to_le_bytes()); + } + key +} + +#[test] +fn the_general_form_zeroes_the_constants_whose_zero_serves_every_binding() { + let general = general_form(constants().into_iter(), &key([1, 1, 1, 5, 3])); + // The sampler's word and the bicubic class keep their values: no arm of theirs serves every + // binding. + assert_eq!(general, Some(key([0, 0, 0, 5, 3]))); + // A plain-class or unbound texture's key and a measured class's alike. + let general = general_form(constants().into_iter(), &key([0, 1, 0, 5, 3])); + assert_eq!(general, Some(key([0, 0, 0, 5, 3]))); +} + +#[test] +fn a_key_in_its_general_form_has_none_of_its_own() { + assert_eq!( + general_form(constants().into_iter(), &key([0, 0, 0, 5, 3])), + None + ); + // A constant the key's stages do not declare is not the general form's to set. + assert_eq!( + general_form(std::iter::empty(), &key([1, 1, 1, 5, 3])), + None + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 46635efb7..3a6487ba4 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -117,6 +117,7 @@ mod function_table; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod functions_translated; mod gate; +mod general_form; mod gpu_pools; mod gpu_time; mod heap; diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index a9776ff0a..46e4103af 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -896,13 +896,13 @@ impl Counters { self.pipelines_pooled.fetch_add(1, Ordering::Relaxed); } - /// A draw or dispatch whose key's `VkPipeline` was not made took its residual form's + /// A draw or dispatch whose key's `VkPipeline` was not made took its general form's /// (`pipeline/render/residual.rs`). pub(crate) fn residual_form_drawn(&self) { self.residual_form_draws.fetch_add(1, Ordering::Relaxed); } - /// A draw or dispatch that began its key's making took its residual form's `VkPipeline` + /// A draw or dispatch that began its key's making took its general form's `VkPipeline` /// meanwhile (`pipeline/render/residual.rs`). pub(crate) fn residual_form_making(&self) { self.residual_form_makings.fetch_add(1, Ordering::Relaxed); @@ -3052,11 +3052,12 @@ pub struct WorkCounts { /// rather than make it at the draw. pub pipelines_pooled: u64, /// Draws and dispatches whose key's `VkPipeline` was not made, which were recorded at once - /// with the made one of its residual form, each of the key's uniform-view slots read at its - /// residual (which reads the same bytes at every bind offset): none waited for its key's - /// making. + /// with the made one of its general form, each of the key's uniform-view slots read at its + /// residual (which reads the same bytes at every bind offset) and, for a draw on a device that + /// samples through Metal's own texture unit, each texture slot converted to `half` by its + /// class's routine (exact for every class): none waited for its key's making. pub residual_form_draws: u64, - /// Of the makings draws and dispatches began, those whose command took its key's residual + /// Of the makings draws and dispatches began, those whose command took its key's general /// form meanwhile: makings on the device's pool that nothing waits for. pub residual_form_makings: u64, /// The pieces the device's pipeline pool holds as the counts are read, waiting or running: diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index b41a04df4..64063982d 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -b3d90b9c02a84252633f356df01ab78efd80f26437cfe5700934968476c12736 +560c846275f2d1069e1e6d8cde840d0d275bea2fbc5768f950a8f4f49db6e74f diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 03a4509e1..d2b618452 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -56,8 +56,9 @@ pub const METAL_ENVIRONMENT: &str = "apple-m3-max-macos27.0.1"; const WAIT: Duration = Duration::from_secs(60); /// `device`'s work counts once its pipeline pool holds no piece (`WorkCounts::pipeline_pool_busy`), -/// waiting at most [`WAIT`]: a draw that took its key's residual form does not wait for its own -/// key's making, which may outlast the draw's command buffer. +/// waiting at most [`WAIT`]: a draw that took its key's general form does not wait for its own +/// key's making, which may outlast the draw's command buffer, and a state's creation hands its +/// predicted key's making to the pool after its general form's, not waiting for it. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] fn pipelines_settled(device: &Device) -> metal2vulkan_runtime::WorkCounts { let until = std::time::Instant::now() + WAIT; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/made_at_creation.rs b/crates/metal2vulkan-validation/src/runtime_lane/made_at_creation.rs index 02f107433..a959332ff 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/made_at_creation.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/made_at_creation.rs @@ -9,9 +9,10 @@ //! vertices through a vertex descriptor (`LAYOUT_FUNCTIONS`). use super::degrade_notices::{counts, on_device}; +use super::pixel_samplers::metal_sampler; use super::{ - dynamic_input_assembly, layer_reported_nothing_at_all, validated_device_with, Messages, - ScratchCache, WAIT, + dynamic_input_assembly, layer_reported_nothing_at_all, pipelines_settled, + validated_device_with, Messages, ScratchCache, WAIT, }; use crate::air_library::AirLibrary; use crate::gpu::TEST_DEVICE; @@ -302,7 +303,10 @@ fn a_state_s_first_draw_takes_the_pipeline_made_at_its_creation() { /// there may hold one (`PrecisionNote::DeviceNanEncoding`, a test of the bound format, which no /// pipeline's key carries). Each draw binds an `RGBA16Float` texture, which takes the pipeline /// made at creation (`a_draw_binding_a_texture_takes_the_pipeline_made_at_creation`); every kind -/// the first draw announces is one the stage specializes ([`specialized_kinds`]). +/// the first draw announces is one the stage specializes ([`specialized_kinds`]). On a device that +/// samples through Metal's own texture unit the creation makes the predicted key's general form, +/// and hands the predicted key itself to the pool right after (`pipeline/render/residual.rs`): +/// both counted once the pool settles, and neither announcing anything before a draw. #[test] fn a_pipeline_made_at_creation_announces_at_its_first_draw() { let cache = ScratchCache::new().unwrap(); @@ -319,10 +323,13 @@ fn a_pipeline_made_at_creation_announces_at_its_first_draw() { drop(messages.take_notices()); let before = device.work_counts(); let state = state(&device, "sampled_fragment"); + pipelines_settled(&device); + let metal = metal_sampler(&device); assert_eq!( made_since(&device, &before), - (1, 0), - "the predicted key's pipeline, made at creation" + (1 + u64::from(metal), 0), + "the predicted key's pipeline, made at creation, and its general form where the \ + device samples through Metal's texture unit ({metal})" ); let at_creation = counts(&messages.take_notices()); let created = device.work_counts(); @@ -369,13 +376,23 @@ fn a_pipeline_made_at_creation_announces_at_its_first_draw() { /// draw binds. A draw of `sampled_fragment` binding nothing takes the pipeline made at creation, /// and so do draws binding an `RGBA8Unorm` or an `RGBA16Float` texture, each sampling its texels: /// the class of the format the slot binds reaches the function as a push field, not as the -/// pipeline's specialization. +/// pipeline's specialization. On a device that samples through Metal's own texture unit the +/// creation makes the predicted key's general form too (`pipeline/render/residual.rs`), and the +/// predicted key, made on the pool right after, is the one these draws take once the pool settles: +/// each class is plain and measured, as the unbound slot the prediction binds. #[test] fn a_draw_binding_a_texture_takes_the_pipeline_made_at_creation() { on_device(|device, _| { + let metal = metal_sampler(device); let before = device.work_counts(); let state = state(device, "sampled_fragment"); - assert_eq!(made_since(device, &before), (1, 0), "made at creation"); + pipelines_settled(device); + assert_eq!( + made_since(device, &before), + (1 + u64::from(metal), 0), + "made at creation, with the general form where the device samples through Metal's \ + texture unit ({metal})" + ); let created = device.work_counts(); draw(device, &state, PrimitiveType::Triangle); assert_eq!( @@ -405,6 +422,92 @@ fn a_draw_binding_a_texture_takes_the_pipeline_made_at_creation() { 1, "the pipeline made at creation drew" ); + assert_eq!( + after.residual_form_draws, before.residual_form_draws, + "no draw took the general form" + ); + }); +} + +/// A `BC4RUnorm` texture of `side` texels square, every block of it `block`'s 8 bytes. +fn bc4_filled(device: &Device, side: u64, block: [u8; 8]) -> Texture { + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::BC4RUnorm, side, side, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::shared(); + let texture = device.new_texture(&descriptor).unwrap(); + let blocks = side / 4; + let bytes = block.repeat((blocks * blocks) as usize); + texture + .replace_region( + Region::new_2d(0, 0, side, side), + 0, + 0, + &bytes, + 8 * blocks, + 0, + ) + .unwrap(); + texture +} + +/// A draw binding a texture of a class whose `half` conversion is not measured, a `BC4RUnorm` one, +/// draws at once with the pipeline its state's creation made. On a device that samples through +/// Metal's own texture unit the class keys apart from the prediction (`SpecKey::UnmeasuredTexels` +/// 1, where the unbound slot the prediction binds has 0), so the draw takes its key's general form, +/// the one the creation made (`pipeline/render/residual.rs`), and hands its own key's making to +/// the pool, which nothing waits for; once made, a second draw takes it. Elsewhere the class is a +/// push field alone, and both draws take the predicted key. Each draws the blocks' red, 1. +#[test] +fn a_draw_of_an_unmeasured_class_takes_the_general_form_its_creation_made() { + on_device(|device, _| { + let metal = metal_sampler(device); + let before = device.work_counts(); + let state = state(device, "sampled_fragment"); + let created = pipelines_settled(device); + assert_eq!( + made_since(device, &before), + (1 + u64::from(metal), 0), + "made at creation, with the general form where the device samples through Metal's \ + texture unit ({metal})" + ); + // Both endpoints 255, every index 0: red 1, and Metal's green 0, blue 0 and alpha 1. + let red = bc4_filled(device, SIDE, [0xff, 0xff, 0, 0, 0, 0, 0, 0]); + const RED: [u8; 4] = [255, 0, 0, 255]; + assert_eq!( + draw_with(device, &state, PrimitiveType::Triangle, Some(&red)), + RED + ); + let drawn = pipelines_settled(device); + let metal_count = u64::from(metal); + assert_eq!( + ( + drawn.residual_form_draws - created.residual_form_draws, + drawn.residual_form_makings - created.residual_form_makings, + drawn.creation_pipelines_drawn - created.creation_pipelines_drawn, + ), + (metal_count, metal_count, 1), + "the draw took the general form, made at creation, and began its own key's making \ + where the device samples through Metal's texture unit ({metal}); elsewhere the \ + predicted key" + ); + assert_eq!( + made_since(device, &created), + (metal_count, metal_count), + "its own key, made on the pool while the draw went on, where the class keys apart" + ); + assert_eq!( + draw_with(device, &state, PrimitiveType::Triangle, Some(&red)), + RED + ); + let again = device.work_counts(); + assert_eq!( + ( + again.residual_form_draws - drawn.residual_form_draws, + made_since(device, &drawn), + ), + (0, (0, 0)), + "the second draw took its own key, made" + ); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/pipeline_creation.rs b/crates/metal2vulkan-validation/src/runtime_lane/pipeline_creation.rs index 978137dde..039c87745 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/pipeline_creation.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/pipeline_creation.rs @@ -861,7 +861,9 @@ fn quadrants( /// pipelines made already: one state drawn binding each of four formats into a quadrant each, then /// as a line, under a `Counting` visibility query. The format draws take the `VkPipeline` the /// state's creation made, on every device: each format's class reaches the function as a push -/// field, and none keys apart. The line, whose key no creation predicts, hands its making to the +/// field, and none keys apart (where the device samples through Metal's own texture unit, the +/// creation's predicted key, or its general form while the pool still makes the predicted key, +/// `pipeline/render/residual.rs`). The line, whose key no creation predicts, hands its making to the /// pool; none is made at a draw; the command buffer completes, and a command buffer committed /// after it on its queue completes after it. The same draws again, /// their pipelines made, hand nothing to the pool, and render the same bytes and count the same diff --git a/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs index 463ef8e0f..a44eb7be4 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/ycbcr_textures.rs @@ -1430,6 +1430,10 @@ fn a_ycbcr_slot_takes_the_devices_filter_in_the_pipeline_its_creation_made() { .unwrap(); for fragment in ["between_runtime_float", "between_runtime_half"] { let pipeline = between_state(device, &library, fragment); + // Where the device samples through Metal's texture unit, the `half` function's + // creation hands its predicted key's making to the pool after its general form's + // (`pipeline/render/residual.rs`): settled first, so the count below is the draw's. + super::pipelines_settled(device); let plain = drawn_with(device, &pipeline, (&twin, Some(&linear)), |_, _| {}); let before = device.work_counts().variant_pipelines_made; let got = drawn_with(device, &pipeline, (&texture, Some(&linear)), |_, _| {}); diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index d576bfffd..b5eb3f972 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 479; /// 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 = 1705; +pub const RUNTIME_VERSION: u32 = 1706; /// 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/docs/API.md b/docs/API.md index c45c1ff0d..415edecdf 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3374,19 +3374,36 @@ each item named states the rule in full. - **A draw's `VkPipeline` is made while the draw goes on.** A draw whose pipeline is not made yet returns once encoded; the pipeline is made on the device's pool of at most four threads, and the command buffer's work waits for it in queue order. -- **A draw can take its key's residual form while its own pipeline is made.** A state's creation - makes its predicted key with every constant buffer slot read through a uniform view read at the - slot's residual (`RangeAtBindOffset` 0), which reads the same bytes at every bind offset: the - binder writes the slot's descriptor range and residual from the bind offset alone, whichever form - the pipeline takes, and the residual is 0 wherever the range starts at the bind offset. A slot - bound to nothing is read at its residual too (0), so a draw that leaves such slots unbound takes - the creation's pipeline itself. A draw whose own pipeline (which reads such a slot at the bind - offset alone, the residual-free form) is not made, and whose key's residual form's is, draws with - that one at once; its own is made on the pool behind the makings something waits for, and later - draws take it. Only GPU time moves for the draws before it lands: on ANV the residual form's reads - are loads where the other form's are pushed constants (`WorkCounts::residual_form_draws`, - `residual_form_makings`). On MoltenVK every key is its residual form (the two forms measured - alike there), so a state's draws at every bind offset take the one pipeline its creation made. +- **A draw can take its key's general form while its own pipeline is made.** A state's creation + makes its predicted key's general form: each specialization constant with an arm that serves + every binding exactly at that arm. Every constant buffer slot read through a uniform view is read + at the slot's residual (`RangeAtBindOffset` 0), which reads the same bytes at every bind offset: + the binder writes the slot's descriptor range and residual from the bind offset alone, whichever + form the pipeline takes, and the residual is 0 wherever the range starts at the bind offset. A + slot bound to nothing is read at its residual too (0), so a draw that leaves such slots unbound + takes the creation's pipeline itself. On MoltenVK a texture slot a function converts to `half` + converts its texels by the class routine (`PlainHalfTexels` 0, the bound class read from push + data), which rounds a plain class's `float` texel to nearest even as the plain arm does (the arm + Metal's compiler can fold into the image instruction, which a slot bound to nothing or to a plain + class takes: every class but a YCbCr field on the grid 8192), and its `UnmeasuredTexels`, which + no instruction reads, is at 0 (a class whose `half` conversion is not measured, BC4 to BC7 and + the linear ASTC formats among them, takes 1). Where the predicted key is not its own general form + (a slot of the plain arm), the creation hands it to the pool right after, behind the makings + something waits for, and a draw binding a plain, measured class takes it once made. A draw whose + own pipeline (which reads such a buffer slot at the bind offset alone, converts by the plain arm, + or names an unmeasured class) is not made, and whose key's general form's is, draws with that one + at once; its own is made on the pool behind the makings something waits for, and later draws + take it. So a draw binding a texture of an unmeasured class waits for no compile of its own. + Only GPU time moves for the draws before it lands (`WorkCounts::residual_form_draws`, + `residual_form_makings`): on ANV the residual form's reads are loads where the other form's are + pushed constants; on MoltenVK the class routine converts each `half` read in place of the image + instruction's own conversion. The creation of a state + whose predicted key is not its general form makes two pipelines, the second on the pool, nothing + waiting for it. On MoltenVK every key reads its buffer slots at their residual (the two forms + measured alike there), so a draw's bind offsets choose no pipeline there. A constant with no arm + that serves every binding stays a pipeline per value, made at the first draw of it: a sampler's + state (`SamplerState`, each sampler word a sampling emulation of its own) and how the bicubic + filter treats the bound format's texels (`BicubicTexels`). - **A dispatch's `VkPipeline` is made while the dispatch goes on**, the same way: one pipeline per threadgroup size and edge region, made on the pool. A compute state whose descriptor states `requiredThreadsPerThreadgroup` -- the threadgroup every dispatch of the state must have -- makes