RUNTIME 2434: A settle of the device's maps looks only at the objects released since the last

Every compute or render state creation whose variant is not live
(VariantObjects::kept_or_create) settled the device's content-keyed maps:
the linked pipelines, the four graphics pipeline library parts, the shader
modules, the pipeline layouts and the sampler sets. Each settle walked
every entry with Arc::get_mut (a compare-exchange on each entry's weak
count) under the map's lock, so a creation cost O(objects the device
holds), a run of creations O(N^2), and creating threads queued behind each
other's walks. A guest benchmark's 7,981 compute makes spent 19.4% of their
on-CPU time in settle_device_maps and 6 + 3 ms asleep on those locks; the
new COMPUTE-CREATE-SCALING bench shows the slope (XTX, 4 threads: p50 10.7
us at 64 modules, 80.3 us at 4,160).

Now holders take a Share<T> from the map instead of a bare Arc<T>: the
object counts its shares, and the drop that leaves it with none queues its
insertion number on the map's release queue (a leaf mutex, each number
once until a settle takes it). ContentKeyed::settle drains only that queue
and destroys each queued object that still has no share, read under the
queue's lock and the map's (a lookup, the only way to take a share anew,
holds the map's lock; a later last drop queues the object again). The
objects destroyed, their order (insertion) and the calls that destroy them
are today's: the walk found exactly the objects whose shares had all gone.
No switch, no deferral, every map bound as before. The render libraries'
maps (Libraries::settle, the links and the four parts) are ContentKeyed
maps too, so a compute creation no longer walks them either.

Holders changed from Arc to Share: StageObject.module, VariantObjects and
KeptObjects samplers and layout, SharedLayout's sampler set, Link's parts
and layout, Linked. A layout's empty sampler set is Share::unmapped.

Tests (content_keyed, no device):
- a_settle_looks_only_at_what_was_released: 10,000 held, one released, the
  settle looks at 1 object (0 with none released); the old walk looked at
  10,000 each time.
- a_share_taken_again_before_the_settle_keeps_the_object, and the same on
  another thread: a share taken between the last drop and the settle keeps
  the object; released and taken again, it is queued once.
- settles_racing_shares_destroy_nothing_held: 4 threads take and drop
  shares while another settles; nothing destroyed while held, each object
  destroyed once.
- a_share_dropped_after_its_map_leaves_nothing: a share that outlives the
  map's teardown drain goes without panicking and frees its object and the
  queue.

Also: the COMPUTE-CREATE-SCALING and COMPUTE-CREATE-KEYS benches (ignored) and their profile
targets; the content-keyed map tests start their threads through exit_guard::spawn.

Verified (pipesettle): lavapipe gem10 m3-max-35753 (debug, m2v_cpu_icd) 142/142 (pipeline::*,
kept_variants, sampler_sets, linked_pipelines_shared, render_stage_digests, kept_across_calls,
core_image_libraries, exit_guard); msi 35734 clippy -D warnings 0 and 67 pipeline:: tests; gpucfg
build 35754. XTX release bench 35765 (not exclusive, same neighbour both runs), p50 us per creation
at 64 / 1088 / 4160 modules: T=1 5.9/9.3/21.8 -> 5.4/5.2/5.2; T=4 7.6/23.4/76.2 -> 6.8/7.0/6.6.
PHOENIX suites (35772) and clippy x3 + rustdoc at the tip follow.
This commit is contained in:
Anees Iqbal committed 2026-11-16 01:26:02 -08:00
1 parent ecf4c80873
commit 1c0833c2dd
9 files changed
+815 -115

No files matched your search

@@ -5,35 +5,46 @@
//! - **Exact.** An object is found by its whole content (the map hashes it, then compares it):
//! two variants share one only where the content that made it is the same.
//! - **The device's, destroyed by the map alone**. An object keeps no device functions and has no
//! `Drop` that reaches Vulkan: a holder's `Arc` (a variant's objects, a kept instance's,
//! `kept.rs`) is a share, a count, never a destructor. Only the map destroys an object
//! `Drop` that reaches Vulkan: a holder's [`Share`] (a variant's objects, a kept instance's,
//! `kept.rs`) is a count, never a destructor. Only the map destroys an object
//! ([`Owned::destroy`], through the device it is handed, `DeviceShared::vk`), on one of three
//! paths, each returning what it let go ([`Gone`]), destroyed once the map's lock is released:
//! - [`ContentKeyed::settle`], in a program's call, once the map's is the object's only share;
//! - [`ContentKeyed::settle`], in a program's call, once no share of the object is left;
//! - [`ContentKeyed::sweep`], on any thread, for the objects of a host step's or a pool piece's
//! own (below) that nothing else holds;
//! - [`ContentKeyed::drain`], at the device's teardown (`DeviceShared::drop`), after the kept
//! variants': everything left.
//!
//! So no object is destroyed before the device's teardown while anything else shares it (a new
//! holder takes a share from the map, under its lock, so none appears after the check), and none
//! after it: the map is the device's, so a destruction always has a live device. The check is
//! `Arc::get_mut`, whose Acquire orders every use a released holder made (a pool piece's
//! `vkCreate*Pipelines` from a module, on its thread) before the destruction, as the last
//! drop's fence did when the object destroyed itself; at the teardown the device's own last
//! drop does (every holder's use came before it let go of its device, or of what held its
//! share). A share left at the teardown is one whose holder is dropping its own `Device` right
//! then (a variant whose last device handle goes before its fields), and a share is used only
//! through its holder's device, which is gone: dropping it calls nothing. The order of a
//! holder's fields therefore decides nothing (the earlier rule, a destroying `Drop` of the
//! object's own, gave).
//! share is taken from the map, under its lock, or cloned from a live one, so none appears
//! after the check), and none after it: the map is the device's, so a destruction always has a
//! live device. The check reads the object's count of shares, with an Acquire that orders every
//! use a released holder made (a pool piece's `vkCreate*Pipelines` from a module, on its thread)
//! before the destruction, as each share's Release drop publishes it; at the teardown the
//! device's own last drop does (every holder's use came before it let go of its device, or of
//! what held its share). A share left at the teardown is one whose holder is dropping its own
//! `Device` right then (a variant whose last device handle goes before its fields), and a share
//! is used only through its holder's device, which is gone: dropping it calls nothing. The
//! order of a holder's fields therefore decides nothing (the earlier rule, a destroying `Drop`
//! of the object's own, gave).
//! - **A settle visits only what was released.** The share whose drop leaves an object of the map
//! with none queues the object's place in the order of insertion on its map's release queue (a
//! leaf lock: nothing else is taken under it), once until a settle takes it. A settle takes the
//! queue, and destroys each queued object that still has no share, checked under the map's lock,
//! where alone a share can be taken anew; one a lookup took a share of since stays, and is queued
//! again when that share goes. So a settle lets go of exactly the objects whose shares all went,
//! which a walk of every object found, in the same order, at the same calls; but its work is the
//! objects released since the last settle, not every object the device holds, and one with
//! nothing released takes the queue's lock and finds it empty. The device's modules, layouts,
//! sampler sets, graphics pipeline libraries and linked pipelines are all such maps
//! (`objects.rs`, `shared_layouts.rs`, `libraries.rs`): a compute state's creation settles them
//! all, the render libraries among them, and walks none.
//! - **On the program's threads, in the program's order** (the owner's HITCH rule 1). Only a
//! program's call ([`program_call`]: a thread of the program's or one running its code, outside
//! a host step and a pool piece) inserts ([`ContentKeyed::insert`]) or settles, each a debug
//! assertion; a host step or a pool piece only looks up ([`ContentKeyed::get`]) and, on a miss,
//! makes an object of its own that no lookup finds. Settling removes in the order of insertion.
//! What remains timing's is only whether a command buffer let its variants go before a settle,
//! as for the kept variants.
//! a host step and a pool piece) inserts or settles, each a debug assertion; a host step or a
//! pool piece only looks up ([`ContentKeyed::get`]) and, on a miss, makes an object of its own
//! that no lookup finds. Settling removes in the order of insertion. What remains timing's is
//! only whether a command buffer let its variants go before a settle, as for the kept variants.
//! - **The exception: an object of a host step's own.** No lookup finds it, so it changes nothing
//! another variant takes; the map keeps it apart (`own`) only to destroy it. For a variant a
//! command buffer's host step made (a device-generated replay's, `generated_execute.rs`, which
@@ -41,9 +52,11 @@
//! command buffer releases its segment, and its own objects go at the next sweep or settle (the
//! next variant made, on any thread) or at the teardown.
use std::collections::HashMap;
use crate::device::lock;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::hash::Hash;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
/// Whether this call is the program's own (the module docs): a thread of the program's, or a
/// runtime thread running the program's code (`exit_guard::in_program_call`), and neither a
@@ -62,22 +75,107 @@ pub(crate) trait Owned<C: ?Sized> {
fn destroy(&self, owner: &C);
}
/// A map's release queue (the module docs): the places in its order of insertion of the objects
/// whose last share went since its last settle, each once. Its lock is a leaf: a share's drop
/// takes it holding any other, and nothing is taken under it.
type Released = Mutex<BTreeSet<u64>>;
/// One object, with the count of its holders' shares.
struct Held<T> {
object: T,
/// The [`Share`]s of it that live.
shares: AtomicUsize,
/// Its place in its map's order of insertion.
at: u64,
/// The release queue of the map whose lookups find it; `None` for an object no lookup finds
/// (a host step's own, which a sweep looks at, or one no map holds).
released: Option<Arc<Released>>,
}
/// A holder's share of an object of a device's map (the module docs): a count the map reads,
/// never a destructor. Its drop that leaves an object of the map with no share queues it for the
/// map's next settle.
pub(crate) struct Share<T>(Arc<Held<T>>);
impl<T> Share<T> {
/// A new share of `held`.
fn of(held: &Arc<Held<T>>) -> Share<T> {
held.shares.fetch_add(1, Ordering::Relaxed);
Share(Arc::clone(held))
}
/// The share of `object`, which no map holds: dropping it destroys nothing, as there is
/// nothing to destroy (a layout's empty sampler set).
pub(crate) fn unmapped(object: T) -> Share<T> {
let held = Held {
object,
shares: AtomicUsize::new(0),
at: 0,
released: None,
};
Share::of(&Arc::new(held))
}
}
impl<T> Clone for Share<T> {
fn clone(&self) -> Share<T> {
// As `Arc::clone`: a live share holds the count above zero, so the new one needs no
// ordering of its own.
Share::of(&self.0)
}
}
impl<T> Drop for Share<T> {
fn drop(&mut self) {
// Release: every use made through this share comes before the settle that reads the
// count it leaves (its Acquire).
if self.0.shares.fetch_sub(1, Ordering::Release) != 1 {
return;
}
// The last share: queued for the map's settle, which checks the count again under the
// queue's lock and the map's. A count read here as zero and taken back up by a lookup
// before that settle leaves the object in the map.
if let Some(released) = &self.0.released {
lock(released).insert(self.0.at);
}
}
}
impl<T> std::ops::Deref for Share<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0.object
}
}
/// The device's objects of one kind, by their content `K`.
pub(crate) struct ContentKeyed<K, T> {
/// Each object, with its place in the order of insertion.
entries: HashMap<K, (u64, Arc<T>)>,
/// Each object found by lookups, by its content.
entries: HashMap<K, Arc<Held<T>>>,
/// Each such object's content, by its place in the order of insertion.
keys: BTreeMap<u64, K>,
/// The objects of a host step's or a pool piece's own, which no lookup finds, in the order
/// they were made: held only until a sweep finds nothing else sharing them.
own: Vec<Arc<T>>,
own: Vec<Arc<Held<T>>>,
/// The places of the objects whose last share went since the last settle.
released: Arc<Released>,
next: u64,
/// The objects the settles looked at (`tests::content_keyed`'s check of a settle's work).
#[cfg(test)]
looked_at: u64,
}
impl<K, T> Default for ContentKeyed<K, T> {
fn default() -> Self {
ContentKeyed {
entries: HashMap::new(),
keys: BTreeMap::new(),
own: Vec::new(),
released: Arc::default(),
next: 0,
#[cfg(test)]
looked_at: 0,
}
}
}
@@ -85,7 +183,7 @@ impl<K, T> Default for ContentKeyed<K, T> {
/// What a map let go of, in its order: destroyed through the owner once the map's lock is
/// released ([`Gone::destroy`]).
#[must_use = "the map let these go: destroy them through the device"]
pub(crate) struct Gone<T>(Vec<Arc<T>>);
pub(crate) struct Gone<T>(Vec<Arc<Held<T>>>);
impl<T> Gone<T> {
/// Destroy each, in order, through `owner`.
@@ -93,70 +191,107 @@ impl<T> Gone<T> {
where
T: Owned<C>,
{
for object in &self.0 {
object.destroy(owner);
for held in &self.0 {
held.object.destroy(owner);
}
}
}
impl<K: Hash + Eq, T> ContentKeyed<K, T> {
/// The object of `key`, if the map holds one.
pub(crate) fn get(&self, key: &K) -> Option<Arc<T>> {
self.entries.get(key).map(|(_, object)| Arc::clone(object))
impl<K: Hash + Eq + Clone, T> ContentKeyed<K, T> {
/// A share of the object of `key`, if the map holds one.
pub(crate) fn get(&self, key: &K) -> Option<Share<T>> {
self.entries.get(key).map(Share::of)
}
/// Hold `object` as the one of `key` (a program's call made it; none was there).
pub(crate) fn insert(&mut self, key: K, object: &Arc<T>) {
/// Hold `object` as the one of `key` (a program's call made it; none was there): a share of
/// it.
fn insert(&mut self, key: K, object: T) -> Share<T> {
debug_assert!(
program_call(),
"a device's map changed outside a program's call"
);
let at = self.next;
self.next += 1;
self.entries.insert(key, (at, Arc::clone(object)));
let held = Arc::new(Held {
object,
shares: AtomicUsize::new(0),
at,
released: Some(Arc::clone(&self.released)),
});
let share = Share::of(&held);
self.keys.insert(at, key.clone());
self.entries.insert(key, held);
share
}
/// The object of `key`, else one `make` makes now (and whether it was made): found by later
/// lookups where `program` (a program's call made it), else the caller's own (a host step's
/// or a pool piece's), which the map holds apart until a sweep.
/// A share of the object of `key`, else of one `make` makes now (and whether it was made):
/// found by later lookups where `program` (a program's call made it), else the caller's own
/// (a host step's or a pool piece's), which the map holds apart until a sweep.
pub(crate) fn get_or_make<E>(
&mut self,
key: K,
program: bool,
make: impl FnOnce() -> Result<T, E>,
) -> Result<(Arc<T>, bool), E> {
) -> Result<(Share<T>, bool), E> {
if let Some(object) = self.get(&key) {
return Ok((object, false));
}
let object = Arc::new(make()?);
match program {
true => self.insert(key, &object),
false => self.own.push(Arc::clone(&object)),
}
Ok((object, true))
let object = make()?;
let share = match program {
true => self.insert(key, object),
false => {
let held = Arc::new(Held {
object,
shares: AtomicUsize::new(0),
at: 0,
released: None,
});
self.own.push(Arc::clone(&held));
Share::of(&held)
}
};
Ok((share, true))
}
/// Let go of every object the map alone holds, those found by lookups in the order they were
/// inserted, then those of a host step's own: in a program's call.
/// Let go of every object found by lookups whose last share went since the last settle and
/// that none was taken of since, in the order they were inserted, then of the objects of a
/// host step's own that nothing holds: in a program's call. Only the queued objects are
/// looked at (the module docs).
pub(crate) fn settle(&mut self) -> Gone<T> {
debug_assert!(
program_call(),
"a device's map settled outside a program's call"
);
let mut gone: Vec<(u64, Arc<T>)> = Vec::new();
self.entries.retain(|_, (at, object)| {
// `Arc::get_mut` answers whether the map's is the only share with an Acquire, so
// every earlier use by a holder that let its share go (a pool piece's
// `vkCreate*Pipelines` from a module) happens before the destruction, as the last
// drop's fence ordered it (the consumer's review).
if Arc::get_mut(object).is_none() {
return true;
let mut gone = Vec::new();
{
// Held while the counts are read: a share whose drop leaves none after this read
// queues its object again once the lock is free, for the next settle; one that left
// none before it is read as none here.
let mut released = lock(&self.released);
while let Some(at) = released.pop_first() {
#[cfg(test)]
{
self.looked_at += 1;
}
// Gone already: queued again after a settle took it, or drained.
let Some(key) = self.keys.get(&at) else {
continue;
};
let Some(held) = self.entries.get(key) else {
continue;
};
// Acquire: every use by a holder that let its share go happens before the
// destruction (the module docs). A share taken since by a lookup keeps it.
if held.shares.load(Ordering::Acquire) != 0 {
continue;
}
if let Some(key) = self.keys.remove(&at) {
if let Some(held) = self.entries.remove(&key) {
gone.push(held);
}
}
}
gone.push((*at, Arc::clone(object)));
false
});
gone.sort_by_key(|(at, _)| *at);
let mut gone: Vec<Arc<T>> = gone.into_iter().map(|(_, object)| object).collect();
}
gone.extend(self.unheld_own());
Gone(gone)
}
@@ -168,26 +303,36 @@ impl<K: Hash + Eq, T> ContentKeyed<K, T> {
}
/// The own objects nothing else holds, removed, in the order they were made.
fn unheld_own(&mut self) -> Vec<Arc<T>> {
fn unheld_own(&mut self) -> Vec<Arc<Held<T>>> {
let mut gone = Vec::new();
self.own.retain_mut(|object| {
// As in `settle`: unique, with an Acquire.
if Arc::get_mut(object).is_none() {
self.own.retain(|held| {
// As in `settle`: no share left, with an Acquire. No lookup finds an own object, so
// none is taken anew.
if held.shares.load(Ordering::Acquire) != 0 {
return true;
}
gone.push(Arc::clone(object));
gone.push(Arc::clone(held));
false
});
gone
}
/// How many objects it holds, those found by lookups and the own ones (a bench's look).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn len(&self) -> usize {
self.entries.len() + self.own.len()
}
/// Every object, those found by lookups in the order they were inserted, then the own ones:
/// the device's teardown, whatever still shares them.
/// the device's teardown, whatever still shares them. A share left then queues nothing that
/// is destroyed again: its drop finds its place gone from the map.
pub(crate) fn drain(&mut self) -> Gone<T> {
let mut all: Vec<(u64, Arc<T>)> = self.entries.drain().map(|(_, entry)| entry).collect();
all.sort_by_key(|(at, _)| *at);
let mut all: Vec<Arc<T>> = all.into_iter().map(|(_, object)| object).collect();
let mut all = Vec::with_capacity(self.entries.len() + self.own.len());
while let Some((_, key)) = self.keys.pop_first() {
all.extend(self.entries.remove(&key));
}
all.append(&mut self.own);
lock(&self.released).clear();
Gone(all)
}
}
@@ -195,7 +340,7 @@ impl<K: Hash + Eq, T> ContentKeyed<K, T> {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
/// An object whose destruction its owner, a log, records; dropping it records nothing.
struct Recorded(u32);
@@ -213,18 +358,34 @@ mod tests {
log.lock().unwrap().clone()
}
/// The object of `n`, made for the program where none is.
fn made(map: &mut ContentKeyed<u32, Recorded>, n: u32) -> Share<Recorded> {
map.get_or_make(n, true, || Ok::<_, ()>(Recorded(n)))
.unwrap()
.0
}
/// The objects a settle of `map` looked at.
fn settled(map: &mut ContentKeyed<u32, Recorded>, log: &Log) -> u64 {
let before = map.looked_at;
map.settle().destroy(log);
map.looked_at - before
}
#[test]
fn objects_leave_only_when_the_map_alone_holds_them_in_insertion_order() {
let log = Log::default();
let mut map: ContentKeyed<Vec<u32>, Recorded> = ContentKeyed::default();
let a = Arc::new(Recorded(1));
let b = Arc::new(Recorded(2));
let c = Arc::new(Recorded(3));
map.insert(vec![7, 7], &a);
map.insert(vec![8], &b);
map.insert(vec![9], &c);
let mut make = |key: Vec<u32>, n| {
map.get_or_make(key, true, || Ok::<_, ()>(Recorded(n)))
.unwrap()
.0
};
let a = make(vec![7, 7], 1);
let b = make(vec![8], 2);
let c = make(vec![9], 3);
// The same content finds the same object; other content none.
assert!(Arc::ptr_eq(&map.get(&vec![7, 7]).unwrap(), &a));
assert!(std::ptr::eq(&*map.get(&vec![7, 7]).unwrap(), &*a));
assert!(map.get(&vec![7]).is_none());
// Held by a variant: nothing leaves, nothing is destroyed.
map.settle().destroy(&log);
@@ -264,7 +425,7 @@ mod tests {
assert!(fresh);
let (again, fresh) = map.get_or_make(6, false, made(60)).unwrap();
assert!(!fresh);
assert!(Arc::ptr_eq(&first, &again));
assert!(std::ptr::eq(&*first, &*again));
// A failed making leaves nothing.
assert!(map
.get_or_make(7, true, || Err::<Recorded, ()>(()))
@@ -335,4 +496,197 @@ mod tests {
"a late share destroyed nothing"
);
}
/// A share that outlives its map (a holder dropping its device after the teardown) goes with
/// no panic, and leaves nothing behind: neither its object nor the map's release queue.
#[test]
fn a_share_dropped_after_its_map_leaves_nothing() {
let log = Log::default();
let mut map: ContentKeyed<u32, Recorded> = ContentKeyed::default();
let late = made(&mut map, 1);
let copy = late.clone();
let object = Arc::downgrade(&late.0);
let queue = Arc::downgrade(&map.released);
map.drain().destroy(&log);
drop(map);
drop(copy);
drop(late);
assert_eq!(destroyed(&log), vec![1], "destroyed once, at the teardown");
assert!(object.upgrade().is_none(), "the object was freed");
assert!(queue.upgrade().is_none(), "the release queue was freed");
}
/// The bound this fixes: a settle looks only at the objects released since the last, however
/// many the map holds, and at none where none was released.
#[test]
fn a_settle_looks_only_at_what_was_released() {
let log = Log::default();
let mut map: ContentKeyed<u32, Recorded> = ContentKeyed::default();
let mut held: Vec<Share<Recorded>> = (0..10_000).map(|n| made(&mut map, n)).collect();
assert_eq!(
settled(&mut map, &log),
0,
"nothing released, nothing looked at"
);
let released = held.swap_remove(4321);
drop(released);
assert_eq!(settled(&mut map, &log), 1, "one released, one looked at");
assert_eq!(destroyed(&log), vec![4321]);
assert_eq!(settled(&mut map, &log), 0);
assert_eq!(map.entries.len(), 9_999);
drop(held);
assert_eq!(settled(&mut map, &log), 9_999);
assert_eq!(map.entries.len(), 0);
}
/// A share taken from the map after the object's last went, before the settle, keeps the
/// object: the settle looks at it and leaves it, and its next release queues it again. Taken
/// and let go again before the settle, it is queued once.
#[test]
fn a_share_taken_again_before_the_settle_keeps_the_object() {
let log = Log::default();
let mut map: ContentKeyed<u32, Recorded> = ContentKeyed::default();
drop(made(&mut map, 1));
let again = map.get(&1).unwrap();
assert_eq!(settled(&mut map, &log), 1);
assert!(destroyed(&log).is_empty(), "the share taken again keeps it");
assert_eq!(map.entries.len(), 1);
drop(again);
drop(map.get(&1).unwrap());
drop(map.get(&1).unwrap());
assert_eq!(settled(&mut map, &log), 1, "queued once");
assert_eq!(destroyed(&log), vec![1]);
assert!(map.get(&1).is_none());
}
/// A thread of the runtime's (`exit_guard::spawn`, as every thread the runtime starts is),
/// running `f`: a holder's, as a handler thread or a pool piece is, outside the program's
/// calls.
fn holder_thread<T: Send + 'static>(
f: impl FnOnce() -> T + Send + 'static,
) -> std::thread::JoinHandle<T> {
crate::exit_guard::spawn(std::thread::Builder::new(), f).unwrap()
}
/// The same across threads: one thread lets its share go, another takes one from the map
/// before the settle and holds it through it; the object stays until that share goes, then
/// leaves at the next settle.
#[test]
fn a_share_taken_on_another_thread_before_the_settle_keeps_the_object() {
let log = Log::default();
let map = Arc::new(Mutex::new(ContentKeyed::<u32, Recorded>::default()));
let first = made(&mut lock(&map), 1);
holder_thread(move || drop(first)).join().unwrap();
let (taken, give_back) = std::sync::mpsc::channel::<()>();
let holder = {
let map = Arc::clone(&map);
holder_thread(move || {
let share = lock(&map).get(&1).unwrap();
taken.send(()).unwrap();
// Held until the main thread's settle is done.
std::thread::park();
drop(share);
})
};
give_back.recv().unwrap();
lock(&map).settle().destroy(&log);
assert!(
destroyed(&log).is_empty(),
"the other thread's share keeps it"
);
holder.thread().unpark();
holder.join().unwrap();
lock(&map).settle().destroy(&log);
assert_eq!(destroyed(&log), vec![1]);
}
/// An object whose destruction marks it, and a log of each destroyed once.
struct Marked {
id: u32,
destroyed: AtomicBool,
}
impl Owned<Log> for Marked {
fn destroy(&self, log: &Log) {
assert!(
!self.destroyed.swap(true, Ordering::SeqCst),
"destroyed twice"
);
log.lock().unwrap().push(self.id);
}
}
/// Holders' threads that take shares from the map and let them go while the program's
/// thread makes the objects again and settles the map, as a pool piece's or a handler
/// thread's holders race a program's settle: no object is destroyed while a share of it
/// lives, none twice, and every one made by the end. The program's thread lets its own share
/// go as it makes each object, so a holder's share taken before the next settle is what keeps
/// it: the race between a last drop and a settle.
#[test]
fn settles_racing_shares_destroy_nothing_held() {
const THREADS: usize = 4;
const HOLDS: u32 = 2_000;
const KEYS: u32 = 8;
let log = Log::default();
let map = Arc::new(Mutex::new(ContentKeyed::<u32, Marked>::default()));
let running = Arc::new(AtomicUsize::new(THREADS));
let takers: Vec<_> = (0..THREADS as u32)
.map(|t| {
let (map, running) = (Arc::clone(&map), Arc::clone(&running));
holder_thread(move || {
let (mut held, mut n) = (0, t);
while held < HOLDS {
n = n.wrapping_add(1);
let Some(share) = lock(&map).get(&(n % KEYS)) else {
continue;
};
let copy = share.clone();
drop(share);
assert!(
!copy.destroyed.load(Ordering::SeqCst),
"destroyed while held"
);
held += 1;
}
running.fetch_sub(1, Ordering::SeqCst);
})
})
.collect();
// The program's thread: each key's object made again where a settle let it go, its own
// share let go at once; the settle under a lock of its own, so holders take shares
// between the two.
let mut made = 0u32;
while running.load(Ordering::SeqCst) > 0 {
{
let mut map = lock(&map);
for key in 0..KEYS {
let (share, fresh) = map
.get_or_make(key, true, || {
Ok::<_, ()>(Marked {
id: made,
destroyed: AtomicBool::new(false),
})
})
.unwrap();
made += u32::from(fresh);
drop(share);
}
}
std::thread::yield_now();
let gone = lock(&map).settle();
gone.destroy(&log);
}
for taker in takers {
taker.join().unwrap();
}
lock(&map).settle().destroy(&log);
let mut destroyed = log.lock().unwrap().clone();
destroyed.sort_unstable();
assert_eq!(
destroyed,
(0..made).collect::<Vec<_>>(),
"each made, destroyed once"
);
assert_eq!(lock(&map).entries.len(), 0);
}
}
@@ -48,6 +48,7 @@
//! - **Teardown.** The device destroys what is left at its teardown (`DeviceShared::drop`), the
//! queue's included.
use super::content_keyed::Share;
use super::graphics::GraphicsKey;
use super::objects::{SamplerSet, StageObject};
use super::region_ledger::{Listed, Unlisted};
@@ -183,13 +184,13 @@ impl StepNumbers {
/// after these.
pub(crate) struct KeptObjects {
pub(crate) stages: Vec<StageObject>,
pub(crate) samplers: Arc<SamplerSet>,
pub(crate) samplers: Share<SamplerSet>,
/// Its set layouts and pipeline layout, a share of the device's (`shared_layouts.rs`).
pub(crate) layout: Arc<SharedLayout>,
pub(crate) layout: Share<SharedLayout>,
/// The digest the variant's makings' records are named by (`objects::variant_content`).
pub(crate) content: metal2vulkan::cache::Hash256,
/// Each stage's words' digest (`objects::words_digest`), in stage order.
pub(crate) words: std::sync::Arc<[metal2vulkan::cache::Hash256]>,
pub(crate) words: Arc<[metal2vulkan::cache::Hash256]>,
}
/// A kept `VkPipeline`: its place, and whether its specialized notices wait for a draw's first
@@ -52,14 +52,14 @@
//! record.
use super::budget;
use super::content_keyed::{program_call, ContentKeyed, Owned};
use super::content_keyed::{program_call, ContentKeyed, Owned, Share};
use super::shared_layouts::SharedLayout;
use crate::device::{lock, DeviceShared};
use crate::error::Error;
use crate::release;
use ash::vk;
use metal2vulkan::cache::Hash256;
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use std::sync::{Condvar, Mutex, PoisonError};
/// The four parts of a graphics pipeline's state, in the order a linked pipeline takes them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -222,10 +222,10 @@ struct LinkKey {
pub(crate) struct Link {
pipeline: Library,
/// Its four libraries, in [`Part::ALL`]'s order.
parts: [Arc<Library>; 4],
parts: [Share<Library>; 4],
/// The layout it is linked with: Vulkan may read a pipeline's creation's objects for as long
/// as the pipeline lives.
layout: Arc<SharedLayout>,
layout: Share<SharedLayout>,
}
impl Owned<DeviceShared> for Link {
@@ -239,7 +239,7 @@ impl Owned<DeviceShared> for Link {
/// The linked pipeline of a variant's key, with the libraries it is linked from, held while the
/// variant's pipeline lives: the device's, which other variants of the same link share.
#[derive(Clone)]
pub(crate) struct Linked(Arc<Link>);
pub(crate) struct Linked(Share<Link>);
/// The device's libraries, by part and content, and its linked pipelines, by link
/// (`DeviceShared::libraries`).
@@ -258,10 +258,10 @@ impl Libraries {
&self,
shared: &DeviceShared,
names: &[Hash256; 4],
layout: &Arc<SharedLayout>,
layout: &Share<SharedLayout>,
) -> Linked {
let program = program_call();
let parts: [Arc<Library>; 4] = std::array::from_fn(|at| {
let parts: [Share<Library>; 4] = std::array::from_fn(|at| {
let mut map = lock(&self.parts[at]);
let (library, _) = match map.get_or_make(names[at], program, || {
Ok::<Library, std::convert::Infallible>(Library::new())
@@ -284,7 +284,7 @@ impl Libraries {
Ok::<Link, std::convert::Infallible>(Link {
pipeline: Library::new(),
parts,
layout: Arc::clone(layout),
layout: layout.clone(),
})
}) {
Ok(found) => found,
@@ -307,6 +307,17 @@ impl Libraries {
}
}
/// How many linked pipelines and libraries it holds (a bench's look).
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
pub(crate) fn len(&self) -> usize {
lock(&self.links).len()
+ self
.parts
.iter()
.map(|part| lock(part).len())
.sum::<usize>()
}
/// Destroy every linked pipeline, then every library: the device's teardown, after the kept
/// pipelines.
pub(crate) fn drain(&self, shared: &DeviceShared) {
@@ -321,7 +332,7 @@ impl Libraries {
impl Linked {
/// Its libraries, in [`Part::ALL`]'s order.
pub(crate) fn parts(&self) -> &[Arc<Library>; 4] {
pub(crate) fn parts(&self) -> &[Share<Library>; 4] {
&self.0.parts
}
@@ -355,7 +366,7 @@ mod tests {
use crate::error::internal;
use crate::exit_guard;
use ash::vk::Handle;
use std::sync::mpsc;
use std::sync::{mpsc, Arc};
use std::thread::Builder;
use std::time::Duration;
@@ -12,7 +12,7 @@
//! layout, by their exact definition (`shared_layouts.rs`). Only the device's maps destroy those:
//! a variant's are shares.
use super::content_keyed::{program_call, ContentKeyed, Owned};
use super::content_keyed::{program_call, ContentKeyed, Owned, Share};
use super::creation_log;
use super::graphics::Notices;
use super::interlocked_writes;
@@ -62,7 +62,7 @@ struct ComputeStage<'a> {
#[derive(Clone)]
pub(crate) struct StageObject {
pub(super) stage: vk::ShaderStageFlags,
pub(super) module: Arc<ShaderModule>,
pub(super) module: Share<ShaderModule>,
pub(super) entry: CString,
}
@@ -128,12 +128,12 @@ pub(crate) type SamplerSets = ContentKeyed<Vec<metal2vulkan::vk::SamplerDesc>, S
pub(crate) fn sampler_set(
device: &Device,
descs: Vec<metal2vulkan::vk::SamplerDesc>,
) -> Result<(Arc<SamplerSet>, bool), Error> {
) -> Result<(Share<SamplerSet>, bool), Error> {
if descs.is_empty() {
let empty = SamplerSet {
samplers: Vec::new(),
};
return Ok((Arc::new(empty), false));
return Ok((Share::unmapped(empty), false));
}
// A warm pass makes no sampler, nor holds the device's (`warm/pass.rs`): either would count
// against the device's limit at a moment the program's order does not decide.
@@ -173,7 +173,7 @@ fn make_sampler_set(
descs: &[metal2vulkan::vk::SamplerDesc],
conversions: &[Option<vk::SamplerYcbcrConversion>],
program: bool,
) -> Result<(Arc<SamplerSet>, bool), Error> {
) -> Result<(Share<SamplerSet>, bool), Error> {
let shared = device.shared();
// The lock is held across the creation, so two of the program's calls never make two sets of
// the same samplers.
@@ -276,7 +276,7 @@ impl StageObject {
/// One `VkShaderModule`: the device's module of its SPIR-V, shared by every variant whose stage
/// has those exact words ([`ShaderModules`]), or a host step's own. It keeps no device functions
/// and has no destroying `Drop`: a holder's `Arc` is a share, and only the device's map destroys
/// and has no destroying `Drop`: a holder's `Share` is a count, and only the device's map destroys
/// it ([`Owned::destroy`]), once nothing else shares it or at the device's teardown
/// (`content_keyed.rs`), so a holder that outlives the device's teardown (a variant whose last
/// device handle goes before its stages) calls nothing. On MoltenVK a module keeps the libraries
@@ -414,7 +414,7 @@ pub(crate) fn shader_module(
device: &Device,
spirv: &[u32],
digest: &Hash256,
) -> Result<Arc<ShaderModule>, Error> {
) -> Result<Share<ShaderModule>, Error> {
let shared = device.shared();
let program = program_call();
// The lock is held across the creation, so two of the program's calls never make two
@@ -475,10 +475,10 @@ pub(crate) struct VariantObjects {
pub(super) device: Device,
/// The stages' modules, in the pipeline's stage order.
pub(super) stages: Vec<StageObject>,
samplers: Arc<SamplerSet>,
samplers: Share<SamplerSet>,
/// Its set layouts and pipeline layout: the device's of their definition
/// (`shared_layouts.rs`).
layout: Arc<SharedLayout>,
layout: Share<SharedLayout>,
/// What one set of each layout set takes from a pool, by set number.
set_needs: Vec<SetNeeds>,
/// Whether its draws push set 0 rather than allocate it (`pushes_set_zero`).
@@ -595,8 +595,8 @@ impl Drop for VariantObjects {
};
let objects = KeptObjects {
stages: self.stages.clone(),
samplers: Arc::clone(&self.samplers),
layout: Arc::clone(&self.layout),
samplers: self.samplers.clone(),
layout: self.layout.clone(),
content: self.content,
words: Arc::clone(&self.words),
};
@@ -1034,7 +1034,7 @@ impl VariantObjects {
/// Its share of the device's layout, which a linked pipeline made with it holds
/// (`libraries.rs`).
pub(crate) fn shared_layout(&self) -> &Arc<SharedLayout> {
pub(crate) fn shared_layout(&self) -> &Share<SharedLayout> {
&self.layout
}
@@ -21,7 +21,7 @@
//! sampler set its set layouts bake until the map destroys it.
//! - **Counted**: `WorkCounts::pipeline_layouts_made`, `WorkCounts::pipeline_layouts_shared`.
use super::content_keyed::{program_call, ContentKeyed, Owned};
use super::content_keyed::{program_call, ContentKeyed, Owned, Share};
use super::objects::{create_set_layout, SamplerSet};
use crate::device::{lock, DeviceShared};
use crate::error::{internal, vulkan, Error};
@@ -29,7 +29,6 @@ use crate::release;
use crate::Device;
use ash::vk;
use metal2vulkan::pipeline::{PipelineLayout, PushConstantRange};
use std::sync::Arc;
/// One shared layout: its set layouts, by set number, and its pipeline layout. It keeps no
/// device functions and destroys nothing itself: only the device's map destroys it, once nothing
@@ -38,7 +37,7 @@ pub(crate) struct SharedLayout {
set_layouts: Vec<vk::DescriptorSetLayout>,
layout: vk::PipelineLayout,
/// The immutable samplers its set layouts bake, held until the map destroys it.
_samplers: Arc<SamplerSet>,
_samplers: Share<SamplerSet>,
}
impl Owned<DeviceShared> for SharedLayout {
@@ -112,9 +111,9 @@ pub(crate) type SharedLayouts = ContentKeyed<LayoutKey, SharedLayout>;
pub(crate) fn shared_layout(
device: &Device,
layout: &PipelineLayout,
samplers: &Arc<SamplerSet>,
samplers: &Share<SamplerSet>,
(push_set_zero, dynamic): (bool, &[u32]),
) -> Result<Arc<SharedLayout>, Error> {
) -> Result<Share<SharedLayout>, Error> {
let mut baked = samplers.samplers().iter().copied();
let mut sets = Vec::with_capacity(layout.sets.len());
for (index, set) in layout.sets.iter().enumerate() {
@@ -191,13 +190,13 @@ fn made_layout(
device: &Device,
layout: &PipelineLayout,
key: &LayoutKey,
samplers: &Arc<SamplerSet>,
samplers: &Share<SamplerSet>,
) -> Result<SharedLayout, Error> {
let shared = device.shared();
let mut made = SharedLayout {
set_layouts: Vec::with_capacity(key.sets.len()),
layout: vk::PipelineLayout::null(),
_samplers: Arc::clone(samplers),
_samplers: samplers.clone(),
};
for (set, set_key) in layout.sets.iter().zip(&key.sets) {
let immutable: Vec<&[vk::Sampler]> =
@@ -0,0 +1,334 @@
//! What a warm compute pipeline state's creation costs as the device holds more objects
//! (ignored, `COMPUTE-CREATE-SCALING`; run in release), on several threads at once, as a guest's
//! pipeline compiles make them.
//!
//! The device first holds a base of `n` live states (each of its own SPIR-V words, so each holds
//! its own shader module), for each `n` of [`LIVE`]; then each of `threads` threads makes and
//! releases states from a small working set of its own, [`ROUNDS`] times over: each making after
//! the first takes back the objects the released variant left (`pipeline/kept.rs`), as a guest that
//! releases a state and makes it again does. Printed for each `n` and thread count: the median,
//! 90th and 99th percentile creation times, the device's maps' sizes (what a settle of them
//! walks), and the round's work counts (translations, variants taken back, modules made).
//!
//! The kernel is the owned fixture `kernel_vector_function_constant`
//! (`validation/fixtures/public`), assembled by `llvm-as`, whose `uint4` constant's lanes are
//! folded into the value it stores: each sum is a module of its own.
//!
//! [`compute_create_scaling_profile_empty`] and [`compute_create_scaling_profile_full`] are
//! targets for a profiler: four threads' churn alone, over no live base and over the largest.
//!
//! [`compute_create_key_costs`] (`COMPUTE-CREATE-KEYS`) times the keys a creation derives on its
//! own: the function's compile key and the compute pipeline's key, and the `Debug` text each
//! formats today, and the layout text that names a new variant's makings.
//!
//! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`).
use super::blit_holds::{options, Scratch};
use crate::{ComputePipelineState, Device, Library, PipelineOptions, WorkCounts};
use metal2vulkan::library::{FunctionConstantValue, FunctionConstantValues};
use metal2vulkan::metal::DataType;
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
/// The kernel.
const KERNEL: &str = "kernel_vector_function_constant";
/// The live base sizes measured, in order: the base grows to each.
const LIVE: [u32; 5] = [0, 512, 1024, 2048, 4096];
/// The thread counts measured at each base size.
const THREADS: [u32; 2] = [1, 4];
/// The states of each thread's working set.
const WORKING: u32 = 16;
/// How many times each thread makes and releases its working set at each base size.
const ROUNDS: u32 = 24;
/// Where a working set's sums start: past every base state's.
const WORKING_BASE: u32 = 1 << 24;
/// The kernel's library on `device`.
fn library(device: &Device) -> Library {
let ll = metal2vulkan_devtools::fixtures_dir().join(format!("{KERNEL}.ll"));
let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap();
device.new_library_with_compile_library(
metal2vulkan::library::Library::from_air(&bitcode).unwrap(),
)
}
/// The kernel's constants whose stored sum is `sum`.
fn constants(sum: u32) -> FunctionConstantValues {
let lanes: Vec<u8> = [sum, 0, 0, 0]
.iter()
.flat_map(|l| l.to_le_bytes())
.collect();
FunctionConstantValues::defaults().with_name(
"vector_value",
FunctionConstantValue::new(DataType::UInt4, lanes),
)
}
/// The state whose stored sum is `sum`, made on `device` from `library`, and how long the
/// creation took.
fn state(device: &Device, library: &Library, sum: u32) -> (ComputePipelineState, Duration) {
let function = library
.new_function_with_name_constant_values(KERNEL, &constants(sum))
.unwrap();
let descriptor =
ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor()));
let began = Instant::now();
let state = device
.new_compute_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap();
(state, began.elapsed())
}
/// The states of sums `from..to`, made on `threads` threads, each thread with a library of its
/// own.
fn base(device: &Device, from: u32, to: u32, threads: u32) -> Vec<ComputePipelineState> {
std::thread::scope(|scope| {
let parts: Vec<_> = (0..threads)
.map(|t| {
scope.spawn(move || {
let library = library(device);
(from..to)
.filter(|sum| sum % threads == t)
.map(|sum| state(device, &library, sum).0)
.collect::<Vec<_>>()
})
})
.collect();
parts
.into_iter()
.flat_map(|part| part.join().unwrap())
.collect()
})
}
/// Each of `threads` threads makes and releases its working set `rounds` times: every creation's
/// time.
fn churn(device: &Device, threads: u32, rounds: u32) -> Vec<Duration> {
std::thread::scope(|scope| {
let parts: Vec<_> = (0..threads)
.map(|t| {
scope.spawn(move || {
let library = library(device);
let first = WORKING_BASE + t * WORKING;
let mut times = Vec::new();
for _ in 0..rounds {
for sum in first..first + WORKING {
let (state, took) = state(device, &library, sum);
drop(state);
times.push(took);
}
}
times
})
})
.collect();
parts
.into_iter()
.flat_map(|part| part.join().unwrap())
.collect()
})
}
/// The median, 90th and 99th percentile of `times`, in microseconds.
fn spread(times: &[Duration]) -> String {
let mut times = times.to_vec();
times.sort();
let at = |q: f64| times[((times.len() - 1) as f64 * q) as usize].as_secs_f64() * 1e6;
format!(
"p50 {:.1} us, p90 {:.1} us, p99 {:.1} us",
at(0.5),
at(0.9),
at(0.99)
)
}
/// The device's maps' sizes: what a settle of them walks.
fn maps(device: &Device) -> String {
let shared = device.shared();
let modules = crate::device::lock(&shared.shader_modules).len();
let layouts = crate::device::lock(&shared.pipeline_layouts).len();
let sets = crate::device::lock(&shared.sampler_sets).len();
let libraries = shared.libraries.as_ref().map_or(0, |l| l.len());
let (kept, _) = crate::device::lock(&shared.kept).held();
format!(
"modules {modules}, layouts {layouts}, sampler sets {sets}, libraries and links \
{libraries}, kept instances {kept}"
)
}
/// What the churn did, from `before` to `after`.
fn work(before: &WorkCounts, after: &WorkCounts) -> String {
format!(
"translated {}, taken back {}, modules made {}, VkPipelines made {}",
after.functions_translated - before.functions_translated,
after.variants_taken_back - before.variants_taken_back,
after.shader_modules_made - before.shader_modules_made,
after.variant_pipelines_made - before.variant_pipelines_made,
)
}
/// A device over the shader cache in `scratch`, with a record hook that only counts into
/// `records`, as a consumer's hands each record to a writer thread; each thread's working set
/// made once on it, cold, and released, so every later making of one is warm.
fn device_of(scratch: &Scratch, records: &Arc<AtomicU64>) -> Device {
let mut options = options(&scratch.0);
let counted = Arc::clone(records);
options.pipeline_records = Some(Arc::new(move |record| {
drop(record);
counted.fetch_add(1, Ordering::Relaxed);
}));
let device = Device::system_default_with(&options).unwrap();
churn(&device, *THREADS.iter().max().unwrap(), 1);
device
}
/// The bench (the module docs).
#[test]
#[ignore = "a release-mode benchmark"]
fn compute_create_scaling_bench() {
let scratch = Scratch::new("compute-create-scaling");
let records = Arc::new(AtomicU64::new(0));
let device = device_of(&scratch, &records);
let mut live: Vec<ComputePipelineState> = Vec::new();
for n in LIVE {
let began = Instant::now();
let made = live.len() as u32;
live.extend(base(&device, made, n, 4));
let grown = began.elapsed();
for threads in THREADS {
let before = device.work_counts();
let began = Instant::now();
let times = churn(&device, threads, ROUNDS);
let wall = began.elapsed();
eprintln!(
"COMPUTE-CREATE-SCALING {} live {n} threads {threads}: {} creations in {:.1} ms \
({:.1} us each); {}; {}; {} (base grown in {:.1} s)",
device.name(),
times.len(),
wall.as_secs_f64() * 1e3,
wall.as_secs_f64() * 1e6 / times.len() as f64,
spread(&times),
maps(&device),
work(&before, &device.work_counts()),
grown.as_secs_f64(),
);
}
}
eprintln!(
"COMPUTE-CREATE-SCALING {}: {} records handed over",
device.name(),
records.load(Ordering::Relaxed)
);
drop(live);
}
/// The rounds of each thread's churn in a profile target.
const PROFILE_ROUNDS: u32 = 400;
/// Four threads' churn of [`PROFILE_ROUNDS`] rounds over a live base of `live` states, printed as
/// the bench prints.
fn profile(live: u32) {
let scratch = Scratch::new("compute-create-scaling-profile");
let records = Arc::new(AtomicU64::new(0));
let device = device_of(&scratch, &records);
let base = base(&device, 0, live, 4);
let began = Instant::now();
let times = churn(&device, 4, PROFILE_ROUNDS);
let wall = began.elapsed();
eprintln!(
"COMPUTE-CREATE-SCALING-PROFILE {} live {live} threads 4: {} creations in {:.1} ms; {}; {}",
device.name(),
times.len(),
wall.as_secs_f64() * 1e3,
spread(&times),
maps(&device),
);
drop(base);
}
/// For a profiler (ignored; run in release): four threads' churn over no live base, what a
/// creation costs apart from what the device holds.
#[test]
#[ignore = "a release-mode profile target"]
fn compute_create_scaling_profile_empty() {
profile(0);
}
/// For a profiler (ignored; run in release): four threads' churn over the largest live base.
#[test]
#[ignore = "a release-mode profile target"]
fn compute_create_scaling_profile_full() {
profile(*LIVE.iter().max().unwrap());
}
/// The calls each of [`compute_create_key_costs`]' pieces is timed over.
const KEY_CALLS: u32 = 20_000;
/// The mean of [`KEY_CALLS`] runs of `piece`, in microseconds.
fn mean_of<T>(mut piece: impl FnMut() -> T) -> f64 {
let began = Instant::now();
for _ in 0..KEY_CALLS {
std::hint::black_box(piece());
}
began.elapsed().as_secs_f64() * 1e6 / f64::from(KEY_CALLS)
}
/// What the keys a warm creation of the bench's kernel derives cost on their own (ignored,
/// `COMPUTE-CREATE-KEYS`; run in release), each the mean of [`KEY_CALLS`] calls: the function's
/// compile key (`Variant::compiled`), the compute pipeline's key of the compiled kernel
/// (`Sources::kernel`), the `Debug` text of the lowering inputs and of the descriptor's fields
/// those keys format, and the text of the layout that names a new variant's makings
/// (`objects::variant_content`).
#[test]
#[ignore = "a release-mode benchmark"]
fn compute_create_key_costs() {
use metal2vulkan::pipeline::LoweringInputs;
let scratch = Scratch::new("compute-create-keys");
let device = Device::system_default_with(&options(&scratch.0)).unwrap();
let library = library(&device);
let function = library
.new_function_with_name_constant_values(KERNEL, &constants(7))
.unwrap();
let descriptor = function.function_descriptor();
let compile = device.compile_device();
let inputs = LoweringInputs::default();
let budget = metal2vulkan::Budget::standard();
let compiled = compile
.compile_function(&descriptor, &inputs, &budget)
.unwrap();
let kernel = ComputePipelineDescriptor::new(StageSource::Compiled(compiled));
let pipeline = compile.compile_compute_pipeline(&kernel, &budget).unwrap();
let function_key = mean_of(|| compile.function_compile_key(&descriptor, &inputs));
let pipeline_key = mean_of(|| compile.compute_pipeline_key(&kernel));
let inputs_text = mean_of(|| {
format!(
"LoweringInputs {{ vertex_fetch: {:?}, storage_images: {:?}, psb_slots: {:?} }}",
inputs.vertex_fetch, inputs.storage_images, inputs.psb_slots
)
});
let fields_text = mean_of(|| {
format!(
"{:?}",
(
kernel.stage_input.as_ref(),
kernel.max_total_threads_per_threadgroup,
kernel.threadgroup_size_is_multiple_of_execution_width,
kernel.support_indirect_command_buffers,
)
)
});
let layout_text = mean_of(|| format!("{:?}", pipeline.layout));
eprintln!(
"COMPUTE-CREATE-KEYS {}: function_compile_key {function_key:.2} us (its inputs' text \
{inputs_text:.2} us); compute_pipeline_key {pipeline_key:.2} us (its fields' text \
{fields_text:.2} us); a variant's layout text {layout_text:.2} us (means of {KEY_CALLS})",
device.name(),
);
}
@@ -94,6 +94,8 @@ mod compute_bind_memo;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod compute_create_bench;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod compute_create_scaling_bench;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod compute_instantiated;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod compute_parked;
@@ -14,7 +14,6 @@ use crate::{Device, DeviceKind, DeviceOptions};
use metal2vulkan::bind::SamplerDescriptor;
use metal2vulkan::metal::sampler::{vk_sampler, SamplerUse};
use metal2vulkan::metal::SamplerAddressMode;
use std::sync::Arc;
/// The device the cfg selects: a CPU device under `m2v_cpu_icd`, else a GPU.
fn device() -> Device {
@@ -64,17 +63,17 @@ fn equal_baked_samplers_are_one_set_counted_once() {
"the set's two samplers"
);
let (again, made) = sampler_set(&device, descs.clone()).unwrap();
assert!(!made && Arc::ptr_eq(&first, &again), "the device's set");
assert!(!made && std::ptr::eq(&*first, &*again), "the device's set");
let (stepped, made) =
crate::exit_guard::host_step(|| sampler_set(&device, descs.clone())).unwrap();
assert!(
!made && Arc::ptr_eq(&first, &stepped),
!made && std::ptr::eq(&*first, &*stepped),
"a host step takes the device's set"
);
assert_eq!(shared.sampler_count.live(), live + 2, "counted once");
let (other, made) = sampler_set(&device, vec![desc(SamplerAddressMode::MirrorRepeat)]).unwrap();
assert!(
made && !Arc::ptr_eq(&first, &other),
made && !std::ptr::eq(&*first, &*other),
"other samplers, another set"
);
assert_eq!(shared.sampler_count.live(), live + 3);
@@ -109,7 +108,7 @@ fn equal_baked_samplers_are_one_set_counted_once() {
assert_eq!(shared.sampler_count.live(), live + 2);
let (program, made) = sampler_set(&device, mirrored).unwrap();
assert!(
made && !Arc::ptr_eq(&own, &program),
made && !std::ptr::eq(&*own, &*program),
"the step's set is not the device's"
);
assert_eq!(shared.sampler_count.live(), live + 4);
+1 -1
View File
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523;
/// 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 = 2433;
pub const RUNTIME_VERSION: u32 = 2434;
/// 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