Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Metal DSL: support function constants in host-side dispatch expressions (#608)

CCYeh0fc632ad9454
diff --git a/crates/backend-uzu/build/metal/bindgen/arguments.rs b/crates/backend-uzu/build/metal/bindgen/arguments.rs
index cd961c42f..13e2d891f 100644
--- a/crates/backend-uzu/build/metal/bindgen/arguments.rs
+++ b/crates/backend-uzu/build/metal/bindgen/arguments.rs
@@ -11,7 +11,7 @@ use super::{
},
enum_path_rewrite::rewrite_for_rust,
},
- variant_path_rewriter::VariantPathRewriter,
+ host_expression_rewriter::HostExpressionRewriter,
};
use crate::common::enum_paths::EnumPaths;
@@ -62,7 +62,7 @@ pub struct IndirectDispatchArgument;
pub fn parse(
kernel: &MetalKernelInfo,
enum_paths: &EnumPaths,
- variant_path_rewriter: &mut VariantPathRewriter,
+ host_expression_rewriter: &mut HostExpressionRewriter,
) -> Result<Vec<ArgumentEmission>> {
let mut emissions = Vec::new();
let mut next_buffer_index = 0usize;
@@ -88,7 +88,7 @@ pub fn parse(
dimensions.as_deref(),
next_threadgroup_index,
enum_paths,
- variant_path_rewriter,
+ host_expression_rewriter,
)?;
emissions.push(ArgumentEmission::Shared(shared));
next_threadgroup_index += 1;
@@ -109,7 +109,7 @@ fn parse_shared_argument(
dimensions: Option<&str>,
threadgroup_index: usize,
enum_paths: &EnumPaths,
- variant_path_rewriter: &mut VariantPathRewriter,
+ host_expression_rewriter: &mut HostExpressionRewriter,
) -> Result<SharedArgument> {
let condition = parse_argument_condition(argument, enum_paths)?
.context("optional threadgroup argument must carry a condition")?;
@@ -117,7 +117,7 @@ fn parse_shared_argument(
let element_size = shared_element_byte_size(&argument.c_type)?;
let dimension_factors = dimensions
.split("][")
- .map(|dimension| variant_path_rewriter.rewrite(dimension))
+ .map(|dimension| host_expression_rewriter.rewrite(dimension))
.collect::<Result<Vec<TokenStream>>>()?;
let element_count = dimension_factors
.into_iter()
diff --git a/crates/backend-uzu/build/metal/bindgen/dispatch.rs b/crates/backend-uzu/build/metal/bindgen/dispatch.rs
index 594cd7124..2f99bf4ea 100644
--- a/crates/backend-uzu/build/metal/bindgen/dispatch.rs
+++ b/crates/backend-uzu/build/metal/bindgen/dispatch.rs
@@ -7,7 +7,7 @@ use syn::LitInt;
use super::{
super::ast::{MetalArgumentType, MetalGroupsType, MetalKernelInfo},
- variant_path_rewriter::VariantPathRewriter,
+ host_expression_rewriter::HostExpressionRewriter,
};
pub struct DispatchEmission {
@@ -17,20 +17,20 @@ pub struct DispatchEmission {
pub fn parse(
kernel: &MetalKernelInfo,
- variant_path_rewriter: &mut VariantPathRewriter,
+ host_expression_rewriter: &mut HostExpressionRewriter,
) -> Result<DispatchEmission> {
let (dispatch_code, dispatch_size_expressions) = if kernel.has_axis() {
if kernel.has_groups() || kernel.has_threads() {
bail!("mixing groups/threads and axis is not supported");
}
- build_axis_dispatch(kernel, variant_path_rewriter)?
+ build_axis_dispatch(kernel, host_expression_rewriter)?
} else if kernel.has_groups_indirect() {
if kernel.has_groups_direct() {
bail!("cannot mix indirect and direct groups");
}
- build_indirect_dispatch(kernel, variant_path_rewriter)?
+ build_indirect_dispatch(kernel, host_expression_rewriter)?
} else {
- build_direct_dispatch(kernel, variant_path_rewriter)?
+ build_direct_dispatch(kernel, host_expression_rewriter)?
};
let empty_dispatch_guards = build_empty_dispatch_guards(&dispatch_size_expressions);
@@ -43,7 +43,7 @@ pub fn parse(
fn build_axis_dispatch(
kernel: &MetalKernelInfo,
- variant_path_rewriter: &mut VariantPathRewriter,
+ host_expression_rewriter: &mut HostExpressionRewriter,
) -> Result<(TokenStream, Vec<TokenStream>)> {
let mut axis_pairs: Vec<(TokenStream, TokenStream)> = kernel
.arguments
@@ -55,8 +55,8 @@ fn build_axis_dispatch(
_ => None,
})
.map(|(threads_text, threads_per_group_text)| -> Result<(TokenStream, TokenStream)> {
- let threads = variant_path_rewriter.rewrite(threads_text)?;
- let threads_per_group = variant_path_rewriter.rewrite(threads_per_group_text)?;
+ let threads = host_expression_rewriter.rewrite(threads_text)?;
+ let threads_per_group = host_expression_rewriter.rewrite(threads_per_group_text)?;
Ok((threads, threads_per_group))
})
.collect::<Result<_>>()?;
@@ -78,9 +78,9 @@ fn build_axis_dispatch(
fn build_indirect_dispatch(
kernel: &MetalKernelInfo,
- variant_path_rewriter: &mut VariantPathRewriter,
+ host_expression_rewriter: &mut HostExpressionRewriter,
) -> Result<(TokenStream, Vec<TokenStream>)> {
- let mut threads = collect_thread_expressions(kernel, variant_path_rewriter)?;
+ let mut threads = collect_thread_expressions(kernel, host_expression_rewriter)?;
threads.extend(repeat_n(quote! { 1 }, 3 - threads.len()));
let dispatch_code = quote! {
@@ -96,9 +96,9 @@ fn build_indirect_dispatch(
fn build_direct_dispatch(
kernel: &MetalKernelInfo,
- variant_path_rewriter: &mut VariantPathRewriter,
+ host_expression_rewriter: &mut HostExpressionRewriter,
) -> Result<(TokenStream, Vec<TokenStream>)> {
- let mut threads = collect_thread_expressions(kernel, variant_path_rewriter)?;
+ let mut threads = collect_thread_expressions(kernel, host_expression_rewriter)?;
threads.extend(repeat_n(quote! { 1 }, 3 - threads.len()));
let mut groups: Vec<TokenStream> = kernel
@@ -106,7 +106,7 @@ fn build_direct_dispatch(
.iter()
.filter_map(|argument| match &argument.argument_type {
MetalArgumentType::Groups(MetalGroupsType::Direct(groups_text)) => {
- Some(variant_path_rewriter.rewrite(groups_text))
+ Some(host_expression_rewriter.rewrite(groups_text))
},
_ => None,
})
@@ -127,13 +127,13 @@ fn build_direct_dispatch(
fn collect_thread_expressions(
kernel: &MetalKernelInfo,
- variant_path_rewriter: &mut VariantPathRewriter,
+ host_expression_rewriter: &mut HostExpressionRewriter,
) -> Result<Vec<TokenStream>> {
kernel
.arguments
.iter()
.filter_map(|argument| match &argument.argument_type {
- MetalArgumentType::Threads(threads_text) => Some(variant_path_rewriter.rewrite(threads_text)),
+ MetalArgumentType::Threads(threads_text) => Some(host_expression_rewriter.rewrite(threads_text)),
_ => None,
})
.collect()
diff --git a/crates/backend-uzu/build/metal/bindgen/variant_path_rewriter.rs b/crates/backend-uzu/build/metal/bindgen/host_expression_rewriter.rs
similarity index 53%
rename from crates/backend-uzu/build/metal/bindgen/variant_path_rewriter.rs
rename to crates/backend-uzu/build/metal/bindgen/host_expression_rewriter.rs
index fe81dd2bf..582c20227 100644
--- a/crates/backend-uzu/build/metal/bindgen/variant_path_rewriter.rs
+++ b/crates/backend-uzu/build/metal/bindgen/host_expression_rewriter.rs
@@ -2,25 +2,33 @@ use std::collections::BTreeSet;
use anyhow::{Context, Result};
use proc_macro2::TokenStream;
-use quote::quote;
+use quote::{format_ident, quote};
use syn::Expr;
-use super::variants::VariantBind;
-use crate::common::expr_rewrite::rewrite_paths_with;
+use crate::{
+ common::{enum_paths::EnumPaths, expr_rewrite::rewrite_paths_with},
+ metal::{bindgen::variants::VariantBind, enum_path_rewrite::qualify_enum_path},
+};
-pub struct VariantPathRewriter<'context> {
+pub struct HostExpressionRewriter<'context> {
variants: &'context [VariantBind],
+ enum_paths: &'context EnumPaths,
+ specialization_names: Vec<String>,
referenced_parameter_names: BTreeSet<String>,
kernel_name: &'context str,
}
-impl<'context> VariantPathRewriter<'context> {
+impl<'context> HostExpressionRewriter<'context> {
pub fn new(
variants: &'context [VariantBind],
+ enum_paths: &'context EnumPaths,
+ specialization_names: Vec<String>,
kernel_name: &'context str,
) -> Self {
Self {
variants,
+ enum_paths,
+ specialization_names,
referenced_parameter_names: BTreeSet::new(),
kernel_name,
}
@@ -35,18 +43,30 @@ impl<'context> VariantPathRewriter<'context> {
})?;
let variants = self.variants;
+ let enum_paths = self.enum_paths;
+ let specialization_names = &self.specialization_names;
let referenced_parameter_names = &mut self.referenced_parameter_names;
rewrite_paths_with(&mut expression, |path| {
+ if let Some(qualified) = qualify_enum_path(path, enum_paths) {
+ return Some(qualified);
+ }
+
if path.leading_colon.is_some()
|| path.segments.len() != 1
|| !matches!(path.segments[0].arguments, syn::PathArguments::None)
{
return None;
}
- let segment_name = path.segments[0].ident.to_string();
- let bind = variants.iter().find(|variant| variant.parameter_name == segment_name)?;
- referenced_parameter_names.insert(segment_name);
- let field_name = &bind.field_name;
+
+ let name = path.segments[0].ident.to_string();
+ let field_name = if let Some(variant) = variants.iter().find(|variant| variant.parameter_name == name) {
+ variant.field_name.clone()
+ } else if specialization_names.contains(&name) {
+ format_ident!("specialize_{name}")
+ } else {
+ return None;
+ };
+ referenced_parameter_names.insert(name);
Some(syn::parse_quote! { self.#field_name })
});
diff --git a/crates/backend-uzu/build/metal/bindgen/mod.rs b/crates/backend-uzu/build/metal/bindgen/mod.rs
index 5c0b72e55..42640ecb9 100644
--- a/crates/backend-uzu/build/metal/bindgen/mod.rs
+++ b/crates/backend-uzu/build/metal/bindgen/mod.rs
@@ -1,15 +1,15 @@
mod arguments;
mod dispatch;
+mod host_expression_rewriter;
mod specialize;
mod trait_wiring;
-mod variant_path_rewriter;
mod variants;
use anyhow::Result;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
-use self::variant_path_rewriter::VariantPathRewriter;
+use self::host_expression_rewriter::HostExpressionRewriter;
use super::{ast::MetalKernelInfo, wrapper::SpecializeBaseIndices};
use crate::common::{enum_paths::EnumPaths, mangling::dynamic_mangle};
@@ -23,14 +23,15 @@ pub fn bindgen(
let struct_name = format_ident!("{}MetalKernel", kernel_name);
let variant_binds = variants::parse(kernel)?;
- let mut variant_path_rewriter = VariantPathRewriter::new(&variant_binds, kernel_name);
- let argument_emissions = arguments::parse(kernel, enum_paths, &mut variant_path_rewriter)?;
let specialize_emission =
specialize::parse(kernel, specialize_indices.get(&kernel.name).copied(), kernel_name, enum_paths)?;
+ let mut host_expression_rewriter =
+ HostExpressionRewriter::new(&variant_binds, enum_paths, specialize_emission.argument_names(), kernel_name);
+ let argument_emissions = arguments::parse(kernel, enum_paths, &mut host_expression_rewriter)?;
let trait_wiring = trait_wiring::build(kernel, &trait_name, &struct_name);
- let dispatch_emission = dispatch::parse(kernel, &mut variant_path_rewriter)?;
- let referenced_parameter_names = variant_path_rewriter.finish();
+ let dispatch_emission = dispatch::parse(kernel, &mut host_expression_rewriter)?;
+ let referenced_parameter_names = host_expression_rewriter.finish();
let conditional_buffer_fields: Vec<TokenStream> =
argument_emissions.iter().filter_map(|argument| argument.struct_field()).collect();
@@ -55,6 +56,10 @@ pub fn bindgen(
let entry_name = dynamic_mangle(kernel_name, variant_kernel_format);
let specialize_arguments = specialize_emission.constructor_arguments();
+ let specialize::RetainedSpecializations {
+ wrapper_fields: retained_specialization_fields,
+ wrapper_initializers: retained_specialization_initializers,
+ } = specialize_emission.retain_referenced(&referenced_parameter_names);
let function_constants_initialization = specialize_emission.function_constants_initialization();
let function_constants_argument = specialize_emission.function_constants_argument();
let cache_key = specialize_emission.cache_key();
@@ -76,6 +81,7 @@ pub fn bindgen(
pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
#(#conditional_buffer_fields,)*
#(#variant_struct_fields,)*
+ #(#retained_specialization_fields,)*
}
#[allow(clippy::style, clippy::complexity, clippy::perf)]
@@ -90,7 +96,12 @@ pub fn bindgen(
let entry_name = #entry_name;
#function_constants_initialization
let pipeline = context.compute_pipeline_state(#cache_key, &entry_name, #function_constants_argument)?;
- Ok(Self { pipeline #(, #conditional_buffer_initializers)* #(, #variant_struct_initializers)* })
+ Ok(Self {
+ pipeline
+ #(, #conditional_buffer_initializers)*
+ #(, #variant_struct_initializers)*
+ #(, #retained_specialization_initializers)*
+ })
}
#method_visibility fn encode<#(#encode_lifetimes),*>(
diff --git a/crates/backend-uzu/build/metal/bindgen/specialize.rs b/crates/backend-uzu/build/metal/bindgen/specialize.rs
index 631ba85b2..f39f4f72b 100644
--- a/crates/backend-uzu/build/metal/bindgen/specialize.rs
+++ b/crates/backend-uzu/build/metal/bindgen/specialize.rs
@@ -1,3 +1,5 @@
+use std::collections::BTreeSet;
+
use anyhow::{Context, Result};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
@@ -26,6 +28,11 @@ pub struct SpecializeEmission {
arguments: Vec<SpecializeArgument>,
}
+pub struct RetainedSpecializations {
+ pub wrapper_fields: Vec<TokenStream>,
+ pub wrapper_initializers: Vec<TokenStream>,
+}
+
pub fn parse(
kernel: &MetalKernelInfo,
base_function_constant_index: Option<usize>,
@@ -66,6 +73,32 @@ pub fn parse(
}
impl SpecializeEmission {
+ pub fn argument_names(&self) -> Vec<String> {
+ self.arguments.iter().map(|argument| argument.name.to_string()).collect()
+ }
+
+ pub fn retain_referenced(
+ &self,
+ referenced: &BTreeSet<String>,
+ ) -> RetainedSpecializations {
+ let (wrapper_fields, wrapper_initializers) = self
+ .arguments
+ .iter()
+ .filter(|argument| referenced.contains(&argument.name.to_string()))
+ .map(|argument| {
+ let name = &argument.name;
+ let field = format_ident!("specialize_{}", name);
+ let rust_type = &argument.rust_type;
+ (quote! { #field: #rust_type }, quote! { #field: #name })
+ })
+ .unzip();
+
+ RetainedSpecializations {
+ wrapper_fields,
+ wrapper_initializers,
+ }
+ }
+
pub fn constructor_arguments(&self) -> Vec<TokenStream> {
self.arguments
.iter()
diff --git a/crates/backend-uzu/build/metal/enum_path_rewrite.rs b/crates/backend-uzu/build/metal/enum_path_rewrite.rs
index 27e17dc17..c7c270bfb 100644
--- a/crates/backend-uzu/build/metal/enum_path_rewrite.rs
+++ b/crates/backend-uzu/build/metal/enum_path_rewrite.rs
@@ -39,7 +39,7 @@ pub fn rewrite_for_rust(
Ok(parsed.into_token_stream())
}
-fn qualify_enum_path(
+pub(super) fn qualify_enum_path(
path: &Path,
enum_paths: &EnumPaths,
) -> Option<Expr> {