使用 torch.cuda.max_memory_allocated 与 torch.profiler 结果差异原因?

解读

国内一线/二线厂 GPU 面试常把“显存到底涨了多少”作为性能调优的必考题。
torch.cuda.max_memory_allocated 返回的是“CUDA 分配器(Caching Allocator)向 GPU 驱动申请过的最大块”,单位 Byte;
torch.profiler(含 legacy profiler 与新版 kineto-based profiler)在 GPU 活动记录里看到的则是“kernel 执行期间实际占用的显存”,它把分配器内部缓存、未使用块、book-keeping 开销全部刨掉,只统计真正被 tensor/kernel 用到的部分。
两者口径不同,数值必然出现差异;若候选人只说“统计方式不一样”而没有讲清“Caching Allocator 预留-缓存机制”与“profiler 采样粒度”,会被认为只停留在 API 层面,深度不够。

知识点

  1. PyTorch CUDA Caching Allocator
    • 按 block 管理显存,避免频繁 cudaMalloc/cudaFree;
    • 已释放 tensor 不会立即归还驱动,而是留在 caching pool;
    • max_memory_allocated 记录的是“pool 向驱动申请的历史峰值”,包含空闲缓存。
  2. torch.profiler / nvtx / kineto
    • 在 kernel 发射前后插入采样点,读取活跃显存;
    • 默认过滤掉 allocator 内部碎片与空闲块;
    • 可配置 profile_memory=True,但仍以“tensor 生命周期”为粒度,不会统计 pool 里尚未拆分的 block。
  3. 其他干扰项
    • CUDA context (~400-2000 MiB) 既不在 max_memory_allocated 也不在 profiler 的 tensor 统计里;
    • cudnn/cublas workspace 可能由算法自动申请,profiler 有时滞后记录;
    • 异步执行导致时间对齐误差,profiler 采样点可能错过短期峰值。
  4. 国内面试官常追问的“实战”
    • 如何强制释放缓存:torch.cuda.empty_cache() 只能归还“完全空闲”的 block,不能解决碎片;
    • 如何看到“真实峰值”:结合 torch.cuda.memory_stats() 中的 “allocated_bytes.all.peak” 与 “reserved_bytes.all.peak” 做交叉验证;
    • 如何对齐 profiler:在 profiler 内使用 schedule(skip_first=warmup, wait=0, warmup=1, active=1) 并同步 cuda.synchronize(),减少异步误差。

答案

差异根因是统计口径不同:

  1. torch.cuda.max_memory_allocated 统计的是“CUDA 分配器向 GPU 驱动申请过的最大显存块”,包含尚未被 tensor 占用的空闲缓存;
  2. torch.profiler 只统计“kernel 执行期间 tensor 实际占用的显存”,不包含空闲块与内部碎片;
  3. 因此前者数值 ≥ 后者,差距越大说明缓存碎片或预分配策略越激进;
  4. 若需要一致对比,应在同一代码位置插入 torch.cuda.synchronize(),并用 profiler 的 profile_memory=True 记录,同时查看 memory_stats() 中的 reserved/allocated 峰值做三角验证。

拓展思考

  1. 生产环境如何设定 allocator 策略?
    国内大模型训练常通过 export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128,roundup_power2_divisions:4 降低碎片,再监控 “reserved_bytes.all.peak” 与 “allocated_bytes.all.peak” 的差值,若差值持续 >20% 则考虑调整 batch size 或开启 checkpoint。
  2. 如何向面试官展示“我不仅知道差异,还能压到最低”?
    给出一段最小复现代码:在 for 循环内不断创建不同形状 tensor,展示 max_memory_allocated 持续上涨,而 profiler 的“Active GPU Memory” plateau;随后插入 empty_cache() 与 manual gc,并对比曲线,证明碎片来源与缓解手段。
  3. 面试反向提问技巧
    当面试官追问“还有别的差异吗?”可补充:
    • profiler 的 CPU 端采样间隔默认 1 ms,若 kernel 极短会漏采;
    • 多 stream 场景下,allocator 按 stream 划分 pool,profiler 可能把跨 stream 的 tensor 重复计算或遗漏;
    • 在 Ampere 架构上打开 cudaGraphCapture 时,allocator 会预分配一整块 workspace,此时 max_memory_allocated 暴涨但 profiler 只记录 graph 执行瞬间,差异会被放大。
      这些细节能让面试官确信你具备线上 GPU 性能调优的落地经验。