inky-engine 3.0.0

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
--------------------------- MODULE PoolPreempt ---------------------------
\* The KV pool livelock escape of the serve loop (src/serve.rs: `partition_pool_exhausted`,
\* `preempt_for_pool`, `choose_preempt_victim`, `LaneS::preempt`, `requeue_preempted`, and the
\* admission that resumes a preempted request), with the lane states it moves a request through:
\* queued, admitted (ready), planned, deferred, preempted and queued again, resumed.
\*
\* One token is one block: every prefill row and every decode row takes one block of the pool, so
\* a lane needs a new block for each step. A request is `Prompt` rows of prompt and `Reply` reply
\* tokens; it writes `Prompt + Reply - 1` rows (the last token is sent without another row).
\* Admission reserves the rows to the end of the prompt and at most `Reserve` decode rows for each
\* lane (`InflightLaneReserve::reserved_end`, `MAX_ADMIT_DECODE_RESERVE`), so replies longer than
\* that can outgrow the pool together. Retained start points are evictable and count as free.
\*
\* The serve loop is serialized: one lane is planned, then it runs, or it is deferred (its block is
\* not there and another lane can still make progress), or the loop is in livelock (no lane can
\* take its next block and none can free one) and one lane gives way. `Run` of the last prefill
\* row samples and sends the next reply token, as a decode row does.
\*
\* A request preempted in its reply resumes as a continuation of itself: its rows to prefill are
\* the prompt and every reply token already sent (`PfEnd`), the last of them the token that was
\* sent but not yet fed, and the logits of that last row draw the next token. `out[r]` is what the
\* client received, as reply indexes: NoTokenTwice says it is 1, 2, 3, ... with no repeat, gap or
\* restart.
\*
\* `Stall` lets a client stop reading (`backpressured`): such a lane cannot step, but it is not
\* stuck on the pool, and the escape waits for it (`client_gated`).
\* `StitchLen > 0` gives each admitted prompt a stitch at row `StitchAt`: `StitchLen` blocks taken
\* at once, or the plan is given up and the rows are prefilled (`StitchStartOutcome::PoolBusy`).
\*
\* Bug selects a reversed witness; each is one change against the code:
\*   "fail_victim"       the behaviour before preemption: the escape fails the lane it was asked
\*                       about with an HTTP 500 (FailOnlyAsLastResort)
\*   "resend_pending"    the continuation stops at the committed rows, so the token that was sent
\*                       but not fed is drawn and sent again (NoTokenTwice)
\*   "restart_reply"     the request is queued again as it arrived and its reply starts over
\*                       (NoTokenTwice)
\*   "queue_behind"      a preempted request goes to the back of the queue (QueueOrder)
\*   "drop_requeue"      the lane is released and the request never queued (PreemptedResumes)
\*   "resume_unchecked"  a preempted request is admitted again without the pool check, into the
\*                       pool it was just preempted from (NoRequestFailed)
\*   "ignore_client"     the escape does not wait for a lane that only waits for its client
\*                       (EscapeOnlyAtLivelock)
\*   "stitch_defer"      a stitch that does not fit defers its lane, which the wake test (one
\*                       ordinary row fits) then wakes again, every step (NoFalseDeferral)
EXTENDS Integers, Sequences, FiniteSets

CONSTANTS N, Lanes, Pool, Prompt, Reply, Reserve, MaxPreempt, Stall, StitchAt, StitchLen, Bug
ASSUME /\ N \in Nat /\ N >= 1
       /\ Lanes \in Nat /\ Lanes >= 1
       /\ Prompt \in Nat /\ Prompt >= 1
       /\ Reply \in Nat /\ Reply >= 1
       /\ Reserve \in Nat
       \* One request alone always fits (`context_over` refuses the others before they queue).
       /\ Pool \in Nat /\ Pool >= Prompt + Reply - 1
       /\ MaxPreempt \in Nat
       /\ Stall \in BOOLEAN
       /\ StitchAt \in Nat /\ StitchLen \in Nat
       /\ StitchLen > 0 => StitchAt + StitchLen < Prompt
       /\ Bug \in {"none", "fail_victim", "resend_pending", "restart_reply", "queue_behind",
                   "drop_requeue", "resume_unchecked", "ignore_client", "stitch_defer"}

\* Request ordinals (`Job::seq`): a lower one arrived earlier.
Reqs == 1..N
Min(a, b) == IF a < b THEN a ELSE b

VARIABLES
    st,          \* "new", "queued", "prefill", "decode", "done", "failed"
    ls,          \* on a lane: "ready", "planned" (picked for the step), "deferred" (`pool_deferred`)
    kv,          \* rows the request's lane holds (0 off a lane): blocks of the pool
    sent,        \* reply tokens sent to the client
    out,         \* the reply indexes the client received, in order
    pre,         \* times the request was preempted (`Resumed::preemptions`)
    stitch,      \* a stitch plan waits at row StitchAt
    bp,          \* the client is not reading (`backpressured`)
    queue,       \* the scheduler's queue, head first
    badFail,     \* ghost: a request failed while a lane could be preempted
    earlyEscape, \* ghost: a lane gave way while another lane only waited for its client
    falseDefer   \* ghost: a lane was deferred while its next row had a block
vars == <<st, ls, kv, sent, out, pre, stitch, bp, queue, badFail, earlyEscape, falseDefer>>

OnLane(r) == st[r] \in {"prefill", "decode"}
Busy == {r \in Reqs : OnLane(r)}

RECURSIVE Sum(_, _)
Sum(f, S) == IF S = {} THEN 0 ELSE LET x == CHOOSE x \in S : TRUE IN f[x] + Sum(f, S \ {x})
Free == Pool - Sum(kv, Reqs)

\* Rows a request prefills before its next sample: its prompt, then the reply tokens already sent.
PfEnd(r) == IF Bug = "resend_pending" /\ pre[r] > 0 /\ sent[r] > 0 THEN Prompt + sent[r] - 1
            ELSE Prompt + sent[r]

\* Blocks admission still counts for a lane (`reserved_end - written`), and for a queued request.
ToTake(r) == IF st[r] = "decode" THEN Min(Reply - sent[r], Reserve)
             ELSE (PfEnd(r) - kv[r]) + Min(Reply - sent[r] - 1, Reserve)
Need(q) == PfEnd(q) + Min(Reply - sent[q] - 1, Reserve)
Fits(q) == \/ Busy = {}
           \/ Sum([r \in Reqs |-> IF OnLane(r) THEN ToTake(r) ELSE 0], Reqs) + Need(q) <= Free
           \/ Bug = "resume_unchecked" /\ pre[q] > 0

Init ==
    /\ st = [r \in Reqs |-> "new"]
    /\ ls = [r \in Reqs |-> "ready"]
    /\ kv = [r \in Reqs |-> 0]
    /\ sent = [r \in Reqs |-> 0]
    /\ out = [r \in Reqs |-> << >>]
    /\ pre = [r \in Reqs |-> 0]
    /\ stitch = [r \in Reqs |-> FALSE]
    /\ bp = [r \in Reqs |-> FALSE]
    /\ queue = << >>
    /\ badFail = FALSE
    /\ earlyEscape = FALSE
    /\ falseDefer = FALSE

\* Requests arrive in the order of their ordinals.
Arrive(r) ==
    /\ st[r] = "new"
    /\ \A o \in Reqs : o < r => st[o] # "new"
    /\ st' = [st EXCEPT ![r] = "queued"]
    /\ queue' = Append(queue, r)
    /\ UNCHANGED <<ls, kv, sent, out, pre, stitch, bp, badFail, earlyEscape, falseDefer>>

\* Admission is from the head of the queue only: nothing passes a request that does not fit.
Admit ==
    /\ queue # << >>
    /\ Cardinality(Busy) < Lanes
    /\ \A r \in Reqs : ls[r] # "planned"
    /\ LET q == Head(queue) IN
        /\ Fits(q)
        /\ st' = [st EXCEPT ![q] = "prefill"]
        /\ ls' = [ls EXCEPT ![q] = "ready"]
        /\ stitch' = [stitch EXCEPT ![q] = StitchLen > 0 /\ PfEnd(q) > StitchAt + StitchLen]
    /\ queue' = Tail(queue)
    /\ UNCHANGED <<kv, sent, out, pre, bp, badFail, earlyEscape, falseDefer>>

\* A lane the planner may pick: ready, or deferred with a block for its next row
\* (`refresh_pool_deferred` wakes it before the plan).
Awake(r) == OnLane(r) /\ ~bp[r] /\ (ls[r] = "ready" \/ (ls[r] = "deferred" /\ Free >= 1))
AtStitch(r) == st[r] = "prefill" /\ stitch[r] /\ kv[r] = StitchAt
NonePlanned == \A r \in Reqs : ls[r] # "planned"

\* The stitch at the lane's position, before the plan: all its blocks at once, or none. When they
\* are not there the plan is given up and the lane prefills the rows.
StitchStep(r) ==
    /\ NonePlanned /\ Awake(r) /\ AtStitch(r)
    /\ IF Free >= StitchLen
       THEN /\ kv' = [kv EXCEPT ![r] = @ + StitchLen]
            /\ stitch' = [stitch EXCEPT ![r] = FALSE]
            /\ ls' = [ls EXCEPT ![r] = "ready"]
            /\ UNCHANGED falseDefer
       ELSE IF Bug = "stitch_defer" /\ \E s \in Busy \ {r} : ~bp[s] /\ ls[s] # "deferred"
            THEN /\ ls' = [ls EXCEPT ![r] = "deferred"]
                 /\ falseDefer' = (falseDefer \/ Free >= 1)
                 /\ UNCHANGED <<kv, stitch>>
            ELSE /\ stitch' = [stitch EXCEPT ![r] = FALSE]
                 /\ ls' = [ls EXCEPT ![r] = "ready"]
                 /\ UNCHANGED <<kv, falseDefer>>
    /\ UNCHANGED <<st, sent, out, pre, bp, queue, badFail, earlyEscape>>

Plan(r) ==
    /\ NonePlanned /\ Awake(r) /\ ~AtStitch(r)
    /\ ls' = [ls EXCEPT ![r] = "planned"]
    /\ UNCHANGED <<st, kv, sent, out, pre, stitch, bp, queue, badFail, earlyEscape, falseDefer>>

\* The planned lane writes one row. The last prefill row and every decode row sample one token
\* and send it; the reply's last token ends the request and releases the lane.
Run(r) ==
    /\ ls[r] = "planned" /\ Free >= 1
    /\ LET rows == kv[r] + 1
           samples == st[r] = "decode" \/ rows = PfEnd(r)
           resent == Bug = "resend_pending" /\ st[r] = "prefill" /\ pre[r] > 0 /\ sent[r] > 0
           n == IF resent THEN sent[r] ELSE sent[r] + 1
           last == samples /\ n = Reply
       IN  /\ out' = [out EXCEPT ![r] = IF samples THEN Append(@, n) ELSE @]
           /\ sent' = [sent EXCEPT ![r] = IF samples THEN n ELSE @]
           /\ st' = [st EXCEPT ![r] = IF last THEN "done" ELSE IF samples THEN "decode" ELSE @]
           /\ kv' = [kv EXCEPT ![r] = IF last THEN 0 ELSE rows]
    /\ ls' = [ls EXCEPT ![r] = "ready"]
    /\ UNCHANGED <<pre, stitch, bp, queue, badFail, earlyEscape, falseDefer>>

\* Another lane can still make progress: it is runnable, or it only waits for its client (a client
\* that reads lets it step; one that is gone is cancelled and its lane released).
ClientGated(s) == OnLane(s) /\ bp[s]
OtherProgress(r) ==
    \E s \in Busy \ {r} : \/ ~bp[s] /\ ls[s] = "ready"
                          \/ Bug # "ignore_client" /\ ClientGated(s)

Defer(r) ==
    /\ ls[r] = "planned" /\ Free = 0 /\ OtherProgress(r)
    /\ ls' = [ls EXCEPT ![r] = "deferred"]
    /\ UNCHANGED <<st, kv, sent, out, pre, stitch, bp, queue, badFail, earlyEscape, falseDefer>>

\* `choose_preempt_victim`: among the lanes stuck on the pool, a request preempted before gives way
\* after one that never was; then the lane with the fewest blocks of its own (the least work to
\* compute again); then the youngest request.
Better(v, w) == \/ pre[v] < pre[w]
                \/ pre[v] = pre[w] /\ kv[v] < kv[w]
                \/ pre[v] = pre[w] /\ kv[v] = kv[w] /\ v >= w
Stuck(r) == {r} \cup {s \in Busy : ls[s] = "deferred"}
Cands(r) == {v \in Stuck(r) : pre[v] < MaxPreempt /\ kv[v] >= 1}
CanPreempt(r) == Cardinality(Busy) >= 2 /\ Cands(r) # {}
Victim(r) == CHOOSE v \in Cands(r) : \A w \in Cands(r) : Better(v, w)

\* `requeue_preempted`: ahead of every request that has not run, behind preempted ones that arrived
\* before it.
Requeue(q, v) ==
    LET k == Cardinality({i \in 1..Len(q) : pre[q[i]] > 0 /\ q[i] < v})
    IN  SubSeq(q, 1, k) \o <<v>> \o SubSeq(q, k + 1, Len(q))

\* No lane can take its next block and none can free one: one lane gives way.
Escape(r) ==
    /\ ls[r] = "planned" /\ Free = 0 /\ ~OtherProgress(r)
    /\ earlyEscape' = (earlyEscape \/ \E s \in Busy \ {r} : ClientGated(s))
    /\ IF Bug # "fail_victim" /\ CanPreempt(r)
       THEN LET v == Victim(r) IN
            /\ st' = [st EXCEPT ![v] = "queued"]
            /\ kv' = [kv EXCEPT ![v] = 0]
            /\ pre' = [pre EXCEPT ![v] = @ + 1]
            /\ sent' = [sent EXCEPT ![v] = IF Bug = "restart_reply" THEN 0 ELSE @]
            /\ stitch' = [stitch EXCEPT ![v] = FALSE]
            /\ bp' = [bp EXCEPT ![v] = FALSE]
            /\ ls' = [s \in Reqs |-> IF s = v THEN "ready" ELSE IF s = r THEN "deferred" ELSE ls[s]]
            /\ queue' = CASE Bug = "drop_requeue" -> queue
                          [] Bug = "queue_behind" -> Append(queue, v)
                          [] OTHER -> Requeue(queue, v)
            /\ UNCHANGED <<out, badFail>>
       ELSE /\ st' = [st EXCEPT ![r] = "failed"]
            /\ kv' = [kv EXCEPT ![r] = 0]
            /\ ls' = [ls EXCEPT ![r] = "ready"]
            /\ stitch' = [stitch EXCEPT ![r] = FALSE]
            /\ bp' = [bp EXCEPT ![r] = FALSE]
            /\ badFail' = (badFail \/ CanPreempt(r))
            /\ UNCHANGED <<sent, out, pre, queue>>
    /\ UNCHANGED falseDefer

StallOn(r) ==
    /\ Stall /\ OnLane(r) /\ ~bp[r] /\ ls[r] = "ready"
    /\ bp' = [bp EXCEPT ![r] = TRUE]
    /\ UNCHANGED <<st, ls, kv, sent, out, pre, stitch, queue, badFail, earlyEscape, falseDefer>>

\* The client reads again (the client write timeout bounds how long it may not).
StallOff(r) ==
    /\ bp[r]
    /\ bp' = [bp EXCEPT ![r] = FALSE]
    /\ UNCHANGED <<st, ls, kv, sent, out, pre, stitch, queue, badFail, earlyEscape, falseDefer>>

Work == \/ Admit
        \/ \E r \in Reqs : Arrive(r) \/ StitchStep(r) \/ Plan(r) \/ Run(r) \/ Defer(r) \/ Escape(r) \/ StallOff(r)
Next == Work \/ \E r \in Reqs : StallOn(r)
\* The loop keeps stepping while it can, and a stalled client reads again.
Spec == Init /\ [][Next]_vars /\ WF_vars(Work)

TypeOK ==
    /\ st \in [Reqs -> {"new", "queued", "prefill", "decode", "done", "failed"}]
    /\ ls \in [Reqs -> {"ready", "planned", "deferred"}]
    /\ kv \in [Reqs -> 0..Pool]
    /\ sent \in [Reqs -> 0..Reply]
    /\ \A r \in Reqs : Len(out[r]) <= Reply + MaxPreempt
    /\ pre \in [Reqs -> 0..MaxPreempt]
    /\ stitch \in [Reqs -> BOOLEAN]
    /\ bp \in [Reqs -> BOOLEAN]
    /\ badFail \in BOOLEAN /\ earlyEscape \in BOOLEAN /\ falseDefer \in BOOLEAN

\* The pool is never over-committed, and only lanes hold blocks.
PoolBound == Free >= 0 /\ \A r \in Reqs : ~OnLane(r) => kv[r] = 0 /\ ls[r] = "ready" /\ ~bp[r]
\* At most `Lanes` requests are on lanes, and a decoding lane holds its prompt and all but the last
\* token it sent.
LaneShape == /\ Cardinality(Busy) <= Lanes
             /\ \A r \in Reqs : st[r] = "decode" => kv[r] = Prompt + sent[r] - 1
\* The client receives each reply token once, in order: no repeat, no gap, no restart.
NoTokenTwice == \A r \in Reqs : /\ Len(out[r]) = sent[r]
                               /\ \A i \in 1..Len(out[r]) : out[r][i] = i
\* No request is failed while a lane could have been preempted instead.
FailOnlyAsLastResort == ~badFail
\* With room for every request alone and preemptions to spare, none fails at all.
NoRequestFailed == \A r \in Reqs : st[r] # "failed"
\* No lane gives way while another could still free blocks by itself.
EscapeOnlyAtLivelock == ~earlyEscape
\* A deferred lane lacked a block when it was deferred.
NoFalseDeferral == ~falseDefer
\* A queued request is in the queue once; preempted requests wait ahead of the others, oldest first.
QueueOrder ==
    /\ \A r \in Reqs : st[r] = "queued" => \E i \in 1..Len(queue) : queue[i] = r
    /\ \A i, j \in 1..Len(queue) : i < j =>
          /\ queue[i] # queue[j]
          /\ pre[queue[j]] > 0 => pre[queue[i]] > 0 /\ queue[i] < queue[j]

\* A preempted request is admitted again, and every request ends.
PreemptedResumes == \A r \in Reqs : (st[r] = "queued" /\ pre[r] > 0) ~> (st[r] # "queued")
AllEnd == <>(\A r \in Reqs : st[r] \in {"done", "failed"})
=============================================================================