Measure dispatches after one useResources in host_ab's encode workload
The steps this packet landed as, in order: - Take the compute dispatch memo while the encoder's residency is unchanged - Start a shared event listener's thread at its first notification - Add a command buffer's scheduled event signal (encodeSignalEventScheduled:value:) - Count the scheduler's passes, and measure signals, bursts and moving offsets in host_ab - Hash the pipeline memos with the runtime's key hasher - Let a dispatch take what its pipeline state last planned for the same shape - Drop two casts clippy flags in completion_here's scheduled signal check - State host_ab's dispatches taken as settled and as planned before Content: the tree of `development` at f9d39326a3, unchanged.
This commit is contained in:
1 parent
328f69c087
commit
27ad7597c1
23 files changed
+1581
-199
No files matched your search
@@ -28,6 +28,8 @@ pub trait Gpu {
|
||||
type Heap;
|
||||
type DepthStencil;
|
||||
type IndirectCommands;
|
||||
type SharedEvent;
|
||||
type Listener;
|
||||
|
||||
/// The side and the device's name.
|
||||
fn label(&self) -> String;
|
||||
@@ -264,6 +266,8 @@ pub trait Gpu {
|
||||
fn use_commands(&self, encoder: &mut Self::ComputeEncoder, commands: &Self::IndirectCommands);
|
||||
/// `useResource:usage:` of `buffer`, read and write: the executed commands bind it.
|
||||
fn use_buffer(&self, encoder: &mut Self::ComputeEncoder, buffer: &Self::Buffer);
|
||||
/// `useResources:count:usage:` of `buffers`, `MTLResourceUsageRead`.
|
||||
fn use_buffers(&self, encoder: &mut Self::ComputeEncoder, buffers: &[&Self::Buffer]);
|
||||
/// `executeCommandsInBuffer:withRange:` of commands `0..count`.
|
||||
fn execute_commands(
|
||||
&self,
|
||||
@@ -299,6 +303,41 @@ pub trait Gpu {
|
||||
fn wait(&self, command_buffer: &Self::CommandBuffer);
|
||||
/// `addCompletedHandler:`.
|
||||
fn on_completed(&self, command_buffer: &Self::CommandBuffer, handler: Box<dyn FnOnce() + Send>);
|
||||
/// `newSharedEvent`.
|
||||
fn shared_event(&self) -> Self::SharedEvent;
|
||||
/// `signaledValue`.
|
||||
fn event_value(&self, event: &Self::SharedEvent) -> u64;
|
||||
/// `addScheduledHandler:` of a handler that sets `event`'s value to `value`: how a program
|
||||
/// without `encodeSignalEventScheduled:value:` signals as the command buffer is scheduled.
|
||||
fn set_when_scheduled(
|
||||
&self,
|
||||
command_buffer: &Self::CommandBuffer,
|
||||
event: &Self::SharedEvent,
|
||||
value: u64,
|
||||
);
|
||||
/// `encodeSignalEventScheduled:value:` (Apple's private call; the runtime's
|
||||
/// `encode_signal_event_scheduled`).
|
||||
fn signal_when_scheduled(
|
||||
&self,
|
||||
command_buffer: &Self::CommandBuffer,
|
||||
event: &Self::SharedEvent,
|
||||
value: u64,
|
||||
);
|
||||
/// `[[MTLSharedEventListener alloc] init]`.
|
||||
fn listener(&self) -> Self::Listener;
|
||||
/// `notifyListener:atValue:block:` of `event`, calling `block` on the listener's thread.
|
||||
fn notify(
|
||||
&self,
|
||||
event: &Self::SharedEvent,
|
||||
listener: &Self::Listener,
|
||||
value: u64,
|
||||
block: Box<dyn FnOnce() + Send>,
|
||||
);
|
||||
/// A submission check that answers none (the runtime's `set_submission_check`, which Metal
|
||||
/// has not): whether the side has it.
|
||||
fn check_submissions(&self, _command_buffer: &Self::CommandBuffer) -> bool {
|
||||
false
|
||||
}
|
||||
/// `GPUEndTime - GPUStartTime`, in seconds, where the side measures it on the GPU.
|
||||
fn gpu_seconds(&self, command_buffer: &Self::CommandBuffer) -> Option<f64>;
|
||||
/// `kernelStartTime`, `kernelEndTime`, `GPUStartTime` and `GPUEndTime`, in seconds of the
|
||||
|
||||
@@ -20,9 +20,13 @@
|
||||
//! vertex buffer and offset, and another fragment texture), `pipeline` (as `bind`, and the
|
||||
//! pipeline state switched between two) and `passes` (as `pipeline`, in render passes of three
|
||||
//! draws, as a window server draws), and a compute encoder of as many single-threadgroup
|
||||
//! dispatches, `static` and `churn` (the pipeline state and both buffers' offsets each
|
||||
//! dispatch). Per draw and dispatch: the encoding thread's wall time from the command buffer's
|
||||
//! dispatches, `static`, `offsets` (both buffers' offsets each dispatch) and `churn` (the
|
||||
//! pipeline state and both buffers' offsets each dispatch). Per draw and dispatch: the encoding thread's wall time from the command buffer's
|
||||
//! creation through `endEncoding`, and the whole process's CPU time until the wait returned.
|
||||
//! Then `dispatch_resident_*`: as many dispatches of the tiny kernel after one
|
||||
//! `useResources:count:usage:` of 0, 1, 256 or 4096 buffers, or of one buffer 4096 times
|
||||
//! (`same_4096`); per variant the `useResources` call, and per dispatch the encoding thread's
|
||||
//! wall time after it and the process's CPU time.
|
||||
//! - `fixed`: a command buffer's creation, an encoder of one command each (render, compute,
|
||||
//! blit), and the commit call of a command buffer of 30 such encoders.
|
||||
//! - `latency`: commit to `waitUntilCompleted`'s return, and commit to the completed handler, of
|
||||
@@ -35,6 +39,19 @@
|
||||
//! read as `half` and as `float`, threadgroup float, threadgroup half) on the kernel's grid
|
||||
//! and loop. With both sides, each round also compares every kernel's output buffer after its
|
||||
//! last run between the sides, and the last table counts the 32-bit words that differ.
|
||||
//! - `signals`: a command buffer of one tiny fill with a completed handler, committed alone and
|
||||
//! waited for, as the consumer's isolated execution is: `plain`; `scheduled_handler`, with a
|
||||
//! scheduled handler that sets a shared event's value (how a program without
|
||||
//! `encodeSignalEventScheduled:value:` signals as it is scheduled); `scheduled_signal`, with that
|
||||
//! private call (the runtime's `encode_signal_event_scheduled`); and the runtime's alone,
|
||||
//! `checked`, with a submission check that answers none (`set_submission_check`). Per command
|
||||
//! buffer: commit to the completed handler, commit to the wait's return, the process's CPU time,
|
||||
//! and on the runtime's side its work counts (`rt_*`: handler-thread and scheduler wakes, and
|
||||
//! the command buffers scheduled where their last batch was submitted, the scheduler's passes).
|
||||
//! Then bursts of 64 such command buffers committed back to back, `plain` and `checked`, to
|
||||
//! the last one's completion, per command buffer. Then a shared event listener made and dropped
|
||||
//! unused, one made, and its first notification, asked for a value already reached, from the
|
||||
//! ask to the block's start.
|
||||
//! - `latency_split` (with `latency`): the same command buffers' host-clock timeline, commit to
|
||||
//! `kernelStartTime` to `kernelEndTime` to `GPUStartTime` to `GPUEndTime` to the wait's return.
|
||||
//! The runtime's GPU times on MoltenVK are the host's (its docs): its GPU start is its kernel
|
||||
@@ -142,7 +159,8 @@
|
||||
//! `--metallib PATH` (skip the compile; not with `pipeline`), `--cache DIR` (the runtime's shader
|
||||
//! cache, with `--side`), `--variants a,b,...` (the encode workload's variants alone:
|
||||
//! `draw_static`, `draw_bind`, `draw_pipeline`, `draw_passes`, `dispatch_static`,
|
||||
//! `dispatch_churn`; for a profile of one; and the memory workload's parts alone: `create`,
|
||||
//! `dispatch_offsets`, `dispatch_churn`, `dispatch_resident_0`, `_1`, `_256`, `_4096`,
|
||||
//! `_same_4096`; for a profile of one; and the memory workload's parts alone: `create`,
|
||||
//! `no_copy`, `held_1m`, `held_64m`, `texture`), `--announce-each a,b,...` (the runtime's device
|
||||
//! announces these degradation kinds, by code with or without its `metal2vulkan-degrade-` prefix,
|
||||
//! or `all` of them, at every occurrence, `DeviceOptions::announce_each`, as a consumer that hears
|
||||
@@ -166,7 +184,7 @@ use std::process::{Command, Stdio};
|
||||
use std::time::Instant;
|
||||
use workloads::Sizes;
|
||||
|
||||
const WORKLOADS: [&str; 15] = [
|
||||
const WORKLOADS: [&str; 16] = [
|
||||
"encode",
|
||||
"fixed",
|
||||
"latency",
|
||||
@@ -182,6 +200,7 @@ const WORKLOADS: [&str; 15] = [
|
||||
"burst",
|
||||
"icb",
|
||||
"icb_draws",
|
||||
"signals",
|
||||
];
|
||||
|
||||
struct Options {
|
||||
@@ -441,6 +460,7 @@ fn run<G: Gpu>(g: &G, opened: Instant, metallib: &Path, options: &Options) {
|
||||
"burst" => workloads::burst(g, &scene),
|
||||
"icb" => workloads::icb(g, &library, sizes),
|
||||
"icb_draws" => workloads::icb_draws(g, &library, sizes),
|
||||
"signals" => workloads::signals(g, &scene, sizes),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,9 +14,10 @@ use objc2_metal::{
|
||||
MTLIndexType, MTLIndirectCommandBuffer, MTLIndirectCommandBufferDescriptor,
|
||||
MTLIndirectCommandType, MTLLibrary, MTLLoadAction, MTLOrigin, MTLPipelineOption,
|
||||
MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder, MTLRenderPassDescriptor,
|
||||
MTLRenderPipelineDescriptor, MTLRenderPipelineState, MTLRenderStages, MTLResourceOptions,
|
||||
MTLResourceUsage, MTLSamplerDescriptor, MTLSamplerMinMagFilter, MTLSamplerState, MTLSize,
|
||||
MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor, MTLTextureUsage, MTLWinding,
|
||||
MTLRenderPipelineDescriptor, MTLRenderPipelineState, MTLRenderStages, MTLResource,
|
||||
MTLResourceOptions, MTLResourceUsage, MTLSamplerDescriptor, MTLSamplerMinMagFilter,
|
||||
MTLSamplerState, MTLSharedEvent, MTLSharedEventListener, MTLSize, MTLStorageMode,
|
||||
MTLStoreAction, MTLTexture, MTLTextureDescriptor, MTLTextureUsage, MTLWinding,
|
||||
};
|
||||
use std::ffi::c_void;
|
||||
use std::path::Path;
|
||||
@@ -80,6 +81,8 @@ impl Gpu for Native {
|
||||
type Heap = Object<dyn MTLHeap>;
|
||||
type DepthStencil = Object<dyn MTLDepthStencilState>;
|
||||
type IndirectCommands = Object<dyn MTLIndirectCommandBuffer>;
|
||||
type SharedEvent = Object<dyn MTLSharedEvent>;
|
||||
type Listener = Retained<MTLSharedEventListener>;
|
||||
|
||||
fn label(&self) -> String {
|
||||
format!("native Metal on {}", self.device.name())
|
||||
@@ -703,6 +706,18 @@ impl Gpu for Native {
|
||||
);
|
||||
}
|
||||
|
||||
fn use_buffers(&self, encoder: &mut Self::ComputeEncoder, buffers: &[&Self::Buffer]) {
|
||||
let resources: Vec<NonNull<ProtocolObject<dyn MTLResource>>> = buffers
|
||||
.iter()
|
||||
.map(|buffer| NonNull::from(ProtocolObject::from_ref(&***buffer)))
|
||||
.collect();
|
||||
let Some(first) = NonNull::new(resources.as_ptr().cast_mut()) else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: `first` points at `resources.len()` live resources, held by `buffers`.
|
||||
unsafe { encoder.useResources_count_usage(first, resources.len(), MTLResourceUsage::Read) };
|
||||
}
|
||||
|
||||
fn execute_commands(
|
||||
&self,
|
||||
encoder: &mut Self::ComputeEncoder,
|
||||
@@ -799,6 +814,65 @@ impl Gpu for Native {
|
||||
);
|
||||
}
|
||||
|
||||
fn shared_event(&self) -> Self::SharedEvent {
|
||||
self.device.newSharedEvent().expect("newSharedEvent")
|
||||
}
|
||||
|
||||
fn event_value(&self, event: &Self::SharedEvent) -> u64 {
|
||||
event.signaledValue()
|
||||
}
|
||||
|
||||
fn set_when_scheduled(
|
||||
&self,
|
||||
command_buffer: &Self::CommandBuffer,
|
||||
event: &Self::SharedEvent,
|
||||
value: u64,
|
||||
) {
|
||||
let event = event.clone();
|
||||
let block = RcBlock::new(move |_: NonNull<ProtocolObject<dyn MTLCommandBuffer>>| {
|
||||
event.setSignaledValue(value);
|
||||
});
|
||||
// SAFETY: the block is a valid scheduled handler, which Metal copies.
|
||||
unsafe { command_buffer.addScheduledHandler(RcBlock::as_ptr(&block)) };
|
||||
}
|
||||
|
||||
fn listener(&self) -> Self::Listener {
|
||||
MTLSharedEventListener::new()
|
||||
}
|
||||
|
||||
fn notify(
|
||||
&self,
|
||||
event: &Self::SharedEvent,
|
||||
listener: &Self::Listener,
|
||||
value: u64,
|
||||
block: Box<dyn FnOnce() + Send>,
|
||||
) {
|
||||
let block = Mutex::new(Some(block));
|
||||
let block = RcBlock::new(
|
||||
move |_: NonNull<ProtocolObject<dyn MTLSharedEvent>>, _: u64| {
|
||||
if let Some(block) = block.lock().unwrap().take() {
|
||||
block();
|
||||
}
|
||||
},
|
||||
);
|
||||
// SAFETY: the block is a valid notification block, which Metal copies.
|
||||
unsafe { event.notifyListener_atValue_block(listener, value, RcBlock::as_ptr(&block)) };
|
||||
}
|
||||
|
||||
fn signal_when_scheduled(
|
||||
&self,
|
||||
command_buffer: &Self::CommandBuffer,
|
||||
event: &Self::SharedEvent,
|
||||
value: u64,
|
||||
) {
|
||||
let event: &ProtocolObject<dyn MTLSharedEvent> = event;
|
||||
// SAFETY: `encodeSignalEventScheduled:value:` takes a shared event and a 64-bit value
|
||||
// (`v@:@Q`) and returns nothing.
|
||||
let _: () = unsafe {
|
||||
objc2::msg_send![&**command_buffer, encodeSignalEventScheduled: event, value: value]
|
||||
};
|
||||
}
|
||||
|
||||
fn on_completed(
|
||||
&self,
|
||||
command_buffer: &Self::CommandBuffer,
|
||||
|
||||
@@ -86,6 +86,8 @@ impl Gpu for Runtime {
|
||||
type Heap = rt::Heap;
|
||||
type DepthStencil = rt::DepthStencilState;
|
||||
type IndirectCommands = rt::IndirectCommandBuffer;
|
||||
type SharedEvent = rt::SharedEvent;
|
||||
type Listener = rt::SharedEventListener;
|
||||
|
||||
fn label(&self) -> String {
|
||||
format!("runtime on {}", self.device.name())
|
||||
@@ -692,6 +694,13 @@ impl Gpu for Runtime {
|
||||
.expect("use_resource");
|
||||
}
|
||||
|
||||
fn use_buffers(&self, encoder: &mut rt::ComputeCommandEncoder, buffers: &[&rt::Buffer]) {
|
||||
let resources: Vec<_> = buffers.iter().map(|buffer| buffer.as_resource()).collect();
|
||||
encoder
|
||||
.use_resources(&resources, ResourceUsage::READ)
|
||||
.expect("use_resources");
|
||||
}
|
||||
|
||||
fn execute_commands(
|
||||
&self,
|
||||
encoder: &mut rt::ComputeCommandEncoder,
|
||||
@@ -776,6 +785,58 @@ impl Gpu for Runtime {
|
||||
);
|
||||
}
|
||||
|
||||
fn shared_event(&self) -> rt::SharedEvent {
|
||||
self.device.new_shared_event().expect("new_shared_event")
|
||||
}
|
||||
|
||||
fn event_value(&self, event: &rt::SharedEvent) -> u64 {
|
||||
event.signaled_value()
|
||||
}
|
||||
|
||||
fn set_when_scheduled(
|
||||
&self,
|
||||
command_buffer: &rt::CommandBuffer,
|
||||
event: &rt::SharedEvent,
|
||||
value: u64,
|
||||
) {
|
||||
let event = event.clone();
|
||||
command_buffer
|
||||
.add_scheduled_handler(Box::new(move |_| event.set_signaled_value(value)))
|
||||
.expect("add_scheduled_handler");
|
||||
}
|
||||
|
||||
fn signal_when_scheduled(
|
||||
&self,
|
||||
command_buffer: &rt::CommandBuffer,
|
||||
event: &rt::SharedEvent,
|
||||
value: u64,
|
||||
) {
|
||||
command_buffer
|
||||
.encode_signal_event_scheduled(event, value)
|
||||
.expect("encode_signal_event_scheduled");
|
||||
}
|
||||
|
||||
fn listener(&self) -> rt::SharedEventListener {
|
||||
rt::SharedEventListener::new()
|
||||
}
|
||||
|
||||
fn notify(
|
||||
&self,
|
||||
event: &rt::SharedEvent,
|
||||
listener: &rt::SharedEventListener,
|
||||
value: u64,
|
||||
block: Box<dyn FnOnce() + Send>,
|
||||
) {
|
||||
event.notify_listener(listener, value, Box::new(move |_, _| block()));
|
||||
}
|
||||
|
||||
fn check_submissions(&self, command_buffer: &rt::CommandBuffer) -> bool {
|
||||
command_buffer
|
||||
.set_submission_check(std::sync::Arc::new(|_: &rt::Submission<'_>| None))
|
||||
.expect("set_submission_check");
|
||||
true
|
||||
}
|
||||
|
||||
fn on_completed(&self, command_buffer: &rt::CommandBuffer, handler: Box<dyn FnOnce() + Send>) {
|
||||
command_buffer
|
||||
.add_completed_handler(Box::new(move |_| handler()))
|
||||
@@ -851,6 +912,20 @@ impl Gpu for Runtime {
|
||||
("merged_draw_commands", c.merged_draw_commands),
|
||||
("indirect_records_read", c.indirect_records_read),
|
||||
("dispatches_indirect", replayed.cmd_dispatch_indirect),
|
||||
("wakes_handler_threads", c.wakes_handler_threads),
|
||||
("scheduled_where_submitted", c.scheduled_where_submitted),
|
||||
("scheduler_passes", c.scheduler_passes),
|
||||
("scheduler_sleeps", c.scheduler_sleeps),
|
||||
("scheduler_wakes_commit", c.scheduler_wakes_commit),
|
||||
("scheduler_wakes_host", c.scheduler_wakes_host),
|
||||
(
|
||||
"dispatches_settled_as_before",
|
||||
c.dispatches_settled_as_before,
|
||||
),
|
||||
(
|
||||
"dispatches_planned_as_before",
|
||||
c.dispatches_planned_as_before,
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, count)| (name, count as f64))
|
||||
|
||||
@@ -321,15 +321,17 @@ fn encode_dispatches<G: Gpu>(
|
||||
s: &Scene<G>,
|
||||
command_buffer: &G::CommandBuffer,
|
||||
dispatches: usize,
|
||||
churn: bool,
|
||||
churn: DispatchChurn,
|
||||
) {
|
||||
let mut encoder = g.compute_encoder(command_buffer);
|
||||
g.set_compute_pipeline(&mut encoder, &s.tiny[0]);
|
||||
g.set_buffer(&mut encoder, &s.tiny_out, 0, 0);
|
||||
g.set_buffer(&mut encoder, &s.tiny_values, 0, 1);
|
||||
for dispatch in 0..dispatches {
|
||||
if churn {
|
||||
if churn == DispatchChurn::Churn {
|
||||
g.set_compute_pipeline(&mut encoder, &s.tiny[dispatch % 2]);
|
||||
}
|
||||
if churn != DispatchChurn::Static {
|
||||
let offset = (dispatch % RECTS) * RECT_STRIDE;
|
||||
g.set_buffer(&mut encoder, &s.tiny_out, offset, 0);
|
||||
g.set_buffer(&mut encoder, &s.tiny_values, offset, 1);
|
||||
@@ -339,6 +341,27 @@ fn encode_dispatches<G: Gpu>(
|
||||
g.end_compute(encoder);
|
||||
}
|
||||
|
||||
/// What the encode workload's dispatches change between them.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum DispatchChurn {
|
||||
/// Nothing.
|
||||
Static,
|
||||
/// Both buffers' offsets.
|
||||
Offsets,
|
||||
/// The pipeline state and both buffers' offsets.
|
||||
Churn,
|
||||
}
|
||||
|
||||
impl DispatchChurn {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
DispatchChurn::Static => "static",
|
||||
DispatchChurn::Offsets => "offsets",
|
||||
DispatchChurn::Churn => "churn",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The CPU cost of encoding: per draw and per dispatch, on the encoding thread (wall) and in the
|
||||
/// whole process (CPU time of every thread, from the command buffer's creation until its wait
|
||||
/// returned, which takes in work moved off the encoding thread to commit or to other threads).
|
||||
@@ -391,15 +414,20 @@ pub fn encode<G: Gpu>(g: &G, s: &Scene<G>, sizes: &Sizes, variants: &[String]) {
|
||||
);
|
||||
emit("encode", &format!("draw_{name}_cb_total"), "ms", &mut total);
|
||||
}
|
||||
for churn in [false, true] {
|
||||
if !runs(format!(
|
||||
"dispatch_{}",
|
||||
if churn { "churn" } else { "static" }
|
||||
)) {
|
||||
for churn in [
|
||||
DispatchChurn::Static,
|
||||
DispatchChurn::Offsets,
|
||||
DispatchChurn::Churn,
|
||||
] {
|
||||
if !runs(format!("dispatch_{}", churn.name())) {
|
||||
continue;
|
||||
}
|
||||
let (mut wall, mut cpu, mut total) = (vec![], vec![], vec![]);
|
||||
let mut counts = None;
|
||||
for run in 0..sizes.timed + 3 {
|
||||
if run == 3 {
|
||||
counts = Some(g.work_counts());
|
||||
}
|
||||
g.pool(|| {
|
||||
let cpu0 = process_cpu();
|
||||
let t0 = Instant::now();
|
||||
@@ -417,7 +445,7 @@ pub fn encode<G: Gpu>(g: &G, s: &Scene<G>, sizes: &Sizes, variants: &[String]) {
|
||||
}
|
||||
});
|
||||
}
|
||||
let name = if churn { "churn" } else { "static" };
|
||||
let name = churn.name();
|
||||
emit(
|
||||
"encode",
|
||||
&format!("dispatch_{name}_encode"),
|
||||
@@ -436,6 +464,108 @@ pub fn encode<G: Gpu>(g: &G, s: &Scene<G>, sizes: &Sizes, variants: &[String]) {
|
||||
"ms",
|
||||
&mut total,
|
||||
);
|
||||
let dispatches = (sizes.timed * n) as f64;
|
||||
emit_memo_shares(g, counts, dispatches, &format!("dispatch_{name}"));
|
||||
}
|
||||
encode_resident(g, s, sizes, &runs);
|
||||
}
|
||||
|
||||
/// The resident buffers of the encode workload's `dispatch_resident` variants, of 256 bytes each.
|
||||
const RESIDENT: usize = 4096;
|
||||
|
||||
/// The encode workload's `dispatch_resident_*` variants: a compute encoder whose pipeline state
|
||||
/// and buffers are set, one `useResources:count:usage:` (reading) of none, 1, 256 or 4096
|
||||
/// buffers, or of one buffer 4096 times (`same_4096`), then `draws` single-threadgroup dispatches
|
||||
/// of the tiny kernel. Per variant: the `useResources` call, the encoding thread's wall time per
|
||||
/// dispatch, the process's CPU time per dispatch, and the command buffer's whole time.
|
||||
fn encode_resident<G: Gpu>(g: &G, s: &Scene<G>, sizes: &Sizes, runs: &dyn Fn(String) -> bool) {
|
||||
let variants = [
|
||||
("0", 0, false),
|
||||
("1", 1, false),
|
||||
("256", 256, false),
|
||||
("4096", 4096, false),
|
||||
("same_4096", 4096, true),
|
||||
];
|
||||
let wanted: Vec<_> = (variants.iter())
|
||||
.filter(|(name, ..)| runs(format!("dispatch_resident_{name}")))
|
||||
.collect();
|
||||
if wanted.is_empty() {
|
||||
return;
|
||||
}
|
||||
let n = sizes.draws;
|
||||
let resident: Vec<G::Buffer> = (0..RESIDENT).map(|_| g.buffer(256)).collect();
|
||||
for &&(name, count, same) in &wanted {
|
||||
let list: Vec<&G::Buffer> = match same {
|
||||
true => vec![&resident[0]; count],
|
||||
false => resident[..count].iter().collect(),
|
||||
};
|
||||
let (mut using, mut wall, mut cpu, mut total) = (vec![], vec![], vec![], vec![]);
|
||||
let mut counts = None;
|
||||
for run in 0..sizes.timed + 3 {
|
||||
if run == 3 {
|
||||
counts = Some(g.work_counts());
|
||||
}
|
||||
g.pool(|| {
|
||||
let cpu0 = process_cpu();
|
||||
let t0 = Instant::now();
|
||||
let command_buffer = g.command_buffer();
|
||||
let mut encoder = g.compute_encoder(&command_buffer);
|
||||
g.set_compute_pipeline(&mut encoder, &s.tiny[0]);
|
||||
g.set_buffer(&mut encoder, &s.tiny_out, 0, 0);
|
||||
g.set_buffer(&mut encoder, &s.tiny_values, 0, 1);
|
||||
let t1 = Instant::now();
|
||||
g.use_buffers(&mut encoder, &list);
|
||||
let t2 = Instant::now();
|
||||
for _ in 0..n {
|
||||
g.dispatch(&mut encoder, 1, 64);
|
||||
}
|
||||
let t3 = Instant::now();
|
||||
g.end_compute(encoder);
|
||||
g.commit(&command_buffer);
|
||||
g.wait(&command_buffer);
|
||||
let t4 = Instant::now();
|
||||
let cpu1 = process_cpu();
|
||||
if run >= 3 {
|
||||
using.push(us(t2 - t1));
|
||||
wall.push(us(t3 - t2) / n as f64);
|
||||
cpu.push(us(cpu1 - cpu0) / n as f64);
|
||||
total.push(ms(t4 - t0));
|
||||
}
|
||||
});
|
||||
}
|
||||
let metric = |what: &str| format!("dispatch_resident_{name}_{what}");
|
||||
emit("encode", &metric("use_call"), "us", &mut using);
|
||||
emit("encode", &metric("encode"), "us/dispatch", &mut wall);
|
||||
emit("encode", &metric("process_cpu"), "us/dispatch", &mut cpu);
|
||||
emit("encode", &metric("cb_total"), "ms", &mut total);
|
||||
let dispatches = (sizes.timed * n) as f64;
|
||||
emit_memo_shares(g, counts, dispatches, &format!("dispatch_resident_{name}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The share of `dispatches` since `counts` the runtime took as settled before
|
||||
/// (`dispatches_settled_as_before`) and as planned before (`dispatches_planned_as_before`), as
|
||||
/// the encode workload's `<variant>_rt_*` lines.
|
||||
fn emit_memo_shares<G: Gpu>(
|
||||
g: &G,
|
||||
counts: Option<Vec<(&'static str, f64)>>,
|
||||
dispatches: f64,
|
||||
variant: &str,
|
||||
) {
|
||||
let after = g.work_counts();
|
||||
for ((counted, before), (_, now)) in counts.unwrap_or_default().iter().zip(&after) {
|
||||
let metric = match *counted {
|
||||
"dispatches_settled_as_before" => "rt_settled_as_before",
|
||||
"dispatches_planned_as_before" => "rt_planned_as_before",
|
||||
_ => continue,
|
||||
};
|
||||
let share = (now - before) / dispatches;
|
||||
emit(
|
||||
"encode",
|
||||
&format!("{variant}_{metric}"),
|
||||
"share",
|
||||
&mut [share],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -508,7 +638,7 @@ fn encode_tiny<G: Gpu>(g: &G, s: &Scene<G>, command_buffer: &G::CommandBuffer, t
|
||||
match tiny {
|
||||
Tiny::Empty => {}
|
||||
Tiny::Fill => g.fill(command_buffer, &s.fill, 256),
|
||||
Tiny::Dispatch => encode_dispatches(g, s, command_buffer, 1, false),
|
||||
Tiny::Dispatch => encode_dispatches(g, s, command_buffer, 1, DispatchChurn::Static),
|
||||
Tiny::Draw => encode_draws(g, s, command_buffer, 1, Churn::Static),
|
||||
}
|
||||
}
|
||||
@@ -596,6 +726,181 @@ pub fn latency<G: Gpu>(g: &G, s: &Scene<G>, sizes: &Sizes) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `signals` workload (module docs of `main.rs`): a command buffer of one tiny fill with a
|
||||
/// completed handler, committed alone and waited for, as the consumer's isolated execution is,
|
||||
/// `plain`, and with what each other variant adds.
|
||||
pub fn signals<G: Gpu>(g: &G, s: &Scene<G>, sizes: &Sizes) {
|
||||
for name in ["plain", "scheduled_handler", "scheduled_signal", "checked"] {
|
||||
let event = g.shared_event();
|
||||
let (mut handler, mut wait, mut cpu) = (vec![], vec![], vec![]);
|
||||
let mut counts = None;
|
||||
let mut has = true;
|
||||
let runs = sizes.latency + 10;
|
||||
for run in 0..runs {
|
||||
if run == 10 {
|
||||
counts = Some(g.work_counts());
|
||||
}
|
||||
let value = run as u64 + 1;
|
||||
g.pool(|| {
|
||||
let command_buffer = g.command_buffer();
|
||||
encode_tiny(g, s, &command_buffer, Tiny::Fill);
|
||||
match name {
|
||||
"scheduled_handler" => g.set_when_scheduled(&command_buffer, &event, value),
|
||||
"scheduled_signal" => g.signal_when_scheduled(&command_buffer, &event, value),
|
||||
"checked" => has = g.check_submissions(&command_buffer),
|
||||
_ => {}
|
||||
}
|
||||
let (send, receive) = mpsc::channel();
|
||||
g.on_completed(
|
||||
&command_buffer,
|
||||
Box::new(move || {
|
||||
let _ = send.send(Instant::now());
|
||||
}),
|
||||
);
|
||||
let cpu0 = process_cpu();
|
||||
let t0 = Instant::now();
|
||||
g.commit(&command_buffer);
|
||||
let at = receive.recv().expect("the completed handler ran");
|
||||
g.wait(&command_buffer);
|
||||
let t1 = Instant::now();
|
||||
let cpu1 = process_cpu();
|
||||
if run >= 10 {
|
||||
handler.push(us(at - t0));
|
||||
wait.push(us(t1 - t0));
|
||||
cpu.push(us(cpu1 - cpu0));
|
||||
}
|
||||
});
|
||||
if !has {
|
||||
break;
|
||||
}
|
||||
if name.starts_with("scheduled") {
|
||||
assert_eq!(g.event_value(&event), value, "{name}: the value set");
|
||||
}
|
||||
}
|
||||
if !has {
|
||||
continue;
|
||||
}
|
||||
emit(
|
||||
"signals",
|
||||
&format!("{name}_commit_to_handler"),
|
||||
"us",
|
||||
&mut handler,
|
||||
);
|
||||
emit(
|
||||
"signals",
|
||||
&format!("{name}_commit_to_wait_return"),
|
||||
"us",
|
||||
&mut wait,
|
||||
);
|
||||
emit("signals", &format!("{name}_process_cpu"), "us", &mut cpu);
|
||||
let after = g.work_counts();
|
||||
for ((counted, before), (_, now)) in counts.unwrap_or_default().iter().zip(&after) {
|
||||
let per = (now - before) / sizes.latency as f64;
|
||||
emit(
|
||||
"signals",
|
||||
&format!("rt_{name}_{counted}"),
|
||||
"per cb",
|
||||
&mut [per],
|
||||
);
|
||||
}
|
||||
}
|
||||
// A burst of command buffers committed back to back, each checked or not, to the last one's
|
||||
// completion: the scheduler's cost of a batch, per command buffer.
|
||||
const BURST: usize = 64;
|
||||
for name in ["plain", "checked"] {
|
||||
let (mut wall, mut cpu) = (vec![], vec![]);
|
||||
let mut counts = None;
|
||||
let mut has = true;
|
||||
for run in 0..sizes.latency + 3 {
|
||||
if run == 3 {
|
||||
counts = Some(g.work_counts());
|
||||
}
|
||||
g.pool(|| {
|
||||
let buffers: Vec<_> = (0..BURST)
|
||||
.map(|_| {
|
||||
let command_buffer = g.command_buffer();
|
||||
encode_tiny(g, s, &command_buffer, Tiny::Fill);
|
||||
if name == "checked" {
|
||||
has = g.check_submissions(&command_buffer);
|
||||
}
|
||||
command_buffer
|
||||
})
|
||||
.collect();
|
||||
let cpu0 = process_cpu();
|
||||
let t0 = Instant::now();
|
||||
for command_buffer in &buffers {
|
||||
g.commit(command_buffer);
|
||||
}
|
||||
g.wait(&buffers[BURST - 1]);
|
||||
let t1 = Instant::now();
|
||||
let cpu1 = process_cpu();
|
||||
if run >= 3 {
|
||||
wall.push(us(t1 - t0) / BURST as f64);
|
||||
cpu.push(us(cpu1 - cpu0) / BURST as f64);
|
||||
}
|
||||
});
|
||||
if !has {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !has {
|
||||
continue;
|
||||
}
|
||||
emit("signals", &format!("burst_{name}_wall"), "us/cb", &mut wall);
|
||||
emit(
|
||||
"signals",
|
||||
&format!("burst_{name}_process_cpu"),
|
||||
"us/cb",
|
||||
&mut cpu,
|
||||
);
|
||||
let after = g.work_counts();
|
||||
for ((counted, before), (_, now)) in counts.unwrap_or_default().iter().zip(&after) {
|
||||
let per = (now - before) / (sizes.latency * BURST) as f64;
|
||||
emit(
|
||||
"signals",
|
||||
&format!("rt_burst_{name}_{counted}"),
|
||||
"per cb",
|
||||
&mut [per],
|
||||
);
|
||||
}
|
||||
}
|
||||
// A listener made and dropped unused, as the consumer makes one per task; then one made, and
|
||||
// its first notification asked for a value already reached, to its block's start.
|
||||
let (mut unused, mut made, mut first) = (vec![], vec![], vec![]);
|
||||
let event = g.shared_event();
|
||||
for run in 0..sizes.latency + 10 {
|
||||
let t0 = Instant::now();
|
||||
drop(g.listener());
|
||||
let t1 = Instant::now();
|
||||
let listener = g.listener();
|
||||
let t2 = Instant::now();
|
||||
let (send, receive) = mpsc::channel();
|
||||
g.notify(
|
||||
&event,
|
||||
&listener,
|
||||
0,
|
||||
Box::new(move || {
|
||||
let _ = send.send(Instant::now());
|
||||
}),
|
||||
);
|
||||
let at = receive.recv().expect("the notification ran");
|
||||
drop(listener);
|
||||
if run >= 10 {
|
||||
unused.push(us(t1 - t0));
|
||||
made.push(us(t2 - t1));
|
||||
first.push(us(at - t2));
|
||||
}
|
||||
}
|
||||
emit(
|
||||
"signals",
|
||||
"listener_made_and_dropped_unused",
|
||||
"us",
|
||||
&mut unused,
|
||||
);
|
||||
emit("signals", "listener_made", "us", &mut made);
|
||||
emit("signals", "listener_first_notification", "us", &mut first);
|
||||
}
|
||||
|
||||
/// GPU time of the heavy shaders and the feature kernels, one command buffer in flight: from the
|
||||
/// commit until the wait returned, and `GPUEndTime - GPUStartTime` where the side measures it on
|
||||
/// the GPU. With `outputs`, each kernel's output after its last run goes to `<outputs>/<name>.bin`.
|
||||
@@ -1092,7 +1397,7 @@ fn drag_once<G: Gpu>(
|
||||
g.end_render(encoder);
|
||||
}
|
||||
if at < DRAG_DISPATCHES {
|
||||
encode_dispatches(g, s, &command_buffer, 1, false);
|
||||
encode_dispatches(g, s, &command_buffer, 1, DispatchChurn::Static);
|
||||
}
|
||||
g.commit(&command_buffer);
|
||||
last = Some(command_buffer);
|
||||
|
||||
@@ -61,7 +61,7 @@ use super::error::{
|
||||
FailedPipeline, MeshRecordsOverflow, PipelineCreationCause, Problem,
|
||||
TessellationRecordsOverflow, TimedOut,
|
||||
};
|
||||
use super::event::{EventRef, EventShared};
|
||||
use super::event::{EventRef, EventShared, SharedEvent};
|
||||
use super::execution::Execution;
|
||||
use super::exit_guard::{self, Call};
|
||||
use super::function_table::TableSnapshot;
|
||||
@@ -500,6 +500,9 @@ pub(super) struct State {
|
||||
pub(super) prefix: Option<vk::CommandBuffer>,
|
||||
/// The encoders split at the event and binary semaphore waits and signals.
|
||||
batches: Batches<Arc<EventShared>, vk::Semaphore>,
|
||||
/// Its scheduled signals, in the order encoded
|
||||
/// ([`CommandBuffer::encode_signal_event_scheduled`]).
|
||||
scheduled_signals: Vec<(Arc<EventShared>, u64)>,
|
||||
scheduled: VecDeque<Handler>,
|
||||
/// Its submission handlers ([`CommandBuffer::add_submission_handler`]): run on the thread
|
||||
/// that takes its last batch for its queue (submits it, or holds it in a group), before its
|
||||
@@ -1527,6 +1530,7 @@ impl CommandBuffer {
|
||||
folds: Vec::new(),
|
||||
prefix: None,
|
||||
batches: Batches::default(),
|
||||
scheduled_signals: Vec::new(),
|
||||
scheduled: VecDeque::new(),
|
||||
submission: VecDeque::new(),
|
||||
submitting: false,
|
||||
@@ -1853,6 +1857,41 @@ impl CommandBuffer {
|
||||
})
|
||||
}
|
||||
|
||||
/// `encodeSignalEventScheduled:value:`, private: once the command buffer is scheduled, the
|
||||
/// event's value becomes at least `value`, set as [`SharedEvent::set_signaled_value`] sets it:
|
||||
/// before its status reads `Scheduled`, before any of its scheduled handlers runs (one added
|
||||
/// before this call too) and before [`wait_until_scheduled`](Self::wait_until_scheduled)
|
||||
/// returns, as Metal's (an M3 Max, macOS 27.0.1); several in the order encoded. No handler
|
||||
/// thread is woken for it: a command buffer whose transition to `Scheduled` has nothing else
|
||||
/// to run makes it on the thread that submitted its last batch. One that fails before it is
|
||||
/// scheduled sets nothing, as it runs no scheduled handler.
|
||||
///
|
||||
/// Called once the command buffer is committed, it does nothing, as Metal's (measured before
|
||||
/// and after the command buffer was scheduled). Refused while an encoder is open (Metal
|
||||
/// asserts), after an abandoned encoder, and for another device's event, as
|
||||
/// [`encode_signal_event`](Self::encode_signal_event) is. Metal ends the process for an
|
||||
/// `MTLEvent`, which this call does not take.
|
||||
pub fn encode_signal_event_scheduled(
|
||||
&self,
|
||||
event: &SharedEvent,
|
||||
value: u64,
|
||||
) -> Result<(), Error> {
|
||||
const CALL: &str = "encode_signal_event_scheduled";
|
||||
let event = EventRef::Shared(event);
|
||||
let event = event.shared();
|
||||
if !event.device().same(&self.0.device) {
|
||||
return Err(invalid(CALL, Problem::ForeignObject));
|
||||
}
|
||||
self.settle_end();
|
||||
let mut state = self.state();
|
||||
match state.refusal() {
|
||||
None => state.scheduled_signals.push((Arc::clone(event), value)),
|
||||
Some(Problem::AlreadyCommitted) => {}
|
||||
Some(problem) => return Err(invalid(CALL, problem)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `encodeWaitForEvent:value:`: the work encoded after it starts once the event's value
|
||||
/// reached `value`. Refused as [`CommandBuffer::encode_signal_event`] is.
|
||||
pub fn encode_wait_for_event(&self, event: EventRef<'_>, value: u64) -> Result<(), Error> {
|
||||
@@ -3453,10 +3492,12 @@ impl CommandBufferShared {
|
||||
}
|
||||
|
||||
/// The scheduler submitted the last batch, or held it in a group (`group.rs`): in the queue's
|
||||
/// context, once the submitting thread ran its submission handlers, become `Scheduled`, then run the scheduled handlers on
|
||||
/// context, once the submitting thread ran its submission handlers, set the scheduled signals'
|
||||
/// values, in the order encoded, then become `Scheduled`, then run the scheduled handlers on
|
||||
/// this thread, in the order added, then let `wait_until_scheduled` return. Metal's status
|
||||
/// reads `Scheduled` just before its first scheduled handler starts, and its wait returns
|
||||
/// once the last returned (an M4, macOS 27.0.1).
|
||||
/// once the last returned (an M4, macOS 27.0.1); its scheduled signals' values show before
|
||||
/// its status reads `Scheduled` (an M3 Max, macOS 27.0.1).
|
||||
fn run_scheduled(self: &Arc<Self>) {
|
||||
{
|
||||
let mut state = lock(&self.state);
|
||||
@@ -3474,6 +3515,16 @@ impl CommandBufferShared {
|
||||
.0;
|
||||
state.parked -= 1;
|
||||
}
|
||||
if !state.scheduled_signals.is_empty() {
|
||||
// Set without the command buffer's lock: a set wakes the scheduler, whose lock
|
||||
// comes first.
|
||||
let signals = std::mem::take(&mut state.scheduled_signals);
|
||||
drop(state);
|
||||
for (event, value) in signals {
|
||||
event.set(value);
|
||||
}
|
||||
state = lock(&self.state);
|
||||
}
|
||||
state.status = CommandBufferStatus::Scheduled;
|
||||
self.answer(&state);
|
||||
}
|
||||
|
||||
@@ -69,8 +69,8 @@ use super::indirect_dispatch::{
|
||||
use super::indirect_execute::{self, Execute, ExecutionRange};
|
||||
use super::pending_dispatch::{PendingDispatch, Recording};
|
||||
use super::pipeline::{
|
||||
flat_dispatch, BufferForms, ComputePipelineState, RawPipeline, RegionKey, RegionPipeline,
|
||||
Variant, VariantObjects,
|
||||
flat_dispatch, BufferForms, ComputePipelineState, Planned, RawPipeline, RegionKey,
|
||||
RegionPipeline, Variant, VariantObjects,
|
||||
};
|
||||
use super::predication::{Captures, Event};
|
||||
use super::pvrtc::degrade_unreadable;
|
||||
@@ -178,6 +178,9 @@ pub struct ComputeCommandEncoder {
|
||||
dispatches: usize,
|
||||
/// What its last dispatch settled ([`DispatchMemo`]).
|
||||
memo: DispatchMemo,
|
||||
/// The residency's generation as a command last noted the heaps of what it made resident
|
||||
/// (`command_encoded`): no command notes them again before it changes.
|
||||
heaps_noted: Option<u64>,
|
||||
}
|
||||
|
||||
/// The state of a compute encoder a command ran with, which a predicated loop's copies replay it
|
||||
@@ -242,6 +245,7 @@ impl CommandBuffer {
|
||||
.then(|| self.device().shared().scheduler.spare_logs().compute()),
|
||||
dispatches: 0,
|
||||
memo: DispatchMemo::default(),
|
||||
heaps_noted: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -270,6 +274,7 @@ impl ComputeCommandEncoder {
|
||||
log: None,
|
||||
dispatches: 0,
|
||||
memo: DispatchMemo::default(),
|
||||
heaps_noted: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1259,8 +1264,13 @@ impl ComputeCommandEncoder {
|
||||
/// Once a command was encoded, note the heaps the encoder used; and where it reads texture
|
||||
/// handles from memory (`reads`), the textures it reaches whose blocks a carrier holds.
|
||||
fn command_encoded(&mut self, reads: bool) {
|
||||
// The command, encoded, used the heaps of what the encoder made resident.
|
||||
self.core.touch_heaps(self.residency.heaps());
|
||||
// The command, encoded, used the heaps of what the encoder made resident: noted once a
|
||||
// change of it, as an earlier command noted those it held then.
|
||||
let generation = self.residency.generation();
|
||||
if self.heaps_noted != Some(generation) {
|
||||
self.core.touch_heaps(self.residency.heaps());
|
||||
self.heaps_noted = Some(generation);
|
||||
}
|
||||
if !reads {
|
||||
return;
|
||||
}
|
||||
@@ -1537,16 +1547,15 @@ fn apart_samplers(device: &Device, objects: &VariantObjects) -> bool {
|
||||
/// What a dispatch settles before it binds ([`settle_dispatch`]): the device's sampler states it
|
||||
/// lists (less those at IDs no set-1 sampler array of the variant holds, `unlisted` saying so:
|
||||
/// `heap_sets::fit_samplers`), the visible-function tables its state made, its runtime samplers'
|
||||
/// address-mode maps, its bind state, and the variant it runs on with its plan, for `dispatch`.
|
||||
/// address-mode maps, its bind state, and what it planned: the state's shape, and the variant it
|
||||
/// runs on with its plan, for `planned.dispatch`.
|
||||
pub(super) struct SettledDispatch {
|
||||
argument_samplers: Vec<SamplerState>,
|
||||
function_tables: Vec<VisibleFunctionTable>,
|
||||
unlisted: Option<(u64, u64)>,
|
||||
sampler_maps: SamplerMaps,
|
||||
state: BindState,
|
||||
variant: Arc<Variant>,
|
||||
plan: Arc<BindingPlan>,
|
||||
dispatch: Dispatch,
|
||||
planned: Arc<Planned>,
|
||||
}
|
||||
|
||||
/// A flat indirect call and its preprocess's description (`indirect_dispatch.rs`).
|
||||
@@ -1555,7 +1564,10 @@ type Flat<'a> = Option<(FlatCall<'a>, FlatIndirect)>;
|
||||
/// What a dispatch of `tables`, of `direct` group counts or of a flat indirect call (`gpu`),
|
||||
/// settles ([`SettledDispatch`]) with `function_tables`, its state's, and `samplers`, the
|
||||
/// device's sampler states: the flat call's preprocess description beside it, and `None` where
|
||||
/// the GPU path does not take an indirect dispatch (`indirect_dispatch.rs`).
|
||||
/// the GPU path does not take an indirect dispatch (`indirect_dispatch.rs`). A direct dispatch
|
||||
/// whose bind state has the shape the state's last direct dispatch planned, of the same dispatch
|
||||
/// and buffer forms, takes what that one planned ([`Planned`]); one that plans keeps what it
|
||||
/// planned for the next.
|
||||
fn settle_dispatch<'a>(
|
||||
tables: &DispatchTables<'_>,
|
||||
(direct, gpu): (Option<Dispatch>, Option<FlatCall<'a>>),
|
||||
@@ -1570,37 +1582,67 @@ fn settle_dispatch<'a>(
|
||||
let mut unlisted = None;
|
||||
// Its runtime samplers' address modes as the textures they sample map them.
|
||||
let sampler_maps = tables.sampler_maps()?;
|
||||
let (state, variant, plan, dispatch, flat) = loop {
|
||||
let last = match direct {
|
||||
Some(dispatch) => pipeline
|
||||
.planned()
|
||||
.filter(|last| last.dispatch == dispatch && last.forms == tables.forms),
|
||||
None => None,
|
||||
};
|
||||
let (state, planned, as_before, flat) = loop {
|
||||
let mut state = tables.bind_state(&argument_samplers, &function_tables);
|
||||
sampler_maps.apply(&mut state);
|
||||
let (variant, plan, dispatch, flat) = match (direct, gpu) {
|
||||
(Some(dispatch), _) => {
|
||||
let (variant, plan) = pipeline.settle(&state.shape(), &dispatch, tables.forms)?;
|
||||
(variant, plan, dispatch, None)
|
||||
let last = last.as_ref().filter(|last| state.has_shape(&last.shape));
|
||||
let (planned, as_before, flat) = match (last, direct, gpu) {
|
||||
(Some(last), ..) => (Arc::clone(last), true, None),
|
||||
(None, Some(dispatch), _) => {
|
||||
let shape = state.shape();
|
||||
let (variant, plan) = pipeline.settle(&shape, &dispatch, tables.forms)?;
|
||||
let planned = Planned {
|
||||
shape: Arc::new(shape),
|
||||
dispatch,
|
||||
forms: tables.forms,
|
||||
variant,
|
||||
plan,
|
||||
made: OnceLock::new(),
|
||||
};
|
||||
(Arc::new(planned), false, None)
|
||||
}
|
||||
(None, Some(gpu)) => match settle_indirect(pipeline, gpu, &state.shape())? {
|
||||
Some((variant, plan, indirect)) => {
|
||||
let dispatch = flat_dispatch(indirect.threads_per_threadgroup);
|
||||
(variant, plan, dispatch, Some((gpu, indirect)))
|
||||
}
|
||||
None => return Ok(None),
|
||||
},
|
||||
(None, None) => return Err(internal("a dispatch of no counts")),
|
||||
(None, None, Some(gpu)) => {
|
||||
let shape = state.shape();
|
||||
let Some((variant, plan, indirect)) = settle_indirect(pipeline, gpu, &shape)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let planned = Planned {
|
||||
shape: Arc::new(shape),
|
||||
dispatch: flat_dispatch(indirect.threads_per_threadgroup),
|
||||
forms: tables.forms,
|
||||
variant,
|
||||
plan,
|
||||
made: OnceLock::new(),
|
||||
};
|
||||
(Arc::new(planned), false, Some((gpu, indirect)))
|
||||
}
|
||||
(None, None, None) => return Err(internal("a dispatch of no counts")),
|
||||
};
|
||||
let set = variant.pipeline().layout.sets.get(1);
|
||||
let set = planned.variant.pipeline().layout.sets.get(1);
|
||||
if heap_sets::fit_samplers(set, &mut argument_samplers, &mut unlisted) {
|
||||
break (state, variant, plan, dispatch, flat);
|
||||
break (state, planned, as_before, flat);
|
||||
}
|
||||
};
|
||||
match (as_before, direct) {
|
||||
(true, _) => (pipeline.device().shared().counts).dispatch_planned_as_before(),
|
||||
// A flat dispatch's variant and plan are the flat path's: none a direct one takes.
|
||||
(false, Some(_)) => pipeline.keep_planned(Arc::clone(&planned)),
|
||||
(false, None) => {}
|
||||
}
|
||||
let settled = SettledDispatch {
|
||||
argument_samplers,
|
||||
function_tables,
|
||||
unlisted,
|
||||
sampler_maps,
|
||||
state,
|
||||
variant,
|
||||
plan,
|
||||
dispatch,
|
||||
planned,
|
||||
};
|
||||
Ok(Some((settled, flat)))
|
||||
}
|
||||
@@ -1616,15 +1658,22 @@ fn settle_dispatch<'a>(
|
||||
/// (a texture's and a sampler's facts, fixed as it is made; a buffer's length, base and
|
||||
/// addresses, which only a no-copy buffer's move changes: `buffer::host_cells_moved`), of the
|
||||
/// threadgroup lengths, imageblock size and stage-in region set, of what the encoder made
|
||||
/// resident (nothing: a dispatch of an encoder that made a resource or a heap resident takes no
|
||||
/// memo), of the device's live sampler states (`Device::sampler_slots_changed`), of the
|
||||
/// state's visible-function tables (none: a dispatch of a state that made one takes no memo),
|
||||
/// and of the sampler maps, which are the table's and the residency's.
|
||||
/// resident (its generation, which every change of it draws anew, `Residency::generation`;
|
||||
/// what a used resource states of it beyond that, its buffers' addresses, which only a no-copy
|
||||
/// buffer's move changes, and whether each indirect command buffer holds its ID's slot, which a
|
||||
/// buffer made later with the ID takes: `Residency::holds_slots_as`), of the device's live
|
||||
/// sampler states (`Device::sampler_slots_changed`), of the state's visible-function tables
|
||||
/// (none: a dispatch of a state that made one takes no memo), and of the sampler maps, which
|
||||
/// are the table's and the residency's.
|
||||
/// - **The variant and plan** are `ComputePipelineState::settle`'s of the shape, the dispatch and
|
||||
/// the buffer forms; **the commands** are the plan's instantiation for the state and the
|
||||
/// dispatch, their regions keyed by the variant for the device (`Variant::keyed_regions`).
|
||||
/// - **A region's `VkPipeline`** found made is its variant's for the region's key, which its
|
||||
/// making never changes; regions not all made are looked up again at the next dispatch.
|
||||
/// - **A dispatch that settles again** (another table, another residency) takes the variant, the
|
||||
/// plan and the made `VkPipeline`s of the state's last direct dispatch that planned where its
|
||||
/// bind state has that one's shape ([`Planned`], [`settle_dispatch`]): so does one whose
|
||||
/// buffers' offsets alone moved, and an encoder's first dispatch of the state.
|
||||
#[derive(Default)]
|
||||
pub(super) struct DispatchMemo(Option<Arc<KeptDispatch>>);
|
||||
|
||||
@@ -1637,6 +1686,8 @@ pub(super) struct KeptDispatch {
|
||||
imageblock: ImageblockSize,
|
||||
stage_in_region: Option<StageInRegion>,
|
||||
forms: BufferForms,
|
||||
/// The residency's generation (`Residency::generation`).
|
||||
residency: u64,
|
||||
/// `buffer::host_cells_moved` and `Device::sampler_slots_changed` as it was settled.
|
||||
counted: (u64, u64),
|
||||
settled: SettledDispatch,
|
||||
@@ -1657,12 +1708,14 @@ impl DispatchMemo {
|
||||
let kept = self.0.as_ref()?;
|
||||
let same = kept.pipeline == *tables.pipeline
|
||||
&& kept.stamp == tables.table.stamp()
|
||||
&& kept.settled.dispatch == *dispatch
|
||||
&& kept.settled.planned.dispatch == *dispatch
|
||||
&& kept.counted == counted
|
||||
&& kept.forms == tables.forms
|
||||
&& kept.imageblock == tables.imageblock
|
||||
&& kept.stage_in_region == tables.stage_in_region
|
||||
&& kept.threadgroup_lengths == *tables.threadgroup_lengths;
|
||||
&& kept.threadgroup_lengths == *tables.threadgroup_lengths
|
||||
&& kept.residency == tables.residency.generation()
|
||||
&& (tables.residency).holds_slots_as(&kept.settled.state.used_resources);
|
||||
same.then(|| Arc::clone(kept))
|
||||
}
|
||||
|
||||
@@ -1681,6 +1734,7 @@ impl DispatchMemo {
|
||||
imageblock: tables.imageblock,
|
||||
stage_in_region: tables.stage_in_region,
|
||||
forms: tables.forms,
|
||||
residency: tables.residency.generation(),
|
||||
counted,
|
||||
settled,
|
||||
commands: OnceLock::new(),
|
||||
@@ -1714,14 +1768,9 @@ fn record(
|
||||
// The live visible-function tables the pipeline state made: the encoder's, or an indirect
|
||||
// command's own state's.
|
||||
let function_tables = pipeline.function_tables();
|
||||
// An encoder's own direct dispatch, of a state that made no table, in an encoder that made
|
||||
// nothing resident, takes the memo.
|
||||
// An encoder's own direct dispatch, of a state that made no table, takes the memo.
|
||||
let memo = match (memo, direct) {
|
||||
(Some(memo), Some(dispatch))
|
||||
if function_tables.is_empty() && tables.residency.is_empty() =>
|
||||
{
|
||||
Some((memo, dispatch))
|
||||
}
|
||||
(Some(memo), Some(dispatch)) if function_tables.is_empty() => Some((memo, dispatch)),
|
||||
_ => None,
|
||||
};
|
||||
let mut fresh = None;
|
||||
@@ -1770,10 +1819,15 @@ fn record(
|
||||
unlisted,
|
||||
sampler_maps,
|
||||
state,
|
||||
planned,
|
||||
} = settled;
|
||||
let Planned {
|
||||
shape,
|
||||
variant,
|
||||
plan,
|
||||
dispatch,
|
||||
} = settled;
|
||||
..
|
||||
} = &**planned;
|
||||
let (unlisted, dispatch) = (*unlisted, *dispatch);
|
||||
let interface = &variant.pipeline().interface;
|
||||
core.device().degrade_argument_pixel_samplers(
|
||||
@@ -1834,7 +1888,7 @@ fn record(
|
||||
core.executed(|| {
|
||||
Execution::new(
|
||||
ExecutedPipeline::Compute(Arc::clone(variant.shared_pipeline())),
|
||||
Arc::new(state.shape()),
|
||||
Arc::clone(shape),
|
||||
Vec::new(),
|
||||
)
|
||||
});
|
||||
@@ -1956,11 +2010,19 @@ fn record(
|
||||
// Where the driver loses a layout's baked samplers after a copy in the same
|
||||
// `VkCommandBuffer` (`RuntimeDriverDefect::ImmutableSamplersLostAfterCopies`), a variant that
|
||||
// bakes them records in one of its own, as one being made does.
|
||||
// Those the memo's entry holds, else those found made for what the dispatch planned, of its
|
||||
// regions' keys ([`Planned`]).
|
||||
let kept_made = (kept.as_ref())
|
||||
.and_then(|kept| kept.made.get())
|
||||
.or_else(|| planned.made_for(commands))
|
||||
.filter(|_| !apart_samplers(&device, &objects));
|
||||
let (pipelines, pending) = match (own.filter(|_| !core.encodes_again()), kept_made) {
|
||||
(Some(_), Some(made)) => (made.clone(), None),
|
||||
(Some(_), Some(made)) => {
|
||||
if let Some(kept) = &kept {
|
||||
drop(kept.made.set(made.clone()));
|
||||
}
|
||||
(made.clone(), None)
|
||||
}
|
||||
(Some(dispatch), None) => {
|
||||
let begun: Vec<_> = commands
|
||||
.regions
|
||||
@@ -1979,10 +2041,19 @@ fn record(
|
||||
.collect();
|
||||
match made {
|
||||
Some(made) if !apart_samplers(&device, &objects) => {
|
||||
// Kept with the entry, which the next dispatch of its inputs takes.
|
||||
// Kept with the entry, which the next dispatch of its inputs takes, and with
|
||||
// what it planned, which the next dispatch of its shape takes.
|
||||
if let Some(kept) = &kept {
|
||||
drop(kept.made.set(made.clone()));
|
||||
}
|
||||
// Not a key's residual form, which serves only while its own is made.
|
||||
let own = (begun.iter().zip(&made)).all(|((key, _), made)| {
|
||||
planned.made.get().is_none() && variant.made_as(key, made)
|
||||
});
|
||||
if own {
|
||||
let keys = begun.iter().map(|(key, _)| key.clone()).collect();
|
||||
drop(planned.made.set((keys, made.clone())));
|
||||
}
|
||||
(made, None)
|
||||
}
|
||||
Some(_) => {
|
||||
@@ -2091,7 +2162,7 @@ fn record(
|
||||
core.executed(|| {
|
||||
Execution::made_later(
|
||||
ExecutedPipeline::Compute(Arc::clone(variant.shared_pipeline())),
|
||||
Arc::new(state.shape()),
|
||||
Arc::clone(shape),
|
||||
creation,
|
||||
)
|
||||
});
|
||||
@@ -2109,7 +2180,7 @@ fn record(
|
||||
core.executed(|| {
|
||||
Execution::new(
|
||||
ExecutedPipeline::Compute(Arc::clone(variant.shared_pipeline())),
|
||||
Arc::new(state.shape()),
|
||||
Arc::clone(shape),
|
||||
pipelines.iter().map(|made| made.created_in).collect(),
|
||||
)
|
||||
});
|
||||
|
||||
@@ -26,10 +26,13 @@
|
||||
//! new `SharedEvent` of the same event. Opening it on another device is refused: Vulkan
|
||||
//! semaphores do not cross devices unless exported, which the runtime does not do.
|
||||
//! - **Listeners** run notifications on a thread of their own, one after another in the order they
|
||||
//! came due. A notification for a value already reached comes due at once (measured on Metal).
|
||||
//! came due, started as the first notification is asked for: a listener no notification is
|
||||
//! asked of starts no thread, as Metal's runs its blocks on a dispatch queue, whose threads
|
||||
//! come and go with the work. A notification for a value already reached comes due at once
|
||||
//! (measured on Metal).
|
||||
|
||||
use super::device::{lock, Device};
|
||||
use super::error::{vulkan, Error, MemoryKind, RuntimeGap};
|
||||
use super::error::{vulkan, Error, RuntimeGap};
|
||||
use super::event_timeline::{EventTimeline, Signal, WaitFor};
|
||||
use super::exit_guard::{self, Call};
|
||||
use crate::release;
|
||||
@@ -250,8 +253,9 @@ impl EventShared {
|
||||
lock(&self.state).timeline.value()
|
||||
}
|
||||
|
||||
/// The host set `value`.
|
||||
fn set(self: &Arc<Self>, value: u64) {
|
||||
/// The host set `value`: [`SharedEvent::set_signaled_value`]'s, and a command buffer's
|
||||
/// scheduled signal's (`CommandBuffer::encode_signal_event_scheduled`).
|
||||
pub(super) fn set(self: &Arc<Self>, value: u64) {
|
||||
let due = {
|
||||
let mut state = lock(&self.state);
|
||||
if !state.timeline.set(value) {
|
||||
@@ -302,6 +306,8 @@ impl EventShared {
|
||||
value: u64,
|
||||
block: SharedEventNotification,
|
||||
) {
|
||||
// Its thread runs from now on, so the notification runs as it comes due.
|
||||
listener.start();
|
||||
let notification = Notification {
|
||||
value,
|
||||
listener: listener.clone(),
|
||||
@@ -484,9 +490,12 @@ impl SharedEventHandle {
|
||||
}
|
||||
|
||||
/// A Metal shared event listener (`MTLSharedEventListener`): a thread of its own that runs the
|
||||
/// notifications posted to it, one after another. Cheap to clone (a retain); `Send + Sync`. The
|
||||
/// thread ends once every handle is gone, including those that pending notifications hold, and
|
||||
/// what was posted ran.
|
||||
/// notifications posted to it, one after another, started as the first one is asked for
|
||||
/// ([`SharedEvent::notify_listener`]; none for a listener never asked one). Cheap to clone (a
|
||||
/// retain); `Send + Sync`. The thread ends once every handle is gone, including those that pending
|
||||
/// notifications hold, and what was posted ran. Metal runs the blocks on a dispatch queue of its
|
||||
/// own, which a listener made with `initWithDispatchQueue:` names: the runtime has no form of that
|
||||
/// initializer.
|
||||
#[derive(Clone)]
|
||||
pub struct SharedEventListener(Arc<ListenerHandle>);
|
||||
|
||||
@@ -509,7 +518,7 @@ impl Drop for ListenerHandle {
|
||||
}
|
||||
}
|
||||
|
||||
type Job = Box<dyn FnOnce() + Send>;
|
||||
pub(super) type Job = Box<dyn FnOnce() + Send>;
|
||||
|
||||
struct ListenerQueue {
|
||||
jobs: Mutex<Jobs>,
|
||||
@@ -520,33 +529,65 @@ struct Jobs {
|
||||
posted: VecDeque<Job>,
|
||||
/// Every handle is gone: nothing more can be posted.
|
||||
closed: bool,
|
||||
/// The thread was started ([`SharedEventListener::start`]).
|
||||
started: bool,
|
||||
}
|
||||
|
||||
impl Default for SharedEventListener {
|
||||
fn default() -> SharedEventListener {
|
||||
SharedEventListener::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl SharedEventListener {
|
||||
/// `[[MTLSharedEventListener alloc] init]`: a listener with a thread of its own; refused when
|
||||
/// the host cannot start one.
|
||||
pub fn new() -> Result<SharedEventListener, Error> {
|
||||
/// `[[MTLSharedEventListener alloc] init]`: a listener whose thread starts as its first
|
||||
/// notification is asked for. Where the host cannot start the thread then, each later
|
||||
/// notification asked for or come due tries again, and those come due wait for it.
|
||||
pub fn new() -> SharedEventListener {
|
||||
let queue = Arc::new(ListenerQueue {
|
||||
jobs: Mutex::new(Jobs {
|
||||
posted: VecDeque::new(),
|
||||
closed: false,
|
||||
started: false,
|
||||
}),
|
||||
wake: Condvar::new(),
|
||||
});
|
||||
{
|
||||
let queue = Arc::clone(&queue);
|
||||
exit_guard::spawn(
|
||||
std::thread::Builder::new().name("metal2vulkan-listener".into()),
|
||||
move || listen(&queue),
|
||||
)
|
||||
.map_err(|_| Error::OutOfMemory(MemoryKind::Host))?;
|
||||
}
|
||||
Ok(SharedEventListener(Arc::new(ListenerHandle { queue })))
|
||||
SharedEventListener(Arc::new(ListenerHandle { queue }))
|
||||
}
|
||||
|
||||
fn post(&self, job: Job) {
|
||||
lock(&self.0.queue.jobs).posted.push_back(job);
|
||||
self.0.queue.wake.notify_all();
|
||||
/// Start the thread unless it started.
|
||||
fn start(&self) {
|
||||
Self::start_under(&self.0.queue, &mut lock(&self.0.queue.jobs));
|
||||
}
|
||||
|
||||
/// Start `queue`'s thread unless it started, under its jobs' lock (`jobs`): one thread
|
||||
/// starts, whatever thread asks.
|
||||
fn start_under(queue: &Arc<ListenerQueue>, jobs: &mut Jobs) {
|
||||
if jobs.started {
|
||||
return;
|
||||
}
|
||||
let listening = Arc::clone(queue);
|
||||
let started = exit_guard::spawn(
|
||||
std::thread::Builder::new().name("metal2vulkan-listener".into()),
|
||||
move || listen(&listening),
|
||||
);
|
||||
jobs.started = started.is_ok();
|
||||
}
|
||||
|
||||
/// Post `job`, after the jobs posted before it; the thread started where it has not.
|
||||
pub(super) fn post(&self, job: Job) {
|
||||
let queue = &self.0.queue;
|
||||
let mut jobs = lock(&queue.jobs);
|
||||
jobs.posted.push_back(job);
|
||||
Self::start_under(queue, &mut jobs);
|
||||
drop(jobs);
|
||||
queue.wake.notify_all();
|
||||
}
|
||||
|
||||
/// Whether its thread was started.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn started(&self) -> bool {
|
||||
lock(&self.0.queue.jobs).started
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1071,6 +1071,12 @@ impl PartialEq for IndirectCommandBuffer {
|
||||
|
||||
impl Eq for IndirectCommandBuffer {}
|
||||
|
||||
impl std::hash::Hash for IndirectCommandBuffer {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
std::ptr::hash(Arc::as_ptr(&self.0), state);
|
||||
}
|
||||
}
|
||||
|
||||
impl IndirectCommandBuffer {
|
||||
/// The records' bytes: the header, then each command's record.
|
||||
fn bytes(&self) -> Result<*mut u8, Error> {
|
||||
|
||||
@@ -1,20 +1,24 @@
|
||||
//! The hasher of the runtime's maps keyed by its own identities (`ResourceKey`, sequence numbers)
|
||||
//! and by the descriptions it looks its Vulkan objects up by (an image's views, a pass's
|
||||
//! compatible render pass): a multiply-and-fold of each word. Those maps are looked up on the
|
||||
//! encoding thread at every draw and command (the hazard tracker's uses, a buffer's host
|
||||
//! aliases, a draw's texture views, the buffers over host pages a command takes, `rebind.rs`),
|
||||
//! as each pass opens (a new texture's unwritten texels) and as each batch is planned
|
||||
//! (`tracker.rs`) or committed (the resources it reached, `used_resources.rs`).
|
||||
//! and by the descriptions it looks its Vulkan objects up by (an image's views, a pass's compatible
|
||||
//! render pass): a multiply-and-fold of each word. Those maps are looked up on the encoding thread
|
||||
//! at every draw and command (the hazard tracker's uses, a buffer's host aliases, a draw's texture
|
||||
//! views, the buffers over host pages a command takes, `rebind.rs`), as each pass opens (a new
|
||||
//! texture's unwritten texels) and as each batch is planned (`tracker.rs`) or committed (the
|
||||
//! resources it reached, `used_resources.rs`); by the resources an encoder made resident, each its
|
||||
//! object's address (`residency.rs`), at each resource `useResources:count:usage:` names; and by
|
||||
//! the pipeline memos' keys (`pipeline/memo.rs`, every one an `Lru`), among them a variant's plans
|
||||
//! by bind shape, looked up at each dispatch and draw that settles.
|
||||
//!
|
||||
//! The standard maps' default hasher (SipHash-1-3 with random keys) resists inputs chosen to
|
||||
//! collide, and costs its rounds at every lookup. Identities are numbered by the runtime, so a
|
||||
//! program cannot choose them. A program does choose the descriptions behind a view or a pass,
|
||||
//! but each distinct one costs it a Vulkan object, or stays in a bounded memo (a render
|
||||
//! encoder's kept views, `binding.rs`). So keys made to collide would slow only that program's
|
||||
//! own lookups. The multiply spreads consecutive numbers over the high bits the map's control
|
||||
//! bytes read, and the fold brings them down to the low bits its buckets index by. Iteration order
|
||||
//! follows the hash. None of these maps' users depends on it; under the random keys it changed
|
||||
//! from map to map.
|
||||
//! collide, and costs its rounds at every lookup. Identities are numbered by the runtime, and
|
||||
//! objects' addresses placed by the allocator, so a program cannot choose them. A program does
|
||||
//! choose the descriptions behind a view or a pass, a bind shape or a shader, but each distinct one
|
||||
//! costs it a Vulkan object, or stays in a bounded memo (a render encoder's kept views,
|
||||
//! `binding.rs`; every pipeline memo, an `Lru` of bounded entries). So keys made to collide would
|
||||
//! slow only that program's own lookups. The multiply spreads consecutive numbers over the high
|
||||
//! bits the map's control bytes read, and the fold brings them down to the low bits its buckets
|
||||
//! index by. Iteration order follows the hash. None of these maps' users depends on it; under the
|
||||
//! random keys it changed from map to map.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{BuildHasherDefault, Hasher};
|
||||
|
||||
@@ -76,6 +76,13 @@ impl RegionKey {
|
||||
required_subgroup_size: region.required_subgroup_size,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether it is `region`'s key, [`of`](Self::of) it.
|
||||
pub(crate) fn is_of(&self, region: &DispatchRegion) -> bool {
|
||||
self.specialization == region.specialization
|
||||
&& self.stage_flags == region.stage_flags
|
||||
&& self.required_subgroup_size == region.required_subgroup_size
|
||||
}
|
||||
}
|
||||
|
||||
impl Variant {
|
||||
@@ -134,6 +141,12 @@ impl Variant {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `made` is the `VkPipeline` made for `key` itself, not its residual form's, which a
|
||||
/// dispatch takes while `key`'s is being made ([`residual_made`](Self::residual_made)).
|
||||
pub(crate) fn made_as(&self, key: &RegionKey, made: &Arc<RawPipeline>) -> bool {
|
||||
(self.pipelines.made(key)).is_some_and(|own| Arc::ptr_eq(&own, made))
|
||||
}
|
||||
|
||||
/// The made `VkPipeline` of `key`'s residual form, each of its uniform views read at its
|
||||
/// residual, where `key` is not its own residual form (`render/residual.rs`), for a dispatch
|
||||
/// that binds `formats` and takes it at once, which counts it as a residual-form command.
|
||||
|
||||
@@ -19,10 +19,11 @@
|
||||
use super::render::RenderVariant;
|
||||
use super::Variant;
|
||||
use crate::device::lock;
|
||||
use crate::key_hash::KeyMap;
|
||||
use metal2vulkan::cache::PipelineKey;
|
||||
use metal2vulkan::library::{CompiledFunction, FunctionCompileKey};
|
||||
use metal2vulkan::pipeline::{ComputePipeline, RenderPipeline};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::BTreeMap;
|
||||
use std::hash::Hash;
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
@@ -32,8 +33,10 @@ pub(crate) const MEMO_ENTRIES: usize = 4096;
|
||||
/// A map that keeps at most `max_weight` of its entries' weights and at most `max_entries`
|
||||
/// entries, removing the least recently used past either. A lookup or an insert is a use.
|
||||
pub(crate) struct Lru<K, V> {
|
||||
/// Each entry's number: the stamp of the insert that kept it.
|
||||
numbers: HashMap<K, u64>,
|
||||
/// Each entry's number: the stamp of the insert that kept it, found by the runtime's key
|
||||
/// hasher (`key_hash.rs`): a lookup of a variant's plan by bind shape is one per dispatch that
|
||||
/// settles.
|
||||
numbers: KeyMap<K, u64>,
|
||||
/// The entries, by number.
|
||||
entries: BTreeMap<u64, Slot<K, V>>,
|
||||
/// Each entry's number by its last use, oldest first.
|
||||
@@ -64,7 +67,7 @@ impl<K: Clone + Eq + Hash, V> Lru<K, V> {
|
||||
/// An empty map bounded by `max_weight` and `max_entries`.
|
||||
pub(crate) fn new(max_weight: u64, max_entries: usize) -> Lru<K, V> {
|
||||
Lru {
|
||||
numbers: HashMap::new(),
|
||||
numbers: KeyMap::default(),
|
||||
entries: BTreeMap::new(),
|
||||
order: BTreeMap::new(),
|
||||
clock: 0,
|
||||
|
||||
@@ -123,7 +123,7 @@ use metal2vulkan::reflection::ComputePipelineReflection;
|
||||
use sources::Sources;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
use std::sync::{Arc, Mutex, OnceLock, Weak};
|
||||
|
||||
/// `imageblockMemoryLengthForDimensions:` for an explicit imageblock of `cell_bytes` a cell (the
|
||||
/// compile's), none without an imageblock or at a width or height of 0. Otherwise each side rounds
|
||||
@@ -284,6 +284,39 @@ pub(super) struct Program {
|
||||
/// Its buffer slots whose bind offset class tells the device's view base alignment apart
|
||||
/// (`argument_table::AtBindViews`), of its base's interface.
|
||||
at_bind_views: AtBindViews,
|
||||
/// What its last direct dispatch that planned planned ([`Planned`]).
|
||||
planned: Mutex<Option<Arc<Planned>>>,
|
||||
}
|
||||
|
||||
/// What a direct dispatch of a compute state planned (`compute::settle_dispatch`): the variant
|
||||
/// `dispatch` of a bind state of `shape` runs on in `forms`, and its plan for `shape`, as
|
||||
/// [`ComputePipelineState::settle`] answers them, a function of those three alone; and the
|
||||
/// `VkPipeline`s of its regions of those keys, where all were found made. A later dispatch of the
|
||||
/// same dispatch and forms whose bind state has the shape takes them, from any encoder, rather
|
||||
/// than settling them again (`WorkCounts::dispatches_planned_as_before`).
|
||||
pub(crate) struct Planned {
|
||||
pub(crate) shape: Arc<BindShape>,
|
||||
pub(crate) dispatch: Dispatch,
|
||||
pub(crate) forms: BufferForms,
|
||||
pub(crate) variant: Arc<Variant>,
|
||||
pub(crate) plan: Arc<BindingPlan>,
|
||||
/// Each region's key and its made `VkPipeline`, where all were found made, each its key's own
|
||||
/// (none a residual form's, `dispatch_making.rs`).
|
||||
pub(crate) made: OnceLock<(Vec<RegionKey>, Vec<Arc<RawPipeline>>)>,
|
||||
}
|
||||
|
||||
impl Planned {
|
||||
/// The made `VkPipeline`s of `commands`' regions, where they are as many, each of the key of
|
||||
/// one found made.
|
||||
pub(crate) fn made_for(&self, commands: &DispatchCommands) -> Option<&Vec<Arc<RawPipeline>>> {
|
||||
let (keys, made) = self.made.get()?;
|
||||
let same = keys.len() == commands.regions.len()
|
||||
&& keys
|
||||
.iter()
|
||||
.zip(&commands.regions)
|
||||
.all(|(key, region)| key.is_of(region));
|
||||
same.then_some(made)
|
||||
}
|
||||
}
|
||||
|
||||
/// The program's release returns at once: a piece not started stops, and a piece running gives
|
||||
@@ -670,6 +703,7 @@ impl ComputePipelineState {
|
||||
label: options.label.clone(),
|
||||
pieces: piece_holds::PieceHolds::new(),
|
||||
at_bind_views,
|
||||
planned: Mutex::new(None),
|
||||
};
|
||||
StateShared {
|
||||
id,
|
||||
@@ -1019,6 +1053,16 @@ impl ComputePipelineState {
|
||||
ComputeProgram(Arc::clone(&self.0.program))
|
||||
}
|
||||
|
||||
/// What its last direct dispatch that planned planned ([`Planned`]).
|
||||
pub(super) fn planned(&self) -> Option<Arc<Planned>> {
|
||||
lock(&self.0.planned).clone()
|
||||
}
|
||||
|
||||
/// Keep `planned`, a direct dispatch's, in place of what the last planned.
|
||||
pub(super) fn keep_planned(&self, planned: Arc<Planned>) {
|
||||
*lock(&self.0.planned) = Some(planned);
|
||||
}
|
||||
|
||||
/// The variant `dispatch` of a bind state of `shape` runs on in `forms`, and its plan for
|
||||
/// `shape`: the first variant's plan, or that of the variant it asks for, compiled when first
|
||||
/// needed.
|
||||
|
||||
@@ -60,7 +60,17 @@
|
||||
//! shadowed texture is copied in and back as at a slot.
|
||||
//! - **Tokens.** A resource has one token in the encoder, its position in the order the encoder
|
||||
//! first used it, and the union of every usage it was used with; so a plan's shape changes
|
||||
//! only when the encoder uses another resource or widens a usage.
|
||||
//! only when the encoder uses another resource or widens a usage. A resource is found among
|
||||
//! those made resident by its identity, so `useResources:count:usage:` of `n` resources costs
|
||||
//! `n` lookups, whatever the encoder made resident before.
|
||||
//! - **Generations.** Each change of what a residency holds (a resource made resident, a usage or
|
||||
//! stage widened, a heap used or widened, a live table given or taken) gives it a generation no
|
||||
//! other residency of the process had ([`Residency::generation`]): a compute encoder's dispatch
|
||||
//! that finds the generation, and every other input, its last dispatch settled with takes what
|
||||
//! that one settled (`compute.rs`, `DispatchMemo`), and its residency's share of the bind state
|
||||
//! (the used resources, their shape and the plan's commands) is made once per change. What a
|
||||
//! used resource states besides (a buffer's addresses, an indirect command buffer's hold on
|
||||
//! its ID's slot) changes outside the residency: the memo keys on those apart.
|
||||
//! - **Stages.** A render encoder makes a resource resident for the render stages it names
|
||||
//! (`useResource:usage:stages:`, `useHeap:stages:`), joined as the usages are: a draw's
|
||||
//! functions reach it in those of their stages alone (the binder's `UsedResource::stages`), and
|
||||
@@ -70,14 +80,24 @@
|
||||
use super::buffer::{Buffer, ReadApart};
|
||||
use super::heap::Heap;
|
||||
use super::indirect_command_buffer::IndirectCommandBuffer;
|
||||
use super::key_hash::KeyMap;
|
||||
use super::live_buffers::LiveTable;
|
||||
use super::resource::ResourceRef;
|
||||
use super::texture::Texture;
|
||||
use metal2vulkan::bind::{ResidentRange, ResourceClass, UsedResource};
|
||||
use metal2vulkan::metal::{RenderStages, ResourceUsage};
|
||||
use metal2vulkan::pipeline::{BindingSource, PipelineLayout, Stage, SyntheticBinding};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The generation last given to a residency of the process ([`Residency::generation`]).
|
||||
static GENERATIONS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// A generation no residency of the process had.
|
||||
fn next_generation() -> u64 {
|
||||
GENERATIONS.fetch_add(1, Ordering::Relaxed) + 1
|
||||
}
|
||||
|
||||
/// A resource an encoder made resident.
|
||||
#[derive(Clone)]
|
||||
pub(super) enum Used {
|
||||
@@ -97,12 +117,24 @@ pub(super) enum Used {
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct Residency {
|
||||
used: Vec<(Used, ResourceUsage, RenderStages)>,
|
||||
/// Each resource of `used` by its identity, with its token.
|
||||
tokens: KeyMap<Used, u32>,
|
||||
/// The tokens of the indirect command buffers among `used`.
|
||||
indirect: Vec<u32>,
|
||||
/// The tokens of the textures among `used`: a command's look at the textures made resident
|
||||
/// costs their count, not every resource's.
|
||||
textures: Vec<u32>,
|
||||
/// The heaps the encoder used, each with the render stages it used it in and the number of
|
||||
/// the first of its textures not made resident yet (`Heap::textures_from`).
|
||||
heaps: Vec<HeapUse>,
|
||||
/// Each heap of `heaps` by its place there.
|
||||
heap_places: KeyMap<Heap, usize>,
|
||||
/// A command buffer's: the device's live buffers at its commit, which an address in no
|
||||
/// resource made resident resolves against (`live_buffers.rs`).
|
||||
live: Option<Arc<LiveTable>>,
|
||||
/// The module docs' generation: 0 while it holds nothing it was given, else one no other
|
||||
/// residency of the process had, drawn at its last change.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
/// A heap an encoder used (`Residency::heaps`).
|
||||
@@ -119,6 +151,44 @@ impl Residency {
|
||||
self.used.is_empty() && self.heaps.is_empty() && self.live.is_none()
|
||||
}
|
||||
|
||||
/// Its generation (the module docs): equal to another residency's only where neither changed
|
||||
/// since one was cloned from the other, or both hold nothing they were given.
|
||||
pub(super) fn generation(&self) -> u64 {
|
||||
self.generation
|
||||
}
|
||||
|
||||
/// Whether each indirect command buffer made resident holds its ID's slot as `used`, the bind
|
||||
/// state's used resources made of it ([`used_resources`](Self::used_resources)), states: a
|
||||
/// buffer made later with the ID takes the slot (`address.rs`) without changing the residency.
|
||||
pub(super) fn holds_slots_as(&self, used: &[UsedResource]) -> bool {
|
||||
self.indirect.iter().all(|&token| {
|
||||
let stated = used
|
||||
.get(token as usize)
|
||||
.map(|used| used.gpu_address.is_some());
|
||||
match self.used.get(token as usize) {
|
||||
Some((Used::IndirectCommandBuffer(icb), ..)) => stated == Some(icb.holds_id_slot()),
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The heap used at `heap`'s place in `heaps`, if the encoder used it.
|
||||
fn heap_use(&mut self, heap: &Heap) -> Option<&mut HeapUse> {
|
||||
let place = *self.heap_places.get(heap)?;
|
||||
self.heaps.get_mut(place)
|
||||
}
|
||||
|
||||
/// Note `heap`'s first use, in render `stages`, its textures before number `next` made
|
||||
/// resident.
|
||||
fn push_heap(&mut self, heap: &Heap, stages: RenderStages, next: u64) {
|
||||
self.heap_places.insert(heap.clone(), self.heaps.len());
|
||||
self.heaps.push(HeapUse {
|
||||
heap: heap.clone(),
|
||||
stages,
|
||||
next,
|
||||
});
|
||||
}
|
||||
|
||||
/// Make `resource` resident with `usage` in render `stages` (none for a compute encoder),
|
||||
/// joined to the usage and stages it had: the resource, when the encoder first uses it here
|
||||
/// (the caller then holds it until the command buffer completes).
|
||||
@@ -148,18 +218,20 @@ impl Residency {
|
||||
/// (the caller then holds them until the command buffer completes).
|
||||
pub(super) fn use_heap(&mut self, heap: &Heap, stages: RenderStages) -> Vec<Used> {
|
||||
let (textures, next) = heap.textures_from(0);
|
||||
let stages = match self.heaps.iter_mut().find(|used| used.heap == *heap) {
|
||||
let stages = match self.heap_use(heap) {
|
||||
Some(used) => {
|
||||
used.stages = used.stages.union(stages);
|
||||
let widened = used.stages.union(stages);
|
||||
let changed = widened != used.stages || used.next != next;
|
||||
used.stages = widened;
|
||||
used.next = next;
|
||||
used.stages
|
||||
if changed {
|
||||
self.generation = next_generation();
|
||||
}
|
||||
widened
|
||||
}
|
||||
None => {
|
||||
self.heaps.push(HeapUse {
|
||||
heap: heap.clone(),
|
||||
stages,
|
||||
next,
|
||||
});
|
||||
self.push_heap(heap, stages, next);
|
||||
self.generation = next_generation();
|
||||
stages
|
||||
}
|
||||
};
|
||||
@@ -199,6 +271,8 @@ impl Residency {
|
||||
let (textures, next) = used.heap.textures_from(used.next);
|
||||
used.next = next;
|
||||
made.extend(textures.into_iter().map(|texture| (texture, used.stages)));
|
||||
// The number it looks from on: what a later look reads.
|
||||
self.generation = next_generation();
|
||||
}
|
||||
made.into_iter()
|
||||
.filter_map(|(texture, stages)| {
|
||||
@@ -222,18 +296,17 @@ impl Residency {
|
||||
}
|
||||
for heap in &ended.heaps {
|
||||
let stages = reach(heap.stages);
|
||||
match self.heaps.iter_mut().find(|had| had.heap == heap.heap) {
|
||||
match self.heap_use(&heap.heap) {
|
||||
Some(had) => {
|
||||
had.stages = had.stages.union(stages);
|
||||
had.next = had.next.min(heap.next);
|
||||
}
|
||||
None => self.heaps.push(HeapUse {
|
||||
heap: heap.heap.clone(),
|
||||
stages,
|
||||
next: heap.next,
|
||||
}),
|
||||
None => self.push_heap(&heap.heap, stages, heap.next),
|
||||
}
|
||||
}
|
||||
if !ended.heaps.is_empty() {
|
||||
self.generation = next_generation();
|
||||
}
|
||||
}
|
||||
|
||||
/// The residency a compute command reaches, stated as a compute encoder's (no render
|
||||
@@ -246,6 +319,9 @@ impl Residency {
|
||||
for heap in &mut self.heaps {
|
||||
heap.stages = RenderStages::empty();
|
||||
}
|
||||
if !self.is_empty() {
|
||||
self.generation = next_generation();
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -276,19 +352,30 @@ impl Residency {
|
||||
pub(super) fn past<'a>(&'a self, other: &'a Residency) -> impl Iterator<Item = &'a Used> {
|
||||
(self.used.iter())
|
||||
.map(|(used, ..)| used)
|
||||
.filter(|used| !other.used.iter().any(|(had, ..)| same(had, used)))
|
||||
.filter(|used| !other.tokens.contains_key(used))
|
||||
}
|
||||
|
||||
/// `used` resident with `usage` in `stages`, joined to the usage and stages it had: `used`,
|
||||
/// when it is new here.
|
||||
fn join(&mut self, used: Used, usage: ResourceUsage, stages: RenderStages) -> Option<Used> {
|
||||
let had = self.used.iter_mut().find(|(had, ..)| same(had, &used));
|
||||
if let Some((_, had_usage, had_stages)) = had {
|
||||
*had_usage = had_usage.union(usage);
|
||||
*had_stages = had_stages.union(stages);
|
||||
if let Some(&token) = self.tokens.get(&used) {
|
||||
let (_, had_usage, had_stages) = &mut self.used[token as usize];
|
||||
let (usage, stages) = (had_usage.union(usage), had_stages.union(stages));
|
||||
if (usage, stages) != (*had_usage, *had_stages) {
|
||||
(*had_usage, *had_stages) = (usage, stages);
|
||||
self.generation = next_generation();
|
||||
}
|
||||
return None;
|
||||
}
|
||||
let token = u32::try_from(self.used.len()).expect("fewer than 2^32 resources resident");
|
||||
match used {
|
||||
Used::IndirectCommandBuffer(_) => self.indirect.push(token),
|
||||
Used::Texture(_) => self.textures.push(token),
|
||||
Used::Buffer(_) | Used::Heap { .. } => {}
|
||||
}
|
||||
self.tokens.insert(used.clone(), token);
|
||||
self.used.push((used.clone(), usage, stages));
|
||||
self.generation = next_generation();
|
||||
Some(used)
|
||||
}
|
||||
|
||||
@@ -348,6 +435,7 @@ impl Residency {
|
||||
pub(super) fn with_live(self, live: Arc<LiveTable>) -> Residency {
|
||||
Residency {
|
||||
live: Some(live),
|
||||
generation: next_generation(),
|
||||
..self
|
||||
}
|
||||
}
|
||||
@@ -356,7 +444,15 @@ impl Residency {
|
||||
/// holds no table of them, whose pages a release or a rebind lets go until the command
|
||||
/// buffer is first submitted.
|
||||
pub(super) fn without_live(self) -> Residency {
|
||||
Residency { live: None, ..self }
|
||||
let generation = match self.live {
|
||||
Some(_) => next_generation(),
|
||||
None => self.generation,
|
||||
};
|
||||
Residency {
|
||||
live: None,
|
||||
generation,
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// The ranges of its buffers, heaps (their own buffers) and indirect command buffers'
|
||||
@@ -404,53 +500,49 @@ impl Residency {
|
||||
/// ended encoders made resident, each with its usage and, for a render encoder, its render
|
||||
/// stages (a compute encoder names none).
|
||||
pub(super) fn shadows(&self, render: bool) -> Residency {
|
||||
let used = (self.used.iter())
|
||||
.filter(|(used, ..)| matches!(used, Used::Texture(t) if t.shadow().is_some()))
|
||||
.map(|(used, usage, stages)| {
|
||||
let stages = if render {
|
||||
*stages
|
||||
} else {
|
||||
RenderStages::empty()
|
||||
};
|
||||
(used.clone(), *usage, stages)
|
||||
})
|
||||
.collect();
|
||||
Residency {
|
||||
used,
|
||||
heaps: Vec::new(),
|
||||
live: None,
|
||||
let mut shadows = Residency::default();
|
||||
let shadowed = (self.used.iter())
|
||||
.filter(|(used, ..)| matches!(used, Used::Texture(t) if t.shadow().is_some()));
|
||||
for (used, usage, stages) in shadowed {
|
||||
let stages = match render {
|
||||
true => *stages,
|
||||
false => RenderStages::empty(),
|
||||
};
|
||||
shadows.join(used.clone(), *usage, stages);
|
||||
}
|
||||
shadows
|
||||
}
|
||||
|
||||
/// The textures made resident, each with its usage and render stages.
|
||||
fn resident_textures(&self) -> impl Iterator<Item = (&Texture, ResourceUsage, RenderStages)> {
|
||||
self.textures
|
||||
.iter()
|
||||
.filter_map(|&token| match self.used.get(token as usize) {
|
||||
Some((Used::Texture(texture), usage, stages)) => Some((texture, *usage, *stages)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The textures made resident.
|
||||
pub(super) fn textures(&self) -> impl Iterator<Item = &Texture> {
|
||||
self.used.iter().filter_map(|(used, ..)| match used {
|
||||
Used::Texture(texture) => Some(texture),
|
||||
Used::Buffer(_) | Used::Heap { .. } | Used::IndirectCommandBuffer(_) => None,
|
||||
})
|
||||
self.resident_textures().map(|(texture, ..)| texture)
|
||||
}
|
||||
|
||||
/// The textures made resident that a render command whose functions read texture handles
|
||||
/// from memory in render `stages` reaches: those made resident in one of those stages.
|
||||
pub(super) fn textures_reached(&self, stages: RenderStages) -> impl Iterator<Item = &Texture> {
|
||||
self.used
|
||||
.iter()
|
||||
.filter_map(move |(used, _, made)| match used {
|
||||
Used::Texture(texture) if made.intersects(stages) => Some(texture),
|
||||
_ => None,
|
||||
})
|
||||
self.resident_textures()
|
||||
.filter(move |(_, _, made)| made.intersects(stages))
|
||||
.map(|(texture, ..)| texture)
|
||||
}
|
||||
|
||||
/// The textures made resident, each with whether a function's use of it may write: its
|
||||
/// usage writes, or neither reads nor writes, which a plan takes as both (the plan's used
|
||||
/// resources, `metal2vulkan::bind`).
|
||||
pub(super) fn textures_written(&self) -> impl Iterator<Item = (&Texture, bool)> {
|
||||
self.used.iter().filter_map(|(used, usage, _)| match used {
|
||||
Used::Texture(texture) => {
|
||||
let reads = usage.intersects(ResourceUsage::READ | ResourceUsage::SAMPLE);
|
||||
Some((texture, usage.contains(ResourceUsage::WRITE) || !reads))
|
||||
}
|
||||
Used::Buffer(_) | Used::Heap { .. } | Used::IndirectCommandBuffer(_) => None,
|
||||
self.resident_textures().map(|(texture, usage, _)| {
|
||||
let reads = usage.intersects(ResourceUsage::READ | ResourceUsage::SAMPLE);
|
||||
(texture, usage.contains(ResourceUsage::WRITE) || !reads)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -469,14 +561,30 @@ impl Residency {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are one resource.
|
||||
fn same(a: &Used, b: &Used) -> bool {
|
||||
match (a, b) {
|
||||
(Used::Buffer(a), Used::Buffer(b)) => a == b,
|
||||
(Used::Texture(a), Used::Texture(b)) => a == b,
|
||||
(Used::Heap { heap: a, .. }, Used::Heap { heap: b, .. }) => a == b,
|
||||
(Used::IndirectCommandBuffer(a), Used::IndirectCommandBuffer(b)) => a == b,
|
||||
_ => false,
|
||||
// Two are equal where they are one resource: a heap by the heap alone.
|
||||
impl PartialEq for Used {
|
||||
fn eq(&self, other: &Used) -> bool {
|
||||
match (self, other) {
|
||||
(Used::Buffer(a), Used::Buffer(b)) => a == b,
|
||||
(Used::Texture(a), Used::Texture(b)) => a == b,
|
||||
(Used::Heap { heap: a, .. }, Used::Heap { heap: b, .. }) => a == b,
|
||||
(Used::IndirectCommandBuffer(a), Used::IndirectCommandBuffer(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Used {}
|
||||
|
||||
impl std::hash::Hash for Used {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
std::mem::discriminant(self).hash(state);
|
||||
match self {
|
||||
Used::Buffer(buffer) => buffer.hash(state),
|
||||
Used::Texture(texture) => texture.hash(state),
|
||||
Used::Heap { heap, .. } => heap.hash(state),
|
||||
Used::IndirectCommandBuffer(icb) => icb.hash(state),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -301,6 +301,8 @@ struct SchedulerShared {
|
||||
spared: AtomicU64,
|
||||
/// The sleeps on the GPU, of `sleeps` (the module docs).
|
||||
gpu_waits: AtomicU64,
|
||||
/// The passes the thread made.
|
||||
passes: AtomicU64,
|
||||
/// The device's nudge, where the thread waits for the GPU itself (the module docs).
|
||||
nudge: OnceLock<Nudge>,
|
||||
/// The device's cleared encoder logs (`replay.rs`): an encoder takes one, and its log comes
|
||||
@@ -509,6 +511,7 @@ impl Scheduler {
|
||||
wakings: Default::default(),
|
||||
spared: AtomicU64::new(0),
|
||||
gpu_waits: AtomicU64::new(0),
|
||||
passes: AtomicU64::new(0),
|
||||
nudge: OnceLock::new(),
|
||||
spare_logs: SpareLogs::default(),
|
||||
});
|
||||
@@ -687,6 +690,11 @@ impl Scheduler {
|
||||
)
|
||||
}
|
||||
|
||||
/// The passes the thread made so far (`WorkCounts::scheduler_passes`).
|
||||
pub(crate) fn passes(&self) -> u64 {
|
||||
self.shared.passes.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The device's cleared encoder logs (`replay.rs`).
|
||||
pub(crate) fn spare_logs(&self) -> &SpareLogs {
|
||||
&self.shared.spare_logs
|
||||
@@ -863,6 +871,7 @@ fn run_work(kind: Kind, work: Work) -> bool {
|
||||
/// exiting.
|
||||
fn round(shared: &SchedulerShared, left: &mut Left<Work>, passed: &mut Passed) -> bool {
|
||||
(shared.inbox).pass(|state, commits| {
|
||||
shared.passes.fetch_add(1, Ordering::Relaxed);
|
||||
pass(state, commits, (&mut *passed, &mut *left), &shared.awaits);
|
||||
!passed.exiting && left.is_empty() && !passed.more
|
||||
});
|
||||
|
||||
@@ -150,23 +150,41 @@ fn a_command_buffer_with_no_handler_finishes_where_its_completion_is_seen() {
|
||||
drop(device);
|
||||
}
|
||||
|
||||
/// [`ROUNDS`] command buffers of `queue`, each a fill of 16 bytes, with a scheduled handler where
|
||||
/// `handler`, each committed and waited for before the next: how many were scheduled where their
|
||||
/// last batch was submitted.
|
||||
fn scheduled_where_submitted(device: &Device, queue: &CommandQueue, handler: bool) -> u64 {
|
||||
/// What a command buffer of [`scheduled_where_submitted`] has besides its fill.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Besides {
|
||||
Nothing,
|
||||
ScheduledHandler,
|
||||
/// A scheduled signal of the shared event, of the round's number and one.
|
||||
ScheduledSignal,
|
||||
}
|
||||
|
||||
/// [`ROUNDS`] command buffers of `queue`, each a fill of 16 bytes with what `besides` says, each
|
||||
/// committed and waited for before the next: how many were scheduled where their last batch was
|
||||
/// submitted. Each scheduled signal set its value by its wait's return.
|
||||
fn scheduled_where_submitted(device: &Device, queue: &CommandQueue, besides: Besides) -> u64 {
|
||||
let target = device.new_buffer(16, ResourceOptions::shared()).unwrap();
|
||||
let event = device.new_shared_event().unwrap();
|
||||
let before = device.work_counts().scheduled_where_submitted;
|
||||
for round in 0..ROUNDS {
|
||||
let command_buffer = queue.command_buffer().unwrap();
|
||||
let mut blit = command_buffer.blit_command_encoder().unwrap();
|
||||
blit.fill_buffer(&target, 0..16, round as u8).unwrap();
|
||||
blit.end_encoding().unwrap();
|
||||
if handler {
|
||||
command_buffer
|
||||
match besides {
|
||||
Besides::Nothing => {}
|
||||
Besides::ScheduledHandler => command_buffer
|
||||
.add_scheduled_handler(Box::new(|_: &CommandBuffer| {}))
|
||||
.unwrap();
|
||||
.unwrap(),
|
||||
Besides::ScheduledSignal => command_buffer
|
||||
.encode_signal_event_scheduled(&event, round + 1)
|
||||
.unwrap(),
|
||||
}
|
||||
command_buffer.commit().unwrap();
|
||||
command_buffer.wait_until_scheduled().unwrap();
|
||||
if besides == Besides::ScheduledSignal {
|
||||
assert_eq!(event.signaled_value(), round + 1);
|
||||
}
|
||||
command_buffer.wait_until_completed().unwrap();
|
||||
}
|
||||
device.work_counts().scheduled_where_submitted - before
|
||||
@@ -174,18 +192,25 @@ fn scheduled_where_submitted(device: &Device, queue: &CommandQueue, handler: boo
|
||||
|
||||
/// Command buffers with no scheduled handler are scheduled where their last batch is submitted:
|
||||
/// at least one of [`ROUNDS`] (the one before's transition to `Completed` may still hold its
|
||||
/// queue's context as the next one's last batch goes, which is then posted behind it). Those with
|
||||
/// a scheduled handler never are.
|
||||
/// queue's context as the next one's last batch goes, which is then posted behind it), those with
|
||||
/// a scheduled signal too, which wakes no handler thread. Those with a scheduled handler never
|
||||
/// are.
|
||||
#[test]
|
||||
fn a_command_buffer_with_no_scheduled_handler_is_scheduled_where_submitted() {
|
||||
let scratch = Scratch::new();
|
||||
let device = device(&scratch.0);
|
||||
let queue = device.new_command_queue().unwrap();
|
||||
let plain = scheduled_where_submitted(&device, &queue, false);
|
||||
let plain = scheduled_where_submitted(&device, &queue, Besides::Nothing);
|
||||
println!("scheduled where submitted: {plain} of {ROUNDS} with no handler");
|
||||
assert!(plain >= 1, "none of {ROUNDS} was scheduled where submitted");
|
||||
let signalled = scheduled_where_submitted(&device, &queue, Besides::ScheduledSignal);
|
||||
println!("scheduled where submitted: {signalled} of {ROUNDS} with a scheduled signal");
|
||||
assert!(
|
||||
signalled >= 1,
|
||||
"none of {ROUNDS} was scheduled where submitted"
|
||||
);
|
||||
assert_eq!(
|
||||
scheduled_where_submitted(&device, &queue, true),
|
||||
scheduled_where_submitted(&device, &queue, Besides::ScheduledHandler),
|
||||
0,
|
||||
"a command buffer with a scheduled handler was scheduled off its queue's handler thread"
|
||||
);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
//! A shared event listener's thread (`event.rs`): none for a listener never asked a notification,
|
||||
//! started by the first, and the notifications run on it one after another in the order posted.
|
||||
|
||||
use crate::event::SharedEventListener;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// The longest a notification may take to run.
|
||||
const WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Listeners made, cloned and dropped without a notification start no thread.
|
||||
#[test]
|
||||
fn a_listener_never_asked_starts_no_thread() {
|
||||
let listeners: Vec<SharedEventListener> = (0..64).map(|_| SharedEventListener::new()).collect();
|
||||
let clones = listeners.clone();
|
||||
assert!(listeners.iter().all(|listener| !listener.started()));
|
||||
drop(clones);
|
||||
assert!(listeners.iter().all(|listener| !listener.started()));
|
||||
}
|
||||
|
||||
/// The first notification posted starts the thread; it and the later ones run there, off the
|
||||
/// posting thread, one thread for them all, in the order posted.
|
||||
#[test]
|
||||
fn the_first_notification_starts_the_thread() {
|
||||
let listener = SharedEventListener::new();
|
||||
let (send, receive) = mpsc::channel();
|
||||
for n in 0..8 {
|
||||
let send = send.clone();
|
||||
listener.post(Box::new(move || {
|
||||
let _ = send.send((n, std::thread::current().id()));
|
||||
}));
|
||||
assert!(listener.started(), "posted {n}");
|
||||
}
|
||||
let ran: Vec<_> = (0..8)
|
||||
.map(|_| receive.recv_timeout(WAIT).unwrap())
|
||||
.collect();
|
||||
let order: Vec<u32> = ran.iter().map(|&(n, _)| n).collect();
|
||||
assert_eq!(order, (0..8).collect::<Vec<_>>());
|
||||
let thread = ran[0].1;
|
||||
assert_ne!(thread, std::thread::current().id());
|
||||
assert!(ran.iter().all(|&(_, id)| id == thread), "one thread");
|
||||
}
|
||||
@@ -65,6 +65,7 @@ mod enables;
|
||||
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
|
||||
mod encoder_holds;
|
||||
mod error_kinds;
|
||||
mod event_listener;
|
||||
mod event_timeline;
|
||||
mod exactness;
|
||||
mod exit_guard;
|
||||
|
||||
@@ -206,6 +206,7 @@ pub(crate) struct Counters {
|
||||
set_zero_sets_found: AtomicU64,
|
||||
draw_shapes_reused: AtomicU64,
|
||||
dispatches_settled_as_before: AtomicU64,
|
||||
dispatches_planned_as_before: AtomicU64,
|
||||
baked_sampler_dispatches_apart: AtomicU64,
|
||||
host_deallocators_delayed: AtomicU64,
|
||||
host_import_releases_posted: AtomicU64,
|
||||
@@ -1488,6 +1489,13 @@ impl Counters {
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// A direct dispatch that settled a bind state of the shape its state's last direct dispatch
|
||||
/// planned and took what that one planned (`pipeline::Planned`).
|
||||
pub(crate) fn dispatch_planned_as_before(&self) {
|
||||
self.dispatches_planned_as_before
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// A dispatch of a variant that bakes samplers, its pipelines made, recorded in a
|
||||
/// `VkCommandBuffer` of its own (`RuntimeDriverDefect::ImmutableSamplersLostAfterCopies`).
|
||||
pub(crate) fn baked_sampler_dispatch_apart(&self) {
|
||||
@@ -2809,6 +2817,11 @@ pub struct WorkCounts {
|
||||
pub scheduler_wakes_host: u64,
|
||||
/// Sleeps that ended at the thread's longest wait with nothing having woken it.
|
||||
pub scheduler_sleep_slices: u64,
|
||||
/// Passes the scheduler's thread made over its order (`scheduler/mod.rs`): one takes in what
|
||||
/// was committed and submits what is ready; one more follows a submission check or a host
|
||||
/// step the thread ran without its lock, a waker's nudge during a pass, and a pass that
|
||||
/// stopped after a few submissions.
|
||||
pub scheduler_passes: u64,
|
||||
/// Of `scheduler_sleeps`, those on the GPU: in one wait for the event values every head's
|
||||
/// checks wait for to land, or for the scheduler's nudge, which a commit, a host signal or a
|
||||
/// stop signals (`scheduler/mod.rs`; not on MoltenVK). A value landed wakes it as a
|
||||
@@ -3229,10 +3242,19 @@ pub struct WorkCounts {
|
||||
/// Compute encoders' dispatches that took the bind state, variant, plan, commands and made
|
||||
/// `VkPipeline`s their encoder's last dispatch settled, rather than settling them again:
|
||||
/// those of the same pipeline state, dispatch, table (no call changed it since), threadgroup
|
||||
/// lengths, imageblock size and stage-in region, in an encoder that made nothing resident, of
|
||||
/// a state that made no visible-function table, while no no-copy buffer moved and no sampler
|
||||
/// state was made or went (`compute::DispatchMemo`).
|
||||
/// lengths, imageblock size and stage-in region, in an encoder whose residency did not change
|
||||
/// since (no resource made resident, no usage widened, no heap used), of a state that made no
|
||||
/// visible-function table, while no no-copy buffer moved, no sampler state was made or went
|
||||
/// and no buffer took a resident indirect command buffer's ID (`compute::DispatchMemo`).
|
||||
pub dispatches_settled_as_before: u64,
|
||||
/// Direct dispatches that settled their bind state again (another table, another residency,
|
||||
/// another encoder) into one of the shape their pipeline state's last direct dispatch that
|
||||
/// planned planned, of the same dispatch and buffer forms, and took that one's variant and
|
||||
/// plan rather than planning them again, and its regions' made `VkPipeline`s where their keys
|
||||
/// are the same (`pipeline::Planned`): a dispatch whose buffers' offsets alone moved, and an
|
||||
/// encoder's first dispatch of a state dispatched before, for two. Not counted in
|
||||
/// `dispatches_settled_as_before`.
|
||||
pub dispatches_planned_as_before: u64,
|
||||
/// Dispatches of a kernel's variant whose layout bakes immutable samplers (constexpr
|
||||
/// samplers'), their pipelines made, recorded in a `VkCommandBuffer` of their own, as a
|
||||
/// dispatch whose pipeline is still being made is (`pending_dispatch.rs`): on a device whose
|
||||
@@ -3955,6 +3977,7 @@ impl Device {
|
||||
scheduler_wakes_host: by_host,
|
||||
scheduler_sleep_slices: by_slice,
|
||||
scheduler_gpu_waits: gpu_waits,
|
||||
scheduler_passes: self.shared().scheduler.passes(),
|
||||
wakes_completion_waiters: completion_wakes,
|
||||
wakes_handler_threads: handler_wakes,
|
||||
wakes_command_buffer_waiters: command_buffer_wakes,
|
||||
@@ -4084,6 +4107,8 @@ impl Device {
|
||||
draw_shapes_reused: counters.draw_shapes_reused.load(Ordering::Relaxed),
|
||||
dispatches_settled_as_before: (counters.dispatches_settled_as_before)
|
||||
.load(Ordering::Relaxed),
|
||||
dispatches_planned_as_before: (counters.dispatches_planned_as_before)
|
||||
.load(Ordering::Relaxed),
|
||||
baked_sampler_dispatches_apart: (counters.baked_sampler_dispatches_apart)
|
||||
.load(Ordering::Relaxed),
|
||||
host_deallocators_delayed: counters.host_deallocators_delayed.load(Ordering::Relaxed),
|
||||
|
||||
@@ -4,16 +4,23 @@
|
||||
//! (`WorkCounts::dispatches_pushing_set_zero`); and what a dispatch settles, taken again by the
|
||||
//! encoder's next dispatch only where its inputs are the same (`WorkCounts::
|
||||
//! dispatches_settled_as_before`, `set_zero_sets_reused`). Each runs both ways
|
||||
//! (`draw_work::on_device_both_ways`).
|
||||
//! (`draw_work::on_device_both_ways`). And what a dispatch settles with what the encoder made
|
||||
//! resident: taken again only while the residency is unchanged, each dispatch's execution stating
|
||||
//! the resources resident as it was encoded.
|
||||
//!
|
||||
//! The kernel is the owned fixture `a4_index_word` (`out[t] = in[3t + 1]`).
|
||||
|
||||
use super::draw_work::{on_device_both_ways, pushes};
|
||||
use super::executions::on_device_with;
|
||||
use super::indirect_host_steps::state;
|
||||
use super::{buffer_with, read_buffer, WAIT};
|
||||
use metal2vulkan::bind::SamplerDescriptor;
|
||||
use metal2vulkan::metal::ResourceUsage;
|
||||
use metal2vulkan_runtime::{CommandBufferStatus, ResourceRef, Size, WorkCounts};
|
||||
use metal2vulkan::bind::{SamplerDescriptor, UsedClass, UsedShape};
|
||||
use metal2vulkan::metal::{IndirectCommandType, ResourceUsage};
|
||||
use metal2vulkan_runtime::{
|
||||
CommandBufferStatus, IdPlacement, IndirectCommandBufferDescriptor, ResourceOptions,
|
||||
ResourceRef, Size, WorkCounts,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// `after`'s count of `count` less `before`'s.
|
||||
fn grew(before: &WorkCounts, after: &WorkCounts, count: fn(&WorkCounts) -> u64) -> u64 {
|
||||
@@ -82,15 +89,15 @@ struct Step {
|
||||
|
||||
/// A compute encoder's dispatch takes the bind state, variant, plan, commands and made pipelines
|
||||
/// its last dispatch settled only where it has the same inputs
|
||||
/// (`WorkCounts::dispatches_settled_as_before`): a dispatch again of an unchanged state takes
|
||||
/// them; one after a change of a buffer's offset, of the grid, after a sampler state was made, of
|
||||
/// another pipeline state of the same kernel, or in an encoder that made a buffer resident,
|
||||
/// settles again. Set 0 is apart from that memo: a dispatch binds the last set 0 wherever it
|
||||
/// writes the same descriptors into a set of the same layout (`WorkCounts::set_zero_sets_reused`),
|
||||
/// so each dispatch that settles as before binds it, where the device binds set 0, and the first
|
||||
/// does not; whether a changed offset or grid changes the set's writes is the variant's (an
|
||||
/// offset may be push data). Every dispatch writes its words. Both ways
|
||||
/// ([`on_device_both_ways`]).
|
||||
/// (`WorkCounts::dispatches_settled_as_before`): a dispatch again of an unchanged state takes them;
|
||||
/// one after a change of a buffer's offset, of the grid, after a sampler state was made, of another
|
||||
/// pipeline state of the same kernel, or after a buffer was made resident, settles again
|
||||
/// ([`dispatches_take_what_they_settled_only_with_the_same_residency`]). Set 0 is apart from that
|
||||
/// memo: a dispatch binds the last set 0 wherever it writes the same descriptors into a set of the
|
||||
/// same layout (`WorkCounts::set_zero_sets_reused`), so each dispatch that settles as before binds
|
||||
/// it, where the device binds set 0, and the first does not; whether a changed offset or grid
|
||||
/// changes the set's writes is the variant's (an offset may be push data). Every dispatch writes
|
||||
/// its words. Both ways ([`on_device_both_ways`]).
|
||||
#[test]
|
||||
fn dispatches_settle_again_only_where_their_inputs_changed() {
|
||||
on_device_both_ways(|device| {
|
||||
@@ -219,3 +226,299 @@ fn dispatches_settle_again_only_where_their_inputs_changed() {
|
||||
assert_eq!(words, expected);
|
||||
});
|
||||
}
|
||||
|
||||
/// What one dispatch of [`dispatches_take_what_they_settled_only_with_the_same_residency`]
|
||||
/// changed before it ran, the usages resident as it was encoded, by token, and whether it takes
|
||||
/// what the dispatch before it settled.
|
||||
struct Resident {
|
||||
change: &'static str,
|
||||
usages: &'static [ResourceUsage],
|
||||
as_before: bool,
|
||||
}
|
||||
|
||||
/// A compute encoder's dispatch takes what its last dispatch settled with what the encoder made
|
||||
/// resident only while that is unchanged (`WorkCounts::dispatches_settled_as_before`), and each
|
||||
/// dispatch's execution states the resources resident as it was encoded: a dispatch after a
|
||||
/// resource made resident, a usage widened, or a buffer made later at a resident indirect command
|
||||
/// buffer's ID (which then reaches it no more) settles again with the residency of then, and the
|
||||
/// next dispatch takes that; a resource made resident again with a usage it had changes nothing.
|
||||
/// Every dispatch writes its words, those that settled as before as those that did not.
|
||||
#[test]
|
||||
fn dispatches_take_what_they_settled_only_with_the_same_residency() {
|
||||
const READ: ResourceUsage = ResourceUsage::READ;
|
||||
const BOTH: ResourceUsage = ResourceUsage::READ.union(ResourceUsage::WRITE);
|
||||
on_device_with(
|
||||
|options| options.record_executions = true,
|
||||
|device| {
|
||||
let kernel = state(device, "a4_index_word", false);
|
||||
let words = 3 * THREADS;
|
||||
let input: Vec<u8> = (0..words as u32).flat_map(u32::to_le_bytes).collect();
|
||||
let input = buffer_with(device, &input).unwrap();
|
||||
let out = buffer_with(device, &vec![0; (4 * THREADS) as usize]).unwrap();
|
||||
let first = buffer_with(device, &[0; 64]).unwrap();
|
||||
let second = buffer_with(device, &[0; 64]).unwrap();
|
||||
let mut descriptor = IndirectCommandBufferDescriptor::new();
|
||||
descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH;
|
||||
descriptor.max_kernel_buffer_bind_count = 2;
|
||||
let icb = device
|
||||
.new_indirect_command_buffer(&descriptor, 4, ResourceOptions::shared())
|
||||
.unwrap();
|
||||
let mut taken = None;
|
||||
let queue = device.new_command_queue().unwrap();
|
||||
let command_buffer = queue.command_buffer().unwrap();
|
||||
let mut encoder = command_buffer.compute_command_encoder().unwrap();
|
||||
encoder.set_compute_pipeline_state(&kernel).unwrap();
|
||||
encoder.set_buffer(Some(&input), 0, 0).unwrap();
|
||||
encoder.set_buffer(Some(&out), 0, 1).unwrap();
|
||||
let steps = [
|
||||
Resident {
|
||||
change: "the first",
|
||||
usages: &[],
|
||||
as_before: false,
|
||||
},
|
||||
Resident {
|
||||
change: "nothing",
|
||||
usages: &[],
|
||||
as_before: true,
|
||||
},
|
||||
Resident {
|
||||
change: "a buffer made resident",
|
||||
usages: &[READ],
|
||||
as_before: false,
|
||||
},
|
||||
Resident {
|
||||
change: "nothing, it resident",
|
||||
usages: &[READ],
|
||||
as_before: true,
|
||||
},
|
||||
Resident {
|
||||
change: "it made resident again with its usage",
|
||||
usages: &[READ],
|
||||
as_before: true,
|
||||
},
|
||||
Resident {
|
||||
change: "its usage widened",
|
||||
usages: &[BOTH],
|
||||
as_before: false,
|
||||
},
|
||||
Resident {
|
||||
change: "another buffer made resident",
|
||||
usages: &[BOTH, READ],
|
||||
as_before: false,
|
||||
},
|
||||
Resident {
|
||||
change: "nothing, both resident",
|
||||
usages: &[BOTH, READ],
|
||||
as_before: true,
|
||||
},
|
||||
Resident {
|
||||
change: "an indirect command buffer made resident",
|
||||
usages: &[BOTH, READ, READ],
|
||||
as_before: false,
|
||||
},
|
||||
Resident {
|
||||
change: "nothing, it resident too",
|
||||
usages: &[BOTH, READ, READ],
|
||||
as_before: true,
|
||||
},
|
||||
Resident {
|
||||
change: "a buffer made at its ID",
|
||||
usages: &[BOTH, READ, READ],
|
||||
as_before: false,
|
||||
},
|
||||
Resident {
|
||||
change: "nothing, its ID taken",
|
||||
usages: &[BOTH, READ, READ],
|
||||
as_before: true,
|
||||
},
|
||||
];
|
||||
let mut settled = Vec::new();
|
||||
for step in &steps {
|
||||
match step.change {
|
||||
"a buffer made resident" | "it made resident again with its usage" => encoder
|
||||
.use_resource(ResourceRef::Buffer(&first), READ)
|
||||
.unwrap(),
|
||||
"its usage widened" => encoder
|
||||
.use_resource(ResourceRef::Buffer(&first), ResourceUsage::WRITE)
|
||||
.unwrap(),
|
||||
"another buffer made resident" => encoder
|
||||
.use_resources(&[ResourceRef::Buffer(&second)], READ)
|
||||
.unwrap(),
|
||||
"an indirect command buffer made resident" => {
|
||||
encoder.use_resource(icb.as_resource(), READ).unwrap();
|
||||
}
|
||||
"a buffer made at its ID" => {
|
||||
let mut placed = descriptor;
|
||||
placed.placement = IdPlacement::At(icb.gpu_resource_id());
|
||||
let made = device
|
||||
.new_indirect_command_buffer(&placed, 4, ResourceOptions::shared())
|
||||
.unwrap();
|
||||
taken = Some(made);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let before = device.work_counts();
|
||||
encoder
|
||||
.dispatch_threads(Size::new(THREADS, 1, 1), Size::new(THREADS, 1, 1))
|
||||
.unwrap();
|
||||
let after = device.work_counts();
|
||||
settled.push((
|
||||
step.change,
|
||||
grew(&before, &after, |c| c.dispatches_settled_as_before),
|
||||
));
|
||||
}
|
||||
encoder.end_encoding().unwrap();
|
||||
command_buffer.commit().unwrap();
|
||||
command_buffer.wait_until_completed_for(WAIT).unwrap();
|
||||
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
|
||||
drop(taken);
|
||||
let want: Vec<_> = (steps.iter())
|
||||
.map(|step| (step.change, u64::from(step.as_before)))
|
||||
.collect();
|
||||
assert_eq!(settled, want);
|
||||
let executions = command_buffer.executions();
|
||||
assert_eq!(executions.len(), steps.len());
|
||||
for (step, execution) in steps.iter().zip(&executions) {
|
||||
let want: BTreeMap<u32, (UsedClass, ResourceUsage)> = (0u32..)
|
||||
.zip(step.usages)
|
||||
.map(|(token, &usage)| (token, (UsedClass::Buffer, usage)))
|
||||
.collect();
|
||||
let used: BTreeMap<u32, (UsedClass, ResourceUsage)> = (execution.shape().used)
|
||||
.iter()
|
||||
.map(|(&token, used): (&u32, &UsedShape)| (token, (used.class, used.usage)))
|
||||
.collect();
|
||||
assert_eq!(used, want, "{}", step.change);
|
||||
}
|
||||
let words: Vec<u32> = read_buffer(&out, 0, 4 * THREADS)
|
||||
.unwrap()
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|word| u32::from_le_bytes(*word))
|
||||
.collect();
|
||||
let want: Vec<u32> = (0..THREADS as u32).map(|t| 3 * t + 1).collect();
|
||||
assert_eq!(words, want);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// What one dispatch of [`dispatches_take_what_their_state_planned_for_the_same_shape`] changed
|
||||
/// before it ran, where it writes, and whether it took what its state's last dispatch that planned
|
||||
/// planned (`WorkCounts::dispatches_planned_as_before`) or what the encoder's last dispatch
|
||||
/// settled (`dispatches_settled_as_before`).
|
||||
struct Planning {
|
||||
change: &'static str,
|
||||
at: u64,
|
||||
threads: u64,
|
||||
planned: bool,
|
||||
settled: bool,
|
||||
}
|
||||
|
||||
/// A dispatch whose bind state has the shape its pipeline state's last direct dispatch planned,
|
||||
/// of the same grid, takes that one's variant, plan and made pipelines: one whose buffer's offset
|
||||
/// alone moved, and another encoder's first dispatch of the state. A grid or a resource made
|
||||
/// resident plans again, and the next dispatch of the new shape takes that. Every dispatch writes
|
||||
/// its words. Both ways ([`on_device_both_ways`]).
|
||||
#[test]
|
||||
fn dispatches_take_what_their_state_planned_for_the_same_shape() {
|
||||
on_device_both_ways(|device| {
|
||||
let kernel = state(device, "a4_index_word", false);
|
||||
let input: Vec<u8> = (0..3 * 2 * THREADS as u32)
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let input = buffer_with(device, &input).unwrap();
|
||||
const WORDS: u64 = 12 * THREADS;
|
||||
let out = buffer_with(device, &vec![0; (4 * WORDS) as usize]).unwrap();
|
||||
let queue = device.new_command_queue().unwrap();
|
||||
let command_buffer = queue.command_buffer().unwrap();
|
||||
let step = |change, at, threads, (planned, settled)| Planning {
|
||||
change,
|
||||
at,
|
||||
threads,
|
||||
planned,
|
||||
settled,
|
||||
};
|
||||
let encoders = [
|
||||
vec![
|
||||
step("the first", 0, THREADS, (false, false)),
|
||||
step("out's offset", THREADS, THREADS, (true, false)),
|
||||
step("the grid", 2 * THREADS, 2 * THREADS, (false, false)),
|
||||
step(
|
||||
"out's offset again",
|
||||
4 * THREADS,
|
||||
2 * THREADS,
|
||||
(true, false),
|
||||
),
|
||||
],
|
||||
vec![
|
||||
step("another encoder", 6 * THREADS, 2 * THREADS, (true, false)),
|
||||
step(
|
||||
"a buffer made resident",
|
||||
8 * THREADS,
|
||||
2 * THREADS,
|
||||
(false, false),
|
||||
),
|
||||
step(
|
||||
"out's offset, resident",
|
||||
10 * THREADS,
|
||||
2 * THREADS,
|
||||
(true, false),
|
||||
),
|
||||
step("nothing", 10 * THREADS, 2 * THREADS, (false, true)),
|
||||
],
|
||||
];
|
||||
let mut seen = Vec::new();
|
||||
for steps in &encoders {
|
||||
let mut encoder = command_buffer.compute_command_encoder().unwrap();
|
||||
encoder.set_compute_pipeline_state(&kernel).unwrap();
|
||||
encoder.set_buffer(Some(&input), 0, 0).unwrap();
|
||||
let mut bound = None;
|
||||
for step in steps {
|
||||
// Bound again only where it moved: a call that binds draws a new table stamp.
|
||||
if bound != Some(step.at) {
|
||||
encoder.set_buffer(Some(&out), 4 * step.at, 1).unwrap();
|
||||
bound = Some(step.at);
|
||||
}
|
||||
if step.change == "a buffer made resident" {
|
||||
encoder
|
||||
.use_resource(ResourceRef::Buffer(&input), ResourceUsage::READ)
|
||||
.unwrap();
|
||||
}
|
||||
let before = device.work_counts();
|
||||
encoder
|
||||
.dispatch_threads(Size::new(step.threads, 1, 1), Size::new(THREADS, 1, 1))
|
||||
.unwrap();
|
||||
let after = device.work_counts();
|
||||
let planned = grew(&before, &after, |c| c.dispatches_planned_as_before);
|
||||
let settled = grew(&before, &after, |c| c.dispatches_settled_as_before);
|
||||
seen.push((step.change, planned, settled));
|
||||
}
|
||||
encoder.end_encoding().unwrap();
|
||||
}
|
||||
command_buffer.commit().unwrap();
|
||||
command_buffer.wait_until_completed_for(WAIT).unwrap();
|
||||
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
|
||||
let steps: Vec<&Planning> = encoders.iter().flatten().collect();
|
||||
let want: Vec<_> = (steps.iter())
|
||||
.map(|step| {
|
||||
let (planned, settled) = (u64::from(step.planned), u64::from(step.settled));
|
||||
(step.change, planned, settled)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(seen, want);
|
||||
let words: Vec<u32> = read_buffer(&out, 0, 4 * WORDS)
|
||||
.unwrap()
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|word| u32::from_le_bytes(*word))
|
||||
.collect();
|
||||
let mut expected = vec![0u32; WORDS as usize];
|
||||
for step in &steps {
|
||||
for t in 0..step.threads {
|
||||
expected[(step.at + t) as usize] = 3 * t as u32 + 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(words, expected);
|
||||
});
|
||||
}
|
||||
@@ -597,7 +597,7 @@ fn listeners_hear_reached_and_later_values() {
|
||||
on_device(|device| {
|
||||
let queue = device.new_command_queue().unwrap();
|
||||
let event = device.new_shared_event().unwrap();
|
||||
let listener = SharedEventListener::new().unwrap();
|
||||
let listener = SharedEventListener::new();
|
||||
let (send, receive) = mpsc::channel();
|
||||
event.set_signaled_value(3);
|
||||
for (name, at) in [("passed", 2), ("later", 5)] {
|
||||
@@ -805,6 +805,129 @@ fn a_scheduled_handler_signals_a_shared_event() {
|
||||
});
|
||||
}
|
||||
|
||||
/// A command buffer's scheduled signal (`encode_signal_event_scheduled`) sets its value before the
|
||||
/// status reads `Scheduled`, before every scheduled handler runs (one added before it too) and
|
||||
/// before `wait_until_scheduled` returns, as Metal's does (an M3 Max, macOS 27.0.1), and releases
|
||||
/// another queue's wait for the value. A value below the event's changes nothing, and two signals
|
||||
/// end at the higher. One held for an event the host has not set is not scheduled, and its signal
|
||||
/// waits with it. Encoded with an encoder open it is refused (Metal asserts); after the commit it
|
||||
/// does nothing, as Metal's.
|
||||
#[test]
|
||||
fn a_scheduled_signal_sets_its_value_as_the_command_buffer_is_scheduled() {
|
||||
on_device(|device| {
|
||||
let (first, second) = (
|
||||
device.new_command_queue().unwrap(),
|
||||
device.new_command_queue().unwrap(),
|
||||
);
|
||||
// Before the status and every scheduled handler.
|
||||
let event = device.new_shared_event().unwrap();
|
||||
let command_buffer = first.command_buffer().unwrap();
|
||||
let (send, receive) = mpsc::channel();
|
||||
for name in ["added before", "added after"] {
|
||||
if name == "added after" {
|
||||
command_buffer
|
||||
.encode_signal_event_scheduled(&event, 5)
|
||||
.unwrap();
|
||||
}
|
||||
let (send, event) = (send.clone(), event.clone());
|
||||
command_buffer
|
||||
.add_scheduled_handler(Box::new(move |buffer: &CommandBuffer| {
|
||||
let _ = send.send((name, event.signaled_value(), buffer.status()));
|
||||
}))
|
||||
.unwrap();
|
||||
}
|
||||
command_buffer.commit().unwrap();
|
||||
command_buffer.wait_until_scheduled().unwrap();
|
||||
assert_eq!(
|
||||
event.signaled_value(),
|
||||
5,
|
||||
"at wait_until_scheduled's return"
|
||||
);
|
||||
let scheduled = CommandBufferStatus::Scheduled;
|
||||
assert_eq!(
|
||||
receive.recv_timeout(WAIT),
|
||||
Ok(("added before", 5, scheduled))
|
||||
);
|
||||
assert_eq!(
|
||||
receive.recv_timeout(WAIT),
|
||||
Ok(("added after", 5, scheduled))
|
||||
);
|
||||
completed(&command_buffer);
|
||||
|
||||
// Releasing a wait on another queue.
|
||||
let gate = device.new_shared_event().unwrap();
|
||||
let scratch = device.new_buffer(BIG, ResourceOptions::private()).unwrap();
|
||||
let waiting = second.command_buffer().unwrap();
|
||||
waiting
|
||||
.encode_wait_for_event(EventRef::from(&gate), 2)
|
||||
.unwrap();
|
||||
let mut encoder = waiting.blit_command_encoder().unwrap();
|
||||
encoder.fill_buffer(&scratch, 0..BIG, 2).unwrap();
|
||||
encoder.end_encoding().unwrap();
|
||||
waiting.commit().unwrap();
|
||||
let signalling = blit(&first, |encoder| {
|
||||
encoder.fill_buffer(&scratch, 0..BIG, 1).unwrap()
|
||||
});
|
||||
signalling.encode_signal_event_scheduled(&gate, 2).unwrap();
|
||||
signalling.commit().unwrap();
|
||||
completed(&signalling);
|
||||
completed(&waiting);
|
||||
assert_eq!(gate.signaled_value(), 2);
|
||||
|
||||
// Values only rise.
|
||||
let floor = device.new_shared_event().unwrap();
|
||||
floor.set_signaled_value(10);
|
||||
let rising = device.new_shared_event().unwrap();
|
||||
let command_buffer = first.command_buffer().unwrap();
|
||||
command_buffer
|
||||
.encode_signal_event_scheduled(&floor, 4)
|
||||
.unwrap();
|
||||
for value in [6, 3] {
|
||||
command_buffer
|
||||
.encode_signal_event_scheduled(&rising, value)
|
||||
.unwrap();
|
||||
}
|
||||
command_buffer.commit().unwrap();
|
||||
completed(&command_buffer);
|
||||
assert_eq!((floor.signaled_value(), rising.signaled_value()), (10, 6));
|
||||
|
||||
// Held for an event: not scheduled, and nor is its signal.
|
||||
let held_for = device.new_shared_event().unwrap();
|
||||
let later = device.new_shared_event().unwrap();
|
||||
let held = first.command_buffer().unwrap();
|
||||
held.encode_wait_for_event(EventRef::from(&held_for), 1)
|
||||
.unwrap();
|
||||
held.encode_signal_event_scheduled(&later, 3).unwrap();
|
||||
held.commit().unwrap();
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
assert_eq!(held.status(), CommandBufferStatus::Committed);
|
||||
assert_eq!(later.signaled_value(), 0);
|
||||
held_for.set_signaled_value(1);
|
||||
completed(&held);
|
||||
assert_eq!(later.signaled_value(), 3);
|
||||
|
||||
// Refused with an encoder open; after the commit, nothing.
|
||||
let command_buffer = first.command_buffer().unwrap();
|
||||
let mut encoder = command_buffer.blit_command_encoder().unwrap();
|
||||
encoder.fill_buffer(&scratch, 0..64, 1).unwrap();
|
||||
assert_eq!(
|
||||
command_buffer.encode_signal_event_scheduled(&later, 9),
|
||||
Err(invalid(
|
||||
"encode_signal_event_scheduled",
|
||||
Problem::EncoderOpen
|
||||
))
|
||||
);
|
||||
encoder.end_encoding().unwrap();
|
||||
command_buffer.commit().unwrap();
|
||||
assert_eq!(
|
||||
command_buffer.encode_signal_event_scheduled(&later, 9),
|
||||
Ok(())
|
||||
);
|
||||
completed(&command_buffer);
|
||||
assert_eq!(later.signaled_value(), 3);
|
||||
});
|
||||
}
|
||||
|
||||
/// A program that waits for its last command buffer and then drops its last handles destroys the
|
||||
/// device on its own thread, before the drop returns. The device's instance holds the round's
|
||||
/// message list (its debug messenger's sink) until the instance is destroyed, the teardown's last
|
||||
|
||||
@@ -579,7 +579,7 @@ fn child() {
|
||||
}
|
||||
"listener_exits" => {
|
||||
let event = device.new_shared_event().unwrap();
|
||||
let listener = SharedEventListener::new().unwrap();
|
||||
let listener = SharedEventListener::new();
|
||||
let in_listener = messages.clone();
|
||||
event.notify_listener(
|
||||
&listener,
|
||||
@@ -627,7 +627,7 @@ fn child() {
|
||||
{
|
||||
let queue = device.new_command_queue().unwrap();
|
||||
let event = device.new_shared_event().unwrap();
|
||||
let listener = SharedEventListener::new().unwrap();
|
||||
let listener = SharedEventListener::new();
|
||||
event.notify_listener(
|
||||
&listener,
|
||||
1,
|
||||
|
||||
@@ -138,6 +138,7 @@ narrow refusal that the call's rustdoc describes.
|
||||
| `compute_encoder` | `computeCommandEncoder` | `CommandBuffer::compute_command_encoder` |
|
||||
| `device` | `device` | `CommandBuffer::device` |
|
||||
| `encode_signal` | `encodeSignalEvent:value:` | `CommandBuffer::encode_signal_event` |
|
||||
| `encode_signal_when_scheduled` | `encodeSignalEventScheduled:value:` (SPI) | `CommandBuffer::encode_signal_event_scheduled` |
|
||||
| `encode_wait` | `encodeWaitForEvent:value:` | `CommandBuffer::encode_wait_for_event` |
|
||||
| `error` | `error` | `CommandBuffer::error` |
|
||||
| `render_encoder` | `renderCommandEncoderWithDescriptor:` | `CommandBuffer::render_command_encoder` *(partial)* |
|
||||
@@ -577,7 +578,6 @@ These items have no single runtime call. The consumer builds them from the calls
|
||||
| Item | How |
|
||||
|---|---|
|
||||
| `BlitCmd::CopyTextureRegionOptions` | options 0 is `BlitCommandEncoder::copy_from_texture_to_texture`; a public `BlitOption` goes through a buffer (`copy_from_texture_to_buffer`, then `copy_from_buffer_to_texture`) |
|
||||
| `CommandBuffer::encode_signal_when_scheduled` | `CommandBuffer::add_scheduled_handler`, whose handler calls `SharedEvent::set_signaled_value` |
|
||||
| `RateMap::reset` | a new map: `Device::new_rasterization_rate_map` |
|
||||
| `RenderCmd::SetDepthClipModeSpi` | the public `RenderCommandEncoder::set_depth_clip_mode` |
|
||||
| `RenderCmd::SetPrimitiveRestartEnabled` | `RenderCommandEncoder::set_primitive_restart_enabled`: indexed strips restart at the index as Metal takes it for their index type, and only there |
|
||||
|
||||
Reference in new issue
Block a user