Compare commits

...
Author SHA1 Message Date
katherinebytes a7fa8b0d65 Retry the ARM64 CI run
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 20:47:35 +00:00
katherinebytes 9ddb708cdf Merge upstream main for the compute pipeline cache
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:15:39 +00:00
katherinebytes 6f1ac2a906 Reuse Metal compute pipelines
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:12:15 +00:00
3 changed files with 251 additions and 27 deletions

No files matched your search

+1
View File
@@ -15,6 +15,7 @@ remains unsupported.
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
+76 -27
View File
@@ -1,4 +1,4 @@
use std::collections::BTreeMap;
use std::collections::{BTreeMap, VecDeque};
use std::ffi::c_void;
use std::fmt;
use std::mem::size_of_val;
@@ -37,6 +37,16 @@ const MAX_GROUPS: usize = 64;
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
const MAX_SOURCE_BYTES: usize = 64 * 1024;
const MAX_IN_FLIGHT: usize = 16;
const MAX_CACHED_PIPELINES: usize = 16;
type ComputePipeline = Retained<ProtocolObject<dyn MTLComputePipelineState>>;
struct CachedPipeline {
source: Box<str>,
entry: Box<str>,
shader_validation: bool,
pipeline: ComputePipeline,
}
const BC_READBACK: &str = r"
#include <metal_stdlib>
@@ -148,7 +158,9 @@ impl std::error::Error for MetalError {}
/// measure a single submission and are not a benchmark distribution.
#[derive(Debug, Clone)]
pub struct RunProfile {
/// Host library compilation time, or zero when reusing a compute pipeline.
pub library_seconds: f64,
/// Host pipeline creation time, or zero when reusing a compute pipeline.
pub pipeline_seconds: f64,
pub gpu_seconds: f64,
/// Host wall time from the start of setup until wait observes completion.
@@ -171,6 +183,8 @@ pub struct NativeCompute {
device: Retained<ProtocolObject<dyn MTLDevice>>,
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
submissions: Mutex<SubmissionTable>,
// Least recently used first. In-flight submissions retain their own reference.
compute_pipelines: Mutex<VecDeque<CachedPipeline>>,
}
/// A submitted dispatch whose result can be collected by its issuing context.
@@ -247,7 +261,7 @@ struct SubmissionEntry {
/// Metal reports Completed or Error.
struct InFlightResources {
command: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
_pipeline: ComputePipeline,
_input: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
output: Retained<ProtocolObject<dyn MTLBuffer>>,
_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
@@ -348,6 +362,7 @@ impl NativeCompute {
device,
queue,
submissions: Mutex::default(),
compute_pipelines: Mutex::default(),
})
})
}
@@ -901,7 +916,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
self.run_profiled_words(source, entry, input, Some(width))
}
/// Compile the kernel and report the smaller of the device and pipeline width limits.
/// Find or compile the kernel and report the smaller of the device and pipeline width limits.
///
/// Input size and threadgroup count are checked separately at dispatch.
///
@@ -911,11 +926,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
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)?;
let (pipeline, _, _) = self.prepare_compute_pipeline(source, entry)?;
Ok(self.pipeline_group_width_limit(&pipeline))
})
}
@@ -963,15 +974,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
host_start: Instant,
) -> Result<Submission<'_>, MetalError> {
self.submissions().check_capacity()?;
let options = compile_options()?;
let library_start = Instant::now();
let library = self.compile_library(source, &options)?;
let library_seconds = library_start.elapsed().as_secs_f64();
let function = find_function(&library, entry)?;
let pipeline_start = Instant::now();
let pipeline = self.compute_pipeline(&function)?;
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
verify_shader_validation(&pipeline)?;
let (pipeline, library_seconds, pipeline_seconds) =
self.prepare_compute_pipeline(source, entry)?;
let limit = self.pipeline_group_width_limit(&pipeline);
let width = match group_width {
@@ -1108,18 +1112,67 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
})
}
fn compute_pipeline(
fn prepare_compute_pipeline(
&self,
function: &ProtocolObject<dyn MTLFunction>,
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
self.device
.newComputePipelineStateWithFunction_error(function)
source: &str,
entry: &str,
) -> Result<(ComputePipeline, f64, f64), MetalError> {
let shader_validation = std::env::var("MTL_SHADER_VALIDATION").as_deref() == Ok("1");
// Device identity is fixed by this context. All misses use the same
// compile options (safe math, precise functions, default language,
// no macros) and unspecialized functions. Any configurable options
// must become part of the key before they are used here.
let mut cache = self
.compute_pipelines
.lock()
.unwrap_or_else(PoisonError::into_inner);
if let Some(index) = cache.iter().position(|cached| {
cached.source.as_ref() == source
&& cached.entry.as_ref() == entry
&& cached.shader_validation == shader_validation
}) {
let cached = cache.remove(index).expect("position in the locked cache");
let pipeline = cached.pipeline.clone();
cache.push_back(cached);
return Ok((pipeline, 0.0, 0.0));
}
// Serialize cache misses in this context so concurrent requests for
// one key share the same build. The submission table is unlocked here.
let options = compile_options()?;
let library_start = Instant::now();
let library = self.compile_library(source, &options)?;
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_seconds = pipeline_start.elapsed().as_secs_f64();
if shader_validation {
verify_shader_validation(&pipeline)?;
}
// Bound owned key text to 1 MiB. A valid oversized key can run
// uncached, so this budget does not alter source or entry validation.
if entry.len() <= MAX_SOURCE_BYTES.saturating_sub(source.len()) {
if cache.len() == MAX_CACHED_PIPELINES {
cache.pop_front();
}
cache.push_back(CachedPipeline {
source: source.into(),
entry: entry.into(),
shader_validation,
pipeline: pipeline.clone(),
});
}
Ok((pipeline, library_seconds, pipeline_seconds))
}
fn pipeline_group_width_limit(
@@ -1232,10 +1285,6 @@ fn check_command_status(
fn verify_shader_validation(
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
) -> Result<(), MetalError> {
if std::env::var("MTL_SHADER_VALIDATION").as_deref() != Ok("1") {
return Ok(());
}
if !pipeline.respondsToSelector(sel!(shaderValidation)) {
return Err(MetalError::new(
"shaderValidation",
+174
View File
@@ -356,6 +356,131 @@ fn multiple_submissions() {
assert_eq!(second, [5, 5, 1, 5]);
}
fn pipeline_was_reused(profile: &xenora_metal::RunProfile) -> bool {
profile.library_seconds == 0.0 && profile.pipeline_seconds == 0.0
}
#[test]
fn compute_pipeline_cache_distinguishes_source_entry_and_context() {
let context = context();
let source = fixture("output[id] = input[id] + 1u;");
let second_entry =
fixture("output[id] = input[id] * 2u;").replace("void fixture(", "void other(");
let source = format!("{source}\n{second_entry}");
let changed = source.replace("input[id] + 1u", "input[id] - 1u");
let input = [0, 11, u32::MAX];
for (msl, entry, expected) in [
(source.as_str(), "fixture", [1, 12, 0]),
(source.as_str(), "other", [0, 22, u32::MAX - 1]),
(changed.as_str(), "fixture", [u32::MAX, 10, u32::MAX - 1]),
] {
let cold = native(context.run_words_profiled(msl, entry, &input));
let warm = native(context.run_words_profiled(msl, entry, &input));
assert!(!pipeline_was_reused(&cold), "{entry}");
assert!(pipeline_was_reused(&warm), "{entry}");
assert_eq!(cold.output, expected, "{entry}");
assert_eq!(warm.output, expected, "{entry}");
}
let separate = native(NativeCompute::new());
let fresh = native(separate.run_words_profiled(&source, "fixture", &input));
assert!(!pipeline_was_reused(&fresh));
assert_eq!(fresh.output, [1, 12, 0]);
for _ in 0..2 {
for (msl, entry, operation) in [
(source.as_str(), "missing", "newFunctionWithName"),
("not valid MSL", "fixture", "newLibraryWithSource"),
] {
let error = context
.run_words_profiled(msl, entry, &input)
.expect_err("invalid pipeline must still fail after warming the cache");
assert_eq!(error.operation, operation);
}
}
let error = context
.run_words_with_group_width(&source, "fixture", &input, 0)
.expect_err("cached pipeline must still check dispatch width");
assert_eq!(error.operation, "threadgroup width");
}
#[test]
fn compute_pipeline_cache_bounds_key_bytes_without_rejecting_maximum_source() {
const SOURCE_LIMIT: usize = 64 * 1024;
let context = context();
let mut source = fixture("output[id] = input[id] ^ 1u;");
source.push_str("\n// ");
source.push_str(&" ".repeat(SOURCE_LIMIT - source.len()));
for _ in 0..2 {
let profile = native(context.run_words_profiled(&source, "fixture", &[8]));
assert_eq!(profile.output, [9]);
assert!(!pipeline_was_reused(&profile));
}
source.push(' ');
let error = context
.run_words_profiled(&source, "fixture", &[8])
.expect_err("source above 64 KiB must fail before pipeline lookup");
assert_eq!(error.operation, "source bounds");
}
#[test]
fn compute_pipeline_cache_evicts_oldest_unused_key_and_keeps_pending_work_alive() {
let context = context();
// Seventeen entries in one source fit in Metal's input limit and exceed
// Xenora's 16-pipeline cache. Each kernel writes a distinct result.
let source: String = (0..=16)
.map(|id| {
fixture(&format!("output[id] = input[id] + {id}u;"))
.replace("void fixture(", &format!("void entry{id}("))
})
.collect::<Vec<_>>()
.join("\n");
native(context.max_group_width(&source, "entry0"));
let (pending, gate) = native(context.submit_words_gated(&source, "entry1", &[7]));
for id in 2..16 {
native(context.max_group_width(&source, &format!("entry{id}")));
}
native(context.max_group_width(&source, "entry0"));
native(context.max_group_width(&source, "entry16"));
gate.open();
let finished = native(context.wait(pending));
assert_eq!(finished.output, [8]);
let recent = native(context.run_words_profiled(&source, "entry0", &[29]));
assert!(pipeline_was_reused(&recent));
assert_eq!(recent.output, [29]);
let rebuilt = native(context.run_words_profiled(&source, "entry1", &[17]));
assert!(!pipeline_was_reused(&rebuilt));
assert_eq!(rebuilt.output, [18]);
}
#[test]
fn simultaneous_compute_submissions_share_one_pipeline_build() {
let context = context();
let source = fixture("output[id] = input[id] ^ 5u;");
let start = std::sync::Barrier::new(4);
std::thread::scope(|scope| {
let workers: Vec<_> = (0..4)
.map(|input| {
let (context, source, start) = (&context, &source, &start);
scope.spawn(move || {
start.wait();
let token = native(context.submit_words(source, "fixture", &[input]));
let result = native(context.wait(token));
assert_eq!(result.output, [input ^ 5]);
usize::from(!pipeline_was_reused(&result))
})
})
.collect();
let builds: usize = workers
.into_iter()
.map(|worker| worker.join().unwrap())
.sum();
assert_eq!(builds, 1);
});
}
#[test]
fn errors_propagate() {
let context = context();
@@ -413,3 +538,52 @@ kernel void fixture(device const uint *input [[buffer(0)]],
}
}
}
#[test]
#[ignore = "manual GPU timing run"]
fn compute_pipeline_reuse_benchmark() {
const WARMUPS: usize = 10;
const SAMPLES: usize = 101;
let warm_context = context();
let device = warm_context.device_name();
let source = fixture("output[id] = input[id] * 7u + 3u;");
let input = mixing_input(131);
let expected: Vec<_> = input
.iter()
.map(|word| word.wrapping_mul(7).wrapping_add(3))
.collect();
let mut timings = [[[0.0; SAMPLES]; 4]; 2];
for round in 0..WARMUPS + SAMPLES {
let cold_context = context();
// Alternate order so neither measurement always follows the other.
let contexts = [&cold_context, &warm_context];
for index in [round % 2, (round + 1) % 2] {
let profile = native(contexts[index].run_words_profiled(&source, "fixture", &input));
assert_eq!(profile.output, expected, "context={index} round={round}");
if round >= WARMUPS {
for (samples, seconds) in timings[index].iter_mut().zip([
profile.library_seconds,
profile.pipeline_seconds,
profile.host_seconds,
profile.gpu_seconds,
]) {
samples[round - WARMUPS] = seconds;
}
}
}
}
for (label, [mut library, mut pipeline, mut host, mut gpu]) in
["fresh context", "repeated context"]
.into_iter()
.zip(timings)
{
println!(
"device={device} {label} samples={SAMPLES} library_us[{}] pipeline_us[{}] host_us[{}] gpu_us[{}]",
timing_summary(&mut library),
timing_summary(&mut pipeline),
timing_summary(&mut host),
timing_summary(&mut gpu),
);
}
}