llama_cpp_2/context/
kv_cache.rs

1//! utilities for working with the kv cache
2
3use crate::context::LlamaContext;
4use std::ffi::c_int;
5use std::num::{NonZeroU8, TryFromIntError};
6
7/// Errors that can occur when attempting to prepare values for the kv cache
8#[derive(Debug, Eq, PartialEq, thiserror::Error)]
9#[allow(clippy::module_name_repetitions)]
10pub enum KvCacheConversionError {
11    /// Sequence id conversion to i32 failed
12    #[error("Provided sequence id is too large for a i32")]
13    SeqIdTooLarge(#[source] TryFromIntError),
14    /// Position 0 conversion to i32 failed
15    #[error("Provided start position is too large for a i32")]
16    P0TooLarge(#[source] TryFromIntError),
17    /// Position 1 conversion to i32 failed
18    #[error("Provided end position is too large for a i32")]
19    P1TooLarge(#[source] TryFromIntError),
20}
21
22impl LlamaContext<'_> {
23    /// Copy the cache from one sequence to another.
24    ///
25    /// # Parameters
26    ///
27    /// * `src` - The sequence id to copy the cache from.
28    /// * `dest` - The sequence id to copy the cache to.
29    /// * `size` - The size of the cache to copy.
30    pub fn copy_cache(&mut self, src: i32, dest: i32, size: i32) {
31        let mem = unsafe { llama_cpp_sys_2::llama_get_memory(self.context.as_ptr()) };
32        unsafe { llama_cpp_sys_2::llama_memory_seq_cp(mem, src, dest, 0, size) }
33    }
34
35    /// Copy the cache from one sequence to another.
36    ///
37    /// # Returns
38    /// A `Result` indicating whether the operation was successful.
39    ///
40    /// # Parameters
41    /// * `src` - The sequence id to copy the cache from.
42    /// * `dest` - The sequence id to copy the cache to.
43    /// * `p0` - The start position of the cache to clear. If `None`, the entire cache is copied up to `p1`.
44    /// * `p1` - The end position of the cache to clear. If `None`, the entire cache is copied starting from `p0`.
45    ///
46    /// # Errors
47    /// If either position exceeds [`i32::MAX`].
48    pub fn copy_kv_cache_seq(
49        &mut self,
50        src: i32,
51        dest: i32,
52        p0: Option<u32>,
53        p1: Option<u32>,
54    ) -> Result<(), KvCacheConversionError> {
55        let p0 = p0
56            .map_or(Ok(-1), i32::try_from)
57            .map_err(KvCacheConversionError::P0TooLarge)?;
58        let p1 = p1
59            .map_or(Ok(-1), i32::try_from)
60            .map_err(KvCacheConversionError::P1TooLarge)?;
61        let mem = unsafe { llama_cpp_sys_2::llama_get_memory(self.context.as_ptr()) };
62        unsafe { llama_cpp_sys_2::llama_memory_seq_cp(mem, src, dest, p0, p1) };
63        Ok(())
64    }
65
66    /// Clear the kv cache for the given sequence within the specified range `[p0, p1)`
67    /// Returns `false` only when partial sequence removals fail. Full sequence removals always succeed.
68    ///
69    /// # Returns
70    /// A `Result` indicating whether the operation was successful. If the sequence id or
71    /// either position exceeds the maximum i32 value, no removal is attempted and an `Err` is returned.
72    ///
73    /// # Parameters
74    /// * `src` - The sequence id to clear the cache for. If `None`, matches all sequences
75    /// * `p0` - The start position of the cache to clear. If `None`, the entire cache is cleared up to `p1`.
76    /// * `p1` - The end position of the cache to clear. If `None`, the entire cache is cleared from `p0`.
77    ///
78    /// # Errors
79    /// If the sequence id or either position exceeds [`i32::MAX`].
80    pub fn clear_kv_cache_seq(
81        &mut self,
82        src: Option<u32>,
83        p0: Option<u32>,
84        p1: Option<u32>,
85    ) -> Result<bool, KvCacheConversionError> {
86        let src = src
87            .map_or(Ok(-1), i32::try_from)
88            .map_err(KvCacheConversionError::SeqIdTooLarge)?;
89        let p0 = p0
90            .map_or(Ok(-1), i32::try_from)
91            .map_err(KvCacheConversionError::P0TooLarge)?;
92        let p1 = p1
93            .map_or(Ok(-1), i32::try_from)
94            .map_err(KvCacheConversionError::P1TooLarge)?;
95        let mem = unsafe { llama_cpp_sys_2::llama_get_memory(self.context.as_ptr()) };
96        Ok(unsafe { llama_cpp_sys_2::llama_memory_seq_rm(mem, src, p0, p1) })
97    }
98
99    /// Clear the KV cache
100    pub fn clear_kv_cache(&mut self) {
101        let mem = unsafe { llama_cpp_sys_2::llama_get_memory(self.context.as_ptr()) };
102        // clear both metadata and data buffers to match previous semantics
103        unsafe { llama_cpp_sys_2::llama_memory_clear(mem, true) }
104    }
105
106    /// Removes all tokens that do not belong to the specified sequence
107    ///
108    /// # Parameters
109    ///
110    /// * `seq_id` - The sequence id to keep
111    pub fn llama_kv_cache_seq_keep(&mut self, seq_id: i32) {
112        let mem = unsafe { llama_cpp_sys_2::llama_get_memory(self.context.as_ptr()) };
113        unsafe { llama_cpp_sys_2::llama_memory_seq_keep(mem, seq_id) }
114    }
115
116    #[allow(clippy::doc_markdown)]
117    /// Adds relative position "delta" to all tokens that belong to the specified sequence and have positions in `[p0, p1)`
118    /// If the KV cache is RoPEd, the KV data is updated accordingly:
119    ///   - lazily on next [`LlamaContext::decode`]
120    ///   - explicitly with [`Self::kv_cache_update`]
121    ///
122    /// # Returns
123    /// A `Result` indicating whether the operation was successful.
124    ///
125    /// # Parameters
126    ///
127    /// * `seq_id` - The sequence id to update
128    /// * `p0` - The start position of the cache to update. If `None`, the entire cache is updated up to `p1`.
129    /// * `p1` - The end position of the cache to update. If `None`, the entire cache is updated starting from `p0`.
130    /// * `delta` - The relative position to add to the tokens
131    ///
132    /// # Errors
133    /// If either position exceeds [`i32::MAX`].
134    pub fn kv_cache_seq_add(
135        &mut self,
136        seq_id: i32,
137        p0: Option<u32>,
138        p1: Option<u32>,
139        delta: i32,
140    ) -> Result<(), KvCacheConversionError> {
141        let p0 = p0
142            .map_or(Ok(-1), i32::try_from)
143            .map_err(KvCacheConversionError::P0TooLarge)?;
144        let p1 = p1
145            .map_or(Ok(-1), i32::try_from)
146            .map_err(KvCacheConversionError::P1TooLarge)?;
147        let mem = unsafe { llama_cpp_sys_2::llama_get_memory(self.context.as_ptr()) };
148        unsafe { llama_cpp_sys_2::llama_memory_seq_add(mem, seq_id, p0, p1, delta) };
149        Ok(())
150    }
151
152    /// Integer division of the positions by factor of `d > 1`
153    /// If the KV cache is `RoPEd`, the KV data is updated accordingly:
154    ///   - lazily on next [`LlamaContext::decode`]
155    ///   - explicitly with [`Self::kv_cache_update`]
156    ///
157    /// # Returns
158    /// A `Result` indicating whether the operation was successful.
159    ///
160    /// # Parameters
161    ///
162    /// * `seq_id` - The sequence id to update
163    /// * `p0` - The start position of the cache to update. If `None`, the entire cache is updated up to `p1`.
164    /// * `p1` - The end position of the cache to update. If `None`, the entire cache is updated starting from `p0`.
165    /// * `d` - The factor to divide the positions by
166    ///
167    /// # Errors
168    /// If either position exceeds [`i32::MAX`].
169    pub fn kv_cache_seq_div(
170        &mut self,
171        seq_id: i32,
172        p0: Option<u32>,
173        p1: Option<u32>,
174        d: NonZeroU8,
175    ) -> Result<(), KvCacheConversionError> {
176        let p0 = p0
177            .map_or(Ok(-1), i32::try_from)
178            .map_err(KvCacheConversionError::P0TooLarge)?;
179        let p1 = p1
180            .map_or(Ok(-1), i32::try_from)
181            .map_err(KvCacheConversionError::P1TooLarge)?;
182        let d = c_int::from(d.get());
183        let mem = unsafe { llama_cpp_sys_2::llama_get_memory(self.context.as_ptr()) };
184        unsafe { llama_cpp_sys_2::llama_memory_seq_div(mem, seq_id, p0, p1, d) }
185        Ok(())
186    }
187
188    /// Returns the largest position present in the KV cache for the specified sequence
189    ///
190    /// # Parameters
191    ///
192    /// * `seq_id` - The sequence id to get the max position for
193    #[must_use]
194    pub fn kv_cache_seq_pos_max(&self, seq_id: i32) -> i32 {
195        let mem = unsafe { llama_cpp_sys_2::llama_get_memory(self.context.as_ptr()) };
196        unsafe { llama_cpp_sys_2::llama_memory_seq_pos_max(mem, seq_id) }
197    }
198}