Engine build holds a host copy and a GPU copy of all weights at the same time, in every build mode

未关闭
#4,933 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 6 天内回复

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
5/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
活跃
技术栈
cpp, python

调研方向

This is a memory-peak report in the TensorRT builder, not a local edit. Start by running the attached trt_build_memory.py script (python trt_build_memory.py 8 serialized) to reproduce the host and GPU peaks, then read the three open questions to see which copy the maintainers might drop. Done would need a measured lower peak in the builder with the weight copies accounted for, which requires access to the closed-source builder internals and maintainer input.

由索引模型根据 Issue 内容生成。

描述

Module:Engine Build

What is wrong

When TensorRT builds a network whose weights are in host memory, the peak during the build is about:

  • the caller's host weights (TensorRT reads them by pointer until the build ends),
  • one more host copy of about the same size inside the builder,
  • a GPU copy of all weights, about 1.1 times their size.

On a discrete GPU the last item is GPU memory. On Jetson Thor or DGX Spark the CPU and GPU share memory, so all 3 come out of the same RAM. Building an engine with W bytes of weights would need about 3.4 W (2.3 W host plus 1.1 W GPU, from the A100 numbers below), even when the plan is streamed to a file, or the weights are stripped. This decides whether large models can be built on the device at all.

What this blocks

On the 8 GB Jetson Orin Nano, lawam and vla_jepa each need more memory to compile their single large program than the board has (pytorch/executorch#24353). This build peak is one reason.
On Jetson and DGX Spark, where CPU and GPU share memory, an engine build would need about 3.4 times its weights (from the A100 numbers below).
A fix that frees one of the copies lets larger models build on the device itself.

Results

TensorRT 11.4.0.106, A100 80 GB, driver 580.126.09, W = 8 GiB (32 bf16 matrices of 8192 x 8192). Before the build the process holds 1.14 W (the caller's weights plus the process baseline).

mode host peak GPU peak
build_engine_with_config 2.29 W 1.10 W
build_serialized_network 2.30 W 1.10 W
build_serialized_network_to_stream 2.30 W 1.10 W
REFIT 2.29 W 1.10 W
REFIT + STRIP_PLAN 2.29 W 1.10 W
WEIGHT_STREAMING 2.29 W 1.10 W
builder_optimization_level = 0 2.29 W 1.10 W

GPU peak is the device total during the build (8985 MiB); 1.04 W of it is added by the build.

No flag changes either peak.

Questions

  1. Is the second host copy needed while the GPU copy exists, or the other way round? Either one alone would cut the peak by about a third.
  2. Could the builder upload weights layer by layer instead of keeping all of them on the GPU, at least when the plan is streamed or stripped?
  3. With WEIGHT_STREAMING, could the build respect a GPU budget, as the runtime does?

Repro

python trt_build_memory.py 8 serialized (modes: engine, serialized, stream, refit, strip, wstream, opt0). Needs tensorrt and torch.

trt_build_memory.py
import sys, threading, time
import tensorrt as trt
import torch

GIB, MODE = float(sys.argv[1]), sys.argv[2]
H = 8192
LAYERS = max(1, round(GIB * 2**30 / (H * H * 2)))
peak = {"host": 0, "gpu": 0}


def rss_mib():
    for line in open("/proc/self/status"):
        if line.startswith("VmRSS"):
            return int(line.split()[1]) // 1024


def gpu_mib():
    free, total = torch.cuda.mem_get_info()
    return (total - free) >> 20


def sampler():
    while True:
        peak["host"] = max(peak["host"], rss_mib())
        peak["gpu"] = max(peak["gpu"], gpu_mib())
        time.sleep(0.05)


torch.zeros(1, device="cuda")
ws = [torch.randn(H, H, dtype=torch.bfloat16) * H**-0.5 for _ in range(LAYERS)]
w_mib = LAYERS * H * H * 2 >> 20

builder = trt.Builder(trt.Logger(trt.Logger.WARNING))
net = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED))
x = net.add_input("x", trt.bfloat16, (16, H))
for w in ws:
    c = net.add_constant((H, H), trt.Weights(trt.bfloat16, w.data_ptr(), w.numel()))
    x = net.add_matrix_multiply(x, trt.MatrixOperation.NONE, c.get_output(0),
                                trt.MatrixOperation.TRANSPOSE).get_output(0)
net.mark_output(x)
cfg = builder.create_builder_config()
if MODE in ("refit", "strip"):
    cfg.set_flag(trt.BuilderFlag.REFIT)
if MODE == "strip":
    cfg.set_flag(trt.BuilderFlag.STRIP_PLAN)
if MODE == "wstream":
    cfg.set_flag(trt.BuilderFlag.WEIGHT_STREAMING)
if MODE == "opt0":
    cfg.builder_optimization_level = 0


class FileWriter(trt.IStreamWriter):
    def __init__(self, f):
        trt.IStreamWriter.__init__(self)
        self.f = f

    def write(self, data):
        self.f.write(data)
        return len(data)


host0, gpu0 = rss_mib(), gpu_mib()
threading.Thread(target=sampler, daemon=True).start()
if MODE == "stream":
    with open("plan.engine", "wb") as f:
        builder.build_serialized_network_to_stream(net, cfg, FileWriter(f))
elif MODE in ("serialized", "strip"):
    plan = builder.build_serialized_network(net, cfg)
else:
    engine = builder.build_engine_with_config(net, cfg)
time.sleep(0.2)
print(f"mode {MODE}: weights {w_mib} MiB; before build host {host0} MiB ({host0 / w_mib:.2f} W), "
      f"gpu {gpu0} MiB; build peak host {peak['host']} MiB ({peak['host'] / w_mib:.2f} W), "
      f"gpu {peak['gpu']} MiB ({(peak['gpu'] - gpu0) / w_mib:.2f} W above start)")

Actual

python trt_build_memory.py 8 <mode> for each mode, A100 80 GB, driver 580.126.09:

mode engine: weights 8192 MiB; before build host 9335 MiB (1.14 W), gpu 429 MiB; build peak host 18756 MiB (2.29 W), gpu 8985 MiB (1.04 W above start)
mode serialized: weights 8192 MiB; before build host 9335 MiB (1.14 W), gpu 429 MiB; build peak host 18820 MiB (2.30 W), gpu 8985 MiB (1.04 W above start)
mode stream: weights 8192 MiB; before build host 9335 MiB (1.14 W), gpu 429 MiB; build peak host 18821 MiB (2.30 W), gpu 8985 MiB (1.04 W above start)
mode refit: weights 8192 MiB; before build host 9335 MiB (1.14 W), gpu 429 MiB; build peak host 18760 MiB (2.29 W), gpu 8987 MiB (1.04 W above start)
mode strip: weights 8192 MiB; before build host 9335 MiB (1.14 W), gpu 429 MiB; build peak host 18760 MiB (2.29 W), gpu 8987 MiB (1.04 W above start)
mode wstream: weights 8192 MiB; before build host 9335 MiB (1.14 W), gpu 429 MiB; build peak host 18757 MiB (2.29 W), gpu 8985 MiB (1.04 W above start)
mode opt0: weights 8192 MiB; before build host 9335 MiB (1.14 W), gpu 429 MiB; build peak host 18720 MiB (2.29 W), gpu 8985 MiB (1.04 W above start)

Related on the Torch-TensorRT side: pytorch/TensorRT#4867 and pytorch/TensorRT#5001 (memory-efficient compilation).

主要语言
C++
星标
13.5k
派生
2.4k
平均合并
6 天 21 小时
30 天内合并 PR
3

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

NVIDIA/TensorRT 的其他 Issue

查看 NVIDIA/TensorRT 的全部 Issue

相似的 Issue

更多 C++ Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。