Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Hotfix support ring KV caches for noncausal attention (#775)

uuuvn1f190fb8c409
diff --git a/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs b/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs
index 56abbb3c9..646a190b4 100644
--- a/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs
+++ b/crates/uzu-engine/src/encodable_block/mixer/attention/state.rs
@@ -95,20 +95,12 @@ impl KVCacheState {
) -> u32 {
match self {
Self::Full {
- length,
- } => {
- assert_eq!(*length, context_length, "cache length mismatch");
- context_length
- },
+ ..
+ } => context_length,
Self::Ring {
- length,
capacity,
..
- } => {
- let required = context_length.min(*capacity);
- assert_eq!(*length, required, "cache length mismatch");
- required
- },
+ } => context_length.min(*capacity),
}
}
@@ -142,12 +134,14 @@ impl KVCacheState {
length,
capacity,
} => {
- assert!(accepted_indices.len() as u32 <= *capacity, "accept exceeds ring capacity");
- let mut copies = Vec::with_capacity(accepted_indices.len());
- for accepted_index in accepted_indices {
- let source = suffix_base + *accepted_index;
+ let count = accepted_indices.len() as u32;
+ let mut copies = Vec::with_capacity(accepted_indices.len().min(*capacity as usize));
+ for (index, accepted_index) in accepted_indices.iter().copied().enumerate() {
+ let source = suffix_base + accepted_index;
let destination = (*offset + *length) % *capacity;
- if source != destination {
+ // A copy is dead when a later accept in the same batch overwrites its
+ // destination; emitting it would alias in a single kernel dispatch.
+ if index as u32 + *capacity >= count && source != destination {
copies.push(Copy {
source,
destination,
diff --git a/crates/uzu-engine/unit/encodable_block/kv_cache_state_test.rs b/crates/uzu-engine/unit/encodable_block/kv_cache_state_test.rs
index 51cc00745..8dab1f22a 100644
--- a/crates/uzu-engine/unit/encodable_block/kv_cache_state_test.rs
+++ b/crates/uzu-engine/unit/encodable_block/kv_cache_state_test.rs
@@ -23,3 +23,17 @@ fn ring_accepts_append_then_wrap() {
assert_eq!(state.view().ring_params().unwrap().ring_offset, 1);
assert_eq!(state.required_prefix_len(99), 2);
}
+
+#[uzu_test]
+fn ring_accept_over_capacity_keeps_last() {
+ let mut state = KVCacheState::ring(2);
+
+ // Only the last `capacity` tokens survive; earlier copies are dead.
+ assert_eq!(accept(&mut state, &[0, 1, 2]), [(2, 0)]);
+ assert_eq!(state.view().prefix_len(), 2);
+ assert_eq!(state.view().ring_params().unwrap().ring_offset, 1);
+
+ // Same with a wrapped ring: destinations keep rotating.
+ assert_eq!(accept(&mut state, &[0, 1, 2]), [(3, 0), (4, 1)]);
+ assert_eq!(state.view().ring_params().unwrap().ring_offset, 0);
+}