Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions crates/victory-gpu/src/pipeline/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -600,9 +600,16 @@ impl HostPipeline {
return None;
}
};
// Not from the library if it has static samplers (their places in the
// driver's table differ between runs: `library::with_static_samplers`).
let _samplers = super::library::with_static_samplers(!samplers.is_empty());
// Not from the library if it has static samplers whose places in the
// driver's table may differ between runs; those `samplers::prime` made
// hold theirs (`library::with_static_samplers`).
let places = if samplers.is_empty() {
None
} else {
let all: Vec<_> = stages.iter().filter_map(|(s, _)| s.translated()).flat_map(|t| t.host.static_samplers.iter().copied()).collect();
super::samplers::primed_places(&all)
};
let _samplers = super::library::with_static_samplers(!samplers.is_empty(), places.as_deref());
let code = |i: usize| {
stages.get(i).and_then(|(s, _)| s.translated()).map_or(
D3D12_SHADER_BYTECODE::default(),
Expand Down
114 changes: 97 additions & 17 deletions crates/victory-gpu/src/pipeline/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,11 +258,17 @@ thread_local! {
/// Whether the pipeline this thread makes has static samplers
/// ([`with_static_samplers`]).
static STATIC_SAMPLERS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// The places of the static samplers of the pipeline this thread makes,
/// where it may go into the library with them: part of its [`name`].
static PLACES: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) };
}

/// The pipelines this thread makes while the guard lives have static
/// samplers (`samplers`): they are made, never loaded from or stored in the
/// library, unless `VICTORY_LIBRARY_STATIC_SAMPLERS=1`.
/// library, unless their samplers hold the same places in every process
/// (`places`: those of `samplers::prime`, see `samplers::primed_places`),
/// or `VICTORY_LIBRARY_STATIC_SAMPLERS=1` keeps them all.
/// `VICTORY_LIBRARY_STATIC_SAMPLERS=0`: none of them, as before 2026-11-28.
///
/// Why: the card's driver (NVIDIA, 4070 SUPER) keeps static samplers in a
/// table of its own and puts their places in that table into the compiled
Expand All @@ -279,30 +285,43 @@ thread_local! {
/// run, the image was smooth). Every loaded pipeline with static samplers
/// may read through another one's: other filters, address modes, levels
/// and comparisons.
/// shortcut: they are compiled every run (the driver's own cache on disk
/// makes that quick); a fixed order of static samplers made before any
/// pipeline would let the library keep them again.
pub(crate) fn with_static_samplers(samplers: bool) -> StaticSamplers {
StaticSamplers(STATIC_SAMPLERS.replace(samplers && !static_samplers_kept()))
/// shortcut: they are compiled every run, and the driver's cache on disk does
/// not always find them (an RTX 3060, driver 621.40: about 1,100 of them at
/// 2.2 s each, median, 4.5 minutes at 3.5 fps after every start). With the
/// samplers made first in one order (`samplers`), a sampler's place is its
/// line in the list in every process: loaded from the library, such a
/// pipeline reads through the samplers it was made with (`lut3d_probe`:
/// stored and loaded with the same ten samplers made first, every sample
/// filtered). Its places are in its name, so a list made again in another
/// order finds none of the pipelines stored before.
pub(crate) fn with_static_samplers(samplers: bool, places: Option<&[u32]>) -> StaticSamplers {
let kept = samplers && static_samplers_kept().unwrap_or(places.is_some());
let text = match places.filter(|_| kept) {
Some(places) => format!("static samplers at {places:?}"),
None => String::new(),
};
StaticSamplers(STATIC_SAMPLERS.replace(samplers && !kept), PLACES.replace(text))
}

/// While it lives, the pipelines this thread makes skip the library if they
/// have static samplers ([`with_static_samplers`]); the setting before it
/// comes back when it is dropped.
pub(crate) struct StaticSamplers(bool);
/// have static samplers that may not go there ([`with_static_samplers`]);
/// the settings before it come back when it is dropped.
pub(crate) struct StaticSamplers(bool, String);

impl Drop for StaticSamplers {
fn drop(&mut self) {
STATIC_SAMPLERS.set(self.0);
PLACES.replace(std::mem::take(&mut self.1));
}
}

/// `VICTORY_LIBRARY_STATIC_SAMPLERS=1`: pipelines with static samplers are
/// loaded from and stored in the library too, as before.
fn static_samplers_kept() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
/// `VICTORY_LIBRARY_STATIC_SAMPLERS`: `1`, every pipeline with static
/// samplers is loaded from and stored in the library (as before 2026-11-26);
/// `0`, none is; unset (`None`), those whose samplers were primed are.
fn static_samplers_kept() -> Option<bool> {
static ON: OnceLock<Option<bool>> = OnceLock::new();
*ON.get_or_init(|| {
std::env::var_os("VICTORY_LIBRARY_STATIC_SAMPLERS").is_some_and(|v| v == "1")
std::env::var("VICTORY_LIBRARY_STATIC_SAMPLERS").ok().map(|v| v.trim() == "1")
})
}

Expand Down Expand Up @@ -577,6 +596,15 @@ pub(crate) fn name(kind: &str, root: &[u8], code: &[&[u8]], state: &str) -> Stri
h.update(&(part.len() as u64).to_le_bytes());
h.update(part);
}
// The static samplers' places, where the pipeline may be kept with them
// (nothing is added for the others: their names are as they were).
PLACES.with(|p| {
let p = p.borrow();
if !p.is_empty() {
h.update(&(p.len() as u64).to_le_bytes());
h.update(p.as_bytes());
}
});
h.finalize().to_hex()[..32].to_owned()
}

Expand Down Expand Up @@ -794,9 +822,19 @@ pub(crate) fn slow(key: &str) -> bool {
slow_ones().as_ref().is_some_and(|s| s.contains_key(key))
}

/// The title pipeline with `key` took `ms` to make.
/// The title pipeline with `key` took `ms` to make. One listed as slow that
/// came quickly this time (loaded from the library, or found by the driver's
/// cache) leaves the list: listed, it would wait behind the quarter of the
/// workers that slow ones may have (`make::slow_limit`) at every start. With
/// the pipelines of static samplers in the library, 651 listed ones (median
/// 2.2 s when made) loaded two at a time kept the world's first minute at
/// 12-20 fps; taken in the title's order, the queue was empty 17 s after the
/// world's first frame (RTX 3060).
pub(crate) fn note_time(key: &str, ms: u64) {
if ms < SLOW_MS {
if slow_ones().as_mut().and_then(|s| s.remove(key)).is_some() {
USED_CHANGED.store(true, Ordering::Relaxed);
}
return;
}
let mut slow = slow_ones();
Expand Down Expand Up @@ -870,7 +908,7 @@ mod tests {
fn pipelines_with_static_samplers_skip_the_library() {
let looked = std::cell::Cell::new(false);
{
let _guard = with_static_samplers(true);
let _guard = with_static_samplers(true, None);
let made = pipeline(
"with static samplers",
|_, _| {
Expand All @@ -882,14 +920,56 @@ mod tests {
assert!(made.is_err());
assert!(!looked.get(), "the library was asked");
{
let _inner = with_static_samplers(false);
let _inner = with_static_samplers(false, None);
assert!(!STATIC_SAMPLERS.get());
}
assert!(STATIC_SAMPLERS.get());
}
assert!(!STATIC_SAMPLERS.get());
}

/// A pipeline that took long is listed as slow, and leaves the list when it
/// comes quickly (loaded from the library); a quick one is never listed.
#[test]
fn a_slow_pipeline_that_comes_quickly_leaves_the_slow_list() {
let key = "a slow pipeline that comes quickly (test)";
note_time(key, 10);
assert!(!slow(key));
note_time(key, SLOW_MS + 1200);
assert!(slow(key));
note_time(key, SLOW_MS);
assert!(slow(key), "as long as the limit: still slow");
note_time(key, 3);
assert!(!slow(key));
}

/// Static samplers in their primed places: the pipeline may use the library
/// (unless `VICTORY_LIBRARY_STATIC_SAMPLERS=0`), under a name that holds the
/// places; without samplers, or once the guard is gone, names are as before.
#[test]
fn primed_static_samplers_keep_the_library_under_their_places() {
if static_samplers_kept().is_some() {
return; // set from outside: not the default this checks
}
let plain = name("graphics", b"root", &[b"vs", b"ps"], "state");
{
let _guard = with_static_samplers(true, Some(&[0, 3]));
assert!(!STATIC_SAMPLERS.get(), "skips the library");
let at = name("graphics", b"root", &[b"vs", b"ps"], "state");
assert_ne!(at, plain);
{
let _other = with_static_samplers(true, Some(&[1, 3]));
assert_ne!(name("graphics", b"root", &[b"vs", b"ps"], "state"), at, "other places, another name");
}
assert_eq!(name("graphics", b"root", &[b"vs", b"ps"], "state"), at);
{
let _none = with_static_samplers(false, None);
assert_eq!(name("graphics", b"root", &[b"vs", b"ps"], "state"), plain);
}
}
assert_eq!(name("graphics", b"root", &[b"vs", b"ps"], "state"), plain);
}

#[test]
fn a_rejected_blob_gives_an_empty_library() {
let Some(device) = crate::host::host().and_then(|h| h.device.cast::<ID3D12Device1>().ok()) else {
Expand Down
40 changes: 35 additions & 5 deletions crates/victory-gpu/src/pipeline/samplers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@
//! has 28 in all (the driver's table holds 2,032).
//!
//! `VICTORY_SAMPLER_ORDER=0`: in the order each process makes them, as before.
//!
//! The samplers made by [`prime`] hold the same places in every process: the
//! first ones the driver is given, in the list's order. A pipeline whose
//! samplers are all among them has the same places wherever it is made or
//! loaded, so the pipeline library may keep it ([`primed_places`]). Those met
//! later in a run may come after other static samplers of the layer's own
//! (the composite's, the tiles') and are made in every run until a start
//! primes them.
use std::collections::HashSet;
use std::io::{Read, Seek, SeekFrom, Write};
Expand Down Expand Up @@ -64,6 +72,10 @@ unsafe impl Send for Made {}

static MADE: Mutex<Option<Made>> = Mutex::new(None);

/// The samplers [`prime`] made and their places in the driver's table (the
/// order they were made in), set once.
static PRIMED: OnceLock<std::collections::HashMap<Words, u32>> = OnceLock::new();

fn on() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_SAMPLER_ORDER").is_none_or(|v| v != "0"))
Expand Down Expand Up @@ -93,11 +105,25 @@ pub(crate) fn order() -> Vec<u8> {
/// made, before anything else has a static sampler.
pub(crate) fn prime(device: &ID3D12Device) {
if on() {
let made = sync(device, &[]);
let (made, new) = sync(device, &[]);
let places = new.into_iter().zip(0u32..).collect();
let _ = PRIMED.set(places);
tracing::info!(samplers = made, "static samplers made in the order of the cache's list");
}
}

/// The places of `samplers` in the driver's table where [`prime`] made them
/// all, else `None` (the order off, not primed, or one met only in this run).
pub(crate) fn primed_places(samplers: &[StaticSampler]) -> Option<Vec<u32>> {
if !on() {
return None;
}
let primed = PRIMED.get()?;
let host = crate::host::host_made()?;
let supported = aniso_point_mip(&host.device);
samplers.iter().map(|s| primed.get(&words(s, supported)).copied()).collect()
}

/// A shader with these static samplers is about to get a pipeline, or was
/// translated: those not yet in the list are added to it and made.
pub(crate) fn know(samplers: &[StaticSampler]) {
Expand Down Expand Up @@ -189,8 +215,8 @@ fn open_alone() -> Option<std::fs::File> {

/// Makes what the list holds and this process has not made yet, in the
/// list's order, then `mine` where new (added to the list). How many this
/// process has made in all.
fn sync(device: &ID3D12Device, mine: &[Words]) -> usize {
/// process has made in all, and those of this call the driver took, in order.
fn sync(device: &ID3D12Device, mine: &[Words]) -> (usize, Vec<Words>) {
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
let made = made.get_or_insert_with(|| Made { known: HashSet::new(), kept: Vec::new() });
let mut file = open_alone();
Expand All @@ -212,9 +238,13 @@ fn sync(device: &ID3D12Device, mine: &[Words]) -> usize {
added.push('\n');
}
}
let mut taken = Vec::with_capacity(new.len());
for w in &new {
match root_with(device, w) {
Ok(root) => made.kept.push(root),
Ok(root) => {
made.kept.push(root);
taken.push(*w);
}
Err(e) => tracing::warn!(error = %e, sampler = line(w), "a static sampler of the list was refused"),
}
}
Expand All @@ -231,7 +261,7 @@ fn sync(device: &ID3D12Device, mine: &[Words]) -> usize {
drop(file);
let mut seen = SEEN.write().unwrap_or_else(|e| e.into_inner());
seen.get_or_insert_default().extend(new);
made.known.len()
(made.known.len(), taken)
}

/// A root signature with the one static sampler `w`.
Expand Down