Initial
This commit is contained in:
1 parent
2cff35f215
commit
49e10bb398
357 files changed
+253936
-74
No files matched your search
@@ -0,0 +1,489 @@
|
||||
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use crate::hle::known_pipelines as known;
|
||||
|
||||
const AT_ONCE: usize = 40;
|
||||
|
||||
const LONGEST: Duration = Duration::from_secs(180);
|
||||
|
||||
const SLOW_MS: f64 = 1000.0;
|
||||
|
||||
fn folder() -> Result<PathBuf> {
|
||||
let cfg = eonacat_xsbox_gpu::core::Config::load()?;
|
||||
Ok(cfg.cache_subdir("shaders")?.with_file_name("pipelines"))
|
||||
}
|
||||
|
||||
fn fingerprint() -> (String, String) {
|
||||
let card = eonacat_xsbox_gpu::shader::emit::host::hardware_adapter().map(|(_, name, _)| name).unwrap_or_default();
|
||||
let mut h = blake3::Hasher::new();
|
||||
h.update(known::fingerprint().as_bytes());
|
||||
h.update(program().as_bytes());
|
||||
h.update(card.as_bytes());
|
||||
(h.finalize().to_hex()[..16].to_owned(), card)
|
||||
}
|
||||
|
||||
fn program() -> String {
|
||||
std::env::current_exe().map(|p| p.to_string_lossy().to_lowercase()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn done_names<'a>(text: &'a str, marks: &str) -> HashSet<&'a str> {
|
||||
text.lines().filter_map(|line| line.split_once(' ').filter(|(of, _)| *of == marks).map(|(_, name)| name)).collect()
|
||||
}
|
||||
|
||||
fn to_make(candidates: &[usize], names: &[Option<String>], done: &HashSet<&str>, again: bool) -> (Vec<usize>, usize, usize) {
|
||||
let (mut seen, mut all, mut reused, mut twins) = (HashSet::new(), Vec::new(), 0, 0);
|
||||
for (&n, name) in candidates.iter().zip(names) {
|
||||
match name {
|
||||
Some(name) if !again && done.contains(name.as_str()) => reused += 1,
|
||||
Some(name) if !seen.insert(name.as_str()) => twins += 1,
|
||||
_ => all.push(n),
|
||||
}
|
||||
}
|
||||
(all, reused, twins)
|
||||
}
|
||||
|
||||
fn bad_keys<'a>(text: &'a str, fingerprint: &str) -> HashSet<&'a str> {
|
||||
let hex = |word: &str, len| word.len() == len && word.bytes().all(|b| b.is_ascii_hexdigit());
|
||||
text.lines()
|
||||
.filter_map(|line| {
|
||||
let mut words = line.split_whitespace();
|
||||
let first = words.next()?;
|
||||
let second = words.next();
|
||||
let (key, recorded) = match second {
|
||||
Some(key) if hex(first, 16) && hex(key, 32) => (key, Some(first)),
|
||||
_ => (first, second.and_then(|word| word.strip_prefix("fp=")).filter(|fp| hex(fp, 16))),
|
||||
};
|
||||
(hex(key, 32) && recorded.is_none_or(|fp| fp.eq_ignore_ascii_case(fingerprint))).then_some(key)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
const USED_LIST_MIN: usize = 1000;
|
||||
|
||||
const ROUNDS: usize = 5;
|
||||
|
||||
fn used_list_min() -> usize {
|
||||
std::env::var("EONACAT_XS_PRELOAD_USED_MIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(USED_LIST_MIN)
|
||||
}
|
||||
|
||||
fn used_list_has_pipelines(list: &str, at_least: usize) -> bool {
|
||||
list.lines().filter(|line| !line.trim().is_empty()).take(at_least.max(1)).count() >= at_least.max(1)
|
||||
}
|
||||
|
||||
pub fn used_pipelines_recorded() -> Result<bool> {
|
||||
let file = folder()?.join("early-pipelines.txt");
|
||||
match std::fs::read_to_string(&file) {
|
||||
Ok(list) => Ok(used_list_has_pipelines(&list, used_list_min())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
|
||||
Err(e) => Err(e).with_context(|| format!("reading {}", file.display())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(jobs: Option<usize>, limit: Option<usize>, again: bool, used: bool, these: Option<String>) -> Result<()> {
|
||||
let dir = folder()?;
|
||||
if let Some(these) = these {
|
||||
return make(&dir, &these);
|
||||
}
|
||||
let began = Instant::now();
|
||||
|
||||
std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
|
||||
crate::hle::known_pipelines::use_translations(dir.with_file_name("shaders"));
|
||||
|
||||
let shared = shared_on() && used;
|
||||
|
||||
let (fingerprint, card) = fingerprint();
|
||||
|
||||
let marks = mark_fingerprint(&known::made_for(), &program(), &card, shared);
|
||||
if shared_on() && !used {
|
||||
println!("EONACAT_XS_WARM_SHARED applies to `warm --used` only: this warm keeps the driver's cache, as before");
|
||||
}
|
||||
let done_file = dir.join("warm-done.txt");
|
||||
let bad_file = dir.join("warm-bad.txt");
|
||||
let keys = known::keys(&dir);
|
||||
let listed = std::fs::read_to_string(&done_file).unwrap_or_default();
|
||||
|
||||
let library_dir = library_folder(&dir, std::env::var_os("EONACAT_XS_LIBRARY_DIR"));
|
||||
let library_there = !shared || library_dir.join(LIBRARY_FILE).is_file();
|
||||
if !library_there {
|
||||
println!("EONACAT_XS_WARM_SHARED: no {LIBRARY_FILE} in {}, earlier marks do not count", library_dir.display());
|
||||
}
|
||||
let done = if library_there { done_names(&listed, &marks) } else { HashSet::new() };
|
||||
|
||||
let listed_bad = if again || std::env::var_os("EONACAT_XS_WARM_BAD").is_some_and(|v| v == "0") {
|
||||
String::new()
|
||||
} else {
|
||||
std::fs::read_to_string(&bad_file).unwrap_or_default()
|
||||
};
|
||||
let bad = bad_keys(&listed_bad, &fingerprint);
|
||||
let early = std::fs::read_to_string(dir.join("early-pipelines.txt")).unwrap_or_default();
|
||||
let early: HashSet<&str> = early.lines().collect();
|
||||
|
||||
let mut candidates: Vec<usize> = (0..keys.len())
|
||||
.filter(|&n| {
|
||||
let key = keys[n].as_str();
|
||||
!bad.contains(key) && (!used || early.contains(key))
|
||||
})
|
||||
.collect();
|
||||
candidates.sort_by_key(|&n| (!early.contains(keys[n].as_str()), &keys[n]));
|
||||
let jobs = crate::cpu_budget::workers(jobs, Some(candidates.len()));
|
||||
let naming = Instant::now();
|
||||
let names = known::names(&dir, &candidates, jobs);
|
||||
let unnamed = names.iter().filter(|n| n.is_none()).count();
|
||||
let (mut all, reused, twins) = to_make(&candidates, &names, &done, again);
|
||||
all.truncate(limit.unwrap_or(usize::MAX));
|
||||
let names: std::collections::HashMap<usize, String> =
|
||||
candidates.iter().copied().zip(names).filter_map(|(n, name)| Some((n, name?))).collect();
|
||||
println!(
|
||||
"{} pipelines known, {} to warm, named in {:.1} s ({unnamed} have no host pipeline here); \
|
||||
{reused} made before by what is in them ({marks}, on {card}), {twins} the same as another, {} bad; {} to make, {jobs} processes",
|
||||
keys.len(),
|
||||
candidates.len(),
|
||||
naming.elapsed().as_secs_f64(),
|
||||
bad.len(),
|
||||
all.len()
|
||||
);
|
||||
let total = all.len();
|
||||
let state = Mutex::new((Vec::<f64>::new(), 0usize, 0usize));
|
||||
let done_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&done_file)?);
|
||||
|
||||
let made = Mutex::new(Vec::<usize>::new());
|
||||
let slow_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(dir.join("slow-pipelines.txt"))?);
|
||||
let bad_out = Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&bad_file)?);
|
||||
|
||||
let mut todo = all;
|
||||
for round in 1..=ROUNDS {
|
||||
let chunks: Vec<&[usize]> = todo.chunks(AT_ONCE).collect();
|
||||
let next = AtomicUsize::new(0);
|
||||
let answered = Mutex::new(HashSet::<usize>::new());
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..jobs.min(chunks.len()) {
|
||||
s.spawn(|| {
|
||||
while let Some(&chunk) = chunks.get(next.fetch_add(1, Ordering::Relaxed)) {
|
||||
let mut rest = chunk;
|
||||
while !rest.is_empty() {
|
||||
let (made, ended) = child(rest, |n, ms, there| {
|
||||
if ms >= SLOW_MS {
|
||||
let _ = writeln!(lock(&slow_out), "\n{} {ms:.0}", keys[n]);
|
||||
}
|
||||
lock(&answered).insert(n);
|
||||
let mut state = lock(&state);
|
||||
state.0.push(ms);
|
||||
state.1 += usize::from(!there);
|
||||
let count = state.0.len();
|
||||
if count.is_multiple_of(1000) {
|
||||
println!("{count} of {}, {:.0} s", total, began.elapsed().as_secs_f64());
|
||||
}
|
||||
drop(state);
|
||||
|
||||
if there && shared {
|
||||
lock(&made).push(n);
|
||||
} else if there && let Some(name) = names.get(&n) {
|
||||
let _ = writeln!(lock(&done_out), "{marks} {name}");
|
||||
}
|
||||
});
|
||||
rest = &rest[made.min(rest.len())..];
|
||||
match (ended, rest.split_first()) {
|
||||
(Some(why), Some((&n, after))) => {
|
||||
|
||||
println!("pipeline {n} {}: {why}", keys[n]);
|
||||
let _ = writeln!(lock(&bad_out), "{} fp={fingerprint} {why}", keys[n]);
|
||||
lock(&answered).insert(n);
|
||||
lock(&state).2 += 1;
|
||||
rest = after;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
let answered = answered.into_inner().unwrap_or_else(|e| e.into_inner());
|
||||
let before = todo.len();
|
||||
todo.retain(|n| !answered.contains(n));
|
||||
if todo.is_empty() {
|
||||
if round > 1 {
|
||||
println!("every pipeline to make answered after {round} rounds");
|
||||
}
|
||||
break;
|
||||
}
|
||||
if todo.len() == before || round == ROUNDS {
|
||||
println!("{} pipelines were not made (their processes ended early); the next preload tries them again", todo.len());
|
||||
break;
|
||||
}
|
||||
println!("{} pipelines were not made (their processes ended early); making them again, round {} of {ROUNDS}", todo.len(), round + 1);
|
||||
}
|
||||
let (mut times, refused, crashed) = state.into_inner().unwrap_or_else(|e| e.into_inner());
|
||||
times.sort_by(f64::total_cmp);
|
||||
let at = |q: f64| times.get((times.len() as f64 * q) as usize).copied().unwrap_or(0.0);
|
||||
println!(
|
||||
"{} made in {:.0} s ({refused} have no host pipeline, {crashed} ended their process); ms each: median {:.1}, p90 {:.1}, p99 {:.1}, most {:.0}, sum {:.0} s",
|
||||
times.len(),
|
||||
began.elapsed().as_secs_f64(),
|
||||
at(0.5),
|
||||
at(0.9),
|
||||
at(0.99),
|
||||
times.last().copied().unwrap_or(0.0),
|
||||
times.iter().sum::<f64>() / 1e3
|
||||
);
|
||||
|
||||
if shared {
|
||||
let mut made = made.into_inner().unwrap_or_else(|e| e.into_inner());
|
||||
made.sort_unstable();
|
||||
if !made.is_empty() {
|
||||
fill_library(&dir, &names, &marks, &made, &done_out)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const LIBRARY_FILE: &str = "host-pipelines.bin";
|
||||
|
||||
fn library_folder(pipelines: &Path, shared_dir: Option<std::ffi::OsString>) -> PathBuf {
|
||||
match shared_dir {
|
||||
Some(d) if !d.is_empty() => PathBuf::from(d),
|
||||
_ => pipelines.to_path_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
fn shared_on() -> bool {
|
||||
std::env::var_os("EONACAT_XS_WARM_SHARED").is_some_and(|v| v == "1")
|
||||
}
|
||||
|
||||
fn mark_fingerprint(base: &str, program: &str, card: &str, shared: bool) -> String {
|
||||
let mut h = blake3::Hasher::new();
|
||||
h.update(base.as_bytes());
|
||||
if shared {
|
||||
h.update(b"shared-library");
|
||||
} else {
|
||||
h.update(program.as_bytes());
|
||||
}
|
||||
h.update(card.as_bytes());
|
||||
h.finalize().to_hex()[..16].to_owned()
|
||||
}
|
||||
|
||||
fn fill_library(
|
||||
dir: &Path,
|
||||
names: &std::collections::HashMap<usize, String>,
|
||||
marks: &str,
|
||||
made: &[usize],
|
||||
done_out: &Mutex<std::fs::File>,
|
||||
) -> Result<()> {
|
||||
|
||||
const THREADS: usize = 8;
|
||||
|
||||
const SAVE_EVERY: usize = 1000;
|
||||
let began = Instant::now();
|
||||
let cfg = eonacat_xsbox_gpu::core::Config::load()?;
|
||||
known::use_library(cfg.cache_subdir("shaders")?);
|
||||
let threads = std::env::var("EONACAT_XS_WARM_LIBRARY_THREADS")
|
||||
.ok()
|
||||
.and_then(|v| v.trim().parse::<usize>().ok())
|
||||
.unwrap_or(THREADS)
|
||||
.clamp(1, 16);
|
||||
let (count, stored) = (AtomicUsize::new(0), AtomicUsize::new(0));
|
||||
let pending = Mutex::new(Vec::<usize>::new());
|
||||
let flush = || {
|
||||
|
||||
let taken = std::mem::take(&mut *lock(&pending));
|
||||
known::keep_library();
|
||||
let mut out = lock(done_out);
|
||||
for name in taken.iter().filter_map(|n| names.get(n)) {
|
||||
let _ = writeln!(out, "{marks} {name}");
|
||||
}
|
||||
};
|
||||
println!("host pipeline library: making {} pipelines on {threads} threads", made.len());
|
||||
std::thread::scope(|s| -> Result<()> {
|
||||
for t in 0..threads {
|
||||
let these: Vec<usize> = made.iter().copied().skip(t).step_by(threads).collect();
|
||||
let (count, stored, pending, flush) = (&count, &stored, &pending, &flush);
|
||||
spawn_library_worker(s, t, move || {
|
||||
let mut last = None;
|
||||
known::make(dir, &these, |n, came| match came {
|
||||
None => last = Some(n),
|
||||
Some((_, there)) => {
|
||||
if there && last == Some(n) {
|
||||
stored.fetch_add(1, Ordering::Relaxed);
|
||||
lock(pending).push(n);
|
||||
}
|
||||
let c = count.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if c.is_multiple_of(250) {
|
||||
println!("{c} of {} in the library, {:.0} s", made.len(), began.elapsed().as_secs_f64());
|
||||
}
|
||||
if c.is_multiple_of(SAVE_EVERY) {
|
||||
flush();
|
||||
}
|
||||
}
|
||||
});
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
flush();
|
||||
println!(
|
||||
"host pipeline library: {} of {} stored and marked, {:.0} s",
|
||||
stored.load(Ordering::Relaxed),
|
||||
made.len(),
|
||||
began.elapsed().as_secs_f64()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn library_workers(jobs: Option<usize>, pipelines: usize) -> usize {
|
||||
crate::cpu_budget::workers(jobs, Some(pipelines))
|
||||
}
|
||||
|
||||
fn library_worker_name(index: usize) -> String {
|
||||
format!("eonacat-xs-pipelines-warm-{index}")
|
||||
}
|
||||
|
||||
fn spawn_library_worker<'scope, 'env>(
|
||||
scope: &'scope std::thread::Scope<'scope, 'env>,
|
||||
index: usize,
|
||||
work: impl FnOnce() + Send + 'scope,
|
||||
) -> Result<()> {
|
||||
std::thread::Builder::new()
|
||||
.name(library_worker_name(index))
|
||||
.spawn_scoped(scope, work)
|
||||
.with_context(|| format!("spawning pipeline library worker {index}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn into_library(jobs: Option<usize>) -> Result<()> {
|
||||
let dir = folder()?;
|
||||
let cfg = eonacat_xsbox_gpu::core::Config::load()?;
|
||||
known::use_library(cfg.cache_subdir("shaders")?);
|
||||
let keys = known::keys(&dir);
|
||||
let read = |file: &str| std::fs::read_to_string(dir.join(file)).unwrap_or_default();
|
||||
let (bad, early, slow) = (read("warm-bad.txt"), read("early-pipelines.txt"), read("slow-pipelines.txt"));
|
||||
|
||||
let bad = bad_keys(&bad, &fingerprint().0);
|
||||
let early: HashSet<&str> = early.lines().collect();
|
||||
let slow: HashSet<&str> = slow.lines().filter_map(|l| l.split(' ').next()).filter(|k| !k.is_empty()).collect();
|
||||
let mut all: Vec<usize> = (0..keys.len())
|
||||
.filter(|&n| {
|
||||
let key = keys[n].as_str();
|
||||
!bad.contains(key) && (early.contains(key) || slow.contains(key))
|
||||
})
|
||||
.collect();
|
||||
all.sort_by_key(|&n| (!early.contains(keys[n].as_str()), &keys[n]));
|
||||
let threads = library_workers(jobs, all.len());
|
||||
println!("into the pipeline library: {} pipelines (loading and slow ones), {threads} threads", all.len());
|
||||
let began = Instant::now();
|
||||
let (count, made) = (AtomicUsize::new(0), AtomicUsize::new(0));
|
||||
std::thread::scope(|s| -> Result<()> {
|
||||
for t in 0..threads {
|
||||
let these: Vec<usize> = all.iter().copied().skip(t).step_by(threads).collect();
|
||||
let (count, made, total, dir) = (&count, &made, all.len(), &dir);
|
||||
spawn_library_worker(s, t, move || {
|
||||
known::make(dir, &these, |_, came| {
|
||||
let Some((_, there)) = came else { return };
|
||||
made.fetch_add(usize::from(there), Ordering::Relaxed);
|
||||
let n = count.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if n.is_multiple_of(500) {
|
||||
println!("{n} of {total} in the library, {:.0} s", began.elapsed().as_secs_f64());
|
||||
}
|
||||
});
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
known::keep_library();
|
||||
println!(
|
||||
"{} of {} in the pipeline library in {:.0} s",
|
||||
made.load(Ordering::Relaxed),
|
||||
all.len(),
|
||||
began.elapsed().as_secs_f64()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn child(these: &[usize], mut each: impl FnMut(usize, f64, bool)) -> (usize, Option<String>) {
|
||||
let list: Vec<String> = these.iter().map(usize::to_string).collect();
|
||||
let spawned = std::env::current_exe().and_then(|exe| {
|
||||
use std::os::windows::process::CommandExt;
|
||||
const IDLE_PRIORITY_CLASS: u32 = 0x40;
|
||||
Command::new(exe)
|
||||
.args(["warm", "--these", &list.join(",")])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.creation_flags(IDLE_PRIORITY_CLASS)
|
||||
.spawn()
|
||||
});
|
||||
let Ok(mut process) = spawned else { return (these.len(), None) };
|
||||
let Some(out) = process.stdout.take() else { return (these.len(), None) };
|
||||
let process = Mutex::new(process);
|
||||
let (heard, over) = (Mutex::new(Instant::now()), AtomicBool::new(false));
|
||||
let hung = AtomicBool::new(false);
|
||||
let mut made = 0;
|
||||
std::thread::scope(|s| {
|
||||
s.spawn(|| {
|
||||
while !over.load(Ordering::Relaxed) {
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
if lock(&heard).elapsed() > LONGEST {
|
||||
hung.store(true, Ordering::Relaxed);
|
||||
let _ = lock(&process).kill();
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
for line in BufReader::new(out).lines().map_while(Result::ok) {
|
||||
*lock(&heard) = Instant::now();
|
||||
let mut words = line.split(' ');
|
||||
if words.next() == Some("made")
|
||||
&& let (Some(n), Some(ms), Some(there)) = (words.next(), words.next(), words.next())
|
||||
&& let (Ok(n), Ok(ms)) = (n.parse(), ms.parse())
|
||||
{
|
||||
made += 1;
|
||||
each(n, ms, there == "1");
|
||||
}
|
||||
}
|
||||
over.store(true, Ordering::Relaxed);
|
||||
});
|
||||
let status = lock(&process).wait();
|
||||
let well = status.as_ref().is_ok_and(|s| s.success());
|
||||
if well {
|
||||
return (these.len(), None);
|
||||
}
|
||||
let why = if hung.load(Ordering::Relaxed) {
|
||||
format!("hung for {} s", LONGEST.as_secs())
|
||||
} else {
|
||||
status.map_or_else(|e| e.to_string(), |s| format!("{s}"))
|
||||
};
|
||||
(made, Some(why))
|
||||
}
|
||||
|
||||
fn make(dir: &Path, these: &str) -> Result<()> {
|
||||
let these: Vec<usize> = these.split(',').map(|n| n.parse().context("--these")).collect::<Result<_>>()?;
|
||||
let cfg = eonacat_xsbox_gpu::core::Config::load()?;
|
||||
crate::hle::known_pipelines::use_translations(cfg.cache_subdir("shaders")?);
|
||||
let mut out = std::io::stdout();
|
||||
known::make(dir, &these, |n, came| {
|
||||
let told = match came {
|
||||
None => writeln!(out, "at {n}"),
|
||||
Some((ms, there)) => writeln!(out, "made {n} {ms:.2} {}", u8::from(there)),
|
||||
};
|
||||
if told.and_then(|()| out.flush()).is_err() {
|
||||
|
||||
std::process::exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
let _ = out.flush();
|
||||
std::process::exit(0)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user