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,
#[arg(short, long, value_name = "PATH_OR_ID")]
pub model: Option<String>,
#[arg(long, value_name = "REVISION", requires = "model")]
pub revision: Option<String>,
#[arg(long, value_name = "DEVICE")]
pub device: Option<CliDevice>,
#[arg(long, value_name = "BYTES")]
pub allocator_cache_limit_bytes: Option<u64>,
#[arg(long, value_name = "BITS")]
pub quantize: Option<i32>,
#[arg(long, value_enum, default_value_t = LoadQuantizationMode::Affine)]
pub quantization_mode: LoadQuantizationMode,
#[arg(long, default_value_t = 64, value_name = "WEIGHTS")]
pub quantization_group_size: i32,
#[arg(long)]
pub layerwise_host: bool,
#[arg(long)]
pub dense_disk_stream: bool,
#[arg(long, default_value_t = 1, value_name = "LAYERS")]
pub device_layer_window: usize,
#[arg(long, value_name = "BYTES")]
pub device_budget_bytes: Option<u64>,
#[arg(long, value_name = "BYTES")]
pub host_budget_bytes: Option<u64>,
#[arg(long, default_value_t = 4, value_name = "SHARDS")]
pub cached_shards: usize,
#[arg(short = 't', long, value_name = "FLOAT")]
pub temperature: Option<f32>,
#[arg(long, value_name = "FLOAT")]
pub top_p: Option<f32>,
#[arg(long, value_name = "FLOAT")]
pub repeat_penalty: Option<f32>,
#[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()))
}
#[derive(Debug, Clone, Default, PartialEq, clap::Args)]
pub(crate) struct PreparedCacheArgs {
#[arg(long, requires = "prepared_cache_bytes")]
prepared_cache_dir: Option<std::path::PathBuf>,
#[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()
}
}