mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 12:50:43 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d28fc89de | ||
|
|
3b47c21bb0 | ||
|
|
9a62d86a89 | ||
|
|
4b32c532fe | ||
|
|
bbc84c0da0 | ||
|
|
a7fa8b0d65 | ||
|
|
061c28b405 | ||
|
|
2f28a5adbb | ||
|
|
9ddb708cdf | ||
|
|
6f1ac2a906 |
No files matched your search
@@ -21,12 +21,16 @@ remains unsupported.
|
||||
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
|
||||
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
|
||||
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
|
||||
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
|
||||
- Avoided resolver allocations for permitted guest data reads and writes contained in one mapping, preserving checked fallback for split spans and faults (#105).
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
|
||||
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
|
||||
|
||||
### Added
|
||||
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
|
||||
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
|
||||
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
|
||||
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
|
||||
|
||||
@@ -309,7 +309,7 @@ These require a Metal-capable Apple Silicon Mac.
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host.
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host. On macOS, the script uses a Python 3 fallback when GNU `timeout` is unavailable.
|
||||
|
||||
### Verify guest execution
|
||||
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
//! Synthetic interpreter and DBT timings.
|
||||
//!
|
||||
//! Set `XENORA_DBT_BENCH_JSON=<path>` to also write the results as one JSON
|
||||
//! document (format version 1). The text output does not change. Values the
|
||||
//! benchmark cannot determine, such as the git revision outside a checkout,
|
||||
//! are written as `null`.
|
||||
//!
|
||||
//! The benchmark target disables Cargo's test harness. To run the percentile
|
||||
//! unit tests, build with
|
||||
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
|
||||
@@ -10,7 +15,7 @@
|
||||
use std::hint::black_box;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::dbt::{DbtEngine, DbtMetrics};
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
use xenora_loader::pe::{
|
||||
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
|
||||
@@ -103,19 +108,215 @@ fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
|
||||
lower + (upper - lower).mul_f64(rank.fract())
|
||||
}
|
||||
|
||||
fn report(label: &str, samples: &mut [Duration]) {
|
||||
/// Order statistics of one timing series, shared by the text and JSON reports.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Summary {
|
||||
samples: usize,
|
||||
median: Duration,
|
||||
min: Duration,
|
||||
max: Duration,
|
||||
p95: Duration,
|
||||
p99: Duration,
|
||||
iqr: Duration,
|
||||
mips: f64,
|
||||
}
|
||||
|
||||
fn summarize(samples: &mut [Duration]) -> Summary {
|
||||
samples.sort_unstable();
|
||||
let median = percentile(samples, 0.50);
|
||||
let p95 = percentile(samples, 0.95);
|
||||
let p99 = percentile(samples, 0.99);
|
||||
let iqr = percentile(samples, 0.75) - percentile(samples, 0.25);
|
||||
let min = samples[0];
|
||||
let max = samples[samples.len() - 1];
|
||||
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
|
||||
println!(
|
||||
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, p95 {p95:?}, p99 {p99:?}, IQR {iqr:?}, median {mips:.2} MIPS",
|
||||
samples.len()
|
||||
);
|
||||
Summary {
|
||||
samples: samples.len(),
|
||||
median,
|
||||
min: samples[0],
|
||||
max: samples[samples.len() - 1],
|
||||
p95: percentile(samples, 0.95),
|
||||
p99: percentile(samples, 0.99),
|
||||
iqr: percentile(samples, 0.75) - percentile(samples, 0.25),
|
||||
mips: INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn report_line(label: &str, s: &Summary) -> String {
|
||||
format!(
|
||||
"{label}: {} samples, median {:?}, min {:?}, max {:?}, p95 {:?}, p99 {:?}, IQR {:?}, median {:.2} MIPS",
|
||||
s.samples, s.median, s.min, s.max, s.p95, s.p99, s.iqr, s.mips
|
||||
)
|
||||
}
|
||||
|
||||
/// Facts about the run that are not timings. `None` means the benchmark could not
|
||||
/// determine the value.
|
||||
struct RunInfo {
|
||||
unix_time: Option<u64>,
|
||||
cpu: Option<String>,
|
||||
os: &'static str,
|
||||
os_version: Option<String>,
|
||||
arch: &'static str,
|
||||
revision: Option<String>,
|
||||
dirty: Option<bool>,
|
||||
debug_assertions: bool,
|
||||
guest_code_bytes: usize,
|
||||
warmup: usize,
|
||||
}
|
||||
|
||||
fn command_output(program: &str, args: &[&str]) -> Option<String> {
|
||||
let output = std::process::Command::new(program)
|
||||
.args(args)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
Some(String::from_utf8(output.stdout).ok()?.trim().to_owned())
|
||||
}
|
||||
|
||||
fn run_info(guest_code_bytes: usize, warmup: usize) -> RunInfo {
|
||||
let non_empty = |value: Option<String>| value.filter(|v| !v.is_empty());
|
||||
RunInfo {
|
||||
unix_time: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.ok()
|
||||
.map(|d| d.as_secs()),
|
||||
cpu: non_empty(command_output(
|
||||
"sysctl",
|
||||
&["-n", "machdep.cpu.brand_string"],
|
||||
)),
|
||||
os: std::env::consts::OS,
|
||||
os_version: non_empty(command_output("sw_vers", &["-productVersion"])),
|
||||
arch: std::env::consts::ARCH,
|
||||
revision: non_empty(command_output("git", &["rev-parse", "HEAD"])),
|
||||
dirty: command_output("git", &["status", "--porcelain", "--untracked-files=no"])
|
||||
.map(|status| !status.is_empty()),
|
||||
debug_assertions: cfg!(debug_assertions),
|
||||
guest_code_bytes,
|
||||
warmup,
|
||||
}
|
||||
}
|
||||
|
||||
fn json_string(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len() + 2);
|
||||
out.push('"');
|
||||
for c in value.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
fn json_option<T>(value: Option<T>, render: impl FnOnce(T) -> String) -> String {
|
||||
value.map_or_else(|| "null".to_owned(), render)
|
||||
}
|
||||
|
||||
/// JSON has no infinity or NaN, so a non-finite rate (a zero median) is `null`.
|
||||
fn json_f64(value: f64) -> String {
|
||||
if value.is_finite() {
|
||||
format!("{value}")
|
||||
} else {
|
||||
"null".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn json_object(fields: &[(&str, String)]) -> String {
|
||||
let body: Vec<String> = fields
|
||||
.iter()
|
||||
.map(|(key, value)| format!("{}:{value}", json_string(key)))
|
||||
.collect();
|
||||
format!("{{{}}}", body.join(","))
|
||||
}
|
||||
|
||||
fn json_summary(s: &Summary) -> String {
|
||||
json_object(&[
|
||||
("samples", s.samples.to_string()),
|
||||
("median_ns", s.median.as_nanos().to_string()),
|
||||
("min_ns", s.min.as_nanos().to_string()),
|
||||
("max_ns", s.max.as_nanos().to_string()),
|
||||
("p95_ns", s.p95.as_nanos().to_string()),
|
||||
("p99_ns", s.p99.as_nanos().to_string()),
|
||||
("iqr_ns", s.iqr.as_nanos().to_string()),
|
||||
("median_mips", json_f64(s.mips)),
|
||||
])
|
||||
}
|
||||
|
||||
fn json_document(
|
||||
info: &RunInfo,
|
||||
interpreter: &Summary,
|
||||
cold: &Summary,
|
||||
warm: &Summary,
|
||||
metrics: &DbtMetrics,
|
||||
) -> String {
|
||||
let string = |value: &String| json_string(value);
|
||||
json_object(&[
|
||||
("format_version", "1".to_owned()),
|
||||
("benchmark", json_string("dbt_bench")),
|
||||
("unix_time", json_option(info.unix_time, |t| t.to_string())),
|
||||
(
|
||||
"host",
|
||||
json_object(&[
|
||||
("cpu", json_option(info.cpu.as_ref(), string)),
|
||||
("os", json_string(info.os)),
|
||||
("os_version", json_option(info.os_version.as_ref(), string)),
|
||||
("arch", json_string(info.arch)),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"source",
|
||||
json_object(&[
|
||||
("revision", json_option(info.revision.as_ref(), string)),
|
||||
("dirty", json_option(info.dirty, |d| d.to_string())),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"build",
|
||||
json_object(&[("debug_assertions", info.debug_assertions.to_string())]),
|
||||
),
|
||||
(
|
||||
"workload",
|
||||
json_object(&[
|
||||
("name", json_string("add_rax_chain")),
|
||||
("guest_instructions", INSTRUCTIONS.to_string()),
|
||||
("guest_code_bytes", info.guest_code_bytes.to_string()),
|
||||
("instruction_budget", BUDGET.to_string()),
|
||||
("warmup_rounds", info.warmup.to_string()),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"timings",
|
||||
json_object(&[
|
||||
("interpreter", json_summary(interpreter)),
|
||||
("cold_dbt", json_summary(cold)),
|
||||
("warm_dbt", json_summary(warm)),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"cold_dbt_metrics",
|
||||
json_object(&[
|
||||
("blocks_compiled", metrics.blocks_compiled.to_string()),
|
||||
("cache_hits", metrics.cache_hits.to_string()),
|
||||
("cache_misses", metrics.cache_misses.to_string()),
|
||||
(
|
||||
"native_bytes_emitted",
|
||||
metrics.native_bytes_emitted.to_string(),
|
||||
),
|
||||
("dbt_dispatches", metrics.dbt_dispatches.to_string()),
|
||||
(
|
||||
"instructions_executed",
|
||||
metrics.instructions_executed.to_string(),
|
||||
),
|
||||
(
|
||||
"interpreter_fallbacks",
|
||||
metrics.interpreter_fallbacks.to_string(),
|
||||
),
|
||||
("service_calls", metrics.service_calls.to_string()),
|
||||
]),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@@ -190,14 +391,24 @@ fn main() {
|
||||
"Percentiles describe this synthetic workload on this host; tail estimates vary with sample count."
|
||||
);
|
||||
println!("Even sample counts use the midpoint of the two middle values for the median.");
|
||||
report("Interpreter", &mut interpreter);
|
||||
report("Cold DBT", &mut cold);
|
||||
report("Warm DBT", &mut warm);
|
||||
let interpreter = summarize(&mut interpreter);
|
||||
let cold = summarize(&mut cold);
|
||||
let warm = summarize(&mut warm);
|
||||
println!("{}", report_line("Interpreter", &interpreter));
|
||||
println!("{}", report_line("Cold DBT", &cold));
|
||||
println!("{}", report_line("Warm DBT", &warm));
|
||||
let metrics = cold_metrics.unwrap();
|
||||
println!(
|
||||
"Cold DBT compiled {} blocks and emitted {} native bytes in {} dispatches",
|
||||
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
|
||||
);
|
||||
|
||||
if let Some(path) = std::env::var_os("XENORA_DBT_BENCH_JSON") {
|
||||
let info = run_info(code.len(), warmup_count);
|
||||
let document = json_document(&info, &interpreter, &cold, &warm, &metrics);
|
||||
std::fs::write(&path, document + "\n").expect("write XENORA_DBT_BENCH_JSON");
|
||||
println!("JSON results written to {}", path.to_string_lossy());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -233,4 +444,140 @@ mod tests {
|
||||
let samples = [10, 20, 100].map(Duration::from_micros);
|
||||
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_strings_escape_quotes_backslashes_and_controls() {
|
||||
use super::json_string;
|
||||
|
||||
assert_eq!(json_string("plain"), r#""plain""#);
|
||||
assert_eq!(json_string(r#"a"b\c"#), r#""a\"b\\c""#);
|
||||
assert_eq!(json_string("l1\nl2\r\t"), r#""l1\nl2\r\t""#);
|
||||
assert_eq!(json_string("\u{1}\u{1f}"), r#""\u0001\u001f""#);
|
||||
// Non-ASCII text needs no escape in UTF-8 JSON.
|
||||
assert_eq!(json_string("Zażółć"), "\"Zażółć\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_values_and_non_finite_rates_are_null() {
|
||||
use super::{json_f64, json_option};
|
||||
|
||||
assert_eq!(json_option(None::<u64>, |v| v.to_string()), "null");
|
||||
assert_eq!(json_option(Some(7_u64), |v| v.to_string()), "7");
|
||||
assert_eq!(json_f64(f64::INFINITY), "null");
|
||||
assert_eq!(json_f64(f64::NAN), "null");
|
||||
assert_eq!(json_f64(12.5), "12.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_has_every_field_with_the_summary_values() {
|
||||
fn fixed_summary(median_us: u64) -> super::Summary {
|
||||
use super::Duration;
|
||||
super::Summary {
|
||||
samples: 3,
|
||||
median: Duration::from_micros(median_us),
|
||||
min: Duration::from_micros(10),
|
||||
max: Duration::from_micros(100),
|
||||
p95: Duration::from_nanos(92_000),
|
||||
p99: Duration::from_nanos(98_400),
|
||||
iqr: Duration::from_micros(45),
|
||||
mips: 500.25,
|
||||
}
|
||||
}
|
||||
|
||||
fn fixed_info() -> super::RunInfo {
|
||||
super::RunInfo {
|
||||
unix_time: Some(1_700_000_000),
|
||||
cpu: Some("Test \"CPU\"\\1".to_owned()),
|
||||
os: "macos",
|
||||
os_version: None,
|
||||
arch: "aarch64",
|
||||
revision: Some("0123abcd".to_owned()),
|
||||
dirty: Some(false),
|
||||
debug_assertions: false,
|
||||
guest_code_bytes: 40_011,
|
||||
warmup: 10,
|
||||
}
|
||||
}
|
||||
|
||||
use super::{DbtMetrics, INSTRUCTIONS, json_document};
|
||||
|
||||
let metrics = DbtMetrics {
|
||||
blocks_compiled: 626,
|
||||
cache_hits: 0,
|
||||
cache_misses: 626,
|
||||
native_bytes_emitted: 245_168,
|
||||
dbt_dispatches: 626,
|
||||
instructions_executed: 10_002,
|
||||
interpreter_fallbacks: 1,
|
||||
service_calls: 0,
|
||||
};
|
||||
let document = json_document(
|
||||
&fixed_info(),
|
||||
&fixed_summary(20),
|
||||
&fixed_summary(30),
|
||||
&fixed_summary(40),
|
||||
&metrics,
|
||||
);
|
||||
let summary = |median: &str| {
|
||||
format!(
|
||||
r#"{{"samples":3,"median_ns":{median},"min_ns":10000,"max_ns":100000,"p95_ns":92000,"p99_ns":98400,"iqr_ns":45000,"median_mips":500.25}}"#
|
||||
)
|
||||
};
|
||||
let expected = format!(
|
||||
concat!(
|
||||
r#"{{"format_version":1,"benchmark":"dbt_bench","unix_time":1700000000,"#,
|
||||
r#""host":{{"cpu":"Test \"CPU\"\\1","os":"macos","os_version":null,"arch":"aarch64"}},"#,
|
||||
r#""source":{{"revision":"0123abcd","dirty":false}},"#,
|
||||
r#""build":{{"debug_assertions":false}},"#,
|
||||
r#""workload":{{"name":"add_rax_chain","guest_instructions":{},"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10}},"#,
|
||||
r#""timings":{{"interpreter":{},"cold_dbt":{},"warm_dbt":{}}},"#,
|
||||
r#""cold_dbt_metrics":{{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":1,"service_calls":0}}}}"#,
|
||||
),
|
||||
INSTRUCTIONS,
|
||||
summary("20000"),
|
||||
summary("30000"),
|
||||
summary("40000"),
|
||||
);
|
||||
assert_eq!(document, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_report_keeps_its_format() {
|
||||
fn fixed_summary(median_us: u64) -> super::Summary {
|
||||
use super::Duration;
|
||||
super::Summary {
|
||||
samples: 3,
|
||||
median: Duration::from_micros(median_us),
|
||||
min: Duration::from_micros(10),
|
||||
max: Duration::from_micros(100),
|
||||
p95: Duration::from_nanos(92_000),
|
||||
p99: Duration::from_nanos(98_400),
|
||||
iqr: Duration::from_micros(45),
|
||||
mips: 500.25,
|
||||
}
|
||||
}
|
||||
|
||||
use super::report_line;
|
||||
|
||||
assert_eq!(
|
||||
report_line("Cold DBT", &fixed_summary(20)),
|
||||
"Cold DBT: 3 samples, median 20µs, min 10µs, max 100µs, p95 92µs, p99 98.4µs, IQR 45µs, median 500.25 MIPS"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_matches_the_percentile_helper() {
|
||||
use super::{Duration, INSTRUCTIONS, summarize};
|
||||
|
||||
let mut samples = [100, 10, 30, 20].map(Duration::from_micros);
|
||||
let s = summarize(&mut samples);
|
||||
assert_eq!(s.samples, 4);
|
||||
assert_eq!(s.median, Duration::from_micros(25));
|
||||
assert_eq!(s.min, Duration::from_micros(10));
|
||||
assert_eq!(s.max, Duration::from_micros(100));
|
||||
assert_eq!(s.p95, Duration::from_nanos(89_500));
|
||||
assert_eq!(s.p99, Duration::from_nanos(97_900));
|
||||
assert_eq!(s.iqr, Duration::from_micros(30));
|
||||
assert_eq!(s.mips, INSTRUCTIONS as f64 / 25e-6 / 1e6);
|
||||
}
|
||||
}
|
||||
+613
-1
@@ -5,7 +5,7 @@
|
||||
//! Provides isolated, page-aligned guest virtual memory with permission checking
|
||||
//! (Read, Write, Execute) and bounds enforcement without host OS mapping tricks.
|
||||
|
||||
use std::fmt;
|
||||
use std::{fmt, ops::Range};
|
||||
|
||||
pub(crate) const ALLOCATION_GRANULARITY: u64 = 65_536;
|
||||
|
||||
@@ -505,14 +505,39 @@ impl GuestMemory {
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
if let Some((index, range)) = self.contiguous_region(address, src.len())
|
||||
&& self.regions[index].permissions.write
|
||||
{
|
||||
self.regions[index].data[range].copy_from_slice(src);
|
||||
return Ok(());
|
||||
}
|
||||
self.write_checked(address, src, Some("write"))
|
||||
}
|
||||
|
||||
/// Read raw bytes from guest memory at the specified address, checking permissions.
|
||||
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
|
||||
if let Some((index, range)) = self.contiguous_region(address, dst.len())
|
||||
&& self.regions[index].permissions.read
|
||||
{
|
||||
dst.copy_from_slice(&self.regions[index].data[range]);
|
||||
return Ok(());
|
||||
}
|
||||
self.read_checked(address, dst, Some("read"))
|
||||
}
|
||||
|
||||
// Only the first eligible mapping may supply the whole span. Otherwise
|
||||
// the checked resolver must preserve split-access and overlap priority.
|
||||
fn contiguous_region(&self, address: u64, len: usize) -> Option<(usize, Range<usize>)> {
|
||||
let (index, region) = self
|
||||
.regions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, region)| region.base + region.data.len() as u64 > address)?;
|
||||
let offset = usize::try_from(address.checked_sub(region.base)?).ok()?;
|
||||
let end = offset.checked_add(len)?;
|
||||
(end <= region.data.len()).then_some((index, offset..end))
|
||||
}
|
||||
|
||||
/// Read an instruction byte from guest memory, verifying execute permission.
|
||||
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
|
||||
address.checked_add(1).ok_or(MemoryError::Overflow)?;
|
||||
@@ -854,3 +879,590 @@ mod instruction_fetch_tests {
|
||||
assert_eq!(m.fetch_instruction_byte(BASE + 3), Ok(0x44));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod data_access_contract_tests {
|
||||
use super::{MemoryPermissions as P, *};
|
||||
const A: u64 = 0x10_0000;
|
||||
|
||||
#[test]
|
||||
fn data_permissions_are_independent_and_failed_reads_leave_output_untouched() {
|
||||
for bits in 0..8 {
|
||||
let p = P {
|
||||
read: bits & 1 != 0,
|
||||
write: bits & 2 != 0,
|
||||
execute: bits & 4 != 0,
|
||||
};
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 4, p, &[1, 2, 3, 4]).unwrap();
|
||||
let mut out = [0xee; 2];
|
||||
let read = m.read_bytes(A + 1, &mut out);
|
||||
assert_eq!(
|
||||
read,
|
||||
if p.read {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 1,
|
||||
required: "read",
|
||||
})
|
||||
}
|
||||
);
|
||||
assert_eq!(out, if p.read { [2, 3] } else { [0xee; 2] });
|
||||
let write = m.write_bytes(A + 1, &[0x55, 0x66]);
|
||||
assert_eq!(
|
||||
write,
|
||||
if p.write {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 1,
|
||||
required: "write",
|
||||
})
|
||||
}
|
||||
);
|
||||
let mut stored = [0; 4];
|
||||
m.read_checked(A, &mut stored, None).unwrap();
|
||||
assert_eq!(
|
||||
stored,
|
||||
if p.write {
|
||||
[1, 0x55, 0x66, 4]
|
||||
} else {
|
||||
[1, 2, 3, 4]
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_data_spans_keep_inclusive_ends_and_ignore_permissions() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0, P::NO_ACCESS).unwrap();
|
||||
m.map_region(A + 16, 3, P::NO_ACCESS).unwrap();
|
||||
m.map_region(u64::MAX, 0, P::NO_ACCESS).unwrap();
|
||||
for at in [A, A + 16, A + 17, A + 19, u64::MAX] {
|
||||
assert_eq!(m.read_bytes(at, &mut []), Ok(()));
|
||||
assert_eq!(m.write_bytes(at, &[]), Ok(()));
|
||||
}
|
||||
for at in [A - 1, A + 1, A + 15, A + 20] {
|
||||
assert_eq!(
|
||||
m.read_bytes(at, &mut []),
|
||||
Err(MemoryError::UnmappedAddress(at))
|
||||
);
|
||||
assert_eq!(
|
||||
m.write_bytes(at, &[]),
|
||||
Err(MemoryError::UnmappedAddress(at))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_address_overflow_precedes_permissions_and_preserves_output() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(u64::MAX - 3, 3, P::NO_ACCESS).unwrap();
|
||||
let mut out = [0xee; 2];
|
||||
assert_eq!(
|
||||
m.read_bytes(u64::MAX - 1, &mut out),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(out, [0xee; 2]);
|
||||
assert_eq!(
|
||||
m.write_bytes(u64::MAX - 1, &[1, 2]),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(
|
||||
m.read_bytes(u64::MAX, &mut out[..1]),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(m.write_bytes(u64::MAX, &[1]), Err(MemoryError::Overflow));
|
||||
assert_eq!(m.read_u16(u64::MAX - 1), Err(MemoryError::Overflow));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_data_accesses_keep_exact_fallback_errors_and_atomicity() {
|
||||
for (gap, right) in [
|
||||
(0, P::READ_WRITE),
|
||||
(0, P::READ_ONLY),
|
||||
(0, P::NO_ACCESS),
|
||||
(
|
||||
0,
|
||||
P {
|
||||
read: false,
|
||||
write: true,
|
||||
execute: false,
|
||||
},
|
||||
),
|
||||
(1, P::READ_WRITE),
|
||||
] {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 8, P::READ_WRITE, &[0, 1, 2, 3, 4, 5, 6, 7])
|
||||
.unwrap();
|
||||
let b = A + 8 + gap;
|
||||
m.map_region_with_data(b, 8, right, &[8, 9, 10, 11, 12, 13, 14, 15])
|
||||
.unwrap();
|
||||
let mut expected = m.clone();
|
||||
let mut actual_out = [0xee; 4];
|
||||
let mut expected_out = [0xee; 4];
|
||||
assert_eq!(
|
||||
m.read_bytes(A + 6, &mut actual_out),
|
||||
expected.read_checked(A + 6, &mut expected_out, Some("read"))
|
||||
);
|
||||
assert_eq!(actual_out, expected_out);
|
||||
assert_eq!(
|
||||
actual_out,
|
||||
if gap == 0 && right.read {
|
||||
[6, 7, 8, 9]
|
||||
} else {
|
||||
[0xee; 4]
|
||||
}
|
||||
);
|
||||
let bytes = [0xa0, 0xa1, 0xa2, 0xa3];
|
||||
assert_eq!(
|
||||
m.write_bytes(A + 6, &bytes),
|
||||
expected.write_checked(A + 6, &bytes, Some("write"))
|
||||
);
|
||||
let written = gap == 0 && right.write;
|
||||
assert_eq!(
|
||||
m.read_u64_bypass(A).unwrap().to_le_bytes(),
|
||||
if written {
|
||||
[0, 1, 2, 3, 4, 5, 0xa0, 0xa1]
|
||||
} else {
|
||||
[0, 1, 2, 3, 4, 5, 6, 7]
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
m.read_u64_bypass(b).unwrap().to_le_bytes(),
|
||||
if written {
|
||||
[0xa2, 0xa3, 10, 11, 12, 13, 14, 15]
|
||||
} else {
|
||||
[8, 9, 10, 11, 12, 13, 14, 15]
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_accesses_keep_first_mapping_priority_for_partial_overlaps() {
|
||||
const BASE: u64 = 0x0000_0003_0000_0000;
|
||||
for first in [P::READ_WRITE, P::READ_ONLY] {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(0x1000, 1, P::NO_ACCESS).unwrap();
|
||||
m.map_region_with_data(BASE, 4, first, &[1, 2, 3, 4])
|
||||
.unwrap();
|
||||
let empty = m.map_heap_allocation(PROCESS_HEAP, 0).unwrap();
|
||||
assert_eq!(empty, BASE);
|
||||
assert_eq!(
|
||||
m.resize_heap_allocation(PROCESS_HEAP, empty, 8, true),
|
||||
Ok(BASE)
|
||||
);
|
||||
let mut out = [0xee; 8];
|
||||
assert_eq!(m.read_bytes(BASE, &mut out), Ok(()));
|
||||
assert_eq!(out, [1, 2, 3, 4, 0, 0, 0, 0]);
|
||||
assert_eq!(m.read_u16(BASE), Ok(0x0201));
|
||||
let bytes = [0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7];
|
||||
let mut expected = m.clone();
|
||||
assert_eq!(
|
||||
m.write_bytes(BASE, &bytes),
|
||||
expected.write_checked(BASE, &bytes, Some("write"))
|
||||
);
|
||||
m.read_bytes(BASE, &mut out).unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
if first.write {
|
||||
bytes
|
||||
} else {
|
||||
[1, 2, 3, 4, 0, 0, 0, 0]
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_accesses_observe_writes_clones_release_and_remap() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 8, P::READ_WRITE, &[1; 8])
|
||||
.unwrap();
|
||||
let mut clone = m.clone();
|
||||
m.write_u64(A, 0x1122_3344_5566_7788).unwrap();
|
||||
clone.write_u32(A, 0xaabb_ccdd).unwrap();
|
||||
assert_eq!(m.read_u64(A), Ok(0x1122_3344_5566_7788));
|
||||
assert_eq!(clone.read_u64(A), Ok(0x0101_0101_aabb_ccdd));
|
||||
let b = m.map_virtual_allocation(0x4000, 2, P::READ_WRITE).unwrap();
|
||||
m.write_u16(b, 0x1234).unwrap();
|
||||
assert_eq!(m.read_u16(b), Ok(0x1234));
|
||||
assert!(m.release_virtual_allocation(b));
|
||||
assert_eq!(m.read_u16(b), Err(MemoryError::UnmappedAddress(b)));
|
||||
m.map_region_with_data(b, 2, P::READ_ONLY, &[0x56, 0x78])
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u16(b), Ok(0x7856));
|
||||
assert_eq!(
|
||||
m.write_u8(b, 0),
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: b,
|
||||
required: "write"
|
||||
})
|
||||
);
|
||||
assert_eq!(clone.read_u16(b), Err(MemoryError::UnmappedAddress(b)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod data_memory_bench {
|
||||
use super::{MemoryPermissions as P, *};
|
||||
use crate::{CpuState, DbtEngine, ExitReason, Register};
|
||||
use std::{hint::black_box, time::Instant};
|
||||
|
||||
const CODE: u64 = 0x1000;
|
||||
const VALUE: u64 = 0xffff_ff00;
|
||||
#[derive(Clone, Copy)]
|
||||
enum Kind {
|
||||
Registers,
|
||||
Counter,
|
||||
Sequential,
|
||||
Split,
|
||||
}
|
||||
|
||||
fn setting(name: &str, default: usize, maximum: usize) -> usize {
|
||||
let value = std::env::var(name).map_or(default, |s| s.parse().expect(name));
|
||||
assert!((1..=maximum).contains(&value), "invalid {name}");
|
||||
value
|
||||
}
|
||||
fn quantile(sorted: &[f64], fraction: f64) -> f64 {
|
||||
let rank = (sorted.len() - 1) as f64 * fraction;
|
||||
let lo = rank.floor() as usize;
|
||||
sorted[lo] + (sorted[rank.ceil() as usize] - sorted[lo]) * rank.fract()
|
||||
}
|
||||
fn guest(kind: Kind, iterations: usize, data: u64) -> (Vec<u8>, usize) {
|
||||
// MOV RCX, iterations; MOV RDX, VALUE (control) or RSI, data; XOR EAX,EAX.
|
||||
let registers = matches!(kind, Kind::Registers);
|
||||
let sequential = matches!(kind, Kind::Sequential);
|
||||
let mut code = vec![0x48, 0xb9];
|
||||
code.extend_from_slice(&(iterations as u64).to_le_bytes());
|
||||
code.extend_from_slice(&[0x48, if registers { 0xba } else { 0xbe }]);
|
||||
let target = if registers { VALUE } else { data };
|
||||
code.extend_from_slice(&target.to_le_bytes());
|
||||
code.extend_from_slice(&[0x31, 0xc0]);
|
||||
let per_iteration = if registers {
|
||||
// ADD RAX,RDX; ADD RDX,1; DEC RCX; JNZ -12.
|
||||
code.extend_from_slice(&[
|
||||
0x48, 0x01, 0xd0, 0x48, 0x83, 0xc2, 0x01, 0x48, 0xff, 0xc9, 0x75, 0xf4,
|
||||
]);
|
||||
4
|
||||
} else {
|
||||
// MOV RDX,[RSI]; ADD RAX,RDX; ADD RDX,1; MOV [RSI],RDX.
|
||||
code.extend_from_slice(&[
|
||||
0x48, 0x8b, 0x16, 0x48, 0x01, 0xd0, 0x48, 0x83, 0xc2, 0x01, 0x48, 0x89, 0x16,
|
||||
]);
|
||||
if sequential {
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xc6, 0x08]); // ADD RSI,8.
|
||||
}
|
||||
// DEC RCX; JNZ -22 (sequential) or -18 (counter).
|
||||
let back = if sequential { 0xea } else { 0xee };
|
||||
code.extend_from_slice(&[0x48, 0xff, 0xc9, 0x75, back]);
|
||||
6 + usize::from(sequential)
|
||||
};
|
||||
code.push(0xf4); // HLT; three setup instructions and one halt.
|
||||
(code, iterations * per_iteration + 4)
|
||||
}
|
||||
|
||||
// Run identical source on the baseline and candidate with the same release profile.
|
||||
// Allocation counting is deliberately separate: instrumentation distorts these timings.
|
||||
#[test]
|
||||
#[ignore = "manual, correctness-gated warm DBT data-memory timing"]
|
||||
fn warm_data_memory_benchmark() {
|
||||
let samples = setting("XENORA_DATA_BENCH_SAMPLES", 31, 1001);
|
||||
let counter = setting("XENORA_DATA_BENCH_ITERS", 32768, 65536);
|
||||
let sequential = setting("XENORA_DATA_BENCH_STREAM_ITERS", 16384, 65536);
|
||||
for (label, kind, regions, last) in [
|
||||
("register-control", Kind::Registers, 4, false),
|
||||
("counter-front", Kind::Counter, 4, false),
|
||||
("counter-front-many", Kind::Counter, 64, false),
|
||||
("counter-first", Kind::Counter, 4, false),
|
||||
("counter-first-many", Kind::Counter, 64, false),
|
||||
("counter-third-many", Kind::Counter, 64, false),
|
||||
("counter-middle", Kind::Counter, 64, false),
|
||||
("counter-last", Kind::Counter, 64, true),
|
||||
("sequential-front", Kind::Sequential, 4, false),
|
||||
("sequential-front-many", Kind::Sequential, 64, false),
|
||||
("sequential-first", Kind::Sequential, 4, false),
|
||||
("sequential-first-many", Kind::Sequential, 64, false),
|
||||
("sequential-last", Kind::Sequential, 64, true),
|
||||
("split-counter-control", Kind::Split, 4, false),
|
||||
] {
|
||||
let iterations = if matches!(kind, Kind::Sequential) {
|
||||
sequential
|
||||
} else {
|
||||
counter
|
||||
};
|
||||
let code_address = if label.contains("-first") {
|
||||
0x8000_0000
|
||||
} else {
|
||||
CODE
|
||||
};
|
||||
let data = if last {
|
||||
0x4000_0000
|
||||
} else if label.contains("-third") {
|
||||
0x20_1000
|
||||
} else if label.contains("-middle") {
|
||||
0x23_f000
|
||||
} else {
|
||||
0x1_0000
|
||||
};
|
||||
let (code, expected_instructions) = guest(kind, iterations, data);
|
||||
let words = if matches!(kind, Kind::Sequential) {
|
||||
iterations
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let initial: Vec<u8> = (0..words)
|
||||
.flat_map(|i| (VALUE + i as u64).to_le_bytes())
|
||||
.collect();
|
||||
let increment = match kind {
|
||||
Kind::Registers => 0,
|
||||
Kind::Sequential => 1,
|
||||
_ => iterations as u64,
|
||||
};
|
||||
let expected: Vec<u8> = (0..words)
|
||||
.flat_map(|i| (VALUE + i as u64 + increment).to_le_bytes())
|
||||
.collect();
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(code_address, 4096, P::READ_EXECUTE, &code)
|
||||
.unwrap();
|
||||
let pieces = if matches!(kind, Kind::Split) {
|
||||
memory
|
||||
.map_region_with_data(data, 4, P::READ_WRITE, &initial[..4])
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(data + 4, 4, P::READ_WRITE, &initial[4..])
|
||||
.unwrap();
|
||||
2
|
||||
} else {
|
||||
memory
|
||||
.map_region_with_data(data, initial.len(), P::READ_WRITE, &initial)
|
||||
.unwrap();
|
||||
1
|
||||
};
|
||||
for i in 0..regions - pieces - 1 {
|
||||
memory
|
||||
.map_region(0x20_0000 + i as u64 * 8192, 4096, P::READ_ONLY)
|
||||
.unwrap();
|
||||
}
|
||||
let initial_cpu = CpuState::new(code_address, 0x8000_0000); // No stack instructions.
|
||||
let mut dbt = DbtEngine::new(1024 * 1024).unwrap();
|
||||
let mut readback = vec![0; initial.len()];
|
||||
let n = iterations as u64;
|
||||
let sum = n * VALUE + n * (n - 1) / 2;
|
||||
let mut timings = Vec::with_capacity(samples);
|
||||
let warmups = 5;
|
||||
for sample in 0..samples + warmups {
|
||||
memory.write_bytes(data, &initial).unwrap();
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let before = dbt.metrics;
|
||||
let started = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut memory, expected_instructions + 16));
|
||||
let elapsed = started.elapsed();
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt, "{label}");
|
||||
assert_eq!(
|
||||
result.instructions_executed, expected_instructions,
|
||||
"{label}"
|
||||
);
|
||||
let state = (
|
||||
cpu.get(Register::Rax),
|
||||
cpu.get(Register::Rdx),
|
||||
cpu.get(Register::Rcx),
|
||||
);
|
||||
assert_eq!(state, (sum, VALUE + n, 0), "{label}");
|
||||
memory.read_bytes(data, &mut readback).unwrap();
|
||||
assert_eq!(readback, expected, "{label}");
|
||||
assert_eq!(dbt.metrics.interpreter_fallbacks, 0, "{label}");
|
||||
if sample > 0 {
|
||||
let compiled = |m: crate::DbtMetrics| {
|
||||
(m.blocks_compiled, m.native_bytes_emitted, m.cache_misses)
|
||||
};
|
||||
assert_eq!(compiled(dbt.metrics), compiled(before), "{label}");
|
||||
if sample >= warmups {
|
||||
timings.push(elapsed.as_nanos() as f64 / n as f64);
|
||||
}
|
||||
} else {
|
||||
assert!(dbt.metrics.blocks_compiled > 0, "{label}");
|
||||
}
|
||||
}
|
||||
timings.sort_by(f64::total_cmp);
|
||||
println!(
|
||||
"warm-data label={label} regions={regions} iterations={iterations} samples={samples} warmups={warmups} instructions={expected_instructions} median_ns_per_iteration={:.3} p10={:.3} p90={:.3}",
|
||||
quantile(&timings, 0.5),
|
||||
quantile(&timings, 0.1),
|
||||
quantile(&timings, 0.9)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod mapping_group_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn aliases_preserve_bytes_across_resize_relocation_and_release() {
|
||||
const BASE: u64 = 0x0000_0003_0000_0000;
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region(BASE - 16, 8, MemoryPermissions::READ_ONLY)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(BASE, 4, MemoryPermissions::READ_ONLY, &[1, 2, 3, 4])
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(BASE + 16, 8, MemoryPermissions::READ_ONLY)
|
||||
.unwrap();
|
||||
let heap = memory.create_private_heap(0).unwrap();
|
||||
assert_eq!(memory.map_heap_allocation(PROCESS_HEAP, 0), Ok(BASE));
|
||||
assert_eq!(memory.map_heap_allocation(heap, 0), Ok(BASE));
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 8, true),
|
||||
Err(MemoryError::AllocationFailed)
|
||||
);
|
||||
assert_eq!(memory.resize_heap_allocation(heap, BASE, 8, true), Ok(BASE));
|
||||
memory.write_bytes(BASE + 4, &[5, 6, 7, 8]).unwrap();
|
||||
assert_eq!(memory.read_u64(BASE), Ok(0x0807_0605_0403_0201));
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(heap, BASE, 32, true),
|
||||
Err(MemoryError::AllocationFailed)
|
||||
);
|
||||
let moved = memory
|
||||
.resize_heap_allocation(heap, BASE, 32, false)
|
||||
.unwrap();
|
||||
assert_ne!(moved, BASE);
|
||||
let mut bytes = [0xff; 32];
|
||||
memory.read_bytes(moved, &mut bytes).unwrap();
|
||||
let mut expected = [0; 32];
|
||||
expected[4..8].copy_from_slice(&[5, 6, 7, 8]);
|
||||
assert_eq!(bytes, expected);
|
||||
let mut failed = [0xff; 8];
|
||||
assert_eq!(
|
||||
memory.read_bytes(BASE, &mut failed),
|
||||
Err(MemoryError::UnmappedAddress(BASE + 4))
|
||||
);
|
||||
assert_eq!(failed, [0xff; 8]);
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 8, true),
|
||||
Ok(BASE)
|
||||
);
|
||||
assert_eq!(memory.read_u64(BASE), Ok(0x0403_0201));
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 2, true),
|
||||
Ok(BASE)
|
||||
);
|
||||
assert_eq!(memory.read_u16(BASE + 2), Ok(0x0403));
|
||||
assert!(memory.release_heap_allocation(PROCESS_HEAP, BASE));
|
||||
assert_eq!(memory.read_u32(BASE), Ok(0x0403_0201));
|
||||
assert_eq!(memory.read_u64(BASE - 16), Ok(0));
|
||||
assert_eq!(memory.read_u64(BASE + 16), Ok(0));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod bounds_access_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn permitted_empty_spans_and_high_addresses_keep_exact_bounds() {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
u64::MAX - 8,
|
||||
8,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&[1, 2, 3, 4, 5, 6, 7, 8],
|
||||
)
|
||||
.unwrap();
|
||||
for at in [u64::MAX - 8, u64::MAX - 4, u64::MAX - 1, u64::MAX] {
|
||||
assert_eq!(memory.read_bytes(at, &mut []), Ok(()));
|
||||
assert_eq!(memory.write_bytes(at, &[]), Ok(()));
|
||||
}
|
||||
assert_eq!(memory.read_u64(u64::MAX - 8), Ok(0x0807_0605_0403_0201));
|
||||
assert_eq!(memory.read_u8(u64::MAX - 1), Ok(8));
|
||||
let mut failed = [0xee; 2];
|
||||
assert_eq!(
|
||||
memory.read_bytes(u64::MAX - 1, &mut failed),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(failed, [0xee; 2]);
|
||||
assert_eq!(
|
||||
memory.write_u16(u64::MAX - 1, 0xffff),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(memory.read_u64(u64::MAX - 7), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
memory.write_u64(u64::MAX - 7, u64::MAX),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
memory.write_u8(u64::MAX - 1, 0x99).unwrap();
|
||||
let mut actual = [0; 8];
|
||||
memory.read_bytes(u64::MAX - 8, &mut actual).unwrap();
|
||||
assert_eq!(actual, [1, 2, 3, 4, 5, 6, 7, 0x99]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod mapping_search_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn every_mapping_and_gap_keeps_its_bytes_across_table_sizes() {
|
||||
const BASE: u64 = 0x40_0000;
|
||||
for count in [0usize, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 32, 33] {
|
||||
let mut memory = GuestMemory::new();
|
||||
for index in (0..count).rev() {
|
||||
memory
|
||||
.map_region_with_data(
|
||||
BASE + index as u64 * 0x100,
|
||||
8,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&[(index + 1) as u8; 8],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
memory.read_u8(BASE - 1),
|
||||
Err(MemoryError::UnmappedAddress(BASE - 1))
|
||||
);
|
||||
if count == 0 {
|
||||
assert_eq!(
|
||||
memory.read_u8(BASE),
|
||||
Err(MemoryError::UnmappedAddress(BASE))
|
||||
);
|
||||
assert_eq!(
|
||||
memory.write_u8(BASE, 1),
|
||||
Err(MemoryError::UnmappedAddress(BASE))
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_bytes(BASE, &mut []),
|
||||
Err(MemoryError::UnmappedAddress(BASE))
|
||||
);
|
||||
}
|
||||
for index in 0..count {
|
||||
let address = BASE + index as u64 * 0x100;
|
||||
let mut actual = [0; 8];
|
||||
memory.read_bytes(address, &mut actual).unwrap();
|
||||
assert_eq!(actual, [(index + 1) as u8; 8]);
|
||||
let replacement = [0x80 + index as u8; 8];
|
||||
memory.write_bytes(address, &replacement).unwrap();
|
||||
memory.read_bytes(address, &mut actual).unwrap();
|
||||
assert_eq!(actual, replacement);
|
||||
assert_eq!(memory.read_bytes(address + 8, &mut []), Ok(()));
|
||||
assert_eq!(
|
||||
memory.read_u8(address + 8),
|
||||
Err(MemoryError::UnmappedAddress(address + 8))
|
||||
);
|
||||
let mut failed = [0xee; 2];
|
||||
assert_eq!(
|
||||
memory.read_bytes(address + 7, &mut failed),
|
||||
Err(MemoryError::UnmappedAddress(address + 8))
|
||||
);
|
||||
assert_eq!(failed, [0xee; 2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+76
-27
@@ -1,4 +1,4 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::ffi::c_void;
|
||||
use std::fmt;
|
||||
use std::mem::size_of_val;
|
||||
@@ -37,6 +37,16 @@ const MAX_GROUPS: usize = 64;
|
||||
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
|
||||
const MAX_SOURCE_BYTES: usize = 64 * 1024;
|
||||
const MAX_IN_FLIGHT: usize = 16;
|
||||
const MAX_CACHED_PIPELINES: usize = 16;
|
||||
|
||||
type ComputePipeline = Retained<ProtocolObject<dyn MTLComputePipelineState>>;
|
||||
|
||||
struct CachedPipeline {
|
||||
source: Box<str>,
|
||||
entry: Box<str>,
|
||||
shader_validation: bool,
|
||||
pipeline: ComputePipeline,
|
||||
}
|
||||
|
||||
const BC_READBACK: &str = r"
|
||||
#include <metal_stdlib>
|
||||
@@ -148,7 +158,9 @@ impl std::error::Error for MetalError {}
|
||||
/// measure a single submission and are not a benchmark distribution.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunProfile {
|
||||
/// Host library compilation time, or zero when reusing a compute pipeline.
|
||||
pub library_seconds: f64,
|
||||
/// Host pipeline creation time, or zero when reusing a compute pipeline.
|
||||
pub pipeline_seconds: f64,
|
||||
pub gpu_seconds: f64,
|
||||
/// Host wall time from the start of setup until wait observes completion.
|
||||
@@ -171,6 +183,8 @@ pub struct NativeCompute {
|
||||
device: Retained<ProtocolObject<dyn MTLDevice>>,
|
||||
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
|
||||
submissions: Mutex<SubmissionTable>,
|
||||
// Least recently used first. In-flight submissions retain their own reference.
|
||||
compute_pipelines: Mutex<VecDeque<CachedPipeline>>,
|
||||
}
|
||||
|
||||
/// A submitted dispatch whose result can be collected by its issuing context.
|
||||
@@ -247,7 +261,7 @@ struct SubmissionEntry {
|
||||
/// Metal reports Completed or Error.
|
||||
struct InFlightResources {
|
||||
command: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
|
||||
_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
|
||||
_pipeline: ComputePipeline,
|
||||
_input: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
|
||||
output: Retained<ProtocolObject<dyn MTLBuffer>>,
|
||||
_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
|
||||
@@ -348,6 +362,7 @@ impl NativeCompute {
|
||||
device,
|
||||
queue,
|
||||
submissions: Mutex::default(),
|
||||
compute_pipelines: Mutex::default(),
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -901,7 +916,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
self.run_profiled_words(source, entry, input, Some(width))
|
||||
}
|
||||
|
||||
/// Compile the kernel and report the smaller of the device and pipeline width limits.
|
||||
/// Find or compile the kernel and report the smaller of the device and pipeline width limits.
|
||||
///
|
||||
/// Input size and threadgroup count are checked separately at dispatch.
|
||||
///
|
||||
@@ -911,11 +926,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
pub fn max_group_width(&self, source: &str, entry: &str) -> Result<usize, MetalError> {
|
||||
validate_source(source, &[entry])?;
|
||||
autoreleasepool(|_| {
|
||||
let options = compile_options()?;
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
verify_shader_validation(&pipeline)?;
|
||||
let (pipeline, _, _) = self.prepare_compute_pipeline(source, entry)?;
|
||||
Ok(self.pipeline_group_width_limit(&pipeline))
|
||||
})
|
||||
}
|
||||
@@ -963,15 +974,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
host_start: Instant,
|
||||
) -> Result<Submission<'_>, MetalError> {
|
||||
self.submissions().check_capacity()?;
|
||||
let options = compile_options()?;
|
||||
let library_start = Instant::now();
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let library_seconds = library_start.elapsed().as_secs_f64();
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline_start = Instant::now();
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
|
||||
verify_shader_validation(&pipeline)?;
|
||||
let (pipeline, library_seconds, pipeline_seconds) =
|
||||
self.prepare_compute_pipeline(source, entry)?;
|
||||
|
||||
let limit = self.pipeline_group_width_limit(&pipeline);
|
||||
let width = match group_width {
|
||||
@@ -1108,18 +1112,67 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
})
|
||||
}
|
||||
|
||||
fn compute_pipeline(
|
||||
fn prepare_compute_pipeline(
|
||||
&self,
|
||||
function: &ProtocolObject<dyn MTLFunction>,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
|
||||
self.device
|
||||
.newComputePipelineStateWithFunction_error(function)
|
||||
source: &str,
|
||||
entry: &str,
|
||||
) -> Result<(ComputePipeline, f64, f64), MetalError> {
|
||||
let shader_validation = std::env::var("MTL_SHADER_VALIDATION").as_deref() == Ok("1");
|
||||
// Device identity is fixed by this context. All misses use the same
|
||||
// compile options (safe math, precise functions, default language,
|
||||
// no macros) and unspecialized functions. Any configurable options
|
||||
// must become part of the key before they are used here.
|
||||
let mut cache = self
|
||||
.compute_pipelines
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(index) = cache.iter().position(|cached| {
|
||||
cached.source.as_ref() == source
|
||||
&& cached.entry.as_ref() == entry
|
||||
&& cached.shader_validation == shader_validation
|
||||
}) {
|
||||
let cached = cache.remove(index).expect("position in the locked cache");
|
||||
let pipeline = cached.pipeline.clone();
|
||||
cache.push_back(cached);
|
||||
return Ok((pipeline, 0.0, 0.0));
|
||||
}
|
||||
|
||||
// Serialize cache misses in this context so concurrent requests for
|
||||
// one key share the same build. The submission table is unlocked here.
|
||||
let options = compile_options()?;
|
||||
let library_start = Instant::now();
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let library_seconds = library_start.elapsed().as_secs_f64();
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline_start = Instant::now();
|
||||
let pipeline = self
|
||||
.device
|
||||
.newComputePipelineStateWithFunction_error(&function)
|
||||
.map_err(|error| {
|
||||
MetalError::new(
|
||||
"newComputePipelineStateWithFunction",
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})
|
||||
})?;
|
||||
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
|
||||
if shader_validation {
|
||||
verify_shader_validation(&pipeline)?;
|
||||
}
|
||||
|
||||
// Bound owned key text to 1 MiB. A valid oversized key can run
|
||||
// uncached, so this budget does not alter source or entry validation.
|
||||
if entry.len() <= MAX_SOURCE_BYTES.saturating_sub(source.len()) {
|
||||
if cache.len() == MAX_CACHED_PIPELINES {
|
||||
cache.pop_front();
|
||||
}
|
||||
cache.push_back(CachedPipeline {
|
||||
source: source.into(),
|
||||
entry: entry.into(),
|
||||
shader_validation,
|
||||
pipeline: pipeline.clone(),
|
||||
});
|
||||
}
|
||||
Ok((pipeline, library_seconds, pipeline_seconds))
|
||||
}
|
||||
|
||||
fn pipeline_group_width_limit(
|
||||
@@ -1232,10 +1285,6 @@ fn check_command_status(
|
||||
fn verify_shader_validation(
|
||||
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
|
||||
) -> Result<(), MetalError> {
|
||||
if std::env::var("MTL_SHADER_VALIDATION").as_deref() != Ok("1") {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !pipeline.respondsToSelector(sel!(shaderValidation)) {
|
||||
return Err(MetalError::new(
|
||||
"shaderValidation",
|
||||
|
||||
@@ -356,6 +356,131 @@ fn multiple_submissions() {
|
||||
assert_eq!(second, [5, 5, 1, 5]);
|
||||
}
|
||||
|
||||
fn pipeline_was_reused(profile: &xenora_metal::RunProfile) -> bool {
|
||||
profile.library_seconds == 0.0 && profile.pipeline_seconds == 0.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pipeline_cache_distinguishes_source_entry_and_context() {
|
||||
let context = context();
|
||||
let source = fixture("output[id] = input[id] + 1u;");
|
||||
let second_entry =
|
||||
fixture("output[id] = input[id] * 2u;").replace("void fixture(", "void other(");
|
||||
let source = format!("{source}\n{second_entry}");
|
||||
let changed = source.replace("input[id] + 1u", "input[id] - 1u");
|
||||
let input = [0, 11, u32::MAX];
|
||||
|
||||
for (msl, entry, expected) in [
|
||||
(source.as_str(), "fixture", [1, 12, 0]),
|
||||
(source.as_str(), "other", [0, 22, u32::MAX - 1]),
|
||||
(changed.as_str(), "fixture", [u32::MAX, 10, u32::MAX - 1]),
|
||||
] {
|
||||
let cold = native(context.run_words_profiled(msl, entry, &input));
|
||||
let warm = native(context.run_words_profiled(msl, entry, &input));
|
||||
assert!(!pipeline_was_reused(&cold), "{entry}");
|
||||
assert!(pipeline_was_reused(&warm), "{entry}");
|
||||
assert_eq!(cold.output, expected, "{entry}");
|
||||
assert_eq!(warm.output, expected, "{entry}");
|
||||
}
|
||||
let separate = native(NativeCompute::new());
|
||||
let fresh = native(separate.run_words_profiled(&source, "fixture", &input));
|
||||
assert!(!pipeline_was_reused(&fresh));
|
||||
assert_eq!(fresh.output, [1, 12, 0]);
|
||||
|
||||
for _ in 0..2 {
|
||||
for (msl, entry, operation) in [
|
||||
(source.as_str(), "missing", "newFunctionWithName"),
|
||||
("not valid MSL", "fixture", "newLibraryWithSource"),
|
||||
] {
|
||||
let error = context
|
||||
.run_words_profiled(msl, entry, &input)
|
||||
.expect_err("invalid pipeline must still fail after warming the cache");
|
||||
assert_eq!(error.operation, operation);
|
||||
}
|
||||
}
|
||||
let error = context
|
||||
.run_words_with_group_width(&source, "fixture", &input, 0)
|
||||
.expect_err("cached pipeline must still check dispatch width");
|
||||
assert_eq!(error.operation, "threadgroup width");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pipeline_cache_bounds_key_bytes_without_rejecting_maximum_source() {
|
||||
const SOURCE_LIMIT: usize = 64 * 1024;
|
||||
let context = context();
|
||||
let mut source = fixture("output[id] = input[id] ^ 1u;");
|
||||
source.push_str("\n// ");
|
||||
source.push_str(&" ".repeat(SOURCE_LIMIT - source.len()));
|
||||
|
||||
for _ in 0..2 {
|
||||
let profile = native(context.run_words_profiled(&source, "fixture", &[8]));
|
||||
assert_eq!(profile.output, [9]);
|
||||
assert!(!pipeline_was_reused(&profile));
|
||||
}
|
||||
source.push(' ');
|
||||
let error = context
|
||||
.run_words_profiled(&source, "fixture", &[8])
|
||||
.expect_err("source above 64 KiB must fail before pipeline lookup");
|
||||
assert_eq!(error.operation, "source bounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pipeline_cache_evicts_oldest_unused_key_and_keeps_pending_work_alive() {
|
||||
let context = context();
|
||||
// Seventeen entries in one source fit in Metal's input limit and exceed
|
||||
// Xenora's 16-pipeline cache. Each kernel writes a distinct result.
|
||||
let source: String = (0..=16)
|
||||
.map(|id| {
|
||||
fixture(&format!("output[id] = input[id] + {id}u;"))
|
||||
.replace("void fixture(", &format!("void entry{id}("))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
native(context.max_group_width(&source, "entry0"));
|
||||
let (pending, gate) = native(context.submit_words_gated(&source, "entry1", &[7]));
|
||||
for id in 2..16 {
|
||||
native(context.max_group_width(&source, &format!("entry{id}")));
|
||||
}
|
||||
native(context.max_group_width(&source, "entry0"));
|
||||
native(context.max_group_width(&source, "entry16"));
|
||||
gate.open();
|
||||
let finished = native(context.wait(pending));
|
||||
assert_eq!(finished.output, [8]);
|
||||
|
||||
let recent = native(context.run_words_profiled(&source, "entry0", &[29]));
|
||||
assert!(pipeline_was_reused(&recent));
|
||||
assert_eq!(recent.output, [29]);
|
||||
let rebuilt = native(context.run_words_profiled(&source, "entry1", &[17]));
|
||||
assert!(!pipeline_was_reused(&rebuilt));
|
||||
assert_eq!(rebuilt.output, [18]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simultaneous_compute_submissions_share_one_pipeline_build() {
|
||||
let context = context();
|
||||
let source = fixture("output[id] = input[id] ^ 5u;");
|
||||
let start = std::sync::Barrier::new(4);
|
||||
std::thread::scope(|scope| {
|
||||
let workers: Vec<_> = (0..4)
|
||||
.map(|input| {
|
||||
let (context, source, start) = (&context, &source, &start);
|
||||
scope.spawn(move || {
|
||||
start.wait();
|
||||
let token = native(context.submit_words(source, "fixture", &[input]));
|
||||
let result = native(context.wait(token));
|
||||
assert_eq!(result.output, [input ^ 5]);
|
||||
usize::from(!pipeline_was_reused(&result))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let builds: usize = workers
|
||||
.into_iter()
|
||||
.map(|worker| worker.join().unwrap())
|
||||
.sum();
|
||||
assert_eq!(builds, 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_propagate() {
|
||||
let context = context();
|
||||
@@ -413,3 +538,52 @@ kernel void fixture(device const uint *input [[buffer(0)]],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual GPU timing run"]
|
||||
fn compute_pipeline_reuse_benchmark() {
|
||||
const WARMUPS: usize = 10;
|
||||
const SAMPLES: usize = 101;
|
||||
let warm_context = context();
|
||||
let device = warm_context.device_name();
|
||||
let source = fixture("output[id] = input[id] * 7u + 3u;");
|
||||
let input = mixing_input(131);
|
||||
let expected: Vec<_> = input
|
||||
.iter()
|
||||
.map(|word| word.wrapping_mul(7).wrapping_add(3))
|
||||
.collect();
|
||||
let mut timings = [[[0.0; SAMPLES]; 4]; 2];
|
||||
|
||||
for round in 0..WARMUPS + SAMPLES {
|
||||
let cold_context = context();
|
||||
// Alternate order so neither measurement always follows the other.
|
||||
let contexts = [&cold_context, &warm_context];
|
||||
for index in [round % 2, (round + 1) % 2] {
|
||||
let profile = native(contexts[index].run_words_profiled(&source, "fixture", &input));
|
||||
assert_eq!(profile.output, expected, "context={index} round={round}");
|
||||
if round >= WARMUPS {
|
||||
for (samples, seconds) in timings[index].iter_mut().zip([
|
||||
profile.library_seconds,
|
||||
profile.pipeline_seconds,
|
||||
profile.host_seconds,
|
||||
profile.gpu_seconds,
|
||||
]) {
|
||||
samples[round - WARMUPS] = seconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (label, [mut library, mut pipeline, mut host, mut gpu]) in
|
||||
["fresh context", "repeated context"]
|
||||
.into_iter()
|
||||
.zip(timings)
|
||||
{
|
||||
println!(
|
||||
"device={device} {label} samples={SAMPLES} library_us[{}] pipeline_us[{}] host_us[{}] gpu_us[{}]",
|
||||
timing_summary(&mut library),
|
||||
timing_summary(&mut pipeline),
|
||||
timing_summary(&mut host),
|
||||
timing_summary(&mut gpu),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,43 @@ export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4}
|
||||
# allow slower hosts to raise it without editing the script.
|
||||
export XENORA_SEMANTIC_TIMEOUT=${XENORA_SEMANTIC_TIMEOUT:-300s}
|
||||
|
||||
# macOS does not ship GNU timeout. Python 3 is already a project requirement,
|
||||
# so use a small POSIX-compatible fallback rather than making coreutils a
|
||||
# prerequisite for the native suite.
|
||||
if ! command -v timeout >/dev/null 2>&1; then
|
||||
timeout() {
|
||||
duration=$1
|
||||
shift
|
||||
python3 - "$duration" "$@" <<'PY'
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
text = sys.argv[1]
|
||||
match = re.fullmatch(r"(\d+(?:\.\d+)?)([smh]?)", text)
|
||||
if match is None:
|
||||
print(f"timeout: invalid duration {text!r}", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
seconds = float(match.group(1)) * {"": 1, "s": 1, "m": 60, "h": 3600}[match.group(2)]
|
||||
try:
|
||||
process = subprocess.Popen(sys.argv[2:], start_new_session=True)
|
||||
except FileNotFoundError as error:
|
||||
print(f"timeout: {error}", file=sys.stderr)
|
||||
raise SystemExit(127)
|
||||
try:
|
||||
code = process.wait(timeout=seconds)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
print(f"timeout: command exceeded {seconds:g} seconds", file=sys.stderr)
|
||||
raise SystemExit(124)
|
||||
raise SystemExit(code)
|
||||
PY
|
||||
}
|
||||
fi
|
||||
|
||||
cargo test --locked -p xenora-metal --features gpu-tests --test native_compute --no-run
|
||||
timeout 30s cargo test --locked -p xenora-metal --features gpu-tests --test native_compute -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
Reference in new issue
Block a user