Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
162 lines
5.7 KiB
Rust
162 lines
5.7 KiB
Rust
//! Extract the Qwen tokenizer assets from GGUF without a Python runtime.
|
|
|
|
use std::{
|
|
collections::BTreeMap,
|
|
error::Error,
|
|
fs::{self, File},
|
|
io::Write,
|
|
path::{Path, PathBuf},
|
|
};
|
|
|
|
use serde_json::json;
|
|
|
|
use crate::gguf;
|
|
|
|
type Result<T> = std::result::Result<T, Box<dyn Error>>;
|
|
|
|
// Kept byte-for-byte equivalent to the upstream qwen35 oracle pattern.
|
|
pub(crate) const QWEN35_PATTERN: &str = concat!(
|
|
r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])",
|
|
r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+",
|
|
r"|\p{N}",
|
|
r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*",
|
|
r"|\s*[\r\n]+",
|
|
r"|\s+(?!\S)",
|
|
r"|\s+",
|
|
);
|
|
|
|
pub fn extract(gguf_path: &Path, output: &Path) -> Result<PathBuf> {
|
|
let metadata = gguf::tokenizer_metadata(gguf_path)?;
|
|
fs::create_dir_all(output)?;
|
|
let destination = output.join("tokenizer");
|
|
if destination.exists() || destination.is_symlink() {
|
|
return Err(format!(
|
|
"tokenizer destination already exists: {}",
|
|
destination.display()
|
|
)
|
|
.into());
|
|
}
|
|
let stage = output.join(format!(".tokenizer-{}.tmp", std::process::id()));
|
|
fs::create_dir(&stage)?;
|
|
let result = (|| -> Result<()> {
|
|
let mut vocab = BTreeMap::new();
|
|
for (id, token) in metadata.tokens.iter().enumerate() {
|
|
vocab.insert(token, id);
|
|
}
|
|
write_synced(&stage.join("vocab.json"), &serde_json::to_vec(&vocab)?)?;
|
|
write_synced(
|
|
&stage.join("merges.txt"),
|
|
metadata.merges.join("\n").as_bytes(),
|
|
)?;
|
|
write_synced(
|
|
&stage.join("token_type.json"),
|
|
&serde_json::to_vec(&metadata.token_types)?,
|
|
)?;
|
|
let config = json!({
|
|
"model": metadata.model,
|
|
"pre": metadata.pre,
|
|
"vocab_size": metadata.tokens.len(),
|
|
"n_merges": metadata.merges.len(),
|
|
"special_ids": metadata.special_ids,
|
|
"add_bos_token": false,
|
|
"pre_pattern": QWEN35_PATTERN,
|
|
"pre_pattern_source": ".ref/llama.cpp src/llama-vocab.cpp L396 (LLAMA_VOCAB_PRE_TYPE_QWEN35)",
|
|
});
|
|
write_synced(
|
|
&stage.join("tokenizer.json"),
|
|
&serde_json::to_vec_pretty(&config)?,
|
|
)?;
|
|
write_synced(
|
|
&stage.join("chat_template.jinja"),
|
|
metadata.chat_template.as_bytes(),
|
|
)?;
|
|
File::open(&stage)?.sync_all()?;
|
|
crate::immutable_directory::publish(&stage, &destination)?;
|
|
File::open(output)?.sync_all()?;
|
|
Ok(())
|
|
})();
|
|
if result.is_err() {
|
|
let _ = fs::remove_dir_all(&stage);
|
|
}
|
|
result?;
|
|
Ok(destination)
|
|
}
|
|
|
|
fn write_synced(path: &Path, bytes: &[u8]) -> Result<()> {
|
|
let mut file = File::create(path)?;
|
|
file.write_all(bytes)?;
|
|
file.sync_all()?;
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn gguf_string(bytes: &mut Vec<u8>, value: &str) {
|
|
bytes.extend_from_slice(&(value.len() as u64).to_le_bytes());
|
|
bytes.extend_from_slice(value.as_bytes());
|
|
}
|
|
|
|
fn string_field(bytes: &mut Vec<u8>, key: &str, value: &str) {
|
|
gguf_string(bytes, key);
|
|
bytes.extend_from_slice(&8u32.to_le_bytes());
|
|
gguf_string(bytes, value);
|
|
}
|
|
|
|
fn string_array(bytes: &mut Vec<u8>, key: &str, values: &[&str]) {
|
|
gguf_string(bytes, key);
|
|
bytes.extend_from_slice(&9u32.to_le_bytes());
|
|
bytes.extend_from_slice(&8u32.to_le_bytes());
|
|
bytes.extend_from_slice(&(values.len() as u64).to_le_bytes());
|
|
for value in values {
|
|
gguf_string(bytes, value);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn exports_checked_tokenizer_assets() {
|
|
let mut gguf = b"GGUF".to_vec();
|
|
gguf.extend_from_slice(&3u32.to_le_bytes());
|
|
gguf.extend_from_slice(&0u64.to_le_bytes()); // no tensors
|
|
gguf.extend_from_slice(&7u64.to_le_bytes());
|
|
string_field(&mut gguf, "tokenizer.ggml.model", "gpt2");
|
|
string_field(&mut gguf, "tokenizer.ggml.pre", "qwen35");
|
|
string_array(
|
|
&mut gguf,
|
|
"tokenizer.ggml.tokens",
|
|
&["a", "b", "ab", "<|im_end|>"],
|
|
);
|
|
string_array(&mut gguf, "tokenizer.ggml.merges", &["a b"]);
|
|
gguf_string(&mut gguf, "tokenizer.ggml.token_type");
|
|
gguf.extend_from_slice(&9u32.to_le_bytes());
|
|
gguf.extend_from_slice(&4u32.to_le_bytes());
|
|
gguf.extend_from_slice(&4u64.to_le_bytes());
|
|
for value in [1u32, 1, 1, 3] {
|
|
gguf.extend_from_slice(&value.to_le_bytes());
|
|
}
|
|
gguf_string(&mut gguf, "tokenizer.ggml.eos_token_id");
|
|
gguf.extend_from_slice(&4u32.to_le_bytes());
|
|
gguf.extend_from_slice(&3u32.to_le_bytes());
|
|
string_field(&mut gguf, "tokenizer.chat_template", "{{ messages }}");
|
|
gguf.resize(gguf.len().div_ceil(32) * 32, 0);
|
|
|
|
let root = std::env::temp_dir().join(format!("strata-tokens-{}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&root);
|
|
fs::create_dir(&root).unwrap();
|
|
let source = root.join("tiny.gguf");
|
|
fs::write(&source, &gguf).unwrap();
|
|
let dir = extract(&source, &root).unwrap();
|
|
let vocab: BTreeMap<String, u32> =
|
|
serde_json::from_slice(&fs::read(dir.join("vocab.json")).unwrap()).unwrap();
|
|
assert_eq!(vocab["<|im_end|>"], 3);
|
|
assert_eq!(fs::read_to_string(dir.join("merges.txt")).unwrap(), "a b");
|
|
let config: serde_json::Value =
|
|
serde_json::from_slice(&fs::read(dir.join("tokenizer.json")).unwrap()).unwrap();
|
|
assert_eq!(config["special_ids"]["tokenizer.ggml.eos_token_id"], 3);
|
|
assert_eq!(config["pre_pattern"], QWEN35_PATTERN);
|
|
assert!(extract(&source, &root).is_err());
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
}
|