metal: explicit threadgroup widths, measured against the default (#138)

Expose a bounded way to dispatch at a chosen width so every legal
configuration can be checked for identical known answers, including grids
that do not divide evenly, and timed against the default policy. On an
Apple M5 Pro widths 64-256 tie (median 58.8 us GPU), 512 is 6% slower and
1024 about 2x, so the default of 64 stays. run() keeps its signature; the
sized path is a separate private helper.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
This commit is contained in:
elforeign committed 2026-11-24 02:31:33 -06:00
1 parent 0e7fa4aa93
commit ee8347a39f
3 files changed
+282 -14

No files matched your search

+1
View File
@@ -11,6 +11,7 @@ remains unsupported.
### Added
- Added `NativeCompute::run_words_with_group_width` and `max_group_width` to run a trusted kernel at an explicit threadgroup width, rejecting zero and widths above the device or pipeline limit. Native tests check 91 legal width and grid-size pairs (widths 1 to 1,024, including non-divisible grids) against independently computed outputs, and confirm the dispatched group sizes, including trimmed last groups. On an Apple M5 Pro, a 4,096-thread integer-mixing kernel took a median of 58.8 µs of GPU time at widths 64, 128 and 256, 62 µs at 512 and 119 µs at 1,024. The default width of 64 is therefore unchanged. This was measured on one device only.
- Added the gfx1030 SOP2 forms `s_add_i32` and `s_sub_i32`, with SCC as signed overflow as defined in the AMD RDNA 2 ISA guide (sections 5.3 and 12.1). They are checked on CPU and on native Metal with validation on 400 boundary programs, four immediate-operand overflows and the scalar ALU fixture, plus eight hand-worked overflow and no-overflow cases on CPU.
- Added the gfx1030 SOP2 scalar forms `s_add_u32`, `s_sub_u32`, `s_addc_u32`, `s_subb_u32`, `s_and_b32`, `s_or_b32` and `s_xor_b32`. They are decoded, executed by the reference and independent interpreters, and resolved by the translator, with SCC as carry, borrow or nonzero result. `v_mov_b32_e32` can now read a normal SGPR. Verified on 1,400 original operand vectors plus an LLVM-assembled fixture, on CPU and on native Metal with validation. The other SOP2 forms stay unsupported. See `docs/shaders/scalar-alu.md`.
- Added `scripts/audit/test_inventory.py`, which lists the Cargo test inventory of two commits in temporary detached worktrees and reports removed, added, newly ignored and newly un-ignored tests, failing on any loss not explained in an `--allow` file. Run against the old PR #166 head 5450612 and main 951189c, it reports the 12 BC texture tests that head was missing (exit 1); the same commit against itself reports no change. Default features only; see `docs/testing/test-inventory.md`.
+99 -14
View File
@@ -551,6 +551,56 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
source: &str,
entry: &str,
input: &[u32],
) -> Result<RunProfile, MetalError> {
self.run_profiled_words(source, entry, input, None)
}
/// Run trusted MSL with an explicit one-dimensional threadgroup width.
///
/// The grid still contains one invocation per input word. The requested width
/// is passed to Metal even when the grid is smaller or ends in a partial group.
/// The trusted-kernel requirements of [`Self::run_words`] apply.
///
/// # Errors
///
/// Returns the same errors as [`Self::run_words_profiled`], with dispatch
/// bounds evaluated using this width. Zero and widths above the device or
/// pipeline limit are rejected.
pub fn run_words_with_group_width(
&self,
source: &str,
entry: &str,
input: &[u32],
width: usize,
) -> Result<RunProfile, MetalError> {
self.run_profiled_words(source, entry, input, Some(width))
}
/// Compile the kernel and report the smaller of the device and pipeline width limits.
///
/// Input size and threadgroup count are checked separately at dispatch.
///
/// # Errors
///
/// Returns an error if source validation, compilation or pipeline setup fails.
pub fn max_group_width(&self, source: &str, entry: &str) -> Result<usize, MetalError> {
validate_source(source, &[entry])?;
autoreleasepool(|_| {
let options = compile_options()?;
let library = self.compile_library(source, &options)?;
let function = find_function(&library, entry)?;
let pipeline = self.compute_pipeline(&function)?;
verify_shader_validation(&pipeline)?;
Ok(self.pipeline_group_width_limit(&pipeline))
})
}
fn run_profiled_words(
&self,
source: &str,
entry: &str,
input: &[u32],
group_width: Option<usize>,
) -> Result<RunProfile, MetalError> {
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
return Err(MetalError::new(
@@ -559,7 +609,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
));
}
validate_source(source, &[entry])?;
autoreleasepool(|_| self.run(source, entry, ComputeInput::Words(input)))
autoreleasepool(|_| self.run_sized(source, entry, ComputeInput::Words(input), group_width))
}
fn run(
@@ -567,6 +617,18 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
source: &str,
entry: &str,
input: ComputeInput<'_>,
) -> Result<RunProfile, MetalError> {
self.run_sized(source, entry, input, None)
}
/// [`Self::run`] with an optional explicit threadgroup width; `None` keeps
/// the default sizing.
fn run_sized(
&self,
source: &str,
entry: &str,
input: ComputeInput<'_>,
group_width: Option<usize>,
) -> Result<RunProfile, MetalError> {
let host_start = Instant::now();
let options = compile_options()?;
@@ -575,22 +637,21 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let library_seconds = library_start.elapsed().as_secs_f64();
let function = find_function(&library, entry)?;
let pipeline_start = Instant::now();
let pipeline = self
.device
.newComputePipelineStateWithFunction_error(&function)
.map_err(|error| {
MetalError::new(
"newComputePipelineStateWithFunction",
error.localizedDescription().to_string(),
)
})?;
let pipeline = self.compute_pipeline(&function)?;
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
verify_shader_validation(&pipeline)?;
let width = MAX_THREADS_PER_GROUP
.min(input.len())
.min(self.device.maxThreadsPerThreadgroup().width)
.min(pipeline.maxTotalThreadsPerThreadgroup());
let limit = self.pipeline_group_width_limit(&pipeline);
let width = match group_width {
Some(width) if (1..=limit).contains(&width) => width,
Some(width) => {
return Err(MetalError::new(
"threadgroup width",
format!("expected a nonzero width at most {limit}, got {width}"),
));
}
None => MAX_THREADS_PER_GROUP.min(input.len()).min(limit),
};
if width == 0 || input.len().div_ceil(width) > MAX_GROUPS {
return Err(MetalError::new(
"dispatch bounds",
@@ -681,6 +742,30 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
})
}
fn compute_pipeline(
&self,
function: &ProtocolObject<dyn MTLFunction>,
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
self.device
.newComputePipelineStateWithFunction_error(function)
.map_err(|error| {
MetalError::new(
"newComputePipelineStateWithFunction",
error.localizedDescription().to_string(),
)
})
}
fn pipeline_group_width_limit(
&self,
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
) -> usize {
self.device
.maxThreadsPerThreadgroup()
.width
.min(pipeline.maxTotalThreadsPerThreadgroup())
}
fn new_buffer(
&self,
words: &[u32],
+182
View File
@@ -51,6 +51,165 @@ fn verify_words(body: &str, input: &[u32], expected: &[u32]) {
assert_eq!(actual, expected);
}
const MAX_DISPATCH_GROUPS: usize = 64;
fn mixing_fixture(rounds: u32) -> String {
fixture(&format!(
"
uint value = input[id] ^ (id * 0x9e3779b9u);
for (uint round = 0u; round < {rounds}u; ++round) {{
value ^= value << 13u;
value ^= value >> 17u;
value ^= value << 5u;
value = value * 0x85ebca6bu + round;
}}
output[id] = value;
"
))
}
fn mixing_expectation(input: &[u32], rounds: u32) -> Vec<u32> {
(0_u32..)
.zip(input)
.map(|(id, &word)| {
let mut value = word ^ id.wrapping_mul(0x9e37_79b9);
for round in 0..rounds {
let left = value ^ (value << 13);
let right = left ^ (left >> 17);
let mixed = right ^ (right << 5);
value = mixed.wrapping_mul(0x85eb_ca6b).wrapping_add(round);
}
value
})
.collect()
}
fn mixing_input(words: u32) -> Vec<u32> {
(0..words)
.map(|id| id.wrapping_mul(0xc2b2_ae35) ^ 0xdead_beef)
.collect()
}
#[test]
fn threadgroup_widths_give_identical_known_answers() {
const WIDTHS: [usize; 16] = [
1, 2, 3, 7, 31, 32, 33, 63, 64, 65, 96, 128, 255, 256, 512, 1024,
];
const GRIDS: [u32; 7] = [1, 63, 64, 65, 1000, 4093, 4096];
const ROUNDS: u32 = 37;
let context = context();
let source = mixing_fixture(ROUNDS);
let limit = native(context.max_group_width(&source, "fixture"));
let mut checked = 0;
let mut skipped = 0;
for grid in GRIDS {
let input = mixing_input(grid);
let expected = mixing_expectation(&input, ROUNDS);
for width in WIDTHS {
if width > limit {
println!("skipped grid={grid} width={width}: device/pipeline limit is {limit}");
skipped += 1;
continue;
}
let groups = input.len().div_ceil(width);
if groups > MAX_DISPATCH_GROUPS {
println!(
"skipped grid={grid} width={width}: {groups} groups exceed {MAX_DISPATCH_GROUPS}"
);
skipped += 1;
continue;
}
let profile =
native(context.run_words_with_group_width(&source, "fixture", &input, width));
assert_eq!(profile.output, expected, "grid={grid} width={width}");
checked += 1;
}
}
assert!(checked > 0);
println!("checked {checked} configurations, skipped {skipped}");
}
#[test]
fn threadgroup_width_rejections() {
let context = context();
let source = fixture("output[id] = input[id];");
let limit = native(context.max_group_width(&source, "fixture"));
for width in [0, limit + 1] {
let error = context
.run_words_with_group_width(&source, "fixture", &[25], width)
.expect_err("invalid threadgroup width must fail");
assert_eq!(error.operation, "threadgroup width");
}
let error = context
.run_words_with_group_width(&source, "fixture", &[25; MAX_DISPATCH_GROUPS + 1], 1)
.expect_err("too many threadgroups must fail");
assert_eq!(error.operation, "dispatch bounds");
}
fn timing_summary(samples: &mut [f64]) -> String {
samples.sort_by(f64::total_cmp);
let count = samples.len();
let median = f64::midpoint(samples[(count - 1) / 2], samples[count / 2]);
let p95 = samples[(count * 95).div_ceil(100) - 1];
format!(
"median={:.3} min={:.3} max={:.3} p95={:.3}",
median * 1e6,
samples[0] * 1e6,
samples[count - 1] * 1e6,
p95 * 1e6,
)
}
#[test]
#[ignore = "manual GPU timing run"]
fn threadgroup_width_benchmark() {
const ROUNDS: u32 = 2000;
const WARMUPS: usize = 5;
const SAMPLES: usize = 30;
let context = context();
let device = context.device_name();
let source = mixing_fixture(ROUNDS);
let input = mixing_input(4096);
let expected = mixing_expectation(&input, ROUNDS);
let limit = native(context.max_group_width(&source, "fixture"));
let mut widths = vec![None];
for width in [32, 64, 128, 256, 512, 1024] {
if width > limit {
println!("device={device} skipped width={width}: device/pipeline limit is {limit}");
} else if input.len().div_ceil(width) > MAX_DISPATCH_GROUPS {
println!("device={device} skipped width={width}: exceeds {MAX_DISPATCH_GROUPS} groups");
} else {
widths.push(Some(width));
}
}
let mut timings = vec![([0.0; SAMPLES], [0.0; SAMPLES]); widths.len()];
for round in 0..WARMUPS + SAMPLES {
for (width, (gpu, host)) in widths.iter().zip(&mut timings) {
let profile = native(match width {
Some(width) => {
context.run_words_with_group_width(&source, "fixture", &input, *width)
}
None => context.run_words_profiled(&source, "fixture", &input),
});
assert_eq!(profile.output, expected, "width={width:?} round={round}");
if round >= WARMUPS {
gpu[round - WARMUPS] = profile.gpu_seconds;
host[round - WARMUPS] = profile.host_seconds;
}
}
}
for (width, (gpu, host)) in widths.into_iter().zip(&mut timings) {
let width = width.map_or_else(|| "default".to_owned(), |width| width.to_string());
println!(
"device={device} width={width} gpu_us[{}] host_us[{}]",
timing_summary(gpu),
timing_summary(host),
);
}
}
#[test]
fn integer_multiplication() {
let context = context();
@@ -203,3 +362,26 @@ fn errors_propagate() {
.expect_err("excessive dispatch must fail");
assert_eq!(error.operation, "dispatch bounds");
}
/// Identical outputs alone cannot show which width ran, so each thread also
/// reports its group size and in-group index.
#[test]
fn requested_threadgroup_width_is_dispatched() {
let context = context();
let source = fixture("output[id] = (group_size << 16u) | local;");
let limit = native(context.max_group_width(&source, "fixture"));
for (grid, width) in [(1000_usize, 33_usize), (4093, 64), (4096, 256), (65, 1024)] {
if width > limit {
println!("skipped grid={grid} width={width}: device/pipeline limit is {limit}");
continue;
}
let profile =
native(context.run_words_with_group_width(&source, "fixture", &vec![0; grid], width));
for (id, word) in profile.output.iter().enumerate() {
// dispatchThreads trims the last group to the grid's remainder.
let size = width.min(grid - id / width * width);
let expected = u32::try_from((size << 16) | (id % width)).unwrap();
assert_eq!(*word, expected, "grid={grid} width={width} id={id}");
}
}
}