AnyBot/src/m2v.rs

357 lines
14 KiB
Rust
Raw Normal View History

記憶: a page to see it, a few lines picked while typing, a local model The memory had grown into a list carried whole, a top-14 recalled by a trigram index and pasted into the system prompt with the clock, and a page that broke its own layout. Nobody could see what went to the model, the prompt cache missed every message, and 「記住」 kept saying the same thing twice. Rebuilt per the spec (docs/memory.md): - Three kinds in memory.db: 記得的事 (fact), 做過的事 (event, a line per finished turn), 整理過的 (rollup). Each keeps pinned, uses, last_used, deleted, superseded_by, span. state.json keeps the facts as the copy that syncs; the page reads SQLite. - Search: jieba words ∪ CJK bigrams in an FTS5 unicode61 table (Traditional text goes through Simplified first), weighted share of query terms hit; plus local vectors, vec = clamp((cos−0.35)/0.35). score = max + 0.15×min, events ×0.9. ≥0.15 suggested, ≥0.5 ticked, ≥0.55 carried when nobody chose (3 at most). - What the model gets: the system prompt has the time zone and the pinned memories only, the same every turn. Each person message gets 〔送出時間〕 and 〔相關記憶〕 from Message.memories, built in group_history into a transient Message.context, so the beginning of a chat reads the same next turn (cache hits) and the event log, skills and audit see only what was typed. A memory already carried in view isn't carried again; each carry counts a use. - Picks travel with the message: Cmd::Send / POST send / sync act "memories" (empty = none; absent = the brain chooses, once, saved). - remember finds the like one (cos ≥ 0.85 or the same words) and asks for `replaces`; the old one is superseded, never carried. A fact forgotten and remembered again comes back. New search_memory (query, kind), with dates; read-only. - Nightly on the brain, no model: events past 30 days fold into a line per week (「11/3–11/9 做過的事(14 件):整理照片 ×3…」, ≤400 chars, like with like by words or vectors), weeks past 180 days into months; the folded go to 最近刪除 for 30 days. Facts are never removed. The page offers duplicates, facts unused for half a year, and what can fold now. - Local model: minishlab/potion-multilingual-128M through m2v.rs (same token ids as model2vec-rs on 13/13 sentences, cos ≥ 0.9999, without tokenizers' 1.1 GB). Converted while downloading: vocab.bin, table.i8 (int8 + row scales), dims.json, 137 MB kept of 530 MB; ANYBOT_HF_BASE picks a mirror (now passed into the server's brain container too). Loaded when first needed (34 ms), let go after 10 idle minutes. The brain loads it; a screen only with a document folder set; hands and phones never. 設定 › 一般 › 語意搜尋: 本機模型/Ollama/關閉; a new engine clears every vector. - Three files, three connections: memory.db (backed up nightly, 7 kept), docs.db (a cache), oplog/audit.db (30 days). An old audit.db hands its memories and documents over once and shrinks (a real one: 172 MB → 16 KB). docs_search scans every chunk now, vectors cached in RAM (it stopped at 8000); FTS optimize + VACUUM daily (260 MB of tombstones over 31 MB of text). - API: POST /api/memory (owner) and /api/sync/memory (mirror). Reads answer on the HTTP thread; writes go through phone_act("memory"). - Screens: a memory dialog (Bot menu 記憶…, Bot settings 打開記憶) with counts, live search, filters, suggestions, per-item kind/date/uses and pin/edit/forget/restore; chips above the composer 300 ms after typing stops, with a token estimate; 「帶了 N 條記憶」 under person messages. The phone has the same as a 記憶 tab, chips and tag. Checked: make test passes (app 297, relay 16), with new tests for the scores and thresholds, Traditional Chinese segmentation, remember's dedupe and replaces, two turns sending the same beginning, no double carry, weekly/monthly folding and the trash, and the audit.db move. Brain idle 37 MB as before, ~230 MB with the model loaded; search on the brain 0.2–0.5 ms, 7–44 ms from the phone page. A deadlock found on the way (stats re-taking the lock) is fixed and tested. Docs: docs/memory.md has the whole design; FEATURES.md, protocol, architecture (zh/en), multi-device and install say what changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
2026-11-10 23:46:50 +00:00
//! 本機語意模型: 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();
記憶: a page to see it, a few lines picked while typing, a local model The memory had grown into a list carried whole, a top-14 recalled by a trigram index and pasted into the system prompt with the clock, and a page that broke its own layout. Nobody could see what went to the model, the prompt cache missed every message, and 「記住」 kept saying the same thing twice. Rebuilt per the spec (docs/memory.md): - Three kinds in memory.db: 記得的事 (fact), 做過的事 (event, a line per finished turn), 整理過的 (rollup). Each keeps pinned, uses, last_used, deleted, superseded_by, span. state.json keeps the facts as the copy that syncs; the page reads SQLite. - Search: jieba words ∪ CJK bigrams in an FTS5 unicode61 table (Traditional text goes through Simplified first), weighted share of query terms hit; plus local vectors, vec = clamp((cos−0.35)/0.35). score = max + 0.15×min, events ×0.9. ≥0.15 suggested, ≥0.5 ticked, ≥0.55 carried when nobody chose (3 at most). - What the model gets: the system prompt has the time zone and the pinned memories only, the same every turn. Each person message gets 〔送出時間〕 and 〔相關記憶〕 from Message.memories, built in group_history into a transient Message.context, so the beginning of a chat reads the same next turn (cache hits) and the event log, skills and audit see only what was typed. A memory already carried in view isn't carried again; each carry counts a use. - Picks travel with the message: Cmd::Send / POST send / sync act "memories" (empty = none; absent = the brain chooses, once, saved). - remember finds the like one (cos ≥ 0.85 or the same words) and asks for `replaces`; the old one is superseded, never carried. A fact forgotten and remembered again comes back. New search_memory (query, kind), with dates; read-only. - Nightly on the brain, no model: events past 30 days fold into a line per week (「11/3–11/9 做過的事(14 件):整理照片 ×3…」, ≤400 chars, like with like by words or vectors), weeks past 180 days into months; the folded go to 最近刪除 for 30 days. Facts are never removed. The page offers duplicates, facts unused for half a year, and what can fold now. - Local model: minishlab/potion-multilingual-128M through m2v.rs (same token ids as model2vec-rs on 13/13 sentences, cos ≥ 0.9999, without tokenizers' 1.1 GB). Converted while downloading: vocab.bin, table.i8 (int8 + row scales), dims.json, 137 MB kept of 530 MB; ANYBOT_HF_BASE picks a mirror (now passed into the server's brain container too). Loaded when first needed (34 ms), let go after 10 idle minutes. The brain loads it; a screen only with a document folder set; hands and phones never. 設定 › 一般 › 語意搜尋: 本機模型/Ollama/關閉; a new engine clears every vector. - Three files, three connections: memory.db (backed up nightly, 7 kept), docs.db (a cache), oplog/audit.db (30 days). An old audit.db hands its memories and documents over once and shrinks (a real one: 172 MB → 16 KB). docs_search scans every chunk now, vectors cached in RAM (it stopped at 8000); FTS optimize + VACUUM daily (260 MB of tombstones over 31 MB of text). - API: POST /api/memory (owner) and /api/sync/memory (mirror). Reads answer on the HTTP thread; writes go through phone_act("memory"). - Screens: a memory dialog (Bot menu 記憶…, Bot settings 打開記憶) with counts, live search, filters, suggestions, per-item kind/date/uses and pin/edit/forget/restore; chips above the composer 300 ms after typing stops, with a token estimate; 「帶了 N 條記憶」 under person messages. The phone has the same as a 記憶 tab, chips and tag. Checked: make test passes (app 297, relay 16), with new tests for the scores and thresholds, Traditional Chinese segmentation, remember's dedupe and replaces, two turns sending the same beginning, no double carry, weekly/monthly folding and the trash, and the audit.db move. Brain idle 37 MB as before, ~230 MB with the model loaded; search on the brain 0.2–0.5 ms, 7–44 ms from the phone page. A deadlock found on the way (stats re-taking the lock) is fixed and tested. Docs: docs/memory.md has the whole design; FEATURES.md, protocol, architecture (zh/en), multi-device and install say what changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
2026-11-10 23:46:50 +00:00
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> {
記憶: a page to see it, a few lines picked while typing, a local model The memory had grown into a list carried whole, a top-14 recalled by a trigram index and pasted into the system prompt with the clock, and a page that broke its own layout. Nobody could see what went to the model, the prompt cache missed every message, and 「記住」 kept saying the same thing twice. Rebuilt per the spec (docs/memory.md): - Three kinds in memory.db: 記得的事 (fact), 做過的事 (event, a line per finished turn), 整理過的 (rollup). Each keeps pinned, uses, last_used, deleted, superseded_by, span. state.json keeps the facts as the copy that syncs; the page reads SQLite. - Search: jieba words ∪ CJK bigrams in an FTS5 unicode61 table (Traditional text goes through Simplified first), weighted share of query terms hit; plus local vectors, vec = clamp((cos−0.35)/0.35). score = max + 0.15×min, events ×0.9. ≥0.15 suggested, ≥0.5 ticked, ≥0.55 carried when nobody chose (3 at most). - What the model gets: the system prompt has the time zone and the pinned memories only, the same every turn. Each person message gets 〔送出時間〕 and 〔相關記憶〕 from Message.memories, built in group_history into a transient Message.context, so the beginning of a chat reads the same next turn (cache hits) and the event log, skills and audit see only what was typed. A memory already carried in view isn't carried again; each carry counts a use. - Picks travel with the message: Cmd::Send / POST send / sync act "memories" (empty = none; absent = the brain chooses, once, saved). - remember finds the like one (cos ≥ 0.85 or the same words) and asks for `replaces`; the old one is superseded, never carried. A fact forgotten and remembered again comes back. New search_memory (query, kind), with dates; read-only. - Nightly on the brain, no model: events past 30 days fold into a line per week (「11/3–11/9 做過的事(14 件):整理照片 ×3…」, ≤400 chars, like with like by words or vectors), weeks past 180 days into months; the folded go to 最近刪除 for 30 days. Facts are never removed. The page offers duplicates, facts unused for half a year, and what can fold now. - Local model: minishlab/potion-multilingual-128M through m2v.rs (same token ids as model2vec-rs on 13/13 sentences, cos ≥ 0.9999, without tokenizers' 1.1 GB). Converted while downloading: vocab.bin, table.i8 (int8 + row scales), dims.json, 137 MB kept of 530 MB; ANYBOT_HF_BASE picks a mirror (now passed into the server's brain container too). Loaded when first needed (34 ms), let go after 10 idle minutes. The brain loads it; a screen only with a document folder set; hands and phones never. 設定 › 一般 › 語意搜尋: 本機模型/Ollama/關閉; a new engine clears every vector. - Three files, three connections: memory.db (backed up nightly, 7 kept), docs.db (a cache), oplog/audit.db (30 days). An old audit.db hands its memories and documents over once and shrinks (a real one: 172 MB → 16 KB). docs_search scans every chunk now, vectors cached in RAM (it stopped at 8000); FTS optimize + VACUUM daily (260 MB of tombstones over 31 MB of text). - API: POST /api/memory (owner) and /api/sync/memory (mirror). Reads answer on the HTTP thread; writes go through phone_act("memory"). - Screens: a memory dialog (Bot menu 記憶…, Bot settings 打開記憶) with counts, live search, filters, suggestions, per-item kind/date/uses and pin/edit/forget/restore; chips above the composer 300 ms after typing stops, with a token estimate; 「帶了 N 條記憶」 under person messages. The phone has the same as a 記憶 tab, chips and tag. Checked: make test passes (app 297, relay 16), with new tests for the scores and thresholds, Traditional Chinese segmentation, remember's dedupe and replaces, two turns sending the same beginning, no double carry, weekly/monthly folding and the trash, and the audit.db move. Brain idle 37 MB as before, ~230 MB with the model loaded; search on the brain 0.2–0.5 ms, 7–44 ms from the phone page. A deadlock found on the way (stats re-taking the lock) is fixed and tested. Docs: docs/memory.md has the whole design; FEATURES.md, protocol, architecture (zh/en), multi-device and install say what changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
2026-11-10 23:46:50 +00:00
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)
}