diff --git a/crates/metal2vulkan-runtime/Cargo.toml b/crates/metal2vulkan-runtime/Cargo.toml index 1a2ce89f5..00fb047fa 100644 --- a/crates/metal2vulkan-runtime/Cargo.toml +++ b/crates/metal2vulkan-runtime/Cargo.toml @@ -123,6 +123,13 @@ path = "examples/queue_plan_cost.rs" name = "pass_costs" path = "examples/pass_costs.rs" +# Not a consumer's example: what a chain of dependent compute dispatches costs the GPU, by how a +# command buffer holds them (an encoder each, one serial or concurrent encoder), beside the same +# chain recorded straight through Vulkan (examples/dispatch_chain.rs). +[[example]] +name = "dispatch_chain" +path = "examples/dispatch_chain.rs" + [dependencies] # The translator, through its public API only: the compiler checks that the runtime # reaches nothing else. `ash` gives `ash_interop`'s conversions and `DeviceDescription::query`. diff --git a/crates/metal2vulkan-runtime/examples/dispatch_chain.rs b/crates/metal2vulkan-runtime/examples/dispatch_chain.rs new file mode 100644 index 000000000..8db808e4c --- /dev/null +++ b/crates/metal2vulkan-runtime/examples/dispatch_chain.rs @@ -0,0 +1,855 @@ +//! Not a consumer's example: what a chain of dependent compute dispatches costs the GPU, by how a +//! command buffer holds them, beside the same chain recorded straight through Vulkan on a +//! `VkDevice` of the example's own, made on the runtime device's physical device. +//! +//! ```sh +//! cargo run --release -p metal2vulkan-runtime --example dispatch_chain -- \ +//! [--dispatches N] [--groups G] [--threads T] [--runs R] [--only SHAPE,...] +//! ``` +//! +//! Each run is one command buffer of `N` dispatches (200 by default) of `G` threadgroups of `T` +//! threads (4096 of 32 by default) over one `Private` buffer of `G * T` words, each thread adding +//! 1 to its own word: every dispatch reads what the one before wrote. The shapes: +//! +//! - **`encoders`**: `N` compute encoders of one dispatch each, as a program that opens an encoder +//! for each dispatch records them; +//! - **`serial`**: one serial compute encoder of the `N` dispatches; +//! - **`concurrent`**: one concurrent encoder of them, with no memory barrier: nothing orders the +//! dispatches, so this is the kernels' own time with no barrier between them (their words race, +//! which is not checked); +//! - **`raw-barrier`**: one `VkCommandBuffer` of the `N` dispatches of the same work (a SPIR-V +//! kernel written here, assembled by `spirv-as`), each after one `VkMemoryBarrier` from +//! `COMPUTE_SHADER`'s `SHADER_WRITE` to `COMPUTE_SHADER`'s `SHADER_READ | SHADER_WRITE`, the +//! least barrier Vulkan states for a read after a write between dispatches; +//! - **`raw-wide`**: the same, with the runtime's barrier between dispatches of an encoder +//! (`Barrier::between_dispatches`: also `DRAW_INDIRECT` and its `INDIRECT_COMMAND_READ`, and +//! `UNIFORM_READ`); +//! - **`raw-split`**: `raw-barrier` with each dispatch in a `VkCommandBuffer` of its own, after +//! a `VkCommandBuffer` holding its barrier alone: `2N` command buffers in one `vkQueueSubmit`; +//! - **`raw-none`**: one `VkCommandBuffer` of the dispatches with no barrier. +//! +//! The runtime's shapes take the GPU's time from the command buffer's `gpu_start_time` to its +//! `gpu_end_time`, the raw ones from a timestamp before the first dispatch to one after the last. +//! Each line is the median over `R` runs (9 by default) after one not counted, per dispatch, with +//! the runtime's counts per command buffer that moved (`WorkCounts`, by name from their `Debug` +//! form), and those of the run not counted, the shape's first command buffer, apart: its first +//! recording of the kernel's dispatches, as a program's first command buffer of a kind is. The +//! words are read back after each chained shape: each must hold the dispatches run on it. +//! +//! ```text +//! CHAIN dispatches groups threads gpu_us_per_dispatch least +//! +//! CHAIN-COUNTS = ... +//! CHAIN-FIRST = ... +//! ``` +//! +//! 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_runtime::{ + Buffer, CommandBufferStatus, ComputePipelineState, Device, DeviceOptions, PipelineOptions, + ResourceOptions, Size, WorkCounts, +}; +use std::collections::BTreeMap; +use std::io::Write; +use std::process::{Command, Stdio}; +use std::time::Duration; + +/// The example's result: every runtime refusal is a typed `metal2vulkan_runtime::Error`. +type Result = std::result::Result>; + +/// The longest the example waits for a command buffer. +const WAIT: Duration = Duration::from_secs(60); + +/// `bump`: `a[gid] += 1`, `a` a buffer of words at index 0. +const KERNEL: &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(ptr addrspace(1) noundef %a, i32 noundef %gid) {\n\ +entry:\n\ + %gw = zext i32 %gid to i64\n\ + %p = getelementptr inbounds i32, ptr addrspace(1) %a, i64 %gw\n\ + %x = load i32, ptr addrspace(1) %p, align 4\n\ + %v = add i32 %x, 1\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, !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\ +!7 = !{i32 1, !\"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, !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 +OpMemoryModel Logical GLSL450 +OpEntryPoint GLCompute %main \"main\" %gid %buf +OpExecutionMode %main LocalSize {T} 1 1 +OpDecorate %gid BuiltIn GlobalInvocationId +OpDecorate %words ArrayStride 4 +OpMemberDecorate %block 0 Offset 0 +OpDecorate %block Block +OpDecorate %buf DescriptorSet 0 +OpDecorate %buf Binding 0 +%void = OpTypeVoid +%fn = OpTypeFunction %void +%uint = OpTypeInt 32 0 +%v3uint = OpTypeVector %uint 3 +%in_v3 = OpTypePointer Input %v3uint +%gid = OpVariable %in_v3 Input +%words = OpTypeRuntimeArray %uint +%block = OpTypeStruct %words +%sb_block = OpTypePointer StorageBuffer %block +%buf = OpVariable %sb_block StorageBuffer +%sb_uint = OpTypePointer StorageBuffer %uint +%zero = OpConstant %uint 0 +%one = OpConstant %uint 1 +%main = OpFunction %void None %fn +%entry = OpLabel +%g = OpLoad %v3uint %gid +%x = OpCompositeExtract %uint %g 0 +%p = OpAccessChain %sb_uint %buf %zero %x +%v = OpLoad %uint %p +%w = OpIAdd %uint %v %one +OpStore %p %w +OpReturn +OpFunctionEnd +"; + +/// The run's shape: dispatches a command buffer, threadgroups a dispatch, threads a threadgroup, +/// timed runs, and the shapes to run. +struct Shape { + dispatches: u32, + groups: u32, + threads: u32, + runs: usize, + only: Option>, +} + +impl Shape { + fn from_args() -> Result { + let mut shape = Shape { + dispatches: 200, + groups: 4096, + threads: 32, + runs: 9, + only: None, + }; + let mut args = std::env::args().skip(1); + while let Some(flag) = args.next() { + let value = args.next().ok_or(format!("{flag} takes a value"))?; + match flag.as_str() { + "--dispatches" => shape.dispatches = value.parse()?, + "--groups" => shape.groups = value.parse()?, + "--threads" => shape.threads = value.parse()?, + "--runs" => shape.runs = value.parse()?, + "--only" => shape.only = Some(value.split(',').map(str::to_owned).collect()), + _ => return Err(format!("unknown flag {flag}").into()), + } + } + Ok(shape) + } + + fn runs(&self, name: &str) -> bool { + self.only + .as_ref() + .is_none_or(|only| only.iter().any(|shape| shape == name)) + } + + fn words(&self) -> u64 { + u64::from(self.groups) * u64::from(self.threads) + } +} + +/// Run `tool` from `PATH` over `input` on its standard input: its standard output. +fn tool(tool: &str, args: &[&str], input: &str) -> Result> { + let mut child = Command::new(tool) + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|error| format!("cannot run {tool} (put it on PATH): {error}"))?; + child + .stdin + .take() + .ok_or("no stdin")? + .write_all(input.as_bytes())?; + let output = child.wait_with_output()?; + if !output.status.success() { + return Err(format!("{tool}: {}", String::from_utf8_lossy(&output.stderr)).into()); + } + Ok(output.stdout) +} + +/// The state of [`KERNEL`]. +fn state(device: &Device) -> Result { + let bitcode = tool("llvm-as", &["-o", "-", "-"], KERNEL)?; + let library = metal2vulkan::library::Library::from_air(&bitcode)?; + let function = device + .new_library_with_compile_library(library) + .new_function_with_name("bump")?; + Ok(device.new_compute_pipeline_state_with_function(&function, &PipelineOptions::default())?) +} + +/// The counts of `counts` by name, read from their `Debug` form. +fn counts(counts: &WorkCounts) -> BTreeMap { + let text = format!("{counts:?}"); + text.split([',', '{']) + .filter_map(|part| { + let (name, value) = part.split_once(':')?; + Some((name.trim().to_owned(), value.trim().parse().ok()?)) + }) + .collect() +} + +/// The samples of one shape: GPU microseconds per dispatch, the counts' sums over the runs +/// counted, and the counts of the run not counted, its first. +#[derive(Default)] +struct Samples { + per_dispatch: Vec, + counts: BTreeMap, + first: BTreeMap, +} + +/// What moved from `before` to `after`, added to `into`. +fn add_moved(into: &mut BTreeMap, before: &WorkCounts, after: &WorkCounts) { + let before = counts(before); + for (name, value) in counts(after) { + let moved = value.saturating_sub(before.get(&name).copied().unwrap_or(0)); + if moved > 0 { + *into.entry(name).or_default() += moved; + } + } +} + +impl Samples { + fn add_counts(&mut self, before: &WorkCounts, after: &WorkCounts) { + add_moved(&mut self.counts, before, after); + } + + fn print(mut self, name: &str, shape: &Shape, device: &str) { + self.per_dispatch.sort_by(f64::total_cmp); + println!( + "CHAIN {name} dispatches {} groups {} threads {} gpu_us_per_dispatch {:.2} least {:.2} \ + {device}", + shape.dispatches, + shape.groups, + shape.threads, + self.per_dispatch[self.per_dispatch.len() / 2], + self.per_dispatch[0], + ); + if !self.counts.is_empty() { + let runs = self.per_dispatch.len() as f64; + let line: Vec = (self.counts.iter()) + .map(|(name, sum)| format!("{name}={:.2}", *sum as f64 / runs)) + .collect(); + println!("CHAIN-COUNTS {name} {}", line.join(" ")); + } + if !self.first.is_empty() { + let line: Vec = (self.first.iter()) + .map(|(name, value)| format!("{name}={value}")) + .collect(); + println!("CHAIN-FIRST {name} {}", line.join(" ")); + } + } +} + +/// The runtime's shapes over one buffer. +struct Ours<'a> { + device: &'a Device, + state: ComputePipelineState, + words: Buffer, + readback: Buffer, +} + +impl Ours<'_> { + /// One command buffer of `shape`'s dispatches as `name` holds them, committed and waited for: + /// its GPU time per dispatch in microseconds. + fn run(&self, name: &str, shape: &Shape) -> Result { + let queue = self.device.new_command_queue()?; + let command_buffer = queue.command_buffer()?; + 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, + }; + 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()?, + }; + encoder.set_compute_pipeline_state(&self.state)?; + encoder.set_buffer(Some(&self.words), 0, 0)?; + for _ in 0..shape.dispatches / encoders { + encoder.dispatch_threadgroups(groups, threads)?; + } + encoder.end_encoding()?; + } + command_buffer.commit()?; + 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()); + } + let gpu = command_buffer.gpu_end_time()? - command_buffer.gpu_start_time()?; + Ok(gpu * 1e6 / f64::from(shape.dispatches)) + } + + /// 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)?; + let mut samples = Samples::default(); + for run in 0..=shape.runs { + let before = self.device.work_counts(); + let per = self.run(name, shape)?; + match run { + 0 => add_moved(&mut samples.first, &before, &self.device.work_counts()), + _ => { + samples.per_dispatch.push(per); + samples.add_counts(&before, &self.device.work_counts()); + } + } + } + if name != "concurrent" { + self.check(shape.dispatches * (shape.runs as u32 + 1), name)?; + } + samples.print(name, shape, device); + Ok(()) + } + + fn fill(&self, value: u8) -> Result<()> { + let queue = self.device.new_command_queue()?; + let command_buffer = queue.command_buffer()?; + let mut blit = command_buffer.blit_command_encoder()?; + blit.fill_buffer(&self.words, 0..self.words.length(), value)?; + blit.end_encoding()?; + command_buffer.commit()?; + command_buffer + .wait_until_completed_for(WAIT) + .map_err(|_| "the fill did not complete")?; + Ok(()) + } + + /// Copy the words back and check each is `want`. + fn check(&self, want: u32, name: &str) -> Result<()> { + let queue = self.device.new_command_queue()?; + let command_buffer = queue.command_buffer()?; + let mut blit = command_buffer.blit_command_encoder()?; + blit.copy_from_buffer_to_buffer(&self.words, 0, &self.readback, 0, self.words.length())?; + blit.end_encoding()?; + command_buffer.commit()?; + command_buffer + .wait_until_completed_for(WAIT) + .map_err(|_| "the read back did not complete")?; + let contents = self.readback.contents().ok_or("no contents")?; + for at in 0..(self.words.length() / 4) as usize { + // SAFETY: `readback` is `Shared`, as long as `words`, and no command buffer writes it + // while the CPU reads it. + let word = unsafe { contents.as_ptr().cast::().add(at).read_volatile() }; + if word != want { + return Err(format!("{name}: word {at} is {word}, not {want}").into()); + } + } + Ok(()) + } +} + +/// The raw shapes' Vulkan objects, on a `VkDevice` of their own over the runtime device's +/// physical device, whose instance they borrow. +struct Raw<'a> { + _runtime: &'a Device, + vk: ash::Device, + queue: vk::Queue, + pool: vk::CommandPool, + commands: Vec, + layout: vk::PipelineLayout, + set_layout: vk::DescriptorSetLayout, + descriptors: vk::DescriptorPool, + set: vk::DescriptorSet, + module: vk::ShaderModule, + pipeline: vk::Pipeline, + buffers: [(vk::Buffer, vk::DeviceMemory); 2], + bytes: u64, + mapped: *const u32, + queries: vk::QueryPool, + fence: vk::Fence, + period: f64, +} + +/// The least barrier between dispatches, a read after a write. +fn least() -> vk::MemoryBarrier<'static> { + vk::MemoryBarrier::default() + .src_access_mask(vk::AccessFlags::SHADER_WRITE) + .dst_access_mask(vk::AccessFlags::SHADER_READ | vk::AccessFlags::SHADER_WRITE) +} + +impl<'a> Raw<'a> { + /// The objects, on a `VkDevice` made with one queue of the runtime device's primary family. + fn new(device: &'a Device, shape: &Shape) -> Result> { + // SAFETY: the handles are used while the runtime device lives (the result borrows it), + // and none of the runtime's objects is destroyed. + let handles = unsafe { device.raw() }; + let family = handles.queue_family; + let priorities = [1.0f32]; + let queues = [vk::DeviceQueueCreateInfo::default() + .queue_family_index(family) + .queue_priorities(&priorities)]; + // SAFETY: the instance's own physical device and a valid creation; the device is + // destroyed in `drop`, before the instance (which the runtime device holds) goes. + let vk = unsafe { + handles.instance.create_device( + handles.physical_device, + &vk::DeviceCreateInfo::default().queue_create_infos(&queues), + None, + ) + }?; + // SAFETY: the family and index were created. + let queue = unsafe { vk.get_device_queue(family, 0) }; + let text = SPIRV.replace("{T}", &shape.threads.to_string()); + let bytes = tool( + "spirv-as", + &["--target-env", "vulkan1.2", "-o", "-", "-"], + &text, + )?; + let code: Vec = (bytes.as_chunks::<4>().0.iter()) + .map(|word| u32::from_le_bytes(*word)) + .collect(); + let properties = + // SAFETY: the instance's own physical device. + unsafe { handles.instance.get_physical_device_properties(handles.physical_device) }; + let memory = + // SAFETY: as above. + unsafe { handles.instance.get_physical_device_memory_properties(handles.physical_device) }; + // SAFETY: every info below is valid and lives for its call; every object is of `vk`. + // Objects made before a failure here are not destroyed: the example ends on it. + unsafe { + let make_buffer = + |bytes: u64, usage, flags| -> Result<(vk::Buffer, vk::DeviceMemory)> { + let buffer = vk.create_buffer( + &vk::BufferCreateInfo::default().size(bytes).usage(usage), + None, + )?; + let requirements = vk.get_buffer_memory_requirements(buffer); + let index = (0..memory.memory_type_count) + .find(|&index| { + requirements.memory_type_bits & (1 << index) != 0 + && memory.memory_types[index as usize] + .property_flags + .contains(flags) + }) + .ok_or("no memory type for the buffer")?; + let allocation = vk.allocate_memory( + &vk::MemoryAllocateInfo::default() + .allocation_size(requirements.size) + .memory_type_index(index), + None, + )?; + vk.bind_buffer_memory(buffer, allocation, 0)?; + Ok((buffer, allocation)) + }; + let bytes = shape.words() * 4; + let words = make_buffer( + bytes, + vk::BufferUsageFlags::STORAGE_BUFFER + | vk::BufferUsageFlags::TRANSFER_SRC + | vk::BufferUsageFlags::TRANSFER_DST, + vk::MemoryPropertyFlags::DEVICE_LOCAL, + )?; + let readback = make_buffer( + bytes, + vk::BufferUsageFlags::TRANSFER_DST, + vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, + )?; + let mapped = vk + .map_memory(readback.1, 0, bytes, vk::MemoryMapFlags::empty())? + .cast::(); + let binding = [vk::DescriptorSetLayoutBinding::default() + .binding(0) + .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) + .descriptor_count(1) + .stage_flags(vk::ShaderStageFlags::COMPUTE)]; + let set_layout = vk.create_descriptor_set_layout( + &vk::DescriptorSetLayoutCreateInfo::default().bindings(&binding), + None, + )?; + let layout = vk.create_pipeline_layout( + &vk::PipelineLayoutCreateInfo::default().set_layouts(&[set_layout]), + None, + )?; + let module = + vk.create_shader_module(&vk::ShaderModuleCreateInfo::default().code(&code), None)?; + let stage = vk::PipelineShaderStageCreateInfo::default() + .stage(vk::ShaderStageFlags::COMPUTE) + .module(module) + .name(c"main"); + let pipeline = vk + .create_compute_pipelines( + vk::PipelineCache::null(), + &[vk::ComputePipelineCreateInfo::default() + .stage(stage) + .layout(layout)], + None, + ) + .map_err(|(_, error)| error)?[0]; + let sizes = [vk::DescriptorPoolSize::default() + .ty(vk::DescriptorType::STORAGE_BUFFER) + .descriptor_count(1)]; + let descriptors = vk.create_descriptor_pool( + &vk::DescriptorPoolCreateInfo::default() + .max_sets(1) + .pool_sizes(&sizes), + None, + )?; + let set = vk.allocate_descriptor_sets( + &vk::DescriptorSetAllocateInfo::default() + .descriptor_pool(descriptors) + .set_layouts(&[set_layout]), + )?[0]; + let info = [vk::DescriptorBufferInfo::default() + .buffer(words.0) + .range(vk::WHOLE_SIZE)]; + vk.update_descriptor_sets( + &[vk::WriteDescriptorSet::default() + .dst_set(set) + .descriptor_type(vk::DescriptorType::STORAGE_BUFFER) + .buffer_info(&info)], + &[], + ); + let pool = vk.create_command_pool( + &vk::CommandPoolCreateInfo::default().queue_family_index(family), + None, + )?; + let commands = vk.allocate_command_buffers( + &vk::CommandBufferAllocateInfo::default() + .command_pool(pool) + .level(vk::CommandBufferLevel::PRIMARY) + .command_buffer_count(2 * shape.dispatches + 2), + )?; + let queries = vk.create_query_pool( + &vk::QueryPoolCreateInfo::default() + .query_type(vk::QueryType::TIMESTAMP) + .query_count(2), + None, + )?; + let fence = vk.create_fence(&vk::FenceCreateInfo::default(), None)?; + Ok(Raw { + _runtime: device, + vk, + queue, + pool, + commands, + layout, + set_layout, + descriptors, + set, + module, + pipeline, + buffers: [words, readback], + bytes, + mapped, + queries, + fence, + period: f64::from(properties.limits.timestamp_period), + }) + } + } + + /// Submit `commands` and wait for them. + /// + /// # Safety + /// + /// Each is recorded and executable, and none is pending. + unsafe fn submit(&self, commands: &[vk::CommandBuffer]) -> Result<()> { + // SAFETY: the caller's contract; the queue is the caller's alone. + unsafe { + self.vk.queue_submit( + self.queue, + &[vk::SubmitInfo::default().command_buffers(commands)], + self.fence, + )?; + self.vk + .wait_for_fences(&[self.fence], true, WAIT.as_nanos() as u64)?; + self.vk.reset_fences(&[self.fence])?; + } + Ok(()) + } + + /// Begin `command` for one submission. + /// + /// # Safety + /// + /// `command` is of the pool, not pending. + unsafe fn begin(&self, command: vk::CommandBuffer) -> Result<()> { + let info = vk::CommandBufferBeginInfo::default() + .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + // SAFETY: the caller's contract. + unsafe { self.vk.begin_command_buffer(command, &info) }?; + Ok(()) + } + + /// Record a dispatch of the kernel into `command`. + /// + /// # Safety + /// + /// `command` is recording. + unsafe fn dispatch(&self, command: vk::CommandBuffer, shape: &Shape) { + // SAFETY: the caller's contract; the objects are live. + unsafe { + self.vk + .cmd_bind_pipeline(command, vk::PipelineBindPoint::COMPUTE, self.pipeline); + self.vk.cmd_bind_descriptor_sets( + command, + vk::PipelineBindPoint::COMPUTE, + self.layout, + 0, + &[self.set], + &[], + ); + self.vk.cmd_dispatch(command, shape.groups, 1, 1); + } + } + + /// Record `barrier` from `src` stages to `dst` stages into `command`. + /// + /// # Safety + /// + /// `command` is recording. + unsafe fn barrier( + &self, + command: vk::CommandBuffer, + (src, dst, barrier): ( + vk::PipelineStageFlags, + vk::PipelineStageFlags, + vk::MemoryBarrier, + ), + ) { + // SAFETY: the caller's contract. + unsafe { + self.vk.cmd_pipeline_barrier( + command, + src, + dst, + vk::DependencyFlags::empty(), + &[barrier], + &[], + &[], + ); + } + } + + /// One run of `name`: its GPU time per dispatch in microseconds. + fn run(&self, name: &str, shape: &Shape) -> Result { + let compute = vk::PipelineStageFlags::COMPUTE_SHADER; + let barrier = match name { + "raw-wide" => Some(( + compute, + compute | vk::PipelineStageFlags::DRAW_INDIRECT, + vk::MemoryBarrier::default() + .src_access_mask(vk::AccessFlags::SHADER_WRITE) + .dst_access_mask( + vk::AccessFlags::SHADER_READ + | vk::AccessFlags::SHADER_WRITE + | vk::AccessFlags::UNIFORM_READ + | vk::AccessFlags::INDIRECT_COMMAND_READ, + ), + )), + "raw-none" => None, + _ => Some((compute, compute, least())), + }; + let split = name == "raw-split"; + // SAFETY: every command buffer is of the pool, none pending (each run waits for its + // submission), and the pool is reset before they are recorded again. + unsafe { + self.vk + .reset_command_pool(self.pool, vk::CommandPoolResetFlags::empty())?; + let first = self.commands[0]; + self.begin(first)?; + self.vk.cmd_reset_query_pool(first, self.queries, 0, 2); + self.vk.cmd_write_timestamp( + first, + vk::PipelineStageFlags::TOP_OF_PIPE, + self.queries, + 0, + ); + let mut used = vec![first]; + let mut current = first; + for n in 0..shape.dispatches as usize { + if split { + self.vk.end_command_buffer(current)?; + current = self.commands[1 + 2 * n]; + self.begin(current)?; + used.push(current); + } + if let (Some(barrier), true) = (barrier, n > 0) { + self.barrier(current, barrier); + } + if split { + self.vk.end_command_buffer(current)?; + current = self.commands[2 + 2 * n]; + self.begin(current)?; + used.push(current); + } + self.dispatch(current, shape); + } + self.vk.cmd_write_timestamp( + current, + vk::PipelineStageFlags::BOTTOM_OF_PIPE, + self.queries, + 1, + ); + self.vk.end_command_buffer(current)?; + self.submit(&used)?; + let mut stamps = [0u64; 2]; + self.vk.get_query_pool_results( + self.queries, + 0, + &mut stamps, + vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WAIT, + )?; + let nanos = stamps[1].wrapping_sub(stamps[0]) as f64 * self.period; + Ok(nanos / 1e3 / f64::from(shape.dispatches)) + } + } + + /// Fill the words with `value`, or copy them back. + fn transfer(&self, fill: Option) -> Result<()> { + let command = self.commands[0]; + // SAFETY: as `run`. + unsafe { + self.vk + .reset_command_pool(self.pool, vk::CommandPoolResetFlags::empty())?; + self.begin(command)?; + match fill { + Some(value) => { + self.vk + .cmd_fill_buffer(command, self.buffers[0].0, 0, vk::WHOLE_SIZE, value) + } + None => { + let to_copy = vk::MemoryBarrier::default() + .src_access_mask(vk::AccessFlags::SHADER_WRITE) + .dst_access_mask(vk::AccessFlags::TRANSFER_READ); + self.barrier( + command, + ( + vk::PipelineStageFlags::COMPUTE_SHADER, + vk::PipelineStageFlags::TRANSFER, + to_copy, + ), + ); + let region = vk::BufferCopy::default().size(self.bytes); + self.vk.cmd_copy_buffer( + command, + self.buffers[0].0, + self.buffers[1].0, + &[region], + ); + let to_host = vk::MemoryBarrier::default() + .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) + .dst_access_mask(vk::AccessFlags::HOST_READ); + self.barrier( + command, + ( + vk::PipelineStageFlags::TRANSFER, + vk::PipelineStageFlags::HOST, + to_host, + ), + ); + } + } + if fill.is_some() { + let to_compute = vk::MemoryBarrier::default() + .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) + .dst_access_mask(vk::AccessFlags::SHADER_READ | vk::AccessFlags::SHADER_WRITE); + self.barrier( + command, + ( + vk::PipelineStageFlags::TRANSFER, + vk::PipelineStageFlags::COMPUTE_SHADER, + to_compute, + ), + ); + } + self.vk.end_command_buffer(command)?; + self.submit(&[command])?; + } + Ok(()) + } +} + +impl Drop for Raw<'_> { + fn drop(&mut self) { + // SAFETY: nothing is pending (each submission was waited for), and every object is this + // example's own. + unsafe { + self.vk.destroy_fence(self.fence, None); + self.vk.destroy_query_pool(self.queries, None); + self.vk.destroy_command_pool(self.pool, None); + self.vk.destroy_descriptor_pool(self.descriptors, None); + self.vk.destroy_pipeline(self.pipeline, None); + self.vk.destroy_shader_module(self.module, None); + self.vk.destroy_pipeline_layout(self.layout, None); + self.vk.destroy_descriptor_set_layout(self.set_layout, None); + for (buffer, memory) in self.buffers { + self.vk.destroy_buffer(buffer, None); + self.vk.free_memory(memory, None); + } + self.vk.destroy_device(None); + } + } +} + +fn main() -> Result<()> { + let shape = Shape::from_args()?; + let device = Device::system_default_with(&DeviceOptions::default())?; + let name = device.name().to_string(); + println!("device: {name}"); + let bytes = shape.words() * 4; + let ours = Ours { + device: &device, + state: state(&device)?, + words: device.new_buffer(bytes, ResourceOptions::private())?, + 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)?; + } + } + let raw = Raw::new(&device, &shape)?; + for shape_name in ["raw-barrier", "raw-wide", "raw-split", "raw-none"] { + if !shape.runs(shape_name) { + continue; + } + raw.transfer(Some(0))?; + let mut samples = Samples::default(); + for run in 0..=shape.runs { + let per = raw.run(shape_name, &shape)?; + if run > 0 { + samples.per_dispatch.push(per); + } + } + if shape_name != "raw-none" { + raw.transfer(None)?; + let want = shape.dispatches * (shape.runs as u32 + 1); + for at in 0..shape.words() as usize { + // SAFETY: the mapped read-back, as long as the words, written by the copy the + // transfer waited for. + let word = unsafe { raw.mapped.add(at).read_volatile() }; + if word != want { + return Err(format!("{shape_name}: word {at} is {word}, not {want}").into()); + } + } + } + samples.print(shape_name, &shape, &name); + } + Ok(()) +} diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index 3c69bb87c..deaf6a289 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -188,7 +188,12 @@ impl CommandBuffer { /// after one was abandoned, and after commit. pub fn blit_command_encoder(&self) -> Result { let _for = self.notices_for(); - let core = EncoderCore::open(self, "blit_command_encoder", EncoderKind::Blit, true)?; + let core = EncoderCore::open( + self, + "blit_command_encoder", + EncoderKind::Blit, + (true, None), + )?; Ok(BlitCommandEncoder { core, pattern: None, diff --git a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs new file mode 100644 index 000000000..d92393d72 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs @@ -0,0 +1,159 @@ +//! A command buffer's groups of compute encoders recorded into one `VkCommandBuffer` +//! (`encoder_fold.rs`): the group its tail holds, which compute encoder joins it, its logs, and +//! the failures that fail a whole group. + +use super::{FailedEncoders, Failure, State}; +use crate::encoder_fold::{Fold, FoldEnd, FoldOrder, Joining, Stashed}; +use crate::replay::Replay; +use crate::resource::ResourceKey; +use crate::tracker::Summary; +use crate::work_counts::Counters; +use std::collections::BTreeSet; +use std::ops::Range; + +impl State { + /// The group the compute encoder opening now joins, asking `joining`, where its command + /// buffer's tail holds one it may join (`encoder_fold.rs`'s **Where**): taken, with the tail, + /// which the encoder records into. `None` where it joins none, the group left in place: the + /// encoder's open closes it once it opened ([`close_fold`](Self::close_fold)). + pub(crate) fn join_fold(&mut self, joining: Joining, trail: bool) -> Option> { + let fold = self.fold.as_ref()?; + let joins = fold.joining == joining + && self.tail == Some(fold.tail) + && self.batches.all().len() == fold.batches + && !self.batches.signals_pending() + && !self.predicated + && self.protection.options() == 0 + && !trail; + if !joins { + return None; + } + self.tail = None; + self.fold.take() + } + + /// A compute encoder ended (`end`), its last `VkCommandBuffer` the tail: it goes on in the + /// group it joined where the tail is still that group's and it leaves nothing that needs a + /// boundary, else the group closes and it begins one of its own where it may lead one (its + /// one part leaves nothing that needs a boundary, the command buffer used no command + /// predication, and its protection options are 0). Its log, which it did not keep, goes with + /// the group it ends in; the logs that come back are the caller's to give back without this + /// lock ([`close_fold`](Self::close_fold)). + pub(crate) fn fold_ended(&mut self, end: FoldEnd, counts: &Counters) -> Vec { + let FoldEnd { + joining, + fold, + encoder, + summary, + log, + } = end; + let may_lead = !self.predicated && self.protection.options() == 0; + let leads = joining.zip(summary).filter(|_| may_lead); + let mut log = log.map(|(log, executions)| Stashed { + encoder, + log, + executions, + }); + let mut unkept = Vec::new(); + if let Some(mut fold) = fold { + fold.members.end = encoder + 1; + fold.stashed.extend(log.take()); + let goes_on = self.tail == Some(fold.tail); + if let (Some((_, summary)), true) = (&leads, goes_on) { + fold.order.join(summary); + fold.batches = self.batches.all().len(); + self.fold = Some(fold); + return unkept; + } + self.fold = Some(fold); + unkept = self.close_fold(counts); + } + match (leads, self.tail) { + (Some((joining, summary)), Some(tail)) => { + self.fold = Some(Box::new(Fold { + tail, + leader: self.recorded.len() - 1, + members: encoder..encoder + 1, + batches: self.batches.all().len(), + joining, + order: FoldOrder::after(&summary), + stashed: log.into_iter().collect(), + })); + } + _ => unkept.extend(log.map(|stashed| stashed.log)), + } + unkept + } + + /// Join `worked`, the uses and fence waits of a compute encoder whose commands went into the + /// `VkCommandBuffer` of the group it joined, to the summary of that group's first part, + /// `leader`, which the batch's submission plans the group's barrier and waits by. + pub(crate) fn join_leader(&mut self, leader: usize, worked: Summary) { + if let Some(part) = self.recorded.get_mut(leader) { + part.summary.join(worked); + } + } + + /// Close the group the command buffer's tail holds, where it holds one: no encoder joins it + /// any more. Where it holds more than one encoder, each notes the group's encoders, which a + /// failure and a rebind take together (`widen_failure`, `reencode.rs`), and the logs its + /// members did not keep are kept where one member kept its own and the command buffer used no + /// command predication, so the group can be encoded again; else they come back, for the + /// caller to give back to the device's spares without this lock (`replay.rs`). + pub(crate) fn close_fold(&mut self, counts: &Counters) -> Vec { + let Some(fold) = self.fold.take() else { + return Vec::new(); + }; + let Fold { + members, stashed, .. + } = *fold; + if members.len() < 2 { + return stashed.into_iter().map(|stashed| stashed.log).collect(); + } + for record in &mut self.ended[members.clone()] { + record.group = Some(members.clone()); + } + let logged = (self.ended[members.clone()].iter()).any(|record| record.replay.is_some()); + if !logged || self.predicated { + return stashed.into_iter().map(|stashed| stashed.log).collect(); + } + let mut unkept = Vec::new(); + for Stashed { + encoder, + log, + executions, + } in stashed + { + let bytes = log.bytes(); + match self.keep_replay(encoder, Some(log), executions) { + Some(log) => unkept.push(log), + None => counts.replay_log_kept(bytes), + } + } + unkept + } + + /// `failure`, its failed encoders widened to every encoder of each group one of them lies in + /// (`encoder_fold.rs`'s **Failed**): a group's encoders record into one `VkCommandBuffer`, which + /// runs all of them or none. Unchanged where it fails no group in part. + pub(super) fn widen_failure(&self, mut failure: Failure) -> Failure { + let group = |encoder: usize| -> Option> { + self.ended + .get(encoder) + .and_then(|record| record.group.clone()) + }; + failure.encoders = match failure.encoders { + FailedEncoders::From(first) => match group(first) { + Some(group) => FailedEncoders::From(group.start), + None => FailedEncoders::From(first), + }, + FailedEncoders::Set(set) => { + let widened: BTreeSet = (set.iter()) + .flat_map(|&encoder| group(encoder).unwrap_or(encoder..encoder + 1)) + .collect(); + FailedEncoders::Set(widened) + } + }; + failure + } +} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index cbd62b782..d1a06af49 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -38,6 +38,7 @@ pub(super) mod completion; mod copies_again; pub(super) mod fences; mod first_submission; +mod fold; pub(super) mod follow; pub(super) mod gate; mod group; @@ -799,6 +800,10 @@ pub(super) struct State { /// into it as the batch ends ([`CommandBufferShared::close_tail`]), or it ends as it is where /// a later encoder joins its batch. pub(super) tail: Option, + /// The group of compute encoders whose last one's `VkCommandBuffer` is `tail`, which the next + /// compute encoder may join, recording on into it (`encoder_fold.rs`); held by that encoder + /// while it is open. + pub(super) fold: Option>, /// The batches whose end went into their last `VkCommandBuffer` (`submit.rs`): each batch's /// index, that command buffer, and whether it wrote the command buffer's end timestamp. folds: Vec, @@ -1168,6 +1173,7 @@ impl State { held: Vec::new(), unlogged: None, refused: None, + group: None, }); self.ended.len() - 1 } @@ -2479,6 +2485,7 @@ impl CommandBuffer { own_reached: 0, recorded: Revised::new(Vec::new(), &footprints.revision), tail: None, + fold: None, folds: Vec::new(), prefix: None, batches: Revised::new(Batches::default(), &footprints.revision), @@ -3561,7 +3568,9 @@ impl CommandBuffer { /// each one's kind, its place among the event waits and signals, and what it uses. A command /// buffer Metal fails from a render pass on ([`commit`](Self::commit)) fails from there too, /// whatever `failure` names, and signals no event after the pass; it completes with - /// `failure.code`. + /// `failure.code`. Differs: compute encoders recorded into one `VkCommandBuffer` + /// (`WorkCounts::encoders_folded`) fail together, so a first failed encoder or a set member + /// inside such a group fails the whole group (docs/API.md, section 10). /// /// Refused, changing nothing, as [`commit`](Self::commit) is; and for a set naming an /// encoder past the ended ones (`Invalid`, `Problem::IndexOutOfRange`, its `limit` the @@ -3769,6 +3778,12 @@ impl CommandBuffer { // a refusal that left the count behind would be a correctness question. device.shared().program_gave_gpu_work(); self.mark_gpu_written(); + // No compute encoder joins the group its tail holds from here (`encoder_fold.rs`): its + // encoders take a failure and a rebind together, and the logs it keeps for that are kept. + let unkept = self.state().close_fold(&device.shared().counts); + for log in unkept { + device.shared().scheduler.spare_logs().give(log); + } let (segments, places, failure, reached, hangs): ( Vec<(Deferred, bool)>, Vec, @@ -3889,6 +3904,9 @@ impl CommandBuffer { true => Some(Failure::revoked()), false => failure, }; + // A group of compute encoders in one `VkCommandBuffer` runs whole or not at all + // (`encoder_fold.rs`). + let failure = failure.map(|failure| state.widen_failure(failure)); // The encoders that run: all but those `failure` fails. let runs = |encoder: usize| Failure::runs(failure.as_ref(), encoder); state.committing = true; diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index e42cc712b..cb7b5d7df 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -58,6 +58,10 @@ //! and it keeps the run's scratch after its own merge where a later pass went on over it, a //! linear attachment's run's box copied in again first (`State::replaying_keeps`, recorded by //! `EncoderCore::finish_replay`). Its run's other passes are not encoded again. +//! - **Groups whole.** The compute encoders of a group recorded into one `VkCommandBuffer` +//! (`encoder_fold.rs`) are encoded again together: a rebind that moves one encodes each again, +//! into `VkCommandBuffer`s of its own, and puts them in their places together, or puts none +//! where one of them kept no log, is refused or does not fit its place. //! - **What cannot be encoded again stays as before.** An encoder whose log is gone (a compute //! encoder of a command buffer that used command predication whose unit laid a step before it //! opened, or one of its own that the unit's later encoders read, or a loop, or left work out; @@ -73,11 +77,13 @@ use crate::deferred::{Deferred, StepInputs}; use crate::encoder::{RecordedSegment, Replayed, ReplayedPart, Segment}; use crate::pass_runs::RunMerge; use crate::pipeline::budget::Urgency; +use crate::predication::Predication; use crate::replay::Replay; use crate::residency::Residency; use crate::resource::ResourceKey; use crate::texture::faces::with_faces_as_of; use crate::used_resources::EncoderKind; +use crate::work_counts::Counters; use std::collections::BTreeSet; use std::sync::atomic::Ordering; use std::sync::Arc; @@ -118,8 +124,8 @@ impl CommandBufferShared { // So are those whose pass took a rasterization-rate map since reset; one that kept no // log draws by the map as it took it, announced (`rate_mapped_pass.rs`). let mut unencoded = Vec::new(); - let moved: Vec<(usize, Arc)> = { - let state = lock(&self.state); + let units: Vec)>> = { + let mut state = lock(&self.state); match state.finished() { true => Vec::new(), false => { @@ -127,7 +133,7 @@ impl CommandBufferShared { .map(|part| part.encoder) .collect(); let submitting = device.shared().rebinds.submitting(); - (state.ended.iter().enumerate()) + let moved: Vec<(usize, Arc)> = (state.ended.iter().enumerate()) .filter(|(at, _)| open.contains(at)) .filter_map(|(at, record)| { let reset = record.taken.rate_map_reset(); @@ -140,7 +146,8 @@ impl CommandBufferShared { let moved = submitting.rebound(&record.taken) || reset; moved.then(|| (at, Arc::clone(replay))) }) - .collect() + .collect(); + state.encoded_together(moved, &device.shared().counts) } } }; @@ -150,109 +157,95 @@ impl CommandBufferShared { let handle = CommandBuffer(Arc::clone(self)); // The encoders encoded again, whose segments the encoding again recorded. let mut spliced = Vec::new(); - for (at, replay) in moved { - // A compute encoder of a command buffer that used command predication, which - // encodes again exactly, does so in its unit begun anew - // (`Predication::replaying`). - // The merges its first encoding left to runs of passes (`pass_runs.rs`): encoded again, - // it leaves them, and keeps after itself what a later pass of a run went on over. - let (residency, runs, parts) = { - let mut state = lock(&self.state); - state.replaying_predication = match state.predicated { - true => state.predication.replaying(at), - false => None, - }; - let runs: Vec> = (state.recorded.iter()) - .filter(|part| part.encoder == at) - .flat_map(|part| &part.segments) - .filter_map(|segment| match &segment.work { - Deferred::RunMerge(merge) => Some(Arc::clone(merge)), - _ => None, - }) - .collect(); - state.replaying_keeps = runs.iter().filter_map(|run| run.keep_after()).collect(); - // Its first encoding's takes of copies taken at use, taken again where they were: - // that encoding's recording is never submitted (`shadow::Takes`). - state.replaying_takes = state.ended[at].takes.clone(); - // Its parts, by which the encoding again meets the faces of the command buffer's - // turns as its first encoding met them (`texture/faces.rs`, **Encoded again**). - let mut parts = (state.recorded.iter().enumerate()) - .filter(|(_, part)| part.encoder == at) - .map(|(index, _)| index); - let first = parts.next().unwrap_or(state.recorded.len()); - let parts = first..parts.next_back().map_or(first + 1, |last| last + 1); - (state.residency_before(at, replay.kind()), runs, parts) - }; - let run = with_faces_as_of(device, (self.address(), parts), || { - replay.run(&handle, residency) - }); - { - let mut state = lock(&self.state); - state.replaying_keeps.clear(); - state.replaying_takes.clear(); + // Each unit's encoders are encoded again before any takes its place: a group of compute + // encoders recorded into one `VkCommandBuffer` takes its places whole or not at all + // (`encoder_fold.rs`). + for unit in units { + let mut again = Vec::new(); + for (at, replay) in &unit { + match self.encode_again(&handle, *at, replay) { + Some(done) => again.push(done), + None => break, + } } - // Its steps' gates listed as the commit lists the first encoding's. - let run = { - let mut state = lock(&self.state); - let state = &mut *state; - match (run, state.replaying_predication.take()) { - (Ok(replayed), Some(mut predication)) => predication - .commit(&mut state.uploads, device) - .map(|()| (replayed, Some(predication))), - (run, _) => run.map(|replayed| (replayed, None)), + if again.len() < unit.len() { + if unit.len() > 1 { + let mut state = lock(&self.state); + for (at, _) in &unit { + let record = &mut state.ended[*at]; + record.refused.get_or_insert_with(|| TOGETHER.to_owned()); + } + for _ in &again { + device.shared().counts.reencode_refused(); + } } - }; + // What the encodings held goes after the lock. + drop(again); + continue; + } let counts = &device.shared().counts; - let ((replayed, residency), predication) = match run { - Ok(replayed) => replayed, - Err(error) => { - counts.reencode_refused(); - let reset = { - let mut state = lock(&self.state); - state.ended[at].refused = Some(error.to_string()); - state.ended[at].taken.rate_map_reset() - }; - if reset { - crate::rate_mapped_pass::degrade_unencoded(device, None); - } - continue; - } - }; // What a refused splice held goes after the lock. - let spliced_now = { + let unspliced = { let mut state = lock(&self.state); - // Its residency joins what the first encoding made resident before the encoding - // again takes that one's place (`State::joined_residency`). - if residency.is_some() { - state.joined_residency(counts); + let fits = again + .iter() + .all(|done| state.splice_fits(done.at, &done.replayed)); + match fits { + true => { + for done in again.drain(..) { + // Its residency joins what the first encoding made resident before + // the encoding again takes that one's place + // (`State::joined_residency`). + if done.residency.is_some() { + state.joined_residency(counts); + } + let spliced_now = + state.splice_replay(done.at, done.replayed, done.residency); + if let (Ok(()), Some(predication)) = (&spliced_now, done.predication) { + state.predication.take_checks(predication); + } + match spliced_now { + Ok(()) => { + counts.encoder_reencoded(); + spliced.push(done.at); + for run in &done.runs { + run.leave(); + } + } + Err(unspliced) => { + counts.reencode_refused(); + state.ended[done.at].refused = Some(UNFIT.to_owned()); + drop(unspliced); + } + } + } + // Encoded again, each in `VkCommandBuffer`s of its own, the group's + // encoders share none any more. + for (at, _) in &unit { + state.ended[*at].group = None; + } + Vec::new() + } + false => { + for done in &again { + counts.reencode_refused(); + let refusal = match unit.len() { + 1 => UNFIT, + _ => TOGETHER, + }; + state.ended[done.at].refused = Some(refusal.to_owned()); + } + again + } } - let spliced = state.splice_replay(at, replayed, residency); - if let (Ok(()), Some(predication)) = (&spliced, predication) { - state.predication.take_checks(predication); - } - spliced }; - match spliced_now { - Ok(()) => { - counts.encoder_reencoded(); - spliced.push(at); - for run in &runs { - run.leave(); - } - } - Err(unspliced) => { - counts.reencode_refused(); - let refusal = "its place holds other parts or work than its encoding again's"; - let reset = { - let mut state = lock(&self.state); - state.ended[at].refused = Some(refusal.to_owned()); - state.ended[at].taken.rate_map_reset() - }; - drop(unspliced); - if reset { - crate::rate_mapped_pass::degrade_unencoded(device, None); - } - } + let reset = { + let state = lock(&self.state); + (unspliced.iter()).any(|done| state.ended[done.at].taken.rate_map_reset()) + }; + drop(unspliced); + if reset { + crate::rate_mapped_pass::degrade_unencoded(device, None); } } // Each making a spliced segment now waits for wakes the scheduler as it @@ -336,6 +329,113 @@ impl CommandBufferShared { drop(turn); device.shared().scheduler.wake(); } + + /// Encode ended encoder `at` again from `replay`, its log, on the rebind's thread (the module + /// docs), for the caller to put in its place. `None` where the encoding again is refused, the + /// refusal noted on the encoder and counted. + fn encode_again( + &self, + handle: &CommandBuffer, + at: usize, + replay: &Replay, + ) -> Option { + let device = &self.device; + // A compute encoder of a command buffer that used command predication, which + // encodes again exactly, does so in its unit begun anew + // (`Predication::replaying`). + // The merges its first encoding left to runs of passes (`pass_runs.rs`): encoded again, + // it leaves them, and keeps after itself what a later pass of a run went on over. + let (residency, runs, parts) = { + let mut state = lock(&self.state); + state.replaying_predication = match state.predicated { + true => state.predication.replaying(at), + false => None, + }; + let runs: Vec> = (state.recorded.iter()) + .filter(|part| part.encoder == at) + .flat_map(|part| &part.segments) + .filter_map(|segment| match &segment.work { + Deferred::RunMerge(merge) => Some(Arc::clone(merge)), + _ => None, + }) + .collect(); + state.replaying_keeps = runs.iter().filter_map(|run| run.keep_after()).collect(); + // Its first encoding's takes of copies taken at use, taken again where they were: + // that encoding's recording is never submitted (`shadow::Takes`). + state.replaying_takes = state.ended[at].takes.clone(); + // Its parts, by which the encoding again meets the faces of the command buffer's + // turns as its first encoding met them (`texture/faces.rs`, **Encoded again**). + let mut parts = (state.recorded.iter().enumerate()) + .filter(|(_, part)| part.encoder == at) + .map(|(index, _)| index); + let first = parts.next().unwrap_or(state.recorded.len()); + let parts = first..parts.next_back().map_or(first + 1, |last| last + 1); + (state.residency_before(at, replay.kind()), runs, parts) + }; + let run = with_faces_as_of(device, (self.address(), parts), || { + replay.run(handle, residency) + }); + { + let mut state = lock(&self.state); + state.replaying_keeps.clear(); + state.replaying_takes.clear(); + } + // Its steps' gates listed as the commit lists the first encoding's. + let run = { + let mut state = lock(&self.state); + let state = &mut *state; + match (run, state.replaying_predication.take()) { + (Ok(replayed), Some(mut predication)) => predication + .commit(&mut state.uploads, device) + .map(|()| (replayed, Some(predication))), + (run, _) => run.map(|replayed| (replayed, None)), + } + }; + match run { + Ok(((replayed, residency), predication)) => Some(EncodedAgain { + at, + replayed, + residency, + predication, + runs, + }), + Err(error) => { + device.shared().counts.reencode_refused(); + let reset = { + let mut state = lock(&self.state); + state.ended[at].refused = Some(error.to_string()); + state.ended[at].taken.rate_map_reset() + }; + if reset { + crate::rate_mapped_pass::degrade_unencoded(device, None); + } + None + } + } + } +} + +/// Why an encoder encoded again keeps its first recording where its place holds other parts or +/// work than its encoding again's. +const UNFIT: &str = "its place holds other parts or work than its encoding again's"; + +/// Why an encoder of a group of compute encoders recorded into one `VkCommandBuffer` keeps its +/// first recording where the group cannot be encoded again whole (`encoder_fold.rs`). +const TOGETHER: &str = "it records into one VkCommandBuffer with compute encoders around it, \ + which are not all encoded again"; + +/// An ended encoder encoded again, for its place ([`State::splice_replay`]). +struct EncodedAgain { + /// The encoder. + at: usize, + /// What it recorded. + replayed: Replayed, + /// What it made resident. + residency: Option, + /// Its unit of command predication begun anew, whose gates its place takes. + predication: Option, + /// The runs of passes it leaves once in place. + runs: Vec>, } impl State { @@ -357,6 +457,85 @@ impl State { joined.shadows(kind == EncoderKind::Render) } + /// The units the rebind's turn encodes again of `moved`, the ended encoders it moved, with + /// their logs, in order: each encoder alone, but an encoder of a group of compute encoders + /// recorded into one `VkCommandBuffer` with every encoder of its group (`encoder_fold.rs`), + /// whose shared recording none may leave alone. A group one of whose encoders kept no log, or + /// of a command buffer that used command predication, is encoded again by none: its moved + /// encoders keep their first recording, the refusal noted and counted. + pub(super) fn encoded_together( + &mut self, + moved: Vec<(usize, Arc)>, + counts: &Counters, + ) -> Vec)>> { + let mut units = Vec::new(); + let mut reached = 0; + for (at, replay) in moved { + let Some(group) = self.ended[at].group.clone() else { + units.push(vec![(at, replay)]); + continue; + }; + if group.start < reached { + continue; + } + reached = group.end; + let logs: Option)>> = (group.clone()) + .map(|member| { + let log = self.ended.get(member)?.replay.as_ref()?; + Some((member, Arc::clone(log))) + }) + .collect(); + match logs.filter(|_| !self.predicated) { + Some(unit) => units.push(unit), + None => { + for record in &mut self.ended[group] { + if record.replay.is_some() { + counts.reencode_refused(); + } + record.refused.get_or_insert_with(|| TOGETHER.to_owned()); + } + } + } + } + units + } + + /// The parts of ended encoder `at`, in order. + fn parts_of(&self, at: usize) -> Vec { + (self.recorded.iter().enumerate()) + .filter(|(_, part)| part.encoder == at) + .map(|(index, _)| index) + .collect() + } + + /// Whether `replayed`, ended encoder `at` encoded again, may take its place + /// ([`splice_replay`](Self::splice_replay)). + fn splice_fits(&self, at: usize, replayed: &Replayed) -> bool { + let parts = self.parts_of(at); + let replaces = |part: &usize| { + let recorded = &self.recorded[*part]; + recorded.sparse.is_empty() + && (recorded.segments.iter()).all(|segment| { + segment.keeps_pipelines() + || segment.work.left_for_pipelines() + || segment.gpu_alone + || segment.work.joins_a_run() + || segment.work.recorded_by_an_encoding_again() + }) + }; + let unjudged = self.unjudged_parts(); + !self.finished() + && !parts.is_empty() + && parts.iter().all(|&part| part >= unjudged) + && parts.len() == replayed.parts.len() + && parts.iter().all(replaces) + && !self.unrunnable.contains(&at) + && self + .ended + .get(at) + .is_some_and(|record| record.replay.is_some()) + } + /// Put `replayed`, ended encoder `at` encoded again, and what it made resident in its place, /// before the submission of its event group: each of its parts' recordings, uses and segments /// (recorded on the GPU alone), its executions (the later encoders' and segments' places @@ -379,35 +558,10 @@ impl State { replayed: Replayed, residency: Option, ) -> Result<(), Box<(Replayed, Option)>> { - let parts: Vec = (self.recorded.iter().enumerate()) - .filter(|(_, part)| part.encoder == at) - .map(|(index, _)| index) - .collect(); - let replaces = |part: &usize| { - let recorded = &self.recorded[*part]; - recorded.sparse.is_empty() - && (recorded.segments.iter()).all(|segment| { - segment.keeps_pipelines() - || segment.work.left_for_pipelines() - || segment.gpu_alone - || segment.work.joins_a_run() - || segment.work.recorded_by_an_encoding_again() - }) - }; - let unjudged = self.unjudged_parts(); - let fits = !self.finished() - && !parts.is_empty() - && parts.iter().all(|&part| part >= unjudged) - && parts.len() == replayed.parts.len() - && parts.iter().all(replaces) - && !self.unrunnable.contains(&at) - && self - .ended - .get(at) - .is_some_and(|record| record.replay.is_some()); - if !fits { + if !self.splice_fits(at, &replayed) { return Err(Box::new((replayed, residency))); } + let parts = self.parts_of(at); let Replayed { parts: mut replayed_parts, held, diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 268e14694..c0f1002b2 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -68,6 +68,7 @@ use super::deferred::Deferred; use super::degradation::{BoundFormats, CompiledPipeline, Degradation}; use super::device::Device; use super::encoder::{EncoderCore, Replayed}; +use super::encoder_fold::Joining; use super::error::{internal, invalid, Error, IndirectRule, Problem, RuntimeGap}; use super::execution::{ExecutedPipeline, Execution}; use super::fetch_reach; @@ -269,12 +270,16 @@ impl CommandBuffer { let _for = self.notices_for(); // Metal's process ends here under some protection options (`command_buffer/protection.rs`). self.refuse_protected_encoder(call)?; - let core = EncoderCore::open( - self, - call, - EncoderKind::Compute, - dispatch_type == DispatchType::Serial, - )?; + // It logs its calls where the device has a buffer over host pages (`replay.rs`), and joins + // the group of compute encoders before it, recording into their `VkCommandBuffer`, where + // it may (`encoder_fold.rs`). + let logs = self.device().shared().rebinds.any(); + let joining = Joining { + dispatch_type, + logs, + }; + let serial = dispatch_type == DispatchType::Serial; + let core = EncoderCore::open(self, call, EncoderKind::Compute, (serial, Some(joining)))?; // It joins its command buffer's unit of command predication, carrying on the loops open // across its start, or starts the next. let carried = self.state().enter_predication(dispatch_type); @@ -296,8 +301,7 @@ impl CommandBuffer { indirect_stage_in: None, residency: self.inherited_residency(false), captures: Captures::carried(carried), - log: (self.device().shared().rebinds.any()) - .then(|| self.device().shared().scheduler.spare_logs().compute()), + log: logs.then(|| self.device().shared().scheduler.spare_logs().compute()), dispatches: 0, // The bind state the device's last ended compute encoder left (`compute/live.rs`). live: self.device().shared().live_dispatches.take(), diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index d849ac9a1..121b74326 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -3,7 +3,9 @@ //! //! - **Recording.** `open` allocates a primary `VkCommandBuffer` from the command buffer's pool //! and begins it; `end` ends it and appends it to the command buffer's recordings, which -//! `commit` submits in that order. +//! `commit` submits in that order. A compute encoder records on instead in the one of the +//! compute encoders before it where nothing between them needs a boundary, a barrier from their +//! commands before each of its own that needs one (`encoder_fold.rs`). //! - **Segments**. An indirect command buffer's commands may change until the command buffer is //! committed, so an encoder that executes them [`defer`](EncoderCore::defer)s them: it ends its //! `VkCommandBuffer` there and goes on in a new one, and the segment's own is recorded later @@ -46,6 +48,7 @@ use super::command_buffer::rebound_use::Unlogged; use super::command_buffer::{recording_error, CommandBuffer}; use super::deferred::{Deferred, StepInputs}; use super::degradation::NoticesFor; +use super::encoder_fold::{self, Fold, FoldEnd, Joining}; use super::error::{internal, invalid, vulkan, CommandBufferError, Error}; use super::execution::Execution; use super::fresh_unwritten::{FreshRead, FreshUnwritten}; @@ -407,6 +410,12 @@ pub(super) struct EncoderCore { /// command buffer. Not `recorded`: a pass may hold it, and what records before that pass /// goes in another before it, which leads the encoder's then. barriered: Option, + /// What a compute encoder asked, as it opened, of the group of compute encoders its command + /// buffer's tail held (`encoder_fold.rs`); `None` for any other encoder. + joining: Option, + /// The group it joined, recording on into its tail, which its group's first part holds + /// (`encoder_fold.rs`); `None` where it began a `VkCommandBuffer` of its own. + fold: Option>, /// The encoder's `VkCommandBuffer`s ended before a segment, in order. ended: Vec, /// Those of `ended` that end a piece of a segment's submission ([`cut_piece`](Self::cut_piece)). @@ -654,13 +663,15 @@ impl EncoderCore { } /// Open an encoder on `command_buffer` for Metal's `call`, `ordered` when Metal runs its - /// commands in encoded order (a blit or serial compute encoder). Refused when the command + /// commands in encoded order (a blit or serial compute encoder); a compute encoder asks + /// `joining` of the group of compute encoders the command buffer's tail holds, which it joins + /// where it may, recording on into the tail (`encoder_fold.rs`). Refused when the command /// buffer is committed, has an open encoder, or has an abandoned one. pub(super) fn open( command_buffer: &CommandBuffer, call: &'static str, kind: EncoderKind, - ordered: bool, + (ordered, joining): (bool, Option), ) -> Result { // The last render encoder's end, where its call left it to the device's lowering thread. command_buffer.settle_end(); @@ -668,30 +679,44 @@ impl EncoderCore { if let Some(problem) = state.refusal() { return Err(invalid(call, problem)); } - // The pool's primary begun ahead where it holds one (`spares.rs`). - let (raw, begun) = command_buffer.encoder_primary(&mut state)?; let shared = command_buffer.device().shared(); - if !begun { - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - // SAFETY: the command buffer was just handed out of the pool, under the state lock. - unsafe { shared.vk().begin_command_buffer(raw, &begin) }.map_err(vulkan)?; - } - shared.counts.encoder_command_buffer_begun(Begun::Encoder); - if begun { - shared.counts.encoder_primary_begun_ahead(); - } - // The first encoder of a timed command buffer writes its start first (`gpu_time.rs`). - command_buffer.open_start(&mut state, raw); - // Past the encoders whose barriers the scheduler plans, a barrier from everything before - // leads the encoder's commands (the module docs). - let barriered = (state.encoders_ended() >= PLANNED_BARRIERS).then(|| { - // SAFETY: the command buffer was just begun, outside a render pass, under the state - // lock; only this encoder records it. - unsafe { Barrier::everything().record(shared.vk(), raw) }; - shared.counts.encoder_barriered_at_open(); - raw - }); + let fold = joining.and_then(|joining| state.join_fold(joining, shared.encoder_trail)); + let (raw, barriered) = match &fold { + Some(fold) => { + shared.counts.encoder_folded(); + (fold.tail, None) + } + None => { + // The pool's primary begun ahead where it holds one (`spares.rs`). + let (raw, begun) = command_buffer.encoder_primary(&mut state)?; + if !begun { + let begin = vk::CommandBufferBeginInfo::default() + .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); + // SAFETY: the command buffer was just handed out of the pool, under the state + // lock. + unsafe { shared.vk().begin_command_buffer(raw, &begin) }.map_err(vulkan)?; + } + shared.counts.encoder_command_buffer_begun(Begun::Encoder); + if begun { + shared.counts.encoder_primary_begun_ahead(); + } + // The first encoder of a timed command buffer writes its start first + // (`gpu_time.rs`). + command_buffer.open_start(&mut state, raw); + // Past the encoders whose barriers the scheduler plans, a barrier from everything + // before leads the encoder's commands (the module docs). + let barriered = (state.encoders_ended() >= PLANNED_BARRIERS).then(|| { + // SAFETY: the command buffer was just begun, outside a render pass, under the + // state lock; only this encoder records it. + unsafe { Barrier::everything().record(shared.vk(), raw) }; + shared.counts.encoder_barriered_at_open(); + raw + }); + (raw, barriered) + } + }; + // A group of compute encoders it did not join takes no encoder from here. + let unkept = state.close_fold(&shared.counts); state.encoder_open = true; // Made under the protection options set now (`command_buffer/protection.rs`). state.protected_made(); @@ -701,11 +726,10 @@ impl EncoderCore { let carry = state.shadows_to_carry(); let routes = state.routes.carried(); drop(state); - command_buffer - .device() - .shared() - .identifiers - .encoder_opened(kind); + for log in unkept { + shared.scheduler.spare_logs().give(log); + } + shared.identifiers.encoder_opened(kind); Ok(EncoderCore { open: OpenGuard { command_buffer: command_buffer.clone(), @@ -715,6 +739,8 @@ impl EncoderCore { recorded: false, pass: None, barriered, + joining, + fold, ended: Vec::new(), piece_ends: Vec::new(), segments: Vec::new(), @@ -879,6 +905,8 @@ impl EncoderCore { recorded: false, pass: None, barriered: None, + joining: None, + fold: None, ended: Vec::new(), piece_ends: Vec::new(), segments: Vec::new(), @@ -1266,12 +1294,39 @@ impl EncoderCore { /// begun, which goes before the pass's; the open gather runs record into it first /// ([`gather`](Self::gather)). `None` where none can be made, which abandons the command /// buffer (as a failure to end one does, [`defer`](Self::defer)). + /// + /// In an encoder that joined a group of compute encoders (`encoder_fold.rs`), whose commands + /// record here without the order each command takes after the group's earlier encoders + /// ([`track`](Self::track)), a barrier from everything of theirs not yet ordered to + /// everything after goes first. fn recording(&mut self) -> Option { + let raw = self.recording_ordered()?; + self.order_after_fold(raw); + Some(raw) + } + + /// [`recording`](Self::recording) for a command [`track`](Self::track) ordered after the + /// group of compute encoders the encoder joined. + fn recording_ordered(&mut self) -> Option { let raw = self.raw_recording()?; self.record_gathers(raw); Some(raw) } + /// Record into `raw` the barrier from everything the earlier encoders of the group the + /// encoder joined did, not yet ordered, to everything after (`FoldOrder::everything`). + fn order_after_fold(&mut self, raw: vk::CommandBuffer) { + let Some(fold) = self.fold.as_mut() else { + return; + }; + let Some(barrier) = fold.order.everything() else { + return; + }; + // SAFETY: as in `barrier`. + unsafe { barrier.record(self.open.command_buffer.device().shared().vk(), raw) }; + fold.order.ordered(barrier); + } + /// [`recording`](Self::recording) before the open gather runs record into it. fn raw_recording(&mut self) -> Option { if self.raw == vk::CommandBuffer::null() { @@ -1455,7 +1510,7 @@ impl EncoderCore { let Some(barrier) = self.track(stages, uses, (resident, reach), reads) else { return; }; - let Some(raw) = self.recording() else { + let Some(raw) = self.recording_ordered() else { return; }; let device = self.open.command_buffer.device().shared().vk(); @@ -1513,6 +1568,18 @@ impl EncoderCore { self.shadows.wrote(tracked); self.open.command_buffer.note_dirty(tracked); let barrier = self.uses.order(stages, tracked, reach); + // After the earlier encoders of the group it joined, as the tracker orders two encoders + // of a batch (`encoder_fold.rs`). + let barrier = match self.fold.as_mut() { + Some(fold) => { + let joined = encoder_fold::joined(barrier, fold.order.barrier(tracked)); + if let Some(joined) = joined { + fold.order.ordered(joined); + } + joined + } + None => barrier, + }; if barrier.is_some() { self.device().shared().counts.command_barrier(); } @@ -3014,14 +3081,20 @@ impl EncoderCore { } Some(_) => None, }; - // A log not kept goes back to the device's spares (`replay.rs`). + // A log not kept goes back to the device's spares (`replay.rs`); a compute encoder's + // waits for its end, which keeps it where the encoder is in a group of compute encoders + // that may be encoded again (`encoder_fold.rs`). + let mut held_log = None; let replay = replay.and_then(|log| { let keeps = self.segments.iter().all(Segment::records_again) && self.fails_command_buffer.is_none() && self.faults.is_none() && self.taken.encodes_again(); if !keeps { - self.device().shared().scheduler.spare_logs().give(log); + match self.joining.is_some() { + true => held_log = Some(log), + false => self.device().shared().scheduler.spare_logs().give(log), + } return None; } Some(log) @@ -3037,8 +3110,10 @@ impl EncoderCore { mut open, raw, barriered, + joining, + fold, mut ended, - segments, + mut segments, left_out, uses, retained, @@ -3060,6 +3135,18 @@ impl EncoderCore { .. } = self; ended.push(raw); + // The tail of the group it joined, where its commands began, is its group's first part's + // (`encoder_fold.rs`): its own `VkCommandBuffer`s are those after it, where it went on in + // one of its own. + let shared_first = fold + .as_ref() + .is_some_and(|fold| ended.first() == Some(&fold.tail)); + if shared_first { + ended.remove(0); + for segment in &mut segments { + segment.at = segment.at.saturating_sub(1); + } + } // The keys it found, for the device's next encoder (`host_aliases::Quiet`). (open.command_buffer.generation().aliases).give_quiet(aliases_quiet); let keyed = open @@ -3097,6 +3184,8 @@ impl EncoderCore { let command_buffer_id = open.command_buffer.object_id().get(); let trail = trail.map(|notes| notes.described(kind, command_buffer_id, encoder)); state.encoder_holds(encoder, uses.held().to_vec()); + // Whether it may begin or go on in a group of compute encoders (`encoder_fold.rs`). + let fails = fails_command_buffer.is_some() || faults.is_some(); match fails_command_buffer { Some(CommandBufferError::GpuHang) => { state.hang_from(encoder, open.command_buffer.device())?; @@ -3115,8 +3204,10 @@ impl EncoderCore { // One part, its executions these: a log not kept comes back, to go without the lock. let logged = replay.as_ref().map(Replay::bytes); let executed = base..base + executions.len(); - let unkept = state.keep_replay(encoder, replay, executed); - if let (Some(bytes), None) = (logged, &unkept) { + let mut unkept: Vec = (state.keep_replay(encoder, replay, executed.clone())) + .into_iter() + .collect(); + if let (Some(bytes), true) = (logged, unkept.is_empty()) { open.command_buffer .device() .shared() @@ -3154,13 +3245,32 @@ impl EncoderCore { // Its whole writes go with its first part, which records its pass's clears before its // draws; none where a command-predication record left parts out before it. let mut overwrites = (left_out == 0).then_some(overwrites); + // What a compute encoder of one part used, which the next encoder of a group of compute + // encoders it begins or goes on in orders after (`encoder_fold.rs`); and whether that + // part leaves nothing that needs a `VkCommandBuffer` of its own after it. + let mut fold_summary = None; + let mut plain = joining.is_some() && count == 1 && left_out == 0 && !fails; for (at, (raws, segments)) in parts.into_iter().enumerate() { - let summary = summaries + let mut summary = summaries .next() .ok_or_else(|| internal("an encoder's part without its summary"))?; if at > 0 { state.host_step(); } + if plain { + plain = segments.is_empty() && !summary.has_updates(); + fold_summary = plain.then(|| summary.clone()); + } + // Its uses and fence waits join its group's first part's summary, whose + // `VkCommandBuffer` its first commands went into; its own part keeps its fence + // updates, and, where it went on in `VkCommandBuffer`s of its own, all of them. + if let (0, true, Some(fold)) = (at, shared_first, &fold) { + let own = !raws.is_empty() || !segments.is_empty(); + let full = own.then(|| summary.clone()); + let (worked, updated) = summary.split_updates(); + state.join_leader(fold.leader, worked); + summary = full.unwrap_or(updated); + } let twin_writes = match at + 1 == count { true => twin_writes.take().unwrap_or_default(), false => Vec::new(), @@ -3187,13 +3297,26 @@ impl EncoderCore { ); } state.tail = Some(raw); + // It begins a group of compute encoders, goes on in the one it joined, or closes it + // (`encoder_fold.rs`). + if joining.is_some() { + let shared = open.command_buffer.device().shared(); + let end = FoldEnd { + joining: joining.filter(|_| !shared.encoder_trail), + fold, + encoder, + summary: fold_summary, + log: held_log.map(|log| (log, executed)), + }; + unkept.extend(state.fold_ended(end, &shared.counts)); + } state.retained.extend(retained.into_entry()); state.executions.extend(executions); if !holds.is_empty() { state.holds.push(holds); } drop(state); - if let Some(log) = unkept { + for log in unkept { let device = open.command_buffer.device(); device.shared().scheduler.spare_logs().give(log); } diff --git a/crates/metal2vulkan-runtime/src/encoder_fold.rs b/crates/metal2vulkan-runtime/src/encoder_fold.rs new file mode 100644 index 000000000..9233819f2 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/encoder_fold.rs @@ -0,0 +1,296 @@ +//! Consecutive compute encoders of one command buffer recorded into one `VkCommandBuffer`. +//! +//! Every encoder records into a primary `VkCommandBuffer` of its own (`encoder.rs`), and each +//! batch's submission puts the barrier the tracker plans before each encoder in a command buffer +//! of barriers of its own (`command_buffer/submit.rs`, `command_buffer/kept_barriers.rs`): a +//! command buffer of `N` one-dispatch compute encoders went to the queue as `2N - 1` command +//! buffers. Each boundary between command buffers costs GPU time beyond a barrier inside one +//! (`examples/dispatch_chain.rs`). A compute encoder that opens where the encoder before it +//! leaves nothing that needs a boundary records on in that encoder's `VkCommandBuffer`, the +//! command buffer's tail, and its batch's submission submits no command buffer for it. +//! +//! - **Where.** A compute encoder takes the tail where the encoder before it was a compute +//! encoder of the same dispatch type ([`Fold`], kept by the command buffer as that one ended) +//! whose recording is one part, with no work left for later (no segment), no fence update and +//! nothing that fails or faults its command buffer, in the same batch (no event or semaphore +//! wait or signal, host step or resource state encoder since: `Batches`), where the command +//! buffer used no command predication, the encoder trail is off, its protection options are 0, +//! and both encoders log their calls or neither does (`replay.rs`). So a group lies inside one +//! batch and one unit of command predication (`predication.rs`), and a fence orders nothing +//! inside it: what a later encoder waits for is updated after the group's last. Counted: +//! `WorkCounts::encoders_folded`. +//! - **The barrier between them** is recorded as the encoder records, by the rule the tracker +//! applies between two encoders of one batch: from each earlier write of a tracked resource's +//! overlapping range to a later read or write, its accesses made visible, and from each earlier +//! read to a later write, an execution dependency ([`FoldOrder`]). Each command's barrier joins +//! the one its own encoder orders it by (a serial encoder's, `tracker::EncoderUses`), in one +//! `vkCmdPipelineBarrier` with one global `VkMemoryBarrier`; encoders that share no tracked +//! resource get none, as the tracker plans none between them. A recording that bypasses that +//! per-command order (an unordered encoder's shadow copy, a memory barrier the program asks for) +//! first records one barrier from every access of the group's earlier encoders to every later +//! access ([`FoldOrder::everything`]). +//! - **Its submission.** The folded encoder's part holds no `VkCommandBuffer`, and its summary +//! holds its fence updates alone; its uses and its fence waits join the summary of the group's +//! first part, whose `VkCommandBuffer` holds them all, so what the tracker plans before that +//! part (a barrier, a wait for another queue) orders every encoder of the group after earlier +//! work. A folded encoder that leaves work for later (a dispatch whose pipelines are being +//! made, an indirect command buffer's execution) ends the shared `VkCommandBuffer` there and +//! goes on in its own, which its part holds, planned as any part is. +//! - **Encoded again** (`command_buffer/reencode.rs`). A rebind that moves a buffer one encoder of +//! a group named encodes every encoder of the group again, each into `VkCommandBuffer`s of its +//! own, or none: the shared one is never submitted. So each group member's log is held until the +//! group closes and kept for every member where one member keeps its own. A group with a member +//! that cannot be encoded again is not encoded again, and its moved members are refused. +//! - **Failed.** A failure of the command buffer that fails one encoder of a group fails every +//! encoder of it (`State::widen_failure`): a recording failure at a folded encoder's end, and +//! `CommandBuffer::commit_failed` with a set or a first failed encoder that falls inside a +//! group. A first failed encoder at a group's boundary (an encoder made under protection +//! options, which never folds, or one that is not a compute encoder) fails what it failed +//! before (docs/API.md, "A command buffer committed as failed"). + +use crate::key_hash::KeyMap; +use crate::replay::Replay; +use crate::resource::ResourceKey; +use crate::tracker::{Access, Barrier, Summary, Use, UseRange, ENTRIES_PER_KEY}; +use ash::vk; +use metal2vulkan::metal::DispatchType; +use std::hash::Hash; +use std::ops::Range; + +/// What a group's earlier encoders did to one range of one tracked resource, and what the +/// barriers recorded since ordered after it. +#[derive(Clone)] +struct Prior { + range: UseRange, + /// Their writes: empty where none wrote. + write: Access, + /// What the barriers since made those writes visible to. + visible: Access, + /// The stages they read in since the last write. + reads: vk::PipelineStageFlags2, + /// The stages the barriers since ordered after those reads. + after_reads: vk::PipelineStageFlags2, +} + +impl Prior { + /// What it holds once `other`, over a range that overlaps it, joins it over `range`: the + /// writes and reads of both, made visible and ordered only where both were. + fn absorb(&mut self, other: Prior, range: UseRange) { + self.range = range; + self.write = self.write.union(other.write); + self.visible = Access::new( + self.visible.stages & other.visible.stages, + self.visible.access & other.visible.access, + ); + self.reads |= other.reads; + self.after_reads &= other.after_reads; + } +} + +/// The order of a group's next encoder's commands after the group's earlier encoders (the module +/// docs): what those did to the tracked resources, by resource and range. +pub(crate) struct FoldOrder { + priors: KeyMap>, +} + +impl FoldOrder { + /// The order after the encoder whose summary is `summary`. + pub(crate) fn after(summary: &Summary) -> FoldOrder { + let mut order = FoldOrder { + priors: KeyMap::default(), + }; + order.join(summary); + order + } + + /// Note the next encoder of the group ended, with `summary`: its uses come after everything + /// before it in the group. A write of a range the earlier encoders used replaces what they did + /// there: a barrier ordered them before it as its commands recorded. + pub(crate) fn join(&mut self, summary: &Summary) { + for used in summary.uses() { + let priors = self.priors.entry(used.key).or_default(); + if !used.write.is_empty() { + priors.retain(|prior| !used.range.contains(&prior.range)); + } + match priors.iter_mut().find(|prior| prior.range == used.range) { + Some(prior) => { + // A read alone: no barrier orders it yet after anything. + prior.reads |= used.read.stages; + prior.after_reads = vk::PipelineStageFlags2::NONE; + } + None => priors.push(Prior { + range: used.range.clone(), + write: used.write, + visible: Access::NONE, + reads: used.read.stages, + after_reads: vk::PipelineStageFlags2::NONE, + }), + } + if priors.len() > ENTRIES_PER_KEY { + coalesce(priors); + } + } + } + + /// The barrier a command with `uses` needs after the group's earlier encoders: from a write + /// of an overlapping range of a tracked resource not yet visible to the command's read or + /// write of it, and from a read of one not yet ordered before its write, as the tracker + /// plans between two parts of a batch (`tracker::Entry::depend`). `None` where it needs none. + pub(crate) fn barrier(&self, uses: &[Use]) -> Option { + let mut barrier = Barrier::default(); + let mut add = |src: Access, dst: Access| { + barrier.src = barrier.src.union(src); + barrier.dst = barrier.dst.union(dst); + }; + for used in uses + .iter() + .filter(|used| used.tracked && !used.is_nothing()) + { + let Some(priors) = self.priors.get(&used.key) else { + continue; + }; + for prior in priors + .iter() + .filter(|prior| prior.range.overlaps(&used.range)) + { + let written = !prior.write.is_empty(); + if !used.read.is_empty() && written && !prior.visible.covers(used.read) { + add(prior.write, used.read); + } + if used.write.is_empty() { + continue; + } + if written && !prior.visible.covers(used.write) { + add(prior.write, used.write); + } + if !prior.reads.is_empty() && !prior.after_reads.contains(used.write.stages) { + add( + Access::new(prior.reads, vk::AccessFlags2::NONE), + Access::new(used.write.stages, vk::AccessFlags2::NONE), + ); + } + } + } + (!barrier.src.is_empty() && !barrier.dst.is_empty()).then_some(barrier) + } + + /// Note `barrier` recorded: it made each earlier write its source covers visible to its + /// destination, and ordered each earlier read its source stages hold before its destination + /// stages (a global memory barrier orders every command before it in its source scope). + pub(crate) fn ordered(&mut self, barrier: Barrier) { + for prior in self.priors.values_mut().flatten() { + if barrier.src.covers(prior.write) { + prior.visible = prior.visible.union(barrier.dst); + } + if barrier.src.stages.contains(prior.reads) { + prior.after_reads |= barrier.dst.stages; + } + } + } + + /// The barrier from every access of the group's earlier encoders not yet ordered to every + /// later access: what a recording that bypasses the per-command order records first. `None` + /// where none is left to order. + pub(crate) fn everything(&self) -> Option { + let all = vk::PipelineStageFlags2::ALL_COMMANDS; + let mut src = Access::NONE; + for prior in self.priors.values().flatten() { + if !prior.write.is_empty() && !prior.visible.covers(Barrier::everything().dst) { + src = src.union(prior.write); + } + if !prior.reads.is_empty() && !prior.after_reads.contains(all) { + src = src.union(Access::new(prior.reads, vk::AccessFlags2::NONE)); + } + } + (!src.is_empty()).then_some(Barrier { + src, + dst: Barrier::everything().dst, + }) + } +} + +/// Merge a resource's priors into one per kind of range. +fn coalesce(priors: &mut Vec) { + let mut first = 0; + while first < priors.len() { + let mut next = first + 1; + while next < priors.len() { + match priors[first].range.hull(&priors[next].range) { + Some(range) => { + let other = priors.swap_remove(next); + priors[first].absorb(other, range); + } + None => next += 1, + } + } + first += 1; + } +} + +/// `own`, the barrier a command's encoder orders it by, joined with `fold`'s: one barrier of +/// both sources and both destinations, which orders at least what each does. +pub(crate) fn joined(own: Option, fold: Option) -> Option { + match (own, fold) { + (Some(own), Some(fold)) => Some(Barrier { + src: own.src.union(fold.src), + dst: own.dst.union(fold.dst), + }), + (own, fold) => own.or(fold), + } +} + +/// A log of a group's member not kept by itself, held until the group closes (the module docs). +pub(crate) struct Stashed { + /// The member's place among the command buffer's ended encoders. + pub(crate) encoder: usize, + pub(crate) log: Replay, + /// Its executions' place among the command buffer's. + pub(crate) executions: Range, +} + +/// What a compute encoder asks of the group its command buffer's tail may hold, as it opens: its +/// dispatch type, and whether it logs its calls (`replay.rs`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Joining { + pub(crate) dispatch_type: DispatchType, + pub(crate) logs: bool, +} + +/// The group of compute encoders whose last ended one's `VkCommandBuffer` is its command buffer's +/// tail and may take the next compute encoder (the module docs): kept by the command buffer +/// between encoders, held by the encoder that joined it while it is open. +pub(crate) struct Fold { + /// The tail: the group's shared `VkCommandBuffer`, the last of its first part's. + pub(crate) tail: vk::CommandBuffer, + /// The part whose last `VkCommandBuffer` is the tail: the group's first part, whose summary + /// its later encoders' uses join. + pub(crate) leader: usize, + /// The group's encoders, by their places among the command buffer's ended encoders. + pub(crate) members: Range, + /// How many batches the command buffer had as the group's last encoder ended: a later + /// encoder joins it only in that batch. + pub(crate) batches: usize, + /// What its encoders asked as they opened: one dispatch type, and logs or none. + pub(crate) joining: Joining, + /// What its encoders did, which the next one's commands order after. + pub(crate) order: FoldOrder, + /// Its members' logs not kept by themselves. + pub(crate) stashed: Vec, +} + +/// A compute encoder's end as the group of compute encoders it begins or goes on in takes it +/// (`State::fold_ended`). +pub(crate) struct FoldEnd { + /// What it asked as it opened; `None` where no group may take it (the encoder trail is on). + pub(crate) joining: Option, + /// The group it joined, where it joined one. + pub(crate) fold: Option>, + /// Its place among its command buffer's ended encoders. + pub(crate) encoder: usize, + /// What its one part used, where that part leaves nothing that needs a `VkCommandBuffer` + /// boundary after it: no work for later, no fence update, nothing that fails or faults its + /// command buffer. `None` where it is not so. + pub(crate) summary: Option>, + /// Its log, which it did not keep, with its executions' place. + pub(crate) log: Option<(Replay, Range)>, +} diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index c9307abd4..d35d5351b 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -94,6 +94,7 @@ mod dynamic_library; mod dynamic_state; mod enables; mod encoder; +mod encoder_fold; mod encoder_trail; mod error; mod etc; diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index c4b126cc1..106f694a3 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -2302,7 +2302,7 @@ impl CommandBuffer { }; // A refusal past here leaves the secondary command buffer unused, freed with the pool. let mut core = match again { - None => EncoderCore::open(self, CALL, EncoderKind::Render, false)?, + None => EncoderCore::open(self, CALL, EncoderKind::Render, (false, None))?, Some(_) => EncoderCore::replaying(self, false)?, } .boxed(); diff --git a/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs b/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs new file mode 100644 index 000000000..9d8121e5e --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/encoder_fold.rs @@ -0,0 +1,480 @@ +//! Consecutive compute encoders of one command buffer recorded into one `VkCommandBuffer` +//! (`encoder_fold.rs`): which encoders join a group and what ends one, the barrier the tracker's +//! rule records between two encoders of a group, a failure that fails a group whole, and a rebind +//! that encodes a group again whole. +//! +//! [`dependent_encoders_of_a_group_read_what_the_encoders_before_them_wrote`] is the barrier's +//! check: each small encoder reads the tail of the large write the encoder before it made, which +//! a GPU that overlaps two dispatches with no barrier between them may read before it is written. +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The kernel is `scale_and_offset` of the +//! owned fixture `validation/fixtures/public/examples/runtime_examples.ll` +//! (`output[i] = input[i] * scale + i`), with a scale of 1. + +use super::blit_holds::{device, Scratch, WAIT}; +use super::dispatch_pending::state; +use super::encoder_holds::words_of; +use super::rebind_behind_a_wait::{Page, BYTES}; +use crate::{ + Buffer, CommandBuffer, CommandBufferError, CommandBufferStatus, CommitFailure, + ComputePipelineState, Device, Error, EventRef, FailedEncoders, ResourceOptions, Size, + WorkCounts, +}; +use metal2vulkan::metal::DispatchType; +use std::collections::BTreeSet; + +/// The words of a large write: threadgroups enough that a GPU runs them in many waves. +const LARGE: u64 = 1 << 20; + +/// The words of a small read: one threadgroup. +const SMALL: u64 = 64; + +/// The threads of a threadgroup. +const GROUP: u64 = 64; + +/// The large writes of the chain: each word of the `k`th's is `(k + 1) * i`, below `2^24`, so +/// every float is exact. +const STEPS: u64 = 12; + +/// The byte a blit encoder fills with. +const FILL: u8 = 0x5a; + +/// A `Shared` buffer of `words` floats, word `i` `value(i)`. +fn floats(device: &Device, words: u64, value: impl Fn(u64) -> f32) -> Buffer { + let bytes: Vec = (0..words).flat_map(|i| value(i).to_le_bytes()).collect(); + device + .new_buffer_with_bytes(&bytes, ResourceOptions::shared()) + .unwrap() +} + +/// The floats of `buffer`, a host-visible buffer no command writes now. +fn read(buffer: &Buffer) -> Vec { + words_of(buffer).into_iter().map(f32::from_bits).collect() +} + +/// `words` floats, word `i` `value(i)`. +fn expected(words: u64, value: impl Fn(u64) -> u64) -> Vec { + (0..words).map(|i| value(i) as f32).collect() +} + +/// The device, the kernel's state and its scale of 1. +struct Kernel { + device: Device, + state: ComputePipelineState, + scale: Buffer, +} + +impl Kernel { + fn new(scratch: &Scratch) -> Kernel { + let device = device(&scratch.0); + let state = state(&device); + let scale = device + .new_buffer_with_bytes(&1f32.to_le_bytes(), ResourceOptions::shared()) + .unwrap(); + Kernel { + device, + state, + scale, + } + } + + /// An encoder of `dispatch_type` of one dispatch over `words` threads, reading `input` from + /// byte `offset` on and writing `output`, ended. + fn dispatch( + &self, + command_buffer: &CommandBuffer, + dispatch_type: DispatchType, + (input, offset): (&Buffer, u64), + (output, words): (&Buffer, u64), + ) { + let mut encoder = command_buffer + .compute_command_encoder_with_dispatch_type(dispatch_type) + .unwrap(); + encoder.set_compute_pipeline_state(&self.state).unwrap(); + encoder.set_buffer(Some(input), offset, 0).unwrap(); + encoder.set_buffer(Some(output), 0, 1).unwrap(); + encoder.set_buffer(Some(&self.scale), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(words, 1, 1), Size::new(GROUP, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + } + + /// Commit `command_buffer` and wait for it: it completes with no error. + fn run(&self, command_buffer: &CommandBuffer) { + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!( + command_buffer.status(), + CommandBufferStatus::Completed, + "{:?}", + command_buffer.error() + ); + } +} + +/// What moved of the counts the groups name, from `before` to `after`. +#[derive(Debug, PartialEq, Eq)] +struct Moved { + /// `encoders_folded`. + folded: u64, + /// `command_buffers_begun_encoders`. + begun: u64, + /// `command_barriers`. + barriers: u64, +} + +impl Moved { + fn of(before: &WorkCounts, after: &WorkCounts) -> Moved { + Moved { + folded: after.encoders_folded - before.encoders_folded, + begun: after.command_buffers_begun_encoders - before.command_buffers_begun_encoders, + barriers: after.command_barriers - before.command_barriers, + } + } +} + +/// A chain of `STEPS` large writes, each from the buffer the one before wrote into the other, +/// each followed by a small read of the tail of what it wrote, each one encoder: one group of +/// `2 * STEPS` encoders in one `VkCommandBuffer`, each small read after a barrier from the large +/// write before it, and every word what the chain computes. +#[test] +fn dependent_encoders_of_a_group_read_what_the_encoders_before_them_wrote() { + let scratch = Scratch::new("fold-chain"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let tail = (LARGE - SMALL) * 4; + let large = [ + floats(device, LARGE, |_| 0.0), + floats(device, LARGE, |_| 0.0), + ]; + let small: Vec = (0..STEPS).map(|_| floats(device, SMALL, |_| 0.0)).collect(); + // Warm, over buffers of its own: the shapes' pipelines are made, so the chain below records + // each dispatch at once, leaving no segment that would end the group. + let warm = [ + floats(device, LARGE, |_| 0.0), + floats(device, LARGE, |_| 0.0), + floats(device, SMALL, |_| 0.0), + ]; + let command_buffer = queue.command_buffer().unwrap(); + let serial = DispatchType::Serial; + kernel.dispatch(&command_buffer, serial, (&warm[0], 0), (&warm[1], LARGE)); + kernel.dispatch(&command_buffer, serial, (&warm[1], tail), (&warm[2], SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for k in 0..STEPS as usize { + let (from, to) = (&large[k % 2], &large[(k + 1) % 2]); + kernel.dispatch(&command_buffer, serial, (from, 0), (to, LARGE)); + kernel.dispatch(&command_buffer, serial, (to, tail), (&small[k], SMALL)); + } + kernel.run(&command_buffer); + let moved = Moved::of(&before, &device.work_counts()); + // The words first: what a missing barrier changes. + let wrong: Vec<(u64, usize)> = (small.iter().enumerate()) + .map(|(k, small)| { + let k = k as u64; + let value = |j| (k + 1) * (LARGE - SMALL + j) + j; + let read = read(small); + let wanted = expected(SMALL, value); + (k, read.iter().zip(&wanted).filter(|(a, b)| a != b).count()) + }) + .filter(|&(_, wrong)| wrong > 0) + .collect(); + let last = &large[(STEPS % 2) as usize]; + let wrong_last = (read(last).iter().zip(expected(LARGE, |i| STEPS * i))) + .filter(|(a, b)| *a != b) + .count(); + println!("FOLD-CHAIN {moved:?} small reads wrong (write, words) {wrong:?} last write's words wrong {wrong_last}"); + assert_eq!( + (wrong, wrong_last), + (Vec::new(), 0), + "the small reads read what the large writes before them wrote" + ); + let encoders = 2 * STEPS; + assert_eq!( + (moved.folded, moved.begun), + (encoders - 1, 1), + "every encoder after the first joined the first's group: {moved:?}" + ); + assert!( + moved.barriers >= STEPS, + "each small read waits for the large write before it: {moved:?}" + ); +} + +/// Encoders that read one buffer and each write a buffer of its own share no written resource: +/// one group with no barrier inside it. +#[test] +fn encoders_that_share_no_written_resource_record_no_barrier_between_them() { + let scratch = Scratch::new("fold-apart"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let input = floats(device, SMALL, |i| i as f32); + let outputs: Vec = (0..8).map(|_| floats(device, SMALL, |_| 0.0)).collect(); + let warm = floats(device, SMALL, |_| 0.0); + let serial = DispatchType::Serial; + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm, SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for output in &outputs { + kernel.dispatch(&command_buffer, serial, (&input, 0), (output, SMALL)); + } + kernel.run(&command_buffer); + let moved = Moved::of(&before, &device.work_counts()); + let folded = outputs.len() as u64 - 1; + assert_eq!( + moved, + Moved { + folded, + begun: 1, + barriers: 0 + } + ); + for output in &outputs { + assert_eq!(read(output), expected(SMALL, |i| 2 * i)); + } +} + +/// A group holds encoders of one dispatch type: a serial encoder after a concurrent one, or a +/// concurrent one after a serial one, begins a group of its own. +#[test] +fn a_change_of_dispatch_type_begins_a_group() { + let scratch = Scratch::new("fold-types"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let input = floats(device, SMALL, |i| i as f32); + let (serial, concurrent) = (DispatchType::Serial, DispatchType::Concurrent); + let types = [serial, serial, concurrent, concurrent, serial]; + let outputs: Vec = (types.iter()) + .map(|_| floats(device, SMALL, |_| 0.0)) + .collect(); + let warm = floats(device, SMALL, |_| 0.0); + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm, SMALL)); + kernel.dispatch(&command_buffer, concurrent, (&input, 0), (&warm, SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for (&dispatch_type, output) in types.iter().zip(&outputs) { + kernel.dispatch(&command_buffer, dispatch_type, (&input, 0), (output, SMALL)); + } + kernel.run(&command_buffer); + let moved = Moved::of(&before, &device.work_counts()); + assert_eq!((moved.folded, moved.begun), (2, 3), "{moved:?}"); + for output in &outputs { + assert_eq!(read(output), expected(SMALL, |i| 2 * i)); + } +} + +/// An encoder that updates a fence ends its group, so a fence orders nothing inside one: the +/// encoder that waits for it begins a group of its own, which the encoder after it joins. +#[test] +fn a_fence_update_ends_a_group() { + let scratch = Scratch::new("fold-fence"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let input = floats(device, SMALL, |i| i as f32); + let buffers: Vec = (0..3).map(|_| floats(device, SMALL, |_| 0.0)).collect(); + let fence = device.new_fence(); + let warm = floats(device, SMALL, |_| 0.0); + let serial = DispatchType::Serial; + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm, SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&kernel.state).unwrap(); + encoder.set_buffer(Some(&input), 0, 0).unwrap(); + encoder.set_buffer(Some(&buffers[0]), 0, 1).unwrap(); + encoder.set_buffer(Some(&kernel.scale), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(SMALL, 1, 1), Size::new(GROUP, 1, 1)) + .unwrap(); + encoder.update_fence(&fence).unwrap(); + encoder.end_encoding().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.wait_for_fence(&fence).unwrap(); + encoder.set_compute_pipeline_state(&kernel.state).unwrap(); + encoder.set_buffer(Some(&buffers[0]), 0, 0).unwrap(); + encoder.set_buffer(Some(&buffers[1]), 0, 1).unwrap(); + encoder.set_buffer(Some(&kernel.scale), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(SMALL, 1, 1), Size::new(GROUP, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + kernel.dispatch( + &command_buffer, + serial, + (&buffers[1], 0), + (&buffers[2], SMALL), + ); + kernel.run(&command_buffer); + let moved = Moved::of(&before, &device.work_counts()); + assert_eq!((moved.folded, moved.begun), (1, 2), "{moved:?}"); + for (at, buffer) in buffers.iter().enumerate() { + let times = at as u64 + 2; + assert_eq!(read(buffer), expected(SMALL, |i| times * i), "buffer {at}"); + } +} + +/// Three encoders of one group, a blit encoder's fill, and a compute encoder after it, committed +/// as failed with `encoders`: which of the five ran, read from what each wrote. +fn failed_with(encoders: FailedEncoders) -> [bool; 5] { + let scratch = Scratch::new("fold-failed"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let input = floats(device, SMALL, |i| i as f32); + let outputs: Vec = (0..5).map(|_| floats(device, SMALL, |_| 0.0)).collect(); + let warm = floats(device, SMALL, |_| 0.0); + let serial = DispatchType::Serial; + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&warm, SMALL)); + kernel.run(&command_buffer); + + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for output in &outputs[..3] { + kernel.dispatch(&command_buffer, serial, (&input, 0), (output, SMALL)); + } + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(&outputs[3], 0..SMALL * 4, FILL).unwrap(); + blit.end_encoding().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&outputs[4], SMALL)); + let moved = Moved::of(&before, &device.work_counts()); + assert_eq!((moved.folded, moved.begun), (2, 3), "{moved:?}"); + let failure = CommitFailure { + code: 2, + encoders, + signals: true, + }; + command_buffer.commit_failed(failure).unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Error); + assert_eq!( + command_buffer.error(), + Some(CommandBufferError::Injected(2)) + ); + let ran = |at: usize| words_of(&outputs[at]).iter().any(|&word| word != 0); + [ran(0), ran(1), ran(2), ran(3), ran(4)] +} + +/// A failed set that names one encoder of a group fails the group whole; the encoders after it +/// run. +#[test] +fn a_failed_encoder_inside_a_group_fails_the_group() { + let set = FailedEncoders::Set(BTreeSet::from([1])); + assert_eq!(failed_with(set), [false, false, false, true, true]); +} + +/// A first failed encoder inside a group fails from the group's first encoder on. +#[test] +fn a_first_failed_encoder_inside_a_group_fails_from_the_group_s_first() { + let from = FailedEncoders::From(1); + assert_eq!(failed_with(from), [false; 5]); +} + +/// A first failed encoder at a group's boundary (an encoder that is not a compute encoder) fails +/// what it failed before: the group before it runs. +#[test] +fn a_first_failed_encoder_at_a_group_s_boundary_fails_from_there() { + let from = FailedEncoders::From(3); + assert_eq!(failed_with(from), [true, true, true, false, false]); +} + +/// A group of two encoders, the second writing a buffer over host pages, committed behind an +/// event wait only the host signals, the buffer then rebound before the signal: the rebind +/// encodes both encoders again, each into `VkCommandBuffer`s of its own, and the command buffer +/// writes the pages the buffer lies in at its submission. +#[test] +fn a_rebind_encodes_every_encoder_of_a_group_again() { + // Declared before the device, so dropped after it. + let pages = [Page::new(), Page::new()]; + let scratch = Scratch::new("fold-rebind"); + let kernel = Kernel::new(&scratch); + let device = &kernel.device; + let queue = device.new_command_queue().unwrap(); + let words = (BYTES / 4) as u64; + let input = floats(device, words, |i| i as f32); + let middle = floats(device, words, |_| 0.0); + // SAFETY: each page outlives every buffer over it (dropped after the device), and only the + // buffer's commands use it while it lives. + let made = unsafe { + device.new_buffer_with_bytes_no_copy( + pages[0].memory(), + BYTES as u64, + ResourceOptions::shared(), + None, + ) + }; + let output = match made { + Ok(buffer) => buffer, + Err(Error::Unsupported(gap)) => { + eprintln!("FOLD-REBIND: the device imports no host memory: {gap:?}"); + return; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + let serial = DispatchType::Serial; + let warm = floats(device, words, |_| 0.0); + let command_buffer = queue.command_buffer().unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&middle, words)); + kernel.dispatch(&command_buffer, serial, (&middle, 0), (&warm, words)); + kernel.run(&command_buffer); + + let gate = device.new_shared_event().unwrap(); + let before = device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + command_buffer + .encode_wait_for_event(EventRef::Shared(&gate), 1) + .unwrap(); + kernel.dispatch(&command_buffer, serial, (&input, 0), (&middle, words)); + kernel.dispatch(&command_buffer, serial, (&middle, 0), (&output, words)); + command_buffer.commit().unwrap(); + assert_eq!(output.detach_backing(), Ok(true)); + // SAFETY: as above. + unsafe { output.rebind_bytes_no_copy(pages[1].memory(), None, None) }.unwrap(); + // Read before the signal: the rebind encodes again in its own call. + let after = device.work_counts(); + gate.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!( + command_buffer.status(), + CommandBufferStatus::Completed, + "{:?}", + command_buffer.error() + ); + assert_eq!(after.encoders_folded - before.encoders_folded, 1); + assert_eq!( + ( + after.encoders_reencoded - before.encoders_reencoded, + after.reencodes_refused - before.reencodes_refused + ), + (2, 0), + "the rebind encoded both encoders of the group again" + ); + assert!( + !pages[0].written(), + "the group wrote the pages the buffer left" + ); + let written: Vec = pages[1] + .words() + .iter() + .copied() + .map(f32::from_bits) + .collect(); + assert_eq!(written, expected(words, |i| 3 * i)); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 474e75c5f..616611396 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -209,6 +209,8 @@ mod dropped_usage; mod dynamic_multi_variable; mod enables; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod encoder_fold; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod encoder_holds; mod error_kinds; mod event_listener; diff --git a/crates/metal2vulkan-runtime/src/tracker.rs b/crates/metal2vulkan-runtime/src/tracker.rs index f860801ab..8c4035305 100644 --- a/crates/metal2vulkan-runtime/src/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tracker.rs @@ -127,7 +127,7 @@ impl Access { } /// Whether every stage and access type of `other` is in this side. - fn covers(self, other: Access) -> bool { + pub(super) fn covers(self, other: Access) -> bool { self.stages.contains(other.stages) && self.access.contains(other.access) } } @@ -2264,6 +2264,40 @@ impl Summary { Summary::of_fences(fences(&self.waits), fences(&self.updates)) } + /// Whether it updates a fence. + pub(super) fn has_updates(&self) -> bool { + !self.updates.is_empty() + } + + /// Split it in two: its uses, stages and fence waits, and its fence updates alone, in its + /// stages. A compute encoder recorded into the `VkCommandBuffer` of the encoders before it + /// (`encoder_fold.rs`) joins the first to their first part's summary, where the work it + /// orders lies, and keeps the second in its own place, after theirs. + pub(super) fn split_updates(self) -> (Summary, Summary) { + let Summary { + uses, + stages, + waits, + updates, + } = self; + let updated = Summary { + uses: Vec::new(), + stages: match updates.is_empty() { + true => vk::PipelineStageFlags2::NONE, + false => stages, + }, + waits: Vec::new(), + updates, + }; + let worked = Summary { + uses, + stages, + waits, + updates: Vec::new(), + }; + (worked, updated) + } + /// The resources of the tracked uses, in order, each once per range. pub(super) fn keys(&self) -> impl Iterator + '_ { self.uses.iter().map(|used| used.key) diff --git a/crates/metal2vulkan-runtime/src/used_resources.rs b/crates/metal2vulkan-runtime/src/used_resources.rs index 0608f7e41..b9f7aa679 100644 --- a/crates/metal2vulkan-runtime/src/used_resources.rs +++ b/crates/metal2vulkan-runtime/src/used_resources.rs @@ -135,6 +135,10 @@ pub(super) struct EncoderRecord { pub(super) unlogged: Option, /// Why a rebind's encoding of it again was refused (`command_buffer/reencode.rs`). pub(super) refused: Option, + /// The places of the compute encoders whose commands one `VkCommandBuffer` holds with its + /// own, where it is one of more (`encoder_fold.rs`): a failure fails them together, and a + /// rebind encodes them again together. + pub(super) group: Option>, } /// What owns the memory under a key, held without keeping it. diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 0ccdb7727..e72c08608 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -351,6 +351,7 @@ pub(crate) struct Counters { inline_passes: AtomicU64, inline_passes_split: AtomicU64, encoders_barriered_at_open: AtomicU64, + encoders_folded: AtomicU64, kept_draws_carried: AtomicU64, kept_draws_carried_across: AtomicU64, kept_draws_carry_dropped: [AtomicU64; CarryDropped::COUNT], @@ -3461,7 +3462,8 @@ impl Counters { } /// A command of an encoder Metal orders (a blit encoder, a serial compute encoder) was - /// recorded after a barrier for the encoder's earlier commands (`tracker::EncoderUses`). + /// recorded after a barrier for the encoder's earlier commands (`tracker::EncoderUses`), or a + /// compute encoder's after one for the earlier encoders of its group (`encoder_fold.rs`). pub(crate) fn command_barrier(&self) { self.command_barriers.fetch_add(1, Ordering::Relaxed); } @@ -3473,6 +3475,12 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// A compute encoder joined the group of compute encoders before it, recording into their + /// `VkCommandBuffer` (`encoder_fold.rs`). + pub(crate) fn encoder_folded(&self) { + self.encoders_folded.fetch_add(1, Ordering::Relaxed); + } + /// A render pass's first instance began inline in a primary command buffer of its encoder's /// (`render/inline_first.rs`). pub(crate) fn inline_pass(&self) { @@ -6751,6 +6759,13 @@ pub struct WorkCounts { /// their barriers. Such a barrier orders every command of the encoder after every command /// before it, where Metal orders only those whose resources meet. pub encoders_barriered_at_open: u64, + /// Compute encoders that began no `VkCommandBuffer` of their own: each recorded into the one + /// of the compute encoders before it in its command buffer, where nothing between them needs a + /// boundary (the same batch, dispatch type and logging, no work left for later, no fence + /// update, nothing failing), after the barrier the tracker plans between two encoders of a + /// batch, and its batch's submission submits no command buffer for it, of barriers or of its + /// own. Of `encoder_command_buffers_begun`'s encoders, those it does not count. + pub encoders_folded: u64, /// Of `command_buffers_begun`, the device's own submissions' and staging submissions'. pub command_buffers_begun_internal: u64, /// Of `encoder_command_buffers_begun`, the encoders' own `VkCommandBuffer`s begun ahead: a @@ -7234,8 +7249,9 @@ pub struct WorkCounts { /// timestamp (`gpu_time.rs`): those batches start bare where nothing else is planned. pub prefixed_starts: u64, /// Barriers recorded before a command of an encoder Metal orders (a blit encoder, a serial - /// compute encoder) for the encoder's earlier commands (`tracker::EncoderUses`): on MoltenVK - /// each ends the Metal encoder, and the next waits for the one before (`tracker.rs`, + /// compute encoder) for the encoder's earlier commands (`tracker::EncoderUses`), or of a + /// compute encoder for the earlier encoders of the group it joined (`encoder_fold.rs`): on + /// MoltenVK each ends the Metal encoder, and the next waits for the one before (`tracker.rs`, /// **Inside an encoder**, orders a blit's untracked uses by key and range). pub command_barriers: u64, /// Render pass instances a pass replaced or gave up before running them (a draw that needed @@ -10748,6 +10764,7 @@ impl Device { untouched_passes_skipped: counters.untouched_passes_skipped.load(Ordering::Relaxed), inline_passes: counters.inline_passes.load(Ordering::Relaxed), encoders_barriered_at_open: counters.encoders_barriered_at_open.load(Ordering::Relaxed), + encoders_folded: counters.encoders_folded.load(Ordering::Relaxed), kept_draws_carried: counters.kept_draws_carried.load(Ordering::Relaxed), kept_draws_carried_across: counters.kept_draws_carried_across.load(Ordering::Relaxed), kept_draws_carry_dropped_between: carry_dropped(CarryDropped::Between), diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index c9874af32..de908c319 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 = 2267; +pub const RUNTIME_VERSION: u32 = 2268; /// 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 ed86bd7ee..28ccaa05a 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2938,6 +2938,7 @@ field metal2vulkan-runtime::WorkCounts.empty_memory_blocks_live pub empty_memory field metal2vulkan-runtime::WorkCounts.encoder_command_buffers_begun pub encoder_command_buffers_begun: u64 field metal2vulkan-runtime::WorkCounts.encoder_primaries_begun_ahead pub encoder_primaries_begun_ahead: u64 field metal2vulkan-runtime::WorkCounts.encoders_barriered_at_open pub encoders_barriered_at_open: u64 +field metal2vulkan-runtime::WorkCounts.encoders_folded pub encoders_folded: u64 field metal2vulkan-runtime::WorkCounts.encoders_last_draw_empty pub encoders_last_draw_empty: u64 field metal2vulkan-runtime::WorkCounts.encoders_none_kept_next_between pub encoders_none_kept_next_between: u64 field metal2vulkan-runtime::WorkCounts.encoders_none_kept_next_ends pub encoders_none_kept_next_ends: u64 diff --git a/docs/API.md b/docs/API.md index ff2eccfb8..cebd231cf 100644 --- a/docs/API.md +++ b/docs/API.md @@ -5349,6 +5349,22 @@ each item named states the rule in full. rasterization-order access) or on a device without the interlock, such as the Radeon RX 550 (the runtime's `render/snapshot.rs`, `texture/attached_reads.rs`). +**A command buffer committed as failed** (`CommandBuffer::commit_failed`) + +- **A failure inside a group of compute encoders recorded into one `VkCommandBuffer` fails the + whole group.** The runtime records a compute encoder into the `VkCommandBuffer` of the compute + encoder before it where nothing needs a boundary between them: the same dispatch type, the same + batch (no event wait or signal between them), no fence update or work left for later in the + earlier one, no command predication, the encoder trail off (`DeviceOptions::encoder_trail`) and + protection options 0 (`WorkCounts::encoders_folded` counts each). That `VkCommandBuffer` runs + whole or not at all. So a `FailedEncoders::From(n)` whose `n` lies inside such a group, and a + `FailedEncoders::Set` that names an encoder of one, run none of that group, where Metal runs the + group's encoders before `n` and those the set leaves out. A failure from an encoder on that the + runtime makes itself (a fault, a recording failure) is widened alike. A `From(n)` at a group's + boundary fails what it failed before: an `n` that names an encoder that is not a compute + encoder, one made under protection options, or the first compute encoder after another kind of + encoder, a change of dispatch type, an event wait or signal, or a fence update. + **GPU hangs and faults** (a draw of private primitive type 9, `DrawPrimitiveType::Nine`) - **A hang reads `Scheduled` 5.06 ms after its commit and completes no sooner than 27.5 ms after diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 9ed1daeb5..47bea668c 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -2191,7 +2191,9 @@ compares with Metal's. `DontCare`, a multisampled, layered or resolved pass, and the other kinds `WorkCounts::passes_not_inline_*` count). A batch begins one more before each of the first 2,048 encoders of its command buffer that needs a barrier, and none past them (`encoder.rs`, - `WorkCounts::encoders_barriered_at_open`). On ms01's Iris Xe one command buffer of 10,000 render + `WorkCounts::encoders_barriered_at_open`); a compute encoder recorded into the + `VkCommandBuffer` of the compute encoders before it takes none (`encoder_fold.rs`, + `WorkCounts::encoders_folded`). On ms01's Iris Xe one command buffer of 10,000 render passes, each a draw beside a cleared depth target, runs in 12,049 command buffers (`tests::many_passes`); one of such passes recorded inline encoded 16,173 and refused to open the next, and one of passes that take a secondary failed at the end of its 8,087th, the