Skip to main content

kute_cli/
shadow.rs

1//! `kute shadow`: try a candidate vocabulary beside the one in use, on
2//! data neither was made from, and say whether it has earned its place.
3//!
4//! Every input is encoded with both vocabularies. Nothing is published,
5//! replaced or sent: the output is a decision with the measurements it
6//! rests on. The candidate is approved only if what it saves, after the
7//! cost of distributing it, is at least the improvement asked for, and
8//! no constraint is broken.
9
10use crate::vocab;
11use kute::{KuteError, UnknownPolicy};
12use serde_json::{json, Value};
13use std::path::PathBuf;
14use std::time::Instant;
15
16pub struct Options {
17    pub parent: PathBuf,
18    pub candidate: PathBuf,
19    /// Held-out inputs, each encoded as one message.
20    pub inputs: Vec<PathBuf>,
21    pub unknown: String,
22    /// Least net saving, as a share of the parent's bytes, to approve.
23    pub min_improvement: f64,
24    /// How much traffic the candidate will carry, as a multiple of the inputs.
25    pub horizon: f64,
26    /// How many times the candidate vocabulary has to be sent.
27    pub distributions: u64,
28    /// Most the candidate may slow encoding, as a ratio.
29    pub max_slowdown: f64,
30    /// Timed passes over the inputs with each vocabulary, taken in
31    /// alternating order; the least time of each is used.
32    pub passes: usize,
33}
34
35struct Side {
36    tokens: u64,
37    escaped: u64,
38    container_bytes: u64,
39    seconds: f64,
40}
41
42/// Encode every input and check each decodes to its source. Returns the
43/// totals and the container size of each input.
44fn measure(engine: &kute::Engine, tokenizer: &dyn kute::Tokenizer, raws: &[Vec<u8>], policy: UnknownPolicy) -> kute::Result<Result<(Side, Vec<u64>), String>> {
45    let mut side = Side { tokens: 0, escaped: 0, container_bytes: 0, seconds: 0.0 };
46    let mut each = Vec::with_capacity(raws.len());
47    for (i, raw) in raws.iter().enumerate() {
48        let sequence = match engine.encode_raw_open(tokenizer, raw, policy) {
49            Ok(sequence) => sequence,
50            // With `strict`, a symbol the vocabulary lacks ends here: a
51            // finding about the vocabulary, not a failure of the command.
52            Err(e) => return Ok(Err(format!("input {}: {e}", i + 1))),
53        };
54        side.tokens += sequence.ids.len() as u64;
55        side.escaped += sequence.escapes.len() as u64;
56        let bytes = sequence.to_bytes_compressed()?.len() as u64;
57        side.container_bytes += bytes;
58        each.push(bytes);
59        if engine.decode_raw_bounded(tokenizer, &sequence, u64::MAX)? != *raw {
60            return Ok(Err(format!("input {} does not decode to itself", i + 1)));
61        }
62    }
63    Ok(Ok((side, each)))
64}
65
66/// One timed pass of encoding every input.
67fn timed(engine: &kute::Engine, tokenizer: &dyn kute::Tokenizer, raws: &[Vec<u8>], policy: UnknownPolicy) -> kute::Result<f64> {
68    let started = Instant::now();
69    for raw in raws {
70        std::hint::black_box(engine.encode_raw_open(tokenizer, raw, policy)?);
71    }
72    Ok(started.elapsed().as_secs_f64())
73}
74
75fn describe(side: &Side) -> Value {
76    json!({ "tokens": side.tokens, "escaped_symbols": side.escaped, "container_bytes": side.container_bytes, "encode_seconds": (side.seconds * 1e6).round() / 1e6 })
77}
78
79/// Returns the report and whether the candidate was approved.
80pub fn run(engine: &kute::Engine, options: &Options) -> kute::Result<(Value, bool)> {
81    let config = |why: &str| Err(KuteError::InvalidConfig(why.into()));
82    if options.inputs.is_empty() {
83        return config("shadow needs at least one input");
84    }
85    if !(options.min_improvement.is_finite() && (0.0..1.0).contains(&options.min_improvement)) {
86        return config("--min-improvement is a share between 0 and 1");
87    }
88    if !(options.horizon.is_finite() && options.horizon > 0.0 && options.max_slowdown.is_finite() && options.max_slowdown >= 1.0) {
89        return config("--horizon must be positive and --max-slowdown at least 1");
90    }
91    if options.passes == 0 || options.passes > 99 {
92        return config("--passes must be between 1 and 99");
93    }
94    let policy = UnknownPolicy::parse(&options.unknown)?;
95    let parent = vocab::load(&options.parent)?;
96    let candidate = vocab::load(&options.candidate)?;
97    let parent_digest = parent.digest()?;
98    let candidate_digest = candidate.digest()?;
99    let declared_parent = vocab::parent_digest(&candidate);
100    let candidate_file_bytes = std::fs::metadata(&options.candidate)?.len();
101    let (parent_tokens, candidate_tokens) = (parent.len(), candidate.len());
102    let raws = options.inputs.iter().map(std::fs::read).collect::<std::io::Result<Vec<_>>>()?;
103    let input_bytes: u64 = raws.iter().map(|r| r.len() as u64).sum();
104
105    let mut reasons: Vec<String> = Vec::new();
106    if parent_digest == candidate_digest {
107        reasons.push("the candidate is the parent".into());
108    }
109    let lineage = match &declared_parent {
110        Some(digest) if *digest == parent_digest => "child of the parent",
111        Some(_) => "child of another vocabulary",
112        None => "no parent recorded",
113    };
114    let parent = engine.tokenizer(parent)?;
115    let candidate = engine.tokenizer(candidate)?;
116    let (mut before, before_each) = match measure(engine, parent.as_ref(), &raws, policy)? {
117        Ok(measured) => measured,
118        Err(why) => return Err(KuteError::InvalidInput(format!("the parent vocabulary cannot carry the inputs: {why}"))),
119    };
120    let mut after = measure(engine, candidate.as_ref(), &raws, policy)?;
121    if let Ok((after, _)) = &mut after {
122        // Whichever is timed second runs on warmer caches, so the order
123        // alternates, and the least time of each is kept: the least is
124        // the one least disturbed by whatever else the machine was doing.
125        (before.seconds, after.seconds) = (f64::INFINITY, f64::INFINITY);
126        for pass in 0..options.passes {
127            if pass % 2 == 0 {
128                before.seconds = before.seconds.min(timed(engine, parent.as_ref(), &raws, policy)?);
129                after.seconds = after.seconds.min(timed(engine, candidate.as_ref(), &raws, policy)?);
130            } else {
131                after.seconds = after.seconds.min(timed(engine, candidate.as_ref(), &raws, policy)?);
132                before.seconds = before.seconds.min(timed(engine, parent.as_ref(), &raws, policy)?);
133            }
134        }
135    }
136
137    let mut report = json!({
138        "parent": { "path": options.parent, "digest": parent_digest, "tokens_in_vocabulary": parent_tokens, "measured": describe(&before) },
139        "candidate": { "path": options.candidate, "digest": candidate_digest, "tokens_in_vocabulary": candidate_tokens, "file_bytes": candidate_file_bytes, "lineage": lineage },
140        "inputs": { "files": raws.len(), "bytes": input_bytes },
141        "terms": {
142            "min_improvement": options.min_improvement,
143            "horizon": options.horizon,
144            "distributions": options.distributions,
145            "max_slowdown": options.max_slowdown,
146            "unknown": options.unknown,
147            "passes": options.passes,
148        },
149    });
150    match after {
151        Err(why) => reasons.push(format!("the candidate cannot carry the inputs: {why}")),
152        Ok((after, after_each)) => {
153            let smaller = before_each.iter().zip(&after_each).filter(|(b, a)| a < b).count();
154            let larger = before_each.iter().zip(&after_each).filter(|(b, a)| a > b).count();
155            let worst = before_each.iter().zip(&after_each).map(|(b, a)| *a as i64 - *b as i64).max().unwrap_or(0).max(0);
156            // What the inputs stand for, scaled to the traffic expected,
157            // less what it costs to hand the candidate out.
158            let saved_on_inputs = before.container_bytes as f64 - after.container_bytes as f64;
159            let distribution_cost = options.distributions as f64 * candidate_file_bytes as f64;
160            let net = options.horizon * saved_on_inputs - distribution_cost;
161            let basis = options.horizon * before.container_bytes as f64;
162            let improvement = if basis > 0.0 { net / basis } else { 0.0 };
163            let slowdown = if before.seconds > 0.0 { after.seconds / before.seconds } else { 1.0 };
164            if improvement < options.min_improvement {
165                reasons.push(format!("net improvement {:.4} is below the {:.4} required", improvement, options.min_improvement));
166            }
167            if slowdown > options.max_slowdown {
168                reasons.push(format!("encoding is {slowdown:.2} times slower; the limit is {:.2}", options.max_slowdown));
169            }
170            if after.escaped > before.escaped {
171                reasons.push(format!("the candidate escapes more symbols ({} against {})", after.escaped, before.escaped));
172            }
173            report["candidate"]["measured"] = describe(&after);
174            report["comparison"] = json!({
175                "container_bytes_saved_on_inputs": saved_on_inputs,
176                // The decision is on the total; these say how it is spread.
177                "inputs_smaller": smaller,
178                "inputs_larger": larger,
179                "inputs_unchanged": before_each.len() - smaller - larger,
180                "largest_increase_on_one_input_bytes": worst,
181                "container_ratio": if before.container_bytes > 0 { after.container_bytes as f64 / before.container_bytes as f64 } else { 1.0 },
182                "token_ratio": if before.tokens > 0 { after.tokens as f64 / before.tokens as f64 } else { 1.0 },
183                "distribution_cost_bytes": distribution_cost,
184                "net_bytes_saved_over_horizon": net,
185                "net_improvement": improvement,
186                "encode_slowdown": (slowdown * 1000.0).round() / 1000.0,
187                // The inputs it would take, at this rate of saving, to pay
188                // for distributing the candidate; absent when it saves nothing.
189                "break_even_horizon": if saved_on_inputs > 0.0 { Some(distribution_cost / saved_on_inputs) } else { None },
190            });
191        }
192    }
193    let approved = reasons.is_empty();
194    report["decision"] = json!(if approved { "approve" } else { "reject" });
195    report["reasons"] = json!(reasons);
196    report["not_measured"] = json!("memory, task quality and predictive utility; timing is wall-clock on this machine");
197    report["assumes"] = json!("that the inputs stand for the traffic to come: the horizon multiplies what was saved on them, which is what drift breaks. The candidate's file is counted at its size as stored at the path given.");
198    Ok((report, approved))
199}