cortiq-cli 0.9.31

Command-line tools for the CMF model format: inspect, convert, run and serve .cmf models.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! The loop sidecar of Qwen4-35B-A3B: `<stem>.loop.cmf` beside the model.
//!
//! The adapter lets the middle layers of the base (`core_start..core_end`) run
//! several times per token: an entry module rebuilds the input of every extra
//! pass from the state before the core and the exit of the previous pass, and
//! a mixer in front of a few core layers feeds that exit in again. The file
//! holds the adapter only, in F32 and in the checkpoint's own names, shapes
//! and orientation, so one sidecar serves every quantization of the base.
//!
//! The gates stay unfolded (`base`, `pass[slot]`, `rem[slot]`): the sum a pass
//! uses depends on the pass count, and the runtime forms it for the count it
//! was started with. Everything that selects the function (core range, mixer
//! layers, which normalizations are matched) is not in the tensor file at all
//! but in `ckpt_best.json`, and the trainer's own defaults describe a
//! different model, so that JSON is a required input and goes into the header
//! unchanged.

use crate::convert::open_safetensors;
use cortiq_core::format::CmfStreamWriter;
use cortiq_core::types::{ModelArch, QuantType, TensorDtype};
use cortiq_core::{CMF_VERSION, CmfHeader, CmfModel};
use std::fs;
use std::path::{Path, PathBuf};

// One definition of the file's names for the writer here and the engine's reader.
use cortiq_engine::qwen4_loop::{FORMAT as SOURCE_FORMAT, NAMESPACE, RECORD_KEY, SIDECAR_ARCH};

const SOURCE_REPO: &str = "sliderforthewin/Looped-Qwen4-35B-A3B";
const SOURCE_FILE: &str = "ckpt_best.safetensors";
/// The base's stream geometry: four hyper-connection streams of 2048.
const HC_COUNT: usize = 4;
const HIDDEN: usize = 2048;
/// Keys the converter adds beside the checkpoint's `loop_config` keys.
const ADDED_KEYS: [&str; 5] = ["format", "step", "source_repo", "source_file", "source_sha256"];
/// Checkpoint tensors the looped forward does not read for a zero LoRA B:
/// the LoRA pairs of the looped layers (`layers.N.*`) and their per-pass scales.
const LORA_SUFFIXES: [&str; 4] = [".lora_a", ".lora_b", ".pass_delta", ".rem_delta"];

/// What was written, for the command's summary.
pub struct Report {
    pub path: PathBuf,
    pub tensors: usize,
    pub payload_bytes: u64,
    pub file_bytes: u64,
    /// Checkpoint tensors left out (LoRA pairs whose B is zero).
    pub skipped: usize,
    pub core_start: usize,
    pub core_end: usize,
    pub mixer_layers: Vec<usize>,
    pub num_passes: usize,
    pub max_trained_passes: usize,
    pub max_passes: usize,
    pub sha256: String,
    /// The checkpoint's JSON carried a hash and the file matched it.
    pub sha256_checked: bool,
    /// The base model the adapter was checked against, when one was named.
    pub base: Option<String>,
}

impl std::fmt::Display for Report {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "✓ wrote loop sidecar {}", self.path.display())?;
        writeln!(
            f,
            "  tensors: {} F32, {} bytes ({:.1} MB; file {} bytes); {} LoRA tensors of the checkpoint not stored (every lora_b is zero)",
            self.tensors,
            self.payload_bytes,
            self.payload_bytes as f64 / 1e6,
            self.file_bytes,
            self.skipped
        )?;
        writeln!(
            f,
            "  core: layers {}..{} run once per pass, mixers before layers {}",
            self.core_start,
            self.core_end - 1,
            list(&self.mixer_layers)
        )?;
        writeln!(
            f,
            "  passes: {} by default, trained up to {}, at most {} (--loops N)",
            self.num_passes, self.max_trained_passes, self.max_passes
        )?;
        writeln!(
            f,
            "  source: sha256 {} ({})",
            self.sha256,
            if self.sha256_checked { "matches ckpt_best.json" } else { "ckpt_best.json carries none to compare" }
        )?;
        match &self.base {
            Some(b) => write!(f, "  base: {b} (width, streams, depth and PLE placement checked)"),
            None => write!(f, "  base: not named, so not checked here (the loader checks it)"),
        }
    }
}

fn list(v: &[usize]) -> String {
    v.iter().map(|l| l.to_string()).collect::<Vec<_>>().join(", ")
}

/// The fields of `loop_config` that fix the function and the tensor shapes.
struct LoopConfig {
    core_start: usize,
    core_end: usize,
    num_passes: usize,
    max_passes: usize,
    max_trained_passes: usize,
    entry_rank: usize,
    mixer_rank: usize,
    mixer_layers: Vec<usize>,
}

type Json = serde_json::Map<String, serde_json::Value>;

fn cfg_usize(cfg: &Json, key: &str) -> anyhow::Result<usize> {
    cfg.get(key)
        .and_then(|v| v.as_u64())
        .map(|v| v as usize)
        .ok_or_else(|| anyhow::anyhow!("loop sidecar: loop_config.{key} is missing or not a non-negative integer"))
}

fn cfg_str<'a>(cfg: &'a Json, key: &str) -> anyhow::Result<&'a str> {
    cfg.get(key)
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("loop sidecar: loop_config.{key} is missing or not a string"))
}

fn cfg_bool(cfg: &Json, key: &str) -> anyhow::Result<bool> {
    cfg.get(key)
        .and_then(|v| v.as_bool())
        .ok_or_else(|| anyhow::anyhow!("loop sidecar: loop_config.{key} is missing or not a boolean"))
}

/// Read `loop_config` and refuse every configuration whose forward is not the
/// one the runtime implements: other values of these switches select other
/// formulas in the trainer, they are not variations of this one.
fn checked_config(cfg: &Json) -> anyhow::Result<LoopConfig> {
    let (hc, hidden) = (cfg_usize(cfg, "hc_count")?, cfg_usize(cfg, "hidden_size")?);
    anyhow::ensure!(
        hc == HC_COUNT && hidden == HIDDEN,
        "loop sidecar: the adapter is for {hc} streams of {hidden}, the runtime's loop is for {HC_COUNT} streams of {HIDDEN}"
    );
    let c = LoopConfig {
        core_start: cfg_usize(cfg, "core_start")?,
        core_end: cfg_usize(cfg, "core_end")?,
        num_passes: cfg_usize(cfg, "num_passes")?,
        max_passes: cfg_usize(cfg, "max_passes")?,
        max_trained_passes: cfg_usize(cfg, "max_trained_passes")?,
        entry_rank: cfg_usize(cfg, "entry_rank")?,
        mixer_rank: cfg_usize(cfg, "mixer_rank")?,
        mixer_layers: cfg
            .get("mixer_layers")
            .and_then(|v| v.as_array())
            .and_then(|a| a.iter().map(|l| l.as_u64().map(|l| l as usize)).collect::<Option<Vec<_>>>())
            .ok_or_else(|| anyhow::anyhow!("loop sidecar: loop_config.mixer_layers is missing or not a list of layer indices"))?,
    };
    // An empty core is no loop: the runtime has no layer to run again and
    // refuses such a record, so it is refused here, before a file is written.
    anyhow::ensure!(
        0 < c.core_start && c.core_start < c.core_end,
        "loop sidecar: core range {}..{} is not 0 < core_start < core_end (the layers before the core give the anchor, and the core needs a layer to run again)",
        c.core_start,
        c.core_end
    );
    // The list is a set: the mixers' tensors are named by layer, so any order
    // is taken (and kept as it is in the record), and the runtime finds each
    // layer's mixer by its number.
    for (i, &l) in c.mixer_layers.iter().enumerate() {
        anyhow::ensure!(
            c.core_start <= l && l < c.core_end,
            "loop sidecar: mixer layer {l} is outside the core {}..{}",
            c.core_start,
            c.core_end
        );
        anyhow::ensure!(!c.mixer_layers[..i].contains(&l), "loop sidecar: mixer layer {l} is listed twice");
    }
    // The per-pass tables hold `max_passes - 1` slots, and the default pass
    // count has to be one the file can run.
    anyhow::ensure!(
        c.max_passes >= 2 && (1..=c.max_passes).contains(&c.num_passes) && c.max_trained_passes >= 1,
        "loop sidecar: pass counts num_passes {}, max_trained_passes {}, max_passes {} are not a usable schedule",
        c.num_passes,
        c.max_trained_passes,
        c.max_passes
    );
    anyhow::ensure!(c.entry_rank >= 1 && c.mixer_rank >= 1, "loop sidecar: entry_rank and mixer_rank must be at least 1");
    let source = cfg_str(cfg, "mixer_source")?;
    anyhow::ensure!(
        source == "core_exit",
        "loop sidecar: mixer_source {source:?} is not supported: the runtime's mixer reads the previous pass's core exit (\"core_exit\")"
    );
    let s_hat = cfg_str(cfg, "s_hat_mode")?;
    anyhow::ensure!(
        s_hat == "rms_match",
        "loop sidecar: s_hat_mode {s_hat:?} is not supported: the runtime's entry matches the normalized exit to the anchor's RMS (\"rms_match\")"
    );
    anyhow::ensure!(
        cfg_bool(cfg, "delta_rms_match")?,
        "loop sidecar: delta_rms_match false is not supported: the runtime RMS-matches the low-rank term and applies tanh to its gates"
    );
    anyhow::ensure!(
        cfg_bool(cfg, "per_pass_conditioning")?,
        "loop sidecar: per_pass_conditioning false is not supported: the runtime adds the per-pass and per-remaining gate tables"
    );
    // LoopCD is part of the function when its weight is not zero; the loader
    // decides whether it can run it, so its settings have to be on record.
    let omega = cfg
        .get("loop_cd_omega")
        .and_then(|v| v.as_f64())
        .ok_or_else(|| anyhow::anyhow!("loop sidecar: loop_config.loop_cd_omega is missing or not a number"))?;
    if omega != 0.0 {
        cfg_str(cfg, "loop_cd_ref")?;
        cfg_str(cfg, "loop_cd_rms_mode")?;
        cfg_bool(cfg, "loop_cd_rms_match")?;
    }
    Ok(c)
}

/// The tensors the looped forward reads, in checkpoint names and shapes: ten
/// of the entry and nine per mixer. A matrix is `[out, in]`; the entry's
/// low-rank input is the two normalized states side by side. A gate is a
/// `[streams, hidden]` base plus two `[max_passes - 1, streams, hidden]`
/// tables indexed by pass and by passes remaining.
fn live_tensors(c: &LoopConfig) -> Vec<(String, Vec<usize>)> {
    let wide = HC_COUNT * HIDDEN;
    let per_stream = vec![HC_COUNT, HIDDEN];
    let table = vec![c.max_passes - 1, HC_COUNT, HIDDEN];
    let mut out = Vec::new();
    let mut put = |name: String, shape: &[usize]| out.push((name, shape.to_vec()));
    let e = "workspace_entry";
    put(format!("{e}.norm_s.weight"), &per_stream);
    put(format!("{e}.norm_a.weight"), &per_stream);
    put(format!("{e}.entry_a"), &[c.entry_rank, 2 * wide]);
    put(format!("{e}.entry_b"), &[wide, c.entry_rank]);
    for gate in ["g_state", "g_mix"] {
        put(format!("{e}.{gate}_base"), &per_stream);
        put(format!("{e}.{gate}_pass"), &table);
        put(format!("{e}.{gate}_rem"), &table);
    }
    for l in &c.mixer_layers {
        let m = format!("cross_pass_mixers.{l}");
        put(format!("{m}.norm.weight"), &per_stream);
        put(format!("{m}.mix_a"), &[c.mixer_rank, wide]);
        put(format!("{m}.mix_b"), &[wide, c.mixer_rank]);
        put(format!("{m}.gamma"), &per_stream);
        put(format!("{m}.gamma_pass"), &table);
        put(format!("{m}.gamma_rem"), &table);
        put(format!("{m}.delta_kappa"), &per_stream);
        put(format!("{m}.dkappa_pass"), &table);
        put(format!("{m}.dkappa_rem"), &table);
    }
    out
}

fn sha256_hex(path: &Path) -> anyhow::Result<String> {
    use sha2::{Digest, Sha256};
    use std::io::Read;
    let mut file = fs::File::open(path).map_err(|e| anyhow::anyhow!("loop sidecar: open {}: {e}", path.display()))?;
    let mut hasher = Sha256::new();
    let mut buf = vec![0u8; 4 << 20];
    loop {
        let n = file.read(&mut buf)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
}

/// The base model's side of the contract: the adapter's streams are the
/// base's, the core lies inside its layers, and no layer of the core or after
/// it has a PLE (its history exists once, and only the first run of the
/// layers before the core feeds it). PLE ids are one-indexed.
fn check_base(base_path: &Path, c: &LoopConfig) -> anyhow::Result<serde_json::Value> {
    let base = CmfModel::open(base_path).map_err(|e| anyhow::anyhow!("loop sidecar: open base {}: {e}", base_path.display()))?;
    let arch = base.arch();
    let q = arch.qwen4_exp.as_ref().ok_or_else(|| {
        anyhow::anyhow!("loop sidecar: base {} ({}) has no hyper-connection streams; the adapter is for Qwen4-35B-A3B", base_path.display(), arch.arch_name)
    })?;
    anyhow::ensure!(
        q.hc_count == HC_COUNT && arch.hidden_size == HIDDEN,
        "loop sidecar: base has {} streams of {}, the adapter {HC_COUNT} of {HIDDEN}",
        q.hc_count,
        arch.hidden_size
    );
    anyhow::ensure!(
        c.core_end <= arch.num_layers,
        "loop sidecar: core {}..{} does not fit the base's {} layers",
        c.core_start,
        c.core_end,
        arch.num_layers
    );
    if let Some(id) = q.ple_layer_ids.iter().find(|&&id| id > c.core_start) {
        anyhow::bail!("loop sidecar: the base has a PLE in layer {} which is not before the core (starts at {})", id - 1, c.core_start);
    }
    Ok(serde_json::json!({
        "filename": base_path.file_name().map(|n| n.to_string_lossy().into_owned()),
        "arch_name": arch.arch_name,
        "hidden_size": arch.hidden_size,
        "hc_count": q.hc_count,
        "num_layers": arch.num_layers,
    }))
}

/// Convert the published loop checkpoint into the loop sidecar.
///
/// `checkpoint` is `ckpt_best.safetensors` (or the directory holding it) with
/// its `.json` beside it. `output` is either the sidecar itself (a name ending
/// in `.loop.cmf`) or the base model, in which case the base is checked
/// against the adapter and the sidecar goes beside it.
pub fn write_sidecar(checkpoint: &Path, output: &Path) -> anyhow::Result<Report> {
    let checkpoint = if checkpoint.is_dir() { checkpoint.join(SOURCE_FILE) } else { checkpoint.to_path_buf() };
    anyhow::ensure!(checkpoint.is_file(), "loop sidecar: no checkpoint at {} (--model names ckpt_best.safetensors)", checkpoint.display());
    let meta_path = checkpoint.with_extension("json");
    let meta_text = fs::read_to_string(&meta_path).map_err(|e| {
        anyhow::anyhow!(
            "loop sidecar: {}: {e} (the checkpoint's JSON is required beside it: the core range, the mixer layers and the mode switches are only there)",
            meta_path.display()
        )
    })?;
    let meta: serde_json::Value = serde_json::from_str(&meta_text).map_err(|e| anyhow::anyhow!("loop sidecar: {}: {e}", meta_path.display()))?;
    let format = meta.get("format").and_then(|v| v.as_str()).unwrap_or("");
    anyhow::ensure!(format == SOURCE_FORMAT, "loop sidecar: {} has format {format:?}, expected {SOURCE_FORMAT:?}", meta_path.display());
    let cfg = meta
        .get("loop_config")
        .and_then(|v| v.as_object())
        .ok_or_else(|| anyhow::anyhow!("loop sidecar: {} has no loop_config object", meta_path.display()))?;
    let c = checked_config(cfg)?;
    if let Some(k) = ADDED_KEYS.iter().find(|k| cfg.contains_key(**k)) {
        anyhow::bail!("loop sidecar: loop_config already has a key {k:?}, which the sidecar header uses for the source record");
    }

    let out = cortiq_core::loop_sidecar_path(output);
    let base = if out == output {
        None
    } else {
        anyhow::ensure!(
            output.is_file(),
            "loop sidecar: --output {} is neither an existing base .cmf nor a path ending in .loop.cmf",
            output.display()
        );
        Some(check_base(output, &c)?)
    };
    anyhow::ensure!(!out.exists(), "loop sidecar: {} already exists; refusing to overwrite it", out.display());

    let sha256 = sha256_hex(&checkpoint)?;
    let expected_sha = meta.get("sha256").and_then(|v| v.as_str()).map(|s| s.trim().to_ascii_lowercase());
    if let Some(expected) = &expected_sha {
        anyhow::ensure!(
            &sha256 == expected,
            "loop sidecar: {} has sha256 {sha256}, {} records {expected}: not the file that JSON describes",
            checkpoint.display(),
            meta_path.display()
        );
    }

    let source = open_safetensors(&checkpoint)?;
    let live = live_tensors(&c);
    let mut skipped = 0usize;
    for t in &source.tensors {
        if live.iter().any(|(name, _)| name == &t.name) {
            continue;
        }
        anyhow::ensure!(
            t.name.starts_with("layers.") && LORA_SUFFIXES.iter().any(|s| t.name.ends_with(s)),
            "loop sidecar: the checkpoint holds {}, which is neither one of the {} tensors its loop_config describes nor a LoRA tensor: it was made for a different function",
            t.name,
            live.len()
        );
        skipped += 1;
    }
    // A LoRA whose B is zero adds nothing in any pass, which is what lets the
    // extra passes run the base's own layers. A trained B is another model.
    for t in source.tensors.iter().filter(|t| t.name.contains("lora_b")) {
        let bytes = source.try_bytes(t).ok_or_else(|| anyhow::anyhow!("loop sidecar: {} lies outside the checkpoint file", t.name))?;
        let zero = match t.dtype.as_str() {
            "F32" => bytes.chunks_exact(4).all(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]) == 0.0),
            _ => bytes.iter().all(|&b| b == 0),
        };
        anyhow::ensure!(
            zero,
            "loop sidecar: {} is not all zero: this checkpoint trained LoRA weights on the looped layers, which the runtime does not apply",
            t.name
        );
    }
    let mut payload_bytes = 0u64;
    for (name, shape) in &live {
        let t = source.tensors.iter().find(|t| &t.name == name).ok_or_else(|| anyhow::anyhow!("loop sidecar: the checkpoint has no {name}"))?;
        anyhow::ensure!(t.dtype == "F32", "loop sidecar: {name} is {}, expected F32", t.dtype);
        anyhow::ensure!(&t.shape == shape, "loop sidecar: {name} shape {:?}, expected {shape:?}", t.shape);
        let bytes = source.try_bytes(t).ok_or_else(|| anyhow::anyhow!("loop sidecar: {name} lies outside the checkpoint file"))?;
        anyhow::ensure!(
            bytes.len() == 4 * shape.iter().product::<usize>() && bytes.chunks_exact(4).all(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]).is_finite()),
            "loop sidecar: {name} holds an invalid payload"
        );
        payload_bytes += bytes.len() as u64;
    }

    let mut record = cfg.clone();
    record.insert("format".into(), SOURCE_FORMAT.into());
    // As the checkpoint's JSON gives it, whatever its type: the runtime only
    // shows it.
    record.insert("step".into(), meta.get("step").cloned().unwrap_or(serde_json::Value::Null));
    record.insert("source_repo".into(), SOURCE_REPO.into());
    record.insert(
        "source_file".into(),
        checkpoint.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| SOURCE_FILE.into()).into(),
    );
    record.insert("source_sha256".into(), sha256.clone().into());
    let mut provenance = serde_json::json!({
        "kind": SIDECAR_ARCH,
        RECORD_KEY: record,
        "tensor_namespace": NAMESPACE,
        "tensor_count": live.len(),
        "converter": format!("cortiq {}", env!("CARGO_PKG_VERSION")),
    });
    if let Some(b) = &base {
        provenance["base_checked"] = b.clone();
    }
    // The file is not a model: it has no layers, heads or vocabulary of its
    // own. The width and the epsilon are those of the adapter's stream norms.
    let arch: ModelArch = serde_json::from_value(serde_json::json!({
        "arch_name": SIDECAR_ARCH,
        "hidden_size": HIDDEN,
        "intermediate_size": 0,
        "num_layers": 0,
        "num_attention_heads": 0,
        "num_kv_heads": 0,
        "head_dim": 0,
        "vocab_size": 0,
        "layer_types": [],
        "rms_norm_eps": 1e-6,
        "max_position_embeddings": 0,
    }))?;
    let header = CmfHeader {
        format: "cmf".into(),
        version: CMF_VERSION,
        arch,
        quant_type: QuantType::F32,
        provenance: Some(provenance),
        tokenizer_config: None,
        section_hashes: None,
        skills: Vec::new(),
        shard: None,
        calibration: None,
        routing: None,
        genome: None,
        lineage: Vec::new(),
        router: None,
        segments: Vec::new(),
    };

    let name = out.file_name().and_then(|v| v.to_str()).ok_or_else(|| anyhow::anyhow!("loop sidecar: output filename must be UTF-8"))?;
    let partial = out.with_file_name(format!(".{name}.part-{}", std::process::id()));
    let write = || -> anyhow::Result<()> {
        let mut writer = CmfStreamWriter::new(&partial, CmfStreamWriter::head_reserve_for(live.len(), 64))
            .map_err(|e| anyhow::anyhow!("loop sidecar: create {}: {e}", partial.display()))?;
        for (source_name, shape) in &live {
            let t = source.tensors.iter().find(|t| &t.name == source_name).expect("checked above");
            let name = format!("{NAMESPACE}{source_name}");
            // safetensors F32 is little-endian, as the CMF payload is: the
            // bytes go through unchanged.
            writer.push(&name, TensorDtype::F32, shape, source.bytes(t)).map_err(|e| anyhow::anyhow!("loop sidecar: write {name}: {e}"))?;
        }
        writer.finish(&header, None, None).map_err(|e| anyhow::anyhow!("loop sidecar: finalize {}: {e}", partial.display()))?;
        // the file as the loader will read it
        let written = CmfModel::open(&partial).map_err(|e| anyhow::anyhow!("loop sidecar: reopen {}: {e}", partial.display()))?;
        anyhow::ensure!(written.tensors.len() == live.len(), "loop sidecar: wrote {} tensors, the file lists {}", live.len(), written.tensors.len());
        for (source_name, shape) in &live {
            let name = format!("{NAMESPACE}{source_name}");
            let e = written.tensor(&name).ok_or_else(|| anyhow::anyhow!("loop sidecar: the written file has no {name}"))?;
            anyhow::ensure!(e.dtype == TensorDtype::F32 && &e.shape == shape, "loop sidecar: {name} was written as {:?} {:?}", e.dtype, e.shape);
        }
        Ok(())
    };
    if let Err(e) = write() {
        let _ = fs::remove_file(&partial);
        return Err(e);
    }
    fs::rename(&partial, &out).map_err(|e| anyhow::anyhow!("loop sidecar: publish {} -> {}: {e}", partial.display(), out.display()))?;
    let file_bytes = fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
    Ok(Report {
        path: out,
        tensors: live.len(),
        payload_bytes,
        file_bytes,
        skipped,
        core_start: c.core_start,
        core_end: c.core_end,
        mixer_layers: c.mixer_layers,
        num_passes: c.num_passes,
        max_trained_passes: c.max_trained_passes,
        max_passes: c.max_passes,
        sha256,
        sha256_checked: expected_sha.is_some(),
        base: base.map(|_| output.display().to_string()),
    })
}

/// The `cortiq info` line for the loop sidecar of `model` (or for `model`
/// itself when it is one): read from the sidecar's header alone, no tensor is
/// touched. None when there is no sidecar.
pub fn info_line(model: &Path) -> Option<String> {
    let side = cortiq_core::loop_sidecar_path(model);
    if !side.exists() {
        return None;
    }
    let name = side.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
    let header = match cortiq_core::format::peek_header(&side) {
        Ok(Some((_, header))) => header,
        Ok(None) => return Some(format!("  Looped:      {name} is not a CMF file")),
        Err(e) => return Some(format!("  Looped:      {name} is unreadable ({e})")),
    };
    let arch = header.pointer("/arch/arch_name").and_then(|v| v.as_str()).unwrap_or("");
    let Some(l) = header.pointer(&format!("/provenance/{RECORD_KEY}")).filter(|_| arch == SIDECAR_ARCH) else {
        return Some(format!("  Looped:      {name} is not a loop sidecar (arch {arch:?})"));
    };
    let n = |key: &str| l.get(key).and_then(|v| v.as_u64()).map(|v| v.to_string()).unwrap_or_else(|| "?".into());
    let core = match (l.get("core_start").and_then(|v| v.as_u64()), l.get("core_end").and_then(|v| v.as_u64())) {
        (Some(a), Some(b)) if b > a => format!("{a}..{}", b - 1),
        _ => "?".into(),
    };
    let mixers = l
        .get("mixer_layers")
        .and_then(|v| v.as_array())
        .map(|a| a.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
        .unwrap_or_else(|| "?".into());
    Some(format!(
        "  Looped:      sidecar {name}: core layers {core} run per pass, mixers before {mixers}; {} passes by default, trained up to {}, at most {} (--loops N); from {}",
        n("num_passes"),
        n("max_trained_passes"),
        n("max_passes"),
        l.get("source_repo").and_then(|v| v.as_str()).unwrap_or("?")
    ))
}