Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/__init__.py +19 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/__init__.py +38 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/functional.py +644 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__init__.py +131 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/batchnorm.py +106 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/conv.py +945 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/dropout.py +27 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/embedding_ops.py +295 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/functional_modules.py +249 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/linear.py +303 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/normalization.py +199 -0
- llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/utils.py +117 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__init__.py +23 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/__init__.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/_common_operator_config_utils.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/backend_config.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/executorch.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/native.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/qnnpack.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/tensorrt.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/utils.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_common_operator_config_utils.py +637 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_qnnpack_pt2e.py +160 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/executorch.py +493 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/native.py +204 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/observation_type.py +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/onednn.py +542 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/qnnpack.py +160 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/tensorrt.py +81 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/utils.py +279 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/x86.py +113 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_decomposed.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_lower_to_native_backend.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/fuse_handler.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/lstm_utils.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/pattern_utils.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/prepare.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/qconfig_mapping_utils.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/tracer.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/utils.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/__init__.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/composable_quantizer.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/embedding_quantizer.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/quantizer.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/utils.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/x86_inductor_quantizer.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer.cpython-310.pyc +0 -0
- llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer_utils.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -1213,3 +1213,5 @@ vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/bilateral_cy.cpython-
|
|
| 1213 |
vlmpy310/lib/python3.10/site-packages/skimage/util/_remap.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1214 |
vlmpy310/lib/python3.10/site-packages/skimage/feature/_sift.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1215 |
vlmpy310/lib/python3.10/site-packages/skimage/feature/orb_cy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 1213 |
vlmpy310/lib/python3.10/site-packages/skimage/util/_remap.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1214 |
vlmpy310/lib/python3.10/site-packages/skimage/feature/_sift.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1215 |
vlmpy310/lib/python3.10/site-packages/skimage/feature/orb_cy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1216 |
+
vlmpy310/lib/python3.10/site-packages/skimage/filters/rank/percentile_cy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1217 |
+
vlmpy310/lib/python3.10/site-packages/OpenGL_accelerate/arraydatatype.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# We are exposing all subpackages to the end-user.
|
| 2 |
+
# Because of possible inter-dependency, we want to avoid
|
| 3 |
+
# the cyclic imports, thus implementing lazy version
|
| 4 |
+
# as per https://peps.python.org/pep-0562/
|
| 5 |
+
|
| 6 |
+
import importlib
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"intrinsic",
|
| 10 |
+
"qat",
|
| 11 |
+
"quantizable",
|
| 12 |
+
"quantized",
|
| 13 |
+
"sparse",
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
def __getattr__(name):
|
| 17 |
+
if name in __all__:
|
| 18 |
+
return importlib.import_module("." + name, __name__)
|
| 19 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import functional
|
| 2 |
+
from .modules import * # noqa: F403
|
| 3 |
+
from .modules import MaxPool2d
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
'BatchNorm2d',
|
| 7 |
+
'BatchNorm3d',
|
| 8 |
+
'Conv1d',
|
| 9 |
+
'Conv2d',
|
| 10 |
+
'Conv3d',
|
| 11 |
+
'ConvTranspose1d',
|
| 12 |
+
'ConvTranspose2d',
|
| 13 |
+
'ConvTranspose3d',
|
| 14 |
+
'DeQuantize',
|
| 15 |
+
'ELU',
|
| 16 |
+
'Embedding',
|
| 17 |
+
'EmbeddingBag',
|
| 18 |
+
'GroupNorm',
|
| 19 |
+
'Hardswish',
|
| 20 |
+
'InstanceNorm1d',
|
| 21 |
+
'InstanceNorm2d',
|
| 22 |
+
'InstanceNorm3d',
|
| 23 |
+
'LayerNorm',
|
| 24 |
+
'LeakyReLU',
|
| 25 |
+
'Linear',
|
| 26 |
+
'LSTM',
|
| 27 |
+
'MultiheadAttention',
|
| 28 |
+
'Quantize',
|
| 29 |
+
'ReLU6',
|
| 30 |
+
'Sigmoid',
|
| 31 |
+
'Softmax',
|
| 32 |
+
'Dropout',
|
| 33 |
+
'PReLU',
|
| 34 |
+
# Wrapper modules
|
| 35 |
+
'FloatFunctional',
|
| 36 |
+
'FXFloatFunctional',
|
| 37 |
+
'QFunctional',
|
| 38 |
+
]
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/functional.py
ADDED
|
@@ -0,0 +1,644 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r""" Functional interface (quantized)."""
|
| 2 |
+
from typing import List, Optional
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
from torch.nn.modules.utils import _pair, _triple
|
| 8 |
+
from torch.jit.annotations import BroadcastingList2
|
| 9 |
+
|
| 10 |
+
from .modules.utils import _pair_from_first
|
| 11 |
+
|
| 12 |
+
# Although some of the functions and docstrings are mirrored from the torch.nn,
|
| 13 |
+
# we want to have them here for future changes.
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
"avg_pool2d",
|
| 17 |
+
"avg_pool3d",
|
| 18 |
+
"adaptive_avg_pool2d",
|
| 19 |
+
"adaptive_avg_pool3d",
|
| 20 |
+
"conv1d",
|
| 21 |
+
"conv2d",
|
| 22 |
+
"conv3d",
|
| 23 |
+
"interpolate",
|
| 24 |
+
"linear",
|
| 25 |
+
"max_pool1d",
|
| 26 |
+
"max_pool2d",
|
| 27 |
+
"celu",
|
| 28 |
+
"leaky_relu",
|
| 29 |
+
"hardtanh",
|
| 30 |
+
"hardswish",
|
| 31 |
+
"threshold",
|
| 32 |
+
"elu",
|
| 33 |
+
"hardsigmoid",
|
| 34 |
+
"clamp",
|
| 35 |
+
"upsample",
|
| 36 |
+
"upsample_bilinear",
|
| 37 |
+
"upsample_nearest",
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
def avg_pool2d(input, kernel_size, stride=None, padding=0, ceil_mode=False,
|
| 41 |
+
count_include_pad=True, divisor_override=None):
|
| 42 |
+
r"""
|
| 43 |
+
Applies 2D average-pooling operation in :math:`kH \times kW` regions by step size
|
| 44 |
+
:math:`sH \times sW` steps. The number of output features is equal to the number of
|
| 45 |
+
input planes.
|
| 46 |
+
|
| 47 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 48 |
+
|
| 49 |
+
See :class:`~torch.ao.nn.quantized.AvgPool2d` for details and output shape.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
input: quantized input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
|
| 53 |
+
kernel_size: size of the pooling region. Can be a single number or a
|
| 54 |
+
tuple `(kH, kW)`
|
| 55 |
+
stride: stride of the pooling operation. Can be a single number or a
|
| 56 |
+
tuple `(sH, sW)`. Default: :attr:`kernel_size`
|
| 57 |
+
padding: implicit zero paddings on both sides of the input. Can be a
|
| 58 |
+
single number or a tuple `(padH, padW)`. Default: 0
|
| 59 |
+
ceil_mode: when True, will use `ceil` instead of `floor` in the formula
|
| 60 |
+
to compute the output shape. Default: ``False``
|
| 61 |
+
count_include_pad: when True, will include the zero-padding in the
|
| 62 |
+
averaging calculation. Default: ``True``
|
| 63 |
+
divisor_override: if specified, it will be used as divisor, otherwise
|
| 64 |
+
size of the pooling region will be used. Default: None
|
| 65 |
+
"""
|
| 66 |
+
if not input.is_quantized:
|
| 67 |
+
raise ValueError("Input to 'quantized.avg_pool2d' must be quantized!")
|
| 68 |
+
return torch.nn.functional.avg_pool2d(input, kernel_size, stride, padding,
|
| 69 |
+
ceil_mode, count_include_pad,
|
| 70 |
+
divisor_override)
|
| 71 |
+
|
| 72 |
+
def avg_pool3d(input, kernel_size, stride=None, padding=0, ceil_mode=False,
|
| 73 |
+
count_include_pad=True, divisor_override=None):
|
| 74 |
+
r"""
|
| 75 |
+
Applies 3D average-pooling operation in :math:`kD \ times kH \times kW` regions by step size
|
| 76 |
+
:math:`sD \times sH \times sW` steps. The number of output features is equal to the number of
|
| 77 |
+
input planes.
|
| 78 |
+
|
| 79 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
input: quantized input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
|
| 83 |
+
kernel_size: size of the pooling region. Can be a single number or a
|
| 84 |
+
tuple `(kD, kH, kW)`
|
| 85 |
+
stride: stride of the pooling operation. Can be a single number or a
|
| 86 |
+
tuple `(sD, sH, sW)`. Default: :attr:`kernel_size`
|
| 87 |
+
padding: implicit zero paddings on both sides of the input. Can be a
|
| 88 |
+
single number or a tuple `(padD, padH, padW)`. Default: 0
|
| 89 |
+
ceil_mode: when True, will use `ceil` instead of `floor` in the formula
|
| 90 |
+
to compute the output shape. Default: ``False``
|
| 91 |
+
count_include_pad: when True, will include the zero-padding in the
|
| 92 |
+
averaging calculation. Default: ``True``
|
| 93 |
+
divisor_override: if specified, it will be used as divisor, otherwise
|
| 94 |
+
size of the pooling region will be used. Default: None
|
| 95 |
+
"""
|
| 96 |
+
if not input.is_quantized:
|
| 97 |
+
raise ValueError("Input to 'quantized.avg_pool3d' must be quantized!")
|
| 98 |
+
return torch.nn.functional.avg_pool3d(input, kernel_size, stride, padding,
|
| 99 |
+
ceil_mode, count_include_pad,
|
| 100 |
+
divisor_override)
|
| 101 |
+
|
| 102 |
+
def adaptive_avg_pool2d(input: Tensor, output_size: BroadcastingList2[int]) -> Tensor:
|
| 103 |
+
r"""
|
| 104 |
+
Applies a 2D adaptive average pooling over a quantized input signal composed
|
| 105 |
+
of several quantized input planes.
|
| 106 |
+
|
| 107 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 108 |
+
|
| 109 |
+
See :class:`~torch.ao.nn.quantized.AdaptiveAvgPool2d` for details and output shape.
|
| 110 |
+
|
| 111 |
+
Args:
|
| 112 |
+
output_size: the target output size (single integer or
|
| 113 |
+
double-integer tuple)
|
| 114 |
+
"""
|
| 115 |
+
if not input.is_quantized:
|
| 116 |
+
raise ValueError("Input to 'quantized.functional.adaptive_avg_pool2d' must be quantized!")
|
| 117 |
+
return torch.nn.functional.adaptive_avg_pool2d(input, output_size)
|
| 118 |
+
|
| 119 |
+
def adaptive_avg_pool3d(input: Tensor, output_size: BroadcastingList2[int]) -> Tensor:
|
| 120 |
+
r"""
|
| 121 |
+
Applies a 3D adaptive average pooling over a quantized input signal composed
|
| 122 |
+
of several quantized input planes.
|
| 123 |
+
|
| 124 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 125 |
+
|
| 126 |
+
See :class:`~torch.ao.nn.quantized.AdaptiveAvgPool3d` for details and output shape.
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
output_size: the target output size (single integer or
|
| 130 |
+
double-integer tuple)
|
| 131 |
+
"""
|
| 132 |
+
if not input.is_quantized:
|
| 133 |
+
raise ValueError(
|
| 134 |
+
"Input to 'quantized.functional.adaptive_avg_pool3d' must be quantized!")
|
| 135 |
+
return torch.nn.functional.adaptive_avg_pool3d(input, output_size)
|
| 136 |
+
|
| 137 |
+
def conv1d(input, weight, bias,
|
| 138 |
+
stride=1, padding=0, dilation=1, groups=1,
|
| 139 |
+
padding_mode='zeros',
|
| 140 |
+
scale=1.0, zero_point=0,
|
| 141 |
+
dtype=torch.quint8):
|
| 142 |
+
r"""
|
| 143 |
+
Applies a 1D convolution over a quantized 1D input composed of several input
|
| 144 |
+
planes.
|
| 145 |
+
|
| 146 |
+
See :class:`~torch.ao.nn.quantized.Conv1d` for details and output shape.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
input: quantized input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`
|
| 150 |
+
weight: quantized filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , iW)`
|
| 151 |
+
bias: **non-quantized** bias tensor of shape :math:`(\text{out\_channels})`. The tensor type must be `torch.float`.
|
| 152 |
+
stride: the stride of the convolving kernel. Can be a single number or a
|
| 153 |
+
tuple `(sW,)`. Default: 1
|
| 154 |
+
padding: implicit paddings on both sides of the input. Can be a
|
| 155 |
+
single number or a tuple `(padW,)`. Default: 0
|
| 156 |
+
dilation: the spacing between kernel elements. Can be a single number or
|
| 157 |
+
a tuple `(dW,)`. Default: 1
|
| 158 |
+
groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
|
| 159 |
+
number of groups. Default: 1
|
| 160 |
+
padding_mode: the padding mode to use. Only "zeros" is supported for quantized convolution at the moment. Default: "zeros"
|
| 161 |
+
scale: quantization scale for the output. Default: 1.0
|
| 162 |
+
zero_point: quantization zero_point for the output. Default: 0
|
| 163 |
+
dtype: quantization data type to use. Default: ``torch.quint8``
|
| 164 |
+
|
| 165 |
+
Examples::
|
| 166 |
+
|
| 167 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 168 |
+
>>> from torch.ao.nn.quantized import functional as qF
|
| 169 |
+
>>> filters = torch.randn(33, 16, 3, dtype=torch.float)
|
| 170 |
+
>>> inputs = torch.randn(20, 16, 50, dtype=torch.float)
|
| 171 |
+
>>> bias = torch.randn(33, dtype=torch.float)
|
| 172 |
+
>>>
|
| 173 |
+
>>> scale, zero_point = 1.0, 0
|
| 174 |
+
>>> dtype_inputs = torch.quint8
|
| 175 |
+
>>> dtype_filters = torch.qint8
|
| 176 |
+
>>>
|
| 177 |
+
>>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters)
|
| 178 |
+
>>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs)
|
| 179 |
+
>>> qF.conv1d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point)
|
| 180 |
+
""" # noqa: E501
|
| 181 |
+
if padding_mode != 'zeros':
|
| 182 |
+
raise NotImplementedError("Only zero-padding is supported!")
|
| 183 |
+
if input.dtype != torch.quint8:
|
| 184 |
+
raise NotImplementedError("Only torch.quint8 is supported for activation tensor!")
|
| 185 |
+
if weight.dtype != torch.qint8:
|
| 186 |
+
raise NotImplementedError("Only torch.qint8 is supported for weight tensor!")
|
| 187 |
+
if input.ndim != 3:
|
| 188 |
+
raise ValueError("Input shape must be `(N, C, L)`!")
|
| 189 |
+
stride = _pair_from_first(stride)
|
| 190 |
+
padding = _pair_from_first(padding)
|
| 191 |
+
dilation = _pair_from_first(dilation)
|
| 192 |
+
|
| 193 |
+
packed_params = torch.ops.quantized.conv1d_prepack(
|
| 194 |
+
weight, bias, stride, padding, dilation, groups)
|
| 195 |
+
return torch.ops.quantized.conv1d(input, packed_params, scale, zero_point)
|
| 196 |
+
|
| 197 |
+
def conv2d(input, weight, bias,
|
| 198 |
+
stride=1, padding=0, dilation=1, groups=1,
|
| 199 |
+
padding_mode='zeros',
|
| 200 |
+
scale=1.0, zero_point=0,
|
| 201 |
+
dtype=torch.quint8):
|
| 202 |
+
r"""
|
| 203 |
+
Applies a 2D convolution over a quantized 2D input composed of several input
|
| 204 |
+
planes.
|
| 205 |
+
|
| 206 |
+
See :class:`~torch.ao.nn.quantized.Conv2d` for details and output shape.
|
| 207 |
+
|
| 208 |
+
Args:
|
| 209 |
+
input: quantized input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
|
| 210 |
+
weight: quantized filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kH , kW)`
|
| 211 |
+
bias: **non-quantized** bias tensor of shape :math:`(\text{out\_channels})`. The tensor type must be `torch.float`.
|
| 212 |
+
stride: the stride of the convolving kernel. Can be a single number or a
|
| 213 |
+
tuple `(sH, sW)`. Default: 1
|
| 214 |
+
padding: implicit paddings on both sides of the input. Can be a
|
| 215 |
+
single number or a tuple `(padH, padW)`. Default: 0
|
| 216 |
+
dilation: the spacing between kernel elements. Can be a single number or
|
| 217 |
+
a tuple `(dH, dW)`. Default: 1
|
| 218 |
+
groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
|
| 219 |
+
number of groups. Default: 1
|
| 220 |
+
padding_mode: the padding mode to use. Only "zeros" is supported for quantized convolution at the moment. Default: "zeros"
|
| 221 |
+
scale: quantization scale for the output. Default: 1.0
|
| 222 |
+
zero_point: quantization zero_point for the output. Default: 0
|
| 223 |
+
dtype: quantization data type to use. Default: ``torch.quint8``
|
| 224 |
+
|
| 225 |
+
Examples::
|
| 226 |
+
|
| 227 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 228 |
+
>>> from torch.ao.nn.quantized import functional as qF
|
| 229 |
+
>>> filters = torch.randn(8, 4, 3, 3, dtype=torch.float)
|
| 230 |
+
>>> inputs = torch.randn(1, 4, 5, 5, dtype=torch.float)
|
| 231 |
+
>>> bias = torch.randn(8, dtype=torch.float)
|
| 232 |
+
>>>
|
| 233 |
+
>>> scale, zero_point = 1.0, 0
|
| 234 |
+
>>> dtype_inputs = torch.quint8
|
| 235 |
+
>>> dtype_filters = torch.qint8
|
| 236 |
+
>>>
|
| 237 |
+
>>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters)
|
| 238 |
+
>>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs)
|
| 239 |
+
>>> qF.conv2d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point)
|
| 240 |
+
""" # noqa: E501
|
| 241 |
+
if padding_mode != 'zeros':
|
| 242 |
+
raise NotImplementedError("Only zero-padding is supported!")
|
| 243 |
+
if input.dtype != torch.quint8:
|
| 244 |
+
raise NotImplementedError("Only torch.quint8 is supported for activation tensor!")
|
| 245 |
+
if weight.dtype != torch.qint8:
|
| 246 |
+
raise NotImplementedError("Only torch.qint8 is supported for weight tensor!")
|
| 247 |
+
if input.ndim != 4:
|
| 248 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 249 |
+
stride = _pair(stride)
|
| 250 |
+
padding = _pair(padding)
|
| 251 |
+
dilation = _pair(dilation)
|
| 252 |
+
|
| 253 |
+
packed_params = torch.ops.quantized.conv2d_prepack(
|
| 254 |
+
weight, bias, stride, padding, dilation, groups)
|
| 255 |
+
return torch.ops.quantized.conv2d(input, packed_params, scale, zero_point)
|
| 256 |
+
|
| 257 |
+
def conv3d(input, weight, bias, stride=1, padding=0, dilation=1, groups=1,
|
| 258 |
+
padding_mode='zeros', scale=1.0, zero_point=0, dtype=torch.quint8):
|
| 259 |
+
r"""
|
| 260 |
+
Applies a 3D convolution over a quantized 3D input composed of several input
|
| 261 |
+
planes.
|
| 262 |
+
|
| 263 |
+
See :class:`~torch.ao.nn.quantized.Conv3d` for details and output shape.
|
| 264 |
+
|
| 265 |
+
Args:
|
| 266 |
+
input: quantized input tensor of shape
|
| 267 |
+
:math:`(\text{minibatch} , \text{in\_channels} , iD , iH , iW)`
|
| 268 |
+
weight: quantized filters of shape
|
| 269 |
+
:math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kD , kH , kW)`
|
| 270 |
+
bias: **non-quantized** bias tensor of shape
|
| 271 |
+
:math:`(\text{out\_channels})`. The tensor type must be `torch.float`.
|
| 272 |
+
stride: the stride of the convolving kernel. Can be a single number or a
|
| 273 |
+
tuple `(sD, sH, sW)`. Default: 1
|
| 274 |
+
padding: implicit paddings on both sides of the input. Can be a
|
| 275 |
+
single number or a tuple `(padD, padH, padW)`. Default: 0
|
| 276 |
+
dilation: the spacing between kernel elements. Can be a single number or
|
| 277 |
+
a tuple `(dD, dH, dW)`. Default: 1
|
| 278 |
+
groups: split input into groups, :math:`\text{in\_channels}` should be
|
| 279 |
+
divisible by the number of groups. Default: 1
|
| 280 |
+
padding_mode: the padding mode to use. Only "zeros" is supported for
|
| 281 |
+
quantized convolution at the moment. Default: "zeros"
|
| 282 |
+
scale: quantization scale for the output. Default: 1.0
|
| 283 |
+
zero_point: quantization zero_point for the output. Default: 0
|
| 284 |
+
dtype: quantization data type to use. Default: ``torch.quint8``
|
| 285 |
+
|
| 286 |
+
Examples::
|
| 287 |
+
|
| 288 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 289 |
+
>>> from torch.ao.nn.quantized import functional as qF
|
| 290 |
+
>>> filters = torch.randn(8, 4, 3, 3, 3, dtype=torch.float)
|
| 291 |
+
>>> inputs = torch.randn(1, 4, 5, 5, 5, dtype=torch.float)
|
| 292 |
+
>>> bias = torch.randn(8, dtype=torch.float)
|
| 293 |
+
>>>
|
| 294 |
+
>>> scale, zero_point = 1.0, 0
|
| 295 |
+
>>> dtype_inputs = torch.quint8
|
| 296 |
+
>>> dtype_filters = torch.qint8
|
| 297 |
+
>>>
|
| 298 |
+
>>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype_filters)
|
| 299 |
+
>>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype_inputs)
|
| 300 |
+
>>> qF.conv3d(q_inputs, q_filters, bias, padding=1, scale=scale, zero_point=zero_point)
|
| 301 |
+
""" # noqa: E501
|
| 302 |
+
if padding_mode != 'zeros':
|
| 303 |
+
raise NotImplementedError("Only zero-padding is supported!")
|
| 304 |
+
if input.dtype != torch.quint8:
|
| 305 |
+
raise NotImplementedError("Only torch.quint8 is supported for activation tensor!")
|
| 306 |
+
if weight.dtype != torch.qint8:
|
| 307 |
+
raise NotImplementedError("Only torch.qint8 is supported for weight tensor!")
|
| 308 |
+
if input.ndim != 5:
|
| 309 |
+
raise ValueError("Input shape must be `(N, C, D, H, W)`!")
|
| 310 |
+
stride = _triple(stride)
|
| 311 |
+
padding = _triple(padding)
|
| 312 |
+
dilation = _triple(dilation)
|
| 313 |
+
|
| 314 |
+
packed_params = torch.ops.quantized.conv3d_prepack(
|
| 315 |
+
weight, bias, stride, padding, dilation, groups)
|
| 316 |
+
return torch.ops.quantized.conv3d(input, packed_params, scale, zero_point)
|
| 317 |
+
|
| 318 |
+
def interpolate(input, size=None, scale_factor=None, mode='nearest', align_corners=None):
|
| 319 |
+
r"""Down/up samples the input to either the given :attr:`size` or the given
|
| 320 |
+
:attr:`scale_factor`
|
| 321 |
+
|
| 322 |
+
See :func:`torch.nn.functional.interpolate` for implementation details.
|
| 323 |
+
|
| 324 |
+
The input dimensions are interpreted in the form:
|
| 325 |
+
`mini-batch x channels x [optional depth] x [optional height] x width`.
|
| 326 |
+
|
| 327 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 328 |
+
|
| 329 |
+
.. note:: Only 2D/3D input is supported for quantized inputs
|
| 330 |
+
|
| 331 |
+
.. note:: Only the following modes are supported for the quantized inputs:
|
| 332 |
+
|
| 333 |
+
- `bilinear`
|
| 334 |
+
- `nearest`
|
| 335 |
+
|
| 336 |
+
Args:
|
| 337 |
+
input (Tensor): the input tensor
|
| 338 |
+
size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]):
|
| 339 |
+
output spatial size.
|
| 340 |
+
scale_factor (float or Tuple[float]): multiplier for spatial size. Has to match input size if it is a tuple.
|
| 341 |
+
mode (str): algorithm used for upsampling:
|
| 342 |
+
``'nearest'`` | ``'bilinear'``
|
| 343 |
+
align_corners (bool, optional): Geometrically, we consider the pixels of the
|
| 344 |
+
input and output as squares rather than points.
|
| 345 |
+
If set to ``True``, the input and output tensors are aligned by the
|
| 346 |
+
center points of their corner pixels, preserving the values at the corner pixels.
|
| 347 |
+
If set to ``False``, the input and output tensors are aligned by the corner
|
| 348 |
+
points of their corner pixels, and the interpolation uses edge value padding
|
| 349 |
+
for out-of-boundary values, making this operation *independent* of input size
|
| 350 |
+
when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode`
|
| 351 |
+
is ``'bilinear'``.
|
| 352 |
+
Default: ``False``
|
| 353 |
+
"""
|
| 354 |
+
if not input.is_quantized:
|
| 355 |
+
raise ValueError("Input to 'quantized.interpolate' must be quantized!")
|
| 356 |
+
return torch.nn.functional.interpolate(input, size, scale_factor, mode,
|
| 357 |
+
align_corners)
|
| 358 |
+
|
| 359 |
+
def linear(
|
| 360 |
+
input: Tensor, weight: Tensor, bias: Optional[Tensor] = None,
|
| 361 |
+
scale: Optional[float] = None, zero_point: Optional[int] = None
|
| 362 |
+
) -> Tensor:
|
| 363 |
+
r"""
|
| 364 |
+
Applies a linear transformation to the incoming quantized data:
|
| 365 |
+
:math:`y = xA^T + b`.
|
| 366 |
+
See :class:`~torch.ao.nn.quantized.Linear`
|
| 367 |
+
|
| 368 |
+
.. note::
|
| 369 |
+
|
| 370 |
+
Current implementation packs weights on every call, which has penalty on performance.
|
| 371 |
+
If you want to avoid the overhead, use :class:`~torch.ao.nn.quantized.Linear`.
|
| 372 |
+
|
| 373 |
+
Args:
|
| 374 |
+
input (Tensor): Quantized input of type `torch.quint8`
|
| 375 |
+
weight (Tensor): Quantized weight of type `torch.qint8`
|
| 376 |
+
bias (Tensor): None or fp32 bias of type `torch.float`
|
| 377 |
+
scale (double): output scale. If None, derived from the input scale
|
| 378 |
+
zero_point (long): output zero point. If None, derived from the input zero_point
|
| 379 |
+
|
| 380 |
+
Shape:
|
| 381 |
+
- Input: :math:`(N, *, in\_features)` where `*` means any number of
|
| 382 |
+
additional dimensions
|
| 383 |
+
- Weight: :math:`(out\_features, in\_features)`
|
| 384 |
+
- Bias: :math:`(out\_features)`
|
| 385 |
+
- Output: :math:`(N, *, out\_features)`
|
| 386 |
+
"""
|
| 387 |
+
if scale is None:
|
| 388 |
+
scale = input.q_scale()
|
| 389 |
+
if zero_point is None:
|
| 390 |
+
zero_point = input.q_zero_point()
|
| 391 |
+
_packed_params = torch.ops.quantized.linear_prepack(weight, bias)
|
| 392 |
+
return torch.ops.quantized.linear(input, _packed_params, scale, zero_point)
|
| 393 |
+
|
| 394 |
+
def max_pool1d(input, kernel_size, stride=None, padding=0, dilation=1,
|
| 395 |
+
ceil_mode=False, return_indices=False):
|
| 396 |
+
r"""Applies a 1D max pooling over a quantized input signal composed of
|
| 397 |
+
several quantized input planes.
|
| 398 |
+
|
| 399 |
+
.. note:: The input quantization parameters are propagated to the output.
|
| 400 |
+
|
| 401 |
+
See :class:`~torch.ao.nn.quantized.MaxPool1d` for details.
|
| 402 |
+
"""
|
| 403 |
+
if return_indices:
|
| 404 |
+
raise NotImplementedError("return_indices is not yet implemented!")
|
| 405 |
+
if stride is None:
|
| 406 |
+
stride = torch.jit.annotate(List[int], [])
|
| 407 |
+
return torch.nn.functional.max_pool1d(input, kernel_size, stride, padding,
|
| 408 |
+
dilation, ceil_mode=ceil_mode, return_indices=return_indices)
|
| 409 |
+
|
| 410 |
+
def max_pool2d(input, kernel_size, stride=None, padding=0, dilation=1,
|
| 411 |
+
ceil_mode=False, return_indices=False):
|
| 412 |
+
r"""Applies a 2D max pooling over a quantized input signal composed of
|
| 413 |
+
several quantized input planes.
|
| 414 |
+
|
| 415 |
+
.. note:: The input quantization parameters are propagated to the output.
|
| 416 |
+
|
| 417 |
+
See :class:`~torch.ao.nn.quantized.MaxPool2d` for details.
|
| 418 |
+
"""
|
| 419 |
+
if return_indices:
|
| 420 |
+
raise NotImplementedError("return_indices is not yet implemented!")
|
| 421 |
+
if stride is None:
|
| 422 |
+
stride = torch.jit.annotate(List[int], [])
|
| 423 |
+
return torch.nn.functional.max_pool2d(input, kernel_size, stride, padding,
|
| 424 |
+
dilation, ceil_mode=ceil_mode, return_indices=return_indices)
|
| 425 |
+
|
| 426 |
+
def celu(input: Tensor, scale: float, zero_point: int, alpha: float = 1.) -> Tensor:
|
| 427 |
+
r"""celu(input, scale, zero_point, alpha=1.) -> Tensor
|
| 428 |
+
|
| 429 |
+
Applies the quantized CELU function element-wise.
|
| 430 |
+
|
| 431 |
+
.. math::
|
| 432 |
+
\text{CELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x / \alpha) - 1))
|
| 433 |
+
|
| 434 |
+
Args:
|
| 435 |
+
input: quantized input
|
| 436 |
+
alpha: the :math:`\alpha` value for the CELU formulation. Default: 1.0
|
| 437 |
+
"""
|
| 438 |
+
if not input.is_quantized:
|
| 439 |
+
raise ValueError("Input to 'quantized.celu' must be quantized!")
|
| 440 |
+
return torch.ops.quantized.celu(input, scale, zero_point, alpha)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def leaky_relu(input: Tensor, negative_slope: float = 0.01, inplace: bool = False,
|
| 444 |
+
scale: Optional[float] = None, zero_point: Optional[int] = None):
|
| 445 |
+
r"""
|
| 446 |
+
Quantized version of the.
|
| 447 |
+
leaky_relu(input, negative_slope=0.01, inplace=False, scale, zero_point) -> Tensor
|
| 448 |
+
|
| 449 |
+
Applies element-wise,
|
| 450 |
+
:math:`\text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x)`
|
| 451 |
+
|
| 452 |
+
Args:
|
| 453 |
+
input: Quantized input
|
| 454 |
+
negative_slope: The slope of the negative input
|
| 455 |
+
inplace: Inplace modification of the input tensor
|
| 456 |
+
scale, zero_point: Scale and zero point of the output tensor.
|
| 457 |
+
|
| 458 |
+
See :class:`~torch.nn.LeakyReLU` for more details.
|
| 459 |
+
"""
|
| 460 |
+
if scale is not None and zero_point is not None:
|
| 461 |
+
assert not inplace, "Cannot rescale with `inplace`"
|
| 462 |
+
output = torch._empty_affine_quantized(
|
| 463 |
+
input.shape, scale=scale, zero_point=int(zero_point), dtype=input.dtype)
|
| 464 |
+
torch._C._nn.leaky_relu(input, negative_slope, out=output)
|
| 465 |
+
return output
|
| 466 |
+
if inplace:
|
| 467 |
+
result = torch._C._nn.leaky_relu_(input, negative_slope)
|
| 468 |
+
else:
|
| 469 |
+
result = torch._C._nn.leaky_relu(input, negative_slope)
|
| 470 |
+
return result
|
| 471 |
+
|
| 472 |
+
def hardtanh(input: Tensor, min_val: float = -1., max_val: float = 1., inplace: bool = False) -> Tensor:
|
| 473 |
+
r"""This is the quantized version of :func:`~torch.nn.functional.hardtanh`.
|
| 474 |
+
"""
|
| 475 |
+
if not input.is_quantized:
|
| 476 |
+
raise ValueError("Input to 'quantized.hardtanh' must be quantized!")
|
| 477 |
+
if inplace:
|
| 478 |
+
return torch._C._nn.hardtanh_(input, min_val, max_val)
|
| 479 |
+
return torch._C._nn.hardtanh(input, min_val, max_val)
|
| 480 |
+
|
| 481 |
+
def hardswish(input: Tensor, scale: float, zero_point: int) -> Tensor:
|
| 482 |
+
r"""This is the quantized version of :func:`~torch.nn.functional.hardswish`.
|
| 483 |
+
|
| 484 |
+
Args:
|
| 485 |
+
input: quantized input
|
| 486 |
+
scale: quantization scale of the output tensor
|
| 487 |
+
zero_point: quantization zero point of the output tensor
|
| 488 |
+
"""
|
| 489 |
+
if not input.is_quantized:
|
| 490 |
+
raise ValueError("Input to 'quantized.hardswish' must be quantized!")
|
| 491 |
+
return torch._ops.ops.quantized.hardswish(input, scale, zero_point)
|
| 492 |
+
|
| 493 |
+
def threshold(input: Tensor, threshold: float, value: float) -> Tensor:
|
| 494 |
+
r"""Applies the quantized version of the threshold function element-wise:
|
| 495 |
+
|
| 496 |
+
.. math::
|
| 497 |
+
x = \begin{cases}
|
| 498 |
+
x & \text{if~} x > \text{threshold} \\
|
| 499 |
+
\text{value} & \text{otherwise}
|
| 500 |
+
\end{cases}
|
| 501 |
+
|
| 502 |
+
See :class:`~torch.nn.Threshold` for more details.
|
| 503 |
+
"""
|
| 504 |
+
if not input.is_quantized:
|
| 505 |
+
raise ValueError("Input to 'quantized.threshold' must be quantized!")
|
| 506 |
+
if threshold is None:
|
| 507 |
+
raise ValueError("Input to 'threshold' must be specified!")
|
| 508 |
+
if value is None:
|
| 509 |
+
raise ValueError("Input to 'value' must be specified!")
|
| 510 |
+
return torch._ops.ops.quantized.threshold(input, threshold, value)
|
| 511 |
+
|
| 512 |
+
def elu(input: Tensor, scale: float, zero_point: int, alpha: float = 1.) -> Tensor:
|
| 513 |
+
r"""This is the quantized version of :func:`~torch.nn.functional.elu`.
|
| 514 |
+
|
| 515 |
+
Args:
|
| 516 |
+
input: quantized input
|
| 517 |
+
scale: quantization scale of the output tensor
|
| 518 |
+
zero_point: quantization zero point of the output tensor
|
| 519 |
+
alpha: the alpha constant
|
| 520 |
+
"""
|
| 521 |
+
if not input.is_quantized:
|
| 522 |
+
raise ValueError("Input to 'quantized.elu' must be quantized!")
|
| 523 |
+
return torch.ops.quantized.elu(input, scale, zero_point, alpha)
|
| 524 |
+
|
| 525 |
+
def hardsigmoid(input: Tensor, inplace: bool = False) -> Tensor:
|
| 526 |
+
r"""This is the quantized version of :func:`~torch.nn.functional.hardsigmoid`.
|
| 527 |
+
"""
|
| 528 |
+
if not input.is_quantized:
|
| 529 |
+
raise ValueError("Input to 'quantized.hardsigmoid' must be quantized!")
|
| 530 |
+
if inplace:
|
| 531 |
+
return torch._C._nn.hardsigmoid_(input) # type: ignore[attr-defined]
|
| 532 |
+
return torch._C._nn.hardsigmoid(input)
|
| 533 |
+
|
| 534 |
+
def clamp(input: Tensor, min_: float, max_: float) -> Tensor:
|
| 535 |
+
r"""float(input, min\_, max\_) -> Tensor
|
| 536 |
+
|
| 537 |
+
Applies the clamp function element-wise.
|
| 538 |
+
See :class:`~torch.ao.nn.quantized.clamp` for more details.
|
| 539 |
+
|
| 540 |
+
Args:
|
| 541 |
+
input: quantized input
|
| 542 |
+
min_: minimum value for clamping
|
| 543 |
+
max_: maximum value for clamping
|
| 544 |
+
"""
|
| 545 |
+
if not input.is_quantized:
|
| 546 |
+
raise ValueError("Input to 'quantized.clamp' must be quantized!")
|
| 547 |
+
return torch.clamp(input, min_, max_)
|
| 548 |
+
|
| 549 |
+
def upsample(input, size=None, scale_factor=None, mode='nearest', align_corners=None):
|
| 550 |
+
r"""Upsamples the input to either the given :attr:`size` or the given
|
| 551 |
+
:attr:`scale_factor`
|
| 552 |
+
|
| 553 |
+
.. warning::
|
| 554 |
+
This function is deprecated in favor of
|
| 555 |
+
:func:`torch.ao.nn.quantized.functional.interpolate`.
|
| 556 |
+
This is equivalent with ``nn.quantized.functional.interpolate(...)``.
|
| 557 |
+
|
| 558 |
+
See :func:`torch.nn.functional.interpolate` for implementation details.
|
| 559 |
+
|
| 560 |
+
The input dimensions are interpreted in the form:
|
| 561 |
+
`mini-batch x channels x [optional depth] x [optional height] x width`.
|
| 562 |
+
|
| 563 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 564 |
+
|
| 565 |
+
.. note:: Only 2D input is supported for quantized inputs
|
| 566 |
+
|
| 567 |
+
.. note:: Only the following modes are supported for the quantized inputs:
|
| 568 |
+
|
| 569 |
+
- `bilinear`
|
| 570 |
+
- `nearest`
|
| 571 |
+
|
| 572 |
+
Args:
|
| 573 |
+
input (Tensor): quantized input tensor
|
| 574 |
+
size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]):
|
| 575 |
+
output spatial size.
|
| 576 |
+
scale_factor (float or Tuple[float]): multiplier for spatial size. Has to be an integer.
|
| 577 |
+
mode (str): algorithm used for upsampling:
|
| 578 |
+
``'nearest'`` | ``'bilinear'``
|
| 579 |
+
align_corners (bool, optional): Geometrically, we consider the pixels of the
|
| 580 |
+
input and output as squares rather than points.
|
| 581 |
+
If set to ``True``, the input and output tensors are aligned by the
|
| 582 |
+
center points of their corner pixels, preserving the values at the corner pixels.
|
| 583 |
+
If set to ``False``, the input and output tensors are aligned by the corner
|
| 584 |
+
points of their corner pixels, and the interpolation uses edge value padding
|
| 585 |
+
for out-of-boundary values, making this operation *independent* of input size
|
| 586 |
+
when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode`
|
| 587 |
+
is ``'bilinear'``.
|
| 588 |
+
Default: ``False``
|
| 589 |
+
|
| 590 |
+
.. warning::
|
| 591 |
+
With ``align_corners = True``, the linearly interpolating modes
|
| 592 |
+
(`bilinear`) don't proportionally align the
|
| 593 |
+
output and input pixels, and thus the output values can depend on the
|
| 594 |
+
input size. This was the default behavior for these modes up to version
|
| 595 |
+
0.3.1. Since then, the default behavior is ``align_corners = False``.
|
| 596 |
+
See :class:`~torch.nn.Upsample` for concrete examples on how this
|
| 597 |
+
affects the outputs.
|
| 598 |
+
"""
|
| 599 |
+
warnings.warn("nn.quantized.functional.upsample is deprecated. Use nn.quantized.functional.interpolate instead.")
|
| 600 |
+
return interpolate(input, size, scale_factor, mode, align_corners)
|
| 601 |
+
|
| 602 |
+
def upsample_bilinear(input, size=None, scale_factor=None):
|
| 603 |
+
r"""Upsamples the input, using bilinear upsampling.
|
| 604 |
+
|
| 605 |
+
.. warning::
|
| 606 |
+
This function is deprecated in favor of
|
| 607 |
+
:func:`torch.ao.nn.quantized.functional.interpolate`.
|
| 608 |
+
This is equivalent with
|
| 609 |
+
``nn.quantized.functional.interpolate(..., mode='bilinear', align_corners=True)``.
|
| 610 |
+
|
| 611 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 612 |
+
|
| 613 |
+
.. note:: Only 2D inputs are supported
|
| 614 |
+
|
| 615 |
+
Args:
|
| 616 |
+
input (Tensor): quantized input
|
| 617 |
+
size (int or Tuple[int, int]): output spatial size.
|
| 618 |
+
scale_factor (int or Tuple[int, int]): multiplier for spatial size
|
| 619 |
+
"""
|
| 620 |
+
# DeprecationWarning is ignored by default
|
| 621 |
+
warnings.warn("nn.quantized.functional.upsample_bilinear is deprecated. Use nn.quantized.functional.interpolate instead.")
|
| 622 |
+
return interpolate(input, size, scale_factor, mode='bilinear', align_corners=True)
|
| 623 |
+
|
| 624 |
+
def upsample_nearest(input, size=None, scale_factor=None):
|
| 625 |
+
r"""Upsamples the input, using nearest neighbours' pixel values.
|
| 626 |
+
|
| 627 |
+
.. warning::
|
| 628 |
+
This function is deprecated in favor of
|
| 629 |
+
:func:`torch.ao.nn.quantized.functional.interpolate`.
|
| 630 |
+
This is equivalent with ``nn.quantized.functional.interpolate(..., mode='nearest')``.
|
| 631 |
+
|
| 632 |
+
.. note:: The input quantization parameters propagate to the output.
|
| 633 |
+
|
| 634 |
+
.. note:: Only 2D inputs are supported
|
| 635 |
+
|
| 636 |
+
Args:
|
| 637 |
+
input (Tensor): quantized input
|
| 638 |
+
size (int or Tuple[int, int] or Tuple[int, int, int]): output spatial
|
| 639 |
+
size.
|
| 640 |
+
scale_factor (int): multiplier for spatial size. Has to be an integer.
|
| 641 |
+
"""
|
| 642 |
+
# DeprecationWarning is ignored by default
|
| 643 |
+
warnings.warn("nn.quantized.functional.upsample_nearest is deprecated. Use nn.quantized.functional.interpolate instead.")
|
| 644 |
+
return interpolate(input, size, scale_factor, mode='nearest')
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__init__.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
# The quantized modules use `torch.nn` and `torch.ao.nn.quantizable`
|
| 4 |
+
# packages. However, the `quantizable` package uses "lazy imports"
|
| 5 |
+
# to avoid circular dependency.
|
| 6 |
+
# Hence we need to include it here to make sure it is resolved before
|
| 7 |
+
# they are used in the modules.
|
| 8 |
+
import torch.ao.nn.quantizable
|
| 9 |
+
|
| 10 |
+
from torch.nn.modules.pooling import MaxPool2d
|
| 11 |
+
|
| 12 |
+
from .activation import ReLU6, Hardswish, ELU, LeakyReLU, Sigmoid, Softmax, MultiheadAttention, PReLU
|
| 13 |
+
from .dropout import Dropout
|
| 14 |
+
from .batchnorm import BatchNorm2d, BatchNorm3d
|
| 15 |
+
from .normalization import LayerNorm, GroupNorm, InstanceNorm1d, \
|
| 16 |
+
InstanceNorm2d, InstanceNorm3d
|
| 17 |
+
from .conv import Conv1d, Conv2d, Conv3d
|
| 18 |
+
from .conv import ConvTranspose1d, ConvTranspose2d, ConvTranspose3d
|
| 19 |
+
from .linear import Linear
|
| 20 |
+
from .embedding_ops import Embedding, EmbeddingBag
|
| 21 |
+
from .rnn import LSTM
|
| 22 |
+
|
| 23 |
+
from .functional_modules import FloatFunctional, FXFloatFunctional, QFunctional
|
| 24 |
+
|
| 25 |
+
__all__ = [
|
| 26 |
+
'BatchNorm2d',
|
| 27 |
+
'BatchNorm3d',
|
| 28 |
+
'Conv1d',
|
| 29 |
+
'Conv2d',
|
| 30 |
+
'Conv3d',
|
| 31 |
+
'ConvTranspose1d',
|
| 32 |
+
'ConvTranspose2d',
|
| 33 |
+
'ConvTranspose3d',
|
| 34 |
+
'DeQuantize',
|
| 35 |
+
'ELU',
|
| 36 |
+
'Embedding',
|
| 37 |
+
'EmbeddingBag',
|
| 38 |
+
'GroupNorm',
|
| 39 |
+
'Hardswish',
|
| 40 |
+
'InstanceNorm1d',
|
| 41 |
+
'InstanceNorm2d',
|
| 42 |
+
'InstanceNorm3d',
|
| 43 |
+
'LayerNorm',
|
| 44 |
+
'LeakyReLU',
|
| 45 |
+
'Linear',
|
| 46 |
+
'LSTM',
|
| 47 |
+
'MultiheadAttention',
|
| 48 |
+
'Quantize',
|
| 49 |
+
'ReLU6',
|
| 50 |
+
'Sigmoid',
|
| 51 |
+
'Softmax',
|
| 52 |
+
'Dropout',
|
| 53 |
+
'PReLU',
|
| 54 |
+
# Wrapper modules
|
| 55 |
+
'FloatFunctional',
|
| 56 |
+
'FXFloatFunctional',
|
| 57 |
+
'QFunctional',
|
| 58 |
+
]
|
| 59 |
+
|
| 60 |
+
class Quantize(torch.nn.Module):
|
| 61 |
+
r"""Quantizes an incoming tensor
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
`scale`: scale of the output Quantized Tensor
|
| 65 |
+
`zero_point`: zero_point of output Quantized Tensor
|
| 66 |
+
`dtype`: data type of output Quantized Tensor
|
| 67 |
+
`factory_kwargs`: Dictionary of kwargs used for configuring initialization
|
| 68 |
+
of internal buffers. Currently, `device` and `dtype` are supported.
|
| 69 |
+
Example: `factory_kwargs={'device': 'cuda', 'dtype': torch.float64}`
|
| 70 |
+
will initialize internal buffers as type `torch.float64` on the current CUDA device.
|
| 71 |
+
Note that `dtype` only applies to floating-point buffers.
|
| 72 |
+
|
| 73 |
+
Examples::
|
| 74 |
+
>>> t = torch.tensor([[1., -1.], [1., -1.]])
|
| 75 |
+
>>> scale, zero_point, dtype = 1.0, 2, torch.qint8
|
| 76 |
+
>>> qm = Quantize(scale, zero_point, dtype)
|
| 77 |
+
>>> # xdoctest: +SKIP
|
| 78 |
+
>>> qt = qm(t)
|
| 79 |
+
>>> print(qt)
|
| 80 |
+
tensor([[ 1., -1.],
|
| 81 |
+
[ 1., -1.]], size=(2, 2), dtype=torch.qint8, scale=1.0, zero_point=2)
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
scale: torch.Tensor
|
| 85 |
+
zero_point: torch.Tensor
|
| 86 |
+
|
| 87 |
+
def __init__(self, scale, zero_point, dtype, factory_kwargs=None):
|
| 88 |
+
factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
|
| 89 |
+
super().__init__()
|
| 90 |
+
self.register_buffer('scale', torch.tensor([scale], **factory_kwargs))
|
| 91 |
+
self.register_buffer('zero_point',
|
| 92 |
+
torch.tensor([zero_point], dtype=torch.long,
|
| 93 |
+
**{k: v for k, v in factory_kwargs.items() if k != 'dtype'}))
|
| 94 |
+
self.dtype = dtype
|
| 95 |
+
|
| 96 |
+
def forward(self, X):
|
| 97 |
+
return torch.quantize_per_tensor(X, float(self.scale),
|
| 98 |
+
int(self.zero_point), self.dtype)
|
| 99 |
+
|
| 100 |
+
@staticmethod
|
| 101 |
+
def from_float(mod):
|
| 102 |
+
assert hasattr(mod, 'activation_post_process')
|
| 103 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 104 |
+
return Quantize(scale.float().item(), zero_point.long().item(), mod.activation_post_process.dtype)
|
| 105 |
+
|
| 106 |
+
def extra_repr(self):
|
| 107 |
+
return f'scale={self.scale}, zero_point={self.zero_point}, dtype={self.dtype}'
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class DeQuantize(torch.nn.Module):
|
| 111 |
+
r"""Dequantizes an incoming tensor
|
| 112 |
+
|
| 113 |
+
Examples::
|
| 114 |
+
>>> input = torch.tensor([[1., -1.], [1., -1.]])
|
| 115 |
+
>>> scale, zero_point, dtype = 1.0, 2, torch.qint8
|
| 116 |
+
>>> qm = Quantize(scale, zero_point, dtype)
|
| 117 |
+
>>> # xdoctest: +SKIP
|
| 118 |
+
>>> quantized_input = qm(input)
|
| 119 |
+
>>> dqm = DeQuantize()
|
| 120 |
+
>>> dequantized = dqm(quantized_input)
|
| 121 |
+
>>> print(dequantized)
|
| 122 |
+
tensor([[ 1., -1.],
|
| 123 |
+
[ 1., -1.]], dtype=torch.float32)
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
def forward(self, Xq):
|
| 127 |
+
return Xq.dequantize()
|
| 128 |
+
|
| 129 |
+
@staticmethod
|
| 130 |
+
def from_float(mod):
|
| 131 |
+
return DeQuantize()
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-310.pyc
ADDED
|
Binary file (11.1 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/batchnorm.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.ao.nn.intrinsic as nni
|
| 3 |
+
|
| 4 |
+
__all__ = [
|
| 5 |
+
"BatchNorm2d",
|
| 6 |
+
"BatchNorm3d"
|
| 7 |
+
]
|
| 8 |
+
|
| 9 |
+
class _BatchNorm(torch.nn.modules.batchnorm._BatchNorm):
|
| 10 |
+
def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None) -> None:
|
| 11 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 12 |
+
super().__init__(num_features, eps, momentum, True, True, **factory_kwargs)
|
| 13 |
+
self.register_buffer('scale', torch.tensor(1.0, **factory_kwargs))
|
| 14 |
+
self.register_buffer('zero_point', torch.tensor(0, **factory_kwargs))
|
| 15 |
+
|
| 16 |
+
@staticmethod
|
| 17 |
+
def from_float(cls, mod):
|
| 18 |
+
activation_post_process = mod.activation_post_process
|
| 19 |
+
if type(mod) == cls._NNI_BN_RELU_MODULE:
|
| 20 |
+
mod = mod[0]
|
| 21 |
+
scale, zero_point = activation_post_process.calculate_qparams()
|
| 22 |
+
new_mod = cls(mod.num_features, mod.eps)
|
| 23 |
+
new_mod.weight = mod.weight
|
| 24 |
+
new_mod.bias = mod.bias
|
| 25 |
+
new_mod.running_mean = mod.running_mean
|
| 26 |
+
new_mod.running_var = mod.running_var
|
| 27 |
+
new_mod.scale = scale
|
| 28 |
+
new_mod.zero_point = zero_point
|
| 29 |
+
return new_mod
|
| 30 |
+
|
| 31 |
+
@classmethod
|
| 32 |
+
def from_reference(cls, bn, output_scale, output_zero_point):
|
| 33 |
+
qbn = cls(
|
| 34 |
+
bn.num_features,
|
| 35 |
+
bn.eps,
|
| 36 |
+
bn.momentum,
|
| 37 |
+
device=bn.weight.device,
|
| 38 |
+
dtype=bn.weight.dtype
|
| 39 |
+
)
|
| 40 |
+
qbn.weight = bn.weight
|
| 41 |
+
qbn.bias = bn.bias
|
| 42 |
+
qbn.running_mean = bn.running_mean
|
| 43 |
+
qbn.running_var = bn.running_var
|
| 44 |
+
qbn.scale = output_scale
|
| 45 |
+
qbn.zero_point = output_zero_point
|
| 46 |
+
return qbn
|
| 47 |
+
|
| 48 |
+
class BatchNorm2d(_BatchNorm):
|
| 49 |
+
r"""This is the quantized version of :class:`~torch.nn.BatchNorm2d`.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
_NNI_BN_RELU_MODULE = nni.BNReLU2d
|
| 53 |
+
|
| 54 |
+
def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None) -> None:
|
| 55 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 56 |
+
super().__init__(num_features, eps, momentum, **factory_kwargs)
|
| 57 |
+
|
| 58 |
+
def _get_name(self):
|
| 59 |
+
return 'QuantizedBatchNorm2d'
|
| 60 |
+
|
| 61 |
+
def _check_input_dim(self, input):
|
| 62 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 63 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 64 |
+
if len(input.shape) != 4:
|
| 65 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 66 |
+
|
| 67 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 68 |
+
# disabling this since this is not symbolically traceable
|
| 69 |
+
# self._check_input_dim(input)
|
| 70 |
+
return torch.ops.quantized.batch_norm2d(
|
| 71 |
+
input, self.weight, self.bias, self.running_mean,
|
| 72 |
+
self.running_var, self.eps, self.scale, self.zero_point)
|
| 73 |
+
|
| 74 |
+
@classmethod
|
| 75 |
+
def from_float(cls, mod):
|
| 76 |
+
return _BatchNorm.from_float(cls, mod)
|
| 77 |
+
|
| 78 |
+
class BatchNorm3d(_BatchNorm):
|
| 79 |
+
r"""This is the quantized version of :class:`~torch.nn.BatchNorm3d`.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
_NNI_BN_RELU_MODULE = nni.BNReLU3d
|
| 83 |
+
|
| 84 |
+
def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None):
|
| 85 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 86 |
+
super().__init__(num_features, eps, momentum, **factory_kwargs)
|
| 87 |
+
|
| 88 |
+
def _get_name(self):
|
| 89 |
+
return 'QuantizedBatchNorm3d'
|
| 90 |
+
|
| 91 |
+
def _check_input_dim(self, input):
|
| 92 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 93 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 94 |
+
if len(input.shape) != 5:
|
| 95 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 96 |
+
|
| 97 |
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
|
| 98 |
+
# disabling this since this is not symbolically traceable
|
| 99 |
+
# self._check_input_dim(input)
|
| 100 |
+
return torch.ops.quantized.batch_norm3d(
|
| 101 |
+
input, self.weight, self.bias, self.running_mean,
|
| 102 |
+
self.running_var, self.eps, self.scale, self.zero_point)
|
| 103 |
+
|
| 104 |
+
@classmethod
|
| 105 |
+
def from_float(cls, mod):
|
| 106 |
+
return _BatchNorm.from_float(cls, mod)
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/conv.py
ADDED
|
@@ -0,0 +1,945 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""Quantized convolution modules."""
|
| 2 |
+
|
| 3 |
+
from typing import Optional, List, TypeVar
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
import torch.ao.nn.intrinsic as nni
|
| 9 |
+
import torch.ao.nn.intrinsic.qat as nniqat
|
| 10 |
+
|
| 11 |
+
from torch._ops import ops
|
| 12 |
+
from torch.nn.common_types import _size_1_t
|
| 13 |
+
from torch.nn.modules.utils import _single, _pair, _triple
|
| 14 |
+
from torch.nn.utils import fuse_conv_bn_weights
|
| 15 |
+
|
| 16 |
+
from .utils import _quantize_weight, WeightedQuantizedModule
|
| 17 |
+
|
| 18 |
+
__all__ = ['Conv1d', 'Conv2d', 'Conv3d', 'ConvTranspose1d', 'ConvTranspose2d', 'ConvTranspose3d']
|
| 19 |
+
|
| 20 |
+
_SUPPORTED_PADDING = {
|
| 21 |
+
'zeros',
|
| 22 |
+
'reflect'
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _reverse_repeat_padding(padding: List[int]) -> List[int]:
|
| 27 |
+
_reversed_padding_repeated_twice: List[int] = []
|
| 28 |
+
N = len(padding)
|
| 29 |
+
for idx in range(N):
|
| 30 |
+
for _ in range(2):
|
| 31 |
+
_reversed_padding_repeated_twice.append(padding[N - idx - 1])
|
| 32 |
+
return _reversed_padding_repeated_twice
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class _ConvNd(WeightedQuantizedModule):
|
| 36 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
| 37 |
+
padding=0, dilation=1, groups=1, bias=True,
|
| 38 |
+
padding_mode='zeros', device=None, dtype=None):
|
| 39 |
+
# All subclasses have this signature - See PR #49702s
|
| 40 |
+
raise NotImplementedError
|
| 41 |
+
|
| 42 |
+
def _init(self, in_channels, out_channels, kernel_size, stride,
|
| 43 |
+
padding, dilation,
|
| 44 |
+
transposed, output_padding,
|
| 45 |
+
groups, bias,
|
| 46 |
+
padding_mode='zeros',
|
| 47 |
+
device=None,
|
| 48 |
+
dtype=None) -> None:
|
| 49 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 50 |
+
super().__init__()
|
| 51 |
+
|
| 52 |
+
if in_channels % groups != 0:
|
| 53 |
+
raise ValueError('in_channels must be divisible by groups')
|
| 54 |
+
if out_channels % groups != 0:
|
| 55 |
+
raise ValueError('out_channels must be divisible by groups')
|
| 56 |
+
self.in_channels = in_channels
|
| 57 |
+
self.out_channels = out_channels
|
| 58 |
+
self.kernel_size = kernel_size
|
| 59 |
+
self.stride = stride
|
| 60 |
+
self.padding = padding
|
| 61 |
+
self.dilation = dilation
|
| 62 |
+
self.transposed = transposed
|
| 63 |
+
self.output_padding = output_padding
|
| 64 |
+
self.groups = groups
|
| 65 |
+
if padding_mode not in _SUPPORTED_PADDING:
|
| 66 |
+
raise ValueError(f"'padding_mode' {padding_mode} is not supported by quantized convolution")
|
| 67 |
+
self.padding_mode = padding_mode
|
| 68 |
+
# Initialize as NCHW. set_weight will internally transpose to NHWC.
|
| 69 |
+
if self.transposed:
|
| 70 |
+
weight_shape = [in_channels, out_channels // self.groups]
|
| 71 |
+
else:
|
| 72 |
+
weight_shape = [out_channels, in_channels // self.groups]
|
| 73 |
+
qweight = torch._empty_affine_quantized(
|
| 74 |
+
weight_shape + list(kernel_size),
|
| 75 |
+
scale=1, zero_point=0, dtype=torch.qint8,
|
| 76 |
+
**{k: v for k, v in factory_kwargs.items() if k != 'dtype'})
|
| 77 |
+
bias_float = (
|
| 78 |
+
torch.zeros(out_channels, dtype=torch.float,
|
| 79 |
+
**{k: v for k, v in factory_kwargs.items() if k != 'dtype'}) if bias else None)
|
| 80 |
+
|
| 81 |
+
self.set_weight_bias(qweight, bias_float)
|
| 82 |
+
self.scale = 1.0
|
| 83 |
+
self.zero_point = 0
|
| 84 |
+
|
| 85 |
+
def set_weight_bias(self, qweight, bias_float):
|
| 86 |
+
raise NotImplementedError
|
| 87 |
+
|
| 88 |
+
def bias(self):
|
| 89 |
+
raise NotImplementedError
|
| 90 |
+
|
| 91 |
+
def _weight_bias(self):
|
| 92 |
+
raise NotImplementedError
|
| 93 |
+
|
| 94 |
+
def extra_repr(self):
|
| 95 |
+
s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}'
|
| 96 |
+
', stride={stride}, scale={scale}, zero_point={zero_point}')
|
| 97 |
+
if self.padding != (0,) * len(self.padding):
|
| 98 |
+
s += ', padding={padding}'
|
| 99 |
+
if self.dilation != (1,) * len(self.dilation):
|
| 100 |
+
s += ', dilation={dilation}'
|
| 101 |
+
if self.output_padding != (0,) * len(self.output_padding):
|
| 102 |
+
s += ', output_padding={output_padding}'
|
| 103 |
+
if self.groups != 1:
|
| 104 |
+
s += ', groups={groups}'
|
| 105 |
+
if self.bias() is None:
|
| 106 |
+
s += ', bias=False'
|
| 107 |
+
return s.format(**self.__dict__)
|
| 108 |
+
|
| 109 |
+
# ===== Serialization methods =====
|
| 110 |
+
# The special consideration here is that we have to unpack the weights into
|
| 111 |
+
# their regular QTensor form for serialization. Packed weights should not
|
| 112 |
+
# live outside the process in which they were created, rather they should be
|
| 113 |
+
# derived from the QTensor weight.
|
| 114 |
+
# self
|
| 115 |
+
# |--- weight : Tensor
|
| 116 |
+
# |--- bias : Tensor
|
| 117 |
+
#
|
| 118 |
+
# TODO: maybe change to this when https://github.com/pytorch/pytorch/pull/32958 is landed
|
| 119 |
+
# self
|
| 120 |
+
# |--- _packed_params : Conv2dPackedParamsBase or Conv3dPackedParamsBase
|
| 121 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
| 122 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
| 123 |
+
(w, b) = self._weight_bias()
|
| 124 |
+
destination[prefix + 'weight'] = w
|
| 125 |
+
destination[prefix + 'bias'] = b
|
| 126 |
+
destination[prefix + 'scale'] = torch.tensor(self.scale)
|
| 127 |
+
destination[prefix + 'zero_point'] = torch.tensor(self.zero_point)
|
| 128 |
+
|
| 129 |
+
@torch.jit.export
|
| 130 |
+
def __getstate__(self):
|
| 131 |
+
(w, b) = self._weight_bias()
|
| 132 |
+
return (
|
| 133 |
+
self.in_channels,
|
| 134 |
+
self.out_channels,
|
| 135 |
+
self.kernel_size,
|
| 136 |
+
self.stride,
|
| 137 |
+
self.padding,
|
| 138 |
+
self.dilation,
|
| 139 |
+
self.transposed,
|
| 140 |
+
self.output_padding,
|
| 141 |
+
self.groups,
|
| 142 |
+
self.padding_mode,
|
| 143 |
+
w,
|
| 144 |
+
b,
|
| 145 |
+
self.scale,
|
| 146 |
+
self.zero_point,
|
| 147 |
+
self.training
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# ===== Deserialization methods =====
|
| 151 |
+
# Counterpart to the serialization methods, we must pack the serialized
|
| 152 |
+
# QTensor weight into its packed format for use by the FBGEMM ops.
|
| 153 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
|
| 154 |
+
missing_keys, unexpected_keys, error_msgs):
|
| 155 |
+
self.set_weight_bias(
|
| 156 |
+
state_dict[prefix + 'weight'], state_dict[prefix + 'bias'])
|
| 157 |
+
state_dict.pop(prefix + 'weight')
|
| 158 |
+
state_dict.pop(prefix + 'bias')
|
| 159 |
+
self.scale = float(state_dict[prefix + 'scale'])
|
| 160 |
+
state_dict.pop(prefix + 'scale')
|
| 161 |
+
self.zero_point = int(state_dict[prefix + 'zero_point'])
|
| 162 |
+
state_dict.pop(prefix + 'zero_point')
|
| 163 |
+
super()._load_from_state_dict(
|
| 164 |
+
state_dict, prefix, local_metadata, False, missing_keys,
|
| 165 |
+
unexpected_keys, error_msgs)
|
| 166 |
+
|
| 167 |
+
@torch.jit.export
|
| 168 |
+
def __setstate__(self, state):
|
| 169 |
+
self.in_channels = state[0]
|
| 170 |
+
self.out_channels = state[1]
|
| 171 |
+
self.kernel_size = state[2]
|
| 172 |
+
self.stride = state[3]
|
| 173 |
+
self.padding = state[4]
|
| 174 |
+
self.dilation = state[5]
|
| 175 |
+
self.transposed = state[6]
|
| 176 |
+
self.output_padding = state[7]
|
| 177 |
+
self.groups = state[8]
|
| 178 |
+
self.padding_mode = state[9]
|
| 179 |
+
self.set_weight_bias(state[10], state[11])
|
| 180 |
+
self.scale = state[12]
|
| 181 |
+
self.zero_point = state[13]
|
| 182 |
+
self.training = state[14]
|
| 183 |
+
|
| 184 |
+
def __deepcopy__(self, memo):
|
| 185 |
+
new_instance = type(self).__new__(type(self))
|
| 186 |
+
torch.nn.Module.__init__(new_instance)
|
| 187 |
+
state = self.__getstate__()
|
| 188 |
+
new_instance.__setstate__(state)
|
| 189 |
+
return new_instance
|
| 190 |
+
|
| 191 |
+
def __copy__(self):
|
| 192 |
+
return self.__deepcopy__({})
|
| 193 |
+
|
| 194 |
+
@classmethod
|
| 195 |
+
def get_qconv(cls, mod, activation_post_process, weight_post_process=None):
|
| 196 |
+
r"""Creates a qconv object and returns it.
|
| 197 |
+
"""
|
| 198 |
+
if weight_post_process is None:
|
| 199 |
+
weight_post_process = mod.qconfig.weight()
|
| 200 |
+
weight_post_process(mod.weight)
|
| 201 |
+
assert weight_post_process.dtype == torch.qint8, \
|
| 202 |
+
'Weight observer must have a dtype of qint8'
|
| 203 |
+
qweight = _quantize_weight(mod.weight.float(), weight_post_process)
|
| 204 |
+
# the __init__ call used is the one from derived classes and not the one from _ConvNd
|
| 205 |
+
qconv = cls(mod.in_channels, mod.out_channels, mod.kernel_size,
|
| 206 |
+
mod.stride, mod.padding, mod.dilation, mod.groups,
|
| 207 |
+
mod.bias is not None, mod.padding_mode)
|
| 208 |
+
qconv.set_weight_bias(qweight, mod.bias)
|
| 209 |
+
if activation_post_process is None or activation_post_process.dtype == torch.float:
|
| 210 |
+
return qconv # dynamic quantization doesn't need scale/zero_point
|
| 211 |
+
else:
|
| 212 |
+
act_scale, act_zp = activation_post_process.calculate_qparams()
|
| 213 |
+
qconv.scale = float(act_scale)
|
| 214 |
+
qconv.zero_point = int(act_zp)
|
| 215 |
+
return qconv
|
| 216 |
+
|
| 217 |
+
@staticmethod
|
| 218 |
+
def from_float(cls, mod):
|
| 219 |
+
if hasattr(mod, "weight_fake_quant"):
|
| 220 |
+
# assert type(mod) == cls.__QAT_MODULE, " nnq." + cls.__name__ + \
|
| 221 |
+
# ".from_float only works for " + cls.__QAT_MODULE.__name__
|
| 222 |
+
if type(mod) == cls._NNIQAT_CONV_BN_MODULE:
|
| 223 |
+
mod.weight, mod.bias = fuse_conv_bn_weights(
|
| 224 |
+
mod.weight, mod.bias, mod.bn.running_mean, mod.bn.running_var,
|
| 225 |
+
mod.bn.eps, mod.bn.weight, mod.bn.bias)
|
| 226 |
+
assert hasattr(mod, "activation_post_process"), \
|
| 227 |
+
"Input QAT module must have observer attached"
|
| 228 |
+
weight_post_process = mod.weight_fake_quant
|
| 229 |
+
activation_post_process = mod.activation_post_process
|
| 230 |
+
else:
|
| 231 |
+
assert type(mod) == cls._FLOAT_MODULE, \
|
| 232 |
+
" nnq." + cls.__name__ + ".from_float only works for " + \
|
| 233 |
+
cls._FLOAT_MODULE.__name__ + " but got:" + str(type(mod))
|
| 234 |
+
assert hasattr(mod, "qconfig"), \
|
| 235 |
+
"Input float module must have qconfig defined."
|
| 236 |
+
activation_post_process = None if not hasattr(
|
| 237 |
+
mod, "activation_post_process") else mod.activation_post_process
|
| 238 |
+
if type(mod) in [cls._NNI_CONV_RELU_MODULE, cls._NNI_CONV_ADD_MODULE, cls._NNI_CONV_ADD_RELU_MODULE]:
|
| 239 |
+
mod = mod[0]
|
| 240 |
+
weight_post_process = mod.qconfig.weight()
|
| 241 |
+
return cls.get_qconv(mod, activation_post_process, weight_post_process)
|
| 242 |
+
|
| 243 |
+
@classmethod
|
| 244 |
+
def from_reference(cls, ref_qconv, output_scale, output_zero_point):
|
| 245 |
+
r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module
|
| 246 |
+
Args:
|
| 247 |
+
ref_qconv (Module): a reference quantized module, either produced by torch.ao.quantization
|
| 248 |
+
utilities or provided by the user
|
| 249 |
+
output_scale (float): scale for output Tensor
|
| 250 |
+
output_zero_point (int): zero point for output Tensor
|
| 251 |
+
"""
|
| 252 |
+
qconv = cls(
|
| 253 |
+
ref_qconv.in_channels,
|
| 254 |
+
ref_qconv.out_channels,
|
| 255 |
+
ref_qconv.kernel_size, # type: ignore[arg-type]
|
| 256 |
+
ref_qconv.stride, # type: ignore[arg-type]
|
| 257 |
+
ref_qconv.padding, # type: ignore[arg-type]
|
| 258 |
+
ref_qconv.dilation, # type: ignore[arg-type]
|
| 259 |
+
ref_qconv.groups,
|
| 260 |
+
ref_qconv.bias is not None, # type: ignore[arg-type]
|
| 261 |
+
ref_qconv.padding_mode,
|
| 262 |
+
device=ref_qconv.weight.device,
|
| 263 |
+
dtype=ref_qconv.weight.dtype)
|
| 264 |
+
qweight = ref_qconv.get_quantized_weight()
|
| 265 |
+
qconv.set_weight_bias(qweight, ref_qconv.bias)
|
| 266 |
+
qconv.scale = float(output_scale)
|
| 267 |
+
qconv.zero_point = int(output_zero_point)
|
| 268 |
+
return qconv
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class Conv1d(_ConvNd):
|
| 272 |
+
r"""Applies a 1D convolution over a quantized input signal composed of
|
| 273 |
+
several quantized input planes.
|
| 274 |
+
|
| 275 |
+
For details on input arguments, parameters, and implementation see
|
| 276 |
+
:class:`~torch.nn.Conv1d`.
|
| 277 |
+
|
| 278 |
+
.. note::
|
| 279 |
+
Only `zeros` is supported for the :attr:`padding_mode` argument.
|
| 280 |
+
|
| 281 |
+
.. note::
|
| 282 |
+
Only `torch.quint8` is supported for the input data type.
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
Attributes:
|
| 286 |
+
weight (Tensor): packed tensor derived from the learnable weight
|
| 287 |
+
parameter.
|
| 288 |
+
scale (Tensor): scalar for the output scale
|
| 289 |
+
zero_point (Tensor): scalar for the output zero point
|
| 290 |
+
|
| 291 |
+
See :class:`~torch.nn.Conv1d` for other attributes.
|
| 292 |
+
|
| 293 |
+
Examples::
|
| 294 |
+
|
| 295 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 296 |
+
>>> m = nn.quantized.Conv1d(16, 33, 3, stride=2)
|
| 297 |
+
>>> input = torch.randn(20, 16, 100)
|
| 298 |
+
>>> # quantize input to quint8
|
| 299 |
+
>>> # xdoctest: +SKIP
|
| 300 |
+
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0,
|
| 301 |
+
... dtype=torch.quint8)
|
| 302 |
+
>>> output = m(q_input)
|
| 303 |
+
|
| 304 |
+
"""
|
| 305 |
+
|
| 306 |
+
_FLOAT_MODULE = nn.Conv1d
|
| 307 |
+
_NNIQAT_CONV_BN_MODULE = nniqat.ConvBn1d
|
| 308 |
+
_NNI_CONV_RELU_MODULE = nni.ConvReLU1d
|
| 309 |
+
_NNI_CONV_ADD_MODULE = None
|
| 310 |
+
_NNI_CONV_ADD_RELU_MODULE = None
|
| 311 |
+
|
| 312 |
+
def __init__(self,
|
| 313 |
+
in_channels: int,
|
| 314 |
+
out_channels: int,
|
| 315 |
+
kernel_size: _size_1_t,
|
| 316 |
+
stride: _size_1_t = 1,
|
| 317 |
+
padding: _size_1_t = 0,
|
| 318 |
+
dilation: _size_1_t = 1,
|
| 319 |
+
groups: int = 1,
|
| 320 |
+
bias: bool = True,
|
| 321 |
+
padding_mode: str = 'zeros',
|
| 322 |
+
device=None,
|
| 323 |
+
dtype=None):
|
| 324 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 325 |
+
kernel_size = _single(kernel_size)
|
| 326 |
+
stride = _single(stride)
|
| 327 |
+
padding = padding if isinstance(padding, str) else _single(padding)
|
| 328 |
+
dilation = _single(dilation)
|
| 329 |
+
|
| 330 |
+
# Subclasses of _ConvNd needs to call _init rather than __init__. See
|
| 331 |
+
# discussion on PR #49702
|
| 332 |
+
super()._init(
|
| 333 |
+
in_channels, out_channels, kernel_size, stride, padding, dilation,
|
| 334 |
+
False, _single(0), groups, bias, padding_mode, **factory_kwargs)
|
| 335 |
+
|
| 336 |
+
def _get_name(self):
|
| 337 |
+
return 'QuantizedConv1d'
|
| 338 |
+
|
| 339 |
+
def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None:
|
| 340 |
+
if self.padding_mode == 'zeros':
|
| 341 |
+
self._packed_params = torch.ops.quantized.conv1d_prepack(
|
| 342 |
+
w, b, self.stride, self.padding, self.dilation, self.groups)
|
| 343 |
+
else:
|
| 344 |
+
self._packed_params = torch.ops.quantized.conv1d_prepack(
|
| 345 |
+
w, b, self.stride, _pair(0), self.dilation,
|
| 346 |
+
self.groups)
|
| 347 |
+
|
| 348 |
+
def _weight_bias(self):
|
| 349 |
+
w, b = torch.ops.quantized.conv1d_unpack(self._packed_params)
|
| 350 |
+
return w, b
|
| 351 |
+
|
| 352 |
+
def weight(self):
|
| 353 |
+
return self._weight_bias()[0]
|
| 354 |
+
|
| 355 |
+
def bias(self):
|
| 356 |
+
return self._weight_bias()[1]
|
| 357 |
+
|
| 358 |
+
def forward(self, input):
|
| 359 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 360 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 361 |
+
if len(input.shape) != 3:
|
| 362 |
+
raise ValueError("Input shape must be `(N, C, L)`!")
|
| 363 |
+
if self.padding_mode != 'zeros':
|
| 364 |
+
# Padding in Conv1d is stored as (p, p), need to get (p,)
|
| 365 |
+
_reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding[:1])
|
| 366 |
+
input = F.pad(input, _reversed_padding_repeated_twice,
|
| 367 |
+
mode=self.padding_mode)
|
| 368 |
+
return ops.quantized.conv1d(input, self._packed_params, self.scale, self.zero_point)
|
| 369 |
+
|
| 370 |
+
@classmethod
|
| 371 |
+
def from_float(cls, mod):
|
| 372 |
+
r"""Creates a quantized module from a float module or qparams_dict.
|
| 373 |
+
|
| 374 |
+
Args:
|
| 375 |
+
mod (Module): a float module, either produced by torch.ao.quantization
|
| 376 |
+
utilities or provided by the user
|
| 377 |
+
"""
|
| 378 |
+
return _ConvNd.from_float(cls, mod)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
class Conv2d(_ConvNd):
|
| 382 |
+
r"""Applies a 2D convolution over a quantized input signal composed of
|
| 383 |
+
several quantized input planes.
|
| 384 |
+
|
| 385 |
+
For details on input arguments, parameters, and implementation see
|
| 386 |
+
:class:`~torch.nn.Conv2d`.
|
| 387 |
+
|
| 388 |
+
.. note::
|
| 389 |
+
Only `zeros` is supported for the :attr:`padding_mode` argument.
|
| 390 |
+
|
| 391 |
+
.. note::
|
| 392 |
+
Only `torch.quint8` is supported for the input data type.
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
Attributes:
|
| 396 |
+
weight (Tensor): packed tensor derived from the learnable weight
|
| 397 |
+
parameter.
|
| 398 |
+
scale (Tensor): scalar for the output scale
|
| 399 |
+
zero_point (Tensor): scalar for the output zero point
|
| 400 |
+
|
| 401 |
+
See :class:`~torch.nn.Conv2d` for other attributes.
|
| 402 |
+
|
| 403 |
+
Examples::
|
| 404 |
+
|
| 405 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 406 |
+
>>> # With square kernels and equal stride
|
| 407 |
+
>>> m = nn.quantized.Conv2d(16, 33, 3, stride=2)
|
| 408 |
+
>>> # non-square kernels and unequal stride and with padding
|
| 409 |
+
>>> m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
|
| 410 |
+
>>> # non-square kernels and unequal stride and with padding and dilation
|
| 411 |
+
>>> m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
|
| 412 |
+
>>> input = torch.randn(20, 16, 50, 100)
|
| 413 |
+
>>> # quantize input to quint8
|
| 414 |
+
>>> # xdoctest: +SKIP
|
| 415 |
+
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
|
| 416 |
+
>>> output = m(q_input)
|
| 417 |
+
|
| 418 |
+
"""
|
| 419 |
+
_FLOAT_MODULE = nn.Conv2d
|
| 420 |
+
_NNIQAT_CONV_BN_MODULE = nniqat.ConvBn2d
|
| 421 |
+
_NNI_CONV_RELU_MODULE = nni.ConvReLU2d
|
| 422 |
+
_NNI_CONV_ADD_MODULE = nni.ConvAdd2d
|
| 423 |
+
_NNI_CONV_ADD_RELU_MODULE = nni.ConvAddReLU2d
|
| 424 |
+
|
| 425 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
| 426 |
+
padding=0, dilation=1, groups=1, bias=True,
|
| 427 |
+
padding_mode='zeros', device=None, dtype=None):
|
| 428 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 429 |
+
kernel_size = _pair(kernel_size)
|
| 430 |
+
stride = _pair(stride)
|
| 431 |
+
padding = _pair(padding)
|
| 432 |
+
dilation = _pair(dilation)
|
| 433 |
+
# Subclasses of _ConvNd need to call _init rather than __init__. See
|
| 434 |
+
# discussion on PR #49702
|
| 435 |
+
super()._init(
|
| 436 |
+
in_channels, out_channels, kernel_size, stride, padding, dilation,
|
| 437 |
+
False, _pair(0), groups, bias, padding_mode, **factory_kwargs)
|
| 438 |
+
|
| 439 |
+
def _get_name(self):
|
| 440 |
+
return 'QuantizedConv2d'
|
| 441 |
+
|
| 442 |
+
def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None:
|
| 443 |
+
if self.padding_mode == 'zeros':
|
| 444 |
+
self._packed_params = torch.ops.quantized.conv2d_prepack(
|
| 445 |
+
w, b, self.stride, self.padding, self.dilation, self.groups)
|
| 446 |
+
else:
|
| 447 |
+
self._packed_params = torch.ops.quantized.conv2d_prepack(
|
| 448 |
+
w, b, self.stride, _pair(0), self.dilation, self.groups)
|
| 449 |
+
|
| 450 |
+
def _weight_bias(self):
|
| 451 |
+
return self._packed_params.unpack()
|
| 452 |
+
|
| 453 |
+
def weight(self):
|
| 454 |
+
return self._weight_bias()[0]
|
| 455 |
+
|
| 456 |
+
def bias(self):
|
| 457 |
+
return self._weight_bias()[1]
|
| 458 |
+
|
| 459 |
+
def forward(self, input):
|
| 460 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 461 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 462 |
+
if len(input.shape) != 4:
|
| 463 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 464 |
+
if self.padding_mode != 'zeros':
|
| 465 |
+
_reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
|
| 466 |
+
input = F.pad(input, _reversed_padding_repeated_twice,
|
| 467 |
+
mode=self.padding_mode)
|
| 468 |
+
return ops.quantized.conv2d(
|
| 469 |
+
input, self._packed_params, self.scale, self.zero_point)
|
| 470 |
+
|
| 471 |
+
@classmethod
|
| 472 |
+
def from_float(cls, mod):
|
| 473 |
+
r"""Creates a quantized module from a float module or qparams_dict.
|
| 474 |
+
|
| 475 |
+
Args:
|
| 476 |
+
mod (Module): a float module, either produced by torch.ao.quantization
|
| 477 |
+
utilities or provided by the user
|
| 478 |
+
"""
|
| 479 |
+
return _ConvNd.from_float(cls, mod)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
class Conv3d(_ConvNd):
|
| 483 |
+
r"""Applies a 3D convolution over a quantized input signal composed of
|
| 484 |
+
several quantized input planes.
|
| 485 |
+
|
| 486 |
+
For details on input arguments, parameters, and implementation see
|
| 487 |
+
:class:`~torch.nn.Conv3d`.
|
| 488 |
+
|
| 489 |
+
.. note::
|
| 490 |
+
Only `zeros` is supported for the :attr:`padding_mode` argument.
|
| 491 |
+
|
| 492 |
+
.. note::
|
| 493 |
+
Only `torch.quint8` is supported for the input data type.
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
Attributes:
|
| 497 |
+
weight (Tensor): packed tensor derived from the learnable weight
|
| 498 |
+
parameter.
|
| 499 |
+
scale (Tensor): scalar for the output scale
|
| 500 |
+
zero_point (Tensor): scalar for the output zero point
|
| 501 |
+
|
| 502 |
+
See :class:`~torch.nn.Conv3d` for other attributes.
|
| 503 |
+
|
| 504 |
+
Examples::
|
| 505 |
+
|
| 506 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 507 |
+
>>> # With square kernels and equal stride
|
| 508 |
+
>>> m = nn.quantized.Conv3d(16, 33, 3, stride=2)
|
| 509 |
+
>>> # non-square kernels and unequal stride and with padding
|
| 510 |
+
>>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2))
|
| 511 |
+
>>> # non-square kernels and unequal stride and with padding and dilation
|
| 512 |
+
>>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2), dilation=(1, 2, 2))
|
| 513 |
+
>>> input = torch.randn(20, 16, 56, 56, 56)
|
| 514 |
+
>>> # quantize input to quint8
|
| 515 |
+
>>> # xdoctest: +SKIP
|
| 516 |
+
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
|
| 517 |
+
>>> output = m(q_input)
|
| 518 |
+
|
| 519 |
+
"""
|
| 520 |
+
_FLOAT_MODULE = nn.Conv3d
|
| 521 |
+
_NNIQAT_CONV_BN_MODULE = nniqat.ConvBn3d
|
| 522 |
+
_NNI_CONV_RELU_MODULE = nni.ConvReLU3d
|
| 523 |
+
_NNI_CONV_ADD_MODULE = None
|
| 524 |
+
_NNI_CONV_ADD_RELU_MODULE = None
|
| 525 |
+
|
| 526 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
| 527 |
+
padding=0, dilation=1, groups=1, bias=True,
|
| 528 |
+
padding_mode='zeros', device=None, dtype=None):
|
| 529 |
+
assert padding_mode != 'reflect', "Conv3d does not support reflection padding"
|
| 530 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 531 |
+
kernel_size = _triple(kernel_size)
|
| 532 |
+
stride = _triple(stride)
|
| 533 |
+
padding = _triple(padding)
|
| 534 |
+
dilation = _triple(dilation)
|
| 535 |
+
# Subclasses of _ConvNd need to call _init rather than __init__. See
|
| 536 |
+
# discussion on PR #49702
|
| 537 |
+
super()._init(
|
| 538 |
+
in_channels, out_channels, kernel_size, stride, padding, dilation,
|
| 539 |
+
False, _triple(0), groups, bias, padding_mode, **factory_kwargs)
|
| 540 |
+
|
| 541 |
+
def _get_name(self):
|
| 542 |
+
return 'QuantizedConv3d'
|
| 543 |
+
|
| 544 |
+
def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None:
|
| 545 |
+
if self.padding_mode == 'zeros':
|
| 546 |
+
self._packed_params = torch.ops.quantized.conv3d_prepack(
|
| 547 |
+
w, b, self.stride, self.padding, self.dilation, self.groups)
|
| 548 |
+
else:
|
| 549 |
+
self._packed_params = torch.ops.quantized.conv3d_prepack(
|
| 550 |
+
w, b, self.stride, _triple(0), self.dilation, self.groups)
|
| 551 |
+
|
| 552 |
+
def _weight_bias(self):
|
| 553 |
+
return self._packed_params.unpack()
|
| 554 |
+
|
| 555 |
+
def weight(self):
|
| 556 |
+
return self._weight_bias()[0]
|
| 557 |
+
|
| 558 |
+
def bias(self):
|
| 559 |
+
return self._weight_bias()[1]
|
| 560 |
+
|
| 561 |
+
def forward(self, input):
|
| 562 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 563 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 564 |
+
if len(input.shape) != 5:
|
| 565 |
+
raise ValueError("Input shape must be `(N, C, D, H, W)`!")
|
| 566 |
+
if self.padding_mode != 'zeros':
|
| 567 |
+
_reversed_padding_repeated_twice = _reverse_repeat_padding(self.padding)
|
| 568 |
+
input = F.pad(input, _reversed_padding_repeated_twice,
|
| 569 |
+
mode=self.padding_mode)
|
| 570 |
+
return ops.quantized.conv3d(
|
| 571 |
+
input, self._packed_params, self.scale, self.zero_point)
|
| 572 |
+
|
| 573 |
+
@classmethod
|
| 574 |
+
def from_float(cls, mod):
|
| 575 |
+
r"""Creates a quantized module from a float module or qparams_dict.
|
| 576 |
+
|
| 577 |
+
Args:
|
| 578 |
+
mod (Module): a float module, either produced by torch.ao.quantization
|
| 579 |
+
utilities or provided by the user
|
| 580 |
+
"""
|
| 581 |
+
return _ConvNd.from_float(cls, mod)
|
| 582 |
+
|
| 583 |
+
# === Transposed Convolutions ===
|
| 584 |
+
MOD = TypeVar('MOD', bound=nn.modules.conv._ConvNd)
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
class _ConvTransposeNd(_ConvNd):
|
| 588 |
+
|
| 589 |
+
_FLOAT_MODULE = MOD
|
| 590 |
+
|
| 591 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride,
|
| 592 |
+
padding, dilation, transposed, output_padding,
|
| 593 |
+
groups, bias, padding_mode, device=None, dtype=None):
|
| 594 |
+
if padding_mode != 'zeros':
|
| 595 |
+
raise ValueError(f'Only "zeros" padding mode is supported for {self.__class__.__name__}')
|
| 596 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 597 |
+
# Subclasses of _ConvNd need to call _init rather than __init__. See
|
| 598 |
+
# discussion on PR #49702
|
| 599 |
+
super()._init(
|
| 600 |
+
in_channels, out_channels, kernel_size, stride,
|
| 601 |
+
padding, dilation, transposed, output_padding,
|
| 602 |
+
groups, bias, padding_mode, **factory_kwargs)
|
| 603 |
+
|
| 604 |
+
def _input_padding(self, kernel_size: List[int], dilation: List[int], padding: List[int]) -> List[int]:
|
| 605 |
+
res = torch.jit.annotate(List[int], [])
|
| 606 |
+
for kdx in range(len(kernel_size)):
|
| 607 |
+
pad = (dilation[kdx] * (kernel_size[kdx] - 1) - padding[kdx])
|
| 608 |
+
res.append(pad)
|
| 609 |
+
return res
|
| 610 |
+
|
| 611 |
+
@classmethod
|
| 612 |
+
def from_float(cls, mod):
|
| 613 |
+
r"""Creates a quantized module from a float module or qparams_dict.
|
| 614 |
+
Args:
|
| 615 |
+
mod (Module): a float module, either produced by torch.ao.quantization
|
| 616 |
+
utilities or provided by the user
|
| 617 |
+
"""
|
| 618 |
+
# derived classes override cls._FLOAT_MODULE attribute
|
| 619 |
+
msg = ' nnq.' + cls.__name__ + '.from_float only works for ' + \
|
| 620 |
+
cls._FLOAT_MODULE.__name__ # type: ignore[attr-defined]
|
| 621 |
+
assert type(mod) == cls._FLOAT_MODULE, msg
|
| 622 |
+
assert hasattr(mod, 'qconfig'), \
|
| 623 |
+
'Input float module must have qconfig defined.'
|
| 624 |
+
weight_post_process = mod.qconfig.weight()
|
| 625 |
+
weight_post_process(mod.weight)
|
| 626 |
+
assert weight_post_process.dtype == torch.qint8, \
|
| 627 |
+
'Weight observer must have a dtype of qint8'
|
| 628 |
+
qweight = _quantize_weight(mod.weight.float(), weight_post_process)
|
| 629 |
+
# the __init__ call used is the one from derived classes and not the one from _ConvTransposeNd
|
| 630 |
+
qconv = cls(mod.in_channels, mod.out_channels, mod.kernel_size, # type: ignore[call-arg]
|
| 631 |
+
mod.stride, mod.padding, mod.output_padding, mod.groups,
|
| 632 |
+
mod.bias is not None, mod.dilation, mod.padding_mode)
|
| 633 |
+
qconv.set_weight_bias(qweight, mod.bias)
|
| 634 |
+
if not hasattr(mod, "activation_post_process") or mod.activation_post_process.dtype == torch.float:
|
| 635 |
+
return qconv # dynamic quantization doesn't need scale/zero_point
|
| 636 |
+
else:
|
| 637 |
+
act_scale, act_zp = mod.activation_post_process.calculate_qparams()
|
| 638 |
+
qconv.scale = float(act_scale)
|
| 639 |
+
qconv.zero_point = int(act_zp)
|
| 640 |
+
return qconv
|
| 641 |
+
|
| 642 |
+
@staticmethod
|
| 643 |
+
def from_reference(cls, ref_qconvt, output_scale, output_zero_point):
|
| 644 |
+
r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module
|
| 645 |
+
Args:
|
| 646 |
+
ref_qconvt (Module): a reference quantized module, either produced by torch.ao.quantization
|
| 647 |
+
utilities or provided by the user
|
| 648 |
+
output_scale (float): scale for output Tensor
|
| 649 |
+
output_zero_point (int): zero point for output Tensor
|
| 650 |
+
"""
|
| 651 |
+
qconv = cls(
|
| 652 |
+
ref_qconvt.in_channels,
|
| 653 |
+
ref_qconvt.out_channels,
|
| 654 |
+
ref_qconvt.kernel_size, # type: ignore[arg-type]
|
| 655 |
+
ref_qconvt.stride, # type: ignore[arg-type]
|
| 656 |
+
ref_qconvt.padding, # type: ignore[arg-type]
|
| 657 |
+
ref_qconvt.output_padding, # type: ignore[arg-type]
|
| 658 |
+
ref_qconvt.groups,
|
| 659 |
+
ref_qconvt.bias is not None, # type: ignore[arg-type]
|
| 660 |
+
ref_qconvt.dilation, # type: ignore[arg-type]
|
| 661 |
+
ref_qconvt.padding_mode,
|
| 662 |
+
device=ref_qconvt.weight.device,
|
| 663 |
+
dtype=ref_qconvt.weight.dtype)
|
| 664 |
+
qweight = ref_qconvt.get_quantized_weight()
|
| 665 |
+
qconv.set_weight_bias(qweight, ref_qconvt.bias)
|
| 666 |
+
qconv.scale = float(output_scale)
|
| 667 |
+
qconv.zero_point = int(output_zero_point)
|
| 668 |
+
return qconv
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
class ConvTranspose1d(_ConvTransposeNd):
|
| 672 |
+
r"""Applies a 1D transposed convolution operator over an input image
|
| 673 |
+
composed of several input planes.
|
| 674 |
+
For details on input arguments, parameters, and implementation see
|
| 675 |
+
:class:`~torch.nn.ConvTranspose1d`.
|
| 676 |
+
|
| 677 |
+
.. note:: Currently only the QNNPACK engine is implemented.
|
| 678 |
+
Please, set the `torch.backends.quantized.engine = 'qnnpack'`
|
| 679 |
+
|
| 680 |
+
For special notes, please, see :class:`~torch.ao.nn.quantized.Conv1d`
|
| 681 |
+
|
| 682 |
+
Attributes:
|
| 683 |
+
weight (Tensor): packed tensor derived from the learnable weight
|
| 684 |
+
parameter.
|
| 685 |
+
scale (Tensor): scalar for the output scale
|
| 686 |
+
zero_point (Tensor): scalar for the output zero point
|
| 687 |
+
See :class:`~torch.nn.ConvTranspose2d` for other attributes.
|
| 688 |
+
|
| 689 |
+
Examples::
|
| 690 |
+
|
| 691 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 692 |
+
>>> torch.backends.quantized.engine = 'qnnpack'
|
| 693 |
+
>>> from torch.ao.nn import quantized as nnq
|
| 694 |
+
>>> # With square kernels and equal stride
|
| 695 |
+
>>> m = nnq.ConvTranspose1d(16, 33, 3, stride=2)
|
| 696 |
+
>>> # non-square kernels and unequal stride and with padding
|
| 697 |
+
>>> m = nnq.ConvTranspose1d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
|
| 698 |
+
>>> input = torch.randn(20, 16, 50)
|
| 699 |
+
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
|
| 700 |
+
>>> output = m(q_input)
|
| 701 |
+
>>> # exact output size can be also specified as an argument
|
| 702 |
+
>>> input = torch.randn(1, 16, 12)
|
| 703 |
+
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
|
| 704 |
+
>>> downsample = nnq.Conv1d(16, 16, 3, stride=2, padding=1)
|
| 705 |
+
>>> upsample = nnq.ConvTranspose1d(16, 16, 3, stride=2, padding=1)
|
| 706 |
+
>>> h = downsample(q_input)
|
| 707 |
+
>>> h.size()
|
| 708 |
+
torch.Size([1, 16, 6])
|
| 709 |
+
>>> # xdoctest: +SKIP("FIXME: output_size is not a parameter)
|
| 710 |
+
>>> output = upsample(h, output_size=input.size())
|
| 711 |
+
>>> output.size()
|
| 712 |
+
torch.Size([1, 16, 12])
|
| 713 |
+
"""
|
| 714 |
+
|
| 715 |
+
_FLOAT_MODULE = nn.ConvTranspose1d
|
| 716 |
+
|
| 717 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
| 718 |
+
padding=0, output_padding=0, groups=1, bias=True,
|
| 719 |
+
dilation=1, padding_mode='zeros', device=None, dtype=None):
|
| 720 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 721 |
+
kernel_size = _single(kernel_size)
|
| 722 |
+
stride = _single(stride)
|
| 723 |
+
padding = _single(padding)
|
| 724 |
+
dilation = _single(dilation)
|
| 725 |
+
output_padding = _single(output_padding)
|
| 726 |
+
|
| 727 |
+
super().__init__(
|
| 728 |
+
in_channels, out_channels, kernel_size, stride, padding, dilation,
|
| 729 |
+
True, output_padding, groups, bias, padding_mode, **factory_kwargs)
|
| 730 |
+
|
| 731 |
+
def _get_name(self):
|
| 732 |
+
return 'QuantizedConvTranspose1d'
|
| 733 |
+
|
| 734 |
+
def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None:
|
| 735 |
+
self._packed_params = torch.ops.quantized.conv_transpose1d_prepack(
|
| 736 |
+
w, b, self.stride, self.padding, self.output_padding, self.dilation,
|
| 737 |
+
self.groups)
|
| 738 |
+
|
| 739 |
+
def _weight_bias(self):
|
| 740 |
+
w, b = torch.ops.quantized.conv_transpose1d_unpack(self._packed_params)
|
| 741 |
+
return w, b
|
| 742 |
+
|
| 743 |
+
def weight(self):
|
| 744 |
+
(w, _) = self._weight_bias()
|
| 745 |
+
return w
|
| 746 |
+
|
| 747 |
+
def bias(self):
|
| 748 |
+
(_, b) = self._weight_bias()
|
| 749 |
+
return b
|
| 750 |
+
|
| 751 |
+
def forward(self, input):
|
| 752 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 753 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 754 |
+
if len(input.shape) != 3:
|
| 755 |
+
raise ValueError("Input shape must be `(N, C, L)`!")
|
| 756 |
+
return torch.ops.quantized.conv_transpose1d(
|
| 757 |
+
input, self._packed_params, self.scale, self.zero_point)
|
| 758 |
+
|
| 759 |
+
@classmethod
|
| 760 |
+
def from_reference(cls, ref_qconvt, output_scale, output_zero_point):
|
| 761 |
+
return _ConvTransposeNd.from_reference(cls, ref_qconvt, output_scale, output_zero_point)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
class ConvTranspose2d(_ConvTransposeNd):
|
| 765 |
+
r"""Applies a 2D transposed convolution operator over an input image
|
| 766 |
+
composed of several input planes.
|
| 767 |
+
For details on input arguments, parameters, and implementation see
|
| 768 |
+
:class:`~torch.nn.ConvTranspose2d`.
|
| 769 |
+
|
| 770 |
+
For special notes, please, see :class:`~torch.ao.nn.quantized.Conv2d`
|
| 771 |
+
|
| 772 |
+
Attributes:
|
| 773 |
+
weight (Tensor): packed tensor derived from the learnable weight
|
| 774 |
+
parameter.
|
| 775 |
+
scale (Tensor): scalar for the output scale
|
| 776 |
+
zero_point (Tensor): scalar for the output zero point
|
| 777 |
+
See :class:`~torch.nn.ConvTranspose2d` for other attributes.
|
| 778 |
+
|
| 779 |
+
Examples::
|
| 780 |
+
|
| 781 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 782 |
+
>>> # QNNPACK or FBGEMM as backend
|
| 783 |
+
>>> torch.backends.quantized.engine = 'qnnpack'
|
| 784 |
+
>>> # With square kernels and equal stride
|
| 785 |
+
>>> import torch.ao.nn.quantized as nnq
|
| 786 |
+
>>> m = nnq.ConvTranspose2d(16, 33, 3, stride=2)
|
| 787 |
+
>>> # non-square kernels and unequal stride and with padding
|
| 788 |
+
>>> m = nnq.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
|
| 789 |
+
>>> input = torch.randn(20, 16, 50, 100)
|
| 790 |
+
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
|
| 791 |
+
>>> output = m(q_input)
|
| 792 |
+
>>> # exact output size can be also specified as an argument
|
| 793 |
+
>>> input = torch.randn(1, 16, 12, 12)
|
| 794 |
+
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
|
| 795 |
+
>>> downsample = nnq.Conv2d(16, 16, 3, stride=2, padding=1)
|
| 796 |
+
>>> upsample = nnq.ConvTranspose2d(16, 16, 3, stride=2, padding=1)
|
| 797 |
+
>>> h = downsample(q_input)
|
| 798 |
+
>>> h.size()
|
| 799 |
+
torch.Size([1, 16, 6, 6])
|
| 800 |
+
>>> # xdoctest: +SKIP("FIXME: output_size is not a parameter)
|
| 801 |
+
>>> output = upsample(h, output_size=input.size())
|
| 802 |
+
>>> output.size()
|
| 803 |
+
torch.Size([1, 16, 12, 12])
|
| 804 |
+
"""
|
| 805 |
+
|
| 806 |
+
_FLOAT_MODULE = nn.ConvTranspose2d
|
| 807 |
+
|
| 808 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
| 809 |
+
padding=0, output_padding=0, groups=1, bias=True,
|
| 810 |
+
dilation=1, padding_mode='zeros', device=None, dtype=None):
|
| 811 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 812 |
+
kernel_size = _pair(kernel_size)
|
| 813 |
+
stride = _pair(stride)
|
| 814 |
+
padding = _pair(padding)
|
| 815 |
+
dilation = _pair(dilation)
|
| 816 |
+
output_padding = _pair(output_padding)
|
| 817 |
+
|
| 818 |
+
super().__init__(
|
| 819 |
+
in_channels, out_channels, kernel_size, stride, padding, dilation,
|
| 820 |
+
True, output_padding, groups, bias, padding_mode, **factory_kwargs)
|
| 821 |
+
|
| 822 |
+
def _get_name(self):
|
| 823 |
+
return 'QuantizedConvTranspose2d'
|
| 824 |
+
|
| 825 |
+
def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None:
|
| 826 |
+
self._packed_params = torch.ops.quantized.conv_transpose2d_prepack(
|
| 827 |
+
w, b, self.stride, self.padding, self.output_padding, self.dilation,
|
| 828 |
+
self.groups)
|
| 829 |
+
|
| 830 |
+
def _weight_bias(self):
|
| 831 |
+
w, b = torch.ops.quantized.conv2d_unpack(self._packed_params)
|
| 832 |
+
return w, b
|
| 833 |
+
|
| 834 |
+
def weight(self):
|
| 835 |
+
(w, _) = self._weight_bias()
|
| 836 |
+
return w
|
| 837 |
+
|
| 838 |
+
def bias(self):
|
| 839 |
+
(_, b) = self._weight_bias()
|
| 840 |
+
return b
|
| 841 |
+
|
| 842 |
+
def forward(self, input):
|
| 843 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 844 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 845 |
+
if len(input.shape) != 4:
|
| 846 |
+
raise ValueError("Input shape must be `(N, C, H, W)`!")
|
| 847 |
+
return ops.quantized.conv_transpose2d(
|
| 848 |
+
input, self._packed_params, self.scale, self.zero_point)
|
| 849 |
+
|
| 850 |
+
@classmethod
|
| 851 |
+
def from_reference(cls, ref_qconvt, output_scale, output_zero_point):
|
| 852 |
+
return _ConvTransposeNd.from_reference(cls, ref_qconvt, output_scale, output_zero_point)
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
class ConvTranspose3d(_ConvTransposeNd):
|
| 856 |
+
r"""Applies a 3D transposed convolution operator over an input image
|
| 857 |
+
composed of several input planes.
|
| 858 |
+
For details on input arguments, parameters, and implementation see
|
| 859 |
+
:class:`~torch.nn.ConvTranspose3d`.
|
| 860 |
+
|
| 861 |
+
.. note:: Currently only the FBGEMM engine is implemented.
|
| 862 |
+
Please, set the `torch.backends.quantized.engine = 'fbgemm'`
|
| 863 |
+
|
| 864 |
+
For special notes, please, see :class:`~torch.ao.nn.quantized.Conv3d`
|
| 865 |
+
|
| 866 |
+
Attributes:
|
| 867 |
+
weight (Tensor): packed tensor derived from the learnable weight
|
| 868 |
+
parameter.
|
| 869 |
+
scale (Tensor): scalar for the output scale
|
| 870 |
+
zero_point (Tensor): scalar for the output zero point
|
| 871 |
+
See :class:`~torch.nn.ConvTranspose3d` for other attributes.
|
| 872 |
+
|
| 873 |
+
Examples::
|
| 874 |
+
|
| 875 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 876 |
+
>>> torch.backends.quantized.engine = 'fbgemm'
|
| 877 |
+
>>> from torch.ao.nn import quantized as nnq
|
| 878 |
+
>>> # With cubic kernels and equal stride
|
| 879 |
+
>>> m = nnq.ConvTranspose3d(16, 33, 3, stride=2)
|
| 880 |
+
>>> # non-cubic kernels and unequal stride and with padding
|
| 881 |
+
>>> m = nnq.ConvTranspose3d(16, 33, (3, 3, 5), stride=(2, 1, 1), padding=(4, 2, 2))
|
| 882 |
+
>>> input = torch.randn(20, 16, 50, 100, 100)
|
| 883 |
+
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
|
| 884 |
+
>>> output = m(q_input)
|
| 885 |
+
>>> # exact output size can be also specified as an argument
|
| 886 |
+
>>> input = torch.randn(1, 16, 12, 12, 12)
|
| 887 |
+
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.quint8)
|
| 888 |
+
>>> downsample = nnq.Conv3d(16, 16, 3, stride=2, padding=1)
|
| 889 |
+
>>> upsample = nnq.ConvTranspose3d(16, 16, 3, stride=2, padding=1)
|
| 890 |
+
>>> h = downsample(q_input)
|
| 891 |
+
>>> h.size()
|
| 892 |
+
torch.Size([1, 16, 6, 6, 6])
|
| 893 |
+
>>> # xdoctest: +SKIP("FIXME: output_size is not a parameter)
|
| 894 |
+
>>> output = upsample(h, output_size=input.size())
|
| 895 |
+
>>> output.size()
|
| 896 |
+
torch.Size([1, 16, 12, 12, 12])
|
| 897 |
+
"""
|
| 898 |
+
|
| 899 |
+
_FLOAT_MODULE = nn.ConvTranspose3d
|
| 900 |
+
|
| 901 |
+
def __init__(self, in_channels, out_channels, kernel_size, stride=1,
|
| 902 |
+
padding=0, output_padding=0, groups=1, bias=True,
|
| 903 |
+
dilation=1, padding_mode='zeros', device=None, dtype=None):
|
| 904 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 905 |
+
kernel_size = _triple(kernel_size)
|
| 906 |
+
stride = _triple(stride)
|
| 907 |
+
padding = _triple(padding)
|
| 908 |
+
dilation = _triple(dilation)
|
| 909 |
+
output_padding = _triple(output_padding)
|
| 910 |
+
|
| 911 |
+
super().__init__(
|
| 912 |
+
in_channels, out_channels, kernel_size, stride, padding, dilation,
|
| 913 |
+
True, output_padding, groups, bias, padding_mode, **factory_kwargs)
|
| 914 |
+
|
| 915 |
+
def _get_name(self):
|
| 916 |
+
return 'QuantizedConvTranspose3d'
|
| 917 |
+
|
| 918 |
+
def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None:
|
| 919 |
+
self._packed_params = torch.ops.quantized.conv_transpose3d_prepack(
|
| 920 |
+
w, b, self.stride, self.padding, self.output_padding, self.dilation,
|
| 921 |
+
self.groups)
|
| 922 |
+
|
| 923 |
+
def _weight_bias(self):
|
| 924 |
+
w, b = torch.ops.quantized.conv3d_unpack(self._packed_params)
|
| 925 |
+
return w, b
|
| 926 |
+
|
| 927 |
+
def weight(self):
|
| 928 |
+
(w, _) = self._weight_bias()
|
| 929 |
+
return w
|
| 930 |
+
|
| 931 |
+
def bias(self):
|
| 932 |
+
(_, b) = self._weight_bias()
|
| 933 |
+
return b
|
| 934 |
+
|
| 935 |
+
def forward(self, input):
|
| 936 |
+
# Temporarily using len(shape) instead of ndim due to JIT issue
|
| 937 |
+
# https://github.com/pytorch/pytorch/issues/23890
|
| 938 |
+
if len(input.shape) != 5:
|
| 939 |
+
raise ValueError("Input shape must be `(N, C, T, H, W)`!")
|
| 940 |
+
return ops.quantized.conv_transpose3d(
|
| 941 |
+
input, self._packed_params, self.scale, self.zero_point)
|
| 942 |
+
|
| 943 |
+
@classmethod
|
| 944 |
+
def from_reference(cls, ref_qconvt, output_scale, output_zero_point):
|
| 945 |
+
return _ConvTransposeNd.from_reference(cls, ref_qconvt, output_scale, output_zero_point)
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/dropout.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
__all__ = ['Dropout']
|
| 4 |
+
|
| 5 |
+
class Dropout(torch.nn.Dropout):
|
| 6 |
+
r"""This is the quantized equivalent of :class:`~torch.nn.Dropout`.
|
| 7 |
+
And this is a placeholder to enable models where fp32 tensors
|
| 8 |
+
had dropout to work with quantized tensors in train and eval mode.
|
| 9 |
+
|
| 10 |
+
Args:
|
| 11 |
+
p: probability of an element to be zeroed
|
| 12 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def forward(self, input):
|
| 16 |
+
return input
|
| 17 |
+
|
| 18 |
+
def _get_name(self):
|
| 19 |
+
return 'QuantizedDropout'
|
| 20 |
+
|
| 21 |
+
@classmethod
|
| 22 |
+
def from_float(cls, mod):
|
| 23 |
+
return cls(mod.p, mod.inplace)
|
| 24 |
+
|
| 25 |
+
@classmethod
|
| 26 |
+
def from_reference(cls, mod, scale, zero_point):
|
| 27 |
+
return cls(mod.p, mod.inplace)
|
llava_next/lib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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from torch import Tensor # noqa: F401
|
| 4 |
+
from torch._jit_internal import Optional, List # noqa: F401
|
| 5 |
+
|
| 6 |
+
from .utils import _hide_packed_params_repr
|
| 7 |
+
from .utils import _quantize_weight
|
| 8 |
+
|
| 9 |
+
__all__ = ['EmbeddingPackedParams', 'Embedding', 'EmbeddingBag']
|
| 10 |
+
|
| 11 |
+
class EmbeddingPackedParams(torch.nn.Module):
|
| 12 |
+
_version = 1
|
| 13 |
+
|
| 14 |
+
def __init__(self, num_embeddings, embedding_dim, dtype=torch.quint8):
|
| 15 |
+
super().__init__()
|
| 16 |
+
self.dtype = dtype
|
| 17 |
+
if self.dtype in [torch.quint8, torch.quint4x2]:
|
| 18 |
+
scales = torch.ones(num_embeddings, dtype=torch.float)
|
| 19 |
+
zero_points = torch.zeros(num_embeddings, dtype=torch.float)
|
| 20 |
+
wq = torch._empty_per_channel_affine_quantized([num_embeddings, embedding_dim], scales=scales,
|
| 21 |
+
zero_points=zero_points,
|
| 22 |
+
axis=0, dtype=self.dtype)
|
| 23 |
+
self.set_weight(wq)
|
| 24 |
+
else:
|
| 25 |
+
raise NotImplementedError(f'Unsupported dtype on quantized embedding! Supports quint8 and quint4x2. Got dtype: {dtype}')
|
| 26 |
+
|
| 27 |
+
@torch.jit.export
|
| 28 |
+
def set_weight(self, weight: torch.Tensor) -> None:
|
| 29 |
+
if self.dtype in [torch.quint8, torch.quint4x2]:
|
| 30 |
+
self._packed_weight = torch.ops.quantized.embedding_bag_prepack(weight)
|
| 31 |
+
else:
|
| 32 |
+
raise NotImplementedError('Unsupported dtype for quantized embedding prepack! Supports quint8 and quint4x2.')
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@torch.jit.export
|
| 36 |
+
def _weight(self):
|
| 37 |
+
if self.dtype in [torch.quint8, torch.quint4x2]:
|
| 38 |
+
return torch.ops.quantized.embedding_bag_unpack(self._packed_weight)
|
| 39 |
+
else:
|
| 40 |
+
raise NotImplementedError('Unsupported dtype for quantized embedding unpack! Supports quint8 and quint4x2.')
|
| 41 |
+
|
| 42 |
+
def forward(self, x):
|
| 43 |
+
return x
|
| 44 |
+
|
| 45 |
+
# Version 1
|
| 46 |
+
# self
|
| 47 |
+
# |--- _packed_weight : Tensor representing weight of EmbeddingPackedParamsBase
|
| 48 |
+
# |--- dtype : torch.dtype
|
| 49 |
+
|
| 50 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
| 51 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
| 52 |
+
destination[prefix + 'dtype'] = self.dtype
|
| 53 |
+
destination[prefix + '_packed_weight'] = self._weight()
|
| 54 |
+
|
| 55 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
|
| 56 |
+
missing_keys, unexpected_keys, error_msgs):
|
| 57 |
+
self.dtype = state_dict[prefix + 'dtype']
|
| 58 |
+
state_dict.pop(prefix + 'dtype')
|
| 59 |
+
|
| 60 |
+
weight = state_dict[prefix + '_packed_weight']
|
| 61 |
+
state_dict.pop(prefix + '_packed_weight')
|
| 62 |
+
self.set_weight(weight)
|
| 63 |
+
|
| 64 |
+
super()._load_from_state_dict(state_dict, prefix, local_metadata, False,
|
| 65 |
+
missing_keys, unexpected_keys, error_msgs)
|
| 66 |
+
|
| 67 |
+
def __repr__(self):
|
| 68 |
+
return self._weight().__repr__()
|
| 69 |
+
|
| 70 |
+
class Embedding(torch.nn.Module):
|
| 71 |
+
r"""
|
| 72 |
+
A quantized Embedding module with quantized packed weights as inputs.
|
| 73 |
+
We adopt the same interface as `torch.nn.Embedding`, please see
|
| 74 |
+
https://pytorch.org/docs/stable/nn.html#torch.nn.Embedding for documentation.
|
| 75 |
+
|
| 76 |
+
Similar to :class:`~torch.nn.Embedding`, attributes will be randomly
|
| 77 |
+
initialized at module creation time and will be overwritten later
|
| 78 |
+
|
| 79 |
+
Attributes:
|
| 80 |
+
weight (Tensor): the non-learnable quantized weights of the module of
|
| 81 |
+
shape :math:`(\text{num\_embeddings}, \text{embedding\_dim})`.
|
| 82 |
+
|
| 83 |
+
Examples::
|
| 84 |
+
>>> m = nn.quantized.Embedding(num_embeddings=10, embedding_dim=12)
|
| 85 |
+
>>> indices = torch.tensor([9, 6, 5, 7, 8, 8, 9, 2, 8])
|
| 86 |
+
>>> output = m(indices)
|
| 87 |
+
>>> print(output.size())
|
| 88 |
+
torch.Size([9, 12])
|
| 89 |
+
|
| 90 |
+
"""
|
| 91 |
+
_version = 1
|
| 92 |
+
|
| 93 |
+
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None,
|
| 94 |
+
max_norm: Optional[float] = None, norm_type: float = 2., scale_grad_by_freq: bool = False,
|
| 95 |
+
sparse: bool = False, _weight: Optional[Tensor] = None, dtype=torch.quint8) -> None:
|
| 96 |
+
super().__init__()
|
| 97 |
+
self.num_embeddings = num_embeddings
|
| 98 |
+
self.embedding_dim = embedding_dim
|
| 99 |
+
self.dtype = dtype
|
| 100 |
+
|
| 101 |
+
if _weight is None:
|
| 102 |
+
scales = torch.ones(num_embeddings, dtype=torch.float)
|
| 103 |
+
zero_points = torch.zeros(num_embeddings, dtype=torch.float)
|
| 104 |
+
qweight = torch._empty_per_channel_affine_quantized([num_embeddings, embedding_dim],
|
| 105 |
+
scales=scales, zero_points=zero_points,
|
| 106 |
+
axis=0, dtype=torch.quint8)
|
| 107 |
+
else:
|
| 108 |
+
assert list(_weight.shape) == [num_embeddings, embedding_dim], \
|
| 109 |
+
'Shape of weight does not match num_embeddings and embedding_dim'
|
| 110 |
+
qweight = _weight
|
| 111 |
+
|
| 112 |
+
self._packed_params = EmbeddingPackedParams(num_embeddings, embedding_dim, dtype)
|
| 113 |
+
self._packed_params.set_weight(qweight)
|
| 114 |
+
|
| 115 |
+
def forward(self, indices: Tensor) -> Tensor:
|
| 116 |
+
if self.dtype == torch.quint4x2:
|
| 117 |
+
return torch.ops.quantized.embedding_4bit(self._packed_params._packed_weight, indices)
|
| 118 |
+
else:
|
| 119 |
+
return torch.ops.quantized.embedding_byte(self._packed_params._packed_weight, indices)
|
| 120 |
+
|
| 121 |
+
def _get_name(self):
|
| 122 |
+
return 'QuantizedEmbedding'
|
| 123 |
+
|
| 124 |
+
def __repr__(self):
|
| 125 |
+
return _hide_packed_params_repr(self, EmbeddingPackedParams)
|
| 126 |
+
|
| 127 |
+
def extra_repr(self):
|
| 128 |
+
extra_repr_str = 'num_embeddings={}, embedding_dim={}, dtype={}, qscheme={}'.format(
|
| 129 |
+
self.num_embeddings, self.embedding_dim, self._packed_params.dtype, self.weight().qscheme()
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
return extra_repr_str
|
| 133 |
+
|
| 134 |
+
def set_weight(self, w: torch.Tensor) -> None:
|
| 135 |
+
self._packed_params.set_weight(w)
|
| 136 |
+
|
| 137 |
+
def weight(self):
|
| 138 |
+
return self._packed_params._weight()
|
| 139 |
+
|
| 140 |
+
@classmethod
|
| 141 |
+
def from_float(cls, mod):
|
| 142 |
+
r"""Create a quantized embedding module from a float module
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
mod (Module): a float module, either produced by torch.ao.quantization
|
| 146 |
+
utilities or provided by user
|
| 147 |
+
"""
|
| 148 |
+
if hasattr(mod, 'weight_fake_quant'):
|
| 149 |
+
assert type(mod) == torch.ao.nn.qat.Embedding, 'nnq.' + cls.__name__ + '.from_float ' + \
|
| 150 |
+
'with fake quant only works for ' + torch.ao.nn.qat.Embedding.__name__
|
| 151 |
+
weight_observer = mod.weight_fake_quant
|
| 152 |
+
activation_post_process = mod.activation_post_process
|
| 153 |
+
else:
|
| 154 |
+
assert type(mod) == nn.Embedding, 'nnq.' + cls.__name__ + '.from_float only works for ' + \
|
| 155 |
+
nn.Embedding.__name__
|
| 156 |
+
assert hasattr(mod, 'qconfig'), 'Embedding input float module must have qconfig defined'
|
| 157 |
+
from torch.ao.quantization import float_qparams_weight_only_qconfig
|
| 158 |
+
if mod.qconfig is not None and mod.qconfig.weight is not None: # type: ignore[union-attr]
|
| 159 |
+
weight_observer = mod.qconfig.weight() # type: ignore[union-attr, operator]
|
| 160 |
+
else:
|
| 161 |
+
weight_observer = float_qparams_weight_only_qconfig.weight()
|
| 162 |
+
|
| 163 |
+
dtype = weight_observer.dtype
|
| 164 |
+
is_float_qparams_qconfig = weight_observer.qscheme == torch.per_channel_affine_float_qparams
|
| 165 |
+
assert is_float_qparams_qconfig, \
|
| 166 |
+
'Embedding quantization is only supported with float_qparams_weight_only_qconfig.'
|
| 167 |
+
|
| 168 |
+
assert dtype == torch.quint8 or dtype == torch.quint4x2, \
|
| 169 |
+
f'The only supported dtype for nnq.Embedding is torch.quint8 and torch.quint4x2, got {dtype}'
|
| 170 |
+
|
| 171 |
+
# Run the observer to calculate qparams.
|
| 172 |
+
weight_observer(mod.weight)
|
| 173 |
+
qweight = _quantize_weight(mod.weight.float(), weight_observer)
|
| 174 |
+
|
| 175 |
+
# Create quantized Embedding module and pass in the quantized weight
|
| 176 |
+
qembedding = Embedding(mod.num_embeddings, mod.embedding_dim)
|
| 177 |
+
qembedding.set_weight(qweight)
|
| 178 |
+
return qembedding
|
| 179 |
+
|
| 180 |
+
@classmethod
|
| 181 |
+
def from_reference(cls, ref_embedding):
|
| 182 |
+
qembedding = cls(
|
| 183 |
+
ref_embedding.num_embeddings,
|
| 184 |
+
ref_embedding.embedding_dim,
|
| 185 |
+
ref_embedding.padding_idx,
|
| 186 |
+
ref_embedding.max_norm,
|
| 187 |
+
ref_embedding.norm_type,
|
| 188 |
+
ref_embedding.scale_grad_by_freq,
|
| 189 |
+
ref_embedding.sparse,
|
| 190 |
+
ref_embedding.get_quantized_weight(),
|
| 191 |
+
ref_embedding.weight_dtype,
|
| 192 |
+
)
|
| 193 |
+
return qembedding
|
| 194 |
+
|
| 195 |
+
class EmbeddingBag(Embedding):
|
| 196 |
+
r"""
|
| 197 |
+
A quantized EmbeddingBag module with quantized packed weights as inputs.
|
| 198 |
+
We adopt the same interface as `torch.nn.EmbeddingBag`, please see
|
| 199 |
+
https://pytorch.org/docs/stable/nn.html#torch.nn.EmbeddingBag for documentation.
|
| 200 |
+
|
| 201 |
+
Similar to :class:`~torch.nn.EmbeddingBag`, attributes will be randomly
|
| 202 |
+
initialized at module creation time and will be overwritten later
|
| 203 |
+
|
| 204 |
+
Attributes:
|
| 205 |
+
weight (Tensor): the non-learnable quantized weights of the module of
|
| 206 |
+
shape :math:`(\text{num\_embeddings}, \text{embedding\_dim})`.
|
| 207 |
+
|
| 208 |
+
Examples::
|
| 209 |
+
>>> m = nn.quantized.EmbeddingBag(num_embeddings=10, embedding_dim=12, include_last_offset=True, mode='sum')
|
| 210 |
+
>>> 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])
|
| 211 |
+
>>> offsets = torch.tensor([0, 19, 20, 28, 28, 32])
|
| 212 |
+
>>> output = m(indices, offsets)
|
| 213 |
+
>>> print(output.size())
|
| 214 |
+
torch.Size([5, 12])
|
| 215 |
+
|
| 216 |
+
"""
|
| 217 |
+
_version = 1
|
| 218 |
+
|
| 219 |
+
def __init__(self, num_embeddings: int, embedding_dim: int,
|
| 220 |
+
max_norm: Optional[float] = None, norm_type: float = 2., scale_grad_by_freq: bool = False,
|
| 221 |
+
mode: str = 'sum', sparse: bool = False, _weight: Optional[Tensor] = None,
|
| 222 |
+
include_last_offset: bool = False, dtype=torch.quint8) -> None:
|
| 223 |
+
super().__init__(num_embeddings, embedding_dim, _weight=_weight, dtype=dtype)
|
| 224 |
+
|
| 225 |
+
self.mode = mode
|
| 226 |
+
self.pruned_weights = False
|
| 227 |
+
self.include_last_offset = include_last_offset
|
| 228 |
+
self.dtype = dtype
|
| 229 |
+
|
| 230 |
+
def forward(self, indices: Tensor, offsets: Optional[Tensor] = None, per_sample_weights: Optional[Tensor] = None,
|
| 231 |
+
compressed_indices_mapping: Optional[Tensor] = None) -> Tensor:
|
| 232 |
+
if self.dtype == torch.quint4x2:
|
| 233 |
+
return torch.ops.quantized.embedding_bag_4bit(self._packed_params._packed_weight, indices, offsets, False, 0,
|
| 234 |
+
self.pruned_weights, per_sample_weights, compressed_indices_mapping,
|
| 235 |
+
self.include_last_offset)
|
| 236 |
+
else:
|
| 237 |
+
return torch.ops.quantized.embedding_bag_byte(self._packed_params._packed_weight, indices, offsets, False, 0,
|
| 238 |
+
self.pruned_weights, per_sample_weights, compressed_indices_mapping,
|
| 239 |
+
self.include_last_offset)
|
| 240 |
+
|
| 241 |
+
def _get_name(self):
|
| 242 |
+
return 'QuantizedEmbeddingBag'
|
| 243 |
+
|
| 244 |
+
@classmethod
|
| 245 |
+
def from_float(cls, mod):
|
| 246 |
+
r"""Create a quantized embedding_bag module from a float module
|
| 247 |
+
|
| 248 |
+
Args:
|
| 249 |
+
mod (Module): a float module, either produced by torch.ao.quantization
|
| 250 |
+
utilities or provided by user
|
| 251 |
+
"""
|
| 252 |
+
if hasattr(mod, 'weight_fake_quant'):
|
| 253 |
+
weight_observer = mod.weight_fake_quant
|
| 254 |
+
else:
|
| 255 |
+
assert type(mod) == nn.EmbeddingBag, 'nnq.' + cls.__name__ + '.from_float only works for ' + \
|
| 256 |
+
nn.EmbeddingBag.__name__
|
| 257 |
+
assert hasattr(mod, 'qconfig'), 'EmbeddingBag input float module must have qconfig defined'
|
| 258 |
+
from torch.ao.quantization.qconfig import float_qparams_weight_only_qconfig
|
| 259 |
+
if mod.qconfig is not None and mod.qconfig.weight is not None: # type: ignore[union-attr]
|
| 260 |
+
weight_observer = mod.qconfig.weight() # type: ignore[union-attr, operator]
|
| 261 |
+
else:
|
| 262 |
+
weight_observer = float_qparams_weight_only_qconfig.weight()
|
| 263 |
+
|
| 264 |
+
dtype = weight_observer.dtype
|
| 265 |
+
is_float_qparams_qconfig = weight_observer.qscheme == torch.per_channel_affine_float_qparams
|
| 266 |
+
assert is_float_qparams_qconfig, \
|
| 267 |
+
'EmbeddingBag quantization is only supported with float_qparams_weight_only_qconfig.'
|
| 268 |
+
|
| 269 |
+
assert dtype == torch.quint8 or dtype == torch.quint4x2, \
|
| 270 |
+
f'The only supported dtype for nnq.EmbeddingBag is torch.quint8 and torch.quint4x2, got {dtype}'
|
| 271 |
+
|
| 272 |
+
# Run the observer to calculate qparams.
|
| 273 |
+
weight_observer(mod.weight)
|
| 274 |
+
qweight = _quantize_weight(mod.weight.float(), weight_observer)
|
| 275 |
+
|
| 276 |
+
# Create quantized EmbeddingBag module and pass in the quantized weight
|
| 277 |
+
qembedding_bag = EmbeddingBag(mod.num_embeddings, mod.embedding_dim, dtype=dtype)
|
| 278 |
+
qembedding_bag.set_weight(qweight)
|
| 279 |
+
return qembedding_bag
|
| 280 |
+
|
| 281 |
+
@classmethod
|
| 282 |
+
def from_reference(cls, ref_embedding_bag):
|
| 283 |
+
qembedding_bag = cls(
|
| 284 |
+
ref_embedding_bag.num_embeddings,
|
| 285 |
+
ref_embedding_bag.embedding_dim,
|
| 286 |
+
ref_embedding_bag.max_norm,
|
| 287 |
+
ref_embedding_bag.norm_type,
|
| 288 |
+
ref_embedding_bag.scale_grad_by_freq,
|
| 289 |
+
ref_embedding_bag.mode,
|
| 290 |
+
ref_embedding_bag.sparse,
|
| 291 |
+
ref_embedding_bag.get_quantized_weight(),
|
| 292 |
+
ref_embedding_bag.include_last_offset,
|
| 293 |
+
ref_embedding_bag.weight_dtype,
|
| 294 |
+
)
|
| 295 |
+
return qembedding_bag
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/functional_modules.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import Tensor
|
| 5 |
+
from torch._ops import ops
|
| 6 |
+
|
| 7 |
+
__all__ = ['FloatFunctional', 'FXFloatFunctional', 'QFunctional']
|
| 8 |
+
|
| 9 |
+
class FloatFunctional(torch.nn.Module):
|
| 10 |
+
r"""State collector class for float operations.
|
| 11 |
+
|
| 12 |
+
The instance of this class can be used instead of the ``torch.`` prefix for
|
| 13 |
+
some operations. See example usage below.
|
| 14 |
+
|
| 15 |
+
.. note::
|
| 16 |
+
|
| 17 |
+
This class does not provide a ``forward`` hook. Instead, you must use
|
| 18 |
+
one of the underlying functions (e.g. ``add``).
|
| 19 |
+
|
| 20 |
+
Examples::
|
| 21 |
+
|
| 22 |
+
>>> f_add = FloatFunctional()
|
| 23 |
+
>>> a = torch.tensor(3.0)
|
| 24 |
+
>>> b = torch.tensor(4.0)
|
| 25 |
+
>>> f_add.add(a, b) # Equivalent to ``torch.add(a, b)``
|
| 26 |
+
|
| 27 |
+
Valid operation names:
|
| 28 |
+
- add
|
| 29 |
+
- cat
|
| 30 |
+
- mul
|
| 31 |
+
- add_relu
|
| 32 |
+
- add_scalar
|
| 33 |
+
- mul_scalar
|
| 34 |
+
"""
|
| 35 |
+
def __init__(self):
|
| 36 |
+
super().__init__()
|
| 37 |
+
self.activation_post_process = torch.nn.Identity()
|
| 38 |
+
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
raise RuntimeError("FloatFunctional is not intended to use the " +
|
| 41 |
+
"'forward'. Please use the underlying operation")
|
| 42 |
+
|
| 43 |
+
r"""Operation equivalent to ``torch.add(Tensor, Tensor)``"""
|
| 44 |
+
def add(self, x: Tensor, y: Tensor) -> Tensor:
|
| 45 |
+
r = torch.add(x, y)
|
| 46 |
+
r = self.activation_post_process(r)
|
| 47 |
+
return r
|
| 48 |
+
|
| 49 |
+
r"""Operation equivalent to ``torch.add(Tensor, float)``"""
|
| 50 |
+
def add_scalar(self, x: Tensor, y: float) -> Tensor:
|
| 51 |
+
r = torch.add(x, y)
|
| 52 |
+
# Note: this operation is not observed because the observation is not
|
| 53 |
+
# needed for the quantized op.
|
| 54 |
+
return r
|
| 55 |
+
|
| 56 |
+
r"""Operation equivalent to ``torch.mul(Tensor, Tensor)``"""
|
| 57 |
+
def mul(self, x: Tensor, y: Tensor) -> Tensor:
|
| 58 |
+
r = torch.mul(x, y)
|
| 59 |
+
r = self.activation_post_process(r)
|
| 60 |
+
return r
|
| 61 |
+
|
| 62 |
+
r"""Operation equivalent to ``torch.mul(Tensor, float)``"""
|
| 63 |
+
def mul_scalar(self, x: Tensor, y: float) -> Tensor:
|
| 64 |
+
r = torch.mul(x, y)
|
| 65 |
+
# Note: this operation is not observed because the observation is not
|
| 66 |
+
# needed for the quantized op.
|
| 67 |
+
return r
|
| 68 |
+
|
| 69 |
+
r"""Operation equivalent to ``torch.cat``"""
|
| 70 |
+
def cat(self, x: List[Tensor], dim: int = 0) -> Tensor:
|
| 71 |
+
r = torch.cat(x, dim=dim)
|
| 72 |
+
r = self.activation_post_process(r)
|
| 73 |
+
return r
|
| 74 |
+
|
| 75 |
+
r"""Operation equivalent to ``relu(torch.add(x,y))``"""
|
| 76 |
+
def add_relu(self, x: Tensor, y: Tensor) -> Tensor:
|
| 77 |
+
r = torch.add(x, y)
|
| 78 |
+
r = torch.nn.functional.relu(r)
|
| 79 |
+
r = self.activation_post_process(r)
|
| 80 |
+
return r
|
| 81 |
+
|
| 82 |
+
r"""Operation equivalent to ``torch.matmul(Tensor, Tensor)``"""
|
| 83 |
+
def matmul(self, x: Tensor, y: Tensor) -> Tensor:
|
| 84 |
+
r = torch.matmul(x, y)
|
| 85 |
+
r = self.activation_post_process(r)
|
| 86 |
+
return r
|
| 87 |
+
|
| 88 |
+
class FXFloatFunctional(torch.nn.Module):
|
| 89 |
+
r""" module to replace FloatFunctional module before FX graph mode quantization,
|
| 90 |
+
since activation_post_process will be inserted in top level module directly
|
| 91 |
+
|
| 92 |
+
Valid operation names:
|
| 93 |
+
- add
|
| 94 |
+
- cat
|
| 95 |
+
- mul
|
| 96 |
+
- add_relu
|
| 97 |
+
- add_scalar
|
| 98 |
+
- mul_scalar
|
| 99 |
+
"""
|
| 100 |
+
def forward(self, x):
|
| 101 |
+
raise RuntimeError("FloatFunctional is not intended to use the " +
|
| 102 |
+
"'forward'. Please use the underlying operation")
|
| 103 |
+
|
| 104 |
+
r"""Operation equivalent to ``torch.add(Tensor, Tensor)``"""
|
| 105 |
+
def add(self, x: Tensor, y: Tensor) -> Tensor:
|
| 106 |
+
r = torch.add(x, y)
|
| 107 |
+
return r
|
| 108 |
+
|
| 109 |
+
r"""Operation equivalent to ``torch.add(Tensor, float)``"""
|
| 110 |
+
def add_scalar(self, x: Tensor, y: float) -> Tensor:
|
| 111 |
+
r = torch.add(x, y)
|
| 112 |
+
return r
|
| 113 |
+
|
| 114 |
+
r"""Operation equivalent to ``torch.mul(Tensor, Tensor)``"""
|
| 115 |
+
def mul(self, x: Tensor, y: Tensor) -> Tensor:
|
| 116 |
+
r = torch.mul(x, y)
|
| 117 |
+
return r
|
| 118 |
+
|
| 119 |
+
r"""Operation equivalent to ``torch.mul(Tensor, float)``"""
|
| 120 |
+
def mul_scalar(self, x: Tensor, y: float) -> Tensor:
|
| 121 |
+
r = torch.mul(x, y)
|
| 122 |
+
return r
|
| 123 |
+
|
| 124 |
+
r"""Operation equivalent to ``torch.cat``"""
|
| 125 |
+
def cat(self, x: List[Tensor], dim: int = 0) -> Tensor:
|
| 126 |
+
r = torch.cat(x, dim=dim)
|
| 127 |
+
return r
|
| 128 |
+
|
| 129 |
+
r"""Operation equivalent to ``relu(torch.add(x,y))``"""
|
| 130 |
+
def add_relu(self, x: Tensor, y: Tensor) -> Tensor:
|
| 131 |
+
r = torch.add(x, y)
|
| 132 |
+
r = torch.nn.functional.relu(r)
|
| 133 |
+
return r
|
| 134 |
+
|
| 135 |
+
r"""Operation equivalent to ``torch.matmul(Tensor, Tensor)``"""
|
| 136 |
+
def matmul(self, x: Tensor, y: Tensor) -> Tensor:
|
| 137 |
+
r = torch.matmul(x, y)
|
| 138 |
+
return r
|
| 139 |
+
|
| 140 |
+
class QFunctional(torch.nn.Module):
|
| 141 |
+
r"""Wrapper class for quantized operations.
|
| 142 |
+
|
| 143 |
+
The instance of this class can be used instead of the
|
| 144 |
+
``torch.ops.quantized`` prefix. See example usage below.
|
| 145 |
+
|
| 146 |
+
.. note::
|
| 147 |
+
|
| 148 |
+
This class does not provide a ``forward`` hook. Instead, you must use
|
| 149 |
+
one of the underlying functions (e.g. ``add``).
|
| 150 |
+
|
| 151 |
+
Examples::
|
| 152 |
+
|
| 153 |
+
>>> q_add = QFunctional()
|
| 154 |
+
>>> # xdoctest: +SKIP
|
| 155 |
+
>>> a = torch.quantize_per_tensor(torch.tensor(3.0), 1.0, 0, torch.qint32)
|
| 156 |
+
>>> b = torch.quantize_per_tensor(torch.tensor(4.0), 1.0, 0, torch.qint32)
|
| 157 |
+
>>> q_add.add(a, b) # Equivalent to ``torch.ops.quantized.add(a, b, 1.0, 0)``
|
| 158 |
+
|
| 159 |
+
Valid operation names:
|
| 160 |
+
- add
|
| 161 |
+
- cat
|
| 162 |
+
- mul
|
| 163 |
+
- add_relu
|
| 164 |
+
- add_scalar
|
| 165 |
+
- mul_scalar
|
| 166 |
+
"""
|
| 167 |
+
def __init__(self):
|
| 168 |
+
super().__init__()
|
| 169 |
+
self.scale = 1.0
|
| 170 |
+
self.zero_point = 0
|
| 171 |
+
self.activation_post_process = torch.nn.Identity()
|
| 172 |
+
|
| 173 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
| 174 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
| 175 |
+
destination[prefix + 'scale'] = torch.tensor(self.scale)
|
| 176 |
+
destination[prefix + 'zero_point'] = torch.tensor(self.zero_point)
|
| 177 |
+
|
| 178 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
|
| 179 |
+
missing_keys, unexpected_keys, error_msgs):
|
| 180 |
+
|
| 181 |
+
self.scale = float(state_dict.pop(prefix + 'scale'))
|
| 182 |
+
self.zero_point = int(state_dict.pop(prefix + 'zero_point'))
|
| 183 |
+
super()._load_from_state_dict(state_dict, prefix, local_metadata, False,
|
| 184 |
+
missing_keys, unexpected_keys, error_msgs)
|
| 185 |
+
|
| 186 |
+
def _get_name(self):
|
| 187 |
+
return 'QFunctional'
|
| 188 |
+
|
| 189 |
+
def extra_repr(self):
|
| 190 |
+
return f'scale={self.scale}, zero_point={self.zero_point}'
|
| 191 |
+
|
| 192 |
+
def forward(self, x):
|
| 193 |
+
raise RuntimeError("Functional is not intended to use the " +
|
| 194 |
+
"'forward'. Please use the underlying operation")
|
| 195 |
+
|
| 196 |
+
r"""Operation equivalent to ``torch.ops.quantized.add``"""
|
| 197 |
+
def add(self, x: Tensor, y: Tensor) -> Tensor:
|
| 198 |
+
r = ops.quantized.add(x, y, scale=self.scale, zero_point=self.zero_point)
|
| 199 |
+
r = self.activation_post_process(r)
|
| 200 |
+
return r
|
| 201 |
+
|
| 202 |
+
r"""Operation equivalent to ``torch.ops.quantized.add(Tensor, float)``"""
|
| 203 |
+
def add_scalar(self, x: Tensor, y: float) -> Tensor:
|
| 204 |
+
r = ops.quantized.add_scalar(x, y)
|
| 205 |
+
# Note: this operation is not observed because the observation is not
|
| 206 |
+
# needed for the quantized op.
|
| 207 |
+
return r
|
| 208 |
+
|
| 209 |
+
r"""Operation equivalent to ``torch.ops.quantized.mul(Tensor, Tensor)``"""
|
| 210 |
+
def mul(self, x: Tensor, y: Tensor) -> Tensor:
|
| 211 |
+
r = ops.quantized.mul(x, y, scale=self.scale, zero_point=self.zero_point)
|
| 212 |
+
r = self.activation_post_process(r)
|
| 213 |
+
return r
|
| 214 |
+
|
| 215 |
+
r"""Operation equivalent to ``torch.ops.quantized.mul(Tensor, float)``"""
|
| 216 |
+
def mul_scalar(self, x: Tensor, y: float) -> Tensor:
|
| 217 |
+
r = ops.quantized.mul_scalar(x, y)
|
| 218 |
+
# Note: this operation is not observed because the observation is not
|
| 219 |
+
# needed for the quantized op.
|
| 220 |
+
return r
|
| 221 |
+
|
| 222 |
+
r"""Operation equivalent to ``torch.ops.quantized.cat``"""
|
| 223 |
+
def cat(self, x: List[Tensor], dim: int = 0) -> Tensor:
|
| 224 |
+
r = ops.quantized.cat(x, scale=self.scale, zero_point=self.zero_point, dim=dim)
|
| 225 |
+
r = self.activation_post_process(r)
|
| 226 |
+
return r
|
| 227 |
+
|
| 228 |
+
r"""Operation equivalent to ``torch.ops.quantized.add_relu``"""
|
| 229 |
+
def add_relu(self, x: Tensor, y: Tensor) -> Tensor:
|
| 230 |
+
r = ops.quantized.add_relu(x, y, scale=self.scale, zero_point=self.zero_point)
|
| 231 |
+
r = self.activation_post_process(r)
|
| 232 |
+
return r
|
| 233 |
+
|
| 234 |
+
r"""Operation equivalent to ``torch.ops.quantized.matmul(Tensor, Tensor)``"""
|
| 235 |
+
def matmul(self, x: Tensor, y: Tensor) -> Tensor:
|
| 236 |
+
r = ops.quantized.matmul(x, y, scale=self.scale, zero_point=self.zero_point)
|
| 237 |
+
# Note: this operation is not observed because the observation is not
|
| 238 |
+
# needed for the quantized op.
|
| 239 |
+
return r
|
| 240 |
+
|
| 241 |
+
@classmethod
|
| 242 |
+
def from_float(cls, mod):
|
| 243 |
+
assert type(mod) == FloatFunctional,\
|
| 244 |
+
"QFunctional.from_float expects an instance of FloatFunctional"
|
| 245 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams() # type: ignore[operator]
|
| 246 |
+
new_mod = QFunctional()
|
| 247 |
+
new_mod.scale = float(scale)
|
| 248 |
+
new_mod.zero_point = int(zero_point)
|
| 249 |
+
return new_mod
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/mod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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Iterable
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.ao.nn.intrinsic as nni
|
| 6 |
+
import torch.ao.nn.intrinsic.qat as nniqat
|
| 7 |
+
from torch.nn.utils.fusion import fuse_linear_bn_weights
|
| 8 |
+
from torch.nn.utils.parametrize import type_before_parametrizations
|
| 9 |
+
|
| 10 |
+
from typing import Optional
|
| 11 |
+
|
| 12 |
+
from .utils import _quantize_weight, _hide_packed_params_repr, WeightedQuantizedModule
|
| 13 |
+
|
| 14 |
+
__all__ = ['LinearPackedParams', 'Linear']
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class LinearPackedParams(torch.nn.Module):
|
| 18 |
+
_version = 3
|
| 19 |
+
|
| 20 |
+
def __init__(self, dtype=torch.qint8):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.dtype = dtype
|
| 23 |
+
if self.dtype == torch.qint8:
|
| 24 |
+
wq = torch._empty_affine_quantized([1, 1], scale=1.0, zero_point=0, dtype=torch.qint8)
|
| 25 |
+
elif self.dtype == torch.float16:
|
| 26 |
+
wq = torch.zeros([1, 1], dtype=torch.float)
|
| 27 |
+
self.set_weight_bias(wq, None)
|
| 28 |
+
|
| 29 |
+
@torch.jit.export
|
| 30 |
+
def set_weight_bias(self, weight: torch.Tensor, bias: Optional[torch.Tensor]) -> None:
|
| 31 |
+
if self.dtype == torch.qint8:
|
| 32 |
+
self._packed_params = torch.ops.quantized.linear_prepack(weight, bias)
|
| 33 |
+
elif self.dtype == torch.float16:
|
| 34 |
+
self._packed_params = torch.ops.quantized.linear_prepack_fp16(weight, bias)
|
| 35 |
+
else:
|
| 36 |
+
raise RuntimeError('Unsupported dtype on dynamic quantized linear!')
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@torch.jit.export
|
| 40 |
+
def _weight_bias(self):
|
| 41 |
+
if self.dtype == torch.qint8:
|
| 42 |
+
return torch.ops.quantized.linear_unpack(self._packed_params)
|
| 43 |
+
elif self.dtype == torch.float16:
|
| 44 |
+
return torch.ops.quantized.linear_unpack_fp16(self._packed_params)
|
| 45 |
+
else:
|
| 46 |
+
raise RuntimeError('Unsupported dtype on dynamic quantized linear!')
|
| 47 |
+
|
| 48 |
+
def forward(self, x):
|
| 49 |
+
return x
|
| 50 |
+
|
| 51 |
+
# Version 1
|
| 52 |
+
# self
|
| 53 |
+
# |--- weight : Tensor
|
| 54 |
+
# |--- bias : Tensor
|
| 55 |
+
#
|
| 56 |
+
# Version 2
|
| 57 |
+
# self
|
| 58 |
+
# |--- weight : Tensor
|
| 59 |
+
# |--- bias : Tensor
|
| 60 |
+
# |--- dtype : torch.dtype
|
| 61 |
+
#
|
| 62 |
+
# Version 3
|
| 63 |
+
# self
|
| 64 |
+
# |--- _packed_params : (Tensor, Tensor) representing (weight, bias)
|
| 65 |
+
# of LinearPackedParams
|
| 66 |
+
# |--- dtype : torch.dtype
|
| 67 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
| 68 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
| 69 |
+
destination[prefix + 'dtype'] = self.dtype
|
| 70 |
+
destination[prefix + '_packed_params'] = self._weight_bias()
|
| 71 |
+
|
| 72 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
|
| 73 |
+
missing_keys, unexpected_keys, error_msgs):
|
| 74 |
+
version = local_metadata.get('version', None)
|
| 75 |
+
if version is None or version < 2:
|
| 76 |
+
self.dtype = torch.qint8
|
| 77 |
+
else:
|
| 78 |
+
self.dtype = state_dict[prefix + 'dtype']
|
| 79 |
+
state_dict.pop(prefix + 'dtype')
|
| 80 |
+
|
| 81 |
+
if version is None or version < 3:
|
| 82 |
+
self.set_weight_bias(state_dict[prefix + 'weight'], state_dict[prefix + 'bias'])
|
| 83 |
+
state_dict.pop(prefix + 'weight')
|
| 84 |
+
state_dict.pop(prefix + 'bias')
|
| 85 |
+
|
| 86 |
+
if version == 3:
|
| 87 |
+
weight, bias = state_dict[prefix + '_packed_params']
|
| 88 |
+
state_dict.pop(prefix + '_packed_params')
|
| 89 |
+
self.set_weight_bias(weight, bias)
|
| 90 |
+
|
| 91 |
+
super()._load_from_state_dict(state_dict, prefix, local_metadata, False,
|
| 92 |
+
missing_keys, unexpected_keys, error_msgs)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def __repr__(self):
|
| 96 |
+
return self._weight_bias().__repr__()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class Linear(WeightedQuantizedModule):
|
| 100 |
+
r"""
|
| 101 |
+
A quantized linear module with quantized tensor as inputs and outputs.
|
| 102 |
+
We adopt the same interface as `torch.nn.Linear`, please see
|
| 103 |
+
https://pytorch.org/docs/stable/nn.html#torch.nn.Linear for documentation.
|
| 104 |
+
|
| 105 |
+
Similar to :class:`~torch.nn.Linear`, attributes will be randomly
|
| 106 |
+
initialized at module creation time and will be overwritten later
|
| 107 |
+
|
| 108 |
+
Attributes:
|
| 109 |
+
weight (Tensor): the non-learnable quantized weights of the module of
|
| 110 |
+
shape :math:`(\text{out\_features}, \text{in\_features})`.
|
| 111 |
+
bias (Tensor): the non-learnable bias of the module of shape :math:`(\text{out\_features})`.
|
| 112 |
+
If :attr:`bias` is ``True``, the values are initialized to zero.
|
| 113 |
+
scale: `scale` parameter of output Quantized Tensor, type: double
|
| 114 |
+
zero_point: `zero_point` parameter for output Quantized Tensor, type: long
|
| 115 |
+
|
| 116 |
+
Examples::
|
| 117 |
+
|
| 118 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_QENGINE)
|
| 119 |
+
>>> m = nn.quantized.Linear(20, 30)
|
| 120 |
+
>>> input = torch.randn(128, 20)
|
| 121 |
+
>>> # xdoctest: +SKIP
|
| 122 |
+
>>> input = torch.quantize_per_tensor(input, 1.0, 0, torch.quint8)
|
| 123 |
+
>>> output = m(input)
|
| 124 |
+
>>> print(output.size())
|
| 125 |
+
torch.Size([128, 30])
|
| 126 |
+
"""
|
| 127 |
+
_version = 3
|
| 128 |
+
_FLOAT_MODULE = (nn.Linear, nn.modules.linear.NonDynamicallyQuantizableLinear)
|
| 129 |
+
|
| 130 |
+
def __init__(self, in_features, out_features, bias_=True,
|
| 131 |
+
dtype=torch.qint8):
|
| 132 |
+
super().__init__()
|
| 133 |
+
# We don't muck around with buffers or attributes or anything here
|
| 134 |
+
# to keep the module simple. *everything* is simply a Python attribute.
|
| 135 |
+
# Serialization logic is explicitly handled in the below serialization and
|
| 136 |
+
# deserialization modules
|
| 137 |
+
self.in_features = in_features
|
| 138 |
+
self.out_features = out_features
|
| 139 |
+
bias = None
|
| 140 |
+
if bias_:
|
| 141 |
+
bias = torch.zeros(out_features, dtype=torch.float)
|
| 142 |
+
|
| 143 |
+
if dtype == torch.qint8:
|
| 144 |
+
qweight = torch._empty_affine_quantized(
|
| 145 |
+
[out_features, in_features], scale=1, zero_point=0, dtype=torch.qint8)
|
| 146 |
+
elif dtype == torch.float16:
|
| 147 |
+
qweight = torch.zeros([out_features, in_features], dtype=torch.float)
|
| 148 |
+
else:
|
| 149 |
+
raise RuntimeError('Unsupported dtype specified for quantized Linear!')
|
| 150 |
+
|
| 151 |
+
self._packed_params = LinearPackedParams(dtype)
|
| 152 |
+
self._packed_params.set_weight_bias(qweight, bias)
|
| 153 |
+
self.scale = 1.0
|
| 154 |
+
self.zero_point = 0
|
| 155 |
+
|
| 156 |
+
def _get_name(self):
|
| 157 |
+
return 'QuantizedLinear'
|
| 158 |
+
|
| 159 |
+
def extra_repr(self):
|
| 160 |
+
return 'in_features={}, out_features={}, scale={}, zero_point={}, qscheme={}'.format(
|
| 161 |
+
self.in_features, self.out_features, self.scale, self.zero_point, self.weight().qscheme()
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def __repr__(self):
|
| 165 |
+
return _hide_packed_params_repr(self, LinearPackedParams)
|
| 166 |
+
|
| 167 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 168 |
+
return torch.ops.quantized.linear(
|
| 169 |
+
x, self._packed_params._packed_params, self.scale, self.zero_point)
|
| 170 |
+
|
| 171 |
+
# ===== Serialization methods =====
|
| 172 |
+
# The special consideration here is that we have to unpack the weights into their
|
| 173 |
+
# regular QTensor form for serialization. Packed weights should not live
|
| 174 |
+
# outside the process in which they were created, rather they should be derived
|
| 175 |
+
# from the QTensor weight.
|
| 176 |
+
#
|
| 177 |
+
# Version 1
|
| 178 |
+
# self
|
| 179 |
+
# |--- scale : float
|
| 180 |
+
# |--- zero_point : int
|
| 181 |
+
# |--- weight : Tensor
|
| 182 |
+
# |--- bias : Tensor
|
| 183 |
+
#
|
| 184 |
+
# Version 2
|
| 185 |
+
# self
|
| 186 |
+
# |--- scale : float
|
| 187 |
+
# |--- zero_point : int
|
| 188 |
+
# |--- _packed_params : Module
|
| 189 |
+
# |--- weight : Tensor
|
| 190 |
+
# |--- bias : Tensor
|
| 191 |
+
#
|
| 192 |
+
# Version 3
|
| 193 |
+
# self
|
| 194 |
+
# |--- scale : float
|
| 195 |
+
# |--- zero_point : int
|
| 196 |
+
# |--- _packed_params : Module
|
| 197 |
+
# |--- _packed_params : (Tensor, Tensor) representing weight, bias
|
| 198 |
+
# of LinearPackedParams C++ struct
|
| 199 |
+
#
|
| 200 |
+
def _save_to_state_dict(self, destination, prefix, keep_vars):
|
| 201 |
+
super()._save_to_state_dict(destination, prefix, keep_vars)
|
| 202 |
+
destination[prefix + 'scale'] = torch.tensor(self.scale)
|
| 203 |
+
destination[prefix + 'zero_point'] = torch.tensor(self.zero_point)
|
| 204 |
+
|
| 205 |
+
# ===== Deserialization methods =====
|
| 206 |
+
# Counterpart to the serialization methods, we must pack the serialized QTensor
|
| 207 |
+
# weight into its packed format for use by the FBGEMM ops.
|
| 208 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
|
| 209 |
+
missing_keys, unexpected_keys, error_msgs):
|
| 210 |
+
self.scale = float(state_dict[prefix + 'scale'])
|
| 211 |
+
state_dict.pop(prefix + 'scale')
|
| 212 |
+
|
| 213 |
+
self.zero_point = int(state_dict[prefix + 'zero_point'])
|
| 214 |
+
state_dict.pop(prefix + 'zero_point')
|
| 215 |
+
|
| 216 |
+
version = local_metadata.get('version', None)
|
| 217 |
+
|
| 218 |
+
if version is None or version == 1:
|
| 219 |
+
# We moved the parameters into a LinearPackedParameters submodule
|
| 220 |
+
weight = state_dict.pop(prefix + 'weight')
|
| 221 |
+
bias = state_dict.pop(prefix + 'bias')
|
| 222 |
+
state_dict.update({prefix + '_packed_params.weight': weight,
|
| 223 |
+
prefix + '_packed_params.bias': bias})
|
| 224 |
+
|
| 225 |
+
super()._load_from_state_dict(
|
| 226 |
+
state_dict, prefix, local_metadata, False,
|
| 227 |
+
missing_keys, unexpected_keys, error_msgs)
|
| 228 |
+
|
| 229 |
+
# Function rather than property to make sure that JIT serialization doesn't
|
| 230 |
+
# register this as an attribute
|
| 231 |
+
def _weight_bias(self):
|
| 232 |
+
return self._packed_params._weight_bias()
|
| 233 |
+
|
| 234 |
+
def weight(self):
|
| 235 |
+
return self._weight_bias()[0]
|
| 236 |
+
|
| 237 |
+
def bias(self):
|
| 238 |
+
return self._weight_bias()[1]
|
| 239 |
+
|
| 240 |
+
def set_weight_bias(self, w: torch.Tensor, b: Optional[torch.Tensor]) -> None:
|
| 241 |
+
self._packed_params.set_weight_bias(w, b)
|
| 242 |
+
|
| 243 |
+
@classmethod
|
| 244 |
+
def from_float(cls, mod):
|
| 245 |
+
r"""Create a quantized module from an observed float module
|
| 246 |
+
|
| 247 |
+
Args:
|
| 248 |
+
mod (Module): a float module, either produced by torch.ao.quantization
|
| 249 |
+
utilities or provided by the user
|
| 250 |
+
"""
|
| 251 |
+
if hasattr(mod, 'weight_fake_quant'):
|
| 252 |
+
if type_before_parametrizations(mod) == nniqat.LinearBn1d:
|
| 253 |
+
mod.weight, mod.bias = fuse_linear_bn_weights(
|
| 254 |
+
mod.weight, mod.bias, mod.bn.running_mean, mod.bn.running_var,
|
| 255 |
+
mod.bn.eps, mod.bn.weight, mod.bn.bias)
|
| 256 |
+
weight_post_process = mod.weight_fake_quant
|
| 257 |
+
activation_post_process = mod.activation_post_process
|
| 258 |
+
else:
|
| 259 |
+
# This function does not participate in JIT, so it is OK to ignore
|
| 260 |
+
# the type mismatch in assignment. Also, mypy has an issue with
|
| 261 |
+
# iterables not being implemented, so we are ignoring those too.
|
| 262 |
+
if not isinstance(cls._FLOAT_MODULE, Iterable):
|
| 263 |
+
cls._FLOAT_MODULE = [cls._FLOAT_MODULE] # type: ignore[assignment]
|
| 264 |
+
supported_modules = ', '.join([float_mod.__name__ for float_mod in cls._FLOAT_MODULE]) # type: ignore[attr-defined]
|
| 265 |
+
error_msg = f'nnq.{cls.__name__}.from_float only works for {supported_modules}, but got: {type(mod)}'
|
| 266 |
+
assert type_before_parametrizations(mod) in cls._FLOAT_MODULE, error_msg.format() # type: ignore[attr-defined]
|
| 267 |
+
assert hasattr(mod, 'qconfig'), 'Input float module must have qconfig defined'
|
| 268 |
+
activation_post_process = mod.activation_post_process
|
| 269 |
+
if type_before_parametrizations(mod) == nni.LinearReLU:
|
| 270 |
+
mod = mod[0]
|
| 271 |
+
weight_post_process = mod.qconfig.weight()
|
| 272 |
+
weight_post_process(mod.weight)
|
| 273 |
+
dtype = weight_post_process.dtype
|
| 274 |
+
act_scale, act_zp = activation_post_process.calculate_qparams()
|
| 275 |
+
assert dtype == torch.qint8, 'Weight observer must have dtype torch.qint8'
|
| 276 |
+
qweight = _quantize_weight(mod.weight.float(), weight_post_process)
|
| 277 |
+
qlinear = cls(mod.in_features,
|
| 278 |
+
mod.out_features,
|
| 279 |
+
dtype=dtype)
|
| 280 |
+
qlinear.set_weight_bias(qweight, mod.bias)
|
| 281 |
+
qlinear.scale = float(act_scale)
|
| 282 |
+
qlinear.zero_point = int(act_zp)
|
| 283 |
+
return qlinear
|
| 284 |
+
|
| 285 |
+
@classmethod
|
| 286 |
+
def from_reference(cls, ref_qlinear, output_scale, output_zero_point):
|
| 287 |
+
r"""Create a (fbgemm/qnnpack) quantized module from a reference quantized module
|
| 288 |
+
|
| 289 |
+
Args:
|
| 290 |
+
ref_qlinear (Module): a reference quantized linear module, either produced by torch.ao.quantization
|
| 291 |
+
utilities or provided by the user
|
| 292 |
+
output_scale (float): scale for output Tensor
|
| 293 |
+
output_zero_point (int): zero point for output Tensor
|
| 294 |
+
"""
|
| 295 |
+
qlinear = cls(
|
| 296 |
+
ref_qlinear.in_features,
|
| 297 |
+
ref_qlinear.out_features)
|
| 298 |
+
qweight = ref_qlinear.get_quantized_weight()
|
| 299 |
+
qlinear.set_weight_bias(qweight, ref_qlinear.bias)
|
| 300 |
+
|
| 301 |
+
qlinear.scale = float(output_scale)
|
| 302 |
+
qlinear.zero_point = int(output_zero_point)
|
| 303 |
+
return qlinear
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/normalization.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
__all__ = ['LayerNorm', 'GroupNorm', 'InstanceNorm1d', 'InstanceNorm2d', 'InstanceNorm3d']
|
| 4 |
+
|
| 5 |
+
class LayerNorm(torch.nn.LayerNorm):
|
| 6 |
+
r"""This is the quantized version of :class:`~torch.nn.LayerNorm`.
|
| 7 |
+
|
| 8 |
+
Additional args:
|
| 9 |
+
* **scale** - quantization scale of the output, type: double.
|
| 10 |
+
* **zero_point** - quantization zero point of the output, type: long.
|
| 11 |
+
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
def __init__(self, normalized_shape, weight, bias, scale, zero_point, eps=1e-5,
|
| 15 |
+
elementwise_affine=True, device=None, dtype=None) -> None:
|
| 16 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 17 |
+
super().__init__(normalized_shape, eps=eps, elementwise_affine=elementwise_affine,
|
| 18 |
+
**factory_kwargs)
|
| 19 |
+
self.weight = weight
|
| 20 |
+
self.bias = bias
|
| 21 |
+
self.register_buffer('scale', torch.tensor(scale, **factory_kwargs))
|
| 22 |
+
self.register_buffer('zero_point', torch.tensor(zero_point, **factory_kwargs))
|
| 23 |
+
|
| 24 |
+
def forward(self, input):
|
| 25 |
+
return torch.ops.quantized.layer_norm(
|
| 26 |
+
input, self.normalized_shape, weight=self.weight, bias=self.bias,
|
| 27 |
+
eps=self.eps, output_scale=self.scale, output_zero_point=self.zero_point)
|
| 28 |
+
|
| 29 |
+
def _get_name(self):
|
| 30 |
+
return 'QuantizedLayerNorm'
|
| 31 |
+
|
| 32 |
+
@classmethod
|
| 33 |
+
def from_float(cls, mod):
|
| 34 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 35 |
+
new_mod = cls(
|
| 36 |
+
mod.normalized_shape, mod.weight, mod.bias, float(scale),
|
| 37 |
+
int(zero_point), mod.eps, mod.elementwise_affine)
|
| 38 |
+
return new_mod
|
| 39 |
+
|
| 40 |
+
@classmethod
|
| 41 |
+
def from_reference(cls, mod, scale, zero_point):
|
| 42 |
+
return cls(
|
| 43 |
+
mod.normalized_shape, mod.weight, mod.bias, float(scale),
|
| 44 |
+
int(zero_point), mod.eps, mod.elementwise_affine)
|
| 45 |
+
|
| 46 |
+
class GroupNorm(torch.nn.GroupNorm):
|
| 47 |
+
r"""This is the quantized version of :class:`~torch.nn.GroupNorm`.
|
| 48 |
+
|
| 49 |
+
Additional args:
|
| 50 |
+
* **scale** - quantization scale of the output, type: double.
|
| 51 |
+
* **zero_point** - quantization zero point of the output, type: long.
|
| 52 |
+
|
| 53 |
+
"""
|
| 54 |
+
__constants__ = ['num_groups', 'num_channels', 'eps', 'affine']
|
| 55 |
+
|
| 56 |
+
def __init__(self, num_groups, num_channels, weight, bias, scale, zero_point, eps=1e-5,
|
| 57 |
+
affine=True, device=None, dtype=None) -> None:
|
| 58 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 59 |
+
super().__init__(num_groups, num_channels, eps, affine, **factory_kwargs)
|
| 60 |
+
self.weight = weight
|
| 61 |
+
self.bias = bias
|
| 62 |
+
self.register_buffer('scale', torch.tensor(scale, **factory_kwargs))
|
| 63 |
+
self.register_buffer('zero_point', torch.tensor(zero_point, **factory_kwargs))
|
| 64 |
+
|
| 65 |
+
def forward(self, input):
|
| 66 |
+
return torch.ops.quantized.group_norm(
|
| 67 |
+
input, self.num_groups, self.weight, self.bias, self.eps, self.scale,
|
| 68 |
+
self.zero_point)
|
| 69 |
+
|
| 70 |
+
def _get_name(self):
|
| 71 |
+
return 'QuantizedGroupNorm'
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
def from_float(cls, mod):
|
| 75 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 76 |
+
new_mod = cls(
|
| 77 |
+
mod.num_groups, mod.num_channels, mod.weight, mod.bias, float(scale), int(zero_point),
|
| 78 |
+
mod.eps, mod.affine)
|
| 79 |
+
return new_mod
|
| 80 |
+
|
| 81 |
+
class InstanceNorm1d(torch.nn.InstanceNorm1d):
|
| 82 |
+
r"""This is the quantized version of :class:`~torch.nn.InstanceNorm1d`.
|
| 83 |
+
|
| 84 |
+
Additional args:
|
| 85 |
+
* **scale** - quantization scale of the output, type: double.
|
| 86 |
+
* **zero_point** - quantization zero point of the output, type: long.
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
def __init__(self, num_features, weight, bias, scale, zero_point,
|
| 90 |
+
eps=1e-5, momentum=0.1, affine=False,
|
| 91 |
+
track_running_stats=False, device=None, dtype=None) -> None:
|
| 92 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 93 |
+
super().__init__(num_features, eps, momentum, affine, track_running_stats, **factory_kwargs)
|
| 94 |
+
self.weight = weight
|
| 95 |
+
self.bias = bias
|
| 96 |
+
self.register_buffer('scale', torch.tensor(scale, **factory_kwargs))
|
| 97 |
+
self.register_buffer('zero_point', torch.tensor(zero_point, **factory_kwargs))
|
| 98 |
+
|
| 99 |
+
def forward(self, input):
|
| 100 |
+
return torch.ops.quantized.instance_norm(
|
| 101 |
+
input, self.weight, self.bias, self.eps, self.scale,
|
| 102 |
+
self.zero_point)
|
| 103 |
+
|
| 104 |
+
def _get_name(self):
|
| 105 |
+
return 'QuantizedInstanceNorm1d'
|
| 106 |
+
|
| 107 |
+
@classmethod
|
| 108 |
+
def from_float(cls, mod):
|
| 109 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 110 |
+
new_mod = cls(
|
| 111 |
+
mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point),
|
| 112 |
+
mod.eps, mod.affine)
|
| 113 |
+
return new_mod
|
| 114 |
+
|
| 115 |
+
@classmethod
|
| 116 |
+
def from_reference(cls, mod, scale, zero_point):
|
| 117 |
+
return cls(
|
| 118 |
+
mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point),
|
| 119 |
+
mod.eps, mod.affine)
|
| 120 |
+
|
| 121 |
+
class InstanceNorm2d(torch.nn.InstanceNorm2d):
|
| 122 |
+
r"""This is the quantized version of :class:`~torch.nn.InstanceNorm2d`.
|
| 123 |
+
|
| 124 |
+
Additional args:
|
| 125 |
+
* **scale** - quantization scale of the output, type: double.
|
| 126 |
+
* **zero_point** - quantization zero point of the output, type: long.
|
| 127 |
+
|
| 128 |
+
"""
|
| 129 |
+
def __init__(self, num_features, weight, bias, scale, zero_point,
|
| 130 |
+
eps=1e-5, momentum=0.1, affine=False,
|
| 131 |
+
track_running_stats=False, device=None, dtype=None) -> None:
|
| 132 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 133 |
+
super().__init__(num_features, eps, momentum, affine, track_running_stats, **factory_kwargs)
|
| 134 |
+
self.weight = weight
|
| 135 |
+
self.bias = bias
|
| 136 |
+
self.register_buffer('scale', torch.tensor(scale, **factory_kwargs))
|
| 137 |
+
self.register_buffer('zero_point', torch.tensor(zero_point, **factory_kwargs))
|
| 138 |
+
|
| 139 |
+
def forward(self, input):
|
| 140 |
+
return torch.ops.quantized.instance_norm(
|
| 141 |
+
input, self.weight, self.bias, self.eps, self.scale,
|
| 142 |
+
self.zero_point)
|
| 143 |
+
|
| 144 |
+
def _get_name(self):
|
| 145 |
+
return 'QuantizedInstanceNorm2d'
|
| 146 |
+
|
| 147 |
+
@classmethod
|
| 148 |
+
def from_float(cls, mod):
|
| 149 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 150 |
+
new_mod = cls(
|
| 151 |
+
mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point),
|
| 152 |
+
mod.eps, mod.affine)
|
| 153 |
+
return new_mod
|
| 154 |
+
|
| 155 |
+
@classmethod
|
| 156 |
+
def from_reference(cls, mod, scale, zero_point):
|
| 157 |
+
return cls(
|
| 158 |
+
mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point),
|
| 159 |
+
mod.eps, mod.affine)
|
| 160 |
+
|
| 161 |
+
class InstanceNorm3d(torch.nn.InstanceNorm3d):
|
| 162 |
+
r"""This is the quantized version of :class:`~torch.nn.InstanceNorm3d`.
|
| 163 |
+
|
| 164 |
+
Additional args:
|
| 165 |
+
* **scale** - quantization scale of the output, type: double.
|
| 166 |
+
* **zero_point** - quantization zero point of the output, type: long.
|
| 167 |
+
|
| 168 |
+
"""
|
| 169 |
+
def __init__(self, num_features, weight, bias, scale, zero_point,
|
| 170 |
+
eps=1e-5, momentum=0.1, affine=False,
|
| 171 |
+
track_running_stats=False, device=None, dtype=None) -> None:
|
| 172 |
+
factory_kwargs = {'device': device, 'dtype': dtype}
|
| 173 |
+
super().__init__(num_features, eps, momentum, affine, track_running_stats, **factory_kwargs)
|
| 174 |
+
self.weight = weight
|
| 175 |
+
self.bias = bias
|
| 176 |
+
self.register_buffer('scale', torch.tensor(scale, **factory_kwargs))
|
| 177 |
+
self.register_buffer('zero_point', torch.tensor(zero_point, **factory_kwargs))
|
| 178 |
+
|
| 179 |
+
def forward(self, input):
|
| 180 |
+
return torch.ops.quantized.instance_norm(
|
| 181 |
+
input, self.weight, self.bias, self.eps, self.scale,
|
| 182 |
+
self.zero_point)
|
| 183 |
+
|
| 184 |
+
def _get_name(self):
|
| 185 |
+
return 'QuantizedInstanceNorm3d'
|
| 186 |
+
|
| 187 |
+
@classmethod
|
| 188 |
+
def from_float(cls, mod):
|
| 189 |
+
scale, zero_point = mod.activation_post_process.calculate_qparams()
|
| 190 |
+
new_mod = cls(
|
| 191 |
+
mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point),
|
| 192 |
+
mod.eps, mod.affine)
|
| 193 |
+
return new_mod
|
| 194 |
+
|
| 195 |
+
@classmethod
|
| 196 |
+
def from_reference(cls, mod, scale, zero_point):
|
| 197 |
+
return cls(
|
| 198 |
+
mod.num_features, mod.weight, mod.bias, float(scale), int(zero_point),
|
| 199 |
+
mod.eps, mod.affine)
|
llava_next/lib/python3.10/site-packages/torch/ao/nn/quantized/modules/utils.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
import torch
|
| 3 |
+
import itertools
|
| 4 |
+
import collections
|
| 5 |
+
from torch.nn.modules.module import _addindent
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"WeightedQuantizedModule",
|
| 9 |
+
]
|
| 10 |
+
|
| 11 |
+
class WeightedQuantizedModule(torch.nn.Module, metaclass=abc.ABCMeta):
|
| 12 |
+
"""Wrapper for quantized modules than can be lowered from reference modules."""
|
| 13 |
+
@classmethod
|
| 14 |
+
@abc.abstractmethod
|
| 15 |
+
def from_reference(cls, ref_module, output_scale, output_zero_point):
|
| 16 |
+
raise NotImplementedError
|
| 17 |
+
|
| 18 |
+
def _get_weight_observer(observer):
|
| 19 |
+
# FakeQuantize observer
|
| 20 |
+
if hasattr(observer, "activation_post_process"):
|
| 21 |
+
observer = observer.activation_post_process
|
| 22 |
+
# UniformQuantizationObserverBase observer
|
| 23 |
+
return observer
|
| 24 |
+
|
| 25 |
+
def _needs_weight_clamping(observer, dtype):
|
| 26 |
+
observer = _get_weight_observer(observer)
|
| 27 |
+
if dtype in [torch.qint8, torch.quint8, torch.qint32]:
|
| 28 |
+
info = torch.iinfo(dtype)
|
| 29 |
+
return observer.quant_min > info.min or observer.quant_max < info.max
|
| 30 |
+
return False
|
| 31 |
+
|
| 32 |
+
def _clamp_weights(qweight, observer, scale, zp):
|
| 33 |
+
if not _needs_weight_clamping(observer, qweight.dtype):
|
| 34 |
+
return qweight
|
| 35 |
+
|
| 36 |
+
observer = _get_weight_observer(observer)
|
| 37 |
+
min_, max_ = observer.quant_min, observer.quant_max
|
| 38 |
+
|
| 39 |
+
# Doing this because can't use torch.ops.quantized.clamp() with per_channel qscheme yet.
|
| 40 |
+
qw_int_max = torch.clone(qweight.int_repr()).fill_(max_)
|
| 41 |
+
qw_int_min = torch.clone(qweight.int_repr()).fill_(min_)
|
| 42 |
+
qw_int = torch.minimum(torch.maximum(qweight.int_repr(), qw_int_min), qw_int_max)
|
| 43 |
+
|
| 44 |
+
if observer.qscheme in [torch.per_tensor_symmetric,
|
| 45 |
+
torch.per_tensor_affine]:
|
| 46 |
+
qweight = torch._make_per_tensor_quantized_tensor(qw_int, scale.item(), zp.item())
|
| 47 |
+
elif observer.qscheme in [torch.per_channel_symmetric,
|
| 48 |
+
torch.per_channel_affine,
|
| 49 |
+
torch.per_channel_affine_float_qparams]:
|
| 50 |
+
qweight = torch._make_per_channel_quantized_tensor(qw_int, scale, zp, axis=observer.ch_axis)
|
| 51 |
+
else:
|
| 52 |
+
raise ValueError("Unexpected qscheme " + observer.qscheme)
|
| 53 |
+
return qweight
|
| 54 |
+
|
| 55 |
+
def _quantize_weight(float_wt, observer):
|
| 56 |
+
wt_scale, wt_zp = observer.calculate_qparams()
|
| 57 |
+
if observer.qscheme in [torch.per_tensor_symmetric, torch.per_tensor_affine]:
|
| 58 |
+
qweight = torch.quantize_per_tensor(
|
| 59 |
+
float_wt,
|
| 60 |
+
float(wt_scale), int(wt_zp), torch.qint8)
|
| 61 |
+
qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp)
|
| 62 |
+
elif observer.qscheme in [torch.per_channel_symmetric, torch.per_channel_affine]:
|
| 63 |
+
wt_axis = observer.ch_axis
|
| 64 |
+
qweight = torch.quantize_per_channel(
|
| 65 |
+
float_wt,
|
| 66 |
+
wt_scale.to(torch.double), wt_zp.to(torch.int64), wt_axis, torch.qint8)
|
| 67 |
+
qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp)
|
| 68 |
+
elif observer.qscheme in [torch.per_channel_affine_float_qparams]:
|
| 69 |
+
qweight = torch.quantize_per_channel(
|
| 70 |
+
float_wt,
|
| 71 |
+
wt_scale.to(torch.float), wt_zp.to(torch.float), observer.ch_axis, observer.dtype)
|
| 72 |
+
qweight = _clamp_weights(qweight, observer, wt_scale, wt_zp)
|
| 73 |
+
else:
|
| 74 |
+
raise ValueError("Unexpected qscheme " + observer.qscheme)
|
| 75 |
+
return qweight
|
| 76 |
+
|
| 77 |
+
def _ntuple_from_first(n):
|
| 78 |
+
"""Converts the argument to a tuple of size n
|
| 79 |
+
with the first element repeated."""
|
| 80 |
+
def parse(x):
|
| 81 |
+
while isinstance(x, collections.abc.Sequence):
|
| 82 |
+
if len(x) == n:
|
| 83 |
+
break
|
| 84 |
+
x = x[0]
|
| 85 |
+
return tuple(itertools.repeat(x, n))
|
| 86 |
+
return parse
|
| 87 |
+
|
| 88 |
+
def _hide_packed_params_repr(self, params):
|
| 89 |
+
# We don't want to show `PackedParams` children, hence custom
|
| 90 |
+
# `__repr__`. This is the same as nn.Module.__repr__, except the check
|
| 91 |
+
# for the `params module`.
|
| 92 |
+
extra_lines = []
|
| 93 |
+
extra_repr = self.extra_repr()
|
| 94 |
+
# empty string will be split into list ['']
|
| 95 |
+
if extra_repr:
|
| 96 |
+
extra_lines = extra_repr.split('\n')
|
| 97 |
+
child_lines = []
|
| 98 |
+
for key, module in self._modules.items():
|
| 99 |
+
if isinstance(module, params):
|
| 100 |
+
continue
|
| 101 |
+
mod_str = repr(module)
|
| 102 |
+
mod_str = _addindent(mod_str, 2)
|
| 103 |
+
child_lines.append('(' + key + '): ' + mod_str)
|
| 104 |
+
lines = extra_lines + child_lines
|
| 105 |
+
|
| 106 |
+
main_str = self._get_name() + '('
|
| 107 |
+
if lines:
|
| 108 |
+
# simple one-liner info, which most builtin Modules will use
|
| 109 |
+
if len(extra_lines) == 1 and not child_lines:
|
| 110 |
+
main_str += extra_lines[0]
|
| 111 |
+
else:
|
| 112 |
+
main_str += '\n ' + '\n '.join(lines) + '\n'
|
| 113 |
+
|
| 114 |
+
main_str += ')'
|
| 115 |
+
return main_str
|
| 116 |
+
|
| 117 |
+
_pair_from_first = _ntuple_from_first(2)
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .backend_config import BackendConfig, BackendPatternConfig, DTypeConfig, DTypeWithConstraints, ObservationType
|
| 2 |
+
from .fbgemm import get_fbgemm_backend_config
|
| 3 |
+
from .native import get_native_backend_config, get_native_backend_config_dict
|
| 4 |
+
from .qnnpack import get_qnnpack_backend_config
|
| 5 |
+
from .tensorrt import get_tensorrt_backend_config, get_tensorrt_backend_config_dict
|
| 6 |
+
from .executorch import get_executorch_backend_config
|
| 7 |
+
from .onednn import get_onednn_backend_config
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
"get_fbgemm_backend_config",
|
| 11 |
+
"get_native_backend_config",
|
| 12 |
+
"get_native_backend_config_dict",
|
| 13 |
+
"get_qnnpack_backend_config",
|
| 14 |
+
"get_tensorrt_backend_config",
|
| 15 |
+
"get_tensorrt_backend_config_dict",
|
| 16 |
+
"get_executorch_backend_config",
|
| 17 |
+
"BackendConfig",
|
| 18 |
+
"BackendPatternConfig",
|
| 19 |
+
"DTypeConfig",
|
| 20 |
+
"DTypeWithConstraints",
|
| 21 |
+
"ObservationType",
|
| 22 |
+
"get_onednn_backend_config",
|
| 23 |
+
]
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (874 Bytes). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/_common_operator_config_utils.cpython-310.pyc
ADDED
|
Binary file (12.9 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/backend_config.cpython-310.pyc
ADDED
|
Binary file (26.6 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/executorch.cpython-310.pyc
ADDED
|
Binary file (7.68 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/native.cpython-310.pyc
ADDED
|
Binary file (3.58 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/qnnpack.cpython-310.pyc
ADDED
|
Binary file (2.61 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/tensorrt.cpython-310.pyc
ADDED
|
Binary file (2.07 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (9.59 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_common_operator_config_utils.py
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import operator
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.ao.nn.intrinsic as nni
|
| 7 |
+
import torch.ao.nn.intrinsic.qat as nniqat
|
| 8 |
+
import torch.ao.nn.qat as nnqat
|
| 9 |
+
import torch.ao.nn.quantized.reference as nnqr
|
| 10 |
+
from collections import namedtuple
|
| 11 |
+
from typing import Callable, Dict, List, Union
|
| 12 |
+
from .backend_config import (
|
| 13 |
+
BackendPatternConfig,
|
| 14 |
+
DTypeConfig,
|
| 15 |
+
DTypeWithConstraints,
|
| 16 |
+
ObservationType,
|
| 17 |
+
)
|
| 18 |
+
from ..fuser_method_mappings import (
|
| 19 |
+
_sequential_wrapper2,
|
| 20 |
+
fuse_conv_bn,
|
| 21 |
+
fuse_conv_bn_relu,
|
| 22 |
+
fuse_linear_bn,
|
| 23 |
+
fuse_convtranspose_bn,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
__all__: List[str] = []
|
| 27 |
+
|
| 28 |
+
# TODO: rename to be more explicit, e.g. qat_conv_relu
|
| 29 |
+
_ConvMetadata = namedtuple(
|
| 30 |
+
"_ConvMetadata",
|
| 31 |
+
["root", "transpose", "bn", "reference", "transpose_reference",
|
| 32 |
+
"fused_conv_relu", "fused_conv_bn", "fused_conv_bn_relu",
|
| 33 |
+
"qat", "relu_qat", "bn_qat", "bn_relu_qat",
|
| 34 |
+
"func", "func_transpose"])
|
| 35 |
+
_Conv1dMetadata = _ConvMetadata(
|
| 36 |
+
nn.Conv1d, nn.ConvTranspose1d, nn.BatchNorm1d, nnqr.Conv1d, nnqr.ConvTranspose1d,
|
| 37 |
+
nni.ConvReLU1d, nni.ConvBn1d, nni.ConvBnReLU1d,
|
| 38 |
+
nnqat.Conv1d, nniqat.ConvReLU1d, nniqat.ConvBn1d, nniqat.ConvBnReLU1d,
|
| 39 |
+
F.conv1d, F.conv_transpose1d)
|
| 40 |
+
_Conv2dMetadata = _ConvMetadata(
|
| 41 |
+
nn.Conv2d, nn.ConvTranspose2d, nn.BatchNorm2d, nnqr.Conv2d, nnqr.ConvTranspose2d,
|
| 42 |
+
nni.ConvReLU2d, nni.ConvBn2d, nni.ConvBnReLU2d,
|
| 43 |
+
nnqat.Conv2d, nniqat.ConvReLU2d, nniqat.ConvBn2d, nniqat.ConvBnReLU2d,
|
| 44 |
+
F.conv2d, F.conv_transpose2d)
|
| 45 |
+
_Conv3dMetadata = _ConvMetadata(
|
| 46 |
+
nn.Conv3d, nn.ConvTranspose3d, nn.BatchNorm3d, nnqr.Conv3d, nnqr.ConvTranspose3d,
|
| 47 |
+
nni.ConvReLU3d, nni.ConvBn3d, nni.ConvBnReLU3d,
|
| 48 |
+
nnqat.Conv3d, nniqat.ConvReLU3d, nniqat.ConvBn3d, nniqat.ConvBnReLU3d,
|
| 49 |
+
F.conv3d, F.conv_transpose3d)
|
| 50 |
+
|
| 51 |
+
# Add constraints for fixed qparams ops like sigmoid and tanh to ensure values
|
| 52 |
+
# fall within the proper ranges, e.g. [0, 1] for sigmoid, [-1, 1] for tanh
|
| 53 |
+
_FIXED_QPARAM_OP_0TO1_CONSTRAINTS = DTypeWithConstraints(
|
| 54 |
+
dtype=torch.quint8,
|
| 55 |
+
quant_min_lower_bound=0,
|
| 56 |
+
quant_max_upper_bound=255,
|
| 57 |
+
scale_exact_match=1.0 / 256.0,
|
| 58 |
+
zero_point_exact_match=0,
|
| 59 |
+
)
|
| 60 |
+
_FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS = DTypeWithConstraints(
|
| 61 |
+
dtype=torch.quint8,
|
| 62 |
+
quant_min_lower_bound=0,
|
| 63 |
+
quant_max_upper_bound=255,
|
| 64 |
+
scale_exact_match=2.0 / 256.0,
|
| 65 |
+
zero_point_exact_match=128,
|
| 66 |
+
)
|
| 67 |
+
_FIXED_QPARAMS_OP_TO_CONSTRAINTS: Dict[Union[Callable, str], DTypeWithConstraints] = {
|
| 68 |
+
torch.nn.Hardsigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 69 |
+
torch.nn.functional.hardsigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 70 |
+
"hardsigmoid": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 71 |
+
"hardsigmoid_": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 72 |
+
torch.nn.Sigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 73 |
+
torch.sigmoid: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 74 |
+
"sigmoid": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 75 |
+
"sigmoid_": _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 76 |
+
torch.nn.Softmax: _FIXED_QPARAM_OP_0TO1_CONSTRAINTS,
|
| 77 |
+
torch.nn.Tanh: _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS,
|
| 78 |
+
torch.tanh: _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS,
|
| 79 |
+
"tanh": _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS,
|
| 80 |
+
"tanh_": _FIXED_QPARAM_OP_NEG1TO1_CONSTRAINTS,
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
def _get_binary_op_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 84 |
+
binary_op_configs: List[BackendPatternConfig] = []
|
| 85 |
+
num_tensor_args_to_observation_type_mapping = {
|
| 86 |
+
# TODO: this is not used right now since we have extra check in prepare
|
| 87 |
+
# will need to change this to NO_OBSERVER later after we implemented
|
| 88 |
+
# Tensor dtype inference properly
|
| 89 |
+
0: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
|
| 90 |
+
1: ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT,
|
| 91 |
+
2: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
|
| 92 |
+
}
|
| 93 |
+
for op_with_quantized_bop_scalar_variant in [operator.add, torch.add, operator.mul, torch.mul]:
|
| 94 |
+
bop_patterns = [
|
| 95 |
+
(op_with_quantized_bop_scalar_variant, nn.ReLU),
|
| 96 |
+
(op_with_quantized_bop_scalar_variant, F.relu),
|
| 97 |
+
(op_with_quantized_bop_scalar_variant, torch.relu),
|
| 98 |
+
op_with_quantized_bop_scalar_variant
|
| 99 |
+
]
|
| 100 |
+
for bop_pattern in bop_patterns:
|
| 101 |
+
binary_op_configs.append(
|
| 102 |
+
BackendPatternConfig(bop_pattern)
|
| 103 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 104 |
+
._set_num_tensor_args_to_observation_type(num_tensor_args_to_observation_type_mapping))
|
| 105 |
+
# matmul
|
| 106 |
+
binary_op_configs.append(
|
| 107 |
+
BackendPatternConfig(torch.matmul)
|
| 108 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 109 |
+
)
|
| 110 |
+
return binary_op_configs
|
| 111 |
+
|
| 112 |
+
def _get_linear_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 113 |
+
"""
|
| 114 |
+
Return all configs related to linear modules and ops.
|
| 115 |
+
"""
|
| 116 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 117 |
+
linear_configs: List[BackendPatternConfig] = []
|
| 118 |
+
|
| 119 |
+
# (1) Single linear modules/functions
|
| 120 |
+
# -------------------------------------
|
| 121 |
+
# linear module
|
| 122 |
+
linear_configs.append(
|
| 123 |
+
BackendPatternConfig(torch.nn.Linear)
|
| 124 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 125 |
+
.set_dtype_configs(dtype_configs)
|
| 126 |
+
.set_root_module(torch.nn.Linear)
|
| 127 |
+
.set_reference_quantized_module(nnqr.Linear)
|
| 128 |
+
.set_qat_module(nnqat.Linear))
|
| 129 |
+
# linear qat module
|
| 130 |
+
linear_configs.append(
|
| 131 |
+
BackendPatternConfig(nnqat.Linear)
|
| 132 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 133 |
+
.set_dtype_configs(dtype_configs)
|
| 134 |
+
.set_root_module(torch.nn.Linear)
|
| 135 |
+
.set_reference_quantized_module(nnqr.Linear))
|
| 136 |
+
# functional linear
|
| 137 |
+
linear_configs.append(
|
| 138 |
+
BackendPatternConfig(torch.nn.functional.linear)
|
| 139 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 140 |
+
.set_dtype_configs(dtype_configs)
|
| 141 |
+
._set_input_type_to_index({"weight": 1, "bias": 2}))
|
| 142 |
+
|
| 143 |
+
# (2) Linear + relu
|
| 144 |
+
# -------------------
|
| 145 |
+
# 2.1 linear module + relu fusion config
|
| 146 |
+
# linear relu, linear module + relu module
|
| 147 |
+
linear_configs.append(
|
| 148 |
+
BackendPatternConfig((torch.nn.Linear, torch.nn.ReLU))
|
| 149 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 150 |
+
.set_fuser_method(_sequential_wrapper2(nni.LinearReLU))
|
| 151 |
+
.set_fused_module(nni.LinearReLU))
|
| 152 |
+
# linear relu, linear module + functional relu
|
| 153 |
+
linear_configs.append(
|
| 154 |
+
BackendPatternConfig((torch.nn.Linear, torch.nn.functional.relu))
|
| 155 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 156 |
+
.set_fuser_method(_sequential_wrapper2(nni.LinearReLU))
|
| 157 |
+
.set_fused_module(nni.LinearReLU))
|
| 158 |
+
|
| 159 |
+
# 2.2 linear module + relu, fused module configs
|
| 160 |
+
# linear relu, fused module
|
| 161 |
+
linear_configs.append(
|
| 162 |
+
BackendPatternConfig(nni.LinearReLU)
|
| 163 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 164 |
+
.set_dtype_configs(dtype_configs)
|
| 165 |
+
.set_root_module(torch.nn.Linear)
|
| 166 |
+
.set_reference_quantized_module(nnqr.Linear)
|
| 167 |
+
.set_qat_module(nniqat.LinearReLU))
|
| 168 |
+
# linear relu, qat fused module
|
| 169 |
+
linear_configs.append(
|
| 170 |
+
BackendPatternConfig(nniqat.LinearReLU)
|
| 171 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 172 |
+
.set_dtype_configs(dtype_configs)
|
| 173 |
+
.set_root_module(torch.nn.Linear)
|
| 174 |
+
.set_reference_quantized_module(nnqr.Linear))
|
| 175 |
+
# 2.3 functional linear + relu configs
|
| 176 |
+
# linear relu, functional linear + relu module
|
| 177 |
+
linear_configs.append(
|
| 178 |
+
BackendPatternConfig((F.linear, torch.nn.ReLU))
|
| 179 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 180 |
+
.set_dtype_configs(dtype_configs))
|
| 181 |
+
# linear relu, functional linear + functional relu
|
| 182 |
+
linear_configs.append(
|
| 183 |
+
BackendPatternConfig((F.linear, F.relu))
|
| 184 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 185 |
+
.set_dtype_configs(dtype_configs))
|
| 186 |
+
|
| 187 |
+
# (3) Linear + batchnorm
|
| 188 |
+
# ------------------------
|
| 189 |
+
# 3.1 linear bn fusion
|
| 190 |
+
linear_configs.append(
|
| 191 |
+
BackendPatternConfig((nn.Linear, nn.BatchNorm1d))
|
| 192 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 193 |
+
.set_fuser_method(fuse_linear_bn)
|
| 194 |
+
.set_fused_module(nni.LinearBn1d))
|
| 195 |
+
|
| 196 |
+
# 3.2 linear bn fused
|
| 197 |
+
# linear bn, fused module
|
| 198 |
+
linear_configs.append(
|
| 199 |
+
BackendPatternConfig(nni.LinearBn1d)
|
| 200 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 201 |
+
.set_dtype_configs(dtype_configs)
|
| 202 |
+
.set_root_module(torch.nn.Linear)
|
| 203 |
+
.set_reference_quantized_module(nnqr.Linear)
|
| 204 |
+
.set_qat_module(nniqat.LinearBn1d))
|
| 205 |
+
# linear bn, qat fused module
|
| 206 |
+
linear_configs.append(
|
| 207 |
+
BackendPatternConfig(nniqat.LinearBn1d)
|
| 208 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 209 |
+
.set_dtype_configs(dtype_configs)
|
| 210 |
+
.set_root_module(torch.nn.Linear)
|
| 211 |
+
.set_reference_quantized_module(nnqr.Linear))
|
| 212 |
+
return linear_configs
|
| 213 |
+
|
| 214 |
+
def _get_conv_configs(dtype_configs):
|
| 215 |
+
"""
|
| 216 |
+
Return all configs related to conv modules and ops.
|
| 217 |
+
"""
|
| 218 |
+
conv_configs = []
|
| 219 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 220 |
+
for convs in [_Conv1dMetadata, _Conv2dMetadata, _Conv3dMetadata]:
|
| 221 |
+
|
| 222 |
+
# (1) Single conv modules/functions
|
| 223 |
+
# -----------------------------------
|
| 224 |
+
# conv module
|
| 225 |
+
conv_configs.append(
|
| 226 |
+
BackendPatternConfig(convs.root)
|
| 227 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 228 |
+
.set_dtype_configs(dtype_configs)
|
| 229 |
+
.set_root_module(convs.root)
|
| 230 |
+
.set_reference_quantized_module(convs.reference)
|
| 231 |
+
.set_qat_module(convs.qat))
|
| 232 |
+
# conv qat module
|
| 233 |
+
conv_configs.append(
|
| 234 |
+
BackendPatternConfig(convs.qat)
|
| 235 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 236 |
+
.set_dtype_configs(dtype_configs)
|
| 237 |
+
.set_root_module(convs.root)
|
| 238 |
+
.set_reference_quantized_module(convs.reference))
|
| 239 |
+
# functional conv
|
| 240 |
+
conv_configs.append(
|
| 241 |
+
BackendPatternConfig(convs.func)
|
| 242 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 243 |
+
.set_dtype_configs(dtype_configs)
|
| 244 |
+
._set_input_type_to_index({"weight": 1, "bias": 2}))
|
| 245 |
+
|
| 246 |
+
# (2) Conv + relu
|
| 247 |
+
# -----------------
|
| 248 |
+
# 2.1 conv module + relu fusion configs
|
| 249 |
+
# conv relu fusion, conv module + relu module
|
| 250 |
+
conv_configs.append(
|
| 251 |
+
BackendPatternConfig((convs.root, torch.nn.ReLU))
|
| 252 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 253 |
+
.set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu))
|
| 254 |
+
.set_fused_module(convs.fused_conv_relu))
|
| 255 |
+
# conv relu fusion, conv module + functional relu
|
| 256 |
+
conv_configs.append(
|
| 257 |
+
BackendPatternConfig((convs.root, F.relu))
|
| 258 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 259 |
+
.set_fuser_method(_sequential_wrapper2(convs.fused_conv_relu))
|
| 260 |
+
.set_fused_module(convs.fused_conv_relu))
|
| 261 |
+
# 2.2 conv module + relu fused module configs
|
| 262 |
+
# conv relu, fused module
|
| 263 |
+
conv_configs.append(
|
| 264 |
+
BackendPatternConfig(convs.fused_conv_relu)
|
| 265 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 266 |
+
.set_dtype_configs(dtype_configs)
|
| 267 |
+
.set_root_module(convs.root)
|
| 268 |
+
.set_reference_quantized_module(convs.reference)
|
| 269 |
+
.set_qat_module(convs.relu_qat))
|
| 270 |
+
# conv relu, qat fused module
|
| 271 |
+
conv_configs.append(
|
| 272 |
+
BackendPatternConfig(convs.relu_qat)
|
| 273 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 274 |
+
.set_dtype_configs(dtype_configs)
|
| 275 |
+
.set_root_module(convs.root)
|
| 276 |
+
.set_reference_quantized_module(convs.reference))
|
| 277 |
+
# 2.3 functional conv + relu configs
|
| 278 |
+
# conv relu, functional conv + relu module
|
| 279 |
+
conv_configs.append(
|
| 280 |
+
BackendPatternConfig((convs.func, torch.nn.ReLU))
|
| 281 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 282 |
+
.set_dtype_configs(dtype_configs))
|
| 283 |
+
# conv relu, functional conv + functional relu
|
| 284 |
+
conv_configs.append(
|
| 285 |
+
BackendPatternConfig((convs.func, F.relu))
|
| 286 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 287 |
+
.set_dtype_configs(dtype_configs))
|
| 288 |
+
|
| 289 |
+
# fused conv relu
|
| 290 |
+
conv_configs.append(
|
| 291 |
+
BackendPatternConfig(convs.fused_conv_relu)
|
| 292 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 293 |
+
.set_qat_module(convs.relu_qat))
|
| 294 |
+
|
| 295 |
+
conv_configs.append(
|
| 296 |
+
BackendPatternConfig(convs.relu_qat)
|
| 297 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 298 |
+
.set_root_module(convs.root)
|
| 299 |
+
.set_reference_quantized_module(convs.reference))
|
| 300 |
+
|
| 301 |
+
# (3) Conv + batchnorm (+ relu)
|
| 302 |
+
# -------------------------------
|
| 303 |
+
# 3.1 conv bn fusion configs
|
| 304 |
+
# conv + bn fusion
|
| 305 |
+
conv_configs.append(
|
| 306 |
+
BackendPatternConfig((convs.root, convs.bn))
|
| 307 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 308 |
+
.set_fuser_method(fuse_conv_bn)
|
| 309 |
+
.set_fused_module(convs.fused_conv_bn))
|
| 310 |
+
# conv + bn + relu module fusion
|
| 311 |
+
conv_configs.append(
|
| 312 |
+
BackendPatternConfig((convs.root, convs.bn, nn.ReLU))
|
| 313 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 314 |
+
.set_fuser_method(fuse_conv_bn_relu)
|
| 315 |
+
.set_fused_module(convs.fused_conv_bn_relu))
|
| 316 |
+
# conv + bn + relu functional fusion
|
| 317 |
+
conv_configs.append(
|
| 318 |
+
BackendPatternConfig((convs.root, convs.bn, F.relu))
|
| 319 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 320 |
+
.set_root_module(convs.root)
|
| 321 |
+
.set_fuser_method(fuse_conv_bn_relu)
|
| 322 |
+
.set_fused_module(convs.fused_conv_bn_relu))
|
| 323 |
+
# TODO: we can add fusion for torch.relu as well
|
| 324 |
+
|
| 325 |
+
# 3.2 conv + bn (+ relu) fused module configs
|
| 326 |
+
# fused conv bn
|
| 327 |
+
conv_configs.append(
|
| 328 |
+
BackendPatternConfig(convs.fused_conv_bn)
|
| 329 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 330 |
+
.set_qat_module(convs.bn_qat))
|
| 331 |
+
|
| 332 |
+
# fused conv bn relu
|
| 333 |
+
conv_configs.append(
|
| 334 |
+
BackendPatternConfig(convs.fused_conv_bn_relu)
|
| 335 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 336 |
+
.set_qat_module(convs.bn_relu_qat))
|
| 337 |
+
|
| 338 |
+
# conv bn, qat fused module
|
| 339 |
+
conv_configs.append(
|
| 340 |
+
BackendPatternConfig(convs.bn_qat)
|
| 341 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 342 |
+
.set_dtype_configs(dtype_configs)
|
| 343 |
+
.set_root_module(convs.root)
|
| 344 |
+
.set_reference_quantized_module(convs.reference))
|
| 345 |
+
# conv bn relu, qat fused module
|
| 346 |
+
conv_configs.append(
|
| 347 |
+
BackendPatternConfig(convs.bn_relu_qat)
|
| 348 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 349 |
+
.set_dtype_configs(dtype_configs)
|
| 350 |
+
.set_root_module(convs.root)
|
| 351 |
+
.set_reference_quantized_module(convs.reference))
|
| 352 |
+
|
| 353 |
+
# (4) conv transpose and its fusion
|
| 354 |
+
# 4.1 conv transpose config
|
| 355 |
+
conv_configs.append(
|
| 356 |
+
BackendPatternConfig(convs.transpose)
|
| 357 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 358 |
+
.set_root_module(convs.transpose)
|
| 359 |
+
.set_reference_quantized_module(convs.transpose_reference))
|
| 360 |
+
|
| 361 |
+
# 4.2 conv transpose + bn fusion
|
| 362 |
+
conv_configs.append(
|
| 363 |
+
BackendPatternConfig((convs.transpose, convs.bn))
|
| 364 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 365 |
+
.set_fuser_method(fuse_convtranspose_bn)
|
| 366 |
+
.set_root_module(convs.transpose)
|
| 367 |
+
.set_reference_quantized_module(convs.transpose_reference))
|
| 368 |
+
|
| 369 |
+
# 4.3 functional conv transpose
|
| 370 |
+
conv_configs.append(
|
| 371 |
+
BackendPatternConfig(convs.func_transpose)
|
| 372 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 373 |
+
._set_input_type_to_index({"weight": 1, "bias": 2}))
|
| 374 |
+
|
| 375 |
+
return conv_configs
|
| 376 |
+
|
| 377 |
+
def _get_cat_config(dtype_configs: List[DTypeConfig]) -> BackendPatternConfig:
|
| 378 |
+
return BackendPatternConfig(torch.cat) \
|
| 379 |
+
.set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT) \
|
| 380 |
+
.set_dtype_configs(dtype_configs)
|
| 381 |
+
|
| 382 |
+
def _get_ln_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 383 |
+
ln_configs = []
|
| 384 |
+
ln_configs.append(
|
| 385 |
+
BackendPatternConfig(torch.nn.LayerNorm)
|
| 386 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
|
| 387 |
+
.set_dtype_configs(dtype_configs)
|
| 388 |
+
)
|
| 389 |
+
ln_configs.append(
|
| 390 |
+
BackendPatternConfig(torch.nn.functional.layer_norm)
|
| 391 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
|
| 392 |
+
.set_dtype_configs(dtype_configs)
|
| 393 |
+
._set_input_type_to_index({"weight": 2, "bias": 3})
|
| 394 |
+
)
|
| 395 |
+
return ln_configs
|
| 396 |
+
|
| 397 |
+
def _get_default_op_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 398 |
+
configs = []
|
| 399 |
+
default_ops = [
|
| 400 |
+
torch.nn.ELU,
|
| 401 |
+
torch.nn.LeakyReLU,
|
| 402 |
+
torch.nn.Hardswish,
|
| 403 |
+
torch.nn.InstanceNorm1d,
|
| 404 |
+
torch.nn.InstanceNorm2d,
|
| 405 |
+
torch.nn.InstanceNorm3d,
|
| 406 |
+
torch.nn.Dropout,
|
| 407 |
+
torch.nn.PReLU,
|
| 408 |
+
torch.nn.functional.elu,
|
| 409 |
+
torch.nn.functional.hardswish,
|
| 410 |
+
torch.nn.functional.leaky_relu,
|
| 411 |
+
torch.nn.functional.dropout,
|
| 412 |
+
]
|
| 413 |
+
for op in default_ops:
|
| 414 |
+
configs.append(
|
| 415 |
+
BackendPatternConfig(op)
|
| 416 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
|
| 417 |
+
.set_dtype_configs(dtype_configs))
|
| 418 |
+
|
| 419 |
+
configs.append(
|
| 420 |
+
BackendPatternConfig(torch.nn.functional.group_norm)
|
| 421 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
|
| 422 |
+
.set_dtype_configs(dtype_configs)
|
| 423 |
+
._set_input_type_to_index({"weight": 2, "bias": 3})
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
configs.append(
|
| 427 |
+
BackendPatternConfig(torch.nn.functional.instance_norm)
|
| 428 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
|
| 429 |
+
.set_dtype_configs(dtype_configs)
|
| 430 |
+
._set_input_type_to_index({"weight": 3, "bias": 4})
|
| 431 |
+
)
|
| 432 |
+
return configs
|
| 433 |
+
|
| 434 |
+
def _add_fixed_qparams_to_dtype_configs(
|
| 435 |
+
dtype_configs: List[DTypeConfig],
|
| 436 |
+
constraints: DTypeWithConstraints,
|
| 437 |
+
) -> List[DTypeConfig]:
|
| 438 |
+
"""
|
| 439 |
+
Return a copy of the list of DTypeConfigs where activations are subject to the specified
|
| 440 |
+
constraints required for fixed qparams ops.
|
| 441 |
+
|
| 442 |
+
If the data type doesn't match the one in the constraints, simply leave the corresponding
|
| 443 |
+
DTypeConfig unchanged.
|
| 444 |
+
|
| 445 |
+
If `scale_min_lower_bound` or `scale_max_upper_bound` is specified in the activations,
|
| 446 |
+
throw an exception since these settings are incompatible with fixed qparams ops.
|
| 447 |
+
"""
|
| 448 |
+
new_dtype_configs = []
|
| 449 |
+
for dtype_config in dtype_configs:
|
| 450 |
+
dc = copy.deepcopy(dtype_config)
|
| 451 |
+
for orig_constraints in [dc.input_dtype_with_constraints, dc.output_dtype_with_constraints]:
|
| 452 |
+
if orig_constraints.dtype != constraints.dtype:
|
| 453 |
+
continue
|
| 454 |
+
if orig_constraints.scale_min_lower_bound is not None:
|
| 455 |
+
raise ValueError(f"scale_min_lower_bound is invalid for fixed qparams ops: {dtype_config}")
|
| 456 |
+
if orig_constraints.scale_max_upper_bound is not None:
|
| 457 |
+
raise ValueError(f"scale_max_upper_bound is invalid for fixed qparams ops: {dtype_config}")
|
| 458 |
+
orig_constraints.quant_min_lower_bound = constraints.quant_min_lower_bound
|
| 459 |
+
orig_constraints.quant_max_upper_bound = constraints.quant_max_upper_bound
|
| 460 |
+
orig_constraints.scale_exact_match = constraints.scale_exact_match
|
| 461 |
+
orig_constraints.zero_point_exact_match = constraints.zero_point_exact_match
|
| 462 |
+
new_dtype_configs.append(dc)
|
| 463 |
+
return new_dtype_configs
|
| 464 |
+
|
| 465 |
+
def _get_fixed_qparams_op_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 466 |
+
fixed_qparams_op_configs = []
|
| 467 |
+
for fixed_qparam_op, constraints in _FIXED_QPARAMS_OP_TO_CONSTRAINTS.items():
|
| 468 |
+
new_dtype_configs = _add_fixed_qparams_to_dtype_configs(dtype_configs, constraints)
|
| 469 |
+
fixed_qparams_op_configs.append(
|
| 470 |
+
BackendPatternConfig(fixed_qparam_op)
|
| 471 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
|
| 472 |
+
.set_dtype_configs(new_dtype_configs))
|
| 473 |
+
return fixed_qparams_op_configs
|
| 474 |
+
|
| 475 |
+
def _get_share_qparams_op_configs(dtype_configs):
|
| 476 |
+
""" Get the operator config for the operators that works for both float and quantized input
|
| 477 |
+
if input is quantized, the output Tensor shares the same quantization parameter
|
| 478 |
+
with input.
|
| 479 |
+
Example operator: avgpool2d, reshape, transpose, maxpool2d
|
| 480 |
+
Example observed operator:
|
| 481 |
+
observer_0 - avgpool2d - observer_0 (same observer instance as input)
|
| 482 |
+
"""
|
| 483 |
+
|
| 484 |
+
def _get_share_qprams_op_backend_config(op):
|
| 485 |
+
return BackendPatternConfig(op) \
|
| 486 |
+
.set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT) \
|
| 487 |
+
.set_dtype_configs(dtype_configs)
|
| 488 |
+
|
| 489 |
+
share_qparams_ops = [
|
| 490 |
+
torch.nn.AdaptiveAvgPool1d,
|
| 491 |
+
torch.nn.AdaptiveAvgPool2d,
|
| 492 |
+
torch.nn.AdaptiveAvgPool3d,
|
| 493 |
+
torch.nn.AvgPool1d,
|
| 494 |
+
torch.nn.AvgPool2d,
|
| 495 |
+
torch.nn.AvgPool3d,
|
| 496 |
+
torch.nn.Hardtanh,
|
| 497 |
+
torch.nn.Identity,
|
| 498 |
+
torch.nn.MaxPool1d,
|
| 499 |
+
torch.nn.MaxPool2d,
|
| 500 |
+
torch.nn.MaxPool3d,
|
| 501 |
+
torch.nn.PixelShuffle,
|
| 502 |
+
torch.nn.PixelUnshuffle,
|
| 503 |
+
torch.nn.ReLU,
|
| 504 |
+
torch.nn.ReLU6,
|
| 505 |
+
torch.adaptive_avg_pool1d,
|
| 506 |
+
torch.nn.functional.adaptive_avg_pool2d,
|
| 507 |
+
torch.nn.functional.adaptive_avg_pool3d,
|
| 508 |
+
torch.nn.functional.hardtanh,
|
| 509 |
+
torch.nn.functional.hardtanh_,
|
| 510 |
+
torch.nn.functional.interpolate,
|
| 511 |
+
torch.nn.functional.max_pool1d,
|
| 512 |
+
torch.nn.functional.max_pool2d,
|
| 513 |
+
torch.nn.functional.max_pool3d,
|
| 514 |
+
torch.nn.functional.pixel_shuffle,
|
| 515 |
+
torch.nn.functional.pixel_unshuffle,
|
| 516 |
+
torch.nn.functional.relu,
|
| 517 |
+
torch.nn.functional.relu6,
|
| 518 |
+
torch.avg_pool1d,
|
| 519 |
+
torch._C._nn.avg_pool2d,
|
| 520 |
+
torch._C._nn.avg_pool3d,
|
| 521 |
+
torch.clamp,
|
| 522 |
+
torch.flatten,
|
| 523 |
+
torch.mean,
|
| 524 |
+
torch.narrow,
|
| 525 |
+
torch.repeat_interleave,
|
| 526 |
+
torch.transpose,
|
| 527 |
+
torch.squeeze,
|
| 528 |
+
torch.stack,
|
| 529 |
+
torch.unsqueeze,
|
| 530 |
+
operator.floordiv,
|
| 531 |
+
"contiguous",
|
| 532 |
+
"clamp",
|
| 533 |
+
"detach",
|
| 534 |
+
"detach_",
|
| 535 |
+
"mean",
|
| 536 |
+
"permute",
|
| 537 |
+
"repeat",
|
| 538 |
+
"repeat_interleave",
|
| 539 |
+
"reshape",
|
| 540 |
+
"resize_",
|
| 541 |
+
"relu",
|
| 542 |
+
"relu_",
|
| 543 |
+
"squeeze",
|
| 544 |
+
"squeeze_",
|
| 545 |
+
"transpose",
|
| 546 |
+
"unsqueeze",
|
| 547 |
+
"unsqueeze_",
|
| 548 |
+
"view"
|
| 549 |
+
]
|
| 550 |
+
return [_get_share_qprams_op_backend_config(op) for op in share_qparams_ops]
|
| 551 |
+
|
| 552 |
+
def _get_bn_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 553 |
+
""" Get configs related to batchnorm. """
|
| 554 |
+
bn_configs = []
|
| 555 |
+
bn_to_fused_bn = {
|
| 556 |
+
torch.nn.BatchNorm2d: nni.BNReLU2d,
|
| 557 |
+
torch.nn.BatchNorm3d: nni.BNReLU3d,
|
| 558 |
+
}
|
| 559 |
+
for bn in bn_to_fused_bn.keys():
|
| 560 |
+
fused_bn = bn_to_fused_bn[bn]
|
| 561 |
+
# bn module + relu module fusion config
|
| 562 |
+
bn_configs.append(
|
| 563 |
+
BackendPatternConfig((bn, nn.ReLU))
|
| 564 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 565 |
+
.set_fuser_method(_sequential_wrapper2(fused_bn))
|
| 566 |
+
.set_fused_module(fused_bn))
|
| 567 |
+
# bn module + F.relu fusion config
|
| 568 |
+
bn_configs.append(
|
| 569 |
+
BackendPatternConfig((bn, F.relu))
|
| 570 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 571 |
+
.set_fuser_method(_sequential_wrapper2(fused_bn))
|
| 572 |
+
.set_fused_module(fused_bn))
|
| 573 |
+
bn_configs.append(
|
| 574 |
+
BackendPatternConfig(bn)
|
| 575 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
|
| 576 |
+
.set_dtype_configs(dtype_configs))
|
| 577 |
+
|
| 578 |
+
# fused bn configs
|
| 579 |
+
for fused_bn in bn_to_fused_bn.values():
|
| 580 |
+
bn_configs.append(
|
| 581 |
+
BackendPatternConfig(fused_bn)
|
| 582 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
|
| 583 |
+
.set_dtype_configs(dtype_configs))
|
| 584 |
+
return bn_configs
|
| 585 |
+
|
| 586 |
+
def _get_rnn_op_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 587 |
+
rnn_op_configs = []
|
| 588 |
+
for rnn_op, ref_rnn_op in [
|
| 589 |
+
(nn.GRUCell, nnqr.GRUCell),
|
| 590 |
+
(nn.LSTMCell, nnqr.LSTMCell),
|
| 591 |
+
(nn.RNNCell, nnqr.RNNCell),
|
| 592 |
+
(nn.LSTM, nnqr.LSTM),
|
| 593 |
+
(nn.GRU, nnqr.GRU)
|
| 594 |
+
]:
|
| 595 |
+
rnn_op_configs.append(
|
| 596 |
+
BackendPatternConfig(rnn_op)
|
| 597 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
|
| 598 |
+
.set_dtype_configs(dtype_configs)
|
| 599 |
+
.set_root_module(rnn_op)
|
| 600 |
+
.set_reference_quantized_module(ref_rnn_op))
|
| 601 |
+
return rnn_op_configs
|
| 602 |
+
|
| 603 |
+
def _get_embedding_op_configs(dtype_configs: List[DTypeConfig]) -> List[BackendPatternConfig]:
|
| 604 |
+
embedding_op_configs = []
|
| 605 |
+
for embedding_op, qat_embedding_op, ref_embedding_op in [
|
| 606 |
+
(nn.Embedding, nnqat.Embedding, nnqr.Embedding),
|
| 607 |
+
(nn.EmbeddingBag, nnqat.EmbeddingBag, nnqr.EmbeddingBag),
|
| 608 |
+
]:
|
| 609 |
+
embedding_op_configs.append(
|
| 610 |
+
BackendPatternConfig(embedding_op)
|
| 611 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
|
| 612 |
+
.set_dtype_configs(dtype_configs)
|
| 613 |
+
.set_qat_module(qat_embedding_op)
|
| 614 |
+
.set_root_module(embedding_op)
|
| 615 |
+
.set_reference_quantized_module(ref_embedding_op))
|
| 616 |
+
|
| 617 |
+
# config for qat op
|
| 618 |
+
embedding_op_configs.append(
|
| 619 |
+
BackendPatternConfig(qat_embedding_op)
|
| 620 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) # noqa: E131
|
| 621 |
+
.set_dtype_configs(dtype_configs)
|
| 622 |
+
.set_root_module(embedding_op)
|
| 623 |
+
.set_reference_quantized_module(ref_embedding_op))
|
| 624 |
+
return embedding_op_configs
|
| 625 |
+
|
| 626 |
+
def _get_tensor_info_op_configs(dtype_configs):
|
| 627 |
+
"""
|
| 628 |
+
These ops work on tensors of different dtypes but return non-tensors
|
| 629 |
+
containing information about the input tensor.
|
| 630 |
+
"""
|
| 631 |
+
|
| 632 |
+
def _get_config(op):
|
| 633 |
+
return BackendPatternConfig(op) \
|
| 634 |
+
.set_observation_type(ObservationType.INPUT_OUTPUT_NOT_OBSERVED) \
|
| 635 |
+
.set_dtype_configs(dtype_configs)
|
| 636 |
+
|
| 637 |
+
return [_get_config(op) for op in ("shape", "size")]
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_qnnpack_pt2e.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import operator
|
| 2 |
+
import torch
|
| 3 |
+
from torch.ao.quantization.backend_config import (
|
| 4 |
+
BackendConfig,
|
| 5 |
+
DTypeConfig,
|
| 6 |
+
ObservationType,
|
| 7 |
+
BackendPatternConfig,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
weighted_op_quint8_dtype_config = DTypeConfig(
|
| 11 |
+
input_dtype=torch.quint8,
|
| 12 |
+
output_dtype=torch.quint8,
|
| 13 |
+
weight_dtype=torch.qint8,
|
| 14 |
+
bias_dtype=torch.float,
|
| 15 |
+
)
|
| 16 |
+
from typing import List
|
| 17 |
+
|
| 18 |
+
def get_linear_configs():
|
| 19 |
+
linear_configs = []
|
| 20 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 21 |
+
dtype_configs = [weighted_op_quint8_dtype_config]
|
| 22 |
+
|
| 23 |
+
# TODO: need to fix the way we insert observers for this pattern
|
| 24 |
+
# should be solved in the new fusion API
|
| 25 |
+
# reason that this doesn't work: the pattern is a bit complicated and we don't
|
| 26 |
+
# have a way to specify which input of the pattern we would like to observe
|
| 27 |
+
# pattern:
|
| 28 |
+
# bias input weight
|
| 29 |
+
# \ | /
|
| 30 |
+
# \ | t
|
| 31 |
+
# \ | /
|
| 32 |
+
# addmm
|
| 33 |
+
# we want to observe "weight" as weight, but there is not way to convey this
|
| 34 |
+
# information with current pattern language
|
| 35 |
+
#
|
| 36 |
+
# right now:
|
| 37 |
+
# original:
|
| 38 |
+
# weight - t \
|
| 39 |
+
# input - addmm
|
| 40 |
+
# observed (no hack):
|
| 41 |
+
# weight - t - observer \
|
| 42 |
+
# input - observer - addmm
|
| 43 |
+
# target:
|
| 44 |
+
# weight - observer - t \
|
| 45 |
+
# input - observer - addmm
|
| 46 |
+
|
| 47 |
+
# def root_node_getter(node_pattern):
|
| 48 |
+
# addmm, bias, act, weight = node_pattern
|
| 49 |
+
# return addmm
|
| 50 |
+
|
| 51 |
+
# linear_configs.append(
|
| 52 |
+
# BackendPatternConfig((torch.ops.aten.addmm.default, MatchAllNode, MatchAllNode, torch.ops.aten.t.default))
|
| 53 |
+
# .set_observation_type(observation_type) # noqa: E131
|
| 54 |
+
# .set_dtype_configs(dtype_configs)
|
| 55 |
+
# ._set_root_node_getter(root_node_getter))
|
| 56 |
+
|
| 57 |
+
linear_configs.append(
|
| 58 |
+
BackendPatternConfig(torch.ops.aten.addmm.default)
|
| 59 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 60 |
+
.set_dtype_configs(dtype_configs)
|
| 61 |
+
._set_input_type_to_index({"weight": 2, "bias": 0})
|
| 62 |
+
)
|
| 63 |
+
# linear is decomposed to `t - mm` if bias is not present
|
| 64 |
+
linear_configs.append(
|
| 65 |
+
BackendPatternConfig(torch.ops.aten.mm.default)
|
| 66 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 67 |
+
.set_dtype_configs(dtype_configs)
|
| 68 |
+
._set_input_type_to_index({"weight": 1})
|
| 69 |
+
)
|
| 70 |
+
return linear_configs
|
| 71 |
+
|
| 72 |
+
def get_conv_configs():
|
| 73 |
+
conv_configs = []
|
| 74 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 75 |
+
dtype_configs = [weighted_op_quint8_dtype_config]
|
| 76 |
+
conv_configs.append(
|
| 77 |
+
BackendPatternConfig(torch.ops.aten.convolution.default)
|
| 78 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 79 |
+
.set_dtype_configs(dtype_configs)
|
| 80 |
+
._set_input_type_to_index({"weight": 1, "bias": 2})
|
| 81 |
+
)
|
| 82 |
+
conv_configs.append(
|
| 83 |
+
BackendPatternConfig((torch.ops.aten.convolution.default, torch.ops.aten.relu.default))
|
| 84 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 85 |
+
.set_dtype_configs(dtype_configs)
|
| 86 |
+
._set_input_type_to_index({"weight": 1, "bias": 2})
|
| 87 |
+
)
|
| 88 |
+
# TODO: remove when functionalization is supported in PT2 mode
|
| 89 |
+
conv_configs.append(
|
| 90 |
+
BackendPatternConfig((torch.ops.aten.convolution.default, torch.ops.aten.relu_.default))
|
| 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 |
+
return conv_configs
|
| 96 |
+
|
| 97 |
+
def get_pooling_configs():
|
| 98 |
+
backend_pattern_configs = []
|
| 99 |
+
observation_type = ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT
|
| 100 |
+
dtype_configs = [weighted_op_quint8_dtype_config]
|
| 101 |
+
|
| 102 |
+
def root_node_getter(node_pattern):
|
| 103 |
+
getitem, maxpool, index = node_pattern
|
| 104 |
+
return maxpool
|
| 105 |
+
|
| 106 |
+
backend_pattern_configs.append(
|
| 107 |
+
BackendPatternConfig()
|
| 108 |
+
._set_pattern_complex_format((operator.getitem, torch.ops.aten.max_pool2d_with_indices.default, 0))
|
| 109 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 110 |
+
.set_dtype_configs(dtype_configs)
|
| 111 |
+
._set_root_node_getter(root_node_getter)
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
return backend_pattern_configs
|
| 115 |
+
|
| 116 |
+
def get_relu_configs():
|
| 117 |
+
backend_pattern_configs = []
|
| 118 |
+
observation_type = ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT
|
| 119 |
+
dtype_configs = [weighted_op_quint8_dtype_config]
|
| 120 |
+
backend_pattern_configs.append(
|
| 121 |
+
BackendPatternConfig(torch.ops.aten.relu.default)
|
| 122 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 123 |
+
.set_dtype_configs(dtype_configs))
|
| 124 |
+
return backend_pattern_configs
|
| 125 |
+
|
| 126 |
+
def get_binary_op_configs():
|
| 127 |
+
binary_op_configs: List[BackendPatternConfig] = []
|
| 128 |
+
dtype_configs = [weighted_op_quint8_dtype_config]
|
| 129 |
+
num_tensor_args_to_observation_type_mapping = {
|
| 130 |
+
# TODO: this is not used right now since we have extra check in prepare
|
| 131 |
+
# will need to change this to NO_OBSERVER later after we implemented
|
| 132 |
+
# Tensor dtype inference properly
|
| 133 |
+
0: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
|
| 134 |
+
1: ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT,
|
| 135 |
+
2: ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT,
|
| 136 |
+
}
|
| 137 |
+
for op_with_quantized_bop_scalar_variant in [torch.ops.aten.add.Tensor, torch.ops.aten.add_.Tensor]:
|
| 138 |
+
bop_patterns = [
|
| 139 |
+
(op_with_quantized_bop_scalar_variant, torch.ops.aten.relu.default),
|
| 140 |
+
op_with_quantized_bop_scalar_variant,
|
| 141 |
+
# TODO: remove when functionalization is supported in pt2_mode
|
| 142 |
+
(op_with_quantized_bop_scalar_variant, torch.ops.aten.relu_.default),
|
| 143 |
+
]
|
| 144 |
+
for bop_pattern in bop_patterns:
|
| 145 |
+
binary_op_configs.append(
|
| 146 |
+
BackendPatternConfig(bop_pattern)
|
| 147 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 148 |
+
._set_num_tensor_args_to_observation_type(num_tensor_args_to_observation_type_mapping))
|
| 149 |
+
|
| 150 |
+
return binary_op_configs
|
| 151 |
+
|
| 152 |
+
def get_qnnpack_pt2e_backend_config():
|
| 153 |
+
return (
|
| 154 |
+
BackendConfig("qnnpack_pytorch_2.0_export")
|
| 155 |
+
.set_backend_pattern_configs(get_linear_configs())
|
| 156 |
+
.set_backend_pattern_configs(get_binary_op_configs())
|
| 157 |
+
.set_backend_pattern_configs(get_conv_configs())
|
| 158 |
+
.set_backend_pattern_configs(get_pooling_configs())
|
| 159 |
+
.set_backend_pattern_configs(get_relu_configs())
|
| 160 |
+
)
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/executorch.py
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
|
| 13 |
+
from ..fuser_method_mappings import (
|
| 14 |
+
_sequential_wrapper2,
|
| 15 |
+
fuse_conv_bn,
|
| 16 |
+
fuse_conv_bn_relu,
|
| 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 [operator.add, torch.add, operator.sub, torch.sub, operator.mul, torch.mul]:
|
| 315 |
+
bop_patterns = [
|
| 316 |
+
(op, torch.nn.ReLU),
|
| 317 |
+
(op, torch.nn.functional.relu),
|
| 318 |
+
(op, torch.relu),
|
| 319 |
+
op
|
| 320 |
+
]
|
| 321 |
+
for bop_pattern in bop_patterns:
|
| 322 |
+
binary_op_configs.append(
|
| 323 |
+
BackendPatternConfig(bop_pattern)
|
| 324 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 325 |
+
._set_num_tensor_args_to_observation_type(
|
| 326 |
+
num_tensor_args_to_observation_type_mapping
|
| 327 |
+
)
|
| 328 |
+
)
|
| 329 |
+
return binary_op_configs
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _get_share_qparams_ops_configs() -> List[BackendPatternConfig]:
|
| 333 |
+
"""
|
| 334 |
+
Return the operator configs for the operators that works for both float and quantized
|
| 335 |
+
input if input is quantized, the output Tensor shares the same quantization parameter
|
| 336 |
+
with input.
|
| 337 |
+
|
| 338 |
+
Example operator: avgpool2d, reshape, transpose, maxpool2d
|
| 339 |
+
Example observed operator:
|
| 340 |
+
observer_0 - avgpool2d - observer_0 (same observer instance as input)
|
| 341 |
+
"""
|
| 342 |
+
observation_type = ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT
|
| 343 |
+
dtype_configs = [
|
| 344 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 345 |
+
executorch_default_op_quint8_dtype_config,
|
| 346 |
+
]
|
| 347 |
+
share_qparams_ops = [
|
| 348 |
+
F.adaptive_avg_pool2d,
|
| 349 |
+
F.elu,
|
| 350 |
+
F.hardtanh,
|
| 351 |
+
F.max_pool2d,
|
| 352 |
+
F.pad,
|
| 353 |
+
F.relu,
|
| 354 |
+
F.relu6,
|
| 355 |
+
F.leaky_relu,
|
| 356 |
+
F.leaky_relu_,
|
| 357 |
+
torch.nn.AdaptiveAvgPool2d,
|
| 358 |
+
torch.nn.ConstantPad2d,
|
| 359 |
+
torch.nn.ELU,
|
| 360 |
+
torch.nn.MaxPool2d,
|
| 361 |
+
torch.nn.ReLU6,
|
| 362 |
+
torch.nn.Hardtanh,
|
| 363 |
+
torch.nn.LeakyReLU,
|
| 364 |
+
torch.clamp,
|
| 365 |
+
torch.flatten,
|
| 366 |
+
torch.mean,
|
| 367 |
+
torch.permute,
|
| 368 |
+
torch.permute_copy,
|
| 369 |
+
torch.squeeze,
|
| 370 |
+
"clamp",
|
| 371 |
+
"mean",
|
| 372 |
+
"permute",
|
| 373 |
+
"reshape",
|
| 374 |
+
"relu",
|
| 375 |
+
"relu_",
|
| 376 |
+
"squeeze",
|
| 377 |
+
"squeeze_",
|
| 378 |
+
"leaky_relu",
|
| 379 |
+
]
|
| 380 |
+
share_qparams_op_configs: List[BackendPatternConfig] = []
|
| 381 |
+
for op in share_qparams_ops:
|
| 382 |
+
share_qparams_op_configs.append(
|
| 383 |
+
BackendPatternConfig(op)
|
| 384 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 385 |
+
.set_dtype_configs(dtype_configs)
|
| 386 |
+
)
|
| 387 |
+
return share_qparams_op_configs
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def _get_bn_configs() -> List[BackendPatternConfig]:
|
| 391 |
+
"""
|
| 392 |
+
Return all configs related to batchnorm.
|
| 393 |
+
"""
|
| 394 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 395 |
+
dtype_configs = [
|
| 396 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 397 |
+
executorch_default_op_quint8_dtype_config,
|
| 398 |
+
]
|
| 399 |
+
bn_configs = []
|
| 400 |
+
bn_configs.append(
|
| 401 |
+
BackendPatternConfig(nn.BatchNorm2d)
|
| 402 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 403 |
+
.set_dtype_configs(dtype_configs)
|
| 404 |
+
)
|
| 405 |
+
return bn_configs
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def _get_cat_configs() -> List[BackendPatternConfig]:
|
| 409 |
+
dtype_configs = [
|
| 410 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 411 |
+
executorch_default_op_quint8_dtype_config,
|
| 412 |
+
]
|
| 413 |
+
cat_configs = []
|
| 414 |
+
cat_configs.append(
|
| 415 |
+
BackendPatternConfig(torch.cat)
|
| 416 |
+
.set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT)
|
| 417 |
+
.set_dtype_configs(dtype_configs)
|
| 418 |
+
)
|
| 419 |
+
cat_configs.append(
|
| 420 |
+
BackendPatternConfig(torch.concat)
|
| 421 |
+
.set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT)
|
| 422 |
+
.set_dtype_configs(dtype_configs)
|
| 423 |
+
)
|
| 424 |
+
cat_configs.append(
|
| 425 |
+
BackendPatternConfig(torch.concatenate)
|
| 426 |
+
.set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT)
|
| 427 |
+
.set_dtype_configs(dtype_configs)
|
| 428 |
+
)
|
| 429 |
+
return cat_configs
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def _get_embedding_op_configs() -> List[BackendPatternConfig]:
|
| 433 |
+
dtype_configs = [
|
| 434 |
+
executorch_weight_only_quint8_dtype_config,
|
| 435 |
+
]
|
| 436 |
+
embedding_op_configs = []
|
| 437 |
+
for embedding_op, qat_embedding_op, ref_embedding_op in [
|
| 438 |
+
(nn.Embedding, nnqat.Embedding, nnqr.Embedding),
|
| 439 |
+
(nn.EmbeddingBag, nnqat.EmbeddingBag, nnqr.EmbeddingBag),
|
| 440 |
+
]:
|
| 441 |
+
embedding_op_configs.append(
|
| 442 |
+
BackendPatternConfig(embedding_op)
|
| 443 |
+
.set_observation_type(
|
| 444 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 445 |
+
) # noqa: E131
|
| 446 |
+
.set_dtype_configs(dtype_configs)
|
| 447 |
+
.set_qat_module(qat_embedding_op)
|
| 448 |
+
.set_root_module(embedding_op)
|
| 449 |
+
.set_reference_quantized_module(ref_embedding_op)
|
| 450 |
+
)
|
| 451 |
+
# config for qat op
|
| 452 |
+
embedding_op_configs.append(
|
| 453 |
+
BackendPatternConfig(qat_embedding_op)
|
| 454 |
+
.set_observation_type(
|
| 455 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 456 |
+
) # noqa: E131
|
| 457 |
+
.set_dtype_configs(dtype_configs)
|
| 458 |
+
.set_root_module(embedding_op)
|
| 459 |
+
.set_reference_quantized_module(ref_embedding_op)
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
# config for functional embedding
|
| 463 |
+
embedding_op_configs.append(
|
| 464 |
+
BackendPatternConfig(torch.nn.functional.embedding)
|
| 465 |
+
.set_observation_type(
|
| 466 |
+
ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 467 |
+
) # noqa: E131
|
| 468 |
+
.set_dtype_configs(dtype_configs)
|
| 469 |
+
._set_input_type_to_index({"weight": 1})
|
| 470 |
+
)
|
| 471 |
+
return embedding_op_configs
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
# =====================
|
| 476 |
+
# | BACKEND CONFIGS |
|
| 477 |
+
# =====================
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def get_executorch_backend_config() -> BackendConfig:
|
| 481 |
+
"""
|
| 482 |
+
Return the `BackendConfig` for backends PyTorch lowers to through the Executorch stack.
|
| 483 |
+
"""
|
| 484 |
+
return (
|
| 485 |
+
BackendConfig("executorch")
|
| 486 |
+
.set_backend_pattern_configs(_get_linear_configs())
|
| 487 |
+
.set_backend_pattern_configs(_get_conv_configs())
|
| 488 |
+
.set_backend_pattern_configs(_get_binary_ops_configs())
|
| 489 |
+
.set_backend_pattern_configs(_get_share_qparams_ops_configs())
|
| 490 |
+
.set_backend_pattern_configs(_get_bn_configs())
|
| 491 |
+
.set_backend_pattern_configs(_get_cat_configs())
|
| 492 |
+
.set_backend_pattern_configs(_get_embedding_op_configs())
|
| 493 |
+
)
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/native.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from ._common_operator_config_utils import (
|
| 3 |
+
_get_binary_op_configs,
|
| 4 |
+
_get_bn_configs,
|
| 5 |
+
_get_cat_config,
|
| 6 |
+
_get_conv_configs,
|
| 7 |
+
_get_default_op_configs,
|
| 8 |
+
_get_embedding_op_configs,
|
| 9 |
+
_get_fixed_qparams_op_configs,
|
| 10 |
+
_get_linear_configs,
|
| 11 |
+
_get_ln_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 |
+
__all__ = [
|
| 19 |
+
"get_test_only_legacy_native_backend_config",
|
| 20 |
+
"default_op_quint8_dtype_config",
|
| 21 |
+
"default_op_fp16_dtype_config",
|
| 22 |
+
"default_dynamic_int8_dtype_config",
|
| 23 |
+
"default_dynamic_float16_dtype_config",
|
| 24 |
+
"input_output_only_quint8_dtype_config",
|
| 25 |
+
"weight_only_quint8_dtype_config",
|
| 26 |
+
"weight_only_quint4x2_dtype_config",
|
| 27 |
+
"get_native_backend_config",
|
| 28 |
+
"get_native_backend_config_dict",
|
| 29 |
+
"get_test_only_legacy_native_backend_config_dict",
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
# ===================
|
| 33 |
+
# | DTYPE CONFIGS |
|
| 34 |
+
# ===================
|
| 35 |
+
|
| 36 |
+
# weighted op int8 dtype config
|
| 37 |
+
# this is config for ops that has quantized weights, like linear, conv
|
| 38 |
+
weighted_op_quint8_dtype_config = DTypeConfig(
|
| 39 |
+
input_dtype=torch.quint8,
|
| 40 |
+
output_dtype=torch.quint8,
|
| 41 |
+
weight_dtype=torch.qint8,
|
| 42 |
+
bias_dtype=torch.float,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
default_op_quint8_dtype_config = DTypeConfig(
|
| 46 |
+
input_dtype=torch.quint8,
|
| 47 |
+
output_dtype=torch.quint8,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
default_op_fp16_dtype_config = DTypeConfig(
|
| 51 |
+
input_dtype=torch.float16,
|
| 52 |
+
output_dtype=torch.float16,
|
| 53 |
+
weight_dtype=torch.float16,
|
| 54 |
+
bias_dtype=torch.float16,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
default_dynamic_int8_dtype_config = DTypeConfig(
|
| 58 |
+
input_dtype=torch.quint8,
|
| 59 |
+
output_dtype=torch.float,
|
| 60 |
+
weight_dtype=torch.qint8,
|
| 61 |
+
bias_dtype=torch.float,
|
| 62 |
+
# currently the dtype check is not yet enabled, so we provided the dtype_configs but
|
| 63 |
+
# it is not really used yet,
|
| 64 |
+
# we will enable it a bit later after we moved everything to backend_config_dict
|
| 65 |
+
is_dynamic=True,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
default_dynamic_float16_dtype_config = DTypeConfig(
|
| 69 |
+
input_dtype=torch.float16,
|
| 70 |
+
output_dtype=torch.float,
|
| 71 |
+
weight_dtype=torch.float16,
|
| 72 |
+
bias_dtype=torch.float,
|
| 73 |
+
# currently the dtype check is not yet enabled, so we provided the dtype_configs but
|
| 74 |
+
# it is not really used yet,
|
| 75 |
+
# we will enable it a bit later after we moved everything to backend_config_dict
|
| 76 |
+
is_dynamic=True,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
# Needed for LayerNorm and f.layer_norm, since currently the kernel only supports float weights
|
| 80 |
+
input_output_only_quint8_dtype_config = DTypeConfig(
|
| 81 |
+
input_dtype=torch.quint8,
|
| 82 |
+
output_dtype=torch.quint8,
|
| 83 |
+
weight_dtype=torch.float,
|
| 84 |
+
bias_dtype=torch.float,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
weight_only_quint8_dtype_config = DTypeConfig(
|
| 88 |
+
input_dtype=torch.float,
|
| 89 |
+
output_dtype=torch.float,
|
| 90 |
+
weight_dtype=torch.quint8,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
weight_only_quint4x2_dtype_config = DTypeConfig(
|
| 94 |
+
input_dtype=torch.float,
|
| 95 |
+
output_dtype=torch.float,
|
| 96 |
+
weight_dtype=torch.quint4x2,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# =====================
|
| 101 |
+
# | BACKEND CONFIGS |
|
| 102 |
+
# =====================
|
| 103 |
+
|
| 104 |
+
def get_test_only_legacy_native_backend_config() -> BackendConfig:
|
| 105 |
+
"""
|
| 106 |
+
Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack) with various additional fp16 ops.
|
| 107 |
+
"""
|
| 108 |
+
conv_dtype_configs = [weighted_op_quint8_dtype_config]
|
| 109 |
+
linear_dtype_configs = [
|
| 110 |
+
weighted_op_quint8_dtype_config,
|
| 111 |
+
default_dynamic_int8_dtype_config,
|
| 112 |
+
default_dynamic_float16_dtype_config,
|
| 113 |
+
default_op_fp16_dtype_config,
|
| 114 |
+
]
|
| 115 |
+
binary_op_dtype_configs = [
|
| 116 |
+
default_op_quint8_dtype_config,
|
| 117 |
+
default_op_fp16_dtype_config,
|
| 118 |
+
]
|
| 119 |
+
default_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 120 |
+
fixed_qparams_op_dtype_configs = [
|
| 121 |
+
default_op_quint8_dtype_config,
|
| 122 |
+
default_op_fp16_dtype_config,
|
| 123 |
+
]
|
| 124 |
+
share_qparams_op_dtype_configs = [
|
| 125 |
+
default_op_quint8_dtype_config,
|
| 126 |
+
default_op_fp16_dtype_config
|
| 127 |
+
]
|
| 128 |
+
tensor_info_op_dtype_configs = [
|
| 129 |
+
default_op_quint8_dtype_config,
|
| 130 |
+
]
|
| 131 |
+
rnn_op_dtype_configs = [
|
| 132 |
+
default_dynamic_int8_dtype_config,
|
| 133 |
+
default_dynamic_float16_dtype_config,
|
| 134 |
+
]
|
| 135 |
+
embedding_op_dtype_configs = [
|
| 136 |
+
weight_only_quint8_dtype_config,
|
| 137 |
+
weight_only_quint4x2_dtype_config,
|
| 138 |
+
]
|
| 139 |
+
layer_norm_op_dtype_configs = [input_output_only_quint8_dtype_config]
|
| 140 |
+
return BackendConfig("_native_and_fp16") \
|
| 141 |
+
.set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs)) \
|
| 142 |
+
.set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs)) \
|
| 143 |
+
.set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \
|
| 144 |
+
.set_backend_pattern_config(_get_cat_config(default_op_dtype_configs)) \
|
| 145 |
+
.set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs)) \
|
| 146 |
+
.set_backend_pattern_configs(_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)) \
|
| 147 |
+
.set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \
|
| 148 |
+
.set_backend_pattern_configs(_get_tensor_info_op_configs(tensor_info_op_dtype_configs)) \
|
| 149 |
+
.set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs)) \
|
| 150 |
+
.set_backend_pattern_configs(_get_ln_configs(layer_norm_op_dtype_configs)) \
|
| 151 |
+
.set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs)) \
|
| 152 |
+
.set_backend_pattern_configs(_get_embedding_op_configs(embedding_op_dtype_configs))
|
| 153 |
+
|
| 154 |
+
def get_native_backend_config() -> BackendConfig:
|
| 155 |
+
"""
|
| 156 |
+
Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack).
|
| 157 |
+
"""
|
| 158 |
+
# TODO: express this BackendConfig as a union of the FBGEMM and QNNPACK BackendConfigs
|
| 159 |
+
conv_dtype_configs = [weighted_op_quint8_dtype_config]
|
| 160 |
+
linear_dtype_configs = [
|
| 161 |
+
weighted_op_quint8_dtype_config,
|
| 162 |
+
default_dynamic_int8_dtype_config,
|
| 163 |
+
default_dynamic_float16_dtype_config,
|
| 164 |
+
]
|
| 165 |
+
binary_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 166 |
+
default_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 167 |
+
fixed_qparams_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 168 |
+
share_qparams_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 169 |
+
tensor_info_op_dtype_configs = [default_op_quint8_dtype_config]
|
| 170 |
+
rnn_op_dtype_configs = [
|
| 171 |
+
default_dynamic_int8_dtype_config,
|
| 172 |
+
default_dynamic_float16_dtype_config,
|
| 173 |
+
]
|
| 174 |
+
embedding_op_dtype_configs = [
|
| 175 |
+
weight_only_quint8_dtype_config,
|
| 176 |
+
weight_only_quint4x2_dtype_config,
|
| 177 |
+
]
|
| 178 |
+
layer_norm_op_dtype_configs = [input_output_only_quint8_dtype_config]
|
| 179 |
+
return BackendConfig("native") \
|
| 180 |
+
.set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs)) \
|
| 181 |
+
.set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs)) \
|
| 182 |
+
.set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \
|
| 183 |
+
.set_backend_pattern_config(_get_cat_config(default_op_dtype_configs)) \
|
| 184 |
+
.set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs)) \
|
| 185 |
+
.set_backend_pattern_configs(_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)) \
|
| 186 |
+
.set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \
|
| 187 |
+
.set_backend_pattern_configs(_get_tensor_info_op_configs(tensor_info_op_dtype_configs)) \
|
| 188 |
+
.set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs)) \
|
| 189 |
+
.set_backend_pattern_configs(_get_ln_configs(layer_norm_op_dtype_configs)) \
|
| 190 |
+
.set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs)) \
|
| 191 |
+
.set_backend_pattern_configs(_get_embedding_op_configs(embedding_op_dtype_configs))
|
| 192 |
+
|
| 193 |
+
def get_native_backend_config_dict():
|
| 194 |
+
"""
|
| 195 |
+
Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack) in dictionary form.
|
| 196 |
+
"""
|
| 197 |
+
return get_native_backend_config().to_dict()
|
| 198 |
+
|
| 199 |
+
def get_test_only_legacy_native_backend_config_dict():
|
| 200 |
+
"""
|
| 201 |
+
Return the `BackendConfig` for PyTorch Native backend (fbgemm/qnnpack) with various additional
|
| 202 |
+
fp16 ops in dictionary form.
|
| 203 |
+
"""
|
| 204 |
+
return get_test_only_legacy_native_backend_config().to_dict()
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/observation_type.py
ADDED
|
File without changes
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/onednn.py
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.ao.nn.intrinsic as nni
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import torch.ao.nn.quantized.reference as nnqr
|
| 6 |
+
from ._common_operator_config_utils import (
|
| 7 |
+
_get_conv_configs,
|
| 8 |
+
_get_linear_configs,
|
| 9 |
+
_get_binary_op_configs,
|
| 10 |
+
_get_bn_configs,
|
| 11 |
+
_get_cat_config,
|
| 12 |
+
_get_default_op_configs,
|
| 13 |
+
_get_embedding_op_configs,
|
| 14 |
+
_get_fixed_qparams_op_configs,
|
| 15 |
+
_get_ln_configs,
|
| 16 |
+
_get_rnn_op_configs,
|
| 17 |
+
_get_share_qparams_op_configs,
|
| 18 |
+
)
|
| 19 |
+
from .backend_config import (
|
| 20 |
+
BackendPatternConfig,
|
| 21 |
+
BackendConfig,
|
| 22 |
+
DTypeConfig,
|
| 23 |
+
ObservationType,
|
| 24 |
+
)
|
| 25 |
+
from ..fuser_method_mappings import (
|
| 26 |
+
_sequential_wrapper2,
|
| 27 |
+
)
|
| 28 |
+
import operator
|
| 29 |
+
from torch.ao.quantization.utils import MatchAllNode
|
| 30 |
+
import itertools
|
| 31 |
+
|
| 32 |
+
# ===================
|
| 33 |
+
# | DTYPE CONFIGS |
|
| 34 |
+
# ===================
|
| 35 |
+
|
| 36 |
+
onednn_weighted_op_int8_dtype_config = DTypeConfig(
|
| 37 |
+
input_dtype=torch.quint8,
|
| 38 |
+
output_dtype=torch.quint8,
|
| 39 |
+
weight_dtype=torch.qint8,
|
| 40 |
+
bias_dtype=torch.float,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
onednn_op_quint8_dtype_config = DTypeConfig(
|
| 44 |
+
input_dtype=torch.quint8,
|
| 45 |
+
output_dtype=torch.quint8,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
onednn_dynamic_int8_dtype_config = DTypeConfig(
|
| 49 |
+
input_dtype=torch.quint8,
|
| 50 |
+
output_dtype=torch.float,
|
| 51 |
+
weight_dtype=torch.qint8,
|
| 52 |
+
bias_dtype=torch.float,
|
| 53 |
+
is_dynamic=True,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
onednn_weight_only_qint8_dtype_config = DTypeConfig(
|
| 57 |
+
input_dtype=torch.float,
|
| 58 |
+
output_dtype=torch.float,
|
| 59 |
+
weight_dtype=torch.qint8,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
onednn_input_output_only_quint8_dtype_config = DTypeConfig(
|
| 63 |
+
input_dtype=torch.quint8,
|
| 64 |
+
output_dtype=torch.quint8,
|
| 65 |
+
weight_dtype=torch.float,
|
| 66 |
+
bias_dtype=torch.float,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
# ===================
|
| 70 |
+
# | FUSER METHODS |
|
| 71 |
+
# ===================
|
| 72 |
+
|
| 73 |
+
def _fuse_linear_bn_leaky_relu(is_qat, linear, bn, leaky_relu):
|
| 74 |
+
r"""Given the linear, bn and leaky_relu modules, fuses them and returns the fused module
|
| 75 |
+
Args:
|
| 76 |
+
is_qat: a flag for whether we are using quantization aware training fusion
|
| 77 |
+
or post training quantization fusion
|
| 78 |
+
linear: Module instance of type Linear
|
| 79 |
+
bn: BatchNorm1d instance that needs to be fused with the linear layer
|
| 80 |
+
leaky_relu: LeakyReLU instance that needs to be fused with the linear layer
|
| 81 |
+
Examples::
|
| 82 |
+
>>> # xdoctest: +SKIP(failing)
|
| 83 |
+
>>> m1 = nn.Linear(20, 10)
|
| 84 |
+
>>> b1 = nn.BatchNorm1d(10)
|
| 85 |
+
>>> lr = nn.LeakyReLU(0.01)
|
| 86 |
+
>>> m2 = _fuse_linear_bn_leaky_relu(m1, b1, lr)
|
| 87 |
+
"""
|
| 88 |
+
assert(linear.training == bn.training and bn.training == leaky_relu.training),\
|
| 89 |
+
"Linear, BN and LeakyReLU all must be in the same mode (train or eval)."
|
| 90 |
+
|
| 91 |
+
if is_qat:
|
| 92 |
+
raise NotImplementedError(f"Cannot fuse train modules: {(linear, bn, leaky_relu)}")
|
| 93 |
+
else:
|
| 94 |
+
map_to_fused_module_eval = {
|
| 95 |
+
nn.Linear: nni.LinearLeakyReLU,
|
| 96 |
+
}
|
| 97 |
+
fused_module = map_to_fused_module_eval.get(type(linear), None)
|
| 98 |
+
if fused_module is not None:
|
| 99 |
+
fused_linear = nn.utils.fusion.fuse_linear_bn_eval(linear, bn)
|
| 100 |
+
fm = fused_module(fused_linear, leaky_relu)
|
| 101 |
+
return fm
|
| 102 |
+
else:
|
| 103 |
+
raise NotImplementedError(f"Cannot fuse eval modules: {(linear, bn, leaky_relu)}")
|
| 104 |
+
|
| 105 |
+
# ======================
|
| 106 |
+
# | CONFIGS FOR CONV |
|
| 107 |
+
# ======================
|
| 108 |
+
observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
|
| 109 |
+
|
| 110 |
+
conv_dtype_configs = [onednn_weighted_op_int8_dtype_config]
|
| 111 |
+
conv_configs = _get_conv_configs(conv_dtype_configs)
|
| 112 |
+
|
| 113 |
+
# (1) Conv2d + Add
|
| 114 |
+
|
| 115 |
+
# conv2d Y
|
| 116 |
+
# \ /
|
| 117 |
+
# add
|
| 118 |
+
|
| 119 |
+
# include:
|
| 120 |
+
# conv2d conv2d
|
| 121 |
+
# \ /
|
| 122 |
+
# add
|
| 123 |
+
|
| 124 |
+
def _fuse_conv_add_left(is_qat, add, conv, _):
|
| 125 |
+
return nni.ConvAdd2d(conv, add)
|
| 126 |
+
|
| 127 |
+
def _conv_add_root_node_getter_left(pattern):
|
| 128 |
+
_, conv, _ = pattern
|
| 129 |
+
return conv
|
| 130 |
+
|
| 131 |
+
def _conv_add_extra_inputs_getter_left(pattern):
|
| 132 |
+
""" get inputs pattern for extra inputs, inputs for root node
|
| 133 |
+
are assumed to be copied over from root node to the fused node
|
| 134 |
+
"""
|
| 135 |
+
_, conv, extra_input = pattern
|
| 136 |
+
return [extra_input]
|
| 137 |
+
|
| 138 |
+
# conv2d
|
| 139 |
+
# \
|
| 140 |
+
# bn Y
|
| 141 |
+
# \ /
|
| 142 |
+
# add
|
| 143 |
+
|
| 144 |
+
def _fuse_conv_bn_add_left(is_qat, add, bn_conv, _):
|
| 145 |
+
bn, conv = bn_conv
|
| 146 |
+
if is_qat:
|
| 147 |
+
raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn, add)}")
|
| 148 |
+
else:
|
| 149 |
+
fused_conv = nn.utils.fusion.fuse_conv_bn_eval(conv, bn)
|
| 150 |
+
return nni.ConvAdd2d(fused_conv, add)
|
| 151 |
+
|
| 152 |
+
def _conv_bn_add_root_node_getter_left(add_pattern):
|
| 153 |
+
_, bn_conv, _ = add_pattern
|
| 154 |
+
bn, conv = bn_conv
|
| 155 |
+
return conv
|
| 156 |
+
|
| 157 |
+
def _conv_bn_add_extra_inputs_getter_left(add_pattern):
|
| 158 |
+
""" get inputs pattern for extra inputs, inputs for root node
|
| 159 |
+
are assumed to be copied over from root node to the fused node
|
| 160 |
+
"""
|
| 161 |
+
_, bn_conv, extra_input = add_pattern
|
| 162 |
+
bn, conv = bn_conv
|
| 163 |
+
return [extra_input]
|
| 164 |
+
|
| 165 |
+
conv_add_left_optioins = itertools.product(
|
| 166 |
+
[True, False], # with_bn
|
| 167 |
+
[torch.add, operator.add], # add_op
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
for with_bn, add_op in conv_add_left_optioins:
|
| 171 |
+
if with_bn:
|
| 172 |
+
conv_configs.append(
|
| 173 |
+
BackendPatternConfig()
|
| 174 |
+
._set_pattern_complex_format((add_op, (nn.BatchNorm2d, nn.Conv2d), MatchAllNode)) # noqa: E131
|
| 175 |
+
.set_observation_type(observation_type)
|
| 176 |
+
.set_dtype_configs(conv_dtype_configs)
|
| 177 |
+
.set_fuser_method(_fuse_conv_bn_add_left)
|
| 178 |
+
._set_root_node_getter(_conv_bn_add_root_node_getter_left)
|
| 179 |
+
._set_extra_inputs_getter(_conv_bn_add_extra_inputs_getter_left)
|
| 180 |
+
.set_fused_module(nni.ConvAdd2d))
|
| 181 |
+
else:
|
| 182 |
+
conv_configs.append(
|
| 183 |
+
BackendPatternConfig()
|
| 184 |
+
._set_pattern_complex_format((add_op, nn.Conv2d, MatchAllNode)) # noqa: E131
|
| 185 |
+
.set_observation_type(observation_type)
|
| 186 |
+
.set_dtype_configs(conv_dtype_configs)
|
| 187 |
+
.set_fuser_method(_fuse_conv_add_left)
|
| 188 |
+
._set_root_node_getter(_conv_add_root_node_getter_left)
|
| 189 |
+
._set_extra_inputs_getter(_conv_add_extra_inputs_getter_left)
|
| 190 |
+
.set_fused_module(nni.ConvAdd2d))
|
| 191 |
+
|
| 192 |
+
# Y conv2d
|
| 193 |
+
# \ /
|
| 194 |
+
# add
|
| 195 |
+
|
| 196 |
+
def _fuse_conv_add_right(is_qat, add, _, conv):
|
| 197 |
+
return nni.ConvAdd2d(conv, add)
|
| 198 |
+
|
| 199 |
+
def _conv_add_root_node_getter_right(pattern):
|
| 200 |
+
add, _, conv = pattern
|
| 201 |
+
return conv
|
| 202 |
+
|
| 203 |
+
def _conv_add_extra_inputs_getter_right(pattern):
|
| 204 |
+
""" get inputs pattern for extra inputs, inputs for root node
|
| 205 |
+
are assumed to be copied over from root node to the fused node
|
| 206 |
+
"""
|
| 207 |
+
_, extra_input, conv = pattern
|
| 208 |
+
return [extra_input]
|
| 209 |
+
|
| 210 |
+
# conv2d
|
| 211 |
+
# /
|
| 212 |
+
# Y bn
|
| 213 |
+
# \ /
|
| 214 |
+
# add
|
| 215 |
+
|
| 216 |
+
def _fuse_conv_bn_add_right(is_qat, add, _, bn_conv):
|
| 217 |
+
bn, conv = bn_conv
|
| 218 |
+
if is_qat:
|
| 219 |
+
raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn, add)}")
|
| 220 |
+
else:
|
| 221 |
+
fused_conv = nn.utils.fusion.fuse_conv_bn_eval(conv, bn)
|
| 222 |
+
return nni.ConvAdd2d(fused_conv, add)
|
| 223 |
+
|
| 224 |
+
def _conv_bn_add_root_node_getter_right(pattern):
|
| 225 |
+
add, _, bn_conv = pattern
|
| 226 |
+
bn, conv = bn_conv
|
| 227 |
+
return conv
|
| 228 |
+
|
| 229 |
+
def _conv_bn_add_extra_inputs_getter_right(pattern):
|
| 230 |
+
""" get inputs pattern for extra inputs, inputs for root node
|
| 231 |
+
are assumed to be copied over from root node to the fused node
|
| 232 |
+
"""
|
| 233 |
+
_, extra_input, bn_conv = pattern
|
| 234 |
+
bn, conv = bn_conv
|
| 235 |
+
return [extra_input]
|
| 236 |
+
|
| 237 |
+
conv_add_optioins = itertools.product(
|
| 238 |
+
[True, False], # with_bn
|
| 239 |
+
[torch.add, operator.add], # add_op
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
for with_bn, add_op in conv_add_optioins:
|
| 243 |
+
if with_bn:
|
| 244 |
+
conv_configs.append(
|
| 245 |
+
BackendPatternConfig()
|
| 246 |
+
._set_pattern_complex_format((add_op, MatchAllNode, (nn.BatchNorm2d, nn.Conv2d))) # noqa: E131
|
| 247 |
+
.set_observation_type(observation_type)
|
| 248 |
+
.set_dtype_configs(conv_dtype_configs)
|
| 249 |
+
.set_fuser_method(_fuse_conv_bn_add_right)
|
| 250 |
+
._set_root_node_getter(_conv_bn_add_root_node_getter_right)
|
| 251 |
+
._set_extra_inputs_getter(_conv_bn_add_extra_inputs_getter_right)
|
| 252 |
+
.set_fused_module(nni.ConvAdd2d))
|
| 253 |
+
else:
|
| 254 |
+
conv_configs.append(
|
| 255 |
+
BackendPatternConfig()
|
| 256 |
+
._set_pattern_complex_format((add_op, MatchAllNode, nn.Conv2d)) # noqa: E131
|
| 257 |
+
.set_observation_type(observation_type)
|
| 258 |
+
.set_dtype_configs(conv_dtype_configs)
|
| 259 |
+
.set_fuser_method(_fuse_conv_add_right)
|
| 260 |
+
._set_root_node_getter(_conv_add_root_node_getter_right)
|
| 261 |
+
._set_extra_inputs_getter(_conv_add_extra_inputs_getter_right)
|
| 262 |
+
.set_fused_module(nni.ConvAdd2d))
|
| 263 |
+
|
| 264 |
+
conv_configs.append(
|
| 265 |
+
BackendPatternConfig(nni.ConvAdd2d)
|
| 266 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 267 |
+
.set_dtype_configs(conv_dtype_configs)
|
| 268 |
+
.set_root_module(nn.Conv2d)
|
| 269 |
+
.set_reference_quantized_module(nnqr.Conv2d))
|
| 270 |
+
|
| 271 |
+
# (2) Conv2d + Add + Relu
|
| 272 |
+
|
| 273 |
+
# conv2d Y
|
| 274 |
+
# \ /
|
| 275 |
+
# add
|
| 276 |
+
# \
|
| 277 |
+
# relu
|
| 278 |
+
|
| 279 |
+
def _fuse_conv_add_relu_left(is_qat, relu, add_pattern):
|
| 280 |
+
add, conv, _ = add_pattern
|
| 281 |
+
return nni.ConvAddReLU2d(conv, add, relu)
|
| 282 |
+
|
| 283 |
+
def _conv_add_relu_root_node_getter_left(pattern):
|
| 284 |
+
relu, add_pattern = pattern
|
| 285 |
+
_, conv, _ = add_pattern
|
| 286 |
+
return conv
|
| 287 |
+
|
| 288 |
+
def _conv_add_relu_extra_inputs_getter_left(pattern):
|
| 289 |
+
""" get inputs pattern for extra inputs, inputs for root node
|
| 290 |
+
are assumed to be copied over from root node to the fused node
|
| 291 |
+
"""
|
| 292 |
+
relu, add_pattern = pattern
|
| 293 |
+
_, conv, extra_input = add_pattern
|
| 294 |
+
return [extra_input]
|
| 295 |
+
|
| 296 |
+
# conv2d
|
| 297 |
+
# \
|
| 298 |
+
# bn Y
|
| 299 |
+
# \ /
|
| 300 |
+
# add
|
| 301 |
+
# \
|
| 302 |
+
# relu
|
| 303 |
+
|
| 304 |
+
def _fuse_conv_bn_add_relu_left(is_qat, relu, add_pattern):
|
| 305 |
+
add, bn_conv, _ = add_pattern
|
| 306 |
+
bn, conv = bn_conv
|
| 307 |
+
if is_qat:
|
| 308 |
+
raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn, add, relu)}")
|
| 309 |
+
else:
|
| 310 |
+
fused_conv = nn.utils.fusion.fuse_conv_bn_eval(conv, bn)
|
| 311 |
+
return nni.ConvAddReLU2d(fused_conv, add, relu)
|
| 312 |
+
|
| 313 |
+
def _conv_bn_add_relu_root_node_getter_left(pattern):
|
| 314 |
+
relu, add_pattern = pattern
|
| 315 |
+
_, bn_conv, _ = add_pattern
|
| 316 |
+
bn, conv = bn_conv
|
| 317 |
+
return conv
|
| 318 |
+
|
| 319 |
+
def _conv_bn_add_relu_extra_inputs_getter_left(pattern):
|
| 320 |
+
""" get inputs pattern for extra inputs, inputs for root node
|
| 321 |
+
are assumed to be copied over from root node to the fused node
|
| 322 |
+
"""
|
| 323 |
+
relu, add_pattern = pattern
|
| 324 |
+
_, bn_conv, extra_input = add_pattern
|
| 325 |
+
bn, conv = bn_conv
|
| 326 |
+
return [extra_input]
|
| 327 |
+
|
| 328 |
+
conv_add_relu_left_optioins = itertools.product(
|
| 329 |
+
[True, False], # with_bn
|
| 330 |
+
[torch.add, operator.add], # add_op
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
for with_bn, add_op in conv_add_relu_left_optioins:
|
| 334 |
+
if with_bn:
|
| 335 |
+
conv_configs.append(
|
| 336 |
+
BackendPatternConfig()
|
| 337 |
+
._set_pattern_complex_format((nn.ReLU, (add_op, (nn.BatchNorm2d, nn.Conv2d), MatchAllNode))) # noqa: E131
|
| 338 |
+
.set_observation_type(observation_type)
|
| 339 |
+
.set_dtype_configs(conv_dtype_configs)
|
| 340 |
+
.set_fuser_method(_fuse_conv_bn_add_relu_left)
|
| 341 |
+
._set_root_node_getter(_conv_bn_add_relu_root_node_getter_left)
|
| 342 |
+
._set_extra_inputs_getter(_conv_bn_add_relu_extra_inputs_getter_left)
|
| 343 |
+
.set_fused_module(nni.ConvAddReLU2d))
|
| 344 |
+
else:
|
| 345 |
+
conv_configs.append(
|
| 346 |
+
BackendPatternConfig()
|
| 347 |
+
._set_pattern_complex_format((nn.ReLU, (add_op, nn.Conv2d, MatchAllNode))) # noqa: E131
|
| 348 |
+
.set_observation_type(observation_type)
|
| 349 |
+
.set_dtype_configs(conv_dtype_configs)
|
| 350 |
+
.set_fuser_method(_fuse_conv_add_relu_left)
|
| 351 |
+
._set_root_node_getter(_conv_add_relu_root_node_getter_left)
|
| 352 |
+
._set_extra_inputs_getter(_conv_add_relu_extra_inputs_getter_left)
|
| 353 |
+
.set_fused_module(nni.ConvAddReLU2d))
|
| 354 |
+
|
| 355 |
+
# Y conv2d
|
| 356 |
+
# \ /
|
| 357 |
+
# add
|
| 358 |
+
# \
|
| 359 |
+
# relu
|
| 360 |
+
|
| 361 |
+
def _fuse_conv_add_relu_right(is_qat, relu, add_pattern):
|
| 362 |
+
add, _, conv = add_pattern
|
| 363 |
+
return nni.ConvAddReLU2d(conv, add, relu)
|
| 364 |
+
|
| 365 |
+
def _conv_add_relu_root_node_getter_right(pattern):
|
| 366 |
+
relu, add_pattern = pattern
|
| 367 |
+
_, _, conv = add_pattern
|
| 368 |
+
return conv
|
| 369 |
+
|
| 370 |
+
def _conv_add_relu_extra_inputs_getter_right(pattern):
|
| 371 |
+
""" get inputs pattern for extra inputs, inputs for root node
|
| 372 |
+
are assumed to be copied over from root node to the fused node
|
| 373 |
+
"""
|
| 374 |
+
relu, add_pattern = pattern
|
| 375 |
+
_, extra_input, conv = add_pattern
|
| 376 |
+
return [extra_input]
|
| 377 |
+
|
| 378 |
+
# conv2d
|
| 379 |
+
# /
|
| 380 |
+
# Y bn
|
| 381 |
+
# \ /
|
| 382 |
+
# add
|
| 383 |
+
# \
|
| 384 |
+
# relu
|
| 385 |
+
|
| 386 |
+
def _fuse_conv_bn_add_relu_right(is_qat, relu, add_pattern):
|
| 387 |
+
add, _, bn_conv = add_pattern
|
| 388 |
+
bn, conv = bn_conv
|
| 389 |
+
if is_qat:
|
| 390 |
+
raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn, add, relu)}")
|
| 391 |
+
else:
|
| 392 |
+
fused_conv = nn.utils.fusion.fuse_conv_bn_eval(conv, bn)
|
| 393 |
+
return nni.ConvAddReLU2d(fused_conv, add, relu)
|
| 394 |
+
|
| 395 |
+
def _conv_bn_add_relu_root_node_getter_right(pattern):
|
| 396 |
+
relu, add_pattern = pattern
|
| 397 |
+
_, _, bn_conv = add_pattern
|
| 398 |
+
bn, conv = bn_conv
|
| 399 |
+
return conv
|
| 400 |
+
|
| 401 |
+
def _conv_bn_add_relu_extra_inputs_getter_right(pattern):
|
| 402 |
+
""" get inputs pattern for extra inputs, inputs for root node
|
| 403 |
+
are assumed to be copied over from root node to the fused node
|
| 404 |
+
"""
|
| 405 |
+
relu, add_pattern = pattern
|
| 406 |
+
_, extra_input, bn_conv = add_pattern
|
| 407 |
+
bn, conv = bn_conv
|
| 408 |
+
return [extra_input]
|
| 409 |
+
|
| 410 |
+
conv_add_relu_optioins = itertools.product(
|
| 411 |
+
[True, False], # with_bn
|
| 412 |
+
[torch.add, operator.add], # add_op
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
for with_bn, add_op in conv_add_relu_optioins:
|
| 416 |
+
if with_bn:
|
| 417 |
+
conv_configs.append(
|
| 418 |
+
BackendPatternConfig()
|
| 419 |
+
._set_pattern_complex_format((nn.ReLU, (add_op, MatchAllNode, (nn.BatchNorm2d, nn.Conv2d)))) # noqa: E131
|
| 420 |
+
.set_observation_type(observation_type)
|
| 421 |
+
.set_dtype_configs(conv_dtype_configs)
|
| 422 |
+
.set_fuser_method(_fuse_conv_bn_add_relu_right)
|
| 423 |
+
._set_root_node_getter(_conv_bn_add_relu_root_node_getter_right)
|
| 424 |
+
._set_extra_inputs_getter(_conv_bn_add_relu_extra_inputs_getter_right)
|
| 425 |
+
.set_fused_module(nni.ConvAddReLU2d))
|
| 426 |
+
else:
|
| 427 |
+
conv_configs.append(
|
| 428 |
+
BackendPatternConfig()
|
| 429 |
+
._set_pattern_complex_format((nn.ReLU, (add_op, MatchAllNode, nn.Conv2d))) # noqa: E131
|
| 430 |
+
.set_observation_type(observation_type)
|
| 431 |
+
.set_dtype_configs(conv_dtype_configs)
|
| 432 |
+
.set_fuser_method(_fuse_conv_add_relu_right)
|
| 433 |
+
._set_root_node_getter(_conv_add_relu_root_node_getter_right)
|
| 434 |
+
._set_extra_inputs_getter(_conv_add_relu_extra_inputs_getter_right)
|
| 435 |
+
.set_fused_module(nni.ConvAddReLU2d))
|
| 436 |
+
|
| 437 |
+
conv_configs.append(
|
| 438 |
+
BackendPatternConfig(nni.ConvAddReLU2d)
|
| 439 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 440 |
+
.set_dtype_configs(conv_dtype_configs)
|
| 441 |
+
.set_root_module(nn.Conv2d)
|
| 442 |
+
.set_reference_quantized_module(nnqr.Conv2d))
|
| 443 |
+
|
| 444 |
+
# ========================
|
| 445 |
+
# | CONFIGS FOR LINEAR |
|
| 446 |
+
# ========================
|
| 447 |
+
|
| 448 |
+
linear_dtype_configs = [
|
| 449 |
+
onednn_weighted_op_int8_dtype_config,
|
| 450 |
+
onednn_dynamic_int8_dtype_config,
|
| 451 |
+
]
|
| 452 |
+
linear_configs = _get_linear_configs(linear_dtype_configs)
|
| 453 |
+
|
| 454 |
+
def _add_eltwise_fusion_configs(configs, root_module, root_op, post_module, post_op,
|
| 455 |
+
dtype_configs, fuser_method, fused_module, observation_type,
|
| 456 |
+
ref_quant_module):
|
| 457 |
+
# 1 base module + op module fusion config
|
| 458 |
+
configs.append(
|
| 459 |
+
BackendPatternConfig((root_module, post_module))
|
| 460 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 461 |
+
.set_fuser_method(fuser_method)
|
| 462 |
+
.set_fused_module(fused_module))
|
| 463 |
+
# base module + functional post op
|
| 464 |
+
configs.append(
|
| 465 |
+
BackendPatternConfig((root_module, post_op))
|
| 466 |
+
.set_dtype_configs(dtype_configs) # noqa: E131
|
| 467 |
+
.set_fuser_method(fuser_method)
|
| 468 |
+
.set_fused_module(fused_module))
|
| 469 |
+
|
| 470 |
+
# 2 fused module configs
|
| 471 |
+
configs.append(
|
| 472 |
+
BackendPatternConfig(fused_module)
|
| 473 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 474 |
+
.set_dtype_configs(dtype_configs)
|
| 475 |
+
.set_root_module(root_module)
|
| 476 |
+
.set_reference_quantized_module(ref_quant_module))
|
| 477 |
+
|
| 478 |
+
# 3 functional base op + post op configs
|
| 479 |
+
configs.append(
|
| 480 |
+
BackendPatternConfig((root_op, post_module))
|
| 481 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 482 |
+
.set_dtype_configs(dtype_configs))
|
| 483 |
+
configs.append(
|
| 484 |
+
BackendPatternConfig((root_op, post_op))
|
| 485 |
+
.set_observation_type(observation_type) # noqa: E131
|
| 486 |
+
.set_dtype_configs(dtype_configs))
|
| 487 |
+
|
| 488 |
+
# Configs for linear + leaky_relu fusion
|
| 489 |
+
_add_eltwise_fusion_configs(linear_configs, nn.Linear, F.linear,
|
| 490 |
+
nn.LeakyReLU, F.leaky_relu, linear_dtype_configs,
|
| 491 |
+
_sequential_wrapper2(nni.LinearLeakyReLU),
|
| 492 |
+
nni.LinearLeakyReLU, observation_type, nnqr.Linear)
|
| 493 |
+
|
| 494 |
+
# Configs for linear module + batchnorm + leaky_relu
|
| 495 |
+
linear_configs.append(
|
| 496 |
+
BackendPatternConfig((nn.Linear, nn.BatchNorm1d, nn.LeakyReLU))
|
| 497 |
+
.set_dtype_configs(linear_dtype_configs) # noqa: E131
|
| 498 |
+
.set_fuser_method(_fuse_linear_bn_leaky_relu)
|
| 499 |
+
.set_fused_module(nni.LinearLeakyReLU))
|
| 500 |
+
|
| 501 |
+
# Configs for linear + tanh fusion
|
| 502 |
+
_add_eltwise_fusion_configs(linear_configs, nn.Linear, F.linear,
|
| 503 |
+
nn.Tanh, torch.tanh, linear_dtype_configs,
|
| 504 |
+
_sequential_wrapper2(nni.LinearTanh),
|
| 505 |
+
nni.LinearTanh, observation_type, nnqr.Linear)
|
| 506 |
+
|
| 507 |
+
# ===========================
|
| 508 |
+
# | CONFIGS FOR OTHER OPS |
|
| 509 |
+
# ===========================
|
| 510 |
+
|
| 511 |
+
binary_op_dtype_configs = [onednn_op_quint8_dtype_config]
|
| 512 |
+
default_op_dtype_configs = [onednn_op_quint8_dtype_config]
|
| 513 |
+
fixed_qparams_op_dtype_configs = [onednn_op_quint8_dtype_config]
|
| 514 |
+
share_qparams_op_dtype_configs = [onednn_op_quint8_dtype_config]
|
| 515 |
+
rnn_op_dtype_configs = [onednn_dynamic_int8_dtype_config]
|
| 516 |
+
embedding_op_dtype_configs = [onednn_weight_only_qint8_dtype_config]
|
| 517 |
+
layer_norm_op_dtype_configs = [onednn_input_output_only_quint8_dtype_config]
|
| 518 |
+
|
| 519 |
+
# =====================
|
| 520 |
+
# | BACKEND CONFIGS |
|
| 521 |
+
# =====================
|
| 522 |
+
|
| 523 |
+
def get_onednn_backend_config() -> BackendConfig:
|
| 524 |
+
"""
|
| 525 |
+
Return the `BackendConfig` for PyTorch's native ONEDNN backend.
|
| 526 |
+
"""
|
| 527 |
+
return BackendConfig("onednn") \
|
| 528 |
+
.set_backend_pattern_configs(conv_configs) \
|
| 529 |
+
.set_backend_pattern_configs(linear_configs) \
|
| 530 |
+
.set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \
|
| 531 |
+
.set_backend_pattern_config(_get_cat_config(default_op_dtype_configs)) \
|
| 532 |
+
.set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs)) \
|
| 533 |
+
.set_backend_pattern_configs(_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)) \
|
| 534 |
+
.set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \
|
| 535 |
+
.set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs)) \
|
| 536 |
+
.set_backend_pattern_configs(_get_ln_configs(layer_norm_op_dtype_configs)) \
|
| 537 |
+
.set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs)) \
|
| 538 |
+
.set_backend_pattern_configs(_get_embedding_op_configs(embedding_op_dtype_configs))
|
| 539 |
+
|
| 540 |
+
__all__ = [
|
| 541 |
+
"get_onednn_backend_config",
|
| 542 |
+
]
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/qnnpack.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from ._common_operator_config_utils import (
|
| 3 |
+
_get_binary_op_configs,
|
| 4 |
+
_get_bn_configs,
|
| 5 |
+
_get_cat_config,
|
| 6 |
+
_get_conv_configs,
|
| 7 |
+
_get_default_op_configs,
|
| 8 |
+
_get_embedding_op_configs,
|
| 9 |
+
_get_fixed_qparams_op_configs,
|
| 10 |
+
_get_linear_configs,
|
| 11 |
+
_get_rnn_op_configs,
|
| 12 |
+
_get_share_qparams_op_configs,
|
| 13 |
+
)
|
| 14 |
+
from .backend_config import BackendConfig, DTypeConfig, DTypeWithConstraints
|
| 15 |
+
|
| 16 |
+
__all__ = [
|
| 17 |
+
"get_qnnpack_backend_config",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
# ===================
|
| 21 |
+
# | DTYPE CONFIGS |
|
| 22 |
+
# ===================
|
| 23 |
+
|
| 24 |
+
qnnpack_weighted_op_quint8_dtype_config = DTypeConfig(
|
| 25 |
+
input_dtype=torch.quint8,
|
| 26 |
+
output_dtype=torch.quint8,
|
| 27 |
+
weight_dtype=torch.qint8,
|
| 28 |
+
bias_dtype=torch.float,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
qnnpack_default_op_quint8_dtype_config = DTypeConfig(
|
| 32 |
+
input_dtype=torch.quint8,
|
| 33 |
+
output_dtype=torch.quint8,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
qnnpack_default_op_fp16_dtype_config = DTypeConfig(
|
| 37 |
+
input_dtype=torch.float16,
|
| 38 |
+
output_dtype=torch.float16,
|
| 39 |
+
weight_dtype=torch.float16,
|
| 40 |
+
bias_dtype=torch.float16,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
qnnpack_default_dynamic_int8_dtype_config = DTypeConfig(
|
| 44 |
+
input_dtype=torch.quint8,
|
| 45 |
+
output_dtype=torch.float,
|
| 46 |
+
weight_dtype=torch.qint8,
|
| 47 |
+
bias_dtype=torch.float,
|
| 48 |
+
is_dynamic=True,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
qnnpack_default_dynamic_float16_dtype_config = DTypeConfig(
|
| 52 |
+
input_dtype=torch.float16,
|
| 53 |
+
output_dtype=torch.float,
|
| 54 |
+
weight_dtype=torch.float16,
|
| 55 |
+
bias_dtype=torch.float,
|
| 56 |
+
is_dynamic=True,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
qnnpack_weight_only_quint8_dtype_config = DTypeConfig(
|
| 60 |
+
input_dtype=torch.float,
|
| 61 |
+
output_dtype=torch.float,
|
| 62 |
+
weight_dtype=torch.quint8,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
qnnpack_weight_only_quint4x2_dtype_config = DTypeConfig(
|
| 66 |
+
input_dtype=torch.float,
|
| 67 |
+
output_dtype=torch.float,
|
| 68 |
+
weight_dtype=torch.quint4x2,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# xnnpack compatible dtype configs
|
| 72 |
+
|
| 73 |
+
# We restrict scale values to be 2 ** -12 to ensure the
|
| 74 |
+
# requantization scale never falls below the xnnpack lower
|
| 75 |
+
# threshold. Additionally, for qint8 weight, we restrict
|
| 76 |
+
# the quantization values to [-127, +127], excluding -128.
|
| 77 |
+
# For more detail, refer to the description of
|
| 78 |
+
# `default_symmetric_qnnpack_qconfig`.
|
| 79 |
+
|
| 80 |
+
# TODO: add additional restriction on qscheme to ensure it
|
| 81 |
+
# is either per_tensor_symmetric or per_channel_symmetric
|
| 82 |
+
|
| 83 |
+
qnnpack_act_qint8_scale_min_2_neg_12 = DTypeWithConstraints(
|
| 84 |
+
dtype=torch.qint8,
|
| 85 |
+
scale_min_lower_bound=2 ** -12,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
qnnpack_weight_qint8_neg_127_to_127_scale_min_2_neg_12 = DTypeWithConstraints(
|
| 89 |
+
dtype=torch.qint8,
|
| 90 |
+
quant_min_lower_bound=-127,
|
| 91 |
+
quant_max_upper_bound=127,
|
| 92 |
+
scale_min_lower_bound=2 ** -12,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
qnnpack_weighted_op_qint8_symmetric_dtype_config = DTypeConfig(
|
| 96 |
+
input_dtype=qnnpack_act_qint8_scale_min_2_neg_12,
|
| 97 |
+
output_dtype=qnnpack_act_qint8_scale_min_2_neg_12,
|
| 98 |
+
weight_dtype=qnnpack_weight_qint8_neg_127_to_127_scale_min_2_neg_12,
|
| 99 |
+
bias_dtype=torch.float,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
qnnpack_default_op_qint8_symmetric_dtype_config = DTypeConfig(
|
| 103 |
+
input_dtype=qnnpack_act_qint8_scale_min_2_neg_12,
|
| 104 |
+
output_dtype=qnnpack_act_qint8_scale_min_2_neg_12,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# =====================
|
| 109 |
+
# | BACKEND CONFIGS |
|
| 110 |
+
# =====================
|
| 111 |
+
|
| 112 |
+
def get_qnnpack_backend_config() -> BackendConfig:
|
| 113 |
+
"""
|
| 114 |
+
Return the `BackendConfig` for PyTorch's native QNNPACK backend.
|
| 115 |
+
"""
|
| 116 |
+
conv_dtype_configs = [
|
| 117 |
+
qnnpack_weighted_op_qint8_symmetric_dtype_config,
|
| 118 |
+
qnnpack_weighted_op_quint8_dtype_config,
|
| 119 |
+
]
|
| 120 |
+
linear_dtype_configs = [
|
| 121 |
+
qnnpack_weighted_op_qint8_symmetric_dtype_config,
|
| 122 |
+
qnnpack_weighted_op_quint8_dtype_config,
|
| 123 |
+
qnnpack_default_dynamic_int8_dtype_config,
|
| 124 |
+
qnnpack_default_dynamic_float16_dtype_config,
|
| 125 |
+
]
|
| 126 |
+
binary_op_dtype_configs = [
|
| 127 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 128 |
+
qnnpack_default_op_quint8_dtype_config,
|
| 129 |
+
]
|
| 130 |
+
default_op_dtype_configs = [
|
| 131 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 132 |
+
qnnpack_default_op_quint8_dtype_config,
|
| 133 |
+
]
|
| 134 |
+
fixed_qparams_op_dtype_configs = [
|
| 135 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 136 |
+
qnnpack_default_op_quint8_dtype_config,
|
| 137 |
+
]
|
| 138 |
+
share_qparams_op_dtype_configs = [
|
| 139 |
+
qnnpack_default_op_qint8_symmetric_dtype_config,
|
| 140 |
+
qnnpack_default_op_quint8_dtype_config,
|
| 141 |
+
]
|
| 142 |
+
rnn_op_dtype_configs = [
|
| 143 |
+
qnnpack_default_dynamic_int8_dtype_config,
|
| 144 |
+
qnnpack_default_dynamic_float16_dtype_config,
|
| 145 |
+
]
|
| 146 |
+
embedding_op_dtype_configs = [
|
| 147 |
+
qnnpack_weight_only_quint8_dtype_config,
|
| 148 |
+
qnnpack_weight_only_quint4x2_dtype_config,
|
| 149 |
+
]
|
| 150 |
+
return BackendConfig("qnnpack") \
|
| 151 |
+
.set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs)) \
|
| 152 |
+
.set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs)) \
|
| 153 |
+
.set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \
|
| 154 |
+
.set_backend_pattern_config(_get_cat_config(default_op_dtype_configs)) \
|
| 155 |
+
.set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs)) \
|
| 156 |
+
.set_backend_pattern_configs(_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)) \
|
| 157 |
+
.set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \
|
| 158 |
+
.set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs)) \
|
| 159 |
+
.set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs)) \
|
| 160 |
+
.set_backend_pattern_configs(_get_embedding_op_configs(embedding_op_dtype_configs))
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/tensorrt.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from .backend_config import (
|
| 3 |
+
BackendConfig,
|
| 4 |
+
BackendPatternConfig,
|
| 5 |
+
DTypeConfig,
|
| 6 |
+
ObservationType
|
| 7 |
+
)
|
| 8 |
+
from ._common_operator_config_utils import (
|
| 9 |
+
_get_binary_op_configs,
|
| 10 |
+
_get_linear_configs,
|
| 11 |
+
_get_conv_configs,
|
| 12 |
+
_get_share_qparams_op_configs,
|
| 13 |
+
_get_tensor_info_op_configs,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
__all__ = [
|
| 17 |
+
"get_tensorrt_backend_config",
|
| 18 |
+
"get_tensorrt_backend_config_dict",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
def get_tensorrt_backend_config() -> BackendConfig:
|
| 22 |
+
"""
|
| 23 |
+
Return the `BackendConfig` for the TensorRT backend.
|
| 24 |
+
NOTE: Current api will change in the future, it's just to unblock experimentation for
|
| 25 |
+
new backends, please don't use it right now.
|
| 26 |
+
TODO: add a README when it's more stable
|
| 27 |
+
"""
|
| 28 |
+
# dtype configs
|
| 29 |
+
weighted_op_qint8_dtype_config = DTypeConfig(
|
| 30 |
+
input_dtype=torch.qint8,
|
| 31 |
+
output_dtype=torch.qint8,
|
| 32 |
+
weight_dtype=torch.qint8,
|
| 33 |
+
bias_dtype=torch.float,
|
| 34 |
+
)
|
| 35 |
+
non_weighted_op_qint8_dtype_config = DTypeConfig(
|
| 36 |
+
input_dtype=torch.qint8,
|
| 37 |
+
output_dtype=torch.qint8,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
addmm_config = BackendPatternConfig(torch.addmm) \
|
| 41 |
+
.set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
|
| 42 |
+
.add_dtype_config(weighted_op_qint8_dtype_config) \
|
| 43 |
+
._set_input_type_to_index({
|
| 44 |
+
"bias": 0,
|
| 45 |
+
"input": 1,
|
| 46 |
+
"weight": 2,
|
| 47 |
+
})
|
| 48 |
+
cat_config = BackendPatternConfig(torch.cat) \
|
| 49 |
+
.set_observation_type(ObservationType.OUTPUT_SHARE_OBSERVER_WITH_INPUT) \
|
| 50 |
+
.add_dtype_config(non_weighted_op_qint8_dtype_config)
|
| 51 |
+
conv_dtype_configs = [
|
| 52 |
+
weighted_op_qint8_dtype_config,
|
| 53 |
+
]
|
| 54 |
+
linear_dtype_configs = [
|
| 55 |
+
weighted_op_qint8_dtype_config,
|
| 56 |
+
]
|
| 57 |
+
binary_op_dtype_configs = [
|
| 58 |
+
weighted_op_qint8_dtype_config,
|
| 59 |
+
]
|
| 60 |
+
share_qparams_op_dtype_configs = [
|
| 61 |
+
non_weighted_op_qint8_dtype_config,
|
| 62 |
+
]
|
| 63 |
+
tensor_info_op_dtype_configs = [
|
| 64 |
+
non_weighted_op_qint8_dtype_config,
|
| 65 |
+
]
|
| 66 |
+
# there might be things not supported in fx2trt, but it will error out
|
| 67 |
+
# during fx2trt conversion and can support them after that
|
| 68 |
+
return BackendConfig("tensorrt") \
|
| 69 |
+
.set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs)) \
|
| 70 |
+
.set_backend_pattern_config(addmm_config) \
|
| 71 |
+
.set_backend_pattern_config(cat_config) \
|
| 72 |
+
.set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs)) \
|
| 73 |
+
.set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \
|
| 74 |
+
.set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \
|
| 75 |
+
.set_backend_pattern_configs(_get_tensor_info_op_configs(tensor_info_op_dtype_configs))
|
| 76 |
+
|
| 77 |
+
def get_tensorrt_backend_config_dict():
|
| 78 |
+
"""
|
| 79 |
+
Return the `BackendConfig` for the TensorRT backend in dictionary form.
|
| 80 |
+
"""
|
| 81 |
+
return get_tensorrt_backend_config().to_dict()
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/utils.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from .backend_config import (
|
| 7 |
+
BackendConfig,
|
| 8 |
+
BackendPatternConfig,
|
| 9 |
+
DTypeConfig,
|
| 10 |
+
)
|
| 11 |
+
from ..utils import Pattern
|
| 12 |
+
from ..fuser_method_mappings import (
|
| 13 |
+
_reverse2,
|
| 14 |
+
_reverse3,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"get_pattern_to_dtype_configs",
|
| 19 |
+
"get_qat_module_classes",
|
| 20 |
+
"get_fused_module_classes",
|
| 21 |
+
"get_pattern_to_input_type_to_index",
|
| 22 |
+
"get_root_module_to_quantized_reference_module",
|
| 23 |
+
"get_fuser_method_mapping",
|
| 24 |
+
"get_module_to_qat_module",
|
| 25 |
+
"get_fusion_pattern_to_root_node_getter",
|
| 26 |
+
"get_fusion_pattern_to_extra_inputs_getter",
|
| 27 |
+
"remove_boolean_dispatch_from_name",
|
| 28 |
+
"pattern_to_human_readable",
|
| 29 |
+
"entry_to_pretty_str",
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
def get_pattern_to_dtype_configs(backend_config: BackendConfig) -> Dict[Pattern, List[DTypeConfig]]:
|
| 33 |
+
pattern_to_dtype_configs: Dict[Pattern, List[DTypeConfig]] = {}
|
| 34 |
+
for pattern, config in backend_config._pattern_complex_format_to_config.items():
|
| 35 |
+
pattern_to_dtype_configs[pattern] = config.dtype_configs
|
| 36 |
+
return pattern_to_dtype_configs
|
| 37 |
+
|
| 38 |
+
def get_qat_module_classes(backend_config: BackendConfig) -> Tuple[type, ...]:
|
| 39 |
+
qat_module_classes = []
|
| 40 |
+
for config in backend_config.configs:
|
| 41 |
+
if config.qat_module is not None:
|
| 42 |
+
qat_module_classes.append(config.qat_module)
|
| 43 |
+
return tuple(set(qat_module_classes))
|
| 44 |
+
|
| 45 |
+
def get_fused_module_classes(backend_config: BackendConfig) -> Tuple[type, ...]:
|
| 46 |
+
fused_module_classes = []
|
| 47 |
+
for config in backend_config.configs:
|
| 48 |
+
if config.fused_module is not None:
|
| 49 |
+
fused_module_classes.append(config.fused_module)
|
| 50 |
+
return tuple(set(fused_module_classes))
|
| 51 |
+
|
| 52 |
+
def get_pattern_to_input_type_to_index(backend_config: BackendConfig) -> Dict[Pattern, Dict[str, int]]:
|
| 53 |
+
pattern_to_input_type_to_index: Dict[Pattern, Dict[str, int]] = {}
|
| 54 |
+
for pattern, config in backend_config._pattern_complex_format_to_config.items():
|
| 55 |
+
pattern_to_input_type_to_index[pattern] = config._input_type_to_index
|
| 56 |
+
return pattern_to_input_type_to_index
|
| 57 |
+
|
| 58 |
+
def get_root_module_to_quantized_reference_module(
|
| 59 |
+
backend_config: BackendConfig) -> Dict[Type[torch.nn.Module], Type[torch.nn.Module]]:
|
| 60 |
+
mapping: Dict[Type[torch.nn.Module], Type[torch.nn.Module]] = {}
|
| 61 |
+
for config in backend_config.configs:
|
| 62 |
+
if config.root_module is not None and config.reference_quantized_module is not None:
|
| 63 |
+
mapping[config.root_module] = config.reference_quantized_module
|
| 64 |
+
return mapping
|
| 65 |
+
|
| 66 |
+
def get_fuser_method_mapping(backend_config: BackendConfig) -> Dict[Pattern, Union[nn.Sequential, Callable]]:
|
| 67 |
+
fuser_method_mapping : Dict[Pattern, Union[nn.Sequential, Callable]] = {}
|
| 68 |
+
for pattern, config in backend_config._pattern_complex_format_to_config.items():
|
| 69 |
+
if config.fuser_method is not None:
|
| 70 |
+
# Note: both the fuser method and the pattern are specified in forward order in the
|
| 71 |
+
# BackendConfig, but the internal pattern matching code uses the reversed nested tuple
|
| 72 |
+
# format, so we need to convert both to the internal format
|
| 73 |
+
fuser_method = _get_fuser_method_in_reversed_nested_tuple_format(config)
|
| 74 |
+
fuser_method_mapping[pattern] = fuser_method
|
| 75 |
+
return fuser_method_mapping
|
| 76 |
+
|
| 77 |
+
def get_module_to_qat_module(backend_config: BackendConfig) -> Dict[Pattern, Type[torch.nn.Module]]:
|
| 78 |
+
module_to_qat_module: Dict[Pattern, Type[torch.nn.Module]] = {}
|
| 79 |
+
for pattern, config in backend_config._pattern_complex_format_to_config.items():
|
| 80 |
+
if config.qat_module is not None:
|
| 81 |
+
module_to_qat_module[pattern] = config.qat_module
|
| 82 |
+
return module_to_qat_module
|
| 83 |
+
|
| 84 |
+
def get_fusion_pattern_to_root_node_getter(backend_config: BackendConfig) -> Dict[Pattern, Callable]:
|
| 85 |
+
""" Get a map from fusion pattern to a function that returns the root node
|
| 86 |
+
from the fusion pattern, e.g. the most common one is:
|
| 87 |
+
def get_root_node(node_pattern):
|
| 88 |
+
while not isinstance(node_pattern[-1], Node):
|
| 89 |
+
node_pattern = node_pattern[-1]
|
| 90 |
+
return node_pattern[-1]
|
| 91 |
+
This can work for all patterns whose root node is the "last node" in the pattern,
|
| 92 |
+
e.g. (torch.add, MatchAllNode, (torch.ReLU, torch.Conv2d))
|
| 93 |
+
"""
|
| 94 |
+
root_node_getter_mapping: Dict[Pattern, Callable] = {}
|
| 95 |
+
for pattern, config in backend_config._pattern_complex_format_to_config.items():
|
| 96 |
+
if config._root_node_getter is not None:
|
| 97 |
+
root_node_getter_mapping[pattern] = config._root_node_getter
|
| 98 |
+
return root_node_getter_mapping
|
| 99 |
+
|
| 100 |
+
def get_fusion_pattern_to_extra_inputs_getter(backend_config: BackendConfig) -> Dict[Pattern, Callable]:
|
| 101 |
+
""" Get a map from fusion pattern to a function that returns extra input nodes
|
| 102 |
+
from the fusion pattern, in the order required by the root node. This is optional,
|
| 103 |
+
if not specified, we will not copy over any extra inputs for the root node.
|
| 104 |
+
Example:
|
| 105 |
+
# Let's say we have the pattern (torch.add, MatchAllNode, (torch.nn.BatchNorm2d, torch.nn.Conv2d))
|
| 106 |
+
# and root node is torch.nn.Conv2d, and the node in MatchAllNode would be an extra
|
| 107 |
+
# argument to the fused module, we can unpack the pattern and return the node at
|
| 108 |
+
# MatchAllNode here
|
| 109 |
+
# we can implement extra_inputs_getter as follows:
|
| 110 |
+
def extra_inputs_getter(pattern) -> List[Any]:
|
| 111 |
+
add, extra_input, conv_pattern = pattern
|
| 112 |
+
return [extra_input]
|
| 113 |
+
"""
|
| 114 |
+
extra_inputs_getter_mapping: Dict[Pattern, Callable] = {}
|
| 115 |
+
for pattern, config in backend_config._pattern_complex_format_to_config.items():
|
| 116 |
+
if config._extra_inputs_getter is not None:
|
| 117 |
+
extra_inputs_getter_mapping[pattern] = config._extra_inputs_getter
|
| 118 |
+
return extra_inputs_getter_mapping
|
| 119 |
+
|
| 120 |
+
def remove_boolean_dispatch_from_name(p) -> Any:
|
| 121 |
+
"""
|
| 122 |
+
Some ops have a default string representation such as
|
| 123 |
+
'<function boolean_dispatch.<locals>.fn at 0x7ff1106bf280>',
|
| 124 |
+
this function replaces them with the hardcoded function names.
|
| 125 |
+
"""
|
| 126 |
+
if p is F.fractional_max_pool2d:
|
| 127 |
+
return "torch.nn.functional.fractional_max_pool2d"
|
| 128 |
+
elif p is F.fractional_max_pool3d:
|
| 129 |
+
return "torch.nn.functional.fractional_max_pool3d"
|
| 130 |
+
elif p is F.max_pool1d:
|
| 131 |
+
return "torch.nn.functional.max_pool1d"
|
| 132 |
+
elif p is F.max_pool2d:
|
| 133 |
+
return "torch.nn.functional.max_pool2d"
|
| 134 |
+
elif p is F.max_pool3d:
|
| 135 |
+
return "torch.nn.functional.max_pool3d"
|
| 136 |
+
elif p is F.adaptive_max_pool1d:
|
| 137 |
+
return "torch.nn.functional.adaptive_max_pool1d"
|
| 138 |
+
elif p is F.adaptive_max_pool2d:
|
| 139 |
+
return "torch.nn.functional.adaptive_max_pool2d"
|
| 140 |
+
elif p is F.adaptive_max_pool3d:
|
| 141 |
+
return "torch.nn.functional.adaptive_max_pool3d"
|
| 142 |
+
assert "boolean_dispatch" not in str(p), \
|
| 143 |
+
f"{p} does not have a human readable representation in " + \
|
| 144 |
+
"quantization documentation"
|
| 145 |
+
return p
|
| 146 |
+
|
| 147 |
+
def pattern_to_human_readable(p) -> Any:
|
| 148 |
+
if isinstance(p, tuple):
|
| 149 |
+
# nested patterns, recurse
|
| 150 |
+
return tuple(pattern_to_human_readable(inner_p) for inner_p in p)
|
| 151 |
+
elif isinstance(p, str):
|
| 152 |
+
# method names are already human readable
|
| 153 |
+
return p
|
| 154 |
+
else:
|
| 155 |
+
p = remove_boolean_dispatch_from_name(p)
|
| 156 |
+
return p
|
| 157 |
+
|
| 158 |
+
# TODO(future PR): move backend_config_dict to use dataclass and move this logic to
|
| 159 |
+
# the corresponding __str__ function
|
| 160 |
+
def entry_to_pretty_str(entry) -> str:
|
| 161 |
+
"""
|
| 162 |
+
Given a backend_config_dict entry, returns a string with the human readable
|
| 163 |
+
representation of it.
|
| 164 |
+
"""
|
| 165 |
+
s = "{\n"
|
| 166 |
+
|
| 167 |
+
# always output the pattern first
|
| 168 |
+
if "pattern" in entry:
|
| 169 |
+
pattern_str = pattern_to_human_readable(entry["pattern"])
|
| 170 |
+
|
| 171 |
+
s += f" 'pattern': {pattern_str},\n"
|
| 172 |
+
|
| 173 |
+
# custom output for dtype_configs to make it look nice
|
| 174 |
+
if "dtype_configs" in entry:
|
| 175 |
+
s += " 'dtype_configs': [\n"
|
| 176 |
+
for dtype_config in entry["dtype_configs"]:
|
| 177 |
+
s += " {\n"
|
| 178 |
+
for k, v in dtype_config.items():
|
| 179 |
+
s += f" '{k}': {v},\n"
|
| 180 |
+
s += " },\n"
|
| 181 |
+
s += " ],\n"
|
| 182 |
+
|
| 183 |
+
# custom output for num_tensor_args_to_observation_type to make it look nice
|
| 184 |
+
if "num_tensor_args_to_observation_type" in entry:
|
| 185 |
+
s += " 'num_tensor_args_to_observation_type': {\n"
|
| 186 |
+
for k, v in entry["num_tensor_args_to_observation_type"].items():
|
| 187 |
+
s += f" {k}: {v},\n"
|
| 188 |
+
s += " },\n"
|
| 189 |
+
|
| 190 |
+
# output all the other fields
|
| 191 |
+
custom_handled_fields = [
|
| 192 |
+
"pattern",
|
| 193 |
+
"dtype_configs",
|
| 194 |
+
"num_tensor_args_to_observation_type",
|
| 195 |
+
]
|
| 196 |
+
for field_name in entry:
|
| 197 |
+
if field_name in custom_handled_fields:
|
| 198 |
+
continue
|
| 199 |
+
s += f" '{field_name}': {entry[field_name]},\n"
|
| 200 |
+
|
| 201 |
+
s += "}"
|
| 202 |
+
return s
|
| 203 |
+
|
| 204 |
+
def _get_pattern_in_reversed_nested_tuple_format(config: BackendPatternConfig) -> Pattern:
|
| 205 |
+
"""
|
| 206 |
+
Return the pattern specified in the given config in the reversed nested tuple format
|
| 207 |
+
used internally in the quantization pattern matching code.
|
| 208 |
+
|
| 209 |
+
If the pattern is not a tuple, or the pattern is already specified in the reversed
|
| 210 |
+
nested tuple format, return the pattern as is. Otherwise:
|
| 211 |
+
|
| 212 |
+
For 2-tuples (a, b), return (b, a).
|
| 213 |
+
For 3-tuples (a, b, c), return (c, (b, a)).
|
| 214 |
+
|
| 215 |
+
For example:
|
| 216 |
+
* Given nn.Linear, return nn.Linear
|
| 217 |
+
* Given (nn.Linear, nn.ReLU), return (nn.ReLU, nn.Linear)
|
| 218 |
+
* Given (nn.Conv2d, nn.BatchNorm2d, nn.ReLU), return
|
| 219 |
+
(nn.ReLU, (nn.BatchNorm2d, nn.Conv2d))
|
| 220 |
+
|
| 221 |
+
For context, the reason why this is needed is the user-facing BackendConfig
|
| 222 |
+
API accepts the flat 2-or-3-tuple format in forward order. While this simple
|
| 223 |
+
format handles the vast majority of use cases, it does not handle the more
|
| 224 |
+
complex ones, and so the internal pattern matching code for quantization uses
|
| 225 |
+
the following, more general reversed nested tuple format instead:
|
| 226 |
+
|
| 227 |
+
operator = module_type | functional | torch op | native op | MatchAllNode
|
| 228 |
+
Pattern = (operator, Pattern, Pattern, ...) | operator
|
| 229 |
+
|
| 230 |
+
In the future, we expect to replace the above complex format with the one used
|
| 231 |
+
by the subgraph rewriter in torch.fx, so we don't have to maintain our own
|
| 232 |
+
complex pattern matching code. Then we won't need this helper function anymore.
|
| 233 |
+
"""
|
| 234 |
+
if config._pattern_complex_format is not None:
|
| 235 |
+
return config._pattern_complex_format
|
| 236 |
+
if config.pattern is None:
|
| 237 |
+
raise ValueError("Either 'pattern' or 'pattern_complex_format' must be specified")
|
| 238 |
+
if not isinstance(config.pattern, tuple):
|
| 239 |
+
return config.pattern
|
| 240 |
+
|
| 241 |
+
# Pattern is specified in the simple tuple format, need to convert
|
| 242 |
+
if len(config.pattern) == 2:
|
| 243 |
+
(a, b) = config.pattern
|
| 244 |
+
return (b, a)
|
| 245 |
+
elif len(config.pattern) == 3:
|
| 246 |
+
(a, b, c) = config.pattern
|
| 247 |
+
return (c, (b, a))
|
| 248 |
+
else:
|
| 249 |
+
raise ValueError("Expected a tuple with 2 or 3 elements, got: ", config.pattern)
|
| 250 |
+
|
| 251 |
+
def _get_fuser_method_in_reversed_nested_tuple_format(config: BackendPatternConfig) -> Callable:
|
| 252 |
+
"""
|
| 253 |
+
Return the fuser method specified in the given config in the reversed nested
|
| 254 |
+
tuple format used internally in the quantization pattern matching code.
|
| 255 |
+
|
| 256 |
+
If pattern is specified in the reversed nested tuple format, we assume the
|
| 257 |
+
fuser method is also specified in this format and simply return it as is.
|
| 258 |
+
Otherwise, we convert the fuser method as follows:
|
| 259 |
+
|
| 260 |
+
* Given f(is_qat, conv, relu), return f'(is_qat, relu, conv)
|
| 261 |
+
* Given f(is_qat, conv, bn, relu), return f'(is_qat, relu, bn_conv),
|
| 262 |
+
where bn_conv is a 2-tuple (bn, conv)
|
| 263 |
+
|
| 264 |
+
The first argument of a fuser method is always `is_qat` and is not affected
|
| 265 |
+
in the conversion. We currently only support functions with 3 or 4 arguments.
|
| 266 |
+
"""
|
| 267 |
+
assert config.fuser_method is not None
|
| 268 |
+
if config._pattern_complex_format is not None:
|
| 269 |
+
return config.fuser_method
|
| 270 |
+
if not isinstance(config.pattern, tuple):
|
| 271 |
+
raise ValueError("Expected pattern to be a tuple, got: ", config.pattern)
|
| 272 |
+
|
| 273 |
+
# Pattern is specified in the simple tuple format, need to convert
|
| 274 |
+
if len(config.pattern) == 2:
|
| 275 |
+
return _reverse2(config.fuser_method)
|
| 276 |
+
elif len(config.pattern) == 3:
|
| 277 |
+
return _reverse3(config.fuser_method)
|
| 278 |
+
else:
|
| 279 |
+
raise ValueError("Expected a tuple with 2 or 3 elements, got: ", config.pattern)
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/backend_config/x86.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from ._common_operator_config_utils import (
|
| 3 |
+
_get_binary_op_configs,
|
| 4 |
+
_get_bn_configs,
|
| 5 |
+
_get_cat_config,
|
| 6 |
+
_get_conv_configs,
|
| 7 |
+
_get_default_op_configs,
|
| 8 |
+
_get_embedding_op_configs,
|
| 9 |
+
_get_fixed_qparams_op_configs,
|
| 10 |
+
_get_linear_configs,
|
| 11 |
+
_get_rnn_op_configs,
|
| 12 |
+
_get_share_qparams_op_configs,
|
| 13 |
+
_get_tensor_info_op_configs,
|
| 14 |
+
)
|
| 15 |
+
from .backend_config import BackendConfig, DTypeConfig
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
"get_x86_backend_config",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
# ===================
|
| 22 |
+
# | DTYPE CONFIGS |
|
| 23 |
+
# ===================
|
| 24 |
+
|
| 25 |
+
# X86 aligns with FBGEMM for now
|
| 26 |
+
|
| 27 |
+
x86_weighted_op_int8_dtype_config = DTypeConfig(
|
| 28 |
+
input_dtype=torch.quint8,
|
| 29 |
+
output_dtype=torch.quint8,
|
| 30 |
+
weight_dtype=torch.qint8,
|
| 31 |
+
bias_dtype=torch.float,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
x86_default_op_quint8_dtype_config = DTypeConfig(
|
| 35 |
+
input_dtype=torch.quint8,
|
| 36 |
+
output_dtype=torch.quint8,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
x86_default_op_fp16_dtype_config = DTypeConfig(
|
| 40 |
+
input_dtype=torch.float16,
|
| 41 |
+
output_dtype=torch.float16,
|
| 42 |
+
weight_dtype=torch.float16,
|
| 43 |
+
bias_dtype=torch.float16,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
x86_default_dynamic_int8_dtype_config = DTypeConfig(
|
| 47 |
+
input_dtype=torch.quint8,
|
| 48 |
+
output_dtype=torch.float,
|
| 49 |
+
weight_dtype=torch.qint8,
|
| 50 |
+
bias_dtype=torch.float,
|
| 51 |
+
is_dynamic=True,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
x86_default_dynamic_float16_dtype_config = DTypeConfig(
|
| 55 |
+
input_dtype=torch.float16,
|
| 56 |
+
output_dtype=torch.float,
|
| 57 |
+
weight_dtype=torch.float16,
|
| 58 |
+
bias_dtype=torch.float,
|
| 59 |
+
is_dynamic=True,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
x86_weight_only_quint8_dtype_config = DTypeConfig(
|
| 63 |
+
input_dtype=torch.float,
|
| 64 |
+
output_dtype=torch.float,
|
| 65 |
+
weight_dtype=torch.quint8,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
x86_weight_only_quint4x2_dtype_config = DTypeConfig(
|
| 69 |
+
input_dtype=torch.float,
|
| 70 |
+
output_dtype=torch.float,
|
| 71 |
+
weight_dtype=torch.quint4x2,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# =====================
|
| 76 |
+
# | BACKEND CONFIGS |
|
| 77 |
+
# =====================
|
| 78 |
+
|
| 79 |
+
def get_x86_backend_config() -> BackendConfig:
|
| 80 |
+
"""
|
| 81 |
+
Return the `BackendConfig` for PyTorch's native x86 backend.
|
| 82 |
+
"""
|
| 83 |
+
conv_dtype_configs = [x86_weighted_op_int8_dtype_config]
|
| 84 |
+
linear_dtype_configs = [
|
| 85 |
+
x86_weighted_op_int8_dtype_config,
|
| 86 |
+
x86_default_dynamic_int8_dtype_config,
|
| 87 |
+
x86_default_dynamic_float16_dtype_config,
|
| 88 |
+
]
|
| 89 |
+
binary_op_dtype_configs = [x86_weighted_op_int8_dtype_config]
|
| 90 |
+
default_op_dtype_configs = [x86_default_op_quint8_dtype_config]
|
| 91 |
+
fixed_qparams_op_dtype_configs = [x86_weighted_op_int8_dtype_config]
|
| 92 |
+
share_qparams_op_dtype_configs = [x86_default_op_quint8_dtype_config]
|
| 93 |
+
tensor_info_op_dtype_configs = [x86_default_op_quint8_dtype_config]
|
| 94 |
+
rnn_op_dtype_configs = [
|
| 95 |
+
x86_default_dynamic_int8_dtype_config,
|
| 96 |
+
x86_default_dynamic_float16_dtype_config,
|
| 97 |
+
]
|
| 98 |
+
embedding_op_dtype_configs = [
|
| 99 |
+
x86_weight_only_quint8_dtype_config,
|
| 100 |
+
x86_weight_only_quint4x2_dtype_config,
|
| 101 |
+
]
|
| 102 |
+
return BackendConfig("x86") \
|
| 103 |
+
.set_backend_pattern_configs(_get_conv_configs(conv_dtype_configs)) \
|
| 104 |
+
.set_backend_pattern_configs(_get_linear_configs(linear_dtype_configs)) \
|
| 105 |
+
.set_backend_pattern_configs(_get_binary_op_configs(binary_op_dtype_configs)) \
|
| 106 |
+
.set_backend_pattern_config(_get_cat_config(default_op_dtype_configs)) \
|
| 107 |
+
.set_backend_pattern_configs(_get_default_op_configs(default_op_dtype_configs)) \
|
| 108 |
+
.set_backend_pattern_configs(_get_fixed_qparams_op_configs(fixed_qparams_op_dtype_configs)) \
|
| 109 |
+
.set_backend_pattern_configs(_get_share_qparams_op_configs(share_qparams_op_dtype_configs)) \
|
| 110 |
+
.set_backend_pattern_configs(_get_tensor_info_op_configs(tensor_info_op_dtype_configs)) \
|
| 111 |
+
.set_backend_pattern_configs(_get_bn_configs(default_op_dtype_configs)) \
|
| 112 |
+
.set_backend_pattern_configs(_get_rnn_op_configs(rnn_op_dtype_configs)) \
|
| 113 |
+
.set_backend_pattern_configs(_get_embedding_op_configs(embedding_op_dtype_configs))
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_decomposed.cpython-310.pyc
ADDED
|
Binary file (14.4 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_lower_to_native_backend.cpython-310.pyc
ADDED
|
Binary file (26.8 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/fuse_handler.cpython-310.pyc
ADDED
|
Binary file (4.27 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/lstm_utils.cpython-310.pyc
ADDED
|
Binary file (5.97 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/pattern_utils.cpython-310.pyc
ADDED
|
Binary file (3 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/prepare.cpython-310.pyc
ADDED
|
Binary file (38 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/qconfig_mapping_utils.cpython-310.pyc
ADDED
|
Binary file (8.7 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/tracer.cpython-310.pyc
ADDED
|
Binary file (1.81 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (27.4 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (509 Bytes). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/composable_quantizer.cpython-310.pyc
ADDED
|
Binary file (2.81 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/embedding_quantizer.cpython-310.pyc
ADDED
|
Binary file (3.54 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/quantizer.cpython-310.pyc
ADDED
|
Binary file (4.7 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (2.25 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/x86_inductor_quantizer.cpython-310.pyc
ADDED
|
Binary file (19 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer.cpython-310.pyc
ADDED
|
Binary file (13.3 kB). View file
|
|
|
llava_next/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer_utils.cpython-310.pyc
ADDED
|
Binary file (14.1 kB). View file
|
|
|