blazebsc's picture
Upload train.py with huggingface_hub
b6d4565 verified
Raw History Blame Contribute Delete
5.79 kB
#!/usr/bin/env python3
"""Trains the crash-confirmation 1D-CNN on the 4070, exports TFLite + Kotlin weights."""
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import TensorDataset, DataLoader
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("device:", device)
class CrashCNN(nn.Module):
"""1D-CNN over a (3, 400) sensor window @ 50 Hz. ~44K params.
Channel sizes chosen by scale_experiment.py: the 4x variant gained
+0.5 crash recall over the 11K model; the 16x variant overfit and
lost recall."""
def __init__(self):
super().__init__()
self.conv = nn.Sequential(
nn.Conv1d(3, 32, kernel_size=5, stride=2, padding=2), # → (32, 200)
nn.ReLU(),
nn.MaxPool1d(4), # → (32, 50)
nn.Conv1d(32, 64, kernel_size=5, stride=2, padding=2), # → (64, 25)
nn.ReLU(),
nn.AdaptiveAvgPool1d(8), # → (64, 8)
)
self.head = nn.Sequential(
nn.Flatten(),
nn.Linear(64 * 8, 64),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(64, 2), # [not-crash, crash]
)
def forward(self, x):
return self.head(self.conv(x))
def main():
# seeded + batch 256 / 12 epochs — the configuration scale_experiment.py
# validated at 99.75% crash recall (batch 64/20 epochs overfits to 98.6%)
torch.manual_seed(42)
np.random.seed(42)
data = np.load("/home/blake7/Documents/GitHub/paralino/ml/dataset.npz")
train_x = torch.from_numpy(data["train_x"]) # (N, 3, 200)
train_y = torch.from_numpy(data["train_y"])
val_x = torch.from_numpy(data["val_x"])
val_y = torch.from_numpy(data["val_y"])
print(f"train {len(train_y)} ({sum(train_y).item()} crash) val {len(val_y)} ({sum(val_y).item()} crash)")
# class weights: crashes are rare
counts = np.bincount(data["train_y"])
weight = torch.tensor(len(train_y) / (2.0 * max(counts[1], 1)), dtype=torch.float32)
criterion = nn.CrossEntropyLoss(weight=torch.tensor([1.0, weight.item()], device=device))
model = CrashCNN().to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=12)
train_ds = TensorDataset(train_x, train_y)
train_loader = DataLoader(train_ds, batch_size=256, shuffle=True, drop_last=True)
best_score = 0.0
best_state = None
for epoch in range(12):
model.train()
total_loss = 0.0
for xb, yb in train_loader:
xb, yb = xb.to(device), yb.to(device)
optimizer.zero_grad()
loss = criterion(model(xb), yb)
loss.backward()
optimizer.step()
total_loss += loss.item() * len(xb)
scheduler.step()
model.eval()
with torch.no_grad():
vx = val_x.to(device)
preds = model(vx).argmax(dim=1).cpu()
val_acc = (preds == val_y).float().mean().item()
# crash recall — the metric that matters (missing a crash is worse)
crash_mask = val_y == 1
crash_recall = (preds[crash_mask] == 1).float().mean().item() if crash_mask.any() else 0.0
neg_acc = (preds[~crash_mask] == 0).float().mean().item() if (~crash_mask).any() else 0.0
print(f"epoch {epoch+1}: loss {total_loss/len(train_y):.4f} "
f"val_acc {val_acc:.3f} crash_recall {crash_recall:.3f} neg_acc {neg_acc:.3f}")
# select by recall + neg_acc (the experiment's criterion) — val_acc
# alone picks low-recall epochs when negatives dominate the average
score = crash_recall + neg_acc
if score > best_score:
best_score = score
best_state = {k: v.cpu().clone() for k, v in model.state_dict().items()}
if best_state:
model.load_state_dict(best_state)
torch.save(model.state_dict(), "/home/blake7/Documents/GitHub/paralino/ml/crash_cnn.pt")
print("saved crash_cnn.pt")
# export for Kotlin: flatten all weights into one binary + a JSON header.
# The decision threshold is baked in as a crash-logit bias offset: Kotlin
# fires at p' >= 0.5, which equals raw p >= 0.15 — the threshold sweep's
# knee (100% recall on 786 real held-out crashes, 97.3% neg accuracy).
# A missed crash is a safety failure; an extra false alarm is a dismissed
# countdown, so recall wins the trade. The saved .pt stays raw/unshifted.
DECISION_THRESHOLD = 0.15
import json, math
state = model.state_dict()
# trigger when raw z1 - z0 >= log(t/(1-t)); Kotlin fires when z1' - z0 >= 0,
# so the offset is the NEGATIVE of the log-odds (log(t/(1-t)) is negative
# for t < 0.5 and must RAISE the crash logit)
with torch.no_grad():
state["head.4.bias"][1] -= math.log(DECISION_THRESHOLD / (1 - DECISION_THRESHOLD))
layers = {}
flat = np.array([], dtype=np.float32)
for name, tensor in state.items():
arr = tensor.detach().cpu().numpy().astype(np.float32).flatten()
layers[name] = {"offset": int(len(flat)), "count": int(len(arr)),
"shape": list(tensor.shape)}
flat = np.concatenate([flat, arr])
flat.tofile("/home/blake7/Documents/GitHub/paralino/ml/crash_model_weights.bin")
with open("/home/blake7/Documents/GitHub/paralino/ml/crash_model_spec.json", "w") as f:
json.dump({"layers": layers}, f, indent=1)
total_params = sum(l["count"] for l in layers.values())
print(f"exported {total_params} params ({len(flat)*4} bytes) to crash_model_weights.bin")
if __name__ == "__main__":
main()