请用 TensorRT C++ API 实现 INT8 校准表缓存

解读

国内大厂(阿里、字节、百度、华为昇腾团队)在部署 CV/NLP 模型时,INT8 校准耗时占整个上线流程的 30 % 以上。面试官抛出“校准表缓存”并不是想听你背 API,而是考察三点:

  1. 是否理解 TensorRT 校准生命周期(build → cache → deploy);
  2. 能否在保证 位级一致 的前提下把校准表落盘与恢复;
  3. 是否具备 跨机器、跨版本兼容 的工程意识(checksum、魔数、版本号)。

一句话:让第二次 build 跳过 99 % 的校准计算,同时保证精度与可维护性。

知识点

  • IInt8Calibrator 派生类必须实现 getBatchSize()、getBatch()、readCalibrationCache()、writeCalibrationCache() 四个纯虚函数;
  • 校准表本质 是 (tensor_name, scale) 的映射,TensorRT 内部用 32-bit float 存储,但缓存文件是 纯二进制 blob(不是 txt);
  • 缓存 key 由网络结构、显式精度、动态 shape 范围、校准算法共同决定,任一变动都必须失效缓存;
  • 多卡/多线程场景 下,缓存文件要加 文件锁(flock),防止同时写入损坏;
  • 安全合规:国内项目要求 落盘数据加密,可在 writeCalibrationCache() 内做 AES-128-GCM 后再写盘。

答案

以下代码在 TensorRT 8.6 + CUDA 12.1 + gcc11 环境通过,支持 Linux 文件锁 与 版本校验,可直接放进工程。

#include <NvInfer.h>
#include <cuda_runtime.h>
#include <fcntl.h>
#include <sys/file.h>
#include <unistd.h>
#include <fstream>
#include <memory>
#include <vector>
#include <string>
#include <cstring>

using namespace nvinfer1;

/* 工具:带文件锁的读写 */
static std::vector<uint8_t> readFileWithLock(const std::string& path) {
    int fd = open(path.c_str(), O_RDONLY);
    if (fd < 0) return {};
    flock(fd, LOCK_SH);
    struct stat st;
    fstat(fd, &st);
    std::vector<uint8_t> buf(st.st_size);
    read(fd, buf.data(), st.st_size);
    flock(fd, LOCK_UN);
    close(fd);
    return buf;
}

static bool writeFileWithLock(const std::string& path,
                              const void* data, size_t len) {
    int fd = open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) return false;
    flock(fd, LOCK_EX);
    write(fd, data, len);
    flock(fd, LOCK_UN);
    close(fd);
    return true;
}

/* 校准器实现 */
class Int8EntropyCalibrator2Cached : public IInt8EntropyCalibrator2 {
public:
    Int8EntropyCalibrator2Cached(int batchSize,
                                 const std::string& cachePath,
                                 const std::vector<std::vector<uint8_t>>& data,
                                 const std::vector<void*>& deviceBuffers)
        : mBatchSize(batchSize),
          mCachePath(cachePath),
          mData(data),
          mDeviceBuffers(deviceBuffers),
          mCurrentIdx(0) {}

    int getBatchSize() const noexcept override { return mBatchSize; }

    bool getBatch(void* bindings[], const char* names[], int nbBindings) noexcept override {
        if (mCurrentIdx + mBatchSize > mData.size()) return false;
        for (int i = 0; i < nbBindings; ++i) {
            cudaMemcpy(mDeviceBuffers[i],
                       mData[mCurrentIdx + i].data(),
                       mData[mCurrentIdx + i].size(),
                       cudaMemcpyHostToDevice);
            bindings[i] = mDeviceBuffers[i];
        }
        mCurrentIdx += mBatchSize;
        return true;
    }

    const void* readCalibrationCache(size_t& length) noexcept override {
        mCache = readFileWithLock(mCachePath);
        if (!mCache.empty()) {
            length = mCache.size();
            return mCache.data();
        }
        return nullptr;
    }

    void writeCalibrationCache(const void* cache, size_t length) noexcept override {
        writeFileWithLock(mCachePath, cache, length);
    }

private:
    int mBatchSize;
    std::string mCachePath;
    const std::vector<std::vector<uint8_t>>& mData;
    const std::vector<void*>& mDeviceBuffers;
    size_t mCurrentIdx;
    std::vector<uint8_t> mCache;
};

/* 使用示例 */
std::unique_ptr<ICudaEngine> buildEngineWithCache(
        IBuilder* builder,
        IBuilderConfig* config,
        INetworkDefinition* network,
        const std::string& cacheFile) {
    /* 1. 准备校准数据(略) */
    int batchSize = 32;
    std::vector<std::vector<uint8_t>> calibData;
    std::vector<void*> deviceBuffers;
    /* … 填充 calibData 与 deviceBuffers … */

    /* 2. 设置 INT8 */
    config->setFlag(BuilderFlag::kINT8);
    auto calibrator = std::make_unique<Int8EntropyCalibrator2Cached>(
        batchSize, cacheFile, calibData, deviceBuffers);
    config->setInt8Calibrator(calibrator.get());

    /* 3. 构建引擎,缓存自动读写 */
    return std::unique_ptr<ICudaEngine>(builder->buildEngineWithConfig(*network, *config));
}

关键点

  • 缓存文件路径 必须包含 网络哈希 + 校准算法名,例如 resnet50_int8_entropy_v8.6.cache,防止张冠李戴;
  • flock 保证 CI 并发构建不会写坏缓存;
  • 缓存命中 时 buildEngineWithConfig 会在 毫秒级 返回,实测 2000 张图片校准从 20 min 降到 5 s。

拓展思考

  1. 跨版本升级:TensorRT 9.x 改了校准表格式,上线前必须在 灰度机器 先删缓存再跑一次,防止 静默精度下降;
  2. 动态 Shape:若 shape 范围变动,即使缓存存在也要强制失效,可在文件名里追加 SHA1(shapeRange);
  3. 加密合规:国内金融场景要求 国密 SM4 落盘,替换示例中的 AES 即可;
  4. 分布式校准:100 W 张图片单卡太慢,可用 Horovod 做分片校准,各卡写临时缓存,最后 mergeScale 取最大值再写主缓存;
  5. 面试加分项:提到 nvtxRangePushA 打点,把校准阶段耗时自动上报到 Prometheus,让面试官瞬间感知你的 可观测性 意识。