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
Zach Doxsee 5b7ffec90a Merge pull request #347 from Arths17/task/109-relocation-overhead
loader: avoid per-entry relocation histogram lookups
2026-11-24 20:15:11 +01:00
Zach Doxsee 48c5d20aa9 Merge pull request #335 from izdat-sl4w/fix/audit-utf8-locale
audit: read and write tracked files as UTF-8
2026-11-24 20:14:57 +01:00
katherinebytes 6f1ac2a906 Reuse Metal compute pipelines
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 19:12:15 +00:00
atharvranjan adf10db015 loader: build relocation type counts once per image
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 12:04:05 -06:00
4 changed files with 486 additions and 28 deletions

No files matched your search

+2
View File
@@ -10,10 +10,12 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
- 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
+234 -1
View File
@@ -163,7 +163,6 @@ pub fn apply_relocations(
let reloc_type = (entry_val >> 12) as u8;
let offset_in_page = (entry_val & 0x0FFF) as u32;
*report.type_counts.entry(reloc_type).or_insert(0) += 1;
report.total_entries += 1;
match reloc_type {
@@ -221,6 +220,17 @@ pub fn apply_relocations(
read_bytes += block_size as usize;
}
// Only these two types can reach a successful return. Build the public
// histogram once instead of searching its tree for every relocation.
for (kind, count) in [
(IMAGE_REL_BASED_ABSOLUTE, report.skipped_absolute),
(IMAGE_REL_BASED_DIR64, report.applied_dir64),
] {
if count != 0 {
report.type_counts.insert(kind, count);
}
}
Ok(report)
}
@@ -274,3 +284,226 @@ fn find_reloc_directory(
Ok(Some((reloc_rva, reloc_size)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::memory::MemoryPermissions;
use crate::pe::PeSection;
use std::hint::black_box;
use std::time::Instant;
const PREFERRED: u64 = 0x140000000;
const LOADED: u64 = PREFERRED + 0x200000;
const DATA_RVA: u32 = 0x1000;
const DIRECTORY_RVA: u32 = 0x10000000;
const DIRECTORY_OFFSET: usize = 0x200;
// Original synthetic directory, laid out from Microsoft's PE Format,
// .reloc section: eight-byte block headers and two-byte type/offset words.
// https://learn.microsoft.com/windows/win32/debug/pe-format#the-reloc-section-image-only
// Header fields and metadata are supplied directly: PE parsing is not timed.
fn fixture(blocks: &[(u32, Vec<u16>)], data: &[u8]) -> (ParsedPe, Vec<u8>, GuestMemory) {
let mut bytes = vec![0u8; DIRECTORY_OFFSET];
bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
bytes[0x104..0x108].copy_from_slice(&16u32.to_le_bytes());
bytes[0x130..0x134].copy_from_slice(&DIRECTORY_RVA.to_le_bytes());
for (page, entries) in blocks {
bytes.extend_from_slice(&page.to_le_bytes());
bytes.extend_from_slice(&(8u32 + entries.len() as u32 * 2).to_le_bytes());
for entry in entries {
bytes.extend_from_slice(&entry.to_le_bytes());
}
}
let size = (bytes.len() - DIRECTORY_OFFSET) as u32;
bytes[0x134..0x138].copy_from_slice(&size.to_le_bytes());
let pe = ParsedPe {
machine: 0x8664,
number_of_sections: 1,
time_date_stamp: 0,
image_base: PREFERRED,
section_alignment: 4096,
file_alignment: 512,
size_of_image: DIRECTORY_RVA + size.max(4096),
size_of_headers: 512,
entry_point_rva: 0,
sections: vec![PeSection {
name: ".reloc".into(),
virtual_address: DIRECTORY_RVA,
virtual_size: size,
raw_data_ptr: DIRECTORY_OFFSET as u32,
raw_data_size: size,
characteristics: 0x40000040,
permissions: MemoryPermissions::READ_ONLY,
}],
};
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
LOADED + u64::from(DATA_RVA),
data.len(),
MemoryPermissions::READ_ONLY,
data,
)
.unwrap();
(pe, bytes, memory)
}
#[test]
fn counts_padding_and_rebases_read_only_targets() {
for (preferred, initial, expected) in [
(PREFERRED, 0x140001234, 0x140201234),
(LOADED + 0x200000, 0x140001234, 0x13fe01234),
(LOADED - 8, u64::MAX - 3, 4),
(LOADED + 8, 3, u64::MAX - 4),
] {
let (mut pe, bytes, mut memory) =
fixture(&[(DATA_RVA, vec![0x0fff, 0xa000])], &initial.to_le_bytes());
pe.image_base = preferred;
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), expected);
assert_eq!(report.total_entries, 2);
assert_eq!(report.applied_dir64, 1);
assert_eq!(report.skipped_absolute, 1);
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 1)]));
}
}
#[test]
fn histogram_omits_types_that_did_not_occur() {
for (entries, counts) in [
(vec![], BTreeMap::new()),
(vec![0x0fff, 0x0000], BTreeMap::from([(0, 2)])),
(vec![0xa000, 0xa008], BTreeMap::from([(10, 2)])),
] {
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &[0; 16]);
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
assert_eq!(report.type_counts, counts);
}
}
#[test]
fn preserves_duplicate_and_overlapping_entry_order() {
let (pe, bytes, mut memory) = fixture(
&[(DATA_RVA, vec![0xa000, 0xa000, 0xa004, 0x0000])],
&[0; 16],
);
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
// Two additions of 0x200000 at offset zero, then one at offset four.
let mut actual = [0; 16];
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
assert_eq!(
actual,
[0, 0, 0x40, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0]
);
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 3)]));
}
#[test]
fn overlapping_fields_observe_prior_carries_in_directory_order() {
let initial = [255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0];
for (entries, expected) in [
(vec![0xa000, 0xa004], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]),
(vec![0xa004, 0xa000], [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]),
] {
let (mut pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &initial);
pe.image_base = LOADED - 1;
apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
let mut actual = [0; 12];
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
assert_eq!(actual, expected);
}
}
#[test]
fn preserves_prior_writes_and_rejects_unsupported_types() {
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, vec![0xa000, 0xf008])], &[0; 16]);
assert_eq!(
apply_relocations(&pe, &bytes, LOADED, &mut memory),
Err(RelocationError::UnsupportedRelocationType(15))
);
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), 0x200000);
assert_eq!(memory.read_u64(LOADED + 0x1008).unwrap(), 0);
}
#[test]
fn zero_delta_keeps_the_empty_report_without_parsing() {
let (mut pe, _, mut memory) = fixture(&[], &[0; 8]);
pe.image_base = LOADED;
assert_eq!(
apply_relocations(&pe, &[], LOADED, &mut memory).unwrap(),
RelocationReport::default()
);
}
#[test]
#[ignore = "manual relocation timing run; release build on an otherwise idle host"]
fn relocation_profile() {
for pages in [1u32, 128] {
for padding_every in [0usize, 2, 1] {
let blocks: Vec<_> = (0..pages)
.map(|page| {
let entries = (0..512)
.map(|slot| {
let padding = padding_every != 0 && slot % padding_every == 0;
(if padding { 0 } else { 0xa000 }) | (slot as u16 * 8)
})
.collect();
(DATA_RVA + page * 4096, entries)
})
.collect();
let (pe, bytes, initial) = fixture(&blocks, &vec![0; pages as usize * 4096]);
let mut samples = Vec::new();
for run in 0..36 {
let mut memory = initial.clone();
let start = Instant::now();
let report = black_box(
apply_relocations(
black_box(&pe),
black_box(&bytes),
LOADED,
black_box(&mut memory),
)
.unwrap(),
);
let elapsed = start.elapsed().as_secs_f64() * 1e6;
assert_eq!(report.total_entries, pages as usize * 512);
let padding = match padding_every {
0 => 0,
2 => report.total_entries / 2,
_ => report.total_entries,
};
assert_eq!(report.skipped_absolute, padding);
assert_eq!(report.applied_dir64, report.total_entries - padding);
// Check every output against the fixture's independently specified pattern.
for slot in 0..pages as usize * 512 {
let expected = if padding_every != 0 && slot % padding_every == 0 {
0
} else {
0x200000
};
assert_eq!(
memory.read_u64(LOADED + 0x1000 + slot as u64 * 8).unwrap(),
expected
);
}
if run >= 5 {
samples.push(elapsed);
}
}
samples.sort_by(f64::total_cmp);
let mean = samples.iter().sum::<f64>() / samples.len() as f64;
let variance =
samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / samples.len() as f64;
println!(
"pages={pages} padding_every={padding_every} n={} median_us={:.3} variance_us2={variance:.3} min_us={:.3} max_us={:.3}",
samples.len(),
samples[samples.len() / 2],
samples[0],
samples[samples.len() - 1]
);
}
}
}
}
+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),
);
}
}