File size: 3,945 Bytes
254780c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build a TensorRT engine from a METEOR2 ONNX file.

    python3 build_trt_engine.py meteor2_gather.onnx meteor2_gather_fp16.engine --fp16
    python3 build_trt_engine.py meteor2_gather.onnx meteor2_gather_fp16g.engine --fp16 --geometry-fp32

--fp16           allow fp16 kernels (default: fp32, TF32 off)
--geometry-fp32  with --fp16: keep the camera-projection subgraph of the Gather form in fp32. These are the layers
                 whose inputs depend only on K / T_cam_ego and constants (ego points -> camera -> pixel column and
                 depth-bin coordinates that feed GridSample). They are cheap elementwise layers; keeping them in fp32
                 brings the fp16 engine closer to the fp32 outputs (see the model card). No effect on the NPU form.
--workspace-gb   builder workspace (default 4)

Tested with TensorRT 10.16. Engines are specific to the GPU and the TensorRT version they are built with.
"""
import argparse
import time

import tensorrt as trt

GEOMETRY_INPUTS = ("K", "T_cam_ego")
FLOAT_TYPES = (trt.float32, trt.float16)


def geometry_layers(net):
    """Indices of layers whose every input is derived only from K / T_cam_ego and constants."""
    geo = {net.get_input(i).name for i in range(net.num_inputs) if net.get_input(i).name in GEOMETRY_INPUTS}
    const_like = set()
    picked = []
    for i in range(net.num_layers):
        L = net.get_layer(i)
        ins = [L.get_input(j) for j in range(L.num_inputs) if L.get_input(j) is not None]
        if L.type in (trt.LayerType.CONSTANT,) or (ins and all(t.name in const_like for t in ins)) or not ins:
            for j in range(L.num_outputs):
                const_like.add(L.get_output(j).name)
            continue
        if ins and all(t.name in geo or t.name in const_like for t in ins) and any(t.name in geo for t in ins):
            for j in range(L.num_outputs):
                geo.add(L.get_output(j).name)
            if L.type != trt.LayerType.SHAPE and all(L.get_output(j).dtype in FLOAT_TYPES for j in range(L.num_outputs)):
                picked.append(i)
    return picked


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("onnx")
    ap.add_argument("engine")
    ap.add_argument("--fp16", action="store_true")
    ap.add_argument("--geometry-fp32", action="store_true")
    ap.add_argument("--workspace-gb", type=int, default=4)
    a = ap.parse_args()
    log = trt.Logger(trt.Logger.WARNING)
    b = trt.Builder(log)
    flags = 0 if int(trt.__version__.split(".")[0]) >= 10 else 1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
    net = b.create_network(flags)
    p = trt.OnnxParser(net, log)
    with open(a.onnx, "rb") as f:
        if not p.parse(f.read()):
            raise SystemExit("\n".join(str(p.get_error(i)) for i in range(p.num_errors)))
    cfg = b.create_builder_config()
    cfg.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, a.workspace_gb << 30)
    if a.fp16:
        cfg.set_flag(trt.BuilderFlag.FP16)
    else:
        cfg.clear_flag(trt.BuilderFlag.TF32)
    if a.geometry_fp32:
        assert a.fp16, "--geometry-fp32 only makes sense with --fp16"
        idx = geometry_layers(net)
        for i in idx:
            L = net.get_layer(i)
            L.precision = trt.float32
            for j in range(L.num_outputs):
                L.set_output_type(j, trt.float32)
        cfg.set_flag(trt.BuilderFlag.OBEY_PRECISION_CONSTRAINTS)
        print(f"geometry subgraph kept in fp32: {len(idx)} layers")
    t0 = time.time()
    ser = b.build_serialized_network(net, cfg)
    if ser is None:
        raise SystemExit("engine build failed")
    with open(a.engine, "wb") as f:
        f.write(ser)
    print(f"saved {a.engine} ({ser.nbytes / 1e6:.0f} MB) in {time.time() - t0:.0f} s, TensorRT {trt.__version__}, "
          f"{'fp16' if a.fp16 else 'fp32'}{' + geometry fp32' if a.geometry_fp32 else ''}")


if __name__ == "__main__":
    main()