Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Support dsl.specialize_if (#882)

CCYeh33e1ad5833e6
diff --git a/crates/uzu-engine/build/cpu/compiler.rs b/crates/uzu-engine/build/cpu/compiler.rs
index 0ee5dde47..0c2c51a1c 100644
--- a/crates/uzu-engine/build/cpu/compiler.rs
+++ b/crates/uzu-engine/build/cpu/compiler.rs
@@ -574,6 +574,17 @@ impl CpuCompiler {
encode_args_defs
.push(quote! { command_buffer: &mut <<crate::backends::cpu::Cpu as crate::backends::common::Backend>::CommandBuffer as crate::backends::common::CommandBuffer>::Encoding });
+ let specialization_validation = function_arguments.iter().filter_map(|argument| {
+ if !matches!(argument.ty, FunctionArgumentType::Specialization(_)) {
+ return None;
+ }
+ let condition = argument.conditional.as_ref()?;
+ let name = &argument.name;
+ Some(quote! {
+ assert_eq!(#name.is_some(), #condition, concat!("invalid presence for specialization ", stringify!(#name)));
+ })
+ });
+
let tokens = quote! {
#[allow(non_snake_case)]
pub struct #struct_ident {
@@ -585,6 +596,7 @@ impl CpuCompiler {
type Backend = crate::backends::cpu::Cpu;
fn new(#[allow(unused)] context: &crate::backends::cpu::context::CpuContext #(, #parameter_args)*) -> Result<Self, crate::backends::cpu::error::CpuError> {
+ #(#specialization_validation)*
Ok(Self {
#(#struct_fields_sets ,)*
})
diff --git a/crates/uzu-engine/build/metal/ast.rs b/crates/uzu-engine/build/metal/ast.rs
index 322d75d38..01ce86c74 100644
--- a/crates/uzu-engine/build/metal/ast.rs
+++ b/crates/uzu-engine/build/metal/ast.rs
@@ -277,6 +277,16 @@ fn parse_argument_annotation(
annotation: Option<&[Box<str>]>,
integer_defines: &IntegerObjectDefines,
) -> anyhow::Result<(MetalArgumentType, Option<Box<str>>)> {
+ if let Some(annotation) = annotation
+ && annotation.first().map(|s| s.as_ref()) == Some("dsl.specialize_if")
+ {
+ if annotation.len() != 2 {
+ bail!("dsl.specialize_if takes 1 argument, found {}", annotation.len() - 1);
+ }
+ let ty = MetalArgument::scalar_type_to_rust(c_type)?;
+ return Ok((MetalArgumentType::Specialize(format!("Option < {ty} >").into()), Some(annotation[1].clone())));
+ }
+
if let Some(annotation) = annotation
&& annotation.first().map(|s| s.as_ref()) == Some("dsl.optional")
{
diff --git a/crates/uzu-engine/build/metal/bindgen/arguments.rs b/crates/uzu-engine/build/metal/bindgen/arguments.rs
index 052470d82..3a2eec622 100644
--- a/crates/uzu-engine/build/metal/bindgen/arguments.rs
+++ b/crates/uzu-engine/build/metal/bindgen/arguments.rs
@@ -4,7 +4,7 @@ use quote::{format_ident, quote};
use syn::{Expr, Ident, Type};
use crate::{
- common::enum_paths::EnumPaths,
+ common::{enum_paths::EnumPaths, expr_rewrite::rewrite_paths_with},
metal::{
ast::{
MetalArgument, MetalArgumentType, MetalBufferAccess, MetalConstantType, MetalGroupsType, MetalKernelInfo,
@@ -205,11 +205,26 @@ impl ArgumentEmission {
Some(quote! { #field_name: bool })
}
- pub fn struct_initializer(&self) -> Option<TokenStream> {
+ pub fn struct_initializer(
+ &self,
+ kernel: &MetalKernelInfo,
+ ) -> Option<TokenStream> {
let condition = self.condition()?;
let field_name = &condition.field_name;
- let rust_expression = &condition.rust_expression;
- Some(quote! { #field_name: #rust_expression })
+ let mut expression: Expr = syn::parse2(condition.rust_expression.clone()).unwrap();
+ rewrite_paths_with(&mut expression, |path| {
+ let ident = path.get_ident()?;
+ kernel
+ .arguments
+ .iter()
+ .any(|argument| {
+ ident == argument.name.as_ref()
+ && matches!(argument.argument_type, MetalArgumentType::Specialize(_))
+ && argument.condition.is_some()
+ })
+ .then(|| syn::parse_quote! { #ident.unwrap() })
+ });
+ Some(quote! { #field_name: #expression })
}
pub fn encode_argument_definition(&self) -> Option<TokenStream> {
diff --git a/crates/uzu-engine/build/metal/bindgen/mod.rs b/crates/uzu-engine/build/metal/bindgen/mod.rs
index fd6d8120b..df497d193 100644
--- a/crates/uzu-engine/build/metal/bindgen/mod.rs
+++ b/crates/uzu-engine/build/metal/bindgen/mod.rs
@@ -42,7 +42,7 @@ pub fn bindgen(
let conditional_buffer_fields: Vec<TokenStream> =
argument_emissions.iter().filter_map(|argument| argument.struct_field()).collect();
let conditional_buffer_initializers: Vec<TokenStream> =
- argument_emissions.iter().filter_map(|argument| argument.struct_initializer()).collect();
+ argument_emissions.iter().filter_map(|argument| argument.struct_initializer(kernel)).collect();
let mut encode_argument_definitions: Vec<TokenStream> =
argument_emissions.iter().filter_map(|argument| argument.encode_argument_definition()).collect();
let encode_deconstructs: Vec<TokenStream> =
@@ -61,6 +61,7 @@ pub fn bindgen(
let entry_name = dynamic_mangle(kernel_name, variant_kernel_format);
let specialize_arguments = specialize_emission.constructor_arguments();
+ let specialization_validation = &specialize_emission.presence_checks;
let specialize::RetainedSpecializations {
wrapper_fields: retained_specialization_fields,
wrapper_initializers: retained_specialization_initializers,
@@ -104,6 +105,7 @@ pub fn bindgen(
#(, #variant_constructor_arguments)*
#(, #specialize_arguments)*
) -> Result<Self, MetalError> {
+ #(#specialization_validation)*
let entry_name = #entry_name;
#function_constants_initialization
let pipeline = context.compute_pipeline_state(#library_data, #library_compressed, #cache_key, &entry_name, #function_constants_argument)?;
diff --git a/crates/uzu-engine/build/metal/bindgen/specialize.rs b/crates/uzu-engine/build/metal/bindgen/specialize.rs
index f39f4f72b..dc3d3c937 100644
--- a/crates/uzu-engine/build/metal/bindgen/specialize.rs
+++ b/crates/uzu-engine/build/metal/bindgen/specialize.rs
@@ -7,7 +7,7 @@ use syn::{Ident, Type};
use super::super::{
ast::{MetalArgumentType, MetalKernelInfo},
- enum_path_rewrite::gpu_type_kind_for_c_type,
+ enum_path_rewrite::{gpu_type_kind_for_c_type, rewrite_for_rust},
};
use crate::common::enum_paths::{EnumPaths, GpuTypeKind};
@@ -22,10 +22,12 @@ struct SpecializeArgument {
rust_type: Type,
function_constant_index: usize,
lowering: SpecializeLowering,
+ optional: bool,
}
pub struct SpecializeEmission {
arguments: Vec<SpecializeArgument>,
+ pub presence_checks: Vec<TokenStream>,
}
pub struct RetainedSpecializations {
@@ -39,6 +41,7 @@ pub fn parse(
kernel_name: &str,
enum_paths: &EnumPaths,
) -> Result<SpecializeEmission> {
+ let mut presence_checks = Vec::new();
let arguments = kernel
.arguments
.iter()
@@ -58,17 +61,25 @@ pub fn parse(
Some(GpuTypeKind::OptionSet) => SpecializeLowering::OptionSet,
None => SpecializeLowering::Direct,
};
+ if let Some(condition) = argument.condition.as_deref() {
+ let condition = rewrite_for_rust(enum_paths, condition)?;
+ presence_checks.push(quote! {
+ assert_eq!(#name.is_some(), #condition, concat!("invalid presence for specialization ", stringify!(#name)));
+ });
+ }
Ok(SpecializeArgument {
name,
rust_type,
function_constant_index,
lowering,
+ optional: argument.condition.is_some(),
})
})
.collect::<Result<_>>()?;
Ok(SpecializeEmission {
arguments,
+ presence_checks,
})
}
@@ -120,7 +131,7 @@ impl SpecializeEmission {
.map(|argument| {
let name = &argument.name;
let index = argument.function_constant_index;
- match &argument.lowering {
+ let assignment = match &argument.lowering {
SpecializeLowering::Direct => {
quote! { function_constants.set_value(&#name, #index); }
},
@@ -130,6 +141,11 @@ impl SpecializeEmission {
SpecializeLowering::OptionSet => {
quote! { function_constants.set_value(&#name.bits(), #index); }
},
+ };
+ if argument.optional {
+ quote! { if let Some(#name) = #name { #assignment } }
+ } else {
+ assignment
}
})
.collect();
diff --git a/crates/uzu-engine/build/metal/wrapper.rs b/crates/uzu-engine/build/metal/wrapper.rs
index cbd11548f..13ba9f409 100644
--- a/crates/uzu-engine/build/metal/wrapper.rs
+++ b/crates/uzu-engine/build/metal/wrapper.rs
@@ -71,7 +71,7 @@ impl SpecializeBinding<'_> {
}
fn alias_target(&self) -> String {
- if self.enum_type.is_some() {
+ if self.enum_type.is_some() || self.argument.condition.is_some() {
self.typed_name()
} else {
self.slot_name()
@@ -116,7 +116,14 @@ fn kernel_header(
}
for binding in bindings.iter() {
- if let Some(enum_type) = &binding.enum_type {
+ let ty = binding.argument.c_type.trim_start_matches("const ").trim();
+ let slot = binding.slot_name();
+ if binding.argument.condition.is_some() {
+ lines.push(format!(
+ "constant {ty} {name} = is_function_constant_defined({slot}) ? static_cast<{ty}>({slot}) : static_cast<{ty}>(0);",
+ name = binding.typed_name(),
+ ));
+ } else if let Some(enum_type) = &binding.enum_type {
lines.push(format!(
"constant {ty} {name} = {ty}({slot});",
ty = enum_type,
diff --git a/crates/uzu-engine/src/backends/metal/kernel/common/dsl.h b/crates/uzu-engine/src/backends/metal/kernel/common/dsl.h
index a0375fe9c..3795eda56 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/common/dsl.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/common/dsl.h
@@ -19,6 +19,7 @@ using namespace metal;
#define KERNEL(NAME) DSL_META("dsl.kernel") void NAME
#define SPECIALIZE DSL_META("dsl.specialize")
+#define SPECIALIZE_IF(EXPR) DSL_META("dsl.specialize_if", DSL_XSTR(EXPR))
#define OPTIONAL(EXPR) DSL_META("dsl.optional", DSL_XSTR(EXPR))
#define AXIS(TDS, TPG) DSL_META("dsl.axis", DSL_XSTR(TDS), DSL_XSTR(TPG))