A high-performance inference engine for AI models
policy/sampling separation (#41)
uuuvn1601f2d6438a
diff --git a/crates/uzu/src/backends/metal/forward_pass/buffers.rs b/crates/uzu/src/backends/metal/forward_pass/buffers.rsindex 3e7c3e51f..2ed74ca5c 100644--- a/crates/uzu/src/backends/metal/forward_pass/buffers.rs+++ b/crates/uzu/src/backends/metal/forward_pass/buffers.rs@@ -18,6 +18,7 @@ pub struct ForwardPassBuffers {// 1-Dpub token_ids: MTLBuffer,pub token_positions: MTLBuffer,+ pub token_seeds: MTLBuffer,pub sampling_output: MTLBuffer,// 2-D@@ -89,6 +90,7 @@ impl ForwardPassBuffers {// 1-Dtoken_ids: alloc(&[max_suffix_len], DataType::U64),token_positions: alloc(&[max_suffix_len], DataType::I32),+ token_seeds: alloc(&[max_suffix_len], DataType::U64),sampling_output: alloc(&[max_suffix_len], DataType::U32),// 2-Ddiff --git a/crates/uzu/src/backends/metal/forward_pass/state.rs b/crates/uzu/src/backends/metal/forward_pass/state.rsindex 7efacb4d5..cf0b00503 100644--- a/crates/uzu/src/backends/metal/forward_pass/state.rs+++ b/crates/uzu/src/backends/metal/forward_pass/state.rs@@ -708,6 +708,8 @@ pub struct ForwardPassState {token_ids: ArrayCell,/// [suffix_length] - i32token_positions: ArrayCell,+ /// [suffix_length] - u64+ token_seeds: ArrayCell,/// [suffix_length, suffix_length + prefix_length]attention_bias: HashMap<Option<usize>, ArrayCell>,/// [suffix_length, vocabulary_size]@@ -732,6 +734,7 @@ impl ForwardPassState {shared_buffers: Rc<RefCell<SharedBuffers>>,token_ids: &[u64],token_positions: &[usize],+ token_seeds: &[u64],trace: bool,external_bias_fn: Option<&dyn Fn(usize, usize) -> bool>,) -> Self {@@ -787,6 +790,19 @@ impl ForwardPassState {);let token_positions_refcell = RefCell::new(token_positions_array);+ // --------------------+ // Token Seeds+ // --------------------+ let mut token_seeds_array = unsafe {+ MetalArray::new(+ scratch.token_seeds.clone(),+ &[suffix_length],+ DataType::U64,+ )+ };+ context.copy_from_view(&mut token_seeds_array, token_seeds.into());+ let token_seeds_refcell = RefCell::new(token_seeds_array);+// --------------------// Attention Bias// --------------------@@ -861,6 +877,7 @@ impl ForwardPassState {context,token_ids: token_ids_refcell,token_positions: token_positions_refcell,+ token_seeds: token_seeds_refcell,attention_bias,logits,kv_cache,@@ -879,6 +896,7 @@ impl ForwardPassState {match id {ArrayId::TokenIds => self.token_ids.clone(),ArrayId::TokenPositions => self.token_positions.clone(),+ ArrayId::TokenSeeds => self.token_seeds.clone(),ArrayId::Logits => self.logits.clone(),ArrayId::Main => self.aux_buffers.main.clone(),ArrayId::Shortcut => self.aux_buffers.shortcut.clone(),@@ -1078,6 +1096,7 @@ pub enum ArrayId {TokenIds,TokenPositions,Logits,+ TokenSeeds,Main,Shortcut,diff --git a/crates/uzu/src/backends/metal/kernel/rng.metal b/crates/uzu/src/backends/metal/kernel/rng.metalindex ec316f255..565a901df 100644--- a/crates/uzu/src/backends/metal/kernel/rng.metal+++ b/crates/uzu/src/backends/metal/kernel/rng.metal@@ -50,7 +50,7 @@ inline void curand_philox4x32_10(thread uint* ctr, thread uint* key, thread uintuint local_key[2] = {key[0], key[1]};// 10 rounds- philox4x32round(local_ctr, local_key); // 1+ philox4x32round(local_ctr, local_key); // 1philox4x32bumpkey(local_key); philox4x32round(local_ctr, local_key); // 2philox4x32bumpkey(local_key); philox4x32round(local_ctr, local_key); // 3philox4x32bumpkey(local_key); philox4x32round(local_ctr, local_key); // 4@@ -107,4 +107,4 @@ inline float uniform_float(thread PhiloxState* state) {return float(philox_next(state)) * (1.0f/4294967296.0f); /* (0,1) */}-#endif /* rng_metal */\ No newline at end of file+#endif /* rng_metal */diff --git a/crates/uzu/src/backends/metal/kernel/sampling/categorical.metal b/crates/uzu/src/backends/metal/kernel/sampling/categorical.metaldeleted file mode 100644index f2b604060..000000000--- a/crates/uzu/src/backends/metal/kernel/sampling/categorical.metal+++ /dev/null@@ -1,389 +0,0 @@-#include <metal_stdlib>-#include <metal_atomic>-#include "../definitions.metal"-#include "../rng.metal"-using namespace metal;--#define BLOCK_SIZE 1024-#define GRAIN_SIZE 4--struct CategoricalTempStorage {- _atomic<uint> sampled_id;- float random_threshold;-};--template<typename T>-void categorical_sampling_kernel_impl(- const device T* logits,- device uint* out_ids,- constant uint& batch,- constant uint& vocab,- constant float& temperature,- constant uint64_t& seed,- threadgroup CategoricalTempStorage& ts,- threadgroup float* shared_max,- threadgroup float* shared_sum,- uint batch_idx,- uint lid)-{- if (batch_idx >= batch) return;-- const uint stride_elems = BLOCK_SIZE * GRAIN_SIZE;- const uint num_vec_chunks = (vocab + stride_elems - 1) / stride_elems;- const uint row_off = batch_idx * vocab;-- PhiloxState rng;- uint64_t philox_offset = batch_idx;- philox_init(&rng, seed, philox_offset);-- /* Initialize shared memory */- if (lid == 0) {- atomic_store_explicit(&ts.sampled_id, vocab, memory_order_relaxed);- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- /* ── Step 1: Find max logit for numerical stability ── */- float local_max = -INFINITY;- for (uint i = lid; i < vocab; i += BLOCK_SIZE) {- local_max = max(local_max, float(logits[row_off + i]));- }- float max_logit = threadgroup_cooperative_reduce_max<BLOCK_SIZE>(local_max, shared_max, lid);-- /* ── Step 2: Compute sum of exp((logit - max_logit) / temperature) for normalization ── */- float safe_temperature = max(temperature, 1e-8f);-- float local_sum = 0.0f;- for (uint i = lid; i < vocab; i += BLOCK_SIZE) {- local_sum += exp((float(logits[row_off + i]) - max_logit) / safe_temperature);- }- float sum_exp = threadgroup_cooperative_reduce_sum<BLOCK_SIZE>(local_sum, shared_sum, lid);-- /* ── Step 3: Generate random threshold ── */- if (lid == 0) {- ts.random_threshold = uniform_float(&rng);- }- threadgroup_barrier(mem_flags::mem_threadgroup);- float random_threshold = ts.random_threshold;-- /* ── Step 4: Find the token where cumulative probability crosses threshold ── */- float running_prob_sum = 0.0f;-- for (uint vec_i = 0; vec_i < num_vec_chunks; ++vec_i) {- /* Load probabilities for this chunk */- float prob_vec[GRAIN_SIZE];- bool valid[GRAIN_SIZE];-- for (uint j = 0; j < GRAIN_SIZE; ++j) {- uint global_token_id = (vec_i * BLOCK_SIZE + lid) * GRAIN_SIZE + j;- if (global_token_id < vocab) {- prob_vec[j] = exp((float(logits[row_off + global_token_id]) - max_logit) / safe_temperature) / sum_exp;- valid[j] = true;- } else {- prob_vec[j] = 0.0f;- valid[j] = false;- }- }-- /* Compute block-wide sum for this chunk */- float local_chunk_sum = prob_vec[0] + prob_vec[1] + prob_vec[2] + prob_vec[3];- float block_chunk_sum = threadgroup_cooperative_reduce_sum<BLOCK_SIZE>(local_chunk_sum, shared_sum, lid);-- /* Check if our target is in this chunk */- if (running_prob_sum + block_chunk_sum > random_threshold) {- /* Compute prefix sum within thread's elements */- float cumulative_probs[GRAIN_SIZE];- cumulative_probs[0] = prob_vec[0];- for (uint j = 1; j < GRAIN_SIZE; ++j) {- cumulative_probs[j] = cumulative_probs[j-1] + prob_vec[j];- }-- /* Get prefix sum from previous threads */- float thread_prefix = threadgroup_raking_prefix_exclusive_sum<BLOCK_SIZE>(local_chunk_sum, shared_sum, lid);-- /* Add global running sum and thread prefix */- for (uint j = 0; j < GRAIN_SIZE; ++j) {- cumulative_probs[j] += running_prob_sum + thread_prefix;- }-- /* Find first element that crosses the threshold */- for (uint j = 0; j < GRAIN_SIZE; ++j) {- if (valid[j] && cumulative_probs[j] > random_threshold) {- uint global_token_id = (vec_i * BLOCK_SIZE + lid) * GRAIN_SIZE + j;- atomic_fetch_min_explicit(&ts.sampled_id, global_token_id, memory_order_relaxed);- break;- }- }- break;- }-- running_prob_sum += block_chunk_sum;- }-- threadgroup_barrier(mem_flags::mem_threadgroup);-- /* Output the result */- if (lid == 0) {- uint sampled = atomic_load_explicit(&ts.sampled_id, memory_order_relaxed);- // Fallback to last valid token if something went wrong- if (sampled >= vocab) {- sampled = vocab - 1;- }- out_ids[batch_idx] = sampled;- }-}--// Generate categorical single-pass kernels using macro approach-#define outerArguments(T) \-(device const T* logits_data [[ buffer(0) ]], \-device uint* sampled_tokens [[ buffer(1) ]], \-constant uint& batch_size [[ buffer(2) ]], \-constant uint& vocab_size [[ buffer(3) ]], \-constant float& temperature [[ buffer(4) ]], \-constant uint64_t& seed [[ buffer(5) ]], \-uint batch_idx [[ threadgroup_position_in_grid ]], \-uint local_id [[ thread_position_in_threadgroup ]])--#define innerArguments \-(logits_data, sampled_tokens, batch_size, vocab_size, temperature, seed, temp_storage, shared_max, shared_sum, batch_idx, local_id)--#define generateCategoricalKernel(functionName, T, outerArgs, innerArgs) \-kernel void functionName##_##T outerArgs { \- threadgroup CategoricalTempStorage temp_storage; \- threadgroup float shared_max[BLOCK_SIZE]; \- threadgroup float shared_sum[BLOCK_SIZE]; \- categorical_sampling_kernel_impl<T> innerArgs; \-}--generateCategoricalKernel(batched_categorical_main, float, outerArguments(float), innerArguments)-generateCategoricalKernel(batched_categorical_main, half, outerArguments(half), innerArguments)-generateCategoricalKernel(batched_categorical_main, bfloat, outerArguments(bfloat), innerArguments)--#undef outerArguments-#undef innerArguments-#undef generateCategoricalKernel--// MARK: - 2-Pass Categorical Sampling--struct CategoricalChunkResult {- float max_logit;- float sum_exp;- float cumulative_prob;-};--template<typename T>-void categorical_sampling_main_2pass_impl(- const device T* logits,- device CategoricalChunkResult* chunk_results,- constant uint& batch,- constant uint& vocab,- constant float& temperature,- constant uint64_t& seed,- threadgroup float* shared_max,- threadgroup float* shared_sum,- uint batch_idx,- uint chunk_idx,- uint lid)-{- if (batch_idx >= batch) return;-- const uint stride_elems = BLOCK_SIZE * GRAIN_SIZE;- const uint chunk_start = chunk_idx * stride_elems;- const uint chunk_end = min(chunk_start + stride_elems, vocab);- const uint row_off = batch_idx * vocab;-- // Step 1: Find max logit in this chunk- float local_max = -INFINITY;- for (uint i = chunk_start + lid; i < chunk_end; i += BLOCK_SIZE) {- local_max = max(local_max, float(logits[row_off + i]));- }- float chunk_max = threadgroup_raking_reduce_max<BLOCK_SIZE>(local_max, shared_max, lid);-- // Step 2: Compute sum of exp((logit - max_logit) / temperature) for this chunk- float safe_temperature = max(temperature, 1e-8f);-- float local_sum = 0.0f;- for (uint i = chunk_start + lid; i < chunk_end; i += BLOCK_SIZE) {- local_sum += exp((float(logits[row_off + i]) - chunk_max) / safe_temperature);- }- float chunk_sum = threadgroup_raking_reduce_sum<BLOCK_SIZE>(local_sum, shared_sum, lid);-- // Store results for this chunk- if (lid == 0) {- uint vocab_groups_per_batch = (vocab + stride_elems - 1) / stride_elems;- uint result_idx = batch_idx * vocab_groups_per_batch + chunk_idx;- chunk_results[result_idx] = {chunk_max, chunk_sum, 0.0f}; // cumulative_prob set in final pass- }-}--template<typename T>-void categorical_sampling_final_2pass_impl(- const device T* logits,- const device CategoricalChunkResult* chunk_results,- device uint* out_ids,- constant uint& batch,- constant uint& vocab,- constant uint& num_chunks,- constant float& temperature,- constant uint64_t& seed,- threadgroup float* shared_storage,- threadgroup float* shared_sum,- uint batch_idx,- uint lid)-{- if (batch_idx >= batch) return;-- const uint chunk_offset = batch_idx * num_chunks;- const uint row_off = batch_idx * vocab;-- // Find global max across all chunks- float global_max = -INFINITY;- for (uint i = lid; i < num_chunks; i += BLOCK_SIZE) {- global_max = max(global_max, chunk_results[chunk_offset + i].max_logit);- }- global_max = threadgroup_raking_reduce_max<BLOCK_SIZE>(global_max, shared_storage, lid);-- // Compute global sum with proper normalization- float global_sum = 0.0f;- for (uint i = lid; i < num_chunks; i += BLOCK_SIZE) {- const device CategoricalChunkResult& chunk = chunk_results[chunk_offset + i];- float renorm_factor = exp(chunk.max_logit - global_max);- global_sum += chunk.sum_exp * renorm_factor;- }- global_sum = threadgroup_raking_reduce_sum<BLOCK_SIZE>(global_sum, shared_storage, lid);-- // Generate random threshold and find target chunk- threadgroup uint* shared_target_chunk = (threadgroup uint*)shared_storage;- threadgroup float* shared_target_within = (threadgroup float*)(shared_storage + 1);-- if (lid == 0) {- PhiloxState rng;- uint64_t philox_offset = batch_idx;- philox_init(&rng, seed, philox_offset);- float random_threshold = uniform_float(&rng) * global_sum;-- // Find which chunk contains the target probability- float cumulative_prob = 0.0f;- uint target_chunk = num_chunks; // fallback- float target_within_chunk = 0.0f;-- for (uint chunk_i = 0; chunk_i < num_chunks; chunk_i++) {- const device CategoricalChunkResult& chunk = chunk_results[chunk_offset + chunk_i];- float chunk_prob = chunk.sum_exp * exp(chunk.max_logit - global_max);-- if (cumulative_prob + chunk_prob > random_threshold) {- target_chunk = chunk_i;- // Calculate relative position within the chunk (0.0 to 1.0)- target_within_chunk = (random_threshold - cumulative_prob) / chunk_prob;- break;- }- cumulative_prob += chunk_prob;- }-- // Store in shared memory for all threads- *shared_target_chunk = target_chunk;- *shared_target_within = target_within_chunk;- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- uint target_chunk = *shared_target_chunk;- float target_within_chunk = *shared_target_within;-- // If no valid chunk found, fallback- if (target_chunk >= num_chunks) {- if (lid == 0) {- out_ids[batch_idx] = vocab - 1;- }- return;- }-- // only thread 0 does the scan- if (lid == 0) {- const uint stride_elems = BLOCK_SIZE * GRAIN_SIZE;- const uint chunk_start = target_chunk * stride_elems;- const uint chunk_end = min(chunk_start + stride_elems, vocab);- const device CategoricalChunkResult& target_chunk_result = chunk_results[chunk_offset + target_chunk];-- float safe_temperature = max(temperature, 1e-8f);- float chunk_threshold = target_within_chunk * target_chunk_result.sum_exp;-- // Sample within the chunk using cumulative distribution- float running_sum = 0.0f;- uint selected_token = chunk_end - 1; // fallback to last token in chunk-- // Only thread 0 scans the target chunk - eliminates 1023 redundant operations- for (uint i = chunk_start; i < chunk_end; i++) {- float prob = exp((float(logits[row_off + i]) - target_chunk_result.max_logit) / safe_temperature);- running_sum += prob;-- if (running_sum > chunk_threshold) {- selected_token = i;- break;- }- }-- out_ids[batch_idx] = selected_token;- }-}--// Generate categorical 2-pass main kernels using macro approach-#define outerArguments(T) \-(device const T* logits_data [[ buffer(0) ]], \-device CategoricalChunkResult* chunk_results [[ buffer(1) ]], \-constant uint& batch_size [[ buffer(2) ]], \-constant uint& vocab_size [[ buffer(3) ]], \-constant float& temperature [[ buffer(4) ]], \-constant uint64_t& seed [[ buffer(5) ]], \-uint2 group_position [[ threadgroup_position_in_grid ]], \-uint2 local_position [[ thread_position_in_threadgroup ]])--#define innerArguments \-(logits_data, chunk_results, batch_size, vocab_size, temperature, seed, shared_max, shared_sum, group_position.x, group_position.y, local_position.x)--#define generateCategorical2PassMainKernel(functionName, T, outerArgs, innerArgs) \-kernel void functionName##_##T outerArgs { \- threadgroup float shared_max[BLOCK_SIZE]; \- threadgroup float shared_sum[BLOCK_SIZE]; \- categorical_sampling_main_2pass_impl<T> innerArgs; \-}--generateCategorical2PassMainKernel(batched_categorical_main_2pass, float, outerArguments(float), innerArguments)-generateCategorical2PassMainKernel(batched_categorical_main_2pass, half, outerArguments(half), innerArguments)-generateCategorical2PassMainKernel(batched_categorical_main_2pass, bfloat, outerArguments(bfloat), innerArguments)--#undef outerArguments-#undef innerArguments-#undef generateCategorical2PassMainKernel--// Generate categorical 2-pass final kernels using macro approach-#define outerArguments(T) \-(device const T* logits_data [[ buffer(0) ]], \-device const CategoricalChunkResult* chunk_results [[ buffer(1) ]], \-device uint* sampled_tokens [[ buffer(2) ]], \-constant uint& batch_size [[ buffer(3) ]], \-constant uint& vocab_size [[ buffer(4) ]], \-constant uint& num_chunks [[ buffer(5) ]], \-constant float& temperature [[ buffer(6) ]], \-constant uint64_t& seed [[ buffer(7) ]], \-uint batch_idx [[ threadgroup_position_in_grid ]], \-uint local_id [[ thread_position_in_threadgroup ]])--#define innerArguments \-(logits_data, chunk_results, sampled_tokens, batch_size, vocab_size, num_chunks, temperature, seed, shared_storage, shared_sum, batch_idx, local_id)--#define generateCategorical2PassFinalKernel(functionName, T, outerArgs, innerArgs) \-kernel void functionName##_##T outerArgs { \- threadgroup float shared_storage[BLOCK_SIZE]; \- threadgroup float shared_sum[BLOCK_SIZE]; \- categorical_sampling_final_2pass_impl<T> innerArgs; \-}--generateCategorical2PassFinalKernel(batched_categorical_final_2pass, float, outerArguments(float), innerArguments)-generateCategorical2PassFinalKernel(batched_categorical_final_2pass, half, outerArguments(half), innerArguments)-generateCategorical2PassFinalKernel(batched_categorical_final_2pass, bfloat, outerArguments(bfloat), innerArguments)--#undef outerArguments-#undef innerArguments-#undef generateCategorical2PassFinalKernel--#undef BLOCK_SIZE-#undef GRAIN_SIZE\ No newline at end of filediff --git a/crates/uzu/src/backends/metal/kernel/sampling/gumbel.metal b/crates/uzu/src/backends/metal/kernel/sampling/gumbel.metalnew file mode 100644index 000000000..6cb34bacd--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/sampling/gumbel.metal@@ -0,0 +1,53 @@+#include <metal_stdlib>+#include "../definitions.metal"+#include "../rng.metal"++#define GRAIN_SIZE 64+#define BLOCK_SIZE 1024++#define WORDS_PER_OFFSET 4++template <typename T>+void batched_gumbel(+ device const T* logits_data,+ device const uint64_t* batch_seeds,+ device T* processed_logits,+ constant uint& vocab_size,+ uint group_idx,+ uint batch_idx,+ uint thread_idx+) {+ uint batch_start = vocab_size * batch_idx;+ uint batch_end = batch_start + vocab_size;++ uint grain_offset_in_batch = group_idx * BLOCK_SIZE * GRAIN_SIZE + thread_idx;++ uint grain_offset = batch_start + grain_offset_in_batch;++ uint64_t rng_seed = batch_seeds[batch_idx];+ uint64_t rng_offset = (group_idx * BLOCK_SIZE + thread_idx) * (GRAIN_SIZE + WORDS_PER_OFFSET - 1) / WORDS_PER_OFFSET;+ PhiloxState rng;+ philox_init(&rng, rng_seed, rng_offset);++ for (uint i = 0; i < GRAIN_SIZE; i++) {+ uint global_idx = grain_offset + i * BLOCK_SIZE;+ if (global_idx < batch_end) {+ processed_logits[global_idx] = logits_data[global_idx] + T(-log(-log(uniform_float(&rng))));+ }+ }+}++#define outerArguments(T) \+(device const T* logits_data [[ buffer(0) ]], \+device const uint64_t* batch_seeds [[ buffer(1) ]], \+device T* processed_logits [[ buffer(2) ]], \+constant uint& vocab_size [[ buffer(3) ]], \+uint3 threadgroup_idx [[ threadgroup_position_in_grid ]], \+uint3 thread_idx [[ thread_position_in_threadgroup ]])++#define innerArguments (logits_data, batch_seeds, processed_logits, vocab_size, threadgroup_idx.x, threadgroup_idx.y, thread_idx.x)++generateKernels(batched_gumbel)++#undef outerArguments+#undef innerArgumentsdiff --git a/crates/uzu/src/backends/metal/kernel/sampling/mod.rs b/crates/uzu/src/backends/metal/kernel/sampling/mod.rsindex e1dcabe10..74639522d 100644--- a/crates/uzu/src/backends/metal/kernel/sampling/mod.rs+++ b/crates/uzu/src/backends/metal/kernel/sampling/mod.rs@@ -1,4 +1,4 @@-use std::{collections::HashMap, mem::size_of, rc::Rc};+use std::{mem::size_of, rc::Rc};use metal::{Buffer as MTLBuffer, CommandBuffer as MTLCommandBuffer,@@ -9,6 +9,7 @@ use mpsgraph::CommandBuffer as MPSCommandBuffer;use thiserror::Error;use crate::{+ DataType,backends::metal::{KernelDataType, MTLContext, MTLError,forward_pass::{@@ -20,7 +21,8 @@ use crate::{};const BLOCK_SIZE: usize = 1024;-const GRAIN_SIZE: usize = 4;+const ELEMENTWISE_GRAIN_SIZE: usize = 64;+const TWOPASS_ARGMAX_GRAIN_SIZE: usize = 4;#[derive(Debug, Clone, Copy, PartialEq)]pub enum ArgmaxStrategy {@@ -28,21 +30,6 @@ pub enum ArgmaxStrategy {TwoPass, // Multi-stage reduction}-#[derive(Debug, Clone, Copy, PartialEq)]-pub enum CategoricalStrategy {- SinglePass, // One threadgroup per batch item- TwoPass, // Multi-stage reduction for large vocabularies-}--#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]-enum SamplingAlgorithm {- ArgmaxSinglePass,- ArgmaxTwoPass,- TopP,- CategoricalSinglePass,- CategoricalTwoPass,-}-#[repr(C)]#[derive(Debug, Clone, Copy)]struct ArgmaxPair {@@ -59,17 +46,29 @@ impl Default for ArgmaxPair {}}+enum ArgmaxImplementation {+ SinglePass {+ pipeline: MTLComputePipelineState,+ },+ TwoPass {+ main_pipeline: MTLComputePipelineState,+ final_pipeline: MTLComputePipelineState,+ partial_results_buffer: MTLBuffer,+ },+}+pub struct SamplingKernel {- // Pipeline lookup by algorithm -> array of pipeline stages- pipelines: HashMap<SamplingAlgorithm, Vec<MTLComputePipelineState>>,- argmax_strategy: ArgmaxStrategy,- categorical_strategy: CategoricalStrategy,- partial_results_buffer: MTLBuffer,- categorical_partial_buffer: MTLBuffer,+ temperature_pipeline: MTLComputePipelineState,+ partial_temperature_buffer: MTLBuffer,+ topk_pipeline: MTLComputePipelineState,+ partial_topk_buffer: MTLBuffer,+ topp_pipeline: MTLComputePipelineState,+ partial_topp_buffer: MTLBuffer,+ gumbel_pipeline: MTLComputePipelineState,+ partial_gumbel_buffer: MTLBuffer,+ argmax_implementation: ArgmaxImplementation,max_batch_size: usize,max_vocab_size: usize,- sampling_seed: u64,- invocation_count: std::cell::Cell<u64>,}#[derive(Debug, Error)]@@ -82,28 +81,16 @@ pub enum SamplingError {BatchSizeExceeded(usize, usize),#[error("Vocab size {0} exceeds maximum {1}")]VocabSizeExceeded(usize, usize),+ #[error("Stochastic sampling encode must have a seed")]+ StochasticWithoutSeed,}impl SamplingKernel {- fn hash_seed(- base_seed: u64,- invocation: u64,- ) -> u64 {- let mut hash = base_seed.wrapping_add(invocation);- hash ^= hash >> 33;- hash = hash.wrapping_mul(0xff51afd7ed558ccd);- hash ^= hash >> 33;- hash = hash.wrapping_mul(0xc4ceb9fe1a85ec53);- hash ^= hash >> 33;- hash- }-pub fn new(context: &MTLContext,data_type: KernelDataType,max_batch_size: usize,max_vocab_size: usize,- sampling_seed: u64,) -> Result<Self, SamplingError> {Self::new_with_strategy(context,@@ -111,7 +98,6 @@ impl SamplingKernel {max_batch_size,max_vocab_size,ArgmaxStrategy::TwoPass,- sampling_seed,)}@@ -121,102 +107,84 @@ impl SamplingKernel {max_batch_size: usize,max_vocab_size: usize,argmax_strategy: ArgmaxStrategy,- sampling_seed: u64,- ) -> Result<Self, SamplingError> {- Self::new_with_strategies(- context,- data_type,- max_batch_size,- max_vocab_size,- argmax_strategy,- CategoricalStrategy::SinglePass,- sampling_seed,- )- }-- pub fn new_with_strategies(- context: &MTLContext,- data_type: KernelDataType,- max_batch_size: usize,- max_vocab_size: usize,- argmax_strategy: ArgmaxStrategy,- categorical_strategy: CategoricalStrategy,- sampling_seed: u64,) -> Result<Self, SamplingError> {let data_suffix = data_type.function_name_suffix();- let mut pipelines = HashMap::new();+ let max_elements = max_batch_size * max_vocab_size;- // Build argmax pipelines based on strategy- match argmax_strategy {- ArgmaxStrategy::SinglePass => {- let pipeline = context- .compute_pipeline_state_with_reflection(- &format!("batched_argmax_single_{}", data_suffix),- None,- )- .map(|(pipeline, _)| pipeline)- .map_err(SamplingError::MetalError)?;- pipelines.insert(- SamplingAlgorithm::ArgmaxSinglePass,- vec![pipeline],- );- },- ArgmaxStrategy::TwoPass => {- let main_pipeline = context- .compute_pipeline_state_with_reflection(- &format!("batched_argmax_main_{}", data_suffix),- None,- )- .map(|(pipeline, _)| pipeline)- .map_err(SamplingError::MetalError)?;+ let temperature_pipeline = context+ .compute_pipeline_state_with_reflection(+ &format!("batched_temperature_{}", data_suffix),+ None,+ )+ .map(|(pipeline, _)| pipeline)+ .map_err(SamplingError::MetalError)?;- let final_pipeline = context- .compute_pipeline_state_with_reflection(- &format!("batched_argmax_final_{}", data_suffix),- None,- )- .map(|(pipeline, _)| pipeline)- .map_err(SamplingError::MetalError)?;+ let partial_temperature_buffer = context.device.new_buffer(+ (max_elements * Into::<DataType>::into(data_type).size_in_bytes())+ as u64,+ MTLResourceOptions::StorageModeShared,+ );- pipelines.insert(- SamplingAlgorithm::ArgmaxTwoPass,- vec![main_pipeline, final_pipeline],- );- },- }+ let topk_pipeline = context+ .compute_pipeline_state_with_reflection(+ &format!("batched_topk_{}", data_suffix),+ None,+ )+ .map(|(pipeline, _)| pipeline)+ .map_err(SamplingError::MetalError)?;++ let partial_topk_buffer = context.device.new_buffer(+ (max_elements * Into::<DataType>::into(data_type).size_in_bytes())+ as u64,+ MTLResourceOptions::StorageModeShared,+ );- // Build top-p pipeline (single pass)- let top_p_pipeline = context+ let topp_pipeline = context.compute_pipeline_state_with_reflection(- &format!("batched_topp_main_{}", data_suffix),+ &format!("batched_topp_{}", data_suffix),None,).map(|(pipeline, _)| pipeline).map_err(SamplingError::MetalError)?;- pipelines.insert(SamplingAlgorithm::TopP, vec![top_p_pipeline]);- // Build categorical pipelines based on strategy- match categorical_strategy {- CategoricalStrategy::SinglePass => {- let categorical_pipeline = context+ let partial_topp_buffer = context.device.new_buffer(+ (max_elements * Into::<DataType>::into(data_type).size_in_bytes())+ as u64,+ MTLResourceOptions::StorageModeShared,+ );++ let gumbel_pipeline = context+ .compute_pipeline_state_with_reflection(+ &format!("batched_gumbel_{}", data_suffix),+ None,+ )+ .map(|(pipeline, _)| pipeline)+ .map_err(SamplingError::MetalError)?;++ let partial_gumbel_buffer = context.device.new_buffer(+ (max_elements * Into::<DataType>::into(data_type).size_in_bytes())+ as u64,+ MTLResourceOptions::StorageModeShared,+ );++ let argmax_implementation = match argmax_strategy {+ ArgmaxStrategy::SinglePass => {+ let pipeline = context.compute_pipeline_state_with_reflection(- &format!("batched_categorical_main_{}", data_suffix),+ &format!("batched_argmax_single_{}", data_suffix),None,).map(|(pipeline, _)| pipeline).map_err(SamplingError::MetalError)?;- pipelines.insert(- SamplingAlgorithm::CategoricalSinglePass,- vec![categorical_pipeline],- );++ ArgmaxImplementation::SinglePass {+ pipeline,+ }},- CategoricalStrategy::TwoPass => {+ ArgmaxStrategy::TwoPass => {let main_pipeline = context.compute_pipeline_state_with_reflection(- &format!(- "batched_categorical_main_2pass_{}",- data_suffix- ),+ &format!("batched_argmax_main_{}", data_suffix),None,).map(|(pipeline, _)| pipeline)@@ -224,66 +192,63 @@ impl SamplingKernel {let final_pipeline = context.compute_pipeline_state_with_reflection(- &format!(- "batched_categorical_final_2pass_{}",- data_suffix- ),+ &format!("batched_argmax_final_{}", data_suffix),None,).map(|(pipeline, _)| pipeline).map_err(SamplingError::MetalError)?;- pipelines.insert(- SamplingAlgorithm::CategoricalTwoPass,- vec![main_pipeline, final_pipeline],- );- },- }+ let elements_per_group = BLOCK_SIZE * TWOPASS_ARGMAX_GRAIN_SIZE;+ let max_vocab_groups_per_batch =+ (max_vocab_size + elements_per_group - 1)+ / elements_per_group;+ let max_partial_results =+ max_batch_size * max_vocab_groups_per_batch;- let elements_per_group = BLOCK_SIZE * GRAIN_SIZE;- let max_vocab_groups_per_batch =- (max_vocab_size + elements_per_group - 1) / elements_per_group;- let max_partial_results = max_batch_size * max_vocab_groups_per_batch;-- let partial_results_buffer = context.device.new_buffer(- (max_partial_results * size_of::<ArgmaxPair>()) as u64,- MTLResourceOptions::StorageModeShared,- );+ let partial_results_buffer = context.device.new_buffer(+ (max_partial_results * size_of::<ArgmaxPair>()) as u64,+ MTLResourceOptions::StorageModeShared,+ );- // Buffer for categorical 2-pass: stores CategoricalChunkResult per chunk- // CategoricalChunkResult has 3 floats: max_logit, sum_exp, cumulative_prob- let categorical_partial_buffer = context.device.new_buffer(- (max_partial_results * size_of::<f32>() * 3) as u64,- MTLResourceOptions::StorageModeShared,- );+ ArgmaxImplementation::TwoPass {+ main_pipeline,+ final_pipeline,+ partial_results_buffer,+ }+ },+ };Ok(Self {- pipelines,- argmax_strategy,- categorical_strategy,- partial_results_buffer,- categorical_partial_buffer,+ temperature_pipeline,+ partial_temperature_buffer,+ topk_pipeline,+ partial_topk_buffer,+ topp_pipeline,+ partial_topp_buffer,+ gumbel_pipeline,+ partial_gumbel_buffer,+ argmax_implementation,max_batch_size,max_vocab_size,- sampling_seed,- invocation_count: std::cell::Cell::new(0),})}pub fn encode(&self,- sampling_method: &SamplingMethod,logits_buffer: &MTLBuffer,+ seeds_buffer: Option<&MTLBuffer>,sampled_tokens_buffer: &MTLBuffer,+ sampling_method: SamplingMethod,batch_size: usize,vocab_size: usize,command_buffer: &MTLCommandBuffer,) -> Result<(), SamplingError> {let compute_encoder = command_buffer.new_compute_command_encoder();self.encode_with_encoder(- sampling_method,logits_buffer,+ seeds_buffer,sampled_tokens_buffer,+ sampling_method,batch_size,vocab_size,&compute_encoder,@@ -294,9 +259,10 @@ impl SamplingKernel {pub fn encode_with_encoder(&self,- sampling_method: &SamplingMethod,logits_buffer: &MTLBuffer,+ seeds_buffer: Option<&MTLBuffer>,sampled_tokens_buffer: &MTLBuffer,+ sampling_method: SamplingMethod,batch_size: usize,vocab_size: usize,compute_encoder: &ComputeCommandEncoderRef,@@ -314,307 +280,246 @@ impl SamplingKernel {));}- let batch_size_u32 = batch_size as u32;- let vocab_size_u32 = vocab_size as u32;-- let elements_per_group = BLOCK_SIZE * GRAIN_SIZE;- let vocab_groups_per_batch =- (vocab_size + elements_per_group - 1) / elements_per_group;-- let threads_per_threadgroup = MTLSize::new(BLOCK_SIZE as u64, 1, 1);-- match sampling_method {- SamplingMethod::Greedy => self.encode_argmax(- logits_buffer,- sampled_tokens_buffer,- batch_size_u32,- vocab_size_u32,- vocab_groups_per_batch,- threads_per_threadgroup,- compute_encoder,- ),- SamplingMethod::TopP {- top_p,- } => self.encode_top_p(- *top_p,- logits_buffer,- sampled_tokens_buffer,- batch_size_u32,- vocab_size_u32,- vocab_groups_per_batch,- threads_per_threadgroup,- compute_encoder,- ),- SamplingMethod::Temperature {- temperature,- } => self.encode_categorical(- *temperature,- logits_buffer,- sampled_tokens_buffer,- batch_size_u32,- vocab_size_u32,- vocab_groups_per_batch,- threads_per_threadgroup,+ let mut last_logits_buffer = logits_buffer;++ if let SamplingMethod::Stochastic {+ temperature,+ top_k,+ top_p,+ } = sampling_method+ {+ if let Some(temperature) = temperature {+ self.encode_temperature(+ last_logits_buffer,+ &self.partial_temperature_buffer,+ batch_size as u32,+ vocab_size as u32,+ temperature,+ compute_encoder,+ )?;+ last_logits_buffer = &self.partial_temperature_buffer;+ }++ if let Some(top_k) = top_k {+ self.encode_topk(+ last_logits_buffer,+ &self.partial_topk_buffer,+ batch_size as u32,+ vocab_size as u32,+ top_k,+ compute_encoder,+ )?;+ last_logits_buffer = &self.partial_topk_buffer;+ }++ if let Some(top_p) = top_p {+ self.encode_topp(+ last_logits_buffer,+ &self.partial_topp_buffer,+ batch_size as u32,+ vocab_size as u32,+ top_p,+ compute_encoder,+ )?;+ last_logits_buffer = &self.partial_topp_buffer;+ }++ self.encode_gumbel(+ last_logits_buffer,+ seeds_buffer.ok_or(SamplingError::StochasticWithoutSeed)?,+ &self.partial_gumbel_buffer,+ batch_size as u32,+ vocab_size as u32,compute_encoder,- ),+ )?;+ last_logits_buffer = &self.partial_gumbel_buffer;}- }- fn encode_argmax(- &self,- logits_buffer: &MTLBuffer,- sampled_tokens_buffer: &MTLBuffer,- batch_size_u32: u32,- vocab_size_u32: u32,- vocab_groups_per_batch: usize,- threads_per_threadgroup: MTLSize,- compute_encoder: &ComputeCommandEncoderRef,- ) -> Result<(), SamplingError> {- match self.argmax_strategy {- ArgmaxStrategy::SinglePass => self.encode_argmax_single_pass(- logits_buffer,+ match &self.argmax_implementation {+ ArgmaxImplementation::SinglePass {+ pipeline,+ } => self.encode_argmax_single_pass(+ pipeline,+ last_logits_buffer,sampled_tokens_buffer,- batch_size_u32,- vocab_size_u32,- threads_per_threadgroup,+ batch_size,+ vocab_size,compute_encoder,),- ArgmaxStrategy::TwoPass => self.encode_argmax_two_pass(- logits_buffer,+ ArgmaxImplementation::TwoPass {+ main_pipeline,+ final_pipeline,+ partial_results_buffer,+ } => self.encode_argmax_two_pass(+ main_pipeline,+ final_pipeline,+ last_logits_buffer,+ partial_results_buffer,sampled_tokens_buffer,- batch_size_u32,- vocab_size_u32,- vocab_groups_per_batch,- threads_per_threadgroup,+ batch_size,+ vocab_size,compute_encoder,),}}- fn encode_argmax_single_pass(+ pub fn encode_temperature(&self,logits_buffer: &MTLBuffer,- sampled_tokens_buffer: &MTLBuffer,- batch_size_u32: u32,- vocab_size_u32: u32,- threads_per_threadgroup: MTLSize,+ processed_logits_buffer: &MTLBuffer,+ batch_size: u32,+ vocab_size: u32,+ temperature: f32,compute_encoder: &ComputeCommandEncoderRef,) -> Result<(), SamplingError> {- compute_encoder.set_compute_pipeline_state(- &self.pipelines[&SamplingAlgorithm::ArgmaxSinglePass][0],- );+ compute_encoder.set_compute_pipeline_state(&self.temperature_pipeline);+compute_encoder.set_buffer(0, Some(logits_buffer), 0);- compute_encoder.set_buffer(1, Some(sampled_tokens_buffer), 0);+ compute_encoder.set_buffer(1, Some(processed_logits_buffer), 0);compute_encoder.set_bytes(2,size_of::<u32>() as u64,- &batch_size_u32 as *const u32 as *const std::ffi::c_void,+ &vocab_size as *const u32 as *const std::ffi::c_void,);compute_encoder.set_bytes(3,- size_of::<u32>() as u64,- &vocab_size_u32 as *const u32 as *const std::ffi::c_void,+ size_of::<f32>() as u64,+ &temperature as *const f32 as *const std::ffi::c_void,);- let threadgroups_per_grid = MTLSize::new(batch_size_u32 as u64, 1, 1);+ let elements_in_group = BLOCK_SIZE * ELEMENTWISE_GRAIN_SIZE;+ let groups = (vocab_size + (elements_in_group as u32 - 1))+ / elements_in_group as u32;+compute_encoder.dispatch_thread_groups(- threadgroups_per_grid,- threads_per_threadgroup,+ MTLSize::new(groups as u64, batch_size as u64, 1),+ MTLSize::new(BLOCK_SIZE as u64, 1, 1),);Ok(())}- fn encode_argmax_two_pass(+ pub fn encode_topk(&self,logits_buffer: &MTLBuffer,- sampled_tokens_buffer: &MTLBuffer,- batch_size_u32: u32,- vocab_size_u32: u32,- vocab_groups_per_batch: usize,- threads_per_threadgroup: MTLSize,+ processed_logits_buffer: &MTLBuffer,+ batch_size: u32,+ vocab_size: u32,+ top_k: u32,compute_encoder: &ComputeCommandEncoderRef,) -> Result<(), SamplingError> {- // Main pass- compute_encoder.set_compute_pipeline_state(- &self.pipelines[&SamplingAlgorithm::ArgmaxTwoPass][0],- );- compute_encoder.set_buffer(0, Some(logits_buffer), 0);- compute_encoder.set_buffer(1, Some(&self.partial_results_buffer), 0);- compute_encoder.set_bytes(- 2,- size_of::<u32>() as u64,- &batch_size_u32 as *const u32 as *const std::ffi::c_void,- );- compute_encoder.set_bytes(- 3,- size_of::<u32>() as u64,- &vocab_size_u32 as *const u32 as *const std::ffi::c_void,- );+ compute_encoder.set_compute_pipeline_state(&self.topk_pipeline);- let threadgroups_per_grid = MTLSize::new(- batch_size_u32 as u64,- vocab_groups_per_batch as u64,- 1,- );- compute_encoder.dispatch_thread_groups(- threadgroups_per_grid,- threads_per_threadgroup,- );-- // Final pass - two-pass argmax always has exactly 2 stages- let final_pipeline =- &self.pipelines[&SamplingAlgorithm::ArgmaxTwoPass][1];- compute_encoder.set_compute_pipeline_state(final_pipeline);- compute_encoder.set_buffer(0, Some(&self.partial_results_buffer), 0);- compute_encoder.set_buffer(1, Some(sampled_tokens_buffer), 0);+ compute_encoder.set_buffer(0, Some(logits_buffer), 0);+ compute_encoder.set_buffer(1, Some(processed_logits_buffer), 0);compute_encoder.set_bytes(2,size_of::<u32>() as u64,- &batch_size_u32 as *const u32 as *const std::ffi::c_void,+ &vocab_size as *const u32 as *const std::ffi::c_void,);compute_encoder.set_bytes(3,size_of::<u32>() as u64,- &vocab_size_u32 as *const u32 as *const std::ffi::c_void,+ &top_k as *const u32 as *const std::ffi::c_void,);- let final_threadgroups = MTLSize::new(batch_size_u32 as u64, 1, 1);compute_encoder.dispatch_thread_groups(- final_threadgroups,- threads_per_threadgroup,+ MTLSize::new(batch_size as u64, 1, 1),+ MTLSize::new(BLOCK_SIZE as u64, 1, 1),);Ok(())}- fn encode_top_p(+ pub fn encode_topp(&self,- top_p: f32,logits_buffer: &MTLBuffer,- sampled_tokens_buffer: &MTLBuffer,- batch_size_u32: u32,- vocab_size_u32: u32,- _vocab_groups_per_batch: usize,- threads_per_threadgroup: MTLSize,+ processed_logits_buffer: &MTLBuffer,+ batch_size: u32,+ vocab_size: u32,+ top_p: f32,compute_encoder: &ComputeCommandEncoderRef,) -> Result<(), SamplingError> {- let current_invocation = self.invocation_count.get();- self.invocation_count.set(current_invocation + 1);- let seed = Self::hash_seed(self.sampling_seed, current_invocation);+ compute_encoder.set_compute_pipeline_state(&self.topp_pipeline);- // Single pass - directly write to sampled_tokens_buffer- compute_encoder.set_compute_pipeline_state(- &self.pipelines[&SamplingAlgorithm::TopP][0],- );compute_encoder.set_buffer(0, Some(logits_buffer), 0);- compute_encoder.set_buffer(1, Some(sampled_tokens_buffer), 0);+ compute_encoder.set_buffer(1, Some(processed_logits_buffer), 0);compute_encoder.set_bytes(2,size_of::<u32>() as u64,- &batch_size_u32 as *const u32 as *const std::ffi::c_void,+ &vocab_size as *const u32 as *const std::ffi::c_void,);compute_encoder.set_bytes(3,- size_of::<u32>() as u64,- &vocab_size_u32 as *const u32 as *const std::ffi::c_void,- );- compute_encoder.set_bytes(- 4,size_of::<f32>() as u64,&top_p as *const f32 as *const std::ffi::c_void,);- compute_encoder.set_bytes(- 5,- size_of::<u64>() as u64,- &seed as *const u64 as *const std::ffi::c_void,- );- let threadgroups_per_grid = MTLSize::new(batch_size_u32 as u64, 1, 1);compute_encoder.dispatch_thread_groups(- threadgroups_per_grid,- threads_per_threadgroup,+ MTLSize::new(batch_size as u64, 1, 1),+ MTLSize::new(BLOCK_SIZE as u64, 1, 1),);Ok(())}- fn encode_categorical(+ pub fn encode_gumbel(&self,- temperature: f32,logits_buffer: &MTLBuffer,- sampled_tokens_buffer: &MTLBuffer,- batch_size_u32: u32,- vocab_size_u32: u32,- vocab_groups_per_batch: usize,- threads_per_threadgroup: MTLSize,+ seeds_buffer: &MTLBuffer,+ processed_logits_buffer: &MTLBuffer,+ batch_size: u32,+ vocab_size: u32,compute_encoder: &ComputeCommandEncoderRef,) -> Result<(), SamplingError> {- match self.categorical_strategy {- CategoricalStrategy::SinglePass => self- .encode_categorical_single_pass(- temperature,- logits_buffer,- sampled_tokens_buffer,- batch_size_u32,- vocab_size_u32,- threads_per_threadgroup,- compute_encoder,- ),- CategoricalStrategy::TwoPass => self.encode_categorical_two_pass(- temperature,- logits_buffer,- sampled_tokens_buffer,- batch_size_u32,- vocab_size_u32,- vocab_groups_per_batch,- threads_per_threadgroup,- compute_encoder,- ),- }+ compute_encoder.set_compute_pipeline_state(&self.gumbel_pipeline);++ compute_encoder.set_buffer(0, Some(logits_buffer), 0);+ compute_encoder.set_buffer(1, Some(seeds_buffer), 0);+ compute_encoder.set_buffer(2, Some(processed_logits_buffer), 0);+ compute_encoder.set_bytes(+ 3,+ size_of::<u32>() as u64,+ &vocab_size as *const u32 as *const std::ffi::c_void,+ );++ let elements_in_group = BLOCK_SIZE * ELEMENTWISE_GRAIN_SIZE;+ let groups = (vocab_size + (elements_in_group as u32 - 1))+ / elements_in_group as u32;++ compute_encoder.dispatch_thread_groups(+ MTLSize::new(groups as u64, batch_size as u64, 1),+ MTLSize::new(BLOCK_SIZE as u64, 1, 1),+ );++ Ok(())}- fn encode_categorical_single_pass(+ pub fn encode_argmax_single_pass(&self,- temperature: f32,+ pipeline: &MTLComputePipelineState,logits_buffer: &MTLBuffer,sampled_tokens_buffer: &MTLBuffer,- batch_size_u32: u32,- vocab_size_u32: u32,- threads_per_threadgroup: MTLSize,+ batch_size: usize,+ vocab_size: usize,compute_encoder: &ComputeCommandEncoderRef,) -> Result<(), SamplingError> {- let current_invocation = self.invocation_count.get();- self.invocation_count.set(current_invocation + 1);- let seed = Self::hash_seed(self.sampling_seed, current_invocation);-- compute_encoder.set_compute_pipeline_state(- &self.pipelines[&SamplingAlgorithm::CategoricalSinglePass][0],- );+ compute_encoder.set_compute_pipeline_state(pipeline);compute_encoder.set_buffer(0, Some(logits_buffer), 0);compute_encoder.set_buffer(1, Some(sampled_tokens_buffer), 0);compute_encoder.set_bytes(2,size_of::<u32>() as u64,- &batch_size_u32 as *const u32 as *const std::ffi::c_void,+ &(batch_size as u32) as *const u32 as *const std::ffi::c_void,);compute_encoder.set_bytes(3,size_of::<u32>() as u64,- &vocab_size_u32 as *const u32 as *const std::ffi::c_void,- );- compute_encoder.set_bytes(- 4,- size_of::<f32>() as u64,- &temperature as *const f32 as *const std::ffi::c_void,- );- compute_encoder.set_bytes(- 5,- size_of::<u64>() as u64,- &seed as *const u64 as *const std::ffi::c_void,+ &(vocab_size as u32) as *const u32 as *const std::ffi::c_void,);- let threadgroups_per_grid = MTLSize::new(batch_size_u32 as u64, 1, 1);+ let threadgroups_per_grid = MTLSize::new(batch_size as u64, 1, 1);+ let threads_per_threadgroup = MTLSize::new(BLOCK_SIZE as u64, 1, 1);compute_encoder.dispatch_thread_groups(threadgroups_per_grid,threads_per_threadgroup,@@ -623,101 +528,60 @@ impl SamplingKernel {Ok(())}- fn encode_categorical_two_pass(+ pub fn encode_argmax_two_pass(&self,- temperature: f32,+ main_pipeline: &MTLComputePipelineState,+ final_pipeline: &MTLComputePipelineState,logits_buffer: &MTLBuffer,+ partial_results_buffer: &MTLBuffer,sampled_tokens_buffer: &MTLBuffer,- batch_size_u32: u32,- vocab_size_u32: u32,- vocab_groups_per_batch: usize,- threads_per_threadgroup: MTLSize,+ batch_size: usize,+ vocab_size: usize,compute_encoder: &ComputeCommandEncoderRef,) -> Result<(), SamplingError> {- let current_invocation = self.invocation_count.get();- self.invocation_count.set(current_invocation + 1);- let seed = Self::hash_seed(self.sampling_seed, current_invocation);+ let elements_per_group = BLOCK_SIZE * TWOPASS_ARGMAX_GRAIN_SIZE;+ let vocab_groups_per_batch =+ (vocab_size + elements_per_group - 1) / elements_per_group;- // Main pass - parallel chunk processing- compute_encoder.set_compute_pipeline_state(- &self.pipelines[&SamplingAlgorithm::CategoricalTwoPass][0],- );+ // Main pass+ compute_encoder.set_compute_pipeline_state(main_pipeline);compute_encoder.set_buffer(0, Some(logits_buffer), 0);- compute_encoder.set_buffer(- 1,- Some(&self.categorical_partial_buffer),- 0,- );+ compute_encoder.set_buffer(1, Some(partial_results_buffer), 0);compute_encoder.set_bytes(2,size_of::<u32>() as u64,- &batch_size_u32 as *const u32 as *const std::ffi::c_void,+ &(batch_size as u32) as *const u32 as *const std::ffi::c_void,);compute_encoder.set_bytes(3,size_of::<u32>() as u64,- &vocab_size_u32 as *const u32 as *const std::ffi::c_void,- );- compute_encoder.set_bytes(- 4,- size_of::<f32>() as u64,- &temperature as *const f32 as *const std::ffi::c_void,- );- compute_encoder.set_bytes(- 5,- size_of::<u64>() as u64,- &seed as *const u64 as *const std::ffi::c_void,+ &(vocab_size as u32) as *const u32 as *const std::ffi::c_void,);- let threadgroups_per_grid = MTLSize::new(- batch_size_u32 as u64,- vocab_groups_per_batch as u64,- 1,- );+ let threadgroups_per_grid =+ MTLSize::new(batch_size as u64, vocab_groups_per_batch as u64, 1);+ let threads_per_threadgroup = MTLSize::new(BLOCK_SIZE as u64, 1, 1);compute_encoder.dispatch_thread_groups(threadgroups_per_grid,threads_per_threadgroup,);- // Final pass - combine results and sample- let final_pipeline =- &self.pipelines[&SamplingAlgorithm::CategoricalTwoPass][1];+ // Final pass - two-pass argmax always has exactly 2 stagescompute_encoder.set_compute_pipeline_state(final_pipeline);- compute_encoder.set_buffer(0, Some(logits_buffer), 0);- compute_encoder.set_buffer(- 1,- Some(&self.categorical_partial_buffer),- 0,- );- compute_encoder.set_buffer(2, Some(sampled_tokens_buffer), 0);- compute_encoder.set_bytes(- 3,- size_of::<u32>() as u64,- &batch_size_u32 as *const u32 as *const std::ffi::c_void,- );+ compute_encoder.set_buffer(0, Some(partial_results_buffer), 0);+ compute_encoder.set_buffer(1, Some(sampled_tokens_buffer), 0);compute_encoder.set_bytes(- 4,+ 2,size_of::<u32>() as u64,- &vocab_size_u32 as *const u32 as *const std::ffi::c_void,+ &(batch_size as u32) as *const u32 as *const std::ffi::c_void,);compute_encoder.set_bytes(- 5,+ 3,size_of::<u32>() as u64,- &(vocab_groups_per_batch as u32) as *const u32- as *const std::ffi::c_void,- );- compute_encoder.set_bytes(- 6,- size_of::<f32>() as u64,- &temperature as *const f32 as *const std::ffi::c_void,- );- compute_encoder.set_bytes(- 7,- size_of::<u64>() as u64,- &seed as *const u64 as *const std::ffi::c_void,+ &(vocab_size as u32) as *const u32 as *const std::ffi::c_void,);- let final_threadgroups = MTLSize::new(batch_size_u32 as u64, 1, 1);+ let final_threadgroups = MTLSize::new(batch_size as u64, 1, 1);compute_encoder.dispatch_thread_groups(final_threadgroups,threads_per_threadgroup,@@ -737,14 +601,12 @@ impl SamplingKernelEncodable {data_type: KernelDataType,max_batch_size: usize,max_vocab_size: usize,- sampling_seed: u64,) -> Result<Self, SamplingError> {let kernel = SamplingKernel::new(context,data_type,max_batch_size,max_vocab_size,- sampling_seed,)?;Ok(Self {kernel,@@ -757,7 +619,6 @@ impl SamplingKernelEncodable {max_batch_size: usize,max_vocab_size: usize,argmax_strategy: ArgmaxStrategy,- sampling_seed: u64,) -> Result<Self, SamplingError> {let kernel = SamplingKernel::new_with_strategy(context,@@ -765,30 +626,6 @@ impl SamplingKernelEncodable {max_batch_size,max_vocab_size,argmax_strategy,- sampling_seed,- )?;- Ok(Self {- kernel,- })- }-- pub fn new_with_strategies(- context: &Rc<MTLContext>,- data_type: KernelDataType,- max_batch_size: usize,- max_vocab_size: usize,- argmax_strategy: ArgmaxStrategy,- categorical_strategy: CategoricalStrategy,- sampling_seed: u64,- ) -> Result<Self, SamplingError> {- let kernel = SamplingKernel::new_with_strategies(- context,- data_type,- max_batch_size,- max_vocab_size,- argmax_strategy,- categorical_strategy,- sampling_seed,)?;Ok(Self {kernel,@@ -803,37 +640,39 @@ impl EncodableWithState for SamplingKernelEncodable {command_buffer: &MPSCommandBuffer,parameters: &EncodingParameters,) {- let sampling_method = state.sampling_method.unwrap_or_default();+ assert!(+ state.sampling_output.is_some(),+ "Sampling output buffer must be pre-allocated"+ );let logits_binding = state.arrays(&[crate::backends::metal::forward_pass::ArrayId::Logits]);- let logits = logits_binding[0].borrow();+ let mut logits = logits_binding[0].borrow_mut();+let logits_shape = {use crate::Array;logits.shape()};let batch_size = logits_shape[0];let vocab_size = logits_shape[1];- drop(logits);- assert!(- state.sampling_output.is_some(),- "Sampling output buffer must be pre-allocated"- );-- let logits_binding = state- .arrays(&[crate::backends::metal::forward_pass::ArrayId::Logits]);- let mut logits = logits_binding[0].borrow_mut();+ let seeds_binding = state.arrays(&[+ crate::backends::metal::forward_pass::ArrayId::TokenSeeds,+ ]);+ let mut seeds = seeds_binding[0].borrow_mut();let mut output_buffer_ref =state.sampling_output.as_ref().unwrap().borrow_mut();+ let sampling_method = state.sampling_method.unwrap();+let root_command_buffer =command_buffer.root_command_buffer().to_owned();if let Err(e) = self.kernel.encode(- &sampling_method,unsafe { &logits.mtl_buffer() },+ unsafe { Some(&seeds.mtl_buffer()) },unsafe { &output_buffer_ref.mtl_buffer() },+ sampling_method,batch_size,vocab_size,&root_command_buffer,diff --git a/crates/uzu/src/backends/metal/kernel/sampling/temperature.metal b/crates/uzu/src/backends/metal/kernel/sampling/temperature.metalnew file mode 100644index 000000000..e451397dd--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/sampling/temperature.metal@@ -0,0 +1,41 @@+#include <metal_stdlib>+#include "../definitions.metal"++#define GRAIN_SIZE 64+#define BLOCK_SIZE 1024++template <typename T>+void batched_temperature(+ device const T* logits_data,+ device T* processed_logits,+ constant uint& vocab_size,+ constant float& temperature,+ uint group_idx,+ uint batch_idx,+ uint thread_idx+) {+ uint base_idx = batch_idx * vocab_size + group_idx * BLOCK_SIZE * GRAIN_SIZE + thread_idx;+ uint batch_end = batch_idx * vocab_size + vocab_size;++ for (uint i = 0; i < GRAIN_SIZE; i++) {+ uint global_idx = base_idx + i * BLOCK_SIZE;+ if (global_idx < batch_end) {+ processed_logits[global_idx] = logits_data[global_idx] / T(temperature);+ }+ }+}++#define outerArguments(T) \+(device const T* logits_data [[ buffer(0) ]], \+device T* processed_logits [[ buffer(1) ]], \+constant uint& vocab_size [[ buffer(2) ]], \+constant float& temperature [[ buffer(3) ]], \+uint3 threadgroup_idx [[ threadgroup_position_in_grid ]], \+uint3 thread_idx [[ thread_position_in_threadgroup ]])++#define innerArguments (logits_data, processed_logits, vocab_size, temperature, threadgroup_idx.x, threadgroup_idx.y, thread_idx.x)++generateKernels(batched_temperature)++#undef outerArguments+#undef innerArgumentsdiff --git a/crates/uzu/src/backends/metal/kernel/sampling/top_k.metal b/crates/uzu/src/backends/metal/kernel/sampling/top_k.metalnew file mode 100644index 000000000..a88d9af88--- /dev/null+++ b/crates/uzu/src/backends/metal/kernel/sampling/top_k.metal@@ -0,0 +1,93 @@+#include <metal_stdlib>+#include "../definitions.metal"++#define BLOCK_SIZE 1024+#define MAX_ITERS 20++template <typename T>+void batched_topk(+ device const T* logits_data,+ device T* processed_logits,+ threadgroup float shared_reduce_buffer[BLOCK_SIZE],+ constant uint& vocab_size,+ constant uint& top_k,+ uint batch_idx,+ uint thread_idx+) {+ uint batch_start = batch_idx * vocab_size;++ // Find min and max logit for binary search+ float local_max = -INFINITY;+ float local_min = INFINITY;+ for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {+ float logit_value = float(logits_data[batch_start + i]);+ local_max = fmax(local_max, logit_value);+ local_min = fmin(local_min, logit_value);+ }+ float max_logit = threadgroup_cooperative_reduce_max<BLOCK_SIZE>(local_max, shared_reduce_buffer, thread_idx);+ float min_logit = threadgroup_cooperative_reduce_min<BLOCK_SIZE>(local_min, shared_reduce_buffer, thread_idx);+++ // Do the binary search on the threshold+ float low = min_logit;+ float high = max_logit;+ float threshold = (min_logit + max_logit) / 2.0;++ for (uint iter = 0; iter < MAX_ITERS; iter++) {+ // Find the mass above threshold+ uint local_num_above_threshold = 0;+ for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {+ float logit_value = float(logits_data[batch_start + i]);+ if (logit_value >= threshold) {+ local_num_above_threshold += 1;+ }+ }+ uint num_above_threshold = threadgroup_cooperative_reduce_sum<BLOCK_SIZE>(local_num_above_threshold, (threadgroup uint*)shared_reduce_buffer, thread_idx);++ // Update binary search+ if (num_above_threshold == top_k) {+ break;+ } else if (num_above_threshold > top_k) {+ low = threshold;+ } else {+ high = threshold;+ }+ threshold = (low + high) / 2.0;+ }++ T t_threshold = T(threshold);++ // We know the threshold, just mask everything below it+ for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {+ T logit_value = logits_data[batch_start + i];+ processed_logits[batch_start + i] = (logit_value >= t_threshold) ? logit_value : T(-INFINITY);+ }+}++#define outerArguments(T) \+(device const T* logits_data [[ buffer(0) ]], \+device T* processed_logits [[ buffer(1) ]], \+constant uint& vocab_size [[ buffer(2) ]], \+constant uint& top_k [[ buffer(3) ]], \+uint3 threadgroup_idx [[ threadgroup_position_in_grid ]], \+uint3 thread_idx [[ thread_position_in_threadgroup ]])++#define innerArguments (logits_data, processed_logits, shared_reduce_buffer, vocab_size, top_k, threadgroup_idx.x, thread_idx.x)++#define generateTopkKernel(functionName, scalarType, outerArgs, innerArgs) \+kernel void functionName##_##scalarType outerArgs { \+ threadgroup float shared_reduce_buffer[BLOCK_SIZE]; \+ functionName innerArgs; \+}++#define generateTopkKernels(functionName) \+generateTopkKernel(functionName, float, outerArguments(float), innerArguments); \+generateTopkKernel(functionName, bfloat, outerArguments(bfloat), innerArguments); \+generateTopkKernel(functionName, half, outerArguments(half), innerArguments);++generateTopkKernels(batched_topk)++#undef outerArguments+#undef innerArguments+#undef generateTopkKernel+#undef generateTopkKernelsdiff --git a/crates/uzu/src/backends/metal/kernel/sampling/top_p.metal b/crates/uzu/src/backends/metal/kernel/sampling/top_p.metalindex e0e1aacf2..e255ee79c 100644--- a/crates/uzu/src/backends/metal/kernel/sampling/top_p.metal+++ b/crates/uzu/src/backends/metal/kernel/sampling/top_p.metal@@ -1,292 +1,105 @@#include <metal_stdlib>-#include <metal_atomic>#include "../definitions.metal"-#include "../rng.metal"-using namespace metal;#define BLOCK_SIZE 1024-#define GRAIN_SIZE 4--struct SamplingTempStorage {- _atomic<uint> sampled_id;- _atomic<int> last_valid_id;- float chunk_prob_sum;- float min_val;- float max_val;- float pivot0_mass_broadcast;- float pivot1_mass_broadcast;-};--inline void process_probability_chunk(- uint chunk_idx, uint vocab_size,- float prob_threshold,- float random_sample,- thread const float (&prob_vec)[GRAIN_SIZE],- thread float &cumulative_prob,- threadgroup SamplingTempStorage& ts,- uint local_id,- threadgroup float* shared_sum,- threadgroup int* shared_max)-{- bool valid[GRAIN_SIZE];- float filtered_probs[GRAIN_SIZE];- float cumulative_distribution[GRAIN_SIZE];-- /* build masked probability vector & validity bits */- for (uint j=0;j<GRAIN_SIZE;++j) {- bool keep_condition = prob_vec[j] > prob_threshold;- filtered_probs[j] = keep_condition ? prob_vec[j] : 0.f;- uint global_token_id = (chunk_idx*BLOCK_SIZE + local_id)*GRAIN_SIZE + j;- valid[j] = keep_condition && global_token_id < vocab_size;- }-- /* 1. block-reduce sum using optimized raking reduction */- float local_sum = filtered_probs[0] + filtered_probs[1] +- filtered_probs[2] + filtered_probs[3];- float block_sum = threadgroup_cooperative_reduce_sum<BLOCK_SIZE>(local_sum, shared_sum, local_id);-- if (local_id == 0) ts.chunk_prob_sum = block_sum;- threadgroup_barrier(mem_flags::mem_threadgroup);- block_sum = ts.chunk_prob_sum;-- /* 2. check if candidate is in this chunk */- if (cumulative_prob + block_sum > random_sample) {- /* compute inclusive scan within this thread's GRAIN_SIZE elements */- thread_prefix_inclusive_sum<GRAIN_SIZE>(filtered_probs);- for (uint j = 0; j < GRAIN_SIZE; ++j) {- cumulative_distribution[j] = filtered_probs[j];- }-- /* get prefix sum from previous threads using optimized raking scan */- float thread_prefix = threadgroup_raking_prefix_exclusive_sum<BLOCK_SIZE>(local_sum, shared_sum, local_id);-- /* add global prefix to local inclusive scan */- for (uint j = 0; j < GRAIN_SIZE; ++j) {- cumulative_distribution[j] += thread_prefix + cumulative_prob;- }-- /* find elements that cross the sample threshold */- bool exceeds_sample[GRAIN_SIZE];- bool is_first_match[GRAIN_SIZE];-- for (uint j = 0; j < GRAIN_SIZE; ++j) {- exceeds_sample[j] = (cumulative_distribution[j] > random_sample) && valid[j];- }-- /* find first match elements (first occurrence in each run) */- is_first_match[0] = exceeds_sample[0];- for (uint j = 1; j < GRAIN_SIZE; ++j) {- is_first_match[j] = exceeds_sample[j] && !exceeds_sample[j-1];- }-- /* atomic update for first qualifying element */- for (uint j = 0; j < GRAIN_SIZE; ++j) {- if (is_first_match[j]) {- uint global_token_id = (chunk_idx*BLOCK_SIZE + local_id)*GRAIN_SIZE + j;- atomic_fetch_min_explicit(&ts.sampled_id, global_token_id, memory_order_relaxed);- }- }- }-- /* 3. update last_valid_id using optimized raking reduction */- int local_last_valid = -1; // sentinel smaller than any real token id- for (uint j = 0; j < GRAIN_SIZE; ++j) {- if (valid[j]) {- local_last_valid = int((chunk_idx*BLOCK_SIZE + local_id)*GRAIN_SIZE + j);- }- }-- int max_valid_token = threadgroup_cooperative_reduce_max<BLOCK_SIZE>(local_last_valid, shared_max, local_id);- if (local_id == 0) {- atomic_fetch_max_explicit(&ts.last_valid_id, max_valid_token, memory_order_relaxed);- }-- /* 4. update running cumulative probability */- cumulative_prob += block_sum;-}--template<typename T>-void topp_sampling_kernel_impl(- const device T* logits,- device uint* out_ids,- constant uint& batch,- constant uint& vocab,+#define MAX_ITERS 20+#define ATOL 1e-6++template <typename T>+void batched_topp(+ device const T* logits_data,+ device T* processed_logits,+ threadgroup float shared_reduce_buffer[BLOCK_SIZE],+ constant uint& vocab_size,constant float& top_p,- constant uint64_t& seed,- threadgroup SamplingTempStorage& ts,- threadgroup float* s_max,- threadgroup float* s_sum,- threadgroup int* s_last_idx,- threadgroup float* shared_pivot0_reduction,- threadgroup float* shared_pivot1_reduction,uint batch_idx,- uint lid)-{- if (batch_idx>=batch) return;-- const uint stride_elems = BLOCK_SIZE * GRAIN_SIZE;- const uint num_vec_chunks = (vocab + stride_elems - 1) / stride_elems;- const uint row_off = batch_idx * vocab;-- PhiloxState rng;- uint64_t philox_offset = batch_idx;- philox_init(&rng, seed, philox_offset);+ uint thread_idx+) {+ uint batch_start = batch_idx * vocab_size;- /* ── init shared with proper barriers */- if (lid==0){- atomic_store_explicit(&ts.sampled_id, vocab, memory_order_relaxed);- atomic_store_explicit(&ts.last_valid_id, -1, memory_order_relaxed);- }- threadgroup_barrier(mem_flags::mem_threadgroup);-- /* ── max-logit reduction using optimized raking reduction */+ // Find min (for binary search) and max (for binary search and softmax)float local_max = -INFINITY;- for(uint i = lid; i < vocab; i += BLOCK_SIZE) {- local_max = max(local_max, float(logits[row_off + i]));+ float local_min = INFINITY;+ for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {+ float logit_value = float(logits_data[batch_start + i]);+ local_max = fmax(local_max, logit_value);+ local_min = fmin(local_min, logit_value);}- float max_logit = threadgroup_cooperative_reduce_max<BLOCK_SIZE>(local_max, s_max, lid);-- /* ── sum-exp reduction using optimized raking reduction */- float local_sum = 0.f;- for (uint i = lid; i < vocab; i += BLOCK_SIZE) {- local_sum += exp(float(logits[row_off + i]) - max_logit);+ float max_logit = threadgroup_cooperative_reduce_max<BLOCK_SIZE>(local_max, shared_reduce_buffer, thread_idx);+ float min_logit = threadgroup_cooperative_reduce_min<BLOCK_SIZE>(local_min, shared_reduce_buffer, thread_idx);++ // Find denominator for softmax+ float local_sum = 0.0f;+ for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {+ float logit_value = float(logits_data[batch_start + i]);+ local_sum += exp(logit_value - max_logit);}- float sum_exp = threadgroup_cooperative_reduce_sum<BLOCK_SIZE>(local_sum, s_sum, lid);-- /* ── rejection-sampling loop */- float low = 0.0f, high = 1.0f, interval_mass = 1.0f;- uint sampled = vocab;-- do {- /* Proper atomic initialization with barriers */- if (lid == 0) {- atomic_store_explicit(&ts.sampled_id , vocab, memory_order_relaxed);- }- threadgroup_barrier(mem_flags::mem_threadgroup);+ float total_sum = threadgroup_cooperative_reduce_sum<BLOCK_SIZE>(local_sum, shared_reduce_buffer, thread_idx);- float sample_target = uniform_float(&rng) * interval_mass;- float running_prob_sum = 0.f;- /* ---------- PASS A ---------- */- for (uint vec_i = 0; vec_i < num_vec_chunks; ++vec_i) {- /* load vec */- float prob_vec[GRAIN_SIZE];- for (uint j = 0; j < GRAIN_SIZE; ++j) {- uint gid = (vec_i * BLOCK_SIZE + lid) * GRAIN_SIZE + j;- prob_vec[j] = (gid < vocab) ? exp(float(logits[row_off + gid]) - max_logit) / sum_exp : 0.f;- }-- process_probability_chunk(- vec_i, vocab,- low,- sample_target,- prob_vec,- running_prob_sum,- ts, lid,- s_sum,- s_last_idx);+ // Do the binary search on the threshold+ float target_mass = top_p * total_sum;- if (running_prob_sum > sample_target) break;- }- threadgroup_barrier(mem_flags::mem_threadgroup);+ float low = min_logit;+ float high = max_logit;+ float threshold = (min_logit + max_logit) / 2.0;- sampled = atomic_load_explicit(&ts.sampled_id, memory_order_relaxed);- if (sampled == vocab) {- int last_valid = atomic_load_explicit(&ts.last_valid_id, memory_order_relaxed);- if (last_valid >= 0) { // only cast when we have a real index- sampled = uint(last_valid);+ for (uint iter = 0; iter < MAX_ITERS; iter++) {+ // Find the mass above threshold+ float local_sum_above_threshold = 0.0f;+ for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {+ float logit_value = float(logits_data[batch_start + i]);+ if (logit_value >= threshold) {+ local_sum_above_threshold += exp(logit_value - max_logit);}}+ float sum_above_threshold = threadgroup_cooperative_reduce_sum<BLOCK_SIZE>(local_sum_above_threshold, shared_reduce_buffer, thread_idx);- /* If we still don't have a valid token, restart the loop */- if (sampled >= vocab) {- continue; // go back to the top of the rejection loop- }-- /* ---------- PASS B ---------- */- float sampled_p = exp(float(logits[row_off + sampled]) - max_logit) / sum_exp;- float pivot0 = sampled_p;- float pivot1 = (pivot0 + high) / 2.0f;-- float pivot0_mass = 0.0f, pivot1_mass = 0.0f;-- for (uint vec_i = 0; vec_i < num_vec_chunks; ++vec_i) {- float local_pivot0_sum = 0.f, local_pivot1_sum = 0.f;- for (uint j = 0; j < GRAIN_SIZE; ++j) {- uint gid = (vec_i * BLOCK_SIZE + lid) * GRAIN_SIZE + j;- if (gid < vocab) {- float p = exp(float(logits[row_off + gid]) - max_logit) / sum_exp;- if (p > pivot0) local_pivot0_sum += p;- if (p > pivot1) local_pivot1_sum += p;- }- }-- float block_pivot0_sum = threadgroup_cooperative_reduce_sum<BLOCK_SIZE>(local_pivot0_sum, shared_pivot0_reduction, lid);- float block_pivot1_sum = threadgroup_cooperative_reduce_sum<BLOCK_SIZE>(local_pivot1_sum, shared_pivot1_reduction, lid);-- if (lid == 0) {- pivot0_mass += block_pivot0_sum;- pivot1_mass += block_pivot1_sum;- }- threadgroup_barrier(mem_flags::mem_threadgroup);+ // Update binary search+ if (sum_above_threshold >= target_mass) {+ low = threshold;+ } else {+ high = threshold;}+ threshold = (low + high) / 2.0;- /* FIX: Broadcast pivot masses to all threads */- if (lid == 0) {- ts.pivot0_mass_broadcast = pivot0_mass;- ts.pivot1_mass_broadcast = pivot1_mass;- }- threadgroup_barrier(mem_flags::mem_threadgroup);- pivot0_mass = ts.pivot0_mass_broadcast;- pivot1_mass = ts.pivot1_mass_broadcast;+ // Exit early if we found it+ if (high - low < ATOL) break;+ }- /* acceptance logic */- if (pivot0_mass < top_p) break;- if (pivot1_mass < top_p) {- low = pivot0; high = pivot1; interval_mass = pivot0_mass;- } else {- low = pivot1; interval_mass = pivot1_mass;- }- } while(low < high);+ T t_threshold = T(low);- if (lid == 0) {- out_ids[batch_idx] = sampled;+ // We know the threshold, just mask everything below it+ for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {+ T logit_value = logits_data[batch_start + i];+ processed_logits[batch_start + i] = (logit_value >= t_threshold) ? logit_value : T(-INFINITY);}}-// Generate top-p kernels using macro approach#define outerArguments(T) \(device const T* logits_data [[ buffer(0) ]], \-device uint* sampled_tokens [[ buffer(1) ]], \-constant uint& batch_size [[ buffer(2) ]], \-constant uint& vocab_size [[ buffer(3) ]], \-constant float& top_p [[ buffer(4) ]], \-constant uint64_t& seed [[ buffer(5) ]], \-uint batch_idx [[ threadgroup_position_in_grid ]], \-uint local_id [[ thread_position_in_threadgroup ]])--#define innerArguments \-(logits_data, sampled_tokens, batch_size, vocab_size, top_p, seed, temp_storage, shared_max, shared_sum, shared_last_idx, shared_pivot0_reduction, shared_pivot1_reduction, batch_idx, local_id)--#define generateToppKernel(functionName, T, outerArgs, innerArgs) \-kernel void functionName##_##T outerArgs { \- threadgroup SamplingTempStorage temp_storage; \- threadgroup float shared_max[BLOCK_SIZE]; \- threadgroup float shared_sum[BLOCK_SIZE]; \- threadgroup int shared_last_idx[BLOCK_SIZE]; \- threadgroup float shared_pivot0_reduction[BLOCK_SIZE]; \- threadgroup float shared_pivot1_reduction[BLOCK_SIZE]; \- topp_sampling_kernel_impl<T> innerArgs; \+device T* processed_logits [[ buffer(1) ]], \+constant uint& vocab_size [[ buffer(2) ]], \+constant float& top_p [[ buffer(3) ]], \+uint3 threadgroup_idx [[ threadgroup_position_in_grid ]], \+uint3 thread_idx [[ thread_position_in_threadgroup ]])++#define innerArguments (logits_data, processed_logits, shared_reduce_buffer, vocab_size, top_p, threadgroup_idx.x, thread_idx.x)++#define generateToppKernel(functionName, scalarType, outerArgs, innerArgs) \+kernel void functionName##_##scalarType outerArgs { \+ threadgroup float shared_reduce_buffer[BLOCK_SIZE]; \+ functionName innerArgs; \}-generateToppKernel(batched_topp_main, float, outerArguments(float), innerArguments)-generateToppKernel(batched_topp_main, half, outerArguments(half), innerArguments)-generateToppKernel(batched_topp_main, bfloat, outerArguments(bfloat), innerArguments)+#define generateToppKernels(functionName) \+generateToppKernel(functionName, float, outerArguments(float), innerArguments); \+generateToppKernel(functionName, bfloat, outerArguments(bfloat), innerArguments); \+generateToppKernel(functionName, half, outerArguments(half), innerArguments);++generateToppKernels(batched_topp)#undef outerArguments#undef innerArguments#undef generateToppKernel--#undef BLOCK_SIZE-#undef GRAIN_SIZE-+#undef generateToppKernelsdiff --git a/crates/uzu/src/generator/context.rs b/crates/uzu/src/generator/context.rsindex 4426fc7a3..8d1282e0a 100644--- a/crates/uzu/src/generator/context.rs+++ b/crates/uzu/src/generator/context.rs@@ -13,6 +13,7 @@ use crate::{kernel::SamplingKernelEncodable,},config::{LanguageModelConfig, ModelMetadata},+ generator::rng::DerivableSeed,parameters::ParameterLoader,session::{config::DecodingConfig,@@ -34,6 +35,7 @@ pub struct GeneratorContext {pub executables: DecoderExecutables,pub kv_cache_update: Box<KVCacheUpdate>,pub gpu_sampler: SamplingKernelEncodable,+ pub next_seed: DerivableSeed,}impl GeneratorContext {@@ -134,10 +136,12 @@ impl GeneratorContext {kernel_data_type,max_suffix_length,decoder_config.vocab_size,- decoding_config.sampling_seed.resolve(),).map_err(|_| Error::UnableToCreateMetalContext)?;+ let base_seed = decoding_config.sampling_seed.resolve();+ let next_seed = DerivableSeed::new(base_seed);+let context = Self {mtl_context,command_buffer,@@ -149,6 +153,7 @@ impl GeneratorContext {executables,kv_cache_update,gpu_sampler,+ next_seed,};return Ok(context);diff --git a/crates/uzu/src/generator/generator.rs b/crates/uzu/src/generator/generator.rsindex 66f9d57ad..d1ddcf0b9 100644--- a/crates/uzu/src/generator/generator.rs+++ b/crates/uzu/src/generator/generator.rs@@ -88,6 +88,7 @@ impl Generator {let speculator = &self.decoding_config.speculator_config.speculator;let speculated_suffix = TokenTrie::from_speculator(&tokens,+ &mut self.context.next_seed,false,speculator.as_ref(),&TrieCreationConfig::default(),@@ -118,6 +119,16 @@ impl Generator {padded_positions.extend(std::iter::repeat(INVALID_POSITION).take(padding_count));+ let zero_padding_left_seeds: Vec<u64> = vec![0; tokens_length];+ let zero_padding_right_seeds: Vec<u64> =+ vec![0; unused_tokens_count - speculated_suffix.seeds.len()];+ let padded_seeds = [+ &zero_padding_left_seeds[..],+ &speculated_suffix.seeds[..],+ &zero_padding_right_seeds[..],+ ]+ .concat();+let mut last_state: Option<ForwardPassState> = None;let mut run_times: Vec<f64> = Vec::new();@@ -129,6 +140,8 @@ impl Generator {&padded_tokens[tokens_start_index..tokens_end_index];let positions_for_step =&padded_positions[tokens_start_index..tokens_end_index];+ let seeds_for_step =+ &padded_seeds[tokens_start_index..tokens_end_index];let is_first_prefill = step == 0;let should_capture =@@ -147,6 +160,7 @@ impl Generator {let task = GeneratorRunTask {token_ids: tokens_for_step.to_vec(),token_positions: positions_for_step.to_vec(),+ token_seeds: seeds_for_step.to_vec(),expected_number_of_new_tokens: prefill_step_size,};@@ -265,6 +279,7 @@ impl Generator {let speculator = &self.decoding_config.speculator_config.speculator;let speculated_suffix = TokenTrie::from_speculator(&self.tokens,+ &mut self.context.next_seed,true,speculator.as_ref(),&TrieCreationConfig::default(),@@ -276,10 +291,15 @@ impl Generator {self.decoding_config.generate_suffix_length();let unused_tokens_count =expected_suffix_length - speculated_suffix.tokens.len();+let zero_padding_tokens: Vec<u64> = vec![0; unused_tokens_count];let padded_tokens =[speculated_suffix.tokens.clone(), zero_padding_tokens].concat();+ let zero_padding_seeds: Vec<u64> = vec![0; unused_tokens_count];+ let padded_seeds =+ [speculated_suffix.seeds.clone(), zero_padding_seeds].concat();+let start_position = self.tokens.len() - 1;let padded_positions: Vec<usize> = speculated_suffix@@ -294,6 +314,7 @@ impl Generator {let task = GeneratorRunTask {token_ids: padded_tokens,token_positions: padded_positions,+ token_seeds: padded_seeds,expected_number_of_new_tokens: 1,};@@ -362,10 +383,12 @@ impl Generator {let task = GeneratorRunTask {token_ids: vec![0; suffix_length],token_positions: (0..suffix_length).collect::<Vec<usize>>(),+ token_seeds: vec![0; suffix_length],expected_number_of_new_tokens: suffix_length,};- let (_, _) = self.run_model(task, true, false, SamplingMethod::Greedy);+ let (_, _) =+ self.run_model(task, true, false, SamplingMethod::default());}fn run_model(diff --git a/crates/uzu/src/generator/gumbel.rs b/crates/uzu/src/generator/gumbel.rsnew file mode 100644index 000000000..73f371a9e--- /dev/null+++ b/crates/uzu/src/generator/gumbel.rs@@ -0,0 +1,90 @@+use std::collections::HashMap;++const PHILOX_W32_0: u32 = 0x9E3779B9;+const PHILOX_W32_1: u32 = 0xBB67AE85;+const PHILOX_M4X32_0: u32 = 0xD2511F53;+const PHILOX_M4X32_1: u32 = 0xCD9E8D57;++#[inline]+fn mulhilo32(+ a: u32,+ b: u32,+) -> (u32, u32) {+ let product = (a as u64) * (b as u64);+ ((product >> 32) as u32, product as u32)+}++#[inline]+fn philox4x32_round(+ ctr: &mut [u32; 4],+ key: &[u32; 2],+) {+ let (hi0, lo0) = mulhilo32(PHILOX_M4X32_0, ctr[0]);+ let (hi1, lo1) = mulhilo32(PHILOX_M4X32_1, ctr[2]);++ let new_ctr = [hi1 ^ ctr[1] ^ key[0], lo1, hi0 ^ ctr[3] ^ key[1], lo0];++ *ctr = new_ctr;+}++#[inline]+fn philox4x32_bumpkey(key: &mut [u32; 2]) {+ key[0] = key[0].wrapping_add(PHILOX_W32_0);+ key[1] = key[1].wrapping_add(PHILOX_W32_1);+}++pub fn uniform_float(+ key: u64,+ (offset, word): (u32, u32),+) -> f32 {+ let mut ctr = [offset, 0, 0, 0];++ let mut key = [key as u32, (key >> 32) as u32];++ philox4x32_round(&mut ctr, &key);++ for _ in 0..9 {+ philox4x32_bumpkey(&mut key);+ philox4x32_round(&mut ctr, &key);+ }++ ctr[word as usize] as f32 * (1.0 / 4294967296.0)+}++pub fn gumbel_float(+ key: u64,+ (offset, word): (u32, u32),+) -> f32 {+ -f32::ln(-f32::ln(uniform_float(key, (offset, word))))+}++const BLOCK_SIZE: u32 = 1024;+const GRAIN_SIZE: u32 = 64;+const BLOCKGRAIN_SIZE: u32 = BLOCK_SIZE * GRAIN_SIZE;+const WORDS_PER_OFFSET: u32 = 4;++pub fn revidx(logit_idx: u32) -> (u32, u32) {+ let global_idx = logit_idx / BLOCKGRAIN_SIZE;+ let logit_idx_in_blockgrain = logit_idx % BLOCKGRAIN_SIZE;+ let grain_idx = logit_idx_in_blockgrain / BLOCK_SIZE;+ let local_idx = logit_idx_in_blockgrain % BLOCK_SIZE;++ let rng_offset = (global_idx * BLOCK_SIZE + local_idx)+ * (GRAIN_SIZE + WORDS_PER_OFFSET - 1)+ / WORDS_PER_OFFSET+ + grain_idx / WORDS_PER_OFFSET;+ let rng_word = grain_idx % WORDS_PER_OFFSET;++ (rng_offset, rng_word)+}++pub fn speculator_sample(+ seed: u64,+ speculator_probs: &HashMap<u64, f32>,+) -> Option<u64> {+ speculator_probs+ .iter()+ .map(|(&k, &v)| (k, f32::ln(v) + gumbel_float(seed, revidx(k as u32))))+ .max_by(|(_ak, av), (_bk, bv)| f32::total_cmp(av, bv))+ .map(|(k, _v)| k)+}diff --git a/crates/uzu/src/generator/mod.rs b/crates/uzu/src/generator/mod.rsindex 7f2575f42..c599c436e 100644--- a/crates/uzu/src/generator/mod.rs+++ b/crates/uzu/src/generator/mod.rs@@ -1,6 +1,8 @@pub mod context;pub mod generator;pub mod gpu_capture;+pub mod gumbel;pub mod result;+pub mod rng;pub mod sampler;pub mod tasks;diff --git a/crates/uzu/src/generator/rng.rs b/crates/uzu/src/generator/rng.rsnew file mode 100644index 000000000..d758e2fe3--- /dev/null+++ b/crates/uzu/src/generator/rng.rs@@ -0,0 +1,29 @@+pub struct DerivableSeed {+ base_seed: u64,+ invocation: u64,+}++impl DerivableSeed {+ pub fn new(seed: u64) -> Self {+ Self {+ base_seed: seed,+ invocation: 0,+ }+ }++ pub fn current(&self) -> u64 {+ let mut hash = self.base_seed.wrapping_add(self.invocation);+ hash ^= hash >> 33;+ hash = hash.wrapping_mul(0xff51afd7ed558ccd);+ hash ^= hash >> 33;+ hash = hash.wrapping_mul(0xc4ceb9fe1a85ec53);+ hash ^= hash >> 33;+ hash+ }++ pub fn next(&mut self) -> u64 {+ self.invocation += 1;++ self.current()+ }+}diff --git a/crates/uzu/src/generator/tasks.rs b/crates/uzu/src/generator/tasks.rsindex 89b685d54..0365df800 100644--- a/crates/uzu/src/generator/tasks.rs+++ b/crates/uzu/src/generator/tasks.rs@@ -14,6 +14,7 @@ pub struct GeneratorEncodedTask {pub struct GeneratorRunTask {pub token_ids: Vec<u64>,pub token_positions: Vec<usize>,+ pub token_seeds: Vec<u64>,pub expected_number_of_new_tokens: usize,}@@ -22,6 +23,7 @@ impl GeneratorRunTask {GeneratorRunTask {token_ids: self.token_ids.clone(),token_positions: self.token_positions.clone(),+ token_seeds: self.token_seeds.clone(),expected_number_of_new_tokens: self.expected_number_of_new_tokens,}}@@ -50,6 +52,7 @@ impl GeneratorRunTask {context.shared_buffers.clone(),&self.token_ids,&self.token_positions,+ &self.token_seeds,false,external_bias_fn,);diff --git a/crates/uzu/src/linearizer/node.rs b/crates/uzu/src/linearizer/node.rsindex 1d7cf92fd..62df6cb1d 100644--- a/crates/uzu/src/linearizer/node.rs+++ b/crates/uzu/src/linearizer/node.rs@@ -35,6 +35,7 @@ impl Node {pub fn get_or_insert_next(&mut self,token: u64,+ seed: u64,) -> &mut Node {if let Some(pos) =self.transitions.iter().position(|t| t.token() == token)@@ -42,23 +43,23 @@ impl Node {return &mut self.transitions[pos].node;}- self.transitions.push(Transition::new(token));+ self.transitions.push(Transition::new(token, seed));&mut self.transitions.last_mut().unwrap().node}pub fn dfs_with_path<F>(&self,- path: &mut Vec<(isize, u64)>,+ path: &mut Vec<(isize, u64, u64)>,callback: &mut F,) -> isizewhere- F: FnMut(&[(isize, u64)]),+ F: FnMut(&[(isize, u64, u64)]),{- let mut node_index = path.last().map(|(idx, _)| *idx).unwrap_or(-1);+ let mut node_index = path.last().map(|(idx, _, _)| *idx).unwrap_or(-1);for transition in self.transitions.iter() {node_index += 1;- path.push((node_index, transition.token()));+ path.push((node_index, transition.token(), transition.seed()));callback(path);node_index = transition.node.dfs_with_path(path, callback);path.pop();@@ -71,9 +72,9 @@ impl Node {&self,mut callback: F,) where- F: FnMut(&[(isize, u64)]),+ F: FnMut(&[(isize, u64, u64)]),{- let mut path: Vec<(isize, u64)> = Vec::new();+ let mut path: Vec<(isize, u64, u64)> = Vec::new();self.dfs_with_path(&mut path, &mut callback);}}diff --git a/crates/uzu/src/linearizer/speculated_suffix.rs b/crates/uzu/src/linearizer/speculated_suffix.rsindex 3e8cd775f..2f3874036 100644--- a/crates/uzu/src/linearizer/speculated_suffix.rs+++ b/crates/uzu/src/linearizer/speculated_suffix.rs@@ -3,6 +3,7 @@ use std::collections::HashMap;#[derive(Debug)]pub struct SpeculatedSuffix {pub tokens: Vec<u64>,+ pub seeds: Vec<u64>,pub indices: Vec<usize>,pub transition_map: HashMap<isize, HashMap<u64, isize>>,}diff --git a/crates/uzu/src/linearizer/tests_node.rs b/crates/uzu/src/linearizer/tests_node.rsindex 0440c8eda..9f4680d76 100644--- a/crates/uzu/src/linearizer/tests_node.rs+++ b/crates/uzu/src/linearizer/tests_node.rs@@ -15,7 +15,7 @@ mod tests {#[test]fn test_has_transition() {let mut node = Node::new();- node.get_or_insert_next(42);+ node.get_or_insert_next(42, 0);assert!(node.has_transition(42));assert!(!node.has_transition(43));@@ -24,7 +24,7 @@ mod tests {#[test]fn test_get_next() {let mut node = Node::new();- node.get_or_insert_next(1);+ node.get_or_insert_next(1, 0);assert!(node.get_next(1).is_some());assert!(node.get_next(2).is_none());@@ -35,20 +35,20 @@ mod tests {let mut node = Node::new();// First insertion should create a new node- let node1 = node.get_or_insert_next(1);+ let node1 = node.get_or_insert_next(1, 0);assert!(!node1.has_transition(99));// Add a transition to the child node- node1.get_or_insert_next(99);+ node1.get_or_insert_next(99, 0);// Get the same node again- let node1_again = node.get_or_insert_next(1);+ let node1_again = node.get_or_insert_next(1, 0);// Verify it's the same node by checking it has the transition we addedassert!(node1_again.has_transition(99));// Different token should give a different node- let node2 = node.get_or_insert_next(2);+ let node2 = node.get_or_insert_next(2, 0);assert!(!node2.has_transition(99));}@@ -58,7 +58,7 @@ mod tests {// Insert several transitionsfor i in 0..5 {- node.get_or_insert_next(i);+ node.get_or_insert_next(i, 0);}// Verify all transitions exist@@ -75,15 +75,16 @@ mod tests {#[test]fn test_dfs_with_path_empty_node() {let node = Node::new();- let mut path: Vec<(isize, u64)> = Vec::new();+ let mut path: Vec<(isize, u64, u64)> = Vec::new();let mut visited = Vec::new();node.dfs_with_path(&mut path, &mut |current_path: &[(isize,u64,+ u64,)]| {let tokens: Vec<u64> =- current_path.iter().map(|(_, token)| *token).collect();+ current_path.iter().map(|(_, token, _)| *token).collect();visited.push(tokens);});@@ -93,17 +94,18 @@ mod tests {#[test]fn test_dfs_with_path_single_node() {let mut node = Node::new();- node.get_or_insert_next(42);+ node.get_or_insert_next(42, 0);- let mut path: Vec<(isize, u64)> = Vec::new();+ let mut path: Vec<(isize, u64, u64)> = Vec::new();let mut visited = Vec::new();node.dfs_with_path(&mut path, &mut |current_path: &[(isize,u64,+ u64,)]| {let tokens: Vec<u64> =- current_path.iter().map(|(_, token)| *token).collect();+ current_path.iter().map(|(_, token, _)| *token).collect();visited.push(tokens);});@@ -116,22 +118,23 @@ mod tests {let mut root = Node::new();// Build a sample trie: [1 -> 2 -> 3], [1 -> 2 -> 4], [1 -> 5], [6]- let node1 = root.get_or_insert_next(1);- let node2 = node1.get_or_insert_next(2);- node2.get_or_insert_next(3);- node2.get_or_insert_next(4);- node1.get_or_insert_next(5);- root.get_or_insert_next(6);-- let mut path: Vec<(isize, u64)> = Vec::new();+ let node1 = root.get_or_insert_next(1, 0);+ let node2 = node1.get_or_insert_next(2, 0);+ node2.get_or_insert_next(3, 0);+ node2.get_or_insert_next(4, 0);+ node1.get_or_insert_next(5, 0);+ root.get_or_insert_next(6, 0);++ let mut path: Vec<(isize, u64, u64)> = Vec::new();let mut visited = Vec::new();root.dfs_with_path(&mut path, &mut |current_path: &[(isize,u64,+ u64,)]| {let tokens: Vec<u64> =- current_path.iter().map(|(_, token)| *token).collect();+ current_path.iter().map(|(_, token, _)| *token).collect();visited.push(tokens);});@@ -150,15 +153,16 @@ mod tests {let mut root = Node::new();// Build a simple trie: [1], [2]- root.get_or_insert_next(1);- root.get_or_insert_next(2);+ root.get_or_insert_next(1, 0);+ root.get_or_insert_next(2, 0);- let mut path: Vec<(isize, u64)> = Vec::new();+ let mut path: Vec<(isize, u64, u64)> = Vec::new();let mut indices = Vec::new();root.dfs_with_path(&mut path, &mut |current_path: &[(isize,u64,+ u64,)]| {if !current_path.is_empty() {indices.push(current_path.last().unwrap().0);@@ -176,9 +180,9 @@ mod tests {let node = Node::new();let mut visited = Vec::new();- node.dfs(|current_path: &[(isize, u64)]| {+ node.dfs(|current_path: &[(isize, u64, u64)]| {let tokens: Vec<u64> =- current_path.iter().map(|(_, token)| *token).collect();+ current_path.iter().map(|(_, token, _)| *token).collect();visited.push(tokens);});@@ -190,18 +194,18 @@ mod tests {let mut root = Node::new();// Build a sample trie: [1 -> 2 -> 3], [1 -> 2 -> 4], [1 -> 5], [6]- let node1 = root.get_or_insert_next(1);- let node2 = node1.get_or_insert_next(2);- node2.get_or_insert_next(3);- node2.get_or_insert_next(4);- node1.get_or_insert_next(5);- root.get_or_insert_next(6);+ let node1 = root.get_or_insert_next(1, 0);+ let node2 = node1.get_or_insert_next(2, 0);+ node2.get_or_insert_next(3, 0);+ node2.get_or_insert_next(4, 0);+ node1.get_or_insert_next(5, 0);+ root.get_or_insert_next(6, 0);let mut visited = Vec::new();- root.dfs(|current_path: &[(isize, u64)]| {+ root.dfs(|current_path: &[(isize, u64, u64)]| {let tokens: Vec<u64> =- current_path.iter().map(|(_, token)| *token).collect();+ current_path.iter().map(|(_, token, _)| *token).collect();visited.push(tokens);});@@ -220,33 +224,34 @@ mod tests {let mut root = Node::new();// Build a more complex trie- let node1 = root.get_or_insert_next(10);- let node2 = node1.get_or_insert_next(20);- node2.get_or_insert_next(30);- node2.get_or_insert_next(40);- node1.get_or_insert_next(50);- let node3 = root.get_or_insert_next(60);- node3.get_or_insert_next(70);+ let node1 = root.get_or_insert_next(10, 0);+ let node2 = node1.get_or_insert_next(20, 0);+ node2.get_or_insert_next(30, 0);+ node2.get_or_insert_next(40, 0);+ node1.get_or_insert_next(50, 0);+ let node3 = root.get_or_insert_next(60, 0);+ node3.get_or_insert_next(70, 0);// Get results from dfs_with_path- let mut path: Vec<(isize, u64)> = Vec::new();+ let mut path: Vec<(isize, u64, u64)> = Vec::new();let mut visited1 = Vec::new();root.dfs_with_path(&mut path, &mut |current_path: &[(isize,u64,+ u64,)]| {let tokens: Vec<u64> =- current_path.iter().map(|(_, token)| *token).collect();+ current_path.iter().map(|(_, token, _)| *token).collect();visited1.push(tokens);});// Get results from simplified dfslet mut visited2 = Vec::new();- root.dfs(|current_path: &[(isize, u64)]| {+ root.dfs(|current_path: &[(isize, u64, u64)]| {let tokens: Vec<u64> =- current_path.iter().map(|(_, token)| *token).collect();+ current_path.iter().map(|(_, token, _)| *token).collect();visited2.push(tokens);});diff --git a/crates/uzu/src/linearizer/transition.rs b/crates/uzu/src/linearizer/transition.rsindex f2f9e65c3..76426fe6c 100644--- a/crates/uzu/src/linearizer/transition.rs+++ b/crates/uzu/src/linearizer/transition.rs@@ -3,13 +3,18 @@ use super::node::Node;#[derive(Debug)]pub struct Transition {token: u64,+ seed: u64,pub node: Node,}impl Transition {- pub fn new(token: u64) -> Self {+ pub fn new(+ token: u64,+ seed: u64,+ ) -> Self {Self {token,+ seed,node: Node::new(),}}@@ -17,4 +22,8 @@ impl Transition {pub fn token(&self) -> u64 {self.token}++ pub fn seed(&self) -> u64 {+ self.seed+ }}diff --git a/crates/uzu/src/linearizer/trie.rs b/crates/uzu/src/linearizer/trie.rsindex 6e93350f3..6ac26b5ff 100644--- a/crates/uzu/src/linearizer/trie.rs+++ b/crates/uzu/src/linearizer/trie.rs@@ -1,6 +1,8 @@use std::collections::HashMap;-use crate::speculators::speculator::Speculator;+use crate::{+ generator::rng::DerivableSeed, speculators::speculator::Speculator,+};use super::{node::Node, speculated_suffix::SpeculatedSuffix};@@ -38,6 +40,7 @@ impl TokenTrie {pub fn from_speculator(prefix: &[u64],+ seed: &mut DerivableSeed,include_last_prefix_token: bool,speculator: &dyn Speculator,creation_config: &TrieCreationConfig,@@ -48,8 +51,8 @@ impl TokenTrie {let mut trie_size = 0;if include_last_prefix_token {- current_node =- current_node.get_or_insert_next(*prefix.last().unwrap());+ current_node = current_node+ .get_or_insert_next(*prefix.last().unwrap(), seed.current());trie_size += 1;}@@ -77,24 +80,16 @@ impl TokenTrie {trie_size += arr.len();for &(tok, _) in arr.iter() {- current_node.get_or_insert_next(tok);+ current_node.get_or_insert_next(tok, seed.next());}- current_node = current_node.get_or_insert_next(top_token);+ current_node = current_node.get_or_insert_next(top_token, 0);speculation_prefix.push(top_token);}trie}- pub fn from_sequences(sequences: &[Vec<u64>]) -> Self {- let mut trie = Self::new();- for sequence in sequences {- trie.insert(sequence);- }- trie- }-pub fn insert<'a, I>(&mut self,sequence: I,@@ -103,7 +98,7 @@ impl TokenTrie {{let mut current_node = &mut self.root;for &token in sequence {- current_node = current_node.get_or_insert_next(token);+ current_node = current_node.get_or_insert_next(token, 0);}}@@ -113,6 +108,7 @@ impl TokenTrie {max_length: usize,) -> SpeculatedSuffix {let mut tokens = Vec::new();+ let mut seeds = Vec::new();let mut indices = Vec::new();self.root.dfs(|path| {@@ -121,6 +117,7 @@ impl TokenTrie {}if !path.is_empty() {tokens.push(path.last().unwrap().1);+ seeds.push(path.last().unwrap().2);indices.push(start_index + path.len() - 1);}});@@ -142,7 +139,7 @@ impl TokenTrie {return;}- let (current_index, current_token) = *path.last().unwrap();+ let (current_index, current_token, _) = *path.last().unwrap();let parent_index = if path.len() > 1 {path[path.len() - 2].0} else {@@ -157,6 +154,7 @@ impl TokenTrie {SpeculatedSuffix {tokens,indices,+ seeds,transition_map,}}diff --git a/crates/uzu/src/runners/decoder_runner.rs b/crates/uzu/src/runners/decoder_runner.rsindex 3de9f4042..9b8693ff3 100644--- a/crates/uzu/src/runners/decoder_runner.rs+++ b/crates/uzu/src/runners/decoder_runner.rs@@ -106,6 +106,7 @@ impl DecoderTestContext {let token_ids: Vec<u64> =(0..max_suffix_length).map(|i| (i % 1000) as u64).collect();let token_positions: Vec<usize> = (0..max_suffix_length).collect();+ let token_seeds: Vec<u64> = (0_u64..max_suffix_length as u64).collect();// Scratch buffers sized for the maximum prefix/suffix lengths in this testlet scratch_buffers = ForwardPassBuffers::new(@@ -125,6 +126,7 @@ impl DecoderTestContext {shared_buffers.clone(),&token_ids,&token_positions,+ &token_seeds,false,None,);diff --git a/crates/uzu/src/session/parameter/sampling_policy.rs b/crates/uzu/src/session/parameter/sampling_policy.rsindex 89a1e41d9..f4c5745f1 100644--- a/crates/uzu/src/session/parameter/sampling_policy.rs+++ b/crates/uzu/src/session/parameter/sampling_policy.rs@@ -5,11 +5,10 @@ use crate::{#[derive(Debug, Copy, Clone, PartialEq)]pub enum SamplingMethod {Greedy,- Temperature {- temperature: f32,- },- TopP {- top_p: f32,+ Stochastic {+ temperature: Option<f32>,+ top_k: Option<u32>,+ top_p: Option<f32>,},}@@ -42,18 +41,10 @@ impl ConfigResolvableValue<LanguageModelConfig, SamplingMethod>) -> SamplingMethod {let generation_config = &config.generation_config;match self {- SamplingPolicy::Default => {- if let Some(top_p) = generation_config.top_p {- return SamplingMethod::TopP {- top_p: top_p,- };- }- if let Some(temperature) = generation_config.temperature {- return SamplingMethod::Temperature {- temperature: temperature,- };- }- return SamplingMethod::Greedy;+ SamplingPolicy::Default => SamplingMethod::Stochastic {+ temperature: generation_config.temperature,+ top_k: generation_config.top_k,+ top_p: generation_config.top_p,},SamplingPolicy::Custom {value,diff --git a/crates/uzu/src/tracer/tracer.rs b/crates/uzu/src/tracer/tracer.rsindex 93fbb1626..7caec808f 100644--- a/crates/uzu/src/tracer/tracer.rs+++ b/crates/uzu/src/tracer/tracer.rs@@ -30,7 +30,7 @@ use crate::{config::{DecodingConfig, SpeculatorConfig},parameter::{ConfigResolvableValue, ContextLength, ContextMode, PrefillStepSize,- ResolvableValue, SamplingSeed,+ SamplingSeed,},},};@@ -269,13 +269,11 @@ impl Tracer {.expect("Failed to create KV cache update kernel"),);- let sampling_seed = decoding_config.sampling_seed.resolve();context.gpu_sampler = SamplingKernelEncodable::new(&context.mtl_context,kernel_dtype,desired_suffix_length,decoder_config.vocab_size,- sampling_seed,).expect("Failed to create sampling kernel");}@@ -303,6 +301,8 @@ impl Tracer {"activation_trace.token_positions".to_string(),);+ let token_seeds: Vec<u64> = vec![0; token_ids.len()];+let mut state = ForwardPassState::new(self.generator_context.mtl_context.clone(),&self.generator_context.model_config.decoder_config,@@ -312,6 +312,7 @@ impl Tracer {self.generator_context.shared_buffers.clone(),&token_ids,&token_positions,+ &token_seeds,true,None,);diff --git a/crates/uzu/tests/sampling_test.rs b/crates/uzu/tests/sampling_test.rsindex 2e9e8e9ab..91b950a70 100644--- a/crates/uzu/tests/sampling_test.rs+++ b/crates/uzu/tests/sampling_test.rs@@ -1,15 +1,14 @@mod common;use metal::{Device, MTLResourceOptions};-use rand::seq::SliceRandom; // for Vec::shuffle+use rand::{Rng, seq::SliceRandom};+// for Vec::shuffleuse uzu::{backends::metal::{KernelDataType, MTLContext,- kernel::{- SamplingKernel,- sampling::{ArgmaxStrategy, CategoricalStrategy},- },+ kernel::{SamplingKernel, sampling::ArgmaxStrategy},metal_extensions::command_buffer_extensions::CommandBufferTimingAccess,},+ generator::gumbel::{gumbel_float, revidx},session::parameter::SamplingMethod,};@@ -35,6 +34,7 @@ fn cpu_reference_top_p(.enumerate().map(|(idx, &z)| (idx, (z - max_logit).exp())).collect();+ let total_mass: f32 = softmax.iter().map(|(_, p)| p).sum();// 2. sort descendingsoftmax.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());@@ -42,7 +42,8 @@ fn cpu_reference_top_p(// 3. accumulate until cumulative ≥ top_plet mut cum = 0.0_f32;let mut cutoff = 0;- while cutoff < softmax.len() && cum < top_p {+ let target = top_p * total_mass;+ while cutoff < softmax.len() && cum < target {cum += softmax[cutoff].1;cutoff += 1;}@@ -76,7 +77,6 @@ fn test_argmax_sampling_with_strategy(strategy: ArgmaxStrategy) {batch_size,vocab_size,strategy,- TEST_SAMPLING_SEED,).expect("Failed to create argmax kernel");@@ -105,9 +105,10 @@ fn test_argmax_sampling_with_strategy(strategy: ArgmaxStrategy) {// Run samplingkernel.encode(- &SamplingMethod::Greedy,&logits_buffer,+ None,&output_buffer,+ SamplingMethod::Greedy,batch_size,vocab_size,&command_buffer,@@ -178,7 +179,6 @@ fn test_topp_sampling_from_prob_exact_match(KernelDataType::Float32,batch_size,vocab_size,- TEST_SAMPLING_SEED,).expect("Failed to create sampling kernel");@@ -233,16 +233,26 @@ fn test_topp_sampling_from_prob_exact_match(let mut counter = vec![0i32; batch_size * vocab_size];// Draw samples- for _draw in 0..num_samples {+ for draw in 0..num_samples {+ let seeds_buf = context.device.new_buffer_with_data(+ vec![TEST_SAMPLING_SEED + draw as u64; batch_size].as_ptr()+ as *const _,+ (batch_size * std::mem::size_of::<u64>()) as u64,+ metal::MTLResourceOptions::StorageModeShared,+ );+let cb_ref = context.command_queue.new_command_buffer();let cb = cb_ref.to_owned();kernel.encode(- &SamplingMethod::TopP {- top_p: p,- },&logits_buf,+ Some(&seeds_buf),&output_buf,+ SamplingMethod::Stochastic {+ temperature: None,+ top_k: None,+ top_p: Some(p),+ },batch_size,vocab_size,&cb,@@ -315,14 +325,9 @@ fn test_topp_sampling_statistical_large() {const TOLERANCE_KL: f32 = 0.05;// ===== 3. Build kernel =====- let kernel = SamplingKernel::new(- &context,- KernelDataType::Float32,- BATCH,- VOCAB,- TEST_SAMPLING_SEED,- )- .expect("Failed to create sampling kernel");+ let kernel =+ SamplingKernel::new(&context, KernelDataType::Float32, BATCH, VOCAB)+ .expect("Failed to create sampling kernel");// ===== 4. Generate reproducible random logits =====let mut rng = StdRng::seed_from_u64(42);@@ -355,17 +360,26 @@ fn test_topp_sampling_statistical_large() {let mut counters = vec![0u32; BATCH * VOCAB];// ===== 8. Draw NUM_DRAWS samples =====- for _ in 0..NUM_DRAWS {+ for draw in 0..NUM_DRAWS {+ let seeds_buf = context.device.new_buffer_with_data(+ vec![TEST_SAMPLING_SEED + draw as u64; BATCH].as_ptr() as *const _,+ (BATCH * std::mem::size_of::<u64>()) as u64,+ metal::MTLResourceOptions::StorageModeShared,+ );+let cb_ref = context.command_queue.new_command_buffer();let cb = cb_ref.to_owned();kernel.encode(- &SamplingMethod::TopP {- top_p: TOP_P,- },&logits_buf,+ Some(&seeds_buf),&output_buf,+ SamplingMethod::Stochastic {+ temperature: None,+ top_k: None,+ top_p: Some(TOP_P),+ },BATCH,VOCAB,&cb,@@ -432,14 +446,9 @@ fn perf_topp_128k_vocab() {const TOP_P: f32 = 0.9;// ---- Kernel ----- let kernel = SamplingKernel::new(- &context,- KernelDataType::Float32,- BATCH,- VOCAB,- TEST_SAMPLING_SEED,- )- .expect("Failed to create sampling kernel");+ let kernel =+ SamplingKernel::new(&context, KernelDataType::Float32, BATCH, VOCAB)+ .expect("Failed to create sampling kernel");// ---- Build random logits ----let mut rng = StdRng::seed_from_u64(123);@@ -454,6 +463,12 @@ fn perf_topp_128k_vocab() {metal::MTLResourceOptions::StorageModeShared,);+ let seeds_buf = context.device.new_buffer_with_data(+ vec![TEST_SAMPLING_SEED; BATCH].as_ptr() as *const _,+ (BATCH * std::mem::size_of::<u64>()) as u64,+ metal::MTLResourceOptions::StorageModeShared,+ );+let output_buf = context.device.new_buffer((BATCH * std::mem::size_of::<u32>()) as u64,metal::MTLResourceOptions::StorageModeShared,@@ -465,11 +480,14 @@ fn perf_topp_128k_vocab() {kernel.encode(- &SamplingMethod::TopP {- top_p: TOP_P,- },&logits_buf,+ Some(&seeds_buf),&output_buf,+ SamplingMethod::Stochastic {+ temperature: None,+ top_k: None,+ top_p: Some(TOP_P),+ },BATCH,VOCAB,&cb,@@ -534,7 +552,6 @@ fn perf_argmax_128k_vocab_with_strategy(strategy: ArgmaxStrategy) {BATCH,VOCAB,strategy,- TEST_SAMPLING_SEED,).expect("Failed to create Argmax kernel");@@ -551,6 +568,12 @@ fn perf_argmax_128k_vocab_with_strategy(strategy: ArgmaxStrategy) {metal::MTLResourceOptions::StorageModeShared,);+ let seeds_buf = context.device.new_buffer_with_data(+ vec![TEST_SAMPLING_SEED; BATCH].as_ptr() as *const _,+ (BATCH * std::mem::size_of::<u64>()) as u64,+ metal::MTLResourceOptions::StorageModeShared,+ );+let output_buf = context.device.new_buffer((BATCH * std::mem::size_of::<u32>()) as u64,metal::MTLResourceOptions::StorageModeShared,@@ -562,9 +585,10 @@ fn perf_argmax_128k_vocab_with_strategy(strategy: ArgmaxStrategy) {kernel.encode(- &SamplingMethod::Greedy,&logits_buf,+ Some(&seeds_buf),&output_buf,+ SamplingMethod::Greedy,BATCH,VOCAB,&cb,@@ -643,7 +667,6 @@ fn test_categorical_sampling() {KernelDataType::Float32,batch_size,vocab_size,- TEST_SAMPLING_SEED,).expect("Failed to create sampling kernel");@@ -670,17 +693,27 @@ fn test_categorical_sampling() {let num_samples = 1000;let mut counts = vec![0; batch_size * vocab_size];- for _ in 0..num_samples {+ for sample_idx in 0..num_samples {+ let seeds_buffer = context.device.new_buffer_with_data(+ vec![TEST_SAMPLING_SEED + sample_idx as u64; batch_size].as_ptr()+ as *const _,+ (batch_size * std::mem::size_of::<u64>()) as u64,+ MTLResourceOptions::StorageModeShared,+ );+let command_buffer_ref = context.command_queue.new_command_buffer();let command_buffer = command_buffer_ref.to_owned();kernel.encode(- &SamplingMethod::Temperature {- temperature: 1.0,- },&logits_buffer,+ Some(&seeds_buffer),&output_buffer,+ SamplingMethod::Stochastic {+ temperature: None,+ top_k: None,+ top_p: None,+ },batch_size,vocab_size,&command_buffer,@@ -758,14 +791,9 @@ fn test_categorical_sampling_statistical() {const NUM_SAMPLES: usize = 5000;const TOLERANCE: f32 = 0.05; // 5% tolerance- let kernel = SamplingKernel::new(- &context,- KernelDataType::Float32,- BATCH,- VOCAB,- TEST_SAMPLING_SEED,- )- .expect("Failed to create sampling kernel");+ let kernel =+ SamplingKernel::new(&context, KernelDataType::Float32, BATCH, VOCAB)+ .expect("Failed to create sampling kernel");// Generate random logitslet mut rng = StdRng::seed_from_u64(42);@@ -808,17 +836,27 @@ fn test_categorical_sampling_statistical() {let mut counts = vec![0; BATCH * VOCAB];// Sample many times- for _ in 0..NUM_SAMPLES {+ for sample_idx in 0..NUM_SAMPLES {+ let seeds_buffer = context.device.new_buffer_with_data(+ vec![TEST_SAMPLING_SEED + sample_idx as u64; BATCH].as_ptr()+ as *const _,+ (BATCH * std::mem::size_of::<u64>()) as u64,+ MTLResourceOptions::StorageModeShared,+ );+let command_buffer_ref = context.command_queue.new_command_buffer();let command_buffer = command_buffer_ref.to_owned();kernel.encode(- &SamplingMethod::Temperature {- temperature: 1.0,- },&logits_buffer,+ Some(&seeds_buffer),&output_buffer,+ SamplingMethod::Stochastic {+ temperature: None,+ top_k: None,+ top_p: None,+ },BATCH,VOCAB,&command_buffer,@@ -883,14 +921,9 @@ fn perf_categorical_128k_vocab() {const BATCH: usize = 8;const VOCAB: usize = 128000; // 128K- let kernel = SamplingKernel::new(- &context,- KernelDataType::Float32,- BATCH,- VOCAB,- TEST_SAMPLING_SEED,- )- .expect("Failed to create sampling kernel");+ let kernel =+ SamplingKernel::new(&context, KernelDataType::Float32, BATCH, VOCAB)+ .expect("Failed to create sampling kernel");// Build random logitslet mut rng = StdRng::seed_from_u64(123);@@ -905,6 +938,12 @@ fn perf_categorical_128k_vocab() {metal::MTLResourceOptions::StorageModeShared,);+ let seeds_buf = context.device.new_buffer_with_data(+ vec![TEST_SAMPLING_SEED; BATCH].as_ptr() as *const _,+ (BATCH * std::mem::size_of::<u64>()) as u64,+ metal::MTLResourceOptions::StorageModeShared,+ );+let output_buf = context.device.new_buffer((BATCH * std::mem::size_of::<u32>()) as u64,metal::MTLResourceOptions::StorageModeShared,@@ -916,11 +955,14 @@ fn perf_categorical_128k_vocab() {kernel.encode(- &SamplingMethod::Temperature {- temperature: 1.0,- },&logits_buf,+ Some(&seeds_buf),&output_buf,+ SamplingMethod::Stochastic {+ temperature: None,+ top_k: None,+ top_p: None,+ },BATCH,VOCAB,&cb,@@ -960,449 +1002,328 @@ fn perf_categorical_128k_vocab() {}#[test]-fn test_categorical_sampling_single_pass() {- test_categorical_sampling_with_strategy(CategoricalStrategy::SinglePass);-}--#[test]-fn test_categorical_sampling_two_pass() {- test_categorical_sampling_with_strategy(CategoricalStrategy::TwoPass);-}--#[test]-fn test_categorical_1pass_vs_2pass_equivalence() {+fn test_temperature_gpu_cpu_match() {let context = match create_test_context() {Ok(ctx) => ctx,Err(e) => {- println!("Skipping categorical equivalence test: {}", e);+ println!("Skipping temperature gpu cpu match test: {}", e);return;},};- let batch_size = 4;- let vocab_size = 16;- const NUM_SAMPLES: usize = 5000;- const TOLERANCE: f32 = 0.05; // 5% tolerance for statistical comparison-- // Create kernels for both strategies- let kernel_1pass = SamplingKernel::new_with_strategies(- &context,- KernelDataType::Float32,- batch_size,- vocab_size,- ArgmaxStrategy::TwoPass,- CategoricalStrategy::SinglePass,- TEST_SAMPLING_SEED,- )- .expect("Failed to create single-pass categorical kernel");+ const BATCH: usize = 4;+ const VOCAB: usize = 1024;+ const TEMPERATURE: f32 = 0.7;+ const RTOL: f32 = 1e-6;+ const ATOL: f32 = 1e-6;- let kernel_2pass = SamplingKernel::new_with_strategies(- &context,- KernelDataType::Float32,- batch_size,- vocab_size,- ArgmaxStrategy::TwoPass,- CategoricalStrategy::TwoPass,- TEST_SAMPLING_SEED,- )- .expect("Failed to create two-pass categorical kernel");+ let kernel =+ SamplingKernel::new(&context, KernelDataType::Float32, BATCH, VOCAB)+ .expect("Failed to create sampling kernel");- // Create test data with varied probability distributions- use rand::{Rng, SeedableRng, rngs::StdRng};- let mut rng = StdRng::seed_from_u64(42);- let mut test_logits = vec![0.0f32; batch_size * vocab_size];- for x in test_logits.iter_mut() {- *x = rng.random_range(-3.0f32..3.0f32);- }+ let logits: Vec<f32> = (0..BATCH * VOCAB)+ .map(|i| ((i * 37 % 1000) as f32 - 500.0) * 0.01)+ .collect();let logits_buffer = context.device.new_buffer_with_data(- test_logits.as_ptr() as *const _,- (test_logits.len() * std::mem::size_of::<f32>()) as u64,- MTLResourceOptions::StorageModeShared,- );-- let output_buffer_1pass = context.device.new_buffer(- (batch_size * std::mem::size_of::<u32>()) as u64,+ logits.as_ptr() as *const _,+ (logits.len() * std::mem::size_of::<f32>()) as u64,MTLResourceOptions::StorageModeShared,);- let output_buffer_2pass = context.device.new_buffer(- (batch_size * std::mem::size_of::<u32>()) as u64,+ let processed_buffer = context.device.new_buffer(+ (logits.len() * std::mem::size_of::<f32>()) as u64,MTLResourceOptions::StorageModeShared,);- // Collect samples from both strategies- let mut counts_1pass = vec![0; batch_size * vocab_size];- let mut counts_2pass = vec![0; batch_size * vocab_size];-- for _ in 0..NUM_SAMPLES {- // Sample from single-pass- let command_buffer_ref = context.command_queue.new_command_buffer();- let command_buffer = command_buffer_ref.to_owned();-- kernel_1pass- .encode(- &SamplingMethod::Temperature {- temperature: 1.0,- },- &logits_buffer,- &output_buffer_1pass,- batch_size,- vocab_size,- &command_buffer,- )- .expect("Single-pass encoding should succeed");-- command_buffer_ref.commit();- command_buffer_ref.wait_until_completed();+ let command_buffer_ref = context.command_queue.new_command_buffer();+ let command_buffer = command_buffer_ref.to_owned();- let result_ptr = output_buffer_1pass.contents() as *const u32;- let results_1pass =- unsafe { std::slice::from_raw_parts(result_ptr, batch_size) };+ let compute_encoder = command_buffer.new_compute_command_encoder();+ kernel+ .encode_temperature(+ &logits_buffer,+ &processed_buffer,+ BATCH as u32,+ VOCAB as u32,+ TEMPERATURE,+ compute_encoder,+ )+ .expect("encode_temperature");+ compute_encoder.end_encoding();- for (batch_idx, &token) in results_1pass.iter().enumerate() {- counts_1pass[batch_idx * vocab_size + token as usize] += 1;- }+ command_buffer_ref.commit();+ command_buffer_ref.wait_until_completed();- // Sample from two-pass- let command_buffer_ref = context.command_queue.new_command_buffer();- let command_buffer = command_buffer_ref.to_owned();+ let gpu_ptr = processed_buffer.contents() as *const f32;+ let gpu_results =+ unsafe { std::slice::from_raw_parts(gpu_ptr, logits.len()) };- kernel_2pass- .encode(- &SamplingMethod::Temperature {- temperature: 1.0,- },- &logits_buffer,- &output_buffer_2pass,- batch_size,- vocab_size,- &command_buffer,- )- .expect("Two-pass encoding should succeed");+ for (idx, (&logit, &processed)) in+ logits.iter().zip(gpu_results.iter()).enumerate()+ {+ let expected = logit / TEMPERATURE;+ let abs_diff = (expected - processed).abs();+ let tolerance = ATOL + RTOL * expected.abs();+ assert!(+ abs_diff <= tolerance,+ "Mismatch at element {}: expected={} actual={} (abs_diff={}, tolerance={})",+ idx,+ expected,+ processed,+ abs_diff,+ tolerance+ );+ }- command_buffer_ref.commit();- command_buffer_ref.wait_until_completed();+ println!(+ "✓ Temperature processor gpu cpu match (temp={}, rtol={}, atol={})",+ TEMPERATURE, RTOL, ATOL+ );+}- let result_ptr = output_buffer_2pass.contents() as *const u32;- let results_2pass =- unsafe { std::slice::from_raw_parts(result_ptr, batch_size) };+#[test]+fn test_topk_gpu_cpu_match() {+ use rand::{SeedableRng, rngs::StdRng};- for (batch_idx, &token) in results_2pass.iter().enumerate() {- counts_2pass[batch_idx * vocab_size + token as usize] += 1;- }- }+ let context = match create_test_context() {+ Ok(ctx) => ctx,+ Err(e) => {+ println!("Skipping topk gpu cpu match test: {}", e);+ return;+ },+ };- // Compute expected probabilities from logits (reference distribution)- let mut expected_probs = vec![0.0f32; batch_size * vocab_size];- for batch_idx in 0..batch_size {- let batch_logits =- &test_logits[batch_idx * vocab_size..(batch_idx + 1) * vocab_size];- let max_logit =- batch_logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);+ const BATCH: usize = 4;+ const VOCAB: usize = 1024;+ const TOPK: u32 = 16;- let mut sum_exp = 0.0f32;- for j in 0..vocab_size {- let exp_val = (batch_logits[j] - max_logit).exp();- expected_probs[batch_idx * vocab_size + j] = exp_val;- sum_exp += exp_val;- }+ let kernel =+ SamplingKernel::new(&context, KernelDataType::Float32, BATCH, VOCAB)+ .expect("Failed to create sampling kernel");- // Normalize- for j in 0..vocab_size {- expected_probs[batch_idx * vocab_size + j] /= sum_exp;- }+ let mut rng = StdRng::seed_from_u64(42);+ let mut logits = vec![0.0f32; BATCH * VOCAB];+ for x in logits.iter_mut() {+ *x = rng.random_range(-1024.0f32..1024.0f32);}- // Compare both strategies against expected distribution and each other- println!(- "Comparing single-pass vs two-pass categorical sampling distributions:"+ let logits_buffer = context.device.new_buffer_with_data(+ logits.as_ptr() as *const _,+ (logits.len() * std::mem::size_of::<f32>()) as u64,+ MTLResourceOptions::StorageModeShared,);- for batch_idx in 0..batch_size {- println!("Batch {}:", batch_idx);+ let processed_buffer = context.device.new_buffer(+ (logits.len() * std::mem::size_of::<f32>()) as u64,+ MTLResourceOptions::StorageModeShared,+ );- // Check that both strategies match the expected distribution- for token_idx in 0..vocab_size {- let expected_freq =- expected_probs[batch_idx * vocab_size + token_idx];+ let command_buffer_ref = context.command_queue.new_command_buffer();+ let command_buffer = command_buffer_ref.to_owned();- let observed_freq_1pass =- counts_1pass[batch_idx * vocab_size + token_idx] as f32- / NUM_SAMPLES as f32;- let observed_freq_2pass =- counts_2pass[batch_idx * vocab_size + token_idx] as f32- / NUM_SAMPLES as f32;+ let compute_encoder = command_buffer.new_compute_command_encoder();+ kernel+ .encode_topk(+ &logits_buffer,+ &processed_buffer,+ BATCH as u32,+ VOCAB as u32,+ TOPK,+ compute_encoder,+ )+ .expect("encode_topk");+ compute_encoder.end_encoding();- // Only check tokens with reasonable probability- if expected_freq > 0.01 {- let error_1pass = (observed_freq_1pass - expected_freq).abs();- let error_2pass = (observed_freq_2pass - expected_freq).abs();+ command_buffer_ref.commit();+ command_buffer_ref.wait_until_completed();- assert!(- error_1pass < TOLERANCE,- "Single-pass: Batch {}, Token {}: expected freq {:.3}, got {:.3}, error {:.3} > tolerance {:.3}",- batch_idx,- token_idx,- expected_freq,- observed_freq_1pass,- error_1pass,- TOLERANCE- );+ let results_ptr = processed_buffer.contents() as *const f32;+ let all_results =+ unsafe { std::slice::from_raw_parts(results_ptr, logits.len()) };- assert!(- error_2pass < TOLERANCE,- "Two-pass: Batch {}, Token {}: expected freq {:.3}, got {:.3}, error {:.3} > tolerance {:.3}",- batch_idx,- token_idx,- expected_freq,- observed_freq_2pass,- error_2pass,- TOLERANCE- );+ for batch_idx in 0..BATCH {+ let cpu_logits = &logits[batch_idx * VOCAB..(batch_idx + 1) * VOCAB];+ let mut cpu_sorted_logits: Vec<(usize, f32)> =+ cpu_logits.iter().copied().enumerate().collect();+ cpu_sorted_logits.sort_by(|(_, a), (_, b)| f32::total_cmp(b, a));+ let mut cpu_processed_logits: Vec<f32> = vec![f32::NEG_INFINITY; VOCAB];+ for (idx, val) in cpu_sorted_logits.into_iter().take(TOPK as usize) {+ cpu_processed_logits[idx] = val;+ }- // Compare the two strategies directly- let strategy_diff =- (observed_freq_1pass - observed_freq_2pass).abs();- assert!(- strategy_diff < TOLERANCE,- "Strategy difference: Batch {}, Token {}: 1-pass {:.3}, 2-pass {:.3}, diff {:.3} > tolerance {:.3}",- batch_idx,- token_idx,- observed_freq_1pass,- observed_freq_2pass,- strategy_diff,- TOLERANCE- );+ let gpu_processed_logits =+ &all_results[batch_idx * VOCAB..(batch_idx + 1) * VOCAB];- println!(- " Token {}: expected={:.3}, 1-pass={:.3}, 2-pass={:.3}, diff={:.3}",- token_idx,- expected_freq,- observed_freq_1pass,- observed_freq_2pass,- strategy_diff- );- }- }+ assert_eq!(cpu_processed_logits, gpu_processed_logits);}- println!(- "✓ Single-pass and two-pass categorical sampling produce equivalent distributions (tolerance: {:.1}%)",- TOLERANCE * 100.0- );+ println!("✓ Topk processor gpu cpu match (topk={})", TOPK);}-fn test_categorical_sampling_with_strategy(strategy: CategoricalStrategy) {+#[test]+fn test_topp_gpu_cpu_match() {+ use rand::{SeedableRng, rngs::StdRng};+let context = match create_test_context() {Ok(ctx) => ctx,Err(e) => {- println!("Skipping categorical test with {:?}: {}", strategy, e);+ println!("Skipping topp gpu cpu match test: {}", e);return;},};- let batch_size = 2;- let vocab_size = 4;+ const BATCH: usize = 4;+ const VOCAB: usize = 1024;+ const TOPP: f32 = 0.9;- let kernel = SamplingKernel::new_with_strategies(- &context,- KernelDataType::Float32,- batch_size,- vocab_size,- ArgmaxStrategy::TwoPass,- strategy,- TEST_SAMPLING_SEED,- )- .expect("Failed to create categorical kernel");+ let kernel =+ SamplingKernel::new(&context, KernelDataType::Float32, BATCH, VOCAB)+ .expect("Failed to create sampling kernel");- // Create test data with different probability distributions- let test_logits: Vec<f32> = vec![- 1.0, 2.0, 1.5, 0.5, // batch 0- 0.0, 1.0, 0.0, 0.0, // batch 1- ];+ let mut rng = StdRng::seed_from_u64(42);+ let mut logits = vec![0.0f32; BATCH * VOCAB];+ for x in logits.iter_mut() {+ *x = rng.random_range(-16.0f32..16.0f32);+ }let logits_buffer = context.device.new_buffer_with_data(- test_logits.as_ptr() as *const _,- (test_logits.len() * std::mem::size_of::<f32>()) as u64,+ logits.as_ptr() as *const _,+ (logits.len() * std::mem::size_of::<f32>()) as u64,MTLResourceOptions::StorageModeShared,);- let output_buffer = context.device.new_buffer(- (batch_size * std::mem::size_of::<u32>()) as u64,+ let processed_buffer = context.device.new_buffer(+ (logits.len() * std::mem::size_of::<f32>()) as u64,MTLResourceOptions::StorageModeShared,);- // Run sampling multiple times to check distribution- let num_samples = 1000;- let mut counts = vec![0; batch_size * vocab_size];-- for _ in 0..num_samples {- let command_buffer_ref = context.command_queue.new_command_buffer();- let command_buffer = command_buffer_ref.to_owned();-- kernel- .encode(- &SamplingMethod::Temperature {- temperature: 1.0,- },- &logits_buffer,- &output_buffer,- batch_size,- vocab_size,- &command_buffer,- )- .expect("Categorical sampling should succeed");+ let command_buffer_ref = context.command_queue.new_command_buffer();+ let command_buffer = command_buffer_ref.to_owned();- command_buffer_ref.commit();- command_buffer_ref.wait_until_completed();+ let compute_encoder = command_buffer.new_compute_command_encoder();+ kernel+ .encode_topp(+ &logits_buffer,+ &processed_buffer,+ BATCH as u32,+ VOCAB as u32,+ TOPP,+ compute_encoder,+ )+ .expect("encode_topp");+ compute_encoder.end_encoding();- let result_ptr = output_buffer.contents() as *const u32;- let results =- unsafe { std::slice::from_raw_parts(result_ptr, batch_size) };+ command_buffer_ref.commit();+ command_buffer_ref.wait_until_completed();- for (batch_idx, &token) in results.iter().enumerate() {- assert!(- (token as usize) < vocab_size,- "Sampled token {} out of range for vocab size {}",- token,- vocab_size- );- counts[batch_idx * vocab_size + token as usize] += 1;- }- }+ let results_ptr = processed_buffer.contents() as *const f32;+ let all_results =+ unsafe { std::slice::from_raw_parts(results_ptr, logits.len()) };- // Check that all batches produced valid outputs- for batch_idx in 0..batch_size {- let batch_counts =- &counts[batch_idx * vocab_size..(batch_idx + 1) * vocab_size];- let total_samples: usize = batch_counts.iter().sum();- assert_eq!(- total_samples, num_samples,- "Batch {} should have {} samples, got {}",- batch_idx, num_samples, total_samples- );-- // For the second batch, token 1 should be sampled most frequently- if batch_idx == 1 {- let max_count = *batch_counts.iter().max().unwrap();- assert_eq!(- batch_counts[1], max_count,- "Token 1 should be most frequent in batch 1 with strategy {:?}, got counts: {:?}",- strategy, batch_counts- );- }+ for batch_idx in 0..BATCH {+ let cpu_logits = &logits[batch_idx * VOCAB..(batch_idx + 1) * VOCAB];+ let cpu_processed_logits = cpu_reference_top_p(cpu_logits, TOPP)+ .into_iter()+ .zip(cpu_logits.iter().copied())+ .map(|(cpu_ref_topp, logit)| {+ if cpu_ref_topp > 0.0 {+ logit+ } else {+ f32::NEG_INFINITY+ }+ })+ .collect::<Vec<f32>>();++ let gpu_processed_logits =+ &all_results[batch_idx * VOCAB..(batch_idx + 1) * VOCAB];++ assert_eq!(&cpu_processed_logits, gpu_processed_logits);}- println!(- "✓ Categorical sampling test passed with {:?} strategy - sampled {} times per batch",- strategy, num_samples- );+ println!("✓ Topp processor gpu cpu match (topp={})", TOPP);}-fn perf_categorical_128k_vocab_with_strategy(strategy: CategoricalStrategy) {- use std::time::Instant;-- use rand::{Rng, SeedableRng, rngs::StdRng};-+#[test]+fn test_gumbel_gpu_cpu_match() {let context = match create_test_context() {Ok(ctx) => ctx,Err(e) => {- println!(- "Skipping categorical perf test with {:?}: {}",- strategy, e- );+ println!("Skipping gumbel gpu cpu match test: {}", e);return;},};- const BATCH: usize = 8;- const VOCAB: usize = 128000; // 128K+ const BATCH: usize = 7;+ const VOCAB: usize = 16 * 1024 * 64;+ const RTOL: f32 = 0.01;+ const ATOL: f32 = 1e-6;- let kernel = SamplingKernel::new_with_strategies(- &context,- KernelDataType::Float32,- BATCH,- VOCAB,- ArgmaxStrategy::TwoPass,- strategy,- TEST_SAMPLING_SEED,- )- .expect("Failed to create sampling kernel");+ let kernel =+ SamplingKernel::new(&context, KernelDataType::Float32, BATCH, VOCAB)+ .expect("Failed to create sampling kernel");- // Build random logits- let mut rng = StdRng::seed_from_u64(123);- let mut logits = vec![0.0f32; BATCH * VOCAB];- for x in logits.iter_mut() {- *x = rng.random_range(-6.0f32..6.0f32);- }+ let logits = vec![0.0f32; BATCH * VOCAB];+ let seeds: Vec<u64> = (0_u64..BATCH as u64).collect();- let logits_buf = context.device.new_buffer_with_data(+ let logits_buffer = context.device.new_buffer_with_data(logits.as_ptr() as *const _,(logits.len() * std::mem::size_of::<f32>()) as u64,- metal::MTLResourceOptions::StorageModeShared,+ MTLResourceOptions::StorageModeShared,);- let output_buf = context.device.new_buffer(- (BATCH * std::mem::size_of::<u32>()) as u64,- metal::MTLResourceOptions::StorageModeShared,+ let seeds_buffer = context.device.new_buffer_with_data(+ seeds.as_ptr() as *const _,+ (BATCH * std::mem::size_of::<u64>()) as u64,+ MTLResourceOptions::StorageModeShared,);- // Launch and time- let cb_ref = context.command_queue.new_command_buffer();- let cb = cb_ref.to_owned();+ let gumbel_logits_buffer = context.device.new_buffer(+ (BATCH * VOCAB * std::mem::size_of::<f32>()) as u64,+ MTLResourceOptions::StorageModeShared,+ );+ let command_buffer_ref = context.command_queue.new_command_buffer();+ let command_buffer = command_buffer_ref.to_owned();++ let compute_encoder = command_buffer.new_compute_command_encoder();kernel- .encode(- &SamplingMethod::Temperature {- temperature: 1.0,- },- &logits_buf,- &output_buf,- BATCH,- VOCAB,- &cb,+ .encode_gumbel(+ &logits_buffer,+ &seeds_buffer,+ &gumbel_logits_buffer,+ BATCH as u32,+ VOCAB as u32,+ compute_encoder,).expect("encode");+ compute_encoder.end_encoding();- let host_timer = Instant::now();- cb_ref.commit();- cb_ref.wait_until_completed();- let host_elapsed_ms = host_timer.elapsed().as_secs_f64() * 1e3;-- let gpu_elapsed_ms = cb.gpu_execution_time_ms();+ command_buffer_ref.commit();+ command_buffer_ref.wait_until_completed();- match gpu_elapsed_ms {- Some(gpu_time) => {- println!(- "Categorical sampling perf (batch={}, vocab={}, strategy={:?}): GPU={:.2} ms, Host-side={:.2} ms",- BATCH, VOCAB, strategy, gpu_time, host_elapsed_ms- );- },- None => {- println!(- "Categorical sampling perf (batch={}, vocab={}, strategy={:?}): Host-side={:.2} ms (GPU timing unavailable)",- BATCH, VOCAB, strategy, host_elapsed_ms+ let result_ptr = gumbel_logits_buffer.contents() as *const f32;+ let all_results =+ unsafe { std::slice::from_raw_parts(result_ptr, BATCH * VOCAB) };++ for (batch_idx, batch_seed) in seeds.iter().copied().enumerate() {+ let results = &all_results[batch_idx * VOCAB..(batch_idx + 1) * VOCAB];+ for (logit_idx, gpu_logit_value) in results.iter().copied().enumerate()+ {+ let cpu_logit_value =+ gumbel_float(batch_seed, revidx(logit_idx as u32));+ let abs_diff = (cpu_logit_value - gpu_logit_value).abs();+ let tolerance = ATOL + RTOL * cpu_logit_value.abs();+ assert!(+ abs_diff <= tolerance,+ "Mismatch at batch {batch_idx} element {logit_idx}: CPU={cpu_logit_value} GPU={gpu_logit_value} (abs_diff={abs_diff}, tolerance={tolerance})");- },- }-- // Sanity check- let ptr = output_buf.contents() as *const u32;- let sample_ids = unsafe { std::slice::from_raw_parts(ptr, BATCH) };- for &tok in sample_ids {- assert!((tok as usize) < VOCAB, "Sampled id out of range");+ }}- println!("✓ Categorical correctness verified with {:?} strategy", strategy);-}--#[test]-fn perf_categorical_128k_vocab_single_pass() {- perf_categorical_128k_vocab_with_strategy(CategoricalStrategy::SinglePass);-}--#[test]-fn perf_categorical_128k_vocab_two_pass() {- perf_categorical_128k_vocab_with_strategy(CategoricalStrategy::TwoPass);+ println!(+ "✓ Gumbel cpu gpu match test passed (rtol: {:.1}%, atol: {:.1e})",+ RTOL * 100.0,+ ATOL+ );}