#[cfg(not(any(feature = "candle", feature = "mlx")))]
compile_error!("the oi-kit-inference CLI requires an mlx or candle backend feature");
#[cfg(feature = "realtime")]
mod audio;
mod common;
mod decisions;
#[cfg(feature = "vision")]
mod media;
mod memory;
#[cfg(feature = "realtime")]
mod realtime;
fn cli_command() -> clap::Command {
let command = Cli::command();
#[cfg(feature = "realtime")]
let command = <CliCommand as clap::Subcommand>::augment_subcommands(command)
.about("Local text, audio tasks and realtime conversation")
.subcommand_negates_reqs(true)
.args_conflicts_with_subcommands(true);
command
}
#[cfg(feature = "realtime")]
#[derive(Debug, clap::Subcommand)]
enum CliCommand {
/// Run a turn-based audio task or a full-duplex conversation.
Audio(audio::Args),
}
use std::{
collections::HashSet,
fmt, fs,
io::{self, IsTerminal, Read, Write},
num::NonZeroUsize,
path::{Path, PathBuf},
process::{Command, Stdio},
str::FromStr,
time::{Instant, UNIX_EPOCH},
};
use anyhow::{bail, Context, Result};
use clap::{parser::ValueSource, ArgMatches, CommandFactory, FromArgMatches, Parser, ValueEnum};
use hf_cache_reader::{resolve_cache_dir, scan_repo, CachedRevision, RepoType};
use oi_kit_inference::{
api::{
inspect_execution, BackendInspection, GenerationRequest, LoadedModel,
PreparedChatGenerationSettings, PreparedChatInput, TextDecoder, TextModelError,
},
runtime::chat::{
ChatTemplateRequest, NativeToolSupport, ParallelToolCallPolicy, SemanticSupport, ToolChoice,
},
};
#[cfg(feature = "vision")]
use oi_kit_inference_core::MultimodalPreparationSession as TextInputSession;
#[cfg(test)]
use oi_kit_inference_core::QuantizationRequest;
#[cfg(not(feature = "vision"))]
use oi_kit_inference_core::TextExecutionSession as TextInputSession;
use oi_kit_inference_core::{
residency::CacheEvictionPolicy, speculative::SpeculativeStats, speculative_decoding_telemetry,
AutomaticPlanRequest, AutomaticPlanner, AutomaticPlannerPolicy, AutomaticPlanningBackend,
BackendHardware, DeviceCapabilities, DevicePlan, DraftPlacementPlan, DraftingPlan,
ExecutionPlan, ExecutionPlanReport, ExecutionTelemetry, ExpertCachePlan, FinishReason,
GenerationCancellationToken, GenerationConfigOverrides, HardwareBackendProfile,
HardwareDeviceKind, HardwareMemorySemantics, HardwareProfile, InspectionSeverity,
ModelResourceProfile, Observed, PlanExplanation, PlanExplanationEntry, PlanExplanationLevel,
ResidencyPlan, SemanticEvent, SessionCapabilities, TextGenerationConfig, TimingTelemetry,
WeightTransformationPlan, EXECUTION_PLAN_SCHEMA_VERSION,
};
use oi_kit_inference_runtime::DenseDiskStreamLoadOptions;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
enum MemoryPolicy {
/// Print estimates and continue ordinary generation.
#[default]
Warn,
/// Refuse when the estimate shows a likely budget shortfall.
Refuse,
}
#[derive(Debug, Clone, Copy, ValueEnum)]
enum ExpertCacheEviction {
Lru,
Lfu,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, ValueEnum)]
enum ThinkingMode {
/// Preserve the model chat template's default.
Auto,
/// Ask a compatible chat template to enable thinking/reasoning.
On,
/// Ask a compatible chat template to disable thinking/reasoning.
Off,
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, ValueEnum)]
enum LoadQuantizationMode {
#[default]
Affine,
Mxfp4,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, ValueEnum)]
enum AutoMode {
/// Inspect hardware and checkpoint headers, print the selected plan as JSON, and exit.
Plan,
/// Select a low-latency single-device plan and execute it.
Quick,
/// Benchmark admitted plans in isolated child processes and select the fastest.
Benchmark,
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, ValueEnum)]
enum CliToolChoice {
None,
#[default]
Auto,
Required,
}
impl From<CliToolChoice> for ToolChoice {
fn from(value: CliToolChoice) -> Self {
match value {
CliToolChoice::None => Self::None,
CliToolChoice::Auto => Self::Auto,
CliToolChoice::Required => Self::Required,
}
}
}
#[derive(Debug, Clone, Copy, ValueEnum)]
enum CliBackend {
Mlx,
Candle,
}
impl CliBackend {
const fn default_available() -> Self {
if cfg!(feature = "mlx") {
Self::Mlx
} else {
Self::Candle
}
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum CliDevice {
Cpu,
Gpu(usize),
Metal(usize),
Cuda(usize),
}
impl fmt::Display for CliDevice {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Cpu => formatter.write_str("cpu"),
Self::Gpu(index) => write!(formatter, "gpu:{index}"),
Self::Metal(index) => write!(formatter, "metal:{index}"),
Self::Cuda(index) => write!(formatter, "cuda:{index}"),
}
}
}
impl FromStr for CliDevice {
type Err = String;
fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
if value == "cpu" {
return Ok(Self::Cpu);
}
let Some((family, index)) = value.split_once(':') else {
return Err("expected `cpu`, `gpu:N`, `metal:N`, or `cuda:N`".into());
};
let index = index
.parse::<usize>()
.map_err(|_| "GPU index must be a non-negative integer".to_string())?;
match family {
"gpu" => Ok(Self::Gpu(index)),
"metal" => Ok(Self::Metal(index)),
"cuda" => Ok(Self::Cuda(index)),
_ => Err("expected `cpu`, `gpu:N`, `metal:N`, or `cuda:N`".into()),
}
}
}
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
enum SpeculativeDraftDevice {
#[default]
Target,
Device(CliDevice),
}
impl fmt::Display for SpeculativeDraftDevice {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Target => formatter.write_str("target"),
Self::Device(device) => device.fmt(formatter),
}
}
}
impl FromStr for SpeculativeDraftDevice {
type Err = String;
fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
if value == "target" {
Ok(Self::Target)
} else {
value.parse().map(Self::Device)
}
}
}
impl ThinkingMode {
const fn enabled(self) -> Option<bool> {
match self {
Self::Auto => None,
Self::On => Some(true),
Self::Off => Some(false),
}
}
}
impl From<ExpertCacheEviction> for CacheEvictionPolicy {
fn from(value: ExpertCacheEviction) -> Self {
match value {
ExpertCacheEviction::Lru => Self::LeastRecentlyUsed,
ExpertCacheEviction::Lfu => Self::LeastFrequentlyUsed,
}
}
}
impl From<CacheEvictionPolicy> for ExpertCacheEviction {
fn from(value: CacheEvictionPolicy) -> Self {
match value {
CacheEvictionPolicy::LeastRecentlyUsed => Self::Lru,
CacheEvictionPolicy::LeastFrequentlyUsed => Self::Lfu,
}
}
}
/// Generate text with a model supported by oi-kit-inference.
#[derive(Debug, Clone, Parser)]
#[command(name = "oi-kit-inference", version, about, long_about = None,
group(clap::ArgGroup::new("text_model").args(["model"]).required(true)))]
struct Cli {
#[command(flatten)]
common: common::CommonOptions,
/// Text execution backend. Defaults to MLX when enabled, otherwise Candle.
#[arg(long, value_enum)]
backend: Option<CliBackend>,
/// Automatically select a single-device execution plan. Defaults to quick.
#[arg(long, value_enum, value_name = "MODE", default_value = "quick")]
auto: Option<AutoMode>,
/// Disable automatic planning and use explicit/default CLI settings only.
#[arg(
long,
conflicts_with_all = [
"auto",
"auto_cache",
"auto_feedback",
"auto_benchmark_tokens",
"auto_benchmark_runs",
"auto_benchmark_timeout_seconds",
"auto_trial_plan"
]
)]
no_auto: bool,
/// Read or update a reusable automatic-plan cache at this path.
#[arg(long, value_name = "PATH", requires = "auto")]
auto_cache: Option<PathBuf>,
/// Prior execution telemetry considered by automatic planning. May be repeated.
#[arg(long, value_name = "PATH", requires = "auto")]
auto_feedback: Vec<PathBuf>,
/// Generated tokens per isolated automatic benchmark trial.
#[arg(long, default_value_t = 32, value_name = "TOKENS", requires = "auto")]
auto_benchmark_tokens: usize,
/// Fresh-process repetitions for each automatic benchmark candidate.
#[arg(long, default_value_t = 1, value_name = "RUNS", requires = "auto")]
auto_benchmark_runs: usize,
/// Maximum wall time allowed for one isolated benchmark process.
#[arg(long, default_value_t = 300, value_name = "SECONDS", requires = "auto")]
auto_benchmark_timeout_seconds: u64,
/// Internal exact plan passed from an automatic benchmark parent process.
#[arg(long, hide = true, value_name = "PATH", conflicts_with = "auto")]
auto_trial_plan: Option<PathBuf>,
/// External assistant directory, GGUF file, or cached Hugging Face identifier.
/// A bare GGUF repository ID selects its unique draft sidecar.
#[arg(long, value_name = "PATH_OR_ID")]
draft_model: Option<String>,
/// Maximum speculative tokens proposed before each target verification.
#[arg(long, default_value_t = 3, value_name = "TOKENS")]
speculative_draft_tokens: usize,
/// Disable same-request optimistic speculative lookahead for equivalent A/B runs.
#[arg(long)]
disable_speculative_lookahead: bool,
/// Keep speculative lookahead enabled even when retained work does not cover discards.
#[arg(long)]
disable_speculative_adaptive_lookahead: bool,
/// External assistant placement: `target`, `cpu`, `gpu:N`, `metal:N`, or `cuda:N`.
///
/// `target` reuses the main execution stream. An explicit device creates
/// a distinct draft stream even when it names the main physical device.
#[arg(long, default_value = "target", value_name = "PLACEMENT")]
speculative_draft_device: SpeculativeDraftDevice,
/// Retained external parameter policy from an exact execution plan.
#[arg(skip)]
draft_residency: ResidencyPlan,
/// Independently admitted image/video tower and processor directory.
#[arg(long, value_name = "DIRECTORY")]
vision_companion: Option<PathBuf>,
/// Independently admitted waveform tower and processor directory.
#[arg(long, value_name = "DIRECTORY")]
audio_companion: Option<PathBuf>,
/// Prompt text. Reads the prompt from stdin when omitted and stdin is piped.
#[arg(value_name = "PROMPT")]
prompt: Option<String>,
/// Require target and draft GGUFs from one cached repository commit.
#[arg(long)]
require_same_revision: bool,
/// Maximum generated tokens. Defaults to the checkpoint value, then 256.
#[arg(short = 'n', long, value_name = "TOKENS")]
max_tokens: Option<usize>,
/// Inspect memory for this many model input positions and exit before loading.
/// Includes any positions inserted by a chat template; no tokenization is performed.
#[arg(long, value_name = "POSITIONS")]
estimate_memory_tokens: Option<u64>,
/// Write the request memory forecast as JSON before generation.
#[arg(long, value_name = "PATH")]
memory_report: Option<PathBuf>,
/// Total model-plus-request application budget, distinct from parameter cache budgets.
#[arg(long, value_name = "BYTES")]
memory_budget_bytes: Option<u64>,
/// Extra headroom for uncertainty and other work, in addition to estimated payloads.
#[arg(long, default_value_t = 268_435_456, value_name = "BYTES")]
memory_reserve_bytes: u64,
/// Continue with a warning, or refuse a predicted memory shortfall.
#[arg(long, value_enum, default_value_t = MemoryPolicy::Warn)]
memory_policy: MemoryPolicy,
/// Keep only the K most likely tokens. Defaults to the checkpoint; zero disables it.
#[arg(long, value_name = "K")]
top_k: Option<i32>,
/// Minimum-probability fraction. Defaults to the checkpoint's declared value.
#[arg(long, value_name = "FLOAT")]
min_p: Option<f32>,
/// Use adaptive Mirostat V2 sampling instead of top-k, top-p, and min-p.
/// Supports ordinary constrained chat; unavailable with speculative drafting.
#[arg(long)]
mirostat_v2: bool,
/// Target Mirostat V2 surprise in bits.
#[arg(long, default_value_t = 5.0, value_name = "FLOAT")]
mirostat_tau: f32,
/// Mirostat V2 adaptation rate.
#[arg(long, default_value_t = 0.1, value_name = "FLOAT")]
mirostat_eta: f32,
/// Penalty history length. Defaults to the checkpoint, then 64; -1 means all.
#[arg(long, value_name = "TOKENS")]
repeat_last_n: Option<i32>,
/// Penalty per token occurrence. Defaults to the checkpoint, then 0 (disabled).
#[arg(long, value_name = "FLOAT")]
frequency_penalty: Option<f32>,
/// Penalty applied once per generated token type. Defaults to the checkpoint, then 0 (disabled).
#[arg(long, value_name = "FLOAT")]
presence_penalty: Option<f32>,
/// Maximum tokens per eligible prefill pass. Omit for automatic sizing.
/// Zero disables caller-imposed chunking.
#[arg(long, value_name = "TOKENS")]
prefill_chunk_size: Option<usize>,
/// Dense-stream host lookahead; use zero with a zero host budget.
#[arg(long, default_value_t = 2, value_name = "LAYERS")]
dense_host_lookahead: usize,
/// Maximum queued dense-stream background host materializations.
#[arg(long, default_value_t = 2, value_name = "REQUESTS")]
dense_background_queue: usize,
/// Cache routed experts independently for any supported MoE model.
#[arg(long)]
expert_cache: bool,
/// Optional logical device budget for cached routed experts.
#[arg(long, value_name = "BYTES")]
expert_cache_device_budget_bytes: Option<u64>,
/// Optional logical host budget for cached routed experts; zero uses disk fallback.
#[arg(long, value_name = "BYTES")]
expert_cache_host_budget_bytes: Option<u64>,
/// Hard maximum bytes for one temporary compact expert bank.
#[arg(long, default_value_t = 1_073_741_824, value_name = "BYTES")]
expert_cache_scratch_bytes: u64,
/// Soft compact expert-bank target used to split multi-token prefill routing.
#[arg(long, default_value_t = 1_073_741_824, value_name = "BYTES")]
expert_cache_prefill_bank_bytes: u64,
/// Deterministic expert cache eviction ordering.
#[arg(long, value_enum, default_value_t = ExpertCacheEviction::Lru)]
expert_cache_eviction: ExpertCacheEviction,
/// Evaluate typed questions and evidence from JSON; '-' reads stdin.
#[arg(long, value_name = "PATH", conflicts_with_all = ["prompt", "auto", "auto_feedback", "auto_trial_plan", "raw", "tools", "draft_model", "mirostat_v2", "temperature", "top_p", "top_k", "min_p", "repeat_penalty", "repeat_last_n", "frequency_penalty", "presence_penalty", "max_tokens", "stop_sequences", "thinking", "reasoning_effort", "memory_report", "estimate_memory_tokens", "telemetry_json", "memory_budget_bytes", "memory_policy", "memory_reserve_bytes", "speculative_draft_tokens"])]
decisions: Option<PathBuf>,
#[cfg(feature = "vision")]
#[command(flatten)]
media: media::MediaArgs,
/// Pass the prompt directly instead of applying the model's chat template.
#[arg(long)]
raw: bool,
/// JSON file containing an array of OpenAI-shaped function tools.
#[arg(long, value_name = "PATH")]
tools: Option<PathBuf>,
/// Native tool selection policy used with `--tools`.
#[arg(long, value_enum, default_value_t = CliToolChoice::Auto)]
tool_choice: CliToolChoice,
/// Enable parallel native calls, optionally bounded to this many calls.
#[arg(long, value_name = "CALLS")]
max_parallel_tool_calls: Option<NonZeroUsize>,
/// Additional decoded stop sequence for prepared native-tool generation.
#[arg(long = "stop", value_name = "TEXT")]
stop_sequences: Vec<String>,
/// Control thinking/reasoning in chat templates that support `enable_thinking`.
///
/// `auto` preserves the model's default. Explicit `on` or `off` fails when
/// the model's chat template does not expose a compatible switch.
#[arg(long, value_enum, default_value_t = ThinkingMode::Auto)]
thinking: ThinkingMode,
/// Select a template-defined reasoning effort such as low, medium, high, or xhigh.
#[arg(long, value_name = "EFFORT")]
reasoning_effort: Option<String>,
/// Suppress reasoning content while retaining generated answers and diagnostics.
#[arg(long)]
hide_reasoning: bool,
/// Allow `--thinking on` to fall back to unparsed raw response text.
#[arg(long)]
allow_unparsed_reasoning: bool,
/// Print labeled reasoning content, model resolution, and generation statistics to stderr.
#[arg(short, long)]
verbose: bool,
/// Report load completion immediately and print generation timing statistics to stderr.
#[arg(long)]
timing: bool,
/// Write stable structured execution telemetry to this JSON file.
#[arg(long, value_name = "PATH")]
telemetry_json: Option<PathBuf>,
}
impl Cli {
fn media_companions(&self) -> oi_kit_inference_core::MediaCompanionSources {
let mut sources = oi_kit_inference_core::MediaCompanionSources::default();
if let Some(path) = &self.vision_companion {
sources = sources.with_vision(path);
}
if let Some(path) = &self.audio_companion {
sources = sources.with_audio(path);
}
sources
}
fn generation_overrides(&self) -> GenerationConfigOverrides {
GenerationConfigOverrides {
temperature: self.common.temperature,
top_k: self.top_k,
top_p: self.common.top_p,
min_p: self.min_p,
repetition_penalty: self.common.repeat_penalty,
repeat_last_n: self.repeat_last_n,
frequency_penalty: self.frequency_penalty,
presence_penalty: self.presence_penalty,
max_new_tokens: self.max_tokens,
..GenerationConfigOverrides::default()
}
}
}
const AUTOMATIC_OVERRIDE_ARGUMENTS: &[&str] = &[
"vision_companion",
"audio_companion",
"draft_model",
"allocator_cache_limit_bytes",
"speculative_draft_tokens",
"disable_speculative_lookahead",
"disable_speculative_adaptive_lookahead",
"speculative_draft_device",
"quantize",
"quantization_mode",
"quantization_group_size",
"layerwise_host",
"dense_disk_stream",
"dense_host_lookahead",
"dense_background_queue",
"expert_cache",
"device_layer_window",
"device_budget_bytes",
"host_budget_bytes",
"expert_cache_device_budget_bytes",
"expert_cache_host_budget_bytes",
"expert_cache_scratch_bytes",
"expert_cache_prefill_bank_bytes",
"expert_cache_eviction",
"cached_shards",
"prepared_cache_dir",
"prepared_cache_bytes",
];
#[derive(Debug, Default)]
struct AutomaticCliOverrides {
explicit: HashSet<&'static str>,
}
impl AutomaticCliOverrides {
fn from_matches(matches: &ArgMatches) -> Self {
Self {
explicit: AUTOMATIC_OVERRIDE_ARGUMENTS
.iter()
.copied()
.filter(|id| matches.value_source(id) == Some(ValueSource::CommandLine))
.collect(),
}
}
fn contains(&self, id: &str) -> bool {
self.explicit.contains(id)
}
fn is_empty(&self) -> bool {
self.explicit.is_empty()
}
fn apply_to_plan(
&self,
plan: &ExecutionPlan,
original: &Cli,
draft_model_path: Option<&Path>,
resources: &ModelResourceProfile,
devices: &HardwareBackendProfile,
) -> Result<ExecutionPlan> {
if self.is_empty() {
return Ok(if plan.prepared_checkpoint_cache().is_some() {
plan.clone()
} else {
plan.clone()
.with_prepared_checkpoint_cache(original.common.prepared_cache.policy())
});
}
let mut args = original.clone();
apply_automatic_plan(&mut args, plan)?;
self.restore(&mut args, original);
let embedded_mtp = draft_model_path.is_none()
&& args.speculative_draft_tokens > 0
&& resources
.embedded_draft_capacity
.value()
.is_some_and(|capacity| *capacity > 0);
let mut result = cli_execution_plan(
&args,
plan.device(),
devices,
draft_model_path,
embedded_mtp,
)?;
if !self.contains("speculative_draft_device") && !self.contains("draft_model") {
if let (
DraftingPlan::External { placement, .. },
DraftingPlan::External {
residency,
model,
max_draft_tokens,
lookahead,
adaptive_lookahead,
..
},
) = (plan.drafting(), result.drafting())
{
let drafting = DraftingPlan::External {
placement: placement.clone(),
residency: residency.clone(),
model: model.clone(),
max_draft_tokens: *max_draft_tokens,
lookahead: *lookahead,
adaptive_lookahead: *adaptive_lookahead,
};
result = result.with_drafting(drafting);
}
}
Ok(result)
}
fn restore(&self, args: &mut Cli, original: &Cli) {
if self.contains("prepared_cache_dir") {
args.common.prepared_cache = original.common.prepared_cache.clone();
}
if self.contains("vision_companion") {
args.vision_companion = original.vision_companion.clone();
}
if self.contains("audio_companion") {
args.audio_companion = original.audio_companion.clone();
}
if self.contains("allocator_cache_limit_bytes") {
args.common.allocator_cache_limit_bytes = original.common.allocator_cache_limit_bytes;
}
if self.contains("quantize") {
args.common.quantize = original.common.quantize;
}
if self.contains("quantization_mode") {
args.common.quantization_mode = original.common.quantization_mode;
}
if self.contains("quantization_group_size") {
args.common.quantization_group_size = original.common.quantization_group_size;
}
if self.contains("layerwise_host") || self.contains("dense_disk_stream") {
args.common.layerwise_host = original.common.layerwise_host;
args.common.dense_disk_stream = original.common.dense_disk_stream;
}
if self.contains("dense_host_lookahead") {
args.dense_host_lookahead = original.dense_host_lookahead;
}
if self.contains("dense_background_queue") {
args.dense_background_queue = original.dense_background_queue;
}
if self.contains("device_layer_window") {
args.common.device_layer_window = original.common.device_layer_window;
}
if self.contains("device_budget_bytes") {
args.common.device_budget_bytes = original.common.device_budget_bytes;
}
if self.contains("host_budget_bytes") {
args.common.host_budget_bytes = original.common.host_budget_bytes;
}
if self.contains("expert_cache") {
args.expert_cache = original.expert_cache;
}
if self.contains("expert_cache_device_budget_bytes") {
args.expert_cache_device_budget_bytes = original.expert_cache_device_budget_bytes;
}
if self.contains("expert_cache_host_budget_bytes") {
args.expert_cache_host_budget_bytes = original.expert_cache_host_budget_bytes;
}
if self.contains("expert_cache_scratch_bytes") {
args.expert_cache_scratch_bytes = original.expert_cache_scratch_bytes;
}
if self.contains("expert_cache_prefill_bank_bytes") {
args.expert_cache_prefill_bank_bytes = original.expert_cache_prefill_bank_bytes;
}
if self.contains("expert_cache_eviction") {
args.expert_cache_eviction = original.expert_cache_eviction;
}
if self.contains("cached_shards") {
args.common.cached_shards = original.common.cached_shards;
}
if self.contains("draft_model") {
args.speculative_draft_tokens = original.speculative_draft_tokens;
args.disable_speculative_lookahead = original.disable_speculative_lookahead;
args.disable_speculative_adaptive_lookahead =
original.disable_speculative_adaptive_lookahead;
args.speculative_draft_device = original.speculative_draft_device;
args.draft_residency = original.draft_residency.clone();
} else {
if self.contains("speculative_draft_tokens") {
args.speculative_draft_tokens = original.speculative_draft_tokens;
}
if self.contains("disable_speculative_lookahead") {
args.disable_speculative_lookahead = original.disable_speculative_lookahead;
}
if self.contains("disable_speculative_adaptive_lookahead") {
args.disable_speculative_adaptive_lookahead =
original.disable_speculative_adaptive_lookahead;
}
if self.contains("speculative_draft_device") {
args.speculative_draft_device = original.speculative_draft_device;
}
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum StopReason {
Eos,
StopSequence,
GrammarComplete,
MaxTokens,
Cancelled,
GeneratorExhausted,
}
impl StopReason {
const fn label(self) -> &'static str {
match self {
Self::Eos => "eos",
Self::StopSequence => "stop_sequence",
Self::GrammarComplete => "grammar_complete",
Self::MaxTokens => "max_tokens",
Self::Cancelled => "cancelled",
Self::GeneratorExhausted => "generator_exhausted",
}
}
}
impl From<FinishReason> for StopReason {
fn from(value: FinishReason) -> Self {
match value {
FinishReason::Eos => Self::Eos,
FinishReason::StopSequence => Self::StopSequence,
FinishReason::GrammarComplete => Self::GrammarComplete,
FinishReason::MaxTokens => Self::MaxTokens,
FinishReason::Cancelled => Self::Cancelled,
}
}
}
fn stop_reason(output_ids: &[u32], eos_token_ids: &[u32], max_tokens: usize) -> StopReason {
if output_ids
.last()
.is_some_and(|token| eos_token_ids.contains(token))
{
StopReason::Eos
} else if output_ids.len() >= max_tokens {
StopReason::MaxTokens
} else {
StopReason::GeneratorExhausted
}
}
fn should_report_stop_reason(stop_reason: StopReason, verbose: bool) -> bool {
verbose || stop_reason == StopReason::MaxTokens
}
fn write_timing_report(
stderr: &mut impl Write,
load_elapsed: std::time::Duration,
generation_elapsed: std::time::Duration,
time_to_first_token: Option<std::time::Duration>,
generated_tokens: usize,
total_elapsed: std::time::Duration,
) -> Result<()> {
let token_rate = if generation_elapsed.is_zero() {
0.0
} else {
generated_tokens as f64 / generation_elapsed.as_secs_f64()
};
writeln!(stderr, "load_time: {:.3} s", load_elapsed.as_secs_f64())?;
writeln!(
stderr,
"generation_time: {:.3} s",
generation_elapsed.as_secs_f64()
)?;
match time_to_first_token {
Some(elapsed) => {
writeln!(
stderr,
"time_to_first_token: {:.3} s",
elapsed.as_secs_f64()
)?;
let decode_tokens = generated_tokens.saturating_sub(1);
let decode_elapsed = generation_elapsed.saturating_sub(elapsed);
let decode_token_rate = if decode_elapsed.is_zero() {
0.0
} else {
decode_tokens as f64 / decode_elapsed.as_secs_f64()
};
writeln!(stderr, "decode_token_rate: {decode_token_rate:.2} tokens/s")?;
}
None => writeln!(stderr, "time_to_first_token: n/a")?,
}
writeln!(stderr, "token_rate: {token_rate:.2} tokens/s")?;
writeln!(
stderr,
"total_execution_time: {:.3} s",
total_elapsed.as_secs_f64()
)?;
Ok(())
}
fn write_streamed_token(
decoder: &mut TextDecoder,
stdout: &mut impl Write,
streamed_text: &mut String,
token_id: u32,
) -> Result<()> {
if let Some(text) = decoder.step(token_id)? {
stdout.write_all(text.as_bytes())?;
stdout.flush()?;
streamed_text.push_str(&text);
}
Ok(())
}
fn write_semantic_event(
event: &SemanticEvent,
stdout: &mut impl Write,
stderr: &mut impl Write,
streamed_text: &mut String,
reasoning_stream: &mut ReasoningStream,
reasoning_output: ReasoningOutput,
) -> Result<()> {
let visible = match event {
SemanticEvent::TextDelta(text) => Some(text.clone()),
SemanticEvent::ToolCallStart { index, id, name } => Some(format!(
"\n{{\"tool_call\":{{\"index\":{index},\"id\":{},\"name\":{},\"arguments\":",
serde_json::to_string(id)?,
serde_json::to_string(name)?,
)),
SemanticEvent::ToolArgumentsDelta { json_fragment, .. } => Some(json_fragment.clone()),
SemanticEvent::ToolCallCompleted { .. } => Some("}}\n".into()),
SemanticEvent::ToolCallRejected { error, .. } => {
Some(format!("}}}}\nTool call rejected: {error}\n"))
}
SemanticEvent::ReasoningDelta(text) => {
reasoning_stream.write_delta(stderr, text, reasoning_output)?;
None
}
SemanticEvent::Finished { .. } => {
reasoning_stream.close(stderr, reasoning_output)?;
None
}
};
if let Some(visible) = visible {
reasoning_stream.close(stderr, reasoning_output)?;
if reasoning_output == ReasoningOutput::Verbose {
reasoning_stream.announce_visible(stderr)?;
}
stdout.write_all(visible.as_bytes())?;
stdout.flush()?;
streamed_text.push_str(&visible);
}
Ok(())
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ReasoningOutput {
Hidden,
InteractivePlain,
InteractiveDimmed,
Verbose,
}
impl ReasoningOutput {
fn for_streams(
verbose: bool,
hide_reasoning: bool,
stdout_is_terminal: bool,
stderr_is_terminal: bool,
) -> Self {
if hide_reasoning {
Self::Hidden
} else if verbose {
Self::Verbose
} else if !stdout_is_terminal {
Self::Hidden
} else if stderr_is_terminal {
Self::InteractiveDimmed
} else {
Self::InteractivePlain
}
}
}
#[derive(Default)]
struct ReasoningStream {
open: bool,
ends_with_newline: bool,
visible_announced: bool,
}
impl ReasoningStream {
fn write_delta(
&mut self,
stderr: &mut impl Write,
text: &str,
output: ReasoningOutput,
) -> Result<()> {
if text.is_empty() || output == ReasoningOutput::Hidden {
return Ok(());
}
if !self.open {
match output {
// Some terminals accept SGR faint but render it at normal
// intensity. Pair it with the standard muted foreground so
// interactive reasoning remains visibly secondary there.
ReasoningOutput::InteractiveDimmed => stderr.write_all(b"\x1b[2;90m")?,
ReasoningOutput::Verbose => {
writeln!(stderr, "--- reasoning content (stderr) ---")?;
}
ReasoningOutput::Hidden | ReasoningOutput::InteractivePlain => {}
}
self.open = true;
}
stderr.write_all(text.as_bytes())?;
self.ends_with_newline = text.ends_with('\n');
stderr.flush()?;
Ok(())
}
fn close(&mut self, stderr: &mut impl Write, output: ReasoningOutput) -> Result<()> {
if !self.open {
return Ok(());
}
if !self.ends_with_newline {
writeln!(stderr)?;
}
match output {
ReasoningOutput::InteractiveDimmed => stderr.write_all(b"\x1b[0m")?,
ReasoningOutput::Verbose => {
writeln!(stderr, "--- end reasoning content (stderr) ---")?;
}
ReasoningOutput::Hidden | ReasoningOutput::InteractivePlain => {}
}
stderr.flush()?;
self.open = false;
self.ends_with_newline = false;
Ok(())
}
fn announce_visible(&mut self, stderr: &mut impl Write) -> Result<()> {
if !self.visible_announced {
writeln!(stderr, "--- generated content (stdout) ---")?;
stderr.flush()?;
self.visible_announced = true;
}
Ok(())
}
}
fn use_semantic_generation(
semantic_support: &SemanticSupport,
tool_support: &NativeToolSupport,
tools_requested: bool,
) -> Result<bool> {
if tools_requested {
return match tool_support {
NativeToolSupport::Supported => Ok(true),
NativeToolSupport::Unsupported { rejection } => {
bail!("native tool calling is unavailable: {rejection}")
}
};
}
match semantic_support {
SemanticSupport::Supported => Ok(true),
SemanticSupport::Unsupported { .. } => Ok(false),
}
}
#[cfg(test)]
fn requested_load_quantization(args: &Cli) -> Result<Option<QuantizationRequest>> {
args.common.quantization_request()
}
const AUTO_DEVICE_FALLBACK_BYTES: u64 = 4 << 30;
const AUTO_HOST_FALLBACK_BYTES: u64 = 16 << 30;
const AUTO_EXPERT_SHARE_PERCENT: u64 = 40;
const AUTO_CACHE_SCHEMA_VERSION: u32 = 1;
const AUTO_BENCHMARK_SCHEMA_VERSION: u32 = 1;
const AUTO_BENCHMARK_PROMPT: &str =
"Explain in one concise paragraph why reproducible benchmarks matter.";
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
struct ArtifactFileStamp {
path: String,
bytes: u64,
modified_unix_nanos: Option<u64>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
struct AutoPlanCacheKey {
planner_schema_version: u32,
model_path: PathBuf,
model_architecture: Option<String>,
stored_tensor_bytes: Option<u64>,
tensor_count: Option<usize>,
checkpoint_shards: Option<usize>,
artifact_files: Vec<ArtifactFileStamp>,
operating_system: String,
architecture: String,
memory_semantics: String,
physical_memory_bytes: Option<u64>,
device: DevicePlan,
device_total_memory_bytes: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AutoBenchmarkTrial {
run: usize,
success: bool,
#[serde(skip_serializing_if = "Option::is_none")]
timing: Option<TimingTelemetry>,
#[serde(skip_serializing_if = "Option::is_none")]
peak_bytes: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AutoBenchmarkCandidate {
plan: ExecutionPlan,
trials: Vec<AutoBenchmarkTrial>,
#[serde(skip_serializing_if = "Option::is_none")]
median_token_rate: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
median_time_to_first_token_seconds: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AutoBenchmarkReport {
schema_version: u32,
generated_tokens_per_trial: usize,
runs_per_candidate: usize,
timeout_seconds: u64,
selection_metric: String,
cache_key: AutoPlanCacheKey,
selected: ExecutionPlanReport,
candidates: Vec<AutoBenchmarkCandidate>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AutoPlanCacheEntry {
key: AutoPlanCacheKey,
report: ExecutionPlanReport,
#[serde(skip_serializing_if = "Option::is_none")]
benchmark_token_rate: Option<f64>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct AutoPlanCache {
schema_version: u32,
entries: Vec<AutoPlanCacheEntry>,
}
fn observed_u64(value: &Observed<u64>) -> Option<u64> {
match value {
Observed::Available { value, .. } => Some(*value),
Observed::Unsupported { .. } | Observed::Unavailable { .. } => None,
}
}
fn artifact_file_stamp(root: &Path, path: &Path) -> Result<ArtifactFileStamp> {
let metadata = fs::metadata(path)
.with_context(|| format!("failed to inspect model artifact {}", path.display()))?;
let modified_unix_nanos = metadata
.modified()
.ok()
.and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
.and_then(|duration| u64::try_from(duration.as_nanos()).ok());
Ok(ArtifactFileStamp {
path: path
.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.into_owned(),
bytes: metadata.len(),
modified_unix_nanos,
})
}
fn artifact_file_stamps(model_path: &Path) -> Result<Vec<ArtifactFileStamp>> {
if model_path.is_file() {
return Ok(vec![artifact_file_stamp(model_path, model_path)?]);
}
let mut paths = fs::read_dir(model_path)
.with_context(|| {
format!(
"failed to enumerate model artifact {}",
model_path.display()
)
})?
.map(|entry| entry.map(|entry| entry.path()))
.collect::<std::result::Result<Vec<_>, _>>()?;
paths.retain(|path| {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| {
name == "config.json"
|| name == "model.safetensors.index.json"
|| name.ends_with(".safetensors")
|| name.ends_with(".gguf")
})
});
paths.sort();
paths
.iter()
.map(|path| artifact_file_stamp(model_path, path))
.collect()
}
fn automatic_cache_key(
model_path: &Path,
report: &ExecutionPlanReport,
) -> Result<AutoPlanCacheKey> {
let device_total_memory_bytes = report
.hardware
.backends
.iter()
.find(|backend| &backend.backend == report.plan.device().backend())
.and_then(|backend| {
backend
.devices
.iter()
.find(|device| device.id == report.plan.device().device())
})
.and_then(|device| observed_u64(&device.total_memory_bytes));
Ok(AutoPlanCacheKey {
planner_schema_version: oi_kit_inference_core::AUTOMATIC_SCHEMA_VERSION,
model_path: fs::canonicalize(model_path).unwrap_or_else(|_| model_path.to_path_buf()),
model_architecture: report.resources.architecture.clone(),
stored_tensor_bytes: observed_u64(&report.resources.stored_tensor_bytes),
tensor_count: report.resources.tensor_count,
checkpoint_shards: report.resources.checkpoint_shards,
artifact_files: artifact_file_stamps(model_path)?,
operating_system: report.hardware.operating_system.clone(),
architecture: report.hardware.architecture.clone(),
memory_semantics: format!("{:?}", report.hardware.physical_memory_semantics),
physical_memory_bytes: observed_u64(&report.hardware.physical_memory_bytes),
device: report.plan.device().clone(),
device_total_memory_bytes,
})
}
fn read_auto_plan_cache(path: &Path) -> Result<AutoPlanCache> {
match fs::read(path) {
Ok(bytes) => {
let cache: AutoPlanCache = serde_json::from_slice(&bytes).with_context(|| {
format!("failed to parse automatic plan cache {}", path.display())
})?;
if cache.schema_version != AUTO_CACHE_SCHEMA_VERSION {
return Ok(AutoPlanCache {
schema_version: AUTO_CACHE_SCHEMA_VERSION,
entries: Vec::new(),
});
}
Ok(cache)
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(AutoPlanCache {
schema_version: AUTO_CACHE_SCHEMA_VERSION,
entries: Vec::new(),
}),
Err(error) => Err(error)
.with_context(|| format!("failed to read automatic plan cache {}", path.display())),
}
}
fn cached_automatic_report(
path: &Path,
key: &AutoPlanCacheKey,
) -> Result<Option<ExecutionPlanReport>> {
Ok(read_auto_plan_cache(path)?
.entries
.into_iter()
.find(|entry| entry.key == *key)
.map(|entry| entry.report))
}
fn write_auto_plan_cache(
path: &Path,
key: AutoPlanCacheKey,
report: ExecutionPlanReport,
benchmark_token_rate: Option<f64>,
) -> Result<()> {
let mut cache = read_auto_plan_cache(path)?;
cache.entries.retain(|entry| entry.key != key);
cache.entries.push(AutoPlanCacheEntry {
key,
report,
benchmark_token_rate,
});
if let Some(parent) = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
{
fs::create_dir_all(parent).with_context(|| {
format!(
"failed to create automatic cache directory {}",
parent.display()
)
})?;
}
let temporary = path.with_extension(format!("auto-cache-tmp-{}", std::process::id()));
let json =
serde_json::to_vec_pretty(&cache).context("failed to serialize automatic plan cache")?;
fs::write(&temporary, json).with_context(|| {
format!(
"failed to write temporary automatic plan cache {}",
temporary.display()
)
})?;
fs::rename(&temporary, path)
.with_context(|| format!("failed to publish automatic plan cache {}", path.display()))?;
Ok(())
}
fn automatic_budget(available: Option<u64>, fallback: u64) -> u64 {
available
.map(|bytes| {
bytes.saturating_mul(
100 - u64::from(AutomaticPlannerPolicy::default().memory_headroom_percent),
) / 100
})
.unwrap_or(fallback)
.max(1)
}
fn selected_device_available_memory(
hardware: &HardwareProfile,
device: &DevicePlan,
) -> Option<u64> {
hardware
.backends
.iter()
.find(|backend| &backend.backend == device.backend() && backend.available)
.and_then(|backend| {
backend
.devices
.iter()
.find(|candidate| candidate.id == device.device())
})
.and_then(|device| observed_u64(&device.available_memory_bytes))
}
fn validate_automatic_device(hardware: &HardwareProfile, device: &DevicePlan) -> Result<()> {
let backend = hardware
.backends
.iter()
.find(|backend| &backend.backend == device.backend())
.with_context(|| {
format!(
"automatic planning did not discover the {} backend selected by --device",
device.backend()
)
})?;
if !backend.available {
bail!(
"automatic planning cannot use unavailable {} backend: {}",
device.backend(),
backend.detail.as_deref().unwrap_or("no detail reported")
);
}
if !backend
.devices
.iter()
.any(|candidate| candidate.id == device.device())
{
bail!(
"automatic planning did not discover {} device {}",
device.backend(),
device.device()
);
}
Ok(())
}
fn automatic_model_bytes(resources: &ModelResourceProfile) -> Option<(u64, &'static str)> {
observed_u64(&resources.materialized_parameter_bytes)
.map(|bytes| (bytes, "materialized parameter estimate"))
.or_else(|| {
observed_u64(&resources.stored_tensor_bytes)
.map(|bytes| (bytes, "stored checkpoint tensor bytes"))
})
}
fn cached_plan_resource_admitted(observations: &ExecutionPlanReport, plan: &ExecutionPlan) -> bool {
let available_device = selected_device_available_memory(&observations.hardware, plan.device())
.map(|bytes| automatic_budget(Some(bytes), 1));
let available_host = observed_u64(&observations.hardware.available_memory_bytes)
.map(|bytes| automatic_budget(Some(bytes), 1));
let fits = |required: u64, available: Option<u64>| {
available.is_none_or(|available| required <= available)
};
if matches!(plan.residency(), ResidencyPlan::FullyResident) {
return automatic_model_bytes(&observations.resources)
.is_some_and(|(bytes, _)| fits(bytes, available_device));
}
let (mut device_required, mut host_required) = match plan.residency() {
ResidencyPlan::LayerwiseHost {
device_budget_bytes: Some(device),
host_budget_bytes: Some(host),
..
} => (*device, *host),
ResidencyPlan::DenseDiskStream {
device_budget_bytes,
host_budget_bytes,
..
} => (*device_budget_bytes, *host_budget_bytes),
ResidencyPlan::LayerwiseHost { .. } | ResidencyPlan::FullyResident => return false,
_ => return false,
};
if let Some(expert) = plan.expert_cache() {
let (Some(device), Some(host)) = (expert.device_budget_bytes(), expert.host_budget_bytes())
else {
return false;
};
device_required = device_required.saturating_add(device);
host_required = host_required.saturating_add(host);
}
if observations.hardware.physical_memory_semantics == HardwareMemorySemantics::Unified {
fits(
device_required.saturating_add(host_required),
available_host.or(available_device),
)
} else {
fits(device_required, available_device) && fits(host_required, available_host)
}
}
type TextArtifactInspection = oi_kit_inference_core::ArtifactInspection<
oi_kit_inference_architectures::processor_plan::ArtifactArchitecturePlan,
>;
fn candidate_is_loadable(
factory: &impl BackendInspection,
model_path: &Path,
plan: &ExecutionPlan,
) -> Result<bool> {
let inspection = inspect_execution(factory, model_path, plan, None)?;
Ok(inspection.report().is_loadable())
}
fn base_automatic_candidates(
device: DevicePlan,
device_budget: u64,
host_budget: u64,
) -> [ExecutionPlan; 3] {
let resident = ExecutionPlan::fully_resident(device.clone());
let layerwise = ExecutionPlan::fully_resident(device.clone()).with_residency(
ResidencyPlan::LayerwiseHost {
device_layer_window: 1,
device_budget_bytes: Some(device_budget),
host_budget_bytes: Some(host_budget),
},
);
let disk =
ExecutionPlan::fully_resident(device).with_residency(ResidencyPlan::DenseDiskStream {
device_budget_bytes: device_budget,
host_budget_bytes: host_budget,
host_lookahead: usize::from(host_budget > 0) * 2,
background_queue: usize::from(host_budget > 0) * 2,
});
[resident, layerwise, disk]
}
fn with_expert_cache(mut plan: ExecutionPlan) -> ExecutionPlan {
let split = |bytes: u64, percent: u64| bytes.saturating_mul(percent) / 100;
let (residency, device_budget, host_budget) = match plan.residency().clone() {
ResidencyPlan::FullyResident => (
ResidencyPlan::FullyResident,
AUTO_DEVICE_FALLBACK_BYTES,
AUTO_HOST_FALLBACK_BYTES,
),
ResidencyPlan::LayerwiseHost {
device_layer_window,
device_budget_bytes,
host_budget_bytes,
} => {
let device = device_budget_bytes.unwrap_or(AUTO_DEVICE_FALLBACK_BYTES);
let host = host_budget_bytes.unwrap_or(AUTO_HOST_FALLBACK_BYTES);
(
ResidencyPlan::LayerwiseHost {
device_layer_window,
device_budget_bytes: Some(
split(device, 100 - AUTO_EXPERT_SHARE_PERCENT).max(1),
),
host_budget_bytes: Some(split(host, 100 - AUTO_EXPERT_SHARE_PERCENT).max(1)),
},
device,
host,
)
}
ResidencyPlan::DenseDiskStream {
device_budget_bytes,
host_budget_bytes,
host_lookahead,
background_queue,
} => (
ResidencyPlan::DenseDiskStream {
device_budget_bytes: split(device_budget_bytes, 100 - AUTO_EXPERT_SHARE_PERCENT)
.max(1),
host_budget_bytes: split(host_budget_bytes, 100 - AUTO_EXPERT_SHARE_PERCENT).max(1),
host_lookahead,
background_queue,
},
device_budget_bytes,
host_budget_bytes,
),
_ => return plan,
};
plan = plan.with_residency(residency);
let scratch = (1_u64 << 30).min(device_budget.max(1));
plan.with_expert_cache(Some(ExpertCachePlan::new(
Some(split(device_budget, AUTO_EXPERT_SHARE_PERCENT).max(1)),
Some(split(host_budget, AUTO_EXPERT_SHARE_PERCENT).max(1)),
scratch,
scratch,
CacheEvictionPolicy::LeastRecentlyUsed,
)))
}
#[cfg(test)]
fn choose_automatic_residency(
resident_fits: bool,
layerwise_fits: bool,
resident_supported: bool,
layerwise_supported: bool,
disk_supported: bool,
) -> Option<usize> {
if resident_fits && resident_supported {
Some(0)
} else if layerwise_fits && layerwise_supported {
Some(1)
} else if disk_supported {
Some(2)
} else if layerwise_supported {
Some(1)
} else if resident_supported {
Some(0)
} else {
None
}
}
fn automatic_observations(
factory: &impl BackendInspection,
model_path: &Path,
device: &DevicePlan,
) -> Result<ExecutionPlanReport> {
let hardware = factory.discover_hardware()?;
validate_automatic_device(&hardware, device)?;
let plan = ExecutionPlan::fully_resident(device.clone());
let resources = inspect_execution(factory, model_path, &plan, None)?
.into_report()
.resources;
Ok(ExecutionPlanReport {
schema_version: oi_kit_inference_core::AUTOMATIC_SCHEMA_VERSION,
hardware,
resources,
plan,
explanation: PlanExplanation {
summary: "collected automatic planning inputs".into(),
entries: Vec::new(),
},
})
}
fn read_automatic_feedback(paths: &[PathBuf]) -> Result<Vec<ExecutionTelemetry>> {
let mut telemetry = Vec::new();
for path in paths {
let bytes = fs::read(path)
.with_context(|| format!("failed to read automatic feedback {}", path.display()))?;
let value: serde_json::Value = serde_json::from_slice(&bytes)
.with_context(|| format!("failed to parse automatic feedback {}", path.display()))?;
if value.is_array() {
telemetry.extend(
serde_json::from_value::<Vec<ExecutionTelemetry>>(value).with_context(|| {
format!(
"failed to decode automatic feedback array {}",
path.display()
)
})?,
);
} else {
telemetry.push(
serde_json::from_value::<ExecutionTelemetry>(value).with_context(|| {
format!("failed to decode automatic feedback {}", path.display())
})?,
);
}
}
Ok(telemetry)
}
fn automatic_plan(
factory: &impl AutomaticPlanningBackend<
oi_kit_inference_architectures::processor_plan::ArtifactArchitecturePlan,
>,
model_path: &Path,
device: &DevicePlan,
prior_telemetry: &[ExecutionTelemetry],
) -> Result<ExecutionPlanReport> {
let request = AutomaticPlanRequest::new(model_path, device.clone())
.with_prior_telemetry(prior_telemetry.iter().cloned());
AutomaticPlanner::default()
.plan(factory, &request)
.map_err(Into::into)
}
#[derive(Clone, Copy)]
struct AutomaticPlanInputs<'a> {
model_path: &'a Path,
device: &'a DevicePlan,
devices: &'a HardwareBackendProfile,
args: &'a Cli,
overrides: &'a AutomaticCliOverrides,
draft_model_path: Option<&'a Path>,
prior_telemetry: &'a [ExecutionTelemetry],
}
fn automatic_plan_with_overrides(
factory: &impl AutomaticPlanningBackend<
oi_kit_inference_architectures::processor_plan::ArtifactArchitecturePlan,
Inspection = TextArtifactInspection,
>,
input: AutomaticPlanInputs<'_>,
) -> Result<(ExecutionPlanReport, TextArtifactInspection)> {
let AutomaticPlanInputs {
model_path,
device,
devices,
args,
overrides,
draft_model_path,
prior_telemetry,
} = input;
let request = AutomaticPlanRequest::new(model_path, device.clone())
.with_prior_telemetry(prior_telemetry.iter().cloned());
AutomaticPlanner::default()
.plan_retained_with_overrides(factory, &request, |plan, resources| {
overrides
.apply_to_plan(plan, args, draft_model_path, resources, devices)
.map_err(|error| {
oi_kit_inference_core::AutomaticPlanningError::Invalid(error.to_string())
})
})
.map(|retained| retained.into_parts())
.map_err(Into::into)
}
fn push_unique_plan(
plans: &mut Vec<ExecutionPlan>,
seen: &mut HashSet<Vec<u8>>,
plan: ExecutionPlan,
) {
let encoded = serde_json::to_vec(&plan).expect("execution plans are serializable");
if seen.insert(encoded) {
plans.push(plan);
}
}
fn automatic_benchmark_candidates(
factory: &impl BackendInspection,
model_path: &Path,
heuristic: &ExecutionPlanReport,
) -> Result<Vec<ExecutionPlan>> {
let device_available =
selected_device_available_memory(&heuristic.hardware, heuristic.plan.device());
let host_available = observed_u64(&heuristic.hardware.available_memory_bytes);
let device_budget = automatic_budget(device_available, AUTO_DEVICE_FALLBACK_BYTES);
let host_budget = automatic_budget(host_available, AUTO_HOST_FALLBACK_BYTES);
let model_bytes = automatic_model_bytes(&heuristic.resources).map(|(bytes, _)| bytes);
let resident_fits = model_bytes.is_some_and(|bytes| bytes <= device_budget);
let layerwise_fits = model_bytes.is_some_and(|bytes| {
if heuristic.hardware.physical_memory_semantics == HardwareMemorySemantics::Unified {
bytes <= host_budget.saturating_mul(2)
} else {
bytes <= host_budget
}
});
let embedded = matches!(heuristic.plan.drafting(), DraftingPlan::Embedded { .. });
let mut plans = Vec::new();
let mut seen = HashSet::new();
for (index, plan) in
base_automatic_candidates(heuristic.plan.device().clone(), device_budget, host_budget)
.into_iter()
.enumerate()
{
let mut plan = plan.with_media_companions(heuristic.plan.media_companions().clone());
if let Some(policy) = heuristic.plan.prepared_checkpoint_cache() {
plan = plan.with_prepared_checkpoint_cache(policy.clone());
}
if (index == 0 && !resident_fits) || (index == 1 && !layerwise_fits) {
continue;
}
if !candidate_is_loadable(factory, model_path, &plan)? {
continue;
}
let mut residency_plans = vec![plan.clone()];
if index != 0 {
let expert = with_expert_cache(plan.clone());
if candidate_is_loadable(factory, model_path, &expert)? {
residency_plans.push(expert);
}
}
for variant in residency_plans {
let mut variant = variant.with_drafting(DraftingPlan::Disabled);
push_unique_plan(&mut plans, &mut seen, variant.clone());
if embedded {
variant = variant.with_drafting(heuristic.plan.drafting().clone());
push_unique_plan(&mut plans, &mut seen, variant);
}
}
}
push_unique_plan(&mut plans, &mut seen, heuristic.plan.clone());
Ok(plans)
}
fn temporary_trial_path(label: &str, candidate: usize, run: usize) -> PathBuf {
std::env::temp_dir().join(format!(
"oi-kit-inference-auto-{label}-{}-{candidate}-{run}.json",
std::process::id()
))
}
fn isolated_benchmark_trial(
model_path: &Path,
plan: &ExecutionPlan,
candidate: usize,
run: usize,
tokens: usize,
timeout_seconds: u64,
prompt: &str,
) -> AutoBenchmarkTrial {
let plan_path = temporary_trial_path("plan", candidate, run);
let telemetry_path = temporary_trial_path("telemetry", candidate, run);
let stderr_path = temporary_trial_path("stderr", candidate, run);
let execute = || -> Result<(TimingTelemetry, Option<u64>)> {
let encoded = serde_json::to_vec(plan).context("failed to serialize benchmark plan")?;
fs::write(&plan_path, encoded).with_context(|| {
format!(
"failed to write isolated trial plan {}",
plan_path.display()
)
})?;
let executable = std::env::current_exe()
.context("failed to locate the current executable for isolated benchmarking")?;
let stderr_file = fs::File::create(&stderr_path).with_context(|| {
format!(
"failed to create isolated trial stderr {}",
stderr_path.display()
)
})?;
let mut child = Command::new(executable)
.arg("--model")
.arg(model_path)
.arg("--backend")
.arg(plan.device().backend().as_str())
.arg("--auto-trial-plan")
.arg(&plan_path)
.arg("--telemetry-json")
.arg(&telemetry_path)
.arg("--max-tokens")
.arg(tokens.to_string())
.arg("--raw")
.arg(prompt)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(stderr_file))
.spawn()
.context("failed to launch isolated benchmark process")?;
let started = Instant::now();
let status = loop {
if let Some(status) = child
.try_wait()
.context("failed to poll isolated benchmark process")?
{
break status;
}
if started.elapsed().as_secs() >= timeout_seconds {
child
.kill()
.context("failed to terminate timed-out benchmark process")?;
let _ = child.wait();
bail!("trial process exceeded {timeout_seconds} second timeout");
}
std::thread::sleep(std::time::Duration::from_millis(100));
};
if !status.success() {
let stderr = fs::read_to_string(&stderr_path).unwrap_or_default();
let detail = stderr.chars().take(2_000).collect::<String>();
bail!(
"trial process exited with {}{}{}",
status,
if detail.is_empty() { "" } else { ": " },
detail.trim()
);
}
let bytes = fs::read(&telemetry_path).with_context(|| {
format!(
"isolated trial did not produce telemetry {}",
telemetry_path.display()
)
})?;
let telemetry: ExecutionTelemetry = serde_json::from_slice(&bytes)
.context("failed to parse isolated benchmark telemetry")?;
if telemetry.generated_tokens == 0 {
bail!("isolated benchmark generated no tokens");
}
Ok((
telemetry.timing,
telemetry
.allocator
.and_then(|allocator| allocator.peak_bytes),
))
};
let result = execute();
let _ = fs::remove_file(&plan_path);
let _ = fs::remove_file(&telemetry_path);
let _ = fs::remove_file(&stderr_path);
match result {
Ok((timing, peak_bytes)) => AutoBenchmarkTrial {
run,
success: true,
timing: Some(timing),
peak_bytes,
error: None,
},
Err(error) => AutoBenchmarkTrial {
run,
success: false,
timing: None,
peak_bytes: None,
error: Some(format!("{error:#}")),
},
}
}
fn median(mut values: Vec<f64>) -> Option<f64> {
values.retain(|value| value.is_finite());
if values.is_empty() {
return None;
}
values.sort_by(f64::total_cmp);
let middle = values.len() / 2;
if values.len().is_multiple_of(2) {
Some((values[middle - 1] + values[middle]) / 2.0)
} else {
Some(values[middle])
}
}
fn benchmark_automatic_plans(
factory: &impl BackendInspection,
model_path: &Path,
mut heuristic: ExecutionPlanReport,
tokens: usize,
runs: usize,
timeout_seconds: u64,
prompt: &str,
) -> Result<AutoBenchmarkReport> {
let plans = automatic_benchmark_candidates(factory, model_path, &heuristic)?;
let candidate_count = plans.len();
let mut candidates = Vec::with_capacity(candidate_count);
for (candidate, plan) in plans.into_iter().enumerate() {
eprintln!(
"automatic benchmark: candidate {}/{} ({:?}, {:?})",
candidate + 1,
candidate_count,
plan.residency(),
plan.drafting()
);
let trials = (0..runs)
.map(|run| {
isolated_benchmark_trial(
model_path,
&plan,
candidate,
run,
tokens,
timeout_seconds,
prompt,
)
})
.collect::<Vec<_>>();
let median_token_rate = median(
trials
.iter()
.filter_map(|trial| trial.timing.as_ref().map(|timing| timing.token_rate))
.collect(),
);
let median_time_to_first_token_seconds = median(
trials
.iter()
.filter_map(|trial| {
trial
.timing
.as_ref()
.and_then(|timing| timing.time_to_first_token_seconds)
})
.collect(),
);
candidates.push(AutoBenchmarkCandidate {
plan,
trials,
median_token_rate,
median_time_to_first_token_seconds,
});
}
let selected = candidates
.iter()
.enumerate()
.filter_map(|(index, candidate)| candidate.median_token_rate.map(|rate| (index, rate)))
.max_by(|left, right| left.1.total_cmp(&right.1))
.map(|(index, _)| index)
.context("every isolated automatic benchmark candidate failed")?;
let selected_rate = candidates[selected]
.median_token_rate
.expect("selected benchmark candidate has a rate");
heuristic.plan = candidates[selected].plan.clone();
heuristic.explanation = PlanExplanation {
summary: format!(
"selected isolated benchmark candidate {} at {:.2} tokens/s median",
selected + 1,
selected_rate
),
entries: vec![
PlanExplanationEntry {
level: PlanExplanationLevel::Decision,
code: "isolated_benchmark_selected".into(),
detail: format!(
"selected candidate {} from {} admitted plans using {runs} fresh process run(s) of {tokens} generated tokens",
selected + 1,
candidates.len()
),
},
PlanExplanationEntry {
level: PlanExplanationLevel::Decision,
code: "benchmark_score".into(),
detail: format!("median generation rate was {selected_rate:.2} tokens/s"),
},
],
};
let cache_key = automatic_cache_key(model_path, &heuristic)?;
Ok(AutoBenchmarkReport {
schema_version: AUTO_BENCHMARK_SCHEMA_VERSION,
generated_tokens_per_trial: tokens,
runs_per_candidate: runs,
timeout_seconds,
selection_metric: "median_generation_tokens_per_second".into(),
cache_key,
selected: heuristic,
candidates,
})
}
fn exact_automatic_report(
factory: &impl BackendInspection,
model_path: &Path,
plan: ExecutionPlan,
) -> Result<ExecutionPlanReport> {
if plan.schema_version() != EXECUTION_PLAN_SCHEMA_VERSION {
bail!(
"exact automatic plan schema {} does not match supported schema {}",
plan.schema_version(),
EXECUTION_PLAN_SCHEMA_VERSION
);
}
let hardware = factory.discover_hardware()?;
validate_automatic_device(&hardware, plan.device())?;
let inspection = inspect_execution(factory, model_path, &plan, None)?.into_report();
if !inspection.is_loadable() {
let detail = inspection
.issues
.iter()
.find(|issue| issue.severity == InspectionSeverity::Error)
.map(|issue| issue.detail.as_str())
.unwrap_or("exact automatic plan was not admitted by checkpoint inspection");
bail!("cannot execute exact automatic plan: {detail}");
}
Ok(ExecutionPlanReport {
schema_version: EXECUTION_PLAN_SCHEMA_VERSION,
hardware,
resources: inspection.resources,
plan,
explanation: PlanExplanation {
summary: "executing an exact plan supplied by an isolated benchmark parent".into(),
entries: vec![PlanExplanationEntry {
level: PlanExplanationLevel::Decision,
code: "isolated_trial_exact_plan".into(),
detail: "the child process applied the serialized candidate without replanning"
.into(),
}],
},
})
}
fn apply_automatic_plan(args: &mut Cli, plan: &ExecutionPlan) -> Result<()> {
args.common.prepared_cache =
crate::common::PreparedCacheArgs::from_policy(plan.prepared_checkpoint_cache());
args.vision_companion = plan.media_companions().vision().map(Path::to_path_buf);
args.audio_companion = plan.media_companions().audio().map(Path::to_path_buf);
match plan.weight_transformation() {
WeightTransformationPlan::PreserveCheckpoint => {
args.common.quantize = None;
args.common.quantization_mode = LoadQuantizationMode::Affine;
}
WeightTransformationPlan::Affine { bits, group_size } => {
args.common.quantize = Some(bits);
args.common.quantization_mode = LoadQuantizationMode::Affine;
args.common.quantization_group_size = group_size;
}
WeightTransformationPlan::MxFp4 => {
args.common.quantize = Some(4);
args.common.quantization_mode = LoadQuantizationMode::Mxfp4;
}
_ => bail!("unsupported weight transformation plan"),
}
args.common.cached_shards = plan.max_cached_shards();
args.common.layerwise_host = false;
args.common.dense_disk_stream = false;
match plan.residency() {
ResidencyPlan::FullyResident => {}
ResidencyPlan::LayerwiseHost {
device_layer_window,
device_budget_bytes,
host_budget_bytes,
} => {
args.common.layerwise_host = true;
args.common.device_layer_window = *device_layer_window;
args.common.device_budget_bytes = *device_budget_bytes;
args.common.host_budget_bytes = *host_budget_bytes;
}
ResidencyPlan::DenseDiskStream {
device_budget_bytes,
host_budget_bytes,
host_lookahead,
background_queue,
} => {
args.common.dense_disk_stream = true;
args.common.device_budget_bytes = Some(*device_budget_bytes);
args.common.host_budget_bytes = Some(*host_budget_bytes);
args.dense_host_lookahead = *host_lookahead;
args.dense_background_queue = *background_queue;
}
_ => bail!("unsupported residency plan"),
}
args.expert_cache = plan.expert_cache().is_some();
if let Some(expert) = plan.expert_cache() {
args.expert_cache_device_budget_bytes = expert.device_budget_bytes();
args.expert_cache_host_budget_bytes = expert.host_budget_bytes();
args.expert_cache_scratch_bytes = expert.scratch_bytes();
args.expert_cache_prefill_bank_bytes = expert.prefill_bank_bytes();
args.expert_cache_eviction = expert.eviction_policy().into();
}
match plan.drafting() {
DraftingPlan::Disabled => args.speculative_draft_tokens = 0,
DraftingPlan::Embedded {
max_draft_tokens,
lookahead,
adaptive_lookahead,
} => {
args.speculative_draft_tokens = *max_draft_tokens;
args.disable_speculative_lookahead = !lookahead;
args.disable_speculative_adaptive_lookahead = !adaptive_lookahead;
}
DraftingPlan::External {
residency,
max_draft_tokens,
lookahead,
adaptive_lookahead,
..
} => {
args.draft_residency = residency.clone();
args.speculative_draft_tokens = *max_draft_tokens;
args.disable_speculative_lookahead = !lookahead;
args.disable_speculative_adaptive_lookahead = !adaptive_lookahead;
}
_ => bail!("unsupported speculative drafting plan"),
}
Ok(())
}
fn automatic_report_with_cache(
factory: &(impl BackendInspection
+ AutomaticPlanningBackend<
oi_kit_inference_architectures::processor_plan::ArtifactArchitecturePlan,
Inspection = TextArtifactInspection,
>),
input: AutomaticPlanInputs<'_>,
cache_path: Option<&Path>,
) -> Result<ExecutionPlanReport> {
let AutomaticPlanInputs {
model_path,
device,
devices,
args,
overrides,
draft_model_path,
prior_telemetry,
} = input;
if let Some(path) = cache_path {
let observations = automatic_observations(factory, model_path, device)?;
let key = automatic_cache_key(model_path, &observations)?;
if prior_telemetry.is_empty() {
if let Some(mut cached) = cached_automatic_report(path, &key)? {
if cached.plan.media_companions() == &args.media_companions()
&& (!matches!(cached.plan.drafting(), DraftingPlan::External { .. })
|| args.draft_model.is_some())
&& overrides.apply_to_plan(
&cached.plan,
args,
draft_model_path,
&observations.resources,
devices,
)? == cached.plan
&& cached_plan_resource_admitted(&observations, &cached.plan)
&& candidate_is_loadable(factory, model_path, &cached.plan)?
{
cached.explanation.entries.insert(
0,
PlanExplanationEntry {
level: PlanExplanationLevel::Decision,
code: "automatic_plan_cache_hit".into(),
detail: format!(
"reused a hardware- and artifact-matched plan from {}",
path.display()
),
},
);
return Ok(cached);
}
}
}
let heuristic = automatic_plan_with_overrides(factory, input)?.0;
write_auto_plan_cache(path, key, heuristic.clone(), None)?;
Ok(heuristic)
} else {
automatic_plan_with_overrides(factory, input).map(|(report, _)| report)
}
}
fn apply_automatic_report(
args: &mut Cli,
original: &Cli,
overrides: &AutomaticCliOverrides,
mut report: ExecutionPlanReport,
) -> Result<ExecutionPlanReport> {
apply_automatic_plan(args, &report.plan)?;
overrides.restore(args, original);
validate_args(args)?;
if !overrides.is_empty() {
report.explanation.entries.push(PlanExplanationEntry {
level: PlanExplanationLevel::Decision,
code: "explicit_cli_overrides".into(),
detail: format!(
"applied explicit CLI overrides before candidate validation: {}",
AUTOMATIC_OVERRIDE_ARGUMENTS
.iter()
.copied()
.filter(|id| overrides.contains(id))
.collect::<Vec<_>>()
.join(", ")
),
});
report.explanation.summary = format!(
"{}; explicit CLI overrides applied",
report.explanation.summary
);
}
Ok(report)
}
fn main() -> Result<()> {
let total_started = Instant::now();
let matches = cli_command().get_matches();
#[cfg(feature = "realtime")]
if matches.subcommand_name().is_some() {
return match CliCommand::from_arg_matches(&matches)? {
CliCommand::Audio(args) => audio::run(args, total_started),
};
}
let overrides = AutomaticCliOverrides::from_matches(&matches);
let args = Cli::from_arg_matches(&matches)?;
let trial_plan = args
.auto_trial_plan
.as_deref()
.map(read_trial_plan)
.transpose()?;
match args.backend.unwrap_or_else(CliBackend::default_available) {
#[cfg(feature = "mlx")]
CliBackend::Mlx => {
let factory = oi_kit_inference::backends::MlxBackendFactory::default()
.with_residency_diagnostics(args.verbose, args.verbose);
run_text(&factory, args, overrides, total_started, trial_plan)
}
#[cfg(not(feature = "mlx"))]
CliBackend::Mlx => bail!("this build does not enable the MLX backend"),
#[cfg(feature = "candle")]
CliBackend::Candle => {
let device = match (&trial_plan, args.common.device) {
(Some(plan), None) => plan.device().clone(),
(_, request) => candle_device(request)?,
};
let factory = oi_kit_inference::backends::CandleBackendFactory::for_device(&device)?
.with_residency_diagnostics(args.verbose, args.verbose);
run_text(&factory, args, overrides, total_started, trial_plan)
}
#[cfg(not(feature = "candle"))]
CliBackend::Candle => bail!("this build does not enable the Candle backend"),
}
}
fn read_trial_plan(path: &Path) -> Result<ExecutionPlan> {
let bytes = fs::read(path)
.with_context(|| format!("failed to read exact trial plan {}", path.display()))?;
serde_json::from_slice(&bytes)
.with_context(|| format!("failed to parse exact trial plan {}", path.display()))
}
#[cfg(feature = "candle")]
fn candle_device(request: Option<CliDevice>) -> Result<DevicePlan> {
let device = match request.unwrap_or(CliDevice::Cpu) {
CliDevice::Cpu => "cpu:0".to_owned(),
CliDevice::Gpu(index) if cfg!(all(feature = "candle-metal", target_os = "macos")) => {
format!("metal:{index}")
}
CliDevice::Gpu(index) if cfg!(feature = "candle-cuda") => format!("cuda:{index}"),
CliDevice::Gpu(_) => bail!("Candle GPU execution requires candle-metal or candle-cuda"),
accelerator => accelerator.to_string(),
};
Ok(DevicePlan::new("candle", device)?)
}
fn run_text<F>(
factory: &F,
mut args: Cli,
automatic_overrides: AutomaticCliOverrides,
total_started: Instant,
trial_plan: Option<ExecutionPlan>,
) -> Result<()>
where
F: BackendInspection
+ AutomaticPlanningBackend<
oi_kit_inference_architectures::processor_plan::ArtifactArchitecturePlan,
Inspection = TextArtifactInspection,
> + oi_kit_inference::api::decision::DecisionBackendFactory<
DraftFacts: oi_kit_inference_core::ExecutionPlanDraftAdmission<
oi_kit_inference_architectures::processor_plan::ArtifactArchitecturePlan,
F::Backend,
Inspection = oi_kit_inference_architectures::ExternalDraftPreparation,
>,
>,
<F::Backend as oi_kit_inference::api::TextSessionComposition>::Installed:
oi_kit_inference_core::AutomaticPromptCacheSession<F::Backend>
+ TextInputSession<F::Backend>
+ oi_kit_inference::api::SpeculativeForecastSession<F::Backend, F::Drafter>,
F::Backend: oi_kit_inference::runtime::speculative::SpeculativeBatchBackend<
<F::Backend as oi_kit_inference::api::TextSessionComposition>::Installed,
Drafter = F::Drafter,
> + oi_kit_inference::api::TextSessionComposition<
Model = oi_kit_inference_core::backend::LoadedModelFor<
F::Backend,
oi_kit_inference_architectures::processor_plan::ArtifactArchitecturePlan,
F::SourcePreparation,
>,
>,
{
if args.no_auto {
args.auto = None;
}
if args.decisions.is_some() {
args.speculative_draft_tokens = 0;
}
let original_args = args.clone();
validate_args(&args)?;
let devices = discover_devices(factory)?;
let device = if trial_plan.is_some() && args.common.device.is_none() {
None
} else {
Some(resolve_device(&devices, args.common.device)?)
};
let decision_request = args.decisions.as_deref().map(decisions::read).transpose()?;
let (resolved_model, resolved_draft) = resolve_model_pair(
args.common
.model
.as_deref()
.expect("text command requires --model"),
args.draft_model.as_deref(),
args.common.revision.as_deref(),
)?;
if let Some(draft) = &resolved_draft {
validate_artifact_pair(&resolved_model, draft, args.require_same_revision)?;
}
let model_path = resolved_model.path;
let draft_model_path = resolved_draft.map(|artifact| artifact.path);
if let Some((mut request, assets)) = decision_request {
request.seed = args.common.seed.or(request.seed);
let plan = cli_execution_plan(
&args,
device
.as_ref()
.context("decisions require a selected device")?,
&devices,
None,
false,
)?;
args.common.apply_allocator_cache_limit(factory)?;
let load_started = Instant::now();
let mut decision_started = None;
let mut on_loaded = || {
eprintln!("load_seconds={:.3}", load_started.elapsed().as_secs_f64());
decision_started = Some(Instant::now());
};
let result = oi_kit_inference::api::decision::evaluate_decisions(
factory,
&model_path,
assets.as_deref(),
&request,
&plan,
(args.timing || args.verbose).then_some(&mut on_loaded as &mut dyn FnMut()),
)?;
if let Some(started) = decision_started {
eprintln!("decision_seconds={:.3}", started.elapsed().as_secs_f64());
}
serde_json::to_writer_pretty(io::stdout().lock(), &result)?;
println!();
return Ok(());
}
let automatic_feedback = read_automatic_feedback(&args.auto_feedback)?;
let mut retained_automatic_inspection = None;
let exact_trial_report = trial_plan
.map(|plan| {
if plan.device().backend() != &devices.backend {
bail!(
"exact trial plan targets backend {}, selected backend is {}",
plan.device().backend(),
devices.backend
);
}
if device
.as_ref()
.is_some_and(|device| device != plan.device())
{
bail!(
"exact trial plan device {} does not match --device",
plan.device().device()
);
}
let plan = if automatic_overrides.is_empty() {
if plan.prepared_checkpoint_cache().is_some() {
plan
} else {
plan.with_prepared_checkpoint_cache(args.common.prepared_cache.policy())
}
} else {
let observations = automatic_observations(factory, &model_path, plan.device())?;
automatic_overrides.apply_to_plan(
&plan,
&original_args,
draft_model_path.as_deref(),
&observations.resources,
&devices,
)?
};
exact_automatic_report(factory, &model_path, plan)
})
.transpose()?;
let automatic_report = if let Some(report) = exact_trial_report {
Some(apply_automatic_report(
&mut args,
&original_args,
&automatic_overrides,
report,
)?)
} else {
let device = device.as_ref().context("no execution device selected")?;
let planning_input = AutomaticPlanInputs {
model_path: &model_path,
device,
devices: &devices,
args: &original_args,
overrides: &automatic_overrides,
draft_model_path: draft_model_path.as_deref(),
prior_telemetry: &automatic_feedback,
};
match args.auto {
Some(mode) => match mode {
AutoMode::Benchmark => {
if automatic_overrides
.explicit
.iter()
.any(|id| !matches!(*id, "prepared_cache_dir" | "prepared_cache_bytes"))
{
bail!(
"performance overrides are supported by automatic quick execution and plan reporting, not --auto benchmark"
);
}
let mut heuristic =
automatic_plan(factory, &model_path, device, &automatic_feedback)?;
heuristic.plan = heuristic
.plan
.with_prepared_checkpoint_cache(args.common.prepared_cache.policy());
let benchmark = benchmark_automatic_plans(
factory,
&model_path,
heuristic,
args.auto_benchmark_tokens,
args.auto_benchmark_runs,
args.auto_benchmark_timeout_seconds,
args.prompt.as_deref().unwrap_or(AUTO_BENCHMARK_PROMPT),
)?;
if let Some(path) = &args.auto_cache {
write_auto_plan_cache(
path,
benchmark.cache_key.clone(),
benchmark.selected.clone(),
benchmark.candidates.iter().find_map(|candidate| {
(candidate.plan == benchmark.selected.plan)
.then_some(candidate.median_token_rate)
.flatten()
}),
)?;
}
serde_json::to_writer_pretty(io::stdout().lock(), &benchmark)
.context("failed to serialize automatic benchmark report")?;
println!();
return Ok(());
}
AutoMode::Plan => {
let report = automatic_report_with_cache(
factory,
planning_input,
args.auto_cache.as_deref(),
)?;
let report = apply_automatic_report(
&mut args,
&original_args,
&automatic_overrides,
report,
)?;
serde_json::to_writer_pretty(io::stdout().lock(), &report)
.context("failed to serialize automatic execution plan")?;
println!();
return Ok(());
}
AutoMode::Quick => {
let (report, inspection) =
automatic_plan_with_overrides(factory, planning_input)?;
retained_automatic_inspection = Some(inspection);
if let Some(path) = &args.auto_cache {
let observations = automatic_observations(factory, &model_path, device)?;
let key = automatic_cache_key(&model_path, &observations)?;
write_auto_plan_cache(path, key, report.clone(), None)?;
}
let report = apply_automatic_report(
&mut args,
&original_args,
&automatic_overrides,
report,
)?;
eprintln!("automatic plan: {}", report.explanation.summary);
Some(report)
}
},
None => None,
}
};
validate_args(&args)?;
let hardware_profile = match &automatic_report {
Some(report) => Some(report.hardware.clone()),
None if args.telemetry_json.is_some() => Some(factory.discover_hardware()?),
None => None,
};
let prompt = if args.estimate_memory_tokens.is_some() {
String::new()
} else {
read_prompt(args.prompt.as_deref())?
};
let configured_embedded_mtp = if automatic_report.is_none()
&& draft_model_path.is_none()
&& args.speculative_draft_tokens > 0
{
let inspection = match retained_automatic_inspection.take() {
Some(inspection) => inspection,
None => oi_kit_inference_architectures::configuration::inspect_artifact(&model_path)?,
};
let available = inspection
.architecture_plan()
.prediction_target_projection()?
.is_some();
retained_automatic_inspection = Some(inspection);
available
} else {
false
};
let execution_plan = match automatic_report.as_ref() {
Some(report) => report.plan.clone(),
None => cli_execution_plan(
&args,
device.as_ref().context("no execution device selected")?,
&devices,
draft_model_path.as_deref(),
configured_embedded_mtp,
)?,
};
if let Some(tokens) = args.estimate_memory_tokens {
let report = memory::report(
factory,
&args,
&model_path,
&execution_plan,
tokens,
args.max_tokens.map(|n| n as u64),
)?;
println!("{}", serde_json::to_string_pretty(&report)?);
memory::advise(&args, &report)?;
return Ok(());
}
args.common.apply_allocator_cache_limit(factory)?;
if args.verbose {
eprintln!("--- oi-kit-inference diagnostics (stderr) ---");
eprintln!("model: {}", model_path.display());
eprintln!("device: {}", execution_plan.device().device());
if let Some(bytes) = args.common.allocator_cache_limit_bytes {
eprintln!("allocator_cache_limit: {}", format_bytes(bytes));
}
if let Some(path) = &draft_model_path {
eprintln!("draft_model: {}", path.display());
eprintln!(
"speculative_draft_device: {}",
args.speculative_draft_device
);
}
let mut stderr = io::stderr().lock();
writeln!(stderr, "execution_plan:")?;
serde_json::to_writer_pretty(&mut stderr, &execution_plan)
.context("failed to serialize verbose execution plan")?;
writeln!(stderr)?;
}
if args.verbose || args.telemetry_json.is_some() {
// Capture the complete model-load and generation high-water mark.
factory.reset_allocator_peak()?;
}
let resource_profile = if let Some(report) = &automatic_report {
Some(report.resources.clone())
} else if args.telemetry_json.is_some() {
Some(
inspect_execution(factory, &model_path, &execution_plan, None)?
.into_report()
.resources,
)
} else {
None
};
let load_started = Instant::now();
let planned = match retained_automatic_inspection {
Some(inspection) => {
oi_kit_inference::api::PreparedTextModel::from_artifact(inspection, Default::default())
.map_err(oi_kit_inference::api::PlannedModelLoadError::from)
.and_then(|prepared| {
prepared.select_execution_plan(factory, &execution_plan, Default::default())
})
.and_then(|selected| selected.load())
}
None => LoadedModel::load_execution_plan(
factory,
&model_path,
&execution_plan,
Default::default(),
),
}
.with_context(|| format!("failed to load model from {}", model_path.display()))?;
let drafting_enabled = planned.drafting().is_enabled();
let mut session = planned;
let model = session.model_mut();
if args.prefill_chunk_size.is_some_and(|size| size > 0)
&& (args.verbose || memory::requested(&args))
{
if let Err(reason) = model.prefill_chunking_support() {
eprintln!("prefill uses one complete pass: {reason}");
}
}
let generation_overrides = args.generation_overrides();
let mut resolved_generation = model.resolve_generation_config(generation_overrides)?;
let temperature = resolved_generation.temperature;
let top_k = resolved_generation.top_k;
let top_p = resolved_generation.top_p;
let min_p = resolved_generation.min_p;
let max_tokens = resolved_generation.max_new_tokens.unwrap_or(256);
resolved_generation.max_new_tokens = Some(max_tokens);
if args.mirostat_v2 && temperature == 0.0 {
bail!("--mirostat-v2 requires an effective temperature greater than zero");
}
if args.verbose {
let source = if model.checkpoint_generation_config().is_some() {
"checkpoint plus CLI overrides"
} else {
"oi-kit-inference defaults plus CLI overrides"
};
eprintln!(
"generation_config: do_sample={}, temperature={temperature}, top_k={top_k}, top_p={top_p}, min_p={min_p}, repetition_penalty={}, repeat_last_n={}, frequency_penalty={}, presence_penalty={}, max_tokens={max_tokens} ({source})",
resolved_generation.do_sample,
resolved_generation.repetition_penalty,
resolved_generation.repeat_last_n,
resolved_generation.frequency_penalty,
resolved_generation.presence_penalty,
);
}
model.synchronize()?;
let load_elapsed = load_started.elapsed();
if args.verbose || args.timing {
eprintln!("model loaded in {:.3} s", load_elapsed.as_secs_f64());
}
let tools_requested = args.tools.is_some();
let tools = args
.tools
.as_deref()
.map(read_tools)
.transpose()?
.unwrap_or_default();
let mut media_input = None;
let (prepared_chat, rendered_prompt, add_special_tokens) = if args.raw {
(None, prompt, true)
} else {
let request = ChatTemplateRequest {
messages: vec![serde_json::json!({
"role": "user",
"content": prompt.clone(),
})],
tools,
tool_choice: if tools_requested {
args.tool_choice.into()
} else {
ToolChoice::None
},
parallel_tool_calls: match args.max_parallel_tool_calls {
Some(max_calls) => ParallelToolCallPolicy::Enabled {
max_calls: Some(max_calls),
},
None => ParallelToolCallPolicy::Disabled,
},
enable_thinking: args.thinking.enabled(),
reasoning_effort: args.reasoning_effort.clone(),
allow_unparsed_reasoning: args.allow_unparsed_reasoning,
add_generation_prompt: true,
..ChatTemplateRequest::default()
};
#[cfg(feature = "vision")]
let media_chat = args.media.prepare(model, &request, &prompt)?;
#[cfg(not(feature = "vision"))]
let media_chat: Option<oi_kit_inference::api::PreparedChatRequest<_>> = None;
let prepared = if let Some(prepared) = media_chat {
let (chat, payload) = prepared.into_parts();
media_input = Some(payload);
Ok(chat)
} else {
model.prepare_chat(request)
};
match prepared {
Ok(prepared) => {
let semantic = use_semantic_generation(
prepared.semantic_support(),
prepared.native_tool_support(),
tools_requested,
)?;
let rendered_prompt = prepared.rendered_prompt().to_owned();
if semantic {
if args.verbose {
let label = if tools_requested {
"native_tool_profile"
} else {
"semantic_profile"
};
eprintln!(
"{label}: {}",
prepared.format_profile_identity().unwrap_or("unregistered")
);
}
(Some(prepared), rendered_prompt, false)
} else {
if args.verbose {
eprintln!(
"semantic_profile: unavailable ({}); using templated text fallback",
prepared
.native_tool_support()
.rejection()
.map(ToString::to_string)
.unwrap_or_else(|| "unknown reason".into())
);
}
(Some(prepared), rendered_prompt, false)
}
}
Err(TextModelError::MissingChatTemplate) if !tools_requested => (None, prompt, true),
Err(error) => return Err(error.into()),
}
};
let (prompt_token_ids, prompt_positions) = if let Some(payload) = &media_input {
(
Vec::new(),
usize::try_from(payload.count().model_positions)?,
)
} else {
let ids = model.encode(&rendered_prompt, add_special_tokens)?;
let positions = ids.len();
(ids, positions)
};
if prompt_positions == 0 {
bail!("the prompt produced no input tokens");
}
let settings = PreparedChatGenerationSettings {
prefill: prefill_chunk_policy(args.prefill_chunk_size, args.memory_reserve_bytes),
overrides: GenerationConfigOverrides {
max_new_tokens: Some(max_tokens),
..generation_overrides
},
seed: args.common.seed.unwrap_or(0),
strategy: if args.mirostat_v2 {
oi_kit_inference::api::TextSamplingStrategy::MirostatV2 {
tau: args.mirostat_tau,
eta: args.mirostat_eta,
}
} else {
oi_kit_inference::api::TextSamplingStrategy::Standard
},
..Default::default()
};
let eos_token_ids = model.eos_token_ids().to_vec();
let mut output_ids = Vec::with_capacity(max_tokens);
let generation_started = Instant::now();
let mut time_to_first_token = None;
let mut speculative_stats: Option<SpeculativeStats> = None;
let mut decoder = model.text_decoder(true);
let mut streamed_text = String::new();
let mut reasoning_stream = ReasoningStream::default();
let stdout = io::stdout();
let stderr = io::stderr();
let reasoning_output = ReasoningOutput::for_streams(
args.verbose,
args.hide_reasoning,
stdout.is_terminal(),
stderr.is_terminal(),
);
let mut stdout = stdout.lock();
if args.verbose && prepared_chat.is_none() {
eprintln!("--- generated content (stdout) ---");
}
let mut stderr = stderr.lock();
let mut prepared_finish_reason = None;
if let Some(prepared) = &prepared_chat {
let semantic = matches!(prepared.semantic_support(), SemanticSupport::Supported);
let mut semantic_error = None;
let cancellation = GenerationCancellationToken::new();
let cancel_on_error = cancellation.clone();
let request = GenerationRequest {
control_handle: None,
input: match media_input.take() {
Some(payload) => payload.into_input(model, prepared)?,
None => PreparedChatInput::rendered_prompt(prepared),
},
output_mode: if semantic {
oi_kit_inference::api::OutputMode::Semantic
} else {
oi_kit_inference::api::OutputMode::Text
},
settings,
caller_stop_sequences: &args.stop_sequences,
cancellation,
on_event: |event| {
if semantic_error.is_none() {
semantic_error = write_semantic_event(
&event,
&mut stdout,
&mut stderr,
&mut streamed_text,
&mut reasoning_stream,
reasoning_output,
)
.err();
if semantic_error.is_some() {
cancel_on_error.cancel();
}
}
},
};
if memory::requested(&args) {
match session
.forecast_generation(&request, &memory::loaded_options(&args))
.map_err(anyhow::Error::from)
.and_then(|forecast| memory::finish_report(&args, forecast))
{
Ok(report) => memory::advise(&args, &report)?,
Err(error) => {
eprintln!("memory forecast unavailable: {error}; generation continues")
}
}
}
let output = session.generate(request)?;
output_ids = output.token_ids().to_vec();
time_to_first_token = output.timing().time_to_first_token();
speculative_stats = output.stats().drafting.clone();
prepared_finish_reason = Some(output.finish_reason());
if let Some(error) = semantic_error {
return Err(error);
}
} else if drafting_enabled {
bail!(
"speculative generation requires a prepared template prompt; raw prompts use ordinary generation"
);
} else {
if memory::requested(&args) {
match model
.forecast_token_ids(&prompt_token_ids, settings, &memory::loaded_options(&args))
.map_err(anyhow::Error::from)
.and_then(|forecast| memory::finish_report(&args, forecast))
{
Ok(report) => memory::advise(&args, &report)?,
Err(error) => {
eprintln!("memory forecast unavailable: {error}; generation continues")
}
}
}
let config = TextGenerationConfig::new(resolved_generation)
.with_seed(args.common.seed.unwrap_or(0))
.with_prefill_chunk_policy(settings.prefill);
let config = if args.mirostat_v2 {
config.with_mirostat_v2(args.mirostat_tau, args.mirostat_eta)?
} else {
config
};
let generator = model.generate_tokens(prompt_token_ids.clone(), config)?;
for token in generator {
let token_id = token?.token_id()?;
if time_to_first_token.is_none() {
time_to_first_token = Some(generation_started.elapsed());
}
output_ids.push(token_id);
if eos_token_ids.contains(&token_id) {
break;
}
write_streamed_token(&mut decoder, &mut stdout, &mut streamed_text, token_id)?;
}
}
let model = session.model_mut();
reasoning_stream.close(&mut stderr, reasoning_output)?;
drop(stderr);
let generation_elapsed = generation_started.elapsed();
let stop_reason = prepared_finish_reason
.map(StopReason::from)
.unwrap_or_else(|| stop_reason(&output_ids, &eos_token_ids, max_tokens));
if prepared_chat.is_none() && stop_reason == StopReason::Eos {
output_ids.pop();
}
if prepared_chat.is_none() {
let output = model.decode(&output_ids, true)?;
let remaining = output.strip_prefix(&streamed_text).with_context(|| {
"incremental tokenizer output did not match the final decoded response"
})?;
stdout.write_all(remaining.as_bytes())?;
if !output.ends_with('\n') {
writeln!(stdout)?;
}
} else if !streamed_text.ends_with('\n') {
writeln!(stdout)?;
}
stdout.flush()?;
if args.verbose {
eprintln!("--- oi-kit-inference diagnostics (stderr) ---");
}
if tools_requested || should_report_stop_reason(stop_reason, args.verbose) {
eprintln!("stop_reason: {}", stop_reason.label());
}
let allocator_telemetry = if args.verbose || args.telemetry_json.is_some() {
model.synchronize()?;
let mut telemetry = factory.allocator_observation()?.map_or_else(
oi_kit_inference_core::AllocatorTelemetry::default,
|observation| observation.telemetry,
);
telemetry.process_rss_bytes = oi_kit_inference_core::host_memory::process_rss_bytes();
Some(telemetry)
} else {
None
};
let total_elapsed = total_started.elapsed();
let (residency, expert_cache) = if args.verbose || args.telemetry_json.is_some() {
(
model.residency_telemetry()?,
model.expert_cache_telemetry()?,
)
} else {
(None, None)
};
if args.verbose {
eprintln!(
"model_family: {}, effective_model_type: {}, prompt_tokens: {}, generated_tokens: {}",
model.model_family().canonical_name(),
model.effective_model_type(),
prompt_positions,
output_ids.len(),
);
write_timing_report(
&mut io::stderr().lock(),
load_elapsed,
generation_elapsed,
time_to_first_token,
output_ids.len(),
total_elapsed,
)?;
if let Some(stats) = &speculative_stats {
eprintln!(
"speculative_execution_topology: {}",
stats.execution_topology()
);
eprintln!(
"speculative_rounds: {}, speculative_draft_tokens: {}, speculative_accepted_tokens: {}, speculative_accept_rate: {:.3}, speculative_optimistic_blocks: {}, speculative_optimistic_bonus_tokens: {}, speculative_optimistic_bonus_matches: {}, speculative_optimistic_bonus_mismatches: {}, speculative_consumed_optimistic_tokens: {}, speculative_reused_optimistic_blocks: {}, speculative_reused_optimistic_tokens: {}, speculative_discarded_optimistic_blocks: {}, speculative_discarded_optimistic_tokens: {}, speculative_adaptive_lookahead_disabled: {}, speculative_cross_request_draft_opportunities: {}",
stats.rounds(),
stats.draft_tokens(),
stats.accepted_tokens(),
stats.accept_rate(),
stats.optimistic_draft_blocks(),
stats.optimistic_target_bonus_tokens(),
stats.optimistic_bonus_matches(),
stats.optimistic_bonus_mismatches(),
stats.consumed_optimistic_tokens(),
stats.reused_optimistic_blocks(),
stats.reused_optimistic_tokens(),
stats.discarded_optimistic_blocks(),
stats.discarded_optimistic_tokens(),
stats.adaptive_lookahead_disabled(),
stats.cross_request_draft_opportunities(),
);
eprintln!(
"speculative_optimistic_draft_time: {:.3} s, speculative_verification_in_flight_time: {:.3} s",
stats.optimistic_draft_time().as_secs_f64(),
stats.verification_in_flight_time().as_secs_f64(),
);
eprintln!("speculative_accept_lens: {:?}", stats.accept_lens());
}
if let Some(allocator) = &allocator_telemetry {
for (label, bytes) in [
("allocator_peak_memory", allocator.peak_bytes),
("allocator_active_memory", allocator.active_bytes),
("allocator_cache_memory", allocator.cache_bytes),
("device_allocated_memory", allocator.device_allocated_bytes),
("process_rss", allocator.process_rss_bytes),
] {
if let Some(bytes) = bytes {
eprintln!("{label}: {}", format_bytes(bytes));
}
}
}
if let Some(report) = &residency {
eprintln!(
"residency_current_host_device: {} / {} bytes",
report.current_host_bytes, report.current_device_bytes
);
eprintln!(
"residency_peak_host_device: {} / {} bytes",
report.peak_host_bytes, report.peak_device_bytes
);
for transfer in &report.transfers {
if transfer.count > 0 {
eprintln!(
"residency_{}: {} transfers, {} bytes",
transfer.direction, transfer.count, transfer.bytes
);
}
}
}
if let Some(report) = &expert_cache {
eprintln!(
"expert_cache_owned: {} experts, {} bytes",
report.owned_experts, report.owned_bytes
);
eprintln!(
"expert_cache_current_host_device: {} / {} experts, {} / {} bytes",
report.host_resident_experts,
report.device_resident_experts,
report.host_resident_bytes,
report.device_resident_bytes
);
}
if eos_token_ids.is_empty() {
eprintln!("warning: the model config contains no EOS token id");
} else {
match stop_reason {
StopReason::MaxTokens => {
eprintln!("warning: generation reached --max-tokens before EOS");
}
StopReason::GeneratorExhausted => {
eprintln!("warning: the token generator ended before EOS");
}
StopReason::Eos
| StopReason::StopSequence
| StopReason::GrammarComplete
| StopReason::Cancelled => {}
}
}
} else if args.timing {
model.synchronize()?;
write_timing_report(
&mut io::stderr().lock(),
load_elapsed,
generation_elapsed,
time_to_first_token,
output_ids.len(),
total_elapsed,
)?;
}
if let Some(path) = &args.telemetry_json {
let plan = execution_plan.clone();
let plan_explanation = automatic_report.as_ref().map_or_else(
|| PlanExplanation {
summary: "recorded the concrete execution settings supplied to the CLI".into(),
entries: vec![PlanExplanationEntry {
level: PlanExplanationLevel::Decision,
code: "explicit_cli_configuration".into(),
detail: "this run records explicit/default CLI settings; no automatic candidate selection was performed"
.into(),
}],
},
|report| report.explanation.clone(),
);
let telemetry = ExecutionTelemetry {
schema_version: oi_kit_inference_core::AUTOMATIC_SCHEMA_VERSION,
effective_model_type: model.effective_model_type().into(),
plan: Some(plan),
plan_explanation: Some(plan_explanation),
hardware: hardware_profile,
resources: resource_profile,
prompt_tokens: prompt_positions,
generated_tokens: output_ids.len(),
stop_reason: stop_reason.label().into(),
timing: TimingTelemetry::new(
load_elapsed,
generation_elapsed,
time_to_first_token,
output_ids.len(),
total_elapsed,
),
allocator: allocator_telemetry,
residency,
expert_cache,
speculative: speculative_stats
.as_ref()
.map(speculative_decoding_telemetry),
};
let json = serde_json::to_vec_pretty(&telemetry)
.context("failed to serialize execution telemetry")?;
std::fs::write(path, json)
.with_context(|| format!("failed to write telemetry to {}", path.display()))?;
}
Ok(())
}
fn discover_devices(factory: &impl BackendHardware) -> Result<HardwareBackendProfile> {
let backend = factory.backend_id();
let profile = factory
.discover_hardware()?
.backends
.into_iter()
.find(|profile| profile.backend == backend)
.with_context(|| format!("device discovery did not report backend {backend}"))?;
if !profile.available {
bail!(
"backend {} is unavailable: {}",
profile.backend,
profile.detail.as_deref().unwrap_or("no detail reported")
);
}
Ok(profile)
}
fn resolve_device(
profile: &HardwareBackendProfile,
request: Option<CliDevice>,
) -> Result<DevicePlan> {
let cpu = || {
profile
.devices
.iter()
.filter(|device| device.kind == HardwareDeviceKind::Cpu)
.min_by_key(|device| (device.index, &device.id))
};
let selected = match request {
Some(CliDevice::Cpu) => cpu(),
Some(
request @ (CliDevice::Gpu(index) | CliDevice::Metal(index) | CliDevice::Cuda(index)),
) => {
let family = match request {
CliDevice::Metal(_) => Some("metal"),
CliDevice::Cuda(_) => Some("cuda"),
_ => None,
};
let mut matches = profile.devices.iter().filter(|device| {
device.kind == HardwareDeviceKind::Gpu
&& device.index == index
&& family.is_none_or(|family| device.family.eq_ignore_ascii_case(family))
});
let selected = matches.next();
if matches.next().is_some() {
bail!(
"backend {} reported multiple GPUs at index {index}",
profile.backend
);
}
selected
}
None => profile
.devices
.iter()
.filter(|device| device.kind == HardwareDeviceKind::Gpu)
.min_by_key(|device| (device.index, &device.id))
.or_else(cpu),
}
.with_context(|| match request {
Some(device) => format!(
"backend {} did not discover device {device}",
profile.backend
),
None => format!(
"backend {} reported no CPU or GPU for default selection",
profile.backend
),
})?;
Ok(DevicePlan::new(profile.backend.as_str(), &selected.id)?)
}
fn resolve_draft_device(profile: &HardwareBackendProfile, device: CliDevice) -> Result<DevicePlan> {
#[cfg(feature = "candle")]
if profile.backend.as_str() == "candle" {
return candle_device(Some(device));
}
resolve_device(profile, Some(device))
}
fn cli_execution_plan(
args: &Cli,
device: &DevicePlan,
devices: &HardwareBackendProfile,
draft_model: Option<&Path>,
embedded_mtp: bool,
) -> Result<ExecutionPlan> {
let residency = if args.common.dense_disk_stream {
let defaults = DenseDiskStreamLoadOptions::default();
ResidencyPlan::DenseDiskStream {
device_budget_bytes: args
.common
.device_budget_bytes
.unwrap_or(defaults.device_budget_bytes()),
host_budget_bytes: args
.common
.host_budget_bytes
.unwrap_or(defaults.host_budget_bytes()),
host_lookahead: args.dense_host_lookahead,
background_queue: args.dense_background_queue,
}
} else if args.common.layerwise_host {
ResidencyPlan::LayerwiseHost {
device_layer_window: args.common.device_layer_window,
device_budget_bytes: args.common.device_budget_bytes,
host_budget_bytes: args.common.host_budget_bytes,
}
} else {
ResidencyPlan::FullyResident
};
let drafting = if let Some(path) = draft_model {
let placement = match args.speculative_draft_device {
SpeculativeDraftDevice::Target => DraftPlacementPlan::Target,
SpeculativeDraftDevice::Device(device) => DraftPlacementPlan::Device {
device: resolve_draft_device(devices, device)?,
},
};
DraftingPlan::External {
residency: args.draft_residency.clone(),
model: path.display().to_string(),
placement,
max_draft_tokens: args.speculative_draft_tokens,
lookahead: !args.disable_speculative_lookahead,
adaptive_lookahead: !args.disable_speculative_adaptive_lookahead,
}
} else if embedded_mtp {
DraftingPlan::Embedded {
max_draft_tokens: args.speculative_draft_tokens,
lookahead: !args.disable_speculative_lookahead,
adaptive_lookahead: !args.disable_speculative_adaptive_lookahead,
}
} else {
DraftingPlan::Disabled
};
let transformation = args.common.weight_transformation()?;
let expert_cache = args.expert_cache.then_some(ExpertCachePlan::new(
args.expert_cache_device_budget_bytes,
args.expert_cache_host_budget_bytes,
args.expert_cache_scratch_bytes,
args.expert_cache_prefill_bank_bytes,
args.expert_cache_eviction.into(),
));
let plan = ExecutionPlan::fully_resident(device.clone())
.with_topology(
oi_kit_inference_core::topology::ParallelTopology::new(1, 1, 1, 1)
.expect("the singleton topology is valid"),
)
.with_residency(residency)
.with_media_companions(args.media_companions())
.with_weight_transformation(transformation)
.with_max_cached_shards(args.common.cached_shards)
.with_expert_cache(expert_cache)
.with_drafting(drafting)
.with_required_device_capabilities(DeviceCapabilities::new(true, false, false))
.with_required_session_capabilities(SessionCapabilities::default());
Ok(plan.with_prepared_checkpoint_cache(args.common.prepared_cache.policy()))
}
fn format_bytes(bytes: u64) -> String {
format!("{} ({bytes} bytes)", format_memory_size(bytes))
}
fn format_memory_size(bytes: u64) -> String {
const KIB: f64 = 1024.0;
const MIB: f64 = KIB * 1024.0;
const GIB: f64 = MIB * 1024.0;
let bytes_float = bytes as f64;
let (value, unit) = if bytes_float >= GIB {
(bytes_float / GIB, "GiB")
} else if bytes_float >= MIB {
(bytes_float / MIB, "MiB")
} else if bytes_float >= KIB {
(bytes_float / KIB, "KiB")
} else {
(bytes_float, "B")
};
format!("{value:.2} {unit}")
}
fn validate_args(args: &Cli) -> Result<()> {
#[cfg(feature = "vision")]
args.media.validate(args.auto)?;
if args.estimate_memory_tokens.is_some()
&& matches!(args.auto, Some(AutoMode::Plan | AutoMode::Benchmark))
{
bail!(
"--estimate-memory-tokens supports --auto quick or --no-auto; benchmarking would load models"
);
}
if args.estimate_memory_tokens == Some(0) {
bail!("--estimate-memory-tokens must be greater than zero");
}
if args.max_tokens == Some(0) {
bail!("--max-tokens must be greater than zero");
}
if args.auto_benchmark_tokens == 0 {
bail!("--auto-benchmark-tokens must be greater than zero");
}
if args.auto_benchmark_runs == 0 {
bail!("--auto-benchmark-runs must be greater than zero");
}
if args.auto_benchmark_timeout_seconds == 0 {
bail!("--auto-benchmark-timeout-seconds must be greater than zero");
}
if args.draft_model.is_some() && args.speculative_draft_tokens == 0 {
bail!("--speculative-draft-tokens must be greater than zero when --draft-model is used");
}
if args.raw && args.draft_model.is_some() {
bail!("--draft-model requires prepared-chat generation and cannot be used with --raw");
}
if args.speculative_draft_device != SpeculativeDraftDevice::Target && args.draft_model.is_none()
{
bail!(
"--speculative-draft-device {} requires an external --draft-model",
args.speculative_draft_device,
);
}
if args
.common
.temperature
.is_some_and(|value| !value.is_finite() || value < 0.0)
{
bail!("--temperature must be a finite, non-negative number");
}
if args.top_k.is_some_and(|value| value < 0) {
bail!("--top-k must be non-negative");
}
if args
.common
.top_p
.is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value))
{
bail!("--top-p must be between zero and one");
}
if args
.min_p
.is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value))
{
bail!("--min-p must be between zero and one");
}
if args.mirostat_v2 && args.common.temperature == Some(0.0) {
bail!("--mirostat-v2 requires --temperature greater than zero");
}
if !args.mirostat_tau.is_finite() || args.mirostat_tau <= 0.0 {
bail!("--mirostat-tau must be a finite number greater than zero");
}
if !args.mirostat_eta.is_finite() || args.mirostat_eta <= 0.0 {
bail!("--mirostat-eta must be a finite number greater than zero");
}
if args
.common
.repeat_penalty
.is_some_and(|value| !value.is_finite() || value <= 0.0)
{
bail!("--repeat-penalty must be a finite number greater than zero");
}
if args.repeat_last_n.is_some_and(|value| value < -1) {
bail!("--repeat-last-n must be -1 or greater");
}
if args
.frequency_penalty
.is_some_and(|value| !value.is_finite())
|| args
.presence_penalty
.is_some_and(|value| !value.is_finite())
{
bail!("frequency and presence penalties must be finite numbers");
}
args.common.validate()?;
if args.expert_cache_scratch_bytes == 0 {
bail!("--expert-cache-scratch-bytes must be greater than zero");
}
if args.expert_cache_prefill_bank_bytes == 0 {
bail!("--expert-cache-prefill-bank-bytes must be greater than zero");
}
if args.expert_cache_prefill_bank_bytes > args.expert_cache_scratch_bytes {
bail!("--expert-cache-prefill-bank-bytes cannot exceed --expert-cache-scratch-bytes");
}
if args.raw && args.thinking != ThinkingMode::Auto {
bail!(
"--thinking on/off cannot be used with --raw because raw prompts bypass the chat template"
);
}
if args.raw && args.reasoning_effort.is_some() {
bail!(
"--reasoning-effort cannot be used with --raw because raw prompts bypass the chat template"
);
}
if args.allow_unparsed_reasoning && args.thinking != ThinkingMode::On {
bail!("--allow-unparsed-reasoning requires --thinking on");
}
if args.raw && args.tools.is_some() {
bail!(
"--tools cannot be used with --raw because raw prompts bypass native tool preparation"
);
}
if args.tools.is_none() && args.tool_choice != CliToolChoice::Auto {
bail!("--tool-choice requires --tools");
}
if args.tools.is_none() && args.max_parallel_tool_calls.is_some() {
bail!("--max-parallel-tool-calls requires --tools");
}
if args.tools.is_none() && !args.stop_sequences.is_empty() {
bail!("--stop requires --tools");
}
Ok(())
}
fn read_prompt(argument: Option<&str>) -> Result<String> {
if let Some(prompt) = argument {
return Ok(prompt.to_owned());
}
if io::stdin().is_terminal() {
bail!("provide PROMPT as an argument or pipe it on stdin");
}
let mut prompt = String::new();
io::stdin()
.read_to_string(&mut prompt)
.context("failed to read the prompt from stdin")?;
if prompt.is_empty() {
bail!("stdin contained no prompt");
}
Ok(prompt)
}
fn read_tools(path: &Path) -> Result<Vec<serde_json::Value>> {
let file = std::fs::File::open(path)
.with_context(|| format!("failed to open tool definitions {}", path.display()))?;
let tools: serde_json::Value = serde_json::from_reader(file)
.with_context(|| format!("failed to parse tool definitions {}", path.display()))?;
tools
.as_array()
.cloned()
.with_context(|| format!("tool definitions {} must be a JSON array", path.display()))
}
fn resolve_model(
spec: &str,
requested_revision: Option<&str>,
gguf_role: CachedGgufRole,
) -> Result<ResolvedModel> {
let path = Path::new(spec);
if path.exists() {
return Ok(ResolvedModel {
// Keep the logical filename: Hugging Face snapshot files are
// symlinks to extensionless blobs, while format dispatch uses the
// user-visible extension.
path: std::path::absolute(path)
.with_context(|| format!("failed to resolve model path {}", path.display()))?,
repository: None,
commit_hash: None,
});
}
let (repo_id, quantization) = split_hf_model_spec(spec)?;
let cache_dir = resolve_cache_dir();
let cache = scan_repo(&cache_dir, RepoType::Model, repo_id)
.context("failed to scan the Hugging Face cache")?;
let repo = cache.repo.as_ref().with_context(|| {
format!(
"{repo_id:?} is not an existing path or a model in the local Hugging Face cache at {}",
cache.cache_dir.display()
)
})?;
match quantization {
Some(quantization) => {
let path = select_cached_gguf_from_revisions(
&repo.revisions,
requested_revision,
quantization,
gguf_role,
)
.with_context(|| {
format!(
"could not select GGUF quantization {quantization:?} for Hugging Face model {repo_id:?}"
)
})?;
let commit_hash = repo
.revisions
.iter()
.find(|revision| revision.files.iter().any(|file| file.snapshot_path == path))
.map(|revision| revision.commit_hash.clone())
.with_context(|| {
format!(
"selected cached artifact {} has no owning revision",
path.display()
)
})?;
Ok(ResolvedModel {
path,
repository: Some(repo_id.to_owned()),
commit_hash: Some(commit_hash),
})
}
None => {
let revision =
select_revision(&repo.revisions, requested_revision).with_context(|| {
format!("could not select a cached revision for Hugging Face model {repo_id:?}")
})?;
let path = if gguf_role == CachedGgufRole::SpeculativeDraft
&& !revision.files.iter().any(|file| {
file.snapshot_path
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extension.eq_ignore_ascii_case("safetensors"))
}) {
select_unique_cached_gguf(revision, gguf_role)?
.unwrap_or_else(|| revision.snapshot_path.clone())
} else {
revision.snapshot_path.clone()
};
Ok(ResolvedModel {
path,
repository: Some(repo_id.to_owned()),
commit_hash: Some(revision.commit_hash.clone()),
})
}
}
}
fn resolve_model_pair(
target_spec: &str,
draft_spec: Option<&str>,
requested_revision: Option<&str>,
) -> Result<(ResolvedModel, Option<ResolvedModel>)> {
let Some(draft_spec) = draft_spec else {
return Ok((
resolve_model(target_spec, requested_revision, CachedGgufRole::Target)?,
None,
));
};
if requested_revision.is_none() {
if let Some(pair) = resolve_common_cached_gguf_pair(target_spec, draft_spec)? {
return Ok((pair.0, Some(pair.1)));
}
}
Ok((
resolve_model(target_spec, requested_revision, CachedGgufRole::Target)?,
Some(resolve_model(
draft_spec,
requested_revision,
CachedGgufRole::SpeculativeDraft,
)?),
))
}
fn resolve_common_cached_gguf_pair(
target_spec: &str,
draft_spec: &str,
) -> Result<Option<(ResolvedModel, ResolvedModel)>> {
if Path::new(target_spec).exists() || Path::new(draft_spec).exists() {
return Ok(None);
}
let (target_repo, Some(target_quantization)) = split_hf_model_spec(target_spec)? else {
return Ok(None);
};
let (draft_repo, Some(draft_quantization)) = split_hf_model_spec(draft_spec)? else {
return Ok(None);
};
if target_repo != draft_repo {
return Ok(None);
}
let cache_dir = resolve_cache_dir();
let cache = scan_repo(cache_dir, RepoType::Model, target_repo)
.context("failed to scan the Hugging Face cache")?;
let Some(repo) = cache.repo.as_ref() else {
return Ok(None);
};
let Some((revision, target_path, draft_path)) = select_cached_gguf_pair_from_revisions(
&repo.revisions,
target_quantization,
draft_quantization,
) else {
return Ok(None);
};
let repository = Some(target_repo.to_owned());
let commit_hash = Some(revision.commit_hash.clone());
Ok(Some((
ResolvedModel {
path: target_path,
repository: repository.clone(),
commit_hash: commit_hash.clone(),
},
ResolvedModel {
path: draft_path,
repository,
commit_hash,
},
)))
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct ResolvedModel {
path: PathBuf,
repository: Option<String>,
commit_hash: Option<String>,
}
fn validate_artifact_pair(
target: &ResolvedModel,
draft: &ResolvedModel,
require_same_revision: bool,
) -> Result<()> {
let same_repository = target.repository.is_some() && target.repository == draft.repository;
let mixed_commits = target.commit_hash.is_some()
&& draft.commit_hash.is_some()
&& target.commit_hash != draft.commit_hash;
let mixed_revisions = same_repository && mixed_commits;
if mixed_revisions && require_same_revision {
bail!(
"target artifact {} resolves to cached commit {}, but draft artifact {} resolves to commit {}; --require-same-revision forbids mixing revisions from repository {:?}",
target.path.display(),
target.commit_hash.as_deref().unwrap_or("unknown"),
draft.path.display(),
draft.commit_hash.as_deref().unwrap_or("unknown"),
target.repository.as_deref().unwrap_or("unknown"),
);
}
Ok(())
}
fn split_hf_model_spec(spec: &str) -> Result<(&str, Option<&str>)> {
let Some((repo_id, quantization)) = spec.rsplit_once(':') else {
return Ok((spec, None));
};
if repo_id.is_empty() {
bail!("Hugging Face model identifier before ':' must not be empty");
}
if quantization.is_empty() {
bail!("GGUF quantization selector after ':' must not be empty");
}
Ok((repo_id, Some(quantization)))
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum QuantizationMatch {
Exact,
UnslothAlias,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CachedGgufRole {
Target,
SpeculativeDraft,
}
fn select_cached_gguf(
revision: &CachedRevision,
quantization: &str,
role: CachedGgufRole,
) -> Result<PathBuf> {
let files = revision
.files
.iter()
.map(|file| file.snapshot_path.as_path())
.collect::<Vec<_>>();
select_cached_gguf_path(&files, quantization, role)
}
fn select_unique_cached_gguf(
revision: &CachedRevision,
role: CachedGgufRole,
) -> Result<Option<PathBuf>> {
let mut candidates = revision
.files
.iter()
.filter_map(|file| {
let path = file.snapshot_path.as_path();
if !path
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extension.eq_ignore_ascii_case("gguf"))
{
return None;
}
let stem = path.file_stem()?.to_str()?;
let (stem, first_shard) = strip_gguf_shard_suffix(stem);
(first_shard && gguf_role_matches(stem, role)).then_some(path.to_owned())
})
.collect::<Vec<_>>();
candidates.sort_unstable();
candidates.dedup();
match candidates.as_slice() {
[] => Ok(None),
[path] => Ok(Some(path.clone())),
_ => bail!(
"cached repository contains multiple draft GGUF files: {}; append :QUANT to --draft-model",
format_cached_paths(&candidates.iter().map(PathBuf::as_path).collect::<Vec<_>>())
),
}
}
fn select_cached_gguf_from_revisions(
revisions: &[CachedRevision],
requested_revision: Option<&str>,
quantization: &str,
role: CachedGgufRole,
) -> Result<PathBuf> {
let preferred = select_revision(revisions, requested_revision)?;
if requested_revision.is_some() {
return select_cached_gguf(preferred, quantization, role);
}
if let Ok(path) = select_cached_gguf(preferred, quantization, role) {
return Ok(path);
}
// Individual downloads can leave files from one repository
// in separate commit snapshots. Search all cached snapshots when `main`
// does not contain the requested quantization, while treating repeated
// pointers to the same content-addressed blob as one candidate.
let mut seen_blobs = HashSet::new();
let files = revisions
.iter()
.flat_map(|revision| &revision.files)
.filter(|file| seen_blobs.insert(&file.blob_path))
.map(|file| file.snapshot_path.as_path())
.collect::<Vec<_>>();
select_cached_gguf_path(&files, quantization, role)
}
fn select_cached_gguf_pair_from_revisions<'a>(
revisions: &'a [CachedRevision],
target_quantization: &str,
draft_quantization: &str,
) -> Option<(&'a CachedRevision, PathBuf, PathBuf)> {
let mut ordered = revisions.iter().collect::<Vec<_>>();
ordered.sort_unstable_by(|left, right| {
let left_is_main = left.refs.iter().any(|name| name == "main");
let right_is_main = right.refs.iter().any(|name| name == "main");
right_is_main
.cmp(&left_is_main)
.then_with(|| right.last_modified.cmp(&left.last_modified))
});
ordered.into_iter().find_map(|revision| {
let target =
select_cached_gguf(revision, target_quantization, CachedGgufRole::Target).ok()?;
let draft = select_cached_gguf(
revision,
draft_quantization,
CachedGgufRole::SpeculativeDraft,
)
.ok()?;
Some((revision, target, draft))
})
}
fn select_cached_gguf_path(
files: &[&Path],
quantization: &str,
role: CachedGgufRole,
) -> Result<PathBuf> {
let selector = quantization.to_ascii_uppercase();
let unsloth_alias = (!selector.starts_with("UD-")).then(|| format!("UD-{selector}"));
let mut gguf_files = Vec::new();
let mut candidates = Vec::new();
for &path in files {
if !path
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extension.eq_ignore_ascii_case("gguf"))
{
continue;
}
gguf_files.push(path);
let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
continue;
};
let (stem, first_shard) = strip_gguf_shard_suffix(stem);
if !first_shard || !gguf_role_matches(stem, role) {
continue;
}
let stem = stem.to_ascii_uppercase();
let matched = if quantization_suffix_matches(&stem, &selector) {
if unsloth_alias
.as_deref()
.is_some_and(|alias| quantization_suffix_matches(&stem, alias))
{
QuantizationMatch::UnslothAlias
} else {
QuantizationMatch::Exact
}
} else {
continue;
};
candidates.push((path, matched));
}
if candidates
.iter()
.any(|(_, matched)| *matched == QuantizationMatch::Exact)
{
candidates.retain(|(_, matched)| *matched == QuantizationMatch::Exact);
}
candidates.sort_unstable_by_key(|(path, _)| *path);
match candidates.as_slice() {
[(path, _)] => Ok((*path).to_owned()),
[] => {
let available = format_cached_paths(&gguf_files);
if available.is_empty() {
bail!("the selected cached revision contains no GGUF files");
}
bail!(
"no cached GGUF filename matches quantization {quantization:?}; available GGUF files: {available}"
)
}
_ => {
let paths = candidates.iter().map(|(path, _)| *path).collect::<Vec<_>>();
bail!(
"quantization {quantization:?} matches multiple cached GGUF files: {}",
format_cached_paths(&paths)
)
}
}
}
fn gguf_role_matches(stem: &str, role: CachedGgufRole) -> bool {
let stem = stem.to_ascii_lowercase();
let mtp_sidecar = stem.starts_with("mtp-")
|| stem == "dflash"
|| stem.starts_with("dflash-")
|| stem.starts_with("dflash_");
match role {
CachedGgufRole::Target => !mtp_sidecar && !stem.starts_with("mmproj-"),
CachedGgufRole::SpeculativeDraft => mtp_sidecar,
}
}
fn quantization_suffix_matches(stem: &str, selector: &str) -> bool {
let Some(prefix) = stem.strip_suffix(selector) else {
return false;
};
prefix.is_empty()
|| prefix
.chars()
.next_back()
.is_some_and(|separator| matches!(separator, '-' | '.' | '_'))
}
fn strip_gguf_shard_suffix(stem: &str) -> (&str, bool) {
let Some((prefix, count)) = stem.rsplit_once("-of-") else {
return (stem, true);
};
let Some((base, number)) = prefix.rsplit_once('-') else {
return (stem, true);
};
let canonical_number = number.len() == 5 && number.bytes().all(|byte| byte.is_ascii_digit());
let canonical_count = count.len() == 5 && count.bytes().all(|byte| byte.is_ascii_digit());
if canonical_number && canonical_count {
(base, number == "00001")
} else {
(stem, true)
}
}
fn format_cached_paths(paths: &[&Path]) -> String {
let mut paths = paths
.iter()
.map(|path| path.display().to_string())
.collect::<Vec<_>>();
paths.sort_unstable();
paths.join(", ")
}
fn select_revision<'a>(
revisions: &'a [CachedRevision],
requested: Option<&str>,
) -> Result<&'a CachedRevision> {
if let Some(requested) = requested {
return revisions
.iter()
.find(|revision| {
revision.commit_hash == requested
|| revision.refs.iter().any(|name| name == requested)
})
.with_context(|| format!("revision {requested:?} is not present in the cache"));
}
revisions
.iter()
.find(|revision| revision.refs.iter().any(|name| name == "main"))
.or_else(|| {
revisions
.iter()
.max_by_key(|revision| revision.last_modified)
})
.context("the cached repository contains no snapshots")
}
fn prefill_chunk_policy(
size: Option<usize>,
reserve_bytes: u64,
) -> oi_kit_inference::api::PrefillChunkPolicy {
use oi_kit_inference::api::PrefillChunkPolicy;
match size {
None => PrefillChunkPolicy::AutomaticWithReserve { reserve_bytes },
Some(size) => std::num::NonZeroUsize::new(size)
.map_or(PrefillChunkPolicy::Unchunked, PrefillChunkPolicy::Bounded),
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "realtime")]
#[test]
fn root_cli_keeps_text_options_and_separates_realtime_options() {
let matches = super::cli_command()
.try_get_matches_from([
"oi-kit-inference",
"--model",
"test-model",
"--quantize",
"8",
"hello",
])
.unwrap();
assert!(matches.subcommand().is_none());
let text = super::Cli::from_arg_matches(&matches).unwrap();
assert_eq!(text.common.model.as_deref(), Some("test-model"));
assert_eq!(text.common.quantize, Some(8));
let controls = [
"--model",
"test-model",
"--revision",
"pinned",
"--device",
"cpu",
"--allocator-cache-limit-bytes",
"0",
"--quantize",
"8",
"--quantization-group-size",
"32",
"--cached-shards",
"7",
"--device-layer-window",
"2",
"--seed",
"17",
"--temperature",
"0.7",
"--top-p",
"0.9",
"--repeat-penalty",
"1.2",
];
let text_matches = super::cli_command()
.try_get_matches_from(["oi-kit-inference"].into_iter().chain(controls))
.unwrap();
let audio_matches = super::cli_command()
.try_get_matches_from(
["oi-kit-inference", "audio", "realtime"]
.into_iter()
.chain(controls),
)
.unwrap();
let text_common = super::common::CommonOptions::from_arg_matches(&text_matches).unwrap();
let audio_common = super::common::CommonOptions::from_arg_matches(
audio_matches
.subcommand_matches("audio")
.unwrap()
.subcommand_matches("realtime")
.unwrap(),
)
.unwrap();
assert_eq!(text_common, audio_common);
assert_eq!(
text_common.weight_transformation().unwrap(),
audio_common.weight_transformation().unwrap()
);
let audio = super::cli_command()
.try_get_matches_from([
"oi-kit-inference",
"audio",
"realtime",
"--list-audio-devices",
])
.unwrap();
assert_eq!(
audio.subcommand_matches("audio").unwrap().subcommand_name(),
Some("realtime")
);
assert!(<super::CliCommand as clap::FromArgMatches>::from_arg_matches(&audio).is_ok());
let audio = super::cli_command()
.try_get_matches_from([
"oi-kit-inference",
"audio",
"realtime",
"--config",
"voicechat.json",
"--input",
"input.wav",
"--offline",
"--no-playback",
"--quantize",
"8",
])
.unwrap();
assert_eq!(
audio.subcommand_matches("audio").unwrap().subcommand_name(),
Some("realtime")
);
assert!(super::cli_command()
.try_get_matches_from(["oi-kit-inference", "audio", "realtime", "--offline"])
.is_err());
assert!(super::cli_command()
.try_get_matches_from([
"oi-kit-inference",
"audio",
"realtime",
"--config",
"voicechat.json",
"--layerwise-host",
])
.is_err());
assert!(super::cli_command()
.try_get_matches_from([
"oi-kit-inference",
"audio",
"realtime",
"--config",
"voicechat.json",
"--layerwise-host",
"--backbone-device-bytes",
"1048576",
"--backbone-host-bytes",
"1048576",
"--speech-device-bytes",
"1048576",
"--speech-host-bytes",
"1048576",
"--quantize",
"8",
])
.is_ok());
assert!(super::cli_command()
.try_get_matches_from(["oi-kit-inference", "hello"])
.is_err());
}
use std::{
path::{Path, PathBuf},
time::{Duration, SystemTime},
};
use clap::{CommandFactory, FromArgMatches, Parser};
use hf_cache_reader::{scan_repo, CachedFile, CachedRevision, RepoType};
use super::{
apply_automatic_plan, artifact_file_stamps, base_automatic_candidates,
cached_automatic_report, choose_automatic_residency, cli_execution_plan, format_bytes,
median, requested_load_quantization, select_cached_gguf_from_revisions,
select_cached_gguf_pair_from_revisions, select_cached_gguf_path, select_revision,
select_unique_cached_gguf, should_report_stop_reason, split_hf_model_spec, stop_reason,
use_semantic_generation, validate_args, validate_artifact_pair, write_auto_plan_cache,
write_semantic_event, write_timing_report, AutoMode, AutoPlanCacheKey,
AutomaticCliOverrides, CachedGgufRole, Cli, CliDevice, CliToolChoice, DraftingPlan,
ExecutionPlan, ExecutionPlanReport, ModelResourceProfile, NativeToolSupport, Observed,
PlanExplanation, QuantizationRequest, ReasoningOutput, ReasoningStream, ResidencyPlan,
ResolvedModel, SemanticEvent, SemanticSupport, SpeculativeDraftDevice, StopReason,
WeightTransformationPlan,
};
fn cpu_plan() -> super::DevicePlan {
super::DevicePlan::new("mlx", "cpu:0").unwrap()
}
fn test_devices() -> super::HardwareBackendProfile {
super::HardwareBackendProfile {
backend: cpu_plan().backend().clone(),
available: true,
detail: None,
devices: vec![oi_kit_inference_core::HardwareDeviceProfile {
id: "cpu:0".into(),
family: "test-host".into(),
kind: super::HardwareDeviceKind::Cpu,
index: 0,
total_memory_bytes: Observed::exact(1, "fixture"),
available_memory_bytes: Observed::exact(1, "fixture"),
}],
}
}
fn scanned_revision() -> CachedRevision {
let directory = tempfile::tempdir().unwrap();
let snapshot = directory
.path()
.join("models--test--repo/snapshots/template");
std::fs::create_dir_all(&snapshot).unwrap();
std::fs::write(snapshot.join("placeholder"), []).unwrap();
scan_repo(directory.path(), RepoType::Model, "test/repo")
.unwrap()
.repo
.unwrap()
.revisions
.pop()
.unwrap()
}
fn revision(hash: &str, refs: &[&str], modified: u64) -> CachedRevision {
let mut revision = scanned_revision();
revision.commit_hash = hash.to_owned();
revision.snapshot_path = hash.into();
revision.files.clear();
revision.size_on_disk = 0;
revision.refs = refs.iter().map(|value| (*value).to_owned()).collect();
revision.last_modified = SystemTime::UNIX_EPOCH + Duration::from_secs(modified);
revision
}
#[test]
fn parses_auto_modes_without_requiring_a_prompt() {
let default =
Cli::try_parse_from(["oi-kit-inference", "--model", "model-id", "prompt"]).unwrap();
assert_eq!(default.auto, Some(AutoMode::Quick));
let plan =
Cli::try_parse_from(["oi-kit-inference", "--model", "model-id", "--auto", "plan"])
.unwrap();
assert_eq!(plan.auto, Some(AutoMode::Plan));
let quick = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--auto",
"quick",
"prompt",
])
.unwrap();
assert_eq!(quick.auto, Some(AutoMode::Quick));
let benchmark = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--auto",
"benchmark",
"--auto-cache",
"plans.json",
"--auto-feedback",
"previous.json",
"--auto-benchmark-runs",
"3",
])
.unwrap();
assert_eq!(benchmark.auto, Some(AutoMode::Benchmark));
assert_eq!(benchmark.auto_benchmark_runs, 3);
assert_eq!(benchmark.auto_benchmark_tokens, 32);
assert_eq!(benchmark.auto_benchmark_timeout_seconds, 300);
assert_eq!(benchmark.auto_feedback, [PathBuf::from("previous.json")]);
let disabled = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--no-auto",
"prompt",
])
.unwrap();
assert!(disabled.no_auto);
}
#[test]
fn benchmark_statistics_use_the_median() {
assert_eq!(median(vec![]), None);
assert_eq!(median(vec![9.0, 1.0, 5.0]), Some(5.0));
assert_eq!(median(vec![8.0, 2.0, 4.0, 6.0]), Some(5.0));
assert_eq!(median(vec![f64::NAN, 7.0]), Some(7.0));
}
#[test]
fn artifact_stamp_changes_invalidate_cache_identity() {
let directory = tempfile::tempdir().unwrap();
let weights = directory.path().join("model.safetensors");
std::fs::write(&weights, b"first").unwrap();
let first = artifact_file_stamps(directory.path()).unwrap();
std::fs::write(&weights, b"second-longer").unwrap();
let second = artifact_file_stamps(directory.path()).unwrap();
assert_ne!(first, second);
}
#[test]
fn plan_cache_round_trips_matching_entries() {
let directory = tempfile::tempdir().unwrap();
let cache_path = directory.path().join("plans.json");
let model_path = directory.path().join("model.gguf");
std::fs::write(&model_path, b"fixture").unwrap();
let device = cpu_plan();
let hardware = super::HardwareProfile::observe_host(
Observed::unavailable("fixture"),
Observed::unavailable("fixture"),
super::HardwareMemorySemantics::Unified,
vec![test_devices()],
);
let resources = ModelResourceProfile {
schema_version: oi_kit_inference_core::AUTOMATIC_SCHEMA_VERSION,
path: model_path.clone(),
artifact_format: oi_kit_inference_core::ArtifactFormat::Gguf,
model_family: None,
architecture: Some("fixture".into()),
tensor_count: Some(1),
checkpoint_shards: Some(1),
embedded_draft_layers: Observed::unsupported("fixture"),
embedded_draft_capacity: Observed::unsupported("fixture"),
stored_tensor_bytes: Observed::exact(7, "fixture"),
largest_stored_tensor_bytes: Observed::exact(7, "fixture"),
materialized_parameter_bytes: Observed::unavailable("fixture"),
pinned_parameter_bytes: Observed::unavailable("fixture"),
largest_execution_group_bytes: Observed::unavailable("fixture"),
largest_adjacent_execution_groups_bytes: Observed::unavailable("fixture"),
expert_parameter_bytes: Observed::unavailable("fixture"),
selected_rank: Observed::unavailable("fixture"),
};
let report = ExecutionPlanReport {
schema_version: oi_kit_inference_core::AUTOMATIC_SCHEMA_VERSION,
hardware,
resources,
plan: ExecutionPlan::fully_resident(device.clone()),
explanation: PlanExplanation {
summary: "fixture".into(),
entries: Vec::new(),
},
};
let key = AutoPlanCacheKey {
planner_schema_version: oi_kit_inference_core::AUTOMATIC_SCHEMA_VERSION,
model_path,
model_architecture: Some("fixture".into()),
stored_tensor_bytes: Some(7),
tensor_count: Some(1),
checkpoint_shards: Some(1),
artifact_files: artifact_file_stamps(directory.path()).unwrap(),
operating_system: "fixture".into(),
architecture: "fixture".into(),
memory_semantics: "fixture".into(),
physical_memory_bytes: Some(1024),
device,
device_total_memory_bytes: Some(1024),
};
write_auto_plan_cache(&cache_path, key.clone(), report.clone(), Some(12.5)).unwrap();
assert_eq!(
cached_automatic_report(&cache_path, &key).unwrap(),
Some(report)
);
let mut miss = key;
miss.stored_tensor_bytes = Some(8);
assert!(cached_automatic_report(&cache_path, &miss)
.unwrap()
.is_none());
}
#[test]
fn automatic_override_merge_covers_drafting_transformation_and_residency() {
let mut resources = ModelResourceProfile::unmeasured(
"model".into(),
oi_kit_inference_core::ArtifactFormat::SafeTensors,
);
resources.embedded_draft_layers = Observed::exact(1, "fixture");
resources.embedded_draft_capacity = Observed::exact(1, "fixture");
let base =
ExecutionPlan::fully_resident(cpu_plan()).with_drafting(DraftingPlan::Embedded {
max_draft_tokens: 1,
lookahead: true,
adaptive_lookahead: true,
});
let cases: &[&[&str]] = &[
&["--speculative-draft-tokens", "0"],
&[
"--speculative-draft-tokens",
"3",
"--disable-speculative-lookahead",
"--disable-speculative-adaptive-lookahead",
],
&[
"--quantize",
"4",
"--quantization-mode",
"mxfp4",
"--cached-shards",
"7",
],
&[
"--draft-model",
"assistant",
"--speculative-draft-tokens",
"2",
"--speculative-draft-device",
"cpu",
],
&[
"--dense-disk-stream",
"--device-budget-bytes",
"16777216",
"--host-budget-bytes",
"33554432",
"--dense-host-lookahead",
"3",
"--dense-background-queue",
"4",
"--expert-cache",
"--expert-cache-device-budget-bytes",
"4194304",
"--expert-cache-host-budget-bytes",
"8388608",
"--expert-cache-scratch-bytes",
"1048576",
"--expert-cache-prefill-bank-bytes",
"524288",
"--expert-cache-eviction",
"lfu",
"--allocator-cache-limit-bytes",
"0",
],
&[
"--layerwise-host",
"--device-layer-window",
"2",
"--device-budget-bytes",
"16777216",
"--host-budget-bytes",
"33554432",
],
];
for (index, flags) in cases.iter().enumerate() {
let matches = Cli::command()
.try_get_matches_from(
["oi-kit-inference", "--model", "model-id", "--device", "cpu"]
.into_iter()
.chain(flags.iter().copied()),
)
.unwrap();
let original = Cli::from_arg_matches(&matches).unwrap();
validate_args(&original).unwrap();
let overrides = AutomaticCliOverrides::from_matches(&matches);
let draft = original.draft_model.as_deref().map(Path::new);
let plan = overrides
.apply_to_plan(&base, &original, draft, &resources, &test_devices())
.unwrap();
assert_eq!(
overrides
.apply_to_plan(&plan, &original, draft, &resources, &test_devices())
.unwrap(),
plan,
"overrides must be idempotent"
);
match index {
0 => assert_eq!(plan.drafting(), &DraftingPlan::Disabled),
1 => assert!(matches!(
plan.drafting(),
DraftingPlan::Embedded {
max_draft_tokens: 3,
lookahead: false,
adaptive_lookahead: false
}
)),
2 => {
assert_eq!(
plan.weight_transformation(),
WeightTransformationPlan::MxFp4
);
assert_eq!(plan.max_cached_shards(), 7);
}
3 => assert!(matches!(
plan.drafting(),
DraftingPlan::External {
max_draft_tokens: 2,
placement: super::DraftPlacementPlan::Device { .. },
..
}
)),
4 => {
assert!(matches!(
plan.residency(),
ResidencyPlan::DenseDiskStream {
device_budget_bytes: 16777216,
host_budget_bytes: 33554432,
host_lookahead: 3,
background_queue: 4
}
));
let expert = plan.expert_cache().unwrap();
assert_eq!(expert.device_budget_bytes(), Some(4194304));
assert_eq!(expert.host_budget_bytes(), Some(8388608));
assert_eq!(expert.scratch_bytes(), 1048576);
assert_eq!(expert.prefill_bank_bytes(), 524288);
assert_eq!(
expert.eviction_policy(),
super::CacheEvictionPolicy::LeastFrequentlyUsed
);
}
5 => assert!(matches!(
plan.residency(),
ResidencyPlan::LayerwiseHost {
device_layer_window: 2,
device_budget_bytes: Some(16777216),
host_budget_bytes: Some(33554432)
}
)),
_ => unreachable!(),
}
let mut applied = original.clone();
apply_automatic_plan(&mut applied, &plan).unwrap();
overrides.restore(&mut applied, &original);
validate_args(&applied).unwrap();
assert_eq!(
cli_execution_plan(
&applied,
&cpu_plan(),
&test_devices(),
draft,
draft.is_none() && applied.speculative_draft_tokens > 0
)
.unwrap(),
plan
);
}
}
#[test]
fn independent_media_companions_survive_plan_overrides_and_replay() {
let original = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"text-model",
"--no-auto",
"--vision-companion",
"vision-source",
"--audio-companion",
"audio-source",
])
.unwrap();
let selected =
cli_execution_plan(&original, &cpu_plan(), &test_devices(), None, false).unwrap();
assert_eq!(
selected.media_companions().vision(),
Some(Path::new("vision-source"))
);
assert_eq!(
selected.media_companions().audio(),
Some(Path::new("audio-source"))
);
let json = serde_json::to_vec(&selected).unwrap();
let selected: ExecutionPlan = serde_json::from_slice(&json).unwrap();
let mut replay =
Cli::try_parse_from(["oi-kit-inference", "--model", "text-model", "--no-auto"])
.unwrap();
apply_automatic_plan(&mut replay, &selected).unwrap();
assert_eq!(
cli_execution_plan(&replay, &cpu_plan(), &test_devices(), None, false).unwrap(),
selected
);
let resources = ModelResourceProfile::unmeasured(
"text-model".into(),
oi_kit_inference_core::ArtifactFormat::SafeTensors,
);
for (flag, replacement, expected_vision, expected_audio) in [
(
"--audio-companion",
"replacement-audio",
"vision-source",
"replacement-audio",
),
(
"--vision-companion",
"replacement-vision",
"replacement-vision",
"audio-source",
),
] {
let matches = Cli::command()
.try_get_matches_from([
"oi-kit-inference",
"--model",
"text-model",
flag,
replacement,
])
.unwrap();
let args = Cli::from_arg_matches(&matches).unwrap();
let plan = AutomaticCliOverrides::from_matches(&matches)
.apply_to_plan(&selected, &args, None, &resources, &test_devices())
.unwrap();
assert_eq!(
plan.media_companions().vision(),
Some(Path::new(expected_vision))
);
assert_eq!(
plan.media_companions().audio(),
Some(Path::new(expected_audio))
);
}
}
#[test]
fn automatic_overrides_preserve_external_parameter_policy() {
let matches = Cli::command()
.try_get_matches_from([
"oi-kit-inference",
"--model",
"target",
"--auto",
"quick",
"--speculative-draft-tokens",
"5",
"prompt",
])
.unwrap();
let args = Cli::from_arg_matches(&matches).unwrap();
let residency = ResidencyPlan::DenseDiskStream {
device_budget_bytes: 8 << 30,
host_budget_bytes: 4 << 30,
host_lookahead: 1,
background_queue: 1,
};
let plan =
ExecutionPlan::fully_resident(cpu_plan()).with_drafting(DraftingPlan::External {
model: "assistant".into(),
placement: super::DraftPlacementPlan::Target,
residency: residency.clone(),
max_draft_tokens: 2,
lookahead: true,
adaptive_lookahead: true,
});
let mut replay = args.clone();
replay.common.device = Some(CliDevice::Gpu(0));
apply_automatic_plan(&mut replay, &plan).unwrap();
assert_eq!(
cli_execution_plan(
&replay,
&cpu_plan(),
&test_devices(),
Some(Path::new("assistant")),
false
)
.unwrap(),
plan.clone()
.with_prepared_checkpoint_cache(replay.common.prepared_cache.policy())
);
let resources = ModelResourceProfile::unmeasured(
"target".into(),
oi_kit_inference_core::ArtifactFormat::SafeTensors,
);
let selected = AutomaticCliOverrides::from_matches(&matches)
.apply_to_plan(
&plan,
&args,
Some(Path::new("assistant")),
&resources,
&test_devices(),
)
.unwrap();
assert!(matches!(selected.drafting(), DraftingPlan::External {
residency: actual, max_draft_tokens: 5, ..
} if actual == &residency));
}
#[test]
fn automatic_residency_prefers_speed_then_bounded_fallbacks() {
assert_eq!(
choose_automatic_residency(true, true, true, true, true),
Some(0)
);
assert_eq!(
choose_automatic_residency(false, true, true, true, true),
Some(1)
);
assert_eq!(
choose_automatic_residency(false, false, true, true, true),
Some(2)
);
assert_eq!(
choose_automatic_residency(false, false, true, true, false),
Some(1)
);
assert_eq!(
choose_automatic_residency(false, false, true, false, false),
Some(0)
);
assert_eq!(
choose_automatic_residency(false, false, false, false, false),
None
);
}
#[test]
fn applying_automatic_plan_sets_residency_expert_cache_and_embedded_mtp() {
let mut args = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--auto",
"quick",
"prompt",
])
.unwrap();
let device = cpu_plan();
let plan = base_automatic_candidates(device, 1 << 30, 2 << 30)[1]
.clone()
.with_expert_cache(Some(super::ExpertCachePlan::new(
Some(256 << 20),
Some(512 << 20),
128 << 20,
64 << 20,
super::CacheEvictionPolicy::LeastRecentlyUsed,
)))
.with_drafting(DraftingPlan::Embedded {
max_draft_tokens: 3,
lookahead: true,
adaptive_lookahead: true,
});
apply_automatic_plan(&mut args, &plan).unwrap();
assert!(args.common.layerwise_host);
assert!(!args.common.dense_disk_stream);
assert!(args.expert_cache);
assert_eq!(args.common.device_budget_bytes, Some(1 << 30));
assert_eq!(args.expert_cache_device_budget_bytes, Some(256 << 20));
assert_eq!(args.speculative_draft_tokens, 3);
assert!(!args.disable_speculative_lookahead);
assert!(matches!(
plan.residency(),
ResidencyPlan::LayerwiseHost { .. }
));
}
#[test]
fn applying_exact_plan_replays_weight_transformation() {
let mut args = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--auto",
"quick",
"prompt",
])
.unwrap();
let mut plan = ExecutionPlan::fully_resident(cpu_plan()).with_weight_transformation(
WeightTransformationPlan::Affine {
bits: 4,
group_size: 128,
},
);
apply_automatic_plan(&mut args, &plan).unwrap();
assert_eq!(args.common.quantize, Some(4));
assert_eq!(args.common.quantization_group_size, 128);
plan = plan.with_weight_transformation(WeightTransformationPlan::MxFp4);
apply_automatic_plan(&mut args, &plan).unwrap();
assert_eq!(args.common.quantize, Some(4));
assert_eq!(
args.common.quantization_mode,
super::LoadQuantizationMode::Mxfp4
);
}
fn cached_file(file_path: &str, blob_path: &str) -> CachedFile {
let mut file = scanned_revision().files.pop().unwrap();
file.relative_path = file_path.into();
file.snapshot_path = file_path.into();
file.blob_path = blob_path.into();
file.size_on_disk = 0;
file.last_accessed = SystemTime::UNIX_EPOCH;
file.last_modified = SystemTime::UNIX_EPOCH;
file
}
#[test]
fn parses_json_telemetry_path_and_records_concrete_plan() {
let args = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--device",
"cpu",
"--layerwise-host",
"--device-layer-window",
"2",
"--telemetry-json",
"run.json",
"prompt",
])
.unwrap();
assert_eq!(args.telemetry_json.as_deref(), Some(Path::new("run.json")));
let plan = cli_execution_plan(&args, &cpu_plan(), &test_devices(), None, false).unwrap();
assert_eq!(plan.device().backend().as_str(), "mlx");
assert_eq!(plan.device().device(), "cpu:0");
assert!(matches!(
plan.residency(),
ResidencyPlan::LayerwiseHost {
device_layer_window: 2,
..
}
));
assert_eq!(plan.drafting(), &DraftingPlan::Disabled);
}
#[test]
fn timing_report_contains_only_timing_statistics() {
let mut stderr = Vec::new();
write_timing_report(
&mut stderr,
Duration::from_millis(1250),
Duration::from_millis(2000),
Some(Duration::from_millis(500)),
7,
Duration::from_millis(4000),
)
.unwrap();
assert_eq!(
String::from_utf8(stderr).unwrap(),
"load_time: 1.250 s\n\
generation_time: 2.000 s\n\
time_to_first_token: 0.500 s\n\
decode_token_rate: 4.00 tokens/s\n\
token_rate: 3.50 tokens/s\n\
total_execution_time: 4.000 s\n"
);
}
#[test]
fn rejects_raw_thinking_modes() {
let raw = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--raw",
"--thinking",
"off",
"prompt",
])
.unwrap();
assert!(validate_args(&raw)
.unwrap_err()
.to_string()
.contains("raw prompts bypass the chat template"));
let raw_effort = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--raw",
"--reasoning-effort",
"low",
"prompt",
])
.unwrap();
assert!(validate_args(&raw_effort)
.unwrap_err()
.to_string()
.contains("--reasoning-effort cannot be used with --raw"));
}
#[test]
fn parses_native_tool_options_and_keeps_raw_generation_explicit() {
let tools = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--tools",
"tools.json",
"--tool-choice",
"required",
"--max-parallel-tool-calls",
"2",
"--stop",
"<done>",
"prompt",
])
.unwrap();
assert_eq!(tools.tool_choice, CliToolChoice::Required);
assert_eq!(tools.max_parallel_tool_calls.unwrap().get(), 2);
assert_eq!(tools.stop_sequences, ["<done>"]);
validate_args(&tools).unwrap();
let raw_tools = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--raw",
"--tools",
"tools.json",
"prompt",
])
.unwrap();
assert!(validate_args(&raw_tools)
.unwrap_err()
.to_string()
.contains("--tools cannot be used with --raw"));
let raw =
Cli::try_parse_from(["oi-kit-inference", "--model", "model-id", "--raw", "prompt"])
.unwrap();
assert!(
validate_args(&raw).is_ok(),
"raw unconstrained generation remains intentionally supported"
);
}
#[test]
fn rejects_external_drafting_for_raw_generation() {
let raw = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--draft-model",
"draft-id",
"--raw",
"prompt",
])
.unwrap();
assert!(validate_args(&raw)
.unwrap_err()
.to_string()
.contains("requires prepared-chat generation"));
}
#[test]
fn registered_profiles_use_semantic_generation_without_tools() {
assert!(use_semantic_generation(
&SemanticSupport::Supported,
&NativeToolSupport::Supported,
false
)
.unwrap());
assert!(use_semantic_generation(
&SemanticSupport::Supported,
&NativeToolSupport::Supported,
true
)
.unwrap());
let unsupported = NativeToolSupport::Unsupported {
rejection: oi_kit_inference::runtime::chat::NativeToolRejection::UnrecognizedProtocol {
reason: "unregistered template".into(),
},
};
let semantic_unsupported = SemanticSupport::Unsupported {
reason: "unregistered template".into(),
};
assert!(!use_semantic_generation(&semantic_unsupported, &unsupported, false).unwrap());
assert!(
use_semantic_generation(&SemanticSupport::Supported, &unsupported, true)
.unwrap_err()
.to_string()
.contains("native tool calling is unavailable")
);
}
#[test]
fn semantic_output_hides_reasoning_and_writes_visible_text() {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let mut streamed_text = String::new();
let mut reasoning_stream = ReasoningStream::default();
write_semantic_event(
&SemanticEvent::ReasoningDelta("private thought".into()),
&mut stdout,
&mut stderr,
&mut streamed_text,
&mut reasoning_stream,
ReasoningOutput::Hidden,
)
.unwrap();
write_semantic_event(
&SemanticEvent::TextDelta("visible answer".into()),
&mut stdout,
&mut stderr,
&mut streamed_text,
&mut reasoning_stream,
ReasoningOutput::Hidden,
)
.unwrap();
assert_eq!(stdout, b"visible answer");
assert!(stderr.is_empty());
assert_eq!(streamed_text, "visible answer");
}
#[test]
fn interactive_semantic_output_dims_reasoning_on_terminal_stderr() {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let mut streamed_text = String::new();
let mut reasoning_stream = ReasoningStream::default();
write_semantic_event(
&SemanticEvent::ReasoningDelta("private thought".into()),
&mut stdout,
&mut stderr,
&mut streamed_text,
&mut reasoning_stream,
ReasoningOutput::InteractiveDimmed,
)
.unwrap();
write_semantic_event(
&SemanticEvent::TextDelta("visible answer".into()),
&mut stdout,
&mut stderr,
&mut streamed_text,
&mut reasoning_stream,
ReasoningOutput::InteractiveDimmed,
)
.unwrap();
assert_eq!(stdout, b"visible answer");
assert_eq!(stderr, b"\x1b[2;90mprivate thought\n\x1b[0m");
assert_eq!(streamed_text, "visible answer");
let mut plain_stderr = Vec::new();
let mut reasoning_stream = ReasoningStream::default();
reasoning_stream
.write_delta(
&mut plain_stderr,
"redirected reasoning",
ReasoningOutput::InteractivePlain,
)
.unwrap();
reasoning_stream
.close(&mut plain_stderr, ReasoningOutput::InteractivePlain)
.unwrap();
assert_eq!(plain_stderr, b"redirected reasoning\n");
}
#[test]
fn reasoning_output_follows_stdout_terminal_and_colors_only_terminal_stderr() {
let args = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--verbose",
"--hide-reasoning",
"prompt",
])
.unwrap();
assert!(args.verbose);
assert!(args.hide_reasoning);
assert_eq!(
ReasoningOutput::for_streams(false, false, false, true),
ReasoningOutput::Hidden
);
assert_eq!(
ReasoningOutput::for_streams(false, false, true, false),
ReasoningOutput::InteractivePlain
);
assert_eq!(
ReasoningOutput::for_streams(false, false, true, true),
ReasoningOutput::InteractiveDimmed
);
assert_eq!(
ReasoningOutput::for_streams(true, false, false, false),
ReasoningOutput::Verbose
);
assert_eq!(
ReasoningOutput::for_streams(true, true, true, true),
ReasoningOutput::Hidden,
"--hide-reasoning must override --verbose reasoning output"
);
}
#[test]
fn verbose_semantic_output_streams_reasoning_in_event_order() {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let mut streamed_text = String::new();
let mut reasoning_stream = ReasoningStream::default();
write_semantic_event(
&SemanticEvent::ReasoningDelta("private ".into()),
&mut stdout,
&mut stderr,
&mut streamed_text,
&mut reasoning_stream,
ReasoningOutput::Verbose,
)
.unwrap();
assert!(stdout.is_empty());
assert_eq!(stderr, b"--- reasoning content (stderr) ---\nprivate ");
write_semantic_event(
&SemanticEvent::ReasoningDelta("thought\nsecond line".into()),
&mut stdout,
&mut stderr,
&mut streamed_text,
&mut reasoning_stream,
ReasoningOutput::Verbose,
)
.unwrap();
assert_eq!(
stderr,
b"--- reasoning content (stderr) ---\nprivate thought\nsecond line"
);
write_semantic_event(
&SemanticEvent::TextDelta("visible answer".into()),
&mut stdout,
&mut stderr,
&mut streamed_text,
&mut reasoning_stream,
ReasoningOutput::Verbose,
)
.unwrap();
assert_eq!(stdout, b"visible answer");
assert_eq!(streamed_text, "visible answer");
assert_eq!(
stderr,
b"--- reasoning content (stderr) ---\nprivate thought\nsecond line\n\
--- end reasoning content (stderr) ---\n\
--- generated content (stdout) ---\n"
);
}
#[test]
fn classifies_generation_stop_reason() {
assert_eq!(stop_reason(&[4, 2], &[2], 10), StopReason::Eos);
assert_eq!(stop_reason(&[4, 5], &[2], 2), StopReason::MaxTokens);
assert_eq!(stop_reason(&[4], &[2], 2), StopReason::GeneratorExhausted);
}
#[test]
fn generation_arguments_override_only_explicit_checkpoint_settings() {
use oi_kit_inference_core::{CheckpointGenerationConfig, ResolvedGenerationConfig};
let checkpoint: CheckpointGenerationConfig = serde_json::from_value(serde_json::json!({
"do_sample": true, "temperature": 1.2, "top_k": 23, "top_p": 0.85,
"min_p": 0.1, "repetition_penalty": 1.3, "repeat_last_n": 129,
"frequency_penalty": 0.4, "presence_penalty": 1.5, "max_new_tokens": 1024
}))
.unwrap();
let inherited = ResolvedGenerationConfig {
do_sample: true,
temperature: 1.2,
top_k: 23,
top_p: 0.85,
min_p: 0.1,
repetition_penalty: 1.3,
repeat_last_n: 129,
frequency_penalty: 0.4,
presence_penalty: 1.5,
max_new_tokens: Some(1024),
};
let cases = [
(None, inherited),
(
Some("--temperature=0"),
ResolvedGenerationConfig {
do_sample: false,
temperature: 0.0,
..inherited
},
),
(
Some("--top-k=0"),
ResolvedGenerationConfig {
top_k: 0,
..inherited
},
),
(
Some("--top-p=1"),
ResolvedGenerationConfig {
top_p: 1.0,
..inherited
},
),
(
Some("--min-p=0"),
ResolvedGenerationConfig {
min_p: 0.0,
..inherited
},
),
(
Some("--repeat-penalty=1"),
ResolvedGenerationConfig {
repetition_penalty: 1.0,
..inherited
},
),
(
Some("--repeat-last-n=0"),
ResolvedGenerationConfig {
repeat_last_n: 0,
..inherited
},
),
(
Some("--frequency-penalty=0"),
ResolvedGenerationConfig {
frequency_penalty: 0.0,
..inherited
},
),
(
Some("--presence-penalty=0"),
ResolvedGenerationConfig {
presence_penalty: 0.0,
..inherited
},
),
(
Some("--max-tokens=512"),
ResolvedGenerationConfig {
max_new_tokens: Some(512),
..inherited
},
),
];
for raw in [false, true] {
for (flag, expected) in cases {
let mut command = vec!["oi-kit-inference", "--model", "model-id", "prompt"];
if raw {
command.push("--raw");
}
command.extend(flag);
let args = Cli::try_parse_from(command).unwrap();
validate_args(&args).unwrap();
let resolved = oi_kit_inference_core::resolve_generation_config(
Some(&checkpoint),
args.generation_overrides(),
)
.unwrap();
assert_eq!(resolved, expected, "raw={raw}, flag={flag:?}");
}
}
}
#[test]
fn reports_only_max_tokens_without_verbose_output() {
assert!(should_report_stop_reason(StopReason::MaxTokens, false));
assert!(!should_report_stop_reason(StopReason::Eos, false));
assert!(!should_report_stop_reason(
StopReason::GeneratorExhausted,
false
));
assert!(should_report_stop_reason(StopReason::Eos, true));
}
#[test]
fn validates_load_time_quantization_arguments() {
let valid = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--quantize",
"4",
"prompt",
])
.unwrap();
validate_args(&valid).unwrap();
let invalid = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--quantize",
"7",
"prompt",
])
.unwrap();
assert!(validate_args(&invalid)
.unwrap_err()
.to_string()
.contains("bits must be one of"));
let mxfp4 = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--quantize",
"4",
"--quantization-mode",
"mxfp4",
"prompt",
])
.unwrap();
validate_args(&mxfp4).unwrap();
assert_eq!(
requested_load_quantization(&mxfp4).unwrap(),
Some(QuantizationRequest::MxFp4)
);
let mut invalid_mxfp4 = mxfp4;
invalid_mxfp4.common.quantize = Some(3);
assert!(validate_args(&invalid_mxfp4)
.unwrap_err()
.to_string()
.contains("requires --quantize 4"));
}
#[test]
fn validates_mirostat_v2_arguments() {
let valid = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--mirostat-v2",
"--temperature",
"1.0",
"prompt",
])
.unwrap();
validate_args(&valid).unwrap();
let zero_temperature = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--mirostat-v2",
"--temperature",
"0",
"prompt",
])
.unwrap();
assert!(validate_args(&zero_temperature)
.unwrap_err()
.to_string()
.contains("--temperature greater than zero"));
let speculative = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--draft-model",
"draft-id",
"--mirostat-v2",
"--temperature",
"1.0",
"prompt",
])
.unwrap();
validate_args(&speculative).unwrap();
}
#[test]
fn parses_main_and_draft_device_selectors() {
assert_eq!("cpu".parse::<CliDevice>().unwrap(), CliDevice::Cpu);
assert_eq!("gpu:0".parse::<CliDevice>().unwrap(), CliDevice::Gpu(0));
assert_eq!("gpu:12".parse::<CliDevice>().unwrap(), CliDevice::Gpu(12));
assert!("gpu".parse::<CliDevice>().is_err());
assert!("gpu:-1".parse::<CliDevice>().is_err());
assert!("gpu:one".parse::<CliDevice>().is_err());
assert_eq!(
"target".parse::<SpeculativeDraftDevice>().unwrap(),
SpeculativeDraftDevice::Target
);
assert_eq!(
"cpu".parse::<SpeculativeDraftDevice>().unwrap(),
SpeculativeDraftDevice::Device(CliDevice::Cpu)
);
assert_eq!(
"gpu:3".parse::<SpeculativeDraftDevice>().unwrap(),
SpeculativeDraftDevice::Device(CliDevice::Gpu(3))
);
let defaults =
Cli::try_parse_from(["oi-kit-inference", "--model", "model-id", "prompt"]).unwrap();
assert!(defaults.common.device.is_none());
assert_eq!(
super::resolve_device(&test_devices(), None).unwrap(),
cpu_plan()
);
// Device IDs and family labels are opaque to the CLI.
let mut profile = test_devices();
let mut gpu = profile.devices[0].clone();
gpu.kind = super::HardwareDeviceKind::Gpu;
gpu.id = "opaque-accelerator-id".into();
gpu.index = 3;
profile.devices.push(gpu);
assert_eq!(
super::resolve_device(&profile, Some(CliDevice::Cpu)).unwrap(),
cpu_plan()
);
for request in [None, Some(CliDevice::Gpu(3))] {
assert_eq!(
super::resolve_device(&profile, request).unwrap().device(),
"opaque-accelerator-id"
);
}
assert!(super::resolve_device(&profile, Some(CliDevice::Gpu(0))).is_err());
assert_eq!(
defaults.speculative_draft_device,
SpeculativeDraftDevice::Target
);
let cpu_target = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--device",
"cpu",
"prompt",
])
.unwrap();
assert_eq!(cpu_target.common.device, Some(CliDevice::Cpu));
validate_args(&cpu_target).unwrap();
}
#[test]
fn explicit_speculative_draft_devices_require_external_drafter() {
for device in ["cpu", "gpu:0", "gpu:3"] {
let without_drafter = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--speculative-draft-device",
device,
"prompt",
])
.unwrap();
assert!(validate_args(&without_drafter)
.unwrap_err()
.to_string()
.contains("requires an external --draft-model"));
let with_drafter = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--draft-model",
"draft-id",
"--speculative-draft-device",
device,
"prompt",
])
.unwrap();
validate_args(&with_drafter).unwrap();
}
}
#[test]
fn parses_and_validates_expert_cache_prefill_bank_target() {
let args = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--expert-cache",
"--expert-cache-scratch-bytes",
"4096",
"--expert-cache-prefill-bank-bytes",
"1024",
"prompt",
])
.unwrap();
assert_eq!(args.expert_cache_scratch_bytes, 4096);
assert_eq!(args.expert_cache_prefill_bank_bytes, 1024);
validate_args(&args).unwrap();
let invalid = Cli {
expert_cache_prefill_bank_bytes: 4097,
..args
};
assert!(validate_args(&invalid).is_err());
}
#[test]
fn validates_dense_stream_residency_conflicts() {
let args = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--dense-disk-stream",
"--layerwise-host",
"prompt",
])
.unwrap();
assert!(validate_args(&args).is_err());
for residency in ["--dense-disk-stream", "--layerwise-host"] {
let args = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
residency,
"--quantize",
"8",
"prompt",
])
.unwrap();
validate_args(&args).unwrap();
assert_eq!(
cli_execution_plan(&args, &cpu_plan(), &test_devices(), None, false)
.unwrap()
.weight_transformation(),
WeightTransformationPlan::Affine {
bits: 8,
group_size: 64
}
);
}
}
#[test]
fn accepts_load_time_quantization_with_a_resident_expert_cache() {
let arguments = Cli::try_parse_from([
"oi-kit-inference",
"--model",
"model-id",
"--expert-cache",
"--quantize",
"4",
"prompt",
])
.unwrap();
validate_args(&arguments).unwrap();
}
#[test]
fn selects_main_by_default() {
let revisions = [revision("older", &["main"], 1), revision("newer", &[], 2)];
assert_eq!(
select_revision(&revisions, None).unwrap().commit_hash,
"older"
);
}
#[test]
fn selects_requested_ref_or_hash() {
let revisions = [
revision("first", &["main"], 1),
revision("second", &["experiment"], 2),
];
assert_eq!(
select_revision(&revisions, Some("experiment"))
.unwrap()
.commit_hash,
"second"
);
assert_eq!(
select_revision(&revisions, Some("first"))
.unwrap()
.commit_hash,
"first"
);
}
#[test]
fn selects_newest_snapshot_without_main() {
let revisions = [revision("older", &[], 1), revision("newer", &[], 2)];
assert_eq!(
select_revision(&revisions, None).unwrap().commit_hash,
"newer"
);
}
#[test]
fn parses_hugging_face_quantization_selector() {
assert_eq!(
split_hf_model_spec("unsloth/model-GGUF:UD-Q4_K_M").unwrap(),
("unsloth/model-GGUF", Some("UD-Q4_K_M"))
);
assert_eq!(
split_hf_model_spec("unsloth/model-GGUF").unwrap(),
("unsloth/model-GGUF", None)
);
assert!(split_hf_model_spec("unsloth/model-GGUF:").is_err());
}
#[test]
fn selects_exact_and_unsloth_aliased_quantizations() {
let q4 = Path::new("snapshot/model-Q4_K_M.gguf");
let ud_q4 = Path::new("snapshot/model-UD-Q4_K_M.gguf");
let files = [q4, ud_q4];
assert_eq!(
select_cached_gguf_path(&files, "UD-Q4_K_M", CachedGgufRole::Target).unwrap(),
ud_q4
);
assert_eq!(
select_cached_gguf_path(&files, "q4_k_m", CachedGgufRole::Target).unwrap(),
q4
);
assert_eq!(
select_cached_gguf_path(&[ud_q4], "Q4_K_M", CachedGgufRole::Target).unwrap(),
ud_q4
);
}
#[test]
fn distinguishes_target_and_mtp_sidecar_at_same_quantization() {
let target = Path::new("snapshot/gemma-4-26B-A4B-it-Q8_0.gguf");
let draft = Path::new("snapshot/MTP/mtp-gemma-4-26B-A4B-it-Q8_0.gguf");
let files = [target, draft];
assert_eq!(
select_cached_gguf_path(&files, "Q8_0", CachedGgufRole::Target).unwrap(),
target
);
assert_eq!(
select_cached_gguf_path(&files, "Q8_0", CachedGgufRole::SpeculativeDraft).unwrap(),
draft
);
}
#[test]
fn selects_muse_dflash_as_the_unique_draft_sidecar() {
let mut revision = revision("main", &["main"], 1);
revision.files = vec![
cached_file("main/muse-glimmer-30B-kquant-17gb.gguf", "blobs/target"),
cached_file("main/mmproj-kquant.gguf", "blobs/projector"),
cached_file("main/dflash-kquant.gguf", "blobs/dflash"),
];
assert_eq!(
select_unique_cached_gguf(&revision, CachedGgufRole::SpeculativeDraft).unwrap(),
Some(Path::new("main/dflash-kquant.gguf").into())
);
assert_eq!(
select_cached_gguf_path(
&revision
.files
.iter()
.map(|file| file.snapshot_path.as_path())
.collect::<Vec<_>>(),
"dflash-kquant",
CachedGgufRole::SpeculativeDraft,
)
.unwrap(),
Path::new("main/dflash-kquant.gguf")
);
}
#[test]
fn bare_draft_repository_rejects_ambiguous_sidecars() {
let mut revision = revision("main", &["main"], 1);
revision.files = vec![
cached_file("main/dflash-Q4_K.gguf", "blobs/q4"),
cached_file("main/dflash-Q8_0.gguf", "blobs/q8"),
];
let error = select_unique_cached_gguf(&revision, CachedGgufRole::SpeculativeDraft)
.unwrap_err()
.to_string();
assert!(error.contains("multiple draft GGUF files"));
assert!(error.contains("append :QUANT"));
}
#[test]
fn finds_quantizations_across_separate_cached_snapshots() {
let mut target = revision("target", &[], 1);
target.files = vec![cached_file(
"target/model-UD-Q4_K_M.gguf",
"blobs/target-q4",
)];
let mut main = revision("assistant", &["main"], 2);
main.files = vec![cached_file(
"assistant/MTP/mtp-assistant-Q8_0.gguf",
"blobs/assistant-q8",
)];
let revisions = [target, main];
assert_eq!(
select_cached_gguf_from_revisions(&revisions, None, "Q4_K_M", CachedGgufRole::Target,)
.unwrap(),
Path::new("target/model-UD-Q4_K_M.gguf")
);
assert_eq!(
select_cached_gguf_from_revisions(
&revisions,
None,
"Q8_0",
CachedGgufRole::SpeculativeDraft,
)
.unwrap(),
Path::new("assistant/MTP/mtp-assistant-Q8_0.gguf")
);
}
#[test]
fn explicit_revision_limits_quantization_selection() {
let mut target = revision("target", &[], 1);
target.files = vec![cached_file(
"target/model-UD-Q4_K_M.gguf",
"blobs/target-q4",
)];
let main = revision("assistant", &["main"], 2);
let revisions = [target, main];
assert!(select_cached_gguf_from_revisions(
&revisions,
Some("main"),
"Q4_K_M",
CachedGgufRole::Target,
)
.is_err());
}
#[test]
fn prefers_a_complete_target_and_draft_snapshot() {
let mut complete = revision("complete", &[], 1);
complete.files = vec![
cached_file("complete/model-UD-Q4_K_M.gguf", "blobs/complete-q4"),
cached_file(
"complete/MTP/mtp-model-Q8_0.gguf",
"blobs/complete-draft-q8",
),
];
let mut main = revision("main", &["main"], 2);
main.files = vec![cached_file("main/model-UD-Q4_K_M.gguf", "blobs/main-q4")];
let revisions = [complete, main];
let (revision, target, draft) =
select_cached_gguf_pair_from_revisions(&revisions, "Q4_K_M", "Q8_0").unwrap();
assert_eq!(revision.commit_hash, "complete");
assert_eq!(target, Path::new("complete/model-UD-Q4_K_M.gguf"));
assert_eq!(draft, Path::new("complete/MTP/mtp-model-Q8_0.gguf"));
}
#[test]
fn mixed_repository_revisions_are_permitted_unless_strictly_required() {
let target = ResolvedModel {
path: "target.gguf".into(),
repository: Some("owner/model".into()),
commit_hash: Some("target-commit".into()),
};
let draft = ResolvedModel {
path: "draft.gguf".into(),
repository: Some("owner/model".into()),
commit_hash: Some("draft-commit".into()),
};
validate_artifact_pair(&target, &draft, false).unwrap();
let error = validate_artifact_pair(&target, &draft, true).unwrap_err();
assert!(error.to_string().contains("--require-same-revision"));
let mut other_repository = draft;
other_repository.repository = Some("owner/assistant".into());
validate_artifact_pair(&target, &other_repository, false).unwrap();
}
#[test]
fn shared_blobs_are_not_ambiguous_across_snapshots() {
let mut older = revision("older", &[], 1);
older.files = vec![cached_file("older/model-Q4_K_M.gguf", "blobs/shared-q4")];
let mut main = revision("main", &["main"], 2);
main.files = vec![cached_file("main/other-Q8_0.gguf", "blobs/other-q8")];
let mut newer = revision("newer", &[], 3);
newer.files = vec![cached_file("newer/model-Q4_K_M.gguf", "blobs/shared-q4")];
let revisions = [older, main, newer];
assert_eq!(
select_cached_gguf_from_revisions(&revisions, None, "Q4_K_M", CachedGgufRole::Target,)
.unwrap(),
Path::new("older/model-Q4_K_M.gguf")
);
}
#[test]
fn selects_first_shard_for_quantization() {
let first = Path::new("snapshot/model-Q4_K_M-00001-of-00002.gguf");
let second = Path::new("snapshot/model-Q4_K_M-00002-of-00002.gguf");
assert_eq!(
select_cached_gguf_path(&[second, first], "Q4_K_M", CachedGgufRole::Target,).unwrap(),
first
);
}
#[test]
fn rejects_ambiguous_or_missing_quantizations() {
let first = Path::new("snapshot/first-Q4_K_M.gguf");
let second = Path::new("snapshot/second-Q4_K_M.gguf");
let error = select_cached_gguf_path(&[first, second], "Q4_K_M", CachedGgufRole::Target)
.unwrap_err()
.to_string();
assert!(error.contains("matches multiple cached GGUF files"));
let error = select_cached_gguf_path(&[first], "Q8_0", CachedGgufRole::Target)
.unwrap_err()
.to_string();
assert!(error.contains("available GGUF files"));
}
#[test]
fn formats_memory_with_exact_bytes() {
assert_eq!(format_bytes(512), "512.00 B (512 bytes)");
assert_eq!(format_bytes(1536), "1.50 KiB (1536 bytes)");
assert_eq!(
format_bytes(3 * 1024 * 1024 * 1024),
"3.00 GiB (3221225472 bytes)"
);
}
}