ZTWHHH commited on
Commit
e7353b3
·
verified ·
1 Parent(s): 5d001ae

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +8 -0
  2. videollama2/lib/python3.10/site-packages/torch/ao/quantization/backend_config/__init__.py +23 -0
  3. videollama2/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_common_operator_config_utils.py +637 -0
  4. videollama2/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_qnnpack_pt2e.py +160 -0
  5. videollama2/lib/python3.10/site-packages/torch/ao/quantization/backend_config/backend_config.py +659 -0
  6. videollama2/lib/python3.10/site-packages/torch/ao/quantization/backend_config/onednn.py +542 -0
  7. videollama2/lib/python3.10/site-packages/torch/ao/quantization/backend_config/qnnpack.py +160 -0
  8. videollama2/lib/python3.10/site-packages/torch/ao/quantization/backend_config/x86.py +113 -0
  9. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/__init__.cpython-310.pyc +0 -0
  10. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_decomposed.cpython-310.pyc +0 -0
  11. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_equalize.cpython-310.pyc +0 -0
  12. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_lower_to_native_backend.cpython-310.pyc +0 -0
  13. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/convert.cpython-310.pyc +0 -0
  14. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/custom_config.cpython-310.pyc +0 -0
  15. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/fuse.cpython-310.pyc +0 -0
  16. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/fuse_handler.cpython-310.pyc +0 -0
  17. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/graph_module.cpython-310.pyc +0 -0
  18. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/lower_to_fbgemm.cpython-310.pyc +0 -0
  19. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/lower_to_qnnpack.cpython-310.pyc +0 -0
  20. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/lstm_utils.cpython-310.pyc +0 -0
  21. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/match_utils.cpython-310.pyc +0 -0
  22. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/pattern_utils.cpython-310.pyc +0 -0
  23. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/prepare.cpython-310.pyc +0 -0
  24. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/qconfig_mapping_utils.cpython-310.pyc +0 -0
  25. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/quantize_handler.cpython-310.pyc +0 -0
  26. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/tracer.cpython-310.pyc +0 -0
  27. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/utils.cpython-310.pyc +0 -0
  28. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_decomposed.py +480 -0
  29. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_lower_to_native_backend.py +1168 -0
  30. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_model_report/__pycache__/__init__.cpython-310.pyc +0 -0
  31. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_model_report/__pycache__/detector.cpython-310.pyc +0 -0
  32. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_model_report/__pycache__/model_report_observer.cpython-310.pyc +0 -0
  33. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_model_report/__pycache__/model_report_visualizer.cpython-310.pyc +0 -0
  34. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_model_report/detector.py +1539 -0
  35. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/fuse.py +161 -0
  36. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/graph_module.py +119 -0
  37. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/lower_to_fbgemm.py +16 -0
  38. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/lstm_utils.py +183 -0
  39. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/match_utils.py +237 -0
  40. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/qconfig_mapping_utils.py +343 -0
  41. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/tracer.py +45 -0
  42. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/utils.py +885 -0
  43. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__init__.py +21 -0
  44. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/__init__.cpython-310.pyc +0 -0
  45. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/composable_quantizer.cpython-310.pyc +0 -0
  46. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/embedding_quantizer.cpython-310.pyc +0 -0
  47. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/quantizer.cpython-310.pyc +0 -0
  48. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/utils.cpython-310.pyc +0 -0
  49. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/x86_inductor_quantizer.cpython-310.pyc +0 -0
  50. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -1383,3 +1383,11 @@ minigpt2/lib/python3.10/site-packages/more_itertools/__pycache__/more.cpython-31
1383
  parrot/lib/python3.10/site-packages/nvidia/cublas/lib/libnvblas.so.12 filter=lfs diff=lfs merge=lfs -text
1384
  parrot/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_core.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1385
  vllm/lib/python3.10/site-packages/pyarrow/_feather.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
1383
  parrot/lib/python3.10/site-packages/nvidia/cublas/lib/libnvblas.so.12 filter=lfs diff=lfs merge=lfs -text
1384
  parrot/lib/python3.10/site-packages/numpy/ma/tests/__pycache__/test_core.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1385
  vllm/lib/python3.10/site-packages/pyarrow/_feather.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1386
+ vllm/lib/python3.10/site-packages/pyarrow/libarrow_dataset.so.1801 filter=lfs diff=lfs merge=lfs -text
1387
+ vllm/lib/python3.10/site-packages/pyarrow/_parquet_encryption.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1388
+ vllm/lib/python3.10/site-packages/pyarrow/_flight.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1389
+ vllm/lib/python3.10/site-packages/pyarrow/_hdfs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1390
+ vllm/lib/python3.10/site-packages/pyarrow/_fs.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1391
+ vllm/lib/python3.10/site-packages/pyarrow/libarrow_acero.so.1801 filter=lfs diff=lfs merge=lfs -text
1392
+ vllm/lib/python3.10/site-packages/pyarrow/_dataset_parquet_encryption.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1393
+ vllm/lib/python3.10/site-packages/pyarrow/libparquet.so.1801 filter=lfs diff=lfs merge=lfs -text
videollama2/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
+ ]
videollama2/lib/python3.10/site-packages/torch/ao/quantization/backend_config/_common_operator_config_utils.py ADDED
@@ -0,0 +1,637 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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")]
videollama2/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
+ )
videollama2/lib/python3.10/site-packages/torch/ao/quantization/backend_config/backend_config.py ADDED
@@ -0,0 +1,659 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass
3
+ from typing import Any, Callable, Dict, List, Optional, Type, Union
4
+
5
+ import torch
6
+ from torch.ao.quantization.utils import Pattern
7
+ from enum import Enum
8
+
9
+
10
+ __all__ = [
11
+ "BackendConfig",
12
+ "BackendPatternConfig",
13
+ "DTypeConfig",
14
+ "DTypeWithConstraints",
15
+ "ObservationType",
16
+ ]
17
+
18
+
19
+ # DTypeConfig dict keys
20
+ INPUT_DTYPE_DICT_KEY = "input_dtype"
21
+ OUTPUT_DTYPE_DICT_KEY = "output_dtype"
22
+ WEIGHT_DTYPE_DICT_KEY = "weight_dtype"
23
+ BIAS_DTYPE_DICT_KEY = "bias_dtype"
24
+ IS_DYNAMIC_DICT_KEY = "is_dynamic"
25
+
26
+ # BackendConfig dict keys
27
+ NAME_DICT_KEY = "name"
28
+ CONFIGS_DICT_KEY = "configs"
29
+
30
+ # BackendPatternConfig dict keys
31
+ PATTERN_DICT_KEY = "pattern"
32
+ PATTERN_COMPLEX_FORMAT_DICT_KEY = "pattern_complex_format"
33
+ OBSERVATION_TYPE_DICT_KEY = "observation_type"
34
+ DTYPE_CONFIGS_DICT_KEY = "dtype_configs"
35
+ ROOT_MODULE_DICT_KEY = "root_module"
36
+ QAT_MODULE_DICT_KEY = "qat_module"
37
+ REFERENCE_QUANTIZED_MODULE_DICT_KEY = "reference_quantized_module_for_root"
38
+ FUSED_MODULE_DICT_KEY = "fused_module"
39
+ FUSER_METHOD_DICT_KEY = "fuser_method"
40
+ ROOT_NODE_GETTER_DICT_KEY = "root_node_getter"
41
+ EXTRA_INPUTS_GETTER_DICT_KEY = "extra_inputs_getter"
42
+ NUM_TENSOR_ARGS_TO_OBSERVATION_TYPE_DICT_KEY = "num_tensor_args_to_observation_type"
43
+ INPUT_TYPE_TO_INDEX_DICT_KEY = "input_type_to_index"
44
+
45
+
46
+ # TODO: maybe rename this to something that's not related to observer
47
+ # e.g. QParamsType
48
+ class ObservationType(Enum):
49
+ """ An enum that represents different ways of how an operator/operator pattern
50
+ should be observed
51
+ """
52
+
53
+ OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT = 0
54
+ """this means input and output are observed with different observers, based
55
+ on qconfig.activation
56
+ example: conv, linear, softmax
57
+ """
58
+
59
+ OUTPUT_SHARE_OBSERVER_WITH_INPUT = 1
60
+ """this means the output will use the same observer instance as input, based
61
+ on qconfig.activation
62
+ example: torch.cat, maxpool
63
+ """
64
+
65
+ INPUT_OUTPUT_NOT_OBSERVED = 2
66
+ """this means the input and output are never observed
67
+ example: x.shape, x.size
68
+ """
69
+
70
+
71
+ @dataclass
72
+ class DTypeWithConstraints:
73
+ """
74
+ Config for specifying additional constraints for a given dtype, such as quantization
75
+ value ranges, scale value ranges, and fixed quantization params, to be used in
76
+ :class:`~torch.ao.quantization.backend_config.DTypeConfig`.
77
+
78
+ The constraints currently supported are:
79
+
80
+ * `quant_min_lower_bound` and `quant_max_upper_bound`: Lower and upper
81
+ bounds for the minimum and maximum quantized values respectively. If
82
+ the QConfig’s `quant_min` and `quant_max` fall outside this range,
83
+ then the QConfig will be ignored.
84
+
85
+ * `scale_min_lower_bound` and `scale_max_upper_bound`: Lower and upper
86
+ bounds for the minimum and maximum scale values respectively. If the
87
+ QConfig’s minimum scale value (currently exposed as `eps`) falls below
88
+ the lower bound, then the QConfig will be ignored. Note that the upper
89
+ bound is currently not enforced.
90
+
91
+ * `scale_exact_match` and `zero_point_exact_match`: Exact match requirements
92
+ for scale and zero point, to be used for operators with fixed quantization
93
+ parameters such as sigmoid and tanh. If the observer specified in the QConfig
94
+ is neither `FixedQParamsObserver` nor `FixedQParamsFakeQuantize`, or if
95
+ the quantization parameters don't match, then the QConfig will be ignored.
96
+ """
97
+ dtype: Optional[torch.dtype] = None
98
+ quant_min_lower_bound: Union[int, float, None] = None
99
+ quant_max_upper_bound: Union[int, float, None] = None
100
+ scale_min_lower_bound: Union[int, float, None] = None
101
+ scale_max_upper_bound: Union[int, float, None] = None
102
+ scale_exact_match: Optional[float] = None
103
+ zero_point_exact_match: Optional[int] = None
104
+
105
+
106
+ @dataclass
107
+ class DTypeConfig:
108
+ """
109
+ Config object that specifies the supported data types passed as arguments to
110
+ quantize ops in the reference model spec, for input and output activations,
111
+ weights, and biases.
112
+
113
+ For example, consider the following reference model:
114
+
115
+ quant1 - [dequant1 - fp32_linear - quant2] - dequant2
116
+
117
+ The pattern in the square brackets refers to the reference pattern of
118
+ statically quantized linear. Setting the input dtype as `torch.quint8`
119
+ in the DTypeConfig means we pass in `torch.quint8` as the dtype argument
120
+ to the first quantize op (quant1). Similarly, setting the output dtype as
121
+ `torch.quint8` means we pass in `torch.quint8` as the dtype argument to
122
+ the second quantize op (quant2).
123
+
124
+ Note that the dtype here does not refer to the interface dtypes of the
125
+ op. For example, the "input dtype" here is not the dtype of the input
126
+ tensor passed to the quantized linear op. Though it can still be the
127
+ same as the interface dtype, this is not always the case, e.g. the
128
+ interface dtype is fp32 in dynamic quantization but the "input dtype"
129
+ specified in the DTypeConfig would still be quint8. The semantics of
130
+ dtypes here are the same as the semantics of the dtypes specified in
131
+ the observers.
132
+
133
+ These dtypes are matched against the ones specified in the user’s
134
+ QConfig. If there is a match, and the QConfig satisfies the constraints
135
+ specified in the DTypeConfig (if any), then we will quantize the given
136
+ pattern using this DTypeConfig. Otherwise, the QConfig is ignored and
137
+ the pattern will not be quantized.
138
+
139
+ Example usage::
140
+
141
+ >>> # xdoctest: +SKIP(failing)
142
+ >>> dtype_config1 = DTypeConfig(
143
+ ... input_dtype=torch.quint8,
144
+ ... output_dtype=torch.quint8,
145
+ ... weight_dtype=torch.qint8,
146
+ ... bias_dtype=torch.float)
147
+
148
+ >>> dtype_config2 = DTypeConfig(
149
+ ... input_dtype=DTypeWithConstraints(
150
+ ... dtype=torch.quint8,
151
+ ... quant_min_lower_bound=0,
152
+ ... quant_max_upper_bound=255,
153
+ ... ),
154
+ ... output_dtype=DTypeWithConstraints(
155
+ ... dtype=torch.quint8,
156
+ ... quant_min_lower_bound=0,
157
+ ... quant_max_upper_bound=255,
158
+ ... ),
159
+ ... weight_dtype=DTypeWithConstraints(
160
+ ... dtype=torch.qint8,
161
+ ... quant_min_lower_bound=-128,
162
+ ... quant_max_upper_bound=127,
163
+ ... ),
164
+ ... bias_dtype=torch.float)
165
+
166
+ >>> dtype_config1.input_dtype
167
+ torch.quint8
168
+
169
+ >>> dtype_config2.input_dtype
170
+ torch.quint8
171
+
172
+ >>> dtype_config2.input_dtype_with_constraints
173
+ DTypeWithConstraints(dtype=torch.quint8, quant_min_lower_bound=0, quant_max_upper_bound=255, \
174
+ scale_min_lower_bound=None, scale_max_upper_bound=None)
175
+ """
176
+ input_dtype_with_constraints: DTypeWithConstraints
177
+ output_dtype_with_constraints: DTypeWithConstraints
178
+ weight_dtype_with_constraints: DTypeWithConstraints
179
+ bias_dtype: Optional[torch.dtype]
180
+ is_dynamic: Optional[bool]
181
+
182
+ def __init__(
183
+ self,
184
+ input_dtype: Union[torch.dtype, DTypeWithConstraints, None] = None,
185
+ output_dtype: Union[torch.dtype, DTypeWithConstraints, None] = None,
186
+ weight_dtype: Union[torch.dtype, DTypeWithConstraints, None] = None,
187
+ bias_dtype: Optional[torch.dtype] = None,
188
+ is_dynamic: Optional[bool] = None,
189
+ ):
190
+ if isinstance(input_dtype, DTypeWithConstraints):
191
+ self.input_dtype_with_constraints = input_dtype
192
+ else:
193
+ self.input_dtype_with_constraints = DTypeWithConstraints(dtype=input_dtype)
194
+
195
+ if isinstance(output_dtype, DTypeWithConstraints):
196
+ self.output_dtype_with_constraints = output_dtype
197
+ else:
198
+ self.output_dtype_with_constraints = DTypeWithConstraints(dtype=output_dtype)
199
+
200
+ if isinstance(weight_dtype, DTypeWithConstraints):
201
+ self.weight_dtype_with_constraints = weight_dtype
202
+ else:
203
+ self.weight_dtype_with_constraints = DTypeWithConstraints(dtype=weight_dtype)
204
+
205
+ self.bias_dtype = bias_dtype
206
+ self.is_dynamic = is_dynamic
207
+
208
+ @property
209
+ def input_dtype(self) -> Optional[torch.dtype]:
210
+ return self.input_dtype_with_constraints.dtype
211
+
212
+ @property
213
+ def output_dtype(self) -> Optional[torch.dtype]:
214
+ return self.output_dtype_with_constraints.dtype
215
+
216
+ @property
217
+ def weight_dtype(self) -> Optional[torch.dtype]:
218
+ return self.weight_dtype_with_constraints.dtype
219
+
220
+ @classmethod
221
+ def from_dict(cls, dtype_config_dict: Dict[str, Any]) -> DTypeConfig:
222
+ """
223
+ Create a ``DTypeConfig`` from a dictionary with the following items (all optional):
224
+ "input_dtype": torch.dtype or ``DTypeWithConstraints``
225
+ "output_dtype": torch.dtype or ``DTypeWithConstraints``
226
+ "weight_dtype": torch.dtype or ``DTypeWithConstraints``
227
+ "bias_type": torch.dtype
228
+ "is_dynamic": bool
229
+ """
230
+ input_dtype = dtype_config_dict.get(INPUT_DTYPE_DICT_KEY, None)
231
+ if input_dtype is not None and not isinstance(input_dtype, (torch.dtype, DTypeWithConstraints)):
232
+ raise ValueError("Expected input_dtype to be a torch.dtype or DTypeWithConstraints")
233
+ output_dtype = dtype_config_dict.get(OUTPUT_DTYPE_DICT_KEY, None)
234
+ if output_dtype is not None and not isinstance(output_dtype, (torch.dtype, DTypeWithConstraints)):
235
+ raise ValueError("Expected output_dtype to be a torch.dtype or DTypeWithConstraints")
236
+ weight_dtype = dtype_config_dict.get(WEIGHT_DTYPE_DICT_KEY, None)
237
+ if weight_dtype is not None and not isinstance(weight_dtype, (torch.dtype, DTypeWithConstraints)):
238
+ raise ValueError("Expected weight_dtype to be a torch.dtype or DTypeWithConstraints")
239
+ bias_dtype = dtype_config_dict.get(BIAS_DTYPE_DICT_KEY, None)
240
+ is_dynamic = dtype_config_dict.get(IS_DYNAMIC_DICT_KEY, None)
241
+ return cls(input_dtype, output_dtype, weight_dtype, bias_dtype, is_dynamic)
242
+
243
+ def to_dict(self) -> Dict[str, Any]:
244
+ """
245
+ Convert this ``DTypeConfig`` to a dictionary with the items described in
246
+ :func:`~torch.ao.quantization.backend_config.DTypeConfig.from_dict`.
247
+ """
248
+ dtype_config_dict: Dict[str, Any] = {}
249
+ if self.input_dtype is not None:
250
+ dtype_config_dict[INPUT_DTYPE_DICT_KEY] = self.input_dtype_with_constraints
251
+ if self.output_dtype is not None:
252
+ dtype_config_dict[OUTPUT_DTYPE_DICT_KEY] = self.output_dtype_with_constraints
253
+ if self.weight_dtype is not None:
254
+ dtype_config_dict[WEIGHT_DTYPE_DICT_KEY] = self.weight_dtype_with_constraints
255
+ if self.bias_dtype is not None:
256
+ dtype_config_dict[BIAS_DTYPE_DICT_KEY] = self.bias_dtype
257
+ if self.is_dynamic is not None:
258
+ dtype_config_dict[IS_DYNAMIC_DICT_KEY] = self.is_dynamic
259
+ return dtype_config_dict
260
+
261
+
262
+ class BackendConfig:
263
+ # TODO: refer to NativeBackendConfig once that is implemented
264
+ """Config that defines the set of patterns that can be quantized on a given backend, and how reference
265
+ quantized models can be produced from these patterns.
266
+
267
+ A pattern in this context refers to a module, a functional, an operator, or a directed acyclic graph
268
+ of the above. Each pattern supported on the target backend can be individually configured through
269
+ :class:`~torch.ao.quantization.backend_config.BackendPatternConfig` in terms of:
270
+
271
+ (1) The supported input/output activation, weight, and bias data types
272
+
273
+ (2) How observers and quant/dequant ops are inserted in order to construct the reference pattern, and
274
+
275
+ (3) (Optionally) Fusion, QAT, and reference module mappings.
276
+
277
+ The format of the patterns is described in:
278
+ https://github.com/pytorch/pytorch/blob/master/torch/ao/quantization/backend_config/README.md
279
+
280
+ Example usage::
281
+
282
+ import torch
283
+ from torch.ao.quantization.backend_config import (
284
+ BackendConfig,
285
+ BackendPatternConfig,
286
+ DTypeConfig,
287
+ ObservationType,
288
+ )
289
+
290
+ weighted_int8_dtype_config = DTypeConfig(
291
+ input_dtype=torch.quint8,
292
+ output_dtype=torch.quint8,
293
+ weight_dtype=torch.qint8,
294
+ bias_dtype=torch.float)
295
+
296
+ def fuse_conv2d_relu(is_qat, conv, relu):
297
+ return torch.ao.nn.intrinsic.ConvReLU2d(conv, relu)
298
+
299
+ # For quantizing Linear
300
+ linear_config = BackendPatternConfig(torch.nn.Linear) \
301
+ .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
302
+ .add_dtype_config(weighted_int8_dtype_config) \
303
+ .set_root_module(torch.nn.Linear) \
304
+ .set_qat_module(torch.ao.nn.qat.Linear) \
305
+ .set_reference_quantized_module(torch.ao.nn.quantized.reference.Linear)
306
+
307
+ # For fusing Conv2d + ReLU into ConvReLU2d
308
+ conv_relu_config = BackendPatternConfig((torch.nn.Conv2d, torch.nn.ReLU)) \
309
+ .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
310
+ .add_dtype_config(weighted_int8_dtype_config) \
311
+ .set_fused_module(torch.ao.nn.intrinsic.ConvReLU2d) \
312
+ .set_fuser_method(fuse_conv2d_relu)
313
+
314
+ # For quantizing ConvReLU2d
315
+ fused_conv_relu_config = BackendPatternConfig(torch.ao.nn.intrinsic.ConvReLU2d) \
316
+ .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
317
+ .add_dtype_config(weighted_int8_dtype_config) \
318
+ .set_root_module(torch.nn.Conv2d) \
319
+ .set_qat_module(torch.ao.nn.intrinsic.qat.ConvReLU2d) \
320
+ .set_reference_quantized_module(torch.ao.nn.quantized.reference.Conv2d)
321
+
322
+ backend_config = BackendConfig("my_backend") \
323
+ .set_backend_pattern_config(linear_config) \
324
+ .set_backend_pattern_config(conv_relu_config) \
325
+ .set_backend_pattern_config(fused_conv_relu_config)
326
+
327
+ """
328
+ def __init__(self, name: str = ""):
329
+ self.name = name
330
+ # Store all BackendPatternConfigs in a map to handle duplicates
331
+ # Note: the key in this map uses the complex reversed tuple format.
332
+ # This is intended only for internal use; users who wish to access
333
+ # the original patterns should go through `self.configs` instead.
334
+ self._pattern_complex_format_to_config: Dict[Pattern, BackendPatternConfig] = {}
335
+
336
+ def __repr__(self):
337
+ return f"BackendConfig({self.__dict__})"
338
+
339
+ def set_name(self, name: str) -> BackendConfig:
340
+ """
341
+ Set the name of the target backend.
342
+ """
343
+ self.name = name
344
+ return self
345
+
346
+ def set_backend_pattern_config(self, config: BackendPatternConfig) -> BackendConfig:
347
+ """
348
+ Set the config for an pattern that can be run on the target backend.
349
+ This overrides any existing config for the given pattern.
350
+ """
351
+ # Avoid circular dependencies
352
+ pattern_complex_format = torch.ao.quantization.backend_config.utils \
353
+ ._get_pattern_in_reversed_nested_tuple_format(config) # type: ignore[attr-defined]
354
+ self._pattern_complex_format_to_config[pattern_complex_format] = config
355
+ return self
356
+
357
+ def set_backend_pattern_configs(self, configs: List[BackendPatternConfig]) -> BackendConfig:
358
+ """
359
+ Set the configs for patterns that can be run on the target backend.
360
+ This overrides any existing config for a given pattern if it was previously registered already.
361
+ """
362
+ for conf in configs:
363
+ self.set_backend_pattern_config(conf)
364
+ return self
365
+
366
+ @property
367
+ def configs(self) -> List[BackendPatternConfig]:
368
+ """
369
+ Return a copy of the list of configs set in this `BackendConfig`.
370
+ """
371
+ return list(self._pattern_complex_format_to_config.values())
372
+
373
+ @classmethod
374
+ def from_dict(cls, backend_config_dict: Dict[str, Any]) -> BackendConfig:
375
+ """
376
+ Create a ``BackendConfig`` from a dictionary with the following items:
377
+
378
+ "name": the name of the target backend
379
+
380
+ "configs": a list of dictionaries that each represents a `BackendPatternConfig`
381
+
382
+ """
383
+ conf = cls(backend_config_dict.get(NAME_DICT_KEY, ""))
384
+ for d in backend_config_dict.get(CONFIGS_DICT_KEY, []):
385
+ if isinstance(d, BackendPatternConfig):
386
+ conf.set_backend_pattern_config(d)
387
+ elif isinstance(d, Dict):
388
+ conf.set_backend_pattern_config(BackendPatternConfig.from_dict(d))
389
+ else:
390
+ raise ValueError(f"Expected backend_config_dict['{CONFIGS_DICT_KEY}'] to be a dictionary")
391
+ return conf
392
+
393
+ def to_dict(self) -> Dict[str, Any]:
394
+ """
395
+ Convert this ``BackendConfig`` to a dictionary with the items described in
396
+ :func:`~torch.ao.quantization.backend_config.BackendConfig.from_dict`.
397
+ """
398
+ return {
399
+ NAME_DICT_KEY: self.name,
400
+ CONFIGS_DICT_KEY: [c.to_dict() for c in self.configs],
401
+ }
402
+
403
+
404
+ class BackendPatternConfig:
405
+ """
406
+ Config object that specifies quantization behavior for a given operator pattern.
407
+ For a detailed example usage, see :class:`~torch.ao.quantization.backend_config.BackendConfig`.
408
+ """
409
+ def __init__(self, pattern: Optional[Pattern] = None):
410
+ self.pattern: Optional[Pattern] = pattern
411
+ self.observation_type = ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT
412
+ self.dtype_configs: List[DTypeConfig] = []
413
+ self.root_module: Optional[Type[torch.nn.Module]] = None
414
+ self.qat_module: Optional[Type[torch.nn.Module]] = None
415
+ self.reference_quantized_module: Optional[Type[torch.nn.Module]] = None
416
+ self.fused_module: Optional[Type[torch.nn.Module]] = None
417
+ self.fuser_method: Optional[Callable] = None
418
+
419
+ # Temporary/internal configs
420
+ self._root_node_getter: Optional[Callable] = None
421
+ self._extra_inputs_getter: Optional[Callable] = None
422
+ self._num_tensor_args_to_observation_type: Dict[int, ObservationType] = {}
423
+ self._input_type_to_index: Dict[str, int] = {}
424
+ self._pattern_complex_format: Optional[Pattern] = None
425
+
426
+ def __repr__(self):
427
+ dict_nonempty = {
428
+ k: v for k, v in self.__dict__.items()
429
+ if (
430
+ (not isinstance(v, (list, dict)) and v is not None)
431
+ or (isinstance(v, (list, dict)) and len(v) > 0)
432
+ )
433
+ }
434
+ return f"BackendPatternConfig({dict_nonempty})"
435
+
436
+ def set_pattern(self, pattern: Pattern) -> BackendPatternConfig:
437
+ """
438
+ Set the pattern to configure.
439
+
440
+ The pattern can be a float module, functional operator, pytorch operator, or a tuple
441
+ combination of the above. Tuple patterns are treated as sequential patterns, and
442
+ currently only tuples of 2 or 3 elements are supported.
443
+ """
444
+ if self._pattern_complex_format is not None:
445
+ raise ValueError("Only one of 'pattern' or 'pattern_complex_format' can be set")
446
+ self.pattern = pattern
447
+ return self
448
+
449
+ def set_observation_type(self, observation_type: ObservationType) -> BackendPatternConfig:
450
+ """
451
+ Set how observers should be inserted in the graph for this pattern.
452
+
453
+ Observation type here refers to how observers (or quant-dequant ops) will be placed
454
+ in the graph. This is used to produce the desired reference patterns understood by
455
+ the backend. Weighted ops such as linear and conv require different observers
456
+ (or quantization parameters passed to quantize ops in the reference model) for the
457
+ input and the output.
458
+
459
+ There are two observation types:
460
+
461
+ `OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT` (default): the output observer instance
462
+ will be different from the input. This is the most common observation type.
463
+
464
+ `OUTPUT_SHARE_OBSERVER_WITH_INPUT`: the output observer instance will be the
465
+ same as the input. This is useful for operators like `cat`.
466
+
467
+ Note: This will be renamed in the near future, since we will soon insert QuantDeQuantStubs
468
+ with observers (and fake quantizes) attached instead of observers themselves.
469
+ """
470
+ self.observation_type = observation_type
471
+ return self
472
+
473
+ def add_dtype_config(self, dtype_config: DTypeConfig) -> BackendPatternConfig:
474
+ """
475
+ Add a set of supported data types passed as arguments to quantize ops in the
476
+ reference model spec.
477
+ """
478
+ self.dtype_configs.append(dtype_config)
479
+ return self
480
+
481
+ def set_dtype_configs(self, dtype_configs: List[DTypeConfig]) -> BackendPatternConfig:
482
+ """
483
+ Set the supported data types passed as arguments to quantize ops in the
484
+ reference model spec, overriding all previously registered data types.
485
+ """
486
+ self.dtype_configs = dtype_configs
487
+ return self
488
+
489
+ def set_root_module(self, root_module: Type[torch.nn.Module]) -> BackendPatternConfig:
490
+ """
491
+ Set the module that represents the root for this pattern.
492
+
493
+ When we construct the reference quantized model during the convert phase,
494
+ the root modules (e.g. torch.nn.Linear for torch.ao.nn.intrinsic.LinearReLU)
495
+ will be swapped to the corresponding reference quantized modules (e.g.
496
+ torch.ao.nn.reference.quantized.Linear). This allows custom backends to
497
+ specify custom reference quantized module implementations to match the
498
+ numerics of their lowered operators. Since this is a one-to-one mapping,
499
+ both the root module and the reference quantized module must be specified
500
+ in the same BackendPatternConfig in order for the conversion to take place.
501
+ """
502
+ self.root_module = root_module
503
+ return self
504
+
505
+ def set_qat_module(self, qat_module: Type[torch.nn.Module]) -> BackendPatternConfig:
506
+ """
507
+ Set the module that represents the QAT implementation for this pattern.
508
+ """
509
+ self.qat_module = qat_module
510
+ return self
511
+
512
+ def set_reference_quantized_module(self, reference_quantized_module: Type[torch.nn.Module]) -> BackendPatternConfig:
513
+ """
514
+ Set the module that represents the reference quantized implementation for
515
+ this pattern's root module.
516
+
517
+ For more detail, see :func:`~torch.ao.quantization.backend_config.BackendPatternConfig.set_root_module`.
518
+ """
519
+ self.reference_quantized_module = reference_quantized_module
520
+ return self
521
+
522
+ def set_fused_module(self, fused_module: Type[torch.nn.Module]) -> BackendPatternConfig:
523
+ """
524
+ Set the module that represents the fused implementation for this pattern.
525
+ """
526
+ self.fused_module = fused_module
527
+ return self
528
+
529
+ def set_fuser_method(self, fuser_method: Callable) -> BackendPatternConfig:
530
+ """
531
+ Set the function that specifies how to fuse this BackendPatternConfig's pattern.
532
+
533
+ The first argument of this function should be `is_qat`, and the rest of the arguments
534
+ should be the items in the tuple pattern. The return value of this function should be
535
+ the resulting fused module.
536
+
537
+ For example, the fuser method for the pattern `(torch.nn.Linear, torch.nn.ReLU)` can be:
538
+
539
+ def fuse_linear_relu(is_qat, linear, relu):
540
+ return torch.ao.nn.intrinsic.LinearReLU(linear, relu)
541
+
542
+ For a more complicated example, see https://gist.github.com/jerryzh168/8bea7180a8ba3c279f2c9b050f2a69a6.
543
+ """
544
+ self.fuser_method = fuser_method
545
+ return self
546
+
547
+ def _set_root_node_getter(self, root_node_getter: Callable) -> BackendPatternConfig:
548
+ self._root_node_getter = root_node_getter
549
+ return self
550
+
551
+ def _set_extra_inputs_getter(self, extra_inputs_getter: Callable) -> BackendPatternConfig:
552
+ self._extra_inputs_getter = extra_inputs_getter
553
+ return self
554
+
555
+ def _set_num_tensor_args_to_observation_type(
556
+ self, num_tensor_args_to_observation_type: Dict[int, ObservationType]) -> BackendPatternConfig:
557
+ self._num_tensor_args_to_observation_type = num_tensor_args_to_observation_type
558
+ return self
559
+
560
+ def _set_input_type_to_index(self, input_type_to_index: Dict[str, int]) -> BackendPatternConfig:
561
+ self._input_type_to_index = input_type_to_index
562
+ return self
563
+
564
+ def _set_pattern_complex_format(self, pattern: Pattern) -> BackendPatternConfig:
565
+ """
566
+ Set the pattern to configure, using the reversed nested tuple format.
567
+
568
+ See the BackendConfig README for more detail:
569
+ https://github.com/pytorch/pytorch/blob/master/torch/ao/quantization/backend_config/README.md#advanced-pattern-specification
570
+ """
571
+ if self.pattern is not None:
572
+ raise ValueError("Only one of 'pattern' or 'pattern_complex_format' can be set")
573
+ self._pattern_complex_format = pattern
574
+ return self
575
+
576
+ @classmethod
577
+ def from_dict(cls, backend_pattern_config_dict: Dict[str, Any]) -> BackendPatternConfig:
578
+ """
579
+ Create a ``BackendPatternConfig`` from a dictionary with the following items:
580
+
581
+ "pattern": the pattern being configured
582
+ "observation_type": the :class:`~torch.ao.quantization.backend_config.ObservationType` that specifies how
583
+ observers should be inserted for this pattern
584
+ "dtype_configs": a list of dictionaries that represents :class:`~torch.ao.quantization.backend_config.DTypeConfig` s
585
+ "root_module": a :class:`torch.nn.Module` that represents the root for this pattern
586
+ "qat_module": a :class:`torch.nn.Module` that represents the QAT implementation for this pattern
587
+ "reference_quantized_module": a :class:`torch.nn.Module` that represents the reference quantized
588
+ implementation for this pattern's root module.
589
+ "fused_module": a :class:`torch.nn.Module` that represents the fused implementation for this pattern
590
+ "fuser_method": a function that specifies how to fuse the pattern for this pattern
591
+ "pattern_complex_format": the pattern specified in the reversed nested tuple format (deprecated)
592
+
593
+ """
594
+ def _get_dtype_config(obj: Any) -> DTypeConfig:
595
+ """
596
+ Convert the given object into a ``DTypeConfig`` if possible, else throw an exception.
597
+ """
598
+ if isinstance(obj, DTypeConfig):
599
+ return obj
600
+ if isinstance(obj, Dict):
601
+ return DTypeConfig.from_dict(obj)
602
+ raise ValueError(
603
+ f"Expected a list of DTypeConfigs in "
604
+ f"backend_pattern_config_dict[\"{DTYPE_CONFIGS_DICT_KEY}\"], got '{type(obj)}'"
605
+ )
606
+
607
+ conf = cls()
608
+ if PATTERN_DICT_KEY in backend_pattern_config_dict:
609
+ conf.set_pattern(backend_pattern_config_dict[PATTERN_DICT_KEY])
610
+ if OBSERVATION_TYPE_DICT_KEY in backend_pattern_config_dict:
611
+ conf.set_observation_type(backend_pattern_config_dict[OBSERVATION_TYPE_DICT_KEY])
612
+ for d in backend_pattern_config_dict.get(DTYPE_CONFIGS_DICT_KEY, []):
613
+ conf.add_dtype_config(_get_dtype_config(d))
614
+ conf.set_root_module(backend_pattern_config_dict.get(ROOT_MODULE_DICT_KEY, None))
615
+ conf.set_qat_module(backend_pattern_config_dict.get(QAT_MODULE_DICT_KEY, None))
616
+ conf.set_reference_quantized_module(backend_pattern_config_dict.get(REFERENCE_QUANTIZED_MODULE_DICT_KEY, None))
617
+ conf.set_fused_module(backend_pattern_config_dict.get(FUSED_MODULE_DICT_KEY, None))
618
+ conf.set_fuser_method(backend_pattern_config_dict.get(FUSER_METHOD_DICT_KEY, None))
619
+ conf._set_root_node_getter(backend_pattern_config_dict.get(ROOT_NODE_GETTER_DICT_KEY, None))
620
+ conf._set_extra_inputs_getter(backend_pattern_config_dict.get(EXTRA_INPUTS_GETTER_DICT_KEY, None))
621
+ conf._set_num_tensor_args_to_observation_type(
622
+ backend_pattern_config_dict.get(NUM_TENSOR_ARGS_TO_OBSERVATION_TYPE_DICT_KEY, {}))
623
+ conf._set_input_type_to_index(backend_pattern_config_dict.get(INPUT_TYPE_TO_INDEX_DICT_KEY, {}))
624
+ if PATTERN_COMPLEX_FORMAT_DICT_KEY in backend_pattern_config_dict:
625
+ conf._set_pattern_complex_format(backend_pattern_config_dict[PATTERN_COMPLEX_FORMAT_DICT_KEY])
626
+ return conf
627
+
628
+ def to_dict(self) -> Dict[str, Any]:
629
+ """
630
+ Convert this ``BackendPatternConfig`` to a dictionary with the items described in
631
+ :func:`~torch.ao.quantization.backend_config.BackendPatternConfig.from_dict`.
632
+ """
633
+ backend_pattern_config_dict: Dict[str, Any] = {
634
+ OBSERVATION_TYPE_DICT_KEY: self.observation_type,
635
+ DTYPE_CONFIGS_DICT_KEY: [c.to_dict() for c in self.dtype_configs],
636
+ }
637
+ if self.pattern is not None:
638
+ backend_pattern_config_dict[PATTERN_DICT_KEY] = self.pattern
639
+ if self.root_module is not None:
640
+ backend_pattern_config_dict[ROOT_MODULE_DICT_KEY] = self.root_module
641
+ if self.qat_module is not None:
642
+ backend_pattern_config_dict[QAT_MODULE_DICT_KEY] = self.qat_module
643
+ if self.reference_quantized_module is not None:
644
+ backend_pattern_config_dict[REFERENCE_QUANTIZED_MODULE_DICT_KEY] = self.reference_quantized_module
645
+ if self.fused_module is not None:
646
+ backend_pattern_config_dict[FUSED_MODULE_DICT_KEY] = self.fused_module
647
+ if self.fuser_method is not None:
648
+ backend_pattern_config_dict[FUSER_METHOD_DICT_KEY] = self.fuser_method
649
+ if self._root_node_getter is not None:
650
+ backend_pattern_config_dict[ROOT_NODE_GETTER_DICT_KEY] = self._root_node_getter
651
+ if self._extra_inputs_getter is not None:
652
+ backend_pattern_config_dict[EXTRA_INPUTS_GETTER_DICT_KEY] = self._extra_inputs_getter
653
+ if len(self._num_tensor_args_to_observation_type) > 0:
654
+ backend_pattern_config_dict[NUM_TENSOR_ARGS_TO_OBSERVATION_TYPE_DICT_KEY] = self._num_tensor_args_to_observation_type
655
+ if len(self._input_type_to_index) > 0:
656
+ backend_pattern_config_dict[INPUT_TYPE_TO_INDEX_DICT_KEY] = self._input_type_to_index
657
+ if self._pattern_complex_format is not None:
658
+ backend_pattern_config_dict[PATTERN_COMPLEX_FORMAT_DICT_KEY] = self._pattern_complex_format
659
+ return backend_pattern_config_dict
videollama2/lib/python3.10/site-packages/torch/ao/quantization/backend_config/onednn.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ]
videollama2/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))
videollama2/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))
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (268 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_decomposed.cpython-310.pyc ADDED
Binary file (14.5 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/_equalize.cpython-310.pyc ADDED
Binary file (25.1 kB). View file
 
videollama2/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
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/convert.cpython-310.pyc ADDED
Binary file (24.9 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/custom_config.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/fuse.cpython-310.pyc ADDED
Binary file (4.03 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/fuse_handler.cpython-310.pyc ADDED
Binary file (4.27 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/graph_module.cpython-310.pyc ADDED
Binary file (5.39 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/lower_to_fbgemm.cpython-310.pyc ADDED
Binary file (745 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/lower_to_qnnpack.cpython-310.pyc ADDED
Binary file (750 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/lstm_utils.cpython-310.pyc ADDED
Binary file (5.97 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/match_utils.cpython-310.pyc ADDED
Binary file (4.99 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/pattern_utils.cpython-310.pyc ADDED
Binary file (3 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/prepare.cpython-310.pyc ADDED
Binary file (37.9 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/qconfig_mapping_utils.cpython-310.pyc ADDED
Binary file (8.7 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/quantize_handler.cpython-310.pyc ADDED
Binary file (7.06 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/tracer.cpython-310.pyc ADDED
Binary file (1.81 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/__pycache__/utils.cpython-310.pyc ADDED
Binary file (27.6 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_decomposed.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.library import Library, impl
3
+ from torch.ao.quantization.utils import determine_qparams, validate_qmin_qmax
4
+ from typing import Tuple
5
+
6
+
7
+ # Note: decomposed means decomposed quantized tensor, using decomposed so that the
8
+ # name is not too long
9
+ quantized_decomposed_lib = Library("quantized_decomposed", "DEF")
10
+
11
+ _DTYPE_TO_QVALUE_BOUNDS = {
12
+ torch.uint8: (0, 255),
13
+ torch.int8: (-128, 127),
14
+ torch.int16: (-(2**15), 2**15 - 1),
15
+ torch.int32: (-(2**31), 2**31 - 1)
16
+ }
17
+
18
+ # Helper to check the passed in quant min and max are valid for the dtype
19
+ def _quant_min_max_bounds_check(quant_min, quant_max, dtype):
20
+ if dtype not in _DTYPE_TO_QVALUE_BOUNDS:
21
+ raise ValueError(f"Unsupported dtype: {dtype}")
22
+ quant_min_lower_bound, quant_max_upper_bound = _DTYPE_TO_QVALUE_BOUNDS[dtype]
23
+
24
+ assert quant_min >= quant_min_lower_bound, \
25
+ "quant_min out of bound for dtype, " \
26
+ f"quant_min_lower_bound: {quant_min_lower_bound} quant_min: {quant_min}"
27
+
28
+ assert quant_max <= quant_max_upper_bound, \
29
+ "quant_max out of bound for dtype, " \
30
+ f"quant_max_upper_bound: {quant_max_upper_bound} quant_max: {quant_max}"
31
+
32
+ quantized_decomposed_lib.define(
33
+ "quantize_per_tensor(Tensor input, float scale, int zero_point, "
34
+ "int quant_min, int quant_max, ScalarType dtype) -> Tensor")
35
+
36
+ @impl(quantized_decomposed_lib, "quantize_per_tensor", "CompositeExplicitAutograd")
37
+ def quantize_per_tensor(
38
+ input: torch.Tensor,
39
+ scale: float,
40
+ zero_point: int,
41
+ quant_min: int,
42
+ quant_max: int,
43
+ dtype: torch.dtype
44
+ ) -> torch.Tensor:
45
+ """ Affine quantization for the Tensor using the same quantization parameters to map
46
+ from floating point to quantized values
47
+
48
+ Args:
49
+ input (torch.Tensor): original float32 or bfloat16 Tensor
50
+ scale (float): quantization parameter for affine quantization
51
+ zero_point (int): quantization parameter for affine quantization
52
+ quant_min (int): minimum quantized value for output Tensor
53
+ quant_max (int): maximum quantized value for output Tensor
54
+ dtype (torch.dtype): requested dtype (e.g. torch.uint8) for output Tensor
55
+
56
+ Returns:
57
+ Tensor with requested dtype (e.g. torch.uint8), note the quantization parameters
58
+ are not stored in the Tensor, we are storing them in function arguments instead
59
+ """
60
+ if input.dtype == torch.bfloat16:
61
+ input = input.to(torch.float32)
62
+
63
+ assert input.dtype == torch.float32, f"Expecting input to have dtype torch.float32, but got dtype: {input.dtype}"
64
+ _quant_min_max_bounds_check(quant_min, quant_max, dtype)
65
+
66
+ inv_scale = 1.0 / scale
67
+ return torch.clamp(torch.round(input * inv_scale) + zero_point, quant_min, quant_max).to(dtype)
68
+
69
+ quantized_decomposed_lib.define(
70
+ "quantize_per_tensor.tensor(Tensor input, Tensor scale, Tensor zero_point, "
71
+ "int quant_min, int quant_max, ScalarType dtype) -> Tensor")
72
+
73
+ @impl(quantized_decomposed_lib, "quantize_per_tensor.tensor", "CompositeExplicitAutograd")
74
+ def quantize_per_tensor_tensor(
75
+ input: torch.Tensor,
76
+ scale: torch.Tensor,
77
+ zero_point: torch.Tensor,
78
+ quant_min: int,
79
+ quant_max: int,
80
+ dtype: torch.dtype
81
+ ) -> torch.Tensor:
82
+ """ Affine quantization for the Tensor using the same quantization parameters to map
83
+ from floating point to quantized values
84
+ Same as `quantize_per_tensor` but scale and zero_point are Scalar Tensor instead of
85
+ scalar values
86
+ """
87
+ assert zero_point.numel() == 1, f"Expecting zero_point tensor to be one element, but received : {zero_point.numel()}"
88
+ assert scale.numel() == 1, f"Expecting scale tensor to be one element, but received : {scale.numel()}"
89
+ return quantize_per_tensor(input, scale.item(), zero_point.item(), quant_min, quant_max, dtype)
90
+
91
+ @impl(quantized_decomposed_lib, "quantize_per_tensor.tensor", "Meta")
92
+ def quantize_per_tensor_tensor_meta(input, scale, zero_point, quant_min, quant_max, dtype):
93
+ assert zero_point.numel() == 1, f"Expecting zero_point tensor to be one element, but received : {zero_point.numel()}"
94
+ assert scale.numel() == 1, f"Expecting scale tensor to be one element, but received : {scale.numel()}"
95
+ assert input.dtype == torch.float32, f"Expecting input to have dtype torch.float32, but got dtype: {input.dtype}"
96
+ return torch.empty_like(input, dtype=dtype)
97
+
98
+ # TODO: remove other variants and keep this one
99
+ quantized_decomposed_lib.define(
100
+ "quantize_per_tensor.tensor2(Tensor input, Tensor scale, Tensor zero_point, "
101
+ "Tensor quant_min, Tensor quant_max, ScalarType dtype) -> Tensor")
102
+
103
+ @impl(quantized_decomposed_lib, "quantize_per_tensor.tensor2", "CompositeExplicitAutograd")
104
+ def quantize_per_tensor_tensor2(
105
+ input: torch.Tensor,
106
+ scale: torch.Tensor,
107
+ zero_point: torch.Tensor,
108
+ quant_min: torch.Tensor,
109
+ quant_max: torch.Tensor,
110
+ dtype: torch.dtype
111
+ ) -> torch.Tensor:
112
+ """ Affine quantization for the Tensor using the same quantization parameters to map
113
+ from floating point to quantized values
114
+ Same as `quantize_per_tensor` but scale and zero_point are Scalar Tensor instead of
115
+ scalar values
116
+ """
117
+ assert zero_point.numel() == 1, f"Expecting zero_point tensor to be one element, but received : {zero_point.numel()}"
118
+ assert scale.numel() == 1, f"Expecting scale tensor to be one element, but received : {scale.numel()}"
119
+ return quantize_per_tensor(input, scale.item(), zero_point.item(), quant_min.item(), quant_max.item(), dtype)
120
+
121
+ @impl(quantized_decomposed_lib, "quantize_per_tensor.tensor2", "Meta")
122
+ def quantize_per_tensor_tensor2_meta(input, scale, zero_point, quant_min, quant_max, dtype):
123
+ return quantize_per_tensor_tensor_meta(input, scale, zero_point, quant_min, quant_max, dtype)
124
+
125
+ # Note: quant_min/quant_max/dtype are not used in the operator, but for now it's kept in
126
+ # the signature as metadata for the input Tensor, this might be useful for pattern
127
+ # matching in the future
128
+ # We will revisit this later if we found there are no use cases for it
129
+ quantized_decomposed_lib.define(
130
+ "dequantize_per_tensor(Tensor input, float scale, int zero_point, "
131
+ "int quant_min, int quant_max, ScalarType dtype) -> Tensor")
132
+
133
+ @impl(quantized_decomposed_lib, "dequantize_per_tensor", "CompositeExplicitAutograd")
134
+ def dequantize_per_tensor(
135
+ input: torch.Tensor,
136
+ scale: float,
137
+ zero_point: int,
138
+ quant_min: int,
139
+ quant_max: int,
140
+ dtype: torch.dtype
141
+ ) -> torch.Tensor:
142
+ """ Affine dequantization for the Tensor using the same quantization parameters to map
143
+ from quantized values to floating point values
144
+
145
+ Args:
146
+ input (torch.Tensor): Tensor with dtype matching `dtype` argument,
147
+ e.g. (`torch.uint8`), it is a per tensor quantized Tensor if combined with
148
+ quantization parameters in the argument of this function (scale/zero_point)
149
+
150
+ scale (float): quantization parameter for affine quantization
151
+
152
+ zero_point (int): quantization parameter for affine quantization
153
+
154
+ quant_min (int): minimum quantized value for input Tensor (not used in computation,
155
+ reserved for pattern matching)
156
+
157
+ quant_max (int): maximum quantized value for input Tensor (not used in computation,
158
+ reserved for pattern matching)
159
+
160
+ dtype (torch.dtype): dtype for input Tensor (not used in computation,
161
+ reserved for pattern matching)
162
+
163
+ Returns:
164
+ dequantized float32 Tensor
165
+ """
166
+ assert input.dtype == dtype, f"Expecting input to have dtype: {dtype}, but got {input.dtype}"
167
+ if dtype in _DTYPE_TO_QVALUE_BOUNDS:
168
+ # TODO: investigate why
169
+ # (input - zero_point).to(torch.float32) * scale
170
+ # failed the test
171
+ return (input.to(torch.float32) - zero_point) * scale
172
+ else:
173
+ raise ValueError(f"Unsupported dtype in dequantize_per_tensor: {dtype}")
174
+
175
+
176
+ quantized_decomposed_lib.define(
177
+ "dequantize_per_tensor.tensor(Tensor input, Tensor scale, Tensor zero_point, "
178
+ "int quant_min, int quant_max, ScalarType dtype) -> Tensor")
179
+
180
+ @impl(quantized_decomposed_lib, "dequantize_per_tensor.tensor", "CompositeExplicitAutograd")
181
+ def dequantize_per_tensor_tensor(
182
+ input: torch.Tensor,
183
+ scale: torch.Tensor,
184
+ zero_point: torch.Tensor,
185
+ quant_min: int,
186
+ quant_max: int,
187
+ dtype: torch.dtype
188
+ ) -> torch.Tensor:
189
+ """ Affine dequantization for the Tensor using the same quantization parameters to map
190
+ from quantized values to floating point values
191
+ Same as `dequantize_per_tensor` but scale and zero_point are Scalar Tensor instead of
192
+ scalar values
193
+ """
194
+ assert zero_point.numel() == 1, f"Expecting zero_point tensor to be one element, but received : {zero_point.numel()}"
195
+ assert scale.numel() == 1, f"Expecting scale tensor to be one element, but received : {scale.numel()}"
196
+ return dequantize_per_tensor(input, scale.item(), zero_point.item(), quant_min, quant_max, dtype)
197
+
198
+ @impl(quantized_decomposed_lib, "dequantize_per_tensor.tensor", "Meta")
199
+ def dequantize_per_tensor_tensor_meta(input, scale, zero_point, quant_min, quant_max, dtype):
200
+ assert zero_point.numel() == 1, f"Expecting zero_point tensor to be one element, but received : {zero_point.numel()}"
201
+ assert scale.numel() == 1, f"Expecting scale tensor to be one element, but received : {scale.numel()}"
202
+ assert input.dtype == dtype, f"Expecting input to have dtype: {dtype}"
203
+ if dtype in _DTYPE_TO_QVALUE_BOUNDS:
204
+ return torch.empty_like(input, dtype=torch.float32)
205
+ else:
206
+ raise ValueError(f"Unsupported dtype in dequantize_per_tensor: {dtype}")
207
+
208
+ # TODO: remove other variants and keep this one
209
+ quantized_decomposed_lib.define(
210
+ "dequantize_per_tensor.tensor2(Tensor input, Tensor scale, Tensor zero_point, "
211
+ "Tensor quant_min, Tensor quant_max, ScalarType dtype) -> Tensor")
212
+
213
+ @impl(quantized_decomposed_lib, "dequantize_per_tensor.tensor2", "CompositeExplicitAutograd")
214
+ def dequantize_per_tensor_tensor2(
215
+ input: torch.Tensor,
216
+ scale: torch.Tensor,
217
+ zero_point: torch.Tensor,
218
+ quant_min: torch.Tensor,
219
+ quant_max: torch.Tensor,
220
+ dtype: torch.dtype
221
+ ) -> torch.Tensor:
222
+ """ Affine dequantization for the Tensor using the same quantization parameters to map
223
+ from quantized values to floating point values
224
+ Same as `dequantize_per_tensor` but scale and zero_point are Scalar Tensor instead of
225
+ scalar values
226
+ """
227
+ assert zero_point.numel() == 1, f"Expecting zero_point tensor to be one element, but received : {zero_point.numel()}"
228
+ assert scale.numel() == 1, f"Expecting scale tensor to be one element, but received : {scale.numel()}"
229
+ return dequantize_per_tensor(input, scale.item(), zero_point.item(), quant_min.item(), quant_max.item(), dtype)
230
+
231
+ @impl(quantized_decomposed_lib, "dequantize_per_tensor.tensor2", "Meta")
232
+ def dequantize_per_tensor_tensor2_meta(input, scale, zero_point, quant_min, quant_max, dtype):
233
+ return dequantize_per_tensor_tensor_meta(input, scale, zero_point, quant_min, quant_max, dtype)
234
+
235
+ quantized_decomposed_lib.define(
236
+ "choose_qparams.tensor(Tensor input, int quant_min, int quant_max, "
237
+ "float eps, ScalarType dtype) -> (Tensor, Tensor)")
238
+
239
+ @impl(quantized_decomposed_lib, "choose_qparams.tensor", "CompositeExplicitAutograd")
240
+ def choose_qparams_tensor(
241
+ input: torch.Tensor,
242
+ qmin: int,
243
+ qmax: int,
244
+ eps: float,
245
+ dtype: torch.dtype
246
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
247
+ """ Given an input Tensor, derive the per tensor affine quantization parameter
248
+ (scale and zero_point) for target quantized Tensor from the Tensor
249
+
250
+ Args:
251
+ input (torch.Tensor): floating point input Tensor
252
+ quant_min (int): minimum quantized value for target quantized Tensor
253
+ quant_max (int): maximum quantized value for target quantized Tensor
254
+ dtype (torch.dtype): dtype for target quantized Tensor
255
+
256
+ Returns:
257
+ scale (float): quantization parameter for the target quantized Tensor
258
+ zero_point (int): quantization parameter for the target quantized Tensor
259
+ """
260
+ assert input.dtype == torch.float32, f"Expecting input to have dtype torch.float32, but got dtype: {input.dtype}"
261
+ assert dtype in _DTYPE_TO_QVALUE_BOUNDS, \
262
+ f"Expecting target dtype to be one of {_DTYPE_TO_QVALUE_BOUNDS.keys()}, but got: {dtype}"
263
+ validate_qmin_qmax(qmin, qmax)
264
+
265
+ min_val, max_val = torch.aminmax(input)
266
+
267
+ return determine_qparams(
268
+ min_val, max_val, qmin, qmax, dtype, torch.Tensor([eps]), has_customized_qrange=False)
269
+
270
+ quantized_decomposed_lib.define(
271
+ "choose_qparams_symmetric.tensor(Tensor input, int quant_min, int quant_max, "
272
+ "float eps, ScalarType dtype) -> (Tensor, Tensor)")
273
+
274
+ @impl(quantized_decomposed_lib, "choose_qparams_symmetric.tensor", "CompositeExplicitAutograd")
275
+ def choose_qparams_symmetric_tensor(
276
+ input: torch.Tensor,
277
+ qmin: int,
278
+ qmax: int,
279
+ eps: float,
280
+ dtype: torch.dtype
281
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
282
+ """ Given an input Tensor, derive the per tensor affine quantization parameter
283
+ (scale and zero_point) for target quantized Tensor from the Tensor
284
+
285
+ Args:
286
+ input (torch.Tensor): floating point input Tensor
287
+ quant_min (int): minimum quantized value for target quantized Tensor
288
+ quant_max (int): maximum quantized value for target quantized Tensor
289
+ dtype (torch.dtype): dtype for target quantized Tensor
290
+
291
+ Returns:
292
+ scale (float): quantization parameter for the target quantized Tensor
293
+ zero_point (int): quantization parameter for the target quantized Tensor
294
+ """
295
+ assert input.dtype == torch.float32, f"Expecting input to have dtype torch.float32, but got dtype: {input.dtype}"
296
+ assert dtype in _DTYPE_TO_QVALUE_BOUNDS, \
297
+ f"Expecting target dtype to be one of {_DTYPE_TO_QVALUE_BOUNDS.keys()}, but got: {dtype}"
298
+ validate_qmin_qmax(qmin, qmax)
299
+
300
+ min_val, max_val = torch.aminmax(input)
301
+ return determine_qparams(
302
+ min_val,
303
+ max_val,
304
+ qmin,
305
+ qmax,
306
+ dtype,
307
+ torch.Tensor([eps]),
308
+ has_customized_qrange=False,
309
+ qscheme=torch.per_tensor_symmetric
310
+ )
311
+
312
+ @impl(quantized_decomposed_lib, "choose_qparams.tensor", "Meta")
313
+ def choose_qparams_tensor_meta(
314
+ input: torch.Tensor,
315
+ quant_min: int,
316
+ quant_max: int,
317
+ eps: float,
318
+ dtype: torch.dtype
319
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
320
+ assert input.dtype == torch.float32, f"Expecting input to have dtype torch.float32, but got dtype: {input.dtype}"
321
+ assert quant_min < quant_max, f"Expecting quant_min to be smaller than quant_max but received min: \
322
+ {quant_min} max: {quant_max}"
323
+ return torch.empty(1, dtype=torch.double, device=input.device), torch.empty(1, dtype=torch.int64, device=input.device)
324
+
325
+ @impl(quantized_decomposed_lib, "choose_qparams_symmetric.tensor", "Meta")
326
+ def choose_qparams_symmetric_tensor_meta(
327
+ input: torch.Tensor,
328
+ quant_min: int,
329
+ quant_max: int,
330
+ eps: float,
331
+ dtype: torch.dtype
332
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
333
+ return torch.empty(1, dtype=torch.double, device=input.device), torch.empty(1, dtype=torch.int64, device=input.device)
334
+
335
+ # Helper function used to implement per-channel quantization against any axis
336
+ def _permute_to_axis_zero(x, axis):
337
+ new_axis_list = list(range(x.dim()))
338
+ new_axis_list[axis] = 0
339
+ new_axis_list[0] = axis
340
+ y = x.permute(tuple(new_axis_list))
341
+ return y, new_axis_list
342
+
343
+ quantized_decomposed_lib.define(
344
+ "quantize_per_channel(Tensor input, Tensor scales, Tensor zero_points, int axis, "
345
+ "int quant_min, int quant_max, ScalarType dtype) -> Tensor")
346
+
347
+ @impl(quantized_decomposed_lib, "quantize_per_channel", "CompositeExplicitAutograd")
348
+ def quantize_per_channel(
349
+ input: torch.Tensor,
350
+ scales: torch.Tensor,
351
+ zero_points: torch.Tensor,
352
+ axis: int,
353
+ quant_min: int,
354
+ quant_max: int,
355
+ dtype: torch.dtype
356
+ ) -> torch.Tensor:
357
+ """ Affine per channel quantization for the Tensor using the same quantization
358
+ parameters for each channel/axis to map from floating point to quantized values
359
+
360
+ Args:
361
+ input (torch.Tensor): original float32 or bfloat16 Tensor
362
+ scales (torch.Tensor): a list of scale quantization parameter for
363
+ affine quantization, one per channel
364
+ zero_point (torch.Tensor): a list of zero_point quantization parameter for
365
+ affine quantization, one per channel
366
+ quant_min (int): minimum quantized value for output Tensor
367
+ quant_max (int): maximum quantized value for output Tensor
368
+ dtype (torch.dtype): requested dtype (e.g. torch.uint8) for output Tensor
369
+
370
+ Returns:
371
+ Tensor with requested dtype (e.g. torch.uint8), note the quantization parameters
372
+ are not stored in the Tensor, we are storing them in function arguments instead
373
+ """
374
+ if input.dtype == torch.bfloat16:
375
+ input = input.to(torch.float32)
376
+
377
+ assert input.dtype == torch.float32, f"Expecting input to have dtype torch.float32, but got dtype: {input.dtype}"
378
+ assert axis < input.dim(), f"Expecting axis to be < {input.dim()}"
379
+ _quant_min_max_bounds_check(quant_min, quant_max, dtype)
380
+ input, permute_axis_list = _permute_to_axis_zero(input, axis)
381
+ res = torch.zeros_like(input)
382
+
383
+ for i in range(input.size(0)):
384
+ res[i] = torch.clamp(
385
+ torch.round(input[i] * (1.0 / scales[i])) + zero_points[i],
386
+ quant_min,
387
+ quant_max
388
+ )
389
+
390
+ out = res.permute(tuple(permute_axis_list))
391
+ return out.to(dtype)
392
+
393
+ @impl(quantized_decomposed_lib, "quantize_per_channel", "Meta")
394
+ def quantize_per_channel_meta(
395
+ input: torch.Tensor,
396
+ scales: torch.Tensor,
397
+ zero_points: torch.Tensor,
398
+ axis: int,
399
+ quant_min: int,
400
+ quant_max: int,
401
+ dtype: torch.dtype
402
+ ) -> torch.Tensor:
403
+ assert input.dtype == torch.float32, f"Expecting input to have dtype torch.float32, but got dtype: {input.dtype}"
404
+ assert axis < input.dim(), f"Expecting axis to be < {input.dim()}"
405
+ _quant_min_max_bounds_check(quant_min, quant_max, dtype)
406
+ return torch.empty_like(input, dtype=dtype)
407
+
408
+ # Note: quant_min/quant_max/dtype are not used in the operator, but for now it's kept in
409
+ # the signature as metadata for the input Tensor, this might be useful for pattern
410
+ # matching in the future
411
+ # We will revisit this later if we found there are no use cases for it
412
+ quantized_decomposed_lib.define(
413
+ "dequantize_per_channel(Tensor input, Tensor scales, Tensor zero_points, int axis, "
414
+ "int quant_min, int quant_max, ScalarType dtype) -> Tensor")
415
+
416
+ @impl(quantized_decomposed_lib, "dequantize_per_channel", "CompositeExplicitAutograd")
417
+ def dequantize_per_channel(
418
+ input: torch.Tensor,
419
+ scales: torch.Tensor,
420
+ zero_points: torch.Tensor,
421
+ axis: int,
422
+ quant_min: int,
423
+ quant_max: int,
424
+ dtype: torch.dtype
425
+ ) -> torch.Tensor:
426
+ """ Affine per channel dequantization for the Tensor using the same quantization
427
+ parameters for each channel/axis to map from quantized values to floating point values
428
+
429
+ Args:
430
+ input (torch.Tensor): Tensor with dtype matching `dtype` argument,
431
+ e.g. (`torch.uint8`), it is a per channel quantized Tensor if combined with
432
+ quantization parameter in the argument of this function (scales/zero_points/axis)
433
+
434
+ scales (torch.Tensor): a list of scale quantization parameter for
435
+ affine quantization, one per channel
436
+
437
+ zero_points (torch.Tensor): a list of zero_point quantization parameter for
438
+ affine quantization, one per channel
439
+
440
+ quant_min (int): minimum quantized value for output Tensor (not used in computation,
441
+ reserved for pattern matching)
442
+
443
+ quant_max (int): maximum quantized value for output Tensor (not used in computation,
444
+ reserved for pattern matching)
445
+
446
+ dtype (torch.dtype): requested dtype for output Tensor (not used in computation,
447
+ reserved for pattern matching)
448
+
449
+ Returns:
450
+ dequantized float32 Tensor
451
+ """
452
+ assert input.dtype == dtype, f"Expecting input to have dtype {dtype}, but got dtype: {input.dtype}"
453
+ assert axis < input.dim(), f"Expecting axis to be < {input.dim()}"
454
+ _quant_min_max_bounds_check(quant_min, quant_max, dtype)
455
+ input, permute_axis_list = _permute_to_axis_zero(input, axis)
456
+ res = torch.zeros_like(input, dtype=torch.float32)
457
+
458
+ for i in range(input.size(0)):
459
+ # TODO: investigate why
460
+ # (input[i] - zero_points[i]).to(torch.float32) * scales[i]
461
+ # failed the test
462
+ res[i] = (input[i].to(torch.float32) - zero_points[i]) * scales[i]
463
+
464
+ out = res.permute(tuple(permute_axis_list))
465
+ return out
466
+
467
+ @impl(quantized_decomposed_lib, "dequantize_per_channel", "Meta")
468
+ def dequantize_per_channel_meta(
469
+ input: torch.Tensor,
470
+ scales: torch.Tensor,
471
+ zero_points: torch.Tensor,
472
+ axis: int,
473
+ quant_min: int,
474
+ quant_max: int,
475
+ dtype: torch.dtype
476
+ ) -> torch.Tensor:
477
+ assert input.dtype == dtype, f"Expecting input to have dtype {dtype}, but got dtype: {input.dtype}"
478
+ assert axis < input.dim(), f"Expecting axis to be < {input.dim()}"
479
+ _quant_min_max_bounds_check(quant_min, quant_max, dtype)
480
+ return torch.empty_like(input, dtype=torch.float32)
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_lower_to_native_backend.py ADDED
@@ -0,0 +1,1168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.fx import map_arg, Node
3
+ from torch.fx.graph import Graph
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import torch.ao.nn.intrinsic as nni
7
+ import torch.ao.nn.intrinsic.quantized as nniq
8
+ import torch.ao.nn.intrinsic.quantized.dynamic as nniqd
9
+ import torch.ao.nn.quantized as nnq
10
+ import torch.ao.nn.quantized.dynamic as nnqd
11
+ import torch.ao.nn.quantized.reference as nnqr
12
+ from torch.ao.nn.quantized.modules.utils import WeightedQuantizedModule
13
+ from torch.fx import GraphModule
14
+ from .utils import (
15
+ collect_producer_nodes,
16
+ get_linear_prepack_op_for_dtype,
17
+ get_new_attr_name_with_prefix,
18
+ get_qconv_prepack_op,
19
+ graph_module_from_producer_nodes,
20
+ )
21
+ from ..utils import _parent_name
22
+ from ..qconfig import QConfigAny
23
+ from ..quantization_mappings import get_quantized_operator
24
+ from .utils import create_node_from_old_node_preserve_meta
25
+ from typing import Dict, Tuple, Type, List, Callable, Any, Union, Set, Optional
26
+ import operator
27
+
28
+ QOP_TO_ARG_NAMES_TO_SKIP = {
29
+ torch._ops.ops.quantized.hardswish: ['inplace'],
30
+ torch._ops.ops.quantized.elu: ['inplace'],
31
+ torch._ops.ops.quantized.dropout: ['inplace'],
32
+ torch._ops.ops.quantized.instance_norm:
33
+ ['running_mean', 'running_var', 'use_input_stats', 'momentum'],
34
+ }
35
+
36
+ def _is_node_in_list(node, modules, func_list, method_list, module_type_list):
37
+ is_call_function = node.op == "call_function" and node.target in func_list
38
+ is_call_method = node.op == "call_method" and node.target in method_list
39
+ is_call_module = node.op == "call_module" and type(modules[str(node.target)]) in module_type_list
40
+ return is_call_function, is_call_method, is_call_module
41
+
42
+ def is_fixed_qparams_node(node, modules):
43
+ func_list = [
44
+ torch.nn.functional.hardsigmoid,
45
+ torch.nn.functional.sigmoid,
46
+ torch.sigmoid,
47
+ torch.tanh,
48
+ ]
49
+ method_list = [
50
+ "hardsigmoid",
51
+ "hardsigmoid_",
52
+ "sigmoid",
53
+ "sigmoid_",
54
+ "tanh",
55
+ "tanh_",
56
+ ]
57
+ module_type_list = [
58
+ torch.nn.Hardsigmoid,
59
+ torch.nn.Sigmoid,
60
+ torch.nn.Tanh,
61
+ torch.nn.Softmax,
62
+ ]
63
+ return _is_node_in_list(node, modules, func_list, method_list, module_type_list)
64
+
65
+ def is_default_node(node, modules):
66
+ func_list = [
67
+ torch.nn.functional.elu,
68
+ torch.nn.functional.hardswish,
69
+ torch.nn.functional.instance_norm,
70
+ torch.nn.functional.layer_norm,
71
+ torch.nn.functional.leaky_relu,
72
+ torch.nn.functional.dropout,
73
+ ]
74
+ method_list: List[Any] = []
75
+ module_type_list = [
76
+ nnqr.ConvTranspose1d,
77
+ nnqr.ConvTranspose2d,
78
+ nnqr.ConvTranspose3d,
79
+ torch.nn.ELU,
80
+ torch.nn.LeakyReLU,
81
+ torch.nn.Hardswish,
82
+ torch.nn.InstanceNorm1d,
83
+ torch.nn.InstanceNorm2d,
84
+ torch.nn.InstanceNorm3d,
85
+ torch.nn.LayerNorm,
86
+ torch.nn.Dropout,
87
+ torch.nn.PReLU,
88
+ torch.nn.BatchNorm2d,
89
+ torch.nn.BatchNorm3d,
90
+ torch.ao.nn.intrinsic.BNReLU2d,
91
+ torch.ao.nn.intrinsic.BNReLU3d,
92
+ ]
93
+ return _is_node_in_list(node, modules, func_list, method_list, module_type_list)
94
+
95
+ def is_copy_node(node, modules):
96
+ func_list = [
97
+ torch.adaptive_avg_pool1d,
98
+ torch.nn.functional.adaptive_avg_pool2d,
99
+ torch.nn.functional.adaptive_avg_pool3d,
100
+ torch.nn.functional.hardtanh,
101
+ torch.nn.functional.hardtanh_,
102
+ torch.nn.functional.interpolate,
103
+ torch.nn.functional.max_pool1d,
104
+ torch.nn.functional.max_pool2d,
105
+ torch.nn.functional.max_pool3d,
106
+ torch.nn.functional.relu,
107
+ torch.nn.functional.relu6,
108
+ torch.avg_pool1d,
109
+ torch._C._nn.avg_pool2d,
110
+ torch._C._nn.avg_pool3d,
111
+ torch.clamp,
112
+ torch.flatten,
113
+ torch.mean,
114
+ operator.floordiv,
115
+ # F.channel_shuffle and torch.channel_shuffle are essentially the same thing
116
+ # so we only need to put one of them here
117
+ torch.channel_shuffle,
118
+ ]
119
+ method_list = [
120
+ "clamp",
121
+ "mean",
122
+ "relu",
123
+ "relu_",
124
+ ]
125
+ module_type_list = [
126
+ torch.nn.AdaptiveAvgPool1d,
127
+ torch.nn.AdaptiveAvgPool2d,
128
+ torch.nn.AdaptiveAvgPool3d,
129
+ torch.nn.AvgPool1d,
130
+ torch.nn.AvgPool2d,
131
+ torch.nn.AvgPool3d,
132
+ torch.nn.Hardtanh,
133
+ torch.nn.MaxPool1d,
134
+ torch.nn.MaxPool2d,
135
+ torch.nn.MaxPool3d,
136
+ torch.nn.ReLU,
137
+ torch.nn.ReLU6,
138
+ torch.nn.ChannelShuffle,
139
+ ]
140
+ return _is_node_in_list(node, modules, func_list, method_list, module_type_list)
141
+
142
+ def is_general_tensor_shape_node(node, modules):
143
+ func_list = [
144
+ torch.narrow,
145
+ torch.transpose,
146
+ torch.repeat_interleave,
147
+ torch.squeeze,
148
+ torch.stack,
149
+ torch.unsqueeze,
150
+ torch.nn.functional.pixel_shuffle,
151
+ torch.nn.functional.pixel_unshuffle,
152
+ ]
153
+ method_list = [
154
+ "contiguous",
155
+ "detach",
156
+ "detach_",
157
+ "permute",
158
+ "repeat",
159
+ "repeat_interleave",
160
+ "reshape",
161
+ "resize_",
162
+ "shape",
163
+ "size",
164
+ "squeeze",
165
+ "squeeze_",
166
+ "transpose",
167
+ "unsqueeze",
168
+ "unsqueeze_",
169
+ "view",
170
+ ]
171
+ module_type_list = [
172
+ torch.nn.Identity,
173
+ torch.nn.PixelShuffle,
174
+ torch.nn.PixelUnshuffle,
175
+ ]
176
+ return _is_node_in_list(node, modules, func_list, method_list, module_type_list)
177
+
178
+ def is_other_node(node, modules):
179
+ func_list = [
180
+ torch.cat,
181
+ ]
182
+ method_list: List[Any] = []
183
+ module_type_list: List[Any] = []
184
+ return _is_node_in_list(node, modules, func_list, method_list, module_type_list)
185
+
186
+ def is_special_pattern_node(node, modules):
187
+ res_function, res_method, res_module = False, False, False
188
+ for checker in [is_fixed_qparams_node, is_default_node, is_copy_node, is_general_tensor_shape_node, is_other_node]:
189
+ is_call_function, is_call_method, is_call_module = checker(node, modules)
190
+ res_function = res_function or is_call_function
191
+ res_method = res_method or is_call_method
192
+ res_module = res_module or is_call_module
193
+ return res_function, res_method, res_module
194
+
195
+ def is_dequantize_node(node):
196
+ return isinstance(node, Node) and node.op == "call_method" and node.target == "dequantize"
197
+
198
+ def is_getattr_tensor_metadata_node(node):
199
+ return node.op == "call_function" and \
200
+ node.target == getattr and \
201
+ node.args[1] in ["shape"]
202
+
203
+ def is_get_tensor_info_node(node):
204
+ return node.op == "call_method" and \
205
+ node.target in ["shape", "size"]
206
+
207
+ def should_skip_lowering(op: torch.fx.node.Node, qconfig_map: Dict[str, QConfigAny]):
208
+ """
209
+ Return True if the op is configured with a None qconfig, False otherwise.
210
+ Note: maybe need to generalize this to also check for the dtype, and we
211
+ only lower when dtype matches, but right now fbgemm/qnnpack only support
212
+ a single dtype, so it is OK for now.
213
+ """
214
+ return op.name in qconfig_map and qconfig_map[op.name] is None
215
+
216
+ # Mapping from reference module class to the replacement static quantized module class for lowering
217
+ STATIC_LOWER_MODULE_MAP: Dict[Type[nn.Module], Type[WeightedQuantizedModule]] = {
218
+ nnqr.Linear: nnq.Linear,
219
+ nnqr.Conv1d: nnq.Conv1d,
220
+ nnqr.Conv2d: nnq.Conv2d,
221
+ nnqr.Conv3d: nnq.Conv3d,
222
+ }
223
+
224
+ # Mapping from reference module class to the replacement dynamic quantized module class for lowering
225
+ DYNAMIC_LOWER_MODULE_MAP: Dict[Type[nn.Module], Type[nn.Module]] = {
226
+ nnqr.Linear: nnqd.Linear,
227
+ nnqr.GRUCell: nnqd.GRUCell,
228
+ nnqr.LSTMCell: nnqd.LSTMCell,
229
+ nnqr.RNNCell: nnqd.RNNCell,
230
+ nnqr.LSTM: nnqd.LSTM,
231
+ nnqr.GRU: nnqd.GRU,
232
+ }
233
+
234
+ # Mapping from reference module class to the replacement weight only quantized module class for lowering
235
+ # TODO: correct the namespace for these modules
236
+ WEIGHT_ONLY_LOWER_MODULE_MAP: Dict[Type[nn.Module], Type[nn.Module]] = {
237
+ nnqr.Embedding: nnq.Embedding,
238
+ nnqr.EmbeddingBag: nnq.EmbeddingBag,
239
+ }
240
+
241
+ # TODO: merge with STATIC_LOWER_MODULE_MAP after we merge
242
+ # _lower_static_weighted_ref_module and special_pattern_replacement
243
+ SPECIAL_PATTERN_LOWER_MODULE_MAP = {
244
+ nn.BatchNorm2d: nnq.BatchNorm2d,
245
+ nn.BatchNorm3d: nnq.BatchNorm3d,
246
+ nnqr.ConvTranspose1d: nnq.ConvTranspose1d,
247
+ nnqr.ConvTranspose2d: nnq.ConvTranspose2d,
248
+ nnqr.ConvTranspose3d: nnq.ConvTranspose3d,
249
+ nn.ELU: nnq.ELU,
250
+ nn.LeakyReLU: nnq.LeakyReLU,
251
+ nn.Hardswish: nnq.Hardswish,
252
+ nn.InstanceNorm1d: nnq.InstanceNorm1d,
253
+ nn.InstanceNorm2d: nnq.InstanceNorm2d,
254
+ nn.InstanceNorm3d: nnq.InstanceNorm3d,
255
+ nn.LayerNorm: nnq.LayerNorm,
256
+ nn.Dropout: nnq.Dropout,
257
+ nn.Softmax: nnq.Softmax,
258
+ nn.PReLU: nnq.PReLU,
259
+ nni.BNReLU2d: nniq.BNReLU2d,
260
+ nni.BNReLU3d: nniq.BNReLU3d,
261
+ }
262
+
263
+ # Mapping from fused module class to a 2-tuple of:
264
+ # 1) The inner reference module class
265
+ # 2) The replacement static quantized module class for lowering
266
+ STATIC_LOWER_FUSED_MODULE_MAP: Dict[Type[nn.Module], Tuple[Type[nn.Module], Type[WeightedQuantizedModule]]] = {
267
+ nni.LinearReLU: (nnqr.Linear, nniq.LinearReLU),
268
+ # TODO: LinearLeakyReLU is registered as global but it is only fused and
269
+ # lowered when ondnn's backend config is used. Maybe need to separate
270
+ # registration and lowering functions for different backends in the future.
271
+ nni.LinearLeakyReLU: (nnqr.Linear, nniq.LinearLeakyReLU),
272
+ nni.LinearTanh: (nnqr.Linear, nniq.LinearTanh),
273
+ nni.ConvReLU1d: (nnqr.Conv1d, nniq.ConvReLU1d),
274
+ nni.ConvReLU2d: (nnqr.Conv2d, nniq.ConvReLU2d),
275
+ nni.ConvReLU3d: (nnqr.Conv3d, nniq.ConvReLU3d),
276
+ }
277
+
278
+ # The difference between STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP and STATIC_LOWER_FUSED_MODULE_MAP:
279
+ # The refer node inside STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP has 2 inputs.
280
+ # Mapping from fused module class to a 2-tuple of:
281
+ # 1) The inner reference module class
282
+ # 2) The replacement static quantized module class for lowering
283
+ STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP: Dict[Type[nn.Module], Tuple[Type[nn.Module], Type[WeightedQuantizedModule]]] = {
284
+ nni.ConvAdd2d: (nnqr.Conv2d, nniq.ConvAdd2d),
285
+ nni.ConvAddReLU2d: (nnqr.Conv2d, nniq.ConvAddReLU2d),
286
+ }
287
+
288
+ # Mapping from fused module class to a 2-tuple of:
289
+ # 1) The inner reference module class
290
+ # 2) The replacement dynamic quantized module class for lowering
291
+ DYNAMIC_LOWER_FUSED_MODULE_MAP: Dict[Type[nn.Module], Tuple[Type[nn.Module], Type[nn.Module]]] = {
292
+ nni.LinearReLU: (nnqr.Linear, nniqd.LinearReLU),
293
+ }
294
+
295
+ # Mapping from a functional to lower to a 2-tuple of
296
+ # 1) The quantized version of the op
297
+ # 2) The quantized version of the op fused with relu, if it exists, else None
298
+ STATIC_LOWER_FUNCTIONAL_MAP: Dict[Callable, Tuple[Callable, Optional[Callable]]] = {
299
+ F.linear: (torch.ops.quantized.linear, torch.ops.quantized.linear_relu),
300
+ F.conv1d: (torch.ops.quantized.conv1d, torch.ops.quantized.conv1d_relu),
301
+ F.conv2d: (torch.ops.quantized.conv2d, torch.ops.quantized.conv2d_relu),
302
+ F.conv3d: (torch.ops.quantized.conv3d, torch.ops.quantized.conv3d_relu),
303
+ F.conv_transpose1d: (torch.ops.quantized.conv_transpose1d, None),
304
+ F.conv_transpose2d: (torch.ops.quantized.conv_transpose2d, None),
305
+ F.conv_transpose3d: (torch.ops.quantized.conv_transpose3d, None),
306
+ }
307
+
308
+ WEIGHT_PREPACK_OPS: Set[Callable] = {
309
+ torch._ops.ops.quantized.linear_prepack,
310
+ torch._ops.ops.quantized.linear_prepack_fp16,
311
+ torch._ops.ops.quantized.conv1d_prepack,
312
+ torch._ops.ops.quantized.conv2d_prepack,
313
+ torch._ops.ops.quantized.conv3d_prepack,
314
+ torch.ops.quantized.conv_transpose1d_prepack,
315
+ torch.ops.quantized.conv_transpose2d_prepack,
316
+ torch.ops.quantized.conv_transpose3d_prepack,
317
+ }
318
+
319
+ # Mapping from a functional to a dictionary, where the key is a 2-tuple of
320
+ # (input_activation_dtype, weight_dtype) and the value is a 2-tuple of
321
+ # 1) The dynamically quantized version of the op
322
+ # 2) The dynamically quantized version of the op fused with relu, if it exists, else None
323
+ DYNAMIC_LOWER_FUNCTIONAL_MAP: Dict[Callable, Dict[Tuple[torch.dtype, torch.dtype], Tuple[Callable, Optional[Callable]]]] = {
324
+ F.linear: {
325
+ (torch.quint8, torch.qint8): (torch.ops.quantized.linear_dynamic,
326
+ torch.ops.quantized.linear_relu_dynamic),
327
+ (torch.float16, torch.float16): (torch.ops.quantized.linear_dynamic_fp16,
328
+ torch.ops.quantized.linear_relu_dynamic_fp16)
329
+ },
330
+ # dynamic conv + relu is not available yet
331
+ F.conv1d: {
332
+ (torch.quint8, torch.qint8): (torch.ops.quantized.conv1d_dynamic, None),
333
+ },
334
+ F.conv2d: {
335
+ (torch.quint8, torch.qint8): (torch.ops.quantized.conv2d_dynamic, None),
336
+ },
337
+ F.conv3d: {
338
+ (torch.quint8, torch.qint8): (torch.ops.quantized.conv3d_dynamic, None),
339
+ },
340
+ }
341
+
342
+ CONV_FUNCTIONAL_OPS: Set[Callable] = {
343
+ F.conv1d,
344
+ F.conv2d,
345
+ F.conv3d,
346
+ }
347
+
348
+ CONV_TRANSPOSE_FUNCTIONAL_OPS: Set[Callable] = {
349
+ F.conv_transpose1d,
350
+ F.conv_transpose2d,
351
+ F.conv_transpose3d,
352
+ }
353
+
354
+ QBIN_OP_MAPPING: Dict[Union[Callable, str], Callable] = {
355
+ operator.add: torch.ops.quantized.add,
356
+ torch.add: torch.ops.quantized.add,
357
+ operator.mul: torch.ops.quantized.mul,
358
+ torch.mul: torch.ops.quantized.mul,
359
+ torch.matmul: torch.ops.quantized.matmul,
360
+ }
361
+ QBIN_RELU_OP_MAPPING: Dict[Union[Callable, str], Callable] = {
362
+ operator.add: torch.ops.quantized.add_relu,
363
+ torch.add: torch.ops.quantized.add_relu,
364
+ operator.mul: torch.ops.quantized.mul_relu,
365
+ torch.mul: torch.ops.quantized.mul_relu,
366
+ }
367
+
368
+ def _save_packed_weight(self, destination, prefix, keep_vars):
369
+ for attr_name in dir(self):
370
+ if "_packed_weight" in attr_name and \
371
+ isinstance(getattr(self, attr_name), torch._C.ScriptObject): # type: ignore[attr-defined]
372
+ packed_weight = getattr(self, attr_name)
373
+ destination[prefix + attr_name] = packed_weight
374
+
375
+ def _load_packed_weight(self, state_dict, prefix, local_metadata, strict,
376
+ missing_keys, unexpected_keys, error_msgs):
377
+ attrs_to_pop = []
378
+ for attr_name in state_dict:
379
+ if attr_name.startswith("_packed_weight") and isinstance(state_dict[attr_name], torch._C.ScriptObject): # type: ignore[attr-defined] # noqa: B950
380
+ setattr(self, attr_name, state_dict[attr_name])
381
+ attrs_to_pop.append(attr_name)
382
+
383
+ # pop the packed param attributesn
384
+ for attr_name in attrs_to_pop:
385
+ state_dict.pop(attr_name)
386
+
387
+ def fold_weight(
388
+ quantized_model: GraphModule,
389
+ node_name_to_scope: Dict[str, Tuple[str, type]]
390
+ ) -> GraphModule:
391
+ """
392
+ Trace back from the weight node util we hit getattr, reconstruct the
393
+ graph module with the traced nodes and run the graph module to pack the
394
+ weight. then replace the original chain of ops with the packed weight.
395
+ """
396
+ packed_weights = {}
397
+ # map from folded node name to the prepacked weight name
398
+ folded_nodes = {}
399
+ # get packed weights
400
+ for node in quantized_model.graph.nodes:
401
+ if node.op == 'call_function' and node.target in WEIGHT_PREPACK_OPS:
402
+ nodes_to_fold = collect_producer_nodes(node)
403
+ if nodes_to_fold is not None:
404
+ for node_to_fold in nodes_to_fold:
405
+ folded_nodes[node_to_fold.name] = node
406
+
407
+ prepacking_module = graph_module_from_producer_nodes(
408
+ quantized_model, nodes_to_fold)
409
+ packed_weight = prepacking_module()
410
+ packed_weights[node.name] = packed_weight
411
+
412
+ # remove folded nodes and replace the prepacking node with getattr
413
+ folded_graph = Graph()
414
+ env: Dict[Any, Any] = {}
415
+
416
+ def load_arg(a):
417
+ return map_arg(a, lambda node: env[node.name])
418
+
419
+ for node in quantized_model.graph.nodes:
420
+ prepack_node = folded_nodes.get(node.name, None)
421
+ if prepack_node is node:
422
+ packed_weight = packed_weights[node.name]
423
+ # add a prepacked attribute to root
424
+ op_node = next(iter(prepack_node.users))
425
+ module_path, _ = node_name_to_scope[op_node.name]
426
+ get_new_packed_weight_name = \
427
+ get_new_attr_name_with_prefix(module_path + '_packed_weight_')
428
+ packed_weight_name = get_new_packed_weight_name(quantized_model)
429
+ setattr(quantized_model, packed_weight_name, packed_weight)
430
+ # replace prepack node with a getattr node
431
+ env[node.name] = folded_graph.create_node(
432
+ 'get_attr', packed_weight_name, (), {})
433
+ elif prepack_node is not None:
434
+ # remove the foled node
435
+ continue
436
+ else:
437
+ # copy other nodes
438
+ env[node.name] = folded_graph.node_copy(node, load_arg)
439
+
440
+ quantized_model = GraphModule(quantized_model, folded_graph)
441
+ quantized_model._register_state_dict_hook(_save_packed_weight)
442
+ quantized_model._register_load_state_dict_pre_hook(_load_packed_weight, with_module=True)
443
+ return quantized_model
444
+
445
+ def _get_module(node: Node, modules: Dict[str, nn.Module]) -> Optional[nn.Module]:
446
+ """
447
+ Return the `torch.nn.Module` that corresponds to the specified node's target.
448
+ If no such node exists, return None.
449
+ """
450
+ if node.op == "call_module" and str(node.target) in modules:
451
+ return modules[str(node.target)]
452
+ else:
453
+ return None
454
+
455
+ def _match_static_pattern(
456
+ node: Node,
457
+ modules: Dict[str, nn.Module],
458
+ qconfig_map: Dict[str, QConfigAny],
459
+ matching_modules_or_ops: List[Callable],
460
+ dequantize_node_arg_indices: List[int]
461
+ ) -> Union[Tuple[Node, Node, Node], Tuple[None, None, None]]:
462
+ """
463
+ Match the pattern (dequantize - ref node - quantize) against the node provided.
464
+
465
+ If there is a match, return a 3-tuple of:
466
+ 1) q_node: the quantize node,
467
+ 2) relu_node: a relu node wrapping the ref_node, and
468
+ 3) ref_node: a reference module or functional node to replace with its quantized counterpart
469
+ Otherwise, if there is no match, return a 3-tuple of (None, None, None).
470
+
471
+ Parameters:
472
+ node: The `torch.fx.Node` to match against.
473
+ modules: A mapping from node names to modules in the model graph, used for module lookup.
474
+ qconfig_map: A mapping from node names to the qconfigs associated with the nodes.
475
+ If the corresponding qconfig for the reference node is None, then return no match.
476
+ matching_modules_or_ops: Either a list of functions or a list of `torch.nn.Module`s.
477
+ If the reference node is not in this list, then return no match.
478
+ dequantize_node_arg_indices: A list of indices in the reference node args where dequantize
479
+ nodes may be present. An empty list means skipping the check for dequantize nodes.
480
+ """
481
+ SKIP_LOWERING_VALUE = (None, None, None)
482
+
483
+ # Match quantize node
484
+ if node.op != "call_function" or node.target != torch.quantize_per_tensor:
485
+ return SKIP_LOWERING_VALUE
486
+ q_node = node
487
+ ref_node = q_node.args[0]
488
+ assert(isinstance(ref_node, Node))
489
+
490
+ # Handle cases where the node is wrapped in a ReLU
491
+ if (ref_node.op == "call_function" and ref_node.target in (F.relu, torch.relu)) or\
492
+ (ref_node.op == "call_module" and type(_get_module(ref_node, modules)) == nn.ReLU):
493
+ relu_node = ref_node
494
+ ref_node = relu_node.args[0]
495
+ assert(isinstance(ref_node, Node))
496
+ else:
497
+ relu_node = None
498
+ if should_skip_lowering(ref_node, qconfig_map):
499
+ return SKIP_LOWERING_VALUE
500
+
501
+ # Match reference module or functional
502
+ if isinstance(matching_modules_or_ops[0], type) and issubclass(matching_modules_or_ops[0], nn.Module):
503
+ expected_op = "call_module"
504
+ match_key = type(_get_module(ref_node, modules))
505
+ else:
506
+ expected_op = "call_function"
507
+ match_key = ref_node.target
508
+ if ref_node.op != expected_op or match_key not in matching_modules_or_ops:
509
+ return SKIP_LOWERING_VALUE
510
+
511
+ # Match dequantize node(s). Both of the following conditions must pass:
512
+ # (1) All `torch.fx.Node`s at the matching indices must be a dequantize node
513
+ # (2) There must be at least one dequantize node
514
+ matched_dequantize = False
515
+ for i in dequantize_node_arg_indices:
516
+ assert i < len(ref_node.args),\
517
+ f"Dequantize index {i} exceeded reference node's arg length {len(ref_node.args)}"
518
+ arg = ref_node.args[i]
519
+ if is_dequantize_node(arg):
520
+ matched_dequantize = True
521
+ elif isinstance(arg, Node):
522
+ return SKIP_LOWERING_VALUE
523
+ if not matched_dequantize:
524
+ return SKIP_LOWERING_VALUE
525
+
526
+ return (q_node, relu_node, ref_node)
527
+
528
+ def _match_static_pattern_with_two_inputs(
529
+ node: Node,
530
+ modules: Dict[str, nn.Module],
531
+ qconfig_map: Dict[str, QConfigAny],
532
+ matching_modules_or_ops: List[Callable]
533
+ ) -> Union[Tuple[Node, Node], Tuple[None, None]]:
534
+ """
535
+ (dequantize \
536
+ Match the pattern (dequantize - ref node - quantize) against the node provided.
537
+
538
+ If there is a match, return a 2-tuple of:
539
+ 1) q_node: the quantize node,
540
+ 2) ref_node: a reference module or functional node to replace with its quantized counterpart
541
+ Otherwise, if there is no match, return a 2-tuple of (None, None).
542
+
543
+ Parameters:
544
+ node: The `torch.fx.Node` to match against.
545
+ modules: A mapping from node names to modules in the model graph, used for module lookup.
546
+ qconfig_map: A mapping from node names to the qconfigs associated with the nodes.
547
+ If the corresponding qconfig for the reference node is None, then return no match.
548
+ matching_modules_or_ops: Either a list of functions or a list of `torch.nn.Module`s.
549
+ If the reference node is not in this list, then return no match.
550
+ """
551
+ SKIP_LOWERING_VALUE = (None, None)
552
+
553
+ # Match quantize node
554
+ if node.op != "call_function" or node.target != torch.quantize_per_tensor:
555
+ return SKIP_LOWERING_VALUE
556
+ q_node = node
557
+ ref_node = q_node.args[0]
558
+ assert(isinstance(ref_node, Node))
559
+
560
+ if should_skip_lowering(ref_node, qconfig_map):
561
+ return SKIP_LOWERING_VALUE
562
+
563
+ # Match reference module or functional
564
+ if isinstance(matching_modules_or_ops[0], type) and issubclass(matching_modules_or_ops[0], nn.Module):
565
+ expected_op = "call_module"
566
+ match_key = type(_get_module(ref_node, modules))
567
+ else:
568
+ # This pass only support op of "call_module"
569
+ return SKIP_LOWERING_VALUE
570
+
571
+ if ref_node.op != expected_op or match_key not in matching_modules_or_ops:
572
+ return SKIP_LOWERING_VALUE
573
+
574
+ # Check ref_node has 2 input nodes, both are dq node.
575
+ if len(ref_node.args) != 2:
576
+ return SKIP_LOWERING_VALUE
577
+ for i in range(len(ref_node.args)):
578
+ arg = ref_node.args[i]
579
+ if not is_dequantize_node(arg):
580
+ return SKIP_LOWERING_VALUE
581
+
582
+ return (q_node, ref_node)
583
+
584
+ def _lower_static_weighted_ref_module(
585
+ model: GraphModule,
586
+ qconfig_map: Dict[str, QConfigAny]):
587
+ """
588
+ Traverse the graph and find dequantize - ref module - quantize patterns
589
+ and replace them with the quantized version of the ref module.
590
+ """
591
+ modules = dict(model.named_modules(remove_duplicate=False))
592
+ nodes = list(model.graph.nodes)
593
+ for n in model.graph.nodes:
594
+ # Step 0: Find nodes that match this pattern (dequantize - ref module - quantize)
595
+ matching_modules = list(STATIC_LOWER_MODULE_MAP.keys()) + list(STATIC_LOWER_FUSED_MODULE_MAP.keys())
596
+ (q_node, relu_node, ref_node) = _match_static_pattern(
597
+ n, modules, qconfig_map, matching_modules, dequantize_node_arg_indices=[0]) # type: ignore[arg-type]
598
+ if q_node is None:
599
+ continue
600
+ assert(ref_node is not None)
601
+ (_, scale_node, zero_point_node, _) = q_node.args
602
+ ref_module = _get_module(ref_node, modules)
603
+ ref_class = type(ref_module)
604
+ assert(isinstance(scale_node, Node))
605
+ assert(isinstance(zero_point_node, Node))
606
+ assert(issubclass(ref_class, nn.Module))
607
+
608
+ # Step 1: Change this pattern to use the corresponding quantized module
609
+ # For fused modules, we also check whether the inner module is a reference module
610
+ # If so, we replace the entire fused module with the corresponding quantized module
611
+ if ref_class in STATIC_LOWER_FUSED_MODULE_MAP:
612
+ inner_ref_class, q_class = STATIC_LOWER_FUSED_MODULE_MAP[ref_class]
613
+ if type(ref_module[0]) != inner_ref_class: # type: ignore[index]
614
+ continue
615
+ else:
616
+ q_class = STATIC_LOWER_MODULE_MAP[ref_class]
617
+ output_scale = getattr(model, scale_node.target)
618
+ output_zero_point = getattr(model, zero_point_node.target)
619
+ q_module = q_class.from_reference(ref_module, output_scale, output_zero_point)
620
+ # replace reference module with quantized module
621
+ parent_name, module_name = _parent_name(ref_node.target)
622
+ setattr(modules[parent_name], module_name, q_module)
623
+
624
+ # Step 2: Reroute around dq_node, and remove q_node and its args
625
+ assert(len(ref_node.args) == 1)
626
+ dq_node = ref_node.args[0]
627
+ assert(isinstance(dq_node, Node))
628
+ ref_node.replace_input_with(dq_node, dq_node.args[0])
629
+ q_node.replace_all_uses_with(ref_node)
630
+ model.graph.erase_node(q_node)
631
+ model.graph.erase_node(scale_node)
632
+ model.graph.erase_node(zero_point_node)
633
+
634
+ def _lower_static_weighted_ref_module_with_two_inputs(
635
+ model: GraphModule,
636
+ qconfig_map: Dict[str, QConfigAny]):
637
+ """
638
+ Traverse the graph and find patterns
639
+ dequantize dequantize
640
+ \\ //
641
+ ref module
642
+ \\
643
+ quantize
644
+ and replace them with the quantized version of the ref module.
645
+ """
646
+ modules = dict(model.named_modules(remove_duplicate=False))
647
+ nodes = list(model.graph.nodes)
648
+ for n in model.graph.nodes:
649
+ # (dequantize \
650
+ # Step 0: Find nodes that match this pattern (dequantize - ref module - quantize)
651
+ matching_modules = list(STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP.keys())
652
+ (q_node, ref_node) = _match_static_pattern_with_two_inputs(
653
+ n, modules, qconfig_map, matching_modules) # type: ignore[arg-type]
654
+ if q_node is None:
655
+ continue
656
+ assert(ref_node is not None)
657
+ (_, scale_node, zero_point_node, _) = q_node.args
658
+ ref_module = _get_module(ref_node, modules)
659
+ ref_class = type(ref_module)
660
+ assert(isinstance(scale_node, Node))
661
+ assert(isinstance(zero_point_node, Node))
662
+ assert(issubclass(ref_class, nn.Module))
663
+
664
+ # Step 1: Change this pattern to use the corresponding quantized module
665
+ # For fused modules, we also check whether the inner module is a reference module
666
+ # If so, we replace the entire fused module with the corresponding quantized module
667
+ if ref_class in STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP:
668
+ inner_ref_class, q_class = STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP[ref_class]
669
+ if type(ref_module[0]) != inner_ref_class: # type: ignore[index]
670
+ continue
671
+ else:
672
+ continue
673
+ output_scale = getattr(model, scale_node.target)
674
+ output_zero_point = getattr(model, zero_point_node.target)
675
+ q_module = q_class.from_reference(ref_module, output_scale, output_zero_point)
676
+ # replace reference module with quantized module
677
+ parent_name, module_name = _parent_name(ref_node.target)
678
+ setattr(modules[parent_name], module_name, q_module)
679
+
680
+ # Step 2: Reroute around dq_node, and remove q_node and its args
681
+ assert(len(ref_node.args) == 2)
682
+ for arg in ref_node.args:
683
+ if not is_dequantize_node(arg):
684
+ continue
685
+ dq_node = arg
686
+ assert(isinstance(dq_node, Node))
687
+ ref_node.replace_input_with(dq_node, dq_node.args[0])
688
+
689
+ q_node.replace_all_uses_with(ref_node)
690
+ model.graph.erase_node(q_node)
691
+ model.graph.erase_node(scale_node)
692
+ model.graph.erase_node(zero_point_node)
693
+
694
+ def _lower_dynamic_weighted_ref_module(model: GraphModule):
695
+ """
696
+ Traverse the graph and find quantize_per_tensor_dynamic - dequantize - ref_module patterns
697
+ and replace them with the dynamically quantized version of the ref module.
698
+ """
699
+ named_modules = dict(model.named_modules(remove_duplicate=False))
700
+ for n in model.graph.nodes:
701
+ if n.op != "call_module" or \
702
+ type(named_modules[str(n.target)]) not in \
703
+ set(DYNAMIC_LOWER_MODULE_MAP.keys()).union(
704
+ set(DYNAMIC_LOWER_FUSED_MODULE_MAP.keys())):
705
+ continue
706
+ ref_node = n
707
+ dq_node = ref_node.args[0]
708
+ if dq_node.op != "call_method" or dq_node.target != "dequantize":
709
+ continue
710
+
711
+ input_dynamic_q_node = dq_node.args[0]
712
+
713
+ if input_dynamic_q_node.op != "call_function" or \
714
+ input_dynamic_q_node.target != torch.quantize_per_tensor_dynamic:
715
+ continue
716
+
717
+ activation_dtype = input_dynamic_q_node.args[1]
718
+ is_fp16 = activation_dtype == torch.float16
719
+ is_int8 = activation_dtype in [torch.quint8, torch.qint8]
720
+ if not is_int8 and not is_fp16:
721
+ continue
722
+
723
+ ref_module = named_modules[str(ref_node.target)]
724
+ ref_class = type(ref_module)
725
+ if ref_class in DYNAMIC_LOWER_FUSED_MODULE_MAP:
726
+ inner_ref_class, q_class = DYNAMIC_LOWER_FUSED_MODULE_MAP[ref_class]
727
+ if type(ref_module[0]) != inner_ref_class:
728
+ continue
729
+ else:
730
+ q_class = DYNAMIC_LOWER_MODULE_MAP.get(ref_class) # type: ignore[assignment]
731
+ # TODO: maybe define a WeightedDynamicallyQuantizedModule
732
+ q_module = q_class.from_reference(ref_module) # type: ignore[attr-defined]
733
+
734
+ # replace reference module with dynamically quantized module
735
+ parent_name, module_name = _parent_name(ref_node.target)
736
+ setattr(named_modules[parent_name], module_name, q_module)
737
+ ref_node.replace_input_with(dq_node, input_dynamic_q_node.args[0])
738
+
739
+ def _lower_weight_only_weighted_ref_module(model: GraphModule):
740
+ """
741
+ Traverse the graph and find ref_module patterns
742
+ and replace them with the weight only quantized version of the ref module.
743
+ """
744
+ named_modules = dict(model.named_modules(remove_duplicate=False))
745
+ for n in model.graph.nodes:
746
+ if n.op != "call_module" or \
747
+ type(named_modules[str(n.target)]) not in \
748
+ set(WEIGHT_ONLY_LOWER_MODULE_MAP.keys()):
749
+ continue
750
+ ref_node = n
751
+ ref_module = named_modules[str(ref_node.target)]
752
+ ref_class = type(ref_module)
753
+ q_class = WEIGHT_ONLY_LOWER_MODULE_MAP.get(ref_class)
754
+ # TODO: WeightedQuantizedModule is currently assuming static quant apis
755
+ # with output_scale, output_zero_point in from_reference, we may want to
756
+ # relax that, or rename this
757
+ # TODO: maybe define a WeightedWeightOnlyQuantizedModule
758
+ q_module = q_class.from_reference(ref_module) # type: ignore[union-attr]
759
+
760
+ # replace reference module with dynamically quantized module
761
+ parent_name, module_name = _parent_name(ref_node.target)
762
+ setattr(named_modules[parent_name], module_name, q_module)
763
+
764
+ def _lower_static_weighted_ref_functional(
765
+ model: GraphModule,
766
+ qconfig_map: Dict[str, QConfigAny]):
767
+ """
768
+ Traverse the graph and replace functional reference patterns with their quantized versions.
769
+ """
770
+ modules = dict(model.named_modules(remove_duplicate=False))
771
+ nodes = list(model.graph.nodes)
772
+ for n in model.graph.nodes:
773
+ # Step 0: Find nodes that match this pattern (dequantize - functional op - quantize)
774
+ matching_ops = list(STATIC_LOWER_FUNCTIONAL_MAP.keys())
775
+ (q_node, relu_node, func_node) = _match_static_pattern(
776
+ n, modules, qconfig_map, matching_ops, dequantize_node_arg_indices=[0, 1])
777
+ if q_node is None:
778
+ continue
779
+ assert(func_node is not None)
780
+ (_, output_scale_node, output_zp_node, _) = q_node.args
781
+ (input_dq_node, weight_dq_node, *remaining_func_args) = func_node.args
782
+ assert(isinstance(output_zp_node, Node))
783
+ assert(isinstance(input_dq_node, Node))
784
+ assert(isinstance(weight_dq_node, Node))
785
+ quantized_weight = weight_dq_node.args[0]
786
+ assert(isinstance(quantized_weight, Node))
787
+ if quantized_weight.op != "call_function" or\
788
+ quantized_weight.target not in (torch.quantize_per_tensor, torch.quantize_per_channel):
789
+ continue
790
+
791
+ # Step 1: Replace quantized weights with packed weights, which will be folded later
792
+ # Use the right prepack op and prepare the corresponding args
793
+ # Linear prepack args: (quantized weights[, bias])
794
+ # Conv prepack args: (quantized weights[, bias, stride, padding, dilation, groups])
795
+ prepack_args = [quantized_weight] + remaining_func_args
796
+ if func_node.target == F.linear:
797
+ weight_dtype = quantized_weight.args[-1]
798
+ prepack_op = get_linear_prepack_op_for_dtype(weight_dtype)
799
+ elif func_node.target in CONV_FUNCTIONAL_OPS:
800
+ prepack_op = get_qconv_prepack_op(func_node.target) # type: ignore[arg-type]
801
+ # For conv1d, the stride, padding, and dilation args may be ints,
802
+ # in which case we need to convert them to tuples
803
+ if func_node.target == F.conv1d:
804
+ for i in [2, 3, 4]:
805
+ if len(prepack_args) > i and isinstance(prepack_args[i], int):
806
+ prepack_args[i] = (prepack_args[i],)
807
+ elif func_node.target in CONV_TRANSPOSE_FUNCTIONAL_OPS:
808
+ prepack_op = get_qconv_prepack_op(func_node.target) # type: ignore[arg-type]
809
+ # For conv_transpose1d, the stride, padding, and dilation args may be ints,
810
+ # in which case we need to convert them to tuples
811
+ if func_node.target == F.conv_transpose1d:
812
+ # Note prepack_args[5] is groups.
813
+ for i in [2, 3, 4, 6]:
814
+ if len(prepack_args) > i and isinstance(prepack_args[i], int):
815
+ prepack_args[i] = (prepack_args[i],)
816
+ # swap dilation and groups
817
+ # prepack op has arguments: {w, b, stride, padding, output_padding, dilation, groups}
818
+ # transposed conv op has arguments: {x, w, b, stride, padding, output_padding, groups, dilation}
819
+ if (len(prepack_args) > 6):
820
+ prepack_args[5], prepack_args[6] = prepack_args[6], prepack_args[5]
821
+ else:
822
+ raise ValueError(f"Lowering is not supported for op '{func_node.target}'")
823
+ with model.graph.inserting_before(output_scale_node):
824
+ # kwargs of the func node are needed for prepack op (i.e., quantized::linear_prepack)
825
+ # They are not needed for compute op (i.e., quantized::linear)
826
+ kwargs = func_node.kwargs
827
+ # F.linear uses 'bias' key for bias while qlinear_prepack uses 'B' for bias
828
+ if func_node.target == F.linear and 'bias' in kwargs:
829
+ kwargs = kwargs.copy()
830
+ kwargs['B'] = kwargs['bias']
831
+ del kwargs['bias']
832
+ packed_weight = model.graph.create_node("call_function", prepack_op, tuple(prepack_args), kwargs)
833
+
834
+ # Step 2: Replace reference pattern with the corresponding quantized op
835
+ (q_func, q_relu_func) = STATIC_LOWER_FUNCTIONAL_MAP[func_node.target] # type: ignore[index]
836
+ # conv_transpose does not support fusion with relu yet. q_relu_func is None in such cases
837
+ if q_relu_func is not None:
838
+ func_node.target = q_relu_func if relu_node is not None else q_func
839
+ else:
840
+ func_node.target = q_func
841
+ func_node.args = (input_dq_node.args[0], packed_weight, output_scale_node, output_zp_node)
842
+ # kwargs for func_node has been moved to kwargs for prepack op
843
+ func_node.kwargs = {}
844
+ q_node.replace_all_uses_with(func_node)
845
+ # Move func_node after output_zp_node in the graph
846
+ output_zp_node.append(func_node)
847
+
848
+ # Clean up: Remove quantize node, and the relu node if it exists
849
+ model.graph.erase_node(q_node)
850
+ if relu_node is not None and q_relu_func is not None:
851
+ model.graph.erase_node(relu_node)
852
+
853
+ def _lower_dynamic_weighted_ref_functional(
854
+ model: GraphModule,
855
+ qconfig_map: Dict[str, QConfigAny]):
856
+ """
857
+ Traverse the graph and replace functional reference patterns with their dynamically
858
+ quantized versions.
859
+ Examples:
860
+ quantize_per_tensor_dynamic - dequantize - functional linear --> linear_dynamic
861
+ to(torch.float16) - dequantize - functional linear --> linear_dynamic_fp16
862
+ """
863
+ modules = dict(model.named_modules(remove_duplicate=False))
864
+ nodes = list(model.graph.nodes)
865
+ # we want to search in reserved order so that we can match the larger patterns first
866
+ # e.g. we want to match linear - relu before linear.
867
+ for n in reversed(model.graph.nodes):
868
+
869
+ # Step 0: Find nodes that match this pattern
870
+ # (quantize_per_tensor_dynamic - dequantize - dynamically quantized op)
871
+ # We search for the pattern backwards, starting with the quantize node
872
+ # Quantize node args: (func, scale, zp, dtype)
873
+ func_node = n
874
+ # Handle cases where the functional op is wrapped in a ReLU
875
+ if func_node.op == "call_function" and func_node.target == F.relu or \
876
+ func_node.op == "call_module" and \
877
+ type(modules[str(func_node.target)]) == torch.nn.ReLU:
878
+ relu_node = func_node
879
+ func_node = relu_node.args[0]
880
+ else:
881
+ relu_node = None
882
+ if should_skip_lowering(func_node, qconfig_map):
883
+ continue
884
+ # Linear args: (dequantized inputs, dequantized weights[, bias])
885
+ # Conv args: (dequantized inputs, dequantized weights[, bias, stride, padding, dilation, groups])
886
+ if func_node.op != "call_function" or func_node.target not in DYNAMIC_LOWER_FUNCTIONAL_MAP:
887
+ continue
888
+ (input_dq_node, weight_dq_node, *remaining_func_args) = func_node.args
889
+ if input_dq_node.op != "call_method" or input_dq_node.target != "dequantize" or \
890
+ weight_dq_node.op != "call_method" or weight_dq_node.target != "dequantize":
891
+ continue
892
+
893
+ input_dynamic_q_node = input_dq_node.args[0]
894
+
895
+ if input_dynamic_q_node.op != "call_function" or \
896
+ input_dynamic_q_node.target != torch.quantize_per_tensor_dynamic:
897
+ continue
898
+
899
+ reduce_range_node = None
900
+ (pattern_input, activation_dtype, reduce_range_node) = input_dynamic_q_node.args
901
+ is_fp16 = activation_dtype == torch.float16
902
+ is_int8 = activation_dtype in [torch.quint8, torch.qint8]
903
+ if not is_int8 and not is_fp16:
904
+ continue
905
+
906
+ quantized_weight = weight_dq_node.args[0]
907
+ weight_dtype = quantized_weight.args[-1]
908
+
909
+ # Step 1: Try to select reference pattern with the corresponding quantized op
910
+ dynamic_quant_dtype_key = (activation_dtype, weight_dtype)
911
+ if dynamic_quant_dtype_key not in DYNAMIC_LOWER_FUNCTIONAL_MAP[func_node.target]:
912
+ print(f"Didn't find dtype combination {dynamic_quant_dtype_key} during "
913
+ f"dynamic quantized op lowering for {func_node.target}")
914
+ continue
915
+ (q_func, q_relu_func) = DYNAMIC_LOWER_FUNCTIONAL_MAP[func_node.target][dynamic_quant_dtype_key]
916
+
917
+ if q_func is None or q_relu_func is None:
918
+ print("Didn't find corresponding quantized function or quantized relu function "
919
+ f"for {func_node.target}, {dynamic_quant_dtype_key}")
920
+ continue
921
+
922
+ # Step 2: Replace quantized weights with packed weights, which will be folded later
923
+ # Use the right prepack op and prepare the corresponding args
924
+ # Linear prepack args: (quantized weights[, bias])
925
+ # Conv prepack args: (quantized weights[, bias, stride, padding, dilation, groups])
926
+ prepack_args = [quantized_weight] + remaining_func_args
927
+ if func_node.target == F.linear:
928
+ prepack_op = get_linear_prepack_op_for_dtype(weight_dtype)
929
+ elif func_node.target in CONV_FUNCTIONAL_OPS:
930
+ prepack_op = get_qconv_prepack_op(func_node.target)
931
+ # For conv1d, the stride, padding, and dilation args may be ints,
932
+ # in which case we need to convert them to tuples
933
+ if func_node.target == F.conv1d:
934
+ for i in [2, 3, 4]:
935
+ if len(prepack_args) > i and isinstance(prepack_args[i], int):
936
+ prepack_args[i] = (prepack_args[i],)
937
+ else:
938
+ raise ValueError(f"Lowering is not supported for op '{func_node.target}'")
939
+ with model.graph.inserting_before(func_node):
940
+ packed_weight = model.graph.create_node("call_function", prepack_op, tuple(prepack_args), {})
941
+
942
+ # Step 3: Replace reference pattern with the corresponding quantized op
943
+ func_node.target = q_relu_func if relu_node is not None else q_func
944
+ if is_int8:
945
+ func_node.args = (pattern_input, packed_weight, reduce_range_node)
946
+ else:
947
+ func_node.args = (pattern_input, packed_weight)
948
+
949
+ if relu_node is not None:
950
+ relu_node.replace_all_uses_with(func_node)
951
+
952
+ # Step 4: Remove the relu node if it exists
953
+ if relu_node is not None:
954
+ model.graph.erase_node(relu_node)
955
+
956
+ def _lower_quantized_binary_op(
957
+ model: GraphModule,
958
+ qconfig_map: Dict[str, QConfigAny]):
959
+ binary_ops_to_lower: List[Callable] = [operator.add, torch.add, operator.mul, torch.mul, torch.matmul]
960
+ modules = dict(model.named_modules(remove_duplicate=False))
961
+ for n in model.graph.nodes:
962
+ # Step 0: Find nodes that match this pattern (dequantize - ref module - quantize)
963
+ (q_node, relu_node, bop_node) = _match_static_pattern(
964
+ n, modules, qconfig_map, binary_ops_to_lower, dequantize_node_arg_indices=[0, 1])
965
+ if q_node is None:
966
+ continue
967
+ assert(bop_node is not None)
968
+ (_, scale_node, zero_point_node, _) = q_node.args
969
+
970
+ # Step 1: Remove dequant nodes
971
+ num_dq_nodes = 0
972
+ for arg in bop_node.args:
973
+ if not is_dequantize_node(arg):
974
+ continue
975
+ dq_node = arg
976
+ assert(isinstance(dq_node, Node))
977
+ dn_input = dq_node.args[0]
978
+ bop_node.replace_input_with(dq_node, dn_input)
979
+ num_dq_nodes += 1
980
+ assert(num_dq_nodes > 0)
981
+
982
+ # Step 2: Swap binary op to quantized binary op
983
+ assert bop_node.target in QBIN_OP_MAPPING
984
+ binop_to_qbinop = QBIN_OP_MAPPING if relu_node is None else QBIN_RELU_OP_MAPPING
985
+ qbin_op = binop_to_qbinop[bop_node.target]
986
+ # prepare the args for quantized binary op
987
+ # (x, y)
988
+ qop_node_args = list(bop_node.args)
989
+ # (x, y, scale, zero_point)
990
+ # add scale and zero_point arguments for Tensor - Tensor operation
991
+ if num_dq_nodes == 2:
992
+ qop_node_args.extend([scale_node, zero_point_node])
993
+ # insert a call to quantized binary op and remove the original binary op
994
+ with model.graph.inserting_after(q_node):
995
+ qop_node = create_node_from_old_node_preserve_meta(
996
+ model.graph,
997
+ ("call_function", qbin_op, tuple(qop_node_args), {}),
998
+ bop_node)
999
+ q_node.replace_all_uses_with(qop_node)
1000
+
1001
+ # Step 3: Remove quantize node, binary op node, and relu node if any
1002
+ model.graph.erase_node(q_node)
1003
+ if relu_node is not None:
1004
+ model.graph.erase_node(relu_node)
1005
+ model.graph.erase_node(bop_node)
1006
+
1007
+ def special_pattern_replacement(model: GraphModule):
1008
+ modules = dict(model.named_modules(remove_duplicate=False))
1009
+ for n in model.graph.nodes:
1010
+ q_node = n
1011
+ is_quantize = q_node.target == torch.quantize_per_tensor
1012
+ is_to_fp16 = q_node.op == "call_method" and q_node.target == "to" and \
1013
+ len(q_node.args) == 2 and q_node.args[1] == torch.float16
1014
+ if not (is_quantize or is_to_fp16):
1015
+ continue
1016
+ ref_node = q_node.args[0]
1017
+ # get output scale/zero_point/dtype from the quantize node
1018
+ # ref_node, scale_node, zero_point_node, dtype = q_node.args
1019
+ # TODO: add safety checks that users for the ref_node and dq_node needs to be one
1020
+ is_call_function, is_call_method, is_call_module = is_fixed_qparams_node(ref_node, modules)
1021
+ if is_to_fp16 and (is_call_function or is_call_method or is_call_module):
1022
+ # TODO: add a warning or error out here? (bc-breaking if error out)
1023
+ # warnings.warn(
1024
+ # "Only reference patterns are currently supported for {dtype} dtype with {op} op"
1025
+ # "".format(dtype=dtypes, op=ref_node))
1026
+ continue
1027
+
1028
+ is_call_function, is_call_method, is_call_module = is_default_node(ref_node, modules)
1029
+ if is_to_fp16 and (is_call_function or is_call_method or is_call_module):
1030
+ # TODO: add a warning or error out here? (bc-breaking if error out)
1031
+ continue
1032
+
1033
+ # This check includes all supported ops
1034
+ is_call_function, is_call_method, is_call_module = is_special_pattern_node(ref_node, modules)
1035
+ if not (is_call_module or is_call_function or is_call_method):
1036
+ continue
1037
+ assert len(ref_node.args) > 0 or len(ref_node.kwargs) > 0
1038
+ dq_node_or_nodes = ref_node.args[0] if len(ref_node.args) > 0 else next(iter(ref_node.kwargs.values()))
1039
+ assert isinstance(dq_node_or_nodes, (Node, tuple, list))
1040
+ is_dequantize = False
1041
+ if isinstance(dq_node_or_nodes, Node):
1042
+ is_dequantize = dq_node_or_nodes.op == 'call_method' and \
1043
+ dq_node_or_nodes.target == 'dequantize'
1044
+ elif isinstance(dq_node_or_nodes, (tuple, list)):
1045
+ is_dequantize = all(
1046
+ x.op == 'call_method' and x.target == 'dequantize'
1047
+ for x in dq_node_or_nodes)
1048
+
1049
+ if not is_dequantize:
1050
+ continue
1051
+
1052
+ # TODO: enable we have patterns that needs to swap the modules
1053
+ if is_call_module:
1054
+ ref_module = modules[ref_node.target]
1055
+ if type(ref_module) in SPECIAL_PATTERN_LOWER_MODULE_MAP and is_quantize:
1056
+ qmodule_cls = SPECIAL_PATTERN_LOWER_MODULE_MAP.get(type(ref_module))
1057
+ scale_node = q_node.args[1]
1058
+ zero_point_node = q_node.args[2]
1059
+ output_scale = getattr(model, scale_node.target)
1060
+ output_zero_point = getattr(model, zero_point_node.target)
1061
+
1062
+ qmodule = qmodule_cls.from_reference(ref_module, output_scale, output_zero_point) # type:ignore[union-attr]
1063
+ # replace reference module with quantized module
1064
+ parent_name, module_name = _parent_name(ref_node.target)
1065
+ setattr(modules[parent_name], module_name, qmodule)
1066
+
1067
+ # reroute around dq node:
1068
+ dq_nodes: List[Node] = []
1069
+ if isinstance(dq_node_or_nodes, Node):
1070
+ dq_nodes = [dq_node_or_nodes]
1071
+ elif isinstance(dq_node_or_nodes, (tuple, list)):
1072
+ dq_nodes = list(dq_node_or_nodes)
1073
+
1074
+ for dq_node in dq_nodes:
1075
+ dn_input = dq_node.args[0]
1076
+ ref_node.replace_input_with(dq_node, dn_input)
1077
+
1078
+ # store q node args
1079
+ qnode_qparams = list(q_node.args)[1:]
1080
+ # replace uses of q node with input and remove q node
1081
+ q_node_input = q_node.args[0]
1082
+ q_node.replace_all_uses_with(q_node_input)
1083
+ model.graph.erase_node(q_node)
1084
+
1085
+ is_call_function, is_call_method, is_call_module = is_default_node(ref_node, modules)
1086
+ if is_call_function:
1087
+ # pass scale/zer_point arguments from quantize_per_tensor to the default node operator
1088
+ # insert an op after the zero_point node so that the scale/zero_point
1089
+ # nodes are is available
1090
+ qop = get_quantized_operator(ref_node.target)
1091
+ args = list(ref_node.args)
1092
+ kwargs = dict(ref_node.kwargs)
1093
+ if qop in QOP_TO_ARG_NAMES_TO_SKIP:
1094
+ args_to_skip = QOP_TO_ARG_NAMES_TO_SKIP[qop]
1095
+ for arg in args_to_skip:
1096
+ if arg in kwargs:
1097
+ kwargs.pop(arg)
1098
+ kwargs["output_scale"] = qnode_qparams[0]
1099
+ kwargs["output_zero_point"] = qnode_qparams[1]
1100
+ with model.graph.inserting_after(qnode_qparams[1]):
1101
+ qop_node = create_node_from_old_node_preserve_meta(
1102
+ model.graph,
1103
+ ("call_function", qop, tuple(args), kwargs),
1104
+ ref_node)
1105
+ ref_node.replace_all_uses_with(qop_node)
1106
+ model.graph.erase_node(ref_node)
1107
+ else:
1108
+ # remove scale/zero_point node for quantize node
1109
+ for n in qnode_qparams:
1110
+ if isinstance(n, Node):
1111
+ model.graph.erase_node(n)
1112
+
1113
+ return model
1114
+
1115
+ def _lower_getattr_tensor_metadta_op(model: GraphModule):
1116
+ """ Modified the graph of the model inplace, to skip extra dequantize op before
1117
+ the general tensor shape ops when possible
1118
+ """
1119
+ for n in model.graph.nodes:
1120
+ if is_getattr_tensor_metadata_node(n):
1121
+ maybe_dq = n.args[0]
1122
+ if maybe_dq.op != "call_method" or maybe_dq.target != "dequantize":
1123
+ continue
1124
+ # skip the dequantize node
1125
+ args = list(n.args)
1126
+ args[0] = n.args[0].args[0]
1127
+ n.args = tuple(args)
1128
+
1129
+ def _lower_get_tensor_info_op(model: GraphModule):
1130
+ """ Modified the graph of the model inplace, to skip extra dequantize op before
1131
+ the general tensor shape ops when possible
1132
+ """
1133
+ for n in model.graph.nodes:
1134
+ if not is_get_tensor_info_node(n):
1135
+ continue
1136
+ maybe_dq = n.args[0]
1137
+ if maybe_dq.op != "call_method" or maybe_dq.target != "dequantize":
1138
+ continue
1139
+ # skip the dequantize node
1140
+ args = list(n.args)
1141
+ args[0] = n.args[0].args[0]
1142
+ n.args = tuple(args)
1143
+
1144
+ def _lower_to_native_backend(
1145
+ model: GraphModule,
1146
+ qconfig_map: Dict[str, QConfigAny],
1147
+ node_name_to_scope: Dict[str, Tuple[str, type]]
1148
+ ) -> GraphModule:
1149
+ """ Lower a quantized reference model (with reference quantized operator patterns)
1150
+ to the native backend in PyTorch (fbgemm/qnnpack), both backends shares the same
1151
+ operator signature so they can be lowered with the same function
1152
+ """
1153
+ _lower_static_weighted_ref_module(model, qconfig_map)
1154
+ _lower_static_weighted_ref_module_with_two_inputs(model, qconfig_map)
1155
+ _lower_dynamic_weighted_ref_module(model)
1156
+ _lower_weight_only_weighted_ref_module(model)
1157
+ _lower_static_weighted_ref_functional(model, qconfig_map)
1158
+ _lower_dynamic_weighted_ref_functional(model, qconfig_map)
1159
+ _lower_quantized_binary_op(model, qconfig_map)
1160
+ _lower_getattr_tensor_metadta_op(model)
1161
+ _lower_get_tensor_info_op(model)
1162
+ special_pattern_replacement(model)
1163
+ model.graph.eliminate_dead_code()
1164
+ model = fold_weight(model, node_name_to_scope)
1165
+ model.graph.eliminate_dead_code()
1166
+ model.recompile()
1167
+ model.graph.lint()
1168
+ return model
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_model_report/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (195 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_model_report/__pycache__/detector.cpython-310.pyc ADDED
Binary file (49.2 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_model_report/__pycache__/model_report_observer.cpython-310.pyc ADDED
Binary file (7.69 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_model_report/__pycache__/model_report_visualizer.cpython-310.pyc ADDED
Binary file (23.1 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/_model_report/detector.py ADDED
@@ -0,0 +1,1539 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Set, Tuple, Callable, List
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.ao.nn.qat as nnqat
6
+ from abc import ABC, abstractmethod
7
+ from torch.ao.quantization.fake_quantize import FakeQuantize
8
+ from torch.ao.quantization.fx.graph_module import GraphModule
9
+ from torch.ao.quantization.fx._model_report.model_report_observer import ModelReportObserver
10
+ from torch.ao.quantization.qconfig import (
11
+ QConfig,
12
+ default_qconfig,
13
+ _assert_valid_qconfig,
14
+ )
15
+ from torch.ao.quantization.observer import (
16
+ ObserverBase,
17
+ default_dynamic_quant_observer,
18
+ default_per_channel_weight_observer,
19
+ default_observer,
20
+ default_weight_observer,
21
+ )
22
+ from torch.ao.quantization.fx._equalize import (
23
+ default_equalization_qconfig,
24
+ EqualizationQConfig,
25
+ )
26
+ from torch.ao.quantization.observer import _is_activation_post_process
27
+
28
+ # Names for observer insert keys
29
+ DETECTOR_TARGET_NODE_KEY = "target_node"
30
+ DETECTOR_OBS_TO_INSERT_KEY = "observer_to_insert"
31
+ DETECTOR_IS_POST_OBS_KEY = "is_post_observer"
32
+ DETECTOR_OBS_ARGS_KEY = "observer_args"
33
+
34
+ # Mapping related code
35
+ class DetectorQConfigInfo:
36
+ r"""
37
+ This class contains the QConfig information for a single module.
38
+ The list of variables / values this contains can grow depending on the
39
+ extensibility of the qconfig mapping feature set but this currently includes:
40
+ - if activation observer is dynamic
41
+ - if weight observer is per channel
42
+
43
+
44
+ Args:
45
+ module_fqn (str): The fully qualified name (fqn) of the module that this
46
+ information contains info relevant to qconfig for
47
+ """
48
+
49
+ def __init__(self, module_fqn: str):
50
+ super().__init__()
51
+ self.module_fqn = module_fqn
52
+
53
+ # populate this section with all the variables we might find important
54
+ # change from none if your detector is actually using this
55
+ self.is_activation_dynamic = False
56
+ self.is_weight_per_channel = False
57
+
58
+ # equalization related options
59
+ self.is_equalization_recommended = False
60
+
61
+ def generate_quantization_qconfig(self, module: torch.nn.Module) -> QConfig:
62
+ r"""
63
+ Args:
64
+ module (torch.nn.Module) The module we are generating
65
+ the qconfig for
66
+
67
+ Returns the generated quantization QConfig according to what a valid configuration is
68
+ """
69
+ # Apply suggestions to new qconfig
70
+ module_qconfig = default_qconfig
71
+
72
+ # keep track of dynamic and per_channel recommendations
73
+ recommendations_list = []
74
+ # append as if a list of combinations
75
+ recommendations_list.append((self.is_activation_dynamic, self.is_weight_per_channel))
76
+ recommendations_list.append((self.is_activation_dynamic, False)) # only trying dynamic rec
77
+ recommendations_list.append((False, self.is_weight_per_channel)) # only trying dynamic
78
+
79
+ # now we try each of the combinations
80
+ for rec in recommendations_list:
81
+ # rec[0] -> dynamic recommended
82
+ # rec[1] -> per channel recommended
83
+ activation = default_dynamic_quant_observer if rec[0] else default_observer
84
+ weight = default_per_channel_weight_observer if rec[1] else default_weight_observer
85
+ test_config = QConfig(activation, weight)
86
+ try:
87
+ _assert_valid_qconfig(test_config, module)
88
+ module_qconfig = test_config
89
+ break
90
+ except AssertionError:
91
+ # if not a valid configuration, we move on to the next one in priority
92
+ continue
93
+
94
+ # return the QConfig chosen
95
+ return module_qconfig
96
+
97
+ def generate_equalization_qconfig(self) -> EqualizationQConfig:
98
+ r"""
99
+ This returns the equalization configuration for a module.
100
+
101
+ For now, it just returns the default, but as more equalization options become
102
+ possible, this method can get more fleshed out with more nuanced granularity.
103
+
104
+
105
+ Returns the generated equalization QConfig according to what a valid configuration is
106
+ """
107
+ # in this case, we just return default equalization config
108
+ # we know this is valid because only valid modules would even
109
+ # have this option
110
+ return default_equalization_qconfig
111
+
112
+ # Adding base class for detectors
113
+ class DetectorBase(ABC):
114
+ r""" Base Detector Module
115
+ Any detector class should derive from this class.
116
+
117
+ Concrete detectors should follow the same general API, which includes:
118
+ - A method to calculate and return observer insertion points
119
+ - Should return both the fqns and the Observer class to insert
120
+ - A method to return a report based on the detector
121
+ - Should return a str-based report and dict info in Tuple[str,Dict] format
122
+ """
123
+
124
+ def __init__(self):
125
+ super().__init__()
126
+ self.detector_config_info = None
127
+
128
+ @abstractmethod
129
+ def determine_observer_insert_points(self, model) -> Dict:
130
+ r"""
131
+ Args
132
+ model (nn.Module or subclass): model to find observer insertion points
133
+
134
+ Returns a Dict mapping from unique observer fqns (where we want to insert them) to a Dict.
135
+ This dict maps string keys to detector specific information
136
+ """
137
+ pass
138
+
139
+ @abstractmethod
140
+ def get_detector_name(self) -> str:
141
+ r""" Returns the name of the current detector """
142
+ pass
143
+
144
+
145
+ @abstractmethod
146
+ def get_qconfig_info(self, model) -> Dict[str, DetectorQConfigInfo]:
147
+ r""" Returns the DetectorQConfigInfo for each module_fqn relevant
148
+ Args
149
+ model (nn.Module or subclass): model to find observer insertion points
150
+
151
+ Returns a Dict mapping from unique observer fqns (where we want to insert them) to:
152
+ A DetectorQConfigInfo with the information to generate a QConfig for a specific module
153
+ """
154
+ pass
155
+
156
+ def _get_targeting_node(self, prepared_fx_model: GraphModule, target_fqn: str) -> torch.fx.node.Node:
157
+ r"""
158
+ Takes in a GraphModule and the target_fqn and finds the node whose target is this fqn.
159
+
160
+ If it's not found, it means it is most likely inside a fused layer
161
+ We just go one layer up in terms of the fqn we are searching for until we find parent node
162
+ If we get to empty string, then we know that it doesn't exist
163
+
164
+ The reason for the recursion is that if the model that we are looking for got fused,
165
+ we will have module fqn as e.g. x.linear.0 but the graph will only have a node for the fused module,
166
+ which would have fqn as x.linear so they will not match.
167
+ To handle this, if we don't match, we then take off the last bit of the fqn e.g. x.linear.0 -> x.linear,
168
+ or more generally foo.bar.baz -> foo.bar and search again, this will allow us to locate the correct module
169
+ even in cases with fusion
170
+
171
+ Args:
172
+ prepared_fx_model (GraphModule): The prepared Fx GraphModule
173
+ target_fqn (str): The fqn of the layer we are trying to target
174
+
175
+ Returns the node object we are trying to add observers around
176
+ """
177
+ for node in prepared_fx_model.graph.nodes:
178
+ # if the node's target is our target, return it
179
+ if node.target == target_fqn:
180
+ return node
181
+
182
+ # getting here means node not found
183
+ # if no "." we are already at base and failed
184
+ parent_fqn_sep_index = target_fqn.rfind(".")
185
+ if parent_fqn_sep_index == -1:
186
+ raise ValueError("passed in target_fqn not found in graph's targets.")
187
+ else:
188
+ # recursively call it with parent fqn
189
+ return self._get_targeting_node(prepared_fx_model, target_fqn[:parent_fqn_sep_index])
190
+
191
+ @abstractmethod
192
+ def generate_detector_report(self, model) -> Tuple[str, Dict[str, Any]]:
193
+ r"""
194
+ Args
195
+ model (nn.Module or subclass): model to find observer insertion points
196
+
197
+ Returns a Tuple of two elements:
198
+ Str: string report of the suggested improvements
199
+ Dict: contains useful data collected by the observer pertinent to this report
200
+ """
201
+ pass
202
+
203
+ class PerChannelDetector(DetectorBase):
204
+ r""" This class is used to detect if any Linear or Conv layers in a model utilize per_channel quantization.
205
+ Only Linear and Conv layers can use per_channel as of now so only these two are currently checked.
206
+
207
+ per_channel quantization can lead to major benefits in the form of accuracy.
208
+ Therefore, if the backend used by the user supports it, it is recommended to use
209
+
210
+ Args:
211
+ backend (str, optional): the backend the user wishes to use in production
212
+ Default value is current torch.backends.quantized.engine
213
+ """
214
+
215
+ # Keys for return dictionary
216
+ BACKEND_KEY = "backend"
217
+ PER_CHAN_SUPPORTED_KEY = "per_channel_quantization_supported"
218
+ PER_CHAN_USED_KEY = "per_channel_quantization_used"
219
+
220
+ # Default map for representing supported per channel quantization modules for different backends
221
+ DEFAULT_BACKEND_PER_CHANNEL_SUPPORTED_MODULES: Dict[str, Set[Any]] = {
222
+ "fbgemm": {nn.Linear, nn.Conv1d, nn.Conv2d, nn.Conv3d, nnqat.Linear, nnqat.Conv1d, nnqat.Conv2d, nnqat.Conv3d},
223
+ "qnnpack": {nn.Linear, nn.Conv1d, nn.Conv2d, nn.Conv3d, nnqat.Linear, nnqat.Conv1d, nnqat.Conv2d, nnqat.Conv3d},
224
+ "onednn": {nn.Linear, nn.Conv1d, nn.Conv2d, nn.Conv3d, nnqat.Linear, nnqat.Conv1d, nnqat.Conv2d, nnqat.Conv3d},
225
+ "x86": {nn.Linear, nn.Conv1d, nn.Conv2d, nn.Conv3d, nnqat.Linear, nnqat.Conv1d, nnqat.Conv2d, nnqat.Conv3d},
226
+ }
227
+
228
+ def __init__(self, backend: str = torch.backends.quantized.engine):
229
+ super().__init__()
230
+
231
+ # store the backend information
232
+ self.backend_chosen = backend
233
+ self.supported_modules = set()
234
+ if self.backend_chosen in self.DEFAULT_BACKEND_PER_CHANNEL_SUPPORTED_MODULES:
235
+ self.supported_modules = self.DEFAULT_BACKEND_PER_CHANNEL_SUPPORTED_MODULES[self.backend_chosen]
236
+ else:
237
+ raise ValueError(f"Not configured to work with {self.backend_chosen}. Try a different default backend")
238
+
239
+ def get_detector_name(self) -> str:
240
+ r""" returns the string name of this detector"""
241
+ return "per_channel_detector"
242
+
243
+ def get_qconfig_info(self, model) -> Dict[str, DetectorQConfigInfo]:
244
+ r""" Returns the DetectorQConfigInfo for each module_fqn relevant
245
+ Args
246
+ model (nn.Module or subclass): model to find observer insertion points
247
+
248
+ Returns a Dict mapping from unique observer fqns (where we want to insert them) to:
249
+ A DetectorQConfigInfo with the information to generate a QConfig for a specific module
250
+ """
251
+ # run the helper function to populate the dictionary
252
+ per_channel_info = self._detect_per_channel_helper(model)
253
+
254
+ # we actually have a qconfig info object we are populating
255
+ module_fqn_to_detector_qconfig_info = {}
256
+
257
+ for module_fqn in per_channel_info:
258
+ # create a detector info instance
259
+ detector_qconfig_info = DetectorQConfigInfo(module_fqn)
260
+
261
+ # see if per channel quantization is supported
262
+ per_chan_supported: bool = per_channel_info[module_fqn][self.PER_CHAN_SUPPORTED_KEY]
263
+ detector_qconfig_info.is_weight_per_channel = per_chan_supported
264
+ module_fqn_to_detector_qconfig_info[module_fqn] = detector_qconfig_info
265
+
266
+ return module_fqn_to_detector_qconfig_info
267
+
268
+ def determine_observer_insert_points(self, model: nn.Module) -> Dict:
269
+ r"""
270
+ There is no observers inserted for the PerChannelDetector.
271
+
272
+ Returns an empty dictionary since no observers are added or needed
273
+ """
274
+ return {}
275
+
276
+
277
+ def _detect_per_channel_helper(self, model: nn.Module):
278
+ r"""
279
+ determines if per_channel quantization is supported in modules and submodules.
280
+
281
+ Returns a dictionary in the higher level _detect_per_channel function.
282
+ Each entry maps the fully-qualified-name to information on whether per_channel quantization.
283
+
284
+ Args:
285
+ model: The current module that is being checked to see if it is per_channel quantizable
286
+
287
+ Returns dictionary mapping fqns to if per_channel quantization is possible
288
+ """
289
+ # create dict we will return
290
+ per_channel_info: Dict = {}
291
+
292
+ # get the fully qualified name and check if in list of modules to include and list of modules to ignore
293
+ for fqn, module in model.named_modules():
294
+
295
+ is_in_include_list = sum([isinstance(module, x) for x in self.supported_modules]) > 0
296
+
297
+ # check if the module per_channel is supported
298
+ # based on backend
299
+ per_channel_supported = False
300
+
301
+ if is_in_include_list:
302
+ per_channel_supported = True
303
+
304
+ # assert statement for MyPy
305
+ q_config_file = module.qconfig
306
+ assert isinstance(q_config_file, QConfig)
307
+
308
+ # this object should either be fake quant or observer
309
+ q_or_s_obj = module.qconfig.weight.p.func()
310
+ assert isinstance(q_or_s_obj, (FakeQuantize, ObserverBase))
311
+
312
+ per_channel_used = False # will be true if found in qconfig
313
+
314
+ if hasattr(q_or_s_obj, "ch_axis"): # then we know that per_channel quantization used
315
+
316
+ # all fake quants have channel axis so need to check is_per_channel
317
+ if isinstance(q_or_s_obj, FakeQuantize):
318
+ if hasattr(q_or_s_obj, "is_per_channel") and q_or_s_obj.is_per_channel:
319
+ per_channel_used = True
320
+ elif isinstance(q_or_s_obj, ObserverBase):
321
+ # should be an observer otherwise
322
+ per_channel_used = True
323
+ else:
324
+ raise ValueError("Should be either observer or fake quant")
325
+
326
+ per_channel_info[fqn] = {
327
+ self.PER_CHAN_SUPPORTED_KEY: per_channel_supported,
328
+ self.PER_CHAN_USED_KEY: per_channel_used,
329
+ self.BACKEND_KEY: self.backend_chosen
330
+ }
331
+
332
+ return per_channel_info
333
+
334
+ def generate_detector_report(self, model: nn.Module) -> Tuple[str, Dict[str, Any]]:
335
+ r"""Checks if any Linear or Conv layers in the model utilize per_channel quantization.
336
+ Only Linear and Conv layers can use per_channel as of now so only these two are currently checked.
337
+
338
+ Looks at q_config format and backend to determine if per_channel can be utilized.
339
+ Uses the DEFAULT_BACKEND_PER_CHANNEL_SUPPORTED_MODULES structure to determine support
340
+
341
+ Args:
342
+ model: The prepared and calibrated model we want to check if using per_channel
343
+
344
+ Returns a tuple with two elements:
345
+ String report of potential actions to improve model (if per_channel quantization is available in backend)
346
+ Dictionary mapping per_channel quantizable elements to:
347
+ whether per_channel quantization is supported by the backend
348
+ if it is being utilized in the current model
349
+ """
350
+
351
+ # run the helper function to populate the dictionary
352
+ per_channel_info = self._detect_per_channel_helper(model)
353
+
354
+ # String to let the user know of further optimizations
355
+ further_optims_str = f"Further Optimizations for backend {self.backend_chosen}: \n"
356
+
357
+ optimizations_possible = False
358
+ for fqn in per_channel_info:
359
+ fqn_dict = per_channel_info[fqn]
360
+ if fqn_dict[self.PER_CHAN_SUPPORTED_KEY] and not fqn_dict[self.PER_CHAN_USED_KEY]:
361
+ optimizations_possible = True
362
+ further_optims_str += f"Module {fqn} can be configured to use per_channel quantization.\n"
363
+
364
+ if optimizations_possible:
365
+ further_optims_str += (
366
+ "To use per_channel quantization, make sure the qconfig has a per_channel weight observer."
367
+ )
368
+ else:
369
+ further_optims_str += "No further per_channel optimizations possible."
370
+
371
+ # return the string and the dictionary form of same information
372
+ return (further_optims_str, per_channel_info)
373
+
374
+
375
+ class DynamicStaticDetector(DetectorBase):
376
+ r"""
377
+ Determines whether dynamic or static quantization is more appropriate for a given module.
378
+
379
+ Takes advantage of the ModelReportObserver that records range information.
380
+ Stationary distribution of data are strictly above tolerance level for the comparison statistic:
381
+
382
+ S = average_batch_activation_range/epoch_activation_range
383
+
384
+ Nonstationary distributions are below or at the tolerance level for this metric.
385
+
386
+ If the distribution of data right after the module is non-stationary, recommend dynamic quantization
387
+ Otherwise recommend static quantization
388
+
389
+ Args:
390
+ tolerance (float, optional): The threshold where S metric is stationary above and non-stationary otherwise. Default: 0.5
391
+ """
392
+ # names for the pre and post observers that are inserted
393
+ DEFAULT_PRE_OBSERVER_NAME = "model_report_pre_observer"
394
+ DEFAULT_POST_OBSERVER_NAME = "model_report_post_observer"
395
+
396
+ # naming conventions for stationary vs non-stationary data
397
+ STATIONARY_STR = "stationary"
398
+ NON_STATIONARY_STR = "non-stationary"
399
+
400
+ # naming for activation
401
+ INPUT_ACTIVATION_PREFIX = "input_activation_"
402
+ OUTPUT_ACTIVATION_PREFIX = "output_activation_"
403
+
404
+ # naming conventions for the keys of the return module info
405
+ TOLERANCE_KEY = "dynamic_static_tolerance"
406
+ DEFAULT_DYNAMIC_REC_KEY = "dynamic_recommended"
407
+ PRE_OBS_COMP_STAT_KEY = INPUT_ACTIVATION_PREFIX + "dynamic_static_comp_stat"
408
+ POST_OBS_COMP_STAT_KEY = OUTPUT_ACTIVATION_PREFIX + "dynamic_static_comp_stat"
409
+ PRE_OBS_DATA_DIST_KEY = INPUT_ACTIVATION_PREFIX + "dynamic_static_data_classification"
410
+ POST_OBS_DATA_DIST_KEY = OUTPUT_ACTIVATION_PREFIX + "dynamic_static_data_classification"
411
+ IS_CURRENTLY_SUPPORTED_KEY = "is_dynamic_supported"
412
+
413
+ # modules that are supported both dynamic and static for this report function
414
+ DEFAULT_DYNAMIC_STATIC_CHECK_SUPPORTED = {nn.Linear}
415
+
416
+ # modules that will be supported soon for both
417
+ DEFAULT_DYNAMIC_STATIC_FUTURE_SUPPORTED = {nn.Conv1d, nn.Conv2d, nn.Conv3d}
418
+
419
+ def __init__(self, tolerance=0.5):
420
+ super().__init__()
421
+
422
+ # set tolerance level and initialize a set to keep track of useful fqn locations
423
+ self.tolerance = tolerance
424
+ self.useful_observer_fqns: Set[str] = set()
425
+
426
+ def determine_observer_insert_points(self, prepared_fx_model: GraphModule) -> Dict[str, Dict[str, Any]]:
427
+ r"""
428
+ Determines where observers need to be inserted for the Dynamic vs Static detector.
429
+ For this detector, we want to place observers on either side of linear layers in the model.
430
+
431
+ Currently inserts observers for:
432
+ linear layers
433
+
434
+ Args:
435
+ prepared_fx_model (GraphModule): The prepared Fx GraphModule
436
+
437
+ Returns a Dict mapping from unique observer fqns (where we want to insert them) to a Dict with:
438
+ key "target_node" -> the node we are trying to observe with this observer (torch.fx.node.Node)
439
+ key "observer_to_insert" -> the observer we wish to insert (ObserverBase)
440
+ key "is_post_observer" -> True if this is meant to be a post-observer for target_node, False if pre-observer
441
+ key "observer_args" -> The arguments that are meant to be passed into the observer
442
+ """
443
+
444
+ # observer for this detector is ModelReportObserver
445
+ obs_ctr = ModelReportObserver
446
+
447
+ # return dict
448
+ obs_fqn_to_info: Dict[str, Dict[str, Any]] = {}
449
+
450
+ for fqn, module in prepared_fx_model.named_modules():
451
+ # make sure module is supported
452
+ if self._is_supported(module, insert=True):
453
+ # if it's a supported type, we want to get node and add observer insert locations
454
+ targeted_node = self._get_targeting_node(prepared_fx_model, fqn)
455
+
456
+ # add entry for pre-observer
457
+ pre_obs_fqn = fqn + "." + self.DEFAULT_PRE_OBSERVER_NAME
458
+
459
+ obs_fqn_to_info[pre_obs_fqn] = {
460
+ DETECTOR_TARGET_NODE_KEY: targeted_node,
461
+ DETECTOR_OBS_TO_INSERT_KEY: obs_ctr(),
462
+ DETECTOR_IS_POST_OBS_KEY: False,
463
+ DETECTOR_OBS_ARGS_KEY: targeted_node.args
464
+ }
465
+
466
+ # add entry for post-observer
467
+ post_obs_fqn = fqn + "." + self.DEFAULT_POST_OBSERVER_NAME
468
+
469
+ obs_fqn_to_info[post_obs_fqn] = {
470
+ DETECTOR_TARGET_NODE_KEY: targeted_node,
471
+ DETECTOR_OBS_TO_INSERT_KEY: obs_ctr(),
472
+ DETECTOR_IS_POST_OBS_KEY: True,
473
+ DETECTOR_OBS_ARGS_KEY: (targeted_node,)
474
+ }
475
+
476
+ return obs_fqn_to_info
477
+
478
+ def get_detector_name(self) -> str:
479
+ r""" returns the string name of this detector"""
480
+ return "dynamic_vs_static_detector"
481
+
482
+
483
+ def get_qconfig_info(self, model) -> Dict[str, DetectorQConfigInfo]:
484
+ r""" Returns the DetectorQConfigInfo for each module_fqn relevant
485
+ Args
486
+ model (nn.Module or subclass): model to find observer insertion points
487
+
488
+ Returns a Dict mapping from unique observer fqns (where we want to insert them) to:
489
+ A DetectorQConfigInfo with the information to generate a QConfig for a specific module
490
+ """
491
+ # run the helper function to populate the dictionary
492
+ dynamic_static_info = self._generate_dict_info(model)
493
+
494
+ # we actually have a qconfig info object we are populating
495
+ module_fqn_to_detector_qconfig_info = {}
496
+
497
+ for module_fqn in dynamic_static_info:
498
+ # create a detector info instance
499
+ detector_qconfig_info = DetectorQConfigInfo(module_fqn)
500
+
501
+ # see if per channel quantization is supported
502
+ dynamic_static_recommended: bool = dynamic_static_info[module_fqn][self.DEFAULT_DYNAMIC_REC_KEY]
503
+ detector_qconfig_info.is_activation_dynamic = dynamic_static_recommended
504
+ module_fqn_to_detector_qconfig_info[module_fqn] = detector_qconfig_info
505
+
506
+ return module_fqn_to_detector_qconfig_info
507
+
508
+ def _is_supported(self, module: nn.Module, insert: bool = False) -> bool:
509
+ r"""Returns whether the given module is supported for observers
510
+
511
+ Args
512
+ module: The module to check and ensure is supported
513
+ insert: True if this is check for observer insertion, false if for report gen
514
+
515
+ Returns True if the module is supported by observer, False otherwise
516
+ """
517
+ # check to see if module is of a supported type
518
+ is_supported_type = sum([isinstance(module, x) for x in self.DEFAULT_DYNAMIC_STATIC_CHECK_SUPPORTED]) > 0
519
+
520
+ # check if it will be supported
521
+ future_supported_type = sum([isinstance(module, x) for x in self.DEFAULT_DYNAMIC_STATIC_FUTURE_SUPPORTED]) > 0
522
+
523
+ # supported
524
+ supported = is_supported_type or future_supported_type
525
+
526
+ # this is check for observer insertion
527
+ if insert:
528
+ return supported
529
+ else:
530
+ # this is for report gen and we also need to check if it contains observers
531
+ has_obs = hasattr(module, self.DEFAULT_PRE_OBSERVER_NAME) and hasattr(module, self.DEFAULT_POST_OBSERVER_NAME)
532
+ return supported and has_obs
533
+
534
+ def _generate_dict_info(self, model: GraphModule) -> Dict[str, Any]:
535
+ r"""
536
+ Helper function for generate_detector_report that does the generation of the dictionary.
537
+ This process is done as specified in generate_detector_report documentation
538
+
539
+ Args:
540
+ model (GraphModule): The prepared and calibrated GraphModule with inserted ModelReportObservers
541
+
542
+ Returns a Dictionary mapping modules with ModelReportObservers around them to:
543
+ whether dynamic quantization is recommended
544
+ their S metric of input to module
545
+ whether input to module is stationary or non-stationary
546
+ their S metric of output of module
547
+ whether output of module is stationary or non-stationary
548
+ the tolerance level to decided whether input/output is stationary or non-stationary
549
+ whether it is currently supported or planned for the future
550
+ """
551
+ # store modules dynamic vs static information
552
+ module_dynamic_static_info = {}
553
+
554
+ # This for loop goes through the modules, and extracts all relevant information into module_dynamic_static_info
555
+ # This information primary includes whether the data distributions around a supported module is stationary or not
556
+ # Based on this, it is recorded whether dynamic or static quantization is recommended
557
+
558
+ # loop through all submodules included nested ones
559
+ for fqn, module in model.named_modules():
560
+ # if module is Linear has the ModelReportObserver attached to it
561
+ if self._is_supported(module):
562
+ # get pre and post observers for the module
563
+ pre_obs = getattr(module, self.DEFAULT_PRE_OBSERVER_NAME)
564
+ post_obs = getattr(module, self.DEFAULT_POST_OBSERVER_NAME)
565
+
566
+ # get the statistics for each module
567
+ pre_stat = pre_obs.get_batch_to_epoch_ratio()
568
+ post_stat = post_obs.get_batch_to_epoch_ratio()
569
+
570
+ # record module, pre and post stat, and whether to do dynamic or static based off it
571
+ # true if post observer data distribution is non-stationary, false if it's stationary
572
+ dynamic_recommended = post_stat <= self.tolerance
573
+
574
+ # specify the classifications for whether data distributions considered stationary or non-stationary
575
+ pre_obs_dist_classif = self.STATIONARY_STR if pre_stat > self.tolerance else self.NON_STATIONARY_STR
576
+ post_obs_dist_classif = self.STATIONARY_STR if post_stat > self.tolerance else self.NON_STATIONARY_STR
577
+
578
+ # check if current support or future support
579
+ is_supported_type = sum([isinstance(module, x) for x in self.DEFAULT_DYNAMIC_STATIC_CHECK_SUPPORTED]) > 0
580
+
581
+ # store the set of important information for this module
582
+ module_info = {
583
+ self.TOLERANCE_KEY: self.tolerance,
584
+ self.DEFAULT_DYNAMIC_REC_KEY: dynamic_recommended,
585
+ self.PRE_OBS_COMP_STAT_KEY: pre_stat,
586
+ self.PRE_OBS_DATA_DIST_KEY: pre_obs_dist_classif,
587
+ self.POST_OBS_COMP_STAT_KEY: post_stat,
588
+ self.POST_OBS_DATA_DIST_KEY: post_obs_dist_classif,
589
+ self.IS_CURRENTLY_SUPPORTED_KEY: is_supported_type,
590
+ }
591
+
592
+ module_dynamic_static_info[fqn] = module_info
593
+
594
+ return module_dynamic_static_info
595
+
596
+ def generate_detector_report(self, model: GraphModule) -> Tuple[str, Dict[str, Any]]:
597
+ r"""
598
+ Determines whether dynamic or static quantization is more appropriate for a given module.
599
+
600
+ Takes advantage of the ModelReportObserver that records range information.
601
+ Stationary distribution of data are strictly above tolerance level for the comparison statistic:
602
+
603
+ S = average_batch_activation_range/epoch_activation_range
604
+
605
+ Nonstationary distributions are below or at the tolerance level for this metric.
606
+
607
+ If the distribution of data right after the module is non-stationary, recommend dynamic quantization
608
+ Otherwise recommend static quantization
609
+
610
+ This will then generate suggestions for dynamic vs static quantization focused around Linear.
611
+
612
+ Args:
613
+ model (GraphModule): The prepared and calibrated GraphModule with inserted ModelReportObservers
614
+
615
+ Returns a tuple with two elements:
616
+ String report of of whether dynamic or static quantization is recommended for certain modules
617
+ Dictionary mapping modules with ModelReportObservers around them to:
618
+ whether dynamic quantization is recommended
619
+ their S metric of input to module
620
+ whether input to module is stationary or non-stationary
621
+ their S metric of output of module
622
+ whether output of module is stationary or non-stationary
623
+ the tolerance level to decided whether input/output is stationary or non-stationary
624
+ whether it is currently supported or planned for the future
625
+ """
626
+
627
+ # get the dictionary of the information to format the string report
628
+ module_dynamic_static_info = self._generate_dict_info(model)
629
+
630
+ dynamic_vs_static_string = "Dynamic vs. Static Quantization suggestions: \n"
631
+
632
+ modules_added: bool = False # check to make sure at least 1 module added.
633
+
634
+ dynamic_benefit = " You will get more accurate results if you use dynamic quantization"
635
+ static_benefit = " You can increase model efficiency if you use static quantization"
636
+ future_support_str = ". This layer is not yet supported for dynamic quantization"
637
+ # This for loop goes through the information collected in module_dynamic_static_info and:
638
+ # Populates the string based report with the information from module_dynamic_static_info
639
+ # Compiles the complete report by appending relevant formatted strings
640
+
641
+ for module_fqn in module_dynamic_static_info.keys():
642
+
643
+ # there is at least 1 module for suggestion
644
+ modules_added = True
645
+ module_info = module_dynamic_static_info[module_fqn]
646
+ suggestion_string_template = "For module {} it is suggested to use {} quantization because {}.\n"
647
+
648
+ # decide what string formatting values will be
649
+ quantization_type = ""
650
+ quantization_reasoning = "the distribution of data before {} is {} and the distribution after is {}."
651
+
652
+ benefit_str = ""
653
+
654
+ # strings for if dynamic quantized per tensor is needed
655
+ recommend_per_tensor = ". We recommend to add a {} before this module if it is static."
656
+ rec_lay_to_add = "dynamic quantize per tensor layer"
657
+ dynamic_per_tensor_string = recommend_per_tensor.format(rec_lay_to_add)
658
+ dynamic_per_tensor_reasoning_string = (
659
+ " This is because the input to this module has a non-stationary distribution"
660
+ )
661
+
662
+ # start composing explanation
663
+ if module_info[self.DEFAULT_DYNAMIC_REC_KEY]:
664
+ quantization_type = "dynamic"
665
+ # check if currently supported or future supported
666
+ benefit_str = dynamic_benefit
667
+ if not module_info[self.IS_CURRENTLY_SUPPORTED_KEY]:
668
+ benefit_str += future_support_str
669
+ else:
670
+ quantization_type = "static"
671
+ benefit_str = static_benefit
672
+
673
+ # now set the quantization explanation string
674
+ quantization_reasoning = (
675
+ quantization_reasoning.format(
676
+ module_fqn, module_info[self.PRE_OBS_DATA_DIST_KEY], module_info[self.POST_OBS_DATA_DIST_KEY]
677
+ )
678
+ + benefit_str
679
+ )
680
+
681
+ # if we have a non-stationary input -> linear -> stationary we suggested static
682
+ # however, we want to also recommend they add a dynamic quantize per tensor right if this change is made
683
+ if (
684
+ module_info[self.PRE_OBS_DATA_DIST_KEY] == self.NON_STATIONARY_STR
685
+ and module_info[self.POST_OBS_DATA_DIST_KEY] == self.STATIONARY_STR
686
+ ):
687
+ quantization_reasoning = (
688
+ quantization_reasoning + dynamic_per_tensor_string + dynamic_per_tensor_reasoning_string
689
+ )
690
+
691
+ # format the overall suggestion string with the specific inputs
692
+ module_suggestion_string = suggestion_string_template.format(
693
+ module_fqn, quantization_type, quantization_reasoning
694
+ )
695
+
696
+ # append to overall suggestion
697
+ dynamic_vs_static_string += module_suggestion_string
698
+
699
+ if not modules_added:
700
+ dynamic_vs_static_string += "No applicable layers for suggestions. Only linear and conv are valid.\n"
701
+
702
+ # return the string as well as the dictionary of information
703
+ return (dynamic_vs_static_string, module_dynamic_static_info)
704
+
705
+
706
+ class InputWeightEqualizationDetector(DetectorBase):
707
+ r"""
708
+ Determines whether input-weight equalization can help improve quantization for certain modules.
709
+
710
+ Specifically, this list of modules includes:
711
+ linear
712
+ conv
713
+
714
+ Determines whether input-weight equalization is recommended based on the comp stat:
715
+ s_c = sqrt(w_c/W)/sqrt(i_c/I)
716
+ where:
717
+ w_c is range of weight for channel c, W is range of weight over all channels
718
+ i_c is range of input for channel c, I is range of input over all channels
719
+
720
+ if s_c >= threshold or <= 1 / threshold, recommends input-weight equalization
721
+
722
+ Args:
723
+ ratio_threshold (float): The threshold for s_c to determine if input-weight equalization is suggested
724
+ Should be between 0 and 1 (both non-inclusive)
725
+ ch_axis (int, optional): The channel axis being observed to determine input weight equalization
726
+ Default: 1
727
+
728
+ * :attr:`ratio_threshold`: The threshold for s_c to determine if input-weight equalization is suggested
729
+ Should be between 0 and 1
730
+
731
+ * :attr:`ch_axis`: The channel axis being observed to determine input weight equalization
732
+
733
+ * :attr:`SUPPORTED_MODULES`: This specifies the modules that are supported for input-weight equalization
734
+
735
+ * :attr:`DEFAULT_PRE_OBSERVER_NAME`: The name of the pre-observer to be inserted for this detector
736
+ """
737
+
738
+ SUPPORTED_MODULES: Set[Callable] = {nn.Linear,
739
+ nn.Conv1d,
740
+ nn.Conv2d,
741
+ nn.Conv3d,
742
+ nnqat.Linear,
743
+ nnqat.Conv1d,
744
+ nnqat.Conv2d,
745
+ nnqat.Conv3d}
746
+
747
+ # names for the pre and post observers that are inserted
748
+ DEFAULT_PRE_OBSERVER_NAME: str = "model_report_pre_observer"
749
+
750
+ # weight / activation prefix for each of the below info
751
+ WEIGHT_PREFIX = "weight_"
752
+ ACTIVATION_PREFIX = "input_activation_"
753
+
754
+ # string names for keys of info dictionaries
755
+ PER_CHANNEL_MAX_KEY = "per_channel_max"
756
+ PER_CHANNEL_MIN_KEY = "per_channel_min"
757
+ GLOBAL_MAX_KEY = "global_max"
758
+ GLOBAL_MIN_KEY = "global_min"
759
+
760
+ # keys for return dict of recommendations
761
+ RECOMMENDED_KEY = "input_weight_equalization_recommended"
762
+ COMP_METRIC_KEY = "input_weight_channel_comparison_metrics"
763
+ THRESHOLD_KEY = "input_weight_threshold"
764
+ CHANNEL_KEY = "input_weight_channel_axis"
765
+
766
+ # default weight and info strings
767
+ WEIGHT_STR = "weight"
768
+ INPUT_STR = "input"
769
+
770
+ # default for what ratio we recommend input weight
771
+ DEFAULT_RECOMMEND_INPUT_WEIGHT_CHANNEL_RATIO = 0.4
772
+
773
+ def __init__(self, ratio_threshold: float, ch_axis: int = 1):
774
+ # ensure passed in inputs are valid
775
+ if ratio_threshold <= 0 or ratio_threshold >= 1:
776
+ raise ValueError("Make sure threshold is > 0 and < 1")
777
+
778
+ # initialize attributes based on args
779
+ self.ratio_threshold: float = ratio_threshold
780
+ self.ch_axis: int = ch_axis
781
+
782
+ def _is_supported(self, module: nn.Module, insert: bool = False) -> bool:
783
+ r"""Returns whether the given module is supported for observers
784
+
785
+ Args
786
+ module: The module to check and ensure is supported
787
+ insert: True if this is check for observer insertion, false if for report gen
788
+
789
+ Returns True if the module is supported by observer, False otherwise
790
+ """
791
+ # check to see if module is of a supported type
792
+ is_supported_type = sum([type(module) is x for x in self.SUPPORTED_MODULES]) > 0
793
+
794
+ # this is check for observer insertion
795
+ if insert:
796
+ return is_supported_type
797
+ else:
798
+ # this is for report gen and we also need to check if it contains observers
799
+ has_obs = hasattr(module, self.DEFAULT_PRE_OBSERVER_NAME)
800
+ return is_supported_type and has_obs
801
+
802
+ def get_qconfig_info(self, model) -> Dict[str, DetectorQConfigInfo]:
803
+ r""" Returns the DetectorQConfigInfo for each module_fqn relevant
804
+ Args
805
+ model (nn.Module or subclass): model to find observer insertion points
806
+
807
+ Returns a Dict mapping from unique observer fqns (where we want to insert them) to:
808
+ A DetectorQConfigInfo with the information to generate a QConfig for a specific module
809
+ """
810
+ # run the helper function to populate the dictionary
811
+ # find the range of inputs
812
+ input_values: Dict[str, Dict] = self._extract_input_info(model)
813
+
814
+ # find the range of weights
815
+ weight_values: Dict[str, Dict] = self._extract_weight_info(model)
816
+
817
+ # calculate per_channel comparison statistic s_c
818
+ comp_stats: Dict[str, torch.Tensor] = self._generate_comparison_values(input_values, weight_values)
819
+
820
+ # generate the return dictionary
821
+ input_weight_equalization_info: Dict[str, Dict] = self._generate_dict_info(input_values, weight_values, comp_stats)
822
+
823
+ # we actually have a qconfig info object we are populating
824
+ module_fqn_to_detector_qconfig_info = {}
825
+
826
+ for module_fqn in input_weight_equalization_info:
827
+ # create a detector info instance
828
+ detector_qconfig_info = DetectorQConfigInfo(module_fqn)
829
+
830
+ # see if per channel quantization is supported
831
+ input_weight_recommended: bool = input_weight_equalization_info[module_fqn][self.RECOMMENDED_KEY]
832
+ detector_qconfig_info.is_equalization_recommended = input_weight_recommended
833
+ module_fqn_to_detector_qconfig_info[module_fqn] = detector_qconfig_info
834
+
835
+ return module_fqn_to_detector_qconfig_info
836
+
837
+ def determine_observer_insert_points(self, prepared_fx_model: GraphModule) -> Dict[str, Dict[str, Any]]:
838
+ r"""Determines where observers need to be inserted for the Input Weight Equalization Detector.
839
+ For this detector, we want to place observers in front of supported layers.
840
+
841
+ Currently inserts observers for:
842
+ linear layers
843
+ conv layers
844
+
845
+ Args:
846
+ prepared_fx_model (GraphModule): The prepared Fx GraphModule
847
+
848
+ Returns a Dict mapping from unique observer fqns (where we want to insert them) to a Dict with:
849
+ key "target_node" -> the node we are trying to observe with this observer (torch.fx.node.Node)
850
+ key "observer_to_insert" -> the observer we wish to insert (ObserverBase)
851
+ key "is_post_observer" -> True if this is meant to be a post-observer for target_node, False if pre-observer
852
+ key "observer_args" -> The arguments that are meant to be passed into the observer
853
+ """
854
+
855
+ # observer for this detector is ModelReportObserver
856
+ obs_ctr = ModelReportObserver
857
+
858
+ # return dict
859
+ obs_fqn_to_info: Dict[str, Dict[str, Any]] = {}
860
+
861
+ for fqn, module in prepared_fx_model.named_modules():
862
+ # check to see if module is of a supported type
863
+ if self._is_supported(module, insert=True):
864
+ # if it's a supported type, we want to get node and add observer insert locations
865
+ targeted_node = self._get_targeting_node(prepared_fx_model, fqn)
866
+
867
+ # add entry for pre-observer
868
+ pre_obs_fqn = fqn + "." + self.DEFAULT_PRE_OBSERVER_NAME
869
+
870
+ obs_fqn_to_info[pre_obs_fqn] = {
871
+ DETECTOR_TARGET_NODE_KEY: targeted_node,
872
+ DETECTOR_OBS_TO_INSERT_KEY: obs_ctr(ch_axis=self.ch_axis),
873
+ DETECTOR_IS_POST_OBS_KEY: False,
874
+ DETECTOR_OBS_ARGS_KEY: targeted_node.args,
875
+ }
876
+
877
+ return obs_fqn_to_info
878
+
879
+ def get_detector_name(self) -> str:
880
+ r"""Returns the name of this detector"""
881
+ return "input_weight_equalization_detector"
882
+
883
+ def _extract_input_info(self, model: GraphModule) -> Dict[str, Dict]:
884
+ r"""
885
+ Takes in a calibrated GraphModule and then finds the relevant observers.
886
+ It then extracts the input information for each observer returns it
887
+
888
+ Args
889
+ model (GraphModule): The prepared and calibrated GraphModule with inserted ModelReportObservers
890
+
891
+ Returns a dict mapping relevant module fqns (str) to a dict with keys:
892
+ "input_activation_per_channel_max" : maps to the per_channel max values
893
+ "input_activation_per_channel_min" : maps to the per_channel min values
894
+ "input_activation_global_max" : maps to the global max recorded
895
+ "input_activation_global_min" : maps to the global min recorded
896
+ """
897
+
898
+ # return dictionary mapping observer fqns to desired info
899
+ input_info: Dict[str, Dict] = {}
900
+
901
+ for fqn, module in model.named_modules():
902
+ # if module is supported and it has a pre-observer
903
+ if self._is_supported(module):
904
+ # get pre observer for the module
905
+ pre_obs = getattr(module, self.DEFAULT_PRE_OBSERVER_NAME)
906
+
907
+ input_info[fqn] = {
908
+ self.ACTIVATION_PREFIX + self.PER_CHANNEL_MAX_KEY: pre_obs.max_val,
909
+ self.ACTIVATION_PREFIX + self.PER_CHANNEL_MIN_KEY: pre_obs.min_val,
910
+ self.ACTIVATION_PREFIX + self.GLOBAL_MAX_KEY: max(pre_obs.max_val),
911
+ self.ACTIVATION_PREFIX + self.GLOBAL_MIN_KEY: min(pre_obs.min_val),
912
+ }
913
+
914
+ return input_info
915
+
916
+ def _extract_weight_info(self, model: GraphModule) -> Dict[str, Dict]:
917
+ r"""
918
+ Takes in a calibrated GraphModule and then finds the relevant observers.
919
+ It then extracts the weight information for each layer an observer is attached to.
920
+
921
+ Args
922
+ model (GraphModule): The prepared and calibrated GraphModule with inserted ModelReportObservers
923
+
924
+ Returns a dict mapping module fqns (str) to a dict with keys:
925
+ "per_channel_max" : maps to the per_channel max values
926
+ "per_channel_min" : maps to the per_channel min values
927
+ "global_max" : maps to the global max recorded
928
+ "global_min" : maps to the global min recorded
929
+ """
930
+ # return dictionary mapping observer fqns to desired info
931
+ weight_info: Dict[str, Dict] = {}
932
+
933
+ for fqn, module in model.named_modules():
934
+ # if module is supported and it has a pre-observer
935
+ if self._is_supported(module):
936
+ # we don't need actual observer, just the module weights
937
+ # calculate min and max vals
938
+ device = module.weight.device
939
+ min_val: torch.Tensor = torch.tensor([float('inf')], device=device)
940
+ max_val: torch.Tensor = torch.tensor([float('-inf')], device=device)
941
+ x_copy = module.weight
942
+ x_dim = x_copy.size()
943
+
944
+ new_axis_list = [i for i in range(len(x_dim))] # noqa: C416
945
+ new_axis_list[self.ch_axis] = 0
946
+ new_axis_list[0] = self.ch_axis
947
+ y = x_copy.permute(new_axis_list)
948
+
949
+ # Need to match dtype of min/max because the updates to buffers
950
+ # are done in place and types need to match for comparisons
951
+ y = y.to(min_val.dtype)
952
+ y = torch.flatten(y, start_dim=1)
953
+ if min_val.numel() == 0 or max_val.numel() == 0:
954
+ min_val, max_val = torch.aminmax(y, dim=1)
955
+ else:
956
+ min_val_cur, max_val_cur = torch.aminmax(y, dim=1)
957
+ min_val = torch.min(min_val_cur, min_val)
958
+ max_val = torch.max(max_val_cur, max_val)
959
+
960
+ weight_info[fqn] = {
961
+ self.WEIGHT_PREFIX + self.PER_CHANNEL_MAX_KEY: max_val,
962
+ self.WEIGHT_PREFIX + self.PER_CHANNEL_MIN_KEY: min_val,
963
+ self.WEIGHT_PREFIX + self.GLOBAL_MAX_KEY: max(max_val),
964
+ self.WEIGHT_PREFIX + self.GLOBAL_MIN_KEY: min(min_val),
965
+ }
966
+
967
+ return weight_info
968
+
969
+ def _calculate_range_ratio(self, info_dict: Dict, info_str: str, module_fqn: str) -> torch.Tensor:
970
+ r"""
971
+ Takes in an info dict and calculates the s_c matrix.
972
+
973
+ Args:
974
+ info_dict (dict): A dictionary of either input or weight range info
975
+ info_str (str): A str describing whether currently looking at weight or input info
976
+ Either "weight" or "input"
977
+ module_fqn (str): The fqn of the module we are looking at
978
+
979
+ Returns a tensor of values, where each value is the s_c stat for a different channel
980
+ """
981
+ # calculate the ratios of the info
982
+ # get the prefix str
983
+ prefix_str = self.ACTIVATION_PREFIX if info_str == self.INPUT_STR else self.WEIGHT_PREFIX
984
+
985
+ per_channel_range = info_dict[prefix_str + self.PER_CHANNEL_MAX_KEY] - info_dict[prefix_str + self.PER_CHANNEL_MIN_KEY]
986
+ global_range = info_dict[prefix_str + self.GLOBAL_MAX_KEY] - info_dict[prefix_str + self.GLOBAL_MIN_KEY]
987
+
988
+ if global_range == 0:
989
+ range_zero_explanation = "We recommend removing this channel as it doesn't provide any useful information."
990
+ raise ValueError(
991
+ "The range of the {} data for module {} is 0, which means you have a constant value channel. {}".format(
992
+ info_str, module_fqn, range_zero_explanation
993
+ )
994
+ )
995
+
996
+ ratio = per_channel_range / global_range
997
+
998
+ return ratio
999
+
1000
+ def _generate_comparison_values(self, input_info: Dict, weight_info: Dict) -> Dict[str, torch.Tensor]:
1001
+ r"""
1002
+ Takes in the information on the min and max values of the inputs and weights and:
1003
+ Calculates the comp stat for each channel: s_c = sqrt(w_c/W)/sqrt(i_c/I)
1004
+
1005
+ Args:
1006
+ input_info (dict): A dict mapping each observer to input range information
1007
+ weight_info (dict): A dict mapping each observer to weight range information
1008
+
1009
+ Returns a dict mapping relevant observer fqns (str) to a 1-D tensor.
1010
+ Each value is a different s_c value for a different channel
1011
+ """
1012
+ # create return dictionary for each observer
1013
+ module_fqn_to_channel: Dict[str, torch.Tensor] = {}
1014
+
1015
+ # for each module (both passed in dicts should have same keys)
1016
+ for module_fqn in input_info:
1017
+
1018
+ # raise error if not in weight info
1019
+ if module_fqn not in weight_info:
1020
+ raise KeyError(f"Unable to find weight range stats for module {module_fqn}")
1021
+
1022
+ # calculate the ratios of the weight info and input info
1023
+ weight_ratio = self._calculate_range_ratio(weight_info[module_fqn], self.WEIGHT_STR, module_fqn)
1024
+ input_ratio = self._calculate_range_ratio(input_info[module_fqn], self.INPUT_STR, module_fqn)
1025
+
1026
+ # if mismatched size, because of grouping, we want to replicate weight enough times
1027
+ weight_channels = len(weight_ratio)
1028
+ input_channels = len(input_ratio)
1029
+ if weight_channels != input_channels:
1030
+ # we try to replicate
1031
+ assert input_channels % weight_channels == 0, "input channels should be divisible by weight channels."
1032
+ # get replication factor
1033
+ rep_factor: int = input_channels // weight_channels
1034
+
1035
+ # weight ratio is (n,), input ratio is (k,), we just repeat weight ratio k // n
1036
+ weight_ratio = weight_ratio.repeat(rep_factor)
1037
+
1038
+ # calculate the s metric per channel
1039
+ s = torch.sqrt(weight_ratio) / torch.sqrt(input_ratio)
1040
+ module_fqn_to_channel[module_fqn] = s
1041
+
1042
+ # return compiled observer ratios
1043
+ return module_fqn_to_channel
1044
+
1045
+ def _generate_dict_info(self, input_info: Dict, weight_info: Dict, comp_stats: Dict) -> Dict[str, Dict]:
1046
+ r"""
1047
+ Helper function for generate_detector_report that does the generation of the dictionary.
1048
+ This process is done as specified in generate_detector_report documentation
1049
+
1050
+ Args:
1051
+ input_info (dict): A dict mapping each module to input range information
1052
+ weight_info (dict): A dict mapping each module to weight range information
1053
+ comp_stats (dict): A dict mapping each module to its corresponding comp stat
1054
+
1055
+ Returns a dictionary mapping each module with relevant ModelReportObservers around them to:
1056
+ whether input weight equalization is recommended
1057
+ their s_c metric compared to the threshold
1058
+ the threshold used to make the recommendation
1059
+ the channel used for recording data
1060
+ the input channel range info
1061
+ the weight channel range info
1062
+ """
1063
+ # store modules input weight equalization info
1064
+ input_weight_equalization_info: Dict[str, Dict] = {}
1065
+
1066
+ # for each module we add separate set of suggestions
1067
+ for module_fqn in input_info:
1068
+
1069
+ # get relevant info for this module
1070
+ mod_input_info: Dict = input_info[module_fqn]
1071
+ mod_weight_info: Dict = weight_info[module_fqn]
1072
+ mod_comp_stat: Dict = comp_stats[module_fqn]
1073
+
1074
+ # decide if each channel should have input weight equalization or not
1075
+ channel_rec_vals: list = []
1076
+
1077
+ for val in mod_comp_stat:
1078
+ float_rep: float = val.item()
1079
+
1080
+ # decide if recommending input weight equalization
1081
+ recommended: bool = float_rep >= self.ratio_threshold and float_rep <= 1 / self.ratio_threshold
1082
+ channel_rec_vals.append(recommended)
1083
+
1084
+ # build the return dict input
1085
+ # also unpack input and weight dicts into it
1086
+ input_weight_equalization_info[module_fqn] = {
1087
+ self.RECOMMENDED_KEY: channel_rec_vals,
1088
+ self.COMP_METRIC_KEY: mod_comp_stat,
1089
+ self.THRESHOLD_KEY: self.ratio_threshold,
1090
+ self.CHANNEL_KEY: self.ch_axis,
1091
+ **mod_input_info,
1092
+ **mod_weight_info,
1093
+ }
1094
+
1095
+ # return our compiled info for each module
1096
+ return input_weight_equalization_info
1097
+
1098
+ def generate_detector_report(self, model: GraphModule) -> Tuple[str, Dict[str, Any]]:
1099
+ r"""
1100
+ Determines whether input weight equalization is appropriate for a given module.
1101
+
1102
+ Takes advantage of the ModelReport Observer which records per channel information of input range
1103
+ It then uses the passed in weight info inconjunction to compute the desired ratio
1104
+ Finally, it gives suggestions based on this information for each module of interest
1105
+
1106
+ Args:
1107
+ model (GraphModule): The prepared and calibrated GraphModule with inserted ModelReportObservers
1108
+
1109
+ Returns a tuple with two elements:
1110
+ String report of of whether input weight equalization is recommended for certain modules
1111
+ Dictionary mapping modules of interest to:
1112
+ whether input weight equalization is recommended
1113
+ their s_c metric compared to the threshold
1114
+ the threshold used to make the recommendation
1115
+ the channel used for recording data
1116
+ the input channel range info
1117
+ the weight channel range info
1118
+ """
1119
+
1120
+ # find the range of inputs
1121
+ input_values: Dict[str, Dict] = self._extract_input_info(model)
1122
+
1123
+ # find the range of weights
1124
+ weight_values: Dict[str, Dict] = self._extract_weight_info(model)
1125
+
1126
+ # calculate per_channel comparison statistic s_c
1127
+ comp_stats: Dict[str, torch.Tensor] = self._generate_comparison_values(input_values, weight_values)
1128
+
1129
+ # generate the return dictionary
1130
+ input_weight_equalization_info: Dict[str, Dict] = self._generate_dict_info(input_values, weight_values, comp_stats)
1131
+
1132
+ # now we can generate report based on this information
1133
+ input_weight_string = "Input-Weight Equalization suggestions: \n"
1134
+
1135
+ # some strings to be formatted depending on module we are adding
1136
+ module_suggestion_str = "For Module {} looked at with axis {}: \n"
1137
+ channel_suggestion_str = "\tWe suggest {} input weight equalization because {}\n"
1138
+ use_str = "to use"
1139
+ no_use_str = "to not use"
1140
+ input_weight_benefit_str = "{}/{} channels would benefit and we expect significant reduction in quantization error."
1141
+ input_weight_non_benefit_reasoning = "{}/{} channels benefitting from input-weight equalization being applied."
1142
+ input_weight_non_benefit_str = "we don't expect much improvement from input-weight equalization based on {}"
1143
+
1144
+ # added module check
1145
+ added_module: bool = False
1146
+
1147
+ # compile the suggestion string
1148
+ for module_fqn in input_weight_equalization_info:
1149
+ # we added at least 1 module
1150
+ added_module = True
1151
+ # add the module level description
1152
+ input_weight_string += module_suggestion_str.format(module_fqn, self.ch_axis)
1153
+
1154
+ mod_info: Dict[str, Any] = input_weight_equalization_info[module_fqn]
1155
+
1156
+ # gather info on how many channels would benefit from input weight and
1157
+ recommendation_per_channel: torch.Tensor = mod_info[self.RECOMMENDED_KEY]
1158
+ num_recs = sum(recommendation_per_channel)
1159
+
1160
+ if num_recs / len(recommendation_per_channel) >= self.DEFAULT_RECOMMEND_INPUT_WEIGHT_CHANNEL_RATIO:
1161
+ input_benefit_formatted = input_weight_benefit_str.format(num_recs, len(recommendation_per_channel))
1162
+ channel_str = channel_suggestion_str.format(use_str, input_benefit_formatted)
1163
+ input_weight_string += channel_str
1164
+ else:
1165
+ non_benefit_reason_formatted = input_weight_non_benefit_reasoning.format(num_recs, len(recommendation_per_channel))
1166
+ non_benefit_str = input_weight_non_benefit_str.format(non_benefit_reason_formatted)
1167
+ channel_str = channel_suggestion_str.format(no_use_str, non_benefit_str)
1168
+ input_weight_string += channel_str
1169
+
1170
+ # if no modules looked at, amend return string
1171
+ if not added_module:
1172
+ input_weight_string += "No applicable layers for suggestions. Only linear and conv valid.\n"
1173
+
1174
+ # return a tuple with the string explanation and the compiled dict info
1175
+ return (input_weight_string, input_weight_equalization_info)
1176
+
1177
+
1178
+ class OutlierDetector(DetectorBase):
1179
+ r"""
1180
+ Determines whether there are significant outliers in activation data around a certain layer.
1181
+
1182
+ This is ideally used in conjunction with information on stationary vs. non-stationary distribution:
1183
+ If the data is stationary, and there are significant outliers, then we want to flag them
1184
+ We want to do this on a per channel basis for detecting outliers
1185
+
1186
+ Determines whether activation data is flagged as outlier based on if data is stationary and:
1187
+ p_r = avg(100th percentile / "reference_percentile"th percentile)
1188
+ where:
1189
+ p_r is average percentile ratio across all batches in the epoch
1190
+ reference_percentile is a percentile values between 0 and 100 exclusive
1191
+
1192
+ if p_r is above some threshold, then we consider the activations to have significant outliers
1193
+
1194
+ Args:
1195
+ ratio_threshold (float, optional): The threshold for p_r to determine if there are outliers in activations
1196
+ Should be >= 1
1197
+ Default: 3.5
1198
+ reference_percentile (float, optional): The denominator to find the relative scale of the 100th percentile
1199
+ Should be between 0 and 1
1200
+ Default: 0.975
1201
+ fraction_batches_used_threshold (float, optional): Threshold of fraction of batches per channel to determine outlier
1202
+ If fraction is below this, we deem number of samples used to calculate outliers as insignificant and alert user
1203
+ regardless of whether we detected outliers or not in channel to take a closer look at channel results
1204
+ Should be between 0 and 1
1205
+ Default: 0.95
1206
+ ch_axis (int, optional): The channel axis being observed to determine input weight equalization
1207
+ Default: 1
1208
+
1209
+ * :attr:`ratio_threshold`: The threshold for p_r to determine if there are outliers in activations
1210
+ The p_r value (average ratio of 100th percentile/reference_percentile) is compared to ratio_threshold
1211
+ If it is significantly greater, then we consider it an outlier
1212
+ This threshold was calculated based on the ratio of the percentiles in a normal distribution
1213
+ The calculations behind value choice: https://drive.google.com/file/d/1N2wdtXWI-kOH8S7HH4-PYB_NmqzZil4p/view?usp=sharing
1214
+
1215
+ * :attr:`reference_percentile`: The denominator of the top fraction to find the relative scale of the 100th percentile
1216
+ Should be between 0 and 1
1217
+ The calculations behind value choice: https://drive.google.com/file/d/1N2wdtXWI-kOH8S7HH4-PYB_NmqzZil4p/view?usp=sharing
1218
+
1219
+ * :attr:`fraction_batches_used_threshold`: The fraction of batches to determine outliers for each channel should be above this
1220
+ Some batches may not be used because of 0-based errors, so this is to ensure a good amount of the total batches are used
1221
+ Should be between 0 and 1
1222
+
1223
+ * :attr:`ch_axis`: The channel axis being observed to determine outliers
1224
+
1225
+ * :attr:`DEFAULT_PRE_OBSERVER_NAME`: The name of the pre-observer to be inserted for this detector
1226
+ """
1227
+
1228
+ # names for the pre observers that are inserted
1229
+ DEFAULT_PRE_OBSERVER_NAME: str = "model_report_pre_observer"
1230
+
1231
+ # pre activation prefix
1232
+ INPUT_ACTIVATION_PREFIX = "input_activation_"
1233
+
1234
+ # names for dict keys
1235
+ OUTLIER_KEY = "outliers_detected"
1236
+ NUM_BATCHES_KEY = "outlier_detection_batches_used"
1237
+ IS_SUFFICIENT_BATCHES_KEY = "outlier_detection_is_sufficient_batches"
1238
+ COMP_METRIC_KEY = "outlier_detection_percentile_ratios"
1239
+ RATIO_THRES_KEY = "outlier_detection_ratio_threshold"
1240
+ REF_PERCENTILE_KEY = "outlier_detection_reference_percentile"
1241
+ CHANNEL_AXIS_KEY = "outlier_detection_channel_axis"
1242
+ MAX_VALS_KEY = INPUT_ACTIVATION_PREFIX + "per_channel_max"
1243
+ CONSTANT_COUNTS_KEY = "constant_batch_counts"
1244
+
1245
+ def __init__(
1246
+ self,
1247
+ ratio_threshold: float = 3.5,
1248
+ reference_percentile: float = 0.975,
1249
+ fraction_batches_used_threshold: float = 0.95,
1250
+ ch_axis: int = 1,
1251
+ ):
1252
+ # initialize the variables of interest
1253
+ self.ratio_threshold = ratio_threshold
1254
+
1255
+ # make sure passed in percentile is valid
1256
+ assert reference_percentile >= 0 and reference_percentile <= 1
1257
+ assert fraction_batches_used_threshold >= 0 and fraction_batches_used_threshold <= 1
1258
+ self.reference_percentile = reference_percentile
1259
+ self.fraction_batches_used_threshold = fraction_batches_used_threshold
1260
+ self.ch_axis = ch_axis
1261
+
1262
+ def get_detector_name(self) -> str:
1263
+ r"""Returns the name of this detector"""
1264
+ return "outlier_detector"
1265
+
1266
+ def _supports_insertion(self, module: nn.Module) -> bool:
1267
+ r"""Returns whether the given module is supported for observers insertion
1268
+
1269
+ Any module that doesn't have children and isn't an observer itself is supported
1270
+
1271
+ Args
1272
+ module: The module to check and ensure is supported
1273
+
1274
+ Returns True if the module is supported by observer, False otherwise
1275
+ """
1276
+ # case for insertion of module
1277
+ # check if the module has any children and isn't observer
1278
+ num_children = len(list(module.children()))
1279
+ return num_children == 0 and not _is_activation_post_process(module)
1280
+
1281
+ def get_qconfig_info(self, model) -> Dict[str, DetectorQConfigInfo]:
1282
+ r""" Returns the DetectorQConfigInfo for each module_fqn relevant
1283
+ Args
1284
+ model (nn.Module or subclass): model to find observer insertion points
1285
+
1286
+ Returns a Dict mapping from unique observer fqns (where we want to insert them) to:
1287
+ A DetectorQConfigInfo with the information to generate a QConfig for a specific module
1288
+ """
1289
+ # currently doesn't do anything for outlier detector
1290
+ return {}
1291
+
1292
+ def _supports_report_gen(self, module: nn.Module) -> bool:
1293
+ r"""Returns whether the given module is supported for report generation
1294
+
1295
+ Any module that has a model report pre-observer is supported
1296
+
1297
+ Args
1298
+ module: The module to check and ensure is supported
1299
+
1300
+ Returns True if the module is supported by observer, False otherwise
1301
+ """
1302
+ return hasattr(module, self.DEFAULT_PRE_OBSERVER_NAME)
1303
+
1304
+ def determine_observer_insert_points(self, prepared_fx_model: GraphModule) -> Dict[str, Dict[str, Any]]:
1305
+ r""" Determines where observers need to be inserted for the Outlier Detector.
1306
+
1307
+ For this detector, we want to place observers in front of supported layers.
1308
+
1309
+ Currently inserts observers for:
1310
+ all layers that do not have children (leaf level layers)
1311
+
1312
+ Args:
1313
+ prepared_fx_model (GraphModule): The prepared Fx GraphModule
1314
+
1315
+ Returns a Dict mapping from unique observer fqns (where we want to insert them) to a Dict with:
1316
+ key "target_node" -> the node we are trying to observe with this observer (torch.fx.node.Node)
1317
+ key "observer_to_insert" -> the observer we wish to insert (ObserverBase)
1318
+ key "is_post_observer" -> True if this is meant to be a post-observer for target_node, False if pre-observer
1319
+ key "observer_args" -> The arguments that are meant to be passed into the observer
1320
+ """
1321
+ # observer for this detector is ModelReportObserver
1322
+ obs_ctr = ModelReportObserver
1323
+
1324
+ # return dict
1325
+ obs_fqn_to_info: Dict[str, Dict[str, Any]] = {}
1326
+
1327
+ for fqn, module in prepared_fx_model.named_modules():
1328
+ # check to see if module is of a supported type
1329
+ if self._supports_insertion(module):
1330
+ # if it's a supported type, we want to get node and add observer insert locations
1331
+ targeted_node = self._get_targeting_node(prepared_fx_model, fqn)
1332
+
1333
+ # add entry for pre-observer
1334
+ pre_obs_fqn = fqn + "." + self.DEFAULT_PRE_OBSERVER_NAME
1335
+
1336
+ obs_fqn_to_info[pre_obs_fqn] = {
1337
+ DETECTOR_TARGET_NODE_KEY: targeted_node,
1338
+ DETECTOR_OBS_TO_INSERT_KEY: obs_ctr(ch_axis=self.ch_axis, comp_percentile=self.reference_percentile),
1339
+ DETECTOR_IS_POST_OBS_KEY: False,
1340
+ DETECTOR_OBS_ARGS_KEY: targeted_node.args,
1341
+ }
1342
+
1343
+ return obs_fqn_to_info
1344
+
1345
+ def _calculate_outlier_info(
1346
+ self,
1347
+ percentile_ratios: torch.Tensor,
1348
+ counted_batches: torch.Tensor,
1349
+ total_batches: int,
1350
+ ) -> Dict[str, List[bool]]:
1351
+ r"""
1352
+ Gives info on whether the percentile ratios calculated would be considered outliers
1353
+ Also gives information on whether the collected data is statistically significant to make this claim
1354
+
1355
+ Args:
1356
+ percentile_ratios (torch.Tensor): The average percentile_ratios per channel calculated by the observer
1357
+ counted_batches (torch.Tensor): The number of batches used for average calculation per tensor
1358
+ total_batches (int): The total number of batches that passed through observer in this epoch
1359
+
1360
+ Returns a dictionary mapping:
1361
+ "outliers_detected" : list of bools per channel that are true if it is considered an outlier
1362
+ "is_sufficient_batches": if o_r was >= fraction_batches_used_threshold:
1363
+ where o_r = counted_batches / total_batches
1364
+ """
1365
+ outlier_dict: Dict[str, List[bool]] = {self.OUTLIER_KEY: [], self.IS_SUFFICIENT_BATCHES_KEY: []}
1366
+
1367
+ # get both as flattened lists for easy mapping
1368
+ ratios_list: List = percentile_ratios.tolist()
1369
+ num_batches_list: List = counted_batches.tolist()
1370
+
1371
+ # calculate whether channels were statistically significant
1372
+ significant_size = [
1373
+ batch_size / total_batches >= self.fraction_batches_used_threshold for batch_size in num_batches_list
1374
+ ]
1375
+ outlier_dict[self.IS_SUFFICIENT_BATCHES_KEY] = significant_size
1376
+
1377
+ # calculate for each channel whether it's an outlier or not based on ratio
1378
+ outlier_detected = [ratio > self.ratio_threshold for ratio in ratios_list]
1379
+ outlier_dict[self.OUTLIER_KEY] = outlier_detected
1380
+
1381
+ # return the dictionary with the two lists
1382
+ return outlier_dict
1383
+
1384
+ def _generate_info_dict(self, model: GraphModule) -> Dict[str, Dict]:
1385
+ r"""
1386
+ Helper function for generate_detector_report that does the generation of the dictionary.
1387
+ This process is done as specified in generate_detector_report documentation
1388
+
1389
+ Args:
1390
+ model (GraphModule): The prepared and calibrated GraphModule with inserted ModelReportObservers
1391
+
1392
+ Returns a dict mapping relevant module fqns to:
1393
+ whether there were outliers found in activation before
1394
+ the number of batches used for each channel
1395
+ whether fraction of applicable batches used is above fraction_batches_used_threshold
1396
+ their p_r metric compared to the threshold
1397
+ the threshold used to make the recommendation
1398
+ the reference_percentile used to make the recommendation
1399
+ the channel axis used to determine individual channels
1400
+ the constant batch counts per channel
1401
+ the per channel max values
1402
+ """
1403
+ # return dictionary mapping observer fqns to desired info
1404
+ info_dict: Dict[str, Dict] = {}
1405
+
1406
+ for fqn, module in model.named_modules():
1407
+ # if module is supported and it has a pre-observer
1408
+ if self._supports_report_gen(module):
1409
+ # get pre observer for the module
1410
+ pre_obs: ModelReportObserver = getattr(module, self.DEFAULT_PRE_OBSERVER_NAME)
1411
+
1412
+ # get the number of batches and calculated ratio thresholds
1413
+ num_batches: torch.Tensor = pre_obs.percentile_batches_tracked
1414
+ average_ratios: torch.Tensor = pre_obs.average_percentile_ratio
1415
+ channel_batch_cnts: torch.Tensor = pre_obs.constant_channels
1416
+ total_batches: int = pre_obs.num_batches_tracked
1417
+
1418
+ # also get the max values
1419
+ max_vals: torch.Tensor = pre_obs.max_val
1420
+
1421
+ # we have to specifically modify how we are recording negative ratio for pre-relu layers
1422
+ for index, ratio_val in enumerate(average_ratios):
1423
+ # check if we have a negative ratio
1424
+ # a ratio might be negative if we have a situation where the 100th percentile is
1425
+ # > 0 while the nth percentile is < 0, in which case this would not be detected
1426
+ # as an outlier. Since we care more about magnitude, we make it positive.
1427
+ if ratio_val.item() < 0:
1428
+ # first make it positive
1429
+ average_ratios[index] = -ratio_val
1430
+
1431
+ if ratio_val.item() < 1:
1432
+ # if it's less than 1 we have the flip it as well
1433
+ average_ratios[index] = 1 / ratio_val
1434
+
1435
+ outlier_calcs = self._calculate_outlier_info(average_ratios, num_batches, total_batches)
1436
+
1437
+ # calculate whether ratios were outliers
1438
+ info_dict[fqn] = {
1439
+ self.CHANNEL_AXIS_KEY: self.ch_axis,
1440
+ self.REF_PERCENTILE_KEY: self.reference_percentile,
1441
+ self.RATIO_THRES_KEY: self.ratio_threshold,
1442
+ self.COMP_METRIC_KEY: average_ratios,
1443
+ self.NUM_BATCHES_KEY: num_batches,
1444
+ self.OUTLIER_KEY: outlier_calcs[self.OUTLIER_KEY],
1445
+ self.IS_SUFFICIENT_BATCHES_KEY: outlier_calcs[self.IS_SUFFICIENT_BATCHES_KEY],
1446
+ self.CONSTANT_COUNTS_KEY: channel_batch_cnts,
1447
+ self.MAX_VALS_KEY: max_vals
1448
+ }
1449
+
1450
+ return info_dict
1451
+
1452
+ def generate_detector_report(self, model: GraphModule) -> Tuple[str, Dict[str, Any]]:
1453
+ r"""
1454
+ Determines whether input weight equalization is appropriate for a given module.
1455
+
1456
+ Takes advantage of the ModelReport Observer which records the relevant percentile information
1457
+
1458
+ Args:
1459
+ model (GraphModule): The prepared and calibrated GraphModule with inserted ModelReportObservers
1460
+
1461
+ Returns a tuple with two elements:
1462
+ String report of of whether there are outliers in the activations around certain modules
1463
+ Dictionary mapping modules of interest to:
1464
+ whether there were outliers found in activation before
1465
+ the number of batches used for each channel
1466
+ whether fraction of applicable batches used is above fraction_batches_used_threshold
1467
+ their p_r metric compared to the threshold
1468
+ the threshold used to make the recommendation
1469
+ the reference_percentile used to make the recommendation
1470
+ the channel axis used to determine individual channels
1471
+ the constant batch counts per channel
1472
+ the per channel max values
1473
+ """
1474
+ # generate the information dictionary of outlier information
1475
+ info_dict = self._generate_info_dict(model)
1476
+
1477
+ # now we can generate report based on this information
1478
+ outlier_string = "Outlier detection report: \n"
1479
+
1480
+ # added module check
1481
+ added_module: bool = False
1482
+
1483
+ # some strings to be formatted depending on module we are adding
1484
+ module_suggestion_str = "For Module {} looked at with axis {}: \n"
1485
+ channel_suggestion_str = "\tFor channel {}, we found outliers in the preceding activation data with {}.\n"
1486
+ channel_max_value_str = "a max value across all batches of {}"
1487
+ note_string = "Note: outlier detection is only reliable for {}. We recommend {} to ensure the most accurate results."
1488
+ note_distribution = "stationary distributions"
1489
+ note_rec = "running the static vs. dynamic detector to ensure activation data before modules above is stationary"
1490
+
1491
+ # suggestion for constant batch check since that can make it no outliers
1492
+ constant_str = "\tFor channel {}, we found {} constant value batches. {}\n"
1493
+ constant_suggestion = "We recommend taking a look at the dict and data to see how frequent this occurred and why."
1494
+
1495
+ # compile the suggestion string
1496
+ for module_fqn in info_dict:
1497
+ # get module specific info
1498
+ mod_info: Dict[str, Any] = info_dict[module_fqn]
1499
+ # check to see if we already added high level model desc
1500
+ added_model_desc = False
1501
+ # look at each individual channel and add a suggestion
1502
+ for index, outlier_detected in enumerate(mod_info[self.OUTLIER_KEY]):
1503
+ if outlier_detected:
1504
+ # we found at least 1 outlier
1505
+ if not added_model_desc:
1506
+ # add the module level description
1507
+ outlier_string += module_suggestion_str.format(module_fqn, self.ch_axis)
1508
+ added_model_desc = True
1509
+
1510
+ # we mark that we found at least one outlier
1511
+ added_module = True
1512
+ max_value_found_str = channel_max_value_str.format(mod_info[self.MAX_VALS_KEY][index])
1513
+ channel_str = channel_suggestion_str.format(index, max_value_found_str)
1514
+ outlier_string += channel_str
1515
+
1516
+ # also check if we found constant batch
1517
+ if mod_info[self.CONSTANT_COUNTS_KEY][index] != 0:
1518
+ # make sure we add a module level highlight.
1519
+ if not added_model_desc:
1520
+ # add the module level description
1521
+ outlier_string += module_suggestion_str.format(module_fqn, self.ch_axis)
1522
+ added_model_desc = True
1523
+
1524
+ constant_values_for_channel = mod_info[self.CONSTANT_COUNTS_KEY][index]
1525
+ formatted_str = constant_str.format(index, constant_values_for_channel, constant_suggestion)
1526
+ outlier_string += formatted_str
1527
+ # we also added at least one thing to description
1528
+ added_module = True
1529
+
1530
+
1531
+ # if found outlier, give suggestion, else give default response
1532
+ if added_module:
1533
+ # compose the note string
1534
+ note_composed = note_string.format(note_distribution, note_rec)
1535
+ outlier_string += note_composed
1536
+ else:
1537
+ outlier_string += "There were no outliers found in the activations.\n"
1538
+
1539
+ return (outlier_string, info_dict)
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/fuse.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.fx import (
2
+ GraphModule,
3
+ Node,
4
+ map_arg
5
+ )
6
+ from torch.fx.graph import Graph
7
+ from .match_utils import (
8
+ _is_match,
9
+ MatchAllNode,
10
+ )
11
+ from .pattern_utils import (
12
+ _sorted_patterns_dict,
13
+ )
14
+
15
+ from ..backend_config import (
16
+ BackendConfig,
17
+ get_native_backend_config,
18
+ )
19
+ from ..backend_config.utils import (
20
+ get_fuser_method_mapping,
21
+ get_fusion_pattern_to_root_node_getter,
22
+ get_fusion_pattern_to_extra_inputs_getter,
23
+ )
24
+
25
+ from .custom_config import FuseCustomConfig
26
+
27
+ from .fuse_handler import (
28
+ _get_fusion_pattern_to_fuse_handler_cls,
29
+ FuseHandler,
30
+ )
31
+
32
+ from typing import Any, Callable, Dict, List, Tuple, Union
33
+ import warnings
34
+
35
+ from torch.ao.quantization.utils import Pattern, NodePattern
36
+
37
+
38
+ __all__ = [
39
+ "fuse",
40
+ # TODO: We should make this private in the future
41
+ # This is currently needed for test_public_bindings for some reason
42
+ "FuseHandler",
43
+ ]
44
+
45
+
46
+ def fuse(
47
+ model: GraphModule,
48
+ is_qat: bool,
49
+ fuse_custom_config: Union[FuseCustomConfig, Dict[str, Any], None] = None,
50
+ backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
51
+ ) -> GraphModule:
52
+ if fuse_custom_config is None:
53
+ fuse_custom_config = FuseCustomConfig()
54
+
55
+ if isinstance(fuse_custom_config, Dict):
56
+ warnings.warn(
57
+ "Passing a fuse_custom_config_dict to fuse is deprecated and will not be supported "
58
+ "in a future version. Please pass in a FuseCustomConfig instead.")
59
+ fuse_custom_config = FuseCustomConfig.from_dict(fuse_custom_config)
60
+
61
+ if isinstance(backend_config, Dict):
62
+ warnings.warn(
63
+ "Passing a backend_config_dict to prepare is deprecated and will not be supported "
64
+ "in a future version. Please pass in a BackendConfig instead.")
65
+ backend_config = BackendConfig.from_dict(backend_config)
66
+
67
+ named_modules = dict(model.named_modules())
68
+
69
+ if backend_config is None:
70
+ backend_config = get_native_backend_config()
71
+
72
+ fusion_pattern_to_fuse_handler_cls = _sorted_patterns_dict(_get_fusion_pattern_to_fuse_handler_cls(backend_config))
73
+ fuser_method_mapping = get_fuser_method_mapping(backend_config)
74
+ fusion_pattern_to_root_node_getter = get_fusion_pattern_to_root_node_getter(backend_config)
75
+ fusion_pattern_to_extra_inputs_getter = get_fusion_pattern_to_extra_inputs_getter(backend_config)
76
+
77
+ # find fusion
78
+ fusion_pairs = _find_matches(
79
+ model, model.graph, fusion_pattern_to_fuse_handler_cls)
80
+ # TODO: change this to inplace changes to graph, since we no longer construct
81
+ # new GraphModule anymore
82
+ fused_graph = Graph()
83
+ env: Dict[Any, Any] = {}
84
+
85
+ def load_arg(a):
86
+ return map_arg(a, lambda node: env[node.name])
87
+
88
+ def default_root_node_getter(node_pattern):
89
+ while not isinstance(node_pattern[-1], Node):
90
+ node_pattern = node_pattern[-1]
91
+ return node_pattern[-1]
92
+
93
+ for node in model.graph.nodes:
94
+ maybe_last_node, pattern, matched_node_pattern, obj, node_to_subpattern = \
95
+ fusion_pairs.get(node.name, (None, None, None, None, None))
96
+ # get the corresponding subpattern for the current node
97
+ if node_to_subpattern is not None:
98
+ node_subpattern = node_to_subpattern.get(node, None)
99
+ else:
100
+ node_subpattern = None
101
+ if maybe_last_node is node:
102
+ assert obj is not None
103
+ root_node_getter = fusion_pattern_to_root_node_getter.get(pattern, default_root_node_getter)
104
+ root_node = root_node_getter(matched_node_pattern) # type: ignore[index]
105
+ extra_inputs_getter = fusion_pattern_to_extra_inputs_getter.get(pattern, None)
106
+ extra_inputs = []
107
+ if extra_inputs_getter is not None:
108
+ extra_inputs = extra_inputs_getter(matched_node_pattern)
109
+ # TODO: add validation that root_node is a module and has the same type
110
+ # as the root_module in the configuration
111
+ env[node.name] = obj.fuse(
112
+ load_arg, named_modules, fused_graph, root_node, extra_inputs, matched_node_pattern, # type: ignore[arg-type]
113
+ fuse_custom_config, fuser_method_mapping, is_qat)
114
+ elif maybe_last_node is None or node_subpattern is MatchAllNode:
115
+ env[node.name] = fused_graph.node_copy(node, load_arg)
116
+ # node matched in patterns and is not root is removed here
117
+
118
+ model = GraphModule(model, fused_graph)
119
+ return model
120
+
121
+ def _find_matches(
122
+ root: GraphModule,
123
+ graph: Graph,
124
+ pattern_to_fuse_handler_cls: Dict[Pattern, Callable],
125
+ ) -> Dict[str, Tuple[Node, Pattern, NodePattern, FuseHandler, Dict[Node, Any]]]:
126
+ modules = dict(root.named_modules())
127
+ # node name -> (root_node, match_value)
128
+ match_map : Dict[
129
+ str, Tuple[Node, Pattern, NodePattern, FuseHandler, Dict[Node, Any]]] = {}
130
+ # a map from node to the matched subpattern
131
+ node_to_subpattern: Dict[Node, Any] = {}
132
+
133
+ # TODO: dedup with quantization matching function in match_utils.py
134
+ def apply_match(pattern, node, match, matched_node_pattern, node_to_subpattern):
135
+ if isinstance(pattern, tuple):
136
+ s, *args = pattern
137
+ current_node_pattern: List[Node] = []
138
+ apply_match(s, node, match, current_node_pattern, node_to_subpattern)
139
+ for subpattern, arg in zip(args, node.args):
140
+ apply_match(subpattern, arg, match, current_node_pattern, node_to_subpattern)
141
+ matched_node_pattern.append(tuple(current_node_pattern))
142
+ else:
143
+ # the first pattern matches will take precedence
144
+ if node.name not in match_map:
145
+ matched_node_pattern.append(node)
146
+ # MatchAllNode here is actually MatchAllInputNode which should not
147
+ # be added to match_map
148
+ if pattern is not MatchAllNode:
149
+ node_to_subpattern[node] = pattern
150
+ root_node, pattern, handler = match
151
+ match_map[node.name] = (root_node, pattern, matched_node_pattern, handler, node_to_subpattern)
152
+
153
+ for node in reversed(graph.nodes):
154
+ if node.name not in match_map:
155
+ for pattern, fuse_handler_cls in pattern_to_fuse_handler_cls.items():
156
+ matched_node_pattern: List[Node] = []
157
+ if _is_match(modules, node, pattern):
158
+ apply_match(pattern, node, (node, pattern, fuse_handler_cls(node)), matched_node_pattern, node_to_subpattern)
159
+ break
160
+
161
+ return match_map
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/graph_module.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import copy
3
+ from torch.fx import GraphModule
4
+ from torch.fx.graph import Graph
5
+ from typing import Union, Dict, Any, Set
6
+
7
+ __all__ = [
8
+ "FusedGraphModule",
9
+ "ObservedGraphModule",
10
+ "ObservedStandaloneGraphModule",
11
+ "QuantizedGraphModule",
12
+ ]
13
+
14
+ class FusedGraphModule(GraphModule):
15
+ def __init__(self, root: Union[torch.nn.Module, Dict[str, Any]], graph: Graph, preserved_attr_names: Set[str]):
16
+ self.preserved_attr_names = preserved_attr_names
17
+ preserved_attrs = {attr: getattr(root, attr) for attr in self.preserved_attr_names if hasattr(root, attr)}
18
+ super().__init__(root, graph)
19
+ for attr in preserved_attrs:
20
+ setattr(self, attr, preserved_attrs[attr])
21
+
22
+ # GraphModule does not copy attributes which are not in the __dict__
23
+ # of vanilla nn.Module. So, we override __deepcopy__ in order
24
+ # to copy the quantization specific attributes correctly.
25
+ def __deepcopy__(self, memo):
26
+ fake_mod = torch.nn.Module()
27
+ fake_mod.__dict__ = copy.deepcopy(self.__dict__)
28
+ return FusedGraphModule(fake_mod, copy.deepcopy(self.graph), copy.deepcopy(self.preserved_attr_names))
29
+
30
+ class ObservedGraphModule(GraphModule):
31
+
32
+ def __init__(self, root: Union[torch.nn.Module, Dict[str, Any]], graph: Graph, preserved_attr_names: Set[str]):
33
+ self.preserved_attr_names = {
34
+ '_activation_post_process_map',
35
+ '_activation_post_process_indexes',
36
+ '_patterns',
37
+ '_node_name_to_qconfig',
38
+ '_prepare_custom_config',
39
+ '_equalization_node_name_to_qconfig',
40
+ '_node_name_to_scope',
41
+ '_qconfig_mapping',
42
+ '_is_qat',
43
+ '_observed_node_names'}.union(preserved_attr_names)
44
+ preserved_attrs = {attr: getattr(root, attr) for attr in self.preserved_attr_names if hasattr(root, attr)}
45
+ super().__init__(root, graph)
46
+ for attr in preserved_attrs:
47
+ setattr(self, attr, preserved_attrs[attr])
48
+
49
+ # GraphModule does not copy attributes which are not in the __dict__
50
+ # of vanilla nn.Module. So, we override __deepcopy__ in order
51
+ # to copy the quantization specific attributes correctly.
52
+ def __deepcopy__(self, memo):
53
+ fake_mod = torch.nn.Module()
54
+ fake_mod.__dict__ = copy.deepcopy(self.__dict__)
55
+ return ObservedGraphModule(fake_mod, copy.deepcopy(self.graph), copy.deepcopy(self.preserved_attr_names))
56
+
57
+ def _is_observed_module(module: Any) -> bool:
58
+ return hasattr(module, "meta") and "_observed_graph_module_attrs" in module.meta
59
+
60
+ def _get_observed_graph_module_attr(model: Union[torch.nn.Module, GraphModule], attr_name: str) -> Any:
61
+ if hasattr(model, "meta") and "_observed_graph_module_attrs" in model.meta: # type: ignore[operator, index]
62
+ return getattr(model.meta["_observed_graph_module_attrs"], attr_name) # type: ignore[index]
63
+ return None
64
+
65
+ class ObservedStandaloneGraphModule(ObservedGraphModule):
66
+ def __init__(self, root: Union[torch.nn.Module, Dict[str, Any]], graph: Graph, preserved_attr_names: Set[str]):
67
+ preserved_attr_names = preserved_attr_names.union({
68
+ "_standalone_module_input_quantized_idxs",
69
+ "_standalone_module_output_quantized_idxs"})
70
+ super().__init__(root, graph, preserved_attr_names)
71
+
72
+ def __deepcopy__(self, memo):
73
+ fake_mod = torch.nn.Module()
74
+ fake_mod.__dict__ = copy.deepcopy(self.__dict__)
75
+ return ObservedStandaloneGraphModule(fake_mod, copy.deepcopy(self.graph), copy.deepcopy(self.preserved_attr_names))
76
+
77
+ def _is_observed_standalone_module(module: Any) -> bool:
78
+ return _is_observed_module(module) and module.meta["_observed_graph_module_attrs"].is_observed_standalone_module
79
+
80
+ def _save_packed_weight(self, destination, prefix, keep_vars):
81
+ for attr_name in dir(self):
82
+ if "_packed_weight" in attr_name and \
83
+ isinstance(getattr(self, attr_name), torch._C.ScriptObject): # type: ignore[attr-defined]
84
+ packed_weight = getattr(self, attr_name)
85
+ destination[prefix + attr_name] = packed_weight
86
+
87
+ class QuantizedGraphModule(GraphModule):
88
+ """ This class is created to make sure PackedParams
89
+ (e.g. LinearPackedParams, Conv2dPackedParams) to appear in state_dict
90
+ so that we can serialize and deserialize quantized graph module with
91
+ torch.save(m.state_dict()) and m.load_state_dict(state_dict)
92
+ """
93
+ def __init__(self, root: Union[torch.nn.Module, Dict[str, Any]], graph: Graph, preserved_attr_names: Set[str]):
94
+ self.preserved_attr_names = preserved_attr_names
95
+ preserved_attrs = {attr: getattr(root, attr) for attr in self.preserved_attr_names if hasattr(root, attr)}
96
+ super().__init__(root, graph)
97
+ for attr in preserved_attrs:
98
+ setattr(self, attr, preserved_attrs[attr])
99
+ self._register_state_dict_hook(_save_packed_weight)
100
+
101
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
102
+ missing_keys, unexpected_keys, error_msgs):
103
+ attrs_to_pop = []
104
+ for attr_name in state_dict:
105
+ if attr_name.startswith("_packed_weight") and isinstance(state_dict[attr_name], torch._C.ScriptObject): # type: ignore[attr-defined] # noqa: B950
106
+ setattr(self, attr_name, state_dict[attr_name])
107
+ attrs_to_pop.append(attr_name)
108
+
109
+ # pop the packed param attributesn
110
+ for attr_name in attrs_to_pop:
111
+ state_dict.pop(attr_name)
112
+
113
+ super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
114
+
115
+
116
+ def __deepcopy__(self, memo):
117
+ fake_mod = torch.nn.Module()
118
+ fake_mod.__dict__ = copy.deepcopy(self.__dict__)
119
+ return QuantizedGraphModule(fake_mod, copy.deepcopy(self.graph), copy.deepcopy(self.preserved_attr_names))
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/lower_to_fbgemm.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._lower_to_native_backend import _lower_to_native_backend
2
+ from ..qconfig import QConfigAny
3
+ from torch.fx import GraphModule
4
+ from typing import Dict, Tuple
5
+
6
+ __all__ = ['lower_to_fbgemm']
7
+
8
+ def lower_to_fbgemm(
9
+ model: GraphModule,
10
+ qconfig_map: Dict[str, QConfigAny],
11
+ node_name_to_scope: Dict[str, Tuple[str, type]]
12
+ ) -> GraphModule:
13
+ """ Lower a quantized reference model (with reference quantized operator patterns)
14
+ to fbgemm
15
+ """
16
+ return _lower_to_native_backend(model, qconfig_map, node_name_to_scope)
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/lstm_utils.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import operator
3
+ import torch
4
+ from typing import Any, Callable, Optional, Tuple
5
+ from torch.ao.quantization import (
6
+ default_weight_observer,
7
+ default_weight_fake_quant,
8
+ FakeQuantizeBase,
9
+ QConfig,
10
+ QConfigMapping,
11
+ )
12
+ from torch.ao.quantization.backend_config import BackendConfig
13
+ from torch.ao.quantization.observer import _PartialWrapper
14
+ from torch.ao.quantization.quantize_fx import (
15
+ convert_to_reference_fx,
16
+ prepare_fx,
17
+ )
18
+
19
+ # TODO: move all LSTM util functions from fx/utils.py to this file
20
+ def _get_lstm_with_individually_observed_parts(
21
+ float_lstm: torch.nn.LSTM,
22
+ example_inputs: Tuple[Any, ...],
23
+ backend_config: Optional[BackendConfig] = None,
24
+ linear_output_obs_ctr: Optional[_PartialWrapper] = None,
25
+ sigmoid_obs_ctr: Optional[_PartialWrapper] = None,
26
+ tanh_obs_ctr: Optional[_PartialWrapper] = None,
27
+ cell_state_obs_ctr: Optional[_PartialWrapper] = None,
28
+ hidden_state_obs_ctr: Optional[_PartialWrapper] = None,
29
+ ) -> torch.ao.nn.quantizable.LSTM:
30
+ """
31
+ Return an observed `torch.ao.nn.quantizable.LSTM` created from a `torch.nn.LSTM`
32
+ with specific observers or fake quantizes assigned to the inner ops or submodules.
33
+
34
+ In both eager and FX graph mode quantization, `torch.ao.nn.quantizable.LSTM` is
35
+ used as an observed custom module, which is responsible for inserting its own
36
+ observers. By default, all inner ops inherit the parent custom module's QConfig.
37
+ Users who wish to override this behavior may extend `torch.ao.nn.quantizable.LSTM`
38
+ and use this helper function to customize the observer insertion logic.
39
+
40
+ This is meant to be used to convert a float module to an observed module in the
41
+ custom module flow.
42
+
43
+ Args:
44
+ `float_lstm`: The float LSTM module
45
+ `example_inputs`: example inputs for the forward function of the LSTM module
46
+ `backend_config`: BackendConfig to use to observe the LSTM module
47
+ `linear_output_obs_ctr`: observer or fake quantize for linear outputs Wx + b,
48
+ where W is the weight matrix, b is the bias, and x is either the inputs
49
+ or the hidden state from the previous layer (if any)
50
+ `sigmoid_obs_ctr`: observer or fake quantize for sigmoid activations
51
+ `tanh_obs_ctr`: observer or fake quantize for tanh activations
52
+ `cell_state_obs_ctr`: observer or fake quantize for the cell state
53
+ `hidden_state_obs_ctr`: observer or fake quantize for the hidden state and
54
+ the output
55
+
56
+ Return:
57
+ A `torch.ao.nn.quantizable.LSTM` with the specified observers or fake quantizes
58
+ assigned to the inner ops.
59
+ """
60
+ def make_qconfig(obs_ctr: _PartialWrapper) -> QConfig:
61
+ """
62
+ Make a QConfig with fixed qparams observers or fake quantizes.
63
+ """
64
+ if isinstance(obs_ctr(), FakeQuantizeBase):
65
+ weight = default_weight_fake_quant
66
+ else:
67
+ weight = default_weight_observer
68
+ return QConfig(activation=obs_ctr, weight=weight)
69
+
70
+ quantizable_lstm = torch.ao.nn.quantizable.LSTM(
71
+ float_lstm.input_size, float_lstm.hidden_size, float_lstm.num_layers, float_lstm.bias,
72
+ float_lstm.batch_first, float_lstm.dropout, float_lstm.bidirectional)
73
+ quantizable_lstm.qconfig = float_lstm.qconfig
74
+
75
+ for idx in range(float_lstm.num_layers):
76
+ quantizable_lstm.layers[idx] = torch.ao.nn.quantizable.modules.rnn._LSTMLayer.from_float(float_lstm,
77
+ idx,
78
+ float_lstm.qconfig,
79
+ batch_first=False)
80
+
81
+ # Build QConfigMapping for the LSTM cell
82
+ # Note: FloatFunctional qconfigs will be configured separately below
83
+ cell_qm = QConfigMapping().set_global(float_lstm.qconfig) # type: ignore[arg-type]
84
+ if sigmoid_obs_ctr is not None:
85
+ cell_qm.set_module_name("input_gate", make_qconfig(sigmoid_obs_ctr))
86
+ cell_qm.set_module_name("forget_gate", make_qconfig(sigmoid_obs_ctr))
87
+ cell_qm.set_module_name("output_gate", make_qconfig(sigmoid_obs_ctr))
88
+ if tanh_obs_ctr is not None:
89
+ cell_qm.set_module_name("cell_gate", make_qconfig(tanh_obs_ctr))
90
+
91
+ # Insert observers into each LSTM cell
92
+ # TODO: maybe make this work for layer_bw as well
93
+ for layer in quantizable_lstm.layers:
94
+ cell = layer.layer_fw.cell
95
+ cell = prepare_fx(cell, cell_qm, example_inputs, backend_config=backend_config)
96
+ # HACK: Manually replace the activation_post_process following these ops.
97
+ # This is needed for FloatFunctional ops because there is currently no way
98
+ # to configure these ops in FX graph mode quantization today. This is because
99
+ # the FloatFunctional modules simply disappear from the graph after tracing.
100
+ # In the future, we should rewrite quantizable LSTM without FloatFunctionals.
101
+ op_index_to_activation_post_process_ctr = {
102
+ (torch.add, 0): linear_output_obs_ctr, # gates.add
103
+ (torch.mul, 0): cell_state_obs_ctr, # fgate_cx.mul
104
+ (torch.mul, 1): cell_state_obs_ctr, # igate_cgate.mul
105
+ (torch.add, 1): cell_state_obs_ctr, # fgate_cx_igate_cgate.add
106
+ (torch.mul, 2): hidden_state_obs_ctr, # ogate_cy.mul
107
+ }
108
+ add_count = 0
109
+ mul_count = 0
110
+ for node in cell.graph.nodes:
111
+ op_index: Optional[Tuple[Callable, int]] = None # e.g. (torch.add, 1)
112
+ if node.target == torch.add:
113
+ op_index = (torch.add, add_count)
114
+ add_count += 1
115
+ elif node.target == torch.mul:
116
+ op_index = (torch.mul, mul_count)
117
+ mul_count += 1
118
+ else:
119
+ # Neither torch.add nor torch.mul
120
+ continue
121
+ if op_index not in op_index_to_activation_post_process_ctr:
122
+ continue
123
+ assert len(node.users) == 1
124
+ activation_post_process_name = next(iter(node.users.keys())).name
125
+ activation_post_process_ctr = op_index_to_activation_post_process_ctr[op_index]
126
+ if activation_post_process_ctr is not None:
127
+ setattr(cell, activation_post_process_name, activation_post_process_ctr())
128
+ layer.layer_fw.cell = cell
129
+ return quantizable_lstm
130
+
131
+ def _get_reference_quantized_lstm_module(
132
+ observed_lstm: torch.ao.nn.quantizable.LSTM,
133
+ backend_config: Optional[BackendConfig] = None,
134
+ ) -> torch.ao.nn.quantized.LSTM:
135
+ """
136
+ Return a `torch.ao.nn.quantized.LSTM` created from a `torch.ao.nn.quantizable.LSTM`
137
+ with observers or fake quantizes inserted through `prepare_fx`, e.g. from
138
+ `_get_lstm_with_individually_observed_parts`.
139
+
140
+ This is meant to be used to convert an observed module to a quantized module in the
141
+ custom module flow.
142
+
143
+ Args:
144
+ `observed_lstm`: a `torch.ao.nn.quantizable.LSTM` observed through `prepare_fx`
145
+ `backend_config`: BackendConfig to use to produce the reference quantized model
146
+
147
+ Return:
148
+ A reference `torch.ao.nn.quantized.LSTM` module.
149
+ """
150
+ quantized_lstm = torch.ao.nn.quantized.LSTM(
151
+ observed_lstm.input_size, observed_lstm.hidden_size, observed_lstm.num_layers,
152
+ observed_lstm.bias, observed_lstm.batch_first, observed_lstm.dropout,
153
+ observed_lstm.bidirectional)
154
+
155
+ for i, layer in enumerate(quantized_lstm.layers):
156
+ cell = copy.deepcopy(observed_lstm.layers.get_submodule(str(i)).layer_fw.cell) # type: ignore[union-attr]
157
+ cell = convert_to_reference_fx(cell, backend_config=backend_config) # type: ignore[arg-type]
158
+ assert isinstance(cell, torch.fx.GraphModule)
159
+ # HACK: Manually remove input quantize nodes and output dequantize nodes,
160
+ # since custom modules expect quint8 inputs and outputs for now. Note that
161
+ # this functionality is supposedly handled through PrepareCustomConfig's
162
+ # `set_input_quantized_indexes` and `set_output_quantized_indexes`, but that
163
+ # API doesn't currently handle tuple inputs and outputs, so we have to do
164
+ # this manually for now. In the future we should (1) relax the restriction
165
+ # on custom module input/output dtypes, and (2) expand support for complex
166
+ # input/output structures.
167
+ for node in cell.graph.nodes:
168
+ if node.target == torch.quantize_per_tensor:
169
+ arg = node.args[0]
170
+ # Remove quantize(x), quantize(hidden[0]), and quantize(hidden[1])
171
+ if arg.target == "x" or (arg.target == operator.getitem and arg.args[0].target == "hidden"):
172
+ with cell.graph.inserting_before(node):
173
+ node.replace_all_uses_with(arg)
174
+ cell.graph.erase_node(node)
175
+ if node.target == "output":
176
+ # Remove all dequantize nodes in the output tuple
177
+ for arg in node.args[0]:
178
+ with cell.graph.inserting_before(node):
179
+ node.replace_input_with(arg, arg.args[0])
180
+ cell.graph.eliminate_dead_code()
181
+ cell.recompile()
182
+ layer.layer_fw.cell = cell
183
+ return quantized_lstm
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/match_utils.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import torch
3
+ from torch.fx.graph import (
4
+ Graph,
5
+ Node,
6
+ )
7
+ from torch.ao.quantization.utils import Pattern
8
+ from .quantize_handler import (
9
+ QuantizeHandler,
10
+ )
11
+ from ..qconfig import (
12
+ QConfigAny,
13
+ )
14
+ from ..utils import (
15
+ MatchAllNode
16
+ )
17
+ from .graph_module import (
18
+ _is_observed_standalone_module,
19
+ )
20
+ from torch.nn.utils.parametrize import type_before_parametrizations
21
+ from typing import Any, Dict, List, Callable, Optional, Tuple, Type, Set, Iterable
22
+
23
+
24
+ __all__: List[str] = []
25
+
26
+ # TODO(future PR): the 1st argument is typed as `List[Node]`, but a better type
27
+ # would be a recursive `List[Union[Node, Tuple[Union[Node, ...]]]]`
28
+ _MatchResult = Tuple[Node, List[Node], Optional[Pattern], QuantizeHandler]
29
+
30
+ _MatchResultWithQConfig = Tuple[Node, List[Node], Optional[Pattern], QuantizeHandler,
31
+ QConfigAny]
32
+
33
+ # Note: The order of patterns is important! match function will take whatever is matched first, so we'll
34
+ # need to put the fusion patterns before single patterns. For example, add_relu should be registered come before relu.
35
+ # decorators are applied in the reverse order we see. Also when we match the nodes in the graph with these patterns,
36
+ # we'll start from the last node of the graph and traverse back.
37
+ def _is_match(modules, node, pattern, max_uses=sys.maxsize):
38
+ """ Matches a node in fx against a pattern
39
+ """
40
+ if isinstance(pattern, tuple):
41
+ self_match, *arg_matches = pattern
42
+ if self_match is getattr:
43
+ assert len(pattern) == 2, 'Expecting getattr pattern to have two elements'
44
+ arg_matches = []
45
+ else:
46
+ self_match = pattern
47
+ arg_matches = []
48
+
49
+ if isinstance(self_match, type) and issubclass(self_match, MatchAllNode):
50
+ return True
51
+
52
+ if node == pattern:
53
+ return True
54
+
55
+ if not isinstance(node, Node) or len(node.users) > max_uses:
56
+ return False
57
+
58
+ if isinstance(self_match, type) and issubclass(self_match, torch.nn.Module):
59
+ if node.op != 'call_module':
60
+ return False
61
+ if not type_before_parametrizations(modules[node.target]) == self_match:
62
+ return False
63
+ elif callable(self_match):
64
+ if node.op != 'call_function' or node.target is not self_match:
65
+ return False
66
+ elif node.target is getattr:
67
+ if node.args[1] != pattern[1]:
68
+ return False
69
+ elif isinstance(self_match, str):
70
+ if node.op != 'call_method' or node.target != self_match:
71
+ return False
72
+ elif node.target != self_match:
73
+ return False
74
+
75
+ if not arg_matches:
76
+ return True
77
+
78
+ if len(arg_matches) != len(node.args):
79
+ return False
80
+
81
+ return all(_is_match(modules, node, arg_match, max_uses=1) for node, arg_match in zip(node.args, arg_matches))
82
+
83
+ def _find_matches(
84
+ graph: Graph,
85
+ modules: Dict[str, torch.nn.Module],
86
+ patterns: Dict[Pattern, QuantizeHandler],
87
+ root_node_getter_mapping: Dict[Pattern, Callable],
88
+ standalone_module_names: Optional[List[str]] = None,
89
+ standalone_module_classes: Optional[List[Type]] = None,
90
+ custom_module_classes: Optional[List[Any]] = None) -> Dict[str, _MatchResult]:
91
+ """
92
+ Matches the nodes in the input graph to quantization patterns, and
93
+ outputs the information needed to quantize them in future steps.
94
+
95
+ Inputs:
96
+ - graph: an fx.Graph object
97
+ - modules: a mapping of fully qualified module name to instance,
98
+ for example, {'foo': ModuleFoo, ...}
99
+ - patterns: a mapping from a tuple of nodes in reverse order to
100
+ uninitialized QuantizeHandler subclass.
101
+
102
+ Outputs a map of
103
+ node_name ->
104
+ (node, matched_values, matched_pattern, QuantizeHandler instance,
105
+ qconfig)
106
+
107
+ For example, {
108
+ 'relu_1': (relu_1, [relu_1], torch.nn.functional.relu,
109
+ <CopyNodeQuantizeHandler instance>, QConfig(...)),
110
+ ...
111
+ }
112
+ """
113
+ if custom_module_classes is None:
114
+ custom_module_classes = []
115
+
116
+ if standalone_module_classes is None:
117
+ standalone_module_classes = []
118
+
119
+ if standalone_module_names is None:
120
+ standalone_module_names = []
121
+
122
+ match_map: Dict[str, _MatchResult] = {}
123
+ all_matched : Set[str] = set()
124
+
125
+ def _recursive_record_node_in_match_map(
126
+ last_node,
127
+ match_map,
128
+ node_pattern,
129
+ matched_node_pattern,
130
+ pattern,
131
+ match_value):
132
+ if isinstance(node_pattern, Node):
133
+ match_map[node_pattern.name] = (
134
+ last_node, matched_node_pattern, pattern, match_value)
135
+ elif not isinstance(node_pattern, Iterable):
136
+ return
137
+ else:
138
+ for n in node_pattern:
139
+ _recursive_record_node_in_match_map(last_node, match_map, n, matched_node_pattern, pattern, match_value)
140
+
141
+ # TODO: 1. merge with fuse matcher 2. document the code
142
+ def record_match(
143
+ pattern,
144
+ node,
145
+ last_node,
146
+ matched_node_pattern,
147
+ match_map):
148
+ if isinstance(pattern, tuple):
149
+ s, *args = pattern
150
+ is_single_arg = len(args) == 1
151
+ current_node_pattern: List[Node] = []
152
+ record_match(
153
+ s,
154
+ node,
155
+ last_node,
156
+ matched_node_pattern,
157
+ match_map)
158
+ if pattern[0] is not getattr:
159
+ for subpattern, arg in zip(args, node.args):
160
+ record_match(
161
+ subpattern,
162
+ arg,
163
+ node,
164
+ current_node_pattern,
165
+ match_map)
166
+ if len(current_node_pattern) > 1:
167
+ # current_node_pattern is the node pattern we get from matching
168
+ # the subpattern with arguments of the node
169
+ # we use is_single_arg to recover the original structure of the pattern
170
+ # if the original pattern has a single argument, we will have
171
+ # (original_op, (original_arg, ...))
172
+ # otherwise, we'll have a list of arguments
173
+ # (original_op, arg0, arg1, arg2, ...)
174
+ if is_single_arg:
175
+ matched_node_pattern.append(tuple(current_node_pattern))
176
+ else:
177
+ matched_node_pattern.extend(list(current_node_pattern))
178
+ else:
179
+ matched_node_pattern.append(current_node_pattern[0])
180
+ else:
181
+ matched_node_pattern.append(node)
182
+
183
+ for node in reversed(graph.nodes):
184
+ if node.name not in match_map and node.name not in all_matched:
185
+ for pattern, quantize_handler_cls in patterns.items():
186
+ root_node_getter = root_node_getter_mapping.get(pattern, None)
187
+ if _is_match(modules, node, pattern) and node.name not in match_map:
188
+ matched_node_pattern: List[Node] = []
189
+ record_match(
190
+ pattern,
191
+ node,
192
+ node,
193
+ matched_node_pattern,
194
+ match_map)
195
+ quantize_handler = quantize_handler_cls( # type: ignore[operator]
196
+ matched_node_pattern,
197
+ modules,
198
+ root_node_getter)
199
+ last_node = node
200
+ # record the match for all nodes in the pattern
201
+ _recursive_record_node_in_match_map(
202
+ last_node,
203
+ match_map,
204
+ # we need to record all nodes in the matched pattern in the match_map
205
+ matched_node_pattern,
206
+ # this is a part of the value corresponding to the node
207
+ matched_node_pattern,
208
+ pattern,
209
+ quantize_handler)
210
+ break
211
+
212
+ # add custom module instances to the match result
213
+ assert modules is not None
214
+ for node in graph.nodes:
215
+ if node.op == 'call_module' and \
216
+ type(modules[node.target]) in custom_module_classes:
217
+ match_map[node.name] = (
218
+ node, node, None, QuantizeHandler(node, modules, is_custom_module=True))
219
+
220
+ def is_standalone_module(node_target: str, modules: Dict[str, torch.nn.Module]):
221
+ assert modules is not None
222
+ return (
223
+ node_target in standalone_module_names or # type: ignore[operator]
224
+ type(modules[node_target]) in standalone_module_classes # type: ignore[operator]
225
+ )
226
+
227
+ # add standalone modules to the match
228
+ for node in graph.nodes:
229
+ if node.op == 'call_module' and \
230
+ (is_standalone_module(node.target, modules) or
231
+ _is_observed_standalone_module(modules[node.target])):
232
+ # add node to matched nodes
233
+ match_map[node.name] = (
234
+ node, node, None,
235
+ QuantizeHandler(node, modules, is_standalone_module=True))
236
+
237
+ return match_map
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/qconfig_mapping_utils.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import re
3
+ from collections import defaultdict, OrderedDict
4
+ from typing import Callable, Any, Dict, Tuple, Set, List, Union
5
+ from torch.ao.quantization import QConfig
6
+ from torch.ao.quantization.qconfig import _add_module_to_qconfig_obs_ctr, QConfigAny, qconfig_equals
7
+ from torch.ao.quantization.observer import (
8
+ _is_activation_post_process,
9
+ )
10
+ from torch.ao.quantization.backend_config import (
11
+ BackendConfig,
12
+ DTypeConfig,
13
+ )
14
+ from torch.ao.quantization.backend_config.utils import (
15
+ get_module_to_qat_module,
16
+ )
17
+
18
+ from torch.fx import (
19
+ GraphModule,
20
+ )
21
+ from torch.fx.graph import (
22
+ Graph,
23
+ )
24
+ from torch.ao.nn.intrinsic import _FusedModule
25
+
26
+ from ..utils import (
27
+ _parent_name,
28
+ get_qconfig_dtypes,
29
+ )
30
+ from ..qconfig_mapping import (
31
+ _OBJECT_TYPE_DICT_KEY,
32
+ _MODULE_NAME_DICT_KEY,
33
+ _MODULE_NAME_REGEX_DICT_KEY,
34
+ QConfigMapping,
35
+ )
36
+
37
+ __all__: List[str] = []
38
+
39
+
40
+
41
+ def _maybe_adjust_qconfig_for_module_name_object_type_order(
42
+ qconfig_mapping: QConfigMapping,
43
+ cur_module_path: str,
44
+ cur_object_type: Callable,
45
+ cur_object_type_idx: int,
46
+ fallback_qconfig: QConfigAny,
47
+ ) -> QConfigAny:
48
+ for (module_name, object_type, index), qconfig in qconfig_mapping.module_name_object_type_order_qconfigs.items():
49
+ if (
50
+ (module_name == cur_module_path) and
51
+ (object_type == cur_object_type) and
52
+ (index == cur_object_type_idx)
53
+ ):
54
+ return qconfig
55
+ return fallback_qconfig
56
+
57
+
58
+ def _update_qconfig_for_fusion(model: GraphModule, qconfig_mapping: QConfigMapping):
59
+ """
60
+ Update the QConfigMapping to account for fused modules such as LinearReLU.
61
+ This assumes the QConfigMapping's attributes have already been converted to OrderedDicts.
62
+ """
63
+ object_type_dict = qconfig_mapping.object_type_qconfigs
64
+ if len(object_type_dict) == 0:
65
+ return qconfig_mapping
66
+
67
+ modules = dict(model.named_modules())
68
+
69
+ for node in model.graph.nodes:
70
+ if node.op == 'call_module' and node.target in modules:
71
+ maybe_fused_module = modules[str(node.target)]
72
+ if not isinstance(maybe_fused_module, _FusedModule):
73
+ continue
74
+
75
+ ops = list(maybe_fused_module._modules.values())
76
+ fused_qconfig = object_type_dict.get(type(ops[0]), None)
77
+
78
+ # Raise an error if the modules in the fused module have
79
+ # different qconfigs specified in the qconfig_dict
80
+ # TODO: currently it only works for modules,
81
+ # need to make this work for torch.nn.functional.relu
82
+ # TODO: currently it only works for object_type configurations,
83
+ # ideally it should work for different types of configurations,
84
+ # maybe we want to redesign this part
85
+ for op in ops[1:]:
86
+ if not qconfig_equals(object_type_dict.get(type(op), None), fused_qconfig):
87
+ raise LookupError(
88
+ "During fusion, we need to specify the same " +
89
+ f"qconfigs for all module types in {type(maybe_fused_module)} " +
90
+ f"offending type: {type(op)}")
91
+
92
+ if fused_qconfig is not None:
93
+ object_type_dict[type(maybe_fused_module)] = fused_qconfig
94
+
95
+ def _generate_node_name_to_qconfig(
96
+ root: torch.nn.Module,
97
+ modules: Dict[str, torch.nn.Module],
98
+ input_graph: Graph,
99
+ qconfig_mapping: QConfigMapping,
100
+ node_name_to_scope: Dict[str, Tuple[str, type]]) -> Dict[str, QConfigAny]:
101
+ global_qconfig = qconfig_mapping.global_qconfig
102
+ node_name_to_qconfig = {}
103
+
104
+ # example:
105
+ #
106
+ # {'foo.bar': {F.linear: 0, F.conv2d: 1, ...}, ...}
107
+ #
108
+ # meaning in submodule 'foo.bar', we have seen 0 F.linear and
109
+ # 1 F.conv2d invocations so far.
110
+ submodule_to_object_type_to_cur_idx: Dict[str, Dict[Callable, int]] = \
111
+ defaultdict(lambda: defaultdict(int))
112
+ for node in input_graph.nodes:
113
+ qconfig = None
114
+ if node.op == "get_attr":
115
+ module_name, _ = _parent_name(node.target)
116
+ qconfig = _maybe_adjust_qconfig_for_module_type_or_name(
117
+ qconfig_mapping, type(modules[module_name]), module_name, global_qconfig)
118
+ qconfig_with_device_check = _add_module_to_qconfig_obs_ctr(qconfig, modules.get(node.target, None))
119
+ elif node.op == "call_function":
120
+ # precedence: module_name_qconfig
121
+ # > function_qconfig > global_qconfig
122
+ # module_name takes precedence over function qconfig
123
+ function_qconfig = _get_object_type_qconfig(
124
+ qconfig_mapping, node.target, global_qconfig)
125
+ module_path, module_type = node_name_to_scope[node.name]
126
+ qconfig = _maybe_adjust_qconfig_for_module_type_or_name(
127
+ qconfig_mapping, module_type, module_path, function_qconfig)
128
+
129
+ cur_object_type_idx = \
130
+ submodule_to_object_type_to_cur_idx[module_path][node.target]
131
+ submodule_to_object_type_to_cur_idx[module_path][node.target] += 1
132
+ qconfig = _maybe_adjust_qconfig_for_module_name_object_type_order(
133
+ qconfig_mapping, module_path, node.target, cur_object_type_idx, qconfig)
134
+ qconfig_with_device_check = _add_module_to_qconfig_obs_ctr(qconfig, modules.get(node.target, None))
135
+
136
+ elif node.op == "call_method":
137
+ module_path, module_type = node_name_to_scope[node.name]
138
+ # first use node.target (string) to get the qconfig
139
+ # this is to support configs like
140
+ # "object_type": [("reshape", qconfig)]
141
+ qconfig = _maybe_adjust_qconfig_for_module_type_or_name(
142
+ qconfig_mapping, node.target, module_path, global_qconfig)
143
+ # if there is no special config for the method, we'll fall back to the
144
+ # config for the module that contains the call_method node
145
+ qconfig = _maybe_adjust_qconfig_for_module_type_or_name(
146
+ qconfig_mapping, module_type, module_path, qconfig)
147
+ # currently call_method does not support modifying qconfig
148
+ # by order, we can add this later if it is needed.
149
+ qconfig_with_device_check = _add_module_to_qconfig_obs_ctr(qconfig, modules.get(node.target, None))
150
+
151
+ elif node.op == 'call_module':
152
+ # if the node is an observer, just continue - don't add it to the qconfig_map
153
+ if _is_activation_post_process(modules[node.target]):
154
+ continue
155
+ qconfig = _maybe_adjust_qconfig_for_module_type_or_name(
156
+ qconfig_mapping, type(modules[node.target]), node.target, global_qconfig)
157
+
158
+ module_path, module_type = node_name_to_scope[node.name]
159
+ # Note: for call_module, the module_path is the current module's name.
160
+ # to meaningfully count invocations, we need to count them in the parent
161
+ # module.
162
+ parent_name, _ = _parent_name(module_path)
163
+ cur_object_type_idx = \
164
+ submodule_to_object_type_to_cur_idx[parent_name][module_type]
165
+ submodule_to_object_type_to_cur_idx[parent_name][module_type] += 1
166
+ qconfig = _maybe_adjust_qconfig_for_module_name_object_type_order(
167
+ qconfig_mapping, parent_name, module_type, cur_object_type_idx,
168
+ qconfig)
169
+ qconfig_with_device_check = _add_module_to_qconfig_obs_ctr(qconfig, modules.get(node.target, None))
170
+
171
+ # regex is not supported eager mode propagate_qconfig_, we'll
172
+ # need to set the qconfig explicitly here in case regex
173
+ # is used
174
+ modules[node.target].qconfig = qconfig_with_device_check
175
+ else:
176
+ qconfig_with_device_check = None
177
+
178
+ node_name_to_qconfig[node.name] = qconfig_with_device_check
179
+ return node_name_to_qconfig
180
+
181
+
182
+ def _check_is_valid_config_dict(config_dict: Any, allowed_keys: Set[str], dict_name: str) -> None:
183
+ r""" Checks if the given config_dict has the correct keys
184
+
185
+ Args:
186
+ `config_dict`: dictionary whose keys we want to check
187
+ """
188
+
189
+ for k in config_dict.keys():
190
+ if k not in allowed_keys:
191
+ raise ValueError(
192
+ 'Expected ' + dict_name + ' to have the following keys: ' +
193
+ str(allowed_keys) + '. But found \'' + k +
194
+ '\' instead.')
195
+
196
+
197
+ def _compare_prepare_convert_qconfig_mappings(
198
+ prepare_qconfig_mapping: QConfigMapping,
199
+ convert_qconfig_mapping: QConfigMapping):
200
+ r""" Compare the qconfig_mapping passed in convert to the one from prepare and check the values
201
+
202
+ Args:
203
+ `prepare_qconfig_mapping`: configuration for prepare quantization step
204
+ `convert_qconfig_mapping`: configuration for convert quantization step
205
+ """
206
+ assert qconfig_equals(prepare_qconfig_mapping.global_qconfig, convert_qconfig_mapping.global_qconfig), \
207
+ "Expected global qconfigs to be the same in the prepare and convert quantization configs"
208
+ prepare_dicts: List[OrderedDict] = [
209
+ prepare_qconfig_mapping.object_type_qconfigs,
210
+ prepare_qconfig_mapping.module_name_qconfigs,
211
+ prepare_qconfig_mapping.module_name_regex_qconfigs,
212
+ ]
213
+ convert_dicts: List[OrderedDict] = [
214
+ convert_qconfig_mapping.object_type_qconfigs,
215
+ convert_qconfig_mapping.module_name_qconfigs,
216
+ convert_qconfig_mapping.module_name_regex_qconfigs,
217
+ ]
218
+ dict_names = [_OBJECT_TYPE_DICT_KEY, _MODULE_NAME_DICT_KEY, _MODULE_NAME_REGEX_DICT_KEY]
219
+ for i in range(len(prepare_dicts)):
220
+ for name in prepare_dicts[i].keys():
221
+ assert name in convert_dicts[i], f"Missing key {dict_names[i]} {name} in convert QConfigMapping \
222
+ when it was present in prepare"
223
+ assert convert_dicts[i][name] is None \
224
+ or qconfig_equals(prepare_dicts[i][name], convert_dicts[i][name]), \
225
+ f"Expected convert QConfigMapping to have the same qconfig as prepare for key {dict_names[i]} {name}; \
226
+ prepare: {prepare_dicts[i][name]}; convert: {convert_dicts[i][name]}"
227
+
228
+ def _is_qconfig_supported_by_dtype_configs(qconfig: QConfig, dtype_configs: List[DTypeConfig]):
229
+ for dtype_config in dtype_configs:
230
+ is_dynamic = dtype_config.is_dynamic
231
+ if is_dynamic is None:
232
+ is_dynamic = False
233
+ input_dtype = dtype_config.input_dtype or torch.float
234
+ weight_dtype = dtype_config.weight_dtype or torch.float
235
+ bias_dtype = dtype_config.bias_dtype or torch.float
236
+ output_dtype = dtype_config.output_dtype or torch.float
237
+ qconfig_activation_dtype, qconfig_weight_dtype, qconfig_input_act_is_dynamic = \
238
+ get_qconfig_dtypes(qconfig)
239
+ qconfig_bias_dtype = torch.float16 \
240
+ if (
241
+ qconfig_activation_dtype == torch.float16
242
+ and qconfig_weight_dtype == torch.float16
243
+ and not is_dynamic
244
+ ) else torch.float
245
+
246
+ if is_dynamic:
247
+ is_match = qconfig_input_act_is_dynamic and \
248
+ input_dtype == qconfig_activation_dtype and \
249
+ output_dtype == torch.float and \
250
+ weight_dtype == qconfig_weight_dtype
251
+ else:
252
+ is_match = input_dtype == qconfig_activation_dtype and \
253
+ output_dtype == qconfig_activation_dtype and \
254
+ weight_dtype == qconfig_weight_dtype and \
255
+ bias_dtype == qconfig_bias_dtype
256
+ if is_match:
257
+ return True
258
+ return False
259
+
260
+ def _get_object_type_qconfig(
261
+ qconfig_mapping: QConfigMapping,
262
+ object_type: Union[Callable, str],
263
+ fallback_qconfig: QConfigAny) -> QConfigAny:
264
+ return qconfig_mapping.object_type_qconfigs.get(object_type, fallback_qconfig)
265
+
266
+
267
+ def _get_module_name_regex_qconfig(qconfig_mapping, module_name, fallback_qconfig):
268
+ for regex_pattern, qconfig in qconfig_mapping.module_name_regex_qconfigs.items():
269
+ if re.match(regex_pattern, module_name):
270
+ # first match wins
271
+ return qconfig
272
+ return fallback_qconfig
273
+
274
+
275
+ def _get_module_name_qconfig(qconfig_mapping, module_name, fallback_qconfig):
276
+ if module_name == '':
277
+ # module name qconfig not found
278
+ return fallback_qconfig
279
+ if module_name in qconfig_mapping.module_name_qconfigs:
280
+ return qconfig_mapping.module_name_qconfigs[module_name]
281
+ else:
282
+ parent, _ = _parent_name(module_name)
283
+ return _get_module_name_qconfig(qconfig_mapping, parent, fallback_qconfig)
284
+
285
+
286
+ def _maybe_adjust_qconfig_for_module_type_or_name(qconfig_mapping, module_type, module_name, global_qconfig):
287
+ # get qconfig for module_name,
288
+ # fallback to module_name_regex_qconfig, module_type_qconfig,
289
+ # global_qconfig if necessary
290
+ module_type_qconfig = _get_object_type_qconfig(
291
+ qconfig_mapping, module_type, global_qconfig)
292
+ module_name_regex_qconfig = _get_module_name_regex_qconfig(
293
+ qconfig_mapping, module_name, module_type_qconfig)
294
+ module_name_qconfig = _get_module_name_qconfig(
295
+ qconfig_mapping, module_name, module_name_regex_qconfig)
296
+ return module_name_qconfig
297
+
298
+
299
+ def _get_flattened_qconfig_dict(qconfig_mapping: QConfigMapping) -> Dict[Union[Callable, str], QConfigAny]:
300
+ """ flatten the global, object_type and module_name qconfig
301
+ to the same qconfig_dict so that it can be used by
302
+ propagate_qconfig_ function.
303
+ "module_name_regex" is ignored for now since it's not supported
304
+ in propagate_qconfig_, but it can be fixed later.
305
+
306
+ For example:
307
+ Input: {
308
+ "": qconfig,
309
+ "object_type": [
310
+ (torch.add, qconfig)
311
+ ],
312
+ "module_name": [
313
+ ("conv", qconfig)
314
+ ]
315
+ }
316
+
317
+ Output: {
318
+ "": qconfig,
319
+ torch.add: qconfig,
320
+ "conv": qconfig
321
+ }
322
+ """
323
+ flattened: Dict[Union[Callable, str], QConfigAny] = {"": qconfig_mapping.global_qconfig}
324
+ for obj, qconfig in qconfig_mapping.object_type_qconfigs.items():
325
+ flattened[obj] = qconfig
326
+ for obj, qconfig in qconfig_mapping.module_name_qconfigs.items():
327
+ flattened[obj] = qconfig
328
+ return flattened
329
+
330
+
331
+ def _update_qconfig_for_qat(
332
+ qconfig_mapping: QConfigMapping,
333
+ backend_config: BackendConfig):
334
+ """
335
+ Update the qconfig_mapping to account for module swaps during QAT.
336
+ During QAT we perform a module swap on the nn.Module types to the corresponding nn.qat.modules types.
337
+ """
338
+ module_to_qat_module_class = get_module_to_qat_module(backend_config)
339
+ object_type_dict = qconfig_mapping.object_type_qconfigs
340
+ new_object_type_dict = object_type_dict.copy()
341
+ for k, v in new_object_type_dict.items():
342
+ if k in module_to_qat_module_class:
343
+ object_type_dict[module_to_qat_module_class[k]] = v
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/tracer.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.fx._symbolic_trace import Tracer
3
+ from torch.fx.proxy import Scope
4
+ from torch.ao.nn.intrinsic import _FusedModule
5
+ from typing import List, Callable
6
+
7
+ __all__ = [
8
+ "QuantizationTracer",
9
+ ]
10
+
11
+ class ScopeContextManager(torch.fx.proxy.ScopeContextManager):
12
+ def __init__(
13
+ self,
14
+ scope: Scope,
15
+ current_module: torch.nn.Module,
16
+ current_module_path: str
17
+ ):
18
+ super().__init__(scope, Scope(current_module_path, type(current_module)))
19
+
20
+
21
+ class QuantizationTracer(Tracer):
22
+ def __init__(
23
+ self, skipped_module_names: List[str], skipped_module_classes: List[Callable]
24
+ ):
25
+ super().__init__()
26
+ self.skipped_module_names = skipped_module_names
27
+ self.skipped_module_classes = skipped_module_classes
28
+ # NB: initialized the module_type of top level module to None
29
+ # we are assuming people won't configure the model with the type of top level
30
+ # module here, since people can use "" for global config
31
+ # We can change this if there is a use case that configures
32
+ # qconfig using top level module type
33
+ self.scope = Scope("", None)
34
+ self.record_stack_traces = True
35
+
36
+ def is_leaf_module(self, m: torch.nn.Module, module_qualified_name: str) -> bool:
37
+ return (
38
+ (
39
+ (m.__module__.startswith("torch.nn") or m.__module__.startswith("torch.ao.nn"))
40
+ and not isinstance(m, torch.nn.Sequential)
41
+ )
42
+ or module_qualified_name in self.skipped_module_names
43
+ or type(m) in self.skipped_module_classes
44
+ or isinstance(m, _FusedModule)
45
+ )
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fx/utils.py ADDED
@@ -0,0 +1,885 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.ao.quantization import (
5
+ QConfigAny,
6
+ QuantType,
7
+ )
8
+ from torch.ao.quantization.backend_config import (
9
+ DTypeWithConstraints,
10
+ )
11
+ from torch.ao.quantization.fake_quantize import (
12
+ FakeQuantizeBase,
13
+ FixedQParamsFakeQuantize,
14
+ )
15
+ from torch.ao.quantization.observer import (
16
+ FixedQParamsObserver,
17
+ ObserverBase,
18
+ )
19
+ from torch.ao.quantization.qconfig import (
20
+ float16_static_qconfig,
21
+ float16_dynamic_qconfig,
22
+ qconfig_equals,
23
+ )
24
+ from torch.ao.quantization.stubs import DeQuantStub
25
+ from torch.ao.quantization.utils import (
26
+ activation_is_statically_quantized,
27
+ )
28
+ from torch.ao.quantization.observer import _is_activation_post_process
29
+ from torch.ao.quantization.qconfig_mapping import QConfigMapping
30
+
31
+ from torch.fx import GraphModule, map_arg
32
+
33
+ from torch.fx.graph import (
34
+ Graph,
35
+ Node,
36
+ )
37
+ from .custom_config import PrepareCustomConfig
38
+ # importing the lib so that the quantized_decomposed ops are registered
39
+ from ._decomposed import quantized_decomposed_lib # noqa: F401
40
+
41
+ from typing import Callable, Optional, List, Dict, Any, Set, Tuple, Union, Type
42
+ from dataclasses import dataclass
43
+ from collections import namedtuple
44
+ import operator
45
+ import warnings
46
+
47
+ # TODO: revisit this list. Many helper methods shouldn't be public
48
+ __all__ = [
49
+ "all_node_args_except_first",
50
+ "all_node_args_have_no_tensors",
51
+ "assert_and_get_unique_device",
52
+ "collect_producer_nodes",
53
+ "create_getattr_from_value",
54
+ "create_node_from_old_node_preserve_meta",
55
+ "EMPTY_ARG_DICT",
56
+ "get_custom_module_class_keys",
57
+ "get_linear_prepack_op_for_dtype",
58
+ "get_new_attr_name_with_prefix",
59
+ "get_non_observable_arg_indexes_and_types",
60
+ "get_qconv_prepack_op",
61
+ "get_skipped_module_name_and_classes",
62
+ "graph_module_from_producer_nodes",
63
+ "maybe_get_next_module",
64
+ "NodeInfo",
65
+ "node_arg_is_bias",
66
+ "node_arg_is_weight",
67
+ "NON_OBSERVABLE_ARG_DICT",
68
+ "NON_QUANTIZABLE_WEIGHT_OPS",
69
+ "return_arg_list",
70
+ "ObservedGraphModuleAttrs",
71
+ ]
72
+
73
+ NON_QUANTIZABLE_WEIGHT_OPS = {torch.nn.functional.layer_norm, torch.nn.functional.group_norm, torch.nn.functional.instance_norm}
74
+
75
+ @dataclass
76
+ class ObservedGraphModuleAttrs:
77
+ node_name_to_qconfig: Dict[str, QConfigAny]
78
+ node_name_to_scope: Dict[str, Tuple[str, type]]
79
+ prepare_custom_config: PrepareCustomConfig
80
+ equalization_node_name_to_qconfig: Dict[str, Any]
81
+ qconfig_mapping: QConfigMapping
82
+ is_qat: bool
83
+ observed_node_names: Set[str]
84
+ is_observed_standalone_module: bool = False
85
+ standalone_module_input_quantized_idxs: Optional[List[int]] = None
86
+ standalone_module_output_quantized_idxs: Optional[List[int]] = None
87
+
88
+ def node_arg_is_weight(node: Node, arg: Any) -> bool:
89
+ """Returns if node arg is weight"""
90
+ weight_index = None
91
+ if "target_dtype_info" in node.meta:
92
+ weight_index = node.meta["target_dtype_info"].get("weight_index", None)
93
+ if weight_index is not None and weight_index < len(node.args) and node.args[weight_index] is arg:
94
+ return True
95
+ return node.kwargs.get("weight") is arg
96
+
97
+ def node_arg_is_bias(node: Node, arg: Any) -> bool:
98
+ """Returns if node arg is bias"""
99
+ bias_index = None
100
+ if "target_dtype_info" in node.meta:
101
+ bias_index = node.meta["target_dtype_info"].get("bias_index", None)
102
+ if bias_index is not None and bias_index < len(node.args) and node.args[bias_index] is arg:
103
+ return True
104
+ return node.kwargs.get("bias") is arg
105
+
106
+ def get_custom_module_class_keys(custom_module_mapping: Dict[QuantType, Dict[Type, Type]]) -> List[Any]:
107
+ r""" Get all the unique custom module keys in the custom config dict
108
+ e.g.
109
+ Input:
110
+ {
111
+ QuantType.STATIC: {
112
+ CustomModule1: ObservedCustomModule
113
+ },
114
+ QuantType.DYNAMIC: {
115
+ CustomModule2: DynamicObservedCustomModule
116
+ },
117
+ QuantType.WEIGHT_ONLY: {
118
+ CustomModule3: WeightOnlyObservedCustomModule
119
+ },
120
+ }
121
+
122
+ Output:
123
+ # extract the keys across all inner STATIC, DYNAMIC, and WEIGHT_ONLY dicts
124
+ [CustomModule1, CustomModule2, CustomModule3]
125
+ """
126
+ # using set to dedup
127
+ float_custom_module_classes : Set[Any] = set()
128
+ for quant_mode in [QuantType.STATIC, QuantType.DYNAMIC, QuantType.WEIGHT_ONLY]:
129
+ quant_mode_custom_module_config = custom_module_mapping.get(quant_mode, {})
130
+ quant_mode_custom_module_classes = set(quant_mode_custom_module_config.keys())
131
+ float_custom_module_classes |= quant_mode_custom_module_classes
132
+ return list(float_custom_module_classes)
133
+
134
+ def get_linear_prepack_op_for_dtype(dtype):
135
+ if dtype == torch.float16:
136
+ return torch.ops.quantized.linear_prepack_fp16
137
+ elif dtype == torch.qint8:
138
+ return torch.ops.quantized.linear_prepack
139
+ else:
140
+ raise Exception("can't get linear prepack op for dtype:", dtype)
141
+
142
+ def get_qconv_prepack_op(conv_op: Callable) -> Callable:
143
+ prepack_ops = {
144
+ torch.nn.functional.conv1d: torch.ops.quantized.conv1d_prepack,
145
+ torch.nn.functional.conv2d: torch.ops.quantized.conv2d_prepack,
146
+ torch.nn.functional.conv3d: torch.ops.quantized.conv3d_prepack,
147
+ torch.nn.functional.conv_transpose1d: torch.ops.quantized.conv_transpose1d_prepack,
148
+ torch.nn.functional.conv_transpose2d: torch.ops.quantized.conv_transpose2d_prepack,
149
+ torch.nn.functional.conv_transpose3d: torch.ops.quantized.conv_transpose3d_prepack,
150
+ }
151
+ prepack_op = prepack_ops.get(conv_op, None)
152
+ assert prepack_op, f"Didn't find prepack op for {conv_op}"
153
+ return prepack_op
154
+
155
+ # Returns a function that can get a new attribute name for module with given
156
+ # prefix, for example,
157
+ # >> get_new_observer_name = get_new_attr_name_with_prefix('_observer')
158
+ # >> new_name = get_new_observer_name(module)
159
+ # new_name will be an unused attribute name on module, e.g. `_observer_1`
160
+ def get_new_attr_name_with_prefix(prefix: str) -> Callable:
161
+ prefix = prefix.replace(".", "_")
162
+
163
+ def get_new_attr_name(module: torch.nn.Module):
164
+ def get_attr_name(i: int):
165
+ return prefix + str(i)
166
+ i = 0
167
+ attr_name = get_attr_name(i)
168
+ while hasattr(module, attr_name):
169
+ i += 1
170
+ attr_name = get_attr_name(i)
171
+ return attr_name
172
+ return get_new_attr_name
173
+
174
+ def collect_producer_nodes(node: Node) -> Optional[List[Node]]:
175
+ r''' Starting from a target node, trace back until we hit inpu or
176
+ getattr node. This is used to extract the chain of operators
177
+ starting from getattr to the target node, for example
178
+ def forward(self, x):
179
+ observed = self.observer(self.weight)
180
+ return F.linear(x, observed)
181
+ collect_producer_nodes(observed) will either return a list of nodes that
182
+ produces the observed node or None if we can't extract a self contained
183
+ graph without free variables(inputs of the forward function).
184
+ '''
185
+ nodes = [node]
186
+ frontier = [node]
187
+ while frontier:
188
+ node = frontier.pop()
189
+ all_args = list(node.args) + list(node.kwargs.values())
190
+ for arg in all_args:
191
+ if not isinstance(arg, Node):
192
+ continue
193
+ if arg.op == 'placeholder':
194
+ # hit input, can't fold in this case
195
+ return None
196
+ nodes.append(arg)
197
+ if not (arg.op == 'call_function' and arg.target == getattr):
198
+ frontier.append(arg)
199
+ return nodes
200
+
201
+ def graph_module_from_producer_nodes(
202
+ root: GraphModule, producer_nodes: List[Node]) -> GraphModule:
203
+ r''' Construct a graph module from extracted producer nodes
204
+ from `collect_producer_nodes` function
205
+ Args:
206
+ root: the root module for the original graph
207
+ producer_nodes: a list of nodes we use to construct the graph
208
+ Return:
209
+ A graph module constructed from the producer nodes
210
+ '''
211
+ assert len(producer_nodes) > 0, 'list of producer nodes can not be empty'
212
+ # since we traced back from node to getattr
213
+ producer_nodes.reverse()
214
+ graph = Graph()
215
+ env: Dict[Any, Any] = {}
216
+
217
+ def load_arg(a):
218
+ return map_arg(a, lambda node: env[node])
219
+ for producer_node in producer_nodes:
220
+ env[producer_node] = graph.node_copy(producer_node, load_arg)
221
+ graph.output(load_arg(producer_nodes[-1]))
222
+ graph_module = GraphModule(root, graph)
223
+ return graph_module
224
+
225
+ def assert_and_get_unique_device(module: torch.nn.Module) -> Any:
226
+ """
227
+ Returns the unique device for a module, or None if no device is found.
228
+ Throws an error if multiple devices are detected.
229
+ """
230
+ devices = {p.device for p in module.parameters()} | \
231
+ {p.device for p in module.buffers()}
232
+ """
233
+ As a temp workaround for AIMP HHC publish we added CPU check.remove it later. T163614564
234
+ """
235
+ if {torch.device("cpu"), torch.device("meta")} == devices:
236
+ warnings.warn("Both 'meta' and 'cpu' are present in the list of devices. Module can have one device. We Select 'cpu'.")
237
+ devices = {torch.device("cpu")}
238
+ ""
239
+ assert len(devices) <= 1, (
240
+ "prepare only works with cpu or single-device CUDA modules, "
241
+ f"but got devices {devices}"
242
+ )
243
+ device = next(iter(devices)) if len(devices) > 0 else None
244
+ return device
245
+
246
+ def create_getattr_from_value(module: torch.nn.Module, graph: Graph, prefix: str, value: Any) -> Node:
247
+ """
248
+ Given a value of any type, creates a getattr node corresponding to the value and
249
+ registers the value as a buffer to the module.
250
+ """
251
+ get_new_attr_name = get_new_attr_name_with_prefix(prefix)
252
+ attr_name = get_new_attr_name(module)
253
+ device = assert_and_get_unique_device(module)
254
+ new_value = value.clone().detach() if isinstance(value, torch.Tensor) \
255
+ else torch.tensor(value, device=device)
256
+ module.register_buffer(attr_name, new_value)
257
+ # Create get_attr with value
258
+ attr_node = graph.create_node("get_attr", attr_name)
259
+ return attr_node
260
+
261
+ def all_node_args_have_no_tensors(node: Node, modules: Dict[str, torch.nn.Module], cache: Dict[Node, bool]) -> bool:
262
+ """
263
+ If we know for sure that all of this node's args have no
264
+ tensors (are primitives), return True. If we either
265
+ find a tensor or are not sure, return False. Note: this
266
+ function is not exact.
267
+ """
268
+ if cache and node in cache:
269
+ return cache[node]
270
+
271
+ result = False # will be overwritten
272
+ if not isinstance(node, Node):
273
+ result = True
274
+ elif node.op == 'placeholder':
275
+ result = False
276
+ elif node.op == 'call_module':
277
+ assert isinstance(node.target, str)
278
+ if _is_activation_post_process(modules[node.target]):
279
+ result = all_node_args_have_no_tensors(node.args[0], modules, cache) # type: ignore[arg-type]
280
+ elif node.op == 'call_module':
281
+ result = False
282
+ elif node.op == 'call_function' and node.target is operator.getitem:
283
+ result = all_node_args_have_no_tensors(node.args[0], modules, cache) # type: ignore[arg-type]
284
+ elif node.op == 'get_attr':
285
+ result = False
286
+ elif node.target is getattr and node.args[1] in ['ndim', 'shape']:
287
+ # x1 = x0.ndim
288
+ result = True
289
+ elif node.op == 'call_method' and node.target == 'size':
290
+ # x1 = x0.size(0)
291
+ result = True
292
+ else:
293
+ found_one_tensor = False
294
+ for arg in node.args:
295
+ if isinstance(arg, list):
296
+ for list_el in arg:
297
+ if isinstance(list_el, Node):
298
+ this_list_el_args_have_no_tensors = \
299
+ all_node_args_have_no_tensors(list_el, modules, cache)
300
+ found_one_tensor = found_one_tensor or \
301
+ (not this_list_el_args_have_no_tensors)
302
+ # If found_one_tensor is True, there is no point in
303
+ # recursing further as the end result will always
304
+ # be True.
305
+ # TODO(future PR): remove this entire function and
306
+ # change to dtype inference without recursion.
307
+ if found_one_tensor:
308
+ result = not found_one_tensor
309
+ if cache:
310
+ cache[node] = result
311
+ return result
312
+ elif isinstance(arg, int):
313
+ pass
314
+ else:
315
+ if isinstance(arg, Node):
316
+ this_arg_args_have_no_tensors = all_node_args_have_no_tensors(arg, modules, cache)
317
+ found_one_tensor = found_one_tensor or \
318
+ (not this_arg_args_have_no_tensors)
319
+ # If found_one_tensor is True, there is no point in
320
+ # recursing further as the end result will always
321
+ # be True.
322
+ # TODO(future PR): remove this entire function and
323
+ # change to dtype inference without recursion.
324
+ if found_one_tensor:
325
+ result = not found_one_tensor
326
+ if cache:
327
+ cache[node] = result
328
+ return result
329
+ else:
330
+ found_one_tensor = True
331
+ result = not found_one_tensor
332
+ if cache:
333
+ cache[node] = result
334
+ return result
335
+
336
+ def all_node_args_except_first(node: Node) -> List[int]:
337
+ """
338
+ Returns all node arg indices after first
339
+ """
340
+ return list(range(1, len(node.args)))
341
+
342
+ def return_arg_list(arg_indices: List[int]) -> Callable[[Node], List[int]]:
343
+ """
344
+ Constructs a function that takes a node as arg and returns the arg_indices
345
+ that are valid for node.args
346
+ """
347
+ def arg_indices_func(node: Node) -> List[int]:
348
+ return [i for i in arg_indices if i < len(node.args)]
349
+ return arg_indices_func
350
+
351
+ NodeInfo = namedtuple("NodeInfo", "op target")
352
+
353
+ # this dict identifies which indices of a node are non tensors
354
+ # so that they can be propagated correctly since inserting observers
355
+ # for them would cause errors
356
+
357
+ NON_OBSERVABLE_ARG_DICT: Dict[NodeInfo, Dict[Union[type, torch.dtype], Callable[[Node], List[int]]]] = {
358
+ NodeInfo("call_method", "masked_fill") : {
359
+ torch.bool: return_arg_list([1]),
360
+ float: return_arg_list([2])
361
+ },
362
+ NodeInfo("call_method", "permute") : {
363
+ int: all_node_args_except_first
364
+ },
365
+ NodeInfo("call_method", "repeat") : {
366
+ int: all_node_args_except_first
367
+ },
368
+ NodeInfo("call_method", "reshape") : {
369
+ int: all_node_args_except_first
370
+ },
371
+ NodeInfo("call_method", "size") : {
372
+ int: return_arg_list([1])
373
+ },
374
+ NodeInfo("call_method", "transpose") : {
375
+ int: all_node_args_except_first
376
+ },
377
+ NodeInfo("call_method", torch.transpose) : {
378
+ int: all_node_args_except_first
379
+ },
380
+ NodeInfo("call_method", "unsqueeze") : {
381
+ int: return_arg_list([1])
382
+ },
383
+ NodeInfo("call_method", "unsqueeze_") : {
384
+ int: return_arg_list([1])
385
+ },
386
+ NodeInfo("call_method", torch.unsqueeze) : {
387
+ int: return_arg_list([1])
388
+ },
389
+ NodeInfo("call_method", "view") : {
390
+ int: all_node_args_except_first
391
+ },
392
+ }
393
+
394
+ EMPTY_ARG_DICT: Dict[Union[type, torch.dtype], Callable[[Node], List[int]]] = {}
395
+
396
+ def get_non_observable_arg_indexes_and_types(node: Node) -> Dict[Union[type, torch.dtype], Callable[[Node], List[int]]]:
397
+ """
398
+ Returns a dict with of non float tensor types as keys and values which correspond to a
399
+ function to retrieve the list (which takes the node as an argument)
400
+ """
401
+ info = NodeInfo(node.op, node.target)
402
+
403
+ return NON_OBSERVABLE_ARG_DICT.get(info, EMPTY_ARG_DICT)
404
+
405
+ def maybe_get_next_module(
406
+ node: Node,
407
+ modules: Dict[str, nn.Module],
408
+ target_module_type: Optional[Type[nn.Module]] = None,
409
+ target_functional_type: Any = None,
410
+ ) -> Optional[Node]:
411
+ """ Gets the next module that matches what is needed in
412
+ is_target_module_type if it exists
413
+
414
+ Args:
415
+ node: The node whose users we want to look at
416
+ target_module_type: Module type that we want to check
417
+ target_functional_type: Functional type that we want to check
418
+ """
419
+
420
+ for user in node.users.keys():
421
+ if user.op == 'call_module' and target_module_type is not None and \
422
+ isinstance(modules[str(user.target)], target_module_type):
423
+ return user
424
+ elif (user.op == 'call_function' and target_functional_type is not None and
425
+ user.target == target_functional_type):
426
+ return user
427
+
428
+ return None
429
+
430
+ def create_node_from_old_node_preserve_meta(
431
+ quantized_graph: Graph,
432
+ create_node_args: Tuple[Any, ...],
433
+ old_node: Node,
434
+ ) -> Node:
435
+ """
436
+ Creates `new_node` and copies the necessary metadata to it from `old_node`.
437
+ """
438
+ new_node = quantized_graph.create_node(*create_node_args)
439
+ new_node.stack_trace = old_node.stack_trace
440
+ return new_node
441
+
442
+ def get_skipped_module_name_and_classes(
443
+ prepare_custom_config: PrepareCustomConfig,
444
+ is_standalone_module: bool) -> Tuple[List[str], List[Type[Any]]]:
445
+ skipped_module_names = copy.copy(prepare_custom_config.non_traceable_module_names)
446
+ skipped_module_classes = copy.copy(prepare_custom_config.non_traceable_module_classes)
447
+ if not is_standalone_module:
448
+ # standalone module and custom module config are applied in top level module
449
+ skipped_module_names += list(prepare_custom_config.standalone_module_names.keys())
450
+ skipped_module_classes += list(prepare_custom_config.standalone_module_classes.keys())
451
+ skipped_module_classes += get_custom_module_class_keys(prepare_custom_config.float_to_observed_mapping)
452
+
453
+ return skipped_module_names, skipped_module_classes
454
+
455
+ def _is_custom_module_lstm(
456
+ node: Node,
457
+ named_modules: Dict[str, torch.nn.Module],
458
+ qconfig: QConfigAny = None,
459
+ # QuantizeHandler, but we cannot include the type here due to circular imports
460
+ qhandler: Optional[Any] = None,
461
+ ) -> bool:
462
+ """
463
+ Return whether this refers to the custom module LSTM flow.
464
+ """
465
+ mod = _get_module(node, named_modules)
466
+ if qconfig is not None and qhandler is not None:
467
+ assert isinstance(qhandler, torch.ao.quantization.fx.quantize_handler.QuantizeHandler) # type: ignore[attr-defined]
468
+ return isinstance(mod, torch.nn.LSTM) and \
469
+ activation_is_statically_quantized(qconfig) and \
470
+ qhandler.is_custom_module()
471
+ else:
472
+ return isinstance(mod, torch.ao.nn.quantizable.LSTM)
473
+
474
+ def _is_custom_module_mha(
475
+ node: Node,
476
+ named_modules: Dict[str, torch.nn.Module],
477
+ qconfig: QConfigAny = None,
478
+ # QuantizeHandler, but we cannot include the type here due to circular imports
479
+ qhandler: Optional[Any] = None,
480
+ ) -> bool:
481
+ """
482
+ Return whether this refers to the custom module MultiheadAttention flow.
483
+ """
484
+ mod = _get_module(node, named_modules)
485
+ if qconfig is not None and qhandler is not None:
486
+ assert isinstance(qhandler, torch.ao.quantization.fx.quantize_handler.QuantizeHandler) # type: ignore[attr-defined]
487
+ return isinstance(mod, torch.nn.MultiheadAttention) and \
488
+ activation_is_statically_quantized(qconfig) and \
489
+ qhandler.is_custom_module()
490
+ else:
491
+ return isinstance(mod, torch.ao.nn.quantizable.MultiheadAttention)
492
+
493
+ def _get_module(node: Node, named_modules: Dict[str, torch.nn.Module]) -> Optional[torch.nn.Module]:
494
+ """
495
+ If `node` refers to a call_module node, return the module, else None.
496
+ """
497
+ if node.op == "call_module" and str(node.target) in named_modules:
498
+ return named_modules[str(node.target)]
499
+ else:
500
+ return None
501
+
502
+ def _insert_dequant_stub(
503
+ node: Node,
504
+ model: torch.nn.Module,
505
+ named_modules: Dict[str, torch.nn.Module],
506
+ graph: Graph,
507
+ ) -> Node:
508
+ """
509
+ Attach a `DeQuantStub` to the model and create a node that calls this
510
+ `DeQuantStub` on the output of `node`, similar to how observers are inserted.
511
+ """
512
+ prefix = "dequant_stub_"
513
+ get_new_dequant_stub_name = get_new_attr_name_with_prefix(prefix)
514
+ dequant_stub_name = get_new_dequant_stub_name(model)
515
+ dequant_stub = DeQuantStub()
516
+ setattr(model, dequant_stub_name, dequant_stub)
517
+ named_modules[dequant_stub_name] = dequant_stub
518
+ with graph.inserting_after(node):
519
+ return graph.call_module(dequant_stub_name, (node,))
520
+
521
+ def _insert_dequant_stubs_for_custom_module_lstm_output(
522
+ node: Node,
523
+ model: torch.nn.Module,
524
+ named_modules: Dict[str, torch.nn.Module],
525
+ graph: Graph,
526
+ ) -> Node:
527
+ """
528
+ Insert DeQuantStubs after each internal output node of custom module LSTM.
529
+
530
+ Custom module LSTM outputs are nested tuples of the structure (output, (hidden0, hidden1)),
531
+ Since we cannot dequantize a tuple as a whole, we must first break down the tuple into its
532
+ components through `getitem`. This function transforms the graph as follows:
533
+
534
+ (1) Split the LSTM node into (output, (hidden0, hidden1))
535
+ (2) Insert a DeQuantStub after each internal node
536
+ (3) Recombine the DeQuantStubs into the same structure as before
537
+ (4) Reroute all consumers of the original LSTM node and its sub-nodes
538
+ (e.g. lstm[0])
539
+
540
+ Before:
541
+ lstm_output
542
+ |
543
+ v
544
+ original_user(s)
545
+ After:
546
+ lstm_output
547
+ / \\
548
+ / (getitem) \\
549
+ / \\
550
+ v v
551
+ output hidden
552
+ | / \\
553
+ (DeQuantStub) (getitem)
554
+ | / \\
555
+ v v v
556
+ output_dq hidden0 hidden1
557
+ | | |
558
+ | (DeQuantStub) (DeQuantStub)
559
+ | | |
560
+ | v v
561
+ | hidden0_dq hidden1_dq
562
+ | \\ /
563
+ | (tuple)
564
+ | \\ /
565
+ | v v
566
+ | hidden_dq
567
+ \\ /
568
+ \\ (tuple) /
569
+ v v
570
+ lstm_output_dq
571
+ |
572
+ v
573
+ original_user(s)
574
+
575
+ For step (4), reroute all users of the original LSTM node(s) as follows:
576
+ lstm_output -> lstm_output_dq
577
+ lstm_output[0] -> output_dq
578
+ lstm_output[1] -> hidden_dq
579
+ lstm_output[1][0] -> hidden0_dq
580
+ lstm_output[1][1] -> hidden1_dq
581
+
582
+ Return the node `lstm_output_dq`.
583
+ """
584
+ # (1) Split the LSTM node into (output, (hidden0, hidden1))
585
+ # (2) Insert a DeQuantStub after each internal node
586
+ with graph.inserting_after(node):
587
+ output = graph.call_function(operator.getitem, (node, 0))
588
+ output_dq = _insert_dequant_stub(output, model, named_modules, graph)
589
+ with graph.inserting_after(output_dq):
590
+ hidden = graph.call_function(operator.getitem, (node, 1))
591
+ with graph.inserting_after(hidden):
592
+ hidden0 = graph.call_function(operator.getitem, (hidden, 0))
593
+ hidden0_dq = _insert_dequant_stub(hidden0, model, named_modules, graph)
594
+ with graph.inserting_after(hidden0_dq):
595
+ hidden1 = graph.call_function(operator.getitem, (hidden, 1))
596
+ hidden1_dq = _insert_dequant_stub(hidden1, model, named_modules, graph)
597
+
598
+ # (3) Recombine the DeQuantStubs into the same structure as before
599
+ with graph.inserting_after(hidden1_dq):
600
+ hidden_dq = graph.call_function(tuple, ([hidden0_dq, hidden1_dq],))
601
+ with graph.inserting_after(hidden_dq):
602
+ lstm_output_dq = graph.call_function(tuple, ([output_dq, hidden_dq],))
603
+
604
+ # (4) Reroute all consumers of the original LSTM node and its sub-nodes
605
+ for user in list(node.users.keys()):
606
+ if user != output and user != hidden:
607
+ user.replace_input_with(node, lstm_output_dq)
608
+ # The getitem and tuple nodes we added here may interfere with reference quantized
609
+ # pattern matching, so we need to redirect the consumers of internal nodes to the
610
+ # corresponding nodes with DeQuantStubs (e.g. lstm_output_dq[0] -> output_dq) attached,
611
+ # in order to preserve reference patterns like "dequantize - consumer - quantize".
612
+ _reroute_tuple_getitem_pattern(graph)
613
+ return lstm_output_dq
614
+
615
+ def _maybe_get_custom_module_lstm_from_node_arg(
616
+ arg: Node,
617
+ named_modules: Dict[str, torch.nn.Module],
618
+ ) -> Optional[Node]:
619
+ """
620
+ Given an argument of a node, if the argument refers to the path through which the node
621
+ is a consumer of custom module LSTM, return the custom module LSTM node, or None otherwise.
622
+
623
+ This is used to determine whether a node is a consumer of custom module LSTM, and, if so,
624
+ skip inserting input observers for this node. This is because custom module LSTM produces
625
+ quantized outputs, so inserting an input observer for the consumer of custom module LSTM
626
+ would unnecessarily quantize the outputs again.
627
+
628
+ lstm -> consumer
629
+
630
+ In practice, however, custom module LSTM outputs a tuple (output, (hidden0, hidden1)) with
631
+ DeQuantStubs attached to each internal node (see `_insert_dequant_stubs_for_custom_module_lstm_output`).
632
+ This tuple can be consumed in one of four ways:
633
+
634
+ lstm -> getitem -> DeQuantStub -> consumer # consume lstm[0]
635
+ lstm -> getitem -> getitem -> DeQuantStub -> tuple -> consumer # consume lstm[1]
636
+ lstm -> getitem -> getitem -> DeQuantStub -> consumer # consume lstm[1][0] or lstm[1][1]
637
+ lstm -> getitem -> DeQuantStub -> tuple -> consumer # consume lstm
638
+
639
+ Thus, we must match against the above patterns instead of simply checking the parent node
640
+ to determine whether this node is a consumer of a custom module LSTM.
641
+ """
642
+ def match_dq(a):
643
+ return isinstance(_get_module(a, named_modules), DeQuantStub)
644
+
645
+ def match_lstm(a):
646
+ return _is_custom_module_lstm(a, named_modules)
647
+
648
+ def match_getitem(a):
649
+ return a.op == "call_function" and a.target == operator.getitem
650
+
651
+ def match_tuple(a):
652
+ return a.op == "call_function" and a.target == tuple
653
+
654
+ def _match_pattern(match_pattern: List[Callable]) -> Optional[Node]:
655
+ """
656
+ Traverse up the graph and match the args one by one.
657
+ If there is a match, return the last matched node, or None otherwise.
658
+ """
659
+ a = arg
660
+ for i, match in enumerate(match_pattern):
661
+ if not match(a):
662
+ return None
663
+ # Match next arg, for tuple the arg is a tuple of a list, e.g. ([dq_1, other_node],)
664
+ if i < len(match_pattern) - 1:
665
+ if match == match_tuple:
666
+ a = a.args[0][0] # type: ignore[assignment,index]
667
+ else:
668
+ a = a.args[0] # type: ignore[assignment]
669
+ return a
670
+
671
+ all_match_patterns = [
672
+ [match_dq, match_getitem, match_lstm],
673
+ [match_tuple, match_dq, match_getitem, match_getitem, match_lstm],
674
+ [match_dq, match_getitem, match_getitem, match_lstm],
675
+ [match_tuple, match_dq, match_getitem, match_lstm],
676
+ ]
677
+
678
+ for p in all_match_patterns:
679
+ matched_node = _match_pattern(p)
680
+ if matched_node is not None:
681
+ return matched_node
682
+ return None
683
+
684
+ def _reroute_tuple_getitem_pattern(graph: Graph):
685
+ """
686
+ Search for patterns where N consecutive `tuple` call_function nodes are followed by
687
+ N consecutive `getitem` call_function nodes that are "reverses" of the `tuple` nodes.
688
+ If we find this pattern, reroute the consumers of the last `getitem` to skip these
689
+ N `tuple` and `getitem` nodes.
690
+
691
+ Before:
692
+
693
+ a b c
694
+ | \\ /
695
+ \\ tuple
696
+ \\ /
697
+ tuple
698
+ |
699
+ getitem(1)
700
+ |
701
+ getitem(0)
702
+ |
703
+ d
704
+
705
+ After:
706
+
707
+ b
708
+ |
709
+ d
710
+ """
711
+ def find_patterns(
712
+ node: Node,
713
+ index_stack: List[int],
714
+ current_pattern: List[Node],
715
+ matched_patterns: List[List[Node]],
716
+ seen: Set[Tuple[Node, Tuple[int, ...]]]):
717
+ """
718
+ Traverse the graph recursively to match for the N-tuple - N-getitem patterns,
719
+ starting at the given node.
720
+
721
+ We use a stack to keep track of the expected `getitem` indices, since these are
722
+ reversed from the `tuple` indices. In the above example, the stack after
723
+ (b -> tuple -> tuple) will be [0, 1], which will be popped by getitem(1) first
724
+ and then by getitem(0).
725
+
726
+ TODO: traverse upwards from the output and handle the case when tuple is not a
727
+ separate node, e.g. graph.call_function(operator.getitem, args=(a, (b, c)))
728
+ """
729
+ if len(index_stack) == 0 and len(current_pattern) > 0:
730
+ matched_patterns.append(copy.copy(current_pattern))
731
+ current_pattern.clear()
732
+
733
+ # Avoid duplicating work
734
+ state = (node, tuple(index_stack))
735
+ if state in seen:
736
+ return
737
+ seen.add(state)
738
+
739
+ # Iterate through users of this node to find tuple/getitem nodes to match
740
+ for user in node.users:
741
+ if user.op == "call_function" and user.target == tuple:
742
+ for i, user_arg in enumerate(user.args[0]): # type: ignore[arg-type]
743
+ if user_arg == node:
744
+ index_stack.append(i)
745
+ current_pattern.append(user)
746
+ find_patterns(user, index_stack, current_pattern, matched_patterns, seen)
747
+ elif user.op == "call_function" and user.target == operator.getitem:
748
+ if len(index_stack) > 0:
749
+ if user.args[1] == index_stack[-1]:
750
+ index_stack.pop()
751
+ current_pattern.append(user)
752
+ find_patterns(user, index_stack, current_pattern, matched_patterns, seen)
753
+ return matched_patterns
754
+
755
+ # Collect all matched patterns
756
+ matched_patterns: List[List[Node]] = []
757
+ seen: Set[Tuple[Node, Tuple[int, ...]]] = set() # (node, index_stack)
758
+ for node in graph.nodes:
759
+ find_patterns(node, [], [], matched_patterns, seen)
760
+
761
+ # For each pattern, redirect all consumers of the last getitem node to the correct input
762
+ # of the first tuple node
763
+ for pattern in matched_patterns:
764
+ first_tuple = pattern[0]
765
+ last_getitem = pattern[-1]
766
+ assert first_tuple.op == "call_function" and first_tuple.target == tuple
767
+ assert last_getitem.op == "call_function" and last_getitem.target == operator.getitem
768
+ last_getitem_index = last_getitem.args[1]
769
+ new_input = first_tuple.args[0][last_getitem_index] # type: ignore[index]
770
+ for user in list(last_getitem.users.keys()):
771
+ user.replace_input_with(last_getitem, new_input)
772
+
773
+ def _get_observer_from_activation_post_process(
774
+ activation_post_process: Union[ObserverBase, FakeQuantizeBase],
775
+ ) -> ObserverBase:
776
+ """
777
+ If `activation_post_process` is an observer, return the observer.
778
+ If `activation_post_process` is a fake quantize, return the internal observer.
779
+ """
780
+ if isinstance(activation_post_process, ObserverBase):
781
+ return activation_post_process
782
+ else:
783
+ assert isinstance(activation_post_process, FakeQuantizeBase)
784
+ return activation_post_process.activation_post_process # type: ignore[return-value]
785
+
786
+ def _qconfig_satisfies_dtype_config_constraints(
787
+ qconfig: QConfigAny,
788
+ dtype_with_constraints: DTypeWithConstraints,
789
+ is_activation: bool = True) -> bool:
790
+ """
791
+ Return whether `qconfig` satisfies the following constraints from the backend,
792
+ specified through the activation and weight DTypeWithConstraints.
793
+
794
+ 1. QConfig specified a quantization range that falls within the backend's, if any
795
+ 2. QConfig specified a min scale value that is >= the backend's, if any
796
+ 3. QConfig specified a FixedQParamsObserver or FixedQParamsFakeQuantize that has
797
+ scale and zero point that match the backend's, if any
798
+
799
+ If `is_activation` is True, we check `qconfig.activation`, else we check `qconfig.weight`.
800
+ If `qconfig` or `dtype_with_constraints.dtype` is None, or the dtypes do not match, return True.
801
+ """
802
+ # TODO: log warnings only when the user enabled a debug flag
803
+ def _activation_post_process_satisfies_dtype_config_constraints(
804
+ activation_post_process: Union[ObserverBase, FakeQuantizeBase],
805
+ dtype_with_constraints: DTypeWithConstraints,
806
+ debug_string: str) -> bool:
807
+ observer = _get_observer_from_activation_post_process(activation_post_process)
808
+ app_quant_min = getattr(observer, "quant_min", None)
809
+ app_quant_max = getattr(observer, "quant_max", None)
810
+ # TODO: for now, just use the existing eps value as scale_min. In the future, we should
811
+ # resolve the differences between the two, either by renaming eps or some other way
812
+ app_scale_min = getattr(observer, "eps", None)
813
+ backend_quant_min = dtype_with_constraints.quant_min_lower_bound
814
+ backend_quant_max = dtype_with_constraints.quant_max_upper_bound
815
+ backend_scale_min = dtype_with_constraints.scale_min_lower_bound
816
+ backend_scale_exact_match = dtype_with_constraints.scale_exact_match
817
+ backend_zero_point_exact_match = dtype_with_constraints.zero_point_exact_match
818
+ # check quantization ranges
819
+ if backend_quant_min is not None and backend_quant_max is not None:
820
+ if app_quant_min is None or app_quant_max is None:
821
+ warnings.warn(f"QConfig {debug_string} must specify 'quant_min' and 'quant_max', ignoring {qconfig}")
822
+ return False
823
+ elif app_quant_min < backend_quant_min or app_quant_max > backend_quant_max:
824
+ warnings.warn(
825
+ f"QConfig {debug_string} quantization range must fall within the backend's:\n"
826
+ f"QConfig range = ({app_quant_min}, {app_quant_max}), "
827
+ f"BackendConfig range = ({backend_quant_min}, {backend_quant_max}), "
828
+ f"ignoring {qconfig}"
829
+ )
830
+ return False
831
+ # check scale min
832
+ if backend_scale_min is not None:
833
+ if app_scale_min is None:
834
+ warnings.warn(f"QConfig {debug_string} must specify 'eps', ignoring {qconfig}")
835
+ return False
836
+ if app_scale_min < backend_scale_min:
837
+ warnings.warn(
838
+ f"QConfig {debug_string} eps ({app_scale_min}) must be greater than or equal to "
839
+ f"the backend's min scale value ({backend_scale_min}), ignoring {qconfig}"
840
+ )
841
+ return False
842
+ # check fixed scale and zero point
843
+ if backend_scale_exact_match is not None and backend_zero_point_exact_match is not None:
844
+ # For tests only, accept the following qconfigs for now
845
+ # TODO: handle fp16 qconfigs properly
846
+ for accepted_qconfig in [float16_static_qconfig, float16_dynamic_qconfig]:
847
+ if qconfig_equals(qconfig, accepted_qconfig):
848
+ return True
849
+ suggestion_str = (
850
+ "Please use torch.ao.quantization.get_default_qconfig_mapping or "
851
+ "torch.ao.quantization.get_default_qat_qconfig_mapping. Example:\n"
852
+ " qconfig_mapping = get_default_qconfig_mapping(\"fbgemm\")\n"
853
+ " model = prepare_fx(model, qconfig_mapping, example_inputs)"
854
+ )
855
+ if not isinstance(activation_post_process, FixedQParamsObserver) and \
856
+ not isinstance(activation_post_process, FixedQParamsFakeQuantize):
857
+ warnings.warn(
858
+ f"QConfig must specify a FixedQParamsObserver or a FixedQParamsFakeQuantize "
859
+ f"for fixed qparams ops, ignoring {qconfig}.\n{suggestion_str}"
860
+ )
861
+ return False
862
+ if observer.scale != backend_scale_exact_match or observer.zero_point != backend_zero_point_exact_match:
863
+ warnings.warn(
864
+ f"QConfig fixed scale ({observer.scale}) and zero point ({observer.zero_point}) "
865
+ f"do not match the backend's ({backend_scale_exact_match} and {backend_zero_point_exact_match}), "
866
+ f"ignoring {qconfig}.\n{suggestion_str}"
867
+ )
868
+ return False
869
+ return True
870
+
871
+ if qconfig is None or dtype_with_constraints.dtype is None:
872
+ return True
873
+
874
+ activation_post_process_ctr = qconfig.activation if is_activation else qconfig.weight
875
+ debug_string = "activation" if is_activation else "weight"
876
+ satisfies_constraints = True
877
+ if activation_post_process_ctr is not None:
878
+ activation_post_process = activation_post_process_ctr()
879
+ assert _is_activation_post_process(activation_post_process)
880
+ # If dtypes don't match, don't check the activation_post_process and return True early
881
+ if activation_post_process.dtype != dtype_with_constraints.dtype:
882
+ return True
883
+ satisfies_constraints = _activation_post_process_satisfies_dtype_config_constraints(
884
+ activation_post_process, dtype_with_constraints, debug_string)
885
+ return satisfies_constraints
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .quantizer import (
2
+ DerivedQuantizationSpec,
3
+ EdgeOrNode,
4
+ FixedQParamsQuantizationSpec,
5
+ QuantizationAnnotation,
6
+ QuantizationSpec,
7
+ QuantizationSpecBase,
8
+ Quantizer,
9
+ SharedQuantizationSpec,
10
+ )
11
+
12
+ __all__ = [
13
+ "EdgeOrNode",
14
+ "Quantizer",
15
+ "QuantizationSpecBase",
16
+ "QuantizationSpec",
17
+ "FixedQParamsQuantizationSpec",
18
+ "SharedQuantizationSpec",
19
+ "DerivedQuantizationSpec",
20
+ "QuantizationAnnotation",
21
+ ]
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (510 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/composable_quantizer.cpython-310.pyc ADDED
Binary file (2.81 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/embedding_quantizer.cpython-310.pyc ADDED
Binary file (3.54 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/quantizer.cpython-310.pyc ADDED
Binary file (5.46 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/utils.cpython-310.pyc ADDED
Binary file (2.03 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/x86_inductor_quantizer.cpython-310.pyc ADDED
Binary file (22.7 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer.cpython-310.pyc ADDED
Binary file (12.8 kB). View file