mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 11:40:43 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86c048d191 | ||
|
|
0cac6c4fcf | ||
|
|
b69d4b97c6 | ||
|
|
97598903e2 | ||
|
|
af68f7da74 | ||
|
|
6d7523f5d1 | ||
|
|
59ee786a12 | ||
|
|
54506125d4 | ||
|
|
62c933051b |
No files matched your search
@@ -37,6 +37,7 @@ jobs:
|
||||
rustc -vV
|
||||
- name: Check generated status and PE fixtures
|
||||
run: |
|
||||
python3 crates/isa/generate_rdna2_meta.py --check
|
||||
python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
|
||||
@@ -11,7 +11,15 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added `scripts/compare-benchmarks.py` (with built-in `--self-test` unit tests) and documented it in `docs/testing/benchmarks.md`: compares structured benchmark run directories only when revision-independent configuration matches (`device`, `host_arch`, OS/toolchain versions, build profile, Metal validation flags, power source, thermal state, `reps`, and `warmup`), reports medians, IQR/span dispersion, missing or excluded entries, and factual uncertainty signals without an arbitrary pass/fail threshold.
|
||||
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
|
||||
- Added native Metal upload and readback of BC2 and BC3 textures: `xenora-texture` gains a
|
||||
pitched `BcAlphaUpload` for 16-byte blocks, and `NativeCompute::read_bc_alpha_upload` sends
|
||||
the original blocks to `BC2_RGBA` or `BC3_RGBA` textures when the device reports BC support.
|
||||
GPU tests cover explicit and interpolated (six- and eight-value) alpha, both colour endpoint
|
||||
orders, padded row and slice pitches, two layers and two mips against the CPU decoders and
|
||||
hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within
|
||||
1.14 codes of the exact values, so up to two codes from the truncating CPU reference.
|
||||
- Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet.
|
||||
- Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution
|
||||
test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and
|
||||
|
||||
Generated
+2
@@ -153,7 +153,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
name = "xenora"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-decoder",
|
||||
"xenora-import-gen",
|
||||
"xenora-isa",
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-ref",
|
||||
|
||||
@@ -9,6 +9,8 @@ rust-version.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
xenora-decoder = { path = "../decoder" }
|
||||
xenora-isa = { path = "../isa" }
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-ref = { path = "../ref" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod demo;
|
||||
mod runner;
|
||||
mod shaders;
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
@@ -40,6 +41,7 @@ fn main() -> ExitCode {
|
||||
},
|
||||
Some("run") => runner::command(std::env::args_os().skip(2)),
|
||||
Some("imports") => imports_command(std::env::args().skip(2).collect()),
|
||||
Some("shaders") => shaders::command(&std::env::args().skip(2).collect::<Vec<_>>()),
|
||||
Some("probe") => {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut pe_path: Option<String> = None;
|
||||
@@ -132,7 +134,7 @@ fn main() -> ExitCode {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports>");
|
||||
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports|shaders>");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! `xenora shaders`: instruction inventory and stream inspection.
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
|
||||
use xenora_isa::meta::{self, EncodingFamily, FORMS, identify};
|
||||
|
||||
const USAGE: &str = "usage: xenora shaders <coverage [--json] | inspect <gfx1030.bin>>";
|
||||
|
||||
pub fn command(args: &[String]) -> ExitCode {
|
||||
match args.first().map(String::as_str) {
|
||||
Some("coverage") => coverage(args.get(1).map(String::as_str) == Some("--json")),
|
||||
Some("inspect") => match args.get(1) {
|
||||
Some(path) => inspect(path),
|
||||
None => usage(),
|
||||
},
|
||||
_ => usage(),
|
||||
}
|
||||
}
|
||||
|
||||
fn usage() -> ExitCode {
|
||||
eprintln!("{USAGE}");
|
||||
ExitCode::from(2)
|
||||
}
|
||||
|
||||
fn semantic(family: EncodingFamily) -> usize {
|
||||
SEMANTIC_FORMS
|
||||
.iter()
|
||||
.filter(|(_, form_family)| *form_family == family)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Per-family counts. "Discovered" forms come from AMD's XML and are identified
|
||||
/// with their length; "semantic" forms decode into executable instructions.
|
||||
/// Reference, Metal and native GPU evidence per form stays in docs/status.toml.
|
||||
fn coverage(json: bool) -> ExitCode {
|
||||
let rows: Vec<_> = meta::inventory()
|
||||
.into_iter()
|
||||
.map(|(family, discovered)| (family, discovered, semantic(family)))
|
||||
.collect();
|
||||
let total: usize = rows.iter().map(|row| row.1).sum();
|
||||
let supported: usize = rows.iter().map(|row| row.2).sum();
|
||||
if json {
|
||||
let families: Vec<String> = rows
|
||||
.iter()
|
||||
.map(|(family, discovered, semantic)| {
|
||||
format!(
|
||||
"{{\"family\":\"{}\",\"discovered\":{discovered},\"semantic\":{semantic}}}",
|
||||
family.name()
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
println!(
|
||||
"{{\"architecture\":\"gfx1030\",\"source_sha256\":\"{}\",\"discovered\":{total},\"semantic\":{supported},\"families\":[{}]}}",
|
||||
meta::SOURCE_SHA256,
|
||||
families.join(",")
|
||||
);
|
||||
} else {
|
||||
println!("{:<10} {:>10} {:>9}", "family", "discovered", "semantic");
|
||||
for (family, discovered, semantic) in &rows {
|
||||
println!("{:<10} {discovered:>10} {semantic:>9}", family.name());
|
||||
}
|
||||
println!("{:<10} {total:>10} {supported:>9}", "total");
|
||||
println!("Semantic forms decode for the operand subsets in docs/status.toml only.");
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn inspect(path: &str) -> ExitCode {
|
||||
let bytes = match std::fs::read(path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => {
|
||||
eprintln!("{path}: {error}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let mut offset = 0;
|
||||
let mut unsupported = 0;
|
||||
let mut count = 0;
|
||||
while offset < bytes.len() {
|
||||
let found = match identify(&bytes[offset..]) {
|
||||
Ok(found) => found,
|
||||
Err(error) => {
|
||||
println!("{offset:#06x} decode failure: {error}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let words: Vec<String> = bytes[offset..offset + found.len]
|
||||
.chunks(4)
|
||||
.map(|chunk| format!("{:08x}", u32::from_le_bytes(chunk.try_into().unwrap())))
|
||||
.collect();
|
||||
let status = match decode(Architecture::Gfx1030, &bytes[offset..offset + found.len]) {
|
||||
Ok(_) => "semantic".to_owned(),
|
||||
Err(error) if SEMANTIC_FORMS.contains(&(found.form.name, found.form.family)) => {
|
||||
format!("unsupported operands: {error}")
|
||||
}
|
||||
Err(_) => "unsupported instruction semantics".to_owned(),
|
||||
};
|
||||
if status != "semantic" {
|
||||
unsupported += 1;
|
||||
}
|
||||
println!(
|
||||
"{offset:#06x} {:<8} {:<28} {:<26} {status}",
|
||||
found.form.family.name(),
|
||||
found.form.name.to_ascii_lowercase(),
|
||||
words.join(" ")
|
||||
);
|
||||
offset += found.len;
|
||||
count += 1;
|
||||
}
|
||||
println!(
|
||||
"{count} instructions inspected against {} gfx1030 forms; {unsupported} not executable",
|
||||
FORMS.len()
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -12,6 +12,39 @@ use xenora_isa::{
|
||||
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination. Operand restrictions are listed in docs/status.toml;
|
||||
/// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported.
|
||||
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 25] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
|
||||
("S_BRANCH", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_CMP_EQ_U32", EncodingFamily::Sopc),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
|
||||
("V_ADD_F32", EncodingFamily::Vop2),
|
||||
("V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
("V_AND_B32", EncodingFamily::Vop2),
|
||||
("V_ASHRREV_I32", EncodingFamily::Vop2),
|
||||
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
|
||||
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
|
||||
("V_LSHLREV_B32", EncodingFamily::Vop2),
|
||||
("V_LSHRREV_B32", EncodingFamily::Vop2),
|
||||
("V_MOV_B32", EncodingFamily::Vop1),
|
||||
("V_MUL_F32", EncodingFamily::Vop2),
|
||||
("V_OR_B32", EncodingFamily::Vop2),
|
||||
("V_XOR_B32", EncodingFamily::Vop2),
|
||||
];
|
||||
|
||||
/// A successfully decoded instruction and its location in the input stream.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct DecodedInstruction {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Ties the decoder's declared semantic forms to what it decodes from LLVM-assembled fixtures.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
|
||||
use xenora_isa::meta::{FORMS, identify};
|
||||
|
||||
#[test]
|
||||
fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
|
||||
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
|
||||
let mut decoded = BTreeSet::new();
|
||||
for entry in fs::read_dir(directory).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_none_or(|extension| extension != "bin") {
|
||||
continue;
|
||||
}
|
||||
let binary = fs::read(&path).unwrap();
|
||||
for instruction in decode(Architecture::Gfx1030, &binary).unwrap() {
|
||||
let found = identify(&binary[instruction.offset..]).unwrap();
|
||||
assert_eq!(
|
||||
found.len,
|
||||
usize::from(instruction.byte_len),
|
||||
"{}",
|
||||
path.display()
|
||||
);
|
||||
decoded.insert((found.form.name, found.form.family));
|
||||
}
|
||||
}
|
||||
let declared: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
|
||||
assert!(
|
||||
decoded.is_subset(&declared),
|
||||
"{:?}",
|
||||
decoded.difference(&declared)
|
||||
);
|
||||
// Covered by inline words in tests/gfx1030.rs rather than fixture binaries.
|
||||
let inline_only: BTreeSet<_> = declared
|
||||
.difference(&decoded)
|
||||
.map(|(name, _)| *name)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
inline_only,
|
||||
BTreeSet::from(["IMAGE_SAMPLE_LZ", "S_CBRANCH_EXECZ", "S_CBRANCH_VCCZ"])
|
||||
);
|
||||
for (name, family) in SEMANTIC_FORMS {
|
||||
assert!(
|
||||
FORMS
|
||||
.iter()
|
||||
.any(|form| form.name == name && form.family == family),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,426 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate the complete gfx1030 instruction metadata table.
|
||||
|
||||
Two stages keep regeneration offline and checkable without the 11 MB AMD XML:
|
||||
|
||||
snapshot AMD RDNA 2 XML -> crates/isa/data/rdna2.jsonl (normalised, sorted)
|
||||
rust crates/isa/data/rdna2.jsonl -> crates/isa/src/rdna2_meta.rs
|
||||
|
||||
`--check` regenerates in memory and fails when a committed file differs.
|
||||
Only the Python standard library is used. See docs/research/rdna2.md.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from xml.etree import ElementTree
|
||||
|
||||
SOURCE_SHA256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
|
||||
ARCHITECTURE = "AMD RDNA 2"
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
|
||||
RUST = ROOT / "crates/isa/src/rdna2_meta.rs"
|
||||
SCHEMA = 1
|
||||
|
||||
# Encodings whose default condition defines an instruction's base form. The
|
||||
# remaining XML encodings are literal, SDWA, DPP or NSA extensions of these.
|
||||
BASE_ENCODINGS = {
|
||||
"ENC_SOP1": "Sop1",
|
||||
"ENC_SOP2": "Sop2",
|
||||
"ENC_SOPC": "Sopc",
|
||||
"ENC_SOPK": "Sopk",
|
||||
"ENC_SOPP": "Sopp",
|
||||
"ENC_SMEM": "Smem",
|
||||
"ENC_VOP1": "Vop1",
|
||||
"ENC_VOP2": "Vop2",
|
||||
"ENC_VOPC": "Vopc",
|
||||
"ENC_VOP3": "Vop3",
|
||||
"VOP3_SDST_ENC": "Vop3Sdst",
|
||||
"ENC_VOP3P": "Vop3p",
|
||||
"ENC_VINTRP": "Vintrp",
|
||||
"ENC_DS": "Ds",
|
||||
"ENC_MUBUF": "Mubuf",
|
||||
"ENC_MTBUF": "Mtbuf",
|
||||
"ENC_MIMG": "Mimg",
|
||||
"ENC_EXP": "Exp",
|
||||
"ENC_FLAT": "Flat",
|
||||
"ENC_FLAT_GLBL": "Global",
|
||||
"ENC_FLAT_SCRATCH": "Scratch",
|
||||
}
|
||||
|
||||
# Extension encoding -> (base encoding, extension kind). The XML names the
|
||||
# variant and its operands but gives no expression for when it applies; the
|
||||
# decoder implements those rules by hand (docs/research/rdna2.md).
|
||||
EXTENSIONS = {
|
||||
"SOP1_INST_LITERAL": ("ENC_SOP1", "literal"),
|
||||
"SOP2_INST_LITERAL": ("ENC_SOP2", "literal"),
|
||||
"SOPC_INST_LITERAL": ("ENC_SOPC", "literal"),
|
||||
"SOPK_INST_LITERAL": ("ENC_SOPK", "literal"),
|
||||
"VOP1_INST_LITERAL": ("ENC_VOP1", "literal"),
|
||||
"VOP2_INST_LITERAL": ("ENC_VOP2", "literal"),
|
||||
"VOPC_INST_LITERAL": ("ENC_VOPC", "literal"),
|
||||
"VOP3_INST_LITERAL": ("ENC_VOP3", "literal"),
|
||||
"VOP3_SDST_ENC_INST_LITERAL": ("VOP3_SDST_ENC", "literal"),
|
||||
"VOP3P_INST_LITERAL": ("ENC_VOP3P", "literal"),
|
||||
"VOP1_VOP_SDWA": ("ENC_VOP1", "sdwa"),
|
||||
"VOP2_VOP_SDWA": ("ENC_VOP2", "sdwa"),
|
||||
"VOP2_VOP_SDWA_SDST_ENC": ("ENC_VOP2", "sdwa"),
|
||||
"VOPC_VOP_SDWA_SDST_ENC": ("ENC_VOPC", "sdwa"),
|
||||
"VOP1_VOP_DPP8": ("ENC_VOP1", "dpp8"),
|
||||
"VOP2_VOP_DPP8": ("ENC_VOP2", "dpp8"),
|
||||
"VOP1_VOP_DPP16": ("ENC_VOP1", "dpp16"),
|
||||
"VOP2_VOP_DPP16": ("ENC_VOP2", "dpp16"),
|
||||
"MIMG_NSA1": ("ENC_MIMG", "nsa"),
|
||||
"MIMG_NSA2": ("ENC_MIMG", "nsa"),
|
||||
"MIMG_NSA3": ("ENC_MIMG", "nsa"),
|
||||
}
|
||||
|
||||
FLAGS = ("IsBranch", "IsConditionalBranch", "IsIndirectBranch", "IsProgramTerminator", "IsImmediatelyExecuted")
|
||||
|
||||
|
||||
def fail(message):
|
||||
raise SystemExit(f"generate_rdna2_meta: {message}")
|
||||
|
||||
|
||||
def text(element, path):
|
||||
value = element.findtext(path)
|
||||
if value is None:
|
||||
fail(f"missing <{path}>")
|
||||
return value.strip()
|
||||
|
||||
|
||||
def boolean(value):
|
||||
if value not in ("TRUE", "FALSE", "true", "false"):
|
||||
fail(f"unexpected boolean {value!r}")
|
||||
return value.lower() == "true"
|
||||
|
||||
|
||||
def snapshot_from_xml(data):
|
||||
if hashlib.sha256(data).hexdigest() != SOURCE_SHA256:
|
||||
fail("RDNA 2 XML does not match the approved input SHA-256")
|
||||
root = ElementTree.fromstring(data)
|
||||
document = root.find("Document")
|
||||
isa = root.find("ISA")
|
||||
if text(isa, "Architecture/ArchitectureName") != ARCHITECTURE:
|
||||
fail("XML is not the RDNA 2 architecture")
|
||||
records = [{
|
||||
"kind": "source",
|
||||
"schema": SCHEMA,
|
||||
"architecture": ARCHITECTURE,
|
||||
"sha256": SOURCE_SHA256,
|
||||
"release": text(document, "ReleaseDate"),
|
||||
"xml_schema": text(document, "SchemaVersion"),
|
||||
"license": text(document, "License"),
|
||||
"copyright": text(document, "Copyright"),
|
||||
}]
|
||||
|
||||
known = set(BASE_ENCODINGS) | set(EXTENSIONS)
|
||||
encodings = {}
|
||||
for encoding in isa.findall("Encodings/Encoding"):
|
||||
name = text(encoding, "EncodingName")
|
||||
if name not in known:
|
||||
fail(f"unclassified encoding {name}; add it to BASE_ENCODINGS or EXTENSIONS")
|
||||
bits = int(text(encoding, "BitCount"))
|
||||
mask = int(text(encoding, "EncodingIdentifierMask"), 2)
|
||||
identifiers = sorted(int(item.text, 2) for item in encoding.findall("EncodingIdentifiers/EncodingIdentifier"))
|
||||
if mask >> 32 or any(identifier >> 32 for identifier in identifiers):
|
||||
fail(f"{name} identifies instructions beyond the first dword")
|
||||
fields = []
|
||||
for field in encoding.findall("MicrocodeFormat/BitMap/Field"):
|
||||
ranges = sorted(field.findall("BitLayout/Range"), key=lambda item: int(item.attrib.get("Order", 0)))
|
||||
fields.append([
|
||||
text(field, "FieldName"),
|
||||
[[int(text(item, "BitOffset")), int(text(item, "BitCount"))] for item in ranges],
|
||||
])
|
||||
fields.sort(key=lambda item: (item[1][0][0], item[0]))
|
||||
encodings[name] = {"mask": mask, "identifiers": set(identifiers)}
|
||||
records.append({
|
||||
"kind": "encoding",
|
||||
"name": name,
|
||||
"bits": bits,
|
||||
"identifier_mask": mask,
|
||||
"identifiers": identifiers,
|
||||
"conditions": sorted(text(item, "ConditionName") for item in encoding.findall("EncodingConditions/EncodingCondition")),
|
||||
"fields": fields,
|
||||
})
|
||||
missing = known - set(encodings)
|
||||
if missing:
|
||||
fail(f"encodings absent from the XML: {sorted(missing)}")
|
||||
|
||||
for operand_type in isa.findall("OperandTypes/OperandType"):
|
||||
values = sorted(
|
||||
[text(value, "Name"), int(text(value, "Value"))]
|
||||
for value in operand_type.findall("OperandPredefinedValues/PredefinedValue")
|
||||
)
|
||||
records.append({
|
||||
"kind": "operand_type",
|
||||
"name": text(operand_type, "OperandTypeName"),
|
||||
"partitioned": boolean(operand_type.attrib.get("IsPartitioned", "false")),
|
||||
"values": values,
|
||||
})
|
||||
|
||||
for data_format in isa.findall("DataFormats/DataFormat"):
|
||||
records.append({
|
||||
"kind": "data_format",
|
||||
"name": text(data_format, "DataFormatName"),
|
||||
"data_type": text(data_format, "DataType"),
|
||||
"bits": int(text(data_format, "BitCount")),
|
||||
"components": int(text(data_format, "ComponentCount")),
|
||||
})
|
||||
|
||||
seen = set()
|
||||
for instruction in isa.findall("Instructions/Instruction"):
|
||||
name = text(instruction, "InstructionName")
|
||||
flags = {flag: boolean(text(instruction, f"InstructionFlags/{flag}")) for flag in FLAGS}
|
||||
group = instruction.find("FunctionalGroup")
|
||||
for variant in instruction.findall("InstructionEncodings/InstructionEncoding"):
|
||||
encoding_name = text(variant, "EncodingName")
|
||||
condition = text(variant, "EncodingCondition")
|
||||
opcode = int(text(variant, "Opcode"))
|
||||
key = (name, encoding_name, condition)
|
||||
if key in seen:
|
||||
fail(f"duplicate variant {key}")
|
||||
seen.add(key)
|
||||
operands = []
|
||||
for operand in sorted(variant.findall("Operands/Operand"), key=lambda item: int(item.attrib["Order"])):
|
||||
operands.append([
|
||||
operand.findtext("FieldName") or "",
|
||||
operand.findtext("DataFormatName") or "",
|
||||
operand.findtext("OperandType") or "",
|
||||
int(operand.findtext("OperandSize") or 0),
|
||||
boolean(operand.attrib["Input"]),
|
||||
boolean(operand.attrib["Output"]),
|
||||
boolean(operand.attrib["IsImplicit"]),
|
||||
boolean(operand.attrib.get("IsBinaryMicrocodeRequired", "true")),
|
||||
])
|
||||
record = {
|
||||
"kind": "variant",
|
||||
"instruction": name,
|
||||
"encoding": encoding_name,
|
||||
"condition": condition,
|
||||
"opcode": opcode,
|
||||
}
|
||||
# Extension variants keep only what classifies them; their
|
||||
# operands repeat the base form with a literal, SDWA, DPP or NSA word.
|
||||
if encoding_name in BASE_ENCODINGS:
|
||||
record.update({
|
||||
"flags": sorted(flag for flag, value in flags.items() if value),
|
||||
"group": text(group, "Name"),
|
||||
"subgroups": sorted(item.text.strip() for item in group.findall("FunctionalSubgroups/Subgroup")),
|
||||
"operands": operands,
|
||||
})
|
||||
records.append(record)
|
||||
|
||||
order = {"source": 0, "encoding": 1, "operand_type": 2, "data_format": 3, "variant": 4}
|
||||
records.sort(key=lambda record: (
|
||||
order[record["kind"]],
|
||||
record.get("name", ""),
|
||||
record.get("encoding", ""),
|
||||
record.get("instruction", ""),
|
||||
record.get("condition", ""),
|
||||
))
|
||||
return "".join(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n" for record in records)
|
||||
|
||||
|
||||
def place(value, ranges):
|
||||
"""Places `value` into a field layout; returns (mask, bits) within the first two dwords."""
|
||||
mask = bits = 0
|
||||
for offset, count in ranges:
|
||||
if offset + count > 64:
|
||||
fail("opcode field extends beyond the second dword")
|
||||
low = (1 << count) - 1
|
||||
bits |= (value & low) << offset
|
||||
mask |= low << offset
|
||||
value >>= count
|
||||
if value:
|
||||
fail("opcode does not fit its field")
|
||||
return mask, bits
|
||||
|
||||
|
||||
def forms_from_snapshot(snapshot):
|
||||
records = [json.loads(line) for line in snapshot.splitlines()]
|
||||
source = records[0]
|
||||
if source.get("kind") != "source" or source.get("schema") != SCHEMA or source.get("sha256") != SOURCE_SHA256:
|
||||
fail("snapshot header does not match this generator")
|
||||
encodings = {record["name"]: record for record in records if record["kind"] == "encoding"}
|
||||
variants = [record for record in records if record["kind"] == "variant"]
|
||||
|
||||
extensions = {}
|
||||
for variant in variants:
|
||||
if variant["encoding"] in EXTENSIONS:
|
||||
base, kind = EXTENSIONS[variant["encoding"]]
|
||||
entry = extensions.setdefault((variant["instruction"], base), set())
|
||||
if kind == "literal" and variant["condition"] == "default":
|
||||
entry.add("always_literal")
|
||||
entry.add(kind)
|
||||
|
||||
forms = []
|
||||
for variant in variants:
|
||||
encoding_name = variant["encoding"]
|
||||
if encoding_name not in BASE_ENCODINGS:
|
||||
continue
|
||||
# Three VOP1/VOP3 relative moves name the excluded extensions instead of "default".
|
||||
if variant["condition"] != "default" and not variant["condition"].startswith("Nothas_"):
|
||||
fail(f"{variant['instruction']} has non-default base condition {variant['condition']}")
|
||||
encoding = encodings[encoding_name]
|
||||
fields = dict((name, ranges) for name, ranges in encoding["fields"])
|
||||
prefix_mask, _ = place(0, fields["ENCODING"])
|
||||
prefixes = {identifier & prefix_mask for identifier in encoding["identifiers"]}
|
||||
if len(prefixes) != 1:
|
||||
fail(f"{encoding_name} has an ambiguous encoding prefix")
|
||||
prefix = prefixes.pop()
|
||||
id_mask = encoding["identifier_mask"]
|
||||
opcode = variant["opcode"]
|
||||
if "OP" in fields:
|
||||
op_mask, op_bits = place(opcode, fields["OP"])
|
||||
elif opcode == 0:
|
||||
op_mask = op_bits = 0
|
||||
else:
|
||||
fail(f"{encoding_name} has no OP field for opcode {opcode}")
|
||||
# The identifier mask can add selector bits beyond ENCODING and OP,
|
||||
# such as the FLAT segment field. Take them from the listed identifier.
|
||||
# MTBUF keeps one opcode bit in the second dword, which the
|
||||
# first-dword identifiers cannot express; carry it separately.
|
||||
low = 0xFFFFFFFF
|
||||
candidates = sorted({
|
||||
identifier for identifier in encoding["identifiers"]
|
||||
if identifier & (prefix_mask | op_mask) & low == (prefix | op_bits) & low
|
||||
})
|
||||
if len(candidates) != 1:
|
||||
fail(f"{variant['instruction']} matches {len(candidates)} {encoding_name} identifiers")
|
||||
forms.append({
|
||||
"name": variant["instruction"],
|
||||
"encoding": BASE_ENCODINGS[encoding_name],
|
||||
"opcode": opcode,
|
||||
# Opcode bits outside the identifier mask (MIMG bit 0, MTBUF bit 53)
|
||||
# still select the instruction.
|
||||
"mask": id_mask | op_mask,
|
||||
"bits": (candidates[0] & id_mask) | op_bits,
|
||||
"bytes": encoding["bits"] // 8,
|
||||
"flags": variant["flags"],
|
||||
"group": variant["group"],
|
||||
"extensions": sorted(extensions.get((variant["instruction"], encoding_name), ())),
|
||||
"operands": variant["operands"],
|
||||
})
|
||||
|
||||
by_pattern = {}
|
||||
for form in forms:
|
||||
if form["bits"] & ~form["mask"]:
|
||||
fail(f"{form['name']} has identifying bits outside its mask")
|
||||
key = (form["mask"], form["bits"])
|
||||
if key in by_pattern:
|
||||
fail(f"{form['name']} and {by_pattern[key]['name']} share an encoding")
|
||||
by_pattern[key] = form
|
||||
for left in forms:
|
||||
for right in forms:
|
||||
if left is right or left["mask"] == right["mask"]:
|
||||
continue
|
||||
common = left["mask"] & right["mask"]
|
||||
if (left["bits"] ^ right["bits"]) & common == 0:
|
||||
fail(f"{left['name']} ({left['encoding']}) overlaps {right['name']} ({right['encoding']})")
|
||||
forms.sort(key=lambda form: (form["encoding"], form["opcode"]))
|
||||
return source, encodings, forms
|
||||
|
||||
|
||||
def rust_from_snapshot(snapshot):
|
||||
source, encodings, forms = forms_from_snapshot(snapshot)
|
||||
out = []
|
||||
emit = out.append
|
||||
emit("// Generated by crates/isa/generate_rdna2_meta.py from crates/isa/data/rdna2.jsonl. Do not edit.")
|
||||
emit(f"// Source: AMD RDNA 2 XML, {source['release']}, schema {source['xml_schema']}, SHA-256 {source['sha256']}.")
|
||||
emit(f"// {source['copyright']}")
|
||||
emit("// SPDX-License-Identifier: MIT")
|
||||
emit("")
|
||||
emit("use super::meta::{EncodingFamily, Extensions, FieldLayout, Form, FormFlags, OperandInfo};")
|
||||
emit("")
|
||||
emit(f'/// SHA-256 of the AMD XML the table was generated from.\npub const SOURCE_SHA256: &str = "{source["sha256"]}";')
|
||||
emit("")
|
||||
|
||||
operand_sets = {}
|
||||
for form in forms:
|
||||
operand_sets.setdefault(json.dumps(form["operands"]), len(operand_sets))
|
||||
emit("static OPERANDS: [&[OperandInfo]; %d] = [" % len(operand_sets))
|
||||
for operands_json in operand_sets:
|
||||
operands = json.loads(operands_json)
|
||||
items = ", ".join(
|
||||
"OperandInfo { field: %s, format: %s, kind: %s, bits: %d, input: %s, output: %s, implicit: %s, encoded: %s }"
|
||||
% (json.dumps(field), json.dumps(data_format), json.dumps(kind), size,
|
||||
str(i).lower(), str(o).lower(), str(implicit).lower(), str(encoded).lower())
|
||||
for field, data_format, kind, size, i, o, implicit, encoded in operands
|
||||
)
|
||||
emit(f" &[{items}],")
|
||||
emit("];")
|
||||
emit("")
|
||||
|
||||
families = sorted({form["encoding"] for form in forms})
|
||||
emit("/// Field layouts of each base encoding, as (bit offset, bit count) pieces from least significant.")
|
||||
emit("pub static FIELDS: [(EncodingFamily, &[FieldLayout]); %d] = [" % len(families))
|
||||
reverse = {value: key for key, value in BASE_ENCODINGS.items()}
|
||||
for family in families:
|
||||
fields = encodings[reverse[family]]["fields"]
|
||||
items = ", ".join(
|
||||
"FieldLayout { name: %s, pieces: &[%s] }" % (json.dumps(name), ", ".join(f"({o}, {c})" for o, c in ranges))
|
||||
for name, ranges in fields
|
||||
)
|
||||
emit(f" (EncodingFamily::{family}, &[{items}]),")
|
||||
emit("];")
|
||||
emit("")
|
||||
|
||||
flag_bits = {
|
||||
"IsBranch": 1,
|
||||
"IsConditionalBranch": 2,
|
||||
"IsIndirectBranch": 4,
|
||||
"IsProgramTerminator": 8,
|
||||
"IsImmediatelyExecuted": 16,
|
||||
}
|
||||
extension_bits = {"literal": 1, "always_literal": 2, "sdwa": 4, "dpp8": 8, "dpp16": 16, "nsa": 32}
|
||||
emit("/// Every gfx1030 base instruction form in the AMD XML, sorted by encoding family and opcode.")
|
||||
emit("pub static FORMS: [Form; %d] = [" % len(forms))
|
||||
for form in forms:
|
||||
flags = sum(flag_bits[flag] for flag in form["flags"])
|
||||
extensions = sum(extension_bits[item] for item in form["extensions"])
|
||||
emit(
|
||||
" Form { name: %s, family: EncodingFamily::%s, opcode: %d, mask: 0x%016x, bits: 0x%016x, bytes: %d, "
|
||||
"flags: FormFlags(0x%02x), extensions: Extensions(0x%02x), group: %s, operands: OPERANDS[%d] },"
|
||||
% (json.dumps(form["name"]), form["encoding"], form["opcode"], form["mask"], form["bits"], form["bytes"],
|
||||
flags, extensions, json.dumps(form["group"]), operand_sets[json.dumps(form["operands"])])
|
||||
)
|
||||
emit("];")
|
||||
return "\n".join(out) + "\n"
|
||||
|
||||
|
||||
def compare(path, expected):
|
||||
actual = path.read_text() if path.exists() else ""
|
||||
if actual != expected:
|
||||
print(f"{path.relative_to(ROOT)} is out of date; rerun crates/isa/generate_rdna2_meta.py", file=sys.stderr)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--xml", type=Path, help="approved amdgpu_isa_rdna2.xml; regenerates the snapshot too")
|
||||
parser.add_argument("--check", action="store_true", help="fail when committed outputs differ")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.xml:
|
||||
snapshot = snapshot_from_xml(args.xml.read_bytes())
|
||||
elif SNAPSHOT.exists():
|
||||
snapshot = SNAPSHOT.read_text()
|
||||
else:
|
||||
fail("no snapshot; pass --xml")
|
||||
rust = rust_from_snapshot(snapshot)
|
||||
if args.check:
|
||||
ok = compare(RUST, rust)
|
||||
if args.xml:
|
||||
ok = compare(SNAPSHOT, snapshot) and ok
|
||||
raise SystemExit(0 if ok else 1)
|
||||
SNAPSHOT.parent.mkdir(parents=True, exist_ok=True)
|
||||
SNAPSHOT.write_text(snapshot)
|
||||
RUST.write_text(rust)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub mod meta;
|
||||
mod rdna2;
|
||||
#[rustfmt::skip]
|
||||
mod rdna2_meta;
|
||||
pub use rdna2::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
//! Complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML.
|
||||
//!
|
||||
//! Identification here establishes an instruction's form and length only. It is
|
||||
//! not semantic support: [`crate::Instruction`] lists the forms Xenora executes.
|
||||
//! The XML names literal, SDWA, DPP and NSA variants without saying when they
|
||||
//! apply, so [`identify`] implements those length rules by hand from the RDNA 2
|
||||
//! ISA reference guide (see docs/research/rdna2.md).
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub use crate::rdna2_meta::{FIELDS, FORMS, SOURCE_SHA256};
|
||||
|
||||
/// AMD base encoding of an instruction form.
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum EncodingFamily {
|
||||
Ds,
|
||||
Exp,
|
||||
Flat,
|
||||
Global,
|
||||
Mimg,
|
||||
Mtbuf,
|
||||
Mubuf,
|
||||
Scratch,
|
||||
Smem,
|
||||
Sop1,
|
||||
Sop2,
|
||||
Sopc,
|
||||
Sopk,
|
||||
Sopp,
|
||||
Vintrp,
|
||||
Vop1,
|
||||
Vop2,
|
||||
Vop3,
|
||||
Vop3Sdst,
|
||||
Vop3p,
|
||||
Vopc,
|
||||
}
|
||||
|
||||
impl EncodingFamily {
|
||||
/// Every family, in table order.
|
||||
pub const ALL: [Self; 21] = [
|
||||
Self::Ds,
|
||||
Self::Exp,
|
||||
Self::Flat,
|
||||
Self::Global,
|
||||
Self::Mimg,
|
||||
Self::Mtbuf,
|
||||
Self::Mubuf,
|
||||
Self::Scratch,
|
||||
Self::Smem,
|
||||
Self::Sop1,
|
||||
Self::Sop2,
|
||||
Self::Sopc,
|
||||
Self::Sopk,
|
||||
Self::Sopp,
|
||||
Self::Vintrp,
|
||||
Self::Vop1,
|
||||
Self::Vop2,
|
||||
Self::Vop3,
|
||||
Self::Vop3Sdst,
|
||||
Self::Vop3p,
|
||||
Self::Vopc,
|
||||
];
|
||||
|
||||
/// Lower-case name used in reports.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Ds => "ds",
|
||||
Self::Exp => "exp",
|
||||
Self::Flat => "flat",
|
||||
Self::Global => "global",
|
||||
Self::Mimg => "mimg",
|
||||
Self::Mtbuf => "mtbuf",
|
||||
Self::Mubuf => "mubuf",
|
||||
Self::Scratch => "scratch",
|
||||
Self::Smem => "smem",
|
||||
Self::Sop1 => "sop1",
|
||||
Self::Sop2 => "sop2",
|
||||
Self::Sopc => "sopc",
|
||||
Self::Sopk => "sopk",
|
||||
Self::Sopp => "sopp",
|
||||
Self::Vintrp => "vintrp",
|
||||
Self::Vop1 => "vop1",
|
||||
Self::Vop2 => "vop2",
|
||||
Self::Vop3 => "vop3",
|
||||
Self::Vop3Sdst => "vop3-sdst",
|
||||
Self::Vop3p => "vop3p",
|
||||
Self::Vopc => "vopc",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Control-flow flags recorded by the XML.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FormFlags(pub u8);
|
||||
|
||||
impl FormFlags {
|
||||
#[allow(missing_docs)]
|
||||
pub const NONE: Self = Self(0);
|
||||
#[allow(missing_docs)]
|
||||
pub const BRANCH: Self = Self(1);
|
||||
#[allow(missing_docs)]
|
||||
pub const CONDITIONAL: Self = Self(2);
|
||||
#[allow(missing_docs)]
|
||||
pub const INDIRECT: Self = Self(4);
|
||||
#[allow(missing_docs)]
|
||||
pub const TERMINATOR: Self = Self(8);
|
||||
#[allow(missing_docs)]
|
||||
pub const IMMEDIATE: Self = Self(16);
|
||||
|
||||
/// Whether every flag in `other` is set.
|
||||
pub fn contains(self, other: Self) -> bool {
|
||||
self.0 & other.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension words an instruction form may carry.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Extensions(pub u8);
|
||||
|
||||
impl Extensions {
|
||||
#[allow(missing_docs)]
|
||||
pub const NONE: Self = Self(0);
|
||||
/// A source field may select a trailing 32-bit literal.
|
||||
pub const LITERAL: Self = Self(1);
|
||||
/// The form always carries a trailing 32-bit literal.
|
||||
pub const ALWAYS_LITERAL: Self = Self(2);
|
||||
#[allow(missing_docs)]
|
||||
pub const SDWA: Self = Self(4);
|
||||
#[allow(missing_docs)]
|
||||
pub const DPP8: Self = Self(8);
|
||||
#[allow(missing_docs)]
|
||||
pub const DPP16: Self = Self(16);
|
||||
/// MIMG non-sequential address dwords.
|
||||
pub const NSA: Self = Self(32);
|
||||
|
||||
/// Whether every extension in `other` is allowed.
|
||||
pub fn contains(self, other: Self) -> bool {
|
||||
self.0 & other.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
/// One encoded field: pieces of (bit offset, bit count), least significant piece first.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct FieldLayout {
|
||||
#[allow(missing_docs)]
|
||||
pub name: &'static str,
|
||||
#[allow(missing_docs)]
|
||||
pub pieces: &'static [(u8, u8)],
|
||||
}
|
||||
|
||||
impl FieldLayout {
|
||||
/// Extracts the field from the instruction's first two dwords.
|
||||
pub fn extract(&self, value: u64) -> u32 {
|
||||
let mut result = 0u64;
|
||||
let mut shift = 0;
|
||||
for &(offset, count) in self.pieces {
|
||||
result |= ((value >> offset) & ((1u64 << count) - 1)) << shift;
|
||||
shift += count;
|
||||
}
|
||||
result as u32
|
||||
}
|
||||
}
|
||||
|
||||
/// An operand as described by the XML.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct OperandInfo {
|
||||
pub field: &'static str,
|
||||
pub format: &'static str,
|
||||
pub kind: &'static str,
|
||||
pub bits: u16,
|
||||
pub input: bool,
|
||||
pub output: bool,
|
||||
pub implicit: bool,
|
||||
/// Whether the operand occupies microcode bits.
|
||||
pub encoded: bool,
|
||||
}
|
||||
|
||||
/// One instruction in one base encoding.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub struct Form {
|
||||
pub name: &'static str,
|
||||
pub family: EncodingFamily,
|
||||
pub opcode: u16,
|
||||
/// Identifying bits over the first two dwords (little-endian, first dword low).
|
||||
pub mask: u64,
|
||||
pub bits: u64,
|
||||
/// Base length before literal, SDWA, DPP or NSA words.
|
||||
pub bytes: u8,
|
||||
pub flags: FormFlags,
|
||||
pub extensions: Extensions,
|
||||
pub group: &'static str,
|
||||
pub operands: &'static [OperandInfo],
|
||||
}
|
||||
|
||||
impl Form {
|
||||
/// The base encoding's field layouts.
|
||||
pub fn fields(&self) -> &'static [FieldLayout] {
|
||||
FIELDS
|
||||
.iter()
|
||||
.find(|(family, _)| *family == self.family)
|
||||
.map(|(_, fields)| *fields)
|
||||
.unwrap_or(&[])
|
||||
}
|
||||
|
||||
/// The named field's layout, if the encoding has one.
|
||||
pub fn field(&self, name: &str) -> Option<&'static FieldLayout> {
|
||||
self.fields().iter().find(|field| field.name == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which extension words an identified instruction carries.
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub struct Trailer {
|
||||
/// A 32-bit literal follows the base encoding.
|
||||
pub literal: bool,
|
||||
/// SDWA, DPP8 or DPP16 control dword (VOP1, VOP2, VOPC only).
|
||||
pub vector_control: Option<VectorControl>,
|
||||
/// Extra MIMG address dwords.
|
||||
pub nsa_dwords: u8,
|
||||
}
|
||||
|
||||
/// The dword that replaces SRC0 in a VOP1, VOP2 or VOPC instruction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[allow(missing_docs)]
|
||||
pub enum VectorControl {
|
||||
Sdwa,
|
||||
Dpp8 { fetch_inactive: bool },
|
||||
Dpp16,
|
||||
}
|
||||
|
||||
/// An identified instruction.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct Identified {
|
||||
/// The matched form.
|
||||
pub form: &'static Form,
|
||||
/// First two dwords; the second is zero for 32-bit encodings.
|
||||
pub raw: u64,
|
||||
/// Total length in bytes, including extension words.
|
||||
pub len: usize,
|
||||
/// Extension words present.
|
||||
pub trailer: Trailer,
|
||||
}
|
||||
|
||||
impl Identified {
|
||||
/// Extracts a named field of the base encoding.
|
||||
pub fn field(&self, name: &str) -> Option<u32> {
|
||||
self.form.field(name).map(|field| field.extract(self.raw))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why an instruction could not be identified.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum IdentifyError {
|
||||
/// Fewer bytes remain than the encoding or its extension words need.
|
||||
Truncated {
|
||||
/// Bytes required from the instruction start.
|
||||
needed: usize,
|
||||
},
|
||||
/// No gfx1030 form matches; the bits are reserved or belong to another architecture.
|
||||
Unassigned,
|
||||
/// The bits select an extension the form does not allow.
|
||||
InvalidExtension(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for IdentifyError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Truncated { needed } => write!(formatter, "truncated: needs {needed} bytes"),
|
||||
Self::Unassigned => formatter.write_str("no gfx1030 instruction has this encoding"),
|
||||
Self::InvalidExtension(what) => write!(formatter, "invalid extension: {what}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for IdentifyError {}
|
||||
|
||||
/// Source operand value selecting a trailing literal (XML `SRC_LITERAL`).
|
||||
pub const SRC_LITERAL: u32 = 255;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting an SDWA control dword.
|
||||
pub const SRC_SDWA: u32 = 0xf9;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP16 control dword.
|
||||
pub const SRC_DPP16: u32 = 0xfa;
|
||||
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP8 control dword.
|
||||
pub const SRC_DPP8: u32 = 0xe9;
|
||||
/// DPP8 with fetch-inactive set.
|
||||
pub const SRC_DPP8_FI: u32 = 0xea;
|
||||
|
||||
fn read_dword(bytes: &[u8], index: usize) -> Option<u32> {
|
||||
let start = index.checked_mul(4)?;
|
||||
let chunk = bytes.get(start..start.checked_add(4)?)?;
|
||||
Some(u32::from_le_bytes(chunk.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// Finds the form whose identifying bits match.
|
||||
///
|
||||
/// Masks never overlap ambiguously; the generator rejects such tables.
|
||||
pub fn lookup(raw: u64) -> Option<&'static Form> {
|
||||
FORMS.iter().find(|form| raw & form.mask == form.bits)
|
||||
}
|
||||
|
||||
/// Identifies the instruction at the start of `bytes` and computes its length.
|
||||
pub fn identify(bytes: &[u8]) -> Result<Identified, IdentifyError> {
|
||||
let first = read_dword(bytes, 0).ok_or(IdentifyError::Truncated { needed: 4 })?;
|
||||
let second = read_dword(bytes, 1);
|
||||
let raw_guess = u64::from(first) | (u64::from(second.unwrap_or(0)) << 32);
|
||||
// A 32-bit form never inspects the second dword; a 64-bit form needs it.
|
||||
let form = FORMS
|
||||
.iter()
|
||||
.find(|form| (form.bytes == 4 || second.is_some()) && raw_guess & form.mask == form.bits)
|
||||
.or_else(|| {
|
||||
// Distinguish a truncated 64-bit instruction from unassigned bits.
|
||||
FORMS.iter().find(|form| {
|
||||
form.bytes == 8
|
||||
&& u64::from(first) & form.mask & 0xffff_ffff == form.bits & 0xffff_ffff
|
||||
})
|
||||
})
|
||||
.ok_or(IdentifyError::Unassigned)?;
|
||||
if form.bytes == 8 && second.is_none() {
|
||||
return Err(IdentifyError::Truncated { needed: 8 });
|
||||
}
|
||||
let raw = if form.bytes == 4 {
|
||||
u64::from(first)
|
||||
} else {
|
||||
raw_guess
|
||||
};
|
||||
let mut trailer = Trailer::default();
|
||||
let source = |name: &str| form.field(name).map(|field| field.extract(raw));
|
||||
match form.family {
|
||||
EncodingFamily::Sop1 | EncodingFamily::Sop2 | EncodingFamily::Sopc => {
|
||||
trailer.literal = [source("SSRC0"), source("SSRC1")]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|value| value == SRC_LITERAL);
|
||||
}
|
||||
EncodingFamily::Vop1 | EncodingFamily::Vop2 | EncodingFamily::Vopc => {
|
||||
match source("SRC0") {
|
||||
Some(SRC_LITERAL) => trailer.literal = true,
|
||||
Some(SRC_SDWA) => trailer.vector_control = Some(VectorControl::Sdwa),
|
||||
Some(SRC_DPP16) => trailer.vector_control = Some(VectorControl::Dpp16),
|
||||
Some(SRC_DPP8) => {
|
||||
trailer.vector_control = Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: false,
|
||||
})
|
||||
}
|
||||
Some(SRC_DPP8_FI) => {
|
||||
trailer.vector_control = Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true,
|
||||
})
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
EncodingFamily::Vop3 | EncodingFamily::Vop3Sdst | EncodingFamily::Vop3p => {
|
||||
trailer.literal = [source("SRC0"), source("SRC1"), source("SRC2")]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(|value| value == SRC_LITERAL);
|
||||
}
|
||||
EncodingFamily::Mimg => {
|
||||
trailer.nsa_dwords = source("NSA").unwrap_or(0) as u8;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if form.extensions.contains(Extensions::ALWAYS_LITERAL) {
|
||||
trailer.literal = true;
|
||||
} else if trailer.literal && !form.extensions.contains(Extensions::LITERAL) {
|
||||
return Err(IdentifyError::InvalidExtension("literal"));
|
||||
}
|
||||
match trailer.vector_control {
|
||||
Some(VectorControl::Sdwa) if !form.extensions.contains(Extensions::SDWA) => {
|
||||
return Err(IdentifyError::InvalidExtension("sdwa"));
|
||||
}
|
||||
Some(VectorControl::Dpp8 { .. }) if !form.extensions.contains(Extensions::DPP8) => {
|
||||
return Err(IdentifyError::InvalidExtension("dpp8"));
|
||||
}
|
||||
Some(VectorControl::Dpp16) if !form.extensions.contains(Extensions::DPP16) => {
|
||||
return Err(IdentifyError::InvalidExtension("dpp16"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if trailer.nsa_dwords > 0 && !form.extensions.contains(Extensions::NSA) {
|
||||
return Err(IdentifyError::InvalidExtension("nsa"));
|
||||
}
|
||||
let len = usize::from(form.bytes)
|
||||
+ 4 * usize::from(trailer.literal)
|
||||
+ 4 * usize::from(trailer.vector_control.is_some())
|
||||
+ 4 * usize::from(trailer.nsa_dwords);
|
||||
if bytes.len() < len {
|
||||
return Err(IdentifyError::Truncated { needed: len });
|
||||
}
|
||||
Ok(Identified {
|
||||
form,
|
||||
raw,
|
||||
len,
|
||||
trailer,
|
||||
})
|
||||
}
|
||||
|
||||
/// Number of forms per encoding family in the metadata.
|
||||
pub fn inventory() -> Vec<(EncodingFamily, usize)> {
|
||||
EncodingFamily::ALL
|
||||
.iter()
|
||||
.map(|&family| {
|
||||
(
|
||||
family,
|
||||
FORMS.iter().filter(|form| form.family == family).count(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,177 @@
|
||||
//! Instruction identification against LLVM-assembled fixtures and hand-assembled words.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use xenora_isa::meta::{
|
||||
EncodingFamily, Extensions, FORMS, IdentifyError, VectorControl, identify, inventory, lookup,
|
||||
};
|
||||
|
||||
fn words(values: &[u32]) -> Vec<u8> {
|
||||
values
|
||||
.iter()
|
||||
.flat_map(|value| value.to_le_bytes())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn name_of(values: &[u32]) -> (&'static str, usize) {
|
||||
let found = identify(&words(values)).unwrap();
|
||||
(found.form.name, found.len)
|
||||
}
|
||||
|
||||
/// Mnemonics in a fixture's assembly source, without LLVM's encoding suffixes.
|
||||
fn source_mnemonics(source: &str) -> Vec<String> {
|
||||
source
|
||||
.lines()
|
||||
.map(|line| line.split("//").next().unwrap().trim())
|
||||
.filter(|line| !line.is_empty() && !line.starts_with('.') && !line.ends_with(':'))
|
||||
.map(|line| {
|
||||
let mnemonic = line.split_whitespace().next().unwrap().to_ascii_uppercase();
|
||||
mnemonic
|
||||
.trim_end_matches("_E32")
|
||||
.trim_end_matches("_E64")
|
||||
.to_owned()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llvm_fixtures_identify_with_exact_boundaries_and_mnemonics() {
|
||||
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
|
||||
let mut checked = 0;
|
||||
for entry in fs::read_dir(&directory).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_none_or(|extension| extension != "bin") {
|
||||
continue;
|
||||
}
|
||||
let binary = fs::read(&path).unwrap();
|
||||
let source = fs::read_to_string(path.with_extension("s")).unwrap();
|
||||
let mut offset = 0;
|
||||
let mut identified = Vec::new();
|
||||
while offset < binary.len() {
|
||||
let found = identify(&binary[offset..])
|
||||
.unwrap_or_else(|error| panic!("{} at {offset:#x}: {error}", path.display()));
|
||||
identified.push(found.form.name.to_owned());
|
||||
offset += found.len;
|
||||
}
|
||||
assert_eq!(offset, binary.len(), "{}", path.display());
|
||||
assert_eq!(identified, source_mnemonics(&source), "{}", path.display());
|
||||
checked += 1;
|
||||
}
|
||||
assert!(checked >= 11, "only {checked} fixtures found");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hand_assembled_words_identify() {
|
||||
// SOPP s_endpgm (opcode 1), SOP1 s_mov_b32 s0, s1 (opcode 3).
|
||||
assert_eq!(name_of(&[0xbf81_0000]), ("S_ENDPGM", 4));
|
||||
assert_eq!(name_of(&[0xbe80_0301]), ("S_MOV_B32", 4));
|
||||
// VOP1 v_mov_b32 v0, v1: SRC0 = 256 + 1.
|
||||
assert_eq!(name_of(&[0x7e00_0301]), ("V_MOV_B32", 4));
|
||||
// VOP2 v_add_f32 v0, v1, v2: opcode 3 at bits 30:25, VSRC1 = 2 at bits 16:9.
|
||||
assert_eq!(name_of(&[0x0600_0501]), ("V_ADD_F32", 4));
|
||||
// VOP3 v_add_f32_e64 v0, v1, v2: VOP3 opcode 259 = 256 + VOP2 opcode 3.
|
||||
assert_eq!(name_of(&[0xd503_0000, 0x0002_0501]), ("V_ADD_F32", 8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_sdwa_and_dpp_words_extend_the_length() {
|
||||
// v_mov_b32 v0, 0x12345678: SRC0 = 255 selects a literal.
|
||||
let literal = identify(&words(&[0x7e00_02ff, 0x1234_5678])).unwrap();
|
||||
assert_eq!((literal.form.name, literal.len), ("V_MOV_B32", 8));
|
||||
assert!(literal.trailer.literal);
|
||||
// s_add_u32 s0, s1, literal: SSRC1 = 255.
|
||||
assert_eq!(name_of(&[0x8000_ff01, 0x0000_1234]), ("S_ADD_U32", 8));
|
||||
// VOP3 with SRC2 = 255.
|
||||
let fma = identify(&words(&[0xd54b_0000, 0x03fe_0501, 0x3f80_0000]));
|
||||
assert!(matches!(fma, Ok(found) if found.len == 12 && found.trailer.literal));
|
||||
let sdwa = identify(&words(&[0x7e00_02f9, 0x0006_0601])).unwrap();
|
||||
assert_eq!(sdwa.trailer.vector_control, Some(VectorControl::Sdwa));
|
||||
assert_eq!(sdwa.len, 8);
|
||||
let dpp16 = identify(&words(&[0x7e00_02fa, 0x00ff_0001])).unwrap();
|
||||
assert_eq!(dpp16.trailer.vector_control, Some(VectorControl::Dpp16));
|
||||
let dpp8 = identify(&words(&[0x7e00_02ea, 0x00fa_c688])).unwrap();
|
||||
assert_eq!(
|
||||
dpp8.trailer.vector_control,
|
||||
Some(VectorControl::Dpp8 {
|
||||
fetch_inactive: true
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_unassigned_inputs_are_rejected() {
|
||||
assert_eq!(identify(&[]), Err(IdentifyError::Truncated { needed: 4 }));
|
||||
assert_eq!(
|
||||
identify(&[0x00, 0x00, 0x81]),
|
||||
Err(IdentifyError::Truncated { needed: 4 })
|
||||
);
|
||||
// VOP3 first dword alone.
|
||||
assert_eq!(
|
||||
identify(&words(&[0xd503_0000])),
|
||||
Err(IdentifyError::Truncated { needed: 8 })
|
||||
);
|
||||
// Literal selected but absent.
|
||||
assert_eq!(
|
||||
identify(&words(&[0x7e00_02ff])),
|
||||
Err(IdentifyError::Truncated { needed: 8 })
|
||||
);
|
||||
// SOPP opcodes are 7 bits; this table has no SOPP opcode 127.
|
||||
assert!(lookup(0xbf80_0000 | (127 << 16)).is_none());
|
||||
assert_eq!(
|
||||
identify(&words(&[0xbfff_0000])),
|
||||
Err(IdentifyError::Unassigned)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extensions_outside_a_forms_metadata_are_rejected() {
|
||||
let without_sdwa = FORMS
|
||||
.iter()
|
||||
.find(|form| {
|
||||
form.family == EncodingFamily::Vop1 && !form.extensions.contains(Extensions::SDWA)
|
||||
})
|
||||
.expect("a VOP1 form without SDWA");
|
||||
let word = (without_sdwa.bits as u32) | 0xf9;
|
||||
assert_eq!(
|
||||
identify(&words(&[word, 0])),
|
||||
Err(IdentifyError::InvalidExtension("sdwa"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_form_identifies_as_itself() {
|
||||
for form in &FORMS {
|
||||
assert_eq!(lookup(form.bits).map(|found| found.name), Some(form.name));
|
||||
assert_eq!(
|
||||
lookup(form.bits).unwrap().family,
|
||||
form.family,
|
||||
"{}",
|
||||
form.name
|
||||
);
|
||||
}
|
||||
let total: usize = inventory().iter().map(|(_, count)| count).sum();
|
||||
assert_eq!(total, FORMS.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_word_opcode_table_agrees_with_full_metadata() {
|
||||
use xenora_isa::{BUFFER_LOAD_DWORD, S_ENDPGM, V_ADD_F32, V_ADD_NC_U32, V_MOV_B32};
|
||||
for (opcode, name, family) in [
|
||||
(
|
||||
BUFFER_LOAD_DWORD,
|
||||
"BUFFER_LOAD_DWORD",
|
||||
EncodingFamily::Mubuf,
|
||||
),
|
||||
(S_ENDPGM, "S_ENDPGM", EncodingFamily::Sopp),
|
||||
(V_ADD_F32, "V_ADD_F32", EncodingFamily::Vop2),
|
||||
(V_ADD_NC_U32, "V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
(V_MOV_B32, "V_MOV_B32", EncodingFamily::Vop1),
|
||||
] {
|
||||
let form = FORMS
|
||||
.iter()
|
||||
.find(|form| form.name == name && form.family == family)
|
||||
.unwrap();
|
||||
assert!(opcode.matches(form.bits as u32), "{name}");
|
||||
}
|
||||
}
|
||||
+66
-21
@@ -16,7 +16,7 @@ use objc2_metal::{
|
||||
MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture,
|
||||
MTLTextureDescriptor, MTLTextureUsage,
|
||||
};
|
||||
use xenora_texture::{Bc1Upload, TiledBc1};
|
||||
use xenora_texture::{Bc1Upload, BcAlphaFormat, BcAlphaUpload, TiledBc1};
|
||||
|
||||
#[path = "render.rs"]
|
||||
mod render;
|
||||
@@ -26,12 +26,12 @@ const MAX_GROUPS: usize = 64;
|
||||
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
|
||||
const MAX_SOURCE_BYTES: usize = 64 * 1024;
|
||||
|
||||
const BC1_READBACK: &str = r"
|
||||
const BC_READBACK: &str = r"
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void read_bc1(texture2d<float, access::read> image [[texture(0)]],
|
||||
device uint *output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
kernel void read_bc(texture2d<float, access::read> image [[texture(0)]],
|
||||
device uint *output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint width = image.get_width();
|
||||
uint4 channels = uint4(round(image.read(uint2(index % width, index / width)) * 255.0f));
|
||||
output[index] = channels.r | (channels.g << 8u) | (channels.b << 16u) | (channels.a << 24u);
|
||||
@@ -184,11 +184,18 @@ impl NativeCompute {
|
||||
let (width, height) = tiled
|
||||
.mip_extent(mip)
|
||||
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
|
||||
let pixels = self.validate_bc1_extent(width, height)?;
|
||||
let pixels = self.validate_bc_extent(width, height, "BC1")?;
|
||||
let blocks = tiled
|
||||
.linearize(layer, mip)
|
||||
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
|
||||
self.read_bc1_blocks(&blocks, width.div_ceil(4) * 8, width, height, pixels)
|
||||
self.read_bc_blocks(
|
||||
MTLPixelFormat::BC1_RGBA,
|
||||
&blocks,
|
||||
width.div_ceil(4) * 8,
|
||||
width,
|
||||
height,
|
||||
pixels,
|
||||
)
|
||||
}
|
||||
|
||||
/// Sample a native Metal RGBA8 texture using a native Metal sampler on Apple Silicon GPU.
|
||||
@@ -269,8 +276,9 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
let level = upload
|
||||
.subresource(layer, mip)
|
||||
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
|
||||
let pixels = self.validate_bc1_extent(level.width, level.height)?;
|
||||
self.read_bc1_blocks(
|
||||
let pixels = self.validate_bc_extent(level.width, level.height, "BC1")?;
|
||||
self.read_bc_blocks(
|
||||
MTLPixelFormat::BC1_RGBA,
|
||||
level.bytes,
|
||||
level.row_pitch,
|
||||
level.width,
|
||||
@@ -279,7 +287,45 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_bc1_extent(&self, width: usize, height: usize) -> Result<usize, MetalError> {
|
||||
/// Read a selected subresource from a validated pitched BC2 or BC3 upload.
|
||||
///
|
||||
/// The original 16-byte blocks go to a native `BC2_RGBA` or `BC3_RGBA`
|
||||
/// texture, and the output has the layout of [`Self::read_bc1_upload`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for an invalid layer or mip, out-of-policy size,
|
||||
/// unavailable BC compression, or Metal setup or execution failure.
|
||||
pub fn read_bc_alpha_upload(
|
||||
&self,
|
||||
upload: &BcAlphaUpload<'_>,
|
||||
layer: usize,
|
||||
mip: u32,
|
||||
) -> Result<Vec<u32>, MetalError> {
|
||||
let level = upload
|
||||
.subresource(layer, mip)
|
||||
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
|
||||
let (format, name) = match upload.format() {
|
||||
BcAlphaFormat::Bc2 => (MTLPixelFormat::BC2_RGBA, "BC2"),
|
||||
BcAlphaFormat::Bc3 => (MTLPixelFormat::BC3_RGBA, "BC3"),
|
||||
};
|
||||
let pixels = self.validate_bc_extent(level.width, level.height, name)?;
|
||||
self.read_bc_blocks(
|
||||
format,
|
||||
level.bytes,
|
||||
level.row_pitch,
|
||||
level.width,
|
||||
level.height,
|
||||
pixels,
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_bc_extent(
|
||||
&self,
|
||||
width: usize,
|
||||
height: usize,
|
||||
name: &str,
|
||||
) -> Result<usize, MetalError> {
|
||||
let pixels = width
|
||||
.checked_mul(height)
|
||||
.filter(|pixels| (1..=MAX_GRID_WORDS).contains(pixels))
|
||||
@@ -287,14 +333,15 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
if !self.device.supportsBCTextureCompression() {
|
||||
return Err(MetalError::new(
|
||||
"supportsBCTextureCompression",
|
||||
"BC1 is unavailable",
|
||||
format!("{name} is unavailable"),
|
||||
));
|
||||
}
|
||||
Ok(pixels)
|
||||
}
|
||||
|
||||
fn read_bc1_blocks(
|
||||
fn read_bc_blocks(
|
||||
&self,
|
||||
format: MTLPixelFormat,
|
||||
blocks: &[u8],
|
||||
row_pitch: usize,
|
||||
width: usize,
|
||||
@@ -302,14 +349,11 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
pixels: usize,
|
||||
) -> Result<Vec<u32>, MetalError> {
|
||||
autoreleasepool(|_| {
|
||||
// SAFETY: The positive bounded dimensions and supported BC1 format
|
||||
// SAFETY: The positive bounded dimensions and supported BC format
|
||||
// describe a 2D texture with just its base level.
|
||||
let descriptor = unsafe {
|
||||
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
|
||||
MTLPixelFormat::BC1_RGBA,
|
||||
width,
|
||||
height,
|
||||
false,
|
||||
format, width, height, false,
|
||||
)
|
||||
};
|
||||
descriptor.setStorageMode(MTLStorageMode::Shared);
|
||||
@@ -318,7 +362,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
.device
|
||||
.newTextureWithDescriptor(&descriptor)
|
||||
.ok_or_else(|| {
|
||||
MetalError::new("newTextureWithDescriptor", "BC1 allocation failed")
|
||||
MetalError::new("newTextureWithDescriptor", "BC allocation failed")
|
||||
})?;
|
||||
let region = MTLRegion {
|
||||
origin: MTLOrigin { x: 0, y: 0, z: 0 },
|
||||
@@ -332,7 +376,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
let bytes_per_row = if height <= 4 { 0 } else { row_pitch };
|
||||
// SAFETY: The region spans the whole level, including any partial
|
||||
// edge block. Both callers validate that the input holds all rows
|
||||
// of complete BC1 blocks at the supplied, block-aligned stride.
|
||||
// of complete blocks of this format at the supplied, block-aligned
|
||||
// stride.
|
||||
unsafe {
|
||||
texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
|
||||
region,
|
||||
@@ -342,8 +387,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
);
|
||||
}
|
||||
self.run(
|
||||
BC1_READBACK,
|
||||
"read_bc1",
|
||||
BC_READBACK,
|
||||
"read_bc",
|
||||
ComputeInput::Texture(&texture, pixels),
|
||||
)
|
||||
.map(|profile| profile.output)
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//! Native Metal upload and readback of original BC2 and BC3 blocks.
|
||||
//!
|
||||
//! Every block below was written for this test. The full-texel reference is
|
||||
//! the `xenora-texture` CPU decoder; the anchor texels are worked by hand from
|
||||
//! the Microsoft Direct3D 11 block-compression documentation (BC2, BC3) and
|
||||
//! the Khronos Data Format Specification 1.3 (S3TC DXT3/DXT5). Apple's GPU
|
||||
//! decoder is the value under test, so expected and actual values come from
|
||||
//! different decoders.
|
||||
|
||||
use super::context;
|
||||
use xenora_texture::{BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc, decode_bc2, decode_bc3};
|
||||
|
||||
/// The specifications define colour and BC3 alpha interpolation in real
|
||||
/// numbers, and the CPU reference truncates them. On an Apple M5 Pro the
|
||||
/// native decoder's interpolated values lie within 1.14 codes of the real
|
||||
/// value (they match 6-bit fixed-point weights), so they can sit two codes
|
||||
/// above the truncated reference: 124 against 122 for BC3 alpha
|
||||
/// (4 * 200 + 3 * 20) / 7 = 122.86. Endpoints, BC2 alpha and BC3's fixed
|
||||
/// 0 and 255 are exact and are pinned by the anchor checks.
|
||||
const TOLERANCE: u8 = 2;
|
||||
|
||||
/// Bound for anchors against the real-number value of an interpolated code.
|
||||
const REAL_TOLERANCE: f64 = 1.5;
|
||||
|
||||
fn assert_near(label: &str, actual: u8, real: f64) {
|
||||
assert!(
|
||||
(f64::from(actual) - real).abs() <= REAL_TOLERANCE,
|
||||
"{label}: got {actual}, real value {real:.2}"
|
||||
);
|
||||
}
|
||||
|
||||
const WIDTH: usize = 5;
|
||||
const HEIGHT: usize = 5;
|
||||
const ROW_PITCH: usize = 48;
|
||||
const SLICE_PITCH: usize = 112;
|
||||
|
||||
/// Colour half: two little-endian RGB565 endpoints, then 2-bit indices.
|
||||
/// Every row of 0xe4 selects palette entries 0, 1, 2, 3 from left to right.
|
||||
fn colour((first, second): (u16, u16)) -> [u8; 8] {
|
||||
let [a, b] = first.to_le_bytes();
|
||||
let [c, d] = second.to_le_bytes();
|
||||
[a, b, c, d, 0xe4, 0xe4, 0xe4, 0xe4]
|
||||
}
|
||||
|
||||
/// BC3 alpha half whose texel `t` selects palette entry `(t + 6) % 8`, so
|
||||
/// every row starts with the indices 6 and 7 and a full block uses all eight.
|
||||
fn bc3_alpha(first: u8, second: u8) -> [u8; 8] {
|
||||
let bits = (0..16u64).fold(0, |bits, texel| bits | (((texel + 6) % 8) << (3 * texel)));
|
||||
let i = bits.to_le_bytes();
|
||||
[first, second, i[0], i[1], i[2], i[3], i[4], i[5]]
|
||||
}
|
||||
|
||||
fn block(alpha: [u8; 8], colour: [u8; 8]) -> [u8; 16] {
|
||||
let mut block = [0; 16];
|
||||
block[..8].copy_from_slice(&alpha);
|
||||
block[8..].copy_from_slice(&colour);
|
||||
block
|
||||
}
|
||||
|
||||
// First endpoint greater: red over blue.
|
||||
const DESCENDING: (u16, u16) = (0xf800, 0x001f);
|
||||
// First endpoint smaller, with odd channel values that exercise rounding.
|
||||
const ASCENDING: (u16, u16) = (0x52aa, 0xad55);
|
||||
// Equal endpoints: BC1 would decode index 3 as transparent black.
|
||||
const EQUAL: (u16, u16) = (0x07e0, 0x07e0);
|
||||
|
||||
/// White with zero alpha (BC2 nibbles 0; BC3 endpoints 0 and 0) in every
|
||||
/// padding slot, so a wrong row or slice pitch reads visibly wrong texels.
|
||||
const PAD: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0];
|
||||
|
||||
/// Logical blocks of one layer: the 2×2 base-level grid, then mip 1.
|
||||
type Layer = [[u8; 16]; 5];
|
||||
|
||||
/// Two layers of a 5×5 texture with two mips. Each subresource has seven
|
||||
/// physical blocks: rows of two logical blocks plus one padding block, a
|
||||
/// padding block that closes the slice, and mip 1 uses only its block zero.
|
||||
fn upload_bytes(layers: [Layer; 2]) -> Vec<u8> {
|
||||
let mut bytes = Vec::new();
|
||||
for [b0, b1, b2, b3, small] in layers {
|
||||
for slot in [b0, b1, PAD, b2, b3, PAD, PAD] {
|
||||
bytes.extend_from_slice(&slot);
|
||||
}
|
||||
for slot in [small, PAD, PAD, PAD, PAD, PAD, PAD] {
|
||||
bytes.extend_from_slice(&slot);
|
||||
}
|
||||
}
|
||||
assert_eq!(bytes.len(), 2 * 2 * SLICE_PITCH);
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Crops decoded blocks (a row-major block grid) to a `width`×`height` level
|
||||
/// of words with red in the lowest byte, as the readback kernel writes them.
|
||||
fn reference(blocks: &[[[u8; 4]; 16]], blocks_x: usize, width: usize, height: usize) -> Vec<u32> {
|
||||
let mut texels = Vec::new();
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let decoded = blocks[(y / 4) * blocks_x + x / 4];
|
||||
texels.push(u32::from_le_bytes(decoded[(y % 4) * 4 + x % 4]));
|
||||
}
|
||||
}
|
||||
texels
|
||||
}
|
||||
|
||||
fn alpha(word: u32) -> u8 {
|
||||
word.to_le_bytes()[3]
|
||||
}
|
||||
|
||||
/// Returns the largest per-channel difference, failing on any texel above the
|
||||
/// tolerance with its index and both values.
|
||||
fn assert_close(label: &str, actual: &[u32], expected: &[u32]) -> u8 {
|
||||
assert_eq!(actual.len(), expected.len(), "{label}: texel count");
|
||||
let mut worst = 0;
|
||||
for (texel, (&got, &want)) in actual.iter().zip(expected).enumerate() {
|
||||
let diff = got
|
||||
.to_le_bytes()
|
||||
.iter()
|
||||
.zip(want.to_le_bytes())
|
||||
.map(|(g, w)| g.abs_diff(w))
|
||||
.max()
|
||||
.unwrap();
|
||||
assert!(
|
||||
diff <= TOLERANCE,
|
||||
"{label}: texel {texel} got {got:#010x}, want {want:#010x}"
|
||||
);
|
||||
worst = worst.max(diff);
|
||||
}
|
||||
worst
|
||||
}
|
||||
|
||||
/// GPU reads of both layers: `[layer][mip]`.
|
||||
type Reads = [[Vec<u32>; 2]; 2];
|
||||
|
||||
/// Uploads both layers, reads all four subresources on the GPU, compares
|
||||
/// them with the CPU decoder and returns the reads with the worst difference.
|
||||
fn read_and_compare(
|
||||
format: BcAlphaFormat,
|
||||
decode: fn([u8; 16]) -> [[u8; 4]; 16],
|
||||
layers: [Layer; 2],
|
||||
) -> (Reads, u8) {
|
||||
let bytes = upload_bytes(layers);
|
||||
let upload = BcAlphaUpload::new(
|
||||
&bytes,
|
||||
BcAlphaUploadDesc {
|
||||
width: WIDTH,
|
||||
height: HEIGHT,
|
||||
mips: 2,
|
||||
layers: 2,
|
||||
format,
|
||||
row_pitch: ROW_PITCH,
|
||||
slice_pitch: SLICE_PITCH,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let gpu = context();
|
||||
let mut worst = 0;
|
||||
let reads = std::array::from_fn(|layer| {
|
||||
let decoded = layers[layer].map(decode);
|
||||
let base = gpu.read_bc_alpha_upload(&upload, layer, 0).unwrap();
|
||||
let expected = reference(&decoded[..4], 2, WIDTH, HEIGHT);
|
||||
let label = format!("{format:?} layer {layer}");
|
||||
worst = worst.max(assert_close(&format!("{label} mip 0"), &base, &expected));
|
||||
let small = gpu.read_bc_alpha_upload(&upload, layer, 1).unwrap();
|
||||
let expected = reference(&decoded[4..], 1, 2, 2);
|
||||
worst = worst.max(assert_close(&format!("{label} mip 1"), &small, &expected));
|
||||
[base, small]
|
||||
});
|
||||
for (layer, mip) in [(2, 0), (0, 2)] {
|
||||
assert_eq!(
|
||||
gpu.read_bc_alpha_upload(&upload, layer, mip)
|
||||
.unwrap_err()
|
||||
.operation,
|
||||
"texture subresource"
|
||||
);
|
||||
}
|
||||
(reads, worst)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_pitched_bc2_explicit_alpha_across_mips_and_layers() {
|
||||
// Nibble t in texel t, low nibble first: alpha t * 17.
|
||||
let ramp = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe];
|
||||
let reverse = ramp.map(|byte: u8| !byte);
|
||||
let opaque = [0xff; 8];
|
||||
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
|
||||
let (reads, worst) = read_and_compare(
|
||||
BcAlphaFormat::Bc2,
|
||||
decode_bc2,
|
||||
[
|
||||
[
|
||||
block(ramp, descending),
|
||||
block(reverse, ascending),
|
||||
block(opaque, equal),
|
||||
block(ramp, ascending),
|
||||
block(reverse, descending),
|
||||
],
|
||||
[
|
||||
block(opaque, ascending),
|
||||
block(ramp, equal),
|
||||
block(reverse, descending),
|
||||
block(opaque, descending),
|
||||
block(ramp, equal),
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
// Hand-derived anchors, independent of the CPU decoder.
|
||||
let base = &reads[0][0];
|
||||
// (0, 0): red endpoint, nibble 0. (1, 0): blue endpoint, nibble 1.
|
||||
assert_eq!(base[0], 0x0000_00ff);
|
||||
assert_eq!(base[1], 0x11ff_0000);
|
||||
// (0, 2) is texel 8 of block 0: red endpoint, nibble 8 -> 0x88.
|
||||
assert_eq!(base[2 * WIDTH], 0x8800_00ff);
|
||||
// (3, 3) is texel 15 of block 0: nibble 15 -> opaque.
|
||||
assert_eq!(alpha(base[3 * WIDTH + 3]), 0xff);
|
||||
// (4, 0) is texel 0 of block 1: reversed ramp, nibble 15.
|
||||
assert_eq!(alpha(base[4]), 0xff);
|
||||
// (3, 4) is index 3 of block 2's equal green endpoints: opaque green,
|
||||
// not BC1's transparent black.
|
||||
assert_eq!(base[4 * WIDTH + 3], 0xff00_ff00);
|
||||
// Layer 1 mip 1: green endpoints, ramp nibbles 0, 1, 4, 5.
|
||||
assert_eq!(
|
||||
reads[1][1],
|
||||
[0x0000_ff00, 0x1100_ff00, 0x4400_ff00, 0x5500_ff00]
|
||||
);
|
||||
println!("checked 58 BC2 texels from four subresources, worst channel difference {worst}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_pitched_bc3_interpolated_alpha_across_mips_and_layers() {
|
||||
// First endpoint greater: eight-value palette.
|
||||
let eight = bc3_alpha(200, 20);
|
||||
// First endpoint smaller: six-value palette with fixed 0 and 255.
|
||||
let six = bc3_alpha(20, 200);
|
||||
// Equal endpoints also select the six-value palette.
|
||||
let level = bc3_alpha(128, 128);
|
||||
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
|
||||
let (reads, worst) = read_and_compare(
|
||||
BcAlphaFormat::Bc3,
|
||||
decode_bc3,
|
||||
[
|
||||
[
|
||||
block(eight, descending),
|
||||
block(six, ascending),
|
||||
block(level, equal),
|
||||
block(eight, ascending),
|
||||
block(six, descending),
|
||||
],
|
||||
[
|
||||
block(six, equal),
|
||||
block(eight, ascending),
|
||||
block(level, descending),
|
||||
block(six, ascending),
|
||||
block(eight, equal),
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
// Hand-derived anchors, independent of the CPU decoder.
|
||||
let base = &reads[0][0];
|
||||
let a = |x: usize, y: usize| alpha(base[y * WIDTH + x]);
|
||||
// Block 0, eight-value: row 0 holds indices 6, 7, 0, 1, and row 1
|
||||
// indices 2, 3, 4, 5, each (k = index - 1) ((7 - k) * 200 + k * 20) / 7.
|
||||
assert_near("index 6", a(0, 0), (2.0 * 200.0 + 5.0 * 20.0) / 7.0);
|
||||
assert_near("index 7", a(1, 0), (200.0 + 6.0 * 20.0) / 7.0);
|
||||
for (x, k) in (0..4).zip(1..) {
|
||||
let real = f64::from((7 - k) * 200 + k * 20) / 7.0;
|
||||
assert_near(&format!("index {}", k + 1), a(x, 1), real);
|
||||
}
|
||||
// Then the endpoints themselves, exactly; texel (0, 0) is the red endpoint.
|
||||
assert_eq!([a(2, 0), a(3, 0)], [200, 20]);
|
||||
assert_eq!(base[0] & 0x00ff_ffff, 0x0000_00ff);
|
||||
// Block 1, six-value: column 4 holds indices 6, 2, 6, 2. Index 6 is the
|
||||
// fixed 0 and index 2 is (4 * 20 + 200) / 5 = 56.
|
||||
assert_eq!([a(4, 0), a(4, 2)], [0, 0]);
|
||||
assert_near("six-value index 2", a(4, 1), 56.0);
|
||||
assert_near("six-value index 2", a(4, 3), 56.0);
|
||||
// Block 2, equal endpoints of 128: row 4 holds indices 6, 7, 0, 1, so the
|
||||
// six-value mode shows as the fixed 0 and 255.
|
||||
assert_eq!([a(0, 4), a(1, 4), a(2, 4), a(3, 4)], [0, 255, 128, 128]);
|
||||
// Mip 1, six-value: indices 6, 7, 2, 3 -> 0, 255, 56, (3 * 20 + 2 * 200) / 5 = 92.
|
||||
let small: Vec<_> = reads[0][1].iter().copied().map(alpha).collect();
|
||||
assert_eq!(small[..2], [0, 255]);
|
||||
assert_near("six-value index 2", small[2], 56.0);
|
||||
assert_near("six-value index 3", small[3], 92.0);
|
||||
println!("checked 58 BC3 texels from four subresources, worst channel difference {worst}");
|
||||
}
|
||||
@@ -6,6 +6,8 @@ mod guest_buffer;
|
||||
mod offscreen;
|
||||
#[path = "native/texture.rs"]
|
||||
mod texture;
|
||||
#[path = "native/texture_bc_alpha.rs"]
|
||||
mod texture_bc_alpha;
|
||||
#[path = "native/texture_sampling.rs"]
|
||||
mod texture_sampling;
|
||||
#[path = "native/translated_render.rs"]
|
||||
|
||||
@@ -14,7 +14,9 @@ pub use bc::{
|
||||
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
|
||||
};
|
||||
pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata};
|
||||
pub use upload::{Bc1Subresource, Bc1Upload, Bc1UploadDesc};
|
||||
pub use upload::{
|
||||
Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc,
|
||||
};
|
||||
|
||||
const BLOCK_BYTES: usize = 8;
|
||||
const TILE_BLOCKS: usize = 2;
|
||||
|
||||
+207
-37
@@ -32,56 +32,153 @@ pub struct Bc1Subresource<'a> {
|
||||
|
||||
impl<'a> Bc1Upload<'a> {
|
||||
pub fn new(bytes: &'a [u8], desc: Bc1UploadDesc) -> Result<Self, TextureError> {
|
||||
let max_mips = usize::BITS - desc.width.max(desc.height).leading_zeros();
|
||||
if desc.format != 1
|
||||
|| desc.usage != 1
|
||||
|| desc.width == 0
|
||||
|| desc.height == 0
|
||||
|| desc.layers == 0
|
||||
|| desc.mips == 0
|
||||
|| desc.mips > max_mips
|
||||
{
|
||||
if desc.format != 1 || desc.usage != 1 {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
let (blocks_x, blocks_y) = mip_blocks(desc.width, desc.height, 0);
|
||||
let tight_row = blocks_x
|
||||
.checked_mul(BLOCK_BYTES)
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
if desc.row_pitch < tight_row || !desc.row_pitch.is_multiple_of(BLOCK_BYTES) {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
let minimum_slice = desc
|
||||
.row_pitch
|
||||
.checked_mul(blocks_y)
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
if desc.slice_pitch < minimum_slice || !desc.slice_pitch.is_multiple_of(BLOCK_BYTES) {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
let size = desc
|
||||
.slice_pitch
|
||||
.checked_mul(desc.mips as usize)
|
||||
.and_then(|size| size.checked_mul(desc.layers))
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
if bytes.len() != size {
|
||||
return Err(TextureError::InvalidByteLength);
|
||||
}
|
||||
Self::layout(desc).validate(bytes.len(), BLOCK_BYTES)?;
|
||||
Ok(Self { bytes, desc })
|
||||
}
|
||||
|
||||
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
|
||||
if layer >= self.desc.layers || mip >= self.desc.mips {
|
||||
Self::layout(self.desc).subresource(self.bytes, layer, mip)
|
||||
}
|
||||
|
||||
fn layout(desc: Bc1UploadDesc) -> PitchedLayout {
|
||||
PitchedLayout {
|
||||
width: desc.width,
|
||||
height: desc.height,
|
||||
mips: desc.mips,
|
||||
layers: desc.layers,
|
||||
row_pitch: desc.row_pitch,
|
||||
slice_pitch: desc.slice_pitch,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A block-compressed format whose 16-byte block holds an alpha half followed
|
||||
/// by a BC1-style colour half.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BcAlphaFormat {
|
||||
/// Explicit 4-bit alpha per texel.
|
||||
Bc2,
|
||||
/// Interpolated alpha from two 8-bit endpoints and 3-bit indices.
|
||||
Bc3,
|
||||
}
|
||||
|
||||
/// A layer-major BC2 or BC3 upload with the same pitch rules as
|
||||
/// [`Bc1UploadDesc`], measured in 16-byte blocks.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct BcAlphaUploadDesc {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub mips: u32,
|
||||
pub layers: usize,
|
||||
pub format: BcAlphaFormat,
|
||||
pub row_pitch: usize,
|
||||
pub slice_pitch: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BcAlphaUpload<'a> {
|
||||
bytes: &'a [u8],
|
||||
desc: BcAlphaUploadDesc,
|
||||
}
|
||||
|
||||
impl<'a> BcAlphaUpload<'a> {
|
||||
/// Size of one BC2 or BC3 block in bytes.
|
||||
pub const BLOCK_BYTES: usize = 16;
|
||||
|
||||
pub fn new(bytes: &'a [u8], desc: BcAlphaUploadDesc) -> Result<Self, TextureError> {
|
||||
Self::layout(desc).validate(bytes.len(), Self::BLOCK_BYTES)?;
|
||||
Ok(Self { bytes, desc })
|
||||
}
|
||||
|
||||
pub fn format(&self) -> BcAlphaFormat {
|
||||
self.desc.format
|
||||
}
|
||||
|
||||
/// Selects one level; the returned rows hold 16-byte blocks.
|
||||
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
|
||||
Self::layout(self.desc).subresource(self.bytes, layer, mip)
|
||||
}
|
||||
|
||||
fn layout(desc: BcAlphaUploadDesc) -> PitchedLayout {
|
||||
PitchedLayout {
|
||||
width: desc.width,
|
||||
height: desc.height,
|
||||
mips: desc.mips,
|
||||
layers: desc.layers,
|
||||
row_pitch: desc.row_pitch,
|
||||
slice_pitch: desc.slice_pitch,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Format-independent pitch rules shared by the pitched uploads.
|
||||
struct PitchedLayout {
|
||||
width: usize,
|
||||
height: usize,
|
||||
mips: u32,
|
||||
layers: usize,
|
||||
row_pitch: usize,
|
||||
slice_pitch: usize,
|
||||
}
|
||||
|
||||
impl PitchedLayout {
|
||||
fn validate(&self, len: usize, block_bytes: usize) -> Result<(), TextureError> {
|
||||
let max_mips = usize::BITS - self.width.max(self.height).leading_zeros();
|
||||
if self.width == 0
|
||||
|| self.height == 0
|
||||
|| self.layers == 0
|
||||
|| self.mips == 0
|
||||
|| self.mips > max_mips
|
||||
{
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
let (blocks_x, blocks_y) = mip_blocks(self.width, self.height, 0);
|
||||
let tight_row = blocks_x
|
||||
.checked_mul(block_bytes)
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
if self.row_pitch < tight_row || !self.row_pitch.is_multiple_of(block_bytes) {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
let minimum_slice = self
|
||||
.row_pitch
|
||||
.checked_mul(blocks_y)
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
if self.slice_pitch < minimum_slice || !self.slice_pitch.is_multiple_of(block_bytes) {
|
||||
return Err(TextureError::InvalidLayout);
|
||||
}
|
||||
let size = self
|
||||
.slice_pitch
|
||||
.checked_mul(self.mips as usize)
|
||||
.and_then(|size| size.checked_mul(self.layers))
|
||||
.ok_or(TextureError::SizeOverflow)?;
|
||||
if len != size {
|
||||
return Err(TextureError::InvalidByteLength);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn subresource<'a>(
|
||||
&self,
|
||||
bytes: &'a [u8],
|
||||
layer: usize,
|
||||
mip: u32,
|
||||
) -> Result<Bc1Subresource<'a>, TextureError> {
|
||||
if layer >= self.layers || mip >= self.mips {
|
||||
return Err(TextureError::OutOfBounds);
|
||||
}
|
||||
// Construction proved that the complete array fits in the source span.
|
||||
let offset = (layer * self.desc.mips as usize + mip as usize) * self.desc.slice_pitch;
|
||||
let width = (self.desc.width >> mip).max(1);
|
||||
let height = (self.desc.height >> mip).max(1);
|
||||
let offset = (layer * self.mips as usize + mip as usize) * self.slice_pitch;
|
||||
let width = (self.width >> mip).max(1);
|
||||
let height = (self.height >> mip).max(1);
|
||||
let rows = height.div_ceil(4);
|
||||
Ok(Bc1Subresource {
|
||||
bytes: &self.bytes[offset..offset + rows * self.desc.row_pitch],
|
||||
bytes: &bytes[offset..offset + rows * self.row_pitch],
|
||||
width,
|
||||
height,
|
||||
row_pitch: self.desc.row_pitch,
|
||||
row_pitch: self.row_pitch,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -182,4 +279,77 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const ALPHA_DESC: BcAlphaUploadDesc = BcAlphaUploadDesc {
|
||||
width: 5,
|
||||
height: 5,
|
||||
mips: 2,
|
||||
layers: 2,
|
||||
format: BcAlphaFormat::Bc3,
|
||||
row_pitch: 48,
|
||||
slice_pitch: 112,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn selects_bc_alpha_subresources_in_sixteen_byte_blocks() {
|
||||
let mut bytes = [0; 448];
|
||||
// Layer 1 starts at 224; its base row 1, block 1 is at 224 + 48 + 16.
|
||||
bytes[288..304].fill(0x5c);
|
||||
bytes[336] = 0xa7; // Layer 1, mip 1, block 0.
|
||||
let upload = BcAlphaUpload::new(&bytes, ALPHA_DESC).unwrap();
|
||||
assert_eq!(upload.format(), BcAlphaFormat::Bc3);
|
||||
let base = upload.subresource(1, 0).unwrap();
|
||||
assert_eq!((base.width, base.height, base.row_pitch), (5, 5, 48));
|
||||
assert_eq!(base.bytes.len(), 96);
|
||||
assert_eq!(base.bytes[64..80], [0x5c; 16]);
|
||||
let small = upload.subresource(1, 1).unwrap();
|
||||
assert_eq!((small.width, small.height, small.bytes.len()), (2, 2, 48));
|
||||
assert_eq!(small.bytes[0], 0xa7);
|
||||
assert_eq!(
|
||||
upload.subresource(2, 0).unwrap_err(),
|
||||
TextureError::OutOfBounds
|
||||
);
|
||||
assert_eq!(
|
||||
upload.subresource(0, 2).unwrap_err(),
|
||||
TextureError::OutOfBounds
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bc1_pitches_for_sixteen_byte_blocks() {
|
||||
let bytes = [0; 448];
|
||||
// Each pitch is a valid BC1 multiple of 8 but not of 16, or is
|
||||
// shorter than two 16-byte blocks.
|
||||
for desc in [
|
||||
BcAlphaUploadDesc {
|
||||
row_pitch: 24,
|
||||
..ALPHA_DESC
|
||||
},
|
||||
BcAlphaUploadDesc {
|
||||
row_pitch: 40,
|
||||
..ALPHA_DESC
|
||||
},
|
||||
BcAlphaUploadDesc {
|
||||
slice_pitch: 104,
|
||||
..ALPHA_DESC
|
||||
},
|
||||
BcAlphaUploadDesc {
|
||||
slice_pitch: 80,
|
||||
..ALPHA_DESC
|
||||
},
|
||||
BcAlphaUploadDesc {
|
||||
mips: 4,
|
||||
..ALPHA_DESC
|
||||
},
|
||||
] {
|
||||
assert_eq!(
|
||||
BcAlphaUpload::new(&bytes, desc).unwrap_err(),
|
||||
TextureError::InvalidLayout
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
BcAlphaUpload::new(&bytes[..447], ALPHA_DESC).unwrap_err(),
|
||||
TextureError::InvalidByteLength
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -38,3 +38,38 @@ Run from the checkout root after extracting the approved XML.
|
||||
```sh
|
||||
python3 crates/isa/generate_rdna2.py path/to/amdgpu_isa_rdna2.xml | diff -u crates/isa/src/rdna2.rs -
|
||||
```
|
||||
|
||||
## Complete instruction metadata
|
||||
|
||||
`crates/isa/generate_rdna2_meta.py` reduces the same approved XML to every
|
||||
gfx1030 base instruction form: 1,460 forms in 21 encoding families, with
|
||||
identifying bits, field layouts, operands (field, data format, operand type,
|
||||
width, direction), control-flow flags and allowed extension words. It runs in
|
||||
two stages so regeneration and CI checks need no network and no XML:
|
||||
|
||||
```sh
|
||||
python3 crates/isa/generate_rdna2_meta.py --xml path/to/amdgpu_isa_rdna2.xml # XML -> snapshot -> Rust
|
||||
python3 crates/isa/generate_rdna2_meta.py --check # snapshot -> Rust, compare
|
||||
```
|
||||
|
||||
The snapshot `crates/isa/data/rdna2.jsonl` is sorted, normalised MIT data
|
||||
under the AMD notice in `crates/isa/LICENSE-AMD`. The generator rejects a
|
||||
different XML hash, another architecture, unclassified encodings, duplicate
|
||||
variants, identifying bits outside a mask and overlapping encodings. Two
|
||||
details are not in the identifier masks and are handled explicitly: MIMG
|
||||
opcode bit 7 sits at bit 0, and MTBUF opcode bit 3 sits at bit 53.
|
||||
|
||||
The XML names literal, SDWA, DPP8, DPP16 and NSA variants without a rule for
|
||||
when they apply. `xenora_isa::meta::identify` implements those length rules by
|
||||
hand: a source field equal to 255 (`SRC_LITERAL` in the XML) adds a literal;
|
||||
VOP1, VOP2 and VOPC `SRC0` values 0xF9, 0xFA, 0xE9 and 0xEA add an SDWA, DPP16
|
||||
or DPP8 control dword (from the RDNA 2 ISA guide's SDWA and DPP sections, not
|
||||
the XML); MIMG `NSA` adds that many address dwords. An extension the form does
|
||||
not list is rejected. Every LLVM-assembled fixture identifies with exact
|
||||
boundaries and matching mnemonics. A broader LLVM comparison of the extension
|
||||
rules is still open because it needs the LLVM oracle.
|
||||
|
||||
Identification is not execution. `xenora shaders coverage` reports forms
|
||||
discovered in metadata against forms the semantic decoder accepts
|
||||
(`xenora_decoder::SEMANTIC_FORMS`); reference, Metal and native GPU evidence
|
||||
per form remains in `docs/status.toml`.
|
||||
@@ -1,5 +1,7 @@
|
||||
# gfx1030 instruction coverage
|
||||
|
||||
For counts of every gfx1030 form in AMD's metadata against forms Xenora can execute, run `xenora shaders coverage`. Its "discovered" column is metadata coverage, not execution support.
|
||||
|
||||
The decoder accepts an explicitly tagged, little-endian gfx1030 Wave32
|
||||
stream with 32 lanes per wave under the [synthetic memory ABI](../adr/0003-demo-memory-model.md).
|
||||
Recognition means that the opcode mask matches. Decode additionally checks
|
||||
|
||||
@@ -96,3 +96,24 @@ correctness checks. The recorded 1-, 5- and 15-minute load averages were
|
||||
individual compiler stages and cold/warm timing, tool and capability metadata,
|
||||
and noise-based variability reporting. See the
|
||||
[generated report](../../benchmarks/results/apple-m5/run-1795352394/report.md).
|
||||
|
||||
## Comparing runs
|
||||
|
||||
`scripts/compare-benchmarks.py` compares two structured run directories
|
||||
(`metadata.json` and `results.json`) only when their revision-independent
|
||||
configuration matches (`device`, `host_arch`, `os_version`, `os_build`,
|
||||
`rustc`, `xcode`, `profile`, `api_validation`, `shader_validation`, `power`,
|
||||
`thermal`, `reps`, and `warmup`). Only `run_id`, `timestamp`, and `commit` may
|
||||
differ. If any revision-independent field differs or is missing, the tool exits
|
||||
nonzero (`2`) and lists each mismatch instead of computing misleading deltas.
|
||||
|
||||
When configuration matches, the tool reports per-fixture, per-size medians,
|
||||
interquartile ranges (`q3 - q1`), min-max spans, relative deltas, missing or
|
||||
excluded fixtures/sizes/metrics, and factual uncertainty flags (`iqr_overlap`,
|
||||
`low_sample_count`, `gpu_timer_zero_samples`, `zero_baseline_median`). It
|
||||
intentionally applies no arbitrary pass/fail speedup threshold.
|
||||
|
||||
```sh
|
||||
python3 scripts/compare-benchmarks.py <baseline-dir> <candidate-dir> [--format text|json]
|
||||
python3 scripts/compare-benchmarks.py --self-test
|
||||
```
|
||||
Executable
+600
@@ -0,0 +1,600 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Bounded comparison tool for structured Xenora benchmark result sets.
|
||||
|
||||
Compares two benchmark run directories (each containing metadata.json and
|
||||
results.json) only when their revision-independent configuration matches.
|
||||
Reports medians, dispersion (IQR and min-max span), missing or excluded entries,
|
||||
and factual uncertainty notes without applying an arbitrary pass/fail threshold.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
REVISION_DEPENDENT_KEYS = frozenset({"run_id", "timestamp", "commit"})
|
||||
|
||||
REQUIRED_CONFIG_KEYS = (
|
||||
"device",
|
||||
"host_arch",
|
||||
"os_version",
|
||||
"os_build",
|
||||
"rustc",
|
||||
"xcode",
|
||||
"profile",
|
||||
"api_validation",
|
||||
"shader_validation",
|
||||
"power",
|
||||
"thermal",
|
||||
"reps",
|
||||
"warmup",
|
||||
)
|
||||
|
||||
METRICS = ("compile", "library", "pipeline", "gpu", "host")
|
||||
STAT_KEYS = ("median", "min", "max", "q1", "q3", "reps")
|
||||
|
||||
|
||||
def _load_json(path):
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
return json.load(fh)
|
||||
|
||||
|
||||
def load_run(run_dir):
|
||||
meta_path = os.path.join(run_dir, "metadata.json")
|
||||
results_path = os.path.join(run_dir, "results.json")
|
||||
if not os.path.isfile(meta_path):
|
||||
raise FileNotFoundError("missing metadata.json in %s" % run_dir)
|
||||
if not os.path.isfile(results_path):
|
||||
raise FileNotFoundError("missing results.json in %s" % run_dir)
|
||||
return _load_json(meta_path), _load_json(results_path)
|
||||
|
||||
|
||||
def check_config_compatibility(base_meta, cand_meta):
|
||||
"""Return a list of revision-independent configuration mismatches."""
|
||||
mismatches = []
|
||||
all_keys = sorted(
|
||||
(set(REQUIRED_CONFIG_KEYS) | set(base_meta.keys()) | set(cand_meta.keys()))
|
||||
- REVISION_DEPENDENT_KEYS
|
||||
)
|
||||
for key in all_keys:
|
||||
in_base = key in base_meta and base_meta[key] not in (None, "")
|
||||
in_cand = key in cand_meta and cand_meta[key] not in (None, "")
|
||||
if key in REQUIRED_CONFIG_KEYS and (not in_base or not in_cand):
|
||||
mismatches.append(
|
||||
{
|
||||
"field": key,
|
||||
"baseline": base_meta.get(key),
|
||||
"candidate": cand_meta.get(key),
|
||||
"reason": "missing_required_field",
|
||||
}
|
||||
)
|
||||
continue
|
||||
if base_meta.get(key) != cand_meta.get(key):
|
||||
mismatches.append(
|
||||
{
|
||||
"field": key,
|
||||
"baseline": base_meta.get(key),
|
||||
"candidate": cand_meta.get(key),
|
||||
"reason": "value_mismatch",
|
||||
}
|
||||
)
|
||||
return mismatches
|
||||
|
||||
|
||||
def _validate_stat_block(block):
|
||||
if not isinstance(block, dict):
|
||||
return False
|
||||
for k in STAT_KEYS:
|
||||
v = block.get(k)
|
||||
if not isinstance(v, (int, float)) or isinstance(v, bool):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _summarize_block(block):
|
||||
median = float(block["median"])
|
||||
q1 = float(block["q1"])
|
||||
q3 = float(block["q3"])
|
||||
lo = float(block["min"])
|
||||
hi = float(block["max"])
|
||||
reps = int(block["reps"])
|
||||
iqr = q3 - q1
|
||||
return {
|
||||
"median": median,
|
||||
"q1": q1,
|
||||
"q3": q3,
|
||||
"iqr": iqr,
|
||||
"min": lo,
|
||||
"max": hi,
|
||||
"span": hi - lo,
|
||||
"reps": reps,
|
||||
"relative_iqr": (iqr / median) if median > 0.0 else None,
|
||||
}
|
||||
|
||||
|
||||
def _compare_metric(metric_name, base_size, cand_size):
|
||||
base_block = base_size.get(metric_name)
|
||||
cand_block = cand_size.get(metric_name)
|
||||
if not _validate_stat_block(base_block) or not _validate_stat_block(cand_block):
|
||||
return None, {
|
||||
"metric": metric_name,
|
||||
"baseline_present": _validate_stat_block(base_block),
|
||||
"candidate_present": _validate_stat_block(cand_block),
|
||||
}
|
||||
|
||||
b = _summarize_block(base_block)
|
||||
c = _summarize_block(cand_block)
|
||||
delta = c["median"] - b["median"]
|
||||
ratio = (c["median"] / b["median"]) if b["median"] > 0.0 else None
|
||||
pct = ((delta / b["median"]) * 100.0) if b["median"] > 0.0 else None
|
||||
iqr_overlap = max(b["q1"], c["q1"]) <= min(b["q3"], c["q3"])
|
||||
combined_iqr = b["iqr"] + c["iqr"]
|
||||
delta_to_iqr = (abs(delta) / combined_iqr) if combined_iqr > 0.0 else None
|
||||
|
||||
notes = []
|
||||
if iqr_overlap:
|
||||
notes.append("iqr_overlap")
|
||||
if b["reps"] < 5 or c["reps"] < 5:
|
||||
notes.append("low_sample_count")
|
||||
if b["median"] == 0.0:
|
||||
notes.append("zero_baseline_median")
|
||||
|
||||
entry = {
|
||||
"metric": metric_name,
|
||||
"baseline": b,
|
||||
"candidate": c,
|
||||
"median_delta": delta,
|
||||
"median_ratio": ratio,
|
||||
"median_pct_change": pct,
|
||||
"iqr_overlap": iqr_overlap,
|
||||
"combined_iqr": combined_iqr,
|
||||
"delta_to_combined_iqr": delta_to_iqr,
|
||||
"uncertainty_notes": notes,
|
||||
}
|
||||
|
||||
if metric_name == "gpu":
|
||||
bz = base_size.get("gpu_zero_fraction")
|
||||
cz = cand_size.get("gpu_zero_fraction")
|
||||
entry["gpu_zero_fraction_baseline"] = bz
|
||||
entry["gpu_zero_fraction_candidate"] = cz
|
||||
if (isinstance(bz, (int, float)) and bz > 0.0) or (
|
||||
isinstance(cz, (int, float)) and cz > 0.0
|
||||
):
|
||||
notes.append("gpu_timer_zero_samples")
|
||||
|
||||
return entry, None
|
||||
|
||||
|
||||
def compare_runs(base_meta, base_results, cand_meta, cand_results):
|
||||
"""Compare two structured benchmark runs. Never applies an arbitrary pass threshold."""
|
||||
mismatches = check_config_compatibility(base_meta, cand_meta)
|
||||
report = {
|
||||
"compatible": len(mismatches) == 0,
|
||||
"baseline": {
|
||||
"run_id": base_meta.get("run_id"),
|
||||
"commit": base_meta.get("commit"),
|
||||
"timestamp": base_meta.get("timestamp"),
|
||||
},
|
||||
"candidate": {
|
||||
"run_id": cand_meta.get("run_id"),
|
||||
"commit": cand_meta.get("commit"),
|
||||
"timestamp": cand_meta.get("timestamp"),
|
||||
},
|
||||
"config_mismatches": mismatches,
|
||||
"missing_fixtures": {"baseline_only": [], "candidate_only": []},
|
||||
"excluded_fixtures": [],
|
||||
"comparisons": [],
|
||||
}
|
||||
if mismatches:
|
||||
return report
|
||||
|
||||
base_fixtures = {
|
||||
(f.get("name"), f.get("stage"), f.get("source")): f
|
||||
for f in (base_results.get("fixtures") or [])
|
||||
}
|
||||
cand_fixtures = {
|
||||
(f.get("name"), f.get("stage"), f.get("source")): f
|
||||
for f in (cand_results.get("fixtures") or [])
|
||||
}
|
||||
|
||||
all_keys = sorted(set(base_fixtures.keys()) | set(cand_fixtures.keys()))
|
||||
for key in all_keys:
|
||||
name, stage, source = key
|
||||
bf = base_fixtures.get(key)
|
||||
cf = cand_fixtures.get(key)
|
||||
if bf is None:
|
||||
report["missing_fixtures"]["candidate_only"].append(
|
||||
{"name": name, "stage": stage, "source": source}
|
||||
)
|
||||
continue
|
||||
if cf is None:
|
||||
report["missing_fixtures"]["baseline_only"].append(
|
||||
{"name": name, "stage": stage, "source": source}
|
||||
)
|
||||
continue
|
||||
|
||||
if bf.get("status") != "benchmarked" or cf.get("status") != "benchmarked":
|
||||
report["excluded_fixtures"].append(
|
||||
{
|
||||
"name": name,
|
||||
"stage": stage,
|
||||
"source": source,
|
||||
"baseline_status": bf.get("status"),
|
||||
"baseline_reason": bf.get("reason", ""),
|
||||
"candidate_status": cf.get("status"),
|
||||
"candidate_reason": cf.get("reason", ""),
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
base_sizes = {s.get("words"): s for s in (bf.get("sizes") or []) if "words" in s}
|
||||
cand_sizes = {s.get("words"): s for s in (cf.get("sizes") or []) if "words" in s}
|
||||
all_words = sorted(set(base_sizes.keys()) | set(cand_sizes.keys()))
|
||||
|
||||
fixture_comp = {
|
||||
"name": name,
|
||||
"stage": stage,
|
||||
"source": source,
|
||||
"missing_sizes": {"baseline_only": [], "candidate_only": []},
|
||||
"sizes": [],
|
||||
}
|
||||
|
||||
for w in all_words:
|
||||
bs = base_sizes.get(w)
|
||||
cs = cand_sizes.get(w)
|
||||
if bs is None:
|
||||
fixture_comp["missing_sizes"]["candidate_only"].append(w)
|
||||
continue
|
||||
if cs is None:
|
||||
fixture_comp["missing_sizes"]["baseline_only"].append(w)
|
||||
continue
|
||||
|
||||
metrics_out = []
|
||||
missing_metrics = []
|
||||
for m in METRICS:
|
||||
entry, miss = _compare_metric(m, bs, cs)
|
||||
if miss is not None:
|
||||
missing_metrics.append(miss)
|
||||
else:
|
||||
metrics_out.append(entry)
|
||||
|
||||
fixture_comp["sizes"].append(
|
||||
{
|
||||
"words": w,
|
||||
"metrics": metrics_out,
|
||||
"missing_metrics": missing_metrics,
|
||||
}
|
||||
)
|
||||
|
||||
report["comparisons"].append(fixture_comp)
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def _fmt_us(seconds):
|
||||
if seconds is None:
|
||||
return "-"
|
||||
return "%.3f us" % (seconds * 1e6)
|
||||
|
||||
|
||||
def format_text(report):
|
||||
lines = [
|
||||
"Xenora benchmark comparison (no arbitrary pass/fail threshold)",
|
||||
"Baseline: %s (commit %s)"
|
||||
% (report["baseline"]["run_id"], report["baseline"]["commit"]),
|
||||
"Candidate: %s (commit %s)"
|
||||
% (report["candidate"]["run_id"], report["candidate"]["commit"]),
|
||||
]
|
||||
if not report["compatible"]:
|
||||
lines.append("")
|
||||
lines.append("Status: INCOMPATIBLE (revision-independent configuration mismatch)")
|
||||
for m in report["config_mismatches"]:
|
||||
lines.append(
|
||||
"- %s (%s): baseline=%r candidate=%r"
|
||||
% (m["field"], m["reason"], m["baseline"], m["candidate"])
|
||||
)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
lines.append("Status: COMPATIBLE")
|
||||
|
||||
mf = report["missing_fixtures"]
|
||||
if mf["baseline_only"] or mf["candidate_only"]:
|
||||
lines.append("")
|
||||
lines.append("Missing fixtures:")
|
||||
for item in mf["baseline_only"]:
|
||||
lines.append("- baseline_only: %s (%s/%s)" % (item["name"], item["stage"], item["source"]))
|
||||
for item in mf["candidate_only"]:
|
||||
lines.append("- candidate_only: %s (%s/%s)" % (item["name"], item["stage"], item["source"]))
|
||||
|
||||
if report["excluded_fixtures"]:
|
||||
lines.append("")
|
||||
lines.append("Excluded fixtures (not timed):")
|
||||
for ex in report["excluded_fixtures"]:
|
||||
lines.append(
|
||||
"- %s: baseline=%s (%s) candidate=%s (%s)"
|
||||
% (
|
||||
ex["name"],
|
||||
ex["baseline_status"],
|
||||
ex["baseline_reason"],
|
||||
ex["candidate_status"],
|
||||
ex["candidate_reason"],
|
||||
)
|
||||
)
|
||||
|
||||
for fc in report["comparisons"]:
|
||||
lines.append("")
|
||||
lines.append("Fixture: %s (%s, %s)" % (fc["name"], fc["stage"], fc["source"]))
|
||||
ms = fc["missing_sizes"]
|
||||
if ms["baseline_only"] or ms["candidate_only"]:
|
||||
lines.append(
|
||||
" Missing sizes: baseline_only=%s candidate_only=%s"
|
||||
% (ms["baseline_only"], ms["candidate_only"])
|
||||
)
|
||||
lines.append(
|
||||
" words\tmetric\tbase_med\tbase_iqr\tcand_med\tcand_iqr\tdelta_pct\tuncertainty"
|
||||
)
|
||||
for s in fc["sizes"]:
|
||||
for m in s["metrics"]:
|
||||
pct_str = (
|
||||
"%+.2f%%" % m["median_pct_change"]
|
||||
if m["median_pct_change"] is not None
|
||||
else "n/a"
|
||||
)
|
||||
notes = ",".join(m["uncertainty_notes"]) or "none"
|
||||
lines.append(
|
||||
" %d\t%s\t%s\t%s\t%s\t%s\t%s\t%s"
|
||||
% (
|
||||
s["words"],
|
||||
m["metric"],
|
||||
_fmt_us(m["baseline"]["median"]),
|
||||
_fmt_us(m["baseline"]["iqr"]),
|
||||
_fmt_us(m["candidate"]["median"]),
|
||||
_fmt_us(m["candidate"]["iqr"]),
|
||||
pct_str,
|
||||
notes,
|
||||
)
|
||||
)
|
||||
for mm in s["missing_metrics"]:
|
||||
lines.append(
|
||||
" %d\t%s\tMISSING (baseline=%s candidate=%s)"
|
||||
% (s["words"], mm["metric"], mm["baseline_present"], mm["candidate_present"])
|
||||
)
|
||||
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def _sample_meta(**overrides):
|
||||
base = {
|
||||
"run_id": "run-1",
|
||||
"timestamp": "unix:100",
|
||||
"device": "Apple M5",
|
||||
"host_arch": "aarch64",
|
||||
"os_version": "27.3",
|
||||
"os_build": "26C5047e",
|
||||
"rustc": "rustc 1.100.0",
|
||||
"xcode": "Xcode 27.2",
|
||||
"commit": "aaaa1111",
|
||||
"profile": "release",
|
||||
"api_validation": "0",
|
||||
"shader_validation": "0",
|
||||
"power": "AC Power",
|
||||
"thermal": "no warnings recorded",
|
||||
"reps": 21,
|
||||
"warmup": 2,
|
||||
}
|
||||
base.update(overrides)
|
||||
return base
|
||||
|
||||
|
||||
def _sample_stat(median, q1, q3, lo=None, hi=None, reps=21):
|
||||
return {
|
||||
"median": median,
|
||||
"q1": q1,
|
||||
"q3": q3,
|
||||
"min": q1 if lo is None else lo,
|
||||
"max": q3 if hi is None else hi,
|
||||
"reps": reps,
|
||||
}
|
||||
|
||||
|
||||
def _sample_size(words, med=10.0e-6, q1=9.0e-6, q3=11.0e-6, reps=21, gpu_zero=0.0):
|
||||
return {
|
||||
"words": words,
|
||||
"compile": _sample_stat(med, q1, q3, reps=reps),
|
||||
"library": _sample_stat(med * 2, q1 * 2, q3 * 2, reps=reps),
|
||||
"pipeline": _sample_stat(med * 3, q1 * 3, q3 * 3, reps=reps),
|
||||
"gpu": _sample_stat(med * 0.5, q1 * 0.5, q3 * 0.5, reps=reps),
|
||||
"host": _sample_stat(med * 10, q1 * 10, q3 * 10, reps=reps),
|
||||
"gpu_zero_fraction": gpu_zero,
|
||||
}
|
||||
|
||||
|
||||
class CompareBenchmarksSelfTest(unittest.TestCase):
|
||||
def test_rejects_revision_independent_config_mismatch(self):
|
||||
bm = _sample_meta(run_id="r1", commit="111", power="Battery Power", reps=7)
|
||||
cm = _sample_meta(run_id="r2", commit="222", power="AC Power", reps=21)
|
||||
rep = compare_runs(bm, {"fixtures": []}, cm, {"fixtures": []})
|
||||
self.assertFalse(rep["compatible"])
|
||||
fields = {m["field"] for m in rep["config_mismatches"]}
|
||||
self.assertEqual(fields, {"power", "reps"})
|
||||
|
||||
def test_rejects_missing_required_metadata(self):
|
||||
bm = _sample_meta()
|
||||
cm = _sample_meta()
|
||||
del cm["api_validation"]
|
||||
rep = compare_runs(bm, {"fixtures": []}, cm, {"fixtures": []})
|
||||
self.assertFalse(rep["compatible"])
|
||||
self.assertEqual(rep["config_mismatches"][0]["field"], "api_validation")
|
||||
self.assertEqual(rep["config_mismatches"][0]["reason"], "missing_required_field")
|
||||
|
||||
def test_allows_revision_dependent_differences_and_computes_exact_stats(self):
|
||||
bm = _sample_meta(run_id="r1", commit="111", timestamp="unix:100")
|
||||
cm = _sample_meta(run_id="r2", commit="222", timestamp="unix:200")
|
||||
br = {
|
||||
"fixtures": [
|
||||
{
|
||||
"name": "add",
|
||||
"stage": "compute",
|
||||
"source": "translated-rdna",
|
||||
"status": "benchmarked",
|
||||
"reason": "",
|
||||
"sizes": [_sample_size(64, med=10.0e-6, q1=9.0e-6, q3=11.0e-6)],
|
||||
}
|
||||
]
|
||||
}
|
||||
cr = {
|
||||
"fixtures": [
|
||||
{
|
||||
"name": "add",
|
||||
"stage": "compute",
|
||||
"source": "translated-rdna",
|
||||
"status": "benchmarked",
|
||||
"reason": "",
|
||||
"sizes": [_sample_size(64, med=15.0e-6, q1=14.0e-6, q3=16.0e-6)],
|
||||
}
|
||||
]
|
||||
}
|
||||
rep = compare_runs(bm, br, cm, cr)
|
||||
self.assertTrue(rep["compatible"])
|
||||
comp = rep["comparisons"][0]["sizes"][0]["metrics"][0]
|
||||
self.assertEqual(comp["metric"], "compile")
|
||||
self.assertAlmostEqual(comp["baseline"]["iqr"], 2.0e-6, places=12)
|
||||
self.assertAlmostEqual(comp["candidate"]["iqr"], 2.0e-6, places=12)
|
||||
self.assertAlmostEqual(comp["median_delta"], 5.0e-6, places=12)
|
||||
self.assertAlmostEqual(comp["median_ratio"], 1.5, places=9)
|
||||
self.assertAlmostEqual(comp["median_pct_change"], 50.0, places=9)
|
||||
self.assertFalse(comp["iqr_overlap"])
|
||||
self.assertAlmostEqual(comp["delta_to_combined_iqr"], 1.25, places=9)
|
||||
self.assertEqual(comp["uncertainty_notes"], [])
|
||||
|
||||
def test_reports_iqr_overlap_gpu_zero_and_low_samples(self):
|
||||
bm = _sample_meta(reps=3)
|
||||
cm = _sample_meta(reps=3)
|
||||
br = {
|
||||
"fixtures": [
|
||||
{
|
||||
"name": "add",
|
||||
"stage": "compute",
|
||||
"source": "translated-rdna",
|
||||
"status": "benchmarked",
|
||||
"reason": "",
|
||||
"sizes": [_sample_size(4, med=10.0e-6, q1=8.0e-6, q3=12.0e-6, reps=3, gpu_zero=0.25)],
|
||||
}
|
||||
]
|
||||
}
|
||||
cr = {
|
||||
"fixtures": [
|
||||
{
|
||||
"name": "add",
|
||||
"stage": "compute",
|
||||
"source": "translated-rdna",
|
||||
"status": "benchmarked",
|
||||
"reason": "",
|
||||
"sizes": [_sample_size(4, med=11.0e-6, q1=9.0e-6, q3=13.0e-6, reps=3, gpu_zero=0.0)],
|
||||
}
|
||||
]
|
||||
}
|
||||
rep = compare_runs(bm, br, cm, cr)
|
||||
gpu_m = [m for m in rep["comparisons"][0]["sizes"][0]["metrics"] if m["metric"] == "gpu"][0]
|
||||
self.assertTrue(gpu_m["iqr_overlap"])
|
||||
self.assertIn("iqr_overlap", gpu_m["uncertainty_notes"])
|
||||
self.assertIn("low_sample_count", gpu_m["uncertainty_notes"])
|
||||
self.assertIn("gpu_timer_zero_samples", gpu_m["uncertainty_notes"])
|
||||
|
||||
def test_reports_missing_fixtures_sizes_metrics_and_excluded(self):
|
||||
bm = _sample_meta()
|
||||
cm = _sample_meta()
|
||||
size_missing_gpu = _sample_size(64)
|
||||
del size_missing_gpu["gpu"]
|
||||
br = {
|
||||
"fixtures": [
|
||||
{"name": "only-base", "stage": "compute", "source": "translated-rdna", "status": "benchmarked", "reason": "", "sizes": [_sample_size(4)]},
|
||||
{"name": "excl", "stage": "compute", "source": "translated-rdna", "status": "excluded", "reason": "oracle mismatch", "sizes": []},
|
||||
{"name": "shared", "stage": "compute", "source": "translated-rdna", "status": "benchmarked", "reason": "", "sizes": [_sample_size(4), size_missing_gpu]},
|
||||
]
|
||||
}
|
||||
cr = {
|
||||
"fixtures": [
|
||||
{"name": "only-cand", "stage": "compute", "source": "translated-rdna", "status": "benchmarked", "reason": "", "sizes": [_sample_size(4)]},
|
||||
{"name": "excl", "stage": "compute", "source": "translated-rdna", "status": "benchmarked", "reason": "", "sizes": [_sample_size(4)]},
|
||||
{"name": "shared", "stage": "compute", "source": "translated-rdna", "status": "benchmarked", "reason": "", "sizes": [_sample_size(64), _sample_size(256)]},
|
||||
]
|
||||
}
|
||||
rep = compare_runs(bm, br, cm, cr)
|
||||
self.assertTrue(rep["compatible"])
|
||||
self.assertEqual([f["name"] for f in rep["missing_fixtures"]["baseline_only"]], ["only-base"])
|
||||
self.assertEqual([f["name"] for f in rep["missing_fixtures"]["candidate_only"]], ["only-cand"])
|
||||
self.assertEqual(len(rep["excluded_fixtures"]), 1)
|
||||
shared = rep["comparisons"][0]
|
||||
self.assertEqual(shared["missing_sizes"]["baseline_only"], [4])
|
||||
self.assertEqual(shared["missing_sizes"]["candidate_only"], [256])
|
||||
self.assertEqual(shared["sizes"][0]["missing_metrics"][0]["metric"], "gpu")
|
||||
|
||||
def test_no_arbitrary_pass_threshold_on_large_slowdown(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
d1 = os.path.join(td, "r1")
|
||||
d2 = os.path.join(td, "r2")
|
||||
os.makedirs(d1)
|
||||
os.makedirs(d2)
|
||||
with open(os.path.join(d1, "metadata.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump(_sample_meta(run_id="r1", commit="aaa"), fh)
|
||||
with open(os.path.join(d2, "metadata.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump(_sample_meta(run_id="r2", commit="bbb"), fh)
|
||||
with open(os.path.join(d1, "results.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump({"fixtures": [{"name": "add", "stage": "compute", "source": "translated-rdna", "status": "benchmarked", "reason": "", "sizes": [_sample_size(4, med=10e-6, q1=9e-6, q3=11e-6)]}]}, fh)
|
||||
with open(os.path.join(d2, "results.json"), "w", encoding="utf-8") as fh:
|
||||
json.dump({"fixtures": [{"name": "add", "stage": "compute", "source": "translated-rdna", "status": "benchmarked", "reason": "", "sizes": [_sample_size(4, med=100e-6, q1=95e-6, q3=105e-6)]}]}, fh)
|
||||
# Must still exit 0 (factual reporting, no arbitrary pass/fail threshold).
|
||||
self.assertEqual(main([d1, d2, "--format", "json"]), 0)
|
||||
|
||||
def test_real_repo_runs_flag_power_and_reps_mismatch(self):
|
||||
root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
||||
r1 = os.path.join(root, "benchmarks", "results", "apple-m5", "run-1795338391")
|
||||
r2 = os.path.join(root, "benchmarks", "results", "apple-m5", "run-1795352394")
|
||||
if os.path.isdir(r1) and os.path.isdir(r2):
|
||||
bm, br = load_run(r1)
|
||||
cm, cr = load_run(r2)
|
||||
rep = compare_runs(bm, br, cm, cr)
|
||||
self.assertFalse(rep["compatible"])
|
||||
self.assertEqual({m["field"] for m in rep["config_mismatches"]}, {"power", "reps"})
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
p = argparse.ArgumentParser(
|
||||
description="Compare two structured Xenora benchmark run directories."
|
||||
)
|
||||
p.add_argument("baseline", nargs="?", help="Baseline run directory")
|
||||
p.add_argument("candidate", nargs="?", help="Candidate run directory")
|
||||
p.add_argument("--format", choices=("text", "json"), default="text")
|
||||
p.add_argument("--self-test", action="store_true", help="Run built-in unit tests")
|
||||
args = p.parse_args(argv)
|
||||
|
||||
if args.self_test:
|
||||
suite = unittest.defaultTestLoader.loadTestsFromTestCase(CompareBenchmarksSelfTest)
|
||||
res = unittest.TextTestRunner(verbosity=2).run(suite)
|
||||
return 0 if res.wasSuccessful() else 1
|
||||
|
||||
if not args.baseline or not args.candidate:
|
||||
p.error("baseline and candidate run directories are required (or pass --self-test)")
|
||||
|
||||
try:
|
||||
bm, br = load_run(args.baseline)
|
||||
cm, cr = load_run(args.candidate)
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
sys.stderr.write("error: %s\n" % exc)
|
||||
return 2
|
||||
|
||||
report = compare_runs(bm, br, cm, cr)
|
||||
if args.format == "json":
|
||||
json.dump(report, sys.stdout, indent=2, sort_keys=True)
|
||||
sys.stdout.write("\n")
|
||||
else:
|
||||
sys.stdout.write(format_text(report))
|
||||
|
||||
return 0 if report["compatible"] else 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user