Skip to content
Closed
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
12 changes: 10 additions & 2 deletions apps/victory/src/translate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -568,8 +568,16 @@ fn translate(
if let (Some(r), Some(i), Some(s)) = (res, raised, structured) {
let label = || format!("{} {:?}", example(), p.stage);
*counter(t, p.stage, 0) += 1;
let marks = emit::Options { view_marks: true };
match emit::emit_with(&container, &p, &program, &s, &i, &r, marks) {
let options = emit::Options {
view_marks: true,
wave64: checks
.host
.as_ref()
.map_or(emit::Wave64Mode::Native, |(h, _)| {
h.recommended_wave64_mode()
}),
};
match emit::emit_with(&container, &p, &program, &s, &i, &r, options) {
Ok(shader) => {
*counter(t, p.stage, 1) += 1;
check(shader, t, checks, label);
Expand Down
26 changes: 26 additions & 0 deletions crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,9 @@ fn create() -> windows::core::Result<Host> {
),
Err(e) => tracing::debug!(error = %e, "multiply-add fusing not checked"),
}
let wave64_mode = recommended_wave64_mode(&device);
crate::shader_cache::set_wave64_mode(wave64_mode);
tracing::info!(?wave64_mode, "Wave64 compute lowering mode selected");
Ok(Host {
device,
queue,
Expand All @@ -258,6 +261,29 @@ fn create() -> windows::core::Result<Host> {
}
}

/// Queries D3D12 wave lane capabilities and chooses the Wave64 lowering mode.
fn recommended_wave64_mode(device: &ID3D12Device) -> victory_shader::emit::Wave64Mode {
use victory_shader::emit::Wave64Mode;
let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
// SAFETY: plain D3D12 feature query with valid struct size.
let ok = unsafe {
device.CheckFeatureSupport(
D3D12_FEATURE_D3D12_OPTIONS1,
(&raw mut opts).cast(),
size_of_val(&opts) as u32,
)
}
.is_ok();
if !ok || !opts.WaveOps.as_bool() {
return Wave64Mode::Emulate;
}
if opts.WaveLaneCountMin <= 64 && opts.WaveLaneCountMax >= 64 {
Wave64Mode::Native
} else {
Wave64Mode::Emulate
}
}

/// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
/// Reject it before creating a device in diagnostics' software-only mode.
fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
Expand Down
121 changes: 101 additions & 20 deletions crates/victory-gpu/src/shader_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,47 @@

use std::path::PathBuf;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};

use victory_pipeline::{Cache, Converter};
use victory_shader::emit::{HostShader, StaticSampler, UserData};
use victory_shader::emit::{HostShader, StaticSampler, UserData, Wave64Mode};
use victory_shader::{HwStage, RootType};

static CACHE: OnceLock<Cache> = OnceLock::new();
static HITS: AtomicU64 = AtomicU64::new(0);
static MISSES: AtomicU64 = AtomicU64::new(0);
static WAVE64_MODE: AtomicU8 = AtomicU8::new(0);

fn mode_byte(mode: Wave64Mode) -> u8 {
match mode {
Wave64Mode::Native => 0,
Wave64Mode::Wave32 => 1,
Wave64Mode::Emulate => 2,
}
}

/// Records the host device's preferred Wave64 compute lowering strategy.
#[cfg(windows)]
pub(crate) fn set_wave64_mode(mode: Wave64Mode) {
WAVE64_MODE.store(mode_byte(mode), Ordering::Relaxed);
}

fn effective_wave64_mode() -> Wave64Mode {
if let Ok(v) = std::env::var("VICTORY_WAVE64_EMULATE") {
match v.trim().to_ascii_lowercase().as_str() {
"0" | "native" => return Wave64Mode::Native,
"wave32" | "32" => return Wave64Mode::Wave32,
"1" | "emulate" | "force" => return Wave64Mode::Emulate,
"" | "auto" => {}
other => tracing::warn!(value = other, "unknown VICTORY_WAVE64_EMULATE; using auto"),
}
}
match WAVE64_MODE.load(Ordering::Relaxed) {
1 => Wave64Mode::Wave32,
2 => Wave64Mode::Emulate,
_ => Wave64Mode::Native,
}
}

/// Keeps translated shaders in a folder of `dir` from now on: the folder
/// of this translator, `None` if it cannot be opened.
Expand Down Expand Up @@ -84,16 +116,45 @@ fn key(translator: &str, encoding: &[u8], limit: u32) -> [u8; 32] {
pub fn host_shader(container: &[u8]) -> (Result<HostShader, String>, bool) {
// Writes through views mark their pages: copy-backs compare only those
// (`crate::shadow::copy_back_marks`).
let options = victory_shader::emit::Options { view_marks: true };
let translate = |c: &[u8]| victory_shader::emit::translate_with(c, options).map_err(|e| e.to_string());
let wave64 = effective_wave64_mode();
let translate = |c: &[u8]| {
let mut first = None;
for &wave64 in lowerings(wave64) {
let options = victory_shader::emit::Options {
view_marks: true,
wave64,
};
match victory_shader::emit::translate_with(c, options) {
Ok(shader) => return Ok(shader),
Err(e) => {
first.get_or_insert(e.to_string());
}
}
}
Err(first.unwrap_or_default())
};
match CACHE.get() {
Some(cache) => cached(cache, build(), container, translate),
Some(cache) => cached(cache, build(), wave64, container, translate),
None => (translate(container), false),
}
}

/// The cache entry's converter: the build and the container in, the
/// encoded translation (or refusal) out. `ran` tells a miss from a hit.
/// The lowerings a translation tries in turn when `mode` is asked for. The
/// two 64-lane emulations refuse different programs (Wave32 one with a
/// cross-lane operation in divergent control flow, Emulate one with a
/// `v_readfirstlane` there), so a program one refuses tries the other, then
/// the native lowering, whose `WaveSize(64)` a 32-lane host may still refuse
/// when it makes the pipeline. The refusal kept is the one of `mode`.
fn lowerings(mode: Wave64Mode) -> &'static [Wave64Mode] {
match mode {
Wave64Mode::Native => &[Wave64Mode::Native],
Wave64Mode::Wave32 => &[Wave64Mode::Wave32, Wave64Mode::Emulate, Wave64Mode::Native],
Wave64Mode::Emulate => &[Wave64Mode::Emulate, Wave64Mode::Wave32, Wave64Mode::Native],
}
}

/// The cache entry's converter: the build, the lowering mode and the
/// container in, the encoded translation (or refusal) out. `ran` tells a miss from a hit.
struct Translate<F> {
translate: F,
ran: AtomicBool,
Expand All @@ -109,17 +170,19 @@ impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Tra
}
fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>> {
self.ran.store(true, Ordering::Relaxed);
Ok(encode(&(self.translate)(&input[32..])))
Ok(encode(&(self.translate)(&input[33..])))
}
}

fn cached(
cache: &Cache,
build: &[u8; 32],
mode: Wave64Mode,
container: &[u8],
translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync,
) -> (Result<HostShader, String>, bool) {
let input = [&build[..], container].concat();
let mb = [mode_byte(mode)];
let input = [&build[..], &mb[..], container].concat();
let converter = Translate {
translate,
ran: AtomicBool::new(false),
Expand Down Expand Up @@ -387,36 +450,43 @@ mod tests {
Ok(shader())
};
assert_eq!(
cached(&cache, &build, container, translate),
cached(&cache, &build, Wave64Mode::Native, container, translate),
(Ok(shader()), false)
);
assert_eq!(
cached(&cache, &build, container, translate),
cached(&cache, &build, Wave64Mode::Native, container, translate),
(Ok(shader()), true)
);
assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk");

// Another build translates again.
// Another Wave64 mode translates separately.
assert_eq!(
cached(&cache, &[8; 32], container, translate).0,
Ok(shader())
cached(&cache, &build, Wave64Mode::Wave32, container, translate),
(Ok(shader()), false)
);
assert_eq!(runs.load(Ordering::Relaxed), 2);

// Another build translates again.
assert_eq!(
cached(&cache, &[8; 32], Wave64Mode::Native, container, translate),
(Ok(shader()), false)
);
assert_eq!(runs.load(Ordering::Relaxed), 3);

// A damaged entry is a miss, translated and stored again.
for e in walk(dir.path()) {
std::fs::write(e, b"VSH1 broken").unwrap();
}
assert_eq!(
cached(&cache, &build, container, translate),
cached(&cache, &build, Wave64Mode::Native, container, translate),
(Ok(shader()), false)
);
assert_eq!(runs.load(Ordering::Relaxed), 3);
assert_eq!(runs.load(Ordering::Relaxed), 4);
assert_eq!(
cached(&cache, &build, container, translate),
cached(&cache, &build, Wave64Mode::Native, container, translate),
(Ok(shader()), true)
);
assert_eq!(runs.load(Ordering::Relaxed), 3);
assert_eq!(runs.load(Ordering::Relaxed), 4);

// Refusals are stored with their reason, and not tried again.
let fails = AtomicU64::new(0);
Expand All @@ -425,8 +495,11 @@ mod tests {
Err::<HostShader, _>("unsupported".to_owned())
};
let refused = (Err("unsupported".to_owned()), false);
assert_eq!(cached(&cache, &build, b"other", fail), refused);
assert_eq!(cached(&cache, &build, b"other", fail), (refused.0, true));
assert_eq!(cached(&cache, &build, Wave64Mode::Native, b"other", fail), refused);
assert_eq!(
cached(&cache, &build, Wave64Mode::Native, b"other", fail),
(refused.0, true)
);
assert_eq!(fails.load(Ordering::Relaxed), 1);
}

Expand Down Expand Up @@ -479,4 +552,12 @@ mod tests {
assert_eq!(decode(&encode(&refusal)), Some(refusal));
assert_eq!(decode(&[b"VSHE".as_slice(), &[0xff]].concat()), None);
}

#[test]
fn a_lowering_refused_tries_the_other_emulation_then_native() {
use Wave64Mode::{Emulate, Native, Wave32};
assert_eq!(lowerings(Native), [Native]);
assert_eq!(lowerings(Wave32), [Wave32, Emulate, Native]);
assert_eq!(lowerings(Emulate), [Emulate, Wave32, Native]);
}
}
2 changes: 1 addition & 1 deletion crates/victory-shader/src/emit/bvh_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ fn build(wide: bool, memory: bool) -> HostShader {
outputs: Vec::new(),
prims: Vec::new(),
mesh_stride: 0,
view_marks: false,
options: super::Options::default(),
})
.expect("lower");
let shader = HostShader {
Expand Down
Loading