MinMaxObserver
- 类torch.ao.quantization.observer.MinMaxObserver(dtype=torch.quint8, qscheme=torch.per_tensor_affine, reduce_range=False, quant_min=None, quant_max=None, factory_kwargs=None, eps=1.1920928955078125e-07, is_dynamic=False, **kwargs)[源代码]
-
一个用于根据运行过程中的最小值和最大值来计算量化参数的观测模块。
此观察器使用张量的最小值和最大值统计信息来计算量化参数。该模块记录输入张量的运行最小值和最大值,并利用这些统计信息来计算量化参数。
- 参数
-
-
dtype – 实现参考模型规范所需,在量化节点中的dtype参数。
-
qscheme – 用于指定的量化方案
-
reduce_range - 将量化数据类型的范围减少一位
-
quant_min - 最小量化值。若未指定,则默认采用8位设置。
-
quant_max – 最大量化值。若未指定,默认采用8位设置。
-
eps (Tensor) – 表示浮点数
的 epsilon 值,默认为 torch.finfo(torch.float32).eps。
-
当运行中的最小值/最大值分别为$x_\text{min}$和$x_\text{max}$时,缩放因子$s$和零点$z$的计算公式为:
计算运行中的最小值/最大值 $x_\text{min/max}$ 的方法如下:
$\begin{array}{ll} x_\text{min} &= \begin{cases} \min(X) & \text{if~}x_\text{min} = \text{None} \\ \min\left(x_\text{min}, \min(X)\right) & \text{otherwise} \end{cases}\\ x_\text{max} &= \begin{cases} \max(X) & \text{if~}x_\text{max} = \text{None} \\ \max\left(x_\text{max}, \max(X)\right) & \text{otherwise} \end{cases}\\ \end{array}$其中 $X$ 表示观测到的张量。
比例因子 $s$ 和零点 $z$ 的计算方法如下:
$\begin{aligned} \text{if Symmetric:}&\\ &s = 2 \max(|x_\text{min}|, x_\text{max}) / \left( Q_\text{max} - Q_\text{min} \right) \\ &z = \begin{cases} 0 & \text{if dtype is qint8} \\ 128 & \text{otherwise} \end{cases}\\ \text{Otherwise:}&\\ &s = \left( x_\text{max} - x_\text{min} \right ) / \left( Q_\text{max} - Q_\text{min} \right ) \\ &z = Q_\text{min} - \text{round}(x_\text{min} / s) \end{aligned}$其中,$Q_\text{min}$ 和 $Q_\text{max}$ 分别表示量化数据类型中的最小值和最大值。
警告
dtype
只能是torch.qint8
或torch.quint8
。注意
如果运行中的最小值等于最大值,那么 scale 和 zero_point 分别会被设置为 1.0 和 0。
- calculate_qparams()[源代码]
-
计算量化参数。
- forward(x_orig)[源代码]
-
记录
x
的运行中的最小值和最大值。
- reset_min_max_vals()[源代码]
-
重置最小值和最大值。