From 5e7131f72c2c9b25739d331a3ef520f7c70cd692 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 18:40:50 +0100 Subject: [PATCH] STRA-338 size-fn: harmony, offline-tools: remaining production functions within limits, type aliases, usage text wrapped --- crates/harmony/src/parse.rs | 20 +++--- .../harmony/src/render/impl_renderoptions.rs | 3 +- crates/harmony/src/render/render_namespace.rs | 15 +++- crates/offline-tools/src/cli.rs | 9 ++- crates/offline-tools/src/draft_vocab.rs | 68 ++++++++++++------- crates/offline-tools/src/make_profile.rs | 11 ++- crates/offline-tools/src/mtp_rt.rs | 31 ++++++--- crates/offline-tools/src/packs.rs | 46 +++++++------ 8 files changed, 134 insertions(+), 69 deletions(-) diff --git a/crates/harmony/src/parse.rs b/crates/harmony/src/parse.rs index 1292e68d..2ad177af 100644 --- a/crates/harmony/src/parse.rs +++ b/crates/harmony/src/parse.rs @@ -157,15 +157,7 @@ impl HarmonyParser { self.reset_header(); self.mode = Mode::Header; } - Special::Channel => { - // the text before the marker (a role, or a recipient written after the start) is - // not the channel name; the text after it is - if self.mode == Mode::Header { - self.absorb_header(false); - self.channel = None; - self.mode = Mode::Header; - } - } + Special::Channel => self.begin_channel(), Special::Constrain => { if self.mode == Mode::Header { self.absorb_header(true); @@ -182,6 +174,16 @@ impl HarmonyParser { } } + fn begin_channel(&mut self) { + // the text before the marker (a role, or a recipient written after the start) is + // not the channel name; the text after it is + if self.mode == Mode::Header { + self.absorb_header(false); + self.channel = None; + self.mode = Mode::Header; + } + } + fn begin_body(&mut self, events: &mut Vec) { if self.mode == Mode::Header { self.absorb_header(true); diff --git a/crates/harmony/src/render/impl_renderoptions.rs b/crates/harmony/src/render/impl_renderoptions.rs index 76136e57..96cd6d70 100644 --- a/crates/harmony/src/render/impl_renderoptions.rs +++ b/crates/harmony/src/render/impl_renderoptions.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl RenderOptions, fn err, fn truthy, fn to_json, fn write_json_string, fn write_json .... +//! Moved out of the parent module by STRA-338: impl RenderOptions, fn err, fn truthy, fn to_json, +//! fn write_json_string, fn write_json .... #[allow(unused_imports)] use super::*; diff --git a/crates/harmony/src/render/render_namespace.rs b/crates/harmony/src/render/render_namespace.rs index bdcb99f1..bc3c47bb 100644 --- a/crates/harmony/src/render/render_namespace.rs +++ b/crates/harmony/src/render/render_namespace.rs @@ -213,7 +213,19 @@ fn render_assistant( { return Err(err("thinking must not contain channel markers")); } - if is_last && !options.add_generation_prompt { + render_final(out, message, content, is_last && !options.add_generation_prompt, last_tool_call); + Ok(()) +} + +/// The assistant's answer: the closing message of the conversation ends in `<|return|>`, any other in `<|end|>`. +fn render_final( + out: &mut Out, + message: &Message, + content: &str, + closing: bool, + last_tool_call: &mut Option, +) { + if closing { if let Some(thinking) = &message.thinking { out.lit("<|start|>assistant<|channel|>analysis<|message|>"); out.text(thinking); @@ -228,7 +240,6 @@ fn render_assistant( out.lit("<|end|>"); *last_tool_call = None; } - Ok(()) } fn render_tool_call(out: &mut Out, message: &Message, call: &ToolCall) -> Result<(), HarmonyError> { diff --git a/crates/offline-tools/src/cli.rs b/crates/offline-tools/src/cli.rs index 2035c474..cfdccf6a 100644 --- a/crates/offline-tools/src/cli.rs +++ b/crates/offline-tools/src/cli.rs @@ -4,7 +4,14 @@ use std::path::{Path, PathBuf}; use crate::{Result, draft_vocab, make_profile, mtp_rt, packs}; -pub const USAGE: &str = "tools embd-bf16-pack --model DIR --out FILE.gguf|tools ple-fp8-pack --model DIR --out FILE.gguf|tools draft-vocab --gguf FIRST.gguf [--base IDS.bin] [--add han,kana,hangul,cjk_punct,cjk,cyrillic] [--out IDS.bin] [--stats]|tools make-profile [TRACE ...] (--base PROFILE.bin | --no-base) --out PROFILE.bin [--n-expert N]|tools mtp-rt --gguf mtp-q2_0.gguf --out DIR [--n-expert N]"; +pub const USAGE: &str = concat!( + "tools embd-bf16-pack --model DIR --out FILE.gguf|", + "tools ple-fp8-pack --model DIR --out FILE.gguf|", + "tools draft-vocab --gguf FIRST.gguf [--base IDS.bin] [--add han,kana,hangul,cjk_punct,cjk,cyrillic]", + " [--out IDS.bin] [--stats]|", + "tools make-profile [TRACE ...] (--base PROFILE.bin | --no-base) --out PROFILE.bin [--n-expert N]|", + "tools mtp-rt --gguf mtp-q2_0.gguf --out DIR [--n-expert N]" +); struct Flags<'a> { args: &'a [String], diff --git a/crates/offline-tools/src/draft_vocab.rs b/crates/offline-tools/src/draft_vocab.rs index e3289e15..117b3cc9 100644 --- a/crates/offline-tools/src/draft_vocab.rs +++ b/crates/offline-tools/src/draft_vocab.rs @@ -126,27 +126,55 @@ fn script_stats(kinds: &[u32], label: &str, selected: &[i32]) -> String { format!("{label}: {} ids; {}\n", selected.len(), cells.join(", ")) } -/// Returns what the Python tool prints; writes `out` when given. -pub fn run(options: &Options) -> Result { - let metadata = leleka_model_format::gguf::tokenizer_metadata(options.gguf)?; +fn token_kinds(tokens: &[String]) -> Vec { let (_, chars) = leleka_tokenizer::byte_alphabet(); - let n = metadata.tokens.len(); - let kinds: Vec = metadata - .tokens + tokens .iter() .map(|t| token_text(t, &chars).map_or(0, |text| scripts_of(&text))) - .collect(); - let base = read_base_ids(options.base)?; + .collect() +} + +fn check_base_ids(path: Option<&Path>, base: &[i32], n: usize) -> Result<()> { if base.iter().any(|&i| i < 0 || i as usize >= n) { return Err(format!( "{} has ids outside the vocabulary ({n})", - options - .base - .map(|p| p.display().to_string()) - .unwrap_or_default() + path.map(|p| p.display().to_string()).unwrap_or_default() ) .into()); } + Ok(()) +} + +/// The stats lines of the base ids and of the base plus the added ids. +fn selection_stats(kinds: &[u32], base: &[i32], added: &[i32], ids: &[i32]) -> String { + let mut report = String::new(); + if !base.is_empty() { + report += &script_stats(kinds, "base", base); + } + if !added.is_empty() { + report += &script_stats(kinds, "new", ids); + } + report +} + +fn write_ids(out: &Path, ids: &[i32], n_added: usize) -> Result { + let bytes: Vec = ids.iter().flat_map(|i| i.to_le_bytes()).collect(); + fs::write(out, bytes)?; + Ok(format!( + "wrote {}: {} ids ({} added)\n", + out.display(), + ids.len(), + n_added + )) +} + +/// Returns what the Python tool prints; writes `out` when given. +pub fn run(options: &Options) -> Result { + let metadata = leleka_model_format::gguf::tokenizer_metadata(options.gguf)?; + let n = metadata.tokens.len(); + let kinds = token_kinds(&metadata.tokens); + let base = read_base_ids(options.base)?; + check_base_ids(options.base, &base, n)?; let want = wanted_scripts(options.add)?; let have: BTreeSet = base.iter().copied().collect(); let added: Vec = (0..n as i32) @@ -157,22 +185,10 @@ pub fn run(options: &Options) -> Result { let mut report = String::new(); if options.stats || options.out.is_none() { - if !base.is_empty() { - report += &script_stats(&kinds, "base", &base); - } - if !added.is_empty() { - report += &script_stats(&kinds, "new", &ids); - } + report += &selection_stats(&kinds, &base, &added, &ids); } if let Some(out) = options.out { - let bytes: Vec = ids.iter().flat_map(|i| i.to_le_bytes()).collect(); - fs::write(out, bytes)?; - report += &format!( - "wrote {}: {} ids ({} added)\n", - out.display(), - ids.len(), - added.len() - ); + report += &write_ids(out, &ids, added.len())?; } Ok(report) } diff --git a/crates/offline-tools/src/make_profile.rs b/crates/offline-tools/src/make_profile.rs index c9ca5581..34f05450 100644 --- a/crates/offline-tools/src/make_profile.rs +++ b/crates/offline-tools/src/make_profile.rs @@ -132,7 +132,11 @@ fn pairs_by_use(traces: &[&Path], n_expert: usize) -> Result> { Ok(by_use.into_iter().map(|(pair, _)| pair).collect()) } -pub fn run(options: &Options) -> Result { +/// The ranked pairs, how many came from the base and how many from the traces. +type Ranking = (Vec<(u16, u16)>, usize, usize); + +/// The profile order: the base, the traced pairs by use, then every other pair across the layers. +fn rank_pairs(options: &Options) -> Result { let mut ranked: Vec<(u16, u16)> = Vec::new(); let mut seen = std::collections::HashSet::new(); if let Some(base) = options.base { @@ -152,6 +156,11 @@ pub fn run(options: &Options) -> Result { &mut seen, (0..options.n_expert).flat_map(|e| (0..N_LAYER).map(move |l| (l as u16, e as u16))), ); + Ok((ranked, n_base, n_trace)) +} + +pub fn run(options: &Options) -> Result { + let (ranked, n_base, n_trace) = rank_pairs(options)?; write_profile(options.out, &ranked, options.n_expert)?; if read_profile(options.out, options.n_expert)? != ranked { return Err("the profile did not survive the round trip".into()); diff --git a/crates/offline-tools/src/mtp_rt.rs b/crates/offline-tools/src/mtp_rt.rs index ad8fcc3f..df582442 100644 --- a/crates/offline-tools/src/mtp_rt.rs +++ b/crates/offline-tools/src/mtp_rt.rs @@ -133,7 +133,11 @@ fn read_at(file: &mut File, at: u64, length: usize) -> Result> { } /// The gate/up and down expert tensors, checked against the geometry. -fn expert_tensors<'a>(index: &'a TensorIndex, gguf_path: &Path, g: &Geometry) -> Result<(&'a TensorInfo, &'a TensorInfo)> { +fn expert_tensors<'a>( + index: &'a TensorIndex, + gguf_path: &Path, + g: &Geometry, +) -> Result<(&'a TensorInfo, &'a TensorInfo)> { let find = |name: &str| { index .tensors @@ -157,7 +161,13 @@ fn expert_tensors<'a>(index: &'a TensorIndex, gguf_path: &Path, g: &Geometry) -> Ok((gu, dn)) } -fn write_experts(file: &mut File, start: u64, tensors: (&TensorInfo, &TensorInfo), out: &Path, g: &Geometry) -> Result<()> { +fn write_experts( + file: &mut File, + start: u64, + tensors: (&TensorInfo, &TensorInfo), + out: &Path, + g: &Geometry, +) -> Result<()> { let (gu, dn) = tensors; let gu_bytes = 2 * g.ff * (g.h / 64) * Q2_BLOCK; let dn_bytes = g.h * (g.ff / 64) * Q2_BLOCK; @@ -220,6 +230,14 @@ fn bf16_entry(tensor: &TensorInfo, short: &str, data: Vec) -> Result Result<(usize, usize)> { + let pad = (256 - offset % 256) % 256; + dense.write_all(&vec![0u8; pad])?; + dense.write_all(raw)?; + Ok((offset + pad, offset + pad + raw.len())) +} + /// Writes `dense.bin` and `dense.txt`; returns the `dense.txt` lines and the size of `dense.bin`. fn write_dense(file: &mut File, index: &TensorIndex, out: &Path) -> Result<(Vec, usize)> { let start = index.summary.data_start; @@ -234,12 +252,9 @@ fn write_dense(file: &mut File, index: &TensorIndex, out: &Path) -> Result<(Vec< let short = short.strip_prefix("layers.0.").unwrap_or(short); let data = read_at(file, start + tensor.offset, tensor.bytes as usize)?; let (raw, kind, rows, cols) = dense_entry(tensor, short, data)?; - let pad = (256 - offset % 256) % 256; - dense.write_all(&vec![0u8; pad])?; - offset += pad; - dense.write_all(&raw)?; - lines.push(format!("{short} {kind} {rows} {cols} {offset} {}", raw.len())); - offset += raw.len(); + let (at, end) = append_aligned(&mut dense, offset, &raw)?; + lines.push(format!("{short} {kind} {rows} {cols} {at} {}", raw.len())); + offset = end; } dense.flush()?; dense.into_inner().map_err(|e| e.into_error())?.sync_all()?; diff --git a/crates/offline-tools/src/packs.rs b/crates/offline-tools/src/packs.rs index 6615aec2..39dda2f6 100644 --- a/crates/offline-tools/src/packs.rs +++ b/crates/offline-tools/src/packs.rs @@ -143,19 +143,21 @@ pub fn embd_bf16_pack(model: &Path, out: &Path) -> Result { )) } +fn shard_number(name: &str) -> Result { + name.rsplit(".shard_") + .next() + .and_then(|rest| rest.split('.').next()) + .and_then(|n| n.parse::().ok()) + .ok_or_else(|| format!("{name}: cannot read the shard number").into()) +} + /// The numbered n-gram shard tensors and the name of the weight_scale tensor. fn ple_shard_names(model: &Path, map: &WeightMap) -> Result<(std::collections::BTreeMap, String)> { let mut shards = std::collections::BTreeMap::new(); let mut scale_name = None; for name in map.keys() { if name.contains(".ngram_embedding.shard_") && name.ends_with(".weight") { - let number = name - .rsplit(".shard_") - .next() - .and_then(|rest| rest.split('.').next()) - .and_then(|n| n.parse::().ok()) - .ok_or_else(|| format!("{name}: cannot read the shard number"))?; - shards.insert(number, name.clone()); + shards.insert(shard_number(name)?, name.clone()); } else if name.ends_with(".ngram_embedding.weight_scale") { scale_name = Some(name.clone()); } @@ -191,12 +193,15 @@ fn ple_scale(model: &Path, map: &WeightMap, scale_name: &str) -> Result { Ok(f32::from_bits(u32::from(u16::from_le_bytes(bits)) << 16)) } +/// The shards as (file, data offset, bytes), the total rows and the common width. +type PleParts = (Vec<(PathBuf, u64, u64)>, u64, u64); + /// Every shard as (file, data offset, bytes), with the total rows and the common width. fn ple_parts( model: &Path, map: &WeightMap, shards: &std::collections::BTreeMap, -) -> Result<(Vec<(PathBuf, u64, u64)>, u64, u64)> { +) -> Result { let (mut parts, mut rows, mut dim) = (Vec::new(), 0u64, None); for name in shards.values() { let file = shard_file(model, map, name)?; @@ -219,13 +224,7 @@ fn ple_parts( Ok((parts, rows, dim.unwrap_or(0))) } -/// `ple_fp8_pack.py`: `per_layer_token_embd.weight` `[dim, rows]` as I8 holding the FP8 E4M3 bytes, with -/// `strata.ple.format` and the BF16 `weight_scale` as an F32 KV. -pub fn ple_fp8_pack(model: &Path, out: &Path) -> Result { - let map = weight_map(model)?; - let (shards, scale_name) = ple_shard_names(model, &map)?; - let scale = ple_scale(model, &map, &scale_name)?; - let (parts, rows, dim) = ple_parts(model, &map, &shards)?; +fn ple_header(model: &Path, scale: f32, shape: [u64; 2]) -> Vec { let kvs = [ kv_string("general.architecture", "strata-ple"), kv_string("general.name", "PLE n-gram table, FP8 E4M3 as shipped"), @@ -233,12 +232,17 @@ pub fn ple_fp8_pack(model: &Path, out: &Path) -> Result { kv_f32("strata.ple.scale", scale), kv_string("strata.ple.source", model_source(model)), ]; - let head = one_tensor_header( - &kvs, - "per_layer_token_embd.weight", - [dim, rows], - GGML_TYPE_I8, - ); + one_tensor_header(&kvs, "per_layer_token_embd.weight", shape, GGML_TYPE_I8) +} + +/// `ple_fp8_pack.py`: `per_layer_token_embd.weight` `[dim, rows]` as I8 holding the FP8 E4M3 bytes, with +/// `strata.ple.format` and the BF16 `weight_scale` as an F32 KV. +pub fn ple_fp8_pack(model: &Path, out: &Path) -> Result { + let map = weight_map(model)?; + let (shards, scale_name) = ple_shard_names(model, &map)?; + let scale = ple_scale(model, &map, &scale_name)?; + let (parts, rows, dim) = ple_parts(model, &map, &shards)?; + let head = ple_header(model, scale, [dim, rows]); write_published(out, &head, rows * dim, |writer| { for (file, offset, n) in &parts { copy_range(file, *offset, *n, writer)?;