Merge commit '263284f' into HEAD

This commit is contained in:
elforeign committed 2026-11-24 08:38:41 -06:00
commit 685af87f49
16 files changed
+1189 -57

No files matched your search

+2
View File
@@ -10,9 +10,11 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- 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.
- 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
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
- Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`.
+226 -4
View File
@@ -14,11 +14,12 @@ use std::path::PathBuf;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
use xenora_metal::NativeCompute;
use xenora_metal::{NativeCompute, RunProfile};
use xenora_shader::{Architecture, ENTRY_POINT, compile};
const WARMUP_REPS: usize = 2;
const DEFAULT_REPS: usize = 7;
const BATCH: usize = 8;
#[derive(Debug, Clone)]
struct Fixture {
@@ -83,10 +84,66 @@ struct SizeResult {
pipeline: Stats,
gpu: Stats,
host: Stats,
/// Host submission stages inside `host`, plus readback after it.
submit: SubmitStats,
/// Fraction of samples whose GPU timestamp delta was zero.
gpu_zero_fraction: f64,
}
/// Host-side split of one dispatch's submission path.
///
/// `other` is `host` minus library, pipeline and the four stages below it,
/// per sample: compile options, function lookup, bounds and validation checks.
#[derive(Debug, Clone, Default)]
struct SubmitStats {
alloc: Stats,
encode: Stats,
commit: Stats,
wait: Stats,
readback: Stats,
other: Stats,
}
#[derive(Debug, Clone, Default)]
struct SubmitSamples {
alloc: Vec<f64>,
encode: Vec<f64>,
commit: Vec<f64>,
wait: Vec<f64>,
readback: Vec<f64>,
other: Vec<f64>,
}
impl SubmitSamples {
fn push(&mut self, profile: &RunProfile) {
self.alloc.push(profile.alloc_seconds);
self.encode.push(profile.encode_seconds);
self.commit.push(profile.commit_seconds);
self.wait.push(profile.wait_seconds);
self.readback.push(profile.readback_seconds);
self.other.push(
profile.host_seconds
- profile.library_seconds
- profile.pipeline_seconds
- profile.alloc_seconds
- profile.encode_seconds
- profile.commit_seconds
- profile.wait_seconds,
);
}
fn stats(self) -> SubmitStats {
SubmitStats {
alloc: Stats::from_samples(self.alloc),
encode: Stats::from_samples(self.encode),
commit: Stats::from_samples(self.commit),
wait: Stats::from_samples(self.wait),
readback: Stats::from_samples(self.readback),
other: Stats::from_samples(self.other),
}
}
}
#[derive(Debug, Clone)]
struct FixtureResult {
name: String,
@@ -95,6 +152,14 @@ struct FixtureResult {
status: String,
reason: String,
sizes: Vec<SizeResult>,
batch: Option<BatchResult>,
}
#[derive(Debug, Clone)]
struct BatchResult {
words: usize,
sync: Stats,
pipelined: Stats,
}
fn main() -> Result<(), Box<dyn Error>> {
@@ -180,6 +245,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
status: "not-implemented".to_string(),
reason: String::new(),
sizes: Vec::new(),
batch: None,
};
let code = match fs::read(&fixture.path) {
@@ -242,6 +308,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
let mut pipeline_samples = Vec::with_capacity(reps);
let mut gpu_samples = Vec::with_capacity(reps);
let mut host_samples = Vec::with_capacity(reps);
let mut submit_samples = SubmitSamples::default();
let mut gpu_zero = 0usize;
let mut mismatch = None;
@@ -275,6 +342,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
pipeline_samples.push(profile.pipeline_seconds);
gpu_samples.push(profile.gpu_seconds);
host_samples.push(profile.host_seconds);
submit_samples.push(&profile);
if profile.gpu_seconds <= 0.0 {
gpu_zero += 1;
}
@@ -294,6 +362,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
pipeline: Stats::from_samples(pipeline_samples),
gpu: Stats::from_samples(gpu_samples),
host: Stats::from_samples(host_samples),
submit: submit_samples.stats(),
gpu_zero_fraction: if measured == 0 {
0.0
} else {
@@ -302,11 +371,83 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
});
}
let batch_words = fixture
.sizes
.iter()
.copied()
.min_by_key(|words| words.abs_diff(1024))
.unwrap_or(1024);
match measure_batch(metal, &code, fixture, batch_words, reps) {
Ok(batch) => result.batch = Some(batch),
Err(reason) => {
result.status = "excluded".to_string();
result.reason = reason;
return result;
}
}
result.sizes = sizes;
result.status = "benchmarked".to_string();
result
}
fn measure_batch(
metal: &NativeCompute,
code: &[u8],
fixture: &Fixture,
words: usize,
reps: usize,
) -> Result<BatchResult, String> {
let input = expand(&fixture.input, words);
let expected = expand(&fixture.expected, words);
let mut sync = Vec::with_capacity(reps);
let mut pipelined = Vec::with_capacity(reps);
for rep in 0..(WARMUP_REPS + reps) {
for (samples, variant) in [(&mut sync, "sync"), (&mut pipelined, "pipelined")] {
let mut tokens = Vec::with_capacity(BATCH);
let mut outputs = Vec::with_capacity(BATCH);
let start = std::time::Instant::now();
for _ in 0..BATCH {
let compiled = compile(Architecture::Gfx1030, code).map_err(|error| {
format!("{variant} batch compile failed at {words} words: {error}")
})?;
if variant == "sync" {
let profile = metal
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
.map_err(|error| {
format!("{variant} batch run failed at {words} words: {error}")
})?;
outputs.push(profile.output);
} else {
let token = metal
.submit_words(&compiled.msl, ENTRY_POINT, &input)
.map_err(|error| {
format!("{variant} batch submit failed at {words} words: {error}")
})?;
tokens.push(token);
}
}
for token in tokens {
let profile = metal.wait(token).map_err(|error| {
format!("{variant} batch wait failed at {words} words: {error}")
})?;
outputs.push(profile.output);
}
let per_dispatch = start.elapsed().as_secs_f64() / BATCH as f64;
if outputs.iter().any(|output| *output != expected) {
return Err(format!("{variant} batch GPU mismatch at {words} words"));
}
if rep >= WARMUP_REPS {
samples.push(per_dispatch);
}
}
}
Ok(BatchResult {
words,
sync: Stats::from_samples(sync),
pipelined: Stats::from_samples(pipelined),
})
}
fn expand(base: &[u32], words: usize) -> Vec<u32> {
(0..words).map(|i| base[i % base.len()]).collect()
}
@@ -612,13 +753,19 @@ fn results_json(results: &[FixtureResult]) -> String {
for (size_index, size) in result.sizes.iter().enumerate() {
let _ = writeln!(
out,
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"alloc\": {}, \"encode\": {}, \"commit\": {}, \"wait\": {}, \"readback\": {}, \"host_other\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
size.words,
stats_json(&size.compile),
stats_json(&size.library),
stats_json(&size.pipeline),
stats_json(&size.gpu),
stats_json(&size.host),
stats_json(&size.submit.alloc),
stats_json(&size.submit.encode),
stats_json(&size.submit.commit),
stats_json(&size.submit.wait),
stats_json(&size.submit.readback),
stats_json(&size.submit.other),
size.gpu_zero_fraction,
if size_index + 1 == result.sizes.len() {
""
@@ -627,9 +774,19 @@ fn results_json(results: &[FixtureResult]) -> String {
}
);
}
out.push_str(" ]");
if let Some(batch) = &result.batch {
let _ = write!(
out,
",\n \"batch\": {{ \"dispatches\": {BATCH}, \"words\": {}, \"sync\": {}, \"pipelined\": {} }}",
batch.words,
stats_json(&batch.sync),
stats_json(&batch.pipelined)
);
}
let _ = writeln!(
out,
" ]\n }}{}",
"\n }}{}",
if index + 1 == results.len() { "" } else { "," }
);
}
@@ -644,7 +801,7 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
let _ = writeln!(
out,
"Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. \
Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol."
See `docs/testing/benchmarks.md` for the single-dispatch protocol."
);
let _ = writeln!(out);
let _ = writeln!(out, "## Environment");
@@ -739,5 +896,70 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
);
}
}
let _ = writeln!(out);
let _ = writeln!(out, "## Submission split");
let _ = writeln!(out);
let _ = writeln!(
out,
"Medians in microseconds of the host stages inside `host`: `alloc` creates the input and \
output shared buffers, `encode` creates the command buffer and encodes the dispatch, \
`commit` and `wait` time `commit` and `waitUntilCompleted`, and `other` is the per-sample \
remainder of `host` after library, pipeline and these four stages. `readback` copies \
the output after `host` ends."
);
let _ = writeln!(out);
let _ = writeln!(
out,
"| Fixture | Words | host | alloc | encode | commit | wait | other | readback |"
);
let _ = writeln!(
out,
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"
);
for result in results.iter().filter(|r| r.status == "benchmarked") {
for size in &result.sizes {
let stages = &size.submit;
let _ = writeln!(
out,
"| {} | {} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} |",
result.name,
size.words,
size.host.median * 1e6,
stages.alloc.median * 1e6,
stages.encode.median * 1e6,
stages.commit.median * 1e6,
stages.wait.median * 1e6,
stages.other.median * 1e6,
stages.readback.median * 1e6
);
}
}
let _ = writeln!(out);
let _ = writeln!(out, "## Batched submission");
let _ = writeln!(out);
let _ = writeln!(
out,
"Median host microseconds per dispatch in batches of {BATCH}, including recompilation."
);
let _ = writeln!(out);
let _ = writeln!(
out,
"| Fixture | Words | Sync (µs) | Pipelined (µs) | Sync / pipelined |"
);
let _ = writeln!(out, "| --- | --- | --- | --- | --- |");
for result in results {
if let Some(batch) = &result.batch {
let _ = writeln!(
out,
"| {} | {} | {:.2} | {:.2} | {:.2}× |",
result.name,
batch.words,
batch.sync.median * 1e6,
batch.pipelined.median * 1e6,
batch.sync.median / batch.pipelined.median
);
}
}
out
}
+37 -10
View File
@@ -389,14 +389,22 @@ def load_registry(path=REGISTRY):
)
if len(set(includes)) != len(includes):
raise RegistryError(f"{path.name}: a family file is included twice")
for key, kind, name in (("operand_rules", dict, "a table"), ("form", list, "an array"),
("encoding_variant", list, "an array")):
if not isinstance(registry.get(key, kind()), kind):
raise RegistryError(f"{path.name}: {key} must be {name}")
rules = registry.setdefault("operand_rules", {})
forms = registry.setdefault("form", [])
if (path.parent / path.stem).is_symlink():
raise RegistryError(f"{path.name}: the family directory {path.stem}/ is a link")
try:
directory = (path.parent / path.stem).resolve(strict=True)
except (OSError, RuntimeError) as error:
raise RegistryError(f"{path.name}: the family directory {path.stem}/ cannot be read: {error}")
# A standalone registry (no includes) needs no family directory.
if includes:
if (path.parent / path.stem).is_symlink():
raise RegistryError(f"{path.name}: the family directory {path.stem}/ is a link")
try:
directory = (path.parent / path.stem).resolve(strict=True)
except (OSError, RuntimeError) as error:
raise RegistryError(
f"{path.name}: the family directory {path.stem}/ cannot be read: {error}"
)
identities = set()
for include in includes:
part_path = path.parent / include
@@ -416,6 +424,10 @@ def load_registry(path=REGISTRY):
unknown = sorted(set(part) - FAMILY_FILE_KEYS)
if unknown:
raise RegistryError(f"{include}: keys {unknown} belong in the root file")
for key, kind, name in (("operand_rules", dict, "a table"), ("form", list, "an array"),
("encoding_variant", list, "an array")):
if not isinstance(part.get(key, kind()), kind):
raise RegistryError(f"{include}: {key} must be {name}")
for name, rule in part.get("operand_rules", {}).items():
if name in rules:
raise RegistryError(f"{include}: operand rule {name} is declared twice")
@@ -767,9 +779,10 @@ def _well_formed(rule):
)
def variant_row(registry, variant):
def variant_row(registry, variant, base=None):
"""The base form re-encoded: its declaration with the variant's identity."""
base = next(form for form in registry["form"] if form.get("name") == variant["of"])
if base is None:
base = next(form for form in registry["form"] if form.get("name") == variant["of"])
return dict(
base, family=variant["family"], opcode=variant["opcode"], operands=variant["operands"],
spec=variant["spec"], verify=variant["verify"],
@@ -779,7 +792,14 @@ def variant_row(registry, variant):
def _check_variants(registry, rules, documents, snapshot, seen, errors):
forms = {form.get("name"): form for form in registry.get("form", [])}
identities = {(form.get("name"), form.get("family")) for form in registry.get("form", [])}
for index, variant in enumerate(registry.get("encoding_variant", [])):
variants = registry.get("encoding_variant", [])
if not isinstance(variants, list):
errors.append("encoding_variant must be an array of tables")
return
for index, variant in enumerate(variants):
if not isinstance(variant, dict):
errors.append(f"encoding variant #{index}: must be a table, got {variant!r}")
continue
label = f"{variant.get('of', f'variant #{index}')!s} ({variant.get('family')!s})"
missing = sorted(VARIANT_KEYS - set(variant))
extra = sorted(set(variant) - VARIANT_KEYS)
@@ -830,7 +850,14 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors):
errors.append(f"{label}: invalid verification requirements {verify}")
# The XML check runs on the re-encoded declaration, so the variant's
# operands must agree with the base form's widths, signedness and effects.
_check_xml(variant_row(registry, variant), rule, snapshot, errors)
# An incomplete base form has its own diagnostic; checking its re-encoding
# would only fail on the missing fields.
if FORM_KEYS - set(base):
errors.append(f"{label}: not checked, its form {variant['of']} is incomplete")
continue
# The same base row as the completeness check above (with duplicate
# declarations, the dict keeps the last one).
_check_xml(variant_row(registry, variant, base), rule, snapshot, errors)
# Every explicit operand, destination included, has the base encoding's
# data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3).
base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"])))
+2
View File
@@ -25,6 +25,8 @@ unsupported = [
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
]
# VOP3 opcode of a VOP2 form = VOP2 opcode + 0x100 (guide 12.7.1), e.g. 37 + 256
# = 293; each opcode below is still checked against the pinned XML.
[[encoding_variant]]
of = "V_ADD_NC_U32"
family = "VOP3"
+1
View File
@@ -41,6 +41,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
"MTLComputePipeline",
"MTLDepthStencil",
"MTLDevice",
"MTLEvent",
"MTLLibrary",
"MTLPixelFormat",
"MTLPipeline",
+427 -39
View File
@@ -1,9 +1,12 @@
use std::collections::BTreeMap;
use std::ffi::c_void;
use std::fmt;
use std::mem::size_of_val;
use std::ptr::{NonNull, copy_nonoverlapping};
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Instant;
use objc2::Message;
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
use objc2::sel;
@@ -13,8 +16,8 @@ use objc2_metal::{
MTLCompileOptions, MTLComputeCommandEncoder, MTLComputePipelineState,
MTLCreateSystemDefaultDevice, MTLDevice, MTLFunction, MTLGPUFamily, MTLLibrary,
MTLMathFloatingPointFunctions, MTLMathMode, MTLOrigin, MTLPixelFormat, MTLRegion,
MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture,
MTLTextureDescriptor, MTLTextureUsage,
MTLResourceOptions, MTLSamplerState, MTLShaderValidation, MTLSharedEvent, MTLSize,
MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
};
use xenora_texture::{
Bc1Upload, BcAlphaFormat, BcAlphaUpload, BcChannelFormat, BcChannelUpload, TiledBc1,
@@ -33,6 +36,7 @@ const MAX_THREADS_PER_GROUP: usize = 64;
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 BC_READBACK: &str = r"
#include <metal_stdlib>
@@ -65,7 +69,7 @@ enum ComputeInput<'a> {
Texture(&'a ProtocolObject<dyn MTLTexture>, usize),
SampledTexture {
texture: &'a ProtocolObject<dyn MTLTexture>,
sampler: &'a ProtocolObject<dyn objc2_metal::MTLSamplerState>,
sampler: &'a ProtocolObject<dyn MTLSamplerState>,
coords: &'a [u32],
},
}
@@ -147,7 +151,18 @@ pub struct RunProfile {
pub library_seconds: f64,
pub pipeline_seconds: f64,
pub gpu_seconds: f64,
/// Host wall time from the start of setup until wait observes completion.
pub host_seconds: f64,
/// Host time to allocate the input and output shared buffers.
pub alloc_seconds: f64,
/// Host time to create the command buffer and encode the dispatch.
pub encode_seconds: f64,
/// Host time spent in `commit`.
pub commit_seconds: f64,
/// Host time spent in `waitUntilCompleted`.
pub wait_seconds: f64,
/// Host time to copy the output words back; not part of `host_seconds`.
pub readback_seconds: f64,
pub output: Vec<u32>,
}
@@ -155,10 +170,161 @@ pub struct RunProfile {
pub struct NativeCompute {
device: Retained<ProtocolObject<dyn MTLDevice>>,
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
submissions: Mutex<SubmissionTable>,
}
/// A submitted dispatch whose result can be collected by its issuing context.
#[must_use]
pub struct Submission<'a> {
context: &'a NativeCompute,
id: u64,
}
impl Drop for Submission<'_> {
fn drop(&mut self) {
let mut table = self.context.submissions();
if let Some(entry) = table.entries.get_mut(&self.id) {
if entry.resources.is_some() {
entry.abandoned = true;
} else {
table.entries.remove(&self.id);
}
}
}
}
#[doc(hidden)]
pub struct SubmissionGate {
event: Retained<ProtocolObject<dyn MTLSharedEvent>>,
}
impl SubmissionGate {
pub fn open(&self) {
self.event.setSignaledValue(1);
}
}
impl Drop for SubmissionGate {
fn drop(&mut self) {
self.open();
}
}
#[derive(Default)]
struct SubmissionTable {
next_id: u64,
entries: BTreeMap<u64, SubmissionEntry>,
}
impl SubmissionTable {
fn in_flight(&self) -> usize {
self.entries
.values()
.filter(|entry| entry.resources.is_some())
.count()
}
fn check_capacity(&self) -> Result<(), MetalError> {
if self.in_flight() >= MAX_IN_FLIGHT {
return Err(MetalError::new(
"in-flight limit",
format!("at most {MAX_IN_FLIGHT} compute submissions may be in flight"),
));
}
Ok(())
}
}
struct SubmissionEntry {
resources: Option<InFlightResources>,
result: Result<RunProfile, MetalError>,
host_start: Instant,
abandoned: bool,
waiting: bool,
}
/// Owns every resource referenced by the unretained command buffer until
/// Metal reports Completed or Error.
struct InFlightResources {
command: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
_input: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
output: Retained<ProtocolObject<dyn MTLBuffer>>,
_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
_sampler: Option<Retained<ProtocolObject<dyn MTLSamplerState>>>,
gate: Option<Retained<ProtocolObject<dyn MTLSharedEvent>>>,
word_count: usize,
}
// SAFETY: Metal permits command buffers to move between threads with exclusive
// access. The table mutex and waiting flag keep sweeps off a command during its
// wait. Readback uses private shared storage after GPU completion. Retained
// textures and input buffers are only kept alive by the table.
unsafe impl Send for InFlightResources {}
impl SubmissionEntry {
fn retire(&mut self, status: MTLCommandBufferStatus) {
if !is_terminal(status) {
return;
}
let Some(resources) = self.resources.take() else {
return;
};
if let Err(error) = check_command_status(&resources.command, status) {
self.result = Err(error);
return;
}
if let Ok(profile) = &mut self.result {
profile.gpu_seconds = resources.command.GPUEndTime() - resources.command.GPUStartTime();
profile.host_seconds = self.host_start.elapsed().as_secs_f64();
let readback_start = Instant::now();
let byte_len = resources.word_count * size_of::<u32>();
// SAFETY: The initialized shared output is distinct from the host
// vector and the GPU has finished writing to it. Both ranges hold
// byte_len bytes and all u32 bit patterns are valid.
unsafe {
copy_nonoverlapping(
resources.output.contents().cast::<u8>().as_ptr(),
profile.output.as_mut_ptr().cast::<u8>(),
byte_len,
);
}
profile.readback_seconds = readback_start.elapsed().as_secs_f64();
}
}
}
impl Drop for NativeCompute {
fn drop(&mut self) {
// Tokens can be abandoned (or forgotten) while their work is pending.
// Open all remaining gates before draining the queue.
let table = self
.submissions
.get_mut()
.unwrap_or_else(PoisonError::into_inner);
for resources in table
.entries
.values()
.filter_map(|entry| entry.resources.as_ref())
{
if let Some(gate) = &resources.gate {
gate.setSignaledValue(1);
}
}
for (_, entry) in std::mem::take(&mut table.entries) {
if let Some(resources) = entry.resources {
resources.command.waitUntilCompleted();
if !is_terminal(resources.command.status()) {
// Preserve the resources if Metal unexpectedly returns before completion.
std::mem::forget(resources);
}
}
}
}
}
impl NativeCompute {
/// Open the default Apple GPU and create a retained-resource command queue.
/// Open the default Apple GPU and create a command queue.
///
/// # Errors
///
@@ -178,10 +344,47 @@ impl NativeCompute {
let queue = device
.newCommandQueue()
.ok_or_else(|| MetalError::new("newCommandQueue", "queue creation failed"))?;
Ok(Self { device, queue })
Ok(Self {
device,
queue,
submissions: Mutex::default(),
})
})
}
fn submissions(&self) -> MutexGuard<'_, SubmissionTable> {
self.submissions
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
fn retire_completed(&self) {
self.submissions().entries.retain(|_, entry| {
if !entry.waiting
&& let Some(resources) = &entry.resources
{
entry.retire(resources.command.status());
}
!entry.abandoned || entry.resources.is_some()
});
}
fn begin_submission(&self) -> Instant {
let host_start = Instant::now();
self.retire_completed();
host_start
}
#[doc(hidden)]
pub fn in_flight(&self) -> usize {
self.submissions().in_flight()
}
#[doc(hidden)]
pub fn tracked(&self) -> usize {
self.submissions().entries.len()
}
/// Report the selected device's registered name.
pub fn device_name(&self) -> String {
autoreleasepool(|_| self.device.name().to_string())
@@ -561,6 +764,122 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
self.run_profiled_words(source, entry, input, None)
}
/// Submit trusted MSL with read-only words at buffer 0 and output words at buffer 1.
///
/// The trusted-kernel requirements of [`Self::run_words`] apply.
/// Use [`Self::wait`] to collect the result.
///
/// # Errors
///
/// Returns an error for invalid input or source, compilation or dispatch
/// setup failure, or a full in-flight table.
pub fn submit_words(
&self,
source: &str,
entry: &str,
input: &[u32],
) -> Result<Submission<'_>, MetalError> {
autoreleasepool(|_| {
let host_start = self.begin_submission();
validate_words(source, entry, input)?;
self.submit_sized(
source,
entry,
ComputeInput::Words(input),
None,
None,
host_start,
)
})
}
#[doc(hidden)]
pub fn submit_words_gated(
&self,
source: &str,
entry: &str,
input: &[u32],
) -> Result<(Submission<'_>, SubmissionGate), MetalError> {
autoreleasepool(|_| {
let host_start = self.begin_submission();
validate_words(source, entry, input)?;
let event = self
.device
.newSharedEvent()
.ok_or_else(|| MetalError::new("newSharedEvent", "gate creation failed"))?;
let submission = self.submit_sized(
source,
entry,
ComputeInput::Words(input),
None,
Some(&event),
host_start,
)?;
Ok((submission, SubmissionGate { event }))
})
}
/// Wait for this context's submission and return its readback and timings.
///
/// # Errors
///
/// Returns an error for a token from another context, an unknown submission,
/// or a Metal completion failure.
pub fn wait(&self, submission: Submission<'_>) -> Result<RunProfile, MetalError> {
if !std::ptr::eq(self, submission.context) {
return Err(MetalError::new(
"submission",
"token belongs to another context",
));
}
autoreleasepool(|_| {
let id = submission.id;
std::mem::forget(submission);
let result = self.take_result(id);
self.retire_completed();
result
})
}
fn take_result(&self, id: u64) -> Result<RunProfile, MetalError> {
let unknown = || MetalError::new("submission", "unknown submission id");
let command = {
let mut table = self.submissions();
let entry = table.entries.get_mut(&id).ok_or_else(unknown)?;
entry.resources.as_ref().map(|resources| {
entry.waiting = true;
resources.command.clone()
})
};
let wait_seconds = command.map_or(0.0, |command| {
// Keep the table available to other submitters while Metal waits.
let start = Instant::now();
command.waitUntilCompleted();
start.elapsed().as_secs_f64()
});
let mut table = self.submissions();
let entry = table.entries.get_mut(&id).ok_or_else(unknown)?;
entry.waiting = false;
let host_seconds = if let Some(resources) = &entry.resources {
let status = resources.command.status();
if !is_terminal(status) {
entry.abandoned = true;
check_command_status(&resources.command, status)?;
}
entry.retire(status);
None
} else {
Some(entry.host_start.elapsed().as_secs_f64())
};
let mut profile = table.entries.remove(&id).ok_or_else(unknown)?.result?;
profile.wait_seconds = wait_seconds;
if let Some(host_seconds) = host_seconds {
profile.host_seconds = host_seconds;
}
Ok(profile)
}
/// Run trusted MSL with an explicit one-dimensional threadgroup width.
///
/// The grid still contains one invocation per input word. The requested width
@@ -608,13 +927,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
input: &[u32],
group_width: Option<usize>,
) -> Result<RunProfile, MetalError> {
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
return Err(MetalError::new(
"dispatch bounds",
format!("expected 1..={MAX_GRID_WORDS} words, got {}", input.len()),
));
}
validate_source(source, &[entry])?;
validate_words(source, entry, input)?;
autoreleasepool(|_| self.run_sized(source, entry, ComputeInput::Words(input), group_width))
}
@@ -636,7 +949,20 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
input: ComputeInput<'_>,
group_width: Option<usize>,
) -> Result<RunProfile, MetalError> {
let host_start = Instant::now();
let host_start = self.begin_submission();
self.wait(self.submit_sized(source, entry, input, group_width, None, host_start)?)
}
fn submit_sized(
&self,
source: &str,
entry: &str,
input: ComputeInput<'_>,
group_width: Option<usize>,
gate: Option<&ProtocolObject<dyn MTLSharedEvent>>,
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)?;
@@ -672,17 +998,29 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
"fixture exceeds device buffer limit",
));
}
let alloc_start = Instant::now();
let input_buffer = match input {
ComputeInput::Words(words) => Some(self.new_buffer(words)?),
ComputeInput::SampledTexture { coords, .. } => Some(self.new_buffer(coords)?),
ComputeInput::Texture(..) => None,
};
let mut words = vec![0xA5A5_A5A5; input.len()];
let words = vec![0xA5A5_A5A5; input.len()];
let output_buffer = self.new_buffer(&words)?;
let alloc_seconds = alloc_start.elapsed().as_secs_f64();
let mut table = self.submissions();
table.check_capacity()?;
let id = table.next_id;
table.next_id = id
.checked_add(1)
.ok_or_else(|| MetalError::new("submission", "submission ids exhausted"))?;
let encode_start = Instant::now();
let command = self
.queue
.commandBuffer()
.commandBufferWithUnretainedReferences()
.ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?;
if let Some(gate) = gate {
command.encodeWaitForEvent_value(gate.as_ref(), 1);
}
let encoder = command.computeCommandEncoder().ok_or_else(|| {
MetalError::new("computeCommandEncoder", "compute encoder creation failed")
})?;
@@ -710,27 +1048,49 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
}
encoder.dispatchThreads_threadsPerThreadgroup(size(input.len()), size(width));
encoder.endEncoding();
complete_command(&command)?;
let gpu_seconds = command.GPUEndTime() - command.GPUStartTime();
let host_seconds = host_start.elapsed().as_secs_f64();
// SAFETY: Metal copied the initialized words into distinct shared storage.
// The GPU finished before the CPU touches that storage. Both ranges are
// valid for byte_len bytes and don't overlap. A byte copy requires no
// additional alignment and all u32 bit patterns are valid.
unsafe {
copy_nonoverlapping(
output_buffer.contents().cast::<u8>().as_ptr(),
words.as_mut_ptr().cast::<u8>(),
byte_len,
);
}
Ok(RunProfile {
library_seconds,
pipeline_seconds,
gpu_seconds,
host_seconds,
output: words,
})
let encode_seconds = encode_start.elapsed().as_secs_f64();
let (texture, sampler) = match input {
ComputeInput::Texture(texture, _) => (Some(texture.retain()), None),
ComputeInput::SampledTexture {
texture, sampler, ..
} => (Some(texture.retain()), Some(sampler.retain())),
ComputeInput::Words(_) => (None, None),
};
let resources = InFlightResources {
command,
_pipeline: pipeline,
_input: input_buffer,
output: output_buffer,
_texture: texture,
_sampler: sampler,
gate: gate.map(Message::retain),
word_count: input.len(),
};
let commit_start = Instant::now();
resources.command.commit();
let commit_seconds = commit_start.elapsed().as_secs_f64();
table.entries.insert(
id,
SubmissionEntry {
resources: Some(resources),
result: Ok(RunProfile {
library_seconds,
pipeline_seconds,
gpu_seconds: 0.0,
host_seconds: 0.0,
alloc_seconds,
encode_seconds,
commit_seconds,
wait_seconds: 0.0,
readback_seconds: 0.0,
output: words,
}),
host_start,
abandoned: false,
waiting: false,
},
);
Ok(Submission { context: self, id })
}
fn compile_library(
@@ -790,6 +1150,16 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
}
}
fn validate_words(source: &str, entry: &str, input: &[u32]) -> Result<(), MetalError> {
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
return Err(MetalError::new(
"dispatch bounds",
format!("expected 1..={MAX_GRID_WORDS} words, got {}", input.len()),
));
}
validate_source(source, &[entry])
}
fn validate_source(source: &str, entries: &[&str]) -> Result<(), MetalError> {
if source.is_empty()
|| source.len() > MAX_SOURCE_BYTES
@@ -829,11 +1199,29 @@ fn find_function(
fn complete_command(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
command.commit();
command.waitUntilCompleted();
wait_command(command)
}
if command.status() != MTLCommandBufferStatus::Completed {
/// Block until a committed command buffer finishes and check its status.
fn wait_command(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
command.waitUntilCompleted();
check_command_status(command, command.status())
}
fn is_terminal(status: MTLCommandBufferStatus) -> bool {
matches!(
status,
MTLCommandBufferStatus::Completed | MTLCommandBufferStatus::Error
)
}
fn check_command_status(
command: &ProtocolObject<dyn MTLCommandBuffer>,
status: MTLCommandBufferStatus,
) -> Result<(), MetalError> {
if status != MTLCommandBufferStatus::Completed {
let error = command.error().map_or_else(
|| format!("unexpected command status {:?}", command.status()),
|| format!("unexpected command status {status:?}"),
|error| error.localizedDescription().to_string(),
);
return Err(MetalError::new("waitUntilCompleted", error));
+2 -1
View File
@@ -16,7 +16,8 @@ pub mod texture_pipeline;
pub use compute::{
BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare,
DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer, GuestBufferView,
IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile,
IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile, Submission,
SubmissionGate,
};
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
+104
View File
@@ -0,0 +1,104 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use super::{context, fixture, native};
const ENTRY: &str = "fixture";
const INPUT: [u32; 4] = [0, 1, 71, u32::MAX];
const LIMIT: usize = 16;
fn source() -> String {
fixture("output[id] = input[id] * 3u + 7u;")
}
fn expected(input: &[u32]) -> Vec<u32> {
input
.iter()
.map(|word| word.wrapping_mul(3).wrapping_add(7))
.collect()
}
#[test]
fn sweep_keeps_resources_until_completion() {
let metal = context();
let source = source();
let (a, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT));
assert_eq!(metal.in_flight(), 1);
let b = native(metal.submit_words(&source, ENTRY, &INPUT));
assert_eq!(metal.in_flight(), 2);
gate.open();
assert_eq!(native(metal.wait(a)).output, expected(&INPUT));
assert_eq!(native(metal.wait(b)).output, expected(&INPUT));
assert_eq!(metal.in_flight(), 0);
}
#[test]
fn batch_can_be_collected_in_either_order() {
let metal = context();
let source = source();
for reverse in [false, true] {
let mut batch = Vec::new();
for seed in 0..8 {
let input = INPUT.map(|word| word.wrapping_add(seed));
batch.push((input, native(metal.submit_words(&source, ENTRY, &input))));
}
if reverse {
batch.reverse();
}
for (input, submission) in batch {
let output = native(metal.wait(submission)).output;
assert_eq!(output, expected(&input));
assert_eq!(output, native(metal.run_words(&source, ENTRY, &input)));
}
assert_eq!(metal.tracked(), 0);
}
}
#[test]
fn full_queue_returns_in_flight_limit_error() {
let metal = context();
let source = source();
let (first, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT));
let mut tokens = vec![first];
for _ in 1..LIMIT {
tokens.push(native(metal.submit_words(&source, ENTRY, &INPUT)));
}
assert_eq!(metal.in_flight(), LIMIT);
let Err(error) = metal.submit_words(&source, ENTRY, &INPUT) else {
panic!("submission past the in-flight limit succeeded");
};
assert_eq!(error.operation, "in-flight limit");
gate.open();
for token in tokens {
assert_eq!(native(metal.wait(token)).output, expected(&INPUT));
}
assert_eq!(metal.in_flight(), 0);
}
#[test]
fn dropped_token_retires_after_completion() {
let metal = context();
let source = source();
let (a, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT));
drop(a);
let b = native(metal.submit_words(&source, ENTRY, &INPUT));
assert_eq!(metal.in_flight(), 2);
drop(gate);
assert_eq!(native(metal.wait(b)).output, expected(&INPUT));
assert_eq!(metal.in_flight(), 0);
assert_eq!(metal.tracked(), 0);
}
#[test]
fn finished_result_survives_later_submission() {
let metal = context();
let source = source();
let a = native(metal.submit_words(&source, ENTRY, &INPUT));
let b = native(metal.submit_words(&source, ENTRY, &[9]));
assert_eq!(native(metal.wait(b)).output, expected(&[9]));
assert_eq!(metal.in_flight(), 0);
assert_eq!(metal.tracked(), 1);
let profile = native(metal.wait(a));
assert_eq!(profile.output, expected(&INPUT));
assert_eq!(profile.wait_seconds, 0.0);
assert_eq!(metal.tracked(), 0);
}
+2
View File
@@ -16,6 +16,8 @@ mod indexed;
mod indexed_cases;
#[path = "native/offscreen.rs"]
mod offscreen;
#[path = "native/submission.rs"]
mod submission;
#[path = "native/texture.rs"]
mod texture;
#[path = "native/texture_bc_alpha.rs"]
+13 -1
View File
@@ -180,10 +180,22 @@ def read_declarations(registry, identified):
declared = set()
# An encoding variant declares its base form in another encoding family.
raw_variants = registry.get("encoding_variant", [])
if not isinstance(raw_variants, list) or not all(
isinstance(variant, dict)
and {"family", "of", "opcode", "operands"} <= set(variant)
and all(isinstance(variant[key], str) for key in ("family", "of", "operands"))
and type(variant["opcode"]) is int
for variant in raw_variants
):
raise ValueError(
f"{REGISTRY}: every encoding_variant needs string family, of and operands"
" and an integer opcode"
)
variants = [
{"family": variant["family"], "name": variant["of"], "opcode": variant["opcode"],
"operands": variant["operands"]}
for variant in registry.get("encoding_variant", [])
for variant in raw_variants
]
for form in registry["form"] + variants:
key = (form["family"], form["name"])
+19 -2
View File
@@ -112,7 +112,7 @@ def main(argv: list[str] | None = None) -> int:
r = sub.add_parser("rdna2", help="read-only RDNA2 expansion planning")
r.add_argument(
"action",
choices=("inventory", "candidates", "plan", "discrepancies", "diff", "manifests", "reconcile"),
choices=("inventory", "candidates", "plan", "discrepancies", "diff", "manifests", "reconcile", "rank"),
)
r.add_argument("--limit", type=int, default=0)
r.add_argument("--family", action="append", default=[], help="filter by encoding family")
@@ -127,6 +127,7 @@ def main(argv: list[str] | None = None) -> int:
r.add_argument("--out", default="", help="write full JSON under this path (prefer artifacts/)")
r.add_argument("--before", default="", help="JSON inventory for diff")
r.add_argument("--after", default="", help="JSON inventory for diff")
r.add_argument("--no-float", action="store_true", help="rank: exclude floating-point groups")
cpu = sub.add_parser("cpu-coverage", help="legacy heuristic CPU/runtime coverage scan")
cpu.add_argument("--blockers", action="store_true")
@@ -168,6 +169,17 @@ def main(argv: list[str] | None = None) -> int:
br.add_argument("--behind", type=int, required=True)
args = p.parse_args(argv)
if args.command == "rdna2" and args.action == "rank":
from .rdna2_rank import run_rank
try:
return run_rank(_root(), args)
except ValueError as exc:
# A malformed registry is a diagnostic, not a traceback.
print(f"rdna2: {exc}", file=sys.stderr)
return 2
if args.command == "rdna2" and args.no_float:
r.error("--no-float requires the rank action")
root = _root()
if args.command == "orchestrate":
@@ -256,7 +268,12 @@ def main(argv: list[str] | None = None) -> int:
else:
print(json.dumps(payload, indent=2, sort_keys=True))
return 0
data = load_inventories(root)
try:
data = load_inventories(root)
except ValueError as exc:
# A malformed registry is a diagnostic, not a traceback.
print(f"rdna2: {exc}", file=sys.stderr)
return 2
inv = summarize_inventory(data)
exclude_families: list[str] = []
claimed_paths: list[str] = []
+135
View File
@@ -0,0 +1,135 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Rank registry expansion by XML identity and operand shape."""
from __future__ import annotations
import json
import runpy
from argparse import Namespace
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Sequence
from . import rdna2_plan
# Relative planning weights, not measurements of implementation effort.
ENCODING_VARIANT_COST = 1
OPERAND_RULE_COST = 2
PRIMITIVE_COST = 4
FLOAT_FORMATS = {"FMT_NUM_F16", "FMT_NUM_F32", "FMT_NUM_F64"}
DIRECTIONS = {(False, False): "none", (True, False): "in",
(False, True): "out", (True, True): "inout"}
FormKey = tuple[str, str]
Operand = tuple[str, str, str, int, bool, bool, bool, bool]
Signature = tuple[tuple[str, str, int, str], ...]
@dataclass
class RankGroup:
key: str
kind: str
family: str
signature: Signature
cost: int
forms: list[dict[str, str | int]] = field(default_factory=list)
float: bool = False
blocked_by_claims: int = 0
def payload(self) -> dict[str, Any]:
count = len(self.forms)
return {**asdict(self), "count": count, "score": count / self.cost}
def load_xml_operands(root: Path, identified: dict[FormKey, int]) -> dict[FormKey, list[Operand]]:
# Use the same base-row selection as the planner, including literal-only
# forms and relative moves with non-default conditions.
metadata = runpy.run_path(str(root / "crates/isa/generate_rdna2_meta.py"))
snapshot = (root / "crates/isa/data/rdna2.jsonl").read_text(encoding="utf-8")
_, _, forms = metadata["forms_from_snapshot"](snapshot)
return {
key: form["operands"]
for form in forms
if (key := (form["encoding"].upper(), form["name"])) in identified
}
def rank_groups(
data: dict[str, Any],
operands: dict[FormKey, list[Operand]],
*,
families: Sequence[str] = (),
claims: Sequence[rdna2_plan.ClaimScope] = (),
no_float: bool = False,
limit: int | None = None,
) -> list[dict[str, Any]]:
identified = data["identified"]
declared = set(data["declared"]) | {
(variant["family"], variant["of"])
for variant in data["registry"].get("encoding_variant", [])
}
signatures = {
key: tuple((field, kind, size, DIRECTIONS[is_input, is_output])
for field, _, kind, size, is_input, is_output, _, _ in rows)
for key, rows in operands.items()
}
formats = {
key: tuple((row[1], row[3]) for row in rows)
for key, rows in operands.items()
}
# The planner validates each form's rule. Its XML signature supplies the
# kinds, widths and directions that the registry's rule alone lacks.
declared_names = {name for _, name in declared}
rule_shapes = {(key[0], signatures[key]) for key in declared if key in identified}
declared_formats = {formats[key] for key in declared if key in identified}
selected = {family.upper() for family in families}
claimed_families = {family for scope in claims for family in scope.families}
claimed_paths = {path for scope in claims if not scope.families for path in scope.paths}
groups: dict[str, RankGroup] = {}
for family, name in sorted(identified.keys() - declared):
if selected and family not in selected:
continue
form = (family, name)
signature = signatures[form]
if name in declared_names:
kind, cost = "encoding-variant", ENCODING_VARIANT_COST
elif (family, signature) not in rule_shapes and formats[form] in declared_formats:
kind, cost = "operand-rule", OPERAND_RULE_COST
else:
kind, cost = "primitive", PRIMITIVE_COST
shape = ",".join(f"{field}/{kind}/{size}/{direction}" for field, kind, size, direction in signature)
key = f"{kind}:{family}:{shape}"
if key not in groups:
groups[key] = RankGroup(key, kind, family, signature, cost)
group = groups[key]
group.float |= any(fmt in FLOAT_FORMATS for fmt, _ in formats[form])
opcode = identified[form]
candidate = rdna2_plan.Candidate(family, name, opcode, None, None, None)
if family in claimed_families or rdna2_plan.claims_block_candidate(candidate, claimed_paths):
group.blocked_by_claims += 1
else:
group.forms.append({"name": name, "opcode": opcode})
ranked = [group.payload() for group in groups.values()
if group.forms and not (no_float and group.float)]
ranked.sort(key=lambda group: (-group["score"], -group["count"], group["key"]))
return ranked[:limit]
def run_rank(root: Path, args: Namespace) -> int:
data = rdna2_plan.load_inventories(root)
operands = load_xml_operands(root, data["identified"])
claims = rdna2_plan.load_claim_scopes(Path(args.claims)) if args.claims else []
groups = rank_groups(data, operands, families=args.family, claims=claims,
no_float=args.no_float, limit=args.limit or None)
if args.out:
rdna2_plan.write_json(Path(args.out), groups)
if args.compact or args.out:
for group in groups:
print(f"{group['key']} count={group['count']} cost={group['cost']} "
f"score={group['score']:g} float={str(group['float']).lower()} "
f"blocked_by_claims={group['blocked_by_claims']}")
else:
print(json.dumps(groups, indent=2, sort_keys=True))
return 0
+49
View File
@@ -0,0 +1,49 @@
"""A malformed encoding variant gives the planner a diagnostic, not a traceback."""
import contextlib
import io
import unittest
from unittest import mock
import qa.__main__ as cli
from qa import rdna2_plan
from audit import semantic_coverage as coverage
def malformed_loader(variant):
def load(_root):
registry = {
"schema": 1,
"form": [{"family": "SOP2", "name": "S_ADD_U32", "opcode": 0,
"operands": "scalar", "verify": ["reference"]}],
"operand_rules": {"scalar": {"family": "SOP2", "unsupported": ["two_literals"]}},
"encoding_variant": [variant],
}
# The real reader, as load_inventories uses it.
coverage.read_declarations(registry, {("SOP2", "S_ADD_U32"): 0})
raise AssertionError("the malformed variant was accepted")
return load
class MalformedVariant(unittest.TestCase):
def test_inventory_and_rank_report_registry_errors(self):
variants = {
"missing of": {"family": "VOP3", "opcode": 1, "operands": "x"},
"list operands": {"family": "VOP3", "of": "S_ADD_U32", "opcode": 1, "operands": []},
}
for action in ("inventory", "rank"):
for name, variant in variants.items():
with self.subTest(action=action, variant=name):
stderr = io.StringIO()
loader = malformed_loader(variant)
with mock.patch.object(cli, "load_inventories", loader), \
mock.patch.object(rdna2_plan, "load_inventories", loader), \
contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(io.StringIO()):
code = cli.main(["rdna2", action])
self.assertEqual(code, 2)
self.assertIn("encoding_variant needs", stderr.getvalue())
if __name__ == "__main__":
unittest.main()
+111
View File
@@ -0,0 +1,111 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import io
import json
import tempfile
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import patch
from qa.__main__ import main
from qa.rdna2_plan import load_claim_scopes
from qa.rdna2_rank import rank_groups
def operand(field, kind, fmt="FMT_NUM_U32", *, output=False):
return (field, fmt, kind, 32, not output, output, False, True)
class Rdna2Rank(unittest.TestCase):
def setUp(self):
self.base = ("VOP2", "SYNTHETIC_ADD")
self.variant = ("VOP3", "SYNTHETIC_ADD")
self.rule = ("SOP2", "SYNTHETIC_OTHER")
self.primitive = ("VOP2", "SYNTHETIC_NEW")
self.floating = ("VOP2", "SYNTHETIC_FLOAT")
self.data = {
"identified": {self.primitive: 5, self.variant: 17, self.base: 2,
self.floating: 4, self.rule: 11},
"declared": {self.base},
"registry": {},
}
dst = operand("VDST", "OPR_VGPR", output=True)
src = operand("SRC0", "OPR_SRC")
self.operands = {
self.base: [dst, src],
self.variant: [dst, operand("SRC0", "OPR_SRC_NOLDS")],
self.rule: [operand("SDST", "OPR_SGPR", output=True), src],
self.primitive: [dst, src],
self.floating: [dst, operand("SRC0", "OPR_SRC", "FMT_NUM_F32")],
}
def test_kinds_and_costs_determine_ranking(self):
groups = rank_groups(self.data, self.operands)
self.assertEqual(
[(group["kind"], group["cost"], group["score"]) for group in groups],
[("encoding-variant", 1, 1.0), ("primitive", 4, 0.5), ("operand-rule", 2, 0.5)],
)
self.assertEqual(groups[0]["family"], "VOP3")
self.assertEqual(groups[0]["forms"], [{"name": "SYNTHETIC_ADD", "opcode": 17}])
self.assertEqual(groups[0]["signature"], (
("VDST", "OPR_VGPR", 32, "out"), ("SRC0", "OPR_SRC_NOLDS", 32, "in"),
))
def test_declared_variant_is_not_ranked_and_supplies_a_rule_shape(self):
self.data["registry"]["encoding_variant"] = [
{"of": self.base[1], "family": "VOP3", "opcode": 17, "operands": "synthetic_rule"},
]
other = ("VOP3", "SYNTHETIC_OTHER")
self.data["identified"][other] = 18
self.operands[other] = self.operands[self.variant]
groups = rank_groups(self.data, self.operands, families=["vop3"])
self.assertEqual(len(groups), 1)
self.assertEqual(groups[0]["kind"], "primitive")
self.assertEqual(groups[0]["forms"], [{"name": other[1], "opcode": 18}])
def test_claim_file_family_and_path_scopes(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "claims.json"
path.write_text(json.dumps({"claims": [
{"families": ["vop3"], "paths": ["crates/isa/**"]},
{"paths": ["unrelated/**"]},
]}), encoding="utf-8")
remaining = rank_groups(self.data, self.operands, claims=load_claim_scopes(path))
self.assertEqual([group["family"] for group in remaining], ["VOP2", "SOP2"])
path.write_text(json.dumps([{"paths": ["crates/isa/**"]}]), encoding="utf-8")
self.assertEqual(rank_groups(self.data, self.operands, claims=load_claim_scopes(path)), [])
def test_partially_blocked_group_reports_dropped_form(self):
with patch("qa.rdna2_plan.claims_block_candidate", side_effect=lambda cand, _: cand.name == self.primitive[1]):
groups = rank_groups(self.data, self.operands, families=["VOP2"])
self.assertEqual(groups[0]["blocked_by_claims"], 1)
self.assertEqual(groups[0]["count"], 1)
self.assertEqual(groups[0]["score"], 0.25)
self.assertEqual(groups[0]["forms"], [{"name": self.floating[1], "opcode": 4}])
def test_float_marker_and_cli_filter(self):
def invoke(*flags):
stdout = io.StringIO()
with redirect_stdout(stdout):
self.assertEqual(main(["rdna2", "rank", *flags]), 0)
return stdout.getvalue()
with (
patch("qa.rdna2_plan.load_inventories", return_value=self.data),
patch("qa.rdna2_rank.load_xml_operands", return_value=self.operands),
):
groups = json.loads(invoke())
self.assertEqual([group["float"] for group in groups], [False, True, False])
self.assertEqual(json.loads(invoke("--no-float")), [groups[0], groups[2]])
self.assertEqual(json.loads(invoke("--family", "sop2", "--limit", "1")), [groups[2]])
self.assertEqual(len(invoke("--no-float", "--compact").splitlines()), 2)
def test_deterministic_with_reordered_inventory_and_equal_scores(self):
additional_rule = ("SOP1", "SYNTHETIC_OTHER")
self.data["identified"][additional_rule] = 1
self.operands[additional_rule] = self.operands[self.rule]
first = rank_groups(self.data, self.operands)
reordered = {**self.data, "identified": dict(reversed(list(self.data["identified"].items())))}
second = rank_groups(reordered, dict(reversed(list(self.operands.items()))))
self.assertEqual(first, second)
self.assertEqual([group["family"] for group in first], ["VOP3", "VOP2", "SOP1", "SOP2"])
@@ -68,6 +68,11 @@ class SemanticCoverageTests(unittest.TestCase):
# S_ADD_U32 is declared in the registry but absent from the compiled tables.
self.assertEqual(self.counts()["Decoder-supported"], 1)
def test_a_variant_without_its_form_is_an_error_not_a_traceback(self):
self.registry["encoding_variant"] = [{"family": "VOP3", "opcode": 1, "operands": "x"}]
with self.assertRaisesRegex(ValueError, "every encoding_variant needs"):
coverage.read_declarations(self.registry, self.identified)
def test_generated_table_parser(self):
source = (
"pub const FORM_IDS: [(&str, EncodingFamily); 1] = [\n"
@@ -937,6 +937,31 @@ class Validate(unittest.TestCase):
reg["encoding_variant"][0][key] = []
self.rejects(reg, f"[{key!r}] must be strings")
def test_a_variant_of_an_incomplete_form_reports_the_form_not_a_traceback(self):
reg = variants()
base = next(f for f in reg["form"] if f["name"] == reg["encoding_variant"][0]["of"])
del base["width"]
errors = self.errors(reg)
self.assertTrue(any("missing ['width']" in error for error in errors), errors)
self.assertTrue(any("is incomplete" in error for error in errors), errors)
def test_a_variant_of_an_incomplete_first_duplicate_is_a_diagnostic(self):
reg = variants()
base = next(f for f in reg["form"] if f["name"] == reg["encoding_variant"][0]["of"])
incomplete = copy.deepcopy(base)
del incomplete["width"]
reg["form"].insert(reg["form"].index(base), incomplete)
errors = self.errors(reg)
self.assertTrue(any("missing ['width']" in error for error in errors), errors)
def test_a_non_array_or_non_table_variant_is_a_diagnostic(self):
reg = variants()
reg["encoding_variant"] = 1
self.rejects(reg, "encoding_variant must be an array of tables")
reg = variants()
reg["encoding_variant"].append(1)
self.rejects(reg, "must be a table, got 1")
def test_renders_variant_dispatch_and_rows(self):
text = gen.render(variants(), snapshot())
self.assertIn("pub enum VectorAluVop3Op {", text)
@@ -1230,6 +1255,18 @@ class LoadRegistry(unittest.TestCase):
gen.load_registry(root)
self.assertIn(fragment, str(raised.exception))
def test_a_standalone_registry_needs_no_family_directory(self):
(self.dir / "rdna2").rmdir()
root = self.write('[[form]]\nname = "S_ADD_U32"\nfamily = "SOP2"\n', {})
self.assertEqual(gen.load_registry(root)["form"][0]["name"], "S_ADD_U32")
root.write_text("schema = 1\ninclude = []\n", encoding="utf-8")
self.assertEqual(gen.load_registry(root)["form"], [])
def test_a_malformed_variant_list_is_a_registry_error(self):
self.fails(self.write("encoding_variant = 1\n", {}), "encoding_variant must be an array")
root = self.write('include = ["rdna2/vop3.toml"]\n', {"vop3.toml": "encoding_variant = 1\n"})
self.fails(root, "vop3.toml: encoding_variant must be an array")
def test_the_real_split_registry_equals_one_concatenated_file(self):
registry = gen.load_registry()
self.assertNotIn("include", registry)
@@ -1240,6 +1277,23 @@ class LoadRegistry(unittest.TestCase):
declared = set(runs) | {variant["family"] for variant in registry.get("encoding_variant", [])}
for name, rule in registry["operand_rules"].items():
self.assertIn(rule["family"], declared, name)
# The whole merged result equals the files concatenated by hand: every
# form, rule and variant, in order, with nothing dropped or reordered.
import tomllib
with open(gen.REGISTRY, "rb") as handle:
expected = tomllib.load(handle)
includes = expected.pop("include")
expected.setdefault("operand_rules", {})
expected.setdefault("form", [])
for include in includes:
with open(gen.REGISTRY.parent / include, "rb") as handle:
part = tomllib.load(handle)
expected["operand_rules"].update(part.get("operand_rules", {}))
expected["form"] += part.get("form", [])
if "encoding_variant" in part:
expected.setdefault("encoding_variant", []).extend(part["encoding_variant"])
self.assertEqual(registry, expected)
def test_merges_family_files_in_include_order(self):
root = self.write('include = ["rdna2/vop2.toml", "rdna2/sop2.toml"]\n', {