File size: 3,700 Bytes
5f0b693
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Score one of our checkpoints on a test set, in the same JSON shape as run_ncm.py.

Writing both systems' results to one schema is what lets compare.py and
difficulty_curve.py put them on a single axis without special cases.

    python ncm/eval_ours.py --run runs/rec1-full-s0 --data data/sudoku_hard --passes 61

The run directory needs model.pt and result.json; the architecture is rebuilt
from the configuration the run was trained with, so a checkpoint trained
without input injection or with the step embedding reloads as what it was.
"""
import argparse
import json
import time
from collections import defaultdict
from pathlib import Path

import numpy as np
import torch

from demo import load_ours

LEVELS = (1, 4, 16, 61)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--run", required=True)
    ap.add_argument("--data", required=True)
    ap.add_argument("--split", default="test")
    ap.add_argument("--passes", type=int, default=61)
    ap.add_argument("--batch", type=int, default=200)
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--out", default="")
    ap.add_argument("--device", default="cpu")
    ap.add_argument("--seed", type=int, default=0,
                    help="the decoder commits sampled tokens, so fix the seed to make a run "
                         "reproducible; the published numbers were produced without one")
    a = ap.parse_args()

    torch.manual_seed(a.seed)

    import diffusion as dfn

    P = np.load(Path(a.data) / f"{a.split}_puz.npy")
    S = np.load(Path(a.data) / f"{a.split}_sol.npy")
    if a.limit:
        P, S = P[:a.limit], S[:a.limit]

    model, tok, cfg = load_ours(a.run, a.device)
    n_params = sum(p.numel() for p in model.parameters())
    label = "recurrent" if cfg.get("recurrent") else f"{cfg['layers']}-layer feed-forward"

    board = np.zeros(len(P), dtype=bool)
    t0 = time.time()
    with torch.no_grad():
        for i in range(0, len(P), a.batch):
            puz = torch.from_numpy(P[i:i + a.batch].astype(np.int64)).to(a.device)
            sol = torch.from_numpy(S[i:i + a.batch].astype(np.int64)).to(a.device)
            blank = puz == 0
            x = torch.where(blank, torch.full_like(puz, tok.mask), puz - 1)
            y, _ = dfn.fixed_k_decode(model, x, tok, a.device, a.passes, fillable=blank)
            board[i:i + a.batch] = ((y + 1) == sol).all(1).cpu().numpy()
            print(f"  {min(i + a.batch, len(P))}/{len(P)}  "
                  f"board {board[:i + a.batch].mean():.1%}  {time.time() - t0:.0f}s", flush=True)
    secs = time.time() - t0

    clues = (P > 0).sum(1)
    by_clue = defaultdict(lambda: {"n": 0, "board": 0})
    for k, ok in zip(clues, board):
        by_clue[int(k)]["n"] += 1
        by_clue[int(k)]["board"] += int(ok)

    result = {
        "model": f"ours, {label}",
        "params": f"{n_params / 1e3:.0f}k",
        "run": str(a.run),
        "data": str(a.data),
        "split": a.split,
        "n": len(P),
        "nfe": a.passes,
        "seed": a.seed,
        "board_accuracy": float(board.mean()),
        "clues_min": int(clues.min()),
        "clues_max": int(clues.max()),
        "clues_mean": float(clues.mean()),
        "by_clue": {str(k): v for k, v in sorted(by_clue.items())},
        "seconds": secs,
    }

    print(f"\n{result['model']} ({result['params']}) on {a.data}, {a.passes} passes")
    print(f"  board accuracy {result['board_accuracy']:.2%} of {len(P)}   ({secs:.0f}s)")

    if a.out:
        Path(a.out).parent.mkdir(parents=True, exist_ok=True)
        json.dump(result, open(a.out, "w"), indent=2)
        print(f"  written to {a.out}")


if __name__ == "__main__":
    main()