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
// SPDX-License-Identifier: Apache-2.0

use crate::Bytes;
use crate::dataset::{Dataset, TrainingData};
use crate::ftype::FileType;
use crate::model::{LogisticRegression, PerformanceStats};
use crate::row::RowSlice;

use std::fmt::{Display, Formatter};
use std::str::FromStr;

use anyhow::{Result, anyhow, ensure};
use rand::seq::SliceRandom;

/// A subset of a dataset's rows, borrowed rather than copied.
///
/// Holds only row numbers into the dataset, so a view costs eight bytes per row however wide
/// the rows are, and shuffling it reorders those numbers without touching the dataset.
#[derive(Debug, Clone)]
pub struct DatasetView<'a> {
    /// The dataset the rows come from
    dataset: &'a Dataset,

    /// Row numbers into `dataset`, in this view's order
    rows: Vec<usize>,
}

impl<'a> DatasetView<'a> {
    /// A view of the given rows of a dataset.
    ///
    /// # Errors
    ///
    /// Returns an error if the dataset's labels don't match its rows, or a row number is out
    /// of range.
    pub fn new(dataset: &'a Dataset, rows: Vec<usize>) -> Result<Self> {
        ensure!(
            dataset.labels.len() == dataset.data.len(),
            "Dataset has {} labels for {} rows",
            dataset.labels.len(),
            dataset.data.len()
        );
        ensure!(
            rows.iter().all(|row| *row < dataset.len()),
            "Row number out of range for a dataset of {} rows",
            dataset.len()
        );
        Ok(Self { dataset, rows })
    }

    /// The dataset this view borrows from.
    #[must_use]
    pub fn dataset(&self) -> &'a Dataset {
        self.dataset
    }

    /// Row numbers into the dataset, in this view's order.
    #[must_use]
    pub fn rows(&self) -> &[usize] {
        &self.rows
    }

    /// Count the (benign, malicious) rows in the view.
    #[must_use]
    pub fn class_counts(&self) -> (usize, usize) {
        let malicious = self
            .rows
            .iter()
            .filter(|row| self.dataset.labels[**row] >= 1)
            .count();
        (self.rows.len() - malicious, malicious)
    }
}

impl TrainingData for DatasetView<'_> {
    fn len(&self) -> usize {
        self.rows.len()
    }

    fn row_len(&self) -> usize {
        self.dataset.data.row_len()
    }

    fn features(&self) -> &[Bytes] {
        &self.dataset.features
    }

    fn file_type(&self) -> FileType {
        self.dataset.ftype
    }

    fn stride(&self) -> u16 {
        self.dataset.stride
    }

    fn has_labels(&self) -> bool {
        // Checked against the dataset when the view was made.
        true
    }

    fn labelled_rows(&self) -> impl Iterator<Item = (RowSlice<'_>, u8)> + '_ {
        self.rows.iter().filter_map(|row| {
            Some((
                self.dataset.data.row(*row)?,
                *self.dataset.labels.get(*row)?,
            ))
        })
    }

    fn shuffle(&mut self) {
        self.rows.shuffle(&mut rand::rng());
    }

    fn column_sums(&self) -> Vec<f32> {
        let mut sums = vec![0.0f32; self.row_len()];
        for (row, _) in self.labelled_rows() {
            for (index, value) in row.iter_nonzero() {
                if let Some(sum) = sums.get_mut(index) {
                    *sum += value;
                }
            }
        }
        sums
    }

    fn validate(&self) -> bool {
        !self.rows.is_empty() && self.dataset.validate()
    }
}

/// One fold of a cross validation: a label-balanced training set and the held-out rows.
#[derive(Debug, Clone)]
pub struct Fold<'a> {
    /// Which fold this is, from zero
    pub index: usize,

    /// Rows to train on, the same number of benign and malicious
    pub train: DatasetView<'a>,

    /// Rows held out for testing, in the dataset's class proportions
    pub test: DatasetView<'a>,
}

/// Stratified n-fold cross validation over a dataset, borrowing its rows.
///
/// The benign and malicious rows are each shuffled and dealt evenly across the folds, so every
/// fold holds the dataset's class proportions and every row is tested exactly once. A fold's
/// training set is every other fold's rows with the majority class randomly cut down to the
/// size of the minority class, so the model always trains on balanced labels; the rows cut
/// are simply unused by that fold.
#[derive(Debug, Clone)]
pub struct CrossValidation<'a> {
    /// The dataset the folds borrow from
    dataset: &'a Dataset,

    /// Row numbers in each fold
    folds: Vec<Vec<usize>>,
}

impl<'a> CrossValidation<'a> {
    /// Deal a dataset's rows into `folds` stratified folds.
    ///
    /// # Errors
    ///
    /// Returns an error if there are fewer than two folds, the dataset fails
    /// [`Dataset::validate`] or has no labels, or either class has fewer rows than there are
    /// folds.
    pub fn new(dataset: &'a Dataset, folds: usize) -> Result<Self> {
        ensure!(folds >= 2, "Cross validation needs at least two folds");
        ensure!(
            !dataset.labels.is_empty() && dataset.labels.len() == dataset.len(),
            "Cross validation requires a label for every row"
        );
        ensure!(dataset.validate(), "Dataset didn't pass validity check");

        let mut rng = rand::rng();
        let (mut benign, mut malicious): (Vec<usize>, Vec<usize>) =
            (0..dataset.len()).partition(|row| dataset.labels[*row] == 0);
        ensure!(
            benign.len() >= folds && malicious.len() >= folds,
            "Each class needs at least one row per fold, but there are {} benign and {} \
             malicious rows for {folds} folds",
            benign.len(),
            malicious.len()
        );
        benign.shuffle(&mut rng);
        malicious.shuffle(&mut rng);

        // Dealing the malicious rows on from where the benign ones stopped keeps the fold
        // sizes within one row of each other.
        let mut dealt = vec![Vec::with_capacity(dataset.len() / folds + 1); folds];
        for (position, row) in benign.into_iter().chain(malicious).enumerate() {
            dealt[position % folds].push(row);
        }

        Ok(Self {
            dataset,
            folds: dealt,
        })
    }

    /// Number of folds.
    #[must_use]
    pub const fn folds(&self) -> usize {
        self.folds.len()
    }

    /// The training and test sets for one fold.
    ///
    /// Which majority-class rows are left out of the training set is chosen afresh on every
    /// call, so two calls for the same fold can train on different rows.
    ///
    /// # Errors
    ///
    /// Returns an error if `index` isn't a fold.
    pub fn fold(&self, index: usize) -> Result<Fold<'a>> {
        let test = self
            .folds
            .get(index)
            .ok_or_else(|| anyhow!("Fold {index} out of range, there are {}", self.folds()))?
            .clone();

        let (mut benign, mut malicious): (Vec<usize>, Vec<usize>) = self
            .folds
            .iter()
            .enumerate()
            .filter(|(other, _)| *other != index)
            .flat_map(|(_, rows)| rows.iter().copied())
            .partition(|row| self.dataset.labels[*row] == 0);

        let mut rng = rand::rng();
        let per_class = benign.len().min(malicious.len());
        for class in [&mut benign, &mut malicious] {
            if class.len() > per_class {
                class.shuffle(&mut rng);
                class.truncate(per_class);
            }
        }
        benign.append(&mut malicious);

        Ok(Fold {
            index,
            train: DatasetView::new(self.dataset, benign)?,
            test: DatasetView::new(self.dataset, test)?,
        })
    }

    /// Train and test a fresh model on one fold, see [`LogisticRegression::fit`].
    ///
    /// # Errors
    ///
    /// Returns an error if `index` isn't a fold or training fails.
    ///
    /// # Panics
    ///
    /// This won't panic as there will be a test result.
    pub fn run_fold(
        &self,
        index: usize,
        epochs: u32,
        learning_rate: f32,
        l1: f32,
        l2: f32,
    ) -> Result<FoldResult> {
        let Fold {
            mut train, test, ..
        } = self.fold(index)?;

        let mut model = LogisticRegression::new(train.row_len(), learning_rate, l1, l2);
        let run = model.fit(epochs, &mut train, Some(&test))?;

        Ok(FoldResult {
            index,
            train_rows: train.len(),
            test_rows: test.len(),
            loss: run.loss,
            features_removed: run.features_removed,
            test_performance: model.test_performance.unwrap(),
            model,
        })
    }

    /// Train and test a fresh model on every fold in turn.
    ///
    /// # Errors
    ///
    /// Returns an error if any fold fails to train.
    pub fn run(
        &self,
        epochs: u32,
        learning_rate: f32,
        l1: f32,
        l2: f32,
        metric: SelectionMetric,
    ) -> Result<CrossValidationReport> {
        let folds = (0..self.folds())
            .map(|index| self.run_fold(index, epochs, learning_rate, l1, l2))
            .collect::<Result<Vec<_>>>()?;
        CrossValidationReport::new(folds, metric)
    }
}

/// The model trained on one fold, and how it did.
#[derive(Debug, Clone)]
pub struct FoldResult {
    /// Which fold this is, from zero
    pub index: usize,

    /// Rows trained on
    pub train_rows: usize,

    /// Rows held out and tested on
    pub test_rows: usize,

    /// Mean log loss of the final epoch
    pub loss: f32,

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

    /// The trained model. Its `test_performance` is on the held-out fold.
    pub model: LogisticRegression,

    /// Performance results on the test data
    pub test_performance: PerformanceStats,
}

/// The measure used to pick the best fold's model.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SelectionMetric {
    /// Correct predictions over all predictions
    Accuracy,

    /// True positives over predicted positives
    Precision,

    /// True positives over actual positives
    Recall,

    /// Harmonic mean of precision and recall
    F1,

    /// Area under the ROC curve, which doesn't depend on the 0.5 threshold
    #[default]
    Auc,
}

impl SelectionMetric {
    /// Every metric, in display order.
    pub const ALL: [Self; 5] = [
        Self::Accuracy,
        Self::Precision,
        Self::Recall,
        Self::F1,
        Self::Auc,
    ];

    /// This metric's score for some performance statistics.
    #[must_use]
    pub fn score(self, stats: &PerformanceStats) -> f32 {
        match self {
            Self::Accuracy => stats.accuracy(),
            Self::Precision => stats.precision,
            Self::Recall => stats.recall,
            Self::F1 => stats.f1,
            Self::Auc => stats.auc,
        }
    }
}

impl Display for SelectionMetric {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Accuracy => "accuracy",
            Self::Precision => "precision",
            Self::Recall => "recall",
            Self::F1 => "f1",
            Self::Auc => "auc",
        })
    }
}

impl FromStr for SelectionMetric {
    type Err = anyhow::Error;

    fn from_str(value: &str) -> Result<Self> {
        Self::ALL
            .into_iter()
            .find(|metric| metric.to_string().eq_ignore_ascii_case(value))
            .ok_or_else(|| {
                anyhow!("Unknown metric '{value}', expected accuracy, precision, recall, f1 or auc")
            })
    }
}

/// Every fold's model and performance, and which is best.
#[derive(Debug, Clone)]
pub struct CrossValidationReport {
    /// Each fold's result, in fold order
    pub folds: Vec<FoldResult>,

    /// The measure the best fold was picked by
    pub metric: SelectionMetric,

    /// Position in `folds` of the best fold
    best: usize,
}

impl CrossValidationReport {
    /// Collect the fold results and pick the best by `metric` on the held-out data, breaking
    /// ties by AUC (or by F1 when AUC is the metric).
    ///
    /// A fold whose score is `NaN`, such as precision when nothing was predicted malicious,
    /// counts as worse than any other.
    ///
    /// # Errors
    ///
    /// Returns an error if there are no folds.
    pub fn new(folds: Vec<FoldResult>, metric: SelectionMetric) -> Result<Self> {
        let tie_breaker = if metric == SelectionMetric::Auc {
            SelectionMetric::F1
        } else {
            SelectionMetric::Auc
        };
        let score = |metric: SelectionMetric, fold: &FoldResult| {
            let score = metric.score(&fold.test_performance);
            if score.is_nan() {
                f32::NEG_INFINITY
            } else {
                score
            }
        };
        let best = folds
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| {
                score(metric, a)
                    .total_cmp(&score(metric, b))
                    .then_with(|| score(tie_breaker, a).total_cmp(&score(tie_breaker, b)))
            })
            .map(|(position, _)| position)
            .ok_or_else(|| anyhow!("Cross validation produced no folds"))?;

        Ok(Self {
            folds,
            metric,
            best,
        })
    }

    /// The best fold.
    #[must_use]
    pub fn best(&self) -> &FoldResult {
        &self.folds[self.best]
    }

    /// Take the best fold's model, discarding the others.
    #[must_use]
    pub fn into_best(mut self) -> LogisticRegression {
        self.folds.swap_remove(self.best).model
    }

    /// Mean and sample standard deviation of a metric on the held-out folds.
    ///
    /// Folds scoring `NaN` are left out.
    #[must_use]
    #[allow(clippy::cast_precision_loss)]
    pub fn mean_std(&self, metric: SelectionMetric) -> (f32, f32) {
        let scores = self
            .folds
            .iter()
            .map(|fold| metric.score(&fold.test_performance))
            .filter(|score| !score.is_nan())
            .collect::<Vec<_>>();
        if scores.is_empty() {
            return (f32::NAN, f32::NAN);
        }

        let mean = scores.iter().sum::<f32>() / scores.len() as f32;
        let std = if scores.len() > 1 {
            (scores.iter().map(|s| (s - mean).powi(2)).sum::<f32>() / (scores.len() - 1) as f32)
                .sqrt()
        } else {
            0.0
        };
        (mean, std)
    }
}

impl Display for CrossValidationReport {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        writeln!(
            f,
            "Fold | Train rows | Test rows |  Loss    | Features | Accuracy | Precision | Recall | F1     | AUC"
        )?;
        for fold in &self.folds {
            let stats = fold.test_performance;
            writeln!(
                f,
                "{:>4} | {:>10} | {:>9} | {:<8.6} | {:>8} | {:<8.4} | {:<9.4} | {:<6.4} | {:<6.4} | {:<6.4}{}",
                fold.index + 1,
                fold.train_rows,
                fold.test_rows,
                fold.loss,
                fold.model.weights.len(),
                stats.accuracy(),
                stats.precision,
                stats.recall,
                stats.f1,
                stats.auc,
                if fold.index == self.best().index {
                    "  <- best"
                } else {
                    ""
                }
            )?;
        }

        writeln!(f)?;
        for metric in SelectionMetric::ALL {
            let (mean, std) = self.mean_std(metric);
            writeln!(f, "{:<10} {mean:.4} ± {std:.4}", format!("{metric}:"))?;
        }
        writeln!(
            f,
            "\nBest fold by {}: {}",
            self.metric,
            self.best().index + 1
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::row::{DataMatrix, DataRow};

    /// Build a dataset whose rows encode their own index in binary, so folds can be checked
    /// for lost or duplicated rows and for labels that didn't travel with their rows.
    fn indexed_dataset(benign: usize, malicious: usize) -> Dataset {
        const BITS: usize = 16;
        let total = benign + malicious;
        Dataset {
            data: (0..total)
                .map(|row| {
                    let mut r = DataRow::zeroed(BITS);
                    for bit in 0..BITS {
                        if row & (1 << bit) != 0 {
                            r.set(bit, 1.0).unwrap();
                        }
                    }
                    r
                })
                .collect::<DataMatrix>(),
            labels: (0..total).map(|row| u8::from(row >= benign)).collect(),
            features: (0..BITS).map(|b| vec![u8::try_from(b).unwrap()]).collect(),
            ftype: FileType::PDF,
            stride: 1,
        }
    }

    /// Decode the dataset row numbers of a view, checking each label came with its row.
    fn row_ids(view: &DatasetView<'_>, benign: usize) -> Vec<usize> {
        view.labelled_rows()
            .map(|(row, label)| {
                let id = row.iter_nonzero().map(|(bit, _)| 1 << bit).sum::<usize>();
                assert_eq!(label, u8::from(id >= benign), "row {id} lost its label");
                id
            })
            .collect()
    }

    #[test]
    fn every_row_is_tested_exactly_once() {
        let dataset = indexed_dataset(700, 300);
        let cv = CrossValidation::new(&dataset, 5).unwrap();

        let mut tested = vec![];
        for index in 0..cv.folds() {
            let fold = cv.fold(index).unwrap();
            // Stratified: each fold holds the dataset's 70/30 split.
            assert_eq!(fold.test.class_counts(), (140, 60));
            tested.extend(row_ids(&fold.test, 700));
        }
        tested.sort_unstable();
        assert_eq!(tested, (0..1000).collect::<Vec<_>>());
    }

    #[test]
    fn training_folds_are_balanced_and_disjoint_from_test() {
        let dataset = indexed_dataset(700, 300);
        let cv = CrossValidation::new(&dataset, 5).unwrap();

        for index in 0..cv.folds() {
            let fold = cv.fold(index).unwrap();
            assert_eq!(fold.train.class_counts(), (240, 240));

            let train = row_ids(&fold.train, 700);
            let test = row_ids(&fold.test, 700);
            assert!(train.iter().all(|row| !test.contains(row)));

            let mut unique = train.clone();
            unique.sort_unstable();
            unique.dedup();
            assert_eq!(unique.len(), train.len(), "fold {index} repeats a row");
        }
    }

    /// Views reorder row numbers, not the dataset.
    #[test]
    fn shuffling_a_view_leaves_the_dataset_alone() {
        let dataset = indexed_dataset(50, 50);
        let before = dataset.clone();
        let cv = CrossValidation::new(&dataset, 2).unwrap();
        let mut fold = cv.fold(0).unwrap();

        let mut ids = row_ids(&fold.train, 50);
        fold.train.shuffle();
        let mut shuffled = row_ids(&fold.train, 50);
        ids.sort_unstable();
        shuffled.sort_unstable();
        assert_eq!(ids, shuffled);
        assert_eq!(dataset.data, before.data);
        assert_eq!(dataset.labels, before.labels);
    }

    #[test]
    fn view_column_sums_match_its_rows() {
        let dataset = indexed_dataset(20, 20);
        let all = DatasetView::new(&dataset, (0..dataset.len()).collect()).unwrap();
        assert_eq!(TrainingData::column_sums(&all), dataset.column_sums());

        let one = DatasetView::new(&dataset, vec![5]).unwrap();
        let sums = TrainingData::column_sums(&one);
        assert_eq!(sums[0], 1.0);
        assert_eq!(sums[1], 0.0);
        assert_eq!(sums[2], 1.0);
        assert_eq!(sums.iter().sum::<f32>(), 2.0);
    }

    #[test]
    fn rejects_bad_input() {
        let dataset = indexed_dataset(10, 3);
        assert!(CrossValidation::new(&dataset, 1).is_err());
        assert!(CrossValidation::new(&dataset, 4).is_err());
        assert!(CrossValidation::new(&dataset, 3).is_ok());
        assert!(CrossValidation::new(&dataset, 3).unwrap().fold(3).is_err());

        let mut unlabelled = dataset.clone();
        unlabelled.labels.clear();
        assert!(CrossValidation::new(&unlabelled, 2).is_err());
        assert!(DatasetView::new(&dataset, vec![13]).is_err());
    }

    #[test]
    fn run_keeps_a_model_per_fold_and_picks_the_best() {
        // Bit 6 of the row number is set exactly for the malicious rows, so there is signal
        // to learn.
        let dataset = indexed_dataset(64, 64);
        let folds = 4;

        let cv = CrossValidation::new(&dataset, folds).unwrap();
        let report = cv.run(5, 0.2, 0.0, 0.0, SelectionMetric::Auc).unwrap();
        assert_eq!(report.folds.len(), folds);
        assert!(report.folds.iter().all(|f| f.model.trained));
        assert!(
            report
                .folds
                .iter()
                .all(|f| f.model.test_performance.is_some())
        );

        let best_auc = report.best().test_performance.auc;
        assert!(
            report
                .folds
                .iter()
                .all(|f| f.test_performance.auc <= best_auc)
        );
        assert!(report.to_string().contains("<- best"));

        let best = report.best().model.clone();
        assert_eq!(report.into_best(), best);
    }

    #[test]
    fn metric_round_trips_through_strings() {
        for metric in SelectionMetric::ALL {
            assert_eq!(
                metric.to_string().parse::<SelectionMetric>().unwrap(),
                metric
            );
        }
        assert_eq!(
            "AUC".parse::<SelectionMetric>().unwrap(),
            SelectionMetric::Auc
        );
        assert!("bogus".parse::<SelectionMetric>().is_err());
    }
}