STRA-338 size-fn: harmony, offline-tools: remaining production functions within limits, type aliases, usage text wrapped

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 18:40:50 +01:00
parent 65a46dc867
commit 5e7131f72c
8 changed files with 134 additions and 69 deletions
+11 -9
View File
@@ -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<Event>) {
if self.mode == Mode::Header {
self.absorb_header(true);
@@ -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::*;
+13 -2
View File
@@ -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<String>,
) {
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> {
+8 -1
View File
@@ -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],
+42 -26
View File
@@ -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<String> {
let metadata = leleka_model_format::gguf::tokenizer_metadata(options.gguf)?;
fn token_kinds(tokens: &[String]) -> Vec<u32> {
let (_, chars) = leleka_tokenizer::byte_alphabet();
let n = metadata.tokens.len();
let kinds: Vec<u32> = 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<String> {
let bytes: Vec<u8> = 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<String> {
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<i32> = base.iter().copied().collect();
let added: Vec<i32> = (0..n as i32)
@@ -157,22 +185,10 @@ pub fn run(options: &Options) -> Result<String> {
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<u8> = 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)
}
+10 -1
View File
@@ -132,7 +132,11 @@ fn pairs_by_use(traces: &[&Path], n_expert: usize) -> Result<Vec<(u16, u16)>> {
Ok(by_use.into_iter().map(|(pair, _)| pair).collect())
}
pub fn run(options: &Options) -> Result<String> {
/// 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<Ranking> {
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<String> {
&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<String> {
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());
+23 -8
View File
@@ -133,7 +133,11 @@ fn read_at(file: &mut File, at: u64, length: usize) -> Result<Vec<u8>> {
}
/// 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<u8>) -> Result<DenseEn
Ok((q8_0(&f32s), "q8_0", rows, cols))
}
/// Appends `raw` to `dense.bin` on a 256-byte boundary; returns the offset it starts at and the new end.
fn append_aligned(dense: &mut impl Write, offset: usize, raw: &[u8]) -> 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<String>, 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()?;
+25 -21
View File
@@ -143,19 +143,21 @@ pub fn embd_bf16_pack(model: &Path, out: &Path) -> Result<String> {
))
}
fn shard_number(name: &str) -> Result<u64> {
name.rsplit(".shard_")
.next()
.and_then(|rest| rest.split('.').next())
.and_then(|n| n.parse::<u64>().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<u64, String>, 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::<u64>().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<f32> {
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<u64, String>,
) -> Result<(Vec<(PathBuf, u64, u64)>, u64, u64)> {
) -> Result<PleParts> {
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<String> {
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<u8> {
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<String> {
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<String> {
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)?;