"""Build the YOLO11 TensorRT engine from model.json + weights.npz (written by export_weights.py). The network is defined layer by layer with the TensorRT network API, following the checkpoint's module tree. Each builder function quotes the ultralytics source it implements (reference_code commit fc26c3d). usage: python3 build_engine.py --model DIR --out ENGINE [--precision int8|fp16|fp32] [--calib-cache FILE] [--calib-images DIR] """ import argparse import glob import json import os import sys import time import numpy as np import tensorrt as trt sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) IMGSZ = 640 LOGGER = trt.Logger(trt.Logger.WARNING) class Net: def __init__(self, network, weights): self.net = network self.w = weights self.keep = [] # numpy arrays must outlive the build self.fp_layers = [] # layers we may pin to fp16 (precision-sensitive) self.amax = None # explicit INT8: {conv path: activation amax}; convs listed here get Q/DQ inputs self.qdq_skip = () def _qdq(self, x, scale, name, axis=None): """Quantize to int8 and dequantize back (TensorRT fuses the pair into the consumer's int8 kernel).""" sc = np.ascontiguousarray(np.asarray(scale, np.float32)) self.keep.append(sc) c = self._name(self.net.add_constant(sc.shape, trt.Weights(sc)), name + ".scale").get_output(0) q = self.net.add_quantize(x, c) if axis is not None: q.axis = axis dq = self.net.add_dequantize(q.get_output(0), c) if axis is not None: dq.axis = axis self._name(q, name + ".q") return self._name(dq, name + ".dq").get_output(0) def _name(self, layer, name): layer.name = name for i in range(layer.num_outputs): layer.get_output(i).name = name if layer.num_outputs == 1 else f"{name}:{i}" return layer def const(self, arr, name): arr = np.ascontiguousarray(arr, dtype=np.float32) self.keep.append(arr) return self._name(self.net.add_constant(arr.shape, trt.Weights(arr)), name).get_output(0) def ew(self, a, b, op, name): return self._name(self.net.add_elementwise(a, b, op), name).get_output(0) def reshape(self, x, shape, name): l = self.net.add_shuffle(x) l.reshape_dims = tuple(shape) return self._name(l, name).get_output(0) def slice(self, x, axis, start, size, name): shp = list(x.shape) st = [0] * len(shp) st[axis] = start shp[axis] = size return self._name(self.net.add_slice(x, st, shp, [1] * len(shp)), name).get_output(0) def concat(self, xs, axis, name): l = self.net.add_concatenation(xs) l.axis = axis return self._name(l, name).get_output(0) # ultralytics/nn/modules/conv.py Conv (BN folded at export, as Conv.forward_fuse after fuse_conv_and_bn): # self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False) # def forward_fuse(self, x): return self.act(self.conv(x)) # act = nn.SiLU() or nn.Identity() # DWConv(Conv) is the same with groups=gcd(c1, c2); a plain nn.Conv2d (Detect's last 1x1 convs) has no act. def conv(self, x, node, w=None): p = node["path"] w = self.w[p + ".w"] if w is None else w b = self.w.get(p + ".b") if b is None: b = np.zeros(node["cout"], np.float32) w = np.ascontiguousarray(w, np.float32) b = np.ascontiguousarray(b, np.float32) self.keep += [w, b] quant = self.amax is not None and p in self.amax and not any(p == k or p.startswith(k + ".") for k in self.qdq_skip) if quant: # explicit INT8: per-tensor activation scale (calibrated amax / 127), per-output-channel weight scale x = self._qdq(x, max(self.amax[p], 1e-6) / 127.0, p + ".in") wa = np.maximum(np.abs(w).reshape(w.shape[0], -1).max(1), 1e-8) / 127.0 wt = self._name(self.net.add_constant(w.shape, trt.Weights(w)), p + ".wconst").get_output(0) wt = self._qdq(wt, wa, p + ".w", axis=0) l = self.net.add_convolution_nd(x, node["cout"], tuple(node["k"]), trt.Weights(), trt.Weights(b)) l.set_input(1, wt) else: l = self.net.add_convolution_nd(x, node["cout"], tuple(node["k"]), trt.Weights(w), trt.Weights(b)) l.stride_nd = tuple(node["s"]) l.padding_nd = tuple(node["p"]) l.num_groups = node["g"] self._name(l, p) y = l.get_output(0) act = node.get("act", "Identity") if act == "SiLU": # x * sigmoid(x) s = self._name(self.net.add_activation(y, trt.ActivationType.SIGMOID), p + ".sig").get_output(0) y = self.ew(y, s, trt.ElementWiseOperation.PROD, p + ".act") elif act != "Identity": raise NotImplementedError(f"activation {act} at {p}") return y, l def conv_(self, x, node): return self.conv(x, node)[0] # ultralytics/nn/modules/block.py:460-482 Bottleneck # def forward(self, x): return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) def bottleneck(self, x, node): c = node["children"] y = self.conv_(self.conv_(x, c["cv1"]), c["cv2"]) return self.ew(x, y, trt.ElementWiseOperation.SUM, node["path"] + ".add") if node.get("add") else y # ultralytics/nn/modules/block.py:325-348 C3 (C3k subclasses it, block.py:1109-1127) # def forward(self, x): return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1)) def c3(self, x, node): c = node["children"] a = self.module(self.conv_(x, c["cv1"]), c["m"]) b = self.conv_(x, c["cv2"]) return self.conv_(self.concat([a, b], 1, node["path"] + ".cat"), c["cv3"]) # ultralytics/nn/modules/block.py:291-322 C2f (C3k2 subclasses it, block.py:1069-1106) # def forward(self, x): # y = list(self.cv1(x).chunk(2, 1)) # y.extend((m(y[-1]) for m in self.m)) # return self.cv2(torch.cat(y, 1)) def c2f(self, x, node): c, p = node["children"], node["path"] y0 = self.conv_(x, c["cv1"]) ch = y0.shape[1] // 2 y = [self.slice(y0, 1, 0, ch, p + ".chunk0"), self.slice(y0, 1, ch, ch, p + ".chunk1")] for k in sorted(c["m"]["children"], key=int): y.append(self.module(y[-1], c["m"]["children"][k])) return self.conv_(self.concat(y, 1, p + ".cat"), c["cv2"]) # ultralytics/nn/modules/block.py:211-240 SPPF # y = [self.cv1(x)] # y.extend((self.m(y[-1]) for _ in range(getattr(self, 'n', 3)))) # y = self.cv2(torch.cat(y, 1)) # return y + x if getattr(self, 'add', False) else y def sppf(self, x, node): c, p = node["children"], node["path"] mp = c["m"] y = [self.conv_(x, c["cv1"])] for i in range(node.get("n", 3)): k, s, pad = mp["kernel_size"], mp["stride"], mp["padding"] l = self.net.add_pooling_nd(y[-1], trt.PoolingType.MAX, (k, k)) l.stride_nd = (s, s) l.padding_nd = (pad, pad) y.append(self._name(l, f"{p}.m{i}").get_output(0)) out = self.conv_(self.concat(y, 1, p + ".cat"), c["cv2"]) return self.ew(out, x, trt.ElementWiseOperation.SUM, p + ".add") if node.get("add") else out # ultralytics/nn/modules/block.py:1442-1494 C2PSA # a, b = self.cv1(x).split((self.c, self.c), dim=1) # b = self.m(b) # return self.cv2(torch.cat((a, b), 1)) def c2psa(self, x, node): c, p, cc = node["children"], node["path"], node["c"] y = self.conv_(x, c["cv1"]) a = self.slice(y, 1, 0, cc, p + ".a") b = self.module(self.slice(y, 1, cc, cc, p + ".b"), c["m"]) return self.conv_(self.concat([a, b], 1, p + ".cat"), c["cv2"]) # ultralytics/nn/modules/block.py:1337-1384 PSABlock # x = x + self.attn(x) if self.add else self.attn(x) # x = x + self.ffn(x) if self.add else self.ffn(x) def psablock(self, x, node): c, p = node["children"], node["path"] a = self.module(x, c["attn"]) x = self.ew(x, a, trt.ElementWiseOperation.SUM, p + ".add1") if node.get("add") else a f = self.module(x, c["ffn"]) return self.ew(x, f, trt.ElementWiseOperation.SUM, p + ".add2") if node.get("add") else f # ultralytics/nn/modules/block.py:1271-1334 Attention # B, C, H, W = x.shape; N = H * W # qkv = self.qkv(x) # q, k, v = qkv.view(B, self.num_heads, self.key_dim * 2 + self.head_dim, N).split( # [self.key_dim, self.key_dim, self.head_dim], dim=2) # attn = ((q * self.scale).transpose(-2, -1) @ k).softmax(dim=-1) # x = (v @ attn.transpose(-2, -1)).view(B, C, H, W) + self.pe(v.reshape(B, C, H, W)) # x = self.proj(x) def attention(self, x, node): c, p = node["children"], node["path"] B, C, H, W = x.shape N = H * W nh, kd, hd = node["num_heads"], node["key_dim"], node["head_dim"] qkv = self.reshape(self.conv_(x, c["qkv"]), (B, nh, 2 * kd + hd, N), p + ".qkv_view") q = self.slice(qkv, 2, 0, kd, p + ".q") k = self.slice(qkv, 2, kd, kd, p + ".k") v = self.slice(qkv, 2, 2 * kd, hd, p + ".v") q = self.ew(q, self.const(np.full((1, 1, 1, 1), node["scale"]), p + ".scale_c"), trt.ElementWiseOperation.PROD, p + ".qs") mm = self.net.add_matrix_multiply(q, trt.MatrixOperation.TRANSPOSE, k, trt.MatrixOperation.NONE) self._name(mm, p + ".qk") self.fp_layers.append(mm) sm = self.net.add_softmax(mm.get_output(0)) sm.axes = 1 << 3 self._name(sm, p + ".softmax") self.fp_layers.append(sm) mm2 = self.net.add_matrix_multiply(v, trt.MatrixOperation.NONE, sm.get_output(0), trt.MatrixOperation.TRANSPOSE) self._name(mm2, p + ".av") self.fp_layers.append(mm2) o = self.reshape(mm2.get_output(0), (B, C, H, W), p + ".av_view") pe = self.conv_(self.reshape(v, (B, C, H, W), p + ".v_view"), c["pe"]) o = self.ew(o, pe, trt.ElementWiseOperation.SUM, p + ".pe_add") return self.conv_(o, c["proj"]) def sequential(self, x, node): for k in sorted(node["children"], key=int): x = self.module(x, node["children"][k]) return x # torch.nn.Upsample(scale_factor=2, mode="nearest"): out[y, x] = in[floor(y / 2), floor(x / 2)] def upsample(self, x, node): assert node.get("mode", "nearest") == "nearest" s = float(node["scale_factor"]) l = self.net.add_resize(x) l.resize_mode = trt.InterpolationMode.NEAREST l.scales = [1.0, 1.0, s, s] l.coordinate_transformation = trt.ResizeCoordinateTransformation.ASYMMETRIC l.nearest_rounding = trt.ResizeRoundMode.FLOOR return self._name(l, node["path"]).get_output(0) def module(self, x, node): t = node["type"] if t in ("Conv", "DWConv", "Conv2d"): return self.conv_(x, node) fn = {"Bottleneck": self.bottleneck, "C3k": self.c3, "C3": self.c3, "C3k2": self.c2f, "C2f": self.c2f, "SPPF": self.sppf, "C2PSA": self.c2psa, "PSABlock": self.psablock, "Attention": self.attention, "Sequential": self.sequential, "Upsample": self.upsample}.get(t) if fn is None: raise NotImplementedError(f"module type {t} at {node['path']}") return fn(x, node) # ultralytics/nn/modules/head.py:38-295 Detect (one-to-many head, inference, export=False): # boxes = torch.cat([box_head[i](x[i]).view(bs, 4 * self.reg_max, -1) for i in range(self.nl)], dim=-1) # scores = torch.cat([cls_head[i](x[i]).view(bs, self.nc, -1) for i in range(self.nl)], dim=-1) # dbox = self.decode_bboxes(self.dfl(x['boxes']), self.anchors.unsqueeze(0)) * self.strides # y = torch.cat((dbox, x['scores'].sigmoid()), 1) # block.py:60-81 DFL: self.conv(x.view(b, 4, self.c1, a).transpose(2, 1).softmax(1)).view(b, 4, a) # utils/tal.py make_anchors(offset 0.5): anchor (sx, sy) = (x + 0.5, y + 0.5), row-major over (y, x) # utils/tal.py dist2bbox: lt, rb = distance.chunk(2, dim); x1y1 = anchor - lt; x2y2 = anchor + rb # We emit xyxy directly (nms.py converts the reference's xywh to xyxy before NMS), then the best class per # anchor (non_max_suppression multi_label=False: conf, j = cls.max(1)) so the host only filters + NMSes. def detect(self, xs, node): c, p = node["children"], node["path"] nc, reg_max = node["nc"], node["reg_max"] strides = node["stride"] assert not node.get("end2end") and "one2one_cv2" not in c, "end2end heads not supported" boxes, scores, anchors, stride_t = [], [], [], [] for i, x in enumerate(xs): _, _, H, W = x.shape bh = c["cv2"]["children"][str(i)] ch = c["cv3"]["children"][str(i)] b = self.sequential(x, bh) s = self.sequential(x, ch) boxes.append(self.reshape(b, (1, 4 * reg_max, H * W), f"{p}.box{i}")) scores.append(self.reshape(s, (1, nc, H * W), f"{p}.cls{i}")) sy, sx = np.meshgrid(np.arange(H, dtype=np.float32) + 0.5, np.arange(W, dtype=np.float32) + 0.5, indexing="ij") anchors.append(np.stack((sx.ravel(), sy.ravel()), 0)) stride_t.append(np.full((1, H * W), strides[i], np.float32)) A = sum(a.shape[1] for a in anchors) box = self.concat(boxes, 2, p + ".boxes") score = self.concat(scores, 2, p + ".scores") # DFL: softmax over the reg_max bins, then the 1x1 conv with weights 0..reg_max-1 (expected bin) d = self.reshape(box, (1, 4, reg_max, A), p + ".dfl_view") sm = self.net.add_softmax(d) sm.axes = 1 << 2 self._name(sm, p + ".dfl_softmax") self.fp_layers.append(sm) wdfl = self.w[c["dfl"]["children"]["conv"]["path"] + ".w"].reshape(1, 1, reg_max, 1) prod = self.ew(sm.get_output(0), self.const(wdfl, p + ".dfl_w"), trt.ElementWiseOperation.PROD, p + ".dfl_mul") red = self.net.add_reduce(prod, trt.ReduceOperation.SUM, 1 << 2, False) self._name(red, p + ".dfl") dist = red.get_output(0) # [1, 4, A] = l, t, r, b anc = self.const(np.concatenate(anchors, 1)[None], p + ".anchors") # [1, 2, A] st = self.const(np.concatenate(stride_t, 1)[None], p + ".strides") # [1, 1, A] lt = self.slice(dist, 1, 0, 2, p + ".lt") rb = self.slice(dist, 1, 2, 2, p + ".rb") x1y1 = self.ew(self.ew(anc, lt, trt.ElementWiseOperation.SUB, p + ".x1y1g"), st, trt.ElementWiseOperation.PROD, p + ".x1y1") x2y2 = self.ew(self.ew(anc, rb, trt.ElementWiseOperation.SUM, p + ".x2y2g"), st, trt.ElementWiseOperation.PROD, p + ".x2y2") # best class: sigmoid is monotonic, so top-1 over logits then sigmoid on the winner only tk = self.net.add_topk(score, trt.TopKOperation.MAX, 1, 1 << 1) self._name(tk, p + ".top1") conf = self._name(self.net.add_activation(tk.get_output(0), trt.ActivationType.SIGMOID), p + ".conf").get_output(0) cls = self._name(self.net.add_cast(tk.get_output(1), trt.float32), p + ".cls").get_output(0) out = self.concat([x1y1, x2y2, conf, cls], 1, "output") # [1, 6, A] for l in (red,): self.fp_layers.append(l) return out def build_network(builder, meta, weights, amax=None, qdq_skip=()): network = builder.create_network(0) g = Net(network, weights) g.amax, g.qdq_skip = amax, tuple(qdq_skip) # Input: the letterboxed 640x640 BGR uint8 image (HWC), exactly the array LetterBox returns. # ultralytics/engine/predictor.py preprocess: im.permute(0, 3, 1, 2); im.flip(1) (BGR->RGB); im.float() / 255 # The BGR->RGB flip and the 1/255 are folded into the first conv's weights (conv is linear, zero padding). inp = network.add_input("images", trt.uint8, (1, IMGSZ, IMGSZ, 3)) x = g._name(network.add_cast(inp, trt.float32), "input_cast").get_output(0) sh = network.add_shuffle(x) sh.first_transpose = (0, 3, 1, 2) x = g._name(sh, "input_nchw").get_output(0) outs = [] layers = meta["layers"] for li, node in enumerate(layers): f = node["f"] if node["type"] == "Detect": out = g.detect([outs[j] for j in f], node) break if node["type"] == "Concat": y = g.concat([outs[j] if j != -1 else outs[-1] for j in f], node.get("d", 1), node["path"]) else: src = x if li == 0 else outs[f if f != -1 else -1] if isinstance(f, int) else None if li == 0: # (kept out of int8: 3 input channels, raw 0..255 pixels) w0 = weights[node["path"] + ".w"][:, ::-1] / 255.0 # RGB-ordered weights applied to BGR / 255 y, first = g.conv(src, node, w=w0) else: y = g.module(src, node) outs.append(y) out.name = "output" network.mark_output(out) return network, g def make_calibrator(kind, cache, images): base = {"entropy": trt.IInt8EntropyCalibrator2, "minmax": trt.IInt8MinMaxCalibrator}[kind] class Calibrator(_CalibData, base): def __init__(self): base.__init__(self) _CalibData.__init__(self, cache, images) return Calibrator() class _CalibData: def __init__(self, cache, images): self.cache = cache self.files = sorted(images) self.idx = 0 self.dev = None if self.files: import cudart self.cu = cudart self.dev = cudart.malloc(IMGSZ * IMGSZ * 3) def get_batch_size(self): return 1 def get_batch(self, names): if self.idx >= len(self.files): return None import cv2 from prepost import letterbox im = np.ascontiguousarray(letterbox(cv2.imread(self.files[self.idx]), (IMGSZ, IMGSZ))) self.idx += 1 self.cu.memcpy(self.dev, im.ctypes.data, im.nbytes, self.cu.H2D) return [self.dev] def read_calibration_cache(self): if self.cache and os.path.exists(self.cache): with open(self.cache, "rb") as f: return f.read() return None def write_calibration_cache(self, cache): if self.cache: with open(self.cache, "wb") as f: f.write(cache) def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--out", required=True) ap.add_argument("--precision", default="int8", choices=["int8", "int8qdq", "fp16", "fp32"]) ap.add_argument("--amax", default=None, help="int8qdq: JSON from tools/calib_stats.py") ap.add_argument("--amax-mode", default="max", help="int8qdq: max | pNN (percentile of per-image amax)") ap.add_argument("--qdq-skip", default="model.0,model.1,model.2,model.10,model.23", help="int8qdq: module paths whose convs stay fp16 (chosen with tools/sensitivity.py)") ap.add_argument("--calib-cache", default=None) ap.add_argument("--calib-images", default=None) ap.add_argument("--fp16-sensitive", type=int, default=1, help="pin attention/DFL math to fp16 in int8 mode") # Default chosen with tools/sensitivity.py (simulated int8 vs fp32 detections, see NOTES.md): the stem # (model.0-2), the attention block (model.10) and the Detect head (model.23) stay fp16. ap.add_argument("--fp16-layers", default="input_cast,input_nchw,model.0,model.1,model.2,model.10,model.23,output", help="comma-separated module paths kept out of int8 (int8 mode)") ap.add_argument("--calibrator", default="minmax", choices=["minmax", "entropy"]) ap.add_argument("--opt-level", type=int, default=3, help="TensorRT builder optimization level (0-5)") ap.add_argument("--workspace-mb", type=int, default=1024) a = ap.parse_args() t0 = time.time() meta = json.load(open(os.path.join(a.model, "model.json"))) weights = dict(np.load(os.path.join(a.model, "weights.npz"))) builder = trt.Builder(LOGGER) amax = None if a.precision == "int8qdq": st = json.load(open(a.amax))["amax"] if a.amax_mode == "max": amax = {k: float(np.max(v)) for k, v in st.items()} else: amax = {k: float(np.percentile(v, float(a.amax_mode[1:]))) for k, v in st.items()} network, g = build_network(builder, meta, weights, amax, [s for s in a.qdq_skip.split(",") if s]) config = builder.create_builder_config() config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, a.workspace_mb << 20) config.builder_optimization_level = a.opt_level if a.precision in ("fp16", "int8", "int8qdq"): config.set_flag(trt.BuilderFlag.FP16) if a.precision == "int8qdq": config.set_flag(trt.BuilderFlag.INT8) # explicit quantization: int8 only where the Q/DQ pairs are if a.precision == "int8": config.set_flag(trt.BuilderFlag.INT8) imgs = [] if a.calib_images: imgs = glob.glob(os.path.join(a.calib_images, "*.jpg")) if not imgs and not (a.calib_cache and os.path.exists(a.calib_cache)): raise SystemExit("int8 needs --calib-images or an existing --calib-cache") config.int8_calibrator = make_calibrator(a.calibrator, a.calib_cache, imgs) pins = list(g.fp_layers) if a.fp16_sensitive else [] prefixes = [s for s in a.fp16_layers.split(",") if s] if prefixes: for i in range(network.num_layers): l = network.get_layer(i) if any(l.name == pfx or l.name.startswith((pfx + ".", pfx + ":")) for pfx in prefixes): pins.append(l) for l in pins: l.precision = trt.float16 config.set_flag(trt.BuilderFlag.PREFER_PRECISION_CONSTRAINTS) plan = builder.build_serialized_network(network, config) if plan is None: raise SystemExit("engine build failed") with open(a.out, "wb") as f: f.write(plan) print(f"built {a.out} ({a.precision}, {network.num_layers} layers) in {time.time() - t0:.1f}s") if __name__ == "__main__": main()