File size: 6,177 Bytes
8f63b49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Train the MalConv baseline, or score a split with the trained weights.

    python src/train_malconv.py                       # train (best pass chosen by validation AUC)
    python src/train_malconv.py --score val           # write model/malconv_scores_val.csv
    python src/train_malconv.py --score test          # ONCE, at the very end

Same procedure as the main model: class-weighted loss, early stopping on validation AUC,
a checkpoint saved after every pass, test set never used during training.
"""
import argparse
import csv
import os
import time

import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics import roc_auc_score, roc_curve
from torch.utils.data import DataLoader

from malconv import ByteDataset, MalConv, count_parameters

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def predict_all(model, loader, device):
    model.eval()
    logits, labels = [], []
    with torch.no_grad():
        for x, y in loader:
            with torch.autocast(device, dtype=torch.bfloat16):
                logits.append(model(x.to(device, non_blocking=True)).float().cpu())
            labels.append(y)
    return torch.cat(logits), torch.cat(labels)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--name", default="malconv_baseline")
    ap.add_argument("--batch-size", type=int, default=64)
    ap.add_argument("--epochs", type=int, default=15)
    ap.add_argument("--lr", type=float, default=2e-4)
    ap.add_argument("--weight-decay", type=float, default=1e-4)
    ap.add_argument("--patience", type=int, default=3)
    ap.add_argument("--workers", type=int, default=24)
    ap.add_argument("--seed", type=int, default=1337)
    ap.add_argument("--score", choices=["val", "test"], help="score this split with the saved weights instead of training")
    args = ap.parse_args()

    torch.manual_seed(args.seed)
    np.random.seed(args.seed)
    device = "cuda"
    manifest, data_dir, out_dir = os.path.join(ROOT, "dataset", "manifest.csv"), os.path.join(ROOT, "data"), os.path.join(ROOT, "model")
    best_path, last_path, log_path = (os.path.join(out_dir, f"{args.name}{s}") for s in (".pt", "_last.pt", "_log.csv"))
    model = MalConv().to(device)

    if args.score:
        out = os.path.join(out_dir, f"malconv_scores_{args.score}.csv")
        if args.score == "test" and os.path.exists(out):
            raise SystemExit(f"{out} already exists: the test set is scored only once.")
        model.load_state_dict(torch.load(best_path, map_location=device, weights_only=True)["state_dict"])
        ds = ByteDataset(manifest, data_dir, args.score)
        logits, _ = predict_all(model, DataLoader(ds, batch_size=args.batch_size, num_workers=args.workers), device)
        with open(out, "w", newline="") as f:
            w = csv.writer(f)
            w.writerow(["sha256", "label", "probability"])
            for (path, label), p in zip(ds.items, torch.sigmoid(logits).tolist()):
                w.writerow([os.path.basename(path), label, f"{p:.6f}"])
        print(f"{len(ds)} files scored -> {out}")
        return

    train_ds, val_ds = ByteDataset(manifest, data_dir, "train"), ByteDataset(manifest, data_dir, "val")
    train_dl = DataLoader(train_ds, batch_size=args.batch_size, shuffle=True, num_workers=args.workers,
                          pin_memory=True, drop_last=True, persistent_workers=True)
    val_dl = DataLoader(val_ds, batch_size=args.batch_size, shuffle=False, num_workers=args.workers, pin_memory=True)

    n_pos = sum(y for _, y in train_ds.items)
    pos_weight = torch.tensor((len(train_ds) - n_pos) / n_pos)       # balance the two classes in the loss
    train_loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_weight.to(device))
    eval_loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
    opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
    print(f"{count_parameters(model):,} parameters | train {len(train_ds)} | val {len(val_ds)} | lr {args.lr} | "
          f"batch {args.batch_size} | up to {args.epochs} epochs, patience {args.patience}", flush=True)
    with open(log_path, "w", newline="") as f:
        csv.writer(f).writerow(["epoch", "train_loss", "val_loss", "val_auc", "val_tpr_at_1pct_fpr", "seconds"])

    best_auc, bad_epochs = 0.0, 0
    for epoch in range(1, args.epochs + 1):
        t0 = time.time()
        model.train()
        total, n = 0.0, 0
        for x, y in train_dl:
            x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
            with torch.autocast(device, dtype=torch.bfloat16):
                loss = train_loss_fn(model(x).float(), y)
            opt.zero_grad(set_to_none=True)
            loss.backward()
            opt.step()
            total, n = total + loss.item() * len(y), n + len(y)
        logits, labels = predict_all(model, val_dl, device)
        probs = torch.sigmoid(logits).numpy()
        fpr, tpr, _ = roc_curve(labels.numpy(), probs)
        val_loss, val_auc, val_tpr = eval_loss_fn(logits, labels).item(), roc_auc_score(labels.numpy(), probs), float(np.interp(0.01, fpr, tpr))
        secs = time.time() - t0
        improved = val_auc > best_auc
        if improved:
            best_auc, bad_epochs = val_auc, 0
            torch.save({"state_dict": model.state_dict(), "config": vars(args), "epoch": epoch}, best_path)
        else:
            bad_epochs += 1
        torch.save({"model": model.state_dict(), "opt": opt.state_dict(), "epoch": epoch}, last_path)   # checkpoint every pass
        with open(log_path, "a", newline="") as f:
            csv.writer(f).writerow([epoch, f"{total / n:.4f}", f"{val_loss:.4f}", f"{val_auc:.4f}", f"{val_tpr:.4f}", f"{secs:.0f}"])
        print(f"epoch {epoch:2d}  train loss {total / n:.4f}  val loss {val_loss:.4f}  val AUC {val_auc:.4f}  "
              f"val detection@1%FPR {val_tpr:.3f}  {secs:.0f}s {'*' if improved else ''}", flush=True)
        if bad_epochs >= args.patience:
            print(f"early stop: no better val AUC for {args.patience} epochs")
            break
    print(f"best val AUC {best_auc:.4f} -> {best_path}")


if __name__ == "__main__":
    main()