news 2026/9/11 15:25:10

PyTorch 数据类型数值属性详解:torch.finfo 与 torch.iinfo 的完整使用指南

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
PyTorch 数据类型数值属性详解:torch.finfo 与 torch.iinfo 的完整使用指南

PyTorch 数据类型数值属性详解:torch.finfo 与 torch.iinfo 的完整使用指南

【免费下载链接】pytorchTensors and Dynamic neural networks in Python with strong GPU acceleration项目地址: https://gitcode.com/GitHub_Trending/py/pytorch

本指南围绕 PyTorch 中torch.finfotorch.iinfo两大类型信息对象展开,系统讲解如何通过它们查询浮点型与整型torch.dtype的精度、取值范围、机器精度等数值属性。无论你是从事量化、归一化、数值稳定性分析,还是编写自定义算子与模型部署代码,读完本文后都能准确获取任意 dtype 的关键数值参数,并理解其底层实现原理与常见使用陷阱。

概述:为什么需要 Type Info

在深度学习与科学计算中,不同数据类型的数值范围与精度差异直接影响结果的正确性与稳定性。PyTorch 提供了两个专门的对象来封装这些信息:

  • torch.finfo:表示浮点torch.dtype的数值属性,例如torch.float32torch.float64torch.float16torch.bfloat16,以及复数与 8 位浮点等扩展类型;
  • torch.iinfo:表示整数torch.dtype的数值属性,例如torch.uint8torch.int8torch.int16torch.int32torch.int64

两者在设计上分别对应 NumPy 的 numpy.finfo 与 numpy.iinfo,使用习惯高度一致,便于在 PyTorch 与 NumPy 混合编程时平滑迁移。

torch.finfo:浮点类型的数值属性

适用类型与基本用法

torch.finfo接受一个浮点torch.dtype作为构造参数:

import torch info_f32 = torch.finfo(torch.float32) info_bf16 = torch.finfo(torch.bfloat16) print(info_f32) # finfo(resolution=1e-06, min=-3.4028234663852886e+38, max=3.4028234663852886e+38, # eps=1.1920928955078125e-07, smallest_normal=1.1754943508222875e-38, tiny=1.1754943508222875e-38)

属性对照表

torch.finfo提供以下属性:

NameTypeDescription
bitsintThe number of bits occupied by the type.
epsfloatThe difference between 1.0 and the next smallest representable float larger than 1.0.
maxfloatThe largest representable number.
minfloatThe smallest representable number (typically-max).
tinyfloatThe smallest positive normal number. Equivalent tosmallest_normal.
smallest_normalfloatThe smallest positive normal number. See notes.
resolutionfloatThe approximate decimal resolution of this type, i.e.,10**-precision.

各属性含义解读:

  • bits:类型占用的比特数。例如torch.float32bits为 32,torch.bfloat16为 16,8 位浮点(如torch.float8_e5m2)为 8;
  • eps(machine epsilon,机器精度):1.0 与比 1.0 大的下一个可表示浮点数之差,衡量该类型在 1.0 附近的相对精度。torch.float32约为1.1920928955078125e-07
  • max / min:最大/最小可表示数。其中min通常等于-max,对应std::numeric_limits中的lowest()而非min(),这一点在源码 torch/csrc/TypeInfo.cpp 中可清晰看到——min属性由std::numeric_limits<scalar_t>::lowest()计算得出;
  • tiny / smallest_normal:最小的正常规数(normal number)。注意:常规数之下还存在更小的次正规数(subnormal number),参见 Denormal number 中tiny直接复用smallest_normal的实现,二者始终相等;
  • resolution:该类型的近似十进制分辨率,即10 ** -digits10,其中digits10为该类型可无损表示的十进制有效数字位数。torch.float32约为1e-06

无参构造与默认 dtype

torch.finfo的构造函数可以不带任何参数调用,此时它针对 PyTorch 的默认浮点 dtype(由torch.get_default_dtype()返回)创建实例:

print(torch.finfo()) # 等价于 torch.finfo(torch.get_default_dtype()) print(torch.get_default_dtype()) # 初始为 torch.float32

在源码 torch/csrc/TypeInfo.cpp 中,无参路径通过torch::tensors::get_default_scalar_type()取得当前默认标量类型。PyTorch 初始化时的默认浮点类型为torch.float32,可通过torch.set_default_dtype()修改,其完整说明见 torch/init.py。例如:

torch.set_default_dtype(torch.float64) print(torch.finfo()) # finfo(...dtype=float64) torch.set_default_dtype(torch.float32) # 恢复默认

在 test/test_type_info.py 的测试中,也验证了在set_default_dtype(dtype)的上下文中torch.finfo(dtype) == torch.finfo()成立。

参数校验与类型限制

torch.finfo只接受浮点与复数类型。若传入整数类型,会抛出TypeError,提示"requires a floating point input type. Use torch.iinfo to handle..."。这一校验逻辑位于 torch/csrc/TypeInfo.cpp。测试用例 test/test_type_info.py 覆盖了torch.int64torch.int32torch.bool等非法输入。

torch.iinfo:整数类型的数值属性

适用类型与基本用法

torch.iinfo接受一个整数torch.dtype作为构造参数:

info_i64 = torch.iinfo(torch.int64) info_u8 = torch.iinfo(torch.uint8) print(info_i64) # iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64)

属性对照表

torch.iinfo提供以下属性:

NameTypeDescription
bitsintThe number of bits occupied by the type.
maxintThe largest representable number.
minintThe smallest representable number.

对于有符号整数类型,min为负数最小值(如torch.int64-9223372036854775808);对于无符号类型(如torch.uint8),min为 0。源码 torch/csrc/TypeInfo.cpp 中按std::is_unsigned_v<scalar_t>区分了无符号与有符号的max/min计算路径。

量化整数类型的支持

从源码 torch/csrc/TypeInfo.cpp 可以看出,torch.iinfo除了支持普通整型,还额外支持量化整数类型(qint 类型),其max/min基于底层存储类型(underlying_t)计算。这在编写量化算子时非常实用。

参数校验与类型限制

torch.iinfo明确不支持torch.bool,传入时会抛出TypeError(见 torch/csrc/TypeInfo.cpp);传入浮点类型同样抛出TypeError,提示使用torch.finfo。对应测试见 test/test_type_info.py。

常见使用场景与实战案例

1. 构造注意力掩码与填充值

在 Transformer 类模型中,常用finfo(dtype).min作为 softmax 前的掩码填充值,确保被掩码位置的概率为 0:

# 见 torch/_inductor/fx_passes/fuse_attention.py 中的用法 neg_inf = torch.finfo(query.dtype).min

2. 数值归一化与稳定性处理

在实现 LayerNorm、BatchNorm 或自定义损失函数时,eps常被用于防止除零:

eps = torch.finfo(x.dtype).eps y = x / torch.sqrt(var + eps)

torch.finfo(torch.float32).epstorch.finfo(torch.float64).eps在 PyTorch 的分解实现中也有直接使用,参见 torch/_decomp/decompositions.py。

3. 随机整数生成的上界

torch.randint需要显式指定上界,通常借助iinfo取得类型最大值:

seed = torch.randint(0, torch.iinfo(torch.int64).max, (1,)).item()

在 torch/_inductor/codecache.py 与 torch/_functorch/_aot_autograd/runtime_wrappers.py 中均有此类用法。

4. dtype 转换时的边界饱和

将整型常量在不同 dtype 间转换时,需要按目标类型的min/max做饱和裁剪,torch/_inductor/codegen/triton.py中正是通过比较torch.iinfo(src_dtype).maxtorch.iinfo(dst_dtype).max来决定是否替换为新的边界常量。

与 NumPy 的一致性

PyTorch 的finfo/iinfo与 NumPy 对应 API 在数值上保持一致,测试 test/test_type_info.py 中逐个断言了两者在bitsmaxminepstinyresolutiondtype上的完全相等。此外,测试还针对torch.bfloat16torch.float8_e5m2torch.float8_e4m3fn等特殊类型给出了明确数值基准(如 bfloat16 的eps=0.0078125max=3.38953e38),可作为快速核对依据。

底层实现剖析

从源码结构看,finfoiinfo在 Python 层的类型声明位于 torch/_C/init.pyi.in,其 C++ 实现集中在 torch/csrc/TypeInfo.cpp,底层数据结构定义于 torch/csrc/TypeInfo.h:

  • 两者共享基结构THPDTypeInfo,仅保存一个at::ScalarType type字段;
  • 各属性并非预先存储,而是按需动态计算。例如eps调用std::numeric_limits<scalar_t>::epsilon()smallest_normal调用std::numeric_limits<scalar_t>::min()resolution则基于std::numeric_limits<scalar_t>::digits10计算10 ** -digits10
  • 两个类型对象都实现了__eq__/__ne__(比较底层ScalarType)以及__repr__/__str__,便于调试输出;
  • 通过AT_DISPATCH_V2宏分派到浮点、复数、半精度、bfloat16 与 8 位浮点等类型族,实现类型安全的多态属性计算。

这种"按需计算、不缓存数值"的设计,保证了无论 PyTorch 未来新增何种数值类型,finfo/iinfo都能在编译期正确生成对应的属性值。

小结

  • torch.finfo面向浮点与复数 dtype,提供bitsepsmaxmintinysmallest_normalresolution等属性,且支持无参构造以反映当前默认浮点类型;
  • torch.iinfo面向整数 dtype(含量化整型),提供bitsmaxmin三个属性;
  • 两者均对非法输入(如布尔、类型不匹配)抛出TypeError,接口设计与 NumPy 保持一致,数值结果可逐一对照验证;
  • 在掩码填充、数值稳定性、随机数生成、量化与 dtype 边界转换等场景中,它们是最可靠、最规范的数值参数来源。

如需深入了解类型系统的其他维度,可继续阅读 torch.dtype 相关文档 以及数值精度相关的 torch.set_printoptions 文档,并结合 test/test_type_info.py 中的完整测试用例加深理解。

【免费下载链接】pytorchTensors and Dynamic neural networks in Python with strong GPU acceleration项目地址: https://gitcode.com/GitHub_Trending/py/pytorch

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/11 15:24:46

芯片制造行业大文件安全传输与WebUploader分片加密方案

1. 芯片制造行业文件传输的特殊需求在芯片制造这个高度敏感的行业中&#xff0c;工程文件传输面临着独特的挑战。晶圆厂每天产生的设计文件、光罩数据、制程参数等核心资料&#xff0c;往往单个文件就达到数十GB甚至TB级别。这些文件不仅体积庞大&#xff0c;更包含了企业最核心…

作者头像 李华
网站建设 2026/9/11 15:23:33

Docker 运行 Android 模拟器从零到可用:Docker-Android 配置全流程

Docker 运行 Android 模拟器从零到可用&#xff1a;Docker-Android 配置全流程 【免费下载链接】docker-android Android in docker solution with noVNC supported, video recording and mcp server 项目地址: https://gitcode.com/GitHub_Trending/do/docker-android …

作者头像 李华
网站建设 2026/9/11 15:23:23

蓝牙模块选型三证据:射频一致性、功耗预算与量产测试

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/9/11 15:21:05

Python开源项目贡献指南:从PR提交到核心维护

1. 开源贡献入门&#xff1a;为什么选择Python项目&#xff1f;第一次给开源项目提交PR时&#xff0c;我的手都在抖。那是个周末的深夜&#xff0c;我反复检查了七遍代码才敢点下提交按钮——结果第二天醒来发现项目维护者不仅合并了我的代码&#xff0c;还贴心地帮我修正了拼写…

作者头像 李华
网站建设 2026/9/11 15:17:31

VS Code AI Chat接入本地Ollama:从配置到实战全指南

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/9/11 15:15:03

瑞数加密逆向实战:Cookie生成链路与绕过方案

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华