Match Qwen reasoning history across effort changes

This commit is contained in:
Georg Bauer committed 2026-10-04 17:38:21 +02:00
1 parent 6507a494bc
commit 7c18e738cd
42 files changed
+3210 -5

No files matched your search

+54 -1
View File
@@ -445,6 +445,14 @@ fn render_text_prompt(
if latest.user
// A system-prefix cache is not a previous assistant turn.
&& !history.is_empty()
&& (model.family() != ModelFamily::Qwen || history.last().is_some_and(|turn| {
!turn.user && !turn.tool && !turn.system
// A raw history rebuild may have dropped a void
// assistant and now end in a user turn. A committed
// live generation frontier still owns its exact IDs.
&& (!tokenizer::qwen_void_assistant(turn)
|| cached != model.render_history(&settings.system_prompt, history, settings.reasoning_mode))
}))
&& checkpoint_tag
== conversation_tag(
model.family(),
@@ -2106,6 +2114,12 @@ fn conversation_key(
if family == ModelFamily::Qwen && tokenizer::qwen_normalization_changes(value) {
output.extend_from_slice(b"\0qwen-nfc");
}
if family == ModelFamily::Qwen
&& reasoning != ReasoningMode::Direct
&& value.contains(tokenizer::QWEN_ASSISTANT_THINK_PROMPT)
{
output.extend_from_slice(b"\0qwen-generation-seams");
}
output.extend_from_slice(&(value.len() as u64).to_le_bytes());
output.extend_from_slice(value.as_bytes());
};
@@ -2120,7 +2134,46 @@ fn conversation_key(
ReasoningMode::Medium => 4,
ReasoningMode::XHigh => 5,
});
for message in messages {
for (index, message) in messages.iter().enumerate() {
if family == ModelFamily::Qwen
&& (tokenizer::qwen_void_assistant(message)
|| index.checked_sub(1).is_some_and(|previous| {
let previous = &messages[previous];
!message.tool
&& !message.system
&& !previous.tool
&& !previous.system
&& message.user == previous.user
}))
{
output.extend_from_slice(b"\0qwen-history-adapter");
}
// A pre-fix direct-mode checkpoint may contain preserved thinking.
// Keep unaffected keys exact, but never authenticate that old history.
if family == ModelFamily::Qwen
&& reasoning == ReasoningMode::Direct
&& !message.user
&& !message.tool
&& !message.system
&& message
.reasoning
.as_deref()
.is_some_and(|text| !text.trim().is_empty())
{
output.extend_from_slice(b"\0qwen-direct-history");
}
if family == ModelFamily::Qwen
&& reasoning != ReasoningMode::Direct
&& !message.user
&& !message.tool
&& !message.system
&& message
.reasoning
.as_deref()
.is_none_or(|text| text.trim().is_empty())
{
output.extend_from_slice(b"\0qwen-generation-seams");
}
output.push(u8::from(message.user));
output.push(u8::from(message.tool));
output.push(u8::from(message.system));
@@ -98,8 +98,11 @@ fn issue111_token_prefix_cache() {
assert_eq!(cold.cached_tokens, 0);
assert_eq!(cold.prompt_tokens as usize, ids.len());
assert!(owner.tokens().starts_with(&ids));
// Preserve the completed-turn tag: a fabricated tag forces a raw-history
// rebuild and does not exercise compatible live-generation continuation.
let tag = owner.checkpoint_tag();
owner
.save_checkpoint(&directory.join("new-prefix.bin"), [111; 32], &mut |_| {})
.save_checkpoint(&directory.join("new-prefix.bin"), tag, &mut |_| {})
.unwrap();
let mut next = messages.clone();
next.push(cold.message.clone());
@@ -0,0 +1,224 @@
//! Actual live and disk cache migration through the whole-turn request path.
use super::*;
use crate::engine::{ModelFamily, conversation_key, conversation_tag};
use crate::settings::{
GenerationPreferences, ReasoningMode, RuntimePreferences, SpeculativePreferences,
effective_settings,
};
use sha2::{Digest, Sha256};
use std::path::PathBuf;
#[test]
#[ignore = "installed model; serial external memory supervisor required"]
fn issue117_reasoning_history_cache() {
let root = PathBuf::from(std::env::var_os("DS4_QWEN38_ARTIFACTS").unwrap());
let oracle = PathBuf::from(std::env::var_os("DS4_ISSUE117_ORACLE").unwrap());
let directory = PathBuf::from(std::env::var_os("DS4_ISSUE117_DIR").unwrap());
std::fs::create_dir_all(&directory).unwrap();
let requests: serde_json::Value =
serde_json::from_slice(&std::fs::read(oracle.join("requests.json")).unwrap()).unwrap();
let case = &requests[3]; // Direct, preserved nonempty reasoning and no system prompt.
let ids: Vec<i32> = serde_json::from_value(case["ids"].clone()).unwrap();
let legacy: Vec<i32> = serde_json::from_value(case["legacy_history_ids"].clone()).unwrap();
let settings = effective_settings(
crate::model::ModelChoice::Qwen38FlashNext,
&GenerationPreferences {
context_tokens: 8192,
max_generated_tokens: 2,
system_prompt: case["system"].as_str().unwrap().into(),
temperature: Some(0.),
top_p: Some(0.95),
min_p: Some(0.),
seed: Some(1),
reasoning_mode: ReasoningMode::Direct,
},
&RuntimePreferences {
speculative: SpeculativePreferences {
glm_mtp: true,
..Default::default()
},
..Default::default()
},
root.parent().unwrap(),
)
.unwrap();
let messages = case["messages"]
.as_array()
.unwrap()
.iter()
.map(|m| ChatTurn {
user: m["role"] == "user",
tool: false,
system: false,
skip_previous_eos: false,
reasoning: m["reasoning_content"].as_str().map(str::to_owned),
reasoning_complete: true,
content: m["content"].as_str().unwrap().into(),
})
.collect::<Vec<_>>();
let mut owner = QwenExecutor::open(&settings.engine).unwrap();
owner.policy.store_min_suffix = Some(0);
assert_eq!(
owner.metadata.tokenizer.encode_conversation(
&settings.turn.system_prompt,
&messages,
ReasoningMode::Direct
),
ids
);
let old_tag: [u8; 32] = Sha256::digest(conversation_key(
ModelFamily::DeepSeek,
&settings.turn.system_prompt,
ReasoningMode::Direct,
&messages[..2],
))
.into();
let new_tag = conversation_tag(
ModelFamily::Qwen,
&settings.turn.system_prompt,
ReasoningMode::Direct,
&messages[..2],
);
assert_ne!(old_tag, new_tag);
owner.prefill(&legacy, |_| true).unwrap();
owner.note_checkpoint_tag(old_tag);
owner
.save_checkpoint(&directory.join("old.bin"), old_tag, &mut |_| {})
.unwrap();
let metrics = Metrics::new(&directory.join("metrics"));
let run =
|owner: &mut QwenExecutor, messages: &[ChatTurn], turn: &crate::settings::TurnSettings| {
let (out, complete) = owner
.generate(
messages,
turn,
&AtomicBool::new(false),
&metrics,
|_, _, _| {},
|_, _| {},
)
.unwrap();
assert!(complete);
out
};
// Directly exercise the matching raw-history tag shortcut: old live/disk
// histories must miss, even though their source messages are unchanged.
let cold = run(&mut owner, &messages, &settings.turn);
assert_eq!(cold.cached_tokens, 0);
assert_eq!(cold.prompt_tokens as usize, ids.len());
assert!(owner.tokens().starts_with(&ids));
let cold_state = super::issue107_product::state(&owner);
owner.reset().unwrap();
assert!(
owner
.load_checkpoint(&directory.join("old.bin"), &mut |_| {})
.unwrap()
);
assert_eq!(owner.tokens(), legacy);
let disk_cold = run(&mut owner, &messages, &settings.turn);
assert_eq!(disk_cold.cached_tokens, 0);
assert_eq!(cold_state, super::issue107_product::state(&owner));
let tag = owner.checkpoint_tag();
owner
.save_checkpoint(&directory.join("new.bin"), tag, &mut |_| {})
.unwrap();
let mut next = messages.clone();
next.push(disk_cold.message);
next.push(ChatTurn {
content: "Continue the count.".into(),
..messages[0].clone()
});
let warm = run(&mut owner, &next, &settings.turn);
assert!(warm.cached_tokens >= cold.prompt_tokens);
let expected = super::issue107_product::state(&owner);
owner.reset().unwrap();
assert!(
owner
.load_checkpoint(&directory.join("new.bin"), &mut |_| {})
.unwrap()
);
let reopened = run(&mut owner, &next, &settings.turn);
assert_eq!(warm.cached_tokens, reopened.cached_tokens);
assert_eq!(expected, super::issue107_product::state(&owner));
// Switching back to thinking also changes empty-history newline IDs.
let empty = requests
.as_array()
.unwrap()
.iter()
.find(|case| {
case["effort"] == "low"
&& case["preserve_echo"] == true
&& case["system"] == ""
&& case["messages"][1]["reasoning_content"].is_null()
})
.unwrap();
let empty_ids: Vec<i32> = serde_json::from_value(empty["ids"].clone()).unwrap();
let old_empty: Vec<i32> = serde_json::from_value(empty["legacy_history_ids"].clone()).unwrap();
let mut empty_messages = messages.clone();
empty_messages[1].reasoning = None;
let mut thinking_turn = settings.turn.clone();
thinking_turn.reasoning_mode = ReasoningMode::Low;
let empty_old_tag: [u8; 32] = Sha256::digest(conversation_key(
ModelFamily::DeepSeek,
"",
ReasoningMode::Low,
&empty_messages[..2],
))
.into();
owner.reset().unwrap();
owner.prefill(&old_empty, |_| true).unwrap();
owner
.save_checkpoint(
&directory.join("old-empty-thinking.bin"),
empty_old_tag,
&mut |_| {},
)
.unwrap();
owner.reset().unwrap();
assert!(
owner
.load_checkpoint(&directory.join("old-empty-thinking.bin"), &mut |_| {})
.unwrap()
);
let empty_out = run(&mut owner, &empty_messages, &thinking_turn);
assert_eq!(empty_out.cached_tokens, 0);
assert_eq!(empty_out.prompt_tokens as usize, empty_ids.len());
assert!(owner.tokens().starts_with(&empty_ids));
owner.reset().unwrap();
let mut mode_switches = Vec::new();
for mode in [
ReasoningMode::Low,
ReasoningMode::Medium,
ReasoningMode::XHigh,
] {
let mut turn = settings.turn.clone();
turn.reasoning_mode = mode;
let thinking = run(&mut owner, &messages, &turn);
assert_eq!(thinking.cached_tokens, 0);
let mut switched = messages.clone();
switched.push(thinking.message);
switched.push(ChatTurn {
content: "Continue.".into(),
..messages[0].clone()
});
let expected_ids = owner.metadata.tokenizer.encode_conversation(
&settings.turn.system_prompt,
&switched,
ReasoningMode::Direct,
);
let direct = run(&mut owner, &switched, &settings.turn);
assert_eq!(direct.cached_tokens, 0);
assert_eq!(direct.prompt_tokens as usize, expected_ids.len());
assert!(owner.tokens().starts_with(&expected_ids));
mode_switches.push(serde_json::json!({"from":format!("{mode:?}"),"system":settings.turn.system_prompt,"messages":switched.iter().map(|m| serde_json::json!({"role":if m.user {"user"} else {"assistant"},"content":m.content,"reasoning_content":m.reasoning})).collect::<Vec<_>>(),"direct_ids":expected_ids,"context_tokens":direct.prompt_tokens,"cached_tokens":direct.cached_tokens}));
}
std::fs::write(
directory.join("mode-switches.json"),
serde_json::to_vec_pretty(&mode_switches).unwrap(),
)
.unwrap();
println!(
"{}",
serde_json::json!({"case":"reasoning_history_cache", "legacy_history_tokens":legacy.len(),"direct_prompt_tokens":ids.len(),"live_old_miss":true,"disk_old_miss":true,"cold_state_exact":true,"warm_cached":warm.cached_tokens,"disk_cached":reopened.cached_tokens,"warm_disk_state_exact":true})
);
}
+4
View File
@@ -1090,3 +1090,7 @@ mod issue111_product;
#[cfg(test)]
#[path = "issue116_product.rs"]
mod issue116_product;
#[cfg(test)]
#[path = "issue117_product.rs"]
mod issue117_product;
+85 -2
View File
@@ -538,6 +538,39 @@ impl Tokenizer {
reasoning: ReasoningMode,
continue_assistant: bool,
) -> Vec<i32> {
let messages = qwen_history(messages, reasoning);
let rendered =
Self::render_qwen_messages(system_prompt, &messages, reasoning, continue_assistant);
// MTPLX preserves the generation-time BPE boundary in thinking
// histories, including the two separate newlines of an empty thought.
// Direct mode tokenizes the closed scaffold together.
if reasoning != ReasoningMode::Direct
&& messages
.iter()
.any(|message| !message.user && !message.tool && !message.system)
{
let mut output = Vec::new();
let mut start = 0;
for (at, marker) in rendered.match_indices(QWEN_ASSISTANT_THINK_PROMPT) {
let end = at + marker.len();
if end < rendered.len() {
output.extend(self.tokenize_rendered(&rendered[start..end]));
start = end;
}
}
output.extend(self.tokenize_rendered(&rendered[start..]));
output
} else {
self.tokenize_rendered(&rendered)
}
}
fn render_qwen_messages(
system_prompt: Option<&str>,
messages: &[ChatTurn],
reasoning: ReasoningMode,
continue_assistant: bool,
) -> String {
let instruction = match reasoning {
ReasoningMode::Direct | ReasoningMode::Medium => "",
ReasoningMode::Low => {
@@ -587,7 +620,11 @@ impl Tokenizer {
rendered.push_str("<|im_end|>\n");
} else {
rendered.push_str("<|im_start|>assistant\n<think>\n");
if let Some(thinking) = &message.reasoning {
// MTPLX's preserve-echo policy excludes reasoning_content
// when enable_thinking is false, retaining the empty scaffold.
if reasoning != ReasoningMode::Direct
&& let Some(thinking) = &message.reasoning
{
rendered.push_str(thinking.trim());
}
rendered.push_str("\n</think>\n\n");
@@ -601,7 +638,7 @@ impl Tokenizer {
rendered.push_str("\n</think>\n\n");
}
}
self.tokenize_rendered(&rendered)
rendered
}
pub(super) fn encode_continuation(
@@ -895,6 +932,48 @@ pub(super) fn qwen_normalization_changes(text: &str) -> bool {
qwen_normalize(text) != text
}
pub(super) const QWEN_ASSISTANT_THINK_PROMPT: &str = "<|im_start|>assistant\n<think>\n";
pub(super) fn qwen_void_assistant(message: &ChatTurn) -> bool {
!message.user && !message.tool && !message.system && message.content.trim().is_empty()
}
fn qwen_history(messages: &[ChatTurn], mode: ReasoningMode) -> Vec<ChatTurn> {
// MTPLX drops void assistants, then merges adjacent user/assistant roles.
// The server also drops reasoning-only assistants. Keep the
// first assistant's reasoning when merging; trim user text after merging.
let mut normalized: Vec<ChatTurn> = Vec::with_capacity(messages.len());
for message in messages {
if qwen_void_assistant(message) {
continue;
}
let mut message = message.clone();
if !message.user && !message.tool && !message.system {
message.content = message.content.trim().to_owned();
if mode == ReasoningMode::Direct {
message.reasoning = None;
}
}
if let Some(previous) = normalized.last_mut()
&& !previous.tool
&& !previous.system
&& !message.tool
&& !message.system
&& previous.user == message.user
{
if !message.content.is_empty() {
if !previous.content.is_empty() {
previous.content.push_str("\n\n");
}
previous.content.push_str(&message.content);
}
} else {
normalized.push(message);
}
}
normalized
}
/// The trained Qwen3 Split expression. Rust regex supports its Unicode
/// categories but not the penultimate `\s+(?!\S)` alternative: before a
/// non-whitespace character that branch backtracks by one whitespace scalar,
@@ -1418,3 +1497,7 @@ mod issue111;
#[cfg(test)]
#[path = "tokenizer_issue116.rs"]
mod issue116;
#[cfg(test)]
#[path = "tokenizer_issue117.rs"]
mod issue117;
+193
View File
@@ -0,0 +1,193 @@
use super::*;
#[test]
fn direct_history_omits_reasoning_but_retains_the_scaffold() {
let assistant = ChatTurn {
user: false,
tool: false,
system: false,
skip_previous_eos: false,
reasoning: Some(" Prior thinking. ".into()),
reasoning_complete: true,
content: " Answer. ".into(),
};
for mode in [
ReasoningMode::Direct,
ReasoningMode::Low,
ReasoningMode::Medium,
ReasoningMode::XHigh,
] {
let rendered =
Tokenizer::render_qwen_messages(None, std::slice::from_ref(&assistant), mode, false);
let thinking = if mode == ReasoningMode::Direct {
""
} else {
"Prior thinking."
};
assert_eq!(
rendered,
format!("<|im_start|>assistant\n<think>\n{thinking}\n</think>\n\nAnswer.<|im_end|>\n")
);
}
}
#[test]
fn only_affected_histories_change_keys() {
use crate::engine::conversation_key;
for mode in [
ReasoningMode::Direct,
ReasoningMode::Low,
ReasoningMode::Medium,
ReasoningMode::XHigh,
] {
for reasoning in [None, Some(""), Some(" \n"), Some("Prior thinking.")] {
let history = [ChatTurn {
user: false,
tool: false,
system: false,
skip_previous_eos: false,
reasoning: reasoning.map(str::to_owned),
reasoning_complete: true,
content: "Answer.".into(),
}];
let original = conversation_key(ModelFamily::DeepSeek, "System", mode, &history);
assert_eq!(
original,
conversation_key(ModelFamily::Glm, "System", mode, &history)
);
let current = conversation_key(ModelFamily::Qwen, "System", mode, &history);
assert_eq!(
current != original,
(mode == ReasoningMode::Direct) == reasoning.is_some_and(|s| !s.trim().is_empty())
);
let next = [
history[0].clone(),
ChatTurn {
user: true,
content: "Continue".into(),
reasoning: None,
..history[0].clone()
},
];
assert!(
conversation_key(ModelFamily::Qwen, "System", mode, &next).starts_with(&current)
);
}
}
}
#[test]
#[ignore = "CPU-only; installed Qwen tokenizer and pinned history receipts"]
fn issue117_history_renders_tokens_and_context() {
let root = std::path::PathBuf::from(std::env::var_os("DS4_QWEN38_ARTIFACTS").unwrap());
let path = std::path::PathBuf::from(std::env::var_os("DS4_ISSUE117_ORACLE").unwrap());
let cases: serde_json::Value =
serde_json::from_slice(&fs::read(path.join("requests.json")).unwrap()).unwrap();
let tokenizer = Tokenizer::load_qwen(&root.join("tokenizer.json")).unwrap();
let metadata = crate::engine::qwen::QwenMetadata::open(&root, false).unwrap();
let mut settings = crate::settings::TurnSettings {
kv_cache: crate::settings::KvCachePreferences::default().settings(),
context_tokens: 8192,
max_generated_tokens: 2,
system_prompt: String::new(),
temperature: 0.,
top_p: 0.95,
min_p: 0.,
top_k: 0,
stops: vec![],
seed: Some(1),
reasoning_mode: ReasoningMode::Direct,
};
for case in cases.as_array().unwrap() {
let mode = match case["effort"].as_str().unwrap() {
"direct" => ReasoningMode::Direct,
"low" => ReasoningMode::Low,
"medium" => ReasoningMode::Medium,
"xhigh" => ReasoningMode::XHigh,
_ => unreachable!(),
};
let system = case["system"].as_str().unwrap();
let messages = case["messages"]
.as_array()
.unwrap()
.iter()
.map(|m| ChatTurn {
user: m["role"] == "user",
tool: false,
system: false,
skip_previous_eos: false,
reasoning: case["preserve_echo"]
.as_bool()
.unwrap()
.then(|| m["reasoning_content"].as_str().map(str::to_owned))
.flatten(),
reasoning_complete: true,
content: m["content"].as_str().unwrap().into(),
})
.collect::<Vec<_>>();
let rendered = Tokenizer::render_qwen_messages(
Some(system),
&qwen_history(&messages, mode),
mode,
true,
);
assert_eq!(rendered, case["rendered"].as_str().unwrap(), "{case}");
let ids = tokenizer.encode_conversation(system, &messages, mode);
assert_eq!(serde_json::json!(ids), case["ids"], "{case}");
let history = tokenizer.encode_history(system, &messages[..2], mode);
assert_eq!(serde_json::json!(history), case["history_ids"], "{case}");
settings.system_prompt = system.into();
settings.reasoning_mode = mode;
let tag = crate::engine::conversation_tag(ModelFamily::Qwen, system, mode, &messages[..2]);
let request = crate::engine::render_text_prompt(
crate::engine::ModelRef::Qwen(&metadata),
&history,
tag,
&messages,
&settings,
);
assert_eq!(request, ids, "cached history {case}");
let mut continuation = history;
continuation.extend(tokenizer.encode_continuation(&messages[2].content, mode, false));
if qwen_void_assistant(&messages[1]) {
assert_ne!(continuation, ids);
} else {
assert_eq!(continuation, ids);
}
}
println!(
"{}",
serde_json::json!({"case":"reasoning_history","cases":cases.as_array().unwrap().len(),"renders_ids_history_continuation_context_exact":true})
);
}
#[test]
fn reasoning_only_direct_turn_merges_surrounding_users() {
let user = ChatTurn {
user: true,
tool: false,
system: false,
skip_previous_eos: false,
reasoning: None,
reasoning_complete: true,
content: "First ".into(),
};
let assistant = ChatTurn {
user: false,
reasoning: Some("Thinking.".into()),
content: String::new(),
..user.clone()
};
let messages = [
user.clone(),
assistant,
ChatTurn {
content: " Next".into(),
..user
},
];
let direct = qwen_history(&messages, ReasoningMode::Direct);
assert_eq!(direct.len(), 1);
assert_eq!(direct[0].content, "First \n\n Next");
assert_eq!(qwen_history(&messages, ReasoningMode::Low).len(), 1);
}
+47
View File
@@ -633,6 +633,53 @@ pub(crate) fn issue105_wire(active: crate::runtime::ActiveGeneration, streaming:
mod tests {
use super::*;
#[test]
fn qwen_http_requests_keep_echoed_reasoning_without_tools() {
let metrics = Arc::new(Metrics::new(PathBuf::new().as_path()));
let state = State {
generation: GenerationService::spawn(Arc::clone(&metrics)).unwrap(),
config: Arc::new(RwLock::new(Config::default())),
models_path: PathBuf::new(),
cache_path: PathBuf::new(),
sequence: AtomicU64::new(0),
connections: Arc::new(AtomicUsize::new(0)),
tool_memory: Mutex::new(HashMap::new()),
metrics,
cors: false,
};
let messages: Vec<ApiMessage> = serde_json::from_value(json!([
{"role":"user","content":"First"},
{"role":"assistant","content":"Answer","reasoning_content":"Prior thinking."},
{"role":"user","content":"Continue"}
]))
.unwrap();
for model in [
ModelChoice::Qwen38FlashNext,
ModelChoice::DeepSeekV4Flash0731,
ModelChoice::Glm53Flash,
] {
for tools_enabled in [false, true] {
for protocol in [Protocol::Chat, Protocol::Responses, Protocol::Anthropic] {
let (_, turns) = render_messages(
&state,
&messages,
&[],
&[],
tools_enabled,
model,
protocol,
)
.unwrap();
assert_eq!(
turns[1].reasoning.as_deref(),
(model.is_qwen38() || tools_enabled).then_some("Prior thinking.")
);
assert_eq!(turns[1].content, "Answer");
}
}
}
}
#[test]
fn connection_slots_enforce_the_limit_and_release_on_drop() {
let active = Arc::new(AtomicUsize::new(0));
+1
View File
@@ -556,6 +556,7 @@ pub(super) fn parse_chat_request(
&request.tools,
&request.tool_schemas,
tools_enabled,
model,
protocol,
)?;
generation.system_prompt = system;
+3 -1
View File
@@ -327,10 +327,12 @@ pub(super) fn render_messages(
tools: &[Value],
tool_schemas: &[String],
tools_enabled: bool,
model: ModelChoice,
protocol: Protocol,
) -> Result<(String, Vec<ChatTurn>), (u16, String)> {
validate_tool_results(state, messages, protocol)?;
let preserve_reasoning = tools_enabled
let preserve_reasoning = model.is_qwen38()
|| tools_enabled
|| messages.iter().any(|message| {
matches!(message.role.as_str(), "tool" | "function") || !message.tool_calls.is_empty()
});