Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- vllm/lib/python3.10/site-packages/torch/ao/nn/__init__.py +22 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/__init__.py +39 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/functional.py +778 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__init__.py +162 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/activation.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/batchnorm.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/conv.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/dropout.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/functional_modules.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/linear.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/normalization.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/rnn.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/activation.py +343 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/batchnorm.py +128 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/dropout.py +30 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/embedding_ops.py +405 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/linear.py +358 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/utils.py +144 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/__init__.py +19 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/__init__.py +29 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/linear.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/conv.py +511 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/linear.py +68 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/rnn.py +845 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/sparse.py +162 -0
- vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/utils.py +431 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__init__.py +30 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/_common_operator_config_utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/_qnnpack_pt2e.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/backend_config.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/executorch.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/fbgemm.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/native.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/observation_type.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/onednn.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/qnnpack.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/tensorrt.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/x86.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_common_operator_config_utils.py +795 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_qnnpack_pt2e.py +182 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/backend_config.py +749 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/executorch.py +500 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/fbgemm.py +129 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/native.py +231 -0
- vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/observation_type.py +0 -0
vllm/lib/python3.10/site-packages/torch/ao/nn/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
# We are exposing all subpackages to the end-user.
|
| 3 |
+
# Because of possible inter-dependency, we want to avoid
|
| 4 |
+
# the cyclic imports, thus implementing lazy version
|
| 5 |
+
# as per https://peps.python.org/pep-0562/
|
| 6 |
+
|
| 7 |
+
import importlib
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"intrinsic",
|
| 12 |
+
"qat",
|
| 13 |
+
"quantizable",
|
| 14 |
+
"quantized",
|
| 15 |
+
"sparse",
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def __getattr__(name):
|
| 20 |
+
if name in __all__:
|
| 21 |
+
return importlib.import_module("." + name, __name__)
|
| 22 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import functional
|
| 2 |
+
from .modules import * # noqa: F403
|
| 3 |
+
from .modules import MaxPool2d
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
"BatchNorm2d",
|
| 8 |
+
"BatchNorm3d",
|
| 9 |
+
"Conv1d",
|
| 10 |
+
"Conv2d",
|
| 11 |
+
"Conv3d",
|
| 12 |
+
"ConvTranspose1d",
|
| 13 |
+
"ConvTranspose2d",
|
| 14 |
+
"ConvTranspose3d",
|
| 15 |
+
"DeQuantize",
|
| 16 |
+
"ELU",
|
| 17 |
+
"Embedding",
|
| 18 |
+
"EmbeddingBag",
|
| 19 |
+
"GroupNorm",
|
| 20 |
+
"Hardswish",
|
| 21 |
+
"InstanceNorm1d",
|
| 22 |
+
"InstanceNorm2d",
|
| 23 |
+
"InstanceNorm3d",
|
| 24 |
+
"LayerNorm",
|
| 25 |
+
"LeakyReLU",
|
| 26 |
+
"Linear",
|
| 27 |
+
"LSTM",
|
| 28 |
+
"MultiheadAttention",
|
| 29 |
+
"Quantize",
|
| 30 |
+
"ReLU6",
|
| 31 |
+
"Sigmoid",
|
| 32 |
+
"Softmax",
|
| 33 |
+
"Dropout",
|
| 34 |
+
"PReLU",
|
| 35 |
+
# Wrapper modules
|
| 36 |
+
"FloatFunctional",
|
| 37 |
+
"FXFloatFunctional",
|
| 38 |
+
"QFunctional",
|
| 39 |
+
]
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/functional.py
ADDED
|
@@ -0,0 +1,778 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
r""" Functional interface (quantized)."""
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import List, Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
from torch.jit.annotations import BroadcastingList2
|
| 9 |
+
from torch.nn.modules.utils import _pair, _triple
|
| 10 |
+
|
| 11 |
+
from .modules.utils import _pair_from_first
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# Although some of the functions and docstrings are mirrored from the torch.nn,
|
| 15 |
+
# we want to have them here for future changes.
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"avg_pool2d",
|
| 19 |
+
"avg_pool3d",
|
| 20 |
+
"adaptive_avg_pool2d",
|
| 21 |
+
"adaptive_avg_pool3d",
|
| 22 |
+
"conv1d",
|
| 23 |
+
"conv2d",
|
| 24 |
+
"conv3d",
|
| 25 |
+
"interpolate",
|
| 26 |
+
"linear",
|
| 27 |
+
"max_pool1d",
|
| 28 |
+
"max_pool2d",
|
| 29 |
+
"celu",
|
| 30 |
+
"leaky_relu",
|
| 31 |
+
"hardtanh",
|
| 32 |
+
"hardswish",
|
| 33 |
+
"threshold",
|
| 34 |
+
"elu",
|
| 35 |
+
"hardsigmoid",
|
| 36 |
+
"clamp",
|
| 37 |
+
"upsample",
|
| 38 |
+
"upsample_bilinear",
|
| 39 |
+
"upsample_nearest",
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def avg_pool2d(
|
| 44 |
+
input,
|
| 45 |
+
kernel_size,
|
| 46 |
+
stride=None,
|
| 47 |
+
padding=0,
|
| 48 |
+
ceil_mode=False,
|
| 49 |
+
count_include_pad=True,
|
| 50 |
+
divisor_override=None,
|
| 51 |
+
):
|
| 52 |
+
r"""
|
| 53 |
+
Applies 2D average-pooling operation in :math:`kH \times kW` regions by step size
|
| 54 |
+
:math:`sH \times sW` steps. The number of output features is equal to the number of
|
| 55 |
+
input planes.
|
| 56 |
+
|
| 57 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 58 |
+
|
| 59 |
+
See :class:`~torch.ao.nn.quantized.AvgPool2d` for details and output shape.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
input: quantized input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
|
| 63 |
+
kernel_size: size of the pooling region. Can be a single number or a
|
| 64 |
+
tuple `(kH, kW)`
|
| 65 |
+
stride: stride of the pooling operation. Can be a single number or a
|
| 66 |
+
tuple `(sH, sW)`. Default: :attr:`kernel_size`
|
| 67 |
+
padding: implicit zero paddings on both sides of the input. Can be a
|
| 68 |
+
single number or a tuple `(padH, padW)`. Default: 0
|
| 69 |
+
ceil_mode: when True, will use `ceil` instead of `floor` in the formula
|
| 70 |
+
to compute the output shape. Default: ``False``
|
| 71 |
+
count_include_pad: when True, will include the zero-padding in the
|
| 72 |
+
averaging calculation. Default: ``True``
|
| 73 |
+
divisor_override: if specified, it will be used as divisor, otherwise
|
| 74 |
+
size of the pooling region will be used. Default: None
|
| 75 |
+
"""
|
| 76 |
+
if not input.is_quantized:
|
| 77 |
+
raise ValueError("Input to 'quantized.avg_pool2d' must be quantized!")
|
| 78 |
+
return torch.nn.functional.avg_pool2d(
|
| 79 |
+
input,
|
| 80 |
+
kernel_size,
|
| 81 |
+
stride,
|
| 82 |
+
padding,
|
| 83 |
+
ceil_mode,
|
| 84 |
+
count_include_pad,
|
| 85 |
+
divisor_override,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def avg_pool3d(
|
| 90 |
+
input,
|
| 91 |
+
kernel_size,
|
| 92 |
+
stride=None,
|
| 93 |
+
padding=0,
|
| 94 |
+
ceil_mode=False,
|
| 95 |
+
count_include_pad=True,
|
| 96 |
+
divisor_override=None,
|
| 97 |
+
):
|
| 98 |
+
r"""
|
| 99 |
+
Applies 3D average-pooling operation in :math:`kD \ times kH \times kW` regions by step size
|
| 100 |
+
:math:`sD \times sH \times sW` steps. The number of output features is equal to the number of
|
| 101 |
+
input planes.
|
| 102 |
+
|
| 103 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
input: quantized input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
|
| 107 |
+
kernel_size: size of the pooling region. Can be a single number or a
|
| 108 |
+
tuple `(kD, kH, kW)`
|
| 109 |
+
stride: stride of the pooling operation. Can be a single number or a
|
| 110 |
+
tuple `(sD, sH, sW)`. Default: :attr:`kernel_size`
|
| 111 |
+
padding: implicit zero paddings on both sides of the input. Can be a
|
| 112 |
+
single number or a tuple `(padD, padH, padW)`. Default: 0
|
| 113 |
+
ceil_mode: when True, will use `ceil` instead of `floor` in the formula
|
| 114 |
+
to compute the output shape. Default: ``False``
|
| 115 |
+
count_include_pad: when True, will include the zero-padding in the
|
| 116 |
+
averaging calculation. Default: ``True``
|
| 117 |
+
divisor_override: if specified, it will be used as divisor, otherwise
|
| 118 |
+
size of the pooling region will be used. Default: None
|
| 119 |
+
"""
|
| 120 |
+
if not input.is_quantized:
|
| 121 |
+
raise ValueError("Input to 'quantized.avg_pool3d' must be quantized!")
|
| 122 |
+
return torch.nn.functional.avg_pool3d(
|
| 123 |
+
input,
|
| 124 |
+
kernel_size,
|
| 125 |
+
stride,
|
| 126 |
+
padding,
|
| 127 |
+
ceil_mode,
|
| 128 |
+
count_include_pad,
|
| 129 |
+
divisor_override,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def adaptive_avg_pool2d(input: Tensor, output_size: BroadcastingList2[int]) -> Tensor:
|
| 134 |
+
r"""
|
| 135 |
+
Applies a 2D adaptive average pooling over a quantized input signal composed
|
| 136 |
+
of several quantized input planes.
|
| 137 |
+
|
| 138 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 139 |
+
|
| 140 |
+
See :class:`~torch.ao.nn.quantized.AdaptiveAvgPool2d` for details and output shape.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
output_size: the target output size (single integer or
|
| 144 |
+
double-integer tuple)
|
| 145 |
+
"""
|
| 146 |
+
if not input.is_quantized:
|
| 147 |
+
raise ValueError(
|
| 148 |
+
"Input to 'quantized.functional.adaptive_avg_pool2d' must be quantized!"
|
| 149 |
+
)
|
| 150 |
+
return torch.nn.functional.adaptive_avg_pool2d(input, output_size)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def adaptive_avg_pool3d(input: Tensor, output_size: BroadcastingList2[int]) -> Tensor:
|
| 154 |
+
r"""
|
| 155 |
+
Applies a 3D adaptive average pooling over a quantized input signal composed
|
| 156 |
+
of several quantized input planes.
|
| 157 |
+
|
| 158 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 159 |
+
|
| 160 |
+
See :class:`~torch.ao.nn.quantized.AdaptiveAvgPool3d` for details and output shape.
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
output_size: the target output size (single integer or
|
| 164 |
+
double-integer tuple)
|
| 165 |
+
"""
|
| 166 |
+
if not input.is_quantized:
|
| 167 |
+
raise ValueError(
|
| 168 |
+
"Input to 'quantized.functional.adaptive_avg_pool3d' must be quantized!"
|
| 169 |
+
)
|
| 170 |
+
return torch.nn.functional.adaptive_avg_pool3d(input, output_size)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def conv1d(
|
| 174 |
+
input,
|
| 175 |
+
weight,
|
| 176 |
+
bias,
|
| 177 |
+
stride=1,
|
| 178 |
+
padding=0,
|
| 179 |
+
dilation=1,
|
| 180 |
+
groups=1,
|
| 181 |
+
padding_mode="zeros",
|
| 182 |
+
scale=1.0,
|
| 183 |
+
zero_point=0,
|
| 184 |
+
dtype=torch.quint8,
|
| 185 |
+
):
|
| 186 |
+
r"""
|
| 187 |
+
Applies a 1D convolution over a quantized 1D input composed of several input
|
| 188 |
+
planes.
|
| 189 |
+
|
| 190 |
+
See :class:`~torch.ao.nn.quantized.Conv1d` for details and output shape.
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
input: quantized input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`
|
| 194 |
+
weight: quantized filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , iW)`
|
| 195 |
+
bias: **non-quantized** bias tensor of shape :math:`(\text{out\_channels})`. The tensor type must be `torch.float`.
|
| 196 |
+
stride: the stride of the convolving kernel. Can be a single number or a
|
| 197 |
+
tuple `(sW,)`. Default: 1
|
| 198 |
+
padding: implicit paddings on both sides of the input. Can be a
|
| 199 |
+
single number or a tuple `(padW,)`. Default: 0
|
| 200 |
+
dilation: the spacing between kernel elements. Can be a single number or
|
| 201 |
+
a tuple `(dW,)`. Default: 1
|
| 202 |
+
groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
|
| 203 |
+
number of groups. Default: 1
|
| 204 |
+
padding_mode: the padding mode to use. Only "zeros" is supported for quantized convolution at the moment. Default: "zeros"
|
| 205 |
+
scale: quantization scale for the output. Default: 1.0
|
| 206 |
+
zero_point: quantization zero_point for the output. Default: 0
|
| 207 |
+
dtype: quantization data type to use. Default: ``torch.quint8``
|
| 208 |
+
|
| 209 |
+
Examples::
|
| 210 |
+
|
| 211 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 212 |
+
>>> from torch.ao.nn.quantized import functional as qF
|
| 213 |
+
>>> filters = torch.randn(33, 16, 3, dtype=torch.float)
|
| 214 |
+
>>> inputs = torch.randn(20, 16, 50, dtype=torch.float)
|
| 215 |
+
>>> bias = torch.randn(33, dtype=torch.float)
|
| 216 |
+
>>>
|
| 217 |
+
>>> scale, zero_point = 1.0, 0
|
| 218 |
+
>>> dtype_inputs = torch.quint8
|
| 219 |
+
>>> dtype_filters = torch.qint8
|
| 220 |
+
>>>
|
| 221 |
+
>>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters)
|
| 222 |
+
>>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs)
|
| 223 |
+
>>> qF.conv1d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point)
|
| 224 |
+
""" # noqa: E501
|
| 225 |
+
if padding_mode != "zeros":
|
| 226 |
+
raise NotImplementedError("Only zero-padding is supported!")
|
| 227 |
+
if input.dtype != torch.quint8:
|
| 228 |
+
raise NotImplementedError(
|
| 229 |
+
"Only torch.quint8 is supported for activation tensor!"
|
| 230 |
+
)
|
| 231 |
+
if weight.dtype != torch.qint8:
|
| 232 |
+
raise NotImplementedError("Only torch.qint8 is supported for weight tensor!")
|
| 233 |
+
if input.ndim != 3:
|
| 234 |
+
raise ValueError("Input shape must be `(N, C, L)`!")
|
| 235 |
+
stride = _pair_from_first(stride)
|
| 236 |
+
padding = _pair_from_first(padding)
|
| 237 |
+
dilation = _pair_from_first(dilation)
|
| 238 |
+
|
| 239 |
+
packed_params = torch.ops.quantized.conv1d_prepack(
|
| 240 |
+
weight, bias, stride, padding, dilation, groups
|
| 241 |
+
)
|
| 242 |
+
return torch.ops.quantized.conv1d(input, packed_params, scale, zero_point)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def conv2d(
|
| 246 |
+
input,
|
| 247 |
+
weight,
|
| 248 |
+
bias,
|
| 249 |
+
stride=1,
|
| 250 |
+
padding=0,
|
| 251 |
+
dilation=1,
|
| 252 |
+
groups=1,
|
| 253 |
+
padding_mode="zeros",
|
| 254 |
+
scale=1.0,
|
| 255 |
+
zero_point=0,
|
| 256 |
+
dtype=torch.quint8,
|
| 257 |
+
):
|
| 258 |
+
r"""
|
| 259 |
+
Applies a 2D convolution over a quantized 2D input composed of several input
|
| 260 |
+
planes.
|
| 261 |
+
|
| 262 |
+
See :class:`~torch.ao.nn.quantized.Conv2d` for details and output shape.
|
| 263 |
+
|
| 264 |
+
Args:
|
| 265 |
+
input: quantized input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
|
| 266 |
+
weight: quantized filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kH , kW)`
|
| 267 |
+
bias: **non-quantized** bias tensor of shape :math:`(\text{out\_channels})`. The tensor type must be `torch.float`.
|
| 268 |
+
stride: the stride of the convolving kernel. Can be a single number or a
|
| 269 |
+
tuple `(sH, sW)`. Default: 1
|
| 270 |
+
padding: implicit paddings on both sides of the input. Can be a
|
| 271 |
+
single number or a tuple `(padH, padW)`. Default: 0
|
| 272 |
+
dilation: the spacing between kernel elements. Can be a single number or
|
| 273 |
+
a tuple `(dH, dW)`. Default: 1
|
| 274 |
+
groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
|
| 275 |
+
number of groups. Default: 1
|
| 276 |
+
padding_mode: the padding mode to use. Only "zeros" is supported for quantized convolution at the moment. Default: "zeros"
|
| 277 |
+
scale: quantization scale for the output. Default: 1.0
|
| 278 |
+
zero_point: quantization zero_point for the output. Default: 0
|
| 279 |
+
dtype: quantization data type to use. Default: ``torch.quint8``
|
| 280 |
+
|
| 281 |
+
Examples::
|
| 282 |
+
|
| 283 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 284 |
+
>>> from torch.ao.nn.quantized import functional as qF
|
| 285 |
+
>>> filters = torch.randn(8, 4, 3, 3, dtype=torch.float)
|
| 286 |
+
>>> inputs = torch.randn(1, 4, 5, 5, dtype=torch.float)
|
| 287 |
+
>>> bias = torch.randn(8, dtype=torch.float)
|
| 288 |
+
>>>
|
| 289 |
+
>>> scale, zero_point = 1.0, 0
|
| 290 |
+
>>> dtype_inputs = torch.quint8
|
| 291 |
+
>>> dtype_filters = torch.qint8
|
| 292 |
+
>>>
|
| 293 |
+
>>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters)
|
| 294 |
+
>>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs)
|
| 295 |
+
>>> qF.conv2d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point)
|
| 296 |
+
""" # noqa: E501
|
| 297 |
+
if padding_mode != "zeros":
|
| 298 |
+
raise NotImplementedError("Only zero-padding is supported!")
|
| 299 |
+
if input.dtype != torch.quint8:
|
| 300 |
+
raise NotImplementedError(
|
| 301 |
+
"Only torch.quint8 is supported for activation tensor!"
|
| 302 |
+
)
|
| 303 |
+
if weight.dtype != torch.qint8:
|
| 304 |
+
raise NotImplementedError("Only torch.qint8 is supported for weight tensor!")
|
| 305 |
+
if input.ndim != 4:
|
| 306 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 307 |
+
stride = _pair(stride)
|
| 308 |
+
padding = _pair(padding)
|
| 309 |
+
dilation = _pair(dilation)
|
| 310 |
+
|
| 311 |
+
packed_params = torch.ops.quantized.conv2d_prepack(
|
| 312 |
+
weight, bias, stride, padding, dilation, groups
|
| 313 |
+
)
|
| 314 |
+
return torch.ops.quantized.conv2d(input, packed_params, scale, zero_point)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def conv3d(
|
| 318 |
+
input,
|
| 319 |
+
weight,
|
| 320 |
+
bias,
|
| 321 |
+
stride=1,
|
| 322 |
+
padding=0,
|
| 323 |
+
dilation=1,
|
| 324 |
+
groups=1,
|
| 325 |
+
padding_mode="zeros",
|
| 326 |
+
scale=1.0,
|
| 327 |
+
zero_point=0,
|
| 328 |
+
dtype=torch.quint8,
|
| 329 |
+
):
|
| 330 |
+
r"""
|
| 331 |
+
Applies a 3D convolution over a quantized 3D input composed of several input
|
| 332 |
+
planes.
|
| 333 |
+
|
| 334 |
+
See :class:`~torch.ao.nn.quantized.Conv3d` for details and output shape.
|
| 335 |
+
|
| 336 |
+
Args:
|
| 337 |
+
input: quantized input tensor of shape
|
| 338 |
+
:math:`(\text{minibatch} , \text{in\_channels} , iD , iH , iW)`
|
| 339 |
+
weight: quantized filters of shape
|
| 340 |
+
:math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kD , kH , kW)`
|
| 341 |
+
bias: **non-quantized** bias tensor of shape
|
| 342 |
+
:math:`(\text{out\_channels})`. The tensor type must be `torch.float`.
|
| 343 |
+
stride: the stride of the convolving kernel. Can be a single number or a
|
| 344 |
+
tuple `(sD, sH, sW)`. Default: 1
|
| 345 |
+
padding: implicit paddings on both sides of the input. Can be a
|
| 346 |
+
single number or a tuple `(padD, padH, padW)`. Default: 0
|
| 347 |
+
dilation: the spacing between kernel elements. Can be a single number or
|
| 348 |
+
a tuple `(dD, dH, dW)`. Default: 1
|
| 349 |
+
groups: split input into groups, :math:`\text{in\_channels}` should be
|
| 350 |
+
divisible by the number of groups. Default: 1
|
| 351 |
+
padding_mode: the padding mode to use. Only "zeros" is supported for
|
| 352 |
+
quantized convolution at the moment. Default: "zeros"
|
| 353 |
+
scale: quantization scale for the output. Default: 1.0
|
| 354 |
+
zero_point: quantization zero_point for the output. Default: 0
|
| 355 |
+
dtype: quantization data type to use. Default: ``torch.quint8``
|
| 356 |
+
|
| 357 |
+
Examples::
|
| 358 |
+
|
| 359 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 360 |
+
>>> from torch.ao.nn.quantized import functional as qF
|
| 361 |
+
>>> filters = torch.randn(8, 4, 3, 3, 3, dtype=torch.float)
|
| 362 |
+
>>> inputs = torch.randn(1, 4, 5, 5, 5, dtype=torch.float)
|
| 363 |
+
>>> bias = torch.randn(8, dtype=torch.float)
|
| 364 |
+
>>>
|
| 365 |
+
>>> scale, zero_point = 1.0, 0
|
| 366 |
+
>>> dtype_inputs = torch.quint8
|
| 367 |
+
>>> dtype_filters = torch.qint8
|
| 368 |
+
>>>
|
| 369 |
+
>>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters)
|
| 370 |
+
>>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs)
|
| 371 |
+
>>> qF.conv3d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point)
|
| 372 |
+
""" # noqa: E501
|
| 373 |
+
if padding_mode != "zeros":
|
| 374 |
+
raise NotImplementedError("Only zero-padding is supported!")
|
| 375 |
+
if input.dtype != torch.quint8:
|
| 376 |
+
raise NotImplementedError(
|
| 377 |
+
"Only torch.quint8 is supported for activation tensor!"
|
| 378 |
+
)
|
| 379 |
+
if weight.dtype != torch.qint8:
|
| 380 |
+
raise NotImplementedError("Only torch.qint8 is supported for weight tensor!")
|
| 381 |
+
if input.ndim != 5:
|
| 382 |
+
raise ValueError("Input shape must be `(N, C, D, H, W)`!")
|
| 383 |
+
stride = _triple(stride)
|
| 384 |
+
padding = _triple(padding)
|
| 385 |
+
dilation = _triple(dilation)
|
| 386 |
+
|
| 387 |
+
packed_params = torch.ops.quantized.conv3d_prepack(
|
| 388 |
+
weight, bias, stride, padding, dilation, groups
|
| 389 |
+
)
|
| 390 |
+
return torch.ops.quantized.conv3d(input, packed_params, scale, zero_point)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def interpolate(
|
| 394 |
+
input, size=None, scale_factor=None, mode="nearest", align_corners=None
|
| 395 |
+
):
|
| 396 |
+
r"""Down/up samples the input to either the given :attr:`size` or the given
|
| 397 |
+
:attr:`scale_factor`
|
| 398 |
+
|
| 399 |
+
See :func:`torch.nn.functional.interpolate` for implementation details.
|
| 400 |
+
|
| 401 |
+
The input dimensions are interpreted in the form:
|
| 402 |
+
`mini-batch x channels x [optional depth] x [optional height] x width`.
|
| 403 |
+
|
| 404 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 405 |
+
|
| 406 |
+
.. note:: Only 2D/3D input is supported for quantized inputs
|
| 407 |
+
|
| 408 |
+
.. note:: Only the following modes are supported for the quantized inputs:
|
| 409 |
+
|
| 410 |
+
- `bilinear`
|
| 411 |
+
- `nearest`
|
| 412 |
+
|
| 413 |
+
Args:
|
| 414 |
+
input (Tensor): the input tensor
|
| 415 |
+
size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]):
|
| 416 |
+
output spatial size.
|
| 417 |
+
scale_factor (float or Tuple[float]): multiplier for spatial size. Has to match input size if it is a tuple.
|
| 418 |
+
mode (str): algorithm used for upsampling:
|
| 419 |
+
``'nearest'`` | ``'bilinear'``
|
| 420 |
+
align_corners (bool, optional): Geometrically, we consider the pixels of the
|
| 421 |
+
input and output as squares rather than points.
|
| 422 |
+
If set to ``True``, the input and output tensors are aligned by the
|
| 423 |
+
center points of their corner pixels, preserving the values at the corner pixels.
|
| 424 |
+
If set to ``False``, the input and output tensors are aligned by the corner
|
| 425 |
+
points of their corner pixels, and the interpolation uses edge value padding
|
| 426 |
+
for out-of-boundary values, making this operation *independent* of input size
|
| 427 |
+
when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode`
|
| 428 |
+
is ``'bilinear'``.
|
| 429 |
+
Default: ``False``
|
| 430 |
+
"""
|
| 431 |
+
if not input.is_quantized:
|
| 432 |
+
raise ValueError("Input to 'quantized.interpolate' must be quantized!")
|
| 433 |
+
return torch.nn.functional.interpolate(
|
| 434 |
+
input, size, scale_factor, mode, align_corners
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def linear(
|
| 439 |
+
input: Tensor,
|
| 440 |
+
weight: Tensor,
|
| 441 |
+
bias: Optional[Tensor] = None,
|
| 442 |
+
scale: Optional[float] = None,
|
| 443 |
+
zero_point: Optional[int] = None,
|
| 444 |
+
) -> Tensor:
|
| 445 |
+
r"""
|
| 446 |
+
Applies a linear transformation to the incoming quantized data:
|
| 447 |
+
:math:`y = xA^T + b`.
|
| 448 |
+
See :class:`~torch.ao.nn.quantized.Linear`
|
| 449 |
+
|
| 450 |
+
.. note::
|
| 451 |
+
|
| 452 |
+
Current implementation packs weights on every call, which has penalty on performance.
|
| 453 |
+
If you want to avoid the overhead, use :class:`~torch.ao.nn.quantized.Linear`.
|
| 454 |
+
|
| 455 |
+
Args:
|
| 456 |
+
input (Tensor): Quantized input of type `torch.quint8`
|
| 457 |
+
weight (Tensor): Quantized weight of type `torch.qint8`
|
| 458 |
+
bias (Tensor): None or fp32 bias of type `torch.float`
|
| 459 |
+
scale (double): output scale. If None, derived from the input scale
|
| 460 |
+
zero_point (long): output zero point. If None, derived from the input zero_point
|
| 461 |
+
|
| 462 |
+
Shape:
|
| 463 |
+
- Input: :math:`(N, *, in\_features)` where `*` means any number of
|
| 464 |
+
additional dimensions
|
| 465 |
+
- Weight: :math:`(out\_features, in\_features)`
|
| 466 |
+
- Bias: :math:`(out\_features)`
|
| 467 |
+
- Output: :math:`(N, *, out\_features)`
|
| 468 |
+
"""
|
| 469 |
+
if scale is None:
|
| 470 |
+
scale = input.q_scale()
|
| 471 |
+
if zero_point is None:
|
| 472 |
+
zero_point = input.q_zero_point()
|
| 473 |
+
_packed_params = torch.ops.quantized.linear_prepack(weight, bias)
|
| 474 |
+
return torch.ops.quantized.linear(input, _packed_params, scale, zero_point)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def max_pool1d(
|
| 478 |
+
input,
|
| 479 |
+
kernel_size,
|
| 480 |
+
stride=None,
|
| 481 |
+
padding=0,
|
| 482 |
+
dilation=1,
|
| 483 |
+
ceil_mode=False,
|
| 484 |
+
return_indices=False,
|
| 485 |
+
):
|
| 486 |
+
r"""Applies a 1D max pooling over a quantized input signal composed of
|
| 487 |
+
several quantized input planes.
|
| 488 |
+
|
| 489 |
+
.. note:: The input quantization parameters are propagated to the output.
|
| 490 |
+
|
| 491 |
+
See :class:`~torch.ao.nn.quantized.MaxPool1d` for details.
|
| 492 |
+
"""
|
| 493 |
+
if return_indices:
|
| 494 |
+
raise NotImplementedError("return_indices is not yet implemented!")
|
| 495 |
+
if stride is None:
|
| 496 |
+
stride = torch.jit.annotate(List[int], [])
|
| 497 |
+
return torch.nn.functional.max_pool1d(
|
| 498 |
+
input,
|
| 499 |
+
kernel_size,
|
| 500 |
+
stride,
|
| 501 |
+
padding,
|
| 502 |
+
dilation,
|
| 503 |
+
ceil_mode=ceil_mode,
|
| 504 |
+
return_indices=return_indices,
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def max_pool2d(
|
| 509 |
+
input,
|
| 510 |
+
kernel_size,
|
| 511 |
+
stride=None,
|
| 512 |
+
padding=0,
|
| 513 |
+
dilation=1,
|
| 514 |
+
ceil_mode=False,
|
| 515 |
+
return_indices=False,
|
| 516 |
+
):
|
| 517 |
+
r"""Applies a 2D max pooling over a quantized input signal composed of
|
| 518 |
+
several quantized input planes.
|
| 519 |
+
|
| 520 |
+
.. note:: The input quantization parameters are propagated to the output.
|
| 521 |
+
|
| 522 |
+
See :class:`~torch.ao.nn.quantized.MaxPool2d` for details.
|
| 523 |
+
"""
|
| 524 |
+
if return_indices:
|
| 525 |
+
raise NotImplementedError("return_indices is not yet implemented!")
|
| 526 |
+
if stride is None:
|
| 527 |
+
stride = torch.jit.annotate(List[int], [])
|
| 528 |
+
return torch.nn.functional.max_pool2d(
|
| 529 |
+
input,
|
| 530 |
+
kernel_size,
|
| 531 |
+
stride,
|
| 532 |
+
padding,
|
| 533 |
+
dilation,
|
| 534 |
+
ceil_mode=ceil_mode,
|
| 535 |
+
return_indices=return_indices,
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def celu(input: Tensor, scale: float, zero_point: int, alpha: float = 1.0) -> Tensor:
|
| 540 |
+
r"""celu(input, scale, zero_point, alpha=1.) -> Tensor
|
| 541 |
+
|
| 542 |
+
Applies the quantized CELU function element-wise.
|
| 543 |
+
|
| 544 |
+
.. math::
|
| 545 |
+
\text{CELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x / \alpha) - 1))
|
| 546 |
+
|
| 547 |
+
Args:
|
| 548 |
+
input: quantized input
|
| 549 |
+
alpha: the :math:`\alpha` value for the CELU formulation. Default: 1.0
|
| 550 |
+
"""
|
| 551 |
+
if not input.is_quantized:
|
| 552 |
+
raise ValueError("Input to 'quantized.celu' must be quantized!")
|
| 553 |
+
return torch.ops.quantized.celu(input, scale, zero_point, alpha)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def leaky_relu(
|
| 557 |
+
input: Tensor,
|
| 558 |
+
negative_slope: float = 0.01,
|
| 559 |
+
inplace: bool = False,
|
| 560 |
+
scale: Optional[float] = None,
|
| 561 |
+
zero_point: Optional[int] = None,
|
| 562 |
+
):
|
| 563 |
+
r"""
|
| 564 |
+
Quantized version of the.
|
| 565 |
+
leaky_relu(input, negative_slope=0.01, inplace=False, scale, zero_point) -> Tensor
|
| 566 |
+
|
| 567 |
+
Applies element-wise,
|
| 568 |
+
:math:`\text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x)`
|
| 569 |
+
|
| 570 |
+
Args:
|
| 571 |
+
input: Quantized input
|
| 572 |
+
negative_slope: The slope of the negative input
|
| 573 |
+
inplace: Inplace modification of the input tensor
|
| 574 |
+
scale, zero_point: Scale and zero point of the output tensor.
|
| 575 |
+
|
| 576 |
+
See :class:`~torch.nn.LeakyReLU` for more details.
|
| 577 |
+
"""
|
| 578 |
+
if scale is not None and zero_point is not None:
|
| 579 |
+
assert not inplace, "Cannot rescale with `inplace`"
|
| 580 |
+
output = torch._empty_affine_quantized(
|
| 581 |
+
input.shape, scale=scale, zero_point=int(zero_point), dtype=input.dtype
|
| 582 |
+
)
|
| 583 |
+
torch._C._nn.leaky_relu(input, negative_slope, out=output)
|
| 584 |
+
return output
|
| 585 |
+
if inplace:
|
| 586 |
+
result = torch._C._nn.leaky_relu_(input, negative_slope)
|
| 587 |
+
else:
|
| 588 |
+
result = torch._C._nn.leaky_relu(input, negative_slope)
|
| 589 |
+
return result
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def hardtanh(
|
| 593 |
+
input: Tensor, min_val: float = -1.0, max_val: float = 1.0, inplace: bool = False
|
| 594 |
+
) -> Tensor:
|
| 595 |
+
r"""This is the quantized version of :func:`~torch.nn.functional.hardtanh`."""
|
| 596 |
+
if not input.is_quantized:
|
| 597 |
+
raise ValueError("Input to 'quantized.hardtanh' must be quantized!")
|
| 598 |
+
if inplace:
|
| 599 |
+
return torch._C._nn.hardtanh_(input, min_val, max_val)
|
| 600 |
+
return torch._C._nn.hardtanh(input, min_val, max_val)
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
def hardswish(input: Tensor, scale: float, zero_point: int) -> Tensor:
|
| 604 |
+
r"""This is the quantized version of :func:`~torch.nn.functional.hardswish`.
|
| 605 |
+
|
| 606 |
+
Args:
|
| 607 |
+
input: quantized input
|
| 608 |
+
scale: quantization scale of the output tensor
|
| 609 |
+
zero_point: quantization zero point of the output tensor
|
| 610 |
+
"""
|
| 611 |
+
if not input.is_quantized:
|
| 612 |
+
raise ValueError("Input to 'quantized.hardswish' must be quantized!")
|
| 613 |
+
return torch._ops.ops.quantized.hardswish(input, scale, zero_point)
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def threshold(input: Tensor, threshold: float, value: float) -> Tensor:
|
| 617 |
+
r"""Applies the quantized version of the threshold function element-wise:
|
| 618 |
+
|
| 619 |
+
.. math::
|
| 620 |
+
x = \begin{cases}
|
| 621 |
+
x & \text{if~} x > \text{threshold} \\
|
| 622 |
+
\text{value} & \text{otherwise}
|
| 623 |
+
\end{cases}
|
| 624 |
+
|
| 625 |
+
See :class:`~torch.nn.Threshold` for more details.
|
| 626 |
+
"""
|
| 627 |
+
if not input.is_quantized:
|
| 628 |
+
raise ValueError("Input to 'quantized.threshold' must be quantized!")
|
| 629 |
+
if threshold is None:
|
| 630 |
+
raise ValueError("Input to 'threshold' must be specified!")
|
| 631 |
+
if value is None:
|
| 632 |
+
raise ValueError("Input to 'value' must be specified!")
|
| 633 |
+
return torch._ops.ops.quantized.threshold(input, threshold, value)
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
def elu(input: Tensor, scale: float, zero_point: int, alpha: float = 1.0) -> Tensor:
|
| 637 |
+
r"""This is the quantized version of :func:`~torch.nn.functional.elu`.
|
| 638 |
+
|
| 639 |
+
Args:
|
| 640 |
+
input: quantized input
|
| 641 |
+
scale: quantization scale of the output tensor
|
| 642 |
+
zero_point: quantization zero point of the output tensor
|
| 643 |
+
alpha: the alpha constant
|
| 644 |
+
"""
|
| 645 |
+
if not input.is_quantized:
|
| 646 |
+
raise ValueError("Input to 'quantized.elu' must be quantized!")
|
| 647 |
+
return torch.ops.quantized.elu(input, scale, zero_point, alpha)
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
def hardsigmoid(input: Tensor, inplace: bool = False) -> Tensor:
|
| 651 |
+
r"""This is the quantized version of :func:`~torch.nn.functional.hardsigmoid`."""
|
| 652 |
+
if not input.is_quantized:
|
| 653 |
+
raise ValueError("Input to 'quantized.hardsigmoid' must be quantized!")
|
| 654 |
+
if inplace:
|
| 655 |
+
return torch._C._nn.hardsigmoid_(input) # type: ignore[attr-defined]
|
| 656 |
+
return torch._C._nn.hardsigmoid(input)
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def clamp(input: Tensor, min_: float, max_: float) -> Tensor:
|
| 660 |
+
r"""float(input, min\_, max\_) -> Tensor
|
| 661 |
+
|
| 662 |
+
Applies the clamp function element-wise.
|
| 663 |
+
See :class:`~torch.ao.nn.quantized.clamp` for more details.
|
| 664 |
+
|
| 665 |
+
Args:
|
| 666 |
+
input: quantized input
|
| 667 |
+
min_: minimum value for clamping
|
| 668 |
+
max_: maximum value for clamping
|
| 669 |
+
"""
|
| 670 |
+
if not input.is_quantized:
|
| 671 |
+
raise ValueError("Input to 'quantized.clamp' must be quantized!")
|
| 672 |
+
return torch.clamp(input, min_, max_)
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def upsample(input, size=None, scale_factor=None, mode="nearest", align_corners=None):
|
| 676 |
+
r"""Upsamples the input to either the given :attr:`size` or the given
|
| 677 |
+
:attr:`scale_factor`
|
| 678 |
+
|
| 679 |
+
.. warning::
|
| 680 |
+
This function is deprecated in favor of
|
| 681 |
+
:func:`torch.ao.nn.quantized.functional.interpolate`.
|
| 682 |
+
This is equivalent with ``nn.quantized.functional.interpolate(...)``.
|
| 683 |
+
|
| 684 |
+
See :func:`torch.nn.functional.interpolate` for implementation details.
|
| 685 |
+
|
| 686 |
+
The input dimensions are interpreted in the form:
|
| 687 |
+
`mini-batch x channels x [optional depth] x [optional height] x width`.
|
| 688 |
+
|
| 689 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 690 |
+
|
| 691 |
+
.. note:: Only 2D input is supported for quantized inputs
|
| 692 |
+
|
| 693 |
+
.. note:: Only the following modes are supported for the quantized inputs:
|
| 694 |
+
|
| 695 |
+
- `bilinear`
|
| 696 |
+
- `nearest`
|
| 697 |
+
|
| 698 |
+
Args:
|
| 699 |
+
input (Tensor): quantized input tensor
|
| 700 |
+
size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]):
|
| 701 |
+
output spatial size.
|
| 702 |
+
scale_factor (float or Tuple[float]): multiplier for spatial size. Has to be an integer.
|
| 703 |
+
mode (str): algorithm used for upsampling:
|
| 704 |
+
``'nearest'`` | ``'bilinear'``
|
| 705 |
+
align_corners (bool, optional): Geometrically, we consider the pixels of the
|
| 706 |
+
input and output as squares rather than points.
|
| 707 |
+
If set to ``True``, the input and output tensors are aligned by the
|
| 708 |
+
center points of their corner pixels, preserving the values at the corner pixels.
|
| 709 |
+
If set to ``False``, the input and output tensors are aligned by the corner
|
| 710 |
+
points of their corner pixels, and the interpolation uses edge value padding
|
| 711 |
+
for out-of-boundary values, making this operation *independent* of input size
|
| 712 |
+
when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode`
|
| 713 |
+
is ``'bilinear'``.
|
| 714 |
+
Default: ``False``
|
| 715 |
+
|
| 716 |
+
.. warning::
|
| 717 |
+
With ``align_corners = True``, the linearly interpolating modes
|
| 718 |
+
(`bilinear`) don't proportionally align the
|
| 719 |
+
output and input pixels, and thus the output values can depend on the
|
| 720 |
+
input size. This was the default behavior for these modes up to version
|
| 721 |
+
0.3.1. Since then, the default behavior is ``align_corners = False``.
|
| 722 |
+
See :class:`~torch.nn.Upsample` for concrete examples on how this
|
| 723 |
+
affects the outputs.
|
| 724 |
+
"""
|
| 725 |
+
warnings.warn(
|
| 726 |
+
"nn.quantized.functional.upsample is deprecated. Use nn.quantized.functional.interpolate instead."
|
| 727 |
+
)
|
| 728 |
+
return interpolate(input, size, scale_factor, mode, align_corners)
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
def upsample_bilinear(input, size=None, scale_factor=None):
|
| 732 |
+
r"""Upsamples the input, using bilinear upsampling.
|
| 733 |
+
|
| 734 |
+
.. warning::
|
| 735 |
+
This function is deprecated in favor of
|
| 736 |
+
:func:`torch.ao.nn.quantized.functional.interpolate`.
|
| 737 |
+
This is equivalent with
|
| 738 |
+
``nn.quantized.functional.interpolate(..., mode='bilinear', align_corners=True)``.
|
| 739 |
+
|
| 740 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 741 |
+
|
| 742 |
+
.. note:: Only 2D inputs are supported
|
| 743 |
+
|
| 744 |
+
Args:
|
| 745 |
+
input (Tensor): quantized input
|
| 746 |
+
size (int or Tuple[int, int]): output spatial size.
|
| 747 |
+
scale_factor (int or Tuple[int, int]): multiplier for spatial size
|
| 748 |
+
"""
|
| 749 |
+
# DeprecationWarning is ignored by default
|
| 750 |
+
warnings.warn(
|
| 751 |
+
"nn.quantized.functional.upsample_bilinear is deprecated. Use nn.quantized.functional.interpolate instead."
|
| 752 |
+
)
|
| 753 |
+
return interpolate(input, size, scale_factor, mode="bilinear", align_corners=True)
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def upsample_nearest(input, size=None, scale_factor=None):
|
| 757 |
+
r"""Upsamples the input, using nearest neighbours' pixel values.
|
| 758 |
+
|
| 759 |
+
.. warning::
|
| 760 |
+
This function is deprecated in favor of
|
| 761 |
+
:func:`torch.ao.nn.quantized.functional.interpolate`.
|
| 762 |
+
This is equivalent with ``nn.quantized.functional.interpolate(..., mode='nearest')``.
|
| 763 |
+
|
| 764 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 765 |
+
|
| 766 |
+
.. note:: Only 2D inputs are supported
|
| 767 |
+
|
| 768 |
+
Args:
|
| 769 |
+
input (Tensor): quantized input
|
| 770 |
+
size (int or Tuple[int, int] or Tuple[int, int, int]): output spatial
|
| 771 |
+
size.
|
| 772 |
+
scale_factor (int): multiplier for spatial size. Has to be an integer.
|
| 773 |
+
"""
|
| 774 |
+
# DeprecationWarning is ignored by default
|
| 775 |
+
warnings.warn(
|
| 776 |
+
"nn.quantized.functional.upsample_nearest is deprecated. Use nn.quantized.functional.interpolate instead."
|
| 777 |
+
)
|
| 778 |
+
return interpolate(input, size, scale_factor, mode="nearest")
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__init__.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
# The quantized modules use `torch.nn` and `torch.ao.nn.quantizable`
|
| 5 |
+
# packages. However, the `quantizable` package uses "lazy imports"
|
| 6 |
+
# to avoid circular dependency.
|
| 7 |
+
# Hence we need to include it here to make sure it is resolved before
|
| 8 |
+
# they are used in the modules.
|
| 9 |
+
import torch.ao.nn.quantizable
|
| 10 |
+
from torch.nn.modules.pooling import MaxPool2d
|
| 11 |
+
|
| 12 |
+
from .activation import (
|
| 13 |
+
ELU,
|
| 14 |
+
Hardswish,
|
| 15 |
+
LeakyReLU,
|
| 16 |
+
MultiheadAttention,
|
| 17 |
+
PReLU,
|
| 18 |
+
ReLU6,
|
| 19 |
+
Sigmoid,
|
| 20 |
+
Softmax,
|
| 21 |
+
)
|
| 22 |
+
from .batchnorm import BatchNorm2d, BatchNorm3d
|
| 23 |
+
from .conv import (
|
| 24 |
+
Conv1d,
|
| 25 |
+
Conv2d,
|
| 26 |
+
Conv3d,
|
| 27 |
+
ConvTranspose1d,
|
| 28 |
+
ConvTranspose2d,
|
| 29 |
+
ConvTranspose3d,
|
| 30 |
+
)
|
| 31 |
+
from .dropout import Dropout
|
| 32 |
+
from .embedding_ops import Embedding, EmbeddingBag
|
| 33 |
+
from .functional_modules import FloatFunctional, FXFloatFunctional, QFunctional
|
| 34 |
+
from .linear import Linear
|
| 35 |
+
from .normalization import (
|
| 36 |
+
GroupNorm,
|
| 37 |
+
InstanceNorm1d,
|
| 38 |
+
InstanceNorm2d,
|
| 39 |
+
InstanceNorm3d,
|
| 40 |
+
LayerNorm,
|
| 41 |
+
)
|
| 42 |
+
from .rnn import LSTM
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
__all__ = [
|
| 46 |
+
"BatchNorm2d",
|
| 47 |
+
"BatchNorm3d",
|
| 48 |
+
"Conv1d",
|
| 49 |
+
"Conv2d",
|
| 50 |
+
"Conv3d",
|
| 51 |
+
"ConvTranspose1d",
|
| 52 |
+
"ConvTranspose2d",
|
| 53 |
+
"ConvTranspose3d",
|
| 54 |
+
"DeQuantize",
|
| 55 |
+
"ELU",
|
| 56 |
+
"Embedding",
|
| 57 |
+
"EmbeddingBag",
|
| 58 |
+
"GroupNorm",
|
| 59 |
+
"Hardswish",
|
| 60 |
+
"InstanceNorm1d",
|
| 61 |
+
"InstanceNorm2d",
|
| 62 |
+
"InstanceNorm3d",
|
| 63 |
+
"LayerNorm",
|
| 64 |
+
"LeakyReLU",
|
| 65 |
+
"Linear",
|
| 66 |
+
"LSTM",
|
| 67 |
+
"MultiheadAttention",
|
| 68 |
+
"Quantize",
|
| 69 |
+
"ReLU6",
|
| 70 |
+
"Sigmoid",
|
| 71 |
+
"Softmax",
|
| 72 |
+
"Dropout",
|
| 73 |
+
"PReLU",
|
| 74 |
+
# Wrapper modules
|
| 75 |
+
"FloatFunctional",
|
| 76 |
+
"FXFloatFunctional",
|
| 77 |
+
"QFunctional",
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class Quantize(torch.nn.Module):
|
| 82 |
+
r"""Quantizes an incoming tensor
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
`scale`: scale of the output Quantized Tensor
|
| 86 |
+
`zero_point`: zero_point of output Quantized Tensor
|
| 87 |
+
`dtype`: data type of output Quantized Tensor
|
| 88 |
+
`factory_kwargs`: Dictionary of kwargs used for configuring initialization
|
| 89 |
+
of internal buffers. Currently, `device` and `dtype` are supported.
|
| 90 |
+
Example: `factory_kwargs={'device': 'cuda', 'dtype': torch.float64}`
|
| 91 |
+
will initialize internal buffers as type `torch.float64` on the current CUDA device.
|
| 92 |
+
Note that `dtype` only applies to floating-point buffers.
|
| 93 |
+
|
| 94 |
+
Examples::
|
| 95 |
+
>>> t = torch.tensor([[1., -1.], [1., -1.]])
|
| 96 |
+
>>> scale, zero_point, dtype = 1.0, 2, torch.qint8
|
| 97 |
+
>>> qm = Quantize(scale, zero_point, dtype)
|
| 98 |
+
>>> # xdoctest: +SKIP
|
| 99 |
+
>>> qt = qm(t)
|
| 100 |
+
>>> print(qt)
|
| 101 |
+
tensor([[ 1., -1.],
|
| 102 |
+
[ 1., -1.]], size=(2, 2), dtype=torch.qint8, scale=1.0, zero_point=2)
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
scale: torch.Tensor
|
| 106 |
+
zero_point: torch.Tensor
|
| 107 |
+
|
| 108 |
+
def __init__(self, scale, zero_point, dtype, factory_kwargs=None):
|
| 109 |
+
factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
|
| 110 |
+
super().__init__()
|
| 111 |
+
self.register_buffer("scale", torch.tensor([scale], **factory_kwargs))
|
| 112 |
+
self.register_buffer(
|
| 113 |
+
"zero_point",
|
| 114 |
+
torch.tensor(
|
| 115 |
+
[zero_point],
|
| 116 |
+
dtype=torch.long,
|
| 117 |
+
**{k: v for k, v in factory_kwargs.items() if k != "dtype"},
|
| 118 |
+
),
|
| 119 |
+
)
|
| 120 |
+
self.dtype = dtype
|
| 121 |
+
|
| 122 |
+
def forward(self, X):
|
| 123 |
+
return torch.quantize_per_tensor(
|
| 124 |
+
X, float(self.scale), int(self.zero_point), self.dtype
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def from_float(mod, use_precomputed_fake_quant=False):
|
| 129 |
+
assert hasattr(mod, "activation_post_process")
|
| 130 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 131 |
+
return Quantize(
|
| 132 |
+
scale.float().item(),
|
| 133 |
+
zero_point.long().item(),
|
| 134 |
+
mod.activation_post_process.dtype,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
def extra_repr(self):
|
| 138 |
+
return f"scale={self.scale}, zero_point={self.zero_point}, dtype={self.dtype}"
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class DeQuantize(torch.nn.Module):
|
| 142 |
+
r"""Dequantizes an incoming tensor
|
| 143 |
+
|
| 144 |
+
Examples::
|
| 145 |
+
>>> input = torch.tensor([[1., -1.], [1., -1.]])
|
| 146 |
+
>>> scale, zero_point, dtype = 1.0, 2, torch.qint8
|
| 147 |
+
>>> qm = Quantize(scale, zero_point, dtype)
|
| 148 |
+
>>> # xdoctest: +SKIP
|
| 149 |
+
>>> quantized_input = qm(input)
|
| 150 |
+
>>> dqm = DeQuantize()
|
| 151 |
+
>>> dequantized = dqm(quantized_input)
|
| 152 |
+
>>> print(dequantized)
|
| 153 |
+
tensor([[ 1., -1.],
|
| 154 |
+
[ 1., -1.]], dtype=torch.float32)
|
| 155 |
+
"""
|
| 156 |
+
|
| 157 |
+
def forward(self, Xq):
|
| 158 |
+
return Xq.dequantize()
|
| 159 |
+
|
| 160 |
+
@staticmethod
|
| 161 |
+
def from_float(mod, use_precomputed_fake_quant=False):
|
| 162 |
+
return DeQuantize()
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (4.73 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/activation.cpython-310.pyc
ADDED
|
Binary file (11.8 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/batchnorm.cpython-310.pyc
ADDED
|
Binary file (4.03 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/conv.cpython-310.pyc
ADDED
|
Binary file (31.6 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/dropout.cpython-310.pyc
ADDED
|
Binary file (1.37 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-310.pyc
ADDED
|
Binary file (11.3 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/functional_modules.cpython-310.pyc
ADDED
|
Binary file (8.56 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/linear.cpython-310.pyc
ADDED
|
Binary file (9.68 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/normalization.cpython-310.pyc
ADDED
|
Binary file (6.92 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/rnn.cpython-310.pyc
ADDED
|
Binary file (2.06 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (3.71 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/activation.py
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from warnings import warn
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"ReLU6",
|
| 9 |
+
"Hardswish",
|
| 10 |
+
"ELU",
|
| 11 |
+
"LeakyReLU",
|
| 12 |
+
"Sigmoid",
|
| 13 |
+
"Softmax",
|
| 14 |
+
"MultiheadAttention",
|
| 15 |
+
"PReLU",
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ReLU6(torch.nn.ReLU):
|
| 20 |
+
r"""Applies the element-wise function:
|
| 21 |
+
|
| 22 |
+
:math:`\text{ReLU6}(x) = \min(\max(x_0, x), q(6))`, where :math:`x_0` is the
|
| 23 |
+
zero_point, and :math:`q(6)` is the quantized representation of number 6.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 27 |
+
|
| 28 |
+
Shape:
|
| 29 |
+
- Input: :math:`(N, *)` where `*` means, any number of additional
|
| 30 |
+
dimensions
|
| 31 |
+
- Output: :math:`(N, *)`, same shape as the input
|
| 32 |
+
|
| 33 |
+
.. image:: ../scripts/activation_images/ReLU6.png
|
| 34 |
+
|
| 35 |
+
Examples::
|
| 36 |
+
|
| 37 |
+
>>> m = nn.quantized.ReLU6()
|
| 38 |
+
>>> input = torch.randn(2)
|
| 39 |
+
>>> # xdoctest: +SKIP
|
| 40 |
+
>>> input = torch.quantize_per_tensor(input, 1.0, 0, dtype=torch.qint32)
|
| 41 |
+
>>> output = m(input)
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(self, inplace=False):
|
| 45 |
+
super().__init__(inplace)
|
| 46 |
+
self.inplace = inplace
|
| 47 |
+
|
| 48 |
+
def forward(self, input):
|
| 49 |
+
return torch.ops.quantized.relu6(input, self.inplace)
|
| 50 |
+
|
| 51 |
+
def _get_name(self):
|
| 52 |
+
return "QuantizedReLU6"
|
| 53 |
+
|
| 54 |
+
@staticmethod
|
| 55 |
+
def from_float(mod, use_precomputed_fake_quant=False):
|
| 56 |
+
return ReLU6(mod.inplace)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class Hardswish(torch.nn.Hardswish):
|
| 60 |
+
r"""This is the quantized version of :class:`~torch.nn.Hardswish`.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
scale: quantization scale of the output tensor
|
| 64 |
+
zero_point: quantization zero point of the output tensor
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(self, scale, zero_point, device=None, dtype=None):
|
| 68 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 69 |
+
super().__init__()
|
| 70 |
+
self.register_buffer("scale", torch.tensor(scale, **factory_kwargs))
|
| 71 |
+
self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs))
|
| 72 |
+
|
| 73 |
+
def forward(self, input):
|
| 74 |
+
return torch.ops.quantized.hardswish(input, self.scale, self.zero_point)
|
| 75 |
+
|
| 76 |
+
def _get_name(self):
|
| 77 |
+
return "QuantizedHardswish"
|
| 78 |
+
|
| 79 |
+
@staticmethod
|
| 80 |
+
def from_float(mod, use_precomputed_fake_quant=False):
|
| 81 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 82 |
+
return Hardswish(float(scale), int(zero_point))
|
| 83 |
+
|
| 84 |
+
@classmethod
|
| 85 |
+
def from_reference(cls, mod, scale, zero_point):
|
| 86 |
+
return cls(float(scale), int(zero_point))
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class ELU(torch.nn.ELU):
|
| 90 |
+
r"""This is the quantized equivalent of :class:`~torch.nn.ELU`.
|
| 91 |
+
|
| 92 |
+
Args:
|
| 93 |
+
scale: quantization scale of the output tensor
|
| 94 |
+
zero_point: quantization zero point of the output tensor
|
| 95 |
+
alpha: the alpha constant
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
def __init__(self, scale, zero_point, alpha=1.0):
|
| 99 |
+
super().__init__(alpha)
|
| 100 |
+
self.scale = scale
|
| 101 |
+
self.zero_point = zero_point
|
| 102 |
+
|
| 103 |
+
def forward(self, input):
|
| 104 |
+
return torch.ao.nn.quantized.functional.elu(
|
| 105 |
+
input, self.scale, self.zero_point, self.alpha
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
def _get_name(self):
|
| 109 |
+
return "QuantizedELU"
|
| 110 |
+
|
| 111 |
+
@staticmethod
|
| 112 |
+
def from_float(mod, use_precomputed_fake_quant=False):
|
| 113 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 114 |
+
return ELU(float(scale), int(zero_point), mod.alpha)
|
| 115 |
+
|
| 116 |
+
@classmethod
|
| 117 |
+
def from_reference(cls, mod, scale, zero_point):
|
| 118 |
+
return cls(float(scale), int(zero_point), mod.alpha)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class LeakyReLU(torch.nn.LeakyReLU):
|
| 122 |
+
r"""This is the quantized equivalent of :class:`~torch.nn.LeakyReLU`.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
scale: quantization scale of the output tensor
|
| 126 |
+
zero_point: quantization zero point of the output tensor
|
| 127 |
+
negative_slope: Controls the angle of the negative slope. Default: 1e-2
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
def __init__(
|
| 131 |
+
self,
|
| 132 |
+
scale: float,
|
| 133 |
+
zero_point: int,
|
| 134 |
+
negative_slope: float = 1e-2,
|
| 135 |
+
inplace: bool = False,
|
| 136 |
+
device=None,
|
| 137 |
+
dtype=None,
|
| 138 |
+
) -> None:
|
| 139 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 140 |
+
super().__init__(negative_slope, inplace)
|
| 141 |
+
self.register_buffer("scale", torch.tensor(scale, **factory_kwargs))
|
| 142 |
+
self.register_buffer("zero_point", torch.tensor(zero_point, **factory_kwargs))
|
| 143 |
+
|
| 144 |
+
def forward(self, input):
|
| 145 |
+
return torch.ops.quantized.leaky_relu(
|
| 146 |
+
input, self.negative_slope, self.inplace, self.scale, self.zero_point
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
def _get_name(self):
|
| 150 |
+
return "QuantizedLeakyReLU"
|
| 151 |
+
|
| 152 |
+
@classmethod
|
| 153 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 154 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 155 |
+
return cls(float(scale), int(zero_point), mod.negative_slope, mod.inplace)
|
| 156 |
+
|
| 157 |
+
@classmethod
|
| 158 |
+
def from_reference(cls, mod, scale, zero_point):
|
| 159 |
+
return cls(float(scale), int(zero_point), mod.negative_slope, mod.inplace)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class Sigmoid(torch.nn.Sigmoid):
|
| 163 |
+
r"""This is the quantized equivalent of :class:`~torch.nn.Sigmoid`.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
scale: quantization scale of the output tensor
|
| 167 |
+
zero_point: quantization zero point of the output tensor
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
def __init__(self, output_scale: float, output_zero_point: int):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.output_scale = output_scale
|
| 173 |
+
self.output_zero_point = output_zero_point
|
| 174 |
+
|
| 175 |
+
def forward(self, input):
|
| 176 |
+
return torch.ops.quantized.sigmoid(
|
| 177 |
+
input, self.output_scale, self.output_zero_point
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
@classmethod
|
| 181 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 182 |
+
(
|
| 183 |
+
output_scale,
|
| 184 |
+
output_zero_point,
|
| 185 |
+
) = mod.activation_post_process.calculate_qparams()
|
| 186 |
+
return cls(float(output_scale), int(output_zero_point))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class Softmax(torch.nn.Softmax):
|
| 190 |
+
r"""This is the quantized version of :class:`~torch.nn.Softmax`.
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
dim: A dimension along which Softmax will be computed (so every slice along dim will sum to 1).
|
| 194 |
+
scale: quantization scale of the output tensor
|
| 195 |
+
zero_point: quantization zero point of the output tensor
|
| 196 |
+
"""
|
| 197 |
+
|
| 198 |
+
def __init__(self, dim=None, scale=1.0, zero_point=0):
|
| 199 |
+
super().__init__()
|
| 200 |
+
self.dim = dim
|
| 201 |
+
self.scale = scale
|
| 202 |
+
self.zero_point = zero_point
|
| 203 |
+
|
| 204 |
+
def forward(self, input):
|
| 205 |
+
dim = self.dim
|
| 206 |
+
if dim is None:
|
| 207 |
+
stacklevel = 3
|
| 208 |
+
# Note: adding the mypy ignore on _get_softmax_dim seems less bad
|
| 209 |
+
# than making `_get_softmax_dim` an official API.
|
| 210 |
+
dim = torch.nn.functional._get_softmax_dim( # type: ignore[attr-defined]
|
| 211 |
+
"softmax", input.dim(), stacklevel
|
| 212 |
+
)
|
| 213 |
+
return torch.ops.quantized.softmax(input, dim, self.scale, self.zero_point)
|
| 214 |
+
|
| 215 |
+
def _get_name(self):
|
| 216 |
+
return "QuantizedSoftmax"
|
| 217 |
+
|
| 218 |
+
@staticmethod
|
| 219 |
+
def from_float(mod, use_precomputed_fake_quant=False):
|
| 220 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 221 |
+
return Softmax(mod.dim, float(scale), int(zero_point))
|
| 222 |
+
|
| 223 |
+
@classmethod
|
| 224 |
+
def from_reference(cls, mod, scale, zero_point):
|
| 225 |
+
return cls(mod.dim, float(scale), int(zero_point))
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class MultiheadAttention(torch.ao.nn.quantizable.MultiheadAttention):
|
| 229 |
+
_FLOAT_MODULE = torch.ao.nn.quantizable.MultiheadAttention
|
| 230 |
+
|
| 231 |
+
def _get_name(self):
|
| 232 |
+
return "QuantizedMultiheadAttention"
|
| 233 |
+
|
| 234 |
+
@classmethod
|
| 235 |
+
def from_float(cls, other):
|
| 236 |
+
# The whole flow is float -> observed -> quantized
|
| 237 |
+
# This class does observed -> quantized only
|
| 238 |
+
raise NotImplementedError(
|
| 239 |
+
"It looks like you are trying to convert a "
|
| 240 |
+
"non-observed MHA module. Please, see "
|
| 241 |
+
"the examples on quantizable MHAs."
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
@classmethod
|
| 245 |
+
def from_observed(cls, other):
|
| 246 |
+
converted = torch.ao.quantization.convert(
|
| 247 |
+
other,
|
| 248 |
+
mapping=None,
|
| 249 |
+
inplace=False,
|
| 250 |
+
remove_qconfig=True,
|
| 251 |
+
convert_custom_config_dict=None,
|
| 252 |
+
)
|
| 253 |
+
converted.__class__ = cls
|
| 254 |
+
# Remove the parameters for the bias_k and bias_v to quantize them
|
| 255 |
+
# TODO: This is a potential source of accuracy drop.
|
| 256 |
+
# quantized cat takes the scale and zp of the first
|
| 257 |
+
# element, which might lose the precision in the bias_k
|
| 258 |
+
# and the bias_v (which are cat'ed with k/v being first).
|
| 259 |
+
if converted.bias_k is not None:
|
| 260 |
+
bias_k = converted._parameters.pop("bias_k")
|
| 261 |
+
sc, zp = torch._choose_qparams_per_tensor(bias_k, reduce_range=False)
|
| 262 |
+
bias_k = torch.quantize_per_tensor(bias_k, sc, zp, torch.quint8)
|
| 263 |
+
setattr(converted, "bias_k", bias_k) # noqa: B010
|
| 264 |
+
|
| 265 |
+
if converted.bias_v is not None:
|
| 266 |
+
bias_v = converted._parameters.pop("bias_v")
|
| 267 |
+
sc, zp = torch._choose_qparams_per_tensor(
|
| 268 |
+
bias_k, reduce_range=False # type: ignore[possibly-undefined]
|
| 269 |
+
)
|
| 270 |
+
bias_v = torch.quantize_per_tensor(bias_v, sc, zp, torch.quint8)
|
| 271 |
+
setattr(converted, "bias_v", bias_v) # noqa: B010
|
| 272 |
+
|
| 273 |
+
del converted.in_proj_weight
|
| 274 |
+
del converted.in_proj_bias
|
| 275 |
+
|
| 276 |
+
return converted
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class PReLU(torch.nn.Module):
|
| 280 |
+
r"""This is the quantized equivalent of :class:`~torch.nn.PReLU`.
|
| 281 |
+
|
| 282 |
+
Args:
|
| 283 |
+
scale: quantization scale of the output tensor
|
| 284 |
+
zero_point: quantization zero point of the output tensor
|
| 285 |
+
num_parameters: number of parameters: 1, or the number of channels at input. Default: 1
|
| 286 |
+
"""
|
| 287 |
+
|
| 288 |
+
def __init__(
|
| 289 |
+
self, output_scale: float, output_zero_point: int, num_parameters: int = 1
|
| 290 |
+
) -> None:
|
| 291 |
+
super().__init__()
|
| 292 |
+
self.num_parameters = num_parameters
|
| 293 |
+
self.scale = output_scale
|
| 294 |
+
self.zero_point = output_zero_point
|
| 295 |
+
w = torch.randn(num_parameters, dtype=torch.float)
|
| 296 |
+
qw = torch.quantize_per_tensor(w, scale=1.0, zero_point=0, dtype=torch.quint8)
|
| 297 |
+
self.set_weight(qw)
|
| 298 |
+
|
| 299 |
+
def set_weight(self, w: torch.Tensor) -> None:
|
| 300 |
+
self.weight = w
|
| 301 |
+
|
| 302 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 303 |
+
return torch.ops.quantized.prelu(
|
| 304 |
+
input, self.weight, self.scale, self.zero_point
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
def _get_name(self):
|
| 308 |
+
return "QuantizedPReLU"
|
| 309 |
+
|
| 310 |
+
@classmethod
|
| 311 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 312 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 313 |
+
qprelu = cls(float(scale), int(zero_point), mod.num_parameters)
|
| 314 |
+
float_wt = mod.weight.float()
|
| 315 |
+
observer = mod.qconfig.weight()
|
| 316 |
+
observer(float_wt)
|
| 317 |
+
if observer.dtype != torch.quint8:
|
| 318 |
+
warn(
|
| 319 |
+
f"PReLU's weight observer should have dtype quint8 but got {observer.dtype}"
|
| 320 |
+
)
|
| 321 |
+
wt_scale, wt_zp = observer.calculate_qparams()
|
| 322 |
+
qweight = torch.quantize_per_tensor(
|
| 323 |
+
float_wt, float(wt_scale), int(wt_zp), torch.quint8
|
| 324 |
+
)
|
| 325 |
+
qprelu.set_weight(qweight)
|
| 326 |
+
return qprelu
|
| 327 |
+
|
| 328 |
+
@classmethod
|
| 329 |
+
def from_reference(cls, mod, scale, zero_point):
|
| 330 |
+
qprelu = cls(float(scale), int(zero_point), mod.num_parameters)
|
| 331 |
+
float_wt = mod.weight.float()
|
| 332 |
+
observer = mod.qconfig.weight()
|
| 333 |
+
observer(float_wt)
|
| 334 |
+
if observer.dtype != torch.quint8:
|
| 335 |
+
warn(
|
| 336 |
+
f"PReLU's weight observer should have dtype quint8 but got {observer.dtype}"
|
| 337 |
+
)
|
| 338 |
+
wt_scale, wt_zp = observer.calculate_qparams()
|
| 339 |
+
qweight = torch.quantize_per_tensor(
|
| 340 |
+
float_wt, float(wt_scale), int(wt_zp), torch.quint8
|
| 341 |
+
)
|
| 342 |
+
qprelu.set_weight(qweight)
|
| 343 |
+
return qprelu
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/batchnorm.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
import torch.ao.nn.intrinsic as nni
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
__all__ = ["BatchNorm2d", "BatchNorm3d"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class _BatchNorm(torch.nn.modules.batchnorm._BatchNorm):
|
| 10 |
+
def __init__(
|
| 11 |
+
self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None
|
| 12 |
+
) -> None:
|
| 13 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 14 |
+
super().__init__(num_features, eps, momentum, True, True, **factory_kwargs)
|
| 15 |
+
self.register_buffer("scale", torch.tensor(1.0, **factory_kwargs))
|
| 16 |
+
self.register_buffer("zero_point", torch.tensor(0, **factory_kwargs))
|
| 17 |
+
|
| 18 |
+
@staticmethod
|
| 19 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 20 |
+
activation_post_process = mod.activation_post_process
|
| 21 |
+
if type(mod) == cls._NNI_BN_RELU_MODULE:
|
| 22 |
+
mod = mod[0]
|
| 23 |
+
scale, zero_point = activation_post_process.calculate_qparams()
|
| 24 |
+
new_mod = cls(mod.num_features, mod.eps)
|
| 25 |
+
new_mod.weight = mod.weight
|
| 26 |
+
new_mod.bias = mod.bias
|
| 27 |
+
new_mod.running_mean = mod.running_mean
|
| 28 |
+
new_mod.running_var = mod.running_var
|
| 29 |
+
new_mod.scale = scale
|
| 30 |
+
new_mod.zero_point = zero_point
|
| 31 |
+
return new_mod
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def from_reference(cls, bn, output_scale, output_zero_point):
|
| 35 |
+
qbn = cls(
|
| 36 |
+
bn.num_features,
|
| 37 |
+
bn.eps,
|
| 38 |
+
bn.momentum,
|
| 39 |
+
device=bn.weight.device,
|
| 40 |
+
dtype=bn.weight.dtype,
|
| 41 |
+
)
|
| 42 |
+
qbn.weight = bn.weight
|
| 43 |
+
qbn.bias = bn.bias
|
| 44 |
+
qbn.running_mean = bn.running_mean
|
| 45 |
+
qbn.running_var = bn.running_var
|
| 46 |
+
qbn.scale = output_scale
|
| 47 |
+
qbn.zero_point = output_zero_point
|
| 48 |
+
return qbn
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class BatchNorm2d(_BatchNorm):
|
| 52 |
+
r"""This is the quantized version of :class:`~torch.nn.BatchNorm2d`."""
|
| 53 |
+
|
| 54 |
+
_NNI_BN_RELU_MODULE = nni.BNReLU2d
|
| 55 |
+
|
| 56 |
+
def __init__(
|
| 57 |
+
self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None
|
| 58 |
+
) -> None:
|
| 59 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 60 |
+
super().__init__(num_features, eps, momentum, **factory_kwargs)
|
| 61 |
+
|
| 62 |
+
def _get_name(self):
|
| 63 |
+
return "QuantizedBatchNorm2d"
|
| 64 |
+
|
| 65 |
+
def _check_input_dim(self, input):
|
| 66 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 67 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 68 |
+
if len(input.shape) != 4:
|
| 69 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 70 |
+
|
| 71 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 72 |
+
# disabling this since this is not symbolically traceable
|
| 73 |
+
# self._check_input_dim(input)
|
| 74 |
+
return torch.ops.quantized.batch_norm2d(
|
| 75 |
+
input,
|
| 76 |
+
self.weight,
|
| 77 |
+
self.bias,
|
| 78 |
+
self.running_mean,
|
| 79 |
+
self.running_var,
|
| 80 |
+
self.eps,
|
| 81 |
+
self.scale,
|
| 82 |
+
self.zero_point,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
@classmethod
|
| 86 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 87 |
+
return _BatchNorm.from_float(
|
| 88 |
+
cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class BatchNorm3d(_BatchNorm):
|
| 93 |
+
r"""This is the quantized version of :class:`~torch.nn.BatchNorm3d`."""
|
| 94 |
+
|
| 95 |
+
_NNI_BN_RELU_MODULE = nni.BNReLU3d
|
| 96 |
+
|
| 97 |
+
def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
|
| 98 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 99 |
+
super().__init__(num_features, eps, momentum, **factory_kwargs)
|
| 100 |
+
|
| 101 |
+
def _get_name(self):
|
| 102 |
+
return "QuantizedBatchNorm3d"
|
| 103 |
+
|
| 104 |
+
def _check_input_dim(self, input):
|
| 105 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 106 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 107 |
+
if len(input.shape) != 5:
|
| 108 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 109 |
+
|
| 110 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 111 |
+
# disabling this since this is not symbolically traceable
|
| 112 |
+
# self._check_input_dim(input)
|
| 113 |
+
return torch.ops.quantized.batch_norm3d(
|
| 114 |
+
input,
|
| 115 |
+
self.weight,
|
| 116 |
+
self.bias,
|
| 117 |
+
self.running_mean,
|
| 118 |
+
self.running_var,
|
| 119 |
+
self.eps,
|
| 120 |
+
self.scale,
|
| 121 |
+
self.zero_point,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
@classmethod
|
| 125 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 126 |
+
return _BatchNorm.from_float(
|
| 127 |
+
cls, mod, use_precomputed_fake_quant=use_precomputed_fake_quant
|
| 128 |
+
)
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/dropout.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
__all__ = ["Dropout"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Dropout(torch.nn.Dropout):
|
| 9 |
+
r"""This is the quantized equivalent of :class:`~torch.nn.Dropout`.
|
| 10 |
+
And this is a placeholder to enable models where fp32 tensors
|
| 11 |
+
had dropout to work with quantized tensors in train and eval mode.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
p: probability of an element to be zeroed
|
| 15 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def forward(self, input):
|
| 19 |
+
return input
|
| 20 |
+
|
| 21 |
+
def _get_name(self):
|
| 22 |
+
return "QuantizedDropout"
|
| 23 |
+
|
| 24 |
+
@classmethod
|
| 25 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 26 |
+
return cls(mod.p, mod.inplace)
|
| 27 |
+
|
| 28 |
+
@classmethod
|
| 29 |
+
def from_reference(cls, mod, scale, zero_point):
|
| 30 |
+
return cls(mod.p, mod.inplace)
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/embedding_ops.py
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from torch import Tensor # noqa: F401
|
| 6 |
+
from torch._jit_internal import List, Optional # noqa: F401
|
| 7 |
+
|
| 8 |
+
from .utils import _hide_packed_params_repr, _quantize_weight
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
__all__ = ["EmbeddingPackedParams", "Embedding", "EmbeddingBag"]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class EmbeddingPackedParams(torch.nn.Module):
|
| 15 |
+
_version = 1
|
| 16 |
+
|
| 17 |
+
def __init__(self, num_embeddings, embedding_dim, dtype=torch.quint8):
|
| 18 |
+
super().__init__()
|
| 19 |
+
self.dtype = dtype
|
| 20 |
+
if self.dtype in [torch.quint8, torch.quint4x2]:
|
| 21 |
+
scales = torch.ones(num_embeddings, dtype=torch.float)
|
| 22 |
+
zero_points = torch.zeros(num_embeddings, dtype=torch.float)
|
| 23 |
+
wq = torch._empty_per_channel_affine_quantized(
|
| 24 |
+
[num_embeddings, embedding_dim],
|
| 25 |
+
scales=scales,
|
| 26 |
+
zero_points=zero_points,
|
| 27 |
+
axis=0,
|
| 28 |
+
dtype=self.dtype,
|
| 29 |
+
)
|
| 30 |
+
self.set_weight(wq)
|
| 31 |
+
else:
|
| 32 |
+
raise NotImplementedError(
|
| 33 |
+
f"Unsupported dtype on quantized embedding! Supports quint8 and quint4x2. Got dtype: {dtype}"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
@torch.jit.export
|
| 37 |
+
def set_weight(self, weight: torch.Tensor) -> None:
|
| 38 |
+
if self.dtype in [torch.quint8, torch.quint4x2]:
|
| 39 |
+
self._packed_weight = torch.ops.quantized.embedding_bag_prepack(weight)
|
| 40 |
+
else:
|
| 41 |
+
raise NotImplementedError(
|
| 42 |
+
"Unsupported dtype for quantized embedding prepack! Supports quint8 and quint4x2."
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
@torch.jit.export
|
| 46 |
+
def _weight(self):
|
| 47 |
+
if self.dtype in [torch.quint8, torch.quint4x2]:
|
| 48 |
+
return torch.ops.quantized.embedding_bag_unpack(self._packed_weight)
|
| 49 |
+
else:
|
| 50 |
+
raise NotImplementedError(
|
| 51 |
+
"Unsupported dtype for quantized embedding unpack! Supports quint8 and quint4x2."
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
def forward(self, x):
|
| 55 |
+
return x
|
| 56 |
+
|
| 57 |
+
# Version 1
|
| 58 |
+
# self
|
| 59 |
+
# |--- _packed_weight : Tensor representing weight of EmbeddingPackedParamsBase
|
| 60 |
+
# |--- dtype : torch.dtype
|
| 61 |
+
|
| 62 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
| 63 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
| 64 |
+
destination[prefix + "dtype"] = self.dtype
|
| 65 |
+
destination[prefix + "_packed_weight"] = self._weight()
|
| 66 |
+
|
| 67 |
+
def _load_from_state_dict(
|
| 68 |
+
self,
|
| 69 |
+
state_dict,
|
| 70 |
+
prefix,
|
| 71 |
+
local_metadata,
|
| 72 |
+
strict,
|
| 73 |
+
missing_keys,
|
| 74 |
+
unexpected_keys,
|
| 75 |
+
error_msgs,
|
| 76 |
+
):
|
| 77 |
+
self.dtype = state_dict[prefix + "dtype"]
|
| 78 |
+
state_dict.pop(prefix + "dtype")
|
| 79 |
+
|
| 80 |
+
weight = state_dict[prefix + "_packed_weight"]
|
| 81 |
+
state_dict.pop(prefix + "_packed_weight")
|
| 82 |
+
self.set_weight(weight)
|
| 83 |
+
|
| 84 |
+
super()._load_from_state_dict(
|
| 85 |
+
state_dict,
|
| 86 |
+
prefix,
|
| 87 |
+
local_metadata,
|
| 88 |
+
False,
|
| 89 |
+
missing_keys,
|
| 90 |
+
unexpected_keys,
|
| 91 |
+
error_msgs,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def __repr__(self):
|
| 95 |
+
return self._weight().__repr__()
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class Embedding(torch.nn.Module):
|
| 99 |
+
r"""
|
| 100 |
+
A quantized Embedding module with quantized packed weights as inputs.
|
| 101 |
+
We adopt the same interface as `torch.nn.Embedding`, please see
|
| 102 |
+
https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html for documentation.
|
| 103 |
+
|
| 104 |
+
Similar to :class:`~torch.nn.Embedding`, attributes will be randomly
|
| 105 |
+
initialized at module creation time and will be overwritten later
|
| 106 |
+
|
| 107 |
+
Attributes:
|
| 108 |
+
weight (Tensor): the non-learnable quantized weights of the module of
|
| 109 |
+
shape :math:`(\text{num\_embeddings}, \text{embedding\_dim})`.
|
| 110 |
+
|
| 111 |
+
Examples::
|
| 112 |
+
>>> m = nn.quantized.Embedding(num_embeddings=10, embedding_dim=12)
|
| 113 |
+
>>> indices = torch.tensor([9, 6, 5, 7, 8, 8, 9, 2, 8])
|
| 114 |
+
>>> output = m(indices)
|
| 115 |
+
>>> print(output.size())
|
| 116 |
+
torch.Size([9, 12])
|
| 117 |
+
|
| 118 |
+
"""
|
| 119 |
+
_version = 1
|
| 120 |
+
|
| 121 |
+
def __init__(
|
| 122 |
+
self,
|
| 123 |
+
num_embeddings: int,
|
| 124 |
+
embedding_dim: int,
|
| 125 |
+
padding_idx: Optional[int] = None,
|
| 126 |
+
max_norm: Optional[float] = None,
|
| 127 |
+
norm_type: float = 2.0,
|
| 128 |
+
scale_grad_by_freq: bool = False,
|
| 129 |
+
sparse: bool = False,
|
| 130 |
+
_weight: Optional[Tensor] = None,
|
| 131 |
+
dtype=torch.quint8,
|
| 132 |
+
) -> None:
|
| 133 |
+
super().__init__()
|
| 134 |
+
self.num_embeddings = num_embeddings
|
| 135 |
+
self.embedding_dim = embedding_dim
|
| 136 |
+
self.dtype = dtype
|
| 137 |
+
|
| 138 |
+
if _weight is None:
|
| 139 |
+
scales = torch.ones(num_embeddings, dtype=torch.float)
|
| 140 |
+
zero_points = torch.zeros(num_embeddings, dtype=torch.float)
|
| 141 |
+
qweight = torch._empty_per_channel_affine_quantized(
|
| 142 |
+
[num_embeddings, embedding_dim],
|
| 143 |
+
scales=scales,
|
| 144 |
+
zero_points=zero_points,
|
| 145 |
+
axis=0,
|
| 146 |
+
dtype=torch.quint8,
|
| 147 |
+
)
|
| 148 |
+
else:
|
| 149 |
+
assert list(_weight.shape) == [
|
| 150 |
+
num_embeddings,
|
| 151 |
+
embedding_dim,
|
| 152 |
+
], "Shape of weight does not match num_embeddings and embedding_dim"
|
| 153 |
+
qweight = _weight
|
| 154 |
+
|
| 155 |
+
self._packed_params = EmbeddingPackedParams(
|
| 156 |
+
num_embeddings, embedding_dim, dtype
|
| 157 |
+
)
|
| 158 |
+
self._packed_params.set_weight(qweight)
|
| 159 |
+
|
| 160 |
+
def forward(self, indices: Tensor) -> Tensor:
|
| 161 |
+
if self.dtype == torch.quint4x2:
|
| 162 |
+
return torch.ops.quantized.embedding_4bit(
|
| 163 |
+
self._packed_params._packed_weight, indices
|
| 164 |
+
)
|
| 165 |
+
else:
|
| 166 |
+
return torch.ops.quantized.embedding_byte(
|
| 167 |
+
self._packed_params._packed_weight, indices
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def _get_name(self):
|
| 171 |
+
return "QuantizedEmbedding"
|
| 172 |
+
|
| 173 |
+
def __repr__(self):
|
| 174 |
+
return _hide_packed_params_repr(self, EmbeddingPackedParams)
|
| 175 |
+
|
| 176 |
+
def extra_repr(self):
|
| 177 |
+
extra_repr_str = (
|
| 178 |
+
f"num_embeddings={self.num_embeddings}, embedding_dim={self.embedding_dim}, "
|
| 179 |
+
f"dtype={self._packed_params.dtype}, qscheme={self.weight().qscheme()}"
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
return extra_repr_str
|
| 183 |
+
|
| 184 |
+
def set_weight(self, w: torch.Tensor) -> None:
|
| 185 |
+
self._packed_params.set_weight(w)
|
| 186 |
+
|
| 187 |
+
def weight(self):
|
| 188 |
+
return self._packed_params._weight()
|
| 189 |
+
|
| 190 |
+
@classmethod
|
| 191 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 192 |
+
r"""Create a quantized embedding module from a float module
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
mod (Module): a float module, either produced by torch.ao.quantization
|
| 196 |
+
utilities or provided by user
|
| 197 |
+
"""
|
| 198 |
+
if hasattr(mod, "weight_fake_quant"):
|
| 199 |
+
assert type(mod) == torch.ao.nn.qat.Embedding, (
|
| 200 |
+
"nnq."
|
| 201 |
+
+ cls.__name__
|
| 202 |
+
+ ".from_float "
|
| 203 |
+
+ "with fake quant only works for "
|
| 204 |
+
+ torch.ao.nn.qat.Embedding.__name__
|
| 205 |
+
)
|
| 206 |
+
weight_observer = mod.weight_fake_quant
|
| 207 |
+
activation_post_process = mod.activation_post_process
|
| 208 |
+
else:
|
| 209 |
+
assert type(mod) == nn.Embedding, (
|
| 210 |
+
"nnq."
|
| 211 |
+
+ cls.__name__
|
| 212 |
+
+ ".from_float only works for "
|
| 213 |
+
+ nn.Embedding.__name__
|
| 214 |
+
)
|
| 215 |
+
assert hasattr(
|
| 216 |
+
mod, "qconfig"
|
| 217 |
+
), "Embedding input float module must have qconfig defined"
|
| 218 |
+
from torch.ao.quantization import float_qparams_weight_only_qconfig
|
| 219 |
+
|
| 220 |
+
if mod.qconfig is not None and mod.qconfig.weight is not None: # type: ignore[union-attr]
|
| 221 |
+
weight_observer = mod.qconfig.weight() # type: ignore[union-attr, operator]
|
| 222 |
+
else:
|
| 223 |
+
weight_observer = float_qparams_weight_only_qconfig.weight()
|
| 224 |
+
|
| 225 |
+
dtype = weight_observer.dtype
|
| 226 |
+
is_float_qparams_qconfig = (
|
| 227 |
+
weight_observer.qscheme == torch.per_channel_affine_float_qparams
|
| 228 |
+
)
|
| 229 |
+
assert (
|
| 230 |
+
is_float_qparams_qconfig
|
| 231 |
+
), "Embedding quantization is only supported with float_qparams_weight_only_qconfig."
|
| 232 |
+
|
| 233 |
+
assert (
|
| 234 |
+
dtype == torch.quint8 or dtype == torch.quint4x2
|
| 235 |
+
), f"The only supported dtype for nnq.Embedding is torch.quint8 and torch.quint4x2, got {dtype}"
|
| 236 |
+
|
| 237 |
+
# Run the observer to calculate qparams.
|
| 238 |
+
weight_observer(mod.weight)
|
| 239 |
+
qweight = _quantize_weight(mod.weight.float(), weight_observer)
|
| 240 |
+
|
| 241 |
+
# Create quantized Embedding module and pass in the quantized weight
|
| 242 |
+
qembedding = Embedding(mod.num_embeddings, mod.embedding_dim)
|
| 243 |
+
qembedding.set_weight(qweight)
|
| 244 |
+
return qembedding
|
| 245 |
+
|
| 246 |
+
@classmethod
|
| 247 |
+
def from_reference(cls, ref_embedding):
|
| 248 |
+
qembedding = cls(
|
| 249 |
+
ref_embedding.num_embeddings,
|
| 250 |
+
ref_embedding.embedding_dim,
|
| 251 |
+
ref_embedding.padding_idx,
|
| 252 |
+
ref_embedding.max_norm,
|
| 253 |
+
ref_embedding.norm_type,
|
| 254 |
+
ref_embedding.scale_grad_by_freq,
|
| 255 |
+
ref_embedding.sparse,
|
| 256 |
+
ref_embedding.get_quantized_weight(),
|
| 257 |
+
ref_embedding.weight_dtype,
|
| 258 |
+
)
|
| 259 |
+
return qembedding
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class EmbeddingBag(Embedding):
|
| 263 |
+
r"""
|
| 264 |
+
A quantized EmbeddingBag module with quantized packed weights as inputs.
|
| 265 |
+
We adopt the same interface as `torch.nn.EmbeddingBag`, please see
|
| 266 |
+
https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html for documentation.
|
| 267 |
+
|
| 268 |
+
Similar to :class:`~torch.nn.EmbeddingBag`, attributes will be randomly
|
| 269 |
+
initialized at module creation time and will be overwritten later
|
| 270 |
+
|
| 271 |
+
Attributes:
|
| 272 |
+
weight (Tensor): the non-learnable quantized weights of the module of
|
| 273 |
+
shape :math:`(\text{num\_embeddings}, \text{embedding\_dim})`.
|
| 274 |
+
|
| 275 |
+
Examples::
|
| 276 |
+
>>> m = nn.quantized.EmbeddingBag(num_embeddings=10, embedding_dim=12, include_last_offset=True, mode='sum')
|
| 277 |
+
>>> indices = torch.tensor([9, 6, 5, 7, 8, 8, 9, 2, 8, 6, 6, 9, 1, 6, 8, 8, 3, 2, 3, 6, 3, 6, 5, 7, 0, 8, 4, 6, 5, 8, 2, 3])
|
| 278 |
+
>>> offsets = torch.tensor([0, 19, 20, 28, 28, 32])
|
| 279 |
+
>>> output = m(indices, offsets)
|
| 280 |
+
>>> print(output.size())
|
| 281 |
+
torch.Size([5, 12])
|
| 282 |
+
|
| 283 |
+
"""
|
| 284 |
+
_version = 1
|
| 285 |
+
|
| 286 |
+
def __init__(
|
| 287 |
+
self,
|
| 288 |
+
num_embeddings: int,
|
| 289 |
+
embedding_dim: int,
|
| 290 |
+
max_norm: Optional[float] = None,
|
| 291 |
+
norm_type: float = 2.0,
|
| 292 |
+
scale_grad_by_freq: bool = False,
|
| 293 |
+
mode: str = "sum",
|
| 294 |
+
sparse: bool = False,
|
| 295 |
+
_weight: Optional[Tensor] = None,
|
| 296 |
+
include_last_offset: bool = False,
|
| 297 |
+
dtype=torch.quint8,
|
| 298 |
+
) -> None:
|
| 299 |
+
super().__init__(num_embeddings, embedding_dim, _weight=_weight, dtype=dtype)
|
| 300 |
+
|
| 301 |
+
self.mode = mode
|
| 302 |
+
self.pruned_weights = False
|
| 303 |
+
self.include_last_offset = include_last_offset
|
| 304 |
+
self.dtype = dtype
|
| 305 |
+
|
| 306 |
+
def forward(
|
| 307 |
+
self,
|
| 308 |
+
indices: Tensor,
|
| 309 |
+
offsets: Optional[Tensor] = None,
|
| 310 |
+
per_sample_weights: Optional[Tensor] = None,
|
| 311 |
+
compressed_indices_mapping: Optional[Tensor] = None,
|
| 312 |
+
) -> Tensor:
|
| 313 |
+
if self.dtype == torch.quint4x2:
|
| 314 |
+
return torch.ops.quantized.embedding_bag_4bit(
|
| 315 |
+
self._packed_params._packed_weight,
|
| 316 |
+
indices,
|
| 317 |
+
offsets,
|
| 318 |
+
False,
|
| 319 |
+
0,
|
| 320 |
+
self.pruned_weights,
|
| 321 |
+
per_sample_weights,
|
| 322 |
+
compressed_indices_mapping,
|
| 323 |
+
self.include_last_offset,
|
| 324 |
+
)
|
| 325 |
+
else:
|
| 326 |
+
return torch.ops.quantized.embedding_bag_byte(
|
| 327 |
+
self._packed_params._packed_weight,
|
| 328 |
+
indices,
|
| 329 |
+
offsets,
|
| 330 |
+
False,
|
| 331 |
+
0,
|
| 332 |
+
self.pruned_weights,
|
| 333 |
+
per_sample_weights,
|
| 334 |
+
compressed_indices_mapping,
|
| 335 |
+
self.include_last_offset,
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
def _get_name(self):
|
| 339 |
+
return "QuantizedEmbeddingBag"
|
| 340 |
+
|
| 341 |
+
@classmethod
|
| 342 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 343 |
+
r"""Create a quantized embedding_bag module from a float module
|
| 344 |
+
|
| 345 |
+
Args:
|
| 346 |
+
mod (Module): a float module, either produced by torch.ao.quantization
|
| 347 |
+
utilities or provided by user
|
| 348 |
+
"""
|
| 349 |
+
if hasattr(mod, "weight_fake_quant"):
|
| 350 |
+
weight_observer = mod.weight_fake_quant
|
| 351 |
+
else:
|
| 352 |
+
assert type(mod) == nn.EmbeddingBag, (
|
| 353 |
+
"nnq."
|
| 354 |
+
+ cls.__name__
|
| 355 |
+
+ ".from_float only works for "
|
| 356 |
+
+ nn.EmbeddingBag.__name__
|
| 357 |
+
)
|
| 358 |
+
assert hasattr(
|
| 359 |
+
mod, "qconfig"
|
| 360 |
+
), "EmbeddingBag input float module must have qconfig defined"
|
| 361 |
+
from torch.ao.quantization.qconfig import float_qparams_weight_only_qconfig
|
| 362 |
+
|
| 363 |
+
if mod.qconfig is not None and mod.qconfig.weight is not None: # type: ignore[union-attr]
|
| 364 |
+
weight_observer = mod.qconfig.weight() # type: ignore[union-attr, operator]
|
| 365 |
+
else:
|
| 366 |
+
weight_observer = float_qparams_weight_only_qconfig.weight()
|
| 367 |
+
|
| 368 |
+
dtype = weight_observer.dtype
|
| 369 |
+
is_float_qparams_qconfig = (
|
| 370 |
+
weight_observer.qscheme == torch.per_channel_affine_float_qparams
|
| 371 |
+
)
|
| 372 |
+
assert (
|
| 373 |
+
is_float_qparams_qconfig
|
| 374 |
+
), "EmbeddingBag quantization is only supported with float_qparams_weight_only_qconfig."
|
| 375 |
+
|
| 376 |
+
assert (
|
| 377 |
+
dtype == torch.quint8 or dtype == torch.quint4x2
|
| 378 |
+
), f"The only supported dtype for nnq.EmbeddingBag is torch.quint8 and torch.quint4x2, got {dtype}"
|
| 379 |
+
|
| 380 |
+
# Run the observer to calculate qparams.
|
| 381 |
+
weight_observer(mod.weight)
|
| 382 |
+
qweight = _quantize_weight(mod.weight.float(), weight_observer)
|
| 383 |
+
|
| 384 |
+
# Create quantized EmbeddingBag module and pass in the quantized weight
|
| 385 |
+
qembedding_bag = EmbeddingBag(
|
| 386 |
+
mod.num_embeddings, mod.embedding_dim, dtype=dtype
|
| 387 |
+
)
|
| 388 |
+
qembedding_bag.set_weight(qweight)
|
| 389 |
+
return qembedding_bag
|
| 390 |
+
|
| 391 |
+
@classmethod
|
| 392 |
+
def from_reference(cls, ref_embedding_bag):
|
| 393 |
+
qembedding_bag = cls(
|
| 394 |
+
ref_embedding_bag.num_embeddings,
|
| 395 |
+
ref_embedding_bag.embedding_dim,
|
| 396 |
+
ref_embedding_bag.max_norm,
|
| 397 |
+
ref_embedding_bag.norm_type,
|
| 398 |
+
ref_embedding_bag.scale_grad_by_freq,
|
| 399 |
+
ref_embedding_bag.mode,
|
| 400 |
+
ref_embedding_bag.sparse,
|
| 401 |
+
ref_embedding_bag.get_quantized_weight(),
|
| 402 |
+
ref_embedding_bag.include_last_offset,
|
| 403 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
from collections.abc import Iterable
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.ao.nn.intrinsic as nni
|
| 8 |
+
import torch.ao.nn.intrinsic.qat as nniqat
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from torch.nn.utils.fusion import fuse_linear_bn_weights
|
| 11 |
+
from torch.nn.utils.parametrize import type_before_parametrizations
|
| 12 |
+
|
| 13 |
+
from .utils import _hide_packed_params_repr, _quantize_weight, WeightedQuantizedModule
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__all__ = ["LinearPackedParams", "Linear"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class LinearPackedParams(torch.nn.Module):
|
| 20 |
+
_version = 3
|
| 21 |
+
|
| 22 |
+
def __init__(self, dtype=torch.qint8):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.dtype = dtype
|
| 25 |
+
if self.dtype == torch.qint8:
|
| 26 |
+
wq = torch._empty_affine_quantized(
|
| 27 |
+
[1, 1], scale=1.0, zero_point=0, dtype=torch.qint8
|
| 28 |
+
)
|
| 29 |
+
elif self.dtype == torch.float16:
|
| 30 |
+
wq = torch.zeros([1, 1], dtype=torch.float)
|
| 31 |
+
self.set_weight_bias(wq, None) # type: ignore[possibly-undefined]
|
| 32 |
+
|
| 33 |
+
@torch.jit.export
|
| 34 |
+
def set_weight_bias(
|
| 35 |
+
self, weight: torch.Tensor, bias: Optional[torch.Tensor]
|
| 36 |
+
) -> None:
|
| 37 |
+
if self.dtype == torch.qint8:
|
| 38 |
+
self._packed_params = torch.ops.quantized.linear_prepack(weight, bias)
|
| 39 |
+
elif self.dtype == torch.float16:
|
| 40 |
+
self._packed_params = torch.ops.quantized.linear_prepack_fp16(weight, bias)
|
| 41 |
+
else:
|
| 42 |
+
raise RuntimeError("Unsupported dtype on dynamic quantized linear!")
|
| 43 |
+
|
| 44 |
+
@torch.jit.export
|
| 45 |
+
def _weight_bias(self):
|
| 46 |
+
if self.dtype == torch.qint8:
|
| 47 |
+
return torch.ops.quantized.linear_unpack(self._packed_params)
|
| 48 |
+
elif self.dtype == torch.float16:
|
| 49 |
+
return torch.ops.quantized.linear_unpack_fp16(self._packed_params)
|
| 50 |
+
else:
|
| 51 |
+
raise RuntimeError("Unsupported dtype on dynamic quantized linear!")
|
| 52 |
+
|
| 53 |
+
def forward(self, x):
|
| 54 |
+
return x
|
| 55 |
+
|
| 56 |
+
# Version 1
|
| 57 |
+
# self
|
| 58 |
+
# |--- weight : Tensor
|
| 59 |
+
# |--- bias : Tensor
|
| 60 |
+
#
|
| 61 |
+
# Version 2
|
| 62 |
+
# self
|
| 63 |
+
# |--- weight : Tensor
|
| 64 |
+
# |--- bias : Tensor
|
| 65 |
+
# |--- dtype : torch.dtype
|
| 66 |
+
#
|
| 67 |
+
# Version 3
|
| 68 |
+
# self
|
| 69 |
+
# |--- _packed_params : (Tensor, Tensor) representing (weight, bias)
|
| 70 |
+
# of LinearPackedParams
|
| 71 |
+
# |--- dtype : torch.dtype
|
| 72 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
| 73 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
| 74 |
+
destination[prefix + "dtype"] = self.dtype
|
| 75 |
+
destination[prefix + "_packed_params"] = self._weight_bias()
|
| 76 |
+
|
| 77 |
+
def _load_from_state_dict(
|
| 78 |
+
self,
|
| 79 |
+
state_dict,
|
| 80 |
+
prefix,
|
| 81 |
+
local_metadata,
|
| 82 |
+
strict,
|
| 83 |
+
missing_keys,
|
| 84 |
+
unexpected_keys,
|
| 85 |
+
error_msgs,
|
| 86 |
+
):
|
| 87 |
+
version = local_metadata.get("version", None)
|
| 88 |
+
if version is None or version < 2:
|
| 89 |
+
self.dtype = torch.qint8
|
| 90 |
+
else:
|
| 91 |
+
self.dtype = state_dict[prefix + "dtype"]
|
| 92 |
+
state_dict.pop(prefix + "dtype")
|
| 93 |
+
|
| 94 |
+
if version is None or version < 3:
|
| 95 |
+
self.set_weight_bias(
|
| 96 |
+
state_dict[prefix + "weight"], state_dict[prefix + "bias"]
|
| 97 |
+
)
|
| 98 |
+
state_dict.pop(prefix + "weight")
|
| 99 |
+
state_dict.pop(prefix + "bias")
|
| 100 |
+
|
| 101 |
+
if version == 3:
|
| 102 |
+
weight, bias = state_dict[prefix + "_packed_params"]
|
| 103 |
+
state_dict.pop(prefix + "_packed_params")
|
| 104 |
+
self.set_weight_bias(weight, bias)
|
| 105 |
+
|
| 106 |
+
super()._load_from_state_dict(
|
| 107 |
+
state_dict,
|
| 108 |
+
prefix,
|
| 109 |
+
local_metadata,
|
| 110 |
+
False,
|
| 111 |
+
missing_keys,
|
| 112 |
+
unexpected_keys,
|
| 113 |
+
error_msgs,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
def __repr__(self):
|
| 117 |
+
return self._weight_bias().__repr__()
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class Linear(WeightedQuantizedModule):
|
| 121 |
+
r"""
|
| 122 |
+
A quantized linear module with quantized tensor as inputs and outputs.
|
| 123 |
+
We adopt the same interface as `torch.nn.Linear`, please see
|
| 124 |
+
https://pytorch.org/docs/stable/nn.html#torch.nn.Linear for documentation.
|
| 125 |
+
|
| 126 |
+
Similar to :class:`~torch.nn.Linear`, attributes will be randomly
|
| 127 |
+
initialized at module creation time and will be overwritten later
|
| 128 |
+
|
| 129 |
+
Attributes:
|
| 130 |
+
weight (Tensor): the non-learnable quantized weights of the module of
|
| 131 |
+
shape :math:`(\text{out\_features}, \text{in\_features})`.
|
| 132 |
+
bias (Tensor): the non-learnable bias of the module of shape :math:`(\text{out\_features})`.
|
| 133 |
+
If :attr:`bias` is ``True``, the values are initialized to zero.
|
| 134 |
+
scale: `scale` parameter of output Quantized Tensor, type: double
|
| 135 |
+
zero_point: `zero_point` parameter for output Quantized Tensor, type: long
|
| 136 |
+
|
| 137 |
+
Examples::
|
| 138 |
+
|
| 139 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 140 |
+
>>> m = nn.quantized.Linear(20, 30)
|
| 141 |
+
>>> input = torch.randn(128, 20)
|
| 142 |
+
>>> # xdoctest: +SKIP
|
| 143 |
+
>>> input = torch.quantize_per_tensor(input, 1.0, 0, torch.quint8)
|
| 144 |
+
>>> output = m(input)
|
| 145 |
+
>>> print(output.size())
|
| 146 |
+
torch.Size([128, 30])
|
| 147 |
+
"""
|
| 148 |
+
_version = 3
|
| 149 |
+
_FLOAT_MODULE = (nn.Linear, nn.modules.linear.NonDynamicallyQuantizableLinear)
|
| 150 |
+
|
| 151 |
+
def __init__(self, in_features, out_features, bias_=True, dtype=torch.qint8):
|
| 152 |
+
super().__init__()
|
| 153 |
+
# We don't muck around with buffers or attributes or anything here
|
| 154 |
+
# to keep the module simple. *everything* is simply a Python attribute.
|
| 155 |
+
# Serialization logic is explicitly handled in the below serialization and
|
| 156 |
+
# deserialization modules
|
| 157 |
+
self.in_features = in_features
|
| 158 |
+
self.out_features = out_features
|
| 159 |
+
bias = None
|
| 160 |
+
if bias_:
|
| 161 |
+
bias = torch.zeros(out_features, dtype=torch.float)
|
| 162 |
+
|
| 163 |
+
if dtype == torch.qint8:
|
| 164 |
+
qweight = torch._empty_affine_quantized(
|
| 165 |
+
[out_features, in_features], scale=1, zero_point=0, dtype=torch.qint8
|
| 166 |
+
)
|
| 167 |
+
elif dtype == torch.float16:
|
| 168 |
+
qweight = torch.zeros([out_features, in_features], dtype=torch.float)
|
| 169 |
+
else:
|
| 170 |
+
raise RuntimeError("Unsupported dtype specified for quantized Linear!")
|
| 171 |
+
|
| 172 |
+
self._packed_params = LinearPackedParams(dtype)
|
| 173 |
+
self._packed_params.set_weight_bias(qweight, bias)
|
| 174 |
+
self.scale = 1.0
|
| 175 |
+
self.zero_point = 0
|
| 176 |
+
|
| 177 |
+
def _get_name(self):
|
| 178 |
+
return "QuantizedLinear"
|
| 179 |
+
|
| 180 |
+
def extra_repr(self):
|
| 181 |
+
return (
|
| 182 |
+
f"in_features={self.in_features}, out_features={self.out_features}, scale={self.scale}, "
|
| 183 |
+
f"zero_point={self.zero_point}, qscheme={self.weight().qscheme()}"
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
def __repr__(self):
|
| 187 |
+
return _hide_packed_params_repr(self, LinearPackedParams)
|
| 188 |
+
|
| 189 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 190 |
+
return torch.ops.quantized.linear(
|
| 191 |
+
x, self._packed_params._packed_params, self.scale, self.zero_point
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
# ===== Serialization methods =====
|
| 195 |
+
# The special consideration here is that we have to unpack the weights into their
|
| 196 |
+
# regular QTensor form for serialization. Packed weights should not live
|
| 197 |
+
# outside the process in which they were created, rather they should be derived
|
| 198 |
+
# from the QTensor weight.
|
| 199 |
+
#
|
| 200 |
+
# Version 1
|
| 201 |
+
# self
|
| 202 |
+
# |--- scale : float
|
| 203 |
+
# |--- zero_point : int
|
| 204 |
+
# |--- weight : Tensor
|
| 205 |
+
# |--- bias : Tensor
|
| 206 |
+
#
|
| 207 |
+
# Version 2
|
| 208 |
+
# self
|
| 209 |
+
# |--- scale : float
|
| 210 |
+
# |--- zero_point : int
|
| 211 |
+
# |--- _packed_params : Module
|
| 212 |
+
# |--- weight : Tensor
|
| 213 |
+
# |--- bias : Tensor
|
| 214 |
+
#
|
| 215 |
+
# Version 3
|
| 216 |
+
# self
|
| 217 |
+
# |--- scale : float
|
| 218 |
+
# |--- zero_point : int
|
| 219 |
+
# |--- _packed_params : Module
|
| 220 |
+
# |--- _packed_params : (Tensor, Tensor) representing weight, bias
|
| 221 |
+
# of LinearPackedParams C++ struct
|
| 222 |
+
#
|
| 223 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
| 224 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
| 225 |
+
destination[prefix + "scale"] = torch.tensor(self.scale)
|
| 226 |
+
destination[prefix + "zero_point"] = torch.tensor(self.zero_point)
|
| 227 |
+
|
| 228 |
+
# ===== Deserialization methods =====
|
| 229 |
+
# Counterpart to the serialization methods, we must pack the serialized QTensor
|
| 230 |
+
# weight into its packed format for use by the FBGEMM ops.
|
| 231 |
+
def _load_from_state_dict(
|
| 232 |
+
self,
|
| 233 |
+
state_dict,
|
| 234 |
+
prefix,
|
| 235 |
+
local_metadata,
|
| 236 |
+
strict,
|
| 237 |
+
missing_keys,
|
| 238 |
+
unexpected_keys,
|
| 239 |
+
error_msgs,
|
| 240 |
+
):
|
| 241 |
+
self.scale = float(state_dict[prefix + "scale"])
|
| 242 |
+
state_dict.pop(prefix + "scale")
|
| 243 |
+
|
| 244 |
+
self.zero_point = int(state_dict[prefix + "zero_point"])
|
| 245 |
+
state_dict.pop(prefix + "zero_point")
|
| 246 |
+
|
| 247 |
+
version = local_metadata.get("version", None)
|
| 248 |
+
|
| 249 |
+
if version is None or version == 1:
|
| 250 |
+
# We moved the parameters into a LinearPackedParameters submodule
|
| 251 |
+
weight = state_dict.pop(prefix + "weight")
|
| 252 |
+
bias = state_dict.pop(prefix + "bias")
|
| 253 |
+
state_dict.update(
|
| 254 |
+
{
|
| 255 |
+
prefix + "_packed_params.weight": weight,
|
| 256 |
+
prefix + "_packed_params.bias": bias,
|
| 257 |
+
}
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
super()._load_from_state_dict(
|
| 261 |
+
state_dict,
|
| 262 |
+
prefix,
|
| 263 |
+
local_metadata,
|
| 264 |
+
False,
|
| 265 |
+
missing_keys,
|
| 266 |
+
unexpected_keys,
|
| 267 |
+
error_msgs,
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# Function rather than property to make sure that JIT serialization doesn't
|
| 271 |
+
# register this as an attribute
|
| 272 |
+
def _weight_bias(self):
|
| 273 |
+
return self._packed_params._weight_bias()
|
| 274 |
+
|
| 275 |
+
def weight(self):
|
| 276 |
+
return self._weight_bias()[0]
|
| 277 |
+
|
| 278 |
+
def bias(self):
|
| 279 |
+
return self._weight_bias()[1]
|
| 280 |
+
|
| 281 |
+
def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None:
|
| 282 |
+
self._packed_params.set_weight_bias(w, b)
|
| 283 |
+
|
| 284 |
+
@classmethod
|
| 285 |
+
def from_float(cls, mod, use_precomputed_fake_quant=False):
|
| 286 |
+
r"""Create a quantized module from an observed float module
|
| 287 |
+
|
| 288 |
+
Args:
|
| 289 |
+
mod (Module): a float module, either produced by torch.ao.quantization
|
| 290 |
+
utilities or provided by the user
|
| 291 |
+
use_precomputed_fake_quant (bool): if True, the module will reuse min/max
|
| 292 |
+
values from the precomputed fake quant module.
|
| 293 |
+
"""
|
| 294 |
+
if hasattr(mod, "weight_fake_quant"):
|
| 295 |
+
if type_before_parametrizations(mod) == nniqat.LinearBn1d:
|
| 296 |
+
mod.weight, mod.bias = fuse_linear_bn_weights(
|
| 297 |
+
mod.weight,
|
| 298 |
+
mod.bias,
|
| 299 |
+
mod.bn.running_mean,
|
| 300 |
+
mod.bn.running_var,
|
| 301 |
+
mod.bn.eps,
|
| 302 |
+
mod.bn.weight,
|
| 303 |
+
mod.bn.bias,
|
| 304 |
+
)
|
| 305 |
+
weight_post_process = mod.weight_fake_quant
|
| 306 |
+
activation_post_process = mod.activation_post_process
|
| 307 |
+
else:
|
| 308 |
+
# This function does not participate in JIT, so it is OK to ignore
|
| 309 |
+
# the type mismatch in assignment. Also, mypy has an issue with
|
| 310 |
+
# iterables not being implemented, so we are ignoring those too.
|
| 311 |
+
if not isinstance(cls._FLOAT_MODULE, Iterable):
|
| 312 |
+
cls._FLOAT_MODULE = [cls._FLOAT_MODULE] # type: ignore[assignment]
|
| 313 |
+
supported_modules = ", ".join([float_mod.__name__ for float_mod in cls._FLOAT_MODULE]) # type: ignore[attr-defined]
|
| 314 |
+
error_msg = f"nnq.{cls.__name__}.from_float only works for {supported_modules}, but got: {type(mod)}"
|
| 315 |
+
assert type_before_parametrizations(mod) in cls._FLOAT_MODULE, error_msg.format() # type: ignore[attr-defined]
|
| 316 |
+
assert hasattr(
|
| 317 |
+
mod, "qconfig"
|
| 318 |
+
), "Input float module must have qconfig defined"
|
| 319 |
+
activation_post_process = mod.activation_post_process
|
| 320 |
+
if type_before_parametrizations(mod) == nni.LinearReLU:
|
| 321 |
+
mod = mod[0]
|
| 322 |
+
weight_post_process = (
|
| 323 |
+
mod.qconfig.weight()
|
| 324 |
+
if not hasattr(mod, "weight_fake_quant")
|
| 325 |
+
else mod.weight_fake_quant
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
if not use_precomputed_fake_quant:
|
| 329 |
+
# Observer may not have been called yet
|
| 330 |
+
# Observer might have been called in the previous stage via PTQ algorithm e.g. AdaRound
|
| 331 |
+
weight_post_process(mod.weight)
|
| 332 |
+
dtype = weight_post_process.dtype
|
| 333 |
+
act_scale, act_zp = activation_post_process.calculate_qparams()
|
| 334 |
+
assert dtype == torch.qint8, "Weight observer must have dtype torch.qint8"
|
| 335 |
+
qweight = _quantize_weight(mod.weight.float(), weight_post_process)
|
| 336 |
+
qlinear = cls(mod.in_features, mod.out_features, dtype=dtype)
|
| 337 |
+
qlinear.set_weight_bias(qweight, mod.bias)
|
| 338 |
+
qlinear.scale = float(act_scale)
|
| 339 |
+
qlinear.zero_point = int(act_zp)
|
| 340 |
+
return qlinear
|
| 341 |
+
|
| 342 |
+
@classmethod
|
| 343 |
+
def from_reference(cls, ref_qlinear, output_scale, output_zero_point):
|
| 344 |
+
r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module
|
| 345 |
+
|
| 346 |
+
Args:
|
| 347 |
+
ref_qlinear (Module): a reference quantized linear module, either produced by torch.ao.quantization
|
| 348 |
+
utilities or provided by the user
|
| 349 |
+
output_scale (float): scale for output Tensor
|
| 350 |
+
output_zero_point (int): zero point for output Tensor
|
| 351 |
+
"""
|
| 352 |
+
qlinear = cls(ref_qlinear.in_features, ref_qlinear.out_features)
|
| 353 |
+
qweight = ref_qlinear.get_quantized_weight()
|
| 354 |
+
qlinear.set_weight_bias(qweight, ref_qlinear.bias)
|
| 355 |
+
|
| 356 |
+
qlinear.scale = float(output_scale)
|
| 357 |
+
qlinear.zero_point = int(output_zero_point)
|
| 358 |
+
return qlinear
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/utils.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import abc
|
| 3 |
+
import collections
|
| 4 |
+
import itertools
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.nn.modules.module import _addindent
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
"WeightedQuantizedModule",
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class WeightedQuantizedModule(torch.nn.Module, metaclass=abc.ABCMeta):
|
| 16 |
+
"""Wrapper for quantized modules than can be lowered from reference modules."""
|
| 17 |
+
|
| 18 |
+
@classmethod
|
| 19 |
+
@abc.abstractmethod
|
| 20 |
+
def from_reference(cls, ref_module, output_scale, output_zero_point):
|
| 21 |
+
raise NotImplementedError
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _get_weight_observer(observer):
|
| 25 |
+
# FakeQuantize observer
|
| 26 |
+
if hasattr(observer, "activation_post_process"):
|
| 27 |
+
observer = observer.activation_post_process
|
| 28 |
+
# UniformQuantizationObserverBase observer
|
| 29 |
+
return observer
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _needs_weight_clamping(observer, dtype):
|
| 33 |
+
observer = _get_weight_observer(observer)
|
| 34 |
+
if dtype in [torch.qint8, torch.quint8, torch.qint32]:
|
| 35 |
+
info = torch.iinfo(dtype)
|
| 36 |
+
return observer.quant_min > info.min or observer.quant_max < info.max
|
| 37 |
+
return False
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _clamp_weights(qweight, observer, scale, zp):
|
| 41 |
+
if not _needs_weight_clamping(observer, qweight.dtype):
|
| 42 |
+
return qweight
|
| 43 |
+
|
| 44 |
+
observer = _get_weight_observer(observer)
|
| 45 |
+
min_, max_ = observer.quant_min, observer.quant_max
|
| 46 |
+
|
| 47 |
+
# Doing this because can't use torch.ops.quantized.clamp() with per_channel qscheme yet.
|
| 48 |
+
qw_int_max = torch.clone(qweight.int_repr()).fill_(max_)
|
| 49 |
+
qw_int_min = torch.clone(qweight.int_repr()).fill_(min_)
|
| 50 |
+
qw_int = torch.minimum(torch.maximum(qweight.int_repr(), qw_int_min), qw_int_max)
|
| 51 |
+
|
| 52 |
+
if observer.qscheme in [torch.per_tensor_symmetric, torch.per_tensor_affine]:
|
| 53 |
+
qweight = torch._make_per_tensor_quantized_tensor(
|
| 54 |
+
qw_int, scale.item(), zp.item()
|
| 55 |
+
)
|
| 56 |
+
elif observer.qscheme in [
|
| 57 |
+
torch.per_channel_symmetric,
|
| 58 |
+
torch.per_channel_affine,
|
| 59 |
+
torch.per_channel_affine_float_qparams,
|
| 60 |
+
]:
|
| 61 |
+
qweight = torch._make_per_channel_quantized_tensor(
|
| 62 |
+
qw_int, scale, zp, axis=observer.ch_axis
|
| 63 |
+
)
|
| 64 |
+
else:
|
| 65 |
+
raise ValueError("Unexpected qscheme " + observer.qscheme)
|
| 66 |
+
return qweight
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _quantize_weight(float_wt, observer):
|
| 70 |
+
wt_scale, wt_zp = observer.calculate_qparams()
|
| 71 |
+
if observer.qscheme in [torch.per_tensor_symmetric, torch.per_tensor_affine]:
|
| 72 |
+
qweight = torch.quantize_per_tensor(
|
| 73 |
+
float_wt, float(wt_scale), int(wt_zp), torch.qint8
|
| 74 |
+
)
|
| 75 |
+
qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp)
|
| 76 |
+
elif observer.qscheme in [torch.per_channel_symmetric, torch.per_channel_affine]:
|
| 77 |
+
wt_axis = observer.ch_axis
|
| 78 |
+
qweight = torch.quantize_per_channel(
|
| 79 |
+
float_wt,
|
| 80 |
+
wt_scale.to(torch.double),
|
| 81 |
+
wt_zp.to(torch.int64),
|
| 82 |
+
wt_axis,
|
| 83 |
+
torch.qint8,
|
| 84 |
+
)
|
| 85 |
+
qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp)
|
| 86 |
+
elif observer.qscheme in [torch.per_channel_affine_float_qparams]:
|
| 87 |
+
qweight = torch.quantize_per_channel(
|
| 88 |
+
float_wt,
|
| 89 |
+
wt_scale.to(torch.float),
|
| 90 |
+
wt_zp.to(torch.float),
|
| 91 |
+
observer.ch_axis,
|
| 92 |
+
observer.dtype,
|
| 93 |
+
)
|
| 94 |
+
qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp)
|
| 95 |
+
else:
|
| 96 |
+
raise ValueError("Unexpected qscheme " + observer.qscheme)
|
| 97 |
+
return qweight
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _ntuple_from_first(n):
|
| 101 |
+
"""Converts the argument to a tuple of size n
|
| 102 |
+
with the first element repeated."""
|
| 103 |
+
|
| 104 |
+
def parse(x):
|
| 105 |
+
while isinstance(x, collections.abc.Sequence):
|
| 106 |
+
if len(x) == n:
|
| 107 |
+
break
|
| 108 |
+
x = x[0]
|
| 109 |
+
return tuple(itertools.repeat(x, n))
|
| 110 |
+
|
| 111 |
+
return parse
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _hide_packed_params_repr(self, params):
|
| 115 |
+
# We don't want to show `PackedParams` children, hence custom
|
| 116 |
+
# `__repr__`. This is the same as nn.Module.__repr__, except the check
|
| 117 |
+
# for the `params module`.
|
| 118 |
+
extra_lines = []
|
| 119 |
+
extra_repr = self.extra_repr()
|
| 120 |
+
# empty string will be split into list ['']
|
| 121 |
+
if extra_repr:
|
| 122 |
+
extra_lines = extra_repr.split("\n")
|
| 123 |
+
child_lines = []
|
| 124 |
+
for key, module in self._modules.items():
|
| 125 |
+
if isinstance(module, params):
|
| 126 |
+
continue
|
| 127 |
+
mod_str = repr(module)
|
| 128 |
+
mod_str = _addindent(mod_str, 2)
|
| 129 |
+
child_lines.append("(" + key + "): " + mod_str)
|
| 130 |
+
lines = extra_lines + child_lines
|
| 131 |
+
|
| 132 |
+
main_str = self._get_name() + "("
|
| 133 |
+
if lines:
|
| 134 |
+
# simple one-liner info, which most builtin Modules will use
|
| 135 |
+
if len(extra_lines) == 1 and not child_lines:
|
| 136 |
+
main_str += extra_lines[0]
|
| 137 |
+
else:
|
| 138 |
+
main_str += "\n " + "\n ".join(lines) + "\n"
|
| 139 |
+
|
| 140 |
+
main_str += ")"
|
| 141 |
+
return main_str
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
_pair_from_first = _ntuple_from_first(2)
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .modules import * # noqa: F403
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__all__ = [
|
| 5 |
+
"Linear",
|
| 6 |
+
"Conv1d",
|
| 7 |
+
"Conv2d",
|
| 8 |
+
"Conv3d",
|
| 9 |
+
"ConvTranspose1d",
|
| 10 |
+
"ConvTranspose2d",
|
| 11 |
+
"ConvTranspose3d",
|
| 12 |
+
"RNNCell",
|
| 13 |
+
"LSTMCell",
|
| 14 |
+
"GRUCell",
|
| 15 |
+
"LSTM",
|
| 16 |
+
"GRU",
|
| 17 |
+
"Embedding",
|
| 18 |
+
"EmbeddingBag",
|
| 19 |
+
]
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .conv import (
|
| 2 |
+
Conv1d,
|
| 3 |
+
Conv2d,
|
| 4 |
+
Conv3d,
|
| 5 |
+
ConvTranspose1d,
|
| 6 |
+
ConvTranspose2d,
|
| 7 |
+
ConvTranspose3d,
|
| 8 |
+
)
|
| 9 |
+
from .linear import Linear
|
| 10 |
+
from .rnn import GRU, GRUCell, LSTM, LSTMCell, RNNCell
|
| 11 |
+
from .sparse import Embedding, EmbeddingBag
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"Linear",
|
| 16 |
+
"Conv1d",
|
| 17 |
+
"Conv2d",
|
| 18 |
+
"Conv3d",
|
| 19 |
+
"ConvTranspose1d",
|
| 20 |
+
"ConvTranspose2d",
|
| 21 |
+
"ConvTranspose3d",
|
| 22 |
+
"RNNCell",
|
| 23 |
+
"LSTMCell",
|
| 24 |
+
"GRUCell",
|
| 25 |
+
"LSTM",
|
| 26 |
+
"GRU",
|
| 27 |
+
"Embedding",
|
| 28 |
+
"EmbeddingBag",
|
| 29 |
+
]
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/linear.cpython-310.pyc
ADDED
|
Binary file (2.51 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/conv.py
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ional as F
|
| 7 |
+
from torch.nn.common_types import _size_1_t
|
| 8 |
+
|
| 9 |
+
from .utils import ReferenceQuantizedModule
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"Conv1d",
|
| 14 |
+
"Conv2d",
|
| 15 |
+
"Conv3d",
|
| 16 |
+
"ConvTranspose1d",
|
| 17 |
+
"ConvTranspose2d",
|
| 18 |
+
"ConvTranspose3d",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class _ConvNd(torch.nn.modules.conv._ConvNd, ReferenceQuantizedModule):
|
| 23 |
+
"""A reference version of nn.quantized.Conv2d
|
| 24 |
+
we will not pack the parameters in this module, since weight packing is an
|
| 25 |
+
optimization for quantized backends supported in PyTorch (fbgemm/qnnpack),
|
| 26 |
+
this is useful when user want to use this module in other backends like Glow.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
__annotations__ = {"bias": Optional[torch.Tensor]}
|
| 30 |
+
_IS_REFERENCE = True
|
| 31 |
+
|
| 32 |
+
@staticmethod
|
| 33 |
+
def from_float(cls, float_conv, weight_qparams):
|
| 34 |
+
qref_conv = cls(
|
| 35 |
+
float_conv.in_channels,
|
| 36 |
+
float_conv.out_channels,
|
| 37 |
+
float_conv.kernel_size, # type: ignore[arg-type]
|
| 38 |
+
float_conv.stride, # type: ignore[arg-type]
|
| 39 |
+
float_conv.padding, # type: ignore[arg-type]
|
| 40 |
+
float_conv.dilation, # type: ignore[arg-type]
|
| 41 |
+
float_conv.groups,
|
| 42 |
+
float_conv.bias is not None, # type: ignore[arg-type]
|
| 43 |
+
float_conv.padding_mode,
|
| 44 |
+
device=float_conv.weight.device,
|
| 45 |
+
dtype=float_conv.weight.dtype,
|
| 46 |
+
weight_qparams=weight_qparams,
|
| 47 |
+
)
|
| 48 |
+
qref_conv.weight = torch.nn.Parameter(float_conv.weight.detach())
|
| 49 |
+
if float_conv.bias is not None:
|
| 50 |
+
qref_conv.bias = torch.nn.Parameter(float_conv.bias.detach())
|
| 51 |
+
return qref_conv
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class Conv1d(_ConvNd, nn.Conv1d):
|
| 55 |
+
def __init__(
|
| 56 |
+
self,
|
| 57 |
+
in_channels: int,
|
| 58 |
+
out_channels: int,
|
| 59 |
+
kernel_size: _size_1_t,
|
| 60 |
+
stride: _size_1_t = 1,
|
| 61 |
+
padding: _size_1_t = 0,
|
| 62 |
+
dilation: _size_1_t = 1,
|
| 63 |
+
groups: int = 1,
|
| 64 |
+
bias: bool = True,
|
| 65 |
+
padding_mode: str = "zeros",
|
| 66 |
+
device=None,
|
| 67 |
+
dtype=None,
|
| 68 |
+
weight_qparams: Optional[Dict[str, Any]] = None,
|
| 69 |
+
):
|
| 70 |
+
nn.Conv1d.__init__(
|
| 71 |
+
self,
|
| 72 |
+
in_channels,
|
| 73 |
+
out_channels,
|
| 74 |
+
kernel_size,
|
| 75 |
+
stride,
|
| 76 |
+
padding,
|
| 77 |
+
dilation,
|
| 78 |
+
groups,
|
| 79 |
+
bias,
|
| 80 |
+
padding_mode,
|
| 81 |
+
device,
|
| 82 |
+
dtype,
|
| 83 |
+
)
|
| 84 |
+
self._init_weight_qparams(weight_qparams, device)
|
| 85 |
+
|
| 86 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 87 |
+
"""
|
| 88 |
+
we have:
|
| 89 |
+
w(float) -- quant - dequant \
|
| 90 |
+
x(float) ------------- F.conv1d ---
|
| 91 |
+
|
| 92 |
+
In the full model, we will see
|
| 93 |
+
w(float) -- quant - *dequant \
|
| 94 |
+
x -- quant --- *dequant -- *F.conv1d --- *quant - dequant
|
| 95 |
+
and the backend should be able to fuse the ops with `*` into a quantized conv1d
|
| 96 |
+
"""
|
| 97 |
+
weight_quant_dequant = self.get_weight()
|
| 98 |
+
result = F.conv1d(
|
| 99 |
+
x,
|
| 100 |
+
weight_quant_dequant,
|
| 101 |
+
self.bias,
|
| 102 |
+
self.stride,
|
| 103 |
+
self.padding,
|
| 104 |
+
self.dilation,
|
| 105 |
+
self.groups,
|
| 106 |
+
)
|
| 107 |
+
return result
|
| 108 |
+
|
| 109 |
+
def _get_name(self):
|
| 110 |
+
return "QuantizedConv1d(Reference)"
|
| 111 |
+
|
| 112 |
+
@classmethod
|
| 113 |
+
def from_float(cls, float_conv, weight_qparams):
|
| 114 |
+
return _ConvNd.from_float(cls, float_conv, weight_qparams)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class Conv2d(_ConvNd, nn.Conv2d):
|
| 118 |
+
def __init__(
|
| 119 |
+
self,
|
| 120 |
+
in_channels,
|
| 121 |
+
out_channels,
|
| 122 |
+
kernel_size,
|
| 123 |
+
stride=1,
|
| 124 |
+
padding=0,
|
| 125 |
+
dilation=1,
|
| 126 |
+
groups=1,
|
| 127 |
+
bias=True,
|
| 128 |
+
padding_mode="zeros",
|
| 129 |
+
device=None,
|
| 130 |
+
dtype=None,
|
| 131 |
+
weight_qparams: Optional[Dict[str, Any]] = None,
|
| 132 |
+
):
|
| 133 |
+
nn.Conv2d.__init__(
|
| 134 |
+
self,
|
| 135 |
+
in_channels,
|
| 136 |
+
out_channels,
|
| 137 |
+
kernel_size,
|
| 138 |
+
stride,
|
| 139 |
+
padding,
|
| 140 |
+
dilation,
|
| 141 |
+
groups,
|
| 142 |
+
bias,
|
| 143 |
+
padding_mode,
|
| 144 |
+
device,
|
| 145 |
+
dtype,
|
| 146 |
+
)
|
| 147 |
+
self._init_weight_qparams(weight_qparams, device)
|
| 148 |
+
|
| 149 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 150 |
+
"""
|
| 151 |
+
we have:
|
| 152 |
+
w(float) -- quant - dequant \
|
| 153 |
+
x(float) ------------- F.conv2d ---
|
| 154 |
+
|
| 155 |
+
In the full model, we will see
|
| 156 |
+
w(float) -- quant - *dequant \
|
| 157 |
+
x -- quant --- *dequant -- *F.conv2d --- *quant - dequant
|
| 158 |
+
and the backend should be able to fuse the ops with `*` into a quantized conv2d
|
| 159 |
+
"""
|
| 160 |
+
weight_quant_dequant = self.get_weight()
|
| 161 |
+
result = F.conv2d(
|
| 162 |
+
x,
|
| 163 |
+
weight_quant_dequant,
|
| 164 |
+
self.bias,
|
| 165 |
+
self.stride,
|
| 166 |
+
self.padding,
|
| 167 |
+
self.dilation,
|
| 168 |
+
self.groups,
|
| 169 |
+
)
|
| 170 |
+
return result
|
| 171 |
+
|
| 172 |
+
def _get_name(self):
|
| 173 |
+
return "QuantizedConv2d(Reference)"
|
| 174 |
+
|
| 175 |
+
@classmethod
|
| 176 |
+
def from_float(cls, float_conv, weight_qparams):
|
| 177 |
+
return _ConvNd.from_float(cls, float_conv, weight_qparams)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class Conv3d(_ConvNd, nn.Conv3d):
|
| 181 |
+
def __init__(
|
| 182 |
+
self,
|
| 183 |
+
in_channels,
|
| 184 |
+
out_channels,
|
| 185 |
+
kernel_size,
|
| 186 |
+
stride=1,
|
| 187 |
+
padding=0,
|
| 188 |
+
dilation=1,
|
| 189 |
+
groups=1,
|
| 190 |
+
bias=True,
|
| 191 |
+
padding_mode="zeros",
|
| 192 |
+
device=None,
|
| 193 |
+
dtype=None,
|
| 194 |
+
weight_qparams: Optional[Dict[str, Any]] = None,
|
| 195 |
+
):
|
| 196 |
+
nn.Conv3d.__init__(
|
| 197 |
+
self,
|
| 198 |
+
in_channels,
|
| 199 |
+
out_channels,
|
| 200 |
+
kernel_size,
|
| 201 |
+
stride,
|
| 202 |
+
padding,
|
| 203 |
+
dilation,
|
| 204 |
+
groups,
|
| 205 |
+
bias,
|
| 206 |
+
padding_mode,
|
| 207 |
+
device,
|
| 208 |
+
dtype,
|
| 209 |
+
)
|
| 210 |
+
self._init_weight_qparams(weight_qparams, device)
|
| 211 |
+
|
| 212 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 213 |
+
"""
|
| 214 |
+
we have:
|
| 215 |
+
w(float) -- quant - dequant \
|
| 216 |
+
x(float) ------------- F.conv3d ---
|
| 217 |
+
|
| 218 |
+
In the full model, we will see
|
| 219 |
+
w(float) -- quant - *dequant \
|
| 220 |
+
x -- quant --- *dequant -- *F.conv3d --- *quant - dequant
|
| 221 |
+
and the backend should be able to fuse the ops with `*` into a quantized conv3d
|
| 222 |
+
"""
|
| 223 |
+
weight_quant_dequant = self.get_weight()
|
| 224 |
+
result = F.conv3d(
|
| 225 |
+
x,
|
| 226 |
+
weight_quant_dequant,
|
| 227 |
+
self.bias,
|
| 228 |
+
self.stride,
|
| 229 |
+
self.padding,
|
| 230 |
+
self.dilation,
|
| 231 |
+
self.groups,
|
| 232 |
+
)
|
| 233 |
+
return result
|
| 234 |
+
|
| 235 |
+
def _get_name(self):
|
| 236 |
+
return "QuantizedConv3d(Reference)"
|
| 237 |
+
|
| 238 |
+
@classmethod
|
| 239 |
+
def from_float(cls, float_conv, weight_qparams):
|
| 240 |
+
return _ConvNd.from_float(cls, float_conv, weight_qparams)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class _ConvTransposeNd(_ConvNd, torch.nn.modules.conv._ConvTransposeNd):
|
| 244 |
+
"""A reference version of nn.quantized.ConvTranspose2d
|
| 245 |
+
we will not pack the parameters in this module, since weight packing is an
|
| 246 |
+
optimization for quantized backends supported in PyTorch (fbgemm/qnnpack),
|
| 247 |
+
this is useful when user want to use this module in other backends like Glow.
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
@staticmethod
|
| 251 |
+
def from_float(cls, float_conv, weight_qparams):
|
| 252 |
+
qref_conv = cls(
|
| 253 |
+
float_conv.in_channels,
|
| 254 |
+
float_conv.out_channels,
|
| 255 |
+
float_conv.kernel_size, # type: ignore[arg-type]
|
| 256 |
+
float_conv.stride, # type: ignore[arg-type]
|
| 257 |
+
float_conv.padding, # type: ignore[arg-type]
|
| 258 |
+
float_conv.output_padding, # type: ignore[arg-type]
|
| 259 |
+
float_conv.groups,
|
| 260 |
+
float_conv.bias is not None, # type: ignore[arg-type]
|
| 261 |
+
float_conv.dilation, # type: ignore[arg-type]
|
| 262 |
+
float_conv.padding_mode,
|
| 263 |
+
device=float_conv.weight.device,
|
| 264 |
+
dtype=float_conv.weight.dtype,
|
| 265 |
+
weight_qparams=weight_qparams,
|
| 266 |
+
)
|
| 267 |
+
qref_conv.weight = torch.nn.Parameter(float_conv.weight.detach())
|
| 268 |
+
if float_conv.bias is not None:
|
| 269 |
+
qref_conv.bias = torch.nn.Parameter(float_conv.bias.detach())
|
| 270 |
+
return qref_conv
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class ConvTranspose1d(_ConvTransposeNd, nn.ConvTranspose1d):
|
| 274 |
+
def __init__(
|
| 275 |
+
self,
|
| 276 |
+
in_channels: int,
|
| 277 |
+
out_channels: int,
|
| 278 |
+
kernel_size: _size_1_t,
|
| 279 |
+
stride: _size_1_t = 1,
|
| 280 |
+
padding: _size_1_t = 0,
|
| 281 |
+
output_padding: _size_1_t = 0,
|
| 282 |
+
groups: int = 1,
|
| 283 |
+
bias: bool = True,
|
| 284 |
+
dilation: _size_1_t = 1,
|
| 285 |
+
padding_mode: str = "zeros",
|
| 286 |
+
device=None,
|
| 287 |
+
dtype=None,
|
| 288 |
+
weight_qparams: Optional[Dict[str, Any]] = None,
|
| 289 |
+
):
|
| 290 |
+
nn.ConvTranspose1d.__init__(
|
| 291 |
+
self,
|
| 292 |
+
in_channels,
|
| 293 |
+
out_channels,
|
| 294 |
+
kernel_size,
|
| 295 |
+
stride,
|
| 296 |
+
padding,
|
| 297 |
+
output_padding,
|
| 298 |
+
groups,
|
| 299 |
+
bias,
|
| 300 |
+
dilation,
|
| 301 |
+
padding_mode,
|
| 302 |
+
device,
|
| 303 |
+
dtype,
|
| 304 |
+
)
|
| 305 |
+
self._init_weight_qparams(weight_qparams, device)
|
| 306 |
+
|
| 307 |
+
def forward(
|
| 308 |
+
self, x: torch.Tensor, output_size: Optional[List[int]] = None
|
| 309 |
+
) -> torch.Tensor:
|
| 310 |
+
"""
|
| 311 |
+
we have:
|
| 312 |
+
w(float) -- quant - dequant \
|
| 313 |
+
x(float) ------------- F.convTranspose1d ---
|
| 314 |
+
In the full model, we will see
|
| 315 |
+
w(float) -- quant - *dequant \
|
| 316 |
+
x -- quant --- *dequant -- *F.convTranspose1d --- *quant - dequant
|
| 317 |
+
and the backend should be able to fuse the ops with `*` into a quantized conv1d
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
assert isinstance(self.padding, tuple)
|
| 321 |
+
# One cannot replace List by Tuple or Sequence in "_output_padding" because
|
| 322 |
+
# TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
|
| 323 |
+
output_padding = self._output_padding(
|
| 324 |
+
input, # type: ignore[arg-type]
|
| 325 |
+
output_size,
|
| 326 |
+
self.stride, # type: ignore[arg-type]
|
| 327 |
+
self.padding, # type: ignore[arg-type]
|
| 328 |
+
self.kernel_size, # type: ignore[arg-type]
|
| 329 |
+
self.dilation, # type: ignore[arg-type]
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
weight_quant_dequant = self.get_weight()
|
| 333 |
+
result = F.conv_transpose1d(
|
| 334 |
+
x,
|
| 335 |
+
weight_quant_dequant,
|
| 336 |
+
self.bias,
|
| 337 |
+
self.stride,
|
| 338 |
+
self.padding,
|
| 339 |
+
output_padding,
|
| 340 |
+
self.groups,
|
| 341 |
+
self.dilation,
|
| 342 |
+
)
|
| 343 |
+
return result
|
| 344 |
+
|
| 345 |
+
def _get_name(self):
|
| 346 |
+
return "QuantizedConvTranspose1d(Reference)"
|
| 347 |
+
|
| 348 |
+
@classmethod
|
| 349 |
+
def from_float(cls, float_conv, weight_qparams):
|
| 350 |
+
return _ConvTransposeNd.from_float(cls, float_conv, weight_qparams)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
class ConvTranspose2d(_ConvTransposeNd, nn.ConvTranspose2d):
|
| 354 |
+
def __init__(
|
| 355 |
+
self,
|
| 356 |
+
in_channels,
|
| 357 |
+
out_channels,
|
| 358 |
+
kernel_size,
|
| 359 |
+
stride=1,
|
| 360 |
+
padding=0,
|
| 361 |
+
output_padding=0,
|
| 362 |
+
groups=1,
|
| 363 |
+
bias=True,
|
| 364 |
+
dilation=1,
|
| 365 |
+
padding_mode="zeros",
|
| 366 |
+
device=None,
|
| 367 |
+
dtype=None,
|
| 368 |
+
weight_qparams: Optional[Dict[str, Any]] = None,
|
| 369 |
+
):
|
| 370 |
+
nn.ConvTranspose2d.__init__(
|
| 371 |
+
self,
|
| 372 |
+
in_channels,
|
| 373 |
+
out_channels,
|
| 374 |
+
kernel_size,
|
| 375 |
+
stride,
|
| 376 |
+
padding,
|
| 377 |
+
output_padding,
|
| 378 |
+
groups,
|
| 379 |
+
bias,
|
| 380 |
+
dilation,
|
| 381 |
+
padding_mode,
|
| 382 |
+
device,
|
| 383 |
+
dtype,
|
| 384 |
+
)
|
| 385 |
+
self._init_weight_qparams(weight_qparams, device)
|
| 386 |
+
|
| 387 |
+
def forward(
|
| 388 |
+
self, x: torch.Tensor, output_size: Optional[List[int]] = None
|
| 389 |
+
) -> torch.Tensor:
|
| 390 |
+
"""
|
| 391 |
+
we have:
|
| 392 |
+
w(float) -- quant - dequant \
|
| 393 |
+
x(float) ------------- F.convTranspose2d ---
|
| 394 |
+
In the full model, we will see
|
| 395 |
+
w(float) -- quant - *dequant \
|
| 396 |
+
x -- quant --- *dequant -- *F.convTranspose2d --- *quant - dequant
|
| 397 |
+
and the backend should be able to fuse the ops with `*` into a quantized conv2d
|
| 398 |
+
"""
|
| 399 |
+
assert isinstance(self.padding, tuple)
|
| 400 |
+
# One cannot replace List by Tuple or Sequence in "_output_padding" because
|
| 401 |
+
# TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
|
| 402 |
+
|
| 403 |
+
output_padding = self._output_padding(
|
| 404 |
+
input, # type: ignore[arg-type]
|
| 405 |
+
output_size,
|
| 406 |
+
self.stride, # type: ignore[arg-type]
|
| 407 |
+
self.padding, # type: ignore[arg-type]
|
| 408 |
+
self.kernel_size, # type: ignore[arg-type]
|
| 409 |
+
self.dilation, # type: ignore[arg-type]
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
weight_quant_dequant = self.get_weight()
|
| 413 |
+
result = F.conv_transpose2d(
|
| 414 |
+
x,
|
| 415 |
+
weight_quant_dequant,
|
| 416 |
+
self.bias,
|
| 417 |
+
self.stride,
|
| 418 |
+
self.padding,
|
| 419 |
+
output_padding,
|
| 420 |
+
self.groups,
|
| 421 |
+
self.dilation,
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
return result
|
| 425 |
+
|
| 426 |
+
def _get_name(self):
|
| 427 |
+
return "QuantizedConvTranspose2d(Reference)"
|
| 428 |
+
|
| 429 |
+
@classmethod
|
| 430 |
+
def from_float(cls, float_conv, weight_qparams):
|
| 431 |
+
return _ConvTransposeNd.from_float(cls, float_conv, weight_qparams)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
class ConvTranspose3d(_ConvTransposeNd, nn.ConvTranspose3d):
|
| 435 |
+
def __init__(
|
| 436 |
+
self,
|
| 437 |
+
in_channels,
|
| 438 |
+
out_channels,
|
| 439 |
+
kernel_size,
|
| 440 |
+
stride=1,
|
| 441 |
+
padding=0,
|
| 442 |
+
output_padding=0,
|
| 443 |
+
groups=1,
|
| 444 |
+
bias=True,
|
| 445 |
+
dilation=1,
|
| 446 |
+
padding_mode="zeros",
|
| 447 |
+
device=None,
|
| 448 |
+
dtype=None,
|
| 449 |
+
weight_qparams: Optional[Dict[str, Any]] = None,
|
| 450 |
+
):
|
| 451 |
+
nn.ConvTranspose3d.__init__(
|
| 452 |
+
self,
|
| 453 |
+
in_channels,
|
| 454 |
+
out_channels,
|
| 455 |
+
kernel_size,
|
| 456 |
+
stride,
|
| 457 |
+
padding,
|
| 458 |
+
output_padding,
|
| 459 |
+
groups,
|
| 460 |
+
bias,
|
| 461 |
+
dilation,
|
| 462 |
+
padding_mode,
|
| 463 |
+
device,
|
| 464 |
+
dtype,
|
| 465 |
+
)
|
| 466 |
+
self._init_weight_qparams(weight_qparams, device)
|
| 467 |
+
|
| 468 |
+
def forward(
|
| 469 |
+
self, x: torch.Tensor, output_size: Optional[List[int]] = None
|
| 470 |
+
) -> torch.Tensor:
|
| 471 |
+
"""
|
| 472 |
+
we have:
|
| 473 |
+
w(float) -- quant - dequant \
|
| 474 |
+
x(float) ------------- F.convTranspose3d ---
|
| 475 |
+
In the full model, we will see
|
| 476 |
+
w(float) -- quant - *dequant \
|
| 477 |
+
x -- quant --- *dequant -- *F.convTranspose3d --- *quant - dequant
|
| 478 |
+
and the backend should be able to fuse the ops with `*` into a quantized conv3d
|
| 479 |
+
"""
|
| 480 |
+
|
| 481 |
+
assert isinstance(self.padding, tuple)
|
| 482 |
+
# One cannot replace List by Tuple or Sequence in "_output_padding" because
|
| 483 |
+
# TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
|
| 484 |
+
output_padding = self._output_padding(
|
| 485 |
+
input, # type: ignore[arg-type]
|
| 486 |
+
output_size,
|
| 487 |
+
self.stride, # type: ignore[arg-type]
|
| 488 |
+
self.padding, # type: ignore[arg-type]
|
| 489 |
+
self.kernel_size, # type: ignore[arg-type]
|
| 490 |
+
self.dilation, # type: ignore[arg-type]
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
weight_quant_dequant = self.get_weight()
|
| 494 |
+
result = F.conv_transpose3d(
|
| 495 |
+
x,
|
| 496 |
+
weight_quant_dequant,
|
| 497 |
+
self.bias,
|
| 498 |
+
self.stride,
|
| 499 |
+
self.padding,
|
| 500 |
+
output_padding,
|
| 501 |
+
self.groups,
|
| 502 |
+
self.dilation,
|
| 503 |
+
)
|
| 504 |
+
return result
|
| 505 |
+
|
| 506 |
+
def _get_name(self):
|
| 507 |
+
return "QuantizedConvTranspose3d(Reference)"
|
| 508 |
+
|
| 509 |
+
@classmethod
|
| 510 |
+
def from_float(cls, float_conv, weight_qparams):
|
| 511 |
+
return _ConvTransposeNd.from_float(cls, float_conv, weight_qparams)
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/linear.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from typing import Any, Dict, Optional
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
|
| 8 |
+
from .utils import ReferenceQuantizedModule
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
__all__ = ["Linear"]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Linear(nn.Linear, ReferenceQuantizedModule):
|
| 15 |
+
"""A reference quantized linear module that fits into the FX
|
| 16 |
+
Graph Mode Quantization workflow
|
| 17 |
+
activation will be floating point Tensor, we will store floating
|
| 18 |
+
point weight as well in the module, but in forward we'll quantize
|
| 19 |
+
and dequantize the weight before running the floating point functional
|
| 20 |
+
linear operator.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
_IS_REFERENCE = True
|
| 24 |
+
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
in_features: int,
|
| 28 |
+
out_features: int,
|
| 29 |
+
bias_: bool = True,
|
| 30 |
+
device: Optional[torch.device] = None,
|
| 31 |
+
dtype: Optional[torch.dtype] = None,
|
| 32 |
+
weight_qparams: Optional[Dict[str, Any]] = None,
|
| 33 |
+
):
|
| 34 |
+
super().__init__(in_features, out_features, bias_, device, dtype)
|
| 35 |
+
self._init_weight_qparams(weight_qparams, device)
|
| 36 |
+
|
| 37 |
+
def _get_name(self):
|
| 38 |
+
return "QuantizedLinear(Reference)"
|
| 39 |
+
|
| 40 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 41 |
+
"""
|
| 42 |
+
we have:
|
| 43 |
+
w(float) -- quant - dequant \
|
| 44 |
+
x(float) ------------- F.linear ---
|
| 45 |
+
|
| 46 |
+
In the full model, we will see
|
| 47 |
+
w(float) -- quant - *dequant \
|
| 48 |
+
x -- quant --- *dequant -- *F.linear --- *quant - dequant
|
| 49 |
+
and the backend should be able to fuse the ops with `*` into a quantized linear
|
| 50 |
+
"""
|
| 51 |
+
weight_quant_dequant = self.get_weight()
|
| 52 |
+
result = F.linear(x, weight_quant_dequant, self.bias)
|
| 53 |
+
return result
|
| 54 |
+
|
| 55 |
+
@classmethod
|
| 56 |
+
def from_float(cls, float_linear, weight_qparams):
|
| 57 |
+
qref_linear = Linear(
|
| 58 |
+
float_linear.in_features,
|
| 59 |
+
float_linear.out_features,
|
| 60 |
+
float_linear.bias is not None,
|
| 61 |
+
device=float_linear.weight.device,
|
| 62 |
+
dtype=float_linear.weight.dtype,
|
| 63 |
+
weight_qparams=weight_qparams,
|
| 64 |
+
)
|
| 65 |
+
qref_linear.weight = torch.nn.Parameter(float_linear.weight.detach())
|
| 66 |
+
if float_linear.bias is not None:
|
| 67 |
+
qref_linear.bias = torch.nn.Parameter(float_linear.bias.detach())
|
| 68 |
+
return qref_linear
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/rnn.py
ADDED
|
@@ -0,0 +1,845 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from torch import _VF, Tensor
|
| 7 |
+
from torch.nn.utils.rnn import PackedSequence
|
| 8 |
+
|
| 9 |
+
from .utils import _quantize_and_dequantize_weight, _quantize_weight
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
"RNNCellBase",
|
| 14 |
+
"RNNCell",
|
| 15 |
+
"LSTMCell",
|
| 16 |
+
"GRUCell",
|
| 17 |
+
"RNNBase",
|
| 18 |
+
"LSTM",
|
| 19 |
+
"GRU",
|
| 20 |
+
"get_quantized_weight",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _apply_permutation(tensor: Tensor, permutation: Tensor, dim: int = 1) -> Tensor:
|
| 25 |
+
return tensor.index_select(dim, permutation)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _get_weight_and_quantization_params(module, wn):
|
| 29 |
+
weight = getattr(module, wn)
|
| 30 |
+
params = [weight]
|
| 31 |
+
for param_name in [
|
| 32 |
+
wn + n for n in ["_qscheme", "_dtype", "_scale", "_zero_point", "_axis_int"]
|
| 33 |
+
]:
|
| 34 |
+
if hasattr(module, param_name):
|
| 35 |
+
param = getattr(module, param_name)
|
| 36 |
+
else:
|
| 37 |
+
param = None
|
| 38 |
+
params.append(param)
|
| 39 |
+
return params
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_quantized_weight(module, wn):
|
| 43 |
+
if not hasattr(module, wn):
|
| 44 |
+
return None
|
| 45 |
+
params = _get_weight_and_quantization_params(module, wn)
|
| 46 |
+
weight = _quantize_weight(*params)
|
| 47 |
+
return weight
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _get_quantize_and_dequantized_weight(module, wn):
|
| 51 |
+
if not hasattr(module, wn):
|
| 52 |
+
return None
|
| 53 |
+
params = _get_weight_and_quantization_params(module, wn)
|
| 54 |
+
weight = _quantize_and_dequantize_weight(*params)
|
| 55 |
+
return weight
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class RNNCellBase(nn.RNNCellBase):
|
| 59 |
+
def __init__(
|
| 60 |
+
self,
|
| 61 |
+
input_size: int,
|
| 62 |
+
hidden_size: int,
|
| 63 |
+
bias: bool,
|
| 64 |
+
num_chunks: int,
|
| 65 |
+
device=None,
|
| 66 |
+
dtype=None,
|
| 67 |
+
weight_qparams_dict=None,
|
| 68 |
+
) -> None:
|
| 69 |
+
super().__init__(
|
| 70 |
+
input_size, hidden_size, bias, num_chunks, device=device, dtype=dtype
|
| 71 |
+
)
|
| 72 |
+
# TODO(jerryzh168): maybe make this arg a required arg
|
| 73 |
+
if weight_qparams_dict is None:
|
| 74 |
+
weight_qparams = {
|
| 75 |
+
"qscheme": torch.per_tensor_affine,
|
| 76 |
+
"dtype": torch.quint8,
|
| 77 |
+
"scale": 1.0,
|
| 78 |
+
"zero_point": 0,
|
| 79 |
+
}
|
| 80 |
+
weight_qparams_dict = {
|
| 81 |
+
"weight_ih": weight_qparams,
|
| 82 |
+
"weight_hh": weight_qparams,
|
| 83 |
+
"is_decomposed": False,
|
| 84 |
+
}
|
| 85 |
+
assert (
|
| 86 |
+
len(weight_qparams_dict) == 3
|
| 87 |
+
), "Expected length for weight_qparams_dict to be 3 for QuantizedRNNCellBase(Reference)"
|
| 88 |
+
self._init_weight_qparams_dict(weight_qparams_dict, device)
|
| 89 |
+
|
| 90 |
+
def _init_weight_qparams_dict(self, weight_qparams_dict, device):
|
| 91 |
+
assert weight_qparams_dict is not None
|
| 92 |
+
self.is_decomposed = weight_qparams_dict["is_decomposed"]
|
| 93 |
+
for key, weight_qparams in weight_qparams_dict.items():
|
| 94 |
+
if key == "is_decomposed":
|
| 95 |
+
continue
|
| 96 |
+
# TODO: refactor the duplicated code to utils.py
|
| 97 |
+
weight_qscheme = weight_qparams["qscheme"]
|
| 98 |
+
weight_dtype = weight_qparams["dtype"]
|
| 99 |
+
setattr(self, key + "_qscheme", weight_qscheme)
|
| 100 |
+
setattr(self, key + "_dtype", weight_dtype)
|
| 101 |
+
assert weight_qscheme in [
|
| 102 |
+
None,
|
| 103 |
+
torch.per_tensor_affine,
|
| 104 |
+
torch.per_channel_affine,
|
| 105 |
+
], Exception(
|
| 106 |
+
f"qscheme: {weight_qscheme} is not support in {self._get_name()}"
|
| 107 |
+
)
|
| 108 |
+
if weight_qscheme is not None:
|
| 109 |
+
scale = weight_qparams["scale"]
|
| 110 |
+
scale_tensor = (
|
| 111 |
+
scale.clone().detach()
|
| 112 |
+
if isinstance(scale, torch.Tensor)
|
| 113 |
+
else torch.tensor(scale, dtype=torch.float, device=device)
|
| 114 |
+
)
|
| 115 |
+
self.register_buffer(key + "_scale", scale_tensor)
|
| 116 |
+
zp = weight_qparams["zero_point"]
|
| 117 |
+
zp_tensor = (
|
| 118 |
+
zp.clone().detach()
|
| 119 |
+
if isinstance(zp, torch.Tensor)
|
| 120 |
+
else torch.tensor(zp, dtype=torch.int, device=device)
|
| 121 |
+
)
|
| 122 |
+
self.register_buffer(key + "_zero_point", zp_tensor)
|
| 123 |
+
if weight_qscheme == torch.per_channel_affine:
|
| 124 |
+
axis = weight_qparams["axis"]
|
| 125 |
+
axis_tensor = (
|
| 126 |
+
axis.clone().detach()
|
| 127 |
+
if isinstance(axis, torch.Tensor)
|
| 128 |
+
else torch.tensor(axis, dtype=torch.int, device=device)
|
| 129 |
+
)
|
| 130 |
+
self.register_buffer(key + "_axis", axis_tensor)
|
| 131 |
+
else:
|
| 132 |
+
# added for TorchScriptability, not used
|
| 133 |
+
self.register_buffer(
|
| 134 |
+
key + "_axis", torch.tensor(0, dtype=torch.int, device=device)
|
| 135 |
+
)
|
| 136 |
+
setattr(self, key + "_axis_int", getattr(self, key + "_axis").item())
|
| 137 |
+
|
| 138 |
+
def _get_name(self):
|
| 139 |
+
return "QuantizedRNNCellBase(Reference)"
|
| 140 |
+
|
| 141 |
+
def get_quantized_weight_ih(self):
|
| 142 |
+
return get_quantized_weight(self, "weight_ih")
|
| 143 |
+
|
| 144 |
+
def get_quantized_weight_hh(self):
|
| 145 |
+
return get_quantized_weight(self, "weight_hh")
|
| 146 |
+
|
| 147 |
+
def get_weight_ih(self):
|
| 148 |
+
return _get_quantize_and_dequantized_weight(self, "weight_ih")
|
| 149 |
+
|
| 150 |
+
def get_weight_hh(self):
|
| 151 |
+
return _get_quantize_and_dequantized_weight(self, "weight_hh")
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class RNNCell(RNNCellBase):
|
| 155 |
+
"""
|
| 156 |
+
We'll store weight_qparams for all the weights (weight_ih and weight_hh),
|
| 157 |
+
we need to pass in a `weight_qparams_dict` that maps from weight name,
|
| 158 |
+
e.g. weight_ih, to the weight_qparams for that weight
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
def __init__(
|
| 162 |
+
self,
|
| 163 |
+
input_size: int,
|
| 164 |
+
hidden_size: int,
|
| 165 |
+
bias: bool = True,
|
| 166 |
+
nonlinearity: str = "tanh",
|
| 167 |
+
device=None,
|
| 168 |
+
dtype=None,
|
| 169 |
+
weight_qparams_dict: Optional[Dict[str, Any]] = None,
|
| 170 |
+
) -> None:
|
| 171 |
+
factory_kwargs = {
|
| 172 |
+
"device": device,
|
| 173 |
+
"dtype": dtype,
|
| 174 |
+
"weight_qparams_dict": weight_qparams_dict,
|
| 175 |
+
}
|
| 176 |
+
super().__init__(input_size, hidden_size, bias, num_chunks=1, **factory_kwargs)
|
| 177 |
+
self.nonlinearity = nonlinearity
|
| 178 |
+
|
| 179 |
+
def _get_name(self):
|
| 180 |
+
return "QuantizedRNNCell(Reference)"
|
| 181 |
+
|
| 182 |
+
# TODO: refactor nn.RNNCell to have a _forward that takes weight_ih and weight_hh as input
|
| 183 |
+
# and remove duplicated code, same for the other two Cell modules
|
| 184 |
+
def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tensor:
|
| 185 |
+
assert input.dim() in (
|
| 186 |
+
1,
|
| 187 |
+
2,
|
| 188 |
+
), f"RNNCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
|
| 189 |
+
is_batched = input.dim() == 2
|
| 190 |
+
if not is_batched:
|
| 191 |
+
input = input.unsqueeze(0)
|
| 192 |
+
|
| 193 |
+
if hx is None:
|
| 194 |
+
hx = torch.zeros(
|
| 195 |
+
input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
|
| 196 |
+
)
|
| 197 |
+
else:
|
| 198 |
+
hx = hx.unsqueeze(0) if not is_batched else hx
|
| 199 |
+
|
| 200 |
+
if self.nonlinearity == "tanh":
|
| 201 |
+
ret = _VF.rnn_tanh_cell(
|
| 202 |
+
input,
|
| 203 |
+
hx,
|
| 204 |
+
self.get_weight_ih(),
|
| 205 |
+
self.get_weight_hh(),
|
| 206 |
+
self.bias_ih,
|
| 207 |
+
self.bias_hh,
|
| 208 |
+
)
|
| 209 |
+
elif self.nonlinearity == "relu":
|
| 210 |
+
ret = _VF.rnn_relu_cell(
|
| 211 |
+
input,
|
| 212 |
+
hx,
|
| 213 |
+
self.get_weight_ih(),
|
| 214 |
+
self.get_weight_hh(),
|
| 215 |
+
self.bias_ih,
|
| 216 |
+
self.bias_hh,
|
| 217 |
+
)
|
| 218 |
+
else:
|
| 219 |
+
ret = input # TODO: remove when jit supports exception flow
|
| 220 |
+
raise RuntimeError(f"Unknown nonlinearity: {self.nonlinearity}")
|
| 221 |
+
|
| 222 |
+
if not is_batched:
|
| 223 |
+
ret = ret.squeeze(0)
|
| 224 |
+
|
| 225 |
+
return ret
|
| 226 |
+
|
| 227 |
+
@classmethod
|
| 228 |
+
def from_float(cls, mod, weight_qparams_dict):
|
| 229 |
+
ref_mod = cls(
|
| 230 |
+
mod.input_size,
|
| 231 |
+
mod.hidden_size,
|
| 232 |
+
mod.bias,
|
| 233 |
+
mod.nonlinearity,
|
| 234 |
+
mod.weight_ih.device,
|
| 235 |
+
mod.weight_ih.dtype,
|
| 236 |
+
weight_qparams_dict,
|
| 237 |
+
)
|
| 238 |
+
ref_mod.weight_ih = mod.weight_ih
|
| 239 |
+
ref_mod.weight_hh = mod.weight_hh
|
| 240 |
+
ref_mod.bias_ih = mod.bias_ih
|
| 241 |
+
ref_mod.bias_hh = mod.bias_hh
|
| 242 |
+
return ref_mod
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class LSTMCell(RNNCellBase):
|
| 246 |
+
"""
|
| 247 |
+
We'll store weight_qparams for all the weights (weight_ih and weight_hh),
|
| 248 |
+
we need to pass in a `weight_qparams_dict` that maps from weight name,
|
| 249 |
+
e.g. weight_ih, to the weight_qparams for that weight
|
| 250 |
+
"""
|
| 251 |
+
|
| 252 |
+
def __init__(
|
| 253 |
+
self,
|
| 254 |
+
input_size: int,
|
| 255 |
+
hidden_size: int,
|
| 256 |
+
bias: bool = True,
|
| 257 |
+
device=None,
|
| 258 |
+
dtype=None,
|
| 259 |
+
weight_qparams_dict: Optional[Dict[str, Any]] = None,
|
| 260 |
+
) -> None:
|
| 261 |
+
factory_kwargs = {
|
| 262 |
+
"device": device,
|
| 263 |
+
"dtype": dtype,
|
| 264 |
+
"weight_qparams_dict": weight_qparams_dict,
|
| 265 |
+
}
|
| 266 |
+
super().__init__(input_size, hidden_size, bias, num_chunks=4, **factory_kwargs)
|
| 267 |
+
|
| 268 |
+
def _get_name(self):
|
| 269 |
+
return "QuantizedLSTMCell(Reference)"
|
| 270 |
+
|
| 271 |
+
def forward(
|
| 272 |
+
self, input: Tensor, hx: Optional[Tuple[Tensor, Tensor]] = None
|
| 273 |
+
) -> Tuple[Tensor, Tensor]:
|
| 274 |
+
assert input.dim() in (
|
| 275 |
+
1,
|
| 276 |
+
2,
|
| 277 |
+
), f"LSTMCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
|
| 278 |
+
is_batched = input.dim() == 2
|
| 279 |
+
if not is_batched:
|
| 280 |
+
input = input.unsqueeze(0)
|
| 281 |
+
|
| 282 |
+
if hx is None:
|
| 283 |
+
zeros = torch.zeros(
|
| 284 |
+
input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
|
| 285 |
+
)
|
| 286 |
+
hx = (zeros, zeros)
|
| 287 |
+
else:
|
| 288 |
+
hx = (hx[0].unsqueeze(0), hx[1].unsqueeze(0)) if not is_batched else hx
|
| 289 |
+
|
| 290 |
+
ret = _VF.lstm_cell(
|
| 291 |
+
input,
|
| 292 |
+
hx,
|
| 293 |
+
self.get_weight_ih(),
|
| 294 |
+
self.get_weight_hh(),
|
| 295 |
+
self.bias_ih,
|
| 296 |
+
self.bias_hh,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
if not is_batched:
|
| 300 |
+
ret = (ret[0].squeeze(0), ret[1].squeeze(0))
|
| 301 |
+
return ret
|
| 302 |
+
|
| 303 |
+
@classmethod
|
| 304 |
+
def from_float(cls, mod, weight_qparams_dict, use_precomputed_fake_quant=False):
|
| 305 |
+
ref_mod = cls(
|
| 306 |
+
mod.input_size,
|
| 307 |
+
mod.hidden_size,
|
| 308 |
+
mod.bias,
|
| 309 |
+
mod.weight_ih.device,
|
| 310 |
+
mod.weight_ih.dtype,
|
| 311 |
+
weight_qparams_dict,
|
| 312 |
+
)
|
| 313 |
+
ref_mod.weight_ih = mod.weight_ih
|
| 314 |
+
ref_mod.weight_hh = mod.weight_hh
|
| 315 |
+
ref_mod.bias_ih = mod.bias_ih
|
| 316 |
+
ref_mod.bias_hh = mod.bias_hh
|
| 317 |
+
return ref_mod
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class GRUCell(RNNCellBase):
|
| 321 |
+
"""
|
| 322 |
+
We'll store weight_qparams for all the weights (weight_ih and weight_hh),
|
| 323 |
+
we need to pass in a `weight_qparams_dict` that maps from weight name,
|
| 324 |
+
e.g. weight_ih, to the weight_qparams for that weight
|
| 325 |
+
"""
|
| 326 |
+
|
| 327 |
+
def __init__(
|
| 328 |
+
self,
|
| 329 |
+
input_size: int,
|
| 330 |
+
hidden_size: int,
|
| 331 |
+
bias: bool = True,
|
| 332 |
+
device=None,
|
| 333 |
+
dtype=None,
|
| 334 |
+
weight_qparams_dict: Optional[Dict[str, Any]] = None,
|
| 335 |
+
) -> None:
|
| 336 |
+
factory_kwargs = {
|
| 337 |
+
"device": device,
|
| 338 |
+
"dtype": dtype,
|
| 339 |
+
"weight_qparams_dict": weight_qparams_dict,
|
| 340 |
+
}
|
| 341 |
+
super().__init__(input_size, hidden_size, bias, num_chunks=3, **factory_kwargs)
|
| 342 |
+
|
| 343 |
+
def _get_name(self):
|
| 344 |
+
return "QuantizedGRUCell(Reference)"
|
| 345 |
+
|
| 346 |
+
def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tensor:
|
| 347 |
+
assert input.dim() in (
|
| 348 |
+
1,
|
| 349 |
+
2,
|
| 350 |
+
), f"GRUCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
|
| 351 |
+
is_batched = input.dim() == 2
|
| 352 |
+
if not is_batched:
|
| 353 |
+
input = input.unsqueeze(0)
|
| 354 |
+
|
| 355 |
+
if hx is None:
|
| 356 |
+
hx = torch.zeros(
|
| 357 |
+
input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
|
| 358 |
+
)
|
| 359 |
+
else:
|
| 360 |
+
hx = hx.unsqueeze(0) if not is_batched else hx
|
| 361 |
+
|
| 362 |
+
ret = _VF.gru_cell(
|
| 363 |
+
input,
|
| 364 |
+
hx,
|
| 365 |
+
self.get_weight_ih(),
|
| 366 |
+
self.get_weight_hh(),
|
| 367 |
+
self.bias_ih,
|
| 368 |
+
self.bias_hh,
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
if not is_batched:
|
| 372 |
+
ret = ret.squeeze(0)
|
| 373 |
+
|
| 374 |
+
return ret
|
| 375 |
+
|
| 376 |
+
@classmethod
|
| 377 |
+
def from_float(cls, mod, weight_qparams_dict):
|
| 378 |
+
ref_mod = cls(
|
| 379 |
+
mod.input_size,
|
| 380 |
+
mod.hidden_size,
|
| 381 |
+
mod.bias,
|
| 382 |
+
mod.weight_ih.device,
|
| 383 |
+
mod.weight_ih.dtype,
|
| 384 |
+
weight_qparams_dict,
|
| 385 |
+
)
|
| 386 |
+
ref_mod.weight_ih = mod.weight_ih
|
| 387 |
+
ref_mod.weight_hh = mod.weight_hh
|
| 388 |
+
ref_mod.bias_ih = mod.bias_ih
|
| 389 |
+
ref_mod.bias_hh = mod.bias_hh
|
| 390 |
+
return ref_mod
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class RNNBase(nn.RNNBase):
|
| 394 |
+
def __init__(
|
| 395 |
+
self,
|
| 396 |
+
mode: str,
|
| 397 |
+
input_size: int,
|
| 398 |
+
hidden_size: int,
|
| 399 |
+
num_layers: int = 1,
|
| 400 |
+
bias: bool = True,
|
| 401 |
+
batch_first: bool = False,
|
| 402 |
+
dropout: float = 0.0,
|
| 403 |
+
bidirectional: bool = False,
|
| 404 |
+
proj_size: int = 0,
|
| 405 |
+
device=None,
|
| 406 |
+
dtype=None,
|
| 407 |
+
weight_qparams_dict: Optional[Dict[str, Any]] = None,
|
| 408 |
+
) -> None:
|
| 409 |
+
super().__init__(
|
| 410 |
+
mode,
|
| 411 |
+
input_size,
|
| 412 |
+
hidden_size,
|
| 413 |
+
num_layers,
|
| 414 |
+
bias,
|
| 415 |
+
batch_first,
|
| 416 |
+
dropout,
|
| 417 |
+
bidirectional,
|
| 418 |
+
proj_size,
|
| 419 |
+
device,
|
| 420 |
+
dtype,
|
| 421 |
+
)
|
| 422 |
+
# TODO(jerryzh168): maybe make this arg a required arg
|
| 423 |
+
if weight_qparams_dict is None:
|
| 424 |
+
weight_qparams = {
|
| 425 |
+
"qscheme": torch.per_tensor_affine,
|
| 426 |
+
"dtype": torch.quint8,
|
| 427 |
+
"scale": 1.0,
|
| 428 |
+
"zero_point": 0,
|
| 429 |
+
}
|
| 430 |
+
weight_qparams_dict = {"is_decomposed": False} # type: ignore[dict-item]
|
| 431 |
+
for wn in self._flat_weights_names:
|
| 432 |
+
if wn.startswith("weight"):
|
| 433 |
+
weight_qparams_dict[wn] = weight_qparams
|
| 434 |
+
self._init_weight_qparams_dict(weight_qparams_dict, device)
|
| 435 |
+
|
| 436 |
+
def _init_weight_qparams_dict(self, weight_qparams_dict, device):
|
| 437 |
+
self.is_decomposed = weight_qparams_dict["is_decomposed"]
|
| 438 |
+
for key, weight_qparams in weight_qparams_dict.items():
|
| 439 |
+
if key == "is_decomposed":
|
| 440 |
+
continue
|
| 441 |
+
weight_qscheme = weight_qparams["qscheme"]
|
| 442 |
+
weight_dtype = weight_qparams["dtype"]
|
| 443 |
+
setattr(self, key + "_qscheme", weight_qscheme)
|
| 444 |
+
setattr(self, key + "_dtype", weight_dtype)
|
| 445 |
+
assert weight_qscheme in [
|
| 446 |
+
None,
|
| 447 |
+
torch.per_tensor_affine,
|
| 448 |
+
torch.per_channel_affine,
|
| 449 |
+
], Exception(
|
| 450 |
+
f"qscheme: {weight_qscheme} is not support in {self._get_name()}"
|
| 451 |
+
)
|
| 452 |
+
if weight_qscheme is not None:
|
| 453 |
+
self.register_buffer(
|
| 454 |
+
key + "_scale",
|
| 455 |
+
torch.tensor(
|
| 456 |
+
weight_qparams["scale"], dtype=torch.float, device=device
|
| 457 |
+
),
|
| 458 |
+
)
|
| 459 |
+
self.register_buffer(
|
| 460 |
+
key + "_zero_point",
|
| 461 |
+
torch.tensor(
|
| 462 |
+
weight_qparams["zero_point"], dtype=torch.int, device=device
|
| 463 |
+
),
|
| 464 |
+
)
|
| 465 |
+
if weight_qscheme == torch.per_channel_affine:
|
| 466 |
+
self.register_buffer(
|
| 467 |
+
key + "_axis",
|
| 468 |
+
torch.tensor(
|
| 469 |
+
weight_qparams["axis"], dtype=torch.int, device=device
|
| 470 |
+
),
|
| 471 |
+
)
|
| 472 |
+
else:
|
| 473 |
+
# added for TorchScriptability, not used
|
| 474 |
+
self.register_buffer(
|
| 475 |
+
key + "_axis", torch.tensor(0, dtype=torch.int, device=device)
|
| 476 |
+
)
|
| 477 |
+
setattr(self, key + "_axis_int", getattr(self, key + "_axis").item())
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
class LSTM(RNNBase):
|
| 481 |
+
"""Reference Quantized LSTM Module
|
| 482 |
+
We'll store weight_qparams for all the weights in _flat_weights, we need to pass in
|
| 483 |
+
a `weight_qparams_dict` that maps from weight name, e.g. weight_ih_l0,
|
| 484 |
+
to the weight_qparams for that weight
|
| 485 |
+
"""
|
| 486 |
+
|
| 487 |
+
def __init__(self, *args, **kwargs):
|
| 488 |
+
super().__init__("LSTM", *args, **kwargs)
|
| 489 |
+
|
| 490 |
+
# Same as above, see torch/nn/modules/module.py::_forward_unimplemented
|
| 491 |
+
def permute_hidden( # type: ignore[override]
|
| 492 |
+
self,
|
| 493 |
+
hx: Tuple[Tensor, Tensor],
|
| 494 |
+
permutation: Optional[Tensor],
|
| 495 |
+
) -> Tuple[Tensor, Tensor]:
|
| 496 |
+
if permutation is None:
|
| 497 |
+
return hx
|
| 498 |
+
return _apply_permutation(hx[0], permutation), _apply_permutation(
|
| 499 |
+
hx[1], permutation
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
def get_expected_cell_size(
|
| 503 |
+
self, input: Tensor, batch_sizes: Optional[Tensor]
|
| 504 |
+
) -> Tuple[int, int, int]:
|
| 505 |
+
if batch_sizes is not None:
|
| 506 |
+
mini_batch = int(batch_sizes[0])
|
| 507 |
+
else:
|
| 508 |
+
mini_batch = input.size(0) if self.batch_first else input.size(1)
|
| 509 |
+
num_directions = 2 if self.bidirectional else 1
|
| 510 |
+
expected_hidden_size = (
|
| 511 |
+
self.num_layers * num_directions,
|
| 512 |
+
mini_batch,
|
| 513 |
+
self.hidden_size,
|
| 514 |
+
)
|
| 515 |
+
return expected_hidden_size
|
| 516 |
+
|
| 517 |
+
# In the future, we should prevent mypy from applying contravariance rules here.
|
| 518 |
+
# See torch/nn/modules/module.py::_forward_unimplemented
|
| 519 |
+
def check_forward_args( # type: ignore[override]
|
| 520 |
+
self,
|
| 521 |
+
input: Tensor,
|
| 522 |
+
hidden: Tuple[Tensor, Tensor],
|
| 523 |
+
batch_sizes: Optional[Tensor],
|
| 524 |
+
):
|
| 525 |
+
self.check_input(input, batch_sizes)
|
| 526 |
+
self.check_hidden_size(
|
| 527 |
+
hidden[0],
|
| 528 |
+
self.get_expected_hidden_size(input, batch_sizes),
|
| 529 |
+
"Expected hidden[0] size {}, got {}",
|
| 530 |
+
)
|
| 531 |
+
self.check_hidden_size(
|
| 532 |
+
hidden[1],
|
| 533 |
+
self.get_expected_cell_size(input, batch_sizes),
|
| 534 |
+
"Expected hidden[1] size {}, got {}",
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
def get_quantized_weight_bias_dict(self):
|
| 538 |
+
"""dictionary from flat_weight_name to quantized weight or (unquantized) bias
|
| 539 |
+
e.g.
|
| 540 |
+
{
|
| 541 |
+
"weight_ih_l0": quantized_weight,
|
| 542 |
+
"bias_ih_l0": unquantized_bias,
|
| 543 |
+
...
|
| 544 |
+
}
|
| 545 |
+
"""
|
| 546 |
+
quantized_weight_bias_dict = {}
|
| 547 |
+
for wn in self._flat_weights_names:
|
| 548 |
+
if hasattr(self, wn):
|
| 549 |
+
if wn.startswith("weight"):
|
| 550 |
+
weight_or_bias = get_quantized_weight(self, wn)
|
| 551 |
+
else:
|
| 552 |
+
weight_or_bias = getattr(self, wn)
|
| 553 |
+
else:
|
| 554 |
+
weight_or_bias = None
|
| 555 |
+
quantized_weight_bias_dict[wn] = weight_or_bias
|
| 556 |
+
return quantized_weight_bias_dict
|
| 557 |
+
|
| 558 |
+
def get_flat_weights(self):
|
| 559 |
+
flat_weights = []
|
| 560 |
+
for wn in self._flat_weights_names:
|
| 561 |
+
if hasattr(self, wn):
|
| 562 |
+
weight = getattr(self, wn)
|
| 563 |
+
if wn.startswith("weight"):
|
| 564 |
+
params = _get_weight_and_quantization_params(self, wn)
|
| 565 |
+
weight = _quantize_and_dequantize_weight(*params)
|
| 566 |
+
else:
|
| 567 |
+
weight = None
|
| 568 |
+
flat_weights.append(weight)
|
| 569 |
+
return flat_weights
|
| 570 |
+
|
| 571 |
+
def forward(self, input, hx=None): # noqa: F811
|
| 572 |
+
orig_input = input
|
| 573 |
+
# xxx: isinstance check needs to be in conditional for TorchScript to compile
|
| 574 |
+
batch_sizes = None
|
| 575 |
+
if isinstance(orig_input, PackedSequence):
|
| 576 |
+
input, batch_sizes, sorted_indices, unsorted_indices = input
|
| 577 |
+
max_batch_size = int(batch_sizes[0])
|
| 578 |
+
else:
|
| 579 |
+
batch_sizes = None
|
| 580 |
+
is_batched = input.dim() == 3
|
| 581 |
+
batch_dim = 0 if self.batch_first else 1
|
| 582 |
+
if not is_batched:
|
| 583 |
+
input = input.unsqueeze(batch_dim)
|
| 584 |
+
max_batch_size = input.size(0) if self.batch_first else input.size(1)
|
| 585 |
+
sorted_indices = None
|
| 586 |
+
unsorted_indices = None
|
| 587 |
+
|
| 588 |
+
if hx is None:
|
| 589 |
+
num_directions = 2 if self.bidirectional else 1
|
| 590 |
+
real_hidden_size = (
|
| 591 |
+
self.proj_size if self.proj_size > 0 else self.hidden_size
|
| 592 |
+
)
|
| 593 |
+
h_zeros = torch.zeros(
|
| 594 |
+
self.num_layers * num_directions,
|
| 595 |
+
max_batch_size,
|
| 596 |
+
real_hidden_size,
|
| 597 |
+
dtype=input.dtype,
|
| 598 |
+
device=input.device,
|
| 599 |
+
)
|
| 600 |
+
c_zeros = torch.zeros(
|
| 601 |
+
self.num_layers * num_directions,
|
| 602 |
+
max_batch_size,
|
| 603 |
+
self.hidden_size,
|
| 604 |
+
dtype=input.dtype,
|
| 605 |
+
device=input.device,
|
| 606 |
+
)
|
| 607 |
+
hx = (h_zeros, c_zeros)
|
| 608 |
+
else:
|
| 609 |
+
if batch_sizes is None: # If not PackedSequence input.
|
| 610 |
+
if is_batched: # type: ignore[possibly-undefined]
|
| 611 |
+
if hx[0].dim() != 3 or hx[1].dim() != 3:
|
| 612 |
+
msg = (
|
| 613 |
+
"For batched 3-D input, hx and cx should "
|
| 614 |
+
f"also be 3-D but got ({hx[0].dim()}-D, {hx[1].dim()}-D) tensors"
|
| 615 |
+
)
|
| 616 |
+
raise RuntimeError(msg)
|
| 617 |
+
else:
|
| 618 |
+
if hx[0].dim() != 2 or hx[1].dim() != 2:
|
| 619 |
+
msg = (
|
| 620 |
+
"For unbatched 2-D input, hx and cx should "
|
| 621 |
+
f"also be 2-D but got ({hx[0].dim()}-D, {hx[1].dim()}-D) tensors"
|
| 622 |
+
)
|
| 623 |
+
raise RuntimeError(msg)
|
| 624 |
+
hx = (hx[0].unsqueeze(1), hx[1].unsqueeze(1))
|
| 625 |
+
|
| 626 |
+
# Each batch of the hidden state should match the input sequence that
|
| 627 |
+
# the user believes he/she is passing in.
|
| 628 |
+
hx = self.permute_hidden(hx, sorted_indices)
|
| 629 |
+
|
| 630 |
+
self.check_forward_args(input, hx, batch_sizes)
|
| 631 |
+
if batch_sizes is None:
|
| 632 |
+
result = _VF.lstm(
|
| 633 |
+
input,
|
| 634 |
+
hx,
|
| 635 |
+
self.get_flat_weights(),
|
| 636 |
+
self.bias,
|
| 637 |
+
self.num_layers,
|
| 638 |
+
self.dropout,
|
| 639 |
+
self.training,
|
| 640 |
+
self.bidirectional,
|
| 641 |
+
self.batch_first,
|
| 642 |
+
)
|
| 643 |
+
else:
|
| 644 |
+
result = _VF.lstm(
|
| 645 |
+
input,
|
| 646 |
+
batch_sizes,
|
| 647 |
+
hx,
|
| 648 |
+
self.get_flat_weights(),
|
| 649 |
+
self.bias,
|
| 650 |
+
self.num_layers,
|
| 651 |
+
self.dropout,
|
| 652 |
+
self.training,
|
| 653 |
+
self.bidirectional,
|
| 654 |
+
)
|
| 655 |
+
output = result[0]
|
| 656 |
+
hidden = result[1:]
|
| 657 |
+
# xxx: isinstance check needs to be in conditional for TorchScript to compile
|
| 658 |
+
if isinstance(orig_input, PackedSequence):
|
| 659 |
+
output_packed = PackedSequence(
|
| 660 |
+
output, batch_sizes, sorted_indices, unsorted_indices
|
| 661 |
+
)
|
| 662 |
+
return output_packed, self.permute_hidden(hidden, unsorted_indices)
|
| 663 |
+
else:
|
| 664 |
+
if not is_batched: # type: ignore[possibly-undefined]
|
| 665 |
+
output = output.squeeze(batch_dim) # type: ignore[possibly-undefined]
|
| 666 |
+
hidden = (hidden[0].squeeze(1), hidden[1].squeeze(1))
|
| 667 |
+
return output, self.permute_hidden(hidden, unsorted_indices)
|
| 668 |
+
|
| 669 |
+
def _get_name(self):
|
| 670 |
+
return "QuantizedLSTM(Reference)"
|
| 671 |
+
|
| 672 |
+
@classmethod
|
| 673 |
+
def from_float(cls, mod, weight_qparams_dict):
|
| 674 |
+
ref_mod = cls(
|
| 675 |
+
mod.input_size,
|
| 676 |
+
mod.hidden_size,
|
| 677 |
+
mod.num_layers,
|
| 678 |
+
mod.bias,
|
| 679 |
+
mod.batch_first,
|
| 680 |
+
mod.dropout,
|
| 681 |
+
mod.bidirectional,
|
| 682 |
+
weight_qparams_dict=weight_qparams_dict,
|
| 683 |
+
)
|
| 684 |
+
for wn in mod._flat_weights_names:
|
| 685 |
+
setattr(ref_mod, wn, getattr(mod, wn))
|
| 686 |
+
return ref_mod
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
class GRU(RNNBase):
|
| 690 |
+
"""Reference Quantized GRU Module
|
| 691 |
+
We'll store weight_qparams for all the weights in _flat_weights, we need to pass in
|
| 692 |
+
a `weight_qparams_dict` that maps from weight name, e.g. weight_ih_l0,
|
| 693 |
+
to the weight_qparams for that weight
|
| 694 |
+
"""
|
| 695 |
+
|
| 696 |
+
def __init__(self, *args, **kwargs):
|
| 697 |
+
if "proj_size" in kwargs:
|
| 698 |
+
raise ValueError(
|
| 699 |
+
"proj_size argument is only supported for LSTM, not RNN or GRU"
|
| 700 |
+
)
|
| 701 |
+
super().__init__("GRU", *args, **kwargs)
|
| 702 |
+
|
| 703 |
+
def get_quantized_weight_bias_dict(self):
|
| 704 |
+
"""dictionary from flat_weight_name to quantized weight or (unquantized) bias
|
| 705 |
+
e.g.
|
| 706 |
+
{
|
| 707 |
+
"weight_ih_l0": quantized_weight,
|
| 708 |
+
"bias_ih_l0": unquantized_bias,
|
| 709 |
+
...
|
| 710 |
+
}
|
| 711 |
+
"""
|
| 712 |
+
quantized_weight_bias_dict = {}
|
| 713 |
+
for wn in self._flat_weights_names:
|
| 714 |
+
if hasattr(self, wn):
|
| 715 |
+
if wn.startswith("weight"):
|
| 716 |
+
weight_or_bias = get_quantized_weight(self, wn)
|
| 717 |
+
else:
|
| 718 |
+
weight_or_bias = getattr(self, wn)
|
| 719 |
+
else:
|
| 720 |
+
weight_or_bias = None
|
| 721 |
+
quantized_weight_bias_dict[wn] = weight_or_bias
|
| 722 |
+
return quantized_weight_bias_dict
|
| 723 |
+
|
| 724 |
+
def get_flat_weights(self):
|
| 725 |
+
flat_weights = []
|
| 726 |
+
for wn in self._flat_weights_names:
|
| 727 |
+
if hasattr(self, wn):
|
| 728 |
+
weight = getattr(self, wn)
|
| 729 |
+
if wn.startswith("weight"):
|
| 730 |
+
params = _get_weight_and_quantization_params(self, wn)
|
| 731 |
+
weight = _quantize_and_dequantize_weight(*params)
|
| 732 |
+
else:
|
| 733 |
+
weight = None
|
| 734 |
+
flat_weights.append(weight)
|
| 735 |
+
return flat_weights
|
| 736 |
+
|
| 737 |
+
def forward(self, input, hx=None): # noqa: F811
|
| 738 |
+
# Note: this is copied from the forward of GRU in https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/rnn.py
|
| 739 |
+
# only changed self._flat_weights to self.get_flat_weights()
|
| 740 |
+
# TODO: maybe we can try inheriting from that class and define get_flat_weights
|
| 741 |
+
# as a @property? this might interfere with TorchScript, if we remove that
|
| 742 |
+
# requirement in the future we should be able to do this
|
| 743 |
+
orig_input = input
|
| 744 |
+
# xxx: isinstance check needs to be in conditional for TorchScript to compile
|
| 745 |
+
if isinstance(orig_input, PackedSequence):
|
| 746 |
+
input, batch_sizes, sorted_indices, unsorted_indices = input
|
| 747 |
+
max_batch_size = int(batch_sizes[0])
|
| 748 |
+
else:
|
| 749 |
+
batch_sizes = None
|
| 750 |
+
assert input.dim() in (
|
| 751 |
+
2,
|
| 752 |
+
3,
|
| 753 |
+
), f"GRU: Expected input to be 2-D or 3-D but received {input.dim()}-D tensor"
|
| 754 |
+
is_batched = input.dim() == 3
|
| 755 |
+
batch_dim = 0 if self.batch_first else 1
|
| 756 |
+
if not is_batched:
|
| 757 |
+
input = input.unsqueeze(batch_dim)
|
| 758 |
+
if hx is not None:
|
| 759 |
+
if hx.dim() != 2:
|
| 760 |
+
raise RuntimeError(
|
| 761 |
+
f"For unbatched 2-D input, hx should also be 2-D but got {hx.dim()}-D tensor"
|
| 762 |
+
)
|
| 763 |
+
hx = hx.unsqueeze(1)
|
| 764 |
+
else:
|
| 765 |
+
if hx is not None and hx.dim() != 3:
|
| 766 |
+
raise RuntimeError(
|
| 767 |
+
f"For batched 3-D input, hx should also be 3-D but got {hx.dim()}-D tensor"
|
| 768 |
+
)
|
| 769 |
+
max_batch_size = input.size(0) if self.batch_first else input.size(1)
|
| 770 |
+
sorted_indices = None
|
| 771 |
+
unsorted_indices = None
|
| 772 |
+
|
| 773 |
+
if hx is None:
|
| 774 |
+
num_directions = 2 if self.bidirectional else 1
|
| 775 |
+
hx = torch.zeros(
|
| 776 |
+
self.num_layers * num_directions,
|
| 777 |
+
max_batch_size,
|
| 778 |
+
self.hidden_size,
|
| 779 |
+
dtype=input.dtype,
|
| 780 |
+
device=input.device,
|
| 781 |
+
)
|
| 782 |
+
else:
|
| 783 |
+
# Each batch of the hidden state should match the input sequence that
|
| 784 |
+
# the user believes he/she is passing in.
|
| 785 |
+
hx = self.permute_hidden(hx, sorted_indices)
|
| 786 |
+
|
| 787 |
+
self.check_forward_args(input, hx, batch_sizes)
|
| 788 |
+
if batch_sizes is None:
|
| 789 |
+
result = _VF.gru(
|
| 790 |
+
input,
|
| 791 |
+
hx,
|
| 792 |
+
self.get_flat_weights(),
|
| 793 |
+
self.bias,
|
| 794 |
+
self.num_layers,
|
| 795 |
+
self.dropout,
|
| 796 |
+
self.training,
|
| 797 |
+
self.bidirectional,
|
| 798 |
+
self.batch_first,
|
| 799 |
+
)
|
| 800 |
+
else:
|
| 801 |
+
result = _VF.gru(
|
| 802 |
+
input,
|
| 803 |
+
batch_sizes,
|
| 804 |
+
hx,
|
| 805 |
+
self.get_flat_weights(),
|
| 806 |
+
self.bias,
|
| 807 |
+
self.num_layers,
|
| 808 |
+
self.dropout,
|
| 809 |
+
self.training,
|
| 810 |
+
self.bidirectional,
|
| 811 |
+
)
|
| 812 |
+
output = result[0]
|
| 813 |
+
hidden = result[1]
|
| 814 |
+
|
| 815 |
+
# xxx: isinstance check needs to be in conditional for TorchScript to compile
|
| 816 |
+
if isinstance(orig_input, PackedSequence):
|
| 817 |
+
output_packed = PackedSequence(
|
| 818 |
+
output, batch_sizes, sorted_indices, unsorted_indices
|
| 819 |
+
)
|
| 820 |
+
return output_packed, self.permute_hidden(hidden, unsorted_indices)
|
| 821 |
+
else:
|
| 822 |
+
if not is_batched: # type: ignore[possibly-undefined]
|
| 823 |
+
output = output.squeeze(batch_dim) # type: ignore[possibly-undefined]
|
| 824 |
+
hidden = hidden.squeeze(1)
|
| 825 |
+
|
| 826 |
+
return output, self.permute_hidden(hidden, unsorted_indices)
|
| 827 |
+
|
| 828 |
+
def _get_name(self):
|
| 829 |
+
return "QuantizedGRU(Reference)"
|
| 830 |
+
|
| 831 |
+
@classmethod
|
| 832 |
+
def from_float(cls, mod, weight_qparams_dict):
|
| 833 |
+
ref_mod = cls(
|
| 834 |
+
mod.input_size,
|
| 835 |
+
mod.hidden_size,
|
| 836 |
+
mod.num_layers,
|
| 837 |
+
mod.bias,
|
| 838 |
+
mod.batch_first,
|
| 839 |
+
mod.dropout,
|
| 840 |
+
mod.bidirectional,
|
| 841 |
+
weight_qparams_dict=weight_qparams_dict,
|
| 842 |
+
)
|
| 843 |
+
for wn in mod._flat_weights_names:
|
| 844 |
+
setattr(ref_mod, wn, getattr(mod, wn))
|
| 845 |
+
return ref_mod
|
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
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from typing import Any, Dict, Optional
|
| 3 |
+
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
|
| 8 |
+
from .utils import ReferenceQuantizedModule
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
__all__ = ["Embedding", "EmbeddingBag"]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Embedding(nn.Embedding, ReferenceQuantizedModule):
|
| 15 |
+
"""A reference quantized Embedding module that fits into the
|
| 16 |
+
FX Graph Mode Quantization workflow, activation will be floating point Tensor,
|
| 17 |
+
we will store floating point weight as well in the module, but in forward we'll
|
| 18 |
+
quantize and dequantize the weight before running the floating point functional
|
| 19 |
+
embedding operator.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
num_embeddings: int,
|
| 25 |
+
embedding_dim: int,
|
| 26 |
+
padding_idx: Optional[int] = None,
|
| 27 |
+
max_norm: Optional[float] = None,
|
| 28 |
+
norm_type: float = 2.0,
|
| 29 |
+
scale_grad_by_freq: bool = False,
|
| 30 |
+
sparse: bool = False,
|
| 31 |
+
_weight: Optional[Tensor] = None,
|
| 32 |
+
device=None,
|
| 33 |
+
dtype=None,
|
| 34 |
+
weight_qparams: Optional[Dict[str, Any]] = None,
|
| 35 |
+
) -> None:
|
| 36 |
+
super().__init__(
|
| 37 |
+
num_embeddings,
|
| 38 |
+
embedding_dim,
|
| 39 |
+
padding_idx,
|
| 40 |
+
max_norm,
|
| 41 |
+
norm_type,
|
| 42 |
+
scale_grad_by_freq,
|
| 43 |
+
sparse,
|
| 44 |
+
_weight,
|
| 45 |
+
device,
|
| 46 |
+
dtype,
|
| 47 |
+
)
|
| 48 |
+
self._init_weight_qparams(weight_qparams, device)
|
| 49 |
+
|
| 50 |
+
def _get_name(self):
|
| 51 |
+
return "QuantizedEmbedding(Reference)"
|
| 52 |
+
|
| 53 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 54 |
+
weight_quant_dequant = self.get_weight()
|
| 55 |
+
return F.embedding(
|
| 56 |
+
input,
|
| 57 |
+
weight_quant_dequant,
|
| 58 |
+
self.padding_idx,
|
| 59 |
+
self.max_norm,
|
| 60 |
+
self.norm_type,
|
| 61 |
+
self.scale_grad_by_freq,
|
| 62 |
+
self.sparse,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
@classmethod
|
| 66 |
+
def from_float(cls, mod, weight_qparams):
|
| 67 |
+
return cls(
|
| 68 |
+
mod.num_embeddings,
|
| 69 |
+
mod.embedding_dim,
|
| 70 |
+
mod.padding_idx,
|
| 71 |
+
mod.max_norm,
|
| 72 |
+
mod.norm_type,
|
| 73 |
+
mod.scale_grad_by_freq,
|
| 74 |
+
mod.sparse,
|
| 75 |
+
mod.weight,
|
| 76 |
+
mod.weight.device,
|
| 77 |
+
mod.weight.dtype,
|
| 78 |
+
weight_qparams,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class EmbeddingBag(nn.EmbeddingBag, ReferenceQuantizedModule):
|
| 83 |
+
"""A reference quantized EmbeddingBag module that fits into the
|
| 84 |
+
FX Graph Mode Quantization workflow, activation will be floating point Tensor,
|
| 85 |
+
we will store floating point weight as well in the module, but in forward we'll
|
| 86 |
+
quantize and dequantize the weight before running the floating point functional
|
| 87 |
+
embedding operator.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
def __init__(
|
| 91 |
+
self,
|
| 92 |
+
num_embeddings: int,
|
| 93 |
+
embedding_dim: int,
|
| 94 |
+
max_norm: Optional[float] = None,
|
| 95 |
+
norm_type: float = 2.0,
|
| 96 |
+
scale_grad_by_freq: bool = False,
|
| 97 |
+
mode: str = "mean",
|
| 98 |
+
sparse: bool = False,
|
| 99 |
+
_weight: Optional[Tensor] = None,
|
| 100 |
+
include_last_offset: bool = False,
|
| 101 |
+
padding_idx: Optional[int] = None,
|
| 102 |
+
device=None,
|
| 103 |
+
dtype=None,
|
| 104 |
+
weight_qparams: Optional[Dict[str, Any]] = None,
|
| 105 |
+
) -> None:
|
| 106 |
+
super().__init__(
|
| 107 |
+
num_embeddings,
|
| 108 |
+
embedding_dim,
|
| 109 |
+
max_norm,
|
| 110 |
+
norm_type,
|
| 111 |
+
scale_grad_by_freq,
|
| 112 |
+
mode,
|
| 113 |
+
sparse,
|
| 114 |
+
_weight,
|
| 115 |
+
include_last_offset,
|
| 116 |
+
padding_idx,
|
| 117 |
+
device,
|
| 118 |
+
dtype,
|
| 119 |
+
)
|
| 120 |
+
self._init_weight_qparams(weight_qparams, device)
|
| 121 |
+
|
| 122 |
+
def _get_name(self):
|
| 123 |
+
return "QuantizedEmbedding(Reference)"
|
| 124 |
+
|
| 125 |
+
def forward(
|
| 126 |
+
self,
|
| 127 |
+
input: Tensor,
|
| 128 |
+
offsets: Optional[Tensor] = None,
|
| 129 |
+
per_sample_weights: Optional[Tensor] = None,
|
| 130 |
+
) -> Tensor:
|
| 131 |
+
weight_quant_dequant = self.get_weight()
|
| 132 |
+
return F.embedding_bag(
|
| 133 |
+
input,
|
| 134 |
+
weight_quant_dequant,
|
| 135 |
+
offsets,
|
| 136 |
+
self.max_norm,
|
| 137 |
+
self.norm_type,
|
| 138 |
+
self.scale_grad_by_freq,
|
| 139 |
+
self.mode,
|
| 140 |
+
self.sparse,
|
| 141 |
+
per_sample_weights,
|
| 142 |
+
self.include_last_offset,
|
| 143 |
+
self.padding_idx,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
@classmethod
|
| 147 |
+
def from_float(cls, mod, weight_qparams, use_precomputed_fake_quant=False):
|
| 148 |
+
return cls(
|
| 149 |
+
mod.num_embeddings,
|
| 150 |
+
mod.embedding_dim,
|
| 151 |
+
mod.max_norm,
|
| 152 |
+
mod.norm_type,
|
| 153 |
+
mod.scale_grad_by_freq,
|
| 154 |
+
mod.mode,
|
| 155 |
+
mod.sparse,
|
| 156 |
+
mod.weight,
|
| 157 |
+
mod.include_last_offset,
|
| 158 |
+
mod.padding_idx,
|
| 159 |
+
mod.weight.device,
|
| 160 |
+
mod.weight.dtype,
|
| 161 |
+
weight_qparams,
|
| 162 |
+
)
|
vllm/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/utils.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import typing
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"ReferenceQuantizedModule",
|
| 9 |
+
]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ReferenceQuantizedModule(torch.nn.Module):
|
| 13 |
+
def _init_weight_qparams(self, weight_qparams, device):
|
| 14 |
+
if weight_qparams is None:
|
| 15 |
+
weight_qparams = {
|
| 16 |
+
"qscheme": torch.per_tensor_affine,
|
| 17 |
+
"dtype": torch.quint8,
|
| 18 |
+
"scale": 1.0,
|
| 19 |
+
"zero_point": 0,
|
| 20 |
+
}
|
| 21 |
+
self.weight_qscheme: torch.qscheme = weight_qparams["qscheme"]
|
| 22 |
+
self.weight_dtype = weight_qparams["dtype"]
|
| 23 |
+
assert self.weight_qscheme in [
|
| 24 |
+
None,
|
| 25 |
+
torch.per_tensor_affine,
|
| 26 |
+
torch.per_channel_affine,
|
| 27 |
+
torch.per_channel_affine_float_qparams,
|
| 28 |
+
], f"qscheme: {self.weight_qscheme} is not support in reference quantized {self._get_name()}"
|
| 29 |
+
if self.weight_dtype in [
|
| 30 |
+
torch.quint8,
|
| 31 |
+
torch.qint8,
|
| 32 |
+
torch.quint4x2,
|
| 33 |
+
torch.qint32,
|
| 34 |
+
]:
|
| 35 |
+
zero_point_dtype = (
|
| 36 |
+
weight_qparams["zero_point"].dtype
|
| 37 |
+
if isinstance(weight_qparams["zero_point"], torch.Tensor)
|
| 38 |
+
else torch.int
|
| 39 |
+
)
|
| 40 |
+
w_scale = weight_qparams["scale"]
|
| 41 |
+
w_scale_tensor = (
|
| 42 |
+
w_scale.clone().detach()
|
| 43 |
+
if isinstance(w_scale, torch.Tensor)
|
| 44 |
+
else torch.tensor(w_scale, dtype=torch.float, device=device)
|
| 45 |
+
)
|
| 46 |
+
self.register_buffer("weight_scale", w_scale_tensor)
|
| 47 |
+
w_zp = weight_qparams["zero_point"]
|
| 48 |
+
w_zp_tensor = (
|
| 49 |
+
w_zp.clone().detach()
|
| 50 |
+
if isinstance(w_zp, torch.Tensor)
|
| 51 |
+
else torch.tensor(w_zp, dtype=zero_point_dtype, device=device)
|
| 52 |
+
)
|
| 53 |
+
self.register_buffer("weight_zero_point", w_zp_tensor)
|
| 54 |
+
if self.weight_qscheme in [
|
| 55 |
+
torch.per_channel_affine,
|
| 56 |
+
torch.per_channel_affine_float_qparams,
|
| 57 |
+
]:
|
| 58 |
+
w_axis = weight_qparams["axis"]
|
| 59 |
+
w_axis_tensor = (
|
| 60 |
+
w_axis.clone().detach()
|
| 61 |
+
if isinstance(w_axis, torch.Tensor)
|
| 62 |
+
else torch.tensor(w_axis, dtype=torch.int, device=device)
|
| 63 |
+
)
|
| 64 |
+
self.register_buffer("weight_axis", w_axis_tensor)
|
| 65 |
+
else:
|
| 66 |
+
# added for TorchScriptability, not used
|
| 67 |
+
self.register_buffer(
|
| 68 |
+
"weight_axis", torch.tensor(0, dtype=torch.int, device=device)
|
| 69 |
+
)
|
| 70 |
+
else:
|
| 71 |
+
# added for TorchScriptability, and for torch.float
|
| 72 |
+
self.register_buffer(
|
| 73 |
+
"weight_scale", torch.tensor(1.0, dtype=torch.float, device=device)
|
| 74 |
+
)
|
| 75 |
+
self.register_buffer(
|
| 76 |
+
"weight_zero_point", torch.tensor(0, dtype=torch.int, device=device)
|
| 77 |
+
)
|
| 78 |
+
self.register_buffer(
|
| 79 |
+
"weight_axis", torch.tensor(0, dtype=torch.int, device=device)
|
| 80 |
+
)
|
| 81 |
+
self.is_decomposed: bool = weight_qparams.get("is_decomposed", False)
|
| 82 |
+
# store weight_axis as weight_axis_int due to some constraints of torchdynamo.export
|
| 83 |
+
# for capturing `.item` operations
|
| 84 |
+
self.weight_axis_int: int = self.weight_axis.item() # type: ignore[operator, assignment]
|
| 85 |
+
self.weight_quant_min: typing.Optional[int] = weight_qparams.get(
|
| 86 |
+
"quant_min", None
|
| 87 |
+
)
|
| 88 |
+
self.weight_quant_max: typing.Optional[int] = weight_qparams.get(
|
| 89 |
+
"quant_max", None
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
def get_weight(self):
|
| 93 |
+
"""
|
| 94 |
+
Fake quantize (quantize and dequantize) the weight with
|
| 95 |
+
the quantization parameters for weight, this is used to
|
| 96 |
+
simulate the numerics for the quantized weight in a quantized
|
| 97 |
+
model
|
| 98 |
+
"""
|
| 99 |
+
# suppress mypy warning
|
| 100 |
+
assert isinstance(self.weight_scale, torch.Tensor)
|
| 101 |
+
assert isinstance(self.weight_zero_point, torch.Tensor)
|
| 102 |
+
if self.is_decomposed:
|
| 103 |
+
return _quantize_and_dequantize_weight_decomposed(
|
| 104 |
+
self.weight, # type: ignore[arg-type]
|
| 105 |
+
self.weight_qscheme,
|
| 106 |
+
self.weight_dtype,
|
| 107 |
+
self.weight_scale,
|
| 108 |
+
self.weight_zero_point,
|
| 109 |
+
self.weight_axis_int,
|
| 110 |
+
self.weight_quant_min,
|
| 111 |
+
self.weight_quant_max,
|
| 112 |
+
)
|
| 113 |
+
else:
|
| 114 |
+
return _quantize_and_dequantize_weight(
|
| 115 |
+
self.weight, # type: ignore[arg-type]
|
| 116 |
+
self.weight_qscheme,
|
| 117 |
+
self.weight_dtype,
|
| 118 |
+
self.weight_scale,
|
| 119 |
+
self.weight_zero_point,
|
| 120 |
+
self.weight_axis_int,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
def get_quantized_weight(self):
|
| 124 |
+
# suppress mypy warning
|
| 125 |
+
assert isinstance(self.weight_scale, torch.Tensor)
|
| 126 |
+
assert isinstance(self.weight_zero_point, torch.Tensor)
|
| 127 |
+
# assert isinstance(self.weight_axis, torch.Tensor)
|
| 128 |
+
if self.is_decomposed:
|
| 129 |
+
return _quantize_weight_decomposed(
|
| 130 |
+
self.weight, # type: ignore[arg-type]
|
| 131 |
+
self.weight_qscheme,
|
| 132 |
+
self.weight_dtype,
|
| 133 |
+
self.weight_scale,
|
| 134 |
+
self.weight_zero_point,
|
| 135 |
+
self.weight_axis_int,
|
| 136 |
+
self.weight_quant_min,
|
| 137 |
+
self.weight_quant_max,
|
| 138 |
+
)
|
| 139 |
+
else:
|
| 140 |
+
return _quantize_weight(
|
| 141 |
+
self.weight, # type: ignore[arg-type]
|
| 142 |
+
self.weight_qscheme,
|
| 143 |
+
self.weight_dtype,
|
| 144 |
+
self.weight_scale,
|
| 145 |
+
self.weight_zero_point,
|
| 146 |
+
self.weight_axis_int,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
| 150 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
| 151 |
+
_save_weight_qparams(
|
| 152 |
+
destination,
|
| 153 |
+
prefix,
|
| 154 |
+
self.weight_qscheme,
|
| 155 |
+
self.weight_dtype,
|
| 156 |
+
self.weight_scale,
|
| 157 |
+
self.weight_zero_point,
|
| 158 |
+
self.weight_axis,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
def _load_from_state_dict(
|
| 162 |
+
self,
|
| 163 |
+
state_dict,
|
| 164 |
+
prefix,
|
| 165 |
+
local_metadata,
|
| 166 |
+
strict,
|
| 167 |
+
missing_keys,
|
| 168 |
+
unexpected_keys,
|
| 169 |
+
error_msgs,
|
| 170 |
+
):
|
| 171 |
+
for key in _get_weight_qparam_keys(state_dict, prefix):
|
| 172 |
+
setattr(self, key, state_dict[prefix + key])
|
| 173 |
+
state_dict.pop(prefix + key)
|
| 174 |
+
|
| 175 |
+
super()._load_from_state_dict(
|
| 176 |
+
state_dict,
|
| 177 |
+
prefix,
|
| 178 |
+
local_metadata,
|
| 179 |
+
False,
|
| 180 |
+
missing_keys,
|
| 181 |
+
unexpected_keys,
|
| 182 |
+
error_msgs,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _quantize_weight_decomposed(
|
| 187 |
+
weight: torch.Tensor,
|
| 188 |
+
weight_qscheme: torch.qscheme,
|
| 189 |
+
weight_dtype: torch.dtype,
|
| 190 |
+
weight_scale: torch.Tensor,
|
| 191 |
+
weight_zero_point: torch.Tensor,
|
| 192 |
+
weight_axis: int,
|
| 193 |
+
weight_quant_min: typing.Optional[int],
|
| 194 |
+
weight_quant_max: typing.Optional[int],
|
| 195 |
+
) -> torch.Tensor:
|
| 196 |
+
_DTYPE_TO_QVALUE_BOUNDS = {
|
| 197 |
+
torch.uint8: (0, 255),
|
| 198 |
+
torch.int8: (-128, 127),
|
| 199 |
+
torch.int32: (-(2**31), 2**31 - 1),
|
| 200 |
+
}
|
| 201 |
+
# TODO: add an util function for converting qdtype to dtype
|
| 202 |
+
_QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE = {
|
| 203 |
+
torch.quint8: torch.uint8,
|
| 204 |
+
torch.qint8: torch.int8,
|
| 205 |
+
torch.qint32: torch.int32,
|
| 206 |
+
}
|
| 207 |
+
if weight_qscheme == torch.per_tensor_affine:
|
| 208 |
+
if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
|
| 209 |
+
weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
|
| 210 |
+
if weight_quant_min is None or weight_quant_max is None:
|
| 211 |
+
weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[
|
| 212 |
+
weight_dtype_
|
| 213 |
+
]
|
| 214 |
+
weight = torch.ops.quantized_decomposed.quantize_per_tensor(
|
| 215 |
+
weight,
|
| 216 |
+
weight_scale,
|
| 217 |
+
weight_zero_point,
|
| 218 |
+
weight_quant_min,
|
| 219 |
+
weight_quant_max,
|
| 220 |
+
weight_dtype_,
|
| 221 |
+
)
|
| 222 |
+
return weight
|
| 223 |
+
elif weight_qscheme in [
|
| 224 |
+
torch.per_channel_affine,
|
| 225 |
+
torch.per_channel_affine_float_qparams,
|
| 226 |
+
]:
|
| 227 |
+
# TODO: torch.quint4x2 is not supported
|
| 228 |
+
if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
|
| 229 |
+
weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
|
| 230 |
+
if weight_quant_min is None or weight_quant_max is None:
|
| 231 |
+
weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[
|
| 232 |
+
weight_dtype_
|
| 233 |
+
]
|
| 234 |
+
weight = torch.ops.quantized_decomposed.quantize_per_channel(
|
| 235 |
+
weight,
|
| 236 |
+
weight_scale,
|
| 237 |
+
weight_zero_point,
|
| 238 |
+
weight_axis,
|
| 239 |
+
weight_quant_min,
|
| 240 |
+
weight_quant_max,
|
| 241 |
+
weight_dtype_,
|
| 242 |
+
) # type: ignore[arg-type]
|
| 243 |
+
return weight
|
| 244 |
+
raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _dequantize_weight_decomposed(
|
| 248 |
+
weight: torch.Tensor,
|
| 249 |
+
weight_qscheme: torch.qscheme,
|
| 250 |
+
weight_dtype: torch.dtype,
|
| 251 |
+
weight_scale: torch.Tensor,
|
| 252 |
+
weight_zero_point: torch.Tensor,
|
| 253 |
+
weight_axis: int,
|
| 254 |
+
weight_quant_min: typing.Optional[int],
|
| 255 |
+
weight_quant_max: typing.Optional[int],
|
| 256 |
+
) -> torch.Tensor:
|
| 257 |
+
# TODO: get the quant_min and quant_max from activation_post_process
|
| 258 |
+
_DTYPE_TO_QVALUE_BOUNDS = {
|
| 259 |
+
torch.uint8: (0, 255),
|
| 260 |
+
torch.int8: (-128, 127),
|
| 261 |
+
torch.int32: (-(2**31), 2**31 - 1),
|
| 262 |
+
}
|
| 263 |
+
# TODO: add an util function for converting qdtype to dtype
|
| 264 |
+
_QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE = {
|
| 265 |
+
torch.quint8: torch.uint8,
|
| 266 |
+
torch.qint8: torch.int8,
|
| 267 |
+
torch.qint32: torch.int32,
|
| 268 |
+
}
|
| 269 |
+
weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
|
| 270 |
+
if weight_quant_min is None or weight_quant_max is None:
|
| 271 |
+
weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[weight_dtype_]
|
| 272 |
+
if weight_qscheme == torch.per_tensor_affine:
|
| 273 |
+
if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
|
| 274 |
+
weight = torch.ops.quantized_decomposed.dequantize_per_tensor(
|
| 275 |
+
weight,
|
| 276 |
+
weight_scale,
|
| 277 |
+
weight_zero_point,
|
| 278 |
+
weight_quant_min,
|
| 279 |
+
weight_quant_max,
|
| 280 |
+
weight_dtype_,
|
| 281 |
+
)
|
| 282 |
+
return weight
|
| 283 |
+
elif weight_qscheme in [
|
| 284 |
+
torch.per_channel_affine,
|
| 285 |
+
torch.per_channel_affine_float_qparams,
|
| 286 |
+
]:
|
| 287 |
+
# TODO: torch.quint4x2 is not supported
|
| 288 |
+
if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
|
| 289 |
+
weight = torch.ops.quantized_decomposed.dequantize_per_channel(
|
| 290 |
+
weight,
|
| 291 |
+
weight_scale,
|
| 292 |
+
weight_zero_point,
|
| 293 |
+
weight_axis,
|
| 294 |
+
weight_quant_min,
|
| 295 |
+
weight_quant_max,
|
| 296 |
+
weight_dtype_,
|
| 297 |
+
) # type: ignore[arg-type]
|
| 298 |
+
return weight
|
| 299 |
+
raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def _quantize_weight(
|
| 303 |
+
weight: torch.Tensor,
|
| 304 |
+
weight_qscheme: torch.qscheme,
|
| 305 |
+
weight_dtype: torch.dtype,
|
| 306 |
+
weight_scale: torch.Tensor,
|
| 307 |
+
weight_zero_point: torch.Tensor,
|
| 308 |
+
weight_axis_int: int,
|
| 309 |
+
) -> torch.Tensor:
|
| 310 |
+
if weight_dtype == torch.float16:
|
| 311 |
+
weight = weight.to(weight_dtype)
|
| 312 |
+
return weight
|
| 313 |
+
|
| 314 |
+
if weight_qscheme == torch.per_tensor_affine:
|
| 315 |
+
if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
|
| 316 |
+
weight = torch.quantize_per_tensor(
|
| 317 |
+
weight, weight_scale, weight_zero_point, weight_dtype
|
| 318 |
+
)
|
| 319 |
+
return weight
|
| 320 |
+
elif weight_qscheme in [
|
| 321 |
+
torch.per_channel_affine,
|
| 322 |
+
torch.per_channel_affine_float_qparams,
|
| 323 |
+
]:
|
| 324 |
+
if weight_dtype in [torch.quint8, torch.qint8, torch.quint4x2, torch.qint32]:
|
| 325 |
+
weight = torch.quantize_per_channel(
|
| 326 |
+
weight, weight_scale, weight_zero_point, weight_axis_int, weight_dtype
|
| 327 |
+
) # type: ignore[arg-type]
|
| 328 |
+
return weight
|
| 329 |
+
raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _quantize_and_dequantize_weight_decomposed(
|
| 333 |
+
weight: torch.Tensor,
|
| 334 |
+
weight_qscheme: torch.qscheme,
|
| 335 |
+
weight_dtype: torch.dtype,
|
| 336 |
+
weight_scale: torch.Tensor,
|
| 337 |
+
weight_zero_point: torch.Tensor,
|
| 338 |
+
weight_axis_int: int,
|
| 339 |
+
weight_quant_min: typing.Optional[int],
|
| 340 |
+
weight_quant_max: typing.Optional[int],
|
| 341 |
+
) -> torch.Tensor:
|
| 342 |
+
"""Quantize and then dequantize the weight based on
|
| 343 |
+
the quantization parameters
|
| 344 |
+
"""
|
| 345 |
+
if weight_qscheme in [
|
| 346 |
+
torch.per_tensor_affine,
|
| 347 |
+
torch.per_channel_affine,
|
| 348 |
+
torch.per_channel_affine_float_qparams,
|
| 349 |
+
]:
|
| 350 |
+
weight_quant = _quantize_weight_decomposed(
|
| 351 |
+
weight,
|
| 352 |
+
weight_qscheme,
|
| 353 |
+
weight_dtype,
|
| 354 |
+
weight_scale,
|
| 355 |
+
weight_zero_point,
|
| 356 |
+
weight_axis_int,
|
| 357 |
+
weight_quant_min,
|
| 358 |
+
weight_quant_max,
|
| 359 |
+
)
|
| 360 |
+
weight_dequant = _dequantize_weight_decomposed(
|
| 361 |
+
weight_quant,
|
| 362 |
+
weight_qscheme,
|
| 363 |
+
weight_dtype,
|
| 364 |
+
weight_scale,
|
| 365 |
+
weight_zero_point,
|
| 366 |
+
weight_axis_int,
|
| 367 |
+
weight_quant_min,
|
| 368 |
+
weight_quant_max,
|
| 369 |
+
)
|
| 370 |
+
else:
|
| 371 |
+
weight_dequant = weight
|
| 372 |
+
return weight_dequant
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _quantize_and_dequantize_weight(
|
| 376 |
+
weight: torch.Tensor,
|
| 377 |
+
weight_qscheme: torch.qscheme,
|
| 378 |
+
weight_dtype: torch.dtype,
|
| 379 |
+
weight_scale: torch.Tensor,
|
| 380 |
+
weight_zero_point: torch.Tensor,
|
| 381 |
+
weight_axis_int: int,
|
| 382 |
+
) -> torch.Tensor:
|
| 383 |
+
"""Quantize and then dequantize the weight based on
|
| 384 |
+
the quantization parameters
|
| 385 |
+
"""
|
| 386 |
+
if weight_qscheme in [
|
| 387 |
+
torch.per_tensor_affine,
|
| 388 |
+
torch.per_channel_affine,
|
| 389 |
+
torch.per_channel_affine_float_qparams,
|
| 390 |
+
]:
|
| 391 |
+
weight_quant = _quantize_weight(
|
| 392 |
+
weight,
|
| 393 |
+
weight_qscheme,
|
| 394 |
+
weight_dtype,
|
| 395 |
+
weight_scale,
|
| 396 |
+
weight_zero_point,
|
| 397 |
+
weight_axis_int,
|
| 398 |
+
)
|
| 399 |
+
weight_dequant = weight_quant.dequantize()
|
| 400 |
+
else:
|
| 401 |
+
weight_dequant = weight
|
| 402 |
+
return weight_dequant
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def _save_weight_qparams(
|
| 406 |
+
destination,
|
| 407 |
+
prefix,
|
| 408 |
+
weight_qscheme,
|
| 409 |
+
weight_dtype,
|
| 410 |
+
weight_scale,
|
| 411 |
+
weight_zero_point,
|
| 412 |
+
weight_axis,
|
| 413 |
+
):
|
| 414 |
+
destination[prefix + "weight_qscheme"] = weight_qscheme
|
| 415 |
+
destination[prefix + "weight_dtype"] = weight_dtype
|
| 416 |
+
if weight_qscheme is not None:
|
| 417 |
+
destination[prefix + "weight_scale"] = weight_scale
|
| 418 |
+
destination[prefix + "weight_zero_point"] = weight_zero_point
|
| 419 |
+
if weight_qscheme == torch.per_channel_affine:
|
| 420 |
+
destination[prefix + "weight_axis"] = weight_axis
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def _get_weight_qparam_keys(state_dict: typing.Dict[str, typing.Any], prefix: str):
|
| 424 |
+
keys = ["weight_qscheme", "weight_dtype"]
|
| 425 |
+
weight_qscheme = state_dict[prefix + "weight_qscheme"]
|
| 426 |
+
if weight_qscheme is not None:
|
| 427 |
+
keys.append("weight_scale")
|
| 428 |
+
keys.append("weight_zero_point")
|
| 429 |
+
if weight_qscheme == torch.quantize_per_channel:
|
| 430 |
+
keys.append("weight_axis")
|
| 431 |
+
return keys
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .backend_config import (
|
| 2 |
+
BackendConfig,
|
| 3 |
+
BackendPatternConfig,
|
| 4 |
+
DTypeConfig,
|
| 5 |
+
DTypeWithConstraints,
|
| 6 |
+
ObservationType,
|
| 7 |
+
)
|
| 8 |
+
from .executorch import get_executorch_backend_config
|
| 9 |
+
from .fbgemm import get_fbgemm_backend_config
|
| 10 |
+
from .native import get_native_backend_config, get_native_backend_config_dict
|
| 11 |
+
from .onednn import get_onednn_backend_config
|
| 12 |
+
from .qnnpack import get_qnnpack_backend_config
|
| 13 |
+
from .tensorrt import get_tensorrt_backend_config, get_tensorrt_backend_config_dict
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__all__ = [
|
| 17 |
+
"get_fbgemm_backend_config",
|
| 18 |
+
"get_native_backend_config",
|
| 19 |
+
"get_native_backend_config_dict",
|
| 20 |
+
"get_qnnpack_backend_config",
|
| 21 |
+
"get_tensorrt_backend_config",
|
| 22 |
+
"get_tensorrt_backend_config_dict",
|
| 23 |
+
"get_executorch_backend_config",
|
| 24 |
+
"BackendConfig",
|
| 25 |
+
"BackendPatternConfig",
|
| 26 |
+
"DTypeConfig",
|
| 27 |
+
"DTypeWithConstraints",
|
| 28 |
+
"ObservationType",
|
| 29 |
+
"get_onednn_backend_config",
|
| 30 |
+
]
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (868 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/_common_operator_config_utils.cpython-310.pyc
ADDED
|
Binary file (13.1 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/_qnnpack_pt2e.cpython-310.pyc
ADDED
|
Binary file (3.2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/backend_config.cpython-310.pyc
ADDED
|
Binary file (26.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/executorch.cpython-310.pyc
ADDED
|
Binary file (7.72 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/fbgemm.cpython-310.pyc
ADDED
|
Binary file (2.23 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/native.cpython-310.pyc
ADDED
|
Binary file (3.61 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/observation_type.cpython-310.pyc
ADDED
|
Binary file (194 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/onednn.cpython-310.pyc
ADDED
|
Binary file (10.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/qnnpack.cpython-310.pyc
ADDED
|
Binary file (2.62 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/tensorrt.cpython-310.pyc
ADDED
|
Binary file (2.08 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (9.69 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/x86.cpython-310.pyc
ADDED
|
Binary file (2.19 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_common_operator_config_utils.py
ADDED
|
@@ -0,0 +1,795 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import copy
|
| 3 |
+
import operator
|
| 4 |
+
from collections import namedtuple
|
| 5 |
+
from typing import Callable, Dict, List, Union
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.ao.nn.intrinsic as nni
|
| 9 |
+
import torch.ao.nn.intrinsic.qat as nniqat
|
| 10 |
+
import torch.ao.nn.qat as nnqat
|
| 11 |
+
import torch.ao.nn.quantized.reference as nnqr
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
from torch.ao.quantization.fuser_method_mappings import (
|
| 15 |
+
_sequential_wrapper2,
|
| 16 |
+
fuse_conv_bn,
|
| 17 |
+
fuse_conv_bn_relu,
|
| 18 |
+
fuse_convtranspose_bn,
|
| 19 |
+
fuse_linear_bn,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
from .backend_config import (
|
| 23 |
+
BackendPatternConfig,
|
| 24 |
+
DTypeConfig,
|
| 25 |
+
DTypeWithConstraints,
|
| 26 |
+
ObservationType,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
__all__: List[str] = []
|
| 31 |
+
|
| 32 |
+
# TODO: rename to be more explicit, e.g. qat_conv_relu
|
| 33 |
+
_ConvMetadata = namedtuple(
|
| 34 |
+
"_ConvMetadata",
|
| 35 |
+
[
|
| 36 |
+
"root",
|
| 37 |
+
"transpose",
|
| 38 |
+
"bn",
|
| 39 |
+
"reference",
|
| 40 |
+
"transpose_reference",
|
| 41 |
+
"fused_conv_relu",
|
| 42 |
+
"fused_conv_bn",
|
| 43 |
+
"fused_conv_bn_relu",
|
| 44 |
+
"qat",
|
| 45 |
+
"relu_qat",
|
| 46 |
+
"bn_qat",
|
| 47 |
+
"bn_relu_qat",
|
| 48 |
+
"func",
|
| 49 |
+
"func_transpose",
|
| 50 |
+
],
|
| 51 |
+
)
|
| 52 |
+
_Conv1dMetadata = _ConvMetadata(
|
| 53 |
+
nn.Conv1d,
|
| 54 |
+
nn.ConvTranspose1d,
|
| 55 |
+
nn.BatchNorm1d,
|
| 56 |
+
nnqr.Conv1d,
|
| 57 |
+
nnqr.ConvTranspose1d,
|
| 58 |
+
nni.ConvReLU1d,
|
| 59 |
+
nni.ConvBn1d,
|
| 60 |
+
nni.ConvBnReLU1d,
|
| 61 |
+
nnqat.Conv1d,
|
| 62 |
+
nniqat.ConvReLU1d,
|
| 63 |
+
nniqat.ConvBn1d,
|
| 64 |
+
nniqat.ConvBnReLU1d,
|
| 65 |
+
F.conv1d,
|
| 66 |
+
F.conv_transpose1d,
|
| 67 |
+
)
|
| 68 |
+
_Conv2dMetadata = _ConvMetadata(
|
| 69 |
+
nn.Conv2d,
|
| 70 |
+
nn.ConvTranspose2d,
|
| 71 |
+
nn.BatchNorm2d,
|
| 72 |
+
nnqr.Conv2d,
|
| 73 |
+
nnqr.ConvTranspose2d,
|
| 74 |
+
nni.ConvReLU2d,
|
| 75 |
+
nni.ConvBn2d,
|
| 76 |
+
nni.ConvBnReLU2d,
|
| 77 |
+
nnqat.Conv2d,
|
| 78 |
+
nniqat.ConvReLU2d,
|
| 79 |
+
nniqat.ConvBn2d,
|
| 80 |
+
nniqat.ConvBnReLU2d,
|
| 81 |
+
F.conv2d,
|
| 82 |
+
F.conv_transpose2d,
|
| 83 |
+
)
|
| 84 |
+
_Conv3dMetadata = _ConvMetadata(
|
| 85 |
+
nn.Conv3d,
|
| 86 |
+
nn.ConvTranspose3d,
|
| 87 |
+
nn.BatchNorm3d,
|
| 88 |
+
nnqr.Conv3d,
|
| 89 |
+
nnqr.ConvTranspose3d,
|
| 90 |
+
nni.ConvReLU3d,
|
| 91 |
+
nni.ConvBn3d,
|
| 92 |
+
nni.ConvBnReLU3d,
|
| 93 |
+
nnqat.Conv3d,
|
| 94 |
+
nniqat.ConvReLU3d,
|
| 95 |
+
nniqat.ConvBn3d,
|
| 96 |
+
nniqat.ConvBnReLU3d,
|
| 97 |
+
F.conv3d,
|
| 98 |
+
F.conv_transpose3d,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# Add constraints for fixed qparams ops like sigmoid and tanh to ensure values
|
| 102 |
+
# fall within the proper ranges, e.g. [0, 1] for sigmoid, [-1, 1] for tanh
|
| 103 |
+
_FIXED_QPARAM_OP_0TO1_CONSTRAINTS = DTypeWithConstraints(
|
| 104 |
+
dtype=torch.quint8,
|
| 105 |
+
quant_min_lower_bound=0,
|
| 106 |
+
quant_max_upper_bound=255,
|
| 107 |
+
scale_exact_match=1.0 / 256.0,
|
| 108 |
+
zero_point_exact_match=0,
|
| 109 |
+
)
|
| 110 |
+
_FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS = DTypeWithConstraints(
|
| 111 |
+
dtype=torch.quint8,
|
| 112 |
+
quant_min_lower_bound=0,
|
| 113 |
+
quant_max_upper_bound=255,
|
| 114 |
+
scale_exact_match=2.0 / 256.0,
|
| 115 |
+
zero_point_exact_match=128,
|
| 116 |
+
)
|
| 117 |
+
_FIXED_QPARAMS_OP_TO_CONSTRAINTS: Dict[Union[Callable, str], DTypeWithConstraints] = {
|
| 118 |
+
torch.nn.Hardsigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 119 |
+
torch.nn.functional.hardsigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 120 |
+
"hardsigmoid": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 121 |
+
"hardsigmoid_": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 122 |
+
torch.nn.Sigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 123 |
+
torch.sigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 124 |
+
"sigmoid": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 125 |
+
"sigmoid_": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 126 |
+
torch.nn.Softmax: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 127 |
+
torch.nn.Tanh: _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS,
|
| 128 |
+
torch.tanh: _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS,
|
| 129 |
+
"tanh": _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS,
|
| 130 |
+
"tanh_": _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS,
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _get_binary_op_configs(
|
| 135 |
+
dtype_configs: List[DTypeConfig],
|
| 136 |
+
) -> List[BackendPatternConfig]:
|
| 137 |
+
binary_op_configs: List[BackendPatternConfig] = []
|
| 138 |
+
num_tensor_args_to_observation_type_mapping = {
|
| 139 |
+
# TODO: this is not used right now since we have extra check in prepare
|
| 140 |
+
# will need to change this to NO_OBSERVER later after we implemented
|
| 141 |
+
# Tensor dtype inference properly
|
| 142 |
+
0: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
|
| 143 |
+
1: ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT,
|
| 144 |
+
2: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
|
| 145 |
+
}
|
| 146 |
+
for op_with_quantized_bop_scalar_variant in [
|
| 147 |
+
operator.add,
|
| 148 |
+
torch.add,
|
| 149 |
+
operator.mul,
|
| 150 |
+
torch.mul,
|
| 151 |
+
]:
|
| 152 |
+
bop_patterns = [
|
| 153 |
+
(op_with_quantized_bop_scalar_variant, nn.ReLU),
|
| 154 |
+
(op_with_quantized_bop_scalar_variant, F.relu),
|
| 155 |
+
(op_with_quantized_bop_scalar_variant, torch.relu),
|
| 156 |
+
op_with_quantized_bop_scalar_variant,
|
| 157 |
+
]
|
| 158 |
+
for bop_pattern in bop_patterns:
|
| 159 |
+
binary_op_configs.append(
|
| 160 |
+
BackendPatternConfig(bop_pattern)
|
| 161 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 162 |
+
._set_num_tensor_args_to_observation_type(
|
| 163 |
+
num_tensor_args_to_observation_type_mapping
|
| 164 |
+
)
|
| 165 |
+
)
|
| 166 |
+
# matmul
|
| 167 |
+
binary_op_configs.append(
|
| 168 |
+
BackendPatternConfig(torch.matmul).set_dtype_configs(
|
| 169 |
+
dtype_configs
|
| 170 |
+
) # noqa: E131
|
| 171 |
+
)
|
| 172 |
+
return binary_op_configs
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _get_linear_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 176 |
+
"""
|
| 177 |
+
Return all configs related to linear modules and ops.
|
| 178 |
+
"""
|
| 179 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 180 |
+
linear_configs: List[BackendPatternConfig] = []
|
| 181 |
+
|
| 182 |
+
# (1) Single linear modules/functions
|
| 183 |
+
# -------------------------------------
|
| 184 |
+
# linear module
|
| 185 |
+
linear_configs.append(
|
| 186 |
+
BackendPatternConfig(torch.nn.Linear)
|
| 187 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 188 |
+
.set_dtype_configs(dtype_configs)
|
| 189 |
+
.set_root_module(torch.nn.Linear)
|
| 190 |
+
.set_reference_quantized_module(nnqr.Linear)
|
| 191 |
+
.set_qat_module(nnqat.Linear)
|
| 192 |
+
)
|
| 193 |
+
# linear qat module
|
| 194 |
+
linear_configs.append(
|
| 195 |
+
BackendPatternConfig(nnqat.Linear)
|
| 196 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 197 |
+
.set_dtype_configs(dtype_configs)
|
| 198 |
+
.set_root_module(torch.nn.Linear)
|
| 199 |
+
.set_reference_quantized_module(nnqr.Linear)
|
| 200 |
+
)
|
| 201 |
+
# functional linear
|
| 202 |
+
linear_configs.append(
|
| 203 |
+
BackendPatternConfig(torch.nn.functional.linear)
|
| 204 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 205 |
+
.set_dtype_configs(dtype_configs)
|
| 206 |
+
._set_input_type_to_index({"weight": 1, "bias": 2})
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# (2) Linear + relu
|
| 210 |
+
# -------------------
|
| 211 |
+
# 2.1 linear module + relu fusion config
|
| 212 |
+
# linear relu, linear module + relu module
|
| 213 |
+
linear_configs.append(
|
| 214 |
+
BackendPatternConfig((torch.nn.Linear, torch.nn.ReLU))
|
| 215 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 216 |
+
.set_fuser_method(_sequential_wrapper2(nni.LinearReLU))
|
| 217 |
+
.set_fused_module(nni.LinearReLU)
|
| 218 |
+
)
|
| 219 |
+
# linear relu, linear module + functional relu
|
| 220 |
+
linear_configs.append(
|
| 221 |
+
BackendPatternConfig((torch.nn.Linear, torch.nn.functional.relu))
|
| 222 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 223 |
+
.set_fuser_method(_sequential_wrapper2(nni.LinearReLU))
|
| 224 |
+
.set_fused_module(nni.LinearReLU)
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# 2.2 linear module + relu, fused module configs
|
| 228 |
+
# linear relu, fused module
|
| 229 |
+
linear_configs.append(
|
| 230 |
+
BackendPatternConfig(nni.LinearReLU)
|
| 231 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 232 |
+
.set_dtype_configs(dtype_configs)
|
| 233 |
+
.set_root_module(torch.nn.Linear)
|
| 234 |
+
.set_reference_quantized_module(nnqr.Linear)
|
| 235 |
+
.set_qat_module(nniqat.LinearReLU)
|
| 236 |
+
)
|
| 237 |
+
# linear relu, qat fused module
|
| 238 |
+
linear_configs.append(
|
| 239 |
+
BackendPatternConfig(nniqat.LinearReLU)
|
| 240 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 241 |
+
.set_dtype_configs(dtype_configs)
|
| 242 |
+
.set_root_module(torch.nn.Linear)
|
| 243 |
+
.set_reference_quantized_module(nnqr.Linear)
|
| 244 |
+
)
|
| 245 |
+
# 2.3 functional linear + relu configs
|
| 246 |
+
# linear relu, functional linear + relu module
|
| 247 |
+
linear_configs.append(
|
| 248 |
+
BackendPatternConfig((F.linear, torch.nn.ReLU))
|
| 249 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 250 |
+
.set_dtype_configs(dtype_configs)
|
| 251 |
+
)
|
| 252 |
+
# linear relu, functional linear + functional relu
|
| 253 |
+
linear_configs.append(
|
| 254 |
+
BackendPatternConfig((F.linear, F.relu))
|
| 255 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 256 |
+
.set_dtype_configs(dtype_configs)
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
# (3) Linear + batchnorm
|
| 260 |
+
# ------------------------
|
| 261 |
+
# 3.1 linear bn fusion
|
| 262 |
+
linear_configs.append(
|
| 263 |
+
BackendPatternConfig((nn.Linear, nn.BatchNorm1d))
|
| 264 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 265 |
+
.set_fuser_method(fuse_linear_bn)
|
| 266 |
+
.set_fused_module(nni.LinearBn1d)
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
# 3.2 linear bn fused
|
| 270 |
+
# linear bn, fused module
|
| 271 |
+
linear_configs.append(
|
| 272 |
+
BackendPatternConfig(nni.LinearBn1d)
|
| 273 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 274 |
+
.set_dtype_configs(dtype_configs)
|
| 275 |
+
.set_root_module(torch.nn.Linear)
|
| 276 |
+
.set_reference_quantized_module(nnqr.Linear)
|
| 277 |
+
.set_qat_module(nniqat.LinearBn1d)
|
| 278 |
+
)
|
| 279 |
+
# linear bn, qat fused module
|
| 280 |
+
linear_configs.append(
|
| 281 |
+
BackendPatternConfig(nniqat.LinearBn1d)
|
| 282 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 283 |
+
.set_dtype_configs(dtype_configs)
|
| 284 |
+
.set_root_module(torch.nn.Linear)
|
| 285 |
+
.set_reference_quantized_module(nnqr.Linear)
|
| 286 |
+
)
|
| 287 |
+
return linear_configs
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _get_conv_configs(dtype_configs):
|
| 291 |
+
"""
|
| 292 |
+
Return all configs related to conv modules and ops.
|
| 293 |
+
"""
|
| 294 |
+
conv_configs = []
|
| 295 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 296 |
+
for convs in [_Conv1dMetadata, _Conv2dMetadata, _Conv3dMetadata]:
|
| 297 |
+
# (1) Single conv modules/functions
|
| 298 |
+
# -----------------------------------
|
| 299 |
+
# conv module
|
| 300 |
+
conv_configs.append(
|
| 301 |
+
BackendPatternConfig(convs.root)
|
| 302 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 303 |
+
.set_dtype_configs(dtype_configs)
|
| 304 |
+
.set_root_module(convs.root)
|
| 305 |
+
.set_reference_quantized_module(convs.reference)
|
| 306 |
+
.set_qat_module(convs.qat)
|
| 307 |
+
)
|
| 308 |
+
# conv qat module
|
| 309 |
+
conv_configs.append(
|
| 310 |
+
BackendPatternConfig(convs.qat)
|
| 311 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 312 |
+
.set_dtype_configs(dtype_configs)
|
| 313 |
+
.set_root_module(convs.root)
|
| 314 |
+
.set_reference_quantized_module(convs.reference)
|
| 315 |
+
)
|
| 316 |
+
# functional conv
|
| 317 |
+
conv_configs.append(
|
| 318 |
+
BackendPatternConfig(convs.func)
|
| 319 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 320 |
+
.set_dtype_configs(dtype_configs)
|
| 321 |
+
._set_input_type_to_index({"weight": 1, "bias": 2})
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
# (2) Conv + relu
|
| 325 |
+
# -----------------
|
| 326 |
+
# 2.1 conv module + relu fusion configs
|
| 327 |
+
# conv relu fusion, conv module + relu module
|
| 328 |
+
conv_configs.append(
|
| 329 |
+
BackendPatternConfig((convs.root, torch.nn.ReLU))
|
| 330 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 331 |
+
.set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu))
|
| 332 |
+
.set_fused_module(convs.fused_conv_relu)
|
| 333 |
+
)
|
| 334 |
+
# conv relu fusion, conv module + functional relu
|
| 335 |
+
conv_configs.append(
|
| 336 |
+
BackendPatternConfig((convs.root, F.relu))
|
| 337 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 338 |
+
.set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu))
|
| 339 |
+
.set_fused_module(convs.fused_conv_relu)
|
| 340 |
+
)
|
| 341 |
+
# 2.2 conv module + relu fused module configs
|
| 342 |
+
# conv relu, fused module
|
| 343 |
+
conv_configs.append(
|
| 344 |
+
BackendPatternConfig(convs.fused_conv_relu)
|
| 345 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 346 |
+
.set_dtype_configs(dtype_configs)
|
| 347 |
+
.set_root_module(convs.root)
|
| 348 |
+
.set_reference_quantized_module(convs.reference)
|
| 349 |
+
.set_qat_module(convs.relu_qat)
|
| 350 |
+
)
|
| 351 |
+
# conv relu, qat fused module
|
| 352 |
+
conv_configs.append(
|
| 353 |
+
BackendPatternConfig(convs.relu_qat)
|
| 354 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 355 |
+
.set_dtype_configs(dtype_configs)
|
| 356 |
+
.set_root_module(convs.root)
|
| 357 |
+
.set_reference_quantized_module(convs.reference)
|
| 358 |
+
)
|
| 359 |
+
# 2.3 functional conv + relu configs
|
| 360 |
+
# conv relu, functional conv + relu module
|
| 361 |
+
conv_configs.append(
|
| 362 |
+
BackendPatternConfig((convs.func, torch.nn.ReLU))
|
| 363 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 364 |
+
.set_dtype_configs(dtype_configs)
|
| 365 |
+
)
|
| 366 |
+
# conv relu, functional conv + functional relu
|
| 367 |
+
conv_configs.append(
|
| 368 |
+
BackendPatternConfig((convs.func, F.relu))
|
| 369 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 370 |
+
.set_dtype_configs(dtype_configs)
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
# fused conv relu
|
| 374 |
+
conv_configs.append(
|
| 375 |
+
BackendPatternConfig(convs.fused_conv_relu)
|
| 376 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 377 |
+
.set_qat_module(convs.relu_qat)
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
conv_configs.append(
|
| 381 |
+
BackendPatternConfig(convs.relu_qat)
|
| 382 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 383 |
+
.set_root_module(convs.root)
|
| 384 |
+
.set_reference_quantized_module(convs.reference)
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
# (3) Conv + batchnorm (+ relu)
|
| 388 |
+
# -------------------------------
|
| 389 |
+
# 3.1 conv bn fusion configs
|
| 390 |
+
# conv + bn fusion
|
| 391 |
+
conv_configs.append(
|
| 392 |
+
BackendPatternConfig((convs.root, convs.bn))
|
| 393 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 394 |
+
.set_fuser_method(fuse_conv_bn)
|
| 395 |
+
.set_fused_module(convs.fused_conv_bn)
|
| 396 |
+
)
|
| 397 |
+
# conv + bn + relu module fusion
|
| 398 |
+
conv_configs.append(
|
| 399 |
+
BackendPatternConfig((convs.root, convs.bn, nn.ReLU))
|
| 400 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 401 |
+
.set_fuser_method(fuse_conv_bn_relu)
|
| 402 |
+
.set_fused_module(convs.fused_conv_bn_relu)
|
| 403 |
+
)
|
| 404 |
+
# conv + bn + relu functional fusion
|
| 405 |
+
conv_configs.append(
|
| 406 |
+
BackendPatternConfig((convs.root, convs.bn, F.relu))
|
| 407 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 408 |
+
.set_root_module(convs.root)
|
| 409 |
+
.set_fuser_method(fuse_conv_bn_relu)
|
| 410 |
+
.set_fused_module(convs.fused_conv_bn_relu)
|
| 411 |
+
)
|
| 412 |
+
# TODO: we can add fusion for torch.relu as well
|
| 413 |
+
|
| 414 |
+
# 3.2 conv + bn (+ relu) fused module configs
|
| 415 |
+
# fused conv bn
|
| 416 |
+
conv_configs.append(
|
| 417 |
+
BackendPatternConfig(convs.fused_conv_bn)
|
| 418 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 419 |
+
.set_qat_module(convs.bn_qat)
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
# fused conv bn relu
|
| 423 |
+
conv_configs.append(
|
| 424 |
+
BackendPatternConfig(convs.fused_conv_bn_relu)
|
| 425 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 426 |
+
.set_qat_module(convs.bn_relu_qat)
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
# conv bn, qat fused module
|
| 430 |
+
conv_configs.append(
|
| 431 |
+
BackendPatternConfig(convs.bn_qat)
|
| 432 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 433 |
+
.set_dtype_configs(dtype_configs)
|
| 434 |
+
.set_root_module(convs.root)
|
| 435 |
+
.set_reference_quantized_module(convs.reference)
|
| 436 |
+
)
|
| 437 |
+
# conv bn relu, qat fused module
|
| 438 |
+
conv_configs.append(
|
| 439 |
+
BackendPatternConfig(convs.bn_relu_qat)
|
| 440 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 441 |
+
.set_dtype_configs(dtype_configs)
|
| 442 |
+
.set_root_module(convs.root)
|
| 443 |
+
.set_reference_quantized_module(convs.reference)
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
# (4) conv transpose and its fusion
|
| 447 |
+
# 4.1 conv transpose config
|
| 448 |
+
conv_configs.append(
|
| 449 |
+
BackendPatternConfig(convs.transpose)
|
| 450 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 451 |
+
.set_root_module(convs.transpose)
|
| 452 |
+
.set_reference_quantized_module(convs.transpose_reference)
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
# 4.2 conv transpose + bn fusion
|
| 456 |
+
conv_configs.append(
|
| 457 |
+
BackendPatternConfig((convs.transpose, convs.bn))
|
| 458 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 459 |
+
.set_fuser_method(fuse_convtranspose_bn)
|
| 460 |
+
.set_root_module(convs.transpose)
|
| 461 |
+
.set_reference_quantized_module(convs.transpose_reference)
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
# 4.3 functional conv transpose
|
| 465 |
+
conv_configs.append(
|
| 466 |
+
BackendPatternConfig(convs.func_transpose)
|
| 467 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 468 |
+
._set_input_type_to_index({"weight": 1, "bias": 2})
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
return conv_configs
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def _get_cat_config(dtype_configs: List[DTypeConfig]) -> BackendPatternConfig:
|
| 475 |
+
return (
|
| 476 |
+
BackendPatternConfig(torch.cat)
|
| 477 |
+
.set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT)
|
| 478 |
+
.set_dtype_configs(dtype_configs)
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def _get_ln_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 483 |
+
ln_configs = []
|
| 484 |
+
ln_configs.append(
|
| 485 |
+
BackendPatternConfig(torch.nn.LayerNorm)
|
| 486 |
+
.set_observation_type(
|
| 487 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 488 |
+
) # noqa: E131
|
| 489 |
+
.set_dtype_configs(dtype_configs)
|
| 490 |
+
)
|
| 491 |
+
ln_configs.append(
|
| 492 |
+
BackendPatternConfig(torch.nn.functional.layer_norm)
|
| 493 |
+
.set_observation_type(
|
| 494 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 495 |
+
) # noqa: E131
|
| 496 |
+
.set_dtype_configs(dtype_configs)
|
| 497 |
+
._set_input_type_to_index({"weight": 2, "bias": 3})
|
| 498 |
+
)
|
| 499 |
+
return ln_configs
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def _get_default_op_configs(
|
| 503 |
+
dtype_configs: List[DTypeConfig],
|
| 504 |
+
) -> List[BackendPatternConfig]:
|
| 505 |
+
configs = []
|
| 506 |
+
default_ops = [
|
| 507 |
+
torch.nn.ELU,
|
| 508 |
+
torch.nn.LeakyReLU,
|
| 509 |
+
torch.nn.Hardswish,
|
| 510 |
+
torch.nn.InstanceNorm1d,
|
| 511 |
+
torch.nn.InstanceNorm2d,
|
| 512 |
+
torch.nn.InstanceNorm3d,
|
| 513 |
+
torch.nn.Dropout,
|
| 514 |
+
torch.nn.PReLU,
|
| 515 |
+
torch.nn.functional.elu,
|
| 516 |
+
torch.nn.functional.hardswish,
|
| 517 |
+
torch.nn.functional.leaky_relu,
|
| 518 |
+
torch.nn.functional.dropout,
|
| 519 |
+
]
|
| 520 |
+
for op in default_ops:
|
| 521 |
+
configs.append(
|
| 522 |
+
BackendPatternConfig(op)
|
| 523 |
+
.set_observation_type(
|
| 524 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 525 |
+
) # noqa: E131
|
| 526 |
+
.set_dtype_configs(dtype_configs)
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
configs.append(
|
| 530 |
+
BackendPatternConfig(torch.nn.functional.group_norm)
|
| 531 |
+
.set_observation_type(
|
| 532 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 533 |
+
) # noqa: E131
|
| 534 |
+
.set_dtype_configs(dtype_configs)
|
| 535 |
+
._set_input_type_to_index({"weight": 2, "bias": 3})
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
configs.append(
|
| 539 |
+
BackendPatternConfig(torch.nn.functional.instance_norm)
|
| 540 |
+
.set_observation_type(
|
| 541 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 542 |
+
) # noqa: E131
|
| 543 |
+
.set_dtype_configs(dtype_configs)
|
| 544 |
+
._set_input_type_to_index({"weight": 3, "bias": 4})
|
| 545 |
+
)
|
| 546 |
+
return configs
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def _add_fixed_qparams_to_dtype_configs(
|
| 550 |
+
dtype_configs: List[DTypeConfig],
|
| 551 |
+
constraints: DTypeWithConstraints,
|
| 552 |
+
) -> List[DTypeConfig]:
|
| 553 |
+
"""
|
| 554 |
+
Return a copy of the list of DTypeConfigs where activations are subject to the specified
|
| 555 |
+
constraints required for fixed qparams ops.
|
| 556 |
+
|
| 557 |
+
If the data type doesn't match the one in the constraints, simply leave the corresponding
|
| 558 |
+
DTypeConfig unchanged.
|
| 559 |
+
|
| 560 |
+
If `scale_min_lower_bound` or `scale_max_upper_bound` is specified in the activations,
|
| 561 |
+
throw an exception since these settings are incompatible with fixed qparams ops.
|
| 562 |
+
"""
|
| 563 |
+
new_dtype_configs = []
|
| 564 |
+
for dtype_config in dtype_configs:
|
| 565 |
+
dc = copy.deepcopy(dtype_config)
|
| 566 |
+
for orig_constraints in [
|
| 567 |
+
dc.input_dtype_with_constraints,
|
| 568 |
+
dc.output_dtype_with_constraints,
|
| 569 |
+
]:
|
| 570 |
+
if orig_constraints.dtype != constraints.dtype:
|
| 571 |
+
continue
|
| 572 |
+
if orig_constraints.scale_min_lower_bound is not None:
|
| 573 |
+
raise ValueError(
|
| 574 |
+
f"scale_min_lower_bound is invalid for fixed qparams ops: {dtype_config}"
|
| 575 |
+
)
|
| 576 |
+
if orig_constraints.scale_max_upper_bound is not None:
|
| 577 |
+
raise ValueError(
|
| 578 |
+
f"scale_max_upper_bound is invalid for fixed qparams ops: {dtype_config}"
|
| 579 |
+
)
|
| 580 |
+
orig_constraints.quant_min_lower_bound = constraints.quant_min_lower_bound
|
| 581 |
+
orig_constraints.quant_max_upper_bound = constraints.quant_max_upper_bound
|
| 582 |
+
orig_constraints.scale_exact_match = constraints.scale_exact_match
|
| 583 |
+
orig_constraints.zero_point_exact_match = constraints.zero_point_exact_match
|
| 584 |
+
new_dtype_configs.append(dc)
|
| 585 |
+
return new_dtype_configs
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
def _get_fixed_qparams_op_configs(
|
| 589 |
+
dtype_configs: List[DTypeConfig],
|
| 590 |
+
) -> List[BackendPatternConfig]:
|
| 591 |
+
fixed_qparams_op_configs = []
|
| 592 |
+
for fixed_qparam_op, constraints in _FIXED_QPARAMS_OP_TO_CONSTRAINTS.items():
|
| 593 |
+
new_dtype_configs = _add_fixed_qparams_to_dtype_configs(
|
| 594 |
+
dtype_configs, constraints
|
| 595 |
+
)
|
| 596 |
+
fixed_qparams_op_configs.append(
|
| 597 |
+
BackendPatternConfig(fixed_qparam_op)
|
| 598 |
+
.set_observation_type(
|
| 599 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 600 |
+
) # noqa: E131
|
| 601 |
+
.set_dtype_configs(new_dtype_configs)
|
| 602 |
+
)
|
| 603 |
+
return fixed_qparams_op_configs
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def _get_share_qparams_op_configs(dtype_configs):
|
| 607 |
+
"""Get the operator config for the operators that works for both float and quantized input
|
| 608 |
+
if input is quantized, the output Tensor shares the same quantization parameter
|
| 609 |
+
with input.
|
| 610 |
+
Example operator: avgpool2d, reshape, transpose, maxpool2d
|
| 611 |
+
Example observed operator:
|
| 612 |
+
observer_0 - avgpool2d - observer_0 (same observer instance as input)
|
| 613 |
+
"""
|
| 614 |
+
|
| 615 |
+
def _get_share_qprams_op_backend_config(op):
|
| 616 |
+
return (
|
| 617 |
+
BackendPatternConfig(op)
|
| 618 |
+
.set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT)
|
| 619 |
+
.set_dtype_configs(dtype_configs)
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
share_qparams_ops = [
|
| 623 |
+
torch.nn.AdaptiveAvgPool1d,
|
| 624 |
+
torch.nn.AdaptiveAvgPool2d,
|
| 625 |
+
torch.nn.AdaptiveAvgPool3d,
|
| 626 |
+
torch.nn.AvgPool1d,
|
| 627 |
+
torch.nn.AvgPool2d,
|
| 628 |
+
torch.nn.AvgPool3d,
|
| 629 |
+
torch.nn.Hardtanh,
|
| 630 |
+
torch.nn.Identity,
|
| 631 |
+
torch.nn.MaxPool1d,
|
| 632 |
+
torch.nn.MaxPool2d,
|
| 633 |
+
torch.nn.MaxPool3d,
|
| 634 |
+
torch.nn.PixelShuffle,
|
| 635 |
+
torch.nn.PixelUnshuffle,
|
| 636 |
+
torch.nn.ReLU,
|
| 637 |
+
torch.nn.ReLU6,
|
| 638 |
+
torch.adaptive_avg_pool1d,
|
| 639 |
+
torch.nn.functional.adaptive_avg_pool2d,
|
| 640 |
+
torch.nn.functional.adaptive_avg_pool3d,
|
| 641 |
+
torch.nn.functional.hardtanh,
|
| 642 |
+
torch.nn.functional.hardtanh_,
|
| 643 |
+
torch.nn.functional.interpolate,
|
| 644 |
+
torch.nn.functional.max_pool1d,
|
| 645 |
+
torch.nn.functional.max_pool2d,
|
| 646 |
+
torch.nn.functional.max_pool3d,
|
| 647 |
+
torch.nn.functional.pixel_shuffle,
|
| 648 |
+
torch.nn.functional.pixel_unshuffle,
|
| 649 |
+
torch.nn.functional.relu,
|
| 650 |
+
torch.nn.functional.relu6,
|
| 651 |
+
torch.avg_pool1d,
|
| 652 |
+
torch._C._nn.avg_pool2d,
|
| 653 |
+
torch._C._nn.avg_pool3d,
|
| 654 |
+
torch.clamp,
|
| 655 |
+
torch.flatten,
|
| 656 |
+
torch.mean,
|
| 657 |
+
torch.narrow,
|
| 658 |
+
torch.repeat_interleave,
|
| 659 |
+
torch.transpose,
|
| 660 |
+
torch.squeeze,
|
| 661 |
+
torch.stack,
|
| 662 |
+
torch.unsqueeze,
|
| 663 |
+
operator.floordiv,
|
| 664 |
+
"contiguous",
|
| 665 |
+
"clamp",
|
| 666 |
+
"detach",
|
| 667 |
+
"detach_",
|
| 668 |
+
"mean",
|
| 669 |
+
"permute",
|
| 670 |
+
"repeat",
|
| 671 |
+
"repeat_interleave",
|
| 672 |
+
"reshape",
|
| 673 |
+
"resize_",
|
| 674 |
+
"relu",
|
| 675 |
+
"relu_",
|
| 676 |
+
"squeeze",
|
| 677 |
+
"squeeze_",
|
| 678 |
+
"transpose",
|
| 679 |
+
"unsqueeze",
|
| 680 |
+
"unsqueeze_",
|
| 681 |
+
"view",
|
| 682 |
+
]
|
| 683 |
+
return [_get_share_qprams_op_backend_config(op) for op in share_qparams_ops]
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def _get_bn_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 687 |
+
"""Get configs related to batchnorm."""
|
| 688 |
+
bn_configs = []
|
| 689 |
+
bn_to_fused_bn = {
|
| 690 |
+
torch.nn.BatchNorm2d: nni.BNReLU2d,
|
| 691 |
+
torch.nn.BatchNorm3d: nni.BNReLU3d,
|
| 692 |
+
}
|
| 693 |
+
for bn in bn_to_fused_bn.keys():
|
| 694 |
+
fused_bn = bn_to_fused_bn[bn]
|
| 695 |
+
# bn module + relu module fusion config
|
| 696 |
+
bn_configs.append(
|
| 697 |
+
BackendPatternConfig((bn, nn.ReLU))
|
| 698 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 699 |
+
.set_fuser_method(_sequential_wrapper2(fused_bn))
|
| 700 |
+
.set_fused_module(fused_bn)
|
| 701 |
+
)
|
| 702 |
+
# bn module + F.relu fusion config
|
| 703 |
+
bn_configs.append(
|
| 704 |
+
BackendPatternConfig((bn, F.relu))
|
| 705 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 706 |
+
.set_fuser_method(_sequential_wrapper2(fused_bn))
|
| 707 |
+
.set_fused_module(fused_bn)
|
| 708 |
+
)
|
| 709 |
+
bn_configs.append(
|
| 710 |
+
BackendPatternConfig(bn)
|
| 711 |
+
.set_observation_type(
|
| 712 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 713 |
+
) # noqa: E131
|
| 714 |
+
.set_dtype_configs(dtype_configs)
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
# fused bn configs
|
| 718 |
+
for fused_bn in bn_to_fused_bn.values():
|
| 719 |
+
bn_configs.append(
|
| 720 |
+
BackendPatternConfig(fused_bn)
|
| 721 |
+
.set_observation_type(
|
| 722 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 723 |
+
) # noqa: E131
|
| 724 |
+
.set_dtype_configs(dtype_configs)
|
| 725 |
+
)
|
| 726 |
+
return bn_configs
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def _get_rnn_op_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 730 |
+
rnn_op_configs = []
|
| 731 |
+
for rnn_op, ref_rnn_op in [
|
| 732 |
+
(nn.GRUCell, nnqr.GRUCell),
|
| 733 |
+
(nn.LSTMCell, nnqr.LSTMCell),
|
| 734 |
+
(nn.RNNCell, nnqr.RNNCell),
|
| 735 |
+
(nn.LSTM, nnqr.LSTM),
|
| 736 |
+
(nn.GRU, nnqr.GRU),
|
| 737 |
+
]:
|
| 738 |
+
rnn_op_configs.append(
|
| 739 |
+
BackendPatternConfig(rnn_op)
|
| 740 |
+
.set_observation_type(
|
| 741 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 742 |
+
) # noqa: E131
|
| 743 |
+
.set_dtype_configs(dtype_configs)
|
| 744 |
+
.set_root_module(rnn_op)
|
| 745 |
+
.set_reference_quantized_module(ref_rnn_op)
|
| 746 |
+
)
|
| 747 |
+
return rnn_op_configs
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
def _get_embedding_op_configs(
|
| 751 |
+
dtype_configs: List[DTypeConfig],
|
| 752 |
+
) -> List[BackendPatternConfig]:
|
| 753 |
+
embedding_op_configs = []
|
| 754 |
+
for embedding_op, qat_embedding_op, ref_embedding_op in [
|
| 755 |
+
(nn.Embedding, nnqat.Embedding, nnqr.Embedding),
|
| 756 |
+
(nn.EmbeddingBag, nnqat.EmbeddingBag, nnqr.EmbeddingBag),
|
| 757 |
+
]:
|
| 758 |
+
embedding_op_configs.append(
|
| 759 |
+
BackendPatternConfig(embedding_op)
|
| 760 |
+
.set_observation_type(
|
| 761 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 762 |
+
) # noqa: E131
|
| 763 |
+
.set_dtype_configs(dtype_configs)
|
| 764 |
+
.set_qat_module(qat_embedding_op)
|
| 765 |
+
.set_root_module(embedding_op)
|
| 766 |
+
.set_reference_quantized_module(ref_embedding_op)
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
# config for qat op
|
| 770 |
+
embedding_op_configs.append(
|
| 771 |
+
BackendPatternConfig(qat_embedding_op)
|
| 772 |
+
.set_observation_type(
|
| 773 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 774 |
+
) # noqa: E131
|
| 775 |
+
.set_dtype_configs(dtype_configs)
|
| 776 |
+
.set_root_module(embedding_op)
|
| 777 |
+
.set_reference_quantized_module(ref_embedding_op)
|
| 778 |
+
)
|
| 779 |
+
return embedding_op_configs
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
def _get_tensor_info_op_configs(dtype_configs):
|
| 783 |
+
"""
|
| 784 |
+
These ops work on tensors of different dtypes but return non-tensors
|
| 785 |
+
containing information about the input tensor.
|
| 786 |
+
"""
|
| 787 |
+
|
| 788 |
+
def _get_config(op):
|
| 789 |
+
return (
|
| 790 |
+
BackendPatternConfig(op)
|
| 791 |
+
.set_observation_type(ObservationType.INPUT_OUTPUT_NOT_OBSERVED)
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import operator
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch.ao.quantization.backend_config import (
|
| 6 |
+
BackendConfig,
|
| 7 |
+
BackendPatternConfig,
|
| 8 |
+
DTypeConfig,
|
| 9 |
+
ObservationType,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
weighted_op_quint8_dtype_config = DTypeConfig(
|
| 14 |
+
input_dtype=torch.quint8,
|
| 15 |
+
output_dtype=torch.quint8,
|
| 16 |
+
weight_dtype=torch.qint8,
|
| 17 |
+
bias_dtype=torch.float,
|
| 18 |
+
)
|
| 19 |
+
from typing import List
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_linear_configs():
|
| 23 |
+
linear_configs = []
|
| 24 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 25 |
+
dtype_configs = [weighted_op_quint8_dtype_config]
|
| 26 |
+
|
| 27 |
+
# TODO: need to fix the way we insert observers for this pattern
|
| 28 |
+
# should be solved in the new fusion API
|
| 29 |
+
# reason that this doesn't work: the pattern is a bit complicated and we don't
|
| 30 |
+
# have a way to specify which input of the pattern we would like to observe
|
| 31 |
+
# pattern:
|
| 32 |
+
# bias input weight
|
| 33 |
+
# \ | /
|
| 34 |
+
# \ | t
|
| 35 |
+
# \ | /
|
| 36 |
+
# addmm
|
| 37 |
+
# we want to observe "weight" as weight, but there is not way to convey this
|
| 38 |
+
# information with current pattern language
|
| 39 |
+
#
|
| 40 |
+
# right now:
|
| 41 |
+
# original:
|
| 42 |
+
# weight - t \
|
| 43 |
+
# input - addmm
|
| 44 |
+
# observed (no hack):
|
| 45 |
+
# weight - t - observer \
|
| 46 |
+
# input - observer - addmm
|
| 47 |
+
# target:
|
| 48 |
+
# weight - observer - t \
|
| 49 |
+
# input - observer - addmm
|
| 50 |
+
|
| 51 |
+
# def root_node_getter(node_pattern):
|
| 52 |
+
# addmm, bias, act, weight = node_pattern
|
| 53 |
+
# return addmm
|
| 54 |
+
|
| 55 |
+
# linear_configs.append(
|
| 56 |
+
# BackendPatternConfig((torch.ops.aten.addmm.default, MatchAllNode, MatchAllNode, torch.ops.aten.t.default))
|
| 57 |
+
# .set_observation_type(observation_type) # noqa: E131
|
| 58 |
+
# .set_dtype_configs(dtype_configs)
|
| 59 |
+
# ._set_root_node_getter(root_node_getter))
|
| 60 |
+
|
| 61 |
+
linear_configs.append(
|
| 62 |
+
BackendPatternConfig(torch.ops.aten.addmm.default)
|
| 63 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 64 |
+
.set_dtype_configs(dtype_configs)
|
| 65 |
+
._set_input_type_to_index({"weight": 2, "bias": 0})
|
| 66 |
+
)
|
| 67 |
+
# linear is decomposed to `t - mm` if bias is not present
|
| 68 |
+
linear_configs.append(
|
| 69 |
+
BackendPatternConfig(torch.ops.aten.mm.default)
|
| 70 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 71 |
+
.set_dtype_configs(dtype_configs)
|
| 72 |
+
._set_input_type_to_index({"weight": 1})
|
| 73 |
+
)
|
| 74 |
+
return linear_configs
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def get_conv_configs():
|
| 78 |
+
conv_configs = []
|
| 79 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 80 |
+
dtype_configs = [weighted_op_quint8_dtype_config]
|
| 81 |
+
conv_configs.append(
|
| 82 |
+
BackendPatternConfig(torch.ops.aten.convolution.default)
|
| 83 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 84 |
+
.set_dtype_configs(dtype_configs)
|
| 85 |
+
._set_input_type_to_index({"weight": 1, "bias": 2})
|
| 86 |
+
)
|
| 87 |
+
conv_configs.append(
|
| 88 |
+
BackendPatternConfig(
|
| 89 |
+
(torch.ops.aten.convolution.default, torch.ops.aten.relu.default)
|
| 90 |
+
)
|
| 91 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 92 |
+
.set_dtype_configs(dtype_configs)
|
| 93 |
+
._set_input_type_to_index({"weight": 1, "bias": 2})
|
| 94 |
+
)
|
| 95 |
+
# TODO: remove when functionalization is supported in PT2 mode
|
| 96 |
+
conv_configs.append(
|
| 97 |
+
BackendPatternConfig(
|
| 98 |
+
(torch.ops.aten.convolution.default, torch.ops.aten.relu_.default)
|
| 99 |
+
)
|
| 100 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 101 |
+
.set_dtype_configs(dtype_configs)
|
| 102 |
+
._set_input_type_to_index({"weight": 1, "bias": 2})
|
| 103 |
+
)
|
| 104 |
+
return conv_configs
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def get_pooling_configs():
|
| 108 |
+
backend_pattern_configs = []
|
| 109 |
+
observation_type = ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT
|
| 110 |
+
dtype_configs = [weighted_op_quint8_dtype_config]
|
| 111 |
+
|
| 112 |
+
def root_node_getter(node_pattern):
|
| 113 |
+
getitem, maxpool, index = node_pattern
|
| 114 |
+
return maxpool
|
| 115 |
+
|
| 116 |
+
backend_pattern_configs.append(
|
| 117 |
+
BackendPatternConfig()
|
| 118 |
+
._set_pattern_complex_format(
|
| 119 |
+
(operator.getitem, torch.ops.aten.max_pool2d_with_indices.default, 0)
|
| 120 |
+
)
|
| 121 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 122 |
+
.set_dtype_configs(dtype_configs)
|
| 123 |
+
._set_root_node_getter(root_node_getter)
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
return backend_pattern_configs
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def get_relu_configs():
|
| 130 |
+
backend_pattern_configs = []
|
| 131 |
+
observation_type = ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT
|
| 132 |
+
dtype_configs = [weighted_op_quint8_dtype_config]
|
| 133 |
+
backend_pattern_configs.append(
|
| 134 |
+
BackendPatternConfig(torch.ops.aten.relu.default)
|
| 135 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 136 |
+
.set_dtype_configs(dtype_configs)
|
| 137 |
+
)
|
| 138 |
+
return backend_pattern_configs
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def get_binary_op_configs():
|
| 142 |
+
binary_op_configs: List[BackendPatternConfig] = []
|
| 143 |
+
dtype_configs = [weighted_op_quint8_dtype_config]
|
| 144 |
+
num_tensor_args_to_observation_type_mapping = {
|
| 145 |
+
# TODO: this is not used right now since we have extra check in prepare
|
| 146 |
+
# will need to change this to NO_OBSERVER later after we implemented
|
| 147 |
+
# Tensor dtype inference properly
|
| 148 |
+
0: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
|
| 149 |
+
1: ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT,
|
| 150 |
+
2: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
|
| 151 |
+
}
|
| 152 |
+
for op_with_quantized_bop_scalar_variant in [
|
| 153 |
+
torch.ops.aten.add.Tensor,
|
| 154 |
+
torch.ops.aten.add_.Tensor,
|
| 155 |
+
]:
|
| 156 |
+
bop_patterns = [
|
| 157 |
+
(op_with_quantized_bop_scalar_variant, torch.ops.aten.relu.default),
|
| 158 |
+
op_with_quantized_bop_scalar_variant,
|
| 159 |
+
# TODO: remove when functionalization is supported in pt2_mode
|
| 160 |
+
(op_with_quantized_bop_scalar_variant, torch.ops.aten.relu_.default),
|
| 161 |
+
]
|
| 162 |
+
for bop_pattern in bop_patterns:
|
| 163 |
+
binary_op_configs.append(
|
| 164 |
+
BackendPatternConfig(bop_pattern)
|
| 165 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 166 |
+
._set_num_tensor_args_to_observation_type(
|
| 167 |
+
num_tensor_args_to_observation_type_mapping
|
| 168 |
+
)
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
return binary_op_configs
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def get_qnnpack_pt2e_backend_config():
|
| 175 |
+
return (
|
| 176 |
+
BackendConfig("qnnpack_pytorch_2.0_export")
|
| 177 |
+
.set_backend_pattern_configs(get_linear_configs())
|
| 178 |
+
.set_backend_pattern_configs(get_binary_op_configs())
|
| 179 |
+
.set_backend_pattern_configs(get_conv_configs())
|
| 180 |
+
.set_backend_pattern_configs(get_pooling_configs())
|
| 181 |
+
.set_backend_pattern_configs(get_relu_configs())
|
| 182 |
+
)
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/backend_config.py
ADDED
|
@@ -0,0 +1,749 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from typing import Any, Callable, Dict, List, Optional, Type, TYPE_CHECKING, Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from torch.ao.quantization.utils import Pattern
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
"BackendConfig",
|
| 17 |
+
"BackendPatternConfig",
|
| 18 |
+
"DTypeConfig",
|
| 19 |
+
"DTypeWithConstraints",
|
| 20 |
+
"ObservationType",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# DTypeConfig dict keys
|
| 25 |
+
INPUT_DTYPE_DICT_KEY = "input_dtype"
|
| 26 |
+
OUTPUT_DTYPE_DICT_KEY = "output_dtype"
|
| 27 |
+
WEIGHT_DTYPE_DICT_KEY = "weight_dtype"
|
| 28 |
+
BIAS_DTYPE_DICT_KEY = "bias_dtype"
|
| 29 |
+
IS_DYNAMIC_DICT_KEY = "is_dynamic"
|
| 30 |
+
|
| 31 |
+
# BackendConfig dict keys
|
| 32 |
+
NAME_DICT_KEY = "name"
|
| 33 |
+
CONFIGS_DICT_KEY = "configs"
|
| 34 |
+
|
| 35 |
+
# BackendPatternConfig dict keys
|
| 36 |
+
PATTERN_DICT_KEY = "pattern"
|
| 37 |
+
PATTERN_COMPLEX_FORMAT_DICT_KEY = "pattern_complex_format"
|
| 38 |
+
OBSERVATION_TYPE_DICT_KEY = "observation_type"
|
| 39 |
+
DTYPE_CONFIGS_DICT_KEY = "dtype_configs"
|
| 40 |
+
ROOT_MODULE_DICT_KEY = "root_module"
|
| 41 |
+
QAT_MODULE_DICT_KEY = "qat_module"
|
| 42 |
+
REFERENCE_QUANTIZED_MODULE_DICT_KEY = "reference_quantized_module_for_root"
|
| 43 |
+
FUSED_MODULE_DICT_KEY = "fused_module"
|
| 44 |
+
FUSER_METHOD_DICT_KEY = "fuser_method"
|
| 45 |
+
ROOT_NODE_GETTER_DICT_KEY = "root_node_getter"
|
| 46 |
+
EXTRA_INPUTS_GETTER_DICT_KEY = "extra_inputs_getter"
|
| 47 |
+
NUM_TENSOR_ARGS_TO_OBSERVATION_TYPE_DICT_KEY = "num_tensor_args_to_observation_type"
|
| 48 |
+
INPUT_TYPE_TO_INDEX_DICT_KEY = "input_type_to_index"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# TODO: maybe rename this to something that's not related to observer
|
| 52 |
+
# e.g. QParamsType
|
| 53 |
+
class ObservationType(Enum):
|
| 54 |
+
"""An enum that represents different ways of how an operator/operator pattern
|
| 55 |
+
should be observed
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT = 0
|
| 59 |
+
"""this means input and output are observed with different observers, based
|
| 60 |
+
on qconfig.activation
|
| 61 |
+
example: conv, linear, softmax
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
OUTPUT_SHARE_OBSERVER_WITH_INPUT = 1
|
| 65 |
+
"""this means the output will use the same observer instance as input, based
|
| 66 |
+
on qconfig.activation
|
| 67 |
+
example: torch.cat, maxpool
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
INPUT_OUTPUT_NOT_OBSERVED = 2
|
| 71 |
+
"""this means the input and output are never observed
|
| 72 |
+
example: x.shape, x.size
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclass
|
| 77 |
+
class DTypeWithConstraints:
|
| 78 |
+
"""
|
| 79 |
+
Config for specifying additional constraints for a given dtype, such as quantization
|
| 80 |
+
value ranges, scale value ranges, and fixed quantization params, to be used in
|
| 81 |
+
:class:`~torch.ao.quantization.backend_config.DTypeConfig`.
|
| 82 |
+
|
| 83 |
+
The constraints currently supported are:
|
| 84 |
+
|
| 85 |
+
* `quant_min_lower_bound` and `quant_max_upper_bound`: Lower and upper
|
| 86 |
+
bounds for the minimum and maximum quantized values respectively. If
|
| 87 |
+
the QConfig's `quant_min` and `quant_max` fall outside this range,
|
| 88 |
+
then the QConfig will be ignored.
|
| 89 |
+
|
| 90 |
+
* `scale_min_lower_bound` and `scale_max_upper_bound`: Lower and upper
|
| 91 |
+
bounds for the minimum and maximum scale values respectively. If the
|
| 92 |
+
QConfig's minimum scale value (currently exposed as `eps`) falls below
|
| 93 |
+
the lower bound, then the QConfig will be ignored. Note that the upper
|
| 94 |
+
bound is currently not enforced.
|
| 95 |
+
|
| 96 |
+
* `scale_exact_match` and `zero_point_exact_match`: Exact match requirements
|
| 97 |
+
for scale and zero point, to be used for operators with fixed quantization
|
| 98 |
+
parameters such as sigmoid and tanh. If the observer specified in the QConfig
|
| 99 |
+
is neither `FixedQParamsObserver` nor `FixedQParamsFakeQuantize`, or if
|
| 100 |
+
the quantization parameters don't match, then the QConfig will be ignored.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
dtype: Optional[torch.dtype] = None
|
| 104 |
+
quant_min_lower_bound: Union[int, float, None] = None
|
| 105 |
+
quant_max_upper_bound: Union[int, float, None] = None
|
| 106 |
+
scale_min_lower_bound: Union[int, float, None] = None
|
| 107 |
+
scale_max_upper_bound: Union[int, float, None] = None
|
| 108 |
+
scale_exact_match: Optional[float] = None
|
| 109 |
+
zero_point_exact_match: Optional[int] = None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@dataclass
|
| 113 |
+
class DTypeConfig:
|
| 114 |
+
"""
|
| 115 |
+
Config object that specifies the supported data types passed as arguments to
|
| 116 |
+
quantize ops in the reference model spec, for input and output activations,
|
| 117 |
+
weights, and biases.
|
| 118 |
+
|
| 119 |
+
For example, consider the following reference model:
|
| 120 |
+
|
| 121 |
+
quant1 - [dequant1 - fp32_linear - quant2] - dequant2
|
| 122 |
+
|
| 123 |
+
The pattern in the square brackets refers to the reference pattern of
|
| 124 |
+
statically quantized linear. Setting the input dtype as `torch.quint8`
|
| 125 |
+
in the DTypeConfig means we pass in `torch.quint8` as the dtype argument
|
| 126 |
+
to the first quantize op (quant1). Similarly, setting the output dtype as
|
| 127 |
+
`torch.quint8` means we pass in `torch.quint8` as the dtype argument to
|
| 128 |
+
the second quantize op (quant2).
|
| 129 |
+
|
| 130 |
+
Note that the dtype here does not refer to the interface dtypes of the
|
| 131 |
+
op. For example, the "input dtype" here is not the dtype of the input
|
| 132 |
+
tensor passed to the quantized linear op. Though it can still be the
|
| 133 |
+
same as the interface dtype, this is not always the case, e.g. the
|
| 134 |
+
interface dtype is fp32 in dynamic quantization but the "input dtype"
|
| 135 |
+
specified in the DTypeConfig would still be quint8. The semantics of
|
| 136 |
+
dtypes here are the same as the semantics of the dtypes specified in
|
| 137 |
+
the observers.
|
| 138 |
+
|
| 139 |
+
These dtypes are matched against the ones specified in the user's
|
| 140 |
+
QConfig. If there is a match, and the QConfig satisfies the constraints
|
| 141 |
+
specified in the DTypeConfig (if any), then we will quantize the given
|
| 142 |
+
pattern using this DTypeConfig. Otherwise, the QConfig is ignored and
|
| 143 |
+
the pattern will not be quantized.
|
| 144 |
+
|
| 145 |
+
Example usage::
|
| 146 |
+
|
| 147 |
+
>>> # xdoctest: +SKIP(failing)
|
| 148 |
+
>>> dtype_config1 = DTypeConfig(
|
| 149 |
+
... input_dtype=torch.quint8,
|
| 150 |
+
... output_dtype=torch.quint8,
|
| 151 |
+
... weight_dtype=torch.qint8,
|
| 152 |
+
... bias_dtype=torch.float)
|
| 153 |
+
|
| 154 |
+
>>> dtype_config2 = DTypeConfig(
|
| 155 |
+
... input_dtype=DTypeWithConstraints(
|
| 156 |
+
... dtype=torch.quint8,
|
| 157 |
+
... quant_min_lower_bound=0,
|
| 158 |
+
... quant_max_upper_bound=255,
|
| 159 |
+
... ),
|
| 160 |
+
... output_dtype=DTypeWithConstraints(
|
| 161 |
+
... dtype=torch.quint8,
|
| 162 |
+
... quant_min_lower_bound=0,
|
| 163 |
+
... quant_max_upper_bound=255,
|
| 164 |
+
... ),
|
| 165 |
+
... weight_dtype=DTypeWithConstraints(
|
| 166 |
+
... dtype=torch.qint8,
|
| 167 |
+
... quant_min_lower_bound=-128,
|
| 168 |
+
... quant_max_upper_bound=127,
|
| 169 |
+
... ),
|
| 170 |
+
... bias_dtype=torch.float)
|
| 171 |
+
|
| 172 |
+
>>> dtype_config1.input_dtype
|
| 173 |
+
torch.quint8
|
| 174 |
+
|
| 175 |
+
>>> dtype_config2.input_dtype
|
| 176 |
+
torch.quint8
|
| 177 |
+
|
| 178 |
+
>>> dtype_config2.input_dtype_with_constraints
|
| 179 |
+
DTypeWithConstraints(dtype=torch.quint8, quant_min_lower_bound=0, quant_max_upper_bound=255, \
|
| 180 |
+
scale_min_lower_bound=None, scale_max_upper_bound=None)
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
input_dtype_with_constraints: DTypeWithConstraints
|
| 184 |
+
output_dtype_with_constraints: DTypeWithConstraints
|
| 185 |
+
weight_dtype_with_constraints: DTypeWithConstraints
|
| 186 |
+
bias_dtype: Optional[torch.dtype]
|
| 187 |
+
is_dynamic: Optional[bool]
|
| 188 |
+
|
| 189 |
+
def __init__(
|
| 190 |
+
self,
|
| 191 |
+
input_dtype: Union[torch.dtype, DTypeWithConstraints, None] = None,
|
| 192 |
+
output_dtype: Union[torch.dtype, DTypeWithConstraints, None] = None,
|
| 193 |
+
weight_dtype: Union[torch.dtype, DTypeWithConstraints, None] = None,
|
| 194 |
+
bias_dtype: Optional[torch.dtype] = None,
|
| 195 |
+
is_dynamic: Optional[bool] = None,
|
| 196 |
+
):
|
| 197 |
+
if isinstance(input_dtype, DTypeWithConstraints):
|
| 198 |
+
self.input_dtype_with_constraints = input_dtype
|
| 199 |
+
else:
|
| 200 |
+
self.input_dtype_with_constraints = DTypeWithConstraints(dtype=input_dtype)
|
| 201 |
+
|
| 202 |
+
if isinstance(output_dtype, DTypeWithConstraints):
|
| 203 |
+
self.output_dtype_with_constraints = output_dtype
|
| 204 |
+
else:
|
| 205 |
+
self.output_dtype_with_constraints = DTypeWithConstraints(
|
| 206 |
+
dtype=output_dtype
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
if isinstance(weight_dtype, DTypeWithConstraints):
|
| 210 |
+
self.weight_dtype_with_constraints = weight_dtype
|
| 211 |
+
else:
|
| 212 |
+
self.weight_dtype_with_constraints = DTypeWithConstraints(
|
| 213 |
+
dtype=weight_dtype
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
self.bias_dtype = bias_dtype
|
| 217 |
+
self.is_dynamic = is_dynamic
|
| 218 |
+
|
| 219 |
+
@property
|
| 220 |
+
def input_dtype(self) -> Optional[torch.dtype]:
|
| 221 |
+
return self.input_dtype_with_constraints.dtype
|
| 222 |
+
|
| 223 |
+
@property
|
| 224 |
+
def output_dtype(self) -> Optional[torch.dtype]:
|
| 225 |
+
return self.output_dtype_with_constraints.dtype
|
| 226 |
+
|
| 227 |
+
@property
|
| 228 |
+
def weight_dtype(self) -> Optional[torch.dtype]:
|
| 229 |
+
return self.weight_dtype_with_constraints.dtype
|
| 230 |
+
|
| 231 |
+
@classmethod
|
| 232 |
+
def from_dict(cls, dtype_config_dict: Dict[str, Any]) -> DTypeConfig:
|
| 233 |
+
"""
|
| 234 |
+
Create a ``DTypeConfig`` from a dictionary with the following items (all optional):
|
| 235 |
+
"input_dtype": torch.dtype or ``DTypeWithConstraints``
|
| 236 |
+
"output_dtype": torch.dtype or ``DTypeWithConstraints``
|
| 237 |
+
"weight_dtype": torch.dtype or ``DTypeWithConstraints``
|
| 238 |
+
"bias_type": torch.dtype
|
| 239 |
+
"is_dynamic": bool
|
| 240 |
+
"""
|
| 241 |
+
input_dtype = dtype_config_dict.get(INPUT_DTYPE_DICT_KEY, None)
|
| 242 |
+
if input_dtype is not None and not isinstance(
|
| 243 |
+
input_dtype, (torch.dtype, DTypeWithConstraints)
|
| 244 |
+
):
|
| 245 |
+
raise ValueError(
|
| 246 |
+
"Expected input_dtype to be a torch.dtype or DTypeWithConstraints"
|
| 247 |
+
)
|
| 248 |
+
output_dtype = dtype_config_dict.get(OUTPUT_DTYPE_DICT_KEY, None)
|
| 249 |
+
if output_dtype is not None and not isinstance(
|
| 250 |
+
output_dtype, (torch.dtype, DTypeWithConstraints)
|
| 251 |
+
):
|
| 252 |
+
raise ValueError(
|
| 253 |
+
"Expected output_dtype to be a torch.dtype or DTypeWithConstraints"
|
| 254 |
+
)
|
| 255 |
+
weight_dtype = dtype_config_dict.get(WEIGHT_DTYPE_DICT_KEY, None)
|
| 256 |
+
if weight_dtype is not None and not isinstance(
|
| 257 |
+
weight_dtype, (torch.dtype, DTypeWithConstraints)
|
| 258 |
+
):
|
| 259 |
+
raise ValueError(
|
| 260 |
+
"Expected weight_dtype to be a torch.dtype or DTypeWithConstraints"
|
| 261 |
+
)
|
| 262 |
+
bias_dtype = dtype_config_dict.get(BIAS_DTYPE_DICT_KEY, None)
|
| 263 |
+
is_dynamic = dtype_config_dict.get(IS_DYNAMIC_DICT_KEY, None)
|
| 264 |
+
return cls(input_dtype, output_dtype, weight_dtype, bias_dtype, is_dynamic)
|
| 265 |
+
|
| 266 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 267 |
+
"""
|
| 268 |
+
Convert this ``DTypeConfig`` to a dictionary with the items described in
|
| 269 |
+
:func:`~torch.ao.quantization.backend_config.DTypeConfig.from_dict`.
|
| 270 |
+
"""
|
| 271 |
+
dtype_config_dict: Dict[str, Any] = {}
|
| 272 |
+
if self.input_dtype is not None:
|
| 273 |
+
dtype_config_dict[INPUT_DTYPE_DICT_KEY] = self.input_dtype_with_constraints
|
| 274 |
+
if self.output_dtype is not None:
|
| 275 |
+
dtype_config_dict[
|
| 276 |
+
OUTPUT_DTYPE_DICT_KEY
|
| 277 |
+
] = self.output_dtype_with_constraints
|
| 278 |
+
if self.weight_dtype is not None:
|
| 279 |
+
dtype_config_dict[
|
| 280 |
+
WEIGHT_DTYPE_DICT_KEY
|
| 281 |
+
] = self.weight_dtype_with_constraints
|
| 282 |
+
if self.bias_dtype is not None:
|
| 283 |
+
dtype_config_dict[BIAS_DTYPE_DICT_KEY] = self.bias_dtype
|
| 284 |
+
if self.is_dynamic is not None:
|
| 285 |
+
dtype_config_dict[IS_DYNAMIC_DICT_KEY] = self.is_dynamic
|
| 286 |
+
return dtype_config_dict
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
class BackendConfig:
|
| 290 |
+
# TODO: refer to NativeBackendConfig once that is implemented
|
| 291 |
+
"""Config that defines the set of patterns that can be quantized on a given backend, and how reference
|
| 292 |
+
quantized models can be produced from these patterns.
|
| 293 |
+
|
| 294 |
+
A pattern in this context refers to a module, a functional, an operator, or a directed acyclic graph
|
| 295 |
+
of the above. Each pattern supported on the target backend can be individually configured through
|
| 296 |
+
:class:`~torch.ao.quantization.backend_config.BackendPatternConfig` in terms of:
|
| 297 |
+
|
| 298 |
+
(1) The supported input/output activation, weight, and bias data types
|
| 299 |
+
|
| 300 |
+
(2) How observers and quant/dequant ops are inserted in order to construct the reference pattern, and
|
| 301 |
+
|
| 302 |
+
(3) (Optionally) Fusion, QAT, and reference module mappings.
|
| 303 |
+
|
| 304 |
+
The format of the patterns is described in:
|
| 305 |
+
https://github.com/pytorch/pytorch/blob/master/torch/ao/quantization/backend_config/README.md
|
| 306 |
+
|
| 307 |
+
Example usage::
|
| 308 |
+
|
| 309 |
+
import torch
|
| 310 |
+
from torch.ao.quantization.backend_config import (
|
| 311 |
+
BackendConfig,
|
| 312 |
+
BackendPatternConfig,
|
| 313 |
+
DTypeConfig,
|
| 314 |
+
ObservationType,
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
weighted_int8_dtype_config = DTypeConfig(
|
| 318 |
+
input_dtype=torch.quint8,
|
| 319 |
+
output_dtype=torch.quint8,
|
| 320 |
+
weight_dtype=torch.qint8,
|
| 321 |
+
bias_dtype=torch.float)
|
| 322 |
+
|
| 323 |
+
def fuse_conv2d_relu(is_qat, conv, relu):
|
| 324 |
+
return torch.ao.nn.intrinsic.ConvReLU2d(conv, relu)
|
| 325 |
+
|
| 326 |
+
# For quantizing Linear
|
| 327 |
+
linear_config = BackendPatternConfig(torch.nn.Linear) \
|
| 328 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
|
| 329 |
+
.add_dtype_config(weighted_int8_dtype_config) \
|
| 330 |
+
.set_root_module(torch.nn.Linear) \
|
| 331 |
+
.set_qat_module(torch.ao.nn.qat.Linear) \
|
| 332 |
+
.set_reference_quantized_module(torch.ao.nn.quantized.reference.Linear)
|
| 333 |
+
|
| 334 |
+
# For fusing Conv2d + ReLU into ConvReLU2d
|
| 335 |
+
conv_relu_config = BackendPatternConfig((torch.nn.Conv2d, torch.nn.ReLU)) \
|
| 336 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
|
| 337 |
+
.add_dtype_config(weighted_int8_dtype_config) \
|
| 338 |
+
.set_fused_module(torch.ao.nn.intrinsic.ConvReLU2d) \
|
| 339 |
+
.set_fuser_method(fuse_conv2d_relu)
|
| 340 |
+
|
| 341 |
+
# For quantizing ConvReLU2d
|
| 342 |
+
fused_conv_relu_config = BackendPatternConfig(torch.ao.nn.intrinsic.ConvReLU2d) \
|
| 343 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
|
| 344 |
+
.add_dtype_config(weighted_int8_dtype_config) \
|
| 345 |
+
.set_root_module(torch.nn.Conv2d) \
|
| 346 |
+
.set_qat_module(torch.ao.nn.intrinsic.qat.ConvReLU2d) \
|
| 347 |
+
.set_reference_quantized_module(torch.ao.nn.quantized.reference.Conv2d)
|
| 348 |
+
|
| 349 |
+
backend_config = BackendConfig("my_backend") \
|
| 350 |
+
.set_backend_pattern_config(linear_config) \
|
| 351 |
+
.set_backend_pattern_config(conv_relu_config) \
|
| 352 |
+
.set_backend_pattern_config(fused_conv_relu_config)
|
| 353 |
+
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
def __init__(self, name: str = ""):
|
| 357 |
+
self.name = name
|
| 358 |
+
# Store all BackendPatternConfigs in a map to handle duplicates
|
| 359 |
+
# Note: the key in this map uses the complex reversed tuple format.
|
| 360 |
+
# This is intended only for internal use; users who wish to access
|
| 361 |
+
# the original patterns should go through `self.configs` instead.
|
| 362 |
+
self._pattern_complex_format_to_config: Dict[Pattern, BackendPatternConfig] = {}
|
| 363 |
+
|
| 364 |
+
def __repr__(self):
|
| 365 |
+
return f"BackendConfig({self.__dict__})"
|
| 366 |
+
|
| 367 |
+
def set_name(self, name: str) -> BackendConfig:
|
| 368 |
+
"""
|
| 369 |
+
Set the name of the target backend.
|
| 370 |
+
"""
|
| 371 |
+
self.name = name
|
| 372 |
+
return self
|
| 373 |
+
|
| 374 |
+
def set_backend_pattern_config(self, config: BackendPatternConfig) -> BackendConfig:
|
| 375 |
+
"""
|
| 376 |
+
Set the config for an pattern that can be run on the target backend.
|
| 377 |
+
This overrides any existing config for the given pattern.
|
| 378 |
+
"""
|
| 379 |
+
# Avoid circular dependencies
|
| 380 |
+
pattern_complex_format = torch.ao.quantization.backend_config.utils._get_pattern_in_reversed_nested_tuple_format(
|
| 381 |
+
config
|
| 382 |
+
) # type: ignore[attr-defined]
|
| 383 |
+
self._pattern_complex_format_to_config[pattern_complex_format] = config
|
| 384 |
+
return self
|
| 385 |
+
|
| 386 |
+
def set_backend_pattern_configs(
|
| 387 |
+
self, configs: List[BackendPatternConfig]
|
| 388 |
+
) -> BackendConfig:
|
| 389 |
+
"""
|
| 390 |
+
Set the configs for patterns that can be run on the target backend.
|
| 391 |
+
This overrides any existing config for a given pattern if it was previously registered already.
|
| 392 |
+
"""
|
| 393 |
+
for conf in configs:
|
| 394 |
+
self.set_backend_pattern_config(conf)
|
| 395 |
+
return self
|
| 396 |
+
|
| 397 |
+
@property
|
| 398 |
+
def configs(self) -> List[BackendPatternConfig]:
|
| 399 |
+
"""
|
| 400 |
+
Return a copy of the list of configs set in this `BackendConfig`.
|
| 401 |
+
"""
|
| 402 |
+
return list(self._pattern_complex_format_to_config.values())
|
| 403 |
+
|
| 404 |
+
@classmethod
|
| 405 |
+
def from_dict(cls, backend_config_dict: Dict[str, Any]) -> BackendConfig:
|
| 406 |
+
"""
|
| 407 |
+
Create a ``BackendConfig`` from a dictionary with the following items:
|
| 408 |
+
|
| 409 |
+
"name": the name of the target backend
|
| 410 |
+
|
| 411 |
+
"configs": a list of dictionaries that each represents a `BackendPatternConfig`
|
| 412 |
+
|
| 413 |
+
"""
|
| 414 |
+
conf = cls(backend_config_dict.get(NAME_DICT_KEY, ""))
|
| 415 |
+
for d in backend_config_dict.get(CONFIGS_DICT_KEY, []):
|
| 416 |
+
if isinstance(d, BackendPatternConfig):
|
| 417 |
+
conf.set_backend_pattern_config(d)
|
| 418 |
+
elif isinstance(d, Dict):
|
| 419 |
+
conf.set_backend_pattern_config(BackendPatternConfig.from_dict(d))
|
| 420 |
+
else:
|
| 421 |
+
raise ValueError(
|
| 422 |
+
f"Expected backend_config_dict['{CONFIGS_DICT_KEY}'] to be a dictionary"
|
| 423 |
+
)
|
| 424 |
+
return conf
|
| 425 |
+
|
| 426 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 427 |
+
"""
|
| 428 |
+
Convert this ``BackendConfig`` to a dictionary with the items described in
|
| 429 |
+
:func:`~torch.ao.quantization.backend_config.BackendConfig.from_dict`.
|
| 430 |
+
"""
|
| 431 |
+
return {
|
| 432 |
+
NAME_DICT_KEY: self.name,
|
| 433 |
+
CONFIGS_DICT_KEY: [c.to_dict() for c in self.configs],
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
class BackendPatternConfig:
|
| 438 |
+
"""
|
| 439 |
+
Config object that specifies quantization behavior for a given operator pattern.
|
| 440 |
+
For a detailed example usage, see :class:`~torch.ao.quantization.backend_config.BackendConfig`.
|
| 441 |
+
"""
|
| 442 |
+
|
| 443 |
+
def __init__(self, pattern: Optional[Pattern] = None):
|
| 444 |
+
self.pattern: Optional[Pattern] = pattern
|
| 445 |
+
self.observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 446 |
+
self.dtype_configs: List[DTypeConfig] = []
|
| 447 |
+
self.root_module: Optional[Type[torch.nn.Module]] = None
|
| 448 |
+
self.qat_module: Optional[Type[torch.nn.Module]] = None
|
| 449 |
+
self.reference_quantized_module: Optional[Type[torch.nn.Module]] = None
|
| 450 |
+
self.fused_module: Optional[Type[torch.nn.Module]] = None
|
| 451 |
+
self.fuser_method: Optional[Callable] = None
|
| 452 |
+
|
| 453 |
+
# Temporary/internal configs
|
| 454 |
+
self._root_node_getter: Optional[Callable] = None
|
| 455 |
+
self._extra_inputs_getter: Optional[Callable] = None
|
| 456 |
+
self._num_tensor_args_to_observation_type: Dict[int, ObservationType] = {}
|
| 457 |
+
self._input_type_to_index: Dict[str, int] = {}
|
| 458 |
+
self._pattern_complex_format: Optional[Pattern] = None
|
| 459 |
+
|
| 460 |
+
def __repr__(self):
|
| 461 |
+
dict_nonempty = {
|
| 462 |
+
k: v
|
| 463 |
+
for k, v in self.__dict__.items()
|
| 464 |
+
if (
|
| 465 |
+
(not isinstance(v, (list, dict)) and v is not None)
|
| 466 |
+
or (isinstance(v, (list, dict)) and len(v) > 0)
|
| 467 |
+
)
|
| 468 |
+
}
|
| 469 |
+
return f"BackendPatternConfig({dict_nonempty})"
|
| 470 |
+
|
| 471 |
+
def set_pattern(self, pattern: Pattern) -> BackendPatternConfig:
|
| 472 |
+
"""
|
| 473 |
+
Set the pattern to configure.
|
| 474 |
+
|
| 475 |
+
The pattern can be a float module, functional operator, pytorch operator, or a tuple
|
| 476 |
+
combination of the above. Tuple patterns are treated as sequential patterns, and
|
| 477 |
+
currently only tuples of 2 or 3 elements are supported.
|
| 478 |
+
"""
|
| 479 |
+
if self._pattern_complex_format is not None:
|
| 480 |
+
raise ValueError(
|
| 481 |
+
"Only one of 'pattern' or 'pattern_complex_format' can be set"
|
| 482 |
+
)
|
| 483 |
+
self.pattern = pattern
|
| 484 |
+
return self
|
| 485 |
+
|
| 486 |
+
def set_observation_type(
|
| 487 |
+
self, observation_type: ObservationType
|
| 488 |
+
) -> BackendPatternConfig:
|
| 489 |
+
"""
|
| 490 |
+
Set how observers should be inserted in the graph for this pattern.
|
| 491 |
+
|
| 492 |
+
Observation type here refers to how observers (or quant-dequant ops) will be placed
|
| 493 |
+
in the graph. This is used to produce the desired reference patterns understood by
|
| 494 |
+
the backend. Weighted ops such as linear and conv require different observers
|
| 495 |
+
(or quantization parameters passed to quantize ops in the reference model) for the
|
| 496 |
+
input and the output.
|
| 497 |
+
|
| 498 |
+
There are two observation types:
|
| 499 |
+
|
| 500 |
+
`OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT` (default): the output observer instance
|
| 501 |
+
will be different from the input. This is the most common observation type.
|
| 502 |
+
|
| 503 |
+
`OUTPUT_SHARE_OBSERVER_WITH_INPUT`: the output observer instance will be the
|
| 504 |
+
same as the input. This is useful for operators like `cat`.
|
| 505 |
+
|
| 506 |
+
Note: This will be renamed in the near future, since we will soon insert QuantDeQuantStubs
|
| 507 |
+
with observers (and fake quantizes) attached instead of observers themselves.
|
| 508 |
+
"""
|
| 509 |
+
self.observation_type = observation_type
|
| 510 |
+
return self
|
| 511 |
+
|
| 512 |
+
def add_dtype_config(self, dtype_config: DTypeConfig) -> BackendPatternConfig:
|
| 513 |
+
"""
|
| 514 |
+
Add a set of supported data types passed as arguments to quantize ops in the
|
| 515 |
+
reference model spec.
|
| 516 |
+
"""
|
| 517 |
+
self.dtype_configs.append(dtype_config)
|
| 518 |
+
return self
|
| 519 |
+
|
| 520 |
+
def set_dtype_configs(
|
| 521 |
+
self, dtype_configs: List[DTypeConfig]
|
| 522 |
+
) -> BackendPatternConfig:
|
| 523 |
+
"""
|
| 524 |
+
Set the supported data types passed as arguments to quantize ops in the
|
| 525 |
+
reference model spec, overriding all previously registered data types.
|
| 526 |
+
"""
|
| 527 |
+
self.dtype_configs = dtype_configs
|
| 528 |
+
return self
|
| 529 |
+
|
| 530 |
+
def set_root_module(
|
| 531 |
+
self, root_module: Type[torch.nn.Module]
|
| 532 |
+
) -> BackendPatternConfig:
|
| 533 |
+
"""
|
| 534 |
+
Set the module that represents the root for this pattern.
|
| 535 |
+
|
| 536 |
+
When we construct the reference quantized model during the convert phase,
|
| 537 |
+
the root modules (e.g. torch.nn.Linear for torch.ao.nn.intrinsic.LinearReLU)
|
| 538 |
+
will be swapped to the corresponding reference quantized modules (e.g.
|
| 539 |
+
torch.ao.nn.reference.quantized.Linear). This allows custom backends to
|
| 540 |
+
specify custom reference quantized module implementations to match the
|
| 541 |
+
numerics of their lowered operators. Since this is a one-to-one mapping,
|
| 542 |
+
both the root module and the reference quantized module must be specified
|
| 543 |
+
in the same BackendPatternConfig in order for the conversion to take place.
|
| 544 |
+
"""
|
| 545 |
+
self.root_module = root_module
|
| 546 |
+
return self
|
| 547 |
+
|
| 548 |
+
def set_qat_module(self, qat_module: Type[torch.nn.Module]) -> BackendPatternConfig:
|
| 549 |
+
"""
|
| 550 |
+
Set the module that represents the QAT implementation for this pattern.
|
| 551 |
+
"""
|
| 552 |
+
self.qat_module = qat_module
|
| 553 |
+
return self
|
| 554 |
+
|
| 555 |
+
def set_reference_quantized_module(
|
| 556 |
+
self, reference_quantized_module: Type[torch.nn.Module]
|
| 557 |
+
) -> BackendPatternConfig:
|
| 558 |
+
"""
|
| 559 |
+
Set the module that represents the reference quantized implementation for
|
| 560 |
+
this pattern's root module.
|
| 561 |
+
|
| 562 |
+
For more detail, see :func:`~torch.ao.quantization.backend_config.BackendPatternConfig.set_root_module`.
|
| 563 |
+
"""
|
| 564 |
+
self.reference_quantized_module = reference_quantized_module
|
| 565 |
+
return self
|
| 566 |
+
|
| 567 |
+
def set_fused_module(
|
| 568 |
+
self, fused_module: Type[torch.nn.Module]
|
| 569 |
+
) -> BackendPatternConfig:
|
| 570 |
+
"""
|
| 571 |
+
Set the module that represents the fused implementation for this pattern.
|
| 572 |
+
"""
|
| 573 |
+
self.fused_module = fused_module
|
| 574 |
+
return self
|
| 575 |
+
|
| 576 |
+
def set_fuser_method(self, fuser_method: Callable) -> BackendPatternConfig:
|
| 577 |
+
"""
|
| 578 |
+
Set the function that specifies how to fuse this BackendPatternConfig's pattern.
|
| 579 |
+
|
| 580 |
+
The first argument of this function should be `is_qat`, and the rest of the arguments
|
| 581 |
+
should be the items in the tuple pattern. The return value of this function should be
|
| 582 |
+
the resulting fused module.
|
| 583 |
+
|
| 584 |
+
For example, the fuser method for the pattern `(torch.nn.Linear, torch.nn.ReLU)` can be:
|
| 585 |
+
|
| 586 |
+
def fuse_linear_relu(is_qat, linear, relu):
|
| 587 |
+
return torch.ao.nn.intrinsic.LinearReLU(linear, relu)
|
| 588 |
+
|
| 589 |
+
For a more complicated example, see https://gist.github.com/jerryzh168/8bea7180a8ba3c279f2c9b050f2a69a6.
|
| 590 |
+
"""
|
| 591 |
+
self.fuser_method = fuser_method
|
| 592 |
+
return self
|
| 593 |
+
|
| 594 |
+
def _set_root_node_getter(self, root_node_getter: Callable) -> BackendPatternConfig:
|
| 595 |
+
self._root_node_getter = root_node_getter
|
| 596 |
+
return self
|
| 597 |
+
|
| 598 |
+
def _set_extra_inputs_getter(
|
| 599 |
+
self, extra_inputs_getter: Callable
|
| 600 |
+
) -> BackendPatternConfig:
|
| 601 |
+
self._extra_inputs_getter = extra_inputs_getter
|
| 602 |
+
return self
|
| 603 |
+
|
| 604 |
+
def _set_num_tensor_args_to_observation_type(
|
| 605 |
+
self, num_tensor_args_to_observation_type: Dict[int, ObservationType]
|
| 606 |
+
) -> BackendPatternConfig:
|
| 607 |
+
self._num_tensor_args_to_observation_type = num_tensor_args_to_observation_type
|
| 608 |
+
return self
|
| 609 |
+
|
| 610 |
+
def _set_input_type_to_index(
|
| 611 |
+
self, input_type_to_index: Dict[str, int]
|
| 612 |
+
) -> BackendPatternConfig:
|
| 613 |
+
self._input_type_to_index = input_type_to_index
|
| 614 |
+
return self
|
| 615 |
+
|
| 616 |
+
def _set_pattern_complex_format(self, pattern: Pattern) -> BackendPatternConfig:
|
| 617 |
+
"""
|
| 618 |
+
Set the pattern to configure, using the reversed nested tuple format.
|
| 619 |
+
|
| 620 |
+
See the BackendConfig README for more detail:
|
| 621 |
+
https://github.com/pytorch/pytorch/blob/master/torch/ao/quantization/backend_config/README.md#advanced-pattern-specification
|
| 622 |
+
"""
|
| 623 |
+
if self.pattern is not None:
|
| 624 |
+
raise ValueError(
|
| 625 |
+
"Only one of 'pattern' or 'pattern_complex_format' can be set"
|
| 626 |
+
)
|
| 627 |
+
self._pattern_complex_format = pattern
|
| 628 |
+
return self
|
| 629 |
+
|
| 630 |
+
@classmethod
|
| 631 |
+
def from_dict(
|
| 632 |
+
cls, backend_pattern_config_dict: Dict[str, Any]
|
| 633 |
+
) -> BackendPatternConfig:
|
| 634 |
+
"""
|
| 635 |
+
Create a ``BackendPatternConfig`` from a dictionary with the following items:
|
| 636 |
+
|
| 637 |
+
"pattern": the pattern being configured
|
| 638 |
+
"observation_type": the :class:`~torch.ao.quantization.backend_config.ObservationType` that specifies how
|
| 639 |
+
observers should be inserted for this pattern
|
| 640 |
+
"dtype_configs": a list of dictionaries that represents :class:`~torch.ao.quantization.backend_config.DTypeConfig` s
|
| 641 |
+
"root_module": a :class:`torch.nn.Module` that represents the root for this pattern
|
| 642 |
+
"qat_module": a :class:`torch.nn.Module` that represents the QAT implementation for this pattern
|
| 643 |
+
"reference_quantized_module": a :class:`torch.nn.Module` that represents the reference quantized
|
| 644 |
+
implementation for this pattern's root module.
|
| 645 |
+
"fused_module": a :class:`torch.nn.Module` that represents the fused implementation for this pattern
|
| 646 |
+
"fuser_method": a function that specifies how to fuse the pattern for this pattern
|
| 647 |
+
"pattern_complex_format": the pattern specified in the reversed nested tuple format (deprecated)
|
| 648 |
+
|
| 649 |
+
"""
|
| 650 |
+
|
| 651 |
+
def _get_dtype_config(obj: Any) -> DTypeConfig:
|
| 652 |
+
"""
|
| 653 |
+
Convert the given object into a ``DTypeConfig`` if possible, else throw an exception.
|
| 654 |
+
"""
|
| 655 |
+
if isinstance(obj, DTypeConfig):
|
| 656 |
+
return obj
|
| 657 |
+
if isinstance(obj, Dict):
|
| 658 |
+
return DTypeConfig.from_dict(obj)
|
| 659 |
+
raise ValueError(
|
| 660 |
+
f"Expected a list of DTypeConfigs in "
|
| 661 |
+
f"backend_pattern_config_dict[\"{DTYPE_CONFIGS_DICT_KEY}\"], got '{type(obj)}'"
|
| 662 |
+
)
|
| 663 |
+
|
| 664 |
+
conf = cls()
|
| 665 |
+
if PATTERN_DICT_KEY in backend_pattern_config_dict:
|
| 666 |
+
conf.set_pattern(backend_pattern_config_dict[PATTERN_DICT_KEY])
|
| 667 |
+
if OBSERVATION_TYPE_DICT_KEY in backend_pattern_config_dict:
|
| 668 |
+
conf.set_observation_type(
|
| 669 |
+
backend_pattern_config_dict[OBSERVATION_TYPE_DICT_KEY]
|
| 670 |
+
)
|
| 671 |
+
for d in backend_pattern_config_dict.get(DTYPE_CONFIGS_DICT_KEY, []):
|
| 672 |
+
conf.add_dtype_config(_get_dtype_config(d))
|
| 673 |
+
conf.set_root_module(
|
| 674 |
+
backend_pattern_config_dict.get(ROOT_MODULE_DICT_KEY, None)
|
| 675 |
+
)
|
| 676 |
+
conf.set_qat_module(backend_pattern_config_dict.get(QAT_MODULE_DICT_KEY, None))
|
| 677 |
+
conf.set_reference_quantized_module(
|
| 678 |
+
backend_pattern_config_dict.get(REFERENCE_QUANTIZED_MODULE_DICT_KEY, None)
|
| 679 |
+
)
|
| 680 |
+
conf.set_fused_module(
|
| 681 |
+
backend_pattern_config_dict.get(FUSED_MODULE_DICT_KEY, None)
|
| 682 |
+
)
|
| 683 |
+
conf.set_fuser_method(
|
| 684 |
+
backend_pattern_config_dict.get(FUSER_METHOD_DICT_KEY, None)
|
| 685 |
+
)
|
| 686 |
+
conf._set_root_node_getter(
|
| 687 |
+
backend_pattern_config_dict.get(ROOT_NODE_GETTER_DICT_KEY, None)
|
| 688 |
+
)
|
| 689 |
+
conf._set_extra_inputs_getter(
|
| 690 |
+
backend_pattern_config_dict.get(EXTRA_INPUTS_GETTER_DICT_KEY, None)
|
| 691 |
+
)
|
| 692 |
+
conf._set_num_tensor_args_to_observation_type(
|
| 693 |
+
backend_pattern_config_dict.get(
|
| 694 |
+
NUM_TENSOR_ARGS_TO_OBSERVATION_TYPE_DICT_KEY, {}
|
| 695 |
+
)
|
| 696 |
+
)
|
| 697 |
+
conf._set_input_type_to_index(
|
| 698 |
+
backend_pattern_config_dict.get(INPUT_TYPE_TO_INDEX_DICT_KEY, {})
|
| 699 |
+
)
|
| 700 |
+
if PATTERN_COMPLEX_FORMAT_DICT_KEY in backend_pattern_config_dict:
|
| 701 |
+
conf._set_pattern_complex_format(
|
| 702 |
+
backend_pattern_config_dict[PATTERN_COMPLEX_FORMAT_DICT_KEY]
|
| 703 |
+
)
|
| 704 |
+
return conf
|
| 705 |
+
|
| 706 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 707 |
+
"""
|
| 708 |
+
Convert this ``BackendPatternConfig`` to a dictionary with the items described in
|
| 709 |
+
:func:`~torch.ao.quantization.backend_config.BackendPatternConfig.from_dict`.
|
| 710 |
+
"""
|
| 711 |
+
backend_pattern_config_dict: Dict[str, Any] = {
|
| 712 |
+
OBSERVATION_TYPE_DICT_KEY: self.observation_type,
|
| 713 |
+
DTYPE_CONFIGS_DICT_KEY: [c.to_dict() for c in self.dtype_configs],
|
| 714 |
+
}
|
| 715 |
+
if self.pattern is not None:
|
| 716 |
+
backend_pattern_config_dict[PATTERN_DICT_KEY] = self.pattern
|
| 717 |
+
if self.root_module is not None:
|
| 718 |
+
backend_pattern_config_dict[ROOT_MODULE_DICT_KEY] = self.root_module
|
| 719 |
+
if self.qat_module is not None:
|
| 720 |
+
backend_pattern_config_dict[QAT_MODULE_DICT_KEY] = self.qat_module
|
| 721 |
+
if self.reference_quantized_module is not None:
|
| 722 |
+
backend_pattern_config_dict[
|
| 723 |
+
REFERENCE_QUANTIZED_MODULE_DICT_KEY
|
| 724 |
+
] = self.reference_quantized_module
|
| 725 |
+
if self.fused_module is not None:
|
| 726 |
+
backend_pattern_config_dict[FUSED_MODULE_DICT_KEY] = self.fused_module
|
| 727 |
+
if self.fuser_method is not None:
|
| 728 |
+
backend_pattern_config_dict[FUSER_METHOD_DICT_KEY] = self.fuser_method
|
| 729 |
+
if self._root_node_getter is not None:
|
| 730 |
+
backend_pattern_config_dict[
|
| 731 |
+
ROOT_NODE_GETTER_DICT_KEY
|
| 732 |
+
] = self._root_node_getter
|
| 733 |
+
if self._extra_inputs_getter is not None:
|
| 734 |
+
backend_pattern_config_dict[
|
| 735 |
+
EXTRA_INPUTS_GETTER_DICT_KEY
|
| 736 |
+
] = self._extra_inputs_getter
|
| 737 |
+
if len(self._num_tensor_args_to_observation_type) > 0:
|
| 738 |
+
backend_pattern_config_dict[
|
| 739 |
+
NUM_TENSOR_ARGS_TO_OBSERVATION_TYPE_DICT_KEY
|
| 740 |
+
] = self._num_tensor_args_to_observation_type
|
| 741 |
+
if len(self._input_type_to_index) > 0:
|
| 742 |
+
backend_pattern_config_dict[
|
| 743 |
+
INPUT_TYPE_TO_INDEX_DICT_KEY
|
| 744 |
+
] = self._input_type_to_index
|
| 745 |
+
if self._pattern_complex_format is not None:
|
| 746 |
+
backend_pattern_config_dict[
|
| 747 |
+
PATTERN_COMPLEX_FORMAT_DICT_KEY
|
| 748 |
+
] = self._pattern_complex_format
|
| 749 |
+
return backend_pattern_config_dict
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/executorch.py
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# TODO: rename executorch to qnnpack_executorch since executorch is a general runtime
|
| 2 |
+
# not a specific backend
|
| 3 |
+
|
| 4 |
+
import operator
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.ao.nn.qat as nnqat
|
| 9 |
+
import torch.ao.nn.quantized.reference as nnqr
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from torch.ao.quantization.fuser_method_mappings import (
|
| 13 |
+
_sequential_wrapper2,
|
| 14 |
+
fuse_conv_bn,
|
| 15 |
+
fuse_conv_bn_relu,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
from ._common_operator_config_utils import _Conv2dMetadata
|
| 19 |
+
from .backend_config import (
|
| 20 |
+
BackendConfig,
|
| 21 |
+
BackendPatternConfig,
|
| 22 |
+
DTypeConfig,
|
| 23 |
+
DTypeWithConstraints,
|
| 24 |
+
ObservationType,
|
| 25 |
+
)
|
| 26 |
+
from .qnnpack import (
|
| 27 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 28 |
+
qnnpack_weighted_op_qint8_symmetric_dtype_config,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
__all__ = [
|
| 33 |
+
"get_executorch_backend_config",
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# ===================
|
| 38 |
+
# | DTYPE CONFIGS |
|
| 39 |
+
# ===================
|
| 40 |
+
|
| 41 |
+
executorch_weighted_op_int8_dtype_config = DTypeConfig(
|
| 42 |
+
input_dtype=torch.quint8,
|
| 43 |
+
output_dtype=torch.quint8,
|
| 44 |
+
weight_dtype=torch.qint8,
|
| 45 |
+
bias_dtype=torch.float,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
executorch_default_op_quint8_dtype_config = DTypeConfig(
|
| 49 |
+
input_dtype=torch.quint8,
|
| 50 |
+
output_dtype=torch.quint8,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
executorch_default_dynamic_quint8_dtype_config = DTypeConfig(
|
| 54 |
+
input_dtype=torch.quint8,
|
| 55 |
+
output_dtype=torch.float,
|
| 56 |
+
weight_dtype=torch.qint8,
|
| 57 |
+
bias_dtype=torch.float,
|
| 58 |
+
is_dynamic=True,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
executorch_act_qint8_scale_min_2_neg_12 = DTypeWithConstraints(
|
| 62 |
+
dtype=torch.qint8,
|
| 63 |
+
scale_min_lower_bound=2**-12,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
executorch_weight_qint8_neg_127_to_127_scale_min_2_neg_12 = DTypeWithConstraints(
|
| 67 |
+
dtype=torch.qint8,
|
| 68 |
+
quant_min_lower_bound=-127,
|
| 69 |
+
quant_max_upper_bound=127,
|
| 70 |
+
scale_min_lower_bound=2**-12,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
executorch_default_dynamic_qint8_dtype_config = DTypeConfig(
|
| 74 |
+
input_dtype=executorch_act_qint8_scale_min_2_neg_12,
|
| 75 |
+
output_dtype=torch.float,
|
| 76 |
+
weight_dtype=executorch_weight_qint8_neg_127_to_127_scale_min_2_neg_12,
|
| 77 |
+
bias_dtype=torch.float,
|
| 78 |
+
is_dynamic=True,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
executorch_default_dynamic_float16_dtype_config = DTypeConfig(
|
| 82 |
+
input_dtype=torch.float16,
|
| 83 |
+
output_dtype=torch.float,
|
| 84 |
+
weight_dtype=torch.float16,
|
| 85 |
+
bias_dtype=torch.float,
|
| 86 |
+
is_dynamic=True,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
executorch_weight_only_quint8_dtype_config = DTypeConfig(
|
| 90 |
+
input_dtype=torch.float,
|
| 91 |
+
output_dtype=torch.float,
|
| 92 |
+
weight_dtype=torch.quint8,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# =============================
|
| 97 |
+
# | BACKEND PATTERN CONFIGS |
|
| 98 |
+
# =============================
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _get_linear_configs() -> List[BackendPatternConfig]:
|
| 102 |
+
"""
|
| 103 |
+
Return all configs related to linear modules and ops.
|
| 104 |
+
"""
|
| 105 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 106 |
+
dtype_configs = [
|
| 107 |
+
qnnpack_weighted_op_qint8_symmetric_dtype_config,
|
| 108 |
+
executorch_weighted_op_int8_dtype_config,
|
| 109 |
+
executorch_default_dynamic_quint8_dtype_config,
|
| 110 |
+
executorch_default_dynamic_qint8_dtype_config,
|
| 111 |
+
executorch_default_dynamic_float16_dtype_config,
|
| 112 |
+
]
|
| 113 |
+
linear_configs: List[BackendPatternConfig] = []
|
| 114 |
+
# linear module
|
| 115 |
+
linear_configs.append(
|
| 116 |
+
BackendPatternConfig(torch.nn.Linear)
|
| 117 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 118 |
+
.set_dtype_configs(dtype_configs)
|
| 119 |
+
.set_root_module(torch.nn.Linear)
|
| 120 |
+
.set_reference_quantized_module(nnqr.Linear)
|
| 121 |
+
.set_qat_module(nnqat.Linear)
|
| 122 |
+
)
|
| 123 |
+
# linear qat module
|
| 124 |
+
linear_configs.append(
|
| 125 |
+
BackendPatternConfig(nnqat.Linear)
|
| 126 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 127 |
+
.set_dtype_configs(dtype_configs)
|
| 128 |
+
.set_root_module(torch.nn.Linear)
|
| 129 |
+
.set_reference_quantized_module(nnqr.Linear)
|
| 130 |
+
)
|
| 131 |
+
# functional linear
|
| 132 |
+
linear_configs.append(
|
| 133 |
+
BackendPatternConfig(torch.nn.functional.linear)
|
| 134 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 135 |
+
.set_dtype_configs(dtype_configs)
|
| 136 |
+
._set_input_type_to_index({"weight": 1, "bias": 2})
|
| 137 |
+
)
|
| 138 |
+
return linear_configs
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _get_conv_configs() -> List[BackendPatternConfig]:
|
| 142 |
+
"""
|
| 143 |
+
Return all configs related to conv modules and ops.
|
| 144 |
+
"""
|
| 145 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 146 |
+
dtype_configs = [
|
| 147 |
+
qnnpack_weighted_op_qint8_symmetric_dtype_config,
|
| 148 |
+
executorch_weighted_op_int8_dtype_config,
|
| 149 |
+
]
|
| 150 |
+
conv_configs = []
|
| 151 |
+
for convs in [_Conv2dMetadata]:
|
| 152 |
+
# (1) Single conv modules/functions
|
| 153 |
+
# -----------------------------------
|
| 154 |
+
# conv module
|
| 155 |
+
conv_configs.append(
|
| 156 |
+
BackendPatternConfig(convs.root)
|
| 157 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 158 |
+
.set_dtype_configs(dtype_configs)
|
| 159 |
+
.set_root_module(convs.root)
|
| 160 |
+
.set_reference_quantized_module(convs.reference)
|
| 161 |
+
.set_qat_module(convs.qat)
|
| 162 |
+
)
|
| 163 |
+
# conv qat module
|
| 164 |
+
conv_configs.append(
|
| 165 |
+
BackendPatternConfig(convs.qat)
|
| 166 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 167 |
+
.set_dtype_configs(dtype_configs)
|
| 168 |
+
.set_root_module(convs.root)
|
| 169 |
+
.set_reference_quantized_module(convs.reference)
|
| 170 |
+
)
|
| 171 |
+
# functional conv
|
| 172 |
+
conv_configs.append(
|
| 173 |
+
BackendPatternConfig(convs.func)
|
| 174 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 175 |
+
.set_dtype_configs(dtype_configs)
|
| 176 |
+
._set_input_type_to_index({"weight": 1, "bias": 2})
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# (2) Conv + relu
|
| 180 |
+
# -----------------------------------
|
| 181 |
+
# conv module + relu module
|
| 182 |
+
conv_configs.append(
|
| 183 |
+
BackendPatternConfig((convs.root, nn.ReLU))
|
| 184 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 185 |
+
.set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu))
|
| 186 |
+
.set_fused_module(convs.fused_conv_relu)
|
| 187 |
+
)
|
| 188 |
+
# conv module + functional relu
|
| 189 |
+
conv_configs.append(
|
| 190 |
+
BackendPatternConfig((convs.root, F.relu))
|
| 191 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 192 |
+
.set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu))
|
| 193 |
+
.set_fused_module(convs.fused_conv_relu)
|
| 194 |
+
)
|
| 195 |
+
# fused conv relu module
|
| 196 |
+
conv_configs.append(
|
| 197 |
+
BackendPatternConfig(convs.fused_conv_relu)
|
| 198 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 199 |
+
.set_dtype_configs(dtype_configs)
|
| 200 |
+
.set_root_module(convs.root)
|
| 201 |
+
.set_reference_quantized_module(convs.reference)
|
| 202 |
+
.set_qat_module(convs.relu_qat)
|
| 203 |
+
)
|
| 204 |
+
# conv relu, qat fused module
|
| 205 |
+
conv_configs.append(
|
| 206 |
+
BackendPatternConfig(convs.relu_qat)
|
| 207 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 208 |
+
.set_dtype_configs(dtype_configs)
|
| 209 |
+
.set_root_module(convs.root)
|
| 210 |
+
.set_reference_quantized_module(convs.reference)
|
| 211 |
+
)
|
| 212 |
+
# functional conv + relu module
|
| 213 |
+
conv_configs.append(
|
| 214 |
+
BackendPatternConfig((convs.func, nn.ReLU))
|
| 215 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 216 |
+
.set_dtype_configs(dtype_configs)
|
| 217 |
+
)
|
| 218 |
+
# functional conv + functional relu
|
| 219 |
+
conv_configs.append(
|
| 220 |
+
BackendPatternConfig((convs.func, F.relu))
|
| 221 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 222 |
+
.set_dtype_configs(dtype_configs)
|
| 223 |
+
)
|
| 224 |
+
# fused conv relu
|
| 225 |
+
conv_configs.append(
|
| 226 |
+
BackendPatternConfig(convs.fused_conv_relu)
|
| 227 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 228 |
+
.set_qat_module(convs.relu_qat)
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
conv_configs.append(
|
| 232 |
+
BackendPatternConfig(convs.relu_qat)
|
| 233 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 234 |
+
.set_root_module(convs.root)
|
| 235 |
+
.set_reference_quantized_module(convs.reference)
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
# (3) Conv + batchnorm (+ relu)
|
| 239 |
+
# -------------------------------
|
| 240 |
+
# conv + batchnorm (+ relu)
|
| 241 |
+
conv_configs.append(
|
| 242 |
+
BackendPatternConfig((convs.root, convs.bn))
|
| 243 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 244 |
+
.set_fuser_method(fuse_conv_bn)
|
| 245 |
+
.set_fused_module(convs.fused_conv_bn)
|
| 246 |
+
)
|
| 247 |
+
# conv + bn + relu module fusion
|
| 248 |
+
conv_configs.append(
|
| 249 |
+
BackendPatternConfig((convs.root, convs.bn, nn.ReLU))
|
| 250 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 251 |
+
.set_fuser_method(fuse_conv_bn_relu)
|
| 252 |
+
.set_fused_module(convs.fused_conv_bn_relu)
|
| 253 |
+
)
|
| 254 |
+
# conv + bn + relu functional fusion
|
| 255 |
+
conv_configs.append(
|
| 256 |
+
BackendPatternConfig((convs.root, convs.bn, F.relu))
|
| 257 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 258 |
+
.set_root_module(convs.root)
|
| 259 |
+
.set_fuser_method(fuse_conv_bn_relu)
|
| 260 |
+
.set_fused_module(convs.fused_conv_bn_relu)
|
| 261 |
+
)
|
| 262 |
+
# TODO: we can add fusion for torch.relu as well
|
| 263 |
+
# 3.2 conv + bn (+ relu) fused module configs
|
| 264 |
+
# fused conv bn
|
| 265 |
+
conv_configs.append(
|
| 266 |
+
BackendPatternConfig(convs.fused_conv_bn)
|
| 267 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 268 |
+
.set_qat_module(convs.bn_qat)
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
# fused conv bn relu
|
| 272 |
+
conv_configs.append(
|
| 273 |
+
BackendPatternConfig(convs.fused_conv_bn_relu)
|
| 274 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 275 |
+
.set_qat_module(convs.bn_relu_qat)
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
# conv bn, qat fused module
|
| 279 |
+
conv_configs.append(
|
| 280 |
+
BackendPatternConfig(convs.bn_qat)
|
| 281 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 282 |
+
.set_dtype_configs(dtype_configs)
|
| 283 |
+
.set_root_module(convs.root)
|
| 284 |
+
.set_reference_quantized_module(convs.reference)
|
| 285 |
+
)
|
| 286 |
+
# conv bn relu, qat fused module
|
| 287 |
+
conv_configs.append(
|
| 288 |
+
BackendPatternConfig(convs.bn_relu_qat)
|
| 289 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 290 |
+
.set_dtype_configs(dtype_configs)
|
| 291 |
+
.set_root_module(convs.root)
|
| 292 |
+
.set_reference_quantized_module(convs.reference)
|
| 293 |
+
)
|
| 294 |
+
return conv_configs
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def _get_binary_ops_configs() -> List[BackendPatternConfig]:
|
| 298 |
+
"""
|
| 299 |
+
Return all configs related to binary ops.
|
| 300 |
+
"""
|
| 301 |
+
dtype_configs = [
|
| 302 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 303 |
+
executorch_weighted_op_int8_dtype_config,
|
| 304 |
+
]
|
| 305 |
+
num_tensor_args_to_observation_type_mapping = {
|
| 306 |
+
# TODO: this is not used right now since we have extra check in prepare
|
| 307 |
+
# will need to change this to NO_OBSERVER later after we implemented
|
| 308 |
+
# Tensor dtype inference properly
|
| 309 |
+
0: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
|
| 310 |
+
1: ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT,
|
| 311 |
+
2: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
|
| 312 |
+
}
|
| 313 |
+
binary_op_configs: List[BackendPatternConfig] = []
|
| 314 |
+
for op in [
|
| 315 |
+
operator.add,
|
| 316 |
+
torch.add,
|
| 317 |
+
operator.sub,
|
| 318 |
+
torch.sub,
|
| 319 |
+
operator.mul,
|
| 320 |
+
torch.mul,
|
| 321 |
+
]:
|
| 322 |
+
bop_patterns = [
|
| 323 |
+
(op, torch.nn.ReLU),
|
| 324 |
+
(op, torch.nn.functional.relu),
|
| 325 |
+
(op, torch.relu),
|
| 326 |
+
op,
|
| 327 |
+
]
|
| 328 |
+
for bop_pattern in bop_patterns:
|
| 329 |
+
binary_op_configs.append(
|
| 330 |
+
BackendPatternConfig(bop_pattern)
|
| 331 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 332 |
+
._set_num_tensor_args_to_observation_type(
|
| 333 |
+
num_tensor_args_to_observation_type_mapping
|
| 334 |
+
)
|
| 335 |
+
)
|
| 336 |
+
return binary_op_configs
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def _get_share_qparams_ops_configs() -> List[BackendPatternConfig]:
|
| 340 |
+
"""
|
| 341 |
+
Return the operator configs for the operators that works for both float and quantized
|
| 342 |
+
input if input is quantized, the output Tensor shares the same quantization parameter
|
| 343 |
+
with input.
|
| 344 |
+
|
| 345 |
+
Example operator: avgpool2d, reshape, transpose, maxpool2d
|
| 346 |
+
Example observed operator:
|
| 347 |
+
observer_0 - avgpool2d - observer_0 (same observer instance as input)
|
| 348 |
+
"""
|
| 349 |
+
observation_type = ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT
|
| 350 |
+
dtype_configs = [
|
| 351 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 352 |
+
executorch_default_op_quint8_dtype_config,
|
| 353 |
+
]
|
| 354 |
+
share_qparams_ops = [
|
| 355 |
+
torch.nn.Flatten,
|
| 356 |
+
F.adaptive_avg_pool2d,
|
| 357 |
+
F.elu,
|
| 358 |
+
F.hardtanh,
|
| 359 |
+
F.max_pool2d,
|
| 360 |
+
F.pad,
|
| 361 |
+
F.relu,
|
| 362 |
+
F.relu6,
|
| 363 |
+
F.leaky_relu,
|
| 364 |
+
F.leaky_relu_,
|
| 365 |
+
torch.nn.AdaptiveAvgPool2d,
|
| 366 |
+
torch.nn.ConstantPad2d,
|
| 367 |
+
torch.nn.ELU,
|
| 368 |
+
torch.nn.MaxPool2d,
|
| 369 |
+
torch.nn.ReLU6,
|
| 370 |
+
torch.nn.Hardtanh,
|
| 371 |
+
torch.nn.LeakyReLU,
|
| 372 |
+
torch.clamp,
|
| 373 |
+
torch.flatten,
|
| 374 |
+
torch.mean,
|
| 375 |
+
torch.permute,
|
| 376 |
+
torch.permute_copy,
|
| 377 |
+
torch.squeeze,
|
| 378 |
+
"clamp",
|
| 379 |
+
"mean",
|
| 380 |
+
"permute",
|
| 381 |
+
"reshape",
|
| 382 |
+
"relu",
|
| 383 |
+
"relu_",
|
| 384 |
+
"squeeze",
|
| 385 |
+
"squeeze_",
|
| 386 |
+
"leaky_relu",
|
| 387 |
+
]
|
| 388 |
+
share_qparams_op_configs: List[BackendPatternConfig] = []
|
| 389 |
+
for op in share_qparams_ops:
|
| 390 |
+
share_qparams_op_configs.append(
|
| 391 |
+
BackendPatternConfig(op)
|
| 392 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 393 |
+
.set_dtype_configs(dtype_configs)
|
| 394 |
+
)
|
| 395 |
+
return share_qparams_op_configs
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def _get_bn_configs() -> List[BackendPatternConfig]:
|
| 399 |
+
"""
|
| 400 |
+
Return all configs related to batchnorm.
|
| 401 |
+
"""
|
| 402 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 403 |
+
dtype_configs = [
|
| 404 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 405 |
+
executorch_default_op_quint8_dtype_config,
|
| 406 |
+
]
|
| 407 |
+
bn_configs = []
|
| 408 |
+
bn_configs.append(
|
| 409 |
+
BackendPatternConfig(nn.BatchNorm2d)
|
| 410 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 411 |
+
.set_dtype_configs(dtype_configs)
|
| 412 |
+
)
|
| 413 |
+
return bn_configs
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def _get_cat_configs() -> List[BackendPatternConfig]:
|
| 417 |
+
dtype_configs = [
|
| 418 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 419 |
+
executorch_default_op_quint8_dtype_config,
|
| 420 |
+
]
|
| 421 |
+
cat_configs = []
|
| 422 |
+
cat_configs.append(
|
| 423 |
+
BackendPatternConfig(torch.cat)
|
| 424 |
+
.set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT)
|
| 425 |
+
.set_dtype_configs(dtype_configs)
|
| 426 |
+
)
|
| 427 |
+
cat_configs.append(
|
| 428 |
+
BackendPatternConfig(torch.concat)
|
| 429 |
+
.set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT)
|
| 430 |
+
.set_dtype_configs(dtype_configs)
|
| 431 |
+
)
|
| 432 |
+
cat_configs.append(
|
| 433 |
+
BackendPatternConfig(torch.concatenate)
|
| 434 |
+
.set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT)
|
| 435 |
+
.set_dtype_configs(dtype_configs)
|
| 436 |
+
)
|
| 437 |
+
return cat_configs
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def _get_embedding_op_configs() -> List[BackendPatternConfig]:
|
| 441 |
+
dtype_configs = [
|
| 442 |
+
executorch_weight_only_quint8_dtype_config,
|
| 443 |
+
]
|
| 444 |
+
embedding_op_configs = []
|
| 445 |
+
for embedding_op, qat_embedding_op, ref_embedding_op in [
|
| 446 |
+
(nn.Embedding, nnqat.Embedding, nnqr.Embedding),
|
| 447 |
+
(nn.EmbeddingBag, nnqat.EmbeddingBag, nnqr.EmbeddingBag),
|
| 448 |
+
]:
|
| 449 |
+
embedding_op_configs.append(
|
| 450 |
+
BackendPatternConfig(embedding_op)
|
| 451 |
+
.set_observation_type(
|
| 452 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 453 |
+
) # noqa: E131
|
| 454 |
+
.set_dtype_configs(dtype_configs)
|
| 455 |
+
.set_qat_module(qat_embedding_op)
|
| 456 |
+
.set_root_module(embedding_op)
|
| 457 |
+
.set_reference_quantized_module(ref_embedding_op)
|
| 458 |
+
)
|
| 459 |
+
# config for qat op
|
| 460 |
+
embedding_op_configs.append(
|
| 461 |
+
BackendPatternConfig(qat_embedding_op)
|
| 462 |
+
.set_observation_type(
|
| 463 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 464 |
+
) # noqa: E131
|
| 465 |
+
.set_dtype_configs(dtype_configs)
|
| 466 |
+
.set_root_module(embedding_op)
|
| 467 |
+
.set_reference_quantized_module(ref_embedding_op)
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
# config for functional embedding
|
| 471 |
+
embedding_op_configs.append(
|
| 472 |
+
BackendPatternConfig(torch.nn.functional.embedding)
|
| 473 |
+
.set_observation_type(
|
| 474 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 475 |
+
) # noqa: E131
|
| 476 |
+
.set_dtype_configs(dtype_configs)
|
| 477 |
+
._set_input_type_to_index({"weight": 1})
|
| 478 |
+
)
|
| 479 |
+
return embedding_op_configs
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
# =====================
|
| 483 |
+
# | BACKEND CONFIGS |
|
| 484 |
+
# =====================
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def get_executorch_backend_config() -> BackendConfig:
|
| 488 |
+
"""
|
| 489 |
+
Return the `BackendConfig` for backends PyTorch lowers to through the Executorch stack.
|
| 490 |
+
"""
|
| 491 |
+
return (
|
| 492 |
+
BackendConfig("executorch")
|
| 493 |
+
.set_backend_pattern_configs(_get_linear_configs())
|
| 494 |
+
.set_backend_pattern_configs(_get_conv_configs())
|
| 495 |
+
.set_backend_pattern_configs(_get_binary_ops_configs())
|
| 496 |
+
.set_backend_pattern_configs(_get_share_qparams_ops_configs())
|
| 497 |
+
.set_backend_pattern_configs(_get_bn_configs())
|
| 498 |
+
.set_backend_pattern_configs(_get_cat_configs())
|
| 499 |
+
.set_backend_pattern_configs(_get_embedding_op_configs())
|
| 500 |
+
)
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/fbgemm.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
from ._common_operator_config_utils import (
|
| 4 |
+
_get_binary_op_configs,
|
| 5 |
+
_get_bn_configs,
|
| 6 |
+
_get_cat_config,
|
| 7 |
+
_get_conv_configs,
|
| 8 |
+
_get_default_op_configs,
|
| 9 |
+
_get_embedding_op_configs,
|
| 10 |
+
_get_fixed_qparams_op_configs,
|
| 11 |
+
_get_linear_configs,
|
| 12 |
+
_get_rnn_op_configs,
|
| 13 |
+
_get_share_qparams_op_configs,
|
| 14 |
+
_get_tensor_info_op_configs,
|
| 15 |
+
)
|
| 16 |
+
from .backend_config import BackendConfig, DTypeConfig
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
"get_fbgemm_backend_config",
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
# ===================
|
| 24 |
+
# | DTYPE CONFIGS |
|
| 25 |
+
# ===================
|
| 26 |
+
|
| 27 |
+
# TODO: For now, these DTypeConfigs are identical to the ones defined in native.py
|
| 28 |
+
# In the future, once we support specifying quant_min/quant_max and scale_min/scale_max,
|
| 29 |
+
# these will diverge. In particular, for FBGEMM, we will restrict the activation quantized
|
| 30 |
+
# values to within [0, 127].
|
| 31 |
+
|
| 32 |
+
fbgemm_weighted_op_quint8_dtype_config = DTypeConfig(
|
| 33 |
+
input_dtype=torch.quint8,
|
| 34 |
+
output_dtype=torch.quint8,
|
| 35 |
+
weight_dtype=torch.qint8,
|
| 36 |
+
bias_dtype=torch.float,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
fbgemm_default_op_quint8_dtype_config = DTypeConfig(
|
| 40 |
+
input_dtype=torch.quint8,
|
| 41 |
+
output_dtype=torch.quint8,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
fbgemm_default_op_fp16_dtype_config = DTypeConfig(
|
| 45 |
+
input_dtype=torch.float16,
|
| 46 |
+
output_dtype=torch.float16,
|
| 47 |
+
weight_dtype=torch.float16,
|
| 48 |
+
bias_dtype=torch.float16,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
fbgemm_default_dynamic_int8_dtype_config = DTypeConfig(
|
| 52 |
+
input_dtype=torch.quint8,
|
| 53 |
+
output_dtype=torch.float,
|
| 54 |
+
weight_dtype=torch.qint8,
|
| 55 |
+
bias_dtype=torch.float,
|
| 56 |
+
is_dynamic=True,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
fbgemm_default_dynamic_float16_dtype_config = DTypeConfig(
|
| 60 |
+
input_dtype=torch.float16,
|
| 61 |
+
output_dtype=torch.float,
|
| 62 |
+
weight_dtype=torch.float16,
|
| 63 |
+
bias_dtype=torch.float,
|
| 64 |
+
is_dynamic=True,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
fbgemm_weight_only_quint8_dtype_config = DTypeConfig(
|
| 68 |
+
input_dtype=torch.float,
|
| 69 |
+
output_dtype=torch.float,
|
| 70 |
+
weight_dtype=torch.quint8,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
fbgemm_weight_only_quint4x2_dtype_config = DTypeConfig(
|
| 74 |
+
input_dtype=torch.float,
|
| 75 |
+
output_dtype=torch.float,
|
| 76 |
+
weight_dtype=torch.quint4x2,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# =====================
|
| 81 |
+
# | BACKEND CONFIGS |
|
| 82 |
+
# =====================
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def get_fbgemm_backend_config() -> BackendConfig:
|
| 86 |
+
"""
|
| 87 |
+
Return the `BackendConfig` for PyTorch's native FBGEMM backend.
|
| 88 |
+
"""
|
| 89 |
+
conv_dtype_configs = [fbgemm_weighted_op_quint8_dtype_config]
|
| 90 |
+
linear_dtype_configs = [
|
| 91 |
+
fbgemm_weighted_op_quint8_dtype_config,
|
| 92 |
+
fbgemm_default_dynamic_int8_dtype_config,
|
| 93 |
+
fbgemm_default_dynamic_float16_dtype_config,
|
| 94 |
+
]
|
| 95 |
+
binary_op_dtype_configs = [fbgemm_default_op_quint8_dtype_config]
|
| 96 |
+
default_op_dtype_configs = [fbgemm_default_op_quint8_dtype_config]
|
| 97 |
+
fixed_qparams_op_dtype_configs = [fbgemm_default_op_quint8_dtype_config]
|
| 98 |
+
share_qparams_op_dtype_configs = [fbgemm_default_op_quint8_dtype_config]
|
| 99 |
+
tensor_info_op_dtype_configs = [fbgemm_default_op_quint8_dtype_config]
|
| 100 |
+
rnn_op_dtype_configs = [
|
| 101 |
+
fbgemm_default_dynamic_int8_dtype_config,
|
| 102 |
+
fbgemm_default_dynamic_float16_dtype_config,
|
| 103 |
+
]
|
| 104 |
+
embedding_op_dtype_configs = [
|
| 105 |
+
fbgemm_weight_only_quint8_dtype_config,
|
| 106 |
+
fbgemm_weight_only_quint4x2_dtype_config,
|
| 107 |
+
]
|
| 108 |
+
return (
|
| 109 |
+
BackendConfig("fbgemm")
|
| 110 |
+
.set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs))
|
| 111 |
+
.set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs))
|
| 112 |
+
.set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs))
|
| 113 |
+
.set_backend_pattern_config(_get_cat_config(default_op_dtype_configs))
|
| 114 |
+
.set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs))
|
| 115 |
+
.set_backend_pattern_configs(
|
| 116 |
+
_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)
|
| 117 |
+
)
|
| 118 |
+
.set_backend_pattern_configs(
|
| 119 |
+
_get_share_qparams_op_configs(share_qparams_op_dtype_configs)
|
| 120 |
+
)
|
| 121 |
+
.set_backend_pattern_configs(
|
| 122 |
+
_get_tensor_info_op_configs(tensor_info_op_dtype_configs)
|
| 123 |
+
)
|
| 124 |
+
.set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs))
|
| 125 |
+
.set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs))
|
| 126 |
+
.set_backend_pattern_configs(
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from ._common_operator_config_utils import (
|
| 5 |
+
_get_binary_op_configs,
|
| 6 |
+
_get_bn_configs,
|
| 7 |
+
_get_cat_config,
|
| 8 |
+
_get_conv_configs,
|
| 9 |
+
_get_default_op_configs,
|
| 10 |
+
_get_embedding_op_configs,
|
| 11 |
+
_get_fixed_qparams_op_configs,
|
| 12 |
+
_get_linear_configs,
|
| 13 |
+
_get_ln_configs,
|
| 14 |
+
_get_rnn_op_configs,
|
| 15 |
+
_get_share_qparams_op_configs,
|
| 16 |
+
_get_tensor_info_op_configs,
|
| 17 |
+
)
|
| 18 |
+
from .backend_config import BackendConfig, DTypeConfig
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
"get_test_only_legacy_native_backend_config",
|
| 23 |
+
"default_op_quint8_dtype_config",
|
| 24 |
+
"default_op_fp16_dtype_config",
|
| 25 |
+
"default_dynamic_int8_dtype_config",
|
| 26 |
+
"default_dynamic_float16_dtype_config",
|
| 27 |
+
"input_output_only_quint8_dtype_config",
|
| 28 |
+
"weight_only_quint8_dtype_config",
|
| 29 |
+
"weight_only_quint4x2_dtype_config",
|
| 30 |
+
"get_native_backend_config",
|
| 31 |
+
"get_native_backend_config_dict",
|
| 32 |
+
"get_test_only_legacy_native_backend_config_dict",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
# ===================
|
| 36 |
+
# | DTYPE CONFIGS |
|
| 37 |
+
# ===================
|
| 38 |
+
|
| 39 |
+
# weighted op int8 dtype config
|
| 40 |
+
# this is config for ops that has quantized weights, like linear, conv
|
| 41 |
+
weighted_op_quint8_dtype_config = DTypeConfig(
|
| 42 |
+
input_dtype=torch.quint8,
|
| 43 |
+
output_dtype=torch.quint8,
|
| 44 |
+
weight_dtype=torch.qint8,
|
| 45 |
+
bias_dtype=torch.float,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
default_op_quint8_dtype_config = DTypeConfig(
|
| 49 |
+
input_dtype=torch.quint8,
|
| 50 |
+
output_dtype=torch.quint8,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
default_op_fp16_dtype_config = DTypeConfig(
|
| 54 |
+
input_dtype=torch.float16,
|
| 55 |
+
output_dtype=torch.float16,
|
| 56 |
+
weight_dtype=torch.float16,
|
| 57 |
+
bias_dtype=torch.float16,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
default_dynamic_int8_dtype_config = DTypeConfig(
|
| 61 |
+
input_dtype=torch.quint8,
|
| 62 |
+
output_dtype=torch.float,
|
| 63 |
+
weight_dtype=torch.qint8,
|
| 64 |
+
bias_dtype=torch.float,
|
| 65 |
+
# currently the dtype check is not yet enabled, so we provided the dtype_configs but
|
| 66 |
+
# it is not really used yet,
|
| 67 |
+
# we will enable it a bit later after we moved everything to backend_config_dict
|
| 68 |
+
is_dynamic=True,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
default_dynamic_float16_dtype_config = DTypeConfig(
|
| 72 |
+
input_dtype=torch.float16,
|
| 73 |
+
output_dtype=torch.float,
|
| 74 |
+
weight_dtype=torch.float16,
|
| 75 |
+
bias_dtype=torch.float,
|
| 76 |
+
# currently the dtype check is not yet enabled, so we provided the dtype_configs but
|
| 77 |
+
# it is not really used yet,
|
| 78 |
+
# we will enable it a bit later after we moved everything to backend_config_dict
|
| 79 |
+
is_dynamic=True,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# Needed for LayerNorm and f.layer_norm, since currently the kernel only supports float weights
|
| 83 |
+
input_output_only_quint8_dtype_config = DTypeConfig(
|
| 84 |
+
input_dtype=torch.quint8,
|
| 85 |
+
output_dtype=torch.quint8,
|
| 86 |
+
weight_dtype=torch.float,
|
| 87 |
+
bias_dtype=torch.float,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
weight_only_quint8_dtype_config = DTypeConfig(
|
| 91 |
+
input_dtype=torch.float,
|
| 92 |
+
output_dtype=torch.float,
|
| 93 |
+
weight_dtype=torch.quint8,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
weight_only_quint4x2_dtype_config = DTypeConfig(
|
| 97 |
+
input_dtype=torch.float,
|
| 98 |
+
output_dtype=torch.float,
|
| 99 |
+
weight_dtype=torch.quint4x2,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# =====================
|
| 104 |
+
# | BACKEND CONFIGS |
|
| 105 |
+
# =====================
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def get_test_only_legacy_native_backend_config() -> BackendConfig:
|
| 109 |
+
"""
|
| 110 |
+
Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack) with various additional fp16 ops.
|
| 111 |
+
"""
|
| 112 |
+
conv_dtype_configs = [weighted_op_quint8_dtype_config]
|
| 113 |
+
linear_dtype_configs = [
|
| 114 |
+
weighted_op_quint8_dtype_config,
|
| 115 |
+
default_dynamic_int8_dtype_config,
|
| 116 |
+
default_dynamic_float16_dtype_config,
|
| 117 |
+
default_op_fp16_dtype_config,
|
| 118 |
+
]
|
| 119 |
+
binary_op_dtype_configs = [
|
| 120 |
+
default_op_quint8_dtype_config,
|
| 121 |
+
default_op_fp16_dtype_config,
|
| 122 |
+
]
|
| 123 |
+
default_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 124 |
+
fixed_qparams_op_dtype_configs = [
|
| 125 |
+
default_op_quint8_dtype_config,
|
| 126 |
+
default_op_fp16_dtype_config,
|
| 127 |
+
]
|
| 128 |
+
share_qparams_op_dtype_configs = [
|
| 129 |
+
default_op_quint8_dtype_config,
|
| 130 |
+
default_op_fp16_dtype_config,
|
| 131 |
+
]
|
| 132 |
+
tensor_info_op_dtype_configs = [
|
| 133 |
+
default_op_quint8_dtype_config,
|
| 134 |
+
]
|
| 135 |
+
rnn_op_dtype_configs = [
|
| 136 |
+
default_dynamic_int8_dtype_config,
|
| 137 |
+
default_dynamic_float16_dtype_config,
|
| 138 |
+
]
|
| 139 |
+
embedding_op_dtype_configs = [
|
| 140 |
+
weight_only_quint8_dtype_config,
|
| 141 |
+
weight_only_quint4x2_dtype_config,
|
| 142 |
+
]
|
| 143 |
+
layer_norm_op_dtype_configs = [input_output_only_quint8_dtype_config]
|
| 144 |
+
return (
|
| 145 |
+
BackendConfig("_native_and_fp16")
|
| 146 |
+
.set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs))
|
| 147 |
+
.set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs))
|
| 148 |
+
.set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs))
|
| 149 |
+
.set_backend_pattern_config(_get_cat_config(default_op_dtype_configs))
|
| 150 |
+
.set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs))
|
| 151 |
+
.set_backend_pattern_configs(
|
| 152 |
+
_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)
|
| 153 |
+
)
|
| 154 |
+
.set_backend_pattern_configs(
|
| 155 |
+
_get_share_qparams_op_configs(share_qparams_op_dtype_configs)
|
| 156 |
+
)
|
| 157 |
+
.set_backend_pattern_configs(
|
| 158 |
+
_get_tensor_info_op_configs(tensor_info_op_dtype_configs)
|
| 159 |
+
)
|
| 160 |
+
.set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs))
|
| 161 |
+
.set_backend_pattern_configs(_get_ln_configs(layer_norm_op_dtype_configs))
|
| 162 |
+
.set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs))
|
| 163 |
+
.set_backend_pattern_configs(
|
| 164 |
+
_get_embedding_op_configs(embedding_op_dtype_configs)
|
| 165 |
+
)
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def get_native_backend_config() -> BackendConfig:
|
| 170 |
+
"""
|
| 171 |
+
Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack).
|
| 172 |
+
"""
|
| 173 |
+
# TODO: express this BackendConfig as a union of the FBGEMM and QNNPACK BackendConfigs
|
| 174 |
+
conv_dtype_configs = [weighted_op_quint8_dtype_config]
|
| 175 |
+
linear_dtype_configs = [
|
| 176 |
+
weighted_op_quint8_dtype_config,
|
| 177 |
+
default_dynamic_int8_dtype_config,
|
| 178 |
+
default_dynamic_float16_dtype_config,
|
| 179 |
+
]
|
| 180 |
+
binary_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 181 |
+
default_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 182 |
+
fixed_qparams_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 183 |
+
share_qparams_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 184 |
+
tensor_info_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 185 |
+
rnn_op_dtype_configs = [
|
| 186 |
+
default_dynamic_int8_dtype_config,
|
| 187 |
+
default_dynamic_float16_dtype_config,
|
| 188 |
+
]
|
| 189 |
+
embedding_op_dtype_configs = [
|
| 190 |
+
weight_only_quint8_dtype_config,
|
| 191 |
+
weight_only_quint4x2_dtype_config,
|
| 192 |
+
]
|
| 193 |
+
layer_norm_op_dtype_configs = [input_output_only_quint8_dtype_config]
|
| 194 |
+
return (
|
| 195 |
+
BackendConfig("native")
|
| 196 |
+
.set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs))
|
| 197 |
+
.set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs))
|
| 198 |
+
.set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs))
|
| 199 |
+
.set_backend_pattern_config(_get_cat_config(default_op_dtype_configs))
|
| 200 |
+
.set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs))
|
| 201 |
+
.set_backend_pattern_configs(
|
| 202 |
+
_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)
|
| 203 |
+
)
|
| 204 |
+
.set_backend_pattern_configs(
|
| 205 |
+
_get_share_qparams_op_configs(share_qparams_op_dtype_configs)
|
| 206 |
+
)
|
| 207 |
+
.set_backend_pattern_configs(
|
| 208 |
+
_get_tensor_info_op_configs(tensor_info_op_dtype_configs)
|
| 209 |
+
)
|
| 210 |
+
.set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs))
|
| 211 |
+
.set_backend_pattern_configs(_get_ln_configs(layer_norm_op_dtype_configs))
|
| 212 |
+
.set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs))
|
| 213 |
+
.set_backend_pattern_configs(
|
| 214 |
+
_get_embedding_op_configs(embedding_op_dtype_configs)
|
| 215 |
+
)
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def get_native_backend_config_dict():
|
| 220 |
+
"""
|
| 221 |
+
Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack) in dictionary form.
|
| 222 |
+
"""
|
| 223 |
+
return get_native_backend_config().to_dict()
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def get_test_only_legacy_native_backend_config_dict():
|
| 227 |
+
"""
|
| 228 |
+
Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack) with various additional
|
| 229 |
+
fp16 ops in dictionary form.
|
| 230 |
+
"""
|
| 231 |
+
return get_test_only_legacy_native_backend_config().to_dict()
|
vllm/lib/python3.10/site-packages/torch/ao/quantization/backend_config/observation_type.py
ADDED
|
File without changes
|