instmodel_inference 0.2.0

High-performance neural network inference library with instruction-based execution
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
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
//! Comprehensive tests for the InstructionModel that match the Java implementation.

use instmodel_inference::instruction_model_info::{
    ActivationInstructionInfo, AttentionInstructionInfo, CopyInstructionInfo,
    CopyMaskedInstructionInfo, DotInstructionInfo, ElemWiseAddInstructionInfo,
    ElemWiseBuffersAddInstructionInfo, ElemWiseBuffersMulInstructionInfo,
    ElemWiseMulInstructionInfo, InstructionInfo, ReduceSumInstructionInfo,
};
use instmodel_inference::{Activation, InstructionModel, InstructionModelInfo, ValidationData};

const DELTA: f32 = 0.00005;

/// Creates weights for a neural network structure with 2 input features, 2 hidden layer nodes, and 1 output node.
fn create_weights_for_complex_neural_network(
    input_size: usize,
    weights_layer0: &mut [Vec<f32>],
    weights_layer1: &mut [Vec<f32>],
    bias_layer0: &mut [f32],
    bias_layer1: &mut [f32],
) {
    // Initialize weights_layer0
    for weights_row in weights_layer0.iter_mut() {
        weights_row.resize(input_size, 0.0);
    }

    weights_layer0[0][0] = 2.0;
    weights_layer0[0][1] = 0.5;
    bias_layer0[0] = 0.25;

    // Inverse values to make calculations easier to understand
    weights_layer0[1][0] = -2.0;
    weights_layer0[1][1] = -0.5;
    bias_layer0[1] = -0.25;

    // Initialize weights_layer1
    for weights_row in weights_layer1.iter_mut() {
        weights_row.resize(weights_layer0.len(), 0.0);
    }

    weights_layer1[0][0] = 0.5;
    weights_layer1[0][1] = -1.0;
    bias_layer1[0] = 2.0;
}

#[test]
fn external_memory_management() {
    let layer_sizes = vec![2, 1];
    let weights = vec![vec![0.0; layer_sizes[0]]; layer_sizes[1]];
    let bias = vec![0.0; layer_sizes[1]];

    let model_info = InstructionModelInfo {
        features: Some(vec!["feature1".to_string(), "feature2".to_string()]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes.clone(),
        instructions: vec![InstructionInfo::Dot(DotInstructionInfo {
            input: 0,
            output: 1,
            weights: 0,
            activation: None,
        })],
        weights: vec![weights],
        bias: vec![bias],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");

    // Test that we need a computation buffer
    let result = model.predict(&[1.0, -1.0]);
    assert!(
        result.is_ok(),
        "Prediction should work with internal buffer allocation"
    );
}

#[test]
fn one_forward_pass() {
    let layer_sizes = vec![2, 1];
    let mut weights = vec![vec![0.0; layer_sizes[0]]; layer_sizes[1]];
    let mut bias = vec![0.0; layer_sizes[1]];

    weights[0][0] = 2.0;
    weights[0][1] = 0.5;
    bias[0] = 0.25;

    let model_info = InstructionModelInfo {
        features: Some(vec!["feature1".to_string(), "feature2".to_string()]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes.clone(),
        instructions: vec![InstructionInfo::Dot(DotInstructionInfo {
            input: 0,
            output: 1,
            weights: 0,
            activation: None,
        })],
        weights: vec![weights],
        bias: vec![bias],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");

    let inputs = vec![1.0, -1.0];
    let result = model
        .predict_single(&inputs)
        .expect("Prediction should succeed");
    // 1 * 2 - 1 * 0.5 + 0.25 = 1.75
    assert!((result - 1.75).abs() < DELTA);

    let inputs2 = vec![-1.0, 1.0];
    let result2 = model
        .predict_single(&inputs2)
        .expect("Prediction should succeed");
    // -1 * 2 + 1 * 0.5 + 0.25 = -1.25
    assert!((result2 - (-1.25)).abs() < DELTA);
}

#[test]
fn activation_layers() {
    let layer_sizes = vec![3];

    // Test RELU
    let model_info = InstructionModelInfo {
        features: Some(vec!["f1".to_string(), "f2".to_string(), "f3".to_string()]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes.clone(),
        instructions: vec![InstructionInfo::Activation(ActivationInstructionInfo {
            input: 0,
            activation: Activation::Relu,
        })],
        weights: vec![],
        bias: vec![],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");
    let inputs = vec![1.0, -1.0, 0.5];
    let outputs = model.predict(&inputs).expect("Prediction should succeed");
    assert!((outputs[0] - 1.0).abs() < DELTA);
    assert!((outputs[1] - 0.0).abs() < DELTA);
    assert!((outputs[2] - 0.5).abs() < DELTA);

    // Test SIGMOID
    let model_info = InstructionModelInfo {
        features: Some(vec!["f1".to_string(), "f2".to_string(), "f3".to_string()]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes.clone(),
        instructions: vec![InstructionInfo::Activation(ActivationInstructionInfo {
            input: 0,
            activation: Activation::Sigmoid,
        })],
        weights: vec![],
        bias: vec![],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");
    let inputs = vec![1.0, 0.0, -0.5];
    let outputs = model.predict(&inputs).expect("Prediction should succeed");
    assert!((outputs[0] - 0.7311).abs() < DELTA);
    assert!((outputs[1] - 0.5).abs() < DELTA);
    assert!((outputs[2] - 0.3775).abs() < DELTA);

    // Test SOFTMAX
    let model_info = InstructionModelInfo {
        features: Some(vec!["f1".to_string(), "f2".to_string(), "f3".to_string()]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes.clone(),
        instructions: vec![InstructionInfo::Activation(ActivationInstructionInfo {
            input: 0,
            activation: Activation::Softmax,
        })],
        weights: vec![],
        bias: vec![],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");
    let inputs = vec![1.0, 2.0, 3.0];
    let outputs = model.predict(&inputs).expect("Prediction should succeed");
    assert!((outputs[0] - 0.09003057).abs() < DELTA);
    assert!((outputs[1] - 0.24472847).abs() < DELTA);
    assert!((outputs[2] - 0.66524096).abs() < DELTA);
}

#[test]
fn copy_layers() {
    let layer_sizes = vec![2, 2, 6, 6];

    let instructions = vec![
        InstructionInfo::Copy(CopyInstructionInfo {
            input: 0,
            output: 1,
            internal_index: 0,
        }),
        InstructionInfo::Copy(CopyInstructionInfo {
            input: 0,
            output: 2,
            internal_index: 0,
        }),
        InstructionInfo::Activation(ActivationInstructionInfo {
            input: 0,
            activation: Activation::Sigmoid,
        }),
        InstructionInfo::Activation(ActivationInstructionInfo {
            input: 1,
            activation: Activation::Relu,
        }),
        InstructionInfo::Copy(CopyInstructionInfo {
            input: 0,
            output: 2,
            internal_index: 4,
        }),
        InstructionInfo::Copy(CopyInstructionInfo {
            input: 1,
            output: 2,
            internal_index: 2,
        }),
        InstructionInfo::Copy(CopyInstructionInfo {
            input: 2,
            output: 3,
            internal_index: 0,
        }),
    ];

    let model_info = InstructionModelInfo {
        features: Some(vec!["feature1".to_string(), "feature2".to_string()]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes,
        instructions,
        weights: vec![],
        bias: vec![],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");
    let inputs = vec![1.0, -1.0];
    let result = model.predict(&inputs).expect("Prediction should succeed");

    // The final result should be the copied values from layer 2 to layer 3
    // Based on the debug output, the final result contains the complete layer 2 content:
    // [original inputs, relu results, sigmoid results]
    assert!((result[0] - 1.0).abs() < DELTA); // Copy of original input[0] 
    assert!((result[1] - (-1.0)).abs() < DELTA); // Copy of original input[1]
    assert!((result[2] - 1.0).abs() < DELTA); // Copy of ReLU input[0] = max(0, 1) = 1
    assert!((result[3] - 0.0).abs() < DELTA); // Copy of ReLU input[1] = max(0, -1) = 0
    assert!((result[4] - 0.7311).abs() < DELTA); // Copy of sigmoid input[0]
    assert!((result[5] - 0.2689).abs() < DELTA); // Copy of sigmoid input[1]
}

#[test]
fn copy_masked_layers() {
    let layer_sizes = vec![3, 3, 2, 3];

    let instructions = vec![
        InstructionInfo::CopyMasked(CopyMaskedInstructionInfo {
            input: 0,
            output: 1,
            indexes: vec![1, 2, 0],
        }),
        InstructionInfo::CopyMasked(CopyMaskedInstructionInfo {
            input: 1,
            output: 2,
            indexes: vec![1, 0],
        }),
        InstructionInfo::CopyMasked(CopyMaskedInstructionInfo {
            input: 0,
            output: 3,
            indexes: vec![2, 0, 1],
        }),
    ];

    let model_info = InstructionModelInfo {
        features: Some(vec!["f1".to_string(), "f2".to_string(), "f3".to_string()]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes,
        instructions,
        weights: vec![],
        bias: vec![],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");
    let inputs = vec![1.0, -1.0, 2.0];
    let result = model.predict(&inputs).expect("Prediction should succeed");

    // Verify masked copy results
    assert!((result[0] - 2.0).abs() < DELTA); // Copy of original [2]
    assert!((result[1] - 1.0).abs() < DELTA); // Copy of original [0]
}

#[test]
fn element_wise() {
    let layer_sizes = vec![3, 3, 3];

    let parameters = vec![
        vec![-1.0, 0.0, 1.0],
        vec![5.0, 2.0, 2.0],
        vec![-1.0, 3.0, 1.5],
    ];

    let instructions = vec![
        InstructionInfo::ElemWiseAdd(ElemWiseAddInstructionInfo {
            input: 0,
            parameters: 0,
        }),
        InstructionInfo::Copy(CopyInstructionInfo {
            input: 0,
            output: 1,
            internal_index: 0,
        }),
        InstructionInfo::ElemWiseMul(ElemWiseMulInstructionInfo {
            input: 1,
            parameters: 1,
        }),
        InstructionInfo::Copy(CopyInstructionInfo {
            input: 1,
            output: 2,
            internal_index: 0,
        }),
        InstructionInfo::ElemWiseAdd(ElemWiseAddInstructionInfo {
            input: 2,
            parameters: 2,
        }),
        InstructionInfo::Activation(ActivationInstructionInfo {
            input: 2,
            activation: Activation::Relu,
        }),
    ];

    let model_info = InstructionModelInfo {
        features: Some(vec!["f1".to_string(), "f2".to_string(), "f3".to_string()]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes,
        instructions,
        weights: vec![],
        bias: vec![],
        parameters: Some(parameters),
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");
    let inputs = vec![1.0, -1.0, 0.0];
    let result = model.predict(&inputs).expect("Prediction should succeed");

    // After element-wise operations and relu
    assert!((result[0] - 0.0).abs() < DELTA);
    assert!((result[1] - 1.0).abs() < DELTA);
    assert!((result[2] - 3.5).abs() < DELTA);
}

#[test]
fn element_wise_buffers() {
    let layer_sizes = vec![3, 3, 3, 3];

    let instructions = vec![
        InstructionInfo::ElemWiseBuffersAdd(ElemWiseBuffersAddInstructionInfo {
            input: vec![0, 1],
            output: 2,
        }),
        InstructionInfo::ElemWiseBuffersMul(ElemWiseBuffersMulInstructionInfo {
            input: vec![0, 1],
            output: 3,
        }),
    ];

    let model_info = InstructionModelInfo {
        features: Some(vec![
            "f1".to_string(),
            "f2".to_string(),
            "f3".to_string(),
            "f4".to_string(),
            "f5".to_string(),
            "f6".to_string(),
        ]),
        feature_size: Some(6),
        computation_buffer_sizes: layer_sizes,
        instructions,
        weights: vec![],
        bias: vec![],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");
    let inputs = vec![1.0, 0.0, 0.5, -4.0, 3.5, -5.0];
    let result = model.predict(&inputs).expect("Prediction should succeed");

    // The final result contains the multiplication results from layer 3 (the last layer)
    // Layer 0: [1.0, 0.0, 0.5], Layer 1: [-4.0, 3.5, -5.0]
    // Layer 2 (addition): [-3.0, 3.5, -4.5]
    // Layer 3 (multiplication): [1.0*(-4.0), 0.0*3.5, 0.5*(-5.0)] = [-4.0, 0.0, -2.5]
    assert!((result[0] - (-4.0)).abs() < DELTA); // 1.0 * (-4.0) = -4.0
    assert!((result[1] - 0.0).abs() < DELTA); // 0.0 * 3.5 = 0.0  
    assert!((result[2] - (-2.5)).abs() < DELTA); // 0.5 * (-5.0) = -2.5
}

#[test]
fn complex_neural_network() {
    let layer_sizes = vec![2, 2, 1];
    let mut weights_layer0 = vec![vec![0.0; 2]; 2];
    let mut bias_layer0 = vec![0.0; 2];
    let mut weights_layer1 = vec![vec![0.0; 2]; 1];
    let mut bias_layer1 = vec![0.0; 1];

    create_weights_for_complex_neural_network(
        layer_sizes[0],
        &mut weights_layer0,
        &mut weights_layer1,
        &mut bias_layer0,
        &mut bias_layer1,
    );

    let instructions = vec![
        InstructionInfo::Dot(DotInstructionInfo {
            input: 0,
            output: 1,
            weights: 0,
            activation: Some(Activation::Relu),
        }),
        InstructionInfo::Dot(DotInstructionInfo {
            input: 1,
            output: 2,
            weights: 1,
            activation: Some(Activation::Sigmoid),
        }),
    ];

    let model_info = InstructionModelInfo {
        features: Some(vec!["feature1".to_string(), "feature2".to_string()]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes,
        instructions,
        weights: vec![weights_layer0, weights_layer1],
        bias: vec![bias_layer0, bias_layer1],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");
    let inputs = vec![1.0, -1.0];
    let result = model
        .predict_single(&inputs)
        .expect("Prediction should succeed");

    // result = sigmoid(relu(1 * 2 - 1 * 0.5 + 0.25) * 0.5 + relu(-1 * 2 + 1 * 0.5 - 0.25) * (-1) + 2)
    // = sigmoid(relu(1.75) * 0.5 + relu(-1.75) * (-1) + 2)
    // = sigmoid(1.75 * 0.5 + 0 * (-1) + 2) = sigmoid(2.875)
    assert!((result - 0.9466).abs() < DELTA);
}

#[test]
fn test_feature_size_calculation() {
    // Test with explicit features
    let model_info = InstructionModelInfo {
        features: Some(vec![
            "feature1".to_string(),
            "feature2[3]".to_string(),
            "feature3".to_string(),
        ]),
        feature_size: None,
        computation_buffer_sizes: vec![5],
        instructions: vec![],
        weights: vec![],
        bias: vec![],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let result = InstructionModel::calculate_feature_size(&model_info).unwrap();
    assert_eq!(result, 5); // 1 + 3 + 1

    // Test with feature size only
    let model_info2 = InstructionModelInfo {
        features: None,
        feature_size: Some(10),
        computation_buffer_sizes: vec![10],
        instructions: vec![],
        weights: vec![],
        bias: vec![],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let result2 = InstructionModel::calculate_feature_size(&model_info2).unwrap();
    assert_eq!(result2, 10);
}

#[test]
fn test_validation() {
    let layer_sizes = vec![2, 1];
    let mut weights = vec![vec![0.0; 2]; 1];
    let mut bias = vec![0.0; 1];

    weights[0][0] = 2.0;
    weights[0][1] = 0.5;
    bias[0] = 0.25;

    let validation_data = ValidationData {
        inputs: vec![vec![1.0, -1.0], vec![-1.0, 1.0]],
        expected_outputs: vec![vec![1.75], vec![-1.25]],
    };

    let model_info = InstructionModelInfo {
        features: Some(vec!["feature1".to_string(), "feature2".to_string()]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes,
        instructions: vec![InstructionInfo::Dot(DotInstructionInfo {
            input: 0,
            output: 1,
            weights: 0,
            activation: None,
        })],
        weights: vec![weights],
        bias: vec![bias],
        parameters: None,
        maps: None,
        validation_data: Some(validation_data),
    };

    // This should not panic since validation should pass
    let model = InstructionModel::new(model_info);
    assert!(
        model.is_ok(),
        "Model with valid validation data should be created successfully"
    );
}

#[test]
fn reduce_sum_layer() {
    // Test REDUCE_SUM: sums all values in a buffer to a single value
    let layer_sizes = vec![4, 1];

    let instructions = vec![InstructionInfo::ReduceSum(ReduceSumInstructionInfo {
        input: 0,
        output: 1,
    })];

    let model_info = InstructionModelInfo {
        features: Some(vec![
            "f1".to_string(),
            "f2".to_string(),
            "f3".to_string(),
            "f4".to_string(),
        ]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes,
        instructions,
        weights: vec![],
        bias: vec![],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");

    // Test case 1: positive values
    let inputs = vec![1.0, 2.0, 3.0, 4.0];
    let result = model
        .predict_single(&inputs)
        .expect("Prediction should succeed");
    assert!((result - 10.0).abs() < DELTA); // 1 + 2 + 3 + 4 = 10

    // Test case 2: mixed values
    let inputs2 = vec![1.0, -2.0, 3.0, -4.0];
    let result2 = model
        .predict_single(&inputs2)
        .expect("Prediction should succeed");
    assert!((result2 - (-2.0)).abs() < DELTA); // 1 - 2 + 3 - 4 = -2
}

#[test]
fn reduce_sum_in_pipeline() {
    // Test REDUCE_SUM as part of a larger pipeline
    let layer_sizes = vec![3, 3, 1];

    let instructions = vec![
        // First apply element-wise operations
        InstructionInfo::Activation(ActivationInstructionInfo {
            input: 0,
            activation: Activation::Relu,
        }),
        InstructionInfo::Copy(CopyInstructionInfo {
            input: 0,
            output: 1,
            internal_index: 0,
        }),
        // Then reduce sum
        InstructionInfo::ReduceSum(ReduceSumInstructionInfo {
            input: 1,
            output: 2,
        }),
    ];

    let model_info = InstructionModelInfo {
        features: Some(vec!["f1".to_string(), "f2".to_string(), "f3".to_string()]),
        feature_size: None,
        computation_buffer_sizes: layer_sizes,
        instructions,
        weights: vec![],
        bias: vec![],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");

    // Input with negative values that ReLU will zero out
    let inputs = vec![2.0, -1.0, 3.0];
    let result = model
        .predict_single(&inputs)
        .expect("Prediction should succeed");
    // After ReLU: [2.0, 0.0, 3.0], sum = 5.0
    assert!((result - 5.0).abs() < DELTA);
}

#[test]
fn attention_layer() {
    // Test ATTENTION instruction
    // Attention: linear transform on key -> softmax -> element-wise multiply with query
    let layer_sizes = vec![2, 2, 2];

    // Identity weights so linear transform preserves values
    let weights = vec![vec![1.0, 0.0], vec![0.0, 1.0]];
    let bias = vec![0.0, 0.0];

    let instructions = vec![InstructionInfo::Attention(AttentionInstructionInfo {
        input: 0,  // query buffer
        key: 1,    // key buffer
        output: 2, // output buffer
        weights: 0,
    })];

    let model_info = InstructionModelInfo {
        features: Some(vec![
            "q1".to_string(),
            "q2".to_string(),
            "k1".to_string(),
            "k2".to_string(),
        ]),
        feature_size: Some(4),
        computation_buffer_sizes: layer_sizes,
        instructions,
        weights: vec![weights],
        bias: vec![bias],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");

    // Query: [1.0, 2.0], Key: [0.0, 0.0]
    // Linear on key: [0.0, 0.0]
    // Softmax([0.0, 0.0]) = [0.5, 0.5]
    // Element-wise multiply: [0.5 * 1.0, 0.5 * 2.0] = [0.5, 1.0]
    let inputs = vec![1.0, 2.0, 0.0, 0.0];
    let result = model.predict(&inputs).expect("Prediction should succeed");
    assert!((result[0] - 0.5).abs() < DELTA);
    assert!((result[1] - 1.0).abs() < DELTA);
}

#[test]
fn attention_with_weighted_transform() {
    // Test ATTENTION with non-identity weights
    let layer_sizes = vec![2, 2, 2];

    // Weights that scale and shift
    let weights = vec![vec![2.0, 0.0], vec![0.0, 1.0]];
    let bias = vec![1.0, -1.0];

    let instructions = vec![InstructionInfo::Attention(AttentionInstructionInfo {
        input: 0,
        key: 1,
        output: 2,
        weights: 0,
    })];

    let model_info = InstructionModelInfo {
        features: Some(vec![
            "q1".to_string(),
            "q2".to_string(),
            "k1".to_string(),
            "k2".to_string(),
        ]),
        feature_size: Some(4),
        computation_buffer_sizes: layer_sizes,
        instructions,
        weights: vec![weights],
        bias: vec![bias],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");

    // Query: [1.0, 1.0], Key: [1.0, 1.0]
    // Linear on key: [2.0*1.0 + 0.0*1.0 + 1.0, 0.0*1.0 + 1.0*1.0 - 1.0] = [3.0, 0.0]
    // Softmax([3.0, 0.0]): exp(3-3)/(exp(0)+exp(-3)), exp(0-3)/(exp(0)+exp(-3))
    let exp_0 = 1.0f32;
    let exp_neg3 = (-3.0f32).exp();
    let sum = exp_0 + exp_neg3;
    let softmax_0 = exp_0 / sum;
    let softmax_1 = exp_neg3 / sum;

    let inputs = vec![1.0, 1.0, 1.0, 1.0];
    let result = model.predict(&inputs).expect("Prediction should succeed");

    // Element-wise multiply: [softmax_0 * 1.0, softmax_1 * 1.0]
    assert!((result[0] - softmax_0).abs() < DELTA);
    assert!((result[1] - softmax_1).abs() < DELTA);
}

#[test]
fn attention_in_complex_pipeline() {
    // Test ATTENTION combined with other operations
    let layer_sizes = vec![3, 3, 3, 1];

    let weights = vec![
        vec![1.0, 0.0, 0.0],
        vec![0.0, 1.0, 0.0],
        vec![0.0, 0.0, 1.0],
    ];
    let bias = vec![0.0, 0.0, 0.0];

    let instructions = vec![
        // First, attention between query and key
        InstructionInfo::Attention(AttentionInstructionInfo {
            input: 0,
            key: 1,
            output: 2,
            weights: 0,
        }),
        // Then reduce sum the attention output
        InstructionInfo::ReduceSum(ReduceSumInstructionInfo {
            input: 2,
            output: 3,
        }),
    ];

    let model_info = InstructionModelInfo {
        features: Some(vec![
            "q1".to_string(),
            "q2".to_string(),
            "q3".to_string(),
            "k1".to_string(),
            "k2".to_string(),
            "k3".to_string(),
        ]),
        feature_size: Some(6),
        computation_buffer_sizes: layer_sizes,
        instructions,
        weights: vec![weights],
        bias: vec![bias],
        parameters: None,
        maps: None,
        validation_data: None,
    };

    let model = InstructionModel::new(model_info).expect("Model creation should succeed");

    // Query: [1.0, 2.0, 3.0], Key: [0.0, 0.0, 0.0]
    // Linear on key: [0.0, 0.0, 0.0]
    // Softmax: [1/3, 1/3, 1/3]
    // Element-wise: [1/3 * 1.0, 1/3 * 2.0, 1/3 * 3.0] = [1/3, 2/3, 1.0]
    // Reduce sum: 1/3 + 2/3 + 1.0 = 2.0
    let inputs = vec![1.0, 2.0, 3.0, 0.0, 0.0, 0.0];
    let result = model
        .predict_single(&inputs)
        .expect("Prediction should succeed");
    assert!((result - 2.0).abs() < DELTA);
}