Runtime: a pipeline state answers before the driver's create of its main pipeline, which finish_pipeline makes

What: new_compute_pipeline_state and new_render_pipeline_state now do everything up to the
driver's create of the state's main pipeline (every lowering, every refusal and Metal's own errors,
the shader modules, the samplers' numbering) and answer. The main pipeline is the one VkPipeline
whose key the descriptor holds: a tiling kernel's tiles', an image-only kernel's square
workgroups', an observing kernel's at its required size or declared bound where it takes no
threadgroup memory length; a render content's triangle or patch class, and the line or point class
its inputPrimitiveTopology names. ComputePipelineState::finish_pipeline and
RenderPipelineState::finish_pipeline, which have no Metal counterpart, make it on the calling
thread through the device's pipeline cache. A second call makes nothing. A dispatch or a draw
before it waits for the make in flight or makes the pipeline itself, a first-use wait
(first_use_unfinished_waits), and records what it records with the pipeline made: a state never
finished runs the same. A kernel past the stage bound still makes its main pipeline in the
creation, so StageUnfilled and StageSize reach the helper at the make. Render's main pipelines sit
in a new cell (render::Main); compute's use the kernel's variant cells, started as
VariantStart::Finish. Metrics: finished_pipelines, finished_pipeline_nanos, failed_finishes, and
first_use_unfinished_waits with its time and longest wait. The harness and the replay player call
finish_pipeline inside their make, so their make times and VkPipeline counts still hold the
driver's share.

No Metal answer moves: every answer getter reads values fixed before the driver's create. The
`made` bit of dispatch_variant, no answer of Metal's, reads false until a finish, a
prepare_dispatch call or a dispatch made the main pipeline; the key does not move.

A driver's create that fails after the answer is not kept: finish_pipeline returns Error::Vulkan
and counts failed_finishes, and the first dispatch or draw that needs the pipeline makes it again
and returns the Error::Vulkan if that fails too. That is a new known gap in the runtime README
("Known gaps of pipeline states"), where Metal fails the creation instead. docs/REFUSALS.md does
not change (no refusal moved; refusal_surface --check passes).

Why: on the consumer's first launch the guest waits on the runtime's pipeline creates, and the
driver's compile is most of a make. Answering first lets the consumer run that compile beside the
guest's own work.

Tests: translate.rs every_device_answers_a_state_before_its_main_pipeline_is_made and draw.rs
every_device_answers_a_render_state_before_its_main_pipeline_is_made check that no pipeline is
created at the answer, that every answer is equal before and after finish_pipeline, that the
finish makes the main pipeline once (VariantStart::Finish on compute), that a second finish and
the first use make nothing, and that a state never finished makes its pipeline at its first use,
a first-use wait. Without the form both are expected to fail at their first check, since the
creation made the main pipeline (not run against the old creation).
translate.rs every_device_makes_a_state_s_main_pipeline_once_across_its_finish_and_a_preparation
checks that a prepare_dispatch after the finish makes no second VkPipeline (pipelines_created
unchanged), that a finish after a preparation that made it makes nothing, and that the two called
at once on two threads make one pipeline between them, so a `made` read false costs no second
driver create. main_cells.rs (no device) checks a failed finish
that keeps nothing, then a draw that makes the pipeline again, and a draw during a finish that
waits for its make. The existing device tests' state helpers finish their states.

VariantStart gains a variant: 0 hits for VariantStart in the consumer's checkout at 92ffbed817.

Verified at tree 0a330f8709, this commit's tree (the jobs ran at a scratch commit of that tree):
- compile check m3-max-68090: api_signatures and refusal surface --check, cargo fmt --check,
  clippy -D warnings plain, under --cfg m2v_gpu and under --cfg m2v_cpu_icd, workspace Rustdoc
  -D warnings and scripts/api-docs, all exit 0; then metal2vulkan-runtime's suite under
  --cfg m2v_cpu_icd on lavapipe (llvmpipe, LLVM 23.1.1) under VK_LAYER_KHRONOS_validation
  1.4.363.0: 652 passed, 3 skipped, the layer listed as the device's validation tool.
- RTX 3090 (NVIDIA 620.70.06), m3-max-68091: metal2vulkan-runtime's suite under --cfg m2v_gpu
  under the same layer: 654 passed, 3 skipped. The answer tests printed: compute answered with
  no pipeline made and finished after the answer in 3.0 ms, a never-finished state's dispatch
  made its pipeline in 1.2 ms; render finished in 2.4 ms, a never-finished state's draw made its
  pipeline in 0.09 ms. These are single test runs under the layer, not timings.
This commit is contained in:
Anees Iqbal committed 2026-11-22 09:25:19 -08:00
1 parent 91fed9449c
commit 951285e7a7
17 files changed
+1193 -252

No files matched your search

+10 -4
View File
@@ -530,9 +530,12 @@ impl crate::ComputeDevice for Device {
) -> Result<rt::ComputePipelineState> {
let function = plan::with_private(function.clone(), private);
let descriptor = rt::ComputePipelineDescriptor::new(rt::StageSource::Function(function));
(self.device)
let state = (self.device)
.new_compute_pipeline_state(&descriptor, |samplers| self.sampler_ids(samplers))
.map_err(error)
.map_err(error)?;
// The whole make, as a consumer makes a state: the creation, then its main pipeline.
state.finish_pipeline().map_err(error)?;
Ok(state)
}
fn new_render_pipeline_state(
@@ -547,9 +550,12 @@ impl crate::ComputeDevice for Device {
descriptor.fragment = Some(rt::StageSource::Function(fragment.clone()));
descriptor.color_attachments[0] = Some(rt::ColorAttachmentDescriptor::new(color));
descriptor.raster_sample_count = samples;
(self.device)
let state = (self.device)
.new_render_pipeline_state(&descriptor, |samplers| self.sampler_ids(samplers))
.map_err(error)
.map_err(error)?;
// The whole make, as a consumer makes a state: the creation, then its main pipelines.
state.finish_pipeline().map_err(error)?;
Ok(state)
}
fn new_command_queue(&self) -> Result<rt::CommandQueue> {
+93 -54
View File
@@ -210,9 +210,11 @@ block's rule in Textures below), 0 where none went out; the pipeline cache's rep
bound and its blob writes skipped past it (`pipeline_caches_replaced`,
`pipeline_cache_writes_skipped`, The cache directory below); the dispatches that ran a kernel's
emulated-SIMD-group module (`emulated_simdgroup_dispatches`, Compute pipeline states below); the
compiled contents a state's make dropped because an equal one landed in the device's map first
(`kernel_makes_dropped`); the copies of resolve images into the buffers their textures lie over
(`resolve_copies` and `resolve_copy_bytes`, Render encoders below);
states' main pipelines their `finish_pipeline` calls made, with their time, and the calls whose
make failed (`finished_pipelines`, `finished_pipeline_nanos`, `failed_finishes`, Compute pipeline
states below); the compiled contents a state's make dropped because an equal one landed in the
device's map first (`kernel_makes_dropped`); the copies of resolve images into the buffers their
textures lie over (`resolve_copies` and `resolve_copy_bytes`, Render encoders below);
`gauges()` are live counts per kind of resource, every one zero after teardown, and
`handles_out`, 1 while a handle of the device is out (Teardown). They are relaxed atomics, always
on. What an encoder's commands count arrives when the encoder ends.
@@ -2557,13 +2559,14 @@ while the driver's exit handler waited on a lock, with every runtime thread alre
- a grid of a kernel that is image-only (`CompiledFunction::is_image_only`: it samples,
gathers or reads a texture, and loads, stores and updates atomically nothing through a
`device` pointer; `constant` loads and texture writes are allowed) in workgroups of 16 by 16
by 1 where it is one deep, on one `VkPipeline` made with the state, and of its tile (below)
where it is deeper, on one `VkPipeline` per tile, made at the kernel's first dispatch at that
tile, which waits for it, each thread's position the workgroup's origin plus its place in it,
with no decode. Those pipelines are kept with the kernel's others, at most one per tile of the
45 a rule's tile can be. A tile deeper than 64 runs as one row of its 256 threads (below);
- a grid of any other such kernel in tiles: workgroups of 256 threads on one `VkPipeline`, made
with the state, each one tile of the grid, which its region carries. A thread's position is
by 1 where it is one deep, on one `VkPipeline`, the state's main one (below), and of its
tile (below) where it is deeper, on one `VkPipeline` per tile, made at the kernel's first
dispatch at that tile, which waits for it, each thread's position the workgroup's origin plus
its place in it, with no decode. Those pipelines are kept with the kernel's others, at most
one per tile of the 45 a rule's tile can be. A tile deeper than 64 runs as one row of its 256
threads (below);
- a grid of any other such kernel in tiles: workgroups of 256 threads on one `VkPipeline`, the
state's main one, each one tile of the grid, which its region carries. A thread's position is
the tile's origin plus its index masked and shifted by the tile's sides, with no division.
A tile has power-of-two sides whose product is 256. The translator's `pipeline::grid_tile`
@@ -2574,7 +2577,7 @@ while the driver's exit handler waited on a lock, with every runtime thread alre
the fewest tiles partly past it, then the depth nearest the threadgroup's (the shallower of two
as near), then the most square in `x` and `y`, then the wider. So threadgroups of 8x8x4 over a
grid that 8x8x4 tiles divide run in 8x8x4, and threadgroups one deep in the square 16x16x1,
the pipeline made with the state, wherever 16x16x1 tiles divide the grid. Where the workgroups
the state's main pipeline, wherever 16x16x1 tiles divide the grid. Where the workgroups
do not divide the grid, the dispatch's regions are flagged ragged (the translator's
`NONUNIFORM`), and an invocation past the grid returns before the kernel's body: only there does
a thread compare its position with the grid's last thread, inside one branch on the flag. Every
@@ -2627,44 +2630,65 @@ while the driver's exit handler waited on a lock, with every runtime thread alre
zero grid, and its kernel takes the grid from its threadgroup count. Outside the tiles the packed
size is the pipeline's own workgroup size, so the kernel's `MultiRegion` constant stays at its
default, 0, and the kernel takes the size from its workgroup size, with no decode.
- What a state's creation is given it makes there, as Metal compiles a state when it is made:
every module (the kernel's, and its partial-threadgroups and emulated-SIMD-group variants), the
`VkPipeline` of a tiling kernel's tiles or of an image-only kernel's square workgroups, and,
where the kernel takes no threadgroup memory length from the encoder, an observing kernel's
`VkPipeline`s of a whole and of a ragged grid at the descriptor's
- What a state's creation is given it makes there, as Metal compiles a state when it is made, up
to the driver's create of its main pipeline: every module (the kernel's, and its
partial-threadgroups and emulated-SIMD-group variants), with every refusal and Metal's own
errors, and the samplers' numbering; then it answers. The main pipeline is the one `VkPipeline`
whose key the descriptor holds: a tiling kernel's tiles' or an image-only kernel's square
workgroups', or, where the kernel takes no threadgroup memory length from the encoder, an
observing kernel's of a whole and of a ragged grid at the descriptor's
`requiredThreadsPerThreadgroup`, or, where it sets none and the state declares a bound of
threads (the descriptor's `maxTotalThreadsPerThreadgroup` or the kernel's
`[[max_total_threads_per_threadgroup(n)]]`), at `[N, 1, 1]`, `N` the state's
`maxTotalThreadsPerThreadgroup`. The device's own limit is no declared bound, and a kernel's
bound of Metal's own 1024 is not told apart from none. A kernel's `VkPipeline` at a
threadgroup size and threadgroup memory lengths
only a dispatch gives is made at the consumer's `prepare_dispatch` call (below) or at the
dispatch: one per module, threadgroup size and threadgroup memory lengths, on the encoding
thread that first dispatches any of its states with them, which waits for it. Nothing the
runtime records depends on when a compile finishes: there is one recorded form, made after the
wait. Each such wait is counted in `Metrics::first_use_waits`, with its time in
`first_use_wait_nanos` and the longest in `first_use_wait_max_nanos`, and again by where it
waited, each with its count, time and longest: `first_use_variant_waits` (a kernel's pipeline
bound of Metal's own 1024 is not told apart from none. The consumer's `finish_pipeline` call
makes it after the answer (below); a kernel past the stage bound makes it at the creation
(Kernels past the stage bound, below). A kernel's `VkPipeline` at a threadgroup size and
threadgroup memory lengths only a dispatch gives is made at the consumer's `prepare_dispatch`
call (below) or at the dispatch: one per module, threadgroup size and threadgroup memory
lengths, on the encoding thread that first dispatches any of its states with them, which waits
for it. Nothing the runtime records depends on when a compile finishes: there is one recorded
form, made after the wait. Each such wait is counted in `Metrics::first_use_waits`, with its
time in `first_use_wait_nanos` and the longest in `first_use_wait_max_nanos`, and again by where
it waited, each with its count, time and longest: `first_use_variant_waits` (a kernel's pipeline
for a new workgroup size, threadgroup memory lengths or tiles), `first_use_line_waits` (a
render content's line-class pipeline), `first_use_point_waits` (its point-class pipeline) and
render content's line-class pipeline), `first_use_point_waits` (its point-class pipeline),
`first_use_raster_waits` (its pipeline under the depth clip mode `Clamp` or the triangle fill
mode `Lines`).
mode `Lines`) and `first_use_unfinished_waits` (a state's main pipeline, compute or render,
before its `finish_pipeline` made it).
No dispatch lowers a function. `Counters::variant_makes(from)` answers the kept makes of
kernels' `VkPipeline`s numbered `from` or later, the last 256 to end on the device, each a
`VariantMake`: its key (the `DispatchVariant` its dispatches answer), who started it
(`VariantStart`: the state's creation, a `prepare_dispatch` call, or a dispatch's first use),
when it began and ended in `host_time`, whether it made the pipeline, and the first-use waits
that waited for it, with when the earliest began. A wait on a make another thread started
found that make in flight. Neither type has a Metal counterpart.
(`VariantStart`: a `finish_pipeline` call, the state's creation for a kernel past the stage
bound, a `prepare_dispatch` call, or a dispatch's first use), when it began and ended in
`host_time`, whether it made the pipeline, and the first-use waits that waited for it, with
when the earliest began. A wait on a make another thread started found that make in flight.
Neither type has a Metal counterpart.
- `ComputePipelineState::finish_pipeline()` and `RenderPipelineState::finish_pipeline()` have no
Metal counterpart. Metal compiles a state when it is made, and the program waits for that
answer. Here the creation answers once everything that can refuse is done, and the driver's
create of the state's main pipelines is this call's, so a consumer can answer the program first
and let the driver's compile run beside the program's own work. rt starts no thread for it: the
consumer calls it on a thread of its own once it has answered. It makes each main pipeline
through the device's pipeline cache where it is neither made nor being made, so a second call
makes nothing, and so does a call for a state with no main pipeline or for a kernel past the
stage bound. A dispatch or a draw that needs a main pipeline first waits for the make in flight,
or makes the pipeline itself where none is, a first-use wait (`first_use_unfinished_waits`),
and records what it would have recorded with it made: a state never finished runs the same, its
first use making the pipeline. `Metrics::finished_pipelines` counts what the calls made, with
their time in `finished_pipeline_nanos`, the driver's side of a state's make, which the consumer
reads beside the time of its own two calls; `failed_finishes` counts the calls whose make
failed (Known gaps of pipeline states, below). Its only error is `Error::Vulkan`.
- `ComputePipelineState::prepare_dispatch(Dispatch, threads_per_threadgroup,
threadgroup_memory_lengths)` has no Metal counterpart: it is a hook for a consumer's pre-pass.
Metal compiles a compute state whole when the state is made, and so does the state's creation
here; but a kernel's `VkPipeline` waits for the dispatch's threadgroup size and threadgroup
memory lengths. A consumer that reads a command buffer's dispatches before it encodes them may
pass each one's own arguments: its grid as its call took it (`Dispatch::Threads` for
`dispatchThreads:`, `Dispatch::Threadgroups` for `dispatchThreadgroups:`, `Dispatch::Indirect`
for the indirect form), its threadgroup size, and the encoder's
`setThreadgroupMemoryLength:atIndex:` settings, in stream order, on threads of its own; rt
Metal compiles a compute state whole when the state is made; here the state's creation makes
every module, and a kernel's `VkPipeline`, but for the state's main one, waits for the
dispatch's threadgroup size and threadgroup memory lengths. A consumer that reads a command
buffer's dispatches before it encodes them may pass each one's own arguments: its grid as its
call took it (`Dispatch::Threads` for `dispatchThreads:`, `Dispatch::Threadgroups` for
`dispatchThreadgroups:`, `Dispatch::Indirect` for the indirect form), its threadgroup size, and
the encoder's `setThreadgroupMemoryLength:atIndex:` settings, in stream order, on threads of
its own; rt
starts none. The call decides what the dispatch runs as the dispatch decides it (one function
serves both), then makes that module's `VkPipeline`. It returns at once where that is made, or
another thread is making it. A make runs outside the kernel's lock, its variant marked
@@ -2967,6 +2991,17 @@ cache is answered compile-required on both.
### Known gaps of pipeline states
- A driver's create of a state's main pipeline can fail after the state has answered, where Metal
compiles the state before it answers and a program never meets a state it was given that cannot
run. Vulkan lets `vkCreateComputePipelines` and `vkCreateGraphicsPipelines` fail with
`VK_ERROR_OUT_OF_HOST_MEMORY`, `VK_ERROR_OUT_OF_DEVICE_MEMORY`, `VK_ERROR_UNKNOWN` or
`VK_ERROR_VALIDATION_FAILED` (and `VK_ERROR_INVALID_SHADER_NV`, of an extension the runtime does
not enable). `finish_pipeline` returns the failure as `Error::Vulkan`, keeps nothing and counts
it (`Metrics::failed_finishes`); the first dispatch or draw that needs the pipeline makes it
again, and where that make fails too, that dispatch or draw returns the `Error::Vulkan`. A
kernel past the stage bound makes its main pipeline at the state's creation (Kernels past the
stage bound, above): a make the stage bound refuses fails the creation, and any other failure
there is the first dispatch's in the same way, uncounted by `failed_finishes`.
- One very large app's pipelines can pass the pipeline cache's 128 MiB on KosmicKrisp (the Mac
host's driver), whose blob takes about 140 KB a pipeline against 3-25 KB on NVIDIA's, RADV's and
ANV's drivers for the same pipelines, so about 960 pipelines fill it there. A guest boot's set
@@ -3087,15 +3122,17 @@ cache is answered compile-required on both.
the Iris Xe and 3.6 against 8.1 ms on the Radeon 780M; with the driver's disk cache off, 5.6
against 4,280.6 ms on the Iris Xe and 3.7 against 845.8 ms on the Radeon 780M.
- What a state's creation is given is made there, as Metal compiles a state when it is made:
every lowering, a kernel's variants among them, and each `VkPipeline` whose key the descriptor
every lowering, a kernel's variants among them. Each `VkPipeline` whose key the descriptor
holds (a kernel's, Compute pipeline states above; a render content's triangle class, and its
line or point class where `inputPrimitiveTopology` names that class). What only a dispatch or a
draw gives waits for it: a kernel's `VkPipeline` at a threadgroup size and threadgroup memory
lengths is made at the consumer's `prepare_dispatch` call or at the dispatch, a render
content's line or point class, unless its descriptor names that class, at its first draw of it
(one `VkPipeline` for every class needs `dynamicPrimitiveTopologyUnrestricted`, which the floor
does not require, and no second form is chosen by it), and its `VkPipeline` under the depth
clip mode `Clamp` or the triangle fill mode `Lines` at its first draw under it (Known gaps of
line or point class where `inputPrimitiveTopology` names that class) is made after the answer,
by the consumer's `finish_pipeline` call, or by the first dispatch or draw that needs it before
that call has made it. What only a dispatch or a draw gives waits for it: a kernel's
`VkPipeline` at a threadgroup size and threadgroup memory lengths is made at the consumer's
`prepare_dispatch` call or at the dispatch, a render content's line or point class, unless its
descriptor names that class, at its first draw of it (one `VkPipeline` for every class needs
`dynamicPrimitiveTopologyUnrestricted`, which the floor does not require, and no second form is
chosen by it), and its `VkPipeline` under the depth clip mode `Clamp` or the triangle fill mode
`Lines` at its first draw under it (Known gaps of
render pipeline states). Each such make at a dispatch or a draw is a first-use wait, and on a
cold cache it compiles in that call, where Metal changes these with no compile: on a cold play,
`Metrics::first_use_waits` against `Metrics::made_ahead_variants` reads what the consumer's
@@ -3131,7 +3168,7 @@ cache is answered compile-required on both.
m3-max-67284) and 2.7% faster on an Iris Xe (m3-max-67285), and is not timed per dispatch on
NVIDIA; the consumer reopens it.
- On Intel's Windows driver (101.2145) for the UHD 630, the driver's compile of a tiling kernel's
`VkPipeline`, made with the state, took medians of 6,680 to 6,853 µs for the harness's
`VkPipeline`, the state's main one, took medians of 6,680 to 6,853 µs for the harness's
`create_state` kernel, in three processes of 40 compiles each with no driver cache hit. The
workgroup accounts for 1.1 to 1.3 ms of it: the runtime makes the pipeline at 256 threads, the
tile it runs every grid of such a kernel in, against a pipeline at the dispatch's threadgroup,
@@ -3165,9 +3202,9 @@ cache is answered compile-required on both.
loop need a vote word that does not fit beside its threadgroup memory in
`maxComputeSharedMemorySize`.
- A kernel that observes its threadgroup partition makes a `VkPipeline` per threadgroup size it
is dispatched at: with its state at the descriptor's `requiredThreadsPerThreadgroup` where the
kernel takes no threadgroup memory length from the encoder, and otherwise at a
`prepare_dispatch` call or its first dispatch at that size.
is dispatched at: the state's main pipeline at the descriptor's
`requiredThreadsPerThreadgroup` where the kernel takes no threadgroup memory length from the
encoder, and otherwise at a `prepare_dispatch` call or its first dispatch at that size.
- A kernel that observes its threadgroup partition runs in workgroups of its own threadgroup
size, never in tiles. On Intel's Windows driver (101.2145) for the UHD 630, a kernel that
touches a buffer per thread through its device address runs slower in narrow square workgroups
@@ -3363,9 +3400,11 @@ cache is answered compile-required on both.
(`VertexInputLayout`, with the limit where one is passed);
- the per-patch and per-patch-control-point steps for a vertex function that is not
post-tessellation (`Tessellation`).
- The triangle class's `VkPipeline` is made with the state, through the device's pipeline
cache, and so is the line or the point class's where the descriptor's `inputPrimitiveTopology`
names `MTLPrimitiveTopologyClassLine` or `MTLPrimitiveTopologyClassPoint`; otherwise each is
- The triangle class's `VkPipeline` is a main pipeline of the state, made through the device's
pipeline cache by its `finish_pipeline` call or by the first draw that needs it before then
(Compute pipeline states, `finish_pipeline`), and so is the line or the point class's where the
descriptor's `inputPrimitiveTopology` names `MTLPrimitiveTopologyClassLine` or
`MTLPrimitiveTopologyClassPoint`; otherwise each is
made by the content's first draw of lines or of points, which waits for it
(`Metrics::first_use_waits`, `first_use_line_waits`, `first_use_point_waits`). Of the two replay
streams' 537 render contents drawn, 527 draw only triangles and 2 lines and triangles; a content
@@ -3399,7 +3438,7 @@ cache is answered compile-required on both.
(`RenderCommandEncoder::LINE_NOTE`). Where a line only touches a pixel's diamond at its vertex,
which pixel it covers is the device's own (docs/API.md, section 10).
- A post-tessellation vertex function's state draws its patches through the device's tessellator
(`tessellationShader`, Floor). Its one `VkPipeline` is the patch class's, made with the state:
(`tessellationShader`, Floor). Its one `VkPipeline` is the patch class's, its main pipeline:
the translator's synthesized vertex stage (each patch one vertex of a `PATCH_LIST` of one control
point, at its position), its synthesized control stage, the function as the evaluation stage,
and the fragment function. The control stage reads each patch's factors from the encoder's
+81 -8
View File
@@ -128,8 +128,14 @@ pub(crate) enum FirstUse {
/// A render content's pipeline for the depth clip mode `Clamp` or the triangle fill mode
/// `Lines`, at its first draw under them ([`Metrics::first_use_raster_waits`]).
Raster,
/// A state's main pipeline, which its `finish_pipeline` makes, met by a dispatch or a draw
/// before that make ended ([`Metrics::first_use_unfinished_waits`]).
Unfinished,
}
/// The number of [`FirstUse`] sites.
const FIRST_USE_SITES: usize = FirstUse::Unfinished as usize + 1;
/// The variant makes [`Counters::variant_makes`] keeps: the last this many to end.
pub(crate) const VARIANT_MAKES: usize = 256;
@@ -137,9 +143,15 @@ pub(crate) const VARIANT_MAKES: usize = 256;
/// [`DispatchVariant`] ([`VariantMake::start`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VariantStart {
/// The state's creation, at a size it knows: a tiling kernel's tiles, an image-only kernel's
/// square workgroups, or an observing kernel's `requiredThreadsPerThreadgroup`.
/// The state's creation: the main pipeline of a kernel past the stage bound, which the
/// creation makes so that the stage bound's refusal is the creation's
/// ([`ComputePipelineState::finish_pipeline`](crate::ComputePipelineState::finish_pipeline)).
State,
/// A [`finish_pipeline`](crate::ComputePipelineState::finish_pipeline) call: the state's main
/// pipeline, at a size its creation knows (a tiling kernel's tiles, an image-only kernel's
/// square workgroups, or an observing kernel's `requiredThreadsPerThreadgroup` or declared
/// bound of threads).
Finish,
/// A [`prepare_dispatch`](crate::ComputePipelineState::prepare_dispatch) call, ahead of the
/// dispatches that run it.
Ahead,
@@ -631,9 +643,13 @@ struct Atomics {
first_use_wait_nanos: AtomicU64,
first_use_wait_max_nanos: AtomicU64,
/// Each [`FirstUse`] site's waits, at its index: their count, total and longest nanoseconds.
first_use_sites: [[AtomicU64; 3]; 4],
first_use_sites: [[AtomicU64; 3]; FIRST_USE_SITES],
/// The makes ahead of a dispatch: their count and total nanoseconds.
made_ahead: [AtomicU64; 2],
/// The pipelines `finish_pipeline` calls made: their count and total nanoseconds.
finished: [AtomicU64; 2],
/// [`Metrics::failed_finishes`].
failed_finishes: AtomicU64,
/// [`Counters::variant_makes`].
variant_makes: Mutex<VariantMakes>,
blocks_made: AtomicU64,
@@ -926,6 +942,19 @@ impl Counters {
total.fetch_add(nanos, Relaxed);
}
/// One more pipeline a `finish_pipeline` call made, for `nanos` nanoseconds
/// ([`Metrics::finished_pipelines`]).
pub(crate) fn finished(&self, nanos: u64) {
let [count, total] = &self.atomics.finished;
count.fetch_add(1, Relaxed);
total.fetch_add(nanos, Relaxed);
}
/// One more `finish_pipeline` call whose make failed ([`Metrics::failed_finishes`]).
pub(crate) fn finish_failed(&self) {
self.atomics.failed_finishes.fetch_add(1, Relaxed);
}
/// One more ended variant make, `make` of its number: kept, and the oldest kept dropped past
/// [`VARIANT_MAKES`].
pub(crate) fn variant_made(&self, make: impl FnOnce(u64) -> VariantMake) {
@@ -1570,14 +1599,16 @@ impl Counters {
};
let first_use =
|site: FirstUse| (a.first_use_sites[site as usize].each_ref()).map(|n| n.load(Relaxed));
let [variant, lines, points, raster] = [
let [variant, lines, points, raster, unfinished] = [
FirstUse::Variant,
FirstUse::Lines,
FirstUse::Points,
FirstUse::Raster,
FirstUse::Unfinished,
]
.map(first_use);
let made_ahead = (a.made_ahead.each_ref()).map(|n| n.load(Relaxed));
let finished = (a.finished.each_ref()).map(|n| n.load(Relaxed));
let part = |part: Part| {
let [count, bytes, total, _, over_1, over_5, over_20] = &a.parts[part as usize];
let longest =
@@ -1655,8 +1686,14 @@ impl Counters {
first_use_raster_waits: raster[0],
first_use_raster_wait_nanos: raster[1],
first_use_raster_wait_max_nanos: raster[2],
first_use_unfinished_waits: unfinished[0],
first_use_unfinished_wait_nanos: unfinished[1],
first_use_unfinished_wait_max_nanos: unfinished[2],
made_ahead_variants: made_ahead[0],
made_ahead_variant_nanos: made_ahead[1],
finished_pipelines: finished[0],
finished_pipeline_nanos: finished[1],
failed_finishes: a.failed_finishes.load(Relaxed),
blocks_made: a.blocks_made.load(Relaxed),
block_bytes_made: a.block_bytes_made.load(Relaxed),
consumer_allocations: a.consumer_allocations.load(Relaxed),
@@ -2077,8 +2114,10 @@ pub struct Metrics {
/// counted in [`barriers`](Self::barriers).
pub texture_clear_barriers: u64,
/// `VkPipeline`s created, each counted as its `vkCreateComputePipelines` or
/// `vkCreateGraphicsPipelines` call returns it: one a state's creation makes for a content the
/// device does not hold, or one a first use makes
/// `vkCreateGraphicsPipelines` call returns it: a state's main pipeline, which its
/// `finish_pipeline` makes for a content the device does not hold
/// ([`finished_pipelines`](Self::finished_pipelines)), or its creation for a kernel past the
/// stage bound, one a `prepare_dispatch` call makes, or one a first use makes
/// ([`first_use_waits`](Self::first_use_waits)). A state of a content the device holds makes
/// none, a call still inside the driver is not counted yet, and one that failed is not counted.
pub pipelines_created: u64,
@@ -2090,8 +2129,10 @@ pub struct Metrics {
/// First-use waits: encoding calls that waited while the `VkPipeline` they needed was made,
/// for a workgroup size (a threadgroup size, or the tile of an image-only kernel's grid more
/// than one deep) or threadgroup memory lengths no state of the kernel's content had run with
/// before, or for a render content's first draw of lines or of points, or under the depth
/// clip mode `Clamp` or the triangle fill mode `Lines`.
/// before, for a render content's first draw of lines or of points, or under the depth
/// clip mode `Clamp` or the triangle fill mode `Lines`, or for a state's main pipeline
/// before its `finish_pipeline` had made it
/// ([`first_use_unfinished_waits`](Self::first_use_unfinished_waits)).
pub first_use_waits: u64,
/// The nanoseconds of [`host_time`](crate::host_time) the first-use waits took, in total.
pub first_use_wait_nanos: u64,
@@ -2133,12 +2174,44 @@ pub struct Metrics {
/// The longest of the [`first_use_raster_waits`](Self::first_use_raster_waits), in
/// nanoseconds; a maximum since the device was made.
pub first_use_raster_wait_max_nanos: u64,
/// Of the [`first_use_waits`](Self::first_use_waits), those for a state's main pipeline (the
/// one its `finish_pipeline` makes:
/// [`ComputePipelineState::finish_pipeline`](crate::ComputePipelineState::finish_pipeline),
/// [`RenderPipelineState::finish_pipeline`](crate::RenderPipelineState::finish_pipeline)),
/// met by a dispatch or a draw before a make of it had ended: one that waited for a
/// `finish_pipeline` call still in the driver, or that made the pipeline itself where no call
/// had made it, or where the call's make had failed.
pub first_use_unfinished_waits: u64,
/// The nanoseconds of the [`first_use_unfinished_waits`](Self::first_use_unfinished_waits),
/// in total.
pub first_use_unfinished_wait_nanos: u64,
/// The longest of the [`first_use_unfinished_waits`](Self::first_use_unfinished_waits), in
/// nanoseconds; a maximum since the device was made.
pub first_use_unfinished_wait_max_nanos: u64,
/// The compute kernels' pipelines that
/// [`prepare_dispatch`](crate::ComputePipelineState::prepare_dispatch) made on its caller's
/// thread, ahead of the dispatches that run them (`vkCreateComputePipelines`).
pub made_ahead_variants: u64,
/// The nanoseconds of the [`made_ahead_variants`](Self::made_ahead_variants), in total.
pub made_ahead_variant_nanos: u64,
/// The states' main pipelines that `finish_pipeline` calls made on their callers' threads,
/// after the state's creation answered
/// ([`ComputePipelineState::finish_pipeline`](crate::ComputePipelineState::finish_pipeline),
/// [`RenderPipelineState::finish_pipeline`](crate::RenderPipelineState::finish_pipeline)):
/// the driver's side of a state's make, which a consumer reads beside the creation's own time
/// (the translation's is [`translation_nanos`](Self::translation_nanos)).
pub finished_pipelines: u64,
/// The nanoseconds of [`host_time`](crate::host_time) the
/// [`finished_pipelines`](Self::finished_pipelines) took, in total, each from its entry as
/// being made to its end, its `vkCreateComputePipelines` or `vkCreateGraphicsPipelines` call
/// within it.
pub finished_pipeline_nanos: u64,
/// `finish_pipeline` calls whose make failed: a driver's create that failed after the state's
/// creation answered. The pipeline is not kept; the first dispatch or draw that needs it makes
/// it again, a first-use wait
/// ([`first_use_unfinished_waits`](Self::first_use_unfinished_waits)), and reports the
/// driver's error where that make fails too.
pub failed_finishes: u64,
/// `VkDeviceMemory` allocations made: the allocations blocks are ranges of (the texture
/// blocks among them), the zero source and the parameter ring's blocks.
pub blocks_made: u64,
+2 -1
View File
@@ -1066,7 +1066,8 @@ impl ComputeCommandEncoder {
_ => {
let (set, max) = (&self.threadgroup_lengths, limits.max_shared_memory);
let lengths = threadgroup_memory(kernel, set, local, max)?;
kernel.pipeline(core, inner.dispatch_key(module, local, lengths))?
let variant = inner.dispatch_key(module, local, lengths);
kernel.pipeline(core, variant, inner.first_use(variant))?
}
};
self.last = Some(Last {
+196 -76
View File
@@ -37,20 +37,24 @@
//! size, whose last SIMD group may be partly filled, as Metal runs it; that variant is lowered
//! with the state too.
//!
//! What a state's make is given is made at the make, as Metal compiles a state when it is made:
//! every module ([`Lowered`] holds each variant's: a shader module, or a module past the stage
//! bound's words), and each `VkPipeline` whose key the descriptor holds (a tiling kernel's
//! tiles, an image-only kernel's square workgroups, and an observing kernel's at the
//! What a state's make is given is made at the make, as Metal compiles a state when it is made,
//! up to the driver's create: every module ([`Lowered`] holds each variant's: a shader module, or
//! a module past the stage bound's words), with every refusal. The make then answers, and the
//! one `VkPipeline` whose key the descriptor holds, the content's main pipeline (a tiling
//! kernel's tiles, an image-only kernel's square workgroups, and an observing kernel's at the
//! descriptor's `requiredThreadsPerThreadgroup`, or, with none, at `[N, 1, 1]` for the bound `N`
//! of threads its state declares). Nothing the runtime records
//! depends on when a compile finishes: an encoding call whose `VkPipeline` is not made yet makes
//! it and waits for it, then records, so there is one recorded form. Each such wait is a
//! of threads its state declares), is made by the consumer's
//! [`ComputePipelineState::finish_pipeline`] call on a thread of its own, so the driver's
//! compile overlaps the program's work; a kernel past the stage bound makes it at the make, so
//! that the stage bound's refusal is the make's. Nothing the runtime records depends on when a
//! compile finishes: an encoding call whose `VkPipeline` is not made yet makes it, or waits for
//! the make in flight, then records, so there is one recorded form. Each such wait is a
//! first-use wait, counted with its time
//! ([`Metrics::first_use_waits`](crate::Metrics::first_use_waits)). No translation runs after the
//! make. Each make of a `VkPipeline` is kept in the device's counters as it ends
//! ([`Counters::variant_makes`]): its key, who started it (the state's make, a
//! [`ComputePipelineState::prepare_dispatch`] call or a first use) and the first-use waits that
//! waited for it.
//! ([`Counters::variant_makes`]): its key, who started it (a `finish_pipeline` call, the state's
//! make, a [`ComputePipelineState::prepare_dispatch`] call or a first use) and the first-use
//! waits that waited for it.
use crate::arrays::BINDINGS;
use crate::cache;
@@ -183,6 +187,10 @@ pub(crate) struct Compiled {
notes: Vec<PrecisionNote>,
/// What Metal's state answers of the content, beside its threads.
answers: Answers,
/// The key of the content's main pipeline ([`Compiled::main_key`]), which a state's
/// [`ComputePipelineState::finish_pipeline`] makes, or its creation for a kernel past the
/// stage bound; none where its descriptor holds no key of a `VkPipeline`.
main: Option<DispatchVariant>,
}
/// What Metal's compute state answers of a content beside its threads, from its whole module's
@@ -831,23 +839,27 @@ impl crate::Device {
/// content the device does not hold, the translator compiles the kernel on the calling
/// thread, which waits for it, within the translator's 20-second budget per lowering: a
/// kernel that does not observe its threadgroup partition as its partial-threadgroups
/// variant, whose 256-wide tile's `VkPipeline`, or an image-only kernel's 16x16 workgroups'
/// one, is made here too, and one that does as its partial-threadgroups variant, which its
/// dispatches run, and its plain module too only where the variant's predicated walk takes a
/// vote word of threadgroup memory the plain module does not and the kernel takes a
/// threadgroup memory length from the encoder, or its own memory with the word is past the
/// device's `maxComputeSharedMemorySize`. It is made with the one `VkPipeline` its
/// dispatches run, whole grids, ragged and indirect ones (the plain module's where the
/// variant, whose main pipeline is its 256-wide tile's `VkPipeline`, or an image-only
/// kernel's 16x16 workgroups' one, and one that does as its partial-threadgroups variant,
/// which its dispatches run, and its plain module too only where the variant's predicated
/// walk takes a vote word of threadgroup memory the plain module does not and the kernel
/// takes a threadgroup memory length from the encoder, or its own memory with the word is
/// past the device's `maxComputeSharedMemorySize`. Its main pipeline is the one `VkPipeline`
/// its dispatches run, whole grids, ragged and indirect ones (the plain module's where the
/// variant's threadgroup memory, the vote word with it, is past the device's), at the
/// descriptor's `requiredThreadsPerThreadgroup` where it sets one, or else at `[N, 1, 1]`
/// where the state declares a bound of threads (the descriptor's
/// `maxTotalThreadsPerThreadgroup`, or the kernel's
/// `[[max_total_threads_per_threadgroup(n)]]`), `N` the state's
/// `maxTotalThreadsPerThreadgroup`, and the kernel takes no threadgroup memory length from
/// `maxTotalThreadsPerThreadgroup`, where the kernel takes no threadgroup memory length from
/// the encoder. A kernel whose tier runs only whole SIMD groups has its
/// emulated-SIMD-group variant lowered here too. The translator answers whether the kernel
/// observes its partition without lowering, where the cache directory holds no lowering of
/// the variant to answer it. Where the device has a cache directory
/// the variant to answer it. The call makes every shader module and answers before the
/// driver's create of the main pipeline, which the consumer's
/// [`finish_pipeline`](ComputePipelineState::finish_pipeline) call makes after it, on a
/// thread of its own, or else the first dispatch that runs it; a kernel past the stage bound
/// makes its main pipeline here (Err below). Where the device has a cache directory
/// ([`DeviceOptions::pipeline_cache_dir`]), a lowering a device made before is read from it
/// in place of lowering again, and every `VkPipeline` is made through the pipeline cache it
/// keeps there. The content's other `VkPipeline`s, of a threadgroup size and threadgroup
@@ -880,7 +892,11 @@ impl crate::Device {
/// `supportIndirectCommandBuffers`; [`Gap::KernelInput`] for a kernel that
/// reads what the compute encoder does not supply yet; [`Refusal::SamplerIds`] where
/// `sampler_ids` answers another count; [`Refusal::IndicesNotGranted`] for a constexpr
/// sampler's index; [`Limit::DeviceSamplers`](crate::Limit::DeviceSamplers); [`Error::Vulkan`].
/// sampler's index; [`Limit::DeviceSamplers`](crate::Limit::DeviceSamplers);
/// [`Error::StageUnfilled`], whose request the consumer's helper fills before it makes the
/// state again ([`Device::fill_stage`](crate::Device::fill_stage)), or [`Gap::StageSize`], for
/// the main pipeline of a kernel past the stage bound; [`Error::Vulkan`] where a shader module
/// cannot be made.
pub fn new_compute_pipeline_state(
&self,
descriptor: &ComputePipelineDescriptor,
@@ -1105,55 +1121,57 @@ impl Compiled {
required_threads_per_threadgroup: required.unwrap_or([0; 3]),
..answers
};
let compiled = Compiled::new(core, whole, form, emulated, (notes, answers));
// A tiling kernel's grids one deep run on one `VkPipeline`, made with the state: its
// tiles', or an image-only kernel's square workgroups'.
let first = match &compiled.form {
Form::Tiled => Some((&compiled.whole, Module::Tiles, [GRID_TILE_THREADS, 1, 1])),
Form::Square => Some((&compiled.whole, Module::Whole, SQUARE)),
Form::Sized { .. } => None,
};
if let Some((kernel, module, size)) = first {
let lengths = Lengths::zeros(kernel.interface.threadgroups.len());
let variant = compiled.dispatch_key(module, size, lengths);
let more = lock(&kernel.variants.more);
kernel.make_pending(&compiled.core, more, variant, VariantStart::State, None)?;
}
// An observing kernel at the size its state gives: the descriptor's
// `requiredThreadsPerThreadgroup`, the size its dispatches give, or, with none, `[N, 1, 1]`
// where the state declares a bound of threads, `N` its `maxTotalThreadsPerThreadgroup`.
// The bound is declared by the descriptor's `maxTotalThreadsPerThreadgroup`, or by the
// kernel's `[[max_total_threads_per_threadgroup(n)]]`, which alone brings Metal's answer
// below its 1024; the device's own limit is no declared bound. The `VkPipeline` its
// dispatches of that size run is made, where the module takes no threadgroup memory length
// from the encoder: the partial-threadgroups variant's, which runs whole grids, ragged and
// indirect ones alike, or the whole module's where the content has no such variant or the
// variant's threadgroup memory, a predicated walk's vote word with it, is past the
// device's (`encoder::decide`). A make that fails here is made again by the dispatch that
// needs it, which reports its own error; a make refused for the stage bound refuses the
// state's, which the consumer's helper then fills.
let interface = &compiled.whole.interface;
let declared = descriptor.max_total_threads_per_threadgroup.is_some()
|| interface.metal_max_total_threads < METAL_MAX_THREADS;
let bound = declared.then_some([interface.max_total_threads, 1, 1]);
if let (Form::Sized { .. }, Some(size)) = (&compiled.form, required.or(bound)) {
let found = compiled.dispatched(Dispatch::Threadgroups([1; 3]), size, &[]);
if let Some((kernel, module, local, lengths)) = found {
if kernel.interface.threadgroups.is_empty() {
let variant = compiled.dispatch_key(module, local, lengths);
let made = kernel.make_ahead(&compiled.core, variant, VariantStart::State);
match made {
Err(error) if past_stage_bound(&error) => return Err(error),
Ok(_) | Err(_) => {}
}
}
let mut compiled = Compiled::new(core, whole, form, emulated, (notes, answers));
compiled.main = compiled.main_key(descriptor);
// A kernel past the stage bound makes its main pipeline here, so that a make the stage
// bound refuses refuses the state's, which the consumer's helper then fills. Every other
// error of the make is the dispatch's that makes it again, as a failed
// `finish_pipeline`'s is.
let main = compiled.main_kernel();
if let Some((kernel, variant)) = main.filter(|(kernel, _)| kernel.is_heavy()) {
match kernel.make_ahead(&compiled.core, variant, VariantStart::State) {
Err(error) if past_stage_bound(&error) => return Err(error),
Ok(_) | Err(_) => {}
}
}
Ok(compiled)
}
/// The key of the content's main pipeline, the one `VkPipeline` whose key its descriptor
/// holds, where it has one: a tiling kernel's tiles, or an image-only kernel's square
/// workgroups, which its grids one deep run; for an observing kernel, the one its dispatches
/// at the size its state gives run: the descriptor's `requiredThreadsPerThreadgroup`, the
/// size its dispatches give, or, with none, `[N, 1, 1]` where the state declares a bound of
/// threads, `N` its `maxTotalThreadsPerThreadgroup`. The bound is declared by the
/// descriptor's `maxTotalThreadsPerThreadgroup`, or by the kernel's
/// `[[max_total_threads_per_threadgroup(n)]]`, which alone brings Metal's answer below its
/// 1024; the device's own limit is no declared bound. Its dispatches of that size run the
/// partial-threadgroups variant's, which runs whole grids, ragged and indirect ones alike, or
/// the whole module's where the content has no such variant or the variant's threadgroup
/// memory, a predicated walk's vote word with it, is past the device's (`encoder::decide`);
/// none where the module takes a threadgroup memory length from the encoder.
fn main_key(&self, descriptor: &ComputePipelineDescriptor) -> Option<DispatchVariant> {
let (module, size) = match &self.form {
Form::Tiled => (Module::Tiles, [GRID_TILE_THREADS, 1, 1]),
Form::Square => (Module::Whole, SQUARE),
Form::Sized { .. } => {
let interface = &self.whole.interface;
let declared = descriptor.max_total_threads_per_threadgroup.is_some()
|| interface.metal_max_total_threads < METAL_MAX_THREADS;
let bound = declared.then_some([interface.max_total_threads, 1, 1]);
let size = descriptor.required_threads_per_threadgroup.or(bound)?;
let dispatch = Dispatch::Threadgroups([1; 3]);
let (kernel, module, local, lengths) = self.dispatched(dispatch, size, &[])?;
return (kernel.interface.threadgroups.is_empty())
.then(|| self.dispatch_key(module, local, lengths));
}
};
let lengths = Lengths::zeros(self.whole.interface.threadgroups.len());
Some(self.dispatch_key(module, size, lengths))
}
/// The content of `whole`, its form, emulated variant, notes and Metal's answers, counted
/// live.
/// live, with no main pipeline.
fn new(
core: Arc<Core>,
whole: Kernel,
@@ -1170,6 +1188,7 @@ impl Compiled {
emulated,
notes,
answers,
main: None,
}
}
}
@@ -1765,13 +1784,65 @@ pub(crate) fn access(used: AccessSet) -> Access {
}
impl ComputePipelineState {
/// No Metal counterpart: makes the state's main `VkPipeline` on the calling thread, through
/// the device's pipeline cache, once the state's creation has answered. Metal compiles a
/// compute state whole when the state is made. Here the creation does everything up to the
/// driver's create (every lowering, every refusal and Metal's own errors, the shader modules
/// and the samplers' numbering) and answers, and this call runs the driver's create, so a
/// consumer can answer the program before the driver's compile ends and let that compile
/// overlap the program's own work. The runtime starts no thread for it: the consumer calls it
/// on a thread of its own after it has answered.
///
/// The main pipeline is the one whose key the descriptor holds: a tiling kernel's tiles', an
/// image-only kernel's square workgroups', or an observing kernel's at the descriptor's
/// `requiredThreadsPerThreadgroup` or its declared bound of threads where the kernel takes no
/// threadgroup memory length from the encoder
/// ([`new_compute_pipeline_state`](crate::Device::new_compute_pipeline_state)). A state with
/// none makes nothing here. A kernel past the stage bound makes its main pipeline at the
/// creation, so that the stage bound's refusal is the creation's, and makes nothing here.
///
/// It returns at once where the pipeline is made, or another thread is making it, so a
/// second call makes nothing. A dispatch that needs the pipeline first waits for the make in
/// flight, or makes it itself where none is: a first-use wait
/// ([`Metrics::first_use_unfinished_waits`](crate::Metrics::first_use_unfinished_waits)),
/// after which it records what it records with the pipeline made here. So a state this is
/// never called for runs as one it was called for, its first dispatch making the pipeline.
///
/// Counted as [`Metrics::finished_pipelines`](crate::Metrics::finished_pipelines), with their
/// time.
///
/// Err: [`Error::Vulkan`] where the driver's create failed, which Metal would have answered
/// at the creation (Vulkan lets it fail for exhausted host or device memory, or with
/// `VK_ERROR_UNKNOWN` or `VK_ERROR_VALIDATION_FAILED`), counted in
/// [`Metrics::failed_finishes`](crate::Metrics::failed_finishes): the pipeline is not kept,
/// the first dispatch that needs it makes it again, and that dispatch answers the driver's
/// error where that make fails too.
pub fn finish_pipeline(&self) -> Result<(), Error> {
let compiled = &self.inner.compiled;
let core = &compiled.core;
let main = compiled.main_kernel();
let Some((kernel, variant)) = main.filter(|(kernel, _)| !kernel.is_heavy()) else {
return Ok(());
};
match kernel.make_ahead(core, variant, VariantStart::Finish) {
Ok(Some(nanos)) => core.counters.finished(nanos),
Ok(None) => {}
Err(error) => {
core.counters.finish_failed();
return Err(error);
}
}
Ok(())
}
/// Makes ahead, on the calling thread, what a dispatch of this state makes at its first use,
/// so that the dispatch finds it made. Metal has no counterpart: this is a hook for a
/// consumer's pre-pass. Metal compiles a compute state whole when the state is made, and so
/// does the state's make here, every variant included; but a kernel's `VkPipeline` depends
/// on the threadgroup size and the threadgroup memory lengths, which arrive with the
/// dispatch. A consumer that reads a command buffer's dispatches before it encodes them may
/// call this for each, in their order, on threads of its own; the runtime starts none.
/// does the state's make here, every variant included, with its main pipeline made by
/// [`finish_pipeline`](Self::finish_pipeline); but a kernel's `VkPipeline` depends on the
/// threadgroup size and the threadgroup memory lengths, which arrive with the dispatch. A
/// consumer that reads a command buffer's dispatches before it encodes them may call this for
/// each, in their order, on threads of its own; the runtime starts none.
///
/// `dispatch` and `threads_per_threadgroup` are the dispatch's own arguments, as the program
/// passed them to [`dispatch_threads`](crate::ComputeCommandEncoder::dispatch_threads),
@@ -1832,7 +1903,9 @@ impl ComputePipelineState {
/// read from the kernel's first eight variants with no lock, and past them under the short
/// lock of the kernel's list, which no make holds while the driver compiles. It may answer
/// false for a key whose make ends after the read, and never answers true for a key not
/// made.
/// made. That bit is no answer of Metal's and moves as makes end: a state's main pipeline
/// reads false until its [`finish_pipeline`](Self::finish_pipeline), a `prepare_dispatch`
/// call or a dispatch has made it. The key does not move.
///
/// None where the dispatch would refuse its threadgroup size, its variant or its threadgroup
/// memory, or records nothing (a grid with no threads, a kernel that writes no memory): where
@@ -2046,6 +2119,47 @@ impl Compiled {
}
}
/// The kernel whose module a dispatch of `module` runs, where the content has it made: the
/// content's own for its whole module and its tiles, else its variant's.
fn kernel_of(&self, module: Module) -> Option<&Kernel> {
let which = match module {
Module::Whole | Module::Tiles => return Some(&self.whole),
Module::Partial => Which::Partial,
Module::Emulated => Which::Emulated,
};
if let (
Which::Partial,
Form::Sized {
partial: Partial::Alone,
},
) = (which, &self.form)
{
return Some(&self.whole);
}
match self.variant(which)? {
Lowered::Made(kernel, _) => Some(&**kernel),
Lowered::Refused
| Lowered::Translation(_)
| Lowered::Unsupplied(_)
| Lowered::Failed(_) => None,
}
}
/// The content's main pipeline's kernel and key, where it has one ([`Compiled::main`]).
fn main_kernel(&self) -> Option<(&Kernel, DispatchVariant)> {
let variant = self.main?;
Some((self.kernel_of(variant.module)?, variant))
}
/// Where a first use of `variant` waits ([`FirstUse`]): the content's main pipeline's
/// ([`FirstUse::Unfinished`]), or a variant's no state of the content has run.
pub(crate) fn first_use(&self, variant: DispatchVariant) -> FirstUse {
match self.main == Some(variant) {
true => FirstUse::Unfinished,
false => FirstUse::Variant,
}
}
/// The key of the dispatches that run `module` at workgroup size `local` with threadgroup
/// memory `lengths`: its [`DispatchVariant`].
pub(crate) fn dispatch_key(
@@ -2160,15 +2274,23 @@ impl Kernel {
matches!(self.code, Code::Module(_))
}
/// Whether the kernel is past the stage bound: each of its `VkPipeline`s is made from its
/// helper's cache data alone ([`Code::Heavy`]).
fn is_heavy(&self) -> bool {
matches!(self.code, Code::Heavy(_))
}
/// The `VkPipeline` of `variant`, made now where it is not yet: the calling thread waits for
/// it, a first-use wait, so what is recorded never depends on when a compile finishes. Where
/// another thread is making it, the call waits for that make, also a first-use wait counted in
/// that make's [`VariantMake::waits`], and makes it itself where that one failed. One of the
/// kernel's first [`VARIANT_CELLS`] variants is found with no lock.
/// it, a first-use wait at `site` ([`Compiled::first_use`]), so what is recorded never
/// depends on when a compile finishes. Where another thread is making it, the call waits for
/// that make, also a first-use wait counted in that make's [`VariantMake::waits`], and makes
/// it itself where that one failed. One of the kernel's first [`VARIANT_CELLS`] variants is
/// found with no lock.
pub(crate) fn pipeline(
&self,
core: &Core,
variant: DispatchVariant,
site: FirstUse,
) -> Result<vk::Pipeline, Error> {
let variants = &self.variants;
let key = variant.key();
@@ -2176,10 +2298,8 @@ impl Kernel {
return Ok(pipeline);
}
let began = host_time();
let waited = |core: &Core| {
core.counters
.first_use_wait(FirstUse::Variant, host_time().saturating_sub(began))
};
let waited =
|core: &Core| (core.counters).first_use_wait(site, host_time().saturating_sub(began));
let mut more = lock(&variants.more);
let mut waits = false;
loop {
+219 -58
View File
@@ -26,8 +26,8 @@
//! baked, and a layout whose stride is set per bind (`MTLBufferLayoutStrideDynamic`), which the
//! replay streams' never are, is refused. A draw under the depth clip mode `Clamp` or the triangle
//! fill mode `Lines` takes a `VkPipeline` of its class made for that raster state, by the first
//! such draw of the content, which waits for it, as a draw of a class not made with the content
//! does: Metal sets both per encoder and compiles nothing for them. The fill mode is a triangle's
//! such draw of the content, which waits for it, as a draw of a class not made yet does: Metal
//! sets both per encoder and compiles nothing for them. The fill mode is a triangle's
//! alone, in Metal and in Vulkan, so the line and point classes take the clip mode alone.
//!
//! What a draw supplies is the content's [`Draws`]: each function's slots with their accesses,
@@ -38,12 +38,15 @@
//!
//! A descriptor names no topology class unless it sets `inputPrimitiveTopology`, and the replay
//! streams' never do, while nearly every content draws only triangles (527 of the 537 contents
//! gb and b2 draw). So the triangle class's `VkPipeline` is made with the state, where Metal
//! compiles, and so is the line or the point class's where the descriptor names that class;
//! otherwise each comes with the draws, made by the first draw of lines or of points, as only a
//! draw gives the class (one `VkPipeline` for several classes would need a dynamic topology across
//! classes, which Vulkan 1.3 does not give). The cost: a content drawn only as lines or points
//! makes a triangle `VkPipeline` it never uses (8 contents of the 537).
//! gb and b2 draw). So the triangle class's `VkPipeline` is the content's main one, which Metal
//! compiles with the state, and so is the line or the point class's where the descriptor names
//! that class; otherwise each comes with the draws, made by the first draw of lines or of points,
//! as only a draw gives the class (one `VkPipeline` for several classes would need a dynamic
//! topology across classes, which Vulkan 1.3 does not give). The cost: a content drawn only as
//! lines or points makes a triangle `VkPipeline` it never uses (8 contents of the 537). The state's
//! make does everything up to the driver's create of the main ones and answers; the consumer's
//! [`RenderPipelineState::finish_pipeline`] call makes them after, on a thread of its own, or else
//! the first draw that needs each, which waits for it ([`Main`]).
//!
//! A point's size is the `PointSize` the vertex module writes: the function's `[[point_size]]`,
//! at most Metal's 511 pixels, or 1.0 for a function without one, which the device draws with
@@ -59,7 +62,7 @@
//! which a draw of lines records (`RenderCommandEncoder::LINE_NOTE`).
//!
//! A content whose vertex function is post-tessellation draws patches alone, so its one
//! `VkPipeline` is the patch class's, made with the state: the translator's synthesized vertex and
//! `VkPipeline` is the patch class's, its main one: the translator's synthesized vertex and
//! control stages, the function as the evaluation stage, and a `PATCH_LIST` of one control point
//! per patch. Its control stage reads each patch's factors through their address, which a draw
//! pushes ([`FieldValue::TessellationFactors`]); the evaluation stage reaches its control points'
@@ -68,7 +71,7 @@
//! the replay streams' states never use, are refused ([`RenderPipelineKind::Tessellation`]).
use crate::cache::{self, Lowerings};
use crate::counters::{FirstUse, Gauge, Metric};
use crate::counters::{Counters, FirstUse, Gauge, Metric};
use crate::device::{lock, Core};
use crate::error::{Error, Gap, Refusal, RenderPipelineKind, StageGap};
use crate::hazard::Access;
@@ -93,7 +96,7 @@ use metal2vulkan::pipeline::{
};
use metal2vulkan::Budget;
use std::ffi::CString;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError};
/// `MTLRenderPipelineState`.
///
@@ -214,13 +217,18 @@ pub(crate) struct RenderCompiled {
stages: Vec<Module>,
/// The fixed-function state every `VkPipeline` of the content takes.
fixed: Fixed,
/// The `VkPipeline` made with the content: the triangle class's, or a post-tessellation vertex
/// The content's main `VkPipeline`: the triangle class's, or a post-tessellation vertex
/// function's patch class's, its only class, at the default [`Raster`].
primary: vk::Pipeline,
/// The content's other `VkPipeline`s, each by its class's list topology and its raster state:
/// the line or the point class's at the default raster state, made with the content where its
/// descriptor names that class, and every other, made by the first draw that takes it. At most
/// 7: the triangle or patch class's three other raster states, and two of each other class.
primary: Main,
/// The line or the point class's `VkPipeline` at the default raster state, by its list
/// topology, a main one too, where the descriptor names that class
/// (`inputPrimitiveTopology`).
named: Option<(vk::PrimitiveTopology, Main)>,
/// The content's other `VkPipeline`s, each by its class's list topology and its raster state,
/// each made by the first draw that takes it: the line and the point class's at the default
/// raster state where the descriptor names neither, and those under other raster states. At
/// most 7: the triangle or patch class's three other raster states, and two of each other
/// class.
later: Mutex<Vec<(vk::PrimitiveTopology, Raster, vk::Pipeline)>>,
/// Whether a draw of points rasterizes them: the vertex function writes `[[point_size]]`, or
/// the descriptor names the point class, under which Metal draws a point of a function that
@@ -263,6 +271,100 @@ pub(crate) struct Raster {
pub(crate) lines: bool,
}
/// One of a content's main `VkPipeline`s ([`RenderCompiled::primary`],
/// [`RenderCompiled::named`]): made by a state's [`RenderPipelineState::finish_pipeline`] call,
/// or by the first draw that needs it, which waits for a make in flight. It is made by one thread
/// at a time; a make that failed keeps nothing, and the next call or draw makes it again.
#[derive(Default)]
pub(crate) struct Main {
/// The pipeline once made, which a draw reads with no lock.
made: OnceLock<vk::Pipeline>,
/// Whether a thread is making it.
making: Mutex<bool>,
/// Signalled when a make ends, made or failed: a draw waiting for it looks again.
ended: Condvar,
}
/// A make of a [`Main`] in flight: when it ends, made or not, panicking included, the cell is no
/// longer being made, and the draws waiting for it wake.
struct Making<'a>(&'a Main);
impl Drop for Making<'_> {
fn drop(&mut self) {
*lock(&self.0.making) = false;
self.0.ended.notify_all();
}
}
impl Main {
/// The pipeline, where it is made.
fn get(&self) -> Option<vk::Pipeline> {
self.made.get().copied()
}
/// Makes the pipeline with `make` on the calling thread, where it is neither made nor being
/// made: its nanoseconds where this made it, none where it did not need to, or the make's
/// error, which keeps nothing.
pub(crate) fn make_ahead(
&self,
make: impl FnOnce() -> Result<vk::Pipeline, Error>,
) -> Result<Option<u64>, Error> {
if self.made.get().is_some() {
return Ok(None);
}
let mut making = lock(&self.making);
if *making || self.made.get().is_some() {
return Ok(None);
}
*making = true;
drop(making);
let began = host_time();
self.make(make)?;
Ok(Some(host_time().saturating_sub(began)))
}
/// The pipeline: read with no lock where it is made; else waited for where another thread is
/// making it, and made with `make` on the calling thread where none is or that make failed. A
/// call that did not find it made is a first-use wait ([`FirstUse::Unfinished`]).
pub(crate) fn pipeline(
&self,
counters: &Counters,
make: impl FnOnce() -> Result<vk::Pipeline, Error>,
) -> Result<vk::Pipeline, Error> {
if let Some(pipeline) = self.get() {
return Ok(pipeline);
}
let began = host_time();
let mut making = lock(&self.making);
while *making {
making = (self.ended.wait(making)).unwrap_or_else(PoisonError::into_inner);
}
let made = self.get();
if made.is_none() {
*making = true;
}
drop(making);
let pipeline = match made {
Some(pipeline) => pipeline,
None => self.make(make)?,
};
counters.first_use_wait(FirstUse::Unfinished, host_time().saturating_sub(began));
Ok(pipeline)
}
/// Runs `make`, the cell marked as being made by the caller, and keeps what it made.
fn make(
&self,
make: impl FnOnce() -> Result<vk::Pipeline, Error>,
) -> Result<vk::Pipeline, Error> {
let _making = Making(self);
let pipeline = make()?;
// Only the thread that marked the cell sets it, and it was empty when marked.
let _ = self.made.set(pipeline);
Ok(pipeline)
}
}
/// The next content's [`RenderCompiled::id`].
static CONTENT_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
@@ -364,17 +466,19 @@ impl crate::Device {
/// contents used, compute and render together) costs the translator's key of the descriptor,
/// which reads no function, and a lookup. For a
/// content the device does not hold, the translator lowers each function on the calling
/// thread, which waits for it, within its 20-second budget per lowering, and the content's
/// triangle-class `VkPipeline` is made here. Where the device has a cache directory
/// ([`DeviceOptions::pipeline_cache_dir`]), a lowering a device made before is read from it in
/// place of lowering again, and each `VkPipeline` is made through the pipeline data kept for
/// it there; a content a device made before is read by its record there, kept under the
/// translator's key of the descriptor, which names its two lowerings, so its functions are
/// neither decoded nor specialized
/// ([`Metrics::render_records_read`](crate::Metrics::render_records_read)). The line class's
/// `VkPipeline` is made here too where the descriptor's `inputPrimitiveTopology` names that
/// class, and otherwise comes with the draws. The `completionHandler:` forms are not built (no
/// replay stream calls them).
/// thread, which waits for it, within its 20-second budget per lowering, and its shader
/// modules are made here. The call answers before the driver's create of the content's main
/// `VkPipeline`s, the triangle class's, and the line or the point class's where the
/// descriptor's `inputPrimitiveTopology` names that class, which the consumer's
/// [`finish_pipeline`](RenderPipelineState::finish_pipeline) call makes after it, on a thread
/// of its own, or else the first draw that needs each; any other class's comes with the draws.
/// Where the device has a cache directory ([`DeviceOptions::pipeline_cache_dir`]), a lowering
/// a device made before is read from it in place of lowering again, and each `VkPipeline` is
/// made through the pipeline data kept for it there; a content a device made before is read
/// by its record there, kept under the translator's key of the descriptor, which names its two
/// lowerings, so its functions are neither decoded nor specialized
/// ([`Metrics::render_records_read`](crate::Metrics::render_records_read)). The
/// `completionHandler:` forms are not built (no replay stream calls them).
///
/// [`DeviceOptions::pipeline_cache_dir`]: crate::DeviceOptions::pipeline_cache_dir
///
@@ -401,7 +505,8 @@ impl crate::Device {
/// [`Refusal::PointSizeTopology`] for a vertex function that writes `[[point_size]]` under
/// the line or the triangle class; [`Refusal::SamplerIds`] where `sampler_ids` answers another
/// count; [`Refusal::IndicesNotGranted`] for a constexpr sampler's index;
/// [`Limit::DeviceSamplers`](crate::Limit::DeviceSamplers); [`Error::Vulkan`].
/// [`Limit::DeviceSamplers`](crate::Limit::DeviceSamplers); [`Error::Vulkan`] where a shader
/// module cannot be made.
pub fn new_render_pipeline_state(
&self,
descriptor: &RenderPipelineDescriptor,
@@ -996,7 +1101,7 @@ fn recorded(
impl RenderCompiled {
/// The translation of `lowered`, a descriptor whose `Function` stages are lowered
/// ([`lower_stages`], [`recorded`]), with its triangle-class `VkPipeline`.
/// ([`lower_stages`], [`recorded`]), with its shader modules and no `VkPipeline` made.
fn of(
core: &Arc<Core>,
lowered: &RenderPipelineDescriptor,
@@ -1103,11 +1208,19 @@ impl RenderCompiled {
// sample is its colors alone.
let colors = (lowered.color_attachments).map(|color| color.map(|c| c.pixel_format));
let imageblock_sample = metal2vulkan::metal::format::imageblock_sample_length(&colors);
let mut compiled = RenderCompiled {
// A descriptor that names the line or the point class (`inputPrimitiveTopology`) gives
// that class's key: its `VkPipeline` is a main one too, made as the primary class's is.
let named = match (draws.patches, lowered.input_primitive_topology) {
(false, PrimitiveTopologyClass::Line) => Some(vk::PrimitiveTopology::LINE_LIST),
(false, PrimitiveTopologyClass::Point) => Some(vk::PrimitiveTopology::POINT_LIST),
_ => None,
};
Ok(RenderCompiled {
core: Arc::clone(core),
stages,
fixed: Fixed::of(&pipeline),
primary: vk::Pipeline::null(),
primary: Main::default(),
named: named.map(|list| (list, Main::default())),
later: Mutex::new(Vec::new()),
rasterizes_points: pipeline.graphics.writes_point_size
|| lowered.input_primitive_topology == PrimitiveTopologyClass::Point,
@@ -1119,25 +1232,34 @@ impl RenderCompiled {
samples,
indirect: lowered.support_indirect_command_buffers,
id: CONTENT_IDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
};
// Made whole before the `VkPipeline`, so dropping it releases what was made.
let class = match compiled.draws.patches {
true => vk::PrimitiveTopology::PATCH_LIST,
false => vk::PrimitiveTopology::TRIANGLE_LIST,
};
compiled.primary = compiled.make(class, Raster::default())?;
// A descriptor that names the line or the point class (`inputPrimitiveTopology`) gives
// that class's key: its `VkPipeline` is made here too, and its draws wait for none.
let named = match lowered.input_primitive_topology {
PrimitiveTopologyClass::Line => Some(vk::PrimitiveTopology::LINE_LIST),
PrimitiveTopologyClass::Point => Some(vk::PrimitiveTopology::POINT_LIST),
_ => None,
};
if let (false, Some(list)) = (compiled.draws.patches, named) {
let made = compiled.make(list, Raster::default())?;
lock(&compiled.later).push((list, Raster::default(), made));
})
}
/// Makes the content's main `VkPipeline`s on the calling thread where they are neither made
/// nor being made ([`RenderPipelineState::finish_pipeline`]): the primary class's, then the
/// named class's, each counted as made, both tried where the first fails. Err: the first
/// make's error, the call counted as failed.
fn finish(&self) -> Result<(), Error> {
let primary = (
self.class(vk::PrimitiveTopology::TRIANGLE_LIST),
&self.primary,
);
let named = (self.named.as_ref()).map(|(list, named)| (*list, named));
let mut failed = None;
for (class, main) in std::iter::once(primary).chain(named) {
match main.make_ahead(|| self.make(class, Raster::default())) {
Ok(Some(nanos)) => self.core.counters.finished(nanos),
Ok(None) => {}
Err(error) => failed = failed.or(Some(error)),
}
}
match failed {
Some(error) => {
self.core.counters.finish_failed();
Err(error)
}
None => Ok(()),
}
Ok(compiled)
}
/// The list topology of `topology`'s class, which its `VkPipeline` is made with: a
@@ -1167,9 +1289,10 @@ impl RenderCompiled {
/// The `VkPipeline` of the content for draws of `topology`'s class, a point, line or triangle
/// one, or for a post-tessellation vertex function's content the patch one, which the encoder
/// draws alone with it, under `raster`, whose fill mode a line or point class does not take:
/// one the content was not made with is made by its first draw, which waits for it, a
/// first-use wait ([`Metrics::first_use_waits`](crate::Metrics::first_use_waits)), counted as
/// the line or point class's at the default raster state and as a raster state's otherwise.
/// one not made yet is made by its first draw, which waits for it, or for the make in flight
/// of a main one, a first-use wait ([`Metrics::first_use_waits`](crate::Metrics::first_use_waits)),
/// counted as a main pipeline's before its `finish_pipeline` made it, as the line or point
/// class's at the default raster state, and as a raster state's otherwise.
///
/// Err: [`Error::Vulkan`] where the pipeline cannot be made.
pub(crate) fn pipeline(
@@ -1184,8 +1307,14 @@ impl RenderCompiled {
clamp: raster.clamp,
lines: raster.lines && polygons,
};
let counters = &self.core.counters;
if polygons && raster == Raster::default() {
return Ok(self.primary);
return (self.primary).pipeline(counters, || self.make(class, raster));
}
if let Some((list, named)) = &self.named {
if (*list, raster) == (class, Raster::default()) {
return named.pipeline(counters, || self.make(class, raster));
}
}
let mut later = lock(&self.later);
if let Some(&(.., made)) = (later.iter()).find(|&&(c, r, _)| (c, r) == (class, raster)) {
@@ -1350,6 +1479,38 @@ fn release(core: &Core, stages: &[Module]) {
}
impl RenderPipelineState {
/// No Metal counterpart: makes the state's main `VkPipeline`s on the calling thread, through
/// the device's pipeline cache, once the state's creation has answered. Metal compiles a
/// render state when the state is made. Here the creation does everything up to the driver's
/// create (the lowerings, every refusal and Metal's own errors, the shader modules and the
/// samplers' numbering) and answers, and this call runs the driver's create, so a consumer
/// can answer the program before the driver's compile ends and let that compile overlap the
/// program's own work. The runtime starts no thread for it: the consumer calls it on a thread
/// of its own after it has answered.
///
/// The main pipelines are the triangle class's (a post-tessellation vertex function's patch
/// class's, its only class) and, where the descriptor's `inputPrimitiveTopology` names the
/// line or the point class, that class's, each at the default depth clip and fill modes. Each
/// is made where it is neither made nor being made, so a second call makes nothing. A draw
/// that needs one first waits for the make in flight, or makes it itself where none is: a
/// first-use wait
/// ([`Metrics::first_use_unfinished_waits`](crate::Metrics::first_use_unfinished_waits)),
/// after which it records what it records with the pipeline made here. So a state this is
/// never called for draws as one it was called for, its first draw making the pipeline.
///
/// Counted as [`Metrics::finished_pipelines`](crate::Metrics::finished_pipelines), with their
/// time.
///
/// Err: [`Error::Vulkan`] where a driver's create failed, which Metal would have answered at
/// the creation (Vulkan lets it fail for exhausted host or device memory, or with
/// `VK_ERROR_UNKNOWN` or `VK_ERROR_VALIDATION_FAILED`), counted in
/// [`Metrics::failed_finishes`](crate::Metrics::failed_finishes), the other main pipeline
/// still made: the failed one is not kept, the first draw that needs it makes it again, and
/// that draw answers the driver's error where that make fails too.
pub fn finish_pipeline(&self) -> Result<(), Error> {
self.inner.compiled.finish()
}
/// No Metal counterpart: the translator's notes of where this pipeline's answers may differ
/// from Metal's, of its modules ([`PrecisionNote`]), and
/// [`PrecisionNote::SwizzledOpaqueBlackBorder`] where a function samples through a constexpr
@@ -1444,12 +1605,12 @@ impl Drop for RenderCompiled {
// No state holds it, so no command buffer that used it is left: each kept its state until
// it retired.
self.core.counters.fall(Gauge::RenderContents);
// Only what was made: a main pipeline no call or draw made, or whose make failed, is none.
let named = (self.named.iter()).filter_map(|(_, named)| named.get());
let later = self.later.get_mut().unwrap_or_else(|e| e.into_inner());
let later = later.iter().map(|&(.., pipeline)| pipeline);
for pipeline in std::iter::once(self.primary).chain(later) {
if pipeline != vk::Pipeline::null() {
(self.core.reaper).give(Job::Free(Free::Pipeline(pipeline)));
}
for pipeline in (self.primary.get().into_iter()).chain(named).chain(later) {
(self.core.reaper).give(Job::Free(Free::Pipeline(pipeline)));
}
release(&self.core, &self.stages);
}
@@ -56,15 +56,19 @@ mod on_device {
}
}
/// The state of `f`, its main pipeline then finished, as a consumer finishes it once it has
/// answered.
fn pipeline(name: &str, device: &Device, library: &Library, f: &str) -> ComputePipelineState {
let source = StageSource::Function(FunctionDescriptor::new(
library.function(f).expect("the function"),
));
(device.new_compute_pipeline_state(
let state = (device.new_compute_pipeline_state(
&ComputePipelineDescriptor::new(source),
crate::tests::no_constexpr_samplers,
))
.unwrap_or_else(|error| panic!("{name}: {f}: {error}"))
.unwrap_or_else(|error| panic!("{name}: {f}: {error}"));
(state.finish_pipeline()).unwrap_or_else(|error| panic!("{name}: {f}: {error}"));
state
}
/// The form `state` runs a direct dispatch in.
@@ -351,10 +355,10 @@ mod on_device {
/// `ComputePipelineState::dispatch_variant` keys the dispatches of `tiles_mark`, a tiling
/// kernel, by the `VkPipeline` each runs: every direct dispatch, whatever its grid, its call
/// and its threadgroup size, runs the kernel's tiles, the pipeline made with the state, so
/// they share one key and prepared they make nothing; an indirect dispatch runs the whole
/// module at its own size, without tiles, one key and one pipeline for each size. The state's
/// creation and the preparations make one pipeline for each key.
/// and its threadgroup size, runs the kernel's tiles, the main pipeline its finish_pipeline
/// makes, so they share one key and prepared they make nothing; an indirect dispatch runs
/// the whole module at its own size, without tiles, one key and one pipeline for each size.
/// The state's finish_pipeline and the preparations make one pipeline for each key.
#[test]
fn every_device_keys_a_tiling_kernel_s_dispatches_by_the_pipeline_they_run() {
use crate::Dispatch;
@@ -402,7 +406,7 @@ mod on_device {
after.made_ahead_variants - made.made_ahead_variants,
),
(pipelines.len() as u64, pipelines.len() as u64 - 1),
"{name}: one pipeline for each key, the tiles' made with the state"
"{name}: one pipeline for each key, the tiles' made by finish_pipeline"
);
println!(
"dispatch tiles variant: {name}: {} dispatches, {} keys",
@@ -417,7 +421,7 @@ mod on_device {
/// runs, the whole module at that size, though Metal requires every dispatch of the state to
/// give it. The indirect dispatch's pipeline is made at its first use: here the
/// `prepare_dispatch` call, which makes one. This pins the gap as it is; a make that makes the
/// indirect pipeline with the state turns its first `made` true and fails here.
/// indirect pipeline with the main one turns its first `made` true and fails here.
#[test]
fn every_device_makes_a_tiling_kernel_s_indirect_pipeline_at_its_required_size_at_first_use() {
use crate::Dispatch;
@@ -435,6 +439,7 @@ mod on_device {
let state = (device
.new_compute_pipeline_state(&descriptor, crate::tests::no_constexpr_samplers))
.unwrap_or_else(|error| panic!("{name}: {error}"));
state.finish_pipeline().expect("finished");
assert_eq!(form(&state), "tiled", "{name}: the form");
let made = |dispatch: Dispatch| {
(state.dispatch_variant(dispatch, REQUIRED, &[]))
@@ -443,11 +448,11 @@ mod on_device {
};
assert!(
made(Dispatch::Threadgroups([9, 5, 1])),
"{name}: the tiles' pipeline, made with the state"
"{name}: the tiles' pipeline, made by finish_pipeline"
);
assert!(
!made(Dispatch::Indirect),
"{name}: the indirect dispatch's pipeline, made with the state"
"{name}: the indirect dispatch's pipeline, not made by finish_pipeline"
);
let counters = device.counters();
let before = counters.metrics();
@@ -459,7 +464,7 @@ mod on_device {
);
assert!(made(Dispatch::Indirect), "{name}: made");
println!(
"dispatch tiles required: {name}: tiles made with the state, the indirect \
"dispatch tiles required: {name}: tiles made by finish_pipeline, the indirect \
dispatch's at {REQUIRED:?} at its first use"
);
});
+157 -13
View File
@@ -17,16 +17,17 @@
//! 2,000 more each with a vertex buffer and a fragment texture set before it, add no locked
//! instruction.
//! - a draw of lines makes its content's line `VkPipeline` once, a first-use wait, and draws
//! its row; a state whose descriptor names the line class makes it with the state, and its
//! first draw of lines makes nothing and waits for nothing.
//! its row; a state whose descriptor names the line class makes it at its
//! finish_pipeline, and its first draw of lines makes nothing and waits for nothing.
//! - lines draw at width 1 alone: at width 2 a draw of lines or a line strip is
//! `DrawKind::LineWidth` and a triangle draws; at 1 again, and in a later encoder, lines draw.
//! - points (the owned fixture `engine/rt6_render_state.ll`'s `rt6_point`, of
//! `[[point_size]]` 4) cover the pixels whose centres their square holds, the content's
//! point `VkPipeline` made at its first draw of points, a first-use wait; a state whose
//! descriptor names the point class makes that pipeline with the state, and its points of a
//! function without `[[point_size]]` are 1 pixel each; under another class such points
//! rasterize nothing, and a triangle drawn after them draws through the encoder's scissor.
//! descriptor names the point class makes that pipeline at its finish_pipeline, and its
//! points of a function without `[[point_size]]` are 1 pixel each; under another class
//! such points rasterize nothing, and a triangle drawn after them draws through the
//! encoder's scissor.
//! - a stencil state that replaces the stencil marks what a draw covers, and one that tests it
//! keeps a later draw to those pixels.
//! - a pass clears, loads and stores a shader-read `Depth32Float` depth attachment that its
@@ -180,10 +181,23 @@ pub(crate) mod on_device {
d
}
/// The state of `d` on `device`, its main pipelines then finished, as a consumer finishes
/// them once it has answered.
pub(crate) fn state(
name: &str,
device: &Device,
d: &RenderPipelineDescriptor,
) -> RenderPipelineState {
let state = unfinished(name, device, d);
(state.finish_pipeline()).unwrap_or_else(|error| panic!("{name}: finished: {error}"));
state
}
/// The state of `d` on `device`, its main pipelines not made yet.
pub(crate) fn unfinished(
name: &str,
device: &Device,
d: &RenderPipelineDescriptor,
) -> RenderPipelineState {
(device.new_render_pipeline_state(d, crate::tests::no_constexpr_samplers))
.unwrap_or_else(|error| panic!("{name}: {error}"))
@@ -699,8 +713,8 @@ pub(crate) mod on_device {
}
/// A state whose descriptor names the line class (`inputPrimitiveTopology`) makes its line
/// pipeline with the state, beside the triangle one: its first draw of lines makes nothing and
/// waits for nothing, and draws its row.
/// pipeline as a main one, its `finish_pipeline` making it beside the triangle one: its
/// first draw of lines makes nothing and waits for nothing, and draws its row.
#[test]
fn every_device_makes_a_line_class_state_s_line_pipeline_at_its_make() {
use metal2vulkan::metal::PrimitiveTopologyClass;
@@ -718,7 +732,7 @@ pub(crate) mod on_device {
assert_eq!(
created.pipelines_created - made.pipelines_created,
2,
"{name}: the triangle and the line pipelines, made with the state"
"{name}: the triangle and the line pipelines, made by finish_pipeline"
);
// A line across row 2's centres, Metal's y up.
let y = 1.0 - 2.5 / 4.0;
@@ -755,7 +769,137 @@ pub(crate) mod on_device {
let i = ((2 * SIDE + x) * 4) as usize;
assert_eq!(texels[i..i + 4], rgba8(GREEN), "{name}: ({x}, 2)");
}
println!("{name}: the line class's pipeline made with the state; its lines drew");
println!("{name}: the line class's pipeline made by finish_pipeline; its lines drew");
});
}
/// A render state answers before its main pipeline is made: its creation makes no
/// `VkPipeline` and answers what Metal's state answers, every answer the same after the finish
/// as before it. Its `finish_pipeline` makes the
/// triangle class's after the answer, counted as finished, a second call makes nothing, and a
/// draw then waits for nothing. A state of another content that is never finished draws the
/// same texels: its first draw makes the pipeline, a first-use wait on an unfinished
/// pipeline, and a `finish_pipeline` after it makes nothing.
#[test]
fn every_device_answers_a_render_state_before_its_main_pipeline_is_made() {
let Some(library) = examples() else {
return;
};
let d = descriptor(&library, "colored_fragment", PixelFormat::RGBA8Unorm);
// Another content drawing the same: blending at its default factors keeps the source.
let mut blended = d.clone();
if let Some(color) = &mut blended.color_attachments[0] {
color.blending_enabled = true;
}
let want = texels(|_, y| if y < 4 { GREEN } else { BLACK });
each_device("render_answered_early", |name, _, device| {
let counters = device.counters();
let mut buffers = Buffers::new(&device);
let (positions, colors) = vertices(&device, &mut buffers);
let queue = device.new_command_queue(4).expect("a queue");
// The texels of the fixture's top half drawn green by `state` into a new target.
let drawn = |state: &RenderPipelineState| {
let color = target(
&device,
PixelFormat::RGBA8Unorm,
TextureUsage::RENDER_TARGET,
);
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder = (command_buffer.render_command_encoder(&pass(&color, None)))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let draw =
|result: Result<(), Error>| result.unwrap_or_else(|e| panic!("{name}: {e}"));
draw(encoder.set_render_pipeline_state(state));
draw(encoder.set_vertex_buffer(Some(&positions), 0, 0));
draw(encoder.set_vertex_buffer(Some(&colors), 0, 1));
draw(encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0));
encoder.end_encoding();
run(name, &command_buffer);
read(&color, 4)
};
// The pipelines made, finished, failed to finish and waited for unfinished.
let moved = |before: &crate::Metrics, after: &crate::Metrics| {
(
after.pipelines_created - before.pipelines_created,
after.finished_pipelines - before.finished_pipelines,
after.failed_finishes - before.failed_finishes,
after.first_use_unfinished_waits - before.first_use_unfinished_waits,
)
};
// Every answer of the state.
let answers = |state: &RenderPipelineState| {
(
state.precision_notes(),
state.texture_accesses(crate::Stage::Vertex),
state.texture_accesses(crate::Stage::Fragment),
state.imageblock_sample_length().ok(),
state
.imageblock_memory_length_for_dimensions([8, 4, 3])
.ok(),
state.support_indirect_command_buffers(),
)
};
let before = counters.metrics();
let state = unfinished(name, &device, &d);
let answered = counters.metrics();
assert_eq!(
moved(&before, &answered),
(0, 0, 0, 0),
"{name}: no pipeline at the answer"
);
let early = answers(&state);
assert_eq!(
state.imageblock_sample_length().ok(),
Some(4),
"{name}: Metal's answer"
);
state.finish_pipeline().expect("finished");
assert_eq!(
answers(&state),
early,
"{name}: every answer is the same before the finish and after it"
);
let finished_at = counters.metrics();
assert_eq!(
moved(&answered, &finished_at),
(1, 1, 0, 0),
"{name}: the triangle class's pipeline, made after the answer"
);
assert!(
finished_at.finished_pipeline_nanos > answered.finished_pipeline_nanos,
"{name}: the finish's time"
);
state.finish_pipeline().expect("finished again");
assert_eq!(drawn(&state), want, "{name}: the finished state's texels");
let after = counters.metrics();
assert_eq!(
(moved(&finished_at, &after), after.first_use_waits),
((0, 0, 0, 0), finished_at.first_use_waits),
"{name}: a second finish and a draw make nothing and wait for nothing"
);
let before = counters.metrics();
let never = unfinished(name, &device, &blended);
assert_eq!(drawn(&never), want, "{name}: the unfinished state's texels");
let drawn_at = counters.metrics();
assert_eq!(
moved(&before, &drawn_at),
(1, 0, 0, 1),
"{name}: the draw made the unfinished pipeline and waited for it"
);
never.finish_pipeline().expect("finished after the draw");
assert_eq!(
moved(&drawn_at, &counters.metrics()),
(0, 0, 0, 0),
"{name}: a finish after the draw makes nothing"
);
println!(
"{name}: answered with no pipeline made; finished after the answer in {} ns; an \
unfinished state's draw made its pipeline in {} ns",
finished_at.finished_pipeline_nanos - answered.finished_pipeline_nanos,
drawn_at.first_use_unfinished_wait_nanos - before.first_use_unfinished_wait_nanos,
);
});
}
@@ -859,10 +1003,10 @@ pub(crate) mod on_device {
/// Points of `[[point_size]]` 4 (`rt6_point`, one at the target's centre) cover the 4 by 4
/// pixels whose centres their square holds; the first draw of points makes the content's
/// point pipeline, a first-use wait, and a second makes nothing. A state whose descriptor
/// names the point class makes its point pipeline with the state, and draws a point of a
/// function without `[[point_size]]` (`colored_vertex`) 1 pixel wide, its first draw making
/// and waiting for nothing. Under no class such points rasterize nothing, as Metal's, and a
/// triangle drawn after them in the encoder draws through its scissor again.
/// names the point class makes its point pipeline at its finish_pipeline, and draws a point
/// of a function without `[[point_size]]` (`colored_vertex`) 1 pixel wide, its first draw
/// making and waiting for nothing. Under no class such points rasterize nothing, as
/// Metal's, and a triangle drawn after them in the encoder draws through its scissor again.
#[test]
fn every_device_draws_points_at_their_size_and_a_point_class_s_at_1() {
use metal2vulkan::metal::PrimitiveTopologyClass;
@@ -93,14 +93,18 @@ mod on_device {
ComputePipelineDescriptor::new(StageSource::Function(function))
}
/// The state of `descriptor` on `device`, its main pipeline then finished, as a consumer
/// finishes it once it has answered.
fn state(
name: &str,
device: &Device,
descriptor: &ComputePipelineDescriptor,
) -> ComputePipelineState {
device
let state = device
.new_compute_pipeline_state(descriptor, crate::tests::no_constexpr_samplers)
.unwrap_or_else(|error| panic!("{name}: {error}"))
.unwrap_or_else(|error| panic!("{name}: {error}"));
(state.finish_pipeline()).unwrap_or_else(|error| panic!("{name}: finished: {error}"));
state
}
/// Whether two states share their compiled kernel.
@@ -0,0 +1,99 @@
//! A render content's main pipeline cell (`crate::render::Main`), without a device: what a state's
//! `finish_pipeline` and a draw before it do with it, a driver's create that fails after the
//! state's answer included.
//!
//! - A finish whose make fails keeps nothing. A draw then makes the pipeline itself, a first-use
//! wait on an unfinished pipeline; where its make fails too it answers the driver's error and
//! counts no wait, and the next draw makes it. Once made, a draw reads it and a finish makes
//! nothing.
//! - A draw that meets a finish's make in flight makes nothing itself: it waits for that make and
//! takes its pipeline, and a second finish meanwhile makes nothing.
use crate::counters::Counters;
use crate::render::Main;
use crate::Error;
use ash::vk;
use ash::vk::Handle;
use std::sync::mpsc;
/// The driver's error of a create that failed: device memory exhausted, one of the failures
/// Vulkan lets `vkCreateGraphicsPipelines` answer a valid create with.
fn failed() -> Result<vk::Pipeline, Error> {
Err(Error::Vulkan {
call: "vkCreateGraphicsPipelines",
result: vk::Result::ERROR_OUT_OF_DEVICE_MEMORY,
})
}
/// Whether `made` is the driver's error [`failed`] gives.
fn is_failed<T>(made: &Result<T, Error>) -> bool {
matches!(
made,
Err(Error::Vulkan {
result: vk::Result::ERROR_OUT_OF_DEVICE_MEMORY,
..
})
)
}
#[test]
fn a_failed_finish_keeps_nothing_and_the_first_draw_makes_the_pipeline_again() {
let counters = Counters::new();
let main = Main::default();
let pipeline = vk::Pipeline::from_raw(7);
let waits = || counters.metrics().first_use_unfinished_waits;
assert!(is_failed(&main.make_ahead(failed)), "the finish's error");
assert!(
is_failed(&main.pipeline(&counters, failed)),
"a draw whose make fails too answers the driver's error"
);
assert_eq!(waits(), 0, "a draw that made nothing counts no wait");
let made = main.pipeline(&counters, || Ok(pipeline));
assert_eq!(made.ok(), Some(pipeline), "the next draw makes it");
assert_eq!(waits(), 1, "a first-use wait on an unfinished pipeline");
let read = main.pipeline(&counters, || panic!("a made pipeline is not made again"));
assert_eq!(read.ok(), Some(pipeline), "a draw reads it");
let finish = main.make_ahead(|| panic!("a made pipeline is not made again"));
assert_eq!(finish.ok(), Some(None), "a finish makes nothing");
assert_eq!(waits(), 1, "a draw that read it counts no wait");
}
#[test]
fn a_draw_during_a_finish_waits_for_its_make() {
let counters = Counters::new();
let main = Main::default();
let pipeline = vk::Pipeline::from_raw(9);
let (started, start) = mpsc::channel();
let (release, released) = mpsc::channel::<()>();
let (main, counters) = (&main, &counters);
std::thread::scope(|scope| {
let finish = scope.spawn(move || {
main.make_ahead(move || {
started.send(()).expect("the test's channel");
released.recv().expect("the test's channel");
Ok(pipeline)
})
});
start.recv().expect("the finish's make began");
let draw = scope.spawn(move || {
main.pipeline(counters, || {
panic!("a draw makes nothing while a finish makes it")
})
});
let again = main.make_ahead(|| panic!("a second finish makes nothing meanwhile"));
assert_eq!(again.ok(), Some(None), "a second finish");
release.send(()).expect("the finish's make waits");
let finished = finish.join().expect("the finish");
assert!(matches!(finished, Ok(Some(_))), "the finish made it");
let drawn = draw.join().expect("the draw");
assert_eq!(
drawn.ok(),
Some(pipeline),
"the draw took the finish's pipeline"
);
});
assert!(
counters.metrics().first_use_unfinished_waits <= 1,
"a draw that met the make in flight waited once, one after it none"
);
}
@@ -57,6 +57,7 @@ mod linear_planes;
mod locks;
mod lost_writes;
mod lowered;
mod main_cells;
mod make_parts;
mod maker_yield;
mod managed;
@@ -86,9 +86,10 @@ mod on_device {
d
}
/// The state of `d` on `device`, its main pipelines then finished, as a consumer finishes
/// them once it has answered.
fn state(name: &str, device: &Device, d: &RenderPipelineDescriptor) -> RenderPipelineState {
(device.new_render_pipeline_state(d, crate::tests::no_constexpr_samplers))
.unwrap_or_else(|error| panic!("{name}: {error}"))
crate::tests::draw::on_device::state(name, device, d)
}
/// Whether two states share their compiled content.
@@ -106,7 +106,8 @@ mod on_device {
}
/// The state of the harness's kernel `name`, its numbered samplers given `ids`, after checking
/// they are `numbered`.
/// they are `numbered`, its main pipeline then finished, as a consumer finishes it once it has
/// answered.
fn state(
device: &Device,
library: &Library,
@@ -118,10 +119,12 @@ mod on_device {
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(function),
));
device.new_compute_pipeline_state(&descriptor, |samplers| {
let state = device.new_compute_pipeline_state(&descriptor, |samplers| {
assert!(numbered(samplers), "{name}: {samplers:?}");
Ok(ids)
})
})?;
state.finish_pipeline()?;
Ok(state)
}
/// Texel `(x, y)` of the source: its channels, in sixteenths a half holds exactly.
@@ -995,7 +998,7 @@ mod on_device {
assert_eq!(
created.pipelines_created - made.pipelines_created,
1,
"{name}: the square workgroups' pipeline, made with the state"
"{name}: the square workgroups' pipeline, made by finish_pipeline"
);
let queue = device.new_command_queue(4).expect("a queue");
let runs = [
@@ -1,6 +1,6 @@
//! Translated kernels, under a device cfg on every device of the cfg's kind. A kernel that does not
//! observe its threadgroup partition runs every direct dispatch in tiles of 256 threads on the one
//! `VkPipeline` made with its state, and an indirect dispatch at its own threadgroup size; a
//! `VkPipeline` its finish_pipeline makes, and an indirect dispatch at its own threadgroup size; a
//! precise one answers the same words in a tile as at the app's shape. A kernel that does observe it runs whole grids at
//! their own size, a `dispatchThreads` grid that is not a whole number of threadgroups on its
//! partial-threadgroups variant, and a threadgroup count past the device's limit split; one whose
@@ -76,12 +76,25 @@ mod on_device {
)))
}
/// The state of `descriptor` on `device`, printing what the translator gave where it is
/// refused: the plain module, and for a `Function` kernel its partial-threadgroups variant.
/// The state of `descriptor` on `device`, its main pipeline then finished, as a consumer
/// finishes it once it has answered; printing what the translator gave where it is refused:
/// the plain module, and for a `Function` kernel its partial-threadgroups variant.
fn state(
name: &str,
device: &Device,
descriptor: &ComputePipelineDescriptor,
) -> ComputePipelineState {
let state = unfinished(name, device, descriptor);
(state.finish_pipeline()).unwrap_or_else(|error| panic!("{name}: finished: {error}"));
state
}
/// The state of `descriptor` on `device`, its main pipeline not made yet, printing what the
/// translator gave where it is refused, as [`state`] does.
fn unfinished(
name: &str,
device: &Device,
descriptor: &ComputePipelineDescriptor,
) -> ComputePipelineState {
device
.new_compute_pipeline_state(descriptor, crate::tests::no_constexpr_samplers)
@@ -301,7 +314,7 @@ mod on_device {
assert_eq!(
created.pipelines_created - made.pipelines_created,
1,
"{name}: the tiles' pipeline, made with the state"
"{name}: the tiles' pipeline, made by finish_pipeline"
);
assert_eq!(created.first_use_waits, made.first_use_waits, "{name}");
let queue = device.new_command_queue(4).expect("a queue");
@@ -808,10 +821,11 @@ mod on_device {
}
/// Each make of a kernel's `VkPipeline` is kept in the device's counters with its key and who
/// started it: a tiling kernel's tiles by the state's creation, a size `prepare_dispatch` was
/// given by that call, and a size only a dispatch gives by the dispatch, a first-use wait
/// counted on the make. Each key is the one `dispatch_variant` answers for the dispatch, and
/// the first-use waits the dispatch added are the waits its make counts.
/// started it: a tiling kernel's tiles by its state's `finish_pipeline`, a size
/// `prepare_dispatch` was given by that call, and a size only a dispatch gives by the
/// dispatch, a first-use wait counted on the make. Each key is the one `dispatch_variant`
/// answers for the dispatch, and the first-use waits the dispatch added are the waits its make
/// counts.
#[test]
fn every_device_keeps_each_variant_make_with_its_key_and_who_started_it() {
use crate::{Counters, Dispatch, VariantMake, VariantStart};
@@ -843,7 +857,7 @@ mod on_device {
.map(|(variant, _)| variant);
assert_eq!(
(Some(make.variant), make.start, make.waits, make.first_wait),
(key, VariantStart::State, 0, 0),
(key, VariantStart::Finish, 0, 0),
"{name}: the state's tiles"
);
@@ -897,6 +911,256 @@ mod on_device {
});
}
/// A state answers before its main pipeline is made: its creation makes no `VkPipeline` and
/// answers what Metal's state answers, the tiles' key answered not made; every answer but
/// that one bit is the same after the finish as before it. Its
/// `finish_pipeline` makes that pipeline after the answer, counted as finished and kept as a
/// make the call started, a second call makes nothing, and a dispatch then waits for nothing.
/// A state of another content that is never finished is dispatched all the same: the dispatch
/// makes its main pipeline, a first-use wait on an unfinished pipeline, and a
/// `finish_pipeline` after it makes nothing.
#[test]
fn every_device_answers_a_state_before_its_main_pipeline_is_made() {
use crate::{Dispatch, Metrics, VariantStart};
let Some(descriptor) = descriptor("a1_bool_from_float") else {
return;
};
// Another content of the same kernel: a required size is part of a content's key.
let mut required = descriptor.clone();
required.required_threads_per_threadgroup = Some([GROUP, 1, 1]);
each_device("compute_answered_early", |name, _, device| {
let counters = device.counters();
let mut buffers = Buffers::new(&device, 64 * 1024);
let slots: Vec<Buffer> = (0..3).map(|_| buffers.buffer(8 * 1024)).collect();
let queue = device.new_command_queue(4).expect("a queue");
let dispatch = |state: &ComputePipelineState| {
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut encoder = command_buffer
.compute_command_encoder(DispatchType::Serial)
.expect("an encoder");
encoder.set_compute_pipeline_state(state).expect("a state");
for (index, slot) in (0..).zip(&slots) {
encoder.set_buffer(Some(slot), 0, index).expect("a buffer");
}
encoder
.dispatch_threads([WIDE, 1, 1], [GROUP, 1, 1])
.expect("a dispatch");
encoder.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
};
// The pipelines made, finished, failed to finish and waited for unfinished.
let moved = |before: &Metrics, after: &Metrics| {
(
after.pipelines_created - before.pipelines_created,
after.finished_pipelines - before.finished_pipelines,
after.failed_finishes - before.failed_finishes,
after.first_use_unfinished_waits - before.first_use_unfinished_waits,
)
};
let tiles = |state: &ComputePipelineState| {
state.dispatch_variant(Dispatch::Threads([WIDE, 1, 1]), [GROUP, 1, 1], &[])
};
// Every answer of the state, `dispatch_variant`'s key among them but not whether its
// pipeline is made.
let answers = |state: &ComputePipelineState| {
(
state.max_total_threads_per_threadgroup(),
state.static_threadgroup_memory_length(),
state.thread_execution_width(),
state
.imageblock_memory_length_for_dimensions([8, 4, 3])
.ok(),
state.required_threads_per_threadgroup(),
state.support_indirect_command_buffers(),
state.texture_accesses(),
state.buffer_accesses(),
state.precision_notes(),
tiles(state).map(|(key, _)| key),
)
};
let before = counters.metrics();
let state = unfinished(name, &device, &descriptor);
let answered = counters.metrics();
assert_eq!(
moved(&before, &answered),
(0, 0, 0, 0),
"{name}: no pipeline at the answer"
);
let early = answers(&state);
assert_eq!(state.thread_execution_width(), 32, "{name}: Metal's answer");
assert!(state.max_total_threads_per_threadgroup() > 0, "{name}");
let (key, made) = tiles(&state).expect("the tiles' key");
assert!(
!made,
"{name}: the tiles' pipeline is not made at the answer"
);
state.finish_pipeline().expect("finished");
assert_eq!(
answers(&state),
early,
"{name}: every answer is the same before the finish and after it"
);
let finished_at = counters.metrics();
assert_eq!(
moved(&answered, &finished_at),
(1, 1, 0, 0),
"{name}: the main pipeline, made after the answer"
);
assert!(
finished_at.finished_pipeline_nanos > answered.finished_pipeline_nanos,
"{name}: the finish's time"
);
let make = *(counters.variant_makes(0).last()).expect("a make kept");
assert_eq!(
(make.variant, make.start, make.made, make.waits),
(key, VariantStart::Finish, true, 0),
"{name}: the finish's make"
);
assert_eq!(tiles(&state), Some((key, true)), "{name}: made");
state.finish_pipeline().expect("finished again");
dispatch(&state);
assert_eq!(
moved(&finished_at, &counters.metrics()),
(0, 0, 0, 0),
"{name}: a second finish and a dispatch make nothing"
);
assert_eq!(
counters.metrics().first_use_waits,
finished_at.first_use_waits,
"{name}: the dispatch waited for nothing"
);
let before = counters.metrics();
let never = unfinished(name, &device, &required);
dispatch(&never);
let dispatched = counters.metrics();
assert_eq!(
moved(&before, &dispatched),
(1, 0, 0, 1),
"{name}: the dispatch made the unfinished pipeline and waited for it"
);
assert!(
dispatched.first_use_unfinished_wait_nanos > before.first_use_unfinished_wait_nanos,
"{name}: the wait's time"
);
never
.finish_pipeline()
.expect("finished after the dispatch");
assert_eq!(
moved(&dispatched, &counters.metrics()),
(0, 0, 0, 0),
"{name}: a finish after the dispatch makes nothing"
);
println!(
"{name}: answered with no pipeline made; finished after the answer in {} ns; \
an unfinished state's dispatch made its pipeline in {} ns",
finished_at.finished_pipeline_nanos - answered.finished_pipeline_nanos,
dispatched.first_use_unfinished_wait_nanos - before.first_use_unfinished_wait_nanos,
);
});
}
/// A state's main pipeline is made once, whichever of its `finish_pipeline` and a
/// `prepare_dispatch` call for its key comes first: a preparation after the finish makes no
/// second `VkPipeline`, a finish after a preparation that made it makes nothing, and the two
/// called at once on threads of their own make one between them, the later returning at once
/// while the earlier makes it. So a consumer that reads `dispatch_variant`'s `made` false and
/// prepares costs no second driver create.
#[test]
fn every_device_makes_a_state_s_main_pipeline_once_across_its_finish_and_a_preparation() {
use crate::{Dispatch, Metrics};
use std::sync::Barrier;
use std::thread;
let Some(descriptor) = descriptor("a1_bool_from_float") else {
return;
};
// Contents of one kernel, a required size being part of a content's key, so that each
// order starts from a state whose main pipeline no other state made.
let sized = |size: u32| {
let mut sized = descriptor.clone();
sized.required_threads_per_threadgroup = Some([size, 1, 1]);
sized
};
let (prepared_first, at_once) = (sized(GROUP), sized(GROUP / 2));
each_device("compute_finish_and_prepare", |name, _, device| {
let counters = device.counters();
// The pipelines made, and the makes the finish and the preparation counted.
let moved = |before: &Metrics, after: &Metrics| {
(
after.pipelines_created - before.pipelines_created,
after.finished_pipelines - before.finished_pipelines,
after.made_ahead_variants - before.made_ahead_variants,
)
};
// A preparation of a direct dispatch, which runs the tiles, the main pipeline.
let prepare = |state: &ComputePipelineState, size: u32| {
(state.prepare_dispatch(Dispatch::Threads([WIDE, 1, 1]), [size, 1, 1], &[]))
.expect("prepared");
};
let state = unfinished(name, &device, &descriptor);
state.finish_pipeline().expect("finished");
let finished_at = counters.metrics();
prepare(&state, GROUP);
assert_eq!(
moved(&finished_at, &counters.metrics()),
(0, 0, 0),
"{name}: a preparation after the finish makes nothing"
);
let state = unfinished(name, &device, &prepared_first);
let before = counters.metrics();
prepare(&state, GROUP);
let prepared = counters.metrics();
assert_eq!(
moved(&before, &prepared),
(1, 0, 1),
"{name}: the preparation made the main pipeline"
);
state.finish_pipeline().expect("finished");
assert_eq!(
moved(&prepared, &counters.metrics()),
(0, 0, 0),
"{name}: a finish after the preparation makes nothing"
);
let state = unfinished(name, &device, &at_once);
let before = counters.metrics();
let start = Barrier::new(2);
thread::scope(|scope| {
let finishing = scope.spawn(|| {
start.wait();
state.finish_pipeline()
});
start.wait();
prepare(&state, GROUP / 2);
(finishing.join())
.expect("the finishing thread")
.expect("finished");
});
let (created, finished, ahead) = moved(&before, &counters.metrics());
assert_eq!(
(created, finished + ahead),
(1, 1),
"{name}: one make between a finish and a preparation at once"
);
println!(
"{name}: one main pipeline each: finish then prepare, prepare then finish, and \
both at once (made by the {})",
if finished == 1 {
"finish"
} else {
"preparation"
}
);
});
}
/// A state's make counts the time of its `vkCreateComputePipelines` calls in
/// `Metrics::pipeline_creation_nanos` and of its calls into the translator in
/// `translation_nanos`: each above 0, and the two, made on the make's own thread, within the
@@ -3046,7 +3310,7 @@ define void @nil_read_kernel(ptr addrspace(1) %in, ptr addrspace(1) %out, i32 %t
assert_eq!(
created.pipelines_created - made.pipelines_created,
1,
"{name}: the tiles' pipeline, made with the state"
"{name}: the tiles' pipeline, made by finish_pipeline"
);
assert_eq!(
created.first_use_waits, made.first_use_waits,
@@ -3119,7 +3383,7 @@ define void @nil_read_kernel(ptr addrspace(1) %in, ptr addrspace(1) %out, i32 %t
);
println!(
"{name}: row cells checked in 32 x 2, 64 x 8, 512 x 1, 64 x 4, 48 x 1 and 16 x 4 on \
the tiles' pipeline, made with the state"
the tiles' pipeline, made by finish_pipeline"
);
});
}
@@ -3158,7 +3422,7 @@ define void @nil_read_kernel(ptr addrspace(1) %in, ptr addrspace(1) %out, i32 %t
created.translations - made.translations,
),
(0, 1),
"{name}: no pipeline made with the state, and the variant alone lowered"
"{name}: no pipeline made by finish_pipeline, and the variant alone lowered"
);
let queue = device.new_command_queue(4).expect("a queue");
let run = |state: &ComputePipelineState, grid: [u32; 3], size: [u32; 3]| {
@@ -3269,7 +3533,7 @@ define void @nil_read_kernel(ptr addrspace(1) %in, ptr addrspace(1) %out, i32 %t
println!(
"{name}: row barrier reads checked in 512 x 4 and 512 x 3 in 32 x 2 and 96 x 5 in \
32 x 4, at their own size on the partial variant; declared bound 64: whole and \
ragged grids' pipeline made with the state"
ragged grids' pipeline made by finish_pipeline"
);
});
}
@@ -3306,7 +3570,7 @@ define void @nil_read_kernel(ptr addrspace(1) %in, ptr addrspace(1) %out, i32 %t
assert_eq!(
created.pipelines_created - made.pipelines_created,
1,
"{name}: the whole and ragged grids' pipeline, made with the state"
"{name}: the whole and ragged grids' pipeline, made by finish_pipeline"
);
let queue = device.new_command_queue(4).expect("a queue");
for threads in [128, 100] {
@@ -3343,7 +3607,7 @@ define void @nil_read_kernel(ptr addrspace(1) %in, ptr addrspace(1) %out, i32 %t
whole one on the partial variant"
);
println!(
"{name}: declared bound 64: 128 x 1 and 100 x 1 in 64 x 1 made with the state, \
"{name}: declared bound 64: 128 x 1 and 100 x 1 in 64 x 1 made by finish_pipeline, \
both on the partial variant"
);
});
@@ -3928,7 +4192,7 @@ $REGION_META!4 = !{i32 $OUT, !"air.buffer", !"air.location_index", i32 0, i32 1,
assert_eq!(
made.pipelines_created - before.pipelines_created,
1,
"{name}: {kernel}: the plain module's pipeline, made with the state"
"{name}: {kernel}: the plain module's pipeline, made by finish_pipeline"
);
}
let queue = device.new_command_queue(4).expect("a queue");
@@ -1722,14 +1722,17 @@ impl NewRuntime {
}
/// A compute pipeline state of `kernel`, its numbered constexpr samplers at indices of their
/// own, the same words at one index.
/// own, the same words at one index, its main pipeline then finished, as a consumer finishes
/// it once it has answered.
fn compute_pipeline_state(
&mut self,
descriptor: &rt::ComputePipelineDescriptor,
) -> Result<rt::ComputePipelineState, rt::Error> {
self.numbered(|device, ids| {
let state = self.numbered(|device, ids| {
device.new_compute_pipeline_state(descriptor, |samplers| ids(samplers))
})
})?;
state.finish_pipeline()?;
Ok(state)
}
/// The pipeline state `make` makes on the device with `ids`, which gives each numbered
@@ -3052,6 +3055,12 @@ impl Backend for NewRuntime {
),
("made_ahead_variants", metrics.made_ahead_variants),
("made_ahead_variant_nanos", metrics.made_ahead_variant_nanos),
(
"first_use_unfinished_waits",
metrics.first_use_unfinished_waits,
),
("finished_pipelines", metrics.finished_pipelines),
("failed_finishes", metrics.failed_finishes),
(
"partial_variant_whole_grids",
metrics.partial_variant_whole_grids,
@@ -291,9 +291,11 @@ impl NewRuntime {
)))
})?;
let mark = makes::Mark::new(&self.device, self.prepass.as_ref());
// Its main pipelines finished, as a consumer finishes them once it has answered.
let made = self.numbered(|device, ids| {
device.new_render_pipeline_state(&descriptor, |samplers| ids(samplers))
});
let made = made.and_then(|state| state.finish_pipeline().map(|()| state));
match made {
Ok(state) => {
let (device, prepass) = (&self.device, self.prepass.as_ref());
@@ -1496,6 +1496,9 @@ field metal2vulkan-runtime::Metrics.export_makes pub export_makes: Timed
field metal2vulkan-runtime::Metrics.exported_blocks_addressed pub exported_blocks_addressed: u64
field metal2vulkan-runtime::Metrics.external_acquires pub external_acquires: u64
field metal2vulkan-runtime::Metrics.external_releases pub external_releases: u64
field metal2vulkan-runtime::Metrics.failed_finishes pub failed_finishes: u64
field metal2vulkan-runtime::Metrics.finished_pipeline_nanos pub finished_pipeline_nanos: u64
field metal2vulkan-runtime::Metrics.finished_pipelines pub finished_pipelines: u64
field metal2vulkan-runtime::Metrics.first_use_line_wait_max_nanos pub first_use_line_wait_max_nanos: u64
field metal2vulkan-runtime::Metrics.first_use_line_wait_nanos pub first_use_line_wait_nanos: u64
field metal2vulkan-runtime::Metrics.first_use_line_waits pub first_use_line_waits: u64
@@ -1505,6 +1508,9 @@ field metal2vulkan-runtime::Metrics.first_use_point_waits pub first_use_point_wa
field metal2vulkan-runtime::Metrics.first_use_raster_wait_max_nanos pub first_use_raster_wait_max_nanos: u64
field metal2vulkan-runtime::Metrics.first_use_raster_wait_nanos pub first_use_raster_wait_nanos: u64
field metal2vulkan-runtime::Metrics.first_use_raster_waits pub first_use_raster_waits: u64
field metal2vulkan-runtime::Metrics.first_use_unfinished_wait_max_nanos pub first_use_unfinished_wait_max_nanos: u64
field metal2vulkan-runtime::Metrics.first_use_unfinished_wait_nanos pub first_use_unfinished_wait_nanos: u64
field metal2vulkan-runtime::Metrics.first_use_unfinished_waits pub first_use_unfinished_waits: u64
field metal2vulkan-runtime::Metrics.first_use_variant_wait_max_nanos pub first_use_variant_wait_max_nanos: u64
field metal2vulkan-runtime::Metrics.first_use_variant_wait_nanos pub first_use_variant_wait_nanos: u64
field metal2vulkan-runtime::Metrics.first_use_variant_waits pub first_use_variant_waits: u64
@@ -6243,6 +6249,7 @@ method metal2vulkan-runtime::ComputePipelineDescriptor::reflection pub fn reflec
method metal2vulkan-runtime::ComputePipelineDescriptor::slot_writes pub fn slot_writes(&self, budget: &crate::Budget) -> Result<SlotWrites, Error>
method metal2vulkan-runtime::ComputePipelineState::buffer_accesses pub fn buffer_accesses(&self) -> Vec<(u32, BindingAccess)>
method metal2vulkan-runtime::ComputePipelineState::dispatch_variant pub fn dispatch_variant(&self, dispatch: Dispatch, threads_per_threadgroup: [u32; 3], threadgroup_memory_lengths: &[(u32, u32)]) -> Option<(DispatchVariant, bool)>
method metal2vulkan-runtime::ComputePipelineState::finish_pipeline pub fn finish_pipeline(&self) -> Result<(), Error>
method metal2vulkan-runtime::ComputePipelineState::imageblock_memory_length_for_dimensions pub fn imageblock_memory_length_for_dimensions(&self, _dimensions: [u32; 3]) -> Result<u64, Error>
method metal2vulkan-runtime::ComputePipelineState::max_total_threads_per_threadgroup pub fn max_total_threads_per_threadgroup(&self) -> u32
method metal2vulkan-runtime::ComputePipelineState::precision_notes pub fn precision_notes(&self) -> Vec<PrecisionNote>
@@ -6409,6 +6416,7 @@ method metal2vulkan-runtime::RenderPipelineDescriptor::slot_writes pub fn slot_w
method metal2vulkan-runtime::RenderPipelineDescriptor::stages_using_direct_arguments pub fn stages_using_direct_arguments(&self, budget: &crate::Budget, entries: &StageEntries) -> Result<Vec<DirectArgumentUse>, Error>
method metal2vulkan-runtime::RenderPipelineDescriptor::unwritten_fragment_inputs pub fn unwritten_fragment_inputs(&self, budget: &crate::Budget, entries: &StageEntries) -> Result<Option<UnwrittenFragmentInputs>, Error>
method metal2vulkan-runtime::RenderPipelineDescriptor::vertex_returns_value pub fn vertex_returns_value(&self, budget: &crate::Budget, entries: &StageEntries) -> Result<bool, Error>
method metal2vulkan-runtime::RenderPipelineState::finish_pipeline pub fn finish_pipeline(&self) -> Result<(), Error>
method metal2vulkan-runtime::RenderPipelineState::imageblock_memory_length_for_dimensions pub fn imageblock_memory_length_for_dimensions(&self, dimensions: [u32; 3]) -> Result<u64, Error>
method metal2vulkan-runtime::RenderPipelineState::imageblock_sample_length pub fn imageblock_sample_length(&self) -> Result<u32, Error>
method metal2vulkan-runtime::RenderPipelineState::precision_notes pub fn precision_notes(&self) -> Vec<PrecisionNote>
@@ -9105,6 +9113,7 @@ variant metal2vulkan-runtime::TextureViewKind::SurfacePixelFormat SurfacePixelFo
variant metal2vulkan-runtime::TextureViewKind::TextureBuffer TextureBuffer
variant metal2vulkan-runtime::TextureViewKind::TextureType TextureType
variant metal2vulkan-runtime::VariantStart::Ahead Ahead
variant metal2vulkan-runtime::VariantStart::Finish Finish
variant metal2vulkan-runtime::VariantStart::FirstUse FirstUse
variant metal2vulkan-runtime::VariantStart::State State
variant metal2vulkan-runtime::VisibilityResultMode::Boolean Boolean
Can't render this file because it is too large.