player: each pipeline state's making split into the translator's, the driver's and the rest

What: the replay report gains a `pipeline makes N states: ...` summary line and up to ten
`pipeline make slowest K #ID KINDS ...` lines, documented in docs/REPLAY-STREAM.md. KINDS is
kernel, vertex or post-tessellation vertex, plus +fragment.

How: each render and compute state's making is read from metal2vulkan-runtime's own Metrics on
the player's thread before and after it, with the wall time on rt::host_time (the counters' own
clock): translation_nanos against pipeline_creation_nanos, and the rest as "other". No runtime
counter is added. rt makes every state on the calling thread, and the only other thread that can
run beside a making is the player's own pre-pass. So the pre-pass pool now tallies its
prepare_dispatch calls begun and ended. A making that ran while one of them ran is counted
("beside a pre-pass call") and marked, since its figures include that call's work. The compute
states' `pipeline I wall_nanos=` lines take their wall time from the same clock.

Why: the next cold number needs its cause beside it: per pipeline, the translator's work against
the driver's vkCreate*Pipelines.

Verified: replay::rt_replay::each_pipeline_state_s_making_is_split_into_the_translator_s_and_the_driver_s_time
on lavapipe (m3-max-60980, with fmt, clippy plain, m2v_gpu and m2v_cpu_icd, and workspace
Rustdoc green). Without the line it fails at the summary-line find. On a real card: the cold and
warm states-only plays of one recorded stream on an RTX 3090 (m3-max-60954).
This commit is contained in:
Anees Iqbal committed 2026-11-20 17:38:00 -08:00
1 parent d1e52ab533
commit 10d00d44b4
6 files changed
+335 -4

No files matched your search

@@ -0,0 +1,181 @@
//! Where each pipeline state's making went, from the runtime's own counters read on the play's
//! thread before and after it (`rt::Metrics`): the translator's time (`translation_nanos`), the
//! driver's (`pipeline_creation_nanos`, its `vkCreate*Pipelines` calls), and the rest of the
//! making's wall time, on the clock they count (`rt::host_time`). A making is cold where it lowered a function or made a `VkPipeline`
//! (`translations` or `pipelines_created` rose: the device held no content for the state), held
//! otherwise. The counters sum the calls of every thread, so a making while a call of the
//! pre-pass ran (`prepass::Pool::quiet`) counts that call's work too: such makings are counted
//! apart, and their times are not one making's.
use super::prepass::Pool;
use super::rt;
/// The slowest makings the report lists.
const SLOWEST: usize = 10;
/// A making's times, or the sum of several, in nanoseconds: its wall time, and of it the
/// translator's and the driver's.
#[derive(Clone, Copy, Default)]
struct Split {
wall: u64,
translation: u64,
driver: u64,
}
impl Split {
fn add(&mut self, other: Split) {
self.wall += other.wall;
self.translation += other.translation;
self.driver += other.driver;
}
/// `wall W ms = translation T ms + driver D ms + other O ms`.
fn text(&self) -> String {
let ms = |nanos: u64| nanos as f64 / 1e6;
let other = ms(self.wall) - ms(self.translation) - ms(self.driver);
format!(
"wall {:.3} ms = translation {:.3} ms + driver {:.3} ms + other {other:.3} ms",
ms(self.wall),
ms(self.translation),
ms(self.driver),
)
}
}
/// The makings of one kind summed: how many, and their times.
#[derive(Default)]
struct Sum {
states: u64,
split: Split,
}
/// One of the slowest makings.
struct Slow {
state: u64,
kinds: &'static str,
cold: bool,
beside: bool,
split: Split,
}
/// The counters a split reads: `translation_nanos`, `pipeline_creation_nanos`, `translations`
/// and `pipelines_created`.
fn read(device: &rt::Device) -> [u64; 4] {
let metrics = device.counters().metrics();
[
metrics.translation_nanos,
metrics.pipeline_creation_nanos,
metrics.translations,
metrics.pipelines_created,
]
}
/// A making's start: the pre-pass's calls begun where none ran then (no pre-pass, none), the
/// counters, and the clock.
pub(super) struct Mark {
quiet: Option<u64>,
counters: [u64; 4],
began: u64,
}
impl Mark {
/// A making that starts now on `device`, beside `prepass`.
pub(super) fn new(device: &rt::Device, prepass: Option<&Pool>) -> Mark {
let quiet = prepass.map_or(Some(0), Pool::quiet);
let counters = read(device);
Mark {
quiet,
counters,
began: rt::host_time(),
}
}
}
/// The pipeline states' makings, cold and held, the makings beside a pre-pass call, and the
/// slowest ([`SLOWEST`]), slowest first.
#[derive(Default)]
pub(super) struct Makes {
cold: Sum,
held: Sum,
beside: u64,
slowest: Vec<Slow>,
}
impl Makes {
/// The making `mark` started, of pipeline state `state`, ended with the state made: counted,
/// with `kinds` its stages' kinds where it is among the slowest. Its wall time.
pub(super) fn made(
&mut self,
mark: Mark,
device: &rt::Device,
prepass: Option<&Pool>,
state: u64,
kinds: impl FnOnce() -> &'static str,
) -> u64 {
let wall = rt::host_time().saturating_sub(mark.began);
let counters = read(device);
let quiet = (mark.quiet).is_some_and(|begun| prepass.is_none_or(|p| p.quiet_since(begun)));
let [translation, driver, lowered, pipelines] =
std::array::from_fn(|at| counters[at].saturating_sub(mark.counters[at]));
let cold = lowered > 0 || pipelines > 0;
let split = Split {
wall,
translation,
driver,
};
let sum = match cold {
true => &mut self.cold,
false => &mut self.held,
};
sum.states += 1;
sum.split.add(split);
self.beside += u64::from(!quiet);
let at = (self.slowest.iter())
.take_while(|slow| slow.split.wall >= wall)
.count();
if at < SLOWEST {
let slow = Slow {
state,
kinds: kinds(),
cold,
beside: !quiet,
split,
};
self.slowest.insert(at, slow);
self.slowest.truncate(SLOWEST);
}
wall
}
/// `pipeline makes N states: C cold, SPLIT; H held, SPLIT; B beside a pre-pass call ...`,
/// then `pipeline make slowest K #ID KINDS cold|held: SPLIT` for each of the slowest.
pub(super) fn lines(&self) -> Vec<String> {
let (cold, held) = (&self.cold, &self.held);
let mut lines = vec![format!(
"pipeline makes {} states: {} cold, {}; {} held, {}; {} beside a pre-pass call, whose \
work their times count",
cold.states + held.states,
cold.states,
cold.split.text(),
held.states,
held.split.text(),
self.beside,
)];
for (at, slow) in self.slowest.iter().enumerate() {
lines.push(format!(
"pipeline make slowest {} #{} {} {}: {}{}",
at + 1,
slow.state,
slow.kinds,
if slow.cold { "cold" } else { "held" },
slow.split.text(),
if slow.beside {
", beside a pre-pass call"
} else {
""
},
));
}
lines
}
}
@@ -15,6 +15,7 @@ mod guest_ram;
mod imports;
pub(super) mod indices;
mod judged;
mod makes;
pub(super) mod places;
mod prepass;
mod render;
@@ -525,6 +526,8 @@ pub struct NewRuntime {
/// Each compute pipeline state made, in order, and the kernels made so far.
creations: Vec<Creation>,
kernels: HashSet<Kernel>,
/// Where each pipeline state's making went: the translator's, the driver's and the rest.
makes: makes::Makes,
/// The device's `minImportedHostPointerAlignment`, where it imports host memory: the
/// alignment of the host pages a no-copy buffer's memory is imported from (`imports`).
host_alignment: Option<u64>,
@@ -923,6 +926,7 @@ impl NewRuntime {
block_bytes: [0; 2],
creations: Vec::new(),
kernels: HashSet::new(),
makes: makes::Makes::default(),
})
}
@@ -1677,7 +1681,7 @@ impl NewRuntime {
descriptor: &rt::ComputePipelineDescriptor,
kernel: Kernel,
) -> Result<Option<(Object, Made)>, PlayError> {
let began = std::time::Instant::now();
let mark = makes::Mark::new(&self.device, self.prepass.as_ref());
let state = match self.compute_pipeline_state(descriptor) {
Ok(state) => {
self.skips.states_made[1] += 1;
@@ -1688,8 +1692,10 @@ impl NewRuntime {
}
Err(error) => return Err(failed(call)(error)),
};
let (device, prepass) = (&self.device, self.prepass.as_ref());
let nanos = (self.makes).made(mark, device, prepass, call.result, || "kernel");
self.creations.push(Creation {
nanos: u64::try_from(began.elapsed().as_nanos()).unwrap_or(u64::MAX),
nanos,
new_kernel: self.kernels.insert(kernel),
});
unaddressed(Object::ComputePipeline(state))
@@ -3029,6 +3035,7 @@ impl Backend for NewRuntime {
// A maximum since the device was made: it does not sum, so it is not a frame's counter.
let longest = self.device.counters().metrics().commit_lock_wait_max_nanos;
lines.push(format!("commit lock wait longest {longest} ns"));
lines.extend(self.makes.lines());
if let Some(copies) = self.managed {
let from = match self.identity {
true => "the stream's device identity",
@@ -2,9 +2,11 @@
//! compute dispatches the read-ahead found due (`Backend::prepare`) with
//! `ComputePipelineState::prepare_dispatch`, each thread taking the next in stream order while
//! the play goes on. A dispatch that needs what one of them is making waits for that make alone.
//! The pool tallies the calls begun and ended, so that the play's thread can tell whether one
//! ran while it made a pipeline state (`makes`): the runtime's counters sum both threads' work.
use super::rt;
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed, Ordering::SeqCst};
use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Mutex, PoisonError};
use std::thread::JoinHandle;
@@ -24,6 +26,8 @@ pub(super) struct Pool {
/// Set at the drop: what is still queued is left.
stop: Arc<AtomicBool>,
threads: Vec<JoinHandle<()>>,
/// The `prepare_dispatch` calls begun and ended.
tally: Arc<[AtomicU64; 2]>,
}
impl Pool {
@@ -32,9 +36,11 @@ impl Pool {
let (queue, items) = channel::<Item>();
let items = Arc::new(Mutex::new(items));
let stop = Arc::new(AtomicBool::new(false));
let tally = Arc::new([AtomicU64::new(0), AtomicU64::new(0)]);
let threads = (0..width)
.filter_map(|at| {
let (items, stop) = (Arc::clone(&items), Arc::clone(&stop));
let tally = Arc::clone(&tally);
let run = move || loop {
let next = (items.lock().unwrap_or_else(PoisonError::into_inner)).recv();
let Ok((state, grid, size, lengths)) = next else {
@@ -43,7 +49,9 @@ impl Pool {
if stop.load(Relaxed) {
return;
}
tally[0].fetch_add(1, SeqCst);
state.prepare_dispatch(grid, size, &lengths);
tally[1].fetch_add(1, SeqCst);
};
let named = std::thread::Builder::new().name(format!("m2v-prepass-{at}"));
named.spawn(run).ok()
@@ -53,9 +61,22 @@ impl Pool {
queue: Some(queue),
stop,
threads,
tally,
}
}
/// The calls begun so far, where as many have ended; None where one runs.
pub(super) fn quiet(&self) -> Option<u64> {
let begun = self.tally[0].load(SeqCst);
(self.tally[1].load(SeqCst) == begun).then_some(begun)
}
/// Whether no call began since [`quiet`](Self::quiet) answered `begun`: then no call ran
/// from that answer to this one.
pub(super) fn quiet_since(&self, begun: u64) -> bool {
self.tally[0].load(SeqCst) == begun
}
/// Queues `item` for the next free thread.
pub(super) fn give(&self, item: Item) {
if let Some(queue) = &self.queue {
@@ -13,7 +13,7 @@
use super::super::args::{arg, data, index, list, metal, refuse, uint, Fields};
use super::super::translator::{self, attachment_keys, LINKED_KEYS, PASS_KEYS};
use super::encoders::first;
use super::{failed, unaddressed, NewRuntime, Object, Skips};
use super::{failed, makes, unaddressed, NewRuntime, Object, Skips};
use crate::replay::player::{Made, PlayError};
use crate::replay::stream::Call;
use crate::replay::value::Value;
@@ -230,6 +230,23 @@ macro_rules! set_attachment {
}};
}
/// The kinds of a render pipeline descriptor's stages: `vertex`, or `post-tessellation vertex`
/// where its vertex function draws patches (its `patchType` is not none, as the library states
/// it), then `+fragment` where it has a fragment function.
fn stage_kinds(descriptor: &rt::RenderPipelineDescriptor) -> &'static str {
let patches = match &descriptor.vertex {
rt::StageSource::Function(f) => (f.function.properties(&metal2vulkan::Budget::default()))
.is_ok_and(|p| p.patch_type() != metal2vulkan::metal::PatchType::None),
rt::StageSource::Compiled(_) => false,
};
match (patches, descriptor.fragment.is_some()) {
(false, false) => "vertex",
(false, true) => "vertex+fragment",
(true, false) => "post-tessellation vertex",
(true, true) => "post-tessellation vertex+fragment",
}
}
impl NewRuntime {
/// `newRenderPipelineStateWithDescriptor:error:`: its constexpr samplers numbered as a compute
/// pipeline state's are; skipped and counted where the runtime answers a typed gap or the
@@ -249,11 +266,15 @@ impl NewRuntime {
function.descriptor.with_linked(linked),
)))
})?;
let mark = makes::Mark::new(&self.device, self.prepass.as_ref());
let made = self.numbered(|device, ids| {
device.new_render_pipeline_state(&descriptor, |samplers| ids(samplers))
});
match made {
Ok(state) => {
let (device, prepass) = (&self.device, self.prepass.as_ref());
let kinds = || stage_kinds(&descriptor);
(self.makes).made(mark, device, prepass, call.result, kinds);
self.skips.states_made[0] += 1;
if !records_tessellation(&call.args) {
self.unrecorded_tessellation.states.insert(call.result);
@@ -11,6 +11,10 @@
//! says the play is no verdict past it: its gap, frame and call.
//! - A compute pipeline state the runtime answers with a typed gap is skipped and counted by the
//! gap, and a dispatch of it is skipped, and the play goes on.
//! - Each pipeline state's making is split by the runtime's counters into the translator's time,
//! the driver's and the rest: a kernel's first state and a render state are cold, each with
//! both halves, and a second state of the kernel is held, with no driver time; the slowest are
//! listed by object, with their stages' kinds.
//! - A compute encoder's `setStageInRegion:` plays: the runtime takes it.
//! - The host's library from source is made of its display library where the backend has it, a
//! function of it with it; without it both are skipped.
@@ -1016,6 +1020,90 @@ fn a_compute_state_the_runtime_does_not_build_is_counted_and_its_dispatch_skippe
assert!(lines.iter().any(|l| l.starts_with(line)), "{lines:?}");
}
/// The milliseconds `line` gives after `label`: its making's or makings' `wall W ms =
/// translation T ms + driver D ms + other O ms`, as `[W, T, D, O]`.
fn split_after(line: &str, label: &str) -> [f64; 4] {
let (_, rest) = line.split_once(label).expect(label);
let numbers: Vec<f64> = (rest.split(' '))
.take(16)
.filter_map(|word| word.parse().ok())
.collect();
numbers[..4].try_into().unwrap()
}
#[test]
fn each_pipeline_state_s_making_is_split_into_the_translator_s_and_the_driver_s_time() {
let dir = ScratchDir::new("rt-replay-makes").unwrap();
let functions = [
("scale_and_offset", 2, 0),
("colored_vertex", 0, 1),
("colored_fragment", 1, 2),
];
let path = written(&dir, |w| {
let library = w.blob(&library(&dir, &functions))?;
w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?;
let library = [Value::Blob(library)];
w.call("newLibraryWithData:error:", 1, 3, &library, &[])?;
for (id, (name, _, _)) in (4..).zip(functions) {
w.call(
"newFunctionWithName:",
3,
id,
&[Value::Str(name.into())],
&[],
)?;
}
// Two states of one kernel: the device holds the second's content.
let made = "newComputePipelineStateWithFunction:error:";
w.call(made, 1, 7, &[Value::Object(4)], &[])?;
w.call(made, 1, 8, &[Value::Object(4)], &[])?;
let pipeline = Value::Map(vec![
("vertex".into(), Value::Object(5)),
("fragment".into(), Value::Object(6)),
("color0PixelFormat".into(), Value::Uint(70)),
]);
let made = "newRenderPipelineStateWithDescriptor:error:";
w.call(made, 1, 9, &[pipeline], &[])
});
let (_, lines) = play("makes", &path);
let summary = (lines.iter())
.find(|line| line.starts_with("pipeline makes "))
.unwrap_or_else(|| panic!("{lines:?}"));
assert!(
summary.starts_with("pipeline makes 3 states: 2 cold, "),
"{summary}"
);
let end = "; 0 beside a pre-pass call, whose work their times count";
assert!(summary.ends_with(end), "{summary}");
let [wall, translation, driver, other] = split_after(summary, " cold, ");
assert!(
translation > 0.0 && driver > 0.0 && other >= 0.0,
"{summary}"
);
assert!(wall >= translation + driver, "{summary}");
let [.., other] = split_after(summary, " held, ");
let (_, held) = summary.split_once(" held, ").unwrap();
assert!(
held.contains(" + driver 0.000 ms + ") && other >= 0.0,
"{summary}"
);
let slowest: Vec<&String> = (lines.iter())
.filter(|line| line.starts_with("pipeline make slowest "))
.collect();
assert_eq!(slowest.len(), 3, "{lines:?}");
for (state, kinds) in [
(7, "kernel cold"),
(8, "kernel held"),
(9, "vertex+fragment cold"),
] {
let named = format!(" #{state} {kinds}: wall ");
assert!(
slowest.iter().any(|line| line.contains(&named)),
"{slowest:?}"
);
}
}
#[test]
fn a_stage_in_region_plays_on_a_compute_encoder() {
let dir = ScratchDir::new("rt-replay-stage-in").unwrap();
+13
View File
@@ -973,6 +973,19 @@ making's wall time, and whether no state of another specialization of the kernel
function by name, was made before), its `commit lock wait longest N ns` (the runtime's
`commit_lock_wait_max_nanos`: the longest wait of a commit for the runtime's work lock in the play;
the executed counter `commit_lock_wait_nanos` gives the waits by frame, summed), its
`pipeline makes N states: C cold, SPLIT; H held, SPLIT; B beside a pre-pass call, whose work their
times count` and, for each of the ten slowest makings, slowest first, `pipeline make slowest K #ID
KINDS cold|held: SPLIT` (where each render and compute pipeline state's making went, read from the
runtime's counters on the player's thread before and after it: `SPLIT` is `wall W ms =
translation T ms + driver D ms + other O ms`, the making's wall time on the runtime's clock,
`host_time`, and of it the translator's calls, `translation_nanos`, the driver's
`vkCreate*Pipelines` calls, `pipeline_creation_nanos`, and the rest; a making is cold where it
lowered a function or made a `VkPipeline`, `translations` or `pipelines_created` rose, and held
where the device held the state's content; the counters sum every thread's calls, so the `B`
makings during which a pre-pass thread ran a call, each marked `, beside a pre-pass call`, count
that call's work too; `ID` the state's object and `KINDS` `kernel`, or `vertex` or
`post-tessellation vertex`, where the library states a `patchType`, then `+fragment` where the
state has a fragment function; states the runtime refused are not among them), its
`skipped render states GAP N, the first #ID: WHY` for each
typed gap a render pipeline state met (`GAP` the runtime's gap as Rust prints it for debugging, such
as `RenderPipeline { kind: DepthAttachment }`, or `Translation(KIND)` where the translator refused