Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- pythonProject/.venv/Lib/site-packages/torch/ao/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/modules/__init__.py +38 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/modules/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/modules/__pycache__/fused.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__init__.py +1 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__init__.py +6 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/linear_relu.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/linear_relu.py +56 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__init__.py +17 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/bn_relu.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_add.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_relu.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/linear_relu.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/bn_relu.py +83 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_add.py +94 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_relu.py +176 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/linear_relu.py +178 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/__init__.py +1 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/__init__.py +1 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/modules/__init__.py +3 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/linear.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/modules/linear.py +26 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/__init__.py +14 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/__pycache__/conv.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/__pycache__/embedding_ops.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/__pycache__/linear.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/conv.py +271 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/embedding_ops.py +144 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/linear.py +82 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/__init__.py +1 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/__init__.py +9 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/__pycache__/activation.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/__pycache__/rnn.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/activation.py +473 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/rnn.py +412 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantized/__init__.py +38 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantized/__pycache__/__init__.cpython-310.pyc +0 -0
- pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantized/__pycache__/functional.cpython-310.pyc +0 -0
pythonProject/.venv/Lib/site-packages/torch/ao/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (471 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (491 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (739 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/modules/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .fused import _FusedModule # noqa: F401
|
| 2 |
+
from .fused import ConvBn1d
|
| 3 |
+
from .fused import ConvBn2d
|
| 4 |
+
from .fused import ConvBn3d
|
| 5 |
+
from .fused import ConvBnReLU1d
|
| 6 |
+
from .fused import ConvBnReLU2d
|
| 7 |
+
from .fused import ConvBnReLU3d
|
| 8 |
+
from .fused import ConvReLU1d
|
| 9 |
+
from .fused import ConvReLU2d
|
| 10 |
+
from .fused import ConvReLU3d
|
| 11 |
+
from .fused import LinearReLU
|
| 12 |
+
from .fused import BNReLU2d
|
| 13 |
+
from .fused import BNReLU3d
|
| 14 |
+
from .fused import LinearBn1d
|
| 15 |
+
from .fused import LinearLeakyReLU
|
| 16 |
+
from .fused import LinearTanh
|
| 17 |
+
from .fused import ConvAdd2d
|
| 18 |
+
from .fused import ConvAddReLU2d
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
'ConvBn1d',
|
| 22 |
+
'ConvBn2d',
|
| 23 |
+
'ConvBn3d',
|
| 24 |
+
'ConvBnReLU1d',
|
| 25 |
+
'ConvBnReLU2d',
|
| 26 |
+
'ConvBnReLU3d',
|
| 27 |
+
'ConvReLU1d',
|
| 28 |
+
'ConvReLU2d',
|
| 29 |
+
'ConvReLU3d',
|
| 30 |
+
'LinearReLU',
|
| 31 |
+
'BNReLU2d',
|
| 32 |
+
'BNReLU3d',
|
| 33 |
+
'LinearBn1d',
|
| 34 |
+
'LinearLeakyReLU',
|
| 35 |
+
'LinearTanh',
|
| 36 |
+
'ConvAdd2d',
|
| 37 |
+
'ConvAddReLU2d',
|
| 38 |
+
]
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/modules/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (898 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/modules/__pycache__/fused.cpython-310.pyc
ADDED
|
Binary file (8.35 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (356 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .modules import * # noqa: F403
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (220 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from .linear_relu import LinearReLU
|
| 3 |
+
|
| 4 |
+
__all__ = [
|
| 5 |
+
'LinearReLU',
|
| 6 |
+
]
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (296 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/__pycache__/linear_relu.cpython-310.pyc
ADDED
|
Binary file (2.42 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/dynamic/modules/linear_relu.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch.ao.nn.quantized.dynamic as nnqd
|
| 4 |
+
import torch.ao.nn.intrinsic as nni
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
"LinearReLU"
|
| 8 |
+
]
|
| 9 |
+
|
| 10 |
+
class LinearReLU(nnqd.Linear):
|
| 11 |
+
r"""
|
| 12 |
+
A LinearReLU module fused from Linear and ReLU modules that can be used
|
| 13 |
+
for dynamic quantization.
|
| 14 |
+
Supports both, FP16 and INT8 quantization.
|
| 15 |
+
|
| 16 |
+
We adopt the same interface as :class:`torch.ao.nn.quantized.dynamic.Linear`.
|
| 17 |
+
|
| 18 |
+
Attributes:
|
| 19 |
+
Same as torch.ao.nn.quantized.dynamic.Linear
|
| 20 |
+
|
| 21 |
+
Examples::
|
| 22 |
+
|
| 23 |
+
>>> # xdoctest: +SKIP
|
| 24 |
+
>>> m = nn.intrinsic.quantized.dynamic.LinearReLU(20, 30)
|
| 25 |
+
>>> input = torch.randn(128, 20)
|
| 26 |
+
>>> output = m(input)
|
| 27 |
+
>>> print(output.size())
|
| 28 |
+
torch.Size([128, 30])
|
| 29 |
+
"""
|
| 30 |
+
_FLOAT_MODULE = nni.LinearReLU # type: ignore[assignment]
|
| 31 |
+
|
| 32 |
+
def __init__(self, in_features, out_features, bias=True, dtype=torch.qint8):
|
| 33 |
+
super().__init__(in_features, out_features, bias, dtype)
|
| 34 |
+
|
| 35 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 36 |
+
if self._packed_params.dtype == torch.qint8:
|
| 37 |
+
# TODO check if we should set reduce_rage = True by default here
|
| 38 |
+
Y = torch.ops.quantized.linear_relu_dynamic(
|
| 39 |
+
x, self._packed_params._packed_params, reduce_range=True)
|
| 40 |
+
elif self._packed_params.dtype == torch.float16:
|
| 41 |
+
Y = torch.ops.quantized.linear_relu_dynamic_fp16(
|
| 42 |
+
x, self._packed_params._packed_params)
|
| 43 |
+
else:
|
| 44 |
+
raise RuntimeError('Unsupported dtype on dynamic quantized linear relu!')
|
| 45 |
+
return Y.to(x.dtype)
|
| 46 |
+
|
| 47 |
+
def _get_name(self):
|
| 48 |
+
return 'DynamicQuantizedLinearReLU'
|
| 49 |
+
|
| 50 |
+
@classmethod
|
| 51 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 52 |
+
return super().from_float(mod, use_precomputed_fake_quant=use_precomputed_fake_quant)
|
| 53 |
+
|
| 54 |
+
@classmethod
|
| 55 |
+
def from_reference(cls, ref_qlinear_relu):
|
| 56 |
+
return super().from_reference(ref_qlinear_relu[0])
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .linear_relu import LinearReLU, LinearLeakyReLU, LinearTanh
|
| 2 |
+
from .conv_relu import ConvReLU1d, ConvReLU2d, ConvReLU3d
|
| 3 |
+
from .bn_relu import BNReLU2d, BNReLU3d
|
| 4 |
+
from .conv_add import ConvAdd2d, ConvAddReLU2d
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
'LinearReLU',
|
| 8 |
+
'ConvReLU1d',
|
| 9 |
+
'ConvReLU2d',
|
| 10 |
+
'ConvReLU3d',
|
| 11 |
+
'BNReLU2d',
|
| 12 |
+
'BNReLU3d',
|
| 13 |
+
'LinearLeakyReLU',
|
| 14 |
+
'LinearTanh',
|
| 15 |
+
'ConvAdd2d',
|
| 16 |
+
'ConvAddReLU2d',
|
| 17 |
+
]
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (571 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/bn_relu.cpython-310.pyc
ADDED
|
Binary file (3.11 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_add.cpython-310.pyc
ADDED
|
Binary file (3.38 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/conv_relu.cpython-310.pyc
ADDED
|
Binary file (5.77 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/__pycache__/linear_relu.cpython-310.pyc
ADDED
|
Binary file (6.41 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/bn_relu.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.ao.nn.intrinsic
|
| 5 |
+
import torch.ao.nn.intrinsic.qat
|
| 6 |
+
import torch.ao.nn.quantized as nnq
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"BNReLU2d",
|
| 10 |
+
"BNReLU3d"
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
+
class BNReLU2d(nnq.BatchNorm2d):
|
| 14 |
+
r"""
|
| 15 |
+
A BNReLU2d module is a fused module of BatchNorm2d and ReLU
|
| 16 |
+
|
| 17 |
+
We adopt the same interface as :class:`torch.ao.nn.quantized.BatchNorm2d`.
|
| 18 |
+
|
| 19 |
+
Attributes:
|
| 20 |
+
Same as torch.ao.nn.quantized.BatchNorm2d
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
_FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU2d
|
| 24 |
+
|
| 25 |
+
def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
|
| 26 |
+
super().__init__(num_features, eps=eps, momentum=momentum, device=device, dtype=dtype)
|
| 27 |
+
|
| 28 |
+
def forward(self, input):
|
| 29 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 30 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 31 |
+
if len(input.shape) != 4:
|
| 32 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 33 |
+
return torch.ops.quantized.batch_norm2d_relu(
|
| 34 |
+
input, self.weight, self.bias, self.running_mean,
|
| 35 |
+
self.running_var, self.eps, self.scale, self.zero_point)
|
| 36 |
+
|
| 37 |
+
def _get_name(self):
|
| 38 |
+
return 'QuantizedBNReLU2d'
|
| 39 |
+
|
| 40 |
+
@classmethod
|
| 41 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 42 |
+
# TODO: Add qat support for BNReLU2d
|
| 43 |
+
return super().from_float(mod, use_precomputed_fake_quant=use_precomputed_fake_quant)
|
| 44 |
+
|
| 45 |
+
@classmethod
|
| 46 |
+
def from_reference(cls, bn_relu, output_scale, output_zero_point):
|
| 47 |
+
return super().from_reference(bn_relu[0], output_scale, output_zero_point)
|
| 48 |
+
|
| 49 |
+
class BNReLU3d(nnq.BatchNorm3d):
|
| 50 |
+
r"""
|
| 51 |
+
A BNReLU3d module is a fused module of BatchNorm3d and ReLU
|
| 52 |
+
|
| 53 |
+
We adopt the same interface as :class:`torch.ao.nn.quantized.BatchNorm3d`.
|
| 54 |
+
|
| 55 |
+
Attributes:
|
| 56 |
+
Same as torch.ao.nn.quantized.BatchNorm3d
|
| 57 |
+
|
| 58 |
+
"""
|
| 59 |
+
_FLOAT_MODULE = torch.ao.nn.intrinsic.BNReLU3d
|
| 60 |
+
|
| 61 |
+
def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
|
| 62 |
+
super().__init__(num_features, eps=eps, momentum=momentum, device=device, dtype=dtype)
|
| 63 |
+
|
| 64 |
+
def forward(self, input):
|
| 65 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 66 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 67 |
+
if len(input.shape) != 5:
|
| 68 |
+
raise ValueError("Input shape must be `(N, C, D, H, W)`!")
|
| 69 |
+
return torch.ops.quantized.batch_norm3d_relu(
|
| 70 |
+
input, self.weight, self.bias, self.running_mean,
|
| 71 |
+
self.running_var, self.eps, self.scale, self.zero_point)
|
| 72 |
+
|
| 73 |
+
def _get_name(self):
|
| 74 |
+
return 'QuantizedBNReLU3d'
|
| 75 |
+
|
| 76 |
+
@classmethod
|
| 77 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 78 |
+
# TODO: Add qat support for BNReLU3d
|
| 79 |
+
return super().from_float(mod, use_precomputed_fake_quant=use_precomputed_fake_quant)
|
| 80 |
+
|
| 81 |
+
@classmethod
|
| 82 |
+
def from_reference(cls, bn_relu, output_scale, output_zero_point):
|
| 83 |
+
return super().from_reference(bn_relu[0], output_scale, output_zero_point)
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_add.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch.ao.nn.intrinsic
|
| 4 |
+
import torch.ao.nn.intrinsic.qat
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
import torch.ao.nn.quantized as nnq
|
| 7 |
+
|
| 8 |
+
_reverse_repeat_padding = nnq.modules.conv._reverse_repeat_padding
|
| 9 |
+
|
| 10 |
+
class ConvAdd2d(nnq.Conv2d):
|
| 11 |
+
r"""
|
| 12 |
+
A ConvAdd2d module is a fused module of Conv2d and Add
|
| 13 |
+
|
| 14 |
+
We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`.
|
| 15 |
+
|
| 16 |
+
Attributes:
|
| 17 |
+
Same as torch.ao.nn.quantized.Conv2d
|
| 18 |
+
|
| 19 |
+
"""
|
| 20 |
+
_FLOAT_MODULE = torch.ao.nn.intrinsic.ConvAdd2d # type: ignore[assignment]
|
| 21 |
+
|
| 22 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
| 23 |
+
padding=0, dilation=1, groups=1, bias=True,
|
| 24 |
+
padding_mode='zeros', device=None, dtype=None):
|
| 25 |
+
super().__init__(
|
| 26 |
+
in_channels, out_channels, kernel_size, stride=stride,
|
| 27 |
+
padding=padding, dilation=dilation, groups=groups, bias=bias,
|
| 28 |
+
padding_mode=padding_mode, device=device, dtype=dtype)
|
| 29 |
+
|
| 30 |
+
def forward(self, input, extra_input):
|
| 31 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 32 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 33 |
+
if len(input.shape) != 4:
|
| 34 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 35 |
+
if self.padding_mode != 'zeros':
|
| 36 |
+
_reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
|
| 37 |
+
input = F.pad(input, _reversed_padding_repeated_twice,
|
| 38 |
+
mode=self.padding_mode)
|
| 39 |
+
return torch.ops.quantized.conv2d_add(
|
| 40 |
+
input, extra_input, self._packed_params, self.scale, self.zero_point)
|
| 41 |
+
|
| 42 |
+
def _get_name(self):
|
| 43 |
+
return 'QuantizedConvAdd2d'
|
| 44 |
+
|
| 45 |
+
@classmethod
|
| 46 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 47 |
+
return super().from_float(mod, use_precomputed_fake_quant=use_precomputed_fake_quant)
|
| 48 |
+
|
| 49 |
+
@classmethod
|
| 50 |
+
def from_reference(cls, ref_qconv, output_scale, output_zero_point):
|
| 51 |
+
return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
|
| 52 |
+
|
| 53 |
+
class ConvAddReLU2d(nnq.Conv2d):
|
| 54 |
+
r"""
|
| 55 |
+
A ConvAddReLU2d module is a fused module of Conv2d, Add and Relu
|
| 56 |
+
|
| 57 |
+
We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`.
|
| 58 |
+
|
| 59 |
+
Attributes:
|
| 60 |
+
Same as torch.ao.nn.quantized.Conv2d
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
_FLOAT_MODULE = torch.ao.nn.intrinsic.ConvAddReLU2d # type: ignore[assignment]
|
| 64 |
+
|
| 65 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
| 66 |
+
padding=0, dilation=1, groups=1, bias=True,
|
| 67 |
+
padding_mode='zeros', device=None, dtype=None):
|
| 68 |
+
super().__init__(
|
| 69 |
+
in_channels, out_channels, kernel_size, stride=stride,
|
| 70 |
+
padding=padding, dilation=dilation, groups=groups, bias=bias,
|
| 71 |
+
padding_mode=padding_mode, device=device, dtype=dtype)
|
| 72 |
+
|
| 73 |
+
def forward(self, input, extra_input):
|
| 74 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 75 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 76 |
+
if len(input.shape) != 4:
|
| 77 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 78 |
+
if self.padding_mode != 'zeros':
|
| 79 |
+
_reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
|
| 80 |
+
input = F.pad(input, _reversed_padding_repeated_twice,
|
| 81 |
+
mode=self.padding_mode)
|
| 82 |
+
return torch.ops.quantized.conv2d_add_relu(
|
| 83 |
+
input, extra_input, self._packed_params, self.scale, self.zero_point)
|
| 84 |
+
|
| 85 |
+
def _get_name(self):
|
| 86 |
+
return 'QuantizedConvAddReLU2d'
|
| 87 |
+
|
| 88 |
+
@classmethod
|
| 89 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 90 |
+
return super().from_float(mod, use_precomputed_fake_quant=use_precomputed_fake_quant)
|
| 91 |
+
|
| 92 |
+
@classmethod
|
| 93 |
+
def from_reference(cls, ref_qconv, output_scale, output_zero_point):
|
| 94 |
+
return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/conv_relu.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.ao.nn.intrinsic
|
| 5 |
+
import torch.ao.nn.intrinsic.qat
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
import torch.ao.nn.quantized as nnq
|
| 8 |
+
|
| 9 |
+
from torch.nn.utils import fuse_conv_bn_weights
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"ConvReLU1d",
|
| 13 |
+
"ConvReLU2d",
|
| 14 |
+
"ConvReLU3d",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
_reverse_repeat_padding = nnq.modules.conv._reverse_repeat_padding
|
| 18 |
+
|
| 19 |
+
# TODO: factor out the common parts to ConvNd
|
| 20 |
+
class ConvReLU1d(nnq.Conv1d):
|
| 21 |
+
r"""
|
| 22 |
+
A ConvReLU1d module is a fused module of Conv1d and ReLU
|
| 23 |
+
|
| 24 |
+
We adopt the same interface as :class:`torch.ao.nn.quantized.Conv1d`.
|
| 25 |
+
|
| 26 |
+
Attributes:
|
| 27 |
+
Same as torch.ao.nn.quantized.Conv1d
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
_FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU1d # type: ignore[assignment]
|
| 31 |
+
|
| 32 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
| 33 |
+
padding=0, dilation=1, groups=1, bias=True,
|
| 34 |
+
padding_mode='zeros', device=None, dtype=None):
|
| 35 |
+
super().__init__(
|
| 36 |
+
in_channels, out_channels, kernel_size, stride=stride,
|
| 37 |
+
padding=padding, dilation=dilation, groups=groups, bias=bias,
|
| 38 |
+
padding_mode=padding_mode, device=device, dtype=dtype)
|
| 39 |
+
|
| 40 |
+
def forward(self, input):
|
| 41 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 42 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 43 |
+
if len(input.shape) != 3:
|
| 44 |
+
raise ValueError("Input shape must be `(N, C, L)`!")
|
| 45 |
+
if self.padding_mode != 'zeros':
|
| 46 |
+
# Padding in Conv1d is stored as (p, p), need to get (p,)
|
| 47 |
+
_reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding[:1])
|
| 48 |
+
input = F.pad(input, _reversed_padding_repeated_twice,
|
| 49 |
+
mode=self.padding_mode)
|
| 50 |
+
return torch.ops.quantized.conv1d_relu(
|
| 51 |
+
input, self._packed_params, self.scale, self.zero_point)
|
| 52 |
+
|
| 53 |
+
def _get_name(self):
|
| 54 |
+
return 'QuantizedConvReLU1d'
|
| 55 |
+
|
| 56 |
+
@classmethod
|
| 57 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 58 |
+
if type(mod) == torch.ao.nn.intrinsic.qat.ConvBnReLU1d:
|
| 59 |
+
assert mod.bn.running_var is not None and mod.bn.running_mean is not None
|
| 60 |
+
mod.weight, mod.bias = fuse_conv_bn_weights(
|
| 61 |
+
mod.weight, mod.bias, mod.bn.running_mean, mod.bn.running_var,
|
| 62 |
+
mod.bn.eps, mod.bn.weight, mod.bn.bias)
|
| 63 |
+
return super().from_float(mod, use_precomputed_fake_quant)
|
| 64 |
+
|
| 65 |
+
@classmethod
|
| 66 |
+
def from_reference(cls, ref_qconv, output_scale, output_zero_point):
|
| 67 |
+
assert type(ref_qconv) != torch.ao.nn.intrinsic.ConvBnReLU1d, \
|
| 68 |
+
"BatchNorm1d should be fused into Conv1d before converting to reference module"
|
| 69 |
+
return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
|
| 70 |
+
|
| 71 |
+
class ConvReLU2d(nnq.Conv2d):
|
| 72 |
+
r"""
|
| 73 |
+
A ConvReLU2d module is a fused module of Conv2d and ReLU
|
| 74 |
+
|
| 75 |
+
We adopt the same interface as :class:`torch.ao.nn.quantized.Conv2d`.
|
| 76 |
+
|
| 77 |
+
Attributes:
|
| 78 |
+
Same as torch.ao.nn.quantized.Conv2d
|
| 79 |
+
|
| 80 |
+
"""
|
| 81 |
+
_FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU2d # type: ignore[assignment]
|
| 82 |
+
|
| 83 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
| 84 |
+
padding=0, dilation=1, groups=1, bias=True,
|
| 85 |
+
padding_mode='zeros', device=None, dtype=None):
|
| 86 |
+
super().__init__(
|
| 87 |
+
in_channels, out_channels, kernel_size, stride=stride,
|
| 88 |
+
padding=padding, dilation=dilation, groups=groups, bias=bias,
|
| 89 |
+
padding_mode=padding_mode, device=device, dtype=dtype)
|
| 90 |
+
|
| 91 |
+
def forward(self, input):
|
| 92 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 93 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 94 |
+
if len(input.shape) != 4:
|
| 95 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 96 |
+
if self.padding_mode != 'zeros':
|
| 97 |
+
_reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
|
| 98 |
+
input = F.pad(input, _reversed_padding_repeated_twice,
|
| 99 |
+
mode=self.padding_mode)
|
| 100 |
+
return torch.ops.quantized.conv2d_relu(
|
| 101 |
+
input, self._packed_params, self.scale, self.zero_point)
|
| 102 |
+
|
| 103 |
+
def _get_name(self):
|
| 104 |
+
return 'QuantizedConvReLU2d'
|
| 105 |
+
|
| 106 |
+
@classmethod
|
| 107 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 108 |
+
if type(mod) == torch.ao.nn.intrinsic.qat.ConvBnReLU2d:
|
| 109 |
+
assert mod.bn.running_var is not None and mod.bn.running_mean is not None
|
| 110 |
+
mod.weight, mod.bias = fuse_conv_bn_weights(
|
| 111 |
+
mod.weight, mod.bias, mod.bn.running_mean, mod.bn.running_var,
|
| 112 |
+
mod.bn.eps, mod.bn.weight, mod.bn.bias)
|
| 113 |
+
return super().from_float(mod, use_precomputed_fake_quant=use_precomputed_fake_quant)
|
| 114 |
+
|
| 115 |
+
@classmethod
|
| 116 |
+
def from_reference(cls, ref_qconv, output_scale, output_zero_point):
|
| 117 |
+
assert type(ref_qconv) != torch.ao.nn.intrinsic.ConvBnReLU2d, \
|
| 118 |
+
"BatchNorm2d should be fused into Conv2d before converting to reference module"
|
| 119 |
+
return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class ConvReLU3d(nnq.Conv3d):
|
| 123 |
+
r"""
|
| 124 |
+
A ConvReLU3d module is a fused module of Conv3d and ReLU
|
| 125 |
+
|
| 126 |
+
We adopt the same interface as :class:`torch.ao.nn.quantized.Conv3d`.
|
| 127 |
+
|
| 128 |
+
Attributes: Same as torch.ao.nn.quantized.Conv3d
|
| 129 |
+
|
| 130 |
+
"""
|
| 131 |
+
_FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU3d # type: ignore[assignment]
|
| 132 |
+
|
| 133 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
| 134 |
+
padding=0, dilation=1, groups=1, bias=True,
|
| 135 |
+
padding_mode='zeros', device=None, dtype=None):
|
| 136 |
+
assert padding_mode != 'reflect', "Conv3d does not support reflection padding"
|
| 137 |
+
super().__init__(
|
| 138 |
+
in_channels, out_channels, kernel_size, stride=stride,
|
| 139 |
+
padding=padding, dilation=dilation, groups=groups, bias=bias,
|
| 140 |
+
padding_mode=padding_mode, device=device, dtype=dtype)
|
| 141 |
+
|
| 142 |
+
def forward(self, input):
|
| 143 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 144 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 145 |
+
if len(input.shape) != 5:
|
| 146 |
+
raise ValueError("Input shape must be `(N, C, D, H, W)`!")
|
| 147 |
+
if self.padding_mode != 'zeros':
|
| 148 |
+
_reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
|
| 149 |
+
input = F.pad(input, _reversed_padding_repeated_twice,
|
| 150 |
+
mode=self.padding_mode)
|
| 151 |
+
return torch.ops.quantized.conv3d_relu(
|
| 152 |
+
input, self._packed_params, self.scale, self.zero_point)
|
| 153 |
+
|
| 154 |
+
def _get_name(self):
|
| 155 |
+
return 'QuantizedConvReLU3d'
|
| 156 |
+
|
| 157 |
+
@classmethod
|
| 158 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 159 |
+
if type(mod) == torch.ao.nn.intrinsic.qat.ConvBnReLU3d:
|
| 160 |
+
assert mod.bn.running_var is not None and mod.bn.running_mean is not None
|
| 161 |
+
mod.weight, mod.bias = fuse_conv_bn_weights(
|
| 162 |
+
mod.weight,
|
| 163 |
+
mod.bias,
|
| 164 |
+
mod.bn.running_mean,
|
| 165 |
+
mod.bn.running_var,
|
| 166 |
+
mod.bn.eps,
|
| 167 |
+
mod.bn.weight,
|
| 168 |
+
mod.bn.bias,
|
| 169 |
+
)
|
| 170 |
+
return super().from_float(mod, use_precomputed_fake_quant=use_precomputed_fake_quant)
|
| 171 |
+
|
| 172 |
+
@classmethod
|
| 173 |
+
def from_reference(cls, ref_qconv, output_scale, output_zero_point):
|
| 174 |
+
assert type(ref_qconv) != torch.ao.nn.intrinsic.ConvBnReLU3d, \
|
| 175 |
+
"BatchNorm3d should be fused into Conv3d before converting to reference module"
|
| 176 |
+
return super().from_reference(ref_qconv[0], output_scale, output_zero_point)
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/intrinsic/quantized/modules/linear_relu.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch.ao.nn.quantized as nnq
|
| 4 |
+
import torch.ao.nn.intrinsic as nni
|
| 5 |
+
from torch.ao.nn.quantized.modules.utils import _quantize_weight
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"LinearReLU",
|
| 9 |
+
"LinearLeakyReLU",
|
| 10 |
+
"LinearTanh",
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
+
class LinearReLU(nnq.Linear):
|
| 14 |
+
r"""
|
| 15 |
+
A LinearReLU module fused from Linear and ReLU modules
|
| 16 |
+
|
| 17 |
+
We adopt the same interface as :class:`torch.ao.nn.quantized.Linear`.
|
| 18 |
+
|
| 19 |
+
Attributes:
|
| 20 |
+
Same as torch.ao.nn.quantized.Linear
|
| 21 |
+
|
| 22 |
+
Examples::
|
| 23 |
+
|
| 24 |
+
>>> # xdoctest: +SKIP
|
| 25 |
+
>>> m = nn.intrinsic.LinearReLU(20, 30)
|
| 26 |
+
>>> input = torch.randn(128, 20)
|
| 27 |
+
>>> output = m(input)
|
| 28 |
+
>>> print(output.size())
|
| 29 |
+
torch.Size([128, 30])
|
| 30 |
+
"""
|
| 31 |
+
_FLOAT_MODULE = nni.LinearReLU # type: ignore[assignment]
|
| 32 |
+
|
| 33 |
+
def __init__(self, in_features, out_features, bias=True, dtype=torch.qint8):
|
| 34 |
+
super().__init__(in_features, out_features, bias, dtype)
|
| 35 |
+
|
| 36 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 37 |
+
return torch.ops.quantized.linear_relu(
|
| 38 |
+
x, self._packed_params._packed_params, self.scale, self.zero_point)
|
| 39 |
+
|
| 40 |
+
def _get_name(self):
|
| 41 |
+
return 'QuantizedLinearReLU'
|
| 42 |
+
|
| 43 |
+
@classmethod
|
| 44 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 45 |
+
return super().from_float(mod, use_precomputed_fake_quant)
|
| 46 |
+
|
| 47 |
+
@classmethod
|
| 48 |
+
def from_reference(cls, ref_linear_relu, output_scale, output_zero_point):
|
| 49 |
+
return super().from_reference(ref_linear_relu[0], output_scale, output_zero_point)
|
| 50 |
+
|
| 51 |
+
class LinearLeakyReLU(nnq.Linear):
|
| 52 |
+
r"""
|
| 53 |
+
For onednn backend only
|
| 54 |
+
A LinearLeakyReLU module fused from Linear and LeakyReLU modules
|
| 55 |
+
We adopt the same interface as :class:`torch.ao.nn.quantized.Linear`.
|
| 56 |
+
Attributes:
|
| 57 |
+
Same as torch.ao.nn.quantized.Linear
|
| 58 |
+
+ negative_slope
|
| 59 |
+
Examples::
|
| 60 |
+
>>> # xdoctest: +SKIP
|
| 61 |
+
>>> m = nn.intrinsic.LinearLeakyReLU(20, 30, 0.01)
|
| 62 |
+
>>> input = torch.randn(128, 20)
|
| 63 |
+
>>> output = m(input)
|
| 64 |
+
>>> print(output.size())
|
| 65 |
+
torch.Size([128, 30])
|
| 66 |
+
"""
|
| 67 |
+
_FLOAT_MODULE = nni.LinearLeakyReLU # type: ignore[assignment]
|
| 68 |
+
|
| 69 |
+
def __init__(self, in_features, out_features, negative_slope, bias=True, dtype=torch.qint8):
|
| 70 |
+
super().__init__(in_features, out_features, bias, dtype)
|
| 71 |
+
self.negative_slope = negative_slope
|
| 72 |
+
|
| 73 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 74 |
+
return torch.ops.quantized.linear_leaky_relu(
|
| 75 |
+
x, self._packed_params._packed_params, self.scale, self.zero_point, self.negative_slope)
|
| 76 |
+
|
| 77 |
+
def _get_name(self):
|
| 78 |
+
return 'QuantizedLinearLeakyReLU'
|
| 79 |
+
|
| 80 |
+
@classmethod
|
| 81 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 82 |
+
assert type(mod) == nni.LinearLeakyReLU, 'Input float module should be LinearLeakyReLU'
|
| 83 |
+
assert hasattr(mod, 'qconfig'), 'Input float module must have qconfig defined'
|
| 84 |
+
activation_post_process = mod.activation_post_process
|
| 85 |
+
leaky_relu = mod[1]
|
| 86 |
+
mod = mod[0]
|
| 87 |
+
weight_post_process = mod.qconfig.weight()
|
| 88 |
+
weight_post_process(mod.weight)
|
| 89 |
+
dtype = weight_post_process.dtype
|
| 90 |
+
act_scale, act_zp = activation_post_process.calculate_qparams() # type: ignore[union-attr,operator]
|
| 91 |
+
assert dtype == torch.qint8, 'Weight observer must have dtype torch.qint8'
|
| 92 |
+
qweight = _quantize_weight(mod.weight.float(), weight_post_process)
|
| 93 |
+
qlinear_leaky_relu = cls(
|
| 94 |
+
mod.in_features,
|
| 95 |
+
mod.out_features,
|
| 96 |
+
leaky_relu.negative_slope,
|
| 97 |
+
dtype=dtype)
|
| 98 |
+
qlinear_leaky_relu.set_weight_bias(qweight, mod.bias)
|
| 99 |
+
qlinear_leaky_relu.scale = float(act_scale)
|
| 100 |
+
qlinear_leaky_relu.zero_point = int(act_zp)
|
| 101 |
+
return qlinear_leaky_relu
|
| 102 |
+
|
| 103 |
+
@classmethod
|
| 104 |
+
def from_reference(cls, ref_mod, output_scale, output_zero_point):
|
| 105 |
+
linear = ref_mod[0]
|
| 106 |
+
leaky_relu = ref_mod[1]
|
| 107 |
+
qlinear_leaky_relu = cls(
|
| 108 |
+
linear.in_features,
|
| 109 |
+
linear.out_features,
|
| 110 |
+
leaky_relu.negative_slope)
|
| 111 |
+
qweight = linear.get_quantized_weight()
|
| 112 |
+
qlinear_leaky_relu.set_weight_bias(qweight, linear.bias)
|
| 113 |
+
qlinear_leaky_relu.scale = float(output_scale)
|
| 114 |
+
qlinear_leaky_relu.zero_point = int(output_zero_point)
|
| 115 |
+
return qlinear_leaky_relu
|
| 116 |
+
|
| 117 |
+
class LinearTanh(nnq.Linear):
|
| 118 |
+
r"""
|
| 119 |
+
A LinearTanh module fused from Linear and Tanh modules
|
| 120 |
+
|
| 121 |
+
We adopt the same interface as :class:`torch.ao.nn.quantized.Linear`.
|
| 122 |
+
|
| 123 |
+
Attributes:
|
| 124 |
+
Same as torch.ao.nn.quantized.Linear
|
| 125 |
+
|
| 126 |
+
Examples::
|
| 127 |
+
|
| 128 |
+
>>> # xdoctest: +SKIP
|
| 129 |
+
>>> m = nn.intrinsic.LinearTanh(20, 30)
|
| 130 |
+
>>> input = torch.randn(128, 20)
|
| 131 |
+
>>> output = m(input)
|
| 132 |
+
>>> print(output.size())
|
| 133 |
+
torch.Size([128, 30])
|
| 134 |
+
"""
|
| 135 |
+
_FLOAT_MODULE = nni.LinearTanh # type: ignore[assignment]
|
| 136 |
+
|
| 137 |
+
def __init__(self, in_features, out_features, bias=True, dtype=torch.qint8):
|
| 138 |
+
super().__init__(in_features, out_features, bias, dtype)
|
| 139 |
+
|
| 140 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 141 |
+
return torch.ops.quantized.linear_tanh(
|
| 142 |
+
x, self._packed_params._packed_params, self.scale, self.zero_point)
|
| 143 |
+
|
| 144 |
+
def _get_name(self):
|
| 145 |
+
return 'QuantizedLinearTanh'
|
| 146 |
+
|
| 147 |
+
@classmethod
|
| 148 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 149 |
+
assert type(mod) == nni.LinearTanh, 'Input float module should be LinearTanh'
|
| 150 |
+
assert hasattr(mod, 'qconfig'), 'Input float module must have qconfig defined'
|
| 151 |
+
activation_post_process = mod.activation_post_process
|
| 152 |
+
mod = mod[0]
|
| 153 |
+
weight_post_process = mod.qconfig.weight()
|
| 154 |
+
weight_post_process(mod.weight)
|
| 155 |
+
dtype = weight_post_process.dtype
|
| 156 |
+
act_scale, act_zp = activation_post_process.calculate_qparams() # type: ignore[union-attr,operator]
|
| 157 |
+
assert dtype == torch.qint8, 'Weight observer must have dtype torch.qint8'
|
| 158 |
+
qweight = _quantize_weight(mod.weight.float(), weight_post_process)
|
| 159 |
+
qlinear_tanh = cls(
|
| 160 |
+
mod.in_features,
|
| 161 |
+
mod.out_features,
|
| 162 |
+
dtype=dtype)
|
| 163 |
+
qlinear_tanh.set_weight_bias(qweight, mod.bias)
|
| 164 |
+
qlinear_tanh.scale = float(act_scale)
|
| 165 |
+
qlinear_tanh.zero_point = int(act_zp)
|
| 166 |
+
return qlinear_tanh
|
| 167 |
+
|
| 168 |
+
@classmethod
|
| 169 |
+
def from_reference(cls, ref_mod, output_scale, output_zero_point):
|
| 170 |
+
linear = ref_mod[0]
|
| 171 |
+
qlinear_tanh = cls(
|
| 172 |
+
linear.in_features,
|
| 173 |
+
linear.out_features)
|
| 174 |
+
qweight = linear.get_quantized_weight()
|
| 175 |
+
qlinear_tanh.set_weight_bias(qweight, linear.bias)
|
| 176 |
+
qlinear_tanh.scale = float(output_scale)
|
| 177 |
+
qlinear_tanh.zero_point = int(output_zero_point)
|
| 178 |
+
return qlinear_tanh
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .modules import * # noqa: F403
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (196 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .modules import * # noqa: F403
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (204 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/modules/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .linear import Linear
|
| 2 |
+
|
| 3 |
+
__all__ = ["Linear"]
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (247 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/linear.cpython-310.pyc
ADDED
|
Binary file (1.27 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/dynamic/modules/linear.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
__all__ = ["Linear"]
|
| 5 |
+
|
| 6 |
+
class Linear(torch.ao.nn.qat.Linear):
|
| 7 |
+
r"""
|
| 8 |
+
A linear module attached with FakeQuantize modules for weight,
|
| 9 |
+
used for dynamic quantization aware training.
|
| 10 |
+
|
| 11 |
+
We adopt the same interface as `torch.nn.Linear`, please see
|
| 12 |
+
https://pytorch.org/docs/stable/nn.html#torch.nn.Linear
|
| 13 |
+
for documentation.
|
| 14 |
+
|
| 15 |
+
Similar to `torch.nn.Linear`, with FakeQuantize modules initialized to
|
| 16 |
+
default.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self, in_features, out_features, bias=True,
|
| 20 |
+
qconfig=None, device=None, dtype=None) -> None:
|
| 21 |
+
super().__init__(in_features, out_features, bias, qconfig, device, dtype)
|
| 22 |
+
if not torch.ao.quantization.qconfig._activation_is_memoryless(qconfig):
|
| 23 |
+
raise ValueError(
|
| 24 |
+
"Dynamic QAT requires a memoryless observer." +
|
| 25 |
+
"This means a MovingAverage observer with averaging constant equal to 1"
|
| 26 |
+
)
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .linear import Linear
|
| 2 |
+
from .conv import Conv1d
|
| 3 |
+
from .conv import Conv2d
|
| 4 |
+
from .conv import Conv3d
|
| 5 |
+
from .embedding_ops import EmbeddingBag, Embedding
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"Linear",
|
| 9 |
+
"Conv1d",
|
| 10 |
+
"Conv2d",
|
| 11 |
+
"Conv3d",
|
| 12 |
+
"Embedding",
|
| 13 |
+
"EmbeddingBag",
|
| 14 |
+
]
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (431 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/__pycache__/conv.cpython-310.pyc
ADDED
|
Binary file (6.97 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/__pycache__/embedding_ops.cpython-310.pyc
ADDED
|
Binary file (5.32 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/__pycache__/linear.cpython-310.pyc
ADDED
|
Binary file (2.87 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/conv.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from torch.nn.modules.utils import _single, _pair, _triple
|
| 5 |
+
from torch.ao.nn.intrinsic import _FusedModule
|
| 6 |
+
from typing import Tuple, TypeVar, Union
|
| 7 |
+
from torch.nn.common_types import _size_1_t, _size_2_t, _size_3_t
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
"Conv1d",
|
| 11 |
+
"Conv2d",
|
| 12 |
+
"Conv3d"
|
| 13 |
+
]
|
| 14 |
+
|
| 15 |
+
MOD = TypeVar('MOD', bound=nn.modules.conv._ConvNd)
|
| 16 |
+
|
| 17 |
+
class _ConvNd(nn.modules.conv._ConvNd):
|
| 18 |
+
|
| 19 |
+
_FLOAT_MODULE = MOD
|
| 20 |
+
|
| 21 |
+
def __init__(self,
|
| 22 |
+
in_channels: int,
|
| 23 |
+
out_channels: int,
|
| 24 |
+
kernel_size: Tuple[int, ...],
|
| 25 |
+
stride: Tuple[int, ...],
|
| 26 |
+
padding: Tuple[int, ...],
|
| 27 |
+
dilation: Tuple[int, ...],
|
| 28 |
+
transposed: bool,
|
| 29 |
+
output_padding: Tuple[int, ...],
|
| 30 |
+
groups: int,
|
| 31 |
+
bias: bool,
|
| 32 |
+
padding_mode: str,
|
| 33 |
+
qconfig=None,
|
| 34 |
+
device=None,
|
| 35 |
+
dtype=None) -> None:
|
| 36 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 37 |
+
nn.modules.conv._ConvNd.__init__(self, in_channels, out_channels, kernel_size,
|
| 38 |
+
stride, padding, dilation, transposed,
|
| 39 |
+
output_padding, groups, bias, padding_mode, **factory_kwargs)
|
| 40 |
+
assert qconfig, 'qconfig must be provided for QAT module'
|
| 41 |
+
self.qconfig = qconfig
|
| 42 |
+
self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
|
| 43 |
+
|
| 44 |
+
def forward(self, input):
|
| 45 |
+
return self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
|
| 46 |
+
|
| 47 |
+
@staticmethod
|
| 48 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 49 |
+
r"""Create a qat module from a float module
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
`mod`: a float module, either produced by torch.ao.quantization utilities
|
| 53 |
+
or directly from user
|
| 54 |
+
"""
|
| 55 |
+
assert type(mod) == cls._FLOAT_MODULE, (
|
| 56 |
+
"qat."
|
| 57 |
+
+ cls.__name__
|
| 58 |
+
+ ".from_float only works for "
|
| 59 |
+
+ cls._FLOAT_MODULE.__name__ # type: ignore[attr-defined]
|
| 60 |
+
)
|
| 61 |
+
assert hasattr(mod, 'qconfig'), 'Input float module must have qconfig defined'
|
| 62 |
+
assert mod.qconfig, 'Input float module must have a valid qconfig'
|
| 63 |
+
if issubclass(type(mod), _FusedModule):
|
| 64 |
+
mod = mod[0] # type: ignore[index]
|
| 65 |
+
qconfig = mod.qconfig
|
| 66 |
+
qat_conv = cls(mod.in_channels, mod.out_channels, mod.kernel_size,
|
| 67 |
+
stride=mod.stride, padding=mod.padding, dilation=mod.dilation,
|
| 68 |
+
groups=mod.groups, bias=mod.bias is not None,
|
| 69 |
+
padding_mode=mod.padding_mode, qconfig=qconfig)
|
| 70 |
+
qat_conv.weight = mod.weight
|
| 71 |
+
qat_conv.bias = mod.bias
|
| 72 |
+
return qat_conv
|
| 73 |
+
|
| 74 |
+
def to_float(self):
|
| 75 |
+
""" This works for both single qat conv, and the qat conv - relu modules
|
| 76 |
+
to convert the qat module to a floating point module
|
| 77 |
+
"""
|
| 78 |
+
cls = type(self)
|
| 79 |
+
conv = cls._FLOAT_CONV_MODULE( # type: ignore[attr-defined, operator]
|
| 80 |
+
self.in_channels,
|
| 81 |
+
self.out_channels,
|
| 82 |
+
self.kernel_size, # type: ignore[arg-type]
|
| 83 |
+
self.stride, # type: ignore[arg-type]
|
| 84 |
+
self.padding, # type: ignore[arg-type]
|
| 85 |
+
self.dilation, # type: ignore[arg-type]
|
| 86 |
+
self.groups,
|
| 87 |
+
self.bias is not None,
|
| 88 |
+
self.padding_mode)
|
| 89 |
+
conv.weight = torch.nn.Parameter(self.weight.detach())
|
| 90 |
+
if self.bias is not None:
|
| 91 |
+
conv.bias = torch.nn.Parameter(self.bias.detach())
|
| 92 |
+
# conv relu
|
| 93 |
+
if issubclass(cls, _FusedModule):
|
| 94 |
+
modules = [conv]
|
| 95 |
+
assert hasattr(cls, "_FLOAT_RELU_MODULE")
|
| 96 |
+
relu = cls._FLOAT_RELU_MODULE() # type: ignore[attr-defined]
|
| 97 |
+
modules.append(relu)
|
| 98 |
+
fused = cls._FLOAT_MODULE(*modules) # type: ignore[arg-type, attr-defined, operator]
|
| 99 |
+
fused.train(self.training)
|
| 100 |
+
return fused
|
| 101 |
+
else:
|
| 102 |
+
return conv
|
| 103 |
+
|
| 104 |
+
class Conv1d(_ConvNd, nn.Conv1d):
|
| 105 |
+
r"""
|
| 106 |
+
A Conv1d module attached with FakeQuantize modules for weight,
|
| 107 |
+
used for quantization aware training.
|
| 108 |
+
|
| 109 |
+
We adopt the same interface as :class:`~torch.nn.Conv1d`
|
| 110 |
+
|
| 111 |
+
Similar to :class:`~torch.nn.Conv2d`, with FakeQuantize modules initialized to
|
| 112 |
+
default.
|
| 113 |
+
|
| 114 |
+
Attributes:
|
| 115 |
+
weight_fake_quant: fake quant module for weight
|
| 116 |
+
"""
|
| 117 |
+
_FLOAT_MODULE = nn.Conv1d
|
| 118 |
+
_FLOAT_CONV_MODULE = nn.Conv1d
|
| 119 |
+
|
| 120 |
+
def __init__(self,
|
| 121 |
+
in_channels: int,
|
| 122 |
+
out_channels: int,
|
| 123 |
+
kernel_size: _size_1_t,
|
| 124 |
+
stride: _size_1_t = 1,
|
| 125 |
+
padding: Union[str, _size_1_t] = 0,
|
| 126 |
+
dilation: _size_1_t = 1,
|
| 127 |
+
groups: int = 1,
|
| 128 |
+
bias: bool = True,
|
| 129 |
+
padding_mode: str = 'zeros',
|
| 130 |
+
qconfig=None,
|
| 131 |
+
device=None,
|
| 132 |
+
dtype=None) -> None:
|
| 133 |
+
kernel_size_ = _single(kernel_size)
|
| 134 |
+
stride_ = _single(stride)
|
| 135 |
+
padding_ = padding if isinstance(padding, str) else _single(padding)
|
| 136 |
+
dilation_ = _single(dilation)
|
| 137 |
+
super().__init__(
|
| 138 |
+
in_channels,
|
| 139 |
+
out_channels,
|
| 140 |
+
kernel_size_,
|
| 141 |
+
stride=stride_,
|
| 142 |
+
padding=padding_,
|
| 143 |
+
dilation=dilation_,
|
| 144 |
+
transposed=False,
|
| 145 |
+
output_padding=_single(0),
|
| 146 |
+
groups=groups,
|
| 147 |
+
bias=bias,
|
| 148 |
+
padding_mode=padding_mode,
|
| 149 |
+
qconfig=qconfig,
|
| 150 |
+
device=device,
|
| 151 |
+
dtype=dtype)
|
| 152 |
+
|
| 153 |
+
@classmethod
|
| 154 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 155 |
+
return super().from_float(cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant)
|
| 156 |
+
|
| 157 |
+
class Conv2d(_ConvNd, nn.Conv2d):
|
| 158 |
+
r"""
|
| 159 |
+
A Conv2d module attached with FakeQuantize modules for weight,
|
| 160 |
+
used for quantization aware training.
|
| 161 |
+
|
| 162 |
+
We adopt the same interface as `torch.nn.Conv2d`, please see
|
| 163 |
+
https://pytorch.org/docs/stable/nn.html?highlight=conv2d#torch.nn.Conv2d
|
| 164 |
+
for documentation.
|
| 165 |
+
|
| 166 |
+
Similar to `torch.nn.Conv2d`, with FakeQuantize modules initialized to
|
| 167 |
+
default.
|
| 168 |
+
|
| 169 |
+
Attributes:
|
| 170 |
+
weight_fake_quant: fake quant module for weight
|
| 171 |
+
"""
|
| 172 |
+
_FLOAT_MODULE = nn.Conv2d
|
| 173 |
+
_FLOAT_CONV_MODULE = nn.Conv2d
|
| 174 |
+
|
| 175 |
+
def __init__(self,
|
| 176 |
+
in_channels: int,
|
| 177 |
+
out_channels: int,
|
| 178 |
+
kernel_size: _size_2_t,
|
| 179 |
+
stride: _size_2_t = 1,
|
| 180 |
+
padding: Union[str, _size_2_t] = 0,
|
| 181 |
+
dilation: _size_2_t = 1,
|
| 182 |
+
groups: int = 1,
|
| 183 |
+
bias: bool = True,
|
| 184 |
+
padding_mode: str = 'zeros',
|
| 185 |
+
qconfig=None,
|
| 186 |
+
device=None,
|
| 187 |
+
dtype=None) -> None:
|
| 188 |
+
kernel_size_ = _pair(kernel_size)
|
| 189 |
+
stride_ = _pair(stride)
|
| 190 |
+
padding_ = padding if isinstance(padding, str) else _pair(padding)
|
| 191 |
+
dilation_ = _pair(dilation)
|
| 192 |
+
super().__init__(
|
| 193 |
+
in_channels,
|
| 194 |
+
out_channels,
|
| 195 |
+
kernel_size_,
|
| 196 |
+
stride=stride_,
|
| 197 |
+
padding=padding_,
|
| 198 |
+
dilation=dilation_,
|
| 199 |
+
transposed=False,
|
| 200 |
+
output_padding=_pair(0),
|
| 201 |
+
groups=groups,
|
| 202 |
+
bias=bias,
|
| 203 |
+
padding_mode=padding_mode,
|
| 204 |
+
qconfig=qconfig,
|
| 205 |
+
device=device,
|
| 206 |
+
dtype=dtype)
|
| 207 |
+
|
| 208 |
+
def forward(self, input):
|
| 209 |
+
return self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
|
| 210 |
+
|
| 211 |
+
@classmethod
|
| 212 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 213 |
+
return super().from_float(cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant)
|
| 214 |
+
|
| 215 |
+
class Conv3d(_ConvNd, nn.Conv3d):
|
| 216 |
+
r"""
|
| 217 |
+
A Conv3d module attached with FakeQuantize modules for weight,
|
| 218 |
+
used for quantization aware training.
|
| 219 |
+
|
| 220 |
+
We adopt the same interface as `torch.nn.Conv3d`, please see
|
| 221 |
+
https://pytorch.org/docs/stable/nn.html?highlight=conv3d#torch.nn.Conv3d
|
| 222 |
+
for documentation.
|
| 223 |
+
|
| 224 |
+
Similar to `torch.nn.Conv3d`, with FakeQuantize modules initialized to
|
| 225 |
+
default.
|
| 226 |
+
|
| 227 |
+
Attributes:
|
| 228 |
+
weight_fake_quant: fake quant module for weight
|
| 229 |
+
"""
|
| 230 |
+
_FLOAT_MODULE = nn.Conv3d
|
| 231 |
+
_FLOAT_CONV_MODULE = nn.Conv3d
|
| 232 |
+
|
| 233 |
+
def __init__(self,
|
| 234 |
+
in_channels: int,
|
| 235 |
+
out_channels: int,
|
| 236 |
+
kernel_size: _size_3_t,
|
| 237 |
+
stride: _size_3_t = 1,
|
| 238 |
+
padding: Union[str, _size_3_t] = 0,
|
| 239 |
+
dilation: _size_3_t = 1,
|
| 240 |
+
groups: int = 1,
|
| 241 |
+
bias: bool = True,
|
| 242 |
+
padding_mode: str = 'zeros',
|
| 243 |
+
qconfig=None,
|
| 244 |
+
device=None,
|
| 245 |
+
dtype=None) -> None:
|
| 246 |
+
kernel_size_ = _triple(kernel_size)
|
| 247 |
+
stride_ = _triple(stride)
|
| 248 |
+
padding_ = padding if isinstance(padding, str) else _triple(padding)
|
| 249 |
+
dilation_ = _triple(dilation)
|
| 250 |
+
super().__init__(
|
| 251 |
+
in_channels,
|
| 252 |
+
out_channels,
|
| 253 |
+
kernel_size_,
|
| 254 |
+
stride=stride_,
|
| 255 |
+
padding=padding_,
|
| 256 |
+
dilation=dilation_,
|
| 257 |
+
transposed=False,
|
| 258 |
+
output_padding=_triple(0),
|
| 259 |
+
groups=groups,
|
| 260 |
+
bias=bias,
|
| 261 |
+
padding_mode=padding_mode,
|
| 262 |
+
qconfig=qconfig,
|
| 263 |
+
device=device,
|
| 264 |
+
dtype=dtype)
|
| 265 |
+
|
| 266 |
+
def forward(self, input):
|
| 267 |
+
return self._conv_forward(input, self.weight_fake_quant(self.weight), self.bias)
|
| 268 |
+
|
| 269 |
+
@classmethod
|
| 270 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 271 |
+
return super().from_float(cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant)
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/embedding_ops.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
from torch import Tensor
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
__all__ = ['Embedding', 'EmbeddingBag']
|
| 8 |
+
|
| 9 |
+
class Embedding(nn.Embedding):
|
| 10 |
+
r"""
|
| 11 |
+
An embedding bag module attached with FakeQuantize modules for weight,
|
| 12 |
+
used for quantization aware training.
|
| 13 |
+
|
| 14 |
+
We adopt the same interface as `torch.nn.Embedding`, please see
|
| 15 |
+
https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html#torch.nn.Embedding
|
| 16 |
+
for documentation.
|
| 17 |
+
|
| 18 |
+
Similar to `torch.nn.Embedding`, with FakeQuantize modules initialized to
|
| 19 |
+
default.
|
| 20 |
+
|
| 21 |
+
Attributes:
|
| 22 |
+
weight: fake quant module for weight
|
| 23 |
+
"""
|
| 24 |
+
_FLOAT_MODULE = nn.Embedding
|
| 25 |
+
|
| 26 |
+
def __init__(self, num_embeddings, embedding_dim, padding_idx=None,
|
| 27 |
+
max_norm=None, norm_type=2.0, scale_grad_by_freq=False,
|
| 28 |
+
sparse=False, _weight=None, device=None, dtype=None, qconfig=None) -> None:
|
| 29 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 30 |
+
super().__init__(num_embeddings, embedding_dim, padding_idx, max_norm,
|
| 31 |
+
norm_type, scale_grad_by_freq, sparse, _weight,
|
| 32 |
+
**factory_kwargs)
|
| 33 |
+
assert qconfig, 'qconfig must be provided for QAT module'
|
| 34 |
+
assert qconfig.weight().qscheme == torch.per_channel_affine_float_qparams, \
|
| 35 |
+
'Embedding weights requires a qscheme of torch.per_channel_affine_float_qparams Got ' + \
|
| 36 |
+
str(qconfig.weight().qscheme)
|
| 37 |
+
self.qconfig = qconfig
|
| 38 |
+
self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
|
| 39 |
+
|
| 40 |
+
def forward(self, input) -> Tensor:
|
| 41 |
+
return F.embedding(input, self.weight_fake_quant(self.weight), self.padding_idx,
|
| 42 |
+
self.max_norm, self.norm_type, self.scale_grad_by_freq,
|
| 43 |
+
self.sparse)
|
| 44 |
+
|
| 45 |
+
@classmethod
|
| 46 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 47 |
+
r"""Create a qat module from a float module
|
| 48 |
+
|
| 49 |
+
Args: `mod` a float module, either produced by torch.ao.quantization utilities
|
| 50 |
+
or directly from user
|
| 51 |
+
"""
|
| 52 |
+
assert type(mod) == cls._FLOAT_MODULE, ' qat.' + cls.__name__ + '.from_float only works for ' + \
|
| 53 |
+
cls._FLOAT_MODULE.__name__
|
| 54 |
+
assert hasattr(mod, 'qconfig'), 'Input float module must have qconfig defined'
|
| 55 |
+
assert mod.qconfig, 'Input float module must have a valid qconfig'
|
| 56 |
+
weight_qscheme = mod.qconfig.weight().qscheme # type: ignore[union-attr, operator]
|
| 57 |
+
assert weight_qscheme == torch.per_channel_affine_float_qparams, \
|
| 58 |
+
'Embedding weights requires a qscheme of torch.per_channel_affine_float_qparams Got ' + \
|
| 59 |
+
str(weight_qscheme)
|
| 60 |
+
|
| 61 |
+
qconfig = mod.qconfig
|
| 62 |
+
qat_embedding_bag = cls(mod.num_embeddings, mod.embedding_dim, mod.padding_idx,
|
| 63 |
+
mod.max_norm, mod.norm_type, mod.scale_grad_by_freq,
|
| 64 |
+
mod.sparse, mod.weight, qconfig=qconfig)
|
| 65 |
+
|
| 66 |
+
return qat_embedding_bag
|
| 67 |
+
|
| 68 |
+
def to_float(self):
|
| 69 |
+
embedding_bag = torch.nn.Embedding(self.num_embeddings, self.embedding_dim, self.padding_idx,
|
| 70 |
+
self.max_norm, self.norm_type, self.scale_grad_by_freq,
|
| 71 |
+
self.sparse, None)
|
| 72 |
+
embedding_bag.weight = torch.nn.Parameter(self.weight.detach())
|
| 73 |
+
embedding_bag.train(self.training)
|
| 74 |
+
return embedding_bag
|
| 75 |
+
|
| 76 |
+
class EmbeddingBag(nn.EmbeddingBag):
|
| 77 |
+
r"""
|
| 78 |
+
An embedding bag module attached with FakeQuantize modules for weight,
|
| 79 |
+
used for quantization aware training.
|
| 80 |
+
|
| 81 |
+
We adopt the same interface as `torch.nn.EmbeddingBag`, please see
|
| 82 |
+
https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html#torch.nn.EmbeddingBag
|
| 83 |
+
for documentation.
|
| 84 |
+
|
| 85 |
+
Similar to `torch.nn.EmbeddingBag`, with FakeQuantize modules initialized to
|
| 86 |
+
default.
|
| 87 |
+
|
| 88 |
+
Attributes:
|
| 89 |
+
weight: fake quant module for weight
|
| 90 |
+
"""
|
| 91 |
+
_FLOAT_MODULE = nn.EmbeddingBag
|
| 92 |
+
|
| 93 |
+
def __init__(self, num_embeddings, embedding_dim, max_norm=None,
|
| 94 |
+
norm_type=2.0, scale_grad_by_freq=False, mode='mean',
|
| 95 |
+
sparse=False, _weight=None, include_last_offset=False,
|
| 96 |
+
padding_idx=None, qconfig=None, device=None, dtype=None) -> None:
|
| 97 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 98 |
+
super().__init__(num_embeddings, embedding_dim, max_norm, norm_type,
|
| 99 |
+
scale_grad_by_freq, mode, sparse, _weight,
|
| 100 |
+
include_last_offset, padding_idx, **factory_kwargs)
|
| 101 |
+
assert qconfig, 'qconfig must be provided for QAT module'
|
| 102 |
+
assert qconfig.weight().qscheme == torch.per_channel_affine_float_qparams, \
|
| 103 |
+
'Embedding Bag weights requires a qscheme of torch.per_channel_affine_float_qparams Got ' + \
|
| 104 |
+
str(qconfig.weight().qscheme)
|
| 105 |
+
self.qconfig = qconfig
|
| 106 |
+
self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
|
| 107 |
+
|
| 108 |
+
def forward(self, input, offsets=None, per_sample_weights=None) -> Tensor:
|
| 109 |
+
return F.embedding_bag(input, self.weight_fake_quant(self.weight), offsets,
|
| 110 |
+
self.max_norm, self.norm_type,
|
| 111 |
+
self.scale_grad_by_freq, self.mode, self.sparse,
|
| 112 |
+
per_sample_weights, self.include_last_offset,
|
| 113 |
+
self.padding_idx)
|
| 114 |
+
|
| 115 |
+
@classmethod
|
| 116 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 117 |
+
r"""Create a qat module from a float module
|
| 118 |
+
|
| 119 |
+
Args: `mod` a float module, either produced by torch.ao.quantization utilities
|
| 120 |
+
or directly from user
|
| 121 |
+
"""
|
| 122 |
+
assert type(mod) == cls._FLOAT_MODULE, ' qat.' + cls.__name__ + '.from_float only works for ' + \
|
| 123 |
+
cls._FLOAT_MODULE.__name__
|
| 124 |
+
assert hasattr(mod, 'qconfig'), 'Input float module must have qconfig defined'
|
| 125 |
+
assert mod.qconfig, 'Input float module must have a valid qconfig'
|
| 126 |
+
weight_qscheme = mod.qconfig.weight().qscheme # type: ignore[union-attr, operator]
|
| 127 |
+
assert weight_qscheme == torch.per_channel_affine_float_qparams, \
|
| 128 |
+
'Embedding Bag weights requires a qscheme of torch.per_channel_affine_float_qparams Got ' + \
|
| 129 |
+
str(weight_qscheme)
|
| 130 |
+
|
| 131 |
+
qconfig = mod.qconfig
|
| 132 |
+
qat_embedding_bag = cls(mod.num_embeddings, mod.embedding_dim, mod.max_norm, mod.norm_type,
|
| 133 |
+
mod.scale_grad_by_freq, mod.mode, mod.sparse, mod.weight,
|
| 134 |
+
mod.include_last_offset, mod.padding_idx, qconfig=qconfig)
|
| 135 |
+
|
| 136 |
+
return qat_embedding_bag
|
| 137 |
+
|
| 138 |
+
def to_float(self):
|
| 139 |
+
embedding_bag = torch.nn.EmbeddingBag(self.num_embeddings, self.embedding_dim, self.max_norm,
|
| 140 |
+
self.norm_type, self.scale_grad_by_freq, self.mode, self.sparse,
|
| 141 |
+
None, self.include_last_offset, self.padding_idx)
|
| 142 |
+
embedding_bag.weight = torch.nn.Parameter(self.weight.detach())
|
| 143 |
+
embedding_bag.train(self.training)
|
| 144 |
+
return embedding_bag
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/qat/modules/linear.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch.ao.nn.intrinsic import LinearReLU
|
| 6 |
+
from torch.nn.utils.parametrize import (
|
| 7 |
+
is_parametrized,
|
| 8 |
+
type_before_parametrizations,
|
| 9 |
+
transfer_parametrizations_and_params,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"Linear"
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
class Linear(nn.Linear):
|
| 17 |
+
r"""
|
| 18 |
+
A linear module attached with FakeQuantize modules for weight,
|
| 19 |
+
used for quantization aware training.
|
| 20 |
+
|
| 21 |
+
We adopt the same interface as `torch.nn.Linear`, please see
|
| 22 |
+
https://pytorch.org/docs/stable/nn.html#torch.nn.Linear
|
| 23 |
+
for documentation.
|
| 24 |
+
|
| 25 |
+
Similar to `torch.nn.Linear`, with FakeQuantize modules initialized to
|
| 26 |
+
default.
|
| 27 |
+
|
| 28 |
+
Attributes:
|
| 29 |
+
weight: fake quant module for weight
|
| 30 |
+
"""
|
| 31 |
+
_FLOAT_MODULE = nn.Linear
|
| 32 |
+
|
| 33 |
+
def __init__(self, in_features, out_features, bias=True,
|
| 34 |
+
qconfig=None, device=None, dtype=None) -> None:
|
| 35 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 36 |
+
super().__init__(in_features, out_features, bias, **factory_kwargs)
|
| 37 |
+
assert qconfig, 'qconfig must be provided for QAT module'
|
| 38 |
+
self.qconfig = qconfig
|
| 39 |
+
self.weight_fake_quant = qconfig.weight(factory_kwargs=factory_kwargs)
|
| 40 |
+
|
| 41 |
+
def forward(self, input):
|
| 42 |
+
return F.linear(input, self.weight_fake_quant(self.weight), self.bias)
|
| 43 |
+
|
| 44 |
+
@classmethod
|
| 45 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 46 |
+
r"""Create a qat module from a float module or qparams_dict
|
| 47 |
+
Args: `mod` a float module, either produced by torch.ao.quantization utilities
|
| 48 |
+
or directly from user
|
| 49 |
+
"""
|
| 50 |
+
assert type_before_parametrizations(mod) == cls._FLOAT_MODULE, (
|
| 51 |
+
" qat."
|
| 52 |
+
+ cls.__name__
|
| 53 |
+
+ ".from_float only works for "
|
| 54 |
+
+ cls._FLOAT_MODULE.__name__
|
| 55 |
+
)
|
| 56 |
+
assert hasattr(mod, "qconfig"), "Input float module must have qconfig defined"
|
| 57 |
+
assert mod.qconfig, "Input float module must have a valid qconfig"
|
| 58 |
+
if type_before_parametrizations(mod) == LinearReLU:
|
| 59 |
+
mod = mod[0]
|
| 60 |
+
|
| 61 |
+
qconfig = mod.qconfig
|
| 62 |
+
qat_linear = cls(mod.in_features, mod.out_features, bias=mod.bias is not None, qconfig=qconfig)
|
| 63 |
+
|
| 64 |
+
if is_parametrized(mod, "weight"):
|
| 65 |
+
transfer_parametrizations_and_params(mod, qat_linear, "weight")
|
| 66 |
+
else:
|
| 67 |
+
qat_linear.weight = mod.weight
|
| 68 |
+
|
| 69 |
+
if is_parametrized(mod, "bias"):
|
| 70 |
+
transfer_parametrizations_and_params(mod, qat_linear, "bias")
|
| 71 |
+
else:
|
| 72 |
+
qat_linear.bias = mod.bias
|
| 73 |
+
|
| 74 |
+
return qat_linear
|
| 75 |
+
|
| 76 |
+
def to_float(self):
|
| 77 |
+
linear = torch.nn.Linear(self.in_features, self.out_features, self.bias is not None)
|
| 78 |
+
linear.weight = torch.nn.Parameter(self.weight.detach())
|
| 79 |
+
if self.bias is not None:
|
| 80 |
+
linear.bias = torch.nn.Parameter(self.bias.detach())
|
| 81 |
+
linear.train(self.training)
|
| 82 |
+
return linear
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .modules import * # noqa: F403
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (204 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .activation import MultiheadAttention
|
| 2 |
+
from .rnn import LSTM
|
| 3 |
+
from .rnn import LSTMCell
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
'LSTM',
|
| 7 |
+
'LSTMCell',
|
| 8 |
+
'MultiheadAttention',
|
| 9 |
+
]
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (340 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/__pycache__/activation.cpython-310.pyc
ADDED
|
Binary file (12.1 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/__pycache__/rnn.cpython-310.pyc
ADDED
|
Binary file (12.5 kB). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/activation.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch.jit # this is needed to avoid a circular import
|
| 4 |
+
from torch import nn
|
| 5 |
+
import torch.nn.functional as nnF
|
| 6 |
+
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
from typing import Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"MultiheadAttention"
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
class MultiheadAttention(nn.MultiheadAttention):
|
| 17 |
+
_FLOAT_MODULE = nn.MultiheadAttention
|
| 18 |
+
|
| 19 |
+
r"""Quantizable implementation of the MultiheadAttention.
|
| 20 |
+
|
| 21 |
+
Note::
|
| 22 |
+
Please, refer to :class:`~torch.nn.MultiheadAttention` for more
|
| 23 |
+
information
|
| 24 |
+
|
| 25 |
+
Allows the model to jointly attend to information from different
|
| 26 |
+
representation subspaces.
|
| 27 |
+
See reference: Attention Is All You Need
|
| 28 |
+
|
| 29 |
+
The original MHA module is not quantizable.
|
| 30 |
+
This reimplements it by explicitly instantiating the linear layers.
|
| 31 |
+
|
| 32 |
+
.. math::
|
| 33 |
+
\text{MultiHead}(Q, K, V) = \text{Concat}(head_1,\dots,head_h)W^O
|
| 34 |
+
\text{where} head_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
embed_dim: total dimension of the model.
|
| 38 |
+
num_heads: parallel attention heads.
|
| 39 |
+
dropout: a Dropout layer on attn_output_weights. Default: 0.0.
|
| 40 |
+
bias: add bias as module parameter. Default: True.
|
| 41 |
+
add_bias_kv: add bias to the key and value sequences at dim=0.
|
| 42 |
+
add_zero_attn: add a new batch of zeros to the key and
|
| 43 |
+
value sequences at dim=1.
|
| 44 |
+
kdim: total number of features in key. Default: None.
|
| 45 |
+
vdim: total number of features in value. Default: None.
|
| 46 |
+
batch_first: If ``True``, then the input and output tensors are provided
|
| 47 |
+
as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
|
| 48 |
+
|
| 49 |
+
Note that if :attr:`kdim` and :attr:`vdim` are None, they will be set
|
| 50 |
+
to :attr:`embed_dim` such that query, key, and value have the same
|
| 51 |
+
number of features.
|
| 52 |
+
|
| 53 |
+
Examples::
|
| 54 |
+
|
| 55 |
+
>>> import torch.ao.nn.quantizable as nnqa
|
| 56 |
+
>>> multihead_attn = nnqa.MultiheadAttention(embed_dim, num_heads)
|
| 57 |
+
>>> attn_output, attn_output_weights = multihead_attn(query, key, value)
|
| 58 |
+
|
| 59 |
+
Note::
|
| 60 |
+
Please, follow the quantization flow to convert the quantizable MHA.
|
| 61 |
+
"""
|
| 62 |
+
__constants__ = ['batch_first']
|
| 63 |
+
|
| 64 |
+
def __init__(self, embed_dim: int, num_heads: int,
|
| 65 |
+
dropout: float = 0., bias: bool = True,
|
| 66 |
+
add_bias_kv: bool = False, add_zero_attn: bool = False,
|
| 67 |
+
kdim: Optional[int] = None, vdim: Optional[int] = None, batch_first: bool = False,
|
| 68 |
+
device=None, dtype=None) -> None:
|
| 69 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 70 |
+
super().__init__(embed_dim, num_heads, dropout,
|
| 71 |
+
bias, add_bias_kv,
|
| 72 |
+
add_zero_attn, kdim, vdim, batch_first,
|
| 73 |
+
**factory_kwargs)
|
| 74 |
+
self.linear_Q = nn.Linear(self.embed_dim, self.embed_dim, bias=bias, **factory_kwargs)
|
| 75 |
+
self.linear_K = nn.Linear(self.kdim, self.embed_dim, bias=bias, **factory_kwargs)
|
| 76 |
+
self.linear_V = nn.Linear(self.vdim, self.embed_dim, bias=bias, **factory_kwargs)
|
| 77 |
+
# for the type: ignore, see https://github.com/pytorch/pytorch/issues/58969
|
| 78 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=bias, **factory_kwargs) # type: ignore[assignment]
|
| 79 |
+
|
| 80 |
+
# Functionals
|
| 81 |
+
self.q_scaling_product = torch.ao.nn.quantized.FloatFunctional()
|
| 82 |
+
# note: importing torch.ao.nn.quantized at top creates a circular import
|
| 83 |
+
|
| 84 |
+
# Quant/Dequant
|
| 85 |
+
self.quant_attn_output = torch.ao.quantization.QuantStub()
|
| 86 |
+
self.quant_attn_output_weights = torch.ao.quantization.QuantStub()
|
| 87 |
+
self.dequant_q = torch.ao.quantization.DeQuantStub()
|
| 88 |
+
self.dequant_k = torch.ao.quantization.DeQuantStub()
|
| 89 |
+
self.dequant_v = torch.ao.quantization.DeQuantStub()
|
| 90 |
+
|
| 91 |
+
def _get_name(self):
|
| 92 |
+
return 'QuantizableMultiheadAttention'
|
| 93 |
+
|
| 94 |
+
@classmethod
|
| 95 |
+
def from_float(cls, other):
|
| 96 |
+
assert type(other) == cls._FLOAT_MODULE
|
| 97 |
+
assert hasattr(other, 'qconfig'), "The float module must have 'qconfig'"
|
| 98 |
+
# Setting the dropout to 0.0!
|
| 99 |
+
observed = cls(other.embed_dim, other.num_heads, other.dropout,
|
| 100 |
+
(other.in_proj_bias is not None),
|
| 101 |
+
(other.bias_k is not None),
|
| 102 |
+
other.add_zero_attn, other.kdim, other.vdim,
|
| 103 |
+
other.batch_first)
|
| 104 |
+
observed.bias_k = other.bias_k
|
| 105 |
+
observed.bias_v = other.bias_v
|
| 106 |
+
observed.qconfig = other.qconfig
|
| 107 |
+
|
| 108 |
+
# Set the linear weights
|
| 109 |
+
# for the type: ignores, see https://github.com/pytorch/pytorch/issues/58969
|
| 110 |
+
observed.out_proj.weight = other.out_proj.weight # type: ignore[has-type]
|
| 111 |
+
observed.out_proj.bias = other.out_proj.bias # type: ignore[has-type]
|
| 112 |
+
if other._qkv_same_embed_dim:
|
| 113 |
+
# Use separate params
|
| 114 |
+
bias = other.in_proj_bias
|
| 115 |
+
_start = 0
|
| 116 |
+
_end = _start + other.embed_dim
|
| 117 |
+
weight = other.in_proj_weight[_start:_end, :]
|
| 118 |
+
if bias is not None:
|
| 119 |
+
bias = torch.nn.Parameter(bias[_start:_end], bias.requires_grad)
|
| 120 |
+
observed.linear_Q.weight = torch.nn.Parameter(weight,
|
| 121 |
+
weight.requires_grad)
|
| 122 |
+
observed.linear_Q.bias = bias
|
| 123 |
+
|
| 124 |
+
bias = other.in_proj_bias
|
| 125 |
+
_start = _end
|
| 126 |
+
_end = _start + other.embed_dim
|
| 127 |
+
weight = other.in_proj_weight[_start:_end, :]
|
| 128 |
+
if bias is not None:
|
| 129 |
+
bias = torch.nn.Parameter(bias[_start:_end], bias.requires_grad)
|
| 130 |
+
observed.linear_K.weight = torch.nn.Parameter(weight,
|
| 131 |
+
weight.requires_grad)
|
| 132 |
+
observed.linear_K.bias = bias
|
| 133 |
+
|
| 134 |
+
bias = other.in_proj_bias
|
| 135 |
+
_start = _end
|
| 136 |
+
weight = other.in_proj_weight[_start:, :]
|
| 137 |
+
if bias is not None:
|
| 138 |
+
bias = torch.nn.Parameter(bias[_start:], bias.requires_grad)
|
| 139 |
+
observed.linear_V.weight = torch.nn.Parameter(weight,
|
| 140 |
+
weight.requires_grad)
|
| 141 |
+
observed.linear_V.bias = bias
|
| 142 |
+
else:
|
| 143 |
+
observed.linear_Q.weight = nn.Parameter(other.q_proj_weight)
|
| 144 |
+
observed.linear_K.weight = nn.Parameter(other.k_proj_weight)
|
| 145 |
+
observed.linear_V.weight = nn.Parameter(other.v_proj_weight)
|
| 146 |
+
if other.in_proj_bias is None:
|
| 147 |
+
observed.linear_Q.bias = None # type: ignore[assignment]
|
| 148 |
+
observed.linear_K.bias = None # type: ignore[assignment]
|
| 149 |
+
observed.linear_V.bias = None # type: ignore[assignment]
|
| 150 |
+
else:
|
| 151 |
+
observed.linear_Q.bias = nn.Parameter(other.in_proj_bias[0:other.embed_dim])
|
| 152 |
+
observed.linear_K.bias = nn.Parameter(other.in_proj_bias[other.embed_dim:(other.embed_dim * 2)])
|
| 153 |
+
observed.linear_V.bias = nn.Parameter(other.in_proj_bias[(other.embed_dim * 2):])
|
| 154 |
+
observed.eval()
|
| 155 |
+
# Explicit prepare
|
| 156 |
+
observed = torch.ao.quantization.prepare(observed, inplace=True)
|
| 157 |
+
return observed
|
| 158 |
+
|
| 159 |
+
@torch.jit.unused
|
| 160 |
+
def dequantize(self):
|
| 161 |
+
r"""Utility to convert the quantized MHA back to float.
|
| 162 |
+
|
| 163 |
+
The motivation for this is that it is not trivial to conver the weights
|
| 164 |
+
from the format that is used in the quantized version back to the
|
| 165 |
+
float.
|
| 166 |
+
"""
|
| 167 |
+
fp = self._FLOAT_MODULE(self.embed_dim, self.num_heads, self.dropout,
|
| 168 |
+
(self.linear_Q._weight_bias()[1] is not None),
|
| 169 |
+
(self.bias_k is not None),
|
| 170 |
+
self.add_zero_attn, self.kdim, self.vdim, self.batch_first)
|
| 171 |
+
assert fp._qkv_same_embed_dim == self._qkv_same_embed_dim
|
| 172 |
+
if self.bias_k is not None:
|
| 173 |
+
fp.bias_k = nn.Parameter(self.bias_k.dequantize())
|
| 174 |
+
if self.bias_v is not None:
|
| 175 |
+
fp.bias_v = nn.Parameter(self.bias_v.dequantize())
|
| 176 |
+
|
| 177 |
+
# Set the linear weights
|
| 178 |
+
# Note: Because the linear layers are quantized, mypy does not nkow how
|
| 179 |
+
# to deal with them -- might need to ignore the typing checks.
|
| 180 |
+
# for the type: ignore[has-type], see https://github.com/pytorch/pytorch/issues/58969
|
| 181 |
+
w, b = self.out_proj._weight_bias() # type: ignore[operator, has-type]
|
| 182 |
+
fp.out_proj.weight = nn.Parameter(w.dequantize())
|
| 183 |
+
if b is not None:
|
| 184 |
+
fp.out_proj.bias = nn.Parameter(b)
|
| 185 |
+
|
| 186 |
+
wQ, bQ = self.linear_Q._weight_bias() # type: ignore[operator]
|
| 187 |
+
wQ = wQ.dequantize()
|
| 188 |
+
wK, bK = self.linear_K._weight_bias() # type: ignore[operator]
|
| 189 |
+
wK = wK.dequantize()
|
| 190 |
+
wV, bV = self.linear_V._weight_bias() # type: ignore[operator]
|
| 191 |
+
wV = wV.dequantize()
|
| 192 |
+
if fp._qkv_same_embed_dim:
|
| 193 |
+
# Use separate params
|
| 194 |
+
_start = 0
|
| 195 |
+
_end = _start + fp.embed_dim
|
| 196 |
+
fp.in_proj_weight[_start:_end, :] = wQ
|
| 197 |
+
if fp.in_proj_bias is not None:
|
| 198 |
+
assert all(bQ == 0)
|
| 199 |
+
fp.in_proj_bias[_start:_end] = bQ
|
| 200 |
+
|
| 201 |
+
_start = _end
|
| 202 |
+
_end = _start + fp.embed_dim
|
| 203 |
+
fp.in_proj_weight[_start:_end, :] = wK
|
| 204 |
+
if fp.in_proj_bias is not None:
|
| 205 |
+
assert all(bK == 0)
|
| 206 |
+
fp.in_proj_bias[_start:_end] = bK
|
| 207 |
+
|
| 208 |
+
_start = _end
|
| 209 |
+
fp.in_proj_weight[_start:, :] = wV
|
| 210 |
+
if fp.in_proj_bias is not None:
|
| 211 |
+
assert all(bV == 0)
|
| 212 |
+
fp.in_proj_bias[_start:] = bV
|
| 213 |
+
else:
|
| 214 |
+
fp.q_proj_weight = nn.Parameter(wQ)
|
| 215 |
+
fp.k_proj_weight = nn.Parameter(wK)
|
| 216 |
+
fp.v_proj_weight = nn.Parameter(wV)
|
| 217 |
+
if fp.in_proj_bias is None:
|
| 218 |
+
self.linear_Q.bias = None
|
| 219 |
+
self.linear_K.bias = None
|
| 220 |
+
self.linear_V.bias = None
|
| 221 |
+
else:
|
| 222 |
+
fp.in_proj_bias[0:fp.embed_dim] = bQ
|
| 223 |
+
fp.in_proj_bias[fp.embed_dim:(fp.embed_dim * 2)] = bK
|
| 224 |
+
fp.in_proj_bias[(fp.embed_dim * 2):] = bV
|
| 225 |
+
|
| 226 |
+
return fp
|
| 227 |
+
|
| 228 |
+
@classmethod
|
| 229 |
+
def from_observed(cls, other):
|
| 230 |
+
# The whole flow is float -> observed -> quantized
|
| 231 |
+
# This class does float -> observed only
|
| 232 |
+
# See nn.quantized.MultiheadAttention
|
| 233 |
+
raise NotImplementedError("It looks like you are trying to prepare an "
|
| 234 |
+
"MHA module. Please, see "
|
| 235 |
+
"the examples on quantizable MHAs.")
|
| 236 |
+
|
| 237 |
+
def forward(self,
|
| 238 |
+
query: Tensor,
|
| 239 |
+
key: Tensor,
|
| 240 |
+
value: Tensor,
|
| 241 |
+
key_padding_mask: Optional[Tensor] = None,
|
| 242 |
+
need_weights: bool = True,
|
| 243 |
+
attn_mask: Optional[Tensor] = None,
|
| 244 |
+
average_attn_weights: bool = True,
|
| 245 |
+
is_causal: bool = False) -> Tuple[Tensor, Optional[Tensor]]:
|
| 246 |
+
r"""
|
| 247 |
+
Note::
|
| 248 |
+
Please, refer to :func:`~torch.nn.MultiheadAttention.forward` for more
|
| 249 |
+
information
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
query, key, value: map a query and a set of key-value pairs to an output.
|
| 253 |
+
See "Attention Is All You Need" for more details.
|
| 254 |
+
key_padding_mask: if provided, specified padding elements in the key will
|
| 255 |
+
be ignored by the attention. When given a binary mask and a value is True,
|
| 256 |
+
the corresponding value on the attention layer will be ignored.
|
| 257 |
+
need_weights: output attn_output_weights.
|
| 258 |
+
attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
|
| 259 |
+
the batches while a 3D mask allows to specify a different mask for the entries of each batch.
|
| 260 |
+
|
| 261 |
+
Shape:
|
| 262 |
+
- Inputs:
|
| 263 |
+
- query: :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
|
| 264 |
+
the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``.
|
| 265 |
+
- key: :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
|
| 266 |
+
the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``.
|
| 267 |
+
- value: :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
|
| 268 |
+
the embedding dimension. :math:`(N, S, E)` if ``batch_first`` is ``True``.
|
| 269 |
+
- key_padding_mask: :math:`(N, S)` where N is the batch size, S is the source sequence length.
|
| 270 |
+
If a BoolTensor is provided, the positions with the
|
| 271 |
+
value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
|
| 272 |
+
- attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
|
| 273 |
+
3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
|
| 274 |
+
S is the source sequence length. attn_mask ensure that position i is allowed to attend the unmasked
|
| 275 |
+
positions. If a BoolTensor is provided, positions with ``True``
|
| 276 |
+
is not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
|
| 277 |
+
is provided, it will be added to the attention weight.
|
| 278 |
+
- is_causal: If specified, applies a causal mask as attention mask. Mutually exclusive with providing attn_mask.
|
| 279 |
+
Default: ``False``.
|
| 280 |
+
- average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across
|
| 281 |
+
heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an
|
| 282 |
+
effect when ``need_weights=True.``. Default: True (i.e. average weights across heads)
|
| 283 |
+
|
| 284 |
+
- Outputs:
|
| 285 |
+
- attn_output: :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
|
| 286 |
+
E is the embedding dimension. :math:`(N, L, E)` if ``batch_first`` is ``True``.
|
| 287 |
+
- attn_output_weights: If ``average_attn_weights=True``, returns attention weights averaged
|
| 288 |
+
across heads of shape :math:`(N, L, S)`, where N is the batch size, L is the target sequence length,
|
| 289 |
+
S is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
|
| 290 |
+
head of shape :math:`(N, num_heads, L, S)`.
|
| 291 |
+
"""
|
| 292 |
+
return self._forward_impl(query, key, value, key_padding_mask,
|
| 293 |
+
need_weights, attn_mask, average_attn_weights,
|
| 294 |
+
is_causal)
|
| 295 |
+
|
| 296 |
+
def _forward_impl(self,
|
| 297 |
+
query: Tensor,
|
| 298 |
+
key: Tensor,
|
| 299 |
+
value: Tensor,
|
| 300 |
+
key_padding_mask: Optional[Tensor] = None,
|
| 301 |
+
need_weights: bool = True,
|
| 302 |
+
attn_mask: Optional[Tensor] = None,
|
| 303 |
+
average_attn_weights: bool = True,
|
| 304 |
+
is_causal: bool = False) -> Tuple[Tensor, Optional[Tensor]]:
|
| 305 |
+
# This version will not deal with the static key/value pairs.
|
| 306 |
+
# Keeping it here for future changes.
|
| 307 |
+
#
|
| 308 |
+
# TODO: This method has some duplicate lines with the
|
| 309 |
+
# `torch.nn.functional.multi_head_attention`. Will need to refactor.
|
| 310 |
+
static_k = None
|
| 311 |
+
static_v = None
|
| 312 |
+
|
| 313 |
+
if attn_mask is not None and is_causal:
|
| 314 |
+
raise AssertionError("Only allow causal mask or attn_mask")
|
| 315 |
+
|
| 316 |
+
if is_causal:
|
| 317 |
+
raise AssertionError("causal mask not supported by AO MHA module")
|
| 318 |
+
|
| 319 |
+
if self.batch_first:
|
| 320 |
+
query, key, value = (x.transpose(0, 1) for x in (query, key, value))
|
| 321 |
+
|
| 322 |
+
tgt_len, bsz, embed_dim_to_check = query.size()
|
| 323 |
+
assert self.embed_dim == embed_dim_to_check
|
| 324 |
+
# allow MHA to have different sizes for the feature dimension
|
| 325 |
+
assert key.size(0) == value.size(0) and key.size(1) == value.size(1)
|
| 326 |
+
|
| 327 |
+
head_dim = self.embed_dim // self.num_heads
|
| 328 |
+
assert head_dim * self.num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
|
| 329 |
+
scaling = float(head_dim) ** -0.5
|
| 330 |
+
|
| 331 |
+
q = self.linear_Q(query)
|
| 332 |
+
k = self.linear_K(key)
|
| 333 |
+
v = self.linear_V(value)
|
| 334 |
+
|
| 335 |
+
q = self.q_scaling_product.mul_scalar(q, scaling)
|
| 336 |
+
|
| 337 |
+
if attn_mask is not None:
|
| 338 |
+
if attn_mask.dtype == torch.uint8:
|
| 339 |
+
warnings.warn(
|
| 340 |
+
"Byte tensor for `attn_mask` in `nn.MultiheadAttention` is deprecated. "
|
| 341 |
+
"Use bool tensor instead.",
|
| 342 |
+
stacklevel=3,
|
| 343 |
+
)
|
| 344 |
+
attn_mask = attn_mask.to(torch.bool)
|
| 345 |
+
assert attn_mask.is_floating_point() or attn_mask.dtype == torch.bool, \
|
| 346 |
+
f'Only float and bool types are supported for attn_mask, not {attn_mask.dtype}'
|
| 347 |
+
|
| 348 |
+
if attn_mask.dim() == 2:
|
| 349 |
+
attn_mask = attn_mask.unsqueeze(0)
|
| 350 |
+
if list(attn_mask.size()) != [1, query.size(0), key.size(0)]:
|
| 351 |
+
raise RuntimeError('The size of the 2D attn_mask is not correct.')
|
| 352 |
+
elif attn_mask.dim() == 3:
|
| 353 |
+
if list(attn_mask.size()) != [bsz * self.num_heads, query.size(0), key.size(0)]:
|
| 354 |
+
raise RuntimeError('The size of the 3D attn_mask is not correct.')
|
| 355 |
+
else:
|
| 356 |
+
raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
|
| 357 |
+
# attn_mask's dim is 3 now.
|
| 358 |
+
|
| 359 |
+
# convert ByteTensor key_padding_mask to bool
|
| 360 |
+
if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8:
|
| 361 |
+
warnings.warn(
|
| 362 |
+
"Byte tensor for `key_padding_mask` in `nn.MultiheadAttention` is deprecated. "
|
| 363 |
+
"Use bool tensor instead.",
|
| 364 |
+
stacklevel=3,
|
| 365 |
+
)
|
| 366 |
+
key_padding_mask = key_padding_mask.to(torch.bool)
|
| 367 |
+
if self.bias_k is not None and self.bias_v is not None:
|
| 368 |
+
if static_k is None and static_v is None:
|
| 369 |
+
|
| 370 |
+
# Explicitly assert that bias_k and bias_v are not None
|
| 371 |
+
# in a way that TorchScript can understand.
|
| 372 |
+
bias_k = self.bias_k
|
| 373 |
+
assert bias_k is not None
|
| 374 |
+
bias_v = self.bias_v
|
| 375 |
+
assert bias_v is not None
|
| 376 |
+
|
| 377 |
+
k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
|
| 378 |
+
v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
|
| 379 |
+
if attn_mask is not None:
|
| 380 |
+
attn_mask = nnF.pad(attn_mask, (0, 1))
|
| 381 |
+
if key_padding_mask is not None:
|
| 382 |
+
key_padding_mask = nnF.pad(key_padding_mask, (0, 1))
|
| 383 |
+
else:
|
| 384 |
+
assert static_k is None, "bias cannot be added to static key."
|
| 385 |
+
assert static_v is None, "bias cannot be added to static value."
|
| 386 |
+
else:
|
| 387 |
+
assert self.bias_k is None
|
| 388 |
+
assert self.bias_v is None
|
| 389 |
+
|
| 390 |
+
q = q.contiguous().view(tgt_len, bsz * self.num_heads, head_dim).transpose(0, 1)
|
| 391 |
+
if k is not None:
|
| 392 |
+
k = k.contiguous().view(-1, bsz * self.num_heads, head_dim).transpose(0, 1)
|
| 393 |
+
if v is not None:
|
| 394 |
+
v = v.contiguous().view(-1, bsz * self.num_heads, head_dim).transpose(0, 1)
|
| 395 |
+
|
| 396 |
+
if static_k is not None:
|
| 397 |
+
assert static_k.size(0) == bsz * self.num_heads
|
| 398 |
+
assert static_k.size(2) == head_dim
|
| 399 |
+
k = static_k
|
| 400 |
+
|
| 401 |
+
if static_v is not None:
|
| 402 |
+
assert static_v.size(0) == bsz * self.num_heads
|
| 403 |
+
assert static_v.size(2) == head_dim
|
| 404 |
+
v = static_v
|
| 405 |
+
|
| 406 |
+
src_len = k.size(1)
|
| 407 |
+
|
| 408 |
+
if key_padding_mask is not None:
|
| 409 |
+
assert key_padding_mask.size(0) == bsz
|
| 410 |
+
assert key_padding_mask.size(1) == src_len
|
| 411 |
+
|
| 412 |
+
if self.add_zero_attn:
|
| 413 |
+
src_len += 1
|
| 414 |
+
k_zeros = torch.zeros((k.size(0), 1) + k.size()[2:])
|
| 415 |
+
if k.is_quantized:
|
| 416 |
+
k_zeros = torch.quantize_per_tensor(k_zeros, k.q_scale(), k.q_zero_point(), k.dtype)
|
| 417 |
+
k = torch.cat([k, k_zeros], dim=1)
|
| 418 |
+
v_zeros = torch.zeros((v.size(0), 1) + k.size()[2:])
|
| 419 |
+
if v.is_quantized:
|
| 420 |
+
v_zeros = torch.quantize_per_tensor(v_zeros, v.q_scale(), v.q_zero_point(), v.dtype)
|
| 421 |
+
v = torch.cat([v, v_zeros], dim=1)
|
| 422 |
+
|
| 423 |
+
if attn_mask is not None:
|
| 424 |
+
attn_mask = nnF.pad(attn_mask, (0, 1))
|
| 425 |
+
if key_padding_mask is not None:
|
| 426 |
+
key_padding_mask = nnF.pad(key_padding_mask, (0, 1))
|
| 427 |
+
|
| 428 |
+
# Leaving the quantized zone here
|
| 429 |
+
q = self.dequant_q(q)
|
| 430 |
+
k = self.dequant_k(k)
|
| 431 |
+
v = self.dequant_v(v)
|
| 432 |
+
attn_output_weights = torch.bmm(q, k.transpose(1, 2))
|
| 433 |
+
assert list(attn_output_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]
|
| 434 |
+
|
| 435 |
+
if attn_mask is not None:
|
| 436 |
+
if attn_mask.dtype == torch.bool:
|
| 437 |
+
attn_output_weights.masked_fill_(attn_mask, float('-inf'))
|
| 438 |
+
else:
|
| 439 |
+
attn_output_weights += attn_mask
|
| 440 |
+
|
| 441 |
+
if key_padding_mask is not None:
|
| 442 |
+
attn_output_weights = attn_output_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 443 |
+
attn_output_weights = attn_output_weights.masked_fill(
|
| 444 |
+
key_padding_mask.unsqueeze(1).unsqueeze(2),
|
| 445 |
+
float('-inf'),
|
| 446 |
+
)
|
| 447 |
+
attn_output_weights = attn_output_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 448 |
+
|
| 449 |
+
attn_output_weights = nnF.softmax(
|
| 450 |
+
attn_output_weights, dim=-1)
|
| 451 |
+
attn_output_weights = nnF.dropout(attn_output_weights, p=self.dropout, training=self.training)
|
| 452 |
+
|
| 453 |
+
attn_output = torch.bmm(attn_output_weights, v)
|
| 454 |
+
assert list(attn_output.size()) == [bsz * self.num_heads, tgt_len, head_dim]
|
| 455 |
+
if self.batch_first:
|
| 456 |
+
attn_output = attn_output.view(bsz, tgt_len, self.embed_dim)
|
| 457 |
+
else:
|
| 458 |
+
attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, self.embed_dim)
|
| 459 |
+
|
| 460 |
+
# Reentering the quantized zone
|
| 461 |
+
attn_output = self.quant_attn_output(attn_output)
|
| 462 |
+
# for the type: ignore[has-type], see https://github.com/pytorch/pytorch/issues/58969
|
| 463 |
+
attn_output = self.out_proj(attn_output) # type: ignore[has-type]
|
| 464 |
+
attn_output_weights = self.quant_attn_output_weights(attn_output_weights)
|
| 465 |
+
|
| 466 |
+
if need_weights:
|
| 467 |
+
# average attention weights over heads
|
| 468 |
+
attn_output_weights = attn_output_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 469 |
+
if average_attn_weights:
|
| 470 |
+
attn_output_weights = attn_output_weights.mean(dim=1)
|
| 471 |
+
return attn_output, attn_output_weights
|
| 472 |
+
else:
|
| 473 |
+
return attn_output, None
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantizable/modules/rnn.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import numbers
|
| 3 |
+
from typing import Optional, Tuple
|
| 4 |
+
import warnings
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
We will recreate all the RNN modules as we require the modules to be decomposed
|
| 11 |
+
into its building blocks to be able to observe.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"LSTMCell",
|
| 16 |
+
"LSTM"
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
class LSTMCell(torch.nn.Module):
|
| 20 |
+
r"""A quantizable long short-term memory (LSTM) cell.
|
| 21 |
+
|
| 22 |
+
For the description and the argument types, please, refer to :class:`~torch.nn.LSTMCell`
|
| 23 |
+
|
| 24 |
+
Examples::
|
| 25 |
+
|
| 26 |
+
>>> import torch.ao.nn.quantizable as nnqa
|
| 27 |
+
>>> rnn = nnqa.LSTMCell(10, 20)
|
| 28 |
+
>>> input = torch.randn(6, 10)
|
| 29 |
+
>>> hx = torch.randn(3, 20)
|
| 30 |
+
>>> cx = torch.randn(3, 20)
|
| 31 |
+
>>> output = []
|
| 32 |
+
>>> for i in range(6):
|
| 33 |
+
... hx, cx = rnn(input[i], (hx, cx))
|
| 34 |
+
... output.append(hx)
|
| 35 |
+
"""
|
| 36 |
+
_FLOAT_MODULE = torch.nn.LSTMCell
|
| 37 |
+
|
| 38 |
+
def __init__(self, input_dim: int, hidden_dim: int, bias: bool = True,
|
| 39 |
+
device=None, dtype=None) -> None:
|
| 40 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 41 |
+
super().__init__()
|
| 42 |
+
self.input_size = input_dim
|
| 43 |
+
self.hidden_size = hidden_dim
|
| 44 |
+
self.bias = bias
|
| 45 |
+
|
| 46 |
+
self.igates = torch.nn.Linear(input_dim, 4 * hidden_dim, bias=bias, **factory_kwargs)
|
| 47 |
+
self.hgates = torch.nn.Linear(hidden_dim, 4 * hidden_dim, bias=bias, **factory_kwargs)
|
| 48 |
+
self.gates = torch.ao.nn.quantized.FloatFunctional()
|
| 49 |
+
|
| 50 |
+
self.input_gate = torch.nn.Sigmoid()
|
| 51 |
+
self.forget_gate = torch.nn.Sigmoid()
|
| 52 |
+
self.cell_gate = torch.nn.Tanh()
|
| 53 |
+
self.output_gate = torch.nn.Sigmoid()
|
| 54 |
+
|
| 55 |
+
self.fgate_cx = torch.ao.nn.quantized.FloatFunctional()
|
| 56 |
+
self.igate_cgate = torch.ao.nn.quantized.FloatFunctional()
|
| 57 |
+
self.fgate_cx_igate_cgate = torch.ao.nn.quantized.FloatFunctional()
|
| 58 |
+
|
| 59 |
+
self.ogate_cy = torch.ao.nn.quantized.FloatFunctional()
|
| 60 |
+
|
| 61 |
+
self.initial_hidden_state_qparams: Tuple[float, int] = (1.0, 0)
|
| 62 |
+
self.initial_cell_state_qparams: Tuple[float, int] = (1.0, 0)
|
| 63 |
+
self.hidden_state_dtype: torch.dtype = torch.quint8
|
| 64 |
+
self.cell_state_dtype: torch.dtype = torch.quint8
|
| 65 |
+
|
| 66 |
+
def forward(self, x: Tensor, hidden: Optional[Tuple[Tensor, Tensor]] = None) -> Tuple[Tensor, Tensor]:
|
| 67 |
+
if hidden is None or hidden[0] is None or hidden[1] is None:
|
| 68 |
+
hidden = self.initialize_hidden(x.shape[0], x.is_quantized)
|
| 69 |
+
hx, cx = hidden
|
| 70 |
+
|
| 71 |
+
igates = self.igates(x)
|
| 72 |
+
hgates = self.hgates(hx)
|
| 73 |
+
gates = self.gates.add(igates, hgates)
|
| 74 |
+
|
| 75 |
+
input_gate, forget_gate, cell_gate, out_gate = gates.chunk(4, 1)
|
| 76 |
+
|
| 77 |
+
input_gate = self.input_gate(input_gate)
|
| 78 |
+
forget_gate = self.forget_gate(forget_gate)
|
| 79 |
+
cell_gate = self.cell_gate(cell_gate)
|
| 80 |
+
out_gate = self.output_gate(out_gate)
|
| 81 |
+
|
| 82 |
+
fgate_cx = self.fgate_cx.mul(forget_gate, cx)
|
| 83 |
+
igate_cgate = self.igate_cgate.mul(input_gate, cell_gate)
|
| 84 |
+
fgate_cx_igate_cgate = self.fgate_cx_igate_cgate.add(fgate_cx, igate_cgate)
|
| 85 |
+
cy = fgate_cx_igate_cgate
|
| 86 |
+
|
| 87 |
+
# TODO: make this tanh a member of the module so its qparams can be configured
|
| 88 |
+
tanh_cy = torch.tanh(cy)
|
| 89 |
+
hy = self.ogate_cy.mul(out_gate, tanh_cy)
|
| 90 |
+
return hy, cy
|
| 91 |
+
|
| 92 |
+
def initialize_hidden(self, batch_size: int, is_quantized: bool = False) -> Tuple[Tensor, Tensor]:
|
| 93 |
+
h, c = torch.zeros((batch_size, self.hidden_size)), torch.zeros((batch_size, self.hidden_size))
|
| 94 |
+
if is_quantized:
|
| 95 |
+
(h_scale, h_zp) = self.initial_hidden_state_qparams
|
| 96 |
+
(c_scale, c_zp) = self.initial_cell_state_qparams
|
| 97 |
+
h = torch.quantize_per_tensor(h, scale=h_scale, zero_point=h_zp, dtype=self.hidden_state_dtype)
|
| 98 |
+
c = torch.quantize_per_tensor(c, scale=c_scale, zero_point=c_zp, dtype=self.cell_state_dtype)
|
| 99 |
+
return h, c
|
| 100 |
+
|
| 101 |
+
def _get_name(self):
|
| 102 |
+
return 'QuantizableLSTMCell'
|
| 103 |
+
|
| 104 |
+
@classmethod
|
| 105 |
+
def from_params(cls, wi, wh, bi=None, bh=None):
|
| 106 |
+
"""Uses the weights and biases to create a new LSTM cell.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
wi, wh: Weights for the input and hidden layers
|
| 110 |
+
bi, bh: Biases for the input and hidden layers
|
| 111 |
+
"""
|
| 112 |
+
assert (bi is None) == (bh is None) # Either both None or both have values
|
| 113 |
+
input_size = wi.shape[1]
|
| 114 |
+
hidden_size = wh.shape[1]
|
| 115 |
+
cell = cls(input_dim=input_size, hidden_dim=hidden_size,
|
| 116 |
+
bias=(bi is not None))
|
| 117 |
+
cell.igates.weight = torch.nn.Parameter(wi)
|
| 118 |
+
if bi is not None:
|
| 119 |
+
cell.igates.bias = torch.nn.Parameter(bi)
|
| 120 |
+
cell.hgates.weight = torch.nn.Parameter(wh)
|
| 121 |
+
if bh is not None:
|
| 122 |
+
cell.hgates.bias = torch.nn.Parameter(bh)
|
| 123 |
+
return cell
|
| 124 |
+
|
| 125 |
+
@classmethod
|
| 126 |
+
def from_float(cls, other, use_precomputed_fake_quant=False):
|
| 127 |
+
assert type(other) == cls._FLOAT_MODULE
|
| 128 |
+
assert hasattr(other, 'qconfig'), "The float module must have 'qconfig'"
|
| 129 |
+
observed = cls.from_params(other.weight_ih, other.weight_hh,
|
| 130 |
+
other.bias_ih, other.bias_hh)
|
| 131 |
+
observed.qconfig = other.qconfig
|
| 132 |
+
observed.igates.qconfig = other.qconfig
|
| 133 |
+
observed.hgates.qconfig = other.qconfig
|
| 134 |
+
return observed
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class _LSTMSingleLayer(torch.nn.Module):
|
| 138 |
+
r"""A single one-directional LSTM layer.
|
| 139 |
+
|
| 140 |
+
The difference between a layer and a cell is that the layer can process a
|
| 141 |
+
sequence, while the cell only expects an instantaneous value.
|
| 142 |
+
"""
|
| 143 |
+
def __init__(self, input_dim: int, hidden_dim: int, bias: bool = True,
|
| 144 |
+
device=None, dtype=None) -> None:
|
| 145 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 146 |
+
super().__init__()
|
| 147 |
+
self.cell = LSTMCell(input_dim, hidden_dim, bias=bias, **factory_kwargs)
|
| 148 |
+
|
| 149 |
+
def forward(self, x: Tensor, hidden: Optional[Tuple[Tensor, Tensor]] = None):
|
| 150 |
+
result = []
|
| 151 |
+
seq_len = x.shape[0]
|
| 152 |
+
for i in range(seq_len):
|
| 153 |
+
hidden = self.cell(x[i], hidden)
|
| 154 |
+
result.append(hidden[0]) # type: ignore[index]
|
| 155 |
+
result_tensor = torch.stack(result, 0)
|
| 156 |
+
return result_tensor, hidden
|
| 157 |
+
|
| 158 |
+
@classmethod
|
| 159 |
+
def from_params(cls, *args, **kwargs):
|
| 160 |
+
cell = LSTMCell.from_params(*args, **kwargs)
|
| 161 |
+
layer = cls(cell.input_size, cell.hidden_size, cell.bias)
|
| 162 |
+
layer.cell = cell
|
| 163 |
+
return layer
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class _LSTMLayer(torch.nn.Module):
|
| 167 |
+
r"""A single bi-directional LSTM layer."""
|
| 168 |
+
def __init__(self, input_dim: int, hidden_dim: int, bias: bool = True,
|
| 169 |
+
batch_first: bool = False, bidirectional: bool = False,
|
| 170 |
+
device=None, dtype=None) -> None:
|
| 171 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 172 |
+
super().__init__()
|
| 173 |
+
self.batch_first = batch_first
|
| 174 |
+
self.bidirectional = bidirectional
|
| 175 |
+
self.layer_fw = _LSTMSingleLayer(input_dim, hidden_dim, bias=bias, **factory_kwargs)
|
| 176 |
+
if self.bidirectional:
|
| 177 |
+
self.layer_bw = _LSTMSingleLayer(input_dim, hidden_dim, bias=bias, **factory_kwargs)
|
| 178 |
+
|
| 179 |
+
def forward(self, x: Tensor, hidden: Optional[Tuple[Tensor, Tensor]] = None):
|
| 180 |
+
if self.batch_first:
|
| 181 |
+
x = x.transpose(0, 1)
|
| 182 |
+
if hidden is None:
|
| 183 |
+
hx_fw, cx_fw = (None, None)
|
| 184 |
+
else:
|
| 185 |
+
hx_fw, cx_fw = hidden
|
| 186 |
+
hidden_bw: Optional[Tuple[Tensor, Tensor]] = None
|
| 187 |
+
if self.bidirectional:
|
| 188 |
+
if hx_fw is None:
|
| 189 |
+
hx_bw = None
|
| 190 |
+
else:
|
| 191 |
+
hx_bw = hx_fw[1]
|
| 192 |
+
hx_fw = hx_fw[0]
|
| 193 |
+
if cx_fw is None:
|
| 194 |
+
cx_bw = None
|
| 195 |
+
else:
|
| 196 |
+
cx_bw = cx_fw[1]
|
| 197 |
+
cx_fw = cx_fw[0]
|
| 198 |
+
if hx_bw is not None and cx_bw is not None:
|
| 199 |
+
hidden_bw = hx_bw, cx_bw
|
| 200 |
+
if hx_fw is None and cx_fw is None:
|
| 201 |
+
hidden_fw = None
|
| 202 |
+
else:
|
| 203 |
+
hidden_fw = torch.jit._unwrap_optional(hx_fw), torch.jit._unwrap_optional(cx_fw)
|
| 204 |
+
result_fw, hidden_fw = self.layer_fw(x, hidden_fw)
|
| 205 |
+
|
| 206 |
+
if hasattr(self, 'layer_bw') and self.bidirectional:
|
| 207 |
+
x_reversed = x.flip(0)
|
| 208 |
+
result_bw, hidden_bw = self.layer_bw(x_reversed, hidden_bw)
|
| 209 |
+
result_bw = result_bw.flip(0)
|
| 210 |
+
|
| 211 |
+
result = torch.cat([result_fw, result_bw], result_fw.dim() - 1)
|
| 212 |
+
if hidden_fw is None and hidden_bw is None:
|
| 213 |
+
h = None
|
| 214 |
+
c = None
|
| 215 |
+
elif hidden_fw is None:
|
| 216 |
+
(h, c) = torch.jit._unwrap_optional(hidden_bw)
|
| 217 |
+
elif hidden_bw is None:
|
| 218 |
+
(h, c) = torch.jit._unwrap_optional(hidden_fw)
|
| 219 |
+
else:
|
| 220 |
+
h = torch.stack([hidden_fw[0], hidden_bw[0]], 0) # type: ignore[list-item]
|
| 221 |
+
c = torch.stack([hidden_fw[1], hidden_bw[1]], 0) # type: ignore[list-item]
|
| 222 |
+
else:
|
| 223 |
+
result = result_fw
|
| 224 |
+
h, c = torch.jit._unwrap_optional(hidden_fw) # type: ignore[assignment]
|
| 225 |
+
|
| 226 |
+
if self.batch_first:
|
| 227 |
+
result.transpose_(0, 1)
|
| 228 |
+
|
| 229 |
+
return result, (h, c)
|
| 230 |
+
|
| 231 |
+
@classmethod
|
| 232 |
+
def from_float(cls, other, layer_idx=0, qconfig=None, **kwargs):
|
| 233 |
+
r"""
|
| 234 |
+
There is no FP equivalent of this class. This function is here just to
|
| 235 |
+
mimic the behavior of the `prepare` within the `torch.ao.quantization`
|
| 236 |
+
flow.
|
| 237 |
+
"""
|
| 238 |
+
assert hasattr(other, 'qconfig') or (qconfig is not None)
|
| 239 |
+
|
| 240 |
+
input_size = kwargs.get('input_size', other.input_size)
|
| 241 |
+
hidden_size = kwargs.get('hidden_size', other.hidden_size)
|
| 242 |
+
bias = kwargs.get('bias', other.bias)
|
| 243 |
+
batch_first = kwargs.get('batch_first', other.batch_first)
|
| 244 |
+
bidirectional = kwargs.get('bidirectional', other.bidirectional)
|
| 245 |
+
|
| 246 |
+
layer = cls(input_size, hidden_size, bias, batch_first, bidirectional)
|
| 247 |
+
layer.qconfig = getattr(other, 'qconfig', qconfig)
|
| 248 |
+
wi = getattr(other, f'weight_ih_l{layer_idx}')
|
| 249 |
+
wh = getattr(other, f'weight_hh_l{layer_idx}')
|
| 250 |
+
bi = getattr(other, f'bias_ih_l{layer_idx}', None)
|
| 251 |
+
bh = getattr(other, f'bias_hh_l{layer_idx}', None)
|
| 252 |
+
|
| 253 |
+
layer.layer_fw = _LSTMSingleLayer.from_params(wi, wh, bi, bh)
|
| 254 |
+
|
| 255 |
+
if other.bidirectional:
|
| 256 |
+
wi = getattr(other, f'weight_ih_l{layer_idx}_reverse')
|
| 257 |
+
wh = getattr(other, f'weight_hh_l{layer_idx}_reverse')
|
| 258 |
+
bi = getattr(other, f'bias_ih_l{layer_idx}_reverse', None)
|
| 259 |
+
bh = getattr(other, f'bias_hh_l{layer_idx}_reverse', None)
|
| 260 |
+
layer.layer_bw = _LSTMSingleLayer.from_params(wi, wh, bi, bh)
|
| 261 |
+
return layer
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class LSTM(torch.nn.Module):
|
| 265 |
+
r"""A quantizable long short-term memory (LSTM).
|
| 266 |
+
|
| 267 |
+
For the description and the argument types, please, refer to :class:`~torch.nn.LSTM`
|
| 268 |
+
|
| 269 |
+
Attributes:
|
| 270 |
+
layers : instances of the `_LSTMLayer`
|
| 271 |
+
|
| 272 |
+
.. note::
|
| 273 |
+
To access the weights and biases, you need to access them per layer.
|
| 274 |
+
See examples below.
|
| 275 |
+
|
| 276 |
+
Examples::
|
| 277 |
+
|
| 278 |
+
>>> import torch.ao.nn.quantizable as nnqa
|
| 279 |
+
>>> rnn = nnqa.LSTM(10, 20, 2)
|
| 280 |
+
>>> input = torch.randn(5, 3, 10)
|
| 281 |
+
>>> h0 = torch.randn(2, 3, 20)
|
| 282 |
+
>>> c0 = torch.randn(2, 3, 20)
|
| 283 |
+
>>> output, (hn, cn) = rnn(input, (h0, c0))
|
| 284 |
+
>>> # To get the weights:
|
| 285 |
+
>>> # xdoctest: +SKIP
|
| 286 |
+
>>> print(rnn.layers[0].weight_ih)
|
| 287 |
+
tensor([[...]])
|
| 288 |
+
>>> print(rnn.layers[0].weight_hh)
|
| 289 |
+
AssertionError: There is no reverse path in the non-bidirectional layer
|
| 290 |
+
"""
|
| 291 |
+
_FLOAT_MODULE = torch.nn.LSTM
|
| 292 |
+
|
| 293 |
+
def __init__(self, input_size: int, hidden_size: int,
|
| 294 |
+
num_layers: int = 1, bias: bool = True,
|
| 295 |
+
batch_first: bool = False, dropout: float = 0.,
|
| 296 |
+
bidirectional: bool = False,
|
| 297 |
+
device=None, dtype=None) -> None:
|
| 298 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 299 |
+
super().__init__()
|
| 300 |
+
self.input_size = input_size
|
| 301 |
+
self.hidden_size = hidden_size
|
| 302 |
+
self.num_layers = num_layers
|
| 303 |
+
self.bias = bias
|
| 304 |
+
self.batch_first = batch_first
|
| 305 |
+
self.dropout = float(dropout)
|
| 306 |
+
self.bidirectional = bidirectional
|
| 307 |
+
self.training = False # Default to eval mode. If we want to train, we will explicitly set to training.
|
| 308 |
+
num_directions = 2 if bidirectional else 1
|
| 309 |
+
|
| 310 |
+
if not isinstance(dropout, numbers.Number) or not 0 <= dropout <= 1 or \
|
| 311 |
+
isinstance(dropout, bool):
|
| 312 |
+
raise ValueError("dropout should be a number in range [0, 1] "
|
| 313 |
+
"representing the probability of an element being "
|
| 314 |
+
"zeroed")
|
| 315 |
+
if dropout > 0:
|
| 316 |
+
warnings.warn("dropout option for quantizable LSTM is ignored. "
|
| 317 |
+
"If you are training, please, use nn.LSTM version "
|
| 318 |
+
"followed by `prepare` step.")
|
| 319 |
+
if num_layers == 1:
|
| 320 |
+
warnings.warn("dropout option adds dropout after all but last "
|
| 321 |
+
"recurrent layer, so non-zero dropout expects "
|
| 322 |
+
f"num_layers greater than 1, but got dropout={dropout} "
|
| 323 |
+
f"and num_layers={num_layers}")
|
| 324 |
+
|
| 325 |
+
layers = [_LSTMLayer(self.input_size, self.hidden_size,
|
| 326 |
+
self.bias, batch_first=False,
|
| 327 |
+
bidirectional=self.bidirectional, **factory_kwargs)]
|
| 328 |
+
for layer in range(1, num_layers):
|
| 329 |
+
layers.append(_LSTMLayer(self.hidden_size, self.hidden_size,
|
| 330 |
+
self.bias, batch_first=False,
|
| 331 |
+
bidirectional=self.bidirectional,
|
| 332 |
+
**factory_kwargs))
|
| 333 |
+
self.layers = torch.nn.ModuleList(layers)
|
| 334 |
+
|
| 335 |
+
def forward(self, x: Tensor, hidden: Optional[Tuple[Tensor, Tensor]] = None):
|
| 336 |
+
if self.batch_first:
|
| 337 |
+
x = x.transpose(0, 1)
|
| 338 |
+
|
| 339 |
+
max_batch_size = x.size(1)
|
| 340 |
+
num_directions = 2 if self.bidirectional else 1
|
| 341 |
+
if hidden is None:
|
| 342 |
+
zeros = torch.zeros(num_directions, max_batch_size,
|
| 343 |
+
self.hidden_size, dtype=torch.float,
|
| 344 |
+
device=x.device)
|
| 345 |
+
zeros.squeeze_(0)
|
| 346 |
+
if x.is_quantized:
|
| 347 |
+
zeros = torch.quantize_per_tensor(zeros, scale=1.0,
|
| 348 |
+
zero_point=0, dtype=x.dtype)
|
| 349 |
+
hxcx = [(zeros, zeros) for _ in range(self.num_layers)]
|
| 350 |
+
else:
|
| 351 |
+
hidden_non_opt = torch.jit._unwrap_optional(hidden)
|
| 352 |
+
if isinstance(hidden_non_opt[0], Tensor):
|
| 353 |
+
hx = hidden_non_opt[0].reshape(self.num_layers, num_directions,
|
| 354 |
+
max_batch_size,
|
| 355 |
+
self.hidden_size)
|
| 356 |
+
cx = hidden_non_opt[1].reshape(self.num_layers, num_directions,
|
| 357 |
+
max_batch_size,
|
| 358 |
+
self.hidden_size)
|
| 359 |
+
hxcx = [(hx[idx].squeeze(0), cx[idx].squeeze(0)) for idx in range(self.num_layers)]
|
| 360 |
+
else:
|
| 361 |
+
hxcx = hidden_non_opt
|
| 362 |
+
|
| 363 |
+
hx_list = []
|
| 364 |
+
cx_list = []
|
| 365 |
+
for idx, layer in enumerate(self.layers):
|
| 366 |
+
x, (h, c) = layer(x, hxcx[idx])
|
| 367 |
+
hx_list.append(torch.jit._unwrap_optional(h))
|
| 368 |
+
cx_list.append(torch.jit._unwrap_optional(c))
|
| 369 |
+
hx_tensor = torch.stack(hx_list)
|
| 370 |
+
cx_tensor = torch.stack(cx_list)
|
| 371 |
+
|
| 372 |
+
# We are creating another dimension for bidirectional case
|
| 373 |
+
# need to collapse it
|
| 374 |
+
hx_tensor = hx_tensor.reshape(-1, hx_tensor.shape[-2], hx_tensor.shape[-1])
|
| 375 |
+
cx_tensor = cx_tensor.reshape(-1, cx_tensor.shape[-2], cx_tensor.shape[-1])
|
| 376 |
+
|
| 377 |
+
if self.batch_first:
|
| 378 |
+
x = x.transpose(0, 1)
|
| 379 |
+
|
| 380 |
+
return x, (hx_tensor, cx_tensor)
|
| 381 |
+
|
| 382 |
+
def _get_name(self):
|
| 383 |
+
return 'QuantizableLSTM'
|
| 384 |
+
|
| 385 |
+
@classmethod
|
| 386 |
+
def from_float(cls, other, qconfig=None):
|
| 387 |
+
assert isinstance(other, cls._FLOAT_MODULE)
|
| 388 |
+
assert (hasattr(other, 'qconfig') or qconfig)
|
| 389 |
+
observed = cls(other.input_size, other.hidden_size, other.num_layers,
|
| 390 |
+
other.bias, other.batch_first, other.dropout,
|
| 391 |
+
other.bidirectional)
|
| 392 |
+
observed.qconfig = getattr(other, 'qconfig', qconfig)
|
| 393 |
+
for idx in range(other.num_layers):
|
| 394 |
+
observed.layers[idx] = _LSTMLayer.from_float(other, idx, qconfig,
|
| 395 |
+
batch_first=False)
|
| 396 |
+
|
| 397 |
+
# Prepare the model
|
| 398 |
+
if other.training:
|
| 399 |
+
observed.train()
|
| 400 |
+
observed = torch.ao.quantization.prepare_qat(observed, inplace=True)
|
| 401 |
+
else:
|
| 402 |
+
observed.eval()
|
| 403 |
+
observed = torch.ao.quantization.prepare(observed, inplace=True)
|
| 404 |
+
return observed
|
| 405 |
+
|
| 406 |
+
@classmethod
|
| 407 |
+
def from_observed(cls, other):
|
| 408 |
+
# The whole flow is float -> observed -> quantized
|
| 409 |
+
# This class does float -> observed only
|
| 410 |
+
raise NotImplementedError("It looks like you are trying to convert a "
|
| 411 |
+
"non-quantizable LSTM module. Please, see "
|
| 412 |
+
"the examples on quantizable LSTMs.")
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantized/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import functional
|
| 2 |
+
from .modules import * # noqa: F403
|
| 3 |
+
from .modules import MaxPool2d
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
'BatchNorm2d',
|
| 7 |
+
'BatchNorm3d',
|
| 8 |
+
'Conv1d',
|
| 9 |
+
'Conv2d',
|
| 10 |
+
'Conv3d',
|
| 11 |
+
'ConvTranspose1d',
|
| 12 |
+
'ConvTranspose2d',
|
| 13 |
+
'ConvTranspose3d',
|
| 14 |
+
'DeQuantize',
|
| 15 |
+
'ELU',
|
| 16 |
+
'Embedding',
|
| 17 |
+
'EmbeddingBag',
|
| 18 |
+
'GroupNorm',
|
| 19 |
+
'Hardswish',
|
| 20 |
+
'InstanceNorm1d',
|
| 21 |
+
'InstanceNorm2d',
|
| 22 |
+
'InstanceNorm3d',
|
| 23 |
+
'LayerNorm',
|
| 24 |
+
'LeakyReLU',
|
| 25 |
+
'Linear',
|
| 26 |
+
'LSTM',
|
| 27 |
+
'MultiheadAttention',
|
| 28 |
+
'Quantize',
|
| 29 |
+
'ReLU6',
|
| 30 |
+
'Sigmoid',
|
| 31 |
+
'Softmax',
|
| 32 |
+
'Dropout',
|
| 33 |
+
'PReLU',
|
| 34 |
+
# Wrapper modules
|
| 35 |
+
'FloatFunctional',
|
| 36 |
+
'FXFloatFunctional',
|
| 37 |
+
'QFunctional',
|
| 38 |
+
]
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantized/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (659 Bytes). View file
|
|
|
pythonProject/.venv/Lib/site-packages/torch/ao/nn/quantized/__pycache__/functional.cpython-310.pyc
ADDED
|
Binary file (26 kB). View file
|
|
|