From 6e88d181dd3640a267c74c22cb4a3ce113a75813 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 29 Oct 2026 10:15:21 +0200 Subject: [PATCH] Record each pipeline state creation, and warm a device from an earlier process's records DeviceOptions::pipeline_records (and RawDevice::pipeline_records) hands a hook an opaque PipelineRecord once per pipeline state creation that made its state. That covers compute, render, mesh and tile states, the additional-binary-functions forms, and a render state's draw-time twins (the one-sample and factor-scaling ones). A failed creation and a binary archive's add make none. A record holds the descriptor field by field ("M2VPREC\0", RECORD_FORMAT 1, the library table by content hash, SHA-256), read back and compared at its making. Its libraries are kept once in the shader cache's content directory. to_bytes and from_bytes carry it between processes. Device::warm(records, byte_budget) stands in for Metal's own pipeline caches across processes: - One background thread per device (utility QoS on macOS, Urgency::Warm in the making budget) runs each record's creation under the default options and drops the state. Translations, creation records and driver pipeline-cache data are then in place before the program asks. - The guest sees nothing of it: no identifier, resource ID, sampler number, neutral, room, stand-in copy, kept-variant traffic, live-variant sharing, announcement or record. - It stops at byte_budget of added driver data. - An unread record is counted, and the device's first is announced as the warning metal2vulkan-warm-record-unread; nothing fails. - WarmStatistics and Device::warm_statistics report the pass. Ports dev-perf 14df1fb5fe and 66fe0ada29 without per-entry stamps. Development's build directory names the translator, and its creation records name RUNTIME_VERSION, so no entry of another translator or runtime version is ever found, and dev-perf's re-translate-and-compare check has nothing to do. Adapted: - the memo is asked but never hands a warm thread a live variant the program holds; - a warm thread's waits rank Urgency::Warm, not Program (making.rs), and the pipewait creation bound still applies on warm threads; - unread records are announced. DeviceOptions' and RawDevice's Debug are hand-written. PipelineRecord is among the consumer auto-trait checks. api_signatures re-blessed; runtime README and HOWTO updated. RUNTIME_VERSION 1707. Verified on the M3 Max (MoltenVK 1.4.2), on development 2e2e238346: - 140 device tests and 500 plain tests pass. - Five sabotages each fail their guard: an archive add making a record; a pass answering Warmed without creating; no unread announcement; a warm state taking an identifier; a warm thread taking a live variant. - clippy plain and --cfg m2v_gpu, and rustdoc -D warnings, clean. - Release, 5 runs of the cross-process test, three creations (render, compute, indirect compute): - after a warm pass: 3.11-3.42 ms, with 0 stages decoded, 0 translated, 0 directory lookups and 0 driver caches loaded; - unwarmed over the same directory: 4.19-4.32 ms (6 lookups, 2 loads); - cold: 4.98-5.10 ms. Small shaders, and Metal's own cross-process compiler cache serves all three legs. Lane commits: ws/warmrec-lane (8d106f29ab hook, 30de4fc948 warm). One work packet, landed as 2 commits on archive/development-linear-2026-10-29: 8c709f27a7, then e2f0f2a3d9 (the re-pin). --- crates/metal2vulkan-runtime/README.md | 23 + .../metal2vulkan-runtime/src/degradation.rs | 19 +- .../metal2vulkan-runtime/src/device/adopt.rs | 55 +- .../metal2vulkan-runtime/src/device/create.rs | 93 +- crates/metal2vulkan-runtime/src/device/mod.rs | 9 + crates/metal2vulkan-runtime/src/exit_guard.rs | 15 + crates/metal2vulkan-runtime/src/lib.rs | 2 + .../src/pipeline/budget.rs | 87 +- .../src/pipeline/making.rs | 27 +- .../metal2vulkan-runtime/src/pipeline/memo.rs | 11 +- .../metal2vulkan-runtime/src/pipeline/mod.rs | 87 +- .../src/pipeline/objects.rs | 15 +- .../metal2vulkan-runtime/src/pipeline/pool.rs | 17 +- .../src/pipeline/render.rs | 76 +- .../metal2vulkan-runtime/src/pipeline/tile.rs | 8 + .../src/resource_ids/numbered.rs | 6 +- .../src/shader_cache/driver.rs | 18 +- .../src/shader_cache/libraries.rs | 119 +++ .../src/shader_cache/mod.rs | 9 +- .../src/shader_cache/store.rs | 22 +- crates/metal2vulkan-runtime/src/tests/mod.rs | 3 + crates/metal2vulkan-runtime/src/tests/warm.rs | 573 +++++++++++ .../src/tests/warm_record.rs | 332 +++++++ crates/metal2vulkan-runtime/src/warm/codec.rs | 889 ++++++++++++++++++ crates/metal2vulkan-runtime/src/warm/mod.rs | 80 ++ crates/metal2vulkan-runtime/src/warm/pass.rs | 395 ++++++++ .../metal2vulkan-runtime/src/warm/record.rs | 167 ++++ .../tests/consumer_auto_traits.rs | 9 +- .../runtime-sources.sha256 | 2 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 28 +- docs/HOWTO.md | 18 + 32 files changed, 3122 insertions(+), 94 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/shader_cache/libraries.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/warm.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/warm_record.rs create mode 100644 crates/metal2vulkan-runtime/src/warm/codec.rs create mode 100644 crates/metal2vulkan-runtime/src/warm/mod.rs create mode 100644 crates/metal2vulkan-runtime/src/warm/pass.rs create mode 100644 crates/metal2vulkan-runtime/src/warm/record.rs diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 8162188b2..95820c2c0 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -309,6 +309,29 @@ Calls Metal does not have, for a consumer that emulates a Metal device: - `HostBytes`: bytes at a pointer that may change while a call reads them (a guest's memory), which `Texture::replace_region_with_host_bytes` and `BufferContents::CopyHost` copy once through the pointer, where the slice forms would need the caller's own copy first. +- `DeviceOptions::pipeline_records` (and `RawDevice::pipeline_records`) is called once per + pipeline state creation (compute, render, mesh and tile, and each + `*_with_additional_binary_functions`) with a `PipelineRecord`: the creation's descriptor, every + field, its libraries named by content hash and kept once in the shader cache directory. + `PipelineRecord::to_bytes` and `from_bytes` carry it to a later process; `from_bytes` answers + `None` for a record of another format, so a consumer keeps records across updates and drops + those. Equal creations make equal records. +- `Device::warm(records, byte_budget)` stands in for Metal's own pipeline caches across + processes. It returns at once and, on one background thread of the device's (the utility class + on macOS, its pipeline makings ranked after every other making of the process), makes what each + record's creation makes, in order: its translations into the shader cache and its predicted + `VkPipeline`s' data into the driver's records, so the program's later creation of the same + descriptor finds them. It stops once the driver's pipeline cache data its makings added reaches + `byte_budget` bytes. It takes no identifier, resource ID or sampler number, makes no neutral, + announces no degradation and keeps nothing for the program's kept variants, and it reads no + translation of another translator and no creation record of another `RUNTIME_VERSION` (a record + holds a descriptor, never a translation), so no answer the program gets changes. Nothing fails: + a record it cannot read (another format, damaged, or a library the directory no longer holds) + is counted and dropped, the device's first announced as the warning + `metal2vulkan-warm-record-unread`, and a failed creation is counted and dropped. A mesh render + pipeline's record is not made (its creation keeps nothing past the state), and a layout that + bakes an immutable sampler is translated only. `Device::warm_statistics` counts the records + made, each record's outcome and the driver bytes added. [docs/API.md section 10](../../docs/API.md#10-accepted-differences) lists where the runtime answers otherwise than Metal on purpose. diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index e6e5962c4..6f85bdac9 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2520,7 +2520,12 @@ impl Announced { /// Whether `degradation` is announced now: at each occurrence of a kind the device announces /// at each (met at every occurrence, [`EachWatch`]), else for the first time, once per kind. + /// Never on a warm pass's threads, which count nothing announced (`warm/pass.rs`): what it + /// makes is no program's, and the creation it makes ahead announces as its own. pub(super) fn now(&self, degradation: Degradation) -> bool { + if crate::warm::warming() { + return false; + } let (word, bit) = degradation.bit(); if self.each[word] & bit != 0 { met_each(); @@ -2532,8 +2537,12 @@ impl Announced { /// Whether `degradation` is announced now for the first time, once per kind, whether or not /// the device announces it at each occurrence: a kind met where no program call or host step - /// is (`Device::degrade_encoded_use_rebound`). + /// is (`Device::degrade_encoded_use_rebound`). Never on a warm pass's threads, as + /// [`now`](Self::now). fn once(&self, degradation: Degradation) -> bool { + if crate::warm::warming() { + return false; + } let (word, bit) = degradation.bit(); let seen = &self.seen[word]; seen.load(Ordering::Relaxed) & bit == 0 && seen.fetch_or(bit, Ordering::Relaxed) & bit == 0 @@ -2541,7 +2550,11 @@ impl Announced { /// Whether `degradation` would be announced now ([`Announced::now`]), without counting it /// announced: a kind the device announces at every occurrence, or one not announced yet. + /// Never on a warm pass's threads, as [`now`](Self::now). fn pending(&self, degradation: Degradation) -> bool { + if crate::warm::warming() { + return false; + } let (word, bit) = degradation.bit(); self.each[word] & bit != 0 || self.seen[word].load(Ordering::Relaxed) & bit == 0 } @@ -3077,6 +3090,10 @@ impl Device { /// thread, each as [`degrade`](Self::degrade) announces a kind the device announces at every /// occurrence: through the device's message sink, else on stderr. pub(crate) fn announce_bound(&self, notices: &[BoundNotice]) { + // A warm pass announces nothing ([`Announced::now`]). + if crate::warm::warming() { + return; + } for (degradation, message) in notices { met_each(); match check_announcement(*degradation, true) { diff --git a/crates/metal2vulkan-runtime/src/device/adopt.rs b/crates/metal2vulkan-runtime/src/device/adopt.rs index 8b4dd4536..be6ecaaa3 100644 --- a/crates/metal2vulkan-runtime/src/device/adopt.rs +++ b/crates/metal2vulkan-runtime/src/device/adopt.rs @@ -23,7 +23,7 @@ use std::sync::Arc; /// The consumer's Vulkan objects a runtime device adopts ([`Device::from_raw`]). No Metal /// counterpart: an interop hook. #[non_exhaustive] -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct RawDevice { /// The `vkGetInstanceProcAddr` the instance was made through. pub get_instance_proc_addr: vk::PFN_vkGetInstanceProcAddr, @@ -97,6 +97,57 @@ pub struct RawDevice { /// [`DeviceOptions::lowering_refuses`](crate::DeviceOptions::lowering_refuses) says: none by /// default. pub lowering_refuses: BTreeSet, + /// Where the device hands its pipeline records, as + /// [`DeviceOptions::pipeline_records`](crate::DeviceOptions::pipeline_records) says: `None` + /// by default, no record made. Metal has no such setting. + pub pipeline_records: Option>, +} + +impl std::fmt::Debug for RawDevice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Every field is named, so a field added later is written here or this fails to compile. + let RawDevice { + get_instance_proc_addr, + instance, + instance_api_version, + physical_device, + device, + queue_family, + queue_index, + enabled, + device_extensions, + shader_cache, + sparse_features, + view_format_reinterpretation, + host_image_copy, + gpu_times_from_host, + announce_each, + lowering_refuses, + pipeline_records, + } = self; + f.debug_struct("RawDevice") + .field("get_instance_proc_addr", get_instance_proc_addr) + .field("instance", instance) + .field("instance_api_version", instance_api_version) + .field("physical_device", physical_device) + .field("device", device) + .field("queue_family", queue_family) + .field("queue_index", queue_index) + .field("enabled", enabled) + .field("device_extensions", device_extensions) + .field("shader_cache", shader_cache) + .field("sparse_features", sparse_features) + .field("view_format_reinterpretation", view_format_reinterpretation) + .field("host_image_copy", host_image_copy) + .field("gpu_times_from_host", gpu_times_from_host) + .field("announce_each", announce_each) + .field("lowering_refuses", lowering_refuses) + .field( + "pipeline_records", + &pipeline_records.as_ref().map(|_| "hook"), + ) + .finish() + } } impl RawDevice { @@ -127,6 +178,7 @@ impl RawDevice { gpu_times_from_host: false, announce_each: BTreeSet::new(), lowering_refuses: BTreeSet::new(), + pipeline_records: None, } } } @@ -277,6 +329,7 @@ impl Device { gpu_times_from_host: raw.gpu_times_from_host, // An adopted device keeps no execution record: validation makes its own devices. record_executions: false, + pipeline_records: raw.pipeline_records, fail_in_place_check: false, announce_each: raw.announce_each, lowering_refuses: raw.lowering_refuses, diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs index 44371fe6d..54dfe3832 100644 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ b/crates/metal2vulkan-runtime/src/device/create.rs @@ -57,7 +57,7 @@ use std::sync::{Arc, Mutex, Weak}; /// How the runtime creates its instance and devices. No Metal counterpart: these choose the /// Vulkan side (`MTLCreateSystemDefaultDevice` takes nothing). #[non_exhaustive] -#[derive(Clone, Debug, Default)] +#[derive(Clone, Default)] pub struct DeviceOptions { /// The policy each device's compile device is made with, and whose /// `recommended_enables` each device enables. @@ -184,6 +184,76 @@ pub struct DeviceOptions { /// lanes that hold the shadow to a failed check. No Metal counterpart. #[doc(hidden)] pub fail_in_place_check: bool, + /// Where each device hands its pipeline records: one [`PipelineRecord`](crate::PipelineRecord) + /// per pipeline state creation that made its state (compute, render, mesh render and tile + /// render, and the additional-binary-functions forms; and the one-sample or factor-scaling + /// twin the runtime makes of a render state where a draw first needs it), on the creating + /// thread before the call returns, as the program's own code (a panic in it is caught). A + /// creation that fails, a binary archive's add and a warm pass's make none. A consumer keeps + /// them, in the order they came, and hands a later process's device them + /// ([`Device::warm`](crate::Device::warm)) to make the same translations and `VkPipeline`s + /// before its program asks. `None` by default: no record is made. Devices of one hook are + /// devices of one option (it is compared by identity, as [`messages`](Self::messages) is). + /// No Metal counterpart: Metal keeps its own compiled pipelines in the OS's caches. + pub pipeline_records: Option>, +} + +impl std::fmt::Debug for DeviceOptions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Every field is named, so a field added later is written here or this fails to compile. + let DeviceOptions { + policy, + layers, + layer_settings, + instance_extensions, + device_extensions, + optional_device_extensions, + withheld_features, + withheld_extensions, + messages, + loader, + kinds, + shader_cache, + withhold_generated_commands, + withhold_view_reinterpretation, + instance_api_version, + gpu_times_from_host, + announce_each, + lowering_refuses, + record_executions, + fail_in_place_check, + pipeline_records, + } = self; + f.debug_struct("DeviceOptions") + .field("policy", policy) + .field("layers", layers) + .field("layer_settings", layer_settings) + .field("instance_extensions", instance_extensions) + .field("device_extensions", device_extensions) + .field("optional_device_extensions", optional_device_extensions) + .field("withheld_features", withheld_features) + .field("withheld_extensions", withheld_extensions) + .field("messages", messages) + .field("loader", loader) + .field("kinds", kinds) + .field("shader_cache", shader_cache) + .field("withhold_generated_commands", withhold_generated_commands) + .field( + "withhold_view_reinterpretation", + withhold_view_reinterpretation, + ) + .field("instance_api_version", instance_api_version) + .field("gpu_times_from_host", gpu_times_from_host) + .field("announce_each", announce_each) + .field("lowering_refuses", lowering_refuses) + .field("record_executions", record_executions) + .field("fail_in_place_check", fail_in_place_check) + .field( + "pipeline_records", + &pipeline_records.as_ref().map(|_| "hook"), + ) + .finish() + } } /// One setting of an instance layer (`VkLayerSettingEXT`). @@ -1473,6 +1543,7 @@ fn create_on( announce_each: options.announce_each.clone(), lowering_refuses: options.lowering_refuses.clone(), record_executions: options.record_executions, + pipeline_records: options.pipeline_records.clone(), fail_in_place_check: options.fail_in_place_check, view_reinterpretation, generated_commands, @@ -1535,9 +1606,12 @@ static MADE: Mutex> = Mutex::new(Vec::new()); /// One group of `MADE`: the devices made with equal options. struct Made { - /// The options, less the message sink, which the instance holds (`InstanceShared::sink`): - /// the group keeps no sink alive past its devices. + /// The options, less the message sink, which the instance holds (`InstanceShared::sink`), + /// and the pipeline records' hook, which `records` names: the group keeps neither alive past + /// its devices. options: DeviceOptions, + /// The options' pipeline records' hook, which each of the group's devices holds. + records: Option>, instance: Weak, devices: Vec<(vk::PhysicalDevice, Weak)>, } @@ -1551,7 +1625,12 @@ impl Made { (Some(asked), Some(made)) => asked.same(made), _ => false, }; - (sinks && same_options(&self.options, options)).then_some(instance) + let records = match (&options.pipeline_records, &self.records) { + (None, None) => true, + (Some(asked), Some(made)) => std::sync::Weak::ptr_eq(&Arc::downgrade(asked), made), + _ => false, + }; + (sinks && records && same_options(&self.options, options)).then_some(instance) } /// The live device of `physical`, if the group has one. @@ -1580,7 +1659,8 @@ pub(crate) fn live_devices_with(options: &DeviceOptions) -> usize { }) } -/// Whether `a` and `b` are equal options, but for their message sinks (compared by `Made`). +/// Whether `a` and `b` are equal options, but for their message sinks and pipeline records' +/// hooks (compared by `Made`). fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool { // Every field is named, so a field added later is compared or this fails to compile. let DeviceOptions { @@ -1604,6 +1684,7 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool { lowering_refuses, record_executions, fail_in_place_check, + pipeline_records: _, } = a; *policy == b.policy && *layers == b.layers @@ -1643,8 +1724,10 @@ fn group( made.push(Made { options: DeviceOptions { messages: None, + pipeline_records: None, ..options.clone() }, + records: options.pipeline_records.as_ref().map(Arc::downgrade), instance: Arc::downgrade(&instance), devices: Vec::new(), }); diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index d65e0e3dc..380f21fb8 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -520,6 +520,10 @@ pub(super) struct DeviceShared { /// rebind's or a storage form's new `VkImage`, a detach's stand-in, a reattach): a view kept /// by what it was made of (`binding::BindMemo`) is current while this holds. pub(crate) views_epoch: AtomicU64, + /// Its pipeline records: the hook they go to, and the counts (`warm/record.rs`). + pub(crate) pipeline_recording: crate::warm::Recording, + /// Its warm calls: the records queued, its warm thread, and the counts (`warm/pass.rs`). + pub(crate) warmer: crate::warm::Warmer, } impl DeviceShared { @@ -1159,6 +1163,8 @@ pub(super) struct Parts { pub(super) lowering_refuses: BTreeSet, /// Its command buffers keep execution records (`DeviceOptions::record_executions`). pub(super) record_executions: bool, + /// Where its pipeline records go (`DeviceOptions::pipeline_records`, `warm/record.rs`). + pub(super) pipeline_records: Option, /// Its check of the first move over host pages fails whatever the moves did /// (`DeviceOptions::fail_in_place_check`). pub(super) fail_in_place_check: bool, @@ -1236,6 +1242,7 @@ impl Device { announce_each, lowering_refuses, record_executions, + pipeline_records, fail_in_place_check, view_reinterpretation, generated_commands, @@ -1783,6 +1790,8 @@ impl Device { deferred: crate::render::DeferredEncoders::default(), record_executions, views_epoch: AtomicU64::new(0), + pipeline_recording: crate::warm::Recording::new(pipeline_records), + warmer: crate::warm::Warmer::default(), device_address, upload_alignment, dynamic_buffers: [ diff --git a/crates/metal2vulkan-runtime/src/exit_guard.rs b/crates/metal2vulkan-runtime/src/exit_guard.rs index c1fe58744..25cb2dc73 100644 --- a/crates/metal2vulkan-runtime/src/exit_guard.rs +++ b/crates/metal2vulkan-runtime/src/exit_guard.rs @@ -969,6 +969,21 @@ pub(crate) fn raise_to_user_initiated() { #[cfg(not(target_os = "macos"))] pub(crate) fn raise_to_user_initiated() {} +/// Lower this thread to the utility quality of service: a warm pass's thread (`warm/pass.rs`), +/// whose translations nothing waits for. Its pipeline makings still compile at the +/// user-initiated class, on a thread of their own (`device/compiles.rs`), and a thread it starts +/// starts at the default class ([`spawn`]). +#[cfg(target_os = "macos")] +pub(crate) fn lower_to_utility() { + // SAFETY: sets the calling thread's own class; no pointer. + unsafe { libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_UTILITY, 0) }; +} + +/// Nothing elsewhere: a Linux thread's nice value passes to the threads it starts, and the warm +/// pass starts the pipeline pool's, which serve the program ([`lower_to_utility`] on macOS). +#[cfg(not(target_os = "macos"))] +pub(crate) fn lower_to_utility() {} + /// Run this thread at the user-interactive quality of service, whatever its class: a thread of /// the runtime's own that takes command buffers to their handlers ([`spawn_user_interactive`]). #[cfg(target_os = "macos")] diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 4bbe34532..0cb49befc 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -220,6 +220,7 @@ mod values; mod versioned; mod view_plan; mod visibility; +mod warm; mod word_fill; mod work_counts; mod wrapped_buffer; @@ -353,6 +354,7 @@ pub use values::{ }; pub use view_plan::ViewProblem; pub use visibility::{VisibilityProblem, VisibilityResultMode}; +pub use warm::{PipelineRecord, WarmStatistics}; pub use work_counts::{CopySite, MemoryFrees, WorkCounts}; pub use wrapped_buffer::{VkBufferMemory, WrappedBufferProblem}; pub use ycbcr::{IoSurfaceYCbCr, SurfaceYCbCrMatrix}; diff --git a/crates/metal2vulkan-runtime/src/pipeline/budget.rs b/crates/metal2vulkan-runtime/src/pipeline/budget.rs index d893bf436..2ec1208c4 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/budget.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/budget.rs @@ -30,14 +30,18 @@ //! ([`Urgency::Ahead`]). These take idle turns, but hold at most the budget's `ahead` //! turns (by default all but one) at once, so a waited making that comes //! finds a turn free: the turns past the `ahead` ones are only for makings a thread, a -//! commit or a host step waits for, which take them whatever waits ahead of them. +//! commit or a host step waits for, which take them whatever waits ahead of them; +//! 6. a warm pass's making (`warm/pass.rs`), which nothing in the process asked for: its own +//! thread's and the pieces it hands the pool ([`Urgency::Warm`]). These take the `ahead` +//! turns alone, after every other making, and never age. //! //! A piece's rank rises where something comes to wait for it (`Place::hasten`; a wait or a commit before the piece was handed to the pool is applied //! as it is handed), never falls. Within a rank the earlier ticket goes first. No turn is //! taken back (no preemption). //! - **Aging** (the consumer's reviews). A making that has waited [`AGE`] is ordered as a committed //! command buffer's (rank 3) by its ticket, so a steady stream of other makings cannot starve a -//! draw's piece of the ahead turns. Aging moves a making nothing waits for up the order only: it +//! draw's piece of the ahead turns; a warm pass's making never ages, so the program's makings +//! always go before it. Aging moves a making nothing waits for up the order only: it //! still takes only an ahead turn, so it never takes the turn a waited making finds free, and a //! host step's making, or a queue's first held batch's, goes before it always. //! - **Nothing seen is decided here.** The budget orders driver calls in time and decides nothing @@ -252,6 +256,9 @@ pub(crate) enum Urgency { Program, /// Nothing waits for it yet: a draw's piece before its commit. Ahead, + /// A warm pass makes it (`warm/pass.rs`): nothing in the process asked for it. It takes an + /// ahead turn after every other making, and never ages ([`aged`]). + Warm, } impl Urgency { @@ -263,6 +270,7 @@ impl Urgency { Urgency::Committed => 2, Urgency::Program => 3, Urgency::Ahead => 4, + Urgency::Warm => 5, } } @@ -274,6 +282,7 @@ impl Urgency { 2 => Some(Urgency::Committed), 3 => Some(Urgency::Program), 4 => Some(Urgency::Ahead), + 5 => Some(Urgency::Warm), _ => None, } } @@ -323,7 +332,7 @@ impl Asker { fn rank(&self, age: Duration, ahead_free: bool) -> Option> { match self { Asker::Thread(urgency, ticket, since) => { - let ahead = *urgency == Urgency::Ahead; + let ahead = *urgency >= Urgency::Ahead; Some( (ahead_free || !ahead).then(|| ((aged(*urgency, *since, age), *ticket), ahead)), ) @@ -334,10 +343,11 @@ impl Asker { } /// The order of a making of `urgency` waiting since `since`: a committed one's once it waited -/// `age`, where it ranked lower (the module docs). Which turns it may take follow its own -/// `urgency`, never this. +/// `age`, where it ranked lower, but a warm pass's, which keeps its rank (the module docs). Which +/// turns it may take follow its own `urgency`, never this. pub(crate) fn aged(urgency: Urgency, since: Instant, age: Duration) -> Urgency { - match urgency > Urgency::Committed && since.elapsed() >= age { + let ages = urgency > Urgency::Committed && urgency != Urgency::Warm; + match ages && since.elapsed() >= age { true => Urgency::Committed, false => urgency, } @@ -519,11 +529,15 @@ pub(crate) fn program_turn() -> Option { thread_turn_in(process(), ticket()) } -/// A turn of `budget` for this thread's making with `ticket`, at the thread's rank now. +/// A turn of `budget` for this thread's making with `ticket`, at the thread's rank now: a host +/// step's, a warm pass's, else the program's. fn thread_turn_in(budget: &Arc, ticket: u64) -> Option { - let urgency = match exit_guard::in_host_step() { - true => Urgency::HostStep, - false => Urgency::Program, + let urgency = if exit_guard::in_host_step() { + Urgency::HostStep + } else if crate::warm::warming() { + Urgency::Warm + } else { + Urgency::Program }; let asked = Instant::now(); let (turn, _) = budget.take(Asker::Thread(urgency, ticket, asked))?; @@ -819,6 +833,59 @@ mod tests { until(|| budget.census() == (0, 0)); } + /// A warm pass's makings go after every other making, an aged one included, by their + /// tickets, and never age themselves (`warm/pass.rs`): a warm piece handed first and a warm + /// thread's making asked for next both wait out a piece nothing waits for, which ages past a + /// program's making asked for last, and that program's making, though they waited past the + /// age too. A warm piece runs as part of its pass. + #[test] + fn a_warm_pass_s_makings_go_last_and_never_age() { + let budget = Arc::new(Budget::aging(1, 1, Duration::from_millis(20))); + let held = waited_turn(&budget, ticket()); + let pool = Pool::within(Arc::clone(&budget)); + let order = Arc::new(Mutex::new(Vec::new())); + let pass = Arc::new(crate::warm::Pass::default()); + let noted = Arc::clone(&order); + crate::warm::within(&pass, || { + pool.run(Box::new(move || { + assert!( + crate::warm::warming(), + "a warm piece runs as part of its pass" + ); + noted.lock().unwrap().push("warm piece"); + })) + }); + assert!(!crate::warm::warming(), "the pass ends with its call"); + until(|| budget.census() == (1, 1)); + let warm_thread = { + let (budget, order) = (Arc::clone(&budget), Arc::clone(&order)); + let pass = Arc::clone(&pass); + let asked = ticket(); + crate::exit_guard::spawn(std::thread::Builder::new(), move || { + let _turn = crate::warm::within(&pass, || waited_turn(&budget, asked)); + order.lock().unwrap().push("warm thread"); + }) + .unwrap() + }; + until(|| budget.census() == (1, 2)); + pool.run(noting(&order, "ahead")); + until(|| budget.census() == (1, 3)); + let program = ask(&budget, &order, ("program", false)); + until(|| budget.census() == (1, 4)); + // Past the age for every one of them: only the piece nothing waits for ages. + std::thread::sleep(Duration::from_millis(100)); + drop(held); + for thread in [program, warm_thread] { + thread.join().unwrap(); + } + until(|| order.lock().unwrap().len() == 4); + assert_eq!( + *order.lock().unwrap(), + ["ahead", "program", "warm piece", "warm thread"] + ); + until(|| budget.census() == (0, 0)); + } + /// A queue's first held batch's making goes first to a freed turn, though a piece nothing /// waits for, aged (ordered as a committed one's), and a committed batch's piece behind /// another queue's head were handed before it: Metal holds no submission for a making, so the diff --git a/crates/metal2vulkan-runtime/src/pipeline/making.rs b/crates/metal2vulkan-runtime/src/pipeline/making.rs index 5cf21c656..daaab88d3 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/making.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/making.rs @@ -117,8 +117,8 @@ impl Turn { } } - /// Wait until the making finished, made or failed, hastened meanwhile: as a host step's - /// making in a host step, else as a program's thread's. + /// Wait until the making finished, made or failed, hastened meanwhile as this thread's own + /// making would rank ([`waiter`]). fn wait(&self) -> Outcome { // A turn's holder waiting for another making could, with every turn so held, stop all // of them (`budget.rs`'s module docs). @@ -126,10 +126,7 @@ impl Turn { !super::budget::holds_turn(), "a making waited for another while holding a budget turn" ); - self.hasten(match crate::exit_guard::in_host_step() { - true => Urgency::HostStep, - false => Urgency::Program, - }); + self.hasten(waiter()); let mut state = lock(&self.state); loop { if let TurnState::Finished(outcome) = &*state { @@ -149,10 +146,7 @@ impl Turn { !super::budget::holds_turn(), "a making waited for another while holding a budget turn" ); - self.hasten(match crate::exit_guard::in_host_step() { - true => Urgency::HostStep, - false => Urgency::Program, - }); + self.hasten(waiter()); let mut state = lock(&self.state); loop { if let TurnState::Finished(outcome) = &*state { @@ -191,6 +185,19 @@ impl Turn { } } +/// The rank a making this thread waits for rises to: a host step's in a host step, a warm +/// pass's on its threads (which asks nothing ahead of the program's makings, `warm/pass.rs`), +/// else a program's thread's. +fn waiter() -> Urgency { + if crate::exit_guard::in_host_step() { + Urgency::HostStep + } else if crate::warm::warming() { + Urgency::Warm + } else { + Urgency::Program + } +} + impl Making { /// An empty memo of at most `max_entries` entries. pub(crate) fn counted(max_entries: usize) -> Making { diff --git a/crates/metal2vulkan-runtime/src/pipeline/memo.rs b/crates/metal2vulkan-runtime/src/pipeline/memo.rs index 2d01d433a..9a584f04f 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/memo.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/memo.rs @@ -336,9 +336,16 @@ impl PipelineMemo { } } -/// The live variant `live` names, or else `pipeline`. +/// The live variant `live` names, or else `pipeline`. On a warm pass's threads always `pipeline` +/// (`warm/pass.rs`): a warm state holding a variant of the program's could be the last to let it +/// go, and so hand its objects to the kept variants at a moment the program's order does not +/// decide. fn remembered(pipeline: &Arc

, live: &Weak) -> Remembered { - match live.upgrade() { + let live = match crate::warm::warming() { + true => None, + false => live.upgrade(), + }; + match live { Some(variant) => Remembered::Live(variant), None => Remembered::Compiled(Arc::clone(pipeline)), } diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index 795edc30a..84adf0a11 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -651,16 +651,25 @@ impl ComputePipelineState { used: Option<&Used>, added_unsupported: usize, ) -> Result { + let requested = descriptor; let mut descriptor = descriptor.clone(); descriptor.kernel = crate::dynamic_library::stage_with_dependencies(&descriptor.kernel); - ComputePipelineState::of_kernel( + let state = ComputePipelineState::of_kernel( device, Kernel::Compute(descriptor), options, used, "new_compute_pipeline_state", added_unsupported, - ) + )?; + // The creation's record, as the program asked for it (`warm/record.rs`); a binary + // archive's add makes none. + if used.is_none() { + device.record_pipeline(|| { + crate::warm::Pipeline::Compute(requested.clone(), added_unsupported) + }); + } + Ok(state) } /// The state of `kernel`, a compute or tile descriptor, made on `device` under `options` in @@ -743,8 +752,10 @@ impl ComputePipelineState { // sampler or texel slot's), made here, where the creation may wait, so that no dispatch's // encoding makes one (`neutral.rs`; `RenderPipelineState::make_neutrals`). One that fails // is left to the dispatch that binds it. And room kept in the memory the encodings place - // their own resources in (`Device::keep_room`). - if !crate::exit_guard::in_host_step() { + // their own resources in (`Device::keep_room`). A warm pass makes neither: they take + // memory and addresses, which the program's creation makes in its own order + // (`warm/pass.rs`). + if !crate::exit_guard::in_host_step() && !crate::warm::warming() { if let Ok(plan) = base.plan(device, &BindShape::default()) { let _ = crate::binding::make_neutrals(device, &plan); } @@ -772,21 +783,33 @@ impl ComputePipelineState { .map_or(&[][..], |(_, samplers)| samplers.as_slice()), }], ); - let identifier = - UniqueIdentifier::state(&device.shared().identifiers, StateKind::Compute, indirect)?; + // A warm pass's state takes no identifier and no ID (`warm/pass.rs`): both are numbered + // in the program's order, and its samplers took none above (`numbered.rs`). + let identifier = match crate::warm::warming() { + true => None, + false => Some(UniqueIdentifier::state( + &device.shared().identifiers, + StateKind::Compute, + indirect, + )?), + }; let at_bind_views = AtBindViews::new(device, &base.shared_pipeline().interface); Ok(ComputePipelineState(Arc::new_cyclic(|state| { // The state holds its ID's slot, which lists it among the states an indirect // command's record can name (`indirect_states`). - let id = indirect.then(|| { - let id = IdHold::take(&device.shared().resource_ids, IdSpace::Pipeline, placement); - id.hold_state( - Holder::Pipeline(Weak::clone(state)), - StateKind::Compute, - identifier.value(), - ); - id - }); + let id = match (&identifier, indirect) { + (Some(identifier), true) => { + let ids = &device.shared().resource_ids; + let id = IdHold::take(ids, IdSpace::Pipeline, placement); + id.hold_state( + Holder::Pipeline(Weak::clone(state)), + StateKind::Compute, + identifier.value(), + ); + Some(id) + } + _ => None, + }; let program = Program { device: device.clone(), function: function.clone(), @@ -806,7 +829,7 @@ impl ComputePipelineState { }; StateShared { id, - identifier: Some(identifier), + identifier, _samplers: samplers, program: Arc::new(program), } @@ -814,6 +837,32 @@ impl ComputePipelineState { } } +/// Make on `device` what a creation of `pipeline`, a pipeline record's, makes: the same creation, +/// on a warm pass's thread (`warm/pass.rs`), under the default options, its state let go at once. +/// So its translations reach the shader cache and its `VkPipeline`s the driver's caches under the +/// very keys and records the program's creation of the same descriptor asks for; what the program +/// would see of it (an ID, an identifier, sampler numbers, notices, the kept variants' order, a +/// neutral's memory) each of those paths leaves out on a warm pass's threads. `false` for a mesh +/// render pipeline, which it does not make: that creation keeps no translation on disk and makes +/// no `VkPipeline` (`GraphicsState::create_mesh`), so nothing of it outlives the state. +pub(crate) fn warm(device: &Device, pipeline: &crate::warm::Pipeline) -> Result { + use crate::warm::Pipeline; + let options = PipelineOptions::default(); + match pipeline { + Pipeline::Compute(descriptor, added) => { + ComputePipelineState::create_adding(device, descriptor, &options, None, *added)?; + } + Pipeline::Render(descriptor, added) => { + GraphicsState::create_adding(device, descriptor, &options, None, *added)?; + } + Pipeline::Tile(descriptor, added) => { + TileState::create_adding(device, descriptor, &options, None, *added)?; + } + Pipeline::Mesh(_) => return Ok(false), + } + Ok(true) +} + /// The first name `linked` repeats where Metal's pipeline creation fails or was not measured: a /// name `functions` lists twice ("error: duplicated symbol", without validation too), or /// `binary_functions` twice, and a name both lists hold for two different functions (another @@ -1624,7 +1673,11 @@ impl Variant { variant.pipelines.seed(region, made); } } - device.shared().shader_cache.memo.live_compute(&variant); + // A warm pass's variant is no state's the program holds: the memo does not hand it out + // (`warm/pass.rs`). + if !crate::warm::warming() { + device.shared().shader_cache.memo.live_compute(&variant); + } Ok(variant) } diff --git a/crates/metal2vulkan-runtime/src/pipeline/objects.rs b/crates/metal2vulkan-runtime/src/pipeline/objects.rs index e4fd0ee35..133264961 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/objects.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/objects.rs @@ -125,6 +125,11 @@ pub(crate) fn sampler_set( }; return Ok((Arc::new(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. + if crate::warm::warming() { + return Err(crate::warm::translation_only()); + } let shared = device.shared(); // The device's Y′CbCr conversion of each sampler of a planes image (`texture/ycbcr_planes.rs`), // the one its view is made with, so the two are identically defined: made before the sets' @@ -682,7 +687,13 @@ impl VariantObjects { let dynamic = dynamic_bindings(device, layout, push_set_zero); let set_needs = needs_of(device, layout, push_set_zero, &dynamic)?; let shared = device.shared(); - let back = lock(&shared.kept).take(shared, compiled); + // A warm pass takes nothing back and keeps nothing (`warm/pass.rs`): the kept variants' + // order is the program's (the owner's HITCH rule 1), and its objects go as it lets them. + let warming = crate::warm::warming(); + let back = match warming { + true => None, + false => lock(&shared.kept).take(shared, compiled), + }; // The kept variants' queue applied (an evicted instance's modules let go): the device's // modules nothing holds now go, in the program's order. settle_modules(device); @@ -694,7 +705,7 @@ impl VariantObjects { settle_libraries(device); let Some(back) = back else { let mut objects = VariantObjects::create(device, layout, stages, pipeline, digests)?; - objects.keep = Some(Instance::new(compiled)); + objects.keep = (!warming).then(|| Instance::new(compiled)); return Ok((objects, Vec::new())); }; device.shared().counts.variant_taken_back(); diff --git a/crates/metal2vulkan-runtime/src/pipeline/pool.rs b/crates/metal2vulkan-runtime/src/pipeline/pool.rs index 19ade9edc..17fb0f5b8 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/pool.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/pool.rs @@ -219,7 +219,7 @@ impl State { .filter(|q| ahead_free || q.urgency < Urgency::Ahead) .map(|q| { let rank = (budget::aged(q.urgency, q.handed, age), q.number); - (rank, q.urgency == Urgency::Ahead) + (rank, q.urgency >= Urgency::Ahead) }) .min(); Some(rank) @@ -302,19 +302,28 @@ impl Pool { /// Run `work` on one of the pool's threads, a new one where none is free and fewer than /// [`PoolQueue::makers`] run; on this thread where the host starts none and none runs. Nothing waits for - /// it yet ([`Urgency::Ahead`]); where it waits, to hasten it. + /// it yet ([`Urgency::Ahead`]; a warm pass's piece ranks [`Urgency::Warm`] and runs as part + /// of its pass, `warm::within`); where it waits, to hasten it. pub(crate) fn run(&self, work: Work) -> Place { let number = budget::ticket(); // Its wait here and for its turn, for the creation log: noted as it starts. let handed = Instant::now(); + let pass = crate::warm::pass(); + let urgency = match pass { + Some(_) => Urgency::Warm, + None => Urgency::Ahead, + }; let work: Work = Box::new(move || { budget::waited_in_pool(handed.elapsed()); - work(); + match pass { + Some(pass) => crate::warm::within(&pass, work), + None => work(), + } }); let mut state = lock(&self.shared.state); state.work.push_back(Queued { number, - urgency: Urgency::Ahead, + urgency, handed, work, }); diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index d93b6ccb3..e32392b8b 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -1266,6 +1266,7 @@ impl GraphicsState { reflect: bool, ) -> Result<(GraphicsState, Option), Error> { let _noted = NoteEntries(device); + let requested = descriptor; let mut loaded = descriptor.clone(); loaded.vertex = crate::dynamic_library::stage_with_dependencies(&loaded.vertex); loaded.fragment = loaded @@ -1389,7 +1390,7 @@ impl GraphicsState { let kept = reflection_key .as_ref() .map(|key| cache.kept_render_reflection(compile, key)); - std::thread::scope(|scope| { + let made = std::thread::scope(|scope| { // A thread that cannot be made leaves the reflection to the caller, as before. let making = match (&kept, &reflection_key) { (Some(None), Some(key)) => { @@ -1420,8 +1421,16 @@ impl GraphicsState { )), _ => None, }; - Ok((state, reflected)) - }) + Ok::<_, Error>((state, reflected)) + })?; + // The creation's record, as the program asked for it (`warm/record.rs`); a binary + // archive's add makes none. + if used.is_none() { + device.record_pipeline(|| { + crate::warm::Pipeline::Render(requested.clone(), added_unsupported) + }); + } + Ok(made) } /// The state of `descriptor`, the rasterized descriptor of a render creation whose checks @@ -1595,6 +1604,7 @@ impl GraphicsState { ) -> Result { const CALL: &str = "new_mesh_render_pipeline_state"; let _noted = NoteEntries(device); + let requested = descriptor; // Metal's descriptor validation stops an attachment in a format Metal describes none // of, first (`attachment_formats.rs`). super::attachment_formats::check( @@ -1678,6 +1688,8 @@ impl GraphicsState { None, )?; state.make_neutrals(); + // The creation's record, as the program asked for it (`warm/record.rs`). + device.record_pipeline(|| crate::warm::Pipeline::Mesh(requested.clone())); Ok(state) } @@ -1699,7 +1711,8 @@ impl GraphicsState { /// that fails is left to the draw that binds it, which meets it as it is then. Then room kept /// in the memory the encodings place their own resources in (`Device::keep_room`). fn make_neutrals(&self) { - if crate::exit_guard::in_host_step() { + // A warm pass makes none either: they take memory and addresses (`warm/pass.rs`). + if crate::exit_guard::in_host_step() || crate::warm::warming() { return; } let device = &self.0.device; @@ -1731,26 +1744,40 @@ impl GraphicsState { added_unsupported: [usize; 2], key: Option, ) -> Result { - let identifier = UniqueIdentifier::state( - &device.shared().identifiers, - StateKind::Render, - descriptor.support_indirect_command_buffers(), - )?; + // A warm pass's state takes no identifier, no ID and no sampler number, and the creation + // log numbers no line of it (`warm/pass.rs`): each is numbered in the program's order. + let warming = crate::warm::warming(); + let indirect = descriptor.support_indirect_command_buffers(); + let identifier = match warming { + true => None, + false => Some(UniqueIdentifier::state( + &device.shared().identifiers, + StateKind::Render, + indirect, + )?), + }; let samplers = descriptor.number_samplers(device, &base.shared_pipeline().interface); let at_bind_views = AtBindViews::new(device, &base.shared_pipeline().interface); - let log = StateLog::new(label.as_deref(), &descriptor.function_names()); + let log = match warming { + true => None, + false => StateLog::new(label.as_deref(), &descriptor.function_names()), + }; Ok(GraphicsState(Arc::new_cyclic(|state| { // The state holds its ID's slot, which lists it among the states an indirect render // command's record can name (`indirect_states`). - let id = descriptor.support_indirect_command_buffers().then(|| { - let id = IdHold::take(&device.shared().resource_ids, IdSpace::Pipeline, placement); - id.hold_state( - Holder::RenderPipeline(Weak::clone(state)), - StateKind::Render, - identifier.value(), - ); - id - }); + let id = match (&identifier, indirect) { + (Some(identifier), true) => { + let ids = &device.shared().resource_ids; + let id = IdHold::take(ids, IdSpace::Pipeline, placement); + id.hold_state( + Holder::RenderPipeline(Weak::clone(state)), + StateKind::Render, + identifier.value(), + ); + Some(id) + } + _ => None, + }; let program = Program { device: device.clone(), descriptor, @@ -1776,7 +1803,7 @@ impl GraphicsState { }; StateShared { id, - identifier: Some(identifier), + identifier, _samplers: samplers, program: Arc::new(program), } @@ -2157,6 +2184,10 @@ impl GraphicsState { /// draw (`predicted.rs`); the copies' pipelines depend only on the depth attachment's format /// and samples, so its creation makes them, where Metal compiles. pub(crate) fn make_stand_in_copies(&self) { + // A warm pass makes none: a copy may take memory of its own (`warm/pass.rs`). + if crate::warm::warming() { + return; + } let graphics = &self.base().graphics; let Some(format) = graphics.depth_format else { return; @@ -2610,7 +2641,10 @@ impl RenderVariant { variant.pipelines.seed(*graphics, made); } } - device.shared().shader_cache.memo.live_render(&variant); + // As a compute variant's: a warm pass's is not handed out (`warm/pass.rs`). + if !crate::warm::warming() { + device.shared().shader_cache.memo.live_render(&variant); + } Ok(variant) } diff --git a/crates/metal2vulkan-runtime/src/pipeline/tile.rs b/crates/metal2vulkan-runtime/src/pipeline/tile.rs index b6545bdf6..c18dc894b 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/tile.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/tile.rs @@ -119,6 +119,7 @@ impl TileState { "new_tile_render_pipeline_state", descriptor.raster_sample_count, )?; + let requested = descriptor; let mut descriptor = descriptor.clone(); descriptor.tile = crate::dynamic_library::stage_with_dependencies(&descriptor.tile); let kernel = ComputePipelineState::of_kernel( @@ -129,6 +130,13 @@ impl TileState { "new_tile_render_pipeline_state", added_unsupported, )?; + // The creation's record, as the program asked for it (`warm/record.rs`); a binary + // archive's add makes none. + if used.is_none() { + device.record_pipeline(|| { + crate::warm::Pipeline::Tile(requested.clone(), added_unsupported) + }); + } Ok(TileState(Arc::new(TileShared { kernel, descriptor, diff --git a/crates/metal2vulkan-runtime/src/resource_ids/numbered.rs b/crates/metal2vulkan-runtime/src/resource_ids/numbered.rs index 6369c2b6d..87a761a0f 100644 --- a/crates/metal2vulkan-runtime/src/resource_ids/numbered.rs +++ b/crates/metal2vulkan-runtime/src/resource_ids/numbered.rs @@ -222,11 +222,15 @@ pub(crate) struct NumberedStage<'a> { /// Number the samplers of `stages`, a pipeline state's functions in Metal's order, on `ids`' /// device (the module docs): the keys the state holds, each once. Each function's holds take -/// its keys. +/// its keys. None on a warm pass's threads, whose states the program never sees: the numbers +/// are the program's creations' to take, in its order (`warm/pass.rs`). pub(crate) fn number( ids: &Arc>, stages: &[NumberedStage<'_>], ) -> Vec> { + if crate::warm::warming() { + return Vec::new(); + } // What a lock-holding step upgrades leaves the step: a holder's last handle must not go while // the lock is held, since its drop takes the lock. let per_stage: Vec<(Option>, Vec>)> = { diff --git a/crates/metal2vulkan-runtime/src/shader_cache/driver.rs b/crates/metal2vulkan-runtime/src/shader_cache/driver.rs index 362103e0a..dcd09dbd6 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/driver.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/driver.rs @@ -323,9 +323,9 @@ pub(crate) struct Live { /// Whether the cache was made from the record's data: only then does a making whose driver /// reports the pipeline found in it read no data back (the module docs). loaded: bool, - /// The SHA-256 of the data the cache was made from, or of what a making last wrote as the - /// record; `None` until one of the two happened. - kept: Mutex>, + /// The SHA-256 and the length of the data the cache was made from, or of what a making last + /// wrote as the record; `None` until one of the two happened. + kept: Mutex>, } impl Live { @@ -419,7 +419,7 @@ fn make_live(store: &Store, identity: &Identity, raw: &ash::Device, name: String match made { Ok(cache) => { count(&store.counters.driver_loads); - Some((cache, Sha256::digest(data).into())) + Some((cache, (Sha256::digest(data).into(), data.len() as u64))) } Err(_) => { // The driver refused data that passed the checks; a making's save replaces it. @@ -507,7 +507,8 @@ pub(crate) fn make( /// Write `cache`'s data as its record unless it is what the cache was loaded with or last wrote, /// by its SHA-256 (counted), or the checks refuse it (counted). The read is a section of the exit /// guard ([`exit_guard`]): on the program's own thread, once the process is exiting, nothing is -/// read or written. +/// read or written. On a warm pass's threads, the bytes the data grew by since the cache was +/// loaded or last written count against the pass's budget (`warm::added_pipeline_bytes`). /// /// `vkGetPipelineCacheData` names no externally synchronized parameter, and the Vulkan /// specification's pipeline cache chapter states that the use of a pipeline cache object in the @@ -529,8 +530,9 @@ fn keep(store: &Store, identity: &Identity, raw: &ash::Device, live: &Live) { return; }; let digest: Hash256 = Sha256::digest(&data).into(); + let length = data.len() as u64; let mut kept = lock(&live.kept); - if *kept == Some(digest) { + if kept.is_some_and(|(kept, _)| kept == digest) { count(&store.counters.driver_data_unchanged); return; } @@ -538,9 +540,11 @@ fn keep(store: &Store, identity: &Identity, raw: &ash::Device, live: &Live) { store.counters.refused(refusal); return; } + let before = kept.map_or(0, |(_, length)| length); + crate::warm::added_pipeline_bytes(length.saturating_sub(before)); match store.write_record_soon(&live.name, seal(identity, &data)) { Ok(_) => { - *kept = Some(digest); + *kept = Some((digest, length)); count(&store.counters.driver_saves); } Err(_) => store.write_failed(), diff --git a/crates/metal2vulkan-runtime/src/shader_cache/libraries.rs b/crates/metal2vulkan-runtime/src/shader_cache/libraries.rs new file mode 100644 index 000000000..29b196552 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/shader_cache/libraries.rs @@ -0,0 +1,119 @@ +//! The libraries pipeline records name (`warm/record.rs`), kept in the directory's content +//! directory by their content hash, so a record names each by its hash alone and a VM's records +//! over one library hold it once between them. +//! +//! - **Named by content.** A library's record is named by its content hash +//! (`Library::content_hash`, the SHA-256 of its whole container), in the content directory +//! every build shares (`store.rs`): a pin move finds it as it finds the driver's data. Its +//! bytes are [`MAGIC`], the hash, and the library's container bytes. +//! - **Checked as it is read.** A read is a hit only where the magic, the hash and the length are +//! the record's, the bytes parse as a library (`Library::parse`) and that library's content hash +//! is the one asked for; anything else is a miss and the file is removed. +//! - **Written once.** A pipeline record's making keeps each library it names here where the +//! directory does not hold it already, written by the device's cache thread as an entry is +//! (`worker.rs`); one larger than the queue's whole bound (16 MiB) is written on the creating +//! thread, once per directory. The device keeps the hashes it knows the directory holds +//! ([`KeptLibraries`], at most [`KNOWN`]), forgotten at any removal from the directory, so a +//! later record of the same library asks nothing of the directory. +//! - **Bounded with the rest.** The scans count these records against the directory's cap, and +//! the least recently used go first (a warm pass's read refreshes a library's use); a pipeline +//! record whose library went names one the directory no longer holds, which a warm pass counts +//! unread (`warm/pass.rs`). + +use super::store::{count, entry_name, Lookup}; +use super::{EntryKind, ShaderCache}; +use crate::device::lock; +use metal2vulkan::cache::Hash256; +use metal2vulkan::library::Library; +use std::collections::HashSet; +use std::sync::Mutex; + +/// The first bytes of a library's record. +const MAGIC: &[u8; 8] = b"M2VLIBR1"; + +/// The length of a library record's head: its magic and the content hash. +const HEAD: usize = 8 + 32; + +/// The most library hashes a device keeps as held: more than any one guest's libraries. +pub(crate) const KNOWN: usize = 1024; + +/// The library hashes this device knows the directory holds, and the store's removal count they +/// were known at (`Store::removals`: a removal may have taken one). +pub(crate) struct KeptLibraries(Mutex<(HashSet, u64)>); + +impl KeptLibraries { + /// None known. + pub(crate) fn new() -> KeptLibraries { + KeptLibraries(Mutex::new((HashSet::new(), 0))) + } +} + +/// The name of the record of the library of content hash `hash`. +fn name(hash: &Hash256) -> String { + entry_name(&super::store::content(), EntryKind::Library, hash, &[0; 32]) +} + +impl ShaderCache { + /// Keep `library` in the directory, where this device does not know it holds it already + /// (the module docs). + pub(crate) fn keep_library(&self, library: &Library) { + let hash = *library.content_hash(); + let removals = self.store.removals(); + { + let mut known = lock(&self.libraries.0); + if known.1 != removals { + known.0.clear(); + known.1 = removals; + } + if known.0.contains(&hash) { + return; + } + } + let name = name(&hash); + if !self.store.holds_record(&name) { + let mut bytes = Vec::with_capacity(HEAD + library.bytes().len()); + bytes.extend_from_slice(MAGIC); + bytes.extend_from_slice(&hash); + bytes.extend_from_slice(library.bytes()); + match self.store.write_record_soon(&name, bytes) { + Ok(_) => count(&self.store.counters.libraries_kept), + Err(_) => self.store.write_failed(), + } + if self.store.over_capacity() { + self.worker.evict(); + } + } + let mut known = lock(&self.libraries.0); + if known.0.len() >= KNOWN { + known.0.clear(); + } + known.0.insert(hash); + } + + /// The library of content hash `hash` and container length `length` the directory holds, + /// parsed and checked (the module docs); `None` where it holds none. + pub(crate) fn library(&self, hash: &Hash256, length: u64) -> Option { + let found = self.store.load_content(&name(hash), |bytes| { + if bytes.len() as u64 != HEAD as u64 + length + || &bytes[..8] != MAGIC + || bytes[8..HEAD] != *hash + { + return None; + } + let library = Library::parse(&bytes[HEAD..]).ok()?; + (library.content_hash() == hash).then_some(library) + }); + match found { + Lookup::Hit(library) => Some(library), + Lookup::Absent | Lookup::Unreadable | Lookup::Rejected => None, + } + } + + /// The libraries this device wrote to the directory (`WarmStatistics::libraries_kept`). + pub(crate) fn libraries_kept(&self) -> u64 { + self.store + .counters + .libraries_kept + .load(std::sync::atomic::Ordering::Relaxed) + } +} diff --git a/crates/metal2vulkan-runtime/src/shader_cache/mod.rs b/crates/metal2vulkan-runtime/src/shader_cache/mod.rs index c0e8d025d..3e2a6ef45 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/mod.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/mod.rs @@ -26,7 +26,7 @@ //! versioned by its own tag and magic. //! - **Records of content, every build's**. Beside the builds', one directory holds records named //! by the content they describe, which hold no translation: the driver's data of each family of -//! makings (above). +//! makings (above), and the libraries pipeline records name (`libraries.rs`). //! - **A wrong entry is never used.** An entry's name is the SHA-256 of its build, kind, key and //! profile fingerprint, and a read is a hit only if the envelope's versions, kind, key and //! profile equal the request's and its checksum holds (`from_bytes_for_key`). Anything else is @@ -59,6 +59,7 @@ //! so a sweep of pipeline states over one function pair asks it once rather than once a state. mod creation; +mod libraries; /// The name of a creation's record under a runtime version, which `tests::shader_cache` reads. #[cfg(test)] pub(crate) use creation::record_name; @@ -299,6 +300,8 @@ pub(crate) enum EntryKind { RenderReflection = 9, /// The pipeline key of a render descriptor under a variant key (`creation.rs`). VariantPipeline = 10, + /// A library a pipeline record names, in the content directory (`libraries.rs`). + Library = 11, } /// The translations this build reads and writes: the SHA-256 of the crate's version, both artifact @@ -393,6 +396,9 @@ pub(super) struct ShaderCache { held: held::HeldFunctions, store: Arc, worker: Worker, + /// The libraries pipeline records name that this device knows the directory holds + /// (`libraries.rs`). + libraries: libraries::KeptLibraries, /// What names the makings' records (`driver.rs`). records: Records, /// The `VkPipelineCache` the device keeps for each record name, one per family of makings @@ -431,6 +437,7 @@ impl ShaderCache { held: held::HeldFunctions::new(), store, worker, + libraries: libraries::KeptLibraries::new(), records: Records { identity: driver::Identity::of(properties), settings, diff --git a/crates/metal2vulkan-runtime/src/shader_cache/store.rs b/crates/metal2vulkan-runtime/src/shader_cache/store.rs index 815dd9909..93c4c265a 100644 --- a/crates/metal2vulkan-runtime/src/shader_cache/store.rs +++ b/crates/metal2vulkan-runtime/src/shader_cache/store.rs @@ -9,7 +9,8 @@ //! - One directory beside the builds', the content directory ([`content`]), holds records no build //! owns, named by the content they describe: the driver's pipeline cache data (It was the //! build's; one record per pipeline making), named by what each making reads and read as an entry -//! is, with its counts (`driver.rs`); the scans bound them with the rest. +//! is, with its counts (`driver.rs`), and the libraries pipeline records name, by their content +//! hash (`libraries.rs`); the scans bound them with the rest. //! - An entry's name is the SHA-256 of a domain tag, the build, the entry's kind, its key and the //! profile fingerprint ([`entry_name`]). The decoder the caller hands to [`Store::load`] checks //! the contents against the request byte for byte; contents it refuses are removed. @@ -203,6 +204,9 @@ pub(crate) struct Counters { pub(crate) hits_by: [AtomicU64; Looked::COUNT], /// Of `misses`, likewise. pub(crate) misses_by: [AtomicU64; Looked::COUNT], + /// Libraries pipeline records name that this device wrote to the content directory + /// (`libraries.rs`): `WarmStatistics::libraries_kept`. + pub(crate) libraries_kept: AtomicU64, pub(crate) rejected: AtomicU64, pub(crate) read_failures: AtomicU64, pub(crate) writes: AtomicU64, @@ -438,13 +442,23 @@ impl Store { /// happened yet. Reads no contents and counts in no hit or miss -- it is a question about the /// directory, not a lookup of an entry -- but its `stat` is in [`Counters::read_nanos`]. pub(crate) fn holds(&self, name: &str) -> bool { - let path = self.directory.entry_path(name); - if self.asked.as_ref().is_some_and(|asked| asked.holds(&path)) { + self.holds_at(&self.directory.entry_path(name)) + } + + /// [`Store::holds`] of the record named `name` in the content directory: a library a pipeline + /// record names (`shader_cache/libraries.rs`). + pub(crate) fn holds_record(&self, name: &str) -> bool { + self.holds_at(&self.directory.record_path(name)) + } + + /// [`Store::holds`] of the file at `path`. + fn holds_at(&self, path: &Path) -> bool { + if self.asked.as_ref().is_some_and(|asked| asked.holds(path)) { return true; } count(&self.counters.holds_questions); timed(&self.counters.read_nanos, || { - fs::metadata(&path).is_ok_and(|metadata| metadata.len() <= self.entry_limit()) + fs::metadata(path).is_ok_and(|metadata| metadata.len() <= self.entry_limit()) }) } diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 3a6487ba4..9383c5140 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -310,6 +310,9 @@ mod vertex_conversion_notices; mod view_plan; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod waiter_submits; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod warm; +mod warm_record; mod word_fill; mod wrapped; mod written_commands; diff --git a/crates/metal2vulkan-runtime/src/tests/warm.rs b/crates/metal2vulkan-runtime/src/tests/warm.rs new file mode 100644 index 000000000..6c7583954 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/warm.rs @@ -0,0 +1,573 @@ +//! Pipeline records (`warm/record.rs`) and the warm pass (`warm/pass.rs`): a device with a record +//! hook hands it one record per pipeline state creation that made its state; a device handed the +//! records an earlier process's device made over the same shader cache directory makes their +//! translations and `VkPipeline`s before the program creates them, takes nothing the program sees, +//! stops at its byte budget, and announces a record it cannot read and goes on. +//! +//! # What is counted, and why counts +//! +//! Every assertion is a count of the structure (records handed over and warmed, libraries +//! written, stages decoded, functions translated, identifiers taken, messages heard), never a +//! time: a count holds on any host under any load. The times the cross-process test prints (the +//! creations on a warmed device, on an unwarmed one over the same directory, and on a cold one) +//! are figures of this host, printed and not asserted. +//! +//! Each assertion that a count stayed still is paired with one that the same structure moved +//! elsewhere (the cold device translates, the program's creation takes an identifier, a creation +//! that made its state hands the hook a record), so a pass or a hook that did nothing at all +//! cannot pass it. +//! +//! Each test owns empty cache directories, removed when dropped. The cross-process test's +//! recording half runs as a process of its own. +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are the owned fixtures +//! `validation/fixtures/public/engine/ubo_bind_offsets.ll` and +//! `validation/fixtures/public/examples/runtime_examples.ll` (`llvm-as`). + +use super::blit_holds::Scratch; +use super::descriptor_key_once::descriptor; +use crate::{ + BinaryArchiveDescriptor, Device, DeviceKind, DeviceOptions, MessageSink, PipelineOptions, + PipelineRecord, ShaderCacheOptions, WarmStatistics, +}; +use metal2vulkan::pipeline::{ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +/// The states [`make_states`] creates, so the records each recording hands over. +const STATES: u64 = 3; + +/// The environment variables that make [`record_process`] the recording half of +/// [`a_later_process_warms_what_an_earlier_one_recorded`]. +const DIRECTORY: &str = "M2V_TEST_WARM_DIRECTORY"; +const RECORDS: &str = "M2V_TEST_WARM_RECORDS"; + +/// What a device's message sink heard: its degrade notices, and the id names of its other +/// messages. +#[derive(Default)] +struct Heard { + notices: AtomicU64, + names: Mutex>, +} + +impl Heard { + /// How many messages of id name `name` it heard. + fn named(&self, name: &str) -> usize { + self.names + .lock() + .unwrap() + .iter() + .filter(|heard| *heard == name) + .count() + } +} + +/// A device over `cache`, handing its records to `records` where given, its messages to `heard` +/// where given. +fn device( + cache: &Path, + records: Option<&Arc>>>, + heard: Option<&Arc>, +) -> Device { + let mut options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + shader_cache: ShaderCacheOptions { + directory: Some(cache.to_owned()), + ..ShaderCacheOptions::default() + }, + ..DeviceOptions::default() + }; + if let Some(records) = records { + let records = Arc::clone(records); + options.pipeline_records = Some(Arc::new(move |record| { + records.lock().unwrap().push(record); + })); + } + if let Some(heard) = heard { + let heard = Arc::clone(heard); + options.messages = Some(MessageSink::new(move |message| { + match message.degradation.is_some() { + true => heard.notices.fetch_add(1, Ordering::Relaxed), + false => { + heard.names.lock().unwrap().push(message.id_name.clone()); + 0 + } + }; + })); + } + Device::system_default_with(&options).unwrap() +} + +/// The compute descriptor of `runtime_examples`' `scale_and_offset`, requiring its threadgroup +/// (so its creation makes its first dispatch's `VkPipeline`). +fn compute(device: &Device) -> ComputePipelineDescriptor { + let ll = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/fixtures/public/examples/runtime_examples.ll"); + let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap(); + let function = device + .new_library_with_compile_library( + metal2vulkan::library::Library::from_air(&bitcode).unwrap(), + ) + .new_function_with_name("scale_and_offset") + .unwrap(); + let mut compute = + ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); + compute.required_threads_per_threadgroup = Some([32, 1, 1]); + compute +} + +/// The descriptors of [`make_states`] on `device`: the `ubo_bind_offsets` pair's render +/// descriptor and [`compute`]'s. Their libraries are assembled here (`llvm-as`), apart from the +/// creations a test times. +fn descriptors(device: &Device) -> (RenderPipelineDescriptor, ComputePipelineDescriptor) { + (descriptor(device), compute(device)) +} + +/// The states every test creates, in this order: a render state of the `ubo_bind_offsets` pair, +/// a compute state of [`compute`], and the same kernel's state with indirect command buffer +/// support (so its creation takes a resource ID). Each makes a predicted `VkPipeline`. +fn make_states(device: &Device) -> Vec> { + make(device, &descriptors(device)) +} + +/// [`make_states`] of `descriptors`, [`descriptors`]' on `device`. +fn make( + device: &Device, + (render, compute): &(RenderPipelineDescriptor, ComputePipelineDescriptor), +) -> Vec> { + let options = PipelineOptions::default(); + let render = device.new_render_pipeline_state(render, &options).unwrap(); + let mut compute = compute.clone(); + let plain = device + .new_compute_pipeline_state(&compute, &options) + .unwrap(); + compute.support_indirect_command_buffers = true; + let indirect = device + .new_compute_pipeline_state(&compute, &options) + .unwrap(); + vec![Box::new(render), Box::new(plain), Box::new(indirect)] +} + +/// The records a device over `cache` hands over for [`make_states`]; the device is gone when +/// this returns, so its cache thread wrote what it was handed. +fn recorded(cache: &Path) -> Vec { + let records = Arc::new(Mutex::new(Vec::new())); + let device = device(cache, Some(&records), None); + drop(make_states(&device)); + assert_eq!(device.warm_statistics().records_made, STATES); + drop(device); + let records = records.lock().unwrap().clone(); + assert_eq!(records.len() as u64, STATES, "one record per creation"); + records +} + +/// `device`'s statistics once the warm passes over `records` records are done (each record +/// counted in one outcome), at most two minutes from now. +fn warmed(device: &Device, records: u64) -> WarmStatistics { + let deadline = Instant::now() + Duration::from_secs(120); + loop { + let s = device.warm_statistics(); + let done = s.records_warmed + + s.records_translated + + s.records_failed + + s.records_unread + + s.records_not_warmable + + s.records_not_run; + if done >= records { + return s; + } + assert!( + Instant::now() < deadline, + "the warm pass did not finish: {s:?}" + ); + std::thread::sleep(Duration::from_millis(10)); + } +} + +/// What [`make_states`]' creations cost `device`, their libraries assembled before: their wall +/// time, and the stages they decoded, the functions they translated, the translations they +/// looked up in the shader cache directory, the driver pipeline caches they loaded from it, the +/// shader modules they made and the variant `VkPipeline`s they made. +fn creations(device: &Device) -> (Duration, [u64; 6]) { + let descriptors = descriptors(device); + let before = (device.work_counts(), device.shader_cache_statistics()); + let started = Instant::now(); + let states = make(device, &descriptors); + let took = started.elapsed(); + let after = (device.work_counts(), device.shader_cache_statistics()); + drop(states); + ( + took, + [ + after.0.stage_entries_specialized - before.0.stage_entries_specialized, + after.0.functions_translated - before.0.functions_translated, + (after.1.hits + after.1.misses) - (before.1.hits + before.1.misses), + after.1.driver_loads - before.1.driver_loads, + after.0.shader_modules_made - before.0.shader_modules_made, + after.0.variant_pipelines_made - before.0.variant_pipelines_made, + ], + ) +} + +/// Each creation that made its state hands the hook one record, in the order made, and counts +/// it; a creation that fails and a binary archive's add hand it nothing; the same descriptor +/// created again makes the same record; a record carried through its bytes is the same record; +/// and the two libraries the records name are written to the directory once each, however many +/// records name them. +#[test] +fn each_creation_hands_the_hook_one_record() { + let scratch = Scratch::new("warm-hook"); + let records = Arc::new(Mutex::new(Vec::new())); + let device = device(&scratch.0, Some(&records), None); + let states = make_states(&device); + let s = device.warm_statistics(); + assert_eq!( + (s.records_made, s.records_unmade), + (STATES, 0), + "one record per creation: {s:?}" + ); + assert_eq!(records.lock().unwrap().len() as u64, STATES); + assert_eq!( + s.libraries_kept, 2, + "the render pair's library and the kernel's, each written once: {s:?}" + ); + + // A kernel as a vertex function: Metal's creation fails, and so no record. + let kernel = compute(&device).kernel; + let failing = RenderPipelineDescriptor::new(kernel); + assert!( + device + .new_render_pipeline_state(&failing, &PipelineOptions::default()) + .is_err(), + "a kernel as a vertex function is refused" + ); + // An archive's add makes the state the creation would, and hands the hook nothing. + let archive = device + .new_binary_archive(&BinaryArchiveDescriptor::new(None)) + .unwrap(); + archive + .add_compute_pipeline_functions(&compute(&device)) + .unwrap(); + assert_eq!( + device.warm_statistics().records_made, + STATES, + "a failed creation or an archive's add made a record" + ); + + // The render state again: the same record, its library not written again. + let again = device + .new_render_pipeline_state(&descriptor(&device), &PipelineOptions::default()) + .unwrap(); + let s = device.warm_statistics(); + assert_eq!((s.records_made, s.libraries_kept), (STATES + 1, 2), "{s:?}"); + let records = records.lock().unwrap().clone(); + assert_eq!( + records[STATES as usize], records[0], + "equal creations make equal records" + ); + assert_ne!(records[1], records[2], "two descriptors make two records"); + for record in &records { + assert_eq!( + PipelineRecord::from_bytes(&record.to_bytes()).as_ref(), + Some(record), + "a record read from its own bytes is the same record" + ); + } + drop((states, again)); +} + +/// One process records, and a later one warms its records, then makes the same states: the +/// warmed device's creations decode no stage, translate nothing, look nothing up in the +/// directory and load no driver pipeline cache, where an unwarmed device over the same directory +/// looks its translations up and loads its driver data in its creations, and a cold device +/// translates every function. The creations' times on the three devices are printed. +#[test] +fn a_later_process_warms_what_an_earlier_one_recorded() { + let scratch = Scratch::new("warm-processes"); + let cache = scratch.0.join("cache"); + std::fs::create_dir_all(&cache).unwrap(); + let file = scratch.0.join("records"); + let status = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "tests::warm::record_process", + "--ignored", + "--test-threads=1", + ]) + .env(DIRECTORY, &cache) + .env(RECORDS, &file) + .status() + .unwrap(); + assert!(status.success(), "the recording process failed"); + let records = read_records(&file); + assert_eq!(records.len() as u64, STATES); + + // The same directory without a warm pass: what the program's creations pay there. + let unwarmed = device(&cache, None, None); + let (unwarmed_took, unwarmed_made) = creations(&unwarmed); + drop(unwarmed); + + let warm = device(&cache, None, None); + let started = Instant::now(); + warm.warm(records, u64::MAX); + let s = warmed(&warm, STATES); + let pass_took = started.elapsed(); + assert_eq!( + (s.records_warmed, s.records_failed, s.records_unread), + (STATES, 0, 0), + "every record warmed: {s:?}" + ); + let (warm_took, warm_made) = creations(&warm); + assert_eq!( + warm_made[..4], + [0, 0, 0, 0], + "the warmed device's creations decode, translate, look up and load nothing: the pass did" + ); + assert!( + unwarmed_made[2] > 0 && unwarmed_made[3] > 0, + "an unwarmed device's creations look their translations up and load their driver data, \ + or the warmed leg's zeros above are vacuous: {unwarmed_made:?}" + ); + + let cold_scratch = Scratch::new("warm-processes-cold"); + let cold = device(&cold_scratch.0, None, None); + let (cold_took, cold_made) = creations(&cold); + assert!( + cold_made[1] > 0, + "a cold device translates its functions, or the warm leg's zero above is vacuous" + ); + let cache_stats = warm.shader_cache_statistics(); + println!( + "warm pass: {} records warmed in {pass_took:?}, {} driver bytes added ({} driver pipeline \ + hits, {} misses over the warmed device). The {STATES} creations, as [stages decoded, \ + functions translated, directory lookups, driver caches loaded, shader modules made, \ + variant pipelines made]: {warm_took:?} \ + {warm_made:?} on the warmed device, {unwarmed_took:?} {unwarmed_made:?} on an unwarmed \ + device over the same directory, {cold_took:?} {cold_made:?} on a cold one", + s.records_warmed, + s.pipeline_bytes, + cache_stats.driver_pipeline_hits, + cache_stats.driver_pipeline_misses, + ); +} + +/// The recording half of [`a_later_process_warms_what_an_earlier_one_recorded`], run as its own +/// process: records [`make_states`] over the directory it is named, and writes the records' +/// bytes to the file it is named, each after its length. +#[test] +#[ignore = "a child process of a_later_process_warms_what_an_earlier_one_recorded"] +fn record_process() { + let cache = PathBuf::from(std::env::var_os(DIRECTORY).expect("the parent names the cache")); + let file = PathBuf::from(std::env::var_os(RECORDS).expect("the parent names the file")); + let mut bytes = Vec::new(); + for record in recorded(&cache) { + let record = record.to_bytes(); + bytes.extend_from_slice(&(record.len() as u64).to_le_bytes()); + bytes.extend_from_slice(&record); + } + std::fs::write(file, bytes).unwrap(); +} + +/// The records [`record_process`] wrote to `file`. +fn read_records(file: &Path) -> Vec { + let bytes = std::fs::read(file).unwrap(); + let mut records = Vec::new(); + let mut at = 0; + while at < bytes.len() { + let length = u64::from_le_bytes(bytes[at..at + 8].try_into().unwrap()) as usize; + at += 8; + records.push(PipelineRecord::from_bytes(&bytes[at..at + length]).expect("a record")); + at += length; + } + records +} + +/// A warm pass takes no identifier, no sampler ID and no live variant of the program's, hands +/// the record hook nothing and announces nothing: the program's states made after it number their +/// identifiers on from those made before it, as with no pass between them, and the program's +/// creations announce what a cold device's announce. +#[test] +fn a_warm_pass_takes_nothing_the_program_sees() { + let recording = Scratch::new("warm-unseen-recording"); + let records = recorded(&recording.0); + let scratch = Scratch::new("warm-unseen"); + let heard = Arc::new(Heard::default()); + let hook = Arc::new(Mutex::new(Vec::new())); + let warm = device(&scratch.0, Some(&hook), Some(&heard)); + // Two plain states' identifiers a step apart, before the pass: the step a state takes. + let options = PipelineOptions::default(); + let state = || { + warm.new_render_pipeline_state(&descriptor(&warm), &options) + .unwrap() + }; + let first = state(); + let second = state(); + let step = second.unique_identifier() - first.unique_identifier(); + assert!( + step > 0, + "a plain state's identifier moves at each creation" + ); + let heard_before = heard.notices.load(Ordering::Relaxed); + let ids_before = warm.sampler_ids_live(); + let made_before = warm.warm_statistics().records_made; + assert_eq!(made_before, 2, "the program's creations made records"); + // The render record first, alone, while the program holds two states of its descriptor: the + // pass makes its own variant's objects (its stages take the device's shader modules) rather + // than take the program's live variant, which it could be the last to let go of. + let stages = |device: &Device| { + let counts = device.work_counts(); + counts.shader_modules_made + counts.shader_modules_shared + }; + let stages_before = stages(&warm); + warm.warm(records[..1].to_vec(), u64::MAX); + let s = warmed(&warm, 1); + assert_eq!(s.records_warmed, 1, "{s:?}"); + assert!( + stages(&warm) > stages_before, + "the pass took the program's live variant" + ); + warm.warm(records[1..].to_vec(), u64::MAX); + let s = warmed(&warm, STATES); + assert_eq!(s.records_warmed, STATES, "{s:?}"); + assert_eq!( + heard.notices.load(Ordering::Relaxed), + heard_before, + "the pass announced" + ); + assert_eq!( + warm.sampler_ids_live(), + ids_before, + "the pass holds sampler IDs" + ); + assert_eq!( + warm.warm_statistics().records_made, + made_before, + "the pass handed the record hook its states" + ); + let third = state(); + assert_eq!( + third.unique_identifier() - second.unique_identifier(), + step, + "the pass took identifiers between the program's states" + ); + drop((first, second, third)); + // The program's creations announce on the warmed device what they announce on a cold one: + // the pass counted nothing announced. + let heard_warm = heard.notices.load(Ordering::Relaxed); + drop(make_states(&warm)); + let warm_notices = heard.notices.load(Ordering::Relaxed) - heard_warm; + let cold_scratch = Scratch::new("warm-unseen-cold"); + let cold_heard = Arc::new(Heard::default()); + let cold = device(&cold_scratch.0, None, Some(&cold_heard)); + let cold_state = cold + .new_render_pipeline_state(&descriptor(&cold), &options) + .unwrap(); + let _ = cold_state.unique_identifier(); + let cold_before = cold_heard.notices.load(Ordering::Relaxed); + drop(make_states(&cold)); + let cold_notices = cold_heard.notices.load(Ordering::Relaxed) - cold_before; + assert_eq!( + warm_notices, cold_notices, + "the warmed device's creations announced otherwise than a cold device's" + ); + println!("the creations announced {warm_notices} notice(s) on both devices"); +} + +/// A pass stops before its next record once the driver data its makings added reaches its byte +/// budget: none is made under a budget of 0 bytes, and only the first under a budget of 1 byte +/// where that record's makings added any. +#[test] +fn a_byte_budget_stops_the_pass() { + let recording = Scratch::new("warm-budget-recording"); + let records = recorded(&recording.0); + let none = Scratch::new("warm-budget-none"); + let device_none = device(&none.0, None, None); + device_none.warm(records.clone(), 0); + let s = warmed(&device_none, STATES); + assert_eq!( + (s.records_not_run, s.records_warmed, s.pipeline_bytes), + (STATES, 0, 0), + "a budget of nothing warms nothing: {s:?}" + ); + let one = Scratch::new("warm-budget-one"); + let device_one = device(&one.0, None, None); + device_one.warm(records, 1); + let s = warmed(&device_one, STATES); + match s.pipeline_bytes { + 0 => println!("the driver added no pipeline cache data: the 1-byte leg is not judged"), + _ => assert_eq!( + (s.records_warmed, s.records_not_run), + (1, STATES - 1), + "the pass goes on past a spent budget: {s:?}" + ), + } +} + +/// A record whose library the directory no longer holds is counted unread and announced once, +/// as a warning, and the pass goes on: with the kernel's library removed from the directory, the +/// two compute records handed around the render one are unread, the render one is warmed between +/// them, and the device's sink hears the warning once. +#[test] +fn an_unread_record_is_announced_and_the_pass_goes_on() { + let scratch = Scratch::new("warm-unread"); + let records = recorded(&scratch.0); + // The kernel's library record: the content directory's file holding the library whose + // function table names `scale_and_offset` (`shader_cache/libraries.rs`). + let mut removed = 0; + for entry in walk(&scratch.0) { + let bytes = std::fs::read(&entry).unwrap(); + let named = bytes + .windows(b"scale_and_offset".len()) + .any(|window| window == b"scale_and_offset"); + if bytes.starts_with(b"M2VLIBR1") && named { + std::fs::remove_file(&entry).unwrap(); + removed += 1; + } + } + assert_eq!(removed, 1, "the directory holds the kernel's library once"); + let heard = Arc::new(Heard::default()); + let warm = device(&scratch.0, None, Some(&heard)); + // Carried as bytes, as a later process holds them: a record made in this process keeps its + // libraries and reads nothing from the directory. + let carried = |at: usize| PipelineRecord::from_bytes(&records[at].to_bytes()).unwrap(); + let order = vec![carried(1), carried(0), carried(2)]; + warm.warm(order, u64::MAX); + let s = warmed(&warm, STATES); + assert_eq!( + (s.records_unread, s.records_warmed, s.records_not_run), + (2, 1, 0), + "the compute records unread, the render one between them warmed: {s:?}" + ); + assert_eq!( + heard.named(crate::warm::UNREAD), + 1, + "the device's first unread record is announced, once" + ); +} + +/// Every file under `directory`, recursively. +fn walk(directory: &Path) -> Vec { + let mut files = Vec::new(); + let mut left = vec![directory.to_owned()]; + while let Some(at) = left.pop() { + for entry in std::fs::read_dir(&at).unwrap() { + let path = entry.unwrap().path(); + match path.is_dir() { + true => left.push(path), + false => files.push(path), + } + } + } + files +} diff --git a/crates/metal2vulkan-runtime/src/tests/warm_record.rs b/crates/metal2vulkan-runtime/src/tests/warm_record.rs new file mode 100644 index 000000000..fcea153e3 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/warm_record.rs @@ -0,0 +1,332 @@ +//! Pipeline records (`warm/record.rs`, `warm/codec.rs`): each kind's descriptor, every field away +//! from its default, reads back from its record's bytes equal; a record carried as bytes is the +//! same record; one library named twice is named once; and bytes of another record format, or +//! damaged, cut or foreign bytes, are no record. CPU only: a record compiles nothing. The +//! functions are those of the owned fixtures `validation/fixtures/public/engine/ob3_*.air`. + +use crate::warm::codec::{self, Pipeline, MAGIC, RECORD_FORMAT}; +use crate::PipelineRecord; +use metal2vulkan::library::{Function, FunctionConstantValue, FunctionConstantValues, Library}; +use metal2vulkan::metal::{self, DataType, PixelFormat}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, FunctionDescriptor, LinkedFunction, + LinkedFunctions, MeshPipelineDescriptor, RenderPipelineDescriptor, + StageInputAttributeDescriptor, StageInputDescriptor, StageInputLayoutDescriptor, StageSource, + TessellationDescriptor, TileRenderPipelineDescriptor, VertexAttributeDescriptor, + VertexBufferLayoutDescriptor, VertexDescriptor, +}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::path::Path; + +/// The library of the committed AIR of fixture `stem`. +fn library(stem: &str) -> Library { + let air = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/fixtures/public/engine") + .join(format!("{stem}.air")); + Library::from_air(&std::fs::read(air).expect("the committed AIR")).expect("a library") +} + +/// The function `name` of fixture `stem`. +fn function(stem: &str, name: &str) -> Function { + library(stem).function(name).expect("the function") +} + +/// Constant values by index and by name, of two types. +fn constants() -> FunctionConstantValues { + FunctionConstantValues::defaults() + .with_index( + 3, + FunctionConstantValue::new(DataType::UInt, 7u32.to_le_bytes()), + ) + .with_name( + "scale", + FunctionConstantValue::new(DataType::Float, 1.5f32.to_le_bytes()), + ) +} + +/// A stage of `f` with constants and linked functions in every list and a group. +fn stage(f: Function) -> StageSource { + let linked = function("ob3_texture_array", "ob3_texture_array"); + let mut functions = LinkedFunctions::new() + .with_function(LinkedFunction::new(linked.clone()).with_constants(constants())) + .with_private_function(linked.clone()); + functions + .binary_functions + .push(LinkedFunction::new(linked.clone()).with_precompiled(true)); + functions + .groups + .insert("group".into(), vec![LinkedFunction::new(linked)]); + let mut descriptor = FunctionDescriptor::new(f); + descriptor.constants = constants(); + descriptor.linked = functions; + StageSource::Function(descriptor) +} + +/// Two buffers' mutability. +fn mutability() -> BTreeMap { + BTreeMap::from([ + (0, metal::Mutability::Immutable), + (5, metal::Mutability::Mutable), + ]) +} + +/// A color attachment with every field away from its default. +fn color(format: PixelFormat) -> ColorAttachmentDescriptor { + let mut c = ColorAttachmentDescriptor::new(format); + c.blending_enabled = true; + c.source_rgb_blend_factor = metal::BlendFactor::SourceAlpha; + c.destination_rgb_blend_factor = metal::BlendFactor::OneMinusSourceAlpha; + c.rgb_blend_operation = metal::BlendOperation::Max; + c.source_alpha_blend_factor = metal::BlendFactor::One; + c.destination_alpha_blend_factor = metal::BlendFactor::SourceAlpha; + c.alpha_blend_operation = metal::BlendOperation::ReverseSubtract; + c.write_mask = metal::ColorWriteMask::RED | metal::ColorWriteMask::ALPHA; + c +} + +fn compute() -> Pipeline { + let mut d = + ComputePipelineDescriptor::new(stage(function("ob3_texture_array", "ob3_texture_array"))); + let mut input = StageInputDescriptor::new(); + let mut layout = StageInputLayoutDescriptor::new(Some(16)); + layout.step_function = metal::StepFunction::PerInstance; + layout.step_rate = 2; + input.layouts.insert(1, layout); + input.attributes.insert( + 3, + StageInputAttributeDescriptor::new(metal::AttributeFormat::UChar4, 4, 1), + ); + input.index_type = metal::IndexType::UInt32; + input.index_buffer_index = 9; + d.stage_input = Some(input); + d.max_total_threads_per_threadgroup = Some(256); + d.threadgroup_size_is_multiple_of_execution_width = true; + d.support_indirect_command_buffers = true; + d.max_call_stack_depth = 3; + d.required_threads_per_threadgroup = Some([8, 4, 2]); + d.support_adding_binary_functions = true; + d.buffers = mutability(); + d.needs_custom_border_color_samplers = true; + Pipeline::Compute(d, 2) +} + +fn render() -> Pipeline { + let vertex = function("ob3_vertex_input", "ob3_vertex_input"); + let mut d = RenderPipelineDescriptor::new(stage(vertex.clone())); + d.fragment = Some(StageSource::Function(FunctionDescriptor::new(vertex))); + let mut v = VertexDescriptor::new(); + let mut layout = VertexBufferLayoutDescriptor::new(None); + layout.step_function = metal::VertexStepFunction::PerInstance; + layout.step_rate = 3; + v.layouts.insert(2, layout); + v.attributes.insert( + 1, + VertexAttributeDescriptor::new(metal::VertexFormat::UChar4, 8, 2), + ); + d.vertex_descriptor = Some(v); + d.color_attachments[0] = Some(color(PixelFormat::RGBA8Unorm)); + d.color_attachments[5] = Some(color(PixelFormat::RGBA16Float)); + d.depth_format = Some(PixelFormat::Depth32Float); + d.stencil_format = Some(PixelFormat::Stencil8); + d.raster_sample_count = 4; + d.alpha_to_coverage = true; + d.alpha_to_one = true; + d.rasterization_enabled = false; + d.input_primitive_topology = metal::PrimitiveTopologyClass::Line; + d.max_vertex_amplification_count = 2; + let mut t = TessellationDescriptor::default(); + t.max_tessellation_factor = 32; + t.partition_mode = metal::TessellationPartitionMode::FractionalOdd; + t.factor_step_function = metal::TessellationFactorStepFunction::PerPatchAndPerInstance; + t.output_winding_order = metal::Winding::CounterClockwise; + t.control_point_index_type = metal::TessellationControlPointIndexType::UInt16; + t.factor_scale_enabled = true; + d.tessellation = Some(t); + d.support_indirect_command_buffers = true; + d.max_vertex_call_stack_depth = 2; + d.max_fragment_call_stack_depth = 5; + d.support_adding_vertex_binary_functions = true; + d.support_adding_fragment_binary_functions = true; + d.vertex_buffers = mutability(); + d.fragment_buffers = BTreeMap::from([(1, metal::Mutability::Immutable)]); + d.texture_write_rounding_mode = metal::TextureWriteRoundingMode::NearestEven; + let p = &mut d.private; + p.sample_mask = 0x0f; + p.sample_coverage = 0.5; + p.sample_coverage_invert = true; + p.alpha_test_enabled = true; + p.alpha_test_function = 3; + p.logic_operation_enabled = true; + p.logic_operation = 10; + p.clip_distance_enable_mask = 0x3; + p.point_smooth_enabled = true; + p.point_coord_lower_left = true; + p.point_size_output_vs = true; + p.two_side_enabled = true; + p.vertex_depth_compare_clamp_mask = 0x10; + p.fragment_depth_compare_clamp_mask = 0x8000_0001; + p.depth_stencil_write_disabled = true; + p.needs_custom_border_color_samplers = true; + p.vertex_amplification_mode = 1; + p.explicit_visibility_group_id = 4; + Pipeline::Render(d, [1, 3]) +} + +fn mesh() -> Pipeline { + let f = function("ob3_vertex_input", "ob3_vertex_input"); + let mut d = MeshPipelineDescriptor::new(stage(f.clone())); + d.object = Some(StageSource::Function(FunctionDescriptor::new(f.clone()))); + d.fragment = Some(stage(f)); + d.color_attachments[2] = Some(color(PixelFormat::BGRA8Unorm)); + d.depth_format = Some(PixelFormat::Depth32Float); + d.stencil_format = Some(PixelFormat::Stencil8); + d.raster_sample_count = 2; + d.rasterization_enabled = false; + d.alpha_to_coverage = true; + d.alpha_to_one = true; + d.support_indirect_command_buffers = true; + d.texture_write_rounding_mode = metal::TextureWriteRoundingMode::NearestEven; + Pipeline::Mesh(d) +} + +fn tile() -> Pipeline { + let mut d = TileRenderPipelineDescriptor::new(stage(function( + "ob3_texture_array", + "ob3_texture_array", + ))); + d.color_attachment_formats[0] = Some(PixelFormat::RGBA8Unorm); + d.color_attachment_formats[7] = Some(PixelFormat::R32Float); + d.raster_sample_count = 4; + d.threadgroup_size_matches_tile_size = true; + d.max_total_threads_per_threadgroup = Some(64); + d.max_call_stack_depth = 4; + d.required_threads_per_threadgroup = Some([16, 16, 1]); + d.support_adding_binary_functions = true; + d.buffers = mutability(); + Pipeline::Tile(d, 1) +} + +/// Every kind, every field away from its default, reads back from its record's bytes equal to +/// what was recorded; the same record carried as bytes is the same record, and its bytes are its +/// own; and the defaults round-trip too. +#[test] +fn every_kind_reads_back_field_for_field() { + let defaults = [ + Pipeline::Compute( + ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( + function("ob3_texture_array", "ob3_texture_array"), + ))), + 0, + ), + Pipeline::Render( + RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( + function("ob3_vertex_input", "ob3_vertex_input"), + ))), + [0, 0], + ), + ]; + for pipeline in [compute(), render(), mesh(), tile()] + .into_iter() + .chain(defaults) + { + let record = PipelineRecord::of(&pipeline).expect("a record"); + let bytes = record.to_bytes(); + assert_eq!( + codec::decode(&bytes, record.libraries()).expect("it reads back"), + pipeline + ); + let carried = PipelineRecord::from_bytes(&bytes).expect("the bytes are a record"); + assert_eq!( + carried, record, + "a record carried as bytes is the same record" + ); + assert_eq!(carried.to_bytes(), bytes); + assert!( + carried.libraries().is_empty(), + "its libraries stay in the directory" + ); + } +} + +/// Equal creations make equal bytes, and a creation that differs in one field makes others. +#[test] +fn a_record_is_its_creation_and_nothing_else() { + let a = PipelineRecord::of(&render()).unwrap(); + let b = PipelineRecord::of(&render()).unwrap(); + assert_eq!(a, b); + let Pipeline::Render(mut d, added) = render() else { + unreachable!() + }; + d.private.sample_mask = 0x1f; + assert_ne!(a, PipelineRecord::of(&Pipeline::Render(d, added)).unwrap()); +} + +/// Functions of one library, in every stage and linked list, name that library once; a function +/// of another library adds it. +#[test] +fn one_library_is_named_once() { + let record = PipelineRecord::of(&mesh()).unwrap(); + // The mesh, object and fragment functions are of one library, the linked functions of + // another. + assert_eq!(record.libraries().len(), 2); + let one = library("ob3_vertex_input"); + let vertex = one.function("ob3_vertex_input").unwrap(); + let mut d = RenderPipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new( + vertex.clone(), + ))); + d.fragment = Some(StageSource::Function(FunctionDescriptor::new(vertex))); + let record = PipelineRecord::of(&Pipeline::Render(d, [0, 0])).unwrap(); + assert_eq!(record.libraries(), std::slice::from_ref(&one)); +} + +/// `bytes` with their checksum made again: a record whose checksum holds over whatever they say. +fn resealed(mut bytes: Vec) -> Vec { + let body = bytes.len() - 32; + let checksum: [u8; 32] = Sha256::digest(&bytes[..body]).into(); + bytes[body..].copy_from_slice(&checksum); + bytes +} + +/// A record of another format is dropped as it is read, though its checksum holds; so are +/// damaged, cut, empty and foreign bytes. Bytes whose libraries are not the record's read nothing. +#[test] +fn a_record_of_another_format_or_damaged_is_dropped() { + let record = PipelineRecord::of(&compute()).unwrap(); + let bytes = record.to_bytes(); + assert_eq!(&bytes[..8], MAGIC); + assert!(PipelineRecord::from_bytes(&bytes).is_some()); + let mut other = bytes.clone(); + other[8..12].copy_from_slice(&(RECORD_FORMAT + 1).to_le_bytes()); + assert!( + PipelineRecord::from_bytes(&resealed(other)).is_none(), + "another format" + ); + let mut damaged = bytes.clone(); + damaged[20] ^= 1; + assert!(PipelineRecord::from_bytes(&damaged).is_none(), "damaged"); + assert!( + PipelineRecord::from_bytes(&bytes[..bytes.len() - 1]).is_none(), + "cut" + ); + assert!(PipelineRecord::from_bytes(&[]).is_none(), "empty"); + assert!(PipelineRecord::from_bytes(b"not a record at all, nor near one").is_none()); + let mut magic = bytes.clone(); + magic[0] = b'X'; + assert!( + PipelineRecord::from_bytes(&resealed(magic)).is_none(), + "another magic" + ); + // A body the record's checksum holds over but that reads past or short of its fields. + let mut longer = bytes[..bytes.len() - 32].to_vec(); + longer.push(0); + longer.extend_from_slice(&[0; 32]); + assert!(codec::decode(&resealed(longer), record.libraries()).is_err()); + // Other libraries than the ones it names, or its own in another order. + assert!(codec::decode(&bytes, &[]).is_err()); + let two = PipelineRecord::of(&mesh()).unwrap(); + let swapped: Vec = two.libraries().iter().rev().cloned().collect(); + assert_eq!(swapped.len(), 2); + assert!(codec::decode(&two.to_bytes(), two.libraries()).is_ok()); + assert!(codec::decode(&two.to_bytes(), &swapped).is_err()); +} diff --git a/crates/metal2vulkan-runtime/src/warm/codec.rs b/crates/metal2vulkan-runtime/src/warm/codec.rs new file mode 100644 index 000000000..9732cc833 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/warm/codec.rs @@ -0,0 +1,889 @@ +//! A pipeline record's bytes: the descriptor of a pipeline state's creation, field by field, its +//! libraries named by their content hash. +//! +//! ```text +//! magic "M2VPREC\0" | RECORD_FORMAT u32 | body | SHA-256 of all before it +//! body: libraries (count u32, each: content hash, length u64) | kind u8 | the kind's fields +//! ``` +//! +//! - **Every field.** Each descriptor field is written in declaration order: integers little +//! endian, a `bool` as one byte 0 or 1, an enum as its raw Metal value (`as_raw`, read back +//! through its checked `TryFrom`), an `Option` as a byte 0 or 1 and the value, a list or a +//! map as a `u32` count and its entries in order. A function is its library's place in the +//! record's list and its index in the library's table. Bytes of an unknown enum value, a +//! `bool` other than 0 or 1, a count past the bytes left, or bytes left over are no record. +//! - **What cannot be written.** A stage the compile layer already compiled +//! (`StageSource::Compiled`), and a value of a non-exhaustive enum this codec does not know, +//! make no record ([`Unwritable`]): the creation is made, unrecorded, and counted. +//! - **Checked at the making.** A record is read back the moment it is made, from its own bytes +//! with the creation's own libraries, and kept only where what it reads equals the creation's +//! descriptor (`PipelineRecord::of`): a field this codec missed makes no record, rather than a +//! record of another pipeline. +//! - **Versioned by its format.** [`RECORD_FORMAT`] moves whenever these bytes change meaning (a +//! field added, removed or re-typed); a record of another format is not read. A record holds +//! inputs, no translation, so no translator or runtime version decides whether it is read. + +use metal2vulkan::cache::Hash256; +use metal2vulkan::library::{ + DynamicLibrary, Function, FunctionConstantValue, FunctionConstantValues, Library, +}; +use metal2vulkan::metal; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, DynamicLibraries, FunctionDescriptor, + LinkedFunction, LinkedFunctions, MeshPipelineDescriptor, PrivateRenderState, + RenderPipelineDescriptor, StageInputAttributeDescriptor, StageInputDescriptor, + StageInputLayoutDescriptor, StageSource, TessellationDescriptor, TileRenderPipelineDescriptor, + VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, +}; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, HashMap}; + +/// The first bytes of a record. +pub(crate) const MAGIC: &[u8; 8] = b"M2VPREC\0"; + +/// The record format: bumped whenever a record's bytes change meaning (the module docs). +pub(crate) const RECORD_FORMAT: u32 = 1; + +/// The length of a record's header (magic and format) and of its checksum. +const HEADER: usize = 8 + 4; +const CHECKSUM: usize = 32; + +/// What a record describes: one pipeline state creation's descriptor, and how many of its +/// stages' last binary functions were added without the stage's support flag +/// (`new_*_pipeline_state_with_additional_binary_functions`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Pipeline { + Compute(ComputePipelineDescriptor, usize), + /// The vertex stage's count, then the fragment stage's. + Render(RenderPipelineDescriptor, [usize; 2]), + Mesh(MeshPipelineDescriptor), + Tile(TileRenderPipelineDescriptor, usize), +} + +impl Pipeline { + /// The kind's byte. + fn kind(&self) -> u8 { + match self { + Pipeline::Compute(..) => 1, + Pipeline::Render(..) => 2, + Pipeline::Mesh(..) => 3, + Pipeline::Tile(..) => 4, + } + } +} + +/// A creation this codec cannot write (the module docs). +#[derive(Debug)] +pub(crate) struct Unwritable; + +/// Bytes that are no record of this format: damaged, of another format, or not a record. +#[derive(Debug)] +pub(crate) struct Unreadable; + +/// `pipeline`'s record bytes, and the libraries they name, in the order their places number them. +pub(crate) fn encode(pipeline: &Pipeline) -> Result<(Vec, Vec), Unwritable> { + let mut w = Writer::default(); + w.u8(pipeline.kind()); + match pipeline { + Pipeline::Compute(d, added) => { + w.compute(d)?; + w.usize(*added); + } + Pipeline::Render(d, [vertex, fragment]) => { + w.render(d)?; + w.usize(*vertex); + w.usize(*fragment); + } + Pipeline::Mesh(d) => w.mesh(d)?, + Pipeline::Tile(d, added) => { + w.tile(d)?; + w.usize(*added); + } + } + let Writer { + out: fields, + libraries, + .. + } = w; + let mut out = Vec::with_capacity(HEADER + 4 + libraries.len() * 40 + fields.len() + CHECKSUM); + out.extend_from_slice(MAGIC); + out.extend_from_slice(&RECORD_FORMAT.to_le_bytes()); + out.extend_from_slice(&count(libraries.len())?.to_le_bytes()); + for library in &libraries { + out.extend_from_slice(library.content_hash()); + out.extend_from_slice(&(library.bytes().len() as u64).to_le_bytes()); + } + out.extend_from_slice(&fields); + let checksum: Hash256 = Sha256::digest(&out).into(); + out.extend_from_slice(&checksum); + Ok((out, libraries)) +} + +/// Whether `bytes` are a whole record of this format: its magic, its format and its checksum. +pub(crate) fn is_record(bytes: &[u8]) -> bool { + if bytes.len() < HEADER + CHECKSUM || &bytes[..8] != MAGIC { + return false; + } + if bytes[8..HEADER] != RECORD_FORMAT.to_le_bytes() { + return false; + } + let (signed, checksum) = bytes.split_at(bytes.len() - CHECKSUM); + <[u8; 32]>::from(Sha256::digest(signed)) == checksum +} + +/// What `bytes`, a record ([`is_record`]), describe, with `libraries` the libraries its table +/// names, in its order ([`libraries`]). +pub(crate) fn decode(bytes: &[u8], libraries: &[Library]) -> Result { + let mut r = Reader::body(bytes, libraries)?; + let table = r.library_table()?; + if table.len() != libraries.len() + || table + .iter() + .zip(libraries) + .any(|((hash, length), library)| { + hash != library.content_hash() || *length != library.bytes().len() as u64 + }) + { + return Err(Unreadable); + } + let pipeline = match r.u8()? { + 1 => Pipeline::Compute(r.compute()?, r.usize()?), + 2 => Pipeline::Render(r.render()?, [r.usize()?, r.usize()?]), + 3 => Pipeline::Mesh(r.mesh()?), + 4 => Pipeline::Tile(r.tile()?, r.usize()?), + _ => return Err(Unreadable), + }; + match r.at == r.bytes.len() { + true => Ok(pipeline), + false => Err(Unreadable), + } +} + +/// The libraries `bytes`, a record ([`is_record`]), names, each by its content hash and its +/// container's length, in their places' order: what [`decode`] is then handed. +pub(crate) fn libraries(bytes: &[u8]) -> Result, Unreadable> { + Reader::body(bytes, &[])?.library_table() +} + +/// `n` as a record's count, where it fits. +fn count(n: usize) -> Result { + u32::try_from(n).map_err(|_| Unwritable) +} + +/// The encoder's state: the bytes of the fields so far, and the libraries they name. +#[derive(Default)] +struct Writer { + out: Vec, + libraries: Vec, + places: HashMap, +} + +impl Writer { + fn u8(&mut self, v: u8) { + self.out.push(v); + } + + fn u32(&mut self, v: u32) { + self.out.extend_from_slice(&v.to_le_bytes()); + } + + fn u64(&mut self, v: u64) { + self.out.extend_from_slice(&v.to_le_bytes()); + } + + fn usize(&mut self, v: usize) { + self.u64(v as u64); + } + + fn bool(&mut self, v: bool) { + self.u8(u8::from(v)); + } + + fn bytes(&mut self, v: &[u8]) -> Result<(), Unwritable> { + self.u32(count(v.len())?); + self.out.extend_from_slice(v); + Ok(()) + } + + fn opt_u32(&mut self, v: Option) { + self.bool(v.is_some()); + if let Some(v) = v { + self.u32(v); + } + } + + fn threads(&mut self, v: Option<[u32; 3]>) { + self.bool(v.is_some()); + for n in v.into_iter().flatten() { + self.u32(n); + } + } + + fn pixel_format(&mut self, v: Option) { + self.opt_u32(v.map(metal::PixelFormat::as_raw)); + } + + fn mutability(&mut self, v: &BTreeMap) -> Result<(), Unwritable> { + self.u32(count(v.len())?); + for (index, mutability) in v { + self.u32(*index); + self.u32(mutability.as_raw()); + } + Ok(()) + } + + fn rounding(&mut self, v: metal::TextureWriteRoundingMode) -> Result<(), Unwritable> { + self.u32(match v { + metal::TextureWriteRoundingMode::TowardZero => 0, + metal::TextureWriteRoundingMode::NearestEven => 2, + _ => return Err(Unwritable), + }); + Ok(()) + } + + /// The place of `library` in the record's list, given one at its first use. + fn library(&mut self, library: &Library) -> Result { + if let Some(&place) = self.places.get(library.content_hash()) { + return Ok(place); + } + let place = count(self.libraries.len())?; + self.places.insert(*library.content_hash(), place); + self.libraries.push(library.clone()); + Ok(place) + } + + fn function(&mut self, f: &Function) -> Result<(), Unwritable> { + let place = self.library(f.library())?; + self.u32(place); + self.u32(f.index()); + Ok(()) + } + + fn constant(&mut self, v: &FunctionConstantValue) -> Result<(), Unwritable> { + self.u32(v.ty.as_raw()); + self.bytes(&v.bytes) + } + + fn constants(&mut self, v: &FunctionConstantValues) -> Result<(), Unwritable> { + self.u32(count(v.by_index.len())?); + for (index, value) in &v.by_index { + self.u32(*index); + self.constant(value)?; + } + self.u32(count(v.by_name.len())?); + for (name, value) in &v.by_name { + self.bytes(name.as_bytes())?; + self.constant(value)?; + } + Ok(()) + } + + fn linked_list(&mut self, v: &[LinkedFunction]) -> Result<(), Unwritable> { + self.u32(count(v.len())?); + for f in v { + self.function(&f.function)?; + self.constants(&f.constants)?; + self.bool(f.precompiled); + } + Ok(()) + } + + fn linked(&mut self, v: &LinkedFunctions) -> Result<(), Unwritable> { + self.linked_list(&v.functions)?; + self.linked_list(&v.private_functions)?; + self.linked_list(&v.binary_functions)?; + self.u32(count(v.groups.len())?); + for (name, functions) in &v.groups { + self.bytes(name.as_bytes())?; + self.linked_list(functions)?; + } + Ok(()) + } + + fn dynamic(&mut self, v: &DynamicLibraries) -> Result<(), Unwritable> { + self.u32(count(v.preloaded.len())?); + for library in &v.preloaded { + let place = self.library(library.library())?; + self.u32(place); + } + self.u32(count(v.loaded.len())?); + for (name, library) in &v.loaded { + self.bytes(name.as_bytes())?; + let place = self.library(library.library())?; + self.u32(place); + } + Ok(()) + } + + fn stage(&mut self, v: &StageSource) -> Result<(), Unwritable> { + let StageSource::Function(f) = v else { + return Err(Unwritable); + }; + self.function(&f.function)?; + self.constants(&f.constants)?; + self.linked(&f.linked)?; + self.dynamic(&f.libraries) + } + + fn opt_stage(&mut self, v: Option<&StageSource>) -> Result<(), Unwritable> { + self.bool(v.is_some()); + match v { + Some(stage) => self.stage(stage), + None => Ok(()), + } + } + + fn colors(&mut self, v: &[Option; 8]) { + for color in v { + self.bool(color.is_some()); + if let Some(c) = color { + self.u32(c.pixel_format.as_raw()); + self.bool(c.blending_enabled); + self.u32(c.source_rgb_blend_factor.as_raw()); + self.u32(c.destination_rgb_blend_factor.as_raw()); + self.u32(c.rgb_blend_operation.as_raw()); + self.u32(c.source_alpha_blend_factor.as_raw()); + self.u32(c.destination_alpha_blend_factor.as_raw()); + self.u32(c.alpha_blend_operation.as_raw()); + self.u32(c.write_mask.as_raw()); + } + } + } + + fn vertex_descriptor(&mut self, v: Option<&VertexDescriptor>) -> Result<(), Unwritable> { + self.bool(v.is_some()); + let Some(v) = v else { + return Ok(()); + }; + self.u32(count(v.layouts.len())?); + for (index, layout) in &v.layouts { + self.u32(*index); + self.opt_u32(layout.stride); + self.u32(layout.step_function.as_raw()); + self.u32(layout.step_rate); + } + self.u32(count(v.attributes.len())?); + for (index, attribute) in &v.attributes { + self.u32(*index); + self.u32(attribute.format.as_raw()); + self.u32(attribute.offset); + self.u32(attribute.buffer_index); + } + Ok(()) + } + + fn stage_input(&mut self, v: Option<&StageInputDescriptor>) -> Result<(), Unwritable> { + self.bool(v.is_some()); + let Some(v) = v else { + return Ok(()); + }; + self.u32(count(v.layouts.len())?); + for (index, layout) in &v.layouts { + self.u32(*index); + self.opt_u32(layout.stride); + self.u32(layout.step_function.as_raw()); + self.u32(layout.step_rate); + } + self.u32(count(v.attributes.len())?); + for (index, attribute) in &v.attributes { + self.u32(*index); + self.u32(attribute.format.as_raw()); + self.u32(attribute.offset); + self.u32(attribute.buffer_index); + } + self.u32(v.index_type.as_raw()); + self.u32(v.index_buffer_index); + Ok(()) + } + + fn tessellation(&mut self, v: Option<&TessellationDescriptor>) { + self.bool(v.is_some()); + if let Some(t) = v { + self.u32(t.max_tessellation_factor); + self.u32(t.partition_mode.as_raw()); + self.u32(t.factor_format.as_raw()); + self.u32(t.factor_step_function.as_raw()); + self.u32(t.output_winding_order.as_raw()); + self.u32(t.control_point_index_type.as_raw()); + self.bool(t.factor_scale_enabled); + } + } + + fn private(&mut self, p: &PrivateRenderState) { + self.u64(p.sample_mask); + self.u32(p.sample_coverage.to_bits()); + self.bool(p.sample_coverage_invert); + self.bool(p.alpha_test_enabled); + self.u64(p.alpha_test_function); + self.bool(p.logic_operation_enabled); + self.u64(p.logic_operation); + self.u8(p.clip_distance_enable_mask); + self.bool(p.point_smooth_enabled); + self.bool(p.point_coord_lower_left); + self.bool(p.point_size_output_vs); + self.bool(p.two_side_enabled); + self.u32(p.vertex_depth_compare_clamp_mask); + self.u32(p.fragment_depth_compare_clamp_mask); + self.bool(p.depth_stencil_write_disabled); + self.bool(p.needs_custom_border_color_samplers); + self.u64(p.vertex_amplification_mode); + self.u32(p.explicit_visibility_group_id); + } + + fn compute(&mut self, d: &ComputePipelineDescriptor) -> Result<(), Unwritable> { + self.stage(&d.kernel)?; + self.stage_input(d.stage_input.as_ref())?; + self.opt_u32(d.max_total_threads_per_threadgroup); + self.bool(d.threadgroup_size_is_multiple_of_execution_width); + self.bool(d.support_indirect_command_buffers); + self.u32(d.max_call_stack_depth); + self.threads(d.required_threads_per_threadgroup); + self.bool(d.support_adding_binary_functions); + self.mutability(&d.buffers)?; + self.bool(d.needs_custom_border_color_samplers); + Ok(()) + } + + fn render(&mut self, d: &RenderPipelineDescriptor) -> Result<(), Unwritable> { + self.stage(&d.vertex)?; + self.opt_stage(d.fragment.as_ref())?; + self.vertex_descriptor(d.vertex_descriptor.as_ref())?; + self.colors(&d.color_attachments); + self.pixel_format(d.depth_format); + self.pixel_format(d.stencil_format); + self.u32(d.raster_sample_count); + self.bool(d.alpha_to_coverage); + self.bool(d.alpha_to_one); + self.bool(d.rasterization_enabled); + self.u32(d.input_primitive_topology.as_raw()); + self.u32(d.max_vertex_amplification_count); + self.tessellation(d.tessellation.as_ref()); + self.bool(d.support_indirect_command_buffers); + self.u32(d.max_vertex_call_stack_depth); + self.u32(d.max_fragment_call_stack_depth); + self.bool(d.support_adding_vertex_binary_functions); + self.bool(d.support_adding_fragment_binary_functions); + self.mutability(&d.vertex_buffers)?; + self.mutability(&d.fragment_buffers)?; + self.rounding(d.texture_write_rounding_mode)?; + self.private(&d.private); + Ok(()) + } + + fn mesh(&mut self, d: &MeshPipelineDescriptor) -> Result<(), Unwritable> { + self.opt_stage(d.object.as_ref())?; + self.stage(&d.mesh)?; + self.opt_stage(d.fragment.as_ref())?; + self.colors(&d.color_attachments); + self.pixel_format(d.depth_format); + self.pixel_format(d.stencil_format); + self.u32(d.raster_sample_count); + self.bool(d.rasterization_enabled); + self.bool(d.alpha_to_coverage); + self.bool(d.alpha_to_one); + self.bool(d.support_indirect_command_buffers); + self.rounding(d.texture_write_rounding_mode) + } + + fn tile(&mut self, d: &TileRenderPipelineDescriptor) -> Result<(), Unwritable> { + self.stage(&d.tile)?; + for format in d.color_attachment_formats { + self.pixel_format(format); + } + self.u32(d.raster_sample_count); + self.bool(d.threadgroup_size_matches_tile_size); + self.opt_u32(d.max_total_threads_per_threadgroup); + self.u32(d.max_call_stack_depth); + self.threads(d.required_threads_per_threadgroup); + self.bool(d.support_adding_binary_functions); + self.mutability(&d.buffers) + } +} + +/// The decoder's state: a record's body, how far it has read, and the libraries its places name. +struct Reader<'a> { + bytes: &'a [u8], + at: usize, + libraries: &'a [Library], +} + +impl<'a> Reader<'a> { + /// A reader of the body of `record`, a whole record ([`is_record`]), with its libraries. + fn body(record: &'a [u8], libraries: &'a [Library]) -> Result, Unreadable> { + if !is_record(record) { + return Err(Unreadable); + } + Ok(Reader { + bytes: &record[HEADER..record.len() - CHECKSUM], + at: 0, + libraries, + }) + } + + fn take(&mut self, n: usize) -> Result<&'a [u8], Unreadable> { + let end = self.at.checked_add(n).ok_or(Unreadable)?; + let taken = self.bytes.get(self.at..end).ok_or(Unreadable)?; + self.at = end; + Ok(taken) + } + + fn u8(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + + fn u32(&mut self) -> Result { + let bytes = self.take(4)?.try_into().map_err(|_| Unreadable)?; + Ok(u32::from_le_bytes(bytes)) + } + + fn u64(&mut self) -> Result { + let bytes = self.take(8)?.try_into().map_err(|_| Unreadable)?; + Ok(u64::from_le_bytes(bytes)) + } + + fn usize(&mut self) -> Result { + usize::try_from(self.u64()?).map_err(|_| Unreadable) + } + + fn bool(&mut self) -> Result { + match self.u8()? { + 0 => Ok(false), + 1 => Ok(true), + _ => Err(Unreadable), + } + } + + /// A count of entries each at least `least` bytes long: past the bytes left is no record. + fn count(&mut self, least: usize) -> Result { + let n = self.u32()? as usize; + match n.saturating_mul(least) <= self.bytes.len() - self.at { + true => Ok(n), + false => Err(Unreadable), + } + } + + fn bytes(&mut self) -> Result<&'a [u8], Unreadable> { + let n = self.count(1)?; + self.take(n) + } + + fn string(&mut self) -> Result { + let bytes = self.bytes()?; + String::from_utf8(bytes.to_vec()).map_err(|_| Unreadable) + } + + fn opt_u32(&mut self) -> Result, Unreadable> { + match self.bool()? { + true => Ok(Some(self.u32()?)), + false => Ok(None), + } + } + + fn threads(&mut self) -> Result, Unreadable> { + match self.bool()? { + true => Ok(Some([self.u32()?, self.u32()?, self.u32()?])), + false => Ok(None), + } + } + + /// A Metal enum or option set, by its checked `TryFrom`. + fn raw>(&mut self) -> Result { + T::try_from(self.u32()?).map_err(|_| Unreadable) + } + + fn pixel_format(&mut self) -> Result, Unreadable> { + match self.bool()? { + true => Ok(Some(self.raw()?)), + false => Ok(None), + } + } + + fn mutability(&mut self) -> Result, Unreadable> { + let n = self.count(8)?; + let mut out = BTreeMap::new(); + for _ in 0..n { + let index = self.u32()?; + out.insert(index, self.raw()?); + } + Ok(out) + } + + fn rounding(&mut self) -> Result { + match self.u32()? { + 0 => Ok(metal::TextureWriteRoundingMode::TowardZero), + 2 => Ok(metal::TextureWriteRoundingMode::NearestEven), + _ => Err(Unreadable), + } + } + + fn library_table(&mut self) -> Result, Unreadable> { + let n = self.count(40)?; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + let hash: Hash256 = self.take(32)?.try_into().map_err(|_| Unreadable)?; + out.push((hash, self.u64()?)); + } + Ok(out) + } + + fn library(&mut self) -> Result { + let place = self.u32()? as usize; + self.libraries.get(place).cloned().ok_or(Unreadable) + } + + fn function(&mut self) -> Result { + let library = self.library()?; + let index = self.u32()?; + library.function_at(index).map_err(|_| Unreadable) + } + + fn constant(&mut self) -> Result { + let ty: metal::DataType = self.raw()?; + Ok(FunctionConstantValue::new(ty, self.bytes()?.to_vec())) + } + + fn constants(&mut self) -> Result { + let mut out = FunctionConstantValues::defaults(); + for _ in 0..self.count(8)? { + let index = self.u32()?; + out = out.with_index(index, self.constant()?); + } + for _ in 0..self.count(8)? { + let name = self.string()?; + out = out.with_name(name, self.constant()?); + } + Ok(out) + } + + fn linked_list(&mut self) -> Result, Unreadable> { + let n = self.count(17)?; + let mut out = Vec::with_capacity(n); + for _ in 0..n { + let function = self.function()?; + let constants = self.constants()?; + let precompiled = self.bool()?; + out.push( + LinkedFunction::new(function) + .with_constants(constants) + .with_precompiled(precompiled), + ); + } + Ok(out) + } + + fn linked(&mut self) -> Result { + let mut out = LinkedFunctions::new(); + out.functions = self.linked_list()?; + out.private_functions = self.linked_list()?; + out.binary_functions = self.linked_list()?; + for _ in 0..self.count(8)? { + let name = self.string()?; + out.groups.insert(name, self.linked_list()?); + } + Ok(out) + } + + fn dynamic_library(&mut self) -> Result { + DynamicLibrary::loaded(self.library()?).map_err(|_| Unreadable) + } + + fn dynamic(&mut self) -> Result { + let mut out = DynamicLibraries::new(); + for _ in 0..self.count(4)? { + out.preloaded.push(self.dynamic_library()?); + } + for _ in 0..self.count(8)? { + let name = self.string()?; + out.loaded.insert(name, self.dynamic_library()?); + } + Ok(out) + } + + fn stage(&mut self) -> Result { + let mut f = FunctionDescriptor::new(self.function()?); + f.constants = self.constants()?; + f.linked = self.linked()?; + f.libraries = self.dynamic()?; + Ok(StageSource::Function(f)) + } + + fn opt_stage(&mut self) -> Result, Unreadable> { + match self.bool()? { + true => Ok(Some(self.stage()?)), + false => Ok(None), + } + } + + fn colors(&mut self) -> Result<[Option; 8], Unreadable> { + let mut out: [Option; 8] = Default::default(); + for slot in &mut out { + if !self.bool()? { + continue; + } + let mut c = ColorAttachmentDescriptor::new(self.raw()?); + c.blending_enabled = self.bool()?; + c.source_rgb_blend_factor = self.raw()?; + c.destination_rgb_blend_factor = self.raw()?; + c.rgb_blend_operation = self.raw()?; + c.source_alpha_blend_factor = self.raw()?; + c.destination_alpha_blend_factor = self.raw()?; + c.alpha_blend_operation = self.raw()?; + c.write_mask = self.raw()?; + *slot = Some(c); + } + Ok(out) + } + + fn vertex_descriptor(&mut self) -> Result, Unreadable> { + if !self.bool()? { + return Ok(None); + } + let mut v = VertexDescriptor::new(); + for _ in 0..self.count(13)? { + let index = self.u32()?; + let mut layout = VertexBufferLayoutDescriptor::new(self.opt_u32()?); + layout.step_function = self.raw()?; + layout.step_rate = self.u32()?; + v.layouts.insert(index, layout); + } + for _ in 0..self.count(16)? { + let index = self.u32()?; + let attribute = VertexAttributeDescriptor::new(self.raw()?, self.u32()?, self.u32()?); + v.attributes.insert(index, attribute); + } + Ok(Some(v)) + } + + fn stage_input(&mut self) -> Result, Unreadable> { + if !self.bool()? { + return Ok(None); + } + let mut v = StageInputDescriptor::new(); + for _ in 0..self.count(13)? { + let index = self.u32()?; + let mut layout = StageInputLayoutDescriptor::new(self.opt_u32()?); + layout.step_function = self.raw()?; + layout.step_rate = self.u32()?; + v.layouts.insert(index, layout); + } + for _ in 0..self.count(16)? { + let index = self.u32()?; + let attribute = + StageInputAttributeDescriptor::new(self.raw()?, self.u32()?, self.u32()?); + v.attributes.insert(index, attribute); + } + v.index_type = self.raw()?; + v.index_buffer_index = self.u32()?; + Ok(Some(v)) + } + + fn tessellation(&mut self) -> Result, Unreadable> { + if !self.bool()? { + return Ok(None); + } + let mut t = TessellationDescriptor::default(); + t.max_tessellation_factor = self.u32()?; + t.partition_mode = self.raw()?; + t.factor_format = self.raw()?; + t.factor_step_function = self.raw()?; + t.output_winding_order = self.raw()?; + t.control_point_index_type = self.raw()?; + t.factor_scale_enabled = self.bool()?; + Ok(Some(t)) + } + + fn private(&mut self) -> Result { + let mut p = PrivateRenderState::new(); + p.sample_mask = self.u64()?; + p.sample_coverage = f32::from_bits(self.u32()?); + p.sample_coverage_invert = self.bool()?; + p.alpha_test_enabled = self.bool()?; + p.alpha_test_function = self.u64()?; + p.logic_operation_enabled = self.bool()?; + p.logic_operation = self.u64()?; + p.clip_distance_enable_mask = self.u8()?; + p.point_smooth_enabled = self.bool()?; + p.point_coord_lower_left = self.bool()?; + p.point_size_output_vs = self.bool()?; + p.two_side_enabled = self.bool()?; + p.vertex_depth_compare_clamp_mask = self.u32()?; + p.fragment_depth_compare_clamp_mask = self.u32()?; + p.depth_stencil_write_disabled = self.bool()?; + p.needs_custom_border_color_samplers = self.bool()?; + p.vertex_amplification_mode = self.u64()?; + p.explicit_visibility_group_id = self.u32()?; + Ok(p) + } + + fn compute(&mut self) -> Result { + let mut d = ComputePipelineDescriptor::new(self.stage()?); + d.stage_input = self.stage_input()?; + d.max_total_threads_per_threadgroup = self.opt_u32()?; + d.threadgroup_size_is_multiple_of_execution_width = self.bool()?; + d.support_indirect_command_buffers = self.bool()?; + d.max_call_stack_depth = self.u32()?; + d.required_threads_per_threadgroup = self.threads()?; + d.support_adding_binary_functions = self.bool()?; + d.buffers = self.mutability()?; + d.needs_custom_border_color_samplers = self.bool()?; + Ok(d) + } + + fn render(&mut self) -> Result { + let mut d = RenderPipelineDescriptor::new(self.stage()?); + d.fragment = self.opt_stage()?; + d.vertex_descriptor = self.vertex_descriptor()?; + d.color_attachments = self.colors()?; + d.depth_format = self.pixel_format()?; + d.stencil_format = self.pixel_format()?; + d.raster_sample_count = self.u32()?; + d.alpha_to_coverage = self.bool()?; + d.alpha_to_one = self.bool()?; + d.rasterization_enabled = self.bool()?; + d.input_primitive_topology = self.raw()?; + d.max_vertex_amplification_count = self.u32()?; + d.tessellation = self.tessellation()?; + d.support_indirect_command_buffers = self.bool()?; + d.max_vertex_call_stack_depth = self.u32()?; + d.max_fragment_call_stack_depth = self.u32()?; + d.support_adding_vertex_binary_functions = self.bool()?; + d.support_adding_fragment_binary_functions = self.bool()?; + d.vertex_buffers = self.mutability()?; + d.fragment_buffers = self.mutability()?; + d.texture_write_rounding_mode = self.rounding()?; + d.private = self.private()?; + Ok(d) + } + + fn mesh(&mut self) -> Result { + let object = self.opt_stage()?; + let mut d = MeshPipelineDescriptor::new(self.stage()?); + d.object = object; + d.fragment = self.opt_stage()?; + d.color_attachments = self.colors()?; + d.depth_format = self.pixel_format()?; + d.stencil_format = self.pixel_format()?; + d.raster_sample_count = self.u32()?; + d.rasterization_enabled = self.bool()?; + d.alpha_to_coverage = self.bool()?; + d.alpha_to_one = self.bool()?; + d.support_indirect_command_buffers = self.bool()?; + d.texture_write_rounding_mode = self.rounding()?; + Ok(d) + } + + fn tile(&mut self) -> Result { + let mut d = TileRenderPipelineDescriptor::new(self.stage()?); + for format in &mut d.color_attachment_formats { + *format = self.pixel_format()?; + } + d.raster_sample_count = self.u32()?; + d.threadgroup_size_matches_tile_size = self.bool()?; + d.max_total_threads_per_threadgroup = self.opt_u32()?; + d.max_call_stack_depth = self.u32()?; + d.required_threads_per_threadgroup = self.threads()?; + d.support_adding_binary_functions = self.bool()?; + d.buffers = self.mutability()?; + Ok(d) + } +} diff --git a/crates/metal2vulkan-runtime/src/warm/mod.rs b/crates/metal2vulkan-runtime/src/warm/mod.rs new file mode 100644 index 000000000..4097ac517 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/warm/mod.rs @@ -0,0 +1,80 @@ +//! Pipeline records and the warm pass: what a device hands +//! [`DeviceOptions::pipeline_records`](crate::DeviceOptions::pipeline_records) at each pipeline +//! state's creation (`record.rs`, `codec.rs`), for a consumer to keep and hand a later process's +//! device ([`Device::warm`]), which makes the same translations and `VkPipeline`s before its +//! program asks for them (`pass.rs`). + +pub(crate) mod codec; +mod pass; +mod record; + +pub(crate) use codec::Pipeline; +/// A warm pass's progress, which the budget's tests make one of. +#[cfg(test)] +pub(crate) use pass::Pass; +/// The id name of the warning of a device's first unread record, which `tests::warm` listens for. +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +pub(crate) use pass::UNREAD; +pub(crate) use pass::{added_pipeline_bytes, pass, translation_only, warming, within, Warmer}; +pub use record::PipelineRecord; +pub(crate) use record::{RecordHook, Recording}; + +use crate::device::Device; +use std::sync::atomic::Ordering; + +/// No Metal counterpart: a device's pipeline records and warm passes since it was made +/// ([`Device::warm_statistics`]). +/// +/// The record counts of a warm pass add up, once its calls are done, to the records handed to +/// [`Device::warm`]: each was warmed, translated only, failed, unread, not warmable or not run. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct WarmStatistics { + /// Records handed to [`DeviceOptions::pipeline_records`](crate::DeviceOptions::pipeline_records): + /// one per creation that made its state. + pub records_made: u64, + /// Creations the hook was set for whose record was not made: a stage the compile layer had + /// compiled already, a value the record format cannot hold, or bytes that did not read back as + /// the creation's descriptor (`warm/codec.rs`). + pub records_unmade: u64, + /// Libraries those records name that the device wrote to its shader cache directory, each + /// once per directory (`shader_cache/libraries.rs`). + pub libraries_kept: u64, + /// Records a warm pass made the creation of: its translations and its predicted + /// `VkPipeline`s. + pub records_warmed: u64, + /// Records a warm pass made the translations of alone: a layout that bakes an immutable + /// sampler, which a warm pass makes none of. + pub records_translated: u64, + /// Records whose creation failed on the warm pass, dropped. + pub records_failed: u64, + /// Records a warm pass could not read: of another format, damaged, or naming a library the + /// shader cache directory no longer holds. The device's first is announced + /// (`metal2vulkan-warm-record-unread`); the pass goes on with the next record. + pub records_unread: u64, + /// Mesh render pipeline records, which a warm pass does not make: that creation keeps no + /// translation on disk and makes no `VkPipeline`. + pub records_not_warmable: u64, + /// Records a warm pass did not reach: its byte budget was spent, the process began exiting, + /// or no thread could be started. + pub records_not_run: u64, + /// The driver's pipeline cache data the warm passes' makings added, in bytes: what + /// [`Device::warm`]'s `byte_budget` bounds. + pub pipeline_bytes: u64, +} + +impl Device { + /// No Metal counterpart: the device's pipeline records and warm passes since it was made. + pub fn warm_statistics(&self) -> WarmStatistics { + let shared = self.shared(); + let read = |counter: &std::sync::atomic::AtomicU64| counter.load(Ordering::Relaxed); + let mut statistics = WarmStatistics { + records_made: read(&shared.pipeline_recording.made), + records_unmade: read(&shared.pipeline_recording.unmade), + libraries_kept: shared.shader_cache.libraries_kept(), + ..WarmStatistics::default() + }; + shared.warmer.read(&mut statistics); + statistics + } +} diff --git a/crates/metal2vulkan-runtime/src/warm/pass.rs b/crates/metal2vulkan-runtime/src/warm/pass.rs new file mode 100644 index 000000000..4da0760c9 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/warm/pass.rs @@ -0,0 +1,395 @@ +//! The warm pass: [`Device::warm`] makes, on a thread of its own and below every other making, +//! what the creations its records describe make, before the program asks for them. +//! +//! - **One thread a device, in order.** A call queues its records and returns; the device's warm +//! thread (`metal2vulkan-warm`, started by the call that finds none running) takes each call's +//! records in the order given, one at a time, and ends once none are left. On macOS it runs at +//! the utility class (`exit_guard::lower_to_utility`); its pipeline makings rank below every +//! other making of the process ([`Urgency::Warm`](crate::pipeline::budget::Urgency::Warm)), +//! on its thread and in the pieces it hands the device's pool, which run as part of the pass +//! ([`within`]). It holds its device only while it warms a record, so a device the program let +//! go goes, and the pass with it. +//! - **The creation itself** (`pipeline::warm`). Each record is read back (its libraries from the +//! shader cache directory, `shader_cache/libraries.rs`, unless it was made in this process) and +//! created as the program created it, under the default options, inside one exit-guard section; +//! the state is let go at once. So the translations land in the shader cache and the predicted +//! `VkPipeline`s' data in the driver's records under the very names the program's creation of the +//! same descriptor asks for. A mesh render pipeline is not made: its creation keeps nothing past +//! the state. +//! - **The guest sees nothing.** On the pass's threads ([`warming`]) a creation takes no +//! identifier, no resource ID and no sampler number, makes no neutral and keeps no room, takes +//! nothing back from and gives nothing to the kept variants, makes no immutable sampler (a +//! layout that bakes one stops the creation after its translation: [`translation_only`]), takes +//! from the memo none of the program's live variants and lets it hand out none of its own (the +//! memo's translations it takes as any creation does), announces nothing and counts nothing +//! announced, makes no depth stand-in copy, numbers no creation log line, and hands the +//! pipeline-record hook nothing. A failed creation is counted and dropped, never said. +//! - **No answer of another build.** A record holds a descriptor, never a translation, so what +//! the pass makes of it is what the program's own creation of that descriptor makes on this +//! build, through the same lookups: translations from and into this build's directory of the +//! shader cache, which only this translator reads and writes (`shader_cache::this_build`), and +//! a render creation's answers under this runtime's `RUNTIME_VERSION` +//! (`shader_cache/creation.rs`). A record an earlier runtime or translator made is warmed by +//! this one's. +//! - **Unread records are said, never fatal.** A record the pass cannot read (of another format, +//! damaged, or naming a library the directory no longer holds) is counted; the device's first +//! is announced through its message sink, else on stderr, as the warning +//! `metal2vulkan-warm-record-unread`, and the pass goes on with the next record. +//! - **The byte budget.** The pass stops before its next record once the driver's pipeline cache +//! data its makings added (each record's growth as a making writes it, `shader_cache/driver.rs`) +//! reaches the call's `byte_budget`; the records left are counted, not made. + +use super::codec; +use super::{PipelineRecord, WarmStatistics}; +use crate::device::{lock, Device, WeakDevice}; +use crate::exit_guard; +use metal2vulkan::cache::Hash256; +use metal2vulkan::library::Library; +use std::cell::RefCell; +use std::collections::{HashMap, VecDeque}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +/// The most libraries a pass keeps read from the directory at once: records in first-use order +/// name the same few in turn, and each can be large. +const LIBRARIES: usize = 16; + +/// One warm call's progress, shared by the pass's thread and the pieces it hands the pool. +#[derive(Default)] +pub(crate) struct Pass { + /// The driver's pipeline cache data its makings added, in bytes. + bytes: AtomicU64, + /// The current record's creation stopped after its translation ([`translation_only`]). + translation_only: AtomicBool, +} + +thread_local! { + /// The pass this thread works for now, if any ([`within`]). + static PASS: RefCell>> = const { RefCell::new(None) }; +} + +/// Whether this thread works for a warm pass now: the pass's thread, or a pool's piece it handed. +pub(crate) fn warming() -> bool { + PASS.with(|pass| pass.borrow().is_some()) +} + +/// The pass this thread works for now, which a piece it hands the pool works for too. +pub(crate) fn pass() -> Option> { + PASS.with(|pass| pass.borrow().clone()) +} + +/// Run `f` on this thread as part of `pass`, as it returns or unwinds restoring what the thread +/// worked for before. +pub(crate) fn within(pass: &Arc, f: impl FnOnce() -> T) -> T { + /// Puts the earlier pass back. + struct Restore(Option>); + impl Drop for Restore { + fn drop(&mut self) { + PASS.with(|pass| *pass.borrow_mut() = self.0.clone()); + } + } + let earlier = PASS.with(|current| current.replace(Some(Arc::clone(pass)))); + let _restore = Restore(earlier); + f() +} + +/// Count `bytes` of driver data a making added toward this thread's pass, if it works for one +/// (`shader_cache/driver.rs`). +pub(crate) fn added_pipeline_bytes(bytes: u64) { + PASS.with(|pass| { + if let Some(pass) = &*pass.borrow() { + pass.bytes.fetch_add(bytes, Ordering::Relaxed); + } + }); +} + +/// The error a warm creation stops with where its layout bakes an immutable sampler, which a warm +/// pass makes none of (`pipeline/objects.rs`): its translations are kept, its objects and +/// pipelines not made. The pass counts the record as translated, not failed. +pub(crate) fn translation_only() -> crate::Error { + PASS.with(|pass| { + if let Some(pass) = &*pass.borrow() { + pass.translation_only.store(true, Ordering::Relaxed); + } + }); + crate::error::internal("a warm pass makes no immutable sampler") +} + +/// A device's warm calls: the records queued, whether its thread runs, and the counts. +#[derive(Default)] +pub(crate) struct Warmer { + queue: Mutex, + counts: Counts, +} + +#[derive(Default)] +struct Queue { + calls: VecDeque, + running: bool, +} + +/// One warm call: its records in order, and its budget. +struct Call { + records: Vec, + byte_budget: u64, +} + +/// What the device's passes did, by record. +#[derive(Default)] +struct Counts { + warmed: AtomicU64, + translated: AtomicU64, + failed: AtomicU64, + unread: AtomicU64, + not_warmable: AtomicU64, + not_run: AtomicU64, + pipeline_bytes: AtomicU64, + /// The device's first unread record was announced ([`UNREAD`]). + said_unread: AtomicBool, +} + +/// The id name of the warning of a device's first record a warm pass could not read. +pub(crate) const UNREAD: &str = "metal2vulkan-warm-record-unread"; + +/// What became of one record. +enum Outcome { + Warmed, + Translated, + Failed, + /// Not read, for the reason given. + Unread(&'static str), + NotWarmable, +} + +impl Warmer { + /// Its counts, into `statistics`. + pub(crate) fn read(&self, statistics: &mut WarmStatistics) { + let counts = &self.counts; + let read = |counter: &AtomicU64| counter.load(Ordering::Relaxed); + statistics.records_warmed = read(&counts.warmed); + statistics.records_translated = read(&counts.translated); + statistics.records_failed = read(&counts.failed); + statistics.records_unread = read(&counts.unread); + statistics.records_not_warmable = read(&counts.not_warmable); + statistics.records_not_run = read(&counts.not_run); + statistics.pipeline_bytes = read(&counts.pipeline_bytes); + } + + /// Count `outcome`, a record's on `device`; the device's first unread record is announced + /// (the module docs). + fn count(&self, device: &Device, outcome: Outcome) { + let counts = &self.counts; + let counter = match outcome { + Outcome::Warmed => &counts.warmed, + Outcome::Translated => &counts.translated, + Outcome::Failed => &counts.failed, + Outcome::Unread(why) => { + if !counts.said_unread.swap(true, Ordering::Relaxed) { + say_unread(device, why); + } + &counts.unread + } + Outcome::NotWarmable => &counts.not_warmable, + }; + counter.fetch_add(1, Ordering::Relaxed); + } + + fn not_run(&self, records: usize) { + self.counts + .not_run + .fetch_add(records as u64, Ordering::Relaxed); + } +} + +impl Device { + /// No Metal counterpart: it stands in for Metal's own pipeline caches across processes, which + /// keep the pipelines a program made in the OS's caches and make them again from there at + /// their creation. Make, in the background, what the creations `records` describe make + /// (handed earlier by + /// [`DeviceOptions::pipeline_records`](crate::DeviceOptions::pipeline_records), in a process + /// over the same shader cache directory), in the order given, until the driver's pipeline + /// cache data the pass added reaches `byte_budget` bytes: their translations into the shader + /// cache and their predicted `VkPipeline`s' data into the driver's records, so the program's + /// creations of the same descriptors find them. Returns at once. + /// + /// - It makes no object the program sees and changes no answer: no state, identifier, + /// resource ID, sampler number, notice or memory the program's calls decide; a state the + /// program creates meanwhile is made as without it. + /// - What it makes is what the program's own creation of each descriptor makes on this build: + /// a record holds a descriptor, never a translation, so it reads no translation of another + /// translator and no creation record of another runtime version (the shader cache keeps both + /// apart). A record an earlier version made is warmed by this one. + /// - It runs on one thread of the device's, at the utility class on macOS, its pipeline + /// makings after every other making of the process; calls queue behind each other. + /// - Nothing fails and nothing ends the run. A record it cannot read (of another format, + /// damaged, or naming a library the directory no longer holds) is counted + /// ([`Device::warm_statistics`]) and dropped, the device's first announced as the warning + /// `metal2vulkan-warm-record-unread`; a creation that fails is counted and dropped. A mesh + /// render pipeline's record is counted and not made (its creation keeps nothing past the + /// state); a layout that bakes an immutable sampler is translated only. + pub fn warm(&self, records: Vec, byte_budget: u64) { + let warmer = &self.shared().warmer; + let mut queue = lock(&warmer.queue); + queue.calls.push_back(Call { + records, + byte_budget, + }); + if queue.running { + return; + } + queue.running = true; + drop(queue); + let device = self.downgrade(); + let started = exit_guard::spawn( + std::thread::Builder::new().name("metal2vulkan-warm".into()), + move || run(&device), + ); + if started.is_err() { + // No thread: the calls queued are not run, and a later call tries again. + let mut queue = lock(&warmer.queue); + let left: usize = queue.calls.drain(..).map(|call| call.records.len()).sum(); + queue.running = false; + drop(queue); + warmer.not_run(left); + } + } +} + +/// The warm thread of `device`: its calls in order, until none is left or the device went. +fn run(device: &WeakDevice) { + exit_guard::lower_to_utility(); + loop { + let Some(held) = device.upgrade() else { + return; + }; + let call = { + let mut queue = lock(&held.shared().warmer.queue); + match queue.calls.pop_front() { + Some(call) => call, + None => { + queue.running = false; + return; + } + } + }; + drop(held); + warm_call(device, call); + } +} + +/// Warm `call`'s records on `device`, in order, within its budget (the module docs). +fn warm_call(device: &WeakDevice, call: Call) { + let pass = Arc::new(Pass::default()); + let mut libraries = Libraries::default(); + let Call { + records, + byte_budget, + } = call; + let total = records.len(); + for (at, record) in records.iter().enumerate() { + let Some(held) = device.upgrade() else { + return; + }; + let warmer = &held.shared().warmer; + if pass.bytes.load(Ordering::Relaxed) >= byte_budget { + warmer.not_run(total - at); + return; + } + // Every Vulkan call of the creation runs inside this section, which an exit waits for + // (`exit_guard`); once the process is exiting, nothing more is made. + let Some(_busy) = exit_guard::enter() else { + warmer.not_run(total - at); + return; + }; + let before = pass.bytes.load(Ordering::Relaxed); + pass.translation_only.store(false, Ordering::Relaxed); + let outcome = within(&pass, || warm_record(&held, record, &mut libraries, &pass)); + let added = pass.bytes.load(Ordering::Relaxed) - before; + warmer + .counts + .pipeline_bytes + .fetch_add(added, Ordering::Relaxed); + warmer.count(&held, outcome); + } +} + +/// Announce that a record handed to `device`'s warm pass could not be read, for `why`, through +/// the device's message sink, else on stderr: a warning, which ends nothing. +fn say_unread(device: &Device, why: &str) { + let text = format!( + "metal2vulkan: a pipeline record handed to Device::warm could not be read ({why}): it is not warmed, the pass goes on with the next record, and the program's creation of its descriptor makes what it needs when asked. This device's later unread records are counted alone (`WarmStatistics::records_unread`)." + ); + let message = crate::DebugMessage { + severity: crate::MessageSeverity::Warning, + kind: crate::MessageKind { + general: true, + ..crate::MessageKind::default() + }, + id_name: UNREAD.to_owned(), + id: 0, + text, + degradation: None, + }; + match device.shared().instance.sink() { + Some(sink) => sink.deliver(&message), + None => eprintln!("{}", message.text), + } +} + +/// Make on `device` what `record`'s creation makes (the module docs). +fn warm_record( + device: &Device, + record: &PipelineRecord, + libraries: &mut Libraries, + pass: &Pass, +) -> Outcome { + let bytes = record.bytes(); + let read = + match record.libraries() { + made if !made.is_empty() => codec::decode(bytes, made), + _ => match libraries.of(device, bytes) { + Some(named) => codec::decode(bytes, &named), + None => return Outcome::Unread( + "it names a library the shader cache directory does not hold, or is no record", + ), + }, + }; + let Ok(pipeline) = read else { + return Outcome::Unread("its libraries do not hold what it names, or it is damaged"); + }; + match crate::pipeline::warm(device, &pipeline) { + Ok(true) => Outcome::Warmed, + Ok(false) => Outcome::NotWarmable, + Err(_) if pass.translation_only.load(Ordering::Relaxed) => Outcome::Translated, + Err(_) => Outcome::Failed, + } +} + +/// The libraries a pass read from the directory, by content hash: at most [`LIBRARIES`], all let +/// go once it holds that many. +#[derive(Default)] +struct Libraries(HashMap); + +impl Libraries { + /// The libraries `record`'s bytes name, in their places' order, each from this pass's or the + /// device's shader cache directory; `None` where one is in neither, or the bytes are no + /// record. + fn of(&mut self, device: &Device, record: &[u8]) -> Option> { + let table = codec::libraries(record).ok()?; + let cache = &device.shared().shader_cache; + let mut named = Vec::with_capacity(table.len()); + for (hash, length) in table { + if let Some(library) = self.0.get(&hash) { + named.push(library.clone()); + continue; + } + let library = cache.library(&hash, length)?; + if self.0.len() >= LIBRARIES { + self.0.clear(); + } + self.0.insert(hash, library.clone()); + named.push(library); + } + Some(named) + } +} diff --git a/crates/metal2vulkan-runtime/src/warm/record.rs b/crates/metal2vulkan-runtime/src/warm/record.rs new file mode 100644 index 000000000..f1027fa36 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/warm/record.rs @@ -0,0 +1,167 @@ +//! [`PipelineRecord`] and its making: what a device hands +//! [`DeviceOptions::pipeline_records`](crate::DeviceOptions::pipeline_records) at each pipeline +//! state's creation. +//! +//! - **Once per creation.** Each `new_compute_pipeline_state*`, `new_render_pipeline_state*`, +//! `new_mesh_render_pipeline_state*`, `new_tile_render_pipeline_state*` and +//! `new_*_pipeline_state_with_additional_binary_functions` call that makes a state hands the +//! hook one record, on the creating thread, after the state is made and before the call +//! returns, as the program's own code (a panic in the hook is caught). So does a twin the +//! runtime makes of a program's render state where a draw first needs one (its one-sample or +//! factor-scaling form, `GraphicsState::single_sample`), on the thread that makes it: its +//! translations are the program's too. A creation that fails, a binary archive's add, and a +//! state a warm pass makes ([`Device::warm`]) hand it nothing. Without a hook no record is made. +//! - **What it holds.** The creation's descriptor as the program gave it, every field, with each +//! stage's function by its library and table index, its constants as supplied, its linked +//! functions and its dynamic libraries; and how many of each stage's last binary functions were +//! added without the stage's support flag. Its libraries are named by their content hash, and +//! their bytes are kept in the device's shader cache directory (`shader_cache/libraries.rs`), +//! once per library, so a record is small and a VM's records over one library hold it once. +//! Nothing a later process would compute again is in it: no key, translation, variant or +//! pipeline, so a record outlives every translator change (`codec.rs`). +//! - **Exact or none.** A record is read back from its own bytes as it is made, and handed over +//! only where that reading equals the creation's descriptor; one that cannot be written (a stage +//! the compile layer compiled already) or read back is counted +//! ([`WarmStatistics::records_unmade`](super::WarmStatistics::records_unmade)) and not handed +//! over. + +use super::codec::{self, Pipeline, Unwritable}; +use crate::device::Device; +use metal2vulkan::library::Library; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +/// No Metal counterpart: one pipeline state creation, as +/// [`DeviceOptions::pipeline_records`](crate::DeviceOptions::pipeline_records) hands it over, to +/// make the same translations and `VkPipeline`s again in a later process +/// ([`Device::warm`]). Opaque; cheap to clone; `Send + Sync`. +/// +/// It holds the creation's descriptor and its stages' functions, constants, linked functions and +/// dynamic libraries; its libraries are named by their content hash, their bytes kept in the +/// device's shader cache directory, so a record warms only on a device over the same directory. +/// [`to_bytes`](Self::to_bytes) and [`from_bytes`](Self::from_bytes) carry it between processes; +/// equal records have equal bytes, so a consumer may keep each once. +#[derive(Clone)] +pub struct PipelineRecord { + bytes: Arc<[u8]>, + /// The libraries its table names, in its order, where it was made in this process; empty for + /// one read from bytes, whose libraries the warm pass reads from the directory. + libraries: Arc<[Library]>, +} + +impl PipelineRecord { + /// The record of `pipeline`, read back from its own bytes and found equal (the module docs). + pub(crate) fn of(pipeline: &Pipeline) -> Result { + let (bytes, libraries) = codec::encode(pipeline)?; + match codec::decode(&bytes, &libraries) { + Ok(read) if read == *pipeline => Ok(PipelineRecord { + bytes: bytes.into(), + libraries: libraries.into(), + }), + _ => Err(Unwritable), + } + } + + /// No Metal counterpart: the record as bytes, which [`from_bytes`](Self::from_bytes) reads in + /// a later process. They name the record format; its libraries' bytes stay in the shader + /// cache directory. + pub fn to_bytes(&self) -> Vec { + self.bytes.to_vec() + } + + /// No Metal counterpart: the record `bytes` hold, `None` where they hold none: damaged, cut, + /// not a record, or a record of another format, which this build does not read (the format + /// moves only where the record's bytes change meaning, never with a translator or runtime + /// change alone, so a consumer may keep records across updates and drop those this returns + /// `None` for). + pub fn from_bytes(bytes: &[u8]) -> Option { + codec::is_record(bytes).then(|| PipelineRecord { + bytes: bytes.into(), + libraries: Arc::from([]), + }) + } + + /// The libraries it was made with in this process, in its table's order; empty for a record + /// read from bytes. + pub(crate) fn libraries(&self) -> &[Library] { + &self.libraries + } + + /// Its bytes. + pub(crate) fn bytes(&self) -> &[u8] { + &self.bytes + } +} + +impl PartialEq for PipelineRecord { + fn eq(&self, other: &PipelineRecord) -> bool { + self.bytes == other.bytes + } +} + +impl Eq for PipelineRecord {} + +impl std::hash::Hash for PipelineRecord { + fn hash(&self, state: &mut H) { + self.bytes.hash(state); + } +} + +impl std::fmt::Debug for PipelineRecord { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PipelineRecord") + .field("bytes", &self.bytes.len()) + .finish() + } +} + +/// The hook a device hands its records to. +pub(crate) type RecordHook = Arc; + +/// A device's records: its hook, and the counts of what it made. +pub(crate) struct Recording { + hook: Option, + /// Records handed to the hook. + pub(crate) made: AtomicU64, + /// Creations the hook was set for whose record could not be made. + pub(crate) unmade: AtomicU64, +} + +impl Recording { + /// A device's recording to `hook`, none where `None`. + pub(crate) fn new(hook: Option) -> Recording { + Recording { + hook, + made: AtomicU64::new(0), + unmade: AtomicU64::new(0), + } + } +} + +impl Device { + /// Hand the device's hook the record of `pipeline`, a creation that made its state (the + /// module docs): nothing where the device has no hook or the warm pass made the state. + /// `pipeline` is asked for only where a record is made. + pub(crate) fn record_pipeline(&self, pipeline: impl FnOnce() -> Pipeline) { + if super::warming() { + return; + } + let shared = self.shared(); + let recording = &shared.pipeline_recording; + let Some(hook) = &recording.hook else { + return; + }; + let record = match PipelineRecord::of(&pipeline()) { + Ok(record) => record, + Err(Unwritable) => { + recording.unmade.fetch_add(1, Ordering::Relaxed); + return; + } + }; + for library in record.libraries() { + shared.shader_cache.keep_library(library); + } + recording.made.fetch_add(1, Ordering::Relaxed); + crate::exit_guard::program(|| hook(record)); + } +} diff --git a/crates/metal2vulkan-runtime/tests/consumer_auto_traits.rs b/crates/metal2vulkan-runtime/tests/consumer_auto_traits.rs index f25938220..42d19d354 100644 --- a/crates/metal2vulkan-runtime/tests/consumer_auto_traits.rs +++ b/crates/metal2vulkan-runtime/tests/consumer_auto_traits.rs @@ -18,10 +18,10 @@ use metal2vulkan_runtime::{ ArgumentEncoder, BinaryArchive, BlitCommandEncoder, Buffer, CommandBuffer, CommandBufferError, CommandQueue, ComputeCommandEncoder, ComputePipelineState, DegradeNotice, DepthStencilState, Device, DynamicLibrary, Error, Event, Fence, Function, Heap, IndirectCommandBuffer, - IndirectComputeCommand, IndirectRenderCommand, Library, MessageSink, RasterizationRateMap, - RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState, ResourceStateCommandEncoder, - SamplerState, SharedEvent, SharedEventHandle, SharedEventListener, SharedTextureHandle, - Texture, VisibleFunctionTable, WorkCounts, + IndirectComputeCommand, IndirectRenderCommand, Library, MessageSink, PipelineRecord, + RasterizationRateMap, RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState, + ResourceStateCommandEncoder, SamplerState, SharedEvent, SharedEventHandle, SharedEventListener, + SharedTextureHandle, Texture, VisibleFunctionTable, WorkCounts, }; /// `T` held as a program's crate holds it: the bound of reims-vgpu's `platform::Obj`, one @@ -81,6 +81,7 @@ held! { argument_encoder: ArgumentEncoder; visible_function_table: VisibleFunctionTable; rasterization_rate_map: RasterizationRateMap; + pipeline_record: PipelineRecord; message_sink: MessageSink; error: Error; command_buffer_error: CommandBufferError; diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 64063982d..19af655ea 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -560c846275f2d1069e1e6d8cde840d0d275bea2fbc5768f950a8f4f49db6e74f +20f34e29acd5322082f316df5b70d33a5fe49e6383a1ae21bd9bde065abe1bda diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index b5eb3f972..9e80bf9f3 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 479; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1706; +pub const RUNTIME_VERSION: u32 = 1707; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 9f3ae7f12..7bc59cb7d 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1993,6 +1993,7 @@ field metal2vulkan-runtime::DeviceOptions.loader pub loader: Option field metal2vulkan-runtime::DeviceOptions.lowering_refuses pub lowering_refuses: BTreeSet field metal2vulkan-runtime::DeviceOptions.messages pub messages: Option field metal2vulkan-runtime::DeviceOptions.optional_device_extensions pub optional_device_extensions: Vec +field metal2vulkan-runtime::DeviceOptions.pipeline_records pub pipeline_records: Option> field metal2vulkan-runtime::DeviceOptions.policy pub policy: DevicePolicy field metal2vulkan-runtime::DeviceOptions.record_executions pub record_executions: bool field metal2vulkan-runtime::DeviceOptions.shader_cache pub shader_cache: ShaderCacheOptions @@ -2214,6 +2215,7 @@ field metal2vulkan-runtime::RawDevice.instance pub instance: vk::Instance field metal2vulkan-runtime::RawDevice.instance_api_version pub instance_api_version: metal2vulkan::vk::ApiVersion field metal2vulkan-runtime::RawDevice.lowering_refuses pub lowering_refuses: BTreeSet field metal2vulkan-runtime::RawDevice.physical_device pub physical_device: vk::PhysicalDevice +field metal2vulkan-runtime::RawDevice.pipeline_records pub pipeline_records: Option> field metal2vulkan-runtime::RawDevice.queue_family pub queue_family: u32 field metal2vulkan-runtime::RawDevice.queue_index pub queue_index: u32 field metal2vulkan-runtime::RawDevice.shader_cache pub shader_cache: ShaderCacheOptions @@ -2409,6 +2411,16 @@ field metal2vulkan-runtime::VkBufferMemory.offset pub offset: u64 field metal2vulkan-runtime::VkBufferMemory.type_index pub type_index: u32 field metal2vulkan-runtime::VkImageLayouts.home pub home: ImageLayout field metal2vulkan-runtime::VkImageLayouts.initial pub initial: ImageLayout +field metal2vulkan-runtime::WarmStatistics.libraries_kept pub libraries_kept: u64 +field metal2vulkan-runtime::WarmStatistics.pipeline_bytes pub pipeline_bytes: u64 +field metal2vulkan-runtime::WarmStatistics.records_failed pub records_failed: u64 +field metal2vulkan-runtime::WarmStatistics.records_made pub records_made: u64 +field metal2vulkan-runtime::WarmStatistics.records_not_run pub records_not_run: u64 +field metal2vulkan-runtime::WarmStatistics.records_not_warmable pub records_not_warmable: u64 +field metal2vulkan-runtime::WarmStatistics.records_translated pub records_translated: u64 +field metal2vulkan-runtime::WarmStatistics.records_unmade pub records_unmade: u64 +field metal2vulkan-runtime::WarmStatistics.records_unread pub records_unread: u64 +field metal2vulkan-runtime::WarmStatistics.records_warmed pub records_warmed: u64 field metal2vulkan-runtime::WorkCounts.addressable_buffers_made pub addressable_buffers_made: u64 field metal2vulkan-runtime::WorkCounts.ahead_framebuffers_made pub ahead_framebuffers_made: u64 field metal2vulkan-runtime::WorkCounts.ahead_nanos pub ahead_nanos: u64 @@ -7699,6 +7711,8 @@ method metal2vulkan-runtime::Device::system_default_with pub fn system_default_w method metal2vulkan-runtime::Device::texture_level_info pub fn texture_level_info(&self, query: &TextureLevelQuery) -> TextureLevelInfo method metal2vulkan-runtime::Device::use_host_ram pub fn use_host_ram(&self, ram: &Arc) -> Result method metal2vulkan-runtime::Device::vk_buffer_usage pub fn vk_buffer_usage(&self) -> BufferUsageFlags +method metal2vulkan-runtime::Device::warm pub fn warm(&self, records: Vec, byte_budget: u64) +method metal2vulkan-runtime::Device::warm_statistics pub fn warm_statistics(&self) -> WarmStatistics method metal2vulkan-runtime::Device::with_loader_word pub fn with_loader_word(&self, call: impl FnOnce() -> R) -> R method metal2vulkan-runtime::Device::with_registry_id pub fn with_registry_id(registry_id: u64, options: &DeviceOptions) -> Result method metal2vulkan-runtime::Device::work_counts pub fn work_counts(&self) -> WorkCounts @@ -7917,6 +7931,8 @@ method metal2vulkan-runtime::PipelineOption::contains pub const fn contains(self method metal2vulkan-runtime::PipelineOption::from_raw pub const fn from_raw(raw: u64) -> PipelineOption method metal2vulkan-runtime::PipelineOption::raw pub const fn raw(self) -> u64 method metal2vulkan-runtime::PipelineOptions::new pub fn new(options: PipelineOption) -> PipelineOptions +method metal2vulkan-runtime::PipelineRecord::from_bytes pub fn from_bytes(bytes: &[u8]) -> Option +method metal2vulkan-runtime::PipelineRecord::to_bytes pub fn to_bytes(&self) -> Vec method metal2vulkan-runtime::PixelFormatInfo::describes_a_format pub fn describes_a_format(&self) -> bool method metal2vulkan-runtime::PrivateAnswer::metal pub fn metal(self) -> T method metal2vulkan-runtime::PrivateAnswer::value pub fn value(self) -> Option @@ -9241,7 +9257,7 @@ struct metal2vulkan-runtime::DegradeNotice #[derive(Clone, Debug, PartialEq, Eq) struct metal2vulkan-runtime::DepthStencilState #[derive(Clone)] pub struct DepthStencilState(Arc) struct metal2vulkan-runtime::Device #[derive(Clone)] pub struct Device(Arc) struct metal2vulkan-runtime::DeviceHandles #[derive(Clone, Copy)] #[non_exhaustive] pub struct DeviceHandles<'a> -struct metal2vulkan-runtime::DeviceOptions #[derive(Clone, Debug, Default)] #[non_exhaustive] pub struct DeviceOptions +struct metal2vulkan-runtime::DeviceOptions #[derive(Clone, Default)] #[non_exhaustive] pub struct DeviceOptions struct metal2vulkan-runtime::DeviceProperties #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DeviceProperties struct metal2vulkan-runtime::DirtyStamp #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct DirtyStamp(pub u64) struct metal2vulkan-runtime::DmaBufChunk #[derive(Debug)] pub struct DmaBufChunk @@ -9295,10 +9311,11 @@ struct metal2vulkan-runtime::Origin #[derive(Clone, Copy, Debug, Default, Partia struct metal2vulkan-runtime::PhysicalDeviceIdentity #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct PhysicalDeviceIdentity struct metal2vulkan-runtime::PipelineOption #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct PipelineOption(u64) struct metal2vulkan-runtime::PipelineOptions #[derive(Clone, Debug, Default)] #[non_exhaustive] pub struct PipelineOptions +struct metal2vulkan-runtime::PipelineRecord #[derive(Clone)] pub struct PipelineRecord struct metal2vulkan-runtime::PixelFormatInfo #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct PixelFormatInfo struct metal2vulkan-runtime::PrivateProperties #[derive(Clone, Debug, PartialEq, Eq)] pub struct PrivateProperties struct metal2vulkan-runtime::RasterizationRateMap #[derive(Clone)] pub struct RasterizationRateMap(Arc) -struct metal2vulkan-runtime::RawDevice #[derive(Clone, Debug)] #[non_exhaustive] pub struct RawDevice +struct metal2vulkan-runtime::RawDevice #[derive(Clone)] #[non_exhaustive] pub struct RawDevice struct metal2vulkan-runtime::Region #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct Region struct metal2vulkan-runtime::RenderCommandEncoder pub struct RenderCommandEncoder struct metal2vulkan-runtime::RenderPassColorAttachmentDescriptor #[derive(Clone, Debug)] #[non_exhaustive] pub struct RenderPassColorAttachmentDescriptor @@ -9346,6 +9363,7 @@ struct metal2vulkan-runtime::VisibleFunctionTableDescriptor #[derive(Clone, Copy struct metal2vulkan-runtime::VkBufferMemory #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct VkBufferMemory struct metal2vulkan-runtime::VkImageLayouts #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct VkImageLayouts struct metal2vulkan-runtime::VkResultCode #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct VkResultCode(pub i32) +struct metal2vulkan-runtime::WarmStatistics #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct WarmStatistics struct metal2vulkan-runtime::WorkCounts #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct WorkCounts struct metal2vulkan::Budget #[derive(Clone, Debug, Default)] #[non_exhaustive] pub struct Budget struct metal2vulkan::CancelToken #[derive(Clone, Debug, Default)] pub struct CancelToken(Arc) @@ -9748,6 +9766,7 @@ trait-impl metal2vulkan-runtime::DepthStencilState impl std::fmt::Debug impl std trait-impl metal2vulkan-runtime::Device impl ImageMaker impl ImageMaker for Device trait-impl metal2vulkan-runtime::Device impl std::fmt::Debug impl std::fmt::Debug for Device trait-impl metal2vulkan-runtime::DeviceHandles impl std::fmt::Debug impl std::fmt::Debug for DeviceHandles<'_> +trait-impl metal2vulkan-runtime::DeviceOptions impl std::fmt::Debug impl std::fmt::Debug for DeviceOptions trait-impl metal2vulkan-runtime::DmaBufRequest impl fe impl Send unsafe impl Send for DmaBufRequest trait-impl metal2vulkan-runtime::DmaBufRequest impl fe impl Sync unsafe impl Sync for DmaBufRequest trait-impl metal2vulkan-runtime::DrawPrimitiveType impl From impl From for DrawPrimitiveType @@ -9791,9 +9810,14 @@ trait-impl metal2vulkan-runtime::Library impl Owned impl Owned