Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

grammar speculator fix

uuuvna0999646f5b9
diff --git a/crates/uzu/src/language_model/grammar.rs b/crates/uzu/src/language_model/grammar.rs
index 9d6d841fe..b968a37de 100644
--- a/crates/uzu/src/language_model/grammar.rs
+++ b/crates/uzu/src/language_model/grammar.rs
@@ -185,7 +185,10 @@ impl CompiledGrammar {
self.vocab_size,
));
}
- self.matcher.accept_token(token_id as i32);
+
+ if !self.matcher.accept_token(token_id as i32) {
+ return Err(Error::GrammarReject);
+ }
}
self.engagement_state.accept_token(token_id);
diff --git a/crates/uzu/src/language_model/language_model_generator.rs b/crates/uzu/src/language_model/language_model_generator.rs
index 20ef6409d..8119aaf15 100644
--- a/crates/uzu/src/language_model/language_model_generator.rs
+++ b/crates/uzu/src/language_model/language_model_generator.rs
@@ -274,14 +274,10 @@ impl LanguageModelGenerator {
let last_suffix_start = prefill_step_size * (prefill_steps - 1);
let suffix_root_index = (tokens_length - last_suffix_start) - 1;
- let (accepted_tokens, accepted_token_indices) =
- flat_trie.accept(&sampled_tokens[suffix_root_index..]);
-
- if let Some(compiled_grammar) = compiled_grammar.as_deref_mut() {
- for &token in &accepted_tokens {
- compiled_grammar.accept_token(token)?;
- }
- }
+ let (accepted_tokens, accepted_token_indices) = flat_trie.accept(
+ &sampled_tokens[suffix_root_index..],
+ compiled_grammar.as_deref_mut(),
+ );
self.update_cache_layers(
&accepted_token_indices
@@ -383,13 +379,7 @@ impl LanguageModelGenerator {
let sampled_tokens = self.sample(&mut state)?;
let (accepted_tokens, accepted_token_indices) =
- flat_trie.accept(&sampled_tokens);
-
- if let Some(compiled_grammar) = compiled_grammar.as_deref_mut() {
- for &token in &accepted_tokens {
- compiled_grammar.accept_token(token)?;
- }
- }
+ flat_trie.accept(&sampled_tokens, compiled_grammar.as_deref_mut());
self.update_cache_layers(&accepted_token_indices[1..], None, false);
diff --git a/crates/uzu/src/session/types/error.rs b/crates/uzu/src/session/types/error.rs
index 273d3e4ce..963e8b2bf 100644
--- a/crates/uzu/src/session/types/error.rs
+++ b/crates/uzu/src/session/types/error.rs
@@ -42,6 +42,8 @@ pub enum Error {
SamplingFailed,
#[error("Grammar error")]
GrammarError,
+ #[error("Grammar rejected the token")]
+ GrammarReject,
#[error("Token {0} out of grammar vocabulary range (0..{1})")]
TokenOutOfGrammarRange(u64, usize),
#[error("Classifier error: {0}")]
diff --git a/crates/uzu/src/trie.rs b/crates/uzu/src/trie.rs
index 0fcdbca88..1bd28cf4d 100644
--- a/crates/uzu/src/trie.rs
+++ b/crates/uzu/src/trie.rs
@@ -247,6 +247,7 @@ impl<'a> FlatTrie<'a> {
pub fn accept(
&self,
sampled_tokens: &[u64],
+ mut compiled_grammar: Option<&mut CompiledGrammar>,
) -> (Vec<u64>, Vec<usize>) {
let mut current_token = self.root().unwrap();
let mut accepted_tokens = Vec::new();
@@ -257,11 +258,23 @@ impl<'a> FlatTrie<'a> {
accepted_token_indices.push(current_token_index);
accepted_tokens.push(current_token_id);
+ if let Some(compiled_grammar) = compiled_grammar.as_deref_mut()
+ && !compiled_grammar.is_terminated()
+ {
+ compiled_grammar.accept_token(current_token_id).unwrap();
+ }
let Some(next_token) = current_token.get(current_token_id) else {
break;
};
+ if let Some(compiled_grammar) = compiled_grammar.as_deref_mut() {
+ assert!(
+ !compiled_grammar.is_terminated(),
+ "Grammar has terminated but llm continued generation"
+ );
+ }
+
current_token = next_token;
}
diff --git a/crates/uzu/tests/common/mod.rs b/crates/uzu/tests/common/mod.rs
index 1c1f9b325..e912e4743 100644
--- a/crates/uzu/tests/common/mod.rs
+++ b/crates/uzu/tests/common/mod.rs
@@ -1,7 +1,9 @@
#![allow(dead_code)]
-use std::path::PathBuf;
+
+use std::{collections::HashMap, path::PathBuf};
use uzu::VERSION;
+use uzu::speculators::speculator::Speculator;
pub const MODEL_DIR_NAME: &str = "Llama-3.2-1B-Instruct";
pub const MODEL_FILE_NAME: &str = "model.safetensors";
@@ -30,3 +32,56 @@ pub fn get_test_weights_path() -> PathBuf {
pub fn get_traces_path() -> PathBuf {
get_test_model_path().join(TRACES_FILE_NAME)
}
+
+pub struct StaticSpeculator {
+ responses: HashMap<Vec<u64>, HashMap<u64, f32>>,
+ default_response: Option<HashMap<u64, f32>>,
+}
+
+impl StaticSpeculator {
+ pub fn new(responses: HashMap<Vec<u64>, HashMap<u64, f32>>) -> Self {
+ Self {
+ responses,
+ default_response: None,
+ }
+ }
+
+ pub fn with_default_response(default_response: HashMap<u64, f32>) -> Self {
+ Self {
+ responses: HashMap::new(),
+ default_response: Some(default_response),
+ }
+ }
+}
+
+impl Speculator for StaticSpeculator {
+ fn speculate(
+ &self,
+ prefix: &[u64],
+ ) -> HashMap<u64, f32> {
+ self.responses
+ .get(prefix)
+ .cloned()
+ .or_else(|| self.default_response.clone())
+ .unwrap_or_default()
+ }
+}
+
+pub struct RepeatSpeculator;
+
+impl Speculator for RepeatSpeculator {
+ fn speculate(
+ &self,
+ prefix: &[u64],
+ ) -> HashMap<u64, f32> {
+ let mut hm = HashMap::new();
+
+ for (pos, token) in prefix.iter().copied().enumerate() {
+ *hm.entry(token).or_insert(0.0) += f32::sqrt((1 + pos) as f32);
+ }
+
+ let sum = hm.values().sum::<f32>();
+
+ hm.into_iter().map(|(pos, weight)| (pos, weight / sum)).collect()
+ }
+}
diff --git a/crates/uzu/tests/grammar_json_schema_test.rs b/crates/uzu/tests/grammar_json_schema_test.rs
index b9cc284c6..8621f613a 100644
--- a/crates/uzu/tests/grammar_json_schema_test.rs
+++ b/crates/uzu/tests/grammar_json_schema_test.rs
@@ -1,12 +1,14 @@
#![cfg(target_os = "macos")]
-use std::path::PathBuf;
+use std::sync::Arc;
+mod common;
+use common::{RepeatSpeculator, get_test_model_path};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use uzu::session::{
Session,
- config::{DecodingConfig, GrammarConfig, RunConfig},
+ config::{DecodingConfig, GrammarConfig, RunConfig, SpeculatorConfig},
parameter::SamplingPolicy,
types::Input,
};
@@ -28,16 +30,8 @@ struct Person {
hobbies: Vec<String>,
}
-#[test]
-#[ignore = "Test requires model; run manually with RUST_TEST_THREADS=1"]
-fn test_grammar_json_schema() {
- let crate_version = env!("CARGO_PKG_VERSION");
- let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
- let repo_root = manifest_dir.parent().unwrap().parent().unwrap();
- let model_dir = repo_root
- .join("models")
- .join(crate_version)
- .join("Llama-3.2-1B-Instruct");
+fn test_grammar(speculator_config: SpeculatorConfig) {
+ let model_dir = get_test_model_path();
if !model_dir.exists() {
eprintln!(
@@ -47,7 +41,9 @@ fn test_grammar_json_schema() {
return;
}
- let decoding_config = DecodingConfig::default();
+ let decoding_config = DecodingConfig::default()
+ .with_sampling_seed(uzu::prelude::SamplingSeed::Custom(42))
+ .with_speculator_config(speculator_config);
let mut session = Session::new(model_dir, decoding_config)
.expect("Failed to create session");
@@ -55,23 +51,13 @@ fn test_grammar_json_schema() {
"Generate a detailed person profile with address and hobbies in JSON format.".to_string(),
);
- let grammar_config_simple =
- GrammarConfig::from_json_schema_type::<Person>()
- .expect("Failed to create grammar config");
-
- let _grammar_config_advanced =
- GrammarConfig::from_json_schema_type_with_config::<Person>(
- true,
- Some(4),
- Some((",".to_string(), ": ".to_string())),
- true,
- )
+ let grammar_config = GrammarConfig::from_json_schema_type::<Person>()
.expect("Failed to create grammar config");
let run_config = RunConfig::default()
- .tokens_limit(1000)
+ .tokens_limit(1024)
.sampling_policy(SamplingPolicy::Default)
- .grammar_config(grammar_config_simple);
+ .grammar_config(grammar_config);
let output = session
.run(input, run_config, None::<fn(uzu::session::types::Output) -> bool>)
@@ -120,3 +106,17 @@ fn test_grammar_json_schema() {
},
}
}
+
+#[test]
+fn test_grammar_json_schema() {
+ test_grammar(SpeculatorConfig::default());
+}
+
+#[test]
+#[ignore = "still broken (?)"]
+fn test_grammar_json_schema_with_speculator() {
+ test_grammar(SpeculatorConfig {
+ number_of_speculated_tokens: 16,
+ speculator: Arc::new(RepeatSpeculator),
+ });
+}
diff --git a/crates/uzu/tests/trie_test.rs b/crates/uzu/tests/trie_test.rs
index 4d3b970ed..49a9fb099 100644
--- a/crates/uzu/tests/trie_test.rs
+++ b/crates/uzu/tests/trie_test.rs
@@ -2,30 +2,12 @@ use std::collections::{HashMap, HashSet};
use uzu::{
language_model::rng::DerivableSeed,
- speculators::{empty_speculator::EmptySpeculator, speculator::Speculator},
+ speculators::empty_speculator::EmptySpeculator,
trie::{TrieCreationConfig, TrieNode},
};
-struct StaticSpeculator {
- responses: HashMap<Vec<u64>, HashMap<u64, f32>>,
-}
-
-impl StaticSpeculator {
- fn new(responses: HashMap<Vec<u64>, HashMap<u64, f32>>) -> Self {
- Self {
- responses,
- }
- }
-}
-
-impl Speculator for StaticSpeculator {
- fn speculate(
- &self,
- prefix: &[u64],
- ) -> HashMap<u64, f32> {
- self.responses.get(prefix).cloned().unwrap_or_default()
- }
-}
+mod common;
+use common::StaticSpeculator;
fn verify_sprout(
trie_root: &TrieNode,