Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

dsl value variants (#187)

uuuvn9142b3c416b1
diff --git a/crates/uzu/build/common/kernel.rs b/crates/uzu/build/common/kernel.rs
index 36fe4f2ed..53f9bf08c 100644
--- a/crates/uzu/build/common/kernel.rs
+++ b/crates/uzu/build/common/kernel.rs
@@ -14,8 +14,8 @@ pub struct KernelArgument {
#[derive(PartialEq, Debug)]
pub enum KernelParameterType {
- DType,
- Specialization(Box<str>),
+ Type,
+ Value(Box<str>),
}
#[derive(PartialEq, Debug)]
diff --git a/crates/uzu/build/common/mangling.rs b/crates/uzu/build/common/mangling.rs
new file mode 100644
index 000000000..b017e4f5b
--- /dev/null
+++ b/crates/uzu/build/common/mangling.rs
@@ -0,0 +1,33 @@
+use std::iter::repeat_n;
+
+use itertools::Itertools;
+use proc_macro2::TokenStream;
+use quote::quote;
+
+pub fn static_mangle(
+ function_name: impl AsRef<str>,
+ variant: impl IntoIterator<Item = impl AsRef<str>>,
+) -> String {
+ format!(
+ "_D{}{}{}",
+ &function_name.as_ref().len().to_string(),
+ function_name.as_ref(),
+ variant.into_iter().map(|v| format!("S{}V{}", v.as_ref().len(), v.as_ref().replace('-', "n"))).join("")
+ )
+}
+
+pub fn dynamic_mangle(
+ function_name: impl AsRef<str>,
+ variant: impl IntoIterator<Item = TokenStream>,
+) -> TokenStream {
+ let variant = variant.into_iter().collect::<Vec<TokenStream>>();
+
+ let format_string = format!(
+ "_D{}{}{}",
+ &function_name.as_ref().len().to_string(),
+ function_name.as_ref(),
+ repeat_n("S{}V{}", variant.len()).join("")
+ );
+
+ quote! { format!(#format_string #(, #variant.len(), #variant.replace('-', "n"))*) }
+}
diff --git a/crates/uzu/build/common/mod.rs b/crates/uzu/build/common/mod.rs
index a6c6718d7..c7b97f162 100644
--- a/crates/uzu/build/common/mod.rs
+++ b/crates/uzu/build/common/mod.rs
@@ -4,4 +4,5 @@ pub mod compiler;
pub mod envs;
pub mod kernel;
pub mod logging;
+pub mod mangling;
pub mod traitgen;
diff --git a/crates/uzu/build/common/traitgen.rs b/crates/uzu/build/common/traitgen.rs
index e0eea2f13..537c7f9c4 100644
--- a/crates/uzu/build/common/traitgen.rs
+++ b/crates/uzu/build/common/traitgen.rs
@@ -19,8 +19,8 @@ pub fn traitgen(kernel: &Kernel) -> (TokenStream, TokenStream) {
let params = kernel.parameters.iter().map(|p| {
let name = format_ident!("{}", p.name.as_ref());
let ty = match &p.ty {
- KernelParameterType::DType => quote! { DataType },
- KernelParameterType::Specialization(ty) => {
+ KernelParameterType::Type => quote! { DataType },
+ KernelParameterType::Value(ty) => {
let ty: Type = syn::parse_str(ty.as_ref()).unwrap();
quote! { #ty }
},
diff --git a/crates/uzu/build/metal/ast.rs b/crates/uzu/build/metal/ast.rs
index 2374a2d51..36b9d0c5f 100644
--- a/crates/uzu/build/metal/ast.rs
+++ b/crates/uzu/build/metal/ast.rs
@@ -6,7 +6,7 @@ use crate::common::kernel::{Kernel, KernelArgument, KernelArgumentType, KernelPa
pub type MetalAstNode = clang_ast::Node<MetalAstKind>;
#[derive(Debug, Clone, Deserialize)]
-pub struct ParmVarDeclType {
+pub struct MetalAstType {
#[serde(rename = "qualType")]
qual_type: Box<str>,
#[serde(rename = "desugaredQualType")]
@@ -20,6 +20,11 @@ pub enum MetalAstKind {
TemplateTypeParmDecl {
name: Option<Box<str>>,
},
+ NonTypeTemplateParmDecl {
+ name: Option<Box<str>>,
+ #[serde(rename = "type")]
+ ty: MetalAstType,
+ },
FunctionDecl {
name: Box<str>,
},
@@ -27,7 +32,7 @@ pub enum MetalAstKind {
name: Option<Box<str>>,
range: clang_ast::SourceRange,
#[serde(rename = "type")]
- ty: ParmVarDeclType,
+ ty: MetalAstType,
},
AnnotateAttr,
ConstantExpr,
@@ -141,7 +146,7 @@ impl MetalArgument {
let MetalAstKind::ParmVarDecl {
name,
range,
- ty: ParmVarDeclType {
+ ty: MetalAstType {
qual_type,
desugared_qual_type,
},
@@ -269,7 +274,7 @@ impl MetalArgument {
match self.argument_type().unwrap() {
MetalArgumentType::Specialize(ty) => Some(KernelParameter {
name: self.name.clone(),
- ty: KernelParameterType::Specialization(ty),
+ ty: KernelParameterType::Value(ty),
}),
_ => None,
}
@@ -277,16 +282,26 @@ impl MetalArgument {
}
#[derive(Debug, Serialize, Deserialize)]
-pub struct MetalTypeParameter {
+pub enum MetalTemplateParameterType {
+ Type,
+ Value(Box<str>),
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct MetalTemplateParameter {
pub name: Box<str>,
+ pub ty: MetalTemplateParameterType,
pub variants: Box<[Box<str>]>,
}
-impl MetalTypeParameter {
+impl MetalTemplateParameter {
fn to_parameter(&self) -> KernelParameter {
KernelParameter {
name: self.name.clone(),
- ty: KernelParameterType::DType,
+ ty: match &self.ty {
+ MetalTemplateParameterType::Type => KernelParameterType::Type,
+ MetalTemplateParameterType::Value(ty) => KernelParameterType::Value(ty.clone()),
+ },
}
}
}
@@ -295,7 +310,7 @@ impl MetalTypeParameter {
pub struct MetalKernelInfo {
pub name: Box<str>,
pub arguments: Box<[MetalArgument]>,
- pub variants: Option<Box<[MetalTypeParameter]>>,
+ pub variants: Option<Box<[MetalTemplateParameter]>>,
}
impl MetalKernelInfo {
@@ -385,7 +400,14 @@ impl MetalKernelInfo {
name,
} => {
let name = name.context("template parameter missing name")?;
- template_parameters.push(name);
+ template_parameters.push((name, None));
+ },
+ MetalAstKind::NonTypeTemplateParmDecl {
+ name,
+ ty,
+ } => {
+ let name = name.context("template parameter missing name")?;
+ template_parameters.push((name, Some(ty)));
},
MetalAstKind::FunctionDecl {
name: _,
@@ -443,20 +465,17 @@ impl MetalKernelInfo {
return Ok(None);
}
- let variants: Box<[MetalTypeParameter]> = annotations
+ let variants: Box<[_]> = annotations
.iter()
.filter(|(k, _)| k.as_ref() == "dsl.variants")
.map(|(_, v)| {
- let [typename, variant_values] = v.as_ref() else {
+ let [variant_name, variant_values] = v.as_ref() else {
bail!("malformed dsl.variants annotation");
};
- let variants = variant_values.split(',').map(|v| v.trim().into()).collect::<Box<[Box<str>]>>();
+ let variant_values = variant_values.split(',').map(|v| v.trim().into()).collect::<Box<[Box<str>]>>();
- Ok(MetalTypeParameter {
- name: typename.clone(),
- variants,
- })
+ Ok((variant_name.clone(), variant_values))
})
.collect::<anyhow::Result<_>>()?;
@@ -464,18 +483,35 @@ impl MetalKernelInfo {
bail!("mismatch between AST nodes and variants annotation");
}
- if is_template {
- let template_names = template_parameters.iter().map(|name| name.as_ref()).collect::<Vec<_>>();
- let variant_names = variants.iter().map(|variant| variant.name.as_ref()).collect::<Vec<_>>();
+ let variants = if is_template {
+ let template_names = template_parameters.iter().map(|(name, _)| name.as_ref()).collect::<Vec<_>>();
+ let variant_names = variants.iter().map(|(name, _)| name.as_ref()).collect::<Vec<_>>();
if template_names != variant_names {
bail!("template parameters {:?} do not match dsl.variants order {:?}", template_names, variant_names);
}
- }
- let variants = if variants.is_empty() {
- None
+ Some(
+ template_parameters
+ .into_iter()
+ .zip(variants.into_iter())
+ .map(|((name, ty), (v_name, variants))| {
+ assert_eq!(name, v_name);
+
+ Ok(MetalTemplateParameter {
+ name,
+ ty: match ty {
+ None => MetalTemplateParameterType::Type,
+ Some(ntt) => MetalTemplateParameterType::Value(MetalArgument::scalar_type_to_rust(
+ ntt.desugared_qual_type.unwrap_or(ntt.qual_type).as_ref(),
+ )?),
+ },
+ variants,
+ })
+ })
+ .collect::<anyhow::Result<_>>()?,
+ )
} else {
- Some(variants)
+ None
};
let arguments = arg_nodes
diff --git a/crates/uzu/build/metal/bindgen.rs b/crates/uzu/build/metal/bindgen.rs
index e021590e6..e16857e28 100644
--- a/crates/uzu/build/metal/bindgen.rs
+++ b/crates/uzu/build/metal/bindgen.rs
@@ -4,20 +4,22 @@ use anyhow::Context;
use itertools::Itertools;
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
-use syn::{Lifetime, LitInt, Type};
+use syn::{Ident, Lifetime, LitInt, Type};
use super::{
ast::{MetalArgumentType, MetalConstantType, MetalKernelInfo},
wrapper::SpecializeBaseIndices,
};
-use crate::metal::ast::MetalGroupsType;
+use crate::{
+ common::mangling::dynamic_mangle,
+ metal::ast::{MetalGroupsType, MetalTemplateParameterType},
+};
pub fn bindgen(
kernel: &MetalKernelInfo,
specialize_indices: &SpecializeBaseIndices,
) -> anyhow::Result<(TokenStream, TokenStream)> {
let kernel_name = kernel.name.as_ref();
- let entry_name = format!("__dsl_entry_{kernel_name}");
let trait_name = format_ident!("{kernel_name}Kernel");
let struct_name = format_ident!("{kernel_name}MetalKernel");
@@ -27,19 +29,28 @@ pub fn bindgen(
};
let (variants_extra_arguments, variants_kernel_format) = if let Some(variants) = &kernel.variants {
- let variant_names =
- variants.iter().map(|type_parameter| format_ident!("{}", type_parameter.name.as_ref())).collect::<Vec<_>>();
-
- let kernel_format = repeat_n("{}", variant_names.len() + 1).join("_");
-
- (
- variant_names.iter().map(|name| quote! { #[allow(non_snake_case)] #name: crate::DataType }).collect(),
- quote! { &format!(#kernel_format, #entry_name #(, #variant_names.metal_type())*) },
- )
+ variants
+ .iter()
+ .map(|variant| {
+ let name = Ident::new(variant.name.as_ref(), Span::call_site());
+
+ match &variant.ty {
+ MetalTemplateParameterType::Type => {
+ Ok((quote! { #[allow(non_snake_case)] #name: crate::DataType }, quote! { #name.metal_type() }))
+ },
+ MetalTemplateParameterType::Value(ty) => {
+ let ty: Type = syn::parse_str(ty.as_ref())?;
+ Ok((quote! { #[allow(non_snake_case)] #name: #ty }, quote! { #name.to_string() }))
+ },
+ }
+ })
+ .collect::<anyhow::Result<_>>()?
} else {
- (Vec::new(), quote! { #entry_name })
+ (Vec::new(), Vec::new())
};
+ let entry_name = dynamic_mangle(kernel.name.as_ref(), variants_kernel_format);
+
let base_index = specialize_indices.get(&kernel.name).copied();
let (specialize_args, specialize_setup): (Vec<TokenStream>, Vec<TokenStream>) = kernel
.arguments
@@ -295,7 +306,7 @@ pub fn bindgen(
fn new(context: &MTLContext #(, #variants_extra_arguments)* #(, #specialize_args)*) -> Result<Self, MTLError> {
#function_constants_init
- let pipeline = context.compute_pipeline_state(#variants_kernel_format, #function_constants_arg)?;
+ let pipeline = context.compute_pipeline_state(&#entry_name, #function_constants_arg)?;
Ok(Self { pipeline #(, #conditional_buffer_sets)* })
}
diff --git a/crates/uzu/build/metal/wrapper.rs b/crates/uzu/build/metal/wrapper.rs
index 68b9dd572..a54488126 100644
--- a/crates/uzu/build/metal/wrapper.rs
+++ b/crates/uzu/build/metal/wrapper.rs
@@ -4,6 +4,7 @@ use anyhow::bail;
use itertools::Itertools;
use super::ast::{MetalArgumentType, MetalKernelInfo};
+use crate::common::mangling::static_mangle;
pub type SpecializeBaseIndices = HashMap<Box<str>, usize>;
@@ -73,11 +74,11 @@ fn kernel_wrappers(
} {
let (wrapper_name, underlying_name) = if let Some(type_variant) = &type_variant {
(
- format!("__dsl_entry_{}_{}", kernel.name, type_variant.iter().map(|(_k, v)| v).join("_")),
+ static_mangle(kernel.name.as_ref(), type_variant.iter().map(|(_k, v)| v.as_str())),
format!("{}<{}>", kernel.name, type_variant.iter().map(|(_k, v)| v).join(", ")),
)
} else {
- (format!("__dsl_entry_{}", kernel.name), kernel.name.to_string())
+ (static_mangle(kernel.name.as_ref(), [] as [&str; 0]), kernel.name.to_string())
};
let max_total_threads_per_threadgroup = kernel
diff --git a/crates/uzu/src/forward_pass/scratch_buffers.rs b/crates/uzu/src/forward_pass/scratch_buffers.rs
index f41e16520..6789482f1 100644
--- a/crates/uzu/src/forward_pass/scratch_buffers.rs
+++ b/crates/uzu/src/forward_pass/scratch_buffers.rs
@@ -196,14 +196,12 @@ impl<B: Backend> ScratchBuffers<B> {
.map(|max_routed| alloc(&model_shape.moe_hidden_shape(max_routed), DataType::F32, "moe_hidden")),
moe_two_pass_row_expert_map: moe_max_routed
.map(|max_routed| alloc(&[max_routed], DataType::U32, "moe_two_pass_row_expert_map")),
- moe_tile_counts: moe
- .map(|moe| {
- alloc(&model_shape.moe_counts_shape(moe.num_routed_experts), DataType::U32, "moe_tile_counts")
- }),
- moe_tile_offsets: moe
- .map(|moe| {
- alloc(&model_shape.moe_offsets_shape(moe.num_routed_experts), DataType::U32, "moe_tile_offsets")
- }),
+ moe_tile_counts: moe.map(|moe| {
+ alloc(&model_shape.moe_counts_shape(moe.num_routed_experts), DataType::U32, "moe_tile_counts")
+ }),
+ moe_tile_offsets: moe.map(|moe| {
+ alloc(&model_shape.moe_offsets_shape(moe.num_routed_experts), DataType::U32, "moe_tile_offsets")
+ }),
moe_tile_map: moe_max_routed
.map(|max_routed| alloc(&model_shape.moe_tile_map_shape(max_routed), DataType::U32, "moe_tile_map")),
moe_total_tiles: moe.map(|_| alloc(&model_shape.moe_total_tiles_shape(), DataType::U32, "moe_total_tiles")),
diff --git a/crates/uzu/src/forward_pass/state/language_model_generator_aux_buffers.rs b/crates/uzu/src/forward_pass/state/language_model_generator_aux_buffers.rs
index be01197d7..fa0c0beee 100644
--- a/crates/uzu/src/forward_pass/state/language_model_generator_aux_buffers.rs
+++ b/crates/uzu/src/forward_pass/state/language_model_generator_aux_buffers.rs
@@ -100,11 +100,9 @@ impl<B: Backend> LanguageModelGeneratorAuxBuffers<B> {
.as_ref()
.zip(model_shape.ssm_z_shape(suffix_length))
.map(|(buf, shape)| buf.view(&shape)),
- moe_topk_ids: moe
- .zip(scratch.moe_topk_ids.as_ref())
- .map(|(moe, buf)| {
- buf.view(&model_shape.moe_topk_ids_shape(suffix_length, moe.num_active_routed_experts))
- }),
+ moe_topk_ids: moe.zip(scratch.moe_topk_ids.as_ref()).map(|(moe, buf)| {
+ buf.view(&model_shape.moe_topk_ids_shape(suffix_length, moe.num_active_routed_experts))
+ }),
moe_topk_probs: moe.zip(scratch.moe_topk_probs.as_ref()).map(|(moe, buf)| {
buf.view(&model_shape.moe_topk_probs_shape(suffix_length, moe.num_active_routed_experts))
}),
@@ -121,11 +119,9 @@ impl<B: Backend> LanguageModelGeneratorAuxBuffers<B> {
moe_x_perm: max_routed
.zip(scratch.moe_x_perm.as_ref())
.map(|(max_routed, buf)| buf.view(&model_shape.moe_x_perm_shape(max_routed))),
- moe_tok2row: moe
- .zip(scratch.moe_tok2row.as_ref())
- .map(|(moe, buf)| {
- buf.view(&model_shape.moe_tok2row_shape(suffix_length, moe.num_active_routed_experts))
- }),
+ moe_tok2row: moe.zip(scratch.moe_tok2row.as_ref()).map(|(moe, buf)| {
+ buf.view(&model_shape.moe_tok2row_shape(suffix_length, moe.num_active_routed_experts))
+ }),
moe_y_partial: max_routed
.zip(scratch.moe_y_partial.as_ref())
.map(|(max_routed, buf)| buf.view(&model_shape.moe_y_partial_shape(max_routed))),