A high-performance inference engine for AI models
Add changing sampling seed (#1087)
Aleksandr Golokoz628c12b3e3d0
diff --git a/README.md b/README.mdindex 540a36077..126cb6ce8 100644--- a/README.md+++ b/README.md@@ -1485,7 +1485,7 @@ cargo run --release -p cli -- server --model trymirai/Qwen3.5-4B-M --host 0.0.0.It exposes the following endpoints, available both at the root and under `/v1`:-- `POST /v1/chat/completions` — chat completions, with streaming when `"stream": true`. Honors `temperature`, `top_p`, `top_k`, and `max_tokens`.+- `POST /v1/chat/completions` — chat completions, with streaming when `"stream": true`. Honors `temperature`, `top_p`, `top_k`, `max_tokens`, and `seed`. Requests without a `seed` use the one passed with `--seed`, or a random one.- `GET /v1/models` — lists the loaded model.```bashdiff --git a/crates/legacy/cli-tools/readme/template.md b/crates/legacy/cli-tools/readme/template.mdindex 45c1a1d1f..868ed754a 100644--- a/crates/legacy/cli-tools/readme/template.md+++ b/crates/legacy/cli-tools/readme/template.md@@ -133,7 +133,7 @@ cargo run --release -p cli -- server --model trymirai/Qwen3.5-4B-M --host 0.0.0.It exposes the following endpoints, available both at the root and under `/v1`:-- `POST /v1/chat/completions` — chat completions, with streaming when `"stream": true`. Honors `temperature`, `top_p`, `top_k`, and `max_tokens`.+- `POST /v1/chat/completions` — chat completions, with streaming when `"stream": true`. Honors `temperature`, `top_p`, `top_k`, `max_tokens`, and `seed`. Requests without a `seed` use the one passed with `--seed`, or a random one.- `GET /v1/models` — lists the loaded model.```bashdiff --git a/crates/legacy/cli/src/main.rs b/crates/legacy/cli/src/main.rsindex 99a73219a..fec124910 100644--- a/crates/legacy/cli/src/main.rs+++ b/crates/legacy/cli/src/main.rs@@ -21,8 +21,8 @@ struct Cli {/// Overrides the saved preference for this run only; never persisted.#[arg(long, value_name = "EFFORT")]reasoning_effort: Option<ReasoningEffort>,- /// Sampling seed for chat sessions.- #[arg(long, value_name = "SEED", allow_negative_numbers = true)]+ /// Sampling seed for chat sessions. In server mode, the seed for requests that don't set `seed`.+ #[arg(long, value_name = "SEED", allow_negative_numbers = true, global = true)]seed: Option<i64>,/// Disable built-in tools in interactive chat sessions.#[arg(long)]@@ -89,7 +89,9 @@ async fn main() -> Result<()> {prefix_cache,no_prefix_cache,verbose_file_log,- }) => server::run_server(model, host, port, prefix_cache || !no_prefix_cache, verbose_file_log).await?,+ }) => {+ server::run_server(model, host, port, prefix_cache || !no_prefix_cache, verbose_file_log, cli.seed).await?+ },Some(Commands::Storage {download_manager,}) => storage::run(download_manager).await?,diff --git a/crates/legacy/cli/src/server/chat_completions.rs b/crates/legacy/cli/src/server/chat_completions.rsindex 7ad50a36f..e2621b392 100644--- a/crates/legacy/cli/src/server/chat_completions.rs+++ b/crates/legacy/cli/src/server/chat_completions.rs@@ -19,7 +19,7 @@ use tracing::Instrument;use uzu::{session::chat::{ChatSession, ChatSessionError, ChatSessionStream, ChatSessionStreamChunk, UNPARSED_ARGUMENTS_KEY},types::{- basic::{BackendError, Grammar, ReasoningEffort, SamplingMethod},+ basic::{BackendError, Grammar, ReasoningEffort, SamplingMethod, SamplingSeed},session::chat::{ChatContentBlock, ChatMessage, ChatReplyConfig, ChatReplyFinishReason, ChatReplyStats, ChatRole,},@@ -104,6 +104,8 @@ pub struct ChatCompletionRequest {pub top_p: Option<f64>,#[serde(default)]pub top_k: Option<i64>,+ #[serde(default)]+ pub seed: Option<i64>,// Raw value (not typed) so a bad response_format is our 400, not Rocket's 422.#[serde(default)]pub response_format: Option<serde_json::Value>,@@ -553,6 +555,11 @@ fn build_reply_config(request: &ChatCompletionRequest) -> Result<ChatReplyConfigsuffix_repetition_length: None,});}+ if let Some(seed) = request.seed {+ config = config.with_sampling_seed(SamplingSeed::Custom {+ seed,+ });+ }let response_format = match &request.response_format {Some(value) => Some(diff --git a/crates/legacy/cli/src/server/runner.rs b/crates/legacy/cli/src/server/runner.rsindex ff374c788..809416c54 100644--- a/crates/legacy/cli/src/server/runner.rs+++ b/crates/legacy/cli/src/server/runner.rs@@ -6,7 +6,7 @@ use rocket::{Config, config::LogLevel, routes};use tokio::sync::Mutex;use uzu::{engine::{Engine, EngineConfig},- types::{model::ModelSpecialization, session::chat::ChatConfig},+ types::{basic::SamplingSeed, model::ModelSpecialization, session::chat::ChatConfig},};use crate::{@@ -24,6 +24,7 @@ pub async fn run_server(port: u16,prefix_cache: bool,verbose_file_logs: bool,+ seed: Option<i64>,) -> Result<()> {let file_logger = if verbose_file_logs {let cache_dir = std::env::var_os("XDG_CACHE_HOME")@@ -85,7 +86,12 @@ pub async fn run_server((rocket, "System One server", details.to_string())} else {let thinking_support = ThinkingSupport::for_model(&resolved);- let session = engine.chat(resolved, ChatConfig::default()).await.context("Failed to create chat session")?;+ let chat_config = seed.map_or_else(ChatConfig::default, |seed| {+ ChatConfig::default().with_sampling_seed(SamplingSeed::Custom {+ seed,+ })+ });+ let session = engine.chat(resolved, chat_config).await.context("Failed to create chat session")?;let state = ChatState {session: Arc::new(Mutex::new(session)),thinking_support,diff --git a/crates/legacy/cli/unit/server/chat_completions_test.rs b/crates/legacy/cli/unit/server/chat_completions_test.rsindex 499465468..8131fddf5 100644--- a/crates/legacy/cli/unit/server/chat_completions_test.rs+++ b/crates/legacy/cli/unit/server/chat_completions_test.rs@@ -20,6 +20,34 @@ fn response_format_maps_to_grammar() {);}+#[test]+fn seed_maps_to_reply_sampling_seed() {+ assert_eq!(reply_config(r#"{"messages":[]}"#).sampling_seed, SamplingSeed::Default {});+ assert_eq!(+ reply_config(r#"{"messages":[],"seed":42}"#).sampling_seed,+ SamplingSeed::Custom {+ seed: 42+ }+ );+ assert_eq!(+ reply_config(r#"{"messages":[],"seed":-7}"#).sampling_seed,+ SamplingSeed::Custom {+ seed: -7+ }+ );+ // A seed alone leaves the model's default sampling in place.+ assert_eq!(+ reply_config(r#"{"messages":[],"seed":42}"#).sampling_policy,+ uzu::types::basic::SamplingPolicy::Default {}+ );+}++#[test]+fn seed_must_be_an_integer() {+ assert!(serde_json::from_str::<ChatCompletionRequest>(r#"{"messages":[],"seed":1.5}"#).is_err());+ assert!(serde_json::from_str::<ChatCompletionRequest>(r#"{"messages":[],"seed":"42"}"#).is_err());+}+#[test]fn response_format_unrecognized_is_invalid() {let error = build_reply_config(&request(r#"{"messages":[],"response_format":{"type":"totally-bogus"}}"#))diff --git a/crates/legacy/shoji/src/types/session/chat/reply/config.rs b/crates/legacy/shoji/src/types/session/chat/reply/config.rsindex 531e8d970..8e6aa172e 100644--- a/crates/legacy/shoji/src/types/session/chat/reply/config.rs+++ b/crates/legacy/shoji/src/types/session/chat/reply/config.rs@@ -1,6 +1,6 @@use serde::{Deserialize, Serialize};-use crate::types::basic::{Grammar, SamplingMethod, SamplingPolicy};+use crate::types::basic::{Grammar, SamplingMethod, SamplingPolicy, SamplingSeed};#[bindings::export(Structure(Class))]#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]@@ -11,6 +11,8 @@ pub struct ChatReplyConfig {/// Maximum number of automatic tool-call turns per reply./// `None` allows unlimited turns; `Some(0)` prevents automatic tool execution.pub tool_turn_limit: Option<u32>,+ /// Seed for this reply only. `Default` keeps the session's seed from `ChatConfig`.+ pub sampling_seed: SamplingSeed,}#[bindings::export(Implementation)]@@ -79,4 +81,15 @@ impl ChatReplyConfig {..self.clone()}}++ #[bindings::export(Method)]+ pub fn with_sampling_seed(+ &self,+ sampling_seed: SamplingSeed,+ ) -> Self {+ Self {+ sampling_seed,+ ..self.clone()+ }+ }}diff --git a/crates/legacy/uzu/bindings/python/uzu/__init__.pyi b/crates/legacy/uzu/bindings/python/uzu/__init__.pyiindex 0da35d2a6..fd0478b8e 100644--- a/crates/legacy/uzu/bindings/python/uzu/__init__.pyi+++ b/crates/legacy/uzu/bindings/python/uzu/__init__.pyi@@ -370,7 +370,12 @@ class ChatReplyConfig:Maximum number of automatic tool-call turns per reply.`None` allows unlimited turns; `Some(0)` prevents automatic tool execution."""- def __new__(cls, token_limit: typing.Optional[builtins.int], sampling_policy: SamplingPolicy, grammar: typing.Optional[Grammar], tool_turn_limit: typing.Optional[builtins.int]) -> ChatReplyConfig: ...+ @property+ def sampling_seed(self) -> SamplingSeed:+ r"""+ Seed for this reply only. `Default` keeps the session's seed from `ChatConfig`.+ """+ def __new__(cls, token_limit: typing.Optional[builtins.int], sampling_policy: SamplingPolicy, grammar: typing.Optional[Grammar], tool_turn_limit: typing.Optional[builtins.int], sampling_seed: SamplingSeed) -> ChatReplyConfig: ...@staticmethoddef create() -> ChatReplyConfig: ...def with_token_limit(self, token_limit: typing.Optional[builtins.int]) -> ChatReplyConfig: ...@@ -378,6 +383,7 @@ class ChatReplyConfig:def with_sampling_method(self, sampling_method: SamplingMethod) -> ChatReplyConfig: ...def with_tool_turn_limit(self, tool_turn_limit: typing.Optional[builtins.int]) -> ChatReplyConfig: ...def with_grammar(self, grammar: typing.Optional[Grammar]) -> ChatReplyConfig: ...+ def with_sampling_seed(self, sampling_seed: SamplingSeed) -> ChatReplyConfig: ...class ChatReplyJoulesPerToken:@typing.finaldiff --git a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swiftindex 7f27391fe..217677c84 100644--- a/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift+++ b/crates/legacy/uzu/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift@@ -1075,6 +1075,10 @@ public struct ChatReplyConfig: Equatable, Hashable, Codable {* `None` allows unlimited turns; `Some(0)` prevents automatic tool execution.*/public var toolTurnLimit: UInt32?+ /**+ * Seed for this reply only. `Default` keeps the session's seed from `ChatConfig`.+ */+ public var samplingSeed: SamplingSeed// Default memberwise initializers are never public by default, so we// declare one manually.@@ -1082,11 +1086,15 @@ public struct ChatReplyConfig: Equatable, Hashable, Codable {/*** Maximum number of automatic tool-call turns per reply.* `None` allows unlimited turns; `Some(0)` prevents automatic tool execution.- */toolTurnLimit: UInt32?) {+ */toolTurnLimit: UInt32?,+ /**+ * Seed for this reply only. `Default` keeps the session's seed from `ChatConfig`.+ */samplingSeed: SamplingSeed) {self.tokenLimit = tokenLimitself.samplingPolicy = samplingPolicyself.grammar = grammarself.toolTurnLimit = toolTurnLimit+ self.samplingSeed = samplingSeed}@@ -1117,6 +1125,15 @@ public func withSamplingPolicy(samplingPolicy: SamplingPolicy) -> ChatReplyConfi})}+public func withSamplingSeed(samplingSeed: SamplingSeed) -> ChatReplyConfig {+ return try! FfiConverterTypeChatReplyConfig_lift(try! rustCall() {+ uniffi_shoji_fn_method_chatreplyconfig_with_sampling_seed(+ FfiConverterTypeChatReplyConfig_lower(self),+ FfiConverterTypeSamplingSeed_lower(samplingSeed),$0+ )+})+}+public func withTokenLimit(tokenLimit: UInt32?) -> ChatReplyConfig {return try! FfiConverterTypeChatReplyConfig_lift(try! rustCall() {uniffi_shoji_fn_method_chatreplyconfig_with_token_limit(@@ -1153,7 +1170,8 @@ public struct FfiConverterTypeChatReplyConfig: FfiConverterRustBuffer {tokenLimit: FfiConverterOptionUInt32.read(from: &buf),samplingPolicy: FfiConverterTypeSamplingPolicy.read(from: &buf),grammar: FfiConverterOptionTypeGrammar.read(from: &buf),- toolTurnLimit: FfiConverterOptionUInt32.read(from: &buf)+ toolTurnLimit: FfiConverterOptionUInt32.read(from: &buf),+ samplingSeed: FfiConverterTypeSamplingSeed.read(from: &buf))}@@ -1162,6 +1180,7 @@ public struct FfiConverterTypeChatReplyConfig: FfiConverterRustBuffer {FfiConverterTypeSamplingPolicy.write(value.samplingPolicy, into: &buf)FfiConverterOptionTypeGrammar.write(value.grammar, into: &buf)FfiConverterOptionUInt32.write(value.toolTurnLimit, into: &buf)+ FfiConverterTypeSamplingSeed.write(value.samplingSeed, into: &buf)}}diff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mtsindex b05861339..38aa77b44 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.mts@@ -366,7 +366,9 @@ export declare class ChatReplyConfig {* `None` allows unlimited turns; `Some(0)` prevents automatic tool execution.*/toolTurnLimit?: number- constructor(tokenLimit?: number, samplingPolicy: SamplingPolicy, grammar?: Grammar, toolTurnLimit?: number)+ /** Seed for this reply only. `Default` keeps the session's seed from `ChatConfig`. */+ samplingSeed: SamplingSeed+ constructor(tokenLimit?: number, samplingPolicy: SamplingPolicy, grammar?: Grammar, toolTurnLimit?: number, samplingSeed: SamplingSeed)static create(): ChatReplyConfigwithTokenLimit(tokenLimit?: number | undefined | null): ChatReplyConfig@@ -374,6 +376,7 @@ export declare class ChatReplyConfig {withSamplingMethod(samplingMethod: SamplingMethod): ChatReplyConfigwithToolTurnLimit(toolTurnLimit?: number | undefined | null): ChatReplyConfigwithGrammar(grammar?: Grammar | undefined | null): ChatReplyConfig+ withSamplingSeed(samplingSeed: SamplingSeed): ChatReplyConfig}export declare class ChatReplyJoulesPerTokenComponents {diff --git a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.tsindex b05861339..38aa77b44 100644--- a/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts+++ b/crates/legacy/uzu/bindings/typescript/src/napi/index.d.ts@@ -366,7 +366,9 @@ export declare class ChatReplyConfig {* `None` allows unlimited turns; `Some(0)` prevents automatic tool execution.*/toolTurnLimit?: number- constructor(tokenLimit?: number, samplingPolicy: SamplingPolicy, grammar?: Grammar, toolTurnLimit?: number)+ /** Seed for this reply only. `Default` keeps the session's seed from `ChatConfig`. */+ samplingSeed: SamplingSeed+ constructor(tokenLimit?: number, samplingPolicy: SamplingPolicy, grammar?: Grammar, toolTurnLimit?: number, samplingSeed: SamplingSeed)static create(): ChatReplyConfigwithTokenLimit(tokenLimit?: number | undefined | null): ChatReplyConfig@@ -374,6 +376,7 @@ export declare class ChatReplyConfig {withSamplingMethod(samplingMethod: SamplingMethod): ChatReplyConfigwithToolTurnLimit(toolTurnLimit?: number | undefined | null): ChatReplyConfigwithGrammar(grammar?: Grammar | undefined | null): ChatReplyConfig+ withSamplingSeed(samplingSeed: SamplingSeed): ChatReplyConfig}export declare class ChatReplyJoulesPerTokenComponents {diff --git a/crates/legacy/uzu/src/engine/bridge/chat_token_backend.rs b/crates/legacy/uzu/src/engine/bridge/chat_token_backend.rsindex b485793e5..00c5e1c15 100644--- a/crates/legacy/uzu/src/engine/bridge/chat_token_backend.rs+++ b/crates/legacy/uzu/src/engine/bridge/chat_token_backend.rs@@ -102,7 +102,7 @@ impl<B: Backend> BackendInstance for UzuChatTokenBackendInstance<B> {self.model.create_empty_state(self.max_context_length, sampling_seed).map_err(|err| ShojiBackendError::from(err.to_string()))- .map(|state| Box::new(UzuChatTokenBackendInstanceState::new(state)) as Box<dyn State>)+ .map(|state| Box::new(UzuChatTokenBackendInstanceState::new(state, sampling_seed)) as Box<dyn State>)})}@@ -141,6 +141,14 @@ impl<B: Backend> BackendInstance for UzuChatTokenBackendInstance<B> {None};+ let model_state = state.value.get_mut();+ model_state.set_sampling_seed(match config.sampling_seed {+ SamplingSeed::Default {} => state.sampling_seed,+ SamplingSeed::Custom {+ seed,+ } => seed as u64,+ });+let sampling_method = match get_sampling_method::<B>(&self.model, &config.sampling_policy) {Ok(sampling_method) => sampling_method,Err(err) => {@@ -152,7 +160,7 @@ impl<B: Backend> BackendInstance for UzuChatTokenBackendInstance<B> {options.sampling_method = sampling_method;options.grammar = grammar;- let stream = match self.model.stream(input, state.value.get_mut(), options) {+ let stream = match self.model.stream(input, model_state, options) {Ok(stream) => stream,Err(err) => {return Box::pin(NoMetricsStream::new(error_to_stream_output(stream_error_to_backend_error(err))));diff --git a/crates/legacy/uzu/src/engine/bridge/chat_token_state.rs b/crates/legacy/uzu/src/engine/bridge/chat_token_state.rsindex 01f9bd8f2..93c97e7ed 100644--- a/crates/legacy/uzu/src/engine/bridge/chat_token_state.rs+++ b/crates/legacy/uzu/src/engine/bridge/chat_token_state.rs@@ -4,12 +4,17 @@ use uzu_engine::{backends::Backend, engine::language_model::state::LanguageModelpub struct UzuChatTokenBackendInstanceState<B: Backend> {pub value: Mutex<LanguageModelState<B>>,+ pub sampling_seed: u64,}impl<B: Backend> UzuChatTokenBackendInstanceState<B> {- pub fn new(value: LanguageModelState<B>) -> Self {+ pub fn new(+ value: LanguageModelState<B>,+ sampling_seed: u64,+ ) -> Self {Self {value: Mutex::new(value),+ sampling_seed,}}}diff --git a/crates/legacy/uzu/tests/test_engine.rs b/crates/legacy/uzu/tests/test_engine.rsindex 9bef887bf..077fb6668 100644--- a/crates/legacy/uzu/tests/test_engine.rs+++ b/crates/legacy/uzu/tests/test_engine.rs@@ -2,10 +2,13 @@use uzu::{engine::{Engine, EngineConfig},- session::chat::ChatSessionStreamChunk,- types::session::{- chat::{ChatConfig, ChatMessage, ChatReplyConfig},- classification::ClassificationMessage,+ session::chat::{ChatSession, ChatSessionStreamChunk},+ types::{+ basic::{ReasoningEffort, SamplingMethod, SamplingSeed},+ session::{+ chat::{ChatConfig, ChatContentBlock, ChatMessage, ChatReplyConfig},+ classification::ClassificationMessage,+ },},};@@ -97,6 +100,76 @@ async fn test_engine_chat() {}}+async fn reply_content(+ session: &ChatSession,+ messages: Vec<ChatMessage>,+ config: ChatReplyConfig,+) -> Vec<ChatContentBlock> {+ let replies = session.reply(messages, config).await.unwrap();+ replies.last().unwrap().message.content.clone()+}++async fn fresh_reply(+ session: &ChatSession,+ config: ChatReplyConfig,+) -> Vec<ChatContentBlock> {+ session.reset().await.unwrap();+ // Without thinking, so the sample isn't spent on the model's fixed reasoning preamble.+ let messages = vec![+ ChatMessage::system().with_reasoning_effort(ReasoningEffort::Disabled),+ ChatMessage::user().with_text("Write one sentence about a random animal.".to_string()),+ ];+ reply_content(session, messages, config).await+}++async fn follow_up_reply(+ session: &ChatSession,+ config: ChatReplyConfig,+) -> Vec<ChatContentBlock> {+ reply_content(session, vec![ChatMessage::user().with_text("Now another one.".to_string())], config).await+}++#[ignore]+#[tokio::test]+async fn test_engine_chat_reply_seed() {+ let engine = Engine::new(EngineConfig::default()).await.unwrap();+ let model = engine.model("alibaba:qwen3.5:0.8b:mirai:mirai-m:4".to_string()).await.unwrap().unwrap();+ let download = engine.download(&model).await.unwrap();+ while download.next().await.is_some() {}++ let session_config = ChatConfig::default().with_sampling_seed(SamplingSeed::Custom {+ seed: 1,+ });+ let session = engine.chat(model, session_config).await.unwrap();+ let config =+ ChatReplyConfig::default().with_token_limit(Some(32)).with_sampling_method(SamplingMethod::Stochastic {+ temperature: Some(1.0),+ top_k: None,+ top_p: None,+ min_p: None,+ repetition_penalty: None,+ suffix_repetition_length: None,+ });+ let with_seed = |seed| {+ config.with_sampling_seed(SamplingSeed::Custom {+ seed,+ })+ };++ let session_seed = fresh_reply(&session, config.clone()).await;+ let other_seed = fresh_reply(&session, with_seed(2)).await;+ let same_seed_per_reply = fresh_reply(&session, with_seed(1)).await;+ assert_ne!(session_seed, other_seed, "a reply seed should change the sample");+ assert_eq!(session_seed, same_seed_per_reply, "a reply seed should match the same session seed");++ // The follow-up continues on the state the seeded reply sampled with.+ fresh_reply(&session, with_seed(2)).await;+ let follow_up_without_seed = follow_up_reply(&session, config.clone()).await;+ fresh_reply(&session, with_seed(2)).await;+ let follow_up_with_session_seed = follow_up_reply(&session, with_seed(1)).await;+ assert_eq!(follow_up_without_seed, follow_up_with_session_seed, "a reply seed should not outlive its reply");+}+#[ignore]#[tokio::test]async fn test_engine_classification() {diff --git a/crates/uzu-engine/src/engine/language_model/state.rs b/crates/uzu-engine/src/engine/language_model/state.rsindex 4835bc60a..c7d755635 100644--- a/crates/uzu-engine/src/engine/language_model/state.rs+++ b/crates/uzu-engine/src/engine/language_model/state.rs@@ -20,6 +20,13 @@ impl<B: Backend> LanguageModelState<B> {pub fn tokens(&self) -> &[u64] {&self.tokens}++ pub fn set_sampling_seed(+ &mut self,+ sampling_seed: u64,+ ) {+ self.prng = PRng::new(sampling_seed);+ }}#[derive(Debug, Error)]