Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Unified sampling (#517)

uuuvna67ed673cc85
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/argmax.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/argmax.rs
deleted file mode 100644
index 011130867..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/sampling/argmax.rs
+++ /dev/null
@@ -1,91 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::{array::ArrayElement, backends::common::gpu_types::argmax::ArgmaxPair};
-
-fn argmax_is_better(
- a: &ArgmaxPair,
- b: &ArgmaxPair,
-) -> bool {
- a.value > b.value || (a.value == b.value && a.index < b.index)
-}
-
-const ARGMAX_INIT: ArgmaxPair = ArgmaxPair {
- value: f32::NEG_INFINITY,
- index: u32::MAX,
-};
-
-#[kernel(ArgmaxSingle)]
-#[variants(T, f32, f16, bf16)]
-pub fn argmax_single<T: ArrayElement + Float>(
- logits_data: *const T,
- final_tokens: *mut u32,
- batch_size: u32,
- vocab_size: u32,
-) {
- for batch_idx in 0..batch_size as usize {
- let mut best = ARGMAX_INIT;
-
- for vocab_idx in 0..vocab_size as usize {
- let global_idx = batch_idx * vocab_size as usize + vocab_idx;
- let value = unsafe { (*logits_data.add(global_idx)).to_f32().unwrap() };
- let candidate = ArgmaxPair {
- value,
- index: vocab_idx as u32,
- };
- if argmax_is_better(&candidate, &best) {
- best = candidate;
- }
- }
-
- unsafe {
- *final_tokens.add(batch_idx) = best.index;
- }
- }
-}
-
-#[kernel(ArgmaxMain)]
-#[variants(T, f32, f16, bf16)]
-pub fn argmax_main<T: ArrayElement + Float>(
- logits_data: *const T,
- partial_results: *mut ArgmaxPair,
- batch_size: u32,
- vocab_size: u32,
-) {
- for batch_idx in 0..batch_size as usize {
- let mut best = ARGMAX_INIT;
-
- for vocab_idx in 0..vocab_size as usize {
- let global_idx = batch_idx * vocab_size as usize + vocab_idx;
- let value = unsafe { (*logits_data.add(global_idx)).to_f32().unwrap() };
- let candidate = ArgmaxPair {
- value,
- index: vocab_idx as u32,
- };
- if argmax_is_better(&candidate, &best) {
- best = candidate;
- }
- }
-
- unsafe {
- *partial_results.add(batch_idx) = best;
- }
- }
-}
-
-#[kernel(ArgmaxFinal)]
-pub fn argmax_final(
- partial_results: *const ArgmaxPair,
- final_tokens: *mut u32,
- batch_size: u32,
- vocab_size: u32,
-) {
- for batch_idx in 0..batch_size as usize {
- unsafe {
- let pair = *partial_results.add(batch_idx);
- assert!(pair.index < vocab_size);
- *final_tokens.add(batch_idx) = pair.index;
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/bitmask.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/bitmask.rs
deleted file mode 100644
index e4015cfb4..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/sampling/bitmask.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(Bitmask)]
-#[variants(T, f32, f16, bf16)]
-pub fn bitmask<T: ArrayElement + Float>(
- #[optional(!in_place)] logits: Option<*const T>,
- bitmask: *const u32,
- processed_logits: *mut T,
- batch_size: u32,
- vocab_size: u32,
- #[specialize] in_place: bool,
-) {
- let logits: *const T = match in_place {
- true => processed_logits,
- false => logits.unwrap(),
- };
-
- let batch_size = batch_size as usize;
- let vocab_size = vocab_size as usize;
- let bitmask_size = vocab_size.div_ceil(32);
-
- for batch_idx in 0..batch_size {
- for token_idx in 0..vocab_size {
- let global_idx = batch_idx * vocab_size + token_idx;
- let bitmask_idx = batch_idx * bitmask_size + token_idx / 32;
- unsafe {
- let mask = (*bitmask.add(bitmask_idx) >> (token_idx % 32)) & 1;
- *processed_logits.add(global_idx) = match mask != 0 {
- true => *logits.add(global_idx),
- false => T::neg_infinity(),
- };
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/gumbel.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/gumbel.rs
deleted file mode 100644
index 93ab6c2da..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/sampling/gumbel.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::{
- array::ArrayElement,
- language_model::gumbel::{gumbel_float, revidx},
-};
-
-#[kernel(Gumbel)]
-#[variants(T, f32, f16, bf16)]
-pub fn gumbel<T: ArrayElement + Float>(
- #[optional(!in_place)] logits: Option<*const T>,
- batch_seeds: *const u64,
- batch_seeds_offset: u32,
- processed_logits: *mut T,
- batch_size: u32,
- vocab_size: u32,
- #[specialize] in_place: bool,
-) {
- let logits: *const T = match in_place {
- true => processed_logits,
- false => logits.unwrap(),
- };
-
- for batch_idx in 0..batch_size as usize {
- let batch_start = batch_idx * vocab_size as usize;
- let rng_seed = unsafe { *batch_seeds.add(batch_seeds_offset as usize + batch_idx) };
- for vocab_idx in 0..vocab_size as usize {
- let global_idx = batch_start + vocab_idx;
- unsafe {
- let logit = (*logits.add(global_idx)).to_f32().unwrap();
- let gumbel_noise = gumbel_float(rng_seed, revidx(vocab_idx as u32));
- *processed_logits.add(global_idx) = T::from(logit + gumbel_noise).unwrap();
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/min_p.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/min_p.rs
deleted file mode 100644
index 59f653f34..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/sampling/min_p.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(MinP)]
-#[variants(T, f32, f16, bf16)]
-pub fn min_p<T: ArrayElement + Float>(
- #[optional(!in_place)] logits: Option<*const T>,
- processed_logits: *mut T,
- batch_size: u32,
- vocab_size: u32,
- min_p: f32,
- #[specialize] in_place: bool,
-) {
- let logits = match in_place {
- true => processed_logits,
- false => logits.unwrap(),
- };
-
- let batch_size = batch_size as usize;
- let vocab_size = vocab_size as usize;
-
- for batch_idx in 0..batch_size {
- // find maximum logit
- let mut max_logit = f32::NEG_INFINITY;
- for i in 0..vocab_size {
- let logit = unsafe { *logits.add(batch_idx * vocab_size + i) }.to_f32().unwrap();
- max_logit = max_logit.max(logit);
- }
-
- // then the threshold is just max_logit + log(min_p), mask everything strictly below it
- let threshold: T = T::from(max_logit + min_p.ln()).unwrap();
- for i in 0..vocab_size {
- let position = batch_idx * vocab_size + i;
- unsafe {
- let logit = *logits.add(position);
- *processed_logits.add(position) = match logit >= threshold {
- true => logit,
- false => T::neg_infinity(),
- }
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/mod.rs
index db49e2e7a..5171b2be1 100644
--- a/crates/backend-uzu/src/backends/cpu/kernel/sampling/mod.rs
+++ b/crates/backend-uzu/src/backends/cpu/kernel/sampling/mod.rs
@@ -1,7 +1 @@
-pub mod argmax;
-pub mod bitmask;
-pub mod gumbel;
-pub mod min_p;
-pub mod temperature;
-pub mod top_k;
-pub mod top_p;
+pub mod unified_sampling;
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/temperature.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/temperature.rs
deleted file mode 100644
index f5bcdce13..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/sampling/temperature.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(Temperature)]
-#[variants(T, f32, f16, bf16)]
-pub fn temperature<T: ArrayElement + Float>(
- #[optional(!in_place)] logits: Option<*const T>,
- processed_logits: *mut T,
- batch_size: u32,
- vocab_size: u32,
- temperature: f32,
- #[specialize] in_place: bool,
-) {
- let logits: *const T = match in_place {
- true => processed_logits,
- false => logits.unwrap(),
- };
-
- for batch_idx in 0..batch_size as usize {
- for vocab_idx in 0..vocab_size as usize {
- let global_idx = batch_idx * vocab_size as usize + vocab_idx;
- unsafe {
- let value: f32 = (*logits.add(global_idx)).to_f32().unwrap() / temperature;
- *processed_logits.add(global_idx) = T::from(value).unwrap();
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/top_k.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/top_k.rs
deleted file mode 100644
index c7a5700ae..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/sampling/top_k.rs
+++ /dev/null
@@ -1,47 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(TopK)]
-#[variants(T, f32, f16, bf16)]
-pub fn top_k<T: ArrayElement + Float>(
- #[optional(!in_place)] logits: Option<*const T>,
- processed_logits: *mut T,
- batch_size: u32,
- vocab_size: u32,
- top_k: u32,
- #[specialize] in_place: bool,
-) {
- if top_k == 0 || top_k > vocab_size {
- return;
- }
-
- let logits: *const T = match in_place {
- true => processed_logits,
- false => logits.unwrap(),
- };
-
- let vocab_size = vocab_size as usize;
- let top_k = top_k as usize;
-
- for batch_idx in 0..batch_size as usize {
- let batch_start = batch_idx * vocab_size;
- let mut sorted_logits = unsafe { std::slice::from_raw_parts(logits.add(batch_start), vocab_size) }.to_vec();
- sorted_logits.sort_unstable_by(|a, b| b.partial_cmp(a).unwrap());
- let t_threshold = sorted_logits[top_k - 1];
-
- // Mask everything below the threshold
- for i in 0..vocab_size {
- let logit_value = unsafe { *logits.add(batch_start + i) };
- unsafe {
- *processed_logits.add(batch_start + i) = if logit_value >= t_threshold {
- logit_value
- } else {
- T::from(f32::NEG_INFINITY).unwrap()
- };
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/top_p.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/top_p.rs
deleted file mode 100644
index 07a78539e..000000000
--- a/crates/backend-uzu/src/backends/cpu/kernel/sampling/top_p.rs
+++ /dev/null
@@ -1,68 +0,0 @@
-use half::{bf16, f16};
-use num_traits::Float;
-use proc_macros::kernel;
-
-use crate::array::ArrayElement;
-
-#[kernel(TopP)]
-#[variants(T, f32, f16, bf16)]
-pub fn top_p<T: ArrayElement + Float>(
- #[optional(!in_place)] logits: Option<*const T>,
- processed_logits: *mut T,
- batch_size: u32,
- vocab_size: u32,
- top_p: f32,
- #[specialize] in_place: bool,
-) {
- let logits: *const T = match in_place {
- true => processed_logits,
- false => logits.unwrap(),
- };
-
- let vocab_size = vocab_size as usize;
-
- for batch_idx in 0..batch_size as usize {
- let batch_start = batch_idx * vocab_size;
-
- // Sort logits in descending order
- let mut sorted_logits = unsafe { std::slice::from_raw_parts(logits.add(batch_start), vocab_size) }.to_vec();
- sorted_logits.sort_unstable_by(|a, b| b.partial_cmp(a).unwrap());
- let max_logit: f32 = sorted_logits[0].to_f32().unwrap();
-
- // Compute softmax probabilities and find threshold via cumulative sum
- let total_sum: f32 = sorted_logits
- .iter()
- .map(|&v| v.to_f32().unwrap())
- .filter(|&v| v > f32::NEG_INFINITY)
- .map(|v| (v - max_logit).exp())
- .sum();
-
- let mut cumulative: f32 = 0.0;
- let mut threshold: f32 = sorted_logits[0].to_f32().unwrap();
- for &logit in &sorted_logits {
- let logit_f32 = logit.to_f32().unwrap();
- if logit_f32 == f32::NEG_INFINITY {
- break;
- }
- threshold = logit_f32;
- cumulative += (logit_f32 - max_logit).exp() / total_sum;
- if cumulative >= top_p {
- break;
- }
- }
-
- let t_threshold = T::from(threshold).unwrap();
-
- // Mask everything below the threshold
- for i in 0..vocab_size {
- let logit_value = unsafe { *logits.add(batch_start + i) };
- unsafe {
- *processed_logits.add(batch_start + i) = if logit_value >= t_threshold {
- logit_value
- } else {
- T::from(f32::NEG_INFINITY).unwrap()
- };
- }
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/cpu/kernel/sampling/unified_sampling.rs b/crates/backend-uzu/src/backends/cpu/kernel/sampling/unified_sampling.rs
new file mode 100644
index 000000000..7f8644913
--- /dev/null
+++ b/crates/backend-uzu/src/backends/cpu/kernel/sampling/unified_sampling.rs
@@ -0,0 +1,104 @@
+use std::cmp::Ordering;
+
+use half::bf16;
+use num_traits::Float;
+use proc_macros::kernel;
+
+use crate::{array::ArrayElement, gumbel_float, revidx};
+
+// NOTE: top_k + top_p combination is not exactly matching lalamo ("parallel" here, should be top-k then top-p)
+#[kernel(UnifiedSampling)]
+#[variants(T, f32, bf16)]
+pub fn unified_sampling<T: ArrayElement + Float>(
+ logits: *const T,
+ output: *mut u32,
+ #[optional(is_stochastic)] seeds: Option<*const u64>,
+ #[optional(has_bitmask)] bitmask: Option<*const u32>,
+ #[optional(has_temperature)] temperature: Option<f32>,
+ #[optional(has_top_k)] top_k: Option<u32>,
+ #[optional(has_top_p)] top_p: Option<f32>,
+ #[optional(has_min_p)] min_p: Option<f32>,
+ vocab_size: u32,
+ batch_size: u32,
+ #[specialize] is_stochastic: bool,
+ #[specialize] has_bitmask: bool,
+ #[specialize] has_temperature: bool,
+ #[specialize] temperature_after_filters: bool,
+ #[specialize] has_top_k: bool,
+ #[specialize] has_top_p: bool,
+ #[specialize] has_min_p: bool,
+) {
+ for batch_idx in 0..batch_size {
+ let mut logits = unsafe {
+ std::slice::from_raw_parts(logits.wrapping_add((vocab_size * batch_idx) as usize), vocab_size as usize)
+ }
+ .iter()
+ .map(|logit| logit.to_f32().unwrap())
+ .collect::<Vec<f32>>();
+
+ if has_bitmask {
+ let bitmask = unsafe {
+ std::slice::from_raw_parts(
+ bitmask.unwrap().wrapping_add((vocab_size.div_ceil(u32::BITS) * batch_idx) as usize),
+ vocab_size.div_ceil(u32::BITS) as usize,
+ )
+ };
+ for (logit_index, logit) in logits.iter_mut().enumerate() {
+ if bitmask[logit_index / (u32::BITS as usize)] & (1 << (logit_index % (u32::BITS as usize))) == 0 {
+ *logit = f32::NEG_INFINITY;
+ }
+ }
+ }
+
+ if has_temperature && !temperature_after_filters {
+ let recip_temperature = 1.0 / temperature.unwrap();
+ for logit in logits.iter_mut() {
+ *logit *= recip_temperature;
+ }
+ }
+
+ if has_top_k || has_top_p || has_min_p {
+ let mut sorted_logits = logits.iter().copied().enumerate().collect::<Vec<_>>();
+ sorted_logits.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(Ordering::Equal).then(a.0.cmp(&b.0)));
+
+ let logits_max = sorted_logits[0].1;
+ let logits_norm = sorted_logits.iter().map(|logit| (logit.1 - logits_max).exp()).sum::<f32>();
+
+ logits.fill(f32::NEG_INFINITY);
+ let mut top_p_mass = 0.0;
+ for (top_k_num, (index, logit)) in sorted_logits.into_iter().enumerate() {
+ if (has_top_k && top_k_num as u32 >= top_k.unwrap())
+ || (has_top_p && top_p_mass >= top_p.unwrap())
+ || (has_min_p && logit < logits_max + min_p.unwrap().ln())
+ {
+ break;
+ }
+ logits[index] = logit;
+ top_p_mass += (logit - logits_max).exp() / logits_norm;
+ }
+ }
+
+ if has_temperature && temperature_after_filters {
+ let recip_temperature = 1.0 / temperature.unwrap();
+ for logit in logits.iter_mut() {
+ *logit *= recip_temperature;
+ }
+ }
+
+ if is_stochastic {
+ let seed = unsafe { *seeds.unwrap().wrapping_add(batch_idx as usize) };
+ for (logit_index, logit) in logits.iter_mut().enumerate() {
+ *logit += gumbel_float(seed, revidx(logit_index as u32, vocab_size));
+ }
+ }
+
+ let argmax = logits
+ .into_iter()
+ .enumerate()
+ .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal).then(b.0.cmp(&a.0)))
+ .unwrap()
+ .0;
+
+ unsafe { *output.wrapping_add(batch_idx as usize) = argmax as u32 }
+ }
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/common/defines.h b/crates/backend-uzu/src/backends/metal/kernel/common/defines.h
index 904411eac..f72b10db2 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/common/defines.h
+++ b/crates/backend-uzu/src/backends/metal/kernel/common/defines.h
@@ -6,3 +6,8 @@
#define METAL_SIMD_SIZE 32
METAL_FUNC int pow2(int n) { return 1 << n; }
+
+template <typename T, typename U>
+METAL_FUNC T div_ceil(T dividend, U divisor) {
+ return (dividend + T(divisor) - T(1)) / T(divisor);
+}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/argmax.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/argmax.metal
deleted file mode 100644
index 38a96c209..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/sampling/argmax.metal
+++ /dev/null
@@ -1,198 +0,0 @@
-#include <metal_stdlib>
-#include <metal_atomic>
-#include "../common/dsl.h"
-#include "../common/thread_context.h"
-#include "../common/threadgroup_reduce.h"
-
-#include "argmax.h"
-
-#define BLOCK_SIZE 1024
-#define GRAIN_SIZE 4
-
-using namespace uzu::argmax;
-
-constant ArgmaxPair ARGMAX_INIT = {-INFINITY, UINT_MAX};
-
-bool argmax_is_better(ArgmaxPair a, ArgmaxPair b) {
- return a.value > b.value || (a.value == b.value && a.index < b.index);
-}
-
-ArgmaxPair argmax_combine(ArgmaxPair a, ArgmaxPair b) { return argmax_is_better(a, b) ? a : b; }
-
-struct SimdReduceArgmax {
- using value_type = ArgmaxPair;
- static constant constexpr ArgmaxPair identity = ARGMAX_INIT;
- static ArgmaxPair simd_reduce(ArgmaxPair x) {
- for (ushort offset = 16; offset > 0; offset /= 2) {
- ArgmaxPair other = {simd_shuffle_down(x.value, offset), simd_shuffle_down(x.index, offset)};
- x = argmax_combine(x, other);
- }
- return x;
- }
-};
-
-template <ushort GRAIN_SIZE_PARAM>
-static inline ArgmaxPair thread_argmax_reduce(thread ArgmaxPair (&values)[GRAIN_SIZE_PARAM]) {
- ArgmaxPair result = values[0];
- for (ushort i = 1; i < GRAIN_SIZE_PARAM; i++) {
- result = argmax_combine(result, values[i]);
- }
- return result;
-}
-
-template <ushort GRAIN_SIZE_PARAM, typename T>
-static void load_blocked_argmax_batched(
- thread ArgmaxPair (&values)[GRAIN_SIZE_PARAM],
- const device T* logits_data,
- const ushort local_id,
- const uint batch_idx,
- const uint vocab_offset,
- const uint vocab_size
-) {
- for (ushort i = 0; i < GRAIN_SIZE_PARAM; i++) {
- uint vocab_idx = vocab_offset + local_id * GRAIN_SIZE_PARAM + i;
- if (vocab_idx < vocab_size) {
- uint global_idx = batch_idx * vocab_size + vocab_idx;
- float value;
- value = static_cast<float>(logits_data[global_idx]);
- values[i] = {value, vocab_idx};
- } else {
- values[i] = ARGMAX_INIT;
- }
- }
-}
-
-template <ushort BLOCK_SIZE_PARAM>
-static ArgmaxPair threadgroup_raking_argmax(ArgmaxPair value, threadgroup ArgmaxPair* shared, const ushort lid) {
- shared[lid] = value;
- threadgroup_barrier(mem_flags::mem_threadgroup);
-
- if (lid < 32) {
- const ushort values_per_thread = BLOCK_SIZE_PARAM / 32;
- const ushort first_index = lid * values_per_thread;
-
- ArgmaxPair thread_result = shared[first_index];
- for (ushort i = first_index + 1; i < first_index + values_per_thread; i++) {
- thread_result = argmax_combine(thread_result, shared[i]);
- }
-
- ArgmaxPair simd_result = thread_result;
-
- for (ushort offset = 16; offset > 0; offset /= 2) {
- ArgmaxPair other = {simd_shuffle_down(simd_result.value, offset), simd_shuffle_down(simd_result.index, offset)};
- simd_result = argmax_combine(simd_result, other);
- }
-
- ArgmaxPair final_result = {simd_broadcast(simd_result.value, 0), simd_broadcast(simd_result.index, 0)};
-
- for (ushort i = first_index; i < first_index + values_per_thread; i++) {
- shared[i] = final_result;
- }
- }
-
- threadgroup_barrier(mem_flags::mem_threadgroup);
- const ArgmaxPair result = shared[lid];
- threadgroup_barrier(mem_flags::mem_threadgroup);
- return result;
-}
-
-// Single-pass argmax
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(ArgmaxSingle)(
- const device T* logits_data,
- device uint* final_tokens,
- constant uint& batch_size,
- constant uint& vocab_size,
- threadgroup ArgmaxPair shared[BLOCK_SIZE],
- uint batch_idx GROUPS(batch_size),
- ushort local_id THREADS(BLOCK_SIZE)
-) {
- if (batch_idx >= batch_size)
- return;
-
- const uint elements_per_tile = BLOCK_SIZE * GRAIN_SIZE;
- ArgmaxPair best = ARGMAX_INIT;
-
- for (uint vocab_offset = 0; vocab_offset < vocab_size; vocab_offset += elements_per_tile) {
- ArgmaxPair buf[GRAIN_SIZE];
- load_blocked_argmax_batched<GRAIN_SIZE>(buf, logits_data, local_id, batch_idx, vocab_offset, vocab_size);
- ArgmaxPair tile_best = thread_argmax_reduce<GRAIN_SIZE>(buf);
- best = argmax_combine(best, tile_best);
- }
-
- ArgmaxPair group_best = threadgroup_raking_argmax<BLOCK_SIZE>(best, shared, local_id);
-
- if (local_id == 0) {
- final_tokens[batch_idx] = group_best.index;
- }
-}
-
-// Two-pass argmax
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(ArgmaxMain)(
- const device T* logits_data,
- device ArgmaxPair* partial_results,
- constant uint& batch_size,
- constant uint& vocab_size,
- threadgroup ArgmaxPair shared[BLOCK_SIZE],
- const ThreadContext thread_context,
- uint batch_idx GROUPS(batch_size),
- uint vocab_group_idx GROUPS(vocab_size.div_ceil(BLOCK_SIZE * GRAIN_SIZE)),
- ushort local_id THREADS(BLOCK_SIZE)
-) {
-
- if (batch_idx >= batch_size)
- return;
-
- const uint elements_per_group = BLOCK_SIZE * GRAIN_SIZE;
- const uint vocab_offset = vocab_group_idx * elements_per_group;
-
- ArgmaxPair values[GRAIN_SIZE];
- load_blocked_argmax_batched<GRAIN_SIZE>(values, logits_data, local_id, batch_idx, vocab_offset, vocab_size);
-
- ArgmaxPair thread_result = thread_argmax_reduce<GRAIN_SIZE>(values);
- ArgmaxPair group_result =
- threadgroup_cooperative_reduce<SimdReduceArgmax, BLOCK_SIZE>(thread_result, shared, thread_context);
-
- if (local_id == 0) {
- uint vocab_groups_per_batch = (vocab_size + elements_per_group - 1) / elements_per_group;
- uint partial_idx = batch_idx * vocab_groups_per_batch + vocab_group_idx;
- partial_results[partial_idx] = group_result;
- }
-}
-
-PUBLIC KERNEL(ArgmaxFinal)(
- const device ArgmaxPair* partial_results,
- device uint* final_tokens,
- constant uint& batch_size,
- constant uint& vocab_size,
- threadgroup ArgmaxPair shared[BLOCK_SIZE],
- const ThreadContext thread_context,
- uint batch_idx GROUPS(batch_size),
- ushort local_id THREADS(BLOCK_SIZE)
-) {
-
- if (batch_idx >= batch_size)
- return;
-
- const uint elements_per_group = BLOCK_SIZE * GRAIN_SIZE;
- const uint vocab_groups_per_batch = (vocab_size + elements_per_group - 1) / elements_per_group;
- const uint partial_offset = batch_idx * vocab_groups_per_batch;
-
- ArgmaxPair thread_result = ARGMAX_INIT;
-
- for (uint i = local_id; i < vocab_groups_per_batch; i += BLOCK_SIZE) {
- thread_result = argmax_combine(thread_result, partial_results[partial_offset + i]);
- }
-
- ArgmaxPair result =
- threadgroup_cooperative_reduce<SimdReduceArgmax, BLOCK_SIZE>(thread_result, shared, thread_context);
-
- if (local_id == 0) {
- final_tokens[batch_idx] = result.index;
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/bitmask.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/bitmask.metal
deleted file mode 100644
index e5f776520..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/sampling/bitmask.metal
+++ /dev/null
@@ -1,39 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-#define BLOCK_SIZE 1024
-#define GRAIN_SIZE 64
-#define BITS_IN_U32 32
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(Bitmask) (
- device const T* logits OPTIONAL(!in_place),
- device const uint32_t* bitmask,
- device T* processed_logits,
- constant uint& batch_size,
- constant uint& vocab_size,
- uint group_idx GROUPS(vocab_size.div_ceil(BLOCK_SIZE * GRAIN_SIZE)),
- uint batch_idx GROUPS(batch_size),
- uint thread_idx THREADS(BLOCK_SIZE),
- const bool in_place SPECIALIZE
-) {
- if (in_place) {
- logits = processed_logits;
- }
-
- uint bitmask_size = (vocab_size + (BITS_IN_U32 - 1)) / BITS_IN_U32;
- uint base_idx = batch_idx * vocab_size + group_idx * BLOCK_SIZE * GRAIN_SIZE + thread_idx;
- uint batch_end = batch_idx * vocab_size + vocab_size;
-
-#pragma unroll(4)
- for (uint i = 0; i < GRAIN_SIZE; i++) {
- uint global_idx = base_idx + i * BLOCK_SIZE;
- if (global_idx < batch_end) {
- uint token_idx = global_idx - batch_idx * vocab_size;
- uint bitmask_idx = batch_idx * bitmask_size + (token_idx / BITS_IN_U32);
- bool mask = (bitmask[bitmask_idx] >> (token_idx % BITS_IN_U32)) & 0b1;
- processed_logits[global_idx] = select(T(-INFINITY), logits[global_idx], mask);
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/gumbel.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/gumbel.metal
deleted file mode 100644
index 5fb7b19aa..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/sampling/gumbel.metal
+++ /dev/null
@@ -1,46 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../rng.h"
-
-#define BLOCK_SIZE 1024
-#define GRAIN_SIZE 64
-#define WORDS_PER_OFFSET 4
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(Gumbel) (
- device const T* logits OPTIONAL(!in_place),
- device const uint64_t* batch_seeds,
- constant uint& batch_seeds_offset,
- device T* processed_logits,
- constant uint& batch_size,
- constant uint& vocab_size,
- uint group_idx GROUPS(vocab_size.div_ceil(BLOCK_SIZE * GRAIN_SIZE)),
- uint batch_idx GROUPS(batch_size),
- uint thread_idx THREADS(BLOCK_SIZE),
- const bool in_place SPECIALIZE
-) {
- if (in_place) {
- logits = processed_logits;
- }
-
- 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_seeds_offset + 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);
-
-#pragma unroll(4)
- 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[global_idx] + T(-fast::log(-fast::log(uniform_float(&rng))));
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/min_p.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/min_p.metal
deleted file mode 100644
index 79355c6fe..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/sampling/min_p.metal
+++ /dev/null
@@ -1,47 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../common/thread_context.h"
-#include "../common/threadgroup_reduce.h"
-
-#define BLOCK_SIZE 1024
-#define BLOCK_SIZE_IN_SIMDS (BLOCK_SIZE / 32)
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(MinP) (
- device const T* logits OPTIONAL(!in_place),
- device T* processed_logits,
- threadgroup float shared_reduce_buffer[BLOCK_SIZE_IN_SIMDS],
- constant uint& batch_size,
- constant uint& vocab_size,
- constant float& min_p,
- const ThreadContext thread_context,
- uint batch_idx GROUPS(batch_size),
- uint thread_idx THREADS(BLOCK_SIZE),
- const bool in_place SPECIALIZE
-) {
- if (in_place) {
- logits = processed_logits;
- }
-
- uint batch_start = batch_idx * vocab_size;
-
- // Find maximum logit
- float local_max = -INFINITY;
-#pragma unroll(4)
- for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {
- float logit_value = float(logits[batch_start + i]);
- local_max = fmax(local_max, logit_value);
- }
- float max_logit =
- threadgroup_cooperative_reduce<SimdReduceMax<float>, BLOCK_SIZE>(local_max, shared_reduce_buffer, thread_context);
-
- // Then the threshold is just max_logit + log(min_p), mask everything strictly
- // below it
- T t_threshold = T(max_logit + log(min_p));
-#pragma unroll(4)
- for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {
- T logit_value = logits[batch_start + i];
- processed_logits[batch_start + i] = select(T(-INFINITY), logit_value, logit_value >= t_threshold);
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/temperature.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/temperature.metal
deleted file mode 100644
index 57b63dbb1..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/sampling/temperature.metal
+++ /dev/null
@@ -1,34 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-
-#define BLOCK_SIZE 1024
-#define GRAIN_SIZE 64
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(Temperature) (
- device const T* logits OPTIONAL(!in_place),
- device T* processed_logits,
- constant uint& batch_size,
- constant uint& vocab_size,
- constant float& temperature,
- uint group_idx GROUPS(vocab_size.div_ceil(BLOCK_SIZE * GRAIN_SIZE)),
- uint batch_idx GROUPS(batch_size),
- uint thread_idx THREADS(BLOCK_SIZE),
- const bool in_place SPECIALIZE
-) {
- if (in_place) {
- logits = processed_logits;
- }
-
- uint base_idx = batch_idx * vocab_size + group_idx * BLOCK_SIZE * GRAIN_SIZE + thread_idx;
- uint batch_end = batch_idx * vocab_size + vocab_size;
-
-#pragma unroll(4)
- 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] = T(float(logits[global_idx]) / temperature);
- }
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/top_k.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/top_k.metal
deleted file mode 100644
index b88dc4092..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/sampling/top_k.metal
+++ /dev/null
@@ -1,81 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../common/thread_context.h"
-#include "../common/threadgroup_reduce.h"
-
-#define BLOCK_SIZE 1024
-#define BLOCK_SIZE_IN_SIMDS (BLOCK_SIZE / 32)
-#define MAX_ITERS 16
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(TopK)(
- device const T* logits OPTIONAL(!in_place),
- device T* processed_logits,
- threadgroup float shared_reduce_buffer[BLOCK_SIZE_IN_SIMDS],
- constant uint& batch_size,
- constant uint& vocab_size,
- constant uint& top_k,
- const ThreadContext thread_context,
- uint batch_idx GROUPS(batch_size),
- uint thread_idx THREADS(BLOCK_SIZE),
- const bool in_place SPECIALIZE
-) {
- if (in_place) {
- logits = processed_logits;
- }
-
- uint batch_start = batch_idx * vocab_size;
-
- // Find min and max logit for binary search
- float local_max = -INFINITY;
- float local_min = INFINITY;
-#pragma unroll(4)
- for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {
- float logit_value = float(logits[batch_start + i]);
- local_max = fmax(local_max, logit_value);
- local_min = select(local_min, fmin(local_min, logit_value), logit_value > -INFINITY);
- }
- float max_logit =
- threadgroup_cooperative_reduce<SimdReduceMax<float>, BLOCK_SIZE>(local_max, shared_reduce_buffer, thread_context);
- float min_logit =
- threadgroup_cooperative_reduce<SimdReduceMin<float>, BLOCK_SIZE>(local_min, shared_reduce_buffer, thread_context);
- // 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;
-#pragma unroll(4)
- for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {
- float logit_value = float(logits[batch_start + i]);
- local_num_above_threshold += select(0, 1, logit_value >= threshold);
- }
- uint num_above_threshold = threadgroup_cooperative_reduce<SimdReduceSum<uint>, BLOCK_SIZE>(
- local_num_above_threshold,
- (threadgroup uint*)shared_reduce_buffer,
- thread_context
- );
-
- // 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
-#pragma unroll(4)
- for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {
- T logit_value = logits[batch_start + i];
- processed_logits[batch_start + i] = select(T(-INFINITY), logit_value, logit_value >= t_threshold);
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/top_p.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/top_p.metal
deleted file mode 100644
index 7a6303feb..000000000
--- a/crates/backend-uzu/src/backends/metal/kernel/sampling/top_p.metal
+++ /dev/null
@@ -1,106 +0,0 @@
-#include <metal_stdlib>
-#include "../common/dsl.h"
-#include "../common/thread_context.h"
-#include "../common/threadgroup_reduce.h"
-
-#define BLOCK_SIZE 1024
-#define BLOCK_SIZE_IN_SIMDS (BLOCK_SIZE / 32)
-
-#define MAX_ITERS 16
-
-template <typename T>
-VARIANTS(T, float, half, bfloat)
-PUBLIC KERNEL(TopP) (
- device const T* logits OPTIONAL(!in_place),
- device T* processed_logits,
- threadgroup float shared_reduce_buffer[BLOCK_SIZE_IN_SIMDS],
- constant uint& batch_size,
- constant uint& vocab_size,
- constant float& top_p,
- const ThreadContext thread_context,
- uint batch_idx GROUPS(batch_size),
- uint thread_idx THREADS(BLOCK_SIZE),
- const bool in_place SPECIALIZE
-) {
- if (in_place) {
- logits = processed_logits;
- }
-
- uint batch_start = batch_idx * vocab_size;
-
- // Find min (for binary search) and max (for binary search and softmax)
- float local_max = -INFINITY;
- float local_min = INFINITY;
-#pragma unroll(4)
- for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {
- float logit_value = float(logits[batch_start + i]);
- local_max = fmax(local_max, logit_value);
- local_min = select(local_min, fmin(local_min, logit_value), logit_value > -INFINITY);
- }
- float max_logit =
- threadgroup_cooperative_reduce<SimdReduceMax<float>, BLOCK_SIZE>(local_max, shared_reduce_buffer, thread_context);
- float min_logit =
- threadgroup_cooperative_reduce<SimdReduceMin<float>, BLOCK_SIZE>(local_min, shared_reduce_buffer, thread_context);
-
- // Find denominator for softmax
- float local_sum = 0.0f;
-#pragma unroll(4)
- for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {
- float logit_value = float(logits[batch_start + i]);
- local_sum += select(0.0, fast::exp(logit_value - max_logit), logit_value > -INFINITY);
- }
- float total_sum =
- threadgroup_cooperative_reduce<SimdReduceSum<float>, BLOCK_SIZE>(local_sum, shared_reduce_buffer, thread_context);
-
- // Do the binary search on the threshold
- float target_mass = top_p * total_sum;
-
- 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
- float local_sum_above_threshold = 0.0f;
- float local_min_above_threshold = INFINITY;
-#pragma unroll(4)
- for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {
- float logit_value = float(logits[batch_start + i]);
- float logit_mass = fast::exp(logit_value - max_logit);
- local_sum_above_threshold += select(0.0, logit_mass, logit_value >= threshold);
- local_min_above_threshold =
- fmin(local_min_above_threshold, select(INFINITY, logit_mass, logit_value >= threshold));
- }
- float sum_above_threshold = threadgroup_cooperative_reduce<SimdReduceSum<float>, BLOCK_SIZE>(
- local_sum_above_threshold,
- shared_reduce_buffer,
- thread_context
- );
- float min_above_threshold = threadgroup_cooperative_reduce<SimdReduceMin<float>, BLOCK_SIZE>(
- local_min_above_threshold,
- shared_reduce_buffer,
- thread_context
- );
-
- // Early exit
- if (sum_above_threshold >= target_mass && sum_above_threshold - min_above_threshold < target_mass) {
- break;
- }
- // Update binary search
- if (sum_above_threshold >= target_mass) {
- low = threshold;
- } else {
- high = threshold;
- }
- threshold = (low + high) / 2.0;
- }
-
- T t_threshold = T(threshold);
-
- // We know the threshold, just mask everything below it
-#pragma unroll(4)
- for (uint i = thread_idx; i < vocab_size; i += BLOCK_SIZE) {
- T logit_value = logits[batch_start + i];
- processed_logits[batch_start + i] = select(T(-INFINITY), logit_value, logit_value >= t_threshold);
- }
-}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/sampling/unified_sampling.metal b/crates/backend-uzu/src/backends/metal/kernel/sampling/unified_sampling.metal
new file mode 100644
index 000000000..2bad4b0db
--- /dev/null
+++ b/crates/backend-uzu/src/backends/metal/kernel/sampling/unified_sampling.metal
@@ -0,0 +1,252 @@
+#include "../common/threadgroup_reduce.h"
+#include "../common/thread_context.h"
+#include "../common/defines.h"
+#include "../common/dsl.h"
+
+#include "../rng.h"
+
+#include "../generated/argmax.h"
+
+using namespace uzu::argmax;
+
+#define THREADGROUP_SIZE 1024
+#define THREADGROUP_SIZE_IN_SIMDS (THREADGROUP_SIZE / METAL_SIMD_SIZE)
+#define BITS_IN_U32 32
+
+#define WORDS_PER_OFFSET 4
+
+#define MAX_ITERS 64
+
+struct Logit {
+ float value;
+ uint32_t index;
+
+ static const constant Logit LOWEST;
+
+ template <typename T>
+ static inline Logit load(const device T* logits, uint32_t index) {
+ return {.value = float(logits[index]), .index = index};
+ }
+
+ inline bool operator>(Logit rhs) const { return value > rhs.value || (value == rhs.value && index < rhs.index); }
+};
+
+constexpr constant Logit
+ Logit::LOWEST{.value = -numeric_limits<float>::infinity(), .index = numeric_limits<uint32_t>::max()};
+
+struct SimdReduceMaxLogit {
+ using value_type = Logit;
+ static constant constexpr Logit identity = Logit::LOWEST;
+
+ static Logit simd_reduce(Logit x) {
+ METAL_PRAGMA_UNROLL
+ for (uint32_t offset = 16; offset > 0; offset >>= 1) {
+ Logit y = {
+ .value = simd_shuffle_xor(x.value, offset),
+ .index = simd_shuffle_xor(x.index, offset),
+ };
+ x = y > x ? y : x;
+ }
+ return x;
+ }
+};
+
+// NOTE: top_k + top_p combination is not exactly matching lalamo ("parallel" here, should be top-k then top-p)
+template <typename T>
+VARIANTS(T, float, bfloat)
+PUBLIC KERNEL(UnifiedSampling) (
+ const device T* logits,
+ device uint32_t* output,
+ const device uint64_t* seeds OPTIONAL(is_stochastic),
+ const device uint32_t* bitmask OPTIONAL(has_bitmask),
+ const constant float& temperature OPTIONAL(has_temperature),
+ const constant uint32_t& top_k OPTIONAL(has_top_k),
+ const constant float& top_p OPTIONAL(has_top_p),
+ const constant float& min_p OPTIONAL(has_min_p),
+ const constant uint32_t& vocab_size,
+ const constant uint32_t& batch_size,
+ const bool is_stochastic SPECIALIZE,
+ const bool has_bitmask SPECIALIZE,
+ const bool has_temperature SPECIALIZE,
+ const bool temperature_after_filters SPECIALIZE,
+ const bool has_top_k SPECIALIZE,
+ const bool has_top_p SPECIALIZE,
+ const bool has_min_p SPECIALIZE,
+ threadgroup Logit shared[THREADGROUP_SIZE_IN_SIMDS],
+ const ThreadContext thread_context,
+ uint batch_idx GROUPS(batch_size),
+ uint thread_idx THREADS(THREADGROUP_SIZE)
+) {
+ logits += vocab_size * batch_idx;
+ output += batch_idx;
+ uint64_t rng_seed, rng_offset;
+ PhiloxState rng;
+ if (is_stochastic) {
+ rng_seed = seeds[batch_idx];
+ rng_offset = div_ceil(vocab_size, THREADGROUP_SIZE * WORDS_PER_OFFSET) * thread_idx;
+ philox_init(&rng, rng_seed, rng_offset);
+ }
+ if (has_bitmask) {
+ bitmask += div_ceil(vocab_size, BITS_IN_U32) * batch_idx;
+ }
+ float recip_temperature;
+ if (has_temperature) {
+ recip_temperature = 1.0 / temperature;
+ }
+ float log_min_p;
+ if (has_min_p) {
+ log_min_p = log(min_p);
+ }
+
+ float thread_pre_filter_logit_max = -INFINITY;
+ float thread_pre_filter_logit_norm = 0.0;
+ Logit thread_post_gumbel_logit_max = Logit::LOWEST;
+ for (uint32_t logit_index = thread_idx; logit_index < vocab_size; logit_index += THREADGROUP_SIZE) {
+ Logit logit = Logit::load(logits, logit_index);
+
+ if (has_bitmask) {
+ bool mask = (bitmask[logit_index / BITS_IN_U32] >> (logit_index % BITS_IN_U32)) & 0b1;
+ logit.value = mask ? logit.value : -INFINITY;
+ }
+
+ if (has_temperature && !temperature_after_filters) {
+ logit.value *= recip_temperature;
+ }
+
+ if (has_top_p && logit.value != -INFINITY) {
+ float new_thread_pre_filter_logit_max = max(thread_pre_filter_logit_max, logit.value);
+
+ thread_pre_filter_logit_norm =
+ thread_pre_filter_logit_norm * exp(thread_pre_filter_logit_max - new_thread_pre_filter_logit_max) +
+ exp(logit.value - new_thread_pre_filter_logit_max);
+
+ thread_pre_filter_logit_max = new_thread_pre_filter_logit_max;
+ } else if (has_min_p) {
+ thread_pre_filter_logit_max = max(thread_pre_filter_logit_max, logit.value);
+ }
+
+ if (has_temperature && temperature_after_filters) {
+ logit.value *= recip_temperature;
+ }
+
+ if (is_stochastic) {
+ logit.value += -log(-log(uniform_float(&rng)));
+ }
+
+ thread_post_gumbel_logit_max = logit > thread_post_gumbel_logit_max ? logit : thread_post_gumbel_logit_max;
+ }
+ float pre_filter_logit_max;
+ if (has_top_p || has_min_p) {
+ pre_filter_logit_max = threadgroup_cooperative_reduce<SimdReduceMax<float>, THREADGROUP_SIZE>(
+ thread_pre_filter_logit_max,
+ (threadgroup float*)shared,
+ thread_context
+ );
+ }
+ float pre_filter_logit_norm;
+ if (has_top_p) {
+ if (thread_pre_filter_logit_norm != 0.0) {
+ thread_pre_filter_logit_norm *= exp(thread_pre_filter_logit_max - pre_filter_logit_max);
+ }
+ pre_filter_logit_norm = threadgroup_cooperative_reduce<SimdReduceSum<float>, THREADGROUP_SIZE>(
+ thread_pre_filter_logit_norm,
+ (threadgroup float*)shared,
+ thread_context
+ );
+ }
+ Logit candidate_logit_post_gumbel = threadgroup_cooperative_reduce<SimdReduceMaxLogit, THREADGROUP_SIZE>(
+ thread_post_gumbel_logit_max,
+ shared,
+ thread_context
+ );
+
+ for (uint32_t iteration = 0; iteration < MAX_ITERS; iteration++) {
+ Logit candidate_logit_pre_filter = Logit::load(logits, candidate_logit_post_gumbel.index);
+ if (has_temperature && !temperature_after_filters) {
+ candidate_logit_pre_filter.value *= recip_temperature;
+ }
+ if (is_stochastic) {
+ philox_init(&rng, rng_seed, rng_offset);
+ }
+
+ uint32_t thread_num_above_candidate = 0;
+ float thread_mass_above_candidate = 0.0;
+ Logit thread_next_candidate_logit_post_gumbel = Logit::LOWEST;
+ for (uint32_t logit_index = thread_idx; logit_index < vocab_size; logit_index += THREADGROUP_SIZE) {
+ Logit logit = Logit::load(logits, logit_index);
+
+ if (has_bitmask) {
+ bool mask = (bitmask[logit_index / BITS_IN_U32] >> (logit_index % BITS_IN_U32)) & 0b1;
+ logit.value = mask ? logit.value : -INFINITY;
+ }
+
+ if (has_temperature && !temperature_after_filters) {
+ logit.value *= recip_temperature;
+ }
+
+ bool above_current_pre_filter = logit > candidate_logit_pre_filter;
+
+ if (above_current_pre_filter) {
+ if (has_top_k) {
+ thread_num_above_candidate += 1;
+ }
+ if (has_top_p) {
+ thread_mass_above_candidate += exp(logit.value - pre_filter_logit_max) / pre_filter_logit_norm;
+ }
+ }
+
+ if (has_temperature && temperature_after_filters) {
+ logit.value *= recip_temperature;
+ }
+
+ if (is_stochastic) {
+ logit.value += -log(-log(uniform_float(&rng)));
+ }
+
+ if (above_current_pre_filter) {
+ thread_next_candidate_logit_post_gumbel =
+ logit > thread_next_candidate_logit_post_gumbel ? logit : thread_next_candidate_logit_post_gumbel;
+ }
+ }
+ uint32_t num_above_candidate;
+ if (has_top_k) {
+ num_above_candidate = threadgroup_cooperative_reduce<SimdReduceSum<uint32_t>, THREADGROUP_SIZE>(
+ thread_num_above_candidate,
+ (threadgroup uint32_t*)shared,
+ thread_context
+ );
+ }
+ float mass_above_candidate;
+ if (has_top_p) {
+ mass_above_candidate = threadgroup_cooperative_reduce<SimdReduceSum<float>, THREADGROUP_SIZE>(
+ thread_mass_above_candidate,
+ (threadgroup float*)shared,
+ thread_context
+ );
+ }
+ Logit next_candidate_logit_post_gumbel = threadgroup_cooperative_reduce<SimdReduceMaxLogit, THREADGROUP_SIZE>(
+ thread_next_candidate_logit_post_gumbel,
+ shared,
+ thread_context
+ );
+
+ bool filters_passed = true;
+
+ if (has_top_k && num_above_candidate >= top_k) {
+ filters_passed = false;
+ }
+ if (has_top_p && mass_above_candidate >= top_p) {
+ filters_passed = false;
+ }
+ if (has_min_p && candidate_logit_pre_filter.value < pre_filter_logit_max + log_min_p) {
+ filters_passed = false;
+ }
+
+ if (filters_passed || iteration == MAX_ITERS - 1) {
+ *output = candidate_logit_post_gumbel.index;
+ return;
+ }
+
+ candidate_logit_post_gumbel = next_candidate_logit_post_gumbel;
+ }
+}
diff --git a/crates/backend-uzu/src/encodable_block/mod.rs b/crates/backend-uzu/src/encodable_block/mod.rs
index dfb965035..115a9119a 100644
--- a/crates/backend-uzu/src/encodable_block/mod.rs
+++ b/crates/backend-uzu/src/encodable_block/mod.rs
@@ -39,5 +39,5 @@ pub use qk_unpack::QkUnpack;
pub use qkv_norm::QKVNorm;
pub use rms_norm::{PostLayerScalar, RMSNorm, RMSNormError};
pub use rope::{PrecalculatedRope, Rope};
-pub use sampling::{Sampling, SamplingArguments, SamplingInputs};
+pub use sampling::Sampling;
pub use short_conv_mixer::{ShortConvArguments, ShortConvMixer, ShortConvMixerError};
diff --git a/crates/backend-uzu/src/encodable_block/sampling.rs b/crates/backend-uzu/src/encodable_block/sampling.rs
new file mode 100644
index 000000000..2dd038862
--- /dev/null
+++ b/crates/backend-uzu/src/encodable_block/sampling.rs
@@ -0,0 +1,127 @@
+use std::{
+ cell::RefCell,
+ collections::{HashMap, hash_map::Entry},
+ mem::size_of,
+};
+
+use crate::{
+ backends::common::{Allocation, AllocationType, Backend, Context, Encoder, Kernels, kernel::UnifiedSamplingKernel},
+ data_type::DataType,
+ session::parameter::{SamplingMethod, SamplingProcessingOrder},
+};
+
+#[derive(PartialEq, Eq, Hash)]
+struct UnifiedSamplingKey {
+ has_seeds: bool,
+ has_bitmask: bool,
+ has_temperature: bool,
+ temperature_after_filters: bool,
+ has_top_k: bool,
+ has_top_p: bool,
+ has_min_p: bool,
+}
+
+pub struct Sampling<B: Backend> {
+ vocab_size: usize,
+ data_type: DataType,
+ unified_kernels: RefCell<HashMap<UnifiedSamplingKey, <B::Kernels as Kernels>::UnifiedSamplingKernel>>,
+}
+
+impl<B: Backend> Sampling<B> {
+ pub fn new(
+ data_type: DataType,
+ vocab_size: usize,
+ ) -> Self {
+ Self {
+ vocab_size,
+ data_type,
+ unified_kernels: RefCell::new(HashMap::new()),
+ }
+ }
+
+ pub fn encode(
+ &self,
+ logits: &Allocation<B>,
+ seeds: Option<&Allocation<B>>,
+ bitmask: Option<&Allocation<B>>,
+ sampling_method: SamplingMethod,
+ batch_size: usize,
+ encoder: &mut Encoder<B>,
+ ) -> Result<Allocation<B>, B::Error> {
+ // TODO: reject seeds with greedy
+ let (seeds, temperature, temperature_after_filters, top_k, top_p, min_p) = match sampling_method {
+ SamplingMethod::Greedy => (None, None, false, None, None, None),
+ SamplingMethod::Stochastic {
+ temperature,
+ top_k,
+ top_p,
+ min_p,
+ processing_order,
+ } => (
+ Some(seeds.unwrap()),
+ temperature,
+ match processing_order {
+ SamplingProcessingOrder::TemperatureThenFilters => false,
+ SamplingProcessingOrder::FiltersThenTemperature => true,
+ },
+ top_k,
+ top_p,
+ min_p,
+ ),
+ };
+
+ let key = UnifiedSamplingKey {
+ has_seeds: seeds.is_some(),
+ has_bitmask: bitmask.is_some(),
+ has_temperature: temperature.is_some(),
+ temperature_after_filters,
+ has_top_k: top_k.is_some(),
+ has_top_p: top_p.is_some(),
+ has_min_p: min_p.is_some(),
+ };
+ let mut unified_kernels = self.unified_kernels.borrow_mut();
+ let entry = unified_kernels.entry(key);
+ let kernel = match entry {
+ Entry::Occupied(occupied) => occupied.into_mut(),
+ Entry::Vacant(vacant) => {
+ let key = vacant.key();
+
+ let kernel = <B::Kernels as Kernels>::UnifiedSamplingKernel::new(
+ encoder.context(),
+ self.data_type,
+ key.has_seeds,
+ key.has_bitmask,
+ key.has_temperature,
+ key.temperature_after_filters,
+ key.has_top_k,
+ key.has_top_p,
+ key.has_min_p,
+ )?;
+
+ vacant.insert(kernel)
+ },
+ };
+
+ let mut output = encoder.context().create_allocation(batch_size * size_of::<u32>(), AllocationType::Global)?;
+
+ kernel.encode(
+ logits,
+ &mut output,
+ seeds,
+ bitmask,
+ temperature,
+ top_k,
+ top_p,
+ min_p,
+ self.vocab_size as u32,
+ batch_size as u32,
+ encoder,
+ );
+
+ Ok(output)
+ }
+}
+
+#[cfg(test)]
+#[path = "../../tests/unit/encodable_block/sampling_test.rs"]
+mod tests;
diff --git a/crates/backend-uzu/src/encodable_block/sampling/block.rs b/crates/backend-uzu/src/encodable_block/sampling/block.rs
deleted file mode 100644
index 51d9c50fb..000000000
--- a/crates/backend-uzu/src/encodable_block/sampling/block.rs
+++ /dev/null
@@ -1,195 +0,0 @@
-use std::mem::size_of;
-
-use thiserror::Error;
-
-use crate::{
- backends::common::{
- Allocation, Backend, Encoder, Kernels,
- gpu_types::ArgmaxPair,
- kernel::{
- ArgmaxFinalKernel, ArgmaxMainKernel, BitmaskKernel, GumbelKernel, MinPKernel, TemperatureKernel,
- TopKKernel, TopPKernel,
- },
- },
- data_type::DataType,
- session::parameter::{SamplingMethod, SamplingProcessingOrder},
-};
-
-pub struct SamplingBlock<B: Backend> {
- bitmask: <B::Kernels as Kernels>::BitmaskKernel,
- temperature: <B::Kernels as Kernels>::TemperatureKernel,
- topk: <B::Kernels as Kernels>::TopKKernel,
- topp: <B::Kernels as Kernels>::TopPKernel,
- minp: <B::Kernels as Kernels>::MinPKernel,
- gumbel: <B::Kernels as Kernels>::GumbelKernel,
- argmax_main: <B::Kernels as Kernels>::ArgmaxMainKernel,
- argmax_final: <B::Kernels as Kernels>::ArgmaxFinalKernel,
-}
-
-#[derive(Debug, Error)]
-pub enum SamplingError<B: Backend> {
- #[error("Backend error: {0}")]
- BackendError(#[source] B::Error),
- #[error("batch size must be greater than 0")]
- EmptyBatch,
- #[error("vocab size must be greater than 0")]
- EmptyVocab,
-}
-
-impl<B: Backend> SamplingBlock<B> {
- pub fn new(
- context: &B::Context,
- data_type: DataType,
- ) -> Result<Self, SamplingError<B>> {
- let bitmask = <B::Kernels as Kernels>::BitmaskKernel::new(context, data_type, true)
- .map_err(SamplingError::BackendError)?;
- let temperature = <B::Kernels as Kernels>::TemperatureKernel::new(context, data_type, true)
- .map_err(SamplingError::BackendError)?;
- let topk =
- <B::Kernels as Kernels>::TopKKernel::new(context, data_type, true).map_err(SamplingError::BackendError)?;
- let topp =
- <B::Kernels as Kernels>::TopPKernel::new(context, data_type, true).map_err(SamplingError::BackendError)?;
- let minp =
- <B::Kernels as Kernels>::MinPKernel::new(context, data_type, true).map_err(SamplingError::BackendError)?;
- let gumbel = <B::Kernels as Kernels>::GumbelKernel::new(context, data_type, true)
- .map_err(SamplingError::BackendError)?;
- let argmax_main =
- <B::Kernels as Kernels>::ArgmaxMainKernel::new(context, data_type).map_err(SamplingError::BackendError)?;
- let argmax_final =
- <B::Kernels as Kernels>::ArgmaxFinalKernel::new(context).map_err(SamplingError::BackendError)?;
-
- Ok(Self {
- bitmask,
- temperature,
- topk,
- topp,
- minp,
- gumbel,
- argmax_main,
- argmax_final,
- })
- }
-
- pub fn encode(
- &self,
- logits: &mut Allocation<B>,
- seeds: &Allocation<B>,
- bitmask: Option<&Allocation<B>>,
- sampled_tokens: &mut Allocation<B>,
- sampling_method: SamplingMethod,
- batch_size: usize,
- vocab_size: usize,
- encoder: &mut Encoder<B>,
- ) -> Result<(), SamplingError<B>> {
- if batch_size == 0 {
- return Err(SamplingError::EmptyBatch);
- }
- if vocab_size == 0 {
- return Err(SamplingError::EmptyVocab);
- }
-
- if let Some(bitmask) = bitmask {
- self.bitmask.encode(
- None::<&Allocation<B>>,
- bitmask,
- &mut *logits,
- batch_size as u32,
- vocab_size as u32,
- encoder,
- );
- }
-
- if let SamplingMethod::Stochastic {
- temperature,
- top_k,
- top_p,
- min_p,
- processing_order,
- } = sampling_method
- {
- if let Some(temperature) = temperature
- && processing_order == SamplingProcessingOrder::TemperatureThenFilters
- {
- self.temperature.encode(
- None::<&Allocation<B>>,
- &mut *logits,
- batch_size as u32,
- vocab_size as u32,
- temperature,
- encoder,
- );
- }
-
- if let Some(top_k) = top_k {
- self.topk.encode(
- None::<&Allocation<B>>,
- &mut *logits,
- batch_size as u32,
- vocab_size as u32,
- top_k,
- encoder,
- );
- }
- if let Some(top_p) = top_p {
- self.topp.encode(
- None::<&Allocation<B>>,
- &mut *logits,
- batch_size as u32,
- vocab_size as u32,
- top_p,
- encoder,
- );
- }
- if let Some(min_p) = min_p {
- self.minp.encode(
- None::<&Allocation<B>>,
- &mut *logits,
- batch_size as u32,
- vocab_size as u32,
- min_p,
- encoder,
- );
- }
-
- if let Some(temperature) = temperature
- && processing_order == SamplingProcessingOrder::FiltersThenTemperature
- {
- self.temperature.encode(
- None::<&Allocation<B>>,
- &mut *logits,
- batch_size as u32,
- vocab_size as u32,
- temperature,
- encoder,
- );
- }
-
- self.gumbel.encode(
- None::<&Allocation<B>>,
- seeds,
- 0,
- &mut *logits,
- batch_size as u32,
- vocab_size as u32,
- encoder,
- );
- }
-
- let block_size = 1024;
- let grain_size = 4;
- let elements_per_group = block_size * grain_size;
- let vocab_groups_per_batch = vocab_size.div_ceil(elements_per_group);
- let partial_results_count = batch_size * vocab_groups_per_batch;
- let mut partial_results = encoder
- .allocate_scratch(partial_results_count * size_of::<ArgmaxPair>())
- .map_err(SamplingError::BackendError)?;
- self.argmax_main.encode(&*logits, &mut partial_results, batch_size as u32, vocab_size as u32, encoder);
- self.argmax_final.encode(&partial_results, sampled_tokens, batch_size as u32, vocab_size as u32, encoder);
-
- Ok(())
- }
-}
-
-#[cfg(test)]
-#[path = "../../../tests/unit/encodable_block/sampling_top_p_test.rs"]
-mod top_p_tests;
diff --git a/crates/backend-uzu/src/encodable_block/sampling/mod.rs b/crates/backend-uzu/src/encodable_block/sampling/mod.rs
deleted file mode 100644
index a80576ebd..000000000
--- a/crates/backend-uzu/src/encodable_block/sampling/mod.rs
+++ /dev/null
@@ -1,103 +0,0 @@
-//! Sampling encodable.
-
-mod block;
-
-use block::SamplingBlock;
-pub use block::SamplingError;
-use ndarray::ArrayView2;
-
-use crate::{
- array::{Array, ArrayContextExt},
- backends::common::{Allocation, Backend, Encoder},
- data_type::DataType,
- session::parameter::SamplingMethod,
-};
-
-pub struct Sampling<B: Backend> {
- block: SamplingBlock<B>,
-}
-
-pub struct SamplingArguments<'a, B: Backend> {
- pub logits: &'a mut Allocation<B>,
- pub seeds: &'a Allocation<B>,
- pub bitmask: Option<&'a Allocation<B>>,
- pub output: &'a mut Allocation<B>,
- pub sampling_method: SamplingMethod,
- pub batch_size: usize,
- pub vocab_size: usize,
-}
-
-pub struct SamplingInputs<B: Backend> {
- pub seeds: Array<B>,
- pub bitmask: Option<Array<B>>,
-}
-
-impl<B: Backend> SamplingInputs<B> {
- pub fn bitmask_array_from_slice(
- context: &B::Context,
- row_count: usize,
- token_bitmask: &[u32],
- bitmask_row_len: usize,
- ) -> Array<B> {
- let mut array = context.create_array_zeros(&[row_count, bitmask_row_len], DataType::U32);
- let source =
- ArrayView2::from_shape((row_count, bitmask_row_len), token_bitmask).expect("Invalid token bitmask shape");
- array.copy_from_view(source);
- array
- }
-
- pub fn from_slices(
- context: &B::Context,
- token_seeds: &[u64],
- token_bitmask: Option<&[u32]>,
- bitmask_row_len: Option<usize>,
- ) -> Self {
- let seeds = context.create_array_from(&[token_seeds.len()], token_seeds);
-
- let bitmask = match (token_bitmask, bitmask_row_len) {
- (Some(token_bitmask), Some(bitmask_row_len)) => {
- Some(Self::bitmask_array_from_slice(context, token_seeds.len(), token_bitmask, bitmask_row_len))
- },
- (None, None) => None,
- _ => panic!("bitmask data and row length must either both exist or both be absent"),
- };
-
- Self {
- seeds,
- bitmask,
- }
- }
-}
-
-impl<B: Backend> Sampling<B> {
- pub fn new(
- context: &B::Context,
- data_type: DataType,
- ) -> Result<Self, SamplingError<B>> {
- let block = SamplingBlock::new(context, data_type)?;
- Ok(Self {
- block,
- })
- }
-
- pub fn encode(
- &self,
- args: SamplingArguments<B>,
- encoder: &mut Encoder<B>,
- ) -> Result<(), SamplingError<B>> {
- self.block.encode(
- args.logits,
- args.seeds,
- args.bitmask,
- args.output,
- args.sampling_method,
- args.batch_size,
- args.vocab_size,
- encoder,
- )
- }
-}
-
-#[cfg(test)]
-#[path = "../../../tests/unit/encodable_block/sampling_test.rs"]
-mod tests;
diff --git a/crates/backend-uzu/src/forward_pass/model_shape.rs b/crates/backend-uzu/src/forward_pass/model_shape.rs
index 9d43be9ab..0f2d70308 100644
--- a/crates/backend-uzu/src/forward_pass/model_shape.rs
+++ b/crates/backend-uzu/src/forward_pass/model_shape.rs
@@ -8,7 +8,7 @@ pub struct ModelShape {
pub data_type: DataType,
pub rope_data_type: DataType,
- vocabulary_size: usize,
+ pub vocabulary_size: usize,
model_dim: usize,
num_groups: usize,
diff --git a/crates/backend-uzu/src/language_model/gumbel.rs b/crates/backend-uzu/src/language_model/gumbel.rs
index 651c8dcbb..4d8d0e530 100644
--- a/crates/backend-uzu/src/language_model/gumbel.rs
+++ b/crates/backend-uzu/src/language_model/gumbel.rs
@@ -58,31 +58,31 @@ pub fn gumbel_float(
-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 THREADGROUP_SIZE: u32 = 1024;
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;
+pub fn revidx(
+ logit_idx: u32,
+ vocab_size: u32,
+) -> (u32, u32) {
+ let thread_idx = logit_idx % THREADGROUP_SIZE;
+ let thread_offset = vocab_size.div_ceil(THREADGROUP_SIZE * WORDS_PER_OFFSET) * thread_idx;
- 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;
+ let block_idx = logit_idx / THREADGROUP_SIZE;
+ let block_idx_offset = block_idx / WORDS_PER_OFFSET;
+ let block_idx_word = block_idx % WORDS_PER_OFFSET;
- (rng_offset, rng_word)
+ (thread_offset + block_idx_offset, block_idx_word)
}
pub fn speculator_sample(
seed: u64,
+ vocab_size: usize,
speculator_probs: &HashMap<u64, f32>,
) -> Option<u64> {
speculator_probs
.iter()
- .map(|(&k, &v)| (k, f32::ln(v) + gumbel_float(seed, revidx(k as u32))))
+ .map(|(&k, &v)| (k, f32::ln(v) + gumbel_float(seed, revidx(k as u32, vocab_size as u32))))
.max_by(|(_, av), (_, bv)| f32::total_cmp(av, bv))
.map(|(k, _)| k)
}
diff --git a/crates/backend-uzu/src/language_model/language_model_generator.rs b/crates/backend-uzu/src/language_model/language_model_generator.rs
index 35ca5bfa5..2ddef4405 100644
--- a/crates/backend-uzu/src/language_model/language_model_generator.rs
+++ b/crates/backend-uzu/src/language_model/language_model_generator.rs
@@ -17,12 +17,12 @@ use super::{
use crate::{
array::{Array, ArrayContextExt},
backends::common::{
- Allocation, AsBufferRangeRef, Backend, CommandBuffer, Context, DenseBuffer, Encoder, Pending,
+ Allocation, AllocationType, AsBufferRangeRef, Backend, CommandBuffer, Context, DenseBuffer, Encoder, Pending,
kernel::TokenCopySampledKernel,
},
config::model::language_model::LanguageModelConfig,
data_type::DataType,
- encodable_block::{DecoderDecodeInput, SamplingArguments, SamplingInputs},
+ encodable_block::DecoderDecodeInput,
forward_pass::{cache_layers::CacheLayersSlice, kv_cache_layer::INVALID_POSITION, token_inputs::TokenInputs},
language_model::grammar::CompiledGrammar,
session::{
@@ -52,7 +52,8 @@ struct ForwardPassResources<B: Backend> {
token_inputs: TokenInputs<B>,
logits: Option<Allocation<B>>,
sampling_output: Option<Allocation<B>>,
- sampling_inputs: Option<SamplingInputs<B>>,
+ sampling_seeds: Option<Allocation<B>>,
+ sampling_bitmask: Option<Allocation<B>>,
}
struct InFlightForwardPass<B: Backend> {
@@ -174,6 +175,7 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
&self.context.seed,
compiled_grammar.as_deref_mut(),
speculator.as_ref(),
+ self.context.model_shape.vocabulary_size,
&TrieCreationConfig::default(),
suffix_length + 1,
);
@@ -364,6 +366,7 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
&self.context.seed,
compiled_grammar.as_deref_mut(),
speculator.as_ref(),
+ self.context.model_shape.vocabulary_size,
&TrieCreationConfig::default(),
suffix_length,
);
@@ -452,7 +455,13 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
} else {
None
};
- let sampling_inputs = SamplingInputs::from_slices(self.context.context.as_ref(), &[token_seed], None, None);
+ let sampling_seed = [token_seed];
+ let mut sampling_seeds = self
+ .context
+ .context
+ .create_allocation(std::mem::size_of_val(&sampling_seed), AllocationType::Global)
+ .expect("Failed to create sampling seed allocation");
+ sampling_seeds.copyin(&sampling_seed);
let is_first_decode = !is_continuation;
let should_capture = self.gpu_capture.should_capture_decode(is_first_decode);
@@ -477,7 +486,8 @@ impl<B: Backend> LanguageModelGeneratorTrait for LanguageModelGenerator<B> {
sampling_length,
false,
Some(sampling_method),
- Some(sampling_inputs),
+ Some(sampling_seeds),
+ None,
)?;
// Copy sampled token: sampling_output → token_ids (for next pass)
@@ -717,14 +727,33 @@ impl<B: Backend> LanguageModelGenerator<B> {
let batch_dim = task.active_row_count;
let sampling_start = task.sampling_start;
let sampling_length = task.sampling_length;
- let sampling_inputs = sample.then(|| {
- self.create_sampling_inputs(
- task.sampling_start,
- task.sampling_length,
- &task.token_seeds,
- task.token_bitmask.as_deref(),
- )
- });
+ let (sampling_seeds, sampling_bitmask) = if sample {
+ let seeds = &task.token_seeds[task.sampling_start..task.sampling_start + task.sampling_length];
+ let mut seed_allocation = self
+ .context
+ .context
+ .create_allocation(std::mem::size_of_val(seeds), AllocationType::Global)
+ .expect("Failed to create sampling seed allocation");
+ seed_allocation.copyin(seeds);
+
+ let bitmask_allocation = task.token_bitmask.as_deref().map(|mask| {
+ let row_len = self.context.model_shape.bitmask_shape(1)[1];
+ let start = task.sampling_start * row_len;
+ let end = start + task.sampling_length * row_len;
+ let bitmask = &mask[start..end];
+ let mut allocation = self
+ .context
+ .context
+ .create_allocation(std::mem::size_of_val(bitmask), AllocationType::Global)
+ .expect("Failed to create sampling bitmask allocation");
+ allocation.copyin(bitmask);
+ allocation
+ });
+
+ (Some(seed_allocation), bitmask_allocation)
+ } else {
+ (None, None)
+ };
let is_first_decode = task.token_ids.len() == 1;
let should_capture = self.gpu_capture.should_capture_decode(is_first_decode);
@@ -747,7 +776,8 @@ impl<B: Backend> LanguageModelGenerator<B> {
sampling_length,
is_prefilling,
sample.then_some(sampling_method),
- sampling_inputs,
+ sampling_seeds,
+ sampling_bitmask,
)?;
let pending = encoder.end_encoding().submit();
@@ -758,9 +788,10 @@ impl<B: Backend> LanguageModelGenerator<B> {
token_inputs,
logits,
sampling_output,
- sampling_inputs,
+ sampling_seeds,
+ sampling_bitmask,
} = resources;
- drop((token_inputs, logits, sampling_inputs));
+ drop((token_inputs, logits, sampling_seeds, sampling_bitmask));
drop(completed);
let run_time = run_start.elapsed().as_secs_f64();
@@ -787,10 +818,10 @@ impl<B: Backend> LanguageModelGenerator<B> {
sampling_length: usize,
is_prefilling: bool,
sampling_method: Option<SamplingMethod>,
- sampling_inputs: Option<SamplingInputs<B>>,
+ sampling_seeds: Option<Allocation<B>>,
+ sampling_bitmask: Option<Allocation<B>>,
) -> Result<ForwardPassResources<B>, Error> {
- let mut sampling_output = sampling_method
- .map(|_| context.context.create_array_uninitialized(&[sampling_length], DataType::U32).into_allocation());
+ let mut sampling_output = None;
let mut logits = None;
if is_prefilling {
let mut cache_layers = context.cache_layers.borrow_mut();
@@ -818,25 +849,21 @@ impl<B: Backend> LanguageModelGenerator<B> {
#[cfg(feature = "tracing")]
None,
);
- let mut retained_logits = context
+ let retained_logits = context
.executables
.encode_decode(decoder_arguments, DecoderDecodeInput::TokenIds(token_inputs.token_ids()), None, encoder)
.map_err(|e| Error::EncodeFailed(Box::new(e)))?;
- let sampling_inputs = sampling_inputs.as_ref().expect("Sampling requires sampling inputs");
- let sampling_result = context.gpu_sampler.encode(
- SamplingArguments {
- logits: &mut retained_logits,
- seeds: sampling_inputs.seeds.allocation(),
- bitmask: sampling_inputs.bitmask.as_ref().map(Array::allocation),
- output: sampling_output.as_mut().expect("Sampling requires output allocation"),
- sampling_method: sampling_method.expect("Sampling requires method"),
- batch_size: sampling_length,
- vocab_size: context.model_config.decoder_config.vocab_size,
- },
+ let sampling_seeds = sampling_seeds.as_ref().expect("Sampling requires seeds");
+ let output = context.gpu_sampler.encode(
+ &retained_logits,
+ Some(sampling_seeds),
+ sampling_bitmask.as_ref(),
+ sampling_method.expect("Sampling requires method"),
+ sampling_length,
encoder,
);
- sampling_result.map_err(|e| Error::EncodeFailed(Box::new(e)))?;
+ sampling_output = Some(output.map_err(|e| Error::EncodeFailed(Box::new(e)))?);
logits = Some(retained_logits);
}
@@ -844,7 +871,8 @@ impl<B: Backend> LanguageModelGenerator<B> {
token_inputs,
logits,
sampling_output,
- sampling_inputs,
+ sampling_seeds,
+ sampling_bitmask,
})
}
@@ -865,24 +893,6 @@ impl<B: Backend> LanguageModelGenerator<B> {
)
}
- fn create_sampling_inputs(
- &self,
- sampling_start: usize,
- sampling_length: usize,
- token_seeds: &[u64],
- token_bitmask: Option<&[u32]>,
- ) -> SamplingInputs<B> {
- let seeds = &token_seeds[sampling_start..sampling_start + sampling_length];
- let bitmask_row_len = token_bitmask.map(|_| self.context.model_shape.bitmask_shape(1)[1]);
- let bitmask = token_bitmask.map(|mask| {
- let row_len = bitmask_row_len.expect("bitmask row length must exist");
- let start = sampling_start * row_len;
- let end = start + sampling_length * row_len;
- &mask[start..end]
- });
- SamplingInputs::from_slices(self.context.context.as_ref(), seeds, bitmask, bitmask_row_len)
- }
-
fn read_sampling_output(
&self,
sampling_output: &Allocation<B>,
@@ -898,8 +908,8 @@ impl<B: Backend> LanguageModelGenerator<B> {
suffix_start: Option<usize>,
wait_until_completed: bool,
) -> Result<(), Error> {
- let mut encoder =
- Encoder::<B>::new(&self.context.context).map_err(|e| Error::UnableToCreateCommandBuffer(e.into()))?;
+ let mut encoder = Encoder::<B>::new(self.context.context.as_ref())
+ .map_err(|e| Error::UnableToCreateCommandBuffer(e.into()))?;
{
let mut cache_layers = self.context.cache_layers.borrow_mut();
diff --git a/crates/backend-uzu/src/language_model/language_model_generator_context.rs b/crates/backend-uzu/src/language_model/language_model_generator_context.rs
index dca924e6d..9fd45ca9d 100644
--- a/crates/backend-uzu/src/language_model/language_model_generator_context.rs
+++ b/crates/backend-uzu/src/language_model/language_model_generator_context.rs
@@ -147,8 +147,7 @@ impl<B: Backend> LanguageModelGeneratorContext<B> {
.map_err(|e| Error::UnableToCreateContext(e.into()))?,
);
- let gpu_sampler =
- Sampling::<B>::new(&context, model_shape.data_type).map_err(|e| Error::UnableToCreateContext(e.into()))?;
+ let gpu_sampler = Sampling::<B>::new(model_shape.data_type, model_config.decoder_config.vocab_size);
let token_copy_sampled = <B::Kernels as Kernels>::TokenCopySampledKernel::new(&context)
.map_err(|e| Error::UnableToCreateContext(e.into()))?;
diff --git a/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs b/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs
index 29f2d705b..fa633f6b7 100644
--- a/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs
+++ b/crates/backend-uzu/src/session/tts_session/decoder_runtime.rs
@@ -1,11 +1,9 @@
use super::{decoder_support::*, *};
use crate::{
array::{Array, ArrayContextExt},
- backends::common::{Allocation, AsBufferRangeRef},
+ backends::common::{Allocation, AllocationType, AsBufferRangeRef},
config::decoder::DecoderConfig,
- encodable_block::{
- DecoderArguments, DecoderDecodeInput, LayerArguments, Linear, PrecalculatedRope, SamplingInputs,
- },
+ encodable_block::{DecoderArguments, DecoderDecodeInput, LayerArguments, Linear, PrecalculatedRope},
forward_pass::{rope::precalculate_rope, token_inputs::TokenInputs},
session::types::TtsModelConfigError,
};
@@ -47,7 +45,7 @@ impl<B: Backend> TokenDecoderLoadedModel<B> {
&readout_tree,
)
.map_err(|error| Error::UnableToCreateDecoder(Box::new(error)))?;
- let sampler = GpuSampling::new(context.as_ref(), model_shape.data_type).map_err(unable_to_create_context)?;
+ let sampler = GpuSampling::new(model_shape.data_type, decoder_config.vocab_size);
let token_copy_sampled =
<B::Kernels as Kernels>::TokenCopySampledKernel::new(context.as_ref()).map_err(unable_to_create_context)?;
@@ -221,15 +219,6 @@ impl<B: Backend> TokenDecoderRunner<B> {
self.next_position = 0;
}
- fn create_sampling_inputs_from_slices(
- &self,
- token_seeds: &[u64],
- token_bitmask: Option<&[u32]>,
- ) -> SamplingInputs<B> {
- let bitmask_row_len = token_bitmask.map(|_| self.ctx.decoder_config.vocab_size.div_ceil(32));
- SamplingInputs::from_slices(self.ctx.context.as_ref(), token_seeds, token_bitmask, bitmask_row_len)
- }
-
fn llm_token_inputs(
&self,
token_ids: &[u64],
@@ -275,28 +264,24 @@ impl<B: Backend> TokenDecoderRunner<B> {
&self,
encoder: &mut Encoder<B>,
logits: &mut Allocation<B>,
- output: &mut Allocation<B>,
sampling_method: SamplingMethod,
batch_size: usize,
- sampling_inputs: SamplingInputs<B>,
- pending_sampling_inputs: &mut Vec<SamplingInputs<B>>,
- ) -> Result<(), Error> {
- pending_sampling_inputs.push(sampling_inputs);
- let sampling_inputs = pending_sampling_inputs.last().expect("sampling inputs must be pending");
+ sampling_seeds: Allocation<B>,
+ sampling_bitmask: Option<Allocation<B>>,
+ pending_sampling_allocations: &mut Vec<Allocation<B>>,
+ ) -> Result<Allocation<B>, Error> {
+ let seeds_index = pending_sampling_allocations.len();
+ pending_sampling_allocations.push(sampling_seeds);
+ let bitmask_index = sampling_bitmask.map(|sampling_bitmask| {
+ let index = pending_sampling_allocations.len();
+ pending_sampling_allocations.push(sampling_bitmask);
+ index
+ });
+ let sampling_seeds = &pending_sampling_allocations[seeds_index];
+ let sampling_bitmask = bitmask_index.map(|index| &pending_sampling_allocations[index]);
self.ctx
.sampler
- .encode(
- crate::encodable_block::SamplingArguments {
- logits,
- seeds: sampling_inputs.seeds.allocation(),
- bitmask: sampling_inputs.bitmask.as_ref().map(Array::allocation),
- output,
- sampling_method,
- batch_size,
- vocab_size: self.ctx.decoder_config.vocab_size,
- },
- encoder,
- )
+ .encode(logits, Some(sampling_seeds), sampling_bitmask, sampling_method, batch_size, encoder)
.map_err(|err| Error::EncodeFailed(Box::new(err)))
}
@@ -402,7 +387,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
vocab_limit: Option<usize>,
sampling: &mut TextSamplingState,
pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_inputs: &mut Vec<SamplingInputs<B>>,
+ pending_sampling_allocations: &mut Vec<Allocation<B>>,
pending_sampling_outputs: &mut Vec<Allocation<B>>,
) -> Result<usize, Error> {
let total_count =
@@ -489,7 +474,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
pre_injection_encode,
initial_seed,
pending_token_inputs,
- pending_sampling_inputs,
+ pending_sampling_allocations,
)?;
let first_followup_token_ids = if followup_count > 0 {
@@ -516,7 +501,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
sampling.method(),
1,
pending_token_inputs,
- pending_sampling_inputs,
+ pending_sampling_allocations,
pending_sampling_outputs,
)?;
}
@@ -545,7 +530,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
sampling_method: SamplingMethod,
results_offset_slots: usize,
pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_inputs: &mut Vec<SamplingInputs<B>>,
+ pending_sampling_allocations: &mut Vec<Allocation<B>>,
pending_sampling_outputs: &mut Vec<Allocation<B>>,
) -> Result<(), Error> {
let token_bitmask =
@@ -555,8 +540,22 @@ impl<B: Backend> TokenDecoderRunner<B> {
for pass in 0..followup_count {
let results_slot = results_offset_slots + pass;
let token_ids = [0];
- let seed = self.ctx.async_chain_seeds.as_slice::<u64>()[pass];
- let sampling_inputs = self.create_sampling_inputs_from_slices(&[seed], token_bitmask.as_deref());
+ let sampling_seed = [self.ctx.async_chain_seeds.as_slice::<u64>()[pass]];
+ let mut sampling_seeds = self
+ .ctx
+ .context
+ .create_allocation(std::mem::size_of_val(&sampling_seed), AllocationType::Global)
+ .expect("Failed to create sampling seed allocation");
+ sampling_seeds.copyin(&sampling_seed);
+ let sampling_bitmask = token_bitmask.as_deref().map(|bitmask| {
+ let mut allocation = self
+ .ctx
+ .context
+ .create_allocation(std::mem::size_of_val(bitmask), AllocationType::Global)
+ .expect("Failed to create sampling bitmask allocation");
+ allocation.copyin(bitmask);
+ allocation
+ });
let token_inputs =
self.llm_token_inputs(&token_ids, &[self.next_position + pass], next_token_ids.take(), 0, 1);
pending_token_inputs.push(token_inputs);
@@ -572,15 +571,14 @@ impl<B: Backend> TokenDecoderRunner<B> {
1,
false,
)?;
- let mut sampling_output = self.create_sampling_output(1);
- self.encode_sampling_on(
+ let sampling_output = self.encode_sampling_on(
encoder,
&mut logits,
- &mut sampling_output,
sampling_method,
1,
- sampling_inputs,
- pending_sampling_inputs,
+ sampling_seeds,
+ sampling_bitmask,
+ pending_sampling_allocations,
)?;
if pass + 1 < followup_count {
let token_ids_shape = [1];
@@ -672,13 +670,6 @@ impl<B: Backend> TokenDecoderRunner<B> {
self.two_token_vocab_masks.get(&vocab_limit).map(|mask| mask.as_ref())
}
- fn create_sampling_output(
- &self,
- sampling_length: usize,
- ) -> Allocation<B> {
- self.ctx.context.create_array_uninitialized(&[sampling_length], DataType::U32).into_allocation()
- }
-
fn encode_decode_with_fishaudio_readout_on<'input>(
&mut self,
encoder: &mut Encoder<B>,
@@ -779,7 +770,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
mut pre_injection_encode: Option<&mut PreInjectionEncodeCallback<B>>,
preconsumed_seed: Option<u64>,
pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_inputs: &mut Vec<SamplingInputs<B>>,
+ pending_sampling_allocations: &mut Vec<Allocation<B>>,
) -> Result<Allocation<B>, Error> {
if token_ids.is_empty() {
return Err(Error::GenerateFailed);
@@ -846,7 +837,21 @@ impl<B: Backend> TokenDecoderRunner<B> {
let row_end = row_start + sampling_length * row_words;
&mask[row_start..row_end]
});
- let sampling_inputs = self.create_sampling_inputs_from_slices(sampling_token_seeds, sampling_token_bitmask);
+ let mut sampling_seeds = self
+ .ctx
+ .context
+ .create_allocation(std::mem::size_of_val(sampling_token_seeds), AllocationType::Global)
+ .expect("Failed to create sampling seed allocation");
+ sampling_seeds.copyin(sampling_token_seeds);
+ let sampling_bitmask = sampling_token_bitmask.map(|bitmask| {
+ let mut allocation = self
+ .ctx
+ .context
+ .create_allocation(std::mem::size_of_val(bitmask), AllocationType::Global)
+ .expect("Failed to create sampling bitmask allocation");
+ allocation.copyin(bitmask);
+ allocation
+ });
let token_inputs = self.llm_token_inputs(token_ids, positions, None, sampling_start, sampling_length);
pending_token_inputs.push(token_inputs);
let token_inputs = pending_token_inputs.last().expect("token inputs must be pending");
@@ -880,15 +885,14 @@ impl<B: Backend> TokenDecoderRunner<B> {
sampling_length,
capture_hidden,
)?;
- let mut sampling_output = self.create_sampling_output(sampling_length);
- self.encode_sampling_on(
+ let sampling_output = self.encode_sampling_on(
encoder,
&mut logits,
- &mut sampling_output,
sampling.method(),
sampling_length,
- sampling_inputs,
- pending_sampling_inputs,
+ sampling_seeds,
+ sampling_bitmask,
+ pending_sampling_allocations,
)?;
Ok(sampling_output)
@@ -1027,7 +1031,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
let context = Rc::clone(&self.ctx.context);
let mut encoder = Encoder::new(context.as_ref()).map_err(unable_to_create_context)?;
let mut pending_token_inputs = Vec::new();
- let mut pending_sampling_inputs = Vec::new();
+ let mut pending_sampling_allocations = Vec::new();
let sampling_output = self.encode_single_forward_pass_on(
&mut encoder,
@@ -1039,7 +1043,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
pre_injection_encode,
None,
&mut pending_token_inputs,
- &mut pending_sampling_inputs,
+ &mut pending_sampling_allocations,
)?;
self.encode_cache_acceptance_update_on(&mut encoder, token_count);
@@ -1120,7 +1124,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
capture_hidden: bool,
pre_injection_encode: Option<&mut PreInjectionEncodeCallback<B>>,
pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_inputs: &mut Vec<SamplingInputs<B>>,
+ pending_sampling_allocations: &mut Vec<Allocation<B>>,
pending_sampling_outputs: &mut Vec<Allocation<B>>,
) -> Result<(), Error> {
let token_count = token_ids.len();
@@ -1135,7 +1139,7 @@ impl<B: Backend> TokenDecoderRunner<B> {
pre_injection_encode,
None,
pending_token_inputs,
- pending_sampling_inputs,
+ pending_sampling_allocations,
)?;
// Copy sampled token to async_chain_results[0] so the caller can
diff --git a/crates/backend-uzu/src/session/tts_session/fishaudio.rs b/crates/backend-uzu/src/session/tts_session/fishaudio.rs
index a4fd27d7a..7191b4838 100644
--- a/crates/backend-uzu/src/session/tts_session/fishaudio.rs
+++ b/crates/backend-uzu/src/session/tts_session/fishaudio.rs
@@ -6,7 +6,6 @@ use crate::{
decoder::DecoderConfig, embedding::AnyEmbeddingConfig,
tts::text_decoder::fish_audio_text_decoder::FishAudioTextDecoderConfig,
},
- encodable_block::SamplingInputs,
forward_pass::token_inputs::TokenInputs,
session::types::TtsModelConfigError,
};
@@ -624,7 +623,7 @@ impl<B: Backend> FishAudioTextDecoderRuntime<B> {
let mut shared_encoder = Encoder::new(context.as_ref()).map_err(unable_to_create_context)?;
let mut pending_token_inputs = Vec::new();
- let mut pending_sampling_inputs = Vec::new();
+ let mut pending_sampling_allocations = Vec::new();
let mut pending_sampling_outputs = Vec::new();
let total_fast_count = self.encode_fast_passes_on(
&mut shared_encoder,
@@ -633,7 +632,7 @@ impl<B: Backend> FishAudioTextDecoderRuntime<B> {
followup_count,
sampling,
&mut pending_token_inputs,
- &mut pending_sampling_inputs,
+ &mut pending_sampling_allocations,
&mut pending_sampling_outputs,
)?;
self.encode_slow_pass_on(
@@ -644,7 +643,7 @@ impl<B: Backend> FishAudioTextDecoderRuntime<B> {
sampling,
by_codebook,
&mut pending_token_inputs,
- &mut pending_sampling_inputs,
+ &mut pending_sampling_allocations,
&mut pending_sampling_outputs,
)?;
let submit_result = self.slow_runner.submit_and_wait_command_buffer(shared_encoder);
@@ -673,7 +672,7 @@ impl<B: Backend> FishAudioTextDecoderRuntime<B> {
followup_count: usize,
sampling: &mut TextSamplingState,
pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_inputs: &mut Vec<SamplingInputs<B>>,
+ pending_sampling_allocations: &mut Vec<Allocation<B>>,
pending_sampling_outputs: &mut Vec<Allocation<B>>,
) -> Result<usize, Error> {
let (slow_runner, fast_runner, semantic_bridge) =
@@ -702,7 +701,7 @@ impl<B: Backend> FishAudioTextDecoderRuntime<B> {
Some(fast_vocab_limit),
sampling,
pending_token_inputs,
- pending_sampling_inputs,
+ pending_sampling_allocations,
pending_sampling_outputs,
)
}
@@ -717,7 +716,7 @@ impl<B: Backend> FishAudioTextDecoderRuntime<B> {
sampling: &mut TextSamplingState,
by_codebook: &[Vec<u32>],
pending_token_inputs: &mut Vec<TokenInputs<B>>,
- pending_sampling_inputs: &mut Vec<SamplingInputs<B>>,
+ pending_sampling_allocations: &mut Vec<Allocation<B>>,
pending_sampling_outputs: &mut Vec<Allocation<B>>,
) -> Result<(), Error> {
let (slow_runner, fast_runner, semantic_bridge) =
@@ -762,7 +761,7 @@ impl<B: Backend> FishAudioTextDecoderRuntime<B> {
true, // capture_hidden
Some(&mut pre_codebook_sum),
pending_token_inputs,
- pending_sampling_inputs,
+ pending_sampling_allocations,
pending_sampling_outputs,
)
}
diff --git a/crates/backend-uzu/src/trie.rs b/crates/backend-uzu/src/trie.rs
index afbcd51d3..abf14a33a 100644
--- a/crates/backend-uzu/src/trie.rs
+++ b/crates/backend-uzu/src/trie.rs
@@ -97,6 +97,7 @@ impl TrieNode {
seed: &PRng,
mut compiled_grammar: Option<&mut (dyn CompiledGrammar + 'static)>,
speculator: &dyn Speculator,
+ vocab_size: usize,
creation_config: &TrieCreationConfig,
max_length: usize,
) -> Self {
@@ -119,7 +120,9 @@ impl TrieNode {
while length < max_length {
// Guuumbel speculator trick: both speculator and llm sample via gumbel max trick using the same noise for increased acceptance rate
- if let Some(next_speculated_token) = speculator_sample(cur_node.seed(), &cur_node_speculator_weights) {
+ if let Some(next_speculated_token) =
+ speculator_sample(cur_node.seed(), vocab_size, &cur_node_speculator_weights)
+ {
// Add speculated token to the trie
let mask = if let Some(compiled_grammar) = compiled_grammar.as_deref_mut() {
if compiled_grammar.accept_token(next_speculated_token).is_err() {
diff --git a/crates/backend-uzu/tests/common/proptest.rs b/crates/backend-uzu/tests/common/proptest.rs
index caca162c9..79c871590 100644
--- a/crates/backend-uzu/tests/common/proptest.rs
+++ b/crates/backend-uzu/tests/common/proptest.rs
@@ -12,7 +12,7 @@ use backend_uzu::{
use proptest::prelude::*;
pub fn kernel_data_type() -> impl Strategy<Value = DataType> {
- prop_oneof![Just(DataType::F16), Just(DataType::BF16), Just(DataType::F32)]
+ prop_oneof![Just(DataType::BF16), Just(DataType::F32)]
}
pub struct TestContextes {
diff --git a/crates/backend-uzu/tests/performance/kernel/mod.rs b/crates/backend-uzu/tests/performance/kernel/mod.rs
index 104d81618..d5fcf4db9 100644
--- a/crates/backend-uzu/tests/performance/kernel/mod.rs
+++ b/crates/backend-uzu/tests/performance/kernel/mod.rs
@@ -1,3 +1,2 @@
mod matmul;
mod rms_norm_bench;
-mod sampling;
diff --git a/crates/backend-uzu/tests/performance/kernel/sampling/argmax_bench.rs b/crates/backend-uzu/tests/performance/kernel/sampling/argmax_bench.rs
deleted file mode 100644
index 5bcc80cf2..000000000
--- a/crates/backend-uzu/tests/performance/kernel/sampling/argmax_bench.rs
+++ /dev/null
@@ -1,112 +0,0 @@
-use std::mem::{MaybeUninit, size_of};
-
-use backend_uzu::{
- array::{ArrayContextExt, ArrayElement},
- backends::common::{
- AllocationType, Backend, Context, Encoder, Kernels,
- gpu_types::ArgmaxPair,
- kernel::{ArgmaxFinalKernel, ArgmaxMainKernel, ArgmaxSingleKernel},
- },
- data_type::DataType,
-};
-use criterion::{BenchmarkId, Criterion, Throughput};
-use num_traits::{Float, NumCast};
-use rand::{RngExt, SeedableRng, rngs::SmallRng};
-use rand_distr::Normal;
-
-use crate::{common::type_short_name, uzu_bench};
-
-fn get_argmax_data<T: ArrayElement + Float>(
- seed: u64,
- batch_size: usize,
- vocab_size: usize,
-) -> Box<[T]> {
- let mut rng = SmallRng::seed_from_u64(seed);
- let distribution = Normal::new(0.0, 32.0).unwrap();
- let mut logits: Box<[MaybeUninit<T>]> = Box::new_uninit_slice(batch_size * vocab_size);
- for logit in logits.iter_mut() {
- logit.write(<T as NumCast>::from(rng.sample(distribution)).unwrap());
- }
- unsafe { logits.assume_init() }
-}
-
-#[uzu_bench]
-fn bench_argmax(c: &mut Criterion) {
- type T = f32;
- let batch_size = 1;
-
- for_each_backend!(|B| {
- let context = <B as Backend>::Context::new().unwrap();
-
- let single_kernel =
- <<B as Backend>::Kernels as Kernels>::ArgmaxSingleKernel::new(&context, T::data_type()).unwrap();
- let twopass_kernel_main =
- <<B as Backend>::Kernels as Kernels>::ArgmaxMainKernel::new(&context, T::data_type()).unwrap();
- let twopass_kernel_final = <<B as Backend>::Kernels as Kernels>::ArgmaxFinalKernel::new(&context).unwrap();
-
- let mut output_buffer = context.create_array_uninitialized(&[batch_size], DataType::U32).into_allocation();
-
- let mut group = c.benchmark_group(format!("{}/Kernel/Sampling/Argmax", type_short_name::<B>()));
-
- for vocab_size in [
- 65536, // LFM2-350M
- 128256, // Llama-3.2-1B
- 151936, // Qwen3-1.7B
- 262144, // Gemma-3-1b
- ] {
- let logits_data = get_argmax_data::<T>(1337, batch_size, vocab_size);
- let logits_buffer = context.create_array_from(&[logits_data.len()], logits_data.as_ref()).into_allocation();
- let mut twopass_partial_results_buffer = context
- .create_allocation(
- batch_size * vocab_size.div_ceil(4096) * size_of::<ArgmaxPair>(),
- AllocationType::Global,
- )
- .unwrap();
-
- group.throughput(Throughput::Elements(vocab_size as u64));
-
- group.bench_function(BenchmarkId::new("SinglePass", format!("Vocab[{vocab_size}]")), |b| {
- b.iter_custom(|n_iters| {
- let mut encoder = Encoder::<B>::new(&context).unwrap();
-
- for _ in 0..n_iters {
- single_kernel.encode(
- &logits_buffer,
- &mut output_buffer,
- batch_size as u32,
- vocab_size as u32,
- &mut encoder,
- );
- }
-
- encoder.end_encoding().submit().wait_until_completed().unwrap().gpu_execution_time()
- })
- });
-
- group.bench_function(BenchmarkId::new("TwoPass", format!("Vocab[{vocab_size}]")), |b| {
- b.iter_custom(|n_iters| {
- let mut encoder = Encoder::<B>::new(&context).unwrap();
-
- for _ in 0..n_iters {
- twopass_kernel_main.encode(
- &logits_buffer,
- &mut twopass_partial_results_buffer,
- batch_size as u32,
- vocab_size as u32,
- &mut encoder,
- );
- twopass_kernel_final.encode(
- &twopass_partial_results_buffer,
- &mut output_buffer,
- batch_size as u32,
- vocab_size as u32,
- &mut encoder,
- );
- }
-
- encoder.end_encoding().submit().wait_until_completed().unwrap().gpu_execution_time()
- })
- });
- }
- });
-}
diff --git a/crates/backend-uzu/tests/performance/kernel/sampling/mod.rs b/crates/backend-uzu/tests/performance/kernel/sampling/mod.rs
deleted file mode 100644
index ed5b250a0..000000000
--- a/crates/backend-uzu/tests/performance/kernel/sampling/mod.rs
+++ /dev/null
@@ -1 +0,0 @@
-mod argmax_bench;
diff --git a/crates/backend-uzu/tests/performance/language_model/language_model_generator_bench.rs b/crates/backend-uzu/tests/performance/language_model/language_model_generator_bench.rs
index d0c2950ad..e40286f59 100644
--- a/crates/backend-uzu/tests/performance/language_model/language_model_generator_bench.rs
+++ b/crates/backend-uzu/tests/performance/language_model/language_model_generator_bench.rs
@@ -31,6 +31,7 @@ fn run_generator<B: Backend>(
&generator.context.seed,
None,
speculator.as_ref(),
+ 1024, // greedy, doesn't matter
&TrieCreationConfig::default(),
suffix_length,
);
diff --git a/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rs b/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rs
index f789bd0e2..61a1bd99d 100644
--- a/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rs
+++ b/crates/backend-uzu/tests/unit/encodable_block/sampling_test.rs
@@ -1,676 +1,187 @@
-#![cfg(metal_backend)]
+use std::{iter::repeat_with, mem::MaybeUninit};
-use rand::seq::SliceRandom;
+use backend_uzu::{
+ array::ArrayElement,
+ backends::common::{AllocationType, Backend, Context, Encoder},
+ dispatch_dtype,
+};
+use num_traits::{Float, NumCast};
+use proptest::prelude::*;
+use rand::{RngExt, SeedableRng, rngs::SmallRng};
+use rand_distr::Normal;
-// for Vec::shuffle
-use super::block::SamplingBlock;
use crate::{
- backends::{
- common::{
- Backend, Context, Encoder, Kernels,
- kernel::{MinPKernel, TemperatureKernel},
- },
- metal::Metal,
+ common::{
+ for_each_context,
+ proptest::{ComparableTestResults, TestContextes, kernel_data_type},
},
- common::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
data_type::DataType,
- session::parameter::{SamplingMethod, SamplingProcessingOrder},
+ encodable_block::Sampling,
+ prelude::SamplingMethod,
+ session::parameter::SamplingProcessingOrder,
};
-// Constant seed for reproducible test results
-const TEST_SAMPLING_SEED: u64 = 42;
-
-fn cpu_reference_min_p(
- row_logits: &[f32],
- min_p: f32,
-) -> Vec<f32> {
- let max_logit = row_logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
- let threshold = max_logit + min_p.ln();
-
- row_logits
- .iter()
- .map(|&logit| {
- if logit >= threshold {
- logit
- } else {
- f32::NEG_INFINITY
- }
- })
- .collect()
-}
-
-#[test]
-fn test_argmax_sampling() {
- let context = match <Metal as Backend>::Context::new() {
- Ok(ctx) => ctx,
- Err(e) => {
- println!("Skipping argmax test: {}", e);
- return;
- },
- };
-
- let batch_size = 2;
- let vocab_size = 4;
-
- let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
-
- // Create test data: batch_size=2, vocab_size=4
- // First batch: [1.0, 3.0, 2.0, 0.5] -> should select index 1
- // Second batch: [0.1, 0.5, 2.5, 1.0] -> should select index 2
- let test_logits: Vec<f32> = vec![
- 1.0, 3.0, 2.0, 0.5, // batch 0
- 0.1, 0.5, 2.5, 1.0, // batch 1
- ];
-
- let mut logits_buffer = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &test_logits);
- let seeds_buffer = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &[0_u64, 0_u64]);
- let mut output_buffer = alloc_allocation::<Metal, u32>(context.as_ref(), batch_size);
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- block
- .encode(
- &mut logits_buffer,
- &seeds_buffer,
- None,
- &mut output_buffer,
- SamplingMethod::Greedy,
- batch_size,
- vocab_size,
- &mut encoder,
- )
- .expect("Argmax sampling should succeed");
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- // Check results
- let results: Vec<u32> = allocation_to_vec(&output_buffer);
-
- assert_eq!(results[0], 1, "First batch should select token 1 (highest logit: 3.0)");
- assert_eq!(results[1], 2, "Second batch should select token 2 (highest logit: 2.5)");
-
- println!("✓ Argmax sampling test passed - selected tokens: {:?}", results);
-}
-
-#[test]
-#[ignore = "performance-only check"]
-fn perf_argmax_128k_vocab() {
- use std::time::Instant;
-
- use rand::{RngExt, SeedableRng, rngs::StdRng};
-
- // ---- Metal context ----
- let context = match <Metal as Backend>::Context::new() {
- Ok(ctx) => ctx,
- Err(e) => {
- println!("Skipping argmax perf test: {}", e);
- return;
- },
- };
-
- // ---- Problem sizes ----
- const BATCH: usize = 8;
- const VOCAB: usize = 128000; // 128K
-
- // ---- Kernel ----
- let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
-
- // ---- 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 mut logits_buf = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &logits);
-
- let seeds: Vec<u64> = vec![TEST_SAMPLING_SEED; BATCH];
- let seeds_buf = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &seeds);
-
- let mut output_buf = alloc_allocation::<Metal, u32>(context.as_ref(), BATCH);
-
- // ---- Launch once and time ----
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
-
- block
- .encode(
- &mut logits_buf,
- &seeds_buf,
- None::<&backend_uzu::backends::common::Allocation<Metal>>,
- &mut output_buf,
- SamplingMethod::Greedy,
- BATCH,
- VOCAB,
- &mut encoder,
- )
- .expect("encode");
-
- // Time both host-side and GPU execution
- let host_timer = Instant::now();
- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
- let host_elapsed_ms = host_timer.elapsed().as_secs_f64() * 1e3;
-
- let gpu_time_ms = completed.gpu_execution_time().as_secs_f64() * 1e3;
- println!(
- "Argmax sampling perf (batch={}, vocab={}): GPU={:.2} ms, Host-side={:.2} ms",
- BATCH, VOCAB, gpu_time_ms, host_elapsed_ms
- );
-
- // Ensure the kernel produced *some* output (sanity).
- let sample_ids: Vec<u32> = allocation_to_vec(&output_buf);
- for &tok in &sample_ids {
- assert!((tok as usize) < VOCAB, "Sampled id out of range");
- }
-
- // Also verify correctness by checking if selected tokens have highest logits
- for b in 0..BATCH {
- let row_logits = &logits[b * VOCAB..(b + 1) * VOCAB];
- let selected_token = sample_ids[b] as usize;
- let selected_logit = row_logits[selected_token];
+struct SamplingTestResults(Vec<u32>);
- // Find the actual maximum logit
- let max_logit = row_logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
+impl ComparableTestResults for SamplingTestResults {
+ fn compare(
+ backend: &str,
+ actual: &SamplingTestResults,
+ reference: &SamplingTestResults,
+ ) -> Result<(), TestCaseError> {
+ prop_assert_eq!(&actual.0, &reference.0, "{} doesn't match cpu", backend);
- assert!(
- (selected_logit - max_logit).abs() < 1e-5,
- "Batch {}: selected token {} with logit {:.6}, but max logit is {:.6}",
- b,
- selected_token,
- selected_logit,
- max_logit
- );
+ Ok(())
}
-
- println!("✓ Argmax correctness verified");
}
-#[test]
-fn test_categorical_sampling() {
- let context = match <Metal as Backend>::Context::new() {
- Ok(ctx) => ctx,
- Err(e) => {
- println!("Skipping categorical test: {}", e);
- return;
- },
- };
-
- let batch_size = 2;
- let vocab_size = 4;
-
- let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
-
- // Create test data with different probability distributions
- // First batch: [1.0, 2.0, 1.5, 0.5] -> softmax: [0.134, 0.366, 0.201, 0.082]
- // Second batch: [0.0, 1.0, 0.0, 0.0] -> softmax: [0.25, 0.75, 0.25, 0.25] (but 1.0 should dominate)
- 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 output_buffer = alloc_allocation::<Metal, u32>(context.as_ref(), batch_size);
-
- // Run sampling multiple times to check distribution
- let num_samples = 1000;
- let mut counts = vec![0; batch_size * vocab_size];
-
- for sample_idx in 0..num_samples {
- // Create fresh logits buffer since kernel mutates in-place
- let mut logits_buffer = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &test_logits);
-
- let seeds_vec = vec![TEST_SAMPLING_SEED + sample_idx as u64; batch_size];
- let seeds_buffer = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &seeds_vec);
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
-
- block
- .encode(
- &mut logits_buffer,
- &seeds_buffer,
- None,
- &mut output_buffer,
- SamplingMethod::Stochastic {
- temperature: None,
- top_k: None,
- top_p: None,
- min_p: None,
- processing_order: SamplingProcessingOrder::TemperatureThenFilters,
- },
- batch_size,
- vocab_size,
- &mut encoder,
- )
- .expect("Categorical sampling should succeed");
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- let results: Vec<u32> = allocation_to_vec(&output_buffer);
-
- 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;
- }
- }
-
- // 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, got counts: {:?}",
- batch_counts
- );
- // Token 1 should have at least 30% of the samples (due to higher logit)
- assert!(
- batch_counts[1] as f32 / num_samples as f32 > 0.3,
- "Token 1 should have at least 30% frequency, got {:.1}%",
- batch_counts[1] as f32 / num_samples as f32 * 100.0
- );
- }
- }
-
- println!("✓ Categorical sampling test passed - sampled {} times per batch", num_samples);
- println!(" Batch 0 counts: {:?}", &counts[0..vocab_size]);
- println!(" Batch 1 counts: {:?}", &counts[vocab_size..2 * vocab_size]);
-}
-
-#[test]
-fn test_categorical_sampling_statistical() {
- use rand::{RngExt, SeedableRng, rngs::StdRng};
-
- let context = match <Metal as Backend>::Context::new() {
- Ok(ctx) => ctx,
- Err(e) => {
- println!("Skipping categorical statistical test: {}", e);
- return;
- },
+fn do_sampling_backend<B: Backend, T: ArrayElement + Float>(
+ context: &B::Context,
+ logits: &[T],
+ seeds: Option<&[u64]>,
+ bitmask: Option<&[u32]>,
+ vocab_size: usize,
+ method: SamplingMethod,
+ batch_size: usize,
+) -> Result<SamplingTestResults, TestCaseError> {
+ let sampling = Sampling::new(T::data_type(), vocab_size);
+
+ let mut logits_allocation =
+ context.create_allocation(logits.len() * T::data_type().size_in_bytes(), AllocationType::Global).unwrap();
+ logits_allocation.copyin(logits);
+ let seeds_allocation = if let Some(seeds) = seeds {
+ let mut seeds_allocation = context.create_allocation(seeds.len() * 8, AllocationType::Global).unwrap();
+ seeds_allocation.copyin(seeds);
+ Some(seeds_allocation)
+ } else {
+ None
};
-
- const BATCH: usize = 4;
- const VOCAB: usize = 8;
- const NUM_SAMPLES: usize = 5000;
- const TOLERANCE: f32 = 0.05; // 5% tolerance
-
- let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
-
- // Generate random logits
- 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(-3.0f32..3.0f32);
- }
-
- // Compute expected probabilities (softmax)
- let mut expected_probs = [0.0f32; BATCH * VOCAB];
- for batch_idx in 0..BATCH {
- let batch_logits = &logits[batch_idx * VOCAB..(batch_idx + 1) * VOCAB];
- let max_logit = batch_logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
-
- let mut sum_exp = 0.0f32;
- for j in 0..VOCAB {
- let exp_val = (batch_logits[j] - max_logit).exp();
- expected_probs[batch_idx * VOCAB + j] = exp_val;
- sum_exp += exp_val;
- }
-
- // Normalize
- for j in 0..VOCAB {
- expected_probs[batch_idx * VOCAB + j] /= sum_exp;
- }
- }
-
- let mut output_buffer = alloc_allocation::<Metal, u32>(context.as_ref(), BATCH);
-
- let mut counts = [0; BATCH * VOCAB];
-
- // Sample many times
- for sample_idx in 0..NUM_SAMPLES {
- // Create fresh logits buffer since kernel mutates in-place
- let mut logits_buffer = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &logits);
-
- let seeds_vec = vec![TEST_SAMPLING_SEED + sample_idx as u64; BATCH];
- let seeds_buffer = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &seeds_vec);
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
-
- block
- .encode(
- &mut logits_buffer,
- &seeds_buffer,
- None,
- &mut output_buffer,
- SamplingMethod::Stochastic {
- temperature: None,
- top_k: None,
- top_p: None,
- min_p: None,
- processing_order: SamplingProcessingOrder::TemperatureThenFilters,
- },
- BATCH,
- VOCAB,
- &mut encoder,
- )
- .expect("encode");
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- let results: Vec<u32> = allocation_to_vec(&output_buffer);
-
- for (batch_idx, &token) in results.iter().enumerate() {
- counts[batch_idx * VOCAB + token as usize] += 1;
- }
- }
-
- // Check statistical accuracy
- for batch_idx in 0..BATCH {
- for token_idx in 0..VOCAB {
- let observed_freq = counts[batch_idx * VOCAB + token_idx] as f32 / NUM_SAMPLES as f32;
- let expected_freq = expected_probs[batch_idx * VOCAB + token_idx];
-
- if expected_freq > 0.01 {
- // Only check for tokens with reasonable probability
- let error = (observed_freq - expected_freq).abs();
- assert!(
- error < TOLERANCE,
- "Batch {}, Token {}: expected freq {:.3}, got {:.3}, error {:.3} > tolerance {:.3}",
- batch_idx,
- token_idx,
- expected_freq,
- observed_freq,
- error,
- TOLERANCE
- );
- }
- }
- }
-
- println!("✓ Categorical statistical test passed (tolerance: {:.1}%)", TOLERANCE * 100.0);
-}
-
-#[test]
-fn perf_categorical_128k_vocab() {
- use std::time::Instant;
-
- use rand::{RngExt, SeedableRng, rngs::StdRng};
-
- let context = match <Metal as Backend>::Context::new() {
- Ok(ctx) => ctx,
- Err(e) => {
- println!("Skipping categorical perf test: {}", e);
- return;
- },
+ let bitmask_allocation = if let Some(bitmask) = bitmask {
+ let mut bitmask_allocation = context.create_allocation(bitmask.len() * 4, AllocationType::Global).unwrap();
+ bitmask_allocation.copyin(bitmask);
+ Some(bitmask_allocation)
+ } else {
+ None
};
- const BATCH: usize = 8;
- const VOCAB: usize = 128000; // 128K
-
- let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
-
- // 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 mut logits_buf = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &logits);
-
- let seeds: Vec<u64> = vec![TEST_SAMPLING_SEED; BATCH];
- let seeds_buf = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &seeds);
-
- let mut output_buf = alloc_allocation::<Metal, u32>(context.as_ref(), BATCH);
-
- // Launch and time
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
-
- block
+ let mut encoder = Encoder::new(context).unwrap();
+ let sampled_allocation = sampling
.encode(
- &mut logits_buf,
- &seeds_buf,
- None,
- &mut output_buf,
- SamplingMethod::Stochastic {
- temperature: None,
- top_k: None,
- top_p: None,
- min_p: None,
- processing_order: SamplingProcessingOrder::TemperatureThenFilters,
- },
- BATCH,
- VOCAB,
+ &logits_allocation,
+ seeds_allocation.as_ref(),
+ bitmask_allocation.as_ref(),
+ method,
+ batch_size,
&mut encoder,
)
- .expect("encode");
-
- let host_timer = Instant::now();
- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
- let host_elapsed_ms = host_timer.elapsed().as_secs_f64() * 1e3;
-
- let gpu_time_ms = completed.gpu_execution_time().as_secs_f64() * 1e3;
- println!(
- "Categorical sampling perf (batch={}, vocab={}): GPU={:.2} ms, Host-side={:.2} ms",
- BATCH, VOCAB, gpu_time_ms, host_elapsed_ms
- );
-
- // Sanity check
- let sample_ids: Vec<u32> = allocation_to_vec(&output_buf);
- for &tok in &sample_ids {
- assert!((tok as usize) < VOCAB, "Sampled id out of range");
- }
-
- println!("✓ Categorical correctness verified");
-}
-
-#[test]
-fn test_temperature_gpu_cpu_match() {
- let context = match <Metal as Backend>::Context::new() {
- Ok(ctx) => ctx,
- Err(e) => {
- println!("Skipping temperature gpu cpu match test: {}", e);
- return;
- },
- };
-
- 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 = <<Metal as Backend>::Kernels as Kernels>::TemperatureKernel::new(&context, DataType::F32, false)
- .expect("Failed to create temperature kernel");
-
- let logits: Vec<f32> = (0..BATCH * VOCAB).map(|i| ((i * 37 % 1000) as f32 - 500.0) * 0.01).collect();
-
- let logits_buffer = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &logits);
- let mut processed_buffer = alloc_allocation::<Metal, f32>(context.as_ref(), logits.len());
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(Some(&logits_buffer), &mut processed_buffer, BATCH as u32, VOCAB as u32, TEMPERATURE, &mut encoder);
+ .unwrap();
encoder.end_encoding().submit().wait_until_completed().unwrap();
- let gpu_results: Vec<f32> = allocation_to_vec(&processed_buffer);
+ let sampled = sampled_allocation.copyout::<u32>();
- 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
- );
- }
-
- println!("✓ Temperature processor gpu cpu match (temp={}, rtol={}, atol={})", TEMPERATURE, RTOL, ATOL);
+ Ok(SamplingTestResults(sampled))
}
-#[test]
-fn test_minp_gpu_cpu_match() {
- use rand::{RngExt, SeedableRng, rngs::StdRng};
-
- let context = match <Metal as Backend>::Context::new() {
- Ok(ctx) => ctx,
- Err(e) => {
- println!("Skipping minp gpu cpu match test: {}", e);
- return;
- },
- };
-
- const BATCH: usize = 4;
- const VOCAB: usize = 1024;
- const MINP: f32 = 0.1;
-
- let kernel = <<Metal as Backend>::Kernels as Kernels>::MinPKernel::new(&context, DataType::F32, false)
- .expect("Failed to create minp kernel");
-
- 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 = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &logits);
- let mut processed_buffer = alloc_allocation::<Metal, f32>(context.as_ref(), logits.len());
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(Some(&logits_buffer), &mut processed_buffer, BATCH as u32, VOCAB as u32, MINP, &mut encoder);
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- let all_results: Vec<f32> = allocation_to_vec(&processed_buffer);
-
- for batch_idx in 0..BATCH {
- let cpu_logits = &logits[batch_idx * VOCAB..(batch_idx + 1) * VOCAB];
- let cpu_processed_logits = cpu_reference_min_p(cpu_logits, MINP);
-
- let gpu_processed_logits = &all_results[batch_idx * VOCAB..(batch_idx + 1) * VOCAB];
-
- assert_eq!(&cpu_processed_logits, gpu_processed_logits);
- }
-
- println!("✓ Minp processor gpu cpu match (minp={})", MINP);
-}
-
-fn test_minp_sampling_exact_match(
+fn get_data<T: ArrayElement + Float>(
+ seed: u64,
batch_size: usize,
- min_p: f32,
vocab_size: usize,
-) {
- use std::collections::HashSet;
-
- use rand::{SeedableRng, rngs::StdRng};
-
- let context = match <Metal as Backend>::Context::new() {
- Ok(ctx) => ctx,
- Err(e) => {
- eprintln!("Skipping minp exact match test: {}", e);
- return;
- },
- };
-
- let block = SamplingBlock::<Metal>::new(&context, DataType::F32).expect("Failed to create sampling block");
-
- // Build logits where some tokens have high probability and others have low
- // For min_p filtering, tokens with probability < min_p * max_prob are masked
- // We set k tokens to have probability 0.1 each (high), rest get very low probability
- let k = 10;
- let high_logit = 0.0f32; // exp(0) = 1
- let low_logit = -50.0f32; // exp(-50) ≈ 0
-
- let mut logits = vec![low_logit; batch_size * vocab_size];
- let mut high_prob_token_sets: Vec<HashSet<usize>> = Vec::with_capacity(batch_size);
-
- let mut rng = StdRng::seed_from_u64(42);
- let mut all_token_ids: Vec<usize> = (0..vocab_size).collect();
-
- for b in 0..batch_size {
- all_token_ids.shuffle(&mut rng);
- let high_prob_tokens: HashSet<usize> = all_token_ids[..k].iter().cloned().collect();
-
- for &token_id in &high_prob_tokens {
- logits[b * vocab_size + token_id] = high_logit;
+ bitmask: bool,
+ stochastic: bool,
+) -> (Box<[T]>, Option<Box<[u64]>>, Option<Box<[u32]>>) {
+ let mut rng = SmallRng::seed_from_u64(seed);
+ let mean = rng.random_range(-100.0..100.0);
+ let std_dev = rng.random_range(24.0..64.0);
+
+ let distribution: Normal<f32> = Normal::new(mean, std_dev).unwrap();
+ let mut logits: Box<[MaybeUninit<T>]> = Box::new_uninit_slice(batch_size * vocab_size);
+ for logit in logits.iter_mut() {
+ logit.write(<T as NumCast>::from(rng.sample(distribution)).unwrap());
+ }
+
+ let seeds = stochastic.then(|| repeat_with(|| rng.random::<u64>()).take(batch_size).collect());
+ let bitmask = bitmask.then(|| {
+ let bitmask_size = vocab_size.div_ceil(u32::BITS as usize);
+ let mut bitmask: Box<[MaybeUninit<u32>]> = Box::new_uninit_slice(batch_size * bitmask_size);
+ for entry in bitmask.iter_mut() {
+ entry.write(rng.random::<u32>());
}
- high_prob_token_sets.push(high_prob_tokens);
- }
-
- let mut output_buf = alloc_allocation::<Metal, u32>(context.as_ref(), batch_size);
-
- let num_samples = 1000;
- let mut counter = vec![0i32; batch_size * vocab_size];
+ unsafe { bitmask.assume_init() }
+ });
- for draw in 0..num_samples {
- // Create fresh logits buffer since kernel mutates in-place
- let mut logits_buf = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &logits);
+ (unsafe { logits.assume_init() }, seeds, bitmask)
+}
- let seeds: Vec<u64> = vec![TEST_SAMPLING_SEED + draw as u64; batch_size];
- let seeds_buf = alloc_allocation_with_data::<Metal, _>(context.as_ref(), &seeds);
+#[derive(Debug, Clone)]
+struct SamplingCase {
+ data_type: DataType,
+ seed: u64,
+ batch_size: usize,
+ vocab_size: usize,
+ bitmask: bool,
+ method: SamplingMethod,
+}
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- block
- .encode(
- &mut logits_buf,
- &seeds_buf,
- None,
- &mut output_buf,
- SamplingMethod::Stochastic {
- temperature: None,
- top_k: None,
- top_p: None,
- min_p: Some(min_p),
- processing_order: SamplingProcessingOrder::TemperatureThenFilters,
- },
+fn sampling_case() -> impl Strategy<Value = SamplingCase> {
+ (kernel_data_type(), any::<u64>().no_shrink(), 1usize..=7, 1usize..=123456, any::<bool>()).prop_flat_map(
+ |(data_type, seed, batch_size, vocab_size, bitmask)| {
+ let temperature = prop_oneof![Just(None), (0.05f32..=4.0).prop_map(Some),];
+
+ let top_k = prop_oneof![Just(None), (1u32..=vocab_size as u32).prop_map(Some),];
+
+ let top_p = prop_oneof![Just(None), (0.01f32..=1.0).prop_map(Some),];
+
+ let min_p = prop_oneof![Just(None), (0.0f32..=1.0).prop_map(Some),];
+
+ let order = prop_oneof![
+ Just(SamplingProcessingOrder::TemperatureThenFilters),
+ Just(SamplingProcessingOrder::FiltersThenTemperature),
+ ];
+
+ prop_oneof![
+ Just(SamplingMethod::Greedy),
+ (temperature, top_k, top_p, min_p, order).prop_map(
+ |(temperature, top_k, top_p, min_p, processing_order)| {
+ SamplingMethod::Stochastic {
+ temperature,
+ top_k,
+ top_p,
+ min_p,
+ processing_order,
+ }
+ },
+ ),
+ ]
+ .prop_map(move |method| SamplingCase {
+ data_type,
+ seed,
batch_size,
vocab_size,
- &mut encoder,
- )
- .expect("encode");
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- let sampled_ids: Vec<u32> = allocation_to_vec(&output_buf);
-
- for (i, &sampled_id) in sampled_ids.iter().enumerate() {
- assert!((sampled_id as usize) < vocab_size, "Sampled token out of range");
- counter[i * vocab_size + sampled_id as usize] += 1;
- }
- }
-
- for i in 0..batch_size {
- for j in 0..vocab_size {
- if counter[i * vocab_size + j] > 0 {
- assert!(
- high_prob_token_sets[i].contains(&j),
- "high_prob_token_sets[{}] does not contain {} (appeared {} times)",
- i,
- j,
- counter[i * vocab_size + j]
- );
- }
- }
- }
-
- println!("batch_size: {}, min_p: {:.2}, vocab_size: {}, accuracy test passed.", batch_size, min_p, vocab_size);
-}
-
-#[test]
-fn test_minp_sampling_match_small() {
- test_minp_sampling_exact_match(8, 0.1, 1024);
+ bitmask,
+ method,
+ })
+ },
+ )
}
#[test]
-fn test_minp_sampling_match_large() {
- test_minp_sampling_exact_match(32, 0.05, 4096);
+fn test_sampling_prop() {
+ let contextes = TestContextes::new();
+
+ proptest!(|(sampling_case in sampling_case())| {
+ dispatch_dtype!(|(T: sampling_case.data_type)| {
+ let (logits, seeds, bitmask) = get_data(sampling_case.seed, sampling_case.batch_size, sampling_case.vocab_size, sampling_case.bitmask, matches!(sampling_case.method, SamplingMethod::Stochastic { .. }));
+
+ for_each_context!(contextes, |context: C| do_sampling_backend::<<C as Context>::Backend, T>(
+ context,
+ logits.as_ref(),
+ seeds.as_ref().map(Box::as_ref),
+ bitmask.as_ref().map(Box::as_ref),
+ sampling_case.vocab_size,
+ sampling_case.method,
+ sampling_case.batch_size,
+ ))
+ .compare_results()?
+ });
+ });
}
diff --git a/crates/backend-uzu/tests/unit/encodable_block/sampling_top_p_test.rs b/crates/backend-uzu/tests/unit/encodable_block/sampling_top_p_test.rs
deleted file mode 100644
index 33ac4f994..000000000
--- a/crates/backend-uzu/tests/unit/encodable_block/sampling_top_p_test.rs
+++ /dev/null
@@ -1,491 +0,0 @@
-use std::{
- collections::HashSet,
- fmt::{Debug, Display},
-};
-
-use backend_uzu::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{AllocationType, Backend, Context, Encoder, Kernels, kernel::TopPKernel},
- cpu::Cpu,
- },
- data_type::DataType,
- session::parameter::{SamplingMethod, SamplingProcessingOrder},
-};
-use half::{bf16, f16};
-use num_traits::Float;
-use rand::{RngExt, SeedableRng, rngs::StdRng, seq::SliceRandom};
-
-use super::SamplingBlock;
-use crate::common::helpers::{alloc_allocation_with_data, allocation_to_vec};
-
-const TEST_SAMPLING_SEED: u64 = 42;
-
-struct Input<T: ArrayElement + Float> {
- logits: Box<[T]>,
- batch_size: u32,
- vocab_size: u32,
- top_p: f32,
- in_place: bool,
-}
-
-fn get_test_data<T: ArrayElement + Float>(
- batch_size: u32,
- vocab_size: u32,
- top_p: f32,
- in_place: bool,
-) -> (Input<T>, Vec<T>) {
- let len = (batch_size * vocab_size) as usize;
- let mut rng = StdRng::seed_from_u64(42);
- let mut logits: Vec<T> = vec![T::zero(); len];
- for x in logits.iter_mut() {
- *x = T::from(rng.random_range(-16.0f32..16.0f32)).unwrap();
- }
-
- let input = Input {
- logits: logits.into_boxed_slice(),
- batch_size,
- vocab_size,
- top_p,
- in_place,
- };
-
- let expected = get_output::<T, Cpu>(&input);
-
- (input, expected)
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
- let context = <B as Backend>::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::TopPKernel::new(&context, T::data_type(), input.in_place)
- .expect("Failed to create TopPKernel");
-
- let len = (input.batch_size * input.vocab_size) as usize;
- let logits_buffer = (!input.in_place).then(|| context.create_array_from(&[len], &input.logits).into_allocation());
- let mut output = match input.in_place {
- true => context.create_array_from(&[len], &input.logits).into_allocation(),
- false => context.create_array_uninitialized(&[len], T::data_type()).into_allocation(),
- };
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(logits_buffer.as_ref(), &mut output, input.batch_size, input.vocab_size, input.top_p, &mut encoder);
-
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- allocation_to_vec(&output)
-}
-
-fn assert_top_p_equal<T: ArrayElement + Float + Display>(
- expected: &[T],
- actual: &[T],
- vocab_size: u32,
- eps: f32,
- msg: &str,
-) {
- assert_eq!(expected.len(), actual.len(), "Slices size mismatch");
- let vocab_size = vocab_size as usize;
- let num_batches = expected.len() / vocab_size;
-
- for batch_idx in 0..num_batches {
- let start = batch_idx * vocab_size;
- let end = start + vocab_size;
-
- let expected_kept: usize = expected[start..end].iter().filter(|v| v.is_finite()).count();
- let actual_kept: usize = actual[start..end].iter().filter(|v| v.is_finite()).count();
-
- // Allow small differences due to binary search convergence
- let diff = (expected_kept as i64 - actual_kept as i64).unsigned_abs();
- assert!(diff <= 3, "{msg}. Batch {batch_idx}: expected {expected_kept} kept values, got {actual_kept}");
-
- // For values that are kept by both, they should match the original values
- for i in start..end {
- let e = expected[i].to_f32().unwrap();
- let a = actual[i].to_f32().unwrap();
- if e.is_finite() && a.is_finite() {
- let d = (e - a).abs();
- assert!(d < eps, "{msg}. Mismatch at index {i}: expected {e}, got {a}, diff {d}");
- }
- }
- }
-}
-
-fn test_internal<T: ArrayElement + Float + Debug + Display>(
- batch_size: u32,
- vocab_size: u32,
- top_p: f32,
- in_place: bool,
-) {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 1e-2
- } else {
- 1e-5
- };
-
- let (input, expected) = get_test_data::<T>(batch_size, vocab_size, top_p, in_place);
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- let msg = format!("Results are not equal for backend {}", std::any::type_name::<B>());
- assert_top_p_equal::<T>(&expected, &output, vocab_size, eps, &msg);
- });
-}
-
-// Out-of-place tests (same data as sampling_test::test_topp_gpu_cpu_match)
-#[test]
-fn test_f32() {
- test_internal::<f32>(4, 1024, 0.9, false);
-}
-
-#[test]
-fn test_f16() {
- test_internal::<f16>(4, 1024, 0.9, false);
-}
-
-#[test]
-fn test_bf16() {
- test_internal::<bf16>(4, 1024, 0.9, false);
-}
-
-// In-place tests
-#[test]
-fn test_in_place_f32() {
- test_internal::<f32>(4, 1024, 0.9, true);
-}
-
-#[test]
-fn test_in_place_f16() {
- test_internal::<f16>(4, 1024, 0.9, true);
-}
-
-#[test]
-fn test_in_place_bf16() {
- test_internal::<bf16>(4, 1024, 0.9, true);
-}
-
-// Edge cases
-#[test]
-fn test_single_batch_f32() {
- test_internal::<f32>(1, 1024, 0.9, false);
-}
-
-#[test]
-fn test_top_p_very_small() {
- test_internal::<f32>(4, 1024, 0.01, false);
-}
-
-#[test]
-fn test_top_p_near_1() {
- test_internal::<f32>(4, 1024, 0.99, false);
-}
-
-// --- Sampling-level top-p tests (test the full SamplingBlock with top_p) ---
-
-fn cpu_reference_top_p(
- row_logits: &[f32],
- top_p: f32,
-) -> Vec<f32> {
- let max_logit = row_logits.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
- let exp_vals: Vec<f32> = row_logits.iter().map(|&x| (x - max_logit).exp()).collect();
- let sum_exp: f32 = exp_vals.iter().sum();
- let probs: Vec<f32> = exp_vals.iter().map(|&x| x / sum_exp).collect();
-
- let mut indexed: Vec<(usize, f32)> = probs.iter().copied().enumerate().collect();
- indexed.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
-
- let mut cum = 0.0f32;
- let mut keep = vec![false; row_logits.len()];
- for &(idx, p) in &indexed {
- if cum >= top_p {
- break;
- }
- keep[idx] = true;
- cum += p;
- }
-
- // Renormalise kept probabilities
- let kept_sum: f32 = probs.iter().zip(keep.iter()).filter(|&(_, &k)| k).map(|(&p, _)| p).sum();
- probs
- .iter()
- .zip(keep.iter())
- .map(|(&p, &k)| {
- if k {
- p / kept_sum
- } else {
- 0.0
- }
- })
- .collect()
-}
-
-fn test_topp_sampling_from_prob_exact_match_internal<B: Backend>(
- batch_size: usize,
- k: usize,
- vocab_size: usize,
-) {
- let context = <B as Backend>::Context::new().expect("Failed to create Context");
-
- let p = (k as f32) * 0.1;
-
- let block = SamplingBlock::<B>::new(&context, DataType::F32).expect("Failed to create sampling block");
-
- // Build probability table
- let low_prob = (1.0 - p) / (vocab_size - k) as f32;
- let mut probs = vec![low_prob; batch_size * vocab_size];
- let mut high_prob_token_sets: Vec<HashSet<usize>> = Vec::with_capacity(batch_size);
-
- let mut rng = StdRng::seed_from_u64(42);
- let mut all_token_ids: Vec<usize> = (0..vocab_size).collect();
-
- for b in 0..batch_size {
- all_token_ids.shuffle(&mut rng);
- let high_prob_tokens: HashSet<usize> = all_token_ids[..k].iter().cloned().collect();
-
- for &token_id in &high_prob_tokens {
- probs[b * vocab_size + token_id] = 0.1;
- }
- high_prob_token_sets.push(high_prob_tokens);
- }
-
- let logits: Vec<f32> = probs
- .iter()
- .map(|&prob| {
- if prob <= 0.0 {
- -50.0
- } else {
- prob.ln()
- }
- })
- .collect();
-
- let mut output_allocation = context
- .create_allocation(batch_size * std::mem::size_of::<u32>(), AllocationType::Global)
- .expect("Failed to create allocation");
-
- let num_samples = 1000;
- let mut counter = vec![0i32; batch_size * vocab_size];
-
- for draw in 0..num_samples {
- let seeds: Vec<u64> = vec![TEST_SAMPLING_SEED + draw as u64; batch_size];
- let mut logits_allocation = alloc_allocation_with_data::<B, f32>(&context, &logits);
- let seeds_allocation = alloc_allocation_with_data::<B, u64>(&context, &seeds);
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- block
- .encode(
- &mut logits_allocation,
- &seeds_allocation,
- None,
- &mut output_allocation,
- SamplingMethod::Stochastic {
- temperature: None,
- top_k: None,
- top_p: Some(p),
- min_p: None,
- processing_order: SamplingProcessingOrder::TemperatureThenFilters,
- },
- batch_size,
- vocab_size,
- &mut encoder,
- )
- .expect("encode");
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- let sampled_ids = allocation_to_vec::<B, u32>(&output_allocation);
-
- for (i, &sampled_id) in sampled_ids.iter().enumerate() {
- assert!((sampled_id as usize) < vocab_size, "Sampled token out of range");
- counter[i * vocab_size + sampled_id as usize] += 1;
- }
- }
-
- for i in 0..batch_size {
- for j in 0..vocab_size {
- if counter[i * vocab_size + j] > 0 {
- assert!(
- high_prob_token_sets[i].contains(&j),
- "high_prob_token_sets[{}] does not contain {} (appeared {} times)",
- i,
- j,
- counter[i * vocab_size + j]
- );
- }
- }
- }
-
- println!(
- "batch_size: {}, p: {:.1}, vocab_size: {}, accuracy test passed (backend: {}).",
- batch_size,
- p,
- vocab_size,
- std::any::type_name::<B>()
- );
-}
-
-#[test]
-fn test_topp_sampling_match_small() {
- for_each_non_cpu_backend!(|B| {
- test_topp_sampling_from_prob_exact_match_internal::<B>(8, 10, 1024);
- });
-}
-
-#[test]
-fn test_topp_sampling_match_large() {
- for_each_non_cpu_backend!(|B| {
- test_topp_sampling_from_prob_exact_match_internal::<B>(32, 50, 4096);
- });
-}
-
-#[test]
-fn test_topp_sampling_statistical_large() {
- for_each_non_cpu_backend!(|B| {
- const BATCH: usize = 32;
- const VOCAB: usize = 4096;
- const NUM_DRAWS: usize = 10_000;
- const TOP_P: f32 = 0.9;
- const TOLERANCE_KL: f32 = 0.05;
-
- let context = <B as Backend>::Context::new().expect("Failed to create Context");
-
- let block = SamplingBlock::<B>::new(&context, DataType::F32).expect("Failed to create sampling block");
-
- 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(-6.0f32..6.0f32);
- }
-
- // Build Top-p renormalised target distribution per row
- let mut probs = vec![0.0f32; BATCH * VOCAB];
- for b in 0..BATCH {
- let row_logits = &logits[b * VOCAB..(b + 1) * VOCAB];
- let dist = cpu_reference_top_p(row_logits, TOP_P);
- probs[b * VOCAB..(b + 1) * VOCAB].copy_from_slice(&dist);
- }
-
- let mut output_allocation = context
- .create_allocation(BATCH * std::mem::size_of::<u32>(), AllocationType::Global)
- .expect("Failed to create allocation");
- let mut counters = vec![0u32; BATCH * VOCAB];
-
- for draw in 0..NUM_DRAWS {
- let seeds: Vec<u64> = vec![TEST_SAMPLING_SEED + draw as u64; BATCH];
- let mut logits_allocation = alloc_allocation_with_data::<B, f32>(&context, &logits);
- let seeds_allocation = alloc_allocation_with_data::<B, u64>(&context, &seeds);
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
-
- block
- .encode(
- &mut logits_allocation,
- &seeds_allocation,
- None,
- &mut output_allocation,
- SamplingMethod::Stochastic {
- temperature: None,
- top_k: None,
- top_p: Some(TOP_P),
- min_p: None,
- processing_order: SamplingProcessingOrder::TemperatureThenFilters,
- },
- BATCH,
- VOCAB,
- &mut encoder,
- )
- .expect("encode");
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- let sample_ids = allocation_to_vec::<B, u32>(&output_allocation);
- for (b, &tok) in sample_ids.iter().enumerate() {
- counters[b * VOCAB + tok as usize] += 1;
- }
- }
-
- // Compute KL divergence per row
- for b in 0..BATCH {
- let mut kl = 0.0_f32;
- for j in 0..VOCAB {
- let expected = probs[b * VOCAB + j];
- if expected < 1e-12 {
- continue;
- }
- let observed = (counters[b * VOCAB + j] as f32) / (NUM_DRAWS as f32);
- if observed > 0.0 {
- kl += observed * (observed.ln() - expected.ln());
- }
- }
- assert!(kl < TOLERANCE_KL, "Row {} KL {:.4} exceeded tolerance {:.3}", b, kl, TOLERANCE_KL);
- }
-
- println!(
- "Large statistical Top-p test passed (KL < {:.3}, backend: {})",
- TOLERANCE_KL,
- std::any::type_name::<B>()
- );
- });
-}
-
-#[test]
-fn perf_topp_128k_vocab() {
- for_each_non_cpu_backend!(|B| {
- const BATCH: usize = 8;
- const VOCAB: usize = 128000;
- const TOP_P: f32 = 0.9;
-
- let context = <B as Backend>::Context::new().expect("Failed to create Context");
-
- let block = SamplingBlock::<B>::new(&context, DataType::F32).expect("Failed to create sampling block");
-
- 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 seeds: Vec<u64> = vec![TEST_SAMPLING_SEED; BATCH];
- let mut logits_allocation = alloc_allocation_with_data::<B, f32>(&context, &logits);
- let seeds_allocation = alloc_allocation_with_data::<B, u64>(&context, &seeds);
- let mut output_allocation = context
- .create_allocation(BATCH * std::mem::size_of::<u32>(), AllocationType::Global)
- .expect("Failed to create allocation");
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
-
- block
- .encode(
- &mut logits_allocation,
- &seeds_allocation,
- None,
- &mut output_allocation,
- SamplingMethod::Stochastic {
- temperature: None,
- top_k: None,
- top_p: Some(TOP_P),
- min_p: None,
- processing_order: SamplingProcessingOrder::TemperatureThenFilters,
- },
- BATCH,
- VOCAB,
- &mut encoder,
- )
- .expect("encode");
-
- let host_timer = std::time::Instant::now();
- let completed = encoder.end_encoding().submit().wait_until_completed().unwrap();
- let host_elapsed_ms = host_timer.elapsed().as_secs_f64() * 1e3;
-
- let gpu_time_ms = completed.gpu_execution_time().as_secs_f64() * 1e3;
- println!(
- "Top-p sampling perf (batch={}, vocab={}, backend={}): GPU={:.2} ms, Host-side={:.2} ms",
- BATCH,
- VOCAB,
- std::any::type_name::<B>(),
- gpu_time_ms,
- host_elapsed_ms
- );
-
- let sample_ids = allocation_to_vec::<B, u32>(&output_allocation);
- for tok in sample_ids {
- assert!((tok as usize) < VOCAB, "Sampled id out of range");
- }
- });
-}
diff --git a/crates/backend-uzu/tests/unit/kernel/mod.rs b/crates/backend-uzu/tests/unit/kernel/mod.rs
index 7e9bdfff2..18b7fd962 100644
--- a/crates/backend-uzu/tests/unit/kernel/mod.rs
+++ b/crates/backend-uzu/tests/unit/kernel/mod.rs
@@ -15,7 +15,6 @@ mod qk_unpack_test;
mod qkv_norm_test;
mod rms_norm_test;
mod rope_test;
-mod sampling;
mod short_conv;
mod ssm;
mod tensor_add_bias_test;
diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/argmax_test_old.rs b/crates/backend-uzu/tests/unit/kernel/sampling/argmax_test_old.rs
deleted file mode 100644
index 120c214db..000000000
--- a/crates/backend-uzu/tests/unit/kernel/sampling/argmax_test_old.rs
+++ /dev/null
@@ -1,192 +0,0 @@
-use std::{fmt::Display, mem::size_of};
-
-use backend_uzu::{
- array::{ArrayContextExt, ArrayElement},
- backends::common::{
- Backend, Context, Encoder, Kernels,
- gpu_types::ArgmaxPair,
- kernel::{ArgmaxFinalKernel, ArgmaxMainKernel, ArgmaxSingleKernel},
- },
- data_type::DataType,
-};
-use half::{bf16, f16};
-use num_traits::Float;
-
-use crate::uzu_test;
-
-struct Input<T: ArrayElement + Float> {
- logits: Box<[T]>,
- batch_size: u32,
- vocab_size: u32,
-}
-
-fn reference_argmax<T: ArrayElement + Float>(input: &Input<T>) -> Vec<u32> {
- let mut tokens = vec![0u32; input.batch_size as usize];
- for batch_idx in 0..input.batch_size as usize {
- let mut best_value = f32::NEG_INFINITY;
- let mut best_index = u32::MAX;
- for vocab_idx in 0..input.vocab_size as usize {
- let global_idx = batch_idx * input.vocab_size as usize + vocab_idx;
- let value = input.logits[global_idx].to_f32().unwrap();
- if value > best_value || (value == best_value && (vocab_idx as u32) < best_index) {
- best_value = value;
- best_index = vocab_idx as u32;
- }
- }
- tokens[batch_idx] = best_index;
- }
- tokens
-}
-
-fn get_test_data<T: ArrayElement + Float>(
- batch_size: u32,
- vocab_size: u32,
-) -> (Input<T>, Vec<u32>) {
- let len = (batch_size * vocab_size) as usize;
- let mut logits: Vec<T> = vec![T::zero(); len];
- for i in 0..len {
- logits[i] = T::from((i as f32 * 0.1).sin() * 10.0f32).unwrap();
- }
-
- let input = Input {
- logits: logits.into_boxed_slice(),
- batch_size,
- vocab_size,
- };
-
- let expected = reference_argmax(&input);
-
- (input, expected)
-}
-
-fn get_output_single<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<u32> {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::ArgmaxSingleKernel::new(&context, T::data_type())
- .expect("Failed to create ArgmaxSingleKernel");
-
- let len = (input.batch_size * input.vocab_size) as usize;
- let logits_array = context.create_array_from(&[len], &input.logits);
- let mut output = context.create_array_uninitialized(&[input.batch_size as usize], DataType::U32).into_allocation();
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(logits_array.allocation(), &mut output, input.batch_size, input.vocab_size, &mut encoder);
-
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- crate::common::helpers::allocation_to_vec(&output)
-}
-
-fn get_output_two_pass<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<u32> {
- let context = B::Context::new().expect("Failed to create Context");
-
- let main_kernel = <<B as Backend>::Kernels as Kernels>::ArgmaxMainKernel::new(&context, T::data_type())
- .expect("Failed to create ArgmaxMainKernel");
- let final_kernel = <<B as Backend>::Kernels as Kernels>::ArgmaxFinalKernel::new(&context)
- .expect("Failed to create ArgmaxFinalKernel");
-
- let len = (input.batch_size * input.vocab_size) as usize;
- let logits_array = context.create_array_from(&[len], &input.logits);
- let mut output = context.create_array_uninitialized(&[input.batch_size as usize], DataType::U32).into_allocation();
-
- let block_size = 1024;
- let grain_size = 4;
- let elements_per_group = block_size * grain_size;
- let vocab_groups_per_batch = (input.vocab_size as usize).div_ceil(elements_per_group);
- let partial_results_count = input.batch_size as usize * vocab_groups_per_batch;
- let mut partial_results = context
- .create_array_uninitialized(&[partial_results_count * size_of::<ArgmaxPair>()], DataType::U8)
- .into_allocation();
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- main_kernel.encode(
- logits_array.allocation(),
- &mut partial_results,
- input.batch_size,
- input.vocab_size,
- &mut encoder,
- );
- final_kernel.encode(&partial_results, &mut output, input.batch_size, input.vocab_size, &mut encoder);
-
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- crate::common::helpers::allocation_to_vec(&output)
-}
-
-fn test_single_pass<T: ArrayElement + Float + Display>(
- batch_size: u32,
- vocab_size: u32,
-) {
- let (input, expected) = get_test_data::<T>(batch_size, vocab_size);
- for_each_backend!(|B| {
- let output = get_output_single::<T, B>(&input);
- assert_eq!(output, expected, "Single-pass output does not match for backend {}", std::any::type_name::<B>());
- });
-}
-
-fn test_two_pass<T: ArrayElement + Float + Display>(
- batch_size: u32,
- vocab_size: u32,
-) {
- let (input, expected) = get_test_data::<T>(batch_size, vocab_size);
- for_each_backend!(|B| {
- let output = get_output_two_pass::<T, B>(&input);
- assert_eq!(output, expected, "Two-pass output does not match for backend {}", std::any::type_name::<B>());
- });
-}
-
-// Single-pass tests
-#[uzu_test]
-fn test_single_pass_f32() {
- test_single_pass::<f32>(4, 1024);
-}
-
-#[uzu_test]
-fn test_single_pass_f16() {
- test_single_pass::<f16>(4, 1024);
-}
-
-#[uzu_test]
-fn test_single_pass_bf16() {
- test_single_pass::<bf16>(4, 1024);
-}
-
-// Two-pass tests
-#[uzu_test]
-fn test_two_pass_f32() {
- test_two_pass::<f32>(4, 1024);
-}
-
-#[uzu_test]
-fn test_two_pass_f16() {
- test_two_pass::<f16>(4, 1024);
-}
-
-#[uzu_test]
-fn test_two_pass_bf16() {
- test_two_pass::<bf16>(4, 1024);
-}
-
-// Large vocab tests (exercises multi-group reduction)
-#[uzu_test]
-fn test_single_pass_large_vocab_f32() {
- test_single_pass::<f32>(4, 128 * 1024);
-}
-
-#[uzu_test]
-fn test_two_pass_large_vocab_f32() {
- test_two_pass::<f32>(4, 128 * 1024);
-}
-
-// Edge cases
-#[uzu_test]
-fn test_single_batch_f32() {
- test_single_pass::<f32>(1, 1024);
- test_two_pass::<f32>(1, 1024);
-}
-
-#[uzu_test]
-fn test_small_vocab_f32() {
- test_single_pass::<f32>(4, 4);
- test_two_pass::<f32>(4, 4);
-}
diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/bitmask_test.rs b/crates/backend-uzu/tests/unit/kernel/sampling/bitmask_test.rs
deleted file mode 100644
index 72ebfef3a..000000000
--- a/crates/backend-uzu/tests/unit/kernel/sampling/bitmask_test.rs
+++ /dev/null
@@ -1,293 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use backend_uzu::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Backend, Context, Encoder, Kernels, kernel::BitmaskKernel},
- cpu::Cpu,
- },
- data_type::DataType,
-};
-use half::{bf16, f16};
-use num_traits::Float;
-
-use crate::{common::assert::assert_eq_float, uzu_test};
-
-struct Input<T: ArrayElement + Float> {
- logits: Box<[T]>,
- bitmask: Box<[u32]>,
- batch_size: u32,
- vocab_size: u32,
- in_place: bool,
-}
-
-fn get_test_data_basic<T: ArrayElement + Float>(in_place: bool) -> (Input<T>, Vec<T>) {
- let batch_size = 2u32;
- let vocab_size = 128u32;
-
- let len = (batch_size * vocab_size) as usize;
- let logits: Vec<T> = (0..len).map(|i| T::from((i as f32 * 0.1).sin() * 2.0).unwrap()).collect();
-
- let bitmask_size = vocab_size.div_ceil(32) as usize;
- let mut bitmask = vec![0u32; batch_size as usize * bitmask_size];
- // Allow every other token
- for b in 0..batch_size as usize {
- for word in 0..bitmask_size {
- bitmask[b * bitmask_size + word] = 0x55555555; // bits 0,2,4,...
- }
- }
-
- let input = Input {
- logits: logits.into_boxed_slice(),
- bitmask: bitmask.into_boxed_slice(),
- batch_size,
- vocab_size,
- in_place,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_test_data_all_allowed<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {
- let batch_size = 1u32;
- let vocab_size = 64u32;
-
- let len = (batch_size * vocab_size) as usize;
- let logits: Vec<T> = (0..len).map(|i| T::from(i as f32 * 0.5).unwrap()).collect();
-
- let bitmask_size = vocab_size.div_ceil(32) as usize;
- let bitmask = vec![0xFFFFFFFFu32; batch_size as usize * bitmask_size];
-
- let input = Input {
- logits: logits.into_boxed_slice(),
- bitmask: bitmask.into_boxed_slice(),
- batch_size,
- vocab_size,
- in_place: false,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_test_data_none_allowed<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {
- let batch_size = 1u32;
- let vocab_size = 64u32;
-
- let len = (batch_size * vocab_size) as usize;
- let logits: Vec<T> = (0..len).map(|i| T::from(i as f32 * 0.5).unwrap()).collect();
-
- let bitmask_size = vocab_size.div_ceil(32) as usize;
- let bitmask = vec![0u32; batch_size as usize * bitmask_size];
-
- let input = Input {
- logits: logits.into_boxed_slice(),
- bitmask: bitmask.into_boxed_slice(),
- batch_size,
- vocab_size,
- in_place: false,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_test_data_non_aligned<T: ArrayElement + Float>() -> (Input<T>, Vec<T>) {
- // vocab_size not a multiple of 32
- let batch_size = 2u32;
- let vocab_size = 100u32;
-
- let len = (batch_size * vocab_size) as usize;
- let logits: Vec<T> = (0..len).map(|i| T::from((i as f32 * 0.3).cos() * 3.0).unwrap()).collect();
-
- let bitmask_size = vocab_size.div_ceil(32) as usize;
- let mut bitmask = vec![0u32; batch_size as usize * bitmask_size];
- // Set specific bits
- for b in 0..batch_size as usize {
- for word in 0..bitmask_size {
- bitmask[b * bitmask_size + word] = 0xAAAAAAAA; // bits 1,3,5,...
- }
- }
-
- let input = Input {
- logits: logits.into_boxed_slice(),
- bitmask: bitmask.into_boxed_slice(),
- batch_size,
- vocab_size,
- in_place: false,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::BitmaskKernel::new(&context, T::data_type(), input.in_place)
- .expect("Failed to create BitmaskKernel");
-
- let len = (input.batch_size * input.vocab_size) as usize;
- let bitmask_len = input.bitmask.len();
-
- let logits_buffer = (!input.in_place).then(|| context.create_array_from(&[len], &input.logits).into_allocation());
- let bitmask_array = context.create_array_from(&[bitmask_len], &input.bitmask);
- let mut output = match input.in_place {
- true => context.create_array_from(&[len], &input.logits).into_allocation(),
- false => context.create_array_uninitialized(&[len], T::data_type()).into_allocation(),
- };
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- logits_buffer.as_ref(),
- bitmask_array.allocation(),
- &mut output,
- input.batch_size,
- input.vocab_size,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- crate::common::helpers::allocation_to_vec(&output)
-}
-
-fn test_basic<T: ArrayElement + Float + Debug + Display>(in_place: bool) {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 1e-3
- } else {
- 1e-5
- };
-
- let (input, expected) = get_test_data_basic::<T>(in_place);
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- let msg = format!("Bitmask basic test failed for backend {}", std::any::type_name::<B>());
- assert_eq_float::<T>(&expected, &output, eps, &msg);
- });
-}
-
-fn test_all_allowed<T: ArrayElement + Float + Debug + Display>() {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 1e-3
- } else {
- 1e-5
- };
-
- let (input, expected) = get_test_data_all_allowed::<T>();
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- let msg = format!("Bitmask all-allowed test failed for backend {}", std::any::type_name::<B>());
- assert_eq_float::<T>(&expected, &output, eps, &msg);
- });
-}
-
-fn test_none_allowed<T: ArrayElement + Float + Debug + Display>() {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 1e-3
- } else {
- 1e-5
- };
-
- let (input, expected) = get_test_data_none_allowed::<T>();
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- let msg = format!("Bitmask none-allowed test failed for backend {}", std::any::type_name::<B>());
- assert_eq_float::<T>(&expected, &output, eps, &msg);
- });
-}
-
-fn test_non_aligned<T: ArrayElement + Float + Debug + Display>() {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 1e-3
- } else {
- 1e-5
- };
-
- let (input, expected) = get_test_data_non_aligned::<T>();
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- let msg = format!("Bitmask non-aligned test failed for backend {}", std::any::type_name::<B>());
- assert_eq_float::<T>(&expected, &output, eps, &msg);
- });
-}
-
-// Out-of-place basic tests
-#[uzu_test]
-fn test_basic_f32() {
- test_basic::<f32>(false);
-}
-
-#[uzu_test]
-fn test_basic_f16() {
- test_basic::<f16>(false);
-}
-
-#[uzu_test]
-fn test_basic_bf16() {
- test_basic::<bf16>(false);
-}
-
-// In-place basic tests
-#[uzu_test]
-fn test_in_place_f32() {
- test_basic::<f32>(true);
-}
-
-#[uzu_test]
-fn test_in_place_f16() {
- test_basic::<f16>(true);
-}
-
-#[uzu_test]
-fn test_in_place_bf16() {
- test_basic::<bf16>(true);
-}
-
-// All-allowed tests
-#[uzu_test]
-fn test_all_allowed_f32() {
- test_all_allowed::<f32>();
-}
-
-#[uzu_test]
-fn test_all_allowed_f16() {
- test_all_allowed::<f16>();
-}
-
-#[uzu_test]
-fn test_all_allowed_bf16() {
- test_all_allowed::<bf16>();
-}
-
-// None-allowed tests
-#[uzu_test]
-fn test_none_allowed_f32() {
- test_none_allowed::<f32>();
-}
-
-#[uzu_test]
-fn test_none_allowed_f16() {
- test_none_allowed::<f16>();
-}
-
-#[uzu_test]
-fn test_none_allowed_bf16() {
- test_none_allowed::<bf16>();
-}
-
-// Non-aligned vocab_size tests
-#[uzu_test]
-fn test_non_aligned_f32() {
- test_non_aligned::<f32>();
-}
-
-#[uzu_test]
-fn test_non_aligned_f16() {
- test_non_aligned::<f16>();
-}
-
-#[uzu_test]
-fn test_non_aligned_bf16() {
- test_non_aligned::<bf16>();
-}
diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/gumbel_test.rs b/crates/backend-uzu/tests/unit/kernel/sampling/gumbel_test.rs
deleted file mode 100644
index 454db8035..000000000
--- a/crates/backend-uzu/tests/unit/kernel/sampling/gumbel_test.rs
+++ /dev/null
@@ -1,156 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use backend_uzu::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Backend, Context, Encoder, Kernels, kernel::GumbelKernel},
- cpu::Cpu,
- },
- gumbel_float, revidx,
-};
-use half::{bf16, f16};
-use num_traits::Float;
-
-use crate::uzu_test;
-
-struct Input<T: ArrayElement + Float> {
- logits: Box<[T]>,
- seeds: Box<[u64]>,
- batch_size: u32,
- vocab_size: u32,
- in_place: bool,
-}
-
-fn get_test_data<T: ArrayElement + Float>(
- batch_size: u32,
- vocab_size: u32,
- in_place: bool,
-) -> (Input<T>, Vec<T>) {
- let len = (batch_size * vocab_size) as usize;
- let mut logits: Vec<T> = vec![T::zero(); len];
- for i in 0..len {
- logits[i] = T::from((i as f32 * 0.1).sin() * 2.0f32).unwrap();
- }
-
- let seeds: Vec<u64> = (0..batch_size as u64).collect();
-
- let input = Input {
- logits: logits.into_boxed_slice(),
- seeds: seeds.into_boxed_slice(),
- batch_size,
- vocab_size,
- in_place,
- };
-
- let expected = get_output::<T, Cpu>(&input);
-
- (input, expected)
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::GumbelKernel::new(&context, T::data_type(), input.in_place)
- .expect("Failed to create GumbelKernel");
-
- let len = (input.batch_size * input.vocab_size) as usize;
- let logits_buffer = (!input.in_place).then(|| context.create_array_from(&[len], &input.logits).into_allocation());
-
- let seeds_array = context.create_array_from(&[input.batch_size as usize], &input.seeds);
-
- let mut output = match input.in_place {
- true => context.create_array_from(&[len], &input.logits).into_allocation(),
- false => context.create_array_uninitialized(&[len], T::data_type()).into_allocation(),
- };
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- logits_buffer.as_ref(),
- seeds_array.allocation(),
- 0,
- &mut output,
- input.batch_size,
- input.vocab_size,
- &mut encoder,
- );
-
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- crate::common::helpers::allocation_to_vec(&output)
-}
-
-// Verify determinism: same seeds produce same output.
-fn test_determinism<T: ArrayElement + Float + Debug + Display>(
- batch_size: u32,
- vocab_size: u32,
-) {
- let (input, output1) = get_test_data::<T>(batch_size, vocab_size, false);
- let output2 = get_output::<T, Cpu>(&input);
- assert_eq!(output1, output2, "Determinism check failed");
-}
-
-fn test_internal<T: ArrayElement + Float + Display>(
- batch_size: usize,
- vocab_size: usize,
-) {
- const RTOL: f32 = 0.01;
- const ATOL: f32 = 1e-6;
-
- let logits = vec![T::zero(); batch_size * vocab_size];
- let seeds: Vec<u64> = (0_u64..batch_size as u64).collect();
-
- let input = Input {
- logits: logits.into_boxed_slice(),
- seeds: seeds.clone().into_boxed_slice(),
- batch_size: batch_size as u32,
- vocab_size: vocab_size as u32,
- in_place: false,
- };
-
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
-
- for (batch_idx, batch_seed) in seeds.iter().copied().enumerate() {
- let results = &output[batch_idx * vocab_size..(batch_idx + 1) * vocab_size];
- for (logit_idx, gpu_logit_value) in results.iter().copied().enumerate() {
- let cpu_logit_value = T::from(gumbel_float(batch_seed, revidx(logit_idx as u32))).unwrap();
- let abs_diff = (cpu_logit_value - gpu_logit_value).abs().to_f32().unwrap();
- let tolerance = ATOL + RTOL * cpu_logit_value.abs().to_f32().unwrap();
- 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})"
- );
- }
- }
- });
-}
-
-#[uzu_test]
-fn test_determinism_f32() {
- test_determinism::<f32>(4, 128);
-}
-
-#[uzu_test]
-fn test_determinism_f16() {
- test_determinism::<f16>(4, 128);
-}
-
-#[uzu_test]
-fn test_determinism_bf16() {
- test_determinism::<bf16>(4, 128);
-}
-
-#[uzu_test]
-fn test_f32() {
- test_internal::<f32>(7, 16 * 1024 * 64);
-}
-
-#[uzu_test]
-fn test_f16() {
- test_internal::<f16>(7, 16 * 1024 * 64);
-}
-
-#[uzu_test]
-fn test_bf16() {
- test_internal::<bf16>(7, 16 * 1024 * 64);
-}
diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/min_p_test.rs b/crates/backend-uzu/tests/unit/kernel/sampling/min_p_test.rs
deleted file mode 100644
index 4a6970683..000000000
--- a/crates/backend-uzu/tests/unit/kernel/sampling/min_p_test.rs
+++ /dev/null
@@ -1,159 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use backend_uzu::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Backend, Context, Encoder, Kernels, kernel::MinPKernel},
- cpu::Cpu,
- },
- data_type::DataType,
-};
-use half::{bf16, f16};
-use num_traits::Float;
-
-use crate::{common::assert::assert_eq_float, uzu_test};
-
-struct Input<T: ArrayElement + Float> {
- logits: Box<[T]>,
- batch_size: u32,
- vocab_size: u32,
- min_p: f32,
- in_place: bool,
-}
-
-fn get_test_data<T: ArrayElement + Float>(
- batch_size: u32,
- vocab_size: u32,
- min_p: f32,
- in_place: bool,
-) -> (Input<T>, Vec<T>) {
- let len = (batch_size * vocab_size) as usize;
- let logits: Vec<T> = (0..len).map(|i| T::from((i as f32 * 0.1).sin() * 2.0).unwrap()).collect();
-
- let input = Input {
- logits: logits.into_boxed_slice(),
- batch_size,
- vocab_size,
- min_p,
- in_place,
- };
-
- let expected = get_output::<T, Cpu>(&input);
- (input, expected)
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::MinPKernel::new(&context, T::data_type(), input.in_place)
- .expect("Failed to create MinPKernel");
-
- let len = (input.batch_size * input.vocab_size) as usize;
- let logits_buffer = (!input.in_place).then(|| context.create_array_from(&[len], &input.logits).into_allocation());
- let mut output = match input.in_place {
- true => context.create_array_from(&[len], &input.logits).into_allocation(),
- false => context.create_array_uninitialized(&[len], T::data_type()).into_allocation(),
- };
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(logits_buffer.as_ref(), &mut output, input.batch_size, input.vocab_size, input.min_p, &mut encoder);
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- crate::common::helpers::allocation_to_vec(&output)
-}
-
-fn test_internal<T: ArrayElement + Float + Debug + Display>(
- batch_size: u32,
- vocab_size: u32,
- min_p: f32,
- in_place: bool,
-) {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 1e-3
- } else {
- 1e-5
- };
-
- let (input, expected) = get_test_data::<T>(batch_size, vocab_size, min_p, in_place);
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- let msg = format!("MinP test failed for backend {}", std::any::type_name::<B>());
- assert_eq_float::<T>(&expected, &output, eps, &msg);
- });
-}
-
-// Out-of-place tests
-#[uzu_test]
-fn test_f32() {
- test_internal::<f32>(4, 128, 0.1, false);
-}
-
-#[uzu_test]
-fn test_f16() {
- test_internal::<f16>(4, 128, 0.1, false);
-}
-
-#[uzu_test]
-fn test_bf16() {
- test_internal::<bf16>(4, 128, 0.1, false);
-}
-
-// In-place tests
-#[uzu_test]
-fn test_in_place_f32() {
- test_internal::<f32>(4, 128, 0.1, true);
-}
-
-#[uzu_test]
-fn test_in_place_f16() {
- test_internal::<f16>(4, 128, 0.1, true);
-}
-
-#[uzu_test]
-fn test_in_place_bf16() {
- test_internal::<bf16>(4, 128, 0.1, true);
-}
-
-// High min_p — filters most tokens
-#[uzu_test]
-fn test_high_min_p_f32() {
- test_internal::<f32>(2, 128, 0.9, false);
-}
-
-#[uzu_test]
-fn test_high_min_p_f16() {
- test_internal::<f16>(2, 128, 0.9, false);
-}
-
-#[uzu_test]
-fn test_high_min_p_bf16() {
- test_internal::<bf16>(2, 128, 0.9, false);
-}
-
-// Low min_p — keeps most tokens
-#[uzu_test]
-fn test_low_min_p_f32() {
- test_internal::<f32>(2, 128, 0.01, false);
-}
-
-#[uzu_test]
-fn test_low_min_p_f16() {
- test_internal::<f16>(2, 128, 0.01, false);
-}
-
-#[uzu_test]
-fn test_low_min_p_bf16() {
- test_internal::<bf16>(2, 128, 0.01, false);
-}
-
-// Single batch
-#[uzu_test]
-fn test_single_batch_f32() {
- test_internal::<f32>(1, 256, 0.1, false);
-}
-
-// Large vocab
-#[uzu_test]
-fn test_large_vocab_f32() {
- test_internal::<f32>(2, 2048, 0.1, false);
-}
diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/mod.rs b/crates/backend-uzu/tests/unit/kernel/sampling/mod.rs
deleted file mode 100644
index bc67c32fb..000000000
--- a/crates/backend-uzu/tests/unit/kernel/sampling/mod.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-mod argmax_test_old;
-mod bitmask_test;
-mod gumbel_test;
-mod min_p_test;
-mod temperature_test;
-mod test_argmax;
-mod top_k_test;
diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/temperature_test.rs b/crates/backend-uzu/tests/unit/kernel/sampling/temperature_test.rs
deleted file mode 100644
index d77d3b151..000000000
--- a/crates/backend-uzu/tests/unit/kernel/sampling/temperature_test.rs
+++ /dev/null
@@ -1,148 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use backend_uzu::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Backend, Context, Encoder, Kernels, kernel::TemperatureKernel},
- cpu::Cpu,
- },
- data_type::DataType,
-};
-use half::{bf16, f16};
-use num_traits::Float;
-
-use crate::{common::assert::assert_eq_float, uzu_test};
-
-struct Input<T: ArrayElement + Float> {
- logits: Box<[T]>,
- batch_size: u32,
- vocab_size: u32,
- temperature: f32,
- in_place: bool,
-}
-
-fn get_test_data<T: ArrayElement + Float>(
- batch_size: u32,
- vocab_size: u32,
- temperature: f32,
- in_place: bool,
-) -> (Input<T>, Vec<T>) {
- let len = (batch_size * vocab_size) as usize;
- let mut logits: Vec<T> = vec![T::zero(); len];
- for i in 0..len {
- logits[i] = T::from((i as f32 * 0.1).sin() * 2.0f32).unwrap();
- }
-
- let input = Input {
- logits: logits.into_boxed_slice(),
- batch_size,
- vocab_size,
- temperature,
- in_place,
- };
-
- let expected = get_output::<T, Cpu>(&input);
-
- (input, expected)
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::TemperatureKernel::new(&context, T::data_type(), input.in_place)
- .expect("Failed to create TemperatureKernel");
-
- let len = (input.batch_size * input.vocab_size) as usize;
- let input_logits = (!input.in_place).then(|| context.create_array_from(&[len], &input.logits).into_allocation());
- let mut output = match input.in_place {
- true => context.create_array_from(&[len], &input.logits).into_allocation(),
- false => context.create_array_uninitialized(&[len], T::data_type()).into_allocation(),
- };
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(
- input_logits.as_ref(),
- &mut output,
- input.batch_size,
- input.vocab_size,
- input.temperature,
- &mut encoder,
- );
-
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- crate::common::helpers::allocation_to_vec(&output)
-}
-
-fn test_internal<T: ArrayElement + Float + Debug + Display>(
- batch_size: u32,
- vocab_size: u32,
- temperature: f32,
- in_place: bool,
-) {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 0.02f32
- } else {
- 1e-5
- };
-
- let (input, expected) = get_test_data::<T>(batch_size, vocab_size, temperature, in_place);
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- let msg = format!("Results are not equal for backend {}", std::any::type_name::<B>());
- assert_eq_float::<T>(&expected, &output, eps, &msg);
- });
-}
-
-// Out-of-place tests
-#[uzu_test]
-fn test_f32() {
- test_internal::<f32>(4, 128, 0.7, false);
-}
-
-#[uzu_test]
-fn test_f16() {
- test_internal::<f16>(4, 128, 0.7, false);
-}
-
-#[uzu_test]
-fn test_bf16() {
- test_internal::<bf16>(4, 128, 0.7, false);
-}
-
-// In-place tests
-#[uzu_test]
-fn test_in_place_f32() {
- test_internal::<f32>(4, 128, 0.7, true);
-}
-
-#[uzu_test]
-fn test_in_place_f16() {
- test_internal::<f16>(4, 128, 0.7, true);
-}
-
-#[uzu_test]
-fn test_in_place_bf16() {
- test_internal::<bf16>(4, 128, 0.7, true);
-}
-
-// Edge cases
-#[uzu_test]
-fn test_temperature_1_f32() {
- test_internal::<f32>(2, 64, 1.0, false);
-}
-
-#[uzu_test]
-fn test_high_temperature_f32() {
- test_internal::<f32>(2, 64, 100.0, false);
-}
-
-#[uzu_test]
-fn test_low_temperature_f32() {
- test_internal::<f32>(2, 64, 0.1, false);
-}
-
-#[uzu_test]
-fn test_single_batch_f32() {
- test_internal::<f32>(1, 256, 0.7, false);
-}
diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/test_argmax.rs b/crates/backend-uzu/tests/unit/kernel/sampling/test_argmax.rs
deleted file mode 100644
index c348b4029..000000000
--- a/crates/backend-uzu/tests/unit/kernel/sampling/test_argmax.rs
+++ /dev/null
@@ -1,114 +0,0 @@
-use std::mem::{MaybeUninit, size_of};
-
-use backend_uzu::{
- array::{ArrayContextExt, ArrayElement},
- backends::common::{
- AllocationType, Backend, Context, Encoder, Kernels,
- gpu_types::ArgmaxPair,
- kernel::{ArgmaxFinalKernel, ArgmaxMainKernel, ArgmaxSingleKernel},
- },
- data_type::DataType,
- dispatch_dtype,
-};
-use num_traits::{Float, NumCast};
-use proptest::prelude::*;
-use rand::{RngExt, SeedableRng, rngs::SmallRng};
-use rand_distr::Normal;
-
-use crate::{
- common::{
- for_each_context,
- proptest::{ComparableTestResults, TestContextes, kernel_data_type},
- },
- uzu_test,
-};
-
-struct ArgmaxTestResults(Box<[u32]>);
-
-impl ComparableTestResults for ArgmaxTestResults {
- fn compare(
- backend: &str,
- actual: &ArgmaxTestResults,
- reference: &ArgmaxTestResults,
- ) -> Result<(), TestCaseError> {
- prop_assert_eq!(&actual.0, &reference.0, "{} doesn't match cpu", backend);
-
- Ok(())
- }
-}
-
-fn do_argmax_backend<B: Backend, T: ArrayElement + Float>(
- context: &B::Context,
- logits: &[T],
- batch_size: usize,
- vocab_size: usize,
-) -> Result<ArgmaxTestResults, TestCaseError> {
- let logits_buffer = context.create_array_from(&[logits.len()], logits).into_allocation();
- let mut twopass_partial_results_buffer = context
- .create_allocation(batch_size * vocab_size.div_ceil(4096) * size_of::<ArgmaxPair>(), AllocationType::Global)
- .unwrap();
- let mut single_output_buffer = context.create_array_uninitialized(&[batch_size], DataType::U32).into_allocation();
- let mut twopass_output_buffer = context.create_array_uninitialized(&[batch_size], DataType::U32).into_allocation();
-
- let single_kernel = <B::Kernels as Kernels>::ArgmaxSingleKernel::new(context, T::data_type()).unwrap();
- let twopass_kernel_main = <B::Kernels as Kernels>::ArgmaxMainKernel::new(context, T::data_type()).unwrap();
- let twopass_kernel_final = <B::Kernels as Kernels>::ArgmaxFinalKernel::new(context).unwrap();
-
- let mut encoder = Encoder::new(context).unwrap();
- single_kernel.encode(&logits_buffer, &mut single_output_buffer, batch_size as u32, vocab_size as u32, &mut encoder);
- twopass_kernel_main.encode(
- &logits_buffer,
- &mut twopass_partial_results_buffer,
- batch_size as u32,
- vocab_size as u32,
- &mut encoder,
- );
- twopass_kernel_final.encode(
- &twopass_partial_results_buffer,
- &mut twopass_output_buffer,
- batch_size as u32,
- vocab_size as u32,
- &mut encoder,
- );
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- let single_output = crate::common::helpers::allocation_to_vec::<B, u32>(&single_output_buffer);
- let twopass_output = crate::common::helpers::allocation_to_vec::<B, u32>(&twopass_output_buffer);
-
- prop_assert_eq!(&single_output, &twopass_output, "single and twopass argmax output differs");
-
- Ok(ArgmaxTestResults(single_output.into_boxed_slice()))
-}
-
-fn get_argmax_data<T: ArrayElement + Float>(
- seed: u64,
- batch_size: usize,
- vocab_size: usize,
-) -> Box<[T]> {
- let mut rng = SmallRng::seed_from_u64(seed);
- let distribution = Normal::new(0.0, 32.0).unwrap();
- let mut logits: Box<[MaybeUninit<T>]> = Box::new_uninit_slice(batch_size * vocab_size);
- for logit in logits.iter_mut() {
- logit.write(<T as NumCast>::from(rng.sample(distribution)).unwrap());
- }
- unsafe { logits.assume_init() }
-}
-
-#[uzu_test]
-fn test_argmax_prop() {
- let contextes = TestContextes::new();
-
- proptest!(|(data_type in kernel_data_type(), seed in any::<u64>().no_shrink(), batch_size in (1usize..=7usize), vocab_size in (1usize..=123456usize))| {
- dispatch_dtype!(|(T: data_type)| {
- let logits = get_argmax_data(seed, batch_size, vocab_size);
-
- for_each_context!(contextes, |context: C| do_argmax_backend::<<C as Context>::Backend, T>(
- context,
- logits.as_ref(),
- batch_size,
- vocab_size
- ))
- .compare_results()?
- });
- });
-}
diff --git a/crates/backend-uzu/tests/unit/kernel/sampling/top_k_test.rs b/crates/backend-uzu/tests/unit/kernel/sampling/top_k_test.rs
deleted file mode 100644
index fe60d3b1e..000000000
--- a/crates/backend-uzu/tests/unit/kernel/sampling/top_k_test.rs
+++ /dev/null
@@ -1,177 +0,0 @@
-use std::fmt::{Debug, Display};
-
-use backend_uzu::{
- array::{ArrayContextExt, ArrayElement},
- backends::{
- common::{Backend, Context, Encoder, Kernels, kernel::TopKKernel},
- cpu::Cpu,
- },
- data_type::DataType,
-};
-use half::{bf16, f16};
-use num_traits::Float;
-use rand::{RngExt, SeedableRng, rngs::StdRng};
-
-use crate::uzu_test;
-
-struct Input<T: ArrayElement + Float> {
- logits: Box<[T]>,
- batch_size: u32,
- vocab_size: u32,
- top_k: u32,
- in_place: bool,
-}
-
-fn get_test_data<T: ArrayElement + Float>(
- batch_size: u32,
- vocab_size: u32,
- top_k: u32,
- in_place: bool,
-) -> (Input<T>, Vec<T>) {
- let len = (batch_size * vocab_size) as usize;
- let mut rng = StdRng::seed_from_u64(42);
- let mut logits: Vec<T> = vec![T::zero(); len];
- for x in logits.iter_mut() {
- *x = T::from(rng.random_range(-1024.0f32..1024.0f32)).unwrap();
- }
-
- let input = Input {
- logits: logits.into_boxed_slice(),
- batch_size,
- vocab_size,
- top_k,
- in_place,
- };
-
- let expected = get_output::<T, Cpu>(&input);
-
- (input, expected)
-}
-
-fn get_output<T: ArrayElement + Float, B: Backend>(input: &Input<T>) -> Vec<T> {
- let context = B::Context::new().expect("Failed to create Context");
-
- let kernel = <<B as Backend>::Kernels as Kernels>::TopKKernel::new(&context, T::data_type(), input.in_place)
- .expect("Failed to create TopKKernel");
-
- let len = (input.batch_size * input.vocab_size) as usize;
- let logits_buffer = (!input.in_place).then(|| context.create_array_from(&[len], &input.logits).into_allocation());
- let mut output = match input.in_place {
- true => context.create_array_from(&[len], &input.logits).into_allocation(),
- false => context.create_array_uninitialized(&[len], T::data_type()).into_allocation(),
- };
-
- let mut encoder = Encoder::new(context.as_ref()).expect("Failed to create encoder");
- kernel.encode(logits_buffer.as_ref(), &mut output, input.batch_size, input.vocab_size, input.top_k, &mut encoder);
-
- encoder.end_encoding().submit().wait_until_completed().unwrap();
-
- crate::common::helpers::allocation_to_vec(&output)
-}
-
-fn assert_top_k_equal<T: ArrayElement + Float + Display>(
- expected: &[T],
- actual: &[T],
- vocab_size: u32,
- top_k: u32,
- eps: f32,
- msg: &str,
-) {
- assert_eq!(expected.len(), actual.len(), "Slices size mismatch");
- let vocab_size = vocab_size as usize;
- let num_batches = expected.len() / vocab_size;
-
- for batch_idx in 0..num_batches {
- let start = batch_idx * vocab_size;
- let end = start + vocab_size;
-
- // Both should keep approximately top_k values and mask the rest
- let expected_kept: usize = expected[start..end].iter().filter(|v| v.is_finite()).count();
- let actual_kept: usize = actual[start..end].iter().filter(|v| v.is_finite()).count();
-
- // Allow small differences due to binary search convergence
- let diff = (expected_kept as i64 - actual_kept as i64).unsigned_abs();
- assert!(
- diff <= 3,
- "{msg}. Batch {batch_idx}: expected {expected_kept} kept values, got {actual_kept} (top_k={top_k})"
- );
-
- // For values that are kept by both, they should match the original values
- for i in start..end {
- let e = expected[i].to_f32().unwrap();
- let a = actual[i].to_f32().unwrap();
- if e.is_finite() && a.is_finite() {
- let d = (e - a).abs();
- assert!(d < eps, "{msg}. Mismatch at index {i}: expected {e}, got {a}, diff {d}");
- }
- }
- }
-}
-
-fn test_internal<T: ArrayElement + Float + Debug + Display>(
- batch_size: u32,
- vocab_size: u32,
- top_k: u32,
- in_place: bool,
-) {
- let eps = if matches!(T::data_type(), DataType::F16 | DataType::BF16) {
- 1e-2
- } else {
- 1e-5
- };
-
- let (input, expected) = get_test_data::<T>(batch_size, vocab_size, top_k, in_place);
- for_each_non_cpu_backend!(|B| {
- let output = get_output::<T, B>(&input);
- let msg = format!("Results are not equal for backend {}", std::any::type_name::<B>());
- assert_top_k_equal::<T>(&expected, &output, vocab_size, top_k, eps, &msg);
- });
-}
-
-// Out-of-place tests (same data as sampling_test::test_topk_gpu_cpu_match)
-#[uzu_test]
-fn test_f32() {
- test_internal::<f32>(4, 1024, 16, false);
-}
-
-#[uzu_test]
-fn test_f16() {
- test_internal::<f16>(4, 1024, 16, false);
-}
-
-#[uzu_test]
-fn test_bf16() {
- test_internal::<bf16>(4, 1024, 16, false);
-}
-
-// In-place tests
-#[uzu_test]
-fn test_in_place_f32() {
- test_internal::<f32>(4, 1024, 16, true);
-}
-
-#[uzu_test]
-fn test_in_place_f16() {
- test_internal::<f16>(4, 1024, 16, true);
-}
-
-#[uzu_test]
-fn test_in_place_bf16() {
- test_internal::<bf16>(4, 1024, 16, true);
-}
-
-// Edge cases
-#[uzu_test]
-fn test_single_batch_f32() {
- test_internal::<f32>(1, 1024, 16, false);
-}
-
-#[uzu_test]
-fn test_top_k_1_f32() {
- test_internal::<f32>(4, 1024, 1, false);
-}
-
-#[uzu_test]
-fn test_top_k_equals_vocab_f32() {
- test_internal::<f32>(4, 1024, 1024, false);
-}
diff --git a/crates/backend-uzu/tests/unit/trie_test.rs b/crates/backend-uzu/tests/unit/trie_test.rs
index 21d7fe278..4e07d32df 100644
--- a/crates/backend-uzu/tests/unit/trie_test.rs
+++ b/crates/backend-uzu/tests/unit/trie_test.rs
@@ -64,6 +64,7 @@ fn test_trie_from_speculator_sprout() {
&rng,
None,
&speculator,
+ 1024,
&TrieCreationConfig {
width: 5,
},
@@ -135,6 +136,7 @@ fn test_trie_from_speculator_stick() {
&rng,
None,
&speculator,
+ 1024,
&TrieCreationConfig {
width: 1,
},
@@ -203,6 +205,7 @@ fn test_trie_from_speculator_bush() {
&rng,
None,
&speculator,
+ 1024,
&TrieCreationConfig {
width: 3,
},