inky-engine 2.0.2

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
use crate::scheduler::{ServeLaneInput, ServeStepPlan, ServeStepPlanner};

pub(super) const SERVE_STEP_MAX_BYPASS: u32 = 16;

/// Default `--prefill-share`: percent of charged step time (each step capped at 4 s) prefill gets while decoders also wait.
pub(super) const SERVE_PREFILL_SHARE: u32 = 60;

/// The live scheduler calls this after it has applied backpressure and cache deferrals.
#[inline]
pub(super) fn plan(
    planner: &mut ServeStepPlanner,
    inputs: &[ServeLaneInput],
    budget: usize,
    align: usize,
) -> Option<ServeStepPlan> {
    #[cfg(test)]
    let before = super::scheduler_trace::snapshot(planner, inputs.len());
    let decision = planner.plan_and_begin_step(inputs, budget, align);
    #[cfg(test)]
    if let Some(ages) = before {
        super::scheduler_trace::record(planner, inputs, budget, align, &ages, decision.as_ref());
    }
    decision
}

/// The live scheduler calls this with the measured wall time of each step it executed.
#[inline]
pub(super) fn charge(planner: &mut ServeStepPlanner, elapsed: std::time::Duration) {
    let elapsed_us = u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX);
    #[cfg(test)]
    let before = super::scheduler_trace::charge_snapshot(planner);
    planner.charge_step(elapsed_us);
    #[cfg(test)]
    if let Some(before) = before {
        super::scheduler_trace::record_charge(planner, elapsed_us, before);
    }
}

/// Wall time of one step's GPU intervals, each counted exactly once: the step's command buffer
/// and any GPU work dispatched after it before the step's results are used (DSpark's rejection
/// sampling, batched or per span). The clock is an argument so tests can delay the work.
pub(super) struct StepTime<C: FnMut() -> std::time::Instant> {
    clock: C,
    total: std::time::Duration,
}

impl<C: FnMut() -> std::time::Instant> StepTime<C> {
    pub(super) fn new(clock: C) -> Self {
        Self { clock, total: std::time::Duration::ZERO }
    }

    /// Add an interval measured elsewhere (the command buffer from encode to completion).
    pub(super) fn add(&mut self, interval: std::time::Duration) {
        self.total += interval;
    }

    /// Run synchronous GPU work and add its wall time.
    pub(super) fn time<T>(&mut self, work: impl FnOnce() -> T) -> T {
        let start = (self.clock)();
        let out = work();
        self.total += (self.clock)().saturating_duration_since(start);
        out
    }

    pub(super) fn total(&self) -> std::time::Duration {
        self.total
    }
}