Apply Qwen NFC normalization before token splitting
This commit is contained in:
1 parent
5129c450ee
commit
6507a494bc
36 files changed
+1831
-39
No files matched your search
+164
-29
@@ -352,6 +352,13 @@ impl LoadedModel {
|
||||
}
|
||||
|
||||
impl ModelRef<'_> {
|
||||
fn family(self) -> ModelFamily {
|
||||
match self {
|
||||
Self::Gguf(model) => model.shape.family,
|
||||
Self::Qwen(_) => ModelFamily::Qwen,
|
||||
}
|
||||
}
|
||||
|
||||
fn summary(self) -> ModelSummary {
|
||||
match self {
|
||||
Self::Gguf(model) => model.summary(),
|
||||
@@ -440,6 +447,7 @@ fn render_text_prompt(
|
||||
&& !history.is_empty()
|
||||
&& checkpoint_tag
|
||||
== conversation_tag(
|
||||
model.family(),
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
history,
|
||||
@@ -846,8 +854,10 @@ impl Generator {
|
||||
) -> Result<GenerationOutput, String> {
|
||||
let result: Result<_, String> = (|| {
|
||||
let checkpoint_present = checkpoint.is_file();
|
||||
let family = self.executor.model().family();
|
||||
let selected = self.select_checkpoint(checkpoint, |tag| {
|
||||
checkpoint_matches_prefix(
|
||||
family,
|
||||
tag,
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
@@ -883,7 +893,12 @@ impl Generator {
|
||||
self.save_checkpoint(
|
||||
checkpoint,
|
||||
if prompt_complete {
|
||||
conversation_tag(&settings.system_prompt, settings.reasoning_mode, &completed)
|
||||
conversation_tag(
|
||||
family,
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
&completed,
|
||||
)
|
||||
} else {
|
||||
[0; 32]
|
||||
},
|
||||
@@ -898,7 +913,12 @@ impl Generator {
|
||||
if let Err(error) = &result {
|
||||
let mut paths = vec![checkpoint.to_owned()];
|
||||
if let Some(directory) = bootstrap {
|
||||
let key = conversation_key(&settings.system_prompt, settings.reasoning_mode, &[]);
|
||||
let key = conversation_key(
|
||||
self.executor.model().family(),
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
&[],
|
||||
);
|
||||
let tag = Sha256::digest(&key).into();
|
||||
paths.push(directory.join(format!("{}.bin", kvstore::key_hash(&key))));
|
||||
paths.push(resident_key(directory, tag));
|
||||
@@ -958,8 +978,12 @@ impl Generator {
|
||||
.split_last()
|
||||
.map_or(messages, |(_, history)| history);
|
||||
let store = KvStore::open(directory, settings.kv_cache.budget_bytes)?;
|
||||
let history_key =
|
||||
conversation_key(&settings.system_prompt, settings.reasoning_mode, history);
|
||||
let history_key = conversation_key(
|
||||
self.executor.model().family(),
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
history,
|
||||
);
|
||||
let history_tag: [u8; 32] = Sha256::digest(&history_key).into();
|
||||
let previous_checkpoint =
|
||||
self.restore_cached_prefix(directory, &store, &history_key, history_tag)?;
|
||||
@@ -978,8 +1002,12 @@ impl Generator {
|
||||
.and_then(|path| std::fs::metadata(path).ok())
|
||||
.map(|item| item.len());
|
||||
if prompt_complete {
|
||||
let completed_key =
|
||||
conversation_key(&settings.system_prompt, settings.reasoning_mode, &completed);
|
||||
let completed_key = conversation_key(
|
||||
self.executor.model().family(),
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
&completed,
|
||||
);
|
||||
let completed_tag: [u8; 32] = Sha256::digest(&completed_key).into();
|
||||
if !settings.kv_cache.stores(
|
||||
self.executor.position(),
|
||||
@@ -1030,6 +1058,7 @@ impl Generator {
|
||||
let mut paths = Vec::new();
|
||||
for count in 0..=messages.len() {
|
||||
let key = conversation_key(
|
||||
self.executor.model().family(),
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
&messages[..count],
|
||||
@@ -1097,7 +1126,12 @@ impl Generator {
|
||||
progress: &mut impl FnMut(u32, u32, Option<f32>),
|
||||
phase: &mut impl FnMut(&'static str),
|
||||
) -> Result<(), String> {
|
||||
let key = conversation_key(&settings.system_prompt, settings.reasoning_mode, &[]);
|
||||
let key = conversation_key(
|
||||
self.executor.model().family(),
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
&[],
|
||||
);
|
||||
let tag: [u8; 32] = Sha256::digest(&key).into();
|
||||
let store = KvStore::open(directory, settings.kv_cache.budget_bytes)?;
|
||||
self.restore_cached_prefix(directory, &store, &key, tag)?;
|
||||
@@ -1295,7 +1329,12 @@ impl Generator {
|
||||
if completed != history_tokens.len() || cancelled.load(Ordering::Relaxed) {
|
||||
return Err("context compaction interrupted during rebuild".into());
|
||||
}
|
||||
let tag = conversation_tag(&rebuilt_system, settings.reasoning_mode, &tail);
|
||||
let tag = conversation_tag(
|
||||
self.executor.model().family(),
|
||||
&rebuilt_system,
|
||||
settings.reasoning_mode,
|
||||
&tail,
|
||||
);
|
||||
phase("Saving compacted context…");
|
||||
self.save_checkpoint(checkpoint, tag)?;
|
||||
Ok(CompactionOutput {
|
||||
@@ -2053,11 +2092,23 @@ fn emit_safe_text(
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn conversation_key(system: &str, reasoning: ReasoningMode, messages: &[ChatTurn]) -> Vec<u8> {
|
||||
fn text(output: &mut Vec<u8>, value: &str) {
|
||||
fn conversation_key(
|
||||
family: ModelFamily,
|
||||
system: &str,
|
||||
reasoning: ReasoningMode,
|
||||
messages: &[ChatTurn],
|
||||
) -> Vec<u8> {
|
||||
// Keep the original byte keys for both DS4 families and unaffected Qwen
|
||||
// text. A field changed by NFC must not authenticate a pre-NFC checkpoint
|
||||
// through the completed-history fast path. Per-field markers preserve the
|
||||
// prefix property when appending turns, and keep distinct raw histories.
|
||||
let text = |output: &mut Vec<u8>, value: &str| {
|
||||
if family == ModelFamily::Qwen && tokenizer::qwen_normalization_changes(value) {
|
||||
output.extend_from_slice(b"\0qwen-nfc");
|
||||
}
|
||||
output.extend_from_slice(&(value.len() as u64).to_le_bytes());
|
||||
output.extend_from_slice(value.as_bytes());
|
||||
}
|
||||
};
|
||||
|
||||
let mut output = b"DS4Server chat checkpoint v5".to_vec();
|
||||
text(&mut output, system);
|
||||
@@ -2088,12 +2139,18 @@ fn conversation_key(system: &str, reasoning: ReasoningMode, messages: &[ChatTurn
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn conversation_tag(system: &str, reasoning: ReasoningMode, messages: &[ChatTurn]) -> [u8; 32] {
|
||||
Sha256::digest(conversation_key(system, reasoning, messages)).into()
|
||||
fn conversation_tag(
|
||||
family: ModelFamily,
|
||||
system: &str,
|
||||
reasoning: ReasoningMode,
|
||||
messages: &[ChatTurn],
|
||||
) -> [u8; 32] {
|
||||
Sha256::digest(conversation_key(family, system, reasoning, messages)).into()
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn checkpoint_matches_prefix(
|
||||
family: ModelFamily,
|
||||
checkpoint: [u8; 32],
|
||||
system: &str,
|
||||
reasoning: ReasoningMode,
|
||||
@@ -2103,7 +2160,7 @@ fn checkpoint_matches_prefix(
|
||||
// scanning a genuinely changed, very long history becomes measurable.
|
||||
(0..messages.len())
|
||||
.rev()
|
||||
.any(|end| checkpoint == conversation_tag(system, reasoning, &messages[..end]))
|
||||
.any(|end| checkpoint == conversation_tag(family, system, reasoning, &messages[..end]))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -2921,31 +2978,66 @@ mod sampling_tests {
|
||||
reasoning_complete: true,
|
||||
content: "Hello".into(),
|
||||
}];
|
||||
let tag = conversation_tag("System", ReasoningMode::High, &messages);
|
||||
let tag = conversation_tag(
|
||||
ModelFamily::DeepSeek,
|
||||
"System",
|
||||
ReasoningMode::High,
|
||||
&messages,
|
||||
);
|
||||
assert_eq!(
|
||||
tag,
|
||||
conversation_tag("System", ReasoningMode::High, &messages)
|
||||
conversation_tag(
|
||||
ModelFamily::DeepSeek,
|
||||
"System",
|
||||
ReasoningMode::High,
|
||||
&messages
|
||||
)
|
||||
);
|
||||
assert_ne!(
|
||||
tag,
|
||||
conversation_tag("Changed", ReasoningMode::High, &messages)
|
||||
conversation_tag(
|
||||
ModelFamily::DeepSeek,
|
||||
"Changed",
|
||||
ReasoningMode::High,
|
||||
&messages
|
||||
)
|
||||
);
|
||||
assert_ne!(
|
||||
tag,
|
||||
conversation_tag("System", ReasoningMode::Direct, &messages)
|
||||
conversation_tag(
|
||||
ModelFamily::DeepSeek,
|
||||
"System",
|
||||
ReasoningMode::Direct,
|
||||
&messages
|
||||
)
|
||||
);
|
||||
messages[0].system = true;
|
||||
assert_ne!(
|
||||
tag,
|
||||
conversation_tag("System", ReasoningMode::High, &messages)
|
||||
conversation_tag(
|
||||
ModelFamily::DeepSeek,
|
||||
"System",
|
||||
ReasoningMode::High,
|
||||
&messages
|
||||
)
|
||||
);
|
||||
messages[0].system = false;
|
||||
messages[0].skip_previous_eos = true;
|
||||
assert_ne!(
|
||||
tag,
|
||||
conversation_tag("System", ReasoningMode::High, &messages)
|
||||
conversation_tag(
|
||||
ModelFamily::DeepSeek,
|
||||
"System",
|
||||
ReasoningMode::High,
|
||||
&messages
|
||||
)
|
||||
);
|
||||
let prefix = conversation_key(
|
||||
ModelFamily::DeepSeek,
|
||||
"System",
|
||||
ReasoningMode::High,
|
||||
&messages,
|
||||
);
|
||||
let prefix = conversation_key("System", ReasoningMode::High, &messages);
|
||||
messages.push(ChatTurn {
|
||||
user: false,
|
||||
tool: false,
|
||||
@@ -2955,7 +3047,15 @@ mod sampling_tests {
|
||||
reasoning_complete: true,
|
||||
content: "Hi".into(),
|
||||
});
|
||||
assert!(conversation_key("System", ReasoningMode::High, &messages).starts_with(&prefix));
|
||||
assert!(
|
||||
conversation_key(
|
||||
ModelFamily::DeepSeek,
|
||||
"System",
|
||||
ReasoningMode::High,
|
||||
&messages
|
||||
)
|
||||
.starts_with(&prefix)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2969,7 +3069,12 @@ mod sampling_tests {
|
||||
reasoning_complete: true,
|
||||
content: "Question".into(),
|
||||
}];
|
||||
let checkpoint = conversation_tag("System", ReasoningMode::High, &messages);
|
||||
let checkpoint = conversation_tag(
|
||||
ModelFamily::DeepSeek,
|
||||
"System",
|
||||
ReasoningMode::High,
|
||||
&messages,
|
||||
);
|
||||
messages.extend([
|
||||
ChatTurn {
|
||||
user: false,
|
||||
@@ -2992,12 +3097,14 @@ mod sampling_tests {
|
||||
]);
|
||||
|
||||
assert!(checkpoint_matches_prefix(
|
||||
ModelFamily::DeepSeek,
|
||||
checkpoint,
|
||||
"System",
|
||||
ReasoningMode::High,
|
||||
&messages,
|
||||
));
|
||||
assert!(!checkpoint_matches_prefix(
|
||||
ModelFamily::DeepSeek,
|
||||
checkpoint,
|
||||
"Changed",
|
||||
ReasoningMode::High,
|
||||
@@ -3008,7 +3115,7 @@ mod sampling_tests {
|
||||
#[test]
|
||||
fn workspace_instruction_identity_participates_in_append_only_kv_keys() {
|
||||
let system = "System";
|
||||
let bootstrap = conversation_key(system, ReasoningMode::High, &[]);
|
||||
let bootstrap = conversation_key(ModelFamily::DeepSeek, system, ReasoningMode::High, &[]);
|
||||
let mut messages = vec![
|
||||
ChatTurn {
|
||||
user: false,
|
||||
@@ -3030,16 +3137,39 @@ mod sampling_tests {
|
||||
},
|
||||
];
|
||||
|
||||
assert!(conversation_key(system, ReasoningMode::High, &messages).starts_with(&bootstrap));
|
||||
assert!(
|
||||
conversation_key(
|
||||
ModelFamily::DeepSeek,
|
||||
system,
|
||||
ReasoningMode::High,
|
||||
&messages
|
||||
)
|
||||
.starts_with(&bootstrap)
|
||||
);
|
||||
let mut changed_opening = messages[0].clone();
|
||||
changed_opening.content = changed_opening
|
||||
.content
|
||||
.replace("identity: abc", "identity: def");
|
||||
assert_ne!(
|
||||
conversation_tag(system, ReasoningMode::High, &messages[..1]),
|
||||
conversation_tag(system, ReasoningMode::High, &[changed_opening])
|
||||
conversation_tag(
|
||||
ModelFamily::DeepSeek,
|
||||
system,
|
||||
ReasoningMode::High,
|
||||
&messages[..1]
|
||||
),
|
||||
conversation_tag(
|
||||
ModelFamily::DeepSeek,
|
||||
system,
|
||||
ReasoningMode::High,
|
||||
&[changed_opening]
|
||||
)
|
||||
);
|
||||
let baseline = conversation_key(
|
||||
ModelFamily::DeepSeek,
|
||||
system,
|
||||
ReasoningMode::High,
|
||||
&messages,
|
||||
);
|
||||
let baseline = conversation_key(system, ReasoningMode::High, &messages);
|
||||
messages.push(ChatTurn {
|
||||
user: false,
|
||||
tool: false,
|
||||
@@ -3049,7 +3179,12 @@ mod sampling_tests {
|
||||
reasoning_complete: true,
|
||||
content: "<system-reminder>\nWorkspace instruction identity: def\nReplacement instructions from: /project/AGENTS.md\nkeep that\n</system-reminder>".into(),
|
||||
});
|
||||
let changed = conversation_key(system, ReasoningMode::High, &messages);
|
||||
let changed = conversation_key(
|
||||
ModelFamily::DeepSeek,
|
||||
system,
|
||||
ReasoningMode::High,
|
||||
&messages,
|
||||
);
|
||||
assert!(changed.starts_with(&baseline));
|
||||
}
|
||||
|
||||
|
||||
@@ -105,8 +105,18 @@ fn product(mtp: bool) {
|
||||
let mut messages = vec![message("Count from one.")];
|
||||
let baseline = generate(&mut generator, &baseline_path, &messages, &settings);
|
||||
messages.push(baseline.message);
|
||||
let tag = conversation_tag(&settings.system_prompt, settings.reasoning_mode, &messages);
|
||||
let key = conversation_key(&settings.system_prompt, settings.reasoning_mode, &messages);
|
||||
let tag = conversation_tag(
|
||||
crate::engine::ModelFamily::Qwen,
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
&messages,
|
||||
);
|
||||
let key = conversation_key(
|
||||
crate::engine::ModelFamily::Qwen,
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
&messages,
|
||||
);
|
||||
messages.push(message("Continue."));
|
||||
let healthy_path = directory.join("healthy.bin");
|
||||
generate(
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! 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 issue116_normalized_token_cache() {
|
||||
let root = PathBuf::from(std::env::var_os("DS4_QWEN38_ARTIFACTS").unwrap());
|
||||
let oracle = PathBuf::from(std::env::var_os("DS4_ISSUE116_ORACLE").unwrap());
|
||||
let directory = PathBuf::from(std::env::var_os("DS4_ISSUE116_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]; // Low, with a decomposed system prompt and history.
|
||||
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::Low,
|
||||
},
|
||||
&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::Low
|
||||
),
|
||||
ids
|
||||
);
|
||||
let old_tag: [u8; 32] = Sha256::digest(conversation_key(
|
||||
ModelFamily::DeepSeek,
|
||||
&settings.turn.system_prompt,
|
||||
ReasoningMode::Low,
|
||||
&messages[..2],
|
||||
))
|
||||
.into();
|
||||
let new_tag = conversation_tag(
|
||||
ModelFamily::Qwen,
|
||||
&settings.turn.system_prompt,
|
||||
ReasoningMode::Low,
|
||||
&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]| {
|
||||
let (out, complete) = owner
|
||||
.generate(
|
||||
messages,
|
||||
&settings.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);
|
||||
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);
|
||||
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 e\u{301} and 가.".into(),
|
||||
..messages[0].clone()
|
||||
});
|
||||
let warm = run(&mut owner, &next);
|
||||
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);
|
||||
assert_eq!(warm.cached_tokens, reopened.cached_tokens);
|
||||
assert_eq!(expected, super::issue107_product::state(&owner));
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"case":"nfc_cache", "legacy_history_tokens":legacy.len(),"normalized_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})
|
||||
);
|
||||
}
|
||||
@@ -1031,7 +1031,12 @@ fn qwen_vision_chat_checkpoint_preserves_image_identity() {
|
||||
assert_eq!(repeat.cached_tokens, first.prompt_tokens);
|
||||
assert_eq!(repeat.message.content, first.message.content);
|
||||
messages.push(repeat.message);
|
||||
let tag = crate::engine::conversation_tag("", ReasoningMode::Low, &messages);
|
||||
let tag = crate::engine::conversation_tag(
|
||||
crate::engine::ModelFamily::Qwen,
|
||||
"",
|
||||
ReasoningMode::Low,
|
||||
&messages,
|
||||
);
|
||||
let checkpoint = directory.join("vision.kv");
|
||||
executor
|
||||
.save_checkpoint(&checkpoint, tag, &mut |_| {})
|
||||
@@ -1081,3 +1086,7 @@ mod issue109_product;
|
||||
#[cfg(test)]
|
||||
#[path = "issue111_product.rs"]
|
||||
mod issue111_product;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "issue116_product.rs"]
|
||||
mod issue116_product;
|
||||
@@ -220,8 +220,12 @@ impl LiveSession {
|
||||
{
|
||||
let mut completed = messages.to_vec();
|
||||
completed.push(result.output.message.clone());
|
||||
self.tag =
|
||||
conversation_tag(&settings.system_prompt, settings.reasoning_mode, &completed);
|
||||
self.tag = conversation_tag(
|
||||
crate::engine::ModelFamily::Qwen,
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
&completed,
|
||||
);
|
||||
self.current = Some(snapshot);
|
||||
self.current_images = images;
|
||||
}
|
||||
|
||||
@@ -537,6 +537,7 @@ fn mtplx_full_installed_chat_matches_reference() {
|
||||
}),
|
||||
};
|
||||
let key = crate::engine::conversation_key(
|
||||
crate::engine::ModelFamily::Qwen,
|
||||
&settings.system_prompt,
|
||||
settings.reasoning_mode,
|
||||
&messages,
|
||||
|
||||
+6
-1
@@ -1280,7 +1280,12 @@ mod tests {
|
||||
let ending = metadata.tokenizer.tokenize_rendered("<|im_end|>\n");
|
||||
assert_eq!(ending, [metadata.tokenizer.eos(), 198]);
|
||||
assert!(cached.ends_with(&ending));
|
||||
let tag = super::super::conversation_tag("system", mode, &history);
|
||||
let tag = super::super::conversation_tag(
|
||||
super::super::ModelFamily::Qwen,
|
||||
"system",
|
||||
mode,
|
||||
&history,
|
||||
);
|
||||
// Full template, MTPLX EOS frontier and scalar pre-EOS
|
||||
// frontier must all append the same complete turn boundary.
|
||||
for missing in 0..=ending.len() {
|
||||
|
||||
+34
-2
@@ -8,6 +8,7 @@ use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use unicode_normalization_alignments::UnicodeNormalization;
|
||||
|
||||
const HIGH_REASONING_PREFIX: &str = "Reasoning Effort: Absolute maximum with no shortcuts permitted.\n\
|
||||
You MUST be very thorough in your thinking and comprehensively decompose the problem to resolve the root cause, rigorously stress-testing your logic against all potential paths, edge cases, and adversarial scenarios.\n\
|
||||
@@ -54,10 +55,18 @@ pub(super) struct Tokenizer {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct QwenTokenizerFile {
|
||||
normalizer: QwenNormalizer,
|
||||
added_tokens: Vec<QwenAddedToken>,
|
||||
model: QwenBpe,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "type")]
|
||||
enum QwenNormalizer {
|
||||
#[serde(rename = "NFC")]
|
||||
Nfc,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct QwenAddedToken {
|
||||
id: usize,
|
||||
@@ -190,6 +199,7 @@ impl Tokenizer {
|
||||
&fs::read(path).map_err(|error| format!("{}: {error}", path.display()))?,
|
||||
)
|
||||
.map_err(|error| format!("{}: {error}", path.display()))?;
|
||||
let QwenNormalizer::Nfc = file.normalizer;
|
||||
if file.model.kind != "BPE" || file.model.byte_fallback {
|
||||
return Err("Qwen tokenizer must use BPE without byte fallback".into());
|
||||
}
|
||||
@@ -772,7 +782,10 @@ impl Tokenizer {
|
||||
}
|
||||
|
||||
fn tokenize_qwen(&self, text: &str, output: &mut Vec<i32>) {
|
||||
for piece in qwen_pieces(text) {
|
||||
// Added tokens are extracted first by tokenize_rendered. Normalize each
|
||||
// remaining span before the trained split and BPE, as in tokenizers.
|
||||
let normalized = qwen_normalize(text);
|
||||
for piece in qwen_pieces(&normalized) {
|
||||
self.emit_piece(piece.as_bytes(), output);
|
||||
}
|
||||
}
|
||||
@@ -867,6 +880,21 @@ impl Tokenizer {
|
||||
}
|
||||
}
|
||||
|
||||
fn qwen_normalize(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.is_ascii() {
|
||||
text.into()
|
||||
} else {
|
||||
text.nfc()
|
||||
.map(|(character, _)| character)
|
||||
.collect::<String>()
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn qwen_normalization_changes(text: &str) -> bool {
|
||||
qwen_normalize(text) != text
|
||||
}
|
||||
|
||||
/// 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,
|
||||
@@ -1214,7 +1242,7 @@ mod tests {
|
||||
let rendered = render_text_prompt(
|
||||
ModelRef::Gguf(&model),
|
||||
&bootstrap,
|
||||
conversation_tag("", settings.reasoning_mode, &[]),
|
||||
conversation_tag(model.shape.family, "", settings.reasoning_mode, &[]),
|
||||
&messages,
|
||||
&settings,
|
||||
);
|
||||
@@ -1386,3 +1414,7 @@ mod tests {
|
||||
#[cfg(test)]
|
||||
#[path = "tokenizer_issue111.rs"]
|
||||
mod issue111;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tokenizer_issue116.rs"]
|
||||
mod issue116;
|
||||
@@ -100,13 +100,22 @@ fn issue111_qwen_tokens_and_requests() {
|
||||
case["pieces"],
|
||||
"split {text:?}"
|
||||
);
|
||||
let mut component = Vec::new();
|
||||
for piece in qwen_pieces(text) {
|
||||
tokenizer.emit_piece(piece.as_bytes(), &mut component);
|
||||
}
|
||||
assert_eq!(
|
||||
serde_json::json!(component),
|
||||
case["ids"],
|
||||
"component {text:?}"
|
||||
);
|
||||
for ids in [tokenizer.tokenize(text), tokenizer.tokenize_rendered(text)] {
|
||||
assert_eq!(serde_json::json!(ids), case["ids"], "{text:?}");
|
||||
assert_eq!(serde_json::json!(ids), case["full_ids"], "{text:?}");
|
||||
let decoded = ids
|
||||
.iter()
|
||||
.flat_map(|&id| tokenizer.token_bytes(id).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(decoded, text.as_bytes());
|
||||
assert_eq!(decoded, qwen_normalize(text).as_bytes());
|
||||
}
|
||||
}
|
||||
let requests: serde_json::Value =
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
use super::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
#[test]
|
||||
fn nfc_contract_and_composition() {
|
||||
assert!(serde_json::from_str::<QwenNormalizer>(r#"{"type":"NFC"}"#).is_ok());
|
||||
for unsupported in [
|
||||
"null",
|
||||
r#"{"type":"NFD"}"#,
|
||||
r#"{"type":"NFKC"}"#,
|
||||
r#"{"type":"Sequence","normalizers":[]}"#,
|
||||
] {
|
||||
assert!(serde_json::from_str::<QwenNormalizer>(unsupported).is_err());
|
||||
}
|
||||
for (text, expected) in [
|
||||
("e\u{301}", "é"),
|
||||
("a\u{301}\u{323}", "ạ\u{301}"),
|
||||
("각", "각"),
|
||||
("① Ⅷ ² 𝟘", "① Ⅷ ² 𝟘"),
|
||||
("ASCII", "ASCII"),
|
||||
] {
|
||||
assert_eq!(qwen_normalize(text), expected);
|
||||
assert_eq!(qwen_normalization_changes(text), text != expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_affected_qwen_history_changes_checkpoint_tags() {
|
||||
use crate::engine::{checkpoint_matches_prefix, conversation_key, conversation_tag};
|
||||
let message = ChatTurn {
|
||||
user: true,
|
||||
tool: false,
|
||||
system: false,
|
||||
skip_previous_eos: false,
|
||||
reasoning: None,
|
||||
reasoning_complete: true,
|
||||
content: "é".into(),
|
||||
};
|
||||
for (system, content, reasoning) in [
|
||||
("", "é", None),
|
||||
("e\u{301}", "é", None),
|
||||
("", "e\u{301}", None),
|
||||
("", "é", Some("e\u{301}")),
|
||||
] {
|
||||
let history = [ChatTurn {
|
||||
content: content.into(),
|
||||
reasoning: reasoning.map(str::to_owned),
|
||||
..message.clone()
|
||||
}];
|
||||
let old: [u8; 32] = Sha256::digest(conversation_key(
|
||||
ModelFamily::DeepSeek,
|
||||
system,
|
||||
ReasoningMode::Low,
|
||||
&history,
|
||||
))
|
||||
.into();
|
||||
let new = conversation_tag(ModelFamily::Qwen, system, ReasoningMode::Low, &history);
|
||||
let changed = !system.is_empty() || content != "é" || reasoning.is_some();
|
||||
assert_eq!(old != new, changed);
|
||||
for family in [ModelFamily::DeepSeek, ModelFamily::Glm] {
|
||||
assert_eq!(
|
||||
conversation_tag(family, system, ReasoningMode::Low, &history),
|
||||
old
|
||||
);
|
||||
}
|
||||
let next = [history[0].clone(), message.clone()];
|
||||
let next_key = conversation_key(ModelFamily::Qwen, system, ReasoningMode::Low, &next);
|
||||
assert!(next_key.starts_with(&conversation_key(
|
||||
ModelFamily::Qwen,
|
||||
system,
|
||||
ReasoningMode::Low,
|
||||
&history
|
||||
)));
|
||||
assert_eq!(
|
||||
next_key.starts_with(&conversation_key(
|
||||
ModelFamily::DeepSeek,
|
||||
system,
|
||||
ReasoningMode::Low,
|
||||
&history
|
||||
)),
|
||||
!changed
|
||||
);
|
||||
assert!(checkpoint_matches_prefix(
|
||||
ModelFamily::Qwen,
|
||||
new,
|
||||
system,
|
||||
ReasoningMode::Low,
|
||||
&next
|
||||
));
|
||||
assert_eq!(
|
||||
checkpoint_matches_prefix(ModelFamily::Qwen, old, system, ReasoningMode::Low, &next),
|
||||
!changed
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "CPU-only; pinned NFC receipts and installed Qwen tokenizer"]
|
||||
fn issue116_nfc_tokens_and_requests() {
|
||||
let root = std::path::PathBuf::from(std::env::var_os("DS4_QWEN38_ARTIFACTS").unwrap());
|
||||
let oracle = std::path::PathBuf::from(std::env::var_os("DS4_ISSUE116_ORACLE").unwrap());
|
||||
let read = |name: &str| -> serde_json::Value {
|
||||
serde_json::from_slice(&fs::read(oracle.join(name)).unwrap()).unwrap()
|
||||
};
|
||||
let tokenizer = Tokenizer::load_qwen(&root.join("tokenizer.json")).unwrap();
|
||||
let scalar = read("scalar-nfc.json");
|
||||
let text: String = (0..=0x10ffff)
|
||||
.filter_map(char::from_u32)
|
||||
.flat_map(|c| ['a', c, '\u{301}', '\u{323}', '|'])
|
||||
.collect();
|
||||
let normalized = qwen_normalize(&text);
|
||||
assert_eq!(normalized.len() as u64, scalar["bytes"].as_u64().unwrap());
|
||||
assert_eq!(
|
||||
Sha256::digest(normalized.as_bytes())
|
||||
.iter()
|
||||
.map(|b| format!("{b:02x}"))
|
||||
.collect::<String>(),
|
||||
scalar["sha256"].as_str().unwrap()
|
||||
);
|
||||
let cases = read("tokens.json");
|
||||
for case in cases.as_array().unwrap() {
|
||||
let text = case["text"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
qwen_normalize(text),
|
||||
case["normalized"].as_str().unwrap(),
|
||||
"{text:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::json!(tokenizer.tokenize(text)),
|
||||
case["plain_ids"],
|
||||
"plain {text:?}"
|
||||
);
|
||||
let ids = tokenizer.tokenize_rendered(text);
|
||||
assert_eq!(serde_json::json!(ids), case["ids"], "rendered {text:?}");
|
||||
let decoded = ids
|
||||
.iter()
|
||||
.flat_map(|&id| tokenizer.token_bytes(id).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
decoded,
|
||||
case["decoded"].as_str().unwrap().as_bytes(),
|
||||
"decode {text:?}"
|
||||
);
|
||||
}
|
||||
for case in read("requests.json").as_array().unwrap() {
|
||||
let effort = 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: m["reasoning_content"].as_str().map(str::to_owned),
|
||||
reasoning_complete: true,
|
||||
content: m["content"].as_str().unwrap().into(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let ids = tokenizer.encode_conversation(system, &messages, effort);
|
||||
assert_eq!(
|
||||
serde_json::json!(ids),
|
||||
case["ids"],
|
||||
"{} {system:?}",
|
||||
case["effort"]
|
||||
);
|
||||
let mut resumed = tokenizer.encode_history(system, &messages[..2], effort);
|
||||
resumed.extend(tokenizer.encode_continuation(&messages[2].content, effort, false));
|
||||
assert_eq!(resumed, ids);
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"effort":case["effort"],"system":system,"context_tokens":ids.len(),"exact":true})
|
||||
);
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"case":"nfc", "scalar_sha256":scalar["sha256"],"token_cases":cases.as_array().unwrap().len(),"requests":8,"exact":true})
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user