A high-performance inference engine for AI models
More fine grained cache key (#757)
uuuvn45ab1a2a919d
diff --git a/crates/backend-uzu/build/common/caching.rs b/crates/backend-uzu/build/common/caching.rsindex c65dd27d0..fe08d1541 100644--- a/crates/backend-uzu/build/common/caching.rs+++ b/crates/backend-uzu/build/common/caching.rs@@ -1,20 +1,63 @@#![cfg(all(feature = "metal", target_os = "macos"))]-use std::{fs, sync::OnceLock};+use std::{+ fs,+ path::{Path, PathBuf},+ sync::OnceLock,+};use anyhow::Context;+use walkdir::WalkDir;static BUILD_SYSTEM_HASH: OnceLock<blake3::Hash> = OnceLock::new();+fn hash_directory(+ hasher: &mut blake3::Hasher,+ directory: &Path,+) -> anyhow::Result<()> {+ let mut files: Vec<PathBuf> = WalkDir::new(directory)+ .into_iter()+ .collect::<Result<Vec<_>, _>>()+ .with_context(|| format!("cannot walk {}", directory.display()))?+ .into_iter()+ .filter(|entry| entry.file_type().is_file())+ .map(|entry| entry.into_path())+ .collect();+ files.sort();++ for file in files {+ hash_file(hasher, &file)?;+ }++ Ok(())+}++fn hash_file(+ hasher: &mut blake3::Hasher,+ file: &Path,+) -> anyhow::Result<()> {+ hasher.update(file.as_os_str().as_encoded_bytes());+ hasher.update(b"\0");+ hasher.update(&fs::read(file).with_context(|| format!("cannot read {}", file.display()))?);+ hasher.update(b"\0");++ Ok(())+}+pub fn build_system_hash() -> anyhow::Result<&'static blake3::Hash> {if let Some(bsh) = BUILD_SYSTEM_HASH.get() {Ok(bsh)} else {- let bsh = blake3::hash(- &fs::read(&std::env::current_exe().context("cannot get build system executable")?)- .context("cannot read build system executable")?,- );+ let crate_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").context("missing CARGO_MANIFEST_DIR")?);+ let workspace_dir =+ crate_dir.parent().and_then(Path::parent).context("cannot find workspace root from CARGO_MANIFEST_DIR")?;++ let mut hasher = blake3::Hasher::new();+ hash_file(&mut hasher, &workspace_dir.join("Cargo.toml")).context("cannot hash Cargo.toml")?;+ hash_file(&mut hasher, &workspace_dir.join("Cargo.lock")).context("cannot hash Cargo.lock")?;+ hash_file(&mut hasher, &crate_dir.join("Cargo.toml")).context("cannot hash Cargo.toml")?;+ hash_directory(&mut hasher, &crate_dir.join("build")).context("cannot hash build/")?;- Ok(BUILD_SYSTEM_HASH.get_or_init(|| bsh))+ Ok(BUILD_SYSTEM_HASH.get_or_init(|| hasher.finalize()))}}diff --git a/crates/backend-uzu/build/common/gpu_types/mod.rs b/crates/backend-uzu/build/common/gpu_types/mod.rsindex 88c7b08b5..63384d8c8 100644--- a/crates/backend-uzu/build/common/gpu_types/mod.rs+++ b/crates/backend-uzu/build/common/gpu_types/mod.rs@@ -98,6 +98,7 @@ impl GpuTypes {pub fn scan() -> anyhow::Result<Self> {let src_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").context("Missing CARGO_MANIFEST_DIR")?).join("src/backends/common/gpu_types");+ println!("cargo::rerun-if-changed={}", src_dir.display());let mut sources: Vec<PathBuf> = WalkDir::new(&src_dir).into_iter()diff --git a/crates/backend-uzu/build/cpu/compiler.rs b/crates/backend-uzu/build/cpu/compiler.rsindex 24343de5f..34b8e6778 100644--- a/crates/backend-uzu/build/cpu/compiler.rs+++ b/crates/backend-uzu/build/cpu/compiler.rs@@ -127,6 +127,7 @@ impl CpuCompiler {pub fn new() -> anyhow::Result<Self> {let src_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").context("missing CARGO_MANIFEST_DIR")?).join("src/backends/cpu/kernel");+ println!("cargo::rerun-if-changed={}", src_dir.display());let build_dir = PathBuf::from(env::var("OUT_DIR").context("missing OUT_DIR")?).join("cpu");fs::create_dir_all(&build_dir).with_context(|| format!("cannot create {}", build_dir.display()))?;diff --git a/crates/backend-uzu/build/main.rs b/crates/backend-uzu/build/main.rsindex 0f3456948..24474505e 100644--- a/crates/backend-uzu/build/main.rs+++ b/crates/backend-uzu/build/main.rs@@ -13,7 +13,8 @@ mod metal;#[tokio::main(flavor = "current_thread")]async fn main() -> anyhow::Result<ExitCode> {- println!("cargo::rerun-if-changed=.");+ println!("cargo::rerun-if-changed=build");+if envs::build_always() {println!("cargo::rerun-if-changed=/var/empty/hack_nonexistent_file_to_always_rerun");}@@ -63,7 +64,7 @@ async fn main() -> anyhow::Result<ExitCode> {#[cfg(all(feature = "metal", target_os = "macos"))]if backend_metal {- compilers.push(Box::new(metal::MetalCompiler::new()?));+ compilers.push(Box::new(metal::MetalCompiler::new().await?));}if compilers.is_empty() {diff --git a/crates/backend-uzu/build/metal/compiler.rs b/crates/backend-uzu/build/metal/compiler.rsindex e121da175..cad996ede 100644--- a/crates/backend-uzu/build/metal/compiler.rs+++ b/crates/backend-uzu/build/metal/compiler.rs@@ -1,4 +1,8 @@-use std::{collections::HashMap, env, fs, path::PathBuf};+use std::{+ collections::HashMap,+ env, fs,+ path::{Path, PathBuf},+};use anyhow::Context;use async_trait::async_trait;@@ -19,7 +23,7 @@ use crate::{#[derive(Serialize, Deserialize)]struct Cached {- buildsystem_hash: [u8; blake3::OUT_LEN],+ cache_key: [u8; blake3::OUT_LEN],dependency_hashes: HashMap<Box<str>, [u8; blake3::OUT_LEN]>,public_kernels: Box<[Kernel]>,has_kernels: bool,@@ -32,12 +36,14 @@ pub struct MetalCompiler {output_directory: PathBuf,metallib_compressed: bool,toolchain: MetalToolchain,+ cache_key: [u8; blake3::OUT_LEN],}impl MetalCompiler {- pub fn new() -> anyhow::Result<Self> {+ pub async fn new() -> anyhow::Result<Self> {let source_directory = PathBuf::from(env::var("CARGO_MANIFEST_DIR").context("missing CARGO_MANIFEST_DIR")?).join("src/backends/metal/kernel");+ println!("cargo::rerun-if-changed={}", source_directory.display());let gpu_types_directory = source_directory.join("generated");@@ -51,17 +57,39 @@ impl MetalCompiler {};let toolchain = MetalToolchain::from_env_with_include_dir(Some(gpu_types_directory.clone()))+ .await.context("cannot create toolchain")?;+ let cache_key = {+ let build_system_hash = caching::build_system_hash().context("cannot get build system hash")?;++ let mut hasher = blake3::Hasher::new();+ hasher.update(build_system_hash.as_bytes());+ hasher.update(toolchain.cache_key());+ hasher.update(&[u8::from(metallib_compressed)]);++ hasher.finalize().into()+ };+Ok(Self {source_directory,gpu_types_directory,output_directory,metallib_compressed,toolchain,+ cache_key,})}+ fn emit_rerun_if_changed_for_dependency(+ &self,+ path: &str,+ ) {+ if !Path::new(path).starts_with(&self.source_directory) {+ println!("cargo::rerun-if-changed={path}");+ }+ }+async fn compile(&self,source_path: PathBuf,@@ -92,15 +120,16 @@ impl MetalCompiler {let bindgen_file = output_base_path.with_extension("rs");let cached_file = output_base_path.with_extension("cached");- let buildsystem_hash = caching::build_system_hash().context("cannot get build system hash")?.as_bytes();-if let Ok(cached_contents) = fs::read(&cached_file)&& let Ok(cached) = serde_json::from_slice::<Cached>(&cached_contents)- && &cached.buildsystem_hash == buildsystem_hash+ && cached.cache_key == self.cache_key&& cached.dependency_hashes.iter().all(|(path, hash)| {fs::read(path.as_ref()).map(|contents| blake3::hash(&contents).as_bytes() == hash).unwrap_or(false)}){+ for path in cached.dependency_hashes.keys() {+ self.emit_rerun_if_changed_for_dependency(path);+ }debug_log!("compile cached: {source_path_relative_str}");return Ok((kernel_path, cached.public_kernels, cached.has_kernels));}@@ -115,6 +144,7 @@ impl MetalCompiler {let dependency_hashes = dependencies.map(|path| {+ self.emit_rerun_if_changed_for_dependency(&path);Ok((path.clone(),blake3::hash(&fs::read(path.as_ref()).with_context(|| format!("cannot read {path}"))?).into(),@@ -202,7 +232,7 @@ impl MetalCompiler {let has_kernels = !kernel_infos.is_empty();let cached = Cached {- buildsystem_hash: *buildsystem_hash,+ cache_key: self.cache_key,dependency_hashes,public_kernels: public_kernels.clone(),has_kernels,diff --git a/crates/backend-uzu/build/metal/toolchain.rs b/crates/backend-uzu/build/metal/toolchain.rsindex 3b8bfbab5..c135f8208 100644--- a/crates/backend-uzu/build/metal/toolchain.rs+++ b/crates/backend-uzu/build/metal/toolchain.rs@@ -95,10 +95,11 @@ pub struct MetalToolchain {opt_flags: Box<[OsString]>,extra_options: Box<[OsString]>,include_dirs: Box<[PathBuf]>,+ cache_key: [u8; blake3::OUT_LEN],}impl MetalToolchain {- pub fn from_env_with_include_dir(include_dir: Option<PathBuf>) -> anyhow::Result<Self> {+ pub async fn from_env_with_include_dir(include_dir: Option<PathBuf>) -> anyhow::Result<Self> {let sdk = MetalSdk::from_env().context("cannot get sdk")?;let std = MetalStd::Metal4_0;@@ -118,16 +119,49 @@ impl MetalToolchain {let opt_flags = [opt_level_flags, debug_flags].concat().into_boxed_slice();- let extra_options = Box::new([OsString::from(format!("-m{}-version-min={}", sdk.os(), std.min_os()))]);+ let extra_options: Box<[OsString]> =+ Box::new([OsString::from(format!("-m{}-version-min={}", sdk.os(), std.min_os()))]);let include_dirs = include_dir.into_iter().collect();+ let cache_key = {+ let mut hasher = blake3::Hasher::new();++ hasher.update(sdk.to_str().as_bytes());+ hasher.update(b"\0");+ hasher.update(std.to_str().as_bytes());+ hasher.update(b"\0");+ for flag in opt_flags.iter().chain(extra_options.iter()) {+ hasher.update(flag.as_encoded_bytes());+ hasher.update(b"\0");+ }++ for args in [&["metal", "--version"][..], &["--show-sdk-version"][..], &["--show-sdk-build-version"][..]] {+ let output = Command::new("xcrun")+ .args(["-sdk", sdk.to_str()])+ .args(args)+ .output()+ .await+ .with_context(|| format!("cannot execute xcrun {}", args.join(" ")))?;+ if !output.status.success() {+ bail!("xcrun {} failed: {}", args.join(" "), String::from_utf8_lossy(&output.stderr));+ }+ hasher.update(&output.stdout);+ hasher.update(b"\0");+ hasher.update(&output.stderr);+ hasher.update(b"\0");+ }++ hasher.finalize().into()+ };+Ok(Self {sdk,std,opt_flags,extra_options,include_dirs,+ cache_key,})}@@ -137,6 +171,10 @@ impl MetalToolchain {cmd}+ pub fn cache_key(&self) -> &[u8; blake3::OUT_LEN] {+ &self.cache_key+ }+fn add_include_dirs(&self,cmd: &mut Command,