Merge PR #6813: A layer that doesn't fit in GPU memory no longer breaks GPU drawing: older pages are freed and the layer is retried

This commit is contained in:
aiongg committed 2026-10-21 21:56:21 +00:00
commit 1bc45862cb
3 files changed
+186 -22

No files matched your search

+151 -20
View File
@@ -478,6 +478,10 @@ pub struct Compositor {
staged: u64,
/// Copies and render passes recorded since the last submit.
recorded: u32,
/// Why a layer page texture couldn't be created this refresh (it then ends on the CPU).
layer_alloc: Option<String>,
/// Bytes of pages dropped to admit new ones, not yet counted towards an intermediate submit.
admit_freed: u64,
acc_format: wgpu::TextureFormat,
/// Whether the effect-map pipelines could be built (else documents with layer effects are
/// [`Unsupported`] and use the CPU compositor).
@@ -589,6 +593,25 @@ fn field_reaches(progs: &[fx::MapProgram]) -> HashMap<FieldKind, i32> {
want
}
/// Why a refresh whose layer pages don't fit GPU memory is drawn on the CPU.
pub const OVER_BUDGET: &str = "layers exceed the GPU memory budget; full refresh on the CPU";
/// Which of `pages` (LRU clock, key, bytes) to drop, least recently used first, so `incoming`
/// more bytes fit `budget` on top of the `total` held now. Callers leave out pages that must stay.
fn lru_victims<K>(mut pages: Vec<(u64, K, u64)>, total: u64, incoming: u64, budget: u64) -> Vec<K> {
pages.sort_unstable_by_key(|p| p.0);
let mut total = total;
let mut out = Vec::new();
for (_, k, bytes) in pages {
if total.saturating_add(incoming) <= budget {
break;
}
total = total.saturating_sub(bytes);
out.push(k);
}
out
}
/// Runs `f` inside GPU error scopes and returns the first error raised.
/// Native wgpu reports errors synchronously; where they only arrive asynchronously (WebGPU) none
/// is reported.
@@ -720,6 +743,8 @@ impl Compositor {
stamp: 0,
staged: 0,
recorded: 0,
layer_alloc: None,
admit_freed: 0,
acc_format,
effect_maps: map_error.is_none(),
cmyk: 0,
@@ -1162,6 +1187,8 @@ impl Compositor {
self.stamp += 1;
self.staged = 0;
self.recorded = 0;
self.layer_alloc = None;
self.admit_freed = 0;
// Only render owns submission. A caller may discard encode's command buffer, so it
// cannot establish (or consume) a checkpoint whose GPU copy might never execute.
@@ -1225,9 +1252,45 @@ impl Compositor {
if let Some(f) = self.fault() {
return Err(Unsupported(f.to_string()));
}
// Out of memory although every page this cell doesn't use was dropped: the work recorded
// since the last submit can still hold those pages. Submit it, wait until the GPU is done
// with it so their memory is released, and run the cell once more. `encode` can't
// submit, so there the refresh goes to the CPU straight away.
if flush && self.layer_alloc.as_deref() == Some(OVER_BUDGET) {
self.layer_alloc = None;
submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit);
#[cfg(not(target_arch = "wasm32"))]
match self.health.as_ref() {
Some(h) => {
h.wait(device, last_submit.clone());
}
None => {
let _ = device.poll(wgpu::PollType::Wait { submission_index: last_submit.clone(), timeout: None });
}
}
self.staged = 0;
self.recorded = 0;
work = 0;
freed = 0;
self.admit_freed = 0;
stats.flushes += 1;
if let Some(f) = self.fault() {
return Err(Unsupported(f.to_string()));
}
let mut batch = Some(&mut last_submit);
self.run_cell(device, queue, encoder, doc.id, &plan, &runs, &paged, cell, &fr, &chunks, checkpoint, &mut stats, sink, &mut batch);
if let Some(f) = self.fault() {
return Err(Unsupported(f.to_string()));
}
}
// A page didn't fit even after evicting: this refresh goes to the CPU, the next one
// tries the GPU again (#6563).
if let Some(e) = self.layer_alloc.take() {
return Err(Unsupported(e));
}
let (evicted, bytes) = self.evict();
stats.evicted += evicted;
freed += bytes;
freed = freed.saturating_add(bytes.saturating_add(std::mem::take(&mut self.admit_freed)));
if flush && (self.staged >= flush_bytes || work >= FLUSH_WORK || freed >= flush_bytes || self.recorded >= FLUSH_OPS) {
submit_batch(device, queue, encoder, self.health.as_ref(), self.timer.as_mut(), &mut last_submit);
self.staged = 0;
@@ -1280,22 +1343,7 @@ impl Compositor {
/// whole-region effect maps drawn this frame. Returns how many textures were dropped and
/// their bytes.
fn evict(&mut self) -> (usize, u64) {
let (mut n, mut freed) = (0, 0u64);
let mut total = self.resident_bytes();
if total > self.resident_budget {
let mut lru: Vec<(u64, ResKey, u64)> =
self.residents.iter().filter(|(_, r)| r.stamp != self.stamp).map(|(k, r)| (r.stamp, *k, r.bytes())).collect();
lru.sort_unstable_by_key(|c| c.0);
for (_, k, bytes) in lru {
if total <= self.resident_budget {
break;
}
self.residents.remove(&k);
total = total.saturating_sub(bytes);
n += 1;
freed += bytes;
}
}
let (mut n, mut freed) = self.evict_residents(self.resident_budget, 0, None);
let mut total = self.fx_cache_bytes();
let fx_budget = usize::try_from(self.fx_budget).unwrap_or(usize::MAX);
if total > fx_budget {
@@ -1321,6 +1369,67 @@ impl Compositor {
(n, freed)
}
/// Drop least recently used resident pages until `incoming` more bytes fit in `budget`.
/// Never drops what the current cell uses, nor `keep`. Returns how many pages were dropped
/// and their bytes.
fn evict_residents(&mut self, budget: u64, incoming: u64, keep: Option<ResKey>) -> (usize, u64) {
let stamp = self.stamp;
let pages: Vec<(u64, ResKey, u64)> =
self.residents.iter().filter(|(k, r)| r.stamp != stamp && Some(**k) != keep).map(|(k, r)| (r.stamp, *k, r.bytes())).collect();
let (mut n, mut freed) = (0, 0u64);
for k in lru_victims(pages, self.resident_bytes(), incoming, budget) {
if let Some(r) = self.residents.remove(&k) {
n += 1;
freed += r.bytes();
}
}
(n, freed)
}
/// Create the page texture for `key`, `bytes` large. Least recently used pages make room in
/// the budget first; when the device is still out of memory, every page the current cell
/// doesn't use is dropped and creation is tried once more (#6563). `None` (with
/// `layer_alloc` set) when it still fails: `render` submits the recorded work, which can still
/// hold the dropped pages, and runs the cell once more; after that the CPU draws the refresh.
fn create_layer_texture(
&mut self,
device: &wgpu::Device,
desc: &wgpu::TextureDescriptor<'_>,
key: ResKey,
bytes: u64,
stats: &mut Stats,
) -> Option<wgpu::Texture> {
let replaced = self.residents.get(&key).map_or(0, Resident::bytes);
let (n, dropped) = self.evict_residents(self.resident_budget, bytes.saturating_sub(replaced), Some(key));
stats.evicted += n;
self.admit_freed = self.admit_freed.saturating_add(dropped);
// WebGPU reports errors asynchronously: its failures reach the health callbacks.
if cfg!(target_arch = "wasm32") {
return Some(device.create_texture(desc));
}
for retry in [false, true] {
let (texture, error) = first_error(device, || device.create_texture(desc));
match error {
None => return Some(texture),
Some(wgpu::Error::OutOfMemory { .. }) if !retry => {
let (n, dropped) = self.evict_residents(0, 0, Some(key));
stats.evicted += n;
self.admit_freed = self.admit_freed.saturating_add(dropped);
}
Some(wgpu::Error::OutOfMemory { .. }) => {
self.layer_alloc = Some(OVER_BUDGET.into());
return None;
}
Some(e) => {
self.layer_alloc = Some(format!("GPU layer texture failed: {e}"));
return None;
}
}
}
self.layer_alloc = Some(OVER_BUDGET.into());
None
}
/// Per-frame resources of `plan`: the tile area of each pass's surfaces, its LUT and pattern.
fn frame_res(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, canvas: Rect, plan: &Plan<'_>) -> FrameRes {
let grid = tile_grid(canvas);
@@ -1420,6 +1529,10 @@ impl Compositor {
.and_then(|_| chunks.iter().map(|c| self.prefix.restore_point(*c).map(|r| r.pass_end)).try_fold(usize::MAX, |m, p| Some(m.min(p?))))
.unwrap_or(0);
let bound = self.bind_cell(device, queue, encoder, doc, plan, paged, cell, fr, first_pass, stats);
// A page couldn't be created: draw nothing with the pages missing (the caller ends the refresh).
if self.layer_alloc.is_some() {
return;
}
// Chunk pool.
while self.pool.len() < plan.slots as usize {
@@ -1638,7 +1751,8 @@ impl Compositor {
region: Rect,
stats: &mut Stats,
) -> Option<(ResKey, [i32; 4])> {
if region.is_empty() {
// An earlier page of this cell didn't fit: the refresh ends after the cell anyway.
if region.is_empty() || self.layer_alloc.is_some() {
return None;
}
let format = surface.format();
@@ -1651,7 +1765,7 @@ impl Compositor {
.get(&key)
.is_none_or(|r| r.region != region || r.kind != kind || r.format != format || r.cmyk != cmyk || r.default_bits != default_bits);
if stale {
let texture = device.create_texture(&wgpu::TextureDescriptor {
let desc = wgpu::TextureDescriptor {
label: Some("pc_compose_layer"),
size: wgpu::Extent3d { width: region.width(), height: region.height(), depth_or_array_layers: 1 },
mip_level_count: 1,
@@ -1660,7 +1774,9 @@ impl Compositor {
format: kind.format(),
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
};
let bytes = region.width() as u64 * region.height() as u64 * kind.bytes_per_pixel() as u64;
let texture = self.create_layer_texture(device, &desc, key, bytes, stats)?;
let view = texture.create_view(&Default::default());
let default_nonzero = default_pixel.iter().any(|v| *v != 0.0);
let mut r = Resident {
@@ -2850,6 +2966,21 @@ mod tests {
}
}
#[test]
fn layer_pages_are_admitted_by_evicting_least_recently_used_first() {
let pages = || vec![(5, 'c', 40), (1, 'a', 30), (3, 'b', 20)];
// Fits already: nothing dropped.
assert!(lru_victims(pages(), 90, 10, 100).is_empty());
// 90 held + 40 incoming over 100: the oldest page goes first, then the next.
assert_eq!(lru_victims(pages(), 90, 40, 100), vec!['a']);
assert_eq!(lru_victims(pages(), 90, 60, 100), vec!['a', 'b']);
// Out of memory: a zero budget drops every candidate, and an impossible request stops
// when none are left instead of looping or overflowing.
assert_eq!(lru_victims(pages(), 90, 0, 0), vec!['a', 'b', 'c']);
assert_eq!(lru_victims(pages(), u64::MAX, u64::MAX, 1), vec!['a', 'b', 'c']);
assert!(lru_victims(Vec::<(u64, char, u64)>::new(), 90, 40, 100).is_empty());
}
#[test]
fn uniform_buffer_sizes_are_checked_before_allocation() {
assert_eq!(uniform_buffer_len(1, 255, 65_536).unwrap(), 65_536);
+32
View File
@@ -2781,6 +2781,38 @@ fn pages_are_evicted_under_the_budget() {
check(&mut g, &d, "after eviction");
}
/// #6563: a page texture that doesn't fit the budget is admitted by first dropping the least
/// recently used pages of other cells (never the current cell's). With a zero budget every page
/// created in a cell evicts the previous cell's pages, and the refresh still stays on the GPU
/// (budget pressure alone never ends it on the CPU) and matches the CPU compositor.
#[test]
fn layer_pages_are_admitted_under_a_zero_budget_and_stay_on_the_gpu() {
let Some(mut g) = gpu() else { return };
let mut d = base_doc(600, 500);
d.layers.push(noise_layer("mid", PixelFormat::RGBA8, Rect::new(-20, 10, 590, 480), 61, 0.0));
let mut top = noise_layer("top", PixelFormat::RGBA8, Rect::new(30, -15, 620, 510), 62, 0.2);
top.blend = BlendMode::Multiply;
d.layers.push(top);
// Exercise page residency itself: lower-stack checkpoints could skip binding the pages.
g.paged.set_composite_cache_budget(0);
check(&mut g, &d, "warm");
let all = g.paged.resident_bytes();
g.paged.set_resident_budget(0);
for round in 0..2 {
let cpu = photocraft_compose::flatten(&d);
let (out, s) = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, d.bounds())
.unwrap_or_else(|e| panic!("round {round}: a zero budget must not end the refresh on the CPU: {e}"));
let worst = worst_diff(&cpu.px, &out);
assert!(worst.0 <= TOL, "round {round}: max diff {:.2}/255 at {}", worst.0 * 255.0, worst.1);
assert!(s.cells > 1 && s.evicted > 0, "round {round}: {s:?}");
// Evicted pages were created again (uploaded), and only the last cell's are left.
assert!(s.tiles_uploaded > 0, "round {round}: {s:?}");
assert!(g.paged.resident_bytes() < all, "round {round}: {} of {all}", g.paged.resident_bytes());
d.layers[1].surface_mut().unwrap().fill_rect(Rect::new(40 + round * 250, 60, 90 + round * 250, 120), &[0.2, 0.8, 0.3, 1.0]);
}
check(&mut g, &d, "after zero-budget renders");
}
#[test]
fn the_focused_view_stays_resident_after_a_full_refresh() {
let _gamma = TEXT_GAMMA.lock().unwrap_or_else(|e| e.into_inner());
+3 -2
View File
@@ -1379,8 +1379,9 @@ impl LayerFit {
/// Floor of the compositor's memory budget: enough for a viewport's pages of a dozen layers.
pub const MIN_GPU_BUDGET: u64 = 512 << 20;
/// Why a full refresh whose layer pages don't fit [`memory_budget`] goes to the CPU compositor.
pub const OVER_BUDGET: &str = "layers exceed the GPU memory budget; full refresh on the CPU";
/// Why a full refresh whose layer pages don't fit [`memory_budget`] (or GPU memory) goes to the
/// CPU compositor.
pub const OVER_BUDGET: &str = photocraft_gpu::OVER_BUDGET;
/// GPU memory the wgpu compositor may hold for layer pages and effect maps.
///