kizzasi-inference 0.2.1

Unified autoregressive inference engine for Kizzasi AGSP
Documentation
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
//! State checkpointing and serialization
//!
//! This module provides functionality for saving and loading inference state,
//! enabling:
//! - Long-running inference sessions with state persistence
//! - State migration between processes
//! - Distributed inference with state sharding
//! - Rollback to previous states for constraint violations

use crate::context::{ContextConfig, InferenceContext};
use crate::error::{InferenceError, InferenceResult};
use kizzasi_core::HiddenState;
use scirs2_core::ndarray::Array1;
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::path::Path;

/// Version for checkpoint format (for backward compatibility)
const CHECKPOINT_VERSION: u32 = 1;

/// Serializable representation of a HiddenState
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SerializableHiddenState {
    /// Hidden dimension
    hidden_dim: usize,
    /// State dimension
    state_dim: usize,
    /// Flattened state matrix (row-major)
    state_data: Vec<f32>,
    /// Whether state has been updated
    updated: bool,
}

impl SerializableHiddenState {
    /// Convert from HiddenState
    fn from_hidden_state(hs: &HiddenState) -> Self {
        let state = hs.state();
        let shape = state.shape();
        let state_data: Vec<f32> = state.iter().copied().collect();

        Self {
            hidden_dim: shape[0],
            state_dim: shape[1],
            state_data,
            updated: true, // Assume updated if we're serializing
        }
    }

    /// Convert to HiddenState
    fn to_hidden_state(&self) -> InferenceResult<HiddenState> {
        if self.state_data.len() != self.hidden_dim * self.state_dim {
            return Err(InferenceError::DimensionMismatch {
                expected: self.hidden_dim * self.state_dim,
                got: self.state_data.len(),
            });
        }

        let mut hs = HiddenState::new(self.hidden_dim, self.state_dim);

        // Reconstruct the state matrix
        let state_array = scirs2_core::ndarray::Array2::from_shape_vec(
            (self.hidden_dim, self.state_dim),
            self.state_data.clone(),
        )
        .map_err(|e| InferenceError::SerializationError(e.to_string()))?;

        hs.update(state_array);
        Ok(hs)
    }
}

/// Checkpoint containing full inference state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Checkpoint {
    /// Checkpoint format version
    version: u32,
    /// Context configuration
    config: ContextConfig,
    /// Serialized hidden states for each layer
    states: Vec<SerializableHiddenState>,
    /// History of past inputs (flattened)
    history: Vec<Vec<f32>>,
    /// Number of steps processed
    step_count: usize,
    /// Optional metadata
    metadata: CheckpointMetadata,
}

/// Metadata for checkpoints
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CheckpointMetadata {
    /// Timestamp when checkpoint was created
    pub timestamp: u64,
    /// Optional description
    pub description: String,
    /// Model identifier
    pub model_id: String,
    /// Custom tags
    pub tags: Vec<String>,
}

impl Default for CheckpointMetadata {
    fn default() -> Self {
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0); // Fallback to 0 if system time is before UNIX_EPOCH

        Self {
            timestamp,
            description: String::new(),
            model_id: String::from("unknown"),
            tags: Vec::new(),
        }
    }
}

impl Checkpoint {
    /// Create a checkpoint from an InferenceContext
    pub fn from_context(context: &InferenceContext) -> Self {
        let states: Vec<SerializableHiddenState> = context
            .states()
            .iter()
            .map(SerializableHiddenState::from_hidden_state)
            .collect();

        let history: Vec<Vec<f32>> = context
            .recent_history(context.history_len())
            .into_iter()
            .rev() // Reverse back to chronological order
            .map(|arr| arr.iter().copied().collect())
            .collect();

        Self {
            version: CHECKPOINT_VERSION,
            config: context.config().clone(),
            states,
            history,
            step_count: context.step_count(),
            metadata: CheckpointMetadata::default(),
        }
    }

    /// Restore an InferenceContext from this checkpoint
    pub fn to_context(&self) -> InferenceResult<InferenceContext> {
        if self.version != CHECKPOINT_VERSION {
            return Err(InferenceError::SerializationError(format!(
                "Incompatible checkpoint version: expected {}, got {}",
                CHECKPOINT_VERSION, self.version
            )));
        }

        let mut context = InferenceContext::new(self.config.clone());

        // Restore states
        for (i, serialized_state) in self.states.iter().enumerate() {
            let state = serialized_state.to_hidden_state()?;
            context.update_state(i, state)?;
        }

        // Restore history
        for hist_vec in &self.history {
            let arr = Array1::from_vec(hist_vec.clone());
            context.push(arr);
        }

        // Restore step count (push increments it, so we need to adjust)
        // Actually, InferenceContext doesn't expose step_count setter, so this is handled by push

        Ok(context)
    }

    /// Set metadata
    pub fn with_metadata(mut self, metadata: CheckpointMetadata) -> Self {
        self.metadata = metadata;
        self
    }

    /// Set description
    pub fn with_description(mut self, description: String) -> Self {
        self.metadata.description = description;
        self
    }

    /// Set model ID
    pub fn with_model_id(mut self, model_id: String) -> Self {
        self.metadata.model_id = model_id;
        self
    }

    /// Add a tag
    pub fn with_tag(mut self, tag: String) -> Self {
        self.metadata.tags.push(tag);
        self
    }

    /// Get metadata
    pub fn metadata(&self) -> &CheckpointMetadata {
        &self.metadata
    }

    /// Get checkpoint version
    pub fn version(&self) -> u32 {
        self.version
    }

    /// Get step count
    pub fn step_count(&self) -> usize {
        self.step_count
    }

    /// Save checkpoint to file (JSON format)
    pub fn save_json<P: AsRef<Path>>(&self, path: P) -> InferenceResult<()> {
        let file =
            File::create(path).map_err(|e| InferenceError::SerializationError(e.to_string()))?;
        let writer = BufWriter::new(file);
        serde_json::to_writer_pretty(writer, self)
            .map_err(|e| InferenceError::SerializationError(e.to_string()))?;
        Ok(())
    }

    /// Load checkpoint from JSON file
    pub fn load_json<P: AsRef<Path>>(path: P) -> InferenceResult<Self> {
        let file =
            File::open(path).map_err(|e| InferenceError::SerializationError(e.to_string()))?;
        let reader = BufReader::new(file);
        let checkpoint = serde_json::from_reader(reader)
            .map_err(|e| InferenceError::SerializationError(e.to_string()))?;
        Ok(checkpoint)
    }

    /// Save checkpoint to file (MessagePack format - more compact)
    #[cfg(feature = "msgpack")]
    pub fn save_msgpack<P: AsRef<Path>>(&self, path: P) -> InferenceResult<()> {
        let file =
            File::create(path).map_err(|e| InferenceError::SerializationError(e.to_string()))?;
        let mut writer = BufWriter::new(file);
        rmp_serde::encode::write(&mut writer, self)
            .map_err(|e| InferenceError::SerializationError(e.to_string()))?;
        Ok(())
    }

    /// Load checkpoint from MessagePack file
    #[cfg(feature = "msgpack")]
    pub fn load_msgpack<P: AsRef<Path>>(path: P) -> InferenceResult<Self> {
        let file =
            File::open(path).map_err(|e| InferenceError::SerializationError(e.to_string()))?;
        let reader = BufReader::new(file);
        let checkpoint = rmp_serde::from_read(reader)
            .map_err(|e| InferenceError::SerializationError(e.to_string()))?;
        Ok(checkpoint)
    }

    /// Serialize to bytes
    pub fn to_bytes(&self) -> InferenceResult<Vec<u8>> {
        serde_json::to_vec(self).map_err(|e| InferenceError::SerializationError(e.to_string()))
    }

    /// Deserialize from bytes
    pub fn from_bytes(bytes: &[u8]) -> InferenceResult<Self> {
        serde_json::from_slice(bytes).map_err(|e| InferenceError::SerializationError(e.to_string()))
    }
}

/// Manager for checkpoint snapshots (for rollback)
#[derive(Debug)]
pub struct CheckpointManager {
    /// Maximum number of checkpoints to keep
    max_checkpoints: usize,
    /// Stack of checkpoints (most recent first)
    checkpoints: VecDeque<Checkpoint>,
}

impl CheckpointManager {
    /// Create a new checkpoint manager
    pub fn new(max_checkpoints: usize) -> Self {
        Self {
            max_checkpoints,
            checkpoints: VecDeque::new(),
        }
    }

    /// Save a checkpoint
    pub fn save(&mut self, checkpoint: Checkpoint) {
        if self.checkpoints.len() >= self.max_checkpoints {
            self.checkpoints.pop_back();
        }
        self.checkpoints.push_front(checkpoint);
    }

    /// Get the most recent checkpoint
    pub fn latest(&self) -> Option<&Checkpoint> {
        self.checkpoints.front()
    }

    /// Rollback to previous checkpoint
    pub fn rollback(&mut self) -> Option<Checkpoint> {
        self.checkpoints.pop_front()
    }

    /// Get checkpoint at index (0 = most recent)
    pub fn get(&self, index: usize) -> Option<&Checkpoint> {
        self.checkpoints.get(index)
    }

    /// Number of stored checkpoints
    pub fn len(&self) -> usize {
        self.checkpoints.len()
    }

    /// Check if manager is empty
    pub fn is_empty(&self) -> bool {
        self.checkpoints.is_empty()
    }

    /// Clear all checkpoints
    pub fn clear(&mut self) {
        self.checkpoints.clear();
    }
}

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

    #[test]
    fn test_checkpoint_creation() {
        let config = ContextConfig::new().num_layers(2).store_history(true);
        let mut context = InferenceContext::new(config);

        context.push(Array1::from_vec(vec![1.0, 2.0]));
        context.push(Array1::from_vec(vec![3.0, 4.0]));

        let checkpoint = Checkpoint::from_context(&context);
        assert_eq!(checkpoint.version(), CHECKPOINT_VERSION);
        assert_eq!(checkpoint.states.len(), 2);
        assert_eq!(checkpoint.history.len(), 2);
    }

    #[test]
    fn test_checkpoint_roundtrip() {
        let mut config = ContextConfig::new();
        config.num_layers = 2;
        config.hidden_dim = 4;
        config.store_history = true;
        let mut context = InferenceContext::new(config);

        context.push(Array1::from_vec(vec![1.0, 2.0]));
        context.push(Array1::from_vec(vec![3.0, 4.0]));

        let checkpoint = Checkpoint::from_context(&context);
        let restored = checkpoint.to_context().unwrap();

        assert_eq!(restored.step_count(), context.step_count());
        assert_eq!(restored.states().len(), context.states().len());
    }

    #[test]
    fn test_checkpoint_serialization() {
        let config = ContextConfig::new().num_layers(2).store_history(true);
        let mut context = InferenceContext::new(config);

        context.push(Array1::from_vec(vec![1.0]));

        let checkpoint = Checkpoint::from_context(&context);
        let bytes = checkpoint.to_bytes().unwrap();
        let restored = Checkpoint::from_bytes(&bytes).unwrap();

        assert_eq!(restored.version(), checkpoint.version());
        assert_eq!(restored.states.len(), checkpoint.states.len());
    }

    #[test]
    fn test_checkpoint_metadata() {
        let config = ContextConfig::new().num_layers(1);
        let context = InferenceContext::new(config);

        let checkpoint = Checkpoint::from_context(&context)
            .with_description("Test checkpoint".to_string())
            .with_model_id("test-model".to_string())
            .with_tag("v1".to_string());

        assert_eq!(checkpoint.metadata().description, "Test checkpoint");
        assert_eq!(checkpoint.metadata().model_id, "test-model");
        assert_eq!(checkpoint.metadata().tags, vec!["v1"]);
    }

    #[test]
    fn test_checkpoint_manager() {
        let mut manager = CheckpointManager::new(3);
        let config = ContextConfig::new().num_layers(1).store_history(true);

        // Save 5 checkpoints
        for i in 0..5 {
            let mut context = InferenceContext::new(config.clone());
            context.push(Array1::from_vec(vec![i as f32]));
            let checkpoint = Checkpoint::from_context(&context);
            manager.save(checkpoint);
        }

        // Should only keep last 3
        assert_eq!(manager.len(), 3);

        // Most recent should be step 4
        let latest = manager.latest().unwrap();
        assert_eq!(latest.history[0][0], 4.0);
    }

    #[test]
    fn test_checkpoint_rollback() {
        let mut manager = CheckpointManager::new(5);
        let config = ContextConfig::new().num_layers(1).store_history(true);

        for i in 0..3 {
            let mut context = InferenceContext::new(config.clone());
            context.push(Array1::from_vec(vec![i as f32]));
            manager.save(Checkpoint::from_context(&context));
        }

        assert_eq!(manager.len(), 3);

        let rolled_back = manager.rollback().unwrap();
        assert_eq!(rolled_back.history[0][0], 2.0);
        assert_eq!(manager.len(), 2);
    }

    #[test]
    fn test_checkpoint_file_io() {
        use std::env;

        let config = ContextConfig::new().num_layers(2).store_history(true);
        let mut context = InferenceContext::new(config);

        context.push(Array1::from_vec(vec![1.0, 2.0]));
        context.push(Array1::from_vec(vec![3.0, 4.0]));

        let checkpoint =
            Checkpoint::from_context(&context).with_description("Test save/load".to_string());

        // Save to temporary file
        let tmp_dir = env::temp_dir();
        let path = tmp_dir.join("test_checkpoint.json");

        checkpoint.save_json(&path).unwrap();

        // Load back
        let loaded = Checkpoint::load_json(&path).unwrap();
        assert_eq!(loaded.metadata().description, "Test save/load");
        assert_eq!(loaded.states.len(), 2);
        assert_eq!(loaded.history.len(), 2);

        // Cleanup
        std::fs::remove_file(path).ok();
    }
}