harness: constant_managed and constant_private, a Managed table the CPU modifies before each run

The old runtime's 64 KiB constant reads from a Managed buffer ran at 1.53x Private on the 3090 and
1.15x on the XTX once it moved Managed to a VRAM copy (4b4484576), and at 6.6x and 1.91x before.
No harness row measured it, so nothing held the new runtime to that figure.

- A plan's BufferPlan gains `modified`: a range the CPU writes again before each run, with the
  buffer's starting bytes there (zero where it has none), and marks with didModifyRange: where
  Managed, inside the timed runs. The bytes are those the range holds, so a run in flight reads
  the same values and every run's result is the first's. Plan::validate refuses it on a Private
  buffer and outside the buffer (BufferPlan::modify_problem). A session that gives such a buffer
  no CPU copy refuses the plan with a typed refusal: the new runtime's session, whose Managed
  buffer is a Private one until the new runtime has Managed storage.
- The authored fixture gains constant_reads: each of 2^20 threads folds 64 of a 64 KiB constant
  table's 4,096 entries into a word. Regenerated by scripts/regen-air-fixtures (--dir harness
  workloads) on the M3 with the recorded toolchain (job 43163).
- Two authored workloads over it, each with its CPU reference: constant_managed, its table
  Managed with the first 256 bytes modified before each run, and constant_private, the same table
  Private and never modified, its reference. On the new runtime constant_managed prints REFUSED
  and the budget does not compare it until the new runtime's session maps Managed to the
  runtime's own Managed buffers.
- A description's buffer takes managed storage, and `modify BUFFER OFFSET LENGTH` sets a buffer's
  modified range; a private buffer, a buffer not yet made and a range past the buffer are
  refused with their line.

Verified (check 43181, msi): clippy plain, --cfg m2v_gpu and --cfg m2v_cpu_icd; Rustdoc with and
without private items; the harness's tests, 22 of 22, among them every authored plan validating
(the two new ones with their CPU references), the description's managed buffer and modify range
parsed, and modify on a private buffer, an unmade buffer and past a buffer refused with their
line; its lavapipe device tests, 26 of 26, among them every authored workload on both runtimes,
each matching its CPU reference or refused with a typed refusal (the test prints which; its
output was not kept); and the translator's engine_identity tests over the regenerated fixture.
This commit is contained in:
Anees Iqbal committed 2026-11-17 16:47:13 -08:00
1 parent 319af230ca
commit fdfe70b997
10 files changed
+1004 -697

No files matched your search

+81 -1
View File
@@ -7,6 +7,7 @@ use crate::plan::{
SamplerPlan, Scaled, Source, TextureExpect, TexturePlan, Values,
};
use crate::{Result, Storage};
use std::ops::Range;
/// An authored workload: its name, and the builder of its plan. A plan holds its inputs and
/// expected results (up to 128 MiB), so each is built when it runs.
@@ -19,7 +20,7 @@ pub struct Workload {
}
/// The authored workloads.
pub const WORKLOADS: [Workload; 20] = [
pub const WORKLOADS: [Workload; 22] = [
Workload {
name: "bandwidth",
plan: bandwidth,
@@ -100,6 +101,14 @@ pub const WORKLOADS: [Workload; 20] = [
name: "vote_loop",
plan: vote_loop,
},
Workload {
name: "constant_managed",
plan: constant_managed,
},
Workload {
name: "constant_private",
plan: constant_private,
},
];
/// A creation workload: `Shared` buffers of one length made and released in turn, so that each
@@ -307,6 +316,7 @@ fn simd_reduce() -> Plan {
length: 16,
storage: Storage::Shared,
contents: Some(vec![0; 16]),
modified: None,
},
],
dispatches: vec![
@@ -469,6 +479,7 @@ fn private(contents: Vec<u8>) -> BufferPlan {
length: contents.len() as u64,
storage: Storage::Private,
contents: Some(contents),
modified: None,
}
}
@@ -478,6 +489,7 @@ fn unset(length: u64) -> BufferPlan {
length,
storage: Storage::Private,
contents: None,
modified: None,
}
}
@@ -564,6 +576,7 @@ fn lcg_frame(
length: 16,
storage,
contents: Some(word_bytes(&[increment, 0, 0, 0])),
modified: None,
},
],
dispatches: vec![dispatch; steps],
@@ -716,6 +729,73 @@ fn vote_loop() -> Plan {
}
}
/// Reads of a 64 KiB table as constants (`constant_reads`): 2^20 threads in threadgroups of 256,
/// each folding 64 of the table's 4,096 entries into a word, the table `Managed`, and the first
/// 256 bytes of it written again by the CPU before each run and marked with `didModifyRange:`, as
/// a program updates a constant buffer a little before each frame. On a GPU with memory of its
/// own, each run reads the table after its update reached the GPU's copy.
fn constant_managed() -> Plan {
constant_reads("constant_managed", Storage::Managed, Some(0..256))
}
/// [`constant_managed`]'s reads from a `Private` table that nothing writes after its first run:
/// the reference its time is read against.
fn constant_private() -> Plan {
constant_reads("constant_private", Storage::Private, None)
}
/// The constant reads of [`constant_managed`] from a table of `storage`, `modified` before each
/// run.
fn constant_reads(name: &str, storage: Storage, modified: Option<Range<u64>>) -> Plan {
const THREADS: u32 = 1 << 20;
const ENTRIES: u32 = 4096;
const GROUP: u32 = 256;
let table = words(16, 4 * ENTRIES as usize);
let folded: Vec<u32> = (0..THREADS)
.map(|index| {
(0..64).fold(index, |folded, i| {
let at = 4 * ((index + i * 67) & (ENTRIES - 1)) as usize;
let entry = &table[at..at + 4];
(folded ^ entry[0] ^ entry[1]).wrapping_add(entry[2] ^ entry[3])
})
})
.collect();
Plan {
name: name.to_owned(),
library: Source::Authored,
buffers: vec![
BufferPlan {
length: 16 * u64::from(ENTRIES),
storage,
contents: Some(word_bytes(&table)),
modified,
},
unset(4 * u64::from(THREADS)),
],
dispatches: vec![Dispatch {
function: "constant_reads".to_owned(),
linked: Vec::new(),
constants: Vec::new(),
bindings: vec![buffer(0, 0), buffer(1, 1)],
grid: Grid::Threadgroups {
groups: [u64::from(THREADS / GROUP), 1, 1],
threads: [u64::from(GROUP), 1, 1],
},
}],
expect: vec![Expect {
buffer: 1,
values: Values::Words(folded),
}],
textures: Vec::new(),
expect_textures: Vec::new(),
outputs: Vec::new(),
per_command_buffer: None,
per_encoder: None,
commit_to_complete: false,
scaled: None,
}
}
/// Narrow integers: 2^19 threads, each 512 steps of 8- and 16-bit arithmetic (`narrow_mix`), every
/// value held in a 32-bit container whose bits above its width the translation clears after each
/// step that can set them. The reference runs each thread's steps in Rust's wrapping arithmetic.
+49 -13
View File
@@ -7,7 +7,12 @@
//!
//! ```text
//! workload NAME METALLIB the metallib, a file in the directory
//! buffer LENGTH shared|private FILL the next buffer, numbered from 0
//! buffer LENGTH STORAGE FILL the next buffer, numbered from 0, its storage shared,
//! managed or private
//! modify BUFFER OFFSET LENGTH before each run, the CPU writes LENGTH bytes of BUFFER
//! at OFFSET again, its starting bytes there, and marks
//! them with didModifyRange: where managed; a shared or
//! managed BUFFER alone
//! set-buffer INDEX BUFFER [OFFSET] setBuffer:offset:atIndex: before the next dispatch
//! set-bytes INDEX LENGTH FILL setBytes:length:atIndex: before the next dispatch
//! threadgroup-length INDEX LENGTH setThreadgroupMemoryLength:atIndex: before the next
@@ -60,6 +65,7 @@ use crate::plan::{
};
use crate::{Result, Size, Storage};
use metal2vulkan::metal::{PixelFormat, SamplerAddressMode, TextureType, TextureUsage};
use std::ops::Range;
use std::path::{Path, PathBuf};
/// A workload a description names: its lines, made into its plan when it runs, since a plan
@@ -129,25 +135,41 @@ impl Described {
};
let mut lines = self.lines.iter().map(|(number, words)| {
let words: Vec<&str> = words.iter().map(String::as_str).collect();
line(&words).map_err(|why| format!("line {number}: {why}"))
(line(&words).map(|line| (*number, line)))
.map_err(|why| format!("line {number}: {why}"))
});
// A dispatch at a time: the lines up to it, its bindings and constants among them.
loop {
let (mut bindings, mut constants, mut linked) = (Vec::new(), Vec::new(), Vec::new());
let dispatch = loop {
match lines.next().transpose()? {
None => break None,
Some(Line::Buffer(buffer)) => plan.buffers.push(buffer),
Some(Line::Texture(texture)) => plan.textures.push(texture),
Some(Line::Binding(binding)) => bindings.push(binding),
Some(Line::Constant(constant)) => constants.push(constant),
Some(Line::Linked(functions)) => linked.extend(functions),
Some(Line::Output(output)) => plan.outputs.push(output),
Some(Line::Dispatch {
let Some((number, line)) = lines.next().transpose()? else {
break None;
};
match line {
Line::Buffer(buffer) => plan.buffers.push(buffer),
Line::Modify { buffer, range } => {
let Some(made) = plan.buffers.get_mut(buffer) else {
return Err(format!(
"line {number}: modify names buffer {buffer}, which no line \
before it makes"
)
.into());
};
made.modified = Some(range);
if let Some(problem) = made.modify_problem() {
return Err(format!("line {number}: buffer {buffer}: {problem}").into());
}
}
Line::Texture(texture) => plan.textures.push(texture),
Line::Binding(binding) => bindings.push(binding),
Line::Constant(constant) => constants.push(constant),
Line::Linked(functions) => linked.extend(functions),
Line::Output(output) => plan.outputs.push(output),
Line::Dispatch {
function,
grid,
repeat,
}) => break Some((function, grid, repeat)),
} => break Some((function, grid, repeat)),
}
};
let Some((function, grid, repeat)) = dispatch else {
@@ -192,6 +214,10 @@ impl Described {
/// What a line inside a workload adds to it.
enum Line {
Buffer(BufferPlan),
Modify {
buffer: usize,
range: Range<u64>,
},
Texture(TexturePlan),
Binding(Binding),
Constant(Constant),
@@ -211,18 +237,28 @@ fn line(words: &[&str]) -> std::result::Result<Line, String> {
let length = number(length)?;
let storage = match *storage {
"shared" => Storage::Shared,
"managed" => Storage::Managed,
"private" => Storage::Private,
other => return Err(format!("storage {other} is neither shared nor private")),
other => return Err(format!("storage {other} is not shared, managed or private")),
};
Line::Buffer(BufferPlan {
length,
storage,
modified: None,
contents: match fill {
["zero"] => None,
fill => Some(filled(length, fill)?),
},
})
}
["modify", buffer, offset, length] => {
let (offset, length): (u64, u64) = (number(offset)?, number(length)?);
Line::Modify {
buffer: number(buffer)?,
range: offset..offset.checked_add(length).ok_or("the range does not fit")?,
}
}
["modify", ..] => return Err("modify takes BUFFER OFFSET LENGTH".to_owned()),
["set-buffer", index, buffer, offset @ ..] => {
let offset = match offset {
[] => 0,
+3
View File
@@ -13,6 +13,9 @@
//! run, and the buffers runtimes compare. Most workloads put a run in one command buffer; `frame`
//! and `frame_5cb` are frames of one and of five command buffers of four small dispatches each,
//! the `burst_` workloads bursts of 160 and 2,000, and `long_4cb` four long command buffers.
//! `constant_managed` reads a `Managed` table of constants whose first 256 bytes the CPU writes
//! again before each run (`plan::BufferPlan::modified`), and `constant_private` the same reads
//! from a `Private` table, its reference.
//! A [`run::Session`] makes its objects, checks the first run, then times the rest. The authored
//! workloads ([`authored`]) are MSL kernels committed as public fixtures
//! (`crates/metal2vulkan-validation/fixtures/public/harness/workloads.metal`, compiled by
+25
View File
@@ -8,6 +8,7 @@ use metal2vulkan::metal::{
DataType, PixelFormat, SamplerAddressMode, SamplerMinMagFilter, TextureType, TextureUsage,
};
use metal2vulkan::pipeline::{FunctionDescriptor, LinkedFunction, LinkedFunctions};
use std::ops::Range;
use std::path::PathBuf;
/// One workload.
@@ -106,6 +107,27 @@ pub struct BufferPlan {
/// `contents`, for `Private` copied in from a `Shared` buffer by the harness's own kernel.
/// `None`: as `newBufferWithLength:` made it.
pub contents: Option<Vec<u8>>,
/// The range the CPU writes again before each run, with the buffer's starting bytes there
/// (zero where it has none), and marks with `didModifyRange:` where `Managed`: a program's
/// update of a buffer before each frame. A `Shared` or `Managed` buffer's alone.
pub modified: Option<Range<u64>>,
}
impl BufferPlan {
/// What is wrong with its modified range, if anything.
pub fn modify_problem(&self) -> Option<String> {
let range = self.modified.as_ref()?;
if self.storage == Storage::Private {
return Some("the CPU writes no private buffer".to_owned());
}
if range.is_empty() || range.end > self.length {
return Some(format!(
"its modified range {range:?} is not within its {} bytes",
self.length
));
}
None
}
}
/// `function` with `private` linked as its private functions
@@ -591,6 +613,9 @@ impl Plan {
)
.into());
}
if let Some(problem) = buffer.modify_problem() {
return Err(format!("{name}: buffer {i}: {problem}").into());
}
if let Some(contents) = &buffer.contents {
if contents.len() as u64 != buffer.length {
return Err(format!(
+2 -1
View File
@@ -12,7 +12,8 @@
//! The new runtime has no `Managed` storage, so a `Managed` buffer is a `Private` one here: the
//! GPU's copy in device memory, which the harness writes as it writes a `Private` buffer, through
//! a `Shared` buffer and its copy kernel, as `didModifyRange:` brings a `Managed` buffer's GPU copy
//! up to date on a Mac with a discrete GPU. It has no CPU copy: its `contents` is `None`.
//! up to date on a Mac with a discrete GPU. It has no CPU copy: its `contents` is `None`, and a
//! plan whose CPU writes such a buffer before each run (`BufferPlan::modified`) is refused.
//!
//! Its known gaps and the device's limits (`Error::Unsupported`, `Error::Limit`) are typed
//! refusals ([`Refused`]); its other errors are failures.
+37
View File
@@ -491,6 +491,11 @@ impl<D: ComputeDevice> Harness<D> {
made: &Made<D>,
completions: Option<&Arc<Completions>>,
) -> Result<Vec<D::CommandBuffer>> {
for (buffer, object) in plan.buffers.iter().zip(&made.buffers) {
if let Some(range) = &buffer.modified {
modify(object, buffer, range)?;
}
}
parts(0..plan.dispatches.len(), plan.per_command_buffer)
.enumerate()
.map(|(place, range)| {
@@ -721,6 +726,15 @@ impl<D: ComputeDevice> Session for Harness<D> {
self.texels = Some(self.make_texels()?);
}
self.fill(&plan.buffers, &made.buffers)?;
for (i, (buffer, object)) in plan.buffers.iter().zip(&made.buffers).enumerate() {
if buffer.modified.is_some() && object.contents().is_none() {
return Err(Box::new(Refused(format!(
"{}: buffer {i}, which the CPU writes before each run, is {:?}, and this \
runtime gives it no CPU copy",
plan.name, buffer.storage
))));
}
}
self.fill_textures(&plan.textures, &made.textures)?;
wait_run::<D>(&self.commit_run(plan, &made, None)?)?;
for expect in &plan.expect {
@@ -938,6 +952,29 @@ fn write(buffer: &impl Buffer, bytes: &[u8]) -> Result<()> {
Ok(())
}
/// The CPU's write of `range` of `buffer` before a run: `plan`'s starting bytes there, or zero
/// where it has none, marked with `didModifyRange:` where `Managed`. The bytes are those the range
/// already holds, so a run still in flight reads the same values.
fn modify(buffer: &impl Buffer, plan: &BufferPlan, range: &Range<u64>) -> Result<()> {
let contents = buffer
.contents()
.ok_or("a modified buffer has no contents")?;
let (at, length) = (range.start as usize, (range.end - range.start) as usize);
// SAFETY: `contents` holds the buffer's `plan.length` bytes, `range` is within them
// (`Plan::validate`), and so it is within the starting bytes.
unsafe {
let to = contents.as_ptr().add(at);
match &plan.contents {
Some(bytes) => std::ptr::copy_nonoverlapping(bytes[at..].as_ptr(), to, length),
None => std::ptr::write_bytes(to, 0, length),
}
}
if plan.storage == Storage::Managed {
buffer.did_modify_range(range.start, range.end - range.start)?;
}
Ok(())
}
/// A copy of the first `length` bytes of the `Shared` buffer `buffer`, which no GPU work writes
/// now.
fn bytes(buffer: &impl Buffer, length: u64) -> Result<Vec<u8>> {
+29 -2
View File
@@ -89,6 +89,7 @@ fn one_buffer_plan(length: u64, contents: Option<Vec<u8>>, bound: usize) -> Plan
length,
storage: Storage::Private,
contents,
modified: None,
}],
dispatches: vec![Dispatch {
function: "copy_words".to_owned(),
@@ -313,6 +314,8 @@ check 1 float 0.5
workload second other.metallib
buffer 16 private zero
buffer 64 managed words 3
modify 1 16 32
texture 2 70 4 2 1 1 shared plain words 5
texture 3 20 2 2 3 3 managed heap zero
texture 2 115 16 16 1 0 private over-buffer undefined
@@ -408,6 +411,14 @@ fn a_description_makes_its_plans() {
));
assert_eq!(second.dispatches[0].linked, ["f", "g"]);
assert!(first.dispatches.iter().all(|d| d.linked.is_empty()));
assert_eq!(
(
second.buffers[1].storage,
second.buffers[1].modified.clone()
),
(Storage::Managed, Some(16..48))
);
assert!(first.buffers.iter().all(|b| b.modified.is_none()));
let [words, array, undefined] = second.textures.as_slice() else {
panic!("three textures, not {}", second.textures.len());
};
@@ -513,8 +524,24 @@ fn a_faulty_description_is_refused_naming_its_line() {
"line 1: workload takes NAME METALLIB"
);
assert_eq!(
refusal("buffer 16 managed zero"),
"line 3: storage managed is neither shared nor private"
refusal("buffer 16 memoryless zero"),
"line 3: storage memoryless is not shared, managed or private"
);
assert_eq!(
refusal("modify 0 0 16"),
"line 3: buffer 0: the CPU writes no private buffer"
);
assert_eq!(
refusal("modify 1 0 16"),
"line 3: modify names buffer 1, which no line before it makes"
);
assert_eq!(
refusal("buffer 32 managed zero\nmodify 1 16 32"),
"line 4: buffer 1: its modified range 16..48 is not within its 32 bytes"
);
assert_eq!(
refusal("modify 0 0"),
"line 3: modify takes BUFFER OFFSET LENGTH"
);
assert_eq!(
refusal("buffer 16 shared hex 00ff"),
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -2,8 +2,8 @@
// standing for a class of compute work: bandwidth-bound, ALU-bound, threadgroup memory with
// barriers, SIMD reductions, 2D image-like indexing, many tiny dispatches in a chain, narrow
// integer arithmetic, sampling through a runtime sampler and through a constexpr one, products
// by a constant zero of either sign, many buffers bound for each of many dispatches, and many
// one-wave threadgroups that each do almost nothing. Written
// by a constant zero of either sign, many buffers bound for each of many dispatches, many
// one-wave threadgroups that each do almost nothing, and reads of a table of constants. Written
// from scratch for it; `scripts/regen-air-fixtures/regen-air-fixtures.sh --dir harness` compiles
// it. The harness holds a CPU reference of every result. No translator sweep reads this directory.
#include <metal_stdlib>
@@ -302,3 +302,17 @@ kernel void group_sums(device const uint *source [[buffer(0)]],
sums[group] = scratch[0];
}
}
// Reads of a 64 KiB table in the constant address space, as a program reads a constant buffer it
// updates a little before each frame: each thread folds 64 of the table's 4,096 entries into one
// word, the threads of a threadgroup reading consecutive entries.
kernel void constant_reads(constant uint4 *table [[buffer(0)]],
device uint *destination [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint folded = index;
for (uint i = 0; i < 64; ++i) {
uint4 entry = table[(index + i * 67) & 4095];
folded = (folded ^ entry.x ^ entry.y) + (entry.z ^ entry.w);
}
destination[index] = folded;
}