inky-engine 3.0.1

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
//! What happens when a turn's thinking reaches its budget.
//!
//! The Inkling chat template writes each part of a model turn as its own message:
//! `<|message_model|>[name]<|content_thinking|>...<|end_message|><|message_model|>[tool]<|content_invoke_tool_json|>...`.
//! A forced close therefore ends the thinking message with `<|end_message|>` and opens the next model message
//! with `<|message_model|>`, so the model picks the header (a tool name or `<|content_text|>`) itself and the
//! tool grammar sees a normal tool span. An optional bridge, a short sentence written inside the thinking
//! message before the close, tells the model to act rather than narrate a plan.
//!
//! The budget is the turn's total: thinking tokens of every thinking message in the turn count against it.
//!
//! Answer room is kept by output position, not by a count fixed when the turn starts, because a turn may open
//! a thinking message anywhere: first, after an earlier thinking message closed, or after text. [`Room`] says
//! from which output token thinking must be closed, and from which one a thinking message may no longer open.
//! Under a budget, a turn therefore never reaches its `max_tokens` (or `-n`) inside a thinking message.

use std::sync::Arc;

use super::Specials;

/// Answer tokens kept free after a forced close unless `INK_THINKING_ANSWER_ROOM` says otherwise.
pub(super) const DEFAULT_ANSWER_ROOM: usize = 1024;

/// Written inside the thinking message before the forced close (`INK_THINKING_CAP_BRIDGE`). Empty by default:
/// with `<|message_model|>` forced after the close, studio smokes on Inkling-2-Mini made the tool call without
/// one. Set it to A/B a nudge such as "\n\nThinking budget reached. I act now: call the needed tool directly,
/// or answer if no tool is needed."
pub(super) const DEFAULT_BRIDGE: &str = "";

/// Tokens the model spends opening its thinking message (`<|message_model|><|content_thinking|>`), which
/// count against `max_tokens` but not against the thinking budget.
const THINK_OPEN: usize = 2;

#[derive(Clone, Debug)]
pub(super) struct ThinkCapPolicy {
    pub(super) answer_room: usize,
    /// The whole forced sequence: bridge tokens, then `<|end_message|>`, then `<|message_model|>`.
    pub(super) close: Arc<[u32]>,
}

impl Default for ThinkCapPolicy {
    /// Default room, no bridge; an empty `close` means `[<|end_message|>, <|message_model|>]`.
    fn default() -> Self {
        Self { answer_room: DEFAULT_ANSWER_ROOM, close: Arc::from([]) }
    }
}

impl ThinkCapPolicy {
    pub(super) fn new(answer_room: usize, bridge: &[u32], sp: &Specials) -> Self {
        Self { answer_room, close: close_sequence(bridge, sp).into() }
    }

    /// Reads `INK_THINKING_ANSWER_ROOM` and `INK_THINKING_CAP_BRIDGE` (internal developer settings).
    pub(super) fn from_env(tk: &crate::tokenizer::Tokenizer, sp: &Specials) -> Result<Self, String> {
        let answer_room = match std::env::var("INK_THINKING_ANSWER_ROOM") {
            Ok(v) => v
                .trim()
                .parse::<usize>()
                .map_err(|_| format!("INK_THINKING_ANSWER_ROOM must be a whole number of tokens, got {v:?}"))?,
            Err(_) => DEFAULT_ANSWER_ROOM,
        };
        let bridge_text = std::env::var("INK_THINKING_CAP_BRIDGE").unwrap_or_else(|_| DEFAULT_BRIDGE.to_string());
        // Plain text only: a control-token spelling in the bridge stays ordinary text.
        let bridge = tk.encode(&bridge_text, false);
        Ok(Self::new(answer_room, &bridge, sp))
    }
}

/// `bridge ++ [<|end_message|>, <|message_model|>]`: closes the thinking message as the template does and
/// opens the next model message, so a tool call or a text answer follows and the turn cannot end empty.
pub(super) fn close_sequence(bridge: &[u32], sp: &Specials) -> Vec<u32> {
    let mut v = Vec::with_capacity(bridge.len() + 2);
    v.extend_from_slice(bridge);
    v.push(sp.end);
    v.push(sp.msg_model);
    v
}

/// Where in a turn's output thinking has to stop so the forced close and the answer room still fit.
///
/// Output tokens are numbered from 0 in the order they are sampled, whatever they are. The answer room is
/// `answer_room`, or half of `max_gen` when that is smaller.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Room {
    /// `max_gen - close_len - room`: a token at this index or later that would continue a thinking message is
    /// replaced by the forced close, which then ends with exactly the room left.
    close_from: usize,
}

impl Default for Room {
    /// No limit: thinking is never closed or refused for room.
    fn default() -> Self {
        Self { close_from: usize::MAX }
    }
}

impl Room {
    pub(super) fn new(max_gen: usize, answer_room: usize, close_len: usize) -> Self {
        let room = answer_room.min(max_gen / 2);
        Self { close_from: max_gen.saturating_sub(close_len.saturating_add(room)) }
    }

    /// Whether output token `at`, continuing a thinking message, must give way to the forced close.
    pub(super) fn must_close(&self, at: usize) -> bool {
        at >= self.close_from
    }

    /// Whether `<|content_thinking|>` may be sampled as output token `at`: the token after it must still be
    /// allowed to think, or the message would be closed before its first token. A turn's first token is
    /// charged like its second, so a thinking message opened without `<|message_model|>` gets no extra token.
    pub(super) fn may_open(&self, at: usize) -> bool {
        !self.must_close(at.max(THINK_OPEN - 1).saturating_add(1))
    }

    /// Thinking tokens that fit when thinking is the turn's first message.
    fn first_message_limit(&self) -> usize {
        self.close_from.saturating_sub(THINK_OPEN)
    }
}

/// The thinking budget a turn runs with.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Budget {
    /// No budget (`0`): thinking is not capped.
    Unlimited,
    /// Cap thinking at this many tokens (`>= 1`); `clamped` when answer room lowered the requested budget.
    Cap { tokens: usize, clamped: bool },
    /// `max_gen` cannot hold the thinking open, one thinking token, the close and the answer room: thinking is
    /// never opened (`<|content_thinking|>` is banned from the first token), so the turn goes to its answer.
    NoThinking,
}

/// The most a turn can think: its total budget, lowered to what fits when thinking is the turn's first message.
///
/// `budget == 0` (unlimited) is left alone. Otherwise the budget is lowered so that the thinking open, the
/// thinking itself, the forced close and `answer_room` answer tokens all fit in `max_gen`. When `max_gen` is
/// too small for the full room, the answer gets half of it. When not even one thinking token fits, the turn
/// does not think at all: a turn that opened thinking there would end at length inside it.
///
/// A turn that opens thinking later, or more than once, has less room than this: [`Room`] holds it to that.
pub(super) fn effective_budget(budget: usize, max_gen: usize, answer_room: usize, close_len: usize) -> Budget {
    if budget == 0 {
        return Budget::Unlimited;
    }
    let limit = Room::new(max_gen, answer_room, close_len).first_message_limit();
    if limit == 0 {
        Budget::NoThinking
    } else if limit < budget {
        Budget::Cap { tokens: limit, clamped: true }
    } else {
        Budget::Cap { tokens: budget, clamped: false }
    }
}

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

    #[test]
    fn production_pin_keeps_its_budget() {
        // -n 20480 with --thinking-budget 16384 leaves 4,096 - 2 - close for the answer: no lowering.
        assert_eq!(effective_budget(16_384, 20_480, 1024, 30), Budget::Cap { tokens: 16_384, clamped: false });
    }

    #[test]
    fn small_max_tokens_lowers_the_budget_to_keep_answer_room() {
        // Client sends max_tokens 4096 against a 16,384 budget: thinking stops at 4096 - 2 - 30 - 1024.
        assert_eq!(effective_budget(16_384, 4096, 1024, 30), Budget::Cap { tokens: 3040, clamped: true });
        // Exactly at the boundary: no lowering.
        assert_eq!(effective_budget(3040, 4096, 1024, 30), Budget::Cap { tokens: 3040, clamped: false });
        assert_eq!(effective_budget(3041, 4096, 1024, 30), Budget::Cap { tokens: 3040, clamped: true });
    }

    #[test]
    fn tiny_max_tokens_splits_what_is_left() {
        // max_tokens 100: room is 50, thinking gets 100 - 2 - 2 - 50 = 46.
        assert_eq!(effective_budget(16_384, 100, 1024, 2), Budget::Cap { tokens: 46, clamped: true });
        // The smallest turn that may think: 9 = open 2 + 1 thinking + close 2 + room 4.
        assert_eq!(effective_budget(16_384, 9, 1024, 2), Budget::Cap { tokens: 1, clamped: true });
        // Anything smaller does not think at all.
        for max_gen in 0..=8 {
            assert_eq!(effective_budget(16_384, max_gen, 1024, 2), Budget::NoThinking, "max_gen {max_gen}");
        }
        assert_eq!(effective_budget(1, 8, 1024, 2), Budget::NoThinking);
    }

    #[test]
    fn unlimited_budget_and_zero_room() {
        assert_eq!(effective_budget(0, 100, 1024, 2), Budget::Unlimited);
        assert_eq!(effective_budget(0, 1, 1024, 2), Budget::Unlimited);
        // Room 0 still reserves the thinking open and the close.
        assert_eq!(effective_budget(16_384, 1000, 0, 2), Budget::Cap { tokens: 996, clamped: true });
        assert_eq!(effective_budget(16_384, 5, 0, 2), Budget::Cap { tokens: 1, clamped: true });
        assert_eq!(effective_budget(16_384, 4, 0, 2), Budget::NoThinking);
        assert_eq!(effective_budget(usize::MAX, usize::MAX, usize::MAX, usize::MAX), Budget::NoThinking);
    }

    #[test]
    fn close_sequence_ends_thinking_then_opens_the_next_model_message() {
        let tk = crate::tokenizer::Tokenizer::for_byte_test();
        let sp = Specials::try_from_tokenizer(&tk).unwrap();
        assert_eq!(close_sequence(&[], &sp), vec![sp.end, sp.msg_model]);
        let bridge = tk.encode("Act now.", false);
        let seq = close_sequence(&bridge, &sp);
        assert_eq!(&seq[..bridge.len()], &bridge[..]);
        assert_eq!(&seq[bridge.len()..], &[sp.end, sp.msg_model]);
        let text: Vec<u8> = seq.iter().flat_map(|&t| tk.decode_bytes(t)).collect();
        assert_eq!(String::from_utf8(text).unwrap(), "Act now.<|end_message|><|message_model|>");
    }
}