Skip to content

Commit b9c9506

Browse files
authored
Merge pull request #112 from zh217/main
Expose functions `llama_load_session_file` and `llama_save_session_file`
2 parents 1c2306f + 1a37ca0 commit b9c9506

File tree

2 files changed

+92
-0
lines changed

2 files changed

+92
-0
lines changed

llama-cpp-2/src/context.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use std::slice;
1515
pub mod kv_cache;
1616
pub mod params;
1717
pub mod sample;
18+
pub mod session;
1819

1920
/// Safe wrapper around `llama_context`.
2021
#[allow(clippy::module_name_repetitions)]

llama-cpp-2/src/context/session.rs

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
//! utilities for working with session files
2+
3+
use std::ffi::{CString, NulError};
4+
use std::path::{Path, PathBuf};
5+
use crate::context::LlamaContext;
6+
use crate::token::LlamaToken;
7+
8+
#[derive(Debug, Eq, PartialEq, thiserror::Error)]
9+
pub enum SaveSessionError {
10+
#[error("Failed to save session file")]
11+
FailedToSave,
12+
13+
#[error("null byte in string {0}")]
14+
NullError(#[from] NulError),
15+
16+
#[error("failed to convert path {0} to str")]
17+
PathToStrError(PathBuf),
18+
}
19+
20+
#[derive(Debug, Eq, PartialEq, thiserror::Error)]
21+
pub enum LoadSessionError {
22+
#[error("Failed to load session file")]
23+
FailedToLoad,
24+
25+
#[error("null byte in string {0}")]
26+
NullError(#[from] NulError),
27+
28+
#[error("failed to convert path {0} to str")]
29+
PathToStrError(PathBuf),
30+
}
31+
32+
impl LlamaContext<'_> {
33+
/// Save the current session to a file.
34+
///
35+
/// # Parameters
36+
///
37+
/// * `path_session` - The file to save to.
38+
/// * `tokens` - The tokens to associate the session with. This should be a prefix of a sequence of tokens that the context has processed, so that the relevant KV caches are already filled.
39+
pub fn save_session_file(&self, path_session: impl AsRef<Path>, tokens: &[LlamaToken]) -> Result<(), SaveSessionError> {
40+
let path = path_session.as_ref();
41+
let path = path
42+
.to_str()
43+
.ok_or(SaveSessionError::PathToStrError(path.to_path_buf()))?;
44+
45+
let cstr = CString::new(path)?;
46+
47+
if unsafe {
48+
llama_cpp_sys_2::llama_save_session_file(
49+
self.context.as_ptr(),
50+
cstr.as_ptr(),
51+
tokens.as_ptr() as *const i32,
52+
tokens.len())
53+
} {
54+
Ok(())
55+
} else {
56+
Err(SaveSessionError::FailedToSave)
57+
}
58+
}
59+
/// Load a session file into the current context.
60+
///
61+
/// You still need to pass the returned tokens to the context for inference to work. What this function buys you is that the KV caches are already filled with the relevant data.
62+
///
63+
/// # Parameters
64+
///
65+
/// * `path_session` - The file to load from. It must be a session file from a compatible context, otherwise the function will error.
66+
/// * `max_tokens` - The maximum token length of the loaded session. If the session was saved with a longer length, the function will error.
67+
pub fn load_session_file(&mut self, path_session: impl AsRef<Path>, max_tokens: usize) -> Result<Vec<LlamaToken>, LoadSessionError> {
68+
let path = path_session.as_ref();
69+
let path = path
70+
.to_str()
71+
.ok_or(LoadSessionError::PathToStrError(path.to_path_buf()))?;
72+
73+
let cstr = CString::new(path)?;
74+
let mut tokens = Vec::with_capacity(max_tokens);
75+
let mut n_out = 0;
76+
77+
unsafe {
78+
if llama_cpp_sys_2::llama_load_session_file(
79+
self.context.as_ptr(),
80+
cstr.as_ptr(),
81+
tokens.as_mut_ptr() as *mut i32,
82+
max_tokens,
83+
&mut n_out) {
84+
tokens.set_len(n_out);
85+
Ok(tokens)
86+
} else {
87+
Err(LoadSessionError::FailedToLoad)
88+
}
89+
}
90+
}
91+
}

0 commit comments

Comments
 (0)