"""trtnet.py [batch]: one of OUR nets (chessnet.Net) as a TensorRT fp16 engine, for gmcts3 with GM3_TRT=1. Run on a box (TensorRT engines are specific to the GPU and library version): exports the net in half precision to ONNX for a fixed batch (default 256: the search batch), builds the engine, times it and compares its output with PyTorch (fp32 reference, and the bf16 autocast the engine normally uses). Writes .b.trt. TrtRunner is the run-time side: an engine with fixed-shape inputs / outputs bound to torch tensors, so a call is one copy into the input buffer plus one enqueue on the current CUDA stream (it can be captured into a CUDA graph).""" import os import sys import time import torch import torch.nn as nn class TrtRunner: def __init__(self, plan, dev="cuda", B=None): """B: the batch for an engine with a dynamic batch dimension (Lc0 ONNX files).""" import tensorrt as trt dt = {trt.DataType.FLOAT: torch.float32, trt.DataType.HALF: torch.float16, trt.DataType.INT64: torch.int64, trt.DataType.INT32: torch.int32} self.log = trt.Logger(trt.Logger.ERROR) self.eng = trt.Runtime(self.log).deserialize_cuda_engine(open(plan, "rb").read()) self.ctx = self.eng.create_execution_context() self.inp, self.out = {}, {} names = [self.eng.get_tensor_name(i) for i in range(self.eng.num_io_tensors)] for n in names: if self.eng.get_tensor_mode(n) == trt.TensorIOMode.INPUT: shp = tuple(self.eng.get_tensor_shape(n)) if shp[0] < 0: shp = (B,) + shp[1:] self.ctx.set_input_shape(n, shp) self.inp[n] = torch.zeros(shp, dtype=dt[self.eng.get_tensor_dtype(n)], device=dev) for n in names: if n not in self.inp: self.out[n] = torch.zeros(tuple(self.ctx.get_tensor_shape(n)), dtype=dt[self.eng.get_tensor_dtype(n)], device=dev) for n, t in list(self.inp.items()) + list(self.out.items()): self.ctx.set_tensor_address(n, t.data_ptr()) self.x = next(iter(self.inp.values())) self.extra = list(self.inp.values())[1:] # further inputs (a legal-move net: the legal slots li [B, K]) self.B = self.x.shape[0] def __call__(self, x, *extra): self.x.copy_(x) for buf, e in zip(self.extra, extra): buf.copy_(e) self.ctx.execute_async_v3(torch.cuda.current_stream().cuda_stream) return self.out def build(onnx_path, plan_path, shape=None): """ONNX -> engine file; shape = the fixed input shape if the ONNX batch is dynamic (Lc0 nets).""" import tensorrt as trt log = trt.Logger(trt.Logger.WARNING) builder = trt.Builder(log) net = builder.create_network(0) parser = trt.OnnxParser(net, log) if not parser.parse_from_file(onnx_path): for i in range(parser.num_errors): print("PARSE", parser.get_error(i)) raise RuntimeError("TensorRT could not parse " + onnx_path) cfg = builder.create_builder_config() if hasattr(trt.BuilderFlag, "FP16"): # TensorRT <= 10; from 11 on the ONNX types decide cfg.set_flag(trt.BuilderFlag.FP16) if shape is not None: prof = builder.create_optimization_profile() prof.set_shape(net.get_input(0).name, shape, shape, shape) cfg.add_optimization_profile(prof) t0 = time.time() plan = builder.build_serialized_network(net, cfg) if plan is None: raise RuntimeError("TensorRT build failed") open(plan_path, "wb").write(plan) print(f"engine built in {time.time() - t0:.0f} s, {os.path.getsize(plan_path) / 1e6:.0f} MB", flush=True) class _Play(nn.Module): def __init__(self, net): super().__init__() self.net = net def forward(self, x): pol, val = self.net(x) return pol, val @torch.no_grad() def main(): import random import chess sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import chessnet import gpuchess as G from chessnet import make_net, planes ck, B = sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 256 d = torch.load(ck, map_location="cuda") net = make_net(d).cuda().eval() net.load_state_dict(d["state"]) rng, bs = random.Random(3), [] while len(bs) < B: b = chess.Board() for _ in range(rng.randint(6, 90)): ms = list(b.legal_moves) if not ms: break b.push(rng.choice(ms)) if not b.is_game_over(): bs.append(b) u, t, f = zip(*[G.from_board(b, "cuda") for b in bs]) x = planes(torch.cat([torch.cat(u), torch.cat(t)], 1), torch.cat(f)) # [B, 17, 8, 8] float if getattr(net, "legal", False): # archzoo ZNet(legal=True): engine over (x, li [B, K]) K = int(os.environ.get("GM3_K", 128)) li = torch.zeros(B, K, dtype=torch.long, device="cuda") for i, b in enumerate(bs): sl = sorted({chessnet.move_index(b, m) for m in b.legal_moves})[:K] li[i, :len(sl)] = torch.tensor(sl) ref_p, ref_v = net.forward_core(x, li) class _Core(nn.Module): def __init__(self, n): super().__init__() self.n = n def forward(self, x, li): return self.n.forward_core(x, li) half = _Core(net.half().eval()) onnx_path, plan = ck + f".b{B}.onnx", ck + f".b{B}.trt" torch.onnx.export(half, (x.half(), li), onnx_path, opset_version=17, input_names=["x", "li"], output_names=["pol", "val"], dynamo=False) build(onnx_path, plan) r = TrtRunner(plan) o = r(x, li) ok = (li > 0) d = ((o["pol"].float() - ref_p.float().to(o["pol"].device)).abs() * ok).max() top = (o["pol"].float().masked_fill(~ok, -1e9).argmax(1) == ref_p.float().masked_fill(~ok, -1e9).argmax(1)).float().mean() dv = (2 * torch.sigmoid(o["val"].float()) - 2 * torch.sigmoid(ref_v.float())).abs().max() for _ in range(20): r(x, li) torch.cuda.synchronize() t0 = time.perf_counter() for _ in range(300): r(x, li) torch.cuda.synchronize() ms = (time.perf_counter() - t0) / 300 * 1000 print(f"TensorRT fp16 legal-input engine (B {B}, K {K}): {ms:.2f} ms / {B} = {B / ms * 1000:.0f} positions/s nan {int(torch.isnan(o['pol']).sum())} " f"legal logits max|d| {float(d):.4f} top1 same {float(top):.3f} value max|d| {float(dv):.4f}", flush=True) print("TRTNET_DONE") return ref_p, ref_v = net(x) q = lambda v: 2 * torch.sigmoid(v.float()) - 1 sm = lambda z: torch.softmax(z.float(), 1) def report(name, p, v, ms): print(f"{name}: {ms:.2f} ms / {B} = {B / ms * 1000:.0f} positions/s nan {int(torch.isnan(p).sum())} " f"prior max|d| {float((sm(p) - sm(ref_p)).abs().max()):.4f} top1 same " f"{float((p.argmax(1) == ref_p.argmax(1)).float().mean()):.3f} value max|d| {float((q(v) - q(ref_v)).abs().max()):.4f}", flush=True) def clock(fn, n=100): for _ in range(10): fn() torch.cuda.synchronize() t0 = time.perf_counter() for _ in range(n): fn() torch.cuda.synchronize() return (time.perf_counter() - t0) / n * 1000 xc = x.to(memory_format=torch.channels_last) netc = net.to(memory_format=torch.channels_last) def bf16(): with torch.autocast("cuda", torch.bfloat16, cache_enabled=False): return netc(xc) report("torch bf16 (engine today)", *bf16(), clock(bf16)) onnx_path, plan = ck + f".b{B}.onnx", ck + f".b{B}.trt" chessnet.ATTN_IMPL = "manual" half = make_net(d).cuda().eval() half.load_state_dict(d["state"]) half = _Play(half.half()) torch.onnx.export(half, (x.half(),), onnx_path, opset_version=17, input_names=["x"], output_names=["pol", "val"], dynamo=False) print("onnx", os.path.getsize(onnx_path) // 1000000, "MB", flush=True) build(onnx_path, plan) r = TrtRunner(plan) o = r(x) report("TensorRT fp16", o["pol"].float(), o["val"].float(), clock(lambda: r(x), 300)) print("TRTNET_DONE") if __name__ == "__main__": main()