Ledger: the plan's strategy table stays charged; the typed module's charge goes at serialization

In process the ledger is a translation's memory bound on live bytes: it refuses past 450 MiB so
the attempt holds under its 500 MiB ceiling. Selection charged the strategy table (one entry per
value) and the facts while it ran and released both when it returned, though the plan holds them
through emission, the roll and serialization. They now stay charged; only the walk's per-value
scratch goes. A guest kernel (function hash 4cc9c0bb, Iris profile, the size estimate lifted)
tripped at ledger 448.7 MiB with 538 MiB live in the attempt (job 62539); with this change it
trips at 450.0 MiB with 455 MiB live, 5 MiB uncounted (62588).

The other direction: the builder's growth, charged during emission, stayed on the ledger after
serialization consumed the typed module. `Emitted::held` carries it, and it goes when
serialization does: at serialization the ledger falls from 211.1 to 89.1 MiB with 90.0 MiB live
(function hash 16d856fc), and from 539.5 to 245.8 MiB with 199.5 live (4cc9c0bb under a raised
cap) (62611 against 62588).

The runtime README says what the bound is: live bytes. While an attempt ran, resident memory
stayed within about 10 MiB of them (16d856fc: 250.3 MiB live peak, 256 MiB resident peak; 62588);
after it returned, glibc kept about 140 MiB of it resident (18 MiB before, 158 after, 32 after
malloc_trim(0); 62601), which is the consumer's to return.

Verified:
- tests::ledger_resident (new): a function of 6,000 float operations applied 16 times in a chain
  (the applications roll into one loop), compiled for runtime-floor under ledger caps of 1/8 to
  7/8 of its uncapped peak. Each is refused LedgerBytes holding at most the cap and a ninth (the
  ratio of 500 to 450); uncapped, it holds at most its ledger peak and a ninth. Fails on
  development (62576: 45,049,929 bytes held at once against a ledger peak of 32,733,356, 1.38x);
  passes with this change (62604: 45,049,929 against 45,553,651; every cap held under the cap).
- The measurements above: release command line with a counting allocator (a probe that does not
  land), on the guest library's two kernels, by hash.
- The change moves only what the ledger counts: no emitted word depends on it, and a module is
  refused LedgerBytes only where its live bytes reach the cap.
This commit is contained in:
Anees Iqbal committed 2026-11-21 01:58:21 -08:00
1 parent 52ee4de509
commit fe1e8780a2
6 files changed
+200 -10

No files matched your search

+5
View File
@@ -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
+11 -4
View File
@@ -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<SlotRef>,
/// 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<Emitted, Err
crate::structurize::structurize(&view, m)
})?;
let mut mb = ModuleBuilder::new();
let emitted = (|| -> Result<(TypedModule, Vec<Offer>, BTreeSet<SlotRef>), Error> {
let emitted = (|| -> Result<(TypedModule, Vec<Offer>, BTreeSet<SlotRef>, 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<Emitted, Err
let offers = mb.offers().to_vec();
let module = mb.finalize()?;
m.charge(std::mem::size_of_val(offers.as_slice()))?;
Ok((module, offers, merged))
Ok((module, offers, merged, held.charged()))
})();
structured.release(m);
let (mut module, offers, merged) = emitted?;
let (mut module, offers, merged, held) = emitted?;
promote_single_store(&mut module, m)?;
// What no instruction reads leaves the module, after P9 turned its loads into copies, and the
// offers that make it smaller are taken.
@@ -1611,7 +1614,11 @@ pub fn emit_module(e: &Entry, plan: &Plan, m: &mut Meter) -> Result<Emitted, Err
if plan.families.arith.controls {
crate::spirv::half_hold::hold(&mut module, m)?;
}
Ok(Emitted { module, merged })
Ok(Emitted {
module,
merged,
held,
})
}
#[cfg(test)]
+13 -4
View File
@@ -1283,9 +1283,11 @@ fn select_entry(
stage_io::plan_entry(&mut cx).map_err(|e| located_param(e, &cx, None))?;
mesh::plan_entry(&mut cx).map_err(|e| located_param(e, &cx, None))?;
// Uses: which parameters are read, and the block of every use (for demotion).
// The strategy table, and the walk's scratch: which parameters are read, and the block of
// every use (for demotion).
let n = cx.values.len();
let bytes = n.saturating_mul(std::mem::size_of::<Option<Strategy>>() + 8);
let table = n.saturating_mul(std::mem::size_of::<Option<Strategy>>());
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
}
+7 -2
View File
@@ -3197,7 +3197,11 @@ fn lower_bounded<K>(
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<K>(
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.
@@ -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<Vec<u8>> {
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"
);
}
}
+1
View File
@@ -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;