diff --git a/crates/metal2vulkan-runtime/examples/dispatch_chain.rs b/crates/metal2vulkan-runtime/examples/dispatch_chain.rs index 693864db5..6334e59be 100644 --- a/crates/metal2vulkan-runtime/examples/dispatch_chain.rs +++ b/crates/metal2vulkan-runtime/examples/dispatch_chain.rs @@ -8,7 +8,7 @@ //! [--binds 1|4|tex|tex-moved|ptr|params|params-off] [--host C] [--pages] [--heap] [--heap-churn K] \ //! [--heap-kept H] [--live L] [--idle MS] [--vary] [--ragged] [--samplers K] [--classes K] \ //! [--zero-classes Z] [--stay Q] [--states K] [--back-to-back] [--encoding-threads E] \ -//! [--settle MS] +//! [--queue-each] [--spawned] [--settle MS] //! ``` //! //! Each run is one command buffer of `N` dispatches (200 by default) of `G` threadgroups of `T` @@ -177,7 +177,10 @@ //! `--encoding-threads E` runs `E` threads at once, started together each run, each making its own //! `C` command buffers on the one queue, as a guest's queue is walked on threads of its own: a //! `HOST /thread-` line for each thread, its calls per its own dispatch, and the lines -//! after it over every thread's dispatches. `HOST-COMMIT` splits the commit call by the device's +//! after it over every thread's dispatches. `--queue-each` gives each encoding thread a queue of +//! its own, as a program whose threads each encode on their own queue does. `--spawned` runs one +//! encoding thread as the several run, a thread of its own started each run, rather than on the +//! calling thread. `HOST-COMMIT` splits the commit call by the device's //! commit phases (`WorkCounts::commit_lowering_nanos` and kin). `HOST-THREADS` is each group of the //! process's threads' CPU time per dispatch over the counted runs, waits included, by the thread's //! name (Linux only, from `/proc/self/task/*/schedstat`): `committer` is the calling thread (the @@ -563,6 +566,11 @@ struct Shape { /// The threads that each encode a run's command buffers on the one queue at once /// (`--encoding-threads`). encoding_threads: u32, + /// Whether each encoding thread encodes on a queue of its own (`--queue-each`). + queue_each: bool, + /// Whether one encoding thread is started each run, as several are, rather than the calling + /// thread encoding (`--spawned`). + spawned: bool, } /// The dispatches of `--ragged`'s cycle of thread counts. @@ -603,16 +611,28 @@ impl Shape { states: 1, back_to_back: false, encoding_threads: 1, + queue_each: false, + spawned: false, }; let mut args = std::env::args().skip(1); while let Some(flag) = args.next() { - let flags = ["--pages", "--heap", "--vary", "--ragged", "--back-to-back"]; + let flags = [ + "--pages", + "--heap", + "--vary", + "--ragged", + "--back-to-back", + "--queue-each", + "--spawned", + ]; if flags.contains(&flag.as_str()) { shape.pages |= flag == "--pages"; shape.heap |= flag == "--heap"; shape.vary |= flag == "--vary"; shape.ragged |= flag == "--ragged"; shape.back_to_back |= flag == "--back-to-back"; + shape.queue_each |= flag == "--queue-each"; + shape.spawned |= flag == "--spawned"; continue; } let value = args.next().ok_or(format!("{flag} takes a value"))?; @@ -687,6 +707,12 @@ impl Shape { if shape.encoding_threads == 0 || (shape.encoding_threads > 1 && shape.host.is_none()) { return Err("--encoding-threads takes 1 or more, and more than 1 takes --host".into()); } + if shape.queue_each && shape.encoding_threads < 2 { + return Err("--queue-each takes --encoding-threads 2 or more".into()); + } + if shape.spawned && shape.host.is_none() { + return Err("--spawned takes --host".into()); + } if shape.back_to_back && (shape.host.is_none() || shape.churn.is_some()) { return Err("--back-to-back takes --host and no --heap-churn".into()); } @@ -1604,24 +1630,26 @@ impl Ours<'_> { Ok(()) } - /// [`run_host`](Self::run_host) on each of `hosts.len()` threads at once, all on `queue`, each - /// counted in its own sample: on the calling thread where there is one. + /// [`run_host`](Self::run_host) on each of `hosts.len()` threads at once, thread `t` on + /// `queues[t % queues.len()]`, each counted in its own sample: on the calling thread where + /// there is one. fn run_host_threads( &self, - queue: &CommandQueue, + queues: &[CommandQueue], name: &str, shape: &Shape, command_buffers: u32, hosts: &mut [HostSample], ) -> Result<()> { - if let [host] = hosts { - return self.run_host(queue, name, shape, command_buffers, host); + if let ([host], false) = (&mut *hosts, shape.spawned) { + return self.run_host(&queues[0], name, shape, command_buffers, host); } let start = std::sync::Barrier::new(hosts.len()); let ran: Vec> = std::thread::scope(|scope| { let running: std::io::Result> = (hosts.iter_mut().enumerate()) .map(|(thread, host)| { let start = &start; + let queue = &queues[thread % queues.len()]; std::thread::Builder::new() .name(format!("encoding-{thread}")) .spawn_scoped(scope, move || { @@ -1661,15 +1689,18 @@ impl Ours<'_> { /// Clear the words, run the host's time of `shape` as `name` holds it, and check the words. fn host_shape(&self, name: &str, shape: &Shape, command_buffers: u32) -> Result<()> { self.fill(0)?; - let queue = self.device.new_command_queue()?; let encoding = shape.encoding_threads as usize; + let made = (0..if shape.queue_each { encoding } else { 1 }) + .map(|_| self.device.new_command_queue()) + .collect::, _>>(); + let queues = made?; let mut first: Vec = (0..encoding).map(|_| HostSample::default()).collect(); - self.run_host_threads(&queue, name, shape, command_buffers, &mut first)?; + self.run_host_threads(&queues, name, shape, command_buffers, &mut first)?; let mut hosts: Vec = (0..encoding).map(|_| HostSample::default()).collect(); let (before, threads) = (self.device.work_counts(), cpu_by_group()); let began = Instant::now(); for _ in 0..shape.runs { - self.run_host_threads(&queue, name, shape, command_buffers, &mut hosts)?; + self.run_host_threads(&queues, name, shape, command_buffers, &mut hosts)?; } let wall = began.elapsed(); let (after, threads_after) = (self.device.work_counts(), cpu_by_group()); diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 4927ffc56..18c228c98 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -111,6 +111,7 @@ use metal2vulkan::error::{BindError, RuntimeDriverDefect}; use metal2vulkan::metal::{BarrierScope, DispatchType, RenderStages, ResourceUsage}; use metal2vulkan::pipeline::Stage; use std::borrow::Cow; +use std::cell::Cell; use std::collections::BTreeMap; use std::ops::Range; use std::sync::atomic::AtomicU64; @@ -2968,12 +2969,11 @@ fn record( // upload (16-aligned, as the variant reads it): the grid in threads is the call's, so nothing // on the device writes it. if let Some(bytes) = commands.region_record { - let device = core.device().clone(); let record = { let mut state = core.command_buffer().state(); state .uploads - .upload_aligned(&device, &bytes, bytes.len() as u64, 16)? + .upload_aligned(core.device(), &bytes, bytes.len() as u64, 16)? }; let Some(address) = record.device_address() else { return Err(internal( @@ -3060,7 +3060,8 @@ fn record( core.counts().dispatch_skipped_inert(); return Ok(true); } - let device = core.device().clone(); + // The device through the command buffer's handle, borrowed at each use (`core.device()`): no + // handle of its own, whose count every encoding thread's handles share. // Inside a block of command predication, each command runs from its gate: the flat path's // preprocess (whose command then stays zero), else each region's dispatch. Their group // counts are listed only for a unit that gates them. @@ -3079,7 +3080,7 @@ fn record( .map(|region| region.group_count) .collect(), }; - predication.gates(uploads, &device, &counts)? + predication.gates(uploads, core.device(), &counts)? } false => (None, Vec::new()), } @@ -3098,7 +3099,7 @@ fn record( let mut state = core.command_buffer().state(); binding::bind( call, - &device, + core.device(), &mut state, plan, &command, @@ -3129,12 +3130,12 @@ fn record( let kept_made = kept .and_then(|kept| kept.made.get()) .or_else(|| planned.made_for(commands)) - .filter(|_| !apart_samplers(&device, objects)); + .filter(|_| !apart_samplers(core.device(), objects)); // Inside a predicated loop's laying, it waits for them too, so the laying, which its check // may submit again (`command_buffer/rerun.rs`), is not split for it; but where its variant // records in one of its own. let laying = core.command_buffer().state().predication_mut().laying(); - let waits = laying && !apart_samplers(&device, objects); + let waits = laying && !apart_samplers(core.device(), objects); let (pipelines, pending) = match (own.filter(|_| !waits), kept_made) { (Some(_), Some(made)) => { if let Some(kept) = kept.filter(|kept| kept.made.get().is_none()) { @@ -3164,7 +3165,7 @@ fn record( pipeline.record_dispatch(direct, state); } match made { - Some(made) if !apart_samplers(&device, objects) => { + Some(made) if !apart_samplers(core.device(), objects) => { // Kept with the entry, which the next dispatch of its inputs takes, and with // what it planned, which the next dispatch of its shape takes. if let Some(kept) = kept { @@ -3181,7 +3182,7 @@ fn record( (Cow::Owned(made), None) } Some(_) => { - device + core.device() .shared() .counts .thread() @@ -3214,18 +3215,20 @@ fn record( }; // The shadowed textures the dispatch binds, at the first draw or dispatch of each, its // shadow made now (`shadow_log.rs`). - crate::shadow_log::dispatched(&device, variant.pipeline(), tables.table); + crate::shadow_log::dispatched(core.device(), variant.pipeline(), tables.table); // The resident textures' shadows as the encoder keeps them (`compute/live.rs`). let textures = tables.table.textures.values(); let shadows = match resident_shadows { - Some(kept) => shadow::shadow_uses_of(textures, kept.of(&device, tables.residency), uses), + Some(kept) => { + shadow::shadow_uses_of(textures, kept.of(core.device(), tables.residency), uses) + } None => shadow::shadow_uses(textures.chain(tables.residency.textures()), uses), }; let copies = core.plan_shadows(&shadows, uses)?; let heap_set = match heap { Some(_) => Some( heap_sets::bind( - &device, + core.device(), objects, &mut core.command_buffer().state().heaps, heap_writes, @@ -3250,7 +3253,7 @@ fn record( // here, what its push carries (`binding::PushedSetZero`). let pushes = !pushed.is_empty(); if pushes && pending.is_some() { - (device.shared().counts.thread()).dispatch_pushing_set_zero(pushed.len() as u64); + (core.device().shared().counts.thread()).dispatch_pushing_set_zero(pushed.len() as u64); } let recording = Recording { layout: objects.layout(), @@ -3264,7 +3267,7 @@ fn record( }; let stages = vk::PipelineStageFlags2::COMPUTE_SHADER; let regions = &commands.regions; - (device.shared().counts.thread()).dispatch_tracked(uses.len() as u64); + (core.device().shared().counts.thread()).dispatch_tracked(uses.len() as u64); match pending { Some((dispatch, begun, next)) => { // Tracked here, as a command recorded here is; its execution recorded here, its @@ -3297,19 +3300,20 @@ fn record( } None => { let made = &*pipelines; - let shared = device.shared(); - let stale = shared.pushes_after_pipeline_binds; + let stale = core.device().shared().pushes_after_pipeline_binds; let resident = uses.resident(); + let carried = Cell::new(0); core.command_reaching_pushed(stages, uses, resident, |raw, command_buffer, held| { // SAFETY: the encoder's command buffer is recording outside a render pass; // every object recorded is live until the command buffer completes (retained // below), the pipelines are the variant's, one per region, and `held` is what // its compute bind point holds (`EncoderCore::command_reaching_pushed`). - let carried = unsafe { recording.record(raw, command_buffer, made, (held, stale)) }; - if pushes { - (shared.counts.thread()).dispatch_pushing_set_zero(carried); - } + let pushed = unsafe { recording.record(raw, command_buffer, made, (held, stale)) }; + carried.set(carried.get() + pushed); }); + if pushes { + (core.device().shared().counts.thread()).dispatch_pushing_set_zero(carried.get()); + } core.shadows_used(&shadows, uses, &[]); core.executed(|| { Execution::new( @@ -3330,7 +3334,7 @@ fn record( .iter() .all(|earlier| earlier.specialization != region.specialization) { - device.degrade_bound_values( + core.device().degrade_bound_values( std::slice::from_ref(&variant.pipeline().stage), ®ion.specialization, &|k| plan.specialized_value(k), @@ -3338,8 +3342,10 @@ fn record( ); } } - device.degrade_cross_class(&plan.diagnostics, formats); - device.degrade_astc_storage(&plan.diagnostics, formats); + core.device() + .degrade_cross_class(&plan.diagnostics, formats); + core.device() + .degrade_astc_storage(&plan.diagnostics, formats); objects.announce_bound( ( std::slice::from_ref(&variant.pipeline().stage), @@ -3370,20 +3376,20 @@ fn record( } let emulated = variant.emulates_simdgroups(); let split = (regions.len(), variant.runs_partial_threadgroups()); - degrade_dispatch(&device, kernel, &dispatch, split, emulated); + degrade_dispatch(core.device(), kernel, &dispatch, split, emulated); // A large kernel's whole grid on its partial-threadgroups variant ([`partial_direct`]). if variant.runs_partial_threadgroups() && whole_grid(&dispatch) { core.counts().whole_dispatch_on_partial_variant(); } if let Some(unlisted) = unlisted { heap_sets::degrade_unlisted( - &device, + core.device(), unlisted, &format!("kernel `{kernel}`'s dispatches"), ); // It runs with the states its sampler arrays hold. let mut held = core.command_buffer().state(); - held.unlisted_argument_sampler(&device); + held.unlisted_argument_sampler(core.device()); } Ok(true) } diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 838113568..2bf352172 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -2733,6 +2733,12 @@ impl EncoderCore { shadows: &[ShadowUse], uses: &[Use], ) -> Result, Error> { + // A command that uses no shadowed texture, of an encoder that used none yet, takes no + // copy and changes nothing (`ShadowSync::is_empty`): every dispatch of a program that + // shadows nothing, which then touches none of the device's shared state here. + if shadows.is_empty() && self.shadows.is_empty() { + return Ok(Vec::new()); + } // What a copy records beyond what the texture holds from its making: a converted // two-plane YCbCr texture's conversion, made at its first use of its image; a 4:2:2 // texture's set over its buffer's `VkBuffer` now, held until the command buffer completes; @@ -2744,7 +2750,10 @@ impl EncoderCore { self.retain_shared(held); } } - let device = self.device().clone(); + // The device through the command buffer's handle, borrowed apart from the shadows and + // leases the merges take: no handle of its own, whose count every encoding thread's + // handles share. + let device = self.open.command_buffer.device(); // The uses with their host memory's, where the shadows read them at all. let aliased = match self.shadows.reads_uses(shadows) { true => self.aliased(uses), @@ -2763,7 +2772,7 @@ impl EncoderCore { .shadows .before(shadows, uses, |copies, made_for, area| { let merging = (made_for.two_ways, made_for.blocks, area); - let made = ShadowMerge::new(&device, copies, merging, (images, pool), lent)?; + let made = ShadowMerge::new(device, copies, merging, (images, pool), lent)?; let (merge, lease) = (Arc::new(made.0), made.1); if let Some(lease) = lease { leases.push((Arc::downgrade(&merge), lease)); @@ -2783,7 +2792,7 @@ impl EncoderCore { // How this command's first copies in stood against their images' last standing, which // sizes the carry on a run without a timing (`shadow::CarryTally`). let tally = self.shadows.tally(); - (device.shared().counts).shadow_first_copies_in_tallied(tally); + (self.device().shared().counts).shadow_first_copies_in_tallied(tally); let by = match Location::caller().file() { file if file.ends_with("compute.rs") => KeepBy::Compute, file if file.ends_with("blit.rs") => KeepBy::Blit, @@ -2791,7 +2800,7 @@ impl EncoderCore { }; for copy in &copies { if let Step::Keep(merge) = ©.step { - let churn = &device.shared().counts.churn; + let churn = &self.device().shared().counts.churn; churn.kept(by, merge.cuts(), merge.texels_kept()); self.retain(Arc::clone(merge)); } @@ -3007,6 +3016,10 @@ impl EncoderCore { /// the host copies the texels the commands left into its scratch, whose changed bytes the /// host step stores (`shadow_splice.rs`, [`drain_splices`](Self::drain_splices)). pub(super) fn shadow_copies(&mut self, copies: &[ShadowCopy]) { + // No copy records nothing, barriers nothing and splices nothing. + if copies.is_empty() { + return; + } let device = self.device().clone(); let mut run = ShadowRun::default(); // The keeps a dispatch at their copy in took, which record nothing, and those that copy diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index ab9b70edd..6ce615895 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 524; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2473; +pub const RUNTIME_VERSION: u32 = 2474; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles