Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4736b193da | ||
|
|
d7d24c7401 | ||
|
|
fb3ce6e8c5 | ||
|
|
63a56772da | ||
|
|
b848e433a3 | ||
|
|
3aea854d41 | ||
|
|
3a478b603c | ||
|
|
0383253c60 | ||
|
|
7e61ab8007 |
@@ -1,20 +1,29 @@
|
||||
name: Desktop foundation
|
||||
on:
|
||||
push:
|
||||
paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml']
|
||||
# Main pushes exclude CLI release tags; feature branches use pull requests.
|
||||
branches: [main]
|
||||
paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml', 'scripts/install-pinned-rustup.sh', 'Cargo.toml', 'Cargo.lock']
|
||||
pull_request:
|
||||
paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml']
|
||||
paths: ['desktop-core/**', 'desktop/**', '.github/workflows/desktop.yml', 'rust-toolchain.toml', 'scripts/install-pinned-rustup.sh', 'Cargo.toml', 'Cargo.lock']
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
core:
|
||||
env:
|
||||
CARGO_TARGET_DIR: ${{ github.workspace }}/desktop-core/target
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
# Windows/macOS validation is deferred and unqualified.
|
||||
os: [ubuntu-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Linux build tools
|
||||
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates build-essential python3 python-is-python3
|
||||
- name: Install pinned Rust
|
||||
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
|
||||
- name: Format
|
||||
run: cargo fmt --manifest-path desktop-core/Cargo.toml --check
|
||||
- name: Tests
|
||||
|
||||
@@ -33,11 +33,13 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install build tools
|
||||
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake ninja-build g++ python3-numpy
|
||||
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y cmake ninja-build g++ python3-numpy docker.io
|
||||
- name: Install pinned Rust
|
||||
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
|
||||
- name: Local checks
|
||||
run: scripts/check-local.sh
|
||||
- name: GPU-hidden fixed PTX assembly
|
||||
run: scripts/test-cuda-fixed-ptx.sh
|
||||
|
||||
keyless-cuda-gate:
|
||||
if: gitea.event_name == 'workflow_dispatch'
|
||||
@@ -479,12 +481,41 @@ jobs:
|
||||
command -v docker >/dev/null 2>&1 || { apt-get update -qq; DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker.io; }
|
||||
docker version
|
||||
- name: Build actual CLI-only scratch image
|
||||
run: docker build --file deploy/Dockerfile.static-cli --tag strata-cli-check .
|
||||
run: |
|
||||
set -euo pipefail
|
||||
owned_dir="$(mktemp -d "$RUNNER_TEMP/leleka-cli-check-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}-XXXXXX")"
|
||||
image_tag="leleka-cli-check:${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}-${owned_dir##*-}"
|
||||
printf '%s\n' "CLI_CHECK_DIR=$owned_dir" "CLI_CHECK_TAG=$image_tag" >> "$GITHUB_ENV"
|
||||
# The nonce label makes identical builds distinct image configs on the shared daemon.
|
||||
docker build --file deploy/Dockerfile.static-cli --tag "$image_tag" \
|
||||
--label "io.leleka.ci.cli-check-owner=$image_tag" --iidfile "$owned_dir/image.iid" .
|
||||
image="$(cat "$owned_dir/image.iid")"
|
||||
[[ "$image" =~ ^sha256:[0-9a-f]{64}$ ]]
|
||||
test "$(docker image inspect --format '{{ index .Config.Labels "io.leleka.ci.cli-check-owner" }}' "$image")" = "$image_tag"
|
||||
- name: Check isolated CLI container startup and shutdown
|
||||
run: python3 scripts/smoke-cli-container.py strata-cli-check
|
||||
run: |
|
||||
set -euo pipefail
|
||||
image="$(cat "$CLI_CHECK_DIR/image.iid")"
|
||||
[[ "$image" =~ ^sha256:[0-9a-f]{64}$ ]]
|
||||
test "$(docker image inspect --format '{{ index .Config.Labels "io.leleka.ci.cli-check-owner" }}' "$image")" = "$CLI_CHECK_TAG"
|
||||
python3 scripts/smoke-cli-container.py "$image"
|
||||
- name: Remove test image
|
||||
if: always()
|
||||
run: docker image rm strata-cli-check || true
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -n "${CLI_CHECK_DIR:-}" || exit 0
|
||||
trap 'rm -f -- "$CLI_CHECK_DIR/image.iid"; rmdir -- "$CLI_CHECK_DIR"' EXIT
|
||||
if test -s "$CLI_CHECK_DIR/image.iid"; then
|
||||
image="$(cat "$CLI_CHECK_DIR/image.iid")"
|
||||
else
|
||||
# A failed build may leave the owned tag without writing an IID receipt.
|
||||
image="$(docker image inspect --format '{{.Id}}' "$CLI_CHECK_TAG" 2>/dev/null || true)"
|
||||
fi
|
||||
test -n "$image" || exit 0
|
||||
[[ "$image" =~ ^sha256:[0-9a-f]{64}$ ]]
|
||||
test "$(docker image inspect --format '{{ index .Config.Labels "io.leleka.ci.cli-check-owner" }}' "$image")" = "$CLI_CHECK_TAG"
|
||||
# No force or parent pruning: cleanup cannot remove other jobs' references or cache.
|
||||
docker image rm --no-prune "$image"
|
||||
|
||||
release-cli:
|
||||
permissions:
|
||||
|
||||
Generated
+7
@@ -1007,6 +1007,13 @@ dependencies = [
|
||||
name = "leleka-backend-api"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "leleka-cuda-driver"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leleka-model-format"
|
||||
version = "0.1.0"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "control-plane", "desktop-core"]
|
||||
members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "crates/cuda-driver", "control-plane", "desktop-core"]
|
||||
default-members = ["crates/backend-api", "crates/tokenizer", "crates/model-format", "crates/quant-core", "control-plane", "desktop-core"]
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -9,6 +9,72 @@ Store future benchmark definitions and sanitized fixtures in Git; place generate
|
||||
`fixtures/chat/paired-smoke.json` contains public synthetic arithmetic, retrieval, and function-call prompts. Run `scripts/bench-chat-paired.py` from the repository root. It sends one untimed warmup per case and endpoint, then alternates baseline/candidate order over repeated, sequential requests with the same model, prompt, greedy sampling settings, and token cap. It checks each response's terminal `finish_reason` and case-specific text or tool arguments. The report includes per-case pass counts, raw response timings, and paired wall-time ratios. The full response report is written only to a new private path outside Git with mode 0600; API keys are read from private server config files and omitted from the report.
|
||||
|
||||
For the current upstream server, pass its full bound URL as `--baseline-url`, its `/health` URL as `--baseline-ready-url`, the configured model name as `--model`, and its private JSON config as `--baseline-auth-config`. The readiness poll waits for a nonzero `max_context` because upstream can report `loaded: true` during loading. Once a compressed inference endpoint exists, pass its URL as `--candidate-url` and optionally `--candidate-ready-url`. A baseline-only run is a functional check and cannot establish a speedup. Even a paired run of this small synthetic suite is only a smoke test: the charter's long-context, real-agent, cache-state, and model-quality gates still require separate runs. Record engine/config digests, GPU, driver, CUDA, power settings, and artifact digests in a private `--metadata` JSON for any reported performance result. Never commit the report or private config.
|
||||
|
||||
## Offline comparison of sequential Chat reports
|
||||
|
||||
When two model arms cannot fit together, compare two **single-arm** schema-1
|
||||
reports from the same suite/model/configuration. A standalone harness run may
|
||||
label its rows `baseline` in both files; the filenames select the comparison
|
||||
arms. Each file must contain one arm, exactly one warmup per case and the full
|
||||
declared repeat range. Missing or duplicate pairs, category drift, malformed
|
||||
rows, nonfinite numbers and inconsistent successful HTTP/terminal/quality
|
||||
claims fail before any comparison is published. Genuine observed quality or
|
||||
HTTP failures remain explicit data, with failed categories reported separately.
|
||||
|
||||
```sh
|
||||
python3 -B scripts/compare-chat-reports.py \
|
||||
/private/evaluation/baseline.json /private/evaluation/candidate.json \
|
||||
--output /private/evaluation/comparison.json
|
||||
python3 -B scripts/render-paired-report.py /private/evaluation/comparison.json \
|
||||
--output /private/evaluation/comparison.md
|
||||
```
|
||||
|
||||
JSON and Markdown outputs must be new files outside Git and use mode 0600;
|
||||
neither overwrites an existing file. The comparator prints fixed aggregate
|
||||
counts only, without case labels, response text, tool arguments or metadata.
|
||||
Markdown omits raw responses, tool arguments and metadata values. Private
|
||||
metadata remains in the private JSON for reproducibility.
|
||||
|
||||
Existing schema-1 median fields remain available. Overall, category and case
|
||||
groups additionally contain mean, median, linearly interpolated p10/p90 and
|
||||
sample counts for both arms' wall times and positive paired prefill/decode
|
||||
rates. Ratios are calculated **within each pair**, then summarized; they are
|
||||
not ratios of arm medians. Zero token rates (for example fully cached prefill)
|
||||
and missing timings never become divisions by zero: `timing_coverage` and
|
||||
`unavailable_pairs` disclose their exclusion, while a wholly unavailable
|
||||
throughput summary stays `null`. Counts must be nonnegative integers; timing
|
||||
values must be finite/nonnegative and measured wall times strictly positive.
|
||||
|
||||
Ratio uncertainty uses a deterministic distribution-free, two-sided 95%
|
||||
confidence interval for the population **median paired ratio**, selected from
|
||||
order statistics with exact binomial coverage. This bounds work without a
|
||||
bootstrap dependency or random seed. Fewer than six pairs cannot yield a finite
|
||||
95% interval and receive `null` bounds; fewer than 30 pairs receive an explicit
|
||||
small-sample flag. The interval assumes independent pairs sharing a population
|
||||
median; sequential cache/load drift and correlated repeats can invalidate that
|
||||
assumption. Category/overall mixtures also depend on case composition. The
|
||||
interval does not measure those systematic errors or uncertainty in the mean.
|
||||
|
||||
The report names missing charter provenance fields without echoing their
|
||||
values: `engine_commit`, `control_plane_commit`, `model_sha256`, `quantization`,
|
||||
`gpu`, `driver`, `cuda_toolkit`, `power_limit_watts`, `context_tokens`,
|
||||
`kv_configuration`, `slots`, `batch_size`, `speculation`, `cache_state`,
|
||||
`workload_sha256`, `quality_gate_result`, `draft_acceptance_rate`,
|
||||
`expert_cache_hit_rate`, `kv_streaming_hit_rate`; measured TTFT and prompt/output
|
||||
token-count coverage are checked separately. Unavailable/not-applicable metrics
|
||||
should be explained in private provenance; a declaration is not a measurement.
|
||||
Conflicting declared hardware, model source, context/KV/slot/batch/speculation,
|
||||
cache or workload identity refuses pairing. Engine/control-plane/codec version
|
||||
changes can be the intended comparison, but must be recorded for each arm.
|
||||
|
||||
Inputs are bounded to 32 MiB each, 64 cases, 4,096 measured pairs, 100 repeats
|
||||
per case, JSON depth 32 and one million JSON nodes. Timing/count magnitudes are
|
||||
bounded to 10^12. Split larger suites deliberately instead of silently dropping
|
||||
rows. JSON statistics and the Markdown rendering remain **descriptive**:
|
||||
sequential runs, synthetic CPU fixtures, complete metadata or passing smoke
|
||||
checks never automatically qualify GPU inference, model quality or an
|
||||
end-to-end agent performance improvement. Those charter gates remain separate.
|
||||
|
||||
# Live Responses episode replay
|
||||
|
||||
`scripts/replay-live-responses.py` is an offline evaluator for an **explicitly
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "leleka-cuda-driver"
|
||||
version = "0.1.0"
|
||||
description = "Opt-in bounded CUDA Driver context and byte-buffer foundation"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
cuda-driver = []
|
||||
|
||||
[target.'cfg(all(target_os = "linux", target_pointer_width = "64"))'.dependencies]
|
||||
libc = "=0.2.190"
|
||||
|
||||
# The workspace unsafe forbid remains unchanged. Only private ffi.rs may allow
|
||||
# unsafe code; all other modules deny it, and unsafe operations require blocks.
|
||||
[lints.rust]
|
||||
unsafe_code = "deny"
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
|
||||
[lints.clippy]
|
||||
all = "warn"
|
||||
@@ -0,0 +1,445 @@
|
||||
//! Private audited C ABI boundary. No host or device pointers are exported.
|
||||
//! Behavior references: CUDA Driver API archive 13.0.1 context management,
|
||||
//! memory management, and api-sync-behavior.html. Exact create/pointer ABI was
|
||||
//! checked against the official pinned CUDA 13.0.88 cuda.h (line 25633 declares
|
||||
//! cuCtxCreate_v2 with THREE arguments; line 90 maps today's cuCtxCreate alias
|
||||
//! to cuCtxCreate_v4; line 274 defines the 64-bit CUdeviceptr). This header is
|
||||
//! verification evidence only and is not a production dependency. Do not infer
|
||||
//! a fixed export ABI from the newer alias.
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct ContextHandle(usize);
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct BufferHandle(u64);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ModuleHandle(usize);
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct FunctionHandle(usize);
|
||||
|
||||
struct ArgumentStorage {
|
||||
addresses: [u64; 3],
|
||||
count: u32,
|
||||
parameters: [*mut std::ffi::c_void; 4],
|
||||
}
|
||||
// Convert the allocation to raw ownership BEFORE forming field pointers.
|
||||
// A later move or mutable borrow of a Box must not retag/invalidate pointers
|
||||
// derived from it (std::boxed unsafe-code considerations). This owner moves
|
||||
// only a NonNull value; it never creates a reference to the pointed-to storage.
|
||||
// Drop reconstructs the Box once, after completion or before any launch attempt.
|
||||
pub(crate) struct LaunchArguments {
|
||||
storage: std::ptr::NonNull<ArgumentStorage>,
|
||||
}
|
||||
impl LaunchArguments {
|
||||
pub(crate) fn new(a: BufferHandle, b: BufferHandle, output: BufferHandle, count: u32) -> Self {
|
||||
let storage = Box::into_raw(Box::new(ArgumentStorage {
|
||||
addresses: [a.0, b.0, output.0],
|
||||
count,
|
||||
parameters: [std::ptr::null_mut(); 4],
|
||||
}));
|
||||
// SAFETY: the non-null allocation is now uniquely raw-owned and stable.
|
||||
// Initialize all self-referential pointers without borrowing/moving a
|
||||
// Box or creating new references to the entire allocation.
|
||||
unsafe {
|
||||
for i in 0..3 {
|
||||
(*storage).parameters[i] = (&raw mut (*storage).addresses[i]).cast();
|
||||
}
|
||||
(*storage).parameters[3] = (&raw mut (*storage).count).cast();
|
||||
}
|
||||
Self {
|
||||
storage: std::ptr::NonNull::new(storage).expect("Box allocation is non-null"),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for LaunchArguments {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: exactly one owner reconstructs this Box. The caller only
|
||||
// permits Drop before a launch or after successful synchronization;
|
||||
// ambiguous completion forgets this owner and retains the allocation.
|
||||
unsafe {
|
||||
drop(Box::from_raw(self.storage.as_ptr()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
feature = "cuda-driver",
|
||||
target_os = "linux",
|
||||
target_pointer_width = "64"
|
||||
))]
|
||||
mod enabled {
|
||||
use super::*;
|
||||
use libc::{c_int, c_uint, c_void};
|
||||
|
||||
type CuResult = c_int;
|
||||
type CuDevice = c_int;
|
||||
type CuContext = *mut c_void;
|
||||
type CuDevicePtr = u64;
|
||||
type Init = unsafe extern "C" fn(c_uint) -> CuResult;
|
||||
type DriverGetVersion = unsafe extern "C" fn(*mut c_int) -> CuResult;
|
||||
type DeviceGet = unsafe extern "C" fn(*mut CuDevice, c_int) -> CuResult;
|
||||
type ContextCreateV2 = unsafe extern "C" fn(*mut CuContext, c_uint, CuDevice) -> CuResult;
|
||||
type ContextDestroyV2 = unsafe extern "C" fn(CuContext) -> CuResult;
|
||||
type ContextPushCurrentV2 = unsafe extern "C" fn(CuContext) -> CuResult;
|
||||
type ContextPopCurrentV2 = unsafe extern "C" fn(*mut CuContext) -> CuResult;
|
||||
type ContextSynchronize = unsafe extern "C" fn() -> CuResult;
|
||||
type MemAllocV2 = unsafe extern "C" fn(*mut CuDevicePtr, usize) -> CuResult;
|
||||
type MemFreeV2 = unsafe extern "C" fn(CuDevicePtr) -> CuResult;
|
||||
type MemcpyHtoDV2 = unsafe extern "C" fn(CuDevicePtr, *const c_void, usize) -> CuResult;
|
||||
type ModuleLoadData = unsafe extern "C" fn(*mut *mut c_void, *const c_void) -> CuResult;
|
||||
type ModuleGetFunction =
|
||||
unsafe extern "C" fn(*mut *mut c_void, *mut c_void, *const libc::c_char) -> CuResult;
|
||||
type ModuleUnload = unsafe extern "C" fn(*mut c_void) -> CuResult;
|
||||
type LaunchKernel = unsafe extern "C" fn(
|
||||
*mut c_void,
|
||||
c_uint,
|
||||
c_uint,
|
||||
c_uint,
|
||||
c_uint,
|
||||
c_uint,
|
||||
c_uint,
|
||||
c_uint,
|
||||
*mut c_void,
|
||||
*mut *mut c_void,
|
||||
*mut *mut c_void,
|
||||
) -> CuResult;
|
||||
static FIXED_PTX: &[u8] = concat!(include_str!("vector_add.ptx"), "\0").as_bytes();
|
||||
type MemcpyDtoHV2 = unsafe extern "C" fn(*mut c_void, CuDevicePtr, usize) -> CuResult;
|
||||
|
||||
struct Library(*mut c_void);
|
||||
impl Drop for Library {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: this is the successful dlopen handle, owned exactly once.
|
||||
// All loaded functions live in Api alongside this Library. Driver
|
||||
// owner borrows retain Api through all resource operations/cleanup.
|
||||
unsafe {
|
||||
libc::dlclose(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Api {
|
||||
_library: Library,
|
||||
init: Init,
|
||||
version: DriverGetVersion,
|
||||
device: DeviceGet,
|
||||
create: ContextCreateV2,
|
||||
destroy: ContextDestroyV2,
|
||||
push: ContextPushCurrentV2,
|
||||
pop: ContextPopCurrentV2,
|
||||
synchronize: ContextSynchronize,
|
||||
allocate: MemAllocV2,
|
||||
free: MemFreeV2,
|
||||
copy_from: MemcpyHtoDV2,
|
||||
copy_to: MemcpyDtoHV2,
|
||||
load_module: ModuleLoadData,
|
||||
get_function: ModuleGetFunction,
|
||||
unload_module: ModuleUnload,
|
||||
launch_kernel: LaunchKernel,
|
||||
}
|
||||
fn check(operation: &'static str, code: CuResult) -> Result<()> {
|
||||
if code == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Driver { operation, code })
|
||||
}
|
||||
}
|
||||
impl Api {
|
||||
pub(crate) fn load() -> Result<Self> {
|
||||
// SAFETY: a fixed NUL-terminated soname, no caller-provided paths;
|
||||
// immediate local symbol resolution, with null checked before use.
|
||||
let handle = unsafe {
|
||||
libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL)
|
||||
};
|
||||
if handle.is_null() {
|
||||
return Err(Error::LibraryUnavailable);
|
||||
}
|
||||
let library = Library(handle);
|
||||
macro_rules! symbol {
|
||||
($name:literal, $ty:ty) => {{
|
||||
// SAFETY: valid owned library handle and static C name.
|
||||
let address = unsafe { libc::dlsym(library.0, $name.as_ptr()) };
|
||||
if address.is_null() {
|
||||
return Err(Error::MissingSymbol(
|
||||
$name.to_str().expect("static ASCII symbol"),
|
||||
));
|
||||
}
|
||||
// SAFETY: the fixed ABI name is paired with its exact
|
||||
// documented signature. Linux64 supports dlsym function
|
||||
// addresses; no generic or caller-selected reinterpretation.
|
||||
unsafe { std::mem::transmute::<*mut c_void, $ty>(address) }
|
||||
}};
|
||||
}
|
||||
let init = symbol!(c"cuInit", Init);
|
||||
let version = symbol!(c"cuDriverGetVersion", DriverGetVersion);
|
||||
let device = symbol!(c"cuDeviceGet", DeviceGet);
|
||||
let create = symbol!(c"cuCtxCreate_v2", ContextCreateV2);
|
||||
let destroy = symbol!(c"cuCtxDestroy_v2", ContextDestroyV2);
|
||||
let push = symbol!(c"cuCtxPushCurrent_v2", ContextPushCurrentV2);
|
||||
let pop = symbol!(c"cuCtxPopCurrent_v2", ContextPopCurrentV2);
|
||||
let synchronize = symbol!(c"cuCtxSynchronize", ContextSynchronize);
|
||||
let allocate = symbol!(c"cuMemAlloc_v2", MemAllocV2);
|
||||
let free = symbol!(c"cuMemFree_v2", MemFreeV2);
|
||||
let copy_from = symbol!(c"cuMemcpyHtoD_v2", MemcpyHtoDV2);
|
||||
let copy_to = symbol!(c"cuMemcpyDtoH_v2", MemcpyDtoHV2);
|
||||
let load_module = symbol!(c"cuModuleLoadData", ModuleLoadData);
|
||||
let get_function = symbol!(c"cuModuleGetFunction", ModuleGetFunction);
|
||||
let unload_module = symbol!(c"cuModuleUnload", ModuleUnload);
|
||||
let launch_kernel = symbol!(c"cuLaunchKernel", LaunchKernel);
|
||||
Ok(Self {
|
||||
_library: library,
|
||||
init,
|
||||
version,
|
||||
device,
|
||||
create,
|
||||
destroy,
|
||||
push,
|
||||
pop,
|
||||
synchronize,
|
||||
allocate,
|
||||
free,
|
||||
copy_from,
|
||||
copy_to,
|
||||
load_module,
|
||||
get_function,
|
||||
unload_module,
|
||||
launch_kernel,
|
||||
})
|
||||
}
|
||||
pub(crate) fn load_fixed_module(&self) -> Result<ModuleHandle> {
|
||||
let mut module = std::ptr::null_mut();
|
||||
// SAFETY: current owned context, writable module out pointer, and
|
||||
// static trusted NUL-terminated PTX remains live indefinitely.
|
||||
check("cuModuleLoadData", unsafe {
|
||||
(self.load_module)(&mut module, FIXED_PTX.as_ptr().cast())
|
||||
})?;
|
||||
if module.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleLoadData"));
|
||||
}
|
||||
Ok(ModuleHandle(module as usize))
|
||||
}
|
||||
pub(crate) fn fixed_function(&self, module: ModuleHandle) -> Result<FunctionHandle> {
|
||||
let mut function = std::ptr::null_mut();
|
||||
// SAFETY: live private module in current owner context; fixed C
|
||||
// entry name; valid writable opaque function output.
|
||||
check("cuModuleGetFunction", unsafe {
|
||||
(self.get_function)(
|
||||
&mut function,
|
||||
module.0 as *mut c_void,
|
||||
c"leleka_vector_add_f32".as_ptr(),
|
||||
)
|
||||
})?;
|
||||
if function.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuModuleGetFunction"));
|
||||
}
|
||||
Ok(FunctionHandle(function as usize))
|
||||
}
|
||||
pub(crate) fn unload(&self, module: ModuleHandle) -> Result<()> {
|
||||
// SAFETY: usable handle was consumed before this single attempt,
|
||||
// current context owns it, and all prior work completed. It is
|
||||
// never retried or reused even when unload reports failure.
|
||||
check("cuModuleUnload", unsafe {
|
||||
(self.unload_module)(module.0 as *mut c_void)
|
||||
})
|
||||
}
|
||||
pub(crate) fn launch(
|
||||
&self,
|
||||
function: FunctionHandle,
|
||||
grid: u32,
|
||||
arguments: &mut LaunchArguments,
|
||||
) -> Result<()> {
|
||||
// SAFETY: fixed live function/owner context; checked exact shapes,
|
||||
// nonaliasing output and grid; six fixed dimensions + sharedBytes;
|
||||
// null stream/extra. Four pointer entries address initialized typed
|
||||
// boxed values, NOT device addresses interpreted as host pointers.
|
||||
// Caller keeps the entire box/table alive through mandatory sync,
|
||||
// and retains it permanently on ambiguous completion.
|
||||
check("cuLaunchKernel", unsafe {
|
||||
(self.launch_kernel)(
|
||||
function.0 as *mut c_void,
|
||||
grid,
|
||||
1,
|
||||
1,
|
||||
128,
|
||||
1,
|
||||
1,
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
(&raw mut (*arguments.storage.as_ptr()).parameters).cast(),
|
||||
std::ptr::null_mut(),
|
||||
)
|
||||
})
|
||||
}
|
||||
pub(crate) fn init(&self) -> Result<()> {
|
||||
// SAFETY: resolved exact ABI, mandated zero flags, live library.
|
||||
check("cuInit", unsafe { (self.init)(0) })
|
||||
}
|
||||
pub(crate) fn version(&self) -> Result<i32> {
|
||||
let mut value = 0;
|
||||
// SAFETY: resolved ABI and valid initialized writable C int.
|
||||
check("cuDriverGetVersion", unsafe { (self.version)(&mut value) })?;
|
||||
Ok(value)
|
||||
}
|
||||
pub(crate) fn device(&self, ordinal: i32) -> Result<i32> {
|
||||
let mut value = 0;
|
||||
// SAFETY: resolved ABI, valid out pointer, ordinal prevalidated.
|
||||
check("cuDeviceGet", unsafe { (self.device)(&mut value, ordinal) })?;
|
||||
Ok(value)
|
||||
}
|
||||
pub(crate) fn create(&self, device: i32) -> Result<ContextHandle> {
|
||||
let mut context = std::ptr::null_mut();
|
||||
// SAFETY: exact legacy v2 THREE-argument ABI, zero flags, a device
|
||||
// returned by cuDeviceGet, and a valid writable context pointer.
|
||||
check("cuCtxCreate_v2", unsafe {
|
||||
(self.create)(&mut context, 0, device)
|
||||
})?;
|
||||
if context.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuCtxCreate_v2"));
|
||||
}
|
||||
Ok(ContextHandle(context as usize))
|
||||
}
|
||||
pub(crate) fn destroy(&self, context: ContextHandle) -> Result<()> {
|
||||
// SAFETY: this handle was created by this Api and remains owned by
|
||||
// the caller context. No buffer can outlive the borrow owner. This
|
||||
// API explicitly supports destroying a non-current owned context.
|
||||
check("cuCtxDestroy_v2", unsafe {
|
||||
(self.destroy)(context.0 as CuContext)
|
||||
})
|
||||
}
|
||||
pub(crate) fn push(&self, context: ContextHandle) -> Result<()> {
|
||||
// SAFETY: live private context, same creating thread (Rc owners).
|
||||
check("cuCtxPushCurrent_v2", unsafe {
|
||||
(self.push)(context.0 as CuContext)
|
||||
})
|
||||
}
|
||||
pub(crate) fn pop(&self) -> Result<ContextHandle> {
|
||||
let mut context = std::ptr::null_mut();
|
||||
// SAFETY: called after successful create/push on the same thread,
|
||||
// valid out pointer. Callers verify identity and poison on failure.
|
||||
check("cuCtxPopCurrent_v2", unsafe { (self.pop)(&mut context) })?;
|
||||
Ok(ContextHandle(context as usize))
|
||||
}
|
||||
pub(crate) fn synchronize(&self) -> Result<()> {
|
||||
// SAFETY: caller guard makes its live owned context current.
|
||||
check("cuCtxSynchronize", unsafe { (self.synchronize)() })
|
||||
}
|
||||
pub(crate) fn allocate(&self, bytes: usize) -> Result<BufferHandle> {
|
||||
let mut ptr = 0;
|
||||
// SAFETY: current-context guard; nonzero, bounded size validated
|
||||
// before mutation; valid u64 CUdeviceptr output on Linux64.
|
||||
check("cuMemAlloc_v2", unsafe { (self.allocate)(&mut ptr, bytes) })?;
|
||||
if ptr == 0 {
|
||||
return Err(Error::InvalidDriverValue("cuMemAlloc_v2"));
|
||||
}
|
||||
Ok(BufferHandle(ptr))
|
||||
}
|
||||
pub(crate) fn free(&self, buffer: BufferHandle) -> Result<()> {
|
||||
// SAFETY: uniquely owned allocation, owner context is current.
|
||||
// Poisoned/uncertain contexts never enter this operation.
|
||||
check("cuMemFree_v2", unsafe { (self.free)(buffer.0) })
|
||||
}
|
||||
pub(crate) fn copy_from(&self, buffer: BufferHandle, owned: &[u8]) -> Result<()> {
|
||||
// SAFETY: buffer owner is current, exact allocation size checked,
|
||||
// and the caller owns this staging allocation. It synchronizes on
|
||||
// both success/error and leaks staging on ambiguous completion, so
|
||||
// the pointer stays valid even if the call retains it after return.
|
||||
check("cuMemcpyHtoD_v2", unsafe {
|
||||
(self.copy_from)(buffer.0, owned.as_ptr().cast(), owned.len())
|
||||
})
|
||||
}
|
||||
pub(crate) fn copy_to(&self, buffer: BufferHandle, owned: &mut [u8]) -> Result<()> {
|
||||
// SAFETY: valid owned writable staging of exactly the allocation
|
||||
// size; current owner context; caller synchronizes or leaks as
|
||||
// above. No borrowed output is passed directly to the driver.
|
||||
check("cuMemcpyDtoH_v2", unsafe {
|
||||
(self.copy_to)(owned.as_mut_ptr().cast(), buffer.0, owned.len())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(all(
|
||||
feature = "cuda-driver",
|
||||
target_os = "linux",
|
||||
target_pointer_width = "64"
|
||||
))]
|
||||
pub(crate) use enabled::Api;
|
||||
|
||||
#[cfg(not(all(
|
||||
feature = "cuda-driver",
|
||||
target_os = "linux",
|
||||
target_pointer_width = "64"
|
||||
)))]
|
||||
pub(crate) struct Api;
|
||||
#[cfg(not(all(
|
||||
feature = "cuda-driver",
|
||||
target_os = "linux",
|
||||
target_pointer_width = "64"
|
||||
)))]
|
||||
impl Api {
|
||||
pub(crate) fn load() -> Result<Self> {
|
||||
if cfg!(feature = "cuda-driver") {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
} else {
|
||||
Err(Error::Disabled)
|
||||
}
|
||||
}
|
||||
pub(crate) fn load_fixed_module(&self) -> Result<ModuleHandle> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn fixed_function(&self, module: ModuleHandle) -> Result<FunctionHandle> {
|
||||
let _ = module.0;
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn unload(&self, module: ModuleHandle) -> Result<()> {
|
||||
let _ = module.0;
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn launch(
|
||||
&self,
|
||||
function: FunctionHandle,
|
||||
_: u32,
|
||||
arguments: &mut LaunchArguments,
|
||||
) -> Result<()> {
|
||||
let _ = (function.0, arguments.storage);
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
// These methods cannot be reached through the safe API: load always fails.
|
||||
pub(crate) fn init(&self) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn version(&self) -> Result<i32> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn device(&self, _: i32) -> Result<i32> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn create(&self, _: i32) -> Result<ContextHandle> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn destroy(&self, _: ContextHandle) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn push(&self, _: ContextHandle) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn pop(&self) -> Result<ContextHandle> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn synchronize(&self) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn allocate(&self, _: usize) -> Result<BufferHandle> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn free(&self, _: BufferHandle) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn copy_from(&self, _: BufferHandle, _: &[u8]) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn copy_to(&self, _: BufferHandle, _: &mut [u8]) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
//! Opt-in CUDA Driver context and bounded byte buffers, without inference.
|
||||
//!
|
||||
//! Enable `cuda-driver` and explicitly call [`Driver::load`] on Linux 64-bit.
|
||||
//! Resources are confined to their creating thread and borrow their owners.
|
||||
//! Copies stage owned bytes and synchronize before publishing host output.
|
||||
//! A failed synchronization poisons the context and intentionally leaks the
|
||||
//! bounded staging allocation: completion cannot safely be inferred from an
|
||||
//! error, including a subsequent context-destruction result.
|
||||
#![deny(unsafe_code)]
|
||||
#![deny(unsafe_op_in_unsafe_fn)]
|
||||
|
||||
use std::{cell::Cell, fmt, marker::PhantomData, rc::Rc};
|
||||
|
||||
#[allow(unsafe_code)]
|
||||
mod ffi;
|
||||
|
||||
/// Errors retain CUDA operation names/codes and any subsequent cleanup errors.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
Disabled,
|
||||
UnsupportedPlatform,
|
||||
LibraryUnavailable,
|
||||
MissingSymbol(&'static str),
|
||||
InvalidDriverValue(&'static str),
|
||||
Driver {
|
||||
operation: &'static str,
|
||||
code: i32,
|
||||
},
|
||||
ContextMismatch,
|
||||
InvalidVectorShape,
|
||||
OutputAliasesInput,
|
||||
InvalidOrdinal,
|
||||
InvalidSize,
|
||||
BudgetExceeded,
|
||||
ShapeMismatch {
|
||||
expected: usize,
|
||||
actual: usize,
|
||||
},
|
||||
HostAllocation,
|
||||
ContextPoisoned,
|
||||
UnexpectedContext,
|
||||
Multiple {
|
||||
primary: Box<Error>,
|
||||
secondary: Box<Error>,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Disabled => f.write_str("CUDA Driver feature is disabled"),
|
||||
Self::UnsupportedPlatform => {
|
||||
f.write_str("CUDA Driver requires Linux with 64-bit pointers")
|
||||
}
|
||||
Self::LibraryUnavailable => f.write_str("cannot load libcuda.so.1"),
|
||||
Self::MissingSymbol(symbol) => write!(f, "missing CUDA Driver symbol {symbol}"),
|
||||
Self::InvalidDriverValue(operation) => {
|
||||
write!(f, "{operation} returned an invalid handle on success")
|
||||
}
|
||||
Self::Driver { operation, code } => {
|
||||
write!(f, "{operation} failed with CUDA code {code}")
|
||||
}
|
||||
Self::ContextMismatch => {
|
||||
f.write_str("vector buffers must belong to this exact context")
|
||||
}
|
||||
Self::InvalidVectorShape => {
|
||||
f.write_str("vector shape must be nonempty f32 bytes with a bounded u32 count/grid")
|
||||
}
|
||||
Self::OutputAliasesInput => f.write_str("vector output must not alias an input"),
|
||||
Self::InvalidOrdinal => f.write_str("device ordinal must be nonnegative"),
|
||||
Self::InvalidSize => f.write_str("byte size must be nonzero and fit isize"),
|
||||
Self::BudgetExceeded => f.write_str("allocation exceeds context byte budget"),
|
||||
Self::ShapeMismatch { expected, actual } => {
|
||||
write!(f, "byte shape mismatch: expected {expected}, got {actual}")
|
||||
}
|
||||
Self::HostAllocation => f.write_str("cannot allocate owned host staging memory"),
|
||||
Self::ContextPoisoned => {
|
||||
f.write_str("context is poisoned after uncertain completion or restoration")
|
||||
}
|
||||
Self::UnexpectedContext => f.write_str("CUDA pop returned a different context"),
|
||||
Self::Multiple { primary, secondary } => {
|
||||
write!(f, "{primary}; subsequent error: {secondary}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl std::error::Error for Error {}
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
fn combine<T>(primary: Result<T>, secondary: Result<()>) -> Result<T> {
|
||||
match (primary, secondary) {
|
||||
(Ok(value), Ok(())) => Ok(value),
|
||||
(Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error),
|
||||
(Err(primary), Err(secondary)) => Err(Error::Multiple {
|
||||
primary: Box::new(primary),
|
||||
secondary: Box::new(secondary),
|
||||
}),
|
||||
}
|
||||
}
|
||||
fn valid_size(bytes: usize) -> Result<()> {
|
||||
if bytes == 0 || bytes > isize::MAX as usize {
|
||||
Err(Error::InvalidSize)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A loaded fixed ABI. No resources can be sent or shared between threads.
|
||||
pub struct Driver {
|
||||
api: Rc<ffi::Api>,
|
||||
version: i32,
|
||||
}
|
||||
impl Driver {
|
||||
/// Resolve the entire fixed ABI before initializing CUDA.
|
||||
pub fn load() -> Result<Self> {
|
||||
let api = Rc::new(ffi::Api::load()?);
|
||||
api.init()?;
|
||||
let version = api.version()?;
|
||||
Ok(Self { api, version })
|
||||
}
|
||||
pub fn version(&self) -> i32 {
|
||||
self.version
|
||||
}
|
||||
pub fn device(&self, ordinal: i32) -> Result<Device<'_>> {
|
||||
if ordinal < 0 {
|
||||
return Err(Error::InvalidOrdinal);
|
||||
}
|
||||
Ok(Device {
|
||||
driver: self,
|
||||
handle: self.api.device(ordinal)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A device selected through its owner driver, without a public raw handle.
|
||||
pub struct Device<'driver> {
|
||||
driver: &'driver Driver,
|
||||
handle: i32,
|
||||
}
|
||||
impl<'driver> Device<'driver> {
|
||||
pub fn create_context(&self, byte_budget: usize) -> Result<Context<'driver>> {
|
||||
valid_size(byte_budget)?;
|
||||
let api = &self.driver.api;
|
||||
let handle = api.create(self.handle)?;
|
||||
let restore = api.pop().and_then(|popped| {
|
||||
if popped == handle {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnexpectedContext)
|
||||
}
|
||||
});
|
||||
if let Err(error) = restore {
|
||||
let cleanup = api.destroy(handle);
|
||||
if cleanup.is_err() {
|
||||
// The driver may still own a live context; keep its ABI loaded.
|
||||
std::mem::forget(Rc::clone(api));
|
||||
}
|
||||
return combine(Err(error), cleanup);
|
||||
}
|
||||
Ok(Context {
|
||||
driver: self.driver,
|
||||
handle: Some(handle),
|
||||
budget: byte_budget,
|
||||
allocated: Cell::new(0),
|
||||
poisoned: Cell::new(false),
|
||||
kernel: Cell::new(None),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A private context with a budget for actual live allocations.
|
||||
pub struct Context<'driver> {
|
||||
driver: &'driver Driver,
|
||||
handle: Option<ffi::ContextHandle>,
|
||||
budget: usize,
|
||||
allocated: Cell<usize>,
|
||||
poisoned: Cell<bool>,
|
||||
kernel: Cell<Option<FixedKernel>>,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct FixedKernel {
|
||||
module: ffi::ModuleHandle,
|
||||
function: ffi::FunctionHandle,
|
||||
}
|
||||
|
||||
// Wider integer arithmetic also covers the final partial block at u32::MAX.
|
||||
fn vector_shape(bytes: usize) -> Result<(u32, u32)> {
|
||||
if valid_size(bytes).is_err() || !bytes.is_multiple_of(4) {
|
||||
return Err(Error::InvalidVectorShape);
|
||||
}
|
||||
let count = u32::try_from(bytes / 4).map_err(|_| Error::InvalidVectorShape)?;
|
||||
let grid = u64::from(count)
|
||||
.checked_add(127)
|
||||
.ok_or(Error::InvalidVectorShape)?
|
||||
/ 128;
|
||||
if grid == 0 || grid > i32::MAX as u64 {
|
||||
return Err(Error::InvalidVectorShape);
|
||||
}
|
||||
Ok((
|
||||
count,
|
||||
u32::try_from(grid).map_err(|_| Error::InvalidVectorShape)?,
|
||||
))
|
||||
}
|
||||
impl Context<'_> {
|
||||
pub fn budget_bytes(&self) -> usize {
|
||||
self.budget
|
||||
}
|
||||
/// Failed frees remain charged until context destruction.
|
||||
pub fn allocated_bytes(&self) -> usize {
|
||||
self.allocated.get()
|
||||
}
|
||||
fn enter(&self) -> Result<CurrentGuard<'_, '_>> {
|
||||
if self.poisoned.get() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
let handle = self.handle.ok_or(Error::ContextPoisoned)?;
|
||||
self.driver.api.push(handle)?;
|
||||
Ok(CurrentGuard {
|
||||
context: self,
|
||||
active: true,
|
||||
})
|
||||
}
|
||||
pub fn allocate(&self, bytes: usize) -> Result<DeviceBuffer<'_>> {
|
||||
valid_size(bytes)?;
|
||||
let total = self
|
||||
.allocated
|
||||
.get()
|
||||
.checked_add(bytes)
|
||||
.ok_or(Error::BudgetExceeded)?;
|
||||
if total > self.budget {
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
let guard = self.enter()?;
|
||||
let allocation = self.driver.api.allocate(bytes);
|
||||
if allocation.is_ok() {
|
||||
self.allocated.set(total);
|
||||
}
|
||||
// A successful allocation whose pop fails stays charged. The poisoned
|
||||
// context owns that allocation until destruction, so no unguarded free.
|
||||
let handle = combine(allocation, guard.finish())?;
|
||||
Ok(DeviceBuffer {
|
||||
context: self,
|
||||
handle: Some(handle),
|
||||
bytes,
|
||||
_thread: PhantomData,
|
||||
})
|
||||
}
|
||||
pub fn synchronize(&self) -> Result<()> {
|
||||
let guard = self.enter()?;
|
||||
let sync = self.driver.api.synchronize();
|
||||
if sync.is_err() {
|
||||
self.poisoned.set(true);
|
||||
}
|
||||
combine(sync, guard.finish())
|
||||
}
|
||||
/// Add two exact f32 byte vectors with the fixed trusted kernel. The
|
||||
/// output is usable as a computed vector only after a successful return.
|
||||
pub fn vector_add_f32(
|
||||
&self,
|
||||
a: &DeviceBuffer<'_>,
|
||||
b: &DeviceBuffer<'_>,
|
||||
output: &mut DeviceBuffer<'_>,
|
||||
) -> Result<()> {
|
||||
if self.poisoned.get() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
if !std::ptr::eq(self, a.context)
|
||||
|| !std::ptr::eq(self, b.context)
|
||||
|| !std::ptr::eq(self, output.context)
|
||||
{
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
let (count, grid) = vector_shape(a.bytes)?;
|
||||
if a.bytes != b.bytes || a.bytes != output.bytes {
|
||||
return Err(Error::InvalidVectorShape);
|
||||
}
|
||||
let a_handle = a.handle.ok_or(Error::ContextPoisoned)?;
|
||||
let b_handle = b.handle.ok_or(Error::ContextPoisoned)?;
|
||||
let out_handle = output.handle.ok_or(Error::ContextPoisoned)?;
|
||||
if a_handle == out_handle || b_handle == out_handle {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
// Establish the owned parameter addresses after their stable heap
|
||||
// placement, before any native mutation. No caller host data is used.
|
||||
let mut arguments = ffi::LaunchArguments::new(a_handle, b_handle, out_handle, count);
|
||||
let guard = self.enter()?;
|
||||
let kernel = match self.fixed_kernel() {
|
||||
Ok(kernel) => kernel,
|
||||
Err(error) => return combine(Err(error), guard.finish()),
|
||||
};
|
||||
let launch = self
|
||||
.driver
|
||||
.api
|
||||
.launch(kernel.function, grid, &mut arguments);
|
||||
// A launch error can describe earlier asynchronous work. Synchronize
|
||||
// after EVERY attempted launch; preserve launch/sync/pop error order.
|
||||
let sync = self.driver.api.synchronize();
|
||||
if sync.is_err() {
|
||||
self.poisoned.set(true);
|
||||
// Both boxed scalars and their pointer table may still be read.
|
||||
// One poisoned context admits no further launch or explicit frees.
|
||||
std::mem::forget(arguments);
|
||||
}
|
||||
combine(combine(launch, sync), guard.finish())
|
||||
}
|
||||
fn fixed_kernel(&self) -> Result<FixedKernel> {
|
||||
if let Some(kernel) = self.kernel.get() {
|
||||
return Ok(kernel);
|
||||
}
|
||||
let module = self.driver.api.load_fixed_module()?;
|
||||
match self.driver.api.fixed_function(module) {
|
||||
Ok(function) => {
|
||||
let kernel = FixedKernel { module, function };
|
||||
self.kernel.set(Some(kernel));
|
||||
Ok(kernel)
|
||||
}
|
||||
Err(error) => {
|
||||
// Local usable handle consumed by this single unload attempt;
|
||||
// no cache publishes a partial module or retries failed unload.
|
||||
let cleanup = self.driver.api.unload(module);
|
||||
if cleanup.is_err() {
|
||||
self.poisoned.set(true);
|
||||
}
|
||||
combine(Err(error), cleanup)
|
||||
}
|
||||
}
|
||||
}
|
||||
fn unload_kernel(&self) -> Result<()> {
|
||||
// Consume BEFORE attempting unload; even an error can invalidate it.
|
||||
let Some(kernel) = self.kernel.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
if self.poisoned.get() {
|
||||
return Ok(());
|
||||
}
|
||||
let guard = match self.enter() {
|
||||
Ok(guard) => guard,
|
||||
Err(error) => {
|
||||
self.poisoned.set(true);
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let unload = self.driver.api.unload(kernel.module);
|
||||
if unload.is_err() {
|
||||
self.poisoned.set(true);
|
||||
}
|
||||
combine(unload, guard.finish())
|
||||
}
|
||||
/// Consume the context and report destruction failure. Borrows prevent
|
||||
/// closing a context while a device buffer can still be used.
|
||||
pub fn close(mut self) -> Result<()> {
|
||||
self.destroy()
|
||||
}
|
||||
fn destroy(&mut self) -> Result<()> {
|
||||
let unload = self.unload_kernel();
|
||||
if let Some(handle) = self.handle.take() {
|
||||
// cuCtxDestroy accepts an owned non-current context. Pushing here
|
||||
// would add a stack entry for a handle invalidated by destruction.
|
||||
let result = self.driver.api.destroy(handle);
|
||||
if result.is_err() {
|
||||
std::mem::forget(Rc::clone(&self.driver.api));
|
||||
}
|
||||
if result.is_ok() {
|
||||
self.allocated.set(0);
|
||||
}
|
||||
combine(unload, result)
|
||||
} else {
|
||||
unload
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Context<'_> {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
/// Push/pop balance with fallible explicit finish and nonpanicking fallback.
|
||||
struct CurrentGuard<'context, 'driver> {
|
||||
context: &'context Context<'driver>,
|
||||
active: bool,
|
||||
}
|
||||
impl CurrentGuard<'_, '_> {
|
||||
fn finish(mut self) -> Result<()> {
|
||||
self.restore()
|
||||
}
|
||||
fn restore(&mut self) -> Result<()> {
|
||||
if !self.active {
|
||||
return Ok(());
|
||||
}
|
||||
self.active = false;
|
||||
let result = self.context.driver.api.pop().and_then(|popped| {
|
||||
if Some(popped) == self.context.handle {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnexpectedContext)
|
||||
}
|
||||
});
|
||||
if result.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
impl Drop for CurrentGuard<'_, '_> {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.restore();
|
||||
}
|
||||
}
|
||||
|
||||
/// An exact nonempty byte allocation borrowing its owning context.
|
||||
pub struct DeviceBuffer<'context> {
|
||||
context: &'context Context<'context>,
|
||||
handle: Option<ffi::BufferHandle>,
|
||||
bytes: usize,
|
||||
_thread: PhantomData<Rc<()>>,
|
||||
}
|
||||
impl DeviceBuffer<'_> {
|
||||
pub fn len(&self) -> usize {
|
||||
self.bytes
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn staging(&self, actual: usize) -> Result<Vec<u8>> {
|
||||
if actual != self.bytes {
|
||||
return Err(Error::ShapeMismatch {
|
||||
expected: self.bytes,
|
||||
actual,
|
||||
});
|
||||
}
|
||||
if self.context.poisoned.get() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
}
|
||||
let mut staging = Vec::new();
|
||||
staging
|
||||
.try_reserve_exact(self.bytes)
|
||||
.map_err(|_| Error::HostAllocation)?;
|
||||
staging.resize(self.bytes, 0);
|
||||
Ok(staging)
|
||||
}
|
||||
pub fn copy_from(&mut self, input: &[u8]) -> Result<()> {
|
||||
let mut staging = self.staging(input.len())?;
|
||||
staging.copy_from_slice(input);
|
||||
self.copy_staged(staging, false).map(|_| ())
|
||||
}
|
||||
pub fn copy_to(&self, output: &mut [u8]) -> Result<()> {
|
||||
let staging = self.staging(output.len())?;
|
||||
let staging = self.copy_staged(staging, true)?;
|
||||
output.copy_from_slice(&staging);
|
||||
Ok(())
|
||||
}
|
||||
fn copy_staged(&self, mut staging: Vec<u8>, to_host: bool) -> Result<Vec<u8>> {
|
||||
let handle = self.handle.ok_or(Error::ContextPoisoned)?;
|
||||
let guard = self.context.enter()?;
|
||||
let copy = if to_host {
|
||||
self.context.driver.api.copy_to(handle, &mut staging)
|
||||
} else {
|
||||
self.context.driver.api.copy_from(handle, &staging)
|
||||
};
|
||||
// Even copy errors can report earlier asynchronous work. Synchronize
|
||||
// on every attempted copy before considering the staging reclaimable.
|
||||
let sync = self.context.driver.api.synchronize();
|
||||
if sync.is_err() {
|
||||
self.context.poisoned.set(true);
|
||||
// CUDA may still reference these owned host bytes. A poisoned
|
||||
// context admits no further copy, limiting this leak to one buffer
|
||||
// (at most its context budget), regardless of caller lifetimes.
|
||||
std::mem::forget(staging);
|
||||
return combine(combine(copy, sync), guard.finish()).map(|()| Vec::new());
|
||||
}
|
||||
combine(copy, guard.finish())?;
|
||||
Ok(staging)
|
||||
}
|
||||
pub fn release(mut self) -> Result<()> {
|
||||
self.free()
|
||||
}
|
||||
fn free(&mut self) -> Result<()> {
|
||||
let Some(handle) = self.handle.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
let guard = self.context.enter()?;
|
||||
let free = self.context.driver.api.free(handle);
|
||||
if free.is_ok() {
|
||||
self.context
|
||||
.allocated
|
||||
.set(self.context.allocated.get() - self.bytes);
|
||||
}
|
||||
combine(free, guard.finish())
|
||||
}
|
||||
}
|
||||
impl Drop for DeviceBuffer<'_> {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.free();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn sizes_and_error_composition() {
|
||||
assert_eq!(valid_size(0), Err(Error::InvalidSize));
|
||||
assert_eq!(valid_size(usize::MAX), Err(Error::InvalidSize));
|
||||
assert_eq!(valid_size(1), Ok(()));
|
||||
assert_eq!(
|
||||
combine::<()>(Err(Error::InvalidSize), Err(Error::UnexpectedContext)),
|
||||
Err(Error::Multiple {
|
||||
primary: Box::new(Error::InvalidSize),
|
||||
secondary: Box::new(Error::UnexpectedContext)
|
||||
})
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn vector_count_geometry_boundaries() {
|
||||
for bytes in [0, 1, 3, 5, usize::MAX] {
|
||||
assert!(vector_shape(bytes).is_err());
|
||||
}
|
||||
for n in [1u32, 127, 128, 129, 1025, u32::MAX] {
|
||||
let bytes = usize::try_from(u64::from(n) * 4).unwrap();
|
||||
assert_eq!(
|
||||
vector_shape(bytes),
|
||||
Ok((n, u32::try_from(u64::from(n).div_ceil(128)).unwrap()))
|
||||
);
|
||||
}
|
||||
assert!(vector_shape((u32::MAX as usize + 1) * 4).is_err());
|
||||
}
|
||||
#[cfg(not(feature = "cuda-driver"))]
|
||||
#[test]
|
||||
fn default_load_rejects_before_driver_use() {
|
||||
assert!(matches!(Driver::load(), Err(Error::Disabled)));
|
||||
}
|
||||
#[cfg(all(
|
||||
feature = "cuda-driver",
|
||||
not(all(target_os = "linux", target_pointer_width = "64"))
|
||||
))]
|
||||
#[test]
|
||||
fn unsupported_load_rejects_before_driver_use() {
|
||||
assert!(matches!(Driver::load(), Err(Error::UnsupportedPlatform)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// Trusted fixed operation; byte image is embedded with a final NUL by ffi.rs.
|
||||
.version 7.0
|
||||
.target sm_75
|
||||
.address_size 64
|
||||
|
||||
.visible .entry leleka_vector_add_f32(
|
||||
.param .u64 input_a,
|
||||
.param .u64 input_b,
|
||||
.param .u64 output,
|
||||
.param .u32 count
|
||||
)
|
||||
{
|
||||
.reg .pred %p;
|
||||
.reg .b32 %r<3>;
|
||||
.reg .b64 %rd<8>;
|
||||
.reg .f32 %f<3>;
|
||||
|
||||
ld.param.u64 %rd0, [input_a];
|
||||
ld.param.u64 %rd1, [input_b];
|
||||
ld.param.u64 %rd2, [output];
|
||||
ld.param.u32 %r2, [count];
|
||||
mov.u32 %r0, %ctaid.x;
|
||||
mov.u32 %r1, %tid.x;
|
||||
mul.wide.u32 %rd3, %r0, 128;
|
||||
cvt.u64.u32 %rd4, %r1;
|
||||
add.u64 %rd3, %rd3, %rd4;
|
||||
cvt.u64.u32 %rd4, %r2;
|
||||
setp.ge.u64 %p, %rd3, %rd4;
|
||||
@%p bra DONE;
|
||||
|
||||
shl.b64 %rd4, %rd3, 2;
|
||||
add.u64 %rd5, %rd0, %rd4;
|
||||
add.u64 %rd6, %rd1, %rd4;
|
||||
add.u64 %rd7, %rd2, %rd4;
|
||||
ld.global.f32 %f0, [%rd5];
|
||||
ld.global.f32 %f1, [%rd6];
|
||||
add.rn.f32 %f2, %f0, %f1;
|
||||
st.global.f32 [%rd7], %f2;
|
||||
DONE:
|
||||
ret;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
/* Synthetic CPU-only CUDA Driver ABI fixture. No NVIDIA headers/devices/library. */
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef void *CUcontext;
|
||||
typedef uint64_t CUdeviceptr;
|
||||
typedef int CUresult;
|
||||
static CUcontext current=(void *)(uintptr_t)0x11;
|
||||
static CUcontext stack[64];
|
||||
static size_t depth;
|
||||
static CUcontext contexts[16];
|
||||
static size_t next_context;
|
||||
static int context_live(CUcontext ctx){for(size_t i=0;i<16;i++)if(contexts[i]==ctx&&ctx)return 1;return 0;}
|
||||
static int live_context;
|
||||
static unsigned failed_mask;
|
||||
static struct {void *raw,*ptr;size_t size;CUcontext owner;} buffers[16];
|
||||
static struct {void *handle,*function;CUcontext owner;} modules[16];
|
||||
static size_t next_module;
|
||||
static void **pending_args;
|
||||
static uint64_t pending_values[3];
|
||||
static uint32_t pending_n;
|
||||
static CUcontext pending_owner;
|
||||
static const void *pending_host;
|
||||
static void *pending_device;
|
||||
static size_t pending_bytes;
|
||||
static void *pending_destination;
|
||||
static unsigned calls[16];
|
||||
static const char *names[]={"init","version","device","create","destroy","push","pop","sync","alloc","free","htod","dtoh","load","lookup","unload","launch"};
|
||||
static size_t charged(void) {size_t result=0;for(size_t i=0;i<16;i++)result+=buffers[i].size;return result;}
|
||||
static void trace(const char *stage,int code,size_t bytes) {
|
||||
const char *path=getenv("MOCK_CUDA_TRACE");if(!path)abort();
|
||||
FILE *f=fopen(path,"a");if(!f)abort();
|
||||
fprintf(f,"%s %d %lu %zu %d %zu %zu\n",stage,code,(unsigned long)(uintptr_t)current,depth,live_context,charged(),bytes);
|
||||
fclose(f);
|
||||
}
|
||||
static int fault(int op) {
|
||||
calls[op]++;
|
||||
const char *value=getenv("MOCK_CUDA_FAIL");
|
||||
if(!value||(failed_mask&(1u<<op)))return 0;
|
||||
char requested[128],expected[64];snprintf(requested,sizeof(requested),"%s",value);
|
||||
snprintf(expected,sizeof(expected),"%s:%u",names[op],calls[op]);
|
||||
for(char *token=strtok(requested,",");token;token=strtok(NULL,",")) {
|
||||
if(strcmp(token,names[op])==0||strcmp(token,expected)==0) {
|
||||
failed_mask|=1u<<op;trace(names[op],700,0);return 700;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
static void check_canary(size_t i) {
|
||||
unsigned char *raw=buffers[i].raw;
|
||||
if(!raw)return;
|
||||
for(size_t j=0;j<8;j++)if(raw[j]!=0xa5||raw[8+buffers[i].size+j]!=0xa5){trace("canary",1,i);abort();}
|
||||
}
|
||||
static void complete_pending(void) {
|
||||
if(pending_args){
|
||||
for(size_t i=0;i<3;i++)if(*(uint64_t *)pending_args[i]!=pending_values[i])abort();
|
||||
if(*(uint32_t *)pending_args[3]!=pending_n)abort();
|
||||
float *a=(float *)(uintptr_t)pending_values[0],*b=(float *)(uintptr_t)pending_values[1],*out=(float *)(uintptr_t)pending_values[2];
|
||||
for(uint32_t i=0;i<pending_n;i++)out[i]=a[i]+b[i];
|
||||
trace("pending_launch",0,pending_n);
|
||||
pending_args=NULL;pending_n=0;
|
||||
}
|
||||
for(size_t i=0;i<16;i++)check_canary(i);
|
||||
if(pending_host&&pending_device){
|
||||
size_t sum=0;for(size_t i=0;i<pending_bytes;i++)sum+=((const unsigned char *)pending_host)[i];
|
||||
const unsigned char expected[8]={0,1,2,3,255,128,85,170};
|
||||
int exact=pending_bytes==sizeof(expected)&&memcmp(pending_host,expected,sizeof(expected))==0;
|
||||
trace("pending_htod",exact||getenv("MOCK_CUDA_VECTOR")?0:1,sum);memcpy(pending_device,pending_host,pending_bytes);
|
||||
}
|
||||
if(pending_destination&&pending_device){trace("pending_dtoh",0,pending_bytes);memcpy(pending_destination,pending_device,pending_bytes);}
|
||||
pending_host=NULL;pending_device=NULL;pending_destination=NULL;pending_bytes=0;
|
||||
}
|
||||
static int require_context(void) {return context_live(current)?0:201;}
|
||||
static void *lookup(CUdeviceptr ptr,size_t count) {
|
||||
for(size_t i=0;i<16;i++)if((CUdeviceptr)(uintptr_t)buffers[i].ptr==ptr&&count==buffers[i].size&&buffers[i].owner==current)return buffers[i].ptr;
|
||||
return NULL;
|
||||
}
|
||||
CUresult cuInit(unsigned flags) {if(flags)return 1;if(fault(0))return 700;trace("init",0,0);return 0;}
|
||||
CUresult cuDriverGetVersion(int *version) {if(fault(1))return 700;*version=13000;trace("version",0,0);return 0;}
|
||||
CUresult cuDeviceGet(int *device,int ordinal) {if(fault(2))return 700;if(ordinal!=0)return 101;*device=0;trace("device",0,0);return 0;}
|
||||
CUresult cuCtxCreate_v2(CUcontext *result,unsigned flags,int device) {
|
||||
if(flags||device)return 1;if(fault(3))return 700;
|
||||
if(next_context>=16)return 2;
|
||||
CUcontext owned=(void *)(uintptr_t)(0x22+next_context);contexts[next_context++]=owned;
|
||||
stack[depth++]=current;current=owned;live_context++;*result=owned;trace("create",0,0);return 0;
|
||||
}
|
||||
CUresult cuCtxDestroy_v2(CUcontext ctx) {
|
||||
if(fault(4))return 700;if(!context_live(ctx))return 201;
|
||||
/* Read retained pending source before disposing it: a delayed HtoD host borrow. */
|
||||
if(pending_args&&pending_owner!=ctx)abort();complete_pending();
|
||||
for(size_t i=0;i<16;i++)if(buffers[i].owner==ctx){free(buffers[i].raw);memset(&buffers[i],0,sizeof(buffers[i]));}
|
||||
for(size_t i=0;i<16;i++)if(modules[i].owner==ctx)memset(&modules[i],0,sizeof(modules[i]));
|
||||
for(size_t i=0;i<16;i++)if(contexts[i]==ctx)contexts[i]=NULL;
|
||||
live_context--;if(current==ctx)current=depth?stack[--depth]:(void *)(uintptr_t)0x11;
|
||||
trace("destroy",0,0);return 0;
|
||||
}
|
||||
CUresult cuCtxPushCurrent_v2(CUcontext ctx) {
|
||||
if(fault(5))return 700;if(!context_live(ctx)||depth>=64)return 201;
|
||||
stack[depth++]=current;current=ctx;trace("push",0,0);return 0;
|
||||
}
|
||||
CUresult cuCtxPopCurrent_v2(CUcontext *result) {
|
||||
if(fault(6))return 700;if(!depth)return 201;
|
||||
*result=current;current=stack[--depth];
|
||||
const char *wrong=getenv("MOCK_CUDA_WRONG_POP");
|
||||
if(wrong&&calls[6]==(unsigned)strtoul(wrong,NULL,10))*result=(void *)(uintptr_t)0x99;
|
||||
trace("pop",0,0);return 0;
|
||||
}
|
||||
CUresult cuCtxSynchronize(void) {
|
||||
if(fault(7))return 700;if(require_context())return 201;
|
||||
complete_pending();trace("sync",0,0);return 0;
|
||||
}
|
||||
CUresult cuMemAlloc_v2(CUdeviceptr *ptr,size_t bytes) {
|
||||
if(fault(8))return 700;if(require_context()||!bytes||bytes>16384)return 201;
|
||||
for(size_t i=0;i<16;i++)if(!buffers[i].ptr){buffers[i].raw=calloc(1,bytes+16);if(!buffers[i].raw)return 2;memset(buffers[i].raw,0xa5,8);memset((unsigned char*)buffers[i].raw+8+bytes,0xa5,8);buffers[i].ptr=(unsigned char*)buffers[i].raw+8;buffers[i].size=bytes;buffers[i].owner=current;*ptr=(CUdeviceptr)(uintptr_t)buffers[i].ptr;trace("alloc",0,bytes);return 0;}
|
||||
return 2;
|
||||
}
|
||||
CUresult cuMemFree_v2(CUdeviceptr ptr) {
|
||||
if(fault(9))return 700;if(require_context())return 201;
|
||||
for(size_t i=0;i<16;i++)if((CUdeviceptr)(uintptr_t)buffers[i].ptr==ptr){if(pending_args){trace("unsafe_pending_free",0,0);abort();}check_canary(i);if(pending_device==buffers[i].ptr){trace("unsafe_pending_free",0,0);pending_device=NULL;pending_host=NULL;pending_destination=NULL;pending_bytes=0;}free(buffers[i].raw);memset(&buffers[i],0,sizeof(buffers[i]));trace("free",0,0);return 0;}
|
||||
return 1;
|
||||
}
|
||||
CUresult cuMemcpyHtoD_v2(CUdeviceptr ptr,const void *host,size_t bytes) {
|
||||
if(fault(10))return 700;if(require_context()||!lookup(ptr,bytes))return 201;
|
||||
/* Copy is deliberately delayed to explicit synchronization. */
|
||||
pending_host=host;pending_device=lookup(ptr,bytes);pending_bytes=bytes;trace("htod",0,bytes);return 0;
|
||||
}
|
||||
#ifndef MOCK_MISSING_DTOH
|
||||
CUresult cuMemcpyDtoH_v2(void *host,CUdeviceptr ptr,size_t bytes) {
|
||||
if(fault(11))return 700;if(require_context()||!lookup(ptr,bytes))return 201;
|
||||
pending_destination=host;pending_device=lookup(ptr,bytes);pending_bytes=bytes;trace("dtoh",0,bytes);return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Independent fixed vector ABI fixture. Arithmetic here is a CPU reference;
|
||||
it neither interprets nor executes PTX. */
|
||||
CUresult cuModuleLoadData(void **result,const void *image) {
|
||||
if(fault(12))return 700;if(require_context())return 201;
|
||||
const char *ptx=image;
|
||||
if(!ptx||!strstr(ptx,".version 7.0")||!strstr(ptx,".target sm_75")||!strstr(ptx,".address_size 64")||!strstr(ptx,".entry leleka_vector_add_f32")||!strstr(ptx,"add.rn.f32"))return 218;
|
||||
if(getenv("MOCK_CUDA_NULL_LOAD")){*result=NULL;trace("load_null",0,0);return 0;}
|
||||
if(next_module>=16)return 2;
|
||||
size_t slot=next_module++;modules[slot].handle=(void *)(uintptr_t)(0x100+slot);
|
||||
modules[slot].function=(void *)(uintptr_t)(0x200+slot);modules[slot].owner=current;
|
||||
*result=modules[slot].handle;trace("load",0,0);return 0;
|
||||
}
|
||||
CUresult cuModuleGetFunction(void **result,void *module,const char *name) {
|
||||
if(fault(13))return 700;if(require_context()||strcmp(name,"leleka_vector_add_f32"))return 201;
|
||||
if(getenv("MOCK_CUDA_NULL_FUNCTION")){*result=NULL;trace("lookup_null",0,0);return 0;}
|
||||
for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){*result=modules[i].function;trace("lookup",0,0);return 0;}
|
||||
return 201;
|
||||
}
|
||||
CUresult cuModuleUnload(void *module) {
|
||||
if(pending_args){trace("unsafe_pending_unload",0,0);abort();}
|
||||
if(fault(14))return 700;if(require_context())return 201;
|
||||
for(size_t i=0;i<16;i++)if(modules[i].handle==module&&modules[i].owner==current){memset(&modules[i],0,sizeof(modules[i]));trace("unload",0,0);return 0;}
|
||||
return 201;
|
||||
}
|
||||
CUresult cuLaunchKernel(void *function,unsigned gx,unsigned gy,unsigned gz,unsigned bx,unsigned by,unsigned bz,unsigned shared,void *stream,void **params,void **extra) {
|
||||
if(require_context()||!params||extra||stream||shared||gy!=1||gz!=1||bx!=128||by!=1||bz!=1)return 201;
|
||||
int found=0;for(size_t i=0;i<16;i++)if(modules[i].function==function&&modules[i].owner==current)found=1;
|
||||
if(!found)return 201;
|
||||
uintptr_t stack_address=(uintptr_t)&found;
|
||||
uintptr_t table_address=(uintptr_t)params;
|
||||
if(table_address>stack_address-1048576&&table_address<stack_address+1048576){trace("stack_arguments",1,0);return 1;}
|
||||
uint32_t n=*(uint32_t *)params[3];
|
||||
if(!n||gx!=(n+127ull)/128)return 1;
|
||||
for(size_t i=0;i<3;i++){
|
||||
uintptr_t arg=(uintptr_t)params[i];if(arg>stack_address-1048576&&arg<stack_address+1048576)return 1;
|
||||
uint64_t value=*(uint64_t *)params[i];if(!lookup(value,(size_t)n*4))return 1;pending_values[i]=value;
|
||||
}
|
||||
if(pending_values[2]==pending_values[0]||pending_values[2]==pending_values[1])return 1;
|
||||
pending_args=params;pending_n=n;pending_owner=current;
|
||||
trace("geometry",0,gx);trace("arguments",0,n);
|
||||
if(fault(15))return 700;trace("launch",0,n);return 0;
|
||||
}
|
||||
@@ -0,0 +1,717 @@
|
||||
#![cfg(all(target_os = "linux", target_pointer_width = "64"))]
|
||||
|
||||
use leleka_cuda_driver::Driver;
|
||||
use std::{fs, path::PathBuf, process::Command};
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Row {
|
||||
stage: String,
|
||||
code: i32,
|
||||
current: usize,
|
||||
depth: usize,
|
||||
live: usize,
|
||||
charged: usize,
|
||||
bytes: usize,
|
||||
}
|
||||
fn trace() -> Vec<Row> {
|
||||
let path = std::env::var("MOCK_CUDA_TRACE").unwrap();
|
||||
fs::read_to_string(path)
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let v: Vec<_> = line.split_whitespace().collect();
|
||||
assert_eq!(v.len(), 7);
|
||||
Row {
|
||||
stage: v[0].into(),
|
||||
code: v[1].parse().unwrap(),
|
||||
current: v[2].parse().unwrap(),
|
||||
depth: v[3].parse().unwrap(),
|
||||
live: v[4].parse().unwrap(),
|
||||
charged: v[5].parse().unwrap(),
|
||||
bytes: v[6].parse().unwrap(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn valid_context_trace(rows: &[Row]) {
|
||||
for row in rows.iter().filter(|row| row.code == 0) {
|
||||
if ["alloc", "htod", "dtoh", "sync", "free"].contains(&row.stage.as_str()) {
|
||||
assert_eq!(row.current, 0x22, "{row:?}");
|
||||
assert_eq!(row.depth, 1, "{row:?}");
|
||||
assert_eq!(row.live, 1);
|
||||
}
|
||||
if row.stage == "pop" {
|
||||
assert_eq!(row.current, 0x11, "{row:?}");
|
||||
assert_eq!(row.depth, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cuda_errors(error: &leleka_cuda_driver::Error) -> Vec<(&'static str, i32)> {
|
||||
match error {
|
||||
leleka_cuda_driver::Error::Driver { operation, code } => vec![(*operation, *code)],
|
||||
leleka_cuda_driver::Error::Multiple { primary, secondary } => {
|
||||
let mut errors = cuda_errors(primary);
|
||||
errors.extend(cuda_errors(secondary));
|
||||
errors
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires isolated CPU-only fake libcuda harness"]
|
||||
fn isolated_cpu_elf_matrix() {
|
||||
assert_eq!(
|
||||
std::env::var("LELEKA_CUDA_MOCK_HARNESS").as_deref(),
|
||||
Ok("1"),
|
||||
"run only the isolated synthetic ELF harness"
|
||||
);
|
||||
let root = PathBuf::from(std::env::var("LELEKA_CUDA_MOCK_ROOT").unwrap());
|
||||
assert!(root.is_absolute());
|
||||
let scenarios = [
|
||||
"success",
|
||||
"bounds",
|
||||
"missing",
|
||||
"missing_cuInit",
|
||||
"missing_cuDriverGetVersion",
|
||||
"missing_cuDeviceGet",
|
||||
"missing_cuCtxCreate_v2",
|
||||
"missing_cuCtxDestroy_v2",
|
||||
"missing_cuCtxPushCurrent_v2",
|
||||
"missing_cuCtxPopCurrent_v2",
|
||||
"missing_cuCtxSynchronize",
|
||||
"missing_cuMemAlloc_v2",
|
||||
"missing_cuMemFree_v2",
|
||||
"missing_cuMemcpyHtoD_v2",
|
||||
"init",
|
||||
"version",
|
||||
"device",
|
||||
"create",
|
||||
"create_pop",
|
||||
"push",
|
||||
"pop",
|
||||
"wrong_pop",
|
||||
"operation_wrong_pop",
|
||||
"context_sync",
|
||||
"alloc",
|
||||
"htod",
|
||||
"dtoh",
|
||||
"sync_htod",
|
||||
"sync_dtoh",
|
||||
"htod_sync",
|
||||
"dtoh_sync",
|
||||
"free",
|
||||
"destroy",
|
||||
"missing_cuModuleLoadData",
|
||||
"missing_cuModuleGetFunction",
|
||||
"missing_cuModuleUnload",
|
||||
"missing_cuLaunchKernel",
|
||||
"vector_1",
|
||||
"vector_127",
|
||||
"vector_128",
|
||||
"vector_129",
|
||||
"vector_1025",
|
||||
"vector_cache",
|
||||
"vector_contexts",
|
||||
"vector_bounds",
|
||||
"vector_same_input",
|
||||
"vector_load",
|
||||
"vector_lookup",
|
||||
"vector_null_load",
|
||||
"vector_null_function",
|
||||
"vector_launch",
|
||||
"vector_sync",
|
||||
"vector_launch_sync",
|
||||
"vector_launch_sync_pop",
|
||||
"vector_pop",
|
||||
"vector_wrong_pop",
|
||||
"vector_unload",
|
||||
"vector_lookup_unload",
|
||||
"vector_close_pop",
|
||||
"vector_close_destroy",
|
||||
"vector_push",
|
||||
];
|
||||
for scenario in scenarios {
|
||||
let path = root.join(format!("trace-{scenario}"));
|
||||
let mut command = Command::new(std::env::current_exe().unwrap());
|
||||
command
|
||||
.args(["--exact", "fixture_child", "--ignored", "--nocapture"])
|
||||
.env("LELEKA_CUDA_CASE", scenario)
|
||||
.env("MOCK_CUDA_TRACE", &path)
|
||||
.env_remove("MOCK_CUDA_FAIL")
|
||||
.env_remove("MOCK_CUDA_WRONG_POP")
|
||||
.env_remove("MOCK_CUDA_NULL_LOAD")
|
||||
.env_remove("MOCK_CUDA_NULL_FUNCTION")
|
||||
.env_remove("MOCK_CUDA_VECTOR");
|
||||
if scenario.starts_with("vector_") {
|
||||
command.env("MOCK_CUDA_VECTOR", "1");
|
||||
}
|
||||
command.env(
|
||||
"LD_LIBRARY_PATH",
|
||||
root.join(if scenario.starts_with("missing") {
|
||||
scenario
|
||||
} else {
|
||||
"complete"
|
||||
}),
|
||||
);
|
||||
let failure = match scenario {
|
||||
"vector_load" => Some("load"),
|
||||
"vector_lookup" => Some("lookup"),
|
||||
"vector_launch" => Some("launch"),
|
||||
"vector_sync" => Some("sync:3"),
|
||||
"vector_launch_sync" => Some("launch,sync:3"),
|
||||
"vector_launch_sync_pop" => Some("launch,sync:3,pop:7"),
|
||||
"vector_pop" => Some("pop:7"),
|
||||
"vector_unload" => Some("unload"),
|
||||
"vector_lookup_unload" => Some("lookup,unload"),
|
||||
"vector_close_pop" => Some("pop:14"),
|
||||
"vector_close_destroy" => Some("destroy"),
|
||||
"vector_push" => Some("push:6"),
|
||||
other if other.starts_with("vector_") => None,
|
||||
"create_pop" => Some("pop"),
|
||||
"pop" => Some("pop:2"),
|
||||
"sync_htod" => Some("sync"),
|
||||
"sync_dtoh" => Some("sync:2"),
|
||||
"htod_sync" => Some("htod,sync"),
|
||||
"dtoh_sync" => Some("dtoh,sync:2"),
|
||||
"success" | "bounds" | "missing" | "wrong_pop" | "operation_wrong_pop" => None,
|
||||
"context_sync" => Some("sync"),
|
||||
other => Some(other),
|
||||
};
|
||||
if let Some(failure) = failure {
|
||||
command.env("MOCK_CUDA_FAIL", failure);
|
||||
}
|
||||
if ["wrong_pop", "operation_wrong_pop"].contains(&scenario) {
|
||||
command.env(
|
||||
"MOCK_CUDA_WRONG_POP",
|
||||
if scenario == "wrong_pop" { "1" } else { "2" },
|
||||
);
|
||||
}
|
||||
if scenario == "vector_wrong_pop" {
|
||||
command.env("MOCK_CUDA_WRONG_POP", "7");
|
||||
}
|
||||
if scenario == "vector_null_load" {
|
||||
command.env("MOCK_CUDA_NULL_LOAD", "1");
|
||||
}
|
||||
if scenario == "vector_null_function" {
|
||||
command.env("MOCK_CUDA_NULL_FUNCTION", "1");
|
||||
}
|
||||
let output = command.output().unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"scenario {scenario}\n{}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
println!("synthetic CPU ELF scenario {scenario}: PASS");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "invoked only by isolated_cpu_elf_matrix with synthetic library"]
|
||||
fn fixture_child() {
|
||||
assert_eq!(std::env::var("LELEKA_CUDA_MOCK_HARNESS").unwrap(), "1");
|
||||
let case = std::env::var("LELEKA_CUDA_CASE").unwrap();
|
||||
if case.starts_with("vector_") {
|
||||
vector_child(&case);
|
||||
return;
|
||||
}
|
||||
if case.starts_with("missing") || ["init", "version"].contains(&case.as_str()) {
|
||||
let error = Driver::load()
|
||||
.err()
|
||||
.expect("missing ABI/init/version must fail");
|
||||
if case.starts_with("missing") {
|
||||
let symbol = case.strip_prefix("missing_").unwrap_or("cuMemcpyDtoH_v2");
|
||||
assert!(
|
||||
matches!(error,leleka_cuda_driver::Error::MissingSymbol(actual) if actual==symbol)
|
||||
);
|
||||
}
|
||||
let rows = trace();
|
||||
if case.starts_with("missing") {
|
||||
assert!(rows.is_empty(), "symbol resolution must precede init");
|
||||
} else {
|
||||
assert!(rows.iter().any(|row| row.stage == case && row.code == 700));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let driver = Driver::load().unwrap();
|
||||
assert_eq!(driver.version(), 13000);
|
||||
if case == "device" {
|
||||
assert!(driver.device(0).is_err());
|
||||
return;
|
||||
}
|
||||
assert!(driver.device(-1).is_err());
|
||||
let device = driver.device(0).unwrap();
|
||||
if case == "bounds" {
|
||||
let before = trace().len();
|
||||
assert!(device.create_context(0).is_err());
|
||||
assert!(device.create_context(usize::MAX).is_err());
|
||||
assert_eq!(trace().len(), before);
|
||||
}
|
||||
if ["create", "create_pop", "wrong_pop"].contains(&case.as_str()) {
|
||||
assert!(device.create_context(16).is_err());
|
||||
let rows = trace();
|
||||
if case == "create" {
|
||||
assert!(!rows.iter().any(|row| row.stage == "destroy"));
|
||||
} else {
|
||||
assert!(
|
||||
rows.iter()
|
||||
.any(|row| row.stage == "destroy" && row.code == 0)
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let context = device.create_context(16).unwrap();
|
||||
assert_eq!(context.budget_bytes(), 16);
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
assert_eq!(trace().last().unwrap().current, 0x11);
|
||||
if ["alloc", "push", "pop", "operation_wrong_pop"].contains(&case.as_str()) {
|
||||
assert!(context.allocate(8).is_err());
|
||||
if ["pop", "operation_wrong_pop"].contains(&case.as_str()) {
|
||||
let before = trace().len();
|
||||
assert!(context.allocate(8).is_err());
|
||||
assert!(context.synchronize().is_err());
|
||||
assert_eq!(trace().len(), before, "poison must reject native work");
|
||||
} else {
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
}
|
||||
drop(context);
|
||||
valid_context_trace(&trace());
|
||||
return;
|
||||
}
|
||||
if case == "context_sync" {
|
||||
assert!(context.synchronize().is_err());
|
||||
drop(context);
|
||||
valid_context_trace(&trace());
|
||||
return;
|
||||
}
|
||||
if case == "bounds" {
|
||||
let before = trace().len();
|
||||
assert!(context.allocate(0).is_err());
|
||||
assert!(context.allocate(17).is_err());
|
||||
assert!(context.allocate(usize::MAX).is_err());
|
||||
assert_eq!(trace().len(), before);
|
||||
}
|
||||
let mut buffer = context.allocate(8).unwrap();
|
||||
assert_eq!(buffer.len(), 8);
|
||||
assert_eq!(context.allocated_bytes(), 8);
|
||||
if case == "bounds" {
|
||||
let before = trace().len();
|
||||
assert!(context.allocate(9).is_err());
|
||||
assert!(buffer.copy_from(&[1; 7]).is_err());
|
||||
assert!(buffer.copy_from(&[1; 9]).is_err());
|
||||
let mut short = [0x99; 7];
|
||||
assert!(buffer.copy_to(&mut short).is_err());
|
||||
assert_eq!(short, [0x99; 7]);
|
||||
assert_eq!(
|
||||
trace().len(),
|
||||
before,
|
||||
"bounds reject before driver mutation"
|
||||
);
|
||||
}
|
||||
let mut input = [0, 1, 2, 3, 0xff, 0x80, 0x55, 0xaa];
|
||||
let mut output = [0x99; 8];
|
||||
if ["htod", "sync_htod", "htod_sync"].contains(&case.as_str()) {
|
||||
let error = buffer.copy_from(&input).unwrap_err();
|
||||
let expected = match case.as_str() {
|
||||
"htod" => vec![("cuMemcpyHtoD_v2", 700)],
|
||||
"sync_htod" => vec![("cuCtxSynchronize", 700)],
|
||||
_ => vec![("cuMemcpyHtoD_v2", 700), ("cuCtxSynchronize", 700)],
|
||||
};
|
||||
assert_eq!(
|
||||
cuda_errors(&error),
|
||||
expected,
|
||||
"copy/completion errors retained in order"
|
||||
);
|
||||
input.fill(0);
|
||||
std::hint::black_box(input);
|
||||
if ["sync_htod", "htod_sync"].contains(&case.as_str()) {
|
||||
let before = trace().len();
|
||||
assert!(context.allocate(1).is_err());
|
||||
assert_eq!(trace().len(), before);
|
||||
}
|
||||
} else {
|
||||
buffer.copy_from(&input).unwrap();
|
||||
if ["dtoh", "sync_dtoh", "dtoh_sync"].contains(&case.as_str()) {
|
||||
let error = buffer.copy_to(&mut output).unwrap_err();
|
||||
let expected = match case.as_str() {
|
||||
"dtoh" => vec![("cuMemcpyDtoH_v2", 700)],
|
||||
"sync_dtoh" => vec![("cuCtxSynchronize", 700)],
|
||||
_ => vec![("cuMemcpyDtoH_v2", 700), ("cuCtxSynchronize", 700)],
|
||||
};
|
||||
assert_eq!(
|
||||
cuda_errors(&error),
|
||||
expected,
|
||||
"copy/completion errors retained in order"
|
||||
);
|
||||
assert_eq!(output, [0x99; 8], "failed copy must not publish staging");
|
||||
if ["sync_dtoh", "dtoh_sync"].contains(&case.as_str()) {
|
||||
let before = trace().len();
|
||||
assert!(context.synchronize().is_err());
|
||||
assert_eq!(trace().len(), before);
|
||||
}
|
||||
} else {
|
||||
buffer.copy_to(&mut output).unwrap();
|
||||
assert_eq!(output, input);
|
||||
}
|
||||
}
|
||||
if case == "free" {
|
||||
let error = buffer.release().unwrap_err();
|
||||
assert_eq!(cuda_errors(&error), vec![("cuMemFree_v2", 700)]);
|
||||
assert_eq!(context.allocated_bytes(), 8);
|
||||
} else if ["sync_htod", "sync_dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) {
|
||||
drop(buffer);
|
||||
} else {
|
||||
buffer.release().unwrap();
|
||||
assert_eq!(context.allocated_bytes(), 0);
|
||||
}
|
||||
if case == "destroy" {
|
||||
let error = context.close().unwrap_err();
|
||||
assert_eq!(cuda_errors(&error), vec![("cuCtxDestroy_v2", 700)]);
|
||||
} else if ["sync_htod", "sync_dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) {
|
||||
drop(context);
|
||||
} else {
|
||||
context.close().unwrap();
|
||||
}
|
||||
let rows = trace();
|
||||
if case == "sync_htod" {
|
||||
assert!(
|
||||
rows.iter()
|
||||
.any(|row| row.stage == "pending_htod" && row.code == 0 && row.bytes == 644),
|
||||
"delayed source retained original owned bytes after caller input changed"
|
||||
);
|
||||
}
|
||||
if case == "sync_dtoh" {
|
||||
assert!(
|
||||
rows.iter()
|
||||
.any(|row| row.stage == "pending_dtoh" && row.bytes == 8)
|
||||
);
|
||||
assert_eq!(
|
||||
output, [0x99; 8],
|
||||
"completion after failed sync must target retained staging, never caller output"
|
||||
);
|
||||
}
|
||||
if ["htod", "dtoh", "htod_sync", "dtoh_sync"].contains(&case.as_str()) {
|
||||
let copy = if case.starts_with("htod") {
|
||||
"htod"
|
||||
} else {
|
||||
"dtoh"
|
||||
};
|
||||
let index = rows
|
||||
.iter()
|
||||
.position(|row| row.stage == copy && row.code == 700)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
rows[index + 1].stage,
|
||||
"sync",
|
||||
"sync must be attempted after copy failure"
|
||||
);
|
||||
assert_eq!(
|
||||
rows[index + 1].code,
|
||||
if case.ends_with("_sync") { 700 } else { 0 }
|
||||
);
|
||||
}
|
||||
valid_context_trace(&rows);
|
||||
assert!(
|
||||
rows.iter().any(|row| row.stage == "destroy"),
|
||||
"owned context cleanup attempted"
|
||||
);
|
||||
assert!(
|
||||
!rows.iter().any(|row| row.stage == "unsafe_pending_free"),
|
||||
"pending copy device freed early"
|
||||
);
|
||||
for row in rows
|
||||
.iter()
|
||||
.filter(|row| row.stage == "alloc" && row.code == 0)
|
||||
{
|
||||
assert_eq!(row.bytes, 8);
|
||||
assert_eq!(row.charged, 8);
|
||||
}
|
||||
if !["destroy"].contains(&case.as_str()) {
|
||||
let destroyed = rows
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|row| row.stage == "destroy" && row.code == 0)
|
||||
.unwrap();
|
||||
assert_eq!(destroyed.live, 0);
|
||||
assert_eq!(destroyed.charged, 0);
|
||||
assert_eq!(destroyed.current, 0x11);
|
||||
}
|
||||
}
|
||||
|
||||
// Expected values and geometry are derived from FR-VADD-1..5 and the NVIDIA
|
||||
// launch ABI, independent of the wrapper/PTX implementation. CPU mock results
|
||||
// are host dataflow/ownership evidence only.
|
||||
fn vector_child(case: &str) {
|
||||
use leleka_cuda_driver::Error;
|
||||
let driver = Driver::load().unwrap();
|
||||
let device = driver.device(0).unwrap();
|
||||
let count = case
|
||||
.strip_prefix("vector_")
|
||||
.unwrap()
|
||||
.parse::<usize>()
|
||||
.unwrap_or(129);
|
||||
let bytes = count * 4;
|
||||
let context = device.create_context(bytes * 4 + 16).unwrap();
|
||||
let mut a = context.allocate(bytes).unwrap();
|
||||
let mut b = context.allocate(bytes).unwrap();
|
||||
let mut out = context.allocate(bytes).unwrap();
|
||||
let av: Vec<f32> = (0..count)
|
||||
.map(|i| (i as i32 % 31 - 15) as f32 * 0.5)
|
||||
.collect();
|
||||
let bv: Vec<f32> = (0..count)
|
||||
.map(|i| (i as i32 % 23 - 11) as f32 * 0.25)
|
||||
.collect();
|
||||
let encode = |v: &[f32]| {
|
||||
v.iter()
|
||||
.flat_map(|value| value.to_ne_bytes())
|
||||
.collect::<Vec<u8>>()
|
||||
};
|
||||
a.copy_from(&encode(&av)).unwrap();
|
||||
b.copy_from(&encode(&bv)).unwrap();
|
||||
if case == "vector_bounds" {
|
||||
let foreign = device.create_context(bytes * 3).unwrap();
|
||||
let foreign_input = foreign.allocate(bytes).unwrap();
|
||||
let short = context.allocate(4).unwrap();
|
||||
let odd = context.allocate(3).unwrap();
|
||||
let mut odd_out = context.allocate(3).unwrap();
|
||||
let before = trace().len();
|
||||
assert!(matches!(
|
||||
context.vector_add_f32(&foreign_input, &b, &mut out),
|
||||
Err(Error::ContextMismatch)
|
||||
));
|
||||
assert!(context.vector_add_f32(&a, &short, &mut out).is_err());
|
||||
assert!(context.vector_add_f32(&odd, &odd, &mut odd_out).is_err());
|
||||
assert_eq!(trace().len(), before, "validation before ABI mutation");
|
||||
drop((foreign_input, short, odd, odd_out));
|
||||
foreign.close().unwrap();
|
||||
}
|
||||
let result = if case == "vector_same_input" {
|
||||
context.vector_add_f32(&a, &a, &mut out)
|
||||
} else {
|
||||
context.vector_add_f32(&a, &b, &mut out)
|
||||
};
|
||||
let execution_failure = [
|
||||
"vector_load",
|
||||
"vector_lookup",
|
||||
"vector_null_load",
|
||||
"vector_null_function",
|
||||
"vector_launch",
|
||||
"vector_sync",
|
||||
"vector_launch_sync",
|
||||
"vector_launch_sync_pop",
|
||||
"vector_pop",
|
||||
"vector_wrong_pop",
|
||||
"vector_lookup_unload",
|
||||
"vector_push",
|
||||
]
|
||||
.contains(&case);
|
||||
if execution_failure {
|
||||
let error = result.unwrap_err();
|
||||
let expected = match case {
|
||||
"vector_load" => vec![("cuModuleLoadData", 700)],
|
||||
"vector_lookup" => vec![("cuModuleGetFunction", 700)],
|
||||
"vector_lookup_unload" => vec![("cuModuleGetFunction", 700), ("cuModuleUnload", 700)],
|
||||
"vector_launch" => vec![("cuLaunchKernel", 700)],
|
||||
"vector_sync" => vec![("cuCtxSynchronize", 700)],
|
||||
"vector_launch_sync" => vec![("cuLaunchKernel", 700), ("cuCtxSynchronize", 700)],
|
||||
"vector_launch_sync_pop" => vec![
|
||||
("cuLaunchKernel", 700),
|
||||
("cuCtxSynchronize", 700),
|
||||
("cuCtxPopCurrent_v2", 700),
|
||||
],
|
||||
"vector_pop" => vec![("cuCtxPopCurrent_v2", 700)],
|
||||
"vector_push" => vec![("cuCtxPushCurrent_v2", 700)],
|
||||
_ => vec![],
|
||||
};
|
||||
assert_eq!(cuda_errors(&error), expected);
|
||||
if case == "vector_null_load" {
|
||||
assert!(matches!(
|
||||
error,
|
||||
Error::InvalidDriverValue("cuModuleLoadData")
|
||||
));
|
||||
}
|
||||
if case == "vector_null_function" {
|
||||
assert!(matches!(
|
||||
error,
|
||||
Error::InvalidDriverValue("cuModuleGetFunction")
|
||||
));
|
||||
}
|
||||
if case == "vector_wrong_pop" {
|
||||
assert_eq!(error, Error::UnexpectedContext);
|
||||
}
|
||||
if [
|
||||
"vector_sync",
|
||||
"vector_launch_sync",
|
||||
"vector_launch_sync_pop",
|
||||
"vector_pop",
|
||||
"vector_wrong_pop",
|
||||
"vector_lookup_unload",
|
||||
]
|
||||
.contains(&case)
|
||||
{
|
||||
let before = trace().len();
|
||||
assert!(context.vector_add_f32(&a, &b, &mut out).is_err());
|
||||
assert!(context.allocate(4).is_err());
|
||||
assert!(a.copy_from(&encode(&av)).is_err());
|
||||
assert!(context.synchronize().is_err());
|
||||
assert_eq!(trace().len(), before, "poison admits zero native work");
|
||||
// Encourage allocator reuse before containment reads pending args.
|
||||
let churn: Vec<_> = (0..1024).map(|_| Box::new([0xdeadbeefu64; 8])).collect();
|
||||
std::hint::black_box(churn);
|
||||
}
|
||||
} else {
|
||||
result.unwrap();
|
||||
if case == "vector_cache" {
|
||||
context.vector_add_f32(&a, &b, &mut out).unwrap();
|
||||
}
|
||||
let mut output = vec![0; bytes];
|
||||
out.copy_to(&mut output).unwrap();
|
||||
let expected: Vec<_> = av
|
||||
.iter()
|
||||
.zip(if case == "vector_same_input" {
|
||||
&av
|
||||
} else {
|
||||
&bv
|
||||
})
|
||||
.map(|(a, b)| (a + b).to_bits())
|
||||
.collect();
|
||||
let actual: Vec<_> = output
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|v| u32::from_ne_bytes(*v))
|
||||
.collect();
|
||||
assert_eq!(actual, expected, "independent exact finite f32 reference");
|
||||
let mut unchanged = vec![0; bytes];
|
||||
a.copy_to(&mut unchanged).unwrap();
|
||||
assert_eq!(unchanged, encode(&av));
|
||||
b.copy_to(&mut unchanged).unwrap();
|
||||
assert_eq!(unchanged, encode(&bv));
|
||||
if case == "vector_contexts" {
|
||||
let second = device.create_context(bytes * 3).unwrap();
|
||||
let mut x = second.allocate(bytes).unwrap();
|
||||
let mut y = second.allocate(bytes).unwrap();
|
||||
let mut z = second.allocate(bytes).unwrap();
|
||||
x.copy_from(&encode(&av)).unwrap();
|
||||
y.copy_from(&encode(&bv)).unwrap();
|
||||
second.vector_add_f32(&x, &y, &mut z).unwrap();
|
||||
z.copy_to(&mut output).unwrap();
|
||||
assert_eq!(
|
||||
output,
|
||||
encode(&av.iter().zip(&bv).map(|(a, b)| a + b).collect::<Vec<_>>())
|
||||
);
|
||||
drop((x, y, z));
|
||||
second.close().unwrap();
|
||||
}
|
||||
}
|
||||
drop((a, b, out));
|
||||
let closed = context.close();
|
||||
match case {
|
||||
"vector_unload" => assert_eq!(
|
||||
cuda_errors(&closed.unwrap_err()),
|
||||
vec![("cuModuleUnload", 700)]
|
||||
),
|
||||
"vector_close_pop" => assert_eq!(
|
||||
cuda_errors(&closed.unwrap_err()),
|
||||
vec![("cuCtxPopCurrent_v2", 700)]
|
||||
),
|
||||
"vector_close_destroy" => assert_eq!(
|
||||
cuda_errors(&closed.unwrap_err()),
|
||||
vec![("cuCtxDestroy_v2", 700)]
|
||||
),
|
||||
_ => closed.unwrap(),
|
||||
}
|
||||
let rows = trace();
|
||||
assert!(!rows.iter().any(|r| {
|
||||
[
|
||||
"unsafe_pending_free",
|
||||
"unsafe_pending_unload",
|
||||
"stack_arguments",
|
||||
]
|
||||
.contains(&r.stage.as_str())
|
||||
}));
|
||||
let expected_modules = if case == "vector_contexts" { 2 } else { 1 };
|
||||
if !["vector_load", "vector_null_load", "vector_push"].contains(&case) {
|
||||
assert_eq!(
|
||||
rows.iter()
|
||||
.filter(|r| r.stage == "load" && r.code == 0)
|
||||
.count(),
|
||||
expected_modules
|
||||
);
|
||||
}
|
||||
if !execution_failure {
|
||||
assert_eq!(
|
||||
rows.iter()
|
||||
.filter(|r| r.stage == "lookup" && r.code == 0)
|
||||
.count(),
|
||||
expected_modules
|
||||
);
|
||||
let launches = if ["vector_cache", "vector_contexts"].contains(&case) {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
assert_eq!(
|
||||
rows.iter().filter(|r| r.stage == "launch").count(),
|
||||
launches
|
||||
);
|
||||
assert!(
|
||||
rows.iter()
|
||||
.filter(|r| r.stage == "geometry")
|
||||
.all(|r| r.bytes == count.div_ceil(128))
|
||||
);
|
||||
assert!(
|
||||
rows.iter()
|
||||
.filter(|r| r.stage == "arguments")
|
||||
.all(|r| r.bytes == count)
|
||||
);
|
||||
}
|
||||
for (i, row) in rows.iter().enumerate().filter(|(_, r)| r.stage == "launch") {
|
||||
assert!(
|
||||
rows[i + 1..]
|
||||
.iter()
|
||||
.take_while(|r| r.stage != "pop")
|
||||
.any(|r| r.stage == "sync"),
|
||||
"mandatory sync after any launch attempt"
|
||||
);
|
||||
assert!([0, 700].contains(&row.code));
|
||||
}
|
||||
if [
|
||||
"vector_sync",
|
||||
"vector_launch_sync",
|
||||
"vector_launch_sync_pop",
|
||||
]
|
||||
.contains(&case)
|
||||
{
|
||||
assert_eq!(rows.iter().filter(|r| r.stage == "unload").count(), 0);
|
||||
assert!(
|
||||
rows.iter()
|
||||
.any(|r| r.stage == "pending_launch" && r.bytes == count)
|
||||
);
|
||||
}
|
||||
if ["vector_unload", "vector_lookup_unload"].contains(&case) {
|
||||
assert_eq!(
|
||||
rows.iter().filter(|r| r.stage == "unload").count(),
|
||||
1,
|
||||
"failed handle consumed once"
|
||||
);
|
||||
}
|
||||
for stage in ["load", "lookup", "unload", "launch"] {
|
||||
for row in rows.iter().filter(|r| r.stage == stage && r.code == 0) {
|
||||
assert!([0x22, 0x23].contains(&row.current));
|
||||
assert_eq!(row.depth, 1);
|
||||
}
|
||||
}
|
||||
if case != "vector_close_destroy" {
|
||||
let last = rows
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|r| r.stage == "destroy" && r.code == 0)
|
||||
.unwrap();
|
||||
assert_eq!(last.current, 0x11);
|
||||
assert_eq!(last.live, 0);
|
||||
assert_eq!(last.charged, 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
# Independent CUDA driver bootstrap contract
|
||||
|
||||
Requirements of record for bounded STRA-102 plan
|
||||
`d20f1568-5b7b-477d-8eab-a32219af7fd7`, before implementation.
|
||||
This foundation does not implement inference, model loading or GPU kernels and
|
||||
must not change production serving or advertise any supported model.
|
||||
|
||||
## Platform and ABI
|
||||
|
||||
- Explicit `cuda-driver` Cargo feature, disabled by default, plus an explicit
|
||||
`Driver::load()` call; Linux with 64-bit pointers. Unsupported platforms or
|
||||
disabled capability must return a clear error without touching a CUDA driver.
|
||||
- Load only the installed NVIDIA Driver ABI soname `libcuda.so.1` at runtime.
|
||||
No CUDA Toolkit, Strata, Python, C compiler or native build script is a
|
||||
production build/runtime dependency of this Rust crate.
|
||||
- Resolve the fixed documented legacy ABI symbols, with `_v2` context, device
|
||||
allocation/free and synchronous copy symbols where required. Missing symbols
|
||||
fail before CUDA initialization or resource mutation. No symbol-version
|
||||
fallback or API reinterpretation.
|
||||
- Isolate all unsafe FFI and dynamic loader code in the driver crate. Public
|
||||
callers get owned typed resources and errors, never raw host/device pointers
|
||||
or mutable CUDA context handles.
|
||||
|
||||
## Fixed ABI and source evidence
|
||||
|
||||
The exact symbol set is `cuInit`, `cuDriverGetVersion`, `cuDeviceGet`,
|
||||
`cuCtxCreate_v2`, `cuCtxDestroy_v2`, `cuCtxPushCurrent_v2`,
|
||||
`cuCtxPopCurrent_v2`, `cuCtxSynchronize`, `cuMemAlloc_v2`, `cuMemFree_v2`,
|
||||
`cuMemcpyHtoD_v2`, `cuMemcpyDtoH_v2`. The legacy create binding has three
|
||||
arguments: `CUcontext*`, `unsigned int`, `CUdevice`; the current unversioned
|
||||
CUDA 13 header macro points to the four-argument v4 entry instead and must
|
||||
not be rebound to this function type. Device pointers are 64-bit for this
|
||||
64-bit-only surface; byte counts use `size_t`.
|
||||
|
||||
Independent TL verification read the official
|
||||
[NVIDIA cudart 13.0.88 archive](https://developer.download.nvidia.com/compute/cuda/redist/cuda_cudart/linux-x86_64/cuda_cudart-linux-x86_64-13.0.88-archive.tar.xz)
|
||||
in memory, without installing headers or a toolkit. Archive size 1,491,604 bytes,
|
||||
SHA256 `bc44226f069402ab327bcf9e754660621aa6bc61fb7fc6afe03b794dfaaab658`;
|
||||
`cuda.h` SHA256 `64025f81a9d6d2b10e9e11654f3523e5b046d01b883f0b9ca474e463274b80d4`.
|
||||
Header lines 25633/90 prove the legacy declaration/current alias respectively;
|
||||
line 274 defines the 64-bit device pointer. Runtime behavior still requires
|
||||
separate installed-driver qualification. See NVIDIA's
|
||||
[synchronization behavior](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/api-sync-behavior.html)
|
||||
for why calling a synchronous-named copy alone does not prove completion of
|
||||
all host memory references.
|
||||
|
||||
## Ownership and context discipline
|
||||
|
||||
- Driver, context and device-buffer lifetimes keep the dynamic library alive
|
||||
until every dependent operation and cleanup finishes. Resources cannot be
|
||||
sent or shared between threads (`!Send`, `!Sync`).
|
||||
- Create a private context and pop it immediately, restoring the caller's
|
||||
previous context. Do not use or mutate an external primary context.
|
||||
- Push the owned context for every operation that needs it, and restore the
|
||||
previous context on both success and failure. Pop failures must surface as
|
||||
errors; never claim restoration after the driver rejects restoration.
|
||||
- Buffers cannot outlive their owner context; allocation/copy operations are
|
||||
bounded, checked before driver mutation and reject empty/oversized shapes.
|
||||
- Copies use exact-sized byte slices with bounded owned staging memory and the
|
||||
synchronous Driver API. DtoH publishes staging only after completion; ambiguous
|
||||
completion errors retain staging and poison the context to prevent dangling
|
||||
host DMA pointers. Synchronize
|
||||
before returning host borrows. Failed copy/synchronization paths must preserve
|
||||
context cleanup, while reporting the original driver failure accurately.
|
||||
- Cleanup is best-effort on drop, does not panic and must not free resources in
|
||||
an unrelated context. Explicit fallible cleanup should expose failure when
|
||||
the API supports it; permanently failed driver cleanup cannot be guaranteed.
|
||||
|
||||
## Independent CPU qualification
|
||||
|
||||
Only synthetic owned fixtures may be used. The test library is compiled to an
|
||||
ELF named `libcuda.so.1`, injected through a private subprocess loader environment
|
||||
inside a disposable Linux CPU Docker container. No installed driver is called,
|
||||
no NVIDIA device is exposed, and no GPU/model/request probe is performed.
|
||||
The fake library records synthetic ABI operations, context stack, allocated bytes,
|
||||
copy/sync actions and cleanup. Independent assertions cover missing symbols,
|
||||
init/device/create/push/pop/alloc/copy/sync/free/destroy errors, bounds before
|
||||
mutation, byte-copy round trips and prior-context restoration. Lifetime and
|
||||
thread-safety compile-fail gates are required as well as runtime tests.
|
||||
|
||||
All existing local gates remain; focused checks add crate format/Clippy/unit and
|
||||
the Linux ELF mock gate. Results below must report the actual environment,
|
||||
counts and cleanup, never infer GPU success from a mock or compile pass.
|
||||
|
||||
## Qualification state
|
||||
|
||||
Actual local CPU result on 2026-10-07:
|
||||
|
||||
- Linux **aarch64**, native CPU Docker Desktop execution; Rust 1.99.0
|
||||
(`b940084d7 2026-09-28`), GNU C compiler Debian 12.2.0-14+deb12u1.
|
||||
- Pinned Rust base OCI index:
|
||||
`sha256:114c7a4425406451c2866b6aafe69fe29b1b298832db1277d411ac73c82d04d6`.
|
||||
Independently inspected index contains Linux amd64 manifest
|
||||
`sha256:b36c246742b4d323472588f789601be34eb4af053255e2af53969078ee8dcec7`
|
||||
and arm64 manifest
|
||||
`sha256:e393e07b3c3c39f238de676b0eb60c03dc7aefe5d6e37be6d29c686bf4d7e256`.
|
||||
The final owned fixture image after installing matching rustfmt/Clippy was
|
||||
`sha256:a7fd4951f84b368826117e60c93f1e067ade2e39b2b69329108e70b052dd136d`.
|
||||
- Actual test container: nonroot UID/GID 65532, default runc, network `none`,
|
||||
all effective/permitted/bounding capabilities zero, no privileges, no host
|
||||
binds or device requests/devices; raw NVIDIA/DRI device guard passed.
|
||||
Build tools were provisioned in an earlier disposable setup container;
|
||||
all tests and compilation then ran offline with network disabled.
|
||||
- Minimal synthetic workspace contained only exact driver crate source/tests,
|
||||
matching workspace package/lint declarations, and approved pinned libc
|
||||
0.2.190. Engine, control-plane, CUDA Toolkit/headers/nvcc and installed
|
||||
`libcuda` were physically absent. The existing registry archive SHA256
|
||||
`ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78`
|
||||
was checked before extraction, then Cargo verified every vendored source
|
||||
checksum. Normal dependency tree was driver crate → libc only.
|
||||
- Default denial/unit tests: **2 passed**. Actual enabled-FFI all-target,
|
||||
all-feature Clippy with warnings denied and formatting passed.
|
||||
- **33 isolated subprocess scenarios passed**: round trip, pre-mutation
|
||||
shape/budget refusal, each of the twelve missing symbols, init/version/device,
|
||||
create/pop cleanup, push/pop errors, mismatched popped context and poisoned
|
||||
future work, allocation, both copy directions, explicit synchronization,
|
||||
copy-plus-sync dual errors in original/cleanup order, free and destroy faults.
|
||||
The fixture matrix is explicitly ignored by ordinary `cargo test`; the harness
|
||||
selects it with `--ignored` and requires its marker, so an absent harness
|
||||
cannot appear as a vacuous integration pass.
|
||||
- Delayed synthetic HtoD at destruction read the exact original eight owned
|
||||
staging bytes after the caller source was changed to zeros. Delayed DtoH at
|
||||
destruction wrote retained staging while the still-live caller destination
|
||||
remained unchanged after failed synchronization. These independently
|
||||
witness the declared staging/completion behavior, alongside source review;
|
||||
they are not a proof of all possible memory safety or vendor behavior.
|
||||
- **10 independent compile refusals passed**: Send and Sync for Driver, Device,
|
||||
Context and DeviceBuffer; context outliving Driver; buffer outliving Context.
|
||||
Assertions checked the expected auto-trait/borrow compiler diagnostics.
|
||||
- Final fake full/missing-DtoH ELF SHA256 values:
|
||||
`551878f9b518b200f8ac3dbf3570ec7494f1a2226917530c84ea30b418c1d41f` /
|
||||
`a95af6e51e678a5e3fc5f937b4232393493497161195391e256138a5d2009991`.
|
||||
Source hashes inside the container matched the working-tree bytes.
|
||||
- All owned setup/test containers, derived fixture images, private source
|
||||
staging, synthetic libraries, trace files and target directories were
|
||||
removed. The shared pinned base image and existing registry cache were retained.
|
||||
Cleanup attempts each resource independently, preserves test failure, and
|
||||
fails a successful test run if any cleanup fails.
|
||||
|
||||
Two initial fixture provisioning failures occurred before Rust integration:
|
||||
missing optional rustfmt/Clippy, then Docker tmpfs execution denial for libc's
|
||||
Rust build script. The final fixture installs verified toolchain components and
|
||||
uses an explicitly executable owned `/tmp`; product behavior and assertions
|
||||
were not weakened.
|
||||
|
||||
Production source receipts: `src/lib.rs`
|
||||
`7ce58fcf033b5e9704b2d134fc4c16cd2d5c57c5c45a867d2399c310dec3c4d4`;
|
||||
`src/ffi.rs` `5f00400fab73d98578ca53bfedcb86b4163133d2956a88ac3d2cd156455800c8`.
|
||||
|
||||
## Remaining integration limits
|
||||
|
||||
These outcomes qualify a GNU/Linux CPU mock contract. They do not execute an
|
||||
installed NVIDIA driver, GPU allocation/copy or a kernel, and they do not prove
|
||||
vendor cleanup succeeds after a driver failure. A sync fault deliberately
|
||||
retains bounded staging and poisons that context; failed destruction can retain
|
||||
the library/context instead of pretending release occurred. Repeated poisoned
|
||||
contexts can accumulate retained resources; there is no process-wide recovery
|
||||
or memory-bounded serving guarantee in this bootstrap.
|
||||
|
||||
The existing statically linked musl executable is also **unqualified** for this
|
||||
loader. [musl's static dlopen stub](https://git.musl-libc.org/cgit/musl/plain/src/ldso/dlopen.c)
|
||||
refuses dynamic loading; the GNU/Linux ELF mock pass does not make static musl
|
||||
capable of loading `libcuda.so.1`. A separate executable/loader integration gate
|
||||
is required. The OCI index admits amd64 builds, but this actual local mock run
|
||||
was arm64; hosted amd64/compiler qualification is separately pending.
|
||||
|
||||
Installed-driver GPU allocation/copy, kernel execution, model inference,
|
||||
model quality and paired performance remain separate unqualified gates.
|
||||
@@ -0,0 +1,238 @@
|
||||
# Fixed CUDA f32 vector-add requirements
|
||||
|
||||
Bounded STRA-102 requirements for plan
|
||||
`05e21fde-510e-4d63-8aa1-442e67339961`, written before implementation on
|
||||
base `0383253c6011ec795aa395b613405263f63378ee`.
|
||||
|
||||
This unit supplies one opt-in, typed operation over owned CUDA buffers:
|
||||
`out[i] = add.rn.f32(a[i], b[i])`. A successful return must mean the attempted
|
||||
launch completed and the caller's previous context was restored. Validation
|
||||
errs toward refusal before native mutation; uncertain completion or restoration
|
||||
errs toward poisoning and retaining resources. These properties can support
|
||||
bounded wrapper/ABI claims after their respective gates; they cannot establish
|
||||
model support or numerical execution merely from a mock or compilation.
|
||||
|
||||
The historical [bootstrap contract](cuda-driver-bootstrap.md) and its actual
|
||||
12-symbol qualification receipts remain unchanged. This document owns only the
|
||||
extension below. The charter remains the project goal and quality authority;
|
||||
this unit advances the independent Rust NVIDIA execution foundation without
|
||||
changing production serving or the imported Strata engine.
|
||||
|
||||
## Scope and caller outcome
|
||||
|
||||
An internal engine developer can explicitly enable the `cuda-driver` feature,
|
||||
load the driver, create a private context, allocate/upload two input buffers and
|
||||
an output buffer, invoke the fixed add operation and read the completed output.
|
||||
The safe interface accepts owned buffer references and returns structured errors;
|
||||
it accepts no PTX, module image, entry name, stream, launch geometry, raw pointer,
|
||||
foreign context or callback from a caller.
|
||||
|
||||
The existing default feature remains off. No new HTTP endpoint, worker switch,
|
||||
backend/model admission, scheduler, tensor loader, inference implementation or
|
||||
production deployment integration is included. Deployment of this foundation
|
||||
must continue to require only the installed NVIDIA driver rather than Strata,
|
||||
Python, a C compiler or CUDA Toolkit; offline verification tools are separate.
|
||||
|
||||
## Requirements and acceptance conditions
|
||||
|
||||
### FR-VADD-1 — validate owned shapes before mutation
|
||||
|
||||
- Accept two immutable input buffers and one mutable output buffer belonging to
|
||||
the exact same owned `Context` instance. Equal device ordinals or separate
|
||||
contexts on the same GPU do not establish ownership equality.
|
||||
- All three byte lengths must be equal, nonzero and divisible by four; interpret
|
||||
them as f32 elements. The element count must fit `u32`, byte bounds must retain
|
||||
the bootstrap's checked budget/`isize` constraints, and grid arithmetic must be
|
||||
checked without truncation or overflow.
|
||||
- Preserve safe aliasing: inputs may refer to the same immutable allocation;
|
||||
output must not alias an input. The public borrow contract must enforce this,
|
||||
with defensive identity refusal wherever implementation structure permits
|
||||
otherwise. No unsafe bypass is exposed publicly.
|
||||
- Reject invalid ownership, shape/count/geometry, unavailable capability and
|
||||
poisoned contexts before push, module load, lookup or launch. Do not mutate
|
||||
output or allocation accounting on validation refusal. Do not allocate new
|
||||
device buffers implicitly for this operation.
|
||||
|
||||
### FR-VADD-2 — one trusted module and function
|
||||
|
||||
- Embed a bounded, NUL-terminated PTX byte sequence in the crate. It contains
|
||||
exactly the fixed entry `leleka_vector_add_f32` with parameters in this order:
|
||||
input A u64 device address, input B u64 device address, output u64 device
|
||||
address, element count u32. Treat pointers as private ABI values, never public
|
||||
Rust handles. Record the exact embedded bytes' SHA256 for verification.
|
||||
- The entry checks `i < n` before any element access; address arithmetic must
|
||||
not wrap. Every in-range thread reads the corresponding A/B elements and
|
||||
writes exactly one output element. No input writes, external symbols,
|
||||
indirect calls, atomics, shared-memory state or out-of-range writes.
|
||||
- Use explicit `add.rn.f32` without `.ftz`, saturation, approximate arithmetic
|
||||
or floating-point contraction. No `fma`/`mad` substitutes for the add. The
|
||||
selected fixed image uses PTX 7.0, `sm_75`, and `.address_size 64`; unsupported
|
||||
driver/target combinations fail explicitly, not by selecting another kernel.
|
||||
- Cache at most one successfully loaded module/function per context, lazily
|
||||
after validation. Repeated successful calls reuse it. Publish a cache entry
|
||||
only after both load and function lookup succeeded with valid non-null
|
||||
handles. Failed initialization must not create a usable partial cache.
|
||||
|
||||
The arithmetic spelling is grounded in NVIDIA's archived
|
||||
[PTX floating-point add specification](https://docs.nvidia.com/cuda/archive/13.0.1/parallel-thread-execution/index.html#floating-point-instructions-add).
|
||||
This is the required arithmetic, not evidence that real hardware has executed
|
||||
it. Signed zeros, subnormal handling, overflow, infinities, NaNs and NaN payload
|
||||
behavior still require explicit installed-driver numerical qualification.
|
||||
|
||||
### FR-VADD-3 — fixed 16-symbol loader and launch ABI
|
||||
|
||||
Extend the bootstrap's fixed twelve symbols by precisely these four:
|
||||
|
||||
| Symbol | Private C ABI parameters | Return |
|
||||
| --- | --- | --- |
|
||||
| `cuModuleLoadData` | `CUmodule*`, `const void*` | `CUresult` |
|
||||
| `cuModuleGetFunction` | `CUfunction*`, `CUmodule`, `const char*` | `CUresult` |
|
||||
| `cuModuleUnload` | `CUmodule` | `CUresult` |
|
||||
| `cuLaunchKernel` | `CUfunction`, six `unsigned int` grid/block dimensions, `unsigned int` shared bytes, `CUstream`, `void** kernelParams`, `void** extra` | `CUresult` |
|
||||
|
||||
All sixteen resolve before `cuInit`; each missing extension symbol must fail
|
||||
before initialization. Keep the legacy bootstrap `_v2` signatures, soname,
|
||||
library lifetime and platform guards. Opaque module/function/stream pointers
|
||||
remain inside audited private FFI. The ABI references are NVIDIA's archived
|
||||
[module management](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/group__CUDA__MODULE.html)
|
||||
and [execution control](https://docs.nvidia.com/cuda/archive/13.0.1/cuda-driver-api/group__CUDA__EXEC.html)
|
||||
documentation. Independent advisory verification checked the official pinned
|
||||
cudart 13.0.88 archive (1,491,604 bytes, SHA256
|
||||
`bc44226f069402ab327bcf9e754660621aa6bc61fb7fc6afe03b794dfaaab658`)
|
||||
and `cuda.h` SHA256
|
||||
`64025f81a9d6d2b10e9e11654f3523e5b046d01b883f0b9ca474e463274b80d4`.
|
||||
Header lines 7365/7476/7532 identify load/unload/function lookup; lines
|
||||
17537–17547 identify launch with seven unsigned-int arguments including shared
|
||||
bytes. This is header evidence, not an execution result.
|
||||
|
||||
Launch one dimension with fixed block size 128, `grid.x = ceil(n / 128)`;
|
||||
grid/block y and z are one, shared memory is zero, stream is null, `extra` is
|
||||
null. `kernelParams` is a private four-entry array of pointers to the typed
|
||||
argument values above. Own the scalar/device-address parameter storage and
|
||||
pointer table, keeping their addresses stable through launch and synchronization.
|
||||
If the table references fields of its own storage object, establish those pointers
|
||||
only after stable heap placement; moving an inline self-referential object must
|
||||
not invalidate them. NVIDIA's documentation describes copying parameter values
|
||||
from the supplied regions, but this contract does not infer a stronger
|
||||
before-return timing guarantee from that wording;
|
||||
if completion is uncertain, retain any storage the driver could still reference
|
||||
and poison future work. No caller host pointer or arbitrary argument escapes
|
||||
into this interface. Compute the grid in a wider
|
||||
integer and require `grid.x <= i32::MAX`. Kernel index/address arithmetic must
|
||||
cover the final partial block without u32 overflow or reading beyond `n`.
|
||||
No caller can alter this launch shape. The driver may still reject this fixed
|
||||
shape on unsupported hardware; that is a reported operation failure.
|
||||
|
||||
### FR-VADD-4 — completion and context restoration
|
||||
|
||||
- Push the owned context for module/launch operations and pop it on all paths
|
||||
after a successful push, checking that the popped handle is the owned one.
|
||||
Successful operations and handled failures restore the prior caller context;
|
||||
a failed or mismatched pop reports the failure and poisons this context.
|
||||
- After **every attempted `cuLaunchKernel`**, synchronize even when launch
|
||||
returns an error. Retain the launch error and subsequent synchronization/pop
|
||||
errors in their operation order; cleanup must not replace the original error.
|
||||
A lookup/load failure before launch is not a launch attempt.
|
||||
- Return success only after launch, synchronization and restoration all succeed.
|
||||
Inputs stay immutable; output contents after a native execution failure are
|
||||
unspecified and must not be reported as a successfully computed vector.
|
||||
- Synchronization failure means completion is uncertain: poison the context,
|
||||
reject future allocation/copy/sync/kernel work without further native work,
|
||||
and keep possibly referenced buffers/module alive until safe context teardown.
|
||||
Do not free or unload them merely because a failed launch was observed.
|
||||
- Continue the bootstrap's staged-copy rule, including keeping ambiguous host
|
||||
DMA staging alive. A fixed kernel must not weaken existing copy/borrow safety.
|
||||
|
||||
### FR-VADD-5 — module ownership and failure cleanup
|
||||
|
||||
- Module/function cache lifetime is inside its owner context and dynamic-library
|
||||
lifetime. No public module or function can outlive that context or cross a
|
||||
thread; retain the existing `!Send`/`!Sync` resource guarantees.
|
||||
- On function lookup failure after module load, attempt unload in the owned
|
||||
current context. Consume the module's usable-handle slot before calling unload,
|
||||
regardless of its return value; unload at most once per handle. A failed
|
||||
unload poisons the context. Retain only context-owned residual/accounting for
|
||||
final destruction: never retry unload, reuse the handle or reinitialize a
|
||||
healthy cache after that failure. If restoration is uncertain, likewise
|
||||
report all relevant errors and forbid treating the module as a valid kernel.
|
||||
- Healthy teardown unloads the cached module after completed work, in the owned
|
||||
context, before destroying the context. Pending/uncertain work must not be
|
||||
followed by explicit module unload or buffer free. Context destruction is the
|
||||
final containment attempt; permanent driver failures cannot be called cleaned.
|
||||
- Explicit fallible close reports unload/restoration/destruction failures;
|
||||
destruction should still be attempted when safe. Drop remains best effort
|
||||
and nonpanicking. Failed destroy retains the library as required by the
|
||||
bootstrap rather than permitting calls through an unloaded library.
|
||||
- No automatic retries of a failed launch. Repeated poisoned contexts can
|
||||
retain resources; this unit supplies no process-wide recovery or cumulative
|
||||
resource bound and must not advertise a leak-free serving guarantee.
|
||||
|
||||
## Security and non-functional contract
|
||||
|
||||
| Dimension | Metric / threshold | Planned verification |
|
||||
| --- | --- | --- |
|
||||
| Critical usability | One typed add action; structured errors, no raw pointer/module interface | Public API review and synthetic caller |
|
||||
| Reliability | Success requires launch + completion + restoration; zero silent launch retries | Fault matrix and trace order |
|
||||
| Performance | No speed/SLO assertion; one launch and one mandatory completion sync per valid call | ABI trace, separate future paired benchmark |
|
||||
| Capacity | One cached module/context; fixed block128; checked count/grid and existing byte budget | Boundary/refusal and repeated-call tests |
|
||||
| Security / isolation | Exact context ownership, private fixed PTX/entry, no safe arbitrary execution surface | Cross-context/alias/ABI review and compile refusals |
|
||||
| Audit / retention | Only owned synthetic traces; no model/request/credentials in Git; private evidence outside source | Harness output and cleanup review |
|
||||
| Observability | Fixed operation names, driver codes, ordered primary/cleanup errors; no pointers or PTX dumps in error text | Fault assertions and error-text inspection |
|
||||
| Accessibility / i18n | No UI is introduced; existing user interfaces/locales remain unchanged | Changed-surface review |
|
||||
| Rate / admission | One synchronous call on the creating thread; existing per-context memory budget; no new network/tenant admission | Thread/lifetime gates and budget refusals |
|
||||
| Deploy / rollback | Default feature off, no serving consumer, no deployment-tool dependency added; disable opt-in to return to existing path | Feature/default/dependency/consumer review |
|
||||
| Support | Load/lookup/launch/completion/cleanup failures remain diagnosable; no production support SLA is claimed | Error matrix and documented residuals |
|
||||
| AI dependence | This fixed arithmetic operation performs no model call; no AI output or quality gate substituted by it | Consumer/source review |
|
||||
| Integrity | Inputs unchanged; output published as success only for completed add; no hidden persistent state except bounded cache | Synthetic data/canaries and cache traces |
|
||||
| Backup / recovery | No durable data introduced; failed driver teardown is reported/retained, not treated as recovery | Fault/ownership review |
|
||||
| Privacy | Only sanitized synthetic vectors permitted in this unit's verification | Fixture and artifact review |
|
||||
| Maintainability | Four additional exact symbols, one embedded module/entry, no new normal dependency | Source/ABI/dependency review |
|
||||
| Compatibility | Linux 64-bit opt-in only; legacy12 bindings and existing33 mock/10 compile guards preserved | Default/platform and regression gates |
|
||||
| Cost / efficiency | CPU mock/tooling work only for this delivery; no GPU/probe/model access, no duplicated CI | Recorded commands and container guards |
|
||||
|
||||
## Verification plan — outcomes not yet measured
|
||||
|
||||
The planned instruments derive from the requirements and official ABI, rather
|
||||
than obtaining expected outputs from the wrapper implementation. A synthetic
|
||||
mock can witness argument/context/cleanup behavior and expected fixture data;
|
||||
it does not execute or establish correctness of the embedded PTX instructions.
|
||||
|
||||
| Gate | Required checks / predicted refusal | Claim licensed by a pass |
|
||||
| --- | --- | --- |
|
||||
| Existing regression | Retain all 33 bootstrap mock cases and 10 compile refusals, default-denial units, enabled FFI format/Clippy | Existing contract still holds against changed source |
|
||||
| Missing extension symbols | Independently omit each of four new symbols; zero `cuInit` and resource mutation | Fixed16 pre-initialization admission |
|
||||
| Typed validation | Different contexts on same device; unequal/nonmultiple4/empty shapes; count/grid overflow; invalid output alias; poisoned context. All refuse before push/load/launch | Bounded safe wrapper admission |
|
||||
| ABI and synthetic data | Verify exact trusted PTX/entry identity, parameter order/width/value and live owned device allocations, fixed dimensions/null stream/null extra, context sentinel, input immutability/output/canaries | Mocked host ABI/dataflow only |
|
||||
| Launch bounds | Counts 1,127,128,129 and a bounded larger nonmultiple128 vector; checked maximum/count-overflow tests without giant allocations | Shape/tail guard contract, not real GPU memory safety |
|
||||
| Cache/lifetime | First valid call loads/looks up once; next call reuses; independent contexts own separate caches; zero unload with pending work; healthy unload before destroy | Bounded cache and resource ordering |
|
||||
| Faults | Load/lookup/null-success handles/push/launch/sync/pop/wrong-pop/unload/destroy, plus launch+sync and lookup+unload errors; failed unload consumed once, no retry/reuse/cache reinitialization | Original errors retained, cleanup attempts, poison/refusal behavior |
|
||||
| Delayed completion | Mock defers add completion to sync, including dereferencing retained parameter storage; failed sync leaves work pending until containment; no early argument release/buffer free/module unload; caller output never presented as successful after failure | Declared containment behavior alongside source review |
|
||||
| Ownership compile gates | Existing driver/context/buffer borrow and thread refusals remain; no safe arbitrary module/function/pointer escape | Rust safe API lifetime/thread surface |
|
||||
| Offline PTX assembly | GPU-hidden Linux CPU Docker with pinned `ptxas`; exact PTX SHA, tool/version/container target and flags; no devices, installed driver calls or user data | PTX assembler acceptance for the recorded target only |
|
||||
| Installed-driver numerical execution | Separate authorized real-GPU gate: independent f32 reference; declare finite tolerance before execution (target exact finite bits), signed zeros/subnormal/overflow/Inf/NaN cases with NaN classification/payload limits | Only the executed hardware/driver numerical scope |
|
||||
| Model / protocol / throughput | Separate Qwen and two named MoE integration, real quality/protocol gates, same-workload paired distributions/provenance | Whole-engine claims only after their own evidence |
|
||||
|
||||
Record actual argv, source/commit and embedded PTX hashes, toolchain, architecture,
|
||||
image/ELF identity, environment/guards, exact test counts, failures and exit codes.
|
||||
Keep generated evidence private outside Git, remove owned disposable resources,
|
||||
and report cleanup failures. No number in the planned matrix is a measured pass.
|
||||
|
||||
## Remaining platform and qualification boundaries
|
||||
|
||||
GNU/Linux 64-bit CPU mock/assembly results do not qualify the existing static
|
||||
musl executable for `dlopen(libcuda.so.1)`. Its loader integration remains open,
|
||||
as described in the historical bootstrap contract. PTX loading may require the
|
||||
installed driver to JIT the fixed image; driver/JIT compatibility is unqualified
|
||||
until a separate real-driver gate. No Toolkit becomes a deployment prerequisite
|
||||
merely because offline assembly is used for validation.
|
||||
|
||||
No real GPU allocation, kernel execution, model support, quality, protocol
|
||||
completion, rollback or performance is established by this requirements unit.
|
||||
The autonomous engine parent and its dependent intake/delivery items remain
|
||||
open under root coordination. No admission/closure flags are changed here.
|
||||
|
||||
No active host-local `.leasevibe.yaml` pointer was supplied; it was absent in
|
||||
the worktree and canonical repository. Task-relevant host settings are therefore
|
||||
unavailable, not inferred. The explicit session restrictions remain binding:
|
||||
Gitea only for future publication/CI, no merge, no active Qwen/runtime changes,
|
||||
no GPU/model/user-data probes. This BA unit changes only this requirements file.
|
||||
@@ -5,6 +5,8 @@ repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
|
||||
python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py"
|
||||
python3 "${repo_root}/scripts/test-benchmark-harness.py"
|
||||
python3 "${repo_root}/scripts/test-paired-report.py"
|
||||
python3 "${repo_root}/scripts/test-paired-markdown.py"
|
||||
python3 "${repo_root}/scripts/test-native-service.py"
|
||||
python3 "${repo_root}/scripts/test-native-api.py"
|
||||
python3 "${repo_root}/scripts/test-native-menu.py"
|
||||
@@ -24,6 +26,10 @@ cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-backend-
|
||||
cargo fmt --manifest-path "${repo_root}/crates/quant-core/Cargo.toml" --check
|
||||
cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-quant-core --all-targets -- -D warnings
|
||||
cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-quant-core
|
||||
cargo fmt --manifest-path "${repo_root}/crates/cuda-driver/Cargo.toml" --check
|
||||
cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-cuda-driver --all-targets --all-features -- -D warnings
|
||||
cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-cuda-driver
|
||||
"${repo_root}/scripts/test-cuda-driver-bootstrap.sh"
|
||||
cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check
|
||||
cargo clippy --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --all-targets -- -D warnings
|
||||
cargo test --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked
|
||||
|
||||
+453
-139
@@ -1,69 +1,379 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare two private, sequential runs of bench-chat-paired.py.
|
||||
"""Descriptively compare two private, sequential bench-chat-paired.py runs.
|
||||
|
||||
Useful on one GPU when both model arms cannot fit in VRAM together. The output
|
||||
is a descriptive paired report; load order and disk/cache drift still matter.
|
||||
No performance/model-quality qualification follows from this offline report.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import sys
|
||||
|
||||
MAX_INPUT_BYTES = 32 * 1024 * 1024
|
||||
MAX_CASES = 64
|
||||
MAX_PAIRS = 4096
|
||||
MAX_REPEATS = 100
|
||||
MAX_NUMBER = 1e12
|
||||
COUNT_FIELDS = {"prompt_n", "predicted_n", "cache_n", "draft_n", "draft_accepted_n"}
|
||||
USAGE_COUNTS = {"prompt_tokens", "completion_tokens", "total_tokens", "input_tokens",
|
||||
"output_tokens", "cached_tokens", "reasoning_tokens",
|
||||
"accepted_prediction_tokens", "rejected_prediction_tokens"}
|
||||
# Canonical private metadata keys. Presence is an operator assertion, not proof.
|
||||
PROVENANCE_FIELDS = (
|
||||
"engine_commit", "control_plane_commit", "model_sha256", "quantization",
|
||||
"gpu", "driver", "cuda_toolkit", "power_limit_watts", "context_tokens",
|
||||
"kv_configuration", "slots", "batch_size", "speculation", "cache_state",
|
||||
"workload_sha256", "quality_gate_result", "draft_acceptance_rate",
|
||||
"expert_cache_hit_rate", "kv_streaming_hit_rate",
|
||||
)
|
||||
LIMITATION = (
|
||||
"Descriptive only: sequential model loads and requests may drift with I/O, "
|
||||
"cache state and load order; repeats may be correlated. Synthetic/CPU "
|
||||
"results and supplied metadata do not qualify GPU inference, end-to-end "
|
||||
"agent performance or model quality. Pooled cases/categories depend on "
|
||||
"their case composition; uncertainty assumes independent pairs sharing "
|
||||
"a common population median."
|
||||
)
|
||||
|
||||
|
||||
def reject(message):
|
||||
# Fixed field names only; never include values from a private report.
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def integer(value, minimum=0, maximum=int(MAX_NUMBER)):
|
||||
return type(value) is int and minimum <= value <= maximum
|
||||
|
||||
|
||||
def number(value, positive=False):
|
||||
return (type(value) in (int, float) and math.isfinite(value)
|
||||
and (value > 0 if positive else value >= 0) and value <= MAX_NUMBER)
|
||||
|
||||
|
||||
def label(value):
|
||||
return isinstance(value, str) and bool(value.strip()) and len(value) <= 128
|
||||
|
||||
|
||||
def unique_object(items):
|
||||
result = {}
|
||||
for key, value in items:
|
||||
if key in result:
|
||||
reject("duplicate JSON field")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def finite_float(text):
|
||||
value = float(text)
|
||||
if not math.isfinite(value):
|
||||
reject("nonfinite JSON number")
|
||||
return value
|
||||
|
||||
|
||||
def bounded_tree(report):
|
||||
# Keep only one iterator per depth, not a second copy of a wide JSON array.
|
||||
stack = [(iter((report,)), 0)]
|
||||
nodes = 0
|
||||
while stack:
|
||||
iterator, depth = stack[-1]
|
||||
try:
|
||||
value = next(iterator)
|
||||
except StopIteration:
|
||||
stack.pop()
|
||||
continue
|
||||
nodes += 1
|
||||
if depth > 32 or nodes > 1_000_000:
|
||||
reject("report exceeds structure limit")
|
||||
if isinstance(value, dict):
|
||||
stack.append((iter(value.values()), depth + 1))
|
||||
elif isinstance(value, list):
|
||||
stack.append((iter(value), depth + 1))
|
||||
elif type(value) is float and not math.isfinite(value):
|
||||
reject("nonfinite JSON number")
|
||||
|
||||
|
||||
def load_report(path):
|
||||
with path.open("rb") as source:
|
||||
raw = source.read(MAX_INPUT_BYTES + 1)
|
||||
if len(raw) > MAX_INPUT_BYTES:
|
||||
reject("report exceeds input byte limit")
|
||||
try:
|
||||
report = json.loads(raw, object_pairs_hook=unique_object, parse_float=finite_float,
|
||||
parse_constant=lambda _: reject("nonfinite JSON number"))
|
||||
except (UnicodeError, json.JSONDecodeError, RecursionError):
|
||||
reject("invalid report JSON")
|
||||
bounded_tree(report)
|
||||
validate_report(report)
|
||||
return report
|
||||
|
||||
|
||||
def normalized(row):
|
||||
try:
|
||||
message = row["response"]["choices"][0]["message"]
|
||||
return {
|
||||
"content": message.get("content"),
|
||||
"tool_calls": [
|
||||
{"name": call["function"]["name"],
|
||||
"arguments": json.loads(call["function"]["arguments"])}
|
||||
for call in message.get("tool_calls") or []
|
||||
],
|
||||
}
|
||||
except (KeyError, IndexError, TypeError, ValueError):
|
||||
choices = row["response"]["choices"]
|
||||
if not isinstance(choices, list) or len(choices) != 1:
|
||||
return None
|
||||
choice = choices[0]
|
||||
message = choice["message"]
|
||||
if message.get("role") != "assistant" or choice.get("finish_reason") not in ("stop", "tool_calls"):
|
||||
return None
|
||||
content = message.get("content")
|
||||
if content is not None and not isinstance(content, str):
|
||||
return None
|
||||
calls = message.get("tool_calls")
|
||||
if calls is None:
|
||||
calls = []
|
||||
if not isinstance(calls, list) or len(calls) > 128:
|
||||
return None
|
||||
if bool(calls) != (choice["finish_reason"] == "tool_calls"):
|
||||
return None
|
||||
tools, call_ids = [], set()
|
||||
for call in calls:
|
||||
call_id = call.get("id")
|
||||
if not label(call_id) or call_id in call_ids:
|
||||
return None
|
||||
call_ids.add(call_id)
|
||||
function = call["function"]
|
||||
if call.get("type") != "function" or not label(function["name"]):
|
||||
return None
|
||||
if not isinstance(function["arguments"], str):
|
||||
return None
|
||||
arguments = json.loads(function["arguments"], object_pairs_hook=unique_object, parse_float=finite_float,
|
||||
parse_constant=lambda _: reject("nonfinite tool JSON"))
|
||||
if not isinstance(arguments, dict):
|
||||
return None
|
||||
bounded_tree(arguments)
|
||||
tools.append({"name": function["name"], "arguments": arguments})
|
||||
if content is None and not tools:
|
||||
return None
|
||||
return {"content": content, "tool_calls": tools}
|
||||
except (KeyError, IndexError, TypeError, ValueError, AttributeError, RecursionError):
|
||||
return None
|
||||
|
||||
|
||||
def selected(report):
|
||||
rows = {}
|
||||
for row in report["rows"]:
|
||||
def validate_usage(usage):
|
||||
if usage is None:
|
||||
return
|
||||
if not isinstance(usage, dict):
|
||||
reject("usage must be an object")
|
||||
for key, value in usage.items():
|
||||
if key in USAGE_COUNTS and not integer(value):
|
||||
reject("usage token count must be a bounded nonnegative integer")
|
||||
if key in ("prompt_tokens_details", "completion_tokens_details",
|
||||
"input_tokens_details", "output_tokens_details"):
|
||||
if not isinstance(value, dict):
|
||||
reject("usage token details must be an object")
|
||||
validate_usage(value)
|
||||
if all(key in usage for key in ("prompt_tokens", "completion_tokens", "total_tokens")):
|
||||
if usage["prompt_tokens"] + usage["completion_tokens"] != usage["total_tokens"]:
|
||||
reject("usage total_tokens is inconsistent")
|
||||
for prefix in ("prompt", "input"):
|
||||
total = usage.get(prefix + "_tokens")
|
||||
cached = usage.get(prefix + "_tokens_details", {}).get("cached_tokens")
|
||||
if total is not None and cached is not None and cached > total:
|
||||
reject("usage cached_tokens exceeds input tokens")
|
||||
|
||||
|
||||
def validate_report(report):
|
||||
if not isinstance(report, dict) or type(report.get("schema")) is not int or report["schema"] != 1:
|
||||
reject("unsupported report schema")
|
||||
digest = report.get("suite_sha256")
|
||||
if (not isinstance(digest, str) or len(digest) != 64
|
||||
or any(char not in "0123456789abcdefABCDEF" for char in digest)):
|
||||
reject("suite_sha256 must be a SHA-256 digest")
|
||||
if not label(report.get("model")):
|
||||
reject("model must be a bounded nonempty string")
|
||||
config = report.get("configuration")
|
||||
if not isinstance(config, dict) or not integer(config.get("repeats"), 1, MAX_REPEATS):
|
||||
reject("configuration.repeats is invalid")
|
||||
for field in ("max_tokens", "seed"):
|
||||
if field in config and not integer(config[field], 1 if field == "max_tokens" else 0):
|
||||
reject("configuration integer is invalid")
|
||||
if "temperature" in config and not number(config["temperature"]):
|
||||
reject("configuration.temperature is invalid")
|
||||
if "stream" in config and config["stream"] is not False:
|
||||
reject("configuration.stream must be false")
|
||||
for field in ("reasoning_effort", "cache_state"):
|
||||
if field in config and (not isinstance(config[field], str) or not config[field].strip() or len(config[field]) > 1024):
|
||||
reject("configuration text field is invalid")
|
||||
if not isinstance(report.get("metadata", {}), dict):
|
||||
reject("metadata must be an object")
|
||||
rows = report.get("rows")
|
||||
if not isinstance(rows, list) or not rows or len(rows) > MAX_PAIRS + MAX_CASES:
|
||||
reject("rows exceed report limits or are empty")
|
||||
cases, measured, warmups, arms = {}, set(), set(), set()
|
||||
for row in rows:
|
||||
if not isinstance(row, dict) or not label(row.get("case_id")) or not label(row.get("category")):
|
||||
reject("row case_id/category is invalid")
|
||||
if row.get("arm") not in ("baseline", "candidate"):
|
||||
reject("row arm is invalid")
|
||||
arms.add(row["arm"])
|
||||
case = row["case_id"]
|
||||
if case in cases and cases[case] != row["category"]:
|
||||
reject("case category changes between rows")
|
||||
cases[case] = row["category"]
|
||||
if type(row.get("warmup")) is not bool:
|
||||
reject("row warmup must be boolean")
|
||||
if row["warmup"]:
|
||||
continue
|
||||
key = (row["case_id"], row["repeat"])
|
||||
if key in rows:
|
||||
raise ValueError(f"duplicate run {key}")
|
||||
rows[key] = row
|
||||
return rows
|
||||
if row.get("repeat") is not None or case in warmups:
|
||||
reject("invalid or duplicate warmup")
|
||||
warmups.add(case)
|
||||
else:
|
||||
repeat = row.get("repeat")
|
||||
if not integer(repeat, 0, config["repeats"] - 1) or (case, repeat) in measured:
|
||||
reject("invalid or duplicate measured repeat")
|
||||
measured.add((case, repeat))
|
||||
if not number(row.get("wall_seconds"), positive=True):
|
||||
reject("wall_seconds must be finite and positive")
|
||||
if not integer(row.get("http_status"), 100, 599):
|
||||
reject("http_status is invalid")
|
||||
quality = row.get("quality")
|
||||
if not isinstance(quality, dict) or type(quality.get("passed")) is not bool:
|
||||
reject("quality.passed must be boolean")
|
||||
response = row.get("response")
|
||||
if not isinstance(response, dict):
|
||||
reject("response must be an object")
|
||||
if quality["passed"] and (row["http_status"] != 200 or normalized(row) is None):
|
||||
reject("quality.passed contradicts HTTP/terminal response")
|
||||
validate_usage(response.get("usage"))
|
||||
timing = response.get("timings")
|
||||
if timing is not None:
|
||||
if not isinstance(timing, dict):
|
||||
reject("timings must be an object")
|
||||
for key, value in timing.items():
|
||||
if key in COUNT_FIELDS or key.endswith("_n"):
|
||||
if not integer(value):
|
||||
reject("timing token count must be a bounded nonnegative integer")
|
||||
elif not number(value):
|
||||
reject("optional timing must be finite and nonnegative")
|
||||
if (len(arms) != 1 or len(cases) > MAX_CASES or len(measured) > MAX_PAIRS
|
||||
or warmups != cases.keys()
|
||||
or len(measured) != len(cases) * config["repeats"]):
|
||||
reject("report must contain one arm and complete warmup/repeat coverage")
|
||||
|
||||
|
||||
def selected(report):
|
||||
return {(row["case_id"], row["repeat"]): row for row in report["rows"] if not row["warmup"]}
|
||||
|
||||
|
||||
def percentile(values, fraction):
|
||||
position = (len(values) - 1) * fraction
|
||||
lower = int(position)
|
||||
remainder = position - lower
|
||||
return values[lower] * (1 - remainder) + values[min(lower + 1, len(values) - 1)] * remainder
|
||||
|
||||
|
||||
def median_interval(values):
|
||||
"""Exact distribution-free paired median order-statistic interval.
|
||||
|
||||
Pick the narrowest symmetric interval with >=95% binomial coverage.
|
||||
Below six pairs no finite two-sided 95% interval exists; disclose null bounds.
|
||||
"""
|
||||
n = len(values)
|
||||
total = 1 << n
|
||||
weight, tail, chosen, chosen_tail = 1, 0, 0, 0
|
||||
for k in range(1, n // 2 + 1):
|
||||
tail += weight
|
||||
if 40 * tail > total:
|
||||
break
|
||||
chosen, chosen_tail = k, tail
|
||||
weight = weight * (n - k + 1) // k
|
||||
return {
|
||||
"method": "exact paired median order-statistic interval",
|
||||
"confidence_level": 0.95,
|
||||
"coverage_lower_bound": 1 - 2 * chosen_tail / total if chosen else None,
|
||||
"lower": values[chosen - 1] if chosen else None,
|
||||
"upper": values[n - chosen] if chosen else None,
|
||||
"finite_interval_available": bool(chosen),
|
||||
"assumption": "independent pairs with a common population median; ties are conservative",
|
||||
}
|
||||
|
||||
|
||||
def distribution(values, uncertainty=False):
|
||||
values = sorted(values)
|
||||
result = {"sample_count": len(values), "mean": statistics.fmean(values),
|
||||
"median": statistics.median(values), "p10": percentile(values, 0.1),
|
||||
"p90": percentile(values, 0.9), "small_sample": len(values) < 30}
|
||||
if uncertainty:
|
||||
result["median_confidence_interval"] = median_interval(values)
|
||||
return result
|
||||
|
||||
|
||||
def ratio(candidate, baseline):
|
||||
result = candidate / baseline
|
||||
if not math.isfinite(result) or result <= 0:
|
||||
reject("paired ratio is not finite and positive")
|
||||
return result
|
||||
|
||||
|
||||
def throughput(pairs, field):
|
||||
measured = [(pair["baseline_timings"].get(field), pair["candidate_timings"].get(field))
|
||||
for pair in pairs]
|
||||
valid = [(a, b) for a, b in measured if a is not None and b is not None and a > 0 and b > 0]
|
||||
if not valid:
|
||||
return None
|
||||
ratios = [ratio(b, a) for a, b in valid]
|
||||
return {
|
||||
"pairs": len(valid), "unavailable_pairs": len(pairs) - len(valid),
|
||||
"baseline_median_tokens_per_second": statistics.median(a for a, _ in valid),
|
||||
"candidate_median_tokens_per_second": statistics.median(b for _, b in valid),
|
||||
"candidate_over_baseline_median_ratio": statistics.median(ratios),
|
||||
"baseline_distribution": distribution([a for a, _ in valid]),
|
||||
"candidate_distribution": distribution([b for _, b in valid]),
|
||||
"candidate_over_baseline_ratio_distribution": distribution(ratios, uncertainty=True),
|
||||
}
|
||||
|
||||
|
||||
def group_summary(pairs):
|
||||
baseline_failed = sum(not pair["baseline_quality_passed"] for pair in pairs)
|
||||
candidate_failed = sum(not pair["candidate_quality_passed"] for pair in pairs)
|
||||
mismatched = sum(not pair["same_normalized_output"] for pair in pairs)
|
||||
return {
|
||||
"pairs": len(pairs),
|
||||
"same_normalized_output": len(pairs) - mismatched,
|
||||
"both_quality_passed": sum(pair["baseline_quality_passed"] and
|
||||
pair["candidate_quality_passed"] for pair in pairs),
|
||||
"candidate_over_baseline_wall_median_ratio": statistics.median(
|
||||
pair["candidate_over_baseline_wall_ratio"] for pair in pairs),
|
||||
"wall_seconds": {
|
||||
"baseline": distribution([pair["baseline_wall_seconds"] for pair in pairs]),
|
||||
"candidate": distribution([pair["candidate_wall_seconds"] for pair in pairs]),
|
||||
},
|
||||
"candidate_over_baseline_wall_ratio_distribution": distribution(
|
||||
[pair["candidate_over_baseline_wall_ratio"] for pair in pairs], uncertainty=True),
|
||||
"quality": {"baseline_failed": baseline_failed, "candidate_failed": candidate_failed,
|
||||
"normalized_output_mismatches": mismatched,
|
||||
"baseline_http_or_protocol_failed": sum(pair["baseline_protocol_failed"] for pair in pairs),
|
||||
"candidate_http_or_protocol_failed": sum(pair["candidate_protocol_failed"] for pair in pairs),
|
||||
"observed_checks_passed": not (baseline_failed or candidate_failed or mismatched)},
|
||||
"timing_coverage": {
|
||||
field: {"available_pairs": sum(pair["baseline_timings"].get(field, 0) > 0 and
|
||||
pair["candidate_timings"].get(field, 0) > 0 for pair in pairs),
|
||||
"total_pairs": len(pairs)}
|
||||
for field in ("prompt_per_second", "predicted_per_second")
|
||||
},
|
||||
"prefill": throughput(pairs, "prompt_per_second"),
|
||||
"decode": throughput(pairs, "predicted_per_second"),
|
||||
}
|
||||
|
||||
|
||||
def initial_requests(base, candidate):
|
||||
def rows(report):
|
||||
selected_rows = {}
|
||||
for row in report["rows"]:
|
||||
if row["warmup"]:
|
||||
case = row["case_id"]
|
||||
if case in selected_rows:
|
||||
raise ValueError(f"duplicate initial request for {case}")
|
||||
selected_rows[case] = row
|
||||
return selected_rows
|
||||
|
||||
b_rows, c_rows = rows(base), rows(candidate)
|
||||
b_rows = {row["case_id"]: row for row in base["rows"] if row["warmup"]}
|
||||
c_rows = {row["case_id"]: row for row in candidate["rows"] if row["warmup"]}
|
||||
if b_rows.keys() != c_rows.keys():
|
||||
raise ValueError("initial requests differ between arms")
|
||||
reject("initial requests differ between arms")
|
||||
result = {}
|
||||
for case in sorted(b_rows):
|
||||
b, c = b_rows[case], c_rows[case]
|
||||
b_timing = b["response"].get("timings") or {}
|
||||
c_timing = c["response"].get("timings") or {}
|
||||
if b["category"] != c["category"]:
|
||||
reject("initial case category differs")
|
||||
b_timing, c_timing = b["response"].get("timings") or {}, c["response"].get("timings") or {}
|
||||
result[case] = {
|
||||
"baseline_wall_seconds": b["wall_seconds"],
|
||||
"candidate_wall_seconds": c["wall_seconds"],
|
||||
"baseline_quality_passed": b["quality"]["passed"],
|
||||
"candidate_quality_passed": c["quality"]["passed"],
|
||||
"baseline_wall_seconds": b["wall_seconds"], "candidate_wall_seconds": c["wall_seconds"],
|
||||
"baseline_quality_passed": b["quality"]["passed"], "candidate_quality_passed": c["quality"]["passed"],
|
||||
"baseline_prompt_tokens_processed": b_timing.get("prompt_n"),
|
||||
"candidate_prompt_tokens_processed": c_timing.get("prompt_n"),
|
||||
"baseline_cached_prompt_tokens": b_timing.get("cache_n"),
|
||||
@@ -74,35 +384,71 @@ def initial_requests(base, candidate):
|
||||
return result
|
||||
|
||||
|
||||
def throughput(pairs, field):
|
||||
measured = []
|
||||
def provenance(report):
|
||||
metadata = report.get("metadata", {})
|
||||
missing = [field for field in PROVENANCE_FIELDS if metadata.get(field) in (None, "", [], {})]
|
||||
measured = [row for row in report["rows"] if not row["warmup"]]
|
||||
if not all(any((row["response"].get("timings") or {}).get(key, 0) > 0
|
||||
for key in ("ttft_ms", "ttft_seconds")) for row in measured):
|
||||
missing.append("ttft")
|
||||
if not all(all(key in (row["response"].get("usage") or {})
|
||||
for key in ("prompt_tokens", "completion_tokens")) for row in measured):
|
||||
missing.append("prompt_output_token_counts")
|
||||
return {"missing_fields": missing, "metadata_presence_is_not_verified_evidence": True}
|
||||
|
||||
|
||||
def compare(base, candidate):
|
||||
for field in ("schema", "suite_sha256", "model", "configuration"):
|
||||
if base[field] != candidate[field]:
|
||||
reject("reports differ in " + field)
|
||||
# An intended code/codec change may differ between arms, but a declared
|
||||
# different workload/hardware/cache setup cannot be pooled as matched pairs.
|
||||
for field in ("gpu", "driver", "power_limit_watts", "model_sha256", "context_tokens",
|
||||
"kv_configuration", "slots", "batch_size", "speculation", "cache_state", "workload_sha256"):
|
||||
b_value, c_value = base.get("metadata", {}).get(field), candidate.get("metadata", {}).get(field)
|
||||
if b_value not in (None, "", [], {}) and c_value not in (None, "", [], {}) and b_value != c_value:
|
||||
reject("incompatible paired provenance field")
|
||||
b_rows, c_rows = selected(base), selected(candidate)
|
||||
if not b_rows or b_rows.keys() != c_rows.keys():
|
||||
reject("reports do not contain the same measured cases")
|
||||
pairs = []
|
||||
for key in sorted(b_rows):
|
||||
b, c = b_rows[key], c_rows[key]
|
||||
if b["category"] != c["category"]:
|
||||
reject("case category differs")
|
||||
b_normal, c_normal = normalized(b), normalized(c)
|
||||
pairs.append({
|
||||
"case_id": key[0], "repeat": key[1], "category": b["category"],
|
||||
"baseline_wall_seconds": b["wall_seconds"], "candidate_wall_seconds": c["wall_seconds"],
|
||||
"candidate_over_baseline_wall_ratio": ratio(c["wall_seconds"], b["wall_seconds"]),
|
||||
"baseline_quality_passed": b["quality"]["passed"], "candidate_quality_passed": c["quality"]["passed"],
|
||||
"baseline_protocol_failed": b["http_status"] != 200 or b_normal is None,
|
||||
"candidate_protocol_failed": c["http_status"] != 200 or c_normal is None,
|
||||
"same_normalized_output": b["http_status"] == c["http_status"] == 200 and b_normal is not None and b_normal == c_normal,
|
||||
"baseline_usage": b["response"].get("usage"), "candidate_usage": c["response"].get("usage"),
|
||||
"baseline_timings": b["response"].get("timings") or {}, "candidate_timings": c["response"].get("timings") or {},
|
||||
})
|
||||
grouped_cases, grouped_categories = {}, {}
|
||||
for pair in pairs:
|
||||
baseline = pair["baseline_timings"].get(field)
|
||||
candidate = pair["candidate_timings"].get(field)
|
||||
if (isinstance(baseline, (int, float)) and isinstance(candidate, (int, float))
|
||||
and baseline > 0 and candidate > 0):
|
||||
measured.append((baseline, candidate))
|
||||
if not measured:
|
||||
return None
|
||||
return {
|
||||
"pairs": len(measured),
|
||||
"baseline_median_tokens_per_second": statistics.median(a for a, _ in measured),
|
||||
"candidate_median_tokens_per_second": statistics.median(b for _, b in measured),
|
||||
"candidate_over_baseline_median_ratio": statistics.median(b / a for a, b in measured),
|
||||
}
|
||||
|
||||
|
||||
def group_summary(pairs):
|
||||
return {
|
||||
"pairs": len(pairs),
|
||||
"same_normalized_output": sum(pair["same_normalized_output"] for pair in pairs),
|
||||
"both_quality_passed": sum(pair["baseline_quality_passed"] and
|
||||
pair["candidate_quality_passed"] for pair in pairs),
|
||||
"candidate_over_baseline_wall_median_ratio": statistics.median(
|
||||
pair["candidate_over_baseline_wall_ratio"] for pair in pairs),
|
||||
"prefill": throughput(pairs, "prompt_per_second"),
|
||||
"decode": throughput(pairs, "predicted_per_second"),
|
||||
}
|
||||
grouped_cases.setdefault(pair["case_id"], []).append(pair)
|
||||
grouped_categories.setdefault(pair["category"], []).append(pair)
|
||||
categories = {category: group_summary(members) for category, members in sorted(grouped_categories.items())}
|
||||
summary = group_summary(pairs)
|
||||
summary.update({
|
||||
"baseline_quality_passed": sum(p["baseline_quality_passed"] for p in pairs),
|
||||
"candidate_quality_passed": sum(p["candidate_quality_passed"] for p in pairs),
|
||||
"categories": categories,
|
||||
"cases": {case: group_summary(members) for case, members in sorted(grouped_cases.items())},
|
||||
"failed_quality_categories": [name for name, result in categories.items()
|
||||
if not result["quality"]["observed_checks_passed"]],
|
||||
})
|
||||
warmups = initial_requests(base, candidate)
|
||||
summary["initial_request_quality_failed"] = sum(
|
||||
not (row["baseline_quality_passed"] and row["candidate_quality_passed"]) for row in warmups.values())
|
||||
return {"summary": summary, "pairs": pairs, "initial_requests": warmups,
|
||||
"provenance": {"baseline": provenance(base), "candidate": provenance(candidate)},
|
||||
"qualification": {"performance_qualified": False, "model_quality_qualified": False,
|
||||
"reason": "descriptive offline comparison; separate charter gates required"}}
|
||||
|
||||
|
||||
def main():
|
||||
@@ -111,78 +457,46 @@ def main():
|
||||
parser.add_argument("candidate", type=Path)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
repository = Path(__file__).resolve().parent.parent
|
||||
output = args.output.resolve()
|
||||
if output == repository or repository in output.parents:
|
||||
parser.error("output must be outside the repository")
|
||||
base, candidate = (json.loads(path.read_text()) for path in
|
||||
(args.baseline, args.candidate))
|
||||
for field in ("schema", "suite_sha256", "model", "configuration"):
|
||||
if base[field] != candidate[field]:
|
||||
raise ValueError(f"reports differ in {field}")
|
||||
b_rows, c_rows = selected(base), selected(candidate)
|
||||
if not b_rows or b_rows.keys() != c_rows.keys():
|
||||
raise ValueError("reports do not contain the same measured cases")
|
||||
pairs = []
|
||||
for key in sorted(b_rows):
|
||||
b, c = b_rows[key], c_rows[key]
|
||||
if b["category"] != c["category"]:
|
||||
raise ValueError("case category differs")
|
||||
pairs.append({
|
||||
"case_id": key[0], "repeat": key[1], "category": b["category"],
|
||||
"baseline_wall_seconds": b["wall_seconds"],
|
||||
"candidate_wall_seconds": c["wall_seconds"],
|
||||
"candidate_over_baseline_wall_ratio": c["wall_seconds"] / b["wall_seconds"],
|
||||
"baseline_quality_passed": b["quality"]["passed"],
|
||||
"candidate_quality_passed": c["quality"]["passed"],
|
||||
"same_normalized_output": (b["http_status"] == c["http_status"] == 200
|
||||
and normalized(b) is not None
|
||||
and normalized(b) == normalized(c)),
|
||||
"baseline_usage": b["response"].get("usage") if isinstance(b["response"], dict) else None,
|
||||
"candidate_usage": c["response"].get("usage") if isinstance(c["response"], dict) else None,
|
||||
"baseline_timings": (b["response"].get("timings") or {})
|
||||
if isinstance(b["response"], dict) else {},
|
||||
"candidate_timings": (c["response"].get("timings") or {})
|
||||
if isinstance(c["response"], dict) else {},
|
||||
})
|
||||
categories = {}
|
||||
for category in sorted({pair["category"] for pair in pairs}):
|
||||
members = [pair for pair in pairs if pair["category"] == category]
|
||||
categories[category] = group_summary(members)
|
||||
cases = {case: group_summary([pair for pair in pairs if pair["case_id"] == case])
|
||||
for case in sorted({pair["case_id"] for pair in pairs})}
|
||||
report = {
|
||||
"schema": 1, "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
"baseline_report": str(args.baseline.resolve()),
|
||||
"candidate_report": str(args.candidate.resolve()),
|
||||
"baseline_metadata": base.get("metadata", {}),
|
||||
"candidate_metadata": candidate.get("metadata", {}),
|
||||
"comparison_limit": "Sequential model loads on one GPU; wall times include API and may drift with I/O and cache state.",
|
||||
"summary": {
|
||||
"pairs": len(pairs),
|
||||
"baseline_quality_passed": sum(p["baseline_quality_passed"] for p in pairs),
|
||||
"candidate_quality_passed": sum(p["candidate_quality_passed"] for p in pairs),
|
||||
"same_normalized_output": sum(p["same_normalized_output"] for p in pairs),
|
||||
"candidate_over_baseline_wall_median_ratio": statistics.median(
|
||||
p["candidate_over_baseline_wall_ratio"] for p in pairs),
|
||||
"prefill": throughput(pairs, "prompt_per_second"),
|
||||
"decode": throughput(pairs, "predicted_per_second"),
|
||||
"categories": categories,
|
||||
"cases": cases,
|
||||
},
|
||||
"initial_requests": initial_requests(base, candidate),
|
||||
"pairs": pairs,
|
||||
}
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
old_mask = os.umask(0o077)
|
||||
try:
|
||||
with output.open("x", encoding="utf-8") as file:
|
||||
json.dump(report, file, indent=2, ensure_ascii=False)
|
||||
file.write("\n")
|
||||
finally:
|
||||
os.umask(old_mask)
|
||||
print(json.dumps(report["summary"], indent=2))
|
||||
repository = Path(__file__).resolve().parent.parent
|
||||
if args.output.is_symlink():
|
||||
reject("output must not be a symbolic link")
|
||||
output = args.output.resolve()
|
||||
if output == repository or repository in output.parents or any((parent / ".git").exists() for parent in output.parents):
|
||||
reject("output must be outside Git repositories")
|
||||
base, candidate = load_report(args.baseline), load_report(args.candidate)
|
||||
report = {"schema": 1, "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
"baseline_report": str(args.baseline.resolve()), "candidate_report": str(args.candidate.resolve()),
|
||||
"baseline_metadata": base.get("metadata", {}), "candidate_metadata": candidate.get("metadata", {}),
|
||||
"comparison_limit": LIMITATION, **compare(base, candidate)}
|
||||
payload = (json.dumps(report, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
|
||||
old_mask = os.umask(0o077)
|
||||
try:
|
||||
output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
finally:
|
||||
os.umask(old_mask)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as destination:
|
||||
destination.write(payload)
|
||||
except BaseException:
|
||||
output.unlink(missing_ok=True)
|
||||
raise
|
||||
summary = report["summary"]
|
||||
print(json.dumps({"pairs": summary["pairs"],
|
||||
"baseline_quality_passed": summary["baseline_quality_passed"],
|
||||
"candidate_quality_passed": summary["candidate_quality_passed"],
|
||||
"same_normalized_output": summary["same_normalized_output"],
|
||||
"failed_quality_category_count": len(summary["failed_quality_categories"]),
|
||||
"performance_qualified": False, "model_quality_qualified": False}))
|
||||
except (ValueError, TypeError, OverflowError, RecursionError):
|
||||
print("paired report rejected: invalid or incompatible report data", file=sys.stderr)
|
||||
return 1
|
||||
except OSError:
|
||||
print("paired report rejected: private input/output unavailable or output already exists", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
raise SystemExit(main())
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render a private descriptive paired JSON report as private Markdown."""
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
MAX_BYTES = 16 * 1024 * 1024
|
||||
MAX_GROUPS = 1000
|
||||
|
||||
|
||||
def count(value, ceiling=None):
|
||||
if type(value) is not int or value < 0 or (ceiling is not None and value > ceiling):
|
||||
raise ValueError("invalid count")
|
||||
return value
|
||||
|
||||
|
||||
def number(value):
|
||||
if type(value) not in (int, float) or not math.isfinite(value) or value <= 0:
|
||||
raise ValueError("invalid measurement")
|
||||
return f"{value:.6g}"
|
||||
|
||||
|
||||
def label(value):
|
||||
if not isinstance(value, str) or not value or len(value) > 256:
|
||||
raise ValueError("invalid group label")
|
||||
return html.escape(value).replace("|", "|").replace("`", "`").replace("\n", " ").replace("\r", " ").replace("[", "[").replace("]", "]")
|
||||
|
||||
|
||||
def distribution_row(name, distribution, expected):
|
||||
n = count(distribution["sample_count"], expected)
|
||||
if n != expected or not n:
|
||||
raise ValueError("distribution count does not match")
|
||||
values = [number(distribution[key]) for key in ("mean", "median", "p10", "p90")]
|
||||
if not distribution["p10"] <= distribution["median"] <= distribution["p90"]:
|
||||
raise ValueError("invalid percentiles")
|
||||
small = distribution["small_sample"]
|
||||
if type(small) is not bool or small != (n < 30):
|
||||
raise ValueError("invalid sample warning")
|
||||
interval = distribution.get("median_confidence_interval")
|
||||
bounds = "not reported"
|
||||
if interval is not None:
|
||||
available = interval["finite_interval_available"]
|
||||
if type(available) is not bool:
|
||||
raise ValueError("invalid interval availability")
|
||||
level = interval["confidence_level"]
|
||||
number(level)
|
||||
if level > 1:
|
||||
raise ValueError("invalid confidence level")
|
||||
if available:
|
||||
lower, upper = interval["lower"], interval["upper"]
|
||||
low_text, high_text = number(lower), number(upper)
|
||||
if not lower <= distribution["median"] <= upper:
|
||||
raise ValueError("invalid confidence interval")
|
||||
bounds = f"{level * 100:.6g}%: [{low_text}, {high_text}]"
|
||||
else:
|
||||
if interval["lower"] is not None or interval["upper"] is not None:
|
||||
raise ValueError("unavailable interval has bounds")
|
||||
bounds = "insufficient pairs for finite interval"
|
||||
warning = "small sample (<30 pairs)" if small else "30+ pairs; still descriptive"
|
||||
return f"| {name} | {n} | {' | '.join(values)} | {bounds} | {warning} |"
|
||||
|
||||
|
||||
def render(report):
|
||||
if not isinstance(report, dict) or type(report.get("schema")) is not int or report["schema"] != 1:
|
||||
raise ValueError("unsupported report")
|
||||
summary = report["summary"]
|
||||
pairs = count(summary["pairs"])
|
||||
if not pairs:
|
||||
raise ValueError("empty report")
|
||||
baseline = count(summary["baseline_quality_passed"], pairs)
|
||||
candidate = count(summary["candidate_quality_passed"], pairs)
|
||||
same = count(summary["same_normalized_output"], pairs)
|
||||
ratio = number(summary["candidate_over_baseline_wall_median_ratio"])
|
||||
lines = ["# Descriptive paired comparison", "",
|
||||
"Sequential loads and synthetic fixtures may confound this comparison. "
|
||||
"These numbers do not qualify GPU inference, model quality, or a performance improvement.", "",
|
||||
"## Aggregate", "", "| Metric | Value |", "| --- | ---: |",
|
||||
f"| Measured pairs | {pairs} |",
|
||||
f"| Baseline quality checks passed | {baseline}/{pairs} |",
|
||||
f"| Candidate quality checks passed | {candidate}/{pairs} |",
|
||||
f"| Same normalized output | {same}/{pairs} |",
|
||||
f"| Candidate/baseline median wall ratio (lower is faster) | {ratio} |"]
|
||||
if "initial_request_quality_failed" in summary:
|
||||
initial_failed = count(summary["initial_request_quality_failed"], pairs)
|
||||
lines.append(f"| Initial requests failing quality checks | {initial_failed} |")
|
||||
lines += ["",
|
||||
"## Categories", "", "Any failing category remains a failed gate; aggregate results cannot hide it.", "",
|
||||
"| Category | Pairs | Both quality checks passed | Same output | Wall ratio | Observed checks |",
|
||||
"| --- | ---: | ---: | ---: | ---: | --- |"]
|
||||
groups = summary["categories"]
|
||||
if not isinstance(groups, dict) or not groups or len(groups) > MAX_GROUPS:
|
||||
raise ValueError("invalid categories")
|
||||
total = total_same = total_both_quality = 0
|
||||
for name, group in sorted(groups.items()):
|
||||
n = count(group["pairs"], pairs)
|
||||
if not n:
|
||||
raise ValueError("empty category")
|
||||
total += n
|
||||
quality = count(group["both_quality_passed"], n)
|
||||
same_group = count(group["same_normalized_output"], n)
|
||||
total_same += same_group
|
||||
total_both_quality += quality
|
||||
wall = number(group["candidate_over_baseline_wall_median_ratio"])
|
||||
verdict = "PASS (observed only)" if quality == same_group == n else "FAIL"
|
||||
lines.append(f"| {label(name)} | {n} | {quality}/{n} | {same_group}/{n} | {wall} | {verdict} |")
|
||||
if total != pairs or total_same != same or total_both_quality > min(baseline, candidate):
|
||||
raise ValueError("category counts do not match")
|
||||
lines += ["", "## Throughput", "",
|
||||
"Optional timings cover only pairs with measurements in both arms.", "",
|
||||
"| Timing | Pairs | Baseline median tok/s | Candidate median tok/s | Candidate/baseline ratio |",
|
||||
"| --- | ---: | ---: | ---: | ---: |"]
|
||||
for name in ("prefill", "decode"):
|
||||
timing = summary.get(name)
|
||||
if timing is None:
|
||||
lines.append(f"| {name} | 0 | unavailable | unavailable | unavailable |")
|
||||
continue
|
||||
n = count(timing["pairs"], pairs)
|
||||
if not n:
|
||||
raise ValueError("empty timing")
|
||||
b = number(timing["baseline_median_tokens_per_second"])
|
||||
c = number(timing["candidate_median_tokens_per_second"])
|
||||
r = number(timing["candidate_over_baseline_median_ratio"])
|
||||
lines.append(f"| {name} | {n} | {b} | {c} | {r} |")
|
||||
distributions = []
|
||||
for name, group in [("Aggregate", summary), *[(label(k), v) for k, v in sorted(groups.items())]]:
|
||||
for arm in ("baseline", "candidate"):
|
||||
value = group.get("wall_seconds", {}).get(arm)
|
||||
if value is not None:
|
||||
distributions.append(distribution_row(f"{name}: {arm} wall seconds", value, group["pairs"]))
|
||||
value = group.get("candidate_over_baseline_wall_ratio_distribution")
|
||||
if value is not None:
|
||||
distributions.append(distribution_row(f"{name}: wall ratio", value, group["pairs"]))
|
||||
for name in ("prefill", "decode"):
|
||||
timing = summary.get(name)
|
||||
if timing is not None:
|
||||
for key in ("baseline_distribution", "candidate_distribution", "candidate_over_baseline_ratio_distribution"):
|
||||
if key in timing:
|
||||
distributions.append(distribution_row(f"{name}: {key.replace('_', ' ')}", timing[key], timing["pairs"]))
|
||||
if distributions:
|
||||
lines += ["", "## Distributions and uncertainty", "",
|
||||
"Intervals describe paired medians under independent-pair assumptions. "
|
||||
"Repeated cases, sequential loads and cache drift limit their interpretation.", "",
|
||||
"| Measurement | Pairs | Mean | Median | P10 | P90 | Median interval | Sample limit |",
|
||||
"| --- | ---: | ---: | ---: | ---: | ---: | --- | --- |", *distributions]
|
||||
lines += ["", "Raw responses, tool arguments, and private metadata values are omitted.", ""]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("report", type=Path)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
output = args.output.resolve()
|
||||
if any((parent / ".git").exists() for parent in (output, *output.parents)):
|
||||
raise ValueError("output must be outside Git")
|
||||
with args.report.open("rb") as source:
|
||||
data = source.read(MAX_BYTES + 1)
|
||||
if len(data) > MAX_BYTES:
|
||||
raise ValueError("report too large")
|
||||
document = render(json.loads(data))
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as target:
|
||||
target.write(document)
|
||||
except BaseException:
|
||||
output.unlink()
|
||||
raise
|
||||
except (ValueError, KeyError, TypeError, OSError, RecursionError):
|
||||
parser.exit(1, "paired Markdown report refused: invalid input or unavailable private output\n")
|
||||
print("Private descriptive Markdown report written.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -9,12 +9,43 @@ import subprocess
|
||||
from docker_smoke_http import ISOLATION, docker, prepare_probe, request
|
||||
|
||||
|
||||
def report_best_effort(message):
|
||||
try:
|
||||
print(message, file=sys.stderr, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def diagnose_owned_container(name):
|
||||
"""Emit bounded state/log diagnostics for this invocation's unique container."""
|
||||
commands = (
|
||||
('inspect', ('inspect', '--format', '{{json .State}}', name)),
|
||||
('logs', ('logs', '--tail', '40', name)),
|
||||
)
|
||||
for label, args in commands:
|
||||
try:
|
||||
result = docker(*args, check=False, timeout=8)
|
||||
output = (result.stdout or '') + (result.stderr or '')
|
||||
if len(output) > 8192:
|
||||
output = '[earlier output truncated]\n' + output[-8192:]
|
||||
if output:
|
||||
report_best_effort(
|
||||
f'Owned container {label} (exit {result.returncode}):\n{output}')
|
||||
else:
|
||||
report_best_effort(
|
||||
f'Owned container {label}: no output (exit {result.returncode})')
|
||||
except Exception as error:
|
||||
report_best_effort(
|
||||
f'Owned container {label} diagnostics unavailable: {type(error).__name__}')
|
||||
|
||||
|
||||
def main(image):
|
||||
name = 'strata-cli-smoke-' + uuid.uuid4().hex
|
||||
common = ['--name', name, *ISOLATION]
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
prepare_probe()
|
||||
|
||||
primary_error = None
|
||||
try:
|
||||
version = docker('run', '--rm', *common, '--network', 'none', image, '--version').stdout
|
||||
assert version.startswith('strata-next '), version
|
||||
@@ -24,8 +55,16 @@ def main(image):
|
||||
info = json.loads(docker('run', '--rm', *common, '--network', 'none', image,
|
||||
'engine-info').stdout)
|
||||
assert info['embedded'] is False and info['model_bundled'] is False, info
|
||||
docker('run', '-d', *common, '--network', 'none',
|
||||
'-e', 'STRATA_BIND=127.0.0.1:8081', image, 'serve')
|
||||
try:
|
||||
docker('run', '-d', *common, '--network', 'none',
|
||||
'-e', 'STRATA_BIND=127.0.0.1:8081', image, 'serve', timeout=120)
|
||||
except subprocess.TimeoutExpired:
|
||||
try:
|
||||
diagnose_owned_container(name)
|
||||
except Exception as error:
|
||||
report_best_effort(
|
||||
f'Owned container diagnostics failed: {type(error).__name__}')
|
||||
raise
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
try:
|
||||
@@ -42,8 +81,25 @@ def main(image):
|
||||
assert state['ExitCode'] == 0 and not state['OOMKilled'], state
|
||||
print('CLI OCI passed: actual image, exact upstream license, no embedded engine/model, '
|
||||
'non-root read-only health200/ready503, graceful stop. No GPU inference qualified.')
|
||||
except BaseException as error:
|
||||
primary_error = error
|
||||
raise
|
||||
finally:
|
||||
docker('rm', '-f', name, check=False)
|
||||
cleanup_error = None
|
||||
try:
|
||||
result = docker('rm', '-f', name, check=False, timeout=10)
|
||||
if result.returncode:
|
||||
cleanup_error = subprocess.CalledProcessError(
|
||||
result.returncode, ['docker', 'rm', '-f', name],
|
||||
output=result.stdout, stderr=result.stderr)
|
||||
except Exception as error:
|
||||
cleanup_error = error
|
||||
if cleanup_error is not None:
|
||||
if primary_error is None:
|
||||
raise cleanup_error
|
||||
report_best_effort(
|
||||
f'Owned container cleanup failed after {type(primary_error).__name__}: '
|
||||
f'{type(cleanup_error).__name__}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -28,7 +28,8 @@ class Handler(http.server.BaseHTTPRequestHandler):
|
||||
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||
if "tools" in body:
|
||||
message = {"role": "assistant", "content": None,
|
||||
"tool_calls": [{"function": {"name": "get_weather",
|
||||
"tool_calls": [{"id": "call_fixture_weather", "type": "function",
|
||||
"function": {"name": "get_weather",
|
||||
"arguments": '{"city":"Paris"}'}}]}
|
||||
finish = "tool_calls"
|
||||
else:
|
||||
@@ -117,6 +118,15 @@ def main():
|
||||
assert sequential["candidate_quality_passed"] == 3
|
||||
assert sequential["decode"]["pairs"] == 3
|
||||
assert sequential["prefill"]["candidate_over_baseline_median_ratio"] == 1.0
|
||||
markdown = private / "sequential-comparison.md"
|
||||
rendered = subprocess.run([
|
||||
"python3", str(root / "scripts/render-paired-report.py"),
|
||||
str(compared), "--output", str(markdown),
|
||||
], check=True, capture_output=True, text=True)
|
||||
assert stat.S_IMODE(markdown.stat().st_mode) == 0o600
|
||||
assert TOKEN not in markdown.read_text() + rendered.stdout + rendered.stderr
|
||||
assert "Distributions and uncertainty" in markdown.read_text()
|
||||
assert "insufficient pairs for finite interval" in markdown.read_text()
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
Executable
+169
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env bash
|
||||
# Usage: scripts/test-cuda-driver-bootstrap.sh [--inside]
|
||||
# Default: isolated Linux CPU Docker mock ELF gate; --inside is container-only.
|
||||
# Synthetic crate-only workspace; no installed CUDA driver or model data accessed.
|
||||
set -euo pipefail
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
image='rust@sha256:114c7a4425406451c2866b6aafe69fe29b1b298832db1277d411ac73c82d04d6'
|
||||
if [[ "${1:-}" == --inside ]]; then
|
||||
[[ $# == 1 && -f /.dockerenv && "$(uname -s)" == Linux ]]
|
||||
[[ "$(id -u)" == 65532 ]]
|
||||
[[ "$(awk '/^Cap(Eff|Prm|Bnd):/{print $2}' /proc/self/status)" == $'0000000000000000\n0000000000000000\n0000000000000000' ]]
|
||||
for device in /dev/nvidia* /dev/dri/*; do
|
||||
[[ ! -e "$device" ]] || { echo 'raw GPU device present; refusing mock gate' >&2; exit 1; }
|
||||
done
|
||||
[[ ! -e "${repo_root}/engine" && ! -e "${repo_root}/control-plane" ]]
|
||||
command -v nvcc >/dev/null && { echo 'unexpected CUDA Toolkit' >&2; exit 1; }
|
||||
if ldconfig -p 2>/dev/null | grep -q 'libcuda\.so'; then
|
||||
echo 'installed CUDA driver present; refusing mock gate' >&2; exit 1
|
||||
fi
|
||||
work="$(mktemp -d /tmp/leleka-cuda-mock.XXXXXX)"
|
||||
trap 'result=$?; rm -rf "$work" || { if [[ "$result" == 0 ]]; then result=1; fi; }; exit "$result"' EXIT
|
||||
mkdir -p "$work/complete" "$work/missing"
|
||||
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC \
|
||||
"${repo_root}/crates/cuda-driver/tests/mock_cuda.c" -o "$work/complete/libcuda.so.1"
|
||||
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC -DMOCK_MISSING_DTOH \
|
||||
"${repo_root}/crates/cuda-driver/tests/mock_cuda.c" -o "$work/missing/libcuda.so.1"
|
||||
for symbol in cuInit cuDriverGetVersion cuDeviceGet cuCtxCreate_v2 cuCtxDestroy_v2 \
|
||||
cuCtxPushCurrent_v2 cuCtxPopCurrent_v2 cuCtxSynchronize cuMemAlloc_v2 cuMemFree_v2 cuMemcpyHtoD_v2 cuModuleLoadData cuModuleGetFunction cuModuleUnload cuLaunchKernel; do
|
||||
mkdir "$work/missing_$symbol"
|
||||
cc -std=c11 -Wall -Wextra -Werror -Wno-misleading-indentation -shared -fPIC \
|
||||
"-D${symbol}=mock_replaced_${symbol}" "${repo_root}/crates/cuda-driver/tests/mock_cuda.c" \
|
||||
-o "$work/missing_$symbol/libcuda.so.1"
|
||||
done
|
||||
readelf -h "$work/complete/libcuda.so.1" | grep 'Class:.*ELF64'
|
||||
sha256sum "$work/complete/libcuda.so.1" "$work/missing/libcuda.so.1"
|
||||
sha256sum "${repo_root}/crates/cuda-driver/Cargo.toml" \
|
||||
"${repo_root}/crates/cuda-driver/src/lib.rs" "${repo_root}/crates/cuda-driver/src/ffi.rs" \
|
||||
"${repo_root}/crates/cuda-driver/src/vector_add.ptx" \
|
||||
"${repo_root}/crates/cuda-driver/tests/mock_cuda.c" "${repo_root}/crates/cuda-driver/tests/mock_driver.rs"
|
||||
rustup component list --installed
|
||||
rustc --version
|
||||
cc --version | head -1
|
||||
export CARGO_TARGET_DIR="$work/target"
|
||||
cd "$repo_root"
|
||||
cargo fmt --manifest-path "${repo_root}/Cargo.toml" --all -- --check
|
||||
cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --lib
|
||||
cargo clippy --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --all-targets --all-features -- -D warnings
|
||||
LELEKA_CUDA_MOCK_HARNESS=1 LELEKA_CUDA_MOCK_ROOT="$work" \
|
||||
cargo test --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver \
|
||||
--features cuda-driver --test mock_driver -- --exact isolated_cpu_elf_matrix --ignored --test-threads=1 --nocapture
|
||||
rlib="$(find "$work/target/debug/deps" -maxdepth 1 -name 'libleleka_cuda_driver-*.rlib' -print -quit)"
|
||||
[[ -n "$rlib" ]]
|
||||
# Independent negative compile gates: lifetimes/auto-traits cannot escape FFI ownership.
|
||||
for typename in Driver 'Device<'"'static"'>' 'Context<'"'static"'>' 'DeviceBuffer<'"'static"'>';
|
||||
do
|
||||
for trait in Send Sync; do
|
||||
printf 'use leleka_cuda_driver::*;fn require<T:%s>(){}fn main(){require::<%s>();}\n' "$trait" "$typename" > "$work/reject.rs"
|
||||
if rustc --edition=2024 --extern "leleka_cuda_driver=$rlib" -L "dependency=$work/target/debug/deps" \
|
||||
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then
|
||||
echo "unsafe trait escape: $typename $trait" >&2; exit 1
|
||||
fi
|
||||
grep -Eq 'cannot be (sent|shared).*safely' "$work/reject.log"
|
||||
echo "compile refusal $typename $trait: PASS"
|
||||
done
|
||||
done
|
||||
cat > "$work/reject.rs" <<'RS'
|
||||
use leleka_cuda_driver::Driver;
|
||||
fn main(){let driver=Driver::load().unwrap();let device=driver.device(0).unwrap();let context=device.create_context(16).unwrap();drop(driver);context.synchronize().unwrap();}
|
||||
RS
|
||||
if rustc --edition=2024 --extern "leleka_cuda_driver=$rlib" -L "dependency=$work/target/debug/deps" \
|
||||
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo 'driver lifetime escaped' >&2; exit 1; fi
|
||||
grep -q 'cannot move out of.*driver.*because it is borrowed' "$work/reject.log"
|
||||
cat > "$work/reject.rs" <<'RS'
|
||||
use leleka_cuda_driver::Driver;
|
||||
fn main(){let driver=Driver::load().unwrap();let device=driver.device(0).unwrap();let context=device.create_context(16).unwrap();let buffer=context.allocate(8).unwrap();context.close().unwrap();buffer.copy_to(&mut [0;8]).unwrap();}
|
||||
RS
|
||||
if rustc --edition=2024 --extern "leleka_cuda_driver=$rlib" -L "dependency=$work/target/debug/deps" \
|
||||
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo 'context lifetime escaped' >&2; exit 1; fi
|
||||
grep -q 'cannot move out of.*context.*because it is borrowed' "$work/reject.log"
|
||||
echo 'two lifetime compile refusals: PASS'
|
||||
cat > "$work/reject.rs" <<'RS'
|
||||
use leleka_cuda_driver::Driver;
|
||||
fn main(){let driver=Driver::load().unwrap();let context=driver.device(0).unwrap().create_context(16).unwrap();let mut buffer=context.allocate(4).unwrap();context.vector_add_f32(&buffer,&buffer,&mut buffer).unwrap();}
|
||||
RS
|
||||
if rustc --edition=2024 --extern "leleka_cuda_driver=$rlib" -L "dependency=$work/target/debug/deps" \
|
||||
"$work/reject.rs" -o "$work/reject" 2>"$work/reject.log"; then echo 'output alias escaped' >&2; exit 1; fi
|
||||
grep -q 'cannot borrow.*buffer.*as mutable because it is also borrowed as immutable' "$work/reject.log"
|
||||
echo 'vector output alias compile refusal: PASS'
|
||||
cargo tree --offline --locked --manifest-path "${repo_root}/Cargo.toml" -p leleka-cuda-driver --edges normal
|
||||
exit 0
|
||||
fi
|
||||
[[ $# == 0 ]] || { echo 'Usage: scripts/test-cuda-driver-bootstrap.sh [--inside]' >&2; exit 2; }
|
||||
staging="$(mktemp -d "${TMPDIR:-/tmp}/leleka-cuda-bootstrap.XXXXXX")"
|
||||
container=''
|
||||
setup_container=''
|
||||
fixture_image=''
|
||||
cleanup() {
|
||||
local result=$? failed=0
|
||||
set +e
|
||||
if [[ -n "$container" ]]; then docker rm -f "$container" >/dev/null || failed=1; fi
|
||||
if [[ -n "$setup_container" ]]; then docker rm -f "$setup_container" >/dev/null || failed=1; fi
|
||||
if [[ -n "$fixture_image" ]]; then docker image rm "$fixture_image" >/dev/null || failed=1; fi
|
||||
rm -rf "$staging" || failed=1
|
||||
if [[ "$result" == 0 && "$failed" == 1 ]]; then result=1; fi
|
||||
exit "$result"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
mkdir -p "$staging/src/crates" "$staging/src/scripts"
|
||||
cp -R "${repo_root}/crates/cuda-driver" "$staging/src/crates/"
|
||||
cp "${BASH_SOURCE[0]}" "$staging/src/scripts/test-cuda-driver-bootstrap.sh"
|
||||
{ printf '[workspace]\nresolver = "3"\nmembers = ["crates/cuda-driver"]\n\n';
|
||||
sed -n '/^\[workspace.package\]/,$p' "${repo_root}/Cargo.toml"; } > "$staging/src/Cargo.toml"
|
||||
# Only the already-approved pinned libc registry archive is admitted as a dependency.
|
||||
libc_archive=''
|
||||
for candidate in "${CARGO_HOME:-${HOME}/.cargo}"/registry/cache/*/libc-0.2.190.crate; do
|
||||
if [[ -f "$candidate" ]]; then libc_archive="$candidate"; break; fi
|
||||
done
|
||||
[[ -n "$libc_archive" ]]
|
||||
python3 - "$libc_archive" "$staging/src" "${repo_root}/Cargo.lock" <<'PYVENDOR'
|
||||
import hashlib,json,pathlib,sys,tarfile
|
||||
archive,root,lock=map(pathlib.Path,sys.argv[1:])
|
||||
expected='ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78'
|
||||
assert hashlib.sha256(archive.read_bytes()).hexdigest()==expected
|
||||
rows=lock.read_text().split('[[package]]')
|
||||
packages=[row for row in rows[1:] if '\nname = "leleka-cuda-driver"\n' in row or '\nname = "libc"\n' in row]
|
||||
assert len(packages)==2
|
||||
assert 'checksum = "'+expected+'"' in ''.join(packages)
|
||||
(root/'Cargo.lock').write_text('version = 4\n'+''.join('[[package]]'+row for row in packages))
|
||||
vendor=root/'vendor'/'libc-0.2.190'
|
||||
checksums={}
|
||||
with tarfile.open(archive) as source:
|
||||
for member in source:
|
||||
path=pathlib.PurePosixPath(member.name)
|
||||
assert path.parts[0]=='libc-0.2.190' and '..' not in path.parts and not path.is_absolute()
|
||||
if member.isdir():continue
|
||||
assert member.isfile()
|
||||
relative=pathlib.Path(*path.parts[1:]);destination=vendor/relative
|
||||
destination.parent.mkdir(parents=True,exist_ok=True)
|
||||
data=source.extractfile(member).read();destination.write_bytes(data)
|
||||
checksums[relative.as_posix()]=hashlib.sha256(data).hexdigest()
|
||||
(vendor/'.cargo-checksum.json').write_text(json.dumps({'files':checksums,'package':expected}))
|
||||
(root/'.cargo').mkdir()
|
||||
(root/'.cargo'/'config.toml').write_text('[source.crates-io]\nreplace-with = "vendored-sources"\n[source.vendored-sources]\ndirectory = "vendor"\n')
|
||||
print('Approved libc registry archive SHA256 '+expected+'; exact files vendor-verified by Cargo')
|
||||
PYVENDOR
|
||||
chmod -R a+rX "$staging/src"
|
||||
docker pull "$image" >/dev/null
|
||||
docker image inspect "$image" --format 'Pinned CPU base {{.Id}} architecture={{.Architecture}}'
|
||||
# Rust official image lacks optional lint/format components. Provision only these
|
||||
# verified pinned-toolchain components in a disposable setup container; runtime
|
||||
# tests run later with network disabled and zero capabilities/non-root.
|
||||
setup_container="$(docker create --runtime runc --cap-drop ALL --security-opt no-new-privileges \
|
||||
--network bridge --memory 1536m --cpus 2 --pids-limit 128 "$image" \
|
||||
bash -c 'for d in /dev/nvidia* /dev/dri/*; do [[ ! -e "$d" ]] || exit 1; done; rustup component add rustfmt clippy')"
|
||||
docker start -a "$setup_container"
|
||||
[[ "$(docker inspect "$setup_container" --format '{{.State.ExitCode}}')" == 0 ]]
|
||||
fixture_image="$(docker commit "$setup_container")"
|
||||
docker rm "$setup_container" >/dev/null
|
||||
setup_container=''
|
||||
docker image inspect "$fixture_image" --format 'Actual CPU fixture image {{.Id}} architecture={{.Architecture}}'
|
||||
container="$(docker create --runtime runc --user 65532:65532 --cap-drop ALL \
|
||||
--security-opt no-new-privileges --network none --memory 1536m --cpus 2 --pids-limit 128 \
|
||||
--tmpfs /tmp:rw,nosuid,exec,size=768m "$fixture_image" sleep 900)"
|
||||
configuration="$(docker inspect "$container" --format '{{.HostConfig.NetworkMode}}|{{.HostConfig.Runtime}}|{{.HostConfig.Privileged}}|{{.Config.User}}|{{len .HostConfig.Devices}}|{{len .HostConfig.DeviceRequests}}|{{len .HostConfig.Binds}}|{{.HostConfig.CapDrop}}|{{.HostConfig.SecurityOpt}}')"
|
||||
[[ "$configuration" == 'none|runc|false|65532:65532|0|0|0|[ALL]|[no-new-privileges]' ]]
|
||||
echo "CPU mock container: $configuration"
|
||||
docker cp "$staging/src/." "$container:/src"
|
||||
docker start "$container" >/dev/null
|
||||
docker exec "$container" bash /src/scripts/test-cuda-driver-bootstrap.sh --inside
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env bash
|
||||
# Offline assembly acceptance only; no installed driver, GPU, or PTX execution.
|
||||
set -euo pipefail
|
||||
[[ $# == 0 ]] || { echo 'Usage: scripts/test-cuda-fixed-ptx.sh' >&2; exit 2; }
|
||||
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
image='ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b'
|
||||
work="$(mktemp -d "${TMPDIR:-/tmp}/leleka-fixed-ptx.XXXXXX")"
|
||||
container=''
|
||||
cleanup() {
|
||||
local result=$? failed=0
|
||||
set +e
|
||||
if [[ -n "$container" ]]; then docker rm -f "$container" >/dev/null || failed=1; fi
|
||||
rm -rf "$work" || failed=1
|
||||
if [[ "$failed" == 1 ]]; then echo 'PTX owned cleanup failed' >&2; result=1; else echo 'PTX owned container/files removed; shared base retained'; fi
|
||||
exit "$result"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
python3 - "$repo_root" "$work" <<'PY'
|
||||
import hashlib, json, pathlib, sys, tarfile, urllib.request
|
||||
root, work = map(pathlib.Path, sys.argv[1:])
|
||||
lock = json.loads((root/'deploy/cuda-toolkit.lock.json').read_text())
|
||||
component = next(row for row in lock['components'] if row['component'] == 'cuda_nvcc')
|
||||
expected = '48e35be3cfbf4b4fbc16828eaec8a7048ee789403049dc409f7b643d6259cf7a'
|
||||
assert component['version']=='13.0.88' and component['sha256']==expected
|
||||
assert component['relative_path']=='cuda_nvcc/linux-x86_64/cuda_nvcc-linux-x86_64-13.0.88-archive.tar.xz'
|
||||
assert int(component['size'])==26657716
|
||||
url='https://developer.download.nvidia.com/compute/cuda/redist/'+component['relative_path']
|
||||
with urllib.request.urlopen(url, timeout=60) as response:
|
||||
data=response.read(26657717)
|
||||
assert len(data)==26657716 and hashlib.sha256(data).hexdigest()==expected
|
||||
archive=work/'nvcc.tar.xz'; archive.write_bytes(data)
|
||||
with tarfile.open(archive, 'r:xz') as source:
|
||||
member=source.getmember('cuda_nvcc-linux-x86_64-13.0.88-archive/bin/ptxas')
|
||||
assert member.isfile() and member.size < 100_000_000
|
||||
binary=source.extractfile(member).read()
|
||||
assert binary[:4]==b'\x7fELF'
|
||||
(work/'ptxas').write_bytes(binary); (work/'ptxas').chmod(0o755)
|
||||
ptx=(root/'crates/cuda-driver/src/vector_add.ptx').read_bytes()
|
||||
assert 0<len(ptx)<=16384 and b'\0' not in ptx
|
||||
(work/'vector_add.ptx').write_bytes(ptx)
|
||||
print('Official archive URL:',url)
|
||||
print('Official archive bytes/SHA256:',len(data),expected)
|
||||
print('Extracted ptxas SHA256:',hashlib.sha256(binary).hexdigest())
|
||||
print('PTX file SHA256:',hashlib.sha256(ptx).hexdigest())
|
||||
print('Embedded PTX including final NUL SHA256:',hashlib.sha256(ptx+b'\0').hexdigest())
|
||||
PY
|
||||
docker pull --platform linux/amd64 "$image" >/dev/null
|
||||
docker image inspect "$image" --format 'Pinned assembly CPU base {{.Id}} architecture={{.Architecture}}'
|
||||
container="$(docker create --platform linux/amd64 --runtime runc --user 65532:65532 \
|
||||
--cap-drop ALL --security-opt no-new-privileges --network none --read-only \
|
||||
--memory 768m --cpus 2 --pids-limit 64 --tmpfs /tmp:rw,nosuid,exec,size=128m \
|
||||
"$image" sleep 900)"
|
||||
configuration="$(docker inspect "$container" --format '{{.HostConfig.NetworkMode}}|{{.HostConfig.Runtime}}|{{.HostConfig.Privileged}}|{{.Config.User}}|{{len .HostConfig.Devices}}|{{len .HostConfig.DeviceRequests}}|{{len .HostConfig.Binds}}|{{.HostConfig.CapDrop}}|{{.HostConfig.SecurityOpt}}')"
|
||||
[[ "$configuration" == 'none|runc|false|65532:65532|0|0|0|[ALL]|[no-new-privileges]' ]]
|
||||
echo "PTX assembly container $container: $configuration"
|
||||
docker start "$container" >/dev/null
|
||||
# Docker cp writes the container rootfs rather than this running tmpfs on some
|
||||
# daemon versions. Stream only the two verified files into the owned tmpfs.
|
||||
docker exec -i "$container" sh -c 'cat > /tmp/ptxas && chmod 0755 /tmp/ptxas' < "$work/ptxas"
|
||||
docker exec -i "$container" sh -c 'cat > /tmp/vector_add.ptx' < "$work/vector_add.ptx"
|
||||
docker exec "$container" bash -euc '
|
||||
for device in /dev/nvidia* /dev/dri/*; do [[ ! -e "$device" ]] || exit 1; done
|
||||
[[ "$(awk '\''/^Cap(Eff|Prm|Bnd):/{print $2}'\'' /proc/self/status)" == $'\''0000000000000000\n0000000000000000\n0000000000000000'\'' ]]
|
||||
if ldconfig -p 2>/dev/null | grep -q "libcuda\.so"; then exit 1; fi
|
||||
uname -sm
|
||||
/tmp/ptxas --version
|
||||
echo "argv: /tmp/ptxas -arch=sm_120 /tmp/vector_add.ptx -o /tmp/vector_add.cubin"
|
||||
/tmp/ptxas -arch=sm_120 /tmp/vector_add.ptx -o /tmp/vector_add.cubin
|
||||
sha256sum /tmp/ptxas /tmp/vector_add.ptx /tmp/vector_add.cubin
|
||||
test -s /tmp/vector_add.cubin
|
||||
echo "Pinned PTX assembler acceptance: PASS (no GPU execution)"
|
||||
'
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Owned synthetic CLI tests for private paired Markdown publication."""
|
||||
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SCRIPT = Path(__file__).with_name("render-paired-report.py")
|
||||
|
||||
|
||||
class MarkdownTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory(prefix="leleka-paired-md-")
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.source = self.root / "input.json"
|
||||
self.output = self.root / "report.md"
|
||||
self.report = {"schema": 1, "metadata": {"private": "PRIVATE_VALUE"},
|
||||
"pairs": [{"response": "PRIVATE_RESPONSE"}], "summary": {
|
||||
"pairs": 2, "baseline_quality_passed": 2, "candidate_quality_passed": 1,
|
||||
"same_normalized_output": 1, "candidate_over_baseline_wall_median_ratio": 0.8,
|
||||
"categories": {"tool|<script>[link](url)": {
|
||||
"pairs": 2, "both_quality_passed": 1, "same_normalized_output": 1,
|
||||
"candidate_over_baseline_wall_median_ratio": 0.8}},
|
||||
"prefill": None, "decode": {"pairs": 2,
|
||||
"baseline_median_tokens_per_second": 100,
|
||||
"candidate_median_tokens_per_second": 125,
|
||||
"candidate_over_baseline_median_ratio": 1.25}}}
|
||||
|
||||
def run_report(self, report=None, output=None):
|
||||
self.source.write_text(json.dumps(self.report if report is None else report))
|
||||
return subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.source),
|
||||
"--output", str(output or self.output)], text=True,
|
||||
capture_output=True, timeout=10)
|
||||
|
||||
def test_summary_quality_limits_and_privacy(self):
|
||||
result = self.run_report()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
document = self.output.read_text()
|
||||
self.assertIn("1/2", document)
|
||||
self.assertIn("0.8", document)
|
||||
self.assertIn("1.25", document)
|
||||
self.assertIn("do not qualify GPU inference", document)
|
||||
self.assertIn("|", document)
|
||||
self.assertNotIn("<script>", document)
|
||||
for secret in ("PRIVATE_VALUE", "PRIVATE_RESPONSE"):
|
||||
self.assertNotIn(secret, document + result.stdout + result.stderr)
|
||||
self.assertNotIn("tool|", result.stdout + result.stderr)
|
||||
self.assertEqual(self.output.stat().st_mode & 0o777, 0o600)
|
||||
|
||||
def test_no_overwrite(self):
|
||||
self.output.write_text("keep")
|
||||
self.assertNotEqual(self.run_report().returncode, 0)
|
||||
self.assertEqual(self.output.read_text(), "keep")
|
||||
|
||||
def test_invalid_measurements_publish_nothing(self):
|
||||
for value in (0, -1, True, float("nan"), float("inf"), "0.8"):
|
||||
with self.subTest(value=value):
|
||||
report = copy.deepcopy(self.report)
|
||||
report["summary"]["candidate_over_baseline_wall_median_ratio"] = value
|
||||
self.assertNotEqual(self.run_report(report).returncode, 0)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_counts_must_match(self):
|
||||
report = copy.deepcopy(self.report)
|
||||
report["summary"]["categories"][next(iter(report["summary"]["categories"]))]["pairs"] = 1
|
||||
self.assertNotEqual(self.run_report(report).returncode, 0)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_distribution_and_small_sample_interval(self):
|
||||
self.report["summary"]["candidate_over_baseline_wall_ratio_distribution"] = {
|
||||
"sample_count": 2, "mean": 0.8, "median": 0.8, "p10": 0.7, "p90": 0.9,
|
||||
"small_sample": True, "median_confidence_interval": {
|
||||
"confidence_level": 0.95, "finite_interval_available": False,
|
||||
"lower": None, "upper": None}}
|
||||
self.assertEqual(self.run_report().returncode, 0)
|
||||
document = self.output.read_text()
|
||||
self.assertIn("small sample (<30 pairs)", document)
|
||||
self.assertIn("insufficient pairs for finite interval", document)
|
||||
|
||||
def test_interval_not_allowed_to_hide_invalid_bounds(self):
|
||||
self.report["summary"]["candidate_over_baseline_wall_ratio_distribution"] = {
|
||||
"sample_count": 2, "mean": 0.8, "median": 0.8, "p10": 0.7, "p90": 0.9,
|
||||
"small_sample": True, "median_confidence_interval": {
|
||||
"confidence_level": 0.95, "finite_interval_available": True,
|
||||
"lower": 0.9, "upper": 1.0}}
|
||||
self.assertNotEqual(self.run_report().returncode, 0)
|
||||
self.assertFalse(self.output.exists())
|
||||
|
||||
def test_git_output_refused(self):
|
||||
git = self.root / "checkout"
|
||||
git.mkdir()
|
||||
(git / ".git").write_text("gitdir: ignored")
|
||||
output = git / "private.md"
|
||||
self.assertNotEqual(self.run_report(output=output).returncode, 0)
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,301 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Independent, offline synthetic regression checks for private paired reports."""
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
SCRIPT = ROOT / "scripts/compare-chat-reports.py"
|
||||
PRIVATE = "PRIVATE_SYNTHETIC_SENTINEL_7863"
|
||||
|
||||
|
||||
def response():
|
||||
return {"choices": [{"message": {"role": "assistant", "content": "OK"}, "finish_reason": "stop"}],
|
||||
"usage": {"prompt_tokens": 20, "completion_tokens": 2, "total_tokens": 22},
|
||||
"timings": {"prompt_n": 20, "predicted_n": 2, "prompt_per_second": 200.0,
|
||||
"predicted_per_second": 50.0}}
|
||||
|
||||
|
||||
def report(walls=(1., 2., 3., 4., 5., 6.), case="case", category="arithmetic"):
|
||||
rows = []
|
||||
for repeat, wall in [(None, 10000.), *enumerate(walls)]:
|
||||
rows.append({"arm": "baseline", "case_id": case, "category": category,
|
||||
"repeat": repeat, "warmup": repeat is None, "wall_seconds": wall,
|
||||
"http_status": 200, "quality": {"passed": True}, "response": response()})
|
||||
return {"schema": 1, "suite_sha256": "a" * 64, "model": "synthetic-only",
|
||||
"configuration": {"repeats": len(walls), "temperature": 0, "seed": 42},
|
||||
"metadata": {}, "rows": rows}
|
||||
|
||||
|
||||
class PairedReports(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix="paired-report-private-")
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.directory = Path(self.temp.name)
|
||||
self.b, self.c, self.out = (self.directory / name for name in ("baseline.json", "candidate.json", "comparison.json"))
|
||||
|
||||
def invoke(self, baseline, candidate, output=None):
|
||||
self.b.write_text(json.dumps(baseline))
|
||||
self.c.write_text(json.dumps(candidate))
|
||||
result = subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.b), str(self.c),
|
||||
"--output", str(output or self.out)], text=True, capture_output=True, timeout=15)
|
||||
self.assertNotIn(PRIVATE, result.stdout + result.stderr)
|
||||
return result
|
||||
|
||||
def compare(self, baseline, candidate):
|
||||
result = self.invoke(baseline, candidate)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
return json.loads(self.out.read_text())
|
||||
|
||||
def refuse(self, baseline, candidate):
|
||||
self.out.unlink(missing_ok=True)
|
||||
result = self.invoke(baseline, candidate)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(self.out.exists(), "invalid input must not publish a report")
|
||||
self.assertNotIn("Traceback", result.stderr)
|
||||
|
||||
def test_known_outlier_distribution_and_exact_interval(self):
|
||||
result = self.compare(report((1.,) * 6), report((1., 2., 3., 4., 5., 100.)))
|
||||
group = result["summary"]["cases"]["case"]
|
||||
stats = group["candidate_over_baseline_wall_ratio_distribution"]
|
||||
self.assertEqual(stats["sample_count"], 6)
|
||||
self.assertAlmostEqual(stats["mean"], 115 / 6)
|
||||
self.assertEqual(stats["median"], 3.5)
|
||||
self.assertEqual(stats["p10"], 1.5)
|
||||
self.assertEqual(stats["p90"], 52.5)
|
||||
ci = stats["median_confidence_interval"]
|
||||
# For six independent pairs, extrema cover the median except both
|
||||
# all-below/all-above events: 1 - 2*(1/2)^6 = 31/32.
|
||||
self.assertEqual((ci["lower"], ci["upper"]), (1., 100.))
|
||||
self.assertEqual(ci["coverage_lower_bound"], 31 / 32)
|
||||
self.assertTrue(stats["small_sample"])
|
||||
self.assertEqual(result["summary"]["categories"]["arithmetic"], group)
|
||||
self.assertEqual(group["wall_seconds"]["baseline"]["mean"], 1)
|
||||
|
||||
def test_pair_ratios_are_not_ratio_of_arm_medians(self):
|
||||
baseline, candidate = report((1., 2., 100.) * 2), report((2., 100., 101.) * 2)
|
||||
for row in baseline["rows"]:
|
||||
row["response"]["timings"]["predicted_per_second"] = row["wall_seconds"]
|
||||
for row in candidate["rows"]:
|
||||
row["response"]["timings"]["predicted_per_second"] = row["wall_seconds"]
|
||||
summary = self.compare(baseline, candidate)["summary"]
|
||||
self.assertEqual(summary["candidate_over_baseline_wall_median_ratio"], 2)
|
||||
self.assertEqual(summary["decode"]["candidate_over_baseline_median_ratio"], 2)
|
||||
self.assertEqual(summary["decode"]["candidate_median_tokens_per_second"] /
|
||||
summary["decode"]["baseline_median_tokens_per_second"], 50)
|
||||
|
||||
def test_small_n_has_no_fabricated_finite_confidence(self):
|
||||
stats = self.compare(report((2.,)), report((1.,)))["summary"]["candidate_over_baseline_wall_ratio_distribution"]
|
||||
ci = stats["median_confidence_interval"]
|
||||
self.assertEqual(stats["median"], .5)
|
||||
self.assertFalse(ci["finite_interval_available"])
|
||||
self.assertIsNone(ci["lower"])
|
||||
self.assertIsNone(ci["upper"])
|
||||
self.assertTrue(stats["small_sample"])
|
||||
|
||||
def test_independent_binomial_order_statistic_references(self):
|
||||
# Published binomial tail values/reference ranks, independent of the
|
||||
# comparator's recurrence. Values 1..n make each rank unambiguous.
|
||||
for n, bounds, coverage in ((5, (None, None), None),
|
||||
(9, (2, 8), .9609375),
|
||||
(30, (10, 21), .9572260547429323)):
|
||||
with self.subTest(n=n):
|
||||
self.out.unlink(missing_ok=True)
|
||||
data = self.compare(report((1.,) * n), report(tuple(range(1, n + 1))))
|
||||
stats = data["summary"]["candidate_over_baseline_wall_ratio_distribution"]
|
||||
ci = stats["median_confidence_interval"]
|
||||
self.assertEqual((ci["lower"], ci["upper"]), bounds)
|
||||
if coverage is None:
|
||||
self.assertIsNone(ci["coverage_lower_bound"])
|
||||
else:
|
||||
self.assertAlmostEqual(ci["coverage_lower_bound"], coverage)
|
||||
self.assertEqual(stats["small_sample"], n < 30)
|
||||
|
||||
def test_deterministic_and_order_independent(self):
|
||||
baseline, candidate = report(), report((2., 1., 4., 3., 9., 7.))
|
||||
first = self.compare(baseline, candidate)
|
||||
self.out.unlink()
|
||||
baseline["rows"].reverse()
|
||||
candidate["rows"].reverse()
|
||||
second = self.compare(baseline, candidate)
|
||||
self.assertEqual(first["summary"], second["summary"])
|
||||
self.assertEqual(first["pairs"], second["pairs"])
|
||||
|
||||
def test_failed_category_cannot_be_averaged_into_pass(self):
|
||||
baseline, candidate = report(), report()
|
||||
baseline["rows"] += report(case=PRIVATE, category="tool-integrity")["rows"]
|
||||
candidate["rows"] += report(case=PRIVATE, category="tool-integrity")["rows"]
|
||||
candidate["rows"][-1].update(http_status=500, response={"error": PRIVATE}, quality={"passed": False})
|
||||
result = self.compare(baseline, candidate)
|
||||
summary = result["summary"]
|
||||
self.assertTrue(summary["categories"]["arithmetic"]["quality"]["observed_checks_passed"])
|
||||
failed = summary["categories"]["tool-integrity"]["quality"]
|
||||
self.assertEqual(failed["candidate_failed"], 1)
|
||||
self.assertEqual(failed["candidate_http_or_protocol_failed"], 1)
|
||||
self.assertFalse(failed["observed_checks_passed"])
|
||||
self.assertFalse(summary["quality"]["observed_checks_passed"])
|
||||
self.assertEqual(summary["failed_quality_categories"], ["tool-integrity"])
|
||||
self.assertFalse(result["qualification"]["performance_qualified"])
|
||||
self.assertFalse(result["qualification"]["model_quality_qualified"])
|
||||
|
||||
def test_optional_cached_zero_rates_are_disclosed_not_divided(self):
|
||||
baseline, candidate = report(), report()
|
||||
for row in baseline["rows"] + candidate["rows"]:
|
||||
row["response"]["timings"]["prompt_per_second"] = 0
|
||||
row["response"]["timings"]["prompt_n"] = 0
|
||||
row["response"]["timings"]["cache_n"] = 20
|
||||
candidate["rows"][-1]["response"].pop("timings")
|
||||
summary = self.compare(baseline, candidate)["summary"]
|
||||
self.assertIsNone(summary["prefill"])
|
||||
self.assertEqual(summary["timing_coverage"]["prompt_per_second"]["available_pairs"], 0)
|
||||
self.assertEqual(summary["decode"]["pairs"], 5)
|
||||
self.assertEqual(summary["decode"]["unavailable_pairs"], 1)
|
||||
|
||||
def test_invalid_numeric_and_structural_rows_refused(self):
|
||||
mutations = [
|
||||
lambda r: r.update(wall_seconds=0), lambda r: r.update(wall_seconds=-1),
|
||||
lambda r: r.update(wall_seconds=float("nan")), lambda r: r.update(wall_seconds=float("inf")),
|
||||
lambda r: r.update(wall_seconds=True), lambda r: r.update(wall_seconds="2"),
|
||||
lambda r: r.update(http_status=True), lambda r: r.update(http_status=99),
|
||||
lambda r: r.update(http_status=500), lambda r: r.update(quality={"passed": 1}),
|
||||
lambda r: r.update(quality={"passed": "false"}), lambda r: r.update(response=[]),
|
||||
lambda r: r.update(warmup="false"), lambda r: r.update(repeat=True),
|
||||
lambda r: r["response"].update(timings=[]),
|
||||
lambda r: r["response"]["timings"].update(predicted_per_second=float("nan")),
|
||||
lambda r: r["response"]["timings"].update(predicted_per_second=-1),
|
||||
lambda r: r["response"]["timings"].update(predicted_per_second=True),
|
||||
lambda r: r["response"]["timings"].update(prompt_n=2.5),
|
||||
lambda r: r["response"].update(usage="bad"),
|
||||
lambda r: r["response"]["usage"].update(total_tokens=1),
|
||||
lambda r: r["response"]["usage"].update(completion_tokens=True),
|
||||
lambda r: r["response"]["usage"].update(prompt_tokens_details={"cached_tokens": 21}),
|
||||
]
|
||||
for index, mutate in enumerate(mutations):
|
||||
with self.subTest(index=index):
|
||||
candidate = report()
|
||||
mutate(candidate["rows"][1])
|
||||
self.refuse(report(), candidate)
|
||||
|
||||
def test_pairing_warmups_categories_and_bounds_refused(self):
|
||||
mutations = [lambda r: r["rows"].append(copy.deepcopy(r["rows"][1])),
|
||||
lambda r: r["rows"].append(copy.deepcopy(r["rows"][0])),
|
||||
lambda r: r["rows"].pop(), lambda r: r["rows"].pop(0),
|
||||
lambda r: r["rows"][1].update(category="other"),
|
||||
lambda r: r["rows"][1].update(case_id=PRIVATE),
|
||||
lambda r: r["rows"][1].update(arm="candidate"),
|
||||
lambda r: r["configuration"].update(repeats=101),
|
||||
lambda r: r["configuration"].update(repeats=True),
|
||||
lambda r: r["configuration"].update(max_tokens=True),
|
||||
lambda r: r["configuration"].update(stream=True),
|
||||
lambda r: r.update(schema=True), lambda r: r.update(suite_sha256="bad"),
|
||||
lambda r: r.update(metadata=[])]
|
||||
for index, mutate in enumerate(mutations):
|
||||
with self.subTest(index=index):
|
||||
candidate = report()
|
||||
mutate(candidate)
|
||||
self.refuse(report(), candidate)
|
||||
baseline, candidate = report(), report()
|
||||
baseline["metadata"]["gpu"] = "fixture-a"
|
||||
candidate["metadata"]["gpu"] = "fixture-b"
|
||||
self.refuse(baseline, candidate)
|
||||
|
||||
def test_malformed_tools_and_incomplete_terminals_refused(self):
|
||||
call = {"id": "call_fixture", "type": "function", "function": {"name": "synthetic", "arguments": '{"x":1}'}}
|
||||
for invalid in ("missing-id", "empty-id", "whitespace-id", "whitespace-name", "duplicate-id", "overflow", "duplicate-field", "list-arguments", "incomplete"):
|
||||
with self.subTest(invalid=invalid):
|
||||
candidate = report()
|
||||
choice = candidate["rows"][1]["response"]["choices"][0]
|
||||
choice.update(finish_reason="tool_calls", message={"role": "assistant", "content": None, "tool_calls": [copy.deepcopy(call)]})
|
||||
calls = choice["message"]["tool_calls"]
|
||||
if invalid == "missing-id": calls[0].pop("id")
|
||||
if invalid == "empty-id": calls[0]["id"] = ""
|
||||
if invalid == "whitespace-id": calls[0]["id"] = " \t"
|
||||
if invalid == "whitespace-name": calls[0]["function"]["name"] = " \t"
|
||||
if invalid == "duplicate-id": calls.append(copy.deepcopy(calls[0]))
|
||||
if invalid == "overflow": calls[0]["function"]["arguments"] = '{"x":1e309}'
|
||||
if invalid == "duplicate-field": calls[0]["function"]["arguments"] = '{"x":1,"x":2}'
|
||||
if invalid == "list-arguments": calls[0]["function"]["arguments"] = '[1]'
|
||||
if invalid == "incomplete": choice["finish_reason"] = "length"
|
||||
self.refuse(report(), candidate)
|
||||
|
||||
def test_failure_terminals_never_count_as_protocol_equivalence(self):
|
||||
baseline, candidate = report(), report()
|
||||
for row in baseline["rows"] + candidate["rows"]:
|
||||
row["quality"]["passed"] = False
|
||||
row["response"]["choices"][0]["finish_reason"] = "length"
|
||||
summary = self.compare(baseline, candidate)["summary"]
|
||||
self.assertEqual(summary["same_normalized_output"], 0)
|
||||
self.assertEqual(summary["quality"]["candidate_http_or_protocol_failed"], 6)
|
||||
self.assertFalse(summary["quality"]["observed_checks_passed"])
|
||||
|
||||
def test_case_pair_and_nested_json_work_limits(self):
|
||||
baseline = report((1.,))
|
||||
for index in range(1, 65):
|
||||
baseline["rows"] += report((1.,), case=f"case-{index}")["rows"]
|
||||
self.refuse(baseline, copy.deepcopy(baseline))
|
||||
baseline = report((1.,) * 100)
|
||||
for index in range(1, 41):
|
||||
baseline["rows"] += report((1.,) * 100, case=f"case-{index}")["rows"]
|
||||
self.refuse(baseline, copy.deepcopy(baseline))
|
||||
baseline = report()
|
||||
nested = {}
|
||||
for _ in range(33):
|
||||
nested = {"nested": nested}
|
||||
baseline["metadata"] = nested
|
||||
self.refuse(baseline, report())
|
||||
|
||||
def test_provenance_names_only_and_never_automatic_qualification(self):
|
||||
baseline, candidate = report(), report()
|
||||
baseline["metadata"] = candidate["metadata"] = {"operator_note": PRIVATE, "quality_gate_result": "claimed-pass"}
|
||||
result = self.compare(baseline, candidate)
|
||||
missing = result["provenance"]["candidate"]["missing_fields"]
|
||||
self.assertIn("gpu", missing)
|
||||
self.assertIn("ttft", missing)
|
||||
self.assertNotIn("quality_gate_result", missing)
|
||||
self.assertNotIn(PRIVATE, json.dumps(result["provenance"]))
|
||||
self.assertIn("Synthetic/CPU", result["comparison_limit"])
|
||||
self.assertFalse(result["qualification"]["model_quality_qualified"])
|
||||
|
||||
def test_private_mode_no_overwrite_and_no_git_output(self):
|
||||
old_mask = os.umask(0)
|
||||
try:
|
||||
self.compare(report(), report())
|
||||
finally:
|
||||
os.umask(old_mask)
|
||||
self.assertEqual(self.out.stat().st_mode & 0o777, 0o600)
|
||||
original = self.out.read_bytes()
|
||||
self.assertNotEqual(self.invoke(report(), report()).returncode, 0)
|
||||
self.assertEqual(self.out.read_bytes(), original)
|
||||
git_directory = self.directory / "fake-git"
|
||||
git_directory.mkdir()
|
||||
(git_directory / ".git").write_text("gitdir: fixture")
|
||||
output = git_directory / "report.json"
|
||||
self.assertNotEqual(self.invoke(report(), report(), output).returncode, 0)
|
||||
self.assertFalse(output.exists())
|
||||
symlink = self.directory / "link.json"
|
||||
destination = self.directory / "nonexistent.json"
|
||||
symlink.symlink_to(destination)
|
||||
self.assertNotEqual(self.invoke(report(), report(), symlink).returncode, 0)
|
||||
self.assertFalse(destination.exists())
|
||||
|
||||
def test_duplicate_json_and_oversize_refused_without_private_diagnostic(self):
|
||||
self.c.write_text(json.dumps(report()))
|
||||
self.b.write_text('{"schema":1,"schema":1,"private":"' + PRIVATE + '"}')
|
||||
result = subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.b), str(self.c), "--output", str(self.out)], capture_output=True, text=True, timeout=15)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertNotIn(PRIVATE, result.stdout + result.stderr)
|
||||
self.assertFalse(self.out.exists())
|
||||
with self.b.open("wb") as source:
|
||||
source.truncate(32 * 1024 * 1024 + 1)
|
||||
result = subprocess.run([sys.executable, "-B", str(SCRIPT), str(self.b), str(self.c), "--output", str(self.out)], capture_output=True, text=True, timeout=15)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(self.out.exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user