ZTWHHH commited on
Commit
04cb0ba
·
verified ·
1 Parent(s): 34c93f3

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. videollama2/lib/python3.10/site-packages/torch/ao/pruning/__pycache__/__init__.cpython-310.pyc +0 -0
  2. videollama2/lib/python3.10/site-packages/torch/ao/pruning/__pycache__/_mappings.cpython-310.pyc +0 -0
  3. videollama2/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/__pycache__/nearly_diagonal_sparsifier.cpython-310.pyc +0 -0
  4. videollama2/lib/python3.10/site-packages/torch/ao/quantization/__init__.py +185 -0
  5. videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/_correct_bias.cpython-310.pyc +0 -0
  6. videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/fake_quantize.cpython-310.pyc +0 -0
  7. videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/fuse_modules.cpython-310.pyc +0 -0
  8. videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quant_type.cpython-310.pyc +0 -0
  9. videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantization_mappings.cpython-310.pyc +0 -0
  10. videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantize.cpython-310.pyc +0 -0
  11. videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantize_pt2e.cpython-310.pyc +0 -0
  12. videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/stubs.cpython-310.pyc +0 -0
  13. videollama2/lib/python3.10/site-packages/torch/ao/quantization/_correct_bias.py +144 -0
  14. videollama2/lib/python3.10/site-packages/torch/ao/quantization/_equalize.py +182 -0
  15. videollama2/lib/python3.10/site-packages/torch/ao/quantization/_learnable_fake_quantize.py +164 -0
  16. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fake_quantize.py +546 -0
  17. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fuse_modules.py +175 -0
  18. videollama2/lib/python3.10/site-packages/torch/ao/quantization/fuser_method_mappings.py +259 -0
  19. videollama2/lib/python3.10/site-packages/torch/ao/quantization/observer.py +1679 -0
  20. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__init__.py +0 -0
  21. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/__init__.cpython-310.pyc +0 -0
  22. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/duplicate_dq_pass.cpython-310.pyc +0 -0
  23. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/eval_utils.cpython-310.pyc +0 -0
  24. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/prepare.cpython-310.pyc +0 -0
  25. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/utils.cpython-310.pyc +0 -0
  26. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/eval_utils.py +112 -0
  27. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/generate_numeric_debug_handle.py +17 -0
  28. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/graph_utils.py +109 -0
  29. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/prepare.py +476 -0
  30. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/representation/__init__.py +5 -0
  31. videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/representation/__pycache__/rewrite.cpython-310.pyc +0 -0
  32. videollama2/lib/python3.10/site-packages/torch/ao/quantization/qconfig.py +560 -0
  33. videollama2/lib/python3.10/site-packages/torch/ao/quantization/qconfig_mapping.py +350 -0
  34. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quant_type.py +30 -0
  35. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantization_mappings.py +348 -0
  36. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize.py +664 -0
  37. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_fx.py +726 -0
  38. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_jit.py +335 -0
  39. videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_pt2e.py +249 -0
  40. videollama2/lib/python3.10/site-packages/torch/ao/quantization/stubs.py +64 -0
  41. videollama2/lib/python3.10/site-packages/torch/ao/quantization/utils.py +703 -0
  42. vllm/lib/python3.10/site-packages/textual/css/__init__.py +0 -0
  43. vllm/lib/python3.10/site-packages/textual/css/errors.py +50 -0
  44. vllm/lib/python3.10/site-packages/textual/css/parse.py +466 -0
  45. vllm/lib/python3.10/site-packages/textual/css/styles.py +1423 -0
  46. vllm/lib/python3.10/site-packages/textual/css/tokenize.py +266 -0
  47. vllm/lib/python3.10/site-packages/textual/css/tokenizer.py +342 -0
  48. vllm/lib/python3.10/site-packages/textual/css/types.py +54 -0
  49. vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/__init__.cpython-310.pyc +0 -0
  50. vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/background_screen.cpython-310.pyc +0 -0
videollama2/lib/python3.10/site-packages/torch/ao/pruning/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (884 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/pruning/__pycache__/_mappings.cpython-310.pyc ADDED
Binary file (697 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/pruning/sparsifier/__pycache__/nearly_diagonal_sparsifier.cpython-310.pyc ADDED
Binary file (2.45 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/__init__.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F403
2
+
3
+ from .fake_quantize import * # noqa: F403
4
+ from .fuse_modules import fuse_modules # noqa: F403
5
+ from .fuse_modules import fuse_modules_qat # noqa: F403
6
+ from .fuser_method_mappings import * # noqa: F403
7
+ from .observer import * # noqa: F403
8
+ from .qconfig import * # noqa: F403
9
+ from .qconfig_mapping import * # noqa: F403
10
+ from .quant_type import * # noqa: F403
11
+ from .quantization_mappings import * # type: ignore[no-redef]
12
+ from .quantize import * # noqa: F403
13
+ from .quantize_jit import * # noqa: F403
14
+ from .stubs import * # noqa: F403
15
+ from .pt2e.eval_utils import _move_exported_model_to_eval as move_exported_model_to_eval
16
+ from .pt2e.generate_numeric_debug_handle import generate_numeric_debug_handle # noqa: F401
17
+ from typing import Union, List, Callable, Tuple, Optional
18
+ from torch import Tensor
19
+ import torch
20
+
21
+ ObserverOrFakeQuantize = Union[ObserverBase, FakeQuantizeBase]
22
+ ObserverOrFakeQuantize.__module__ = "torch.ao.quantization"
23
+
24
+ __all__ = [
25
+ "DeQuantStub",
26
+ "FakeQuantize",
27
+ "FakeQuantizeBase",
28
+ "FixedQParamsFakeQuantize",
29
+ "FixedQParamsObserver",
30
+ "FusedMovingAvgObsFakeQuantize",
31
+ "HistogramObserver",
32
+ "MatchAllNode",
33
+ "MinMaxObserver",
34
+ "MovingAverageMinMaxObserver",
35
+ "MovingAveragePerChannelMinMaxObserver",
36
+ "NoopObserver",
37
+ "ObserverBase",
38
+ "ObserverOrFakeQuantize",
39
+ "Pattern",
40
+ "PerChannelMinMaxObserver",
41
+ "PlaceholderObserver",
42
+ "QConfig",
43
+ "QConfigAny",
44
+ "QConfigDynamic",
45
+ "QConfigMapping",
46
+ "QuantStub",
47
+ "QuantType",
48
+ "QuantWrapper",
49
+ "RecordingObserver",
50
+ "ReuseInputObserver",
51
+ "UniformQuantizationObserverBase",
52
+ "add_quant_dequant",
53
+ "convert",
54
+ "convert_dynamic_jit",
55
+ "convert_jit",
56
+ "default_affine_fixed_qparams_fake_quant",
57
+ "default_affine_fixed_qparams_observer",
58
+ "default_debug_observer",
59
+ "default_dynamic_fake_quant",
60
+ "default_dynamic_quant_observer",
61
+ "default_embedding_fake_quant",
62
+ "default_embedding_fake_quant_4bit",
63
+ "default_eval_fn",
64
+ "default_fake_quant",
65
+ "default_fixed_qparams_range_0to1_fake_quant",
66
+ "default_fixed_qparams_range_0to1_observer",
67
+ "default_fixed_qparams_range_neg1to1_fake_quant",
68
+ "default_fixed_qparams_range_neg1to1_observer",
69
+ "default_float_qparams_observer",
70
+ "default_float_qparams_observer_4bit",
71
+ "default_fused_act_fake_quant",
72
+ "default_fused_per_channel_wt_fake_quant",
73
+ "default_fused_wt_fake_quant",
74
+ "default_histogram_fake_quant",
75
+ "default_histogram_observer",
76
+ "default_observer",
77
+ "default_per_channel_weight_fake_quant",
78
+ "default_per_channel_weight_observer",
79
+ "default_placeholder_observer",
80
+ "default_reuse_input_observer",
81
+ "default_symmetric_fixed_qparams_fake_quant",
82
+ "default_symmetric_fixed_qparams_observer",
83
+ "default_weight_fake_quant",
84
+ "default_weight_observer",
85
+ "disable_fake_quant",
86
+ "disable_observer",
87
+ "enable_fake_quant",
88
+ "enable_observer",
89
+ "fuse_conv_bn",
90
+ "fuse_conv_bn_jit",
91
+ "fuse_conv_bn_relu",
92
+ "fuse_convtranspose_bn",
93
+ "fuse_linear_bn",
94
+ "fuse_modules",
95
+ "fuse_modules_qat",
96
+ "fused_per_channel_wt_fake_quant_range_neg_127_to_127",
97
+ "fused_wt_fake_quant_range_neg_127_to_127",
98
+ "get_combined_dict",
99
+ "get_default_compare_output_module_list",
100
+ "get_default_custom_config_dict",
101
+ "get_default_dynamic_quant_module_mappings",
102
+ "get_default_dynamic_sparse_quant_module_mappings",
103
+ "get_default_float_to_quantized_operator_mappings",
104
+ "get_default_qat_module_mappings",
105
+ "get_default_qat_qconfig",
106
+ "get_default_qat_qconfig_dict",
107
+ "get_default_qat_qconfig_mapping",
108
+ "get_default_qconfig",
109
+ "get_default_qconfig_dict",
110
+ "get_default_qconfig_mapping",
111
+ "get_default_qconfig_propagation_list",
112
+ "get_default_static_quant_module_mappings",
113
+ "get_default_static_quant_reference_module_mappings",
114
+ "get_default_static_sparse_quant_module_mappings",
115
+ "get_dynamic_quant_module_class",
116
+ "get_embedding_qat_module_mappings",
117
+ "get_embedding_static_quant_module_mappings",
118
+ "get_fuser_method",
119
+ "get_fuser_method_new",
120
+ "get_observer_state_dict",
121
+ "get_quantized_operator",
122
+ "get_static_quant_module_class",
123
+ "load_observer_state_dict",
124
+ "move_exported_model_to_eval",
125
+ "no_observer_set",
126
+ "per_channel_weight_observer_range_neg_127_to_127",
127
+ "prepare",
128
+ "prepare_dynamic_jit",
129
+ "prepare_jit",
130
+ "prepare_qat",
131
+ "propagate_qconfig_",
132
+ "qconfig_equals",
133
+ "quantize",
134
+ "quantize_dynamic",
135
+ "quantize_dynamic_jit",
136
+ "quantize_jit",
137
+ "quantize_qat",
138
+ "script_qconfig",
139
+ "script_qconfig_dict",
140
+ "swap_module",
141
+ "weight_observer_range_neg_127_to_127",
142
+ "generate_numeric_debug_handle",
143
+ ]
144
+
145
+ def default_eval_fn(model, calib_data):
146
+ r"""Define the default evaluation function.
147
+
148
+ Default evaluation function takes a torch.utils.data.Dataset or a list of
149
+ input Tensors and run the model on the dataset
150
+ """
151
+ for data, target in calib_data:
152
+ model(data)
153
+
154
+ class _DerivedObserverOrFakeQuantize(ObserverBase):
155
+ r"""This observer is used to describe an observer whose quantization parameters
156
+ are derived from other observers
157
+ """
158
+
159
+ def __init__(
160
+ self,
161
+ dtype: torch.dtype,
162
+ obs_or_fqs: List[ObserverOrFakeQuantize],
163
+ derive_qparams_fn: Callable[[List[ObserverOrFakeQuantize]], Tuple[Tensor, Tensor]],
164
+ quant_min: Optional[int]=None,
165
+ quant_max: Optional[int]=None,
166
+ qscheme: Optional[torch.qscheme]=None,
167
+ ch_axis: Optional[int] = None
168
+ ):
169
+ super().__init__(dtype)
170
+ self.obs_or_fqs = obs_or_fqs
171
+ self.derive_qparams_fn = derive_qparams_fn
172
+ self.quant_min = quant_min
173
+ self.quant_max = quant_max
174
+ self.qscheme = qscheme
175
+ self.ch_axis = ch_axis
176
+
177
+ from .utils import is_per_channel
178
+ if is_per_channel(self.qscheme):
179
+ assert self.ch_axis is not None, "Must provide a valid ch_axis if qscheme is per channel"
180
+
181
+ def forward(self, x: Tensor) -> Tensor:
182
+ return x
183
+
184
+ def calculate_qparams(self):
185
+ return self.derive_qparams_fn(self.obs_or_fqs)
videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/_correct_bias.cpython-310.pyc ADDED
Binary file (4.84 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/fake_quantize.cpython-310.pyc ADDED
Binary file (15.7 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/fuse_modules.cpython-310.pyc ADDED
Binary file (5.61 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quant_type.cpython-310.pyc ADDED
Binary file (981 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantization_mappings.cpython-310.pyc ADDED
Binary file (9.52 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantize.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/quantize_pt2e.cpython-310.pyc ADDED
Binary file (8.56 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/__pycache__/stubs.cpython-310.pyc ADDED
Binary file (2.82 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/_correct_bias.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.ao.nn.quantized as nnq
4
+
5
+ import torch.ao.quantization
6
+ import torch.ao.ns._numeric_suite as ns
7
+
8
+ __all__ = [
9
+ "get_module",
10
+ "parent_child_names",
11
+ "get_param",
12
+ "MeanShadowLogger",
13
+ "bias_correction",
14
+ ]
15
+
16
+ _supported_modules = {nn.Linear, nn.Conv2d}
17
+ _supported_modules_quantized = {nnq.Linear, nnq.Conv2d}
18
+
19
+ def get_module(model, name):
20
+ """Given name of submodule, this function grabs the submodule from given model."""
21
+ return dict(model.named_modules())[name]
22
+
23
+ def parent_child_names(name):
24
+ """Split full name of submodule into parent submodule's full name and submodule's name."""
25
+ split_name = name.rsplit('.', 1)
26
+ if len(split_name) == 1:
27
+ return '', split_name[0]
28
+ else:
29
+ return split_name[0], split_name[1]
30
+
31
+ def get_param(module, attr):
32
+ """Get the parameter given a module and attribute.
33
+
34
+ Sometimes the weights/bias attribute gives you the raw tensor, but sometimes
35
+ gives a function that will give you the raw tensor, this function takes care of that logic
36
+ """
37
+ param = getattr(module, attr, None)
38
+ if callable(param):
39
+ return param()
40
+ else:
41
+ return param
42
+
43
+ class MeanShadowLogger(ns.Logger):
44
+ """Mean Logger for a Shadow module.
45
+
46
+ A logger for a Shadow module whose purpose is to record the rolling mean
47
+ of the data passed to the floating point and quantized models
48
+ """
49
+
50
+ def __init__(self):
51
+ """Set up initial values for float and quantized stats, count, float sum, and quant sum."""
52
+ super().__init__()
53
+ self.stats["float"] = None
54
+ self.stats["quantized"] = None
55
+ self.count = 0
56
+ self.float_sum = None
57
+ self.quant_sum = None
58
+
59
+ def forward(self, x, y):
60
+ """Compute the average of quantized and floating-point data from modules.
61
+
62
+ The inputs x,y are output data from the quantized and floating-point modules.
63
+ x is for the quantized module, y is for the floating point module
64
+ """
65
+ if x.is_quantized:
66
+ x = x.dequantize()
67
+
68
+ self.count += 1
69
+ if self.stats["quantized"] is None:
70
+ self.stats["quantized"] = x
71
+ self.quant_sum = x
72
+ else:
73
+ self.quant_sum += x
74
+ self.stats["quantized"] = self.quant_sum / self.count
75
+
76
+ if self.stats["float"] is None:
77
+ self.stats["float"] = y
78
+ self.float_sum = y
79
+ else:
80
+ self.float_sum += y
81
+ self.stats["float"] = self.float_sum / self.count
82
+
83
+ def clear(self):
84
+ self.stats["float"] = None
85
+ self.stats["quantized"] = None
86
+ self.count = 0
87
+ self.float_sum = None
88
+ self.quant_sum = None
89
+
90
+ def bias_correction(float_model, quantized_model, img_data, target_modules=_supported_modules_quantized, neval_batches=None):
91
+ """Perform bias correction on a module.
92
+
93
+ Using numeric suite shadow module, the expected output of the floating point and quantized modules
94
+ is recorded. Using that data the bias of supported modules is shifted to compensate for the drift caused
95
+ by quantization
96
+ Paper reference: https://arxiv.org/pdf/1906.04721.pdf (Section 4.2)
97
+
98
+ Args:
99
+ float_model: a trained model that serves as a reference to what bias correction should aim for
100
+ quantized_model: quantized form of float_model that bias correction is to applied to
101
+ img_data: calibration data to estimate the expected output (used to find quantization error)
102
+ target_modules: specifies what submodules in quantized_model need bias correction (can be extended to
103
+ unquantized submodules)
104
+ neval_batches: a cap to the number of batches you want to be used for estimating the expected output
105
+ """
106
+ ns.prepare_model_with_stubs(float_model, quantized_model, _supported_modules, MeanShadowLogger)
107
+
108
+ uncorrected_modules = {}
109
+ for name, submodule in quantized_model.named_modules():
110
+ if type(submodule) in target_modules:
111
+ uncorrected_modules[name] = submodule
112
+
113
+ for uncorrected_module in uncorrected_modules:
114
+ quantized_submodule = get_module(quantized_model, uncorrected_module)
115
+ bias = get_param(quantized_submodule, 'bias')
116
+ if bias is not None:
117
+
118
+ count = 0
119
+ for data in img_data:
120
+ quantized_model(data[0])
121
+ count += 1
122
+ if count == neval_batches:
123
+ break
124
+ ob_dict = ns.get_logger_dict(quantized_model)
125
+ parent_name, _ = parent_child_names(uncorrected_module)
126
+
127
+ float_data = ob_dict[parent_name + '.stats']['float']
128
+ quant_data = ob_dict[parent_name + '.stats']['quantized']
129
+
130
+ # math for expected_error
131
+ quantization_error = quant_data - float_data
132
+ dims = list(range(quantization_error.dim()))
133
+ # Note: we don't want to take the mean over the output channel dimension
134
+ dims.remove(1)
135
+ expected_error = torch.mean(quantization_error, dims)
136
+
137
+ updated_bias = bias.data - expected_error
138
+
139
+ bias.data = updated_bias
140
+
141
+ # Resets the data contained in the loggers
142
+ for name, submodule in quantized_model.named_modules():
143
+ if isinstance(submodule, MeanShadowLogger):
144
+ submodule.clear()
videollama2/lib/python3.10/site-packages/torch/ao/quantization/_equalize.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import copy
3
+ from typing import Dict, Any
4
+
5
+ __all__ = [
6
+ "set_module_weight",
7
+ "set_module_bias",
8
+ "get_module_weight",
9
+ "get_module_bias",
10
+ "max_over_ndim",
11
+ "min_over_ndim",
12
+ "channel_range",
13
+ "cross_layer_equalization",
14
+ "equalize",
15
+ "converged",
16
+ ]
17
+
18
+ _supported_types = {torch.nn.Conv2d, torch.nn.Linear}
19
+ _supported_intrinsic_types = {torch.ao.nn.intrinsic.ConvReLU2d, torch.ao.nn.intrinsic.LinearReLU}
20
+ _all_supported_types = _supported_types.union(_supported_intrinsic_types)
21
+
22
+ def set_module_weight(module, weight) -> None:
23
+ if type(module) in _supported_types:
24
+ module.weight = torch.nn.Parameter(weight)
25
+ else:
26
+ module[0].weight = torch.nn.Parameter(weight)
27
+
28
+ def set_module_bias(module, bias) -> None:
29
+ if type(module) in _supported_types:
30
+ module.bias = torch.nn.Parameter(bias)
31
+ else:
32
+ module[0].bias = torch.nn.Parameter(bias)
33
+
34
+ def get_module_weight(module):
35
+ if type(module) in _supported_types:
36
+ return module.weight
37
+ else:
38
+ return module[0].weight
39
+
40
+ def get_module_bias(module):
41
+ if type(module) in _supported_types:
42
+ return module.bias
43
+ else:
44
+ return module[0].bias
45
+
46
+ def max_over_ndim(input, axis_list, keepdim=False):
47
+ """Apply 'torch.max' over the given axes."""
48
+ axis_list.sort(reverse=True)
49
+ for axis in axis_list:
50
+ input, _ = input.max(axis, keepdim)
51
+ return input
52
+
53
+ def min_over_ndim(input, axis_list, keepdim=False):
54
+ """Apply 'torch.min' over the given axes."""
55
+ axis_list.sort(reverse=True)
56
+ for axis in axis_list:
57
+ input, _ = input.min(axis, keepdim)
58
+ return input
59
+
60
+ def channel_range(input, axis=0):
61
+ """Find the range of weights associated with a specific channel."""
62
+ size_of_tensor_dim = input.ndim
63
+ axis_list = list(range(size_of_tensor_dim))
64
+ axis_list.remove(axis)
65
+
66
+ mins = min_over_ndim(input, axis_list)
67
+ maxs = max_over_ndim(input, axis_list)
68
+
69
+ assert mins.size(0) == input.size(axis), "Dimensions of resultant channel range does not match size of requested axis"
70
+ return maxs - mins
71
+
72
+ def cross_layer_equalization(module1, module2, output_axis=0, input_axis=1):
73
+ """Scale the range of Tensor1.output to equal Tensor2.input.
74
+
75
+ Given two adjacent tensors', the weights are scaled such that
76
+ the ranges of the first tensors' output channel are equal to the
77
+ ranges of the second tensors' input channel
78
+ """
79
+ if type(module1) not in _all_supported_types or type(module2) not in _all_supported_types:
80
+ raise ValueError("module type not supported:", type(module1), " ", type(module2))
81
+
82
+ weight1 = get_module_weight(module1)
83
+ weight2 = get_module_weight(module2)
84
+
85
+ if weight1.size(output_axis) != weight2.size(input_axis):
86
+ raise TypeError("Number of output channels of first arg do not match \
87
+ number input channels of second arg")
88
+
89
+ bias = get_module_bias(module1)
90
+
91
+ weight1_range = channel_range(weight1, output_axis)
92
+ weight2_range = channel_range(weight2, input_axis)
93
+
94
+ # producing scaling factors to applied
95
+ weight2_range += 1e-9
96
+ scaling_factors = torch.sqrt(weight1_range / weight2_range)
97
+ inverse_scaling_factors = torch.reciprocal(scaling_factors)
98
+
99
+ bias = bias * inverse_scaling_factors
100
+
101
+ # formatting the scaling (1D) tensors to be applied on the given argument tensors
102
+ # pads axis to (1D) tensors to then be broadcasted
103
+ size1 = [1] * weight1.ndim
104
+ size1[output_axis] = weight1.size(output_axis)
105
+ size2 = [1] * weight2.ndim
106
+ size2[input_axis] = weight2.size(input_axis)
107
+
108
+ scaling_factors = torch.reshape(scaling_factors, size2)
109
+ inverse_scaling_factors = torch.reshape(inverse_scaling_factors, size1)
110
+
111
+ weight1 = weight1 * inverse_scaling_factors
112
+ weight2 = weight2 * scaling_factors
113
+
114
+ set_module_weight(module1, weight1)
115
+ set_module_bias(module1, bias)
116
+ set_module_weight(module2, weight2)
117
+
118
+ def equalize(model, paired_modules_list, threshold=1e-4, inplace=True):
119
+ """Equalize modules until convergence is achieved.
120
+
121
+ Given a list of adjacent modules within a model, equalization will
122
+ be applied between each pair, this will repeated until convergence is achieved
123
+
124
+ Keeps a copy of the changing modules from the previous iteration, if the copies
125
+ are not that different than the current modules (determined by converged_test),
126
+ then the modules have converged enough that further equalizing is not necessary
127
+
128
+ Implementation of this referced section 4.1 of this paper https://arxiv.org/pdf/1906.04721.pdf
129
+
130
+ Args:
131
+ model: a model (nn.module) that equalization is to be applied on
132
+ paired_modules_list: a list of lists where each sublist is a pair of two
133
+ submodules found in the model, for each pair the two submodules generally
134
+ have to be adjacent in the model to get expected/reasonable results
135
+ threshold: a number used by the converged function to determine what degree
136
+ similarity between models is necessary for them to be called equivalent
137
+ inplace: determines if function is inplace or not
138
+ """
139
+ if not inplace:
140
+ model = copy.deepcopy(model)
141
+
142
+ name_to_module : Dict[str, torch.nn.Module] = {}
143
+ previous_name_to_module: Dict[str, Any] = {}
144
+ name_set = {name for pair in paired_modules_list for name in pair}
145
+
146
+ for name, module in model.named_modules():
147
+ if name in name_set:
148
+ name_to_module[name] = module
149
+ previous_name_to_module[name] = None
150
+ while not converged(name_to_module, previous_name_to_module, threshold):
151
+ for pair in paired_modules_list:
152
+ previous_name_to_module[pair[0]] = copy.deepcopy(name_to_module[pair[0]])
153
+ previous_name_to_module[pair[1]] = copy.deepcopy(name_to_module[pair[1]])
154
+
155
+ cross_layer_equalization(name_to_module[pair[0]], name_to_module[pair[1]])
156
+
157
+ return model
158
+
159
+ def converged(curr_modules, prev_modules, threshold=1e-4):
160
+ """Test whether modules are converged to a specified threshold.
161
+
162
+ Tests for the summed norm of the differences between each set of modules
163
+ being less than the given threshold
164
+
165
+ Takes two dictionaries mapping names to modules, the set of names for each dictionary
166
+ should be the same, looping over the set of names, for each name take the difference
167
+ between the associated modules in each dictionary
168
+
169
+ """
170
+ if curr_modules.keys() != prev_modules.keys():
171
+ raise ValueError("The keys to the given mappings must have the same set of names of modules")
172
+
173
+ summed_norms = torch.tensor(0.)
174
+ if None in prev_modules.values():
175
+ return False
176
+ for name in curr_modules.keys():
177
+ curr_weight = get_module_weight(curr_modules[name])
178
+ prev_weight = get_module_weight(prev_modules[name])
179
+
180
+ difference = curr_weight.sub(prev_weight)
181
+ summed_norms += torch.norm(difference)
182
+ return bool(summed_norms < threshold)
videollama2/lib/python3.10/site-packages/torch/ao/quantization/_learnable_fake_quantize.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn.parameter import Parameter
3
+ from typing import List
4
+
5
+ __all__: List[str] = []
6
+
7
+ class _LearnableFakeQuantize(torch.ao.quantization.FakeQuantizeBase):
8
+ r"""Generalized extension of the FakeQuantize module in fake_quantize.py.
9
+
10
+ This is an extension of the FakeQuantize module in fake_quantize.py, which
11
+ supports more generalized lower-bit quantization and support learning of the scale
12
+ and zero point parameters through backpropagation. For literature references,
13
+ please see the class _LearnableFakeQuantizePerTensorOp.
14
+
15
+ In addition to the attributes in the original FakeQuantize module, the _LearnableFakeQuantize
16
+ module also includes the following attributes to support quantization parameter learning.
17
+
18
+ * :attr:`channel_len` defines the length of the channel when initializing scale and zero point
19
+ for the per channel case.
20
+
21
+ * :attr:`use_grad_scaling` defines the flag for whether the gradients for scale and zero point are
22
+ normalized by the constant, which is proportional to the square root of the number of
23
+ elements in the tensor. The related literature justifying the use of this particular constant
24
+ can be found here: https://openreview.net/pdf?id=rkgO66VKDS.
25
+
26
+ * :attr:`fake_quant_enabled` defines the flag for enabling fake quantization on the output.
27
+
28
+ * :attr:`static_enabled` defines the flag for using observer's static estimation for
29
+ scale and zero point.
30
+
31
+ * :attr:`learning_enabled` defines the flag for enabling backpropagation for scale and zero point.
32
+ """
33
+ def __init__(self, observer, quant_min=0, quant_max=255, scale=1., zero_point=0., channel_len=-1,
34
+ use_grad_scaling=False, **observer_kwargs):
35
+ super().__init__()
36
+ assert quant_min < quant_max, 'quant_min must be strictly less than quant_max.'
37
+ self.quant_min = quant_min
38
+ self.quant_max = quant_max
39
+ # also pass quant_min and quant_max to observer
40
+ observer_kwargs["quant_min"] = quant_min
41
+ observer_kwargs["quant_max"] = quant_max
42
+ self.use_grad_scaling = use_grad_scaling
43
+ if channel_len == -1:
44
+ self.scale = Parameter(torch.tensor([scale]))
45
+ self.zero_point = Parameter(torch.tensor([zero_point]))
46
+ else:
47
+ assert isinstance(channel_len, int) and channel_len > 0, "Channel size must be a positive integer."
48
+ self.scale = Parameter(torch.tensor([scale] * channel_len))
49
+ self.zero_point = Parameter(torch.tensor([zero_point] * channel_len))
50
+
51
+ self.activation_post_process = observer(**observer_kwargs)
52
+ assert torch.iinfo(self.activation_post_process.dtype).min <= quant_min, \
53
+ 'quant_min out of bound'
54
+ assert quant_max <= torch.iinfo(self.activation_post_process.dtype).max, \
55
+ 'quant_max out of bound'
56
+ self.dtype = self.activation_post_process.dtype
57
+ self.qscheme = self.activation_post_process.qscheme
58
+ self.ch_axis = self.activation_post_process.ch_axis \
59
+ if hasattr(self.activation_post_process, 'ch_axis') else -1
60
+ self.register_buffer('fake_quant_enabled', torch.tensor([1], dtype=torch.uint8))
61
+ self.register_buffer('static_enabled', torch.tensor([1], dtype=torch.uint8))
62
+ self.register_buffer('learning_enabled', torch.tensor([0], dtype=torch.uint8))
63
+
64
+ bitrange = torch.tensor(quant_max - quant_min + 1).double()
65
+ self.bitwidth = int(torch.log2(bitrange).item())
66
+ self.register_buffer('eps', torch.tensor([torch.finfo(torch.float32).eps]))
67
+
68
+ @torch.jit.export
69
+ def enable_param_learning(self):
70
+ r"""Enable parameter learning over static observer estimates.
71
+
72
+ Enables learning of quantization parameters and
73
+ disables static observer estimates. Forward path returns fake quantized X.
74
+ """
75
+ self.toggle_qparam_learning(enabled=True) \
76
+ .toggle_fake_quant(enabled=True) \
77
+ .toggle_observer_update(enabled=False)
78
+ return self
79
+
80
+ @torch.jit.export
81
+ def enable_static_estimate(self):
82
+ """Enable static estimates of quantization parameters.
83
+
84
+ Enables static observer estimates and disables learning of
85
+ quantization parameters. Forward path returns fake quantized X.
86
+ """
87
+ self.toggle_qparam_learning(enabled=False) \
88
+ .toggle_fake_quant(enabled=True) \
89
+ .toggle_observer_update(enabled=True)
90
+
91
+ @torch.jit.export
92
+ def enable_static_observation(self):
93
+ """Enable accumulation of data without updating quantization parameters.
94
+
95
+ Enables static observer accumulating data from input but doesn't
96
+ update the quantization parameters. Forward path returns the original X.
97
+ """
98
+ self.toggle_qparam_learning(enabled=False) \
99
+ .toggle_fake_quant(enabled=False) \
100
+ .toggle_observer_update(enabled=True)
101
+
102
+ @torch.jit.export
103
+ def toggle_observer_update(self, enabled=True):
104
+ self.static_enabled[0] = int(enabled) # type: ignore[operator]
105
+ return self
106
+
107
+ @torch.jit.export
108
+ def enable_observer(self, enabled=True):
109
+ self.toggle_observer_update(enabled)
110
+
111
+ @torch.jit.export
112
+ def toggle_qparam_learning(self, enabled=True):
113
+ self.learning_enabled[0] = int(enabled) # type: ignore[operator]
114
+ self.scale.requires_grad = enabled
115
+ self.zero_point.requires_grad = enabled
116
+ return self
117
+
118
+ @torch.jit.export
119
+ def toggle_fake_quant(self, enabled=True):
120
+ self.fake_quant_enabled[0] = int(enabled)
121
+ return self
122
+
123
+ @torch.jit.export
124
+ def observe_quant_params(self):
125
+ print(f'_LearnableFakeQuantize Scale: {self.scale.detach()}')
126
+ print(f'_LearnableFakeQuantize Zero Point: {self.zero_point.detach()}')
127
+
128
+ @torch.jit.export
129
+ def calculate_qparams(self):
130
+ self.scale.data.clamp_(min=self.eps.item()) # type: ignore[operator]
131
+ scale = self.scale.detach()
132
+ zero_point = self.zero_point.detach().round().clamp(self.quant_min, self.quant_max).long()
133
+ return scale, zero_point
134
+
135
+ def forward(self, X):
136
+ if self.static_enabled[0] == 1: # type: ignore[index]
137
+ self.activation_post_process(X.detach())
138
+ _scale, _zero_point = self.activation_post_process.calculate_qparams()
139
+ _scale = _scale.to(self.scale.device)
140
+ _zero_point = _zero_point.to(self.zero_point.device)
141
+ self.scale.data.copy_(_scale)
142
+ self.zero_point.data.copy_(_zero_point)
143
+ else:
144
+ self.scale.data.clamp_(min=self.eps.item()) # type: ignore[operator]
145
+
146
+ if self.fake_quant_enabled[0] == 1:
147
+ if self.qscheme in (torch.per_channel_symmetric, torch.per_tensor_symmetric):
148
+ self.zero_point.data.zero_()
149
+
150
+ if self.use_grad_scaling:
151
+ grad_factor = 1.0 / (X.numel() * self.quant_max) ** 0.5
152
+ else:
153
+ grad_factor = 1.0
154
+ if self.qscheme in (
155
+ torch.per_channel_symmetric, torch.per_channel_affine):
156
+ X = torch._fake_quantize_learnable_per_channel_affine(
157
+ X, self.scale, self.zero_point, self.ch_axis,
158
+ self.quant_min, self.quant_max, grad_factor)
159
+ else:
160
+ X = torch._fake_quantize_learnable_per_tensor_affine(
161
+ X, self.scale, self.zero_point,
162
+ self.quant_min, self.quant_max, grad_factor)
163
+
164
+ return X
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fake_quantize.py ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implements modules used to perform fake quantization."""
2
+
3
+ import torch
4
+ from torch.nn import Module
5
+ from torch.ao.quantization.observer import (
6
+ MovingAverageMinMaxObserver,
7
+ HistogramObserver,
8
+ MovingAveragePerChannelMinMaxObserver,
9
+ FixedQParamsObserver,
10
+ default_fixed_qparams_range_0to1_observer,
11
+ default_fixed_qparams_range_neg1to1_observer,
12
+ _with_args,
13
+ )
14
+ import re
15
+ from abc import ABC, abstractmethod
16
+ from typing import Any, Tuple
17
+
18
+ __all__ = [
19
+ "FakeQuantizeBase",
20
+ "FakeQuantize",
21
+ "FixedQParamsFakeQuantize",
22
+ "FusedMovingAvgObsFakeQuantize",
23
+ "disable_fake_quant",
24
+ "disable_observer",
25
+ "enable_fake_quant",
26
+ "enable_observer",
27
+ "default_fake_quant",
28
+ "default_weight_fake_quant",
29
+ "default_dynamic_fake_quant",
30
+ "default_fixed_qparams_range_neg1to1_fake_quant",
31
+ "default_fixed_qparams_range_0to1_fake_quant",
32
+ "default_symmetric_fixed_qparams_fake_quant",
33
+ "default_affine_fixed_qparams_fake_quant",
34
+ "default_per_channel_weight_fake_quant",
35
+ "default_embedding_fake_quant",
36
+ "default_embedding_fake_quant_4bit",
37
+ "default_histogram_fake_quant",
38
+ "default_fused_act_fake_quant",
39
+ "default_fused_wt_fake_quant",
40
+ "default_fused_per_channel_wt_fake_quant",
41
+ "fused_wt_fake_quant_range_neg_127_to_127",
42
+ "fused_per_channel_wt_fake_quant_range_neg_127_to_127",
43
+ ]
44
+
45
+ def _is_per_channel(qscheme: 'torch.qscheme') -> bool:
46
+ return qscheme in [torch.per_channel_symmetric, torch.per_channel_affine, torch.per_channel_affine_float_qparams]
47
+
48
+ def _is_per_tensor(qscheme: 'torch.qscheme') -> bool:
49
+ return qscheme in [torch.per_tensor_symmetric, torch.per_tensor_affine]
50
+
51
+ def _is_symmetric_quant(qscheme: 'torch.qscheme') -> bool:
52
+ return qscheme in [torch.per_tensor_symmetric, torch.per_channel_symmetric]
53
+
54
+ def _is_float_qparams(qscheme: 'torch.qscheme') -> bool:
55
+ return qscheme in [torch.per_channel_affine_float_qparams, ]
56
+
57
+ class FakeQuantizeBase(ABC, Module):
58
+ r"""Base fake quantize module.
59
+
60
+ Base fake quantize module
61
+ Any fake quantize implementation should derive from this class.
62
+
63
+ Concrete fake quantize module should follow the same API. In forward, they will update
64
+ the statistics of the observed Tensor and fake quantize the input. They should also provide a
65
+ `calculate_qparams` function that computes the quantization parameters given
66
+ the collected statistics.
67
+
68
+ """
69
+
70
+ fake_quant_enabled: torch.Tensor
71
+ observer_enabled: torch.Tensor
72
+
73
+ def __init__(self):
74
+ """Set fake_quant_enabled and observer_enabled."""
75
+ super().__init__()
76
+ # fake_quant_enabled and observer_enabled are buffers to support their
77
+ # replication in DDP. Data type is uint8 because NCCL does not support
78
+ # bool tensors.
79
+ self.register_buffer('fake_quant_enabled', torch.tensor([1], dtype=torch.uint8))
80
+ self.register_buffer('observer_enabled', torch.tensor([1], dtype=torch.uint8))
81
+
82
+ @abstractmethod
83
+ def forward(self, x):
84
+ pass
85
+
86
+ @abstractmethod
87
+ def calculate_qparams(self, **kwargs):
88
+ pass
89
+
90
+ @torch.jit.export
91
+ def enable_fake_quant(self, enabled: bool = True) -> None:
92
+ self.fake_quant_enabled[0] = 1 if enabled else 0
93
+
94
+ @torch.jit.export
95
+ def disable_fake_quant(self):
96
+ self.enable_fake_quant(False)
97
+
98
+ @torch.jit.export
99
+ def enable_observer(self, enabled: bool = True) -> None:
100
+ self.observer_enabled[0] = 1 if enabled else 0
101
+
102
+ @torch.jit.export
103
+ def disable_observer(self):
104
+ self.enable_observer(False)
105
+
106
+ @classmethod
107
+ def with_args(cls, **kwargs):
108
+ fake_quant_constructor = _with_args(cls, **kwargs)
109
+ # need to assign the correct module to fake_quantize
110
+ # constructors to satisfy public v private requirements
111
+ fake_quant_constructor.__module__ = "torch.ao.quantization.fake_quantize"
112
+ return fake_quant_constructor
113
+
114
+ class FakeQuantize(FakeQuantizeBase):
115
+ r"""Simulate the quantize and dequantize operations in training time.
116
+
117
+ The output of this module is given by::
118
+
119
+ x_out = (
120
+ clamp(round(x/scale + zero_point), quant_min, quant_max) - zero_point
121
+ ) * scale
122
+
123
+ * :attr:`is_dynamic` indicates whether the fake quantie is a placeholder for dynamic quantization
124
+ operators (choose_qparams -> q -> dq) or static quantization operators (q -> dq)
125
+
126
+ * :attr:`scale` defines the scale factor used for quantization.
127
+
128
+ * :attr:`zero_point` specifies the quantized value to which 0 in floating point maps to
129
+
130
+ * :attr:`fake_quant_enabled` controls the application of fake quantization on tensors, note that
131
+ statistics can still be updated.
132
+
133
+ * :attr:`observer_enabled` controls statistics collection on tensors
134
+
135
+ * :attr:`dtype` specifies the quantized dtype that is being emulated with fake-quantization,
136
+ allowable values are torch.qint8 and torch.quint8.
137
+
138
+ Args:
139
+
140
+ observer (module): Module for observing statistics on input tensors and calculating scale
141
+ and zero-point.
142
+ observer_kwargs (optional): Arguments for the observer module
143
+
144
+ Attributes:
145
+ activation_post_process (Module): User provided module that collects statistics on the input tensor and
146
+ provides a method to calculate scale and zero-point.
147
+
148
+ """
149
+
150
+ scale: torch.Tensor
151
+ zero_point: torch.Tensor
152
+
153
+ def __init__(self, observer=MovingAverageMinMaxObserver, quant_min=None, quant_max=None, is_dynamic=False, **observer_kwargs):
154
+ super().__init__()
155
+ # Populate quant_min/quant_max to observer_kwargs if valid
156
+ if quant_min is not None and quant_max is not None:
157
+ assert quant_min <= quant_max, \
158
+ 'quant_min must be less than or equal to quant_max'
159
+ dtype = observer_kwargs.get("dtype", torch.quint8)
160
+ if hasattr(observer, "p"):
161
+ # In case observer is _PartialWrapper, dtype can be stored in
162
+ # observer.p.keywords["dtype"]
163
+ dtype = getattr(getattr(observer, "p", {}), "keywords", {}).get(
164
+ "dtype", dtype
165
+ )
166
+ assert torch.iinfo(dtype).min <= quant_min, 'quant_min out of bound'
167
+ assert quant_max <= torch.iinfo(dtype).max, 'quant_max out of bound'
168
+ observer_kwargs.update({"quant_min": quant_min, "quant_max": quant_max})
169
+ observer_kwargs["is_dynamic"] = is_dynamic
170
+ self.activation_post_process = observer(**observer_kwargs)
171
+ # TODO: keeping self.quant_min/max for BC; remove after a couple releases
172
+ # Users should use self.activation_post_process.quant_min
173
+ self.quant_min = self.activation_post_process.quant_min
174
+ self.quant_max = self.activation_post_process.quant_max
175
+ self.is_dynamic = self.activation_post_process.is_dynamic
176
+ if _is_float_qparams(self.activation_post_process.qscheme):
177
+ zero_point_dtype = torch.float
178
+ else:
179
+ zero_point_dtype = torch.int
180
+ self.register_buffer('scale', torch.tensor([1.0], dtype=torch.float))
181
+ self.register_buffer('zero_point', torch.tensor([0], dtype=zero_point_dtype))
182
+ self.dtype = self.activation_post_process.dtype
183
+ self.qscheme = self.activation_post_process.qscheme
184
+ self.ch_axis = self.activation_post_process.ch_axis \
185
+ if hasattr(self.activation_post_process, 'ch_axis') else -1
186
+ assert _is_per_channel(self.qscheme) or \
187
+ _is_per_tensor(self.qscheme), \
188
+ 'Only per channel and per tensor quantization are supported in fake quantize' + \
189
+ ' got qscheme: ' + str(self.qscheme)
190
+ self.is_per_channel = _is_per_channel(self.qscheme)
191
+
192
+ @torch.jit.export
193
+ def calculate_qparams(self):
194
+ return self.activation_post_process.calculate_qparams()
195
+
196
+ def forward(self, X):
197
+ if self.observer_enabled[0] == 1:
198
+ self.activation_post_process(X.detach())
199
+ _scale, _zero_point = self.calculate_qparams()
200
+ _scale, _zero_point = _scale.to(self.scale.device), _zero_point.to(self.zero_point.device)
201
+ if self.scale.shape != _scale.shape:
202
+ self.scale.resize_(_scale.shape)
203
+ self.zero_point.resize_(_zero_point.shape)
204
+ self.scale.copy_(_scale)
205
+ self.zero_point.copy_(_zero_point)
206
+
207
+ if self.fake_quant_enabled[0] == 1:
208
+ if self.is_per_channel:
209
+ X = torch.fake_quantize_per_channel_affine(
210
+ X, self.scale, self.zero_point,
211
+ self.ch_axis, self.activation_post_process.quant_min, self.activation_post_process.quant_max)
212
+ else:
213
+ X = torch.fake_quantize_per_tensor_affine(
214
+ X, self.scale, self.zero_point,
215
+ self.activation_post_process.quant_min, self.activation_post_process.quant_max)
216
+ return X
217
+
218
+ @torch.jit.export
219
+ def extra_repr(self):
220
+ return 'fake_quant_enabled={}, observer_enabled={}, ' \
221
+ 'quant_min={}, quant_max={}, dtype={}, qscheme={}, ch_axis={}, ' \
222
+ 'scale={}, zero_point={}'.format(
223
+ self.fake_quant_enabled, self.observer_enabled,
224
+ self.activation_post_process.quant_min, self.activation_post_process.quant_max,
225
+ self.dtype, self.qscheme, self.ch_axis, self.scale, self.zero_point)
226
+
227
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
228
+ # We cannot currently register scalar values as buffers, so need to manually
229
+ # specify serialization here.
230
+ super()._save_to_state_dict(destination, prefix, keep_vars)
231
+ destination[prefix + 'scale'] = self.scale
232
+ destination[prefix + 'zero_point'] = self.zero_point
233
+
234
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
235
+ missing_keys, unexpected_keys, error_msgs):
236
+ # Removing this function throws an error that the size of the loaded tensor does not match the original size
237
+ # i.e., These buffers start out with numel 0 and become numel 1 once they have their first forward pass.
238
+ local_state = ['scale', 'zero_point']
239
+ for name in local_state:
240
+ key = prefix + name
241
+ if key in state_dict:
242
+ val = state_dict[key]
243
+ # Custom handling to allow loading scale and zero_point
244
+ # of size N into uninitialized buffers of size 0. The
245
+ # buffers are resized here, and the values are copied in
246
+ # the default state_dict loading code of the parent.
247
+ if name == 'scale':
248
+ self.scale.resize_(val.shape)
249
+ else:
250
+ assert name == 'zero_point'
251
+ self.zero_point.resize_(val.shape)
252
+ # For torchscript module we need to update the attributes here since we do not
253
+ # call the `_load_from_state_dict` function defined module.py
254
+ if torch.jit.is_scripting():
255
+ if name == 'scale':
256
+ self.scale.copy_(val)
257
+ else:
258
+ assert name == 'zero_point'
259
+ self.zero_point.copy_(val)
260
+ elif strict:
261
+ missing_keys.append(key)
262
+ super()._load_from_state_dict(state_dict, prefix, local_metadata, strict,
263
+ missing_keys, unexpected_keys, error_msgs)
264
+
265
+
266
+ class FixedQParamsFakeQuantize(FakeQuantize):
267
+ """Simulate quantize and dequantize in training time.
268
+
269
+ Simulate quantize and dequantize with fixed quantization
270
+ parameters in training time. Only per tensor quantization
271
+ is supported.
272
+ """
273
+
274
+ # TODO: rename observer to observer_ctr
275
+ def __init__(self, observer):
276
+ super().__init__(observer=observer)
277
+ assert type(self.activation_post_process) == FixedQParamsObserver,\
278
+ f"{self.__class__.__name__}'s observer must be a {FixedQParamsObserver.__name__}"
279
+ self._observer_ctr = observer
280
+ self.scale = self.activation_post_process.scale
281
+ self.zero_point = self.activation_post_process.zero_point
282
+ assert _is_per_tensor(self.qscheme), 'Only per tensor quantization is supported' + \
283
+ ' FixedQParamsFakeQuantize module, got qscheme:' + str(self.qscheme)
284
+
285
+ @torch.jit.export
286
+ def calculate_qparams(self):
287
+ return self.scale, self.zero_point
288
+
289
+ @torch.jit.export
290
+ def extra_repr(self):
291
+ """Define a string representation of the object's attributes."""
292
+ return 'fake_quant_enabled={}, observer_enabled={}, scale={}, zero_point={}, ' \
293
+ 'dtype={}, quant_min={}, quant_max={}, qscheme={}'.format(
294
+ self.fake_quant_enabled, self.observer_enabled,
295
+ self.scale, self.zero_point, self.dtype,
296
+ self.activation_post_process.quant_min, self.activation_post_process.quant_max, self.qscheme)
297
+
298
+
299
+ class FusedMovingAvgObsFakeQuantize(FakeQuantize):
300
+ r"""Define a fused module to observe the tensor.
301
+
302
+ Fused module that is used to observe the input tensor (compute min/max), compute
303
+ scale/zero_point and fake_quantize the tensor.
304
+ This module uses calculation similar MovingAverageMinMaxObserver for the inputs,
305
+ to compute the min/max values in order to compute the scale/zero_point.
306
+ The qscheme input in the observer is used to differentiate between symmetric/affine
307
+ quantization scheme.
308
+
309
+ The output of this module is given by
310
+ x_out = (clamp(round(x/scale + zero_point), quant_min, quant_max)-zero_point)*scale
311
+
312
+ Similar to :class:`~torch.ao.quantization.FakeQuantize`, and accepts the same attributes as the
313
+ base class.
314
+
315
+ """
316
+
317
+ def __init__(
318
+ self,
319
+ observer: Any = MovingAverageMinMaxObserver,
320
+ quant_min: int = 0,
321
+ quant_max: int = 255,
322
+ **observer_kwargs: Any
323
+ ) -> None:
324
+ super().__init__(observer, quant_min, quant_max, **observer_kwargs)
325
+ assert isinstance(self.activation_post_process, (MovingAverageMinMaxObserver, MovingAveragePerChannelMinMaxObserver)),\
326
+ "Fused observer+fake_quant module only works with MovingAverageMinMaxObserver"
327
+ self.register_buffer("fake_quant_enabled", torch.tensor([1], dtype=torch.long))
328
+ self.register_buffer("observer_enabled", torch.tensor([1], dtype=torch.long))
329
+ self.is_symmetric_quant = _is_symmetric_quant(self.activation_post_process.qscheme)
330
+
331
+ @torch.jit.export
332
+ def calculate_qparams(self) -> Tuple[torch.Tensor, torch.Tensor]:
333
+ return self.activation_post_process.calculate_qparams()
334
+
335
+ @torch.jit.export
336
+ def extra_repr(self) -> str:
337
+ return (
338
+ "fake_quant_enabled={}, observer_enabled={}, scale={}, zero_point={}, "
339
+ "dtype={}, quant_min={}, quant_max={}, qscheme={}, reduce_range={}".format(
340
+ self.fake_quant_enabled,
341
+ self.observer_enabled,
342
+ self.scale,
343
+ self.zero_point,
344
+ self.dtype,
345
+ self.activation_post_process.quant_min,
346
+ self.activation_post_process.quant_max,
347
+ self.qscheme,
348
+ self.activation_post_process.reduce_range,
349
+ )
350
+ )
351
+
352
+ def forward(self, X: torch.Tensor) -> torch.Tensor:
353
+ return torch.fused_moving_avg_obs_fake_quant(
354
+ X,
355
+ self.observer_enabled,
356
+ self.fake_quant_enabled,
357
+ self.activation_post_process.min_val,
358
+ self.activation_post_process.max_val,
359
+ self.scale,
360
+ self.zero_point,
361
+ self.activation_post_process.averaging_constant,
362
+ self.activation_post_process.quant_min,
363
+ self.activation_post_process.quant_max,
364
+ self.ch_axis,
365
+ self.is_per_channel,
366
+ self.is_symmetric_quant,
367
+ )
368
+
369
+ default_fake_quant = FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, quant_min=0, quant_max=255,
370
+ dtype=torch.quint8, qscheme=torch.per_tensor_affine, reduce_range=True)
371
+ """
372
+ Default fake_quant for activations.
373
+ """
374
+
375
+ default_weight_fake_quant = FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, quant_min=-128, quant_max=127,
376
+ dtype=torch.qint8, qscheme=torch.per_tensor_symmetric, reduce_range=False)
377
+ """
378
+ Default fake_quant for weights.
379
+ Observer is memoryless since averaging_constant is 1.
380
+ """
381
+
382
+ default_dynamic_fake_quant = FakeQuantize.with_args(
383
+ observer=MovingAverageMinMaxObserver, quant_min=0, quant_max=255, is_dynamic=True,
384
+ dtype=torch.quint8, averaging_constant=1)
385
+ """
386
+ Default dynamic fake_quant for activations.
387
+ """
388
+
389
+ default_fixed_qparams_range_neg1to1_fake_quant = (
390
+ FixedQParamsFakeQuantize.with_args(observer=default_fixed_qparams_range_neg1to1_observer)
391
+ )
392
+ default_fixed_qparams_range_0to1_fake_quant = (
393
+ FixedQParamsFakeQuantize.with_args(observer=default_fixed_qparams_range_0to1_observer)
394
+ )
395
+ # TODO: the following 2 variables are kept for backwards compatibility; remove after a few releases
396
+ default_symmetric_fixed_qparams_fake_quant = default_fixed_qparams_range_neg1to1_fake_quant
397
+ default_affine_fixed_qparams_fake_quant = default_fixed_qparams_range_0to1_fake_quant
398
+
399
+ default_per_channel_weight_fake_quant = FakeQuantize.with_args(observer=MovingAveragePerChannelMinMaxObserver,
400
+ quant_min=-128,
401
+ quant_max=127,
402
+ dtype=torch.qint8,
403
+ qscheme=torch.per_channel_symmetric,
404
+ reduce_range=False,
405
+ ch_axis=0)
406
+ """
407
+ Default fake_quant for per-channel weights.
408
+ Observer is memoryless since averaging_constant is 1.
409
+ """
410
+ default_embedding_fake_quant = FakeQuantize.with_args(observer=MovingAveragePerChannelMinMaxObserver,
411
+ qscheme=torch.per_channel_affine_float_qparams,
412
+ dtype=torch.quint8,
413
+ quant_min=0,
414
+ quant_max=255,
415
+ ch_axis=0,
416
+ averaging_constant=1)
417
+ """
418
+ Default fake_quant for embeddings.
419
+ Observer is memoryless since averaging_constant is 1.
420
+ """
421
+
422
+ default_embedding_fake_quant_4bit = FakeQuantize.with_args(observer=MovingAveragePerChannelMinMaxObserver,
423
+ qscheme=torch.per_channel_affine_float_qparams,
424
+ ch_axis=0,
425
+ dtype=torch.quint4x2,
426
+ averaging_constant=1)
427
+
428
+ default_histogram_fake_quant = FakeQuantize.with_args(observer=HistogramObserver,
429
+ quant_min=0,
430
+ quant_max=255,
431
+ dtype=torch.quint8,
432
+ qscheme=torch.per_tensor_affine,
433
+ reduce_range=True)
434
+ """
435
+ Fake_quant for activations using a histogram..
436
+ """
437
+
438
+
439
+ default_fused_act_fake_quant = FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
440
+ quant_min=0,
441
+ quant_max=255,
442
+ dtype=torch.quint8,)
443
+
444
+ """
445
+ Fused version of `default_fake_quant`, with improved performance.
446
+ """
447
+
448
+
449
+ default_fused_wt_fake_quant = FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
450
+ quant_min=-128,
451
+ quant_max=127,
452
+ dtype=torch.qint8,
453
+ qscheme=torch.per_tensor_symmetric)
454
+ """
455
+ Fused version of `default_weight_fake_quant`, with improved performance.
456
+ """
457
+
458
+ default_fused_per_channel_wt_fake_quant = FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAveragePerChannelMinMaxObserver,
459
+ quant_min=-128,
460
+ quant_max=127,
461
+ dtype=torch.qint8,
462
+ qscheme=torch.per_channel_symmetric)
463
+ """
464
+ Fused version of `default_per_channel_weight_fake_quant`, with improved performance.
465
+ """
466
+
467
+ fused_wt_fake_quant_range_neg_127_to_127 = FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
468
+ quant_min=-127,
469
+ quant_max=127,
470
+ dtype=torch.qint8,
471
+ qscheme=torch.per_tensor_symmetric,
472
+ eps=2 ** -12)
473
+ """
474
+ Fused version of `default_weight_fake_quant`, with the 8-bit values restricted to [-127, +127], excluding -128.
475
+ """
476
+
477
+ fused_per_channel_wt_fake_quant_range_neg_127_to_127 = \
478
+ FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAveragePerChannelMinMaxObserver,
479
+ quant_min=-127,
480
+ quant_max=127,
481
+ dtype=torch.qint8,
482
+ qscheme=torch.per_channel_symmetric,
483
+ eps=2 ** -12)
484
+
485
+ """
486
+ Fused version of `default_per_channel_weight_fake_quant`, with the 8-bit values restricted to [-127, +127], excluding -128.
487
+ """
488
+
489
+
490
+ def _is_fake_quant_script_module(mod):
491
+ """Return true if given mod is an instance of FakeQuantize script module."""
492
+ if isinstance(mod, torch.jit.RecursiveScriptModule):
493
+ # qualified name looks like '__torch__.torch.ao.quantization.fake_quantize.___torch_mangle_2.FakeQuantize'
494
+ suffix = mod._c.qualified_name.split('.', 1)[1]
495
+ name = re.sub(r'\.___torch_mangle_\d+', '', suffix)
496
+ return name == 'torch.ao.quantization.fake_quantize.FakeQuantize' or \
497
+ name == 'torch.ao.quantization.fake_quantize.FusedMovingAvgObsFakeQuantize'
498
+ return False
499
+
500
+ def disable_fake_quant(mod):
501
+ """Disable fake quantization for the module.
502
+
503
+ Disable fake quantization for this module, if applicable. Example usage::
504
+
505
+ # model is any PyTorch model
506
+ model.apply(torch.ao.quantization.disable_fake_quant)
507
+
508
+ """
509
+ if isinstance(mod, FakeQuantizeBase) or _is_fake_quant_script_module(mod):
510
+ mod.disable_fake_quant()
511
+
512
+ def enable_fake_quant(mod):
513
+ """Enable fake quantization for the module.
514
+
515
+ Enable fake quantization for this module, if applicable. Example usage::
516
+
517
+ # model is any PyTorch model
518
+ model.apply(torch.ao.quantization.enable_fake_quant)
519
+
520
+ """
521
+ if isinstance(mod, FakeQuantizeBase) or _is_fake_quant_script_module(mod):
522
+ mod.enable_fake_quant()
523
+
524
+ def disable_observer(mod):
525
+ """Disable observation for this module.
526
+
527
+ Disable observation for this module, if applicable. Example usage::
528
+
529
+ # model is any PyTorch model
530
+ model.apply(torch.ao.quantization.disable_observer)
531
+
532
+ """
533
+ if isinstance(mod, FakeQuantizeBase) or _is_fake_quant_script_module(mod):
534
+ mod.disable_observer()
535
+
536
+ def enable_observer(mod):
537
+ """Enable observation for this module.
538
+
539
+ Enable observation for this module, if applicable. Example usage::
540
+
541
+ # model is any PyTorch model
542
+ model.apply(torch.ao.quantization.enable_observer)
543
+
544
+ """
545
+ if isinstance(mod, FakeQuantizeBase) or _is_fake_quant_script_module(mod):
546
+ mod.enable_observer()
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fuse_modules.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+
3
+ import torch.nn as nn
4
+
5
+ from torch.ao.quantization.fuser_method_mappings import get_fuser_method
6
+ # for backward compatibility
7
+ from torch.ao.quantization.fuser_method_mappings import fuse_conv_bn # noqa: F401
8
+ from torch.ao.quantization.fuser_method_mappings import fuse_conv_bn_relu # noqa: F401
9
+ from torch.nn.utils.parametrize import type_before_parametrizations
10
+
11
+ from typing import List, Optional
12
+
13
+ __all__ = [
14
+ "fuse_known_modules",
15
+ "fuse_modules",
16
+ "fuse_modules_qat",
17
+ ]
18
+
19
+ # Generalization of getattr
20
+ def _get_module(model, submodule_key):
21
+ tokens = submodule_key.split('.')
22
+ cur_mod = model
23
+ for s in tokens:
24
+ cur_mod = getattr(cur_mod, s)
25
+ return cur_mod
26
+
27
+ # Generalization of setattr
28
+ def _set_module(model, submodule_key, module):
29
+ tokens = submodule_key.split('.')
30
+ sub_tokens = tokens[:-1]
31
+ cur_mod = model
32
+ for s in sub_tokens:
33
+ cur_mod = getattr(cur_mod, s)
34
+
35
+ setattr(cur_mod, tokens[-1], module)
36
+
37
+ def fuse_known_modules(mod_list, is_qat, additional_fuser_method_mapping=None):
38
+ r"""Return a list of known fuse modules.
39
+
40
+ Returns a list of modules that fuses the operations specified
41
+ in the input module list.
42
+
43
+ Fuses only the following sequence of modules:
44
+ conv, bn
45
+ conv, bn, relu
46
+ conv, relu
47
+ linear, bn
48
+ linear, relu
49
+ For these sequences, the first element in the output module list performs
50
+ the fused operation. The rest of the elements are set to nn.Identity()
51
+ """
52
+ types = tuple(type_before_parametrizations(m) for m in mod_list)
53
+ fuser_method = get_fuser_method(types, additional_fuser_method_mapping)
54
+ if fuser_method is None:
55
+ raise NotImplementedError(f"Cannot fuse modules: {types}")
56
+ new_mod : List[Optional[nn.Module]] = [None] * len(mod_list)
57
+ fused = fuser_method(is_qat, *mod_list)
58
+ # NOTE: forward hooks not processed in the two following for loops will be lost after the fusion
59
+ # Move pre forward hooks of the base module to resulting fused module
60
+ for pre_hook_fn in mod_list[0]._forward_pre_hooks.values():
61
+ fused.register_forward_pre_hook(pre_hook_fn)
62
+ mod_list[0]._forward_pre_hooks.clear()
63
+ # Move post forward hooks of the last module to resulting fused module
64
+ for hook_fn in mod_list[-1]._forward_hooks.values():
65
+ fused.register_forward_hook(hook_fn)
66
+ mod_list[-1]._forward_hooks.clear()
67
+ new_mod[0] = fused
68
+
69
+ for i in range(1, len(mod_list)):
70
+ identity = nn.Identity()
71
+ identity.training = mod_list[0].training
72
+ new_mod[i] = identity
73
+
74
+ return new_mod
75
+
76
+ def _fuse_modules_helper(model, modules_to_fuse, is_qat, fuser_func=fuse_known_modules, fuse_custom_config_dict=None):
77
+ if fuse_custom_config_dict is None:
78
+ fuse_custom_config_dict = {}
79
+ additional_fuser_method_mapping = fuse_custom_config_dict.get("additional_fuser_method_mapping", {})
80
+ mod_list = []
81
+ for item in modules_to_fuse:
82
+ mod_list.append(_get_module(model, item))
83
+
84
+ # Fuse list of modules
85
+ new_mod_list = fuser_func(mod_list, is_qat, additional_fuser_method_mapping)
86
+
87
+ # Replace original module list with fused module list
88
+ for i, item in enumerate(modules_to_fuse):
89
+ _set_module(model, item, new_mod_list[i])
90
+
91
+ def _fuse_modules(model, modules_to_fuse, is_qat, inplace=False, fuser_func=fuse_known_modules, fuse_custom_config_dict=None):
92
+ if not inplace:
93
+ model = copy.deepcopy(model)
94
+
95
+ if all(isinstance(module_element, str) for module_element in modules_to_fuse):
96
+ # Handle case of modules_to_fuse being a list
97
+ _fuse_modules_helper(model, modules_to_fuse, is_qat, fuser_func, fuse_custom_config_dict)
98
+ else:
99
+ # Handle case of modules_to_fuse being a list of lists
100
+ for module_list in modules_to_fuse:
101
+ _fuse_modules_helper(model, module_list, is_qat, fuser_func, fuse_custom_config_dict)
102
+ return model
103
+
104
+ def fuse_modules(model, modules_to_fuse, inplace=False, fuser_func=fuse_known_modules, fuse_custom_config_dict=None):
105
+ r"""Fuse a list of modules into a single module.
106
+
107
+ Fuses only the following sequence of modules:
108
+ conv, bn
109
+ conv, bn, relu
110
+ conv, relu
111
+ linear, relu
112
+ bn, relu
113
+ All other sequences are left unchanged.
114
+ For these sequences, replaces the first item in the list
115
+ with the fused module, replacing the rest of the modules
116
+ with identity.
117
+
118
+ Args:
119
+ model: Model containing the modules to be fused
120
+ modules_to_fuse: list of list of module names to fuse. Can also be a list
121
+ of strings if there is only a single list of modules to fuse.
122
+ inplace: bool specifying if fusion happens in place on the model, by default
123
+ a new model is returned
124
+ fuser_func: Function that takes in a list of modules and outputs a list of fused modules
125
+ of the same length. For example,
126
+ fuser_func([convModule, BNModule]) returns the list [ConvBNModule, nn.Identity()]
127
+ Defaults to torch.ao.quantization.fuse_known_modules
128
+ `fuse_custom_config_dict`: custom configuration for fusion
129
+
130
+ .. code-block:: python
131
+
132
+ # Example of fuse_custom_config_dict
133
+ fuse_custom_config_dict = {
134
+ # Additional fuser_method mapping
135
+ "additional_fuser_method_mapping": {
136
+ (torch.nn.Conv2d, torch.nn.BatchNorm2d): fuse_conv_bn
137
+ },
138
+ }
139
+
140
+ Returns:
141
+ model with fused modules. A new copy is created if inplace=True.
142
+
143
+ Examples::
144
+
145
+ >>> # xdoctest: +SKIP
146
+ >>> m = M().eval()
147
+ >>> # m is a module containing the sub-modules below
148
+ >>> modules_to_fuse = [ ['conv1', 'bn1', 'relu1'], ['submodule.conv', 'submodule.relu']]
149
+ >>> fused_m = torch.ao.quantization.fuse_modules(m, modules_to_fuse)
150
+ >>> output = fused_m(input)
151
+
152
+ >>> m = M().eval()
153
+ >>> # Alternately provide a single list of modules to fuse
154
+ >>> modules_to_fuse = ['conv1', 'bn1', 'relu1']
155
+ >>> fused_m = torch.ao.quantization.fuse_modules(m, modules_to_fuse)
156
+ >>> output = fused_m(input)
157
+
158
+ """
159
+ return _fuse_modules(
160
+ model,
161
+ modules_to_fuse,
162
+ is_qat=False,
163
+ inplace=inplace,
164
+ fuser_func=fuser_func,
165
+ fuse_custom_config_dict=fuse_custom_config_dict)
166
+
167
+ def fuse_modules_qat(model, modules_to_fuse, inplace=False, fuser_func=fuse_known_modules, fuse_custom_config_dict=None):
168
+ """QAT version for `fuse_modules`."""
169
+ return _fuse_modules(
170
+ model,
171
+ modules_to_fuse,
172
+ is_qat=True,
173
+ inplace=inplace,
174
+ fuser_func=fuser_func,
175
+ fuse_custom_config_dict=fuse_custom_config_dict)
videollama2/lib/python3.10/site-packages/torch/ao/quantization/fuser_method_mappings.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch.ao.nn.intrinsic as nni
3
+
4
+ from typing import Any, Union, Callable, List, Tuple, Dict, Optional, Type
5
+ from torch.ao.quantization.utils import Pattern, get_combined_dict, MatchAllNode
6
+ import itertools
7
+
8
+ __all__ = [
9
+ "fuse_conv_bn",
10
+ "fuse_conv_bn_relu",
11
+ "fuse_linear_bn",
12
+ "fuse_convtranspose_bn",
13
+ "get_fuser_method",
14
+ "get_fuser_method_new",
15
+ ]
16
+
17
+ def fuse_conv_bn(is_qat, conv, bn):
18
+ r"""Return the fused the conv and bn modules.
19
+ Given the conv and bn modules, fuses them and returns the fused module
20
+
21
+ Args:
22
+ is_qat: a flag for whether we are using quantization aware training fusion
23
+ or post training quantization fusion
24
+ conv: Module instance of type conv2d/conv3d
25
+ bn: Spatial BN instance that needs to be fused with the conv
26
+
27
+ Examples::
28
+
29
+ >>> m1 = nn.Conv2d(10, 20, 3)
30
+ >>> b1 = nn.BatchNorm2d(20)
31
+ >>> # xdoctest: +SKIP
32
+ >>> m2 = fuse_conv_bn(m1, b1)
33
+ """
34
+ assert(conv.training == bn.training),\
35
+ "Conv and BN both must be in the same mode (train or eval)."
36
+
37
+ fused_module_class_map = {
38
+ nn.Conv1d: nni.ConvBn1d,
39
+ nn.Conv2d: nni.ConvBn2d,
40
+ nn.Conv3d: nni.ConvBn3d,
41
+ }
42
+
43
+ if is_qat:
44
+ assert bn.num_features == conv.out_channels, 'Output channel of Conv2d must match num_features of BatchNorm2d'
45
+ assert bn.affine, 'Only support fusing BatchNorm2d with affine set to True'
46
+ assert bn.track_running_stats, 'Only support fusing BatchNorm2d with tracking_running_stats set to True'
47
+ fused_module_class = fused_module_class_map.get((type(conv)), None)
48
+ if fused_module_class is not None:
49
+ return fused_module_class(conv, bn)
50
+ else:
51
+ raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn)}")
52
+ else:
53
+ return nn.utils.fuse_conv_bn_eval(conv, bn)
54
+
55
+ def fuse_conv_bn_relu(is_qat, conv, bn, relu):
56
+ r"""Return the fused conv and bv modules.
57
+
58
+ Given the conv and bn modules, fuses them and returns the fused module
59
+
60
+ Args:
61
+ is_qat: a flag for whether we are using quantization aware training fusion
62
+ or post training quantization fusion
63
+ conv: Module instance of type conv2d/conv3d
64
+ bn: Spatial BN instance that needs to be fused with the conv
65
+
66
+ Examples::
67
+
68
+ >>> m1 = nn.Conv2d(10, 20, 3)
69
+ >>> b1 = nn.BatchNorm2d(20)
70
+ >>> r1 = nn.ReLU(inplace=False)
71
+ >>> # xdoctest: +SKIP
72
+ >>> m2 = fuse_conv_bn_relu(m1, b1, r1)
73
+ """
74
+ assert(conv.training == bn.training == relu.training),\
75
+ "Conv and BN both must be in the same mode (train or eval)."
76
+ fused_module : Optional[Type[nn.Sequential]] = None
77
+ if is_qat:
78
+ map_to_fused_module_train = {
79
+ nn.Conv1d: nni.ConvBnReLU1d,
80
+ nn.Conv2d: nni.ConvBnReLU2d,
81
+ nn.Conv3d: nni.ConvBnReLU3d,
82
+ }
83
+ assert bn.num_features == conv.out_channels, 'Output channel of Conv must match num_features of BatchNorm'
84
+ assert bn.affine, 'Only support fusing BatchNorm with affine set to True'
85
+ assert bn.track_running_stats, 'Only support fusing BatchNorm with tracking_running_stats set to True'
86
+ fused_module = map_to_fused_module_train.get(type(conv), None)
87
+ if fused_module is not None:
88
+ return fused_module(conv, bn, relu)
89
+ else:
90
+ raise NotImplementedError(f"Cannot fuse train modules: {(conv, bn, relu)}")
91
+ else:
92
+ map_to_fused_module_eval = {
93
+ nn.Conv1d: nni.ConvReLU1d,
94
+ nn.Conv2d: nni.ConvReLU2d,
95
+ nn.Conv3d: nni.ConvReLU3d,
96
+ }
97
+ fused_module = map_to_fused_module_eval.get(type(conv), None)
98
+ if fused_module is not None:
99
+ fused_conv = nn.utils.fusion.fuse_conv_bn_eval(conv, bn)
100
+ return fused_module(fused_conv, relu)
101
+ else:
102
+ raise NotImplementedError(f"Cannot fuse eval modules: {(conv, bn, relu)}")
103
+
104
+ def fuse_linear_bn(is_qat, linear, bn):
105
+ r"""Return the fused linear and bn modules.
106
+ Given the linear and bn modules, fuses them and returns the fused module
107
+
108
+ Args:
109
+ is_qat: a flag for whether we are using quantization aware training fusion
110
+ or post training quantization fusion
111
+ linear: Module instance of type Linear
112
+ bn: BatchNorm1d instance that needs to be fused with the linear layer
113
+
114
+ Examples::
115
+
116
+ >>> m1 = nn.Linear(20, 10)
117
+ >>> b1 = nn.BatchNorm1d(10)
118
+ >>> # xdoctest: +SKIP
119
+ >>> m2 = fuse_linear_bn(m1, b1)
120
+ """
121
+ assert(linear.training == bn.training),\
122
+ "Linear and BN both must be in the same mode (train or eval)."
123
+
124
+ if is_qat:
125
+ assert bn.num_features == linear.out_features,\
126
+ "Output features of Linear must match num_features of BatchNorm1d"
127
+ assert bn.affine, "Only support fusing BatchNorm1d with affine set to True"
128
+ assert bn.track_running_stats,\
129
+ "Only support fusing BatchNorm1d with tracking_running_stats set to True"
130
+ return nni.LinearBn1d(linear, bn)
131
+ else:
132
+ return nn.utils.fusion.fuse_linear_bn_eval(linear, bn)
133
+
134
+ def fuse_convtranspose_bn(is_qat, convt, bn):
135
+ r"""Return the fused ConvTranspose and bn modules.
136
+ Given ConvTranspose and bn modules, fuses them and returns the fused module
137
+
138
+ Args:
139
+ convt: Module instance of type ConvTransposeNd
140
+ bn: BatchNormNd instance that needs to be fused with the linear layer.
141
+ batch norm N should match the ConvTranspose N
142
+
143
+ Examples::
144
+
145
+ >>> m1 = nn.ConvTranspose2d(10, 20, 3)
146
+ >>> b1 = nn.BatchNorm2d(20)
147
+ >>> # xdoctest: +SKIP
148
+ >>> m2 = fuse_convtranspose_bn(m1, b1)
149
+ """
150
+ assert(convt.training == bn.training),\
151
+ "ConvTranspose and BN both must be in the same mode (train or eval)."
152
+
153
+ if is_qat:
154
+ raise Exception("Fusing ConvTranspose+BatchNorm not yet supported in QAT.")
155
+ else:
156
+ return nn.utils.fusion.fuse_conv_bn_eval(convt, bn, transpose=True)
157
+
158
+ def _sequential_wrapper2(sequential):
159
+ """Return a sequential wrapped that for is_qat and two modules.
160
+ Given a sequential class for two modules, return a function that takes
161
+ is_qat, and then two modules as argument, that ignores the is_qat flag
162
+ and always returns the sequential that combines the two input modules
163
+ """
164
+ def fuser_method(is_qat, m1, m2):
165
+ return sequential(m1, m2)
166
+ return fuser_method
167
+
168
+ _DEFAULT_OP_LIST_TO_FUSER_METHOD: Dict[Tuple, Union[nn.Sequential, Callable]] = {
169
+ (nn.Conv1d, nn.BatchNorm1d): fuse_conv_bn,
170
+ (nn.Conv1d, nn.BatchNorm1d, nn.ReLU): fuse_conv_bn_relu,
171
+ (nn.Conv2d, nn.BatchNorm2d): fuse_conv_bn,
172
+ (nn.Conv2d, nn.BatchNorm2d, nn.ReLU): fuse_conv_bn_relu,
173
+ (nn.Conv3d, nn.BatchNorm3d): fuse_conv_bn,
174
+ (nn.Conv3d, nn.BatchNorm3d, nn.ReLU): fuse_conv_bn_relu,
175
+ (nn.Conv1d, nn.ReLU): _sequential_wrapper2(nni.ConvReLU1d),
176
+ (nn.Conv2d, nn.ReLU): _sequential_wrapper2(nni.ConvReLU2d),
177
+ (nn.Conv3d, nn.ReLU): _sequential_wrapper2(nni.ConvReLU3d),
178
+ (nn.Linear, nn.BatchNorm1d): fuse_linear_bn,
179
+ (nn.Linear, nn.ReLU): _sequential_wrapper2(nni.LinearReLU),
180
+ (nn.BatchNorm2d, nn.ReLU): _sequential_wrapper2(nni.BNReLU2d),
181
+ (nn.BatchNorm3d, nn.ReLU): _sequential_wrapper2(nni.BNReLU3d),
182
+ (nn.ConvTranspose1d, nn.BatchNorm1d): fuse_convtranspose_bn,
183
+ (nn.ConvTranspose2d, nn.BatchNorm2d): fuse_convtranspose_bn,
184
+ (nn.ConvTranspose3d, nn.BatchNorm3d): fuse_convtranspose_bn,
185
+ }
186
+
187
+ def get_fuser_method(op_list, additional_fuser_method_mapping=None):
188
+ """Get fuser method for the given list of module types.
189
+
190
+ Get fuser method for the given list of module types,
191
+ return None if fuser method does not exist
192
+ """
193
+ if additional_fuser_method_mapping is None:
194
+ additional_fuser_method_mapping = {}
195
+ all_mappings = get_combined_dict(_DEFAULT_OP_LIST_TO_FUSER_METHOD,
196
+ additional_fuser_method_mapping)
197
+ fuser_method = all_mappings.get(op_list, None)
198
+ assert fuser_method is not None, f"did not find fuser method for: {op_list} "
199
+ return fuser_method
200
+
201
+ def _reverse2(f):
202
+ def reversed(is_qat, x, y):
203
+ return f(is_qat, y, x)
204
+ return reversed
205
+
206
+ def _reverse3(f):
207
+ def reversed(is_qat, x, w):
208
+ y, z = w
209
+ return f(is_qat, z, y, x)
210
+ return reversed
211
+
212
+ def _get_valid_patterns(op_pattern):
213
+ """Return a list of valid patterns generated from the op_pattern.
214
+
215
+ Returns a list of valid patterns generated from the op_pattern,
216
+ since MatchAllNode can match all types of nodes,
217
+ e.g. pattern (torch.nn.Conv2d, torch.add) should also be able to match keys like
218
+ (MatchAllNode, torch.add) and (torch.nn.Conv2d, MatchAllNode)
219
+
220
+ Example Input:
221
+ (torch.add, (torch.nn.ReLU, torch.nn.Conv2d))
222
+
223
+ Example Output:
224
+ [(torch.add, (torch.nn.ReLU, torch.nn.Conv2d)),
225
+ (torch.add, (torch.nn.ReLU, MatchAllNode)),
226
+ (torch.add, (MatchAllNode, torch.nn.Conv2d)),
227
+ (torch.add, (MatchAllNode, MatchAllNode)),
228
+ (MatchAllNode, (torch.nn.ReLU, torch.nn.Conv2d)),
229
+ (MatchAllNode, (torch.nn.ReLU, MatchAllNode)),
230
+ (MatchAllNode, (MatchAllNode, torch.nn.Conv2d)),
231
+ (MatchAllNode, (MatchAllNode, MatchAllNode)),
232
+ ]
233
+ """
234
+ result: List[Any]
235
+ if isinstance(op_pattern, (tuple, list)):
236
+ sub_combs = []
237
+ for sub_pattern in op_pattern:
238
+ sub_combs.append(_get_valid_patterns(sub_pattern))
239
+ result = list(itertools.product(*sub_combs))
240
+ else:
241
+ result = [op_pattern, MatchAllNode]
242
+ return result
243
+
244
+ def get_fuser_method_new(
245
+ op_pattern: Pattern,
246
+ fuser_method_mapping: Dict[Pattern, Union[nn.Sequential, Callable]]):
247
+ """Get fuser method.
248
+
249
+ This will be made default after we deprecate the get_fuser_method
250
+ Would like to implement this first and have a separate PR for deprecation
251
+ """
252
+ op_patterns = _get_valid_patterns(op_pattern)
253
+ fuser_method = None
254
+ for op_pattern in op_patterns:
255
+ fuser_method = fuser_method_mapping.get(op_pattern, None)
256
+ if fuser_method is not None:
257
+ break
258
+ assert fuser_method is not None, f"did not find fuser method for: {op_pattern} "
259
+ return fuser_method
videollama2/lib/python3.10/site-packages/torch/ao/quantization/observer.py ADDED
@@ -0,0 +1,1679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module implements observers which are used to collect statistics about
3
+ the values observed during calibration (PTQ) or training (QAT).
4
+ """
5
+
6
+ import re
7
+ import warnings
8
+ from abc import ABCMeta, abstractmethod
9
+ from collections import OrderedDict
10
+ from functools import partial
11
+ from typing import Any, List, Tuple, Optional, Dict
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+ from torch.ao.quantization.utils import (
16
+ check_min_max_valid, calculate_qmin_qmax, is_per_tensor, is_per_channel, validate_qmin_qmax)
17
+
18
+ __all__ = [
19
+ "default_affine_fixed_qparams_observer",
20
+ "default_debug_observer",
21
+ "default_dynamic_quant_observer",
22
+ "default_fixed_qparams_range_0to1_observer",
23
+ "default_fixed_qparams_range_neg1to1_observer",
24
+ "default_float_qparams_observer",
25
+ "default_float_qparams_observer_4bit",
26
+ "default_histogram_observer",
27
+ "default_observer",
28
+ "default_per_channel_weight_observer",
29
+ "default_placeholder_observer",
30
+ "default_reuse_input_observer",
31
+ "default_symmetric_fixed_qparams_observer",
32
+ "default_weight_observer",
33
+ "get_observer_state_dict",
34
+ "load_observer_state_dict",
35
+ "per_channel_weight_observer_range_neg_127_to_127",
36
+ "weight_observer_range_neg_127_to_127",
37
+ "FixedQParamsObserver",
38
+ "HistogramObserver",
39
+ "MinMaxObserver",
40
+ "MovingAverageMinMaxObserver",
41
+ "MovingAveragePerChannelMinMaxObserver",
42
+ "NoopObserver",
43
+ "ObserverBase",
44
+ "PerChannelMinMaxObserver",
45
+ "PlaceholderObserver",
46
+ "RecordingObserver",
47
+ "ReuseInputObserver",
48
+ "UniformQuantizationObserverBase",
49
+ ]
50
+
51
+
52
+ class _PartialWrapper:
53
+ def __init__(self, p):
54
+ self.p = p
55
+ self.callable_args = {}
56
+
57
+ def __call__(self, *args, **keywords):
58
+ # call each arg in callable_args and add them partial, then run with keywords
59
+ # skip if arg_name in keywords so its possible to overwrite
60
+ for arg_name in self.callable_args:
61
+ if arg_name not in keywords:
62
+ keywords = {**keywords, arg_name: self.callable_args[arg_name]()}
63
+ return self.p(*args, **keywords)
64
+
65
+ def __repr__(self):
66
+ return self.p.__repr__() + self.callable_args.__repr__()
67
+
68
+ def with_args(self, **kwargs):
69
+ return _with_args(self, **kwargs)
70
+
71
+ def with_callable_args(self, **kwargs):
72
+ result = _PartialWrapper(p=self.p)
73
+ result.callable_args = {**self.callable_args, **kwargs}
74
+ return result
75
+
76
+
77
+ def _with_args(cls_or_self, **kwargs):
78
+ r"""Wrapper that allows creation of class factories.
79
+
80
+ This can be useful when there is a need to create classes with the same
81
+ constructor arguments, but different instances. Can be used in conjunction with
82
+ _callable_args
83
+
84
+ Example::
85
+
86
+ >>> # xdoctest: +SKIP("Undefined vars")
87
+ >>> Foo.with_args = classmethod(_with_args)
88
+ >>> foo_builder = Foo.with_args(a=3, b=4).with_args(answer=42)
89
+ >>> foo_instance1 = foo_builder()
90
+ >>> foo_instance2 = foo_builder()
91
+ >>> id(foo_instance1) == id(foo_instance2)
92
+ False
93
+ """
94
+ r = _PartialWrapper(partial(cls_or_self, **kwargs))
95
+ return r
96
+
97
+ def _with_callable_args(cls_or_self, **kwargs):
98
+ r"""Wrapper that allows creation of class factories args that need to be
99
+ called at construction time.
100
+
101
+ This can be useful when there is a need to create classes with the same
102
+ constructor arguments, but different instances and those arguments should only
103
+ be calculated at construction time. Can be used in conjunction with _with_args
104
+
105
+ Example::
106
+
107
+ >>> # xdoctest: +SKIP("Undefined vars")
108
+ >>> Foo.with_callable_args = classmethod(_with_callable_args)
109
+ >>> Foo.with_args = classmethod(_with_args)
110
+ >>> foo_builder = Foo.with_callable_args(cur_time=get_time_func).with_args(name="dan")
111
+ >>> foo_instance1 = foo_builder()
112
+ >>> # wait 50
113
+ >>> foo_instance2 = foo_builder()
114
+ >>> id(foo_instance1.creation_time) == id(foo_instance2.creation_time)
115
+ False
116
+ """
117
+ r = _PartialWrapper(partial(cls_or_self))
118
+ return r.with_callable_args(**kwargs)
119
+
120
+
121
+ ABC: Any = ABCMeta("ABC", (object,), {}) # compatible with Python 2 *and* 3:
122
+
123
+
124
+ class ObserverBase(ABC, nn.Module):
125
+ r"""Base observer Module.
126
+ Any observer implementation should derive from this class.
127
+
128
+ Concrete observers should follow the same API. In forward, they will update
129
+ the statistics of the observed Tensor. And they should provide a
130
+ `calculate_qparams` function that computes the quantization parameters given
131
+ the collected statistics.
132
+
133
+ Args:
134
+ dtype: dtype argument to the `quantize` node needed to implement the
135
+ reference model spec.
136
+ is_dynamic: indicator for whether the observer is a placeholder for dynamic quantization
137
+ or static quantization
138
+ """
139
+
140
+ def __init__(self, dtype, is_dynamic=False):
141
+ super().__init__()
142
+ self.dtype = dtype
143
+ self.is_dynamic = is_dynamic
144
+
145
+ @abstractmethod
146
+ def forward(self, x):
147
+ pass
148
+
149
+ @abstractmethod
150
+ def calculate_qparams(self, **kwargs):
151
+ pass
152
+
153
+ with_args = classmethod(_with_args)
154
+ with_callable_args = classmethod(_with_callable_args)
155
+
156
+
157
+ class UniformQuantizationObserverBase(ObserverBase):
158
+ r"""Common base for all observers using uniform quantization to calculate
159
+ scale and zero_point.
160
+
161
+ Args:
162
+ dtype: dtype argument to the `quantize` node needed to implement the
163
+ reference model spec.
164
+ qscheme: Quantization scheme to be used.
165
+ reduce_range: Reduces the range of the quantized data type by 1 bit.
166
+ This is sometimes required to avoid instruction overflow.
167
+ quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
168
+ quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
169
+ eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
170
+
171
+ .. warning::
172
+
173
+ :attr:`dtype` can only take ``torch.qint8`` or ``torch.quint8``.
174
+ or `torch.int8` or `torch.uint8`
175
+
176
+ .. warning::
177
+
178
+ :attr:`qscheme` can only take one of the following options:
179
+
180
+ - ``torch.per_tensor_affine``
181
+ - ``torch.per_tensor_symmetric``
182
+ - ``torch.per_channel_affine``
183
+ - ``torch.per_channel_symmetric``
184
+ """
185
+
186
+ # Note: the version is shared by all observer types
187
+ #
188
+ # Version 1/None
189
+ # self
190
+ #
191
+ # Version 2 (base class only, does not include child class buffers)
192
+ # self
193
+ # |--- eps : Tensor
194
+ #
195
+ # Version 3
196
+ # for HistogramObserver only, changed the shape of uninitialized
197
+ # min_val and max_val buffers from torch.Size([0]) to torch.Size([])
198
+ # for PerChannelObservers, changed the name of the buffers from min_vals
199
+ # to min_val and from max_vals to max_val.
200
+ _version = 3
201
+
202
+ eps: torch.Tensor
203
+
204
+ def __init__(
205
+ self,
206
+ dtype=torch.quint8,
207
+ qscheme=torch.per_tensor_affine,
208
+ reduce_range=False,
209
+ quant_min=None,
210
+ quant_max=None,
211
+ factory_kwargs=None,
212
+ eps=torch.finfo(torch.float32).eps,
213
+ is_dynamic=False,
214
+ **kwargs,
215
+ ) -> None:
216
+ factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
217
+ super().__init__(dtype=dtype, is_dynamic=is_dynamic, **kwargs)
218
+ self.qscheme = qscheme
219
+ if reduce_range:
220
+ warnings.warn(
221
+ "Please use quant_min and quant_max to specify the range for observers. \
222
+ reduce_range will be deprecated in a future release of PyTorch."
223
+ )
224
+ self.reduce_range = reduce_range
225
+ self.register_buffer(
226
+ "eps", torch.tensor([eps], **factory_kwargs)
227
+ )
228
+ assert self.qscheme in (
229
+ torch.per_tensor_affine,
230
+ torch.per_tensor_symmetric,
231
+ torch.per_channel_affine,
232
+ torch.per_channel_symmetric,
233
+ torch.per_channel_affine_float_qparams,
234
+ ), "Default Observer only works for per_tensor_affine, \
235
+ per_tensor_symmetric, per_channel_affine, \
236
+ per_channel_symmetric and per_channel_float_qparams quantization scheme"
237
+
238
+ _ALLOWED_DTYPES = (
239
+ torch.qint8,
240
+ torch.quint8,
241
+ torch.quint4x2,
242
+ torch.qint32,
243
+ torch.int8,
244
+ torch.uint8,
245
+ torch.int16,
246
+ torch.int32,
247
+ )
248
+
249
+ assert self.dtype in _ALLOWED_DTYPES, f"Default Observer only works for {_ALLOWED_DTYPES} data type"
250
+ self.has_customized_qrange = (quant_min is not None) and (quant_max is not None)
251
+ if self.has_customized_qrange:
252
+ validate_qmin_qmax(quant_min, quant_max)
253
+ self.quant_min, self.quant_max = \
254
+ calculate_qmin_qmax(quant_min, quant_max, self.has_customized_qrange, self.dtype, self.reduce_range)
255
+
256
+ def _load_from_state_dict(
257
+ self,
258
+ state_dict,
259
+ prefix,
260
+ local_metadata,
261
+ strict,
262
+ missing_keys,
263
+ unexpected_keys,
264
+ error_msgs,
265
+ ):
266
+
267
+ version = local_metadata.get("version", None)
268
+
269
+ if version is None or version == 1:
270
+ # eps was moved to a buffer in version 2
271
+ eps = torch.tensor([torch.finfo(torch.float32).eps])
272
+ state_dict[prefix + "eps"] = eps
273
+
274
+ super()._load_from_state_dict(
275
+ state_dict,
276
+ prefix,
277
+ local_metadata,
278
+ strict,
279
+ missing_keys,
280
+ unexpected_keys,
281
+ error_msgs,
282
+ )
283
+
284
+ @torch.jit.export
285
+ def _validate_qmin_qmax(self, quant_min: int, quant_max: int) -> None:
286
+ r"""Validates that the user-specified quantization range is properly initialized
287
+ and within the given bound supported by the observer dtype.
288
+
289
+ To accommodate lower-bit quantization with respect to the existing torch.qint8 and
290
+ torch.quint8 datatypes, the user can choose to use dynamic quantization range by passing
291
+ in a tuple of initial qmin and qmax values. One use case is these customized qmin and qmax
292
+ values are used to calculate static estimates of the scale and zero point for aggressive lower-bit
293
+ fake quantization. These estimates are compared against parameters learned through backpropagation.
294
+ The related literatures for scale and zero point via backpropagation are as follows:
295
+
296
+ Learned Step Size Quantization: https://openreview.net/pdf?id=rkgO66VKDS
297
+ Trained Quantization Thresholds: https://arxiv.org/pdf/1903.08066.pdf
298
+ """
299
+ # The variable names are prefixed with "initial" because their values (qmin and qmax) might be adjusted
300
+ # based on whether quantization range is reduced and the datatype (signed/unsigned) used by the observer.
301
+ assert (
302
+ quant_min <= 0 <= quant_max
303
+ ), "Used-specified quantization range must include 0."
304
+ assert (
305
+ quant_min < quant_max
306
+ ), "qmin must be strictly less than qmax for user-specified quantization range."
307
+
308
+ @torch.jit.export
309
+ def _calculate_qparams(
310
+ self, min_val: torch.Tensor, max_val: torch.Tensor
311
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
312
+ r"""Calculates the quantization parameters, given min and max
313
+ value tensors. Works for both per tensor and per channel cases
314
+
315
+ Args:
316
+ min_val: Minimum values per channel
317
+ max_val: Maximum values per channel
318
+
319
+ Returns:
320
+ scales: Scales tensor of shape (#channels,)
321
+ zero_points: Zero points tensor of shape (#channels,)
322
+ """
323
+ # Functionally equivalent to 'determine_qparams' in utils.py. Observers must be torchscriptable however and qscheme
324
+ # as far as I can tell is not allowed to passed as a parameter in torchscript functions. This makes refactoring observer
325
+ # to use this utility a massive pain and very gross. For now Im opting just to duplicate as this code
326
+ # seems unlikey to change (last update over 1 year ago) and when torchscript is fully deprecated we can refactor.
327
+ # TODO(jakeszwe, jerryzh168)
328
+ if not check_min_max_valid(min_val, max_val):
329
+ return torch.tensor([1.0], device=min_val.device.type), torch.tensor([0], device=min_val.device.type)
330
+
331
+ quant_min, quant_max = self.quant_min, self.quant_max
332
+ min_val_neg = torch.min(min_val, torch.zeros_like(min_val))
333
+ max_val_pos = torch.max(max_val, torch.zeros_like(max_val))
334
+
335
+ device = min_val_neg.device
336
+ scale = torch.ones(min_val_neg.size(), dtype=torch.float32, device=device)
337
+ zero_point = torch.zeros(min_val_neg.size(), dtype=torch.int64, device=device)
338
+
339
+ if (
340
+ self.qscheme == torch.per_tensor_symmetric
341
+ or self.qscheme == torch.per_channel_symmetric
342
+ ):
343
+ max_val_pos = torch.max(-min_val_neg, max_val_pos)
344
+ scale = max_val_pos / (float(quant_max - quant_min) / 2)
345
+ scale = torch.max(scale, self.eps)
346
+ if self.dtype in [torch.quint8, torch.uint8]:
347
+ if self.has_customized_qrange:
348
+ # When customized quantization range is used, down-rounded midpoint of the range is chosen.
349
+ zero_point = zero_point.new_full(
350
+ zero_point.size(), (quant_min + quant_max) // 2
351
+ )
352
+ else:
353
+ zero_point = zero_point.new_full(zero_point.size(), 128)
354
+ elif self.qscheme == torch.per_channel_affine_float_qparams:
355
+ scale = (max_val - min_val) / float(quant_max - quant_min)
356
+ scale = torch.where(scale > self.eps, scale, torch.ones_like(scale))
357
+ # We use the quantize function
358
+ # xq = Round(Xf * inv_scale + zero_point),
359
+ # setting zero_point to (-1 * min *inv_scale) we get
360
+ # Xq = Round((Xf - min) * inv_scale)
361
+ zero_point = -1 * min_val / scale
362
+ else:
363
+ scale = (max_val_pos - min_val_neg) / float(quant_max - quant_min)
364
+ scale = torch.max(scale, self.eps)
365
+ zero_point = quant_min - torch.round(min_val_neg / scale).to(torch.int)
366
+ zero_point = torch.clamp(zero_point, quant_min, quant_max)
367
+
368
+ # For scalar values, cast them to Tensors of size 1 to keep the shape
369
+ # consistent with default values in FakeQuantize.
370
+ if len(scale.shape) == 0:
371
+ # TODO: switch to scale.item() after adding JIT support
372
+ scale = torch.tensor([float(scale)], dtype=scale.dtype, device=device)
373
+ if len(zero_point.shape) == 0:
374
+ # TODO: switch to zero_point.item() after adding JIT support
375
+ zero_point = torch.tensor(
376
+ [int(zero_point)], dtype=zero_point.dtype, device=device
377
+ )
378
+ if self.qscheme == torch.per_channel_affine_float_qparams:
379
+ zero_point = torch.tensor(
380
+ [float(zero_point)], dtype=zero_point.dtype, device=device
381
+ )
382
+
383
+ return scale, zero_point
384
+
385
+ @torch.jit.export
386
+ def reset_min_max_vals(self):
387
+ raise NotImplementedError("Cannot reset min/max values in the given observer.")
388
+
389
+
390
+ # Originally, this class was called `_ObserverBase`. Keeping the old name around
391
+ # for backwards compatibility.
392
+ # TODO(after v1.13): delete this
393
+ _ObserverBase = UniformQuantizationObserverBase
394
+
395
+
396
+ class MinMaxObserver(UniformQuantizationObserverBase):
397
+ r"""Observer module for computing the quantization parameters based on the
398
+ running min and max values.
399
+
400
+ This observer uses the tensor min/max statistics to compute the quantization
401
+ parameters. The module records the running minimum and maximum of incoming
402
+ tensors, and uses this statistic to compute the quantization parameters.
403
+
404
+ Args:
405
+ dtype: dtype argument to the `quantize` node needed to implement the
406
+ reference model spec.
407
+ qscheme: Quantization scheme to be used
408
+ reduce_range: Reduces the range of the quantized data type by 1 bit
409
+ quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
410
+ quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
411
+ eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
412
+
413
+ Given running min/max as :math:`x_\text{min}` and :math:`x_\text{max}`,
414
+ scale :math:`s` and zero point :math:`z` are computed as:
415
+
416
+ The running minimum/maximum :math:`x_\text{min/max}` is computed as:
417
+
418
+ .. math::
419
+
420
+ \begin{array}{ll}
421
+ x_\text{min} &= \begin{cases}
422
+ \min(X) & \text{if~}x_\text{min} = \text{None} \\
423
+ \min\left(x_\text{min}, \min(X)\right) & \text{otherwise}
424
+ \end{cases}\\
425
+ x_\text{max} &= \begin{cases}
426
+ \max(X) & \text{if~}x_\text{max} = \text{None} \\
427
+ \max\left(x_\text{max}, \max(X)\right) & \text{otherwise}
428
+ \end{cases}\\
429
+ \end{array}
430
+
431
+ where :math:`X` is the observed tensor.
432
+
433
+ The scale :math:`s` and zero point :math:`z` are then computed as:
434
+
435
+ .. math::
436
+
437
+ \begin{aligned}
438
+ \text{if Symmetric:}&\\
439
+ &s = 2 \max(|x_\text{min}|, x_\text{max}) /
440
+ \left( Q_\text{max} - Q_\text{min} \right) \\
441
+ &z = \begin{cases}
442
+ 0 & \text{if dtype is qint8} \\
443
+ 128 & \text{otherwise}
444
+ \end{cases}\\
445
+ \text{Otherwise:}&\\
446
+ &s = \left( x_\text{max} - x_\text{min} \right ) /
447
+ \left( Q_\text{max} - Q_\text{min} \right ) \\
448
+ &z = Q_\text{min} - \text{round}(x_\text{min} / s)
449
+ \end{aligned}
450
+
451
+ where :math:`Q_\text{min}` and :math:`Q_\text{max}` are the minimum and
452
+ maximum of the quantized data type.
453
+
454
+ .. warning:: :attr:`dtype` can only take ``torch.qint8`` or ``torch.quint8``.
455
+
456
+ .. note:: If the running minimum equals to the running maximum, the scale
457
+ and zero_point are set to 1.0 and 0.
458
+ """
459
+ min_val: torch.Tensor
460
+ max_val: torch.Tensor
461
+
462
+ def __init__(
463
+ self,
464
+ dtype=torch.quint8,
465
+ qscheme=torch.per_tensor_affine,
466
+ reduce_range=False,
467
+ quant_min=None,
468
+ quant_max=None,
469
+ factory_kwargs=None,
470
+ eps=torch.finfo(torch.float32).eps,
471
+ is_dynamic=False,
472
+ **kwargs,
473
+ ) -> None:
474
+ if not is_per_tensor(qscheme):
475
+ raise NotImplementedError(
476
+ "MinMaxObserver's qscheme only support torch.per_tensor_symmetric \
477
+ and torch.per_tensor_affine."
478
+ )
479
+ # TODO: MinMaxObserver by itself doesn't support dynamic quantization, but
480
+ # if it's inherited by MovingAverageObserver, and averaging_constant is 1, it
481
+ # supports dynamic quantization, we may need to better error checking here
482
+
483
+ # For x86 quantized kernels, we need to ensure that the vpmaddubsw
484
+ # instruction does not overflow. We allow for a reduce_range argument to
485
+ # observers that reduces the quantized range to (0,127) or (-64, 63).
486
+ # For more details see aten/src/ATen/native/quantized/cpu/qconv.cpp
487
+ # This is not an optimal choice for non x86 backends as it loses a bit
488
+ # of precision for activations.
489
+ super().__init__(
490
+ dtype=dtype,
491
+ qscheme=qscheme,
492
+ reduce_range=reduce_range,
493
+ quant_min=quant_min,
494
+ quant_max=quant_max,
495
+ factory_kwargs=factory_kwargs,
496
+ eps=eps,
497
+ is_dynamic=is_dynamic,
498
+ **kwargs,
499
+ )
500
+ factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
501
+ self.register_buffer("min_val", torch.tensor(float("inf"), **factory_kwargs))
502
+ self.register_buffer("max_val", torch.tensor(float("-inf"), **factory_kwargs))
503
+ if (
504
+ self.qscheme == torch.per_tensor_symmetric
505
+ and self.reduce_range
506
+ and self.dtype == torch.quint8
507
+ ):
508
+ raise NotImplementedError(
509
+ "Cannot reduce range for symmetric \
510
+ quantization for quint8"
511
+ )
512
+
513
+ def forward(self, x_orig):
514
+ r"""Records the running minimum and maximum of ``x``."""
515
+ if x_orig.numel() == 0:
516
+ return x_orig
517
+ x = x_orig.detach() # avoid keeping autograd tape
518
+ x = x.to(self.min_val.dtype)
519
+ min_val_cur, max_val_cur = torch.aminmax(x)
520
+ min_val = torch.min(min_val_cur, self.min_val)
521
+ max_val = torch.max(max_val_cur, self.max_val)
522
+ self.min_val.copy_(min_val)
523
+ self.max_val.copy_(max_val)
524
+ return x_orig
525
+
526
+ @torch.jit.export
527
+ def calculate_qparams(self):
528
+ r"""Calculates the quantization parameters."""
529
+ return self._calculate_qparams(self.min_val, self.max_val)
530
+
531
+ @torch.jit.export
532
+ def extra_repr(self):
533
+ return f"min_val={self.min_val}, max_val={self.max_val}"
534
+
535
+ @torch.jit.export
536
+ def reset_min_max_vals(self):
537
+ """Resets the min/max values."""
538
+ self.min_val.copy_(torch.tensor(float("inf")))
539
+ self.max_val.copy_(torch.tensor(float("-inf")))
540
+
541
+ class MovingAverageMinMaxObserver(MinMaxObserver):
542
+ r"""Observer module for computing the quantization parameters based on the
543
+ moving average of the min and max values.
544
+
545
+ This observer computes the quantization parameters based on the moving
546
+ averages of minimums and maximums of the incoming tensors. The module
547
+ records the average minimum and maximum of incoming tensors, and uses this
548
+ statistic to compute the quantization parameters.
549
+
550
+ Args:
551
+ averaging_constant: Averaging constant for min/max.
552
+ dtype: dtype argument to the `quantize` node needed to implement the
553
+ reference model spec.
554
+ qscheme: Quantization scheme to be used
555
+ reduce_range: Reduces the range of the quantized data type by 1 bit
556
+ quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
557
+ quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
558
+ eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
559
+
560
+ The moving average min/max is computed as follows
561
+
562
+ .. math::
563
+
564
+ \begin{array}{ll}
565
+ x_\text{min} = \begin{cases}
566
+ \min(X) & \text{if~}x_\text{min} = \text{None} \\
567
+ (1 - c) x_\text{min} + c \min(X) & \text{otherwise}
568
+ \end{cases}\\
569
+ x_\text{max} = \begin{cases}
570
+ \max(X) & \text{if~}x_\text{max} = \text{None} \\
571
+ (1 - c) x_\text{max} + c \max(X) & \text{otherwise}
572
+ \end{cases}\\
573
+ \end{array}
574
+
575
+ where :math:`x_\text{min/max}` is the running average min/max, :math:`X` is
576
+ is the incoming tensor, and :math:`c` is the ``averaging_constant``.
577
+
578
+ The scale and zero point are then computed as in
579
+ :class:`~torch.ao.quantization.observer.MinMaxObserver`.
580
+
581
+ .. note:: Only works with ``torch.per_tensor_affine`` quantization scheme.
582
+
583
+ .. note:: If the running minimum equals to the running maximum, the scale
584
+ and zero_point are set to 1.0 and 0.
585
+ """
586
+
587
+ def __init__(
588
+ self,
589
+ averaging_constant=0.01,
590
+ dtype=torch.quint8,
591
+ qscheme=torch.per_tensor_affine,
592
+ reduce_range=False,
593
+ quant_min=None,
594
+ quant_max=None,
595
+ eps=torch.finfo(torch.float32).eps,
596
+ is_dynamic=False,
597
+ **kwargs
598
+ ) -> None:
599
+ if not is_per_tensor(qscheme):
600
+ raise NotImplementedError(
601
+ f"MovingAverageMinMaxObserver's qscheme only support \
602
+ torch.per_tensor_symmetric and torch.per_tensor_affine. \
603
+ but got: {qscheme}"
604
+ )
605
+ self.averaging_constant = averaging_constant
606
+ if is_dynamic and self.averaging_constant != 1:
607
+ raise NotImplementedError(
608
+ "MovingAverageMinMaxObserver doesn't support dynamic quantization for "
609
+ f"averaging constant of {self.averaging_constant}"
610
+ )
611
+ super().__init__(
612
+ dtype=dtype,
613
+ qscheme=qscheme,
614
+ reduce_range=reduce_range,
615
+ quant_min=quant_min,
616
+ quant_max=quant_max,
617
+ eps=eps,
618
+ is_dynamic=is_dynamic,
619
+ **kwargs
620
+ )
621
+
622
+ def forward(self, x_orig):
623
+ if x_orig.numel() == 0:
624
+ return x_orig
625
+ x = x_orig.detach() # avoid keeping autograd tape
626
+ x = x.to(self.min_val.dtype)
627
+ min_val = self.min_val
628
+ max_val = self.max_val
629
+ if min_val == float("inf") and max_val == float("-inf"):
630
+ min_val, max_val = torch.aminmax(x)
631
+ else:
632
+ min_val_cur, max_val_cur = torch.aminmax(x)
633
+ min_val = min_val + self.averaging_constant * (min_val_cur - min_val)
634
+ max_val = max_val + self.averaging_constant * (max_val_cur - max_val)
635
+ self.min_val.copy_(min_val)
636
+ self.max_val.copy_(max_val)
637
+ return x_orig
638
+
639
+
640
+ class PerChannelMinMaxObserver(UniformQuantizationObserverBase):
641
+ r"""Observer module for computing the quantization parameters based on the
642
+ running per channel min and max values.
643
+
644
+ This observer uses the tensor min/max statistics to compute the per channel
645
+ quantization parameters. The module records the running minimum and maximum
646
+ of incoming tensors, and uses this statistic to compute the quantization
647
+ parameters.
648
+
649
+ Args:
650
+ ch_axis: Channel axis
651
+ dtype: dtype argument to the `quantize` node needed to implement the
652
+ reference model spec.
653
+ qscheme: Quantization scheme to be used
654
+ reduce_range: Reduces the range of the quantized data type by 1 bit
655
+ quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
656
+ quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
657
+ eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
658
+
659
+ The quantization parameters are computed the same way as in
660
+ :class:`~torch.ao.quantization.observer.MinMaxObserver`, with the difference
661
+ that the running min/max values are stored per channel.
662
+ Scales and zero points are thus computed per channel as well.
663
+
664
+ .. note:: If the running minimum equals to the running maximum, the scales
665
+ and zero_points are set to 1.0 and 0.
666
+ """
667
+ min_val: torch.Tensor
668
+ max_val: torch.Tensor
669
+
670
+ def __init__(
671
+ self,
672
+ ch_axis=0,
673
+ dtype=torch.quint8,
674
+ qscheme=torch.per_channel_affine,
675
+ reduce_range=False,
676
+ quant_min=None,
677
+ quant_max=None,
678
+ factory_kwargs=None,
679
+ eps=torch.finfo(torch.float32).eps,
680
+ is_dynamic=False,
681
+ **kwargs,
682
+ ) -> None:
683
+ if not is_per_channel(qscheme):
684
+ raise NotImplementedError(
685
+ "PerChannelMinMaxObserver's qscheme only support \
686
+ torch.per_channel_symmetric, torch.per_channel_affine and torch.per_channel_affine_float_qparams."
687
+ )
688
+ if is_dynamic:
689
+ raise NotImplementedError(
690
+ "PerChannelMinMaxObserver doesn't support dynamic quantization"
691
+ )
692
+ super().__init__(
693
+ dtype=dtype,
694
+ qscheme=qscheme,
695
+ reduce_range=reduce_range,
696
+ quant_min=quant_min,
697
+ quant_max=quant_max,
698
+ factory_kwargs=factory_kwargs,
699
+ eps=eps,
700
+ is_dynamic=is_dynamic,
701
+ **kwargs,
702
+ )
703
+ factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
704
+ self.ch_axis = ch_axis
705
+ self.register_buffer("min_val", torch.tensor([], **factory_kwargs))
706
+ self.register_buffer("max_val", torch.tensor([], **factory_kwargs))
707
+ if (
708
+ self.qscheme == torch.per_channel_symmetric
709
+ and self.reduce_range
710
+ and self.dtype == torch.quint8
711
+ ):
712
+ raise NotImplementedError(
713
+ "Cannot reduce range for symmetric quantization for quint8"
714
+ )
715
+
716
+ def forward(self, x_orig):
717
+ return self._forward(x_orig)
718
+
719
+ def _forward(self, x_orig):
720
+ if x_orig.numel() == 0:
721
+ return x_orig
722
+ x = x_orig.detach() # avoid keeping autograd tape
723
+ min_val = self.min_val
724
+ max_val = self.max_val
725
+ x_dim = x.size()
726
+
727
+ new_axis_list = [i for i in range(len(x_dim))] # noqa: C416
728
+ new_axis_list[self.ch_axis] = 0
729
+ new_axis_list[0] = self.ch_axis
730
+ y = x.permute(new_axis_list)
731
+ # Need to match dtype of min/max because the updates to buffers
732
+ # are done in place and types need to match for comparisons
733
+ y = y.to(self.min_val.dtype)
734
+ y = torch.flatten(y, start_dim=1)
735
+ if min_val.numel() == 0 or max_val.numel() == 0:
736
+ min_val, max_val = torch.aminmax(y, dim=1)
737
+ else:
738
+ min_val_cur, max_val_cur = torch.aminmax(y, dim=1)
739
+ min_val = torch.min(min_val_cur, min_val)
740
+ max_val = torch.max(max_val_cur, max_val)
741
+ self.min_val.resize_(min_val.shape)
742
+ self.max_val.resize_(max_val.shape)
743
+ self.min_val.copy_(min_val)
744
+ self.max_val.copy_(max_val)
745
+ return x_orig
746
+
747
+ @torch.jit.export
748
+ def calculate_qparams(self):
749
+ return self._calculate_qparams(self.min_val, self.max_val)
750
+
751
+ def extra_repr(self):
752
+ return f"min_val={self.min_val}, max_val={self.max_val}"
753
+
754
+ def _load_from_state_dict(
755
+ self,
756
+ state_dict: Dict[str, Any],
757
+ prefix: str,
758
+ local_metadata: Dict[str, torch.Tensor],
759
+ strict: bool,
760
+ missing_keys: List[str],
761
+ unexpected_keys: List[str],
762
+ error_msgs: List[str],
763
+ ):
764
+ version = local_metadata.get("version", None)
765
+ if version is None or version < 3:
766
+ local_state = ["min_vals", "max_vals"]
767
+ expected_min_name = "min_vals"
768
+ expected_max_name = "max_vals"
769
+ else:
770
+ local_state = ["min_val", "max_val"]
771
+ expected_min_name = "min_val"
772
+ expected_max_name = "max_val"
773
+ for name in local_state:
774
+ key = prefix + name
775
+ if key in state_dict:
776
+ val = state_dict[key]
777
+ # Custom handling to allow loading min_val or max_val
778
+ # of size N into uninitialized buffers of size 0. The
779
+ # buffers are resized here, and the values are copied in
780
+ # the default state_dict loading code of the parent.
781
+ if name == expected_min_name:
782
+ self.min_val.resize_(val.shape)
783
+ elif name == expected_max_name:
784
+ self.max_val.resize_(val.shape)
785
+ else:
786
+ warnings.warn(f"Observer load_from_state_dict got unexpected name {name}")
787
+ # For torchscript module we need to update the attributes here since we do not
788
+ # call the `_load_from_state_dict` function defined module.py
789
+ if torch.jit.is_scripting():
790
+ if name == expected_min_name:
791
+ self.min_val.copy_(val)
792
+ elif name == expected_max_name:
793
+ self.max_val.copy_(val)
794
+ else:
795
+ warnings.warn(f"Observer load_from_state_dict got unexpected name {name}")
796
+ elif strict:
797
+ missing_keys.append(key)
798
+
799
+ if not torch.jit.is_scripting():
800
+ super()._load_from_state_dict(
801
+ state_dict,
802
+ prefix,
803
+ local_metadata,
804
+ False,
805
+ missing_keys,
806
+ unexpected_keys,
807
+ error_msgs,
808
+ )
809
+
810
+ def _load_from_state_dict_script(
811
+ self,
812
+ state_dict: Dict[str, Any],
813
+ prefix: str,
814
+ local_metadata: Dict[str, torch.Tensor],
815
+ strict: bool,
816
+ missing_keys: List[str],
817
+ unexpected_keys: List[str],
818
+ error_msgs: List[str],
819
+ ):
820
+
821
+ self._load_from_state_dict(
822
+ state_dict,
823
+ prefix,
824
+ local_metadata,
825
+ strict,
826
+ missing_keys,
827
+ unexpected_keys,
828
+ error_msgs,
829
+ )
830
+
831
+ @torch.jit.export
832
+ def reset_min_max_vals(self):
833
+ """Resets the min/max values."""
834
+ # This used to be torch.ones but that does not work because
835
+ # JIT compiler can optimize it via common subexpression elimination
836
+ # in which case both min_val and max_val point to the same tensor.
837
+ self.min_val = torch.rand(0, )
838
+ self.max_val = torch.rand(0, )
839
+
840
+
841
+ class MovingAveragePerChannelMinMaxObserver(PerChannelMinMaxObserver):
842
+ r"""Observer module for computing the quantization parameters based on the
843
+ running per channel min and max values.
844
+
845
+ This observer uses the tensor min/max statistics to compute the per channel
846
+ quantization parameters. The module records the running minimum and maximum
847
+ of incoming tensors, and uses this statistic to compute the quantization
848
+ parameters.
849
+
850
+ Args:
851
+ averaging_constant: Averaging constant for min/max.
852
+ ch_axis: Channel axis
853
+ dtype: Quantized data type
854
+ qscheme: Quantization scheme to be used
855
+ reduce_range: Reduces the range of the quantized data type by 1 bit
856
+ quant_min: Minimum quantization value. If unspecified, it will follow the 8-bit setup.
857
+ quant_max: Maximum quantization value. If unspecified, it will follow the 8-bit setup.
858
+ eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
859
+
860
+ The quantization parameters are computed the same way as in
861
+ :class:`~torch.ao.quantization.observer.MovingAverageMinMaxObserver`, with the
862
+ difference that the running min/max values are stored per channel.
863
+ Scales and zero points are thus computed per channel as well.
864
+
865
+ .. note:: If the running minimum equals to the running maximum, the scales
866
+ and zero_points are set to 1.0 and 0.
867
+ """
868
+
869
+ def __init__(
870
+ self,
871
+ averaging_constant=0.01,
872
+ ch_axis=0,
873
+ dtype=torch.quint8,
874
+ qscheme=torch.per_channel_affine,
875
+ reduce_range=False,
876
+ quant_min=None,
877
+ quant_max=None,
878
+ eps=torch.finfo(torch.float32).eps,
879
+ is_dynamic=False,
880
+ **kwargs
881
+ ) -> None:
882
+ if not is_per_channel(qscheme):
883
+ raise NotImplementedError(
884
+ "MovingAveragePerChannelMinMaxObserver's qscheme only support \
885
+ torch.per_channel_symmetric, torch.per_channel_affine and torch.per_channel_affine_float_qparams."
886
+ )
887
+ if is_dynamic:
888
+ raise NotImplementedError(
889
+ "MovingAveragePerChannelMinMaxObserver doesn't support dynamic quantization"
890
+ )
891
+ super().__init__(
892
+ ch_axis=ch_axis,
893
+ dtype=dtype,
894
+ qscheme=qscheme,
895
+ reduce_range=reduce_range,
896
+ quant_min=quant_min,
897
+ quant_max=quant_max,
898
+ eps=eps,
899
+ is_dynamic=is_dynamic,
900
+ **kwargs
901
+ )
902
+ self.averaging_constant = averaging_constant
903
+
904
+ def forward(self, x_orig):
905
+ if x_orig.numel() == 0:
906
+ return x_orig
907
+ x = x_orig.detach() # avoid keeping autograd tape
908
+ x = x.to(self.min_val.dtype)
909
+ min_val = self.min_val
910
+ max_val = self.max_val
911
+ x_dim = x.size()
912
+
913
+ new_axis_list = [i for i in range(len(x_dim))] # noqa: C416
914
+ new_axis_list[self.ch_axis] = 0
915
+ new_axis_list[0] = self.ch_axis
916
+ y = x.permute(new_axis_list)
917
+ y = torch.flatten(y, start_dim=1)
918
+ if min_val.numel() == 0 or max_val.numel() == 0:
919
+ min_val, max_val = torch.aminmax(y, dim=1)
920
+ else:
921
+ min_val_cur, max_val_cur = torch.aminmax(y, dim=1)
922
+ min_val = min_val + self.averaging_constant * (min_val_cur - min_val)
923
+ max_val = max_val + self.averaging_constant * (max_val_cur - max_val)
924
+ self.min_val.resize_(min_val.shape)
925
+ self.max_val.resize_(max_val.shape)
926
+ self.min_val.copy_(min_val)
927
+ self.max_val.copy_(max_val)
928
+ return x_orig
929
+
930
+
931
+ class HistogramObserver(UniformQuantizationObserverBase):
932
+ r"""
933
+ The module records the running histogram of tensor values along with
934
+ min/max values. ``calculate_qparams`` will calculate scale and zero_point.
935
+
936
+ Args:
937
+ bins: Number of bins to use for the histogram
938
+ upsample_rate: Factor by which the histograms are upsampled, this is
939
+ used to interpolate histograms with varying ranges across observations
940
+ dtype: dtype argument to the `quantize` node needed to implement the
941
+ reference model spec
942
+ qscheme: Quantization scheme to be used
943
+ reduce_range: Reduces the range of the quantized data type by 1 bit
944
+ eps: Epsilon value for float32, Defaults to `torch.finfo(torch.float32).eps`.
945
+
946
+ The scale and zero point are computed as follows:
947
+
948
+ 1. Create the histogram of the incoming inputs.
949
+ The histogram is computed continuously, and the ranges per bin change
950
+ with every new tensor observed.
951
+ 2. Search the distribution in the histogram for optimal min/max values.
952
+ The search for the min/max values ensures the minimization of the
953
+ quantization error with respect to the floating point model.
954
+ 3. Compute the scale and zero point the same way as in the
955
+ :class:`~torch.ao.quantization.MinMaxObserver`
956
+ """
957
+ histogram: torch.Tensor
958
+ min_val: torch.Tensor
959
+ max_val: torch.Tensor
960
+
961
+ def __init__(
962
+ self,
963
+ bins: int = 2048,
964
+ upsample_rate: int = 128,
965
+ dtype: torch.dtype = torch.quint8,
966
+ qscheme=torch.per_tensor_affine,
967
+ reduce_range=False,
968
+ quant_min=None,
969
+ quant_max=None,
970
+ factory_kwargs=None,
971
+ eps=torch.finfo(torch.float32).eps,
972
+ is_dynamic=False,
973
+ **kwargs,
974
+ ) -> None:
975
+ if not is_per_tensor(qscheme):
976
+ raise NotImplementedError(
977
+ "HistogramObserver's qscheme only support torch.per_tensor_symmetric \
978
+ and torch.per_tensor_affine."
979
+ )
980
+ if is_dynamic:
981
+ raise NotImplementedError(
982
+ "HistogramObserver doesn't support dynamic quantization"
983
+ )
984
+ # bins: The number of bins used for histogram calculation.
985
+ super().__init__(
986
+ dtype=dtype,
987
+ qscheme=qscheme,
988
+ reduce_range=reduce_range,
989
+ quant_min=quant_min,
990
+ quant_max=quant_max,
991
+ factory_kwargs=factory_kwargs,
992
+ eps=eps,
993
+ is_dynamic=is_dynamic,
994
+ **kwargs
995
+ )
996
+ factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
997
+ self.bins = bins
998
+ self.register_buffer("histogram", torch.zeros(self.bins, **factory_kwargs))
999
+ self.register_buffer("min_val", torch.tensor(float("inf"), **factory_kwargs))
1000
+ self.register_buffer("max_val", torch.tensor(float("-inf"), **factory_kwargs))
1001
+ self.dst_nbins = 2 ** torch.iinfo(self.dtype).bits
1002
+ self.upsample_rate = upsample_rate
1003
+
1004
+ def _get_norm(
1005
+ self, delta_begin: torch.Tensor, delta_end: torch.Tensor, density: torch.Tensor
1006
+ ) -> torch.Tensor:
1007
+ r"""
1008
+ Compute the norm of the values uniformaly distributed between
1009
+ delta_begin and delta_end.
1010
+ Currently only L2 norm is supported.
1011
+
1012
+ norm = density * (integral_{begin, end} x^2)
1013
+ = density * (end^3 - begin^3) / 3
1014
+ """
1015
+ norm = (
1016
+ delta_end * delta_end * delta_end - delta_begin * delta_begin * delta_begin
1017
+ ) / 3
1018
+ return density * norm
1019
+
1020
+ def _compute_quantization_error(self, next_start_bin: int, next_end_bin: int):
1021
+ r"""
1022
+ Compute the quantization error if we use start_bin to end_bin as the
1023
+ min and max to do the quantization.
1024
+ """
1025
+ bin_width = (self.max_val.item() - self.min_val.item()) / self.bins
1026
+
1027
+ dst_bin_width = bin_width * (next_end_bin - next_start_bin + 1) / self.dst_nbins
1028
+ if dst_bin_width == 0.0:
1029
+ return 0.0
1030
+
1031
+ src_bin = torch.arange(self.bins, device=self.histogram.device)
1032
+ # distances from the beginning of first dst_bin to the beginning and
1033
+ # end of src_bin
1034
+ src_bin_begin = (src_bin - next_start_bin) * bin_width
1035
+ src_bin_end = src_bin_begin + bin_width
1036
+
1037
+ # which dst_bins the beginning and end of src_bin belong to?
1038
+ dst_bin_of_begin = torch.clamp(
1039
+ torch.div(src_bin_begin, dst_bin_width, rounding_mode='floor'), 0, self.dst_nbins - 1
1040
+ )
1041
+ dst_bin_of_begin_center = (dst_bin_of_begin + 0.5) * dst_bin_width
1042
+
1043
+ dst_bin_of_end = torch.clamp(
1044
+ torch.div(src_bin_end, dst_bin_width, rounding_mode='floor'), 0, self.dst_nbins - 1
1045
+ )
1046
+ density = self.histogram / bin_width
1047
+
1048
+ norm = torch.zeros(self.bins, device=self.histogram.device)
1049
+
1050
+ delta_begin = src_bin_begin - dst_bin_of_begin_center
1051
+ delta_end = dst_bin_width / 2
1052
+ norm += self._get_norm(delta_begin,
1053
+ torch.ones(self.bins, device=self.histogram.device) * delta_end,
1054
+ density)
1055
+
1056
+ norm += (dst_bin_of_end - dst_bin_of_begin - 1) * self._get_norm(
1057
+ torch.tensor(-dst_bin_width / 2), torch.tensor(dst_bin_width / 2), density
1058
+ )
1059
+
1060
+ dst_bin_of_end_center = dst_bin_of_end * dst_bin_width + dst_bin_width / 2
1061
+
1062
+ delta_begin = -dst_bin_width / 2
1063
+ delta_end = src_bin_end - dst_bin_of_end_center
1064
+ norm += self._get_norm(torch.tensor(delta_begin), delta_end, density)
1065
+
1066
+ return norm.sum().item()
1067
+
1068
+ def _non_linear_param_search(self) -> Tuple[torch.Tensor, torch.Tensor]:
1069
+ r"""Non-linear parameter search.
1070
+
1071
+ An approximation for L2 error minimization for selecting min/max.
1072
+ By selecting new min/max, we filter out outliers in input distribution.
1073
+ This follows the implementation of NormMinimization::NonlinearQuantizationParamsSearch in
1074
+ caffe2/quantization/server/norm_minimization.cc
1075
+ """
1076
+ assert self.histogram.size()[0] == self.bins, "bins mismatch"
1077
+ bin_width = (self.max_val - self.min_val) / self.bins
1078
+
1079
+ # cumulative sum
1080
+ total = torch.sum(self.histogram).item()
1081
+ cSum = torch.cumsum(self.histogram, dim=0)
1082
+
1083
+ stepsize = 1e-5 # granularity
1084
+ alpha = 0.0 # lower bound
1085
+ beta = 1.0 # upper bound
1086
+ start_bin = 0
1087
+ end_bin = self.bins - 1
1088
+ norm_min = float("inf")
1089
+
1090
+ while alpha < beta:
1091
+ # Find the next step
1092
+ next_alpha = alpha + stepsize
1093
+ next_beta = beta - stepsize
1094
+
1095
+ # find the left and right bins between the quantile bounds
1096
+ l = start_bin
1097
+ r = end_bin
1098
+ while l < end_bin and cSum[l] < next_alpha * total:
1099
+ l = l + 1
1100
+ while r > start_bin and cSum[r] > next_beta * total:
1101
+ r = r - 1
1102
+
1103
+ # decide the next move
1104
+ next_start_bin = start_bin
1105
+ next_end_bin = end_bin
1106
+ if (l - start_bin) > (end_bin - r):
1107
+ # move the start bin
1108
+ next_start_bin = l
1109
+ alpha = next_alpha
1110
+ else:
1111
+ # move the end bin
1112
+ next_end_bin = r
1113
+ beta = next_beta
1114
+
1115
+ if next_start_bin == start_bin and next_end_bin == end_bin:
1116
+ continue
1117
+
1118
+ # calculate the quantization error using next_start_bin and next_end_bin
1119
+ norm = self._compute_quantization_error(next_start_bin, next_end_bin)
1120
+
1121
+ if norm > norm_min:
1122
+ break
1123
+ norm_min = norm
1124
+ start_bin = next_start_bin
1125
+ end_bin = next_end_bin
1126
+
1127
+ new_min = self.min_val + bin_width * start_bin
1128
+ new_max = self.min_val + bin_width * (end_bin + 1)
1129
+ return new_min, new_max
1130
+
1131
+ def _adjust_min_max(
1132
+ self, combined_min: torch.Tensor, combined_max: torch.Tensor, upsample_rate: int
1133
+ ) -> Tuple[torch.Tensor, torch.Tensor, int, int]:
1134
+ # We ensure that:
1135
+ # (combined_max - combined_min)/(downsample_rate*Nbins) = (max - min)/(upsample_rate*Nbins)
1136
+ # This allows us to have a common grid of resolution s, where we can align
1137
+ # the input histogram
1138
+ # start_idx maps min_val to the histogram bin index.
1139
+
1140
+ # Compute the width of histogram bins is a straightforward solution, where
1141
+ # hist_bin_width = (self.max_val - self.min_val) / (self.bins * upsample_rate)
1142
+ # Underflow happens if the numerator is close to the smallest positive subnormal number of FP32
1143
+ # Therefore, we avoid such division operation.
1144
+ downsample_rate = int(
1145
+ torch.ceil(
1146
+ (combined_max - combined_min) * upsample_rate / (self.max_val - self.min_val)
1147
+ ).item()
1148
+ )
1149
+ e = downsample_rate * (self.max_val - self.min_val) / upsample_rate - (combined_max - combined_min)
1150
+ start_idx = int(
1151
+ torch.round((self.min_val - combined_min) * self.bins * upsample_rate / (self.max_val - self.min_val)).item()
1152
+ )
1153
+ combined_max = combined_max + e
1154
+ combined_min = combined_min
1155
+ return combined_min, combined_max, downsample_rate, start_idx
1156
+
1157
+ def _combine_histograms(
1158
+ self,
1159
+ orig_hist: torch.Tensor,
1160
+ new_hist: torch.Tensor,
1161
+ upsample_rate: int,
1162
+ downsample_rate: int,
1163
+ start_idx: int,
1164
+ Nbins: int,
1165
+ ) -> torch.Tensor:
1166
+ # First up-sample the histogram with new data by a factor of L
1167
+ # This creates an approximate probability density thats piecewise constant
1168
+ upsampled_histogram = new_hist.repeat_interleave(upsample_rate)
1169
+ # Now insert the upsampled histogram into the output
1170
+ # histogram, which is initialized with zeros.
1171
+ # The offset at which the histogram is introduced is determined
1172
+ # by the start index as the output histogram can cover a wider range
1173
+ histogram_with_output_range = torch.zeros(
1174
+ (Nbins * downsample_rate), device=orig_hist.device
1175
+ )
1176
+ histogram_with_output_range[
1177
+ start_idx : Nbins * upsample_rate + start_idx
1178
+ ] = upsampled_histogram
1179
+ # Compute integral histogram, double precision is needed to ensure
1180
+ # that there are no overflows
1181
+ integral_histogram = torch.cumsum(
1182
+ histogram_with_output_range, 0, dtype=torch.double
1183
+ )[downsample_rate - 1 :: downsample_rate]
1184
+ # Finally perform interpolation
1185
+ shifted_integral_histogram = torch.zeros((Nbins), device=orig_hist.device)
1186
+ shifted_integral_histogram[1:Nbins] = integral_histogram[0:-1]
1187
+ interpolated_histogram = (
1188
+ integral_histogram - shifted_integral_histogram
1189
+ ) / upsample_rate
1190
+ orig_hist = orig_hist + interpolated_histogram.to(torch.float)
1191
+ return orig_hist
1192
+
1193
+ def forward(self, x_orig: torch.Tensor) -> torch.Tensor:
1194
+ if x_orig.numel() == 0:
1195
+ return x_orig
1196
+ x = x_orig.detach()
1197
+ min_val = self.min_val
1198
+ max_val = self.max_val
1199
+ same_values = min_val.item() == max_val.item()
1200
+ is_uninitialized = min_val == float("inf") and max_val == float("-inf")
1201
+ if is_uninitialized or same_values:
1202
+ min_val, max_val = torch.aminmax(x)
1203
+ self.min_val.resize_(min_val.shape)
1204
+ self.min_val.copy_(min_val)
1205
+ self.max_val.resize_(max_val.shape)
1206
+ self.max_val.copy_(max_val)
1207
+ assert (
1208
+ min_val.numel() == 1 and max_val.numel() == 1
1209
+ ), "histogram min/max values must be scalar."
1210
+ torch.histc(
1211
+ x, self.bins, min=min_val, max=max_val, out=self.histogram # type: ignore[arg-type]
1212
+ )
1213
+ else:
1214
+ new_min, new_max = torch.aminmax(x)
1215
+ combined_min = torch.min(new_min, min_val)
1216
+ combined_max = torch.max(new_max, max_val)
1217
+ # combine the existing histogram and new histogram into 1 histogram
1218
+ # We do this by first upsampling the histogram to a dense grid
1219
+ # and then downsampling the histogram efficiently
1220
+ (
1221
+ combined_min,
1222
+ combined_max,
1223
+ downsample_rate,
1224
+ start_idx,
1225
+ ) = self._adjust_min_max(combined_min, combined_max, self.upsample_rate)
1226
+ assert (
1227
+ combined_min.numel() == 1 and combined_max.numel() == 1
1228
+ ), "histogram min/max values must be scalar."
1229
+
1230
+ # TODO: For some reason, this is required for it to pass torchscript test
1231
+ # combined_min and combined_max should already have requires_grad set to False
1232
+ combined_min, combined_max = combined_min.detach(), combined_max.detach()
1233
+
1234
+ combined_histogram = torch.histc(
1235
+ x, self.bins, min=combined_min, max=combined_max # type: ignore[arg-type]
1236
+ )
1237
+ if combined_min == min_val and combined_max == max_val:
1238
+ combined_histogram += self.histogram
1239
+ else:
1240
+ combined_histogram = self._combine_histograms(
1241
+ combined_histogram,
1242
+ self.histogram,
1243
+ self.upsample_rate,
1244
+ downsample_rate,
1245
+ start_idx,
1246
+ self.bins,
1247
+ )
1248
+
1249
+ self.histogram.detach_().resize_(combined_histogram.shape)
1250
+ self.histogram.copy_(combined_histogram)
1251
+ self.min_val.detach_().resize_(combined_min.shape)
1252
+ self.min_val.copy_(combined_min)
1253
+ self.max_val.detach_().resize_(combined_max.shape)
1254
+ self.max_val.copy_(combined_max)
1255
+ return x_orig
1256
+
1257
+ @torch.jit.export
1258
+ def calculate_qparams(self):
1259
+ is_uninitialized = self.min_val == float("inf") and self.max_val == float(
1260
+ "-inf"
1261
+ )
1262
+ if is_uninitialized:
1263
+ warnings.warn(
1264
+ "must run observer before calling calculate_qparams.\
1265
+ Returning default scale and zero point "
1266
+ )
1267
+ return torch.tensor([1.0], device=self.min_val.device.type), torch.tensor([0], device=self.min_val.device.type)
1268
+ assert self.bins == len(self.histogram), (
1269
+ "The number of bins in histogram should be equal to the number of bins "
1270
+ "supplied while making this observer"
1271
+ )
1272
+
1273
+ new_min, new_max = self._non_linear_param_search()
1274
+
1275
+ return self._calculate_qparams(new_min, new_max)
1276
+
1277
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
1278
+ super()._save_to_state_dict(destination, prefix, keep_vars)
1279
+ destination[prefix + "min_val"] = self.min_val
1280
+ destination[prefix + "max_val"] = self.max_val
1281
+
1282
+ def _load_from_state_dict(
1283
+ self,
1284
+ state_dict,
1285
+ prefix,
1286
+ local_metadata,
1287
+ strict,
1288
+ missing_keys,
1289
+ unexpected_keys,
1290
+ error_msgs,
1291
+ ):
1292
+ version = local_metadata.get("version", None)
1293
+
1294
+ if version is None or version < 3:
1295
+ # if min_val and max_val are not initialized, update their shape
1296
+ # to account for the differences between v2 and v3
1297
+ min_val_name, max_val_name = prefix + "min_val", prefix + "max_val"
1298
+ if min_val_name in state_dict:
1299
+ if state_dict[min_val_name].shape == torch.Size([0]):
1300
+ state_dict[min_val_name] = torch.tensor(float("inf"))
1301
+ if max_val_name in state_dict:
1302
+ if state_dict[max_val_name].shape == torch.Size([0]):
1303
+ state_dict[max_val_name] = torch.tensor(float("-inf"))
1304
+
1305
+ local_state = ["min_val", "max_val"]
1306
+ for name in local_state:
1307
+ key = prefix + name
1308
+ if key in state_dict:
1309
+ val = state_dict[key]
1310
+ setattr(self, name, val)
1311
+ elif strict:
1312
+ missing_keys.append(key)
1313
+ super()._load_from_state_dict(
1314
+ state_dict,
1315
+ prefix,
1316
+ local_metadata,
1317
+ strict,
1318
+ missing_keys,
1319
+ unexpected_keys,
1320
+ error_msgs,
1321
+ )
1322
+
1323
+ def extra_repr(self):
1324
+ return f"min_val={self.min_val}, max_val={self.max_val}"
1325
+
1326
+
1327
+ class FixedQParamsObserver(ObserverBase):
1328
+ r"""
1329
+ Observer that simulates quantize and dequantize with fixed
1330
+ quantization parameters in training time. Only per tensor
1331
+ quantization is supported.
1332
+
1333
+ Args:
1334
+ `scale` (float): fixed scale for the observer
1335
+ `zero_point` (int): fixed zero point for the observer
1336
+ `dtype`, `qscheme`, `quant_min`, `quant_max`
1337
+ """
1338
+
1339
+ scale: torch.Tensor
1340
+ zero_point: torch.Tensor
1341
+
1342
+ def __init__(
1343
+ self,
1344
+ scale,
1345
+ zero_point,
1346
+ dtype=torch.quint8,
1347
+ qscheme=torch.per_tensor_affine,
1348
+ quant_min=0,
1349
+ quant_max=255,
1350
+ is_dynamic=False,
1351
+ **kwargs,
1352
+ ):
1353
+ if is_dynamic:
1354
+ raise NotImplementedError(
1355
+ "FixedQParamsObserver doesn't support dynamic quantization"
1356
+ )
1357
+ super().__init__(dtype=dtype, is_dynamic=is_dynamic, **kwargs)
1358
+ self.quant_min = quant_min
1359
+ self.quant_max = quant_max
1360
+ self.register_buffer('scale', torch.tensor([scale], dtype=torch.float))
1361
+ self.register_buffer('zero_point', torch.tensor([zero_point], dtype=torch.int))
1362
+ self.dtype = dtype
1363
+ self.qscheme = qscheme
1364
+
1365
+ def forward(self, X):
1366
+ return X
1367
+
1368
+ @torch.jit.export
1369
+ def calculate_qparams(self):
1370
+ return self.scale, self.zero_point
1371
+
1372
+
1373
+ class PlaceholderObserver(ObserverBase):
1374
+ r"""
1375
+ Observer that doesn't do anything and just passes its configuration to the
1376
+ quantized module's ``.from_float()``.
1377
+
1378
+ Can be used for quantization to float16 which doesn't require determining
1379
+ ranges.
1380
+
1381
+ Args:
1382
+ dtype: dtype argument to the `quantize` node needed to implement the
1383
+ reference model spec.
1384
+ quant_min: minimum value in quantized domain (TODO: align behavior with other observers)
1385
+ quant_max: maximum value in quantized domain
1386
+ custom_op_name: (temporary) specify this observer for an operator that doesn't require any observation
1387
+ (Can be used in Graph Mode Passes for special case ops).
1388
+ compute_dtype (deprecated): if set, marks the future quantize function to use
1389
+ dynamic quantization instead of static quantization.
1390
+ This field is deprecated, use `is_dynamic=True` instead.
1391
+ is_dynamic: if True, the `quantize` function in the reference model
1392
+ representation taking stats from this observer instance will
1393
+ use dynamic quantization.
1394
+ """
1395
+
1396
+ def __init__(
1397
+ self, dtype=torch.float32, custom_op_name="", compute_dtype=None,
1398
+ quant_min=None, quant_max=None, qscheme=None, eps=None,
1399
+ is_dynamic=False,
1400
+ ) -> None:
1401
+ super().__init__(dtype=dtype, is_dynamic=is_dynamic)
1402
+ if qscheme is None:
1403
+ qscheme = torch.per_tensor_affine
1404
+ if eps is None:
1405
+ eps = torch.finfo(torch.float32).eps
1406
+
1407
+ # dtype of input of the target operator, e.g. for dynamic quantization
1408
+ # ops, the dtype will be float32
1409
+ self.dtype = dtype
1410
+ self.qscheme = qscheme
1411
+ self.quant_min = quant_min
1412
+ self.quant_max = quant_max
1413
+ self.eps = eps
1414
+ self.custom_op = custom_op_name
1415
+ # used for configuration of computation type for dynamic quantization
1416
+ if compute_dtype:
1417
+ is_dynamic = True
1418
+ warnings.warn(
1419
+ "Please use `is_dynamic` instead of `compute_dtype`. \
1420
+ `compute_dtype` will be deprecated in a future release \
1421
+ of PyTorch."
1422
+ )
1423
+
1424
+ def forward(self, x):
1425
+ return x
1426
+
1427
+ @torch.jit.export
1428
+ def extra_repr(self):
1429
+ return f"dtype={self.dtype}, is_dynamic={self.is_dynamic}"
1430
+
1431
+ @torch.jit.export
1432
+ def calculate_qparams(self):
1433
+ raise Exception(
1434
+ "calculate_qparams should not be called for PlaceholderObserver"
1435
+ )
1436
+
1437
+
1438
+ class RecordingObserver(ObserverBase):
1439
+ r"""
1440
+ The module is mainly for debug and records the tensor values during runtime.
1441
+
1442
+ Args:
1443
+ dtype: Quantized data type
1444
+ qscheme: Quantization scheme to be used
1445
+ reduce_range: Reduces the range of the quantized data type by 1 bit
1446
+ """
1447
+ __annotations__ = {"tensor_val": List[Optional[torch.Tensor]]}
1448
+
1449
+ def __init__(self, dtype=torch.quint8):
1450
+ super().__init__(dtype=dtype, is_dynamic=False) # type: ignore[call-arg]
1451
+ self.tensor_val = []
1452
+
1453
+ def forward(self, x):
1454
+ self.tensor_val.append(x.clone())
1455
+ return x
1456
+
1457
+ @torch.jit.export
1458
+ def calculate_qparams(self):
1459
+ raise Exception("calculate_qparams should not be called for RecordingObserver")
1460
+
1461
+ @torch.jit.export
1462
+ def get_tensor_value(self):
1463
+ return self.tensor_val
1464
+
1465
+
1466
+ class NoopObserver(ObserverBase):
1467
+ r"""
1468
+ Observer that doesn't do anything and just passes its configuration to the
1469
+ quantized module's ``.from_float()``.
1470
+
1471
+ Primarily used for quantization to float16 which doesn't require determining
1472
+ ranges.
1473
+
1474
+ Args:
1475
+ dtype: Quantized data type
1476
+ custom_op_name: (temporary) specify this observer for an operator that doesn't require any observation
1477
+ (Can be used in Graph Mode Passes for special case ops).
1478
+ """
1479
+
1480
+ def __init__(self, dtype=torch.float16, custom_op_name="") -> None:
1481
+ super().__init__(dtype=dtype, is_dynamic=False)
1482
+ self.dtype = dtype
1483
+ self.custom_op = custom_op_name
1484
+
1485
+ def forward(self, x):
1486
+ return x
1487
+
1488
+ @torch.jit.export
1489
+ def calculate_qparams(self):
1490
+ raise Exception("calculate_qparams should not be called for NoopObserver")
1491
+
1492
+ class ReuseInputObserver(ObserverBase):
1493
+ r""" This observer is used when we want to reuse the observer from the operator
1494
+ that produces the input Tensor, typically used for operators like reshape, e.g.
1495
+ ```
1496
+ x0 = ...
1497
+ x1 = x0.reshape()
1498
+ ```
1499
+ if we configure x0 to be observed by some observer, let's say MinMaxObserver,
1500
+ and reshape is configured with ReuseInputObserver, we'll reuse the observer instance
1501
+ for x0 for x1 (output of reshape). If x0 is not observed, we also won't observe x1.
1502
+
1503
+ Note: this is only enabled in FX Graph Mode Quantization
1504
+ """
1505
+ def __init__(self):
1506
+ super().__init__(torch.quint8, is_dynamic=False)
1507
+
1508
+ def forward(self, x):
1509
+ return x
1510
+
1511
+ @torch.jit.export
1512
+ def calculate_qparams(self):
1513
+ raise Exception("calculate_qparams should not be called for ReuseInputObserver")
1514
+
1515
+ def _is_observer_script_module(mod, obs_type_name):
1516
+ """Returns true if given mod is an instance of Observer script module."""
1517
+ if isinstance(mod, torch.jit.RecursiveScriptModule):
1518
+ # qualified name looks like '__torch__.torch.ao.quantization.observer.___torch_mangle_2.MinMaxObserver'
1519
+ suffix = mod._c.qualified_name.split(".", 1)[1]
1520
+ name = re.sub(r"\.___torch_mangle_\d+", "", suffix)
1521
+ return obs_type_name in name
1522
+ return False
1523
+
1524
+
1525
+ def _is_activation_post_process(module):
1526
+ return (
1527
+ isinstance(module, (torch.ao.quantization.ObserverBase,
1528
+ torch.ao.quantization.FakeQuantizeBase)) or _is_observer_script_module(module, "quantization.observer")
1529
+ )
1530
+
1531
+
1532
+ def _is_per_channel_script_obs_instance(module):
1533
+ if isinstance(module, torch.jit.RecursiveScriptModule):
1534
+ return _is_observer_script_module(
1535
+ module, "quantization.observer.PerChannelMinMaxObserver"
1536
+ ) or _is_observer_script_module(
1537
+ module, "quantization.observer.MovingAveragePerChannelMinMaxObserver"
1538
+ )
1539
+ return False
1540
+
1541
+
1542
+ def get_observer_state_dict(mod):
1543
+ r"""
1544
+ Returns the state dict corresponding to the observer stats.
1545
+ Traverse the model state_dict and extract out the stats.
1546
+ """
1547
+ od = OrderedDict()
1548
+ if isinstance(mod, torch.jit.RecursiveScriptModule):
1549
+ for k, v in mod.state_dict().items():
1550
+ if "observer" in k:
1551
+ od[k] = v
1552
+ else:
1553
+ # path for GraphModule and nn.Module (eager mode)
1554
+ for k, v in mod.state_dict().items():
1555
+ if "activation_post_process" in k:
1556
+ od[k] = v
1557
+ od._metadata = mod.state_dict()._metadata # type: ignore[attr-defined]
1558
+ return od
1559
+
1560
+
1561
+ def load_observer_state_dict(mod, obs_dict):
1562
+ r"""
1563
+ Given input model and a state_dict containing model observer stats,
1564
+ load the stats back into the model. The observer state_dict can be saved
1565
+ using torch.ao.quantization.get_observer_state_dict
1566
+ """
1567
+ missing_keys: List[str] = []
1568
+ unexpected_keys: List[str] = []
1569
+ for name, module in mod.named_modules():
1570
+ prefix = name + "."
1571
+ if _is_activation_post_process(module):
1572
+ if _is_per_channel_script_obs_instance(module):
1573
+ # For per-channel observers we need to call a custom load_from_state_dict to resize the tensor.
1574
+ # However this is not called when the module is scripted and we end up calling the default one in module.py
1575
+ module._load_from_state_dict_script(
1576
+ obs_dict, prefix, {}, True, missing_keys, unexpected_keys, []
1577
+ )
1578
+ else:
1579
+ module._load_from_state_dict(
1580
+ obs_dict, prefix, {}, False, missing_keys, unexpected_keys, []
1581
+ )
1582
+ for k in missing_keys:
1583
+ if "observer" in k or "activation_post_process" in k:
1584
+ raise Exception(f"Missing keys for observer {k} in state_dict")
1585
+ for k in unexpected_keys:
1586
+ if "observer" in k or "activation_post_process" in k:
1587
+ raise Exception(f"Unexpected keys for observer {k} in state_dict")
1588
+
1589
+
1590
+ # Restrict activations to be in the range (0,127)
1591
+ default_observer = MinMaxObserver.with_args(quant_min=0, quant_max=127)
1592
+ """
1593
+ Default observer for static quantization, usually used for debugging.
1594
+ """
1595
+
1596
+ default_placeholder_observer = PlaceholderObserver
1597
+ """
1598
+ Default placeholder observer, usually used for quantization to torch.float16.
1599
+ """
1600
+
1601
+ default_debug_observer = RecordingObserver
1602
+ """
1603
+ Default debug-only observer.
1604
+ """
1605
+
1606
+ default_weight_observer = MinMaxObserver.with_args(
1607
+ dtype=torch.qint8, qscheme=torch.per_tensor_symmetric
1608
+ )
1609
+ """
1610
+ Default weight observer.
1611
+ """
1612
+
1613
+ weight_observer_range_neg_127_to_127 = MinMaxObserver.with_args(
1614
+ dtype=torch.qint8, qscheme=torch.per_tensor_symmetric,
1615
+ quant_min=-127, quant_max=127, eps=2 ** -12)
1616
+ """
1617
+ Symmetric weight observer with the 8-bit values restricted to [-127, +127], excluding -128.
1618
+ """
1619
+
1620
+ default_histogram_observer = HistogramObserver.with_args(quant_min=0, quant_max=127)
1621
+ """
1622
+ Default histogram observer, usually used for PTQ.
1623
+ """
1624
+
1625
+ default_per_channel_weight_observer = PerChannelMinMaxObserver.with_args(
1626
+ dtype=torch.qint8, qscheme=torch.per_channel_symmetric
1627
+ )
1628
+ """
1629
+ Default per-channel weight observer, usually used on backends where per-channel
1630
+ weight quantization is supported, such as `fbgemm`.
1631
+ """
1632
+
1633
+ per_channel_weight_observer_range_neg_127_to_127 = PerChannelMinMaxObserver.with_args(
1634
+ dtype=torch.qint8, qscheme=torch.per_channel_symmetric,
1635
+ quant_min=-127, quant_max=127, eps=2 ** -12)
1636
+ """
1637
+ Per-channel, symmetric weight observer with the 8-bit values restricted to [-127, +127], excluding -128.
1638
+ """
1639
+
1640
+ default_dynamic_quant_observer = PlaceholderObserver.with_args(
1641
+ dtype=torch.quint8, quant_min=0, quant_max=255, is_dynamic=True,
1642
+ )
1643
+ """
1644
+ Default observer for dynamic quantization.
1645
+ """
1646
+
1647
+ default_float_qparams_observer = PerChannelMinMaxObserver.with_args(
1648
+ dtype=torch.quint8, qscheme=torch.per_channel_affine_float_qparams, ch_axis=0
1649
+ )
1650
+ """
1651
+ Default observer for a floating point zero-point.
1652
+ """
1653
+
1654
+ default_float_qparams_observer_4bit = PerChannelMinMaxObserver.with_args(
1655
+ dtype=torch.quint4x2, qscheme=torch.per_channel_affine_float_qparams, ch_axis=0
1656
+ )
1657
+ """
1658
+ Default observer for a floating point zero-point and 4 bit activations.
1659
+ """
1660
+
1661
+ # TODO(future PR): remove these defaults and enforce activation functions
1662
+ # to explicitly specify their output range
1663
+ default_fixed_qparams_range_neg1to1_observer = FixedQParamsObserver.with_args(
1664
+ scale=2.0 / 256.0, zero_point=128, dtype=torch.quint8, quant_min=0, quant_max=255)
1665
+ default_fixed_qparams_range_0to1_observer = FixedQParamsObserver.with_args(
1666
+ scale=1.0 / 256.0, zero_point=0, dtype=torch.quint8, quant_min=0, quant_max=255)
1667
+ # TODO: the following 2 variables are kept for backwards compatibility; remove after a few releases
1668
+ default_symmetric_fixed_qparams_observer = default_fixed_qparams_range_neg1to1_observer
1669
+ default_affine_fixed_qparams_observer = default_fixed_qparams_range_0to1_observer
1670
+
1671
+ """
1672
+ Default observers for fixed qparams operations.
1673
+ """
1674
+
1675
+ default_reuse_input_observer = ReuseInputObserver
1676
+ """
1677
+ Default observer for operators like reshape that reuses the observer of input to
1678
+ the operator
1679
+ """
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__init__.py ADDED
File without changes
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (183 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/duplicate_dq_pass.cpython-310.pyc ADDED
Binary file (2.04 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/eval_utils.cpython-310.pyc ADDED
Binary file (3.07 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/prepare.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/__pycache__/utils.cpython-310.pyc ADDED
Binary file (15 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/eval_utils.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+
4
+
5
+ def _replace_dropout_for_eval(m: torch.fx.GraphModule):
6
+ """
7
+ Replace the aten training dropout pattern with a noop, intended for eval.
8
+
9
+ For models with dropout torch ops (nn.Dropout, F.dropout), calling model.eval()
10
+ effectively turns these dropout ops into noops. For exported models, however,
11
+ this is not done automatically, since the aten dropout patterns previously generated
12
+ for training remain in the graph. Here we rewrite these dropout patterns with noops
13
+ to avoid incorrectly applying further dropout during eval.
14
+
15
+ See https://github.com/pytorch/pytorch/issues/103681.
16
+ """
17
+ # Avoid circular dependencies
18
+ from .utils import get_aten_graph_module
19
+
20
+ # Needed to ensure subgraph matches are self-contained
21
+ m.graph.eliminate_dead_code()
22
+ m.recompile()
23
+
24
+ for inplace in [False, True]:
25
+
26
+ def dropout_train(x):
27
+ return F.dropout(x, p=0.5, training=True, inplace=inplace)
28
+
29
+ def dropout_eval(x):
30
+ return F.dropout(x, p=0.5, training=False, inplace=inplace)
31
+
32
+ example_inputs = (torch.randn(1),)
33
+ match_pattern = get_aten_graph_module(dropout_train, example_inputs)
34
+ replacement_pattern = get_aten_graph_module(dropout_eval, example_inputs)
35
+
36
+ from torch.fx.subgraph_rewriter import replace_pattern_with_filters
37
+
38
+ replace_pattern_with_filters(
39
+ m,
40
+ match_pattern,
41
+ replacement_pattern,
42
+ match_filters=[],
43
+ ignore_literals=True,
44
+ )
45
+ m.recompile()
46
+
47
+
48
+ def _replace_batchnorm_for_eval(m: torch.fx.GraphModule):
49
+ # TODO(Leslie): This function still fails to support custom momentum and eps value.
50
+ # Enable this support in future updates.
51
+
52
+ # Avoid circular dependencies
53
+ from .utils import get_aten_graph_module
54
+
55
+ # Needed to ensure subgraph matches are self-contained
56
+ m.graph.eliminate_dead_code()
57
+ m.recompile()
58
+
59
+ def bn_train(
60
+ x: torch.Tensor,
61
+ bn_weight: torch.Tensor,
62
+ bn_bias: torch.Tensor,
63
+ bn_running_mean: torch.Tensor,
64
+ bn_running_var: torch.Tensor,
65
+ ):
66
+ return F.batch_norm(
67
+ x, bn_running_mean, bn_running_var, bn_weight, bn_bias, training=True
68
+ )
69
+
70
+ def bn_eval(
71
+ x: torch.Tensor,
72
+ bn_weight: torch.Tensor,
73
+ bn_bias: torch.Tensor,
74
+ bn_running_mean: torch.Tensor,
75
+ bn_running_var: torch.Tensor,
76
+ ):
77
+ return F.batch_norm(
78
+ x, bn_running_mean, bn_running_var, bn_weight, bn_bias, training=False
79
+ )
80
+
81
+ example_inputs = (
82
+ torch.randn(1, 1, 3, 3), # x
83
+ torch.randn(1), # bn_weight
84
+ torch.randn(1), # bn_bias
85
+ torch.randn(1), # bn_running_mean
86
+ torch.randn(1), # bn_running_var
87
+ )
88
+ match_pattern = get_aten_graph_module(bn_train, example_inputs)
89
+ replacement_pattern = get_aten_graph_module(bn_eval, example_inputs)
90
+ from torch.fx.subgraph_rewriter import replace_pattern_with_filters
91
+
92
+ replace_pattern_with_filters(
93
+ m,
94
+ match_pattern,
95
+ replacement_pattern,
96
+ match_filters=[],
97
+ ignore_literals=True,
98
+ )
99
+ m.recompile()
100
+
101
+
102
+ # TODO: also support move_exported_model_to_train
103
+ def _move_exported_model_to_eval(model: torch.fx.GraphModule):
104
+ """
105
+ Move an exported GraphModule to eval mode.
106
+
107
+ This is equivalent to model.eval() but only for certain special ops like dropout, batchnorm.
108
+ QAT users should call this before performing inference on the model.
109
+ """
110
+ _replace_dropout_for_eval(model)
111
+ _replace_batchnorm_for_eval(model)
112
+ return model
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/generate_numeric_debug_handle.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.fx import GraphModule, Node
2
+
3
+ __all__ = ["generate_numeric_debug_handle"]
4
+
5
+
6
+ def generate_numeric_debug_handle(graph_module: GraphModule) -> None:
7
+ unique_id = 0
8
+ for node in graph_module.graph.nodes:
9
+ if node.op == "call_function":
10
+ node.meta["numeric_debug_handle"] = {}
11
+ for arg in node.args:
12
+ if isinstance(arg, Node):
13
+ node.meta["numeric_debug_handle"][arg] = unique_id
14
+ unique_id += 1
15
+
16
+ node.meta["numeric_debug_handle"]["output"] = unique_id
17
+ unique_id += 1
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/graph_utils.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from typing import Any, List, OrderedDict, Set, Optional, Callable
3
+ import operator
4
+ from torch.fx import Node
5
+
6
+ import torch
7
+
8
+ from torch.fx.passes.utils.source_matcher_utils import (
9
+ check_subgraphs_connected,
10
+ get_source_partitions,
11
+ SourcePartition,
12
+ )
13
+
14
+ __all__ = [
15
+ "find_sequential_partitions",
16
+ "get_equivalent_types",
17
+ "update_equivalent_types_dict",
18
+ ]
19
+
20
+ _EQUIVALENT_TYPES: List[Set] = [
21
+ {torch.nn.Conv1d, torch.nn.functional.conv1d},
22
+ {torch.nn.Conv2d, torch.nn.functional.conv2d},
23
+ {torch.nn.AdaptiveAvgPool2d, torch.nn.functional.adaptive_avg_pool2d},
24
+ {torch.nn.ReLU, torch.nn.functional.relu, torch.nn.functional.relu_},
25
+ {torch.nn.BatchNorm2d, torch.nn.functional.batch_norm},
26
+ {torch.nn.Hardtanh, torch.nn.functional.hardtanh, torch.nn.functional.hardtanh_},
27
+ {torch.add, operator.add, operator.iadd, "add", "add_"},
28
+ {torch.mul, operator.mul, operator.imul, "mul", "mul_"},
29
+ ]
30
+
31
+
32
+ def _create_equivalent_types_dict():
33
+ _DICT = {}
34
+ for values in _EQUIVALENT_TYPES:
35
+ for v in values:
36
+ _DICT[v] = list(values)
37
+ return _DICT
38
+
39
+
40
+ _EQUIVALENT_TYPES_DICT = _create_equivalent_types_dict()
41
+
42
+ def get_equivalent_types() -> List[Set]:
43
+ return _EQUIVALENT_TYPES
44
+
45
+ def update_equivalent_types_dict(customized_equivalent_types=None):
46
+ """Help function for user who wants to customize the _EQUIVALENT_TYPES and _EQUIVALENT_TYPES_DICT.
47
+ When customized_equivalent_types passes in,
48
+ re-generate _EQUIVALENT_TYPES and _EQUIVALENT_TYPES_DICT.
49
+ """
50
+ if customized_equivalent_types is None:
51
+ raise ValueError("customized_equivalent_types should not be None")
52
+ global _EQUIVALENT_TYPES
53
+ global _EQUIVALENT_TYPES_DICT
54
+ _EQUIVALENT_TYPES = customized_equivalent_types
55
+ _EQUIVALENT_TYPES_DICT = _create_equivalent_types_dict()
56
+
57
+ def _partitions_sequential(partitions: List[SourcePartition]):
58
+ prev_partition = None
59
+ for partition in partitions:
60
+ if prev_partition is not None and not check_subgraphs_connected(
61
+ prev_partition, partition
62
+ ):
63
+ return False
64
+ prev_partition = partition
65
+ return True
66
+
67
+
68
+ def _get_matching_types(partition_type):
69
+ matching_types = [partition_type]
70
+ if partition_type in _EQUIVALENT_TYPES_DICT:
71
+ matching_types.extend(_EQUIVALENT_TYPES_DICT[partition_type])
72
+ return matching_types
73
+
74
+
75
+ def _valid_type_sequence(partition_types: List[Any]):
76
+ partition_types_set = set() # type: ignore[var-annotated]
77
+ for partition_type in partition_types:
78
+ matching_types = _get_matching_types(partition_type)
79
+ matching_types_set = set(matching_types)
80
+ if len(partition_types_set & matching_types_set) > 0:
81
+ return False
82
+ partition_types_set |= matching_types_set
83
+ return True
84
+
85
+
86
+ def find_sequential_partitions(
87
+ gm: torch.fx.GraphModule,
88
+ partition_types: List[Any],
89
+ include_functional_equivalent=True,
90
+ filter_fn: Optional[Callable[[Node], bool]] = None,
91
+ ):
92
+ if not _valid_type_sequence(partition_types):
93
+ raise ValueError(
94
+ f"Invalid partition types: {partition_types}. Each type in the sequence must be unique"
95
+ )
96
+
97
+ typed_partitions: OrderedDict[Any, List[SourcePartition]] = OrderedDict()
98
+ for partition_type in partition_types:
99
+ types_to_match = _get_matching_types(partition_type)
100
+ partitions = get_source_partitions(gm.graph, types_to_match, filter_fn)
101
+ typed_partitions[partition_type] = list(itertools.chain(*partitions.values()))
102
+
103
+ typed_partitions_list = list(typed_partitions.values())
104
+ fusion_candidates = itertools.product(*typed_partitions_list)
105
+ fused_partitions = []
106
+ for candidate in fusion_candidates:
107
+ if _partitions_sequential(candidate): # type: ignore[arg-type]
108
+ fused_partitions.append(candidate)
109
+ return fused_partitions
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/prepare.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch._subclasses import FakeTensor
3
+ from torch.ao.quantization.fx.prepare import (
4
+ _insert_obs_or_fq,
5
+ _save_state,
6
+ _is_activation_post_process_node,
7
+ _create_obs_or_fq_from_qspec,
8
+ )
9
+ from torch.fx import (
10
+ GraphModule,
11
+ Graph,
12
+ Node,
13
+ )
14
+ from torch.fx.node import Argument
15
+
16
+ from torch.ao.quantization import QConfigMapping
17
+ from torch.ao.quantization.qconfig import QConfigAny
18
+ from torch.ao.quantization.fx.custom_config import PrepareCustomConfig
19
+ from typing import Dict, Tuple, Union, Any, Optional
20
+ from torch.ao.quantization.quantizer import (
21
+ EdgeOrNode,
22
+ SharedQuantizationSpec,
23
+ QuantizationSpecBase,
24
+ )
25
+ from torch.ao.quantization import ObserverOrFakeQuantize
26
+
27
+ # TODO: make pt2e folder private?
28
+ __all__ = [
29
+ "prepare",
30
+ ]
31
+
32
+
33
+ def _find_root_edge_or_node(edge_or_node: EdgeOrNode, shared_with_map: Dict[EdgeOrNode, EdgeOrNode]) -> EdgeOrNode:
34
+ """Find the root node for the sharing tree
35
+ Args:
36
+ edge_or_node: edge/node that we want to find the root
37
+ shared_with_map: each edge/node points to the parent, the root node will points to itself
38
+
39
+ Returns:
40
+ root edge/node
41
+ """
42
+ parent = shared_with_map[edge_or_node]
43
+ if parent == edge_or_node:
44
+ return edge_or_node
45
+ root = _find_root_edge_or_node(parent, shared_with_map)
46
+ # path compression
47
+ shared_with_map[edge_or_node] = root
48
+ return root
49
+
50
+ def _union(parent: EdgeOrNode, child: EdgeOrNode, shared_with_map: Dict[EdgeOrNode, EdgeOrNode]) -> None:
51
+ """Merge the subtree for `child` with `parent`, the order is important here
52
+ """
53
+ root_parent = _find_root_edge_or_node(parent, shared_with_map)
54
+ root_child = _find_root_edge_or_node(child, shared_with_map)
55
+ # union the two trees by pointing the root of child to root of parent
56
+ shared_with_map[root_child] = root_parent
57
+
58
+ def _update_shared_with(child: EdgeOrNode, qspec: QuantizationSpecBase, shared_with_map: Dict[EdgeOrNode, EdgeOrNode]):
59
+ """Update the `shared_with_map` based on the qspec, this applies the `SharedQuantizationSpec`
60
+ configuration and established the relationship between `edge_or_node` with the edge/node that it
61
+ is pointing to, we'll use this information in the end to get the group id
62
+ """
63
+ if isinstance(qspec, SharedQuantizationSpec):
64
+ parent = qspec.edge_or_node
65
+ # we point from edge_or_node to the node that it is sharing_with, e.g.
66
+ # qspec for a = SharedQuantizationSpec(b) means `a` points to `b`
67
+ _union(parent, child, shared_with_map)
68
+
69
+ def _unwrap_shared_qspec(
70
+ qspec: QuantizationSpecBase,
71
+ edge_or_node_to_qspec: Dict[EdgeOrNode, QuantizationSpecBase],
72
+ shared_with_map: Dict[EdgeOrNode, EdgeOrNode]
73
+ ) -> QuantizationSpecBase:
74
+ """Unwraps qspec to get the final root qspec (non SharedQuantizationSpec)
75
+ if qspec is SharedQuantizationSpec
76
+ (1). tries to find the root edge or node for the node that the qspec points to
77
+ (2). recursively find the root qspec based on the qspec for the root node
78
+ """
79
+ if isinstance(qspec, SharedQuantizationSpec):
80
+ sharing_with = qspec.edge_or_node
81
+ root = _find_root_edge_or_node(sharing_with, shared_with_map)
82
+ qspec = edge_or_node_to_qspec[root]
83
+ return _unwrap_shared_qspec(qspec, edge_or_node_to_qspec, shared_with_map)
84
+ return qspec
85
+
86
+ def _has_same_dtype(qspec_a: QuantizationSpecBase, qspec_b: QuantizationSpecBase):
87
+ return (
88
+ hasattr(qspec_a, "dtype") and
89
+ hasattr(qspec_b, "dtype") and
90
+ qspec_a.dtype == qspec_b.dtype
91
+ )
92
+
93
+ def _has_same_is_dynamic(qspec_a: QuantizationSpecBase, qspec_b: QuantizationSpecBase):
94
+ return (
95
+ hasattr(qspec_a, "is_dynamic") and
96
+ hasattr(qspec_b, "is_dynamic") and
97
+ qspec_a.is_dynamic == qspec_b.is_dynamic
98
+ )
99
+
100
+ def _get_edge_or_node_to_qspec(model: torch.fx.GraphModule) -> Dict[EdgeOrNode, QuantizationSpecBase]:
101
+ """Get a map from EdgeOrNode to quantization spec based on annotations on the nodes
102
+ """
103
+ edge_or_node_to_qspec: Dict[EdgeOrNode, QuantizationSpecBase] = {}
104
+ for n in model.graph.nodes:
105
+ if hasattr(n, "meta") and "quantization_annotation" in n.meta:
106
+ qa = n.meta["quantization_annotation"]
107
+ for input_to_n, qspec in qa.input_qspec_map.items():
108
+ input_edge = (input_to_n, n)
109
+ edge_or_node_to_qspec[input_edge] = qspec
110
+ if qa.output_qspec is not None:
111
+ output_node = n
112
+ qspec = qa.output_qspec
113
+ edge_or_node_to_qspec[output_node] = qspec
114
+ return edge_or_node_to_qspec
115
+
116
+ def _union_input_edge_with(input_edge, input_edge_root_qspec, edge_or_node, edge_or_node_to_qspec, shared_with_map):
117
+ """Union input edge with another edge or node, used in implicit sharing to point the current input
118
+ edge to other user edges of the producer node, or the output of producer node since these are
119
+ referring to the same Tensor
120
+ """
121
+ root_qspec = None
122
+ if edge_or_node in edge_or_node_to_qspec:
123
+ qspec = edge_or_node_to_qspec[edge_or_node]
124
+ root_qspec = _unwrap_shared_qspec(qspec, edge_or_node_to_qspec, shared_with_map)
125
+ # TODO: add assertions for types of root qspecs
126
+ if (
127
+ root_qspec is not None and
128
+ _has_same_dtype(root_qspec, input_edge_root_qspec) and
129
+ _has_same_is_dynamic(root_qspec, input_edge_root_qspec)
130
+ ):
131
+ # the input arg to the node should reuse the existing output observer for arg
132
+ # since dtype is the same (we may want to extend this to be a more strict check
133
+ # in the future)
134
+ # so we point from `input_edge` to `arg` (output of the argument)
135
+ _union(edge_or_node, input_edge, shared_with_map)
136
+
137
+
138
+ def _get_edge_or_node_to_group_id(edge_or_node_to_qspec: Dict[EdgeOrNode, QuantizationSpecBase]) -> Dict[EdgeOrNode, int]:
139
+ """Map from edge/node to the group ID, generated from quantization annotations,
140
+ edge/node with the same group ID should use the same observer/fake_quant instance
141
+
142
+ This is applying SharedQuantizationSpec configuration and map each edge/node to a group
143
+ There is another implicit sharing that's built in the quantization, when we have the following:
144
+ * op1 -> op2
145
+ * output of op1: int8_qspec
146
+ * (op1 -> op2) input edge: int8_qspec
147
+ we'll assume sharing between the output of op1 and input of (op1 -> op2) since these are the same Tensor.
148
+
149
+ Figuring out the correct group ID for all edge/node is a standard union find problem:
150
+ https://www.geeksforgeeks.org/introduction-to-disjoint-set-data-structure-or-union-find-algorithm/
151
+
152
+ Args:
153
+ edge_or_node_to_qspec: Dictionary from edge_or_node to the qspec, derived from annotations
154
+ Returns:
155
+ edge_or_node_to_group_id: Dictionary from edge_or_node to group_id (int), all edge or node that
156
+ belongs to the same group should have the same id
157
+
158
+ Example:
159
+ op2 -> cat1 -> cat2
160
+ op1 / /
161
+ op3
162
+ edge_or_node_to_qspec: {
163
+ op1: int8_qspec,
164
+ op2: int8_qspec,
165
+ (op1, cat1): int8_qspc,
166
+ (op2, cat1): SharedQuantizationSpec((op1, cat1)),
167
+ cat1: SharedQuantizationSpec((op1, cat1)),
168
+ (op3, cat2): int8_qspec,
169
+ (cat1, cat2): SharedQuantizationSpec((op3, cat2)),
170
+ cat2: SharedQuantizationSpec((op3, cat2)),
171
+ }
172
+
173
+ edge_or_node_to_group_id = _get_edge_or_node_to_group_id(edge_or_node_to_qspec)
174
+ edge_or_node_to_group_id: {
175
+ op1: 1,
176
+ op2: 1,
177
+ (op1, cat1): 1,
178
+ (op2, cat1): 1,
179
+ cat1: 1,
180
+ (op3, cat2): 1,
181
+ (cat1, cat2): 1,
182
+ cat2: 1,
183
+ }
184
+ # everything are in the same group because (cat1) and (cat1, cat2) are implicitly shared, which
185
+ # connects the two sharing group around cat1 and cat2 op due to transitive sharing
186
+ """
187
+ # means the observer of key should be shared with observer with value, by default it will
188
+ # be shared with itself
189
+ shared_with_map: Dict[EdgeOrNode, EdgeOrNode] = {k: k for k in edge_or_node_to_qspec.keys()}
190
+ for edge_or_node, qspec in edge_or_node_to_qspec.items():
191
+ if isinstance(edge_or_node, torch.fx.Node):
192
+ output_node = edge_or_node
193
+ _update_shared_with(output_node, qspec, shared_with_map)
194
+ else:
195
+ input_edge = edge_or_node
196
+ input_edge_root_qspec = _unwrap_shared_qspec(qspec, edge_or_node_to_qspec, shared_with_map)
197
+
198
+ assert isinstance(input_edge, tuple)
199
+ arg, n = input_edge
200
+ if n.meta["quantization_annotation"].allow_implicit_sharing:
201
+ # NOTE: the order is important here, we first share with other users and then share with previous
202
+ # output because the reverse order could cause circular dependency
203
+ # e.g node1 -> node2
204
+ # \ -> node3
205
+ # when processing (node1, node2), if we first point (node1, node2) to node1
206
+ # Step 1. shared_map = {(node1, node2): node1}
207
+ # Step 2. after that, we point the (node1, node2) to its other user (node1, node3) ,
208
+ # which means shared_map = {(node1, node2): node1, node1: (node1, node3)}
209
+ # because we will point the root of (node1, node2) (in this case node1) to the root of (node1, node3)
210
+ # Step 3. and when we process (node1, node3), it can try to point to node1 as well, then we'll
211
+ # have a circular dependency
212
+ # the following order works around this issue, but this does not allow arbitrary configuration
213
+ # of sharing so it might break in a different case in the future, when it breaks
214
+ # quantizer writer can check the notes here to debug the issue
215
+
216
+ # sharing with other users of the producer node
217
+ # (arg, user)
218
+ for user in arg.users:
219
+ if user is n:
220
+ continue
221
+ arg_to_user_edge = (arg, user)
222
+ _union_input_edge_with(
223
+ input_edge,
224
+ input_edge_root_qspec,
225
+ arg_to_user_edge,
226
+ edge_or_node_to_qspec,
227
+ shared_with_map
228
+ )
229
+
230
+ # sharing with output of producer node
231
+ _union_input_edge_with(input_edge, input_edge_root_qspec, arg, edge_or_node_to_qspec, shared_with_map)
232
+
233
+ _update_shared_with(input_edge, qspec, shared_with_map)
234
+
235
+ # now that we get the sharing relations between all edges and nodes, we can assingn group ids
236
+ cur_group_id = 0
237
+ edge_or_node_to_group_id: Dict[EdgeOrNode, int] = {}
238
+ for edge_or_node in shared_with_map.keys():
239
+ root = _find_root_edge_or_node(edge_or_node, shared_with_map)
240
+ if root not in edge_or_node_to_group_id:
241
+ edge_or_node_to_group_id[root] = cur_group_id
242
+ cur_group_id += 1
243
+ edge_or_node_to_group_id[edge_or_node] = edge_or_node_to_group_id[root]
244
+
245
+ return edge_or_node_to_group_id
246
+
247
+ def _get_obs_or_fq_map(
248
+ edge_or_node_to_group_id: Dict[EdgeOrNode, int],
249
+ edge_or_node_to_qspec: Dict[EdgeOrNode, QuantizationSpecBase],
250
+ is_qat: bool
251
+ ) -> Dict[EdgeOrNode, ObserverOrFakeQuantize]:
252
+ """Generates the EdgeOrNode to observer/fake_quant instances
253
+ Makes sure that for EdgeOrNode that has the same group_id should have the same observer or fake quant
254
+ instances
255
+ """
256
+ obs_or_fq_map: Dict[EdgeOrNode, ObserverOrFakeQuantize] = {}
257
+ group_id_to_obs_or_fq: Dict[int, ObserverOrFakeQuantize] = {}
258
+ for edge_or_node, qspec in edge_or_node_to_qspec.items():
259
+ group_id = edge_or_node_to_group_id[edge_or_node]
260
+ if group_id not in group_id_to_obs_or_fq:
261
+ # TODO: maybe edge_or_node_to_qspec should be edge_or_node_to_root_qspec, this will simplify
262
+ # the implementation for _create_obs_or_fq_from_qspec
263
+ group_id_to_obs_or_fq[group_id] = _create_obs_or_fq_from_qspec(qspec, obs_or_fq_map, is_qat)
264
+ obs_or_fq_map[edge_or_node] = group_id_to_obs_or_fq[group_id]
265
+ return obs_or_fq_map
266
+
267
+ def _maybe_insert_input_observer_for_arg_or_kwarg(
268
+ node: Union[Node, Any],
269
+ arg: Argument,
270
+ qconfig: QConfigAny,
271
+ model: torch.nn.Module,
272
+ named_modules: Dict[str, torch.nn.Module],
273
+ obs_or_fq_map: Dict[EdgeOrNode, ObserverOrFakeQuantize],
274
+ is_qat: bool,
275
+ ) -> Argument:
276
+ """
277
+ Given a `node` and an `arg`, inserts an input observer between
278
+ `node` and `arg` if necessary.
279
+ """
280
+ # for ops such as torch.cat([x0, x1]),
281
+ # traverse through the list
282
+ if isinstance(arg, (list, tuple)):
283
+ new_arg_to_return = []
284
+ for inner_arg in arg:
285
+ new_inner_arg = _maybe_insert_input_observer_for_arg_or_kwarg(
286
+ node, inner_arg, qconfig, model, named_modules, obs_or_fq_map, is_qat,
287
+ )
288
+ new_arg_to_return.append(new_inner_arg)
289
+ return type(arg)(new_arg_to_return)
290
+
291
+ if not isinstance(arg, Node):
292
+ return arg
293
+ assert isinstance(arg, Node)
294
+ # default (no observer)
295
+ new_arg = arg
296
+
297
+ # find the original `arg` node to the current node, skipping inserted observer/fake_quant nodes
298
+ original_arg = arg
299
+ while _is_activation_post_process_node(original_arg, named_modules):
300
+ original_arg = original_arg.args[0] # type: ignore[assignment]
301
+ assert isinstance(original_arg, Node), f"expect original argument to be a Node, but got: {type(original_arg)}"
302
+
303
+ input_edge = (original_arg, node)
304
+ if input_edge not in obs_or_fq_map:
305
+ return new_arg
306
+ # input_edge needs to be observed
307
+ input_edge_obs_or_fq = obs_or_fq_map[input_edge]
308
+ if input_edge_obs_or_fq is None:
309
+ return new_arg
310
+
311
+ arg_as_output_obs_or_fq = obs_or_fq_map.get(original_arg, None)
312
+ # the arg is observed as the output and is using the same instance as the input_edge
313
+ # we'll reuse the inserted observer/fake_quant
314
+ if arg_as_output_obs_or_fq is not None and id(arg_as_output_obs_or_fq) == id(input_edge_obs_or_fq):
315
+ return new_arg
316
+
317
+ # otherwise, we'll insert a new observer/fake_quant node
318
+
319
+ existing_obs_node = None
320
+ # skip inserting new observers if the same observer instance is inserted before for another user
321
+ # Example:
322
+ # conv1 -> obs1 -> existing_obs -> conv2
323
+ # \ -> conv3
324
+ #
325
+ # instead of inserting new observers we will have:
326
+ # conv1 -> obs1 -> existing_obs -> conv2
327
+ # \ -> conv3
328
+ for maybe_obs_node in arg.users.keys():
329
+ if not _is_activation_post_process_node(maybe_obs_node, named_modules):
330
+ continue
331
+ maybe_obs_mod = named_modules[maybe_obs_node.target] # type: ignore[index]
332
+ if id(maybe_obs_mod) == id(input_edge_obs_or_fq):
333
+ return maybe_obs_node
334
+
335
+ new_arg = _insert_obs_or_fq(arg, input_edge_obs_or_fq, model, named_modules, model.graph)
336
+ return new_arg
337
+
338
+ def _maybe_insert_input_observers_for_node(
339
+ node: Node,
340
+ qconfig: QConfigAny,
341
+ model: torch.nn.Module,
342
+ named_modules: Dict[str, torch.nn.Module],
343
+ obs_or_fq_map: Dict[EdgeOrNode, ObserverOrFakeQuantize],
344
+ is_qat: bool,
345
+ ) -> None:
346
+ """
347
+ If needed, inserts observers to the input args and kwargs of `node`.
348
+ Note: modifies `node` inplace.
349
+
350
+ For example, if cur_node needs an observer after prev_node, we change from
351
+
352
+ prev_node -> cur_node
353
+
354
+ To
355
+
356
+ prev_node -> obs -> cur_node
357
+
358
+ """
359
+ # Look through every input arg. If that arg's target dtype does not
360
+ # match the current node's target dtype, insert an observer.
361
+ new_args = []
362
+ for arg in node.args:
363
+ new_arg = _maybe_insert_input_observer_for_arg_or_kwarg(
364
+ node, arg, qconfig, model, named_modules, obs_or_fq_map, is_qat,
365
+ )
366
+ new_args.append(new_arg)
367
+
368
+ # Clone has a memory_format kwarg and zeros_like has a pin_memory kwarg
369
+ # that persist in exported graph. This is just a work around for these.
370
+ assert (
371
+ node.target == torch.ops.aten.clone.default or
372
+ node.target == torch.ops.aten.zeros_like.default or
373
+ len(node.kwargs) == 0
374
+ ), " expecting kwargs for aten op IR to be empty"
375
+
376
+ # assign the new args to the node, inplace
377
+ node.args = tuple(new_args)
378
+
379
+ def _maybe_insert_output_observer_for_node(
380
+ node: Node,
381
+ model: torch.nn.Module,
382
+ named_modules: Dict[str, torch.nn.Module],
383
+ graph: Graph,
384
+ obs_or_fq_map: Dict[EdgeOrNode, ObserverOrFakeQuantize],
385
+ is_qat: bool,
386
+ ) -> Optional[Node]:
387
+ if node in obs_or_fq_map:
388
+ output_act_obs_or_fq = obs_or_fq_map[node]
389
+ return _insert_obs_or_fq(node, output_act_obs_or_fq, model, named_modules, graph)
390
+ return None
391
+
392
+ def _maybe_insert_input_and_output_observers_for_node(
393
+ node: Node,
394
+ model: torch.fx.GraphModule,
395
+ obs_or_fq_map: Dict[EdgeOrNode, ObserverOrFakeQuantize],
396
+ is_qat: bool,
397
+ ):
398
+ this_node_quantization_annotation = node.meta["quantization_annotation"] if "quantization_annotation" in node.meta else None
399
+ if this_node_quantization_annotation is None:
400
+ return
401
+
402
+ named_modules = dict(model.named_modules(remove_duplicate=False))
403
+ _maybe_insert_input_observers_for_node(
404
+ node,
405
+ None, # qconfig
406
+ model,
407
+ named_modules,
408
+ obs_or_fq_map,
409
+ is_qat,
410
+ )
411
+
412
+ output_is_a_tensor = "val" in node.meta and isinstance(node.meta["val"], FakeTensor)
413
+ if not output_is_a_tensor:
414
+ return
415
+
416
+ # this returns the new observer node if it was needed
417
+ maybe_output_obs_node = _maybe_insert_output_observer_for_node(
418
+ node, model, named_modules, model.graph, obs_or_fq_map, is_qat)
419
+
420
+ if maybe_output_obs_node is None:
421
+ return
422
+ # Update users of original node to use the output observer
423
+ # instead. For example, change
424
+ #
425
+ # next_node
426
+ # /
427
+ # cur_node -> obs
428
+ #
429
+ # to
430
+ #
431
+ # next_node
432
+ # /
433
+ # cur_node -> obs
434
+ #
435
+ # We need to save orig users before updating uses because
436
+ # the list of users will change as we update uses
437
+ orig_users = list(node.users.keys())
438
+ for user_node in orig_users:
439
+ if user_node is maybe_output_obs_node:
440
+ continue
441
+ user_node.replace_input_with(node, maybe_output_obs_node)
442
+
443
+ def prepare(
444
+ model: GraphModule,
445
+ node_name_to_scope: Dict[str, Tuple[str, type]],
446
+ is_qat: bool,
447
+ ) -> GraphModule:
448
+ # Since we are mutating the graph as we go, we iterate over the original
449
+ # nodes before observer insertion, instead of model.graph.nodes.
450
+ nodes_before_observation = list(model.graph.nodes)
451
+
452
+ # At the high level we construct a map from EdgeOrNode to a observer_or_fake_quant instance
453
+ # all edge/nodes that belongs to the same group will use the same instance
454
+ # and when we insert observers we'll just query this map to get the correct observer_or_fake_quant
455
+ # instance
456
+ edge_or_node_to_qspec = _get_edge_or_node_to_qspec(model)
457
+ edge_or_node_to_group_id = _get_edge_or_node_to_group_id(edge_or_node_to_qspec)
458
+ obs_or_fq_map = _get_obs_or_fq_map(edge_or_node_to_group_id, edge_or_node_to_qspec, is_qat)
459
+
460
+ for node in nodes_before_observation:
461
+ # TODO: simplify logic for inserting observers
462
+ _maybe_insert_input_and_output_observers_for_node(node, model, obs_or_fq_map, is_qat)
463
+
464
+ model = GraphModule(model, model.graph)
465
+
466
+ _save_state(
467
+ model,
468
+ {}, # node_name_to_qconfig
469
+ node_name_to_scope,
470
+ PrepareCustomConfig(),
471
+ {}, # equalization_node_name_to_qconfig
472
+ QConfigMapping(),
473
+ is_qat,
474
+ set() # observed_node_names
475
+ )
476
+ return model
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/representation/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .rewrite import reference_representation_rewrite
2
+
3
+ __all__ = [
4
+ "reference_representation_rewrite",
5
+ ]
videollama2/lib/python3.10/site-packages/torch/ao/quantization/pt2e/representation/__pycache__/rewrite.cpython-310.pyc ADDED
Binary file (12.9 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/quantization/qconfig.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import namedtuple
2
+ from typing import Optional, Any, Union, Type
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from torch.ao.quantization.fake_quantize import (
7
+ FakeQuantize,
8
+ FakeQuantizeBase,
9
+ default_fake_quant,
10
+ default_dynamic_fake_quant,
11
+ default_per_channel_weight_fake_quant,
12
+ default_weight_fake_quant,
13
+ default_fused_act_fake_quant,
14
+ default_fused_wt_fake_quant,
15
+ FusedMovingAvgObsFakeQuantize,
16
+ default_fused_per_channel_wt_fake_quant,
17
+ default_embedding_fake_quant,
18
+ default_embedding_fake_quant_4bit,
19
+ fused_wt_fake_quant_range_neg_127_to_127,
20
+ fused_per_channel_wt_fake_quant_range_neg_127_to_127,
21
+ )
22
+
23
+ from .observer import (
24
+ _PartialWrapper,
25
+ MinMaxObserver,
26
+ HistogramObserver,
27
+ MovingAverageMinMaxObserver,
28
+ NoopObserver,
29
+ PlaceholderObserver,
30
+ ReuseInputObserver,
31
+ default_debug_observer,
32
+ default_dynamic_quant_observer,
33
+ default_float_qparams_observer,
34
+ default_float_qparams_observer_4bit,
35
+ default_observer,
36
+ default_per_channel_weight_observer,
37
+ default_placeholder_observer,
38
+ default_weight_observer,
39
+ weight_observer_range_neg_127_to_127,
40
+ per_channel_weight_observer_range_neg_127_to_127,
41
+ default_reuse_input_observer,
42
+ ObserverBase,
43
+ )
44
+ import warnings
45
+ import copy
46
+
47
+ __all__ = [
48
+ "QConfig",
49
+ # TODO: deprecated, remove
50
+ "QConfigDynamic",
51
+ "default_qconfig",
52
+ "default_debug_qconfig",
53
+ "default_per_channel_qconfig",
54
+ "default_dynamic_qconfig",
55
+ "float16_dynamic_qconfig",
56
+ "float16_static_qconfig",
57
+ "per_channel_dynamic_qconfig",
58
+ "float_qparams_weight_only_qconfig",
59
+ "float_qparams_weight_only_qconfig_4bit",
60
+ "default_quint8_weight_qconfig",
61
+ "default_qat_qconfig",
62
+ "default_dynamic_qat_qconfig",
63
+ "default_weight_only_qconfig",
64
+ "default_activation_only_qconfig",
65
+ "default_qat_qconfig_v2",
66
+ "default_reuse_input_qconfig",
67
+ "default_symmetric_qnnpack_qconfig",
68
+ "default_per_channel_symmetric_qnnpack_qconfig",
69
+ "default_symmetric_qnnpack_qat_qconfig",
70
+ "default_per_channel_symmetric_qnnpack_qat_qconfig",
71
+ "default_embedding_qat_qconfig",
72
+ "default_embedding_qat_qconfig_4bit",
73
+ "get_default_qconfig",
74
+ "get_default_qat_qconfig",
75
+ "get_default_qconfig_dict",
76
+ "get_default_qat_qconfig_dict",
77
+ "QConfigAny",
78
+ "qconfig_equals",
79
+
80
+ ]
81
+
82
+ class QConfig(namedtuple('QConfig', ['activation', 'weight'])):
83
+ """
84
+ Describes how to quantize a layer or a part of the network by providing
85
+ settings (observer classes) for activations and weights respectively.
86
+
87
+
88
+ Note that QConfig needs to contain observer **classes** (like MinMaxObserver) or a callable that returns
89
+ instances on invocation, not the concrete observer instances themselves.
90
+ Quantization preparation function will instantiate observers multiple times for each of the layers.
91
+
92
+
93
+ Observer classes have usually reasonable default arguments, but they can be overwritten with `with_args`
94
+ method (that behaves like functools.partial)::
95
+
96
+ my_qconfig = QConfig(
97
+ activation=MinMaxObserver.with_args(dtype=torch.qint8),
98
+ weight=default_observer.with_args(dtype=torch.qint8))
99
+
100
+ """
101
+ def __new__(cls, activation, weight):
102
+ # catch common mistakes
103
+ if isinstance(activation, nn.Module) or isinstance(weight, nn.Module):
104
+ raise ValueError("QConfig received observer instance, please pass observer class instead. " +
105
+ "Use MyObserver.with_args(x=1) to override arguments to constructor if needed")
106
+ return super().__new__(cls, activation, weight)
107
+
108
+
109
+ class QConfigDynamic(namedtuple('QConfigDynamic', ['activation', 'weight'])):
110
+ """
111
+ Describes how to dynamically quantize a layer or a part of the network by providing
112
+ settings (observer classes) for weights.
113
+
114
+ It's like QConfig, but for dynamic quantization.
115
+
116
+ Note that QConfigDynamic needs to contain observer **classes** (like MinMaxObserver) or a callable that returns
117
+ instances on invocation, not the concrete observer instances themselves.
118
+ Quantization function will instantiate observers multiple times for each of the layers.
119
+
120
+ Observer classes have usually reasonable default arguments, but they can be overwritten with `with_args`
121
+ method (that behaves like functools.partial)::
122
+
123
+ my_qconfig = QConfigDynamic(weight=default_observer.with_args(dtype=torch.qint8))
124
+ """
125
+ def __new__(cls, activation=torch.nn.Identity, weight=torch.nn.Identity):
126
+ # catch common mistakes
127
+ if isinstance(weight, nn.Module):
128
+ raise ValueError("QConfigDynamic received observer instance, please pass observer class instead. " +
129
+ "Use MyObserver.with_args(x=1) to override arguments to constructor if needed")
130
+ warnings.warn("QConfigDynamic is going to be deprecated in PyTorch 1.12, please use QConfig instead")
131
+ return super().__new__(cls, activation, weight)
132
+
133
+
134
+ default_qconfig = QConfig(activation=default_observer,
135
+ weight=default_weight_observer)
136
+ """
137
+ Default qconfig configuration.
138
+ """
139
+
140
+ default_debug_qconfig = QConfig(weight=default_weight_observer,
141
+ activation=default_debug_observer)
142
+ """
143
+ Default qconfig configuration for debugging.
144
+ """
145
+
146
+ default_per_channel_qconfig = QConfig(activation=default_observer,
147
+ weight=default_per_channel_weight_observer)
148
+ """
149
+ Default qconfig configuration for per channel weight quantization.
150
+ """
151
+
152
+ default_dynamic_qconfig = QConfig(activation=default_dynamic_quant_observer,
153
+ weight=default_weight_observer)
154
+ """
155
+ Default dynamic qconfig.
156
+ """
157
+
158
+ float16_dynamic_qconfig = QConfig(activation=PlaceholderObserver.with_args(dtype=torch.float16, is_dynamic=True),
159
+ weight=PlaceholderObserver.with_args(dtype=torch.float16))
160
+ """
161
+ Dynamic qconfig with weights quantized to `torch.float16`.
162
+ """
163
+
164
+ float16_static_qconfig = QConfig(activation=PlaceholderObserver.with_args(dtype=torch.float16),
165
+ weight=PlaceholderObserver.with_args(dtype=torch.float16))
166
+ """
167
+ Dynamic qconfig with both activations and weights quantized to `torch.float16`.
168
+ """
169
+
170
+ per_channel_dynamic_qconfig = QConfig(activation=default_dynamic_quant_observer,
171
+ weight=default_per_channel_weight_observer)
172
+ """
173
+ Dynamic qconfig with weights quantized per channel.
174
+ """
175
+
176
+ float_qparams_weight_only_qconfig = QConfig(
177
+ activation=default_placeholder_observer,
178
+ weight=default_float_qparams_observer)
179
+ """
180
+ Dynamic qconfig with weights quantized with a floating point zero_point.
181
+ """
182
+
183
+ float_qparams_weight_only_qconfig_4bit = QConfig(
184
+ activation=default_placeholder_observer,
185
+ weight=default_float_qparams_observer_4bit)
186
+
187
+ default_qat_qconfig = QConfig(activation=default_fake_quant,
188
+ weight=default_weight_fake_quant)
189
+ """
190
+ Default qconfig for QAT.
191
+ """
192
+
193
+ default_dynamic_qat_qconfig = QConfig(activation=default_dynamic_fake_quant,
194
+ weight=default_weight_fake_quant)
195
+ """
196
+ Default qconfig for dynamic QAT.
197
+ """
198
+
199
+ default_weight_only_qconfig = QConfig(activation=torch.nn.Identity,
200
+ weight=default_weight_fake_quant)
201
+ """
202
+ Default qconfig for quantizing weights only.
203
+ """
204
+
205
+ default_activation_only_qconfig = QConfig(activation=default_fake_quant,
206
+ weight=torch.nn.Identity)
207
+ """
208
+ Default qconfig for quantizing activations only.
209
+ """
210
+
211
+ # QAT config that uses a fused observer + fake quant modules for optimized training performance.
212
+ # to modify the activation/weight observers, the default entries in fake_quantize.py can be modified.
213
+ default_qat_qconfig_v2 = QConfig(activation=default_fused_act_fake_quant, weight=default_fused_wt_fake_quant)
214
+ """
215
+ Fused version of `default_qat_config`, has performance benefits.
216
+ """
217
+
218
+ default_reuse_input_qconfig = QConfig(activation=default_reuse_input_observer,
219
+ weight=NoopObserver)
220
+ """
221
+ Default qconfig for operators that reuse the observers from input Tensor, e.g. reshape
222
+ """
223
+
224
+ def get_default_qconfig(backend='x86', version=0):
225
+ """
226
+ Returns the default PTQ qconfig for the specified backend.
227
+
228
+ Args:
229
+ * `backend` (str): a string representing the target backend. Currently supports
230
+ `x86` (default), `fbgemm`, `qnnpack` and `onednn`.
231
+
232
+ Return:
233
+ qconfig
234
+ """
235
+ supported_backends = ["fbgemm", "x86", "qnnpack", "onednn"]
236
+ if backend not in supported_backends:
237
+ raise AssertionError(
238
+ "backend: " + str(backend) +
239
+ f" not supported. backend must be one of {supported_backends}"
240
+ )
241
+
242
+ if version == 0:
243
+ if backend == 'fbgemm':
244
+ qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=True),
245
+ weight=default_per_channel_weight_observer)
246
+ elif backend == 'qnnpack':
247
+ # TODO: make this compatible with xnnpack constraints
248
+ qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=False),
249
+ weight=default_weight_observer)
250
+ elif backend == 'onednn':
251
+ if not torch.cpu._is_cpu_support_vnni():
252
+ warnings.warn(
253
+ "Default qconfig of oneDNN backend with reduce_range of false may have accuracy issues "
254
+ "on CPU without Vector Neural Network Instruction support.")
255
+ qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=False),
256
+ weight=default_per_channel_weight_observer)
257
+ elif backend == 'x86':
258
+ qconfig = QConfig(activation=HistogramObserver.with_args(reduce_range=True),
259
+ weight=default_per_channel_weight_observer)
260
+ else:
261
+ # won't reach
262
+ qconfig = default_qconfig
263
+ else:
264
+ raise AssertionError("Version number: " + str(version) +
265
+ " in get_default_qconfig is not supported. Version number must be 0")
266
+
267
+ return qconfig
268
+
269
+ """
270
+ Default, symmetric PTQ qconfig for the specified backend. And a per_channel
271
+ variant of the same.
272
+
273
+ Symmetric here applies to signed weights with zero point = 0, and additional
274
+ value restrictions. The activations are also signed 8-bit integers with this
275
+ qconfig.
276
+
277
+ * Once this change is merged [as of 3/17/22], with backend or qengine =
278
+ 'qnnpack', some quantized operators with this symmetric qconfig may use
279
+ operators from xnnpack library.
280
+
281
+ ** Support to use xnnpack ops with `qnnpack` backed for asymmetric
282
+ qconfig (returned by get_default_qconfig()) is not available yet.
283
+
284
+ * This qconfig uses signed activations and weights. Weights have added
285
+ restrictions such as zero point is forced to be 0, making the weights
286
+ symmetric, hence the name. And the 8-bit quantized values are
287
+ restricting to to [-127, +127], excluding -128.
288
+
289
+ * xnnpack has a requantization scale value restriction, 0x1p-32 <=
290
+ requantization_scale < 256.0 where, `requantization_scale = (input_scale
291
+ * kernel_scale) / (output_scale)`. Using this eps (w/ assumed max value
292
+ of 256) is to prevent requantization_scale to go below xnnpack lower
293
+ threshold.
294
+ """
295
+ default_symmetric_qnnpack_qconfig = QConfig(activation=HistogramObserver.with_args(dtype=torch.qint8,
296
+ reduce_range=False,
297
+ eps=2 ** -12),
298
+ weight=weight_observer_range_neg_127_to_127)
299
+
300
+ default_per_channel_symmetric_qnnpack_qconfig = QConfig(activation=HistogramObserver.with_args(dtype=torch.qint8,
301
+ reduce_range=False,
302
+ eps=2 ** -12),
303
+ weight=per_channel_weight_observer_range_neg_127_to_127)
304
+
305
+ default_embedding_qat_qconfig = QConfig(activation=NoopObserver.with_args(dtype=torch.float32),
306
+ weight=default_embedding_fake_quant)
307
+
308
+ default_embedding_qat_qconfig_4bit = QConfig(activation=NoopObserver.with_args(dtype=torch.float32),
309
+ weight=default_embedding_fake_quant_4bit)
310
+
311
+ default_quint8_weight_qconfig = QConfig(activation=HistogramObserver, weight=MinMaxObserver)
312
+
313
+ def get_default_qat_qconfig(backend='x86', version=1):
314
+ """
315
+ Returns the default QAT qconfig for the specified backend.
316
+
317
+ Args:
318
+ * `backend` (str): a string representing the target backend. Currently supports
319
+ `x86` (default), `fbgemm`, `qnnpack` and `onednn`.
320
+ * `version`: version, for backwards compatibility. Can be `None` or `1`.
321
+
322
+ Return:
323
+ qconfig
324
+ """
325
+ supported_backends = ["fbgemm", "x86", "qnnpack", "onednn"]
326
+ if backend not in supported_backends:
327
+ raise AssertionError(
328
+ "backend: " + str(backend) +
329
+ f" not supported. backend must be one of {supported_backends}"
330
+ )
331
+
332
+ # Histogram observer is too slow for quantization aware training
333
+ if version == 0:
334
+ if backend == 'fbgemm':
335
+ qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
336
+ quant_min=0,
337
+ quant_max=255,
338
+ reduce_range=True),
339
+ weight=default_per_channel_weight_fake_quant)
340
+ elif backend == 'qnnpack':
341
+ qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
342
+ quant_min=0,
343
+ quant_max=255,
344
+ reduce_range=False),
345
+ weight=default_weight_fake_quant)
346
+ elif backend == 'onednn':
347
+ qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
348
+ quant_min=0,
349
+ quant_max=255),
350
+ weight=default_per_channel_weight_fake_quant)
351
+ elif backend == 'x86':
352
+ qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
353
+ quant_min=0,
354
+ quant_max=255,
355
+ reduce_range=True),
356
+ weight=default_per_channel_weight_fake_quant)
357
+ else:
358
+ qconfig = default_qat_qconfig
359
+ # Use the fused observe + fake_quant modules for doing QAT.
360
+ elif version == 1:
361
+ if backend == 'fbgemm':
362
+ qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
363
+ quant_min=0,
364
+ quant_max=255,
365
+ reduce_range=True),
366
+ weight=default_fused_per_channel_wt_fake_quant)
367
+ elif backend == 'qnnpack':
368
+ # TODO: make this compatible with xnnpack constraints
369
+ qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
370
+ quant_min=0,
371
+ quant_max=255,
372
+ reduce_range=False),
373
+ weight=default_fused_wt_fake_quant)
374
+ elif backend == 'onednn':
375
+ qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
376
+ quant_min=0,
377
+ quant_max=255),
378
+ weight=default_fused_per_channel_wt_fake_quant)
379
+ elif backend == 'x86':
380
+ qconfig = QConfig(activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
381
+ quant_min=0,
382
+ quant_max=255,
383
+ reduce_range=True),
384
+ weight=default_fused_per_channel_wt_fake_quant)
385
+ else:
386
+ qconfig = default_qat_qconfig_v2
387
+ else:
388
+ raise AssertionError("Version number: " + str(version) +
389
+ "in get_default_qat_qconfig is not supported. Version number must be 0 or 1")
390
+
391
+ return qconfig
392
+
393
+ """
394
+ Default symmetric QAT qconfig for qnnpack. And its per channel weight variant.
395
+ """
396
+ default_symmetric_qnnpack_qat_qconfig = QConfig(
397
+ activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
398
+ quant_min=-128,
399
+ quant_max=127,
400
+ dtype=torch.qint8,
401
+ reduce_range=False,
402
+ eps=2 ** -12),
403
+ weight=fused_wt_fake_quant_range_neg_127_to_127)
404
+
405
+ default_per_channel_symmetric_qnnpack_qat_qconfig = QConfig(
406
+ activation=FusedMovingAvgObsFakeQuantize.with_args(observer=MovingAverageMinMaxObserver,
407
+ quant_min=-128,
408
+ quant_max=127,
409
+ dtype=torch.qint8,
410
+ reduce_range=False,
411
+ eps=2 ** -12),
412
+ weight=fused_per_channel_wt_fake_quant_range_neg_127_to_127)
413
+
414
+ _default_fp32_placeholder_qconfig = QConfig(
415
+ activation=PlaceholderObserver.with_args(dtype=torch.float32),
416
+ weight=PlaceholderObserver.with_args(dtype=torch.float32)
417
+ )
418
+
419
+ _default_quint8_placeholder_qconfig = QConfig(
420
+ activation=PlaceholderObserver.with_args(dtype=torch.quint8),
421
+ # operators using this qconfig doesn't have weights
422
+ weight=None,
423
+ )
424
+
425
+ def get_default_qconfig_dict(backend='x86', version=0):
426
+ warnings.warn(
427
+ "torch.ao.quantization.get_default_qconfig_dict is deprecated and will be removed in "
428
+ "a future version. Please use torch.ao.quantization.get_default_qconfig_mapping instead.")
429
+ return torch.ao.quantization.get_default_qconfig_mapping(backend, version).to_dict()
430
+
431
+ def get_default_qat_qconfig_dict(backend='x86', version=1):
432
+ warnings.warn(
433
+ "torch.ao.quantization.get_default_qat_qconfig_dict is deprecated and will be removed in "
434
+ "a future version. Please use torch.ao.quantization.get_default_qat_qconfig_mapping instead.")
435
+ return torch.ao.quantization.get_default_qat_qconfig_mapping(backend, version).to_dict()
436
+
437
+ def _assert_valid_qconfig(qconfig: Optional[QConfig],
438
+ mod: torch.nn.Module) -> None:
439
+ """
440
+ Verifies that this `qconfig` is valid.
441
+ """
442
+ if qconfig is None:
443
+ return
444
+ is_conv_transpose_mod = (
445
+ isinstance(mod, (torch.nn.ConvTranspose1d, torch.nn.ConvTranspose2d, torch.nn.ConvTranspose3d)))
446
+ if is_conv_transpose_mod:
447
+ if qconfig.weight is None:
448
+ # for now, we assume that any qconfig for ConvTranspose without a weight is valid
449
+ return
450
+ example_observer = qconfig.weight()
451
+ is_per_channel = (
452
+ isinstance(example_observer, (torch.ao.quantization.PerChannelMinMaxObserver,
453
+ torch.ao.quantization.MovingAveragePerChannelMinMaxObserver))
454
+ )
455
+ assert not is_per_channel, \
456
+ 'Per channel weight observer is not supported yet for ConvTranspose{n}d.'
457
+
458
+ QConfigAny = Optional[QConfig]
459
+ QConfigAny.__module__ = "torch.ao.quantization.qconfig"
460
+
461
+ def _add_module_to_qconfig_obs_ctr(
462
+ qconfig: QConfigAny,
463
+ module: Optional[nn.Module]) -> Any:
464
+ r"""This is a helper function for use in quantization prepare that updates a qconfig so that
465
+ the constructors stored in the qconfig will create observers on the same device that
466
+ 'module' is on. This is intended to be used when the qconfigs are propagated to each
467
+ module in order to avoid potential device alignment issues.
468
+
469
+ Args:
470
+ qconfig: QConfig with obs constructors stored in activation and weight
471
+ module: module which the qconfig is related to
472
+
473
+ Return:
474
+ qconfig: configured so that obs constructors set to construct on the same device as module
475
+ """
476
+
477
+ if module is None or qconfig is None or qconfig._fields != ('activation', 'weight'):
478
+ return qconfig
479
+
480
+ def get_factory_kwargs_based_on_module_device():
481
+ assert isinstance(module, torch.nn.Module)
482
+ devices = {p.device for p in module.parameters()} | \
483
+ {p.device for p in module.buffers()}
484
+ device = next(iter(devices)) if len(devices) > 0 else None
485
+ return None if device is None else {'device': device}
486
+
487
+ def configure_constructor_to_put_obs_on_module_device(original_constructor):
488
+ try:
489
+ # check if constructor can accept factory_kwargs
490
+ check = original_constructor.with_args(factory_kwargs=None)
491
+ check()
492
+ return original_constructor.with_callable_args(factory_kwargs=get_factory_kwargs_based_on_module_device)
493
+ except AttributeError: # qconfig doesn't have activation or weight
494
+ return original_constructor
495
+ except TypeError: # the class doesn't accept factory_kwargs argument
496
+ return original_constructor
497
+
498
+ activation = configure_constructor_to_put_obs_on_module_device(qconfig.activation)
499
+ weight = configure_constructor_to_put_obs_on_module_device(qconfig.weight)
500
+
501
+ return QConfig(activation, weight)
502
+
503
+ _ObserverOrFakeQuantizeConstructor = Union[_PartialWrapper, Type[ObserverBase], Type[FakeQuantizeBase]]
504
+
505
+ def _obs_or_fq_ctr_equals(obs_or_fq1: _ObserverOrFakeQuantizeConstructor, obs_or_fq2: _ObserverOrFakeQuantizeConstructor):
506
+ if isinstance(obs_or_fq1, _PartialWrapper) and isinstance(obs_or_fq2, _PartialWrapper):
507
+ return _partial_wrapper_equals(obs_or_fq1, obs_or_fq2)
508
+ return obs_or_fq1 == obs_or_fq2
509
+
510
+ def _partial_wrapper_equals(obs_or_fq1: _PartialWrapper, obs_or_fq2: _PartialWrapper):
511
+ """
512
+ Return whether the two partial wrappers are equal,
513
+ """
514
+ # functools.partial has no __eq__ operator defined so '==' defaults to 'is'
515
+ obs_or_fq1_keywords = copy.copy(obs_or_fq1.p.keywords)
516
+ obs_or_fq2_keywords = copy.copy(obs_or_fq2.p.keywords)
517
+ keywords_equal = True
518
+ # compare observer constructor with _obs_or_fq_ctr_equals since direct compare would fail
519
+ if "observer" in obs_or_fq1_keywords and "observer" in obs_or_fq2_keywords:
520
+ keywords_equal = keywords_equal and _obs_or_fq_ctr_equals(obs_or_fq1_keywords["observer"], obs_or_fq2_keywords["observer"])
521
+ obs_or_fq1_keywords.pop("observer")
522
+ obs_or_fq2_keywords.pop("observer")
523
+ keywords_equal = keywords_equal and obs_or_fq1_keywords == obs_or_fq2_keywords
524
+ return obs_or_fq1.p.func == obs_or_fq2.p.func and obs_or_fq1.p.args == obs_or_fq2.p.args and keywords_equal
525
+
526
+ def qconfig_equals(q1: QConfigAny, q2: QConfigAny):
527
+ """
528
+ Returns `True` if `q1` equals `q2`, and `False` otherwise.
529
+ """
530
+ if q1 is None or q2 is None:
531
+ return q1 == q2
532
+ else:
533
+ assert q1 is not None and q2 is not None
534
+ try:
535
+ # Qconfig weight and activation can be either a partial wrapper,
536
+ # or an observer class. Special handling is required (above) for
537
+ # comparing partial wrappers.
538
+ activation_same = _obs_or_fq_ctr_equals(q1.activation, q2.activation)
539
+ weight_same = _obs_or_fq_ctr_equals(q1.weight, q2.weight)
540
+ return activation_same and weight_same
541
+ except AttributeError:
542
+ return q1 == q2
543
+
544
+ def _activation_is_memoryless(qconfig: QConfig):
545
+ """
546
+ Return whether the observer for activations defined in the given QConfig is memoryless.
547
+ This means a MovingAverage observer with averaging constant equal to 1.
548
+ """
549
+ def _is_memoryless(observer):
550
+ return hasattr(observer, "averaging_constant") and observer.averaging_constant == 1
551
+ act = qconfig.activation()
552
+ if isinstance(act, FakeQuantizeBase) and hasattr(act, "activation_post_process"):
553
+ return _is_memoryless(act.activation_post_process)
554
+ else:
555
+ return _is_memoryless(act)
556
+
557
+ def _is_reuse_input_qconfig(qconfig: Optional[QConfig]):
558
+ return qconfig is not None and \
559
+ isinstance(qconfig.activation(), ReuseInputObserver) and \
560
+ isinstance(qconfig.weight(), NoopObserver)
videollama2/lib/python3.10/site-packages/torch/ao/quantization/qconfig_mapping.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from collections import OrderedDict
3
+ from typing import Any, Callable, Dict, Tuple, Union, List
4
+
5
+ import torch
6
+
7
+ from .fake_quantize import (
8
+ default_weight_fake_quant,
9
+ FixedQParamsFakeQuantize,
10
+ )
11
+ from .observer import (
12
+ _PartialWrapper,
13
+ default_fixed_qparams_range_0to1_observer,
14
+ default_fixed_qparams_range_neg1to1_observer,
15
+ default_placeholder_observer,
16
+ default_weight_observer,
17
+ )
18
+ from .qconfig import (
19
+ default_reuse_input_qconfig,
20
+ default_symmetric_qnnpack_qconfig,
21
+ default_symmetric_qnnpack_qat_qconfig,
22
+ get_default_qconfig,
23
+ get_default_qat_qconfig,
24
+ QConfig,
25
+ QConfigAny,
26
+ default_quint8_weight_qconfig
27
+ )
28
+
29
+
30
+ __all__ = [
31
+ "get_default_qconfig_mapping",
32
+ "get_default_qat_qconfig_mapping",
33
+ "QConfigMapping",
34
+ ]
35
+
36
+
37
+ # TODO: replace all usages with these constants
38
+ _GLOBAL_DICT_KEY = ""
39
+ _OBJECT_TYPE_DICT_KEY = "object_type"
40
+ _MODULE_NAME_REGEX_DICT_KEY = "module_name_regex"
41
+ _MODULE_NAME_DICT_KEY = "module_name"
42
+ _MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY = "module_name_object_type_order"
43
+
44
+ # TODO: derive this map from the BackendConfig
45
+ _FIXED_QPARAMS_OP_TO_OBSERVER: Dict[Union[Callable, str], _PartialWrapper] = {
46
+ torch.nn.Hardsigmoid: default_fixed_qparams_range_0to1_observer,
47
+ torch.nn.functional.hardsigmoid: default_fixed_qparams_range_0to1_observer,
48
+ "hardsigmoid": default_fixed_qparams_range_0to1_observer,
49
+ "hardsigmoid_": default_fixed_qparams_range_0to1_observer,
50
+ torch.nn.Sigmoid: default_fixed_qparams_range_0to1_observer,
51
+ torch.sigmoid: default_fixed_qparams_range_0to1_observer,
52
+ "sigmoid": default_fixed_qparams_range_0to1_observer,
53
+ "sigmoid_": default_fixed_qparams_range_0to1_observer,
54
+ torch.nn.Softmax: default_fixed_qparams_range_0to1_observer,
55
+ torch.nn.Tanh: default_fixed_qparams_range_neg1to1_observer,
56
+ torch.tanh: default_fixed_qparams_range_neg1to1_observer,
57
+ "tanh": default_fixed_qparams_range_neg1to1_observer,
58
+ "tanh_": default_fixed_qparams_range_neg1to1_observer,
59
+ }
60
+
61
+
62
+ def _get_default_qconfig_mapping(is_qat: bool, backend: str, version: int) -> QConfigMapping:
63
+ """
64
+ Return the default QConfigMapping for the given quantization type and backend.
65
+ """
66
+ if is_qat:
67
+ qconfig = get_default_qat_qconfig(backend, version)
68
+ else:
69
+ qconfig = get_default_qconfig(backend, version)
70
+ default_weight = default_weight_fake_quant if is_qat else default_weight_observer
71
+
72
+ # default_per_channel_weight_observer is not currently compatible with fbgemm backend
73
+ # so we have to modify the weight observer to default_weight_observer or another
74
+ # per tensor supported observer.
75
+ # see https://github.com/pytorch/pytorch/issues/47535
76
+ if backend in ("fbgemm", "x86"):
77
+ qconfig_transpose = QConfig(activation=qconfig.activation, weight=default_weight)
78
+ else:
79
+ qconfig_transpose = qconfig
80
+
81
+ # currently layernorm only supports float weights
82
+ # we have to add this because otherwise there will be a extra quantize-dequantize pair
83
+ qconfig_layernorm = QConfig(activation=qconfig.activation, weight=default_placeholder_observer)
84
+
85
+ qconfig_mapping = QConfigMapping() \
86
+ .set_global(qconfig) \
87
+ .set_object_type("reshape", default_reuse_input_qconfig) \
88
+ .set_object_type(torch.nn.ConvTranspose1d, qconfig_transpose) \
89
+ .set_object_type(torch.nn.ConvTranspose2d, qconfig_transpose) \
90
+ .set_object_type(torch.nn.ConvTranspose3d, qconfig_transpose) \
91
+ .set_object_type(torch.nn.functional.conv_transpose1d, qconfig_transpose) \
92
+ .set_object_type(torch.nn.functional.conv_transpose2d, qconfig_transpose) \
93
+ .set_object_type(torch.nn.functional.conv_transpose3d, qconfig_transpose) \
94
+ .set_object_type(torch.nn.functional.layer_norm, qconfig_layernorm) \
95
+ .set_object_type(torch.nn.LayerNorm, qconfig_layernorm) \
96
+ .set_object_type(torch.nn.PReLU, default_quint8_weight_qconfig) \
97
+
98
+ # Use special observers for ops with fixed qparams
99
+ fixed_qparams_observer_to_qconfig: Dict[Any, QConfigAny] = {}
100
+ for fixed_qparams_op, observer in _FIXED_QPARAMS_OP_TO_OBSERVER.items():
101
+ if observer in fixed_qparams_observer_to_qconfig:
102
+ fixed_qparams_qconfig = fixed_qparams_observer_to_qconfig[observer]
103
+ else:
104
+ if is_qat:
105
+ activation = FixedQParamsFakeQuantize.with_args(observer=observer)
106
+ else:
107
+ activation = observer
108
+ fixed_qparams_qconfig = QConfig(activation=activation, weight=default_weight)
109
+ fixed_qparams_observer_to_qconfig[observer] = fixed_qparams_qconfig
110
+ qconfig_mapping.set_object_type(fixed_qparams_op, fixed_qparams_qconfig)
111
+
112
+ # TODO Currently it's required that separate ops in a fused op/module have the same qconfig.
113
+ # Need to be able to support fusion of ops with different qconfigs
114
+
115
+ return qconfig_mapping
116
+
117
+ def get_default_qconfig_mapping(backend="x86", version=0) -> QConfigMapping:
118
+ """
119
+ Return the default QConfigMapping for post training quantization.
120
+
121
+ Args:
122
+ * ``backend`` (str) : the quantization backend for the default qconfig mapping, should be
123
+ one of ["x86" (default), "fbgemm", "qnnpack", "onednn"]
124
+ * ``version`` (int) : the version for the default qconfig mapping
125
+ """
126
+ # TODO: add assert for backend choices
127
+ return _get_default_qconfig_mapping(False, backend, version)
128
+
129
+ def get_default_qat_qconfig_mapping(backend="x86", version=1) -> QConfigMapping:
130
+ """
131
+ Return the default QConfigMapping for quantization aware training.
132
+
133
+ Args:
134
+ * ``backend`` (str) : the quantization backend for the default qconfig mapping, should be
135
+ one of ["x86" (default), "fbgemm", "qnnpack", "onednn"]
136
+ * ``version`` (int) : the version for the default qconfig mapping
137
+ """
138
+ return _get_default_qconfig_mapping(True, backend, version)
139
+
140
+ def _get_symmetric_qnnpack_qconfig_mapping() -> QConfigMapping:
141
+ """
142
+ Return a QConfigMapping that uses `torch.ao.quantization.default_symmetric_qnnpack_qconfig`
143
+ as the default QConfig.
144
+ """
145
+ default_qconfig = default_symmetric_qnnpack_qconfig
146
+ return _get_default_qconfig_mapping_with_default_qconfig(False, "qnnpack", default_qconfig)
147
+
148
+ def _get_symmetric_qnnpack_qat_qconfig_mapping() -> QConfigMapping:
149
+ """
150
+ Return a QConfigMapping that uses `torch.ao.quantization.default_symmetric_qnnpack_qat_qconfig`
151
+ as the default QConfig.
152
+ """
153
+ default_qconfig = default_symmetric_qnnpack_qat_qconfig
154
+ return _get_default_qconfig_mapping_with_default_qconfig(True, "qnnpack", default_qconfig)
155
+
156
+ def _get_default_qconfig_mapping_with_default_qconfig(
157
+ is_qat: bool,
158
+ backend: str,
159
+ default_qconfig: QConfig,
160
+ ) -> QConfigMapping:
161
+ """
162
+ Return a QConfigMapping that uses the provided qconfig as the default QConfig.
163
+ """
164
+ if is_qat:
165
+ qconfig_mapping = get_default_qat_qconfig_mapping(backend)
166
+ else:
167
+ qconfig_mapping = get_default_qconfig_mapping(backend)
168
+ qconfig_mapping.set_global(default_qconfig)
169
+ for pattern in qconfig_mapping.object_type_qconfigs.keys():
170
+ if pattern not in _FIXED_QPARAMS_OP_TO_OBSERVER:
171
+ qconfig_mapping.set_object_type(pattern, default_qconfig)
172
+ return qconfig_mapping
173
+
174
+ _QCONFIG_STYLE_ORDER: List[str] = [
175
+ "global_qconfig",
176
+ "object_type_qconfigs",
177
+ "module_name_regex_qconfigs",
178
+ "module_name_qconfigs",
179
+ "module_name_object_type_order_qconfigs",
180
+ ]
181
+
182
+ class QConfigMapping:
183
+ """
184
+ Mapping from model ops to :class:`torch.ao.quantization.QConfig` s.
185
+
186
+ The user can specify QConfigs using the following methods (in increasing match priority):
187
+
188
+ ``set_global`` : sets the global (default) QConfig
189
+
190
+ ``set_object_type`` : sets the QConfig for a given module type, function, or method name
191
+
192
+ ``set_module_name_regex`` : sets the QConfig for modules matching the given regex string
193
+
194
+ ``set_module_name`` : sets the QConfig for modules matching the given module name
195
+
196
+ ``set_module_name_object_type_order`` : sets the QConfig for modules matching a combination
197
+ of the given module name, object type, and the index at which the module appears
198
+
199
+ Example usage::
200
+
201
+ qconfig_mapping = QConfigMapping()
202
+ .set_global(global_qconfig)
203
+ .set_object_type(torch.nn.Linear, qconfig1)
204
+ .set_object_type(torch.nn.ReLU, qconfig1)
205
+ .set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1)
206
+ .set_module_name_regex("foo.*", qconfig2)
207
+ .set_module_name("module1", qconfig1)
208
+ .set_module_name("module2", qconfig2)
209
+ .set_module_name_object_type_order("foo.bar", torch.nn.functional.linear, 0, qconfig3)
210
+
211
+ """
212
+
213
+ def __init__(self):
214
+ # In increasing match priority:
215
+ self.global_qconfig: QConfigAny = None
216
+ self.object_type_qconfigs: OrderedDict[Union[Callable, str], QConfigAny] = OrderedDict()
217
+ self.module_name_regex_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict()
218
+ self.module_name_qconfigs: OrderedDict[str, QConfigAny] = OrderedDict()
219
+ self.module_name_object_type_order_qconfigs: OrderedDict[Tuple[str, Callable, int], QConfigAny] =\
220
+ OrderedDict()
221
+
222
+ def set_global(self, global_qconfig: QConfigAny) -> QConfigMapping:
223
+ """
224
+ Set the global (default) QConfig.
225
+ """
226
+ self.global_qconfig = global_qconfig
227
+ return self
228
+
229
+ def set_object_type(self, object_type: Union[Callable, str], qconfig: QConfigAny) -> QConfigMapping:
230
+ """
231
+ Set the QConfig for a given module type, function, or method name.
232
+ If the QConfig for an existing object type was already set, the new QConfig will override the old one.
233
+ """
234
+ self.object_type_qconfigs[object_type] = qconfig
235
+ return self
236
+
237
+ def set_module_name_regex(self, module_name_regex: str, qconfig: QConfigAny) -> QConfigMapping:
238
+ """
239
+ Set the QConfig for modules matching the given regex string.
240
+
241
+ Regexes will be matched in the order in which they are registered through this method.
242
+ Thus, the caller should register more specific patterns first, e.g.::
243
+
244
+ qconfig_mapping = QConfigMapping()
245
+ .set_module_name_regex("foo.*bar.*conv[0-9]+", qconfig1)
246
+ .set_module_name_regex("foo.*bar.*", qconfig2)
247
+ .set_module_name_regex("foo.*", qconfig3)
248
+
249
+ In this example, "foo.bar.conv0" would match qconfig1, "foo.bar.linear" would match qconfig2,
250
+ and "foo.baz.relu" would match qconfig3.
251
+
252
+ If the QConfig for an existing module name regex was already set, the new QConfig will override the
253
+ old one while preserving the order in which the regexes were originally registered.
254
+ """
255
+ self.module_name_regex_qconfigs[module_name_regex] = qconfig
256
+ return self
257
+
258
+ def set_module_name(self, module_name: str, qconfig: QConfigAny) -> QConfigMapping:
259
+ """
260
+ Set the QConfig for modules matching the given module name.
261
+ If the QConfig for an existing module name was already set, the new QConfig will override the old one.
262
+ """
263
+ self.module_name_qconfigs[module_name] = qconfig
264
+ return self
265
+
266
+ def set_module_name_object_type_order(
267
+ self,
268
+ module_name: str,
269
+ object_type: Callable,
270
+ index: int,
271
+ qconfig: QConfigAny) -> QConfigMapping:
272
+ """
273
+ Set the QConfig for modules matching a combination of the given module name, object type,
274
+ and the index at which the module appears.
275
+
276
+ If the QConfig for an existing (module name, object type, index) was already set, the new QConfig
277
+ will override the old one.
278
+ """
279
+ self.module_name_object_type_order_qconfigs[(module_name, object_type, index)] = qconfig
280
+ return self
281
+
282
+ def __repr__(self) -> str:
283
+ output = self.__class__.__name__ + " ("
284
+ for style_name in _QCONFIG_STYLE_ORDER:
285
+ output += f"\n {style_name}"
286
+ qconfigs = getattr(self, style_name)
287
+ if isinstance(qconfigs, OrderedDict) and len(qconfigs) > 0:
288
+ for key, qconfig in qconfigs.items():
289
+ output += f"\n {key}: {qconfig}"
290
+ else:
291
+ output += f"\n {qconfigs}"
292
+ return output + "\n)"
293
+
294
+ # TODO: remove this
295
+ def to_dict(self) -> Dict[str, Any]:
296
+ """
297
+ Convert this ``QConfigMapping`` to a dictionary with the following keys:
298
+
299
+ "" (for global QConfig)
300
+
301
+ "object_type"
302
+
303
+ "module_name_regex"
304
+
305
+ "module_name"
306
+
307
+ "module_name_object_type_order"
308
+
309
+ The values of this dictionary are lists of tuples.
310
+ """
311
+ return {
312
+ _GLOBAL_DICT_KEY: self.global_qconfig,
313
+ _OBJECT_TYPE_DICT_KEY: list(self.object_type_qconfigs.items()),
314
+ _MODULE_NAME_REGEX_DICT_KEY: list(self.module_name_regex_qconfigs.items()),
315
+ _MODULE_NAME_DICT_KEY: list(self.module_name_qconfigs.items()),
316
+ _MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY: [
317
+ (*k, v) for k, v in self.module_name_object_type_order_qconfigs.items()
318
+ ],
319
+ }
320
+
321
+ # TODO: remove this
322
+ @classmethod
323
+ def from_dict(cls, qconfig_dict: Dict[str, Any]) -> QConfigMapping:
324
+ """
325
+ Create a ``QConfigMapping`` from a dictionary with the following keys (all optional):
326
+
327
+ "" (for global QConfig)
328
+
329
+ "object_type"
330
+
331
+ "module_name_regex"
332
+
333
+ "module_name"
334
+
335
+ "module_name_object_type_order"
336
+
337
+ The values of this dictionary are expected to be lists of tuples.
338
+ """
339
+ conf = cls()
340
+ if _GLOBAL_DICT_KEY in qconfig_dict:
341
+ conf.set_global(qconfig_dict[_GLOBAL_DICT_KEY])
342
+ for object_type, qconfig in qconfig_dict.get(_OBJECT_TYPE_DICT_KEY, []):
343
+ conf.set_object_type(object_type, qconfig)
344
+ for module_name_regex, qconfig in qconfig_dict.get(_MODULE_NAME_REGEX_DICT_KEY, []):
345
+ conf.set_module_name_regex(module_name_regex, qconfig)
346
+ for module_name, qconfig in qconfig_dict.get(_MODULE_NAME_DICT_KEY, []):
347
+ conf.set_module_name(module_name, qconfig)
348
+ for module_name, object_type, index, qconfig in qconfig_dict.get(_MODULE_NAME_OBJECT_TYPE_ORDER_DICT_KEY, []):
349
+ conf.set_module_name_object_type_order(module_name, object_type, index, qconfig)
350
+ return conf
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quant_type.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+
3
+ __all__ = [
4
+ "QuantType",
5
+ ]
6
+
7
+ # Quantization type (dynamic quantization, static quantization).
8
+ # Should match the c++ enum in quantization_type.h
9
+ class QuantType(enum.IntEnum):
10
+ DYNAMIC = 0
11
+ STATIC = 1
12
+ QAT = 2
13
+ WEIGHT_ONLY = 3
14
+
15
+ _quant_type_to_str = {
16
+ QuantType.STATIC: "static",
17
+ QuantType.DYNAMIC: "dynamic",
18
+ QuantType.QAT: "qat",
19
+ QuantType.WEIGHT_ONLY: "weight_only",
20
+ }
21
+
22
+ # TODO: make this private
23
+ def _get_quant_type_to_str(quant_type: QuantType) -> str:
24
+ return _quant_type_to_str[quant_type]
25
+
26
+ def _quant_type_from_str(name: str) -> QuantType:
27
+ for quant_type, s in _quant_type_to_str.items():
28
+ if name == s:
29
+ return quant_type
30
+ raise ValueError(f"Unknown QuantType name '{name}'")
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantization_mappings.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+ import torch.nn.functional as F
7
+ import torch.ao.nn.intrinsic as nni
8
+ import torch.ao.nn.intrinsic.quantized as nniq
9
+ import torch.ao.nn.intrinsic.quantized.dynamic as nniqd
10
+ import torch.ao.nn.intrinsic.qat as nniqat
11
+ import torch.ao.nn.quantized as nnq
12
+ import torch.ao.nn.quantized.reference as nnqr
13
+ import torch.ao.nn.quantized.dynamic as nnqd
14
+ import torch.ao.nn.qat as nnqat
15
+ import torch.ao.nn.qat.dynamic as nnqatd
16
+
17
+ from typing import Optional, Union, Dict, Set, Callable, Any
18
+
19
+ # Because `torch.ao.nn` uses lazy imports, we need to make
20
+ # sure we import the contents explicitly here.
21
+ import torch.ao.nn.sparse
22
+ import torch.ao.nn as ao_nn
23
+ from torch.ao.quantization.stubs import QuantStub, DeQuantStub
24
+ from torch.ao.quantization.fake_quantize import (
25
+ default_fixed_qparams_range_0to1_fake_quant,
26
+ default_fixed_qparams_range_neg1to1_fake_quant,
27
+ )
28
+ from torch.ao.quantization.utils import get_combined_dict
29
+ from torch.nn.utils.parametrize import type_before_parametrizations
30
+
31
+ __all__ = [
32
+ "DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS",
33
+ "DEFAULT_STATIC_QUANT_MODULE_MAPPINGS",
34
+ "DEFAULT_QAT_MODULE_MAPPINGS",
35
+ "DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS",
36
+ "DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS",
37
+ "DEFAULT_MODULE_TO_ACT_POST_PROCESS",
38
+ "DEFAULT_STATIC_SPARSE_QUANT_MODULE_MAPPINGS",
39
+ "DEFAULT_DYNAMIC_SPARSE_QUANT_MODULE_MAPPINGS",
40
+ "no_observer_set",
41
+ "get_default_static_quant_module_mappings",
42
+ "get_default_static_quant_reference_module_mappings",
43
+ "get_embedding_static_quant_module_mappings",
44
+ "get_default_static_sparse_quant_module_mappings",
45
+ "get_static_quant_module_class",
46
+ "get_dynamic_quant_module_class",
47
+ "get_default_qat_module_mappings",
48
+ "get_embedding_qat_module_mappings",
49
+ "get_default_dynamic_quant_module_mappings",
50
+ "get_default_dynamic_sparse_quant_module_mappings",
51
+ "get_default_qconfig_propagation_list",
52
+ "get_default_compare_output_module_list",
53
+ "get_default_float_to_quantized_operator_mappings",
54
+ "get_quantized_operator",
55
+ ]
56
+
57
+ # Default map for swapping float module to reference quantized modules
58
+ DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS : Dict[Callable, Any] = {
59
+ QuantStub: nnq.Quantize,
60
+ DeQuantStub: nnq.DeQuantize,
61
+ nn.Linear: nnqr.Linear,
62
+ nn.Conv1d: nnqr.Conv1d,
63
+ nn.Conv2d: nnqr.Conv2d,
64
+ nn.Conv3d: nnqr.Conv3d,
65
+ nn.ConvTranspose1d: nnqr.ConvTranspose1d,
66
+ nn.ConvTranspose2d: nnqr.ConvTranspose2d,
67
+ nn.ConvTranspose3d: nnqr.ConvTranspose3d,
68
+ nn.Embedding: nnqr.Embedding,
69
+ nn.EmbeddingBag: nnqr.EmbeddingBag,
70
+ nn.GRUCell: nnqr.GRUCell,
71
+ nn.LSTMCell: nnqr.LSTMCell,
72
+ nn.RNNCell: nnqr.RNNCell,
73
+ nn.LSTM: nnqr.LSTM,
74
+ }
75
+
76
+ # Default map for swapping float module to quantized ones
77
+ DEFAULT_STATIC_QUANT_MODULE_MAPPINGS : Dict[Callable, Any] = {
78
+ QuantStub: nnq.Quantize,
79
+ DeQuantStub: nnq.DeQuantize,
80
+ nn.BatchNorm2d: nnq.BatchNorm2d,
81
+ nn.BatchNorm3d: nnq.BatchNorm3d,
82
+ nn.Dropout: nnq.Dropout,
83
+ nn.Conv1d: nnq.Conv1d,
84
+ nn.Conv2d: nnq.Conv2d,
85
+ nn.Conv3d: nnq.Conv3d,
86
+ nn.ConvTranspose1d: nnq.ConvTranspose1d,
87
+ nn.ConvTranspose2d: nnq.ConvTranspose2d,
88
+ nn.ConvTranspose3d: nnq.ConvTranspose3d,
89
+ nn.ELU: nnq.ELU,
90
+ nn.Embedding: nnq.Embedding,
91
+ nn.EmbeddingBag: nnq.EmbeddingBag,
92
+ nn.GroupNorm: nnq.GroupNorm,
93
+ nn.Hardswish: nnq.Hardswish,
94
+ nn.InstanceNorm1d: nnq.InstanceNorm1d,
95
+ nn.InstanceNorm2d: nnq.InstanceNorm2d,
96
+ nn.InstanceNorm3d: nnq.InstanceNorm3d,
97
+ nn.LayerNorm: nnq.LayerNorm,
98
+ nn.LeakyReLU: nnq.LeakyReLU,
99
+ nn.modules.linear.NonDynamicallyQuantizableLinear: nnq.Linear,
100
+ nn.Linear: nnq.Linear,
101
+ nn.ReLU6: nnq.ReLU6,
102
+ nn.Dropout: nnq.Dropout,
103
+ nn.PReLU: nnq.PReLU,
104
+ # Wrapper Modules:
105
+ nnq.FloatFunctional: nnq.QFunctional,
106
+ # Intrinsic modules:
107
+ nni.BNReLU2d: nniq.BNReLU2d,
108
+ nni.BNReLU3d: nniq.BNReLU3d,
109
+ nni.ConvReLU1d: nniq.ConvReLU1d,
110
+ nni.ConvReLU2d: nniq.ConvReLU2d,
111
+ nni.ConvReLU3d: nniq.ConvReLU3d,
112
+ nni.ConvAdd2d: nniq.ConvAdd2d,
113
+ nni.ConvAddReLU2d: nniq.ConvAddReLU2d,
114
+ nni.LinearReLU: nniq.LinearReLU,
115
+ nni.LinearLeakyReLU: nniq.LinearLeakyReLU,
116
+ nni.LinearTanh: nniq.LinearTanh,
117
+ nniqat.ConvBn1d: nnq.Conv1d,
118
+ nniqat.ConvBn2d: nnq.Conv2d,
119
+ nniqat.ConvBn3d: nnq.Conv3d,
120
+ nniqat.ConvBnReLU1d: nniq.ConvReLU1d,
121
+ nniqat.ConvBnReLU2d: nniq.ConvReLU2d,
122
+ nniqat.ConvBnReLU3d: nniq.ConvReLU3d,
123
+ nniqat.ConvReLU2d: nniq.ConvReLU2d,
124
+ nniqat.ConvReLU3d: nniq.ConvReLU3d,
125
+ nniqat.LinearReLU: nniq.LinearReLU,
126
+ nniqat.LinearBn1d: nnq.Linear,
127
+ # QAT modules:
128
+ nnqat.Linear: nnq.Linear,
129
+ nnqat.Conv2d: nnq.Conv2d,
130
+ nnqat.Conv3d: nnq.Conv3d,
131
+ }
132
+
133
+ # Default map for swapping float module to qat modules
134
+ DEFAULT_QAT_MODULE_MAPPINGS : Dict[Callable, Any] = {
135
+ nn.Conv2d: nnqat.Conv2d,
136
+ nn.Conv3d: nnqat.Conv3d,
137
+ nn.Linear: nnqat.Linear,
138
+ nn.modules.linear.NonDynamicallyQuantizableLinear: nnqat.Linear,
139
+ # Intrinsic modules:
140
+ nni.ConvBn1d: nniqat.ConvBn1d,
141
+ nni.ConvBn2d: nniqat.ConvBn2d,
142
+ nni.ConvBn3d: nniqat.ConvBn3d,
143
+ nni.ConvBnReLU1d: nniqat.ConvBnReLU1d,
144
+ nni.ConvBnReLU2d: nniqat.ConvBnReLU2d,
145
+ nni.ConvBnReLU3d: nniqat.ConvBnReLU3d,
146
+ nni.ConvReLU2d: nniqat.ConvReLU2d,
147
+ nni.ConvReLU3d: nniqat.ConvReLU3d,
148
+ nni.LinearReLU: nniqat.LinearReLU,
149
+ nni.LinearBn1d: nniqat.LinearBn1d,
150
+ }
151
+
152
+ # Default map for swapping dynamic modules
153
+ DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS : Dict[Callable, Any] = {
154
+ nn.GRUCell: nnqd.GRUCell,
155
+ nn.Linear: nnqd.Linear,
156
+ nnqatd.Linear: nnqd.Linear,
157
+ nn.modules.linear.NonDynamicallyQuantizableLinear: nnqd.Linear,
158
+ nn.LSTM: nnqd.LSTM,
159
+ nn.GRU: nnqd.GRU,
160
+ nn.LSTMCell: nnqd.LSTMCell,
161
+ nn.RNNCell: nnqd.RNNCell,
162
+ nni.LinearReLU: nniqd.LinearReLU,
163
+ nn.EmbeddingBag: nnq.EmbeddingBag,
164
+ nn.Embedding: nnq.Embedding,
165
+ # Don't want to enable these by default because the numerical
166
+ # accuracy is poor compared to other dynamic ops
167
+ # nn.Conv1d: nnqd.Conv1d,
168
+ # nn.Conv2d: nnqd.Conv2d,
169
+ # nn.Conv3d: nnqd.Conv3d,
170
+ # nn.ConvTranspose1d: nnqd.ConvTranspose1d,
171
+ # nn.ConvTranspose2d: nnqd.ConvTranspose2d,
172
+ # nn.ConvTranspose3d: nnqd.ConvTranspose3d,
173
+ }
174
+
175
+ # Allowlist for propagating the qconfig
176
+ _INCLUDE_QCONFIG_PROPAGATE_LIST : Set[Callable] = {
177
+ nn.Sequential,
178
+ }
179
+
180
+ # Default mapping from floating point function or torch ops to quantized ops
181
+ # TODO: merge with default static mapping
182
+ DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS : Dict[Union[Callable, str], Callable] = {
183
+ F.elu: torch.ops.quantized.elu,
184
+ F.hardswish: torch.ops.quantized.hardswish,
185
+ F.instance_norm: torch.ops.quantized.instance_norm,
186
+ F.layer_norm: torch.ops.quantized.layer_norm,
187
+ F.leaky_relu: torch.ops.quantized.leaky_relu,
188
+ F.dropout: torch.ops.quantized.dropout,
189
+ }
190
+
191
+ # mapping from module to output activation post process class
192
+ DEFAULT_MODULE_TO_ACT_POST_PROCESS : Dict[Callable, Callable] = {
193
+ nn.Hardsigmoid: default_fixed_qparams_range_0to1_fake_quant,
194
+ nn.Sigmoid: default_fixed_qparams_range_0to1_fake_quant,
195
+ nn.Softmax: default_fixed_qparams_range_0to1_fake_quant,
196
+ nn.Tanh: default_fixed_qparams_range_neg1to1_fake_quant,
197
+ }
198
+
199
+ # Default map for swapping float module to static sparse quantized ones
200
+ DEFAULT_STATIC_SPARSE_QUANT_MODULE_MAPPINGS : Dict[Callable, Any] = {
201
+ nn.Linear: ao_nn.sparse.quantized.Linear
202
+ }
203
+
204
+ # Default map for swapping float module to dynamic sparse quantized ones
205
+ DEFAULT_DYNAMIC_SPARSE_QUANT_MODULE_MAPPINGS : Dict[Callable, Any] = {
206
+ nn.Linear: ao_nn.sparse.quantized.dynamic.Linear
207
+ }
208
+
209
+ def no_observer_set() -> Set[Any]:
210
+ r"""These modules cannot have observers inserted by default."""
211
+ no_observers = {
212
+ nn.quantizable.LSTM,
213
+ nn.quantizable.MultiheadAttention
214
+ }
215
+ return no_observers
216
+
217
+ def get_default_static_quant_module_mappings() -> Dict[Callable, Any]:
218
+ ''' Get module mapping for post training static quantization
219
+ '''
220
+ return copy.deepcopy(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS)
221
+
222
+ def get_default_static_quant_reference_module_mappings() -> Dict[Callable, Any]:
223
+ ''' Get reference module mapping for post training static quantization
224
+ '''
225
+ return copy.deepcopy(DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS)
226
+
227
+ def get_embedding_static_quant_module_mappings() -> Dict[Callable, Any]:
228
+ ''' Get module mapping, including mapping for embedding QAT
229
+ '''
230
+ mapping = copy.deepcopy(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS)
231
+ mapping[nnqat.EmbeddingBag] = nnq.EmbeddingBag
232
+ mapping[nnqat.Embedding] = nnq.Embedding
233
+ return mapping
234
+
235
+ def get_default_static_sparse_quant_module_mappings() -> Dict[Callable, Any]:
236
+ ''' Get module mapping for post training static sparse quantization
237
+ '''
238
+ return copy.deepcopy(DEFAULT_STATIC_SPARSE_QUANT_MODULE_MAPPINGS)
239
+
240
+ def get_static_quant_module_class(
241
+ float_module_class: Callable,
242
+ additional_static_quant_mapping: Optional[Dict[Callable, Any]] = None,
243
+ is_reference: bool = False) -> Any:
244
+ r"""n Get the statically quantized module class corresponding to
245
+ the floating point module class
246
+ """
247
+ if additional_static_quant_mapping is None:
248
+ additional_static_quant_mapping = {}
249
+ all_mappings = get_combined_dict(
250
+ DEFAULT_REFERENCE_STATIC_QUANT_MODULE_MAPPINGS if is_reference
251
+ else DEFAULT_STATIC_QUANT_MODULE_MAPPINGS, additional_static_quant_mapping)
252
+ static_quant_module_class = all_mappings.get(float_module_class, None)
253
+ assert static_quant_module_class is not None, \
254
+ f"Floating point module class {str(float_module_class)}" + \
255
+ " does not have a corresponding quantized module class"
256
+ return copy.deepcopy(static_quant_module_class)
257
+
258
+ def get_dynamic_quant_module_class(
259
+ float_module_class: Callable,
260
+ additional_dynamic_quant_mapping: Optional[Dict[Callable, Any]] = None) -> Any:
261
+ r"""n Get the dynamically quantized module class corresponding to
262
+ the floating point module class
263
+ """
264
+ if additional_dynamic_quant_mapping is None:
265
+ additional_dynamic_quant_mapping = {}
266
+ all_mappings = get_combined_dict(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS, additional_dynamic_quant_mapping)
267
+ dynamic_quant_module_class = all_mappings.get(float_module_class, None)
268
+ assert dynamic_quant_module_class is not None, \
269
+ f"Floating point module class {str(float_module_class)}" + \
270
+ " does not have a corresponding quantized module class"
271
+ return copy.deepcopy(dynamic_quant_module_class)
272
+
273
+ def get_default_qat_module_mappings() -> Dict[Callable, Any]:
274
+ ''' Get default module mapping for quantization aware training
275
+ '''
276
+ return copy.deepcopy(DEFAULT_QAT_MODULE_MAPPINGS)
277
+
278
+ def get_embedding_qat_module_mappings() -> Dict[Callable, Any]:
279
+ ''' Get module mapping for quantization aware training
280
+ This is includes default values in addition to
281
+ enabling qat for embeddings.
282
+ '''
283
+ mapping = copy.deepcopy(DEFAULT_QAT_MODULE_MAPPINGS)
284
+ mapping[nn.EmbeddingBag] = nnqat.EmbeddingBag
285
+ mapping[nn.Embedding] = nnqat.Embedding
286
+ return mapping
287
+
288
+ def get_default_dynamic_quant_module_mappings() -> Dict[Callable, Any]:
289
+ ''' Get module mapping for post training dynamic quantization
290
+ '''
291
+ return DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS
292
+
293
+ def get_default_dynamic_sparse_quant_module_mappings() -> Dict[Callable, Any]:
294
+ ''' Get module mapping for post training dynamic sparse quantization
295
+ '''
296
+ return DEFAULT_DYNAMIC_SPARSE_QUANT_MODULE_MAPPINGS
297
+
298
+ def get_default_qconfig_propagation_list() -> Set[Callable]:
299
+ ''' Get the default list of module types that we'll attach qconfig
300
+ attribute to in prepare
301
+ '''
302
+ QCONFIG_PROPAGATE_MODULE_CLASS_LIST = (
303
+ set(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS.keys()) |
304
+ set(DEFAULT_QAT_MODULE_MAPPINGS.keys()) |
305
+ set(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS.keys()) |
306
+ _INCLUDE_QCONFIG_PROPAGATE_LIST
307
+ )
308
+ return copy.deepcopy(QCONFIG_PROPAGATE_MODULE_CLASS_LIST)
309
+
310
+ def get_default_compare_output_module_list() -> Set[Callable]:
311
+ ''' Get list of module class types that we will record output
312
+ in numeric suite
313
+ '''
314
+ NUMERIC_SUITE_COMPARE_MODEL_OUTPUT_MODULE_LIST = (
315
+ set(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS.values())
316
+ | set(DEFAULT_QAT_MODULE_MAPPINGS.values())
317
+ | set(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS.values())
318
+ | set(DEFAULT_STATIC_QUANT_MODULE_MAPPINGS.keys())
319
+ | set(DEFAULT_QAT_MODULE_MAPPINGS.keys())
320
+ | set(DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS.keys())
321
+ | _INCLUDE_QCONFIG_PROPAGATE_LIST
322
+ )
323
+ return copy.deepcopy(NUMERIC_SUITE_COMPARE_MODEL_OUTPUT_MODULE_LIST)
324
+
325
+ def get_default_float_to_quantized_operator_mappings(
326
+ ) -> Dict[Union[Callable, str], Callable]:
327
+ return copy.deepcopy(DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS)
328
+
329
+ # TODO: merge with get_static_quant_module_class
330
+ def get_quantized_operator(float_op: Union[Callable, str]) -> Callable:
331
+ ''' Get the quantized operator corresponding to the float operator
332
+ '''
333
+ quantized_op = DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS.get(float_op, None)
334
+ assert quantized_op is not None, \
335
+ f'Operator {str(float_op)} does not have corresponding quantized op'
336
+ return quantized_op
337
+
338
+ def _get_special_act_post_process(module: torch.nn.Module) -> Optional[Callable]:
339
+ r""" Get the special activation post process for `module`, this has
340
+ higher priority than the activation post process in `qconfig`
341
+ e.g.
342
+ input: torch.nn.Sigmoid
343
+ output: default_affine_fixed_qparam_fake_quant
344
+ """
345
+ return DEFAULT_MODULE_TO_ACT_POST_PROCESS.get(type_before_parametrizations(module), None)
346
+
347
+ def _has_special_act_post_process(module: torch.nn.Module) -> bool:
348
+ return module.training and type(module) in DEFAULT_MODULE_TO_ACT_POST_PROCESS
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import itertools
3
+ import warnings
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.ao.nn.quantized as nnq
8
+ from torch.ao.nn.intrinsic import _FusedModule
9
+
10
+ from torch.ao.quantization.quantization_mappings import (
11
+ get_default_dynamic_quant_module_mappings,
12
+ get_default_static_quant_module_mappings,
13
+ get_default_static_quant_reference_module_mappings,
14
+ get_default_qat_module_mappings,
15
+ get_default_qconfig_propagation_list,
16
+ no_observer_set,
17
+ _has_special_act_post_process,
18
+ _get_special_act_post_process,
19
+ )
20
+ from .utils import get_qparam_dict, has_no_children_ignoring_parametrizations
21
+ from torch.ao.quantization.stubs import DeQuantStub, QuantWrapper
22
+ from torch.ao.quantization.qconfig import (
23
+ _add_module_to_qconfig_obs_ctr,
24
+ default_dynamic_qconfig,
25
+ float16_dynamic_qconfig,
26
+ float_qparams_weight_only_qconfig,
27
+ float_qparams_weight_only_qconfig_4bit,
28
+ _activation_is_memoryless)
29
+ from torch.nn.utils.parametrize import type_before_parametrizations
30
+ from torch.ao.quantization.observer import _is_activation_post_process
31
+
32
+ # TODO remove this once BC is no longer required to avoid a SEV
33
+ from torch.ao.quantization.observer import ( # noqa: F401
34
+ _is_activation_post_process as is_activation_post_process
35
+ )
36
+
37
+ __all__ = [
38
+ "get_default_custom_config_dict",
39
+ "propagate_qconfig_",
40
+ "add_quant_dequant",
41
+ "prepare",
42
+ "quantize",
43
+ "quantize_dynamic",
44
+ "prepare_qat",
45
+ "quantize_qat",
46
+ "convert",
47
+ "swap_module",
48
+ ]
49
+
50
+ _DEFAULT_CUSTOM_CONFIG_DICT = {
51
+ 'float_to_observed_custom_module_class': {
52
+ nn.LSTM: nn.quantizable.LSTM,
53
+ nn.MultiheadAttention: nn.quantizable.MultiheadAttention,
54
+ },
55
+ 'observed_to_quantized_custom_module_class': {
56
+ nn.quantizable.LSTM: nn.quantized.LSTM,
57
+ nn.quantizable.MultiheadAttention: nn.quantized.MultiheadAttention,
58
+ }
59
+ }
60
+
61
+ def get_default_custom_config_dict():
62
+ r"""Defines the default custom config dict.
63
+ """
64
+ return _DEFAULT_CUSTOM_CONFIG_DICT
65
+
66
+ def _propagate_qconfig_helper(module, qconfig_dict,
67
+ qconfig_parent=None, prefix='', prepare_custom_config_dict=None):
68
+ r"""This is a helper function for `propagate_qconfig_`
69
+
70
+ Args:
71
+ module: input module
72
+ qconfig_dict: dictionary that maps from name of submodule to quantization
73
+ configuration
74
+ qconfig_parent: quantization config of parent module, we will fallback to
75
+ this config when there is no specified config for current
76
+ module
77
+ prefix: corresponding prefix of the current module, used as key in
78
+ qconfig_dict
79
+ prepare_custom_config_dict: dictionary for custom handling of modules
80
+ see docs for :func:`~torch.ao.quantization.prepare_fx`
81
+
82
+ Return:
83
+ None, module is modified inplace with qconfig attached
84
+ """
85
+
86
+ module_qconfig = qconfig_dict.get(type_before_parametrizations(module), qconfig_parent)
87
+ module_qconfig = qconfig_dict.get(prefix, module_qconfig)
88
+ module_qconfig = getattr(module, 'qconfig', module_qconfig)
89
+
90
+ torch.ao.quantization.qconfig._assert_valid_qconfig(module_qconfig, module)
91
+
92
+ qconfig_with_device_check = _add_module_to_qconfig_obs_ctr(module_qconfig, module)
93
+ module.qconfig = qconfig_with_device_check
94
+
95
+ for name, child in module.named_children():
96
+ module_prefix = prefix + '.' + name if prefix else name
97
+ # do no not propagate qconfig to child if child is non traceable
98
+ if prepare_custom_config_dict is None or not (
99
+ name in prepare_custom_config_dict.get("non_traceable_module_name", [])
100
+ or type(child) in prepare_custom_config_dict.get("non_traceable_module_class", [])
101
+ ):
102
+ _propagate_qconfig_helper(
103
+ child, qconfig_dict, qconfig_with_device_check, module_prefix
104
+ )
105
+
106
+ def propagate_qconfig_(module, qconfig_dict=None, prepare_custom_config_dict=None):
107
+ r"""Propagate qconfig through the module hierarchy and assign `qconfig`
108
+ attribute on each leaf module
109
+
110
+ Args:
111
+ module: input module
112
+ qconfig_dict: dictionary that maps from name or type of submodule to
113
+ quantization configuration, qconfig applies to all submodules of a
114
+ given module unless qconfig for the submodules are specified (when
115
+ the submodule already has qconfig attribute)
116
+ prepare_custom_config_dict: dictionary for custom handling of modules
117
+ see docs for :func:`~torch.ao.quantization.prepare_fx`
118
+
119
+ Return:
120
+ None, module is modified inplace with qconfig attached
121
+ """
122
+ if qconfig_dict is None:
123
+ qconfig_dict = {}
124
+ if prepare_custom_config_dict is None:
125
+ prepare_custom_config_dict = {}
126
+ _propagate_qconfig_helper(module, qconfig_dict, prepare_custom_config_dict=prepare_custom_config_dict)
127
+
128
+ def _observer_forward_hook(self, input, output):
129
+ r"""Forward hook that calls observer on the output
130
+ """
131
+ return self.activation_post_process(output)
132
+
133
+ def _observer_forward_pre_hook(self, input):
134
+ r"""Forward pre hook that calls observer on the output
135
+ """
136
+ return self.activation_post_process(input[0])
137
+
138
+ def _register_activation_post_process_hook(module, pre_hook=False):
139
+ assert hasattr(module, 'activation_post_process'), \
140
+ 'Expect activation_post_process attribute already attached to the module'
141
+ if pre_hook:
142
+ handle = module.register_forward_pre_hook(
143
+ _observer_forward_pre_hook, prepend=True
144
+ )
145
+ else:
146
+ handle = module.register_forward_hook(
147
+ _observer_forward_hook, prepend=True
148
+ )
149
+
150
+
151
+ def _add_observer_(module, qconfig_propagation_list=None, non_leaf_module_list=None, device=None, custom_module_class_mapping=None):
152
+ r"""Add observer for the leaf child of the module.
153
+
154
+ This function insert observer module to all leaf child module that
155
+ has a valid qconfig attribute.
156
+
157
+ Args:
158
+ module: input module with qconfig attributes for all the leaf modules that we want to quantize
159
+ qconfig_propagation_list: a list of quantizable modules that will have observers added to them
160
+ if they are leaf nodes
161
+ device: parent device, if any
162
+ non_leaf_module_list: list of non-leaf modules we want to add observer
163
+
164
+ Return:
165
+ None, module is modified inplace with added observer modules and forward_hooks
166
+ """
167
+ if qconfig_propagation_list is None:
168
+ qconfig_propagation_list = get_default_qconfig_propagation_list()
169
+
170
+ if custom_module_class_mapping is None:
171
+ custom_module_class_mapping = {}
172
+
173
+ # respect device affinity when adding observers
174
+ if device is None:
175
+ devices = _get_unique_devices_(module)
176
+ assert len(devices) <= 1, (
177
+ f"_add_observer_ only works with cpu or single-device CUDA modules, but got devices {devices}"
178
+ )
179
+ device = next(iter(devices)) if len(devices) > 0 else None
180
+
181
+ def get_activation_post_process(qconfig, device, special_act_post_process=None):
182
+ activation = qconfig.activation() if special_act_post_process is None else special_act_post_process()
183
+ if device is not None:
184
+ activation.to(device)
185
+ return activation
186
+
187
+ def needs_observation(m):
188
+ return hasattr(m, 'qconfig') and m.qconfig is not None
189
+
190
+ def insert_activation_post_process(m, special_act_post_process=None):
191
+ """ Adds an activation post process module and register
192
+ a pre or post hook that calls the module
193
+ """
194
+ # We don't insert observer/fake_quantize for DeQuantStub
195
+ if needs_observation(m) and not isinstance(m, DeQuantStub):
196
+ # observer and hook will be gone after we swap the module
197
+ m.add_module('activation_post_process', get_activation_post_process(
198
+ m.qconfig, device, special_act_post_process))
199
+ # Register observer as the first entry in the hook list
200
+ # All post forward hooks are preserved and will be executed after the observer before convert
201
+ _register_activation_post_process_hook(m, pre_hook=_activation_is_memoryless(m.qconfig))
202
+
203
+ for name, child in module.named_children():
204
+ # TODO remove Dropout special after codebase stable
205
+ if type_before_parametrizations(child) in [nn.Dropout]:
206
+ continue
207
+ elif issubclass(type_before_parametrizations(child), (nnq.FloatFunctional, nnq.QFunctional)):
208
+ if needs_observation(child):
209
+ assert hasattr(child, "activation_post_process"), (
210
+ f"functional class {type_before_parametrizations(child)} has no pre-defined `activation_post_process`"
211
+ )
212
+ child.activation_post_process = get_activation_post_process(child.qconfig, device)
213
+ elif isinstance(child, _FusedModule):
214
+ # activation_post_process are now added directly to nn.Sequential/_FusedModule
215
+ if needs_observation(child):
216
+ insert_activation_post_process(child)
217
+ elif non_leaf_module_list is not None and type_before_parametrizations(child) in non_leaf_module_list:
218
+ if needs_observation(child):
219
+ insert_activation_post_process(child)
220
+ elif _has_special_act_post_process(child):
221
+ special_act_post_process = _get_special_act_post_process(child)
222
+ insert_activation_post_process(child, special_act_post_process)
223
+ elif needs_observation(child) and type_before_parametrizations(child) in custom_module_class_mapping:
224
+ observed_child = custom_module_class_mapping[type_before_parametrizations(child)].from_float(child)
225
+ setattr(module, name, observed_child)
226
+ # TODO: These are the modules that cannot be observed
227
+ # Once there are more, we should move them to a separate list
228
+ if custom_module_class_mapping[type_before_parametrizations(child)] not in no_observer_set():
229
+ insert_activation_post_process(observed_child)
230
+ else:
231
+ _add_observer_(child, qconfig_propagation_list, non_leaf_module_list, device, custom_module_class_mapping)
232
+
233
+ # Insert observers only for leaf nodes, note that this observer is for
234
+ # the output of the module, for input QuantStub will observe them
235
+ if has_no_children_ignoring_parametrizations(module) and not isinstance(module, torch.nn.Sequential) \
236
+ and type_before_parametrizations(module) in qconfig_propagation_list:
237
+ insert_activation_post_process(module)
238
+
239
+ def _get_unique_devices_(module):
240
+ return {p.device for p in module.parameters()} | \
241
+ {p.device for p in module.buffers()}
242
+
243
+ def add_quant_dequant(module):
244
+ r"""Wrap the leaf child module in QuantWrapper if it has a valid qconfig
245
+ Note that this function will modify the children of module inplace and it
246
+ can return a new module which wraps the input module as well.
247
+
248
+ Args:
249
+ module: input module with qconfig attributes for all the leaf modules
250
+ that we want to quantize
251
+
252
+ Return:
253
+ Either the inplace modified module with submodules wrapped in
254
+ `QuantWrapper` based on qconfig or a new `QuantWrapper` module which
255
+ wraps the input module, the latter case only happens when the input
256
+ module is a leaf module and we want to quantize it.
257
+ """
258
+ if has_no_children_ignoring_parametrizations(module) and hasattr(module, 'qconfig') and module.qconfig:
259
+ return QuantWrapper(module)
260
+
261
+ for name, child in module.named_children():
262
+ module._modules[name] = add_quant_dequant(child)
263
+ return module
264
+
265
+ def prepare(model, inplace=False, allow_list=None,
266
+ observer_non_leaf_module_list=None,
267
+ prepare_custom_config_dict=None):
268
+ r"""Prepares a copy of the model for quantization calibration or quantization-aware training.
269
+
270
+ Quantization configuration should be assigned preemptively
271
+ to individual submodules in `.qconfig` attribute.
272
+
273
+ The model will be attached with observer or fake quant modules, and qconfig
274
+ will be propagated.
275
+
276
+ Args:
277
+ `model`: input model to be modified in-place
278
+ `inplace`: carry out model transformations in-place, the original module is mutated
279
+ `allow_list`: list of quantizable modules
280
+ `observer_non_leaf_module_list`: list of non-leaf modules we want to add observer
281
+ `prepare_custom_config_dict`: customization configuration dictionary for prepare function
282
+
283
+ .. code-block:: python
284
+
285
+ # Example of prepare_custom_config_dict:
286
+ prepare_custom_config_dict = {
287
+ # user will manually define the corresponding observed
288
+ # module class which has a from_float class method that converts
289
+ # float custom module to observed custom module
290
+ "float_to_observed_custom_module_class": {
291
+ CustomModule: ObservedCustomModule
292
+ }
293
+ }
294
+
295
+ """
296
+ torch._C._log_api_usage_once("quantization_api.quantize.prepare")
297
+ if prepare_custom_config_dict is None:
298
+ prepare_custom_config_dict = get_default_custom_config_dict()
299
+ custom_module_class_mapping = prepare_custom_config_dict.get("float_to_observed_custom_module_class", {})
300
+
301
+ if not inplace:
302
+ model = copy.deepcopy(model)
303
+
304
+ # TODO: remove allow_list
305
+ qconfig_propagation_list = allow_list
306
+ if allow_list is None:
307
+ qconfig_propagation_list = get_default_qconfig_propagation_list()
308
+ propagate_qconfig_(model, qconfig_dict=None)
309
+
310
+ # sanity check common API misusage
311
+ if not any(hasattr(m, 'qconfig') and m.qconfig for m in model.modules()):
312
+ warnings.warn("None of the submodule got qconfig applied. Make sure you "
313
+ "passed correct configuration through `qconfig_dict` or "
314
+ "by assigning the `.qconfig` attribute directly on submodules")
315
+
316
+ _add_observer_(
317
+ model, qconfig_propagation_list, observer_non_leaf_module_list,
318
+ custom_module_class_mapping=custom_module_class_mapping)
319
+ return model
320
+
321
+ def _remove_activation_post_process(module):
322
+ # TODO: maybe we should change activation_post_process to _activation_post_process
323
+ # to prevent it from being used by user
324
+ if hasattr(module, 'activation_post_process') and \
325
+ _is_activation_post_process(module.activation_post_process):
326
+ delattr(module, 'activation_post_process')
327
+
328
+ # remove activation_post_process pre and post hooks
329
+ def remove_hooks(pre_hook=False):
330
+ hook_map = module._forward_pre_hooks if pre_hook else module._forward_hooks
331
+ observer_hook = _observer_forward_pre_hook if pre_hook else _observer_forward_hook
332
+ handle_ids_to_remove = set()
333
+ for handle_id, hook_fn in hook_map.items():
334
+ if hook_fn is observer_hook:
335
+ handle_ids_to_remove.add(handle_id)
336
+ for handle_id in handle_ids_to_remove:
337
+ hook_map.pop(handle_id)
338
+
339
+ remove_hooks(pre_hook=True)
340
+ remove_hooks(pre_hook=False)
341
+
342
+ # TODO: rename to something more general
343
+ def _remove_qconfig(module):
344
+ r"""Clean up the qconfig left in the module so that new qconfig can be
345
+ propagated.
346
+
347
+ Args:
348
+ module: module to be cleaned up
349
+ """
350
+ for child in module.children():
351
+ _remove_qconfig(child)
352
+
353
+ if hasattr(module, "qconfig"):
354
+ del module.qconfig
355
+
356
+ _remove_activation_post_process(module)
357
+
358
+ def quantize(model, run_fn, run_args, mapping=None, inplace=False):
359
+ r"""Quantize the input float model with post training static quantization.
360
+
361
+ First it will prepare the model for calibration, then it calls
362
+ `run_fn` which will run the calibration step, after that we will
363
+ convert the model to a quantized model.
364
+
365
+ Args:
366
+ model: input float model
367
+ run_fn: a calibration function for calibrating the prepared model
368
+ run_args: positional arguments for `run_fn`
369
+ inplace: carry out model transformations in-place, the original module is mutated
370
+ mapping: correspondence between original module types and quantized counterparts
371
+
372
+ Return:
373
+ Quantized model.
374
+ """
375
+ torch._C._log_api_usage_once("quantization_api.quantize.quantize")
376
+ if mapping is None:
377
+ mapping = get_default_static_quant_module_mappings()
378
+ if not inplace:
379
+ model = copy.deepcopy(model)
380
+ model.eval()
381
+ prepare(model, inplace=True)
382
+ run_fn(model, *run_args)
383
+ convert(model, mapping, inplace=True)
384
+ return model
385
+
386
+ def quantize_dynamic(model, qconfig_spec=None, dtype=torch.qint8,
387
+ mapping=None, inplace=False):
388
+ r"""Converts a float model to dynamic (i.e. weights-only) quantized model.
389
+
390
+ Replaces specified modules with dynamic weight-only quantized versions and output the quantized model.
391
+
392
+ For simplest usage provide `dtype` argument that can be float16 or qint8. Weight-only quantization
393
+ by default is performed for layers with large weights size - i.e. Linear and RNN variants.
394
+
395
+ Fine grained control is possible with `qconfig` and `mapping` that act similarly to `quantize()`.
396
+ If `qconfig` is provided, the `dtype` argument is ignored.
397
+
398
+ Args:
399
+ model: input model
400
+ qconfig_spec: Either:
401
+
402
+ - A dictionary that maps from name or type of submodule to quantization
403
+ configuration, qconfig applies to all submodules of a given
404
+ module unless qconfig for the submodules are specified (when the
405
+ submodule already has qconfig attribute). Entries in the dictionary
406
+ need to be QConfig instances.
407
+
408
+ - A set of types and/or submodule names to apply dynamic quantization to,
409
+ in which case the `dtype` argument is used to specify the bit-width
410
+
411
+ inplace: carry out model transformations in-place, the original module is mutated
412
+ mapping: maps type of a submodule to a type of corresponding dynamically quantized version
413
+ with which the submodule needs to be replaced
414
+
415
+ """
416
+ torch._C._log_api_usage_once("quantization_api.quantize.quantize_dynamic")
417
+ if qconfig_spec is None:
418
+ if dtype == torch.qint8:
419
+ qconfig_spec = {
420
+ nn.Linear : default_dynamic_qconfig,
421
+ nn.LSTM : default_dynamic_qconfig,
422
+ nn.GRU : default_dynamic_qconfig,
423
+ nn.LSTMCell : default_dynamic_qconfig,
424
+ nn.RNNCell : default_dynamic_qconfig,
425
+ nn.GRUCell : default_dynamic_qconfig,
426
+ }
427
+ elif dtype == torch.float16:
428
+ qconfig_spec = {
429
+ nn.Linear : float16_dynamic_qconfig,
430
+ nn.LSTM : float16_dynamic_qconfig,
431
+ nn.GRU : float16_dynamic_qconfig,
432
+ nn.LSTMCell : float16_dynamic_qconfig,
433
+ nn.RNNCell : float16_dynamic_qconfig,
434
+ nn.GRUCell : float16_dynamic_qconfig,
435
+ }
436
+ elif dtype == torch.quint8:
437
+ qconfig_spec = {
438
+ nn.EmbeddingBag : float_qparams_weight_only_qconfig,
439
+ nn.Embedding : float_qparams_weight_only_qconfig,
440
+ }
441
+ elif dtype == torch.quint4x2:
442
+ qconfig_spec = {
443
+ nn.EmbeddingBag : float_qparams_weight_only_qconfig_4bit,
444
+ }
445
+ else:
446
+ raise ValueError(
447
+ f"Don't know how to quantize with default settings for {dtype}. Provide full qconfig please")
448
+ elif isinstance(qconfig_spec, set):
449
+ if dtype is torch.qint8:
450
+ default_qconfig = default_dynamic_qconfig
451
+ elif dtype is torch.float16:
452
+ default_qconfig = float16_dynamic_qconfig
453
+ elif dtype is torch.quint8:
454
+ default_qconfig = float_qparams_weight_only_qconfig
455
+ elif dtype is torch.quint4x2:
456
+ default_qconfig = float_qparams_weight_only_qconfig_4bit
457
+ else:
458
+ raise RuntimeError('Unknown dtype specified for quantize_dynamic: ', str(dtype))
459
+ qconfig_spec = dict(zip(qconfig_spec, itertools.repeat(default_qconfig)))
460
+
461
+ if mapping is None:
462
+ mapping = get_default_dynamic_quant_module_mappings()
463
+
464
+ if not inplace:
465
+ model = copy.deepcopy(model)
466
+ model.eval()
467
+ propagate_qconfig_(model, qconfig_spec)
468
+ convert(model, mapping, inplace=True)
469
+ return model
470
+
471
+ def prepare_qat(model, mapping=None, inplace=False):
472
+ r"""
473
+ Prepares a copy of the model for quantization calibration or
474
+ quantization-aware training and converts it to quantized version.
475
+
476
+ Quantization configuration should be assigned preemptively
477
+ to individual submodules in `.qconfig` attribute.
478
+
479
+ Args:
480
+ model: input model to be modified in-place
481
+ mapping: dictionary that maps float modules to quantized modules to be
482
+ replaced.
483
+ inplace: carry out model transformations in-place, the original module
484
+ is mutated
485
+ """
486
+ torch._C._log_api_usage_once("quantization_api.quantize.prepare_qat")
487
+ assert model.training, "prepare_qat only works on models in training mode"
488
+ if mapping is None:
489
+ mapping = get_default_qat_module_mappings()
490
+
491
+ if not inplace:
492
+ model = copy.deepcopy(model)
493
+
494
+ propagate_qconfig_(model, qconfig_dict=None)
495
+ convert(model, mapping=mapping, inplace=True, remove_qconfig=False)
496
+ prepare(model, observer_non_leaf_module_list=set(mapping.values()), inplace=True)
497
+ return model
498
+
499
+ def quantize_qat(model, run_fn, run_args, inplace=False):
500
+ r"""Do quantization aware training and output a quantized model
501
+
502
+ Args:
503
+ model: input model
504
+ run_fn: a function for evaluating the prepared model, can be a
505
+ function that simply runs the prepared model or a training
506
+ loop
507
+ run_args: positional arguments for `run_fn`
508
+
509
+ Return:
510
+ Quantized model.
511
+ """
512
+ torch._C._log_api_usage_once("quantization_api.quantize.quantize_qat")
513
+ if not inplace:
514
+ model = copy.deepcopy(model)
515
+ model.train()
516
+ prepare_qat(model, inplace=True)
517
+ run_fn(model, *run_args)
518
+ convert(model, inplace=True)
519
+ return model
520
+
521
+ def convert(
522
+ module, mapping=None, inplace=False, remove_qconfig=True,
523
+ is_reference=False, convert_custom_config_dict=None):
524
+ r"""Converts submodules in input module to a different module according to `mapping`
525
+ by calling `from_float` method on the target module class. And remove qconfig at the
526
+ end if remove_qconfig is set to True.
527
+
528
+ Args:
529
+ `module`: prepared and calibrated module
530
+ `mapping`: a dictionary that maps from source module type to target
531
+ module type, can be overwritten to allow swapping user defined
532
+ Modules
533
+ `inplace`: carry out model transformations in-place, the original module
534
+ is mutated
535
+ `convert_custom_config_dict`: custom configuration dictionary for convert function
536
+
537
+ .. code-block:: python
538
+
539
+ # Example of convert_custom_config_dict:
540
+ convert_custom_config_dict = {
541
+ # user will manually define the corresponding quantized
542
+ # module class which has a from_observed class method that converts
543
+ # observed custom module to quantized custom module
544
+ "observed_to_quantized_custom_module_class": {
545
+ ObservedCustomModule: QuantizedCustomModule
546
+ }
547
+ }
548
+
549
+ """
550
+ torch._C._log_api_usage_once("quantization_api.quantize.convert")
551
+ if not inplace:
552
+ module = copy.deepcopy(module)
553
+ _convert(
554
+ module, mapping, inplace=True, is_reference=is_reference,
555
+ convert_custom_config_dict=convert_custom_config_dict)
556
+ if remove_qconfig:
557
+ _remove_qconfig(module)
558
+ return module
559
+
560
+ def _convert(
561
+ module, mapping=None, inplace=False,
562
+ is_reference=False, convert_custom_config_dict=None):
563
+ r"""Converts submodules in input module to a different module according to `mapping`
564
+ by calling `from_float` method on the target module class
565
+
566
+ Args:
567
+ module: input module
568
+ mapping: a dictionary that maps from source module type to target
569
+ module type, can be overwritten to allow swapping user defined
570
+ Modules
571
+ inplace: carry out model transformations in-place, the original module
572
+ is mutated
573
+ is_reference: a flag to enable quantized reference module
574
+
575
+ """
576
+ if mapping is None:
577
+ mapping = get_default_static_quant_reference_module_mappings() if is_reference \
578
+ else get_default_static_quant_module_mappings()
579
+ if convert_custom_config_dict is None:
580
+ convert_custom_config_dict = get_default_custom_config_dict()
581
+ custom_module_class_mapping = convert_custom_config_dict.get("observed_to_quantized_custom_module_class", {})
582
+
583
+ if not inplace:
584
+ module = copy.deepcopy(module)
585
+ reassign = {}
586
+ for name, mod in module.named_children():
587
+ # both fused modules and observed custom modules are
588
+ # swapped as one unit
589
+ if not isinstance(mod, _FusedModule) and \
590
+ type_before_parametrizations(mod) not in custom_module_class_mapping:
591
+ _convert(mod, mapping, True, # inplace
592
+ is_reference, convert_custom_config_dict)
593
+ reassign[name] = swap_module(mod, mapping, custom_module_class_mapping)
594
+
595
+ for key, value in reassign.items():
596
+ module._modules[key] = value
597
+
598
+ return module
599
+
600
+ def swap_module(mod, mapping, custom_module_class_mapping):
601
+ r"""Swaps the module if it has a quantized counterpart and it has an
602
+ `observer` attached.
603
+
604
+ Args:
605
+ mod: input module
606
+ mapping: a dictionary that maps from nn module to nnq module
607
+
608
+ Return:
609
+ The corresponding quantized module of `mod`
610
+ """
611
+ new_mod = mod
612
+ if hasattr(mod, 'qconfig') and mod.qconfig is not None:
613
+ swapped = False
614
+ if type_before_parametrizations(mod) in custom_module_class_mapping:
615
+ new_mod = custom_module_class_mapping[type_before_parametrizations(mod)].from_observed(mod)
616
+ swapped = True
617
+ elif type_before_parametrizations(mod) in mapping:
618
+ qmod = mapping[type_before_parametrizations(mod)]
619
+ if hasattr(qmod, '_IS_REFERENCE') and qmod._IS_REFERENCE:
620
+ assert mod.qconfig is not None
621
+ weight_post_process = mod.qconfig.weight()
622
+ weight_post_process(mod.weight)
623
+ weight_qparams = get_qparam_dict(weight_post_process)
624
+ new_mod = qmod.from_float(mod, weight_qparams)
625
+ else:
626
+ new_mod = qmod.from_float(mod)
627
+ swapped = True
628
+
629
+ if swapped:
630
+ # Preserve module's pre forward hooks. They'll be called on quantized input
631
+ for pre_hook_fn in mod._forward_pre_hooks.values():
632
+ new_mod.register_forward_pre_hook(pre_hook_fn)
633
+ # Preserve module's post forward hooks except _observer_forward_hook
634
+ # After convert they'll work with quantized output
635
+ for hook_fn in mod._forward_hooks.values():
636
+ if hook_fn is not _observer_forward_hook:
637
+ new_mod.register_forward_hook(hook_fn)
638
+
639
+ # respect device affinity when swapping modules
640
+ devices = _get_unique_devices_(mod)
641
+ assert len(devices) <= 1, (
642
+ f"swap_module only works with cpu or single-device CUDA modules, but got devices {devices}"
643
+ )
644
+ device = next(iter(devices)) if len(devices) > 0 else None
645
+ if device:
646
+ new_mod.to(device)
647
+ return new_mod
648
+
649
+ def _get_observer_dict(mod, target_dict, prefix=""):
650
+ r"""Traverse the modules and save all observers into dict.
651
+ This is mainly used for quantization accuracy debug
652
+ Args:
653
+ mod: the top module we want to save all observers
654
+ prefix: the prefix for the current module
655
+ target_dict: the dictionary used to save all the observers
656
+ """
657
+ def get_prefix(prefix):
658
+ return prefix if prefix == "" else prefix + '.'
659
+
660
+ if hasattr(mod, 'activation_post_process'):
661
+ target_dict[get_prefix(prefix) + 'activation_post_process'] = mod.activation_post_process
662
+ for name, child in mod.named_children():
663
+ module_prefix = get_prefix(prefix) + name if prefix else name
664
+ _get_observer_dict(child, target_dict, module_prefix)
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_fx.py ADDED
@@ -0,0 +1,726 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional, Tuple, Union
2
+ import warnings
3
+
4
+ import torch
5
+ import copy
6
+ from torch.fx import GraphModule
7
+ from torch.fx.graph_module import _USER_PRESERVED_ATTRIBUTES_KEY
8
+ from .fx.tracer import QuantizationTracer
9
+ from .fx.tracer import ( # noqa: F401
10
+ Scope,
11
+ ScopeContextManager
12
+ )
13
+ from .fx.fuse import fuse # noqa: F401
14
+ from .fx.prepare import prepare # noqa: F401
15
+ from .fx.convert import convert
16
+ from .backend_config import ( # noqa: F401
17
+ BackendConfig,
18
+ get_tensorrt_backend_config,
19
+ )
20
+ from .fx.graph_module import ObservedGraphModule # noqa: F401
21
+ from .fx.custom_config import (
22
+ ConvertCustomConfig,
23
+ FuseCustomConfig,
24
+ PrepareCustomConfig,
25
+ )
26
+ from .fx.utils import get_custom_module_class_keys # noqa: F401
27
+ from .fx.utils import get_skipped_module_name_and_classes
28
+ from .qconfig_mapping import QConfigMapping
29
+
30
+ def attach_preserved_attrs_to_model(
31
+ model: Union[GraphModule, torch.nn.Module],
32
+ preserved_attrs: Dict[str, Any],
33
+ ) -> None:
34
+ """ Store preserved attributes to the model.meta so that it can be preserved during deepcopy
35
+ """
36
+ model.meta[_USER_PRESERVED_ATTRIBUTES_KEY] = copy.copy(preserved_attrs) # type: ignore[operator, index, assignment]
37
+ # set the preserved attributes in the model so that user can call
38
+ # model.attr as they do before calling fx graph mode quantization
39
+ for attr_name, attr in model.meta[_USER_PRESERVED_ATTRIBUTES_KEY].items(): # type: ignore[index, union-attr]
40
+ setattr(model, attr_name, attr)
41
+
42
+ def _check_is_graph_module(model: torch.nn.Module) -> None:
43
+ if not isinstance(model, GraphModule):
44
+ raise ValueError(
45
+ "input model must be a GraphModule, "
46
+ + "Got type:"
47
+ + str(type(model))
48
+ + " Please make "
49
+ + "sure to follow the tutorials."
50
+ )
51
+
52
+ def _attach_meta_to_node_if_not_exist(model: GraphModule) -> None:
53
+ """ Attach meta field to all nodes of the graph if it does not exist,
54
+ meta field is a field stores some meta information about the node, such
55
+ as dtype and shape information for output of the node, this only exists
56
+ if the program is captured by make_fx (used in quantize_pt2e flow), if
57
+ the program is captured by torch.fx symbolic tracing, this field may not exist,
58
+ so we add it here to avoid checking this all over the places
59
+ """
60
+ for node in model.graph.nodes:
61
+ if not hasattr(node, "meta"):
62
+ node.meta = {}
63
+
64
+ def _swap_ff_with_fxff(model: torch.nn.Module) -> None:
65
+ r""" Swap FloatFunctional with FXFloatFunctional
66
+ """
67
+ modules_to_swap = []
68
+ for name, module in model.named_children():
69
+ if isinstance(module, torch.ao.nn.quantized.FloatFunctional):
70
+ modules_to_swap.append(name)
71
+ else:
72
+ _swap_ff_with_fxff(module)
73
+
74
+ for name in modules_to_swap:
75
+ del model._modules[name]
76
+ model._modules[name] = torch.ao.nn.quantized.FXFloatFunctional()
77
+
78
+
79
+ def _fuse_fx(
80
+ model: GraphModule,
81
+ is_qat: bool,
82
+ fuse_custom_config: Union[FuseCustomConfig, Dict[str, Any], None] = None,
83
+ backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
84
+ ) -> GraphModule:
85
+ r""" Internal helper function to fuse modules in preparation for quantization
86
+
87
+ Args:
88
+ model: GraphModule object from symbolic tracing (torch.fx.symbolic_trace)
89
+ """
90
+ _check_is_graph_module(model)
91
+ return fuse(
92
+ model, is_qat, fuse_custom_config, backend_config) # type: ignore[operator]
93
+
94
+ def _prepare_fx(
95
+ model: torch.nn.Module,
96
+ qconfig_mapping: Union[QConfigMapping, Dict[str, Any]],
97
+ is_qat: bool,
98
+ example_inputs: Tuple[Any, ...],
99
+ prepare_custom_config: Union[PrepareCustomConfig, Dict[str, Any], None] = None,
100
+ _equalization_config: Optional[Union[QConfigMapping, Dict[str, Any]]] = None,
101
+ backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
102
+ is_standalone_module: bool = False,
103
+ ) -> GraphModule:
104
+ r""" Internal helper function for prepare_fx
105
+ Args:
106
+ `model`, `qconfig_mapping`, `prepare_custom_config`, `_equalization_config`:
107
+ see docs for :func:`~torch.ao.quantization.prepare_fx`
108
+ `is_standalone_module`: a boolean flag indicates whether we are
109
+ quantizing a standalone module or not, a standalone module
110
+ is a submodule of the parent module that is not inlined in the
111
+ forward graph of the parent module,
112
+ the way we quantize standalone module is described in:
113
+ :func:`~torch.ao.quantization._prepare_standalone_module_fx`
114
+ """
115
+ if prepare_custom_config is None:
116
+ prepare_custom_config = PrepareCustomConfig()
117
+ if _equalization_config is None:
118
+ _equalization_config = QConfigMapping()
119
+
120
+ if isinstance(prepare_custom_config, Dict):
121
+ warnings.warn(
122
+ "Passing a prepare_custom_config_dict to prepare is deprecated and will not be supported "
123
+ "in a future version. Please pass in a PrepareCustomConfig instead.")
124
+ prepare_custom_config = PrepareCustomConfig.from_dict(prepare_custom_config)
125
+
126
+ # swap FloatFunctional with FXFloatFunctional
127
+ _swap_ff_with_fxff(model)
128
+
129
+ skipped_module_names, skipped_module_classes = \
130
+ get_skipped_module_name_and_classes(prepare_custom_config, is_standalone_module)
131
+ preserved_attr_names = prepare_custom_config.preserved_attributes
132
+ preserved_attrs = {attr: getattr(model, attr) for attr in preserved_attr_names if hasattr(model, attr)}
133
+ # symbolically trace the model
134
+ tracer = QuantizationTracer(skipped_module_names, skipped_module_classes) # type: ignore[arg-type]
135
+ graph_module = GraphModule(model, tracer.trace(model))
136
+ _attach_meta_to_node_if_not_exist(graph_module)
137
+
138
+ fuse_custom_config = FuseCustomConfig().set_preserved_attributes(prepare_custom_config.preserved_attributes)
139
+ graph_module = _fuse_fx(
140
+ graph_module,
141
+ is_qat,
142
+ fuse_custom_config,
143
+ backend_config)
144
+ prepared = prepare(
145
+ graph_module,
146
+ qconfig_mapping,
147
+ is_qat,
148
+ tracer.node_name_to_scope,
149
+ example_inputs=example_inputs,
150
+ prepare_custom_config=prepare_custom_config,
151
+ _equalization_config=_equalization_config,
152
+ backend_config=backend_config,
153
+ is_standalone_module=is_standalone_module,
154
+ ) # type: ignore[operator]
155
+
156
+ attach_preserved_attrs_to_model(prepared, preserved_attrs)
157
+ return prepared
158
+
159
+
160
+ def _prepare_standalone_module_fx(
161
+ model: torch.nn.Module,
162
+ qconfig_mapping: Union[QConfigMapping, Dict[str, Any]],
163
+ is_qat: bool,
164
+ example_inputs: Tuple[Any, ...],
165
+ prepare_custom_config: Union[PrepareCustomConfig, Dict[str, Any], None] = None,
166
+ backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
167
+ ) -> GraphModule:
168
+ r""" [Internal use only] Prepare a standalone module, so that it can be used when quantizing the
169
+ parent module.
170
+ standalone_module means it a submodule that is not inlined in parent module,
171
+ and will be quantized separately as one unit.
172
+
173
+ How the standalone module is observed is specified by `input_quantized_idxs` and
174
+ `output_quantized_idxs` in the prepare_custom_config for the standalone module
175
+
176
+ Returns:
177
+
178
+ * model(GraphModule): prepared standalone module. It has these attributes in
179
+ model.meta:
180
+
181
+ * `standalone_module_input_quantized_idxs(List[Int])`: a list of
182
+ indexes for the graph input that is expected to be quantized,
183
+ same as input_quantized_idxs configuration provided
184
+ for the standalone module
185
+ * `standalone_module_output_quantized_idxs(List[Int])`: a list of
186
+ indexs for the graph output that is quantized
187
+ same as input_quantized_idxs configuration provided
188
+ for the standalone module
189
+
190
+ """
191
+ return _prepare_fx(
192
+ model,
193
+ qconfig_mapping,
194
+ is_qat,
195
+ example_inputs,
196
+ prepare_custom_config,
197
+ backend_config=backend_config,
198
+ is_standalone_module=True,
199
+ )
200
+
201
+
202
+ def fuse_fx(
203
+ model: torch.nn.Module,
204
+ fuse_custom_config: Union[FuseCustomConfig, Dict[str, Any], None] = None,
205
+ backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
206
+ ) -> GraphModule:
207
+ r""" Fuse modules like conv+bn, conv+bn+relu etc, model must be in eval mode.
208
+ Fusion rules are defined in torch.ao.quantization.fx.fusion_pattern.py
209
+
210
+ Args:
211
+
212
+ * `model` (torch.nn.Module): a torch.nn.Module model
213
+ * `fuse_custom_config` (FuseCustomConfig): custom configurations for fuse_fx.
214
+ See :class:`~torch.ao.quantization.fx.custom_config.FuseCustomConfig` for more details
215
+ Example::
216
+
217
+ from torch.ao.quantization import fuse_fx
218
+ m = Model().eval()
219
+ m = fuse_fx(m)
220
+
221
+ """
222
+ if fuse_custom_config is None:
223
+ fuse_custom_config = FuseCustomConfig()
224
+
225
+ if isinstance(fuse_custom_config, Dict):
226
+ warnings.warn(
227
+ "Passing a fuse_custom_config_dict to fuse is deprecated and will not be supported "
228
+ "in a future version. Please pass in a FuseCustomConfig instead.")
229
+ fuse_custom_config = FuseCustomConfig.from_dict(fuse_custom_config)
230
+
231
+ torch._C._log_api_usage_once("quantization_api.quantize_fx.fuse_fx")
232
+ preserved_attr_names = fuse_custom_config.preserved_attributes
233
+ preserved_attrs = {attr: getattr(model, attr) for attr in preserved_attr_names if hasattr(model, attr)}
234
+
235
+ graph_module = torch.fx.symbolic_trace(model)
236
+ _attach_meta_to_node_if_not_exist(graph_module)
237
+ graph_module = _fuse_fx(graph_module, False, fuse_custom_config, backend_config)
238
+
239
+ attach_preserved_attrs_to_model(graph_module, preserved_attrs)
240
+ return graph_module
241
+
242
+ def prepare_fx(
243
+ model: torch.nn.Module,
244
+ qconfig_mapping: Union[QConfigMapping, Dict[str, Any]],
245
+ example_inputs: Tuple[Any, ...],
246
+ prepare_custom_config: Union[PrepareCustomConfig, Dict[str, Any], None] = None,
247
+ _equalization_config: Optional[Union[QConfigMapping, Dict[str, Any]]] = None,
248
+ backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
249
+ ) -> GraphModule:
250
+ r""" Prepare a model for post training quantization
251
+
252
+ Args:
253
+ * `model` (torch.nn.Module): torch.nn.Module model
254
+
255
+ * `qconfig_mapping` (QConfigMapping): QConfigMapping object to configure how a model is
256
+ quantized, see :class:`~torch.ao.quantization.qconfig_mapping.QConfigMapping`
257
+ for more details
258
+
259
+ * `example_inputs` (Tuple[Any, ...]): Example inputs for forward function of the model,
260
+ Tuple of positional args (keyword args can be passed as positional args as well)
261
+
262
+ * `prepare_custom_config` (PrepareCustomConfig): customization configuration for quantization tool.
263
+ See :class:`~torch.ao.quantization.fx.custom_config.PrepareCustomConfig` for more details
264
+
265
+ * `_equalization_config`: config for specifying how to perform equalization on the model
266
+
267
+ * `backend_config` (BackendConfig): config that specifies how operators are quantized
268
+ in a backend, this includes how the operators are observed,
269
+ supported fusion patterns, how quantize/dequantize ops are
270
+ inserted, supported dtypes etc. See :class:`~torch.ao.quantization.backend_config.BackendConfig` for more details
271
+
272
+ Return:
273
+ A GraphModule with observer (configured by qconfig_mapping), ready for calibration
274
+
275
+ Example::
276
+
277
+ import torch
278
+ from torch.ao.quantization import get_default_qconfig_mapping
279
+ from torch.ao.quantization.quantize_fx import prepare_fx
280
+
281
+ class Submodule(torch.nn.Module):
282
+ def __init__(self):
283
+ super().__init__()
284
+ self.linear = torch.nn.Linear(5, 5)
285
+ def forward(self, x):
286
+ x = self.linear(x)
287
+ return x
288
+
289
+ class M(torch.nn.Module):
290
+ def __init__(self):
291
+ super().__init__()
292
+ self.linear = torch.nn.Linear(5, 5)
293
+ self.sub = Submodule()
294
+
295
+ def forward(self, x):
296
+ x = self.linear(x)
297
+ x = self.sub(x) + x
298
+ return x
299
+
300
+ # initialize a floating point model
301
+ float_model = M().eval()
302
+
303
+ # define calibration function
304
+ def calibrate(model, data_loader):
305
+ model.eval()
306
+ with torch.no_grad():
307
+ for image, target in data_loader:
308
+ model(image)
309
+
310
+ # qconfig is the configuration for how we insert observers for a particular
311
+ # operator
312
+ # qconfig = get_default_qconfig("fbgemm")
313
+ # Example of customizing qconfig:
314
+ # qconfig = torch.ao.quantization.QConfig(
315
+ # activation=MinMaxObserver.with_args(dtype=torch.qint8),
316
+ # weight=MinMaxObserver.with_args(dtype=torch.qint8))
317
+ # `activation` and `weight` are constructors of observer module
318
+
319
+ # qconfig_mapping is a collection of quantization configurations, user can
320
+ # set the qconfig for each operator (torch op calls, functional calls, module calls)
321
+ # in the model through qconfig_mapping
322
+ # the following call will get the qconfig_mapping that works best for models
323
+ # that target "fbgemm" backend
324
+ qconfig_mapping = get_default_qconfig_mapping("fbgemm")
325
+
326
+ # We can customize qconfig_mapping in different ways.
327
+ # e.g. set the global qconfig, which means we will use the same qconfig for
328
+ # all operators in the model, this can be overwritten by other settings
329
+ # qconfig_mapping = QConfigMapping().set_global(qconfig)
330
+ # e.g. quantize the linear submodule with a specific qconfig
331
+ # qconfig_mapping = QConfigMapping().set_module_name("linear", qconfig)
332
+ # e.g. quantize all nn.Linear modules with a specific qconfig
333
+ # qconfig_mapping = QConfigMapping().set_object_type(torch.nn.Linear, qconfig)
334
+ # for a more complete list, please see the docstring for :class:`torch.ao.quantization.QConfigMapping`
335
+ # argument
336
+
337
+ # example_inputs is a tuple of inputs, that is used to infer the type of the
338
+ # outputs in the model
339
+ # currently it's not used, but please make sure model(*example_inputs) runs
340
+ example_inputs = (torch.randn(1, 3, 224, 224),)
341
+
342
+ # TODO: add backend_config after we split the backend_config for fbgemm and qnnpack
343
+ # e.g. backend_config = get_default_backend_config("fbgemm")
344
+ # `prepare_fx` inserts observers in the model based on qconfig_mapping and
345
+ # backend_config. If the configuration for an operator in qconfig_mapping
346
+ # is supported in the backend_config (meaning it's supported by the target
347
+ # hardware), we'll insert observer modules according to the qconfig_mapping
348
+ # otherwise the configuration in qconfig_mapping will be ignored
349
+ #
350
+ # Example:
351
+ # in qconfig_mapping, user sets linear module to be quantized with quint8 for
352
+ # activation and qint8 for weight:
353
+ # qconfig = torch.ao.quantization.QConfig(
354
+ # observer=MinMaxObserver.with_args(dtype=torch.quint8),
355
+ # weight=MinMaxObserver.with-args(dtype=torch.qint8))
356
+ # Note: current qconfig api does not support setting output observer, but
357
+ # we may extend this to support these more fine grained control in the
358
+ # future
359
+ #
360
+ # qconfig_mapping = QConfigMapping().set_object_type(torch.nn.Linear, qconfig)
361
+ # in backend config, linear module also supports in this configuration:
362
+ # weighted_int8_dtype_config = DTypeConfig(
363
+ # input_dtype=torch.quint8,
364
+ # output_dtype=torch.quint8,
365
+ # weight_dtype=torch.qint8,
366
+ # bias_type=torch.float)
367
+
368
+ # linear_pattern_config = BackendPatternConfig(torch.nn.Linear) \
369
+ # .set_observation_type(ObservationType.OUTPUT_USE_DIFFERENT_OBSERVER_AS_INPUT) \
370
+ # .add_dtype_config(weighted_int8_dtype_config) \
371
+ # ...
372
+
373
+ # backend_config = BackendConfig().set_backend_pattern_config(linear_pattern_config)
374
+ # `prepare_fx` will check that the setting requested by suer in qconfig_mapping
375
+ # is supported by the backend_config and insert observers and fake quant modules
376
+ # in the model
377
+ prepared_model = prepare_fx(float_model, qconfig_mapping, example_inputs)
378
+ # Run calibration
379
+ calibrate(prepared_model, sample_inference_data)
380
+ """
381
+ torch._C._log_api_usage_once("quantization_api.quantize_fx.prepare_fx")
382
+ return _prepare_fx(
383
+ model,
384
+ qconfig_mapping,
385
+ False, # is_qat
386
+ example_inputs,
387
+ prepare_custom_config,
388
+ _equalization_config,
389
+ backend_config,
390
+ )
391
+
392
+
393
+ def prepare_qat_fx(
394
+ model: torch.nn.Module,
395
+ qconfig_mapping: Union[QConfigMapping, Dict[str, Any]],
396
+ example_inputs: Tuple[Any, ...],
397
+ prepare_custom_config: Union[PrepareCustomConfig, Dict[str, Any], None] = None,
398
+ backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
399
+ ) -> GraphModule:
400
+ r""" Prepare a model for quantization aware training
401
+
402
+ Args:
403
+ * `model` (torch.nn.Module): torch.nn.Module model
404
+ * `qconfig_mapping` (QConfigMapping): see :func:`~torch.ao.quantization.prepare_fx`
405
+ * `example_inputs` (Tuple[Any, ...]): see :func:`~torch.ao.quantization.prepare_fx`
406
+ * `prepare_custom_config` (PrepareCustomConfig): see :func:`~torch.ao.quantization.prepare_fx`
407
+ * `backend_config` (BackendConfig): see :func:`~torch.ao.quantization.prepare_fx`
408
+
409
+ Return:
410
+ A GraphModule with fake quant modules (configured by qconfig_mapping and backend_config), ready for
411
+ quantization aware training
412
+
413
+ Example::
414
+
415
+ import torch
416
+ from torch.ao.quantization import get_default_qat_qconfig_mapping
417
+ from torch.ao.quantization.quantize_fx import prepare_qat_fx
418
+
419
+ class Submodule(torch.nn.Module):
420
+ def __init__(self):
421
+ super().__init__()
422
+ self.linear = torch.nn.Linear(5, 5)
423
+ def forward(self, x):
424
+ x = self.linear(x)
425
+ return x
426
+
427
+ class M(torch.nn.Module):
428
+ def __init__(self):
429
+ super().__init__()
430
+ self.linear = torch.nn.Linear(5, 5)
431
+ self.sub = Submodule()
432
+
433
+ def forward(self, x):
434
+ x = self.linear(x)
435
+ x = self.sub(x) + x
436
+ return x
437
+
438
+ # initialize a floating point model
439
+ float_model = M().train()
440
+ # (optional, but preferred) load the weights from pretrained model
441
+ # float_model.load_weights(...)
442
+
443
+ # define the training loop for quantization aware training
444
+ def train_loop(model, train_data):
445
+ model.train()
446
+ for image, target in data_loader:
447
+ ...
448
+
449
+ # qconfig is the configuration for how we insert observers for a particular
450
+ # operator
451
+ # qconfig = get_default_qconfig("fbgemm")
452
+ # Example of customizing qconfig:
453
+ # qconfig = torch.ao.quantization.QConfig(
454
+ # activation=FakeQuantize.with_args(observer=MinMaxObserver.with_args(dtype=torch.qint8)),
455
+ # weight=FakeQuantize.with_args(observer=MinMaxObserver.with_args(dtype=torch.qint8)))
456
+ # `activation` and `weight` are constructors of observer module
457
+
458
+ # qconfig_mapping is a collection of quantization configurations, user can
459
+ # set the qconfig for each operator (torch op calls, functional calls, module calls)
460
+ # in the model through qconfig_mapping
461
+ # the following call will get the qconfig_mapping that works best for models
462
+ # that target "fbgemm" backend
463
+ qconfig_mapping = get_default_qat_qconfig("fbgemm")
464
+
465
+ # We can customize qconfig_mapping in different ways, please take a look at
466
+ # the docstring for :func:`~torch.ao.quantization.prepare_fx` for different ways
467
+ # to configure this
468
+
469
+ # example_inputs is a tuple of inputs, that is used to infer the type of the
470
+ # outputs in the model
471
+ # currently it's not used, but please make sure model(*example_inputs) runs
472
+ example_inputs = (torch.randn(1, 3, 224, 224),)
473
+
474
+ # TODO: add backend_config after we split the backend_config for fbgemm and qnnpack
475
+ # e.g. backend_config = get_default_backend_config("fbgemm")
476
+ # `prepare_qat_fx` inserts observers in the model based on qconfig_mapping and
477
+ # backend_config, if the configuration for an operator in qconfig_mapping
478
+ # is supported in the backend_config (meaning it's supported by the target
479
+ # hardware), we'll insert fake_quantize modules according to the qconfig_mapping
480
+ # otherwise the configuration in qconfig_mapping will be ignored
481
+ # see :func:`~torch.ao.quantization.prepare_fx` for a detailed explanation of
482
+ # how qconfig_mapping interacts with backend_config
483
+ prepared_model = prepare_qat_fx(float_model, qconfig_mapping, example_inputs)
484
+ # Run training
485
+ train_loop(prepared_model, train_loop)
486
+
487
+ """
488
+ torch._C._log_api_usage_once("quantization_api.quantize_fx.prepare_qat_fx")
489
+ return _prepare_fx(
490
+ model,
491
+ qconfig_mapping,
492
+ True, # is_qat
493
+ example_inputs,
494
+ prepare_custom_config,
495
+ backend_config=backend_config,
496
+ )
497
+
498
+
499
+ def _convert_fx(
500
+ graph_module: GraphModule,
501
+ is_reference: bool,
502
+ convert_custom_config: Union[ConvertCustomConfig, Dict[str, Any], None] = None,
503
+ is_standalone_module: bool = False,
504
+ _remove_qconfig: bool = True,
505
+ qconfig_mapping: Union[QConfigMapping, Dict[str, Any], None] = None,
506
+ backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
507
+ is_decomposed: bool = False,
508
+ ) -> GraphModule:
509
+ """ `is_standalone_module`: see docs in :func:`~torch.ao.quantization.prepare_standalone_module_fx`
510
+ """
511
+ if convert_custom_config is None:
512
+ convert_custom_config = ConvertCustomConfig()
513
+
514
+ if isinstance(convert_custom_config, Dict):
515
+ warnings.warn(
516
+ "Passing a convert_custom_config_dict to convert is deprecated and will not be supported "
517
+ "in a future version. Please pass in a ConvertCustomConfig instead.")
518
+ convert_custom_config = ConvertCustomConfig.from_dict(convert_custom_config)
519
+
520
+ _check_is_graph_module(graph_module)
521
+ preserved_attr_names = convert_custom_config.preserved_attributes
522
+ preserved_attrs = {attr: getattr(graph_module, attr) for attr in preserved_attr_names if hasattr(graph_module, attr)}
523
+
524
+ quantized = convert(
525
+ graph_module,
526
+ is_reference,
527
+ convert_custom_config,
528
+ is_standalone_module,
529
+ _remove_qconfig_flag=_remove_qconfig,
530
+ qconfig_mapping=qconfig_mapping,
531
+ backend_config=backend_config,
532
+ is_decomposed=is_decomposed,
533
+ )
534
+
535
+ attach_preserved_attrs_to_model(quantized, preserved_attrs)
536
+ return quantized
537
+
538
+
539
+ def convert_fx(
540
+ graph_module: GraphModule,
541
+ convert_custom_config: Union[ConvertCustomConfig, Dict[str, Any], None] = None,
542
+ _remove_qconfig: bool = True,
543
+ qconfig_mapping: Union[QConfigMapping, Dict[str, Any], None] = None,
544
+ backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
545
+ ) -> GraphModule:
546
+ r""" Convert a calibrated or trained model to a quantized model
547
+
548
+ Args:
549
+ * `graph_module` (torch.fx.GraphModule): A prepared and calibrated/trained model (GraphModule)
550
+
551
+ * `convert_custom_config` (ConvertCustomConfig): custom configurations for convert function.
552
+ See :class:`~torch.ao.quantization.fx.custom_config.ConvertCustomConfig` for more details
553
+
554
+ * `_remove_qconfig` (bool): Option to remove the qconfig attributes in the model after convert.
555
+
556
+ * `qconfig_mapping` (QConfigMapping): config for specifying how to convert a model for quantization.
557
+
558
+ The keys must include the ones in the qconfig_mapping passed to `prepare_fx` or `prepare_qat_fx`,
559
+ with the same values or `None`. Additional keys can be specified with values set to `None`.
560
+
561
+ For each entry whose value is set to None, we skip quantizing that entry in the model::
562
+
563
+ qconfig_mapping = QConfigMapping
564
+ .set_global(qconfig_from_prepare)
565
+ .set_object_type(torch.nn.functional.add, None) # skip quantizing torch.nn.functional.add
566
+ .set_object_type(torch.nn.functional.linear, qconfig_from_prepare)
567
+ .set_module_name("foo.bar", None) # skip quantizing module "foo.bar"
568
+
569
+ * `backend_config` (BackendConfig): A configuration for the backend which describes how
570
+ operators should be quantized in the backend, this includes quantization
571
+ mode support (static/dynamic/weight_only), dtype support (quint8/qint8 etc.),
572
+ observer placement for each operators and fused operators.
573
+ See :class:`~torch.ao.quantization.backend_config.BackendConfig` for more details
574
+
575
+ Return:
576
+ A quantized model (torch.nn.Module)
577
+
578
+ Example::
579
+
580
+ # prepared_model: the model after prepare_fx/prepare_qat_fx and calibration/training
581
+ # convert_fx converts a calibrated/trained model to a quantized model for the
582
+ # target hardware, this includes converting the model first to a reference
583
+ # quantized model, and then lower the reference quantized model to a backend
584
+ # Currently, the supported backends are fbgemm (onednn), qnnpack (xnnpack) and
585
+ # they share the same set of quantized operators, so we are using the same
586
+ # lowering procedure
587
+ #
588
+ # backend_config defines the corresponding reference quantized module for
589
+ # the weighted modules in the model, e.g. nn.Linear
590
+ # TODO: add backend_config after we split the backend_config for fbgemm and qnnpack
591
+ # e.g. backend_config = get_default_backend_config("fbgemm")
592
+ quantized_model = convert_fx(prepared_model)
593
+
594
+ """
595
+ torch._C._log_api_usage_once("quantization_api.quantize_fx.convert_fx")
596
+ return _convert_fx(
597
+ graph_module,
598
+ is_reference=False,
599
+ convert_custom_config=convert_custom_config,
600
+ _remove_qconfig=_remove_qconfig,
601
+ qconfig_mapping=qconfig_mapping,
602
+ backend_config=backend_config,
603
+ )
604
+
605
+
606
+ def convert_to_reference_fx(
607
+ graph_module: GraphModule,
608
+ convert_custom_config: Union[ConvertCustomConfig, Dict[str, Any], None] = None,
609
+ _remove_qconfig: bool = True,
610
+ qconfig_mapping: Union[QConfigMapping, Dict[str, Any], None] = None,
611
+ backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
612
+ ) -> GraphModule:
613
+ r""" Convert a calibrated or trained model to a reference quantized model,
614
+ see https://github.com/pytorch/rfcs/blob/master/RFC-0019-Extending-PyTorch-Quantization-to-Custom-Backends.md for more details,
615
+ reference quantized model is a standard representation of a quantized model provided
616
+ by FX Graph Mode Quantization, it can be further lowered to run on the target
617
+ hardware, like accelerators
618
+
619
+ Args:
620
+ * `graph_module` (GraphModule): A prepared and calibrated/trained model (GraphModule)
621
+
622
+ * `convert_custom_config` (ConvertCustomConfig): custom configurations for convert function.
623
+ See :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details.
624
+
625
+ * `_remove_qconfig` (bool): Option to remove the qconfig attributes in the model after convert.
626
+
627
+ * `qconfig_mapping` (QConfigMapping): config for specifying how to convert a model for quantization.
628
+ See :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details.
629
+
630
+ * `backend_config` (BackendConfig): A configuration for the backend which describes how
631
+ operators should be quantized in the backend. See
632
+ :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details.
633
+
634
+ Return:
635
+ A reference quantized model (GraphModule)
636
+
637
+ Example::
638
+
639
+ # prepared_model: the model after prepare_fx/prepare_qat_fx and calibration/training
640
+ # TODO: add backend_config after we split the backend_config for fbgemm and qnnpack
641
+ # e.g. backend_config = get_default_backend_config("fbgemm")
642
+ reference_quantized_model = convert_to_reference_fx(prepared_model)
643
+
644
+ """
645
+ torch._C._log_api_usage_once("quantization_api.quantize_fx.convert_to_reference_fx")
646
+ return _convert_fx(
647
+ graph_module,
648
+ is_reference=True,
649
+ convert_custom_config=convert_custom_config,
650
+ _remove_qconfig=_remove_qconfig,
651
+ qconfig_mapping=qconfig_mapping,
652
+ backend_config=backend_config,
653
+ )
654
+
655
+ def _convert_to_reference_decomposed_fx(
656
+ graph_module: GraphModule,
657
+ convert_custom_config: Union[ConvertCustomConfig, Dict[str, Any], None] = None,
658
+ qconfig_mapping: Union[QConfigMapping, Dict[str, Any], None] = None,
659
+ backend_config: Union[BackendConfig, Dict[str, Any], None] = None,
660
+ ) -> GraphModule:
661
+ r""" Convert a calibrated or trained model to a reference quantized model, with
662
+ decomposed representation for quantized Tensor
663
+ see https://github.com/pytorch/rfcs/blob/master/RFC-0019-Extending-PyTorch-Quantization-to-Custom-Backends.md for more details,
664
+ reference quantized model is a standard representation of a quantized model provided
665
+ by FX Graph Mode Quantization, it can be further lowered to run on the target
666
+ hardware, like accelerators
667
+
668
+ Note: this is not public API
669
+
670
+ Args:
671
+ * `graph_module` (GraphModule): A prepared and calibrated/trained model (GraphModule)
672
+
673
+ * `convert_custom_config` (ConvertCustomConfig): custom configurations for convert function.
674
+ See :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details.
675
+
676
+ * `_remove_qconfig` (bool): Option to remove the qconfig attributes in the model after convert.
677
+
678
+ * `qconfig_mapping` (QConfigMapping): config for specifying how to convert a model for quantization.
679
+ See :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details.
680
+
681
+ * `backend_config` (BackendConfig): A configuration for the backend which describes how
682
+ operators should be quantized in the backend. See
683
+ :func:`~torch.ao.quantization.quantize_fx.convert_fx` for more details.
684
+
685
+ Return:
686
+ A reference quantized model (GraphModule) with operators working with decomposed quantized Tensor
687
+
688
+ Example::
689
+
690
+ # prepared_model: the model after prepare_fx/prepare_qat_fx and calibration/training
691
+ # TODO: add backend_config after we split the backend_config for fbgemm and qnnpack
692
+ # e.g. backend_config = get_default_backend_config("fbgemm")
693
+ reference_quantized_model = _convert_to_reference_decomposed_fx(prepared_model)
694
+
695
+ """
696
+ torch._C._log_api_usage_once("quantization_api.quantize_fx._convert_to_reference_decomposed_fx")
697
+ return _convert_fx(
698
+ graph_module,
699
+ is_reference=True,
700
+ convert_custom_config=convert_custom_config,
701
+ _remove_qconfig=False,
702
+ qconfig_mapping=qconfig_mapping,
703
+ backend_config=backend_config,
704
+ is_decomposed=True,
705
+ )
706
+
707
+
708
+ def _convert_standalone_module_fx(
709
+ graph_module: GraphModule,
710
+ is_reference: bool = False,
711
+ convert_custom_config: Union[ConvertCustomConfig, Dict[str, Any], None] = None,
712
+ ) -> GraphModule:
713
+ r""" [Internal use only] Convert a model produced by :func:`~torch.ao.quantization.prepare_standalone_module_fx`
714
+ and convert it to a quantized model
715
+
716
+ Returns a quantized standalone module, whether input/output is quantized is
717
+ specified by prepare_custom_config, with
718
+ input_quantized_idxs, output_quantized_idxs, please
719
+ see docs for prepare_fx for details
720
+ """
721
+ return _convert_fx(
722
+ graph_module,
723
+ is_reference,
724
+ convert_custom_config,
725
+ is_standalone_module=True,
726
+ )
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_jit.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ from torch.ao.quantization.qconfig import QConfig
4
+ from torch.ao.quantization.quant_type import QuantType
5
+ from torch.jit._recursive import wrap_cpp_module
6
+
7
+ __all__ = [
8
+ "script_qconfig",
9
+ "script_qconfig_dict",
10
+ "fuse_conv_bn_jit",
11
+ "prepare_jit",
12
+ "prepare_dynamic_jit",
13
+ "convert_jit",
14
+ "convert_dynamic_jit",
15
+ "quantize_jit",
16
+ "quantize_dynamic_jit",
17
+ ]
18
+
19
+ def _check_is_script_module(model):
20
+ if not isinstance(model, torch.jit.ScriptModule):
21
+ raise ValueError('input must be a script module, got: ' + str(type(model)))
22
+
23
+ def _check_forward_method(model):
24
+ if not model._c._has_method('forward'):
25
+ raise ValueError('input script module does not have forward method')
26
+
27
+ def script_qconfig(qconfig):
28
+ r"""Instantiate the activation and weight observer modules and script
29
+ them, these observer module instances will be deepcopied during
30
+ prepare_jit step.
31
+ """
32
+ return QConfig(
33
+ activation=torch.jit.script(qconfig.activation())._c,
34
+ weight=torch.jit.script(qconfig.weight())._c)
35
+
36
+ def script_qconfig_dict(qconfig_dict):
37
+ r"""Helper function used by `prepare_jit`.
38
+ Apply `script_qconfig` for all entries in `qconfig_dict` that is
39
+ not None.
40
+ """
41
+ return {k: script_qconfig(v) if v else None for k, v in qconfig_dict.items()}
42
+
43
+ def fuse_conv_bn_jit(model, inplace=False):
44
+ r""" Fuse conv - bn module
45
+ Works for eval model only.
46
+
47
+ Args:
48
+ model: TorchScript model from scripting or tracing
49
+ """
50
+ torch._C._log_api_usage_once("quantization_api.quantize_jit.fuse_conv_bn_jit")
51
+ model_c = model._c
52
+ model_c = torch._C._jit_pass_fold_convbn(model_c)
53
+ if inplace:
54
+ model._reconstruct(model_c)
55
+ else:
56
+ model = wrap_cpp_module(model_c)
57
+ return model
58
+
59
+ def _prepare_jit(model, qconfig_dict, inplace=False, quant_type=QuantType.STATIC):
60
+ _check_is_script_module(model)
61
+ _check_forward_method(model)
62
+ if not all(isinstance(x, str) for x in qconfig_dict.keys()):
63
+ raise ValueError('qconfig_dict should only contain names(str) as keys.')
64
+ scripted_qconfig_dict = script_qconfig_dict(qconfig_dict)
65
+ model = fuse_conv_bn_jit(model, inplace)
66
+ model_c = torch._C._jit_pass_insert_observers(model._c,
67
+ 'forward',
68
+ scripted_qconfig_dict,
69
+ inplace,
70
+ quant_type)
71
+ if inplace:
72
+ model._reconstruct(model_c)
73
+ else:
74
+ model = wrap_cpp_module(model_c)
75
+ return model
76
+
77
+ def _prepare_ondevice_jit(model, qconfig_dict, method_name='forward', inplace=False, quant_type=QuantType.STATIC):
78
+ _check_is_script_module(model)
79
+ if not all(isinstance(x, str) for x in qconfig_dict.keys()):
80
+ raise ValueError('qconfig_dict should only contain names(str) as keys.')
81
+ scripted_qconfig_dict = script_qconfig_dict(qconfig_dict)
82
+ method_graph = model._c._get_method(method_name).graph
83
+ torch._C._jit_pass_inline(method_graph)
84
+ model = fuse_conv_bn_jit(model, inplace)
85
+ model_c = torch._C._jit_pass_insert_observer_method_for_ondevice_ptq(model._c,
86
+ method_name,
87
+ scripted_qconfig_dict,
88
+ inplace,
89
+ quant_type)
90
+ if inplace:
91
+ model._reconstruct(model_c)
92
+ else:
93
+ model = wrap_cpp_module(model_c)
94
+ return model
95
+
96
+ def prepare_jit(model, qconfig_dict, inplace=False):
97
+ torch._C._log_api_usage_once("quantization_api.quantize_jit.prepare_jit")
98
+ return _prepare_jit(model, qconfig_dict, inplace, quant_type=QuantType.STATIC)
99
+
100
+ def prepare_dynamic_jit(model, qconfig_dict, inplace=False):
101
+ torch._C._log_api_usage_once("quantization_api.quantize_jit.prepare_dynamic_jit")
102
+ return _prepare_jit(model, qconfig_dict, inplace, quant_type=QuantType.DYNAMIC)
103
+
104
+
105
+ def _prepare_ondevice_dynamic_jit(model, qconfig_dict, method_name='forward', inplace=False):
106
+ return _prepare_ondevice_jit(model, qconfig_dict, method_name, inplace, quant_type=QuantType.DYNAMIC)
107
+
108
+ def _convert_jit(model, inplace=False, debug=False, quant_type=QuantType.STATIC,
109
+ preserved_attrs=None):
110
+ _check_is_script_module(model)
111
+ model.eval()
112
+ model_c = model._c
113
+ model_c = torch._C._jit_pass_insert_quant_dequant(model_c, 'forward', inplace, debug, quant_type)
114
+ if not debug:
115
+ is_xpu = all(p.device.type == 'xpu' for p in model.parameters())
116
+ if not is_xpu:
117
+ # Moving model parameters to CPU since quantized operators
118
+ # are only supported on CPU and XPU right now
119
+ model.cpu()
120
+ if preserved_attrs is None:
121
+ preserved_attrs = []
122
+ model_c = torch._C._jit_pass_quant_finalize(model_c, quant_type, preserved_attrs)
123
+ if inplace:
124
+ model._reconstruct(model_c)
125
+ else:
126
+ model = wrap_cpp_module(model_c)
127
+ torch._C._jit_pass_constant_propagation(model.graph)
128
+ torch._C._jit_pass_dce(model.graph)
129
+ return model
130
+
131
+
132
+ def _convert_ondevice_jit(model, method_name, inplace=False, debug=False, quant_type=QuantType.STATIC):
133
+ _check_is_script_module(model)
134
+ assert quant_type == QuantType.DYNAMIC, "This API, while should work for static quant, is only tested for dynamic quant."
135
+ assert not method_name.startswith("observe_"), "Pass in valid method to be quantized, e.g. forward"
136
+ observe_method_name = "observe_" + method_name
137
+ quantize_method_name = "quantize_" + method_name
138
+ model_c = model._c
139
+ model_c = torch._C._jit_pass_insert_quant_dequant_for_ondevice_ptq(
140
+ model._c, observe_method_name, inplace, debug, QuantType.DYNAMIC)
141
+ model_c = torch._C._jit_pass_quant_finalize_for_ondevice_ptq(model_c, QuantType.DYNAMIC, quantize_method_name)
142
+ if inplace:
143
+ model._reconstruct(model_c)
144
+ else:
145
+ model = wrap_cpp_module(model_c)
146
+ return model
147
+
148
+ def convert_jit(model, inplace=False, debug=False, preserved_attrs=None):
149
+ torch._C._log_api_usage_once("quantization_api.quantize_jit.convert_jit")
150
+ return _convert_jit(model, inplace, debug, quant_type=QuantType.STATIC, preserved_attrs=preserved_attrs)
151
+
152
+ def convert_dynamic_jit(model, inplace=False, debug=False, preserved_attrs=None):
153
+ torch._C._log_api_usage_once("quantization_api.quantize_jit.convert_dynamic_jit")
154
+ return _convert_jit(model, inplace, debug, quant_type=QuantType.DYNAMIC, preserved_attrs=preserved_attrs)
155
+
156
+
157
+ def _convert_ondevice_dynamic_jit(model, method_name, inplace=False, debug=False):
158
+ return _convert_ondevice_jit(model, method_name, inplace, debug, quant_type=QuantType.DYNAMIC)
159
+
160
+
161
+ def _quantize_ondevice_dynamic_jit_impl(model, qconfig_dict, method_name, inplace=False):
162
+ model = _prepare_ondevice_dynamic_jit(model, qconfig_dict, method_name, inplace)
163
+ model = _convert_ondevice_dynamic_jit(model, method_name, inplace)
164
+ return model
165
+
166
+ def _quantize_jit(model, qconfig_dict, run_fn=None, run_args=None, inplace=False, debug=False, quant_type=QuantType.STATIC):
167
+ # Always do inplace convert because the Tensor is already
168
+ # copied in prepare_jit when inplace is False
169
+ if quant_type == QuantType.DYNAMIC:
170
+ model = prepare_dynamic_jit(model, qconfig_dict, inplace)
171
+ model = convert_dynamic_jit(model, True, debug)
172
+ else:
173
+ assert run_fn, "Must provide calibration function for post training static quantization"
174
+ assert run_args, "Must provide calibration dataset for post training static quantization"
175
+ model = prepare_jit(model, qconfig_dict, inplace)
176
+ run_fn(model, *run_args)
177
+ model = convert_jit(model, True, debug)
178
+
179
+ torch._C._jit_pass_constant_propagation(model.graph)
180
+ torch._C._jit_pass_dce(model.graph)
181
+ return model
182
+
183
+ def quantize_jit(model, qconfig_dict, run_fn, run_args, inplace=False, debug=False):
184
+ r"""Quantize the input float TorchScript model with
185
+ post training static quantization.
186
+
187
+ First it will prepare the model for calibration, then it calls
188
+ `run_fn` which will run the calibration step, after that we will
189
+ convert the model to a quantized model.
190
+
191
+ Args:
192
+ `model`: input float TorchScript model
193
+ `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and
194
+ qconfig for that module as value, empty key means the qconfig will be applied
195
+ to whole model unless it's overwritten by more specific configurations, the
196
+ qconfig for each module is either found in the dictionary or fallback to
197
+ the qconfig of parent module.
198
+
199
+ Right now qconfig_dict is the only way to configure how the model is quantized,
200
+ and it is done in the granularity of module, that is, we only support one type
201
+ of qconfig for each torch.nn.Module, and the qconfig for sub module will
202
+ override the qconfig for parent module, empty string means global configuration.
203
+ `run_fn`: a calibration function for calibrating the prepared model
204
+ `run_args`: positional arguments for `run_fn`
205
+ `inplace`: carry out model transformations in-place, the original module is
206
+ mutated
207
+ `debug`: flag for producing a debug friendly model (preserve weight attribute)
208
+
209
+ Return:
210
+ Quantized TorchSciprt model.
211
+
212
+ Example:
213
+ ```python
214
+ import torch
215
+ from torch.ao.quantization import get_default_qconfig
216
+ from torch.ao.quantization import quantize_jit
217
+
218
+ ts_model = torch.jit.script(float_model.eval()) # or torch.jit.trace(float_model, input)
219
+ qconfig = get_default_qconfig('fbgemm')
220
+ def calibrate(model, data_loader):
221
+ model.eval()
222
+ with torch.no_grad():
223
+ for image, target in data_loader:
224
+ model(image)
225
+
226
+ quantized_model = quantize_jit(
227
+ ts_model,
228
+ {'': qconfig},
229
+ calibrate,
230
+ [data_loader_test])
231
+ ```
232
+ """
233
+ torch._C._log_api_usage_once("quantization_api.quantize_jit.quantize_jit")
234
+ return _quantize_jit(model, qconfig_dict, run_fn, run_args, inplace, debug, quant_type=QuantType.STATIC)
235
+
236
+ def quantize_dynamic_jit(model, qconfig_dict, inplace=False, debug=False):
237
+ r"""Quantize the input float TorchScript model with
238
+ post training dynamic quantization.
239
+ Currently only qint8 quantization of torch.nn.Linear is supported.
240
+
241
+ Args:
242
+ `model`: input float TorchScript model
243
+ `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and
244
+ qconfig for that module as value, please see detailed
245
+ descriptions in :func:`~torch.ao.quantization.quantize_jit`
246
+ `inplace`: carry out model transformations in-place, the original module is
247
+ mutated
248
+ `debug`: flag for producing a debug friendly model (preserve weight attribute)
249
+
250
+ Return:
251
+ Quantized TorchSciprt model.
252
+
253
+ Example:
254
+ ```python
255
+ import torch
256
+ from torch.ao.quantization import per_channel_dynamic_qconfig
257
+ from torch.ao.quantization import quantize_dynamic_jit
258
+
259
+ ts_model = torch.jit.script(float_model.eval()) # or torch.jit.trace(float_model, input)
260
+ qconfig = get_default_qconfig('fbgemm')
261
+ def calibrate(model, data_loader):
262
+ model.eval()
263
+ with torch.no_grad():
264
+ for image, target in data_loader:
265
+ model(image)
266
+
267
+ quantized_model = quantize_dynamic_jit(
268
+ ts_model,
269
+ {'': qconfig},
270
+ calibrate,
271
+ [data_loader_test])
272
+ ```
273
+ """
274
+ torch._C._log_api_usage_once("quantization_api.quantize_jit.quantize_dynamic_jit")
275
+ return _quantize_jit(model, qconfig_dict, inplace=inplace, debug=debug, quant_type=QuantType.DYNAMIC)
276
+
277
+
278
+ def _quantize_ondevice_dynamic_jit(model, qconfig_dict, method_name='forward', inplace=False):
279
+ r"""Prepares the input float TorchScript model with
280
+ *on-device* post training dynamic quantization.
281
+ Currently only qint8 quantization of torch.nn.Linear is supported.
282
+
283
+ Args:
284
+ `model`: input float TorchScript model
285
+ `qconfig_dict`: qconfig_dict is a dictionary with names of sub modules as key and
286
+ qconfig for that module as value, please see detailed
287
+ `method_name`: Name of the method within the model, to be prepared for quantization
288
+ descriptions in :func:`~torch.ao.quantization.quantize_jit`
289
+ `inplace`: carry out model transformations in-place, the original module is
290
+ mutated
291
+
292
+ Return:
293
+ TorchScript model that is ready for on device quantization.
294
+ This means that the returned
295
+ model has:
296
+ - Method is inlined.
297
+ - Model has observer modules inserted in the model.
298
+ - Model has packed params inserted in the model. However they are empty as in they dont
299
+ contain valid quantized weights.
300
+ - observe_<method_name> is added that observe the values to be quantized.
301
+ - reset_observers_<method_name> to reset observers.
302
+ - quantize_<method_name> is added to the model.
303
+ - This method extract scale, zero points.
304
+ - Quantizes observed weights.
305
+ - Creates packed params from it and update the attribute of the model with the new values
306
+ for the packed params.
307
+ - Reset the original fp32 weights with empty tensor using SetAttr.
308
+ - quantized_<method_name> is added to the model.
309
+ - This method uses quantized weights and quantized linear ops instead of fp32 op.
310
+ - This method should be used for inference post PTQ.
311
+ - Note that all method's signatures should be the same as method_name.
312
+
313
+ Later on device:
314
+ - Run reset_observers_<method_name>
315
+ - Run observe_<method_name>
316
+ - Run quantize_<method_name>
317
+ - Now model can be saved and loaded later.
318
+ - Run model with quantized_<method_name>
319
+
320
+ Example:
321
+ ```python
322
+ import torch
323
+ from torch.ao.quantization import per_channel_dynamic_qconfig
324
+ from torch.ao.quantization.quantize_jit import _quantize_ondevice_dynamic_jit
325
+
326
+ ts_model = torch.jit.script(float_model.eval()) # or torch.jit.trace(float_model, input)
327
+ qconfig = get_default_qconfig('fbgemm')
328
+ quant_ready_model = _quantize_ondevice_dynamic_jit(
329
+ ts_model,
330
+ {'': qconfig},
331
+ 'forward',
332
+ True)
333
+ ```
334
+ """
335
+ return _quantize_ondevice_dynamic_jit_impl(model, qconfig_dict, method_name, inplace=inplace)
videollama2/lib/python3.10/site-packages/torch/ao/quantization/quantize_pt2e.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.fx import GraphModule
3
+ from torch.fx import Node
4
+
5
+ from .pt2e.prepare import prepare
6
+ from .pt2e.qat_utils import (
7
+ _fuse_conv_bn_qat,
8
+ _fold_conv_bn_qat,
9
+ )
10
+ from .pt2e.utils import (
11
+ _get_node_name_to_scope,
12
+ _fuse_conv_bn_,
13
+ _disallow_eval_train,
14
+ )
15
+ from .pt2e.representation import reference_representation_rewrite
16
+ from .quantize_fx import _convert_to_reference_decomposed_fx
17
+ from torch.ao.quantization.quantizer import ( # noqa: F401
18
+ Quantizer,
19
+ QuantizationSpecBase,
20
+ QuantizationSpec,
21
+ FixedQParamsQuantizationSpec,
22
+ SharedQuantizationSpec,
23
+ DerivedQuantizationSpec,
24
+ QuantizationAnnotation,
25
+ )
26
+ from torch.fx.passes.infra.pass_manager import PassManager
27
+ from torch.ao.quantization.pt2e.duplicate_dq_pass import DuplicateDQPass
28
+ from torch.ao.quantization.pt2e.port_metadata_pass import PortNodeMetaForQDQ
29
+ from torch._inductor.constant_folding import constant_fold
30
+
31
+ __all__ = [
32
+ "prepare_pt2e",
33
+ "prepare_qat_pt2e",
34
+ "convert_pt2e",
35
+ ]
36
+
37
+
38
+ def prepare_pt2e(
39
+ model: GraphModule,
40
+ quantizer: Quantizer,
41
+ ) -> GraphModule:
42
+ """Prepare a model for post training quantization
43
+
44
+ Args:
45
+ * `model` (torch.fx.GraphModule): a model captured by `torch.export` API
46
+ in the short term we are using `torch._export.capture_pre_autograd_graph`,
47
+ in the long term we'll migrate to some `torch.export` API
48
+ * `quantizer`: A backend specific quantizer that conveys how user want the
49
+ model to be quantized. Tutorial for how to write a quantizer can be found here:
50
+ https://pytorch.org/tutorials/prototype/pt2e_quantizer.html
51
+
52
+ Return:
53
+ A GraphModule with observer (based on quantizer annotation), ready for calibration
54
+
55
+ Example::
56
+
57
+ import torch
58
+ from torch.ao.quantization.quantize_pt2e import prepare_pt2e
59
+ from torch._export import capture_pre_autograd_graph
60
+ from torch.ao.quantization.quantizer import (
61
+ XNNPACKQuantizer,
62
+ get_symmetric_quantization_config,
63
+ )
64
+
65
+ class M(torch.nn.Module):
66
+ def __init__(self):
67
+ super().__init__()
68
+ self.linear = torch.nn.Linear(5, 10)
69
+
70
+ def forward(self, x):
71
+ return self.linear(x)
72
+
73
+ # initialize a floating point model
74
+ float_model = M().eval()
75
+
76
+ # define calibration function
77
+ def calibrate(model, data_loader):
78
+ model.eval()
79
+ with torch.no_grad():
80
+ for image, target in data_loader:
81
+ model(image)
82
+
83
+ # Step 1. program capture
84
+ # NOTE: this API will be updated to torch.export API in the future, but the captured
85
+ # result shoud mostly stay the same
86
+ m = capture_pre_autograd_graph(m, *example_inputs)
87
+ # we get a model with aten ops
88
+
89
+ # Step 2. quantization
90
+ # backend developer will write their own Quantizer and expose methods to allow
91
+ # users to express how they
92
+ # want the model to be quantized
93
+ quantizer = XNNPACKQuantizer().set_global(get_symmetric_quantization_config())
94
+ m = prepare_pt2e(m, quantizer)
95
+
96
+ # run calibration
97
+ # calibrate(m, sample_inference_data)
98
+ """
99
+ torch._C._log_api_usage_once("quantization_api.quantize_pt2e.prepare_pt2e")
100
+ original_graph_meta = model.meta
101
+ node_name_to_scope = _get_node_name_to_scope(model)
102
+ # TODO: check qconfig_mapping to make sure conv and bn are both configured
103
+ # to be quantized before fusion
104
+ # TODO: (maybe) rewrite this with subgraph_rewriter
105
+ _fuse_conv_bn_(model)
106
+ quantizer.transform_for_annotation(model)
107
+ quantizer.annotate(model)
108
+ quantizer.validate(model)
109
+ model = prepare(model, node_name_to_scope, is_qat=False)
110
+ model.meta.update(original_graph_meta)
111
+ model = _disallow_eval_train(model)
112
+ return model
113
+
114
+ def prepare_qat_pt2e(
115
+ model: GraphModule,
116
+ quantizer: Quantizer,
117
+ ) -> GraphModule:
118
+ """Prepare a model for quantization aware training
119
+
120
+ Args:
121
+ * `model` (torch.fx.GraphModule): see :func:`~torch.ao.quantization.quantize_pt2e.prepare_pt2e`
122
+ * `quantizer`: see :func:`~torch.ao.quantization.quantize_pt2e.prepare_pt2e`
123
+
124
+ Return:
125
+ A GraphModule with fake quant modules (based on quantizer annotation), ready for
126
+ quantization aware training
127
+
128
+ Example::
129
+ import torch
130
+ from torch.ao.quantization.quantize_pt2e import prepare_qat_pt2e
131
+ from torch._export import capture_pre_autograd_graph
132
+ from torch.ao.quantization.quantizer import (
133
+ XNNPACKQuantizer,
134
+ get_symmetric_quantization_config,
135
+ )
136
+
137
+ class M(torch.nn.Module):
138
+ def __init__(self):
139
+ super().__init__()
140
+ self.linear = torch.nn.Linear(5, 10)
141
+
142
+ def forward(self, x):
143
+ return self.linear(x)
144
+
145
+ # initialize a floating point model
146
+ float_model = M().eval()
147
+
148
+ # define the training loop for quantization aware training
149
+ def train_loop(model, train_data):
150
+ model.train()
151
+ for image, target in data_loader:
152
+ ...
153
+
154
+ # Step 1. program capture
155
+ # NOTE: this API will be updated to torch.export API in the future, but the captured
156
+ # result shoud mostly stay the same
157
+ m = capture_pre_autograd_graph(m, *example_inputs)
158
+ # we get a model with aten ops
159
+
160
+ # Step 2. quantization
161
+ # backend developer will write their own Quantizer and expose methods to allow
162
+ # users to express how they
163
+ # want the model to be quantized
164
+ quantizer = XNNPACKQuantizer().set_global(get_symmetric_quantization_config())
165
+ m = prepare_qat_pt2e(m, quantizer)
166
+
167
+ # run quantization aware training
168
+ train_loop(prepared_model, train_loop)
169
+
170
+ """
171
+ torch._C._log_api_usage_once("quantization_api.quantize_pt2e.prepare_qat_pt2e")
172
+ original_graph_meta = model.meta
173
+ node_name_to_scope = _get_node_name_to_scope(model)
174
+ quantizer.transform_for_annotation(model)
175
+ quantizer.annotate(model)
176
+ quantizer.validate(model)
177
+ # Perform fusion after annotate to avoid quantizing ops in the new
178
+ # subgraph that don't need to be quantized
179
+ # TODO: only fuse if conv and bn are both configured to be quantized
180
+ _fuse_conv_bn_qat(model)
181
+ model = prepare(model, node_name_to_scope, is_qat=True)
182
+ model.meta.update(original_graph_meta)
183
+ model = _disallow_eval_train(model)
184
+ return model
185
+
186
+ _QUANT_OPS = [
187
+ torch.ops.quantized_decomposed.quantize_per_tensor.default,
188
+ torch.ops.quantized_decomposed.quantize_per_tensor.tensor,
189
+ torch.ops.quantized_decomposed.quantize_per_channel.default,
190
+ ]
191
+ def _quant_node_constraint(n: Node) -> bool:
192
+ """If there is any pure ops between get_attr and quantize op they will be const propagated
193
+ e.g. get_attr(weight) -> transpose -> quantize -> dequantize*
194
+ (Note: dequantize op is not going to be constant propagated)
195
+
196
+ This filter is added because we don't want to constant fold the things that are not
197
+ related to quantization
198
+ """
199
+ return n.op == "call_function" and n.target in _QUANT_OPS
200
+
201
+ def convert_pt2e(
202
+ model: GraphModule,
203
+ use_reference_representation: bool = False,
204
+ fold_quantize: bool = False,
205
+ ) -> GraphModule:
206
+ """Convert a calibrated/trained model to a quantized model
207
+
208
+ Args:
209
+ * `model` (torch.fx.GraphModule): calibrated/trained model
210
+ * `use_reference_representation` (bool): boolean flag to indicate whether to produce referece representation or not
211
+ * `fold_quantize` (bool): boolean flag to indicate whether fold the quantize op or not
212
+
213
+ Note: please set `fold_quantize` to True whenever you can, we'll deprecate this flag and
214
+ make True the default option in the future, to make sure the change doesn't break BC for you, it's
215
+ better to set the flag to True now.
216
+
217
+ Returns:
218
+ quantized model, either in q/dq representation or reference representation
219
+
220
+ Example::
221
+
222
+ # prepared_model: the model produced by `prepare_pt2e`/`prepare_qat_pt2e` and calibration/training
223
+ # `convert_pt2e` produces a quantized model that represents quantized computation with
224
+ # quantize dequantize ops and fp32 ops by default.
225
+ # Please refer to
226
+ # https://pytorch.org/tutorials/prototype/pt2e_quant_ptq_static.html#convert-the-calibrated-model-to-a-quantized-model
227
+ # for detailed explanation of output quantized model
228
+ quantized_model = convert_pt2e(prepared_model)
229
+
230
+ """ # flake8: noqa
231
+ torch._C._log_api_usage_once("quantization_api.quantize_pt2e.convert_pt2e")
232
+ original_graph_meta = model.meta
233
+ model = _convert_to_reference_decomposed_fx(model)
234
+ model = _fold_conv_bn_qat(model)
235
+ pm = PassManager([DuplicateDQPass()])
236
+
237
+ model = pm(model).graph_module
238
+ pm = PassManager([PortNodeMetaForQDQ()])
239
+ model = pm(model).graph_module
240
+
241
+ if fold_quantize:
242
+ constant_fold(model, _quant_node_constraint)
243
+
244
+ if use_reference_representation:
245
+ model = reference_representation_rewrite(model)
246
+
247
+ model.meta.update(original_graph_meta)
248
+ model = _disallow_eval_train(model)
249
+ return model
videollama2/lib/python3.10/site-packages/torch/ao/quantization/stubs.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from torch import nn
3
+
4
+ class QuantStub(nn.Module):
5
+ r"""Quantize stub module, before calibration, this is same as an observer,
6
+ it will be swapped as `nnq.Quantize` in `convert`.
7
+
8
+ Args:
9
+ qconfig: quantization configuration for the tensor,
10
+ if qconfig is not provided, we will get qconfig from parent modules
11
+ """
12
+ def __init__(self, qconfig=None):
13
+ super().__init__()
14
+ if qconfig:
15
+ self.qconfig = qconfig
16
+
17
+ def forward(self, x):
18
+ return x
19
+
20
+
21
+ class DeQuantStub(nn.Module):
22
+ r"""Dequantize stub module, before calibration, this is same as identity,
23
+ this will be swapped as `nnq.DeQuantize` in `convert`.
24
+
25
+ Args:
26
+ qconfig: quantization configuration for the tensor,
27
+ if qconfig is not provided, we will get qconfig from parent modules
28
+ """
29
+ def __init__(self, qconfig=None):
30
+ super().__init__()
31
+ if qconfig:
32
+ self.qconfig = qconfig
33
+
34
+ def forward(self, x):
35
+ return x
36
+
37
+
38
+ class QuantWrapper(nn.Module):
39
+ r"""A wrapper class that wraps the input module, adds QuantStub and
40
+ DeQuantStub and surround the call to module with call to quant and dequant
41
+ modules.
42
+
43
+ This is used by the `quantization` utility functions to add the quant and
44
+ dequant modules, before `convert` function `QuantStub` will just be observer,
45
+ it observes the input tensor, after `convert`, `QuantStub`
46
+ will be swapped to `nnq.Quantize` which does actual quantization. Similarly
47
+ for `DeQuantStub`.
48
+ """
49
+ quant: QuantStub
50
+ dequant: DeQuantStub
51
+ module: nn.Module
52
+
53
+ def __init__(self, module):
54
+ super().__init__()
55
+ qconfig = getattr(module, "qconfig", None)
56
+ self.add_module('quant', QuantStub(qconfig))
57
+ self.add_module('dequant', DeQuantStub(qconfig))
58
+ self.add_module('module', module)
59
+ self.train(module.training)
60
+
61
+ def forward(self, X):
62
+ X = self.quant(X)
63
+ X = self.module(X)
64
+ return self.dequant(X)
videollama2/lib/python3.10/site-packages/torch/ao/quantization/utils.py ADDED
@@ -0,0 +1,703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utils shared by different modes of quantization (eager/graph)
3
+ """
4
+ import functools
5
+ import warnings
6
+ from collections import OrderedDict
7
+ from inspect import getfullargspec, signature
8
+ from typing import Any, Callable, Dict, Optional, Tuple, Union
9
+
10
+ import torch
11
+ from torch.ao.quantization.quant_type import QuantType
12
+ from torch.fx import Node
13
+ from torch.nn.utils.parametrize import is_parametrized
14
+
15
+ NodePattern = Union[Tuple[Node, Node], Tuple[Node, Tuple[Node, Node]], Any]
16
+ NodePattern.__module__ = "torch.ao.quantization.utils"
17
+
18
+ # This is the Quantizer class instance from torch/quantization/fx/quantize.py.
19
+ # Define separately to prevent circular imports.
20
+ # TODO(future PR): improve this.
21
+ # make this public once fixed (can't be public as is because setting the module directly
22
+ # doesn't work)
23
+ QuantizerCls = Any
24
+
25
+ # Type for fusion patterns, it can be more complicated than the following actually,
26
+ # see pattern.md for docs
27
+ # TODO: not sure if typing supports recursive data types
28
+ Pattern = Union[
29
+ Callable, Tuple[Callable, Callable], Tuple[Callable, Tuple[Callable, Callable]], Any
30
+ ]
31
+ Pattern.__module__ = "torch.ao.quantization.utils"
32
+
33
+ # TODO: maybe rename this to MatchInputNode
34
+ class MatchAllNode:
35
+ """ A node pattern that matches all nodes, used in defining
36
+ fusion patterns in FX Graph Mode Quantization
37
+ """
38
+ pass
39
+
40
+ module_type_list = {
41
+ torch.nn.ReLU,
42
+ torch.nn.ReLU6,
43
+ torch.nn.AdaptiveAvgPool1d,
44
+ torch.nn.AdaptiveAvgPool2d,
45
+ torch.nn.AdaptiveAvgPool3d,
46
+ torch.nn.AvgPool1d,
47
+ torch.nn.AvgPool2d,
48
+ torch.nn.AvgPool3d,
49
+ torch.nn.MaxPool1d,
50
+ torch.nn.MaxPool2d,
51
+ torch.nn.MaxPool3d,
52
+ torch.nn.Identity,
53
+ torch.nn.Hardsigmoid,
54
+ torch.nn.Sigmoid,
55
+ torch.nn.Tanh,
56
+ }
57
+ func_list = {
58
+ torch.nn.functional.adaptive_avg_pool1d,
59
+ torch.nn.functional.adaptive_avg_pool2d,
60
+ torch.nn.functional.adaptive_avg_pool3d,
61
+ torch.nn.functional.elu,
62
+ torch.nn.functional.hardswish,
63
+ torch.nn.functional.instance_norm,
64
+ torch.nn.functional.layer_norm,
65
+ torch.nn.functional.leaky_relu,
66
+ torch.nn.functional.silu,
67
+ torch.nn.functional.mish,
68
+ torch.nn.functional.dropout,
69
+ torch.nn.functional.max_pool1d,
70
+ torch.nn.functional.max_pool2d,
71
+ torch.nn.functional.max_pool3d,
72
+ torch.nn.functional.relu,
73
+ torch.nn.functional.hardtanh,
74
+ torch.nn.functional.hardtanh_,
75
+ torch.nn.functional.hardsigmoid,
76
+ torch.nn.functional.sigmoid,
77
+ torch.transpose,
78
+ torch.repeat_interleave,
79
+ torch.sigmoid,
80
+ torch.squeeze,
81
+ torch.stack,
82
+ torch.sum,
83
+ torch.tanh,
84
+ torch.unsqueeze,
85
+ torch.cat,
86
+ }
87
+ method_list = {
88
+ torch.mean,
89
+ 'relu',
90
+ 'relu_',
91
+ 'contiguous',
92
+ 'detach',
93
+ 'detach_',
94
+ 'hardsigmoid',
95
+ 'hardsigmoid_',
96
+ 'permute',
97
+ 'repeat',
98
+ 'repeat_interleave',
99
+ 'reshape',
100
+ 'resize_',
101
+ 'shape',
102
+ 'sigmoid',
103
+ 'sigmoid_',
104
+ 'size',
105
+ 'squeeze',
106
+ 'squeeze_',
107
+ 'tanh',
108
+ 'tanh_',
109
+ 'transpose',
110
+ 'unsqueeze',
111
+ 'unsqueeze_',
112
+ 'view',
113
+ }
114
+
115
+ # TODO: not used now, remove
116
+ def check_node(node, modules):
117
+ # TODO: reuse is_fixed_qparam_node after we move this function to _lower_to_native_backend.py
118
+ is_call_function = node.op == "call_function" and node.target in func_list
119
+ is_call_method = node.op == "call_method" and node.target in method_list
120
+ is_call_module = node.op == "call_module" and type(modules[str(node.target)]) in module_type_list
121
+ return is_call_function, is_call_method, is_call_module
122
+
123
+ def get_combined_dict(default_dict, additional_dict):
124
+ d = default_dict.copy()
125
+ d.update(additional_dict)
126
+ return d
127
+
128
+ def is_per_tensor(qscheme):
129
+ return qscheme == torch.per_tensor_affine or \
130
+ qscheme == torch.per_tensor_symmetric
131
+
132
+ def is_per_channel(qscheme):
133
+ return qscheme in [torch.per_channel_affine,
134
+ torch.per_channel_affine_float_qparams,
135
+ torch.per_channel_symmetric]
136
+
137
+ def getattr_from_fqn(obj: Any, fqn: str) -> Any:
138
+ """
139
+ Given an obj and a fqn such as "foo.bar.baz", returns gm.foo.bar.baz.
140
+ """
141
+ return functools.reduce(getattr, fqn.split("."), obj)
142
+
143
+ def to_underlying_dtype(qdtype):
144
+ DTYPE_MAPPING = {
145
+ torch.quint8: torch.uint8,
146
+ torch.qint8: torch.int8,
147
+ torch.qint32: torch.int32,
148
+ torch.quint4x2: torch.uint8,
149
+ torch.quint2x4: torch.uint8,
150
+ torch.uint8: torch.uint8,
151
+ torch.int8: torch.int8,
152
+ torch.int16: torch.int16,
153
+ torch.int32: torch.int32,
154
+ }
155
+ assert qdtype in DTYPE_MAPPING, "Unsupported dtype: " + qdtype
156
+ return DTYPE_MAPPING[qdtype]
157
+
158
+ def get_qparam_dict(observer_or_fake_quant):
159
+ from torch.ao.quantization.observer import PlaceholderObserver
160
+
161
+ qscheme = getattr(observer_or_fake_quant, "qscheme", None)
162
+ dtype = observer_or_fake_quant.dtype
163
+ qparams = {"qscheme": qscheme, "dtype": dtype}
164
+
165
+ if not qscheme or isinstance(observer_or_fake_quant, PlaceholderObserver):
166
+ return {"qscheme": None, "dtype": dtype}
167
+
168
+ if is_per_tensor(qscheme):
169
+ qscheme = torch.per_tensor_affine
170
+ elif is_per_channel(qscheme):
171
+ # change symmetric to affine since we do not have symmetric
172
+ # quantized Tensor
173
+ if qscheme == torch.per_channel_symmetric:
174
+ qscheme = torch.per_channel_affine
175
+ qparams["axis"] = observer_or_fake_quant.ch_axis
176
+ else:
177
+ raise RuntimeError(f"Unrecognized qscheme: {qscheme}")
178
+ # update qscheme, since we don't have symmetric quant qscheme
179
+ # in quantized Tensor
180
+ qparams["qscheme"] = qscheme
181
+
182
+ scale, zero_point = observer_or_fake_quant.calculate_qparams()
183
+ qparams["scale"] = scale
184
+ qparams["zero_point"] = zero_point
185
+
186
+ if hasattr(observer_or_fake_quant, "quant_min"):
187
+ qparams["quant_min"] = observer_or_fake_quant.quant_min
188
+ if hasattr(observer_or_fake_quant, "quant_max"):
189
+ qparams["quant_max"] = observer_or_fake_quant.quant_max
190
+
191
+ return qparams
192
+
193
+
194
+ def get_swapped_custom_module_class(custom_module, custom_module_class_mapping, qconfig):
195
+ """ Get the observed/quantized custom module class that we need
196
+ to swap `custom_module` to
197
+ Input:
198
+ custom_module: input, can be an instance of either a float or observed custom module
199
+ custom_module_class_mapping: the float to observed or observed to quantized custom module class mapping
200
+ qconfig: qconfig configured for the custom module
201
+
202
+ Output:
203
+ corresponding observed/quantized custom module class for input custom module instance
204
+ """
205
+ quant_type = get_quant_type(qconfig)
206
+ class_mapping = custom_module_class_mapping.get(quant_type, {})
207
+ assert type(custom_module) in class_mapping, "did not find corresponding observed " \
208
+ f"module class for {type(custom_module)} in mapping: {class_mapping}"
209
+ return class_mapping[type(custom_module)]
210
+
211
+ def activation_dtype(qconfig):
212
+ assert qconfig is not None
213
+ activation = qconfig.activation()
214
+ return activation.dtype
215
+
216
+ def weight_dtype(qconfig):
217
+ assert qconfig is not None
218
+ weight = qconfig.weight()
219
+ return weight.dtype
220
+
221
+ def activation_is_statically_quantized(qconfig):
222
+ """ Given a qconfig, decide if the activation needs to be
223
+ quantized or not, this includes quantizing to quint8, qint8 and qint32 and float16
224
+ """
225
+ return (
226
+ activation_dtype(qconfig) in [
227
+ torch.quint8,
228
+ torch.qint8,
229
+ torch.qint32,
230
+ torch.float16,
231
+ torch.uint8,
232
+ torch.int8,
233
+ torch.int16,
234
+ torch.int32
235
+ ]
236
+ and (not activation_is_dynamically_quantized(qconfig))
237
+ )
238
+
239
+ def activation_is_dynamically_quantized(qconfig):
240
+ """ Given a qconfig, decide if the activation needs to be
241
+ dynamically quantized or not, this includes dynamically quantizing to
242
+ quint8, qint8 and float16
243
+ """
244
+ activation_dtype, _, activation_is_dynamic = \
245
+ get_qconfig_dtypes(qconfig)
246
+ return activation_is_dynamic
247
+
248
+ def activation_is_int8_quantized(qconfig):
249
+ """ Given a qconfig, decide if the activation needs to be
250
+ quantized to int8 or not, this includes quantizing to quint8, qint8
251
+ """
252
+ return activation_dtype(qconfig) in [torch.quint8, torch.qint8, torch.uint8, torch.int8]
253
+
254
+ def activation_is_int32_quantized(qconfig):
255
+ """ Given a qconfig, decide if the activation needs to be
256
+ quantized to int32 or not
257
+ """
258
+ return activation_dtype(qconfig) in [torch.qint32, torch.int32]
259
+
260
+ def weight_is_quantized(qconfig):
261
+ """ Given a qconfig, decide if the weight needs to be
262
+ quantized or not
263
+ """
264
+ return weight_dtype(qconfig) in [
265
+ torch.quint8,
266
+ torch.qint8,
267
+ torch.float16,
268
+ torch.quint4x2,
269
+ torch.uint8,
270
+ torch.int8,
271
+ torch.int16,
272
+ torch.int32
273
+ ]
274
+
275
+ def weight_is_statically_quantized(qconfig):
276
+ """ Given a qconfig, decide if the weight needs to be statically
277
+ quantized or not
278
+ """
279
+ return weight_dtype(qconfig) in [torch.quint8, torch.qint8, torch.uint8, torch.int8]
280
+
281
+ def op_is_int8_dynamically_quantized(qconfig) -> bool:
282
+ """ Given a qconfig, returns True if this op is using int8 dynamic
283
+ quantization
284
+ """
285
+ activation_dtype, weight_dtype, activation_is_dynamic = \
286
+ get_qconfig_dtypes(qconfig)
287
+ return (
288
+ activation_dtype in [torch.quint8, torch.uint8] and
289
+ # for now, the lines below assume fbgemm or qnnpack
290
+ weight_dtype in [torch.qint8, torch.int8] and
291
+ activation_is_dynamic
292
+ )
293
+
294
+ def get_qconfig_dtypes(qconfig):
295
+ r""" returns the qconfig tuple for qconfig:
296
+ (activation_dtype, weight_dtype, activation_is_dynamic)
297
+ """
298
+ assert qconfig is not None
299
+ activation = qconfig.activation()
300
+ weight = qconfig.weight()
301
+ act_is_dynamic = getattr(activation, "is_dynamic", False)
302
+ return (activation.dtype, weight.dtype, act_is_dynamic)
303
+
304
+ def get_quant_type(qconfig):
305
+ assert qconfig is not None
306
+ activation = qconfig.activation()
307
+ weight = qconfig.weight()
308
+ static_dtypes = [torch.quint8, torch.qint8, torch.quint4x2, torch.qint32, torch.uint8, torch.int8, torch.int16, torch.int32]
309
+ if weight.dtype in static_dtypes:
310
+ if hasattr(activation, 'is_dynamic') and activation.is_dynamic:
311
+ return QuantType.DYNAMIC
312
+ elif activation.dtype in static_dtypes:
313
+ return QuantType.STATIC
314
+ else:
315
+ return QuantType.WEIGHT_ONLY
316
+
317
+ if weight.dtype == torch.float16:
318
+ if hasattr(activation, 'is_dynamic') and activation.is_dynamic:
319
+ return QuantType.DYNAMIC
320
+ elif activation.dtype == torch.float16:
321
+ return QuantType.STATIC
322
+
323
+ raise Exception(f"Unrecognized dtype combination in get_quant_type: activation({activation.dtype}),"
324
+ f"weight({weight.dtype})")
325
+
326
+ def check_min_max_valid(min_val: torch.Tensor, max_val: torch.Tensor) -> bool:
327
+ """ Checks if the given minimum and maximum values are valid, meaning that
328
+ they exist and the min value is less than the max value.
329
+ """
330
+ if min_val.numel() == 0 or max_val.numel() == 0:
331
+ warnings.warn(
332
+ "must run observer before calling calculate_qparams. " +
333
+ "Returning default values."
334
+ )
335
+ return False
336
+
337
+ if min_val.dim() == 0 or max_val.dim() == 0:
338
+ if min_val == float("inf") and max_val == float("-inf"):
339
+ warnings.warn(
340
+ "must run observer before calling calculate_qparams. " +
341
+ "Returning default values."
342
+ )
343
+
344
+ return False
345
+
346
+ assert min_val <= max_val, f"min {min_val} should be less than max {max_val}"
347
+ else:
348
+ assert torch.all(
349
+ min_val <= max_val
350
+ ), f"min {min_val} should be less than max {max_val}"
351
+
352
+ return True
353
+
354
+
355
+ def calculate_qmin_qmax(quant_min: int, quant_max: int, has_customized_qrange: bool, dtype: torch.dtype,
356
+ reduce_range: bool) -> Tuple[int, int]:
357
+ r"""Calculates actual qmin and qmax based on the quantization range,
358
+ observer datatype and if range is reduced.
359
+ """
360
+ # TODO(jerryzh): Figure out why custom quant_min/quant_max are still adjusted.
361
+ if has_customized_qrange:
362
+ # This initialization here is to be resolve TorchScript compilation issues and allow
363
+ # using of refinement to decouple initial_qmin and initial_qmax from quantization range.
364
+ # The actual values of initial_qmin and initial_qmax will be reset below.
365
+ if dtype in [torch.qint32, torch.int32]:
366
+ initial_quant_min, initial_quant_max = 0, 2**32 - 1
367
+ else:
368
+ initial_quant_min, initial_quant_max = 0, 255
369
+ # The following assignment of self.qmin and self.qmax to the local variables and the if check refine the
370
+ # attribute from Optional valid integers for use, based on TorchScript's requirements.
371
+ custom_quant_min, custom_quant_max = quant_min, quant_max
372
+ if custom_quant_min is not None and custom_quant_max is not None:
373
+ initial_quant_min, initial_quant_max = (
374
+ custom_quant_min,
375
+ custom_quant_max,
376
+ )
377
+
378
+ qrange_len = initial_quant_max - initial_quant_min + 1
379
+ if dtype in [torch.qint8, torch.int8]:
380
+ assert (
381
+ 0 < qrange_len <= 256
382
+ ), "quantization range should be positive and not exceed the maximum bit range (=256)."
383
+ elif dtype in [torch.qint32, torch.int32]:
384
+ assert (
385
+ 0 < qrange_len <= 2**32
386
+ ), "quantization range should be positive and not exceed the maximum bit range (=4294967296)."
387
+ if reduce_range:
388
+ quant_min, quant_max = quant_min // 2, quant_max // 2
389
+ else:
390
+ # Fallback onto default 8-bit qmin and qmax calculation if dynamic range is not used.
391
+ if dtype in [torch.qint8, torch.int8]:
392
+ if reduce_range:
393
+ quant_min, quant_max = -64, 63
394
+ else:
395
+ quant_min, quant_max = -128, 127
396
+ elif dtype in [torch.quint8, torch.uint8]:
397
+ if reduce_range:
398
+ quant_min, quant_max = 0, 127
399
+ else:
400
+ quant_min, quant_max = 0, 255
401
+ elif dtype in [torch.qint32, torch.int32]:
402
+ quant_min, quant_max = -1 * (2 ** 31), (2 ** 31) - 1
403
+ else:
404
+ quant_min, quant_max = 0, 15
405
+ return quant_min, quant_max
406
+
407
+
408
+ def _parent_name(target):
409
+ """
410
+ Turn 'foo.bar' into ['foo', 'bar']
411
+ """
412
+ r = target.rsplit('.', 1)
413
+ if len(r) == 1:
414
+ return '', r[0]
415
+ else:
416
+ return r[0], r[1]
417
+
418
+ def has_no_children_ignoring_parametrizations(module):
419
+ """
420
+ Checks if module._modules is empty or
421
+ if module is a parametrization, checks that module._modules only has
422
+ the 'parametrizations' module
423
+ """
424
+ if len(module._modules) == 0:
425
+ return True
426
+ elif is_parametrized(module):
427
+ return len(module._modules) == 1 and 'parametrizations' in module._modules
428
+ else:
429
+ return False
430
+
431
+ def _get_path_of_module(root: torch.nn.Module, submodule: torch.nn.Module) -> Optional[str]:
432
+ """ Get the path (fully qualified name) of a submodule
433
+
434
+ Example::
435
+
436
+ >> class M(torch.nn.Module):
437
+ def __init__(self):
438
+ self.linear = torch.nn.Linear(5, 5)
439
+ def forward(self, x):
440
+ return self.linear(x)
441
+
442
+ >> m = M()
443
+ >> l = m.linear
444
+ >> _get_path_of_module(m, l)
445
+ "linear"
446
+ """
447
+ for n, p in root.named_modules():
448
+ if submodule is p:
449
+ return n
450
+ return None
451
+
452
+ def _get_signature_locals(f: Callable, loc: Dict[str, Any]) -> Dict[str, Any]:
453
+ """ Get local keyword arguments
454
+
455
+ Example::
456
+
457
+ >> def f(self, a, b=9):
458
+ pass
459
+ >> loc = {"a": 6, "c": 7}
460
+ >> _get_signature_locals(f, loc)
461
+ {"a": 6}
462
+ """
463
+ return {k: v for k, v in loc.items() if k in signature(f).parameters}
464
+
465
+ def _get_default_kwargs(f: Callable) -> "OrderedDict[str, Any]":
466
+ """ Get all default keyword arguments from function signature
467
+
468
+ Example::
469
+
470
+ >> def f(self, a, b=9):
471
+ pass
472
+ >> _get_default_kwargs(f)
473
+ {"b": 9}
474
+ """
475
+ kwargs = {}
476
+ for name, param in signature(f).parameters.items():
477
+ if param.default is not param.empty:
478
+ kwargs[name] = param.default
479
+ elif param.kind is param.VAR_POSITIONAL:
480
+ kwargs[name] = ()
481
+ elif param.kind is param.VAR_KEYWORD:
482
+ kwargs[name] = {}
483
+ return OrderedDict(kwargs)
484
+
485
+ def _normalize_kwargs(func: Callable, loc: Dict[str, Any]) -> "OrderedDict[str, Any]":
486
+ """ Given a function and local function arguments, normalize the keyword
487
+ arguments by filling in default arguments from function signature
488
+
489
+ Example::
490
+
491
+ >> def f(self, key1=3, key2=3):
492
+ pass
493
+ >> loc = {"key2": 6}
494
+ >> _normalize_kwargs(f, loc)
495
+ {"key1": 3, "key2": 6}
496
+ """
497
+ default_kwargs = _get_default_kwargs(func)
498
+ local_kwargs = _get_signature_locals(func, loc)
499
+ normalized_kwargs = default_kwargs.copy()
500
+ for attr, val in local_kwargs.items():
501
+ if attr in normalized_kwargs:
502
+ # override the default keyword arguments
503
+ normalized_kwargs[attr] = val
504
+ return normalized_kwargs
505
+
506
+ def validate_qmin_qmax(quant_min: int, quant_max: int) -> None:
507
+ r"""Validates that the user-specified quantization range is properly initialized
508
+ and within the given bound supported by the observer dtype.
509
+
510
+ To accommodate lower-bit quantization with respect to the existing torch.qint8 and
511
+ torch.quint8 datatypes, the user can choose to use dynamic quantization range by passing
512
+ in a tuple of initial qmin and qmax values. One use case is these customized qmin and qmax
513
+ values are used to calculate static estimates of the scale and zero point for aggressive lower-bit
514
+ fake quantization. These estimates are compared against parameters learned through backpropagation.
515
+ The related literatures for scale and zero point via backpropagation are as follows:
516
+
517
+ Learned Step Size Quantization: https://openreview.net/pdf?id=rkgO66VKDS
518
+ Trained Quantization Thresholds: https://arxiv.org/pdf/1903.08066.pdf
519
+ """
520
+ # The variable names are prefixed with "initial" because their values (qmin and qmax) might be adjusted
521
+ # based on whether quantization range is reduced and the datatype (signed/unsigned) used by the observer.
522
+ assert (
523
+ quant_min <= 0 <= quant_max
524
+ ), "Used-specified quantization range must include 0."
525
+ assert (
526
+ quant_min < quant_max
527
+ ), "qmin must be strictly less than qmax for user-specified quantization range."
528
+
529
+
530
+ # Functionally equivalent to '_calculate_qparams' in observer.py. Observers must be torchscriptable however and qscheme
531
+ # as far as I can tell is not allowed to passed as a parameter in torchscript functions. This makes refactoring observer
532
+ # to use this utility a massive pain and very gross. For now Im opting just to duplicate as this code seems unlikey to change
533
+ # (last update over 1 year ago) and when torchscript is fully deprecated we can refactor. TODO(jakeszwe, jerryzh168)
534
+ def determine_qparams(
535
+ min_val: torch.Tensor, max_val: torch.Tensor, quant_min: int, quant_max: int,
536
+ dtype: torch.dtype, eps: torch.Tensor, has_customized_qrange: bool,
537
+ qscheme: torch.qscheme = torch.per_tensor_affine) -> Tuple[torch.Tensor, torch.Tensor]:
538
+ r"""Calculates the quantization parameters, given min and max
539
+ value tensors. Works for both per tensor and per channel cases
540
+
541
+ Args:
542
+ min_val: Minimum values per channel
543
+ max_val: Maximum values per channel
544
+
545
+ Returns:
546
+ scales: Scales tensor of shape (#channels,)
547
+ zero_points: Zero points tensor of shape (#channels,)
548
+ """
549
+ if not check_min_max_valid(min_val, max_val):
550
+ return torch.tensor([1.0], device=min_val.device.type), torch.tensor([0], device=min_val.device.type)
551
+
552
+ min_val_neg = torch.min(min_val, torch.zeros_like(min_val))
553
+ max_val_pos = torch.max(max_val, torch.zeros_like(max_val))
554
+
555
+ device = min_val_neg.device
556
+ scale = torch.ones(min_val_neg.size(), dtype=torch.double, device=device)
557
+ zero_point = torch.zeros(min_val_neg.size(), dtype=torch.int64, device=device)
558
+
559
+ if (
560
+ qscheme == torch.per_tensor_symmetric
561
+ or qscheme == torch.per_channel_symmetric
562
+ ):
563
+ max_val_pos = torch.max(-min_val_neg, max_val_pos)
564
+ scale = max_val_pos / (float(quant_max - quant_min) / 2)
565
+ scale = torch.max(scale, eps)
566
+ if dtype in [torch.uint8, torch.quint8]:
567
+ if has_customized_qrange:
568
+ # When customized quantization range is used, down-rounded midpoint of the range is chosen.
569
+ zero_point = zero_point.new_full(
570
+ zero_point.size(), (quant_min + quant_max) // 2
571
+ )
572
+ else:
573
+ zero_point = zero_point.new_full(zero_point.size(), 128)
574
+ elif qscheme == torch.per_channel_affine_float_qparams:
575
+ scale = (max_val - min_val) / float(quant_max - quant_min)
576
+ scale = torch.where(scale > eps, scale, torch.ones_like(scale))
577
+ # We use the quantize function
578
+ # xq = Round(Xf * inv_scale + zero_point),
579
+ # setting zero_point to (-1 * min *inv_scale) we get
580
+ # Xq = Round((Xf - min) * inv_scale)
581
+ zero_point = -1 * min_val / scale
582
+ else:
583
+ scale = (max_val_pos - min_val_neg) / float(quant_max - quant_min)
584
+ scale = torch.max(scale, eps)
585
+ zero_point = quant_min - torch.round(min_val_neg / scale).to(torch.int)
586
+ zero_point = torch.clamp(zero_point, quant_min, quant_max)
587
+
588
+ # For scalar values, cast them to Tensors of size 1 to keep the shape
589
+ # consistent with default values in FakeQuantize.
590
+ if len(scale.shape) == 0:
591
+ # TODO: switch to scale.item() after adding JIT support
592
+ scale = torch.tensor([float(scale)], dtype=scale.dtype, device=device)
593
+ if len(zero_point.shape) == 0:
594
+ # TODO: switch to zero_point.item() after adding JIT support
595
+ zero_point = torch.tensor(
596
+ [int(zero_point)], dtype=zero_point.dtype, device=device
597
+ )
598
+ if qscheme == torch.per_channel_affine_float_qparams:
599
+ zero_point = torch.tensor(
600
+ [float(zero_point)], dtype=zero_point.dtype, device=device
601
+ )
602
+
603
+ return scale.to(torch.double), zero_point.to(torch.int64)
604
+
605
+ def _get_num_pos_args(f: Callable) -> int:
606
+ """ Get number of positional args for a function
607
+
608
+ Example::
609
+
610
+ >> def f(self, key1=3, key2=3):
611
+ pass
612
+ >> _get_num_pos_args(f)
613
+ 3
614
+ """
615
+ return len(getfullargspec(f).args)
616
+
617
+ def get_fqn_to_example_inputs(
618
+ model: torch.nn.Module,
619
+ example_inputs: Tuple[Any, ...]
620
+ ) -> Dict[str, Tuple[Any, ...]]:
621
+ """ Given a model and its example inputs, return a dictionary from
622
+ fully qualified name of submodules to example_inputs for that submodule,
623
+ e.g. {"linear1": (tensor1,), "linear2": (tensor2,), "sub": (tensor3,),
624
+ "sub.linear1": (tensor4,), ...}
625
+
626
+ Used to make quantizing submodules easier now that FX Graph Mode Quantization requires
627
+ example inputs.
628
+
629
+ Also works for keyword arguments with default values, we would flatten keyword
630
+ arguments as positional arguments and fill in the missing keyword args with default
631
+ values, e.g. if we have a forward function:
632
+ def forward(self, x, key1=3, key2=3):
633
+ ...
634
+
635
+ and we call it with self.submodule(x, key2=6)
636
+ we'll get example_inputs: (x, 3, 6)
637
+
638
+ user can also override `key1` with positional arguments as well:
639
+ for self.submodule(x, 5, key2=6)
640
+ we'll get: (x, 5, 6)
641
+
642
+ variable positional arguments and variable positional keyword arguments in forward
643
+ function are not supported currently, so please make sure no submodules is using
644
+ them.
645
+ """
646
+ root = model
647
+ fqn_to_example_inputs = {}
648
+
649
+ def _patched_module_call(self, *args, **kwargs):
650
+ submodule_example_inputs = list(args).copy()
651
+ normalized_kwargs = _normalize_kwargs(self.forward, kwargs)
652
+ # minus 1 to skipping counting `self`
653
+ num_args = _get_num_pos_args(self.forward) - 1
654
+ num_to_pop = num_args - len(submodule_example_inputs)
655
+ while num_to_pop and normalized_kwargs:
656
+ normalized_kwargs.popitem(last=False)
657
+ num_to_pop -= 1
658
+ submodule_example_inputs.extend(normalized_kwargs.values())
659
+ submodule_example_inputs_tuple = tuple(submodule_example_inputs)
660
+ fqn = _get_path_of_module(root, self)
661
+ if fqn is not None:
662
+ fqn_to_example_inputs[fqn] = submodule_example_inputs_tuple
663
+ return orig_module_call(self, *args, **kwargs)
664
+
665
+ orig_module_call = torch.nn.Module.__call__
666
+ torch.nn.Module.__call__ = _patched_module_call # type: ignore[method-assign]
667
+ try:
668
+ model(*example_inputs)
669
+ finally:
670
+ # restore the module call even if there is an exception
671
+ torch.nn.Module.__call__ = orig_module_call # type: ignore[method-assign]
672
+ return fqn_to_example_inputs
673
+
674
+ __all__ = [
675
+ "NodePattern",
676
+ "Pattern",
677
+ "MatchAllNode",
678
+ "check_node",
679
+ "get_combined_dict",
680
+ "is_per_tensor",
681
+ "is_per_channel",
682
+ "getattr_from_fqn",
683
+ "get_qparam_dict",
684
+ "get_swapped_custom_module_class",
685
+ "activation_dtype",
686
+ "weight_dtype",
687
+ "activation_is_statically_quantized",
688
+ "activation_is_dynamically_quantized",
689
+ "activation_is_int8_quantized",
690
+ "activation_is_int32_quantized",
691
+ "weight_is_quantized",
692
+ "weight_is_statically_quantized",
693
+ "op_is_int8_dynamically_quantized",
694
+ "get_qconfig_dtypes",
695
+ "get_quant_type",
696
+ "check_min_max_valid",
697
+ "calculate_qmin_qmax",
698
+ "has_no_children_ignoring_parametrizations",
699
+ "get_fqn_to_example_inputs",
700
+ "to_underlying_dtype",
701
+ "determine_qparams",
702
+ "validate_qmin_qmax",
703
+ ]
vllm/lib/python3.10/site-packages/textual/css/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/textual/css/errors.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from rich.console import Console, ConsoleOptions, RenderResult
4
+
5
+ from textual.css._help_renderables import HelpText
6
+ from textual.css.tokenizer import Token, TokenError
7
+
8
+
9
+ class DeclarationError(Exception):
10
+ def __init__(self, name: str, token: Token, message: str | HelpText) -> None:
11
+ self.name = name
12
+ self.token = token
13
+ self.message = message
14
+ super().__init__(str(message))
15
+
16
+
17
+ class StyleTypeError(TypeError):
18
+ pass
19
+
20
+
21
+ class UnresolvedVariableError(TokenError):
22
+ pass
23
+
24
+
25
+ class StyleValueError(ValueError):
26
+ """Raised when the value of a style property is not valid
27
+
28
+ Attributes:
29
+ help_text: Optional HelpText to be rendered when this
30
+ error is raised.
31
+ """
32
+
33
+ def __init__(self, *args: object, help_text: HelpText | None = None):
34
+ super().__init__(*args)
35
+ self.help_text: HelpText | None = help_text
36
+
37
+ def __rich_console__(
38
+ self, console: Console, options: ConsoleOptions
39
+ ) -> RenderResult:
40
+ from rich.traceback import Traceback
41
+
42
+ yield Traceback.from_exception(type(self), self, self.__traceback__)
43
+ if self.help_text is not None:
44
+ yield ""
45
+ yield self.help_text
46
+ yield ""
47
+
48
+
49
+ class StylesheetError(Exception):
50
+ pass
vllm/lib/python3.10/site-packages/textual/css/parse.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ from functools import lru_cache
5
+ from typing import Iterable, Iterator, NoReturn
6
+
7
+ from textual.css._help_renderables import HelpText
8
+ from textual.css._styles_builder import DeclarationError, StylesBuilder
9
+ from textual.css.errors import UnresolvedVariableError
10
+ from textual.css.model import (
11
+ CombinatorType,
12
+ Declaration,
13
+ RuleSet,
14
+ Selector,
15
+ SelectorSet,
16
+ SelectorType,
17
+ )
18
+ from textual.css.styles import Styles
19
+ from textual.css.tokenize import Token, tokenize, tokenize_declarations, tokenize_values
20
+ from textual.css.tokenizer import EOFError, ReferencedBy
21
+ from textual.css.types import CSSLocation, Specificity3
22
+ from textual.suggestions import get_suggestion
23
+
24
+ SELECTOR_MAP: dict[str, tuple[SelectorType, Specificity3]] = {
25
+ "selector": (SelectorType.TYPE, (0, 0, 1)),
26
+ "selector_start": (SelectorType.TYPE, (0, 0, 1)),
27
+ "selector_class": (SelectorType.CLASS, (0, 1, 0)),
28
+ "selector_start_class": (SelectorType.CLASS, (0, 1, 0)),
29
+ "selector_id": (SelectorType.ID, (1, 0, 0)),
30
+ "selector_start_id": (SelectorType.ID, (1, 0, 0)),
31
+ "selector_universal": (SelectorType.UNIVERSAL, (0, 0, 0)),
32
+ "selector_start_universal": (SelectorType.UNIVERSAL, (0, 0, 0)),
33
+ "nested": (SelectorType.NESTED, (0, 0, 0)),
34
+ }
35
+
36
+
37
+ def _add_specificity(
38
+ specificity1: Specificity3, specificity2: Specificity3
39
+ ) -> Specificity3:
40
+ """Add specificity tuples together.
41
+
42
+ Args:
43
+ specificity1: Specificity triple.
44
+ specificity2: Specificity triple.
45
+
46
+ Returns:
47
+ Combined specificity.
48
+ """
49
+
50
+ a1, b1, c1 = specificity1
51
+ a2, b2, c2 = specificity2
52
+ return (a1 + a2, b1 + b2, c1 + c2)
53
+
54
+
55
+ @lru_cache(maxsize=1024)
56
+ def parse_selectors(css_selectors: str) -> tuple[SelectorSet, ...]:
57
+ if not css_selectors.strip():
58
+ return ()
59
+ tokens = iter(tokenize(css_selectors, ("", "")))
60
+
61
+ get_selector = SELECTOR_MAP.get
62
+ combinator: CombinatorType | None = CombinatorType.DESCENDENT
63
+ selectors: list[Selector] = []
64
+ rule_selectors: list[list[Selector]] = []
65
+
66
+ while True:
67
+ try:
68
+ token = next(tokens, None)
69
+ except EOFError:
70
+ break
71
+ if token is None:
72
+ break
73
+ token_name = token.name
74
+
75
+ if token_name == "pseudo_class":
76
+ selectors[-1]._add_pseudo_class(token.value.lstrip(":"))
77
+ elif token_name == "whitespace":
78
+ if combinator is None or combinator == CombinatorType.SAME:
79
+ combinator = CombinatorType.DESCENDENT
80
+ elif token_name == "new_selector":
81
+ rule_selectors.append(selectors[:])
82
+ selectors.clear()
83
+ combinator = None
84
+ elif token_name == "declaration_set_start":
85
+ break
86
+ elif token_name == "combinator_child":
87
+ combinator = CombinatorType.CHILD
88
+ else:
89
+ _selector, specificity = get_selector(
90
+ token_name, (SelectorType.TYPE, (0, 0, 0))
91
+ )
92
+ selectors.append(
93
+ Selector(
94
+ name=token.value.lstrip(".#"),
95
+ combinator=combinator or CombinatorType.DESCENDENT,
96
+ type=_selector,
97
+ specificity=specificity,
98
+ )
99
+ )
100
+ combinator = CombinatorType.SAME
101
+ if selectors:
102
+ rule_selectors.append(selectors[:])
103
+
104
+ selector_set = tuple(SelectorSet.from_selectors(rule_selectors))
105
+ return selector_set
106
+
107
+
108
+ def parse_rule_set(
109
+ scope: str,
110
+ tokens: Iterator[Token],
111
+ token: Token,
112
+ is_default_rules: bool = False,
113
+ tie_breaker: int = 0,
114
+ ) -> Iterable[RuleSet]:
115
+ get_selector = SELECTOR_MAP.get
116
+ combinator: CombinatorType | None = CombinatorType.DESCENDENT
117
+ selectors: list[Selector] = []
118
+ rule_selectors: list[list[Selector]] = []
119
+ styles_builder = StylesBuilder()
120
+
121
+ while True:
122
+ if token.name == "pseudo_class":
123
+ selectors[-1]._add_pseudo_class(token.value.lstrip(":"))
124
+ elif token.name == "whitespace":
125
+ if combinator is None or combinator == CombinatorType.SAME:
126
+ combinator = CombinatorType.DESCENDENT
127
+ elif token.name == "new_selector":
128
+ rule_selectors.append(selectors[:])
129
+ selectors.clear()
130
+ combinator = None
131
+ elif token.name == "declaration_set_start":
132
+ break
133
+ elif token.name == "combinator_child":
134
+ combinator = CombinatorType.CHILD
135
+ else:
136
+ _selector, specificity = get_selector(
137
+ token.name, (SelectorType.TYPE, (0, 0, 0))
138
+ )
139
+ selectors.append(
140
+ Selector(
141
+ name=token.value.lstrip(".#"),
142
+ combinator=combinator or CombinatorType.DESCENDENT,
143
+ type=_selector,
144
+ specificity=specificity,
145
+ )
146
+ )
147
+ combinator = CombinatorType.SAME
148
+
149
+ token = next(tokens)
150
+
151
+ if selectors:
152
+ if scope and selectors[0].name != scope:
153
+ scope_selector, scope_specificity = get_selector(
154
+ scope, (SelectorType.TYPE, (0, 0, 0))
155
+ )
156
+ selectors.insert(
157
+ 0,
158
+ Selector(
159
+ name=scope,
160
+ combinator=CombinatorType.DESCENDENT,
161
+ type=scope_selector,
162
+ specificity=scope_specificity,
163
+ ),
164
+ )
165
+ rule_selectors.append(selectors[:])
166
+
167
+ declaration = Declaration(token, "")
168
+ errors: list[tuple[Token, str | HelpText]] = []
169
+ nested_rules: list[RuleSet] = []
170
+
171
+ while True:
172
+ token = next(tokens)
173
+ token_name = token.name
174
+ if token_name in ("whitespace", "declaration_end"):
175
+ continue
176
+ if token_name in {
177
+ "selector_start_id",
178
+ "selector_start_class",
179
+ "selector_start_universal",
180
+ "selector_start",
181
+ "nested",
182
+ }:
183
+ recursive_parse: list[RuleSet] = list(
184
+ parse_rule_set(
185
+ "",
186
+ tokens,
187
+ token,
188
+ is_default_rules=is_default_rules,
189
+ tie_breaker=tie_breaker,
190
+ )
191
+ )
192
+
193
+ def combine_selectors(
194
+ selectors1: list[Selector], selectors2: list[Selector]
195
+ ) -> list[Selector]:
196
+ """Combine lists of selectors together, processing any nesting.
197
+
198
+ Args:
199
+ selectors1: List of selectors.
200
+ selectors2: Second list of selectors.
201
+
202
+ Returns:
203
+ Combined selectors.
204
+ """
205
+ if selectors2 and selectors2[0].type == SelectorType.NESTED:
206
+ final_selector = selectors1[-1]
207
+ nested_selector = selectors2[0]
208
+ merged_selector = dataclasses.replace(
209
+ final_selector,
210
+ pseudo_classes=(
211
+ final_selector.pseudo_classes
212
+ | nested_selector.pseudo_classes
213
+ ),
214
+ specificity=_add_specificity(
215
+ final_selector.specificity, nested_selector.specificity
216
+ ),
217
+ )
218
+ return [*selectors1[:-1], merged_selector, *selectors2[1:]]
219
+ else:
220
+ return selectors1 + selectors2
221
+
222
+ for rule_selector in rule_selectors:
223
+ for rule_set in recursive_parse:
224
+ nested_rule_set = RuleSet(
225
+ [
226
+ SelectorSet(
227
+ combine_selectors(
228
+ rule_selector, recursive_selectors.selectors
229
+ )
230
+ )._total_specificity()
231
+ for recursive_selectors in rule_set.selector_set
232
+ ],
233
+ rule_set.styles,
234
+ rule_set.errors,
235
+ rule_set.is_default_rules,
236
+ rule_set.tie_breaker + tie_breaker,
237
+ )
238
+ nested_rules.append(nested_rule_set)
239
+ continue
240
+ if token_name == "declaration_name":
241
+ try:
242
+ styles_builder.add_declaration(declaration)
243
+ except DeclarationError as error:
244
+ errors.append((error.token, error.message))
245
+ declaration = Declaration(token, "")
246
+ declaration.name = token.value.rstrip(":")
247
+ elif token_name == "declaration_set_end":
248
+ break
249
+ else:
250
+ declaration.tokens.append(token)
251
+
252
+ try:
253
+ styles_builder.add_declaration(declaration)
254
+ except DeclarationError as error:
255
+ errors.append((error.token, error.message))
256
+
257
+ rule_set = RuleSet(
258
+ list(SelectorSet.from_selectors(rule_selectors)),
259
+ styles_builder.styles,
260
+ errors,
261
+ is_default_rules=is_default_rules,
262
+ tie_breaker=tie_breaker,
263
+ )
264
+
265
+ rule_set._post_parse()
266
+ yield rule_set
267
+
268
+ for nested_rule_set in nested_rules:
269
+ nested_rule_set._post_parse()
270
+ yield nested_rule_set
271
+
272
+
273
+ def parse_declarations(css: str, read_from: CSSLocation) -> Styles:
274
+ """Parse declarations and return a Styles object.
275
+
276
+ Args:
277
+ css: String containing CSS.
278
+ read_from: The location where the CSS was read from.
279
+
280
+ Returns:
281
+ A styles object.
282
+ """
283
+
284
+ tokens = iter(tokenize_declarations(css, read_from))
285
+ styles_builder = StylesBuilder()
286
+
287
+ declaration: Declaration | None = None
288
+ errors: list[tuple[Token, str | HelpText]] = []
289
+ while True:
290
+ token = next(tokens, None)
291
+ if token is None:
292
+ break
293
+ token_name = token.name
294
+ if token_name in ("whitespace", "declaration_end", "eof"):
295
+ continue
296
+ if token_name == "declaration_name":
297
+ if declaration:
298
+ try:
299
+ styles_builder.add_declaration(declaration)
300
+ except DeclarationError as error:
301
+ errors.append((error.token, error.message))
302
+ raise
303
+ declaration = Declaration(token, "")
304
+ declaration.name = token.value.rstrip(":")
305
+ elif token_name == "declaration_set_end":
306
+ break
307
+ else:
308
+ if declaration:
309
+ declaration.tokens.append(token)
310
+
311
+ if declaration:
312
+ try:
313
+ styles_builder.add_declaration(declaration)
314
+ except DeclarationError as error:
315
+ errors.append((error.token, error.message))
316
+ raise
317
+
318
+ return styles_builder.styles
319
+
320
+
321
+ def _unresolved(variable_name: str, variables: Iterable[str], token: Token) -> NoReturn:
322
+ """Raise a TokenError regarding an unresolved variable.
323
+
324
+ Args:
325
+ variable_name: A variable name.
326
+ variables: Possible choices used to generate suggestion.
327
+ token: The Token.
328
+
329
+ Raises:
330
+ UnresolvedVariableError: Always raises a TokenError.
331
+ """
332
+ message = f"reference to undefined variable '${variable_name}'"
333
+ suggested_variable = get_suggestion(variable_name, list(variables))
334
+ if suggested_variable:
335
+ message += f"; did you mean '${suggested_variable}'?"
336
+
337
+ raise UnresolvedVariableError(
338
+ token.read_from,
339
+ token.code,
340
+ token.start,
341
+ message,
342
+ end=token.end,
343
+ )
344
+
345
+
346
+ def substitute_references(
347
+ tokens: Iterable[Token], css_variables: dict[str, list[Token]] | None = None
348
+ ) -> Iterable[Token]:
349
+ """Replace variable references with values by substituting variable reference
350
+ tokens with the tokens representing their values.
351
+
352
+ Args:
353
+ tokens: Iterator of Tokens which may contain tokens
354
+ with the name "variable_ref".
355
+
356
+ Returns:
357
+ Yields Tokens such that any variable references (tokens where
358
+ token.name == "variable_ref") have been replaced with the tokens representing
359
+ the value. In other words, an Iterable of Tokens similar to the original input,
360
+ but with variables resolved. Substituted tokens will have their referenced_by
361
+ attribute populated with information about where the tokens are being substituted to.
362
+ """
363
+ variables: dict[str, list[Token]] = css_variables.copy() if css_variables else {}
364
+ iter_tokens = iter(tokens)
365
+
366
+ while True:
367
+ token = next(iter_tokens, None)
368
+ if token is None:
369
+ break
370
+ if token.name == "variable_name":
371
+ variable_name = token.value[1:-1] # Trim the $ and the :, i.e. "$x:" -> "x"
372
+ variable_tokens = variables.setdefault(variable_name, [])
373
+ yield token
374
+
375
+ while True:
376
+ token = next(iter_tokens, None)
377
+ if token is not None and token.name == "whitespace":
378
+ yield token
379
+ else:
380
+ break
381
+
382
+ # Store the tokens for any variable definitions, and substitute
383
+ # any variable references we encounter with them.
384
+ while True:
385
+ if not token:
386
+ break
387
+ elif token.name == "whitespace":
388
+ variable_tokens.append(token)
389
+ yield token
390
+ elif token.name == "variable_value_end":
391
+ yield token
392
+ break
393
+ # For variables referring to other variables
394
+ elif token.name == "variable_ref":
395
+ ref_name = token.value[1:]
396
+ if ref_name in variables:
397
+ reference_tokens = variables[ref_name]
398
+ variable_tokens.extend(reference_tokens)
399
+ ref_location = token.location
400
+ ref_length = len(token.value)
401
+ for _token in reference_tokens:
402
+ yield _token.with_reference(
403
+ ReferencedBy(
404
+ ref_name, ref_location, ref_length, token.code
405
+ )
406
+ )
407
+ else:
408
+ _unresolved(ref_name, variables.keys(), token)
409
+ else:
410
+ variable_tokens.append(token)
411
+ yield token
412
+ token = next(iter_tokens, None)
413
+ elif token.name == "variable_ref":
414
+ variable_name = token.value[1:] # Trim the $, so $x -> x
415
+ if variable_name in variables:
416
+ variable_tokens = variables[variable_name]
417
+ ref_location = token.location
418
+ ref_length = len(token.value)
419
+ ref_code = token.code
420
+ for _token in variable_tokens:
421
+ yield _token.with_reference(
422
+ ReferencedBy(variable_name, ref_location, ref_length, ref_code)
423
+ )
424
+ else:
425
+ _unresolved(variable_name, variables.keys(), token)
426
+ else:
427
+ yield token
428
+
429
+
430
+ def parse(
431
+ scope: str,
432
+ css: str,
433
+ read_from: CSSLocation,
434
+ variables: dict[str, str] | None = None,
435
+ variable_tokens: dict[str, list[Token]] | None = None,
436
+ is_default_rules: bool = False,
437
+ tie_breaker: int = 0,
438
+ ) -> Iterable[RuleSet]:
439
+ """Parse CSS by tokenizing it, performing variable substitution,
440
+ and generating rule sets from it.
441
+
442
+ Args:
443
+ scope: CSS type name.
444
+ css: The input CSS.
445
+ read_from: The source location of the CSS.
446
+ variables: Substitution variables to substitute tokens for.
447
+ is_default_rules: True if the rules we're extracting are
448
+ default (i.e. in Widget.DEFAULT_CSS) rules. False if they're from user defined CSS.
449
+ """
450
+ reference_tokens = tokenize_values(variables) if variables is not None else {}
451
+ if variable_tokens:
452
+ reference_tokens.update(variable_tokens)
453
+
454
+ tokens = iter(substitute_references(tokenize(css, read_from), variable_tokens))
455
+ while True:
456
+ token = next(tokens, None)
457
+ if token is None:
458
+ break
459
+ if token.name.startswith("selector_start"):
460
+ yield from parse_rule_set(
461
+ scope,
462
+ tokens,
463
+ token,
464
+ is_default_rules=is_default_rules,
465
+ tie_breaker=tie_breaker,
466
+ )
vllm/lib/python3.10/site-packages/textual/css/styles.py ADDED
@@ -0,0 +1,1423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from functools import partial
5
+ from operator import attrgetter
6
+ from typing import TYPE_CHECKING, Any, Callable, Iterable, Literal, cast
7
+
8
+ import rich.repr
9
+ from rich.style import Style
10
+ from typing_extensions import TypedDict
11
+
12
+ from textual._animator import DEFAULT_EASING, Animatable, BoundAnimator, EasingFunction
13
+ from textual._types import AnimationLevel, CallbackType
14
+ from textual.color import Color
15
+ from textual.css._style_properties import (
16
+ AlignProperty,
17
+ BooleanProperty,
18
+ BorderProperty,
19
+ BoxProperty,
20
+ ColorProperty,
21
+ DockProperty,
22
+ FractionalProperty,
23
+ HatchProperty,
24
+ IntegerProperty,
25
+ KeylineProperty,
26
+ LayoutProperty,
27
+ NameListProperty,
28
+ NameProperty,
29
+ OffsetProperty,
30
+ OverflowProperty,
31
+ ScalarListProperty,
32
+ ScalarProperty,
33
+ ScrollbarColorProperty,
34
+ SpacingProperty,
35
+ SplitProperty,
36
+ StringEnumProperty,
37
+ StyleFlagsProperty,
38
+ TransitionsProperty,
39
+ )
40
+ from textual.css.constants import (
41
+ VALID_ALIGN_HORIZONTAL,
42
+ VALID_ALIGN_VERTICAL,
43
+ VALID_BOX_SIZING,
44
+ VALID_CONSTRAIN,
45
+ VALID_DISPLAY,
46
+ VALID_OVERFLOW,
47
+ VALID_OVERLAY,
48
+ VALID_POSITION,
49
+ VALID_SCROLLBAR_GUTTER,
50
+ VALID_TEXT_ALIGN,
51
+ VALID_VISIBILITY,
52
+ )
53
+ from textual.css.scalar import Scalar, ScalarOffset, Unit
54
+ from textual.css.scalar_animation import ScalarAnimation
55
+ from textual.css.transition import Transition
56
+ from textual.css.types import (
57
+ AlignHorizontal,
58
+ AlignVertical,
59
+ BoxSizing,
60
+ Constrain,
61
+ Display,
62
+ Overflow,
63
+ Overlay,
64
+ ScrollbarGutter,
65
+ Specificity3,
66
+ Specificity6,
67
+ TextAlign,
68
+ Visibility,
69
+ )
70
+ from textual.geometry import Offset, Spacing
71
+
72
+ if TYPE_CHECKING:
73
+ from textual.css.types import CSSLocation
74
+ from textual.dom import DOMNode
75
+ from textual.layout import Layout
76
+
77
+
78
+ class RulesMap(TypedDict, total=False):
79
+ """A typed dict for CSS rules.
80
+
81
+ Any key may be absent, indicating that rule has not been set.
82
+
83
+ Does not define composite rules, that is a rule that is made of a combination of other rules.
84
+ """
85
+
86
+ display: Display
87
+ visibility: Visibility
88
+ layout: "Layout"
89
+
90
+ auto_color: bool
91
+ color: Color
92
+ background: Color
93
+ text_style: Style
94
+
95
+ background_tint: Color
96
+
97
+ opacity: float
98
+ text_opacity: float
99
+
100
+ padding: Spacing
101
+ margin: Spacing
102
+ offset: ScalarOffset
103
+ position: str
104
+
105
+ border_top: tuple[str, Color]
106
+ border_right: tuple[str, Color]
107
+ border_bottom: tuple[str, Color]
108
+ border_left: tuple[str, Color]
109
+
110
+ border_title_align: AlignHorizontal
111
+ border_subtitle_align: AlignHorizontal
112
+
113
+ outline_top: tuple[str, Color]
114
+ outline_right: tuple[str, Color]
115
+ outline_bottom: tuple[str, Color]
116
+ outline_left: tuple[str, Color]
117
+
118
+ keyline: tuple[str, Color]
119
+
120
+ box_sizing: BoxSizing
121
+ width: Scalar
122
+ height: Scalar
123
+ min_width: Scalar
124
+ min_height: Scalar
125
+ max_width: Scalar
126
+ max_height: Scalar
127
+
128
+ dock: str
129
+ split: str
130
+
131
+ overflow_x: Overflow
132
+ overflow_y: Overflow
133
+
134
+ layers: tuple[str, ...]
135
+ layer: str
136
+
137
+ transitions: dict[str, Transition]
138
+
139
+ tint: Color
140
+
141
+ scrollbar_color: Color
142
+ scrollbar_color_hover: Color
143
+ scrollbar_color_active: Color
144
+
145
+ scrollbar_corner_color: Color
146
+
147
+ scrollbar_background: Color
148
+ scrollbar_background_hover: Color
149
+ scrollbar_background_active: Color
150
+
151
+ scrollbar_gutter: ScrollbarGutter
152
+
153
+ scrollbar_size_vertical: int
154
+ scrollbar_size_horizontal: int
155
+
156
+ align_horizontal: AlignHorizontal
157
+ align_vertical: AlignVertical
158
+
159
+ content_align_horizontal: AlignHorizontal
160
+ content_align_vertical: AlignVertical
161
+
162
+ grid_size_rows: int
163
+ grid_size_columns: int
164
+ grid_gutter_horizontal: int
165
+ grid_gutter_vertical: int
166
+ grid_rows: tuple[Scalar, ...]
167
+ grid_columns: tuple[Scalar, ...]
168
+
169
+ row_span: int
170
+ column_span: int
171
+
172
+ text_align: TextAlign
173
+
174
+ link_color: Color
175
+ auto_link_color: bool
176
+ link_background: Color
177
+ link_style: Style
178
+
179
+ link_color_hover: Color
180
+ auto_link_color_hover: bool
181
+ link_background_hover: Color
182
+ link_style_hover: Style
183
+
184
+ auto_border_title_color: bool
185
+ border_title_color: Color
186
+ border_title_background: Color
187
+ border_title_style: Style
188
+
189
+ auto_border_subtitle_color: bool
190
+ border_subtitle_color: Color
191
+ border_subtitle_background: Color
192
+ border_subtitle_style: Style
193
+
194
+ hatch: tuple[str, Color] | Literal["none"]
195
+
196
+ overlay: Overlay
197
+ constrain_x: Constrain
198
+ constrain_y: Constrain
199
+
200
+
201
+ RULE_NAMES = list(RulesMap.__annotations__.keys())
202
+ RULE_NAMES_SET = frozenset(RULE_NAMES)
203
+ _rule_getter = attrgetter(*RULE_NAMES)
204
+
205
+
206
+ class StylesBase:
207
+ """A common base class for Styles and RenderStyles"""
208
+
209
+ ANIMATABLE = {
210
+ "offset",
211
+ "padding",
212
+ "margin",
213
+ "width",
214
+ "height",
215
+ "min_width",
216
+ "min_height",
217
+ "max_width",
218
+ "max_height",
219
+ "auto_color",
220
+ "color",
221
+ "background",
222
+ "background_tint",
223
+ "opacity",
224
+ "position",
225
+ "text_opacity",
226
+ "tint",
227
+ "scrollbar_color",
228
+ "scrollbar_color_hover",
229
+ "scrollbar_color_active",
230
+ "scrollbar_background",
231
+ "scrollbar_background_hover",
232
+ "scrollbar_background_active",
233
+ "link_color",
234
+ "link_background",
235
+ "link_color_hover",
236
+ "link_background_hover",
237
+ }
238
+
239
+ node: DOMNode | None = None
240
+
241
+ display = StringEnumProperty(VALID_DISPLAY, "block", layout=True)
242
+ """Set the display of the widget, defining how it's rendered.
243
+
244
+ Valid values are "block" or "none".
245
+
246
+ "none" will hide and allow other widgets to fill the space that this widget would occupy.
247
+
248
+ Set to None to clear any value that was set at runtime.
249
+
250
+ Raises:
251
+ StyleValueError: If an invalid display is specified.
252
+ """
253
+
254
+ visibility = StringEnumProperty(VALID_VISIBILITY, "visible", layout=True)
255
+ """Set the visibility of the widget.
256
+
257
+ Valid values are "visible" or "hidden".
258
+
259
+ "hidden" will hide the widget, but reserve the space for this widget.
260
+ If you want to hide the widget and allow another widget to fill the space,
261
+ set the display attribute to "none" instead.
262
+
263
+ Set to None to clear any value that was set at runtime.
264
+
265
+ Raises:
266
+ StyleValueError: If an invalid visibility is specified.
267
+ """
268
+
269
+ layout = LayoutProperty()
270
+ """Set the layout of the widget, defining how it's children are laid out.
271
+
272
+ Valid values are "grid", "horizontal", and "vertical" or None to clear any layout
273
+ that was set at runtime.
274
+
275
+ Raises:
276
+ MissingLayout: If an invalid layout is specified.
277
+ """
278
+
279
+ auto_color = BooleanProperty(default=False)
280
+ """Enable automatic picking of best contrasting color."""
281
+ color = ColorProperty(Color(255, 255, 255))
282
+ """Set the foreground (text) color of the widget.
283
+ Supports `Color` objects but also strings e.g. "red" or "#ff0000".
284
+ You can also specify an opacity after a color e.g. "blue 10%"
285
+ """
286
+ background = ColorProperty(Color(0, 0, 0, 0))
287
+ """Set the background color of the widget.
288
+ Supports `Color` objects but also strings e.g. "red" or "#ff0000"
289
+ You can also specify an opacity after a color e.g. "blue 10%"
290
+ """
291
+ background_tint = ColorProperty(Color(0, 0, 0, 0))
292
+ """Set a color to tint (blend) with the background.
293
+ Supports `Color` objects but also strings e.g. "red" or "#ff0000"
294
+ You can also specify an opacity after a color e.g. "blue 10%"
295
+ """
296
+ text_style = StyleFlagsProperty()
297
+ """Set the text style of the widget using Rich StyleFlags.
298
+ e.g. `"bold underline"` or `"b u strikethrough"`.
299
+ """
300
+ opacity = FractionalProperty(children=True)
301
+ """Set the opacity of the widget, defining how it blends with the parent."""
302
+ text_opacity = FractionalProperty()
303
+ """Set the opacity of the content within the widget against the widget's background."""
304
+ padding = SpacingProperty()
305
+ """Set the padding (spacing between border and content) of the widget."""
306
+ margin = SpacingProperty()
307
+ """Set the margin (spacing outside the border) of the widget."""
308
+ offset = OffsetProperty()
309
+ """Set the offset of the widget relative to where it would have been otherwise."""
310
+ position = StringEnumProperty(VALID_POSITION, "relative")
311
+ """If `relative` offset is applied to widgets current position, if `absolute` it is applied to (0, 0)."""
312
+
313
+ border = BorderProperty(layout=True)
314
+ """Set the border of the widget e.g. ("rounded", "green") or "none"."""
315
+
316
+ border_top = BoxProperty(Color(0, 255, 0))
317
+ """Set the top border of the widget e.g. ("rounded", "green") or "none"."""
318
+ border_right = BoxProperty(Color(0, 255, 0))
319
+ """Set the right border of the widget e.g. ("rounded", "green") or "none"."""
320
+ border_bottom = BoxProperty(Color(0, 255, 0))
321
+ """Set the bottom border of the widget e.g. ("rounded", "green") or "none"."""
322
+ border_left = BoxProperty(Color(0, 255, 0))
323
+ """Set the left border of the widget e.g. ("rounded", "green") or "none"."""
324
+
325
+ border_title_align = StringEnumProperty(VALID_ALIGN_HORIZONTAL, "left")
326
+ """The alignment of the border title text."""
327
+ border_subtitle_align = StringEnumProperty(VALID_ALIGN_HORIZONTAL, "right")
328
+ """The alignment of the border subtitle text."""
329
+
330
+ outline = BorderProperty(layout=False)
331
+ """Set the outline of the widget e.g. ("rounded", "green") or "none".
332
+ The outline is drawn *on top* of the widget, rather than around it like border.
333
+ """
334
+ outline_top = BoxProperty(Color(0, 255, 0))
335
+ """Set the top outline of the widget e.g. ("rounded", "green") or "none"."""
336
+ outline_right = BoxProperty(Color(0, 255, 0))
337
+ """Set the right outline of the widget e.g. ("rounded", "green") or "none"."""
338
+ outline_bottom = BoxProperty(Color(0, 255, 0))
339
+ """Set the bottom outline of the widget e.g. ("rounded", "green") or "none"."""
340
+ outline_left = BoxProperty(Color(0, 255, 0))
341
+ """Set the left outline of the widget e.g. ("rounded", "green") or "none"."""
342
+
343
+ keyline = KeylineProperty()
344
+ """Keyline parameters."""
345
+
346
+ box_sizing = StringEnumProperty(VALID_BOX_SIZING, "border-box", layout=True)
347
+ """Box sizing method ("border-box" or "conetnt-box")"""
348
+ width = ScalarProperty(percent_unit=Unit.WIDTH)
349
+ """Set the width of the widget."""
350
+ height = ScalarProperty(percent_unit=Unit.HEIGHT)
351
+ """Set the height of the widget."""
352
+ min_width = ScalarProperty(percent_unit=Unit.WIDTH, allow_auto=False)
353
+ """Set the minimum width of the widget."""
354
+ min_height = ScalarProperty(percent_unit=Unit.HEIGHT, allow_auto=False)
355
+ """Set the minimum height of the widget."""
356
+ max_width = ScalarProperty(percent_unit=Unit.WIDTH, allow_auto=False)
357
+ """Set the maximum width of the widget."""
358
+ max_height = ScalarProperty(percent_unit=Unit.HEIGHT, allow_auto=False)
359
+ """Set the maximum height of the widget."""
360
+ dock = DockProperty()
361
+ """Set which edge of the parent to dock this widget to e.g. "top", "left", "right", "bottom", "none".
362
+ """
363
+ split = SplitProperty()
364
+
365
+ overflow_x = OverflowProperty(VALID_OVERFLOW, "hidden")
366
+ """Control what happens when the content extends horizontally beyond the widget's width.
367
+
368
+ Valid values are "scroll", "hidden", or "auto".
369
+ """
370
+
371
+ overflow_y = OverflowProperty(VALID_OVERFLOW, "hidden")
372
+ """Control what happens when the content extends vertically beyond the widget's height.
373
+
374
+ Valid values are "scroll", "hidden", or "auto".
375
+ """
376
+
377
+ layer = NameProperty()
378
+ layers = NameListProperty()
379
+ transitions = TransitionsProperty()
380
+
381
+ tint = ColorProperty("transparent")
382
+ """Set the tint of the widget. This allows you apply a opaque color above the widget.
383
+
384
+ You can specify an opacity after a color e.g. "blue 10%"
385
+ """
386
+ scrollbar_color = ScrollbarColorProperty("ansi_bright_magenta")
387
+ """Set the color of the handle of the scrollbar."""
388
+ scrollbar_color_hover = ScrollbarColorProperty("ansi_yellow")
389
+ """Set the color of the handle of the scrollbar when hovered."""
390
+ scrollbar_color_active = ScrollbarColorProperty("ansi_bright_yellow")
391
+ """Set the color of the handle of the scrollbar when active (being dragged)."""
392
+ scrollbar_corner_color = ScrollbarColorProperty("#666666")
393
+ """Set the color of the space between the horizontal and vertical scrollbars."""
394
+ scrollbar_background = ScrollbarColorProperty("#555555")
395
+ """Set the background color of the scrollbar (the track that the handle sits on)."""
396
+ scrollbar_background_hover = ScrollbarColorProperty("#444444")
397
+ """Set the background color of the scrollbar when hovered."""
398
+ scrollbar_background_active = ScrollbarColorProperty("black")
399
+ """Set the background color of the scrollbar when active (being dragged)."""
400
+
401
+ scrollbar_gutter = StringEnumProperty(
402
+ VALID_SCROLLBAR_GUTTER, "auto", layout=True, refresh_children=True
403
+ )
404
+ """Set to "stable" to reserve space for the scrollbar even when it's not visible.
405
+ This can prevent content from shifting when a scrollbar appears.
406
+ """
407
+
408
+ scrollbar_size_vertical = IntegerProperty(default=2, layout=True)
409
+ """Set the width of the vertical scrollbar (measured in cells)."""
410
+ scrollbar_size_horizontal = IntegerProperty(default=1, layout=True)
411
+ """Set the height of the horizontal scrollbar (measured in cells)."""
412
+
413
+ align_horizontal = StringEnumProperty(
414
+ VALID_ALIGN_HORIZONTAL, "left", layout=True, refresh_children=True
415
+ )
416
+ align_vertical = StringEnumProperty(
417
+ VALID_ALIGN_VERTICAL, "top", layout=True, refresh_children=True
418
+ )
419
+ align = AlignProperty()
420
+
421
+ content_align_horizontal = StringEnumProperty(VALID_ALIGN_HORIZONTAL, "left")
422
+ content_align_vertical = StringEnumProperty(VALID_ALIGN_VERTICAL, "top")
423
+ content_align = AlignProperty()
424
+
425
+ grid_rows = ScalarListProperty(percent_unit=Unit.HEIGHT, refresh_children=True)
426
+ grid_columns = ScalarListProperty(percent_unit=Unit.WIDTH, refresh_children=True)
427
+
428
+ grid_size_columns = IntegerProperty(default=1, layout=True, refresh_children=True)
429
+ grid_size_rows = IntegerProperty(default=0, layout=True, refresh_children=True)
430
+ grid_gutter_horizontal = IntegerProperty(
431
+ default=0, layout=True, refresh_children=True
432
+ )
433
+ grid_gutter_vertical = IntegerProperty(
434
+ default=0, layout=True, refresh_children=True
435
+ )
436
+
437
+ row_span = IntegerProperty(default=1, layout=True)
438
+ column_span = IntegerProperty(default=1, layout=True)
439
+
440
+ text_align = StringEnumProperty(VALID_TEXT_ALIGN, "start")
441
+
442
+ link_color = ColorProperty("transparent")
443
+ auto_link_color = BooleanProperty(False)
444
+ link_background = ColorProperty("transparent")
445
+ link_style = StyleFlagsProperty()
446
+
447
+ link_color_hover = ColorProperty("transparent")
448
+ auto_link_color_hover = BooleanProperty(False)
449
+ link_background_hover = ColorProperty("transparent")
450
+ link_style_hover = StyleFlagsProperty()
451
+
452
+ auto_border_title_color = BooleanProperty(default=False)
453
+ border_title_color = ColorProperty(Color(255, 255, 255, 0))
454
+ border_title_background = ColorProperty(Color(0, 0, 0, 0))
455
+ border_title_style = StyleFlagsProperty()
456
+
457
+ auto_border_subtitle_color = BooleanProperty(default=False)
458
+ border_subtitle_color = ColorProperty(Color(255, 255, 255, 0))
459
+ border_subtitle_background = ColorProperty(Color(0, 0, 0, 0))
460
+ border_subtitle_style = StyleFlagsProperty()
461
+
462
+ hatch = HatchProperty()
463
+ """Add a hatched background effect e.g. ("right", "yellow") or "none" to use no hatch.
464
+ """
465
+
466
+ overlay = StringEnumProperty(
467
+ VALID_OVERLAY, "none", layout=True, refresh_parent=True
468
+ )
469
+ constrain_x: StringEnumProperty[Constrain] = StringEnumProperty(
470
+ VALID_CONSTRAIN, "none"
471
+ )
472
+ constrain_y: StringEnumProperty[Constrain] = StringEnumProperty(
473
+ VALID_CONSTRAIN, "none"
474
+ )
475
+
476
+ def __textual_animation__(
477
+ self,
478
+ attribute: str,
479
+ start_value: object,
480
+ value: object,
481
+ start_time: float,
482
+ duration: float | None,
483
+ speed: float | None,
484
+ easing: EasingFunction,
485
+ on_complete: CallbackType | None = None,
486
+ level: AnimationLevel = "full",
487
+ ) -> ScalarAnimation | None:
488
+ if self.node is None:
489
+ return None
490
+
491
+ # Check we are animating a Scalar or Scalar offset
492
+ if isinstance(start_value, (Scalar, ScalarOffset)):
493
+ # If destination is a number, we can convert that to a scalar
494
+ if isinstance(value, (int, float)):
495
+ value = Scalar(value, Unit.CELLS, Unit.CELLS)
496
+
497
+ # We can only animate to Scalar
498
+ if not isinstance(value, (Scalar, ScalarOffset)):
499
+ return None
500
+
501
+ from textual.widget import Widget
502
+
503
+ assert isinstance(self.node, Widget)
504
+ return ScalarAnimation(
505
+ self.node,
506
+ self,
507
+ start_time,
508
+ attribute,
509
+ value,
510
+ duration=duration,
511
+ speed=speed,
512
+ easing=easing,
513
+ on_complete=(
514
+ partial(self.node.app.call_later, on_complete)
515
+ if on_complete is not None
516
+ else None
517
+ ),
518
+ level=level,
519
+ )
520
+ return None
521
+
522
+ def __eq__(self, styles: object) -> bool:
523
+ """Check that Styles contains the same rules."""
524
+ if not isinstance(styles, StylesBase):
525
+ return NotImplemented
526
+ return self.get_rules() == styles.get_rules()
527
+
528
+ @property
529
+ def gutter(self) -> Spacing:
530
+ """Get space around widget.
531
+
532
+ Returns:
533
+ Space around widget content.
534
+ """
535
+ return self.padding + self.border.spacing
536
+
537
+ @property
538
+ def auto_dimensions(self) -> bool:
539
+ """Check if width or height are set to 'auto'."""
540
+ has_rule = self.has_rule
541
+ return (has_rule("width") and self.width.is_auto) or ( # type: ignore
542
+ has_rule("height") and self.height.is_auto # type: ignore
543
+ )
544
+
545
+ @property
546
+ def is_relative_width(self) -> bool:
547
+ """Does the node have a relative width?"""
548
+ width = self.width
549
+ return width is not None and width.unit in (Unit.FRACTION, Unit.PERCENT)
550
+
551
+ @property
552
+ def is_relative_height(self) -> bool:
553
+ """Does the node have a relative width?"""
554
+ height = self.height
555
+ return height is not None and height.unit in (Unit.FRACTION, Unit.PERCENT)
556
+
557
+ @property
558
+ def is_auto_width(self) -> bool:
559
+ """Does the node have automatic width?"""
560
+ width = self.width
561
+ return width is not None and width.unit == Unit.AUTO
562
+
563
+ @property
564
+ def is_auto_height(self) -> bool:
565
+ """Does the node have automatic height?"""
566
+ height = self.height
567
+ return height is not None and height.unit == Unit.AUTO
568
+
569
+ @property
570
+ def is_docked(self) -> bool:
571
+ """Is the node docked?"""
572
+ dock = self.dock
573
+ return dock != "none"
574
+
575
+ @property
576
+ def is_split(self) -> bool:
577
+ """Is the node split?"""
578
+ split = self.split
579
+ return split != "none"
580
+
581
+ def has_rule(self, rule_name: str) -> bool:
582
+ """Check if a rule is set on this Styles object.
583
+
584
+ Args:
585
+ rule_name: Rule name.
586
+
587
+ Returns:
588
+ ``True`` if the rules is present, otherwise ``False``.
589
+ """
590
+ raise NotImplementedError()
591
+
592
+ def clear_rule(self, rule_name: str) -> bool:
593
+ """Removes the rule from the Styles object, as if it had never been set.
594
+
595
+ Args:
596
+ rule_name: Rule name.
597
+
598
+ Returns:
599
+ ``True`` if a rule was cleared, or ``False`` if the rule is already not set.
600
+ """
601
+ raise NotImplementedError()
602
+
603
+ def get_rules(self) -> RulesMap:
604
+ """Get the rules in a mapping.
605
+
606
+ Returns:
607
+ A TypedDict of the rules.
608
+ """
609
+ raise NotImplementedError()
610
+
611
+ def set_rule(self, rule_name: str, value: object | None) -> bool:
612
+ """Set a rule.
613
+
614
+ Args:
615
+ rule_name: Rule name.
616
+ value: New rule value.
617
+
618
+ Returns:
619
+ ``True`` if the rule changed, otherwise ``False``.
620
+ """
621
+ raise NotImplementedError()
622
+
623
+ def get_rule(self, rule_name: str, default: object = None) -> object:
624
+ """Get an individual rule.
625
+
626
+ Args:
627
+ rule_name: Name of rule.
628
+ default: Default if rule does not exists.
629
+
630
+ Returns:
631
+ Rule value or default.
632
+ """
633
+ raise NotImplementedError()
634
+
635
+ def refresh(
636
+ self,
637
+ *,
638
+ layout: bool = False,
639
+ children: bool = False,
640
+ parent: bool = False,
641
+ repaint: bool = True,
642
+ ) -> None:
643
+ """Mark the styles as requiring a refresh.
644
+
645
+ Args:
646
+ layout: Also require a layout.
647
+ children: Also refresh children.
648
+ parent: Also refresh the parent.
649
+ repaint: Repaint the widgets.
650
+ """
651
+
652
+ def reset(self) -> None:
653
+ """Reset the rules to initial state."""
654
+
655
+ def merge(self, other: StylesBase) -> None:
656
+ """Merge values from another Styles.
657
+
658
+ Args:
659
+ other: A Styles object.
660
+ """
661
+
662
+ def merge_rules(self, rules: RulesMap) -> None:
663
+ """Merge rules in to Styles.
664
+
665
+ Args:
666
+ rules: A mapping of rules.
667
+ """
668
+
669
+ def get_render_rules(self) -> RulesMap:
670
+ """Get rules map with defaults."""
671
+ # Get a dictionary of rules, going through the properties
672
+ rules = dict(zip(RULE_NAMES, _rule_getter(self)))
673
+ return cast(RulesMap, rules)
674
+
675
+ @classmethod
676
+ def is_animatable(cls, rule: str) -> bool:
677
+ """Check if a given rule may be animated.
678
+
679
+ Args:
680
+ rule: Name of the rule.
681
+
682
+ Returns:
683
+ ``True`` if the rule may be animated, otherwise ``False``.
684
+ """
685
+ return rule in cls.ANIMATABLE
686
+
687
+ @classmethod
688
+ def parse(
689
+ cls, css: str, read_from: CSSLocation, *, node: DOMNode | None = None
690
+ ) -> Styles:
691
+ """Parse CSS and return a Styles object.
692
+
693
+ Args:
694
+ css: Textual CSS.
695
+ read_from: Location where the CSS was read from.
696
+ node: Node to associate with the Styles.
697
+
698
+ Returns:
699
+ A Styles instance containing result of parsing CSS.
700
+ """
701
+ from textual.css.parse import parse_declarations
702
+
703
+ styles = parse_declarations(css, read_from)
704
+ styles.node = node
705
+ return styles
706
+
707
+ def _get_transition(self, key: str) -> Transition | None:
708
+ """Get a transition.
709
+
710
+ Args:
711
+ key: Transition key.
712
+
713
+ Returns:
714
+ Transition object or None it no transition exists.
715
+ """
716
+ if key in self.ANIMATABLE:
717
+ return self.transitions.get(key, None)
718
+ else:
719
+ return None
720
+
721
+ def _align_width(self, width: int, parent_width: int) -> int:
722
+ """Align the width dimension.
723
+
724
+ Args:
725
+ width: Width of the content.
726
+ parent_width: Width of the parent container.
727
+
728
+ Returns:
729
+ An offset to add to the X coordinate.
730
+ """
731
+ offset_x = 0
732
+ align_horizontal = self.align_horizontal
733
+ if align_horizontal != "left":
734
+ if align_horizontal == "center":
735
+ offset_x = (parent_width - width) // 2
736
+ else:
737
+ offset_x = parent_width - width
738
+
739
+ return offset_x
740
+
741
+ def _align_height(self, height: int, parent_height: int) -> int:
742
+ """Align the height dimensions
743
+
744
+ Args:
745
+ height: Height of the content.
746
+ parent_height: Height of the parent container.
747
+
748
+ Returns:
749
+ An offset to add to the Y coordinate.
750
+ """
751
+ offset_y = 0
752
+ align_vertical = self.align_vertical
753
+ if align_vertical != "top":
754
+ if align_vertical == "middle":
755
+ offset_y = (parent_height - height) // 2
756
+ else:
757
+ offset_y = parent_height - height
758
+ return offset_y
759
+
760
+ def _align_size(self, child: tuple[int, int], parent: tuple[int, int]) -> Offset:
761
+ """Align a size according to alignment rules.
762
+
763
+ Args:
764
+ child: The size of the child (width, height)
765
+ parent: The size of the parent (width, height)
766
+
767
+ Returns:
768
+ Offset required to align the child.
769
+ """
770
+ width, height = child
771
+ parent_width, parent_height = parent
772
+ return Offset(
773
+ self._align_width(width, parent_width),
774
+ self._align_height(height, parent_height),
775
+ )
776
+
777
+ @property
778
+ def partial_rich_style(self) -> Style:
779
+ """Get the style properties associated with this node only (not including parents in the DOM).
780
+
781
+ Returns:
782
+ Rich Style object.
783
+ """
784
+ style = Style(
785
+ color=(
786
+ self.color.rich_color
787
+ if self.has_rule("color") and self.color.a > 0
788
+ else None
789
+ ),
790
+ bgcolor=(
791
+ self.background.rich_color
792
+ if self.has_rule("background") and self.background.a > 0
793
+ else None
794
+ ),
795
+ )
796
+ style += self.text_style
797
+ return style
798
+
799
+
800
+ @rich.repr.auto
801
+ @dataclass
802
+ class Styles(StylesBase):
803
+ node: DOMNode | None = None
804
+ _rules: RulesMap = field(default_factory=RulesMap)
805
+ _updates: int = 0
806
+
807
+ important: set[str] = field(default_factory=set)
808
+
809
+ def __post_init__(self) -> None:
810
+ self.get_rule: Callable[[str, object], object] = self._rules.get # type: ignore[assignment]
811
+ self.has_rule: Callable[[str], bool] = self._rules.__contains__ # type: ignore[assignment]
812
+
813
+ def copy(self) -> Styles:
814
+ """Get a copy of this Styles object."""
815
+ return Styles(
816
+ node=self.node,
817
+ _rules=self.get_rules(),
818
+ important=self.important,
819
+ )
820
+
821
+ def clear_rule(self, rule_name: str) -> bool:
822
+ """Removes the rule from the Styles object, as if it had never been set.
823
+
824
+ Args:
825
+ rule_name: Rule name.
826
+
827
+ Returns:
828
+ ``True`` if a rule was cleared, or ``False`` if it was already not set.
829
+ """
830
+ changed = self._rules.pop(rule_name, None) is not None # type: ignore
831
+ if changed:
832
+ self._updates += 1
833
+ return changed
834
+
835
+ def get_rules(self) -> RulesMap:
836
+ return self._rules.copy()
837
+
838
+ def set_rule(self, rule: str, value: object | None) -> bool:
839
+ """Set a rule.
840
+
841
+ Args:
842
+ rule: Rule name.
843
+ value: New rule value.
844
+
845
+ Returns:
846
+ ``True`` if the rule changed, otherwise ``False``.
847
+ """
848
+ if value is None:
849
+ changed = self._rules.pop(rule, None) is not None # type: ignore
850
+ if changed:
851
+ self._updates += 1
852
+ return changed
853
+ current = self._rules.get(rule)
854
+ self._rules[rule] = value # type: ignore
855
+ changed = current != value
856
+ if changed:
857
+ self._updates += 1
858
+ return changed
859
+
860
+ def refresh(
861
+ self,
862
+ *,
863
+ layout: bool = False,
864
+ children: bool = False,
865
+ parent: bool = False,
866
+ repaint=True,
867
+ ) -> None:
868
+ node = self.node
869
+ if node is None or not node._is_mounted:
870
+ return
871
+ if parent and node._parent is not None:
872
+ node._parent.refresh(repaint=repaint)
873
+ node.refresh(layout=layout)
874
+ if children:
875
+ for child in node.walk_children(with_self=False, reverse=True):
876
+ child.refresh(layout=layout, repaint=repaint)
877
+
878
+ def reset(self) -> None:
879
+ """Reset the rules to initial state."""
880
+ self._updates += 1
881
+ self._rules.clear() # type: ignore
882
+
883
+ def merge(self, other: StylesBase) -> None:
884
+ """Merge values from another Styles.
885
+
886
+ Args:
887
+ other: A Styles object.
888
+ """
889
+ self._updates += 1
890
+ self._rules.update(other.get_rules())
891
+
892
+ def merge_rules(self, rules: RulesMap) -> None:
893
+ self._updates += 1
894
+ self._rules.update(rules)
895
+
896
+ def extract_rules(
897
+ self,
898
+ specificity: Specificity3,
899
+ is_default_rules: bool = False,
900
+ tie_breaker: int = 0,
901
+ ) -> list[tuple[str, Specificity6, Any]]:
902
+ """Extract rules from Styles object, and apply !important css specificity as
903
+ well as higher specificity of user CSS vs widget CSS.
904
+
905
+ Args:
906
+ specificity: A node specificity.
907
+ is_default_rules: True if the rules we're extracting are
908
+ default (i.e. in Widget.DEFAULT_CSS) rules. False if they're from user defined CSS.
909
+
910
+ Returns:
911
+ A list containing a tuple of <RULE NAME>, <SPECIFICITY> <RULE VALUE>.
912
+ """
913
+ is_important = self.important.__contains__
914
+ default_rules = 0 if is_default_rules else 1
915
+ rules: list[tuple[str, Specificity6, Any]] = [
916
+ (
917
+ rule_name,
918
+ (
919
+ default_rules,
920
+ 1 if is_important(rule_name) else 0,
921
+ *specificity,
922
+ tie_breaker,
923
+ ),
924
+ rule_value,
925
+ )
926
+ for rule_name, rule_value in self._rules.items()
927
+ ]
928
+
929
+ return rules
930
+
931
+ def __rich_repr__(self) -> rich.repr.Result:
932
+ has_rule = self.has_rule
933
+ for name in RULE_NAMES:
934
+ if has_rule(name):
935
+ yield name, getattr(self, name)
936
+ if self.important:
937
+ yield "important", self.important
938
+
939
+ def _get_border_css_lines(
940
+ self, rules: RulesMap, name: str
941
+ ) -> Iterable[tuple[str, str]]:
942
+ """Get pairs of strings containing <RULE NAME>, <RULE VALUE> for border css declarations.
943
+
944
+ Args:
945
+ rules: A rules map.
946
+ name: Name of rules (border or outline)
947
+
948
+ Returns:
949
+ An iterable of CSS declarations.
950
+ """
951
+
952
+ has_rule = rules.__contains__
953
+ get_rule = rules.__getitem__
954
+
955
+ has_top = has_rule(f"{name}_top")
956
+ has_right = has_rule(f"{name}_right")
957
+ has_bottom = has_rule(f"{name}_bottom")
958
+ has_left = has_rule(f"{name}_left")
959
+ if not any((has_top, has_right, has_bottom, has_left)):
960
+ # No border related rules
961
+ return
962
+
963
+ if all((has_top, has_right, has_bottom, has_left)):
964
+ # All rules are set
965
+ # See if we can set them with a single border: declaration
966
+ top = get_rule(f"{name}_top")
967
+ right = get_rule(f"{name}_right")
968
+ bottom = get_rule(f"{name}_bottom")
969
+ left = get_rule(f"{name}_left")
970
+
971
+ if top == right and right == bottom and bottom == left:
972
+ border_type, border_color = rules[f"{name}_top"] # type: ignore
973
+ yield name, f"{border_type} {border_color.hex}"
974
+ return
975
+
976
+ # Check for edges
977
+ if has_top:
978
+ border_type, border_color = rules[f"{name}_top"] # type: ignore
979
+ yield f"{name}-top", f"{border_type} {border_color.hex}"
980
+
981
+ if has_right:
982
+ border_type, border_color = rules[f"{name}_right"] # type: ignore
983
+ yield f"{name}-right", f"{border_type} {border_color.hex}"
984
+
985
+ if has_bottom:
986
+ border_type, border_color = rules[f"{name}_bottom"] # type: ignore
987
+ yield f"{name}-bottom", f"{border_type} {border_color.hex}"
988
+
989
+ if has_left:
990
+ border_type, border_color = rules[f"{name}_left"] # type: ignore
991
+ yield f"{name}-left", f"{border_type} {border_color.hex}"
992
+
993
+ @property
994
+ def css_lines(self) -> list[str]:
995
+ lines: list[str] = []
996
+ append = lines.append
997
+
998
+ def append_declaration(name: str, value: str) -> None:
999
+ if name in self.important:
1000
+ append(f"{name}: {value} !important;")
1001
+ else:
1002
+ append(f"{name}: {value};")
1003
+
1004
+ rules = self.get_rules()
1005
+ get_rule = rules.get
1006
+
1007
+ if "display" in rules:
1008
+ append_declaration("display", rules["display"])
1009
+ if "visibility" in rules:
1010
+ append_declaration("visibility", rules["visibility"])
1011
+ if "padding" in rules:
1012
+ append_declaration("padding", rules["padding"].css)
1013
+ if "margin" in rules:
1014
+ append_declaration("margin", rules["margin"].css)
1015
+
1016
+ for name, rule in self._get_border_css_lines(rules, "border"):
1017
+ append_declaration(name, rule)
1018
+
1019
+ for name, rule in self._get_border_css_lines(rules, "outline"):
1020
+ append_declaration(name, rule)
1021
+
1022
+ if "offset" in rules:
1023
+ x, y = self.offset
1024
+ append_declaration("offset", f"{x} {y}")
1025
+ if "position" in rules:
1026
+ append_declaration("position", self.position)
1027
+ if "dock" in rules:
1028
+ append_declaration("dock", rules["dock"])
1029
+ if "split" in rules:
1030
+ append_declaration("split", rules["split"])
1031
+ if "layers" in rules:
1032
+ append_declaration("layers", " ".join(self.layers))
1033
+ if "layer" in rules:
1034
+ append_declaration("layer", self.layer)
1035
+ if "layout" in rules:
1036
+ assert self.layout is not None
1037
+ append_declaration("layout", self.layout.name)
1038
+
1039
+ if "color" in rules:
1040
+ append_declaration("color", self.color.hex)
1041
+ if "background" in rules:
1042
+ append_declaration("background", self.background.hex)
1043
+ if "background_tint" in rules:
1044
+ append_declaration("background-tint", self.background_tint.hex)
1045
+ if "text_style" in rules:
1046
+ append_declaration("text-style", str(get_rule("text_style")))
1047
+ if "tint" in rules:
1048
+ append_declaration("tint", self.tint.css)
1049
+
1050
+ if "overflow_x" in rules:
1051
+ append_declaration("overflow-x", self.overflow_x)
1052
+ if "overflow_y" in rules:
1053
+ append_declaration("overflow-y", self.overflow_y)
1054
+
1055
+ if "scrollbar_color" in rules:
1056
+ append_declaration("scrollbar-color", self.scrollbar_color.css)
1057
+ if "scrollbar_color_hover" in rules:
1058
+ append_declaration("scrollbar-color-hover", self.scrollbar_color_hover.css)
1059
+ if "scrollbar_color_active" in rules:
1060
+ append_declaration(
1061
+ "scrollbar-color-active", self.scrollbar_color_active.css
1062
+ )
1063
+
1064
+ if "scrollbar_corner_color" in rules:
1065
+ append_declaration(
1066
+ "scrollbar-corner-color", self.scrollbar_corner_color.css
1067
+ )
1068
+
1069
+ if "scrollbar_background" in rules:
1070
+ append_declaration("scrollbar-background", self.scrollbar_background.css)
1071
+ if "scrollbar_background_hover" in rules:
1072
+ append_declaration(
1073
+ "scrollbar-background-hover", self.scrollbar_background_hover.css
1074
+ )
1075
+ if "scrollbar_background_active" in rules:
1076
+ append_declaration(
1077
+ "scrollbar-background-active", self.scrollbar_background_active.css
1078
+ )
1079
+
1080
+ if "scrollbar_gutter" in rules:
1081
+ append_declaration("scrollbar-gutter", self.scrollbar_gutter)
1082
+ if "scrollbar_size" in rules:
1083
+ append_declaration(
1084
+ "scrollbar-size",
1085
+ f"{self.scrollbar_size_horizontal} {self.scrollbar_size_vertical}",
1086
+ )
1087
+ else:
1088
+ if "scrollbar_size_horizontal" in rules:
1089
+ append_declaration(
1090
+ "scrollbar-size-horizontal", str(self.scrollbar_size_horizontal)
1091
+ )
1092
+ if "scrollbar_size_vertical" in rules:
1093
+ append_declaration(
1094
+ "scrollbar-size-vertical", str(self.scrollbar_size_vertical)
1095
+ )
1096
+
1097
+ if "box_sizing" in rules:
1098
+ append_declaration("box-sizing", self.box_sizing)
1099
+ if "width" in rules:
1100
+ append_declaration("width", str(self.width))
1101
+ if "height" in rules:
1102
+ append_declaration("height", str(self.height))
1103
+ if "min_width" in rules:
1104
+ append_declaration("min-width", str(self.min_width))
1105
+ if "min_height" in rules:
1106
+ append_declaration("min-height", str(self.min_height))
1107
+ if "max_width" in rules:
1108
+ append_declaration("max-width", str(self.min_width))
1109
+ if "max_height" in rules:
1110
+ append_declaration("max-height", str(self.min_height))
1111
+ if "transitions" in rules:
1112
+ append_declaration(
1113
+ "transition",
1114
+ ", ".join(
1115
+ f"{name} {transition}"
1116
+ for name, transition in self.transitions.items()
1117
+ ),
1118
+ )
1119
+
1120
+ if "align_horizontal" in rules and "align_vertical" in rules:
1121
+ append_declaration(
1122
+ "align", f"{self.align_horizontal} {self.align_vertical}"
1123
+ )
1124
+ elif "align_horizontal" in rules:
1125
+ append_declaration("align-horizontal", self.align_horizontal)
1126
+ elif "align_vertical" in rules:
1127
+ append_declaration("align-vertical", self.align_vertical)
1128
+
1129
+ if "content_align_horizontal" in rules and "content_align_vertical" in rules:
1130
+ append_declaration(
1131
+ "content-align",
1132
+ f"{self.content_align_horizontal} {self.content_align_vertical}",
1133
+ )
1134
+ elif "content_align_horizontal" in rules:
1135
+ append_declaration(
1136
+ "content-align-horizontal", self.content_align_horizontal
1137
+ )
1138
+ elif "content_align_vertical" in rules:
1139
+ append_declaration("content-align-vertical", self.content_align_vertical)
1140
+
1141
+ if "text_align" in rules:
1142
+ append_declaration("text-align", self.text_align)
1143
+
1144
+ if "border_title_align" in rules:
1145
+ append_declaration("border-title-align", self.border_title_align)
1146
+ if "border_subtitle_align" in rules:
1147
+ append_declaration("border-subtitle-align", self.border_subtitle_align)
1148
+
1149
+ if "opacity" in rules:
1150
+ append_declaration("opacity", str(self.opacity))
1151
+ if "text_opacity" in rules:
1152
+ append_declaration("text-opacity", str(self.text_opacity))
1153
+
1154
+ if "grid_columns" in rules:
1155
+ append_declaration(
1156
+ "grid-columns",
1157
+ " ".join(str(scalar) for scalar in self.grid_columns or ()),
1158
+ )
1159
+ if "grid_rows" in rules:
1160
+ append_declaration(
1161
+ "grid-rows",
1162
+ " ".join(str(scalar) for scalar in self.grid_rows or ()),
1163
+ )
1164
+ if "grid_size_columns" in rules:
1165
+ append_declaration("grid-size-columns", str(self.grid_size_columns))
1166
+ if "grid_size_rows" in rules:
1167
+ append_declaration("grid-size-rows", str(self.grid_size_rows))
1168
+
1169
+ if "grid_gutter_horizontal" in rules:
1170
+ append_declaration(
1171
+ "grid-gutter-horizontal", str(self.grid_gutter_horizontal)
1172
+ )
1173
+ if "grid_gutter_vertical" in rules:
1174
+ append_declaration("grid-gutter-vertical", str(self.grid_gutter_vertical))
1175
+
1176
+ if "row_span" in rules:
1177
+ append_declaration("row-span", str(self.row_span))
1178
+ if "column_span" in rules:
1179
+ append_declaration("column-span", str(self.column_span))
1180
+
1181
+ if "link_color" in rules:
1182
+ append_declaration("link-color", self.link_color.css)
1183
+ if "link_background" in rules:
1184
+ append_declaration("link-background", self.link_background.css)
1185
+ if "link_style" in rules:
1186
+ append_declaration("link-style", str(self.link_style))
1187
+
1188
+ if "link_color_hover" in rules:
1189
+ append_declaration("link-color-hover", self.link_color_hover.css)
1190
+ if "link_background_hover" in rules:
1191
+ append_declaration("link-background-hover", self.link_background_hover.css)
1192
+ if "link_style_hover" in rules:
1193
+ append_declaration("link-style-hover", str(self.link_style_hover))
1194
+
1195
+ if "border_title_color" in rules:
1196
+ append_declaration("title-color", self.border_title_color.css)
1197
+ if "border_title_background" in rules:
1198
+ append_declaration("title-background", self.border_title_background.css)
1199
+ if "border_title_style" in rules:
1200
+ append_declaration("title-text-style", str(self.border_title_style))
1201
+
1202
+ if "border_subtitle_color" in rules:
1203
+ append_declaration("subtitle-color", self.border_subtitle_color.css)
1204
+ if "border_subtitle_background" in rules:
1205
+ append_declaration(
1206
+ "subtitle-background", self.border_subtitle_background.css
1207
+ )
1208
+ if "border_subtitle_text_style" in rules:
1209
+ append_declaration("subtitle-text-style", str(self.border_subtitle_style))
1210
+ if "overlay" in rules:
1211
+ append_declaration("overlay", str(self.overlay))
1212
+ if "constrain_x" in rules and "constrain_y" in rules:
1213
+ if self.constrain_x == self.constrain_y:
1214
+ append_declaration("constrain", self.constrain_x)
1215
+ else:
1216
+ append_declaration(
1217
+ "constrain", f"{self.constrain_x} {self.constrain_y}"
1218
+ )
1219
+ elif "constrain_x" in rules:
1220
+ append_declaration("constrain-x", self.constrain_x)
1221
+ elif "constrain_y" in rules:
1222
+ append_declaration("constrain-y", self.constrain_y)
1223
+
1224
+ if "keyline" in rules:
1225
+ keyline_type, keyline_color = self.keyline
1226
+ if keyline_type != "none":
1227
+ append_declaration("keyline", f"{keyline_type}, {keyline_color.css}")
1228
+ if "hatch" in rules:
1229
+ hatch_character, hatch_color = self.hatch
1230
+ append_declaration("hatch", f'"{hatch_character}" {hatch_color.css}')
1231
+ lines.sort()
1232
+ return lines
1233
+
1234
+ @property
1235
+ def css(self) -> str:
1236
+ return "\n".join(self.css_lines)
1237
+
1238
+
1239
+ @rich.repr.auto
1240
+ class RenderStyles(StylesBase):
1241
+ """Presents a combined view of two Styles object: a base Styles and inline Styles."""
1242
+
1243
+ def __init__(self, node: DOMNode, base: Styles, inline_styles: Styles) -> None:
1244
+ self.node = node
1245
+ self._base_styles = base
1246
+ self._inline_styles = inline_styles
1247
+ self._animate: BoundAnimator | None = None
1248
+ self._updates: int = 0
1249
+ self._rich_style: tuple[int, Style] | None = None
1250
+ self._gutter: tuple[int, Spacing] | None = None
1251
+
1252
+ def __eq__(self, other: object) -> bool:
1253
+ if isinstance(other, RenderStyles):
1254
+ return (
1255
+ self._base_styles._rules == other._base_styles._rules
1256
+ and self._inline_styles._rules == other._inline_styles._rules
1257
+ )
1258
+ return NotImplemented
1259
+
1260
+ @property
1261
+ def _cache_key(self) -> int:
1262
+ """A cache key, that changes when any style is changed.
1263
+
1264
+ Returns:
1265
+ An opaque integer.
1266
+ """
1267
+ return self._updates + self._base_styles._updates + self._inline_styles._updates
1268
+
1269
+ @property
1270
+ def base(self) -> Styles:
1271
+ """Quick access to base (css) style."""
1272
+ return self._base_styles
1273
+
1274
+ @property
1275
+ def inline(self) -> Styles:
1276
+ """Quick access to the inline styles."""
1277
+ return self._inline_styles
1278
+
1279
+ @property
1280
+ def rich_style(self) -> Style:
1281
+ """Get a Rich style for this Styles object."""
1282
+ assert self.node is not None
1283
+ return self.node.rich_style
1284
+
1285
+ @property
1286
+ def gutter(self) -> Spacing:
1287
+ """Get space around widget.
1288
+
1289
+ Returns:
1290
+ Space around widget content.
1291
+ """
1292
+ # This is (surprisingly) a bit of a bottleneck
1293
+ if self._gutter is not None:
1294
+ cache_key, gutter = self._gutter
1295
+ if cache_key == self._cache_key:
1296
+ return gutter
1297
+ gutter = self.padding + self.border.spacing
1298
+ self._gutter = (self._cache_key, gutter)
1299
+ return gutter
1300
+
1301
+ def animate(
1302
+ self,
1303
+ attribute: str,
1304
+ value: str | float | Animatable,
1305
+ *,
1306
+ final_value: object = ...,
1307
+ duration: float | None = None,
1308
+ speed: float | None = None,
1309
+ delay: float = 0.0,
1310
+ easing: EasingFunction | str = DEFAULT_EASING,
1311
+ on_complete: CallbackType | None = None,
1312
+ level: AnimationLevel = "full",
1313
+ ) -> None:
1314
+ """Animate an attribute.
1315
+
1316
+ Args:
1317
+ attribute: Name of the attribute to animate.
1318
+ value: The value to animate to.
1319
+ final_value: The final value of the animation. Defaults to `value` if not set.
1320
+ duration: The duration (in seconds) of the animation.
1321
+ speed: The speed of the animation.
1322
+ delay: A delay (in seconds) before the animation starts.
1323
+ easing: An easing method.
1324
+ on_complete: A callable to invoke when the animation is finished.
1325
+ level: Minimum level required for the animation to take place (inclusive).
1326
+ """
1327
+ if self._animate is None:
1328
+ assert self.node is not None
1329
+ self._animate = self.node.app.animator.bind(self)
1330
+ assert self._animate is not None
1331
+ self._animate(
1332
+ attribute,
1333
+ value,
1334
+ final_value=final_value,
1335
+ duration=duration,
1336
+ speed=speed,
1337
+ delay=delay,
1338
+ easing=easing,
1339
+ on_complete=on_complete,
1340
+ level=level,
1341
+ )
1342
+
1343
+ def __rich_repr__(self) -> rich.repr.Result:
1344
+ yield self.node
1345
+ for rule_name in RULE_NAMES:
1346
+ if self.has_rule(rule_name):
1347
+ yield rule_name, getattr(self, rule_name)
1348
+
1349
+ def refresh(
1350
+ self,
1351
+ *,
1352
+ layout: bool = False,
1353
+ children: bool = False,
1354
+ parent: bool = False,
1355
+ repaint: bool = True,
1356
+ ) -> None:
1357
+ self._inline_styles.refresh(
1358
+ layout=layout, children=children, parent=parent, repaint=repaint
1359
+ )
1360
+
1361
+ def merge(self, other: StylesBase) -> None:
1362
+ """Merge values from another Styles.
1363
+
1364
+ Args:
1365
+ other: A Styles object.
1366
+ """
1367
+ self._inline_styles.merge(other)
1368
+
1369
+ def merge_rules(self, rules: RulesMap) -> None:
1370
+ self._inline_styles.merge_rules(rules)
1371
+ self._updates += 1
1372
+
1373
+ def reset(self) -> None:
1374
+ """Reset the rules to initial state."""
1375
+ self._inline_styles.reset()
1376
+ self._updates += 1
1377
+
1378
+ def has_rule(self, rule_name: str) -> bool:
1379
+ """Check if a rule has been set."""
1380
+ return self._inline_styles.has_rule(rule_name) or self._base_styles.has_rule(
1381
+ rule_name
1382
+ )
1383
+
1384
+ def has_any_rules(self, *rule_names: str) -> bool:
1385
+ """Check if any of the supplied rules have been set.
1386
+
1387
+ Args:
1388
+ rule_names: Number of rules.
1389
+
1390
+ Returns:
1391
+ `True` if any of the supplied rules have been set, `False` if none have.
1392
+ """
1393
+ inline_has_rule = self._inline_styles.has_rule
1394
+ base_has_rule = self._base_styles.has_rule
1395
+ return any(inline_has_rule(name) or base_has_rule(name) for name in rule_names)
1396
+
1397
+ def set_rule(self, rule_name: str, value: object | None) -> bool:
1398
+ self._updates += 1
1399
+ return self._inline_styles.set_rule(rule_name, value)
1400
+
1401
+ def get_rule(self, rule_name: str, default: object = None) -> object:
1402
+ if self._inline_styles.has_rule(rule_name):
1403
+ return self._inline_styles.get_rule(rule_name, default)
1404
+ return self._base_styles.get_rule(rule_name, default)
1405
+
1406
+ def clear_rule(self, rule_name: str) -> bool:
1407
+ """Clear a rule (from inline)."""
1408
+ self._updates += 1
1409
+ return self._inline_styles.clear_rule(rule_name)
1410
+
1411
+ def get_rules(self) -> RulesMap:
1412
+ """Get rules as a dictionary"""
1413
+ rules = {**self._base_styles._rules, **self._inline_styles._rules}
1414
+ return cast(RulesMap, rules)
1415
+
1416
+ @property
1417
+ def css(self) -> str:
1418
+ """Get the CSS for the combined styles."""
1419
+ styles = Styles()
1420
+ styles.merge(self._base_styles)
1421
+ styles.merge(self._inline_styles)
1422
+ combined_css = styles.css
1423
+ return combined_css
vllm/lib/python3.10/site-packages/textual/css/tokenize.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import TYPE_CHECKING, Iterable
5
+
6
+ from textual.css.tokenizer import Expect, Token, Tokenizer
7
+
8
+ if TYPE_CHECKING:
9
+ from textual.css.types import CSSLocation
10
+
11
+ PERCENT = r"-?\d+\.?\d*%"
12
+ DECIMAL = r"-?\d+\.?\d*"
13
+ COMMA = r"\s*,\s*"
14
+ OPEN_BRACE = r"\(\s*"
15
+ CLOSE_BRACE = r"\s*\)"
16
+
17
+ HEX_COLOR = r"\#[0-9a-fA-F]{8}|\#[0-9a-fA-F]{6}|\#[0-9a-fA-F]{4}|\#[0-9a-fA-F]{3}"
18
+ RGB_COLOR = rf"rgb{OPEN_BRACE}{DECIMAL}{COMMA}{DECIMAL}{COMMA}{DECIMAL}{CLOSE_BRACE}|rgba{OPEN_BRACE}{DECIMAL}{COMMA}{DECIMAL}{COMMA}{DECIMAL}{COMMA}{DECIMAL}{CLOSE_BRACE}"
19
+ HSL_COLOR = rf"hsl{OPEN_BRACE}{DECIMAL}{COMMA}{PERCENT}{COMMA}{PERCENT}{CLOSE_BRACE}|hsla{OPEN_BRACE}{DECIMAL}{COMMA}{PERCENT}{COMMA}{PERCENT}{COMMA}{DECIMAL}{CLOSE_BRACE}"
20
+
21
+ COMMENT_LINE = r"\# .*$"
22
+ COMMENT_START = r"\/\*"
23
+ SCALAR = rf"{DECIMAL}(?:fr|%|w|h|vw|vh)"
24
+ DURATION = r"\d+\.?\d*(?:ms|s)"
25
+ NUMBER = r"\-?\d+\.?\d*"
26
+ COLOR = rf"{HEX_COLOR}|{RGB_COLOR}|{HSL_COLOR}"
27
+ KEY_VALUE = r"[a-zA-Z_-][a-zA-Z0-9_-]*=[0-9a-zA-Z_\-\/]+"
28
+ TOKEN = "[a-zA-Z_][a-zA-Z0-9_-]*"
29
+ STRING = r"\".*?\""
30
+ VARIABLE_REF = r"\$[a-zA-Z0-9_\-]+"
31
+
32
+ IDENTIFIER = r"[a-zA-Z_\-][a-zA-Z0-9_\-]*"
33
+ SELECTOR_TYPE_NAME = r"[A-Z_][a-zA-Z0-9_]*"
34
+ """Selectors representing Widget type names should start with upper case or '_'.
35
+
36
+ The fact that a selector starts with an upper case letter or '_' is relevant in the
37
+ context of nested CSS to help determine whether xxx:yyy is a declaration + value or a
38
+ selector + pseudo-class."""
39
+ DECLARATION_NAME = r"[a-z][a-zA-Z0-9_\-]*"
40
+ """Declaration of TCSS rules start with lowercase.
41
+
42
+ The fact that a declaration starts with a lower case letter is relevant in the context
43
+ of nested CSS to help determine whether xxx:yyy is a declaration + value or a selector
44
+ + pseudo-class.
45
+ """
46
+
47
+ # Values permitted in variable and rule declarations.
48
+ DECLARATION_VALUES = {
49
+ "scalar": SCALAR,
50
+ "duration": DURATION,
51
+ "number": NUMBER,
52
+ "color": COLOR,
53
+ "key_value": KEY_VALUE,
54
+ "token": TOKEN,
55
+ "string": STRING,
56
+ "variable_ref": VARIABLE_REF,
57
+ }
58
+
59
+ # The tokenizers "expectation" while at the root/highest level of scope
60
+ # in the CSS file. At this level we might expect to see selectors, comments,
61
+ # variable definitions etc.
62
+ expect_root_scope = Expect(
63
+ "selector or end of file",
64
+ whitespace=r"\s+",
65
+ comment_start=COMMENT_START,
66
+ comment_line=COMMENT_LINE,
67
+ selector_start_id=r"\#" + IDENTIFIER,
68
+ selector_start_class=r"\." + IDENTIFIER,
69
+ selector_start_universal=r"\*",
70
+ selector_start=SELECTOR_TYPE_NAME,
71
+ variable_name=rf"{VARIABLE_REF}:",
72
+ declaration_set_end=r"\}",
73
+ ).expect_eof(True)
74
+
75
+ expect_root_nested = Expect(
76
+ "selector or end of file",
77
+ whitespace=r"\s+",
78
+ comment_start=COMMENT_START,
79
+ comment_line=COMMENT_LINE,
80
+ declaration_name=DECLARATION_NAME + r"\:",
81
+ selector_start_id=r"\#" + IDENTIFIER,
82
+ selector_start_class=r"\." + IDENTIFIER,
83
+ selector_start_universal=r"\*",
84
+ selector_start=SELECTOR_TYPE_NAME,
85
+ variable_name=rf"{VARIABLE_REF}:",
86
+ declaration_set_end=r"\}",
87
+ nested=r"\&",
88
+ )
89
+
90
+ # After a variable declaration e.g. "$warning-text: TOKENS;"
91
+ # for tokenizing variable value ------^~~~~~~^
92
+ expect_variable_name_continue = Expect(
93
+ "variable value",
94
+ variable_value_end=r"\n|;",
95
+ whitespace=r"\s+",
96
+ comment_start=COMMENT_START,
97
+ comment_line=COMMENT_LINE,
98
+ **DECLARATION_VALUES,
99
+ ).expect_eof(True)
100
+
101
+ expect_comment_end = Expect(
102
+ "comment end",
103
+ comment_end=re.escape("*/"),
104
+ )
105
+
106
+ # After we come across a selector in CSS e.g. ".my-class", we may
107
+ # find other selectors, pseudo-classes... e.g. ".my-class :hover"
108
+ expect_selector_continue = Expect(
109
+ "selector or {",
110
+ whitespace=r"\s+",
111
+ comment_start=COMMENT_START,
112
+ comment_line=COMMENT_LINE,
113
+ pseudo_class=r"\:[a-zA-Z_-]+",
114
+ selector_id=r"\#" + IDENTIFIER,
115
+ selector_class=r"\." + IDENTIFIER,
116
+ selector_universal=r"\*",
117
+ selector=SELECTOR_TYPE_NAME,
118
+ combinator_child=">",
119
+ new_selector=r",",
120
+ declaration_set_start=r"\{",
121
+ declaration_set_end=r"\}",
122
+ nested=r"\&",
123
+ ).expect_eof(True)
124
+
125
+ # A rule declaration e.g. "text: red;"
126
+ # ^---^
127
+ expect_declaration = Expect(
128
+ "rule or selector",
129
+ nested=r"\&",
130
+ whitespace=r"\s+",
131
+ comment_start=COMMENT_START,
132
+ comment_line=COMMENT_LINE,
133
+ declaration_name=DECLARATION_NAME + r"\:",
134
+ declaration_set_end=r"\}",
135
+ #
136
+ selector_start_id=r"\#" + IDENTIFIER,
137
+ selector_start_class=r"\." + IDENTIFIER,
138
+ selector_start_universal=r"\*",
139
+ selector_start=SELECTOR_TYPE_NAME,
140
+ )
141
+
142
+ expect_declaration_solo = Expect(
143
+ "rule declaration",
144
+ whitespace=r"\s+",
145
+ comment_start=COMMENT_START,
146
+ comment_line=COMMENT_LINE,
147
+ declaration_name=DECLARATION_NAME + r"\:",
148
+ declaration_set_end=r"\}",
149
+ ).expect_eof(True)
150
+
151
+ # The value(s)/content from a rule declaration e.g. "text: red;"
152
+ # ^---^
153
+ expect_declaration_content = Expect(
154
+ "rule value or end of declaration",
155
+ declaration_end=r";",
156
+ whitespace=r"\s+",
157
+ comment_start=COMMENT_START,
158
+ comment_line=COMMENT_LINE,
159
+ **DECLARATION_VALUES,
160
+ important=r"\!important",
161
+ comma=",",
162
+ declaration_set_end=r"\}",
163
+ )
164
+
165
+ expect_declaration_content_solo = Expect(
166
+ "rule value or end of declaration",
167
+ declaration_end=r";",
168
+ whitespace=r"\s+",
169
+ comment_start=COMMENT_START,
170
+ comment_line=COMMENT_LINE,
171
+ **DECLARATION_VALUES,
172
+ important=r"\!important",
173
+ comma=",",
174
+ declaration_set_end=r"\}",
175
+ ).expect_eof(True)
176
+
177
+
178
+ class TokenizerState:
179
+ """State machine for the tokenizer.
180
+
181
+ Attributes:
182
+ EXPECT: The initial expectation of the tokenizer. Since we start tokenizing
183
+ at the root scope, we might expect to see either a variable or selector, for example.
184
+ STATE_MAP: Maps token names to Expects, defines the sets of valid tokens
185
+ that we'd expect to see next, given the current token. For example, if
186
+ we've just processed a variable declaration name, we next expect to see
187
+ the value of that variable.
188
+ """
189
+
190
+ EXPECT = expect_root_scope
191
+ STATE_MAP = {
192
+ "variable_name": expect_variable_name_continue,
193
+ "variable_value_end": expect_root_scope,
194
+ "selector_start": expect_selector_continue,
195
+ "selector_start_id": expect_selector_continue,
196
+ "selector_start_class": expect_selector_continue,
197
+ "selector_start_universal": expect_selector_continue,
198
+ "selector_id": expect_selector_continue,
199
+ "selector_class": expect_selector_continue,
200
+ "selector_universal": expect_selector_continue,
201
+ "declaration_set_start": expect_declaration,
202
+ "declaration_name": expect_declaration_content,
203
+ "declaration_end": expect_declaration,
204
+ "declaration_set_end": expect_root_nested,
205
+ "nested": expect_selector_continue,
206
+ }
207
+
208
+ def __call__(self, code: str, read_from: CSSLocation) -> Iterable[Token]:
209
+ tokenizer = Tokenizer(code, read_from=read_from)
210
+ expect = self.EXPECT
211
+ get_token = tokenizer.get_token
212
+ get_state = self.STATE_MAP.get
213
+ nest_level = 0
214
+ while True:
215
+ token = get_token(expect)
216
+ name = token.name
217
+ if name == "comment_line":
218
+ continue
219
+ elif name == "comment_start":
220
+ tokenizer.skip_to(expect_comment_end)
221
+ continue
222
+ elif name == "eof":
223
+ break
224
+ elif name == "declaration_set_start":
225
+ nest_level += 1
226
+ elif name == "declaration_set_end":
227
+ nest_level -= 1
228
+ expect = expect_declaration if nest_level else expect_root_scope
229
+ yield token
230
+ continue
231
+ expect = get_state(name, expect)
232
+ yield token
233
+
234
+
235
+ class DeclarationTokenizerState(TokenizerState):
236
+ EXPECT = expect_declaration_solo
237
+ STATE_MAP = {
238
+ "declaration_name": expect_declaration_content,
239
+ "declaration_end": expect_declaration_solo,
240
+ }
241
+
242
+
243
+ class ValueTokenizerState(TokenizerState):
244
+ EXPECT = expect_declaration_content_solo
245
+
246
+
247
+ tokenize = TokenizerState()
248
+ tokenize_declarations = DeclarationTokenizerState()
249
+ tokenize_value = ValueTokenizerState()
250
+
251
+
252
+ def tokenize_values(values: dict[str, str]) -> dict[str, list[Token]]:
253
+ """Tokenizes the values in a dict of strings.
254
+
255
+ Args:
256
+ values: A mapping of CSS variable name on to a value, to be
257
+ added to the CSS context.
258
+
259
+ Returns:
260
+ A mapping of name on to a list of tokens,
261
+ """
262
+ value_tokens = {
263
+ name: list(tokenize_value(value, ("__name__", "")))
264
+ for name, value in values.items()
265
+ }
266
+ return value_tokens
vllm/lib/python3.10/site-packages/textual/css/tokenizer.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from typing import TYPE_CHECKING, NamedTuple
5
+
6
+ import rich.repr
7
+ from rich.console import Group, RenderableType
8
+ from rich.highlighter import ReprHighlighter
9
+ from rich.padding import Padding
10
+ from rich.panel import Panel
11
+ from rich.text import Text
12
+
13
+ from textual.css._error_tools import friendly_list
14
+ from textual.css.constants import VALID_PSEUDO_CLASSES
15
+ from textual.suggestions import get_suggestion
16
+
17
+ if TYPE_CHECKING:
18
+ from textual.css.types import CSSLocation
19
+
20
+
21
+ class TokenError(Exception):
22
+ """Error raised when the CSS cannot be tokenized (syntax error)."""
23
+
24
+ def __init__(
25
+ self,
26
+ read_from: CSSLocation,
27
+ code: str,
28
+ start: tuple[int, int],
29
+ message: str,
30
+ end: tuple[int, int] | None = None,
31
+ ) -> None:
32
+ """
33
+ Args:
34
+ read_from: The location where the CSS was read from.
35
+ code: The code being parsed.
36
+ start: Line and column number of the error (1-indexed).
37
+ message: A message associated with the error.
38
+ end: End location of token (1-indexed), or None if not known.
39
+ """
40
+
41
+ self.read_from = read_from
42
+ self.code = code
43
+ self.start = start
44
+ self.end = end or start
45
+ super().__init__(message)
46
+
47
+ def _get_snippet(self) -> Panel:
48
+ """Get a short snippet of code around a given line number.
49
+
50
+ Returns:
51
+ A renderable.
52
+ """
53
+ from rich.syntax import Syntax
54
+
55
+ line_no = self.start[0]
56
+ # TODO: Highlight column number
57
+ syntax = Syntax(
58
+ self.code,
59
+ lexer="scss",
60
+ theme="ansi_light",
61
+ line_numbers=True,
62
+ indent_guides=True,
63
+ line_range=(max(0, line_no - 2), line_no + 2),
64
+ highlight_lines={line_no},
65
+ )
66
+ syntax.stylize_range(
67
+ "reverse bold",
68
+ (self.start[0], self.start[1] - 1),
69
+ (self.end[0], self.end[1] - 1),
70
+ )
71
+ return Panel(syntax, border_style="red")
72
+
73
+ def __rich__(self) -> RenderableType:
74
+ highlighter = ReprHighlighter()
75
+ errors: list[RenderableType] = []
76
+
77
+ message = str(self)
78
+ errors.append(Text(" Error in stylesheet:", style="bold red"))
79
+
80
+ line_no, col_no = self.start
81
+
82
+ path, widget_variable = self.read_from
83
+ if widget_variable:
84
+ css_location = f" {path}, {widget_variable}:{line_no}:{col_no}"
85
+ else:
86
+ css_location = f" {path}:{line_no}:{col_no}"
87
+ errors.append(highlighter(css_location))
88
+ errors.append(self._get_snippet())
89
+
90
+ final_message = "\n".join(
91
+ f"• {message_part.strip()}" for message_part in message.split(";")
92
+ )
93
+ errors.append(
94
+ Padding(
95
+ highlighter(
96
+ Text(final_message, "red"),
97
+ ),
98
+ pad=(0, 1),
99
+ )
100
+ )
101
+
102
+ return Group(*errors)
103
+
104
+
105
+ class EOFError(TokenError):
106
+ """Indicates that the CSS ended prematurely."""
107
+
108
+
109
+ @rich.repr.auto
110
+ class Expect:
111
+ """Object that describes the format of tokens."""
112
+
113
+ def __init__(self, description: str, **tokens: str) -> None:
114
+ """Create Expect object.
115
+
116
+ Args:
117
+ description: Description of this class of tokens, used in errors.
118
+ """
119
+ self.description = f"Expected {description}"
120
+ self.names = list(tokens.keys())
121
+ self.regexes = list(tokens.values())
122
+ self._regex = re.compile(
123
+ "("
124
+ + "|".join(f"(?P<{name}>{regex})" for name, regex in tokens.items())
125
+ + ")"
126
+ )
127
+ self.match = self._regex.match
128
+ self.search = self._regex.search
129
+ self._expect_eof = False
130
+
131
+ def expect_eof(self, eof: bool) -> Expect:
132
+ self._expect_eof = eof
133
+ return self
134
+
135
+ def __rich_repr__(self) -> rich.repr.Result:
136
+ yield from zip(self.names, self.regexes)
137
+
138
+
139
+ class ReferencedBy(NamedTuple):
140
+ name: str
141
+ location: tuple[int, int]
142
+ length: int
143
+ code: str
144
+
145
+
146
+ @rich.repr.auto(angular=True)
147
+ class Token(NamedTuple):
148
+ name: str
149
+ value: str
150
+ read_from: CSSLocation
151
+ code: str
152
+ location: tuple[int, int]
153
+ """Token starting location, 0-indexed."""
154
+ referenced_by: ReferencedBy | None = None
155
+
156
+ @property
157
+ def start(self) -> tuple[int, int]:
158
+ """Start line and column (1-indexed)."""
159
+ line, offset = self.location
160
+ return (line + 1, offset + 1)
161
+
162
+ @property
163
+ def end(self) -> tuple[int, int]:
164
+ """End line and column (1-indexed)."""
165
+ line, offset = self.location
166
+ return (line + 1, offset + len(self.value) + 1)
167
+
168
+ def with_reference(self, by: ReferencedBy | None) -> "Token":
169
+ """Return a copy of the Token, with reference information attached.
170
+ This is used for variable substitution, where a variable reference
171
+ can refer to tokens which were defined elsewhere. With the additional
172
+ ReferencedBy data attached, we can track where the token we are referring
173
+ to is used.
174
+ """
175
+ return Token(
176
+ name=self.name,
177
+ value=self.value,
178
+ read_from=self.read_from,
179
+ code=self.code,
180
+ location=self.location,
181
+ referenced_by=by,
182
+ )
183
+
184
+ def __str__(self) -> str:
185
+ return self.value
186
+
187
+ def __rich_repr__(self) -> rich.repr.Result:
188
+ yield "name", self.name
189
+ yield "value", self.value
190
+ yield (
191
+ "read_from",
192
+ self.read_from[0] if not self.read_from[1] else self.read_from,
193
+ )
194
+ yield "code", self.code if len(self.code) < 40 else self.code[:40] + "..."
195
+ yield "location", self.location
196
+ yield "referenced_by", self.referenced_by, None
197
+
198
+
199
+ class Tokenizer:
200
+ """Tokenizes Textual CSS."""
201
+
202
+ def __init__(self, text: str, read_from: CSSLocation = ("", "")) -> None:
203
+ """Initialize the tokenizer.
204
+
205
+ Args:
206
+ text: String containing CSS.
207
+ read_from: Information regarding where the CSS was read from.
208
+ """
209
+ self.read_from = read_from
210
+ self.code = text
211
+ self.lines = text.splitlines(keepends=True)
212
+ self.line_no = 0
213
+ self.col_no = 0
214
+
215
+ def get_token(self, expect: Expect) -> Token:
216
+ """Get the next token.
217
+
218
+ Args:
219
+ expect: Expect object which describes which tokens may be read.
220
+
221
+ Raises:
222
+ EOFError: If there is an unexpected end of file.
223
+ TokenError: If there is an error with the token.
224
+
225
+ Returns:
226
+ A new Token.
227
+ """
228
+
229
+ line_no = self.line_no
230
+ col_no = self.col_no
231
+ if line_no >= len(self.lines):
232
+ if expect._expect_eof:
233
+ return Token(
234
+ "eof",
235
+ "",
236
+ self.read_from,
237
+ self.code,
238
+ (line_no, col_no),
239
+ None,
240
+ )
241
+ else:
242
+ raise EOFError(
243
+ self.read_from,
244
+ self.code,
245
+ (line_no + 1, col_no + 1),
246
+ "Unexpected end of file; did you forget a '}' ?",
247
+ )
248
+ line = self.lines[line_no]
249
+ match = expect.match(line, col_no)
250
+ if match is None:
251
+ error_line = line[col_no:].rstrip()
252
+ error_message = (
253
+ f"{expect.description} (found {error_line.split(';')[0]!r})."
254
+ )
255
+ if not error_line.endswith(";"):
256
+ error_message += "; Did you forget a semicolon at the end of a line?"
257
+ raise TokenError(
258
+ self.read_from, self.code, (line_no + 1, col_no + 1), error_message
259
+ )
260
+ iter_groups = iter(match.groups())
261
+
262
+ next(iter_groups)
263
+
264
+ for name, value in zip(expect.names, iter_groups):
265
+ if value is not None:
266
+ break
267
+ else:
268
+ # For MyPy's benefit
269
+ raise AssertionError("can't reach here")
270
+
271
+ token = Token(
272
+ name,
273
+ value,
274
+ self.read_from,
275
+ self.code,
276
+ (line_no, col_no),
277
+ referenced_by=None,
278
+ )
279
+
280
+ if (
281
+ token.name == "pseudo_class"
282
+ and token.value.strip(":") not in VALID_PSEUDO_CLASSES
283
+ ):
284
+ pseudo_class = token.value.strip(":")
285
+ suggestion = get_suggestion(pseudo_class, list(VALID_PSEUDO_CLASSES))
286
+ all_valid = f"must be one of {friendly_list(VALID_PSEUDO_CLASSES)}"
287
+ if suggestion:
288
+ raise TokenError(
289
+ self.read_from,
290
+ self.code,
291
+ (line_no + 1, col_no + 1),
292
+ f"unknown pseudo-class {pseudo_class!r}; did you mean {suggestion!r}?; {all_valid}",
293
+ )
294
+ else:
295
+ raise TokenError(
296
+ self.read_from,
297
+ self.code,
298
+ (line_no + 1, col_no + 1),
299
+ f"unknown pseudo-class {pseudo_class!r}; {all_valid}",
300
+ )
301
+
302
+ col_no += len(value)
303
+ if col_no >= len(line):
304
+ line_no += 1
305
+ col_no = 0
306
+ self.line_no = line_no
307
+ self.col_no = col_no
308
+ return token
309
+
310
+ def skip_to(self, expect: Expect) -> Token:
311
+ """Skip tokens.
312
+
313
+ Args:
314
+ expect: Expect object describing the expected token.
315
+
316
+ Raises:
317
+ EOFError: If end of file is reached.
318
+
319
+ Returns:
320
+ A new token.
321
+ """
322
+ line_no = self.line_no
323
+ col_no = self.col_no
324
+
325
+ while True:
326
+ if line_no >= len(self.lines):
327
+ raise EOFError(
328
+ self.read_from,
329
+ self.code,
330
+ (line_no, col_no),
331
+ "Unexpected end of file; did you forget a '}' ?",
332
+ )
333
+ line = self.lines[line_no]
334
+ match = expect.search(line, col_no)
335
+
336
+ if match is None:
337
+ line_no += 1
338
+ col_no = 0
339
+ else:
340
+ self.line_no = line_no
341
+ self.col_no = match.span(0)[0]
342
+ return self.get_token(expect)
vllm/lib/python3.10/site-packages/textual/css/types.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Tuple
4
+
5
+ from typing_extensions import Literal
6
+
7
+ from textual.color import Color
8
+
9
+ DockEdge = Literal["none", "top", "right", "bottom", "left"]
10
+ EdgeType = Literal[
11
+ "",
12
+ "ascii",
13
+ "none",
14
+ "hidden",
15
+ "blank",
16
+ "round",
17
+ "solid",
18
+ "thick",
19
+ "double",
20
+ "dashed",
21
+ "heavy",
22
+ "inner",
23
+ "outer",
24
+ "hkey",
25
+ "vkey",
26
+ "tall",
27
+ "tab",
28
+ "panel",
29
+ "wide",
30
+ ]
31
+ Visibility = Literal["visible", "hidden", "initial", "inherit"]
32
+ Display = Literal["block", "none"]
33
+ AlignHorizontal = Literal["left", "center", "right"]
34
+ AlignVertical = Literal["top", "middle", "bottom"]
35
+ ScrollbarGutter = Literal["auto", "stable"]
36
+ BoxSizing = Literal["border-box", "content-box"]
37
+ Overflow = Literal["scroll", "hidden", "auto"]
38
+ EdgeStyle = Tuple[EdgeType, Color]
39
+ TextAlign = Literal["left", "start", "center", "right", "end", "justify"]
40
+ Constrain = Literal["none", "inflect", "inside"]
41
+ Overlay = Literal["none", "screen"]
42
+ Position = Literal["relative", "absolute"]
43
+
44
+ Specificity3 = Tuple[int, int, int]
45
+ Specificity6 = Tuple[int, int, int, int, int, int]
46
+
47
+ CSSLocation = Tuple[str, str]
48
+ """Represents the definition location of a piece of CSS code.
49
+
50
+ The first element of the tuple is the file path from where the CSS was read.
51
+ If the CSS was read from a Python source file, the second element contains the class
52
+ variable from where the CSS was read (e.g., "Widget.DEFAULT_CSS"), otherwise it's an
53
+ empty string.
54
+ """
vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (226 Bytes). View file
 
vllm/lib/python3.10/site-packages/textual/renderables/__pycache__/background_screen.cpython-310.pyc ADDED
Binary file (2.38 kB). View file