File size: 5,723 Bytes
dba945b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
"""fp8_probe.py <net> [calib_n]: can the engine of our net run in FP8 (Q/DQ inserted by NVIDIA ModelOpt PTQ) on this GPU? (box side)

Exports the net to ONNX (half, dynamic batch), calibrates on `calib_n` (default 2048) positions of our games (dag6_roots.json),
quantizes the convolutions / matmuls to FP8 (ModelOpt onnx PTQ), builds fixed-batch-256 engines for the fp16 original and the
FP8 version, and prints for both: ms per batch and positions/s; for FP8 vs fp16 on 2048 held-out positions: share of equal top-1
move, mean KL(fp16 || fp8) of the priors over the legal-move-free full softmax, max / mean |value difference| (value in [-1, 1]).
Success: >= 1.3x faster, top-1 >= 98.5%, mean KL <= 0.005, mean |dv| <= 0.01. Log: whatever it prints; FP8_PROBE_DONE at the end."""
import json, os, random, sys, time

import numpy as np
import torch

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
net = sys.argv[1]
NCAL = int(sys.argv[2]) if len(sys.argv) > 2 else 2048
ROOT = "/marimo/chess"
CK = f"{ROOT}/ckpt_{net}.pt"
B = 256

import chess
import tensorrt as trt

import chessnet
import gpuchess as G
from chessnet import make_net, planes
from trtnet import TrtRunner, _Play

print("TensorRT", trt.__version__, flush=True)
d = torch.load(CK, map_location="cuda")
roots = json.load(open(f"{ROOT}/dag6/dag6_roots.json"))
random.Random(11).shuffle(roots)


def positions(n, skip=0):
    xs = []
    for r in roots[skip:skip + n]:
        u, t, f = G.from_board(chess.Board(r["fen"]), "cuda")
        xs.append(planes(torch.cat([u, t], 1), f))
    return torch.cat(xs)


calib = positions(NCAL, 0)
test = positions(2048, NCAL)
chessnet.ATTN_IMPL = "manual"
half = make_net(d).cuda().eval()
half.load_state_dict(d["state"])
half = _Play(half.half())
onnx = f"/tmp/fp8_{net}.onnx"
torch.onnx.export(half, (calib[:B].half(),), onnx, opset_version=17, input_names=["x"], output_names=["pol", "val"],
                  dynamic_axes={"x": {0: "b"}, "pol": {0: "b"}, "val": {0: "b"}}, dynamo=False)
full = make_net(d).cuda().eval()                          # the fp32 export is what ModelOpt quantizes (it casts the rest to fp16 itself)
full.load_state_dict(d["state"])
onnx32 = f"/tmp/fp8_{net}_f32.onnx"
torch.onnx.export(_Play(full), (calib[:B].float(),), onnx32, opset_version=17, input_names=["x"], output_names=["pol", "val"],
                  dynamic_axes={"x": {0: "b"}, "pol": {0: "b"}, "val": {0: "b"}}, dynamo=False)
print("onnx exported", flush=True)


def build(onnx_path, plan, strongly_typed):
    log = trt.Logger(trt.Logger.WARNING)
    bld = trt.Builder(log)
    flags = 0
    if strongly_typed and hasattr(trt.NetworkDefinitionCreationFlag, "STRONGLY_TYPED"):
        flags = 1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)
    n = bld.create_network(flags)
    parser = trt.OnnxParser(n, log)
    if not parser.parse_from_file(onnx_path):
        for i in range(parser.num_errors):
            print("PARSE", parser.get_error(i))
        raise RuntimeError("parse " + onnx_path)
    cfg = bld.create_builder_config()
    if hasattr(trt.BuilderFlag, "FP16") and not strongly_typed:
        cfg.set_flag(trt.BuilderFlag.FP16)
    if hasattr(trt.BuilderFlag, "FP8") and not strongly_typed:
        cfg.set_flag(trt.BuilderFlag.FP8)
    prof = bld.create_optimization_profile()
    prof.set_shape("x", (B, 17, 8, 8), (B, 17, 8, 8), (B, 17, 8, 8))
    cfg.add_optimization_profile(prof)
    t0 = time.time()
    p = bld.build_serialized_network(n, cfg)
    if p is None:
        raise RuntimeError("build failed")
    open(plan, "wb").write(p)
    return time.time() - t0


def clock(r, x, n=200):
    for _ in range(20):
        r(x)
    torch.cuda.synchronize()
    a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    a.record()
    for _ in range(n):
        r(x)
    b.record()
    torch.cuda.synchronize()
    return a.elapsed_time(b) / n


def run_all(r):
    ps, vs = [], []
    for i in range(0, len(test), B):
        o = r(test[i:i + B].half())
        ps.append(o["pol"].float().clone())
        vs.append(o["val"].float().clone())
    return torch.cat(ps), torch.cat(vs)


tb = build(onnx, "/tmp/fp8_ref.trt", False)
ref = TrtRunner("/tmp/fp8_ref.trt", B=B)
ms_ref = clock(ref, test[:B].half())
print(f"fp16 engine: {ms_ref:.2f} ms / batch = {B / ms_ref * 1000:,.0f} positions/s (built in {tb:.0f} s)", flush=True)
pr, vr = run_all(ref)

from modelopt.onnx.quantization import quantize
qonnx = f"/tmp/fp8_{net}_q.onnx"
t0 = time.time()
quantize(onnx32, quantize_mode="fp8", calibration_data={"x": calib.float().cpu().numpy()}, calibration_method="max",
         calibration_eps=["cpu"], output_path=qonnx)
print(f"ModelOpt FP8 quantization: {time.time() - t0:.0f} s", flush=True)
for strongly in (True, False):
    try:
        tb = build(qonnx, f"/tmp/fp8_q_{int(strongly)}.trt", strongly)
    except Exception as e:
        print(f"build (strongly typed={strongly}) failed: {type(e).__name__} {str(e)[:200]}", flush=True)
        continue
    r8 = TrtRunner(f"/tmp/fp8_q_{int(strongly)}.trt", B=B)
    ms = clock(r8, test[:B].half())
    p8, v8 = run_all(r8)
    kl = (torch.softmax(pr, 1) * (torch.log_softmax(pr, 1) - torch.log_softmax(p8, 1))).sum(1)
    dv = ((2 * torch.sigmoid(vr) - 1) - (2 * torch.sigmoid(v8) - 1)).abs()
    print(f"fp8 engine (strongly typed={strongly}): {ms:.2f} ms / batch = {B / ms * 1000:,.0f} positions/s ({ms_ref / ms:.2f}x), built in {tb:.0f} s; "
          f"top1 same {float((pr.argmax(1) == p8.argmax(1)).float().mean()):.4f}  mean KL {float(kl.mean()):.5f}  "
          f"|dv| mean {float(dv.mean()):.4f} max {float(dv.max()):.4f}  nan {int(torch.isnan(p8).sum())}", flush=True)
print("FP8_PROBE_DONE")