diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index d35893f1c..04b51d25f 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -24,7 +24,9 @@ device against the floor below. answer passes, and passes over it otherwise; `Device::extensions` lists those enabled, the floor's first. The consumer names an extension's dependencies too. It names the core Vulkan features its own work needs as `ConsumerFeature`s (`SamplerYcbcrConversion` for now): the device - enables each one it reports, once, and `Device::features` lists those enabled. + enables each one it reports, once, and `Device::features` lists those enabled. It names the + directory the device keeps its compiled kernels in, `pipeline_cache_dir` (see "The cache + directory"). - `Device::raw` gives the instance, physical device, device and queue family handles, and `Device::with_present_queue` runs the consumer's presents on the presenting queue under its lock. The runtime keeps owning every handle. @@ -34,7 +36,8 @@ device against the floor below. The runtime runs four threads per device: the block-maker, the submit thread, the completion thread, and the reaper, which frees the semaphores and command pools the others give up, one at a -time, so no driver free runs on the completion thread and a submission waits behind at most one. +time, so no driver free runs on the completion thread and a submission waits behind at most one, +and writes the pipeline data to the cache directory when it is due. A device is torn down when its last handle, and the last handle of every object made from it, is dropped; a committed command buffer and the blocks the consumer holds do not keep it alive. Teardown stops the submit thread, which submits what is ready and ends what it holds with @@ -59,7 +62,8 @@ by `Device::new`. ### Counters `Device::counters` returns a handle that stays readable after the device is gone. `metrics()` are -cumulative counts (submissions, passes, barriers, bytes copied, pipelines created, blocks made); +cumulative counts (submissions, passes, barriers, bytes copied, pipelines created, blocks made, +first-use waits, kernels lowered and kernels read from the cache directory); `gauges()` are live counts per kind of resource, every one zero after teardown. They are relaxed atomics, always on. @@ -199,7 +203,8 @@ that touch blocks first. - Presenting (the binary semaphore a command buffer signals for a present) comes with presenting. - An indirect dispatch's threadgroup counts are the GPU's to read, so a count above the device's `maxComputeWorkGroupCount` is not refused; Vulkan leaves such a dispatch undefined. A direct - dispatch past it is refused (`Limit::GroupCount`), where Metal's grids go further. + dispatch past it is split into dispatches of at most that many, each told its first + threadgroup. - `setBytes` takes up to 64 KiB, one ring chunk (`Limit::BytesLength`). ## Compute encoders @@ -235,25 +240,63 @@ that touch blocks first. - `Device::new_compute_pipeline_state(&ComputePipelineDescriptor)` is `newComputePipelineStateWithDescriptor:options:reflection:error:` without reflection. The translator compiles the kernel on the calling thread, which waits for it, within its 20-second - budget, for what device creation enabled and under its identity domains: each buffer argument - is the guest address of the bound buffer plus its offset, pushed. A refusal of the translator is - `Error::Translation`. + budget per lowering, for what device creation enabled and under its identity domains: each + buffer argument is the guest address of the bound buffer plus its offset, pushed. A refusal of + the translator is `Error::Translation`. +- Every kernel is lowered first as its partial-threadgroups variant. A kernel that does not + observe its threadgroup partition (it holds no threadgroup memory, barrier, fence or atomic of + threadgroup or SIMD-group scope, SIMD-group or quad function, and reads no builtin of the + partition; the translator decides from its AIR) keeps that module alone: every direct dispatch + runs in tiles of 256 threads, 256 by 1 for a grid 256 threads wide or wider and, for a narrower + one, as wide as the grid rounded down to a power of two, so at most nine `VkPipeline`s; the + 256-wide one is made with the state. An indirect dispatch runs at its own threadgroup size. A + kernel that observes its partition is lowered a second time, plainly: its whole grids, + `dispatch_threadgroups` and indirect dispatches run that module at their own size, and a + `dispatch_threads` grid that is not a whole number of threadgroups runs the variant. - The dispatch region (two `uvec4`) gives every direct dispatch's kernel Metal's grid: its first threadgroup (0), the threadgroup size packed as `(x-1) | (y-1) << 10 | (z-1) << 20`, and Metal's threads per grid; an indirect dispatch pushes a zero grid, and its kernel takes the grid from its threadgroup count. -- A state makes one `VkPipeline` per threadgroup size and threadgroup memory lengths, on the - encoding thread that first dispatches with them, which waits for it. Nothing the runtime records +- A state makes one `VkPipeline` per module, threadgroup size and threadgroup memory lengths, on + the encoding thread that first dispatches with them, which waits for it. Nothing the runtime records depends on when a compile finishes: there is one recorded form, made after the wait. Each such wait is counted in `Metrics::first_use_waits`, with its time in `first_use_wait_nanos` and the longest in `first_use_wait_max_nanos`. - `ComputePipelineState::precision_notes` carries the translator's notes of where the kernel's - answers may differ from Metal's on this device, fixed when the state is made. + answers may differ from Metal's on this device, fixed when the state is made. A kernel compiled + with fast math carries `FastMathRewrites`: a driver may fold its arithmetic differently per + `VkPipeline`, so its answers in a tile and at another size may differ in the last place. + +### The cache directory + +`DeviceOptions::pipeline_cache_dir` names a directory, made where it is missing, that the device +keeps two things in, for compute pipeline states: + +- `translations/`: each kernel lowering, named by its `FunctionCompileKey`, which covers + everything that changes the lowering: the kernel's AIR, entry, constants and linked functions, + its lowering inputs (the variant), the device profile's fingerprint and the translator's + semantics version. A state whose lowering is there reads it in place of lowering + (`Metrics::translations_loaded`, beside `Metrics::translations`); a variant the translator + refused is kept too. The files take at most 256 MiB; past it the least recently used go. +- `pipelines-`: the `VkPipelineCache` data, which the driver keys by each + pipeline's module and specialization. Every `VkPipeline` is made through the device's + `VkPipelineCache`, which starts from this file. The reaper writes it once a `VkPipeline` was + made and 10 seconds have passed since the last write, and the device's end writes it a last + time. Data past 256 MiB is not written, and a file past it is not read: the cache starts empty. + +Each write is a temporary file renamed over its name, and each file checks itself (the +translator's self-checking encoding, the pipeline data's checksum), so a file cut short is a +miss. A failed read or write is a miss too, and never fails a call. Devices open on one directory +share its files, each keeping the cap over the files it knows. With no directory, nothing is kept +on disk; the `VkPipelineCache` still serves the device's own pipelines. ### Known gaps of pipeline states -- Each call translates anew: no cache returns a state made before, and no translation or - `VkPipeline` compile runs ahead of the call or the dispatch that needs it. +- No translation or `VkPipeline` compile runs ahead of the call or the dispatch that needs it: a + state reads only its lowerings from the cache directory, and each `VkPipeline` past the first + tile is made at its first dispatch, through the pipeline data. +- A kernel that observes its threadgroup partition is lowered twice at creation (its variant and + its plain module); the second lowering's time is unmeasured. - A kernel that reads anything the encoder does not supply yet, a texture, a sampler, a function table, a `[[stage_in]]` fetch or constant data, is refused (`Gap::KernelInput`). So is a state for indirect command buffers (`Gap::IndirectCommandBuffers`). @@ -262,9 +305,15 @@ that touch blocks first. threadgroups of whole SIMD groups; a dispatch of another size is refused (`Gap::PartialSimdgroups`): its emulated-SIMD-group variant is not built. - `dispatch_threads` with a grid that is not a whole number of threadgroups on some axis is - refused (`Gap::PartialThreadgroups`): Metal's partial threadgroups are not built. -- A kernel runs at the threadgroup size each dispatch gives. Every size makes its own - `VkPipeline`, even for a kernel that does not observe its size. + refused (`Gap::PartialThreadgroups`) for a kernel that observes its threadgroup partition and + whose partial-threadgroups variant the translator refuses. It refuses the variant of a kernel + whose SIMD groups it emulates: one with SIMD-group operations where the device's compute + subgroups are neither 32 lanes nor 64 or 128 split into 32-lane clusters, and one with a + lockstep pair in divergent flow where the device lacks `VK_KHR_shader_maximal_reconvergence`. + It refuses the variant of a kernel whose barriers in a loop need a vote word that does not fit + beside its threadgroup memory in `maxComputeSharedMemorySize`. +- A kernel that observes its threadgroup partition makes a `VkPipeline` per threadgroup size it + is dispatched at. - A dispatch of a size other than the descriptor's `requiredThreadsPerThreadgroup`, which Metal's validation stops, runs at the size it gives. diff --git a/crates/metal2vulkan-rt/src/cache.rs b/crates/metal2vulkan-rt/src/cache.rs new file mode 100644 index 000000000..5ae0a2dbe --- /dev/null +++ b/crates/metal2vulkan-rt/src/cache.rs @@ -0,0 +1,350 @@ +//! The device's caches on disk, under [`DeviceOptions::pipeline_cache_dir`]: a kernel lowered and +//! a `VkPipeline` compiled in one run cost little in the next. Compute pipelines only. +//! +//! - `translations/`: one file per lowered kernel, named by the hex of its `FunctionCompileKey`, +//! which covers everything that changes the lowering's output: the kernel's AIR, entry, +//! constants and linked functions, its lowering inputs (the variant), the device profile's +//! fingerprint and the translator's semantics version. The bytes are the translator's +//! self-checking encoding (`CompiledFunction::to_bytes`), and bytes that do not decode for the +//! key are a miss. A partial-threadgroups variant the translator refused is kept too, as a +//! marker. The files take at most [`TRANSLATION_BYTES`]; past it the least recently used +//! go. +//! - `pipelines-`: the device's `VkPipelineCache` data, which the driver keys by +//! each pipeline's module and specialization. It is loaded with the device, unless it is past +//! [`PIPELINE_BYTES`] or does not check, when the cache starts empty; it is written on the reaper +//! thread once a `VkPipeline` was made and [`SAVE_INTERVAL`] has passed since the last write, so +//! a run that is killed loses at most that, and at the device's end. +//! +//! Every write is a temporary file renamed over its name, and every file checks itself (the +//! translator's encoding, the pipeline data's checksum), so a file cut short by a crash is a miss. +//! A failed read or write is a miss too: the caches never fail a call. Devices open on one +//! directory share its files, each keeping the cap over the files it knows. +//! +//! [`DeviceOptions::pipeline_cache_dir`]: crate::DeviceOptions::pipeline_cache_dir + +use crate::device::lock; +use ash::vk; +use std::collections::BTreeMap; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::Mutex; +use std::time::{Duration, Instant, SystemTime}; + +/// The most bytes of lowered kernels a cache directory keeps. +pub(crate) const TRANSLATION_BYTES: u64 = 256 << 20; +/// The most bytes of pipeline data loaded and written. +pub(crate) const PIPELINE_BYTES: u64 = 256 << 20; +/// The least time between two writes of the pipeline data. +pub(crate) const SAVE_INTERVAL: Duration = Duration::from_secs(10); +/// How old a temporary file left by a run that ended mid-write is before it is removed. +const STALE: Duration = Duration::from_secs(3600); +/// The first bytes of a pipeline data file, before its length and its checksum. +const MAGIC: &[u8; 8] = b"m2vpipe1"; +/// What a translation file holds where the translator refused the lowering: bytes no lowering +/// encodes to, and that a file cut short is not. +const REFUSED: &[u8] = b"m2v-refused"; + +/// A directory of files of at most `cap` bytes in all, the least recently used going first. +pub(crate) struct Store { + dir: PathBuf, + cap: u64, + /// Each file by name: its length and when it was last used, in `clock`'s ticks. + files: BTreeMap, + total: u64, + clock: u64, +} + +impl Store { + /// The store in `dir`, made where it is missing, with the files a run before left, the + /// least recently written first, evicted down to `cap`. + pub(crate) fn open(dir: PathBuf, cap: u64) -> Store { + let _ = fs::create_dir_all(&dir); + let now = SystemTime::now(); + let mut found = Vec::new(); + for entry in fs::read_dir(&dir).into_iter().flatten().flatten() { + let (Ok(meta), Ok(name)) = (entry.metadata(), entry.file_name().into_string()) else { + continue; + }; + let written = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH); + if !meta.is_file() { + continue; + } + if is_name(&name) { + found.push((written, name, meta.len())); + } else if now.duration_since(written).is_ok_and(|age| age > STALE) { + let _ = fs::remove_file(entry.path()); + } + } + found.sort(); + let mut store = Store { + dir, + cap, + files: BTreeMap::new(), + total: 0, + clock: 0, + }; + for (_, name, len) in found { + store.clock += 1; + store.total += len; + store.files.insert(name, (len, store.clock)); + } + store.evict(); + store + } + + /// The bytes of `name`, where the directory holds it: one this store wrote or found when it + /// opened, or one another device on the directory wrote since. + pub(crate) fn get(&mut self, name: &str) -> Option> { + let read = fs::read(self.dir.join(name)); + self.forget(name); + let bytes = read.ok()?; + self.clock += 1; + self.files + .insert(name.to_owned(), (bytes.len() as u64, self.clock)); + self.total += bytes.len() as u64; + self.evict(); + Some(bytes) + } + + /// Keeps `bytes` as `name`, evicting the least recently used files past the cap. + pub(crate) fn put(&mut self, name: &str, bytes: &[u8]) { + let len = bytes.len() as u64; + if len > self.cap || write_whole(&self.dir.join(name), bytes).is_err() { + return; + } + self.forget(name); + self.clock += 1; + self.files.insert(name.to_owned(), (len, self.clock)); + self.total += len; + self.evict(); + } + + /// Whether the directory holds `bytes` as `name`, reading the file only where its length is + /// theirs. + pub(crate) fn holds(&mut self, name: &str, bytes: &[u8]) -> bool { + fs::metadata(self.dir.join(name)).is_ok_and(|meta| meta.len() == bytes.len() as u64) + && self.get(name).is_some_and(|held| held == bytes) + } + + /// The bytes the store holds. + #[cfg(test)] + pub(crate) fn total(&self) -> u64 { + self.total + } + + fn evict(&mut self) { + while self.total > self.cap { + let Some(oldest) = self + .files + .iter() + .min_by_key(|(_, &(_, used))| used) + .map(|(name, _)| name.clone()) + else { + break; + }; + let _ = fs::remove_file(self.dir.join(&oldest)); + self.forget(&oldest); + } + } + + fn forget(&mut self, name: &str) { + if let Some((len, _)) = self.files.remove(name) { + self.total -= len; + } + } +} + +/// A file name the store keeps: 64 lowercase hex digits, a SHA-256's. +fn is_name(name: &str) -> bool { + name.len() == 64 + && name + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +/// The lowercase hex of `bytes`. +pub(crate) fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +/// Writes `bytes` to `path` through a temporary file beside it, named for this process and this +/// write, then renamed over it. +fn write_whole(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + static WRITES: AtomicU64 = AtomicU64::new(0); + let mut temp = path.as_os_str().to_owned(); + temp.push(format!( + ".{}.{}.tmp", + std::process::id(), + WRITES.fetch_add(1, Relaxed) + )); + let temp = PathBuf::from(temp); + let written = fs::File::create(&temp).and_then(|mut file| file.write_all(bytes)); + match written.and_then(|()| fs::rename(&temp, path)) { + Ok(()) => Ok(()), + Err(error) => { + let _ = fs::remove_file(&temp); + Err(error) + } + } +} + +/// FNV-1a over `bytes`: the pipeline data file's check that it was written whole. +fn checksum(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, &byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3) + }) +} + +/// The pipeline data a file holds: its bytes after the magic, their length and their checksum, +/// where all three check. +pub(crate) fn unframe(file: &[u8]) -> Option<&[u8]> { + let (magic, rest) = file.split_first_chunk::<8>()?; + let (len, rest) = rest.split_first_chunk::<8>()?; + let (sum, data) = rest.split_first_chunk::<8>()?; + (magic == MAGIC + && u64::from_le_bytes(*len) == data.len() as u64 + && u64::from_le_bytes(*sum) == checksum(data)) + .then_some(data) +} + +/// `data` framed for its file. +pub(crate) fn frame(data: &[u8]) -> Vec { + let mut file = Vec::with_capacity(24 + data.len()); + file.extend_from_slice(MAGIC); + file.extend_from_slice(&(data.len() as u64).to_le_bytes()); + file.extend_from_slice(&checksum(data).to_le_bytes()); + file.extend_from_slice(data); + file +} + +/// A device's caches. +pub(crate) struct Caches { + translations: Option>, + /// The pipeline data's file, where there is a directory. + pipelines: Option, + /// Every `VkPipeline` of the device is made through it. + pub(crate) pipeline_cache: vk::PipelineCache, + save: Mutex, +} + +/// When the pipeline data was last written, and whether a `VkPipeline` was made since. +struct Save { + last: Instant, + made: bool, +} + +impl Caches { + /// The caches of a device whose pipeline data is keyed by `uuid`, in `dir` where there is + /// one: its `VkPipelineCache` made from the data a run before wrote. + /// + /// # Safety + /// + /// `device` is live. + pub(crate) unsafe fn new( + device: &ash::Device, + dir: Option<&Path>, + uuid: [u8; vk::UUID_SIZE], + ) -> Result { + let translations = + dir.map(|dir| Mutex::new(Store::open(dir.join("translations"), TRANSLATION_BYTES))); + let pipelines = dir.map(|dir| dir.join(format!("pipelines-{}", hex(&uuid)))); + let loaded = pipelines + .as_ref() + .filter(|path| fs::metadata(path).is_ok_and(|meta| meta.len() <= PIPELINE_BYTES + 24)) + .and_then(|path| fs::read(path).ok()); + let data = loaded.as_deref().and_then(unframe).unwrap_or_default(); + let info = vk::PipelineCacheCreateInfo::default().initial_data(data); + // SAFETY: the caller's contract; `data` is empty or what `vkGetPipelineCacheData` gave, + // whole, as its checksum shows. + let pipeline_cache = unsafe { device.create_pipeline_cache(&info, None) }?; + Ok(Caches { + translations, + pipelines, + pipeline_cache, + save: Mutex::new(Save { + last: Instant::now(), + made: false, + }), + }) + } + + /// The bytes kept for a lowered kernel of key digest `key`. + pub(crate) fn translation(&self, key: &[u8]) -> Option> { + lock(self.translations.as_ref()?).get(&hex(key)) + } + + /// Keeps the bytes of a lowered kernel of key digest `key`. + pub(crate) fn keep_translation(&self, key: &[u8], bytes: &[u8]) { + if let Some(store) = &self.translations { + lock(store).put(&hex(key), bytes); + } + } + + /// Whether the translator refused the lowering of key digest `key` on a device before. + pub(crate) fn refused(&self, key: &[u8]) -> bool { + self.translations + .as_ref() + .is_some_and(|store| lock(store).holds(&hex(key), REFUSED)) + } + + /// Keeps the translator's refusal of the lowering of key digest `key`. + pub(crate) fn keep_refusal(&self, key: &[u8]) { + self.keep_translation(key, REFUSED); + } + + /// Notes a `VkPipeline` made: true where it is the first since the pipeline data's last + /// write, when the reaper is to be woken to time the next. + pub(crate) fn made(&self) -> bool { + if self.pipelines.is_none() { + return false; + } + let mut save = lock(&self.save); + let first = !save.made; + save.made = true; + first + } + + /// How long until the pipeline data is due, where a `VkPipeline` was made since its last + /// write. + pub(crate) fn due_in(&self) -> Option { + let save = lock(&self.save); + save.made + .then(|| SAVE_INTERVAL.saturating_sub(save.last.elapsed())) + } + + /// Writes the pipeline data, where a `VkPipeline` was made since its last write. + pub(crate) fn save(&self, device: &ash::Device) { + let Some(path) = &self.pipelines else { + return; + }; + { + let mut save = lock(&self.save); + if !save.made { + return; + } + save.made = false; + save.last = Instant::now(); + } + // SAFETY: the cache is the device's, and stays until the device's end, which writes it + // last. + let Ok(data) = (unsafe { device.get_pipeline_cache_data(self.pipeline_cache) }) else { + return; + }; + if data.len() as u64 <= PIPELINE_BYTES { + let _ = write_whole(path, &frame(&data)); + } + } + + /// Writes the pipeline data a last time and destroys the cache. + /// + /// # Safety + /// + /// No pipeline is being made from the cache, and none will be. + pub(crate) unsafe fn destroy(&self, device: &ash::Device) { + self.save(device); + // SAFETY: the caller's contract. + unsafe { device.destroy_pipeline_cache(self.pipeline_cache, None) }; + } +} diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 4681ce921..e8026acef 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -17,6 +17,10 @@ pub(crate) enum Metric { PipelinesCreated, /// [`Metrics::blocks_made`]. BlocksMade, + /// [`Metrics::translations`]. + Translations, + /// [`Metrics::translations_loaded`]. + TranslationsLoaded, } /// A gauge the runtime moves. @@ -55,6 +59,8 @@ struct Atomics { first_use_wait_nanos: AtomicU64, first_use_wait_max_nanos: AtomicU64, blocks_made: AtomicU64, + translations: AtomicU64, + translations_loaded: AtomicU64, buffers: AtomicU64, textures: AtomicU64, samplers: AtomicU64, @@ -82,6 +88,8 @@ impl Counters { Metric::Barriers => &a.barriers, Metric::PipelinesCreated => &a.pipelines_created, Metric::BlocksMade => &a.blocks_made, + Metric::Translations => &a.translations, + Metric::TranslationsLoaded => &a.translations_loaded, }; atomic.fetch_add(1, Relaxed); } @@ -129,6 +137,8 @@ impl Counters { first_use_wait_nanos: a.first_use_wait_nanos.load(Relaxed), first_use_wait_max_nanos: a.first_use_wait_max_nanos.load(Relaxed), blocks_made: a.blocks_made.load(Relaxed), + translations: a.translations.load(Relaxed), + translations_loaded: a.translations_loaded.load(Relaxed), } } @@ -178,6 +188,11 @@ pub struct Metrics { /// `VkDeviceMemory` allocations made: pooled and dedicated blocks, the zero source and the /// parameter ring's blocks, and later image blocks. pub blocks_made: u64, + /// Kernels the translator lowered, each a pipeline state's module: one for a kernel that does + /// not observe its threadgroup partition, two for one that does. + pub translations: u64, + /// Lowered kernels a pipeline state took from the cache directory in place of a lowering. + pub translations_loaded: u64, } /// No Metal counterpart: the live count of each kind of resource. Every one is zero once the diff --git a/crates/metal2vulkan-rt/src/device.rs b/crates/metal2vulkan-rt/src/device.rs index 9590eada3..853e77554 100644 --- a/crates/metal2vulkan-rt/src/device.rs +++ b/crates/metal2vulkan-rt/src/device.rs @@ -1,6 +1,7 @@ //! The device: one `VkDevice` for every command queue, every guest process and the compositor; //! its queues, its memory blocks, its threads, quiesce and teardown. +use crate::cache::Caches; use crate::complete::{self, Done}; use crate::counters::{Counters, Gauge}; use crate::error::Error; @@ -23,6 +24,7 @@ use metal2vulkan::device::{ use std::cell::Cell; use std::collections::HashMap; use std::ffi::{c_char, CString}; +use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::thread::{self, JoinHandle}; @@ -158,6 +160,8 @@ pub(crate) struct Core { pub(crate) ids: Ids, /// The translator, for what device creation enables, under the identity domains. pub(crate) translator: metal2vulkan::device::Device, + /// The lowered kernels on disk and the `VkPipelineCache` every pipeline is made through. + pub(crate) caches: Caches, /// Quiesced or torn down: calls that need a thread are refused. closed: AtomicBool, /// [`RUNNING`], [`HALTING`], or the answer of the stop that ran. @@ -194,6 +198,16 @@ pub struct DeviceOptions { /// Vulkan features the consumer needs for its own raw Vulkan work, each enabled where the /// device reports it ([`Device::features`]). pub features: Vec, + /// The directory the device keeps compute kernels it lowered and its compiled pipeline data + /// in, made where it is missing, so a later device on it, in this run or the next, takes + /// them in place of lowering and compiling again ([`Metrics::translations_loaded`]). Each + /// kind is bounded at 256 MiB, the least recently used kernels going first past it; a file + /// that does not check, or a failed read or write, is a miss and never fails a call. `None` + /// keeps nothing on disk. Metal keeps its compiled shaders in a system cache the program does + /// not name. + /// + /// [`Metrics::translations_loaded`]: crate::Metrics::translations_loaded + pub pipeline_cache_dir: Option, } /// Takes a lock. A panic while another thread held it leaves what it guards usable (a queue, the @@ -288,6 +302,27 @@ impl Device { let device = unsafe { vk_instance.create_device(raw, &info, None) } .map_err(Error::vulkan("vkCreateDevice"))?; drop(links); + let mut vulkan11 = vk::PhysicalDeviceVulkan11Properties::default(); + let mut vulkan13 = vk::PhysicalDeviceVulkan13Properties::default(); + let mut properties = vk::PhysicalDeviceProperties2::default() + .push_next(&mut vulkan11) + .push_next(&mut vulkan13); + // SAFETY: as for the floor check; the device is Vulkan 1.3, which defines both structures. + unsafe { vk_instance.get_physical_device_properties2(raw, &mut properties) }; + let directory = options.pipeline_cache_dir.as_deref(); + let uuid = properties.properties.pipeline_cache_uuid; + // SAFETY: the device is live. + let caches = match unsafe { Caches::new(&device, directory, uuid) } { + Ok(caches) => caches, + Err(result) => { + // SAFETY: nothing made from the device is left. + unsafe { device.destroy_device(None) }; + return Err(Error::Vulkan { + call: "vkCreatePipelineCache", + result, + }); + } + }; let counters = Counters::new(); // SAFETY: the device was made from `raw` with `capabilities.features`, and the family is // its queues' family. @@ -295,8 +330,12 @@ impl Device { let (memory_types, filler, done, layout) = match made { Ok(made) => made, Err(error) => { - // SAFETY: nothing made from the device is left. - unsafe { device.destroy_device(None) }; + // SAFETY: nothing made from the device is left but the caches, which made no + // pipeline. + unsafe { + caches.destroy(&device); + device.destroy_device(None); + } return Err(error); } }; @@ -309,13 +348,6 @@ impl Device { } else { Arc::clone(&runtime) }; - let mut vulkan11 = vk::PhysicalDeviceVulkan11Properties::default(); - let mut vulkan13 = vk::PhysicalDeviceVulkan13Properties::default(); - let mut properties = vk::PhysicalDeviceProperties2::default() - .push_next(&mut vulkan11) - .push_next(&mut vulkan13); - // SAFETY: as for the floor check; the device is Vulkan 1.3, which defines both structures. - unsafe { vk_instance.get_physical_device_properties2(raw, &mut properties) }; let unified_memory = matches!( properties.properties.device_type, vk::PhysicalDeviceType::INTEGRATED_GPU | vk::PhysicalDeviceType::CPU @@ -358,6 +390,7 @@ impl Device { ring: Ring::new(), ids: Ids::new(), translator, + caches, closed: AtomicBool::new(false), halt: AtomicU8::new(RUNNING), }); @@ -885,8 +918,10 @@ impl Drop for Core { for _ in 0..ring_blocks { self.counters.fall(Gauge::Blocks); } - // SAFETY: the device is idle, and nothing made from it is left but these objects. + // SAFETY: the device is idle, and nothing made from it is left but these objects; the + // caches write the pipeline data a last time. let zero_source = unsafe { + self.caches.destroy(&self.device); self.device.destroy_pipeline_layout(self.layout, None); self.done.destroy(&self.device); let zero_source = self.filler.destroy(&self.device); diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index b3f32687c..06f43038e 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -174,13 +174,15 @@ pub enum Gap { /// `dispatchThreads` with a grid that is not a whole number of threadgroups on some axis, of /// a kernel that observes its threadgroup partition and whose partial-threadgroups variant the /// translator refused: Metal runs the last threadgroup of such an axis with the threads left. - /// The translator refuses the variant of a kernel whose simdgroups it emulates (a lockstep - /// pair in divergent flow on a device without `VK_KHR_shader_maximal_reconvergence`), and of - /// one whose uniform barriers' vote word its workgroup memory cannot hold. Refused at the - /// dispatch; the state's whole grids run. + /// The translator refuses the variant of a kernel whose SIMD groups it emulates (SIMD-group + /// operations where the device's compute subgroups are neither 32 lanes nor 64 or 128 split + /// into 32-lane clusters, or a lockstep pair in divergent flow on a device without + /// `VK_KHR_shader_maximal_reconvergence`), and of one whose barriers in a loop need a vote + /// word its workgroup memory cannot hold. Refused at the dispatch; the state's whole grids + /// run. /// - /// Basis: ours (the translator's partial-threadgroups variant does not take emulated - /// simdgroups). + /// Basis: ours (the translator's partial-threadgroups variant does not take the emulated + /// SIMD-group tier, nor a vote word past the workgroup memory). PartialThreadgroups { /// The grid asked for. threads_per_grid: [u32; 3], diff --git a/crates/metal2vulkan-rt/src/lib.rs b/crates/metal2vulkan-rt/src/lib.rs index cdc2819fe..a8ffc18b2 100644 --- a/crates/metal2vulkan-rt/src/lib.rs +++ b/crates/metal2vulkan-rt/src/lib.rs @@ -9,6 +9,7 @@ #![warn(missing_docs)] mod buffer; +mod cache; mod command; mod complete; mod counters; diff --git a/crates/metal2vulkan-rt/src/pipeline.rs b/crates/metal2vulkan-rt/src/pipeline.rs index 06afbd162..0d98285d6 100644 --- a/crates/metal2vulkan-rt/src/pipeline.rs +++ b/crates/metal2vulkan-rt/src/pipeline.rs @@ -27,9 +27,9 @@ use ash::vk; use metal2vulkan::error::{Error as TranslationError, Feature}; use metal2vulkan::library::CompiledFunction; use metal2vulkan::pipeline::{ - AccessSet, Axis, BufferKind, ComputePipeline, ComputePipelineDescriptor, PrecisionNote, - PushField, PushLoc, RuntimeFact, SlotClass, SlotInterface, SlotRef, SpecKey, Stage, - StageEntries, StageSource, + AccessSet, Axis, BufferKind, ComputePipeline, ComputePipelineDescriptor, FunctionDescriptor, + LoweringInputs, PrecisionNote, PushField, PushLoc, RuntimeFact, SlotClass, SlotInterface, + SlotRef, SpecKey, Stage, StageEntries, StageSource, }; use metal2vulkan::Budget; use std::ffi::CString; @@ -186,9 +186,13 @@ impl crate::Device { /// The translator compiles the kernel on the calling thread, which waits for it, within the /// translator's 20-second budget per lowering: once for a kernel that does not observe its /// threadgroup partition, whose 256-wide tile's `VkPipeline` is made here too, and twice for - /// one that does (its partial-threadgroups variant and its plain module). Each call compiles - /// anew: no cache keeps a state made before. The state's other `VkPipeline`s are made later, - /// each by the first encoding call that needs it ([`ComputePipelineState`]). + /// one that does (its partial-threadgroups variant and its plain module). Where the device + /// has a cache directory ([`DeviceOptions::pipeline_cache_dir`]), a lowering a device made + /// before is read from it in place of lowering again, and every `VkPipeline` is made through + /// the pipeline data it keeps. The state's other `VkPipeline`s are made later, each by the + /// first encoding call that needs it ([`ComputePipelineState`]). + /// + /// [`DeviceOptions::pipeline_cache_dir`]: crate::DeviceOptions::pipeline_cache_dir /// /// Err: [`Error::Translation`], the translator's typed refusal or a descriptor Metal refuses; /// [`Gap::IndirectCommandBuffers`]; [`Gap::KernelInput`] for a kernel that reads what the @@ -216,14 +220,32 @@ impl crate::Device { .map_err(Error::Translation)?; let mut inputs = plain.clone(); inputs.partial_threadgroups = true; - let lower = |inputs| { - translator.compile_function_from_entries(function, inputs, &budget, &entries) + let lower = + |inputs: &LoweringInputs| lower(&core, function, inputs, &budget, &entries); + // The translator's refusal of the variant (emulated simdgroups, a vote word its + // workgroup memory cannot hold), kept like a lowering: the kernel keeps its plain + // module. + let variant_key = *translator.function_compile_key(function, &inputs).digest(); + let variant = if core.caches.refused(&variant_key) { + core.counters.count(Metric::TranslationsLoaded); + None + } else { + match lower(&inputs) { + Ok(variant) => Some(variant), + Err(TranslationError::Unsupported(refused)) + if refused.feature == Feature::GpuEncodedIndirectCommands => + { + core.caches.keep_refusal(&variant_key); + None + } + Err(error) => return Err(Error::Translation(error)), + } }; - match lower(&inputs) { - Ok(variant) if !variant.observes_threadgroup_partition() => { + match variant { + Some(variant) if !variant.observes_threadgroup_partition() => { (compiled(variant).map_err(Error::Translation)?, None, false) } - Ok(variant) => { + Some(variant) => { let plain = lower(&plain).and_then(compiled); let variant = compiled(variant); ( @@ -232,15 +254,10 @@ impl crate::Device { true, ) } - // The translator's refusal of the variant (emulated simdgroups, a vote word its - // workgroup memory cannot hold): the kernel keeps its plain module. - Err(TranslationError::Unsupported(refused)) - if refused.feature == Feature::GpuEncodedIndirectCommands => - { + None => { let plain = lower(&plain).and_then(compiled); (plain.map_err(Error::Translation)?, None, true) } - Err(error) => return Err(Error::Translation(error)), } } // A kernel the consumer compiled: the variant it was compiled under. @@ -298,6 +315,32 @@ impl crate::Device { } } +/// The kernel `function` lowered under `inputs`: the lowering a device kept in the cache directory +/// under its key, which covers everything that changes the output, or one made now and kept. +fn lower( + core: &Core, + function: &FunctionDescriptor, + inputs: &LoweringInputs, + budget: &Budget, + entries: &StageEntries, +) -> Result { + let translator = &core.translator; + let key = translator.function_compile_key(function, inputs); + let kept = core + .caches + .translation(key.digest()) + .and_then(|bytes| CompiledFunction::from_bytes_for_key(&bytes, &key, translator).ok()); + if let Some(kept) = kept { + core.counters.count(Metric::TranslationsLoaded); + return Ok(kept); + } + core.counters.count(Metric::Translations); + let lowered = translator.compile_function_from_entries(function, inputs, budget, entries)?; + core.caches + .keep_translation(key.digest(), &lowered.to_bytes()); + Ok(lowered) +} + /// The runtime's view of the translator's kernel, or [`Gap::KernelInput`] where the kernel reads /// something the compute encoder does not supply. fn interface( @@ -614,16 +657,19 @@ impl Kernel { .stage(stage) .layout(core.layout); let device = &core.device; - // SAFETY: the module and the layout are the device's, and the specialization gives each - // of the kernel's constants a 4-byte value. - let made = - unsafe { device.create_compute_pipelines(vk::PipelineCache::null(), &[info], None) }; + let cache = core.caches.pipeline_cache; + // SAFETY: the module, the layout and the cache are the device's, and the specialization + // gives each of the kernel's constants a 4-byte value. + let made = unsafe { device.create_compute_pipelines(cache, &[info], None) }; let pipeline = made.map_err(|(_, result)| Error::Vulkan { call: "vkCreateComputePipelines", result, })?[0]; core.counters.count(Metric::PipelinesCreated); core.counters.rise(Gauge::Pipelines); + if core.caches.made() { + core.reaper.wake(); + } Ok(pipeline) } diff --git a/crates/metal2vulkan-rt/src/reaper.rs b/crates/metal2vulkan-rt/src/reaper.rs index 642d97a72..1e9393718 100644 --- a/crates/metal2vulkan-rt/src/reaper.rs +++ b/crates/metal2vulkan-rt/src/reaper.rs @@ -1,7 +1,7 @@ -//! The reaper thread: it frees what the runtime's other threads give up, one object at a time, and -//! runs a teardown that starts on the completion thread. No driver free runs on the completion -//! thread, so no completion waits behind one, and a submission on another thread waits behind at -//! most one free. +//! The reaper thread: it frees what the runtime's other threads give up, one object at a time, runs +//! a teardown that starts on the completion thread, and writes the pipeline data to the cache +//! directory when it is due. No driver free runs on the completion thread, so no completion waits +//! behind one, and a submission on another thread waits behind at most one free. use crate::counters::Gauge; use crate::device::{lock, Core}; @@ -61,6 +61,13 @@ impl Reaper { self.changed.notify_one(); } + /// Wakes the reaper to time the pipeline data's next write. + pub(crate) fn wake(&self) { + // Taken so the wake cannot fall between the reaper's look at the caches and its wait. + drop(lock(&self.state)); + self.changed.notify_one(); + } + /// Tells the reaper to end once its queue is empty. pub(crate) fn stop(&self) { lock(&self.state).stop = true; @@ -106,28 +113,47 @@ fn free(core: &Core, object: Free) { } } -/// The reaper thread, until it is stopped and its queue is empty. +/// What the reaper does next. +enum Next { + Job(Job), + /// Write the pipeline data. + Save, +} + +/// The reaper thread, until it is stopped and its queue is empty. The device's end writes the +/// pipeline data a last time. pub(crate) fn run(core: Arc) { let reaper = &core.reaper; loop { - let job = { + let next = { let mut state = lock(&reaper.state); loop { if let Some(job) = state.jobs.pop_front() { - break job; + break Next::Job(job); } if state.stop { return; } - state = reaper - .changed - .wait(state) - .unwrap_or_else(PoisonError::into_inner); + state = match core.caches.due_in() { + Some(wait) if wait.is_zero() => break Next::Save, + Some(wait) => { + reaper + .changed + .wait_timeout(state, wait) + .unwrap_or_else(PoisonError::into_inner) + .0 + } + None => reaper + .changed + .wait(state) + .unwrap_or_else(PoisonError::into_inner), + }; } }; - match job { - Job::Free(object) => free(&core, object), - Job::Teardown(teardown) => teardown(&core), + match next { + Next::Job(Job::Free(object)) => free(&core, object), + Next::Job(Job::Teardown(teardown)) => teardown(&core), + Next::Save => core.caches.save(&core.device), } } } diff --git a/crates/metal2vulkan-rt/src/tests/cache.rs b/crates/metal2vulkan-rt/src/tests/cache.rs new file mode 100644 index 000000000..eb4c12742 --- /dev/null +++ b/crates/metal2vulkan-rt/src/tests/cache.rs @@ -0,0 +1,97 @@ +//! The cache directory on the host: a store filled past its cap keeps the most recently used +//! files within it, devices on one directory share its files, and pipeline data that does not +//! check is a miss. + +use crate::cache::{frame, unframe, Store}; +use std::fs; +use std::path::PathBuf; + +/// A directory of its own under the OS temp dir, removed when dropped. +struct Scratch(PathBuf); + +impl Scratch { + fn new(test: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("m2v-rt-{test}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + Scratch(dir) + } + + /// The bytes of every file in the directory. + fn bytes(&self) -> u64 { + fs::read_dir(&self.0) + .expect("the directory") + .map(|entry| { + entry + .expect("an entry") + .metadata() + .expect("its metadata") + .len() + }) + .sum() + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +/// A file name the store keeps: 64 hex digits. +fn name(n: u8) -> String { + format!("{n:064x}") +} + +#[test] +fn a_store_filled_past_its_cap_keeps_the_most_recently_used_within_it() { + let scratch = Scratch::new("store-cap"); + let mut store = Store::open(scratch.0.clone(), 1000); + for n in 0..10 { + store.put(&name(n), &[n; 300]); + // Read after every write, the first file stays the most recently used. + assert_eq!(store.get(&name(0)), Some(vec![0; 300]), "file 0 after {n}"); + assert!(store.total() <= 1000, "{} bytes after {n}", store.total()); + assert_eq!(scratch.bytes(), store.total(), "the disk after {n}"); + } + let kept: Vec = (0..10).map(|n| store.get(&name(n)).is_some()).collect(); + let mut want = [false; 10]; + for n in [0, 8, 9] { + want[n] = true; + } + assert_eq!(kept, want, "the files kept"); + // A file past the cap alone is not kept, and evicts nothing. + store.put(&name(10), &[10; 1001]); + assert_eq!(store.get(&name(10)), None); + assert_eq!(store.total(), 900); + // Reopened with a smaller cap, the store evicts down to it. + drop(store); + let reopened = Store::open(scratch.0.clone(), 600); + assert_eq!(reopened.total(), 600); + assert_eq!(scratch.bytes(), 600); +} + +#[test] +fn stores_on_one_directory_share_its_files() { + let scratch = Scratch::new("store-share"); + let mut first = Store::open(scratch.0.clone(), 1000); + let mut second = Store::open(scratch.0.clone(), 1000); + first.put(&name(1), b"lowered"); + assert_eq!(second.get(&name(1)), Some(b"lowered".to_vec())); + assert_eq!(second.total(), 7); + assert!(second.holds(&name(1), b"lowered")); + assert!(!second.holds(&name(1), b"refused")); + assert!(!second.holds(&name(2), b"")); +} + +#[test] +fn pipeline_data_that_does_not_check_is_a_miss() { + let data: Vec = (0..=255).collect(); + let file = frame(&data); + assert_eq!(unframe(&file), Some(&data[..])); + assert_eq!(unframe(&file[..file.len() - 1]), None, "cut short"); + let mut flipped = file.clone(); + flipped[100] ^= 1; + assert_eq!(unframe(&flipped), None, "a flipped bit"); + assert_eq!(unframe(&[]), None, "empty"); + assert_eq!(unframe(&frame(&[])), Some(&[][..]), "no data"); +} diff --git a/crates/metal2vulkan-rt/src/tests/mod.rs b/crates/metal2vulkan-rt/src/tests/mod.rs index 4f2d3661e..d3d1f6a7a 100644 --- a/crates/metal2vulkan-rt/src/tests/mod.rs +++ b/crates/metal2vulkan-rt/src/tests/mod.rs @@ -1,3 +1,4 @@ +mod cache; mod command; mod compute; mod device; diff --git a/crates/metal2vulkan-rt/src/tests/translate.rs b/crates/metal2vulkan-rt/src/tests/translate.rs index 3388e9754..007a02255 100644 --- a/crates/metal2vulkan-rt/src/tests/translate.rs +++ b/crates/metal2vulkan-rt/src/tests/translate.rs @@ -11,10 +11,12 @@ #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod on_device { - use crate::tests::command::on_device::{each_device, finished}; + use crate::tests::command::on_device::{each_device, finished, within}; + use crate::tests::devices_of_the_cfgs_kind; use crate::{ host_time, BlockId, Buffer, ComputePipelineDescriptor, ComputePipelineState, Device, - DispatchType, FunctionDescriptor, Library, MemoryClass, PrecisionNote, StageSource, + DeviceOptions, DispatchType, FunctionDescriptor, Gauges, Instance, Library, MemoryClass, + PrecisionNote, StageSource, }; use metal2vulkan::Budget; use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; @@ -653,4 +655,55 @@ mod on_device { ); }); } + + /// A device on a cache directory a device before it used lowers nothing at creation: the + /// tiling kernel's lowering and the observing kernel's two are read from the directory, and + /// the pipeline data the first device wrote at its end is there. + #[test] + fn every_device_takes_the_kernels_a_device_before_it_lowered_from_the_cache_directory() { + let (Some(tiled), Some(observing)) = ( + descriptor("a1_bool_from_float"), + descriptor("icb_replay_grid_template"), + ) else { + return; + }; + let instance = Instance::new(&[]).expect("an instance at the floor"); + let devices = devices_of_the_cfgs_kind(&instance); + assert!(!devices.is_empty(), "no device of this cfg's kind"); + for (name, physical) in &devices { + let dir = std::env::temp_dir().join(format!("m2v-rt-cache-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for round in 0..2 { + let mut options = DeviceOptions::default(); + options.pipeline_cache_dir = Some(dir.clone()); + let device = Device::new(physical, options) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let counters = device.counters(); + let states = [ + state(name, &device, &tiled), + state(name, &device, &observing), + ]; + let metrics = counters.metrics(); + let counted = (metrics.translations, metrics.translations_loaded); + // One lowering for the tiling kernel, two for the observing one. + let want = [(3, 0), (0, 3)][round]; + assert_eq!(counted, want, "{name}: device {round} on the directory"); + drop(states); + drop(device); + within("the teardown", || counters.gauges() == Gauges::default()); + } + let written = std::fs::read_dir(&dir) + .expect("the cache directory") + .flatten() + .any(|entry| { + entry + .file_name() + .to_string_lossy() + .starts_with("pipelines-") + }); + let _ = std::fs::remove_dir_all(&dir); + assert!(written, "{name}: the pipeline data"); + println!("{name}: 3 lowerings, none on a second device on the directory"); + } + } } diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index f702bf4d5..9b538e536 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1156,6 +1156,7 @@ const metal2vulkan::cache::SOURCE_DIGEST pub const SOURCE_DIGEST: &str const metal2vulkan::device::NVIDIA_AMPERE_GA10X pub const NVIDIA_AMPERE_GA10X: &[u32] const metal2vulkan::metal::sampler::NOT_MIPMAPPED_MAX_LOD pub const NOT_MIPMAPPED_MAX_LOD: f32 const metal2vulkan::metal::vertex::MAX_VERTEX_ALIGNMENT pub const MAX_VERTEX_ALIGNMENT: u32 +const metal2vulkan::pipeline::NONUNIFORM pub const NONUNIFORM: u32 const-value metal2vulkan-air::bitstream::BLOCKINFO_BLOCK_ID 0 const-value metal2vulkan-air::bitstream::TOP_LEVEL_ABBREV_WIDTH 2 const-value metal2vulkan-air::budget::BITSTREAM_NESTING 64 @@ -1249,6 +1250,7 @@ const-value metal2vulkan::cache::SOURCE_DIGEST env!("M2V_SOURCE_DIGEST") const-value metal2vulkan::device::NVIDIA_AMPERE_GA10X &[0x2200, 0x2203, 0x2204, 0x2205, 0x2206, 0x2207, 0x2208, 0x220a, 0x220d, 0x2216, 0x222b, 0x222f, 0x2230, 0x2231, 0x2232, 0x2233, 0x2235, 0x2236, 0x2237, 0x2238, 0x223f, 0x2414, 0x2420, 0x2438, 0x2460, 0x2480, 0x2482, 0x2483, 0x2484, 0x2486, 0x2487, 0x2488, 0x2489, 0x248a, 0x248c, 0x248d, 0x248e, 0x249c, 0x249d, 0x249f, 0x24a0, 0x24a4, 0x24ac, 0x24ad, 0x24af, 0x24b0, 0x24b1, 0x24b6, 0x24b7, 0x24b8, 0x24b9, 0x24ba, 0x24bb, 0x24bf, 0x24c0, 0x24c7, 0x24c8, 0x24c9, 0x24dc, 0x24dd, 0x24df, 0x24e0, 0x24fa, 0x2501, 0x2503, 0x2504, 0x2505, 0x2507, 0x2508, 0x2509, 0x2520, 0x2521, 0x2523, 0x252f, 0x2531, 0x2544, 0x2560, 0x2561, 0x2563, 0x2571, 0x2582, 0x2583, 0x2584, 0x25a0, 0x25a2, 0x25a3, 0x25a4, 0x25a5, 0x25a6, 0x25a7, 0x25a9, 0x25aa, 0x25ab, 0x25ac, 0x25ad, 0x25af, 0x25b0, 0x25b2, 0x25b5, 0x25b6, 0x25b8, 0x25b9, 0x25ba, 0x25bb, 0x25bc, 0x25bd, 0x25e0, 0x25e2, 0x25e5, 0x25ec, 0x25ed, 0x25f9, 0x25fa, 0x25fb] const-value metal2vulkan::metal::sampler::NOT_MIPMAPPED_MAX_LOD 0.25 const-value metal2vulkan::metal::vertex::MAX_VERTEX_ALIGNMENT 4 +const-value metal2vulkan::pipeline::NONUNIFORM 1 enum metal2vulkan-air::abi::AbiHandle #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum AbiHandle enum metal2vulkan-air::abi::AbiInt #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum AbiInt enum metal2vulkan-air::abi::AccelerationStructureKind #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum AccelerationStructureKind @@ -2225,6 +2227,7 @@ field metal2vulkan-rt::ComputePipelineDescriptor.threadgroup_size_is_multiple_of field metal2vulkan-rt::DeviceOptions.block_mappings pub block_mappings: Option> field metal2vulkan-rt::DeviceOptions.extensions pub extensions: Vec field metal2vulkan-rt::DeviceOptions.features pub features: Vec +field metal2vulkan-rt::DeviceOptions.pipeline_cache_dir pub pipeline_cache_dir: Option field metal2vulkan-rt::FunctionDescriptor.constants pub constants: FunctionConstantValues field metal2vulkan-rt::FunctionDescriptor.function pub function: Function field metal2vulkan-rt::FunctionDescriptor.libraries pub libraries: DynamicLibraries @@ -2247,6 +2250,8 @@ field metal2vulkan-rt::Metrics.first_use_waits pub first_use_waits: u64 field metal2vulkan-rt::Metrics.passes pub passes: u64 field metal2vulkan-rt::Metrics.pipelines_created pub pipelines_created: u64 field metal2vulkan-rt::Metrics.submissions pub submissions: u64 +field metal2vulkan-rt::Metrics.translations pub translations: u64 +field metal2vulkan-rt::Metrics.translations_loaded pub translations_loaded: u64 field metal2vulkan-rt::RawDevice.device pub device: &'a ash::Device field metal2vulkan-rt::RawDevice.instance pub instance: &'a ash::Instance field metal2vulkan-rt::RawDevice.physical_device pub physical_device: vk::PhysicalDevice @@ -5950,6 +5955,8 @@ fn metal2vulkan::metal::vertex::vertex_alignment pub fn vertex_alignment(format: fn metal2vulkan::metal::vertex::vk_vertex_format pub fn vk_vertex_format(format: VertexFormat) -> Result fn metal2vulkan::pipeline::heap_sampler_capacity pub fn heap_sampler_capacity(p: &DeviceProfile) -> u32 fn metal2vulkan::pipeline::heap_unused_while_pending pub fn heap_unused_while_pending(p: &DeviceProfile) -> bool +fn metal2vulkan::pipeline::nonuniform_region_bytes pub fn nonuniform_region_bytes(base: [u32; 3], threads: [u32; 3], l: [u32; 3]) -> Option<[u8; 32]> +fn metal2vulkan::pipeline::region_bytes pub fn region_bytes(base: [u32; 3], threads: [u32; 3], l: [u32; 3]) -> Option<[u8; 32]> macro-decl metal2vulkan-air::ir::ArgIdx ir_id! ArgIdx macro-decl metal2vulkan-air::ir::BlockId id_type! BlockId macro-decl metal2vulkan-air::ir::BlockId ir_id! BlockId @@ -8785,6 +8792,7 @@ method metal2vulkan-rt::ComputeCommandEncoder::set_bytes pub fn set_bytes(&mut s method metal2vulkan-rt::ComputeCommandEncoder::set_compute_pipeline_state pub fn set_compute_pipeline_state(&mut self, state: &ComputePipelineState) -> Result<(), Error> method metal2vulkan-rt::ComputeCommandEncoder::set_threadgroup_memory_length pub fn set_threadgroup_memory_length(&mut self, length: u32, index: u32) -> Result<(), Error> method metal2vulkan-rt::ComputeCommandEncoder::use_resource pub fn use_resource(&mut self, resource: Resource<'_>, usage: ResourceUsage) -> Result<(), Error> +method metal2vulkan-rt::ComputePipelineDescriptor::lowering_inputs pub fn lowering_inputs(&self) -> LoweringInputs method metal2vulkan-rt::ComputePipelineDescriptor::new pub fn new(kernel: StageSource) -> ComputePipelineDescriptor method metal2vulkan-rt::ComputePipelineDescriptor::reflection pub fn reflection(&self, budget: &crate::Budget) -> Result method metal2vulkan-rt::ComputePipelineDescriptor::slot_writes pub fn slot_writes(&self, budget: &crate::Budget) -> Result @@ -10502,6 +10510,7 @@ method metal2vulkan::pipeline::CommandWrites::writes_kinds pub const fn writes_k method metal2vulkan::pipeline::ComputePipeline::content_digest pub fn content_digest(&self) -> Hash256 method metal2vulkan::pipeline::ComputePipeline::footprint pub fn footprint(&self) -> u64 method metal2vulkan::pipeline::ComputePipeline::plan pub fn plan(&self, device: &Device, shape: &BindShape) -> Result +method metal2vulkan::pipeline::ComputePipelineDescriptor::lowering_inputs pub fn lowering_inputs(&self) -> LoweringInputs method metal2vulkan::pipeline::ComputePipelineDescriptor::new pub fn new(kernel: StageSource) -> ComputePipelineDescriptor method metal2vulkan::pipeline::ComputePipelineDescriptor::reflection pub fn reflection(&self, budget: &crate::Budget) -> Result method metal2vulkan::pipeline::ComputePipelineDescriptor::slot_writes pub fn slot_writes(&self, budget: &crate::Budget) -> Result @@ -12763,7 +12772,6 @@ variant metal2vulkan-rt::Gap::PartialThreadgroups PartialThreadgroups { threads_ variant metal2vulkan-rt::Limit::BlockIds BlockIds variant metal2vulkan-rt::Limit::BlockLen BlockLen { len: u64, max: u64 } variant metal2vulkan-rt::Limit::BytesLength BytesLength { len: u64, max: u64 } -variant metal2vulkan-rt::Limit::GroupCount GroupCount { count: [u32; 3], max: [u32; 3] } variant metal2vulkan-rt::Limit::ThreadgroupShape ThreadgroupShape { size: [u32; 3], max: [u32; 3] } variant metal2vulkan-rt::MemoryClass::Private Private variant metal2vulkan-rt::MemoryClass::Shared Shared diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index f73291e02..a948f4fe4 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -333,6 +333,9 @@ surface! { "pipeline" => metal2vulkan::pipeline { fn heap_sampler_capacity; fn heap_unused_while_pending; + fn region_bytes; + fn nonuniform_region_bytes; + const NONUNIFORM; struct ComputePipeline N; struct ComputePipelineMetalInfo N; struct CompileReport N; diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index add8ab96d..8d4802c7d 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -38,7 +38,7 @@ Columns: | What a call did wrong, in detail | 174 | 157 | 0 | 0 | 0 | 0 | 0 | | Devices below the new runtime's floor | 6 | 6 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Refusal` | 11 | 11 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Limit` | 5 | 5 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Limit` | 4 | 4 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Gap` | 4 | 4 | 0 | 0 | 0 | 0 | 0 | ## Totals by basis @@ -56,7 +56,7 @@ Columns: | What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 | | Devices below the new runtime's floor | 0 | 0 | 0 | 6 | 0 | 0 | 0 | 0 | | The new runtime's `Refusal` | 2 | 5 | 0 | 0 | 4 | 0 | 0 | 0 | -| The new runtime's `Limit` | 0 | 0 | 0 | 3 | 2 | 0 | 0 | 0 | +| The new runtime's `Limit` | 0 | 0 | 0 | 2 | 2 | 0 | 0 | 0 | | The new runtime's `Gap` | 0 | 0 | 0 | 0 | 4 | 0 | 0 | 0 | ## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`) @@ -621,7 +621,7 @@ Columns: | `NoPipeline` | A dispatch with no pipeline state set | every device (a public call's own check of its arguments) | `metal-documented`: a compute dispatch needs a compute pipeline state set first | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | | `BufferIndex` | A buffer argument index past Metal's 31 entries (`setBuffer`, `setBytes`, `setBufferOffset`, `setThreadgroupMemoryLength`) | every device (a public call's own check of its arguments) | `metal-documented`: the buffer argument table has 31 entries per stage | 1: `crates/metal2vulkan-rt/src/encoder.rs (slot)` | `-` | | `NoBufferAtIndex` | `setBufferOffset` at an index where no buffer is bound | every device (a public call's own check of its arguments) | `ours`: there is no buffer whose offset to change | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)` | `-` | -| `ThreadgroupSize` | A threadgroup of no threads, or of more than the pipeline state's `maxTotalThreadsPerThreadgroup` | every device (a public call's own check of its arguments) | `metal-documented`: a threadgroup's threads total at most the state's `maxTotalThreadsPerThreadgroup` | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | +| `ThreadgroupSize` | A threadgroup of no threads, or of more than the pipeline state's `maxTotalThreadsPerThreadgroup` | every device (a public call's own check of its arguments) | `metal-documented`: a threadgroup's threads total at most the state's `maxTotalThreadsPerThreadgroup` | 2: `crates/metal2vulkan-rt/src/encoder.rs (dispatch, 2 sites)` | `-` | | `IndirectOffset` | An indirect dispatch's argument offset that is not a multiple of 4, or that leaves fewer than 12 bytes (three 32-bit counts) in the buffer | every device (a public call's own check of its arguments) | `ours`: `vkCmdDispatchIndirect` reads three 32-bit counts at a 4-byte aligned offset inside the buffer | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)` | `-` | ## 12. The new runtime's `Limit` (`Error::Limit(Limit)`) @@ -630,7 +630,6 @@ Columns: |---|---|---|---|---|---| | `BlockLen` | A block longer than one allocation and one buffer hold on the device (`Device::take_block` past `maxMemoryAllocationSize` or `maxBufferSize`) | at the device's limit | `device`: the device's `maxMemoryAllocationSize` and `maxBufferSize` | 1: `crates/metal2vulkan-rt/src/memory.rs (dedicated_len)` | `-` | | `BlockIds` | A block after every block number has been used (`Device::take_block`) | every device (a public call's own check of its arguments) | `ours`: block numbers are 32 bits | 1: `crates/metal2vulkan-rt/src/memory.rs (number)` | `-` | -| `GroupCount` | A dispatch of more threadgroups on an axis than the device's `maxComputeWorkGroupCount` | at the device's limit | `device`: the device's `maxComputeWorkGroupCount` | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | | `ThreadgroupShape` | A threadgroup longer on an axis than the device's `maxComputeWorkGroupSize` (the floor holds 1,024 by 1,024 by 64) | at the device's limit | `device`: the device's `maxComputeWorkGroupSize` | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | | `BytesLength` | `setBytes` data longer than one parameter ring chunk | every device (a public call's own check of its arguments) | `ours`: a ring chunk is 64 KiB | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_bytes)` | `-` | @@ -641,7 +640,7 @@ Columns: | `IndirectCommandBuffers` | A compute pipeline state for indirect command buffers (`supportIndirectCommandBuffers`) | every device (a public call's own check of its arguments) | `ours`: indirect command buffers are not built | 1: `crates/metal2vulkan-rt/src/pipeline.rs (new_compute_pipeline_state)` | `-` | | `KernelInput` | A kernel that reads something the compute encoder does not supply yet | every device (a public call's own check of its arguments) | `ours`: the encoder binds buffers alone | 1: `crates/metal2vulkan-rt/src/pipeline.rs (gap)` | `-` | | `PartialSimdgroups` | A dispatch whose threadgroup is not whole SIMD groups of a kernel whose tier runs each SIMD group as one subgroup of `width` threads (a pinned... | every device (a public call's own check of its arguments) | `ours`: the emulated-SIMD-group variant is not built | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | -| `PartialThreadgroups` | `dispatchThreads` with a grid that is not a whole number of threadgroups on some axis | every device (a public call's own check of its arguments) | `ours`: partial threadgroups are not built | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threads)` | `-` | +| `PartialThreadgroups` | `dispatchThreads` with a grid that is not a whole number of threadgroups on some axis, of a kernel that observes its threadgroup partition and... | every device (a public call's own check of its arguments) | `ours`: the translator's partial-threadgroups variant does not take the emulated SIMD-group tier, nor a vote word past the workgroup memory | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | ## Appendix: every site @@ -1138,15 +1137,14 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::NoPipeline`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` - `rt:Refusal::BufferIndex`: `crates/metal2vulkan-rt/src/encoder.rs (slot)` - `rt:Refusal::NoBufferAtIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)` -- `rt:Refusal::ThreadgroupSize`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` +- `rt:Refusal::ThreadgroupSize`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch, 2 sites)` - `rt:Refusal::IndirectOffset`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)` - `rt:Limit::BlockLen`: `crates/metal2vulkan-rt/src/memory.rs (dedicated_len)` - `rt:Limit::BlockIds`: `crates/metal2vulkan-rt/src/memory.rs (number)` -- `rt:Limit::GroupCount`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` - `rt:Limit::ThreadgroupShape`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` - `rt:Limit::BytesLength`: `crates/metal2vulkan-rt/src/encoder.rs (set_bytes)` - `rt:Gap::IndirectCommandBuffers`: `crates/metal2vulkan-rt/src/pipeline.rs (new_compute_pipeline_state)` - `rt:Gap::KernelInput`: `crates/metal2vulkan-rt/src/pipeline.rs (gap)` - `rt:Gap::PartialSimdgroups`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` -- `rt:Gap::PartialThreadgroups`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threads)` +- `rt:Gap::PartialThreadgroups`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)`