oi-kit-inference-cli 0.1.0

Command-line interface for running local models with oi-kit-inference
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Local, digest-checked artifact preparation and selected native startup.

use std::{
    path::{Path, PathBuf},
    time::{Duration, Instant},
};

use anyhow::{ensure, Context, Result};
use oi_kit_inference::api::realtime::{
    bind_realtime, prepare_realtime, prepare_realtime_model, RealtimeArtifactRequest,
    RealtimeArtifactSource as Source, RealtimeAssetDirectories, RealtimeBackendFactory,
    RealtimeLoadOptions, RealtimeSession, SpeechRealtimeSession, SpeechSessionOptions,
    VoiceChatDecodeLimits, VoiceChatInputConfig, VoiceChatPhrasePolicy,
    VoiceChatPublicationCapacity, VoiceChatPublicationLimits, VoiceChatSpeechOptions,
    VoiceChatStartOptions, VoiceChatTextLimits, VoiceChatToolLimits, VoiceChatTurnLimits,
    VoiceChatTurnPolicy,
};
use oi_kit_inference_architectures::voicechat::{
    agent_sampling::AgentSamplingPolicy,
    channels::PromptPolicy,
    component_residency::VoiceChatResidencyPolicy,
    frontend::FrontendOptions,
    perception_rnnt::PerceptionRnntLimits,
    provider_residency::{SpeechProvider, SpeechResidencyPolicy},
    rnnt::RnntLimits,
    schedule::ScheduleLimits,
};
use oi_kit_inference_core::{scheduler::RequestId, ResidencyPlan};
use oi_kit_inference_runtime::{
    execution_plan_layer_residency, CacheResidencyPolicy, ResidencyDiagnostics,
};
use serde::Deserialize;

/// A local request. Relative artifact paths resolve against this JSON file's directory.
/// Required byte limits are logical admission limits, not allocator or process limits.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    pub prepared_checkpoint_cache:
        Option<oi_kit_inference_checkpoint::prepared_cache::PreparedCheckpointCachePolicy>,
    #[serde(default)]
    pub speech_weights: SpeechFloatChoice,
    #[serde(default)]
    pub speech_compute: SpeechFloatChoice,
    pub official_assets: PathBuf,
    pub base_assets: PathBuf,
    pub source: Source,
    #[serde(default)]
    pub system_prompt: String,
    #[serde(default)]
    pub tools: Vec<serde_json::Value>,
    /// Fixed choice spoken during tool-call serialization, overriding random selection.
    #[serde(default)]
    pub acknowledgement: Option<String>,
    /// Select from the released pool using `seed` when no fixed phrase is supplied.
    #[serde(default = "default_random_phrase")]
    pub random_acknowledgement: bool,
    /// Fixed fallback initial reminder; per-call scripted text takes precedence.
    #[serde(default)]
    pub initial_reminder: Option<String>,
    /// Select from the released initial reminder pool when no fixed text is supplied.
    #[serde(default = "default_random_phrase")]
    pub random_initial_reminder: bool,
    #[serde(default)]
    pub device: Device,
    #[serde(default)]
    pub parameter_residency: ParameterResidency,
    pub device_parameter_bytes: u64,
    pub host_parameter_bytes: u64,
    pub max_branch_bytes: u64,
    pub max_total_copy_bytes: u64,
    #[serde(default = "default_frames")]
    pub max_frames: u64,
    #[serde(default = "default_steps")]
    pub max_model_steps: u64,
    /// Consecutive RNNT nonblank frames required for barge-in (80 ms each).
    /// Omission retains the pinned streaming policy's 40-frame threshold.
    #[serde(default)]
    pub interruption_speech_frames: Option<u64>,
    #[serde(default)]
    pub seed: u64,
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Device {
    #[default]
    Cpu,
    Gpu,
}

/// Portable speech projection precision, configured independently of the device.
#[derive(Debug, Default, Clone, Copy, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "snake_case")]
pub enum SpeechFloatChoice {
    #[default]
    F32,
    F16,
    Bf16,
}
impl From<SpeechFloatChoice> for oi_kit_inference_architectures::voicechat::precision::SpeechFloat {
    fn from(value: SpeechFloatChoice) -> Self {
        match value {
            SpeechFloatChoice::F32 => Self::F32,
            SpeechFloatChoice::F16 => Self::F16,
            SpeechFloatChoice::Bf16 => Self::Bf16,
        }
    }
}

/// Every speech provider has its own finite pool; the enclosing totals include all ten.
#[derive(Debug, Default, Deserialize)]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
pub enum ParameterResidency {
    #[default]
    Resident,
    Host {
        backbone_device_bytes: u64,
        backbone_host_bytes: u64,
        speech_device_bytes: u64,
        speech_host_bytes: u64,
        #[serde(default = "default_depth")]
        depth: usize,
    },
    Disk {
        backbone_device_bytes: u64,
        backbone_host_bytes: u64,
        speech_device_bytes: u64,
        speech_host_bytes: u64,
    },
}

fn default_frames() -> u64 {
    4096
}
fn default_steps() -> u64 {
    8192
}
fn default_depth() -> usize {
    1
}
fn default_random_phrase() -> bool {
    true
}

impl Config {
    pub fn resolve_paths(&mut self, directory: &Path) {
        fn resolve(path: &mut PathBuf, directory: &Path) {
            if path.is_relative() {
                *path = directory.join(&*path);
            }
        }
        if let Some(cache) = &mut self.prepared_checkpoint_cache {
            resolve(&mut cache.directory, directory);
        }
        resolve(&mut self.official_assets, directory);
        resolve(&mut self.base_assets, directory);
        match &mut self.source {
            Source::SafeTensors { path } | Source::Gguf { path } => resolve(path, directory),
            Source::AudioGguf {
                backbone,
                projector,
            } => {
                resolve(backbone, directory);
                resolve(projector, directory);
            }
            Source::SplitGguf {
                perception,
                backbone,
                function_head,
                tts,
                companion,
            } => {
                for path in [perception, backbone, function_head, tts, companion] {
                    resolve(path, directory);
                }
            }
        }
    }

    pub fn validate(&self) -> Result<()> {
        ensure!(
            self.official_assets.is_dir(),
            "official_assets must be a local snapshot directory"
        );
        ensure!(
            self.base_assets.is_dir(),
            "base_assets must be a local snapshot directory"
        );
        ensure!(
            self.system_prompt.is_ascii(),
            "VoiceChat system_prompt must be ASCII"
        );
        for (role, text) in [
            ("acknowledgement", &self.acknowledgement),
            ("initial_reminder", &self.initial_reminder),
        ] {
            if let Some(text) = text {
                ensure!(text.is_ascii(), "VoiceChat {role} must be ASCII");
                ensure!(
                    !text.trim().is_empty() && text.len() <= 65_536,
                    "VoiceChat {role} must contain text within the 65536-byte limit"
                );
            }
        }
        ensure!(
            self.device_parameter_bytes > 0 && self.host_parameter_bytes > 0,
            "parameter admission requires positive device and host limits"
        );
        ensure!(
            self.max_branch_bytes > 0 && self.max_total_copy_bytes > 0,
            "state branch and total copy limits must be positive"
        );
        ensure!(
            self.max_frames > 0 && self.max_model_steps > 0,
            "frame and model-step limits must be positive"
        );
        ensure!(
            self.interruption_speech_frames != Some(0),
            "interruption_speech_frames must be positive"
        );
        // Check integer representations before any large artifact is opened.
        usize::try_from(self.max_frames)?;
        usize::try_from(self.max_model_steps)?;
        self.max_model_steps
            .checked_add(8194)
            .context("backbone position capacity overflows")?;
        self.max_model_steps
            .checked_add(128)
            .context("speech position capacity overflows")?;
        match &self.source {
            Source::SafeTensors { path } => ensure!(
                path.exists(),
                "SafeTensors source does not exist: {}",
                path.display()
            ),
            Source::Gguf { path } => ensure!(
                path.is_file(),
                "GGUF source is not a file: {}",
                path.display()
            ),
            Source::AudioGguf { .. } => {
                anyhow::bail!("this WAV conversation command requires a VoiceChat artifact");
            }
            Source::SplitGguf {
                perception,
                backbone,
                function_head,
                tts,
                companion,
            } => {
                for path in [perception, backbone, function_head, tts] {
                    ensure!(
                        path.is_file(),
                        "split GGUF component is not a file: {}",
                        path.display()
                    );
                }
                ensure!(
                    companion.exists(),
                    "explicit complete companion does not exist: {}",
                    companion.display()
                );
            }
        }
        let _ = self.residency(2)?;
        Ok(())
    }

    fn residency(&self, cached_shards: usize) -> Result<VoiceChatResidencyPolicy> {
        let host = |device, host, depth| ResidencyPlan::LayerwiseHost {
            device_layer_window: depth,
            device_budget_bytes: Some(device),
            host_budget_bytes: Some(host),
        };
        let disk = |device, host| {
            let slots = usize::from(host != 0);
            ResidencyPlan::DenseDiskStream {
                device_budget_bytes: device,
                host_budget_bytes: host,
                host_lookahead: slots,
                background_queue: slots,
            }
        };
        let (backbone, speech) = match self.parameter_residency {
            ParameterResidency::Resident => {
                (ResidencyPlan::FullyResident, ResidencyPlan::FullyResident)
            }
            ParameterResidency::Host {
                backbone_device_bytes,
                backbone_host_bytes,
                speech_device_bytes,
                speech_host_bytes,
                depth,
            } => (
                host(backbone_device_bytes, backbone_host_bytes, depth),
                host(speech_device_bytes, speech_host_bytes, depth),
            ),
            ParameterResidency::Disk {
                backbone_device_bytes,
                backbone_host_bytes,
                speech_device_bytes,
                speech_host_bytes,
            } => (
                disk(backbone_device_bytes, backbone_host_bytes),
                disk(speech_device_bytes, speech_host_bytes),
            ),
        };
        let normalize = |plan: &ResidencyPlan| {
            execution_plan_layer_residency(plan, cached_shards, ResidencyDiagnostics::default())
                .map(|residency| residency.layers())
        };
        let backbone = normalize(&backbone)?;
        let speech = normalize(&speech)?;
        let speech = SpeechResidencyPolicy::new(
            SpeechProvider::ALL
                .into_iter()
                .map(|provider| (provider, speech))
                .collect(),
            self.device_parameter_bytes,
            self.host_parameter_bytes,
        )?;
        Ok(VoiceChatResidencyPolicy::new(
            backbone,
            speech,
            self.device_parameter_bytes,
            self.host_parameter_bytes,
        ))
    }
}

pub fn load(
    factory: &impl RealtimeBackendFactory,
    config: &Config,
    quantization: oi_kit_inference_architectures::voicechat::quantization::SpeechQuantizationPolicy,
    device: &oi_kit_inference_core::DevicePlan,
    cached_shards: usize,
    sampling: AgentSamplingPolicy,
) -> Result<Box<dyn SpeechRealtimeSession>> {
    config.validate()?;
    let artifact = prepare_realtime_model(&RealtimeArtifactRequest {
        source: config.source.clone(),
        assets: RealtimeAssetDirectories {
            model: Some(config.official_assets.clone()),
            text_backbone: Some(config.base_assets.clone()),
        },
        prepared_checkpoint_cache: config.prepared_checkpoint_cache.clone(),
    })?;
    let prepared = prepare_realtime(
        factory,
        &artifact,
        &RealtimeLoadOptions::Speech(SpeechSessionOptions {
            quantization,
            conversation: start_options(config, sampling)?,
            parameters: config.residency(cached_shards)?,
            state: CacheResidencyPolicy::Device,
            max_branch_bytes: config.max_branch_bytes,
            max_total_copy_bytes: config.max_total_copy_bytes,
            seed: config.seed,
        }),
    )?;
    if let Some(report) = prepared.speech_residency_report() {
        eprintln!(
            "Planned model memory: device weights {}, host weights {}, loading workspace {}, execution cache {}",
            crate::format_memory_size(report.device_parameter_bytes),
            crate::format_memory_size(report.host_parameter_bytes),
            crate::format_memory_size(report.host_materialization_bytes),
            crate::format_memory_size(report.speech.execution_cache_device_bytes)
        );
        eprintln!(
            "Conversation history and temporary computation buffers require additional memory."
        );
    }
    match bind_realtime(prepared, device)? {
        RealtimeSession::Speech(session) => Ok(session),
        RealtimeSession::Categorical(_) => {
            anyhow::bail!("this WAV conversation command requires a VoiceChat artifact")
        }
    }
}

fn start_options(config: &Config, sampling: AgentSamplingPolicy) -> Result<VoiceChatStartOptions> {
    let frame_capacity = usize::try_from(config.max_frames)?;
    let capacity = VoiceChatPublicationCapacity {
        speech_samples: 8192,
        transcription_tokens: 128,
        agent_text_bytes: 65_536,
        transcription_text_bytes: 65_536,
        audio_codes: 128,
        tool_events: 32,
        tool_bytes: 131_072,
        diagnostics: 128,
    };
    Ok(VoiceChatStartOptions {
        speech_precision: oi_kit_inference_architectures::voicechat::precision::SpeechPrecision {
            weights: config.speech_weights.into(),
            compute: config.speech_compute.into(),
        },
        request: RequestId::new(1),
        system_prompt: config.system_prompt.clone(),
        tools: config.tools.clone(),
        acknowledgement: match &config.acknowledgement {
            Some(text) => VoiceChatPhrasePolicy::Fixed(text.clone()),
            None if config.random_acknowledgement => {
                VoiceChatPhrasePolicy::Streaming { seed: config.seed }
            }
            None => VoiceChatPhrasePolicy::Disabled,
        },
        initial_reminder: match &config.initial_reminder {
            Some(text) => VoiceChatPhrasePolicy::Fixed(text.clone()),
            None if config.random_initial_reminder => VoiceChatPhrasePolicy::Streaming {
                // Independent retained host stream, domain-separated by "REMINDER".
                seed: config.seed ^ 0x5245_4d49_4e44_4552,
            },
            None => VoiceChatPhrasePolicy::Disabled,
        },
        text_limits: VoiceChatTextLimits {
            max_bytes: 65_536,
            max_tokens: 8192,
        },
        prompt_policy: PromptPolicy {
            repeat: 1,
            max_tokens: 8194,
        },
        tool_limits: VoiceChatToolLimits {
            max_payload_tokens: 8192,
            max_payload_bytes: 65_536,
            max_calls: 8,
        },
        schedule_limits: ScheduleLimits {
            max_audio_frames: config.max_frames,
            max_backbone_positions: config
                .max_model_steps
                .checked_add(8194)
                .context("backbone position capacity overflows")?,
            max_tts_positions: config
                .max_model_steps
                .checked_add(128)
                .context("TTS position capacity overflows")?,
            max_codec_frames: config
                .max_model_steps
                .checked_add(128)
                .context("codec position capacity overflows")?,
        },
        sampling,
        turn_policy: VoiceChatTurnPolicy {
            bou_frames: config
                .interruption_speech_frames
                .unwrap_or_else(|| VoiceChatTurnPolicy::default().bou_frames),
            ..VoiceChatTurnPolicy::default()
        },
        turn_limits: VoiceChatTurnLimits {
            max_audio_frames: config.max_frames,
            max_model_steps: config.max_model_steps,
            max_history: 40,
        },
        decode_limits: VoiceChatDecodeLimits::default(),
        transcription_pending_bytes: 65_536,
        frontend: FrontendOptions::default(),
        input_config: VoiceChatInputConfig::default(),
        input_limits: PerceptionRnntLimits {
            frame_capacity: config.max_frames,
            rnnt: RnntLimits {
                max_symbols_per_frame: 10,
                hypothesis_capacity: frame_capacity
                    .checked_mul(10)
                    .context("RNNT hypothesis capacity overflows")?,
            },
        },
        max_character_cells: 65_536,
        max_prompt_positions: 37,
        publication_limits: VoiceChatPublicationLimits {
            max_publications: 1,
            capacity,
        },
        publication_capacity: capacity,
        clock_origin: Instant::now(),
        start_at: Duration::ZERO,
        speech: VoiceChatSpeechOptions {
            force_silence_on_eos: true,
            force_silence_on_pad: true,
        },
    })
}