Hand glibc's free heap back after a large pipeline making

A driver's compiler frees what it took when the making returns, and glibc's malloc keeps
what a thread frees in that thread's arena, so a process whose threads each made a large
pipeline holds each one's compile peak as free heap until it ends. On an RX 7900 XTX (RADV,
Mesa 26.2.6) a kernel of 200,000 fused multiply-adds with 600 values live, made as 9
VkPipelines, took the process's resident set from 105 MiB to 7.3 GiB; malloc_trim handed
back all but 327 MiB, and the VkPipelines and live VkPipelineCaches held about 170 MiB of
that (a probe, m3-max-24140). A guest's Blender run on the XTX grew about 0.5 GiB per large
compute variant until its VkDevice went, and died at its cgroup's cap.

Now a large making (65,536 SPIR-V words or more, the makings pipeline/compile_memory.rs
already holds words for) whose return leaves glibc more than 256 MiB free (mallinfo2's
fordblks, every arena's) calls malloc_trim(0) on its thread before it gives its words back,
counted in the new WorkCounts::heap_trims. It trims glibc's arenas process-wide; on any
other allocator nothing is called. The trade, in compile_memory.rs's docs: the next large
making faults its working set in again (about 1 s per 3.5 GiB).

For a consumer: WorkCounts gains a field (api_signatures.tsv blessed).

Test: tests/heap_trimmed.rs (m2v_gpu, Linux GNU): three large makings of one kernel keep
the resident set within 1 GiB of where it began, and count a trim.
This commit is contained in:
Anees Iqbal committed 2026-11-12 21:16:23 -08:00
1 parent 3d95d813bb
commit e9e48221d8
6 files changed
+208 -2

No files matched your search

@@ -819,15 +819,20 @@ impl DeviceShared {
/// SPIR-V words holds around its driver call (`pipeline/compile_memory.rs`): `None` where it
/// does not count. One that waited for them counts in
/// `WorkCounts::makings_held_for_compile_memory`, its wait in `compile_memory_held_nanos`.
/// Dropped after the call, it hands the free heap the compile left back where it is large
/// (`WorkCounts::heap_trims`).
pub(crate) fn compile_memory(
&self,
words: usize,
) -> Option<crate::pipeline::compile_memory::Words<'static>> {
) -> Option<crate::pipeline::compile_memory::LargeMaking<'_>> {
let (held, waited) = crate::pipeline::compile_memory::hold(words)?;
if let Some(waited) = waited {
self.counts.making_held_for_compile_memory(waited);
}
Some(held)
Some(crate::pipeline::compile_memory::LargeMaking {
_words: held,
counts: &self.counts,
})
}
/// The compute pipeline of `info`, made as
@@ -25,9 +25,24 @@
//! program sees stay the callers'; the limit only delays a driver call.
//! - **Counted.** A making that waited counts in `WorkCounts::makings_held_for_compile_memory`,
//! and its wait in `WorkCounts::compile_memory_held_nanos`.
//! - **The free heap handed back** ([`LargeMaking`]). What the compiler took it frees when the
//! making returns, and glibc's `malloc` keeps what a thread frees in that thread's arena, so a
//! process whose threads each made a large pipeline holds each one's peak as free heap until it
//! ends: on an RX 7900 XTX (RADV, Mesa 26.2.6), one kernel of 200,000 fused multiply-adds with 600
//! values live at once made as 9 `VkPipeline`s took the process's resident set from 105 MiB to
//! 7.3 GiB, of which `malloc_trim` handed back all but 327 MiB (one run; the `VkPipeline`s and the
//! driver's caches held about 170 MiB of it). So where a large making's return leaves glibc more
//! than [`FREE_FLOOR`] bytes free (`mallinfo2`'s `fordblks`, every arena's), the making's thread
//! calls `malloc_trim(0)` before it gives its words back, counted in `WorkCounts::heap_trims`.
//! It trims glibc's own arenas, process-wide: the host's free heap goes back with ours. The
//! trade: the next large making faults its working set in again, about 1 s per 3.5 GiB of it,
//! where it would have reused the free heap; the floor spares makings that leave less. Only
//! where the process's allocator is glibc's (Linux, the GNU environment): on any other nothing is
//! called, and a host whose `malloc` is not glibc's sees no change.
use super::budget::{self, Rank, Urgency};
use crate::device::lock;
use crate::work_counts::Counters;
use std::sync::{Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};
@@ -57,6 +72,46 @@ struct State {
next: u64,
}
/// The most free heap a large making's return leaves glibc before it is handed back: 256 MiB
/// (the module docs).
pub(crate) const FREE_FLOOR: usize = 256 << 20;
/// A large making's words of the process's limit, held around its driver call: when dropped, it
/// hands glibc's free heap back where it holds more than [`FREE_FLOOR`] bytes (the module docs),
/// then gives the words back.
pub(crate) struct LargeMaking<'a> {
pub(crate) _words: Words<'static>,
pub(crate) counts: &'a Counters,
}
impl Drop for LargeMaking<'_> {
fn drop(&mut self) {
if return_free_heap() {
self.counts.heap_trimmed();
}
}
}
/// Hand glibc's free heap back to the system where it holds more than [`FREE_FLOOR`] bytes free,
/// every arena's: whether it called `malloc_trim` (the module docs).
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn return_free_heap() -> bool {
// SAFETY: no precondition.
let free = unsafe { libc::mallinfo2() }.fordblks;
if free <= FREE_FLOOR {
return false;
}
// SAFETY: no precondition; it returns free pages only.
unsafe { libc::malloc_trim(0) };
true
}
/// Nothing where the process's allocator is not glibc's (the module docs).
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
fn return_free_heap() -> bool {
false
}
/// The words a making holds, given back when dropped.
pub(crate) struct Words<'a> {
limit: &'a Limit,
@@ -0,0 +1,130 @@
//! The free heap a large making's compile leaves is handed back (`pipeline/compile_memory.rs`): a
//! kernel of [`STEPS`] fused multiply-adds with [`WINDOW`] values live at once, past the registers,
//! made as three `VkPipeline`s (its state's, for a grid of whole threadgroups, and a ragged grid's
//! interior and edge regions), each a large making. glibc keeps what the driver's compile frees in
//! the compiling thread's arena; handed back after each, the process's resident set stays within
//! [`BOUND_MIB`] of what it was before the first, and the device counts the trims.
//!
//! Measured on an RX 7900 XTX (RADV, Mesa 26.2.6) with 200,000 steps and nothing handed back: 105
//! MiB before, 3.8 GiB after the first making, 7.3 GiB after the third (one run).
//!
//! A device test of glibc's allocator: compiled only under `m2v_gpu` on Linux with the GNU
//! environment. The module is LLVM text written here (`llvm-as`).
use super::blit_holds::{device, Scratch, WAIT};
use super::opencl_mode::words_buffer;
use super::spares_bench::process_memory;
use super::uniform_bind_offsets::idle;
use crate::{CommandBufferStatus, ComputePipelineState, Device, PipelineOptions, Size};
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
use std::fmt::Write;
/// The kernel's fused multiply-adds.
const STEPS: usize = 150_000;
/// The values each step's operand is behind: so many live at once.
const WINDOW: usize = 600;
/// The most the resident set may grow over the makings, in MiB.
const BOUND_MIB: u64 = 1024;
/// `heavy(device float *out [[buffer(0)]], uint gid [[thread_position_in_grid]], uint index
/// [[thread_index_in_threadgroup]])`: `out[gid] = f(index)`, `f` the chain of [`STEPS`] steps, each
/// step's operand [`WINDOW`] steps behind it.
fn kernel() -> String {
let mut body = String::new();
body.push_str("%at = zext i32 %gid to i64\n");
body.push_str("%p = getelementptr inbounds float, ptr addrspace(1) %out, i64 %at\n");
body.push_str("%x0 = uitofp i32 %index to float\n");
let hex = |v: f32| format!("0x{:016X}", f64::from(v).to_bits());
for i in 0..STEPS {
let c = hex(1.0f32 + (i as f32 + 1.0) * 2f32.powi(-22));
let (x, y) = match i < WINDOW {
true => ("%x0".to_owned(), hex((i % 1024) as f32 * 0.25)),
false => (format!("%x{i}"), format!("%x{}", i + 1 - WINDOW)),
};
let a = match i < WINDOW {
true => format!("{x}, float {c}, float {y}"),
false => format!("{x}, float {y}, float {c}"),
};
writeln!(body, "%x{} = call float @llvm.fma.f32(float {a})", i + 1).unwrap();
}
writeln!(body, "store float %x{STEPS}, ptr addrspace(1) %p, align 4").unwrap();
format!(
"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\"\n\
target triple = \"air64_v28-apple-macosx26.0.0\"\n\n\
declare float @llvm.fma.f32(float, float, float)\n\n\
define void @heavy(ptr addrspace(1) noundef %out, i32 noundef %gid, i32 noundef %index) {{\n\
entry:\n{body}ret void\n}}\n\n\
!llvm.module.flags = !{{!0, !1}}\n!air.kernel = !{{!2}}\n!air.version = !{{!8}}\n!air.language_version = !{{!9}}\n\
!0 = !{{i32 7, !\"air.max_device_buffers\", i32 31}}\n\
!1 = !{{i32 7, !\"air.max_threadgroup_buffers\", i32 31}}\n\
!2 = !{{ptr @heavy, !3, !4}}\n!3 = !{{}}\n!4 = !{{!5, !6, !7}}\n\
!5 = !{{i32 0, !\"air.buffer\", !\"air.location_index\", i32 0, i32 1, !\"air.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\
!6 = !{{i32 1, !\"air.thread_position_in_grid\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"gid\"}}\n\
!7 = !{{i32 2, !\"air.thread_index_in_threadgroup\", !\"air.arg_type_name\", !\"uint\", !\"air.arg_name\", !\"index\"}}\n\
!8 = !{{i32 2, i32 8, i32 0}}\n!9 = !{{!\"Metal\", i32 4, i32 0, i32 0}}\n"
)
}
fn state(device: &Device) -> ComputePipelineState {
let air = metal2vulkan_devtools::llvm_assemble_text(&kernel()).unwrap();
let library = metal2vulkan::library::Library::from_air(&air).unwrap();
let function = device
.new_library_with_compile_library(library)
.new_function_with_name("heavy")
.unwrap();
let descriptor =
ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor()));
device
.new_compute_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap()
}
/// Dispatch `n` threads in threadgroups of 128 and wait.
fn dispatch(device: &Device, state: &ComputePipelineState, n: u32) {
let out = words_buffer(device, &[0; 256]);
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(state).unwrap();
encoder.set_buffer(Some(&out), 0, 0).unwrap();
encoder
.dispatch_threads(Size::new(u64::from(n), 1, 1), Size::new(128, 1, 1))
.unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
}
/// The process's resident set, in MiB.
fn resident_mib() -> u64 {
process_memory()["vm-rss"] / 1024
}
#[test]
fn a_large_makings_free_heap_is_handed_back() {
let scratch = Scratch::new("heap-trimmed");
let device = device(&scratch.0);
let before = resident_mib();
let trims = || device.work_counts().heap_trims;
let state = state(&device);
dispatch(&device, &state, 128);
idle(&device);
let first = resident_mib();
dispatch(&device, &state, 129);
idle(&device);
let second = resident_mib();
println!(
"HEAP-TRIMMED {}: resident {before} MiB before, {first} after the first making, {second} \
after the second; {} trims",
device.name(),
trims()
);
assert!(trims() > 0, "no large making handed its free heap back");
assert!(
second <= before + BOUND_MIB,
"the resident set grew from {before} MiB to {second} over three makings"
);
}
@@ -280,6 +280,8 @@ mod heap_tiled;
mod heap_tiled_blocks;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod heap_tiled_scratch;
#[cfg(all(m2v_gpu, target_os = "linux", target_env = "gnu"))]
mod heap_trimmed;
mod heap_usage;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod heap_use_released;
@@ -117,6 +117,7 @@ pub(crate) struct Counters {
flights_followed: AtomicU64,
makings_held_for_compile_memory: AtomicU64,
compile_memory_held_nanos: AtomicU64,
heap_trims: AtomicU64,
predicated_loop_runs_again: AtomicU64,
variants_taken_back: AtomicU64,
unlisted_argument_sampler_buffers: AtomicU64,
@@ -2299,6 +2300,11 @@ impl Counters {
);
}
/// A large making's return handed glibc's free heap back (`pipeline/compile_memory.rs`).
pub(crate) fn heap_trimmed(&self) {
self.heap_trims.fetch_add(1, Ordering::Relaxed);
}
/// A predicated loop's check ran its laying again (`command_buffer/rerun.rs`).
pub(crate) fn predicated_loop_ran_again(&self) {
self.predicated_loop_runs_again
@@ -5609,6 +5615,12 @@ pub struct WorkCounts {
pub makings_held_for_compile_memory: u64,
/// The time those makings waited, in nanoseconds, summed.
pub compile_memory_held_nanos: u64,
/// Large makings (65,536 SPIR-V words or more) whose return left glibc's `malloc` more than
/// 256 MiB of free heap, which the making's thread then handed back to the system with
/// `malloc_trim` (`pipeline/compile_memory.rs`): glibc keeps what a driver's compile frees in
/// the compiling thread's arena. Always 0 where the process's allocator is not glibc's (Linux,
/// the GNU environment). No Metal counterpart.
pub heap_trims: u64,
/// The runs again of predicated loops' layings that a check submitted, the loop still running
/// past its copies (`command_buffer/rerun.rs`).
pub predicated_loop_runs_again: u64,
@@ -9572,6 +9584,7 @@ impl Device {
.makings_held_for_compile_memory
.load(Ordering::Relaxed),
compile_memory_held_nanos: counters.compile_memory_held_nanos.load(Ordering::Relaxed),
heap_trims: counters.heap_trims.load(Ordering::Relaxed),
predicated_loop_runs_again: counters.predicated_loop_runs_again.load(Ordering::Relaxed),
variants_taken_back: counters.variants_taken_back.load(Ordering::Relaxed),
unlisted_argument_sampler_buffers: counters
@@ -2965,6 +2965,7 @@ field metal2vulkan-runtime::WorkCounts.heap_texture_refused_withheld pub heap_te
field metal2vulkan-runtime::WorkCounts.heap_texture_untiled_layouts pub heap_texture_untiled_layouts: u64
field metal2vulkan-runtime::WorkCounts.heap_textures_refit pub heap_textures_refit: u64
field metal2vulkan-runtime::WorkCounts.heap_textures_tiled pub heap_textures_tiled: u64
field metal2vulkan-runtime::WorkCounts.heap_trims pub heap_trims: u64
field metal2vulkan-runtime::WorkCounts.held_depths_released pub held_depths_released: u64
field metal2vulkan-runtime::WorkCounts.host_alias_lookups pub host_alias_lookups: u64
field metal2vulkan-runtime::WorkCounts.host_copy_blocks_made_in_place pub host_copy_blocks_made_in_place: u64
Can't render this file because it is too large.