

近日,PyTorch 团队正式发布了 v2.8.0 版本,带来了多项重要功能更新、性能优化和错误修复。本文将详细介绍该版本的主要变化,帮助开发者更好地理解新特性及其影响。
torch::stable::Tensortorch.compile 的分层编译跟踪中的回归问题
torch.segment_reduce() 时会导致构建崩溃。
因此,我们提供了一个不包含 torch.segment_reduce() 的 wheel 版本来规避该问题。
如果你需要 torch.segment_reduce() 的支持,请使用其他版本的 CUDA。NotImplementedError,而不是 RuntimeError。
请更新异常处理逻辑以反映此变化。在 2.7.0:
try:
torch.nn.Hardshrink()(torch.randint(0, 5, (10,)))
except RuntimeError:
...在 2.8.0:
try:
torch.nn.Hardshrink()(torch.randint(0, 5, (10,)))
except NotImplementedError:
...autograd.Function 增加了缺失的“视图上的就地操作检查”
在 2.8.0 中,如果自定义的 autograd.Function 修改了一个需要梯度的叶子变量(leaf)的视图(view),现在会正确抛出错误。
以前则会静默导致内存泄漏。示例:
class Func(torch.autograd.Function):
@staticmethod
defforward(ctx, inp):
inp.add_(1)
ctx.mark_dirty(inp)
return inp
@staticmethod
defbackward(ctx, gO):
pass
a = torch.tensor([1.0, 2.0], requires_grad=True)
b = a.view_as(a)
Func.apply(b)2.7.0 版本 运行不报错,但是会内存泄漏。
2.8.0 版本 报错:
RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operationtensordot 的 out 版本 现在会在 requires_grad=True 时正确抛出错误。
以前不会报错,但无法为 out 张量计算梯度。在 2.7.0:
a = torch.empty((4, 2), requires_grad=True)
b = torch.empty((2, 4), requires_grad=True)
c = torch.empty((2, 2), requires_grad=True)
# 不报错,但无法计算 c 的梯度
torch.tensordot(a, b, dims=([1], [0]), out=c)在 2.8.0:
# 会报 RuntimeErrormark_dynamic 张量在特定情况下被错误地形状特化的问题
以前,如果在关闭 guard 的情况下测试符号形状,则 guard 可能被遗漏。
已在 2.8 修复。如果新 guard 使 mark_dynamic 的张量被特化,会导致错误。
解决方法:使用 maybe_mark_dynamic 替代 mark_dynamic。torch.compile 相关的配置变量已重命名或移除:enable_cpp_framelocals_guard_eval 现在无效rocm.n_max_profiling_configs 弃用 → 请改用 rocm.ck_max_profiling_configs 和 rocm.ck_tile_max_profiling_configsautotune_fallback_to_aten 弃用 → ATen 回退需显式配置use_mixed_mm 和 mixed_mm_choice 弃用descriptive_names = False 弃用 → 请使用 "torch", "original_aten" 或 "inductor_node"custom_op_default_layout_constraint 从 inductor config 移动到 functorch configemit_current_arch_binary 弃用aot_inductor.embed_cubin 重命名为 aot_inductor.embed_kernel_binaryaot_inductor.compile_wrapper_with_O0 重命名为 compile_wrapper_opt_levelcond)增加了更严格的别名/突变检查。
如果输入与输出间存在不支持的别名或突变,将报错。
解决方法:对有别名的输出调用 .clone()。guard_or_x 与 definitely_x 接口合并
删除了 definitely_true / definitely_false,请改用 guard_or_true / guard_or_false。torch.export.export_for_inference,请使用:torch.export.export_for_training(...).run_decompositions(...)torch.export.export 和 export_for_training 默认 strict=False(旧版默认是 True)。
如需旧行为,请显式传入 strict=True。torch.onnx.export 默认 opset 从 17 升级到 18。
如果需要旧行为,请显式指定 opset_version=17。JitTraceConvertStrategy 支持,当 dynamo=True 时,不再支持 JIT traced/scripted 模块导出到 ONNX。onnxscript>=0.3.1 是 dynamo=True 的必需版本。Dispatcher.h 中移除了 torch/types.h 引入
如果 C++ 代码依赖此隐式包含,请升级 torchvision 版本。kDLGPU → kDLCUDAkDLCPUPinned → kDLCUDAHostUSE_SYSTEM_NVTX=1 时需显式配置。torch.ao.quantization 已弃用,将在 2.10 中移除迁移方式如下:
(torch.ao.quantization.quantize, torch.ao.quantization.quantize_dynamic)
torchao Eager 模式的 quantize_。torchao 的 PT2E 量化。(torch.ao.quantization.quantize_fx.prepare_fx, torch.ao.quantization.quantize_fx.convert_fx)
torchao 的 PT2E 量化(torchao.quantization.quantize_pt2e.prepare_pt2e, torchao.quantization.quantize_pt2e.convert_pt2e)。注意:
torchao 仓库:
📂 torchao.quantization.pt2etorch.onnx.export 的 dynamo=False(当前默认)选项已弃用dynamo=True。dynamo=True 选项,这将使 torch.export.export 成为默认导出路径,取代 TorchScript。如果需要保留旧行为:
dynamo=False。fallback=True 选项,这样当 dynamo=True 出错时,导出器会自动回退到 dynamo=False 路径。nested_compile_region 实现。guard_filter_fn 来丢弃 guard。dont_skip_tracing 装饰器,可绕过大多数 Dynamo skipfiles 规则。draft-export:一种新的导出变体,旨在稳定生成计算图,并生成追踪过程中的调试报告。aot_inductor.model_name_for_generated_files,用于指定生成文件的模型名称。torch.compile。draft_export 策略,在使用 torch.onnx.export 获取 ExportedProgram 时,如果出现数据相关或约束错误,可提供调试信息。dynamo=True 导出路径中,新增对**符号算子(symbolic operators)**的支持。torch.onnx.ops.symbolic 和 torch.onnx.ops.symbolic_multi_out,可直接在 PyTorch 模型中创建 ONNX 符号算子。示例:
def forward(self, x: torch.Tensor) -> torch.Tensor:
# 可以选用 is_in_onnx_export 来控制 ONNX 导出时期的行为
if torch.onnx.is_in_onnx_export():
# 在 "custom_domain" 域中创建名为 "CustomOp" 的 ONNX 符号算子
# 输出张量将具有给定的 dtype 和 shape
return torch.onnx.ops.symbolic(
"custom_domain::CustomOp",
(x,),
dict(attr_key="attr_value"),
dtype=x.dtype,
shape=x.shape,
version=1,
)
else:
return xtorch.float4_e2m1fn_x2。TORCH_CUDA_ARCH_LIST 的过时警告torch::nn::functional::grid_sample 添加了 Bicubic 模式load_inline() 引入 no_implicit_headers 模式TORCH_NCCL_USE_TENSOR_REGISTER_ALLOCATOR_HOOK 的行为needs_contiguous_strides 标签split_group 支持非 NCCL 后端new_subgroups_by_enumeration() 简化 new_subgroups()c10::Halfget_process_group_ranks() 支持 group=Noneinit_process_group 支持仅索引的设备 IDreduce_scatter 和 ReduceOp::AVG 支持use_python_reducer 从 Python 传递到 C++ reducerwrite_size 中的非张量数据torch.cumsum 增加支持torch.distributed.tensor.debug.visualize_sharding 增加详细支持PrivateUse1 后端支持,并将设备类型传递给 pre forward hookset_reshard_after_forwardreshard_after_forward=True 且为根模型时,保留根未分片get_pipeline_order() 支持 Gpipe 和 1F1BParallelStyle PrepareModuleInputOutputDynamo
set、实现了 __torch_function__ 的张量子类,以及 namedtuple 子类的追踪支持torch.compiler.disable 添加了 reason 字段torch 命名空间函数中 lru_cache 的警告aot_inductor.custom_ops_to_c_shims 和 aot_inductor.custom_op_libs:允许指定自定义算子的 C shimmax_fusion_buffer_group_pairwise_attempts:限制融合的最大节点距离cuda.cutlass_enabled_ops:控制 CUTLASS 算子的选择triton.cudagraph_capture_sizes:指定在哪些形状下捕获 CUDAGraph,并跳过其他形状的捕获use_static_cuda_launcher:启用对编译后 triton 的静态启动以提升冷启动性能assume_unaligned_fallback_output:允许 inductor 跟踪未对齐的输出cuda.cutlass_tma_only:控制是否只使用 TMA 兼容的 CUTLASS 内核static_launch_user_defined_triton_kernels:启用静态启动用户自定义 triton 内核precompilation_timeout_seconds:控制预编译的超时时间disable_decompose_k:禁用新的 DecomposeK GEMM 内核min_num_split:设置分块归约(split reduction)的最小分块数max_autotune_flex_search_space:指定 flex attention 自动调优的搜索空间大小LOG_AUTOTUNE_RESULTS 环境变量,用于自动调优日志记录min、max、math.pow)的处理dim hints 添加了 min/max 范围pytree.register_dataclass 注册普通类jit.scripted 函数到 export 结果中graph signature 的美化打印AOTIModelPackageLoader 中添加了 num_runners 参数==normalize_function 中支持边缘方言(edge dialect)算子minifier 中路径命名问题graph_code_verbose_log 用于 FX passesfx.passes.split_module 中添加参数以规范化输入名称cross 添加了张量重叠检查torch.special 操作(以及 index_copy、hardshrink、rsub、col2im、isin)添加了支持index_put 支持半精度浮点ConvTranspose3D 支持 FP32 和复数log1p 和 sigmoid 支持 int64weight_norm 的 FP16 支持dynamo=True 时支持 opset 18-23torch.scanVerificationInfo 类添加 asdict 方法torch.export.dim.DYNAMICsym_float, sym_not, sym_min, sym_max)支持TensorLR 版本lr_lambda 类型检查torch.AcceleratorErrorSize.__radd__()get_default_device() 以支持 torch.device 上下文管理器qconv1d-relu 融合,以及 lowering passtorch.fused_moving_avg_obs_fake_quant 的布尔张量cpp_extension 的默认编译标志mm / bmm / addmm 操作的支持torch.Tensor.scatter_add_torch.matrix_expfp32 因果掩码(causal mask)用于 SDP(Scaled Dot-Product Attention)embed_cubin 和 multi_arch_kernel_binary 选项,用于 Intel GPUUserDefineClass 中添加通用及 Intel GPU 专用的 Stream 和 Event 接口int4 WOQ GEMM(权重量化 GEMM)/permissive- 标志以强制构建符合 C++ 标准torch.norm 中发生溢出log_softmax 降精度 FP 内核中明显的复制粘贴错误torch.backends.cuda.matmul.allow_fp16_accumulation 崩溃问题torch.cuda.MemPool 在多线程用例中的问题layer_norm 中对默认构造的 gamma / beta 调用 sum() 的问题empty_cache 不再报错c10d
barrier 产生额外 CUDA 上下文的问题all_to_all 的 ET trace 收集问题new_subgroups() 中未使用的 group 输入参数问题分布式检查点(DCP)
broadcast_object 工具函数中使用全局协调器 rank 的问题分布式数据并行(DDP)
DTensor
local_mapredistribute 中 new_local_tensor 为 None 的情况流水线并行(Pipeline Parallelism)
RPC
分片张量(ShardedTensor)
张量并行(TensorParallel)
Dynamo
lru_cache 方法的来源问题Inductor
torch.export
aten.is_nonzero、torch.bincount()、aten.div、切片(#150104)、attn_mask、aten.to、标量张量构造dynamic_shapes 在 kwargs 下的规范问题functools.partial 和高阶算子的非严格跟踪None 输入、math 模块、call_torchbind、枚举类型的序列化/反序列化问题run_decompositions 中 state_dict 被修改的问题Ahead-Of-Time Inductor (AOTI)
update_constant_buffer 问题model_package_loader 中的内存泄漏dot 和 gemv 的累积类型torch.lobpcg 计算结果与 scipy、numpy.linalg.eig 一致性问题floor_divide 类型提升lerplogit 对半精度/bfloat16 输入torch.special.entrtri[ul]wherenn.LazyLinear 的 load_state_dict 行为last_epoch > -1 时 lr_scheduler 意外调用 step() 的问题CosineAnnealingWarmRestarts 中 T_cur 重置问题decrefMixtureSameFamily 分布的采样验证Wishart 或 Uniform 分布会修改第一个分布约束的错误torch::utils::tensor_to_numpy 符号torch.[con]cat[enate] 在空输入时的崩溃torch.tensor 和 torch.ops.aten.scalar_tensor 的行为torch.is_vulkan_available() 的检测torch.xpu.is_bf16_supported 正确报告 Intel GPU 支持情况cat 和 index_select 的性能SubsetRandomSampler 中通过迭代列表而不是张量来减少内存使用cpp.use_small_dequant_buffer,以便在 WOQ int4 GEMM 中使用较小的反量化缓冲区torch.dot 在 float16/bfloat16 类型下引入了快速路径cumsum / cumprod 的性能torch.tensordot 在缩约为标量时的性能addmm、baddmm 中标量张量的处理,降低 Intel GPU 上 oneDNN 集成的额外开销ctx.save_for_backward 为什么重要torch.autograd.graph.saved_tensors_hooks 的文档,避免引用循环(refcycle)torch.amin 和 torch.amax 的梯度行为说明NCCLConfig 文档,增加了 QOS 变量get_default_backend_for_deviceignored_params 的文档字符串并增加了单元测试Dims 和 ExportGraphSignature 的文档torch.linalg.norm() 的 ord 参数值为 +2 和 -2 的歧义interpolate 饱和类型转换行为、ConvTranspose2d 的 stride / output_size 参数 以及 register_full_backward_hook 的文档nn.Sequential 和 nn.LazyModuleMixin 的示例nn.modules.padding 和 AvgPoolND 中记录了 padding 大小的限制.rst 文档文件转换为 Markdowncapturable 参数文档中加入了其他加速器的信息dampeningCosineAnnealingLR 文档,使其准确反映递归学习率调度Adafactor 文档中作者引用错误lr_scheduler 中使用 load_state_dict 时调用顺序的提示torch.Library 的 kind 无默认值,以与代码保持一致dtype 说明requires_grad=True 一起使用 在 tensor.to() 中的行为cdist 参数描述Example: 显示为 Example:: 错误as_strided() 的文档keepdim 参数的可选性描述torch.trapezoid 中 x 和 dx 参数互斥torch.min()、torch.max()、torch.all()、torch.any() 的基本说明torch.triu_indices、torch.tril_indices 的 dtype 描述torch.equal 的描述prepare_qat_fx 文档中 get_default_qat_qconfig 错误uniqueID 的广播和全收集(allgather)添加了参数记录功能PGNCCL 增加了日志配置和更多日志内容,例如 nccl_version 以及线程名称/ID,以便飞行记录(flight record)DumpPipe 解除链接并创建命名管道时,暴露错误类型tcpstore 远程关闭时的日志new_subgroups() 中,当世界大小不可整除时增强错误日志记录get_backend() 错误信息,增加更多细节FlatParamHandle 时打印完整限定名称(FQN)rpc_init 中抛出的异常传递给 CPythontorch.distributed.run 添加选项,用于提供事件日志的存储位置TracingContexttorch.export 文档中的 preserve_module_call_signature 描述lift_constants_pass 的类型注解detect_attr_assignment 中的 bugstable::Tensor is_contiguous APIlr_scheduler.py 中的类型注解step() 默认值的类型提示setup-pythonPyTorch 2.8.0 在推理性能、编译优化和分布式训练等方面带来了多项重要更新。开发者需注意部分向后不兼容的变更,并及时调整代码逻辑。建议在升级前充分测试现有代码,确保兼容性和稳定性。
我们相信人工智能为普通人提供了一种“增强工具”,并致力于分享全方位的AI知识。在这里,您可以找到最新的AI科普文章、工具评测、提升效率的秘籍以及行业洞察。 欢迎关注“福大大架构师每日一题”,发消息可获得面试资料,让AI助力您的未来发展。