Download src/train_chunk.py from adamuremek/pe-malware-detector: direct link, hf CLI and curl.
- Browser
- Download file 7.31 kB
-
https://huggingface.co/adamuremek/pe-malware-detector/resolve/main/src/train_chunk.py
- Command line
-
hf download hf://adamuremek/pe-malware-detector/src/train_chunk.py
-
curl -L -o train_chunk.py https://huggingface.co/adamuremek/pe-malware-detector/resolve/main/src/train_chunk.py
7.31 kB
| """Train the chunk attention model: class-weighted loss, best epoch chosen by validation AUC, | |
| test set never touched. | |
| python src/train_chunk.py --name chunk_full | |
| python src/train_chunk.py --name chunk_no_region --no-region # ablation: no region tags | |
| python src/train_chunk.py --name chunk_no_tf --layers 0 # ablation: no chunk-to-chunk attention | |
| """ | |
| 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 chunk_model import ChunkAttentionNet, ChunkDataset, count_parameters | |
| ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| KEYS = ("tokens", "region", "position", "stats") | |
| def run_model(model, batch, device): | |
| args = [batch[k].to(device, non_blocking=True) for k in KEYS] | |
| with torch.autocast(device, dtype=torch.bfloat16): | |
| return model(*args).float() | |
| def evaluate(model, loader, device, loss_fn): | |
| model.eval() | |
| logits, labels = [], [] | |
| with torch.no_grad(): | |
| for batch in loader: | |
| logits.append(run_model(model, batch, device).cpu()) | |
| labels.append(batch["label"]) | |
| logits, labels = torch.cat(logits), torch.cat(labels) | |
| probs = torch.sigmoid(logits).numpy() | |
| fpr, tpr, _ = roc_curve(labels.numpy(), probs) | |
| return loss_fn(logits, labels).item(), roc_auc_score(labels.numpy(), probs), float(np.interp(0.01, fpr, tpr)) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--name", default="chunk_full") | |
| ap.add_argument("--batch-size", type=int, default=32) | |
| ap.add_argument("--epochs", type=int, default=20) | |
| ap.add_argument("--lr", type=float, default=3e-4) | |
| ap.add_argument("--weight-decay", type=float, default=0.01) | |
| ap.add_argument("--dropout", type=float, default=0.1) | |
| ap.add_argument("--layers", type=int, default=2, help="transformer layers (0 = attention pooling only)") | |
| ap.add_argument("--no-region", action="store_true") | |
| ap.add_argument("--no-stats", action="store_true") | |
| 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("--schedule", choices=["none", "cosine"], default="none", | |
| help="cosine: warm up for one epoch, then lower the learning rate smoothly to zero") | |
| ap.add_argument("--manifest", default=None, help="manifest CSV (default: dataset/manifest.csv)") | |
| ap.add_argument("--data-dir", default=None, help="folder with train/ val/ test/ (default: data/)") | |
| args = ap.parse_args() | |
| torch.manual_seed(args.seed) | |
| np.random.seed(args.seed) | |
| device = "cuda" | |
| manifest = args.manifest or os.path.join(ROOT, "dataset", "manifest.csv") | |
| data_dir = args.data_dir or os.path.join(ROOT, "data") | |
| out_dir = 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")) | |
| train_ds, val_ds = ChunkDataset(manifest, data_dir, "train"), ChunkDataset(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) | |
| n_neg = len(train_ds) - n_pos | |
| pos_weight = torch.tensor(n_neg / 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) | |
| model = ChunkAttentionNet(use_region=not args.no_region, use_stats=not args.no_stats, | |
| n_layers=args.layers, dropout=args.dropout).to(device) | |
| opt = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay) | |
| # Optional learning-rate schedule: big steps early to make progress, small steps late to settle. | |
| steps_per_epoch, total_steps = len(train_dl), len(train_dl) * args.epochs | |
| def lr_factor(step): | |
| if args.schedule == "none": | |
| return 1.0 | |
| if step < steps_per_epoch: # warm-up over the first epoch | |
| return (step + 1) / steps_per_epoch | |
| progress = (step - steps_per_epoch) / max(1, total_steps - steps_per_epoch) | |
| return 0.5 * (1 + np.cos(np.pi * min(progress, 1.0))) # cosine decay from 1 to 0 | |
| sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_factor) | |
| print(f"{count_parameters(model):,} parameters | train {len(train_ds)} | val {len(val_ds)} | " | |
| f"region tags {not args.no_region} | chunk stats {not args.no_stats} | transformer layers {args.layers} | " | |
| f"schedule {args.schedule} | 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, best_tpr = 0.0, 0, 0.0 | |
| tpr_path = os.path.join(out_dir, f"{args.name}_best_tpr.pt") | |
| for epoch in range(1, args.epochs + 1): | |
| t0 = time.time() | |
| model.train() | |
| total, n = 0.0, 0 | |
| for batch in train_dl: | |
| y = batch["label"].to(device, non_blocking=True) | |
| loss = train_loss_fn(run_model(model, batch, device), y) | |
| opt.zero_grad(set_to_none=True) | |
| loss.backward() | |
| nn.utils.clip_grad_norm_(model.parameters(), 1.0) # keeps transformer training stable | |
| opt.step() | |
| sched.step() | |
| total, n = total + loss.item() * len(y), n + len(y) | |
| val_loss, val_auc, val_tpr = evaluate(model, val_dl, device, eval_loss_fn) | |
| 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)}, best_path) | |
| else: | |
| bad_epochs += 1 | |
| if val_tpr > best_tpr: # also keep the pass that is best at 1% false positives | |
| best_tpr = val_tpr | |
| torch.save({"state_dict": model.state_dict(), "config": vars(args), "epoch": epoch}, tpr_path) | |
| torch.save({"model": model.state_dict(), "opt": opt.state_dict(), "epoch": epoch, | |
| "best_auc": best_auc, "bad_epochs": bad_epochs, "args": vars(args)}, last_path) | |
| 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() | |