File size: 2,726 Bytes
f730521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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