From d166086d920987cfa62e7d6479b50ebf0a6dc069 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 14 Nov 2026 01:18:32 -0800 Subject: [PATCH] RUNTIME 2270: an encoder's open looks at the encoders ended since the open before, not every earlier one Every compute and render encoder's open built what it starts with (the shadowed textures its command buffer's ended encoders made resident) from scratch: the command buffer's joined residency, then each ended encoder not joined yet, one shadows_onto each. The joined residency advances only where the command buffer's own work reads it, so a command buffer of n compute encoders walked n(n-1)/2 ended encoders: at Geekbench Fluid's ~2300 one-dispatch encoders a command buffer, the open grew to ~2.9 us a dispatch on lavapipe (866 ns at 6 encoders), and reims's decodeperf profile (M3, MoltenVK) put inherited_residency and shadows_onto at 762 of open_compute's 874 samples. The command buffer now keeps what its next compute and its next render encoder start with, with the number of ended encoders it took in (State::inherits): an open takes in the encoders ended since, each once, in the order they ended, and hands out a copy (a count: the residency's resources are shared until one copy changes). It is let go of where the joined residency or an ended encoder's residency may change: joined_residency (every read that joins, the heaps' textures made since, the first submission, a re-encode) and a re-encode's splice of an encoder's residency. The result is the one the walk made: the joined residency's shadows first, then each ended encoder's onto them in order, usages and stages joined as before. Counted: WorkCounts::ended_residencies_looked_at (an ended encoder's residency looked at for an open's inherited shadows). Tests (tests::joined_residency): 64 encoders with a read of the residency after the 32nd look at 62 residencies (the walk: 992); a shadowed texture made resident for reading, then writing, reaches the next encoder with its usage widened. RUNTIME_VERSION 2270: an encoder open inherits residency incrementally (the same result). Also (compenc): dispatch_chain gains --host (each encoder call and the commit timed on the calling thread, commit_and_submit, per-thread CPU on Linux), --binds 4|tex (four buffers, or the Geekbench compute shape: 2 textures, a sampler, an output buffer and setBytes) and --pages (buffers over host pages). Verified (compenc, msi lavapipe): touched tests 165/165 (m3-max-28544) incl. tests::joined_residency: 64 encoders with a residency read after the 32nd look at 62 ended residencies; a shadowed texture made resident READ then WRITE reaches the next encoder as written. Negative control (drop the slots every open, m3-max-28547): 992 vs 62, fails. Release dispatch_chain --host --only encoders --dispatches 2300 --binds 4, ns a dispatch: open 2862 -> 573, encode 7332 -> 5004, thread CPU 7532 -> 5205 (jobs 28534/28545); ended_residencies_looked_at 1.00 a dispatch. SR-like (6 encoders a CB) unchanged (866 -> 913). Clippy x3 and rustdoc run after landing. Squashed from steelbrain/compenc d0d524b6de..84b304c5e3. --- .../examples/dispatch_chain.rs | 517 +++++++++++++++++- .../src/command_buffer/mod.rs | 38 +- .../src/command_buffer/reencode.rs | 2 + .../src/tests/joined_residency.rs | 74 ++- .../metal2vulkan-runtime/src/work_counts.rs | 17 + crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 1 + 7 files changed, 625 insertions(+), 26 deletions(-) diff --git a/crates/metal2vulkan-runtime/examples/dispatch_chain.rs b/crates/metal2vulkan-runtime/examples/dispatch_chain.rs index 8db808e4c..665be5db1 100644 --- a/crates/metal2vulkan-runtime/examples/dispatch_chain.rs +++ b/crates/metal2vulkan-runtime/examples/dispatch_chain.rs @@ -4,7 +4,8 @@ //! //! ```sh //! cargo run --release -p metal2vulkan-runtime --example dispatch_chain -- \ -//! [--dispatches N] [--groups G] [--threads T] [--runs R] [--only SHAPE,...] +//! [--dispatches N] [--groups G] [--threads T] [--runs R] [--only SHAPE,...] \ +//! [--binds 1|4|tex] [--host C] [--pages] //! ``` //! //! Each run is one command buffer of `N` dispatches (200 by default) of `G` threadgroups of `T` @@ -43,19 +44,60 @@ //! CHAIN-FIRST = ... //! ``` //! +//! With `--binds 4` the runtime's shapes run `bump_wide`, which also reads two `Private` buffers of +//! zeros at indices 1 and 2 and a word of 1 set as bytes at index 3 (`a[gid] += b[gid] + c[gid] + +//! k`), each dispatch binding its two zero buffers the other way round from the dispatch before it. +//! With `--binds tex` they run `bump_tex`, which samples two 16 by 16 `RGBA8Unorm` textures at +//! indices 0 and 1 through a sampler at 0, and reads a word of 1 set as bytes at buffer index 1 +//! (`a[gid] += k`, plus 1000 where a texel's red is below -1e30, which none is): each dispatch +//! binds the pipeline state, the two textures (the other way round from the dispatch before it), +//! the sampler, the words and the bytes, the shape of Geekbench's compute workloads' encoders. +//! With `--pages` the words and the zero buffers are `Shared` no-copy buffers over host pages +//! (`new_buffer_with_bytes_no_copy`), as a guest's buffers over its own RAM are on a device with +//! unified memory, which makes the device log the encoders' calls and hold the buffers its commands +//! name (`replay.rs`, `rebind.rs`). +//! +//! **The host's time** (`--host C`): the runtime's shapes alone, each run `C` command buffers of the +//! `N` dispatches, every dispatch setting its pipeline state and buffers again as a program that +//! encodes a dispatch's whole state does, each command buffer committed with `commit_and_submit` +//! (as a consumer that submits on its own thread commits) and waited for before the next is made, +//! outside the times. Each call is timed on the calling thread; per dispatch, the means over the +//! `R` runs after one not counted: +//! +//! ```text +//! HOST dispatches command_buffers binds ns_per_dispatch make open +//! pipeline bind dispatch end encode commit thread_cpu +//! least_encode_commit +//! HOST-COMMIT lowering recording pipeline_wait lock_wait pass +//! submit +//! HOST-THREADS = ... +//! ``` +//! +//! `make` is `command_buffer`, `open` the encoders' opening, `pipeline` and `bind` the state's +//! calls, `end` `end_encoding`; `encode` is their sum and `commit` the `commit_and_submit` call; +//! `thread_cpu` the calling thread's CPU time over both (`CLOCK_THREAD_CPUTIME_ID`), and +//! `least_encode_commit` the least run's. `HOST-COMMIT` splits the commit call by the device's +//! commit phases (`WorkCounts::commit_lowering_nanos` and kin). `HOST-THREADS` is each group of the +//! process's threads' CPU time per dispatch over the counted runs, waits included, by the thread's +//! name (Linux only, from `/proc/self/task/*/schedstat`): `committer` is the calling thread (the +//! process's first), the driver's threads (a CPU device's execution among them) are `driver`. +//! //! The kernels are text here: LLVM IR assembled by `llvm-as`, SPIR-V by `spirv-as`, both from //! `PATH`. use ash::vk; -use metal2vulkan::metal::DispatchType; +use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::metal::{DispatchType, PixelFormat, TextureUsage}; use metal2vulkan_runtime::{ - Buffer, CommandBufferStatus, ComputePipelineState, Device, DeviceOptions, PipelineOptions, - ResourceOptions, Size, WorkCounts, + Buffer, CommandBufferStatus, CommandQueue, ComputeCommandEncoder, ComputePipelineState, Device, + DeviceOptions, HostMemory, PipelineOptions, ResourceOptions, SamplerState, Size, Texture, + TextureDescriptor, WorkCounts, }; use std::collections::BTreeMap; use std::io::Write; use std::process::{Command, Stdio}; -use std::time::Duration; +use std::ptr::NonNull; +use std::time::{Duration, Instant}; /// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. type Result = std::result::Result>; @@ -84,6 +126,77 @@ entry:\n\ !8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ !20 = !{ptr @bump, !3, !4}\n"; +/// `bump_wide`: `a[gid] += b[gid] + c[gid] + *k`, `a` a buffer of words at index 0, `b` and `c` +/// read-only ones at 1 and 2, `k` a `constant` word at 3. +const KERNEL_WIDE: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ +target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ +define void @bump_wide(ptr addrspace(1) noundef %a, ptr addrspace(1) noundef readonly %b, ptr addrspace(1) noundef readonly %c, ptr addrspace(2) noundef %k, i32 noundef %gid) {\n\ +entry:\n\ + %gw = zext i32 %gid to i64\n\ + %p = getelementptr inbounds i32, ptr addrspace(1) %a, i64 %gw\n\ + %pb = getelementptr inbounds i32, ptr addrspace(1) %b, i64 %gw\n\ + %pc = getelementptr inbounds i32, ptr addrspace(1) %c, i64 %gw\n\ + %x = load i32, ptr addrspace(1) %p, align 4\n\ + %y = load i32, ptr addrspace(1) %pb, align 4\n\ + %z = load i32, ptr addrspace(1) %pc, align 4\n\ + %w = load i32, ptr addrspace(2) %k, align 4\n\ + %s1 = add i32 %x, %y\n\ + %s2 = add i32 %s1, %z\n\ + %v = add i32 %s2, %w\n\ + store i32 %v, ptr addrspace(1) %p, align 4\n\ + ret void\n\ +}\n\n\ +!llvm.module.flags = !{!0, !1}\n!air.kernel = !{!20}\n!air.version = !{!8}\n!air.language_version = !{!9}\n\ +!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ +!1 = !{i32 7, !\"air.max_threadgroup_buffers\", i32 31}\n\ +!3 = !{}\n!4 = !{!5, !10, !11, !12, !7}\n\ +!5 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"a\"}\n\ +!10 = !{i32 1, !\"air.buffer\", !\"air.location_index\", i32 1, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"b\"}\n\ +!11 = !{i32 2, !\"air.buffer\", !\"air.location_index\", i32 2, i32 1, !\"air.read\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"c\"}\n\ +!12 = !{i32 3, !\"air.buffer\", !\"air.buffer_size\", i32 4, !\"air.location_index\", i32 3, i32 1, !\"air.read\", !\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"k\"}\n\ +!7 = !{i32 4, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}\n\ +!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ +!20 = !{ptr @bump_wide, !3, !4}\n"; + +/// `bump_tex`: `a[gid] += k`, plus 1000 where a texel `t0` or `t1` samples through `s` at the +/// middle has its red below -1e30; `t0`, `t1` textures at 0 and 1, `s` a sampler at 0, `a` a +/// buffer of words at index 0, `k` a `constant` word at 1. +const KERNEL_TEX: &str = "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\n\ +target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\ +define void @bump_tex(ptr addrspace(1) %t0, ptr addrspace(1) %t1, ptr addrspace(2) %s, ptr addrspace(1) noundef %a, ptr addrspace(2) noundef %k, i32 noundef %gid) {\n\ +entry:\n\ + %r0 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %t0, ptr addrspace(2) %s, <2 x float> , i1 true, <2 x i32> zeroinitializer, i1 true, float 0.0, float 0.0, i32 0)\n\ + %r1 = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %t1, ptr addrspace(2) %s, <2 x float> , i1 true, <2 x i32> zeroinitializer, i1 true, float 0.0, float 0.0, i32 0)\n\ + %v0 = extractvalue { <4 x float>, i8 } %r0, 0\n\ + %v1 = extractvalue { <4 x float>, i8 } %r1, 0\n\ + %x0 = extractelement <4 x float> %v0, i64 0\n\ + %x1 = extractelement <4 x float> %v1, i64 0\n\ + %x = fadd float %x0, %x1\n\ + %low = fcmp olt float %x, -1.0e30\n\ + %e = select i1 %low, i32 1000, i32 0\n\ + %gw = zext i32 %gid to i64\n\ + %p = getelementptr inbounds i32, ptr addrspace(1) %a, i64 %gw\n\ + %w = load i32, ptr addrspace(1) %p, align 4\n\ + %kv = load i32, ptr addrspace(2) %k, align 4\n\ + %s1 = add i32 %w, %kv\n\ + %v = add i32 %s1, %e\n\ + store i32 %v, ptr addrspace(1) %p, align 4\n\ + ret void\n\ +}\n\n\ +declare { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32)\n\n\ +!llvm.module.flags = !{!0, !1}\n!air.kernel = !{!20}\n!air.version = !{!8}\n!air.language_version = !{!9}\n\ +!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n\ +!1 = !{i32 7, !\"air.max_threadgroup_buffers\", i32 31}\n\ +!3 = !{}\n!4 = !{!10, !11, !12, !5, !13, !7}\n\ +!10 = !{i32 0, !\"air.texture\", !\"air.location_index\", i32 0, i32 1, !\"air.sample\", !\"air.arg_type_name\", !\"texture2d\", !\"air.arg_name\", !\"t0\"}\n\ +!11 = !{i32 1, !\"air.texture\", !\"air.location_index\", i32 1, i32 1, !\"air.sample\", !\"air.arg_type_name\", !\"texture2d\", !\"air.arg_name\", !\"t1\"}\n\ +!12 = !{i32 2, !\"air.sampler\", !\"air.location_index\", i32 0, i32 1, !\"air.arg_type_name\", !\"sampler\", !\"air.arg_name\", !\"s\"}\n\ +!5 = !{i32 3, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"a\"}\n\ +!13 = !{i32 4, !\"air.buffer\", !\"air.buffer_size\", i32 4, !\"air.location_index\", i32 1, i32 1, !\"air.read\", !\"air.address_space\", i32 2, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"k\"}\n\ +!7 = !{i32 5, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}\n\ +!8 = !{i32 2, i32 8, i32 0}\n!9 = !{!\"Metal\", i32 4, i32 0, i32 0}\n\ +!20 = !{ptr @bump_tex, !3, !4}\n"; + /// The same work in SPIR-V, its threadgroup `{T}` threads wide: `words[gid.x] += 1` over a /// storage buffer at set 0, binding 0. const SPIRV: &str = "OpCapability Shader @@ -121,6 +234,27 @@ OpReturn OpFunctionEnd "; +/// What a dispatch binds (`--binds`), and so its kernel. +#[derive(Clone, Copy, PartialEq)] +enum Binds { + /// `bump`'s words alone. + One, + /// `bump_wide`'s words, two buffers of zeros and bytes. + Wide, + /// `bump_tex`'s two textures, sampler, words and bytes. + Textures, +} + +impl Binds { + fn name(self) -> &'static str { + match self { + Binds::One => "1", + Binds::Wide => "4", + Binds::Textures => "tex", + } + } +} + /// The run's shape: dispatches a command buffer, threadgroups a dispatch, threads a threadgroup, /// timed runs, and the shapes to run. struct Shape { @@ -129,6 +263,12 @@ struct Shape { threads: u32, runs: usize, only: Option>, + /// What a dispatch binds. + binds: Binds, + /// Command buffers a run of the host's time (`--host`), `None` for the GPU's. + host: Option, + /// Whether the words and zeros lie in no-copy buffers over host pages (`--pages`). + pages: bool, } impl Shape { @@ -139,9 +279,16 @@ impl Shape { threads: 32, runs: 9, only: None, + binds: Binds::One, + host: None, + pages: false, }; let mut args = std::env::args().skip(1); while let Some(flag) = args.next() { + if flag == "--pages" { + shape.pages = true; + continue; + } let value = args.next().ok_or(format!("{flag} takes a value"))?; match flag.as_str() { "--dispatches" => shape.dispatches = value.parse()?, @@ -149,6 +296,15 @@ impl Shape { "--threads" => shape.threads = value.parse()?, "--runs" => shape.runs = value.parse()?, "--only" => shape.only = Some(value.split(',').map(str::to_owned).collect()), + "--binds" => { + shape.binds = match value.as_str() { + "1" => Binds::One, + "4" => Binds::Wide, + "tex" => Binds::Textures, + _ => return Err("--binds takes 1, 4 or tex".into()), + } + } + "--host" => shape.host = Some(value.parse()?), _ => return Err(format!("unknown flag {flag}").into()), } } @@ -187,13 +343,18 @@ fn tool(tool: &str, args: &[&str], input: &str) -> Result> { Ok(output.stdout) } -/// The state of [`KERNEL`]. -fn state(device: &Device) -> Result { - let bitcode = tool("llvm-as", &["-o", "-", "-"], KERNEL)?; +/// The state of the kernel `binds` binds for. +fn state(device: &Device, binds: Binds) -> Result { + let (text, name) = match binds { + Binds::One => (KERNEL, "bump"), + Binds::Wide => (KERNEL_WIDE, "bump_wide"), + Binds::Textures => (KERNEL_TEX, "bump_tex"), + }; + let bitcode = tool("llvm-as", &["-o", "-", "-"], text)?; let library = metal2vulkan::library::Library::from_air(&bitcode)?; let function = device .new_library_with_compile_library(library) - .new_function_with_name("bump")?; + .new_function_with_name(name)?; Ok(device.new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())?) } @@ -260,11 +421,154 @@ impl Samples { } } -/// The runtime's shapes over one buffer. +/// A call of the host's time, in [`Lap`]'s order. +#[derive(Clone, Copy)] +enum Call { + Make, + Open, + Pipeline, + Bind, + Dispatch, + End, + Commit, +} + +/// The calls' names, in [`Call`]'s order. +const CALLS: [&str; 7] = [ + "make", "open", "pipeline", "bind", "dispatch", "end", "commit", +]; + +/// Nanoseconds of the calling thread's time by [`Call`], over a run. +#[derive(Default, Clone, Copy)] +struct Lap([u64; 7]); + +impl Lap { + /// Count the time since `at` to `call`, and start the next call's there. + fn lap(&mut self, at: &mut Instant, call: Call) { + let now = Instant::now(); + self.0[call as usize] += (now - *at).as_nanos() as u64; + *at = now; + } +} + +/// The host's time of the counted runs: each call's sum, the calling thread's CPU over them, and +/// each run's encoding and commit. +#[derive(Default)] +struct HostSample { + calls: [u64; 7], + thread_cpu: u64, + per_run: Vec, +} + +impl HostSample { + fn add(&mut self, lap: Lap) { + for (sum, nanos) in self.calls.iter_mut().zip(lap.0) { + *sum += nanos; + } + self.per_run.push(lap.0.iter().sum()); + } + + fn print(&self, name: &str, shape: &Shape, command_buffers: u32, dispatches: f64) { + let per = |nanos: u64| nanos as f64 / dispatches; + let mut line = format!( + "HOST {name} dispatches {} command_buffers {command_buffers} binds {} ns_per_dispatch", + shape.dispatches, + shape.binds.name() + ); + for (call, nanos) in CALLS.iter().zip(self.calls) { + if *call == "commit" { + let encode: u64 = self.calls[..6].iter().sum(); + line.push_str(&format!(" encode {:.0}", per(encode))); + } + line.push_str(&format!(" {call} {:.0}", per(nanos))); + } + let least = self.per_run.iter().min().copied().unwrap_or(0); + let runs = self.per_run.len().max(1) as f64; + line.push_str(&format!( + " thread_cpu {:.0} least_encode_commit {:.0}", + per(self.thread_cpu), + least as f64 * runs / dispatches + )); + println!("{line}"); + } +} + +/// `bytes` bytes of fresh host pages, read-write, never unmapped: private, as RADV refuses to +/// import shared anonymous memory (`host_memory.rs`'s `import_refused`). +fn host_pages(bytes: usize) -> Result> { + // SAFETY: a fresh anonymous mapping, read-write, never unmapped. + let pages = unsafe { + libc::mmap( + std::ptr::null_mut(), + bytes, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_ANON | libc::MAP_PRIVATE, + -1, + 0, + ) + }; + if pages == libc::MAP_FAILED { + return Err(format!("mmap: {}", std::io::Error::last_os_error()).into()); + } + Ok(NonNull::new(pages.cast::()).ok_or("a null mapping")?) +} + +/// This thread's CPU time so far, in nanoseconds. +fn thread_cpu_nanos() -> u64 { + // SAFETY: a plain call with an out-parameter of the right type. + let spec = unsafe { + let mut spec: libc::timespec = std::mem::zeroed(); + libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut spec); + spec + }; + spec.tv_sec as u64 * 1_000_000_000 + spec.tv_nsec as u64 +} + +/// The group a thread named `comm` is counted in, the process's first thread (`main`) the +/// committer. +fn group_of(comm: &str, main: bool) -> &'static str { + match comm { + _ if main => "committer", + c if c.starts_with("metal2vulkan-sc") => "scheduler", + c if c.starts_with("metal2vulkan-qu") => "queue-waiters", + c if c.starts_with("metal2vulkan") || c.starts_with("m2v-") => "other-m2v", + _ => "driver", + } +} + +/// Nanoseconds of CPU by thread group, each of the process's threads by its name: Linux only, +/// none elsewhere. +fn cpu_by_group() -> Vec<(String, u64)> { + let mut groups: Vec<(String, u64)> = Vec::new(); + let Ok(tasks) = std::fs::read_dir("/proc/self/task") else { + return groups; + }; + for task in tasks.flatten() { + let path = task.path(); + let comm = std::fs::read_to_string(path.join("comm")).unwrap_or_default(); + let stat = std::fs::read_to_string(path.join("schedstat")).unwrap_or_default(); + let nanos: u64 = (stat.split_whitespace().next()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0); + let main = task.file_name().to_str() == Some(&std::process::id().to_string()); + let group = group_of(comm.trim(), main); + match groups.iter_mut().find(|(n, _)| *n == group) { + Some((_, total)) => *total += nanos, + None => groups.push((group.to_owned(), nanos)), + } + } + groups +} + +/// The runtime's shapes over one buffer, with two of zeros for `bump_wide`, and two textures and +/// a sampler for `bump_tex`. struct Ours<'a> { device: &'a Device, state: ComputePipelineState, words: Buffer, + zeros: [Buffer; 2], + textures: [Texture; 2], + sampler: SamplerState, readback: Buffer, } @@ -287,8 +591,8 @@ impl Ours<'_> { _ => command_buffer.compute_command_encoder()?, }; encoder.set_compute_pipeline_state(&self.state)?; - encoder.set_buffer(Some(&self.words), 0, 0)?; - for _ in 0..shape.dispatches / encoders { + for n in 0..shape.dispatches / encoders { + self.bind(&mut encoder, shape.binds, n as usize)?; encoder.dispatch_threadgroups(groups, threads)?; } encoder.end_encoding()?; @@ -304,6 +608,152 @@ impl Ours<'_> { Ok(gpu * 1e6 / f64::from(shape.dispatches)) } + /// Bind what dispatch `n` of an encoder binds: the words, and `bump_wide`'s read-only + /// buffers or `bump_tex`'s textures the other way round from dispatch `n - 1`, with their + /// word of 1. + fn bind(&self, encoder: &mut ComputeCommandEncoder, binds: Binds, n: usize) -> Result<()> { + let one = 1u32.to_le_bytes(); + match binds { + Binds::One => encoder.set_buffer(Some(&self.words), 0, 0)?, + Binds::Wide => { + encoder.set_buffer(Some(&self.words), 0, 0)?; + encoder.set_buffer(Some(&self.zeros[n % 2]), 0, 1)?; + encoder.set_buffer(Some(&self.zeros[1 - n % 2]), 0, 2)?; + encoder.set_bytes(&one, 3)?; + } + Binds::Textures => { + encoder.set_texture(Some(&self.textures[n % 2]), 0)?; + encoder.set_texture(Some(&self.textures[1 - n % 2]), 1)?; + encoder.set_sampler_state(Some(&self.sampler), 0)?; + encoder.set_buffer(Some(&self.words), 0, 0)?; + encoder.set_bytes(&one, 1)?; + } + } + Ok(()) + } + + /// One run of the host's time: `command_buffers` command buffers of `shape`'s dispatches as + /// `name` holds them on `queue`, each committed with `commit_and_submit` and waited for. + fn run_host( + &self, + queue: &CommandQueue, + name: &str, + shape: &Shape, + command_buffers: u32, + host: &mut HostSample, + ) -> Result<()> { + let groups = Size::new(u64::from(shape.groups), 1, 1); + let threads = Size::new(u64::from(shape.threads), 1, 1); + let encoders = match name { + "encoders" => shape.dispatches, + _ => 1, + }; + let mut lap = Lap::default(); + for _ in 0..command_buffers { + let cpu = thread_cpu_nanos(); + let mut at = Instant::now(); + let command_buffer = queue.command_buffer()?; + lap.lap(&mut at, Call::Make); + for _ in 0..encoders { + let mut encoder = match name { + "concurrent" => command_buffer + .compute_command_encoder_with_dispatch_type(DispatchType::Concurrent)?, + _ => command_buffer.compute_command_encoder()?, + }; + lap.lap(&mut at, Call::Open); + for n in 0..shape.dispatches / encoders { + encoder.set_compute_pipeline_state(&self.state)?; + lap.lap(&mut at, Call::Pipeline); + self.bind(&mut encoder, shape.binds, n as usize)?; + lap.lap(&mut at, Call::Bind); + encoder.dispatch_threadgroups(groups, threads)?; + lap.lap(&mut at, Call::Dispatch); + } + encoder.end_encoding()?; + lap.lap(&mut at, Call::End); + } + command_buffer.commit_and_submit()?; + lap.lap(&mut at, Call::Commit); + host.thread_cpu += thread_cpu_nanos() - cpu; + command_buffer + .wait_until_completed_for(WAIT) + .map_err(|_| format!("a command buffer did not complete within {WAIT:?}"))?; + if command_buffer.status() != CommandBufferStatus::Completed { + return Err(format!("a command buffer ended {:?}", command_buffer.error()).into()); + } + } + host.add(lap); + Ok(()) + } + + /// Clear the words, run the host's time of `shape` as `name` holds it, and check the words. + fn host_shape(&self, name: &str, shape: &Shape, command_buffers: u32) -> Result<()> { + self.fill(0)?; + let queue = self.device.new_command_queue()?; + let mut first = HostSample::default(); + self.run_host(&queue, name, shape, command_buffers, &mut first)?; + let mut host = HostSample::default(); + let (before, threads) = (self.device.work_counts(), cpu_by_group()); + for _ in 0..shape.runs { + self.run_host(&queue, name, shape, command_buffers, &mut host)?; + } + let (after, threads_after) = (self.device.work_counts(), cpu_by_group()); + if name != "concurrent" { + let runs = shape.runs as u32 + 1; + self.check(shape.dispatches * command_buffers * runs, name)?; + } + let dispatches = (shape.dispatches * command_buffers) as f64 * shape.runs as f64; + host.print(name, shape, command_buffers, dispatches); + let phases = [ + ( + "lowering", + after.commit_lowering_nanos - before.commit_lowering_nanos, + ), + ( + "recording", + after.commit_recording_nanos - before.commit_recording_nanos, + ), + ( + "pipeline_wait", + after.commit_pipeline_wait_nanos - before.commit_pipeline_wait_nanos, + ), + ( + "lock_wait", + after.commit_lock_wait_nanos - before.commit_lock_wait_nanos, + ), + ("pass", after.commit_pass_nanos - before.commit_pass_nanos), + ( + "submit", + after.commit_submit_nanos - before.commit_submit_nanos, + ), + ]; + let line: Vec = (phases.iter()) + .map(|(phase, nanos)| format!("{phase} {:.0}", *nanos as f64 / dispatches)) + .collect(); + println!("HOST-COMMIT {name} {}", line.join(" ")); + let line: Vec = (threads_after.iter()) + .map(|(group, nanos)| { + let earlier = (threads.iter()) + .find(|(g, _)| g == group) + .map_or(0, |(_, n)| *n); + format!( + "{group}={:.0}", + nanos.saturating_sub(earlier) as f64 / dispatches + ) + }) + .collect(); + if !line.is_empty() { + println!("HOST-THREADS {name} {}", line.join(" ")); + } + let mut moved = BTreeMap::new(); + add_moved(&mut moved, &before, &after); + let line: Vec = (moved.iter()) + .map(|(count, sum)| format!("{count}={:.2}", *sum as f64 / dispatches)) + .collect(); + println!("HOST-COUNTS {name} {}", line.join(" ")); + Ok(()) + } + /// Clear the words, run `shape` as `name` holds it, and check what the chained shapes left. fn shape(&self, name: &str, shape: &Shape, device: &str) -> Result<()> { self.fill(0)?; @@ -331,6 +781,9 @@ impl Ours<'_> { let command_buffer = queue.command_buffer()?; let mut blit = command_buffer.blit_command_encoder()?; blit.fill_buffer(&self.words, 0..self.words.length(), value)?; + for zeros in &self.zeros { + blit.fill_buffer(zeros, 0..zeros.length(), 0)?; + } blit.end_encoding()?; command_buffer.commit()?; command_buffer @@ -813,17 +1266,49 @@ fn main() -> Result<()> { let name = device.name().to_string(); println!("device: {name}"); let bytes = shape.words() * 4; + let buffer = || -> Result { + if !shape.pages { + return Ok(device.new_buffer(bytes, ResourceOptions::private())?); + } + // SAFETY: page-aligned read-write memory of `bytes` bytes, never unmapped, which outlives + // the buffer. + let buffer = unsafe { + device.new_buffer_with_bytes_no_copy( + HostMemory::new(host_pages(bytes as usize)?), + bytes, + ResourceOptions::shared(), + None, + ) + }?; + Ok(buffer) + }; + let texture = || -> Result { + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 16, 16, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::private(); + Ok(device.new_texture(&descriptor)?) + }; let ours = Ours { device: &device, - state: state(&device)?, - words: device.new_buffer(bytes, ResourceOptions::private())?, + state: state(&device, shape.binds)?, + words: buffer()?, + zeros: [buffer()?, buffer()?], + textures: [texture()?, texture()?], + sampler: device.new_sampler_state(&SamplerDescriptor::new())?, readback: device.new_buffer(bytes, ResourceOptions::shared())?, }; for shape_name in ["encoders", "serial", "concurrent"] { - if shape.runs(shape_name) { - ours.shape(shape_name, &shape, &name)?; + match (shape.runs(shape_name), shape.host) { + (false, _) => {} + (true, Some(command_buffers)) => { + ours.host_shape(shape_name, &shape, command_buffers)? + } + (true, None) => ours.shape(shape_name, &shape, &name)?, } } + if shape.host.is_some() { + return Ok(()); + } let raw = Raw::new(&device, &shape)?; for shape_name in ["raw-barrier", "raw-wide", "raw-split", "raw-none"] { if !shape.runs(shape_name) { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 82e7f8ff1..3651c3984 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -992,6 +992,12 @@ pub(super) struct State { residency: Option, /// The ended encoders whose resources `residency` holds joined: those before this place. joined: usize, + /// What its next compute encoder (`[0]`) and render encoder (`[1]`) start with + /// ([`inherited`](Self::inherited)), with the number of ended encoders it took in: kept from + /// one open to the next, so an open looks at the encoders ended since the last alone, not + /// every earlier one. Let go of where `residency` or an ended encoder's residency may change + /// ([`joined_residency`](Self::joined_residency), `splice_replay`). + inherits: [Option<(Residency, usize)>; 2], /// What its work may write through its residency (`Residency::written_uses`), set at its /// commit: every resource made resident for writing, by any of its encoders. A function of /// any of its encoders may write such a resource unnamed (residency is the command @@ -1397,6 +1403,8 @@ impl State { /// (`reencode.rs`). pub(super) fn joined_residency(&mut self, counts: &Counters) -> Option<&mut Residency> { let residency = self.residency.as_mut()?; + // What the next encoders start with is found again from the residency as it is left. + self.inherits = [None, None]; for record in &self.ended[self.joined..] { if let Some(ended) = &record.residency { let compute = record.kind == EncoderKind::Compute; @@ -1428,19 +1436,31 @@ impl State { /// What its next compute or render (`render`) encoder starts with (`Residency::shadows`): /// the shadowed textures its ended encoders made resident, those its residency joined and - /// those it has yet to, in the order they were made resident. - fn inherited(&mut self, render: bool) -> Residency { + /// those it has yet to, in the order they were made resident. Kept from the last open of + /// the kind ([`inherits`](Self::inherits)): the encoders ended since are taken in, each once, + /// in the order they ended, each counted (`WorkCounts::ended_residencies_looked_at`); the + /// encoders before it took in left what they hold, and the residency is as it found it. + fn inherited(&mut self, render: bool, counts: &Counters) -> Residency { let Some(residency) = &mut self.residency else { return Residency::default(); }; - let mut shadows = residency.shadows(render); - for record in &mut self.ended[self.joined..] { + let joined = self.joined; + let (shadows, through) = self.inherits[usize::from(render)] + .get_or_insert_with(|| (residency.shadows(render), joined)); + let since = self.ended.get_mut(*through..).unwrap_or_default(); + let mut looked_at = 0; + for record in since { if let Some(ended) = &mut record.residency { let compute = record.kind == EncoderKind::Compute; - ended.shadows_onto(&mut shadows, render, compute); + ended.shadows_onto(shadows, render, compute); + looked_at += 1; } } - shadows + if looked_at > 0 { + counts.ended_residencies_looked_at(looked_at); + } + *through = self.ended.len(); + shadows.clone() } /// Set [`resident_writes`](Self::resident_writes) from what each ended encoder made resident @@ -2544,6 +2564,7 @@ impl CommandBuffer { holds: Vec::new(), residency: None, joined: 0, + inherits: [None, None], resident_writes: None, ended: Vec::new(), root_tables: Vec::new(), @@ -3043,8 +3064,9 @@ impl CommandBuffer { /// the heaps they used made since included. pub(super) fn inherited_residency(&self, render: bool) -> Residency { let mut state = self.state(); - state.sync_heaps(&self.0.device.shared().counts); - state.inherited(render) + let counts = &self.0.device.shared().counts; + state.sync_heaps(counts); + state.inherited(render, counts) } /// What its ended encoders made resident, every encoder's joined (`residency.rs`): what the diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index cb7b5d7df..fe020977b 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -626,6 +626,8 @@ impl State { segment.executions_at = moved(segment.executions_at); } } + // What the next encoders start with is found again from the residencies as they are left. + self.inherits = [None, None]; let record = &mut self.ended[at]; record.executions = first.start..first.start + count; record.keys = keys; diff --git a/crates/metal2vulkan-runtime/src/tests/joined_residency.rs b/crates/metal2vulkan-runtime/src/tests/joined_residency.rs index 423090c19..812cead2f 100644 --- a/crates/metal2vulkan-runtime/src/tests/joined_residency.rs +++ b/crates/metal2vulkan-runtime/src/tests/joined_residency.rs @@ -5,7 +5,10 @@ //! more (`WorkCounts::resident_resources_joined`). The shadowed textures (`shadow.rs`) an ended //! encoder made resident reach the encoders opened after, whether its resources are joined yet or //! not, each once and in the order they were made resident; making a texture resident reads -//! nothing of it, the open that first asks looks at each once (`Residency::find_shadowed`). +//! nothing of it, the open that first asks looks at each once (`Residency::find_shadowed`). An open +//! looks at the encoders ended since the open before alone, each ended encoder's residency once, +//! not every earlier encoder's again (`WorkCounts::ended_residencies_looked_at`), and a widened +//! usage reaches the encoders opened after. //! //! 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. @@ -142,3 +145,72 @@ fn shadowed_textures_made_resident_reach_the_next_encoders_in_order() { command_buffer.wait_until_completed().unwrap(); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); } + +/// The command buffer's compute encoders, each making one buffer of its own resident. +const ENCODERS: usize = 64; + +/// A command buffer of [`ENCODERS`] compute encoders, each making a buffer resident: each open +/// looks at the encoders ended since the open before alone, 63 ended encoders' residencies in all, +/// not each earlier one at each open (2016). A read of the command buffer's residency after the +/// 32nd joins the 32 ended so far; the opens after it start from what it joined, and look at the +/// encoders ended since alone. +#[test] +fn an_open_looks_at_the_encoders_ended_since_the_open_before_alone() { + let device = device(); + let queue = device.new_command_queue().unwrap(); + let buffers: Vec = (0..ENCODERS) + .map(|_| device.new_buffer(256, ResourceOptions::default()).unwrap()) + .collect(); + let looked_at = || device.work_counts().ended_residencies_looked_at; + let before = looked_at(); + let command_buffer = queue.command_buffer().unwrap(); + for (n, buffer) in buffers.iter().enumerate() { + if n == ENCODERS / 2 { + drop(command_buffer.residency().unwrap()); + } + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder + .use_resources(&[buffer.as_resource()], ResourceUsage::READ) + .unwrap(); + encoder.end_encoding().unwrap(); + } + // The 32 opens before the read look at 31 encoders; the read joins the 32 ended, and the 32 + // opens after it at the 31 ended between them. + assert_eq!( + looked_at() - before, + (ENCODERS - 2) as u64, + "an open looked at encoders an open before it looked at" + ); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed().unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} + +/// A shadowed texture made resident for reading by one compute encoder and for writing by the +/// next: the encoder opened after them starts with it for both, its usage widened, as it would +/// had each open looked at every ended encoder again. +#[test] +fn a_widened_usage_reaches_the_encoders_opened_after() { + let device = device(); + let queue = device.new_command_queue().unwrap(); + let (_bytes, texture) = shadowed(&device); + let command_buffer = queue.command_buffer().unwrap(); + let written = || { + let residency = command_buffer.inherited_residency(false); + (residency.textures_written()) + .map(|(texture, writes)| (texture.clone(), writes)) + .collect::>() + }; + for usage in [ResourceUsage::READ, ResourceUsage::WRITE] { + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder + .use_resources(&[texture.as_resource()], usage) + .unwrap(); + encoder.end_encoding().unwrap(); + let writes = usage == ResourceUsage::WRITE; + assert_eq!(written(), [(texture.clone(), writes)], "after {usage:?}"); + } + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed().unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 1c9be062f..374f8c9e1 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -403,6 +403,7 @@ pub(crate) struct Counters { stand_in_copies_made_at_draws: AtomicU64, resident_textures_looked_at: AtomicU64, resident_resources_joined: AtomicU64, + ended_residencies_looked_at: AtomicU64, resident_address_indexes_made: AtomicU64, resident_kept_keys_listed: AtomicU64, root_table_ranges_noted: AtomicU64, @@ -3864,6 +3865,13 @@ impl Counters { .fetch_add(count, Ordering::Relaxed); } + /// An open of a compute or render encoder looked at `count` ended encoders' residencies for + /// the shadowed textures it starts with (`command_buffer::State::inherited`). + pub(crate) fn ended_residencies_looked_at(&self, count: u64) { + self.ended_residencies_looked_at + .fetch_add(count, Ordering::Relaxed); + } + /// A residency's buffers were indexed by Metal address (`residency::AddressIndex`). pub(crate) fn resident_address_index_made(&self) { self.resident_address_indexes_made @@ -7989,6 +7997,13 @@ pub struct WorkCounts { /// resources once. None for a command buffer whose work never reads it, however many /// resources its encoders made resident. pub resident_resources_joined: u64, + /// Ended compute and render encoders' residencies looked at for the shadowed textures + /// (`shadow.rs`) a later compute or render encoder of their command buffer starts with: each + /// once for the first compute encoder opened after it ended and once for the first render + /// encoder, and again only where the command buffer's residency joined the ended encoders' + /// or an encoder was encoded again since. A command buffer of `n` compute encoders counts at + /// most `n - 1`, not each earlier encoder at each open. + pub ended_residencies_looked_at: u64, /// Indexes of the buffers and heaps a residency made resident by Metal address, which an /// indirect command buffer's commands' addresses resolve in (`Residency::resolve`): one at /// the first look after a resource was made resident into a residency holding a buffer or a @@ -11181,6 +11196,8 @@ impl Device { resident_textures_looked_at: (counters.resident_textures_looked_at) .load(Ordering::Relaxed), resident_resources_joined: (counters.resident_resources_joined).load(Ordering::Relaxed), + ended_residencies_looked_at: (counters.ended_residencies_looked_at) + .load(Ordering::Relaxed), root_table_ranges_noted: (counters.root_table_ranges_noted).load(Ordering::Relaxed), resident_address_indexes_made: (counters.resident_address_indexes_made) .load(Ordering::Relaxed), diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index bf169b0ae..3fc582094 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522; /// 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 = 2269; +pub const RUNTIME_VERSION: u32 = 2270; /// 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 f20119027..cec343f77 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2974,6 +2974,7 @@ field metal2vulkan-runtime::WorkCounts.encoders_uncarried_split pub encoders_unc field metal2vulkan-runtime::WorkCounts.encoders_uncarried_unrebound pub encoders_uncarried_unrebound: u64 field metal2vulkan-runtime::WorkCounts.encoders_uncarried_unsettled pub encoders_uncarried_unsettled: u64 field metal2vulkan-runtime::WorkCounts.encoders_uncarried_visibility pub encoders_uncarried_visibility: u64 +field metal2vulkan-runtime::WorkCounts.ended_residencies_looked_at pub ended_residencies_looked_at: u64 field metal2vulkan-runtime::WorkCounts.event_signals_behind_merge pub event_signals_behind_merge: u64 field metal2vulkan-runtime::WorkCounts.event_waits_met pub event_waits_met: u64 field metal2vulkan-runtime::WorkCounts.exported_dma_buf_images pub exported_dma_buf_images: u64