Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Per-file metallib (#660)

uuuvn5579675760eb
diff --git a/crates/backend-uzu/build/common/kernel.rs b/crates/backend-uzu/build/common/kernel.rs
index 7665a3e3a..c66dc2423 100644
--- a/crates/backend-uzu/build/common/kernel.rs
+++ b/crates/backend-uzu/build/common/kernel.rs
@@ -1,37 +1,39 @@
+use serde::{Deserialize, Serialize};
+
use super::identifiers::{ArgumentName, KernelName};
-#[derive(PartialEq, Debug, Clone)]
+#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub enum KernelBufferAccess {
Read,
ReadWrite,
}
-#[derive(PartialEq, Debug, Clone)]
+#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub enum KernelArgumentType {
Buffer(KernelBufferAccess),
Constant(Box<str>),
}
-#[derive(PartialEq, Debug, Clone)]
+#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct KernelArgument {
pub name: ArgumentName,
pub conditional: bool,
pub ty: KernelArgumentType,
}
-#[derive(PartialEq, Debug, Clone)]
+#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub enum KernelParameterType {
Type,
Value(Box<str>),
}
-#[derive(PartialEq, Debug, Clone)]
+#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct KernelParameter {
pub name: Box<str>,
pub ty: KernelParameterType,
}
-#[derive(PartialEq, Debug, Clone)]
+#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
pub struct Kernel {
pub name: KernelName,
pub parameters: Box<[KernelParameter]>,
diff --git a/crates/backend-uzu/build/cpu/compiler.rs b/crates/backend-uzu/build/cpu/compiler.rs
index bb76257b7..24343de5f 100644
--- a/crates/backend-uzu/build/cpu/compiler.rs
+++ b/crates/backend-uzu/build/cpu/compiler.rs
@@ -633,7 +633,7 @@ impl CpuCompiler {
&self,
objects: impl IntoIterator<Item = &'a (KernelPath, Box<[Kernel]>)> + Clone,
) -> anyhow::Result<()> {
- let out_path = self.build_dir.join("dsl.rs");
+ let out_path = self.build_dir.with_extension("rs");
let associated_types = objects.into_iter().flat_map(|(file_path, kernels)| {
kernels.iter().map(|kernel| {
diff --git a/crates/backend-uzu/build/metal/ast.rs b/crates/backend-uzu/build/metal/ast.rs
index 3b79ef099..322d75d38 100644
--- a/crates/backend-uzu/build/metal/ast.rs
+++ b/crates/backend-uzu/build/metal/ast.rs
@@ -1,6 +1,6 @@
use anyhow::{Context, bail};
use quote::quote;
-use serde::{Deserialize, Serialize};
+use serde::Deserialize;
use crate::common::{
expr_rewrite::rewrite_paths_with,
@@ -121,25 +121,25 @@ fn annotation_from_ast_node(annotation_node: MetalAstNode) -> anyhow::Result<Box
.collect()
}
-#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
+#[derive(Debug, Clone, Copy)]
pub enum MetalBufferAccess {
Read,
ReadWrite,
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Clone)]
pub enum MetalConstantType {
Scalar,
Array(Option<Box<str>>),
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Clone)]
pub enum MetalGroupsType {
Direct(Box<str>),
Indirect,
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Clone)]
pub enum MetalArgumentType {
Buffer(MetalBufferAccess),
Constant((Box<str>, MetalConstantType)),
@@ -151,13 +151,12 @@ pub enum MetalArgumentType {
ThreadContext,
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug)]
pub struct MetalArgument {
pub name: ArgumentName,
pub c_type: Box<str>,
pub argument_type: MetalArgumentType,
pub condition: Option<Box<str>>,
- pub source: Box<str>,
}
pub fn shared_element_type(c_type: &str) -> &str {
@@ -254,7 +253,6 @@ impl MetalArgument {
c_type,
argument_type,
condition,
- source,
})
}
@@ -396,13 +394,13 @@ fn parse_argument_type(
bail!("cannot parse c type: {}", c_type);
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug)]
pub enum MetalTemplateParameterType {
Type,
Value(Box<str>),
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug)]
pub struct MetalTemplateParameter {
pub name: Box<str>,
pub ty: MetalTemplateParameterType,
@@ -421,7 +419,7 @@ impl MetalTemplateParameter {
}
}
-#[derive(Debug, Serialize, Deserialize)]
+#[derive(Debug)]
pub struct MetalKernelInfo {
pub public: bool,
pub name: KernelName,
diff --git a/crates/backend-uzu/build/metal/bindgen/mod.rs b/crates/backend-uzu/build/metal/bindgen/mod.rs
index 42640ecb9..737135003 100644
--- a/crates/backend-uzu/build/metal/bindgen/mod.rs
+++ b/crates/backend-uzu/build/metal/bindgen/mod.rs
@@ -11,12 +11,13 @@ use quote::{format_ident, quote};
use self::host_expression_rewriter::HostExpressionRewriter;
use super::{ast::MetalKernelInfo, wrapper::SpecializeBaseIndices};
-use crate::common::{enum_paths::EnumPaths, mangling::dynamic_mangle};
+use crate::common::{enum_paths::EnumPaths, kernel::Kernel, mangling::dynamic_mangle};
pub fn bindgen(
kernel: &MetalKernelInfo,
specialize_indices: &SpecializeBaseIndices,
enum_paths: &EnumPaths,
+ library_const: &proc_macro2::Ident,
) -> Result<(TokenStream, Option<TokenStream>)> {
let kernel_name = kernel.name.as_ref();
let trait_name = format_ident!("{}Kernel", kernel_name);
@@ -95,7 +96,7 @@ pub fn bindgen(
) -> Result<Self, MetalError> {
let entry_name = #entry_name;
#function_constants_initialization
- let pipeline = context.compute_pipeline_state(#cache_key, &entry_name, #function_constants_argument)?;
+ let pipeline = context.compute_pipeline_state(#library_const, #cache_key, &entry_name, #function_constants_argument)?;
Ok(Self {
pipeline
#(, #conditional_buffer_initializers)*
@@ -121,3 +122,46 @@ pub fn bindgen(
Ok((kernel_tokens, trait_wiring.associated_type))
}
+
+pub fn bindgen_global(kernels: &[(impl AsRef<std::path::Path>, &[Kernel])]) -> Result<TokenStream> {
+ let includes = kernels.iter().map(|(path, _kernels)| {
+ let path = path.as_ref().to_str().expect("bindings path is not utf-8");
+
+ quote! {
+ include!(#path);
+ }
+ });
+
+ let associated_types = kernels.iter().flat_map(|(_path, kernels)| kernels.iter()).map(|kernel| {
+ let trait_name = format_ident!("{}Kernel", kernel.name.as_ref());
+ let struct_name = format_ident!("{}MetalKernel", kernel.name.as_ref());
+
+ quote! {
+ type #trait_name = #struct_name;
+ }
+ });
+
+ let tokens = quote! {
+ use metal::{MTLComputeCommandEncoder, MTLComputePipelineState, MTLFunctionConstantValues, MTLSize};
+ use objc2::{rc::Retained, runtime::ProtocolObject};
+
+ use crate::backends::common::BufferGpuAddressRangeExt;
+ use crate::backends::metal::{
+ context::MetalContext,
+ error::MetalError,
+ metal_extensions::{
+ ComputeEncoderSetValue, FunctionConstantValuesSetValue, MetalDataTypeExt,
+ },
+ };
+
+ #(#includes)*
+
+ macro_rules! autogen_kernels {
+ () => {
+ #(#associated_types)*
+ }
+ }
+ };
+
+ Ok(tokens)
+}
diff --git a/crates/backend-uzu/build/metal/compiler.rs b/crates/backend-uzu/build/metal/compiler.rs
index 33216a235..d690b57f4 100644
--- a/crates/backend-uzu/build/metal/compiler.rs
+++ b/crates/backend-uzu/build/metal/compiler.rs
@@ -2,116 +2,55 @@ use std::{collections::HashMap, env, fs, path::PathBuf};
use anyhow::Context;
use async_trait::async_trait;
-use futures::{StreamExt, TryStreamExt, future::try_join_all, stream};
-use proc_macro2::TokenStream;
-use quote::quote;
+use futures::{StreamExt, TryStreamExt, stream};
+use quote::{format_ident, quote};
use serde::{Deserialize, Serialize};
-use tokio::{io::AsyncReadExt, task::spawn_blocking};
use walkdir::WalkDir;
-use super::{
- ast::MetalKernelInfo,
- toolchain::MetalToolchain,
- wrapper::{SpecializeBaseIndices, wrappers},
-};
+use super::{ast::MetalKernelInfo, bindgen::bindgen_global, toolchain::MetalToolchain, wrapper::wrappers};
use crate::{
common::{
- caching, codegen::write_tokens, compiler::Compiler, enum_paths::EnumPaths, envs, gpu_types::GpuTypes,
+ caching, codegen::write_tokens, compiler::Compiler, enum_paths::EnumPaths, gpu_types::GpuTypes,
identifiers::KernelPath, kernel::Kernel,
},
debug_log,
metal::gpu_types::gpu_type_gen,
};
-#[derive(Serialize, Deserialize, Debug)]
-struct ObjectInfo {
- src_rel_path: PathBuf,
- object_path: PathBuf,
- kernels: Box<[MetalKernelInfo]>,
- specialize_indices: SpecializeBaseIndices,
+#[derive(Serialize, Deserialize)]
+struct Cached {
buildsystem_hash: [u8; blake3::OUT_LEN],
dependency_hashes: HashMap<Box<str>, [u8; blake3::OUT_LEN]>,
-}
-
-impl ObjectInfo {
- fn kernels(&self) -> (KernelPath, Box<[Kernel]>) {
- let src_rel_path: KernelPath = self
- .src_rel_path
- .with_extension("")
- .as_os_str()
- .to_str()
- .unwrap()
- .split("/")
- .map(|s| s.to_string())
- .collect();
-
- let kernels = self.kernels.iter().filter_map(|ki| ki.to_kernel()).collect();
-
- (src_rel_path, kernels)
- }
-}
-
-async fn hash_dependencies(
- dependencies: impl Iterator<Item = Box<str>>
-) -> anyhow::Result<HashMap<Box<str>, [u8; blake3::OUT_LEN]>> {
- let futures: Vec<_> = dependencies
- .map(|path| async move {
- let mut file =
- tokio::fs::File::open(path.as_ref()).await.with_context(|| format!("cannot open file {}", path))?;
- let mut contents = Vec::new();
- file.read_to_end(&mut contents).await.with_context(|| format!("cannot read file {}", path))?;
- let hash = spawn_blocking(move || blake3::hash(&contents)).await.context("hash task panicked")?;
- Ok::<_, anyhow::Error>((path, hash.into()))
- })
- .collect();
- try_join_all(futures).await.map(|v| v.into_iter().collect())
-}
-
-fn objects_hash<'a>(objects: impl IntoIterator<Item = &'a ObjectInfo>) -> anyhow::Result<blake3::Hash> {
- let mut hasher = blake3::Hasher::new();
- hasher.update(caching::build_system_hash().context("cannot get build system hash")?.as_bytes());
- let mut paths: Vec<_> = objects.into_iter().map(|o| &o.object_path).collect();
- paths.sort();
- for path in paths {
- let path_bytes = path.to_string_lossy();
- let path_bytes = path_bytes.as_bytes();
- hasher.update(&(path_bytes.len() as u32).to_le_bytes());
- hasher.update(path_bytes);
- let contents = fs::read(path).with_context(|| format!("cannot read {}", path.display()))?;
- hasher.update(&(contents.len() as u32).to_le_bytes());
- hasher.update(&contents);
- }
- Ok(hasher.finalize())
+ public_kernels: Box<[Kernel]>,
+ has_kernels: bool,
}
#[derive(Debug)]
pub struct MetalCompiler {
- src_dir: PathBuf,
- gpu_types_dir: PathBuf,
- build_dir: PathBuf,
- out_dir: PathBuf,
+ source_directory: PathBuf,
+ gpu_types_directory: PathBuf,
+ output_directory: PathBuf,
toolchain: MetalToolchain,
}
impl MetalCompiler {
pub fn new() -> anyhow::Result<Self> {
- let src_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").context("missing CARGO_MANIFEST_DIR")?)
+ let source_directory = PathBuf::from(env::var("CARGO_MANIFEST_DIR").context("missing CARGO_MANIFEST_DIR")?)
.join("src/backends/metal/kernel");
- let gpu_types_dir = src_dir.join("generated");
+ let gpu_types_directory = source_directory.join("generated");
- let out_dir = PathBuf::from(env::var("OUT_DIR").context("missing OUT_DIR")?);
- let build_dir = out_dir.join("metal");
- fs::create_dir_all(&build_dir).with_context(|| format!("cannot create {}", build_dir.display()))?;
+ let output_directory = PathBuf::from(env::var("OUT_DIR").context("missing OUT_DIR")?).join("metal");
+ fs::create_dir_all(&output_directory)
+ .with_context(|| format!("cannot create {}", output_directory.display()))?;
- let toolchain = MetalToolchain::from_env_with_include_dir(Some(gpu_types_dir.clone()))
+ let toolchain = MetalToolchain::from_env_with_include_dir(Some(gpu_types_directory.clone()))
.context("cannot create toolchain")?;
Ok(Self {
- src_dir,
- gpu_types_dir,
- build_dir,
- out_dir,
+ source_directory,
+ gpu_types_directory,
+ output_directory,
toolchain,
})
}
@@ -120,202 +59,128 @@ impl MetalCompiler {
&self,
source_path: PathBuf,
enum_paths: &EnumPaths,
- ) -> anyhow::Result<ObjectInfo> {
- let buildsystem_hash = *caching::build_system_hash().context("cannot get build system cache")?.as_bytes();
-
- let source_path_pretty = source_path.file_name().unwrap().to_str().unwrap();
- debug_log!("compile start: {source_path_pretty}");
-
- let source_path_display = source_path.display().to_string();
- let source_path_hash = blake3::hash(source_path.to_string_lossy().as_bytes());
- let source_file_name =
- source_path.with_extension("").file_name().context("source path has no file name")?.to_os_string();
-
- let source_path_rel = source_path.strip_prefix(&self.src_dir).context("source is not in src_dir")?;
-
- let build_dir = self.build_dir.join(source_path_hash.to_string());
- let objectinfo_path = build_dir.join(&source_file_name).with_extension("objectinfo");
-
- if build_dir.exists() {
- if let Ok(contents) = tokio::fs::read(&objectinfo_path).await
- && let Ok(cached) = serde_json::from_slice::<ObjectInfo>(&contents)
- && buildsystem_hash == cached.buildsystem_hash
- && let Ok(dependency_hashes) = hash_dependencies(cached.dependency_hashes.keys().cloned()).await
- && dependency_hashes == cached.dependency_hashes
- {
- if envs::build_debug() {
- let kernel_list = cached.kernels.iter().map(|k| k.name.as_ref()).collect::<Vec<_>>().join(", ");
- if kernel_list.is_empty() {
- debug_log!("compile cached: {source_path_pretty}");
- } else {
- debug_log!("compile cached: {source_path_pretty} (kernels: [{kernel_list}])");
- }
- }
- return Ok(cached);
- }
- fs::remove_dir_all(&build_dir).ok();
- }
+ ) -> anyhow::Result<(KernelPath, Box<[Kernel]>, bool)> {
+ let source_path_relative =
+ source_path.strip_prefix(&self.source_directory).context("source is not in src_dir")?;
+ let source_path_relative_str = source_path_relative.to_str().context("source path is not utf-8")?;
+ debug_log!("compile start: {source_path_relative_str}");
- fs::create_dir_all(&build_dir)
- .with_context(|| format!("cannot create build directory {}", build_dir.display()))?;
+ let kernel_path: KernelPath = source_path_relative
+ .with_extension("")
+ .components()
+ .map(|component| component.as_os_str().to_str().unwrap().to_string())
+ .collect();
- let (metal_kernel_infos, dependencies) = self
- .toolchain
- .analyze(&source_path)
- .await
- .with_context(|| format!("cannot analyze {}", source_path_display))?;
+ let output_base_path = self.output_directory.join(source_path_relative).with_extension("");
+ fs::create_dir_all(output_base_path.parent().context("cannot get output directory")?)
+ .context("cannot create output directory")?;
- let kernel_infos: Vec<MetalKernelInfo> = metal_kernel_infos.collect();
+ let object_file = output_base_path.with_extension("air");
+ let metallib_file = output_base_path.with_extension("metallib");
+ let bindgen_file = output_base_path.with_extension("rs");
+ let cached_file = output_base_path.with_extension("cached");
- let (wrapper_strs, specialize_indices) =
- wrappers(&kernel_infos, enum_paths).context("cannot generate kernel wrappers")?;
+ let buildsystem_hash = caching::build_system_hash().context("cannot get build system hash")?.as_bytes();
- let mut footer = String::new();
- for wrapper in wrapper_strs.iter() {
- footer.push_str(wrapper);
+ 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.dependency_hashes.iter().all(|(path, hash)| {
+ fs::read(path.as_ref()).map(|contents| blake3::hash(&contents).as_bytes() == hash).unwrap_or(false)
+ })
+ {
+ debug_log!("compile cached: {source_path_relative_str}");
+ return Ok((kernel_path, cached.public_kernels, cached.has_kernels));
}
- let object_path = build_dir.join(&source_file_name).with_extension("air");
-
- let compile_output = self
+ let (metal_kernel_infos, dependencies) = self
.toolchain
- .compile(&source_path, &footer, &object_path)
+ .analyze(&source_path)
.await
- .with_context(|| format!("cannot compile {}", source_path_display))?;
+ .with_context(|| format!("cannot analyze {source_path_relative_str}"))?;
- if let Some(warnings) = &compile_output {
- for line in warnings.lines() {
- println!("cargo::warning={line}");
- }
- }
+ let kernel_infos: Vec<MetalKernelInfo> = metal_kernel_infos.collect();
- let dependency_hashes = hash_dependencies(dependencies).await.context("cannot hash dependencies")?;
+ let dependency_hashes = dependencies
+ .map(|path| {
+ Ok((
+ path.clone(),
+ blake3::hash(&fs::read(path.as_ref()).with_context(|| format!("cannot read {path}"))?).into(),
+ ))
+ })
+ .collect::<anyhow::Result<HashMap<Box<str>, [u8; blake3::OUT_LEN]>>>()
+ .context("cannot hash dependencies")?;
- let object_info = ObjectInfo {
- src_rel_path: source_path_rel.into(),
- object_path,
- kernels: kernel_infos.into_boxed_slice(),
- specialize_indices,
- buildsystem_hash,
- dependency_hashes,
- };
+ if !kernel_infos.is_empty() {
+ let (wrapper_strs, specialize_indices) =
+ wrappers(&kernel_infos, enum_paths).context("cannot generate kernel wrappers")?;
- fs::write(
- &objectinfo_path,
- serde_json::to_string_pretty(&object_info).context("failed to serialize object info")?.as_bytes(),
- )
- .with_context(|| format!("cannot write object info {}", objectinfo_path.display()))?;
-
- if envs::build_debug() {
- let kernel_list = object_info.kernels.iter().map(|k| k.name.as_ref()).collect::<Vec<_>>().join(", ");
- if kernel_list.is_empty() {
- debug_log!("compile end: {source_path_pretty}");
- } else {
- debug_log!("compile end: {source_path_pretty} (kernels: [{kernel_list}])");
+ let mut footer = String::new();
+ for wrapper in wrapper_strs.iter() {
+ footer.push_str(wrapper);
}
- }
- Ok(object_info)
- }
-
- async fn link<'a>(
- &self,
- objects: impl IntoIterator<Item = &'a ObjectInfo> + Clone,
- ) -> anyhow::Result<PathBuf> {
- let library_path = self.out_dir.join("default.metallib");
- let hash_path = self.out_dir.join("default.metallib.hash");
+ let compile_output = self
+ .toolchain
+ .compile(&source_path, &footer, &object_file)
+ .await
+ .with_context(|| format!("cannot compile {source_path_relative_str}"))?;
- let hash = objects_hash(objects.clone())?;
-
- if let Ok(cached_hash) = fs::read_to_string(&hash_path)
- && cached_hash == hash.to_string()
- {
- debug_log!("linking cached");
- return Ok(library_path);
- }
-
- debug_log!("linking start");
+ if let Some(warnings) = &compile_output {
+ for line in warnings.lines() {
+ println!("cargo::warning={line}");
+ }
+ }
- let link_output = self
- .toolchain
- .link(objects.into_iter().map(|o| &o.object_path), &library_path)
- .await
- .context("cannot link objects")?;
+ let link_output = self
+ .toolchain
+ .link(&object_file, &metallib_file)
+ .await
+ .with_context(|| format!("cannot link {source_path_relative_str}"))?;
- if let Some(warnings) = &link_output {
- for line in warnings.lines() {
- println!("cargo::warning={line}");
+ if let Some(warnings) = &link_output {
+ for line in warnings.lines() {
+ println!("cargo::warning={line}");
+ }
}
- }
- fs::write(&hash_path, hash.to_string())
- .with_context(|| format!("cannot write hash file {}", hash_path.display()))?;
+ let library_const =
+ format_ident!("MTLB_{}", blake3::hash(source_path_relative_str.as_bytes()).to_hex().to_uppercase());
+ let metallib_file_str = metallib_file.to_str().context("metallib path is not utf-8")?;
- debug_log!("linking end");
+ let bindings = kernel_infos
+ .iter()
+ .map(|kernel| {
+ super::bindgen::bindgen(kernel, &specialize_indices, enum_paths, &library_const)
+ .with_context(|| format!("cannot generate bindings for {}", kernel.name))
+ .map(|(tokens, _associated_type)| tokens)
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?;
- Ok(library_path)
- }
+ let tokens = quote! {
+ const #library_const: &[u8] = include_bytes!(#metallib_file_str);
- fn bindgen<'a>(
- &self,
- objects: impl IntoIterator<Item = &'a ObjectInfo> + Clone,
- enum_paths: &EnumPaths,
- ) -> anyhow::Result<()> {
- let out_path = self.out_dir.join("dsl.rs");
- let hash_path = self.out_dir.join("dsl.rs.hash");
-
- let hash = objects_hash(objects.clone())?;
+ #(#bindings)*
+ };
- if let Ok(cached_hash) = fs::read_to_string(&hash_path)
- && cached_hash == hash.to_string()
- {
- debug_log!("bindgen cached");
- return Ok(());
+ write_tokens(tokens, &bindgen_file).context("cannot write bindings")?;
}
- debug_log!("bindgen start");
-
- let (bindings, associated_types) = objects
- .into_iter()
- .flat_map(|o| o.kernels.iter().map(|k| (k, &o.specialize_indices)))
- .map(|(k, specialize_indices)| {
- super::bindgen::bindgen(k, specialize_indices, enum_paths)
- .with_context(|| format!("cannot generate bindings for {}", k.name))
- })
- .collect::<anyhow::Result<(Vec<TokenStream>, Vec<Option<TokenStream>>)>>()?;
-
- let associated_types = associated_types.into_iter().flatten().collect::<Vec<TokenStream>>();
-
- let tokens = quote! {
- use metal::{MTLComputeCommandEncoder, MTLComputePipelineState, MTLFunctionConstantValues, MTLSize};
- use objc2::{rc::Retained, runtime::ProtocolObject};
-
- use crate::backends::common::BufferGpuAddressRangeExt;
- use crate::backends::metal::{
- context::MetalContext,
- error::MetalError,
- metal_extensions::{
- ComputeEncoderSetValue, FunctionConstantValuesSetValue, MetalDataTypeExt,
- },
- };
-
- #(#bindings)*
+ let public_kernels: Box<[Kernel]> = kernel_infos.iter().filter_map(|kernel| kernel.to_kernel()).collect();
+ let has_kernels = !kernel_infos.is_empty();
- macro_rules! autogen_kernels {
- () => {
- #(#associated_types)*
- }
- }
+ let cached = Cached {
+ buildsystem_hash: *buildsystem_hash,
+ dependency_hashes,
+ public_kernels: public_kernels.clone(),
+ has_kernels,
};
+ fs::write(&cached_file, serde_json::to_vec_pretty(&cached).context("cannot serialize cache")?)
+ .context("cannot write cache file")?;
- write_tokens(tokens, &out_path).context("cannot write bindings")?;
-
- fs::write(&hash_path, hash.to_string())
- .with_context(|| format!("cannot write hash file {}", hash_path.display()))?;
-
- debug_log!("bindgen end");
+ debug_log!("compile end: {source_path_relative_str}");
- Ok(())
+ Ok((kernel_path, public_kernels, has_kernels))
}
}
@@ -326,9 +191,9 @@ impl Compiler for MetalCompiler {
gpu_types: &GpuTypes,
enum_paths: &EnumPaths,
) -> anyhow::Result<HashMap<KernelPath, Box<[Kernel]>>> {
- gpu_type_gen(&self.gpu_types_dir, gpu_types).await.context("cannot generate shared gpu types")?;
+ gpu_type_gen(&self.gpu_types_directory, gpu_types).await.context("cannot generate shared gpu types")?;
- let metal_sources: Vec<PathBuf> = WalkDir::new(&self.src_dir)
+ let metal_sources: Vec<PathBuf> = WalkDir::new(&self.source_directory)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| e.file_type().is_file() && e.path().extension().and_then(|s| s.to_str()) == Some("metal"))
@@ -337,16 +202,28 @@ impl Compiler for MetalCompiler {
let num_concurrent_compiles = std::thread::available_parallelism().map(|x| x.get()).unwrap_or(4) * 2;
- let objects: Vec<ObjectInfo> = stream::iter(metal_sources)
- .map(|p| self.compile(p, enum_paths))
+ let compiled: Vec<(KernelPath, Box<[Kernel]>, bool)> = stream::iter(metal_sources)
+ .map(|path| async move {
+ self.compile(path.clone(), enum_paths)
+ .await
+ .with_context(|| format!("cannot compile {}", path.display()))
+ })
.buffer_unordered(num_concurrent_compiles)
.try_collect()
- .await
- .context("cannot compile metal sources")?;
+ .await?;
+
+ let mut kernels_bindgen = compiled
+ .iter()
+ .filter(|(_path, _kernels, has_kernels)| *has_kernels)
+ .map(|(path, kernels, _has_kernels)| {
+ (self.output_directory.join(path.join("/")).with_extension("rs"), kernels.as_ref())
+ })
+ .collect::<Vec<(PathBuf, &[Kernel])>>();
+ kernels_bindgen.sort_by(|(a_path, _a_kernels), (b_path, _b_kernels)| a_path.cmp(b_path));
- self.link(&objects).await.context("cannot link objects")?;
- self.bindgen(&objects, enum_paths).context("cannot generate bindings")?;
+ let tokens = bindgen_global(&kernels_bindgen).context("cannot generate bindings")?;
+ write_tokens(tokens, self.output_directory.with_extension("rs")).context("cannot write bindings")?;
- Ok(objects.iter().map(|o| o.kernels()).collect())
+ Ok(compiled.into_iter().map(|(path, kernels, _has_kernels)| (path, kernels)).collect())
}
}
diff --git a/crates/backend-uzu/build/metal/toolchain.rs b/crates/backend-uzu/build/metal/toolchain.rs
index aa89bcf54..3b8bfbab5 100644
--- a/crates/backend-uzu/build/metal/toolchain.rs
+++ b/crates/backend-uzu/build/metal/toolchain.rs
@@ -266,13 +266,13 @@ impl MetalToolchain {
pub async fn link(
&self,
- objects: impl IntoIterator<Item = impl AsRef<Path>>,
+ object: impl AsRef<Path>,
output: impl AsRef<Path>,
) -> anyhow::Result<Option<Box<str>>> {
let link_output = self
.xcrun()
.arg("metallib")
- .args(objects.into_iter().map(|p| p.as_ref().as_os_str().to_owned()))
+ .arg(object.as_ref())
.arg("-o")
.arg(output.as_ref())
.output()
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/mod.rs
index 2867bd11e..9edb8a195 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/mod.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/mod.rs
@@ -25,7 +25,7 @@ mod tensor_add_swap;
mod tensor_copy;
mod weaver;
-include!(concat!(env!("OUT_DIR"), "/cpu/dsl.rs"));
+include!(concat!(env!("OUT_DIR"), "/cpu.rs"));
pub struct CpuKernels;
diff --git a/crates/backend-uzu/src/backends/metal/context.rs b/crates/backend-uzu/src/backends/metal/context.rs
index 8b683a71f..9a645a946 100644
--- a/crates/backend-uzu/src/backends/metal/context.rs
+++ b/crates/backend-uzu/src/backends/metal/context.rs
@@ -21,7 +21,6 @@ use super::{
Metal,
device_tier::{DeviceTier, device_tier_for_device},
error::MetalError,
- kernel,
metal_extensions::{DeviceExt, LibraryPipelineExtensions},
};
use crate::backends::{
@@ -40,7 +39,7 @@ pub struct MetalContext {
timeline_value: AtomicU64,
allocator: Arc<Allocator<Metal>>,
peak_memory_usage: AtomicUsize,
- library: Retained<ProtocolObject<dyn MTLLibrary>>,
+ library_cache: Mutex<HashMap<usize, Retained<ProtocolObject<dyn MTLLibrary>>>>,
pipeline_cache: Mutex<HashMap<String, Retained<ProtocolObject<dyn MTLComputePipelineState>>>>,
sparse_heap_pool: Mutex<MetalSparseHeapPool>,
device_tier: DeviceTier,
@@ -62,8 +61,28 @@ impl MetalContext {
self.peak_memory_usage.fetch_max(self.device.current_allocated_size(), Ordering::Relaxed);
}
+ fn library(
+ &self,
+ data: &'static [u8],
+ ) -> Result<Retained<ProtocolObject<dyn MTLLibrary>>, MetalError> {
+ // `data` always comes from an `include_bytes!` constant, so its address is a stable, unique key.
+ let key = data.as_ptr() as usize;
+ if let Some(library) = self.library_cache.lock().get(&key) {
+ return Ok(library.clone());
+ }
+
+ let library = self
+ .device
+ .new_library_with_data(data)
+ .map_err(|nserror| MetalError::CannotCreateLibrary(nserror.to_string()))?;
+ self.library_cache.lock().insert(key, library.clone());
+
+ Ok(library)
+ }
+
pub fn compute_pipeline_state(
&self,
+ library_data: &'static [u8],
cache_key: &str,
function_name: &str,
constants: Option<&MTLFunctionConstantValues>,
@@ -72,7 +91,7 @@ impl MetalContext {
return Ok(pipeline.clone());
}
- let pipeline = self.library.compute_pipeline_state(function_name, constants)?;
+ let pipeline = self.library(library_data)?.compute_pipeline_state(function_name, constants)?;
self.pipeline_cache.lock().insert(cache_key.to_string(), pipeline.clone());
Ok(pipeline)
@@ -123,10 +142,6 @@ impl Context for MetalContext {
let command_queue4 = device.new_mtl4_command_queue().ok_or(MetalError::CannotCreateCommandQueueMtl4)?;
- let library = device
- .new_library_with_data(kernel::MTLB)
- .map_err(|nserror| MetalError::CannotCreateLibrary(nserror.to_string()))?;
-
let gpu_core_count = device.gpu_core_count();
let device_tier = device_tier_for_device(gpu_core_count, device.as_ref());
let page_size = MTLSparsePageSize::KB256;
@@ -144,7 +159,7 @@ impl Context for MetalContext {
timeline_value: AtomicU64::new(0),
allocator: Allocator::new(weak_self.clone()),
peak_memory_usage: AtomicUsize::new(0),
- library,
+ library_cache: Mutex::new(HashMap::new()),
pipeline_cache: Mutex::new(HashMap::new()),
sparse_heap_pool: Mutex::new(sparse_pool),
device_tier,
diff --git a/crates/backend-uzu/src/backends/metal/kernel/mod.rs b/crates/backend-uzu/src/backends/metal/kernel/mod.rs
index 29d21e422..8b7b69956 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/mod.rs
+++ b/crates/backend-uzu/src/backends/metal/kernel/mod.rs
@@ -14,9 +14,7 @@ pub mod gdn;
pub mod matmul;
mod radix_top_k_small;
-pub const MTLB: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/default.metallib"));
-
-include!(concat!(env!("OUT_DIR"), "/dsl.rs"));
+include!(concat!(env!("OUT_DIR"), "/metal.rs"));
pub struct MetalKernels;