AnyBot/src/m2v.rs

357 lines
14 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! 本機語意模型: a Model2Vec static model (minishlab/potion-multilingual-128M), loaded the lean way.
//!
//! A static model is a table: each token of the vocabulary has a vector, and a text's vector is
//! the mean of its tokens' rows. The official crate gets the tokens from the general-purpose
//! `tokenizers` library, which holds this 500,000-piece vocabulary in ~700 MB; here the same
//! Unigram (SentencePiece) cut is done with a plain map (~30 MB), and the table is kept as int8
//! with one scale per row (128 MB instead of 512). Output matches the official crate (see the
//! tests): same pieces, same mean, same normalisation.
//!
//! Files (made once by `prepare`, from the model's own files):
//! - `vocab.bin`: the pieces and their scores, from tokenizer.json.
//! - `table.i8`: rows × dim int8, then rows f32 scales (row × scale = the original row).
//! - `dims.json`: {"rows": …, "dim": …, "median": …, "unk": …}
use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::Path;
use unicode_normalization::UnicodeNormalization;
pub struct Model {
vocab: HashMap<Box<str>, u32>,
scores: Vec<f32>,
/// Longest piece, in characters (a cut never looks further back than this).
max_chars: usize,
unk: u32,
min_score: f32,
table: Vec<u8>,
scales: Vec<f32>,
dim: usize,
/// Median piece length in bytes: texts are cut to 512 × this before tokenizing (as the
/// official crate does), so a huge document costs no more than its first pages.
median: usize,
}
const MAX_TOKENS: usize = 512;
/// SentencePiece's unknown-piece penalty below the lowest score.
const UNK_PENALTY: f32 = 10.0;
/// Pieces longer than this many characters are never tried (none of them is common text).
const MAX_PIECE_CHARS: usize = 32;
impl Model {
pub fn load(dir: &Path) -> Result<Model, String> {
let dims: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("dims.json")).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
let rows = dims["rows"].as_u64().unwrap_or(0) as usize;
let dim = dims["dim"].as_u64().unwrap_or(0) as usize;
let median = dims["median"].as_u64().unwrap_or(6).max(1) as usize;
let unk = dims["unk"].as_u64().unwrap_or(1) as u32;
if rows == 0 || dim == 0 {
return Err("模型檔不完整".into());
}
let mut table = std::fs::read(dir.join("table.i8")).map_err(|e| e.to_string())?;
if table.len() != rows * dim + rows * 4 {
return Err("模型檔大小不對(下載沒有完成?)".into());
}
let scales: Vec<f32> = table[rows * dim..].as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect();
table.truncate(rows * dim);
table.shrink_to_fit();
let raw = std::fs::read(dir.join("vocab.bin")).map_err(|e| e.to_string())?;
let (vocab, scores, max_chars) = read_vocab(&raw)?;
if scores.len() != rows {
return Err("模型的字表和向量表對不上".into());
}
let min_score = scores.iter().copied().fold(f32::INFINITY, f32::min);
Ok(Model { vocab, scores, max_chars, unk, min_score, table, scales, dim, median })
}
/// The text's vector (unit length; all zeros for a text with no known piece).
pub fn encode(&self, text: &str) -> Vec<f32> {
let cut: &str = match text.char_indices().nth(MAX_TOKENS * self.median) {
Some((i, _)) => &text[..i],
None => text,
};
let ids = self.tokenize(&normalize(cut));
let mut sum = vec![0f32; self.dim];
let mut n = 0usize;
for &id in ids.iter().take(MAX_TOKENS) {
if id == self.unk {
continue;
}
let i = id as usize;
let s = self.scales[i];
let row = &self.table[i * self.dim..(i + 1) * self.dim];
for (o, &q) in sum.iter_mut().zip(row) {
*o += (q as i8) as f32 * s;
}
n += 1;
}
let d = n.max(1) as f32;
let mut sq = 0f32;
for x in sum.iter_mut() {
*x /= d;
sq += *x * *x;
}
let norm = sq.sqrt().max(1e-12);
for x in sum.iter_mut() {
*x /= norm;
}
sum
}
/// The Unigram cut: the sequence of pieces with the highest total score (Viterbi).
pub fn tokenize(&self, s: &str) -> Vec<u32> {
let bounds: Vec<usize> = s.char_indices().map(|(i, _)| i).chain(std::iter::once(s.len())).collect();
let n = bounds.len() - 1;
if n == 0 {
return vec![];
}
let mut best = vec![f64::NEG_INFINITY; n + 1];
let mut back: Vec<(usize, u32)> = vec![(0, 0); n + 1];
best[0] = 0.0;
let unk_score = (self.min_score - UNK_PENALTY) as f64;
for end in 1..=n {
let lo = end.saturating_sub(self.max_chars);
for start in lo..end {
if best[start] == f64::NEG_INFINITY {
continue;
}
if let Some(&id) = self.vocab.get(&s[bounds[start]..bounds[end]]) {
let sc = best[start] + self.scores[id as usize] as f64;
if sc > best[end] {
best[end] = sc;
back[end] = (start, id);
}
}
}
// A character no piece covers is one unknown piece.
if best[end] == f64::NEG_INFINITY && best[end - 1] > f64::NEG_INFINITY {
best[end] = best[end - 1] + unk_score;
back[end] = (end - 1, self.unk);
}
}
let mut out = vec![];
let mut at = n;
while at > 0 {
let (start, id) = back[at];
out.push(id);
at = start;
}
out.reverse();
// (SentencePiece fuses consecutive unknown pieces into one; they are skipped anyway.)
out.dedup_by(|a, b| *a == self.unk && *b == self.unk);
out
}
}
/// The model's normaliser: NFKC, ASCII punctuation set apart, whitespace collapsed, then
/// SentencePiece's ▁ for spaces with one in front.
pub fn normalize(text: &str) -> String {
let mut s = String::with_capacity(text.len() + 8);
for c in text.nfkc() {
if c.is_ascii_punctuation() {
s.push(' ');
s.push(c);
s.push(' ');
} else if c.is_whitespace() || c.is_control() {
s.push(' ');
} else {
s.push(c);
}
}
let mut out = String::with_capacity(s.len() + 4);
if s.trim().is_empty() {
return out;
}
out.push('▁');
let mut space = false;
for c in s.trim().chars() {
if c == ' ' {
if !space {
out.push('▁');
}
space = true;
} else {
out.push(c);
space = false;
}
}
out
}
/// The words and their rows, the per-row scales, and the vector size.
type Vocab = (HashMap<Box<str>, u32>, Vec<f32>, usize);
fn read_vocab(raw: &[u8]) -> Result<Vocab, String> {
if raw.len() < 8 || &raw[..4] != b"AVB1" {
return Err("字表檔格式不對".into());
}
let count = u32::from_le_bytes([raw[4], raw[5], raw[6], raw[7]]) as usize;
let mut vocab: HashMap<Box<str>, u32> = HashMap::with_capacity(count);
let mut scores = Vec::with_capacity(count);
let mut at = 8;
let mut max_chars = 1;
for id in 0..count {
let len = *raw.get(at).ok_or("字表檔不完整")? as usize;
let piece = std::str::from_utf8(raw.get(at + 1..at + 1 + len).ok_or("字表檔不完整")?).map_err(|_| "字表檔不是 UTF-8")?;
let sc = raw.get(at + 1 + len..at + 5 + len).ok_or("字表檔不完整")?;
scores.push(f32::from_le_bytes([sc[0], sc[1], sc[2], sc[3]]));
let chars = piece.chars().count();
if chars <= MAX_PIECE_CHARS {
max_chars = max_chars.max(chars);
vocab.entry(piece.into()).or_insert(id as u32);
}
at += 5 + len;
}
Ok((vocab, scores, max_chars))
}
/// tokenizer.json (a Unigram model) → vocab.bin, and the numbers dims.json needs.
pub fn convert_vocab(tokenizer_json: &[u8], out: &mut impl Write) -> Result<(usize, u32, usize), String> {
#[derive(serde::Deserialize)]
struct Tok {
model: TokModel,
}
#[derive(serde::Deserialize)]
struct TokModel {
#[serde(rename = "type", default)]
kind: String,
vocab: Vec<(String, f64)>,
#[serde(default)]
unk_id: Option<u32>,
}
let t: Tok = serde_json::from_slice(tokenizer_json).map_err(|e| format!("tokenizer.json 讀不懂:{e}"))?;
if !t.model.kind.is_empty() && t.model.kind != "Unigram" {
return Err(format!("不支援這種字表({})", t.model.kind));
}
let mut lens: Vec<usize> = t.model.vocab.iter().map(|(p, _)| p.len()).collect();
lens.sort_unstable();
let median = lens.get(lens.len() / 2).copied().unwrap_or(1).max(1);
let w = |out: &mut dyn Write, b: &[u8]| out.write_all(b).map_err(|e| e.to_string());
w(out, b"AVB1")?;
w(out, &(t.model.vocab.len() as u32).to_le_bytes())?;
for (p, s) in &t.model.vocab {
let b = p.as_bytes();
let b = &b[..b.len().min(255)];
w(out, &[b.len() as u8])?;
w(out, b)?;
w(out, &(*s as f32).to_le_bytes())?;
}
Ok((t.model.vocab.len(), t.model.unk_id.unwrap_or(1), median))
}
/// model.safetensors (F32 or F16 `embeddings`, optional per-token `weights`), read as a stream
/// (straight from the download) → table.i8: each row as int8 with its own scale, written as it
/// goes, so neither the 512 MB original nor the table is ever held whole. Returns (rows, dim).
pub fn quantize(mut r: impl Read, out: &mut impl Write) -> Result<(usize, usize), String> {
let io = |e: std::io::Error| e.to_string();
let mut n = [0u8; 8];
r.read_exact(&mut n).map_err(io)?;
let n = u64::from_le_bytes(n) as usize;
if n > 16 << 20 {
return Err("模型檔開頭不對".into());
}
let mut h = vec![0u8; n];
r.read_exact(&mut h).map_err(io)?;
let h: serde_json::Value = serde_json::from_slice(&h).map_err(|e| e.to_string())?;
let mut ts: Vec<(String, String, Vec<usize>, usize, usize)> = h
.as_object()
.ok_or("模型檔開頭不對")?
.iter()
.filter(|(k, _)| *k != "__metadata__")
.map(|(k, v)| {
let o = &v["data_offsets"];
let shape = v["shape"].as_array().map(|a| a.iter().filter_map(|x| x.as_u64().map(|x| x as usize)).collect()).unwrap_or_default();
(k.clone(), v["dtype"].as_str().unwrap_or("").to_string(), shape, o[0].as_u64().unwrap_or(0) as usize, o[1].as_u64().unwrap_or(0) as usize)
})
.collect();
ts.sort_by_key(|t| t.3);
if ts.iter().any(|t| t.0 == "mapping") {
return Err("不支援壓縮過字表的模型".into());
}
let mut pos = 0usize;
let mut scales: Vec<f32> = vec![];
let mut weights: Option<Vec<f32>> = None;
let mut dims = (0usize, 0usize);
let f16 = |b: [u8; 2]| f16_to_f32(u16::from_le_bytes(b));
for (name, dtype, shape, start, end) in ts {
if start < pos {
return Err("模型檔內容重疊".into());
}
std::io::copy(&mut (&mut r).take((start - pos) as u64), &mut std::io::sink()).map_err(io)?;
let w = match dtype.as_str() {
"F32" => 4,
"F16" => 2,
_ if name == "weights" || matches!(name.as_str(), "embeddings" | "0" | "embedding.weight") => return Err(format!("不支援 {dtype}")),
_ => 1,
};
if matches!(name.as_str(), "embeddings" | "0" | "embedding.weight") && shape.len() == 2 {
let (rows, cols) = (shape[0], shape[1]);
if rows * cols * w != end - start {
return Err("模型檔大小不對".into());
}
dims = (rows, cols);
let mut buf = vec![0u8; cols * w];
let mut row = vec![0f32; cols];
let mut q = vec![0u8; cols];
for _ in 0..rows {
r.read_exact(&mut buf).map_err(io)?;
for (i, x) in row.iter_mut().enumerate() {
*x = if w == 4 { f32::from_le_bytes([buf[i * 4], buf[i * 4 + 1], buf[i * 4 + 2], buf[i * 4 + 3]]) } else { f16([buf[i * 2], buf[i * 2 + 1]]) };
}
let m = row.iter().fold(0f32, |a, x| a.max(x.abs()));
let s = if m > 0.0 { m / 127.0 } else { 0.0 };
for (o, x) in q.iter_mut().zip(&row) {
*o = if s > 0.0 { (x / s).round().clamp(-127.0, 127.0) as i8 as u8 } else { 0 };
}
out.write_all(&q).map_err(io)?;
scales.push(s);
}
} else if name == "weights" {
let mut buf = vec![0u8; end - start];
r.read_exact(&mut buf).map_err(io)?;
weights = Some(buf.chunks_exact(w).map(|c| if w == 4 { f32::from_le_bytes([c[0], c[1], c[2], c[3]]) } else { f16([c[0], c[1]]) }).collect());
} else {
std::io::copy(&mut (&mut r).take((end - start) as u64), &mut std::io::sink()).map_err(io)?;
}
pos = end;
}
if dims.0 == 0 {
return Err("模型檔裡沒有向量表".into());
}
// A model's own per-token weights fold into the row scales (a row is only ever used times both).
if let Some(w) = weights {
for (s, w) in scales.iter_mut().zip(w) {
*s *= w;
}
}
for s in &scales {
out.write_all(&s.to_le_bytes()).map_err(io)?;
}
Ok(dims)
}
fn f16_to_f32(h: u16) -> f32 {
let s = ((h >> 15) & 1) as u32;
let e = ((h >> 10) & 0x1f) as u32;
let m = (h & 0x3ff) as u32;
let bits = if e == 0 {
if m == 0 {
s << 31
} else {
let mut e2: i32 = 127 - 15 + 1;
let mut m2 = m;
while m2 & 0x400 == 0 {
m2 <<= 1;
e2 -= 1;
}
(s << 31) | ((e2 as u32) << 23) | ((m2 & 0x3ff) << 13)
}
} else if e == 31 {
(s << 31) | 0x7f80_0000 | (m << 13)
} else {
(s << 31) | ((e + 127 - 15) << 23) | (m << 13)
};
f32::from_bits(bits)
}