Download duplex/train_utils.py from RightNowAI/duplex-v0: direct link, hf CLI and curl.
- Browser
- Download file 2.73 kB
-
https://huggingface.co/RightNowAI/duplex-v0/resolve/main/duplex/train_utils.py
- Command line
-
hf download hf://RightNowAI/duplex-v0/duplex/train_utils.py
-
curl -L -o train_utils.py https://huggingface.co/RightNowAI/duplex-v0/resolve/main/duplex/train_utils.py
2.73 kB
| """Small helpers shared by the two trainers: DDP setup, a wall-clock budget that all | |
| ranks agree on, hourly checkpoints, a JSONL log, label metrics.""" | |
| import json | |
| import os | |
| import time | |
| import numpy as np | |
| import torch | |
| import torch.distributed as dist | |
| from duplex.spec import LABELS | |
| def setup_ddp(): | |
| world = int(os.environ.get("WORLD_SIZE", "1")) | |
| rank = int(os.environ.get("RANK", "0")) | |
| local = int(os.environ.get("LOCAL_RANK", "0")) | |
| if world > 1: | |
| torch.cuda.set_device(local) | |
| dist.init_process_group("nccl") | |
| device = torch.device("cuda", local) if torch.cuda.is_available() else torch.device("cpu") | |
| torch.backends.cuda.matmul.allow_tf32 = True | |
| torch.backends.cudnn.allow_tf32 = True | |
| return rank, world, device | |
| class Budget: | |
| """Rank 0's clock is the only clock: every rank reads the same elapsed time, so they | |
| use the same learning rate and stop on the same step.""" | |
| def __init__(self, max_hours, rank, world, device, ckpt_minutes=60.0): | |
| self.t0, self.max_s = time.time(), max_hours * 3600.0 | |
| self.rank, self.world, self.device = rank, world, device | |
| self.elapsed, self.every_s, self.next_ckpt = 0.0, ckpt_minutes * 60.0, 1 | |
| def sync(self): | |
| t = torch.tensor([time.time() - self.t0 if self.rank == 0 else 0.0], device=self.device, dtype=torch.float64) | |
| if self.world > 1: | |
| dist.all_reduce(t) | |
| self.elapsed = float(t.item()) | |
| return self.elapsed / self.max_s | |
| def checkpoint_due(self): | |
| """Returns the checkpoint number once, right after each full interval.""" | |
| if self.elapsed >= self.next_ckpt * self.every_s: | |
| self.next_ckpt += 1 | |
| return self.next_ckpt - 1 | |
| return None | |
| def log_row(path, **row): | |
| row = {k: (round(v, 6) if isinstance(v, float) else v) for k, v in row.items()} | |
| print(json.dumps(row), flush=True) | |
| if path: | |
| with open(path, "a", encoding="utf-8") as f: | |
| f.write(json.dumps(row) + "\n") | |
| def confusion(pred, gold, n=len(LABELS)): | |
| """Rows are the true label, columns the predicted one. Frames with gold < 0 are skipped.""" | |
| pred, gold = np.asarray(pred).reshape(-1), np.asarray(gold).reshape(-1) | |
| keep = gold >= 0 | |
| return np.bincount(gold[keep] * n + pred[keep], minlength=n * n).reshape(n, n) | |
| def precision_recall(conf): | |
| out = {} | |
| for i, name in enumerate(LABELS): | |
| tp, pred_n, gold_n = int(conf[i, i]), int(conf[:, i].sum()), int(conf[i, :].sum()) | |
| out[name] = { | |
| "precision": tp / pred_n if pred_n else None, | |
| "recall": tp / gold_n if gold_n else None, | |
| "frames": gold_n, | |
| "predicted": pred_n, | |
| } | |
| return out | |