From 33e89bd482ef9fa12f265129ecb9016ed3523fd0 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 19 Oct 2026 00:16:00 +0300 Subject: [PATCH] Fit mesh, compute and tile pipelines to ANV's compiler word bound On ANV a pipeline whose largest stage module passes 400,000 words under the exact forms is retranslated with those forms dropped until it fits; render pipelines already were, and now mesh, compute and tile pipelines are too, announced as exact-forms-over-compiler-limit with the kind of pipeline state named. New Device::fit_mesh_variant, fit_compute_pipeline and fit_tile_pipeline for pipelines linked from stages compiled ahead. The known gap is gone from docs/FAST-PATHS.md. Verified: the fit tests for every kind, 188 translator and runtime tests and the device notice tests on ANV, and 7 of 7 on RADV. Folds in: - Fit mesh, compute and tile pipelines to ANV's compiler word bound --- crates/metal2vulkan-runtime/src/compute.rs | 7 +- .../metal2vulkan-runtime/src/degradation.rs | 125 ++-- .../src/generated_execute.rs | 8 +- .../metal2vulkan-runtime/src/pipeline/mod.rs | 30 +- .../src/pipeline/objects.rs | 30 +- .../src/pipeline/render.rs | 6 +- .../src/pipeline/sources.rs | 9 +- crates/metal2vulkan-runtime/src/render.rs | 6 +- .../src/render/tile_dispatch.rs | 6 +- .../src/tests/fitted_variant_notice.rs | 261 ++++++-- .../src/runtime_lane/degrade_notices.rs | 72 ++- crates/metal2vulkan/src/device/derive.rs | 7 +- crates/metal2vulkan/src/device/profile.rs | 8 +- crates/metal2vulkan/src/pipeline/compile.rs | 3 +- .../metal2vulkan/src/pipeline/compile/api.rs | 192 ++---- .../metal2vulkan/src/pipeline/compile/fit.rs | 334 +++++++++++ .../src/pipeline/compile/fit/tests.rs | 555 ++++++++++++++++++ .../src/pipeline/compile/tests.rs | 176 +----- crates/metal2vulkan/src/pipeline/facts.rs | 6 +- docs/API.md | 29 +- docs/FAST-PATHS.md | 1 + 21 files changed, 1386 insertions(+), 485 deletions(-) create mode 100644 crates/metal2vulkan/src/pipeline/compile/fit.rs create mode 100644 crates/metal2vulkan/src/pipeline/compile/fit/tests.rs diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 3c7b8456f..c18608fc9 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -50,7 +50,7 @@ use super::binding; use super::buffer::Buffer; use super::command_buffer::CommandBuffer; use super::deferred::Deferred; -use super::degradation::{BoundFormats, Degradation}; +use super::degradation::{BoundFormats, CompiledPipeline, Degradation}; use super::device::Device; use super::encoder::{EncoderCore, Replayed}; use super::error::{internal, invalid, Error, Problem, RuntimeGap}; @@ -1806,7 +1806,10 @@ fn record( } device.degrade_cross_class(&plan.diagnostics, formats); objects.announce_bound( - (std::slice::from_ref(&variant.pipeline().stage), None), + ( + std::slice::from_ref(&variant.pipeline().stage), + CompiledPipeline::Kernel(variant.pipeline()), + ), regions .iter() .map(|region| (®ion.specialization, Some(formats))), diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index ec37db76d..26808339d 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -40,10 +40,12 @@ //! render pipeline states alike, but for a note the stage records only under some //! specializations, announced where the runtime makes a `VkPipeline` whose specialization (the //! bound formats' classes and samplers' words) takes it; a render pipeline's vertex simdgroups on -//! a driver that runs them without advertising the vertex stage, and the exact forms its -//! translation dropped to fit the device's compiler word bound, where the runtime makes a render -//! variant, before its shader modules (`pipeline/render.rs`, from the pipeline's requirements -//! and dependencies); a +//! a driver that runs them without advertising the vertex stage, where the runtime makes a +//! render variant, before its shader modules (`pipeline/render.rs`, from the pipeline's +//! requirements); the exact forms a pipeline's translation dropped to fit the device's compiler +//! word bound, where the runtime makes a variant of any pipeline state, before its shader modules +//! (`pipeline/render.rs` for a render or mesh render state, `pipeline/mod.rs` for a compute or +//! tile render state, from the pipeline's dependencies); a //! render pass's degradations where its encoder ends (`render.rs`), from the pass's layout, its //! render pass instances and the storage it kept; a rasterization-rate map that is not the //! identity where the device makes it (`rate_map.rs`); a draw's use of an attachment's memory in @@ -80,7 +82,7 @@ use metal2vulkan::cache::SpecializationKey; use metal2vulkan::device::{DriverFact, FunctionStorage, ResolvePolicy, VkProperty}; use metal2vulkan::metal::PixelFormat; use metal2vulkan::pipeline::{ - PrecisionNote, Reconvergence, RenderPipeline, SlotRef, SpecKey, StageModule, + ComputePipeline, PrecisionNote, Reconvergence, RenderPipeline, SlotRef, SpecKey, StageModule, }; use metal2vulkan::vk::{ImageAspectFlags, ShaderStage}; use std::collections::BTreeSet; @@ -440,16 +442,17 @@ degradations! { "each draw runs a geometry stage of its topology class between the vertex and \ fragment stages, which emits each primitive's vertices with the barycentric weights \ or the first vertex's slice and viewport"; - /// A render pipeline state whose largest stage module, under the consumer's exact forms, - /// exceeded the device's compiler word bound + /// A pipeline state (render, mesh render, tile render or compute) whose largest stage + /// module, under the consumer's exact forms, exceeded the device's compiler word bound /// ([`metal2vulkan::pipeline::RuntimeFact::ExactFormsOverCompilerLimit`]; /// [`metal2vulkan::device::DriverWorkaround::RegisterAllocatorOverflowsLargeModules`], /// ANV's register allocator faults compiling a module past it), so the translation dropped /// the consumer's exact forms until it fit: native sampling first, then every - /// module-growing exact answer native. Announced where the runtime makes a render - /// variant whose pipeline the fit reduced, the base variant or another (`pipeline/ - /// render.rs`, from the pipeline's dependencies), naming the forms dropped; the reduced - /// stages announce their own precision notes besides. + /// module-growing exact answer native. Announced where the runtime makes a variant whose + /// pipeline the fit reduced, the base variant or another (`pipeline/render.rs` for a + /// render or mesh render state, `pipeline/mod.rs` for a compute or tile render state, from + /// the pipeline's dependencies), naming the state's kind and the forms dropped; the + /// reduced stages announce their own precision notes besides. ExactFormsOverCompilerLimit = "exact-forms-over-compiler-limit", Precision, "the dropped exact forms' results can differ from Metal's as their notes' \ documentation states, where the device's compiler would fault on the exact module"; @@ -2383,11 +2386,11 @@ pub(crate) struct Kinds([u64; WORDS]); impl Kinds { /// The kinds `stages` (a variant's) may announce where the variant or a `VkPipeline` of it is - /// made (`Device::degrade_stages`, `Device::degrade_specialized`), and those of a render - /// variant's `render` pipeline (`Device::degrade_render`): every note's, a specialized one's - /// under any specialization (a filter note's two-plane YCbCr kind among them), and each other - /// kind a stage's or the pipeline's records state. - pub(crate) fn of(stages: &[StageModule], render: Option<&RenderPipeline>) -> Kinds { + /// made (`Device::degrade_stages`, `Device::degrade_specialized`), and those of the variant's + /// `pipeline` (`Device::degrade_pipeline`): every note's, a specialized one's under any + /// specialization (a filter note's two-plane YCbCr kind among them), and each other kind a + /// stage's or the pipeline's records state. + pub(crate) fn of(stages: &[StageModule], pipeline: CompiledPipeline<'_>) -> Kinds { let mut kinds = Kinds::default(); for stage in stages { let notes = stage.precision_notes.iter().copied(); @@ -2410,7 +2413,7 @@ impl Kinds { kinds.add(Degradation::ImplementationDefinedReconvergence); } } - if let Some(render) = render { + if let CompiledPipeline::Render(render) = pipeline { if render .requirements .properties @@ -2418,9 +2421,9 @@ impl Kinds { { kinds.add(Degradation::UnadvertisedVertexSimdgroups); } - if dropped_exact_forms(&render.dependencies).is_some() { - kinds.add(Degradation::ExactFormsOverCompilerLimit); - } + } + if dropped_exact_forms(pipeline.dependencies()).is_some() { + kinds.add(Degradation::ExactFormsOverCompilerLimit); } kinds } @@ -2431,7 +2434,57 @@ impl Kinds { } } -/// The exact forms a render pipeline's translation dropped to fit the device's compiler word bound +/// A variant's compiled pipeline, whose records beside its stages its making and binds announce +/// (`Device::degrade_pipeline`): a render state's (vertex or mesh) or a compute state's (kernel or +/// tile). +#[derive(Clone, Copy)] +pub(crate) enum CompiledPipeline<'a> { + Render(&'a RenderPipeline), + Kernel(&'a ComputePipeline), +} + +impl<'a> CompiledPipeline<'a> { + /// The pipeline's runtime dependencies. + fn dependencies(self) -> &'a [metal2vulkan::pipeline::RuntimeDependency] { + match self { + CompiledPipeline::Render(p) => &p.dependencies, + CompiledPipeline::Kernel(p) => &p.dependencies, + } + } + + /// The kind of pipeline state a notice of the pipeline names, from its structure: a render + /// pipeline with an object or mesh stage, or with the records of an emulated mesh, is a mesh + /// render pipeline state's; a compute pipeline of a tile function + /// (`RuntimeFact::TileFunction`) a tile render pipeline state's. + fn object(self) -> &'static str { + match self { + CompiledPipeline::Render(p) => { + let meshes = p.graphics.mesh_records.is_some() + || p.stages.iter().any(|s| { + s.stage == ShaderStage::TASK_EXT || s.stage == ShaderStage::MESH_EXT + }); + if meshes { + "a mesh render pipeline state" + } else { + "a render pipeline state" + } + } + CompiledPipeline::Kernel(p) => { + let tile = p + .dependencies + .iter() + .any(|d| d.fact == metal2vulkan::pipeline::RuntimeFact::TileFunction); + if tile { + "a tile render pipeline state" + } else { + "a compute pipeline state" + } + } + } + } +} + +/// The exact forms a pipeline's translation dropped to fit the device's compiler word bound /// (`RuntimeFact::ExactFormsOverCompilerLimit` among its `dependencies`), named; `None` where it /// dropped none. pub(crate) fn dropped_exact_forms( @@ -2742,18 +2795,16 @@ impl Device { /// device's options ask for at every occurrence (`DeviceOptions::announce_each`), with the /// making's object and reason, in the order the making announces them (a memoized variant is /// made once, so its making alone would announce them once). `stages` are the variant's - /// stages, `render` a render variant's pipeline, and `specializations` the specializations and + /// stages, `pipeline` its compiled pipeline, and `specializations` the specializations and /// bound formats of the `VkPipeline`s the bind takes (`Device::degrade_specialized`). pub(crate) fn bound_notices( &self, - (stages, render): (&[StageModule], Option<&RenderPipeline>), + (stages, pipeline): (&[StageModule], CompiledPipeline<'_>), specializations: &[(&SpecializationKey, Option>)], ) -> Vec { let notices = std::cell::RefCell::new(Vec::new()); let at = Occurrence::Bound(¬ices); - if let Some(render) = render { - self.degrade_render(render, at); - } + self.degrade_pipeline(pipeline, at); self.degrade_stages(stages, at); for (n, &(specialization, formats)) in specializations.iter().enumerate() { // A specialization the bind takes twice (a split dispatch's regions) announces once. @@ -2907,17 +2958,18 @@ impl Device { } impl Device { - /// Announce, `at` its variant's making or a bind ([`Occurrence`]), what a render variant's - /// `pipeline` records beside its stages: requirements that hold a vertex function's subgroup - /// operations on a driver that runs them as Metal does without advertising the vertex stage - /// ([`Degradation::UnadvertisedVertexSimdgroups`]), and exact forms the translation dropped to - /// fit the device's compiler word bound ([`Degradation::ExactFormsOverCompilerLimit`]), for the - /// base variant and every other alike, each pipeline by its own records. - pub(super) fn degrade_render(&self, pipeline: &RenderPipeline, at: Occurrence<'_>) { - if let Some(dropped) = dropped_exact_forms(&pipeline.dependencies) { + /// Announce, `at` its variant's making or a bind ([`Occurrence`]), what a variant's `pipeline` + /// records beside its stages: exact forms the translation dropped to fit the device's compiler + /// word bound ([`Degradation::ExactFormsOverCompilerLimit`]), naming the pipeline state's kind + /// (render, mesh render, tile render or compute), and, for a render variant, requirements that + /// hold a vertex function's subgroup operations on a driver that runs them as Metal does + /// without advertising the vertex stage ([`Degradation::UnadvertisedVertexSimdgroups`]); for + /// the base variant and every other alike, each pipeline by its own records. + pub(super) fn degrade_pipeline(&self, pipeline: CompiledPipeline<'_>, at: Occurrence<'_>) { + if let Some(dropped) = dropped_exact_forms(pipeline.dependencies()) { self.degrade_at(at, Degradation::ExactFormsOverCompilerLimit, || { ( - "a render pipeline state".to_owned(), + pipeline.object().to_owned(), format!( "its largest stage module passed the device's compiler word bound, so its \ translation dropped {} to the device's answer", @@ -2926,6 +2978,9 @@ impl Device { ) }); } + let CompiledPipeline::Render(pipeline) = pipeline else { + return; + }; if pipeline .requirements .properties diff --git a/crates/metal2vulkan-runtime/src/generated_execute.rs b/crates/metal2vulkan-runtime/src/generated_execute.rs index d68940d3d..01e22eeeb 100644 --- a/crates/metal2vulkan-runtime/src/generated_execute.rs +++ b/crates/metal2vulkan-runtime/src/generated_execute.rs @@ -48,6 +48,7 @@ use super::binding; use super::blit::reads; use super::buffer::Buffer; use super::command_buffer::CommandBuffer; +use super::degradation::CompiledPipeline; use super::encoder::{EncoderCore, RecordedSegment}; use super::error::{internal, vulkan, Error}; use super::executed_commands::RecordsRead; @@ -498,7 +499,7 @@ fn record_total( &device, &replay.pipeline_layout, std::slice::from_ref(&p.variant.pipeline().stage), - None, + CompiledPipeline::Kernel(p.variant.pipeline()), )?); pipelines.push(made.indirect_bindable_pipeline(region)?); objects.push(made); @@ -681,7 +682,10 @@ fn record_total( for (p, made) in prepared.iter().zip(&objects) { if let [region] = p.commands.regions.as_slice() { made.announce_bound( - (std::slice::from_ref(&p.variant.pipeline().stage), None), + ( + std::slice::from_ref(&p.variant.pipeline().stage), + CompiledPipeline::Kernel(p.variant.pipeline()), + ), [(®ion.specialization, None)], ); } diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index 24815a5ad..220eb987c 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -99,6 +99,7 @@ use super::values::Size; use super::Device; use crate::argument_table::AtBindViews; use crate::binary_archive::Used; +use crate::degradation::{CompiledPipeline, Occurrence}; use crate::residency::handle_stages; use crate::resource_ids::{ function_name, number, pipeline_placement, Holder, IdHold, IdPlacement, IdSpace, Numbered, @@ -369,6 +370,27 @@ impl Kernel { } inputs } + + /// `pipeline`, this descriptor's compile with its kernel or tile function compiled under + /// `inputs` ([`Kernel::inputs`]), held to the device's compiler word bound + /// (`fit_compute_pipeline`, `fit_tile_pipeline`): translated again from the function this + /// descriptor holds, with the exact forms dropped, where its module passes the bound. + fn fit( + &self, + compile: &metal2vulkan::device::Device, + inputs: &metal2vulkan::pipeline::LoweringInputs, + budget: &metal2vulkan::Budget, + pipeline: ComputePipeline, + ) -> Result { + match self { + Kernel::Compute(descriptor) => { + compile.fit_compute_pipeline(descriptor, inputs, budget, pipeline) + } + Kernel::Tile(descriptor) => { + compile.fit_tile_pipeline(descriptor, inputs, budget, pipeline) + } + } + } } /// One compiled variant of a state. @@ -1270,7 +1292,8 @@ impl Variant { /// the variant of it the memo knows live, or the pipeline `sources` give, each stage found or /// compiled under one budget. The function compiles under the descriptor's stage input /// descriptor or color attachment formats ([`Kernel::inputs`]), and the pipeline under its - /// other fields. A refusal is the compile layer's. + /// other fields, held to the device's compiler word bound from `descriptor`, which holds the + /// function ([`Kernel::fit`]). A refusal is the compile layer's. fn compiled( sources: &Sources<'_>, function: &FunctionDescriptor, @@ -1284,6 +1307,7 @@ impl Variant { let compiled = sources.function(function, &inputs, (&function_key, None), &budget)?; sources.kernel( &descriptor.with_stage(StageSource::Compiled(compiled)), + (descriptor, &inputs), &budget, ) } @@ -1300,12 +1324,14 @@ impl Variant { Remembered::Live(variant) => Arc::clone(&variant.pipeline), Remembered::Compiled(pipeline) => pipeline, }; + // Before the variant's shader modules, as a render variant's. + device.degrade_pipeline(CompiledPipeline::Kernel(&pipeline), Occurrence::Made); let (objects, kept) = VariantObjects::kept_or_create( device, kept::Compiled::Compute(pipeline.key), &pipeline.layout, std::slice::from_ref(&pipeline.stage), - None, + CompiledPipeline::Kernel(&pipeline), )?; let variant = Arc::new(Variant { key, diff --git a/crates/metal2vulkan-runtime/src/pipeline/objects.rs b/crates/metal2vulkan-runtime/src/pipeline/objects.rs index 2ca08d309..954e08c4d 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/objects.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/objects.rs @@ -20,7 +20,7 @@ use super::shared_layouts::{settle_layouts, shared_layout, SharedLayout}; use super::RegionKey; use crate::binding::{Info, SetWrite}; use crate::degradation::{ - tested_slots_of, BoundFormats, BoundNotice, Kinds, Occurrence, TestedFormats, + tested_slots_of, BoundFormats, BoundNotice, CompiledPipeline, Kinds, Occurrence, TestedFormats, }; use crate::descriptor_arena::{DescriptorArena, SetNeeds}; use crate::device::{lock, DeviceShared}; @@ -526,14 +526,15 @@ impl VariantObjects { /// guarantees. Once they are made, the device announces what the stages record: their /// precision notes (but those a specialization decides, announced with each `VkPipeline`), and /// reconvergence that is not Metal's (`degradation.rs`), but the kinds it announces at every - /// occurrence, which each bind announces (`announce_bound`); what a render variant's `render` - /// pipeline records beside its stages counts among its kinds (`Device::degrade_render`). + /// occurrence, which each bind announces (`announce_bound`); what the variant's `pipeline` + /// records beside its stages counts among its kinds (`Device::degrade_pipeline`). pub(crate) fn create( device: &Device, layout: &PipelineLayout, stages: &[StageModule], - render: Option<&RenderPipeline>, + pipeline: CompiledPipeline<'_>, ) -> Result { + let push_set_zero = pushes_set_zero(device, layout, stages, pipeline); let set_needs = needs_of(layout, push_set_zero)?; // One sampler per binding that bakes one, in the layout's order: the live set of the same // samplers where it holds one, else one made now (`sampler_set`). @@ -570,7 +571,7 @@ impl VariantObjects { .collect(), heap_layout: layout.sets.get(1).cloned(), heap: Mutex::new(None), - kinds: Kinds::of(stages, render), + kinds: Kinds::of(stages, pipeline), tested: tested_slots_of(stages), bound: Mutex::new(None), keep: None, @@ -604,8 +605,9 @@ impl VariantObjects { compiled: Compiled, layout: &PipelineLayout, stages: &[StageModule], - render: Option<&RenderPipeline>, + pipeline: CompiledPipeline<'_>, ) -> Result<(VariantObjects, Vec<(Place, RawPipeline)>), Error> { + let push_set_zero = pushes_set_zero(device, layout, stages, pipeline); let set_needs = needs_of(layout, push_set_zero)?; let shared = device.shared(); let back = lock(&shared.kept).take(shared, compiled); @@ -619,7 +621,7 @@ impl VariantObjects { // And the device's graphics pipeline libraries nothing holds now. settle_libraries(device); let Some(back) = back else { - let mut objects = VariantObjects::create(device, layout, stages, render)?; + let mut objects = VariantObjects::create(device, layout, stages, pipeline)?; objects.keep = Some(Instance::new(compiled)); return Ok((objects, Vec::new())); }; @@ -645,7 +647,7 @@ impl VariantObjects { .collect(), heap_layout: layout.sets.get(1).cloned(), heap: Mutex::new(None), - kinds: Kinds::of(stages, render), + kinds: Kinds::of(stages, pipeline), tested: tested_slots_of(stages), bound: Mutex::new(None), keep: Some(instance), @@ -682,7 +684,7 @@ impl VariantObjects { /// Announce, at a dispatch's or draw's bind of the variant, the notices its making announces /// whose kinds the device's options ask for at every occurrence (`DeviceOptions:: /// announce_each`), on the calling thread, with the making's object and reason - /// (`Device::bound_notices`): `stages` are the variant's, `render` a render variant's pipeline, + /// (`Device::bound_notices`): `stages` are the variant's, `pipeline` its compiled pipeline, /// and `specializations` the specializations and bound formats of the `VkPipeline`s the bind /// takes. Its kinds are tested first (`Device::binds_each`), so a variant none of whose kinds /// is asked for costs an AND a word. The notices are made once and announced at each bind @@ -690,7 +692,7 @@ impl VariantObjects { /// they are a function of those alone, the variant's stages and pipeline fixed. pub(crate) fn announce_bound<'a>( &self, - (stages, render): (&[StageModule], Option<&RenderPipeline>), + (stages, pipeline): (&[StageModule], CompiledPipeline<'_>), specializations: impl IntoIterator>)>, ) { let device = &self.device; @@ -705,7 +707,7 @@ impl VariantObjects { None => { device.shared().counts.bound_notices_made(); let notices: Arc<[BoundNotice]> = device - .bound_notices((stages, render), &specializations) + .bound_notices((stages, pipeline), &specializations) .into(); let made_for = specializations .iter() @@ -1074,15 +1076,21 @@ const PUSHED_TYPES: [vk::DescriptorType; 9] = [ /// and the variant binds set 0 at one bind point: a render variant of no compute stage at the /// graphics bind point, its draws' (`render::Recording`), where one that emulates a mesh or /// tessellation stage dispatches with set 0 too; a kernel's variant, of compute stages alone +/// (a `CompiledPipeline::Kernel`), at the compute bind point, its dispatches' and tile +/// dispatches' (`pending_dispatch::Recording`, `render::tile_dispatch`). fn pushes_set_zero( device: &Device, layout: &PipelineLayout, stages: &[StageModule], + pipeline: CompiledPipeline<'_>, ) -> bool { let compute = |stage: &StageModule| { let flags: vk::ShaderStageFlags = stage.stage.into(); flags.contains(vk::ShaderStageFlags::COMPUTE) }; + let one_point = match pipeline { + CompiledPipeline::Render(_) => !stages.iter().any(compute), + CompiledPipeline::Kernel(_) => !stages.is_empty() && stages.iter().all(compute), }; device.shared().push_descriptor.is_some() && layout.push_descriptor_eligible diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index 0727575d0..64adb2e58 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -52,7 +52,7 @@ use super::{compile_error, stand_in, PipelineOptions, PIPELINES, PLANS, VARIANTS use crate::argument_table::AtBindViews; use crate::binary_archive::{self, Used}; use crate::color_reformat::Routing; -use crate::degradation::{BoundFormats, Degradation, Occurrence}; +use crate::degradation::{BoundFormats, CompiledPipeline, Degradation, Occurrence}; use crate::device::{device_error, lock}; use crate::error::{internal, invalid, ArchivedPipeline, Error, Problem, RuntimeGap}; use crate::render_pass::MAX_COLOR_ATTACHMENTS; @@ -2297,7 +2297,7 @@ impl RenderVariant { Remembered::Compiled(pipeline) => pipeline, }; // Before the variant's shader modules, whose creation the layer reports. - device.degrade_render(&pipeline, Occurrence::Made); + device.degrade_pipeline(CompiledPipeline::Render(&pipeline), Occurrence::Made); // Where the creation log is on, the stages' SPIR-V it names hashed on a thread of its // own while the objects are made: the hash its first line reads, off the creation's path. let (objects, kept) = std::thread::scope(|scope| { @@ -2316,7 +2316,7 @@ impl RenderVariant { Compiled::Render(pipeline.key), &pipeline.layout, &pipeline.stages, - Some(&*pipeline), + CompiledPipeline::Render(&pipeline), ) })?; let stages = handle_stages(&pipeline.layout, every_render_stage()); diff --git a/crates/metal2vulkan-runtime/src/pipeline/sources.rs b/crates/metal2vulkan-runtime/src/pipeline/sources.rs index 3ffe04334..21346e66b 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/sources.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/sources.rs @@ -116,10 +116,13 @@ impl<'a> Sources<'a> { /// The compute pipeline of `descriptor`, a compute or tile descriptor whose kernel or tile /// function is compiled: the variant of it the memo knows live, or the pipeline found or /// linked now under `budget` (`compile_compute_pipeline` or `compile_tile_pipeline`, each - /// under its own key). A refusal is the compile layer's. + /// under its own key) and held to the device's compiler word bound from `functions`, the same + /// descriptor holding the function, compiled under `inputs` ([`Kernel::fit`]). A refusal is + /// the compile layer's. pub(crate) fn kernel( &self, descriptor: &Kernel, + (functions, inputs): (&Kernel, &LoweringInputs), budget: &Budget, ) -> Result, metal2vulkan::error::Error> { let compile = self.device.compile_device(); @@ -147,6 +150,10 @@ impl<'a> Sources<'a> { compile.compile_tile_pipeline(descriptor, budget)? } }; + // Held to the driver's compiler word bound, translated again from the + // function where its module passes it; it keeps its key, so the cache + // stores and finds it as compiled. + let pipeline = functions.fit(compile, inputs, budget, pipeline)?; let bytes = cache.store_compute_pipeline(compile, &pipeline); (pipeline, bytes) } diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index dd50125ec..5f06bf060 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -274,7 +274,9 @@ use super::color_reformat::{self, Routing}; use super::color_resolve::{self, ShaderResolves}; use super::command_buffer::CommandBuffer; use super::deferred::Deferred; -use super::degradation::{BoundFormats, Degradation, HandedToMetal, SplitCauses, WholePass}; +use super::degradation::{ + BoundFormats, CompiledPipeline, Degradation, HandedToMetal, SplitCauses, WholePass, +}; use super::depth_stand_in::DepthStandIn; use super::depth_stencil::{DepthStencilState, FailingDraw}; use super::depth_stencil_resolve::DrawnResolve; @@ -9125,7 +9127,7 @@ impl RenderCommandEncoder { let formats = |slot| tested.iter().find(|(s, _)| *s == slot)?.1; let compiled = variant.pipeline(); objects.announce_bound( - (&compiled.stages, Some(compiled)), + (&compiled.stages, CompiledPipeline::Render(compiled)), [(specialization, Some(&formats as BoundFormats<'_>))], ); } diff --git a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs index 4ca29762b..22dc64afd 100644 --- a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs +++ b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs @@ -105,6 +105,7 @@ use crate::blit::TRANSFER; use crate::buffer::Buffer; use crate::clear_reach; use crate::command_buffer::CommandBuffer; +use crate::degradation::{BoundFormats, CompiledPipeline}; use crate::device::functions::Vk; use crate::encoder::EncoderCore; use crate::error::{internal, invalid, Error, Problem, RuntimeGap}; @@ -1285,7 +1286,10 @@ impl RenderCommandEncoder { let formats = |slot| tested.iter().find(|(s, _)| *s == slot)?.1; let formats: BoundFormats<'_> = &formats; objects.announce_bound( - (std::slice::from_ref(&variant.pipeline().stage), None), + ( + std::slice::from_ref(&variant.pipeline().stage), + CompiledPipeline::Kernel(variant.pipeline()), + ), commands .regions .iter() diff --git a/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs b/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs index d0988eab2..6e9415373 100644 --- a/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs +++ b/crates/metal2vulkan-runtime/src/tests/fitted_variant_notice.rs @@ -1,30 +1,35 @@ -//! The exact forms a render pipeline's translation dropped to fit the device's compiler word bound -//! (`RuntimeFact::ExactFormsOverCompilerLimit`) are announced from each render variant's own -//! pipeline: `Device::degrade_render`, which every render variant's making runs (the base variant -//! and every other), and `Kinds::of`, whose kinds a bind's notices are made of. So a variant the -//! fit reduced while its base was not announces `exact-forms-over-compiler-limit`, once per device, -//! naming the forms dropped, and a bind of it on a device asking for the kind at every occurrence -//! announces it there; the base announces nothing of it. +//! The exact forms a pipeline's translation dropped to fit the device's compiler word bound +//! (`RuntimeFact::ExactFormsOverCompilerLimit`) are announced from each variant's own pipeline: +//! `Device::degrade_pipeline`, which every variant's making runs (the base variant and every +//! other, of a render, mesh render, compute or tile render state alike), and `Kinds::of`, whose +//! kinds a bind's notices are made of. So a variant the fit reduced while its base was not +//! announces `exact-forms-over-compiler-limit`, once per device, naming the forms dropped and its +//! state's kind, and a bind of it on a device asking for the kind at every occurrence announces it +//! there; the base announces nothing of it. //! //! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. The pipelines are the owned -//! `runtime_examples` fixture's (`llvm-as`), the fitted one carrying the fit's record as the -//! translation adds it. +//! `runtime_examples`, `mesh_draws` and `cfb_tile_norm` fixtures' (`llvm-as`), compiled for the +//! device, each fitted one carrying the fit's record as the translation adds it; nothing runs on +//! the GPU. -use crate::degradation::{Kinds, Occurrence}; +use crate::degradation::{CompiledPipeline, Kinds, Occurrence}; use crate::device::lock; use crate::{Degradation, Device, DeviceKind, DeviceOptions, MessageSink}; +use metal2vulkan::library::Library; use metal2vulkan::metal::PixelFormat; use metal2vulkan::pipeline::{ - ColorAttachmentDescriptor, FunctionDescriptor, Mechanism, RenderPipeline, - RenderPipelineDescriptor, RuntimeDependency, RuntimeFact, StageSource, + ColorAttachmentDescriptor, ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, + Mechanism, MeshPipelineDescriptor, RenderPipeline, RenderPipelineDescriptor, RuntimeDependency, + RuntimeFact, StageModule, StageSource, TileRenderPipelineDescriptor, }; +use metal2vulkan::Budget; use std::collections::BTreeSet; use std::path::Path; use std::sync::{Arc, Mutex}; -/// What the device's sink heard: each degrade notice's kind and reason. -type Heard = Arc>>; +/// What the device's sink heard: each degrade notice's kind, object and reason. +type Heard = Arc>>; /// The device the cfg selects, asking for `each` at every occurrence, with a sink that keeps every /// degrade notice. @@ -33,7 +38,11 @@ fn listening(each: BTreeSet) -> (Device, Heard) { let kept = Arc::clone(&heard); let sink = MessageSink::new(move |message: &crate::DebugMessage| { if let Some(notice) = &message.degradation { - lock(&kept).push((notice.degradation, notice.reason.clone())); + lock(&kept).push(( + notice.degradation, + notice.object.clone(), + notice.reason.clone(), + )); } }); let options = DeviceOptions { @@ -52,25 +61,18 @@ fn listening(each: BTreeSet) -> (Device, Heard) { (Device::system_default_with(&options).unwrap(), heard) } -/// The fixture's render pipeline (`colored_vertex`, `colored_fragment`, one `RGBA8Unorm` target), -/// compiled for `device`, and the same pipeline as the fit records it where it dropped exact -/// sampling and exact float maths. -fn pipelines(device: &Device) -> (RenderPipeline, RenderPipeline) { +/// The owned fixture `name` (under the public fixtures) as a library. +fn library(name: &str) -> Library { let ll = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/fixtures/public/examples/runtime_examples.ll"); + .join("../metal2vulkan-validation/fixtures/public") + .join(name); let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap(); - let library = metal2vulkan::library::Library::from_air(&bitcode).unwrap(); - let function = |name| FunctionDescriptor::new(library.function(name).unwrap()); - let mut descriptor = - RenderPipelineDescriptor::new(StageSource::Function(function("colored_vertex"))); - descriptor.fragment = Some(StageSource::Function(function("colored_fragment"))); - descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); - let base = device - .compile_device() - .compile_render_pipeline(&descriptor, &metal2vulkan::Budget::standard()) - .unwrap(); - let mut fitted = base.clone(); - fitted.dependencies.push(RuntimeDependency::new( + Library::from_air(&bitcode).unwrap() +} + +/// Add to `dependencies` the fit's record of dropping exact sampling and exact float maths. +fn fit_into(dependencies: &mut Vec) { + dependencies.push(RuntimeDependency::new( RuntimeFact::ExactFormsOverCompilerLimit { sampling: true, float_maths: true, @@ -82,15 +84,100 @@ fn pipelines(device: &Device) -> (RenderPipeline, RenderPipeline) { }, Mechanism::None, )); - (base, fitted) } -/// The notices of `kind` the sink heard. -fn of_kind(heard: &Heard, kind: Degradation) -> Vec { +/// `pipeline` as the fit records it. +fn render_fit(pipeline: &RenderPipeline) -> RenderPipeline { + let mut fit = pipeline.clone(); + fit_into(&mut fit.dependencies); + fit +} + +/// `pipeline` as the fit records it. +fn kernel_fit(pipeline: &ComputePipeline) -> ComputePipeline { + let mut fit = pipeline.clone(); + fit_into(&mut fit.dependencies); + fit +} + +/// The fixture's render pipeline (`colored_vertex`, `colored_fragment`, one `RGBA8Unorm` target), +/// compiled for `device`, and the same pipeline as the fit records it. +fn pipelines(device: &Device) -> (RenderPipeline, RenderPipeline) { + let library = library("examples/runtime_examples.ll"); + let function = |name| FunctionDescriptor::new(library.function(name).unwrap()); + let mut descriptor = + RenderPipelineDescriptor::new(StageSource::Function(function("colored_vertex"))); + descriptor.fragment = Some(StageSource::Function(function("colored_fragment"))); + descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + let base = device + .compile_device() + .compile_render_pipeline(&descriptor, &Budget::standard()) + .unwrap(); + let fit = render_fit(&base); + (base, fit) +} + +/// A mesh render pipeline (`mesh_draws`' object, mesh and fragment functions, two `RGBA32Uint` +/// targets), compiled for `device`: its `MeshEXT` stages, or the compute and vertex stages that +/// emulate them. +fn mesh_pipeline(device: &Device) -> RenderPipeline { + let library = library("engine/mesh_draws.ll"); + let stage = + |name| StageSource::Function(FunctionDescriptor::new(library.function(name).unwrap())); + let mut descriptor = MeshPipelineDescriptor::new(stage("mesh_draws_mesh")); + descriptor.object = Some(stage("mesh_draws_object")); + descriptor.fragment = Some(stage("mesh_draws_fragment")); + for color in &mut descriptor.color_attachments[..2] { + *color = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA32Uint)); + } + device + .compile_device() + .compile_mesh_pipeline(&descriptor, &Budget::standard()) + .unwrap() +} + +/// A compute pipeline (`runtime_examples`' `scale_and_offset` kernel) and a tile render pipeline +/// (`cfb_tile_norm`'s write of an `RGBA8Unorm` attachment), compiled for `device`. +fn kernel_pipelines(device: &Device) -> (ComputePipeline, ComputePipeline) { + let compile = device.compile_device(); + let examples = library("examples/runtime_examples.ll"); + let kernel = FunctionDescriptor::new(examples.function("scale_and_offset").unwrap()); + let compute = compile + .compile_compute_pipeline( + &ComputePipelineDescriptor::new(StageSource::Function(kernel)), + &Budget::standard(), + ) + .unwrap(); + let tiles = library("engine/cfb_tile_norm.ll"); + let tile = FunctionDescriptor::new(tiles.function("cfb_tn_write4").unwrap()); + let mut descriptor = TileRenderPipelineDescriptor::new(StageSource::Function(tile)); + descriptor.color_attachment_formats[0] = Some(PixelFormat::RGBA8Unorm); + let tile = compile + .compile_tile_pipeline(&descriptor, &Budget::standard()) + .unwrap(); + (compute, tile) +} + +/// A render variant of `pipeline`: its stages and pipeline, as its making and binds announce them. +fn render_variant(pipeline: &RenderPipeline) -> (&[StageModule], CompiledPipeline<'_>) { + (&pipeline.stages, CompiledPipeline::Render(pipeline)) +} + +/// A compute or tile variant of `pipeline`: its stage and pipeline, as its making and binds +/// announce them. +fn kernel_variant(pipeline: &ComputePipeline) -> (&[StageModule], CompiledPipeline<'_>) { + ( + std::slice::from_ref(&pipeline.stage), + CompiledPipeline::Kernel(pipeline), + ) +} + +/// The notices of `kind` the sink heard, each's object and reason. +fn of_kind(heard: &Heard, kind: Degradation) -> Vec<(String, String)> { lock(heard) .iter() - .filter(|(k, _)| *k == kind) - .map(|(_, reason)| reason.clone()) + .filter(|(k, _, _)| *k == kind) + .map(|(_, object, reason)| (object.clone(), reason.clone())) .collect() } @@ -98,39 +185,111 @@ fn of_kind(heard: &Heard, kind: Degradation) -> Vec { fn a_variant_fitted_while_its_base_was_not_still_announces() { let kind = Degradation::ExactFormsOverCompilerLimit; let (device, heard) = listening(BTreeSet::new()); - let (base, fitted) = pipelines(&device); + let (base, fit) = pipelines(&device); // The base variant's making: no form dropped, nothing of the kind. - device.degrade_render(&base, Occurrence::Made); + device.degrade_pipeline(CompiledPipeline::Render(&base), Occurrence::Made); assert!(of_kind(&heard, kind).is_empty(), "the base announced it"); // Another variant's making, its pipeline fitted: announced, naming the forms dropped. - device.degrade_render(&fitted, Occurrence::Made); + device.degrade_pipeline(CompiledPipeline::Render(&fit), Occurrence::Made); let said = of_kind(&heard, kind); assert_eq!(said.len(), 1, "{said:?}"); + let (object, reason) = &said[0]; + assert_eq!(object, "a render pipeline state"); assert!( - said[0].contains("exact sampling, exact float maths") - && !said[0].contains("exact half blend"), - "{}", - said[0] + reason.contains("exact sampling, exact float maths") + && !reason.contains("exact half blend"), + "{reason}" ); // Once per device: a later fitted variant adds no second notice. - device.degrade_render(&fitted, Occurrence::Made); + device.degrade_pipeline(CompiledPipeline::Render(&fit), Occurrence::Made); assert_eq!(of_kind(&heard, kind).len(), 1); // A device asking for the kind at every occurrence: the fitted variant's kinds hold it, and each // bind's notices carry it, where the base's hold none of it; its making announces nothing. let (each, heard) = listening(BTreeSet::from([kind])); - let (base, fitted) = pipelines(&each); - each.degrade_render(&fitted, Occurrence::Made); + let (base, fit) = pipelines(&each); + let (base, fit) = (render_variant(&base), render_variant(&fit)); + each.degrade_pipeline(fit.1, Occurrence::Made); assert!(of_kind(&heard, kind).is_empty(), "announced at the making"); - assert!(each.binds_each(&Kinds::of(&fitted.stages, Some(&fitted)))); - assert!(!each.binds_each(&Kinds::of(&base.stages, Some(&base)))); + assert!(each.binds_each(&Kinds::of(fit.0, fit.1))); + assert!(!each.binds_each(&Kinds::of(base.0, base.1))); for _ in 0..2 { - let notices = each.bound_notices((&fitted.stages, Some(&fitted)), &[]); + let notices = each.bound_notices(fit, &[]); let kinds: Vec = notices.iter().map(|(k, _)| *k).collect(); assert_eq!(kinds, [kind], "a bind of the fitted variant"); } assert!(each - .bound_notices((&base.stages, Some(&base)), &[]) + .bound_notices(base, &[]) .iter() .all(|(k, _)| *k != kind)); } + +/// A mesh render, compute or tile render state's fitted variant announces the kind as a vertex +/// and fragment state's does, naming its own state's kind, read from its pipeline's structure: +/// at its making (a compute variant's too, which `pipeline/mod.rs` makes), and at each bind on a +/// device asking for the kind at every occurrence, where its unfitted base announces nothing of +/// it. +#[test] +fn every_kind_of_fitted_pipeline_announces_its_state_kind() { + let kind = Degradation::ExactFormsOverCompilerLimit; + // A compute variant's making: announced, as a compute pipeline state's. + let (device, heard) = listening(BTreeSet::new()); + let (compute, _) = kernel_pipelines(&device); + device.degrade_pipeline(CompiledPipeline::Kernel(&compute), Occurrence::Made); + assert!(of_kind(&heard, kind).is_empty(), "the base announced it"); + let fit = kernel_fit(&compute); + device.degrade_pipeline(CompiledPipeline::Kernel(&fit), Occurrence::Made); + let said = of_kind(&heard, kind); + assert_eq!(said.len(), 1, "{said:?}"); + assert_eq!(said[0].0, "a compute pipeline state"); + assert!( + said[0].1.contains("exact sampling, exact float maths"), + "{said:?}" + ); + + // Each kind's bind, on a device asking for the kind at every occurrence. + let (each, _) = listening(BTreeSet::from([kind])); + let (render, _) = pipelines(&each); + let mesh = mesh_pipeline(&each); + let (compute, tile) = kernel_pipelines(&each); + let (render_fitted, mesh_fitted) = (render_fit(&render), render_fit(&mesh)); + let (compute_fitted, tile_fitted) = (kernel_fit(&compute), kernel_fit(&tile)); + let cases = [ + ( + "a render pipeline state", + render_variant(&render), + render_variant(&render_fitted), + ), + ( + "a mesh render pipeline state", + render_variant(&mesh), + render_variant(&mesh_fitted), + ), + ( + "a compute pipeline state", + kernel_variant(&compute), + kernel_variant(&compute_fitted), + ), + ( + "a tile render pipeline state", + kernel_variant(&tile), + kernel_variant(&tile_fitted), + ), + ]; + for (object, base, fit) in cases { + assert!(each.binds_each(&Kinds::of(fit.0, fit.1)), "{object}"); + let notices = each.bound_notices(fit, &[]); + let named: Vec<&str> = notices + .iter() + .filter(|(k, _)| *k == kind) + .filter_map(|(_, message)| Some(message.degradation.as_ref()?.object.as_str())) + .collect(); + assert_eq!(named, [object], "a bind of the fitted variant"); + assert!( + each.bound_notices(base, &[]) + .iter() + .all(|(k, _)| *k != kind), + "{object}: its base" + ); + } +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index 6e0e7fb06..f460498cb 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -58,8 +58,8 @@ //! draws emulated on a device without `VK_EXT_mesh_shader` in `mesh_draws` ([`EMULATED_MESH`]), //! render pipeline states whose draws run a synthesized geometry stage in `barycentric_weights` //! ([`SYNTHESIZED_GEOMETRY`]), tessellated draws emulated on a device without -//! `tessellationShader` in `patches` ([`EMULATED_TESSELLATION`]), render pipeline states whose -//! exact forms a stage past the device's compiler word bound dropped here +//! `tessellationShader` in `patches` ([`EMULATED_TESSELLATION`]), render and compute pipeline +//! states whose exact forms a stage past the device's compiler word bound dropped here //! ([`EXACT_FORMS_OVER_LIMIT`]), //! vertex-stage reads in place of bytes a fragment stage of the pass wrote in `pass_start_reads` //! ([`IN_PLACE_VERTEX_READS`]) and a vertex stage's write of bytes one wrote there @@ -638,19 +638,19 @@ fn moltenvk_argument_buffers_are_announced_where_unread_and_refused_off() { assert_eq!(off.take(), Vec::new(), "the validation layer reported"); } -/// The kind a render pipeline state takes where a stage of its translation, with the device's -/// exact forms, is longer than the device's compiler word bound, and the translation dropped exact +/// The kind a pipeline state takes where a stage of its translation, with the device's exact +/// forms, is longer than the device's compiler word bound, and the translation dropped exact /// forms to fit it ([`exact_forms_past_the_compiler_bound_are_announced_exactly_there`]). const EXACT_FORMS_OVER_LIMIT: [Degradation; 1] = [Degradation::ExactFormsOverCompilerLimit]; -/// A render pipeline state announces [`EXACT_FORMS_OVER_LIMIT`] exactly where a stage of its -/// translation with the lane's exact forms (`runtime_lane::validated_options`) is longer than the -/// device's compiler word bound (`DeviceProfile::module_word_bound`: ANV's, `None` elsewhere). No -/// owned render fixture's stage reaches ANV's bound, so no venue announces it today; each checks -/// the rule on its own device, with the owned `runtime_examples` render pipeline. The runtime's own -/// test `a_variant_fitted_while_its_base_was_not_still_announces` takes the announcement of a -/// fitted variant, and the translator's -/// `a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit` the fit. +/// A render pipeline state, and a compute pipeline state, announces [`EXACT_FORMS_OVER_LIMIT`] +/// exactly where a stage of its translation with the lane's exact forms +/// (`runtime_lane::validated_options`) is longer than the device's compiler word bound +/// (`DeviceProfile::module_word_bound`: ANV's, `None` elsewhere). No owned fixture's stage reaches +/// ANV's bound, so no venue announces it today; each checks the rule on its own device, with the +/// owned `runtime_examples` render pipeline and kernel. The runtime's own tests +/// (`fitted_variant_notice`) take the announcement of a fitted variant of every kind of state, +/// and the translator's (`pipeline::compile::fit`) the fit of every kind of pipeline. #[test] fn exact_forms_past_the_compiler_bound_are_announced_exactly_there() { on_device(|device, messages| { @@ -671,6 +671,25 @@ fn exact_forms_past_the_compiler_bound_are_announced_exactly_there() { descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); let compile = device.compile_device(); + let bound = compile.profile().module_word_bound(); + // The notices a state's creation made, against whether its longest stage passes the bound. + let check = |what: &str, longest: usize| { + let past = bound.is_some_and(|bound| longest > bound as usize); + let announced = counts(&messages.take_notices()) + .get(&Degradation::ExactFormsOverCompilerLimit) + .copied() + .unwrap_or(0); + eprintln!( + "{}: {what}: longest stage {longest} words, compiler word bound {bound:?}", + device.name() + ); + assert_eq!( + announced, + usize::from(past), + "{what}: {:?} exactly past the bound", + EXACT_FORMS_OVER_LIMIT + ); + }; let compiled = compile .compile_render_pipeline(&descriptor, &Budget::standard()) .unwrap(); @@ -680,25 +699,22 @@ fn exact_forms_past_the_compiler_bound_are_announced_exactly_there() { .map(|stage| stage.spirv.len()) .max() .unwrap_or(0); - let bound = compile.profile().module_word_bound(); - let past = bound.is_some_and(|bound| longest > bound as usize); let _state = device .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) .unwrap(); - let announced = counts(&messages.take_notices()) - .get(&Degradation::ExactFormsOverCompilerLimit) - .copied() - .unwrap_or(0); - eprintln!( - "{}: longest stage {longest} words, compiler word bound {bound:?}", - device.name() - ); - assert_eq!( - announced, - usize::from(past), - "{:?} exactly past the bound", - EXACT_FORMS_OVER_LIMIT - ); + check("render", longest); + let kernel = + ComputePipelineDescriptor::new(StageSource::Function(function("scale_and_offset"))); + let longest = compile + .compile_compute_pipeline(&kernel, &Budget::standard()) + .unwrap() + .stage + .spirv + .len(); + let _state = device + .new_compute_pipeline_state(&kernel, &PipelineOptions::default()) + .unwrap(); + check("compute", longest); }); } diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index a883edcae..c0c5b59b0 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -55,8 +55,8 @@ struct DeviceInner { /// runtime's heap sizes read; not a profile field, as above. allocation: AllocationLimits, /// The description the device was made from, kept so a compile over a device's compiler word - /// bound can rebuild the device under a reduced policy (`Device::fit_render_variant`); not - /// a profile field, as above. + /// bound can rebuild the device under a reduced policy (`Device::fit_render_variant` and the + /// other kinds' fits); not a profile field, as above. description: DeviceDescription, } @@ -157,7 +157,8 @@ impl Device { } /// The description the device was made from, for a compile that rebuilds the device under a - /// reduced policy to fit a compiler word bound (`Device::fit_render_variant`). + /// reduced policy to fit a compiler word bound (`Device::fit_render_variant` and the other + /// kinds' fits). pub(crate) fn description(&self) -> &DeviceDescription { &self.0.description } diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 4cd7abce6..aa88678d2 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -182,8 +182,12 @@ impl DeviceProfile { /// The stage-module word count a pipeline's largest stage must fit for this device, where its /// driver faults compiling a module past it /// ([`DriverWorkaround::RegisterAllocatorOverflowsLargeModules`]); `None` where no such bound - /// is measured. A compile over the bound retranslates with the consumer's exact forms dropped - /// to fit ([`Device::fit_render_variant`](crate::device::Device::fit_render_variant)). + /// is measured. A compile of any pipeline kind over the bound retranslates with the consumer's + /// exact forms dropped to fit + /// ([`Device::fit_render_variant`](crate::device::Device::fit_render_variant), + /// [`fit_mesh_variant`](crate::device::Device::fit_mesh_variant), + /// [`fit_compute_pipeline`](crate::device::Device::fit_compute_pipeline), + /// [`fit_tile_pipeline`](crate::device::Device::fit_tile_pipeline)). pub fn module_word_bound(&self) -> Option { self.fields .workarounds diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 4d096ccec..47c451630 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -11,11 +11,12 @@ //! //! The public surface (`Device::compile_function`, `function_compile_key`, //! `compile_compute_pipeline`, `compile_render_pipeline`, and the pipeline keys) is [`api`]; the -//! key derivation is [`key`]. +//! key derivation is [`key`]; holding a pipeline to the device's compiler word bound is `fit`. pub mod api; pub(crate) mod color_group; mod entry; +mod fit; pub mod key; mod numbered; mod partition; diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index a45f12005..52895e9b7 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -24,10 +24,6 @@ use crate::budget::{Budget, Meter}; use crate::cache::VariantKey; -use crate::device::policy::{ - DevicePolicy, FloatMathsPolicy, HalfBlendPolicy, HalfRoundingPolicy, NanMinMaxPolicy, - RoundingOrderPolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy, -}; use crate::device::requirements::{Requirements, VkExtension, VkFeature, VkLimit, VkProperty}; use crate::device::{mechanism, Device, DeviceProfile}; use crate::error::{ @@ -220,12 +216,19 @@ impl Device { /// call stack was sized for another depth (`RuntimeFact::CallStackDepth`) is /// `InvalidDescriptor(MaxCallStackDepth)`. A stage-input attribute whose buffer has no layout, /// read or not, is `InvalidDescriptor(StageInputLayout)`, where Metal stops at an assertion. + /// A `Function` kernel's pipeline is held to the device's compiler word bound + /// ([`Device::fit_compute_pipeline`]). pub fn compile_compute_pipeline( &self, d: &ComputePipelineDescriptor, b: &Budget, ) -> Result { - guarded(|| self.compute_pipeline(d, &mut Meter::new(b))) + guarded(|| { + let inputs = kernel_inputs(d); + let first = self.compute_pipeline(d, &inputs, &mut Meter::new(b))?; + let bound = self.profile().module_word_bound(); + self.fit_compute_within(d, &inputs, b, first, bound) + }) } /// The key of the tile render pipeline `d` (no decode). @@ -255,13 +258,19 @@ impl Device { /// `InvalidDescriptor(ColorAttachment)`. A multisampled pass (`raster_sample_count` above 1) is /// `Unsupported{TileShading, NotImplemented}`: what its imageblock's samples are is not read. /// The tile function's recursion is sized for `d`'s `maxCallStackDepth` as a compute kernel's - /// is. + /// is. A `Function` tile function's pipeline is held to the device's compiler word bound + /// ([`Device::fit_tile_pipeline`]). pub fn compile_tile_pipeline( &self, d: &TileRenderPipelineDescriptor, b: &Budget, ) -> Result { - guarded(|| self.tile_pipeline(d, &mut Meter::new(b))) + guarded(|| { + let inputs = tile_inputs(d); + let first = self.tile_pipeline(d, &inputs, &mut Meter::new(b))?; + let bound = self.profile().module_word_bound(); + self.fit_tile_within(d, &inputs, b, first, bound) + }) } /// The keys of the render pipeline `d`, with the lowering inputs of each `Function` stage. A @@ -415,7 +424,8 @@ impl Device { /// compiled under the same inputs; link refuses a vertex stage compiled under another /// projection. Each stage's recursion is sized for `d`'s `maxVertexCallStackDepth` or /// `maxFragmentCallStackDepth`, as a compute kernel's is for its pipeline's; a `Compiled` stage - /// sized for another depth is `InvalidDescriptor(MaxCallStackDepth)`. + /// sized for another depth is `InvalidDescriptor(MaxCallStackDepth)`. A pipeline of `Function` + /// stages is held to the device's compiler word bound ([`Device::fit_render_variant`]). pub fn compile_render_variant( &self, d: &RenderPipelineDescriptor, @@ -424,73 +434,7 @@ impl Device { ) -> Result { guarded(|| { let first = self.render_pipeline(d, v, &mut Meter::new(b))?; - self.fit_within(d, v, b, first, self.profile().module_word_bound()) - }) - } - - /// `pipeline`, [`Device::compile_render_variant`]'s compile of `d` under `v` (whose stages may - /// be `Compiled`), held to the device's compiler word bound - /// ([`DeviceProfile::module_word_bound`]): where the driver faults compiling a module past it - /// and `pipeline`'s largest stage passes it, `d`'s stages translated again with the device - /// policy's exact forms dropped until the largest fits, in at most two steps (native sampling, - /// then every exact answer that grows a module native), recording the forms dropped - /// (`RuntimeFact::ExactFormsOverCompilerLimit`) and keeping `pipeline`'s key and profile - /// fingerprint, so a cache finds it where it would find `pipeline`. The stages carry the - /// reduced forms' own precision notes. `pipeline` itself where the device has no bound, it - /// fits, or a stage of `d` is `Compiled` (only a `Function` stage can be translated again): - /// a caller that compiled its stages ahead must pass the descriptor of their functions here, - /// or the module goes to the driver unreduced. - pub fn fit_render_variant( - &self, - d: &RenderPipelineDescriptor, - v: &VariantKey, - b: &Budget, - pipeline: RenderPipeline, - ) -> Result { - guarded(|| self.fit_within(d, v, b, pipeline, self.profile().module_word_bound())) - } - - /// [`Device::fit_render_variant`] under `bound` in place of the device's own: a test pins a - /// low bound without a device that carries the workaround. - pub(crate) fn fit_within( - &self, - d: &RenderPipelineDescriptor, - v: &VariantKey, - b: &Budget, - pipeline: RenderPipeline, - bound: Option, - ) -> Result { - let translatable = matches!(d.vertex, StageSource::Function(_)) - && !matches!(d.fragment, Some(StageSource::Compiled(_))); - let Some(bound) = bound.filter(|&w| translatable && largest_stage_words(&pipeline) > w) - else { - return Ok(pipeline); - }; - let base = *self.policy(); - let mut best: Option = None; - for step in [ReducedForms::NativeSampling, ReducedForms::AllNative] { - let policy = step.of(base); - if policy == base { - continue; - } - // The lowering reads the profile, never the policy, and `Device::new` is the profile's - // one producer: the description kept, the policy reduced. - let device = Device::new(self.description().clone(), policy)?; - let mut reduced = device.render_pipeline(d, v, &mut Meter::new(b))?; - record_dropped_forms(&mut reduced, base, &policy, device.profile()); - let fits = largest_stage_words(&reduced) <= bound; - best = Some(reduced); - if fits { - break; - } - } - Ok(match best { - Some(mut reduced) => { - reduced.key = pipeline.key; - reduced.profile = pipeline.profile; - reduced - } - None => pipeline, + self.fit_render_within(d, v, b, first, self.profile().module_word_bound()) }) } @@ -518,17 +462,21 @@ impl Device { /// Compile the mesh render pipeline `d` under the variant `v` a plan of it asked for /// (`BindingPlan::variant`) and budget `b`, as [`Device::compile_mesh_pipeline`] does: each /// `Function` stage under [`VariantKey::lowering_inputs`] of its stage, the fragment function's - /// for the mesh function's outputs. + /// for the mesh function's outputs. A pipeline of `Function` stages is held to the device's + /// compiler word bound ([`Device::fit_mesh_variant`]). pub fn compile_mesh_variant( &self, d: &MeshPipelineDescriptor, v: &VariantKey, b: &Budget, ) -> Result { - guarded(|| self.mesh_pipeline(d, v, &mut Meter::new(b))) + guarded(|| { + let first = self.mesh_pipeline(d, v, &mut Meter::new(b))?; + self.fit_mesh_within(d, v, b, first, self.profile().module_word_bound()) + }) } - /// [`Device::compile_mesh_variant`] with the caller's meter. + /// [`Device::compile_mesh_variant`] with the caller's meter, unfitted. pub(crate) fn mesh_pipeline( &self, d: &MeshPipelineDescriptor, @@ -687,10 +635,13 @@ impl Device { } } - /// [`Device::compile_compute_pipeline`] with the caller's meter (tests count its work). + /// [`Device::compile_compute_pipeline`] with the caller's meter (tests count its work), + /// unfitted, a `Function` kernel compiled under `inputs` (`d`'s own, `kernel_inputs`, or a + /// fit's). pub(crate) fn compute_pipeline( &self, d: &ComputePipelineDescriptor, + inputs: &LoweringInputs, m: &mut Meter, ) -> Result { let p = self.profile(); @@ -698,7 +649,7 @@ impl Device { if let Some(stage_input) = &d.stage_input { stage_input.check_layouts()?; } - let kernel = self.stage(&d.kernel, InputsFrom::Given(&kernel_inputs(d)), m)?; + let kernel = self.stage(&d.kernel, InputsFrom::Given(inputs), m)?; let a = kernel.artifact(); check_stage_in(a, d)?; check_call_stack(a, d.max_call_stack_depth)?; @@ -724,17 +675,19 @@ impl Device { }) } - /// [`Device::compile_tile_pipeline`] with the caller's meter. + /// [`Device::compile_tile_pipeline`] with the caller's meter, unfitted, a `Function` tile + /// function compiled under `inputs` (`d`'s own, `tile_inputs`, or a fit's). pub(crate) fn tile_pipeline( &self, d: &TileRenderPipelineDescriptor, + inputs: &LoweringInputs, m: &mut Meter, ) -> Result { if d.raster_sample_count > 1 { return Err(Unsupported::not_implemented(Feature::TileShading).into()); } let p = self.profile(); - let kernel = self.stage(&d.tile, InputsFrom::Given(&tile_inputs(d)), m)?; + let kernel = self.stage(&d.tile, InputsFrom::Given(inputs), m)?; let a = kernel.artifact(); if a.interface.stage != Stage::Kernel || !a.facts.contains(&RuntimeFact::TileFunction) { return Err(Error::InvalidDescriptor(DescriptorError::StageMismatch { @@ -771,9 +724,9 @@ impl Device { }) } - /// [`Device::compile_render_variant`] with the caller's meter. A variant of one of the - /// pipeline's color groups (`VariantKey::color_group`) compiles and links as the pipeline of - /// its group's attachments (`color_group`), its key's choices of colors naming the group's. + /// [`Device::compile_render_variant`] with the caller's meter, unfitted. A variant of one of + /// the pipeline's color groups (`VariantKey::color_group`) compiles and links as the pipeline + /// of its group's attachments (`color_group`), its key's choices of colors naming the group's. pub(crate) fn render_pipeline( &self, d: &RenderPipelineDescriptor, @@ -1288,75 +1241,6 @@ fn invariant(detail: &str) -> Error { )) } -/// The word count of a render pipeline's largest stage module: what a device's compiler word bound -/// holds ([`DeviceProfile::module_word_bound`]). A pipeline with no stage counts as 0. -fn largest_stage_words(pipeline: &RenderPipeline) -> u32 { - pipeline - .stages - .iter() - .map(|s| u32::try_from(s.spirv.len()).unwrap_or(u32::MAX)) - .max() - .unwrap_or(0) -} - -/// A step of the compiler-word-bound fallback: the exact forms to drop from the consumer's policy. -/// `NativeSampling` drops exact sampling, the single largest exact form, with Metal's filter of a -/// two-plane YCbCr texture (`YCbCrFilterPolicy::Exact`, reported with it); `AllNative` drops every -/// module-growing exact answer (the fast default's forms). Neither touches the policy's other -/// choices (pointer and handle domains, containment, isolation, framebuffer fetch, the 8-bit -#[derive(Clone, Copy)] -enum ReducedForms { - NativeSampling, - AllNative, -} - -impl ReducedForms { - /// `base` with this step's exact forms set to their native, module-smaller answers. - fn of(self, base: DevicePolicy) -> DevicePolicy { - let sampled = DevicePolicy { - sampling: SamplingPolicy::NativeDevice, - ycbcr_filter: YCbCrFilterPolicy::Device, - ..base - }; - match self { - ReducedForms::NativeSampling => sampled, - ReducedForms::AllNative => DevicePolicy { - float_maths: FloatMathsPolicy::Native, - texel_conversion: TexelConversionPolicy::Device, - half_rounding: HalfRoundingPolicy::Native, - nan_and_min_max: NanMinMaxPolicy::Native, - rounding_order: RoundingOrderPolicy::Native, - half_blend: HalfBlendPolicy::Device, - ..sampled - }, - } - } -} - -/// Record on `pipeline` which of the consumer's exact forms the fallback dropped to fit the bound: -/// each field of [`RuntimeFact::ExactFormsOverCompilerLimit`] is set where `base`'s form differs -/// from the reduced `policy`'s. The consumer announces it once per device. -fn record_dropped_forms( - pipeline: &mut RenderPipeline, - base: DevicePolicy, - policy: &DevicePolicy, - reduced: &DeviceProfile, -) { - let fact = RuntimeFact::ExactFormsOverCompilerLimit { - sampling: base.sampling != policy.sampling || base.ycbcr_filter != policy.ycbcr_filter, - float_maths: base.float_maths != policy.float_maths, - texel_conversion: base.texel_conversion != policy.texel_conversion, - half_rounding: base.half_rounding != policy.half_rounding, - nan_and_min_max: base.nan_and_min_max != policy.nan_and_min_max, - rounding_order: base.rounding_order != policy.rounding_order, - half_blend: base.half_blend != policy.half_blend, - }; - pipeline.dependencies.push(RuntimeDependency { - fact, - mechanism: mechanism(&fact, reduced), - }); -} - /// The lowering inputs a `Function` kernel of compute pipeline `d` compiles under: its /// stage-input descriptor and its `maxCallStackDepth` when not Metal's default, 1. fn kernel_inputs(d: &ComputePipelineDescriptor) -> LoweringInputs { diff --git a/crates/metal2vulkan/src/pipeline/compile/fit.rs b/crates/metal2vulkan/src/pipeline/compile/fit.rs new file mode 100644 index 000000000..961d60ac3 --- /dev/null +++ b/crates/metal2vulkan/src/pipeline/compile/fit.rs @@ -0,0 +1,334 @@ +//! The compiler-word-bound fit: a pipeline whose largest stage module passes the device's +//! compiler word bound ([`DeviceProfile::module_word_bound`], where the driver faults compiling a +//! module past it), translated again from its functions with the device policy's exact forms +//! dropped until the largest fits, recording the forms dropped +//! (`RuntimeFact::ExactFormsOverCompilerLimit`). Every pipeline kind is fitted by the one rule: a +//! render pipeline of vertex and fragment stages, a mesh render pipeline (object, mesh and +//! fragment stages, or the compute and synthesized vertex stages of an emulated mesh), a compute +//! pipeline and a tile render pipeline. Each kind's compile from `Function` stages fits itself +//! ([`Device::compile_render_variant`], [`Device::compile_mesh_variant`], +//! [`Device::compile_compute_pipeline`], [`Device::compile_tile_pipeline`]); a pipeline linked from +//! `Compiled` stages is fitted from the descriptor of its functions by the kind's `fit_*` call. + +use crate::budget::{Budget, Meter}; +use crate::cache::VariantKey; +use crate::device::policy::{ + DevicePolicy, FloatMathsPolicy, HalfBlendPolicy, HalfRoundingPolicy, NanMinMaxPolicy, + RoundingOrderPolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy, +}; +use crate::device::{mechanism, Device, DeviceProfile}; +use crate::error::Error; +use crate::pipeline::artifact::{ComputePipeline, RenderPipeline, RuntimeDependency}; +use crate::pipeline::compile::guarded; +use crate::pipeline::descriptor::{ + ComputePipelineDescriptor, MeshPipelineDescriptor, RenderPipelineDescriptor, StageSource, + TileRenderPipelineDescriptor, +}; +use crate::pipeline::facts::RuntimeFact; +use crate::pipeline::lower_inputs::LoweringInputs; + +#[cfg(test)] +mod tests; + +impl Device { + /// `pipeline`, [`Device::compile_render_variant`]'s compile of `d` under `v` (whose stages may + /// be `Compiled`), held to the device's compiler word bound + /// ([`DeviceProfile::module_word_bound`]): where the driver faults compiling a module past it + /// and `pipeline`'s largest stage passes it, `d`'s stages translated again with the device + /// policy's exact forms dropped until the largest fits, in at most two steps (native sampling, + /// then every exact answer that grows a module native), recording the forms dropped + /// (`RuntimeFact::ExactFormsOverCompilerLimit`) and keeping `pipeline`'s key and profile + /// fingerprint, so a cache finds it where it would find `pipeline`. The stages carry the + /// reduced forms' own precision notes. `pipeline` itself where the device has no bound, it + /// fits, or a stage of `d` is `Compiled` (only a `Function` stage can be translated again): + /// a caller that compiled its stages ahead must pass the descriptor of their functions here, + /// or the module goes to the driver unreduced. + pub fn fit_render_variant( + &self, + d: &RenderPipelineDescriptor, + v: &VariantKey, + b: &Budget, + pipeline: RenderPipeline, + ) -> Result { + guarded(|| self.fit_render_within(d, v, b, pipeline, self.profile().module_word_bound())) + } + + /// `pipeline`, [`Device::compile_mesh_variant`]'s compile of `d` under `v` (whose stages may be + /// `Compiled`), held to the device's compiler word bound as + /// [`Device::fit_render_variant`] holds a render pipeline: its object, mesh and fragment + /// stages translated again from `d`'s functions with the exact forms dropped where its largest + /// stage (the synthesized vertex stage of an emulated mesh among them) passes the bound, under + /// `pipeline`'s key. `pipeline` itself where the device has no bound, it fits, or a stage of + /// `d` is `Compiled`. + pub fn fit_mesh_variant( + &self, + d: &MeshPipelineDescriptor, + v: &VariantKey, + b: &Budget, + pipeline: RenderPipeline, + ) -> Result { + guarded(|| self.fit_mesh_within(d, v, b, pipeline, self.profile().module_word_bound())) + } + + /// `pipeline`, [`Device::compile_compute_pipeline`]'s compile of `d` (whose kernel may be + /// `Compiled`), its kernel compiled under `inputs`, held to the device's compiler word bound as + /// [`Device::fit_render_variant`] holds a render pipeline: `d`'s kernel function translated + /// again under `inputs` with the exact forms dropped where its module passes the bound, under + /// `pipeline`'s key. `inputs` are those the kernel was compiled under: a `Function` kernel's + /// in [`Device::compile_compute_pipeline`] are `d`'s stage-input descriptor and + /// `maxCallStackDepth`, and a kernel compiled ahead ([`Device::compile_function`]) is fitted + /// under the inputs given there. `pipeline` itself where the device has no bound, it fits, or + /// `d`'s kernel is `Compiled`. + pub fn fit_compute_pipeline( + &self, + d: &ComputePipelineDescriptor, + inputs: &LoweringInputs, + b: &Budget, + pipeline: ComputePipeline, + ) -> Result { + let bound = self.profile().module_word_bound(); + guarded(|| self.fit_compute_within(d, inputs, b, pipeline, bound)) + } + + /// `pipeline`, [`Device::compile_tile_pipeline`]'s compile of `d` (whose tile function may be + /// `Compiled`), its tile function compiled under `inputs`, held to the device's compiler word + /// bound as [`Device::fit_compute_pipeline`] holds a compute pipeline: `inputs` are those the + /// tile function was compiled under (in [`Device::compile_tile_pipeline`], `d`'s color + /// attachment formats, `threadgroupSizeMatchesTileSize` and `maxCallStackDepth`). `pipeline` + /// itself where the device has no bound, it fits, or `d`'s tile function is `Compiled`. + pub fn fit_tile_pipeline( + &self, + d: &TileRenderPipelineDescriptor, + inputs: &LoweringInputs, + b: &Budget, + pipeline: ComputePipeline, + ) -> Result { + let bound = self.profile().module_word_bound(); + guarded(|| self.fit_tile_within(d, inputs, b, pipeline, bound)) + } + + /// [`Device::fit_render_variant`] under `bound` in place of the device's own: a test pins a + /// low bound without a device that carries the workaround. + pub(crate) fn fit_render_within( + &self, + d: &RenderPipelineDescriptor, + v: &VariantKey, + b: &Budget, + pipeline: RenderPipeline, + bound: Option, + ) -> Result { + let translatable = function(&d.vertex) && d.fragment.as_ref().is_none_or(function); + self.held_to(pipeline, bound, translatable, |device| { + device.render_pipeline(d, v, &mut Meter::new(b)) + }) + } + + /// [`Device::fit_mesh_variant`] under `bound` in place of the device's own. + pub(crate) fn fit_mesh_within( + &self, + d: &MeshPipelineDescriptor, + v: &VariantKey, + b: &Budget, + pipeline: RenderPipeline, + bound: Option, + ) -> Result { + let translatable = d.object.as_ref().is_none_or(function) + && function(&d.mesh) + && d.fragment.as_ref().is_none_or(function); + self.held_to(pipeline, bound, translatable, |device| { + device.mesh_pipeline(d, v, &mut Meter::new(b)) + }) + } + + /// [`Device::fit_compute_pipeline`] under `bound` in place of the device's own. + pub(crate) fn fit_compute_within( + &self, + d: &ComputePipelineDescriptor, + inputs: &LoweringInputs, + b: &Budget, + pipeline: ComputePipeline, + bound: Option, + ) -> Result { + self.held_to(pipeline, bound, function(&d.kernel), |device| { + device.compute_pipeline(d, inputs, &mut Meter::new(b)) + }) + } + + /// [`Device::fit_tile_pipeline`] under `bound` in place of the device's own. + pub(crate) fn fit_tile_within( + &self, + d: &TileRenderPipelineDescriptor, + inputs: &LoweringInputs, + b: &Budget, + pipeline: ComputePipeline, + bound: Option, + ) -> Result { + self.held_to(pipeline, bound, function(&d.tile), |device| { + device.tile_pipeline(d, inputs, &mut Meter::new(b)) + }) + } + + /// `pipeline` held to `bound`, every kind by the one rule: where its stages can be translated + /// again (`translatable`) and its largest stage passes `bound`, `again` (the pipeline's compile + /// on a device of a reduced policy) under native sampling, then under every module-growing + /// exact answer native, stopping at the first that fits (the last where none does), with the + /// forms it dropped recorded and `pipeline`'s key and profile fingerprint kept. A step that + /// changes nothing of the policy is skipped. + fn held_to( + &self, + pipeline: P, + bound: Option, + translatable: bool, + again: impl Fn(&Device) -> Result, + ) -> Result { + let Some(bound) = bound.filter(|&w| translatable && pipeline.largest_stage_words() > w) + else { + return Ok(pipeline); + }; + let base = *self.policy(); + let mut best: Option

= None; + for step in [ReducedForms::NativeSampling, ReducedForms::AllNative] { + let policy = step.of(base); + if policy == base { + continue; + } + // The lowering reads the profile, never the policy, and `Device::new` is the profile's + // one producer: the description kept, the policy reduced. + let device = Device::new(self.description().clone(), policy)?; + let mut reduced = again(&device)?; + reduced + .dependencies_mut() + .push(dropped_forms(base, &policy, device.profile())); + let fits = reduced.largest_stage_words() <= bound; + best = Some(reduced); + if fits { + break; + } + } + Ok(match best { + Some(reduced) => reduced.named_as(&pipeline), + None => pipeline, + }) + } +} + +/// Whether a stage can be translated again: a `Function` stage, not one taken `Compiled`. +fn function(source: &StageSource) -> bool { + matches!(source, StageSource::Function(_)) +} + +/// A compiled pipeline the compiler word bound holds: a render pipeline (vertex or mesh) or a +/// compute pipeline (kernel or tile). +trait Fitted: Sized { + /// The word count of its largest stage module: what a device's compiler word bound holds + /// ([`DeviceProfile::module_word_bound`]). A pipeline with no stage counts as 0. + fn largest_stage_words(&self) -> u32; + /// Its runtime dependencies, where the fit records the forms it dropped. + fn dependencies_mut(&mut self) -> &mut Vec; + /// `self`, named as `compiled` is (its key and profile fingerprint), so a cache stores and + /// finds it where it would `compiled`. + fn named_as(self, compiled: &Self) -> Self; +} + +impl Fitted for RenderPipeline { + fn largest_stage_words(&self) -> u32 { + self.stages + .iter() + .map(|s| words(&s.spirv)) + .max() + .unwrap_or(0) + } + + fn dependencies_mut(&mut self) -> &mut Vec { + &mut self.dependencies + } + + fn named_as(self, compiled: &RenderPipeline) -> RenderPipeline { + RenderPipeline { + key: compiled.key, + profile: compiled.profile, + ..self + } + } +} + +impl Fitted for ComputePipeline { + fn largest_stage_words(&self) -> u32 { + words(&self.stage.spirv) + } + + fn dependencies_mut(&mut self) -> &mut Vec { + &mut self.dependencies + } + + fn named_as(self, compiled: &ComputePipeline) -> ComputePipeline { + ComputePipeline { + key: compiled.key, + profile: compiled.profile, + ..self + } + } +} + +/// A module's word count, saturated. +fn words(spirv: &[u32]) -> u32 { + u32::try_from(spirv.len()).unwrap_or(u32::MAX) +} + +/// A step of the compiler-word-bound fallback: the exact forms to drop from the consumer's policy. +/// `NativeSampling` drops exact sampling, the single largest exact form, with Metal's filter of a +/// two-plane YCbCr texture (`YCbCrFilterPolicy::Exact`, reported with it); `AllNative` drops every +/// module-growing exact answer (the fast default's forms). Neither touches the policy's other +/// choices (pointer and handle domains, containment, isolation, framebuffer fetch, the 8-bit +/// filter, or the runtime's choices, which change no module), so a reduced device keeps them. +#[derive(Clone, Copy)] +enum ReducedForms { + NativeSampling, + AllNative, +} + +impl ReducedForms { + /// `base` with this step's exact forms set to their native, module-smaller answers. + fn of(self, base: DevicePolicy) -> DevicePolicy { + let sampled = DevicePolicy { + sampling: SamplingPolicy::NativeDevice, + ycbcr_filter: YCbCrFilterPolicy::Device, + ..base + }; + match self { + ReducedForms::NativeSampling => sampled, + ReducedForms::AllNative => DevicePolicy { + float_maths: FloatMathsPolicy::Native, + texel_conversion: TexelConversionPolicy::Device, + half_rounding: HalfRoundingPolicy::Native, + nan_and_min_max: NanMinMaxPolicy::Native, + rounding_order: RoundingOrderPolicy::Native, + half_blend: HalfBlendPolicy::Device, + ..sampled + }, + } + } +} + +/// Which of the consumer's exact forms the fallback dropped to fit the bound, as the dependency a +/// fitted pipeline records: each field of [`RuntimeFact::ExactFormsOverCompilerLimit`] is set +/// where `base`'s form differs from the reduced `policy`'s. The consumer announces it. +fn dropped_forms( + base: DevicePolicy, + policy: &DevicePolicy, + reduced: &DeviceProfile, +) -> RuntimeDependency { + let fact = RuntimeFact::ExactFormsOverCompilerLimit { + sampling: base.sampling != policy.sampling || base.ycbcr_filter != policy.ycbcr_filter, + float_maths: base.float_maths != policy.float_maths, + texel_conversion: base.texel_conversion != policy.texel_conversion, + half_rounding: base.half_rounding != policy.half_rounding, + nan_and_min_max: base.nan_and_min_max != policy.nan_and_min_max, + rounding_order: base.rounding_order != policy.rounding_order, + half_blend: base.half_blend != policy.half_blend, + }; + RuntimeDependency { + fact, + mechanism: mechanism(&fact, reduced), + } +} diff --git a/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs b/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs new file mode 100644 index 000000000..0a9be2759 --- /dev/null +++ b/crates/metal2vulkan/src/pipeline/compile/fit/tests.rs @@ -0,0 +1,555 @@ +//! Tests of the compiler-word-bound fit, one per pipeline kind (render, mesh, tile, compute): past +//! the bound, the pipeline is its functions' compile on a device of the reduced policy, recording +//! the forms dropped (`RuntimeFact::ExactFormsOverCompilerLimit`) under its own compile's key and +//! profile fingerprint; within the bound, or on a device without one, it is the compile unchanged. +//! A pipeline linked from stages compiled ahead (the runtime's shape) is fitted from its +//! functions' descriptor and left as it is from its `Compiled` stages. The bound is pinned low in +//! code (`Device::fit_*_within`); no device runs, and no driver's compiler is driven. +//! +//! `llvm-as` assembles the owned fixtures; a missing tool skips a test visibly. + +use std::collections::BTreeMap; +use std::path::Path; + +use super::{Fitted, ReducedForms}; +use crate::budget::{Budget, Meter}; +use crate::cache::VariantKey; +use crate::device::policy::SamplingPolicy; +use crate::device::{Device, DeviceDescription, DevicePolicy}; +use crate::library::Library; +use crate::metal; +use crate::pipeline::artifact::{RenderPipeline, RuntimeDependency}; +use crate::pipeline::descriptor::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, FunctionDescriptor, + MeshPipelineDescriptor, RenderPipelineDescriptor, StageSource, TileRenderPipelineDescriptor, +}; +use crate::pipeline::facts::{Mechanism, RuntimeFact}; +use crate::pipeline::lower_inputs::LoweringInputs; +use crate::pipeline::sym::Stage; +use crate::pipeline::testing::{engine_dir, llvm_assemble, AssembleError}; +use crate::vk::ShaderStage; + +/// The owned fixture at `path` as a library, or `None` (skipped visibly) without `llvm-as`. +fn library(path: &Path) -> Option { + match llvm_assemble(path) { + Ok(bc) => Some(Library::from_air(&bc).expect("library")), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {path:?}: {why}"), + } +} + +/// Committed profile `stem` as the Khronos reader describes it. +fn description(stem: &str) -> DeviceDescription { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/profiles") + .join(format!("{stem}.json")); + let text = std::fs::read_to_string(&path).expect("profile"); + DeviceDescription::from_khronos_json(&text, None).expect("description") +} + +/// Every exact form, Metal's sampler emulated among them. +fn exact() -> DevicePolicy { + DevicePolicy { + sampling: SamplingPolicy::Exact, + ..DevicePolicy::default().exact_answers() + } +} + +/// Committed profile `stem` as a device under `policy`. +fn device(stem: &str, policy: DevicePolicy) -> Device { + Device::new(description(stem), policy).expect("device") +} + +/// The forms a fitted pipeline's `dependencies` record it dropped, in the fact's field order; +/// `None` where it records none. +fn dropped(dependencies: &[RuntimeDependency]) -> Option<[bool; 7]> { + dependencies.iter().find_map(|d| match d.fact { + RuntimeFact::ExactFormsOverCompilerLimit { + sampling, + float_maths, + texel_conversion, + half_rounding, + nan_and_min_max, + rounding_order, + half_blend, + } => Some([ + sampling, + float_maths, + texel_conversion, + half_rounding, + nan_and_min_max, + rounding_order, + half_blend, + ]), + _ => None, + }) +} + +/// `reduced`, the compile of the fitted functions on a device of `exact()` with every +/// module-growing form native, as the fit of `compiled` (their compile under `exact()`) past its +/// bound gives it: recording that it dropped every exact form, named as `compiled` is. +fn fitted_as(reduced: P, compiled: &P) -> P { + let fact = RuntimeFact::ExactFormsOverCompilerLimit { + sampling: true, + float_maths: true, + texel_conversion: true, + half_rounding: true, + nan_and_min_max: true, + rounding_order: true, + half_blend: true, + }; + let mut reduced = reduced; + reduced + .dependencies_mut() + .push(RuntimeDependency::new(fact, Mechanism::None)); + reduced.named_as(compiled) +} + +/// A render pipeline whose largest stage module passes a device's compiler word bound is +/// translated again with the device policy's exact forms dropped until it fits: native sampling +/// first, then every exact answer that grows a module native, recording which forms it dropped +/// (`RuntimeFact::ExactFormsOverCompilerLimit`) and keeping the compile's key and profile +/// fingerprint. A pipeline compiled from stages compiled ahead (the runtime's shape) is fitted from +/// its functions' descriptor ([`Device::fit_render_variant`]), and is left as it is from its +/// `Compiled` stages, which cannot be translated again. Uses the owned `runtime_examples` fixture +/// (a sampled `half` fragment), on a generic desktop profile whose sampler is not Metal's own. +#[test] +fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() { + let path = metal2vulkan_devtools::fixtures_dir().join("examples/runtime_examples.ll"); + let Some(lib) = library(&path) else { + return; + }; + let vertex = lib.function("colored_vertex").expect("vertex"); + let fragment = lib.function("sampled_fragment").expect("fragment"); + let descriptor = || { + let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( + vertex.clone(), + ))); + d.fragment = Some(StageSource::Function(FunctionDescriptor::new( + fragment.clone(), + ))); + d.color_attachments[0] = Some(ColorAttachmentDescriptor::new( + metal::PixelFormat::RGBA8Unorm, + )); + d + }; + let v = VariantKey::new(); + let b = Budget::standard(); + let stem = "lunarg-desktop-baseline-2023"; + let words = |policy: DevicePolicy| -> u32 { + let pipe = device(stem, policy) + .compile_render_variant(&descriptor(), &v, &b) + .expect("compile"); + largest(&pipe) + }; + fn largest(pipe: &RenderPipeline) -> u32 { + pipe.largest_stage_words() + } + + let w_exact = words(exact()); + let w_sampling_native = words(DevicePolicy::default().exact_answers()); + let w_fast = words(DevicePolicy::default()); + assert!( + w_fast <= w_sampling_native && w_sampling_native <= w_exact, + "fast {w_fast} <= sampling-native {w_sampling_native} <= exact {w_exact}" + ); + + let dev = device(stem, exact()); + let first = || { + dev.compile_render_variant(&descriptor(), &v, &b) + .expect("compile") + }; + let fit = |bound: u32| { + let first = first(); + let fitted = dev + .fit_render_within(&descriptor(), &v, &b, first.clone(), Some(bound)) + .expect("fit"); + // The fitted pipeline is what the device's compile of the descriptor gives, as a cache + // stores and finds it. + assert_eq!(fitted.key, first.key, "the compile's key kept"); + assert_eq!(fitted.profile, first.profile, "the compile's profile kept"); + fitted + }; + + // A bound below every form drops every exact form the policy carries: the fast default. + let pipe = fit(0); + assert_eq!(largest(&pipe), w_fast, "reduced to the fast default"); + assert_eq!( + dropped(&pipe.dependencies), + Some([true; 7]), + "every exact form dropped" + ); + + // Over the bound by exact sampling alone (where it grows the module): sampling is dropped + // first, and nothing more, because native sampling already fits. + if w_sampling_native < w_exact { + let pipe = fit(w_sampling_native); + assert_eq!(largest(&pipe), w_sampling_native); + assert_eq!( + dropped(&pipe.dependencies), + Some([true, false, false, false, false, false, false]), + "only sampling dropped" + ); + } + + // Within the bound, or on a device without one: no fallback, no fact, the exact forms kept. + for pipe in [ + fit(u32::MAX), + dev.fit_render_within(&descriptor(), &v, &b, first(), None) + .expect("no bound"), + dev.fit_render_variant(&descriptor(), &v, &b, first()) + .expect("the device's own: none"), + ] { + assert_eq!( + dropped(&pipe.dependencies), + None, + "no fallback within the bound" + ); + assert_eq!(largest(&pipe), w_exact); + } + + // The runtime's shape: each stage compiled ahead under the keys' inputs, linked from the + // `Compiled` stages, then fitted from the functions' descriptor. + let keys = dev.render_pipeline_key(&descriptor(), &b).expect("keys"); + let compiled = |source: &StageSource, inputs: &LoweringInputs| match source { + StageSource::Function(f) => { + StageSource::Compiled(dev.compile_function(f, inputs, &b).expect("stage")) + } + StageSource::Compiled(_) => unreachable!("the descriptor's stages are functions"), + }; + let mut linked = descriptor(); + linked.vertex = compiled(&linked.vertex, keys.vertex_inputs.as_ref().expect("inputs")); + linked.fragment = linked + .fragment + .as_ref() + .map(|f| compiled(f, keys.fragment_inputs.as_ref().expect("inputs"))); + let ahead = dev + .compile_render_variant(&linked, &v, &b) + .expect("compiled stages"); + assert_eq!(ahead.key, keys.pipeline); + assert_eq!(largest(&ahead), w_exact); + // From the compiled stages alone nothing can be translated again: left as it is. + let kept = dev + .fit_render_within(&linked, &v, &b, ahead.clone(), Some(0)) + .expect("compiled stages kept"); + assert_eq!(kept, ahead); + // From the functions' descriptor: fitted, under the compiled pipeline's key. + let fitted = dev + .fit_render_within(&descriptor(), &v, &b, ahead, Some(0)) + .expect("fitted from the functions"); + assert_eq!(fitted.key, keys.pipeline); + assert_eq!(largest(&fitted), w_fast); + assert_eq!(dropped(&fitted.dependencies), Some([true; 7])); +} + +/// A mesh render pipeline is fitted as a vertex and fragment pipeline is: past the bound, its +/// object, mesh and fragment functions translated again with every exact form dropped (its +/// largest stage counted among all of them), recording the forms under its compile's key; within +/// the bound, on a device without one, or with a `Compiled` stage, the compile unchanged. Both +/// forms of a mesh pipeline: `TaskEXT` and `MeshEXT` stages on ANV's Arrow Lake profile, whose +/// own bound (400,000 words) the fixture fits, so its compile is the unfitted one; and on a +/// device without `VK_EXT_mesh_shader`, the compute stages and synthesized vertex stage that +/// emulate them. Uses the owned `mesh_draws` fixture. +#[test] +fn a_mesh_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() { + let Some(lib) = library(&engine_dir().join("mesh_draws.ll")) else { + return; + }; + let function = |name: &str| FunctionDescriptor::new(lib.function(name).expect("function")); + let descriptor = || { + let mut d = MeshPipelineDescriptor::new(StageSource::Function(function("mesh_draws_mesh"))); + d.object = Some(StageSource::Function(function("mesh_draws_object"))); + d.fragment = Some(StageSource::Function(function("mesh_draws_fragment"))); + for color in &mut d.color_attachments[..2] { + *color = Some(ColorAttachmentDescriptor::new( + metal::PixelFormat::RGBA32Uint, + )); + } + d + }; + let (v, b) = (VariantKey::new(), Budget::standard()); + for (stem, bound, kinds) in [ + ( + "intel-arl-anv", + Some(400_000), + &[ + ShaderStage::TASK_EXT, + ShaderStage::MESH_EXT, + ShaderStage::FRAGMENT, + ][..], + ), + ( + "lunarg-desktop-baseline-2023", + None, + &[ + ShaderStage::COMPUTE, + ShaderStage::COMPUTE, + ShaderStage::VERTEX, + ShaderStage::FRAGMENT, + ][..], + ), + ] { + let dev = device(stem, exact()); + assert_eq!(dev.profile().module_word_bound(), bound, "{stem}"); + let compiled = dev.compile_mesh_variant(&descriptor(), &v, &b).expect(stem); + let unfitted = dev + .mesh_pipeline(&descriptor(), &v, &mut Meter::new(&b)) + .expect(stem); + assert_eq!(compiled, unfitted, "{stem}: within the device's own bound"); + assert_eq!(dropped(&compiled.dependencies), None, "{stem}"); + let stages: Vec = compiled.stages.iter().map(|s| s.stage).collect(); + assert_eq!(stages, kinds, "{stem}"); + + let fast = device(stem, ReducedForms::AllNative.of(exact())); + let reduced = fast + .mesh_pipeline(&descriptor(), &v, &mut Meter::new(&b)) + .expect(stem); + let w_fast = device(stem, DevicePolicy::default()) + .compile_mesh_variant(&descriptor(), &v, &b) + .expect(stem) + .largest_stage_words(); + assert_eq!( + reduced.largest_stage_words(), + w_fast, + "{stem}: the fast forms" + ); + let w_exact = compiled.largest_stage_words(); + assert!(w_fast < w_exact, "{stem}: fast {w_fast} < exact {w_exact}"); + let fit = |d: &MeshPipelineDescriptor, bound| { + dev.fit_mesh_within(d, &v, &b, compiled.clone(), bound) + .expect(stem) + }; + assert_eq!( + fit(&descriptor(), Some(0)), + fitted_as(reduced, &compiled), + "{stem}: past the bound" + ); + for bound in [Some(u32::MAX), None] { + assert_eq!( + fit(&descriptor(), bound), + compiled, + "{stem}: within {bound:?}" + ); + } + assert_eq!( + dev.fit_mesh_variant(&descriptor(), &v, &b, compiled.clone()) + .expect(stem), + compiled, + "{stem}: the device's own bound" + ); + // A `Compiled` stage cannot be translated again: left as it is, past the bound too. + let object = dev + .compile_function( + &function("mesh_draws_object"), + &v.lowering_inputs(Stage::Object), + &b, + ) + .expect(stem); + let mut ahead = descriptor(); + ahead.object = Some(StageSource::Compiled(object)); + assert_eq!(fit(&ahead, Some(0)), compiled, "{stem}: a compiled stage"); + } +} + +/// A tile render pipeline is fitted as a render pipeline is, its tile function translated again +/// under the inputs it was compiled under: past the bound, every exact form dropped, recorded +/// under the compile's key; within it, or on a device without one, the compile unchanged. In the +/// runtime's shape (the tile function compiled ahead under the descriptor's inputs and linked +/// from the `Compiled` stage) it is fitted from the function's descriptor and left as it is from +/// the `Compiled` one. On ANV's UHD 770 profile, whose own bound the fixture fits, and a device +/// without a bound. Uses the owned `ttg_tile_simd_blur` fixture (`half` arithmetic into an +/// `RGBA16Float` attachment), its threadgroup the tile's size. +#[test] +fn a_tile_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() { + let Some(lib) = library(&engine_dir().join("ttg_tile_simd_blur.ll")) else { + return; + }; + let f = FunctionDescriptor::new(lib.function("ttg_tile_simd_blur").expect("function")); + let format = metal::PixelFormat::RGBA16Float; + let mut d = TileRenderPipelineDescriptor::new(StageSource::Function(f.clone())); + d.color_attachment_formats[0] = Some(format); + d.threadgroup_size_matches_tile_size = true; + // The inputs `compile_tile_pipeline` compiles a `Function` tile function of `d` under. + let inputs = LoweringInputs { + tile_attachments: Some(BTreeMap::from([(0, format)])), + threadgroup_size_matches_tile_size: true, + ..LoweringInputs::new() + }; + let b = Budget::standard(); + for (stem, bound) in [ + ("intel-uhd770-rpls-anv", Some(400_000)), + ("lunarg-desktop-baseline-2023", None), + ] { + let dev = device(stem, exact()); + assert_eq!(dev.profile().module_word_bound(), bound, "{stem}"); + let compiled = dev.compile_tile_pipeline(&d, &b).expect(stem); + let unfitted = dev + .tile_pipeline(&d, &inputs, &mut Meter::new(&b)) + .expect(stem); + assert_eq!(compiled, unfitted, "{stem}: within the device's own bound"); + assert_eq!(dropped(&compiled.dependencies), None, "{stem}"); + + let fast = device(stem, ReducedForms::AllNative.of(exact())); + let reduced = fast + .tile_pipeline(&d, &inputs, &mut Meter::new(&b)) + .expect(stem); + let w_fast = device(stem, DevicePolicy::default()) + .compile_tile_pipeline(&d, &b) + .expect(stem) + .largest_stage_words(); + assert_eq!( + reduced.largest_stage_words(), + w_fast, + "{stem}: the fast forms" + ); + let w_exact = compiled.largest_stage_words(); + assert!(w_fast < w_exact, "{stem}: fast {w_fast} < exact {w_exact}"); + let expected = fitted_as(reduced, &compiled); + let fit = |d: &TileRenderPipelineDescriptor, pipeline, bound| { + dev.fit_tile_within(d, &inputs, &b, pipeline, bound) + .expect(stem) + }; + assert_eq!( + fit(&d, compiled.clone(), Some(0)), + expected, + "{stem}: past the bound" + ); + for bound in [Some(u32::MAX), None] { + assert_eq!(fit(&d, compiled.clone(), bound), compiled, "{stem}: within"); + } + + // The runtime's shape. + let function = dev.compile_function(&f, &inputs, &b).expect(stem); + let mut linked = d.clone(); + linked.tile = StageSource::Compiled(function); + let ahead = dev.compile_tile_pipeline(&linked, &b).expect(stem); + assert_eq!(ahead, compiled, "{stem}: linked from the compiled function"); + assert_eq!( + dev.fit_tile_pipeline(&d, &inputs, &b, ahead.clone()) + .expect(stem), + compiled, + "{stem}: the device's own bound" + ); + assert_eq!( + fit(&linked, ahead.clone(), Some(0)), + compiled, + "{stem}: a compiled stage" + ); + assert_eq!( + fit(&d, ahead, Some(0)), + expected, + "{stem}: fitted from the function" + ); + } +} + +/// A compute pipeline is fitted as a render pipeline is, its kernel translated again under the +/// inputs it was compiled under, and one within the bound translates exactly as before the fit: +/// on ANV's UHD 770 profile, whose own bound the kernel fits, and on a device without a bound, +/// under every exact form and under the fast default, `compile_compute_pipeline` is the unfitted +/// compile, word for word. Past the bound every exact form is dropped; past it by exact sampling +/// alone, sampling alone. In the runtime's shape (the kernel compiled ahead and linked from the +/// `Compiled` stage) it is fitted from the function's descriptor and left as it is from the +/// `Compiled` one. Uses the owned `a2_kernel_lod_filter` fixture, a kernel that samples. +#[test] +fn a_compute_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() { + let Some(lib) = library(&engine_dir().join("a2_kernel_lod_filter.ll")) else { + return; + }; + let f = FunctionDescriptor::new(lib.function("a2_kernel_lod_filter").expect("function")); + let d = ComputePipelineDescriptor::new(StageSource::Function(f.clone())); + // The inputs `compile_compute_pipeline` compiles a `Function` kernel of `d` under. + let inputs = LoweringInputs::new(); + let b = Budget::standard(); + for (stem, bound) in [ + ("intel-uhd770-rpls-anv", Some(400_000)), + ("lunarg-desktop-baseline-2023", None), + ] { + let unfitted = |dev: &Device| { + dev.compute_pipeline(&d, &inputs, &mut Meter::new(&b)) + .expect(stem) + }; + for policy in [exact(), DevicePolicy::default()] { + let dev = device(stem, policy); + assert_eq!(dev.profile().module_word_bound(), bound, "{stem}"); + let compiled = dev.compile_compute_pipeline(&d, &b).expect(stem); + assert_eq!( + compiled, + unfitted(&dev), + "{stem}: within the device's own bound, as before the fit" + ); + assert_eq!(dropped(&compiled.dependencies), None, "{stem}"); + } + + let dev = device(stem, exact()); + let compiled = dev.compile_compute_pipeline(&d, &b).expect(stem); + let w_exact = compiled.largest_stage_words(); + let sampled = unfitted(&device(stem, ReducedForms::NativeSampling.of(exact()))); + let w_sampling_native = sampled.largest_stage_words(); + let reduced = unfitted(&device(stem, ReducedForms::AllNative.of(exact()))); + let w_fast = device(stem, DevicePolicy::default()) + .compile_compute_pipeline(&d, &b) + .expect(stem) + .largest_stage_words(); + assert_eq!( + reduced.largest_stage_words(), + w_fast, + "{stem}: the fast forms" + ); + assert!( + w_fast <= w_sampling_native && w_sampling_native < w_exact, + "{stem}: fast {w_fast} <= sampling-native {w_sampling_native} < exact {w_exact}" + ); + let expected = fitted_as(reduced, &compiled); + let fit = |d: &ComputePipelineDescriptor, pipeline, bound| { + dev.fit_compute_within(d, &inputs, &b, pipeline, bound) + .expect(stem) + }; + assert_eq!( + fit(&d, compiled.clone(), Some(0)), + expected, + "{stem}: past the bound" + ); + // Over the bound by exact sampling alone: sampling alone dropped. + let pipe = fit(&d, compiled.clone(), Some(w_sampling_native)); + assert_eq!(pipe.stage, sampled.stage, "{stem}: native sampling"); + assert_eq!( + dropped(&pipe.dependencies), + Some([true, false, false, false, false, false, false]), + "{stem}: only sampling dropped" + ); + assert_eq!( + (pipe.key, pipe.profile), + (compiled.key, compiled.profile), + "{stem}" + ); + for bound in [Some(w_exact), Some(u32::MAX), None] { + assert_eq!(fit(&d, compiled.clone(), bound), compiled, "{stem}: within"); + } + + // The runtime's shape. + let function = dev.compile_function(&f, &inputs, &b).expect(stem); + let linked = ComputePipelineDescriptor::new(StageSource::Compiled(function)); + let ahead = dev.compile_compute_pipeline(&linked, &b).expect(stem); + assert_eq!(ahead, compiled, "{stem}: linked from the compiled function"); + assert_eq!( + dev.fit_compute_pipeline(&d, &inputs, &b, ahead.clone()) + .expect(stem), + compiled, + "{stem}: the device's own bound" + ); + assert_eq!( + fit(&linked, ahead.clone(), Some(0)), + compiled, + "{stem}: a compiled stage" + ); + assert_eq!( + fit(&d, ahead, Some(0)), + expected, + "{stem}: fitted from the function" + ); + } +} diff --git a/crates/metal2vulkan/src/pipeline/compile/tests.rs b/crates/metal2vulkan/src/pipeline/compile/tests.rs index 4868efd59..a425aad82 100644 --- a/crates/metal2vulkan/src/pipeline/compile/tests.rs +++ b/crates/metal2vulkan/src/pipeline/compile/tests.rs @@ -346,12 +346,14 @@ fn a_compiled_stage_links_without_decoding() { assert_eq!(compiled.artifact().profile, dev.profile().fingerprint()); let mut m = Meter::new(&Budget::default()); - let from_function = dev.compute_pipeline(&kernel(f), &mut m).expect("function"); + let from_function = dev + .compute_pipeline(&kernel(f), &inp, &mut m) + .expect("function"); assert!(m.work() > 0, "the function path decodes and lowers"); let d = ComputePipelineDescriptor::new(StageSource::Compiled(compiled.clone())); let mut m = Meter::new(&Budget::default()); - let from_compiled = dev.compute_pipeline(&d, &mut m).expect("compiled"); + let from_compiled = dev.compute_pipeline(&d, &inp, &mut m).expect("compiled"); assert_eq!( (m.work(), m.ledger_peak()), (0, 0), @@ -2996,173 +2998,3 @@ fn a_fragment_reads_the_viewport_index_its_vertex_function_wrote() { ); } } - -/// A render pipeline whose largest stage module passes a device's compiler word bound is -/// translated again with the device policy's exact forms dropped until it fits: native sampling -/// first, then every exact answer that grows a module native, recording which forms it dropped -/// (`RuntimeFact::ExactFormsOverCompilerLimit`) and keeping the compile's key and profile -/// fingerprint. A pipeline compiled from stages compiled ahead (the runtime's shape) is fitted from -/// its functions' descriptor ([`Device::fit_render_variant`]), and is left as it is from its -/// `Compiled` stages, which cannot be translated again. The bound is pinned low in code -/// (`Device::fit_within`); no device identity is needed. Uses the owned `runtime_examples` fixture -/// (a sampled `half` fragment), on a generic desktop profile whose sampler is not Metal's own. -#[test] -fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() { - use crate::device::policy::SamplingPolicy; - use crate::pipeline::artifact::RenderPipeline; - use crate::pipeline::facts::RuntimeFact; - let path = metal2vulkan_devtools::fixtures_dir().join("examples/runtime_examples.ll"); - let bc = match llvm_assemble(&path) { - Ok(b) => b, - Err(AssembleError::Missing(why)) => { - eprintln!("SKIPPED: {why}"); - return; - } - Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected runtime_examples: {why}"), - }; - let lib = Library::from_air(&bc).expect("library"); - let vertex = lib.function("colored_vertex").expect("vertex"); - let fragment = lib.function("sampled_fragment").expect("fragment"); - let descriptor = || { - let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( - vertex.clone(), - ))); - d.fragment = Some(StageSource::Function(FunctionDescriptor::new( - fragment.clone(), - ))); - d.color_attachments[0] = Some(ColorAttachmentDescriptor::new( - metal::PixelFormat::RGBA8Unorm, - )); - d - }; - let v = crate::cache::VariantKey::new(); - let b = Budget::standard(); - let stem = "lunarg-desktop-baseline-2023"; - let words = |policy: DevicePolicy| -> u32 { - let dev = Device::new(description(stem), policy).expect("device"); - let pipe = dev - .compile_render_variant(&descriptor(), &v, &b) - .expect("compile"); - largest(&pipe) - }; - fn largest(pipe: &RenderPipeline) -> u32 { - pipe.stages - .iter() - .map(|s| u32::try_from(s.spirv.len()).unwrap()) - .max() - .unwrap() - } - fn dropped(pipe: &RenderPipeline) -> Option<[bool; 7]> { - pipe.dependencies.iter().find_map(|d| match d.fact { - RuntimeFact::ExactFormsOverCompilerLimit { - sampling, - float_maths, - texel_conversion, - half_rounding, - nan_and_min_max, - rounding_order, - half_blend, - } => Some([ - sampling, - float_maths, - texel_conversion, - half_rounding, - nan_and_min_max, - rounding_order, - half_blend, - ]), - _ => None, - }) - } - - let exact = DevicePolicy { - sampling: SamplingPolicy::Exact, - ..DevicePolicy::default().exact_answers() - }; - let w_exact = words(exact); - let w_sampling_native = words(DevicePolicy::default().exact_answers()); - let w_fast = words(DevicePolicy::default()); - assert!( - w_fast <= w_sampling_native && w_sampling_native <= w_exact, - "fast {w_fast} <= sampling-native {w_sampling_native} <= exact {w_exact}" - ); - - let dev = Device::new(description(stem), exact).expect("device"); - let first = || { - dev.compile_render_variant(&descriptor(), &v, &b) - .expect("compile") - }; - let fit = |bound: u32| { - let first = first(); - let fitted = dev - .fit_within(&descriptor(), &v, &b, first.clone(), Some(bound)) - .expect("fit"); - // The fitted pipeline is what the device's compile of the descriptor gives, as a cache - // stores and finds it. - assert_eq!(fitted.key, first.key, "the compile's key kept"); - assert_eq!(fitted.profile, first.profile, "the compile's profile kept"); - fitted - }; - - // A bound below every form drops every exact form the policy carries: the fast default. - let pipe = fit(0); - assert_eq!(largest(&pipe), w_fast, "reduced to the fast default"); - assert_eq!(dropped(&pipe), Some([true; 7]), "every exact form dropped"); - - // Over the bound by exact sampling alone (where it grows the module): sampling is dropped - // first, and nothing more, because native sampling already fits. - if w_sampling_native < w_exact { - let pipe = fit(w_sampling_native); - assert_eq!(largest(&pipe), w_sampling_native); - assert_eq!( - dropped(&pipe), - Some([true, false, false, false, false, false, false]), - "only sampling dropped" - ); - } - - // Within the bound, or on a device without one: no fallback, no fact, the exact forms kept. - for pipe in [ - fit(u32::MAX), - dev.fit_within(&descriptor(), &v, &b, first(), None) - .expect("no bound"), - dev.fit_render_variant(&descriptor(), &v, &b, first()) - .expect("the device's own: none"), - ] { - assert_eq!(dropped(&pipe), None, "no fallback within the bound"); - assert_eq!(largest(&pipe), w_exact); - } - - // The runtime's shape: each stage compiled ahead under the keys' inputs, linked from the - // `Compiled` stages, then fitted from the functions' descriptor. - let keys = dev.render_pipeline_key(&descriptor(), &b).expect("keys"); - let compiled = |source: &StageSource, inputs: &LoweringInputs| match source { - StageSource::Function(f) => { - StageSource::Compiled(dev.compile_function(f, inputs, &b).expect("stage")) - } - StageSource::Compiled(_) => unreachable!("the descriptor's stages are functions"), - }; - let mut linked = descriptor(); - linked.vertex = compiled(&linked.vertex, keys.vertex_inputs.as_ref().expect("inputs")); - linked.fragment = linked - .fragment - .as_ref() - .map(|f| compiled(f, keys.fragment_inputs.as_ref().expect("inputs"))); - let ahead = dev - .compile_render_variant(&linked, &v, &b) - .expect("compiled stages"); - assert_eq!(ahead.key, keys.pipeline); - assert_eq!(largest(&ahead), w_exact); - // From the compiled stages alone nothing can be translated again: left as it is. - let kept = dev - .fit_within(&linked, &v, &b, ahead.clone(), Some(0)) - .expect("compiled stages kept"); - assert_eq!(kept, ahead); - // From the functions' descriptor: fitted, under the compiled pipeline's key. - let fitted = dev - .fit_within(&descriptor(), &v, &b, ahead, Some(0)) - .expect("fitted from the functions"); - assert_eq!(fitted.key, keys.pipeline); - assert_eq!(largest(&fitted), w_fast); - assert_eq!(dropped(&fitted), Some([true; 7])); -} diff --git a/crates/metal2vulkan/src/pipeline/facts.rs b/crates/metal2vulkan/src/pipeline/facts.rs index 528b03800..a98a3b781 100644 --- a/crates/metal2vulkan/src/pipeline/facts.rs +++ b/crates/metal2vulkan/src/pipeline/facts.rs @@ -763,9 +763,9 @@ pub enum RuntimeFact { static_bytes: u32, payload: Option, }, - /// The render pipeline was retranslated with some of the consumer's exact forms dropped to - /// native, because its largest stage module exceeded the device's compiler word bound and that - /// driver faults compiling a module past it + /// The pipeline (render, mesh render, compute or tile render) was retranslated with some of the + /// consumer's exact forms dropped to native, because its largest stage module exceeded the + /// device's compiler word bound and that driver faults compiling a module past it /// ([`DriverWorkaround::RegisterAllocatorOverflowsLargeModules`](crate::device::DriverWorkaround::RegisterAllocatorOverflowsLargeModules): /// ANV's register allocator). Each `true` field is an exact form the pipeline would carry under /// the consumer's policy that the fitting translation gave up to fit the bound (`sampling` diff --git a/docs/API.md b/docs/API.md index a74d4481e..9db4bf6b4 100644 --- a/docs/API.md +++ b/docs/API.md @@ -786,13 +786,17 @@ assert_eq!(linked, pipeline); `compile_function_with_report` also returns a `CompileReport` of what the compile cost. - A render pipeline's stages compile under inputs that a decode of its functions learns. `render_pipeline_key` returns `RenderPipelineKeys`: each stage's function key, and the inputs to - compile a missing stage under. `compile_render_variant` holds a pipeline of `Function` stages to - the device's compiler word bound (`DeviceProfile::module_word_bound`, ANV's) itself; one linked - from `Compiled` stages it cannot translate again. A caller who compiles stages ahead must pass - the linked pipeline, with the descriptor of its functions, to `device.fit_render_variant( - &descriptor, &variant, &budget, pipeline)`, or its module goes to the driver unreduced: the call - translates the functions again with the policy's exact forms dropped where the largest stage - passes the bound (`exact-forms-over-compiler-limit`), under the same key. + compile a missing stage under. Each pipeline kind's compile (`compile_render_variant`, + `compile_mesh_variant`, `compile_compute_pipeline`, `compile_tile_pipeline`) holds a pipeline of + `Function` stages to the device's compiler word bound (`DeviceProfile::module_word_bound`, + ANV's) itself; one linked from `Compiled` stages it cannot translate again. A caller who + compiles stages ahead must pass the linked pipeline, with the descriptor of its functions, to + the kind's fit, or its module goes to the driver unreduced: `device.fit_render_variant( + &descriptor, &variant, &budget, pipeline)`, `fit_mesh_variant` likewise, and + `fit_compute_pipeline(&descriptor, &inputs, &budget, pipeline)` or `fit_tile_pipeline` with the + `LoweringInputs` the kernel or tile function was compiled under. The call translates the + functions again with the policy's exact forms dropped where the largest stage passes the bound + (`exact-forms-over-compiler-limit`), under the same key. - A key names an artifact by its inputs and versions; a content digest names it by what it says. `pipeline.content_digest()` hashes everything but the key and profile, and `plan.content_digest()` (with `serde`) everything a plan states. A cache of driver objects keyed on the digest survives a @@ -1131,13 +1135,14 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. its topology class between the vertex and fragment stages, which emits each primitive's vertices with the barycentric weights or the first vertex's slice and viewport. - `metal2vulkan-degrade-exact-forms-over-compiler-limit` (precision). `ExactFormsOverCompilerLimit`: - A render pipeline state whose largest stage module, under the consumer's exact forms, exceeded the - device's compiler word bound (`RuntimeFact::ExactFormsOverCompilerLimit`; + A pipeline state (render, mesh render, tile render or compute) whose largest stage module, under + the consumer's exact forms, exceeded the device's compiler word bound + (`RuntimeFact::ExactFormsOverCompilerLimit`; `DriverWorkaround::RegisterAllocatorOverflowsLargeModules`, ANV's register allocator faults compiling a module past it), so the translation dropped those forms until it fit: native sampling - first, then every module-growing exact answer native. Announced where the runtime makes a render - variant whose pipeline the fit reduced, the base variant or another, naming the forms dropped; the - reduced stages announce their own precision notes besides. + first, then every module-growing exact answer native. Announced where the runtime makes a variant + whose pipeline the fit reduced, the base variant or another, naming the state's kind and the + forms dropped; the reduced stages announce their own precision notes besides. Cost: the dropped exact forms' results can differ from Metal's as their notes' documentation states, where the device's compiler would fault on the exact module. - `metal2vulkan-degrade-landed-visibility-results` (performance). `LandedVisibilityResults`: diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 08aab50ad..f9cd0348c 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -79,6 +79,7 @@ known. The rest of the differences are docs/API.md section 9's precision notes. | On MoltenVK a light queue's command buffer waits for the latest one another queue committed, where Metal waits for none: MoltenVK fences every encoder of every queue device-wide when argument buffers and a residency set are on. | The runtime needs argument buffers, and MoltenVK has no setting for its residency set; `runtime_lane::queue_storms` judges the runtime against Metal under those fences. | None (timing only) | | A `Counting` visibility result of a draw writing more than one color attachment, on ANV (Mesa 26.2.4): Metal's count multiplied by the colors written, not divided back. `Boolean` results stay exact. | The driver counts each sample once per color output (`RuntimeDriverDefect::OcclusionCountPerColorOutput`), no documented Vulkan form counts it once, and a refusal would withhold the Mac2 and Metal3 families. | `VisibilityCountPerColor` (`visibility-count-per-color`) | | On MoltenVK a no-copy buffer or heap released with no keep-alive while batches are in flight runs its deallocator once the batches submitted before its release completed, and the program's own submissions through `CommandQueue::with_vk_queue` before it, where Metal runs it at the release. | MoltenVK 1.4.1 fails pending work that reads device addresses where memory a device-address buffer lay in is freed (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`), so freed memory waits for the batches in flight (`WorkCounts::freed_memory_parked`). | `HostDeallocatorDelayed` (`host-deallocator-delayed`) | +| On ANV (Mesa 26.2.4) a pipeline whose largest stage module, under the consumer's exact forms, passes 400,000 words is retranslated with those forms dropped until it fits: native sampling first, then every module-growing exact answer native. Every kind is fitted: render (vertex and fragment), mesh render (object, mesh and fragment, or the stages that emulate them), compute and tile render; the notice names the state's kind. On a large enough module the driver's register allocator reads past its interference bitset and the process faults at pipeline creation. | ANV's `brw` register allocator faults on such modules (`DriverWorkaround::RegisterAllocatorOverflowsLargeModules`), no documented Vulkan form bounds a module's register pressure, and a refusal would withhold the consumer's large shaders. | `ExactFormsOverCompilerLimit` (`exact-forms-over-compiler-limit`) | ## Accuracy switches whose default is Metal's