Tests: time a linear sample of a 1080p 4:2:2 frame beside RGBA8Unorm's

The runtime README's 4:2:2 paragraph lost its GPU-time figure when the decode shrank (clamp-to-edge
taps, each footprint row's pairs fetched once): the figure measured the earlier sixteen-fetch decode
with a probe that was never committed. This is that probe as a committed test, so the figure has a
source.

tests::chroma_time's time_a_linear_sample_of_a_1080p_frame, #[ignore]d and run with --run-ignored
only (it prints GPU times and asserts nothing of time, as mesh_costs_print_per_card does):
- xr_samples' xr_sample_runtime (a linear clamp-to-edge sampler state at slot 0) and
  xr_sample_constexpr (its constexpr linear clamp-to-edge sampler) sample each texel's centre of a
  1920 by 1080 frame, one thread a texel, over a GBGR422 texture over a Private buffer at 3,840 bytes
  a row and an RGBA8Unorm one at 7,680, positions and outputs in Private buffers;
- each dispatch is a command buffer of its own, timed by its GPU start and end; a round takes the
  median of nine of each kernel over each texture, the four taking turns; unmeasured rounds run for
  a second first (an NVIDIA card raises its clocks under load), then three rounds print each
  kernel's two medians, their ratio and each texture's form (in place or the copy's cause);
- it asserts the decode ran (chroma_contents +2, chroma_launches = every GBGR422 dispatch, none for
  RGBA8Unorm) and that every value written is finite and within [0, 1] (the outputs start as NaNs).

chroma_pairs' buffer_of, byte and GROUP are now pub(crate) for it.

Verification follows this commit: a run on lavapipe and one on the RTX 3090.
This commit is contained in:
Anees Iqbal committed 2026-12-04 23:49:30 -08:00
1 parent b0c9c9f0c9
commit c08da02d8c
3 files changed
+251 -4

No files matched your search

@@ -30,7 +30,7 @@
//! test skips visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
pub(crate) mod on_device {
use crate::tests::command::on_device::{each_device, finished};
use crate::texture::TextureObject;
use crate::{
@@ -48,7 +48,7 @@ mod on_device {
];
/// The threads of a threadgroup of every dispatch.
const GROUP: u32 = 64;
pub(crate) const GROUP: u32 = 64;
/// The fixture's library, or None where `llvm-as` is missing.
fn library() -> Option<Library> {
@@ -74,7 +74,7 @@ mod on_device {
}
/// Byte `k` of a texture's rows, counted along the rows without their padding: a hash of `k`.
fn byte(k: u32) -> u8 {
pub(crate) fn byte(k: u32) -> u8 {
let mut h = k.wrapping_mul(2_654_435_761).wrapping_add(0x9e37_79b9);
h ^= h >> 15;
h = h.wrapping_mul(0x85eb_ca6b);
@@ -122,7 +122,12 @@ mod on_device {
/// A buffer of `class` holding `bytes` at its start, in a block of its own: a Private one
/// written by a blit from a Shared one.
fn buffer_of(name: &str, device: &Device, class: MemoryClass, bytes: &[u8]) -> Buffer {
pub(crate) fn buffer_of(
name: &str,
device: &Device,
class: MemoryClass,
bytes: &[u8],
) -> Buffer {
let len = bytes.len() as u64;
let shared = |len: u64| {
let block = (device.take_block(MemoryClass::Shared, len))
@@ -0,0 +1,241 @@
//! The GPU time of a linear sample of a 4:2:2 texture beside the same sample of an `RGBA8Unorm`
//! texture of its size, under a device cfg on every device of the cfg's kind, printed and asserting
//! nothing of time. The owned fixture `xr_samples`' `xr_sample_runtime` (through the runtime sampler
//! at sampler slot 0, a linear clamp-to-edge sampler state) and `xr_sample_constexpr` (through its
//! constexpr linear clamp-to-edge sampler) each take one sample at the centre of each texel of a
//! 1920 by 1080 frame, one thread a texel, and write it out, over a `GBGR422` texture made over a
//! Private buffer at 3,840 bytes a row (a 'yuvs' surface's pitch for that width) and over an
//! `RGBA8Unorm` texture made over a Private buffer at 7,680, each in the form
//! `Buffer::new_texture` makes it, which the lines name. The positions and the output are Private
//! buffers too.
//!
//! Each dispatch is a command buffer of its own, timed by its GPU start and end
//! (`CommandBuffer::gpu_start_time`, `CommandBuffer::gpu_end_time`). A round runs nine of each
//! kernel over each texture, the four taking turns, and takes each one's median. Unmeasured rounds
//! run first until a second has passed, so a GPU whose clocks rise under load has raised them;
//! then three rounds print each kernel's two medians and their ratio. The chroma counters show the
//! decode ran: each kernel's state makes one content lowered for its 4:2:2 slot, and each of its
//! dispatches over the `GBGR422` texture runs it (`Metrics::chroma_contents`,
//! `Metrics::chroma_launches`); no dispatch over the `RGBA8Unorm` texture does. Every value written
//! is finite and within [0, 1].
//!
//! Run it on one device with `--run-ignored only`. `llvm-as` assembles the kernels; without it the
//! test skips visibly.
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod on_device {
use crate::tests::chroma_pairs::on_device::{buffer_of, byte, GROUP};
use crate::tests::command::on_device::{each_device, finished};
use crate::tests::draw::on_device::library;
use crate::texture::TextureObject;
use crate::{
Buffer, ComputePipelineDescriptor, ComputePipelineState, DispatchType, FunctionDescriptor,
IndexClass, MemoryClass, PixelFormat, SamplerDescriptor, SamplerMinMagFilter, StageSource,
Texture, TextureDescriptor, TextureType, TextureUsage,
};
use metal2vulkan_devtools::engine_dir;
use std::time::{Duration, Instant};
/// The frame's width and height.
const WIDTH: u32 = 1920;
const HEIGHT: u32 = 1080;
/// The dispatches of each kernel over each texture in a round.
const RUNS: usize = 9;
/// The rounds printed.
const ROUNDS: usize = 3;
/// How long the unmeasured rounds run: at least one round.
const WARM: Duration = Duration::from_secs(1);
/// The kernels, each with the sampler it samples through.
const KERNELS: [(&str, &str); 2] = [
("a runtime sampler", "xr_sample_runtime"),
("a constexpr sampler", "xr_sample_constexpr"),
];
/// The textures' formats, each with its bytes a texel.
const FORMATS: [(PixelFormat, u64); 2] =
[(PixelFormat::GBGR422, 2), (PixelFormat::RGBA8Unorm, 4)];
/// The sampler state's index, and the constexpr sampler's.
const SAMPLER: u32 = 1;
const CONSTEXPR: u32 = 2;
#[test]
#[ignore = "prints GPU times; run it on one device with --run-ignored only"]
fn time_a_linear_sample_of_a_1080p_frame() {
let Some(library) = library(&engine_dir().join("xr_samples.ll")) else {
return;
};
let n = WIDTH * HEIGHT;
let positions: Vec<u8> = (0..HEIGHT)
.flat_map(|y| (0..WIDTH).map(move |x| (x, y)))
.flat_map(|(x, y)| {
[
(x as f32 + 0.5) / WIDTH as f32,
(y as f32 + 0.5) / HEIGHT as f32,
]
})
.flat_map(f32::to_le_bytes)
.collect();
// Each output starts as NaNs, so a dispatch that wrote nothing fails the check.
let unwritten = vec![0xff; 16 * n as usize];
each_device("4:2:2 linear sample time", |name, _, device| {
let _grants =
[(IndexClass::Texture, 1), (IndexClass::Sampler, SAMPLER)].map(|(class, first)| {
(device.grant_indices(class, first, 2))
.unwrap_or_else(|error| panic!("{name}: {error}"))
});
let mut d = SamplerDescriptor::new();
d.min_filter = SamplerMinMagFilter::Linear;
d.mag_filter = SamplerMinMagFilter::Linear;
let sampler = (device.new_sampler_state(&d, SAMPLER))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let states: Vec<ComputePipelineState> = (KERNELS.iter())
.map(|&(_, kernel)| {
let function = library.function(kernel).expect("the kernel");
let descriptor = ComputePipelineDescriptor::new(StageSource::Function(
FunctionDescriptor::new(function),
));
(device.new_compute_pipeline_state(&descriptor, |samplers| {
Ok(vec![CONSTEXPR; samplers.len()])
}))
.unwrap_or_else(|error| panic!("{name}: {kernel}: {error}"))
})
.collect();
let textures: Vec<(Texture, Buffer, String)> = (FORMATS.iter().zip(1..))
.map(|(&(format, texel), index)| {
let pitch = texel * u64::from(WIDTH);
let bytes: Vec<u8> = (0..pitch * u64::from(HEIGHT))
.map(|k| byte(k as u32))
.collect();
let buffer = buffer_of(name, &device, MemoryClass::Private, &bytes);
let mut d = TextureDescriptor::new(TextureType::Type2D, format, WIDTH, HEIGHT);
d.usage = TextureUsage::SHADER_READ;
let texture = (buffer.new_texture(&d, Some(index), 0, pitch))
.unwrap_or_else(|error| panic!("{name}: {format:?}: {error}"));
let form = match texture.copied_over() {
None => "in place".to_owned(),
Some((_, copy)) => format!("copied for {:?}", copy.kind.cause),
};
(texture, buffer, form)
})
.collect();
let uv = buffer_of(name, &device, MemoryClass::Private, &positions);
let outs: Vec<Vec<Buffer>> = (KERNELS.iter())
.map(|_| {
(FORMATS.iter())
.map(|_| buffer_of(name, &device, MemoryClass::Private, &unwritten))
.collect()
})
.collect();
let queue = device.new_command_queue(1).expect("a queue");
// One dispatch of `state` over `texture` into `out`, in a command buffer of its own:
// its GPU time in nanoseconds.
let time = |state: &ComputePipelineState, texture: &Texture, out: &Buffer| -> u64 {
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("the state");
encoder.set_texture(Some(texture), 0).expect("the texture");
(encoder.set_sampler_state(Some(&sampler), 0)).expect("the sampler");
encoder.set_buffer(Some(&uv), 0, 0).expect("the positions");
encoder.set_buffer(Some(out), 0, 1).expect("the output");
(encoder.dispatch_threads([n, 1, 1], [GROUP, 1, 1])).expect("the dispatch");
encoder.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}");
(command_buffer.gpu_end_time()).saturating_sub(command_buffer.gpu_start_time())
};
// Each kernel's median over each texture, the four taking turns.
let round = || -> Vec<Vec<u64>> {
let mut times = vec![vec![Vec::with_capacity(RUNS); FORMATS.len()]; KERNELS.len()];
for _ in 0..RUNS {
for ((state, outs), times) in states.iter().zip(&outs).zip(&mut times) {
for (((texture, ..), out), times) in
textures.iter().zip(outs).zip(times.iter_mut())
{
times.push(time(state, texture, out));
}
}
}
(times.into_iter())
.map(|kernel| {
(kernel.into_iter())
.map(|mut runs| {
runs.sort_unstable();
runs[RUNS / 2]
})
.collect()
})
.collect()
};
let before = device.counters().metrics();
let warming = Instant::now();
let mut warm = 0;
while warm == 0 || warming.elapsed() < WARM {
round();
warm += 1;
}
println!(
"{name}: {warm} unmeasured rounds in {} ms",
warming.elapsed().as_millis()
);
for r in 0..ROUNDS {
for ((sampler, _), medians) in KERNELS.iter().zip(round()) {
let [(chroma, chroma_form), (plain, plain_form)] =
[0, 1].map(|f| (medians[f], &textures[f].2));
println!(
"{name}: round {r}: {sampler}: {:?} {chroma_form}: {chroma} ns; {:?} \
{plain_form}: {plain} ns; ratio {:.3}",
FORMATS[0].0,
FORMATS[1].0,
chroma as f64 / plain.max(1) as f64
);
}
}
let after = device.counters().metrics();
let contents = after.chroma_contents - before.chroma_contents;
let launches = after.chroma_launches - before.chroma_launches;
println!(
"{name}: chroma_contents +{contents}, chroma_launches +{launches}, \
translation_at_encode_max_nanos {}",
after.translation_at_encode_max_nanos
);
assert_eq!(
contents,
KERNELS.len() as u64,
"{name}: the contents lowered for the 4:2:2 texture"
);
let decoded = ((warm + ROUNDS) * RUNS * KERNELS.len()) as u64;
assert_eq!(launches, decoded, "{name}: the dispatches that ran them");
// Every value each kernel wrote over each texture.
let len = 16 * u64::from(n);
let block = (device.take_block(MemoryClass::Shared, len))
.unwrap_or_else(|error| panic!("{name}: {error}"));
let staged = (device.new_buffer(block.id, 0, len, None))
.unwrap_or_else(|error| panic!("{name}: {error}"));
for ((_, kernel), outs) in KERNELS.iter().zip(&outs) {
for ((format, _), out) in FORMATS.iter().zip(outs) {
let command_buffer = queue.command_buffer().expect("a command buffer");
let mut blit = command_buffer.blit_command_encoder().expect("an encoder");
(blit.copy_from_buffer_to_buffer(out, 0, &staged, 0, len))
.unwrap_or_else(|error| panic!("{name}: the read: {error}"));
blit.end_encoding();
command_buffer.commit().expect("a commit");
finished(name, &command_buffer);
assert_eq!(command_buffer.error(), None, "{name}: the read");
let contents = staged.contents().expect("a Shared buffer");
// SAFETY: the copy that wrote the buffer finished, and its writes reach the
// host; the buffer holds `4 n` floats.
let floats = unsafe {
std::slice::from_raw_parts(contents.as_ptr().cast::<f32>(), 4 * n as usize)
};
let wrong = (floats.iter()).position(|v| !(0.0..=1.0).contains(v));
assert_eq!(wrong, None, "{name}: {kernel} over {format:?}: a value");
}
}
});
}
}
@@ -19,6 +19,7 @@ mod cache;
mod choice;
mod chroma_makes;
mod chroma_pairs;
mod chroma_time;
mod coherence;
mod coherent_texels;
pub(crate) mod command;