Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

dslify-token-copy (#171)

Aleksandr Golokoz79d4ba240ad9
diff --git a/crates/uzu/build/metal/bindgen.rs b/crates/uzu/build/metal/bindgen.rs
index ece391bc5..cf6db661e 100644
--- a/crates/uzu/build/metal/bindgen.rs
+++ b/crates/uzu/build/metal/bindgen.rs
@@ -17,6 +17,7 @@ pub fn bindgen(
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");
@@ -33,10 +34,10 @@ pub fn bindgen(
(
variant_names.iter().map(|name| quote! { #[allow(non_snake_case)] #name: crate::DataType }).collect(),
- quote! { &format!(#kernel_format, #kernel_name #(, KernelDataType::from(#variant_names).function_name_suffix())*) },
+ quote! { &format!(#kernel_format, #entry_name #(, KernelDataType::from(#variant_names).function_name_suffix())*) },
)
} else {
- (Vec::new(), quote! { #kernel_name })
+ (Vec::new(), quote! { #entry_name })
};
let base_index = specialize_indices.get(&kernel.name).copied();
diff --git a/crates/uzu/build/metal/wrapper.rs b/crates/uzu/build/metal/wrapper.rs
index 9e0825467..e52ac26f7 100644
--- a/crates/uzu/build/metal/wrapper.rs
+++ b/crates/uzu/build/metal/wrapper.rs
@@ -73,11 +73,11 @@ fn kernel_wrappers(
} {
let (wrapper_name, underlying_name) = if let Some(type_variant) = &type_variant {
(
- format!("{}_{}", kernel.name, type_variant.iter().map(|(_k, v)| v).join("_")),
+ format!("__dsl_entry_{}_{}", kernel.name, type_variant.iter().map(|(_k, v)| v).join("_")),
format!("{}<{}>", kernel.name, type_variant.iter().map(|(_k, v)| v).join(", ")),
)
} else {
- (kernel.name.to_string(), kernel.name.to_string())
+ (format!("__dsl_entry_{}", kernel.name), kernel.name.to_string())
};
let max_total_threads_per_threadgroup = kernel
diff --git a/crates/uzu/src/backends/metal/kernel/mod.rs b/crates/uzu/src/backends/metal/kernel/mod.rs
index 52076d847..060187e34 100644
--- a/crates/uzu/src/backends/metal/kernel/mod.rs
+++ b/crates/uzu/src/backends/metal/kernel/mod.rs
@@ -17,7 +17,6 @@ pub mod moe;
pub mod quant_matmul;
pub mod short_conv;
pub mod ssm;
-pub mod token_copy;
pub use attention::{
AttentionError, AttentionKernel, AttentionKernelVariant, AttentionSinglePassArguments, AttentionTwoPassArguments,
@@ -35,7 +34,6 @@ pub use short_conv::{ShortConvDecodeArguments, ShortConvKernel, ShortConvKernelE
pub use ssm::{
Conv1dPackArguments, Conv1dScanArguments, Conv1dScanKernel, SSDPrefillArguments, SSDPrefillMode, SSMKernelError,
};
-pub use token_copy::TokenCopyKernel;
pub mod media {
pub use super::media_kernels::{ExtractImagePatches, ScalePadNormalizeImage};
diff --git a/crates/uzu/src/backends/metal/kernel/token_copy/mod.rs b/crates/uzu/src/backends/metal/kernel/token_copy/mod.rs
deleted file mode 100644
index 676c90d45..000000000
--- a/crates/uzu/src/backends/metal/kernel/token_copy/mod.rs
+++ /dev/null
@@ -1,55 +0,0 @@
-use crate::backends::metal::{
- MTLBuffer, MTLComputeCommandEncoder, MTLComputePipelineState, MTLContext, MTLError, MTLSize, ProtocolObject,
- Retained,
-};
-
-/// Kernel for copying sampled tokens in async pipeline.
-/// Two operations:
-/// 1. copy_to_token_ids: u32 → u64 for next forward pass embedding
-/// 2. copy_to_results: u32 → u32[offset] for callback to read
-pub struct TokenCopyKernel {
- copy_to_token_ids: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
- copy_to_results: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
-}
-
-impl TokenCopyKernel {
- pub fn new(context: &MTLContext) -> Result<Self, MTLError> {
- let copy_to_token_ids = context.compute_pipeline_state("copy_sampled_token", None)?;
- let copy_to_results = context.compute_pipeline_state("copy_token_to_results", None)?;
-
- Ok(Self {
- copy_to_token_ids,
- copy_to_results,
- })
- }
-
- /// Copies sampling_output[0] (u32) → token_ids[0] (u64)
- /// For next forward pass to read the token.
- pub fn encode_to_token_ids(
- &self,
- sampling_output: &Retained<ProtocolObject<dyn MTLBuffer>>,
- token_ids: &Retained<ProtocolObject<dyn MTLBuffer>>,
- encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,
- ) {
- encoder.set_compute_pipeline_state(&self.copy_to_token_ids);
- encoder.set_buffer(Some(sampling_output), 0, 0);
- encoder.set_buffer(Some(token_ids), 0, 1);
- encoder.dispatch_threads(MTLSize::new(1, 1, 1), MTLSize::new(1, 1, 1));
- }
-
- /// Copies sampling_output[0] (u32) → results[offset] (u32)
- /// For callback to read without race condition.
- pub fn encode_to_results(
- &self,
- sampling_output: &Retained<ProtocolObject<dyn MTLBuffer>>,
- results: &Retained<ProtocolObject<dyn MTLBuffer>>,
- pass_idx: usize,
- encoder: &ProtocolObject<dyn MTLComputeCommandEncoder>,
- ) {
- let offset = (pass_idx * std::mem::size_of::<u32>()) as usize;
- encoder.set_compute_pipeline_state(&self.copy_to_results);
- encoder.set_buffer(Some(sampling_output), 0, 0);
- encoder.set_buffer(Some(results), offset, 1);
- encoder.dispatch_threads(MTLSize::new(1, 1, 1), MTLSize::new(1, 1, 1));
- }
-}
diff --git a/crates/uzu/src/backends/metal/kernel/token_copy/token_copy.metal b/crates/uzu/src/backends/metal/kernel/token_copy/token_copy.metal
index 9b2a1a8e8..ea916f2e9 100644
--- a/crates/uzu/src/backends/metal/kernel/token_copy/token_copy.metal
+++ b/crates/uzu/src/backends/metal/kernel/token_copy/token_copy.metal
@@ -1,28 +1,14 @@
#include <metal_stdlib>
-using namespace metal;
+#include "../definitions.metal"
/// Copies a single sampled token (u32) to the token_ids buffer (u64).
/// Used in async pipeline to pass sampled token to next forward pass.
-[[max_total_threads_per_threadgroup(1)]]
-kernel void copy_sampled_token(
- device const uint32_t* src [[buffer(0)]],
- device uint64_t* dst [[buffer(1)]],
- uint idx [[thread_position_in_grid]]
-) {
- if (idx == 0) {
- dst[0] = static_cast<uint64_t>(src[0]);
- }
+KERNEL(TokenCopySampled)(device const uint32_t* src, device uint64_t* dst) {
+ dst[0] = static_cast<uint64_t>(src[0]);
}
/// Copies a single sampled token (u32) to an indexed results buffer (u32).
/// Used in async pipeline to store result for callback access.
-[[max_total_threads_per_threadgroup(1)]]
-kernel void copy_token_to_results(
- device const uint32_t* src [[buffer(0)]],
- device uint32_t* dst [[buffer(1)]],
- uint idx [[thread_position_in_grid]]
-) {
- if (idx == 0) {
- dst[0] = src[0];
- }
+KERNEL(TokenCopyToResults)(device const uint32_t* src, device uint32_t* dst) {
+ dst[0] = src[0];
}
diff --git a/crates/uzu/src/backends/metal/language_model_generator_context.rs b/crates/uzu/src/backends/metal/language_model_generator_context.rs
index c997bf438..73b1fe021 100644
--- a/crates/uzu/src/backends/metal/language_model_generator_context.rs
+++ b/crates/uzu/src/backends/metal/language_model_generator_context.rs
@@ -6,17 +6,17 @@ use std::{
rc::Rc,
};
-use super::{
- Decoder, KVCacheUpdate, KernelDataType, MTLContext, Metal, compilation_parameters::CompilationConfig,
- kernel::TokenCopyKernel,
-};
+use super::{Decoder, KVCacheUpdate, KernelDataType, MTLContext, Metal, compilation_parameters::CompilationConfig};
use crate::{
DataType,
backends::{
- common::{Context, kernel::MaskUpdateKernel},
+ common::{
+ Context,
+ kernel::{MaskUpdateKernel, TokenCopySampledKernel, TokenCopyToResultsKernel},
+ },
metal::{
MTLBuffer, MTLCommandBuffer, MTLCommandQueue, MTLDeviceExt, MTLEvent, ProtocolObject, Retained,
- kernel::dsl::MaskUpdateMetalKernel,
+ kernel::dsl::{MaskUpdateMetalKernel, TokenCopySampledMetalKernel, TokenCopyToResultsMetalKernel},
},
},
config::{DecoderConfig, LanguageModelConfig, ModelMetadata},
@@ -143,8 +143,9 @@ pub struct LanguageModelGeneratorContext {
pub gpu_sampler: Sampling<Metal>,
pub seed: PRng,
- /// Kernel for copying sampled tokens in async pipeline
- pub token_copy: TokenCopyKernel,
+ /// Kernels for copying sampled tokens in async pipeline
+ pub token_copy_sampled: TokenCopySampledMetalKernel,
+ pub token_copy_results: TokenCopyToResultsMetalKernel,
/// Kernel for updating attention mask between async passes
pub mask_update: Option<MaskUpdateMetalKernel>,
/// Pre-allocated buffers for async generation
@@ -215,7 +216,10 @@ impl LanguageModelGeneratorContext {
Sampling::<Metal>::new(&context, intermediate_data_type, max_suffix_length, decoder_config.vocab_size)
.map_err(|_| Error::UnableToCreateMetalContext)?;
- let token_copy = TokenCopyKernel::new(&context).map_err(|_| Error::UnableToCreateMetalContext)?;
+ let token_copy_sampled =
+ TokenCopySampledMetalKernel::new(&context).map_err(|_| Error::UnableToCreateMetalContext)?;
+ let token_copy_results =
+ TokenCopyToResultsMetalKernel::new(&context).map_err(|_| Error::UnableToCreateMetalContext)?;
// Create mask update kernel if model has attention layers
let mask_update = if decoder_config.has_attention_layers() {
@@ -245,12 +249,13 @@ impl LanguageModelGeneratorContext {
kv_cache_update,
gpu_sampler,
seed,
- token_copy,
+ token_copy_sampled,
+ token_copy_results,
mask_update,
async_buffers,
};
- return Ok(context);
+ Ok(context)
}
pub fn reset_command_buffer(&mut self) {
diff --git a/crates/uzu/src/language_model/language_model_generator.rs b/crates/uzu/src/language_model/language_model_generator.rs
index 953250e59..affec9213 100644
--- a/crates/uzu/src/language_model/language_model_generator.rs
+++ b/crates/uzu/src/language_model/language_model_generator.rs
@@ -12,7 +12,7 @@ use super::{
};
use crate::{
backends::{
- common::kernel::MaskUpdateKernel,
+ common::kernel::{MaskUpdateKernel, TokenCopySampledKernel, TokenCopyToResultsKernel},
metal::{
MTLBuffer, MTLCommandBuffer, MTLCommandBufferExt, MTLCommandBufferHandler, MTLCommandEncoder,
MTLCommandQueue, Metal,
@@ -482,8 +482,9 @@ impl LanguageModelGenerator {
let encoder =
root_command_buffer.new_compute_command_encoder().expect("Failed to create compute command encoder");
- self.context.token_copy.encode_to_token_ids(&sampling_output_buffer, &token_ids_buffer, &encoder);
- self.context.token_copy.encode_to_results(&sampling_output_buffer, &results_buffer, slot, &encoder);
+ self.context.token_copy_sampled.encode(&sampling_output_buffer, &token_ids_buffer, &encoder);
+ let results_offset = slot * std::mem::size_of::<u32>();
+ self.context.token_copy_results.encode(&sampling_output_buffer, (&results_buffer, results_offset), &encoder);
encoder.end_encoding();
// Scatter + register for all transformer layers