cortiq-cli 0.9.25

Command-line tools for the CMF model format: inspect, convert, run and serve .cmf models.
//! `cortiq genesis` — metric genesis of a q4tp / q2tp file in Rust
//! (`cortiq_engine::genesis`): the f16 `lo` / `step` of every tiled row and
//! the RMSNorm gains trained under a teacher's top-K, codes frozen; the
//! output is the same file with new f16 fields.

use cortiq_core::format::TensorSpec;
use cortiq_core::quant::{f16_to_f32, f32_to_f16, q2tp_sections, q4tp_sections};
use cortiq_core::{CmfModel, NormStyle, TensorDtype};
use cortiq_engine::genesis::{GenesisHyper, Student, TopK, run_genesis, teacher_topk};
use std::collections::HashMap;
use std::sync::Arc;

/// `cortiq genesis` arguments. A struct of its own (not fields of the
/// `Commands` variant) so `main`'s dispatch frame stays small.
#[derive(clap::Args, Debug)]
pub struct GenesisCli {
    /// The quantized student (.cmf, q4tp / q2tp linears)
    pub model: String,
    /// Float reference of the same model (f16 / bf16 / f32 .cmf)
    #[arg(long)]
    pub teacher: String,
    /// Training token ids (space-separated, e.g. from CMF_PPL_IDS_OUT)
    #[arg(long)]
    pub train_ids: String,
    /// Held-out token ids (best-checkpoint selection)
    #[arg(long)]
    pub held_ids: String,
    #[arg(long, default_value_t = 256)]
    pub train_windows: usize,
    #[arg(long, default_value_t = 24)]
    pub held_windows: usize,
    #[arg(long, default_value_t = 512)]
    pub window: usize,
    /// Passes over the training windows (ignored with --steps)
    #[arg(long, default_value_t = 1.0)]
    pub epochs: f64,
    #[arg(long, default_value_t = 0)]
    pub steps: usize,
    /// Windows per optimizer step
    #[arg(long, default_value_t = 8)]
    pub bs: usize,
    /// Windows per micro-batch
    #[arg(long, default_value_t = 4)]
    pub mb: usize,
    #[arg(long, default_value_t = 1e-3)]
    pub lr: f64,
    #[arg(long, default_value_t = 16.0)]
    pub step_lr_div: f64,
    #[arg(long, default_value_t = 8)]
    pub warmup: usize,
    #[arg(long, default_value_t = 16)]
    pub eval_every: usize,
    #[arg(long, default_value_t = 64)]
    pub topk: usize,
    /// Train `lo` only (no step tilt)
    #[arg(long, default_value_t = false)]
    pub no_step: bool,
    /// Freeze the RMSNorm gains
    #[arg(long, default_value_t = false)]
    pub no_norm: bool,
    /// Directory for the teacher's cached top-K (reused across students)
    #[arg(long)]
    pub teacher_cache: Option<String>,
    #[arg(long)]
    pub output: String,
    /// Training history as JSON
    #[arg(long)]
    pub report: Option<String>,
}

#[inline(never)]
pub fn run(c: GenesisCli) -> anyhow::Result<()> {
    cmd_genesis(GenesisArgs {
        model: c.model,
        teacher: c.teacher,
        train_ids: c.train_ids,
        held_ids: c.held_ids,
        train_windows: c.train_windows,
        held_windows: c.held_windows,
        window: c.window,
        epochs: c.epochs,
        steps: c.steps,
        hy: GenesisHyper {
            steps: c.steps,
            bs: c.bs,
            mb: c.mb,
            lr: c.lr,
            step_lr_div: c.step_lr_div,
            warmup: c.warmup,
            eval_every: c.eval_every,
            train_step: !c.no_step,
            train_norms: !c.no_norm,
            seed: 0,
        },
        topk: c.topk,
        teacher_cache: c.teacher_cache,
        output: c.output,
        report: c.report,
    })
}

pub struct GenesisArgs {
    pub model: String,
    pub teacher: String,
    pub train_ids: String,
    pub held_ids: String,
    pub train_windows: usize,
    pub held_windows: usize,
    pub window: usize,
    pub epochs: f64,
    pub steps: usize,
    pub hy: GenesisHyper,
    pub topk: usize,
    pub teacher_cache: Option<String>,
    pub output: String,
    pub report: Option<String>,
}

fn read_ids(path: &str) -> anyhow::Result<Vec<u32>> {
    let s = std::fs::read_to_string(path)?;
    s.split_ascii_whitespace()
        .map(|t| t.parse::<u32>().map_err(|e| anyhow::anyhow!("{path}: {e}")))
        .collect()
}

/// `n` windows of `seq` tokens, evenly spaced over `ids` (cortiq ppl's rule).
fn windows(ids: &[u32], n: usize, seq: usize) -> anyhow::Result<Vec<Vec<u32>>> {
    anyhow::ensure!(
        ids.len() > seq + 1,
        "corpus of {} tokens is shorter than a window",
        ids.len()
    );
    let step = (ids.len() - seq - 1) / n.max(1);
    anyhow::ensure!(
        step > 0,
        "{n} windows of {seq} do not fit {} tokens",
        ids.len()
    );
    Ok((0..n)
        .map(|i| ids[i * step..i * step + seq].to_vec())
        .collect())
}

fn digest(w: &[Vec<u32>]) -> u64 {
    let mut h = 0xcbf29ce484222325u64;
    for x in w.iter().flatten() {
        h ^= *x as u64;
        h = h.wrapping_mul(0x100000001b3);
    }
    h
}

/// The teacher's top-K for `w`, from `dir` when a matching cache exists.
fn teacher_rows(
    teacher: &Arc<CmfModel>,
    tpath: &str,
    w: &[Vec<u32>],
    k: usize,
    mb: usize,
    dir: Option<&str>,
    tag: &str,
) -> anyhow::Result<TopK> {
    let size = std::fs::metadata(tpath)?.len();
    let key = format!("{tag}-{:016x}-{size}-{k}", digest(w));
    if let Some(d) = dir {
        let meta = format!("{d}/{key}.json");
        if let Ok(m) = std::fs::read_to_string(&meta) {
            let m: serde_json::Value = serde_json::from_str(&m)?;
            let lp: Vec<f32> = std::fs::read(format!("{d}/{key}.lp"))?
                .chunks_exact(4)
                .map(|c| f32::from_le_bytes(c.try_into().unwrap()))
                .collect();
            let ix: Vec<u32> = std::fs::read(format!("{d}/{key}.ix"))?
                .chunks_exact(4)
                .map(|c| u32::from_le_bytes(c.try_into().unwrap()))
                .collect();
            let seq = w[0].len();
            anyhow::ensure!(
                lp.len() == w.len() * (seq - 1) * k && ix.len() == lp.len(),
                "teacher cache {meta}: wrong size"
            );
            eprintln!("teacher {tag}: cached ({} windows)", w.len());
            return Ok(TopK {
                k,
                seq,
                lp,
                ix,
                ce: m["ce"].as_f64().unwrap_or(f64::NAN),
            });
        }
    }
    let t = teacher_topk(teacher, w, k, mb, &|s| eprintln!("  {s}")).map_err(anyhow::Error::msg)?;
    if let Some(d) = dir {
        std::fs::create_dir_all(d)?;
        let lp: Vec<u8> = t.lp.iter().flat_map(|x| x.to_le_bytes()).collect();
        let ix: Vec<u8> = t.ix.iter().flat_map(|x| x.to_le_bytes()).collect();
        std::fs::write(format!("{d}/{key}.lp"), lp)?;
        std::fs::write(format!("{d}/{key}.ix"), ix)?;
        std::fs::write(format!("{d}/{key}.json"), serde_json::json!({"windows": w.len(), "seq": t.seq, "k": k, "ce": t.ce, "teacher": tpath}).to_string())?;
    }
    eprintln!("teacher {tag}: {} windows, CE {:.5}", w.len(), t.ce);
    Ok(t)
}

pub fn cmd_genesis(a: GenesisArgs) -> anyhow::Result<()> {
    let t0 = std::time::Instant::now();
    let student_m = Arc::new(CmfModel::open(&a.model)?);
    let teacher_m = Arc::new(CmfModel::open(&a.teacher)?);
    let tr = windows(&read_ids(&a.train_ids)?, a.train_windows, a.window)?;
    let he = windows(&read_ids(&a.held_ids)?, a.held_windows, a.window)?;
    let mut hy = a.hy.clone();
    hy.steps = if a.steps > 0 {
        a.steps
    } else {
        ((a.epochs * tr.len() as f64) / hy.bs as f64)
            .round()
            .max(1.0) as usize
    };
    eprintln!(
        "genesis: {} train / {} held windows of {}, {} steps of {} (micro-batch {}), lr {}, step {}, norms {}",
        tr.len(),
        he.len(),
        a.window,
        hy.steps,
        hy.bs,
        hy.mb,
        hy.lr,
        hy.train_step,
        hy.train_norms
    );
    let tk_tr = teacher_rows(
        &teacher_m,
        &a.teacher,
        &tr,
        a.topk,
        hy.mb,
        a.teacher_cache.as_deref(),
        "train",
    )?;
    let tk_he = teacher_rows(
        &teacher_m,
        &a.teacher,
        &he,
        a.topk,
        hy.mb,
        a.teacher_cache.as_deref(),
        "held",
    )?;
    drop(teacher_m);
    let mut st =
        Student::new(&student_m, hy.clone(), &|s| eprintln!("{s}")).map_err(anyhow::Error::msg)?;
    let out = run_genesis(&mut st, &tr, &he, &tk_tr, &tk_he, &|s| eprintln!("{s}"))
        .map_err(anyhow::Error::msg)?;
    drop(st);

    // Write: the source bytes with the trained f16 fields.
    let rows: HashMap<&str, (&[f32], &[f32])> = out
        .rows
        .iter()
        .map(|(n, a, b)| (n.as_str(), (&a[..], &b[..])))
        .collect();
    let norms: HashMap<&str, &[f32]> = out
        .norms
        .iter()
        .map(|(n, v)| (n.as_str(), &v[..]))
        .collect();
    let o = if matches!(student_m.arch().norm_style, NormStyle::Gemma) {
        1.0f64
    } else {
        0.0
    };
    let (mut n_rows, mut n_norms) = (0usize, 0usize);
    let mut specs = Vec::with_capacity(student_m.tensors.len());
    for e in &student_m.tensors {
        let mut data = student_m.entry_bytes(e).to_vec();
        if let Some(&(av, bv)) = rows.get(e.name.as_str()) {
            let (r, c) = (e.shape[0], e.shape[1]);
            let po = match e.dtype {
                TensorDtype::Q2TiledP => q2tp_sections(r, c).0,
                TensorDtype::Q4TiledP => q4tp_sections(r, c).0,
                other => anyhow::bail!("{}: trained rows on a {other:?} tensor", e.name),
            };
            for i in 0..r {
                let p = &mut data[po + 4 * i..po + 4 * i + 4];
                let lo = f16_to_f32(u16::from_le_bytes([p[0], p[1]]));
                p[0..2].copy_from_slice(&f32_to_f16(lo + av[i]).to_le_bytes());
                if !bv.is_empty() {
                    let st = f16_to_f32(u16::from_le_bytes([p[2], p[3]]));
                    p[2..4].copy_from_slice(&f32_to_f16(st + bv[i]).to_le_bytes());
                }
            }
            n_rows += 1;
        } else if let Some(nv) = norms.get(e.name.as_str()) {
            let len: usize = e.shape.iter().product();
            anyhow::ensure!(
                nv.len() == len,
                "{}: {} gains for {len} channels",
                e.name,
                nv.len()
            );
            let gain = |g: f32, n: f32| ((g as f64 + o) * (n as f64).exp2() - o) as f32;
            match e.dtype {
                TensorDtype::F16 => {
                    for i in 0..len {
                        let g = f16_to_f32(u16::from_le_bytes([data[2 * i], data[2 * i + 1]]));
                        data[2 * i..2 * i + 2]
                            .copy_from_slice(&f32_to_f16(gain(g, nv[i])).to_le_bytes());
                    }
                }
                TensorDtype::F32 => {
                    for i in 0..len {
                        let g = f32::from_le_bytes(data[4 * i..4 * i + 4].try_into().unwrap());
                        data[4 * i..4 * i + 4].copy_from_slice(&gain(g, nv[i]).to_le_bytes());
                    }
                }
                other => anyhow::bail!("{}: cannot write a trained gain into {other:?}", e.name),
            }
            n_norms += 1;
        }
        specs.push(TensorSpec {
            name: e.name.clone(),
            dtype: e.dtype,
            shape: e.shape.clone(),
            data,
        });
    }
    anyhow::ensure!(
        n_rows == out.rows.len() && n_norms == out.norms.len(),
        "not every trained field found its tensor"
    );
    let mut header = student_m.header.clone();
    header.section_hashes = None;
    let mut prov = header
        .provenance
        .clone()
        .unwrap_or_else(|| serde_json::json!({}));
    prov["genesis"] = serde_json::json!({
        "teacher": std::path::Path::new(&a.teacher).file_name().map(|f| f.to_string_lossy().into_owned()),
        "train_windows": tr.len(), "held_windows": he.len(), "window": a.window, "topk": a.topk,
        "best_held_ce": out.report["best_held_ce"], "best_step": out.report["best_step"], "steps": out.report["steps"],
    });
    header.provenance = Some(prov);
    CmfModel::write(&a.output, &header, &specs, None, student_m.vocab.as_deref())
        .map_err(|e| anyhow::anyhow!("write {}: {e}", a.output))?;
    eprintln!(
        "wrote {} ({n_rows} tensors' rows, {n_norms} norms) in {:.0} s",
        a.output,
        t0.elapsed().as_secs_f64()
    );
    drop(specs);
    // The snapped check: the written file, reopened, on the held-out windows.
    let written = Arc::new(CmfModel::open(&a.output)?);
    let chk = Student::new(&written, hy, &|_| {}).map_err(anyhow::Error::msg)?;
    let (sce, skl) = chk.held_scores(&he, &tk_he).map_err(anyhow::Error::msg)?;
    eprintln!(
        "written file: held-out CE {sce:.5} KL {skl:.5} (trained best {:.5}, step 0 {:.5})",
        out.report["best_held_ce"].as_f64().unwrap_or(f64::NAN),
        out.report["held_ce_step0"].as_f64().unwrap_or(f64::NAN)
    );
    let mut rep = out.report.clone();
    rep["held_ce_snapped"] = serde_json::json!(sce);
    rep["held_kl_snapped"] = serde_json::json!(skl);
    if let Some(r) = &a.report {
        std::fs::write(r, serde_json::to_string_pretty(&rep)?)?;
    }
    Ok(())
}