cortex_rust 0.6.0

High-performance LLM inference with 4-bit quantization and Test-Time Training (TTT)
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
//! Tests for TTTLayer - Test-Time Training with Online Learning

#[cfg(test)]
mod tests {
    use crate::layers::{AdaptiveBitLinear, BitLinear, TTTLayer};
    use candle_core::{DType, Device, Tensor};

    /// Helper to create a TTTLayer with mock weights (direct construction)
    fn create_test_ttt_layer(hidden_dim: usize, inner_lr: f64) -> candle_core::Result<TTTLayer> {
        let device = Device::Cpu;
        let d_small = hidden_dim / 4;

        // Create down projection with BitLinear
        let down_weight = Tensor::randn(0.0f32, 0.1, (d_small, hidden_dim), &device)?;
        let proj_down = AdaptiveBitLinear {
            legacy_linear: Some(BitLinear {
                weight: down_weight,
                in_features: hidden_dim,
                out_features: d_small,
                packed_params: None,
            }),
            linear_4bit: None,
            reconstructed_weight: None,
            in_features: hidden_dim,
            out_features: d_small,
        };

        // Create up projection with BitLinear
        let up_weight = Tensor::randn(0.0f32, 0.1, (hidden_dim, d_small), &device)?;
        let proj_up = AdaptiveBitLinear {
            legacy_linear: Some(BitLinear {
                weight: up_weight,
                in_features: d_small,
                out_features: hidden_dim,
                packed_params: None,
            }),
            linear_4bit: None,
            reconstructed_weight: None,
            in_features: d_small,
            out_features: hidden_dim,
        };

        Ok(TTTLayer {
            hidden_dim,
            d_small,
            proj_down,
            proj_up,
            inner_lr,
        })
    }

    /// Helper to create initial w_state (identity-like matrix)
    fn create_initial_w_state(d_small: usize, batch_size: usize) -> candle_core::Result<Tensor> {
        let device = Device::Cpu;
        // Start with small identity-like initialization
        let eye = Tensor::eye(d_small, DType::F32, &device)?;
        let eye_scaled = (eye * 0.1)?;

        // Expand to batch: [B, D_small, D_small]
        if batch_size > 1 {
            eye_scaled
                .unsqueeze(0)?
                .expand((batch_size, d_small, d_small))
        } else {
            eye_scaled.unsqueeze(0)
        }
    }

    #[test]
    fn test_ttt_forward_update_basic() -> anyhow::Result<()> {
        let device = Device::Cpu;
        let hidden_dim = 64;
        let d_small = hidden_dim / 4; // 16
        let inner_lr = 0.01;
        let batch_size = 2;

        let ttt = create_test_ttt_layer(hidden_dim, inner_lr)?;

        // Create initial w_state [B, D_small, D_small]
        let w_state = create_initial_w_state(d_small, batch_size)?;

        // Create input x_t [B, Hidden]
        let x_t = Tensor::randn(0.0f32, 1.0, (batch_size, hidden_dim), &device)?;

        // Forward update
        let (output, w_new) = ttt.forward_update(&w_state, &x_t)?;

        // Verify output shape [B, Hidden]
        assert_eq!(
            output.dims(),
            &[batch_size, hidden_dim],
            "Output shape mismatch"
        );

        // Verify w_state shape unchanged [B, D_small, D_small]
        assert_eq!(
            w_new.dims(),
            &[batch_size, d_small, d_small],
            "W_state shape mismatch"
        );

        Ok(())
    }

    #[test]
    fn test_ttt_w_state_update() -> anyhow::Result<()> {
        let device = Device::Cpu;
        let hidden_dim = 64;
        let d_small = hidden_dim / 4;
        let inner_lr = 0.1; // Higher LR to see changes
        let batch_size = 1;

        let ttt = create_test_ttt_layer(hidden_dim, inner_lr)?;

        // Create initial w_state
        let w_state = create_initial_w_state(d_small, batch_size)?;
        let w_state_initial = w_state.clone();

        // Create input
        let x_t = Tensor::randn(0.0f32, 1.0, (batch_size, hidden_dim), &device)?;

        // Forward update
        let (_output, w_new) = ttt.forward_update(&w_state, &x_t)?;

        // W_state should be updated (different from initial)
        let diff = (&w_new - &w_state_initial)?
            .abs()?
            .sum_all()?
            .to_scalar::<f32>()?;
        assert!(
            diff > 1e-6,
            "W_state should be updated after forward_update, diff: {}",
            diff
        );

        Ok(())
    }

    #[test]
    fn test_ttt_sequential_updates() -> anyhow::Result<()> {
        let device = Device::Cpu;
        let hidden_dim = 64;
        let d_small = hidden_dim / 4;
        let inner_lr = 0.01;
        let batch_size = 1;

        let ttt = create_test_ttt_layer(hidden_dim, inner_lr)?;

        // Initial w_state
        let mut w_state = create_initial_w_state(d_small, batch_size)?;
        let w_initial = w_state.clone();

        // Process multiple tokens sequentially
        for _t in 0..5 {
            let x_t = Tensor::randn(0.0f32, 1.0, (batch_size, hidden_dim), &device)?;
            let (_output, w_new) = ttt.forward_update(&w_state, &x_t)?;
            w_state = w_new;
        }

        // W_state should have diverged from initial
        let total_diff = (&w_state - &w_initial)?
            .abs()?
            .sum_all()?
            .to_scalar::<f32>()?;
        assert!(
            total_diff > 0.0,
            "W_state should change over multiple updates"
        );

        Ok(())
    }

    #[test]
    fn test_ttt_forward_chunkwise_basic() -> anyhow::Result<()> {
        let device = Device::Cpu;
        let hidden_dim = 64;
        let d_small = hidden_dim / 4;
        let inner_lr = 0.01;
        let batch_size = 2;
        let seq_len = 16;
        let chunk_size = 4;

        let ttt = create_test_ttt_layer(hidden_dim, inner_lr)?;

        // Create initial w_state [B, D_small, D_small]
        let w_state = create_initial_w_state(d_small, batch_size)?;

        // Create input x [B, T, Hidden]
        let x = Tensor::randn(0.0f32, 1.0, (batch_size, seq_len, hidden_dim), &device)?;

        // Forward chunkwise
        let (output, w_final) = ttt.forward_chunkwise(&w_state, &x, chunk_size)?;

        // Verify output shape [B, T, Hidden]
        assert_eq!(
            output.dims(),
            &[batch_size, seq_len, hidden_dim],
            "Chunkwise output shape mismatch"
        );

        // Verify w_final shape [B, D_small, D_small]
        assert_eq!(
            w_final.dims(),
            &[batch_size, d_small, d_small],
            "W_final shape mismatch"
        );

        Ok(())
    }

    #[test]
    fn test_ttt_chunkwise_different_chunk_sizes() -> anyhow::Result<()> {
        let device = Device::Cpu;
        let hidden_dim = 64;
        let d_small = hidden_dim / 4;
        let inner_lr = 0.01;
        let batch_size = 1;
        let seq_len = 12;

        let ttt = create_test_ttt_layer(hidden_dim, inner_lr)?;

        // Test various chunk sizes
        for chunk_size in [1, 3, 4, 6, 12] {
            let w_state = create_initial_w_state(d_small, batch_size)?;
            let x = Tensor::randn(0.0f32, 1.0, (batch_size, seq_len, hidden_dim), &device)?;

            let (output, w_final) = ttt.forward_chunkwise(&w_state, &x, chunk_size)?;

            assert_eq!(
                output.dims(),
                &[batch_size, seq_len, hidden_dim],
                "Output shape mismatch for chunk_size={}",
                chunk_size
            );
            assert_eq!(
                w_final.dims(),
                &[batch_size, d_small, d_small],
                "W_final shape mismatch for chunk_size={}",
                chunk_size
            );
        }

        Ok(())
    }

    #[test]
    fn test_ttt_chunkwise_non_divisible_seq_len() -> anyhow::Result<()> {
        let device = Device::Cpu;
        let hidden_dim = 64;
        let d_small = hidden_dim / 4;
        let inner_lr = 0.01;
        let batch_size = 1;
        let seq_len = 17; // Not divisible by chunk_size
        let chunk_size = 4;

        let ttt = create_test_ttt_layer(hidden_dim, inner_lr)?;

        let w_state = create_initial_w_state(d_small, batch_size)?;
        let x = Tensor::randn(0.0f32, 1.0, (batch_size, seq_len, hidden_dim), &device)?;

        // Should handle non-divisible sequence length
        let (output, w_final) = ttt.forward_chunkwise(&w_state, &x, chunk_size)?;

        assert_eq!(
            output.dims(),
            &[batch_size, seq_len, hidden_dim],
            "Output should handle non-divisible seq_len"
        );
        assert_eq!(w_final.dims(), &[batch_size, d_small, d_small]);

        Ok(())
    }

    #[test]
    fn test_ttt_chunkwise_w_state_evolves() -> anyhow::Result<()> {
        let device = Device::Cpu;
        let hidden_dim = 64;
        let d_small = hidden_dim / 4;
        let inner_lr = 0.1;
        let batch_size = 1;
        let seq_len = 8;
        let chunk_size = 2;

        let ttt = create_test_ttt_layer(hidden_dim, inner_lr)?;

        let w_state = create_initial_w_state(d_small, batch_size)?;
        let w_initial = w_state.clone();
        let x = Tensor::randn(0.0f32, 1.0, (batch_size, seq_len, hidden_dim), &device)?;

        let (_output, w_final) = ttt.forward_chunkwise(&w_state, &x, chunk_size)?;

        // W_state should evolve through chunks
        let diff = (&w_final - &w_initial)?
            .abs()?
            .sum_all()?
            .to_scalar::<f32>()?;
        assert!(
            diff > 0.0,
            "W_state should change through chunkwise processing"
        );

        Ok(())
    }

    #[test]
    fn test_ttt_output_finite() -> anyhow::Result<()> {
        let device = Device::Cpu;
        let hidden_dim = 64;
        let d_small = hidden_dim / 4;
        let inner_lr = 0.01;
        let batch_size = 2;

        let ttt = create_test_ttt_layer(hidden_dim, inner_lr)?;

        let w_state = create_initial_w_state(d_small, batch_size)?;
        let x_t = Tensor::randn(0.0f32, 1.0, (batch_size, hidden_dim), &device)?;

        let (output, w_new) = ttt.forward_update(&w_state, &x_t)?;

        // Check all values are finite
        let output_vec: Vec<f32> = output.flatten_all()?.to_vec1()?;
        for val in &output_vec {
            assert!(val.is_finite(), "Output contains non-finite value: {}", val);
        }

        let w_vec: Vec<f32> = w_new.flatten_all()?.to_vec1()?;
        for val in &w_vec {
            assert!(val.is_finite(), "W_new contains non-finite value: {}", val);
        }

        Ok(())
    }

    #[test]
    fn test_ttt_precompute_packed() -> anyhow::Result<()> {
        let hidden_dim = 64;
        let inner_lr = 0.01;

        let mut ttt = create_test_ttt_layer(hidden_dim, inner_lr)?;

        // Should not panic
        ttt.precompute_packed()?;

        // Layer should still work after packing
        let device = Device::Cpu;
        let d_small = hidden_dim / 4;
        let w_state = create_initial_w_state(d_small, 1)?;
        let x_t = Tensor::randn(0.0f32, 1.0, (1, hidden_dim), &device)?;

        let (output, _w_new) = ttt.forward_update(&w_state, &x_t)?;
        assert_eq!(output.dims(), &[1, hidden_dim]);

        Ok(())
    }

    #[test]
    fn test_ttt_different_learning_rates() -> anyhow::Result<()> {
        let device = Device::Cpu;
        let hidden_dim = 64;
        let d_small = hidden_dim / 4;
        let batch_size = 1;

        // Same input for both
        let x_t = Tensor::randn(0.0f32, 1.0, (batch_size, hidden_dim), &device)?;

        // Low learning rate
        let ttt_low = create_test_ttt_layer(hidden_dim, 0.001)?;
        let w_state_low = create_initial_w_state(d_small, batch_size)?;
        let (_out_low, w_low) = ttt_low.forward_update(&w_state_low, &x_t)?;

        // High learning rate
        let ttt_high = create_test_ttt_layer(hidden_dim, 0.1)?;
        let w_state_high = create_initial_w_state(d_small, batch_size)?;
        let (_out_high, w_high) = ttt_high.forward_update(&w_state_high, &x_t)?;

        // Higher LR should cause larger change from initial
        let w_initial = create_initial_w_state(d_small, batch_size)?;
        let diff_low = (&w_low - &w_initial)?
            .abs()?
            .sum_all()?
            .to_scalar::<f32>()?;
        let diff_high = (&w_high - &w_initial)?
            .abs()?
            .sum_all()?
            .to_scalar::<f32>()?;

        // Note: Due to different random weights in layers, we just check both run
        // The key point is that both learning rates work without errors
        assert!(diff_low >= 0.0, "Low LR diff should be valid");
        assert!(diff_high >= 0.0, "High LR diff should be valid");

        println!(
            "Low LR update magnitude: {}, High LR update magnitude: {}",
            diff_low, diff_high
        );

        Ok(())
    }

    #[test]
    fn test_ttt_chunkwise_single_chunk() -> anyhow::Result<()> {
        let device = Device::Cpu;
        let hidden_dim = 64;
        let d_small = hidden_dim / 4;
        let inner_lr = 0.01;
        let batch_size = 1;
        let seq_len = 4;
        let chunk_size = 8; // Larger than seq_len, so only one chunk

        let ttt = create_test_ttt_layer(hidden_dim, inner_lr)?;

        let w_state = create_initial_w_state(d_small, batch_size)?;
        let x = Tensor::randn(0.0f32, 1.0, (batch_size, seq_len, hidden_dim), &device)?;

        let (output, w_final) = ttt.forward_chunkwise(&w_state, &x, chunk_size)?;

        assert_eq!(
            output.dims(),
            &[batch_size, seq_len, hidden_dim],
            "Output shape should be correct even with single chunk"
        );
        assert_eq!(w_final.dims(), &[batch_size, d_small, d_small]);

        Ok(())
    }
}