diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 695e59da3..488a1a8f4 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2419,6 +2419,11 @@ while the driver's exit handler waited on a lock, with every runtime thread alre - Each lowering of a state's creation is one translation within its own 500 MiB ceiling, one after another, so the width of the consumer's creating threads multiplies the bound: creations on 4 threads at once hold at most 2 GiB of translation. +- That ceiling is on the bytes a translation holds live, and the high-water of what it freed can + stay resident under the process's allocator once it returns, which is the consumer's to return: + on glibc 2.44, resident memory stayed within about 10 MiB of the live bytes while an attempt ran, + and about 140 MiB of an attempt that peaked near 250 MiB stayed resident after it until + `malloc_trim(0)` returned it. - `ComputePipelineState::precision_notes` carries the translator's notes of where the kernel's answers may differ from Metal's on this device, fixed per operation: those of the modules made with the state, its variants among them. A kernel compiled diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index 00d35e6c4..73ad31182 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -1482,6 +1482,9 @@ pub struct Emitted { /// The buffer slots a store merged a partial word into through the sub-word store's atomics: /// the module reads each of them, whatever the function's own accesses are. pub merged: BTreeSet, + /// The ledger bytes charged for the module as its builder grew: they go when serialization + /// consumes it. + pub held: usize, } /// Structurize and emit `e` under `plan` into a finalized module with P9 applied. @@ -1496,7 +1499,7 @@ pub fn emit_module(e: &Entry, plan: &Plan, m: &mut Meter) -> Result Result<(TypedModule, Vec, BTreeSet), Error> { + let emitted = (|| -> Result<(TypedModule, Vec, BTreeSet, usize), Error> { let decl = declare(&mut mb, plan)?; // The builder is charged as it grows: the declarations here, the walk's growth by // `structurize::emit` after each block, and what the walk left once it returns. @@ -1596,10 +1599,10 @@ pub fn emit_module(e: &Entry, plan: &Plan, m: &mut Meter) -> Result Result>() + 8); + let table = n.saturating_mul(std::mem::size_of::>()); + let bytes = table.saturating_add(n.saturating_mul(8)); m.charge(bytes)?; // The pointer phis' incoming values, once per phi, before any use reads them. let phis = match access::phis::plan(&cx, m) { @@ -1308,9 +1310,16 @@ fn select_entry( let noted = cx.noted; let result = selected.and_then(|sel| finish(cx, sel, widest_pin, &mut fact_bytes, m)); m.release(noted); - m.release(fact_bytes.charged()); - m.release(bytes); m.release(phi_bytes); + // The plan holds the strategy table and the facts through emission and serialization: they + // stay on the ledger. + match &result { + Ok(_) => m.release(bytes - table), + Err(_) => { + m.release(bytes); + m.release(fact_bytes.charged()); + } + } result } diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 135299c60..b4d556e3d 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -3197,7 +3197,11 @@ fn lower_bounded( kernel, unbound, }, - crate::lower::emit::Emitted { mut module, merged }, + crate::lower::emit::Emitted { + mut module, + merged, + held, + }, ) = stage_bound::emit(r, p, (word_cap, bounds), m)?; let function_tables = spec.function_tables.clone(); let reaches_command_buffers = spec.may_encode_indirect_commands(); @@ -3334,7 +3338,8 @@ fn lower_bounded( let ids = crate::spirv::serialize::id_table_bytes(&module); m.charge(ids)?; let module = crate::spirv::serialize::serialize(module)?; - m.release(ids); + // The typed module is gone with its serialization, and its charge with it. + m.release(ids.saturating_add(held)); m.charge(module.footprint())?; // The retained words and relocations. // The estimate refused early; the cap holds on what was emitted. diff --git a/crates/metal2vulkan/src/tests/ledger_resident.rs b/crates/metal2vulkan/src/tests/ledger_resident.rs new file mode 100644 index 000000000..aff5d25cc --- /dev/null +++ b/crates/metal2vulkan/src/tests/ledger_resident.rs @@ -0,0 +1,163 @@ +//! What a translation holds stays within what its ledger counts. +//! +//! The ledger is an attempt's memory ceiling wherever no worker boundary measures one (the runtime +//! translates in its own process): it refuses past 450 MiB (`budget::LEDGER_BYTES`) so that the +//! attempt holds under 500 MiB. That holds only while the bytes the attempt holds at once never +//! pass what the ledger counts by more than a ninth of it (500 / 450), at every point of the +//! attempt. A structure held but not charged passes it in the stages that follow: the plan's +//! strategy table, one entry per value, was released from the ledger when selection returned, +//! though emission, the roll and serialization still hold the plan. +//! +//! So a kernel of that shape, a large function applied many times in a chain (the AIR inliner +//! writes each application out, every value has a strategy, and the roll writes the applications +//! as a loop), compiles under ledger caps of one to seven eighths of its uncapped ledger peak: each +//! is refused `LedgerBytes`, and the most bytes it held at once by then are at most the cap and a +//! ninth. Uncapped, the most bytes it held at once are at most its ledger peak and a ninth. The +//! allocator counts the bytes the translation asked for on its own thread +//! (`constant_blob_footprint::held_during`), the same number on any host. +//! +//! `llvm-as` assembles the kernel; without it the test skips visibly. + +use crate::budget::{Budget, Meter, LEDGER_BYTES, SPIRV_WORDS, WORK_UNITS}; +use crate::device::{DevicePolicy, DeviceProfile}; +use crate::error::{Error, Limit}; +use crate::library::FunctionConstantValues; +use crate::lower::select::LowerInputs; +use crate::pipeline::compile::{compile_bitcode, EntryRef}; +use crate::pipeline::testing::{compile_kept, llvm_assemble, profile, AssembleError, Scratch}; +use crate::tests::constant_blob_footprint::held_during; + +/// The `float` operations of the body. +const OPS: usize = 6_000; + +/// The operations before the body's first selection; each later stretch is one longer than the +/// one before. +const SEGMENT: usize = 500; + +/// The applications of `@body`, each reading the one before's result. +const CHAIN: usize = 16; + +/// `@body(x, c, out)`: `x + c`, then `* 0.5` or `+ 0.25` as [`halves`] picks, `OPS - 1` times, +/// and after stretches of `SEGMENT`, `SEGMENT + 1`, ... operations a selection that stores `-1` +/// to word 0 when the value is below `-2^30`; `@chain` applies the body [`CHAIN`] times, each +/// application to the one before's result, with the constants 1, 2, ..., and stores the last +/// result to word 0. +fn module() -> String { + let mut s = String::from( + "target datalayout = \"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n", + ); + s.push_str( + "define internal fastcc float @body(float %x, float %c, ptr addrspace(1) %out) {\nb0:\n", + ); + s.push_str(" %v0 = fadd float %x, %c\n"); + let (mut next, mut stretch) = (SEGMENT, SEGMENT); + for i in 1..OPS { + let (op, k) = if halves(i) { + ("fmul", "0x3FE0000000000000") + } else { + ("fadd", "0x3FD0000000000000") + }; + s.push_str(&format!(" %v{i} = {op} float %v{}, {k}\n", i - 1)); + if i == next && i + 1 < OPS { + stretch += 1; + next += stretch; + s.push_str(&format!( + " %t{i} = fcmp olt float %v{i}, 0xC1D0000000000000\n br i1 %t{i}, label %r{i}, label %j{i}\nr{i}:\n store float -1.0, ptr addrspace(1) %out, align 4\n br label %j{i}\nj{i}:\n" + )); + } + } + s.push_str(&format!(" ret float %v{}\n}}\n\n", OPS - 1)); + s.push_str( + "define void @chain(ptr addrspace(1) noundef \"air-buffer-no-alias\" %0) {\nentry:\n %c0 = fadd float 0x3FF8000000000000, -0.0\n", + ); + for j in 1..=CHAIN { + s.push_str(&format!( + " %c{j} = call fastcc float @body(float %c{}, float {j}.0, ptr addrspace(1) %0)\n", + j - 1 + )); + } + s.push_str(&format!( + " store float %c{CHAIN}, ptr addrspace(1) %0, align 4\n ret void\n}}\n\n" + )); + s.push_str("!llvm.module.flags = !{!0}\n!air.kernel = !{!20}\n!air.version = !{!17}\n!air.language_version = !{!18}\n\n"); + s.push_str("!0 = !{i32 7, !\"air.max_device_buffers\", i32 31}\n!10 = !{}\n!11 = !{!12}\n!12 = !{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.read_write\", !\"air.address_space\", i32 1, !\"air.arg_type_size\", i32 4, !\"air.arg_type_align_size\", i32 4, !\"air.arg_type_name\", !\"float\", !\"air.arg_name\", !\"out\"}\n!17 = !{i32 2, i32 8, i32 0}\n!18 = !{!\"Metal\", i32 4, i32 0, i32 0}\n!20 = !{ptr @chain, !10, !11}\n"); + s +} + +/// Whether operation `i` of the body halves the value (else it adds `0.25`): a bit of a +/// multiplicative hash of `i`, so no stretch of the body repeats another (only the applications +/// repeat). +fn halves(i: usize) -> bool { + ((i as u64).wrapping_mul(2_654_435_761) >> 16) & 1 == 1 +} + +/// The module assembled by `llvm-as`, or `None` (the test skips visibly) without it. +fn assembled() -> Option> { + let scratch = Scratch::new("m2v-ledger-resident"); + let ll = scratch.path().join("chain.ll"); + std::fs::write(&ll, module()).expect("write"); + match llvm_assemble(&ll) { + Ok(b) => Some(b), + Err(AssembleError::Missing(t)) => { + eprintln!("SKIPPED: {t}"); + None + } + Err(AssembleError::Rejected(e)) => panic!("llvm-as rejected the module: {e}"), + } +} + +/// `@chain` compiled for `p` under a ledger cap of `cap` bytes: the result, the ledger peak, and +/// the most bytes the compile held at once. +fn compiled(bc: &[u8], p: &DeviceProfile, cap: u64) -> (Result<(), Error>, u64, u64) { + let mut m = Meter::with_caps(&Budget::default(), WORK_UNITS, cap); + let (r, held) = held_during(|| { + compile_bitcode( + bc, + EntryRef::Name("chain"), + &FunctionConstantValues::defaults(), + p, + &LowerInputs::new(), + &mut m, + SPIRV_WORDS, + ) + }); + (r.map(|_| ()), m.ledger_peak(), held) +} + +/// The most bytes a ledger of `ledger` bytes stands for: it and a ninth (500 MiB for the 450 MiB +/// cap). +fn within(ledger: u64) -> u64 { + ledger + ledger / 9 +} + +#[test] +fn what_a_translation_holds_stays_within_its_ledger() { + let Some(bc) = assembled() else { + return; + }; + let p = profile("runtime-floor", DevicePolicy::default()).expect("profile"); + // The shape: the applications are rolled into a loop (the body holds none). + let (_, _, kept) = compile_kept(&bc, "chain", &p).expect("chain"); + assert_eq!(kept.loops().len(), 1, "the applications roll into one loop"); + let (r, peak, held) = compiled(&bc, &p, LEDGER_BYTES); + r.expect("translates"); + eprintln!("uncapped: ledger peak {peak} bytes, {held} bytes held at once"); + assert!( + held <= within(peak), + "uncapped: {held} bytes held at once against a ledger peak of {peak} bytes" + ); + for eighths in 1..8 { + let cap = peak * eighths / 8; + let (r, _, held) = compiled(&bc, &p, cap); + eprintln!("cap {cap} bytes ({eighths}/8): {held} bytes held at once"); + assert_eq!( + r, + Err(Error::LimitExceeded(Limit::LedgerBytes)), + "cap {cap} bytes ({eighths}/8)" + ); + assert!( + held <= within(cap), + "cap {cap} bytes ({eighths}/8): {held} bytes held at once by the refusal" + ); + } +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 2d58fad7b..231d858fa 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -220,6 +220,7 @@ mod env_registry; mod fuzz_interp; mod fuzz_soak; mod golden_hashes; +mod ledger_resident; mod library_entries_decode_once; mod library_hash_beside; mod module_version_1;