GPU: size the upload cache from the card's memory (EFFECTCRAFT_GPU_UPLOAD_MB), so 300 large layers upload once

Refs #3731
This commit is contained in:
vangel76 committed 2026-11-15 17:37:13 +01:00
1 parent d6c9ad6643
commit e616abe953
6 files changed
+234 -18

No files matched your search

Generated
+1
View File
@@ -1788,6 +1788,7 @@ dependencies = [
"wasm-bindgen",
"web-time",
"wgpu",
"windows-registry",
]
[[package]]
+3
View File
@@ -27,6 +27,9 @@ web-time = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
pollster = { workspace = true }
[target.'cfg(windows)'.dependencies]
windows-registry = "=0.6.1"
[dev-dependencies]
effectcraft-text = { workspace = true }
+11 -8
View File
@@ -112,9 +112,6 @@ type EffectPipelines = HashMap<&'static str, (usize, std::sync::OnceLock<Result<
/// 8/16 bpc are emulated by clamping and quantising, as on the CPU).
pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float;
/// Uploaded layer buffers kept on the GPU by default (bytes; [`GpuContext::set_upload_budget`]).
const UPLOAD_BUDGET: usize = 1536 << 20;
/// Working textures kept for reuse once their last image is dropped (bytes).
const POOL_BUDGET: usize = 256 << 20;
@@ -1028,7 +1025,7 @@ impl GpuContext {
uploads: Mutex::new(Uploads::default()),
pictures: Default::default(),
upload_staging: Default::default(),
upload_budget: std::sync::atomic::AtomicUsize::new(UPLOAD_BUDGET),
upload_budget: std::sync::atomic::AtomicUsize::new(memcap.upload_budget()),
upload_full_warned: Default::default(),
pool,
staging: Default::default(),
@@ -1168,6 +1165,11 @@ impl GpuContext {
pool + staging + self.upload_staging.bytes() + zeros
}
#[cfg(test)]
pub(crate) fn upload_budget_from_rule(&self) -> usize {
self.memcap.upload_budget()
}
#[cfg(test)]
pub(crate) fn memcap_waits(&self) -> u64 {
self.memcap.waits()
@@ -1580,7 +1582,7 @@ impl GpuContext {
uploads: Mutex::new(Uploads::default()),
pictures: Default::default(),
upload_staging: Default::default(),
upload_budget: std::sync::atomic::AtomicUsize::new(UPLOAD_BUDGET),
upload_budget: std::sync::atomic::AtomicUsize::new(self.upload_budget()),
upload_full_warned: Default::default(),
pool: self.pool.clone(),
staging: Default::default(),
@@ -1658,9 +1660,10 @@ impl GpuContext {
(GpuImage { texture, width: w, height: h, _lease: Some(lease), levels: None }, was_reused)
}
/// Bytes of uploaded layer textures the context keeps (default 1536 MB). An application that
/// knows the device's memory can raise it (static layers of a big frame upload once) or lower
/// it (a small GPU); the least recently used textures go first.
/// Bytes of uploaded layer textures the context keeps (by default 3/8 of the card's memory
/// when known, 1536 MB otherwise; `EFFECTCRAFT_GPU_UPLOAD_MB`, see `memcap`). An application
/// can raise it (static layers of a big frame upload once) or lower it (a small GPU); the
/// least recently used textures go first.
pub fn set_upload_budget(&self, bytes: usize) {
self.upload_budget.store(bytes.max(1 << 20), std::sync::atomic::Ordering::Relaxed);
}
+166 -9
View File
@@ -12,9 +12,16 @@
//! wgpu has no safe query for the adapter's memory size (`max_buffer_size` is capped at `i32::MAX`
//! on Direct3D 12 and Linux/Mesa Vulkan), so the default cap is conservative per device type,
//! and lower on a discrete card whose memory the OS reports without `unsafe` (Linux's amdgpu
//! driver, in sysfs: a 2–4 GB card ran out of memory and took the system down, #1487);
//! driver, in sysfs, and the display class key of the registry on Windows: a 2–4 GB card ran
//! out of memory and took the system down, #1487);
//! `EFFECTCRAFT_GPU_MEMCAP_MB` overrides it (0 = off). Backends without an allocator report
//! (Metal, WebGPU, GL) are never gated.
//!
//! The upload cache (textures of layers already uploaded) has a budget of its own, three eighths
//! of the card's memory when that is known and 1.5 GiB otherwise (`EFFECTCRAFT_GPU_UPLOAD_MB`
//! overrides it): a comp whose layers are larger than the budget re-uploads all of them every
//! frame (#3731). The cache counts against the cap, so the default cap grows with the budget
//! (never above three quarters of the card) and frames in flight are not starved by it.
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
@@ -30,8 +37,16 @@ const MIB: u64 = 1 << 20;
/// Overrides the default cap: whole MiB, 0 turns the gate off.
const MEMCAP_ENV: &str = "EFFECTCRAFT_GPU_MEMCAP_MB";
/// Overrides the default upload cache budget: whole MiB, 0 = the default.
const UPLOAD_ENV: &str = "EFFECTCRAFT_GPU_UPLOAD_MB";
/// The upload cache budget when the card's memory is not known (the default cap leaves room for it).
const UPLOAD_DEFAULT: u64 = GIB + GIB / 2;
pub(crate) struct MemCap {
cap: u64,
/// Bytes of uploaded layer textures to keep (see [`upload_budget`]).
upload: usize,
hysteresis: u64,
calls: AtomicU64,
waits: AtomicU64,
@@ -49,13 +64,32 @@ pub(crate) struct MemCap {
impl MemCap {
pub(crate) fn new(info: &wgpu::AdapterInfo) -> MemCap {
let env = std::env::var(MEMCAP_ENV).ok();
Self::from_env(env.as_deref(), info.device_type, vram(info))
let upload = std::env::var(UPLOAD_ENV).ok();
Self::from_envs(env.as_deref(), upload.as_deref(), info.device_type, vram(info))
}
#[cfg(test)]
fn from_env(var: Option<&str>, device_type: wgpu::DeviceType, vram: Option<u64>) -> MemCap {
let cap = cap_from_env(var, device_type, vram);
Self::from_envs(var, None, device_type, vram)
}
fn from_envs(cap_var: Option<&str>, upload_var: Option<&str>, device_type: wgpu::DeviceType, vram: Option<u64>) -> MemCap {
let mut upload = upload_budget(upload_var, vram);
// An explicit cap is the user's: it does not grow with the cache, so a default budget
// is lowered to half of it (never below the former fixed 1.5 GiB); an explicit one stays.
let cap = match cap_var {
Some(_) => {
let cap = cap_from_env(cap_var, device_type, vram);
if cap > 0 && explicit_upload(upload_var).is_none() {
upload = upload.min((cap / 2).max(UPLOAD_DEFAULT));
}
cap
}
None => default_cap_for(device_type, vram, upload),
};
MemCap {
cap,
upload: usize::try_from(upload).unwrap_or(usize::MAX),
hysteresis: default_hysteresis(cap),
calls: AtomicU64::new(0),
waits: AtomicU64::new(0),
@@ -72,6 +106,7 @@ impl MemCap {
pub(crate) fn fresh(&self) -> MemCap {
MemCap {
cap: self.cap,
upload: self.upload,
hysteresis: self.hysteresis,
calls: AtomicU64::new(0),
waits: AtomicU64::new(0),
@@ -86,6 +121,11 @@ impl MemCap {
self.cap
}
/// Bytes of uploaded layer textures the context keeps.
pub(crate) fn upload_budget(&self) -> usize {
self.upload
}
/// Remember an allocator sample: the peak only grows.
pub(crate) fn note(&self, allocated: u64) {
self.peak.fetch_max(allocated, Relaxed);
@@ -179,9 +219,39 @@ fn cap_from_env(var: Option<&str>, device_type: wgpu::DeviceType, vram: Option<u
}
}
/// The upload cache budget from the `EFFECTCRAFT_GPU_UPLOAD_MB` value: whole MiB, or (0, unset, or
/// with a warning not a number) three eighths of the card's memory when known (`vram`: 4 GB gives
/// the former fixed 1.5 GiB, a 32 GB card 12 GiB) and 1.5 GiB otherwise.
fn upload_budget(var: Option<&str>, vram: Option<u64>) -> u64 {
let default = vram.map_or(UPLOAD_DEFAULT, |v| v / 8 * 3);
if let Some(v) = var
&& explicit_upload(var).is_none()
&& v.trim() != "0"
{
log::warn!(target: "effectcraft_gpu", "{UPLOAD_ENV}={v:?} is not a whole number of MiB that fits in 64 bits: using {} MiB", default / MIB);
}
explicit_upload(var).unwrap_or(default)
}
/// The budget the user set: whole MiB above 0.
fn explicit_upload(var: Option<&str>) -> Option<u64> {
var?.trim().parse::<u64>().ok().and_then(|mb| mb.checked_mul(MIB)).filter(|&b| b > 0)
}
/// The default cap plus what the upload cache holds beyond the 1.5 GiB the default cap already
/// leaves room for, never above three quarters of the card's memory when that is known.
fn default_cap_for(t: wgpu::DeviceType, vram: Option<u64>, upload: u64) -> u64 {
let base = default_cap(t, vram);
let cap = base.saturating_add(upload.saturating_sub(UPLOAD_DEFAULT));
match vram {
Some(v) if t == wgpu::DeviceType::DiscreteGpu => cap.min((v / 4).saturating_mul(3)).max(base),
_ => cap,
}
}
/// Discrete cards: 3 GiB, low enough to fire on 4–8 GB cards with headroom for the driver and
/// desktop while leaving ~1 GiB above the default 1.5 GiB upload cache + 256 MB pool (larger
/// cards can raise it with `EFFECTCRAFT_GPU_MEMCAP_MB`), and at most three quarters of the card's
/// desktop while leaving ~1 GiB above the default 1.5 GiB upload cache + 256 MB pool (a bigger
/// upload cache raises it, see [`default_cap_for`]; `EFFECTCRAFT_GPU_MEMCAP_MB` sets it), and at most three quarters of the card's
/// memory when it is known (`vram`), so a 2 GB card gets 1.5 GiB (#1487). Integrated and software
/// adapters share system memory: 2 GiB, whatever their carve-out.
fn default_cap(t: wgpu::DeviceType, vram: Option<u64>) -> u64 {
@@ -191,22 +261,55 @@ fn default_cap(t: wgpu::DeviceType, vram: Option<u64>) -> u64 {
}
}
/// The adapter's dedicated memory in bytes, where the OS reports it without `unsafe`.
/// The adapter's dedicated memory in bytes, where the OS reports it without `unsafe`: Linux's
/// amdgpu driver in sysfs, the display class key of the registry on Windows.
fn vram(info: &wgpu::AdapterInfo) -> Option<u64> {
if !cfg!(target_os = "linux") || info.device_type != wgpu::DeviceType::DiscreteGpu {
if info.device_type != wgpu::DeviceType::DiscreteGpu {
return None;
}
let bytes = vram_in_sysfs(Path::new("/sys/class/drm"), info.vendor, info.device, &info.device_pci_bus_id);
#[cfg(target_os = "linux")]
let (bytes, source) = (vram_in_sysfs(Path::new("/sys/class/drm"), info.vendor, info.device, &info.device_pci_bus_id), "sysfs");
#[cfg(windows)]
let (bytes, source) = (vram_in_registry(info.vendor, info.device), "registry");
#[cfg(not(any(target_os = "linux", windows)))]
let (bytes, source) = (None::<u64>, "");
if let Some(b) = bytes {
log::info!(target: "effectcraft_gpu", "gpu {}: {} MiB of video memory (sysfs)", info.name, b >> 20);
log::info!(target: "effectcraft_gpu", "gpu {}: {} MiB of video memory ({source})", info.name, b >> 20);
}
bytes
}
/// `HardwareInformation.qwMemorySize` of the display adapters under the display class key whose
/// `MatchingDeviceId` names the PCI vendor and device (drivers write it as a 64-bit value, so a
/// 32 GB card reads right). Variants of one model share the ids: the smallest wins.
#[cfg(windows)]
fn vram_in_registry(vendor: u32, device: u32) -> Option<u64> {
use windows_registry::LOCAL_MACHINE;
let class = LOCAL_MACHINE.open(r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}").ok()?;
let entries: Vec<(String, u64)> = class
.keys()
.ok()?
.filter_map(|name| {
let key = class.open(&name).ok()?;
Some((key.get_string("MatchingDeviceId").ok()?, key.get_u64("HardwareInformation.qwMemorySize").ok()?))
})
.collect();
vram_from_entries(&entries, vendor, device)
}
/// The smallest nonzero memory among `(MatchingDeviceId, bytes)` entries of the PCI device
/// `vendor`:`device` (ids look like `pci\ven_10de&dev_2b85&subsys_...`).
#[cfg_attr(not(any(windows, test)), allow(dead_code))]
fn vram_from_entries(entries: &[(String, u64)], vendor: u32, device: u32) -> Option<u64> {
let want = format!("ven_{vendor:04x}&dev_{device:04x}");
entries.iter().filter(|(id, bytes)| *bytes > 0 && id.to_ascii_lowercase().contains(&want)).map(|&(_, b)| b).min()
}
/// `mem_info_vram_total` (amdgpu) of the DRM card under `drm` whose PCI vendor and device ids are
/// `vendor` and `device`. Connector entries (`card1-DP-1`) are skipped. Variants of one model share
/// those ids (the RX 550 ships with 2 and 4 GB), so the card at PCI address `bus` (`uevent`'s
/// `PCI_SLOT_NAME`, wgpu's `device_pci_bus_id`) wins; without one, the smallest matching card.
#[cfg_attr(not(any(target_os = "linux", test)), allow(dead_code))]
fn vram_in_sysfs(drm: &Path, vendor: u32, device: u32, bus: &str) -> Option<u64> {
let id = |path: &Path| std::fs::read_to_string(path).ok().and_then(|s| u32::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok());
let slot = |dev: &Path| {
@@ -314,6 +417,60 @@ mod tests {
assert_eq!(cap_from_env(Some("4096"), d, Some(2 * GIB)), 4 * GIB, "the override still wins");
}
#[test]
fn video_memory_is_matched_by_pci_ids_in_registry_entries() {
let e = |id: &str, gb: u64| (id.to_string(), gb * GIB);
let entries = [e(r"PCI\VEN_10DE&DEV_2B85&SUBSYS_1", 32), e(r"PCI\VEN_8086&DEV_46A6&SUBSYS_2", 0), e(r"PCI\VEN_10DE&DEV_2204", 24)];
assert_eq!(vram_from_entries(&entries, 0x10de, 0x2b85), Some(32 * GIB));
assert_eq!(vram_from_entries(&entries, 0x8086, 0x46a6), None, "a zero size is not known");
assert_eq!(vram_from_entries(&entries, 0x1002, 0x73bf), None);
let twins = [e(r"PCI\VEN_1002&DEV_699F", 4), e(r"PCI\VEN_1002&DEV_699F&SUBSYS_9", 2)];
assert_eq!(vram_from_entries(&twins, 0x1002, 0x699f), Some(2 * GIB), "the smaller variant");
}
/// #3731: the upload budget follows the card (3/8 of its memory), the environment overrides
/// it, and the default cap leaves room for it.
#[test]
fn upload_budget_follows_the_card_and_the_cap_leaves_room() {
let d = wgpu::DeviceType::DiscreteGpu;
assert_eq!(upload_budget(None, None), 3 * GIB / 2, "unknown memory: the former fixed budget");
assert_eq!(upload_budget(None, Some(4 * GIB)), 3 * GIB / 2);
assert_eq!(upload_budget(None, Some(32 * GIB)), 12 * GIB);
assert_eq!(upload_budget(None, Some(2 * GIB)), 768 * MIB);
assert_eq!(upload_budget(Some("24000"), Some(2 * GIB)), 24000 * MIB, "the override wins");
assert_eq!(upload_budget(Some("0"), Some(32 * GIB)), 12 * GIB, "0 is the default");
for bad in ["", "lots", "-1", "99999999999999999999"] {
assert_eq!(upload_budget(Some(bad), None), 3 * GIB / 2, "{bad:?}");
}
// The cap grows with the budget, never above three quarters of a known card.
assert_eq!(default_cap_for(d, None, 3 * GIB / 2), 3 * GIB);
assert_eq!(default_cap_for(d, Some(32 * GIB), 12 * GIB), 3 * GIB + 21 * GIB / 2);
assert_eq!(default_cap_for(d, Some(32 * GIB), 40 * GIB), 24 * GIB);
assert_eq!(default_cap_for(d, Some(2 * GIB), 768 * MIB), 3 * GIB / 2);
assert_eq!(default_cap_for(wgpu::DeviceType::IntegratedGpu, None, 3 * GIB / 2), 2 * GIB);
// A card of any size: the default budget and cap leave a quarter of the memory free.
for gb in [4, 6, 8, 12, 16, 24, 32] {
let v = gb * GIB;
assert!(default_cap_for(d, Some(v), upload_budget(None, Some(v))) <= v / 4 * 3, "{gb} GB");
}
// An explicit cap is not changed by the budget; the context takes both.
let m = MemCap::from_envs(Some("4096"), Some("9000"), d, Some(32 * GIB));
assert_eq!((m.cap(), m.upload_budget()), (4 * GIB, 9000 * MIB as usize));
// A default budget is lowered to half an explicit cap (not below 1.5 GiB), an explicit one
// is kept, and a cap of 0 (gate off) changes nothing.
let m = MemCap::from_envs(Some("8192"), None, d, Some(32 * GIB));
assert_eq!((m.cap(), m.upload_budget()), (8 * GIB, 4 * GIB as usize));
let m = MemCap::from_envs(Some("4096"), None, d, Some(32 * GIB));
assert_eq!((m.cap(), m.upload_budget()), (4 * GIB, 2 * GIB as usize));
let m = MemCap::from_envs(Some("8"), None, d, Some(32 * GIB));
assert_eq!((m.cap(), m.upload_budget()), (8 * MIB, 3 * GIB as usize / 2));
let m = MemCap::from_envs(Some("0"), None, d, Some(32 * GIB));
assert_eq!((m.cap(), m.upload_budget()), (0, 12 * GIB as usize));
let m = MemCap::from_envs(None, Some("9000"), d, Some(32 * GIB));
assert_eq!((m.cap(), m.upload_budget()), (3 * GIB + 9000 * MIB - 3 * GIB / 2, 9000 * MIB as usize));
assert_eq!(MemCap::from_env(None, d, None).upload_budget(), 3 * GIB as usize / 2);
}
#[test]
fn video_memory_is_read_from_the_matching_drm_card() {
let dir = std::env::temp_dir().join(format!("effectcraft-memcap-{}", std::process::id()));
+49
View File
@@ -1486,6 +1486,55 @@ fn upload_budget_bounds_the_layer_textures_kept() {
assert!(a == b && b == c, "the upload budget changed the frame");
}
/// #3731: layers of footage at 8 bpc (a layer buffer each, uploaded through the upload cache)
/// upload once while they fit the budget and again every frame when they do not. The budget comes
/// from the memory rule, so a child process sets `EFFECTCRAFT_GPU_UPLOAD_MB=1` (smaller than the
/// layers) and must see the uploads repeat, the default must not. (At 32 bpc the layers share
/// the footage picture, which the budget does not bound.)
#[test]
fn upload_budget_comes_from_the_memory_rule() {
const ENV: &str = "EFFECTCRAFT_GPU_UPLOAD_TEST_CHILD";
let tight = std::env::var_os(ENV).is_some();
if !tight && std::env::var_os("EFFECTCRAFT_GPU_UPLOAD_MB").is_some() {
return; // the caller set a budget of their own
}
if !tight {
let exe = std::env::current_exe().expect("test binary path");
let out = std::process::Command::new(exe)
.env(ENV, "1")
.env("EFFECTCRAFT_GPU_UPLOAD_MB", "1")
.args(["--exact", "tests::upload_budget_comes_from_the_memory_rule", "--nocapture"])
.output()
.expect("spawn child test process");
assert!(out.status.success(), "child test failed:\n{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
}
let Some(g) = gpu() else { return };
let mut s = Scene::new(BitDepth::Bpc8);
for i in 0..3 {
let mut l = s.footage(600, 400); // 3.8 MB as RGBA f32 each
set(&mut l, "transform/position", v3(30.0 + 10.0 * i as f64, 30.0));
s.push(l);
}
let cache = effectcraft_render::cache::LayerCache::new(256 << 20);
let frame = |k: u64| {
let mut r = Renderer::new(&s.p, &Pattern, RenderOpts { backend: Backend::Gpu, ..opts() });
r.accel = Some(g);
r.cache = Some(&cache);
let before = g.ctx.transfer_stats().upload_bytes;
g.render(&r, s.cid, Tick::from_seconds_f64(k as f64 / 30.0)).expect("the GPU renders the frame");
g.ctx.transfer_stats().upload_bytes - before
};
let _ = frame(0);
let up = frame(1);
if tight {
assert_eq!(g.ctx.upload_budget(), 1 << 20, "EFFECTCRAFT_GPU_UPLOAD_MB=1");
assert!(up > 0, "layers over the budget must upload again");
} else {
assert_eq!(g.ctx.upload_budget(), g.ctx.upload_budget_from_rule());
assert_eq!(up, 0, "layers within the budget re-uploaded");
}
}
/// Layers with effect stacks run them resident on the GPU (`walk::draw_resident_fx`): GPU
/// effects, a CPU-only effect in the middle (read back, run, upload), opacity and a blend mode,
/// a shape layer whose effects run in effect space from its bounds' corner; 8 and 32 bpc, full
+4 -1
View File
@@ -97,7 +97,10 @@ Commands (CLI, MCP, control channel):
frames the Render Queue renders on the GPU at once. Auto measures the GPU memory after the
job's first GPU frame and fits up to 3 frames into the GPU memory cap (by default a
conservative 3 GiB on a discrete card, less when its memory is known, 2 GiB on an integrated
one; `EFFECTCRAFT_GPU_MEMCAP_MB` sets it), keeping room for the upload cache to fill. It
one; `EFFECTCRAFT_GPU_MEMCAP_MB` sets it), keeping room for the upload cache to fill (the
textures of uploaded layers: 1.5 GiB, or three eighths of the card's memory where the OS
reports it, on Linux with amdgpu and on Windows; the default cap grows with it, never above
three quarters of the card; `EFFECTCRAFT_GPU_UPLOAD_MB` sets it in whole MiB, 0 = default). It
renders one frame at a time where the memory can't be measured (Metal, WebGPU, GL, or the
cap turned off) and once frames have had to wait for memory. The render log names the count.
`EFFECTCRAFT_GPU_INFLIGHT` overrides it. CPU renders have no such setting. A job on GPU