inky-engine 3.0.0

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
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
//! Test-only observation of the step selected by the serving scheduler, including its
//! runnable inputs, the ages and share credit either side of the call, and every step-time
//! charge. The standalone TLC gate compiles this module and the same production planning
//! entry points on hosts without Metal.
use crate::scheduler::{ServeLaneInput, ServeStepPlan, ServeStepPlanner, StepClass};
use std::cell::RefCell;
use std::io::{BufWriter, Write};

thread_local! {
    static FRAMES: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
}

/// Planner state before a plan call: wait ticks and share credit.
pub(super) struct Before {
    ages: Vec<u32>,
    credit: i64,
}

pub(super) fn snapshot(planner: &ServeStepPlanner, lanes: usize) -> Option<Before> {
    FRAMES.with_borrow(|frames| {
        frames.as_ref().map(|_| Before {
            ages: (0..lanes).map(|i| planner.wait_ticks(i)).collect(),
            credit: planner.credit(),
        })
    })
}

/// Planner state before a charge: share credit and the class awaiting its step time.
pub(super) fn charge_snapshot(planner: &ServeStepPlanner) -> Option<(i64, Option<StepClass>)> {
    FRAMES.with_borrow(|frames| frames.as_ref().map(|_| (planner.credit(), planner.pending())))
}

fn class_name(class: Option<StepClass>) -> &'static str {
    match class {
        None => "none",
        Some(StepClass::Decode) => "decode",
        Some(StepClass::Prefill) => "prefill",
    }
}

fn push(frame: impl FnOnce(usize) -> String) {
    FRAMES.with_borrow_mut(|frames| {
        let frames = frames.as_mut().unwrap();
        let seq = frames.len();
        frames.push(frame(seq));
    });
}

/// `budgets` is the step budget passed in, the contended prefill cap (0: none) and the budget
/// the planner used.
pub(super) fn record(
    planner: &ServeStepPlanner,
    inputs: &[ServeLaneInput],
    (step_budget, prefill_cap, budget): (usize, usize, usize),
    align: usize,
    before: &Before,
    plan: Option<&ServeStepPlan>,
) {
    let lanes = inputs.len();
    let mut spans = vec![0; lanes];
    let mut starts = vec![0; lanes];
    let mut select = |i: usize, p0: usize, len: usize| {
        assert!(
            len > 0 && spans[i] == 0,
            "invalid or duplicate span in the step"
        );
        spans[i] = len;
        starts[i] = p0;
    };
    let mode = match plan {
        None => "idle",
        Some(ServeStepPlan::Decode(chosen)) => {
            for &i in chosen {
                select(i, inputs[i].n_past, 1);
            }
            "decode"
        }
        Some(ServeStepPlan::Prefill(chosen)) => {
            for &(i, p0, len) in chosen {
                select(i, p0, len);
            }
            "prefill"
        }
    };
    let runnable: Vec<_> = inputs.iter().map(|i| i.runnable).collect();
    let pending: Vec<_> = inputs.iter().map(|i| i.has_pending_decode).collect();
    let pos: Vec<_> = inputs.iter().map(|i| i.n_past).collect();
    let end: Vec<_> = inputs.iter().map(|i| i.pf_end).collect();
    let after: Vec<_> = (0..lanes).map(|i| planner.wait_ticks(i)).collect();
    let ages = &before.ages;
    // All interpolated arrays contain integers or booleans. Keep this gate usable with rustc alone.
    push(|seq| {
        format!(
            r#"{{"version":4,"kind":"plan","seq":{seq},"runnable":{runnable:?},"pending":{pending:?},"pos":{pos:?},"endPos":{end:?},"before":{ages:?},"after":{after:?},"starts":{starts:?},"spans":{spans:?},"mode":"{mode}","stepBudget":{step_budget},"prefillCap":{prefill_cap},"budget":{budget},"align":{align},"ceiling":{},"share":{},"credit":{},"creditAfter":{},"cls":"{}"}}"#,
            planner.max_bypass(),
            planner.prefill_share(),
            before.credit,
            planner.credit(),
            class_name(planner.pending()),
        )
    });
}

pub(super) fn record_charge(
    planner: &ServeStepPlanner,
    elapsed_us: u64,
    (credit, class): (i64, Option<StepClass>),
) {
    push(|seq| {
        format!(
            r#"{{"version":4,"kind":"charge","seq":{seq},"share":{},"cls":"{}","elapsed":{elapsed_us},"credit":{credit},"creditAfter":{},"cap":{}}}"#,
            planner.prefill_share(),
            class_name(class),
            planner.credit(),
            crate::scheduler::SHARE_CHARGE_CAP_US,
        )
    });
}

fn capture(work: impl FnOnce()) -> Vec<String> {
    FRAMES.with_borrow_mut(|frames| assert!(frames.replace(Vec::new()).is_none()));
    work();
    let frames = FRAMES.with_borrow_mut(Option::take).unwrap();
    assert!(
        !frames.is_empty(),
        "workload did not reach the serving planner"
    );
    frames
}

fn write_trace(frames: &[String]) {
    let path = std::env::var_os("INKY_SCHED_TRACE_OUT").expect("set INKY_SCHED_TRACE_OUT");
    let mut out = BufWriter::new(std::fs::File::create(path).unwrap());
    for frame in frames {
        writeln!(out, "{frame}").unwrap();
    }
    out.flush().unwrap();
}

/// Capture the real GPU-backed scheduler only when the hardware test requests a trace.
pub(super) fn capture_if_requested(work: impl FnOnce()) {
    if std::env::var_os("INKY_SCHED_TRACE_OUT").is_some() {
        write_trace(&capture(work));
    } else {
        work();
    }
}

/// Seeds `0, 2, 4, ...` keep the pure tick policy (share 0); odd seeds exercise the share.
fn share_for(seed: u64) -> u32 {
    match seed % 8 {
        1 | 5 => super::step::SERVE_PREFILL_SHARE,
        3 => 100,
        7 => 35,
        _ => 0,
    }
}

/// Walk seeds whose budgets put two prefillers at the ceiling into a step with room for one
/// block: the first three of the 62 seeds in 0..19999 on which c2a26ce's aligned prefill left a
/// lane at age 17.
const CEILING_SEEDS: [u64; 3] = [415, 567, 597];

/// The walk's corpus: seeds 0..31, `u64::MAX`, and the three above.
const SEEDS: [u64; 36] = {
    let mut seeds = [u64::MAX; 36];
    let mut i = 0;
    while i < 32 {
        seeds[i] = i as u64;
        i += 1;
    }
    seeds[33] = CEILING_SEEDS[0];
    seeds[34] = CEILING_SEEDS[1];
    seeds[35] = CEILING_SEEDS[2];
    seeds
};

fn walk(mut seed: u64) -> Vec<String> {
    use super::step::{charge, plan, SERVE_STEP_MAX_BYPASS};
    use std::time::Duration;
    const LANES: usize = 4;
    const ALIGN: usize = 64;
    let share = share_for(seed);
    let mut next = || {
        seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
        (seed >> 32) as usize
    };
    capture(|| {
        let mut planner = ServeStepPlanner::new(LANES, SERVE_STEP_MAX_BYPASS).with_prefill_share(share);
        let mut inputs = [ServeLaneInput {
            runnable: true,
            n_past: 0,
            pf_end: 0,
            has_pending_decode: true,
        }; LANES];
        for (i, input) in inputs.iter_mut().enumerate() {
            planner.on_admit(i);
            if i >= 2 {
                input.pf_end = 512 + next() % 256;
            }
        }
        for tick in 0..64 {
            // A full W=16 burst followed by two urgent prefillers, then variable
            // backpressure and token budgets. Restart some lanes as new prompts.
            let random = tick > SERVE_STEP_MAX_BYPASS;
            for (i, lane) in inputs.iter_mut().enumerate() {
                lane.runnable = tick != 63 && (!random || next() % 4 != 0);
                if random && lane.n_past >= lane.pf_end && next() % 5 == 0 {
                    planner.on_finish(i);
                    planner.on_admit(i);
                    lane.n_past = next() % ALIGN;
                    lane.pf_end = lane.n_past + 1 + next() % 256;
                }
                lane.has_pending_decode =
                    lane.n_past >= lane.pf_end && (!random || next() % 4 != 0);
            }
            // Any budget the server accepts: at least one token per lane (it refuses more lanes
            // than its chunk), below one block, one block and a part, two and a part. From tick
            // 48 a quarter of the steps also carry a contended prefill cap, from 1 token (below
            // the runnable lanes, where the per-lane floor lifts it) to 160.
            let draw = if random { next() } else { 128 };
            let budget = (draw % 160).max(LANES);
            let cap = (tick >= 48 && (draw / 160) % 4 == 0).then(|| 1 + (draw / 640) % 160);
            // Synthetic step wall times: decode is a fixed pass plus a per-lane cost, prefill
            // grows with its tokens. Some steps take no measurable time or exceed the charge cap,
            // and some fail before charging.
            let mut cost = |base: u64, per: u64, work: usize| match next() % 16 {
                0 => 0,
                1 => 2 * crate::scheduler::SHARE_CHARGE_CAP_US,
                _ => base + per * work as u64 + (next() % 5000) as u64,
            };
            let elapsed = match plan(&mut planner, &inputs, budget, ALIGN, cap) {
                Some(ServeStepPlan::Decode(chosen)) => {
                    for &i in &chosen {
                        inputs[i].n_past += 1;
                    }
                    Some(cost(40_000, 500, chosen.len()))
                }
                Some(ServeStepPlan::Prefill(spans)) => {
                    let tokens: usize = spans.iter().map(|&(_, _, len)| len).sum();
                    for (i, _, len) in spans {
                        inputs[i].n_past += len;
                    }
                    Some(cost(20_000, 250, tokens))
                }
                None => None,
            };
            if let Some(us) = elapsed.filter(|_| next() % 10 != 0) {
                charge(&mut planner, Duration::from_micros(us));
            }
            planner.complete_step();
        }
    })
}

/// Seed of the arrivals workload: W + 2 lanes and the full 4096-token chunk, so every prefiller
/// has a block in every prefill step and the budget left over is a block or more.
const ARRIVALS_SEED: u64 = u64::MAX - 1;

/// Seed of the reserve workload: the same arrivals with a budget of 48 tokens, below one block
/// (`INK_CHUNK=32`, or a contended cap under 64, reach it in serve). Every span is a token grant,
/// so a prefill step can leave a prefiller at W - 1 while the decoder reaches W - 1: the reserve
/// at W - 1 that neither the aligned arrivals nor the four-lane walk needs.
const RESERVE_SEED: u64 = u64::MAX - 3;

/// Seed of the ceiling workload (`ceiling`).
const CEILING_SEED: u64 = u64::MAX - 4;

/// Stella Codex's arrival pattern on 15d7e83, at W = 16 with 18 lanes: a decoder and a prefiller,
/// then 16 more prefillers at once. Prefill steps take one long chunk each under the share, so
/// the decoder ages to W - 1 while prefillers wait.
fn arrivals(budget: usize) -> Vec<String> {
    use super::step::{charge, plan, SERVE_STEP_MAX_BYPASS};
    use std::time::Duration;
    const LANES: usize = SERVE_STEP_MAX_BYPASS as usize + 2;
    const ALIGN: usize = 64;
    capture(|| {
        let mut planner = ServeStepPlanner::new(LANES, SERVE_STEP_MAX_BYPASS)
            .with_prefill_share(super::step::SERVE_PREFILL_SHARE);
        let mut inputs = [ServeLaneInput {
            runnable: false,
            n_past: 0,
            pf_end: 200_000,
            has_pending_decode: false,
        }; LANES];
        inputs[0] = ServeLaneInput {
            runnable: false,
            n_past: 9,
            pf_end: 1,
            has_pending_decode: true,
        };
        for tick in 0..64 {
            for (i, lane) in inputs.iter_mut().enumerate() {
                if (tick == 0 && i < 2) || (tick == 2 && i >= 2) {
                    planner.on_admit(i);
                    lane.runnable = true;
                }
            }
            let elapsed = match plan(&mut planner, &inputs, budget, ALIGN, None) {
                Some(ServeStepPlan::Decode(chosen)) => {
                    for &i in &chosen {
                        inputs[i].n_past += 1;
                    }
                    100_000
                }
                Some(ServeStepPlan::Prefill(spans)) => {
                    for (i, _, len) in spans {
                        inputs[i].n_past += len;
                    }
                    1_000
                }
                None => unreachable!("lanes 0 and 1 are always runnable"),
            };
            charge(&mut planner, Duration::from_micros(elapsed));
            planner.complete_step();
        }
    })
}

/// The ticks at which `ceiling` holds one prefiller back, restarts all three, gives the three
/// owed prefillers a budget their whole spans fill exactly, and starves the step.
const CEILING_HOLD_TICK: usize = 16;
const CEILING_RESTART_TICK: usize = 30;
const CEILING_EXACT_TICK: usize = 46;
const CEILING_STARVED_TICK: usize = 63;

/// The ceiling under block alignment, built: one decoder and three prefillers on the tick policy
/// (W = 16), 64-token blocks and a step budget of 104 tokens, one block and a part.
/// - Tick 16: all three prefillers are at W. One is held back for the step (its age rests at
///   W - 1), and the other two are owed a span with one block between them: the first takes the
///   block and the second the 40 tokens left. c2a26ce made the second wait, a 17th bypass.
/// - After that the lane left inside a block comes back to the boundary, and a lane at W takes its
///   block ahead of younger ones that then wait.
/// - Tick 30: the three restart as new prompts at 0, 7 and 14, so their whole spans are 64, 57 and
///   50 tokens.
/// - Tick 46: all three are at W and the budget is 121 = 64 + 57. Two whole spans fill it and
///   leave nothing for the third; one token stays for it, so the first keeps its block, the second
///   takes 56 and the third 1.
/// - Tick 63, the last plan: all three are at W again and the step has 1 token, fewer than its
///   four runnable lanes. That is the one frame outside the bound's condition (serve refuses such
///   a budget): one prefiller is served and two reach age W + 1.
fn ceiling() -> Vec<String> {
    use super::step::{charge, plan, SERVE_STEP_MAX_BYPASS};
    use std::time::Duration;
    const LANES: usize = 4;
    const ALIGN: usize = 64;
    capture(|| {
        let mut planner = ServeStepPlanner::new(LANES, SERVE_STEP_MAX_BYPASS);
        let mut inputs = [ServeLaneInput {
            runnable: true,
            n_past: 64,
            pf_end: 200_000,
            has_pending_decode: false,
        }; LANES];
        inputs[0] = ServeLaneInput {
            runnable: true,
            n_past: 9,
            pf_end: 1,
            has_pending_decode: true,
        };
        for i in 0..LANES {
            planner.on_admit(i);
        }
        for tick in 0..64 {
            inputs[3].runnable = tick != CEILING_HOLD_TICK;
            if tick == CEILING_RESTART_TICK {
                for (i, lane) in inputs.iter_mut().enumerate().skip(1) {
                    planner.on_finish(i);
                    planner.on_admit(i);
                    lane.n_past = 7 * (i - 1);
                    lane.pf_end = 200_000;
                }
            }
            let budget = match tick {
                CEILING_EXACT_TICK => 121,
                CEILING_STARVED_TICK => 1,
                _ => 104,
            };
            let elapsed = match plan(&mut planner, &inputs, budget, ALIGN, None) {
                Some(ServeStepPlan::Decode(chosen)) => {
                    for &i in &chosen {
                        inputs[i].n_past += 1;
                    }
                    40_000
                }
                Some(ServeStepPlan::Prefill(spans)) => {
                    for (i, _, len) in spans {
                        inputs[i].n_past += len;
                    }
                    20_000
                }
                None => unreachable!("the decoder is always runnable"),
            };
            charge(&mut planner, Duration::from_micros(elapsed));
            planner.complete_step();
        }
    })
}

fn plans(frames: &[String]) -> Vec<&String> {
    frames.iter().filter(|f| f.contains(r#""kind":"plan""#)).collect()
}

#[test]
fn seeded_decisions_are_repeatable() {
    for seed in SEEDS {
        let frames = walk(seed);
        let plan_frames = plans(&frames);
        assert_eq!(plan_frames.len(), 64);
        let burst = super::step::SERVE_STEP_MAX_BYPASS as usize;
        if share_for(seed) == 0 {
            // The tick policy bursts W decodes before the first prefill.
            assert!(plan_frames[..burst]
                .iter()
                .all(|f| f.contains(r#""mode":"decode""#)));
            assert!(plan_frames[burst].contains(r#""mode":"prefill""#));
        } else {
            // With a share, a new contention starts owed to prefill.
            assert!(plan_frames[0].contains(r#""mode":"prefill""#));
        }
        assert!(plan_frames.last().unwrap().contains(r#""mode":"idle""#));
        assert!(frames.iter().any(|f| f.contains(r#""kind":"charge""#)));
        assert_eq!(frames, walk(seed));
    }
}

/// The largest age any lane holds after a plan in these frames.
fn oldest_age(frames: &[String]) -> u32 {
    plans(frames)
        .iter()
        .flat_map(|f| {
            let after = f.split(r#""after":["#).nth(1).unwrap().split(']').next().unwrap();
            after.split(", ").map(|age| age.parse::<u32>().unwrap()).collect::<Vec<_>>()
        })
        .max()
        .unwrap()
}

/// The spans of one plan frame, by lane.
fn spans_of(frame: &str) -> Vec<usize> {
    let spans = frame.split(r#""spans":["#).nth(1).unwrap().split(']').next().unwrap();
    spans.split(", ").map(|span| span.parse().unwrap()).collect()
}

/// No lane may be passed over more than W steps in a row, at any budget the walk draws: every
/// seed of the corpus, which includes the first three on which c2a26ce's aligned prefill left a
/// lane at age 17 (two prefillers at the ceiling, a budget of one block and a part, the second
/// one made to wait).
#[test]
fn walk_seeds_that_broke_the_ceiling_stay_within_it() {
    for seed in SEEDS {
        assert!(
            oldest_age(&walk(seed)) <= super::step::SERVE_STEP_MAX_BYPASS,
            "seed {seed}: a lane was passed over more than W steps in a row"
        );
    }
    assert!(CEILING_SEEDS.iter().all(|seed| SEEDS.contains(seed)));
}

#[test]
fn arrivals_are_repeatable_and_bounded() {
    let w = super::step::SERVE_STEP_MAX_BYPASS;
    for budget in [4096, 48] {
        let frames = arrivals(budget);
        let plan_frames = plans(&frames);
        assert_eq!(plan_frames.len(), 64);
        // The decoder ages under the share while prefillers wait.
        assert!(plan_frames.iter().any(|f| f.contains(r#""mode":"prefill""#)));
        assert!(plan_frames.iter().any(|f| f.contains(r#""mode":"decode""#)));
        assert!(oldest_age(&frames) <= w, "budget {budget}");
        assert_eq!(frames, arrivals(budget));
    }
    // The full chunk gives all 17 prefillers whole blocks, with a block or more left over.
    let full = arrivals(4096);
    let full_spans: Vec<_> = plans(&full).into_iter().filter(|f| f.contains(r#""mode":"prefill""#)).map(|f| spans_of(f)).collect();
    assert!(full_spans.iter().flatten().all(|span| span % 64 == 0));
    assert!(full_spans.iter().any(|spans| spans.iter().filter(|&&span| span > 0).count() == 17));
    // Below one block every span is a token grant, and the reserve at W - 1 is needed.
    let reserve = arrivals(48);
    assert!(plans(&reserve).iter().any(|f| f.contains(r#""mode":"prefill""#) && spans_of(f).contains(&1)));
}

#[test]
fn ceiling_workload_serves_both_owed_prefillers_and_ends_outside_the_bound() {
    let w = super::step::SERVE_STEP_MAX_BYPASS;
    let frames = ceiling();
    let plan_frames = plans(&frames);
    assert_eq!(plan_frames.len(), 64);
    // Tick 16: the held prefiller rests at W - 1; the other two share one block and a part.
    let squeezed = plan_frames[CEILING_HOLD_TICK];
    assert!(squeezed.contains(&format!(r#""before":[0, {w}, {w}, {w}]"#)), "{squeezed}");
    assert!(squeezed.contains(r#""spans":[0, 64, 40, 0]"#), "{squeezed}");
    assert!(squeezed.contains(&format!(r#""after":[1, 0, 0, {}]"#, w - 1)), "{squeezed}");
    // Tick 46: one token stays for the third owed prefiller.
    let exact = plan_frames[CEILING_EXACT_TICK];
    assert!(exact.contains(&format!(r#""before":[0, {w}, {w}, {w}]"#)), "{exact}");
    assert!(exact.contains(r#""spans":[0, 64, 56, 1]"#), "{exact}");
    // Every plan but the last is inside the bound.
    assert!(oldest_age(&frames[..frames.len() - 2]) <= w);
    // The last plan has 1 token for four runnable lanes: outside the bound's condition.
    let starved = plan_frames[CEILING_STARVED_TICK];
    assert!(starved.contains(r#""stepBudget":1,"#), "{starved}");
    assert!(starved.contains(&format!(r#""before":[0, {w}, {w}, {w}]"#)), "{starved}");
    assert!(starved.contains(&format!(r#""after":[1, 0, {}, {}]"#, w + 1, w + 1)), "{starved}");
    assert_eq!(frames, ceiling());
}

#[test]
#[ignore = "writes serve planner observations to INKY_SCHED_TRACE_OUT"]
fn dump() {
    let out = match std::env::var("INKY_SCHED_TRACE_SEED") {
        Ok(seed) => match seed.parse().expect("seed must be a u64") {
            ARRIVALS_SEED => arrivals(4096),
            RESERVE_SEED => arrivals(48),
            CEILING_SEED => ceiling(),
            seed => walk(seed),
        },
        Err(_) => SEEDS.into_iter().flat_map(walk).collect(),
    };
    write_trace(&out);
}