malware-modeler 0.1.0

Train logisitic regression models for benign vs. malicious files based on byte n-grams and published research, plus related tools.
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
// SPDX-License-Identifier: Apache-2.0

use crate::Bytes;
use crate::dataset::{Dataset, TrainingData};
use crate::ftype::FileType;
use crate::hash::{FxBuildHasher, FxHashMap};
use crate::ngram::{Ngrammer, NgramsFile};
use crate::row::RowSlice;

use std::cmp::Ordering;
use std::fs::File;
use std::hash::BuildHasherDefault;
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::Path;

use anyhow::{Result, anyhow, bail, ensure};
use jiff::Timestamp;
use rand::RngExt;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};

// Adapted from https://github.com/ibnz36/lrclassifier/blob/06d136445028653af5d2061e002111ef11b14277/src/lib.rs
// Accessed 01 November 2025

/// The sigmoid function.
#[inline]
#[must_use]
fn sigmoid(x: f32) -> f32 {
    1.0 / (1.0 + (-x).exp())
}

/// Weights per rayon task when applying the regularization decay.
///
/// Large enough that the per-task overhead is negligible next to the work, small enough to
/// keep every core busy for the feature counts this crate produces.
const WEIGHT_CHUNK: usize = 8192;

/// Margin keeping the log-loss away from `ln(0)`.
///
/// This has to be representable in `f32`: the spacing below 1.0 is about 6e-8, so a margin
/// of 1e-8 rounds `1.0 - margin` straight back to 1.0 and the clamp does nothing. A
/// saturated prediction then reached `ln(0)`, making the reported loss `NaN` or infinite.
const LOSS_EPSILON: f32 = 1e-6;

/// Row count above which training reports progress.
///
/// Small enough that any run worth watching shows a bar, large enough that the tests and any
/// toy dataset stay quiet.
const PROGRESS_MIN_ROWS: usize = 4096;

/// Samples between progress bar updates, so the bar costs nothing per sample.
const PROGRESS_UPDATE_SAMPLES: u64 = 4096;

/// Compile-time guard that [`LOSS_EPSILON`] survives `f32` rounding, which a 1e-8 margin
/// does not.
const _: () = assert!(1.0 - LOSS_EPSILON < 1.0);

/// Template for the training progress bar.
///
/// A named constant so a test can check it parses: an invalid template falls back to a default
/// bar that has no `{msg}`, which loses the epoch and loss without failing anything.
const TRAINING_BAR_TEMPLATE: &str =
    "{msg} {wide_bar} {human_pos}/{human_len} samples [{elapsed_precise}<{eta_precise}]";

/// Progress bar for a training run, measured in samples across every epoch.
fn training_progress_bar(total_samples: u64, epochs: u32) -> indicatif::ProgressBar {
    let style = indicatif::ProgressStyle::with_template(TRAINING_BAR_TEMPLATE)
        .unwrap_or_else(|_| indicatif::ProgressStyle::default_bar());

    indicatif::ProgressBar::new(total_samples)
        .with_style(style)
        .with_message(format!("Epoch 1/{epochs}"))
}

/// Machine learning model using logistic regression
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct LogisticRegression {
    /// Learning rate
    pub learning_rate: f32,

    /// Bias term
    pub bias: f32,

    /// Model's weights
    pub weights: Vec<f32>,

    /// When the model was created
    pub created: Timestamp,

    /// L1 LASSO regularization
    pub l1: f32,

    /// L2 Ridge regularization
    pub l2: f32,

    /// N-grams used to train the model
    #[serde(
        serialize_with = "crate::serde::serialize_hex_map",
        deserialize_with = "crate::serde::deserialize_hex_map"
    )]
    /// Keyed with [`crate::hash::FxHasher`]: this map is probed once per byte of a sample
    /// during [`LogisticRegression::evaluate_file`].
    pub features: FxHashMap<Bytes, usize>,

    /// N-gram size
    pub n: u16,

    /// Stride used to find n-grams
    pub s: u16,

    /// If the model has been trained
    pub trained: bool,

    /// Amount of n-grams originally used
    pub original_ngrams: u32,

    /// The type of file this model is trained on
    pub file_type: FileType,

    /// How well the model performed on the training dataset
    pub train_performance: PerformanceStats,

    /// How well the model performed on the testing dataset
    #[serde(default)]
    pub test_performance: Option<PerformanceStats>,
}

impl LogisticRegression {
    /// Magic number indicating that a file is a binary model
    pub const MAGIC_NUMBER: [u8; 4] = *b"ZZMM";

    /// Model file format version number, a placeholder to allow for future changes
    const VERSION: u16 = 1;

    /// Flag to indicate that the model has test data evaluation statistics
    pub const HAS_TEST_STATS: u8 = 1;

    /// Flag to indicate that the model does not have test data evaluation statistics
    const WITHOUT_TEST_STATS: u8 = 0;

    /// Load a model from a path
    ///
    /// # Errors
    ///
    /// Errors result if the file isn't a model, doesn't have a file extension, or
    /// isn't Json or Toml.
    pub fn load<P: AsRef<Path>>(path: P) -> Result<LogisticRegression> {
        ensure!(
            path.as_ref().exists(),
            "File {} not found",
            path.as_ref().display()
        );

        let Some(ext) = path.as_ref().extension().and_then(|ext| ext.to_str()) else {
            bail!("File {} has no extension", path.as_ref().display());
        };

        let model = match ext.to_ascii_lowercase().as_str() {
            "json" => {
                let model_contents = std::fs::read_to_string(&path)?;
                serde_json::from_str(model_contents.as_str())?
            }
            "toml" => {
                let model_contents = std::fs::read_to_string(&path)?;
                toml::from_str(model_contents.as_str())?
            }
            "bin" | "model" => {
                let mut buffer = BufReader::new(File::open(path)?);
                LogisticRegression::from_bytes(&mut buffer)?
            }
            ext => bail!("Unsupported file extension: {ext}"),
        };

        ensure!(
            model.features.len() == model.weights.len(),
            "The amount of features and weights must be equal"
        );

        Ok(model)
    }

    /// New logistic regression model from given parameters.
    #[must_use]
    #[allow(clippy::cast_possible_truncation)]
    pub fn new(input_size: usize, learning_rate: f32, l1: f32, l2: f32) -> Self {
        let mut rng = rand::rng();

        Self {
            learning_rate,
            weights: vec![0.0; input_size],
            l1,
            l2,
            created: Timestamp::now(),
            n: 0,
            s: 0,
            features: FxHashMap::default(),
            trained: false,
            bias: rng.random(),
            original_ngrams: input_size as u32,
            file_type: FileType::NotSet,
            train_performance: PerformanceStats::default(),
            test_performance: None,
        }
    }

    /// Returns a trained logistic regression model from given parameters and dataset. Returns the model
    /// and the error value from the last epoch.
    ///
    /// # Panics
    ///
    /// Panics if `dataset` has no features, or if it fails [`Dataset::validate`] — for
    /// example if it has no labels, or rows of differing lengths. The weight count is taken
    /// from the dataset itself, so it always agrees with the data.
    #[must_use]
    pub fn new_from_dataset_and_train(
        dataset: &mut Dataset,
        test: Option<&Dataset>,
        epochs: u32,
        learning_rate: f32,
        l1: f32,
        l2: f32,
    ) -> (Self, f32) {
        // One weight per *feature*, not per row. Passing the row count produced a model
        // whose weight vector was unrelated to the data, so `train` below rejected it and
        // this function panicked on the `unwrap` for any dataset that wasn't square.
        let mut model = Self::new(dataset.features.len(), learning_rate, l1, l2);
        model.n = u16::try_from(dataset.features[0].len()).unwrap();
        model.s = dataset.stride;
        // Each feature maps to its own column. Mapping them all to 0 (as this did) makes
        // the map useless for `reduce`, and makes `evaluate_file` record every n-gram it
        // finds into column 0.
        model.features = dataset
            .features
            .iter()
            .enumerate()
            .map(|(index, feature)| (feature.clone(), index))
            .collect::<FxHashMap<_, _>>();
        let result = model.train(epochs, dataset).unwrap();
        let train_performance = model.evaluate_dataset(dataset).unwrap();
        model.file_type = dataset.ftype;
        model.train_performance = train_performance.into();

        // `n` is the n-gram size in bytes, not a column count, so comparing it to the test
        // set's width meant the test performance was only ever computed for a dataset that
        // happened to have exactly `n` features.
        if let Some(test) = test
            && dataset.ftype == test.ftype
            && test.data.row_len() == model.weights.len()
            && let Ok(test_performance) = model.evaluate_dataset(test)
        {
            model.test_performance = Some(test_performance.into());
        }

        (model, result)
    }

    /// Predicts the output for a given input row.
    ///
    /// Features beyond the end of the weights vector are ignored, so a row longer than the
    /// model is silently truncated rather than panicking.
    #[inline]
    #[must_use]
    pub fn predict(&self, input: RowSlice<'_>) -> f32 {
        sigmoid(input.dot(&self.weights) + self.bias)
    }

    /// Map each of a dataset's feature columns to the weight that scores it.
    ///
    /// Columns whose n-gram the model doesn't carry map to `u32::MAX` and contribute nothing,
    /// which is correct: the model dropped those features during training.
    ///
    /// # Errors
    ///
    /// Returns an error unless every feature the model carries is present in the dataset. The
    /// dataset having extra features is fine — ignoring them is the point of reducing — but a
    /// model weight with no column behind it would silently contribute nothing.
    fn column_to_weight<D: TrainingData>(&self, dataset: &D) -> Result<Vec<u32>> {
        let mut mapping = vec![u32::MAX; dataset.row_len()];
        // Which of the model's weights the dataset actually supplies a column for.
        let mut supplied = vec![false; self.weights.len()];
        let mut covered = 0usize;

        for (column, feature) in dataset.features().iter().enumerate() {
            if let Some(weight_index) = self.features.get(feature)
                && *weight_index < self.weights.len()
                && let Ok(narrowed) = u32::try_from(*weight_index)
                && let Some(slot) = mapping.get_mut(column)
            {
                *slot = narrowed;
                // Counted once per weight, so a dataset that lists an n-gram twice cannot
                // inflate the coverage.
                if let Some(flag) = supplied.get_mut(*weight_index)
                    && !*flag
                {
                    *flag = true;
                    covered += 1;
                }
            }
        }

        let missing = self.features.len().saturating_sub(covered);
        ensure!(
            missing == 0,
            "The dataset is missing {missing} of the model's {} n-gram features. Every feature \
             the model carries has to be present, otherwise its weight contributes nothing and \
             the score is wrong. The dataset has {} features, so it was probably built from a \
             different n-gram set.",
            self.features.len(),
            dataset.features().len()
        );

        Ok(mapping)
    }

    /// Predict for a row whose columns are mapped onto the weights by [`Self::column_to_weight`].
    #[must_use]
    fn predict_mapped(&self, input: RowSlice<'_>, mapping: &[u32]) -> f32 {
        let linear_model = input
            .indices()
            .iter()
            .filter_map(|column| mapping.get(*column as usize).copied())
            .filter(|weight_index| *weight_index != u32::MAX)
            .filter_map(|weight_index| self.weights.get(weight_index as usize))
            .sum::<f32>();
        sigmoid(linear_model + self.bias)
    }

    /// Trains the classifier once with the given inputs and outputs.
    ///
    /// A mutable reference is required because the dataset is shuffled in place each epoch.
    ///
    /// # Errors
    ///
    /// Returns an error if the data isn't the correct size or if labels are missing.
    #[allow(clippy::cast_precision_loss)]
    pub fn train<D: TrainingData>(
        &mut self,
        epochs: u32,
        dataset: &mut D,
    ) -> Result<f32, &'static str> {
        if !dataset.has_labels() {
            return Err("Dataset must have labels");
        }

        if !dataset.validate() {
            return Err("Dataset didn't pass validity check!");
        }

        if dataset.row_len() != self.weights.len() {
            return Err("Dataset feature length must equal the number of model weights");
        }

        self.n = u16::try_from(dataset.features().first().map_or(0, Vec::len))
            .map_err(|_| "N-gram size is unexpectedly large")?;

        // The bar counts samples across the whole run, so its ETA covers every epoch rather
        // than resetting each one. Converging early just finishes it short.
        let progress = (dataset.len() >= PROGRESS_MIN_ROWS)
            .then(|| training_progress_bar(u64::from(epochs) * dataset.len() as u64, epochs));
        let mut done = 0u64;

        let mut loss = 0.0;
        #[allow(unused)]
        for epoch in 0..epochs {
            loss = 0.0;
            dataset.shuffle();
            for (input, output) in dataset.labelled_rows() {
                let output = f32::from(output);
                let prediction = self.predict(input);
                let error = prediction - output;
                let p = prediction.clamp(LOSS_EPSILON, 1.0 - LOSS_EPSILON);
                loss += -output * p.ln() - (1.0 - output) * (1.0 - p).ln();

                // The update splits in two: the regularization terms apply to every weight
                // regardless of the input, while the error term only applies where the
                // input feature is non-zero. Since rows are a few percent dense, keeping
                // those separate turns the error term from a pass over all the weights into
                // a pass over the row's set features.
                //
                // The regularization pass is chunked across threads rather than using
                // `par_iter_mut().enumerate()` per weight: the old version paid rayon's
                // fork/join and per-element indexing cost once per weight per sample.
                //
                // The decay may shrink a weight to zero but never carry it past. Unclamped, a
                // weight with no signal overshoots zero and then bounces between
                // `±learning_rate * l1 / 2` forever (`signum` of zero is one, so zero isn't a
                // resting point either), which left L1 unable to produce a single zero weight.
                let (learning_rate, l1, l2) = (self.learning_rate, self.l1, self.l2);
                self.weights.par_chunks_mut(WEIGHT_CHUNK).for_each(|chunk| {
                    for weight in chunk {
                        let l1r = l1 * weight.signum();
                        let l2r = l2 * *weight;
                        let decayed = *weight - learning_rate * (l1r + l2r);
                        let same_side =
                            (*weight > 0.0 && decayed > 0.0) || (*weight < 0.0 && decayed < 0.0);
                        *weight = if same_side { decayed } else { 0.0 };
                    }
                });

                let step = learning_rate * error;
                for (index, value) in input.iter_nonzero() {
                    if let Some(weight) = self.weights.get_mut(index) {
                        *weight -= step * value;
                    }
                }

                self.bias -= self.learning_rate * error;

                done += 1;
                if let Some(bar) = &progress
                    && done.is_multiple_of(PROGRESS_UPDATE_SAMPLES)
                {
                    bar.set_position(done);
                }
            }
            // Mean loss per *sample*. Dividing by the weight count instead scaled the loss
            // by an arbitrary factor — with 110,000 features and 300,000 rows it reads 2.8x
            // too small, which also makes the `loss < 1e-6` early stop below fire early.
            loss /= dataset.len() as f32;

            if let Some(bar) = &progress {
                // Also the only place the loss is visible in a release build.
                bar.set_position(done);
                bar.set_message(format!("Epoch {}/{epochs}, loss {loss:.6}", epoch + 1));
            }

            #[cfg(debug_assertions)]
            {
                let line = format!("Epoch: {epoch}, Log loss: {loss}");
                // Printing straight to stdout would tear the bar's line.
                match &progress {
                    Some(bar) => bar.println(line),
                    None => println!("{line}"),
                }
            }

            if loss < 1e-6 {
                break;
            }
        }

        if let Some(bar) = progress {
            bar.finish_and_clear();
        }

        self.trained = true;
        self.file_type = dataset.file_type();
        self.s = dataset.stride();
        self.created = Timestamp::now();
        if let Ok(confusion_matrix) = self.evaluate_dataset(dataset) {
            self.train_performance = confusion_matrix.into();
        }
        Ok(loss)
    }

    /// A complete training run: train, drop the features regularization found unnecessary,
    /// then record the performance on the training data and, if given, on test data.
    ///
    /// The `train` command and every cross validation fold go through this, so a fold's
    /// model is built exactly as a regular one would be.
    ///
    /// # Errors
    ///
    /// Returns an error if training fails (see [`Self::train`]), or if either dataset can't be
    /// evaluated, for example because the test data has a different file type.
    pub fn fit<T: TrainingData, E: TrainingData>(
        &mut self,
        epochs: u32,
        train: &mut T,
        test: Option<&E>,
    ) -> Result<TrainingRun> {
        let loss = self.train(epochs, train).map_err(|e| anyhow!(e))?;

        // Reduce before measuring, so the recorded performance is the saved model's.
        let features_removed = self.set_features_and_reduce(train)?;
        self.train_performance = self.evaluate_dataset(train)?.into();
        self.test_performance = match test {
            Some(test) => Some(self.evaluate_dataset(test)?.into()),
            None => None,
        };

        Ok(TrainingRun {
            loss,
            features_removed,
        })
    }

    /// Evaluate a dataset
    ///
    /// # Errors
    ///
    /// If the dataset doesn't match the model weight length or doesn't have labels
    pub fn evaluate_dataset<D: TrainingData>(&self, dataset: &D) -> Result<ConfusionMatrix> {
        ensure!(!dataset.is_empty(), "Dataset is empty");
        ensure!(dataset.has_labels(), "Dataset labels is empty");
        ensure!(
            self.file_type == dataset.file_type(),
            "Dataset file type must match model file type"
        );

        // Align the dataset's columns to the model's weights by n-gram wherever both sides name
        // their features. Training ends by dropping the features it found unnecessary, so a
        // saved model is narrower than the dataset it was trained on and the two no longer line
        // up positionally — insisting that they do made every model `train` wrote unusable
        // against the dataset it came from.
        let mapping = if self.features.is_empty() || dataset.features().is_empty() {
            ensure!(
                dataset.row_len() == self.weights.len(),
                "Dataset has {} features but the model has {} weights, and one of them lists no \
                 n-grams to align them by.",
                dataset.row_len(),
                self.weights.len()
            );
            None
        } else {
            Some(self.column_to_weight(dataset)?)
        };

        let mut tp_ = 0;
        let mut fp_ = 0;
        let mut tn_ = 0;
        let mut fn_ = 0;
        let mut predictions = Vec::with_capacity(dataset.len());
        let mut labels = Vec::with_capacity(dataset.len());

        // Taking each row with its label keeps the two in step without indexing either: no
        // bounds check per label, and no way for a skipped row to silently desynchronise
        // `predictions` from `labels`, which `auc` later zips together.
        for (row, label) in dataset.labelled_rows() {
            let prediction = match &mapping {
                Some(mapping) => self.predict_mapped(row, mapping),
                None => self.predict(row),
            };

            match (prediction >= 0.5, label >= 1) {
                (true, true) => tp_ += 1,
                (true, false) => fp_ += 1,
                (false, false) => tn_ += 1,
                (false, true) => fn_ += 1,
            }

            predictions.push(prediction);
            labels.push(label);
        }

        Ok(ConfusionMatrix {
            true_p: tp_,
            true_n: tn_,
            false_p: fp_,
            false_n: fn_,
            labels,
            predictions,
        })
    }

    /// Evaluate a file
    ///
    /// # Errors
    ///
    /// Errors will result if the model doesn't have features or if the sample file can't be read
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
    pub fn evaluate_file<P: AsRef<Path>>(&self, path: P) -> Result<(&'static str, f32, u32)> {
        ensure!(
            !self.features.is_empty(),
            "Features are required for file evaluation"
        );

        ensure!(
            self.file_type.matches_path(&path)?,
            "File type doesn't match model type"
        );

        let vector = crate::dataset::featurize_file(path, self.n, &self.features)?;
        let result = self.predict(vector.as_slice());
        let features = vector.count_nonzero() as u32;
        if result > 0.5 {
            Ok(("Malicious", result, features))
        } else {
            Ok(("Benign", result, features))
        }
    }

    /// Remove small weights (from regularization), returns the number of weights removed
    ///
    /// # Errors
    ///
    /// There's an error if the model is not trained
    #[allow(clippy::cast_precision_loss)]
    pub fn reduce<D: TrainingData>(&mut self, dataset: &D) -> Result<usize> {
        const THRESHOLD: f32 = 0.01;

        ensure!(
            self.trained,
            "Model must be trained before reducing weights"
        );
        ensure!(
            self.file_type == dataset.file_type(),
            "Dataset file type must match model file type"
        );

        // One pass for every column sum, rather than a strided pass per column.
        let column_sums = dataset.column_sums();
        ensure!(
            column_sums.len() >= self.weights.len(),
            "Dataset has {} features but the model has {} weights",
            column_sums.len(),
            self.weights.len()
        );

        let row_count = dataset.len() as f32;
        let mut average_features = Vec::with_capacity(self.weights.len());
        for (index, model_weight) in self.weights.iter().enumerate() {
            average_features.push((index, (model_weight * column_sums[index] / row_count).abs()));
        }

        average_features.sort_by(|(_, a), (_, b)| {
            if a > b {
                Ordering::Greater
            } else if a < b {
                Ordering::Less
            } else {
                Ordering::Equal
            }
        });

        let mut removed = vec![];
        let mut running_sum = 0.0;
        for (index, weight) in average_features {
            running_sum += weight;
            if running_sum < THRESHOLD {
                removed.push(index);
            }
        }

        let removed_len = removed.len();

        // Build the old-index -> new-index mapping once, then rebuild the weights in a
        // single pass. Calling `Vec::remove` per dropped index is quadratic, and searching
        // the whole feature map per dropped index (as this did) is quadratic again — with
        // 100,000 features dropped that is on the order of 10^10 map walks.
        let mut dropped = vec![false; self.weights.len()];
        for index in &removed {
            if let Some(flag) = dropped.get_mut(*index) {
                *flag = true;
            }
        }

        let mut new_index_of = vec![None; self.weights.len()];
        let mut next_index = 0;
        for (old_index, is_dropped) in dropped.iter().enumerate() {
            if !is_dropped {
                new_index_of[old_index] = Some(next_index);
                next_index += 1;
            }
        }

        let mut kept_weights = Vec::with_capacity(next_index);
        for (old_index, weight) in self.weights.iter().enumerate() {
            if !dropped[old_index] {
                kept_weights.push(*weight);
            }
        }
        self.weights = kept_weights;

        // Renumber the surviving features to their new columns. Dropping weights without
        // doing this left every remaining feature pointing at its old column, so the model's
        // feature map no longer lined up with its own weights.
        if !self.features.is_empty() {
            self.features
                .retain(|_, index| new_index_of.get(*index).copied().flatten().is_some());
            for index in self.features.values_mut() {
                if let Some(Some(new_index)) = new_index_of.get(*index).copied() {
                    *index = new_index;
                }
            }
        }

        Ok(removed_len)
    }

    /// Set the features by adding to the struct
    ///
    /// # Errors
    ///
    /// Returns an error if the number of weights and features doesn't match
    pub fn set_features(&mut self, features: Vec<Bytes>) -> Result<()> {
        ensure!(
            features.len() == self.weights.len(),
            "Provided features length {} does not equal the number of model features length {}",
            features.len(),
            self.weights.len()
        );
        self.features = features
            .into_iter()
            .enumerate()
            .map(|(f, i)| (i, f))
            .collect::<FxHashMap<_, _>>();

        Ok(())
    }

    /// Convenience function to get the features from the dataset then reduce based on the dataset.
    ///
    /// # Errors
    ///
    /// An error occurs if the conditions below aren't met:
    /// * Ensures the number of model weights matches the dataset features
    /// * Ensures the file types match
    pub fn set_features_and_reduce<D: TrainingData>(&mut self, dataset: &D) -> Result<usize> {
        ensure!(
            self.file_type == dataset.file_type(),
            "Dataset file type must match model file type"
        );
        ensure!(
            dataset.row_len() == self.weights.len(),
            "Dataset length must equal the number of model weights"
        );

        self.features = dataset
            .features()
            .iter()
            .enumerate()
            .map(|(f, i)| (i.clone(), f))
            .collect::<FxHashMap<_, _>>();

        self.reduce(dataset)
    }

    /// Set the features by creating a new struct which has the features
    ///
    /// # Errors
    ///
    /// Returns an error if the number of weights and features doesn't match
    pub fn with_features(self, features: Vec<Bytes>) -> Result<Self> {
        ensure!(
            features.len() == self.weights.len(),
            "Provided features length {} does not equal the number of model features length {}",
            features.len(),
            self.weights.len()
        );

        Ok(Self {
            learning_rate: self.learning_rate,
            bias: self.bias,
            weights: self.weights,
            l1: self.l1,
            l2: self.l2,
            trained: self.trained,
            original_ngrams: self.original_ngrams,
            file_type: self.file_type,
            n: self.n,
            s: self.s,
            created: self.created,
            train_performance: self.train_performance,
            test_performance: self.test_performance,
            features: features
                .into_iter()
                .enumerate()
                .map(|(f, i)| (i, f))
                .collect::<FxHashMap<_, _>>(),
        })
    }

    /// Save a model to disk.
    ///
    /// # Errors
    ///
    /// An error occurs if the file type isn't Json or Toml, or if a file
    /// cannot be created or written.
    pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        use std::io::Write;

        let Some(ext) = path.as_ref().extension().and_then(|ext| ext.to_str()) else {
            bail!("File {} has no extension", path.as_ref().display());
        };

        match ext.to_ascii_lowercase().as_str() {
            "json" => {
                let file = File::create(path)?;
                let mut writer = std::io::BufWriter::with_capacity(1 << 20, file);
                serde_json::to_writer_pretty(&mut writer, self)?;
                writer.flush()?;
                writer.into_inner()?.sync_all()?;
            }
            "toml" => {
                let serialized = toml::to_string_pretty(self)?;
                std::fs::write(path, serialized)?;
            }
            "bin" | "model" => {
                let mut buffer = BufWriter::new(File::create(path)?);
                self.to_bytes(&mut buffer)?;
                buffer.flush()?;
            }
            ext => bail!("Unsupported file extension: {ext}"),
        }

        Ok(())
    }

    /// Write the model as raw bytes. See [`LogisticRegression::from_bytes`]
    /// for the data format.
    ///
    /// # Errors
    ///
    /// Errors result if data cannot be written to the destination.
    #[allow(clippy::cast_possible_truncation)]
    pub fn to_bytes<W: Write>(&self, writer: &mut W) -> Result<()> {
        ensure!(
            self.n > 1 && self.trained,
            "Refusing to save an untrained model!"
        );
        writer.write_all(&LogisticRegression::MAGIC_NUMBER)?;
        writer.write_all(&LogisticRegression::VERSION.to_be_bytes())?;

        writer.write_all(&self.n.to_be_bytes())?;
        writer.write_all(&self.s.to_be_bytes())?;
        let k = self.features.len() as u32;
        writer.write_all(&k.to_be_bytes())?;

        for (ngram, index) in &self.features {
            writer.write_all(ngram)?;
            let position = *index as u32;
            writer.write_all(&position.to_be_bytes())?;
            writer.write_all(&self.weights[*index].to_be_bytes())?;
        }
        writer.write_all(&self.original_ngrams.to_be_bytes())?;
        let timestamp = self.created.as_second().cast_unsigned();
        writer.write_all(&timestamp.to_be_bytes())?;
        let ftype_string = self.file_type.to_string();
        writer.write_all(&(ftype_string.len() as u32).to_be_bytes())?;
        writer.write_all(&ftype_string.into_bytes())?;

        writer.write_all(&self.learning_rate.to_be_bytes())?;
        writer.write_all(&self.bias.to_be_bytes())?;
        writer.write_all(&self.l1.to_be_bytes())?;
        writer.write_all(&self.l2.to_be_bytes())?;

        writer.write_all(&self.train_performance.true_positives.to_be_bytes())?;
        writer.write_all(&self.train_performance.true_negatives.to_be_bytes())?;
        writer.write_all(&self.train_performance.false_positives.to_be_bytes())?;
        writer.write_all(&self.train_performance.false_negatives.to_be_bytes())?;
        writer.write_all(&self.train_performance.auc.to_be_bytes())?;

        if let Some(stats) = self.test_performance {
            writer.write_all(&LogisticRegression::HAS_TEST_STATS.to_be_bytes())?;
            writer.write_all(&stats.true_positives.to_be_bytes())?;
            writer.write_all(&stats.true_negatives.to_be_bytes())?;
            writer.write_all(&stats.false_positives.to_be_bytes())?;
            writer.write_all(&stats.false_negatives.to_be_bytes())?;
            writer.write_all(&stats.auc.to_be_bytes())?;
        } else {
            writer.write_all(&LogisticRegression::WITHOUT_TEST_STATS.to_be_bytes())?;
        }

        writer.flush().map_err(Into::into)
    }

    /// Byte format (all values in [Big Endian](https://en.wikipedia.org/wiki/Endianness)):
    ///
    /// * Magic Number [`LogisticRegression::MAGIC_NUMBER`], 4 bytes
    /// * Version number, 2 bytes, int
    /// * Size of n-grams, 2 bytes, int
    /// * N-gram stride, 2 bytes, int
    /// * Number of n-grams, 4 bytes, int
    /// * For each n-gram:
    ///   * N-gram bytes (size of n)
    ///   * N-gram index, 4 bytes, int
    ///   * Weight, 4 bytes
    /// * Original number of n-grams, 4 bytes, int
    /// * Model creation timestamp, 8 bytes, int
    /// * String size of the file type, 4 bytes, int
    /// * String bytes for the file type, size is above length
    /// * Learning rate, 4 bytes, float
    /// * Bias, 4 bytes, float
    /// * L1 regularization, 4 bytes, float
    /// * L2 regularization, 4 bytes, float
    /// * Model's training performance stats:
    ///     * True Positives, 4 bytes, int
    ///     * True Negatives, 4 bytes, int
    ///     * False Positives, 4 bytes, int
    ///     * False Negatives, 4 bytes, int
    ///     * AUC, 4 bytes, float
    /// * Flag indicating presence of test performance stats, 1 byte
    /// * If flag == [`LogisticRegression::HAS_TEST_STATS`]:
    ///     * True Positives, 4 bytes, int
    ///     * True Negatives, 4 bytes, int
    ///     * False Positives, 4 bytes, int
    ///     * False Negatives, 4 bytes, int
    ///     * AUC, 4 bytes, float
    ///
    /// # Errors
    ///
    /// Errors result if the data cannot be read or if the data is too short.
    #[allow(clippy::cast_precision_loss, clippy::too_many_lines)]
    pub fn from_bytes<R: Read>(reader: &mut R) -> Result<Self> {
        let mut magic = [0; LogisticRegression::MAGIC_NUMBER.len()];
        reader.read_exact(&mut magic)?;
        ensure!(
            magic == LogisticRegression::MAGIC_NUMBER,
            "Invalid magic number"
        );
        let mut version = [0; 2];
        reader.read_exact(&mut version)?;
        ensure!(
            u16::from_be_bytes(version) == LogisticRegression::VERSION,
            "Invalid version"
        );

        let mut two_bytes = [0; 2];
        let mut four_bytes = [0; 4];
        reader.read_exact(&mut two_bytes)?;
        let n = u16::from_be_bytes(two_bytes);
        reader.read_exact(&mut two_bytes)?;
        let s = u16::from_be_bytes(two_bytes);
        reader.read_exact(&mut four_bytes)?;
        let k = u32::from_be_bytes(four_bytes);

        let mut ngram = vec![0; n as usize];
        let mut features =
            FxHashMap::with_capacity_and_hasher(k as usize, BuildHasherDefault::default());
        let mut weights = vec![0.0; k as usize];
        for _ in 0..k {
            reader.read_exact(&mut ngram)?;
            reader.read_exact(&mut four_bytes)?;
            let index = u32::from_be_bytes(four_bytes);
            features.insert(ngram.clone(), index as usize);
            reader.read_exact(&mut four_bytes)?;
            if let Some(w) = weights.get_mut(index as usize) {
                *w = f32::from_be_bytes(four_bytes);
            } else {
                bail!("Invalid weight index {index}");
            }
        }

        reader.read_exact(&mut four_bytes)?;
        let original_ngrams = u32::from_be_bytes(four_bytes);

        let mut eight_bytes = [0u8; 8];
        reader.read_exact(&mut eight_bytes)?;
        let timestamp = u64::from_be_bytes(eight_bytes);

        reader.read_exact(&mut four_bytes)?;
        let string_len = u32::from_be_bytes(four_bytes) as usize;
        let mut string = vec![0; string_len];
        reader.read_exact(&mut string)?;
        let ftype = String::from_utf8(string)?;
        let file_type =
            FileType::from_name(&ftype).ok_or_else(|| anyhow!("Unknown file type `{ftype}`!"))?;

        reader.read_exact(&mut four_bytes)?;
        let learning_rate = f32::from_be_bytes(four_bytes);
        reader.read_exact(&mut four_bytes)?;
        let bias = f32::from_be_bytes(four_bytes);
        reader.read_exact(&mut four_bytes)?;
        let l1 = f32::from_be_bytes(four_bytes);
        reader.read_exact(&mut four_bytes)?;
        let l2 = f32::from_be_bytes(four_bytes);

        reader.read_exact(&mut four_bytes)?;
        let true_positives = u32::from_be_bytes(four_bytes);
        reader.read_exact(&mut four_bytes)?;
        let true_negatives = u32::from_be_bytes(four_bytes);
        reader.read_exact(&mut four_bytes)?;
        let false_positives = u32::from_be_bytes(four_bytes);
        reader.read_exact(&mut four_bytes)?;
        let false_negatives = u32::from_be_bytes(four_bytes);
        let mut recall = true_positives as f32 / (true_positives + false_negatives) as f32;
        let mut precision = true_positives as f32 / (true_positives + false_positives) as f32;
        let mut f1 = 2.0 * (precision * recall) / (precision + recall);
        if !recall.is_normal() {
            recall = 0.0;
        }
        if !precision.is_normal() {
            precision = 0.0;
        }
        if !f1.is_normal() {
            f1 = 0.0;
        }

        reader.read_exact(&mut four_bytes)?;
        let auc = f32::from_be_bytes(four_bytes);

        let mut one_byte = [0u8; 1];
        reader.read_exact(&mut one_byte)?;
        let test_performance = if one_byte[0] == LogisticRegression::HAS_TEST_STATS {
            let mut test_performance = PerformanceStats::default();
            reader.read_exact(&mut four_bytes)?;
            test_performance.true_positives = u32::from_be_bytes(four_bytes);
            reader.read_exact(&mut four_bytes)?;
            test_performance.true_negatives = u32::from_be_bytes(four_bytes);
            reader.read_exact(&mut four_bytes)?;
            test_performance.false_positives = u32::from_be_bytes(four_bytes);
            reader.read_exact(&mut four_bytes)?;
            test_performance.false_negatives = u32::from_be_bytes(four_bytes);
            reader.read_exact(&mut four_bytes)?;
            test_performance.auc = f32::from_be_bytes(four_bytes);

            test_performance.recall = test_performance.true_positives as f32
                / (test_performance.true_positives + test_performance.false_negatives) as f32;
            test_performance.precision = test_performance.true_positives as f32
                / (test_performance.true_positives + test_performance.false_positives) as f32;
            test_performance.f1 = 2.0 * (test_performance.precision * test_performance.recall)
                / (test_performance.precision + test_performance.recall);

            if !test_performance.precision.is_normal() {
                test_performance.precision = 0.0;
            }
            if !test_performance.recall.is_normal() {
                test_performance.recall = 0.0;
            }
            if !test_performance.f1.is_normal() {
                test_performance.f1 = 0.0;
            }

            Some(test_performance)
        } else {
            None
        };

        Ok(Self {
            learning_rate,
            bias,
            weights,
            l1,
            l2,
            features,
            n,
            s,
            created: Timestamp::from_second(i64::try_from(timestamp)?)?,
            trained: true,
            original_ngrams,
            file_type,
            train_performance: PerformanceStats {
                true_positives,
                true_negatives,
                false_positives,
                false_negatives,
                recall,
                precision,
                f1,
                auc,
            },
            test_performance,
        })
    }
}

impl From<LogisticRegression> for Ngrammer {
    #[inline]
    fn from(l: LogisticRegression) -> Self {
        let ngrams =
            dashmap::DashMap::with_capacity_and_hasher(l.features.len(), FxBuildHasher::default());
        for (ngram, index) in l.features {
            ngrams.insert(ngram, index);
        }

        Ngrammer {
            n: l.n,
            k: ngrams.len(),
            s: 1,
            keep_below: u64::MAX,
            paths: vec![],
            ftype: l.file_type,
            ngrams,
        }
    }
}

impl From<LogisticRegression> for NgramsFile {
    #[inline]
    fn from(l: LogisticRegression) -> Self {
        NgramsFile {
            ngrams: l.features,
            ftype: l.file_type,
            n: l.n,
            s: l.s,
        }
    }
}

/// Outcome of [`LogisticRegression::fit`]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TrainingRun {
    /// Mean log loss of the final epoch
    pub loss: f32,

    /// Features dropped after training
    pub features_removed: usize,
}

/// Model performance statistics
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct PerformanceStats {
    /// True positives
    pub true_positives: u32,

    /// True negatives
    pub true_negatives: u32,

    /// False positives
    pub false_positives: u32,

    /// False negatives
    pub false_negatives: u32,

    /// Recall
    pub recall: f32,

    /// Precision
    pub precision: f32,

    /// F1
    pub f1: f32,

    /// AUC
    pub auc: f32,
}

impl PerformanceStats {
    /// Accuracy as correct vs total
    #[inline]
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn accuracy(&self) -> f32 {
        (self.true_positives + self.true_negatives) as f32
            / (self.true_positives
                + self.true_negatives
                + self.false_negatives
                + self.false_positives) as f32
    }

    /// Precision
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn precision(&self) -> f32 {
        self.true_positives as f32 / (self.true_positives + self.false_positives) as f32
    }

    /// Recall
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn recall(&self) -> f32 {
        self.true_positives as f32 / (self.true_positives + self.false_negatives) as f32
    }

    /// F1 score
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn f1(&self) -> f32 {
        2.0 * (self.precision() * self.recall()) / (self.precision() + self.recall())
    }
}

impl std::fmt::Display for PerformanceStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        const WIDTH: usize = 10;

        writeln!(f, "Result \\ Actual  |    Malicious   |  Benign")?;
        writeln!(
            f,
            "   Malicious     |     {:<WIDTH$} |    {:<WIDTH$}",
            self.true_positives, self.false_positives
        )?;
        writeln!(
            f,
            "   Benign        |     {:<WIDTH$} |    {:<WIDTH$}",
            self.false_negatives, self.true_negatives
        )
    }
}

impl From<ConfusionMatrix> for PerformanceStats {
    fn from(value: ConfusionMatrix) -> Self {
        PerformanceStats {
            true_positives: value.true_p,
            true_negatives: value.true_n,
            false_positives: value.false_p,
            false_negatives: value.false_n,
            recall: value.recall(),
            precision: value.precision(),
            f1: value.f1(),
            auc: value.auc(),
        }
    }
}

/// Confusion Matrix
#[derive(Debug, Clone, PartialEq)]
pub struct ConfusionMatrix {
    /// True positives
    pub true_p: u32,

    /// True negatives
    pub true_n: u32,

    /// False positives
    pub false_p: u32,

    /// False negatives
    pub false_n: u32,

    /// Labels of the evaluated rows, in the same order as `predictions`.
    ///
    /// Owned rather than borrowed from the dataset, since a cross validation fold's labels
    /// aren't contiguous in the dataset it borrows from.
    labels: Vec<u8>,

    /// Model's outputs
    predictions: Vec<f32>,
}

impl ConfusionMatrix {
    /// Accuracy as correct vs total
    #[inline]
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn accuracy(&self) -> f32 {
        (self.true_p + self.true_n) as f32 / self.total() as f32
    }

    /// Precision
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn precision(&self) -> f32 {
        self.true_p as f32 / (self.true_p + self.false_p) as f32
    }

    /// Recall
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn recall(&self) -> f32 {
        self.true_p as f32 / (self.true_p + self.false_n) as f32
    }

    /// F1 score
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn f1(&self) -> f32 {
        2.0 * (self.precision() * self.recall()) / (self.precision() + self.recall())
    }

    /// Total items evaluated
    #[inline]
    #[must_use]
    pub fn total(&self) -> u32 {
        self.true_p + self.true_n + self.false_p + self.false_n
    }

    /// Calculate the area under the curve (AUC)
    #[must_use]
    #[allow(clippy::float_cmp)]
    pub fn auc(&self) -> f32 {
        // Adapted from the AUC implementation by Maciej Kula <maciej.kula@gmail.com>
        // https://github.com/maciejkula/rustlearn/blob/2ac052559b04860c62d7ba34c563b57a02912e4d/src/metrics/ranking.rs
        // The last commit was June 2020 so used here directly instead of importing the crate.
        // This code was also Apache 2.0 licensed.

        // vector of pairs (score, label) - the order is switched with respect to function arguments
        let (mut true_positive_count, mut false_positive_count) = {
            let mut pairs: Vec<_> = self
                .predictions
                .iter()
                .copied()
                .zip(self.labels.iter().copied())
                .collect();

            // Sort by scores in descending order
            pairs.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));

            let mut score_prev = f32::NAN;
            // tp .. true positives, fp .. false positives
            let (mut tp, mut fp) = (0.0f32, 0.0f32);
            let (mut tps, mut fps) = (vec![], vec![]);
            for (score, label) in pairs {
                let label = f32::from(label);
                // `tp` and `fp` from the previous iteration are pushed onto the ROC curve only if
                // the `score` changed. This avoids errors due to arbitrary classification of points with
                // identical scores
                if score != score_prev {
                    tps.push(tp);
                    fps.push(fp);
                    score_prev = score;
                }
                tp += label;
                fp += 1.0 - label;
            }
            // Push the final point corresponding to the (1,1) ROC coordinates
            tps.push(tp);
            fps.push(fp);
            (tps, fps)
        };

        let true_positives = true_positive_count[true_positive_count.len() - 1];
        let false_positives = false_positive_count[false_positive_count.len() - 1];

        for (tp, fp) in true_positive_count
            .iter_mut()
            .zip(false_positive_count.iter_mut())
        {
            *tp /= true_positives;
            *fp /= false_positives;
        }

        let mut prev_x = false_positive_count[0];
        let mut prev_y = true_positive_count[0];
        let mut integral = 0.0;

        for (&x, &y) in false_positive_count
            .iter()
            .skip(1)
            .zip(true_positive_count.iter().skip(1))
        {
            integral += (x - prev_x) * (prev_y + y) / 2.0;

            prev_x = x;
            prev_y = y;
        }

        integral
    }
}

impl std::fmt::Display for ConfusionMatrix {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        const WIDTH: usize = 10;

        writeln!(f, "Result \\ Actual  |    Malicious   |  Benign")?;
        writeln!(
            f,
            "   Malicious     |     {:<WIDTH$} |    {:<WIDTH$}",
            self.true_p, self.false_p
        )?;
        writeln!(
            f,
            "   Benign        |     {:<WIDTH$} |    {:<WIDTH$}",
            self.false_n, self.true_n
        )
    }
}

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

    #[test]
    fn xor() {
        let mut dataset = Dataset::from_csv_string(include_str!("../testdata/xor.csv"), 6).unwrap();
        let mut lr = LogisticRegression::new(6, 0.2, 0.0, 0.0);
        lr.train(100, &mut dataset).unwrap();

        let mut correct = 0u16;
        let mut incorrect = 0u16;

        for index in 0..dataset.data.len() {
            println!(
                "Predicted: {}, Expected: {}",
                lr.predict(dataset.data.row(index).unwrap()),
                dataset.labels[index]
            );
            if (lr.predict(dataset.data.row(index).unwrap()) >= 0.5 && dataset.labels[index] >= 1)
                || (lr.predict(dataset.data.row(index).unwrap()) < 0.5 && dataset.labels[index] < 1)
            {
                correct += 1;
            } else {
                incorrect += 1;
            }
        }

        println!("Correct: {correct}, Incorrect: {incorrect}");
        assert!(correct > incorrect);

        let result = lr.evaluate_dataset(&dataset).unwrap();
        println!("{result}");
        println!("Accuracy: {:.2}", result.accuracy());
        println!("Precision: {:.2}", result.precision());
        println!("Recall: {:.2}", result.recall());
        println!("F1: {:.2}", result.f1());
        println!("Auc: {:.2}", result.auc());
    }

    #[test]
    fn reduction() {
        const BOGUS_LEN: usize = 6;

        let mut dataset =
            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
        let mut lr = LogisticRegression::new(BOGUS_LEN, 0.2, 0.1, 0.1);
        lr.set_features(dataset.features.clone()).unwrap();
        lr.train(20, &mut dataset).unwrap();
        let cm = lr.evaluate_dataset(&dataset).unwrap();
        println!("{cm}");
        println!("Weights before reduction: {:?}", lr.weights);
        println!("Features before reduction: {:?}", lr.features);
        lr.reduce(&dataset).expect("Failed to reduce weights");
        println!("Weights after reduction: {:?}", lr.weights);
        println!("Features after reduction: {:?}", lr.features);
        println!("Weights from {BOGUS_LEN} to {}", lr.weights.len());
        assert!(
            lr.weights.len() < BOGUS_LEN,
            "** If this assertion fails, re-run the test once or twice. **"
        );
        lr.test_performance = Some(cm.into());
        println!("Model: {lr:?}");
    }

    /// `new_from_dataset_and_train` sized the weights from the row count, so it panicked on
    /// any dataset that wasn't square, and mapped every feature to column 0.
    #[test]
    fn new_from_dataset_and_train_sizes_from_features() {
        const BOGUS_LEN: usize = 6;
        let mut dataset =
            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
        assert_ne!(
            dataset.len(),
            BOGUS_LEN,
            "test needs a non-square dataset to be meaningful"
        );

        let (model, _loss) =
            LogisticRegression::new_from_dataset_and_train(&mut dataset, None, 10, 0.2, 0.0, 0.0);

        assert_eq!(model.weights.len(), BOGUS_LEN);
        assert_eq!(model.features.len(), BOGUS_LEN);

        // Every feature must own a distinct column, covering 0..BOGUS_LEN.
        let mut columns = model.features.values().copied().collect::<Vec<_>>();
        columns.sort_unstable();
        assert_eq!(columns, (0..BOGUS_LEN).collect::<Vec<_>>());
    }

    /// Aligning by n-gram must give exactly what aligning by column position gives, when the
    /// two happen to line up.
    #[test]
    fn mapped_evaluation_matches_positional() {
        const BOGUS_LEN: usize = 6;

        let mut dataset =
            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
        let mut model = LogisticRegression::new(BOGUS_LEN, 0.2, 0.0, 0.0);
        model.set_features(dataset.features.clone()).unwrap();
        model.train(5, &mut dataset).unwrap();

        // Both sides name their features, so this takes the n-gram alignment path.
        let matrix = model.evaluate_dataset(&dataset).unwrap();

        // The same counts via the positional `predict`.
        let (mut tp, mut fp, mut tn, mut negatives) = (0u32, 0u32, 0u32, 0u32);
        for (row, label) in dataset.data.iter().zip(&dataset.labels) {
            match (model.predict(row) >= 0.5, *label >= 1) {
                (true, true) => tp += 1,
                (true, false) => fp += 1,
                (false, false) => tn += 1,
                (false, true) => negatives += 1,
            }
        }

        assert_eq!(
            (matrix.true_p, matrix.false_p, matrix.true_n, matrix.false_n),
            (tp, fp, tn, negatives)
        );
    }

    /// Training ends by dropping features, so the model `train` writes is narrower than the
    /// dataset it came from. Evaluating that dataset has to work, and has to agree with first
    /// narrowing the dataset to match — the `dataset-convert --model` route.
    #[test]
    fn reduced_model_evaluates_the_original_dataset() {
        const BOGUS_LEN: usize = 6;

        let mut dataset =
            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
        let mut model = LogisticRegression::new(BOGUS_LEN, 0.2, 0.1, 0.1);
        model.set_features(dataset.features.clone()).unwrap();
        model.train(20, &mut dataset).unwrap();

        let removed = model.reduce(&dataset).unwrap();
        assert!(removed > 0, "test needs the model to shed some features");
        assert!(model.weights.len() < dataset.data.row_len());

        // The original, wider dataset against the narrowed model.
        let wide = model.evaluate_dataset(&dataset).unwrap();
        let wide_counts = (wide.true_p, wide.false_p, wide.true_n, wide.false_n);

        // The same thing after narrowing the dataset to match the model.
        let mut narrowed = dataset.clone();
        narrowed.reduce(&model).unwrap();
        assert_eq!(narrowed.data.row_len(), model.weights.len());
        let narrow = model.evaluate_dataset(&narrowed).unwrap();

        assert_eq!(
            wide_counts,
            (narrow.true_p, narrow.false_p, narrow.true_n, narrow.false_n),
            "the two routes must score the same samples the same way"
        );
    }

    /// Only the features the model kept may influence a score. The columns it dropped are not
    /// in the saved model at all, so changing them must make no difference whatsoever.
    #[test]
    fn dropped_features_cannot_affect_evaluation() {
        use crate::row::{DataMatrix, DataRow};

        const LEN: usize = 6;

        let mut dataset =
            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), LEN).unwrap();
        let mut model = LogisticRegression::new(LEN, 0.2, 0.1, 0.1);
        model.set_features(dataset.features.clone()).unwrap();
        model.train(20, &mut dataset).unwrap();
        model.reduce(&dataset).unwrap();

        let dropped = dataset
            .features
            .iter()
            .enumerate()
            .filter(|(_, feature)| !model.features.contains_key(*feature))
            .map(|(column, _)| column)
            .collect::<Vec<_>>();
        assert!(
            !dropped.is_empty(),
            "test needs the model to have dropped something"
        );

        // Every dropped column set in every row, which is the largest perturbation available.
        let perturbed_rows = dataset
            .data
            .iter()
            .map(|row| {
                let mut new_row = DataRow::zeroed(row.len());
                for (column, _) in row.iter_nonzero() {
                    new_row.set(column, 1.0).unwrap();
                }
                for column in &dropped {
                    new_row.set(*column, 1.0).unwrap();
                }
                new_row
            })
            .collect::<Vec<_>>();

        let perturbed = Dataset {
            data: perturbed_rows.into_iter().collect::<DataMatrix>(),
            labels: dataset.labels.clone(),
            features: dataset.features.clone(),
            ftype: dataset.ftype,
            stride: dataset.stride,
        };

        let before = model.evaluate_dataset(&dataset).unwrap();
        let after = model.evaluate_dataset(&perturbed).unwrap();

        assert_eq!(
            (before.true_p, before.false_p, before.true_n, before.false_n),
            (after.true_p, after.false_p, after.true_n, after.false_n),
            "a dropped feature changed the confusion matrix"
        );
        assert!(
            (before.auc() - after.auc()).abs() < 1e-6,
            "a dropped feature changed the AUC: {} vs {}",
            before.auc(),
            after.auc()
        );
    }

    /// A dataset holding only *some* of the model's features used to be scored silently on the
    /// overlap: the missing weights contributed nothing, so the result looked plausible and was
    /// wrong. Partial coverage has to be refused.
    #[test]
    fn partially_covering_dataset_is_rejected() {
        const LEN: usize = 6;

        let mut dataset =
            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), LEN).unwrap();
        let mut model = LogisticRegression::new(LEN, 0.2, 0.0, 0.0);
        model.set_features(dataset.features.clone()).unwrap();
        model.train(2, &mut dataset).unwrap();

        // Same width, same file type, and five of the model's six features still present.
        let mut partial = dataset.clone();
        partial.features[3] = vec![0xF0, 0x0D];

        let err = model.evaluate_dataset(&partial).unwrap_err().to_string();
        assert!(
            err.contains("missing 1 of the model's 6"),
            "unexpected error: {err}"
        );

        // All six present: accepted.
        assert!(model.evaluate_dataset(&dataset).is_ok());
    }

    /// Aligning by n-gram must not quietly score a dataset built from a different feature set.
    #[test]
    fn unrelated_feature_sets_are_rejected() {
        const LEN: usize = 6;

        let mut dataset =
            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), LEN).unwrap();
        let mut model = LogisticRegression::new(LEN, 0.2, 0.0, 0.0);
        model.set_features(dataset.features.clone()).unwrap();
        model.train(2, &mut dataset).unwrap();

        // Same width and file type, but no n-gram in common.
        let mut other = dataset.clone();
        for (index, feature) in other.features.iter_mut().enumerate() {
            *feature = vec![0xF0, u8::try_from(index).unwrap()];
        }

        let err = model.evaluate_dataset(&other).unwrap_err().to_string();
        assert!(
            err.contains("missing") && err.contains("different n-gram set"),
            "unexpected error: {err}"
        );
    }

    /// `reduce` dropped weights but left the surviving features pointing at their old
    /// columns, so the feature map no longer agreed with the model's own weights.
    #[test]
    fn reduce_renumbers_surviving_features() {
        const BOGUS_LEN: usize = 6;

        let mut dataset =
            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();
        let mut model = LogisticRegression::new(BOGUS_LEN, 0.2, 0.1, 0.1);
        model.set_features(dataset.features.clone()).unwrap();
        model.train(20, &mut dataset).unwrap();

        let removed = model.reduce(&dataset).unwrap();
        assert_eq!(model.weights.len(), BOGUS_LEN - removed);
        assert_eq!(model.features.len(), model.weights.len());

        let mut columns = model.features.values().copied().collect::<Vec<_>>();
        columns.sort_unstable();
        assert_eq!(
            columns,
            (0..model.weights.len()).collect::<Vec<_>>(),
            "feature columns must be a dense 0..weights.len() range after reducing"
        );
    }

    /// The loss clamp used a 1e-8 margin, which is smaller than `f32`'s spacing below 1.0,
    /// so `1.0 - 1e-8` rounded back to 1.0 and a saturated prediction reached `ln(0)`.
    /// A bad template is not an error at runtime — it silently falls back to a bar with no
    /// message, losing the epoch and loss — so it has to be checked here.
    #[test]
    fn progress_bar_template_parses() {
        assert!(
            indicatif::ProgressStyle::with_template(super::TRAINING_BAR_TEMPLATE).is_ok(),
            "training bar template is invalid: {}",
            super::TRAINING_BAR_TEMPLATE
        );
    }

    #[test]
    #[allow(clippy::float_cmp)] // Exact comparison is the property under test.
    fn loss_stays_finite_when_predictions_saturate() {
        const BOGUS_LEN: usize = 6;

        let mut dataset =
            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();

        // Huge weights drive every sigmoid to exactly 0.0 or 1.0 in f32.
        let mut model = LogisticRegression::new(BOGUS_LEN, 0.0, 0.0, 0.0);
        model.weights = vec![1.0e30; BOGUS_LEN];
        model.bias = 1.0e30;
        assert!(
            model.predict(dataset.data.row(0).unwrap()) == 1.0,
            "expected the prediction to saturate"
        );

        let loss = model.train(1, &mut dataset).unwrap();
        assert!(loss.is_finite(), "loss was {loss}");
    }

    /// L1 has to be able to land a weight on exactly zero, since that is what `reduce` relies
    /// on. The decay used to step straight past zero, leaving every weight without signal
    /// bouncing between `±learning_rate * l1 / 2` instead.
    #[test]
    #[allow(clippy::float_cmp)] // Exact comparison is the property under test.
    fn l1_decay_stops_at_zero() {
        const BOGUS_LEN: usize = 6;

        let mut dataset =
            Dataset::from_csv_string(include_str!("../testdata/bogus.csv"), BOGUS_LEN).unwrap();

        let mut model = LogisticRegression::new(BOGUS_LEN, 0.1, 0.1, 0.1);
        assert!(model.weights.iter().all(|weight| *weight == 0.0));

        // Start off zero on both sides, some within one decay step of it and some further out.
        model.weights = vec![0.5, -0.5, 0.004, -0.004, 0.015, -0.015];
        model.train(20, &mut dataset).unwrap();

        // Columns 3 to 5 are never set in this dataset, so they get no error term and the
        // regularization is all that moves them.
        for (index, weight) in model.weights.iter().enumerate().skip(2).take(3) {
            assert_eq!(
                *weight, 0.0,
                "weight {index} is {weight}, expected exactly zero"
            );
        }
    }

    #[test]
    fn auc() {
        let y_true = vec![1, 1, 0, 0];
        let y_hat = vec![0.5, 0.2, 0.3, -1.0];

        let confusion_matrix = ConfusionMatrix {
            true_p: 0,
            true_n: 0,
            false_p: 0,
            false_n: 0,
            labels: y_true,
            predictions: y_hat,
        };

        let auc = confusion_matrix.auc();
        println!("Auc: {auc:.2}, expected 0.75");
        assert!((0.73..0.78).contains(&auc));
    }
}