# mypy: 允许未类型化定义
导入
火炬
导入 torch.ao.nn.intrinsic
导入 torch.ao.nn.intrinsic.qat
导入 torch.ao.nn.quantized
作为 nnq
__all__ = ["BNReLU2d", "BNReLU3d"]
[docs]class BNReLU2d(nnq.BatchNorm2d):
r"""
BNReLU2d 模块是 BatchNorm2d 和 ReLU 的融合模块
我们采用了与 :class:`torch.ao.nn.quantized.BatchNorm2d` 相同的接口。
属性:
与 torch.ao.nn.quantized.BatchNorm2d 相同
"""
_FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU2d
def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
super().__init__(
num_features, eps=eps, momentum=momentum, device=device, dtype=dtype
)
def forward(self, input):
# 临时使用 len(shape) 而不是 ndim 以解决 JIT 问题
# https://github.com/pytorch/pytorch/issues/23890
if len(input.shape) != 4:
必须输入形状为 `(N, C, H, W)` 的值!
返回 torch.ops.quantized.batch_norm2d_relu()
输入
self.weight
self.bias,
self.running_mean,
self.running_var,
self.eps,
self.scale,
self.zero_point,
)
def _get_name(self):
返回 "QuantizedBNReLU2d"
@classmethod
def from_float(cls, mod, use_precomputed_fake_quant=False):
# TODO: 为 BNReLU2d 添加量化训练支持
return super().from_float(
mod, 使用预计算的假量化=use_precomputed_fake_quant
)
@classmethod
def from_reference(cls, bn_relu, output_scale, output_zero_point):
return super().from_reference(bn_relu[0], output_scale, output_zero_point)
[文档]class BNReLU3d(nnq.BatchNorm3d):
r"""
BNReLU3d 模块是 BatchNorm3d 和 ReLU 的融合模块
我们采用与 :class:`torch.ao.nn.quantized.BatchNorm3d` 相同的接口
属性:
与 torch.ao.nn.quantized.BatchNorm3d 相同
"""
_FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU3d
def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
super().__init__(
num_features, eps=eps, momentum=momentum, device=device, dtype=dtype
)
def forward(self, input):
# 临时使用 len(shape) 替代 ndim 以解决 JIT 问题
# https://github.com/pytorch/pytorch/issues/23890
如果输入形状的长度不等于 5:
抛出 ValueError 异常("输入形状必须是 `(N, C, D, H, W)`!")
返回 torch.ops.quantized.batch_norm3d_relu(
输入,
self.weight,
self.bias,
self.running_mean,
self.running_var,
self.eps,
self.scale,
self.zero_point,
)
def _get_name(self):
return "QuantizedBNReLU3d"
@classmethod
def from_float(cls, mod, use_precomputed_fake_quant=False):
# TODO: 添加 BNReLU3d 的 qat 支持
return super().from_float(
mod, use_precomputed_fake_quant=use_precomputed_fake_quant
)
@classmethod
def from_reference(cls, bn_relu, output_scale, output_zero_point):
return super().from_reference(bn_relu[0], output_scale, output_zero_point)