Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Qwen3.5 4b speculation (#1067)

uuuvn83e7d8ad1cea
diff --git a/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs b/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs
index 268e1b450..d5ff4cc24 100644
--- a/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs
@@ -111,7 +111,6 @@ impl<B: Backend> ActivationTransform<B> {
Self::new(context, data_type, None, ActivationTransformOp::InputRht, in_place, ActivationFormat::Bf16)
}
- #[cfg(any(backend = "cpu", backend = "metal"))]
pub fn output_rht(
context: &B::Context,
data_type: DataType,
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/sampling/repetition_penalty.rs b/crates/uzu-engine/src/backends/cpu/kernel/sampling/repetition_penalty.rs
index 660fe268c..5d9f9a74f 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/sampling/repetition_penalty.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/sampling/repetition_penalty.rs
@@ -2,7 +2,10 @@ use half::bf16;
use num_traits::{Float, NumCast};
use uzu_engine_macros::kernel;
-use crate::{backends::common::gpu_types::ring::RingParams, data_type::DataTypeRepr};
+use crate::{
+ backends::common::gpu_types::{ring::RingParams, trie::TrieNode},
+ data_type::DataTypeRepr,
+};
#[kernel(RepetitionPenalty)]
#[variants(T, f32, bf16)]
@@ -11,11 +14,13 @@ pub fn repetition_penalty<T: DataTypeRepr + Float + NumCast>(
logits_copy: *mut T,
context_ring: *const u32,
token_ids: *const u32,
+ #[optional(is_trie)] trie: Option<*const TrieNode>,
repetition_penalty: f32,
suffix_repetition_length: u32,
vocab_size: u32,
sampling_start: u32,
sampling_length: u32,
+ #[specialize] is_trie: bool,
) {
fn apply(
original_logits: *const (impl DataTypeRepr + Float),
@@ -37,12 +42,15 @@ pub fn repetition_penalty<T: DataTypeRepr + Float + NumCast>(
}
}
+ assert_eq!(trie.is_some(), is_trie);
let ring = unsafe { &*context_ring.cast::<RingParams>() };
let ring_tokens = unsafe { context_ring.add(2) };
let vocab_size = vocab_size as usize;
for sample_index in 0..sampling_length {
- let batch_prefix_length = sampling_start + sample_index + 1;
+ let batch_index = sampling_start + sample_index;
+ let batch_prefix_length =
+ trie.map_or(batch_index, |trie| unsafe { (*trie.add(batch_index as usize)).height }) + 1;
let total_length = ring.ring_length + batch_prefix_length;
let window_length = total_length.min(suffix_repetition_length);
let skipped_length = total_length - window_length;
@@ -53,7 +61,15 @@ pub fn repetition_penalty<T: DataTypeRepr + Float + NumCast>(
let slot = (ring.ring_offset + source_index) % suffix_repetition_length;
(unsafe { *ring_tokens.add(slot as usize) }) as usize
} else {
- (unsafe { *token_ids.add((source_index - ring.ring_length) as usize) }) as usize
+ let mut token_index = source_index - ring.ring_length;
+ if let Some(trie) = trie {
+ let height = token_index;
+ token_index = batch_index;
+ while unsafe { (*trie.add(token_index as usize)).height } != height {
+ token_index -= 1;
+ }
+ }
+ (unsafe { *token_ids.add(token_index as usize) }) as usize
};
apply(original_logits, logits_copy, vocab_size, sample_index as usize, token_id, repetition_penalty);
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/sampling/repetition_penalty.metal b/crates/uzu-engine/src/backends/metal/kernel/sampling/repetition_penalty.metal
index 0173f74a1..c290bae5a 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/sampling/repetition_penalty.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/sampling/repetition_penalty.metal
@@ -1,9 +1,11 @@
#include <metal_stdlib>
#include "../common/dsl.h"
#include "../generated/ring.h"
+#include "../generated/trie.h"
using namespace metal;
using namespace uzu::ring;
+using namespace uzu::trie;
template <typename T>
VARIANTS(T, float, bfloat)
@@ -12,18 +14,21 @@ PUBLIC KERNEL(RepetitionPenalty)(
device T* logits_copy,
const device uint32_t* context_ring,
const device uint32_t* token_ids,
+ const device TrieNode* trie OPTIONAL(is_trie),
const constant float& repetition_penalty,
const constant uint32_t& suffix_repetition_length,
const constant uint32_t& vocab_size,
const constant uint32_t& sampling_start,
const constant uint32_t& sampling_length,
+ const bool is_trie SPECIALIZE,
const uint32_t position AXIS(sampling_length * suffix_repetition_length, 256)
) {
const RingParams ring = *reinterpret_cast<const device RingParams*>(context_ring);
const uint32_t sample_index = position / suffix_repetition_length;
const uint32_t window_index = position % suffix_repetition_length;
- const uint32_t batch_prefix_length = sampling_start + sample_index + 1;
+ const uint32_t batch_index = sampling_start + sample_index;
+ const uint32_t batch_prefix_length = (is_trie ? trie[batch_index].height : batch_index) + 1;
const uint32_t total_length = ring.ring_length + batch_prefix_length;
const uint32_t window_length = min(total_length, suffix_repetition_length);
if (window_index >= window_length) {
@@ -37,7 +42,15 @@ PUBLIC KERNEL(RepetitionPenalty)(
const uint32_t slot = (ring.ring_offset + source_index) % suffix_repetition_length;
token_id = ring_tokens[slot];
} else {
- token_id = token_ids[source_index - ring.ring_length];
+ uint32_t token_index = source_index - ring.ring_length;
+ if (is_trie) {
+ const uint32_t height = token_index;
+ token_index = batch_index;
+ while (trie[token_index].height != height) {
+ --token_index;
+ }
+ }
+ token_id = token_ids[token_index];
}
const uint32_t logit_offset = sample_index * vocab_size + token_id;
diff --git a/crates/uzu-engine/src/backends/slang/kernel/sampling/repetition_penalty.slang b/crates/uzu-engine/src/backends/slang/kernel/sampling/repetition_penalty.slang
index caa39a278..b619ef16b 100644
--- a/crates/uzu-engine/src/backends/slang/kernel/sampling/repetition_penalty.slang
+++ b/crates/uzu-engine/src/backends/slang/kernel/sampling/repetition_penalty.slang
@@ -1,5 +1,6 @@
// Autogenerated stub
import definitions;
+import generated.trie;
[[Variants("T", "float, BFloat16")]]
[[Public]] [[Kernel]] func RepetitionPenalty<T>(
@@ -7,11 +8,13 @@ import definitions;
RWStructuredBuffer<T> logits_copy,
StructuredBuffer<uint32_t> context_ring,
StructuredBuffer<uint32_t> token_ids,
+ [[Optional("is_trie")]] StructuredBuffer<TrieNode> trie,
float repetition_penalty,
uint32_t suffix_repetition_length,
uint32_t vocab_size,
uint32_t sampling_start,
uint32_t sampling_length,
+ [[Specialize]] bool is_trie,
[[Axis("sampling_length * suffix_repetition_length", "256")]] uint32_t position,
) {
// TODO
diff --git a/crates/uzu-engine/src/encodable_block/dflash.rs b/crates/uzu-engine/src/encodable_block/dflash.rs
index 40f8c52ef..330c9c63c 100644
--- a/crates/uzu-engine/src/encodable_block/dflash.rs
+++ b/crates/uzu-engine/src/encodable_block/dflash.rs
@@ -1,4 +1,4 @@
-use std::{any::Any, range::Range};
+use std::{any::Any, range::Range, sync::Arc};
use derive_more::Debug;
use thiserror::Error;
@@ -94,6 +94,7 @@ impl<B: Backend> DFlash<B> {
pub async fn new(
data_type: DataType,
config: &DFlashDraftConfig,
+ readout_input_hadamard_factors: Option<Arc<B::GlobalGpuBuffer>>,
parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, DFlashNewError<B>> {
@@ -156,7 +157,7 @@ impl<B: Backend> DFlash<B> {
config.model_dim,
data_type,
data_type,
- None,
+ readout_input_hadamard_factors,
ShortcutMode::Add,
PostLayerScalar::None,
&config.output_norm_config,
diff --git a/crates/uzu-engine/src/encodable_block/embedding.rs b/crates/uzu-engine/src/encodable_block/embedding.rs
index 7bdfd2a72..473dfee45 100644
--- a/crates/uzu-engine/src/encodable_block/embedding.rs
+++ b/crates/uzu-engine/src/encodable_block/embedding.rs
@@ -1,3 +1,5 @@
+use std::sync::Arc;
+
use derive_more::Debug;
use parking_lot::Mutex;
use thiserror::Error;
@@ -50,6 +52,7 @@ enum EmbeddingTying<B: Backend> {
pub struct Embedding<B: Backend> {
tying: EmbeddingTying<B>,
+ readout_input_hadamard_factors: Option<Arc<B::GlobalGpuBuffer>>,
input_scale: f32,
data_type: DataType,
logit_transform: Option<LogitTransform<B>>,
@@ -72,6 +75,10 @@ impl<B: Backend> Embedding<B> {
self.model_dim
}
+ pub fn readout_input_hadamard_factors(&self) -> Option<Arc<B::GlobalGpuBuffer>> {
+ self.readout_input_hadamard_factors.clone()
+ }
+
pub async fn new(
vocab_size: u32,
model_dim: u32,
@@ -79,7 +86,7 @@ impl<B: Backend> Embedding<B> {
config: &AnyEmbeddingConfig,
parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
- ) -> Result<(Self, Option<B::GlobalGpuBuffer>), EmbeddingError<B>> {
+ ) -> Result<(Self, Option<Arc<B::GlobalGpuBuffer>>), EmbeddingError<B>> {
let (tying, readout_input_hadamard_factors) = match config {
AnyEmbeddingConfig::TiedEmbeddingConfig(_) => {
let embedding_tree = parameter_tree.subtree("embedding");
@@ -87,10 +94,9 @@ impl<B: Backend> Embedding<B> {
if table.as_matrix().is_none() {
return Err(EmbeddingError::UnsupportedConfiguration("tied embeddings need a matrix table".into()));
}
- // The output norm fuses the readout's input rotation, so it needs its own copy of the factors.
let spec = embedding_tree.metadata("spec")?;
let readout_input_hadamard_factors = if let AnyWeightMatrixSpec::HybridSpec(_) = spec {
- Some(read_output_signs(&embedding_tree, model_dim).await?)
+ Some(Arc::new(read_output_signs(&embedding_tree, model_dim).await?))
} else {
None
};
@@ -146,6 +152,7 @@ impl<B: Backend> Embedding<B> {
Ok((
Self {
tying,
+ readout_input_hadamard_factors: readout_input_hadamard_factors.clone(),
input_scale,
data_type,
logit_transform,
diff --git a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs b/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
index 6fdba1bde..fc13ef196 100644
--- a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
@@ -58,19 +58,14 @@ impl<B: Backend> RHTLinearWrapper<B> {
parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, RHTLinearWrapperError<B>> {
- let weights_tree = parameter_tree.subtree("weights");
- let spec = weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;
- if !has_input_output_rht(&spec) {
- return Err(RHTLinearWrapperError::UnsupportedConfiguration(format!("{spec:?}")));
- }
-
- let (rht_signs, inner_linear, activation_format) = Self::load_inner_with_output_rht(
+ let (rht_signs, inner_linear, activation_format) = Self::load_inner(
input_dimension,
output_dimension,
weights_data_type,
input_data_type,
output_data_type,
has_biases,
+ true,
parameter_tree,
context,
)
@@ -86,6 +81,36 @@ impl<B: Backend> RHTLinearWrapper<B> {
)
}
+ pub async fn new_with_rotated_output(
+ input_dimension: u32,
+ output_dimension: u32,
+ data_type: DataType,
+ parameter_tree: &ParameterTree<'_, B>,
+ context: &B::Context,
+ ) -> Result<Self, RHTLinearWrapperError<B>> {
+ let (rht_signs, inner_linear, activation_format) = Self::load_inner(
+ input_dimension,
+ output_dimension,
+ data_type,
+ data_type,
+ data_type,
+ false,
+ false,
+ parameter_tree,
+ context,
+ )
+ .await?;
+ Self::build_self_contained(
+ data_type,
+ LinearInputPreparation {
+ rht_signs,
+ activation_format,
+ },
+ inner_linear,
+ context,
+ )
+ }
+
pub(super) async fn try_new_with_input_preparation(
input_dimension: u32,
output_dimension: u32,
@@ -103,13 +128,14 @@ impl<B: Backend> RHTLinearWrapper<B> {
return Ok(None);
}
- let (rht_signs, inner_linear, activation_format) = Self::load_inner_with_output_rht(
+ let (rht_signs, inner_linear, activation_format) = Self::load_inner(
input_dimension,
output_dimension,
weights_data_type,
input_data_type,
output_data_type,
has_biases,
+ true,
parameter_tree,
context,
)
@@ -126,23 +152,32 @@ impl<B: Backend> RHTLinearWrapper<B> {
}
}
- async fn load_inner_with_output_rht(
+ async fn load_inner(
input_dimension: u32,
output_dimension: u32,
weights_data_type: DataType,
input_data_type: DataType,
output_data_type: DataType,
has_biases: bool,
+ restore_output_basis: bool,
parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<(B::GlobalGpuBuffer, LinearMatmul<B>, ActivationFormat), RHTLinearWrapperError<B>> {
let weights_tree = parameter_tree.subtree("weights");
+ let spec = weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;
+ if !has_input_output_rht(&spec) {
+ return Err(RHTLinearWrapperError::UnsupportedConfiguration(format!("{spec:?}")));
+ }
let quantized_weights_tree = weights_tree.subtree("quantized");
let quantization_spec = quantized_weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;
let rht_signs =
weights_tree.read_buffer("incoherence_signs.input_signs", &[input_dimension], DataType::I32).await?;
- let output_factors =
- weights_tree.read_buffer("incoherence_signs.output_signs", &[output_dimension], DataType::I32).await?;
+ let output_factors = if restore_output_basis {
+ Some(weights_tree.read_buffer("incoherence_signs.output_signs", &[output_dimension], DataType::I32).await?)
+ } else {
+ weights_tree.ignore("incoherence_signs.output_signs", &[output_dimension], DataType::I32)?;
+ None
+ };
let mut inner_linear = LinearMatmul::load(
input_dimension,
output_dimension,
@@ -150,7 +185,7 @@ impl<B: Backend> RHTLinearWrapper<B> {
input_data_type,
output_data_type,
quantization_spec,
- Some(output_factors),
+ output_factors,
&quantized_weights_tree,
has_biases.then_some(parameter_tree),
context,
diff --git a/crates/uzu-engine/src/encodable_block/normalization.rs b/crates/uzu-engine/src/encodable_block/normalization.rs
index cf30952e0..8f95833a4 100644
--- a/crates/uzu-engine/src/encodable_block/normalization.rs
+++ b/crates/uzu-engine/src/encodable_block/normalization.rs
@@ -1,3 +1,5 @@
+use std::sync::Arc;
+
use derive_more::Debug;
use thiserror::Error;
@@ -42,7 +44,7 @@ pub struct Normalization<B: Backend> {
scales: Option<B::GlobalGpuBuffer>,
biases: Option<B::GlobalGpuBuffer>,
element_count: u32,
- hadamard_factors: Option<B::GlobalGpuBuffer>,
+ hadamard_factors: Option<Arc<B::GlobalGpuBuffer>>,
post_layer_scalar_value: f32,
input_data_type: DataType,
output_data_type: DataType,
@@ -54,7 +56,7 @@ impl<B: Backend> Normalization<B> {
element_count: u32,
input_data_type: DataType,
output_data_type: DataType,
- hadamard_factors: Option<B::GlobalGpuBuffer>,
+ hadamard_factors: Option<Arc<B::GlobalGpuBuffer>>,
shortcut_mode: ShortcutMode,
post_layer_scalar: PostLayerScalar,
config: &NormalizationConfig,
@@ -136,7 +138,7 @@ impl<B: Backend> Normalization<B> {
self.biases.as_ref(),
&mut output,
shortcut,
- self.hadamard_factors.as_ref(),
+ self.hadamard_factors.as_deref(),
row_count,
self.element_count,
self.epsilon,
diff --git a/crates/uzu-engine/src/encodable_block/sampling/mod.rs b/crates/uzu-engine/src/encodable_block/sampling/mod.rs
index 21fd9dff8..fe01a0606 100644
--- a/crates/uzu-engine/src/encodable_block/sampling/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/sampling/mod.rs
@@ -120,23 +120,30 @@ impl<B: Backend> Sampling<B> {
has_min_p: min_p.is_some(),
};
- // TODO: repetition penalty is vibe coded garbage, remove or rewrite properly
let penalized_logits = if let Some(repetition_penalty) = repetition_penalty {
- assert!(batch_dim.is_flat(), "repetition_penalty currently only supports flat batches");
let suffix_repetition_length =
suffix_repetition_length.expect("suffix_repetition_length is required for repetition_penalty");
+ let trie = if batch_dim.is_flat() {
+ None
+ } else {
+ Some(command_buffer.allocate_constant_from_slice(batch_dim.nodes())?)
+ };
let mut logits_copy = command_buffer.allocate_scratch(logits.size())?;
let copy_size = self.vocab_size as usize * sampling_length as usize * self.data_type.size_in_bytes();
command_buffer.encode_copy(logits.subrange(..copy_size), logits_copy.subrange_mut(..copy_size));
- let repetition_penalty_kernel =
- <B::Kernels as Kernels>::RepetitionPenaltyKernel::new(command_buffer.context(), self.data_type)?;
+ let repetition_penalty_kernel = <B::Kernels as Kernels>::RepetitionPenaltyKernel::new(
+ command_buffer.context(),
+ self.data_type,
+ trie.is_some(),
+ )?;
repetition_penalty_kernel.encode(
logits,
&mut logits_copy,
context_ring.expect("context_ring is required for repetition_penalty"),
token_ids.expect("token_ids is required for repetition_penalty"),
+ trie.as_ref(),
repetition_penalty,
suffix_repetition_length,
self.vocab_size,
diff --git a/crates/uzu-engine/src/encodable_block/transformer.rs b/crates/uzu-engine/src/encodable_block/transformer.rs
index 6d93bc62c..0966c0a05 100644
--- a/crates/uzu-engine/src/encodable_block/transformer.rs
+++ b/crates/uzu-engine/src/encodable_block/transformer.rs
@@ -1,4 +1,4 @@
-use std::range::Range;
+use std::{range::Range, sync::Arc};
use derive_more::Debug;
use thiserror::Error;
@@ -110,7 +110,7 @@ impl<B: Backend> Transformer<B> {
pub async fn new(
input_data_type: DataType,
output_data_type: DataType,
- output_norm_hadamard_factors: Option<B::GlobalGpuBuffer>,
+ output_norm_hadamard_factors: Option<Arc<B::GlobalGpuBuffer>>,
transformer_config: &TransformerConfig,
parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
diff --git a/crates/uzu-engine/src/encodable_block/transformer_layer.rs b/crates/uzu-engine/src/encodable_block/transformer_layer.rs
index 002817d64..6016db49c 100644
--- a/crates/uzu-engine/src/encodable_block/transformer_layer.rs
+++ b/crates/uzu-engine/src/encodable_block/transformer_layer.rs
@@ -1,3 +1,5 @@
+use std::sync::Arc;
+
use derive_more::Debug;
use num_traits::AsPrimitive;
use thiserror::Error;
@@ -237,7 +239,7 @@ impl<B: Backend> TransformerLayer<B> {
model_dim,
data_type,
data_type,
- mixer_hadamard_factors,
+ mixer_hadamard_factors.map(Arc::new),
if layer_index > 0 {
ShortcutMode::Add
} else {
@@ -308,7 +310,7 @@ impl<B: Backend> TransformerLayer<B> {
model_dim,
data_type,
data_type,
- mlp_input_hadamard_factors,
+ mlp_input_hadamard_factors.map(Arc::new),
ShortcutMode::Add,
residual_sum_scalar,
&layer_config.pre_mlp_norm_config,
diff --git a/crates/uzu-engine/src/encodable_block/weaver.rs b/crates/uzu-engine/src/encodable_block/weaver.rs
index 0968fd8a6..797de15aa 100644
--- a/crates/uzu-engine/src/encodable_block/weaver.rs
+++ b/crates/uzu-engine/src/encodable_block/weaver.rs
@@ -1,3 +1,5 @@
+use std::sync::Arc;
+
use derive_more::Debug;
use thiserror::Error;
@@ -9,15 +11,15 @@ use crate::{
WeaverSelectionMode::{Children, Frontier, Fused},
},
kernel::{
- AncestorAttentionKernel, AttentionArguments, AttentionInput, AttentionKernel, FullPrecisionInput,
- WeaverSelectKernel, radix_top_k_small::RadixTopKSmall,
+ ActivationTransform, AncestorAttentionKernel, AttentionArguments, AttentionInput, AttentionKernel,
+ FullPrecisionInput, WeaverSelectKernel, radix_top_k_small::RadixTopKSmall,
},
},
config::{rope::AnyRoPEConfig, weaver::WeaverConfig},
data_type::DataType,
encodable_block::{
embedding::{Embedding, EmbeddingError},
- linear::{Linear, LinearBlockError, LinearEncodeError},
+ linear::{Linear, LinearBlockError, LinearEncodeError, RHTLinearWrapper},
mixer::attention::{KVCacheView, rope::PrecalculatedRoPE},
mlp::{MlpBlockNewError, MlpEncodeError},
normalization::{Normalization, NormalizationNewError, PostLayerScalar, ShortcutMode},
@@ -126,6 +128,7 @@ pub struct Weaver<B: Backend> {
layers: Box<[WeaverLayer<B>]>,
readout_norm: Normalization<B>,
readout_query_projection: Box<dyn Linear<B>>,
+ prefix_unrotation: Option<PrefixUnrotation<B>>,
rope_config: AnyRoPEConfig,
top_k: <B::Kernels as Kernels>::RadixTopKSmall,
top_children: <B::Kernels as Kernels>::WeaverSelectKernel,
@@ -138,6 +141,11 @@ pub struct Weaver<B: Backend> {
candidate_pool_size: u32,
}
+struct PrefixUnrotation<B: Backend> {
+ factors: Arc<B::GlobalGpuBuffer>,
+ transform: ActivationTransform<B>,
+}
+
#[derive(Debug, Error)]
pub enum WeaverNewError<B: Backend> {
#[error("Attention kernel error: {0}")]
@@ -188,6 +196,7 @@ impl<B: Backend> Weaver<B> {
pub async fn new(
vocab_size: u32,
config: &WeaverConfig,
+ readout_input_hadamard_factors: Option<Arc<B::GlobalGpuBuffer>>,
parameter_tree: &ParameterTree<'_, B>,
context: &B::Context,
) -> Result<Self, WeaverNewError<B>> {
@@ -274,15 +283,41 @@ impl<B: Backend> Weaver<B> {
context,
)
.await?;
- let readout_query_projection = <dyn Linear<B>>::new(
- config.model_dim,
- config.target_model_dim,
- DATA_TYPE,
- false,
- &parameter_tree.subtree("query_projection"),
- context,
- )
- .await?;
+ let query_projection_tree = parameter_tree.subtree("query_projection");
+ let readout_query_projection: Box<dyn Linear<B>> = if readout_input_hadamard_factors.is_some() {
+ // NOTE: We assume the query projection's output Hadamard signs match the tied
+ // readout's input signs, so its output can stay in the readout's rotated basis.
+ Box::new(
+ RHTLinearWrapper::new_with_rotated_output(
+ config.model_dim,
+ config.target_model_dim,
+ DATA_TYPE,
+ &query_projection_tree,
+ context,
+ )
+ .await
+ .map_err(LinearBlockError::from)?,
+ )
+ } else {
+ <dyn Linear<B>>::new(
+ config.model_dim,
+ config.target_model_dim,
+ DATA_TYPE,
+ false,
+ &query_projection_tree,
+ context,
+ )
+ .await?
+ };
+ let prefix_unrotation = readout_input_hadamard_factors
+ .map(|factors| {
+ Ok(PrefixUnrotation {
+ factors,
+ transform: ActivationTransform::output_rht(context, DATA_TYPE, None, true)?,
+ })
+ })
+ .transpose()
+ .map_err(WeaverNewError::Backend)?;
let top_k =
<B::Kernels as Kernels>::RadixTopKSmall::new(context, vocab_size).map_err(WeaverNewError::Backend)?;
let top_children = <B::Kernels as Kernels>::WeaverSelectKernel::new(context, 256, Children, false)
@@ -302,6 +337,7 @@ impl<B: Backend> Weaver<B> {
layers: layers.into_boxed_slice(),
readout_norm,
readout_query_projection,
+ prefix_unrotation,
rope_config: config.rope_config.clone(),
top_k,
top_children,
@@ -339,6 +375,16 @@ impl<B: Backend> Weaver<B> {
draft_hidden.subrange(hidden_row_bytes..depth as usize * hidden_row_bytes),
prefix_hidden.subrange_mut(hidden_row_bytes..),
);
+ if let Some(unrotation) = &self.prefix_unrotation {
+ unrotation.transform.encode_fp_in_place(
+ &mut prefix_hidden,
+ &*unrotation.factors,
+ None,
+ depth,
+ self.target_model_dim,
+ command_buffer,
+ );
+ }
let normalized_prefix = self
.hidden_state_norm
.encode(&prefix_hidden, 0, depth, None::<&mut B::ScratchBuffer>, command_buffer)
diff --git a/crates/uzu-engine/src/engine/language_model/mod.rs b/crates/uzu-engine/src/engine/language_model/mod.rs
index e289a9549..420919bf4 100644
--- a/crates/uzu-engine/src/engine/language_model/mod.rs
+++ b/crates/uzu-engine/src/engine/language_model/mod.rs
@@ -85,7 +85,7 @@ impl<B: Backend> Engine<B> {
);
let speculator = if let Some(speculator_path) = speculator_path.as_deref() {
- DFlashTfmSpeculator::new(speculator_path, self.context.clone()).await?
+ DFlashTfmSpeculator::new(speculator_path, decoder.embedding(), self.context.clone()).await?
} else {
None
};
diff --git a/crates/uzu-engine/src/safetensors.rs b/crates/uzu-engine/src/safetensors.rs
index 3cc330c3a..a5082829e 100644
--- a/crates/uzu-engine/src/safetensors.rs
+++ b/crates/uzu-engine/src/safetensors.rs
@@ -187,6 +187,17 @@ impl<B: Backend> ParameterTree<'_, B> {
Ok(tensor)
}
+ pub fn ignore(
+ &self,
+ name: &str,
+ shape: &[u32],
+ dtype: DataType,
+ ) -> Result<(), ParameterLoaderError<B>> {
+ let tensor = self.tensor(name, shape, dtype)?;
+ tensor.read.store(true, Ordering::Relaxed);
+ Ok(())
+ }
+
pub async fn read_buffer(
&self,
name: &str,
diff --git a/crates/uzu-engine/src/speculators/dflash_tfm.rs b/crates/uzu-engine/src/speculators/dflash_tfm.rs
index ff0962ffa..f8cf89288 100644
--- a/crates/uzu-engine/src/speculators/dflash_tfm.rs
+++ b/crates/uzu-engine/src/speculators/dflash_tfm.rs
@@ -96,6 +96,7 @@ pub struct DFlashTfmSpeculator<B: Backend> {
impl<B: Backend> DFlashTfmSpeculator<B> {
pub async fn new(
model_path: &Path,
+ target_embedding: &Embedding<B>,
context: Arc<B::Context>,
) -> Result<Option<Self>, DFlashSpeculatorLoadError<B>> {
let mut shapes: HashMap<String, DFlashTfmTreeShape> =
@@ -117,13 +118,20 @@ impl<B: Backend> DFlashTfmSpeculator<B> {
let weight_loader = ParameterLoader::new(model_path.join("model.safetensors"), &*context).await?;
let speculator_tree = weight_loader.tree().subtree("speculator");
- let dflash =
- DFlash::new(data_type, &config.draft_config, &speculator_tree.subtree("draft_model"), &*context).await?;
+ let dflash = DFlash::new(
+ data_type,
+ &config.draft_config,
+ target_embedding.readout_input_hadamard_factors(),
+ &speculator_tree.subtree("draft_model"),
+ &*context,
+ )
+ .await?;
let weaver = if let Some(weaver_config) = &config.weaver_config {
Some(
Weaver::new(
config.draft_config.vocab_size,
weaver_config,
+ target_embedding.readout_input_hadamard_factors(),
&speculator_tree.subtree("weaver"),
&*context,
)
diff --git a/crates/uzu-engine/src/utils/version.rs b/crates/uzu-engine/src/utils/version.rs
index cfa9d7b85..03d9fafa0 100644
--- a/crates/uzu-engine/src/utils/version.rs
+++ b/crates/uzu-engine/src/utils/version.rs
@@ -1,2 +1,2 @@
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
-pub const TOOLCHAIN_VERSION: &str = "0.17.1";
+pub const TOOLCHAIN_VERSION: &str = "0.17.2";
diff --git a/crates/uzu-engine/unit/backends/common/kernel/mod.rs b/crates/uzu-engine/unit/backends/common/kernel/mod.rs
index 8b59accc4..46caa148b 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/mod.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/mod.rs
@@ -10,6 +10,7 @@ mod moe;
mod normalization_test;
mod pooling;
mod radix_top_k_small_test;
+mod repetition_penalty_test;
mod separable_causal_conv_test;
mod short_conv;
mod tensor_add_bias_test;
diff --git a/crates/uzu-engine/unit/backends/common/kernel/repetition_penalty_test.rs b/crates/uzu-engine/unit/backends/common/kernel/repetition_penalty_test.rs
new file mode 100644
index 000000000..4af430b4e
--- /dev/null
+++ b/crates/uzu-engine/unit/backends/common/kernel/repetition_penalty_test.rs
@@ -0,0 +1,203 @@
+use std::{collections::HashSet, fmt::Debug, ops::Range};
+
+use futures::executor::block_on;
+use half::bf16;
+use num_traits::Float;
+use uzu_engine_macros::uzu_test;
+
+use crate::{
+ backends::common::{
+ Backend, CommandBufferEncoding, CommandBufferExecutable, CommandBufferPending, Context, Kernels,
+ gpu_types::trie::TrieNode, kernel::RepetitionPenaltyKernel,
+ },
+ data_type::DataTypeRepr,
+ encodable_block::{
+ batch_topology::BatchTopology,
+ sampling::{Sampling, SamplingMethod},
+ },
+ tests::helpers::{buffer_to_vec, create_buffer_with_data, for_each_backend},
+};
+
+const VOCAB_SIZE: usize = 16;
+const TOKENS: [u32; 9] = [1, 2, 3, 2, 4, 5, 1, 6, 7];
+const PATHS: [&[u32]; 9] =
+ [&[1], &[1, 2], &[1, 2, 3], &[1, 2, 3, 2], &[1, 2, 4], &[1, 5], &[1, 5, 1], &[1, 5, 1, 6], &[1, 5, 7]];
+
+fn nodes(flat: bool) -> Vec<TrieNode> {
+ let ends = [8, 4, 3, 3, 4, 8, 7, 7, 8];
+ (0..TOKENS.len())
+ .map(|index| TrieNode {
+ trie_start: index as u32,
+ trie_end: if flat {
+ 8
+ } else {
+ ends[index]
+ },
+ height: if flat {
+ index as u32
+ } else {
+ PATHS[index].len() as u32 - 1
+ },
+ })
+ .collect()
+}
+
+fn ring(
+ history: &[u32],
+ window: usize,
+ offset: usize,
+) -> Vec<u32> {
+ let history = &history[history.len().saturating_sub(window)..];
+ let mut ring = vec![0; 2 + window];
+ ring[0] = offset as u32;
+ ring[1] = history.len() as u32;
+ for (index, &token) in history.iter().enumerate() {
+ ring[2 + (offset + index) % window] = token;
+ }
+ ring
+}
+
+fn expected<T: DataTypeRepr + Float>(
+ logits: &[T],
+ history: &[u32],
+ window: usize,
+ range: Range<usize>,
+ flat: bool,
+) -> Vec<T> {
+ let mut output = logits.to_vec();
+ for (row, index) in range.enumerate() {
+ let path = if flat {
+ &TOKENS[..=index]
+ } else {
+ PATHS[index]
+ };
+ let history: Vec<_> = history.iter().chain(path).copied().collect();
+ let tokens: HashSet<_> = history[history.len().saturating_sub(window)..].iter().copied().collect();
+ for token in tokens {
+ let offset = row * VOCAB_SIZE + token as usize;
+ let logit = logits[offset].to_f32().unwrap();
+ output[offset] = T::from(if logit > 0.0 {
+ logit / 2.0
+ } else {
+ logit * 2.0
+ })
+ .unwrap();
+ }
+ }
+ output
+}
+
+fn check_kernel<B: Backend, T: DataTypeRepr + Float + Debug>() {
+ let context = block_on(B::Context::new()).unwrap();
+ for flat in [false, true] {
+ let nodes = nodes(flat);
+ let kernel = <B::Kernels as Kernels>::RepetitionPenaltyKernel::new(&context, T::data_type(), !flat).unwrap();
+ for window in [1, 3, 4, 16] {
+ for history in [&[][..], &[8, 2][..], &[9, 1, 8, 4, 3, 2, 7, 6, 5, 2, 8, 9][..]] {
+ for offset in [0, window - 1] {
+ for range in [0..9, 3..5, 7..9] {
+ let logits: Vec<T> = (0..range.len() * VOCAB_SIZE)
+ .map(|index| T::from((index as i32 % 17 - 8) as f32 * 1.25).unwrap())
+ .collect();
+ let expected = expected(&logits, history, window, range.clone(), flat);
+ let mut output = create_buffer_with_data::<B, T>(&context, &logits);
+ let logits = create_buffer_with_data::<B, T>(&context, &logits);
+ let ring = create_buffer_with_data::<B, u32>(&context, &ring(history, window, offset));
+ let tokens = create_buffer_with_data::<B, u32>(&context, &TOKENS);
+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();
+ let trie = (!flat).then(|| command_buffer.allocate_constant_from_slice(&nodes).unwrap());
+ kernel.encode(
+ &logits,
+ &mut output,
+ &ring,
+ &tokens,
+ trie.as_ref(),
+ 2.0,
+ window as u32,
+ VOCAB_SIZE as u32,
+ range.start as u32,
+ range.len() as u32,
+ &mut command_buffer,
+ );
+ drop(trie);
+ block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
+ assert_eq!(
+ buffer_to_vec::<B, T>(&context, &output),
+ expected,
+ "flat={flat}, window={window}, history={history:?}, offset={offset}, range={range:?}",
+ );
+ }
+ }
+ }
+ }
+ }
+}
+
+fn check_sampling<B: Backend, T: DataTypeRepr + Float + Debug>() {
+ let context = block_on(B::Context::new()).unwrap();
+ let sampling = Sampling::<B>::new(VOCAB_SIZE as u32, T::data_type());
+ let method = SamplingMethod::Stochastic {
+ temperature: None,
+ top_k: Some(1),
+ top_p: None,
+ min_p: None,
+ repetition_penalty: Some(2.0),
+ suffix_repetition_length: Some(3),
+ };
+ for flat in [false, true] {
+ let nodes = nodes(flat);
+ let topology = BatchTopology::new(&nodes, flat);
+ for range in [0..9, 3..5, 7..9] {
+ let mut logits = vec![T::from(-16.0).unwrap(); range.len() * VOCAB_SIZE];
+ for row in logits.as_chunks_mut::<VOCAB_SIZE>().0 {
+ row[2] = T::from(10.0).unwrap();
+ row[5] = T::from(9.0).unwrap();
+ row[7] = T::from(8.0).unwrap();
+ }
+ let expected: Vec<_> = expected(&logits, &[2], 3, range.clone(), flat)
+ .as_chunks::<VOCAB_SIZE>()
+ .0
+ .iter()
+ .map(|row| row.iter().enumerate().max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0 as u32)
+ .collect();
+ let logits = create_buffer_with_data::<B, T>(&context, &logits);
+ let ring = create_buffer_with_data::<B, u32>(&context, &ring(&[2], 3, 2));
+ let tokens = create_buffer_with_data::<B, u32>(&context, &TOKENS);
+ let seeds = create_buffer_with_data::<B, u64>(&context, &vec![0; range.len()]);
+ let mut command_buffer = context.create_command_buffer(None, None).unwrap();
+ let output = sampling
+ .encode(
+ &logits,
+ Some(&seeds),
+ None::<&B::GlobalGpuBuffer>,
+ Some(&ring),
+ Some(&tokens),
+ &topology,
+ (range.start as u32..range.end as u32).into(),
+ &method,
+ &mut command_buffer,
+ )
+ .unwrap();
+ block_on(command_buffer.end_encoding().submit().wait_until_completed()).unwrap();
+ assert_eq!(buffer_to_vec::<B, u32>(&context, &output), expected, "flat={flat}, range={range:?}");
+ }
+ }
+}
+
+#[uzu_test]
+fn repetition_penalty_f32() {
+ for_each_backend!(|B| check_kernel::<B, f32>());
+}
+
+#[uzu_test]
+fn repetition_penalty_bf16() {
+ for_each_backend!(|B| check_kernel::<B, bf16>());
+}
+
+#[uzu_test]
+fn repetition_penalty_sampling_trie() {
+ for_each_backend!(|B| {
+ check_sampling::<B, f32>();
+ check_sampling::<B, bf16>();
+ });
+}