oi-kit-inference-cli 0.1.0

Command-line interface for running local models with oi-kit-inference
//! Arguments and portable normalization shared by text and speech commands.
use super::{CliDevice, LoadQuantizationMode};
use anyhow::{bail, Result};
use oi_kit_inference_core::{QuantizationRequest, WeightTransformationPlan};
use oi_kit_inference_runtime::NormalizedLoadRequest;

#[derive(Debug, Clone, PartialEq, clap::Args)]
pub struct CommonOptions {
    #[command(flatten)]
    pub(crate) prepared_cache: PreparedCacheArgs,
    /// Model directory, GGUF file, or cached Hugging Face model identifier.
    /// Append `:QUANT` to select a cached GGUF quantization.
    #[arg(short, long, value_name = "PATH_OR_ID")]
    pub model: Option<String>,

    /// Cached Hugging Face revision (a ref such as `main` or a commit hash).
    #[arg(long, value_name = "REVISION", requires = "model")]
    pub revision: Option<String>,

    /// Main model execution device: `cpu`, `gpu:N`, `metal:N`, or `cuda:N`.
    #[arg(long, value_name = "DEVICE")]
    pub device: Option<CliDevice>,

    /// Backend allocator-cache limit in bytes; zero disables caching.
    #[arg(long, value_name = "BYTES")]
    pub allocator_cache_limit_bytes: Option<u64>,

    /// Quantize eligible dense weights to this bit width while loading.
    #[arg(long, value_name = "BITS")]
    pub quantize: Option<i32>,

    /// Encoding used for load-time quantization. MXFP4 requires --quantize 4.
    #[arg(long, value_enum, default_value_t = LoadQuantizationMode::Affine)]
    pub quantization_mode: LoadQuantizationMode,

    /// Number of adjacent weights sharing quantization parameters.
    #[arg(long, default_value_t = 64, value_name = "WEIGHTS")]
    pub quantization_group_size: i32,

    /// Keep repeated model layers on the host and use a bounded device window.
    #[arg(long)]
    pub layerwise_host: bool,

    /// Stream ordinary execution layers through bounded disk, host, and device caches.
    #[arg(long)]
    pub dense_disk_stream: bool,

    /// Maximum repeated layers resident on the execution device.
    #[arg(long, default_value_t = 1, value_name = "LAYERS")]
    pub device_layer_window: usize,

    /// Optional logical device parameter budget in bytes.
    #[arg(long, value_name = "BYTES")]
    pub device_budget_bytes: Option<u64>,

    /// Optional logical host parameter budget in bytes.
    #[arg(long, value_name = "BYTES")]
    pub host_budget_bytes: Option<u64>,

    /// Maximum simultaneously cached SafeTensors shards or GGUF readers.
    #[arg(long, default_value_t = 4, value_name = "SHARDS")]
    pub cached_shards: usize,

    /// Sampling temperature. Omission preserves the command's sampling policy.
    #[arg(short = 't', long, value_name = "FLOAT")]
    pub temperature: Option<f32>,

    /// Nucleus probability. Omission preserves the command's sampling policy.
    #[arg(long, value_name = "FLOAT")]
    pub top_p: Option<f32>,

    /// Penalty for repeating a token. Omission preserves the command's sampling policy.
    #[arg(long, value_name = "FLOAT")]
    pub repeat_penalty: Option<f32>,

    /// Random seed used when temperature is non-zero.
    #[arg(long)]
    pub seed: Option<u64>,
}
impl CommonOptions {
    pub fn apply_allocator_cache_limit(
        &self,
        factory: &impl oi_kit_inference::api::BackendInspection,
    ) -> Result<()> {
        if let Some(bytes) = self.allocator_cache_limit_bytes {
            factory.set_allocator_cache_limit(bytes)?;
        }
        Ok(())
    }
    pub fn validate(&self) -> Result<()> {
        anyhow::ensure!(
            !(self.revision.is_some()
                && self
                    .model
                    .as_deref()
                    .is_some_and(|model| std::path::Path::new(model).exists())),
            "--revision can only be used with a Hugging Face model identifier"
        );

        anyhow::ensure!(
            self.cached_shards > 0,
            "--cached-shards must be greater than zero"
        );
        anyhow::ensure!(
            self.device_layer_window > 0,
            "--device-layer-window must be greater than zero"
        );
        anyhow::ensure!(
            !(self.layerwise_host && self.dense_disk_stream),
            "--dense-disk-stream conflicts with --layerwise-host"
        );
        self.quantization_request()?;
        Ok(())
    }
    pub fn quantization_request(&self) -> Result<Option<QuantizationRequest>> {
        let request = match (self.quantize, self.quantization_mode) {
            (Some(bits), LoadQuantizationMode::Affine) => Some(QuantizationRequest::Affine {
                group_size: u32::try_from(self.quantization_group_size)?,
                bits: u8::try_from(bits)?,
            }),
            (Some(4), LoadQuantizationMode::Mxfp4) => Some(QuantizationRequest::MxFp4),
            (Some(_), LoadQuantizationMode::Mxfp4) => {
                bail!("--quantization-mode mxfp4 requires --quantize 4")
            }
            (None, LoadQuantizationMode::Mxfp4) => bail!("--quantization-mode requires --quantize"),
            (None, LoadQuantizationMode::Affine) => None,
        };
        if let Some(request) = request {
            NormalizedLoadRequest::with_quantization(request).weight_quantization()?;
        }
        Ok(request)
    }
    pub fn weight_transformation(&self) -> Result<WeightTransformationPlan> {
        Ok(match self.quantization_request()? {
            None => WeightTransformationPlan::PreserveCheckpoint,
            Some(QuantizationRequest::Affine { bits, group_size }) => {
                WeightTransformationPlan::Affine {
                    bits: i32::from(bits),
                    group_size: i32::try_from(group_size)?,
                }
            }
            Some(QuantizationRequest::MxFp4) => WeightTransformationPlan::MxFp4,
            Some(_) => unreachable!("CLI declares only affine and MXFP4 transformations"),
        })
    }
    #[cfg(feature = "realtime")]
    pub fn weight_quantization(
        &self,
    ) -> Result<Option<oi_kit_inference_checkpoint::WeightQuantization>> {
        let request =
            oi_kit_inference_runtime::execution_plan_quantization(self.weight_transformation()?)?;
        request
            .map(|q| NormalizedLoadRequest::with_quantization(q).weight_quantization())
            .transpose()
            .map(Option::flatten)
            .map_err(Into::into)
    }
}

#[cfg(feature = "realtime")]
pub fn output_file(path: &std::path::Path) -> Result<std::fs::File> {
    use anyhow::Context;
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .with_context(|| format!("creating {}; output paths must be new", path.display()))
}

/// Explicit storage for weights prepared by the loader.
#[derive(Debug, Clone, Default, PartialEq, clap::Args)]
pub(crate) struct PreparedCacheArgs {
    /// Directory for file-backed prepared weights (defaults to the user cache directory).
    #[arg(long, requires = "prepared_cache_bytes")]
    prepared_cache_dir: Option<std::path::PathBuf>,
    /// Maximum bytes for prepared weight files (defaults to 32 GiB).
    #[arg(long, requires = "prepared_cache_dir")]
    prepared_cache_bytes: Option<u64>,
}

impl PreparedCacheArgs {
    pub(crate) fn from_policy(
        policy: Option<&oi_kit_inference_checkpoint::prepared_cache::PreparedCheckpointCachePolicy>,
    ) -> Self {
        Self {
            prepared_cache_dir: policy.map(|policy| policy.directory.clone()),
            prepared_cache_bytes: policy.map(|policy| policy.max_bytes),
        }
    }

    pub(crate) fn policy(
        &self,
    ) -> oi_kit_inference_checkpoint::prepared_cache::PreparedCheckpointCachePolicy {
        use std::{env, path::PathBuf};

        let directory = self.prepared_cache_dir.clone().unwrap_or_else(|| {
            let root = if cfg!(target_os = "windows") {
                env::var_os("LOCALAPPDATA").map(PathBuf::from)
            } else {
                env::var_os("XDG_CACHE_HOME")
                    .map(PathBuf::from)
                    .filter(|path| path.is_absolute())
                    .or_else(|| {
                        env::var_os("HOME")
                            .map(PathBuf::from)
                            .filter(|path| path.is_absolute())
                            .map(|home| {
                                home.join(if cfg!(target_os = "macos") {
                                    "Library/Caches"
                                } else {
                                    ".cache"
                                })
                            })
                    })
            };
            root.unwrap_or_else(env::temp_dir)
                .join("oi-kit-inference/prepared-checkpoints-v1")
        });
        oi_kit_inference_checkpoint::prepared_cache::PreparedCheckpointCachePolicy {
            directory,
            max_bytes: self.prepared_cache_bytes.unwrap_or(32 * 1024 * 1024 * 1024),
        }
    }

    #[cfg(feature = "realtime")]
    pub(crate) fn is_explicit(&self) -> bool {
        self.prepared_cache_dir.is_some()
    }
}