inky-engine 3.0.1

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
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
//! Scheduler wall time. Each participating lane is charged the duration of its batch. A request's wall time
//! from arrival to its last token is queue wait, then lane preparation, then its prefill and decode batches.
use std::fmt;
use std::time::{Duration, Instant};

fn rate(tokens: usize, elapsed: Duration) -> f64 {
    if elapsed.is_zero() { 0.0 } else { tokens as f64 / elapsed.as_secs_f64() }
}

#[derive(Default)]
pub(super) struct Phase {
    tokens: usize,
    elapsed: Duration,
    max_prompt_end: usize,
    non_prompt_rows: usize,
}

impl Phase {
    pub(super) fn add(&mut self, tokens: usize, elapsed: Duration) {
        self.tokens += tokens;
        self.elapsed += elapsed;
    }

    pub(super) fn seed_prompt_floor(&mut self, floor: usize) {
        self.max_prompt_end = self.max_prompt_end.max(floor);
    }

    pub(super) fn add_span(&mut self, p0: usize, rows: usize, prompt_len: usize, elapsed: Duration) {
        self.tokens += rows;
        self.elapsed += elapsed;
        let lo = p0.max(self.max_prompt_end).min(prompt_len);
        let hi = (p0 + rows).min(prompt_len);
        let new_prompt = hi.saturating_sub(lo);
        self.max_prompt_end = self.max_prompt_end.max(hi);
        self.non_prompt_rows += rows - new_prompt;
    }

    pub(super) fn prompt_rows(&self) -> usize {
        self.tokens.saturating_sub(self.non_prompt_rows)
    }

    pub(super) fn elapsed_ms(&self) -> u64 {
        self.elapsed.as_millis() as u64
    }
}

/// Where a request's saved work came from, and what it saved: for the traffic record's `reuse` object and the
/// `reuse_*` /health totals. Token counts only; never prompt text.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct ReuseSnapshot {
    /// "none", "exact" (an exact start), "approx" (this conversation's own approximate save) or "spill" (from SSD).
    pub(super) source: &'static str,
    /// Longest block-aligned prefix of the prompt already sealed in the cache at ingress, in tokens.
    pub(super) common_prefix: usize,
    /// The start the lane resumed from, in tokens (0: none).
    pub(super) restore_at: usize,
    /// Prompt rows this request actually prefilled on the GPU.
    pub(super) prefilled_rows: usize,
    /// Time readying the lane after admission (match, bind or restore), in ms.
    pub(super) restore_ms: u64,
    /// Whether the request named its conversation (`X-Inky-Card-Id`), the only way it can own approximate work.
    pub(super) owner_bound: bool,
    /// Structured enum tag classifying hit vs miss cause (never prompt text).
    pub(super) miss_reason: &'static str,
    /// Exact first token index where `toks` diverged from this owner's still-live prior turn, or `None` when
    /// no divergence occurred or prior-turn comparison is unavailable (evicted/missing).
    pub(super) first_divergent_pos: Option<usize>,
    /// Outcome of saving this turn's reply-end approximate start at lane release.
    pub(super) turn_end_start: super::block_cache::TurnEndStart,
}

impl ReuseSnapshot {
    pub(super) fn to_json(self) -> serde_json::Value {
        let source = if self.restore_at == 0 {
            "none"
        } else if self.source == "approx" && !self.owner_bound {
            "exact"
        } else {
            self.source
        };
        let miss_reason = if self.miss_reason.is_empty() {
            if self.restore_at == 0 { "miss_no_prior_turn" } else { "hit_shared_prefix" }
        } else {
            self.miss_reason
        };
        let mut obj = serde_json::json!({
            "source": source,
            "common_prefix": self.common_prefix,
            "restore_at": self.restore_at,
            "prefilled_rows": self.prefilled_rows,
            "restore_ms": self.restore_ms,
            "owner_bound": self.owner_bound,
            "miss_reason": miss_reason,
            "turn_end_start": self.turn_end_start.record_tag(),
        });
        if let Some(pos) = self.first_divergent_pos {
            obj["first_divergent_pos"] = serde_json::json!(pos);
        }
        obj
    }
}

/// Completed per-request phase timing carried to request handlers, logs, and the traffic recorder.
#[derive(Clone, Debug, Default, PartialEq)]
pub(super) struct TimingSnapshot {
    pub(super) queue_ms: u64,
    pub(super) prefill_ms: u64,
    pub(super) decode_ms: u64,
    pub(super) summary: String,
    pub(super) reuse: ReuseSnapshot,
    pub(super) sched: Option<crate::fairness::SchedSnapshot>,
}

pub(super) struct RequestTiming {
    pub(super) queue_wait: Duration,
    pub(super) busy_at_start: usize,
    /// Readying the lane after admission: prefix match/restore, reset, kept state, prompt upload.
    pub(super) prep: Duration,
    pub(super) prefill: Phase,
    pub(super) generation: Phase,
    pub(super) reuse: ReuseSnapshot,
}

impl RequestTiming {
    pub(super) fn snapshot(&self) -> TimingSnapshot {
        TimingSnapshot {
            queue_ms: self.queue_wait.as_millis() as u64,
            prefill_ms: self.prefill.elapsed_ms(),
            decode_ms: self.generation.elapsed_ms(),
            summary: self.to_string(),
            reuse: ReuseSnapshot {
                prefilled_rows: self.prefill.prompt_rows(),
                restore_ms: self.prep.as_millis() as u64,
                ..self.reuse
            },
            sched: None,
        }
    }
}

impl fmt::Display for RequestTiming {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "queue_ms={:.1} prep_ms={:.1} prefill_ms={:.1} prefill_tok_s={:.1} decode_ms={:.1} decode_tok_s={:.1} lanes_busy_start={}",
            self.queue_wait.as_secs_f64() * 1000.0,
            self.prep.as_secs_f64() * 1000.0,
            self.prefill.elapsed.as_secs_f64() * 1000.0,
            rate(self.prefill.tokens, self.prefill.elapsed),
            self.generation.elapsed.as_secs_f64() * 1000.0,
            rate(self.generation.tokens, self.generation.elapsed),
            self.busy_at_start,
        )
    }
}

pub(super) struct Counters {
    start: Instant,
    last_change: Instant,
    busy: usize,
    lane_seconds: f64,
    pub(super) queued: usize,
    pub(super) starts_spilled: u64,
    pub(super) input: usize,
    pub(super) output: usize,
    pub(super) admit_deferrals: u64,
    pub(super) step_deferrals: u64,
    // Cumulative since start, never reset by `summarize`: the operator metrics derive rates from their deltas.
    totals: Totals,
    lane_us_total: f64,
}

/// Which step computed a prompt row: a prefill span, or a single-row step inside a decode batch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum RowPhase {
    PrefillStep,
    DecodeStep,
}

/// Cumulative work since start, for the operator metrics (`summarize` never resets it).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct Totals {
    pub(super) prompt_rows_prefill_step: u64,
    pub(super) prompt_rows_decode_step: u64,
    /// Tokens sent to a live request.
    pub(super) output_enqueued: u64,
    /// Tokens sampled for a request whose client was gone: the send failed.
    pub(super) output_failed: u64,
    /// Occupied lane-microseconds.
    pub(super) lane_us: u64,
}

impl Counters {
    pub(super) fn new(now: Instant) -> Self {
        Self {
            start: now,
            last_change: now,
            busy: 0,
            lane_seconds: 0.0,
            queued: 0,
            starts_spilled: 0,
            input: 0,
            output: 0,
            admit_deferrals: 0,
            step_deferrals: 0,
            totals: Totals::default(),
            lane_us_total: 0.0,
        }
    }

    /// Charge occupied lanes up to `now`. Never rewinds: an event stamped before the last one charges nothing
    /// and leaves `last_change` where it is, so no interval is charged twice.
    fn accrue(&mut self, now: Instant) {
        if now <= self.last_change {
            return;
        }
        let held = now - self.last_change;
        self.lane_seconds += held.as_secs_f64() * self.busy as f64;
        self.lane_us_total += held.as_secs_f64() * 1e6 * self.busy as f64;
        self.last_change = now;
    }

    pub(super) fn admit(&mut self, now: Instant, queued_at: Instant) -> RequestTiming {
        self.accrue(now);
        self.queued = self.queued.saturating_sub(1);
        self.busy += 1;
        RequestTiming {
            queue_wait: now.saturating_duration_since(queued_at),
            busy_at_start: self.busy,
            prep: Duration::ZERO,
            prefill: Phase::default(),
            generation: Phase::default(),
            reuse: ReuseSnapshot::default(),
        }
    }

    /// Prompt rows computed on the GPU by a successful step of `phase`.
    pub(super) fn add_input(&mut self, rows: usize, phase: RowPhase) {
        self.input += rows;
        match phase {
            RowPhase::PrefillStep => self.totals.prompt_rows_prefill_step += rows as u64,
            RowPhase::DecodeStep => self.totals.prompt_rows_decode_step += rows as u64,
        }
    }

    /// Output tokens sampled: `enqueued` reached their request, `failed` found the client gone. The summary
    /// log'"'"'s `output_tok_s` and `/health`'"'"'s `output_tokens` keep counting both, as before.
    pub(super) fn add_output(&mut self, enqueued: usize, failed: usize) {
        self.output += enqueued + failed;
        self.totals.output_enqueued += enqueued as u64;
        self.totals.output_failed += failed as u64;
    }

    /// Cumulative totals as of `now`, read-only: an observation never moves the accrual clock, so one stamped
    /// before the latest event reports what was charged by then and charges nothing twice.
    pub(super) fn totals(&self, now: Instant) -> Totals {
        let pending = now.saturating_duration_since(self.last_change).as_secs_f64() * 1e6 * self.busy as f64;
        Totals { lane_us: (self.lane_us_total + pending) as u64, ..self.totals }
    }

    pub(super) fn release(&mut self, now: Instant) {
        self.accrue(now);
        self.busy = self.busy.saturating_sub(1);
    }

    pub(super) fn summarize(&mut self, now: Instant, waiting_in_gate: usize) -> String {
        self.accrue(now);
        let elapsed = now.saturating_duration_since(self.start);
        let lanes_busy_avg = if elapsed.is_zero() {
            self.busy as f64
        } else {
            self.lane_seconds / elapsed.as_secs_f64()
        };
        let queue_depth = self.queued.saturating_add(waiting_in_gate);
        let line = format!(
            "[serve] summary interval_s={:.1} lanes_busy_avg={:.2} input_tok_s={:.2} output_tok_s={:.2} queue_depth={}",
            elapsed.as_secs_f64(),
            lanes_busy_avg,
            rate(self.input, elapsed),
            rate(self.output, elapsed),
            queue_depth,
        );
        self.start = now;
        self.lane_seconds = 0.0;
        self.input = 0;
        self.output = 0;
        line
    }
}

/// Decode-step phase profile (`INK_SERVE_PROF=<steps>`, timing only): every `<steps>` decode steps of the same
/// lane count, print each phase's median milliseconds to stderr. Off (no clock reads) when unset.
pub(super) struct StepProf {
    every: usize,
    lanes: usize,
    last_start: Option<Instant>,
    rows: Vec<[f64; StepProf::N]>,
}

impl StepProf {
    pub(super) const N: usize = 10;
    const NAMES: [&'static str; StepProf::N] =
        ["cycle", "pre", "encode", "overlap", "wait", "post", "sample", "gpu", "dark", "disp"];

    pub(super) fn from_env() -> StepProf {
        let every = std::env::var("INK_SERVE_PROF").ok().and_then(|v| v.parse().ok()).unwrap_or(0);
        StepProf { every, lanes: 0, last_start: None, rows: Vec::new() }
    }

    pub(super) fn on(&self) -> bool {
        self.every > 0
    }

    pub(super) fn now(&self) -> Option<Instant> {
        self.on().then(Instant::now)
    }

    /// One decode step: `t` holds the instants before pre-work, encode, commit, wait, post-work, sampling and after.
    pub(super) fn record(&mut self, lanes: usize, t: [Option<Instant>; 7], gpu_ms: f64, dispatches: u64) {
        let Some(t) = t.into_iter().collect::<Option<Vec<Instant>>>() else { return };
        if lanes != self.lanes {
            self.rows.clear();
            self.lanes = lanes;
            self.last_start = None;
        }
        let ms = |a: Instant, b: Instant| b.saturating_duration_since(a).as_secs_f64() * 1e3;
        let cycle = self.last_start.map_or(f64::NAN, |s| ms(s, t[0]));
        self.last_start = Some(t[0]);
        let wall = ms(t[0], t[6]);
        self.rows.push([
            cycle,
            ms(t[0], t[1]),
            ms(t[1], t[2]),
            ms(t[2], t[3]),
            ms(t[3], t[4]),
            ms(t[4], t[5]),
            ms(t[5], t[6]),
            gpu_ms,
            wall - gpu_ms,
            dispatches as f64,
        ]);
        if self.rows.len() >= self.every {
            let mut line = format!("[serve prof] lanes={lanes} steps={}", self.rows.len());
            for (k, name) in StepProf::NAMES.iter().enumerate() {
                let mut v: Vec<f64> = self.rows.iter().map(|r| r[k]).filter(|x| x.is_finite()).collect();
                v.sort_by(|a, b| a.total_cmp(b));
                if let Some(m) = v.get(v.len() / 2) {
                    line += &format!(" {name}={m:.2}");
                }
            }
            eprintln!("{line}");
            self.rows.clear();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_out_of_order_observation_never_double_charges_occupancy() {
        let base = Instant::now();
        let at = |s: u64| base + Duration::from_secs(s);
        let mut c = Counters::new(base);
        let _ = c.admit(at(10), at(10));
        let _ = c.summarize(at(20), 0);
        // A snapshot stamped 15 s is observed after the 20 s event.
        assert_eq!(c.totals(at(15)).lane_us, 10_000_000, "charged up to the 20 s event, nothing more");
        c.release(at(30));
        assert_eq!(c.totals(at(30)).lane_us, 20_000_000, "one lane from 10 s to 30 s");
        assert_eq!(c.totals(at(40)).lane_us, 20_000_000);
    }

    #[test]
    fn output_and_prompt_rows_split_by_outcome_and_phase() {
        let now = Instant::now();
        let mut c = Counters::new(now);
        c.add_output(1, 1);
        c.add_input(64, RowPhase::PrefillStep);
        c.add_input(1, RowPhase::DecodeStep);
        let t = c.totals(now);
        assert_eq!((t.output_enqueued, t.output_failed), (1, 1));
        assert_eq!((t.prompt_rows_prefill_step, t.prompt_rows_decode_step), (64, 1));
        assert_eq!((c.output, c.input), (2, 65), "the summary log keeps counting every sampled token and row");
    }

    #[test]
    fn request_charges_only_its_prefill_and_decode_batches() {
        let start = Instant::now();
        let mut counters = Counters::new(start);
        counters.queued = 2;
        counters.admit(start, start);
        let mut timing = counters.admit(start + Duration::from_millis(50), start);
        timing.prefill.add(4, Duration::from_millis(25));
        timing.prefill.add(6, Duration::from_millis(75));
        assert_eq!(
            timing.to_string(),
            "queue_ms=50.0 prep_ms=0.0 prefill_ms=100.0 prefill_tok_s=100.0 decode_ms=0.0 decode_tok_s=0.0 lanes_busy_start=2"
        );
        timing.generation.add(1, Duration::from_millis(50));
        let snap = timing.snapshot();
        assert_eq!(snap.queue_ms, 50);
        assert_eq!(snap.prefill_ms, 100);
        assert_eq!(snap.decode_ms, 50);
        assert!(snap.summary.contains("decode_ms=50.0 decode_tok_s=20.0"));
    }

    #[test]
    fn lane_preparation_is_its_own_phase() {
        // Admission at 40 ms, preparation 15 ms, then a 30 ms prefill: preparation is charged to neither the
        // queue wait (it starts after admission) nor the prefill rate (it moves no prompt tokens).
        let queued = Instant::now();
        let mut counters = Counters::new(queued);
        counters.queued = 1;
        let mut timing = counters.admit(queued + Duration::from_millis(40), queued);
        timing.prep = Duration::from_millis(15);
        timing.prefill.add(6, Duration::from_millis(30));
        assert_eq!(
            timing.to_string(),
            "queue_ms=40.0 prep_ms=15.0 prefill_ms=30.0 prefill_tok_s=200.0 decode_ms=0.0 decode_tok_s=0.0 lanes_busy_start=1"
        );
        let total = timing.queue_wait + timing.prep + timing.prefill.elapsed;
        assert_eq!(total, Duration::from_millis(85));
    }

    #[test]
    fn summary_accounts_for_busy_idle_and_cross_window_jobs() {
        let start = Instant::now();
        let at = |s| start + Duration::from_secs(s);
        let mut c = Counters::new(start);
        c.queued = 3;
        c.admit(at(10), start);
        c.admit(at(20), start);
        c.release(at(40));
        c.input = 300;
        c.output = 60;
        assert_eq!(
            c.summarize(at(60), 0),
            "[serve] summary interval_s=60.0 lanes_busy_avg=1.17 input_tok_s=5.00 output_tok_s=1.00 queue_depth=1"
        );
        c.release(at(90));
        assert_eq!(
            c.summarize(at(120), 2),
            "[serve] summary interval_s=60.0 lanes_busy_avg=0.50 input_tok_s=0.00 output_tok_s=0.00 queue_depth=3"
        );
        assert!(c.summarize(at(180), 0).contains("lanes_busy_avg=0.00"));
        // Zero-duration summary must never produce NaN.
        assert!(!c.summarize(at(180), 0).contains("NaN"));
    }
}