jasonfan commited on
Commit
0b7b58d
·
verified ·
1 Parent(s): 80875a5

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. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/linear.py +69 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/rnn.py +861 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/sparse.py +163 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/utils.py +438 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/__init__.py +1 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/quantized/__init__.py +10 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/quantized/dynamic/__init__.py +6 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/quantized/dynamic/linear.py +191 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/quantized/linear.py +274 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/quantized/utils.py +62 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/__init__.py +0 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/_numeric_suite.py +568 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/_numeric_suite_fx.py +1121 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/__init__.py +0 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/graph_matcher.py +485 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/graph_passes.py +1155 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/mappings.py +763 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/n_shadows_utils.py +1416 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/ns_types.py +66 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/pattern_utils.py +214 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/qconfig_multi_mapping.py +251 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/utils.py +579 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/weight_utils.py +302 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/__init__.py +23 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/__init__.py +0 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__init__.py +0 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/activation_sparsifier.py +482 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__init__.py +6 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/base_data_scheduler.py +199 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__init__.py +8 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/base_data_sparsifier.py +334 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py +204 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/__init__.py +0 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__init__.py +0 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/_data_sparstity_utils.py +44 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/data_sparsity.py +181 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/quantization_utils.py +154 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/FPGM_pruner.py +96 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__init__.py +5 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/base_structured_sparsifier.py +313 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/lstm_saliency_pruner.py +54 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/match_utils.py +65 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/parametrization.py +63 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/prune_functions.py +485 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/saliency_pruner.py +35 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_mappings.py +23 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__init__.py +0 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/scheduler/base_scheduler.py +173 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/scheduler/cubic_scheduler.py +114 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/scheduler/lambda_scheduler.py +64 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/linear.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from .utils import ReferenceQuantizedModule
8
+
9
+
10
+ __all__ = ["Linear"]
11
+
12
+
13
+ class Linear(nn.Linear, ReferenceQuantizedModule):
14
+ """A reference quantized linear module that fits into the FX
15
+ Graph Mode Quantization workflow
16
+ activation will be floating point Tensor, we will store floating
17
+ point weight as well in the module, but in forward we'll quantize
18
+ and dequantize the weight before running the floating point functional
19
+ linear operator.
20
+ """
21
+
22
+ _IS_REFERENCE = True
23
+
24
+ def __init__(
25
+ self,
26
+ in_features: int,
27
+ out_features: int,
28
+ bias_: bool = True,
29
+ device: torch.device | None = None,
30
+ dtype: torch.dtype | None = None,
31
+ weight_qparams: dict[str, Any] | None = None,
32
+ ) -> None:
33
+ super().__init__(in_features, out_features, bias_, device, dtype)
34
+ self._init_weight_qparams(weight_qparams, device)
35
+
36
+ def _get_name(self) -> str:
37
+ return "QuantizedLinear(Reference)"
38
+
39
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
40
+ """
41
+ we have:
42
+ w(float) -- quant - dequant \
43
+ x(float) ------------- F.linear ---
44
+
45
+ In the full model, we will see
46
+ w(float) -- quant - *dequant \
47
+ x -- quant --- *dequant -- *F.linear --- *quant - dequant
48
+ and the backend should be able to fuse the ops with `*` into a quantized linear
49
+ """
50
+ weight_quant_dequant = self.get_weight()
51
+ result = F.linear(x, weight_quant_dequant, self.bias)
52
+ return result
53
+
54
+ @classmethod
55
+ def from_float(
56
+ cls, float_linear: nn.Linear, weight_qparams: dict[str, Any]
57
+ ) -> "Linear":
58
+ qref_linear = Linear(
59
+ float_linear.in_features,
60
+ float_linear.out_features,
61
+ float_linear.bias is not None,
62
+ device=float_linear.weight.device,
63
+ dtype=float_linear.weight.dtype,
64
+ weight_qparams=weight_qparams,
65
+ )
66
+ qref_linear.weight = torch.nn.Parameter(float_linear.weight.detach())
67
+ if float_linear.bias is not None:
68
+ qref_linear.bias = torch.nn.Parameter(float_linear.bias.detach())
69
+ return qref_linear
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/rnn.py ADDED
@@ -0,0 +1,861 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Any
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from torch import _VF, Tensor
7
+ from torch.nn.utils.rnn import PackedSequence
8
+
9
+ from .utils import _quantize_and_dequantize_weight, _quantize_weight
10
+
11
+
12
+ __all__ = [
13
+ "RNNCellBase",
14
+ "RNNCell",
15
+ "LSTMCell",
16
+ "GRUCell",
17
+ "RNNBase",
18
+ "LSTM",
19
+ "GRU",
20
+ "get_quantized_weight",
21
+ ]
22
+
23
+
24
+ def _apply_permutation(tensor: Tensor, permutation: Tensor, dim: int = 1) -> Tensor:
25
+ return tensor.index_select(dim, permutation)
26
+
27
+
28
+ def _get_weight_and_quantization_params(module, wn):
29
+ weight = getattr(module, wn)
30
+ params = [weight]
31
+ for param_name in [
32
+ wn + n for n in ["_qscheme", "_dtype", "_scale", "_zero_point", "_axis_int"]
33
+ ]:
34
+ if hasattr(module, param_name):
35
+ param = getattr(module, param_name)
36
+ else:
37
+ param = None
38
+ params.append(param)
39
+ return params
40
+
41
+
42
+ def get_quantized_weight(module, wn):
43
+ if not hasattr(module, wn):
44
+ return None
45
+ params = _get_weight_and_quantization_params(module, wn)
46
+ weight = _quantize_weight(*params)
47
+ return weight
48
+
49
+
50
+ def _get_quantize_and_dequantized_weight(module, wn):
51
+ if not hasattr(module, wn):
52
+ return None
53
+ params = _get_weight_and_quantization_params(module, wn)
54
+ weight = _quantize_and_dequantize_weight(*params)
55
+ return weight
56
+
57
+
58
+ class RNNCellBase(nn.RNNCellBase):
59
+ def __init__(
60
+ self,
61
+ input_size: int,
62
+ hidden_size: int,
63
+ bias: bool,
64
+ num_chunks: int,
65
+ device=None,
66
+ dtype=None,
67
+ weight_qparams_dict=None,
68
+ ) -> None:
69
+ super().__init__(
70
+ input_size, hidden_size, bias, num_chunks, device=device, dtype=dtype
71
+ )
72
+ # TODO(jerryzh168): maybe make this arg a required arg
73
+ if weight_qparams_dict is None:
74
+ weight_qparams = {
75
+ "qscheme": torch.per_tensor_affine,
76
+ "dtype": torch.quint8,
77
+ "scale": 1.0,
78
+ "zero_point": 0,
79
+ }
80
+ weight_qparams_dict = {
81
+ "weight_ih": weight_qparams,
82
+ "weight_hh": weight_qparams,
83
+ "is_decomposed": False,
84
+ }
85
+ assert len(weight_qparams_dict) == 3, (
86
+ "Expected length for weight_qparams_dict to be 3 for QuantizedRNNCellBase(Reference)"
87
+ )
88
+ self._init_weight_qparams_dict(weight_qparams_dict, device)
89
+
90
+ def _init_weight_qparams_dict(self, weight_qparams_dict, device):
91
+ assert weight_qparams_dict is not None
92
+ self.is_decomposed = weight_qparams_dict["is_decomposed"]
93
+ for key, weight_qparams in weight_qparams_dict.items():
94
+ if key == "is_decomposed":
95
+ continue
96
+ # TODO: refactor the duplicated code to utils.py
97
+ weight_qscheme = weight_qparams["qscheme"]
98
+ weight_dtype = weight_qparams["dtype"]
99
+ setattr(self, key + "_qscheme", weight_qscheme)
100
+ setattr(self, key + "_dtype", weight_dtype)
101
+ assert weight_qscheme in [
102
+ None,
103
+ torch.per_tensor_affine,
104
+ torch.per_channel_affine,
105
+ ], Exception(
106
+ f"qscheme: {weight_qscheme} is not support in {self._get_name()}"
107
+ )
108
+ if weight_qscheme is not None:
109
+ scale = weight_qparams["scale"]
110
+ scale_tensor = (
111
+ scale.detach().clone()
112
+ if isinstance(scale, torch.Tensor)
113
+ else torch.tensor(scale, dtype=torch.float, device=device)
114
+ )
115
+ self.register_buffer(key + "_scale", scale_tensor)
116
+ zp = weight_qparams["zero_point"]
117
+ zp_tensor = (
118
+ zp.detach().clone()
119
+ if isinstance(zp, torch.Tensor)
120
+ else torch.tensor(zp, dtype=torch.int, device=device)
121
+ )
122
+ self.register_buffer(key + "_zero_point", zp_tensor)
123
+ if weight_qscheme == torch.per_channel_affine:
124
+ axis = weight_qparams["axis"]
125
+ axis_tensor = (
126
+ axis.detach().clone()
127
+ if isinstance(axis, torch.Tensor)
128
+ else torch.tensor(axis, dtype=torch.int, device=device)
129
+ )
130
+ self.register_buffer(key + "_axis", axis_tensor)
131
+ else:
132
+ # added for TorchScriptability, not used
133
+ self.register_buffer(
134
+ key + "_axis", torch.tensor(0, dtype=torch.int, device=device)
135
+ )
136
+ setattr(self, key + "_axis_int", getattr(self, key + "_axis").item())
137
+
138
+ def _get_name(self):
139
+ return "QuantizedRNNCellBase(Reference)"
140
+
141
+ def get_quantized_weight_ih(self):
142
+ return get_quantized_weight(self, "weight_ih")
143
+
144
+ def get_quantized_weight_hh(self):
145
+ return get_quantized_weight(self, "weight_hh")
146
+
147
+ def get_weight_ih(self):
148
+ return _get_quantize_and_dequantized_weight(self, "weight_ih")
149
+
150
+ def get_weight_hh(self):
151
+ return _get_quantize_and_dequantized_weight(self, "weight_hh")
152
+
153
+
154
+ class RNNCell(RNNCellBase):
155
+ """
156
+ We'll store weight_qparams for all the weights (weight_ih and weight_hh),
157
+ we need to pass in a `weight_qparams_dict` that maps from weight name,
158
+ e.g. weight_ih, to the weight_qparams for that weight
159
+ """
160
+
161
+ def __init__(
162
+ self,
163
+ input_size: int,
164
+ hidden_size: int,
165
+ bias: bool = True,
166
+ nonlinearity: str = "tanh",
167
+ device=None,
168
+ dtype=None,
169
+ weight_qparams_dict: dict[str, Any] | None = None,
170
+ ) -> None:
171
+ factory_kwargs = {
172
+ "device": device,
173
+ "dtype": dtype,
174
+ "weight_qparams_dict": weight_qparams_dict,
175
+ }
176
+ super().__init__(input_size, hidden_size, bias, num_chunks=1, **factory_kwargs)
177
+ self.nonlinearity = nonlinearity
178
+
179
+ def _get_name(self):
180
+ return "QuantizedRNNCell(Reference)"
181
+
182
+ # TODO: refactor nn.RNNCell to have a _forward that takes weight_ih and weight_hh as input
183
+ # and remove duplicated code, same for the other two Cell modules
184
+ def forward(self, input: Tensor, hx: Tensor | None = None) -> Tensor:
185
+ assert input.dim() in (
186
+ 1,
187
+ 2,
188
+ ), (
189
+ f"RNNCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
190
+ )
191
+ is_batched = input.dim() == 2
192
+ if not is_batched:
193
+ input = input.unsqueeze(0)
194
+
195
+ if hx is None:
196
+ hx = torch.zeros(
197
+ input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
198
+ )
199
+ else:
200
+ hx = hx.unsqueeze(0) if not is_batched else hx
201
+
202
+ if self.nonlinearity == "tanh":
203
+ ret = _VF.rnn_tanh_cell(
204
+ input,
205
+ hx,
206
+ self.get_weight_ih(),
207
+ self.get_weight_hh(),
208
+ self.bias_ih,
209
+ self.bias_hh,
210
+ )
211
+ elif self.nonlinearity == "relu":
212
+ ret = _VF.rnn_relu_cell(
213
+ input,
214
+ hx,
215
+ self.get_weight_ih(),
216
+ self.get_weight_hh(),
217
+ self.bias_ih,
218
+ self.bias_hh,
219
+ )
220
+ else:
221
+ ret = input # TODO: remove when jit supports exception flow
222
+ raise RuntimeError(f"Unknown nonlinearity: {self.nonlinearity}")
223
+
224
+ if not is_batched:
225
+ ret = ret.squeeze(0)
226
+
227
+ return ret
228
+
229
+ @classmethod
230
+ def from_float(cls, mod, weight_qparams_dict):
231
+ ref_mod = cls(
232
+ mod.input_size,
233
+ mod.hidden_size,
234
+ mod.bias,
235
+ mod.nonlinearity,
236
+ mod.weight_ih.device,
237
+ mod.weight_ih.dtype,
238
+ weight_qparams_dict,
239
+ )
240
+ ref_mod.weight_ih = mod.weight_ih
241
+ ref_mod.weight_hh = mod.weight_hh
242
+ ref_mod.bias_ih = mod.bias_ih
243
+ ref_mod.bias_hh = mod.bias_hh
244
+ return ref_mod
245
+
246
+
247
+ class LSTMCell(RNNCellBase):
248
+ """
249
+ We'll store weight_qparams for all the weights (weight_ih and weight_hh),
250
+ we need to pass in a `weight_qparams_dict` that maps from weight name,
251
+ e.g. weight_ih, to the weight_qparams for that weight
252
+ """
253
+
254
+ def __init__(
255
+ self,
256
+ input_size: int,
257
+ hidden_size: int,
258
+ bias: bool = True,
259
+ device=None,
260
+ dtype=None,
261
+ weight_qparams_dict: dict[str, Any] | None = None,
262
+ ) -> None:
263
+ factory_kwargs = {
264
+ "device": device,
265
+ "dtype": dtype,
266
+ "weight_qparams_dict": weight_qparams_dict,
267
+ }
268
+ super().__init__(input_size, hidden_size, bias, num_chunks=4, **factory_kwargs)
269
+
270
+ def _get_name(self):
271
+ return "QuantizedLSTMCell(Reference)"
272
+
273
+ def forward(
274
+ self, input: Tensor, hx: tuple[Tensor, Tensor] | None = None
275
+ ) -> tuple[Tensor, Tensor]:
276
+ assert input.dim() in (
277
+ 1,
278
+ 2,
279
+ ), (
280
+ f"LSTMCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
281
+ )
282
+ is_batched = input.dim() == 2
283
+ if not is_batched:
284
+ input = input.unsqueeze(0)
285
+
286
+ if hx is None:
287
+ zeros = torch.zeros(
288
+ input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
289
+ )
290
+ hx = (zeros, zeros)
291
+ else:
292
+ hx = (hx[0].unsqueeze(0), hx[1].unsqueeze(0)) if not is_batched else hx
293
+
294
+ ret = _VF.lstm_cell(
295
+ input,
296
+ hx,
297
+ self.get_weight_ih(),
298
+ self.get_weight_hh(),
299
+ self.bias_ih,
300
+ self.bias_hh,
301
+ )
302
+
303
+ if not is_batched:
304
+ ret = (ret[0].squeeze(0), ret[1].squeeze(0))
305
+ return ret
306
+
307
+ @classmethod
308
+ def from_float(cls, mod, weight_qparams_dict, use_precomputed_fake_quant=False):
309
+ ref_mod = cls(
310
+ mod.input_size,
311
+ mod.hidden_size,
312
+ mod.bias,
313
+ mod.weight_ih.device,
314
+ mod.weight_ih.dtype,
315
+ weight_qparams_dict,
316
+ )
317
+ ref_mod.weight_ih = mod.weight_ih
318
+ ref_mod.weight_hh = mod.weight_hh
319
+ ref_mod.bias_ih = mod.bias_ih
320
+ ref_mod.bias_hh = mod.bias_hh
321
+ return ref_mod
322
+
323
+
324
+ class GRUCell(RNNCellBase):
325
+ """
326
+ We'll store weight_qparams for all the weights (weight_ih and weight_hh),
327
+ we need to pass in a `weight_qparams_dict` that maps from weight name,
328
+ e.g. weight_ih, to the weight_qparams for that weight
329
+ """
330
+
331
+ def __init__(
332
+ self,
333
+ input_size: int,
334
+ hidden_size: int,
335
+ bias: bool = True,
336
+ device=None,
337
+ dtype=None,
338
+ weight_qparams_dict: dict[str, Any] | None = None,
339
+ ) -> None:
340
+ factory_kwargs = {
341
+ "device": device,
342
+ "dtype": dtype,
343
+ "weight_qparams_dict": weight_qparams_dict,
344
+ }
345
+ super().__init__(input_size, hidden_size, bias, num_chunks=3, **factory_kwargs)
346
+
347
+ def _get_name(self):
348
+ return "QuantizedGRUCell(Reference)"
349
+
350
+ def forward(self, input: Tensor, hx: Tensor | None = None) -> Tensor:
351
+ assert input.dim() in (
352
+ 1,
353
+ 2,
354
+ ), (
355
+ f"GRUCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
356
+ )
357
+ is_batched = input.dim() == 2
358
+ if not is_batched:
359
+ input = input.unsqueeze(0)
360
+
361
+ if hx is None:
362
+ hx = torch.zeros(
363
+ input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
364
+ )
365
+ else:
366
+ hx = hx.unsqueeze(0) if not is_batched else hx
367
+
368
+ ret = _VF.gru_cell(
369
+ input,
370
+ hx,
371
+ self.get_weight_ih(),
372
+ self.get_weight_hh(),
373
+ self.bias_ih,
374
+ self.bias_hh,
375
+ )
376
+
377
+ if not is_batched:
378
+ ret = ret.squeeze(0)
379
+
380
+ return ret
381
+
382
+ @classmethod
383
+ def from_float(cls, mod, weight_qparams_dict):
384
+ ref_mod = cls(
385
+ mod.input_size,
386
+ mod.hidden_size,
387
+ mod.bias,
388
+ mod.weight_ih.device,
389
+ mod.weight_ih.dtype,
390
+ weight_qparams_dict,
391
+ )
392
+ ref_mod.weight_ih = mod.weight_ih
393
+ ref_mod.weight_hh = mod.weight_hh
394
+ ref_mod.bias_ih = mod.bias_ih
395
+ ref_mod.bias_hh = mod.bias_hh
396
+ return ref_mod
397
+
398
+
399
+ class RNNBase(nn.RNNBase):
400
+ def __init__(
401
+ self,
402
+ mode: str,
403
+ input_size: int,
404
+ hidden_size: int,
405
+ num_layers: int = 1,
406
+ bias: bool = True,
407
+ batch_first: bool = False,
408
+ dropout: float = 0.0,
409
+ bidirectional: bool = False,
410
+ proj_size: int = 0,
411
+ device=None,
412
+ dtype=None,
413
+ weight_qparams_dict: dict[str, Any] | None = None,
414
+ ) -> None:
415
+ super().__init__(
416
+ mode,
417
+ input_size,
418
+ hidden_size,
419
+ num_layers,
420
+ bias,
421
+ batch_first,
422
+ dropout,
423
+ bidirectional,
424
+ proj_size,
425
+ device,
426
+ dtype,
427
+ )
428
+ # TODO(jerryzh168): maybe make this arg a required arg
429
+ if weight_qparams_dict is None:
430
+ weight_qparams = {
431
+ "qscheme": torch.per_tensor_affine,
432
+ "dtype": torch.quint8,
433
+ "scale": 1.0,
434
+ "zero_point": 0,
435
+ }
436
+ weight_qparams_dict = {"is_decomposed": False} # type: ignore[dict-item]
437
+ for wn in self._flat_weights_names:
438
+ if wn.startswith("weight"):
439
+ weight_qparams_dict[wn] = weight_qparams
440
+ self._init_weight_qparams_dict(weight_qparams_dict, device)
441
+
442
+ def _init_weight_qparams_dict(self, weight_qparams_dict, device):
443
+ self.is_decomposed = weight_qparams_dict["is_decomposed"]
444
+ for key, weight_qparams in weight_qparams_dict.items():
445
+ if key == "is_decomposed":
446
+ continue
447
+ weight_qscheme = weight_qparams["qscheme"]
448
+ weight_dtype = weight_qparams["dtype"]
449
+ setattr(self, key + "_qscheme", weight_qscheme)
450
+ setattr(self, key + "_dtype", weight_dtype)
451
+ assert weight_qscheme in [
452
+ None,
453
+ torch.per_tensor_affine,
454
+ torch.per_channel_affine,
455
+ ], Exception(
456
+ f"qscheme: {weight_qscheme} is not support in {self._get_name()}"
457
+ )
458
+ if weight_qscheme is not None:
459
+ self.register_buffer(
460
+ key + "_scale",
461
+ torch.tensor(
462
+ weight_qparams["scale"], dtype=torch.float, device=device
463
+ ),
464
+ )
465
+ self.register_buffer(
466
+ key + "_zero_point",
467
+ torch.tensor(
468
+ weight_qparams["zero_point"], dtype=torch.int, device=device
469
+ ),
470
+ )
471
+ if weight_qscheme == torch.per_channel_affine:
472
+ self.register_buffer(
473
+ key + "_axis",
474
+ torch.tensor(
475
+ weight_qparams["axis"], dtype=torch.int, device=device
476
+ ),
477
+ )
478
+ else:
479
+ # added for TorchScriptability, not used
480
+ self.register_buffer(
481
+ key + "_axis", torch.tensor(0, dtype=torch.int, device=device)
482
+ )
483
+ setattr(self, key + "_axis_int", getattr(self, key + "_axis").item())
484
+
485
+
486
+ class LSTM(RNNBase):
487
+ """Reference Quantized LSTM Module
488
+ We'll store weight_qparams for all the weights in _flat_weights, we need to pass in
489
+ a `weight_qparams_dict` that maps from weight name, e.g. weight_ih_l0,
490
+ to the weight_qparams for that weight
491
+ """
492
+
493
+ def __init__(self, *args, **kwargs):
494
+ super().__init__("LSTM", *args, **kwargs)
495
+
496
+ # Same as above, see torch/nn/modules/module.py::_forward_unimplemented
497
+ def permute_hidden( # type: ignore[override]
498
+ self,
499
+ hx: tuple[Tensor, Tensor],
500
+ permutation: Tensor | None,
501
+ ) -> tuple[Tensor, Tensor]:
502
+ if permutation is None:
503
+ return hx
504
+ return _apply_permutation(hx[0], permutation), _apply_permutation(
505
+ hx[1], permutation
506
+ )
507
+
508
+ def get_expected_cell_size(
509
+ self, input: Tensor, batch_sizes: Tensor | None
510
+ ) -> tuple[int, int, int]:
511
+ if batch_sizes is not None:
512
+ mini_batch = int(batch_sizes[0])
513
+ else:
514
+ mini_batch = input.size(0) if self.batch_first else input.size(1)
515
+ num_directions = 2 if self.bidirectional else 1
516
+ expected_hidden_size = (
517
+ self.num_layers * num_directions,
518
+ mini_batch,
519
+ self.hidden_size,
520
+ )
521
+ return expected_hidden_size
522
+
523
+ # In the future, we should prevent mypy from applying contravariance rules here.
524
+ # See torch/nn/modules/module.py::_forward_unimplemented
525
+ def check_forward_args( # type: ignore[override]
526
+ self,
527
+ input: Tensor,
528
+ hidden: tuple[Tensor, Tensor],
529
+ batch_sizes: Tensor | None,
530
+ ):
531
+ self.check_input(input, batch_sizes)
532
+ self.check_hidden_size(
533
+ hidden[0],
534
+ self.get_expected_hidden_size(input, batch_sizes),
535
+ "Expected hidden[0] size {}, got {}",
536
+ )
537
+ self.check_hidden_size(
538
+ hidden[1],
539
+ self.get_expected_cell_size(input, batch_sizes),
540
+ "Expected hidden[1] size {}, got {}",
541
+ )
542
+
543
+ def get_quantized_weight_bias_dict(self):
544
+ """dictionary from flat_weight_name to quantized weight or (unquantized) bias
545
+ e.g.
546
+ {
547
+ "weight_ih_l0": quantized_weight,
548
+ "bias_ih_l0": unquantized_bias,
549
+ ...
550
+ }
551
+ """
552
+ quantized_weight_bias_dict = {}
553
+ for wn in self._flat_weights_names:
554
+ if hasattr(self, wn):
555
+ if wn.startswith("weight"):
556
+ weight_or_bias = get_quantized_weight(self, wn)
557
+ else:
558
+ weight_or_bias = getattr(self, wn)
559
+ else:
560
+ weight_or_bias = None
561
+ quantized_weight_bias_dict[wn] = weight_or_bias
562
+ return quantized_weight_bias_dict
563
+
564
+ def get_flat_weights(self):
565
+ flat_weights = []
566
+ for wn in self._flat_weights_names:
567
+ if hasattr(self, wn):
568
+ weight = getattr(self, wn)
569
+ if wn.startswith("weight"):
570
+ params = _get_weight_and_quantization_params(self, wn)
571
+ weight = _quantize_and_dequantize_weight(*params)
572
+ else:
573
+ weight = None
574
+ flat_weights.append(weight)
575
+ return flat_weights
576
+
577
+ def forward(self, input, hx=None): # noqa: F811
578
+ orig_input = input
579
+ # xxx: isinstance check needs to be in conditional for TorchScript to compile
580
+ batch_sizes = None
581
+ if isinstance(orig_input, PackedSequence):
582
+ input, batch_sizes, sorted_indices, unsorted_indices = input
583
+ max_batch_size = int(batch_sizes[0])
584
+ else:
585
+ batch_sizes = None
586
+ is_batched = input.dim() == 3
587
+ batch_dim = 0 if self.batch_first else 1
588
+ if not is_batched:
589
+ input = input.unsqueeze(batch_dim)
590
+ max_batch_size = input.size(0) if self.batch_first else input.size(1)
591
+ sorted_indices = None
592
+ unsorted_indices = None
593
+
594
+ if hx is None:
595
+ num_directions = 2 if self.bidirectional else 1
596
+ real_hidden_size = (
597
+ self.proj_size if self.proj_size > 0 else self.hidden_size
598
+ )
599
+ h_zeros = torch.zeros(
600
+ self.num_layers * num_directions,
601
+ max_batch_size,
602
+ real_hidden_size,
603
+ dtype=input.dtype,
604
+ device=input.device,
605
+ )
606
+ c_zeros = torch.zeros(
607
+ self.num_layers * num_directions,
608
+ max_batch_size,
609
+ self.hidden_size,
610
+ dtype=input.dtype,
611
+ device=input.device,
612
+ )
613
+ hx = (h_zeros, c_zeros)
614
+ else:
615
+ if batch_sizes is None: # If not PackedSequence input.
616
+ if is_batched: # type: ignore[possibly-undefined]
617
+ if hx[0].dim() != 3 or hx[1].dim() != 3:
618
+ msg = (
619
+ "For batched 3-D input, hx and cx should "
620
+ f"also be 3-D but got ({hx[0].dim()}-D, {hx[1].dim()}-D) tensors"
621
+ )
622
+ raise RuntimeError(msg)
623
+ else:
624
+ if hx[0].dim() != 2 or hx[1].dim() != 2:
625
+ msg = (
626
+ "For unbatched 2-D input, hx and cx should "
627
+ f"also be 2-D but got ({hx[0].dim()}-D, {hx[1].dim()}-D) tensors"
628
+ )
629
+ raise RuntimeError(msg)
630
+ hx = (hx[0].unsqueeze(1), hx[1].unsqueeze(1))
631
+
632
+ # Each batch of the hidden state should match the input sequence that
633
+ # the user believes he/she is passing in.
634
+ hx = self.permute_hidden(hx, sorted_indices)
635
+
636
+ self.check_forward_args(input, hx, batch_sizes)
637
+ if batch_sizes is None:
638
+ result = _VF.lstm(
639
+ input,
640
+ hx,
641
+ self.get_flat_weights(),
642
+ self.bias,
643
+ self.num_layers,
644
+ self.dropout,
645
+ self.training,
646
+ self.bidirectional,
647
+ self.batch_first,
648
+ )
649
+ else:
650
+ result = _VF.lstm(
651
+ input,
652
+ batch_sizes,
653
+ hx,
654
+ self.get_flat_weights(),
655
+ self.bias,
656
+ self.num_layers,
657
+ self.dropout,
658
+ self.training,
659
+ self.bidirectional,
660
+ )
661
+ output = result[0]
662
+ hidden = result[1:]
663
+ # xxx: isinstance check needs to be in conditional for TorchScript to compile
664
+ if isinstance(orig_input, PackedSequence):
665
+ output_packed = PackedSequence(
666
+ output,
667
+ # pyrefly: ignore [bad-argument-type]
668
+ batch_sizes,
669
+ sorted_indices,
670
+ unsorted_indices,
671
+ )
672
+ return output_packed, self.permute_hidden(hidden, unsorted_indices)
673
+ else:
674
+ if not is_batched: # type: ignore[possibly-undefined]
675
+ output = output.squeeze(batch_dim) # type: ignore[possibly-undefined]
676
+ hidden = (hidden[0].squeeze(1), hidden[1].squeeze(1))
677
+ return output, self.permute_hidden(hidden, unsorted_indices)
678
+
679
+ def _get_name(self):
680
+ return "QuantizedLSTM(Reference)"
681
+
682
+ @classmethod
683
+ def from_float(cls, mod, weight_qparams_dict):
684
+ ref_mod = cls(
685
+ mod.input_size,
686
+ mod.hidden_size,
687
+ mod.num_layers,
688
+ mod.bias,
689
+ mod.batch_first,
690
+ mod.dropout,
691
+ mod.bidirectional,
692
+ weight_qparams_dict=weight_qparams_dict,
693
+ )
694
+ for wn in mod._flat_weights_names:
695
+ setattr(ref_mod, wn, getattr(mod, wn))
696
+ return ref_mod
697
+
698
+
699
+ class GRU(RNNBase):
700
+ """Reference Quantized GRU Module
701
+ We'll store weight_qparams for all the weights in _flat_weights, we need to pass in
702
+ a `weight_qparams_dict` that maps from weight name, e.g. weight_ih_l0,
703
+ to the weight_qparams for that weight
704
+ """
705
+
706
+ def __init__(self, *args, **kwargs):
707
+ if "proj_size" in kwargs:
708
+ raise ValueError(
709
+ "proj_size argument is only supported for LSTM, not RNN or GRU"
710
+ )
711
+ super().__init__("GRU", *args, **kwargs)
712
+
713
+ def get_quantized_weight_bias_dict(self):
714
+ """dictionary from flat_weight_name to quantized weight or (unquantized) bias
715
+ e.g.
716
+ {
717
+ "weight_ih_l0": quantized_weight,
718
+ "bias_ih_l0": unquantized_bias,
719
+ ...
720
+ }
721
+ """
722
+ quantized_weight_bias_dict = {}
723
+ for wn in self._flat_weights_names:
724
+ if hasattr(self, wn):
725
+ if wn.startswith("weight"):
726
+ weight_or_bias = get_quantized_weight(self, wn)
727
+ else:
728
+ weight_or_bias = getattr(self, wn)
729
+ else:
730
+ weight_or_bias = None
731
+ quantized_weight_bias_dict[wn] = weight_or_bias
732
+ return quantized_weight_bias_dict
733
+
734
+ def get_flat_weights(self):
735
+ flat_weights = []
736
+ for wn in self._flat_weights_names:
737
+ if hasattr(self, wn):
738
+ weight = getattr(self, wn)
739
+ if wn.startswith("weight"):
740
+ params = _get_weight_and_quantization_params(self, wn)
741
+ weight = _quantize_and_dequantize_weight(*params)
742
+ else:
743
+ weight = None
744
+ flat_weights.append(weight)
745
+ return flat_weights
746
+
747
+ def forward(self, input, hx=None): # noqa: F811
748
+ # Note: this is copied from the forward of GRU in https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/rnn.py
749
+ # only changed self._flat_weights to self.get_flat_weights()
750
+ # TODO: maybe we can try inheriting from that class and define get_flat_weights
751
+ # as a @property? this might interfere with TorchScript, if we remove that
752
+ # requirement in the future we should be able to do this
753
+ orig_input = input
754
+ # xxx: isinstance check needs to be in conditional for TorchScript to compile
755
+ if isinstance(orig_input, PackedSequence):
756
+ input, batch_sizes, sorted_indices, unsorted_indices = input
757
+ max_batch_size = int(batch_sizes[0])
758
+ else:
759
+ batch_sizes = None
760
+ assert input.dim() in (
761
+ 2,
762
+ 3,
763
+ ), (
764
+ f"GRU: Expected input to be 2-D or 3-D but received {input.dim()}-D tensor"
765
+ )
766
+ is_batched = input.dim() == 3
767
+ batch_dim = 0 if self.batch_first else 1
768
+ if not is_batched:
769
+ input = input.unsqueeze(batch_dim)
770
+ if hx is not None:
771
+ if hx.dim() != 2:
772
+ raise RuntimeError(
773
+ f"For unbatched 2-D input, hx should also be 2-D but got {hx.dim()}-D tensor"
774
+ )
775
+ hx = hx.unsqueeze(1)
776
+ else:
777
+ if hx is not None and hx.dim() != 3:
778
+ raise RuntimeError(
779
+ f"For batched 3-D input, hx should also be 3-D but got {hx.dim()}-D tensor"
780
+ )
781
+ max_batch_size = input.size(0) if self.batch_first else input.size(1)
782
+ sorted_indices = None
783
+ unsorted_indices = None
784
+
785
+ if hx is None:
786
+ num_directions = 2 if self.bidirectional else 1
787
+ hx = torch.zeros(
788
+ self.num_layers * num_directions,
789
+ max_batch_size,
790
+ self.hidden_size,
791
+ dtype=input.dtype,
792
+ device=input.device,
793
+ )
794
+ else:
795
+ # Each batch of the hidden state should match the input sequence that
796
+ # the user believes he/she is passing in.
797
+ hx = self.permute_hidden(hx, sorted_indices)
798
+
799
+ self.check_forward_args(input, hx, batch_sizes)
800
+ if batch_sizes is None:
801
+ result = _VF.gru(
802
+ input,
803
+ hx,
804
+ self.get_flat_weights(),
805
+ self.bias,
806
+ self.num_layers,
807
+ self.dropout,
808
+ self.training,
809
+ self.bidirectional,
810
+ self.batch_first,
811
+ )
812
+ else:
813
+ result = _VF.gru(
814
+ input,
815
+ batch_sizes,
816
+ hx,
817
+ self.get_flat_weights(),
818
+ self.bias,
819
+ self.num_layers,
820
+ self.dropout,
821
+ self.training,
822
+ self.bidirectional,
823
+ )
824
+ output = result[0]
825
+ hidden = result[1]
826
+
827
+ # xxx: isinstance check needs to be in conditional for TorchScript to compile
828
+ if isinstance(orig_input, PackedSequence):
829
+ output_packed = PackedSequence(
830
+ output,
831
+ # pyrefly: ignore [bad-argument-type]
832
+ batch_sizes,
833
+ sorted_indices,
834
+ unsorted_indices,
835
+ )
836
+ return output_packed, self.permute_hidden(hidden, unsorted_indices)
837
+ else:
838
+ if not is_batched: # type: ignore[possibly-undefined]
839
+ output = output.squeeze(batch_dim) # type: ignore[possibly-undefined]
840
+ hidden = hidden.squeeze(1)
841
+
842
+ return output, self.permute_hidden(hidden, unsorted_indices)
843
+
844
+ def _get_name(self):
845
+ return "QuantizedGRU(Reference)"
846
+
847
+ @classmethod
848
+ def from_float(cls, mod, weight_qparams_dict):
849
+ ref_mod = cls(
850
+ mod.input_size,
851
+ mod.hidden_size,
852
+ mod.num_layers,
853
+ mod.bias,
854
+ mod.batch_first,
855
+ mod.dropout,
856
+ mod.bidirectional,
857
+ weight_qparams_dict=weight_qparams_dict,
858
+ )
859
+ for wn in mod._flat_weights_names:
860
+ setattr(ref_mod, wn, getattr(mod, wn))
861
+ return ref_mod
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/sparse.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Any
3
+
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from torch import Tensor
7
+
8
+ from .utils import ReferenceQuantizedModule
9
+
10
+
11
+ __all__ = ["Embedding", "EmbeddingBag"]
12
+
13
+
14
+ class Embedding(nn.Embedding, ReferenceQuantizedModule):
15
+ """A reference quantized Embedding module that fits into the
16
+ FX Graph Mode Quantization workflow, activation will be floating point Tensor,
17
+ we will store floating point weight as well in the module, but in forward we'll
18
+ quantize and dequantize the weight before running the floating point functional
19
+ embedding operator.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ num_embeddings: int,
25
+ embedding_dim: int,
26
+ padding_idx: int | None = None,
27
+ max_norm: float | None = None,
28
+ norm_type: float = 2.0,
29
+ scale_grad_by_freq: bool = False,
30
+ sparse: bool = False,
31
+ _weight: Tensor | None = None,
32
+ device=None,
33
+ dtype=None,
34
+ weight_qparams: dict[str, Any] | None = None,
35
+ ) -> None:
36
+ super().__init__(
37
+ num_embeddings,
38
+ embedding_dim,
39
+ padding_idx,
40
+ max_norm,
41
+ norm_type,
42
+ scale_grad_by_freq,
43
+ sparse,
44
+ _weight,
45
+ # pyrefly: ignore [bad-argument-type]
46
+ device,
47
+ dtype,
48
+ )
49
+ self._init_weight_qparams(weight_qparams, device)
50
+
51
+ def _get_name(self):
52
+ return "QuantizedEmbedding(Reference)"
53
+
54
+ def forward(self, input: Tensor) -> Tensor:
55
+ weight_quant_dequant = self.get_weight()
56
+ return F.embedding(
57
+ input,
58
+ weight_quant_dequant,
59
+ self.padding_idx,
60
+ self.max_norm,
61
+ self.norm_type,
62
+ self.scale_grad_by_freq,
63
+ self.sparse,
64
+ )
65
+
66
+ @classmethod
67
+ def from_float(cls, mod, weight_qparams):
68
+ return cls(
69
+ mod.num_embeddings,
70
+ mod.embedding_dim,
71
+ mod.padding_idx,
72
+ mod.max_norm,
73
+ mod.norm_type,
74
+ mod.scale_grad_by_freq,
75
+ mod.sparse,
76
+ mod.weight,
77
+ mod.weight.device,
78
+ mod.weight.dtype,
79
+ weight_qparams,
80
+ )
81
+
82
+
83
+ class EmbeddingBag(nn.EmbeddingBag, ReferenceQuantizedModule):
84
+ """A reference quantized EmbeddingBag module that fits into the
85
+ FX Graph Mode Quantization workflow, activation will be floating point Tensor,
86
+ we will store floating point weight as well in the module, but in forward we'll
87
+ quantize and dequantize the weight before running the floating point functional
88
+ embedding operator.
89
+ """
90
+
91
+ def __init__(
92
+ self,
93
+ num_embeddings: int,
94
+ embedding_dim: int,
95
+ max_norm: float | None = None,
96
+ norm_type: float = 2.0,
97
+ scale_grad_by_freq: bool = False,
98
+ mode: str = "mean",
99
+ sparse: bool = False,
100
+ _weight: Tensor | None = None,
101
+ include_last_offset: bool = False,
102
+ padding_idx: int | None = None,
103
+ device=None,
104
+ dtype=None,
105
+ weight_qparams: dict[str, Any] | None = None,
106
+ ) -> None:
107
+ super().__init__(
108
+ num_embeddings,
109
+ embedding_dim,
110
+ max_norm,
111
+ norm_type,
112
+ scale_grad_by_freq,
113
+ mode,
114
+ sparse,
115
+ _weight,
116
+ include_last_offset,
117
+ padding_idx,
118
+ device,
119
+ dtype,
120
+ )
121
+ self._init_weight_qparams(weight_qparams, device)
122
+
123
+ def _get_name(self):
124
+ return "QuantizedEmbedding(Reference)"
125
+
126
+ def forward(
127
+ self,
128
+ input: Tensor,
129
+ offsets: Tensor | None = None,
130
+ per_sample_weights: Tensor | None = None,
131
+ ) -> Tensor:
132
+ weight_quant_dequant = self.get_weight()
133
+ return F.embedding_bag(
134
+ input,
135
+ weight_quant_dequant,
136
+ offsets,
137
+ self.max_norm,
138
+ self.norm_type,
139
+ self.scale_grad_by_freq,
140
+ self.mode,
141
+ self.sparse,
142
+ per_sample_weights,
143
+ self.include_last_offset,
144
+ self.padding_idx,
145
+ )
146
+
147
+ @classmethod
148
+ def from_float(cls, mod, weight_qparams, use_precomputed_fake_quant=False):
149
+ return cls(
150
+ mod.num_embeddings,
151
+ mod.embedding_dim,
152
+ mod.max_norm,
153
+ mod.norm_type,
154
+ mod.scale_grad_by_freq,
155
+ mod.mode,
156
+ mod.sparse,
157
+ mod.weight,
158
+ mod.include_last_offset,
159
+ mod.padding_idx,
160
+ mod.weight.device,
161
+ mod.weight.dtype,
162
+ weight_qparams,
163
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/quantized/reference/modules/utils.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import typing
3
+
4
+ import torch
5
+
6
+
7
+ __all__ = [
8
+ "ReferenceQuantizedModule",
9
+ ]
10
+
11
+
12
+ class ReferenceQuantizedModule(torch.nn.Module):
13
+ def _init_weight_qparams(self, weight_qparams, device):
14
+ if weight_qparams is None:
15
+ weight_qparams = {
16
+ "qscheme": torch.per_tensor_affine,
17
+ "dtype": torch.quint8,
18
+ "scale": 1.0,
19
+ "zero_point": 0,
20
+ }
21
+ # pyrefly: ignore [bad-assignment]
22
+ self.weight_qscheme: torch.qscheme = weight_qparams["qscheme"]
23
+ self.weight_dtype = weight_qparams["dtype"]
24
+ assert self.weight_qscheme in [
25
+ None,
26
+ torch.per_tensor_affine,
27
+ torch.per_channel_affine,
28
+ torch.per_channel_affine_float_qparams,
29
+ ], (
30
+ f"qscheme: {self.weight_qscheme} is not support in reference quantized {self._get_name()}"
31
+ )
32
+ if self.weight_dtype in [
33
+ torch.quint8,
34
+ torch.qint8,
35
+ torch.quint4x2,
36
+ torch.qint32,
37
+ ]:
38
+ zero_point_dtype = (
39
+ weight_qparams["zero_point"].dtype
40
+ if isinstance(weight_qparams["zero_point"], torch.Tensor)
41
+ else torch.int
42
+ )
43
+ w_scale = weight_qparams["scale"]
44
+ w_scale_tensor = (
45
+ w_scale.detach().clone()
46
+ if isinstance(w_scale, torch.Tensor)
47
+ else torch.tensor(w_scale, dtype=torch.float, device=device)
48
+ )
49
+ self.register_buffer("weight_scale", w_scale_tensor)
50
+ w_zp = weight_qparams["zero_point"]
51
+ w_zp_tensor = (
52
+ w_zp.detach().clone()
53
+ if isinstance(w_zp, torch.Tensor)
54
+ else torch.tensor(w_zp, dtype=zero_point_dtype, device=device)
55
+ )
56
+ self.register_buffer("weight_zero_point", w_zp_tensor)
57
+ if self.weight_qscheme in [
58
+ torch.per_channel_affine,
59
+ torch.per_channel_affine_float_qparams,
60
+ ]:
61
+ w_axis = weight_qparams["axis"]
62
+ w_axis_tensor = (
63
+ w_axis.detach().clone()
64
+ if isinstance(w_axis, torch.Tensor)
65
+ else torch.tensor(w_axis, dtype=torch.int, device=device)
66
+ )
67
+ self.register_buffer("weight_axis", w_axis_tensor)
68
+ else:
69
+ # added for TorchScriptability, not used
70
+ self.register_buffer(
71
+ "weight_axis", torch.tensor(0, dtype=torch.int, device=device)
72
+ )
73
+ else:
74
+ # added for TorchScriptability, and for torch.float
75
+ self.register_buffer(
76
+ "weight_scale", torch.tensor(1.0, dtype=torch.float, device=device)
77
+ )
78
+ self.register_buffer(
79
+ "weight_zero_point", torch.tensor(0, dtype=torch.int, device=device)
80
+ )
81
+ self.register_buffer(
82
+ "weight_axis", torch.tensor(0, dtype=torch.int, device=device)
83
+ )
84
+ # pyrefly: ignore [bad-assignment]
85
+ self.is_decomposed: bool = weight_qparams.get("is_decomposed", False)
86
+ # store weight_axis as weight_axis_int due to some constraints of torchdynamo.export
87
+ # for capturing `.item` operations
88
+ self.weight_axis_int: int = self.weight_axis.item() # type: ignore[operator, assignment]
89
+ # pyrefly: ignore [bad-assignment]
90
+ self.weight_quant_min: int | None = weight_qparams.get("quant_min")
91
+ # pyrefly: ignore [bad-assignment]
92
+ self.weight_quant_max: int | None = weight_qparams.get("quant_max")
93
+
94
+ def get_weight(self):
95
+ """
96
+ Fake quantize (quantize and dequantize) the weight with
97
+ the quantization parameters for weight, this is used to
98
+ simulate the numerics for the quantized weight in a quantized
99
+ model
100
+ """
101
+ # suppress mypy warning
102
+ assert isinstance(self.weight_scale, torch.Tensor)
103
+ assert isinstance(self.weight_zero_point, torch.Tensor)
104
+ if self.is_decomposed:
105
+ return _quantize_and_dequantize_weight_decomposed(
106
+ self.weight, # type: ignore[arg-type]
107
+ self.weight_qscheme,
108
+ # pyrefly: ignore [bad-argument-type]
109
+ self.weight_dtype,
110
+ self.weight_scale,
111
+ self.weight_zero_point,
112
+ self.weight_axis_int,
113
+ self.weight_quant_min,
114
+ self.weight_quant_max,
115
+ )
116
+ else:
117
+ return _quantize_and_dequantize_weight(
118
+ self.weight, # type: ignore[arg-type]
119
+ self.weight_qscheme,
120
+ # pyrefly: ignore [bad-argument-type]
121
+ self.weight_dtype,
122
+ self.weight_scale,
123
+ self.weight_zero_point,
124
+ self.weight_axis_int,
125
+ )
126
+
127
+ def get_quantized_weight(self):
128
+ # suppress mypy warning
129
+ assert isinstance(self.weight_scale, torch.Tensor)
130
+ assert isinstance(self.weight_zero_point, torch.Tensor)
131
+ # assert isinstance(self.weight_axis, torch.Tensor)
132
+ if self.is_decomposed:
133
+ return _quantize_weight_decomposed(
134
+ self.weight, # type: ignore[arg-type]
135
+ self.weight_qscheme,
136
+ # pyrefly: ignore [bad-argument-type]
137
+ self.weight_dtype,
138
+ self.weight_scale,
139
+ self.weight_zero_point,
140
+ self.weight_axis_int,
141
+ self.weight_quant_min,
142
+ self.weight_quant_max,
143
+ )
144
+ else:
145
+ return _quantize_weight(
146
+ self.weight, # type: ignore[arg-type]
147
+ self.weight_qscheme,
148
+ # pyrefly: ignore [bad-argument-type]
149
+ self.weight_dtype,
150
+ self.weight_scale,
151
+ self.weight_zero_point,
152
+ self.weight_axis_int,
153
+ )
154
+
155
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
156
+ super()._save_to_state_dict(destination, prefix, keep_vars)
157
+ _save_weight_qparams(
158
+ destination,
159
+ prefix,
160
+ self.weight_qscheme,
161
+ self.weight_dtype,
162
+ self.weight_scale,
163
+ self.weight_zero_point,
164
+ self.weight_axis,
165
+ )
166
+
167
+ def _load_from_state_dict(
168
+ self,
169
+ state_dict,
170
+ prefix,
171
+ local_metadata,
172
+ strict,
173
+ missing_keys,
174
+ unexpected_keys,
175
+ error_msgs,
176
+ ):
177
+ for key in _get_weight_qparam_keys(state_dict, prefix):
178
+ setattr(self, key, state_dict[prefix + key])
179
+ state_dict.pop(prefix + key)
180
+
181
+ super()._load_from_state_dict(
182
+ state_dict,
183
+ prefix,
184
+ local_metadata,
185
+ False,
186
+ missing_keys,
187
+ unexpected_keys,
188
+ error_msgs,
189
+ )
190
+
191
+
192
+ def _quantize_weight_decomposed(
193
+ weight: torch.Tensor,
194
+ weight_qscheme: torch.qscheme,
195
+ weight_dtype: torch.dtype,
196
+ weight_scale: torch.Tensor,
197
+ weight_zero_point: torch.Tensor,
198
+ weight_axis: int,
199
+ weight_quant_min: int | None,
200
+ weight_quant_max: int | None,
201
+ ) -> torch.Tensor:
202
+ _DTYPE_TO_QVALUE_BOUNDS: dict[torch.dtype, tuple[int, int]] = {
203
+ torch.uint8: (0, 255),
204
+ torch.int8: (-128, 127),
205
+ torch.int32: (-2147483648, 2147483647), # torch.jit interprets 2**31 as a float
206
+ }
207
+
208
+ # TODO: add an util function for converting qdtype to dtype
209
+ _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE = {
210
+ torch.quint8: torch.uint8,
211
+ torch.qint8: torch.int8,
212
+ torch.qint32: torch.int32,
213
+ }
214
+ if weight_qscheme == torch.per_tensor_affine:
215
+ if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
216
+ weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
217
+ if weight_quant_min is None or weight_quant_max is None:
218
+ weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[
219
+ weight_dtype_
220
+ ]
221
+ weight = torch.ops.quantized_decomposed.quantize_per_tensor(
222
+ weight,
223
+ weight_scale,
224
+ weight_zero_point,
225
+ weight_quant_min,
226
+ weight_quant_max,
227
+ weight_dtype_,
228
+ )
229
+ return weight
230
+ elif weight_qscheme in [
231
+ torch.per_channel_affine,
232
+ torch.per_channel_affine_float_qparams,
233
+ ]:
234
+ # TODO: torch.quint4x2 is not supported
235
+ if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
236
+ weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
237
+ if weight_quant_min is None or weight_quant_max is None:
238
+ weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[
239
+ weight_dtype_
240
+ ]
241
+ weight = torch.ops.quantized_decomposed.quantize_per_channel(
242
+ weight,
243
+ weight_scale,
244
+ weight_zero_point,
245
+ weight_axis,
246
+ weight_quant_min,
247
+ weight_quant_max,
248
+ weight_dtype_,
249
+ ) # type: ignore[arg-type]
250
+ return weight
251
+ raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
252
+
253
+
254
+ def _dequantize_weight_decomposed(
255
+ weight: torch.Tensor,
256
+ weight_qscheme: torch.qscheme,
257
+ weight_dtype: torch.dtype,
258
+ weight_scale: torch.Tensor,
259
+ weight_zero_point: torch.Tensor,
260
+ weight_axis: int,
261
+ weight_quant_min: int | None,
262
+ weight_quant_max: int | None,
263
+ ) -> torch.Tensor:
264
+ # TODO: get the quant_min and quant_max from activation_post_process
265
+ _DTYPE_TO_QVALUE_BOUNDS: dict[torch.dtype, tuple[int, int]] = {
266
+ torch.uint8: (0, 255),
267
+ torch.int8: (-128, 127),
268
+ torch.int32: (-2147483648, 2147483647), # torch.jit interprets 2**31 as a float
269
+ }
270
+ # TODO: add an util function for converting qdtype to dtype
271
+ _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE = {
272
+ torch.quint8: torch.uint8,
273
+ torch.qint8: torch.int8,
274
+ torch.qint32: torch.int32,
275
+ }
276
+ weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
277
+ if weight_quant_min is None or weight_quant_max is None:
278
+ weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[weight_dtype_]
279
+ if weight_qscheme == torch.per_tensor_affine:
280
+ if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
281
+ weight = torch.ops.quantized_decomposed.dequantize_per_tensor(
282
+ weight,
283
+ weight_scale,
284
+ weight_zero_point,
285
+ weight_quant_min,
286
+ weight_quant_max,
287
+ weight_dtype_,
288
+ )
289
+ return weight
290
+ elif weight_qscheme in [
291
+ torch.per_channel_affine,
292
+ torch.per_channel_affine_float_qparams,
293
+ ]:
294
+ # TODO: torch.quint4x2 is not supported
295
+ if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
296
+ weight = torch.ops.quantized_decomposed.dequantize_per_channel(
297
+ weight,
298
+ weight_scale,
299
+ weight_zero_point,
300
+ weight_axis,
301
+ weight_quant_min,
302
+ weight_quant_max,
303
+ weight_dtype_,
304
+ ) # type: ignore[arg-type]
305
+ return weight
306
+ raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
307
+
308
+
309
+ def _quantize_weight(
310
+ weight: torch.Tensor,
311
+ weight_qscheme: torch.qscheme,
312
+ weight_dtype: torch.dtype,
313
+ weight_scale: torch.Tensor,
314
+ weight_zero_point: torch.Tensor,
315
+ weight_axis_int: int,
316
+ ) -> torch.Tensor:
317
+ if weight_dtype == torch.float16:
318
+ weight = weight.to(weight_dtype)
319
+ return weight
320
+
321
+ if weight_qscheme == torch.per_tensor_affine:
322
+ if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
323
+ weight = torch.quantize_per_tensor(
324
+ weight, weight_scale, weight_zero_point, weight_dtype
325
+ )
326
+ return weight
327
+ elif weight_qscheme in [
328
+ torch.per_channel_affine,
329
+ torch.per_channel_affine_float_qparams,
330
+ ]:
331
+ if weight_dtype in [torch.quint8, torch.qint8, torch.quint4x2, torch.qint32]:
332
+ weight = torch.quantize_per_channel(
333
+ weight, weight_scale, weight_zero_point, weight_axis_int, weight_dtype
334
+ ) # type: ignore[arg-type]
335
+ return weight
336
+ raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
337
+
338
+
339
+ def _quantize_and_dequantize_weight_decomposed(
340
+ weight: torch.Tensor,
341
+ weight_qscheme: torch.qscheme,
342
+ weight_dtype: torch.dtype,
343
+ weight_scale: torch.Tensor,
344
+ weight_zero_point: torch.Tensor,
345
+ weight_axis_int: int,
346
+ weight_quant_min: int | None,
347
+ weight_quant_max: int | None,
348
+ ) -> torch.Tensor:
349
+ """Quantize and then dequantize the weight based on
350
+ the quantization parameters
351
+ """
352
+ if weight_qscheme in [
353
+ torch.per_tensor_affine,
354
+ torch.per_channel_affine,
355
+ torch.per_channel_affine_float_qparams,
356
+ ]:
357
+ weight_quant = _quantize_weight_decomposed(
358
+ weight,
359
+ weight_qscheme,
360
+ weight_dtype,
361
+ weight_scale,
362
+ weight_zero_point,
363
+ weight_axis_int,
364
+ weight_quant_min,
365
+ weight_quant_max,
366
+ )
367
+ weight_dequant = _dequantize_weight_decomposed(
368
+ weight_quant,
369
+ weight_qscheme,
370
+ weight_dtype,
371
+ weight_scale,
372
+ weight_zero_point,
373
+ weight_axis_int,
374
+ weight_quant_min,
375
+ weight_quant_max,
376
+ )
377
+ else:
378
+ weight_dequant = weight
379
+ return weight_dequant
380
+
381
+
382
+ def _quantize_and_dequantize_weight(
383
+ weight: torch.Tensor,
384
+ weight_qscheme: torch.qscheme,
385
+ weight_dtype: torch.dtype,
386
+ weight_scale: torch.Tensor,
387
+ weight_zero_point: torch.Tensor,
388
+ weight_axis_int: int,
389
+ ) -> torch.Tensor:
390
+ """Quantize and then dequantize the weight based on
391
+ the quantization parameters
392
+ """
393
+ if weight_qscheme in [
394
+ torch.per_tensor_affine,
395
+ torch.per_channel_affine,
396
+ torch.per_channel_affine_float_qparams,
397
+ ]:
398
+ weight_quant = _quantize_weight(
399
+ weight,
400
+ weight_qscheme,
401
+ weight_dtype,
402
+ weight_scale,
403
+ weight_zero_point,
404
+ weight_axis_int,
405
+ )
406
+ weight_dequant = weight_quant.dequantize()
407
+ else:
408
+ weight_dequant = weight
409
+ return weight_dequant
410
+
411
+
412
+ def _save_weight_qparams(
413
+ destination,
414
+ prefix,
415
+ weight_qscheme,
416
+ weight_dtype,
417
+ weight_scale,
418
+ weight_zero_point,
419
+ weight_axis,
420
+ ):
421
+ destination[prefix + "weight_qscheme"] = weight_qscheme
422
+ destination[prefix + "weight_dtype"] = weight_dtype
423
+ if weight_qscheme is not None:
424
+ destination[prefix + "weight_scale"] = weight_scale
425
+ destination[prefix + "weight_zero_point"] = weight_zero_point
426
+ if weight_qscheme == torch.per_channel_affine:
427
+ destination[prefix + "weight_axis"] = weight_axis
428
+
429
+
430
+ def _get_weight_qparam_keys(state_dict: dict[str, typing.Any], prefix: str):
431
+ keys = ["weight_qscheme", "weight_dtype"]
432
+ weight_qscheme = state_dict[prefix + "weight_qscheme"]
433
+ if weight_qscheme is not None:
434
+ keys.append("weight_scale")
435
+ keys.append("weight_zero_point")
436
+ if weight_qscheme == torch.quantize_per_channel:
437
+ keys.append("weight_axis")
438
+ return keys
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from . import quantized
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/quantized/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.ao.nn.sparse.quantized import dynamic
2
+
3
+ from .linear import Linear, LinearPackedParams
4
+
5
+
6
+ __all__ = [
7
+ "dynamic",
8
+ "Linear",
9
+ "LinearPackedParams",
10
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/quantized/dynamic/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .linear import Linear
2
+
3
+
4
+ __all__ = [
5
+ "Linear",
6
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/quantized/dynamic/linear.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.ao.nn.intrinsic as nni
5
+ from torch.ao.nn.quantized.modules.utils import (
6
+ _hide_packed_params_repr,
7
+ _quantize_weight,
8
+ )
9
+ from torch.ao.nn.sparse.quantized import linear
10
+ from torch.ao.nn.sparse.quantized.utils import LinearBlockSparsePattern
11
+
12
+
13
+ __all__ = ["Linear"]
14
+
15
+
16
+ class Linear(torch.nn.Module):
17
+ r"""
18
+ A dynamically quantized sparse linear module with float tensor as inputs and outputs.
19
+ """
20
+
21
+ _version = 1
22
+ _op_type = "sparse_dynamic"
23
+ _FLOAT_MODULE = torch.nn.Linear
24
+
25
+ def __init__(
26
+ self,
27
+ in_features,
28
+ out_features,
29
+ row_block_size,
30
+ col_block_size,
31
+ bias=True,
32
+ dtype=torch.qint8,
33
+ ):
34
+ super().__init__()
35
+
36
+ if dtype != torch.qint8:
37
+ raise NotImplementedError(
38
+ "Only QINT8 is supported for Sparse Quantized Linear Dynamic"
39
+ )
40
+
41
+ self.in_features = in_features
42
+ self.out_features = out_features
43
+
44
+ if bias:
45
+ bias = torch.zeros(self.out_features, dtype=torch.float)
46
+ else:
47
+ bias = None
48
+
49
+ qweight = torch._empty_affine_quantized(
50
+ [out_features, in_features], scale=1, zero_point=0, dtype=torch.qint8
51
+ )
52
+ self._packed_params = linear.LinearPackedParams(
53
+ row_block_size=row_block_size, col_block_size=col_block_size, dtype=dtype
54
+ )
55
+ self._packed_params.set_weight_bias(
56
+ qweight, bias, row_block_size, col_block_size
57
+ )
58
+
59
+ def _get_name(self):
60
+ return "SparseQuantizedDynamicLinear"
61
+
62
+ def extra_repr(self):
63
+ return f"in_features={self.in_features}, out_features={self.out_features}, qscheme={self.weight().qscheme()}"
64
+
65
+ def __repr__(self):
66
+ return _hide_packed_params_repr(self, linear.LinearPackedParams)
67
+
68
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
69
+ return torch.ops.sparse.qlinear_dynamic(x, self._packed_params._packed_params)
70
+
71
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
72
+ super()._save_to_state_dict(destination, prefix, keep_vars)
73
+ destination[prefix + "op_type"] = self._op_type
74
+
75
+ def _load_from_state_dict(
76
+ self,
77
+ state_dict,
78
+ prefix,
79
+ local_metadata,
80
+ strict,
81
+ missing_keys,
82
+ unexpected_keys,
83
+ error_msgs,
84
+ ):
85
+ op_type = int(state_dict[prefix + "op_type"])
86
+ assert op_type == "sparse", (
87
+ f"Cannot load from op_type [{op_type}], expecting [{self._op_type}]"
88
+ )
89
+ state_dict.pop(prefix + "op_type")
90
+
91
+ version = local_metadata.get("version", None)
92
+ assert version <= self._version
93
+
94
+ # Is this code valid? In old quantization it seemed to be used to load
95
+ # older model
96
+ weight = state_dict.pop(prefix + "weight")
97
+ bias = state_dict.pop(prefix + "bias")
98
+ state_dict.update(
99
+ {
100
+ prefix + "_packed_params.weight": weight,
101
+ prefix + "_packed_params.bias": bias,
102
+ }
103
+ )
104
+
105
+ super()._load_from_state_dict(
106
+ state_dict,
107
+ prefix,
108
+ local_metadata,
109
+ False,
110
+ missing_keys,
111
+ unexpected_keys,
112
+ error_msgs,
113
+ )
114
+
115
+ def _weight_bias(self):
116
+ return self._packed_params._weight_bias()
117
+
118
+ def weight(self):
119
+ return self._weight_bias()[0]
120
+
121
+ def bias(self):
122
+ return self._weight_bias()[1]
123
+
124
+ def set_weight_bias(
125
+ self,
126
+ w: torch.Tensor,
127
+ b: torch.Tensor | None,
128
+ row_block_size: int | None,
129
+ col_block_size: int | None,
130
+ ) -> None:
131
+ assert row_block_size is not None and col_block_size is not None
132
+ self.out_features = w.shape[0]
133
+ self.in_features = w.shape[1]
134
+ self._packed_params.set_weight_bias(w, b, row_block_size, col_block_size)
135
+
136
+ @classmethod
137
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
138
+ r"""Create a quantized sparse dynamic module from a float module.
139
+
140
+ We only care about the convert at this stage, no need for observers just yet.
141
+ """
142
+ assert type(mod) is cls._FLOAT_MODULE, (
143
+ " nnq."
144
+ + cls.__name__
145
+ + ".from_float only works for "
146
+ + cls._FLOAT_MODULE.__name__
147
+ )
148
+ # TODO: Need to add options to qconfig to avoid the calibration.
149
+ # TODO: Add calibration for the sparsity
150
+ assert hasattr(mod, "qconfig"), "Input float module must have qconfig defined"
151
+ if type(mod) is nni.LinearReLU:
152
+ mod = mod[0]
153
+ # pyrefly: ignore [missing-attribute]
154
+ if mod.qconfig is not None and mod.qconfig.weight is not None:
155
+ # pyrefly: ignore [not-callable]
156
+ weight_observer = mod.qconfig.weight()
157
+ else:
158
+ # We have the circular import issues if we import the qconfig in the beginning of this file:
159
+ # https://github.com/pytorch/pytorch/pull/24231. The current workaround is to postpone the
160
+ # import until we need it.
161
+ from torch.ao.quantization.qconfig import default_dynamic_qconfig
162
+
163
+ weight_observer = default_dynamic_qconfig.weight()
164
+
165
+ # It is important to multiply by the mask BEFORE calling the `weight_observer`
166
+ # TODO (zaf): Mask might not be part of the qconfig (T83295194)
167
+ weight = mod.weight
168
+ if getattr(mod.qconfig, "mask", False):
169
+ weight = mod.qconfig.mask * mod.weight
170
+
171
+ weight_observer(weight)
172
+ dtype = weight_observer.dtype
173
+ assert dtype == torch.qint8, "Weight observer must have dtype torch.qint8"
174
+ _w_sc, w_zp = weight_observer.calculate_qparams()
175
+ if isinstance(w_zp, torch.Tensor):
176
+ assert not torch.any(w_zp.bool()), "All weight zero points must map to 0"
177
+ else:
178
+ assert w_zp == 0, "Weight zero point must map to 0"
179
+ qweight = _quantize_weight(weight.float(), weight_observer)
180
+
181
+ row_block_size, col_block_size = LinearBlockSparsePattern.block_size()
182
+ qlinear = cls(
183
+ mod.in_features,
184
+ mod.out_features,
185
+ row_block_size,
186
+ col_block_size,
187
+ dtype=dtype,
188
+ )
189
+ # pyrefly: ignore [bad-argument-type]
190
+ qlinear.set_weight_bias(qweight, mod.bias, row_block_size, col_block_size)
191
+ return qlinear
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/quantized/linear.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ from torch.ao.nn.quantized.modules.utils import (
5
+ _hide_packed_params_repr,
6
+ _quantize_weight,
7
+ )
8
+
9
+
10
+ __all__ = ["LinearPackedParams", "Linear"]
11
+
12
+
13
+ # TODO (zaf): Inherit from `quantized.LinearPackedParams` (T83294430)
14
+ class LinearPackedParams(torch.nn.Module):
15
+ _version = 1
16
+
17
+ def __init__(self, row_block_size=1, col_block_size=4, dtype=torch.qint8):
18
+ super().__init__()
19
+
20
+ if dtype != torch.qint8:
21
+ raise NotImplementedError("Linear prepacking only supports QINT8")
22
+ self.dtype = dtype
23
+ wq = torch._empty_affine_quantized(
24
+ [1, 1], scale=1.0, zero_point=0, dtype=torch.qint8
25
+ )
26
+ self.set_weight_bias(wq, None, row_block_size, col_block_size)
27
+
28
+ def _get_name(self):
29
+ return "SparseQuantizedLinearPackedParams"
30
+
31
+ @torch.jit.export
32
+ def set_weight_bias(
33
+ self,
34
+ weight: torch.Tensor,
35
+ bias: torch.Tensor | None,
36
+ row_block_size: int | None,
37
+ col_block_size: int | None,
38
+ ) -> None:
39
+ assert row_block_size is not None and col_block_size is not None
40
+ self._packed_params = torch.ops.sparse.qlinear_prepack(
41
+ weight, bias, row_block_size, col_block_size
42
+ )
43
+
44
+ @torch.jit.export
45
+ def _weight_bias(self):
46
+ (weight, bias, block_sizes) = torch.ops.sparse.qlinear_unpack(
47
+ self._packed_params
48
+ )
49
+ return (weight, bias, block_sizes[0], block_sizes[1])
50
+
51
+ def forward(self, x):
52
+ return x
53
+
54
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
55
+ super()._save_to_state_dict(destination, prefix, keep_vars)
56
+ destination[prefix + "dtype"] = self.dtype
57
+ destination[prefix + "_packed_params"] = self._weight_bias()
58
+
59
+ def _load_from_state_dict(
60
+ self,
61
+ state_dict,
62
+ prefix,
63
+ local_metadata,
64
+ strict,
65
+ missing_keys,
66
+ unexpected_keys,
67
+ error_msgs,
68
+ ):
69
+ version = local_metadata.get("version", None)
70
+ assert version <= self._version
71
+
72
+ self.dtype = state_dict.pop(prefix + "dtype")
73
+ weight, bias, row_block_size, col_block_size = state_dict.pop(
74
+ prefix + "_packed_params"
75
+ )
76
+ self.set_weight_bias(weight, bias, row_block_size, col_block_size)
77
+
78
+ super()._load_from_state_dict(
79
+ state_dict,
80
+ prefix,
81
+ local_metadata,
82
+ False,
83
+ missing_keys,
84
+ unexpected_keys,
85
+ error_msgs,
86
+ )
87
+
88
+ @torch.jit.export
89
+ def __getstate__(self):
90
+ return self._packed_params, self.training, self.dtype
91
+
92
+ @torch.jit.export
93
+ def __setstate__(self, state):
94
+ (self._packed_params, self.training, self.dtype) = state
95
+
96
+ def __repr__(self):
97
+ return self._weight_bias().__repr__()
98
+
99
+
100
+ # TODO (zaf): Inherit from `quantized.Linear` (T83294430)
101
+ class Linear(torch.nn.Module):
102
+ r"""
103
+ A quantized sparse linear module with quantized tensor as inputs and outputs.
104
+ """
105
+
106
+ _version = 1
107
+ _FLOAT_MODULE = torch.nn.Linear
108
+
109
+ def __init__(
110
+ self,
111
+ in_features,
112
+ out_features,
113
+ row_block_size,
114
+ col_block_size,
115
+ bias=True,
116
+ dtype=torch.qint8,
117
+ ):
118
+ super().__init__()
119
+
120
+ if dtype != torch.qint8:
121
+ raise NotImplementedError(
122
+ "Only QINT8 is supported for Sparse Quantized Linear"
123
+ )
124
+
125
+ self.in_features = in_features
126
+ self.out_features = out_features
127
+
128
+ if bias:
129
+ bias = torch.zeros(self.out_features, dtype=torch.float)
130
+ else:
131
+ bias = None
132
+
133
+ qweight = torch._empty_affine_quantized(
134
+ [out_features, in_features], scale=1, zero_point=0, dtype=torch.qint8
135
+ )
136
+ self._packed_params = LinearPackedParams(
137
+ row_block_size=row_block_size, col_block_size=col_block_size, dtype=dtype
138
+ )
139
+ self._packed_params.set_weight_bias(
140
+ qweight, bias, row_block_size, col_block_size
141
+ )
142
+ self.scale = 1.0
143
+ self.zero_point = 0
144
+
145
+ @classmethod
146
+ def _get_name(cls):
147
+ return "SparseQuantizedLinear"
148
+
149
+ def extra_repr(self):
150
+ return (
151
+ f"in_features={self.in_features}, out_features={self.out_features}, scale={self.scale}, "
152
+ f"zero_point={self.zero_point}, qscheme={self.weight().qscheme()}"
153
+ )
154
+
155
+ def __repr__(self):
156
+ return _hide_packed_params_repr(self, LinearPackedParams)
157
+
158
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
159
+ return torch.ops.sparse.qlinear(
160
+ x, self._packed_params._packed_params, self.scale, self.zero_point
161
+ )
162
+
163
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
164
+ super()._save_to_state_dict(destination, prefix, keep_vars)
165
+ destination[prefix + "scale"] = torch.tensor(self.scale)
166
+ destination[prefix + "zero_point"] = torch.tensor(self.zero_point)
167
+
168
+ def _load_from_state_dict(
169
+ self,
170
+ state_dict,
171
+ prefix,
172
+ local_metadata,
173
+ strict,
174
+ missing_keys,
175
+ unexpected_keys,
176
+ error_msgs,
177
+ ):
178
+ self.scale = float(state_dict[prefix + "scale"])
179
+ state_dict.pop(prefix + "scale")
180
+
181
+ self.zero_point = int(state_dict[prefix + "zero_point"])
182
+ state_dict.pop(prefix + "zero_point")
183
+
184
+ state_dict.pop(prefix + "op_type")
185
+
186
+ version = local_metadata.get("version", None)
187
+ assert version <= self._version
188
+
189
+ super()._load_from_state_dict(
190
+ state_dict,
191
+ prefix,
192
+ local_metadata,
193
+ False,
194
+ missing_keys,
195
+ unexpected_keys,
196
+ error_msgs,
197
+ )
198
+
199
+ def _weight_bias(self):
200
+ return self._packed_params._weight_bias()
201
+
202
+ def weight(self):
203
+ return self._weight_bias()[0]
204
+
205
+ def bias(self):
206
+ return self._weight_bias()[1]
207
+
208
+ def set_weight_bias(
209
+ self,
210
+ w: torch.Tensor,
211
+ b: torch.Tensor | None,
212
+ row_block_size: int | None,
213
+ col_block_size: int | None,
214
+ ) -> None:
215
+ assert row_block_size is not None and col_block_size is not None
216
+ self._packed_params.set_weight_bias(w, b, row_block_size, col_block_size)
217
+
218
+ @classmethod
219
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
220
+ r"""Create a quantized sparse module from a float module.
221
+
222
+ We only care about the convert at this stage, no need for observers just yet.
223
+
224
+ TODO(zaf): Need to add the sparse params to the qconfig
225
+ """
226
+ assert type(mod) is cls._FLOAT_MODULE, (
227
+ cls._get_name() + ".from_float only works for " + cls._FLOAT_MODULE.__name__
228
+ )
229
+ assert hasattr(mod, "sparse_params"), (
230
+ "Expecting the Linear to have `sparse_params`. Make sure you have provided arguments "
231
+ 'in the `sparsifier.squash_mask(params_to_save=("sparse_block_shape",))` method.'
232
+ )
233
+ sparse_block_shape = mod.sparse_params.get("sparse_block_shape", None) # type: ignore[operator, union-attr]
234
+ assert isinstance(sparse_block_shape, (tuple, list))
235
+ assert len(sparse_block_shape) == 2
236
+ # TODO: Need to add options to qconfig to avoid the calibration.
237
+ # TODO: Add calibration for the sparsity
238
+ assert hasattr(mod, "qconfig"), "Input float module must have qconfig defined"
239
+ activation_post_process = mod.activation_post_process
240
+ weight_post_process = mod.qconfig.weight() # type: ignore[operator, union-attr]
241
+
242
+ # Assumption is that the weight is already sparsified by the
243
+ # `sparsifier.convert`
244
+ weight = mod.weight
245
+
246
+ weight_post_process(weight)
247
+ dtype = weight_post_process.dtype
248
+ act_scale, act_zp = activation_post_process.calculate_qparams() # type: ignore[operator, union-attr]
249
+ assert dtype == torch.qint8, "Weight observer must have dtype torch.qint8"
250
+ w_sc, w_zp = weight_post_process.calculate_qparams()
251
+ if isinstance(w_zp, torch.Tensor):
252
+ assert not torch.any(w_zp.bool()), "All weight zero points must map to 0"
253
+ else:
254
+ assert w_zp == 0, "Weight zero point must map to 0"
255
+ qweight = _quantize_weight(weight.float(), weight_post_process)
256
+
257
+ row_block_size = mod.sparse_params["sparse_block_shape"][0] # type: ignore[index]
258
+ col_block_size = mod.sparse_params["sparse_block_shape"][1] # type: ignore[index]
259
+ qlinear = cls(
260
+ mod.in_features,
261
+ mod.out_features,
262
+ row_block_size,
263
+ col_block_size,
264
+ dtype=dtype,
265
+ )
266
+ qlinear.set_weight_bias(
267
+ qweight,
268
+ mod.bias,
269
+ row_block_size, # type: ignore[arg-type]
270
+ col_block_size, # type: ignore[arg-type]
271
+ )
272
+ qlinear.scale = float(act_scale)
273
+ qlinear.zero_point = int(act_zp)
274
+ return qlinear
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/nn/sparse/quantized/utils.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+
3
+
4
+ __all__ = ["LinearBlockSparsePattern"]
5
+
6
+
7
+ def _is_valid_linear_block_sparse_pattern(
8
+ row_block_size: int, col_block_size: int
9
+ ) -> bool:
10
+ return (row_block_size == 1 and col_block_size == 4) or (
11
+ row_block_size == 8 and col_block_size == 1
12
+ )
13
+
14
+
15
+ # This is a stop-gap measure as current flow does not allow module
16
+ # specific block sparse pattern.
17
+ # In fact there is no way to convey sparse pattern via module config
18
+ # of quantization flow. Thus using the global context to convey
19
+ # sparsity pattern.
20
+ # Once the flow supports it, this should be removed.
21
+ class LinearBlockSparsePattern:
22
+ rlock = threading.RLock()
23
+ row_block_size: int = 1
24
+ col_block_size: int = 4
25
+ prev_row_block_size: int = 1
26
+ prev_col_block_size: int = 4
27
+
28
+ def __init__(self, row_block_size: int = 1, col_block_size: int = 4):
29
+ assert _is_valid_linear_block_sparse_pattern(row_block_size, col_block_size)
30
+ LinearBlockSparsePattern.rlock.acquire()
31
+ LinearBlockSparsePattern.prev_row_block_size = (
32
+ LinearBlockSparsePattern.row_block_size
33
+ )
34
+ LinearBlockSparsePattern.prev_col_block_size = (
35
+ LinearBlockSparsePattern.col_block_size
36
+ )
37
+ LinearBlockSparsePattern.row_block_size = row_block_size
38
+ LinearBlockSparsePattern.col_block_size = col_block_size
39
+
40
+ def __enter__(self) -> None:
41
+ pass
42
+
43
+ def __exit__(
44
+ self,
45
+ exc_type: type[BaseException] | None,
46
+ exc_value: BaseException | None,
47
+ backtrace: object | None,
48
+ ) -> None:
49
+ LinearBlockSparsePattern.row_block_size = (
50
+ LinearBlockSparsePattern.prev_row_block_size
51
+ )
52
+ LinearBlockSparsePattern.col_block_size = (
53
+ LinearBlockSparsePattern.prev_col_block_size
54
+ )
55
+ LinearBlockSparsePattern.rlock.release()
56
+
57
+ @staticmethod
58
+ def block_size() -> tuple[int, int]:
59
+ return (
60
+ LinearBlockSparsePattern.row_block_size,
61
+ LinearBlockSparsePattern.col_block_size,
62
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/_numeric_suite.py ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections.abc import Callable
3
+ from typing import Any
4
+
5
+ import torch
6
+ import torch.ao.nn.quantized as nnq
7
+ import torch.ao.nn.quantized.dynamic as nnqd
8
+ import torch.nn as nn
9
+ from torch.ao.quantization import prepare
10
+ from torch.ao.quantization.quantization_mappings import (
11
+ get_default_compare_output_module_list,
12
+ )
13
+
14
+
15
+ NON_LEAF_MODULE_TO_ADD_OBSERVER_ALLOW_LIST = {
16
+ nnqd.Linear,
17
+ nnq.Linear,
18
+ nnqd.LSTM,
19
+ nn.LSTM,
20
+ }
21
+
22
+
23
+ def _find_match(
24
+ str_list: dict[str, Any] | list[str],
25
+ key_str: str,
26
+ postfix: str,
27
+ ) -> str | None:
28
+ split_str = key_str.split(".")
29
+ if split_str[-1] == postfix:
30
+ match_string = "".join(key_str.split(".")[0:-1])
31
+ for s2 in str_list:
32
+ pattern1 = "".join(s2.split(".")[0:-1])
33
+ pattern2 = "".join(s2.split(".")[0:-2])
34
+ if match_string == pattern1:
35
+ return s2
36
+ if match_string == pattern2:
37
+ return s2
38
+
39
+ # For matching "fc.weight" and "fc._packed_params._packed_params"
40
+ if postfix == "_packed_params":
41
+ match_string = "".join(key_str.split(".")[0:-2])
42
+ if len(match_string) == 0:
43
+ return None
44
+ for s2 in str_list:
45
+ pattern1 = "".join(s2.split(".")[0:-1])
46
+ pattern2 = "".join(s2.split(".")[0:-2])
47
+ if match_string == pattern1:
48
+ return s2
49
+ if match_string == pattern2:
50
+ return s2
51
+ return None
52
+ else:
53
+ return None
54
+
55
+
56
+ def compare_weights(
57
+ float_dict: dict[str, Any], quantized_dict: dict[str, Any]
58
+ ) -> dict[str, dict[str, torch.Tensor]]:
59
+ r"""Compare the weights of the float module with its corresponding quantized
60
+ module. Return a dict with key corresponding to module names and each entry being
61
+ a dictionary with two keys 'float' and 'quantized', containing the float and
62
+ quantized weights. This dict can be used to compare and compute the quantization
63
+ error of the weights of float and quantized models.
64
+
65
+ Example usage::
66
+
67
+ wt_compare_dict = compare_weights(float_model.state_dict(), qmodel.state_dict())
68
+ for key in wt_compare_dict:
69
+ print(
70
+ key,
71
+ compute_error(
72
+ wt_compare_dict[key]["float"],
73
+ wt_compare_dict[key]["quantized"].dequantize(),
74
+ ),
75
+ )
76
+
77
+ Args:
78
+ float_dict: state dict of the float model
79
+ quantized_dict: state dict of the quantized model
80
+
81
+ Return:
82
+ weight_dict: dict with key corresponding to module names and each entry being
83
+ a dictionary with two keys 'float' and 'quantized', containing the float and
84
+ quantized weights
85
+ """
86
+ torch._C._log_api_usage_once("quantization_api._numeric_suite.compare_weights")
87
+ weight_dict: dict[str, dict] = {}
88
+ for key in quantized_dict:
89
+ match_key = _find_match(float_dict, key, "weight")
90
+ if match_key is not None:
91
+ weight_dict[key] = {}
92
+ weight_dict[key]["float"] = float_dict[match_key]
93
+ weight_dict[key]["quantized"] = quantized_dict[key]
94
+ continue
95
+
96
+ # For matching "fc.weight" and "fc._packed_params._packed_params"
97
+ match_key = _find_match(float_dict, key, "_packed_params")
98
+ if match_key is not None:
99
+ weight_dict[key] = {}
100
+ weight_dict[key]["float"] = float_dict[match_key]
101
+ weight_dict[key]["quantized"] = quantized_dict[key][0]
102
+
103
+ # For LSTM
104
+ split_str = key.split(".")
105
+ if split_str[-1] == "param" and split_str[-3] == "_all_weight_values":
106
+ layer = split_str[-2]
107
+ module_name = ".".join(split_str[:-3])
108
+ float_weight_ih_key = module_name + ".weight_ih_l" + layer
109
+ float_weight_hh_key = module_name + ".weight_hh_l" + layer
110
+ if float_weight_ih_key in float_dict and float_weight_hh_key in float_dict:
111
+ weight_dict[key] = {}
112
+ weight_dict[key]["float"] = float_dict[float_weight_ih_key]
113
+ weight_dict[key]["quantized"] = (
114
+ quantized_dict[key].__getstate__()[0][4][0].__getstate__()[0][0]
115
+ )
116
+ weight_dict[key]["float"] = float_dict[float_weight_hh_key]
117
+ weight_dict[key]["quantized"] = (
118
+ quantized_dict[key].__getstate__()[0][4][1].__getstate__()[0][0]
119
+ )
120
+
121
+ return weight_dict
122
+
123
+
124
+ def _get_logger_dict_helper(
125
+ mod: nn.Module,
126
+ target_dict: dict[str, Any],
127
+ prefix: str = "",
128
+ ) -> None:
129
+ r"""This is the helper function for get_logger_dict
130
+
131
+ Args:
132
+ mod: module we want to save all logger stats
133
+ prefix: prefix for the current module
134
+ target_dict: the dictionary used to save all logger stats
135
+ """
136
+
137
+ def get_prefix(prefix):
138
+ return prefix if prefix == "" else prefix + "."
139
+
140
+ for child in mod.children():
141
+ if isinstance(child, Logger):
142
+ target_dict[get_prefix(prefix) + "stats"] = child.stats
143
+ break
144
+
145
+ for name, child in mod.named_children():
146
+ module_prefix = get_prefix(prefix) + name if prefix else name
147
+ _get_logger_dict_helper(child, target_dict, module_prefix)
148
+
149
+
150
+ def get_logger_dict(mod: nn.Module, prefix: str = "") -> dict[str, dict]:
151
+ r"""Traverse the modules and save all logger stats into target dict.
152
+ This is mainly used for quantization accuracy debug.
153
+
154
+ Type of loggers supported:
155
+ ShadowLogger: used to log the outputs of the quantized module and its matching float shadow module,
156
+ OutputLogger: used to log the outputs of the modules
157
+
158
+ Args:
159
+ mod: module we want to save all logger stats
160
+ prefix: prefix for the current module
161
+
162
+ Return:
163
+ target_dict: the dictionary used to save all logger stats
164
+
165
+ """
166
+ torch._C._log_api_usage_once("quantization_api._numeric_suite.get_logger_dict")
167
+
168
+ target_dict: dict[str, dict] = {}
169
+ _get_logger_dict_helper(mod, target_dict, prefix)
170
+ return target_dict
171
+
172
+
173
+ class Logger(nn.Module):
174
+ r"""Base class for stats logging"""
175
+
176
+ def __init__(self):
177
+ super().__init__()
178
+ self.stats = {}
179
+ # We only insert observer if the op is quantized with static quantization,
180
+ # which is identified by activation_observer.dtype == quint8. This is needed
181
+ # when attaching Logger as observer for FX mode
182
+ self.dtype = torch.quint8
183
+
184
+ def forward(self, x):
185
+ # fmt: off
186
+ """
187
+ """ # blank docblock to make autodoc happy
188
+ # fmt: on
189
+
190
+
191
+ class ShadowLogger(Logger):
192
+ r"""Class used in Shadow module to record the outputs of the original and
193
+ shadow modules.
194
+ """
195
+
196
+ def __init__(self):
197
+ super().__init__()
198
+ self.stats["float"] = []
199
+ self.stats["quantized"] = []
200
+
201
+ def forward(self, x, y): # type: ignore[override]
202
+ # fmt: off
203
+ """
204
+ """ # blank docblock to make autodoc happy
205
+ # fmt: on
206
+ if len(x) > 1:
207
+ x = x[0]
208
+ if len(y) > 1:
209
+ y = y[0]
210
+ self.stats["quantized"].append(x.detach())
211
+ self.stats["float"].append(y.detach())
212
+
213
+
214
+ class OutputLogger(Logger):
215
+ r"""Class used to log the outputs of the module"""
216
+
217
+ def __init__(self):
218
+ super().__init__()
219
+ self.stats["tensor_val"] = []
220
+
221
+ def forward(self, x):
222
+ # fmt: off
223
+ """
224
+ """ # blank docblock to make autodoc happy
225
+ # fmt: on
226
+ self.stats["tensor_val"].append(x)
227
+ return x
228
+
229
+
230
+ def _convert_tuple_to_list(t: Any) -> Any:
231
+ return [_convert_tuple_to_list(x) for x in t] if type(t) is tuple else t
232
+
233
+
234
+ def _dequantize_tensor_list(t: Any) -> Any:
235
+ return (
236
+ [_dequantize_tensor_list(x) for x in t]
237
+ if type(t) is list
238
+ else t.dequantize()
239
+ if t.is_quantized
240
+ else t
241
+ )
242
+
243
+
244
+ class Shadow(nn.Module):
245
+ r"""Shadow module attaches the float module to its matching quantized module
246
+ as the shadow. Then it uses Logger module to process the outputs of both
247
+ modules.
248
+
249
+ Args:
250
+ q_module: module quantized from float_module that we want to shadow
251
+ float_module: float module used to shadow q_module
252
+ logger_cls: type of logger used to process the outputs of q_module and
253
+ float_module. ShadowLogger or custom loggers can be used.
254
+ """
255
+
256
+ def __init__(self, q_module, float_module, logger_cls):
257
+ super().__init__()
258
+ self.orig_module = q_module
259
+ self.shadow_module = float_module
260
+ self.dequant = nnq.DeQuantize()
261
+ self.logger = logger_cls()
262
+
263
+ def forward(self, *x) -> torch.Tensor:
264
+ # fmt: off
265
+ """
266
+ """ # blank docblock to make autodoc happy
267
+ # fmt: on
268
+ xl = _convert_tuple_to_list(x)
269
+ output = self.orig_module(*xl)
270
+ xl_float = _dequantize_tensor_list(xl)
271
+ shadow_output = self.shadow_module(*xl_float)
272
+ self.logger(output, shadow_output)
273
+ return output
274
+
275
+ def add(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
276
+ # fmt: off
277
+ """
278
+ """ # blank docblock to make autodoc happy
279
+ # fmt: on
280
+ output = self.orig_module.add(x, y)
281
+ x = x.dequantize()
282
+ y = y.dequantize()
283
+ shadow_output = self.shadow_module.add(x, y)
284
+ self.logger(output, shadow_output)
285
+ return output
286
+
287
+ def add_scalar(self, x: torch.Tensor, y: float) -> torch.Tensor:
288
+ # fmt: off
289
+ """
290
+ """ # blank docblock to make autodoc happy
291
+ # fmt: on
292
+ output = self.orig_module.add_scalar(x, y)
293
+ x = x.dequantize()
294
+ shadow_output = self.shadow_module.add_scalar(x, y)
295
+ self.logger(output, shadow_output)
296
+ return output
297
+
298
+ def mul(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
299
+ # fmt: off
300
+ """
301
+ """ # blank docblock to make autodoc happy
302
+ # fmt: on
303
+ output = self.orig_module.mul(x, y)
304
+ x = x.dequantize()
305
+ y = y.dequantize()
306
+ shadow_output = self.shadow_module.mul(x, y)
307
+ self.logger(output, shadow_output)
308
+ return output
309
+
310
+ def mul_scalar(self, x: torch.Tensor, y: float) -> torch.Tensor:
311
+ # fmt: off
312
+ """
313
+ """ # blank docblock to make autodoc happy
314
+ # fmt: on
315
+ output = self.orig_module.mul_scalar(x, y)
316
+ x = x.dequantize()
317
+ shadow_output = self.shadow_module.mul_scalar(x, y)
318
+ self.logger(output, shadow_output)
319
+ return output
320
+
321
+ def cat(self, x: list[torch.Tensor], dim: int = 0) -> torch.Tensor:
322
+ # fmt: off
323
+ """
324
+ """ # blank docblock to make autodoc happy
325
+ # fmt: on
326
+ output = self.orig_module.cat(x, dim)
327
+ x = [y.dequantize() for y in x]
328
+ shadow_output = self.shadow_module.cat(x, dim)
329
+ self.logger(output, shadow_output)
330
+ return output
331
+
332
+ def add_relu(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
333
+ # fmt: off
334
+ """
335
+ """ # blank docblock to make autodoc happy
336
+ # fmt: on
337
+ output = self.orig_module.add_relu(x, y)
338
+ x = x.dequantize()
339
+ y = y.dequantize()
340
+ shadow_output = self.shadow_module.add_relu(x, y)
341
+ self.logger(output, shadow_output)
342
+ return output
343
+
344
+
345
+ def prepare_model_with_stubs(
346
+ float_module: nn.Module,
347
+ q_module: nn.Module,
348
+ module_swap_list: set[type],
349
+ logger_cls: Callable,
350
+ ) -> None:
351
+ r"""Prepare the model by attaching the float module to its matching quantized
352
+ module as the shadow if the float module type is in module_swap_list.
353
+
354
+ Example usage::
355
+
356
+ prepare_model_with_stubs(float_model, q_model, module_swap_list, Logger)
357
+ q_model(data)
358
+ ob_dict = get_logger_dict(q_model)
359
+
360
+ Args:
361
+ float_module: float module used to generate the q_module
362
+ q_module: module quantized from float_module
363
+ module_swap_list: list of float module types to attach the shadow
364
+ logger_cls: type of logger to be used in shadow module to process the outputs of
365
+ quantized module and its float shadow module
366
+ """
367
+ torch._C._log_api_usage_once(
368
+ "quantization_api._numeric_suite.prepare_model_with_stubs"
369
+ )
370
+
371
+ float_module_children = dict(float_module.named_children())
372
+
373
+ reassign = {}
374
+ for name, mod in q_module.named_children():
375
+ if name not in float_module_children:
376
+ continue
377
+
378
+ float_mod = float_module_children[name]
379
+
380
+ if type(float_mod) not in module_swap_list:
381
+ prepare_model_with_stubs(float_mod, mod, module_swap_list, logger_cls)
382
+
383
+ # Insert shadow module only if the module is not of the same type as
384
+ # the floating point module
385
+ if type(float_mod) in module_swap_list and not _is_identical_module_type(
386
+ mod, float_mod
387
+ ):
388
+ reassign[name] = Shadow(mod, float_mod, logger_cls)
389
+
390
+ for key, value in reassign.items():
391
+ q_module._modules[key] = value
392
+
393
+
394
+ def _is_identical_module_type(mod1, mod2):
395
+ # Compare if two modules have the same dtype
396
+ mod1_module_types = [type(mod) for mod in mod1.modules()]
397
+ mod2_module_types = [type(mod) for mod in mod2.modules()]
398
+ return mod1_module_types == mod2_module_types
399
+
400
+
401
+ def compare_model_stub(
402
+ float_model: nn.Module,
403
+ q_model: nn.Module,
404
+ module_swap_list: set[type],
405
+ *data,
406
+ logger_cls=ShadowLogger,
407
+ ) -> dict[str, dict]:
408
+ r"""Compare quantized module in a model with its floating point counterpart,
409
+ feeding both of them the same input. Return a dict with key corresponding to
410
+ module names and each entry being a dictionary with two keys 'float' and
411
+ 'quantized', containing the output tensors of quantized and its matching
412
+ float shadow module. This dict can be used to compare and compute the module
413
+ level quantization error.
414
+
415
+ This function first call prepare_model_with_stubs() to swap the quantized
416
+ module that we want to compare with the Shadow module, which takes quantized
417
+ module, corresponding float module and logger as input, and creates a forward
418
+ path inside to make the float module to shadow quantized module sharing the
419
+ same input. The logger can be customizable, default logger is ShadowLogger
420
+ and it will save the outputs of the quantized module and float module that
421
+ can be used to compute the module level quantization error.
422
+
423
+ Example usage::
424
+
425
+ module_swap_list = [
426
+ torchvision.models.quantization.resnet.QuantizableBasicBlock
427
+ ]
428
+ ob_dict = compare_model_stub(float_model, qmodel, module_swap_list, data)
429
+ for key in ob_dict:
430
+ print(
431
+ key,
432
+ compute_error(
433
+ ob_dict[key]["float"], ob_dict[key]["quantized"].dequantize()
434
+ ),
435
+ )
436
+
437
+ Args:
438
+ float_model: float model used to generate the q_model
439
+ q_model: model quantized from float_model
440
+ module_swap_list: list of float module types at which shadow modules will
441
+ be attached.
442
+ data: input data used to run the prepared q_model
443
+ logger_cls: type of logger to be used in shadow module to process the outputs of
444
+ quantized module and its float shadow module
445
+ """
446
+ torch._C._log_api_usage_once("quantization_api._numeric_suite.compare_model_stub")
447
+ prepare_model_with_stubs(float_model, q_model, module_swap_list, logger_cls)
448
+ q_model(*data)
449
+ ob_dict = get_logger_dict(q_model)
450
+ return ob_dict
451
+
452
+
453
+ def get_matching_activations(
454
+ float_module: nn.Module,
455
+ q_module: nn.Module,
456
+ ) -> dict[str, dict[str, torch.Tensor]]:
457
+ r"""Find the matching activation between float and quantized modules.
458
+
459
+ Args:
460
+ float_module: float module used to generate the q_module
461
+ q_module: module quantized from float_module
462
+
463
+ Return:
464
+ act_dict: dict with key corresponding to quantized module names and each
465
+ entry being a dictionary with two keys 'float' and 'quantized', containing
466
+ the matching float and quantized activations
467
+ """
468
+ torch._C._log_api_usage_once(
469
+ "quantization_api._numeric_suite.get_matching_activations"
470
+ )
471
+ float_dict = get_logger_dict(float_module)
472
+ quantized_dict = get_logger_dict(q_module)
473
+ act_dict: dict[str, dict] = {}
474
+ for key in quantized_dict:
475
+ if len(quantized_dict[key]["tensor_val"]) == 0:
476
+ continue
477
+ match_key = _find_match(sorted(float_dict, reverse=True), key, "stats")
478
+ if match_key is not None:
479
+ act_dict[key] = {}
480
+ act_dict[key]["float"] = float_dict[match_key]["tensor_val"]
481
+ act_dict[key]["quantized"] = quantized_dict[key]["tensor_val"]
482
+ return act_dict
483
+
484
+
485
+ def prepare_model_outputs(
486
+ float_module: nn.Module,
487
+ q_module: nn.Module,
488
+ logger_cls=OutputLogger,
489
+ allow_list=None,
490
+ ) -> None:
491
+ r"""Prepare the model by attaching the logger to both float module
492
+ and quantized module if they are in the allow_list.
493
+
494
+ Args:
495
+ float_module: float module used to generate the q_module
496
+ q_module: module quantized from float_module
497
+ logger_cls: type of logger to be attached to float_module and q_module
498
+ allow_list: list of module types to attach logger
499
+ """
500
+ torch._C._log_api_usage_once(
501
+ "quantization_api._numeric_suite.prepare_model_outputs"
502
+ )
503
+ if allow_list is None:
504
+ allow_list = get_default_compare_output_module_list()
505
+
506
+ qconfig_debug = torch.ao.quantization.QConfig(activation=logger_cls, weight=None)
507
+ float_module.qconfig = qconfig_debug # type: ignore[assignment]
508
+ prepare(
509
+ float_module, inplace=True, allow_list=allow_list, prepare_custom_config_dict={}
510
+ )
511
+ q_module.qconfig = qconfig_debug # type: ignore[assignment]
512
+ prepare(
513
+ q_module,
514
+ inplace=True,
515
+ allow_list=allow_list,
516
+ observer_non_leaf_module_list=NON_LEAF_MODULE_TO_ADD_OBSERVER_ALLOW_LIST,
517
+ prepare_custom_config_dict={},
518
+ )
519
+
520
+
521
+ def compare_model_outputs(
522
+ float_model: nn.Module,
523
+ q_model: nn.Module,
524
+ *data,
525
+ logger_cls=OutputLogger,
526
+ allow_list=None,
527
+ ) -> dict[str, dict[str, torch.Tensor]]:
528
+ r"""Compare output activations between float and quantized models at
529
+ corresponding locations for the same input. Return a dict with key corresponding
530
+ to quantized module names and each entry being a dictionary with two keys
531
+ 'float' and 'quantized', containing the activations of quantized model and
532
+ float model at matching locations. This dict can be used to compare and
533
+ compute the propagation quantization error.
534
+
535
+ Example usage::
536
+
537
+ act_compare_dict = compare_model_outputs(float_model, qmodel, data)
538
+ for key in act_compare_dict:
539
+ print(
540
+ key,
541
+ compute_error(
542
+ act_compare_dict[key]["float"],
543
+ act_compare_dict[key]["quantized"].dequantize(),
544
+ ),
545
+ )
546
+
547
+ Args:
548
+ float_model: float model used to generate the q_model
549
+ q_model: model quantized from float_model
550
+ data: input data used to run the prepared float_model and q_model
551
+ logger_cls: type of logger to be attached to float_module and q_module
552
+ allow_list: list of module types to attach logger
553
+
554
+ Return:
555
+ act_compare_dict: dict with key corresponding to quantized module names
556
+ and each entry being a dictionary with two keys 'float' and 'quantized',
557
+ containing the matching float and quantized activations
558
+ """
559
+ torch._C._log_api_usage_once(
560
+ "quantization_api._numeric_suite.compare_model_outputs"
561
+ )
562
+ if allow_list is None:
563
+ allow_list = get_default_compare_output_module_list()
564
+ prepare_model_outputs(float_model, q_model, logger_cls, allow_list)
565
+ float_model(*data)
566
+ q_model(*data)
567
+ act_compare_dict = get_matching_activations(float_model, q_model)
568
+ return act_compare_dict
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/_numeric_suite_fx.py ADDED
@@ -0,0 +1,1121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ This module contains tooling to compare weights and activations
4
+ across models. Example usage::
5
+
6
+ import copy
7
+ import torch
8
+ import torch.ao.quantization.quantize_fx as quantize_fx
9
+ import torch.ao.ns._numeric_suite_fx as ns
10
+
11
+ m = torch.nn.Sequential(torch.nn.Conv2d(1, 1, 1)).eval()
12
+ mp = quantize_fx.prepare_fx(m, {"": torch.ao.quantization.default_qconfig})
13
+ # We convert a copy because we need the original prepared model
14
+ # to be available for comparisons, and `quantize_fx.convert_fx` is inplace.
15
+ mq = quantize_fx.convert_fx(copy.deepcopy(mp))
16
+
17
+ #
18
+ # Comparing weights
19
+ #
20
+
21
+ # extract weight pairs
22
+ weight_comparison = ns.extract_weights("a", mp, "b", mq)
23
+
24
+ # add SQNR for each comparison, inplace
25
+ ns.extend_logger_results_with_comparison(
26
+ weight_comparison, "a", "b", torch.ao.ns.fx.utils.compute_sqnr, "sqnr"
27
+ )
28
+
29
+ # weight_comparison contains the weights from `mp` and `mq` stored
30
+ # in pairs, and can be used for further analysis.
31
+
32
+
33
+ #
34
+ # Comparing activations, with error propagation
35
+ #
36
+
37
+ # add loggers
38
+ mp_ns, mq_ns = ns.add_loggers(
39
+ "a", copy.deepcopy(mp), "b", copy.deepcopy(mq), ns.OutputLogger
40
+ )
41
+
42
+ # send an example datum to capture intermediate activations
43
+ datum = torch.randn(1, 1, 1, 1)
44
+ mp_ns(datum)
45
+ mq_ns(datum)
46
+
47
+ # extract intermediate activations
48
+ act_comparison = ns.extract_logger_info(mp_ns, mq_ns, ns.OutputLogger, "b")
49
+
50
+ # add SQNR for each comparison, inplace
51
+ ns.extend_logger_results_with_comparison(
52
+ act_comparison, "a", "b", torch.ao.ns.fx.utils.compute_sqnr, "sqnr"
53
+ )
54
+
55
+ # act_comparison contains the activations from `mp_ns` and `mq_ns` stored
56
+ # in pairs, and can be used for further analysis.
57
+
58
+ #
59
+ # Comparing activations, without error propagation
60
+ #
61
+
62
+ # create shadow model
63
+ mp_shadows_mq = ns.add_shadow_loggers(
64
+ "a", copy.deepcopy(mp), "b", copy.deepcopy(mq), ns.OutputLogger
65
+ )
66
+
67
+ # send an example datum to capture intermediate activations
68
+ datum = torch.randn(1, 1, 1, 1)
69
+ mp_shadows_mq(datum)
70
+
71
+ # extract intermediate activations
72
+ shadow_act_comparison = ns.extract_shadow_logger_info(
73
+ mp_shadows_mq, ns.OutputLogger, "b"
74
+ )
75
+
76
+ # add SQNR for each comparison, inplace
77
+ ns.extend_logger_results_with_comparison(
78
+ shadow_act_comparison, "a", "b", torch.ao.ns.fx.utils.compute_sqnr, "sqnr"
79
+ )
80
+
81
+ # shadow_act_comparison contains the activations from `mp_ns` and `mq_ns` stored
82
+ # in pairs, and can be used for further analysis.
83
+
84
+ """
85
+
86
+ import collections
87
+ from collections.abc import Callable
88
+ from typing import Any, TYPE_CHECKING
89
+
90
+ import torch
91
+ import torch.ao.quantization.quantize_fx as quantize_fx
92
+ import torch.nn as nn
93
+ from torch.ao.ns.fx.graph_matcher import get_matching_subgraph_pairs
94
+ from torch.ao.ns.fx.mappings import get_base_name_to_sets_of_related_ops
95
+ from torch.ao.ns.fx.n_shadows_utils import (
96
+ _get_dedup_subgraphs,
97
+ create_add_loggers_graph,
98
+ create_n_transformed_and_logged_copies_of_subgraph,
99
+ create_results_comparison,
100
+ extract_weight_comparison,
101
+ group_results_by_subgraph,
102
+ OutputProp,
103
+ print_n_shadows_summary,
104
+ SHADOW_WRAPPER_NODE_NAME_PREFIX,
105
+ )
106
+ from torch.ao.ns.fx.qconfig_multi_mapping import QConfigMultiMapping
107
+ from torch.ao.quantization import QConfigMapping
108
+ from torch.ao.quantization.backend_config import BackendConfig
109
+ from torch.ao.quantization.backend_config.utils import (
110
+ get_fusion_pattern_to_root_node_getter,
111
+ )
112
+ from torch.ao.quantization.fx.graph_module import _get_observed_graph_module_attr
113
+ from torch.ao.quantization.fx.match_utils import _find_matches
114
+ from torch.ao.quantization.fx.qconfig_mapping_utils import (
115
+ _generate_node_name_to_qconfig,
116
+ )
117
+ from torch.ao.quantization.fx.quantize_handler import _get_pattern_to_quantize_handlers
118
+ from torch.fx import GraphModule
119
+ from torch.fx.graph import Node
120
+
121
+ from .fx.graph_passes import add_loggers_to_model, create_a_shadows_b
122
+ from .fx.ns_types import NSNodeTargetType, NSResultsType, NSSingleResultValuesType
123
+ from .fx.utils import (
124
+ get_target_type_str,
125
+ maybe_add_missing_fqns,
126
+ rekey_logger_info_on_node_name_of_model,
127
+ )
128
+ from .fx.weight_utils import extract_weight_from_node
129
+
130
+
131
+ if TYPE_CHECKING:
132
+ from torch.ao.quantization.qconfig import QConfigAny
133
+
134
+ RNNReturnType = tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]
135
+
136
+
137
+ class OutputLogger(nn.Module):
138
+ """
139
+ Base class for capturing intermediate values.
140
+ """
141
+
142
+ stats: list[torch.Tensor]
143
+ stats_rnn: list[RNNReturnType]
144
+
145
+ # Mark as impure so that calls to it will not be removed during DCE.
146
+ _is_impure = True
147
+
148
+ def __init__(
149
+ self,
150
+ ref_node_name: str,
151
+ prev_node_name: str,
152
+ model_name: str,
153
+ ref_name: str,
154
+ prev_node_target_type: str,
155
+ ref_node_target_type: str,
156
+ results_type: str,
157
+ index_within_arg: int,
158
+ index_of_arg: int,
159
+ fqn: str | None,
160
+ qconfig_str: str | None = "",
161
+ ):
162
+ super().__init__()
163
+ self.stats: list[torch.Tensor] = []
164
+ self.stats_rnn: list[RNNReturnType] = []
165
+
166
+ # name of the node which was responsible for adding this logger
167
+ # Note:
168
+ # - if we are logging node outputs, this is the same as prev_node_name
169
+ # - if we are logging node inputs, this is the name of the node
170
+ # whose input this logger is logging.
171
+ #
172
+ # example, where logger1 is logging input of op1 and logger2 is logging
173
+ # the output of op1:
174
+ #
175
+ # x1 -> logger1 -> op1 -> logger2 -> x2
176
+ #
177
+ # in this example,
178
+ # - logger1's prev_node_name is x1 and ref_node_name is op1
179
+ # - logger2's prev_node_name is op1 and ref_node_name is op1
180
+ self.ref_node_name = ref_node_name
181
+ # name of the node whose output this Logger is capturing
182
+ self.prev_node_name = prev_node_name
183
+
184
+ # name of the model from which the node originated from
185
+ self.model_name = model_name
186
+ # reference name, used to match loggers from separate models
187
+ # to each other
188
+ self.ref_name = ref_name
189
+ # type of the target of the node whose output this logger is logging
190
+ self.prev_node_target_type = prev_node_target_type
191
+ # type of the target of the node which was responsible for adding this
192
+ # logger
193
+ self.ref_node_target_type = ref_node_target_type
194
+ # what kind of values are inside of stats
195
+ self.results_type = results_type
196
+ # index of this node within the arg of the input/output node
197
+ # for example, in cat([x1, x2, x3], dim=0), x2 would have index_within_arg == 1
198
+ self.index_within_arg = index_within_arg
199
+ # index of this node within the args of the input/output node
200
+ # for example, in add(x1, x2), x2 would have index_of_arg == 1
201
+ self.index_of_arg = index_of_arg
202
+ # fully qualified name
203
+ self.fqn = fqn
204
+ # if loggers are added before prepare_fx, but we do not want
205
+ # collect results of calibration, only results after convert_fx
206
+ # so, we add a flag to control whether this logger collects data
207
+ self.enabled = True
208
+ # string representation of qconfig
209
+ self.qconfig_str = qconfig_str
210
+ # this can be turned off to reduce memory usage during calibration
211
+ self.save_activations = True
212
+
213
+ # Note: cannot annotate the type of x because TorchScript does not support
214
+ # the Union type.
215
+ def forward(self, x):
216
+ # fmt: off
217
+ """
218
+ """ # blank docblock to make autodoc happy
219
+ # fmt: on
220
+ # TODO(future PR): consider designing this better, as the difference
221
+ # between these two flags is subtle and not obvious.
222
+ if not self.enabled:
223
+ return x
224
+ if not self.save_activations:
225
+ return x
226
+ # TODO(future PR): consider refactoring this to better reuse the parent
227
+ # class
228
+ if isinstance(x, torch.Tensor):
229
+ self.stats.append(x.detach())
230
+ elif isinstance(x, tuple) and len(x) == 2 and len(x[1]) == 2:
231
+ new_res = (x[0].detach(), (x[1][0].detach(), x[1][1].detach()))
232
+ self.stats_rnn.append(new_res)
233
+ return x
234
+
235
+ def __repr__(self):
236
+ clean_dict = {
237
+ k: v
238
+ for k, v in self.__dict__.items()
239
+ # skip nn.Module keys
240
+ if (k != "training") and not k.startswith("_")
241
+ }
242
+ return f"OutputLogger({clean_dict})"
243
+
244
+
245
+ class OutputComparisonLogger(OutputLogger):
246
+ """
247
+ Same as OutputLogger, but also requires the original activation
248
+ in order to calculate the comparison at calibration time
249
+ """
250
+
251
+ def __init__(self, *args, **kwargs):
252
+ super().__init__(*args, **kwargs)
253
+ # TODO(future PR): make the comparison function configurable
254
+ self.comparison_fn = torch.ao.ns.fx.utils.compute_sqnr
255
+ self.comparison_fn_name = "sqnr"
256
+ # precalculated comparisons of logger output versus reference
257
+ self.comparisons = []
258
+ # precalculated comparisons function
259
+
260
+ def forward(self, x, x_ref): # type: ignore[override]
261
+ # fmt: off
262
+ """
263
+ """ # blank docblock to make autodoc happy
264
+ # fmt: on
265
+ if not self.enabled:
266
+ return x
267
+ if not isinstance(x, torch.Tensor):
268
+ raise AssertionError("non-tensor inputs not yet supported")
269
+ if self.save_activations:
270
+ # save the activation, for debugging
271
+ self.stats.append(x.detach())
272
+ # save the comparison
273
+ self.comparisons.append(self.comparison_fn(x, x_ref))
274
+ return x
275
+
276
+ def __repr__(self):
277
+ clean_dict = {
278
+ k: v
279
+ for k, v in self.__dict__.items()
280
+ # skip nn.Module keys
281
+ if (k != "training") and not k.startswith("_")
282
+ }
283
+ return f"OutputComparisonLogger({clean_dict})"
284
+
285
+
286
+ class NSTracer(quantize_fx.QuantizationTracer):
287
+ """
288
+ Just like a regular FX quantization tracer, but treats observers and fake_quantize
289
+ modules as leaf modules.
290
+ """
291
+
292
+ def is_leaf_module(self, m: torch.nn.Module, module_qualified_name: str) -> bool:
293
+ # fmt: off
294
+ """
295
+ """ # blank docblock to make autodoc happy
296
+ # fmt: on
297
+ if isinstance(m, torch.ao.quantization.ObserverBase):
298
+ return True
299
+ elif isinstance(m, torch.ao.quantization.FakeQuantizeBase):
300
+ return True
301
+ return super().is_leaf_module(m, module_qualified_name)
302
+
303
+
304
+ def _extract_weights_one_model(
305
+ model_name: str,
306
+ model: GraphModule,
307
+ nodes_and_names_to_instrument: list[tuple[Node, str]],
308
+ results: NSResultsType,
309
+ op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]]
310
+ | None = None,
311
+ ) -> None:
312
+ torch._C._log_api_usage_once(
313
+ "quantization_api._numeric_suite_fx._extract_weights_one_model"
314
+ )
315
+ for node, ref_name in nodes_and_names_to_instrument:
316
+ res_type = NSSingleResultValuesType.WEIGHT.value
317
+ extracted_weight = extract_weight_from_node(
318
+ node, model, op_to_type_to_weight_extraction_fn
319
+ )
320
+ if extracted_weight:
321
+ if ref_name not in results:
322
+ results[ref_name] = {res_type: {}}
323
+ results[ref_name][res_type][model_name] = [extracted_weight]
324
+
325
+
326
+ def _extract_weights_impl(
327
+ model_name_a: str,
328
+ gm_a: GraphModule,
329
+ model_name_b: str,
330
+ gm_b: GraphModule,
331
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
332
+ unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
333
+ op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]]
334
+ | None = None,
335
+ ) -> NSResultsType:
336
+ torch._C._log_api_usage_once(
337
+ "quantization_api._numeric_suite_fx._extract_weights_impl"
338
+ )
339
+ matched_subgraph_pairs = get_matching_subgraph_pairs(
340
+ gm_a, gm_b, base_name_to_sets_of_related_ops, unmatchable_types_map
341
+ )
342
+
343
+ # split the subgraph pairs into one data structure for each model
344
+ nodes_and_names_to_instrument_a: list[tuple[Node, str]] = []
345
+ nodes_and_names_to_instrument_b: list[tuple[Node, str]] = []
346
+ for match_name, match in matched_subgraph_pairs.items():
347
+ subgraph_a, subgraph_b = match
348
+ nodes_and_names_to_instrument_a.append((subgraph_a.base_op_node, match_name))
349
+ nodes_and_names_to_instrument_b.append((subgraph_b.base_op_node, match_name))
350
+
351
+ # populate the results, one model at a time
352
+ results: NSResultsType = {}
353
+ _extract_weights_one_model(
354
+ model_name_a,
355
+ gm_a,
356
+ nodes_and_names_to_instrument_a,
357
+ results,
358
+ op_to_type_to_weight_extraction_fn,
359
+ )
360
+ _extract_weights_one_model(
361
+ model_name_b,
362
+ gm_b,
363
+ nodes_and_names_to_instrument_b,
364
+ results,
365
+ op_to_type_to_weight_extraction_fn,
366
+ )
367
+
368
+ # fill in missing fqn entries
369
+ maybe_add_missing_fqns(results)
370
+
371
+ # rekey on names of nodes in gm_b
372
+ results = rekey_logger_info_on_node_name_of_model(results, model_name_b)
373
+
374
+ return results
375
+
376
+
377
+ def extract_weights(
378
+ model_name_a: str,
379
+ model_a: nn.Module,
380
+ model_name_b: str,
381
+ model_b: nn.Module,
382
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
383
+ unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
384
+ op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]]
385
+ | None = None,
386
+ ) -> NSResultsType:
387
+ """
388
+ Extract weights from model A and model B, and return a comparison.
389
+
390
+ Args:
391
+ model_name_a: string name of model A to use in results
392
+ model_a: model A
393
+ model_name_b: string name of model B to use in results
394
+ model_b: model B
395
+ base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change
396
+ unmatchable_types_map: optional override of unmatchable types, subject to change
397
+ op_to_type_to_weight_extraction_fn: optional override of function which extracts weight
398
+ from a type, subject to change
399
+
400
+ Return:
401
+ NSResultsType, containing the weight comparisons
402
+ """
403
+
404
+ torch._C._log_api_usage_once("quantization_api._numeric_suite_fx.extract_weights")
405
+ if base_name_to_sets_of_related_ops is None:
406
+ base_name_to_sets_of_related_ops = get_base_name_to_sets_of_related_ops()
407
+
408
+ # TODO(future PR): expose these
409
+ skipped_module_names: list[str] = []
410
+ skipped_module_classes: list[Callable] = []
411
+ tracer_a = NSTracer(skipped_module_names, skipped_module_classes)
412
+ tracer_b = NSTracer(skipped_module_names, skipped_module_classes)
413
+ gm_a = GraphModule(model_a, tracer_a.trace(model_a))
414
+ maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(
415
+ model_a, "node_name_to_scope"
416
+ )
417
+ if maybe_model_a_node_name_to_scope is not None:
418
+ gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope
419
+ gm_b = GraphModule(model_b, tracer_b.trace(model_b))
420
+ maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(
421
+ model_b, "node_name_to_scope"
422
+ )
423
+ if maybe_model_b_node_name_to_scope is not None:
424
+ gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope
425
+ return _extract_weights_impl(
426
+ model_name_a,
427
+ gm_a,
428
+ model_name_b,
429
+ gm_b,
430
+ base_name_to_sets_of_related_ops,
431
+ unmatchable_types_map,
432
+ op_to_type_to_weight_extraction_fn,
433
+ )
434
+
435
+
436
+ def _add_loggers_one_model(
437
+ model_name: str,
438
+ model: GraphModule,
439
+ nodes_and_names_to_instrument_inputs: list[tuple[Node, str, str]],
440
+ nodes_and_names_to_instrument_outputs: list[tuple[Node, str, str]],
441
+ logger_cls: Callable,
442
+ ) -> nn.Module:
443
+ torch._C._log_api_usage_once(
444
+ "quantization_api._numeric_suite_fx._add_loggers_one_model"
445
+ )
446
+
447
+ # TODO(future PR): do not observe nodes we do not care
448
+ # about (both fp32, denylist, etc)
449
+ node_to_instrument_inputs_to_ref_name: dict[Node, tuple[str, str]] = {}
450
+ node_to_instrument_outputs_to_ref_name: dict[Node, tuple[str, str]] = {}
451
+ for node, ref_name, ref_node_type in nodes_and_names_to_instrument_inputs:
452
+ node_to_instrument_inputs_to_ref_name[node] = (ref_name, ref_node_type)
453
+ for node, ref_name, ref_node_type in nodes_and_names_to_instrument_outputs:
454
+ node_to_instrument_outputs_to_ref_name[node] = (ref_name, ref_node_type)
455
+
456
+ model = add_loggers_to_model(
457
+ model,
458
+ node_to_instrument_inputs_to_ref_name,
459
+ node_to_instrument_outputs_to_ref_name,
460
+ logger_cls,
461
+ model_name,
462
+ )
463
+ return model
464
+
465
+
466
+ def _add_loggers_impl(
467
+ name_a: str,
468
+ gm_a: GraphModule,
469
+ name_b: str,
470
+ gm_b: GraphModule,
471
+ logger_cls: Callable,
472
+ should_log_inputs: bool,
473
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
474
+ unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
475
+ ) -> tuple[nn.Module, nn.Module]:
476
+ torch._C._log_api_usage_once("quantization_api._numeric_suite_fx._add_loggers_impl")
477
+ matched_subgraph_pairs = get_matching_subgraph_pairs(
478
+ gm_a, gm_b, base_name_to_sets_of_related_ops, unmatchable_types_map
479
+ )
480
+ nodes_and_names_to_instrument_inputs_a = []
481
+ nodes_and_names_to_instrument_inputs_b = []
482
+ nodes_and_names_to_instrument_outputs_a = []
483
+ nodes_and_names_to_instrument_outputs_b = []
484
+ for match_name, (subgraph_a, subgraph_b) in matched_subgraph_pairs.items():
485
+ ref_node_type_a = get_target_type_str(subgraph_a.base_op_node, gm_a)
486
+ ref_node_type_b = get_target_type_str(subgraph_b.base_op_node, gm_b)
487
+ # Note: for matching inputs we use start_node, such as observing
488
+ # the input of linear in linear-relu
489
+ if should_log_inputs:
490
+ nodes_and_names_to_instrument_inputs_a.append(
491
+ (subgraph_a.start_node, match_name, ref_node_type_a)
492
+ )
493
+ nodes_and_names_to_instrument_inputs_b.append(
494
+ (subgraph_b.start_node, match_name, ref_node_type_b)
495
+ )
496
+ # Note: for matching activations we always use end_node,
497
+ # such as observing the output of relu in linear-relu
498
+ nodes_and_names_to_instrument_outputs_a.append(
499
+ (subgraph_a.end_node, match_name, ref_node_type_a)
500
+ )
501
+ nodes_and_names_to_instrument_outputs_b.append(
502
+ (subgraph_b.end_node, match_name, ref_node_type_b)
503
+ )
504
+
505
+ new_model_a = _add_loggers_one_model(
506
+ name_a,
507
+ gm_a,
508
+ nodes_and_names_to_instrument_inputs_a,
509
+ nodes_and_names_to_instrument_outputs_a,
510
+ logger_cls,
511
+ )
512
+ new_model_b = _add_loggers_one_model(
513
+ name_b,
514
+ gm_b,
515
+ nodes_and_names_to_instrument_inputs_b,
516
+ nodes_and_names_to_instrument_outputs_b,
517
+ logger_cls,
518
+ )
519
+ return (new_model_a, new_model_b)
520
+
521
+
522
+ def add_loggers(
523
+ name_a: str,
524
+ model_a: nn.Module,
525
+ name_b: str,
526
+ model_b: nn.Module,
527
+ logger_cls: Callable,
528
+ should_log_inputs: bool = False,
529
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
530
+ unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
531
+ ) -> tuple[nn.Module, nn.Module]:
532
+ """
533
+ Instrument model A and model B with loggers.
534
+
535
+ Args:
536
+ name_a: string name of model A to use in results
537
+ model_a: model A
538
+ name_b: string name of model B to use in results
539
+ model_b: model B
540
+ logger_cls: class of Logger to use
541
+ base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change
542
+ unmatchable_types_map: optional override of unmatchable types, subject to change
543
+
544
+ Return:
545
+ Returns a tuple of (model_a_with_loggers, model_b_with_loggers). Modifies both models inplace.
546
+ """
547
+
548
+ torch._C._log_api_usage_once("quantization_api._numeric_suite_fx.add_loggers")
549
+ # TODO(future PR): expose these
550
+ skipped_module_names: list[str] = []
551
+ skipped_module_classes: list[Callable] = []
552
+ tracer_a = NSTracer(skipped_module_names, skipped_module_classes)
553
+ tracer_b = NSTracer(skipped_module_names, skipped_module_classes)
554
+ gm_a = GraphModule(model_a, tracer_a.trace(model_a))
555
+ maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(
556
+ model_a, "node_name_to_scope"
557
+ )
558
+ if maybe_model_a_node_name_to_scope is not None:
559
+ gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope
560
+ gm_b = GraphModule(model_b, tracer_b.trace(model_b))
561
+ maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(
562
+ model_b, "node_name_to_scope"
563
+ )
564
+ if maybe_model_b_node_name_to_scope is not None:
565
+ gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope
566
+ return _add_loggers_impl(
567
+ name_a,
568
+ gm_a,
569
+ name_b,
570
+ gm_b,
571
+ logger_cls,
572
+ should_log_inputs=should_log_inputs,
573
+ base_name_to_sets_of_related_ops=base_name_to_sets_of_related_ops,
574
+ unmatchable_types_map=unmatchable_types_map,
575
+ )
576
+
577
+
578
+ def _extract_logger_info_one_model(
579
+ model: nn.Module,
580
+ results: NSResultsType,
581
+ logger_cls: Callable,
582
+ ) -> None:
583
+ torch._C._log_api_usage_once(
584
+ "quantization_api._numeric_suite_fx._extract_logger_info_one_model"
585
+ )
586
+ for _gm_name, mod in model.named_modules():
587
+ # TODO(future PR): better check when scripted
588
+ is_logger = isinstance(mod, logger_cls) or ( # type: ignore[arg-type]
589
+ isinstance(mod, torch.jit.RecursiveScriptModule)
590
+ and mod.original_name == "OutputLogger"
591
+ )
592
+ if is_logger:
593
+ key = mod.ref_name
594
+ if key not in results:
595
+ results[key] = {}
596
+ if mod.model_name in results[key]:
597
+ raise AssertionError(f"{mod.model_name} is already present in results")
598
+ if mod.results_type not in results[key]:
599
+ results[key][mod.results_type] = {}
600
+ if mod.model_name not in results[key][mod.results_type]:
601
+ results[key][mod.results_type][mod.model_name] = []
602
+ stats_to_use = mod.stats
603
+ if len(mod.stats_rnn) > 0:
604
+ stats_to_use = mod.stats_rnn
605
+ data = {
606
+ "type": mod.results_type,
607
+ "values": stats_to_use,
608
+ "ref_node_name": mod.ref_node_name,
609
+ "ref_node_target_type": mod.ref_node_target_type,
610
+ "prev_node_name": mod.prev_node_name,
611
+ "prev_node_target_type": mod.prev_node_target_type,
612
+ "index_within_arg": mod.index_within_arg,
613
+ "index_of_arg": mod.index_of_arg,
614
+ "fqn": mod.fqn,
615
+ "qconfig_str": mod.qconfig_str,
616
+ }
617
+ if hasattr(mod, "comparisons"):
618
+ data["comparisons"] = mod.comparisons
619
+ data["comparison_fn_name"] = mod.comparison_fn_name
620
+ else:
621
+ data["comparisons"] = []
622
+ data["comparison_fn_name"] = ""
623
+ results[key][mod.results_type][mod.model_name].append(data)
624
+ # ensure the list stays sorted
625
+ results[key][mod.results_type][mod.model_name].sort(
626
+ key=lambda res: f"{res['index_of_arg']}:{res['index_within_arg']}"
627
+ )
628
+
629
+
630
+ # TODO(future PR): align on naming
631
+ # this is equivalent of just the comparison extraction part of `ns.compare_model_outputs`
632
+ def extract_logger_info(
633
+ model_a: nn.Module,
634
+ model_b: nn.Module,
635
+ logger_cls: Callable,
636
+ model_name_to_use_for_layer_names: str,
637
+ ) -> NSResultsType:
638
+ """
639
+ Traverse all loggers in `model_a` and `model_b`, and extract the logged
640
+ information.
641
+
642
+ Args:
643
+ model_a: model A
644
+ model_b: model B
645
+ logger_cls: class of Logger to use
646
+ model_name_to_use_for_layer_names: string name of model to use for
647
+ layer names in the output
648
+
649
+ Return:
650
+ NSResultsType, containing the logged comparisons
651
+ """
652
+ torch._C._log_api_usage_once(
653
+ "quantization_api._numeric_suite_fx.extract_logger_info"
654
+ )
655
+ results: NSResultsType = {}
656
+ for model in (model_a, model_b):
657
+ _extract_logger_info_one_model(model, results, logger_cls)
658
+ # fill in missing fqn entries
659
+ maybe_add_missing_fqns(results)
660
+ # rekey on the name of model b
661
+ results = rekey_logger_info_on_node_name_of_model(
662
+ results, model_name_to_use_for_layer_names
663
+ )
664
+ return results
665
+
666
+
667
+ def _add_shadow_loggers_impl(
668
+ name_a: str,
669
+ gm_a: GraphModule,
670
+ name_b: str,
671
+ gm_b: GraphModule,
672
+ logger_cls: Callable,
673
+ should_log_inputs: bool,
674
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
675
+ node_type_to_io_type_map: dict[str, set[NSNodeTargetType]] | None = None,
676
+ unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
677
+ ) -> nn.Module:
678
+ torch._C._log_api_usage_once(
679
+ "quantization_api._numeric_suite_fx._add_shadow_loggers_impl"
680
+ )
681
+ matched_subgraph_pairs = get_matching_subgraph_pairs(
682
+ gm_a, gm_b, base_name_to_sets_of_related_ops, unmatchable_types_map
683
+ )
684
+ gm_a_shadows_b = create_a_shadows_b(
685
+ name_a,
686
+ gm_a,
687
+ name_b,
688
+ gm_b,
689
+ matched_subgraph_pairs,
690
+ logger_cls,
691
+ should_log_inputs=should_log_inputs,
692
+ node_type_to_io_type_map=node_type_to_io_type_map,
693
+ )
694
+ return gm_a_shadows_b
695
+
696
+
697
+ def add_shadow_loggers(
698
+ name_a: str,
699
+ model_a: nn.Module,
700
+ name_b: str,
701
+ model_b: nn.Module,
702
+ logger_cls: Callable,
703
+ should_log_inputs: bool = False,
704
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
705
+ node_type_to_io_type_map: dict[str, set[NSNodeTargetType]] | None = None,
706
+ unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
707
+ ) -> nn.Module:
708
+ """
709
+ Instrument model A and model B with shadow loggers.
710
+
711
+ Args:
712
+ name_a: string name of model A to use in results
713
+ model_a: model A
714
+ name_b: string name of model B to use in results
715
+ model_b: model B
716
+ logger_cls: class of Logger to use
717
+ should_log_inputs: whether to log inputs
718
+ base_name_to_sets_of_related_ops: optional override of subgraph base nodes, subject to change
719
+ unmatchable_types_map: optional override of unmatchable types, subject to change
720
+ """
721
+ torch._C._log_api_usage_once(
722
+ "quantization_api._numeric_suite_fx.add_shadow_loggers"
723
+ )
724
+ # TODO(future PR): expose these
725
+ skipped_module_names: list[str] = []
726
+ skipped_module_classes: list[Callable] = []
727
+ tracer_a = NSTracer(skipped_module_names, skipped_module_classes)
728
+ tracer_b = NSTracer(skipped_module_names, skipped_module_classes)
729
+ gm_a = GraphModule(model_a, tracer_a.trace(model_a))
730
+ maybe_model_a_node_name_to_scope = _get_observed_graph_module_attr(
731
+ model_a, "node_name_to_scope"
732
+ )
733
+ if maybe_model_a_node_name_to_scope is not None:
734
+ gm_a._node_name_to_scope = maybe_model_a_node_name_to_scope
735
+ gm_b = GraphModule(model_b, tracer_b.trace(model_b))
736
+ maybe_model_b_node_name_to_scope = _get_observed_graph_module_attr(
737
+ model_b, "node_name_to_scope"
738
+ )
739
+ if maybe_model_b_node_name_to_scope is not None:
740
+ gm_b._node_name_to_scope = maybe_model_b_node_name_to_scope
741
+ return _add_shadow_loggers_impl(
742
+ name_a,
743
+ gm_a,
744
+ name_b,
745
+ gm_b,
746
+ logger_cls,
747
+ should_log_inputs=should_log_inputs,
748
+ base_name_to_sets_of_related_ops=base_name_to_sets_of_related_ops,
749
+ node_type_to_io_type_map=node_type_to_io_type_map,
750
+ unmatchable_types_map=unmatchable_types_map,
751
+ )
752
+
753
+
754
+ def extract_shadow_logger_info(
755
+ model_a_shadows_b: nn.Module,
756
+ logger_cls: Callable,
757
+ model_name_to_use_for_layer_names: str,
758
+ ) -> NSResultsType:
759
+ """
760
+ Traverse all loggers in a shadow model, and extract the logged
761
+ information.
762
+
763
+ Args:
764
+ model_a_shadows_b: shadow model
765
+ logger_cls: class of Logger to use
766
+ model_name_to_use_for_layer_names: string name of model to use for
767
+ layer names in the output
768
+
769
+ Return:
770
+ NSResultsType, containing the logged comparisons
771
+ """
772
+ torch._C._log_api_usage_once(
773
+ "quantization_api._numeric_suite_fx.extract_shadow_logger_info"
774
+ )
775
+ results: NSResultsType = collections.defaultdict(dict)
776
+ _extract_logger_info_one_model(model_a_shadows_b, results, logger_cls)
777
+ # fill in missing fqn entries
778
+ maybe_add_missing_fqns(results)
779
+ # rekey on the name of model b
780
+ results = rekey_logger_info_on_node_name_of_model(
781
+ results, model_name_to_use_for_layer_names
782
+ )
783
+ return dict(results)
784
+
785
+
786
+ def extend_logger_results_with_comparison(
787
+ results: NSResultsType,
788
+ model_name_1: str,
789
+ model_name_2: str,
790
+ comparison_fn: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
791
+ comparison_name: str,
792
+ ) -> None:
793
+ """
794
+ Compares the logged values from `model_name_2` against the corresponding
795
+ values in `model_name_1`, using `comparison_fn`. Records the result
796
+ in `model_name_2`'s results under `comparison_name`. Modifies `results` inplace.
797
+
798
+ Args:
799
+ results: the result data structure from `extract_logger_info` or
800
+ `extract_shadow_logger_info`.
801
+ model_name_1: string name of model 1
802
+ model_name_2: string name of model 2
803
+ comparison_fn: function to compare two Tensors
804
+ comparison_name: string name of model to use for
805
+ layer names in the output
806
+ """
807
+ for results_type_to_results in results.values():
808
+ for model_name_to_results in results_type_to_results.values():
809
+ if model_name_1 not in model_name_to_results:
810
+ raise AssertionError(f"{model_name_1} not found in results")
811
+ if model_name_2 not in model_name_to_results:
812
+ raise AssertionError(f"{model_name_2} not found in results")
813
+
814
+ results_1 = model_name_to_results[model_name_1]
815
+ results_2 = model_name_to_results[model_name_2]
816
+
817
+ for result_2 in results_2:
818
+ index_within_arg_2 = result_2["index_within_arg"]
819
+ index_of_arg_2 = result_2["index_of_arg"]
820
+ # find corresponding result_1
821
+ result_1 = None
822
+ for cur_result_1 in results_1:
823
+ index_within_arg_1 = cur_result_1["index_within_arg"]
824
+ index_of_arg_1 = cur_result_1["index_of_arg"]
825
+ if (index_within_arg_1 == index_within_arg_2) and (
826
+ index_of_arg_1 == index_of_arg_2
827
+ ):
828
+ result_1 = cur_result_1
829
+ break
830
+ if result_1 is None:
831
+ raise AssertionError("Expected result_1 to be not None")
832
+
833
+ values_1 = result_1["values"]
834
+ values_2 = result_2["values"]
835
+ result_2[comparison_name] = []
836
+ for value_1, value_2 in zip(values_1, values_2):
837
+ comparison_result = comparison_fn(value_1, value_2)
838
+ result_2[comparison_name].append(comparison_result)
839
+
840
+
841
+ def prepare_n_shadows_model(
842
+ model: torch.nn.Module,
843
+ example_inputs: Any,
844
+ qconfig_multi_mapping: QConfigMultiMapping,
845
+ backend_config: BackendConfig,
846
+ custom_prepare_fn: Callable | None = None,
847
+ custom_prepare_kwargs: dict[str, Any] | None = None,
848
+ custom_tracer: Any = None,
849
+ ) -> GraphModule:
850
+ """
851
+ Given a model with a graph with M ops such as
852
+
853
+
854
+ args_kwargs_m -> op_m -> output_m
855
+
856
+
857
+ And a set of N qconfigs for each op, creates a new model, with
858
+ each of the subgraph of `op_m` transformed into
859
+
860
+ .. code::
861
+
862
+ |---------> op_m_n -> log_m_n
863
+ | /
864
+ args_kwargs_m ---------> op_m -> log_m_0
865
+
866
+ Where op_m_n is op_m wrapped in a submodule and transformed with
867
+ qconfig_n, and its inner graph looks like
868
+
869
+ .. code::
870
+
871
+ args_m -------- op_m_prepared_with_qconfig_n -> out_m_n
872
+ /
873
+ kwargs_m ---
874
+
875
+ This is useful for testing different quantization of multiple layers in
876
+ a single pass through the model.
877
+
878
+ High level TODOs for future PRs:
879
+ * figure out a better way to name the output structure
880
+ * return a results data structure instead of printing it out
881
+ * add examples to docblocks
882
+ """
883
+
884
+ if custom_tracer is None:
885
+ tracer = quantize_fx.QuantizationTracer([], [])
886
+ else:
887
+ tracer = custom_tracer
888
+ mt = torch.fx.GraphModule(model, tracer.trace(model))
889
+ # this is necessary to ensure logger FQNs get populated
890
+ mt._node_name_to_scope = tracer.node_name_to_scope # type: ignore[assignment]
891
+
892
+ # run example input propagation, we need this to call prepare_fx on
893
+ # individual subgraphs
894
+ output_prop = OutputProp(mt)
895
+ output_prop.propagate(*example_inputs)
896
+
897
+ # Find the set of subgraphs in the original graph which we need to
898
+ # consider.
899
+ modules = dict(mt.named_modules(remove_duplicate=False))
900
+ patterns = _get_pattern_to_quantize_handlers(backend_config)
901
+ root_node_getter_mapping = get_fusion_pattern_to_root_node_getter(backend_config)
902
+ standalone_module_names: list[str] = []
903
+ standalone_module_classes: list[type] = []
904
+ custom_module_classes: list[type] = []
905
+ matches = _find_matches(
906
+ mt.graph,
907
+ modules,
908
+ patterns,
909
+ root_node_getter_mapping,
910
+ standalone_module_names,
911
+ standalone_module_classes,
912
+ custom_module_classes,
913
+ )
914
+ subgraphs_dedup: dict[str, list[Node]] = _get_dedup_subgraphs(matches)
915
+
916
+ # generate node to qconfig for each subgraph
917
+ # TODO(future PR): deduplicate repeating entries
918
+ list_of_node_name_to_qconfig: list[dict[str, QConfigAny]] = []
919
+ for qconfig_mapping in qconfig_multi_mapping.qconfig_mappings_list:
920
+ node_name_to_qconfig = _generate_node_name_to_qconfig(
921
+ mt, modules, mt.graph, qconfig_mapping, tracer.node_name_to_scope
922
+ )
923
+ list_of_node_name_to_qconfig.append(node_name_to_qconfig)
924
+
925
+ # For each region in the model, do the following:
926
+ # For each qconfig for that region, do the following:
927
+ # 1. create a copy of the region wrapped in a module
928
+ # 2. pass original args, original kwargs, and expected output to module
929
+ # 3. add an output comparison logger and hook it up to compare
930
+ # actual output to expected output
931
+ # 4. run `prepare_fx` on the module
932
+ for subgraph_idx, (match_name, nodes_in_this_subgraph) in enumerate(
933
+ subgraphs_dedup.items()
934
+ ):
935
+ create_n_transformed_and_logged_copies_of_subgraph(
936
+ mt,
937
+ subgraph_idx,
938
+ match_name,
939
+ nodes_in_this_subgraph,
940
+ qconfig_multi_mapping.qconfig_mappings_list,
941
+ list_of_node_name_to_qconfig,
942
+ custom_prepare_fn,
943
+ custom_prepare_kwargs, # type: ignore[arg-type]
944
+ )
945
+
946
+ return mt
947
+
948
+
949
+ # TODO(future PR): we should rethink the names of all the PNP APIs
950
+ def _prepare_n_shadows_add_loggers_model(
951
+ model: torch.nn.Module,
952
+ example_inputs: Any,
953
+ qconfig_mapping: QConfigMapping,
954
+ backend_config: BackendConfig,
955
+ ) -> torch.nn.Module:
956
+ r"""
957
+ Note: this API is not recommended for wide usage, it is only
958
+ provided for customers who need to migrate from the `add_loggers`
959
+ API.
960
+
961
+ This creates a model which provides logging for the following
962
+ problem: if we quantize `model` with `qconfig_mapping` and feed
963
+ the same input through both models, log the comparisons of
964
+ corresponding intermediate layers.
965
+
966
+ The problem is solved with a single model. Specifically, we
967
+ partition `model` into N subgraphs, create a copy of each relevant
968
+ subgraph, wrap it in a module, apply the quantization API to that
969
+ module, and hook up loggers to measure the comparisons.
970
+
971
+ Example starting graph:
972
+
973
+ x0 -> op0 -> x1 -> op1 -> x2
974
+
975
+ Example config: quantize op0 to int8, do nothing to op1.
976
+ The following graph will be created:
977
+
978
+ .. code::
979
+
980
+ x0_0 -> op0_0 -> x1_0 -> log -----> op1_0 -> x2_0 -> log
981
+ \ \ \ # noqa: W605
982
+ ---> op0_1 -> x1_1 ----> clog -> op1_0 -> x2_1 ----> clog
983
+
984
+ Where op0_0 is op0, op0_1 is op0 wrapped in a submodule and quantized
985
+ to int8, op1_0 is op1 (appearing in the graph twice), log is a logger,
986
+ and clog is a comparison logger.
987
+ """
988
+
989
+ tracer = quantize_fx.QuantizationTracer([], [])
990
+ mt = torch.fx.GraphModule(model, tracer.trace(model))
991
+ # this is necessary to ensure logger FQNs get populated
992
+ mt._node_name_to_scope = tracer.node_name_to_scope # type: ignore[assignment]
993
+
994
+ # run example input propagation, we need this to call prepare_fx on
995
+ # individual subgraphs
996
+ output_prop = OutputProp(mt)
997
+ output_prop.propagate(*example_inputs)
998
+
999
+ # Find the set of subgraphs in the original graph which we need to
1000
+ # consider.
1001
+ modules = dict(mt.named_modules(remove_duplicate=False))
1002
+ patterns = _get_pattern_to_quantize_handlers(backend_config)
1003
+ root_node_getter_mapping = get_fusion_pattern_to_root_node_getter(backend_config)
1004
+ standalone_module_names: list[str] = []
1005
+ standalone_module_classes: list[type] = []
1006
+ custom_module_classes: list[type] = []
1007
+ matches = _find_matches(
1008
+ mt.graph,
1009
+ modules,
1010
+ patterns,
1011
+ root_node_getter_mapping,
1012
+ standalone_module_names,
1013
+ standalone_module_classes,
1014
+ custom_module_classes,
1015
+ )
1016
+ subgraphs_dedup: dict[str, list[Node]] = _get_dedup_subgraphs(matches)
1017
+
1018
+ # generate node to qconfig for each subgraph
1019
+ node_name_to_qconfig = _generate_node_name_to_qconfig(
1020
+ mt, modules, mt.graph, qconfig_mapping, tracer.node_name_to_scope
1021
+ )
1022
+
1023
+ # Now, mutate the graph to be the add_loggers graph with propagation
1024
+ # error.
1025
+ create_add_loggers_graph(mt, subgraphs_dedup, qconfig_mapping, node_name_to_qconfig)
1026
+
1027
+ return mt
1028
+
1029
+
1030
+ # TODO(future PR): we should rethink the names of all the PNP APIs
1031
+ def _n_shadows_compare_weights(
1032
+ model: torch.nn.Module,
1033
+ example_inputs: Any,
1034
+ qconfig_mapping: QConfigMapping,
1035
+ backend_config: BackendConfig,
1036
+ ) -> NSResultsType:
1037
+ """
1038
+ Note: this API is not recommended for wide usage, it is only
1039
+ provided for customers who need to migrate from the `add_loggers`
1040
+ API.
1041
+ """
1042
+ qconfig_multi_mapping = QConfigMultiMapping.from_list_qconfig_mapping(
1043
+ [qconfig_mapping]
1044
+ )
1045
+ mp = prepare_n_shadows_model(
1046
+ model, example_inputs, qconfig_multi_mapping, backend_config
1047
+ )
1048
+ # passing inputs through the model is necessary to populate
1049
+ # observers which observe weights with real values
1050
+ mp(*example_inputs)
1051
+ mq = convert_n_shadows_model(mp)
1052
+ weight_comparison = extract_weight_comparison(mq)
1053
+ return weight_comparison
1054
+
1055
+
1056
+ # TODO(future PR): consider aligning API signature with other similar quantization
1057
+ # functions (enable_fake_quant, etc)
1058
+ def loggers_set_enabled(model: torch.nn.Module, enabled: bool) -> None:
1059
+ """
1060
+ Sets the `enabled` setting on a `model`'s loggers
1061
+ """
1062
+ for _, child in model.named_modules():
1063
+ if isinstance(child, OutputLogger):
1064
+ child.enabled = enabled
1065
+
1066
+
1067
+ # TODO(future PR): consider aligning API signature with other similar quantization
1068
+ # functions (enable_fake_quant, etc)
1069
+ def loggers_set_save_activations(
1070
+ model: torch.nn.Module,
1071
+ save_activations: bool,
1072
+ ) -> None:
1073
+ """
1074
+ Sets the `save_activations` setting on a `model`'s loggers
1075
+ """
1076
+ for _name, child in model.named_modules():
1077
+ if isinstance(child, OutputLogger):
1078
+ child.save_activations = save_activations
1079
+
1080
+
1081
+ def convert_n_shadows_model(
1082
+ model: GraphModule,
1083
+ custom_convert_fn: Callable | None = None,
1084
+ custom_convert_kwargs: dict[str, Any] | None = None,
1085
+ ) -> GraphModule:
1086
+ """
1087
+ Given a model from `prepare_n_shadows_model`, runs `convert_fx`
1088
+ on each shadow submodule.
1089
+ """
1090
+ for node in model.graph.nodes:
1091
+ # TODO(future PR): consider matching in a safer way than
1092
+ # node name string match
1093
+ if node.name.startswith(SHADOW_WRAPPER_NODE_NAME_PREFIX):
1094
+ orig_mod = getattr(model, node.name)
1095
+ if custom_convert_fn is None:
1096
+ converted_mod = torch.ao.quantization.quantize_fx.convert_fx(orig_mod)
1097
+ else:
1098
+ if custom_convert_kwargs is None:
1099
+ custom_convert_kwargs = {}
1100
+ converted_mod = custom_convert_fn(orig_mod, **custom_convert_kwargs)
1101
+ setattr(model, node.name, converted_mod)
1102
+
1103
+ return model
1104
+
1105
+
1106
+ def extract_results_n_shadows_model(model: torch.nn.Module) -> NSResultsType:
1107
+ """
1108
+ Extracts logger results from `model`.
1109
+ """
1110
+ results: NSResultsType = {}
1111
+ _extract_logger_info_one_model(model, results, OutputLogger)
1112
+ return results
1113
+
1114
+
1115
+ def print_comparisons_n_shadows_model(results: NSResultsType) -> None:
1116
+ """
1117
+ Prints a summary of extracted `results`.
1118
+ """
1119
+ results_grouped = group_results_by_subgraph(results)
1120
+ results_comparison = create_results_comparison(results_grouped)
1121
+ print_n_shadows_summary(results_comparison)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/graph_matcher.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections
3
+ import enum
4
+ from typing import Any
5
+
6
+ import torch
7
+ from torch.ao.quantization import FakeQuantizeBase, ObserverBase
8
+ from torch.ao.quantization.utils import getattr_from_fqn
9
+ from torch.fx import GraphModule
10
+ from torch.fx.graph import Graph, Node
11
+
12
+ from .mappings import get_base_name_to_sets_of_related_ops, get_unmatchable_types_map
13
+ from .ns_types import NSNodeTargetType, NSSubgraph
14
+ from .pattern_utils import (
15
+ end_node_matches_reversed_fusion,
16
+ get_reversed_fusions,
17
+ get_type_a_related_to_b,
18
+ )
19
+
20
+
21
+ toq = torch.ops.quantized
22
+
23
+
24
+ def _get_output_nodes(g: Graph) -> list[Node]:
25
+ return [n for n in g.nodes if n.op == "output"]
26
+
27
+
28
+ class _NSGraphMatchableSubgraphsIterator:
29
+ """
30
+ Iterates through the graph of gm, starting with the output nodes
31
+ and continuing backwards.
32
+ 1. Returns matchable subgraphs, in order. A subgraph is defined by
33
+ (start_node, end_node).
34
+ 2. Skips over non-matchable subgraphs
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ gm: GraphModule,
40
+ non_matchable_functions: set[NSNodeTargetType],
41
+ non_matchable_modules: set[NSNodeTargetType],
42
+ non_matchable_methods: set[NSNodeTargetType],
43
+ ):
44
+ self.gm: GraphModule = gm
45
+ self.non_matchable_functions: set[NSNodeTargetType] = non_matchable_functions
46
+ self.non_matchable_modules: set[NSNodeTargetType] = non_matchable_modules
47
+ self.non_matchable_methods: set[NSNodeTargetType] = non_matchable_methods
48
+ self.seen_nodes: set[Node] = set()
49
+ self.stack: list[Node] = []
50
+ for start_node in _get_output_nodes(self.gm.graph):
51
+ self.stack.append(start_node)
52
+
53
+ def __iter__(self):
54
+ return self
55
+
56
+ def __next__(self) -> NSSubgraph:
57
+ """
58
+ Returns the next matchable subgraph.
59
+ """
60
+ while len(self.stack) > 0:
61
+ cur_end_node = self.stack.pop()
62
+ if cur_end_node in self.seen_nodes:
63
+ continue
64
+
65
+ # for subgraphs which are single nodes, start_node == end_node
66
+ # for subgraphs with more than one node, start node != end_node
67
+ cur_start_node = cur_end_node
68
+ # Subgraphs like linear-relu have the base node as the start node.
69
+ # Subgraphs like dequantize-linear-relu-to(torch.float16) have the
70
+ # base node as the second node.
71
+ # The cur_base_op_node var will move to the actual node during
72
+ # the fusion matching later in this code block.
73
+ cur_base_op_node = cur_end_node
74
+
75
+ # Check for potential fusions. For now, we are greedy
76
+ # and always skip all non-base nodes of a fusion. For example,
77
+ # if we match linear-relu backwards, we will always skip the
78
+ # relu node and attempt to match the linear node. This can
79
+ # be made configurable later if needed.
80
+ for _reverse_fusion_ops, base_op_idx in get_reversed_fusions():
81
+ is_match = end_node_matches_reversed_fusion(
82
+ cur_end_node, _reverse_fusion_ops, self.gm, self.seen_nodes
83
+ )
84
+ if is_match:
85
+ # navigate to the base node
86
+ for rev_fusion_idx in range(len(_reverse_fusion_ops) - 1):
87
+ # pyrefly: ignore [bad-argument-type]
88
+ self.seen_nodes.add(cur_start_node)
89
+ # for now, assume that there are no other nodes
90
+ # which need to be added to the stack
91
+ cur_start_node = cur_start_node.args[0] # type: ignore[assignment]
92
+ # if the base op index matches the current node, set it
93
+ rev_base_op_idx = len(_reverse_fusion_ops) - 2 - base_op_idx
94
+ if rev_fusion_idx == rev_base_op_idx:
95
+ cur_base_op_node = cur_start_node
96
+ break
97
+
98
+ # pyrefly: ignore [bad-argument-type]
99
+ self.seen_nodes.add(cur_start_node)
100
+ # add args of previous nodes to stack
101
+ # pyrefly: ignore [missing-attribute]
102
+ for arg in cur_start_node.all_input_nodes:
103
+ self._recursively_add_node_arg_to_stack(arg)
104
+
105
+ # skip unmatchable nodes
106
+ # note: this check is done on the start_node, i.e.
107
+ # if we are matching linear-relu in reverse, this would do the matchable
108
+ # check on the linear
109
+ # pyrefly: ignore [bad-argument-type]
110
+ if not self._is_matchable(cur_base_op_node):
111
+ continue
112
+
113
+ # If an observer or a fake_quant was not matched as a part of
114
+ # a pattern of multiple nodes, ignore it. One case where this is
115
+ # relevant is an observer on a graph input, which was added because
116
+ # it is necessary for the next node.
117
+ if cur_end_node.op == "call_module" and cur_start_node is cur_end_node:
118
+ maybe_obs = getattr_from_fqn(self.gm, cur_end_node.target) # type: ignore[arg-type]
119
+ if isinstance(maybe_obs, (ObserverBase, FakeQuantizeBase)):
120
+ continue
121
+
122
+ return NSSubgraph(
123
+ # pyrefly: ignore [bad-argument-type]
124
+ start_node=cur_start_node,
125
+ end_node=cur_end_node,
126
+ # pyrefly: ignore [bad-argument-type]
127
+ base_op_node=cur_base_op_node,
128
+ )
129
+
130
+ raise StopIteration
131
+
132
+ def _recursively_add_node_arg_to_stack(self, arg: Any) -> None:
133
+ """
134
+ Adds all of the nodes in this arg to the stack, properly navigating
135
+ through list, dicts and tuples.
136
+ """
137
+ if isinstance(arg, Node):
138
+ self.stack.append(arg)
139
+ elif (
140
+ isinstance(arg, torch.fx.immutable_collections.immutable_list)
141
+ or type(arg) is tuple
142
+ ):
143
+ for inner_arg in arg:
144
+ self._recursively_add_node_arg_to_stack(inner_arg)
145
+ elif isinstance(arg, torch.fx.immutable_collections.immutable_dict):
146
+ for value in arg.values():
147
+ self._recursively_add_node_arg_to_stack(value)
148
+
149
+ def _is_matchable(self, node: Node) -> bool:
150
+ if node.op == "call_function":
151
+ return node.target not in self.non_matchable_functions
152
+ elif node.op == "call_module":
153
+ if not isinstance(node.target, str):
154
+ raise AssertionError(f"Expected str, got {type(node.target)}")
155
+ target_mod = getattr_from_fqn(self.gm, node.target)
156
+ return not any(
157
+ isinstance(target_mod, t) # type: ignore[arg-type]
158
+ for t in self.non_matchable_modules
159
+ )
160
+ elif node.op == "call_method":
161
+ return node.target not in self.non_matchable_methods
162
+ else:
163
+ return False
164
+
165
+
166
+ class GraphMatchingException(Exception):
167
+ """
168
+ Exception raised when two graphs cannot be matched.
169
+ """
170
+
171
+
172
+ class SubgraphTypeRelationship(enum.Enum):
173
+ # same type, known
174
+ # example: F.linear and F.linear, or nn.Conv2d and nn.Conv2d
175
+ EQUAL = enum.auto()
176
+ # same type, but the type is not known to Numerical Suite
177
+ # (user defined type, etc).
178
+ EQUAL_BUT_UKNOWN = enum.auto()
179
+ # known, same subgraph_relationship set, but not the same type
180
+ # example: F.linear and toq.linear
181
+ RELATED_BUT_NOT_EQUAL = enum.auto()
182
+ # not related
183
+ NOT_RELATED = enum.auto()
184
+
185
+
186
+ def _get_subgraph_relationship_type(
187
+ subgraph_a: NSSubgraph,
188
+ subgraph_b: NSSubgraph,
189
+ gm_a: GraphModule,
190
+ gm_b: GraphModule,
191
+ type_a_related_to_b: set[tuple[NSNodeTargetType, NSNodeTargetType]],
192
+ ) -> SubgraphTypeRelationship:
193
+ node_a = subgraph_a.base_op_node
194
+ node_b = subgraph_b.base_op_node
195
+
196
+ # TODO(next): make this code handle matching by what is before the base op
197
+ if node_a.op != node_b.op:
198
+ if not (
199
+ node_a.op in ("call_function", "call_method")
200
+ and node_b.op in ("call_function", "call_method")
201
+ ):
202
+ return SubgraphTypeRelationship.NOT_RELATED
203
+
204
+ if node_a.op in ("call_function", "call_method"):
205
+ key = (node_a.target, node_b.target)
206
+
207
+ if key not in type_a_related_to_b:
208
+ if node_a.target == node_b.target:
209
+ return SubgraphTypeRelationship.EQUAL_BUT_UKNOWN
210
+ else:
211
+ return SubgraphTypeRelationship.NOT_RELATED
212
+ # after this point, we are dealing with known types
213
+
214
+ if node_a.target == node_b.target:
215
+ node_a_has_prev = subgraph_a.base_op_node == subgraph_a.start_node
216
+ node_b_has_prev = subgraph_b.base_op_node == subgraph_b.start_node
217
+ if node_a_has_prev and (not node_b_has_prev):
218
+ return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
219
+ elif (not node_a_has_prev) and node_b_has_prev:
220
+ return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
221
+ elif (not node_a_has_prev) and (not node_b_has_prev):
222
+ return SubgraphTypeRelationship.EQUAL
223
+ else:
224
+ # TODO(future PR): check for matches start_op_node and base_op_node
225
+ return SubgraphTypeRelationship.EQUAL
226
+
227
+ if key in type_a_related_to_b:
228
+ return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
229
+ else:
230
+ return SubgraphTypeRelationship.NOT_RELATED
231
+ elif node_a.op == "call_module":
232
+ if (
233
+ subgraph_a.base_op_node != subgraph_a.start_node
234
+ or subgraph_b.base_op_node != subgraph_b.start_node
235
+ ):
236
+ raise AssertionError(
237
+ "Matching call_module patterns where base_op_node != start_node is not supported yet"
238
+ )
239
+ # for call_module, we need to look up the modules to do the type check
240
+ if not isinstance(node_a.target, str):
241
+ raise AssertionError(f"Expected str, got {type(node_a.target)}")
242
+ mod_a = getattr_from_fqn(gm_a, node_a.target)
243
+ if not isinstance(node_b.target, str):
244
+ raise AssertionError(f"Expected str, got {type(node_b.target)}")
245
+ mod_b = getattr_from_fqn(gm_b, node_b.target)
246
+
247
+ key = (type(mod_a), type(mod_b))
248
+
249
+ if key not in type_a_related_to_b:
250
+ if type(mod_a) is type(mod_b):
251
+ return SubgraphTypeRelationship.EQUAL_BUT_UKNOWN
252
+ else:
253
+ return SubgraphTypeRelationship.NOT_RELATED
254
+ elif type(mod_a) is type(mod_b):
255
+ return SubgraphTypeRelationship.EQUAL
256
+ else:
257
+ return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
258
+
259
+ return SubgraphTypeRelationship.NOT_RELATED
260
+
261
+
262
+ def _get_name_for_subgraph(
263
+ subgraph_a: NSSubgraph,
264
+ gm_a: GraphModule,
265
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]],
266
+ existing_names: set[str],
267
+ ) -> str:
268
+ """
269
+ Returns a unique name for a subgraph. This name is based on two things:
270
+ 1. the name of the set containing the underlying type of the base op in the
271
+ subgraph (i.e. 'torch.nn.functional.linear' if this is related to a linear op)
272
+ 2. the number of previous subgraphs with related underlying type of the base op
273
+
274
+ For example, in the graph
275
+
276
+ linear0 -> relu0 -> linear1 -> relu1
277
+
278
+ The subgraphs are (linear0, relu0) and (linear1, relu1). If we iterate
279
+ from the output node backwards, the name given to (linear1, relu1) will be
280
+ `base_op_torch.nn.functional.linear_0`, and the name given to (linear0, relu0)
281
+ will be `base_op_torch.nn.functional.linear_1`.
282
+
283
+ Why are we not just using the node name? Answer: because of two requirements:
284
+ A. fusions must be supported
285
+ B. some Numeric Suite APIs can be called without having all of the models in memory
286
+
287
+ For example, let's say we need to match nodes of
288
+
289
+ (1) ... -> linear0 -> relu0 -> ...
290
+
291
+ And
292
+
293
+ (2) ... -> linear_relu0 -> ...
294
+
295
+ Without being able to inspect them together. With the current naming scheme, if
296
+ we iterate through both of these graphs in the same order, and assuming the rest
297
+ of the graphs match, both of these subgraphs will get the same name without
298
+ (1) and (2) knowing anything about each other.
299
+ """
300
+ target_type = _get_node_target_type(subgraph_a.base_op_node, gm_a)
301
+ target_base_type = None
302
+ for base_name, sets_of_related_ops in base_name_to_sets_of_related_ops.items():
303
+ if target_type in sets_of_related_ops:
304
+ target_base_type = base_name
305
+ target_base_name = "base_op_" + str(target_base_type)
306
+ counter = 0
307
+ proposed_name = target_base_name + "_" + str(counter)
308
+ while proposed_name in existing_names:
309
+ counter += 1
310
+ proposed_name = target_base_name + "_" + str(counter)
311
+ existing_names.add(proposed_name)
312
+ return proposed_name
313
+
314
+
315
+ def _get_node_target_type(node: Node, gm: GraphModule) -> NSNodeTargetType | None:
316
+ if node.op in ("call_function", "call_method"):
317
+ return node.target
318
+ elif node.op == "call_module":
319
+ if not isinstance(node.target, str):
320
+ raise AssertionError(f"Expected str, got {type(node.target)}")
321
+ mod = getattr_from_fqn(gm, node.target)
322
+ return type(mod)
323
+ return None
324
+
325
+
326
+ def get_matching_subgraph_pairs(
327
+ gm_a: GraphModule,
328
+ gm_b: GraphModule,
329
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] | None = None,
330
+ unmatchable_types_map: dict[str, set[NSNodeTargetType]] | None = None,
331
+ ) -> dict[str, tuple[NSSubgraph, NSSubgraph]]:
332
+ """
333
+ Matches matchable subgraphs of graph_a to graph_b.
334
+
335
+ For a node, "matchable" is defined as a node which is not an observer,
336
+ fake_quants, quant or dequant.
337
+
338
+ A subgraph can contain one or more nodes. A subgraph is matchable if
339
+ at least one node inside of it is matchable. Currently, all nodes in
340
+ a subgraph must be matchable (because we assume no observers will be
341
+ inserted in the middle of a fusion).
342
+
343
+ A subgraph is defined by (start_node, end_node). We assume that only
344
+ start_node and end_node are linked with the surrounding graph, all other
345
+ nodes in a subgraph are self-contained.
346
+
347
+ A pair of nodes is "related" if both nodes represent the same mathematical
348
+ operation across different quantization flavors. For example,
349
+ `F.linear` and `torch.ops.quantized.linear` are related, and
350
+ `F.linear` and `torch.nn.Conv` are not related.
351
+
352
+ For each matchable pair of nodes node_a and node_b, they will match
353
+ if node_a and node_b are related.
354
+
355
+ For graphs A and B, they will match iff:
356
+ 1. the number of matchable subgraphs in A and B is equivalent
357
+ 2. when iterating through the matchable subgraphs of A and B in the same order, each
358
+ corresponding pair of base nodes is related.
359
+
360
+ This enables us to find the corresponding subgraphs between
361
+ graphs of related models. For example, if we had two graphs such as:
362
+
363
+ graph_a: x0 -> conv_0 (type: nn.Conv2d) -> obs_0 -> x1
364
+ w -/
365
+ b -/
366
+
367
+ graph_b: x0 -> quant_0 -> qconv_0 (type: nnq.Conv2d) -> dequant_0 -> x1
368
+ packed_params_0 -/
369
+
370
+ This function will return the following result:
371
+ {
372
+ 'conv_0': ( # the name of the node in graph_b
373
+ (conv_0, conv_0), # (start_node_a, end_node_a)
374
+ (qconv_0, qconv_0), # (start_node_b, end_node_b)
375
+ ),
376
+ }
377
+
378
+ Or, if we have a fusion pattern,
379
+
380
+ graph_a: x0 -> linear_0 -> relu_0 -> obs_0 -> x1
381
+ w -/
382
+ b -/
383
+
384
+ graph_b: x0 -> quant_0 -> linear_relu_0 -> dequant_0 -> x1
385
+ packed_params_0 -/
386
+
387
+ This function will return the following result:
388
+ {
389
+ 'linear_relu_0': ( # the name of the node in graph_b
390
+ (linear_0, relu_0), # (start_node_a, end_node_a)
391
+ (linear_relu_0, linear_relu_0), # (start_node_b, end_node_b)
392
+ ),
393
+ }
394
+ """
395
+ if unmatchable_types_map is None:
396
+ unmatchable_types_map = get_unmatchable_types_map()
397
+ non_matchable_functions = unmatchable_types_map["funs_unmatchable"]
398
+ non_matchable_modules = unmatchable_types_map["mods_unmatchable"]
399
+ non_matchable_methods = unmatchable_types_map["meths_unmatchable"]
400
+
401
+ graph_a_iterator = _NSGraphMatchableSubgraphsIterator(
402
+ gm_a, non_matchable_functions, non_matchable_modules, non_matchable_methods
403
+ )
404
+ graph_b_iterator = _NSGraphMatchableSubgraphsIterator(
405
+ gm_b, non_matchable_functions, non_matchable_modules, non_matchable_methods
406
+ )
407
+ results = collections.OrderedDict()
408
+ if base_name_to_sets_of_related_ops is None:
409
+ base_name_to_sets_of_related_ops = get_base_name_to_sets_of_related_ops()
410
+ type_a_related_to_b = get_type_a_related_to_b(base_name_to_sets_of_related_ops)
411
+
412
+ existing_names_a: set[str] = set()
413
+ existing_names_b: set[str] = set()
414
+
415
+ while True:
416
+ # fetch the next subgraphs from a and b
417
+ cur_subgraph_a, cur_subgraph_b = None, None
418
+ try:
419
+ cur_subgraph_a = next(graph_a_iterator)
420
+ except StopIteration:
421
+ pass
422
+ try:
423
+ cur_subgraph_b = next(graph_b_iterator)
424
+ except StopIteration:
425
+ pass
426
+
427
+ # look up types of a and b for useful error messages
428
+ type_start_a, type_start_b = None, None
429
+ if cur_subgraph_a is not None:
430
+ type_start_a = _get_node_target_type(cur_subgraph_a.start_node, gm_a)
431
+ if cur_subgraph_b is not None:
432
+ type_start_b = _get_node_target_type(cur_subgraph_b.start_node, gm_b)
433
+
434
+ # check for results and determine what to do next
435
+ if cur_subgraph_a is not None and cur_subgraph_b is not None:
436
+ # both nodes were fetched, check for subgraph_relationship
437
+ # note: subgraph_relationship is checked on the start node, i.e.
438
+ # if a linear-relu pattern is checked, we would check for subgraph_relationship
439
+ # of the linear
440
+ subgraph_relationship = _get_subgraph_relationship_type(
441
+ cur_subgraph_a, cur_subgraph_b, gm_a, gm_b, type_a_related_to_b
442
+ )
443
+ if subgraph_relationship == SubgraphTypeRelationship.NOT_RELATED:
444
+ msg = f"""
445
+ The subgraphs
446
+ ({cur_subgraph_a}, {type_start_a}) and
447
+ ({cur_subgraph_b}, {type_start_b})
448
+ are not related. Please ensure that the two models you pass in have the same number
449
+ of subgraphs, and each pair of subgraphs is related to each other."""
450
+ raise GraphMatchingException(msg)
451
+ elif subgraph_relationship == SubgraphTypeRelationship.EQUAL_BUT_UKNOWN:
452
+ # skip matching but unknown types
453
+ continue
454
+ key_name_a = _get_name_for_subgraph(
455
+ cur_subgraph_a, gm_a, base_name_to_sets_of_related_ops, existing_names_a
456
+ )
457
+ key_name_b = _get_name_for_subgraph(
458
+ cur_subgraph_b, gm_b, base_name_to_sets_of_related_ops, existing_names_b
459
+ )
460
+ if key_name_a != key_name_b:
461
+ raise AssertionError(
462
+ f"Subgraph names {key_name_a} and {key_name_b} do not match"
463
+ )
464
+ results[key_name_a] = (cur_subgraph_a, cur_subgraph_b)
465
+ continue
466
+ elif cur_subgraph_a is None and cur_subgraph_b is None:
467
+ # we reached the end of both graphs
468
+ break
469
+ else:
470
+ # only one node was fetched, no match possible, throw error
471
+ msg = f"""
472
+ Attempting to match
473
+ ({cur_subgraph_a}, {type_start_a}) and
474
+ ({cur_subgraph_b}, {type_start_b}),
475
+ one of which is empty. Please ensure that the two models you pass in have the same number
476
+ of subgraphs."""
477
+ raise GraphMatchingException(msg)
478
+
479
+ # The subgraph pairs are originally created by traversing the two graphs
480
+ # from the outputs to the inputs. Reverse the results to return the
481
+ # subgraphs in their order of execution.
482
+ results = collections.OrderedDict(reversed(results.items()))
483
+
484
+ # pyrefly: ignore [bad-return]
485
+ return results
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/graph_passes.py ADDED
@@ -0,0 +1,1155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections.abc import Callable
3
+ from typing import Any
4
+
5
+ import torch
6
+ from torch.ao.ns.fx.mappings import get_node_type_to_io_type_map
7
+ from torch.ao.quantization.fx.utils import get_new_attr_name_with_prefix
8
+ from torch.ao.quantization.observer import _is_activation_post_process
9
+ from torch.fx import GraphModule, map_arg
10
+ from torch.fx.graph import Graph, Node
11
+
12
+ from .ns_types import NSNodeTargetType, NSSingleResultValuesType, NSSubgraph
13
+ from .utils import (
14
+ get_arg_indices_of_inputs_to_log,
15
+ get_node_first_input_and_output_type,
16
+ get_node_input_qparams,
17
+ get_normalized_nth_input,
18
+ get_number_of_non_param_args,
19
+ get_target_type_str,
20
+ getattr_from_fqn,
21
+ NodeInputOrOutputType,
22
+ op_type_supports_shadowing,
23
+ return_first_non_observer_node,
24
+ )
25
+
26
+
27
+ def _maybe_get_fqn(node: Node, gm: GraphModule) -> str | None:
28
+ fqn = None
29
+ if hasattr(gm, "_node_name_to_scope"):
30
+ # fqn on observers is not present, because they do not
31
+ # exist when the fqns are created during tracing. If this is
32
+ # an observer, get the fqn of the node being observed.
33
+ node_to_use_for_fqn = node
34
+ if node.op == "call_module":
35
+ if not isinstance(node.target, str):
36
+ raise AssertionError(f"Expected str, got {type(node.target)}")
37
+ module = getattr_from_fqn(gm, node.target)
38
+ if _is_activation_post_process(module):
39
+ node_to_use_for_fqn = get_normalized_nth_input(node, gm, 0)
40
+ fqn = gm._node_name_to_scope[node_to_use_for_fqn.name][0] # type: ignore[index]
41
+ return fqn # type: ignore[return-value]
42
+
43
+
44
+ def _insert_logger_after_node(
45
+ node: Node,
46
+ gm: GraphModule,
47
+ logger_cls: Callable,
48
+ logger_node_name_suffix: str,
49
+ ref_node_name: str,
50
+ model_name: str,
51
+ ref_name: str,
52
+ ref_node_target_type: str,
53
+ results_type: str,
54
+ index_within_arg: int,
55
+ index_of_arg: int,
56
+ fqn: str | None,
57
+ ) -> Node:
58
+ """
59
+ Given a starting graph of
60
+
61
+ prev_node -> node -> next_node
62
+
63
+ This function creates a new logger_cls obj and adds it
64
+ after node, resulting in
65
+
66
+ prev_node -> node -> logger_obj -> next_node
67
+ """
68
+ # create new name
69
+ logger_node_name = get_new_attr_name_with_prefix(
70
+ node.name + logger_node_name_suffix
71
+ )(gm)
72
+ target_type = get_target_type_str(node, gm)
73
+ # create the logger object
74
+ logger_obj = logger_cls(
75
+ ref_node_name,
76
+ node.name,
77
+ model_name,
78
+ ref_name,
79
+ target_type,
80
+ ref_node_target_type,
81
+ results_type,
82
+ index_within_arg,
83
+ index_of_arg,
84
+ fqn,
85
+ )
86
+ # attach the logger object to the parent module
87
+ setattr(gm, logger_node_name, logger_obj)
88
+ logger_node = node.graph.create_node("call_module", logger_node_name, (node,), {})
89
+ return logger_node
90
+
91
+
92
+ def add_loggers_to_model(
93
+ gm: GraphModule,
94
+ node_to_instrument_inputs_to_ref_node_name: dict[Node, tuple[str, str]],
95
+ node_to_instrument_outputs_to_ref_node_name: dict[Node, tuple[str, str]],
96
+ logger_cls: Callable,
97
+ model_name: str,
98
+ ) -> GraphModule:
99
+ """
100
+ Takes the graph of gm, adds loggers to the output
101
+ of each node in nodes_to_instrument. Returns a GraphModule with the new
102
+ graph.
103
+ """
104
+
105
+ new_graph = Graph()
106
+ env: dict[str, Any] = {}
107
+
108
+ def load_arg(a):
109
+ return map_arg(a, lambda node: env[node.name])
110
+
111
+ for node in gm.graph.nodes:
112
+ if node.op == "output":
113
+ new_graph.output(map_arg(get_normalized_nth_input(node, gm, 0), load_arg))
114
+ continue
115
+
116
+ if (node in node_to_instrument_inputs_to_ref_node_name) or (
117
+ node in node_to_instrument_outputs_to_ref_node_name
118
+ ):
119
+ fqn = _maybe_get_fqn(node, gm)
120
+
121
+ if node in node_to_instrument_inputs_to_ref_node_name:
122
+ ref_name, ref_node_type = node_to_instrument_inputs_to_ref_node_name[
123
+ node
124
+ ]
125
+ # Ops such add and mul are special because either
126
+ # one or two of the first two arguments can be tensors,
127
+ # and if one argument is a tensor it can be first or
128
+ # second (x + 1 versus 1 + x).
129
+ arg_indices_to_log = get_arg_indices_of_inputs_to_log(node)
130
+ for node_arg_idx in arg_indices_to_log:
131
+ node_arg = get_normalized_nth_input(node, gm, node_arg_idx)
132
+ if type(node_arg) is Node:
133
+ # create a single input logger
134
+ prev_node = env[node_arg.name]
135
+ env[node_arg.name] = _insert_logger_after_node(
136
+ prev_node,
137
+ gm,
138
+ logger_cls,
139
+ "_ns_logger_",
140
+ node.name,
141
+ model_name,
142
+ ref_name,
143
+ ref_node_type,
144
+ NSSingleResultValuesType.NODE_INPUT.value,
145
+ index_within_arg=0,
146
+ index_of_arg=node_arg_idx,
147
+ fqn=fqn,
148
+ )
149
+ elif (
150
+ type(node_arg) is torch.fx.immutable_collections.immutable_list
151
+ ):
152
+ # create N input loggers, one for each node
153
+ for arg_idx, arg in enumerate(node_arg): # type: ignore[var-annotated, arg-type]
154
+ prev_node = env[arg.name]
155
+ env[prev_node.name] = _insert_logger_after_node(
156
+ prev_node,
157
+ gm,
158
+ logger_cls,
159
+ "_ns_logger_",
160
+ node.name,
161
+ model_name,
162
+ ref_name,
163
+ ref_node_type,
164
+ NSSingleResultValuesType.NODE_INPUT.value,
165
+ index_within_arg=arg_idx,
166
+ index_of_arg=node_arg_idx,
167
+ fqn=fqn,
168
+ )
169
+
170
+ # ensure env is populated with base node
171
+ # Note: runs for both inputs and outputs
172
+ env[node.name] = new_graph.node_copy(node, load_arg)
173
+
174
+ if node in node_to_instrument_outputs_to_ref_node_name:
175
+ ref_name, ref_node_type = node_to_instrument_outputs_to_ref_node_name[
176
+ node
177
+ ]
178
+ # add the logger after the base node
179
+ env[node.name] = _insert_logger_after_node(
180
+ env[node.name],
181
+ gm,
182
+ logger_cls,
183
+ "_ns_logger_",
184
+ node.name,
185
+ model_name,
186
+ ref_name,
187
+ ref_node_type,
188
+ NSSingleResultValuesType.NODE_OUTPUT.value,
189
+ index_within_arg=0,
190
+ index_of_arg=0,
191
+ fqn=fqn,
192
+ )
193
+
194
+ else:
195
+ env[node.name] = new_graph.node_copy(node, load_arg)
196
+
197
+ new_gm = GraphModule(gm, new_graph)
198
+ return new_gm
199
+
200
+
201
+ def _insert_quantize_per_tensor_node(
202
+ prev_node_c: Node,
203
+ node_a: Node,
204
+ gm_b: GraphModule,
205
+ graph_c: Graph,
206
+ scale: torch.Tensor | float,
207
+ zero_point: torch.Tensor | int,
208
+ dtype_cast_name: str,
209
+ ) -> Node:
210
+ # copy scale
211
+ scale_node_name = get_new_attr_name_with_prefix(node_a.name + "_input_scale_")(gm_b)
212
+ setattr(gm_b, scale_node_name, scale)
213
+ scale_node = graph_c.create_node(
214
+ "get_attr", scale_node_name, (), {}, scale_node_name
215
+ )
216
+ # copy zero_point
217
+ zero_point_node_name = get_new_attr_name_with_prefix(
218
+ node_a.name + "_input_zero_point_"
219
+ )(gm_b)
220
+ setattr(gm_b, zero_point_node_name, zero_point)
221
+ zero_point_node = graph_c.create_node(
222
+ "get_attr", zero_point_node_name, (), {}, zero_point_node_name
223
+ )
224
+ # create the quantize_per_tensor call
225
+ return graph_c.create_node(
226
+ "call_function",
227
+ torch.quantize_per_tensor,
228
+ (prev_node_c, scale_node, zero_point_node, torch.quint8),
229
+ {},
230
+ dtype_cast_name,
231
+ )
232
+
233
+
234
+ def _insert_dtype_cast_after_node(
235
+ node_a: Node,
236
+ node_c: Node,
237
+ prev_node_c: Node | list[Node],
238
+ gm_a: GraphModule,
239
+ gm_b: GraphModule,
240
+ graph_c: Graph,
241
+ node_name_prefix: str,
242
+ logger_cls: Callable,
243
+ node_type_to_io_type_map: dict[str, set[NSNodeTargetType]],
244
+ ) -> Node | list[Node]:
245
+ """
246
+ Given a starting graph C (derived from graph B) of
247
+
248
+ ... -> prev_node_c -> node_c -> ...
249
+
250
+ And a corresponding related node_a, inserts the correct dtype
251
+ cast node after prev_node_c to cast into the dtype expected
252
+ by node_a, resulting in:
253
+
254
+ dtype_cast
255
+ /
256
+ ... -> prev_node_c -> node_c -> ...
257
+
258
+ For example, if node_c is an int8 op and node_a is an fp32 op, this function
259
+ will insert a dequant.
260
+ """
261
+ dtype_cast_op = None
262
+ dtype_cast_mod_cls = None
263
+ dtype_cast_method = None
264
+ dtype_cast_method_dtype = None
265
+ dtype_cast_scale = None
266
+ dtype_cast_zero_point = None
267
+ node_input_type_a, _node_output_type_a = get_node_first_input_and_output_type(
268
+ node_a, gm_a, logger_cls, node_type_to_io_type_map
269
+ )
270
+ node_input_type_c, _node_output_type_c = get_node_first_input_and_output_type(
271
+ node_c, gm_b, logger_cls, node_type_to_io_type_map
272
+ )
273
+
274
+ if (
275
+ (
276
+ node_input_type_a == NodeInputOrOutputType.FP32
277
+ and node_input_type_c == NodeInputOrOutputType.INT8
278
+ )
279
+ or (
280
+ node_input_type_a == NodeInputOrOutputType.FP32
281
+ and node_input_type_c == NodeInputOrOutputType.FP16
282
+ )
283
+ or
284
+ # TODO(future PR): determine the actual dtype of node_c,
285
+ # the current code only works because dequantize works with
286
+ # multiple input dtypes.
287
+ (
288
+ node_input_type_a == NodeInputOrOutputType.FP32
289
+ and node_input_type_c == NodeInputOrOutputType.FP32_OR_INT8
290
+ )
291
+ ):
292
+ dtype_cast_op = torch.dequantize
293
+ elif (
294
+ node_input_type_a == node_input_type_c
295
+ and node_input_type_a != NodeInputOrOutputType.UNKNOWN
296
+ ):
297
+ dtype_cast_mod_cls = torch.nn.Identity
298
+ elif (
299
+ node_input_type_a == NodeInputOrOutputType.INT8
300
+ and node_input_type_c == NodeInputOrOutputType.FP32
301
+ ):
302
+ # int8 shadows fp32, the dtype cast needs to quantize to int8
303
+ # with the right qparams.
304
+ node_a_input_qparams = get_node_input_qparams(
305
+ node_a, gm_a, node_type_to_io_type_map
306
+ )
307
+ if node_a_input_qparams is not None:
308
+ dtype_cast_op = torch.quantize_per_tensor # type: ignore[assignment]
309
+ dtype_cast_scale, dtype_cast_zero_point = node_a_input_qparams
310
+ elif (
311
+ node_input_type_a == NodeInputOrOutputType.FP16
312
+ and node_input_type_c == NodeInputOrOutputType.FP32
313
+ ):
314
+ dtype_cast_method = "to"
315
+ dtype_cast_method_dtype = torch.float16
316
+ else:
317
+ raise AssertionError(
318
+ f"dtype cast from {node_input_type_c} {node_c.format_node()} to "
319
+ + f"{node_input_type_a} {node_a.format_node()} needs to be implemented"
320
+ )
321
+
322
+ if isinstance(prev_node_c, Node):
323
+ new_dtype_cast_name = get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
324
+ if dtype_cast_op:
325
+ if dtype_cast_scale is not None and dtype_cast_zero_point is not None:
326
+ return _insert_quantize_per_tensor_node(
327
+ prev_node_c,
328
+ node_a,
329
+ gm_b,
330
+ graph_c,
331
+ dtype_cast_scale,
332
+ dtype_cast_zero_point,
333
+ new_dtype_cast_name,
334
+ )
335
+ else:
336
+ return graph_c.create_node(
337
+ "call_function",
338
+ dtype_cast_op,
339
+ (prev_node_c,),
340
+ {},
341
+ new_dtype_cast_name,
342
+ )
343
+ elif dtype_cast_method:
344
+ return graph_c.create_node(
345
+ "call_method",
346
+ dtype_cast_method,
347
+ (prev_node_c, dtype_cast_method_dtype),
348
+ {},
349
+ new_dtype_cast_name,
350
+ )
351
+ else:
352
+ if not dtype_cast_mod_cls:
353
+ raise AssertionError("Expected dtype_cast_mod_cls to be not None")
354
+ dtype_cast_mod = dtype_cast_mod_cls()
355
+ setattr(gm_b, new_dtype_cast_name, dtype_cast_mod)
356
+ return graph_c.create_node(
357
+ "call_module",
358
+ new_dtype_cast_name,
359
+ (prev_node_c,),
360
+ {},
361
+ new_dtype_cast_name,
362
+ )
363
+ elif isinstance(prev_node_c, list):
364
+ results = []
365
+ for prev_node_c_inner in prev_node_c:
366
+ new_dtype_cast_name = get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
367
+ if dtype_cast_op:
368
+ # TODO(future PR): add handling for quantize_per_tensor
369
+ new_dtype_cast_node = graph_c.create_node(
370
+ "call_function",
371
+ dtype_cast_op,
372
+ (prev_node_c_inner,),
373
+ {},
374
+ new_dtype_cast_name,
375
+ )
376
+ results.append(new_dtype_cast_node)
377
+ else:
378
+ if not dtype_cast_mod_cls:
379
+ raise AssertionError("Expected dtype_cast_mod_cls to be not None")
380
+ dtype_cast_mod = dtype_cast_mod_cls()
381
+ setattr(gm_b, new_dtype_cast_name, dtype_cast_mod)
382
+ new_dtype_cast_node = graph_c.create_node(
383
+ "call_module",
384
+ new_dtype_cast_name,
385
+ (prev_node_c_inner,),
386
+ {},
387
+ new_dtype_cast_name,
388
+ )
389
+ results.append(new_dtype_cast_node)
390
+ return results
391
+ else:
392
+ raise AssertionError(f"type f{type(prev_node_c)} is not handled")
393
+
394
+
395
+ # TODO(future PR): look into using copy_node API instead
396
+ def _copy_node_from_a_to_c(
397
+ node_a: Node,
398
+ gm_a: GraphModule,
399
+ gm_b: GraphModule,
400
+ graph_c: Graph,
401
+ ) -> Node:
402
+ """
403
+ Simple copy of node_a to graph_c.
404
+ """
405
+ if node_a.op == "get_attr":
406
+ node_a_copy_name = get_new_attr_name_with_prefix(node_a.name + "_shadow_copy_")(
407
+ gm_b
408
+ )
409
+ node_a_obj = getattr_from_fqn(gm_a, node_a.target) # type: ignore[arg-type]
410
+ if torch.is_tensor(node_a_obj):
411
+ node_a_obj = node_a_obj.detach()
412
+ setattr(gm_b, node_a_copy_name, node_a_obj)
413
+ node_a_copy = graph_c.create_node(
414
+ node_a.op, node_a_copy_name, (), {}, node_a_copy_name
415
+ )
416
+ return node_a_copy
417
+ elif node_a.op == "call_method":
418
+ if node_a.target not in ("dequantize", "to"):
419
+ raise AssertionError(f"target {node_a.target} is not implemented")
420
+ if node_a.target == "dequantize":
421
+ arg_copy = _copy_node_from_a_to_c(
422
+ get_normalized_nth_input(node_a, gm_a, 0), gm_a, gm_b, graph_c
423
+ ) # type: ignore[arg-type]
424
+ node_a_copy_name = get_new_attr_name_with_prefix(
425
+ node_a.name + "_shadow_copy_"
426
+ )(gm_b)
427
+ node_a_copy = graph_c.create_node(
428
+ node_a.op, node_a.target, (arg_copy,), {}, node_a_copy_name
429
+ )
430
+ return node_a_copy
431
+ else: # to
432
+ arg_copy = _copy_node_from_a_to_c(
433
+ get_normalized_nth_input(node_a, gm_a, 0), gm_a, gm_b, graph_c
434
+ ) # type: ignore[arg-type]
435
+ node_a_copy_name = get_new_attr_name_with_prefix(
436
+ node_a.name + "_shadow_copy_"
437
+ )(gm_b)
438
+ node_a_copy = graph_c.create_node(
439
+ node_a.op,
440
+ node_a.target,
441
+ (arg_copy, get_normalized_nth_input(node_a, gm_a, 1)),
442
+ {},
443
+ node_a_copy_name,
444
+ )
445
+ return node_a_copy
446
+
447
+ else:
448
+ raise AssertionError(
449
+ f"handling of node {node_a.format_node()} with op {node_a.op} is not implemented"
450
+ )
451
+
452
+
453
+ def _can_insert_copy_of_subgraph_a(
454
+ subgraph_a: NSSubgraph,
455
+ gm_a: GraphModule,
456
+ num_non_param_args_node_a: int,
457
+ ) -> bool:
458
+ """
459
+ This function returns `False` if the input subgraph cannot be copied by
460
+ `_insert_copy_of_subgraph_a_after_input_node_c`. This usually means
461
+ that there is a corner case logic for which copy is not yet implemented.
462
+ """
463
+ # populate the list of nodes we need to check
464
+ nodes = []
465
+ cur_node = subgraph_a.end_node
466
+ while cur_node != subgraph_a.start_node:
467
+ nodes.append(cur_node)
468
+ cur_node = get_normalized_nth_input(cur_node, gm_a, 0) # type: ignore[assignment]
469
+ nodes.append(cur_node)
470
+ nodes.reverse()
471
+
472
+ def _can_insert(node_a_arg, gm_a):
473
+ if isinstance(node_a_arg, Node):
474
+ arg_a = return_first_non_observer_node(node_a_arg, gm_a)
475
+ if arg_a.op == "call_method":
476
+ return arg_a.target in ("dequantize", "to")
477
+ elif arg_a.op == "get_attr":
478
+ return True
479
+ else:
480
+ return False
481
+ elif isinstance(node_a_arg, (list, tuple)):
482
+ for el in node_a_arg:
483
+ if not isinstance(el, Node):
484
+ return False
485
+ return True
486
+
487
+ # For each node, check if we handle the copy behavior. This follows the
488
+ # logic in `_insert_copy_of_subgraph_a_after_input_node_c`.
489
+ for node_a in nodes:
490
+ local_num_non_param_args_node_a = (
491
+ num_non_param_args_node_a if node_a is nodes[0] else 1
492
+ )
493
+
494
+ norm_args_kwargs = node_a.normalized_arguments(
495
+ gm_a, normalize_to_only_use_kwargs=True
496
+ )
497
+ if norm_args_kwargs is not None:
498
+ norm_args, norm_kwargs = norm_args_kwargs
499
+ else:
500
+ norm_args, norm_kwargs = node_a.args, node_a.kwargs
501
+
502
+ cur_idx = 0
503
+
504
+ while cur_idx < len(norm_args):
505
+ if cur_idx == 0:
506
+ pass
507
+ elif cur_idx == 1 and local_num_non_param_args_node_a == 2:
508
+ pass
509
+ else:
510
+ if not _can_insert(norm_args[cur_idx], gm_a):
511
+ return False
512
+ cur_idx += 1
513
+
514
+ for kwarg_val in norm_kwargs.values():
515
+ # stitch the inputs from base graph
516
+ if cur_idx == 0:
517
+ pass
518
+ elif cur_idx == 1 and local_num_non_param_args_node_a == 2:
519
+ pass
520
+ else:
521
+ if not _can_insert(kwarg_val, gm_a):
522
+ return False
523
+ cur_idx += 1
524
+
525
+ return True
526
+
527
+
528
+ def _insert_copy_of_subgraph_a_after_input_node_c(
529
+ input_node_c: Node | list[Node],
530
+ input_node_c_2: Node | list[Node] | None,
531
+ subgraph_a: NSSubgraph,
532
+ gm_a: GraphModule,
533
+ gm_b: GraphModule,
534
+ node_name_prefix: str,
535
+ ) -> Node:
536
+ """
537
+ TODO(before land): real docblock
538
+ """
539
+ if not isinstance(input_node_c, (Node, list)):
540
+ raise AssertionError(f"Expected Node or list, got {type(input_node_c)}")
541
+
542
+ # create a sequential list of the subgraphs' nodes from start to end,
543
+ # because we need to add the nodes to graph C in non-reverse order
544
+ nodes_of_a = [subgraph_a.end_node]
545
+ cur_node = subgraph_a.end_node
546
+ while cur_node != subgraph_a.start_node:
547
+ cur_node = get_normalized_nth_input(cur_node, gm_a, 0) # type: ignore[assignment]
548
+ nodes_of_a.insert(0, cur_node)
549
+
550
+ # go through nodes of a in order, and insert them into the graph of c
551
+ # sequentially
552
+ cur_node_a = nodes_of_a[0]
553
+ cur_node_c = _insert_copy_of_node_a_after_input_node_c(
554
+ input_node_c, input_node_c_2, cur_node_a, gm_a, gm_b, node_name_prefix
555
+ )
556
+ for cur_idx_a in range(1, len(nodes_of_a)):
557
+ cur_node_a = nodes_of_a[cur_idx_a]
558
+ prev_node_c = cur_node_c # previous added node is the input to next node
559
+ cur_node_c = _insert_copy_of_node_a_after_input_node_c(
560
+ prev_node_c,
561
+ # TODO(future PR): enable multiple inputs for nodes which are not at start of subgraph
562
+ None,
563
+ cur_node_a,
564
+ gm_a,
565
+ gm_b,
566
+ node_name_prefix,
567
+ )
568
+ # return the last inserted node
569
+ return cur_node_c
570
+
571
+
572
+ def _insert_copy_of_node_a_after_input_node_c(
573
+ input_node_c: Node | list[Node],
574
+ input_node_c_2: Node | list[Node] | None,
575
+ node_a: Node,
576
+ gm_a: GraphModule,
577
+ gm_b: GraphModule,
578
+ node_name_prefix: str,
579
+ ) -> Node:
580
+ """
581
+ Assume that node_a from graph_a has
582
+ args (input, (input2)?, arg1, ...), and
583
+ kwargs {kw0: kwarg0, ...}
584
+
585
+ Note: input2 is optional. If it equals to None, we assume that the op
586
+ has a single non-param input. If it is specified, we assume that the op
587
+ has two non-param inputs.
588
+
589
+ Copies the underlying values of arg1..argn and kwarg0..kwargn into gm_b,
590
+ and creates the corresponding nodes in graph_c. Note: observers are ignored,
591
+ so if an arg is an observer we navigate up until we find a non-observer parent.
592
+
593
+ If node_a is a call_module, points the module pointed to by node_a to gm_b.
594
+
595
+ Creates the copy of node_a in graph_c, with input as the first arg,
596
+ and all other args and kwargs pointing to the copies of the objects
597
+ in gm_b created above.
598
+
599
+ An example in pictures:
600
+
601
+ graph A:
602
+ ========
603
+
604
+ input -------------> node_a
605
+ / / /
606
+ (input_2)?----------/ / /
607
+ / /
608
+ weight -> weight_obs /
609
+ /
610
+ bias ----------------
611
+
612
+ graph C (derived from B):
613
+ =========================
614
+
615
+ input_node_c --> node_a_copy
616
+ / / /
617
+ (input_node_c_2)? / /
618
+ / /
619
+ weight_copy ----/ /
620
+ /
621
+ bias_copy ------/
622
+ """
623
+ if isinstance(input_node_c, Node):
624
+ graph_c = input_node_c.graph
625
+ else:
626
+ if not isinstance(input_node_c, list):
627
+ raise AssertionError(f"Expected list, got {type(input_node_c)}")
628
+ graph_c = input_node_c[0].graph
629
+
630
+ norm_args_kwargs = node_a.normalized_arguments(
631
+ gm_a, normalize_to_only_use_kwargs=True
632
+ )
633
+ if norm_args_kwargs is not None:
634
+ norm_args, norm_kwargs = norm_args_kwargs
635
+ else:
636
+ norm_args, norm_kwargs = node_a.args, node_a.kwargs
637
+
638
+ new_args = []
639
+ new_kwargs = {}
640
+
641
+ def _copy_arg(arg):
642
+ # copy the other inputs from the other graph
643
+ if isinstance(arg, Node):
644
+ arg = return_first_non_observer_node(arg, gm_a)
645
+ arg = _copy_node_from_a_to_c(arg, gm_a, gm_b, graph_c)
646
+ return arg
647
+ elif isinstance(arg, (int, float, torch.dtype)):
648
+ return arg
649
+ elif isinstance(kwarg_val, (list, tuple)):
650
+ for el in kwarg_val:
651
+ if isinstance(el, Node):
652
+ raise AssertionError(
653
+ "handling of Node inside list is not implemented"
654
+ )
655
+ return arg
656
+ else:
657
+ raise AssertionError(
658
+ f"handling for kwarg of type {type(kwarg_val)} is not implemented"
659
+ )
660
+
661
+ cur_idx = 0
662
+
663
+ while cur_idx < len(norm_args):
664
+ if cur_idx == 0:
665
+ new_arg = input_node_c
666
+ elif cur_idx == 1 and input_node_c_2 is not None:
667
+ new_arg = input_node_c_2
668
+ else:
669
+ new_arg = _copy_arg(norm_args[cur_idx])
670
+ new_args.append(new_arg)
671
+ cur_idx += 1
672
+
673
+ for kwarg_name, kwarg_val in norm_kwargs.items():
674
+ # stitch the inputs from base graph
675
+ if cur_idx == 0:
676
+ new_kwargs[kwarg_name] = input_node_c
677
+ elif cur_idx == 1 and input_node_c_2 is not None:
678
+ new_kwargs[kwarg_name] = input_node_c_2
679
+ else:
680
+ new_kwargs[kwarg_name] = _copy_arg(kwarg_val)
681
+ cur_idx += 1
682
+
683
+ new_args = tuple(new_args) # type: ignore[assignment]
684
+
685
+ node_a_shadows_c_name = get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
686
+
687
+ if node_a.op == "call_module":
688
+ # if target is a module, we point to the module from gm_b
689
+ new_mod_copy_name = get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
690
+ # fetch the corresponding module from gm_a
691
+ if not isinstance(node_a.target, str):
692
+ raise AssertionError(f"Expected str, got {type(node_a.target)}")
693
+ mod_a = getattr_from_fqn(gm_a, node_a.target)
694
+ setattr(gm_b, new_mod_copy_name, mod_a)
695
+ node_a_shadows_c = graph_c.create_node(
696
+ node_a.op,
697
+ new_mod_copy_name,
698
+ new_args, # type: ignore[arg-type]
699
+ new_kwargs, # type: ignore[arg-type]
700
+ node_a_shadows_c_name,
701
+ )
702
+ return node_a_shadows_c
703
+ else:
704
+ if node_a.op not in ("call_function", "call_method"):
705
+ raise AssertionError(f"Unexpected op: {node_a.op}")
706
+ node_a_shadows_c = graph_c.create_node(
707
+ node_a.op,
708
+ node_a.target,
709
+ new_args, # type: ignore[arg-type]
710
+ new_kwargs, # type: ignore[arg-type]
711
+ node_a_shadows_c_name,
712
+ )
713
+ return node_a_shadows_c
714
+
715
+
716
+ def create_a_shadows_b(
717
+ name_a: str,
718
+ gm_a: GraphModule,
719
+ name_b: str,
720
+ gm_b: GraphModule,
721
+ matched_subgraph_pairs: dict[str, tuple[NSSubgraph, NSSubgraph]],
722
+ logger_cls: Callable,
723
+ should_log_inputs: bool,
724
+ node_type_to_io_type_map: dict[str, set[NSNodeTargetType]] | None = None,
725
+ ) -> GraphModule:
726
+ """
727
+ Creates a new GraphModule consisting of the graph of C, with the meaningful
728
+ nodes of A shadowing the corresponding nodes of B. For example,
729
+
730
+ Graph A:
731
+ a0 -> op0_fp32 -> a1 -> op1_fp32 -> a2
732
+
733
+ Graph B:
734
+ b0 -> op0_int8 -> b1 -> op1_int8 -> b2
735
+
736
+ matched_node_pairs: {'op0': (op0_fp32, op0_int8), 'op1': (op1_fp32, op1_int8)}
737
+
738
+ Graph C (A shadows B):
739
+
740
+ / dequant0 -> op0_fp32 -> logger_a_0 / dequant_1 -> op1_fp32 -> logger_a_1
741
+ / /
742
+ b0 -------------> op0_int8 -> logger_b_0 --------------> op1_int8 -> logger_b_1
743
+
744
+ In a nutshell, this function does the following for each node pair:
745
+ * copies the necessary attributes and modules from gm_a to gm_b,
746
+ keeping names unique
747
+ * adds a dtype cast op (dequant, quant, etc)
748
+ * adds a copy of node_a in gm_b's graph
749
+ * adds loggers to the outputs of node_a and node_b
750
+ """
751
+
752
+ if node_type_to_io_type_map is None:
753
+ node_type_to_io_type_map = get_node_type_to_io_type_map()
754
+
755
+ # graph_c is the graph created from copying the nodes of graph_b and inserting
756
+ # the shadows with the nodes copied from graph_a
757
+ graph_c = Graph()
758
+ env_c: dict[str, Any] = {}
759
+
760
+ def load_arg(a):
761
+ return map_arg(a, lambda node: env_c[node.name])
762
+
763
+ start_node_b_to_matched_subgraph_a_and_name = {}
764
+ end_node_b_to_matched_subgraph_a_and_name = {}
765
+ for match_name, match in matched_subgraph_pairs.items():
766
+ subgraph_a, subgraph_b = match
767
+ ref_node_type_a = get_target_type_str(subgraph_a.base_op_node, gm_a)
768
+ ref_node_type_b = get_target_type_str(subgraph_b.base_op_node, gm_b)
769
+ start_node_b_to_matched_subgraph_a_and_name[subgraph_b.start_node] = (
770
+ subgraph_a,
771
+ match_name,
772
+ ref_node_type_a,
773
+ ref_node_type_b,
774
+ )
775
+ end_node_b_to_matched_subgraph_a_and_name[subgraph_b.end_node] = (
776
+ subgraph_a,
777
+ match_name,
778
+ ref_node_type_a,
779
+ ref_node_type_b,
780
+ )
781
+
782
+ for node_b in gm_b.graph.nodes:
783
+ if node_b.op == "output":
784
+ graph_c.output(map_arg(node_b.args[0], load_arg))
785
+ continue
786
+
787
+ # calculate the flags to determine what to do with this node
788
+ node_b_is_start_node = node_b in start_node_b_to_matched_subgraph_a_and_name
789
+ node_b_is_end_node = node_b in end_node_b_to_matched_subgraph_a_and_name
790
+
791
+ if node_b_is_start_node or node_b_is_end_node:
792
+ if node_b_is_start_node:
793
+ (
794
+ subgraph_a,
795
+ ref_name,
796
+ ref_node_type_a,
797
+ ref_node_type_b,
798
+ ) = start_node_b_to_matched_subgraph_a_and_name[node_b]
799
+ else:
800
+ if not node_b_is_end_node:
801
+ raise AssertionError("Expected node_b_is_end_node to be not false")
802
+ (
803
+ subgraph_a,
804
+ ref_name,
805
+ ref_node_type_a,
806
+ ref_node_type_b,
807
+ ) = end_node_b_to_matched_subgraph_a_and_name[node_b]
808
+
809
+ all_op_types_support_shadowing = op_type_supports_shadowing(
810
+ subgraph_a.start_node
811
+ ) and op_type_supports_shadowing(node_b)
812
+ if not all_op_types_support_shadowing:
813
+ print(
814
+ f"skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}"
815
+ + f", start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}"
816
+ + ", unsupported"
817
+ )
818
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
819
+ continue
820
+
821
+ # For both start_node and end_node verify that we know how to do
822
+ # the dtype cast. If we do not, skip.
823
+ (
824
+ node_input_type_a,
825
+ node_output_type_a,
826
+ ) = get_node_first_input_and_output_type(
827
+ subgraph_a.start_node, gm_a, logger_cls, node_type_to_io_type_map
828
+ )
829
+ (
830
+ node_input_type_b,
831
+ node_output_type_b,
832
+ ) = get_node_first_input_and_output_type(
833
+ node_b, gm_b, logger_cls, node_type_to_io_type_map
834
+ )
835
+ node_io_types_known_a_and_b = (
836
+ node_input_type_a != NodeInputOrOutputType.UNKNOWN
837
+ and node_output_type_a != NodeInputOrOutputType.UNKNOWN
838
+ and node_input_type_b != NodeInputOrOutputType.UNKNOWN
839
+ and node_output_type_b != NodeInputOrOutputType.UNKNOWN
840
+ )
841
+ if not node_io_types_known_a_and_b:
842
+ print(
843
+ f"skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}"
844
+ + f", start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}"
845
+ + ", unknown dtype cast"
846
+ )
847
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
848
+ continue
849
+
850
+ # If we are shadowing from fp32 to int8, we need to insert
851
+ # quantize_per_tensor call with qparams from the previous node.
852
+ # Only do this if we are able to infer these qparams from the graph.
853
+ if (
854
+ node_input_type_a == NodeInputOrOutputType.INT8
855
+ and node_input_type_b == NodeInputOrOutputType.FP32
856
+ ):
857
+ node_a_input_qparams = get_node_input_qparams(
858
+ subgraph_a.start_node, gm_a, node_type_to_io_type_map
859
+ )
860
+ if not node_a_input_qparams:
861
+ print(
862
+ f"skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}"
863
+ + f", start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}"
864
+ + ", unknown input qparams"
865
+ )
866
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
867
+ continue
868
+
869
+ num_non_param_args_node_a = get_number_of_non_param_args(
870
+ subgraph_a.start_node, gm_a
871
+ )
872
+ if not _can_insert_copy_of_subgraph_a(
873
+ subgraph_a, gm_a, num_non_param_args_node_a
874
+ ):
875
+ print(
876
+ f"skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}"
877
+ + f", start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}"
878
+ + ", unhandled logic in subgraph copy"
879
+ )
880
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
881
+ continue
882
+
883
+ fqn_base_a = _maybe_get_fqn(subgraph_a.base_op_node, gm_a)
884
+ fqn_base_b = _maybe_get_fqn(subgraph_b.base_op_node, gm_b) # type: ignore[possibly-undefined]
885
+
886
+ if node_b_is_start_node:
887
+ # if necessary, log the input of node_c
888
+ if should_log_inputs:
889
+ prev_node_b = get_normalized_nth_input(node_b, gm_b, 0)
890
+ if isinstance(prev_node_b, Node):
891
+ prev_node_c = env_c[prev_node_b.name]
892
+ env_c[prev_node_c.name] = _insert_logger_after_node(
893
+ prev_node_c,
894
+ gm_b,
895
+ logger_cls,
896
+ "_ns_logger_b_inp_",
897
+ node_b.name,
898
+ name_b,
899
+ ref_name,
900
+ ref_node_type_b,
901
+ NSSingleResultValuesType.NODE_INPUT.value,
902
+ index_within_arg=0,
903
+ index_of_arg=0,
904
+ fqn=fqn_base_b,
905
+ )
906
+ elif isinstance(prev_node_b, list):
907
+ # first, save the prev_node instances, because they
908
+ # will be overwritten in the env after the first logger
909
+ # is added
910
+ prev_node_c_list = [env_c[arg.name] for arg in prev_node_b]
911
+
912
+ for arg_idx, prev_node_c in enumerate(prev_node_c_list):
913
+ env_c[prev_node_c.name] = _insert_logger_after_node(
914
+ prev_node_c,
915
+ gm_b,
916
+ logger_cls,
917
+ "_ns_logger_b_inp_",
918
+ node_b.name,
919
+ name_b,
920
+ ref_name,
921
+ ref_node_type_b,
922
+ NSSingleResultValuesType.NODE_INPUT.value,
923
+ index_within_arg=arg_idx,
924
+ index_of_arg=0,
925
+ fqn=fqn_base_b,
926
+ )
927
+ else:
928
+ # logging of inputs which are not lists is not supported yet
929
+ raise AssertionError(
930
+ f"type {type(prev_node_b)} is not handled yet"
931
+ )
932
+ # subgraph so far:
933
+ #
934
+ # (prev_node_c)+ -> (logger_c_input)?
935
+
936
+ # Note: this if statement is always True, spelling it out to clarify code
937
+ # intent.
938
+ if node_b_is_start_node or node_b_is_end_node:
939
+ # ensure env_c is populated with base node
940
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
941
+ node_c = env_c[node_b.name]
942
+
943
+ # after this point,
944
+ #
945
+ # node_a is the original node from graph_a, with parent module gm_a
946
+ # node_b is the original node from graph_b, with parent module gm_b
947
+ # node_c is the copy of node_b in graph_c
948
+ #
949
+ # subgraph so far:
950
+ #
951
+ # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
952
+
953
+ if node_b_is_start_node:
954
+ # cast dtype from the dtype of node_c's input to the dtype of
955
+ # node_a's input (dequant, etc)
956
+ # prev_node_c = node_c.args[0]
957
+ prev_node_c = get_normalized_nth_input(node_c, gm_b, 0) # type: ignore[possibly-undefined]
958
+ if should_log_inputs:
959
+ # skip the input logger when inserting a dtype cast
960
+ if isinstance(prev_node_c, Node):
961
+ # pyrefly: ignore [unbound-name]
962
+ prev_node_c = get_normalized_nth_input(node_c, gm_b, 0)
963
+ elif isinstance(prev_node_c, list):
964
+ prev_node_c = [
965
+ get_normalized_nth_input(arg, gm_b, 0)
966
+ for arg in prev_node_c
967
+ ]
968
+ dtype_cast_node = _insert_dtype_cast_after_node(
969
+ subgraph_a.start_node,
970
+ # pyrefly: ignore [unbound-name]
971
+ node_c,
972
+ prev_node_c,
973
+ gm_a,
974
+ gm_b,
975
+ graph_c,
976
+ node_b.name + "_dtype_cast_",
977
+ logger_cls,
978
+ node_type_to_io_type_map,
979
+ )
980
+ # note: not inserting to env_c because all nodes which use the dtype
981
+ # casts are copied from graph_a
982
+ #
983
+ # subgraph so far:
984
+ #
985
+ # (dtype_cast_node)+
986
+ # /
987
+ # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
988
+
989
+ # if input logging is enabled, log the input to the subgraph
990
+ if should_log_inputs:
991
+ # TODO: explain this
992
+ ref_node_name = ""
993
+ if isinstance(dtype_cast_node, Node):
994
+ dtype_cast_node = _insert_logger_after_node(
995
+ dtype_cast_node,
996
+ gm_b,
997
+ logger_cls,
998
+ "_ns_logger_a_inp_",
999
+ ref_node_name,
1000
+ name_a,
1001
+ ref_name,
1002
+ ref_node_type_a,
1003
+ NSSingleResultValuesType.NODE_INPUT.value,
1004
+ index_within_arg=0,
1005
+ index_of_arg=0,
1006
+ fqn=fqn_base_a,
1007
+ )
1008
+ input_logger: Node | list[Node] = dtype_cast_node
1009
+ else:
1010
+ if not isinstance(dtype_cast_node, list):
1011
+ raise AssertionError(
1012
+ f"Expected list, got {type(dtype_cast_node)}"
1013
+ )
1014
+ new_loggers = []
1015
+ for dtype_cast_idx, dtype_cast_node_inner in enumerate(
1016
+ dtype_cast_node
1017
+ ):
1018
+ dtype_cast_logger = _insert_logger_after_node(
1019
+ dtype_cast_node_inner,
1020
+ gm_b,
1021
+ logger_cls,
1022
+ "_ns_logger_a_inp_",
1023
+ ref_node_name,
1024
+ name_a,
1025
+ ref_name,
1026
+ ref_node_type_a,
1027
+ NSSingleResultValuesType.NODE_INPUT.value,
1028
+ index_within_arg=dtype_cast_idx,
1029
+ index_of_arg=0,
1030
+ fqn=fqn_base_a,
1031
+ )
1032
+ new_loggers.append(dtype_cast_logger)
1033
+ dtype_cast_node = new_loggers
1034
+ input_logger = dtype_cast_node
1035
+ # subgraph so far:
1036
+ #
1037
+ # (dtype_cast_node)+ -> (logger_a_input)?
1038
+ # /
1039
+ # prev_node_c -> (logger_c_input)? -> node_start_c
1040
+
1041
+ # hook up the new mod_a copy to be in the graph, receiving the
1042
+ # same inputs as mod_b does, with dtype cast to match a
1043
+ # Some ops, such as LSTMs, have two non-param inputs. If we have
1044
+ # such an op, pass the second param as well. Note: dtype casting
1045
+ # for the second param is not implemented yet, it can be added
1046
+ # later if there is a use case.
1047
+ node_c_second_non_param_arg = None
1048
+ num_non_param_args_node_a = get_number_of_non_param_args(
1049
+ subgraph_a.start_node, gm_a
1050
+ )
1051
+ if num_non_param_args_node_a == 2:
1052
+ # node_c_second_non_param_arg = node_c.args[1]
1053
+ node_c_second_non_param_arg = get_normalized_nth_input(
1054
+ # pyrefly: ignore [unbound-name]
1055
+ node_c,
1056
+ gm_b,
1057
+ 1,
1058
+ )
1059
+ node_a_shadows_c = _insert_copy_of_subgraph_a_after_input_node_c(
1060
+ dtype_cast_node,
1061
+ node_c_second_non_param_arg,
1062
+ subgraph_a,
1063
+ gm_a,
1064
+ gm_b,
1065
+ # pyrefly: ignore [unbound-name]
1066
+ node_c.name + "_shadow_copy_",
1067
+ )
1068
+ env_c[node_a_shadows_c.name] = node_a_shadows_c
1069
+ # subgraph so far:
1070
+ #
1071
+ # dtype_cast_node -> (logger_a_input)? -> subgraph_a_copy(args/kwargs not shown)
1072
+ # /
1073
+ # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
1074
+
1075
+ if should_log_inputs:
1076
+ # When we created the input logger, we left the ref_node_name
1077
+ # as an empty string, because the subgraph copy did not exist
1078
+ # yet. Now that the subgraph copy exists, we modify this name
1079
+ # to its true value.
1080
+ # Note: the alternative to this is to create the input logger
1081
+ # after creating the subgraph, which is slightly more
1082
+ # complicated. This is the lesser of two evils.
1083
+ # input_logger = env_c[dtype_cast_node.name]
1084
+ # Find the first node in the subgraph
1085
+ cur_node = node_a_shadows_c
1086
+ while get_normalized_nth_input(cur_node, gm_b, 0) != input_logger: # type: ignore[possibly-undefined]
1087
+ cur_node = get_normalized_nth_input(cur_node, gm_b, 0) # type: ignore[assignment]
1088
+ # pyrefly: ignore [unbound-name]
1089
+ if isinstance(input_logger, Node):
1090
+ # pyrefly: ignore [unbound-name]
1091
+ input_logger_mod = getattr(gm_b, input_logger.name)
1092
+ input_logger_mod.ref_node_name = cur_node.name
1093
+ else:
1094
+ # pyrefly: ignore [unbound-name]
1095
+ if not isinstance(input_logger, list):
1096
+ raise AssertionError(
1097
+ # pyrefly: ignore [unbound-name]
1098
+ f"Expected list, got {type(input_logger)}"
1099
+ )
1100
+ # pyrefly: ignore [unbound-name]
1101
+ for input_logger_inner in input_logger:
1102
+ input_logger_mod = getattr(gm_b, input_logger_inner.name)
1103
+ input_logger_mod.ref_node_name = cur_node.name
1104
+
1105
+ # hook up a logger to the mod_a copy
1106
+ env_c[node_a_shadows_c.name] = _insert_logger_after_node(
1107
+ env_c[node_a_shadows_c.name],
1108
+ gm_b,
1109
+ logger_cls,
1110
+ "_ns_logger_a_",
1111
+ node_a_shadows_c.name,
1112
+ name_a,
1113
+ ref_name,
1114
+ ref_node_type_a,
1115
+ NSSingleResultValuesType.NODE_OUTPUT.value,
1116
+ index_within_arg=0,
1117
+ index_of_arg=0,
1118
+ fqn=fqn_base_a,
1119
+ )
1120
+ # subgraph so far:
1121
+ #
1122
+ # dtype_cast_node -> (logger_a_input)? -> subgraph_a_copy -> logger_a
1123
+ # /
1124
+ # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
1125
+
1126
+ if node_b_is_end_node:
1127
+ # hook up a logger to the mod_b copy
1128
+ env_c[node_b.name] = _insert_logger_after_node(
1129
+ env_c[node_b.name],
1130
+ gm_b,
1131
+ logger_cls,
1132
+ "_ns_logger_b_",
1133
+ node_b.name,
1134
+ name_b,
1135
+ ref_name,
1136
+ ref_node_type_b,
1137
+ NSSingleResultValuesType.NODE_OUTPUT.value,
1138
+ index_within_arg=0,
1139
+ index_of_arg=0,
1140
+ fqn=fqn_base_b,
1141
+ )
1142
+ # subgraph so far:
1143
+ #
1144
+ # dtype_cast_node -> (logger_a_input)? -> subgraph_a_copy -> logger_a
1145
+ # /
1146
+ # (prev_node_c+) -> (logger_c_input)? -> node_start_c -> ... -> node_end_c -> logger_c
1147
+ #
1148
+ # Note: node_start_c may be the same node as node_end_c, or they
1149
+ # may have nodes in between.
1150
+
1151
+ else:
1152
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
1153
+
1154
+ gm_c = GraphModule(gm_b, graph_c)
1155
+ return gm_c
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/mappings.py ADDED
@@ -0,0 +1,763 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+ from typing import TYPE_CHECKING
3
+
4
+ import torch
5
+ import torch.ao.nn.intrinsic as nni
6
+ import torch.ao.nn.intrinsic.qat as nniqat
7
+ import torch.ao.nn.intrinsic.quantized as nniq
8
+ import torch.ao.nn.intrinsic.quantized.dynamic as nniqd
9
+ import torch.ao.nn.qat as nnqat
10
+ import torch.ao.nn.qat.dynamic as nnqatd
11
+ import torch.ao.nn.quantized as nnq
12
+ import torch.ao.nn.quantized.dynamic as nnqd
13
+ import torch.ao.quantization.fx._lower_to_native_backend as _lower_to_native_backend
14
+ import torch.ao.quantization.quantization_mappings as quantization_mappings
15
+ import torch.nn as nn
16
+ import torch.nn.functional as F
17
+ from torch.ao.quantization.backend_config import get_native_backend_config
18
+
19
+ from .ns_types import NSNodeTargetType
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from collections.abc import Callable
24
+
25
+
26
+ toq = torch.ops.quantized
27
+
28
+
29
+ def get_base_name_to_sets_of_related_ops() -> dict[str, set[NSNodeTargetType]]:
30
+ # note: this set is modified below by items from backend_config
31
+ sets_of_related_ops: list[set[NSNodeTargetType]] = [
32
+ # conv modules
33
+ {
34
+ nn.Conv1d,
35
+ },
36
+ {
37
+ nn.Conv2d,
38
+ },
39
+ {
40
+ nn.Conv3d,
41
+ },
42
+ # conv functionals
43
+ {
44
+ F.conv1d,
45
+ },
46
+ {
47
+ F.conv2d,
48
+ },
49
+ {
50
+ F.conv3d,
51
+ },
52
+ # linear modules
53
+ {
54
+ nn.Linear,
55
+ },
56
+ # linear functionals
57
+ {
58
+ F.linear,
59
+ },
60
+ # average pool
61
+ {
62
+ nn.AvgPool1d,
63
+ torch.avg_pool1d,
64
+ },
65
+ {
66
+ nn.AvgPool2d,
67
+ torch._C._nn.avg_pool2d,
68
+ },
69
+ {
70
+ nn.AvgPool3d,
71
+ torch._C._nn.avg_pool3d,
72
+ },
73
+ # adaptive average pool
74
+ {
75
+ nn.AdaptiveAvgPool1d,
76
+ F.adaptive_avg_pool1d,
77
+ },
78
+ {
79
+ nn.AdaptiveAvgPool2d,
80
+ F.adaptive_avg_pool2d,
81
+ },
82
+ {
83
+ nn.AdaptiveAvgPool3d,
84
+ F.adaptive_avg_pool3d,
85
+ },
86
+ # LSTM
87
+ {
88
+ nn.LSTM,
89
+ },
90
+ # add
91
+ {
92
+ torch.add,
93
+ operator.add, # x + y
94
+ },
95
+ # cat
96
+ {
97
+ torch.cat,
98
+ },
99
+ # mul
100
+ {
101
+ torch.mul,
102
+ operator.mul,
103
+ },
104
+ # relu
105
+ {
106
+ F.relu,
107
+ nn.ReLU,
108
+ "relu",
109
+ "relu_",
110
+ torch.relu,
111
+ },
112
+ # maxpool
113
+ {
114
+ nn.MaxPool1d,
115
+ F.max_pool1d,
116
+ },
117
+ {
118
+ nn.MaxPool2d,
119
+ F.max_pool2d,
120
+ },
121
+ {
122
+ nn.MaxPool3d,
123
+ F.max_pool3d,
124
+ },
125
+ # sigmoid
126
+ {
127
+ torch.sigmoid,
128
+ "sigmoid",
129
+ "sigmoid_",
130
+ nn.Sigmoid,
131
+ F.sigmoid,
132
+ },
133
+ # BatchNorm
134
+ {
135
+ nn.BatchNorm2d,
136
+ },
137
+ {
138
+ nn.BatchNorm3d,
139
+ },
140
+ # ConvTranspose
141
+ {
142
+ nn.ConvTranspose1d,
143
+ },
144
+ {
145
+ nn.ConvTranspose2d,
146
+ },
147
+ {
148
+ nn.ConvTranspose3d,
149
+ },
150
+ # functional transposed conv
151
+ {
152
+ F.conv_transpose1d,
153
+ },
154
+ {
155
+ F.conv_transpose2d,
156
+ },
157
+ {
158
+ F.conv_transpose3d,
159
+ },
160
+ # ELU
161
+ {
162
+ nn.ELU,
163
+ },
164
+ # Embedding
165
+ {
166
+ nn.Embedding,
167
+ },
168
+ # EmbeddingBag
169
+ {
170
+ nn.EmbeddingBag,
171
+ },
172
+ # GroupNorm
173
+ {
174
+ nn.GroupNorm,
175
+ },
176
+ # Hardswish
177
+ {
178
+ nn.Hardswish,
179
+ },
180
+ # InstanceNorm
181
+ {
182
+ nn.InstanceNorm1d,
183
+ },
184
+ {
185
+ nn.InstanceNorm2d,
186
+ },
187
+ {
188
+ nn.InstanceNorm3d,
189
+ },
190
+ # LayerNorm
191
+ {
192
+ nn.LayerNorm,
193
+ },
194
+ # LeakyReLU
195
+ {
196
+ nn.LeakyReLU,
197
+ },
198
+ # ReLU6
199
+ {
200
+ nn.ReLU6,
201
+ F.relu6,
202
+ },
203
+ # F.elu
204
+ {
205
+ F.elu,
206
+ },
207
+ # F.hardswish
208
+ {
209
+ F.hardswish,
210
+ },
211
+ # F.group_norm
212
+ {
213
+ F.group_norm,
214
+ },
215
+ # F.instance_norm
216
+ {
217
+ F.instance_norm,
218
+ },
219
+ # F.layer_norm
220
+ {
221
+ F.layer_norm,
222
+ },
223
+ # F.leaky_relu
224
+ {
225
+ F.leaky_relu,
226
+ },
227
+ # F.silu
228
+ {
229
+ nn.SiLU,
230
+ F.silu,
231
+ },
232
+ # F.mish
233
+ {
234
+ nn.Mish,
235
+ F.mish,
236
+ },
237
+ # F.tanh
238
+ {
239
+ nn.Tanh,
240
+ F.tanh,
241
+ torch.tanh,
242
+ "tanh_",
243
+ "tanh",
244
+ },
245
+ # F.hardsigmoid
246
+ {
247
+ "hardsigmoid_",
248
+ "hardsigmoid",
249
+ F.hardsigmoid,
250
+ nn.Hardsigmoid,
251
+ },
252
+ # F.hardtanh
253
+ {
254
+ nn.Hardtanh,
255
+ F.hardtanh,
256
+ F.hardtanh_,
257
+ },
258
+ # floordiv
259
+ {
260
+ operator.floordiv,
261
+ },
262
+ # unsqueeze
263
+ {
264
+ torch.unsqueeze,
265
+ },
266
+ # stack
267
+ {
268
+ torch.stack,
269
+ },
270
+ # squeeze
271
+ {
272
+ torch.squeeze,
273
+ },
274
+ # sort
275
+ {
276
+ torch.sort,
277
+ },
278
+ # repeat_interleave
279
+ {
280
+ torch.repeat_interleave,
281
+ },
282
+ # min
283
+ {
284
+ torch.min,
285
+ },
286
+ # mean
287
+ {
288
+ torch.mean,
289
+ },
290
+ # max
291
+ {
292
+ torch.max,
293
+ },
294
+ # transpose
295
+ {
296
+ torch.transpose,
297
+ },
298
+ # flatten
299
+ {
300
+ torch.flatten,
301
+ },
302
+ # clamp
303
+ {
304
+ torch.clamp,
305
+ },
306
+ # chunk
307
+ {
308
+ torch.chunk,
309
+ },
310
+ # interpolate
311
+ {
312
+ torch.nn.functional.interpolate,
313
+ },
314
+ # dropout
315
+ {
316
+ nn.Dropout,
317
+ },
318
+ # F.dropout
319
+ {
320
+ F.dropout,
321
+ },
322
+ # matmul
323
+ {
324
+ torch.matmul,
325
+ },
326
+ # Softmax
327
+ {
328
+ nn.Softmax,
329
+ },
330
+ # PReLU
331
+ {
332
+ nn.PReLU,
333
+ nnq.PReLU,
334
+ },
335
+ # F.prelu
336
+ {
337
+ F.prelu,
338
+ toq.prelu,
339
+ },
340
+ # pixel shuffle
341
+ {
342
+ nn.PixelShuffle,
343
+ },
344
+ {
345
+ F.pixel_shuffle,
346
+ },
347
+ # pixel unshuffle
348
+ {
349
+ nn.PixelUnshuffle,
350
+ },
351
+ {
352
+ F.pixel_unshuffle,
353
+ },
354
+ # narrow
355
+ {
356
+ torch.narrow,
357
+ },
358
+ ]
359
+
360
+ # for each floating point op, add versions of the op added by
361
+ # backend_config
362
+ backend_config = get_native_backend_config()
363
+
364
+ new_connections: list[tuple[Callable, Callable]] = [
365
+ # technical debt edge case
366
+ (nn.Linear, nn.modules.linear.NonDynamicallyQuantizableLinear),
367
+ ]
368
+
369
+ for pattern, config in backend_config._pattern_complex_format_to_config.items():
370
+ # pattern format: (c, (b, a))
371
+ first_element = pattern
372
+ # look from the end, because pattern is in reverse order
373
+ while isinstance(first_element, (list, tuple)):
374
+ first_element = first_element[-1]
375
+
376
+ if config.fused_module is not None:
377
+ # case 1: pattern fuses a pattern of ops into an op
378
+ # example: nn.Conv1d, nn.ReLU fused into nni.ConvReLU1d
379
+ new_connections.append((first_element, config.fused_module))
380
+
381
+ if config.qat_module is not None:
382
+ # case 2: pattern swaps a module into a QAT module
383
+ # example: nni.ConvReLU1d swapped into nniqat.ConvReLU1d
384
+ new_connections.append((first_element, config.qat_module))
385
+
386
+ if config.reference_quantized_module is not None:
387
+ # case 3: reference version of floating point module, such as
388
+ # nn.Conv2d and nnqr.Conv2d
389
+ new_connections.append((first_element, config.reference_quantized_module))
390
+
391
+ #
392
+ # Add reference module swaps from default lowering path
393
+ #
394
+
395
+ for source_to_target in (
396
+ _lower_to_native_backend.STATIC_LOWER_MODULE_MAP,
397
+ _lower_to_native_backend.DYNAMIC_LOWER_MODULE_MAP,
398
+ _lower_to_native_backend.WEIGHT_ONLY_LOWER_MODULE_MAP,
399
+ _lower_to_native_backend.SPECIAL_PATTERN_LOWER_MODULE_MAP,
400
+ ):
401
+ for source, target in source_to_target.items(): # type: ignore[attr-defined]
402
+ new_connections.append((source, target))
403
+
404
+ for source_to_double_target in (
405
+ _lower_to_native_backend.STATIC_LOWER_FUSED_MODULE_MAP,
406
+ _lower_to_native_backend.STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP,
407
+ _lower_to_native_backend.DYNAMIC_LOWER_FUSED_MODULE_MAP,
408
+ ):
409
+ for source, (target1, target2) in source_to_double_target.items(): # type: ignore[attr-defined]
410
+ new_connections.append((source, target1))
411
+ new_connections.append((source, target2))
412
+
413
+ #
414
+ # Add function swaps from default lowering path
415
+ #
416
+
417
+ for source, ( # type:ignore[assignment]
418
+ target1,
419
+ target2,
420
+ ) in _lower_to_native_backend.STATIC_LOWER_FUNCTIONAL_MAP.items():
421
+ new_connections.append((source, target1))
422
+ # pyrefly: ignore [bad-argument-type]
423
+ new_connections.append((source, target2))
424
+
425
+ for source_to_target in (
426
+ _lower_to_native_backend.QBIN_OP_MAPPING,
427
+ _lower_to_native_backend.QBIN_RELU_OP_MAPPING,
428
+ quantization_mappings.DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS,
429
+ ):
430
+ for source, target in source_to_target.items(): # type:ignore[assignment]
431
+ # pyrefly: ignore [bad-argument-type]
432
+ new_connections.append((source, target))
433
+
434
+ #
435
+ # Add other swaps, ideally in the future this could be removed
436
+ # after the lowering code stops using these.
437
+ #
438
+ for source_to_target in (
439
+ quantization_mappings.DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS,
440
+ ):
441
+ for source, target in source_to_target.items(): # type:ignore[assignment]
442
+ new_connections.append((source, target))
443
+
444
+ # add the new connections from backend_config
445
+ for item1, item2 in new_connections:
446
+ for set_of_related_ops in sets_of_related_ops:
447
+ if item1 in set_of_related_ops or item2 in set_of_related_ops:
448
+ set_of_related_ops.add(item1)
449
+ set_of_related_ops.add(item2)
450
+ break
451
+
452
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]] = {}
453
+
454
+ for counter, set_of_related_ops in enumerate(sets_of_related_ops):
455
+ base_name = str(counter)
456
+ base_name_to_sets_of_related_ops[base_name] = set_of_related_ops
457
+
458
+ return base_name_to_sets_of_related_ops
459
+
460
+
461
+ def get_base_name_for_op(
462
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]],
463
+ op: NSNodeTargetType,
464
+ ) -> str | None:
465
+ for base_name, set_of_related_ops in base_name_to_sets_of_related_ops.items():
466
+ if op in set_of_related_ops:
467
+ return base_name
468
+ return None
469
+
470
+
471
+ def add_op_to_sets_of_related_ops(
472
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]],
473
+ op: NSNodeTargetType,
474
+ related_op: NSNodeTargetType | None,
475
+ ) -> None:
476
+ if related_op is not None:
477
+ for set_of_related_ops in base_name_to_sets_of_related_ops.values():
478
+ if related_op in set_of_related_ops:
479
+ set_of_related_ops.add(op)
480
+ return
481
+ # if we got here, related_op was not found
482
+ raise AssertionError(f"{related_op} was not found")
483
+ else:
484
+ counter = 0
485
+ while str(counter) in base_name_to_sets_of_related_ops:
486
+ counter += 1
487
+ base_name_to_sets_of_related_ops[str(counter)] = {op}
488
+
489
+
490
+ # TODO(future PR): clean this up
491
+ def get_node_type_to_io_type_map() -> dict[str, set[NSNodeTargetType]]:
492
+ FUNS_IO_TYPE_FP32: set[NSNodeTargetType] = {
493
+ F.linear,
494
+ F.conv1d,
495
+ F.conv2d,
496
+ F.conv3d,
497
+ torch.cat,
498
+ F.elu,
499
+ F.hardswish,
500
+ F.instance_norm,
501
+ F.layer_norm,
502
+ F.leaky_relu,
503
+ F.dropout,
504
+ F.silu,
505
+ F.mish,
506
+ operator.add,
507
+ torch.add,
508
+ operator.mul,
509
+ torch.mul,
510
+ torch.sum,
511
+ F.prelu,
512
+ }
513
+
514
+ FUNS_IO_TYPE_FP16: set[NSNodeTargetType] = set()
515
+
516
+ FUNS_IO_TYPE_INT8: set[NSNodeTargetType] = {
517
+ toq.linear,
518
+ toq.linear_relu,
519
+ toq.conv1d,
520
+ toq.conv1d_relu,
521
+ toq.conv2d,
522
+ toq.conv2d_relu,
523
+ toq.conv3d,
524
+ toq.conv3d_relu,
525
+ toq.cat,
526
+ toq.elu,
527
+ toq.hardswish,
528
+ toq.instance_norm,
529
+ toq.layer_norm,
530
+ toq.leaky_relu,
531
+ toq.dropout,
532
+ toq.prelu,
533
+ # TODO(future PR): implement shadowing for binary ops and
534
+ # uncomment below
535
+ # toq.add,
536
+ # toq.mul,
537
+ }
538
+
539
+ FUNS_IO_TYPE_FP32_OR_INT8: set[NSNodeTargetType] = {
540
+ F.relu,
541
+ F.tanh,
542
+ torch.tanh,
543
+ F.sigmoid,
544
+ torch.sigmoid,
545
+ F.hardsigmoid,
546
+ operator.floordiv,
547
+ torch.adaptive_avg_pool1d,
548
+ F.adaptive_avg_pool2d,
549
+ F.adaptive_avg_pool3d,
550
+ F.dropout,
551
+ F.hardtanh,
552
+ F.hardtanh_,
553
+ F.interpolate,
554
+ F.max_pool1d,
555
+ F.max_pool2d,
556
+ F.max_pool3d,
557
+ F.relu6,
558
+ F.pixel_shuffle,
559
+ F.pixel_unshuffle,
560
+ torch.avg_pool1d,
561
+ torch._C._nn.avg_pool2d,
562
+ torch._C._nn.avg_pool3d,
563
+ torch.cat,
564
+ torch.chunk,
565
+ torch.clamp,
566
+ torch.flatten,
567
+ torch.transpose,
568
+ torch.max,
569
+ torch.mean,
570
+ torch.min,
571
+ torch.narrow,
572
+ torch.repeat_interleave,
573
+ torch.sort,
574
+ torch.squeeze,
575
+ torch.stack,
576
+ torch.unsqueeze,
577
+ operator.add,
578
+ }
579
+
580
+ MODS_IO_TYPE_FP32: set[NSNodeTargetType] = {
581
+ nn.Linear,
582
+ nnqat.Linear,
583
+ nnqatd.Linear,
584
+ nnqd.Linear,
585
+ torch.nn.modules.linear.NonDynamicallyQuantizableLinear,
586
+ nn.Conv1d,
587
+ nn.Conv2d,
588
+ nn.Conv3d,
589
+ nnqat.Conv1d,
590
+ nnqat.Conv2d,
591
+ nnqat.Conv3d,
592
+ nnqat.Embedding,
593
+ nnqat.EmbeddingBag,
594
+ nn.LSTM,
595
+ # note: nnqd.Linear is an instance of nnq.Linear, so this
596
+ # check has to happen before the int8 module check
597
+ nnqd.LSTM,
598
+ nn.BatchNorm2d,
599
+ nn.BatchNorm3d,
600
+ nn.Dropout,
601
+ nn.ConvTranspose1d,
602
+ nn.ConvTranspose2d,
603
+ nn.ConvTranspose3d,
604
+ nn.ELU,
605
+ nn.GroupNorm,
606
+ nn.InstanceNorm1d,
607
+ nn.InstanceNorm2d,
608
+ nn.InstanceNorm3d,
609
+ nn.LayerNorm,
610
+ nn.Hardswish,
611
+ nn.LeakyReLU,
612
+ nn.ReLU6,
613
+ nn.SiLU,
614
+ nn.Mish,
615
+ nn.Softmax,
616
+ nn.PReLU,
617
+ nni.BNReLU2d,
618
+ nni.BNReLU3d,
619
+ nni.ConvReLU1d,
620
+ nni.ConvReLU2d,
621
+ nni.ConvReLU3d,
622
+ nni.LinearReLU,
623
+ nni.LinearBn1d,
624
+ nni.ConvBn1d,
625
+ nni.ConvBn2d,
626
+ nni.ConvBn3d,
627
+ nniqat.ConvBn1d,
628
+ nniqat.ConvBn2d,
629
+ nniqat.ConvBn3d,
630
+ nniqat.ConvBnReLU1d,
631
+ nniqat.ConvBnReLU2d,
632
+ nniqat.ConvBnReLU3d,
633
+ nniqat.ConvReLU1d,
634
+ nniqat.ConvReLU2d,
635
+ nniqat.ConvReLU3d,
636
+ nniqat.LinearReLU,
637
+ nniqat.LinearBn1d,
638
+ nniqd.LinearReLU,
639
+ nni.LinearLeakyReLU,
640
+ nni.LinearTanh,
641
+ nni.ConvAdd2d,
642
+ nni.ConvAddReLU2d,
643
+ }
644
+
645
+ MODS_IO_TYPE_INT8: set[NSNodeTargetType] = {
646
+ nnq.Linear,
647
+ nnq.Conv1d,
648
+ nnq.Conv2d,
649
+ nnq.Conv3d,
650
+ nnq.BatchNorm2d,
651
+ nnq.BatchNorm3d,
652
+ nnq.Dropout,
653
+ nnq.ConvTranspose1d,
654
+ nnq.ConvTranspose2d,
655
+ nnq.ELU,
656
+ nnq.InstanceNorm1d,
657
+ nnq.InstanceNorm2d,
658
+ nnq.InstanceNorm3d,
659
+ nnq.LayerNorm,
660
+ nnq.Hardswish,
661
+ nnq.LeakyReLU,
662
+ nnq.Embedding,
663
+ nnq.EmbeddingBag,
664
+ nnq.Dropout,
665
+ nnq.Softmax,
666
+ nnq.PReLU,
667
+ nniq.BNReLU2d,
668
+ nniq.BNReLU3d,
669
+ nniq.ConvReLU1d,
670
+ nniq.ConvReLU2d,
671
+ nniq.ConvReLU3d,
672
+ nniq.LinearReLU,
673
+ nniq.LinearLeakyReLU,
674
+ nniq.LinearTanh,
675
+ nniq.ConvAdd2d,
676
+ nniq.ConvAddReLU2d,
677
+ }
678
+
679
+ MODS_IO_TYPE_FP32_OR_INT8: set[NSNodeTargetType] = {
680
+ nn.ReLU,
681
+ nn.Tanh,
682
+ nn.Sigmoid,
683
+ nn.Hardsigmoid,
684
+ nn.AdaptiveAvgPool1d,
685
+ nn.AdaptiveAvgPool2d,
686
+ nn.AdaptiveAvgPool3d,
687
+ nn.AvgPool1d,
688
+ nn.AvgPool2d,
689
+ nn.AvgPool3d,
690
+ nn.Dropout,
691
+ nn.Hardtanh,
692
+ nn.Identity,
693
+ nn.MaxPool1d,
694
+ nn.MaxPool2d,
695
+ nn.MaxPool3d,
696
+ nn.PixelShuffle,
697
+ nn.PixelUnshuffle,
698
+ nn.ReLU6,
699
+ }
700
+
701
+ METHS_IO_TYPE_FP32_OR_INT8: set[NSNodeTargetType] = {
702
+ "sigmoid_",
703
+ "sigmoid",
704
+ "tanh_",
705
+ "tanh",
706
+ "hardsigmoid_",
707
+ "hardsigmoid",
708
+ "relu_",
709
+ "relu",
710
+ }
711
+
712
+ return {
713
+ "funs_io_type_fp32": FUNS_IO_TYPE_FP32,
714
+ "funs_io_type_fp16": FUNS_IO_TYPE_FP16,
715
+ "funs_io_type_int8": FUNS_IO_TYPE_INT8,
716
+ "funs_io_type_fp32_or_int8": FUNS_IO_TYPE_FP32_OR_INT8,
717
+ "mods_io_type_fp32": MODS_IO_TYPE_FP32,
718
+ "mods_io_type_int8": MODS_IO_TYPE_INT8,
719
+ "mods_io_type_fp32_or_int8": MODS_IO_TYPE_FP32_OR_INT8,
720
+ "meths_io_type_fp32_or_int8": METHS_IO_TYPE_FP32_OR_INT8,
721
+ }
722
+
723
+
724
+ def get_unmatchable_types_map() -> dict[str, set[NSNodeTargetType]]:
725
+ FUNS_UNMATCHABLE: set[NSNodeTargetType] = {
726
+ torch.quantize_per_tensor,
727
+ operator.getitem,
728
+ }
729
+
730
+ MODS_UNMATCHABLE: set[NSNodeTargetType] = {
731
+ nn.Identity,
732
+ }
733
+
734
+ METHS_UNMATCHABLE: set[NSNodeTargetType] = {
735
+ "to",
736
+ "dequantize",
737
+ "reshape",
738
+ "view",
739
+ "unsqueeze_",
740
+ "unsqueeze",
741
+ "transpose",
742
+ "squeeze_",
743
+ "squeeze",
744
+ "size",
745
+ "shape",
746
+ "resize_",
747
+ "repeat_interleave",
748
+ "repeat",
749
+ "permute",
750
+ "numel",
751
+ "mean",
752
+ "detach_",
753
+ "detach",
754
+ "contiguous",
755
+ "clamp",
756
+ "chunk",
757
+ }
758
+
759
+ return {
760
+ "funs_unmatchable": FUNS_UNMATCHABLE,
761
+ "mods_unmatchable": MODS_UNMATCHABLE,
762
+ "meths_unmatchable": METHS_UNMATCHABLE,
763
+ }
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/n_shadows_utils.py ADDED
@@ -0,0 +1,1416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections
3
+ import copy
4
+ import operator
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ import torch
9
+ import torch.fx
10
+ from torch.ao.ns.fx.graph_passes import _maybe_get_fqn
11
+ from torch.ao.ns.fx.ns_types import NSResultsType, NSSingleResultValuesType
12
+ from torch.ao.ns.fx.utils import ( # TODO(future PR): make this work correctly for methods
13
+ get_normalized_nth_input,
14
+ get_target_type_str,
15
+ )
16
+ from torch.ao.quantization import QConfigMapping
17
+ from torch.ao.quantization.fx.match_utils import _MatchResult
18
+ from torch.ao.quantization.qconfig import QConfigAny
19
+ from torch.ao.quantization.utils import getattr_from_fqn
20
+ from torch.fx import Graph, GraphModule, Node
21
+ from torch.utils._pytree import tree_map
22
+
23
+
24
+ SHADOW_NODE_NAME_PREFIX = "shadow"
25
+ SHADOW_WRAPPER_NODE_NAME_PREFIX = "shadow_wrapper"
26
+
27
+ # TODO(future PR): reuse existing mapping instead of creating a new one
28
+ BINARY_FUNCTIONS = {
29
+ torch.add,
30
+ torch.Tensor.add,
31
+ operator.add,
32
+ torch.mul,
33
+ torch.Tensor.mul,
34
+ operator.mul,
35
+ }
36
+
37
+
38
+ def _get_attr_name(subgraph_idx, subgraph_candidate_idx):
39
+ return f"{SHADOW_NODE_NAME_PREFIX}_{subgraph_idx}_{subgraph_candidate_idx}"
40
+
41
+
42
+ def _get_attr_wrapper_name(subgraph_idx, subgraph_candidate_idx):
43
+ return f"{SHADOW_WRAPPER_NODE_NAME_PREFIX}_{subgraph_idx}_{subgraph_candidate_idx}"
44
+
45
+
46
+ class OutputProp:
47
+ """
48
+ Output propagation (modeled from shape propagation).
49
+
50
+ Given a GraphModule and an example input, saves the output flowing
51
+ through each node on `node.traced_result`.
52
+
53
+ Code based on the example from
54
+ https://pytorch.org/docs/stable/fx.html#the-interpreter-pattern
55
+ """
56
+
57
+ def __init__(self, mod):
58
+ self.mod = mod
59
+ self.graph = mod.graph
60
+ self.modules = dict(self.mod.named_modules())
61
+
62
+ def propagate(self, *args):
63
+ args_iter = iter(args)
64
+ env: dict[str, Node] = {}
65
+
66
+ def load_arg(a):
67
+ return torch.fx.graph.map_arg(a, lambda n: env[n.name])
68
+
69
+ def fetch_attr(target: str):
70
+ target_atoms = target.split(".")
71
+ attr_itr = self.mod
72
+ for i, atom in enumerate(target_atoms):
73
+ if not hasattr(attr_itr, atom):
74
+ raise RuntimeError(
75
+ f"Node referenced nonexistent target {'.'.join(target_atoms[:i])}"
76
+ )
77
+ attr_itr = getattr(attr_itr, atom)
78
+ return attr_itr
79
+
80
+ for node in self.graph.nodes:
81
+ if node.op == "placeholder":
82
+ result = next(args_iter)
83
+ elif node.op == "get_attr":
84
+ result = fetch_attr(node.target)
85
+ elif node.op == "call_function":
86
+ result = node.target(*load_arg(node.args), **load_arg(node.kwargs))
87
+ elif node.op == "call_method":
88
+ self_obj, *args = load_arg(node.args)
89
+ kwargs = load_arg(node.kwargs)
90
+ result = getattr(self_obj, node.target)(*args, **kwargs)
91
+ elif node.op == "call_module":
92
+ result = self.modules[node.target](
93
+ *load_arg(node.args), **load_arg(node.kwargs)
94
+ )
95
+
96
+ if isinstance(result, torch.Tensor): # type: ignore[possibly-undefined]
97
+ # pyrefly: ignore [unbound-name]
98
+ node.traced_result = result
99
+
100
+ # pyrefly: ignore [unsupported-operation]
101
+ # pyrefly: ignore [unbound-name]
102
+ env[node.name] = result
103
+
104
+ return None
105
+
106
+
107
+ def _get_dedup_subgraphs(matches: dict[str, _MatchResult]) -> dict[str, list[Node]]:
108
+ # the original matches variable is unique by node, make it unique by subgraph
109
+ # instead
110
+ seen_nodes = set()
111
+ subgraphs_dedup = {}
112
+
113
+ # Dict items are not reversible until Python 3.8, so we hack it
114
+ # to be compatible with previous Python versions
115
+ # TODO(future PR): try reversed(list(matches.items()))
116
+ matches_items_reversed: list[tuple[str, _MatchResult]] = list(
117
+ reversed(matches.items())
118
+ )
119
+
120
+ # Note: the order is important. `matches` currently provides the matches
121
+ # in reverse order. We would like to process the matches in non-reverse
122
+ # order, so that we can create an intuitive naming scheme, such as
123
+ # naming the first op's submodules `shadow_0_0` through `shadow_0_(n-1)`
124
+ for name, cur_match in matches_items_reversed: # type: ignore[call-overload]
125
+ was_seen = False
126
+ for node_or_tuple in cur_match[1]:
127
+ # Cur_match[1] has an unusual type. It says that it's a `List[Node]`,
128
+ # but it is really not. Furthermore, the contents of this field
129
+ # can change from match results of multiple nodes of the same pattern
130
+ #
131
+ # For example, for conv -> bn -> relu, we see
132
+ # match_results = {
133
+ # 'conv': (relu, [(bn, conv), relu], ...),
134
+ # 'bn': (relu, [(bn, conv), relu], ...),
135
+ # 'relu': (relu, [(bn, conv), relu], ...),
136
+ # }
137
+ #
138
+ # Ideally we should clean up the `find_matches` function to make
139
+ # this more intuitive. For the purposes of this prototype, we hack
140
+ # around it.
141
+
142
+ if isinstance(node_or_tuple, Node):
143
+ if node_or_tuple in seen_nodes:
144
+ was_seen = True
145
+ seen_nodes.add(node_or_tuple)
146
+
147
+ else:
148
+ if not isinstance(node_or_tuple, tuple):
149
+ raise AssertionError(f"Expected tuple, got {type(node_or_tuple)}")
150
+ for node in node_or_tuple:
151
+ if not isinstance(node, Node):
152
+ raise AssertionError(f"Expected Node, got {type(node)}")
153
+ if node in seen_nodes:
154
+ was_seen = True
155
+ seen_nodes.add(node)
156
+
157
+ if was_seen:
158
+ continue
159
+
160
+ # Start with the unusual type, convert it to [op_0, ..., op_n]
161
+ list_of_nodes = []
162
+
163
+ if len(cur_match[1]) == 1:
164
+ list_of_nodes = cur_match[1]
165
+ else:
166
+ if len(cur_match[1]) != 2:
167
+ raise ValueError(
168
+ f"Expected cur_match[1] to have length 2, got {len(cur_match[1])}"
169
+ )
170
+ # either (a, b), or ((a, b), c) or (c, (a, b))
171
+ # cannot make any assumptions on order, not clear what the
172
+ # _find_matches function is doing to populate this
173
+ # TODO(future PR): make this code less confusing, see discussion
174
+ # in https://github.com/pytorch/pytorch/pull/80521/files#r975918836
175
+
176
+ def _order_nodes(node_a, node_b, node_c) -> list[Node]:
177
+ nodes = [node_a, node_b, node_c]
178
+ first_node = None
179
+ mid_node = None
180
+ last_node = None
181
+ for n in nodes:
182
+ prev_n = n.args[0]
183
+ next_n = next(iter(n.users))
184
+ if prev_n not in nodes:
185
+ first_node = n
186
+ elif next_n not in nodes:
187
+ last_node = n
188
+ else:
189
+ mid_node = n
190
+ if first_node is None or mid_node is None or last_node is None:
191
+ raise AssertionError("Expected all nodes to be non-None")
192
+ if mid_node.args[0] is not first_node:
193
+ raise AssertionError("Expected mid_node.args[0] to be first_node")
194
+ if last_node.args[0] is not mid_node:
195
+ raise AssertionError("Expected last_node.args[0] to be mid_node")
196
+ return [last_node, mid_node, first_node]
197
+
198
+ if isinstance(cur_match[1][0], Node) and isinstance(cur_match[1][1], Node):
199
+ # (a, b)
200
+ list_of_nodes = cur_match[1]
201
+ elif isinstance(cur_match[1][0], tuple):
202
+ # ((a, b), c)
203
+ node_a, node_b = cur_match[1][0]
204
+ node_c = cur_match[1][1]
205
+ list_of_nodes = _order_nodes(node_a, node_b, node_c)
206
+ elif isinstance(cur_match[1][1], tuple):
207
+ # (a, (b, c))
208
+ node_a, node_b = cur_match[1][1]
209
+ node_c = cur_match[1][0]
210
+ list_of_nodes = _order_nodes(node_a, node_b, node_c)
211
+
212
+ # [node_n, ..., node_0], note that the order is reversed
213
+ # to make it chronological for simple subgraphs
214
+ list_of_nodes.reverse()
215
+ subgraphs_dedup[name] = list_of_nodes
216
+
217
+ return subgraphs_dedup
218
+
219
+
220
+ def _get_logger_for_subgraph(
221
+ model: GraphModule,
222
+ first_node: Node,
223
+ last_node: Node,
224
+ subgraph_idx: int,
225
+ subgraph_candidate_idx: int,
226
+ qconfig_str: str,
227
+ logger_cls: Callable,
228
+ fqn: str | None,
229
+ ) -> torch.nn.Module:
230
+ """
231
+ Given a model and a linear subgraph starting from `first_node` and
232
+ ending with `last_node`, creates a logger for the end of this
233
+ subgraph.
234
+ """
235
+ if fqn is None:
236
+ fqn = ""
237
+ logger_mod_orig = logger_cls(
238
+ first_node.name, # ref_node_name
239
+ last_node.name, # prev_node_name
240
+ f"subgraph_{subgraph_idx}_{subgraph_candidate_idx}", # model_name
241
+ "model", # ref_name
242
+ get_target_type_str(last_node, model), # prev_node_target_type
243
+ get_target_type_str(first_node, model), # ref_node_target_type
244
+ NSSingleResultValuesType.NODE_OUTPUT.value, # results_type
245
+ 0, # index_within_arg
246
+ 0, # index_of_arg
247
+ fqn, # fqn
248
+ qconfig_str,
249
+ )
250
+ # Usually we expect the user to add loggers, then calibrate, then convert,
251
+ # and then populate loggers. This is why the loggers start disabled.
252
+ # TODO(future PR): reconsider the design to make this more intuitive.
253
+ logger_mod_orig.enabled = False
254
+ return logger_mod_orig
255
+
256
+
257
+ def create_submodule_from_subgraph(
258
+ model: torch.nn.Module,
259
+ first_node: Node,
260
+ last_node: Node,
261
+ ) -> GraphModule:
262
+ """
263
+ Input: a model, and a linear subgraph within the model from first_node to
264
+ last_node.
265
+
266
+ Output: a new submodule containing a copy of the subgraph, with the inputs
267
+ to the first node becoming the inputs to the submodule, and all other
268
+ nodes in the subgraph being copied.
269
+
270
+ Example inputs:
271
+
272
+ `model`: a module with graph
273
+
274
+ x0 -> op1 -> x1 -> op2 -> x2
275
+ |
276
+ arg1
277
+
278
+ `first_node`: op1
279
+ `last_node`: op2
280
+
281
+ Example output: a new module with graph
282
+
283
+ input1 -> op1_copy -> x1 -> op2_copy -> output1
284
+ |
285
+ arg1
286
+ """
287
+
288
+ #
289
+ # create a blank GraphModule with an empty graph
290
+ #
291
+
292
+ class M(torch.nn.Module):
293
+ def forward(self, x):
294
+ pass
295
+
296
+ m = M()
297
+ gm = torch.fx.symbolic_trace(m)
298
+ g = gm.graph
299
+ for node in reversed(gm.graph.nodes):
300
+ g.erase_node(node)
301
+
302
+ #
303
+ # modify the graph to have a copy of our subgraph
304
+ #
305
+
306
+ cur_node_orig = first_node
307
+
308
+ cur_name_idx = 0
309
+
310
+ iteration_limit = 100
311
+ cur_iteration = 0
312
+
313
+ while True:
314
+ if cur_node_orig is first_node:
315
+ # we are at the first node, we need to set up graph inputs
316
+ # TODO(future): some graphs could have placeholders which are unrelated
317
+ # to the first node, need to handle this
318
+ cur_args_copy = []
319
+ cur_kwargs_copy = {}
320
+ seen_names: set[str] = set()
321
+ old_name_to_new_node: dict[str, Node] = {}
322
+
323
+ def _add_placeholder(
324
+ g: Graph, node: Node, seen_names, old_name_to_new_node
325
+ ):
326
+ # note: for graphs starting with patterns such as `y = x + x`, we
327
+ # need to ensure we do not add multiple placeholders with the
328
+ # same name
329
+ counter = 0
330
+ while node.name + "_" + str(counter) in seen_names:
331
+ counter += 1
332
+ cur_name = node.name + "_" + str(counter)
333
+ seen_names.add(cur_name)
334
+ placeholder = g.placeholder(cur_name)
335
+ old_name_to_new_node[node.name] = placeholder
336
+ return placeholder
337
+
338
+ for arg in cur_node_orig.args:
339
+ if isinstance(arg, Node):
340
+ p = _add_placeholder(g, arg, seen_names, old_name_to_new_node)
341
+ cur_args_copy.append(p)
342
+ elif isinstance(arg, (list, tuple)):
343
+ new_arg = []
344
+ for inner_arg in arg:
345
+ if isinstance(inner_arg, Node):
346
+ new_arg.append(
347
+ _add_placeholder(
348
+ g, inner_arg, seen_names, old_name_to_new_node
349
+ )
350
+ )
351
+ else:
352
+ new_arg.append(inner_arg)
353
+ cur_args_copy.append(new_arg)
354
+ else:
355
+ cur_args_copy.append(arg)
356
+
357
+ # TODO(future PR): handle non-normalized kwargs
358
+ for kwarg_name, kwarg in cur_node_orig.kwargs.items():
359
+ if isinstance(kwarg, Node):
360
+ cur_kwargs_copy[kwarg_name] = _add_placeholder(
361
+ g, kwarg, seen_names, old_name_to_new_node
362
+ )
363
+ elif isinstance(kwarg, (list, tuple)):
364
+ new_kwarg = []
365
+ for inner_kwarg in kwarg:
366
+ p = _add_placeholder(
367
+ g,
368
+ inner_kwarg, # type: ignore[arg-type]
369
+ seen_names,
370
+ old_name_to_new_node,
371
+ )
372
+ new_kwarg.append(p)
373
+ cur_kwargs_copy[kwarg_name] = new_kwarg
374
+ else:
375
+ cur_kwargs_copy[kwarg_name] = kwarg
376
+
377
+ cur_args_copy = tuple(cur_args_copy) # type: ignore[assignment]
378
+ else:
379
+ # we are not at first node, first arg is from the previous node,
380
+ # and all other args are copied
381
+
382
+ # the current implementation is simplistic and cannot handle
383
+ # ops with two or more arguments which need to be passed from
384
+ # the previous op, so we assert them out
385
+ if cur_node_orig.target in BINARY_FUNCTIONS:
386
+ raise AssertionError(
387
+ f"Unexpected binary function target: {cur_node_orig.target}"
388
+ )
389
+
390
+ # at this point in the code, cur_node_copy is pointing to the copy
391
+ # of the previous node
392
+ # TODO(future PR): this is not handling complicated graphs correctly, need to
393
+ # look at actual relationships instead of assuming sequential graph
394
+ # TODO(future PR): this is ignoring kwargs, will need to support kwargs
395
+ # for any fusion pattern which has them for a node that is not the
396
+ # first node.
397
+ cur_args_copy = [cur_node_copy] # type: ignore[has-type, possibly-undefined] # noqa: F821
398
+
399
+ if len(cur_node_orig.args) > 1:
400
+ for arg in cur_node_orig.args[1:]:
401
+ if isinstance(arg, torch.nn.Parameter):
402
+ new_arg = arg.detach().clone() # type: ignore[assignment]
403
+ mod_name = f"mod_{cur_name_idx}"
404
+ cur_name_idx += 1
405
+ setattr(gm, mod_name, new_arg)
406
+ new_arg_placeholder = gm.placeholder(mod_name) # type: ignore[operator]
407
+ # pyrefly: ignore [missing-attribute]
408
+ cur_args_copy.append(new_arg_placeholder)
409
+ elif isinstance(arg, (float, int, torch.dtype)):
410
+ # pyrefly: ignore [missing-attribute]
411
+ cur_args_copy.append(arg)
412
+ else:
413
+ raise AssertionError(f"arg of type {type(arg)} not handled yet")
414
+ cur_args_copy = tuple(cur_args_copy) # type: ignore[assignment]
415
+
416
+ # copy the node
417
+ if cur_node_orig.op == "call_module":
418
+ orig_mod = getattr_from_fqn(model, cur_node_orig.target) # type: ignore[arg-type]
419
+ orig_mod_copy = copy.deepcopy(orig_mod)
420
+ mod_name = f"mod_{cur_name_idx}"
421
+ setattr(gm, mod_name, orig_mod_copy)
422
+ cur_name_idx += 1
423
+ cur_node_copy = g.call_module(mod_name, cur_args_copy, cur_kwargs_copy) # type: ignore[possibly-undefined,arg-type]
424
+
425
+ elif cur_node_orig.op == "call_function":
426
+ cur_node_copy = g.call_function(
427
+ cur_node_orig.target, # type: ignore[arg-type]
428
+ cur_args_copy, # type: ignore[arg-type]
429
+ cur_kwargs_copy, # type: ignore[possibly-undefined]
430
+ )
431
+
432
+ elif cur_node_orig.op == "call_method":
433
+ cur_node_copy = g.call_method(
434
+ cur_node_orig.target, # type: ignore[arg-type]
435
+ cur_args_copy, # type: ignore[arg-type]
436
+ cur_kwargs_copy, # type: ignore[possibly-undefined]
437
+ )
438
+
439
+ else:
440
+ raise AssertionError(f"{cur_node_orig.op} not supported yet")
441
+
442
+ if cur_node_orig is last_node:
443
+ break
444
+
445
+ # go to next node
446
+ if len(cur_node_orig.users.keys()) != 1:
447
+ raise AssertionError(
448
+ f"{cur_node_orig} has more than 1 users, not supported yet"
449
+ )
450
+ cur_node_orig = next(iter(cur_node_orig.users.keys()))
451
+ cur_iteration += 1
452
+ if cur_iteration > iteration_limit:
453
+ raise AssertionError("iteration limit exceeded")
454
+
455
+ # set up outputs
456
+ g.output(cur_node_copy)
457
+
458
+ gm.recompile()
459
+ return gm
460
+
461
+
462
+ def create_one_transformed_and_logged_copy_of_subgraph(
463
+ mt: GraphModule,
464
+ subgraph_idx: int,
465
+ subgraph_candidate_idx: int,
466
+ first_node: Node,
467
+ last_node: Node,
468
+ fqn: str | None,
469
+ list_of_node_name_to_qconfig: list[dict[str, QConfigAny]],
470
+ example_inputs: Any,
471
+ last_added_shadow_node_list: list[Node | None],
472
+ custom_prepare_fn: Callable | None = None,
473
+ custom_prepare_kwargs: dict[str, Any] | None = None,
474
+ ) -> None:
475
+ """
476
+ Given a subgraph in `mt` and a subgraph candidate idx, inserts the
477
+ subgraph candidate copy and instruments it with loggers.
478
+
479
+ If subgraph_candidate_idx is 0, this is the baseline fp32 subgraph and we just
480
+ add a logger to the end.
481
+
482
+ If subgraph_candidate_idx is not 0, we create a copy of the subgraph and
483
+ prepare it with `prepare_fx`.
484
+ """
485
+
486
+ # TODO(future PR): move logger classes to utils to remove circular dependency
487
+ from torch.ao.ns._numeric_suite_fx import OutputComparisonLogger, OutputLogger
488
+
489
+ if subgraph_candidate_idx == 0:
490
+ # idx = 0 is the floating point (original) version of the subgraph
491
+ # We keep the subgraph as is, and add a logger at the end
492
+
493
+ qconfig_str = ""
494
+ logger_mod_orig = _get_logger_for_subgraph(
495
+ mt,
496
+ first_node,
497
+ last_node,
498
+ subgraph_idx,
499
+ subgraph_candidate_idx,
500
+ qconfig_str,
501
+ OutputLogger,
502
+ fqn,
503
+ )
504
+
505
+ attr_name = _get_attr_name(subgraph_idx, subgraph_candidate_idx)
506
+ if hasattr(mt, attr_name):
507
+ raise AssertionError(f"Unexpected attribute '{attr_name}' found in {mt}")
508
+ setattr(mt, attr_name, logger_mod_orig)
509
+ with mt.graph.inserting_after(last_node):
510
+ new_node = mt.graph.call_module(attr_name, args=(last_node,), kwargs={})
511
+ last_added_shadow_node_list[0] = new_node
512
+
513
+ else:
514
+ # idx > 0 means we have a candidate qconfig to try, so we need
515
+ # to make a copy of the subgraph, feed it with the right inputs,
516
+ # and add a logger at the end
517
+
518
+ # get the qconfig
519
+ # subtract one because the first candidate is the floating point
520
+ # version of the subgraph
521
+ node_name_to_qconfig = list_of_node_name_to_qconfig[subgraph_candidate_idx - 1]
522
+ qconfig = node_name_to_qconfig[first_node.name]
523
+
524
+ # if no quantization is requested, skip
525
+ # TODO(future PR): deduplicate equivalent qconfigs that come from
526
+ # different qconfig mapping objects
527
+ if qconfig is None:
528
+ return
529
+
530
+ qconfig_mapping = QConfigMapping().set_global(qconfig)
531
+
532
+ # create a copy of the submodule, wrapped in a separate module
533
+ orig_mod_copy_wrapped = create_submodule_from_subgraph(
534
+ mt, first_node, last_node
535
+ )
536
+
537
+ # add a call to prepare_fx on the wrapper module
538
+ if custom_prepare_fn is None:
539
+ orig_mod_copy_wrapped = torch.ao.quantization.quantize_fx.prepare_fx(
540
+ orig_mod_copy_wrapped, qconfig_mapping, example_inputs=example_inputs
541
+ )
542
+ else:
543
+ if custom_prepare_kwargs is None:
544
+ custom_prepare_kwargs = {}
545
+ for kwarg_name in [
546
+ "example_inputs",
547
+ "prepare_custom_config",
548
+ "qconfig_mapping",
549
+ ]:
550
+ if kwarg_name in custom_prepare_kwargs:
551
+ raise AssertionError(
552
+ f"cannot specify {kwarg_name} in custom_prepare_kwargs"
553
+ )
554
+ prepare_kwargs: dict[str, Any] = {
555
+ "example_inputs": example_inputs,
556
+ "qconfig_mapping": qconfig_mapping,
557
+ }
558
+ prepare_kwargs.update(custom_prepare_kwargs)
559
+ orig_mod_copy_wrapped = custom_prepare_fn(
560
+ orig_mod_copy_wrapped, **prepare_kwargs
561
+ )
562
+
563
+ # attach the wrapper to the model
564
+ attr_name = _get_attr_wrapper_name(subgraph_idx, subgraph_candidate_idx)
565
+ if hasattr(mt, attr_name):
566
+ raise AssertionError(f"Unexpected attribute '{attr_name}' found in {mt}")
567
+ setattr(mt, attr_name, orig_mod_copy_wrapped)
568
+
569
+ # add a call to the wrapper module from the parent graph
570
+ insert_after_node = last_added_shadow_node_list[0]
571
+ with mt.graph.inserting_after(insert_after_node):
572
+ # TODO(future PR): handle fusion patterns where non-first nodes
573
+ # need inputs
574
+
575
+ # pass in all node args and kwargs
576
+
577
+ new_args = []
578
+ for arg in first_node.args:
579
+ if isinstance(arg, Node):
580
+ new_args.append(arg)
581
+ elif (
582
+ isinstance(arg, (list, tuple))
583
+ and len(arg)
584
+ and isinstance(arg[0], Node)
585
+ ):
586
+ new_args.extend(
587
+ inner_arg for inner_arg in arg if isinstance(inner_arg, Node)
588
+ )
589
+
590
+ new_kwargs = {}
591
+ for name, old_kwarg in first_node.kwargs.items():
592
+ if isinstance(old_kwarg, Node):
593
+ new_kwargs[name] = old_kwarg
594
+ elif isinstance(old_kwarg, (list, tuple)) and len(old_kwarg):
595
+ # TODO(future PR): clarify why we are adding kwargs to args
596
+ new_args.extend(old_kwarg) # type: ignore[arg-type]
597
+
598
+ new_args = tuple(new_args) # type: ignore[assignment]
599
+
600
+ new_node = mt.graph.call_module(attr_name, args=new_args, kwargs=new_kwargs) # type: ignore[arg-type]
601
+
602
+ # add a logger to parent graph to observe the shadow wrapper
603
+ logger_mod_orig = _get_logger_for_subgraph(
604
+ mt,
605
+ first_node,
606
+ last_node,
607
+ subgraph_idx,
608
+ subgraph_candidate_idx,
609
+ str(qconfig),
610
+ OutputComparisonLogger,
611
+ fqn,
612
+ )
613
+
614
+ attr_name = _get_attr_name(subgraph_idx, subgraph_candidate_idx)
615
+ if hasattr(mt, attr_name):
616
+ raise AssertionError(f"Unexpected attribute '{attr_name}' found in {mt}")
617
+ setattr(mt, attr_name, logger_mod_orig)
618
+ with mt.graph.inserting_after(new_node):
619
+ logger = mt.graph.call_module(
620
+ attr_name, args=(new_node, last_node), kwargs={}
621
+ )
622
+ last_added_shadow_node_list[0] = logger
623
+
624
+ mt.recompile()
625
+
626
+
627
+ def create_n_transformed_and_logged_copies_of_subgraph(
628
+ mt: GraphModule,
629
+ subgraph_idx: int,
630
+ match_name: str,
631
+ nodes_in_this_subgraph: list[Any],
632
+ qconfig_mappings: list[QConfigMapping],
633
+ list_of_node_name_to_qconfig: list[dict[str, QConfigAny]],
634
+ custom_prepare_fn: Callable | None = None,
635
+ custom_prepare_kwargs: dict[str, Any] | None = None,
636
+ ) -> None:
637
+ """
638
+ Given a model `mt` and a subgraph_idx, creates the needed copies
639
+ of the subgraph for all qconfigs, and instruments them with loggers.
640
+ """
641
+ # for now, assume that
642
+ # 1. the first node has one input
643
+ # 2. the last node has one output
644
+
645
+ # for now, ignore all subgraphs that contain non-nodes (tuples, etc)
646
+ # TODO(future PR): implement this
647
+ if any(not isinstance(node, Node) for node in nodes_in_this_subgraph):
648
+ return
649
+
650
+ first_node = nodes_in_this_subgraph[0]
651
+ last_node = nodes_in_this_subgraph[-1]
652
+ # We used output propagation to populate example values on each
653
+ # node. Use the example values from the previous node as the input
654
+ # to the current node.
655
+ prev_node = get_normalized_nth_input(first_node, mt, 0)
656
+ if isinstance(prev_node, list):
657
+ example_inputs = [x.traced_result for x in prev_node]
658
+ elif isinstance(prev_node, tuple):
659
+ example_inputs = (x.traced_result for x in prev_node) # type: ignore[assignment]
660
+ else:
661
+ # currently some customer models do not have a traced_result in
662
+ # every node, so we have to guard for this case since we cannot
663
+ # quantize without an example input
664
+ # TODO(future PR): add a test case for this once we have an easy
665
+ # repro, see https://github.com/pytorch/pytorch/pull/80521/files#r975940489
666
+ # for additional context
667
+ if hasattr(prev_node, "traced_result"):
668
+ example_inputs = (prev_node.traced_result,) # type: ignore[attr-defined, assignment]
669
+ else:
670
+ print(
671
+ "unable to get example input for node "
672
+ + f"{first_node.format_node()}, skipping"
673
+ )
674
+ return
675
+
676
+ # If there are no quantization configs for this subgraph, skip adding
677
+ # loggers. This reduces memory usage for models where not all layers are
678
+ # quantized.
679
+ # TODO(future): consider making this configurable
680
+ found_at_least_one_qconfig = False
681
+ for subgraph_candidate_idx in range(len(qconfig_mappings) + 1):
682
+ if subgraph_candidate_idx == 0:
683
+ # fp32 baseline does not need a qconfig
684
+ continue
685
+
686
+ # a. we have N shadows, so len(qconfig_mappings) is N
687
+ # b. we will have the fp32 layer + N shadows, so overall number of
688
+ # (original_op) + (*shadows) will be N+1
689
+ # c. since `subgraph_candidate_idx` represents (b), we need
690
+ # to subtract 1 to query from (a)
691
+ node_name_to_qconfig = list_of_node_name_to_qconfig[subgraph_candidate_idx - 1]
692
+ qconfig = node_name_to_qconfig[first_node.name]
693
+ if qconfig is not None:
694
+ found_at_least_one_qconfig = True
695
+ break
696
+ if not found_at_least_one_qconfig:
697
+ print(
698
+ "unable to find at least one qconfig for node "
699
+ + f"{first_node.format_node()}, skipping"
700
+ )
701
+ return
702
+
703
+ fqn = _maybe_get_fqn(first_node, mt)
704
+
705
+ # We want the results to contain the subgraphs in natural order,
706
+ # and the graph to also contain shadow wrappers and shadow loggers
707
+ # in natural order.
708
+ # If we just iterate in reverse, the graph will be in natural
709
+ # order but the eventual results will be in reverse order.
710
+ # So, we keep track of the last shadow logger we added and
711
+ # always insert after it.
712
+ last_added_shadow_node_list: list[Node | None] = [None]
713
+ for subgraph_candidate_idx in range(len(qconfig_mappings) + 1):
714
+ create_one_transformed_and_logged_copy_of_subgraph(
715
+ mt,
716
+ subgraph_idx,
717
+ subgraph_candidate_idx,
718
+ first_node,
719
+ last_node,
720
+ fqn,
721
+ list_of_node_name_to_qconfig,
722
+ example_inputs,
723
+ last_added_shadow_node_list,
724
+ custom_prepare_fn,
725
+ custom_prepare_kwargs,
726
+ )
727
+
728
+
729
+ def create_add_loggers_graph(
730
+ model: GraphModule,
731
+ subgraphs_dedup: dict[str, list[Node]],
732
+ qconfig_mapping: QConfigMapping,
733
+ node_name_to_qconfig: dict[str, QConfigAny],
734
+ ) -> None:
735
+ r"""
736
+ Given a model, a model graph partition (currently a set of matched
737
+ subgraphs) and instructions how to transform each subgraph
738
+ (currently quantizing it according to qconfig_mapping), modifies
739
+ the model graph to create an alternate path through the original graph,
740
+ with each of the subgraphs quantized. This is useful to compare
741
+ propagation error of a transformation such as quantization.
742
+
743
+ For example, given layer op0 and op1, there are four cases when handling op1:
744
+ 1. op0 and op1 quantized
745
+ 2. op0 and op1 unquantized
746
+ 3. op0 quantized, op1 unquantized
747
+ 4. op0 unquantized, op1 quantized
748
+
749
+ Example input, case 1:
750
+
751
+ .. code::
752
+
753
+ x0_0 -> op0_0 -> x1_0 -> log -----> op1_0 -> x2_0 -> log
754
+ \ \ \ \ # noqa: W605
755
+ ---> op0_1 -> x1_1 ----> clog op1_1 -> x2_1 ----> clog
756
+
757
+ Example output, case 1:
758
+
759
+ .. code::
760
+
761
+ x0_0 -> op0_0 -> x1_0 -> log -----> op1_0 -> x2_0 -> log
762
+ \ \ \ # noqa: W605
763
+ ---> op0_1 -> x1_1 ----> clog -> op1_1 -> x2_1 ----> clog
764
+
765
+ """
766
+ # TODO(future PR): move logger classes to utils to remove circular dependency
767
+ from torch.ao.ns._numeric_suite_fx import OutputComparisonLogger, OutputLogger
768
+
769
+ def _get_subgraph_containing_node(node, subgraphs_dedup):
770
+ for subgraph in subgraphs_dedup.values():
771
+ if node in subgraph:
772
+ return subgraph
773
+ return None
774
+
775
+ # First, we need to create shadow branches, going from
776
+ #
777
+ # x0 -> op0 -> x1 -> ...
778
+ #
779
+ #
780
+ # to
781
+ #
782
+ # x0 -> op0_0 -> x1_0 -> log -> ...
783
+ # \ \
784
+ # -> op0_1 -> x1_1 -> clog
785
+ #
786
+ # Later, the outputs of each shadow will be rerouted to calculate
787
+ # propagation error.
788
+
789
+ # Note: we cannot iterate over matched subgraphs because some nodes
790
+ # may not be matched. So, we iterate over nodes in the graph, and
791
+ # associate them to matched subgraphs if possible.
792
+
793
+ nodes_to_skip = set()
794
+ # for each subgraph, save a mapping from first node of subgraph
795
+ # to first and last node of the shadow of this subgraph
796
+ orig_first_node_to_shadow_in_node = {}
797
+ orig_first_node_to_shadow_out_node = {}
798
+ # need to record original list because we will mutate the graph as we go
799
+ orig_nodes = list(model.graph.nodes) # type: ignore[union-attr, arg-type]
800
+ cur_subgraph_idx = 0
801
+ for n in orig_nodes:
802
+ if n.op in ("placeholder", "get_attr", "output") or n in nodes_to_skip:
803
+ continue
804
+
805
+ maybe_subgraph = _get_subgraph_containing_node(n, subgraphs_dedup)
806
+ insert_submodule_copy = False
807
+ if maybe_subgraph is not None:
808
+ first_node, last_node = maybe_subgraph[0], maybe_subgraph[-1]
809
+ nodes_to_skip.update(maybe_subgraph)
810
+ qconfig = node_name_to_qconfig[first_node.name]
811
+ if qconfig is not None:
812
+ insert_submodule_copy = True
813
+ else:
814
+ first_node, last_node = n, n
815
+
816
+ if insert_submodule_copy:
817
+ match_name = first_node.name
818
+ create_n_transformed_and_logged_copies_of_subgraph(
819
+ model,
820
+ cur_subgraph_idx,
821
+ match_name,
822
+ # pyrefly: ignore [bad-argument-type]
823
+ maybe_subgraph,
824
+ [qconfig_mapping],
825
+ [node_name_to_qconfig],
826
+ None,
827
+ None, # type: ignore[arg-type]
828
+ )
829
+ # find the created shadow module and record it so we
830
+ # can find it easily in step 2
831
+ expected_shadow_target = f"shadow_wrapper_{cur_subgraph_idx}_1"
832
+ new_shadow_mod = None
833
+ for maybe_shadow_mod in model.graph.nodes:
834
+ if (
835
+ maybe_shadow_mod.op == "call_module"
836
+ and maybe_shadow_mod.target == expected_shadow_target
837
+ ):
838
+ new_shadow_mod = maybe_shadow_mod
839
+ break
840
+ if new_shadow_mod is None:
841
+ raise AssertionError("Expected new_shadow_mod to be non-None")
842
+ orig_first_node_to_shadow_in_node[first_node] = new_shadow_mod
843
+ orig_first_node_to_shadow_out_node[first_node] = new_shadow_mod
844
+
845
+ else:
846
+ # create a copy of the subgraph by only copying FX nodes
847
+ # but not copying any parameters, to minimize memory usage
848
+ subgraph_to_use = (
849
+ maybe_subgraph if maybe_subgraph is not None else [first_node]
850
+ )
851
+
852
+ # add a regular logger after last_node
853
+ qconfig_str = ""
854
+ subgraph_candidate_idx = 0
855
+ fqn = _maybe_get_fqn(first_node, model)
856
+ logger_mod_orig = _get_logger_for_subgraph(
857
+ model,
858
+ first_node,
859
+ last_node,
860
+ cur_subgraph_idx,
861
+ subgraph_candidate_idx,
862
+ qconfig_str,
863
+ OutputLogger,
864
+ fqn,
865
+ )
866
+ attr_name = _get_attr_name(cur_subgraph_idx, subgraph_candidate_idx)
867
+ if hasattr(model, attr_name):
868
+ raise AssertionError(
869
+ f"Unexpected attribute '{attr_name}' found in {model}"
870
+ )
871
+ setattr(model, attr_name, logger_mod_orig)
872
+ insertion_point = last_node
873
+ with model.graph.inserting_after(insertion_point):
874
+ logger = model.graph.call_module(
875
+ attr_name, args=(last_node,), kwargs={}
876
+ )
877
+ insertion_point = logger
878
+
879
+ # create a copy of the subgraph
880
+ cur_node_orig = first_node
881
+ cur_node_copy = None
882
+ first_node_copy = None
883
+ # pyrefly: ignore [bad-assignment]
884
+ while cur_node_orig in subgraph_to_use:
885
+ # TODO(future PR): make this support all possible args/kwargs
886
+ if cur_node_orig is first_node:
887
+ new_args = cur_node_orig.args
888
+ new_kwargs = cur_node_orig.kwargs
889
+ else:
890
+ first_arg_for_copy: Node | None = cur_node_copy
891
+ new_args = (first_arg_for_copy, *cur_node_orig.args[1:])
892
+ new_kwargs = cur_node_orig.kwargs
893
+ # make a copy of cur_node_orig
894
+ with model.graph.inserting_after(insertion_point):
895
+ cur_node_copy = model.graph.create_node(
896
+ cur_node_orig.op,
897
+ cur_node_orig.target,
898
+ new_args,
899
+ new_kwargs,
900
+ # cur_node_orig.name, # TODO(future PR): set name explicitly
901
+ )
902
+ if first_node_copy is None:
903
+ first_node_copy = cur_node_copy
904
+ # since now only linear subgraphs are supported, all nodes
905
+ # except the last one must have only one user
906
+ if cur_node_orig != last_node:
907
+ if len(cur_node_orig.users.keys()) != 1:
908
+ raise AssertionError(
909
+ f"Expected exactly 1, but got {len(cur_node_orig.users)}"
910
+ )
911
+ cur_node_orig = next(iter(cur_node_orig.users.keys()))
912
+ if cur_node_orig.name.startswith(SHADOW_NODE_NAME_PREFIX):
913
+ raise AssertionError(
914
+ "cur_node_orig should not start with SHADOW_NODE_NAME_PREFIX"
915
+ )
916
+ insertion_point = cur_node_copy
917
+
918
+ # add a comparison logger after last_node's copy
919
+ subgraph_candidate_idx = 1
920
+ logger_mod_orig = _get_logger_for_subgraph(
921
+ model,
922
+ first_node,
923
+ last_node,
924
+ cur_subgraph_idx,
925
+ subgraph_candidate_idx,
926
+ qconfig_str,
927
+ OutputComparisonLogger,
928
+ fqn,
929
+ )
930
+ attr_name = _get_attr_name(cur_subgraph_idx, subgraph_candidate_idx)
931
+ if hasattr(model, attr_name):
932
+ raise AssertionError(
933
+ f"Unexpected attribute '{attr_name}' found in {model}"
934
+ )
935
+ setattr(model, attr_name, logger_mod_orig)
936
+ with model.graph.inserting_after(insertion_point):
937
+ logger = model.graph.call_module(
938
+ attr_name, args=(cur_node_copy, last_node), kwargs={}
939
+ )
940
+
941
+ # save the final node so we can use it in step 2
942
+ orig_first_node_to_shadow_in_node[first_node] = first_node_copy
943
+ orig_first_node_to_shadow_out_node[first_node] = cur_node_copy
944
+
945
+ cur_subgraph_idx += 1
946
+
947
+ model.recompile()
948
+
949
+ # Now, we go from
950
+ #
951
+ # x0 -> op0_0 -> x1_0 -> log -> x1 -> op1_0 -> ...
952
+ # \ \ \
953
+ # -> op0_1 -> x1_1 -> clog -> op1_1 -> ...
954
+ #
955
+ # to
956
+ #
957
+ # x0 -> op0_0 -> x1_0 -> log --> x1_0 -> op1_0 -> ...
958
+ # \ \
959
+ # -> op0_1 -> x1_1 -> clog -> x1_1 -> op1_1 -> ...
960
+ #
961
+ # sample values of key internal variables for the example above:
962
+ #
963
+ # orig_first_node_to_shadow_in_node = {op0_0: op0_1, op1_0: op1_1}
964
+ # orig_first_node_to_shadow_out_node = {op0_0: op0_1, op1_0: op1_1}
965
+ #
966
+ # note: for subgraphs with more than one node, in_node will be different
967
+ # compared to out_node
968
+
969
+ nodes_to_skip = set()
970
+ for n in orig_nodes:
971
+ if n.op in ("placeholder", "get_attr", "output") or n in nodes_to_skip:
972
+ continue
973
+
974
+ maybe_subgraph = _get_subgraph_containing_node(n, subgraphs_dedup)
975
+ if maybe_subgraph is not None:
976
+ first_node, last_node = maybe_subgraph[0], maybe_subgraph[-1]
977
+ nodes_to_skip.update(maybe_subgraph)
978
+ else:
979
+ first_node, last_node = n, n
980
+
981
+ def maybe_remap_node_to_shadow(node):
982
+ """
983
+ If unshadowed `node` has a shadow version, return that. If not,
984
+ return `node`.
985
+ """
986
+ if not isinstance(node, Node):
987
+ # handle scalars
988
+ return node
989
+
990
+ if node.op in ("placeholder", "get_attr"):
991
+ return node
992
+
993
+ # Find the shadowed version of this arg from the previous
994
+ # subgraph. For this, we need to:
995
+ # 1. navigate to the first node of the previous subgraph
996
+ # 2. get the output of the shadow wrapper which has (1) as an input
997
+
998
+ # For now, assume the arg is in matched subgraphs. In the
999
+ # future we may have to handle the case where this is not true.
1000
+ prev_subgraph = _get_subgraph_containing_node(node, subgraphs_dedup)
1001
+ if prev_subgraph is None:
1002
+ prev_subgraph = [node]
1003
+ prev_first_node = prev_subgraph[0]
1004
+ prev_shadow_output = orig_first_node_to_shadow_out_node[prev_first_node]
1005
+ return prev_shadow_output
1006
+
1007
+ cur_shadow_input = orig_first_node_to_shadow_in_node[first_node]
1008
+ if cur_shadow_input is None:
1009
+ raise AssertionError("Expected cur_shadow_input to be non-None")
1010
+ cur_shadow_input.args = tree_map(
1011
+ maybe_remap_node_to_shadow, cur_shadow_input.args
1012
+ )
1013
+ cur_shadow_input.kwargs = tree_map(
1014
+ maybe_remap_node_to_shadow, cur_shadow_input.kwargs
1015
+ )
1016
+
1017
+ model.recompile()
1018
+
1019
+
1020
+ def _get_weight_info_from_shadow_wrapper(shadow_wrapper: torch.nn.Module):
1021
+ # input: shadow wrapper module
1022
+ # output if shadow wrapper module has a weighted op:
1023
+ # (quantize_fn, (quantize_fn_args))
1024
+ # output if shadow wrapper module doesn't have a weighted op:
1025
+ # None
1026
+
1027
+ # For now, assume that the weight is the second input
1028
+ # to the shadow module. If that changes, we can fix it later.
1029
+ placeholders_seen = 0
1030
+ for shadow_n in shadow_wrapper.graph.nodes: # type: ignore[union-attr]
1031
+ if shadow_n.op != "placeholder":
1032
+ continue
1033
+
1034
+ placeholders_seen += 1
1035
+ if placeholders_seen != 2:
1036
+ continue
1037
+
1038
+ # the subgraph looks like
1039
+ #
1040
+ # _input_scale_1 = self._input_scale_1
1041
+ # _input_zero_point_1 = self._input_zero_point_1
1042
+ # quantize_per_channel = torch.quantize_per_channel(
1043
+ # w2_0, _input_scale_1, _input_zero_point_1,
1044
+ # 0, torch.qint8)
1045
+ #
1046
+ # we have `w2_0`, and are navigating this subgraph
1047
+ # to get `_input_scale_1` and `_input_zero_point_1`
1048
+
1049
+ if len(shadow_n.users) != 1:
1050
+ raise AssertionError(f"Expected exactly 1, got {len(shadow_n.users)}")
1051
+ quant_node = next(iter(shadow_n.users.keys()))
1052
+ new_args: Any = None
1053
+ if quant_node.target is torch.quantize_per_channel:
1054
+ _weight, scale_node, zp_node, axis, dtype = quant_node.args
1055
+ scale_val = getattr_from_fqn(shadow_wrapper, scale_node.target)
1056
+ zp_val = getattr_from_fqn(shadow_wrapper, zp_node.target)
1057
+ new_args = (scale_val, zp_val, axis, dtype)
1058
+ else:
1059
+ if quant_node.target != torch.quantize_per_tensor:
1060
+ raise AssertionError(
1061
+ f"Expected torch.quantize_per_tensor, but got {quant_node.target}"
1062
+ )
1063
+ _weight, scale_node, zp_node, dtype = quant_node.args
1064
+ scale_val = getattr_from_fqn(shadow_wrapper, scale_node.target)
1065
+ zp_val = getattr_from_fqn(shadow_wrapper, zp_node.target)
1066
+ new_args = (scale_val, zp_val, dtype)
1067
+ return (quant_node.target, new_args)
1068
+
1069
+ return None
1070
+
1071
+
1072
+ def extract_weight_comparison(m: GraphModule) -> NSResultsType:
1073
+ # example graph:
1074
+ #
1075
+ # w1 = self.w1
1076
+ # b1 = self.b1
1077
+ # linear = torch._C._nn.linear(x, w1, b1)
1078
+ # shadow_0_0 = self.shadow_0_0(linear)
1079
+ # shadow_wrapper_0_1 = self.shadow_wrapper_0_1(x, w1, b1)
1080
+ # shadow_0_1 = self.shadow_0_1(shadow_wrapper_0_1, linear)
1081
+ #
1082
+ # algorithm:
1083
+ # 1. for each call_function node matching our allowlist:
1084
+ # 2. if corresponding shadow wrapper exists, extract the weight pair
1085
+ #
1086
+ # Note: this is not super robust, but that's ok because this is
1087
+ # just for legacy customers who depend on the previous two-model version
1088
+ # of this API. TBD if we need to make this robust.
1089
+ # Note: modules are not supported, since existing customers only
1090
+ # use functions.
1091
+
1092
+ # TODO(future PR): move this to config
1093
+ weighted_ops = {
1094
+ torch.nn.functional.linear,
1095
+ }
1096
+
1097
+ results: NSResultsType = {"model": {NSSingleResultValuesType.WEIGHT.value: {}}}
1098
+
1099
+ for n in m.graph.nodes: # type: ignore[union-attr]
1100
+ if not (n.op == "call_function" and n.target in weighted_ops):
1101
+ continue
1102
+
1103
+ # Check if we have a corresponding shadow wrapper
1104
+ # TODO(future PR, if needed): support kwargs
1105
+ # TODO(future PR, if needed): support multiple shadow users
1106
+ first_arg = n.args[0]
1107
+ shadow_wrapper_node = None
1108
+ for user in first_arg.users:
1109
+ # TODO(before land): fix string match
1110
+ if user.op == "call_module" and user.target.startswith("shadow_wrapper"):
1111
+ shadow_wrapper_node = user
1112
+ break
1113
+
1114
+ if shadow_wrapper_node is None:
1115
+ continue
1116
+
1117
+ shadow_wrapper = getattr_from_fqn(m, shadow_wrapper_node.target) # type: ignore[arg-type]
1118
+ weight_info = _get_weight_info_from_shadow_wrapper(shadow_wrapper)
1119
+ if weight_info is None:
1120
+ continue
1121
+
1122
+ # get weight
1123
+ w_node = n.args[1]
1124
+ w_obj = getattr_from_fqn(m, w_node.target).detach()
1125
+
1126
+ # get a quantized version of weight
1127
+ quant_fn, quant_fn_args_except_first = weight_info
1128
+ new_args = (w_obj, *quant_fn_args_except_first)
1129
+ w_obj_q = quant_fn(*new_args)
1130
+
1131
+ # add a comparison
1132
+ ref_node_name = n.name
1133
+ prev_node_name = n.name
1134
+ ref_node_type = get_target_type_str(n, m)
1135
+ prev_node_type = ref_node_type
1136
+ fqn = None
1137
+ if hasattr(m, "_node_name_to_scope"):
1138
+ fqn = m._node_name_to_scope[n.name][0] # type: ignore[index]
1139
+ comparison = torch.ao.ns.fx.utils.compute_sqnr(w_obj, w_obj_q)
1140
+ result_fp32 = {
1141
+ "res_type": NSSingleResultValuesType.WEIGHT.value,
1142
+ "values": [w_obj],
1143
+ "prev_node_name": prev_node_name,
1144
+ "prev_node_target_type": prev_node_type,
1145
+ "ref_node_name": ref_node_name,
1146
+ "ref_node_target_type": ref_node_type,
1147
+ "index_within_arg": 0,
1148
+ "index_of_arg": 0,
1149
+ "fqn": fqn,
1150
+ "qconfig_str": "",
1151
+ "comparisons": [comparison],
1152
+ "comparison_fn_name": "sqnr",
1153
+ }
1154
+ result_q = {
1155
+ "res_type": NSSingleResultValuesType.WEIGHT.value,
1156
+ "values": [w_obj_q],
1157
+ "prev_node_name": prev_node_name,
1158
+ "prev_node_target_type": prev_node_type,
1159
+ "ref_node_name": ref_node_name,
1160
+ "ref_node_target_type": ref_node_type,
1161
+ "index_within_arg": 0,
1162
+ "index_of_arg": 0,
1163
+ "fqn": fqn,
1164
+ "qconfig_str": "",
1165
+ "comparisons": [comparison],
1166
+ "comparison_fn_name": "sqnr",
1167
+ }
1168
+
1169
+ # go from subgraph_n_1 to subgraph_n_0
1170
+ _1, _2, node_idx, _3 = shadow_wrapper_node.target.split("_")
1171
+ name_fp32 = f"subgraph_{node_idx}_0"
1172
+ name_q = f"subgraph_{node_idx}_1"
1173
+
1174
+ results["model"][NSSingleResultValuesType.WEIGHT.value][name_fp32] = [
1175
+ result_fp32
1176
+ ]
1177
+ results["model"][NSSingleResultValuesType.WEIGHT.value][name_q] = [result_q]
1178
+
1179
+ return results
1180
+
1181
+
1182
+ # TODO(future PR): redesign this to make it easier to consume outputs
1183
+ def group_results_by_subgraph(results: NSResultsType) -> Any:
1184
+ """
1185
+ Creates a comparison of results
1186
+
1187
+ Input:
1188
+
1189
+ {
1190
+ 'model': {
1191
+ 'node_output': {
1192
+ 'subgraph_0_0': [
1193
+ 'values': [torch.tensor(...), ...], ...
1194
+ 'ref_node_name': ...,
1195
+ 'ref_node_target_type': ...,
1196
+ 'qconfig_str': ...,
1197
+ 'comparisons': [], ...
1198
+ 'comparison_fn_name': '',
1199
+ 'fqn': '...',
1200
+ ],
1201
+ 'subgraph_0_1': [
1202
+ 'values': [torch.tensor(...), ...], ...
1203
+ 'ref_node_name': ...,
1204
+ 'ref_node_target_type': ...,
1205
+ 'qconfig_str': ...,
1206
+ 'comparisons': [torch.tensor(...), ...], ...
1207
+ 'comparison_fn_name': '...',
1208
+ 'fqn': '...',
1209
+ ],
1210
+ ...
1211
+ },
1212
+ },
1213
+ }
1214
+
1215
+ Output:
1216
+ {
1217
+ 'subgraph_0': {
1218
+ '0': {
1219
+ 'ref_node_name': '...',
1220
+ 'ref_node_target_type': ...,
1221
+ 'values': [torch.tensor(...), ...],
1222
+ 'qconfig_str': None,
1223
+ 'comparisons': [torch.tensor(...), ...], ...
1224
+ 'comparison_fn_name': '...',
1225
+ 'fqn': '...',
1226
+ },
1227
+ '1': {
1228
+ 'ref_node_name': '...',
1229
+ 'ref_node_target_type': ...,
1230
+ 'values': [torch.tensor(...), ...],
1231
+ 'qconfig_str': '...',
1232
+ 'comparisons': [torch.tensor(...), ...], ...
1233
+ 'comparison_fn_name': '...',
1234
+ 'fqn': '...',
1235
+ },
1236
+ },
1237
+ }
1238
+
1239
+ """
1240
+ subgraph_name_to_subgraph_results: Any = collections.defaultdict(dict)
1241
+
1242
+ # node_output or weight
1243
+ key_to_use = next(iter(results["model"].keys()))
1244
+
1245
+ for subgraph_name_with_idx, subgraph_candidate_results in results["model"][
1246
+ key_to_use
1247
+ ].items():
1248
+ # convert from `subgraph_m_n` to `subgraph_m` and `n`
1249
+ (
1250
+ subgraph_str,
1251
+ subgraph_idx,
1252
+ subgraph_candidate_idx,
1253
+ ) = subgraph_name_with_idx.split("_")
1254
+ subgraph_name = f"{subgraph_str}_{subgraph_idx}"
1255
+
1256
+ subgraph_results = {
1257
+ "ref_node_name": subgraph_candidate_results[0]["ref_node_name"],
1258
+ "ref_node_target_type": subgraph_candidate_results[0][
1259
+ "ref_node_target_type"
1260
+ ],
1261
+ "fqn": subgraph_candidate_results[0]["fqn"],
1262
+ "values": subgraph_candidate_results[0]["values"],
1263
+ "qconfig_str": subgraph_candidate_results[0]["qconfig_str"],
1264
+ "comparisons": subgraph_candidate_results[0]["comparisons"],
1265
+ "comparison_fn_name": subgraph_candidate_results[0]["comparison_fn_name"],
1266
+ }
1267
+
1268
+ subgraph_name_to_subgraph_results[subgraph_name][subgraph_candidate_idx] = (
1269
+ subgraph_results
1270
+ )
1271
+
1272
+ return dict(subgraph_name_to_subgraph_results)
1273
+
1274
+
1275
+ # TODO(future PR): redesign this to make it easier to consume outputs
1276
+ def create_results_comparison(
1277
+ results_grouped,
1278
+ ) -> Any:
1279
+ """
1280
+ Input:
1281
+
1282
+ {
1283
+ 'subgraph_0': {
1284
+ '0': {
1285
+ 'ref_node_name': '...',
1286
+ 'ref_node_target_type': ...,
1287
+ 'values': [torch.tensor(...), ...],
1288
+ 'qconfig_str': '',
1289
+ 'comparisons': [],
1290
+ 'comparison_fn_name': '',
1291
+ 'fqn': '...',
1292
+ },
1293
+ '1': {
1294
+ 'ref_node_name': '...',
1295
+ 'ref_node_target_type': ...,
1296
+ 'values': [torch.tensor(...), ...],
1297
+ 'qconfig_str': '...',
1298
+ 'comparisons': [torch.tensor(...), ...],
1299
+ 'comparison_fn_name': 'sqnr',
1300
+ 'fqn': '...',
1301
+ },
1302
+ },
1303
+ }
1304
+
1305
+ Output:
1306
+ {
1307
+ 'subgraph_0': {
1308
+ 'ref_node_name': '...',
1309
+ 'ref_node_target_type': '...',
1310
+ 'fqn': '...',
1311
+ 'candidates': {
1312
+ '1': {
1313
+ 'qconfig_str': ...,
1314
+ 'comparison_fn_name': 'sqnr',
1315
+ 'cmp_raw': [..., ...],
1316
+ 'cmp_mean': ...,
1317
+ },
1318
+ ...,
1319
+ },
1320
+ },
1321
+ }
1322
+ """
1323
+
1324
+ results_comparison = {}
1325
+
1326
+ for subgraph_name, subgraph_results in results_grouped.items():
1327
+ candidates = {}
1328
+ for subgraph_inner_name, subgraph_inner_result in subgraph_results.items():
1329
+ # skip comparing baseline to baseline
1330
+ if subgraph_inner_name == "0":
1331
+ continue
1332
+
1333
+ # we expect the comparisons to be precalculated from
1334
+ # calibration, so we just fetch them here
1335
+ cmp_raw = subgraph_inner_result["comparisons"]
1336
+ cmp_raw_tensor = torch.stack(cmp_raw)
1337
+
1338
+ candidates[subgraph_inner_name] = {
1339
+ "qconfig_str": subgraph_inner_result["qconfig_str"],
1340
+ "comparison_fn_name": subgraph_inner_result["comparison_fn_name"],
1341
+ "cmp_raw": cmp_raw_tensor,
1342
+ "cmp_mean": torch.mean(cmp_raw_tensor),
1343
+ }
1344
+
1345
+ results_comparison[subgraph_name] = {
1346
+ "ref_node_name": subgraph_results["0"]["ref_node_name"],
1347
+ "ref_node_target_type": subgraph_results["0"]["ref_node_target_type"],
1348
+ "fqn": subgraph_results["0"]["fqn"],
1349
+ "candidates": candidates,
1350
+ }
1351
+
1352
+ return results_comparison
1353
+
1354
+
1355
+ # TODO(future PR): redesign this to make it easier to consume outputs
1356
+ def print_n_shadows_summary(
1357
+ results_comparison,
1358
+ ) -> None:
1359
+ """
1360
+ Input:
1361
+
1362
+ {
1363
+ 'subgraph_0': {
1364
+ 'ref_node_name': 'linear1',
1365
+ 'ref_node_target_type': '...',
1366
+ 'fqn': '...',
1367
+ 'candidates': {
1368
+ '1': {
1369
+ 'qconfig_str': ...,
1370
+ 'comparison_fn_name': ...,
1371
+ 'cmp_raw': [45.0, 55.0],
1372
+ 'cmp_mean': 50.0,
1373
+ },
1374
+ ...,
1375
+ },
1376
+ },
1377
+ }
1378
+
1379
+ Prints:
1380
+
1381
+ node_name | node_type | fqn | 0 | 1 | ...
1382
+ linear1 | ... | ... | 45.0 | 50.0 | ...
1383
+ """
1384
+
1385
+ try:
1386
+ from tabulate import tabulate
1387
+ except ImportError:
1388
+ print(
1389
+ "`print_tabular` relies on the library `tabulate`, "
1390
+ "which could not be found on this machine. Run `pip "
1391
+ "install tabulate` to install the library."
1392
+ )
1393
+ return
1394
+
1395
+ results = []
1396
+ for subgraph_data in results_comparison.values():
1397
+ mean_all_candidates = [
1398
+ candidate["cmp_mean"]
1399
+ for candidate_name, candidate in subgraph_data["candidates"].items()
1400
+ ]
1401
+
1402
+ data_row = [
1403
+ subgraph_data["ref_node_name"],
1404
+ subgraph_data["ref_node_target_type"],
1405
+ subgraph_data["fqn"],
1406
+ *mean_all_candidates,
1407
+ ]
1408
+ results.append(data_row)
1409
+
1410
+ max_candidate_idx_len = -1
1411
+ for data_row in results:
1412
+ max_candidate_idx_len = max(max_candidate_idx_len, len(data_row[1]))
1413
+ candidate_idx_headers = [str(x) for x in range(max_candidate_idx_len)]
1414
+
1415
+ headers = ["node_name", "node_type", "fqn", *candidate_idx_headers]
1416
+ print(tabulate(results, headers=headers))
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/ns_types.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ from collections.abc import Callable
3
+ from typing import Any, NamedTuple, Union
4
+
5
+ from torch.fx.graph import Node
6
+
7
+
8
+ class NSSingleResultValuesType(str, enum.Enum):
9
+ WEIGHT = "weight"
10
+ NODE_OUTPUT = "node_output"
11
+ NODE_INPUT = "node_input"
12
+
13
+
14
+ class NSSubgraph(NamedTuple):
15
+ start_node: Node
16
+ end_node: Node
17
+ base_op_node: Node
18
+
19
+
20
+ # TODO(future PR): see if we can use typing_extensions's TypedDict instead
21
+ # to properly type the various keys
22
+ # {
23
+ # # one of NSSingleResultValuesType
24
+ # 'type': 'weight',
25
+ # # the values of type specified above
26
+ # 'values': [torch.tensor(...), ...],
27
+ # # name of the node directly before the logger
28
+ # 'prev_node_name': 'linear1',
29
+ # # type of the underlying function or module
30
+ # 'prev_node_target_type': torch.nn.functional.linear # or torch.nn.Linear, etc
31
+ # # name of the node responsible for adding this logger
32
+ # # Note: this may differ from prev_node_name if we are logging inputs
33
+ # 'ref_node_name': 'linear1',
34
+ # # index of this node within the arg of the input/output node
35
+ # # for example, in cat([x1, x2, x3], dim=0), x2 would have index_within_arg == 1
36
+ # 'index_within_arg': 0,
37
+ # # index of this node within the args of the input/output node
38
+ # # for example, in add(x1, x2), x2 would have index_of_arg == 1
39
+ # 'index_of_arg': 0,
40
+ # # precomputed comparisons of logger values to reference values
41
+ # 'comparisons': [torch.tensor(...), ...]
42
+ # # name of function used for precomputed comparisons
43
+ # 'comparison_fn_name': 'sqnr',
44
+ # # string representation of qconfig responsible for creating this logger
45
+ # 'qconfig_str': 'QConfig(...)',
46
+ # }
47
+ NSSingleResultType = dict[str, Any]
48
+
49
+ # {
50
+ # 'layer_name_1': { # subgraph name
51
+ # 'node_output': { # results type (node_output, node_input, weight)
52
+ # 'model_name_a': # model name
53
+ # [NSSingleResultType, ...], # results, ordered by index_within_arg
54
+ # 'model_name_b':
55
+ # [NSSingleResultType, ...],
56
+ # },
57
+ # },
58
+ # }
59
+ #
60
+ NSResultsType = dict[str, dict[str, dict[str, list[NSSingleResultType]]]]
61
+
62
+ # Defines the underlying target type of a node, for example:
63
+ # `F.conv1d` for a `call_function` conv node
64
+ # `nn.Conv1d` for a `call_module` node calling the forward of a `nn.Conv1d` module
65
+ # `'sigmoid'` for a `call_method` node calling `x.sigmoid()`
66
+ NSNodeTargetType = Union[Callable, str]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/pattern_utils.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import Any, Union
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from torch.ao.quantization import FakeQuantizeBase, ObserverBase
8
+ from torch.ao.quantization.backend_config import get_native_backend_config
9
+ from torch.ao.quantization.fx.quantize_handler import _get_pattern_to_quantize_handlers
10
+ from torch.ao.quantization.utils import getattr_from_fqn
11
+ from torch.fx import GraphModule
12
+ from torch.fx.graph import Node
13
+
14
+ from .ns_types import NSNodeTargetType
15
+
16
+
17
+ toq = torch.ops.quantized
18
+
19
+
20
+ def get_type_a_related_to_b(
21
+ base_name_to_sets_of_related_ops: dict[str, set[NSNodeTargetType]],
22
+ ) -> set[tuple[NSNodeTargetType, NSNodeTargetType]]:
23
+ # TODO(future PR): allow customizations
24
+ # TODO(future PR): reuse existing quantization mappings
25
+ # TODO(future PR): add the rest of modules and ops here
26
+ type_a_related_to_b: set[tuple[NSNodeTargetType, NSNodeTargetType]] = set()
27
+
28
+ for s in base_name_to_sets_of_related_ops.values():
29
+ s_list = list(s)
30
+ # add every bidirectional pair
31
+ for idx_0 in range(len(s_list)):
32
+ for idx_1 in range(idx_0, len(s_list)):
33
+ type_a_related_to_b.add((s_list[idx_0], s_list[idx_1]))
34
+ type_a_related_to_b.add((s_list[idx_1], s_list[idx_0]))
35
+
36
+ return type_a_related_to_b
37
+
38
+
39
+ NSFusionElType = Union[
40
+ Callable, # call_function or call_module type, example: F.linear or nn.Conv2d
41
+ str, # call_method name, example: "dequantize"
42
+ tuple[
43
+ str, Any
44
+ ], # call_method name and first argument, example: ("to", torch.float16)
45
+ ]
46
+ NSFusionType = Union[
47
+ tuple[NSFusionElType, NSFusionElType],
48
+ tuple[NSFusionElType, NSFusionElType, NSFusionElType, NSFusionElType],
49
+ ]
50
+
51
+
52
+ def get_reversed_fusions() -> list[tuple[NSFusionType, int]]:
53
+ """
54
+ Set of potential fusions, in reverse order. The order is reversed
55
+ to match how fusion patterns are defined in quantization code.
56
+
57
+ Fusion format:
58
+ ((fusion_op_0, fusion_op_1), base_op_idx)
59
+
60
+ Where base_op_idx is the idx of the op we should use to match other related
61
+ ops. Note: base_op_idx is specified in non-reverse order, i.e. a base_op_idx
62
+ of 0 represents the first op in regular (non-reverse) order, 1 represents the
63
+ second op, etc.
64
+ """
65
+ results: list[tuple[NSFusionType, int]] = []
66
+
67
+ # Possible syntaxes:
68
+ # * single op: torch.nn.Conv2d
69
+ # * multiple ops: (torch.nn.ReLU, torch.nn.Conv2d)
70
+ # For fusions, we only care about patterns composed of multiple ops.
71
+ # TODO(future PR): allow customizations from default patterns.
72
+ all_quant_patterns = _get_pattern_to_quantize_handlers(get_native_backend_config())
73
+
74
+ default_base_op_idx = 0
75
+ for quant_pattern in all_quant_patterns:
76
+ # TODO: this is a temporary hack to flatten the patterns from quantization so
77
+ # that it works with the ns matcher function, maybe we should use `_is_match`
78
+ # in torch.ao.quantization.fx.match_utils to match the patterns
79
+ if (
80
+ isinstance(quant_pattern, tuple)
81
+ and len(quant_pattern) == 2
82
+ and isinstance(quant_pattern[1], tuple)
83
+ and len(quant_pattern[1]) == 2
84
+ ):
85
+ # flatten the pattern with form (nn.ReLU, (nn.BatchNorm2d, nn.Conv2d))
86
+ quant_pattern = (quant_pattern[0], quant_pattern[1][0], quant_pattern[1][1])
87
+
88
+ # Only patterns of multiple ops are fusions, ignore
89
+ # patterns which contain a single ops (they get matched
90
+ # without caring about fusions).
91
+ if isinstance(quant_pattern, tuple):
92
+ results.append((quant_pattern, default_base_op_idx)) # type: ignore[arg-type]
93
+
94
+ # For each pattern, add additional patterns with observers and
95
+ # fake quants at the end.
96
+ # TODO(future PR): if needed, implement matching for a node
97
+ # having multiple output observers.
98
+ for cls in (ObserverBase, FakeQuantizeBase):
99
+ if isinstance(quant_pattern, tuple):
100
+ new_pattern = (cls, *quant_pattern)
101
+ else:
102
+ new_pattern = (cls, quant_pattern)
103
+ results.append((new_pattern, default_base_op_idx)) # type: ignore[arg-type]
104
+
105
+ # After this point, results contains values such as
106
+ # [..., ((torch.nn.Relu, torch.nn.Conv2d), 0), ...]
107
+
108
+ # Patterns for matching fp16 emulation are not specified in the quantization
109
+ # fusion mappings. For now, define them here.
110
+ fp16_em_base_op_idx = 1
111
+ patterns_to_add = [
112
+ # linear-relu fp16 emulation:
113
+ # fp16_to_fp32 -> linear -> relu -> fp32_to_fp16
114
+ (
115
+ (("to", torch.float16), F.relu, F.linear, "dequantize"),
116
+ fp16_em_base_op_idx,
117
+ ),
118
+ # Conv-BN fusion (this happens outside of quantization patterns,
119
+ # which is why it is defined separately here).
120
+ ((nn.BatchNorm1d, nn.Conv1d), default_base_op_idx),
121
+ ((nn.BatchNorm2d, nn.Conv2d), default_base_op_idx),
122
+ ((nn.BatchNorm3d, nn.Conv3d), default_base_op_idx),
123
+ ((nn.ReLU, nn.BatchNorm1d, nn.Conv1d), default_base_op_idx),
124
+ ((nn.ReLU, nn.BatchNorm2d, nn.Conv2d), default_base_op_idx),
125
+ ((nn.ReLU, nn.BatchNorm3d, nn.Conv3d), default_base_op_idx),
126
+ ]
127
+ for p in patterns_to_add:
128
+ results.append(p) # type: ignore[arg-type]
129
+ results.append(((ObserverBase, *p[0]), p[1])) # type: ignore[arg-type]
130
+ results.append(((FakeQuantizeBase, *p[0]), p[1])) # type: ignore[arg-type]
131
+
132
+ return results
133
+
134
+
135
+ def end_node_matches_reversed_fusion(
136
+ end_node: Node,
137
+ reversed_fusion: NSFusionType,
138
+ gm: GraphModule,
139
+ seen_nodes: set[Node],
140
+ ) -> bool:
141
+ """
142
+ Returns true if a pattern ending with `end_node` matches
143
+ the fusion pattern.
144
+ """
145
+ cur_node = end_node
146
+ for fusion_idx in range(len(reversed_fusion)):
147
+ # each node can only belong to one matched pattern
148
+ if cur_node in seen_nodes:
149
+ return False
150
+
151
+ cur_fusion_el = reversed_fusion[fusion_idx]
152
+
153
+ if cur_node.op == "call_function":
154
+ fusion_el_is_fun = (not isinstance(cur_fusion_el, str)) and (
155
+ not isinstance(cur_fusion_el, type)
156
+ )
157
+ if fusion_el_is_fun:
158
+ if cur_node.target != cur_fusion_el:
159
+ return False
160
+ if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
161
+ cur_node = cur_node.args[0]
162
+ else:
163
+ return False
164
+ else:
165
+ return False
166
+
167
+ elif cur_node.op == "call_module":
168
+ fusion_el_is_mod = isinstance(cur_fusion_el, type)
169
+ if fusion_el_is_mod:
170
+ if not isinstance(cur_node.target, str):
171
+ raise AssertionError(f"Expected str, got {type(cur_node.target)}")
172
+ target_mod = getattr_from_fqn(gm, cur_node.target)
173
+ if not isinstance(cur_fusion_el, type):
174
+ return False
175
+ if not isinstance(target_mod, cur_fusion_el):
176
+ return False
177
+ if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
178
+ cur_node = cur_node.args[0]
179
+ else:
180
+ return False
181
+ else:
182
+ return False
183
+
184
+ elif cur_node.op == "call_method":
185
+ fusion_el_is_meth_with_second_arg = (
186
+ isinstance(cur_fusion_el, tuple) and len(cur_fusion_el) == 2
187
+ )
188
+ fusion_el_is_meth_without_args = isinstance(cur_fusion_el, str)
189
+ if fusion_el_is_meth_without_args or fusion_el_is_meth_with_second_arg:
190
+ if fusion_el_is_meth_without_args:
191
+ if cur_node.target != cur_fusion_el:
192
+ return False
193
+ else:
194
+ if not isinstance(cur_fusion_el, tuple):
195
+ raise AssertionError(
196
+ f"Expected tuple, got {type(cur_fusion_el)}"
197
+ )
198
+ if cur_node.target != cur_fusion_el[0]:
199
+ return False
200
+ elif len(cur_node.args) < 2:
201
+ return False
202
+ elif cur_node.args[1] != cur_fusion_el[1]:
203
+ return False
204
+
205
+ if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
206
+ cur_node = cur_node.args[0]
207
+ else:
208
+ return False
209
+ else:
210
+ return False
211
+ else:
212
+ return False
213
+
214
+ return True
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/qconfig_multi_mapping.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ from typing import Any, TYPE_CHECKING
6
+
7
+ import torch
8
+ from torch.ao.quantization import QConfigMapping
9
+ from torch.ao.quantization.qconfig_mapping import _QCONFIG_STYLE_ORDER
10
+
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Callable
14
+
15
+ from torch.ao.quantization.qconfig import QConfigAny
16
+
17
+ __all__ = ["QConfigMultiMapping"]
18
+
19
+ _QCONFIG_STYLE_TO_METHOD: dict[str, str] = {
20
+ "global_qconfig": "set_global",
21
+ "object_type_qconfigs": "set_object_type",
22
+ "module_name_regex_qconfigs": "set_module_name_regex",
23
+ "module_name_qconfigs": "set_module_name",
24
+ "module_name_object_type_order_qconfigs": "set_module_name_object_type_order",
25
+ }
26
+
27
+
28
+ def _remove_duplicates_and_none(qconfig_list: list[QConfigAny]) -> None:
29
+ to_remove = []
30
+ for index, cur_qconfig in enumerate(qconfig_list):
31
+ if cur_qconfig is None:
32
+ to_remove.append(index)
33
+ break
34
+ for checked_qconfig in qconfig_list[:index]:
35
+ if torch.ao.quantization.qconfig_equals(cur_qconfig, checked_qconfig):
36
+ to_remove.append(index)
37
+ break
38
+ for index in to_remove[::-1]:
39
+ qconfig_list.pop(index)
40
+
41
+
42
+ class QConfigMultiMapping:
43
+ """
44
+ This class, used with the prepare_n_shadows_model API, stores a list of :class:`torch.ao.quantization.QConfigMapping`s
45
+ so that multiple QConfigs can be specified for each QConfig matching style.
46
+
47
+ The user can specify QConfigs using the following methods (in increasing match priority):
48
+
49
+ ``set_global`` : sets the global (default) QConfigs
50
+
51
+ ``set_object_type`` : sets the QConfigs for a given module type, function, or method name
52
+
53
+ ``set_module_name_regex`` : sets the QConfigs for modules matching the given regex string
54
+
55
+ ``set_module_name`` : sets the QConfigs for modules matching the given module name
56
+
57
+ ``set_module_name_object_type_order`` : sets the QConfigs for modules matching a combination
58
+ of the given module name, object type, and the index at which the module appears
59
+
60
+ Note: Usage of set methods is the same as in QConfigMapping except with a passed in list of QConfigs rather than a
61
+ single QConfig.
62
+
63
+ Example usage::
64
+
65
+ qconfig_mapping = QConfigMultiMapping()
66
+ .set_global([qconfig1, qconfig2])
67
+ .set_object_type(torch.nn.Linear, [qconfig2, qconfig3])
68
+ .set_object_type(torch.nn.ReLU, [qconfig1])
69
+ .set_module_name_regex("foo.*bar.*conv[0-9]+", [qconfig2])
70
+ .set_module_name_regex("foo.*", [qconfig1, qconfig2, qconfig3])
71
+ .set_module_name("module1", [None])
72
+ .set_module_name("module2", [qconfig2])
73
+ .set_module_name_object_type_order("foo.bar", torch.nn.functional.linear, 0, [qconfig3])
74
+
75
+ """
76
+
77
+ def __init__(self) -> None:
78
+ # initialize this with 1 QConfigMapping to avoid corner cases
79
+ self.qconfig_mappings_list: list[QConfigMapping] = [QConfigMapping()]
80
+
81
+ def _handle_list_size_mismatch(
82
+ self, qconfig_list: list[QConfigAny], style: str
83
+ ) -> None:
84
+ # this method handles cases where the size of qconfig_list does not match
85
+ # the size of qconfig_mappings_list.
86
+ # Issue: Consider a user inserting global_qconfig A and B first, then inserting
87
+ # qconfig C as an object_type_qconfig for conv ops. If we internally store
88
+ # 1 QConfigMapping with A and C and another with just B, then the
89
+ # second QConfigMapping will match B to conv ops (which is not wanted), since B is global.
90
+
91
+ # we avoid this by maintaining the invariant that if any QConfigMapping
92
+ # has a qconfig style+key with a qconfig in it, all QConfigMappings must
93
+ # have either a qconfig or None for that same style+key. In the above
94
+ # example, a None qconfig would prevent the unwanted match in the
95
+ # second QConfigMapping
96
+
97
+ if len(qconfig_list) > len(self.qconfig_mappings_list):
98
+ # Case: we have more qconfigs (in qconfig_list) than QConfigMappings
99
+
100
+ # Add new QConfigMappings (initialized so we maintain the `invariant`)
101
+
102
+ new_qconfig_mapping = QConfigMapping()
103
+ # searches other QConfigMappings for qconfig style+keys
104
+ # that need to be inserted as `None` into the new QConfigMapping
105
+ for qconfig_mapping in self.qconfig_mappings_list:
106
+ # global_qconfig has None by default
107
+ for check_style in _QCONFIG_STYLE_ORDER[1:]:
108
+ qconfigs_dict = getattr(qconfig_mapping, check_style)
109
+ target_qconfigs_dict = getattr(new_qconfig_mapping, check_style)
110
+ for key in qconfigs_dict:
111
+ target_qconfigs_dict[key] = None
112
+ break
113
+
114
+ # insert copies of this new QConfigMapping until all entries
115
+ # in qconfig_list can fit among the QConfigMappings
116
+ while len(qconfig_list) > len(self.qconfig_mappings_list):
117
+ self.qconfig_mappings_list.append(copy.deepcopy(new_qconfig_mapping))
118
+ else:
119
+ # Case: we have fewer qconfigs in qconfig_list than QConfigMappings
120
+
121
+ # pad qconfig_list with `None` until length is same
122
+ while len(qconfig_list) < len(self.qconfig_mappings_list):
123
+ qconfig_list.append(None)
124
+
125
+ # this function applies the insertion method across each QConfigMapping
126
+ def _insert_qconfig_list(
127
+ self,
128
+ style: str,
129
+ args: list[str | int | Callable],
130
+ qconfig_list: list[QConfigAny],
131
+ ) -> None:
132
+ # we remove duplicates and None to make the ordering of qconfigs
133
+ # deterministic upon insertion.
134
+ _remove_duplicates_and_none(qconfig_list)
135
+
136
+ self._handle_list_size_mismatch(qconfig_list, style)
137
+ method_name = _QCONFIG_STYLE_TO_METHOD[style]
138
+ for qconfig_mapping, qconfig in zip(self.qconfig_mappings_list, qconfig_list):
139
+ # uses QConfigMapping set method to insert qconfig
140
+ set_method = getattr(qconfig_mapping, method_name)
141
+ set_method(*args, qconfig)
142
+
143
+ def set_global(self, global_qconfig_list: list[QConfigAny]) -> QConfigMultiMapping:
144
+ """
145
+ Set global QConfigs
146
+ see :func:`~torch.ao.quantization.QConfigMapping.set_global()` for more info
147
+ """
148
+ self._insert_qconfig_list("global_qconfig", [], global_qconfig_list)
149
+ return self
150
+
151
+ def set_object_type(
152
+ self, object_type: Callable | str, qconfig_list: list[QConfigAny]
153
+ ) -> QConfigMultiMapping:
154
+ """
155
+ Set object type QConfigs
156
+ see :func:`~torch.ao.quantization.QConfigMapping.set_object_type()` for more info
157
+ """
158
+ self._insert_qconfig_list("object_type_qconfigs", [object_type], qconfig_list)
159
+ return self
160
+
161
+ def set_module_name_regex(
162
+ self, module_name_regex: str, qconfig_list: list[QConfigAny]
163
+ ) -> QConfigMultiMapping:
164
+ """
165
+ Set module_name_regex QConfigs
166
+ see :func:`~torch.ao.quantization.QConfigMapping.set_module_name_regex()` for more info
167
+ """
168
+ self._insert_qconfig_list(
169
+ "module_name_regex_qconfigs", [module_name_regex], qconfig_list
170
+ )
171
+ return self
172
+
173
+ def set_module_name(
174
+ self, module_name: str, qconfig_list: list[QConfigAny]
175
+ ) -> QConfigMultiMapping:
176
+ """
177
+ Set module_name QConfigs
178
+ see :func:`~torch.ao.quantization.QConfigMapping.set_module_name()` for more info
179
+ """
180
+ self._insert_qconfig_list("module_name_qconfigs", [module_name], qconfig_list)
181
+ return self
182
+
183
+ def set_module_name_object_type_order(
184
+ self,
185
+ module_name: str,
186
+ object_type: Callable,
187
+ index: int,
188
+ qconfig_list: list[QConfigAny],
189
+ ) -> QConfigMultiMapping:
190
+ """
191
+ Set module_name QConfigs
192
+ see :func:`~torch.ao.quantization.QConfigMapping.set_module_name_object_type_order()` for more info
193
+ """
194
+ self._insert_qconfig_list(
195
+ "module_name_object_type_order_qconfigs",
196
+ [module_name, object_type, index],
197
+ qconfig_list,
198
+ )
199
+ return self
200
+
201
+ def __repr__(self):
202
+ return (
203
+ self.__class__.__name__
204
+ + " ["
205
+ + "".join(
206
+ f"\n{qconfig_mapping.__repr__()},"
207
+ for qconfig_mapping in self.qconfig_mappings_list
208
+ )
209
+ + "\n]"
210
+ )
211
+
212
+ @classmethod
213
+ def from_list_qconfig_mapping(
214
+ cls, qconfig_mapping_list: list[QConfigMapping]
215
+ ) -> QConfigMultiMapping:
216
+ """
217
+ Creates a QConfigMultiMapping from a list of QConfigMappings
218
+ """
219
+ new_qconfig_multi_mapping = cls()
220
+
221
+ new_qconfig_multi_mapping.qconfig_mappings_list = copy.deepcopy(
222
+ qconfig_mapping_list
223
+ )
224
+
225
+ # we need to avoid the issue described in _handle_list_size_mismatch,
226
+ # so we reinsert all the qconfigs using the QConfigMultiMapping
227
+ # set methods
228
+
229
+ # go through all qconfig styles
230
+ # note: global can be ignored since it is None by default
231
+ for style in _QCONFIG_STYLE_ORDER[1:]:
232
+ # gather all key+qconfigs for current style
233
+ # into qconfig_dict_list
234
+ qconfig_dict_list: dict[Any, list[QConfigAny]] = {}
235
+ for qconfig_mapping in qconfig_mapping_list:
236
+ qconfig_dict = getattr(qconfig_mapping, style)
237
+ for key, qconfig in qconfig_dict.items():
238
+ if key not in qconfig_dict_list:
239
+ qconfig_dict_list[key] = []
240
+ qconfig_dict_list[key].append(qconfig)
241
+
242
+ # reinsert all gathered key+qconfigs
243
+ set_method_name = _QCONFIG_STYLE_TO_METHOD[style]
244
+ set_method = getattr(new_qconfig_multi_mapping, set_method_name)
245
+ for key, qconfig_list in qconfig_dict_list.items():
246
+ if isinstance(key, tuple):
247
+ set_method(*key, qconfig_list)
248
+ else:
249
+ set_method(key, qconfig_list)
250
+
251
+ return new_qconfig_multi_mapping
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/utils.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import enum
4
+ import operator
5
+ from collections.abc import Callable
6
+
7
+ import torch
8
+ import torch.ao.nn.intrinsic.quantized as nniq
9
+ import torch.ao.nn.quantized as nnq
10
+ import torch.nn as nn
11
+ from torch.ao.quantization import FakeQuantizeBase, ObserverBase
12
+ from torch.ao.quantization.observer import _is_activation_post_process
13
+ from torch.ao.quantization.utils import getattr_from_fqn
14
+ from torch.fx import GraphModule
15
+ from torch.fx.graph import Node
16
+
17
+ from .ns_types import NSNodeTargetType, NSResultsType
18
+
19
+
20
+ toq = torch.ops.quantized
21
+
22
+
23
+ # TODO(future PR): consider deleting this enum and using the torch types
24
+ # directly. This might be tricky because it is not a one to one mapping.
25
+ class NodeInputOrOutputType(enum.Enum):
26
+ FP32 = enum.auto() # torch.float
27
+ INT8 = enum.auto() # torch.qint8 or torch.quint8
28
+ FP16 = enum.auto() # torch.float16
29
+ UNKNOWN = enum.auto() # we cannot determine input/output dtype
30
+ # TODO(future PR): while these functions can support multiple dtypes,
31
+ # for the purposes of numerical debugging we want to get the actual
32
+ # dtype used in the model. We will likely need some kind of dtype
33
+ # propagation to estimate this.
34
+ FP32_OR_INT8 = enum.auto() # either torch.float or torch.quint8 or torch.qint8
35
+ # TODO(future PRs): dynamic quant, fake quant, etc
36
+
37
+
38
+ def get_node_first_input_and_output_type(
39
+ node: Node,
40
+ gm: GraphModule,
41
+ logger_cls: Callable,
42
+ node_type_to_io_type_map: dict[str, set[NSNodeTargetType]],
43
+ ) -> tuple[NodeInputOrOutputType, NodeInputOrOutputType]:
44
+ # TODO(future PR): clean this up
45
+ FUNS_IO_TYPE_FP32 = node_type_to_io_type_map["funs_io_type_fp32"]
46
+ FUNS_IO_TYPE_FP16 = node_type_to_io_type_map["funs_io_type_fp16"]
47
+ FUNS_IO_TYPE_INT8 = node_type_to_io_type_map["funs_io_type_int8"]
48
+ FUNS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["funs_io_type_fp32_or_int8"]
49
+ MODS_IO_TYPE_FP32 = node_type_to_io_type_map["mods_io_type_fp32"]
50
+ MODS_IO_TYPE_INT8 = node_type_to_io_type_map["mods_io_type_int8"]
51
+ MODS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["mods_io_type_fp32_or_int8"]
52
+ METHS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["meths_io_type_fp32_or_int8"]
53
+
54
+ if node.op == "call_function":
55
+ if node.target in FUNS_IO_TYPE_FP32:
56
+ return (NodeInputOrOutputType.FP32, NodeInputOrOutputType.FP32)
57
+ if node.target in FUNS_IO_TYPE_FP16:
58
+ return (NodeInputOrOutputType.FP16, NodeInputOrOutputType.FP16)
59
+ elif node.target in FUNS_IO_TYPE_INT8:
60
+ return (NodeInputOrOutputType.INT8, NodeInputOrOutputType.INT8)
61
+ elif node.target in FUNS_IO_TYPE_FP32_OR_INT8:
62
+ first_arg = get_normalized_nth_input(node, gm, 0)
63
+ if not isinstance(first_arg, Node):
64
+ raise AssertionError(f"Expected Node, got {type(first_arg)}")
65
+ (
66
+ _prev_node_input_type,
67
+ prev_node_output_type,
68
+ ) = get_node_first_input_and_output_type(
69
+ first_arg, gm, logger_cls, node_type_to_io_type_map
70
+ )
71
+ return (prev_node_output_type, prev_node_output_type)
72
+ else:
73
+ return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
74
+
75
+ elif node.op == "call_module":
76
+ if node.op != "call_module":
77
+ raise AssertionError(f"Expected call_module, got '{node.op}'")
78
+ if not isinstance(node.target, str):
79
+ raise AssertionError(f"Expected str, but got {type(node.target)}")
80
+
81
+ mod = getattr_from_fqn(gm, node.target)
82
+ is_known_fp32_or_int8_input_module = any(
83
+ isinstance(mod, target_type) # type: ignore[arg-type]
84
+ for target_type in MODS_IO_TYPE_FP32_OR_INT8
85
+ )
86
+ if (
87
+ isinstance(mod, (logger_cls, ObserverBase, FakeQuantizeBase)) # type: ignore[arg-type]
88
+ or is_known_fp32_or_int8_input_module
89
+ ):
90
+ # A logger or observer's input and output type is the output
91
+ # type of the preceding node.
92
+ first_arg = get_normalized_nth_input(node, gm, 0)
93
+ if not isinstance(first_arg, Node):
94
+ raise AssertionError(f"Expected Node, got {type(first_arg)}")
95
+ (
96
+ _prev_node_input_type,
97
+ prev_node_output_type,
98
+ ) = get_node_first_input_and_output_type(
99
+ first_arg, gm, logger_cls, node_type_to_io_type_map
100
+ )
101
+ return (prev_node_output_type, prev_node_output_type)
102
+ is_known_fp32_input_module = any(
103
+ isinstance(mod, target_type) # type: ignore[arg-type]
104
+ for target_type in MODS_IO_TYPE_FP32
105
+ )
106
+ is_known_int8_input_module = any(
107
+ isinstance(mod, target_type) # type: ignore[arg-type]
108
+ for target_type in MODS_IO_TYPE_INT8
109
+ )
110
+ if is_known_fp32_input_module:
111
+ return (NodeInputOrOutputType.FP32, NodeInputOrOutputType.FP32)
112
+ elif is_known_int8_input_module:
113
+ return (NodeInputOrOutputType.INT8, NodeInputOrOutputType.INT8)
114
+ else:
115
+ return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
116
+
117
+ elif node.op == "call_method":
118
+ if node.target == "dequantize":
119
+ # Dequantize is a special node because it allows multiple input types.
120
+ # So, we look up the output type of the previous node and return that
121
+ # as the input type of this node instance.
122
+ prev_node = get_normalized_nth_input(node, gm, 0)
123
+ if not isinstance(prev_node, Node):
124
+ raise AssertionError(f"Expected Node, got {type(prev_node)}")
125
+ (
126
+ _prev_node_input_type,
127
+ prev_node_output_type,
128
+ ) = get_node_first_input_and_output_type(
129
+ prev_node, gm, logger_cls, node_type_to_io_type_map
130
+ )
131
+ return (prev_node_output_type, NodeInputOrOutputType.FP32)
132
+
133
+ elif node.target == "to":
134
+ # to is a special node because it allows multiple input types.
135
+ # So, we look up the output type of the previous node and return that
136
+ # as the input type of this node instance. We also look up the target
137
+ # of to and return the correct output type.
138
+ prev_node = get_normalized_nth_input(node, gm, 0)
139
+ if not isinstance(prev_node, Node):
140
+ raise AssertionError(f"Expected Node, got {type(prev_node)}")
141
+ (
142
+ _prev_node_input_type,
143
+ prev_node_output_type,
144
+ ) = get_node_first_input_and_output_type(
145
+ prev_node, gm, logger_cls, node_type_to_io_type_map
146
+ )
147
+
148
+ cur_node_dtype_target = get_normalized_nth_input(node, gm, 1)
149
+ if cur_node_dtype_target is not torch.float16:
150
+ raise AssertionError(
151
+ f"{cur_node_dtype_target} handling needs to be added"
152
+ )
153
+
154
+ return (prev_node_output_type, NodeInputOrOutputType.FP16)
155
+
156
+ elif node.target in METHS_IO_TYPE_FP32_OR_INT8:
157
+ first_arg = get_normalized_nth_input(node, gm, 0)
158
+ if not isinstance(first_arg, Node):
159
+ raise AssertionError(f"Expected Node, got {type(first_arg)}")
160
+ (
161
+ _prev_node_input_type,
162
+ prev_node_output_type,
163
+ ) = get_node_first_input_and_output_type(
164
+ first_arg, gm, logger_cls, node_type_to_io_type_map
165
+ )
166
+ return (prev_node_output_type, prev_node_output_type)
167
+
168
+ return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
169
+ else:
170
+ return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
171
+
172
+
173
+ def get_node_input_qparams(
174
+ node: Node,
175
+ gm: GraphModule,
176
+ node_type_to_io_type_map: dict[str, set[NSNodeTargetType]],
177
+ ) -> tuple[torch.Tensor | float, torch.Tensor | int] | None:
178
+ """
179
+ Returns the qparams (scale, zero_point) of the first input to `node`,
180
+ if they can be inferred from the graph.
181
+ """
182
+ prev_node = get_normalized_nth_input(node, gm, 0)
183
+
184
+ if not isinstance(prev_node, Node):
185
+ return None
186
+
187
+ MODS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["mods_io_type_fp32_or_int8"]
188
+
189
+ def _get_scale_zp_from_function_args(node, gm, scale_arg_idx, zp_arg_idx):
190
+ scale_node = get_normalized_nth_input(node, gm, scale_arg_idx)
191
+ zp_node = get_normalized_nth_input(node, gm, zp_arg_idx)
192
+ if not isinstance(scale_node, Node):
193
+ raise AssertionError(f"Expected Node, got {type(scale_node)}")
194
+ if not isinstance(scale_node.target, str):
195
+ raise AssertionError(f"Expected str, got {type(scale_node.target)}")
196
+ if not isinstance(zp_node, Node):
197
+ raise AssertionError(f"Expected Node, got {type(zp_node)}")
198
+ if not isinstance(zp_node.target, str):
199
+ raise AssertionError(f"Expected str, got {type(zp_node.target)}")
200
+ scale_obj = getattr_from_fqn(gm, scale_node.target)
201
+ zp_obj = getattr_from_fqn(gm, zp_node.target)
202
+ return (scale_obj, zp_obj)
203
+
204
+ if prev_node.op == "call_function":
205
+ # quantize - read the args directly
206
+ if prev_node.target is torch.quantize_per_tensor:
207
+ return _get_scale_zp_from_function_args(prev_node, gm, 1, 2)
208
+ elif prev_node.target in (toq.add, toq.add_relu, toq.mul, toq.mul_relu):
209
+ return _get_scale_zp_from_function_args(prev_node, gm, 2, 3)
210
+
211
+ return None
212
+ # TODO(future PR): handle more functionals
213
+ # TODO(future PR): handle functional ops which inherit qparams from input
214
+
215
+ elif prev_node.op == "call_module":
216
+ # get type of the module
217
+ if not isinstance(prev_node.target, str):
218
+ raise AssertionError(f"Expected str, got {type(prev_node.target)}")
219
+ module_obj = getattr_from_fqn(gm, prev_node.target)
220
+ if isinstance(
221
+ module_obj,
222
+ (
223
+ nnq.Linear,
224
+ nnq.Conv1d,
225
+ nnq.Conv2d,
226
+ nniq.ConvReLU2d,
227
+ nnq.Conv3d,
228
+ nnq.BatchNorm2d,
229
+ nnq.BatchNorm3d,
230
+ nnq.ConvTranspose1d,
231
+ nnq.ConvTranspose2d,
232
+ nnq.ELU,
233
+ nnq.GroupNorm,
234
+ nnq.InstanceNorm1d,
235
+ nnq.InstanceNorm2d,
236
+ nnq.InstanceNorm3d,
237
+ nnq.LayerNorm,
238
+ nnq.Hardswish,
239
+ nnq.LeakyReLU,
240
+ nnq.ReLU6,
241
+ nniq.BNReLU2d,
242
+ nniq.BNReLU3d,
243
+ nniq.ConvReLU1d,
244
+ nniq.ConvReLU2d,
245
+ nniq.ConvReLU3d,
246
+ nniq.LinearReLU,
247
+ ),
248
+ ):
249
+ return (module_obj.scale, module_obj.zero_point) # type: ignore[return-value]
250
+
251
+ is_known_fp32_or_int8_input_module = any(
252
+ isinstance(module_obj, target_type) # type: ignore[arg-type]
253
+ for target_type in MODS_IO_TYPE_FP32_OR_INT8
254
+ )
255
+ if is_known_fp32_or_int8_input_module:
256
+ return get_node_input_qparams(prev_node, gm, node_type_to_io_type_map)
257
+
258
+ return None
259
+
260
+
261
+ def return_first_non_observer_node(
262
+ node: Node,
263
+ gm: GraphModule,
264
+ ) -> Node:
265
+ """
266
+ If node is not an observer, returns it. If node is an observer,
267
+ navigates up the graph and returns the first parent which is not an
268
+ observer. For example,
269
+
270
+ graph: (node_non_obs), node = node_non_obs : returns node_non_obs
271
+ graph: (node_non_obs -> obs0), node = obs0 : returns node_non_obs
272
+ graph: (node_non_obs -> obs0 -> fq0), node = fq0 : returns node_non_obs
273
+ """
274
+ if node.op == "call_module":
275
+ node_obj = getattr_from_fqn(gm, node.target) # type: ignore[arg-type]
276
+ if _is_activation_post_process(node_obj):
277
+ if len(node.args) != 1:
278
+ raise AssertionError(
279
+ f"Expected node.args to have length 1, got {len(node.args)}"
280
+ )
281
+ if not isinstance(node.args[0], Node):
282
+ raise AssertionError(f"Expected Node, got {type(node.args[0])}")
283
+ node = node.args[0]
284
+ # code duplication intended, not worth refactoring
285
+ if not isinstance(node.target, str):
286
+ raise AssertionError(f"Expected str, got {type(node.target)}")
287
+ node_obj = getattr_from_fqn(gm, node.target)
288
+ if _is_activation_post_process(node_obj):
289
+ if len(node.args) != 1:
290
+ raise AssertionError(
291
+ f"Expected node.args to have length 1, got {len(node.args)}"
292
+ )
293
+ if not isinstance(node.args[0], Node):
294
+ raise AssertionError(f"Expected Node, got {type(node.args[0])}")
295
+ node = node.args[0]
296
+ return node
297
+
298
+
299
+ def get_number_of_non_param_args(
300
+ node: Node,
301
+ gm: GraphModule,
302
+ ) -> int:
303
+ """
304
+ Assumes that all non-param args occur first. Returns the number of
305
+ non-param args expected for a node. For example, for
306
+
307
+ F.linear(x, weight, bias)
308
+
309
+ Returns 1, because x is a non-param arg and weight and bias are params.
310
+ For
311
+
312
+ lstm_mod(x, hid)
313
+
314
+ Returns 2, because both x and hid are non-param args.
315
+ """
316
+ if node.op == "call_module":
317
+ node_obj = getattr_from_fqn(gm, node.target) # type: ignore[arg-type]
318
+ if isinstance(node_obj, nn.LSTM):
319
+ return 2
320
+
321
+ # default is 1
322
+ return 1
323
+
324
+
325
+ def get_arg_indices_of_inputs_to_log(node: Node) -> list[int]:
326
+ """
327
+ Returns the indices of args of the node which we should attach
328
+ loggers to, if input logging is enabled.
329
+
330
+ For example,
331
+ * for (x + y), returns [0, 1]
332
+ * for (1 + y), returns [1]
333
+ * for (x + 1), returns [0]
334
+ * for (linear(x, w, b)) returns [0]
335
+ * by default, returns [0]
336
+ """
337
+ if len(node.args) == 0:
338
+ return []
339
+ if node.op == "call_function" and (
340
+ # TODO(future PR): use relationship map instead of hardcoding
341
+ node.target in (torch.add, torch.ops.quantized.add, operator.add)
342
+ or node.target in (torch.mul, torch.ops.quantized.mul, operator.mul)
343
+ ):
344
+ result = [i for i in range(2) if type(node.args[i]) is Node]
345
+ return result
346
+ return [0]
347
+
348
+
349
+ def get_target_type_str(node: Node, gm: GraphModule) -> str:
350
+ """
351
+ Returns a string representation of the type of the function or module
352
+ pointed to by this node, or '' for other node types.
353
+ """
354
+ target_type = ""
355
+ if node.op in ("call_function", "call_method"):
356
+ target_type = torch.typename(node.target)
357
+ elif node.op == "call_module":
358
+ if not isinstance(node.target, str):
359
+ raise AssertionError(f"Expected str, got {type(node.target)}")
360
+ target_mod = getattr_from_fqn(gm, node.target)
361
+ target_type = torch.typename(target_mod)
362
+ return target_type
363
+
364
+
365
+ def rekey_logger_info_on_node_name_of_model(
366
+ results: NSResultsType,
367
+ model_name: str,
368
+ ) -> NSResultsType:
369
+ """
370
+ Rekeys the layer name of a results dictionary to use node names
371
+ from `model_name`.
372
+
373
+ For example, transforms
374
+
375
+ {'base_op_1_0': {'node_output': {'model_a':
376
+ [{'ref_node_name': 'linear1', ...}]}}}
377
+
378
+ into
379
+
380
+ {'linear1': {'node_output': {'model_a':
381
+ [{'ref_node_name': 'linear1', ...}]}}}
382
+
383
+ Note: we cannot use these node names directly because they are not
384
+ guaranteed to be consistent across models. This is why we extract
385
+ the results first and rekey afterwards.
386
+ """
387
+ new_results = {}
388
+ for old_layer_name, result_type_to_results in results.items():
389
+ new_layer_name = None
390
+ for model_name_to_results in result_type_to_results.values():
391
+ for cur_model_name, list_of_results in model_name_to_results.items():
392
+ if cur_model_name == model_name:
393
+ if len(list_of_results) == 0:
394
+ raise AssertionError("Expected list_of_results to be not empty")
395
+ new_layer_name = list_of_results[0]["ref_node_name"]
396
+ else:
397
+ continue
398
+ if new_layer_name is not None:
399
+ new_results[new_layer_name] = result_type_to_results
400
+ else:
401
+ new_results[old_layer_name] = result_type_to_results
402
+ return new_results
403
+
404
+
405
+ def maybe_add_missing_fqns(results: NSResultsType) -> None:
406
+ """
407
+ If `fqn` entries are filled in for one of the models in `results`, copies
408
+ them over to any models which do not have them filled out.
409
+
410
+ A common use case benefitting from this is comparing a model prepared by
411
+ quantization to a quantized model. In this case, the model prepared by
412
+ quantization would have `fqn` entries, and the quantized model would not.
413
+ """
414
+
415
+ # Check in the first result to find any model with fqn entries defined.
416
+ model_name_with_fqns = None
417
+ for result_type_to_results in results.values():
418
+ for model_name_to_results in result_type_to_results.values():
419
+ for model_name, model_results in model_name_to_results.items():
420
+ if len(model_results) > 0:
421
+ if model_results[0]["fqn"] is not None:
422
+ model_name_with_fqns = model_name
423
+ break
424
+ break
425
+ break
426
+
427
+ if model_name_with_fqns:
428
+ for result_type_to_results in results.values():
429
+ for model_name_to_results in result_type_to_results.values():
430
+ ref_model_results = model_name_to_results[model_name_with_fqns]
431
+ for model_name, model_results in model_name_to_results.items():
432
+ if model_name == model_name_with_fqns:
433
+ continue
434
+
435
+ for i in range(len(model_results)):
436
+ fqn = ref_model_results[i]["fqn"]
437
+ model_results[i]["fqn"] = fqn
438
+
439
+
440
+ def maybe_dequantize_first_two_tensor_args_and_handle_tuples(f):
441
+ def inner(*args, **kwargs):
442
+ a0, a1, *a_other = args
443
+
444
+ if (isinstance(a0, tuple) and isinstance(a1, tuple)) or (
445
+ isinstance(a0, list) and isinstance(a1, list)
446
+ ):
447
+ results = []
448
+ for el0, el1 in zip(a0, a1):
449
+ new_args = (el0, el1, *a_other)
450
+ results.append(inner(*new_args, **kwargs))
451
+ return results
452
+
453
+ elif isinstance(a0, torch.Tensor) and isinstance(a1, torch.Tensor):
454
+ if a0.is_quantized:
455
+ a0 = a0.dequantize()
456
+ if a1.is_quantized:
457
+ a1 = a1.dequantize()
458
+
459
+ # for the purposes of this util, only handle floats
460
+ if a0.dtype != torch.float or a1.dtype != torch.float:
461
+ return None
462
+
463
+ new_args = (a0, a1, *a_other)
464
+ return f(*new_args, **kwargs)
465
+
466
+ return inner
467
+
468
+
469
+ @maybe_dequantize_first_two_tensor_args_and_handle_tuples
470
+ def compute_sqnr(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
471
+ """
472
+ Computes the SQNR between `x` and `y`.
473
+
474
+ Args:
475
+ x: Tensor or tuple of tensors
476
+ y: Tensor or tuple of tensors
477
+
478
+ Return:
479
+ float or tuple of floats
480
+ """
481
+ Ps = torch.norm(x)
482
+ Pn = torch.norm(x - y)
483
+ return 20 * torch.log10(Ps / Pn)
484
+
485
+
486
+ @maybe_dequantize_first_two_tensor_args_and_handle_tuples
487
+ def compute_normalized_l2_error(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
488
+ """
489
+ Computes the normalized L2 error between `x` and `y`.
490
+
491
+ Args:
492
+ x: Tensor or tuple of tensors
493
+ y: Tensor or tuple of tensors
494
+
495
+ Return:
496
+ float or tuple of floats
497
+ """
498
+ # pyrefly: ignore [unsupported-operation]
499
+ return torch.sqrt(((x - y) ** 2).sum() / (x**2).sum())
500
+
501
+
502
+ @maybe_dequantize_first_two_tensor_args_and_handle_tuples
503
+ def compute_cosine_similarity(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
504
+ """
505
+ Computes the cosine similarity between `x` and `y`.
506
+
507
+ Args:
508
+ x: Tensor or tuple of tensors
509
+ y: Tensor or tuple of tensors
510
+
511
+ Return:
512
+ float or tuple of floats
513
+ """
514
+ # For convolutions, the shape of the quantized weight has one additional
515
+ # dimension compared to the shape of the fp32 weight. Match the shapes
516
+ # to enable cosine similarity comparison.
517
+ x = x.reshape(1, -1)
518
+ y = y.reshape(1, -1)
519
+ return torch.nn.functional.cosine_similarity(x, y)
520
+
521
+
522
+ def op_type_supports_shadowing(node: Node) -> bool:
523
+ if node.op == "call_function":
524
+ if node.target in (
525
+ torch.add,
526
+ torch.mul,
527
+ operator.add,
528
+ operator.mul,
529
+ torch.cat,
530
+ torch.stack,
531
+ ):
532
+ # shadowing for ops with multiple tensor inputs is not implemented yet
533
+ return False
534
+ return True
535
+
536
+
537
+ def get_normalized_nth_input(node: Node, gm: GraphModule, idx: int) -> Node:
538
+ """
539
+ Given a node, gets the n'th input to that node, normalizing
540
+ args and kwargs to the best of its ability.
541
+ """
542
+ try:
543
+ norm_args_and_kwargs = node.normalized_arguments(
544
+ gm, normalize_to_only_use_kwargs=True
545
+ )
546
+ if norm_args_and_kwargs is not None:
547
+ norm_args, norm_kwargs = norm_args_and_kwargs
548
+ if len(norm_args) + len(norm_kwargs) <= idx:
549
+ raise AssertionError(
550
+ f"Index {idx} out of range: total = {len(norm_args) + len(norm_kwargs)}"
551
+ )
552
+ if idx < len(norm_args):
553
+ return norm_args[idx]
554
+ else:
555
+ # note: in Python 3.7+ dicts are ordered
556
+ return list(norm_kwargs.values())[idx]
557
+ else:
558
+ if len(node.args) + len(node.kwargs) <= idx:
559
+ raise AssertionError(
560
+ f"Index {idx} out of range: total = {len(node.args) + len(node.kwargs)}"
561
+ )
562
+ if idx < len(node.args):
563
+ return node.args[idx] # type: ignore[return-value]
564
+ else:
565
+ kwargs_idx = idx + len(node.args)
566
+ return list(node.kwargs.values())[kwargs_idx] # type: ignore[return-value]
567
+ except RuntimeError:
568
+ # this RuntimeError happens when node argument normalization
569
+ # requires typehints to proceed, such as for torch.add where
570
+ # either the first, second or both arguments could be tensors
571
+ if len(node.args) + len(node.kwargs) <= idx:
572
+ raise AssertionError(
573
+ f"Index {idx} out of range: total = {len(node.args) + len(node.kwargs)}"
574
+ ) from None
575
+ if idx < len(node.args):
576
+ return node.args[idx] # type: ignore[return-value]
577
+ else:
578
+ kwargs_idx = idx + len(node.args)
579
+ return list(node.kwargs.values())[kwargs_idx] # type: ignore[return-value]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/ns/fx/weight_utils.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+
3
+ import torch
4
+ import torch.ao.nn.intrinsic as nni
5
+ import torch.ao.nn.intrinsic.qat as nniqat
6
+ import torch.ao.nn.intrinsic.quantized as nniq
7
+ import torch.ao.nn.qat as nnqat
8
+ import torch.ao.nn.quantized as nnq
9
+ import torch.ao.nn.quantized.dynamic as nnqd
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from torch.fx import GraphModule
13
+ from torch.fx.graph import Node
14
+
15
+ from .ns_types import NSSingleResultType, NSSingleResultValuesType
16
+ from .utils import get_target_type_str, getattr_from_fqn, return_first_non_observer_node
17
+
18
+
19
+ toq = torch.ops.quantized
20
+
21
+
22
+ def mod_weight_detach(mod: nn.Module) -> torch.Tensor:
23
+ return mod.weight.detach() # type: ignore[operator]
24
+
25
+
26
+ def mod_0_weight_detach(mod: nn.Module) -> torch.Tensor:
27
+ return mod[0].weight.detach() # type: ignore[index]
28
+
29
+
30
+ def mod_weight_bias_0(mod: nn.Module) -> torch.Tensor:
31
+ return mod._weight_bias()[0] # type: ignore[operator]
32
+
33
+
34
+ def get_lstm_weight(mod: nn.Module) -> list[torch.Tensor]:
35
+ res = []
36
+ for idx, param_name in enumerate(mod._flat_weights_names): # type: ignore[arg-type]
37
+ if "weight_ih_l" in param_name or "weight_hh_l" in param_name:
38
+ param_value = mod._flat_weights[idx].detach() # type: ignore[index,union-attr]
39
+ res.append(param_value)
40
+ return res
41
+
42
+
43
+ def get_qlstm_weight(mod: nn.Module) -> list[torch.Tensor]:
44
+ res = []
45
+ for weight_value in mod._all_weight_values: # type: ignore[union-attr]
46
+ res.append(weight_value.param.__getstate__()[0][4][0].__getstate__()[0][0])
47
+ res.append(weight_value.param.__getstate__()[0][4][1].__getstate__()[0][0])
48
+ return res
49
+
50
+
51
+ def get_conv_mod_weight(mod: nn.Module) -> torch.Tensor:
52
+ if isinstance(mod, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
53
+ return mod.weight.detach()
54
+ elif isinstance(mod, (nni.ConvReLU1d, nni.ConvReLU2d, nni.ConvReLU3d)):
55
+ return mod[0].weight.detach() # type: ignore[operator]
56
+ else:
57
+ return mod._weight_bias()[0] # type: ignore[operator]
58
+
59
+
60
+ def get_linear_mod_weight(mod: nn.Module) -> torch.Tensor:
61
+ if isinstance(mod, nn.Linear):
62
+ return mod.weight.detach()
63
+ elif isinstance(mod, nni.LinearReLU):
64
+ return mod[0].weight.detach() # type: ignore[operator]
65
+ else:
66
+ return mod._weight_bias()[0] # type: ignore[operator]
67
+
68
+
69
+ def get_lstm_mod_weights(mod: nn.Module) -> list[torch.Tensor]:
70
+ # TODO(future PR): make more generic, handle everything
71
+ if isinstance(mod, nn.LSTM):
72
+ res = []
73
+ for idx, param_name in enumerate(mod._flat_weights_names):
74
+ if "weight_ih_l" in param_name or "weight_hh_l" in param_name:
75
+ param_value = mod._flat_weights[idx].detach() # type: ignore[index,union-attr]
76
+ res.append(param_value)
77
+ return res
78
+ else:
79
+ if not isinstance(mod, nnqd.LSTM):
80
+ raise AssertionError(f"type {type(mod)} not handled yet")
81
+ res = []
82
+ for weight_value in mod._all_weight_values:
83
+ res.append(
84
+ weight_value.param.__getstate__()[0][4][0].__getstate__()[0][0] # type: ignore[index]
85
+ )
86
+ res.append(
87
+ weight_value.param.__getstate__()[0][4][1].__getstate__()[0][0] # type: ignore[index]
88
+ )
89
+ return res
90
+
91
+
92
+ def get_conv_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
93
+ # traverse backwards from the weight arg, accounting for any observers
94
+ weight_arg_node = node.args[1]
95
+ if not isinstance(weight_arg_node, Node):
96
+ raise AssertionError(f"Expected Node, got {type(weight_arg_node)}")
97
+ weight_node = return_first_non_observer_node(weight_arg_node, gm)
98
+ if not isinstance(weight_node, Node):
99
+ raise AssertionError(f"Expected Node, got {type(weight_node)}")
100
+ if weight_node.op != "get_attr":
101
+ raise AssertionError(f"Expected get_attr, got {weight_node.op}")
102
+ weight = getattr_from_fqn(gm, weight_node.target) # type: ignore[arg-type]
103
+ return weight.detach()
104
+
105
+
106
+ def get_qconv_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
107
+ # qconv state is arg 1
108
+ qconv_state_node = node.args[1]
109
+ if not isinstance(qconv_state_node, Node):
110
+ raise AssertionError(f"Expected Node, got {type(qconv_state_node)}")
111
+ if qconv_state_node.op != "get_attr":
112
+ raise AssertionError(f"Expected get_attr, got {qconv_state_node.op}")
113
+ qconv_state_obj = getattr_from_fqn(gm, qconv_state_node.target) # type: ignore[arg-type]
114
+ return qconv_state_obj.weight()
115
+
116
+
117
+ def get_linear_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
118
+ # traverse backwards from the weight arg, accounting for any observers
119
+ # supported patterns:
120
+ # weight -> obs -> linear
121
+ # weight -> to(torch.float16) -> dequantize -> linear
122
+ linear_second_arg = node.args[1]
123
+ if not isinstance(linear_second_arg, Node):
124
+ raise AssertionError(f"Expected Node, got {type(linear_second_arg)}")
125
+
126
+ if linear_second_arg.op == "call_module":
127
+ # weight -> obs -> linear
128
+ weight_arg_node = node.args[1]
129
+ if not isinstance(weight_arg_node, Node):
130
+ raise AssertionError(f"Expected Node, got {type(weight_arg_node)}")
131
+ weight_node = weight_arg_node.args[0]
132
+ if not isinstance(weight_node, Node):
133
+ raise AssertionError(f"Expected Node, got {type(weight_node)}")
134
+ if weight_node.op != "get_attr":
135
+ raise AssertionError(f"Expected get_attr, got {weight_node.op}")
136
+ weight = getattr_from_fqn(gm, weight_node.target) # type: ignore[arg-type]
137
+ return weight.detach()
138
+ elif linear_second_arg.op == "call_method":
139
+ # weight -> to(torch.float16) -> dequantize -> linear
140
+ if linear_second_arg.op != "call_method":
141
+ raise AssertionError(f"Expected call_method, got {linear_second_arg.op}")
142
+ dequant_node = node.args[1]
143
+ if not isinstance(dequant_node, Node):
144
+ raise AssertionError(f"Expected Node, got {type(dequant_node)}")
145
+ to_fp16_node = dequant_node.args[0]
146
+ if not isinstance(to_fp16_node, Node):
147
+ raise AssertionError(f"Expected Node, got {type(to_fp16_node)}")
148
+ # extract the dtype, so we can cast to it before returning
149
+ target_dtype = to_fp16_node.args[1]
150
+ weight_node = to_fp16_node.args[0]
151
+ if not isinstance(weight_node, Node):
152
+ raise AssertionError(f"Expected Node, got {type(weight_node)}")
153
+ if weight_node.op != "get_attr":
154
+ raise AssertionError(f"Expected get_attr, got {weight_node.op}")
155
+ weight = getattr_from_fqn(gm, weight_node.target) # type: ignore[arg-type]
156
+ # return the weight with fp16 cast
157
+ return weight.detach().to(target_dtype)
158
+ else:
159
+ if linear_second_arg.op != "get_attr":
160
+ raise AssertionError(f"Expected get_attr, got {linear_second_arg.op}")
161
+ weight = getattr_from_fqn(gm, linear_second_arg.target) # type: ignore[arg-type]
162
+ return weight.detach()
163
+
164
+
165
+ def get_qlinear_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
166
+ # packed weight is arg 1
167
+ packed_weight_node = node.args[1]
168
+ if not isinstance(packed_weight_node, Node):
169
+ raise AssertionError(f"Expected Node, got {type(packed_weight_node)}")
170
+ if packed_weight_node.op != "get_attr":
171
+ raise AssertionError(f"Expected get_attr, got {packed_weight_node.op}")
172
+ packed_weight = getattr_from_fqn(gm, packed_weight_node.target) # type: ignore[arg-type]
173
+ # TODO(future PR): why does packed_weight.unpack() not work?
174
+ (weight, _bias), _name = packed_weight.__getstate__()
175
+ return weight
176
+
177
+
178
+ def get_op_to_type_to_weight_extraction_fn() -> dict[str, dict[Callable, Callable]]:
179
+ op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]] = {
180
+ "call_module": {
181
+ # Conv1d
182
+ nn.Conv1d: mod_weight_detach,
183
+ nni.ConvReLU1d: mod_0_weight_detach,
184
+ nnq.Conv1d: mod_weight_bias_0,
185
+ nnqat.Conv1d: mod_weight_detach,
186
+ nniqat.ConvBn1d: mod_weight_detach,
187
+ nniqat.ConvBnReLU1d: mod_weight_detach,
188
+ nniqat.ConvReLU1d: mod_weight_detach,
189
+ nniq.ConvReLU1d: mod_weight_bias_0,
190
+ # Conv2d
191
+ nn.Conv2d: mod_weight_detach,
192
+ nni.ConvReLU2d: mod_0_weight_detach,
193
+ nnq.Conv2d: mod_weight_bias_0,
194
+ nnqat.Conv2d: mod_weight_detach,
195
+ nniqat.ConvBn2d: mod_weight_detach,
196
+ nniqat.ConvBnReLU2d: mod_weight_detach,
197
+ nniqat.ConvReLU2d: mod_weight_detach,
198
+ nniq.ConvReLU2d: mod_weight_bias_0,
199
+ # Conv3d
200
+ nn.Conv3d: mod_weight_detach,
201
+ nni.ConvReLU3d: mod_0_weight_detach,
202
+ nnq.Conv3d: mod_weight_bias_0,
203
+ nnqat.Conv3d: mod_weight_detach,
204
+ nniqat.ConvBn3d: mod_weight_detach,
205
+ nniqat.ConvBnReLU3d: mod_weight_detach,
206
+ nniqat.ConvReLU3d: mod_weight_detach,
207
+ nniq.ConvReLU3d: mod_weight_bias_0,
208
+ # Linear
209
+ nn.Linear: mod_weight_detach,
210
+ nnq.Linear: mod_weight_bias_0,
211
+ nni.LinearReLU: mod_0_weight_detach,
212
+ nniq.LinearReLU: mod_weight_bias_0,
213
+ nnqat.Linear: mod_weight_detach,
214
+ nnqd.Linear: mod_weight_bias_0,
215
+ nniqat.LinearReLU: mod_weight_detach,
216
+ nniqat.LinearBn1d: mod_weight_detach,
217
+ nn.modules.linear.NonDynamicallyQuantizableLinear: mod_weight_detach,
218
+ # LSTM
219
+ nn.LSTM: get_lstm_weight,
220
+ nnqd.LSTM: get_qlstm_weight,
221
+ },
222
+ "call_function": {
223
+ # Conv
224
+ F.conv1d: get_conv_fun_weight,
225
+ F.conv2d: get_conv_fun_weight,
226
+ F.conv3d: get_conv_fun_weight,
227
+ toq.conv1d: get_qconv_fun_weight,
228
+ toq.conv2d: get_qconv_fun_weight,
229
+ toq.conv3d: get_qconv_fun_weight,
230
+ toq.conv1d_relu: get_qconv_fun_weight,
231
+ toq.conv2d_relu: get_qconv_fun_weight,
232
+ toq.conv3d_relu: get_qconv_fun_weight,
233
+ # Linear
234
+ F.linear: get_linear_fun_weight,
235
+ toq.linear: get_qlinear_fun_weight,
236
+ toq.linear_relu: get_qlinear_fun_weight,
237
+ },
238
+ }
239
+
240
+ return op_to_type_to_weight_extraction_fn
241
+
242
+
243
+ def extract_weight_from_node(
244
+ node: Node,
245
+ gm: GraphModule,
246
+ op_to_type_to_weight_extraction_fn: dict[str, dict[Callable, Callable]]
247
+ | None = None,
248
+ ) -> NSSingleResultType | None:
249
+ res_type = NSSingleResultValuesType.WEIGHT.value
250
+
251
+ # Not all graphmodules have _node_name_to_scope, so only fill it
252
+ # out if it exists.
253
+ fqn = None
254
+ if hasattr(gm, "_node_name_to_scope"):
255
+ fqn = gm._node_name_to_scope[node.name][0] # type: ignore[index]
256
+
257
+ if op_to_type_to_weight_extraction_fn is None:
258
+ op_to_type_to_weight_extraction_fn = get_op_to_type_to_weight_extraction_fn()
259
+
260
+ ref_node_type = get_target_type_str(node, gm)
261
+ # for extracting weights, these are always the same
262
+ prev_node_type = ref_node_type
263
+
264
+ if node.op == "call_function":
265
+ function_mapping = op_to_type_to_weight_extraction_fn["call_function"]
266
+ for target_fn_type, weight_extraction_fn in function_mapping.items():
267
+ if node.target == target_fn_type:
268
+ weight = weight_extraction_fn(node, gm)
269
+ return {
270
+ "type": res_type,
271
+ "values": [weight],
272
+ "prev_node_name": node.name,
273
+ "prev_node_target_type": prev_node_type,
274
+ "ref_node_name": node.name,
275
+ "ref_node_target_type": ref_node_type,
276
+ "index_within_arg": 0,
277
+ "index_of_arg": 0,
278
+ "fqn": fqn,
279
+ }
280
+
281
+ elif node.op == "call_module":
282
+ # for call_module, we need to look up the modules to do the type check
283
+ if not isinstance(node.target, str):
284
+ raise AssertionError(f"Expected str, got {type(node.target)}")
285
+ mod = getattr_from_fqn(gm, node.target)
286
+ module_mapping = op_to_type_to_weight_extraction_fn["call_module"]
287
+ for target_mod_type, weight_extraction_fn in module_mapping.items():
288
+ if type(mod) is target_mod_type:
289
+ weight = weight_extraction_fn(mod)
290
+ return {
291
+ "type": res_type,
292
+ "values": [weight],
293
+ "prev_node_name": node.name,
294
+ "prev_node_target_type": prev_node_type,
295
+ "ref_node_name": node.name,
296
+ "ref_node_target_type": ref_node_type,
297
+ "index_within_arg": 0,
298
+ "index_of_arg": 0,
299
+ "fqn": fqn,
300
+ }
301
+
302
+ return None
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Variables
2
+ from ._mappings import (
3
+ get_dynamic_sparse_quantized_mapping,
4
+ get_static_sparse_quantized_mapping,
5
+ )
6
+
7
+ # Scheduler
8
+ from .scheduler.base_scheduler import BaseScheduler
9
+ from .scheduler.cubic_scheduler import CubicSL
10
+ from .scheduler.lambda_scheduler import LambdaSL
11
+
12
+ # Sparsifier
13
+ from .sparsifier.base_sparsifier import BaseSparsifier
14
+ from .sparsifier.nearly_diagonal_sparsifier import NearlyDiagonalSparsifier
15
+
16
+ # Parametrizations
17
+ from .sparsifier.utils import (
18
+ FakeSparsity,
19
+ fqn_to_module,
20
+ get_arg_info_from_tensor_fqn,
21
+ module_to_fqn,
22
+ )
23
+ from .sparsifier.weight_norm_sparsifier import WeightNormSparsifier
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/activation_sparsifier/activation_sparsifier.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ import warnings
4
+ from collections import defaultdict
5
+ from typing import Any
6
+
7
+ import torch
8
+ from torch import nn
9
+ from torch.ao.pruning.sparsifier.utils import fqn_to_module, module_to_fqn
10
+
11
+
12
+ __all__ = ["ActivationSparsifier"]
13
+
14
+
15
+ class ActivationSparsifier:
16
+ r"""
17
+ The Activation sparsifier class aims to sparsify/prune activations in a neural
18
+ network. The idea is to attach the sparsifier to a layer (or layers) and it
19
+ zeroes out the activations based on the mask_fn (or sparsification function)
20
+ input by the user.
21
+ The mask_fn is applied once all the inputs are aggregated and reduced i.e.
22
+ mask = mask_fn(reduce_fn(aggregate_fn(activations)))
23
+
24
+ Note::
25
+ The sparsification mask is computed on the input **before it goes through the attached layer**.
26
+
27
+ Args:
28
+ model (nn.Module):
29
+ The model whose layers will be sparsified. The layers that needs to be
30
+ sparsified should be added separately using the register_layer() function
31
+ aggregate_fn (Optional, Callable):
32
+ default aggregate_fn that is used if not specified while registering the layer.
33
+ specifies how inputs should be aggregated over time.
34
+ The aggregate_fn should usually take 2 torch tensors and return the aggregated tensor.
35
+ Example
36
+ def add_agg_fn(tensor1, tensor2): return tensor1 + tensor2
37
+ reduce_fn (Optional, Callable):
38
+ default reduce_fn that is used if not specified while registering the layer.
39
+ reduce_fn will be called on the aggregated tensor i.e. the tensor obtained after
40
+ calling agg_fn() on all inputs.
41
+ Example
42
+ def mean_reduce_fn(agg_tensor): return agg_tensor.mean(dim=0)
43
+ mask_fn (Optional, Callable):
44
+ default mask_fn that is used to create the sparsification mask using the tensor obtained after
45
+ calling the reduce_fn(). This is used by default if a custom one is passed in the
46
+ register_layer().
47
+ Note that the mask_fn() definition should contain the sparse arguments that is passed in sparse_config
48
+ arguments.
49
+ features (Optional, list):
50
+ default selected features to sparsify.
51
+ If this is non-empty, then the mask_fn will be applied for each feature of the input.
52
+ For example,
53
+ mask = [mask_fn(reduce_fn(aggregated_fn(input[feature])) for feature in features]
54
+ feature_dim (Optional, int):
55
+ default dimension of input features. Again, features along this dim will be chosen
56
+ for sparsification.
57
+ sparse_config (Dict):
58
+ Default configuration for the mask_fn. This config will be passed
59
+ with the mask_fn()
60
+
61
+ Example:
62
+ >>> # xdoctest: +SKIP
63
+ >>> model = SomeModel()
64
+ >>> act_sparsifier = ActivationSparsifier(...) # init activation sparsifier
65
+ >>> # Initialize aggregate_fn
66
+ >>> def agg_fn(x, y):
67
+ >>> return x + y
68
+ >>>
69
+ >>> # Initialize reduce_fn
70
+ >>> def reduce_fn(x):
71
+ >>> return torch.mean(x, dim=0)
72
+ >>>
73
+ >>> # Initialize mask_fn
74
+ >>> def mask_fn(data):
75
+ >>> return torch.eye(data.shape).to(data.device)
76
+ >>>
77
+ >>>
78
+ >>> act_sparsifier.register_layer(
79
+ ... model.some_layer,
80
+ ... aggregate_fn=agg_fn,
81
+ ... reduce_fn=reduce_fn,
82
+ ... mask_fn=mask_fn,
83
+ ... )
84
+ >>>
85
+ >>> # start training process
86
+ >>> for _ in [...]:
87
+ >>> # epoch starts
88
+ >>> # model.forward(), compute_loss() and model.backwards()
89
+ >>> # epoch ends
90
+ >>> act_sparsifier.step()
91
+ >>> # end training process
92
+ >>> sparsifier.squash_mask()
93
+ """
94
+
95
+ def __init__(
96
+ self,
97
+ model: nn.Module,
98
+ aggregate_fn=None,
99
+ reduce_fn=None,
100
+ mask_fn=None,
101
+ features=None,
102
+ feature_dim=None,
103
+ **sparse_config,
104
+ ):
105
+ self.model = model
106
+ self.defaults: dict[str, Any] = defaultdict()
107
+ self.defaults["sparse_config"] = sparse_config
108
+
109
+ # functions
110
+ self.defaults["aggregate_fn"] = aggregate_fn
111
+ self.defaults["reduce_fn"] = reduce_fn
112
+ self.defaults["mask_fn"] = mask_fn
113
+
114
+ # default feature and feature_dim
115
+ self.defaults["features"] = features
116
+ self.defaults["feature_dim"] = feature_dim
117
+
118
+ self.data_groups: dict[str, dict] = defaultdict(
119
+ dict
120
+ ) # contains all relevant info w.r.t each registered layer
121
+
122
+ self.state: dict[str, Any] = defaultdict(dict) # layer name -> mask
123
+
124
+ @staticmethod
125
+ def _safe_rail_checks(args):
126
+ """Makes sure that some of the functions and attributes are not passed incorrectly"""
127
+
128
+ # if features are not None, then feature_dim must not be None
129
+ features, feature_dim = args["features"], args["feature_dim"]
130
+ if features is not None:
131
+ if feature_dim is None:
132
+ raise AssertionError("need feature dim to select features")
133
+
134
+ # all the *_fns should be callable
135
+ fn_keys = ["aggregate_fn", "reduce_fn", "mask_fn"]
136
+ for key in fn_keys:
137
+ fn = args[key]
138
+ if not callable(fn):
139
+ raise AssertionError(f"{fn} must be callable")
140
+
141
+ def _aggregate_hook(self, name):
142
+ """Returns hook that computes aggregate of activations passing through."""
143
+
144
+ # gather some data
145
+ feature_dim = self.data_groups[name]["feature_dim"]
146
+ features = self.data_groups[name]["features"]
147
+ agg_fn = self.data_groups[name]["aggregate_fn"]
148
+
149
+ def hook(module, input) -> None:
150
+ input_data = input[0]
151
+
152
+ data = self.data_groups[name].get("data") # aggregated data
153
+ if features is None:
154
+ # no features associated, data should not be a list
155
+ if data is None:
156
+ data = torch.zeros_like(input_data)
157
+ self.state[name]["mask"] = torch.ones_like(input_data)
158
+ out_data = agg_fn(data, input_data)
159
+ else:
160
+ # data should be a list [aggregated over each feature only]
161
+ if data is None:
162
+ out_data = [
163
+ 0 for _ in range(len(features))
164
+ ] # create one in case of 1st forward
165
+ self.state[name]["mask"] = [0 for _ in range(len(features))]
166
+ else:
167
+ out_data = data # a list
168
+
169
+ # compute aggregate over each feature
170
+ for feature_idx in range(len(features)):
171
+ # each feature is either a list or scalar, convert it to torch tensor
172
+ feature_tensor = (
173
+ torch.Tensor([features[feature_idx]])
174
+ .long()
175
+ .to(input_data.device)
176
+ )
177
+ data_feature = torch.index_select(
178
+ input_data, feature_dim, feature_tensor
179
+ )
180
+ if data is None:
181
+ curr_data = torch.zeros_like(data_feature)
182
+ self.state[name]["mask"][feature_idx] = torch.ones_like(
183
+ data_feature
184
+ )
185
+ else:
186
+ curr_data = data[feature_idx]
187
+ out_data[feature_idx] = agg_fn(curr_data, data_feature)
188
+ self.data_groups[name]["data"] = out_data
189
+
190
+ return hook
191
+
192
+ def register_layer(
193
+ self,
194
+ layer: nn.Module,
195
+ aggregate_fn=None,
196
+ reduce_fn=None,
197
+ mask_fn=None,
198
+ features=None,
199
+ feature_dim=None,
200
+ **sparse_config,
201
+ ):
202
+ r"""
203
+ Registers a layer for sparsification. The layer should be part of self.model.
204
+ Specifically, registers a pre-forward hook to the layer. The hook will apply the aggregate_fn
205
+ and store the aggregated activations that is input over each step.
206
+
207
+ Note::
208
+ - There is no need to pass in the name of the layer as it is automatically computed as per
209
+ the fqn convention.
210
+
211
+ - All the functions (fn) passed as argument will be called at a dim, feature level.
212
+ """
213
+ name = module_to_fqn(self.model, layer)
214
+ if name is None:
215
+ raise AssertionError("layer not found in the model")
216
+
217
+ if name in self.data_groups: # unregister layer if already present
218
+ warnings.warn(
219
+ "layer already attached to the sparsifier, deregistering the layer and registering with new config",
220
+ stacklevel=2,
221
+ )
222
+ self.unregister_layer(name=name)
223
+
224
+ local_args = copy.deepcopy(self.defaults)
225
+ update_dict = {
226
+ "aggregate_fn": aggregate_fn,
227
+ "reduce_fn": reduce_fn,
228
+ "mask_fn": mask_fn,
229
+ "features": features,
230
+ "feature_dim": feature_dim,
231
+ "layer": layer,
232
+ }
233
+ local_args.update(
234
+ (arg, val) for arg, val in update_dict.items() if val is not None
235
+ )
236
+ local_args["sparse_config"].update(sparse_config)
237
+
238
+ self._safe_rail_checks(local_args)
239
+
240
+ self.data_groups[name] = local_args
241
+ agg_hook = layer.register_forward_pre_hook(self._aggregate_hook(name=name))
242
+
243
+ self.state[name]["mask"] = (
244
+ None # mask will be created when model forward is called.
245
+ )
246
+
247
+ # attach agg hook
248
+ self.data_groups[name]["hook"] = agg_hook
249
+
250
+ # for serialization purposes, we know whether aggregate_hook is attached
251
+ # or sparsify_hook()
252
+ self.data_groups[name]["hook_state"] = "aggregate" # aggregate hook is attached
253
+
254
+ def get_mask(self, name: str | None = None, layer: nn.Module | None = None):
255
+ """
256
+ Returns mask associated to the layer.
257
+
258
+ The mask is
259
+ - a torch tensor is features for that layer is None.
260
+ - a list of torch tensors for each feature, otherwise
261
+
262
+ Note::
263
+ The shape of the mask is unknown until model.forward() is applied.
264
+ Hence, if get_mask() is called before model.forward(), an
265
+ error will be raised.
266
+ """
267
+ if name is None and layer is None:
268
+ raise AssertionError("Need at least name or layer obj to retrieve mask")
269
+
270
+ if name is None:
271
+ if layer is None:
272
+ raise AssertionError("layer must be provided when name is None")
273
+ name = module_to_fqn(self.model, layer)
274
+ if name is None:
275
+ raise AssertionError("layer not found in the specified model")
276
+
277
+ if name not in self.state:
278
+ raise ValueError("Error: layer with the given name not found")
279
+
280
+ mask = self.state[name].get("mask", None)
281
+
282
+ if mask is None:
283
+ raise ValueError(
284
+ "Error: shape unknown, call layer() routine at least once to infer mask"
285
+ )
286
+ return mask
287
+
288
+ def unregister_layer(self, name):
289
+ """Detaches the sparsifier from the layer"""
290
+
291
+ # detach any hooks attached
292
+ self.data_groups[name]["hook"].remove()
293
+
294
+ # pop from the state dict
295
+ self.state.pop(name)
296
+
297
+ # pop from the data groups
298
+ self.data_groups.pop(name)
299
+
300
+ def step(self):
301
+ """Internally calls the update_mask() function for each layer"""
302
+ with torch.no_grad():
303
+ for name, configs in self.data_groups.items():
304
+ data = configs["data"]
305
+ self.update_mask(name, data, configs)
306
+
307
+ self.data_groups[name].pop("data") # reset the accumulated data
308
+
309
+ def update_mask(self, name, data, configs):
310
+ """
311
+ Called for each registered layer and does the following-
312
+ 1. apply reduce_fn on the aggregated activations
313
+ 2. use mask_fn to compute the sparsification mask
314
+
315
+ Note:
316
+ the reduce_fn and mask_fn is called for each feature, dim over the data
317
+ """
318
+ mask = self.get_mask(name)
319
+ sparse_config = configs["sparse_config"]
320
+ features = configs["features"]
321
+ reduce_fn = configs["reduce_fn"]
322
+ mask_fn = configs["mask_fn"]
323
+ if features is None:
324
+ data = reduce_fn(data)
325
+ mask.data = mask_fn(data, **sparse_config)
326
+ else:
327
+ for feature_idx in range(len(features)):
328
+ data_feature = reduce_fn(data[feature_idx])
329
+ mask[feature_idx].data = mask_fn(data_feature, **sparse_config)
330
+
331
+ def _sparsify_hook(self, name):
332
+ """Returns hook that applies sparsification mask to input entering the attached layer"""
333
+ mask = self.get_mask(name)
334
+ features = self.data_groups[name]["features"]
335
+ feature_dim = self.data_groups[name]["feature_dim"]
336
+
337
+ def hook(module, input):
338
+ input_data = input[0]
339
+ if features is None:
340
+ # apply to all the features
341
+ return input_data * mask
342
+ else:
343
+ # apply per feature, feature_dim
344
+ for feature_idx in range(len(features)):
345
+ feature = (
346
+ torch.Tensor([features[feature_idx]])
347
+ .long()
348
+ .to(input_data.device)
349
+ )
350
+ sparsified = (
351
+ torch.index_select(input_data, feature_dim, feature)
352
+ * mask[feature_idx]
353
+ )
354
+ input_data.index_copy_(feature_dim, feature, sparsified)
355
+ return input_data
356
+
357
+ return hook
358
+
359
+ def squash_mask(self, attach_sparsify_hook=True, **kwargs):
360
+ """
361
+ Unregisters aggregate hook that was applied earlier and registers sparsification hooks if
362
+ attach_sparsify_hook = True.
363
+ """
364
+ for name, configs in self.data_groups.items():
365
+ # unhook agg hook
366
+ configs["hook"].remove()
367
+ configs.pop("hook")
368
+ self.data_groups[name]["hook_state"] = "None"
369
+ if attach_sparsify_hook:
370
+ configs["hook"] = configs["layer"].register_forward_pre_hook(
371
+ self._sparsify_hook(name)
372
+ )
373
+ configs["hook_state"] = (
374
+ "sparsify" # signals that sparsify hook is now attached
375
+ )
376
+
377
+ def _get_serializable_data_groups(self):
378
+ """Exclude hook and layer from the config keys before serializing
379
+
380
+ TODO: Might have to treat functions (reduce_fn, mask_fn etc) in a different manner while serializing.
381
+ For time-being, functions are treated the same way as other attributes
382
+ """
383
+ data_groups: dict[str, Any] = defaultdict()
384
+ for name, config in self.data_groups.items():
385
+ new_config = {
386
+ key: value
387
+ for key, value in config.items()
388
+ if key not in ["hook", "layer"]
389
+ }
390
+ data_groups[name] = new_config
391
+ return data_groups
392
+
393
+ def _convert_mask(self, states_dict, sparse_coo=True):
394
+ r"""Converts the mask to sparse coo or dense depending on the `sparse_coo` argument.
395
+ If `sparse_coo=True`, then the mask is stored as sparse coo else dense tensor
396
+ """
397
+ states = copy.deepcopy(states_dict)
398
+ for state in states.values():
399
+ if state["mask"] is not None:
400
+ if isinstance(state["mask"], list):
401
+ for idx in range(len(state["mask"])):
402
+ if sparse_coo:
403
+ state["mask"][idx] = state["mask"][idx].to_sparse_coo()
404
+ else:
405
+ state["mask"][idx] = state["mask"][idx].to_dense()
406
+ else:
407
+ if sparse_coo:
408
+ state["mask"] = state["mask"].to_sparse_coo()
409
+ else:
410
+ state["mask"] = state["mask"].to_dense()
411
+ return states
412
+
413
+ def state_dict(self) -> dict[str, Any]:
414
+ r"""Returns the state of the sparsifier as a :class:`dict`.
415
+
416
+ It contains:
417
+ * state - contains name -> mask mapping.
418
+ * data_groups - a dictionary containing all config information for each
419
+ layer
420
+ * defaults - the default config while creating the constructor
421
+ """
422
+ data_groups = self._get_serializable_data_groups()
423
+ state = self._convert_mask(self.state)
424
+ return {"state": state, "data_groups": data_groups, "defaults": self.defaults}
425
+
426
+ def load_state_dict(self, state_dict: dict[str, Any]) -> None:
427
+ r"""The load_state_dict() restores the state of the sparsifier based on the state_dict
428
+
429
+ Args:
430
+ * state_dict - the dictionary that to which the current sparsifier needs to be restored to
431
+ """
432
+ state = state_dict["state"]
433
+ data_groups, defaults = state_dict["data_groups"], state_dict["defaults"]
434
+
435
+ self.__set_state__(
436
+ {"state": state, "data_groups": data_groups, "defaults": defaults}
437
+ )
438
+
439
+ def __get_state__(self) -> dict[str, Any]:
440
+ data_groups = self._get_serializable_data_groups()
441
+ state = self._convert_mask(self.state)
442
+ return {
443
+ "defaults": self.defaults,
444
+ "state": state,
445
+ "data_groups": data_groups,
446
+ }
447
+
448
+ def __set_state__(self, state: dict[str, Any]) -> None:
449
+ state["state"] = self._convert_mask(
450
+ state["state"], sparse_coo=False
451
+ ) # convert mask to dense tensor
452
+ self.__dict__.update(state)
453
+
454
+ # need to attach layer and hook info into the data_groups
455
+ for name, config in self.data_groups.items():
456
+ # fetch layer
457
+ layer = fqn_to_module(self.model, name)
458
+ if layer is None:
459
+ raise AssertionError(f"layer {name} not found in the model")
460
+
461
+ # if agg_mode is True, then layer in aggregate mode
462
+ if "hook_state" in config and config["hook_state"] == "aggregate":
463
+ hook = layer.register_forward_pre_hook(self._aggregate_hook(name))
464
+
465
+ elif "hook_state" in config and config["hook_state"] == "sparsify":
466
+ hook = layer.register_forward_pre_hook(self._sparsify_hook(name))
467
+
468
+ config["layer"] = layer
469
+ config["hook"] = hook # type: ignore[possibly-undefined]
470
+
471
+ def __repr__(self):
472
+ format_string = self.__class__.__name__ + " ("
473
+ for name, config in self.data_groups.items():
474
+ format_string += "\n"
475
+ format_string += "\tData Group\n"
476
+ format_string += f"\t name: {name}\n"
477
+ for key in sorted(config.keys()):
478
+ if key in ["data", "hook", "reduce_fn", "mask_fn", "aggregate_fn"]:
479
+ continue
480
+ format_string += f"\t {key}: {config[key]}\n"
481
+ format_string += ")"
482
+ return format_string
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .base_data_scheduler import BaseDataScheduler
2
+
3
+
4
+ __all__ = [
5
+ "BaseDataScheduler",
6
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_scheduler/base_data_scheduler.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import abc
3
+ import warnings
4
+ import weakref
5
+ from functools import wraps
6
+
7
+ from torch.ao.pruning._experimental.data_sparsifier import BaseDataSparsifier
8
+
9
+
10
+ __all__ = ["BaseDataScheduler"]
11
+
12
+
13
+ class BaseDataScheduler:
14
+ r"""
15
+ The BaseDataScheduler is the abstract scheduler class specifically for the
16
+ BaseDataSparsifier class. This class controls a specific hyperparameter of
17
+ the sparsifier class and varies it across the training process (or across time).
18
+
19
+ Args:
20
+ data_sparsifier (instance of BaseDataSparsifier)
21
+ Implemented class data sparsifier class wherein the update_mask is implemented
22
+ schedule_param (str)
23
+ A specific hyperparameter of the passed sparsifier that needs to be scheduled/varied
24
+ last_epoch (int, default=-1)
25
+ This is specifically is passed when training needs to be resumed from a particular
26
+ point.
27
+ verbose (bool, default=False)
28
+ Verbosity of the BaseDataScheduler
29
+
30
+ The *get_hyperparam()* function needs to be implemented by the user.
31
+ """
32
+
33
+ def __init__(
34
+ self, data_sparsifier, schedule_param: str, last_epoch=-1, verbose=False
35
+ ):
36
+ # Attach sparsifier
37
+ if not isinstance(data_sparsifier, BaseDataSparsifier):
38
+ raise TypeError(
39
+ f"{type(data_sparsifier).__name__} is not an instance of torch.ao.pruning.BaseDataSparsifier"
40
+ )
41
+ self.data_sparsifier = data_sparsifier
42
+ self.schedule_param = schedule_param
43
+
44
+ # Initialize epoch and base hyper-params
45
+ self.base_param = {
46
+ name: config.get(schedule_param, None)
47
+ for name, config in self.data_sparsifier.data_groups.items()
48
+ }
49
+
50
+ self.last_epoch = last_epoch
51
+
52
+ # Following https://github.com/pytorch/pytorch/issues/20124
53
+ # We would like to ensure that `scheduler.step()` is called after
54
+ # `sparsifier.step()`
55
+ def with_counter(method):
56
+ if getattr(method, "_with_counter", False):
57
+ # `sparsifier.step()` has already been replaced, return.
58
+ return method
59
+
60
+ # Keep a weak reference to the sparsifier instance to prevent
61
+ # cyclic references.
62
+ instance_ref = weakref.ref(method.__self__)
63
+ # Get the unbound method for the same purpose.
64
+ func = method.__func__
65
+ cls = instance_ref().__class__
66
+ del method
67
+
68
+ @wraps(func)
69
+ def wrapper(*args, **kwargs):
70
+ instance = instance_ref()
71
+ instance._step_count += 1 # type: ignore[union-attr]
72
+ wrapped = func.__get__(instance, cls)
73
+ return wrapped(*args, **kwargs)
74
+
75
+ # Note that the returned function here is no longer a bound method,
76
+ # so attributes like `__func__` and `__self__` no longer exist.
77
+ wrapper._with_counter = True # type: ignore[attr-defined]
78
+ return wrapper
79
+
80
+ self.data_sparsifier.step = with_counter(self.data_sparsifier.step) # type: ignore[assignment]
81
+ self.data_sparsifier._step_count = 0 # type: ignore[attr-defined]
82
+ self._step_count: int = 0
83
+ self.verbose = verbose
84
+
85
+ # Housekeeping
86
+ self._get_sp_called_within_step: bool = False # sp -> schedule parameter
87
+ self.step()
88
+
89
+ @abc.abstractmethod
90
+ def get_schedule_param(self):
91
+ r"""
92
+ Abstract method that needs to be implemented by the child class.
93
+ The expected return type should is a dictionary of name to schedule_param value
94
+ The returned values will be updated in sparsifier when the scheduler step() function
95
+ is called.
96
+
97
+ Example:
98
+ >>> def get_schedule_param(self):
99
+ ... new_param = {}
100
+ ... for name in self.sparsifier.data_groups.keys():
101
+ ... new_param[name] = (
102
+ ... self.sparsifier.data_groups[name][self.schedule_param] * 0.5
103
+ ... )
104
+ ... return new_param
105
+
106
+ When the step() function is called, the value in self.sparsifier.data_groups[name][self.schedule_param]
107
+ would be halved
108
+ """
109
+ raise NotImplementedError
110
+
111
+ def __repr__(self):
112
+ format_string = self.__class__.__name__ + " ("
113
+ format_string += "\n"
114
+ format_string += f"Data Sparsifier {self.data_sparsifier}\n"
115
+ format_string += f" {self.schedule_param}: {self.base_param}\n"
116
+ format_string += ")"
117
+ return format_string
118
+
119
+ def state_dict(self):
120
+ """Returns the state of the scheduler as a :class:`dict`.
121
+
122
+ It contains an entry for every variable in self.__dict__ which
123
+ is not the sparsifier.
124
+
125
+ Note:
126
+ The scheduler class does not track the state of the data_sparsifier.
127
+ Make sure to store the state of the sparsifier before storing the
128
+ state of the scheduler
129
+ """
130
+ return {
131
+ key: value
132
+ for key, value in self.__dict__.items()
133
+ if key != "data_sparsifier"
134
+ }
135
+
136
+ def load_state_dict(self, state_dict):
137
+ """Loads the schedulers state.
138
+
139
+ Note:
140
+ Remember to restore the state of the data_sparsifier before the scheduler.
141
+
142
+ Args:
143
+ state_dict (dict): scheduler state. Should be an object returned
144
+ from a call to :meth:`state_dict`.
145
+ """
146
+ self.__dict__.update(state_dict)
147
+
148
+ def get_last_param(self):
149
+ return self._last_param
150
+
151
+ def step(self):
152
+ # Raise warning if trying to call scheduler step before the sparsifier.
153
+ # https://github.com/pytorch/pytorch/issues/20124
154
+ if self._step_count == 1:
155
+ if not hasattr(self.data_sparsifier.step, "_with_counter"):
156
+ warnings.warn(
157
+ "Seems like `data_sparsifier.step()` has been overridden after sparsity scheduler "
158
+ "initialization. Please, make sure to call `data_sparsifier.step()` before "
159
+ "`scheduler.step()`.",
160
+ UserWarning,
161
+ stacklevel=2,
162
+ )
163
+
164
+ # Just check if there were two first scheduler.step() calls before sparsifier.step()
165
+ elif self.data_sparsifier._step_count < 1: # type: ignore[attr-defined]
166
+ warnings.warn(
167
+ "Detected call of `scheduler.step()` before `data_sparsifier.step()`. "
168
+ "You have to make sure you run the data_sparsifier.step() BEFORE any "
169
+ "calls to the scheduler.step().",
170
+ UserWarning,
171
+ stacklevel=2,
172
+ )
173
+ self._step_count += 1
174
+
175
+ class _enable_get_sp_call:
176
+ def __init__(self, o):
177
+ self.o = o
178
+
179
+ def __enter__(self):
180
+ self.o._get_sp_called_within_step = True
181
+ return self
182
+
183
+ def __exit__(self, type, value, traceback):
184
+ self.o._get_sp_called_within_step = False
185
+
186
+ with _enable_get_sp_call(self):
187
+ self.last_epoch += 1
188
+ updated_scheduler_params = self.get_schedule_param()
189
+
190
+ for name, param in updated_scheduler_params.items():
191
+ self.data_sparsifier.data_groups[name][self.schedule_param] = param
192
+ if self.verbose:
193
+ print(f"Adjusting {self.schedule_param} for group {name} to {param}")
194
+
195
+ self._last_param = {
196
+ name: config.get(self.schedule_param, None)
197
+ for name, config in self.data_sparsifier.data_groups.items()
198
+ }
199
+ self.data_sparsifier.enable_mask_update = True
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from .base_data_sparsifier import BaseDataSparsifier
2
+ from .data_norm_sparsifier import DataNormSparsifier
3
+
4
+
5
+ __all__ = [
6
+ "BaseDataSparsifier",
7
+ "DataNormSparsifier",
8
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/base_data_sparsifier.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import abc
3
+ import copy
4
+ import sys
5
+ import warnings
6
+ from collections import defaultdict
7
+ from typing import Any
8
+
9
+ import torch
10
+ from torch import nn
11
+ from torch.ao.pruning.sparsifier import base_sparsifier, utils
12
+ from torch.nn.utils import parametrize
13
+
14
+
15
+ if not sys.warnoptions:
16
+ # to suppress repeated warnings when being used in a training loop.
17
+ warnings.simplefilter("once")
18
+
19
+ __all__ = ["BaseDataSparsifier"]
20
+
21
+ EMBEDDING_TYPES = {
22
+ nn.Embedding,
23
+ nn.EmbeddingBag,
24
+ }
25
+
26
+ SUPPORTED_TYPES = {
27
+ torch.Tensor,
28
+ nn.Parameter,
29
+ *EMBEDDING_TYPES,
30
+ }
31
+
32
+
33
+ class _Container(nn.Module):
34
+ pass
35
+
36
+
37
+ class BaseDataSparsifier(base_sparsifier.BaseSparsifier):
38
+ r"""
39
+ Base Data Sparsifier class for all Data sparsifiers.
40
+ The abstract class accepts raw torch tensors / embedding / embedding bags (refer to SUPPORTED_TYPES above)
41
+ to prepare for sparsification.
42
+ In this case, mask (and parametrizations) is owned by the class and not by the user.
43
+ Specifically, the container object inside the class maintains the mask and parametrizations of the input data
44
+
45
+ Args:
46
+ data_list (list of tuples)
47
+ list of (name, data) tuples to sparsify. Lookup SUPPORTED_TYPES
48
+ for type of data. Internally, a container module handles the data sparsification.
49
+
50
+ defaults (dict)
51
+ default configurations will be attached to the
52
+ configuration. Only the keys that don't exist in the `config` will
53
+ be updated.
54
+ Example::
55
+ >>> # xdoctest: +SKIP
56
+ >>> data_list = [('tensor_1', torch.randn(3,3)), ('tensor_2', torch.randn(4,4))]
57
+ >>> defaults = {'sparsity_level': 0.7}
58
+ >>> sparsifier = DerivedDataSparsifier(data_list = data_list, **defaults) # Some sparsifier that inherits BaseDataSparsifier
59
+ >>> new_tensor_to_add = {'name': 'tensor_3', 'data': torch.randn(5,5), 'sparsity_level': 0.3}
60
+ >>> sparsifier.add_data(**new_tensor_to_add)
61
+ >>> # tensor_1 and tensor_2 will have sparsity_level of 0.7 but tensor_3 will have sparsity_level=0.3
62
+ """
63
+
64
+ def __init__(self, data_list: list[tuple[str, Any]] | None = None, **defaults):
65
+ super().__init__(defaults=defaults)
66
+
67
+ self._container = _Container()
68
+
69
+ self.data_groups: dict[str, dict] = defaultdict(dict) # name -> {**config}
70
+ if data_list is not None:
71
+ # add data with default config here
72
+ [self.add_data(name, data, **self.defaults) for name, data in data_list]
73
+
74
+ def prepare(self, model, config):
75
+ raise NotImplementedError("this function is undefined for this class")
76
+
77
+ def _extract_weight(self, data):
78
+ # extract the weight parameter instead of underlying data
79
+ if type(data) in [torch.Tensor, nn.Parameter]:
80
+ return data
81
+ elif type(data) in EMBEDDING_TYPES:
82
+ return data.weight
83
+
84
+ def add_data(self, name: str, data, reuse_mask=True, **config):
85
+ r"""Configures and parametrizes the internal container model with name and data.
86
+
87
+ **Note**:
88
+ 1. If the data with name already exists, it replaces the data.
89
+ 2. While replacing, the old mask is reused when `reuse_mask=True`
90
+ 3. If `reuse_mask=True`, then the replacing data needs to have the same shape as that of old data.
91
+ 4. By default, the config of the replaced data is used as config for the replacing data, unless something
92
+ is specified in the config dictionary.
93
+ """
94
+ if type(data) not in SUPPORTED_TYPES:
95
+ raise AssertionError(
96
+ f"specified data type:{type(data)} not supported at the moment"
97
+ )
98
+ local_args = copy.deepcopy(self.defaults)
99
+ local_args.update(config)
100
+ weight = self._extract_weight(data)
101
+
102
+ # Bookkeeping in the container class
103
+ mask = local_args.get("mask", torch.ones_like(weight))
104
+ param_class = local_args.get("parametrization", utils.FakeSparsity)
105
+
106
+ if name in self.state:
107
+ # If the named data already exists - replace
108
+ warnings.warn(
109
+ "Replacing existing data of the same name. - Did you mean a different name?",
110
+ stacklevel=2,
111
+ )
112
+
113
+ # reuse old config
114
+ old_args = self.data_groups[name]
115
+ local_args = copy.deepcopy(old_args)
116
+ local_args.update(config)
117
+
118
+ if reuse_mask:
119
+ current_data = self.get_data(name=name)
120
+ if weight.shape != current_data.shape:
121
+ raise AssertionError(
122
+ "to retain the old mask, the shape of the new data must be the same as the previous one"
123
+ )
124
+ mask = self.get_mask(
125
+ name=name
126
+ ) # reuse mask instead of creating a new one
127
+
128
+ self._delete_data(name=name)
129
+
130
+ # parameter creates a deepcopy of the weight inside, so create a buffer
131
+ self._container.register_buffer(name=name, tensor=weight)
132
+ parametrize.register_parametrization(self._container, name, param_class(mask))
133
+ self.state[name]["mask"] = mask
134
+ self.data_groups[name] = local_args
135
+ return getattr(self._container, name)
136
+
137
+ def get_data(self, name: str, return_original: bool = True):
138
+ r"""Returns weight tensor (or data)
139
+ Args:
140
+ - name: name of the data to be returned
141
+ - return_original returns weight tensor without applying parametrization if True
142
+ else - returns the sparsified version (parametrized)
143
+ """
144
+ if name not in self.data_groups:
145
+ raise ValueError("data with specified name does not exist")
146
+
147
+ if return_original:
148
+ if not parametrize.is_parametrized(self._container, name):
149
+ raise ValueError("mask squashed - original mask value does not exist")
150
+ data = getattr(self._container.parametrizations, name).original
151
+ return data
152
+ else:
153
+ return getattr(self._container, name)
154
+
155
+ def _convert_mask(self, states, sparse_coo=True):
156
+ r"""Converts the mask to sparse coo or dense tensors depending on the `sparse_coo` argument."""
157
+ states = copy.deepcopy(states)
158
+ for state in states.values():
159
+ if sparse_coo:
160
+ state["mask"] = state["mask"].to_sparse_coo()
161
+ else:
162
+ state["mask"] = state["mask"].to_dense()
163
+
164
+ return states
165
+
166
+ def state_dict(self):
167
+ r"""Returns the state of the optimizer as a :class:`dict`.
168
+
169
+ It contains:
170
+ * state - contains name -> mask mapping.
171
+ * data_groups - a list containing all sparsity configuration groups
172
+ with the key name specifying the name of the data
173
+ * container_state_dict - the state dictionary of the internal
174
+ container model used for sparsification
175
+ """
176
+ state = self._convert_mask(self.state)
177
+ return {
178
+ "state": state,
179
+ "data_groups": self.data_groups,
180
+ "_container": self._container.state_dict(),
181
+ }
182
+
183
+ def _load_container_from_state(self, states, data_groups, container_state_dict):
184
+ r"""This restores the state of the container specifically based on the data present in state and data_groups
185
+ If the data was parametrized, then the data would be added to the container and then parametrized,
186
+ else it would just add the attribute the container.
187
+ """
188
+ for name, state in states.items():
189
+ config_name = data_groups.get(name, None)
190
+ if config_name is None:
191
+ raise RuntimeError(f"Error loading {name}")
192
+
193
+ # check if the data with such a name was parametrized, if so parametrize
194
+ # otherwise just set the attribute and continue
195
+ parametrized_name = f"parametrizations.{name}.original"
196
+ parametrized = False
197
+ data = container_state_dict.get(name, None)
198
+ if name in container_state_dict:
199
+ # the parametrization was probably removed for this
200
+ data = container_state_dict.get(name)
201
+
202
+ elif parametrized_name in container_state_dict:
203
+ # so the weight was parametrized
204
+ data = container_state_dict.get(parametrized_name)
205
+ parametrized = True
206
+
207
+ else:
208
+ raise RuntimeError(f"Error loading {name}")
209
+
210
+ self._container.register_buffer(name=name, tensor=data)
211
+
212
+ if parametrized:
213
+ # register parameter if parametrized
214
+ mask = state.get("mask", torch.ones_like(data))
215
+ param_class = data_groups.get(
216
+ "parametrization", utils.FakeSparsity
217
+ ) # change once public_api for utils is fixed!
218
+ parametrize.register_parametrization(
219
+ self._container, name, param_class(mask)
220
+ )
221
+
222
+ def load_state_dict(self, state_dict, strict=True):
223
+ r"""The load_state_dict() restores the state of the sparsifier based on the state_dict
224
+
225
+ Args:
226
+ * state_dict - the dictionary that to which the current sparsifier needs to be restored to
227
+ * strict - If True - the sparsifier is reset and is restored exactly to the state in state_dict.
228
+ If False - the current sparsifier is not reset before loading the state_dict i.e. data added
229
+ before loading the state_dict is not erased.
230
+ """
231
+ states = copy.deepcopy(state_dict["state"])
232
+ data_groups = copy.deepcopy(state_dict["data_groups"])
233
+ container_state_dict = copy.deepcopy(state_dict["_container"])
234
+
235
+ states = self._convert_mask(
236
+ states, sparse_coo=False
237
+ ) # convert sparse coo mask to dense
238
+ if strict:
239
+ # if strict load -> then reset container
240
+ self._container = _Container()
241
+
242
+ self._load_container_from_state(states, data_groups, container_state_dict)
243
+
244
+ if not strict:
245
+ states.update(self.state)
246
+ data_groups.update(self.data_groups)
247
+
248
+ self.__setstate__({"state": states, "data_groups": data_groups})
249
+
250
+ def __setstate__(self, state):
251
+ if "_container" in state: # If container object is in state then load model
252
+ container_dict = state.pop("_container")
253
+ self._container = _Container()
254
+ state["state"] = self._convert_mask(
255
+ state["state"], sparse_coo=False
256
+ ) # convert sparse coo mask to dense
257
+ self._load_container_from_state(
258
+ state["state"], state["data_groups"], container_dict
259
+ )
260
+
261
+ self.__dict__.update(state)
262
+
263
+ def __getstate__(self):
264
+ state = self._convert_mask(self.state)
265
+ return {
266
+ "defaults": self.defaults,
267
+ "state": state,
268
+ "data_groups": self.data_groups,
269
+ "_container": self._container.state_dict(),
270
+ }
271
+
272
+ def __repr__(self): # type:ignore[override]
273
+ format_string = self.__class__.__name__ + " ("
274
+ for name, sparse_args in self.data_groups.items():
275
+ format_string += "\n"
276
+ format_string += "\tData Group\n"
277
+ format_string += f"\t name: {name}\n"
278
+ for key in sorted(sparse_args.keys()):
279
+ if key == "data":
280
+ continue
281
+ format_string += f"\t {key}: {sparse_args[key]}\n"
282
+ format_string += ")"
283
+ return format_string
284
+
285
+ def get_mask(self, name: str):
286
+ if name not in self.state:
287
+ raise ValueError("data with specified name does not exist")
288
+ return self.state[name]["mask"]
289
+
290
+ def squash_mask(self, *args, leave_parametrized=True, names=None, **kwargs):
291
+ r"""Squashes the sparse masks into the appropriate tensors. Also, accepts list of strings
292
+ to squash mask for. If none, squashes mask for all the keys
293
+ kwargs:
294
+ * names: list of strings to squash mask for
295
+ * sparsified: if true - applies the mask before squashing
296
+ if false - does not apply the mask before squashing
297
+ """
298
+ if names is None:
299
+ names = list(self.data_groups.keys())
300
+ for name in names:
301
+ parametrize.remove_parametrizations(
302
+ self._container, name, leave_parametrized=leave_parametrized
303
+ )
304
+
305
+ def step(self): # type:ignore[override]
306
+ if not self.enable_mask_update:
307
+ return
308
+ with torch.no_grad():
309
+ for name, config in self.data_groups.items():
310
+ # get non-sparsified data
311
+ data = self.get_data(name)
312
+ # need name for the mask otherwise can directly pass mask?
313
+ self.update_mask(name, data, **config)
314
+
315
+ @abc.abstractmethod
316
+ def update_mask(self, name, data, **kwargs): # type: ignore[override]
317
+ pass
318
+
319
+ def _delete_data(self, name):
320
+ """Detaches some data from the sparsifier.
321
+
322
+ Args:
323
+ name (str)
324
+ Name of the data to be removed from the sparsifier
325
+
326
+ Note:
327
+ Currently private. Kind of used as a helper function when replacing data of the same name
328
+ """
329
+ self.squash_mask(
330
+ names=[name], leave_parametrized=False
331
+ ) # do not apply the mask while deleting
332
+ delattr(self._container, name)
333
+ self.state.pop(name)
334
+ self.data_groups.pop(name)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import operator
3
+ from functools import reduce
4
+ from typing import Any
5
+
6
+ import torch
7
+ from torch.nn import functional as F
8
+
9
+ from .base_data_sparsifier import BaseDataSparsifier
10
+
11
+
12
+ __all__ = ["DataNormSparsifier"]
13
+
14
+
15
+ class DataNormSparsifier(BaseDataSparsifier):
16
+ r"""L1-Norm Sparsifier
17
+ This sparsifier computes the *L1-norm* of every sparse block and "zeroes-out" the
18
+ ones with the lowest norm. The level of sparsity defines how many of the
19
+ blocks is removed.
20
+ This sparsifier is controlled by three variables:
21
+ 1. `sparsity_level` defines the number of *sparse blocks* that are zeroed-out
22
+ 2. `sparse_block_shape` defines the shape of the sparse blocks. Note that
23
+ the sparse blocks originate at the zero-index of the tensor.
24
+ 3. `zeros_per_block` is the number of zeros that we are expecting in each
25
+ sparse block. By default we assume that all elements within a block are
26
+ zeroed-out. However, setting this variable sets the target number of
27
+ zeros per block. The zeros within each block are chosen as the *smallest
28
+ absolute values*.
29
+ Args:
30
+ sparsity_level: The target level of sparsity
31
+ sparse_block_shape: The shape of a sparse block
32
+ zeros_per_block: Number of zeros in a sparse block
33
+ Note::
34
+ All arguments to the DataNormSparsifier constructor are "default"
35
+ arguments and could be overridden by the configuration provided in the
36
+ `add_data` step.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ data_list: list[tuple[str, Any]] | None = None,
42
+ sparsity_level: float = 0.5,
43
+ sparse_block_shape: tuple[int, int] = (1, 4),
44
+ zeros_per_block: int | None = None,
45
+ norm: str = "L1",
46
+ ):
47
+ if zeros_per_block is None:
48
+ zeros_per_block = reduce(operator.mul, sparse_block_shape)
49
+
50
+ if norm not in ["L1", "L2"]:
51
+ raise AssertionError("only L1 and L2 norm supported at the moment")
52
+
53
+ defaults = {
54
+ "sparsity_level": sparsity_level,
55
+ "sparse_block_shape": sparse_block_shape,
56
+ "zeros_per_block": zeros_per_block,
57
+ }
58
+ self.norm = norm
59
+ super().__init__(data_list=data_list, **defaults)
60
+
61
+ def __get_scatter_folded_mask(
62
+ self, data, dim, indices, output_size, sparse_block_shape
63
+ ):
64
+ mask = torch.ones_like(data)
65
+ mask.scatter_(dim=dim, index=indices, value=0) # zeroing out
66
+ mask = F.fold(
67
+ mask,
68
+ output_size=output_size,
69
+ kernel_size=sparse_block_shape,
70
+ stride=sparse_block_shape,
71
+ )
72
+ mask = mask.to(torch.int8)
73
+ return mask
74
+
75
+ def __get_block_level_mask(self, data, sparse_block_shape, zeros_per_block):
76
+ # Assume data is a squeezed tensor
77
+ height, width = data.shape[-2], data.shape[-1]
78
+ block_height, block_width = sparse_block_shape
79
+ values_per_block = block_height * block_width
80
+
81
+ # just return zeros if zeroing all elements in block
82
+ if values_per_block == zeros_per_block:
83
+ return torch.zeros_like(data, dtype=torch.int8)
84
+
85
+ # creating additional height and width to support padding
86
+ dh = (block_height - height % block_height) % block_height
87
+ dw = (block_width - width % block_width) % block_width
88
+
89
+ # create a new padded tensor like data (to match the block_shape)
90
+ padded_data = torch.ones(
91
+ height + dh, width + dw, dtype=data.dtype, device=data.device
92
+ )
93
+ padded_data = (
94
+ padded_data * torch.nan
95
+ ) # can also be replaced with 0 to stop the removal of edge data
96
+ padded_data[0:height, 0:width] = data
97
+ unfolded_data = F.unfold(
98
+ padded_data[None, None, :],
99
+ kernel_size=sparse_block_shape,
100
+ stride=sparse_block_shape,
101
+ )
102
+
103
+ _, sorted_idx = torch.sort(unfolded_data, dim=1)
104
+ sorted_idx = sorted_idx[
105
+ :, :zeros_per_block, :
106
+ ] # zero out zeros_per_block number of elements
107
+
108
+ mask = self.__get_scatter_folded_mask(
109
+ data=unfolded_data,
110
+ dim=1,
111
+ indices=sorted_idx,
112
+ output_size=padded_data.shape,
113
+ sparse_block_shape=sparse_block_shape,
114
+ )
115
+
116
+ mask = (
117
+ mask.squeeze(0).squeeze(0)[:height, :width].contiguous()
118
+ ) # remove padding and make contiguous
119
+ return mask
120
+
121
+ def __get_data_level_mask(self, data, sparsity_level, sparse_block_shape):
122
+ height, width = data.shape[-2], data.shape[-1]
123
+ block_height, block_width = sparse_block_shape
124
+ dh = (block_height - height % block_height) % block_height
125
+ dw = (block_width - width % block_width) % block_width
126
+
127
+ data_norm = F.avg_pool2d(
128
+ data[None, None, :],
129
+ kernel_size=sparse_block_shape,
130
+ stride=sparse_block_shape,
131
+ ceil_mode=True,
132
+ )
133
+
134
+ values_per_block = reduce(operator.mul, sparse_block_shape)
135
+
136
+ data_norm = data_norm.flatten()
137
+ num_blocks = len(data_norm)
138
+
139
+ data_norm = data_norm.repeat(
140
+ 1, values_per_block, 1
141
+ ) # get similar shape after unfold
142
+ _, sorted_idx = torch.sort(data_norm, dim=2)
143
+
144
+ threshold_idx = round(sparsity_level * num_blocks) # number of blocks to remove
145
+ sorted_idx = sorted_idx[:, :, :threshold_idx]
146
+
147
+ mask = self.__get_scatter_folded_mask(
148
+ data=data_norm,
149
+ dim=2,
150
+ indices=sorted_idx,
151
+ output_size=(height + dh, width + dw),
152
+ sparse_block_shape=sparse_block_shape,
153
+ )
154
+
155
+ mask = mask.squeeze(0).squeeze(0)[
156
+ :height, :width
157
+ ] # squeeze only the first 2 dimension
158
+ return mask
159
+
160
+ def update_mask( # type: ignore[override]
161
+ self, name, data, sparsity_level, sparse_block_shape, zeros_per_block, **kwargs
162
+ ):
163
+ values_per_block = reduce(operator.mul, sparse_block_shape)
164
+ if zeros_per_block > values_per_block:
165
+ raise ValueError(
166
+ "Number of zeros per block cannot be more than "
167
+ "the total number of elements in that block."
168
+ )
169
+ if zeros_per_block < 0:
170
+ raise ValueError("Number of zeros per block should be positive.")
171
+
172
+ if self.norm == "L1":
173
+ data_norm = torch.abs(data).squeeze() # absolute value based (L1)
174
+ else:
175
+ data_norm = (data * data).squeeze() # square every element for L2
176
+
177
+ if len(data_norm.shape) > 2: # only supports 2 dimensional data at the moment
178
+ raise ValueError("only supports 2-D at the moment")
179
+
180
+ elif len(data_norm.shape) == 1: # in case the data is bias (or 1D)
181
+ data_norm = data_norm[None, :]
182
+
183
+ mask = self.get_mask(name)
184
+ if sparsity_level <= 0 or zeros_per_block == 0:
185
+ mask.data = torch.ones_like(mask)
186
+ elif sparsity_level >= 1.0 and (zeros_per_block == values_per_block):
187
+ mask.data = torch.zeros_like(mask)
188
+
189
+ # Fetch the high level mask that zeros out entire blocks
190
+ data_lvl_mask = self.__get_data_level_mask(
191
+ data=data_norm,
192
+ sparsity_level=sparsity_level,
193
+ sparse_block_shape=sparse_block_shape,
194
+ )
195
+
196
+ # Fetch block level mask that zeros out 'zeros_per_block' number of elements in every block
197
+ block_lvl_mask = self.__get_block_level_mask(
198
+ data=data_norm,
199
+ sparse_block_shape=sparse_block_shape,
200
+ zeros_per_block=zeros_per_block,
201
+ )
202
+
203
+ # zero out the entries inside those blocks whose block is sparsified
204
+ mask.data = torch.where(data_lvl_mask == 1, data_lvl_mask, block_lvl_mask)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/_data_sparstity_utils.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+
4
+ from torch.ao.pruning._experimental.data_sparsifier.base_data_sparsifier import (
5
+ SUPPORTED_TYPES,
6
+ )
7
+
8
+
9
+ logger: logging.Logger = logging.getLogger(__name__)
10
+
11
+
12
+ def _attach_model_to_data_sparsifier(module, data_sparsifier, config=None):
13
+ """Attaches a data sparsifier to all the layers of the module.
14
+ Essentially, loop over all the weight parameters in the module and
15
+ attach it to the data sparsifier.
16
+ Note::
17
+ The '.' in the layer names are replaced with '_' (refer to _get_valid_name() below)
18
+ before attaching to the sparsifier. This is because, the data
19
+ sparsifier uses a dummy model inside to store the weight parameters.
20
+ """
21
+ if config is None:
22
+ config = {}
23
+ for name, parameter in module.named_parameters():
24
+ if type(parameter) in SUPPORTED_TYPES:
25
+ valid_name = _get_valid_name(name)
26
+ # will be defaulted to default configs
27
+ data_sparsifier.add_data(
28
+ name=valid_name, data=parameter, **config.get(valid_name, {})
29
+ )
30
+
31
+
32
+ def _get_valid_name(name):
33
+ return name.replace(".", "_") # . is not allowed as a name
34
+
35
+
36
+ def _log_sparsified_level(model, data_sparsifier) -> None:
37
+ # Show the level of sparsity AFTER step:
38
+ for name, parameter in model.named_parameters():
39
+ if type(parameter) not in SUPPORTED_TYPES:
40
+ continue
41
+ valid_name = _get_valid_name(name)
42
+ mask = data_sparsifier.get_mask(name=valid_name)
43
+ sparsity_level = 1.0 - mask.float().mean()
44
+ logger.info("Sparsity in layer %s = % .2%", name, sparsity_level)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/lightning/callbacks/data_sparsity.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections import defaultdict
3
+ from copy import deepcopy
4
+ from typing import Any, TYPE_CHECKING
5
+
6
+ import pytorch_lightning as pl # type: ignore[import]
7
+
8
+ from ._data_sparstity_utils import (
9
+ _attach_model_to_data_sparsifier,
10
+ _get_valid_name,
11
+ _log_sparsified_level,
12
+ )
13
+
14
+
15
+ if TYPE_CHECKING:
16
+ import torch
17
+
18
+
19
+ class PostTrainingDataSparsity(pl.callbacks.Callback):
20
+ """Lightning callback that enables post-training sparsity.
21
+
22
+ This callback aims to sparsify the model inside lightning module after training.
23
+ **Note that the model is copied and then sparsified, so the existing model is not modified**
24
+
25
+ The sparsified model can be used for comparison and can be accessed using
26
+ <callback_obj>.sparsified
27
+
28
+ Args:
29
+ data_sparsifier_class (some implemented class of BaseDataSparsifier)
30
+ The data sparsifier object of this class is created when the
31
+ training starts.
32
+ Note: Objects should not be passed in here as they are created
33
+ once the training completes.
34
+
35
+ data_sparsifier_args (Dict)
36
+ Dictionary of args to be passed to the data sparsifier.
37
+ Note: data_list arg should be ignored
38
+
39
+ Hooks implemented:
40
+ on_fit_end()
41
+ 1. copies the model and attaches it to the sparsifier
42
+ 2. sparsier step() is called
43
+ 3. squashes the mask()
44
+ """
45
+
46
+ def __init__(self, data_sparsifier_class, data_sparsifier_args):
47
+ super().__init__()
48
+ self.data_sparsifier_class = data_sparsifier_class
49
+ self.data_sparsifier_args = data_sparsifier_args
50
+ self.data_sparsifier: Any = None
51
+ self.sparsified: torch.nn.Module | None = None
52
+
53
+ def on_fit_end(self, trainer, pl_module) -> None:
54
+ self.sparsified = deepcopy(pl_module.model).eval()
55
+ self.data_sparsifier = self.data_sparsifier_class(**self.data_sparsifier_args)
56
+
57
+ _attach_model_to_data_sparsifier(self.sparsified, self.data_sparsifier)
58
+
59
+ self.data_sparsifier.step()
60
+
61
+ self.data_sparsifier.squash_mask() # currently squashes params for all mask
62
+
63
+ _log_sparsified_level(self.sparsified, self.data_sparsifier)
64
+
65
+
66
+ class TrainingAwareDataSparsity(pl.callbacks.Callback):
67
+ """Lightning callback that enables in-training sparsity.
68
+
69
+ This callback aims to sparsify the model inside lightning module during training.
70
+ **Note that the model is copied and then sparsified, so the existing model is not modified**
71
+
72
+ The sparsified model can be used for comparison and can be accessed using
73
+ <callback_obj>.sparsified
74
+
75
+ Args:
76
+ data_sparsifier_class (some implemented class of BaseDataSparsifier)
77
+ The data sparsifier object of this class is created when the
78
+ training starts.
79
+ Note: Objects should not be passed in here as they are created
80
+ when the training starts.
81
+
82
+ data_sparsifier_args (Dict)
83
+ Dictionary of args to be passed to the data sparsifier.
84
+ Note: data_list arg should be ignored
85
+
86
+ data_scheduler_class (some implemented class of BaseDataScheduler)
87
+ The data scheduler of this class is created when the training starts
88
+ Note: Objects should not be passed in here as they are created
89
+ when the training starts.
90
+
91
+ data_scheduler_args(Dict)
92
+ Dictionary of args to be passed to the data scheduler.
93
+ **Note: data_sparsifier arg should be ignored as the recipe
94
+ creates and pass sparsifier object into the class**
95
+
96
+ Hooks implemented:
97
+ on_train_start()
98
+ Data sparsifier and scheduler objects are created.
99
+ Pytorch model attached to the sparsifier
100
+
101
+ on_train_epoch_start()
102
+ Loads the state_dict of the data sparsifier
103
+
104
+ on_train_epoch_end()
105
+ 1. Copies the model and attaches it to the sparsifier
106
+ 2. sparsifier step() and scheduler step()
107
+ 3. Dump state_dict of the current sparsifier
108
+
109
+ on_train_end()
110
+ squash mask
111
+ """
112
+
113
+ def __init__(
114
+ self,
115
+ data_sparsifier_class,
116
+ data_sparsifier_args,
117
+ data_scheduler_class,
118
+ data_scheduler_args,
119
+ ):
120
+ super().__init__()
121
+ # data sparsifier objects
122
+ self.data_sparsifier_class = data_sparsifier_class
123
+ self.data_sparsifier_args = data_sparsifier_args
124
+
125
+ # scheduler objects
126
+ self.data_scheduler_class = data_scheduler_class
127
+ self.data_scheduler_args = data_scheduler_args
128
+
129
+ # fields
130
+ self.data_sparsifier: Any = None
131
+ self.data_scheduler: Any = None
132
+ self.sparsified: torch.nn.Module | None = None
133
+
134
+ self.data_sparsifier_state_dict: Any = None
135
+
136
+ def on_train_start(self, trainer, pl_module) -> None:
137
+ # create sparsifier
138
+ self.data_sparsifier = self.data_sparsifier_class(**self.data_sparsifier_args)
139
+ self.sparsified = deepcopy(pl_module.model)
140
+
141
+ _attach_model_to_data_sparsifier(
142
+ self.sparsified, self.data_sparsifier
143
+ ) # just to populate the base_sl in the scheduler
144
+
145
+ # create scheduler
146
+ args = deepcopy(self.data_scheduler_args)
147
+ args["data_sparsifier"] = self.data_sparsifier
148
+ self.data_scheduler = self.data_scheduler_class(**args)
149
+
150
+ def on_train_epoch_start(self, trainer, pl_module):
151
+ if self.data_sparsifier_state_dict is None:
152
+ return # probably first epoch
153
+
154
+ # load the existing config for each data
155
+ self.data_sparsifier.load_state_dict(self.data_sparsifier_state_dict)
156
+
157
+ def __create_config_based_on_state(self, pl_module):
158
+ config: dict = defaultdict()
159
+ if self.data_sparsifier_state_dict is None:
160
+ return config
161
+ for name, _ in pl_module.model.named_parameters():
162
+ valid_name = _get_valid_name(name)
163
+ config[valid_name] = self.data_sparsifier.data_groups[valid_name]
164
+
165
+ return config
166
+
167
+ def on_train_epoch_end(self, trainer, pl_module):
168
+ self.sparsified = deepcopy(pl_module.model)
169
+ config = self.__create_config_based_on_state(pl_module)
170
+
171
+ # attach model to the data sparsifier
172
+ _attach_model_to_data_sparsifier(
173
+ self.sparsified, self.data_sparsifier, config=config
174
+ )
175
+ self.data_sparsifier.step()
176
+ self.data_scheduler.step()
177
+
178
+ self.data_sparsifier_state_dict = self.data_sparsifier.state_dict()
179
+
180
+ def on_train_end(self, trainer, pl_module):
181
+ self.data_sparsifier.squash_mask()
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/data_sparsifier/quantization_utils.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ from torch.ao.pruning.sparsifier.utils import fqn_to_module, module_to_fqn
6
+
7
+
8
+ SUPPORTED_MODULES = {nn.Embedding, nn.EmbeddingBag}
9
+
10
+
11
+ def _fetch_all_embeddings(model):
12
+ """Fetches Embedding and EmbeddingBag modules from the model"""
13
+ embedding_modules = []
14
+ stack = [model]
15
+ while stack:
16
+ module = stack.pop()
17
+ for _, child in module.named_children():
18
+ fqn_name = module_to_fqn(model, child)
19
+ if type(child) in SUPPORTED_MODULES:
20
+ embedding_modules.append((fqn_name, child))
21
+ else:
22
+ stack.append(child)
23
+ return embedding_modules
24
+
25
+
26
+ def post_training_sparse_quantize(
27
+ model,
28
+ data_sparsifier_class,
29
+ sparsify_first=True,
30
+ select_embeddings: list[nn.Module] | None = None,
31
+ **sparse_config,
32
+ ):
33
+ """Takes in a model and applies sparsification and quantization to only embeddings & embeddingbags.
34
+ The quantization step can happen before or after sparsification depending on the `sparsify_first` argument.
35
+
36
+ Args:
37
+ - model (nn.Module)
38
+ model whose embeddings needs to be sparsified
39
+ - data_sparsifier_class (type of data sparsifier)
40
+ Type of sparsification that needs to be applied to model
41
+ - sparsify_first (bool)
42
+ if true, sparsifies first and then quantizes
43
+ otherwise, quantizes first and then sparsifies.
44
+ - select_embeddings (List of Embedding modules)
45
+ List of embedding modules to in the model to be sparsified & quantized.
46
+ If None, all embedding modules with be sparsified
47
+ - sparse_config (Dict)
48
+ config that will be passed to the constructor of data sparsifier object.
49
+
50
+ Note:
51
+ 1. When `sparsify_first=False`, quantization occurs first followed by sparsification.
52
+ - before sparsifying, the embedding layers are dequantized.
53
+ - scales and zero-points are saved
54
+ - embedding layers are sparsified and `squash_mask` is applied
55
+ - embedding weights are requantized using the saved scales and zero-points
56
+ 2. When `sparsify_first=True`, sparsification occurs first followed by quantization.
57
+ - embeddings are sparsified first
58
+ - quantization is applied on the sparsified embeddings
59
+ """
60
+ data_sparsifier = data_sparsifier_class(**sparse_config)
61
+
62
+ # if select_embeddings is None, perform it on all embeddings
63
+ if select_embeddings is None:
64
+ embedding_modules = _fetch_all_embeddings(model)
65
+
66
+ else:
67
+ embedding_modules = []
68
+ if not isinstance(select_embeddings, list):
69
+ raise AssertionError(
70
+ "the embedding_modules must be a list of embedding modules"
71
+ )
72
+ for emb in select_embeddings:
73
+ if type(emb) not in SUPPORTED_MODULES:
74
+ raise AssertionError(
75
+ "the embedding_modules list must be an embedding or embedding bags"
76
+ )
77
+ fqn_name = module_to_fqn(model, emb)
78
+ if fqn_name is None:
79
+ raise AssertionError(
80
+ "the embedding modules must be part of input model"
81
+ )
82
+ embedding_modules.append((fqn_name, emb))
83
+
84
+ if sparsify_first:
85
+ # sparsify
86
+ for name, emb_module in embedding_modules:
87
+ valid_name = name.replace(".", "_")
88
+ data_sparsifier.add_data(name=valid_name, data=emb_module)
89
+
90
+ data_sparsifier.step()
91
+ data_sparsifier.squash_mask()
92
+
93
+ # quantize
94
+ for _, emb_module in embedding_modules:
95
+ emb_module.qconfig = torch.ao.quantization.float_qparams_weight_only_qconfig
96
+
97
+ torch.ao.quantization.prepare(model, inplace=True)
98
+ torch.ao.quantization.convert(model, inplace=True)
99
+
100
+ else:
101
+ # quantize
102
+ for _, emb_module in embedding_modules:
103
+ emb_module.qconfig = torch.ao.quantization.float_qparams_weight_only_qconfig
104
+
105
+ torch.ao.quantization.prepare(model, inplace=True)
106
+ torch.ao.quantization.convert(model, inplace=True)
107
+
108
+ # retrieve scale & zero_points
109
+ quantize_params: dict[str, dict] = {
110
+ "scales": {},
111
+ "zero_points": {},
112
+ "dequant_weights": {},
113
+ "axis": {},
114
+ "dtype": {},
115
+ }
116
+
117
+ for name, _ in embedding_modules:
118
+ quantized_emb = fqn_to_module(model, name)
119
+ if quantized_emb is None:
120
+ raise AssertionError(f"quantized embedding {name} not found in model")
121
+
122
+ quantized_weight = quantized_emb.weight() # type: ignore[operator]
123
+ quantize_params["scales"][name] = quantized_weight.q_per_channel_scales()
124
+ quantize_params["zero_points"][name] = (
125
+ quantized_weight.q_per_channel_zero_points()
126
+ )
127
+ quantize_params["dequant_weights"][name] = torch.dequantize(
128
+ quantized_weight
129
+ )
130
+ quantize_params["axis"][name] = quantized_weight.q_per_channel_axis()
131
+ quantize_params["dtype"][name] = quantized_weight.dtype
132
+
133
+ # attach data to sparsifier
134
+ data_sparsifier.add_data(
135
+ name=name.replace(".", "_"),
136
+ data=quantize_params["dequant_weights"][name],
137
+ )
138
+
139
+ data_sparsifier.step()
140
+ data_sparsifier.squash_mask()
141
+
142
+ for name, _ in embedding_modules:
143
+ quantized_emb = fqn_to_module(model, name)
144
+ if quantized_emb is None:
145
+ raise AssertionError(f"quantized embedding {name} not found in model")
146
+ requantized_vector = torch.quantize_per_channel(
147
+ quantize_params["dequant_weights"][name],
148
+ scales=quantize_params["scales"][name],
149
+ zero_points=quantize_params["zero_points"][name],
150
+ dtype=quantize_params["dtype"][name],
151
+ axis=quantize_params["axis"][name],
152
+ )
153
+
154
+ quantized_emb.set_weight(requantized_vector) # type: ignore[operator]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/FPGM_pruner.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections.abc import Callable
3
+
4
+ import torch
5
+
6
+ from .base_structured_sparsifier import BaseStructuredSparsifier
7
+
8
+
9
+ __all__ = ["FPGMPruner"]
10
+
11
+
12
+ class FPGMPruner(BaseStructuredSparsifier):
13
+ r"""Filter Pruning via Geometric Median (FPGM) Structured Pruner
14
+ This sparsifier prune filter (row) in a tensor according to distances among filters according to
15
+ `Filter Pruning via Geometric Median for Deep Convolutional Neural Networks Acceleration <https://arxiv.org/abs/1811.00250>`_.
16
+
17
+ This sparsifier is controlled by three variables:
18
+ 1. `sparsity_level` defines the number of filters (rows) that are zeroed-out.
19
+ 2. `dist` defines the distance measurement type. Default: 3 (L2 distance).
20
+ Available options are: [1, 2, (custom callable distance function)].
21
+
22
+ Note::
23
+ Inputs should be a 4D convolutional tensor of shape (N, C, H, W).
24
+ - N: output channels size
25
+ - C: input channels size
26
+ - H: height of kernel
27
+ - W: width of kernel
28
+ """
29
+
30
+ def __init__(self, sparsity_level: float = 0.5, dist: Callable | int | None = None):
31
+ defaults = {
32
+ "sparsity_level": sparsity_level,
33
+ }
34
+
35
+ if dist is None:
36
+ dist = 2
37
+
38
+ if callable(dist):
39
+ self.dist_fn = dist
40
+ elif dist == 1:
41
+ self.dist_fn = lambda x: torch.cdist(x, x, p=1)
42
+ elif dist == 2:
43
+ self.dist_fn = lambda x: torch.cdist(x, x, p=2)
44
+ else:
45
+ raise NotImplementedError("Distance function is not yet implemented.")
46
+ super().__init__(defaults=defaults)
47
+
48
+ def _compute_distance(self, t):
49
+ r"""Compute distance across all entries in tensor `t` along all dimension
50
+ except for the one identified by dim.
51
+ Args:
52
+ t (torch.Tensor): tensor representing the parameter to prune
53
+ Returns:
54
+ distance (torch.Tensor): distance computed across filtters
55
+ """
56
+ dim = 0 # prune filter (row)
57
+
58
+ size = t.size(dim)
59
+ slc = [slice(None)] * t.dim()
60
+
61
+ # flatten the tensor along the dimension
62
+ t_flatten = [
63
+ t[tuple(slc[:dim] + [slice(i, i + 1)] + slc[dim + 1 :])].reshape(-1)
64
+ for i in range(size)
65
+ ]
66
+ t_flatten = torch.stack(t_flatten)
67
+
68
+ # distance measurement
69
+ dist_matrix = self.dist_fn(t_flatten)
70
+
71
+ # more similar with other filter indicates large in the sum of row
72
+ # pyrefly: ignore [bad-argument-type]
73
+ distance = torch.sum(torch.abs(dist_matrix), 1)
74
+
75
+ return distance
76
+
77
+ def update_mask( # type: ignore[override]
78
+ self, module, tensor_name, sparsity_level, **kwargs
79
+ ):
80
+ tensor_weight = getattr(module, tensor_name)
81
+ mask = getattr(module.parametrizations, tensor_name)[0].mask
82
+
83
+ if sparsity_level <= 0:
84
+ mask.data = torch.ones_like(mask).bool()
85
+ elif sparsity_level >= 1.0:
86
+ mask.data = torch.zeros_like(mask).bool()
87
+ else:
88
+ distance = self._compute_distance(tensor_weight)
89
+
90
+ tensor_size = tensor_weight.shape[0] # prune filter (row)
91
+ nparams_toprune = round(sparsity_level * tensor_size)
92
+ nparams_toprune = min(
93
+ max(nparams_toprune, 0), tensor_size
94
+ ) # clamp to [0, tensor_size]
95
+ topk = torch.topk(distance, k=nparams_toprune, largest=False)
96
+ mask[topk.indices] = False
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .base_structured_sparsifier import BaseStructuredSparsifier
2
+ from .FPGM_pruner import FPGMPruner
3
+ from .lstm_saliency_pruner import LSTMSaliencyPruner
4
+ from .parametrization import BiasHook, FakeStructuredSparsity
5
+ from .saliency_pruner import SaliencyPruner
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/base_structured_sparsifier.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections.abc import Callable
3
+ from itertools import chain
4
+ from operator import getitem
5
+
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from torch import nn
9
+ from torch.ao.pruning.sparsifier.base_sparsifier import BaseSparsifier
10
+ from torch.fx import symbolic_trace
11
+ from torch.nn.utils import parametrize
12
+
13
+ from .match_utils import apply_match, MatchAllNode
14
+ from .parametrization import BiasHook, FakeStructuredSparsity, module_contains_param
15
+ from .prune_functions import (
16
+ prune_conv2d,
17
+ prune_conv2d_activation_conv2d,
18
+ prune_conv2d_activation_pool_conv2d,
19
+ prune_conv2d_conv2d,
20
+ prune_conv2d_pool_activation_conv2d,
21
+ prune_conv2d_pool_flatten_linear,
22
+ prune_linear,
23
+ prune_linear_activation_linear,
24
+ prune_linear_linear,
25
+ prune_lstm_output_layernorm_linear,
26
+ prune_lstm_output_linear,
27
+ )
28
+
29
+
30
+ def _get_supported_structured_pruning_modules():
31
+ SUPPORTED_STRUCTURED_PRUNING_MODULES = { # added to config if None given
32
+ nn.Linear,
33
+ nn.Conv2d,
34
+ nn.LSTM,
35
+ }
36
+ return SUPPORTED_STRUCTURED_PRUNING_MODULES
37
+
38
+
39
+ def _get_supported_activation_functions():
40
+ SUPPORTED_ACTIVATION_FUNCTIONS = {
41
+ F.relu,
42
+ F.rrelu,
43
+ F.hardtanh,
44
+ F.relu6,
45
+ F.sigmoid,
46
+ F.hardsigmoid,
47
+ F.tanh,
48
+ F.silu,
49
+ F.mish,
50
+ F.hardswish,
51
+ F.elu,
52
+ F.celu,
53
+ F.selu,
54
+ F.hardshrink,
55
+ F.leaky_relu,
56
+ F.logsigmoid,
57
+ F.softplus,
58
+ F.prelu,
59
+ F.softsign,
60
+ F.tanhshrink,
61
+ F.gelu,
62
+ }
63
+ return SUPPORTED_ACTIVATION_FUNCTIONS
64
+
65
+
66
+ def _get_supported_activation_modules():
67
+ SUPPORTED_ACTIVATION_MODULES = {
68
+ nn.ReLU,
69
+ nn.RReLU,
70
+ nn.Hardtanh,
71
+ nn.ReLU6,
72
+ nn.Sigmoid,
73
+ nn.Hardsigmoid,
74
+ nn.Tanh,
75
+ nn.SiLU,
76
+ nn.Mish,
77
+ nn.Hardswish,
78
+ nn.ELU,
79
+ nn.CELU,
80
+ nn.SELU,
81
+ nn.Hardshrink,
82
+ nn.LeakyReLU,
83
+ nn.LogSigmoid,
84
+ nn.Softplus,
85
+ nn.PReLU,
86
+ nn.Softsign,
87
+ nn.Tanhshrink,
88
+ nn.GELU,
89
+ }
90
+ return SUPPORTED_ACTIVATION_MODULES
91
+
92
+
93
+ def _get_default_structured_pruning_patterns() -> dict[
94
+ tuple[type[nn.Module] | Callable | MatchAllNode | str, ...],
95
+ Callable[..., None],
96
+ ]:
97
+ """
98
+ Returns the patterns for conv2d / linear conversion for each element in the activation functions/modules defined above.
99
+ """
100
+ patterns: dict[
101
+ tuple[type[nn.Module] | Callable | MatchAllNode | str, ...],
102
+ Callable[..., None],
103
+ ] = {
104
+ # linear -> linear
105
+ (nn.Linear, "output"): prune_linear,
106
+ (nn.Linear, nn.Linear): prune_linear_linear,
107
+ # conv2d -> conv2d
108
+ (nn.Conv2d, "output"): prune_conv2d,
109
+ (nn.Conv2d, nn.Conv2d): prune_conv2d_conv2d,
110
+ # TODO LSTM Structured pruning does not support returned state currently.
111
+ # Should find a way to explicitly match getitem(0) instead of getitem.
112
+ # This will also require changing the pruning function.
113
+ # lstm -> getitem(0) -> linear
114
+ (nn.LSTM, getitem, nn.Linear): prune_lstm_output_linear,
115
+ # lstm -> getitem(0) -> layernorm -> linear
116
+ (nn.LSTM, getitem, nn.LayerNorm, nn.Linear): prune_lstm_output_layernorm_linear,
117
+ }
118
+
119
+ for activation in chain(
120
+ _get_supported_activation_functions(), _get_supported_activation_modules()
121
+ ):
122
+ patterns.update(
123
+ {
124
+ # linear -> activation -> linear
125
+ (nn.Linear, activation, nn.Linear): prune_linear_activation_linear,
126
+ # conv2d -> activation -> conv2d
127
+ (nn.Conv2d, activation, nn.Conv2d): prune_conv2d_activation_conv2d,
128
+ # conv2d -> activation -> pool -> conv2d
129
+ (
130
+ nn.Conv2d,
131
+ activation,
132
+ nn.AvgPool2d,
133
+ nn.Conv2d,
134
+ ): prune_conv2d_activation_pool_conv2d,
135
+ (
136
+ nn.Conv2d,
137
+ activation,
138
+ F.avg_pool2d,
139
+ nn.Conv2d,
140
+ ): prune_conv2d_activation_pool_conv2d,
141
+ (
142
+ nn.Conv2d,
143
+ activation,
144
+ nn.MaxPool2d,
145
+ nn.Conv2d,
146
+ ): prune_conv2d_activation_pool_conv2d,
147
+ (
148
+ nn.Conv2d,
149
+ activation,
150
+ F.max_pool2d,
151
+ nn.Conv2d,
152
+ ): prune_conv2d_activation_pool_conv2d,
153
+ # conv2d -> pool -> activation -> conv2d
154
+ (
155
+ nn.Conv2d,
156
+ nn.AvgPool2d,
157
+ activation,
158
+ nn.Conv2d,
159
+ ): prune_conv2d_pool_activation_conv2d,
160
+ (
161
+ nn.Conv2d,
162
+ F.avg_pool2d,
163
+ activation,
164
+ nn.Conv2d,
165
+ ): prune_conv2d_pool_activation_conv2d,
166
+ (
167
+ nn.Conv2d,
168
+ nn.MaxPool2d,
169
+ activation,
170
+ nn.Conv2d,
171
+ ): prune_conv2d_pool_activation_conv2d,
172
+ (
173
+ nn.Conv2d,
174
+ F.max_pool2d,
175
+ activation,
176
+ nn.Conv2d,
177
+ ): prune_conv2d_pool_activation_conv2d,
178
+ # conv2d -> adaptive pool -> flatten -> linear
179
+ (
180
+ nn.Conv2d,
181
+ nn.AdaptiveAvgPool2d,
182
+ nn.Flatten,
183
+ nn.Linear,
184
+ ): prune_conv2d_pool_flatten_linear,
185
+ (
186
+ nn.Conv2d,
187
+ nn.AdaptiveAvgPool2d,
188
+ torch.flatten,
189
+ nn.Linear,
190
+ ): prune_conv2d_pool_flatten_linear,
191
+ (
192
+ nn.Conv2d,
193
+ nn.AdaptiveMaxPool2d,
194
+ nn.Flatten,
195
+ nn.Linear,
196
+ ): prune_conv2d_pool_flatten_linear,
197
+ (
198
+ nn.Conv2d,
199
+ nn.AdaptiveMaxPool2d,
200
+ torch.flatten,
201
+ nn.Linear,
202
+ ): prune_conv2d_pool_flatten_linear,
203
+ }
204
+ )
205
+ return patterns
206
+
207
+
208
+ class BaseStructuredSparsifier(BaseSparsifier):
209
+ r"""Base class for structured pruning.
210
+
211
+ Abstract methods that need to be implemented:
212
+ - update_mask: Function to compute a new mask for all keys in the
213
+ `groups` attribute.
214
+
215
+ Args:
216
+ - defaults [dict]: default configurations will be attached to the
217
+ configuration. Only the keys that don't exist in the `config` will
218
+ be updated.
219
+ """
220
+
221
+ def __init__(self, defaults, patterns=None):
222
+ super().__init__(defaults)
223
+ if patterns is None:
224
+ patterns = _get_default_structured_pruning_patterns()
225
+ self.patterns = patterns
226
+
227
+ def make_config_from_model(
228
+ self,
229
+ model: nn.Module,
230
+ SUPPORTED_MODULES: set[type] | None = None,
231
+ ) -> None:
232
+ if SUPPORTED_MODULES is None:
233
+ SUPPORTED_MODULES = _get_supported_structured_pruning_modules()
234
+ super().make_config_from_model(model, SUPPORTED_MODULES=SUPPORTED_MODULES)
235
+
236
+ def _prepare(self, *args, **kwargs) -> None:
237
+ r"""This function will attach the FakeStructuredSparsity parameterizations
238
+ and BiasHooks at the appropriate points in the model.
239
+ """
240
+ for config in self.groups:
241
+ module = config["module"]
242
+ tensor_name = config["tensor_name"]
243
+ parametrization = config.get("parametrization", FakeStructuredSparsity)
244
+ tensor = getattr(module, tensor_name)
245
+
246
+ mask = config.get(
247
+ "mask",
248
+ torch.ones(tensor.shape[0], dtype=torch.bool, device=tensor.device),
249
+ )
250
+ self.state[config["tensor_fqn"]]["mask"] = mask
251
+ parametrize.register_parametrization(
252
+ module, tensor_name, parametrization(mask)
253
+ )
254
+
255
+ # if linear / conv, we add in bias hooks
256
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
257
+ prune_bias = config.get("prune_bias", True)
258
+ if module.bias is not None:
259
+ module.register_parameter(
260
+ "_bias", nn.Parameter(module.bias.detach())
261
+ )
262
+ # pyrefly: ignore [bad-assignment]
263
+ module.bias = None
264
+ module.prune_bias = prune_bias
265
+
266
+ module.register_forward_hook(
267
+ BiasHook(module.parametrizations.weight[0], prune_bias) # type: ignore[union-attr, index]
268
+ )
269
+
270
+ def prune(self) -> None:
271
+ r"""
272
+ This function will FX symbolically trace the model and then find instances of the patterns
273
+ defined in self.patterns (by default SUPPORTED_STRUCTURED_PRUNING_PATTERNS ).
274
+
275
+ For each pattern, it will apply to corresponding conversion function, which will modify the output
276
+ and input size expected by the modules within the pattern
277
+ """
278
+
279
+ self.traced = symbolic_trace(self.model)
280
+ modules = dict(self.traced.named_modules())
281
+
282
+ # Right now we check for matches simply by iterating across all the patterns
283
+ # if this is slow we can store patterns in a trie-structure and modify this code for faster lookup
284
+ for node in self.traced.graph.nodes:
285
+ for pattern, convert_fn in self.patterns.items():
286
+ matched = apply_match(modules, pattern, node, [])
287
+ if matched is None:
288
+ continue
289
+
290
+ first_module = modules.get(node.target)
291
+ # check if first module exists and has appropriate parameterization, otherwise skip
292
+ if (
293
+ first_module is not None
294
+ and parametrize.is_parametrized(first_module)
295
+ and module_contains_param(first_module, FakeStructuredSparsity)
296
+ ):
297
+ convert_block = []
298
+ for node in matched:
299
+ if node.op == "call_module":
300
+ convert_block.append(modules.get(node.target))
301
+ elif node.op == "call_function":
302
+ convert_block.append(node.target)
303
+ convert_fn(*convert_block)
304
+
305
+ for module in self.traced.modules():
306
+ if module_contains_param(module, FakeStructuredSparsity):
307
+ raise Exception( # noqa: TRY002
308
+ f"Error: {module} still contains FakeStructuredSparsity parametrizations!"
309
+ )
310
+
311
+ self.traced.graph.lint()
312
+ self.traced.recompile()
313
+ return self.traced # type: ignore[return-value]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/lstm_saliency_pruner.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, cast
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+ from .base_structured_sparsifier import BaseStructuredSparsifier
7
+ from .parametrization import FakeStructuredSparsity
8
+
9
+
10
+ class LSTMSaliencyPruner(BaseStructuredSparsifier):
11
+ """
12
+ Prune packed LSTM weights based on saliency.
13
+ For each layer {k} inside a LSTM, we have two packed weight matrices
14
+ - weight_ih_l{k}
15
+ - weight_hh_l{k}
16
+
17
+ These tensors pack the weights for the 4 linear layers together for efficiency.
18
+
19
+ [W_ii | W_if | W_ig | W_io]
20
+
21
+ Pruning this tensor directly will lead to weights being misassigned when unpacked.
22
+ To ensure that each packed linear layer is pruned the same amount:
23
+ 1. We split the packed weight into the 4 constituent linear parts
24
+ 2. Update the mask for each individual piece using saliency individually
25
+
26
+ This applies to both weight_ih_l{k} and weight_hh_l{k}.
27
+ """
28
+
29
+ def update_mask(self, module: nn.Module, tensor_name: str, **kwargs: Any) -> None:
30
+ weights = getattr(module, tensor_name)
31
+
32
+ for p in getattr(module.parametrizations, tensor_name):
33
+ if isinstance(p, FakeStructuredSparsity):
34
+ mask = cast(torch.Tensor, p.mask)
35
+
36
+ # select weights based on magnitude
37
+ if weights.dim() <= 1:
38
+ raise Exception( # noqa: TRY002
39
+ "Structured pruning can only be applied to a 2+dim weight tensor!"
40
+ )
41
+ # take norm over all but first dim
42
+ dims = tuple(range(1, weights.dim()))
43
+ saliency = weights.norm(dim=dims, p=1)
44
+
45
+ # handle weights in 4 groups
46
+ split_size = len(mask) // 4
47
+ masks = torch.split(mask, split_size)
48
+ saliencies = torch.split(saliency, split_size)
49
+
50
+ for keep_mask, sal in zip(masks, saliencies):
51
+ # mask smallest k values to be removed
52
+ k = int(len(keep_mask) * kwargs["sparsity_level"])
53
+ prune = sal.topk(k, largest=False, sorted=False).indices
54
+ keep_mask.data[prune] = False # modifies underlying p.mask directly
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/match_utils.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Contains utility functions to check if a pattern is in the graph and return the matching nodes
3
+ """
4
+
5
+ from typing import Any
6
+
7
+ import torch
8
+ from torch import nn
9
+ from torch.ao.quantization.utils import MatchAllNode
10
+ from torch.fx import Node
11
+ from torch.nn.utils import parametrize
12
+
13
+
14
+ def _match(
15
+ modules: dict[str, nn.ModuleDict],
16
+ node: Node,
17
+ current: nn.Module | Any,
18
+ ) -> bool:
19
+ r"""
20
+ checks to see if a single node of a pattern matches
21
+ """
22
+ if isinstance(current, type) and issubclass(current, MatchAllNode):
23
+ return True
24
+ if not isinstance(node, Node):
25
+ return False
26
+ if isinstance(current, type) and issubclass(current, torch.nn.Module):
27
+ return (
28
+ node.op == "call_module"
29
+ and parametrize.type_before_parametrizations(modules[node.target]) # type: ignore[index]
30
+ == current
31
+ )
32
+ elif callable(current):
33
+ return node.op == "call_function" and node.target is current
34
+ elif isinstance(current, str):
35
+ return node.target == current
36
+ return False
37
+
38
+
39
+ def apply_match(
40
+ modules: dict[str, nn.ModuleDict],
41
+ pattern: tuple[Any] | Any,
42
+ node: Node,
43
+ matched_node_pattern: list[Node],
44
+ ) -> list[Node] | None:
45
+ r"""
46
+ This function will return the matched nodes if the pattern matches the node given
47
+ If there is no match, it will return None
48
+ """
49
+ if isinstance(pattern, tuple):
50
+ if len(pattern) == 1:
51
+ if _match(modules, node, pattern[0]):
52
+ return matched_node_pattern + [node]
53
+
54
+ first, *rest = pattern
55
+ if _match(modules, node, first):
56
+ if rest is None:
57
+ return matched_node_pattern + [node]
58
+
59
+ for user in node.users:
60
+ return apply_match(
61
+ modules, tuple(rest), user, matched_node_pattern + [node]
62
+ )
63
+ elif _match(modules, node, pattern):
64
+ return [node]
65
+ return None
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/parametrization.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ from torch import nn
4
+ from torch.nn.utils.parametrize import is_parametrized
5
+
6
+
7
+ def module_contains_param(module, parametrization):
8
+ if is_parametrized(module):
9
+ # see if any of the module tensors have a parametriztion attached that matches the one passed in
10
+ return any(
11
+ any(isinstance(param, parametrization) for param in param_list)
12
+ for key, param_list in module.parametrizations.items()
13
+ )
14
+ return False
15
+
16
+
17
+ # Structured Pruning Parameterizations
18
+ class FakeStructuredSparsity(nn.Module):
19
+ r"""
20
+ Parametrization for Structured Pruning. Like FakeSparsity, this should be attached to
21
+ the 'weight' or any other parameter that requires a mask.
22
+
23
+ Instead of an element-wise bool mask, this parameterization uses a row-wise bool mask.
24
+ """
25
+
26
+ def __init__(self, mask):
27
+ super().__init__()
28
+ self.register_buffer("mask", mask)
29
+
30
+ def forward(self, x):
31
+ if not isinstance(self.mask, torch.Tensor):
32
+ raise AssertionError("mask must be a torch.Tensor")
33
+ if self.mask.shape[0] != x.shape[0]:
34
+ raise AssertionError(
35
+ f"mask shape[0] ({self.mask.shape[0]}) must match x shape[0] ({x.shape[0]})"
36
+ )
37
+ shape = [1] * len(x.shape)
38
+ shape[0] = -1
39
+ return self.mask.reshape(shape) * x
40
+
41
+ def state_dict(self, *args, **kwargs):
42
+ # avoid double saving masks
43
+ return {}
44
+
45
+
46
+ class BiasHook:
47
+ def __init__(self, parametrization, prune_bias):
48
+ self.param = parametrization
49
+ self.prune_bias = prune_bias
50
+
51
+ def __call__(self, module, input, output):
52
+ if getattr(module, "_bias", None) is not None:
53
+ bias = module._bias.data
54
+ if self.prune_bias:
55
+ bias[~self.param.mask] = 0
56
+
57
+ # reshape bias to broadcast over output dimensions
58
+ idx = [1] * len(output.shape)
59
+ idx[1] = -1
60
+ bias = bias.reshape(idx)
61
+
62
+ output += bias
63
+ return output
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/prune_functions.py ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ Collection of conversion functions for linear / conv2d structured pruning
4
+ Also contains utilities for bias propagation
5
+ """
6
+
7
+ from collections.abc import Callable
8
+ from typing import cast
9
+
10
+ import torch
11
+ from torch import nn, Tensor
12
+ from torch.nn.utils import parametrize
13
+ from torch.nn.utils.parametrize import ParametrizationList
14
+
15
+ from .parametrization import BiasHook, FakeStructuredSparsity
16
+
17
+
18
+ # BIAS PROPAGATION
19
+ def _remove_bias_handles(module: nn.Module) -> None:
20
+ if hasattr(module, "_forward_hooks"):
21
+ bias_hooks: list[int] = []
22
+ for key, hook in module._forward_hooks.items():
23
+ if isinstance(hook, BiasHook):
24
+ bias_hooks.append(key)
25
+
26
+ for key in bias_hooks:
27
+ del module._forward_hooks[key]
28
+
29
+
30
+ def _get_adjusted_next_layer_bias(
31
+ next_layer: nn.Module, pruned_biases: Tensor, mask: Tensor
32
+ ) -> nn.Parameter:
33
+ r"""Returns new adjusted bias for the second supported module"""
34
+ if parametrize.is_parametrized(next_layer):
35
+ # need to access original weight
36
+ parametrization_dict = cast(nn.ModuleDict, next_layer.parametrizations)
37
+ weight_parameterizations = cast(
38
+ ParametrizationList, parametrization_dict.weight
39
+ )
40
+ next_weight = weight_parameterizations.original
41
+ else:
42
+ next_weight = cast(Tensor, next_layer.weight)
43
+
44
+ scaling_weight = next_weight[:, ~mask]
45
+ if isinstance(next_layer, nn.Conv2d): # checking for Conv2d
46
+ # Propagating first layer pruned biases and calculating the new second layer bias
47
+ # involves more steps since the Conv2d scaling weight has extra dimensions,
48
+ # so adding bias involves broadcasting, logically:
49
+ # for each channel k in range(oC):
50
+ # scaled_biases = sum(first_bias[pruned_idx] @ next_weight[k, pruned_idx, :, :].T)
51
+ # new_next_bias[k] = old_next_bias[k] + scaled_biases
52
+ scaling_product = torch.matmul(
53
+ pruned_biases.reshape(1, -1), torch.transpose(scaling_weight, 1, 2)
54
+ )
55
+ sum_range = list(range(len(scaling_product.shape)))[
56
+ 1:
57
+ ] # all but the first dimension
58
+ scaled_biases = torch.sum(scaling_product, sum_range)
59
+ elif isinstance(next_layer, nn.Linear): # Linear
60
+ scaled_biases = torch.matmul(
61
+ pruned_biases, torch.transpose(scaling_weight, 0, 1)
62
+ ) # recall b2_new = b1 @ w2.T + b2
63
+ else:
64
+ raise NotImplementedError(f"Type {type(next_layer)} not supported yet.")
65
+
66
+ if (
67
+ parametrize.is_parametrized(next_layer)
68
+ and getattr(next_layer, "_bias", None) is not None
69
+ ): # next_layer is parametrized & has original bias ._bias
70
+ adjusted_bias = nn.Parameter(scaled_biases + next_layer._bias) # type: ignore[operator]
71
+ elif (
72
+ not parametrize.is_parametrized(next_layer) and next_layer.bias is not None
73
+ ): # next_layer not parametrized & has .bias
74
+ adjusted_bias = nn.Parameter(scaled_biases + next_layer.bias) # type: ignore[operator]
75
+ else: # next_layer has no bias
76
+ adjusted_bias = nn.Parameter(scaled_biases)
77
+ return adjusted_bias
78
+
79
+
80
+ def _prune_module_bias(module: nn.Module, mask: Tensor) -> None:
81
+ r"""Applies mask to given modules bias"""
82
+ # prune bias along with weights, discard pruned indices of bias
83
+ original_bias = cast(Tensor, getattr(module, "_bias", module.bias))
84
+ if original_bias is not None:
85
+ module.bias = nn.Parameter(original_bias[mask])
86
+
87
+ # remove _bias parameter
88
+ if hasattr(module, "_bias"):
89
+ delattr(module, "_bias")
90
+
91
+
92
+ def _propagate_module_bias(module: nn.Module, mask: Tensor) -> Tensor | None:
93
+ r"""
94
+ In the case that we need to propagate biases, this function will return the biases we need
95
+ """
96
+ # set current module bias
97
+ if module.bias is not None:
98
+ module.bias = nn.Parameter(cast(Tensor, module.bias)[mask])
99
+ elif getattr(module, "_bias", None) is not None:
100
+ # pyrefly: ignore [bad-assignment]
101
+ module.bias = nn.Parameter(cast(Tensor, module._bias)[mask])
102
+
103
+ # get pruned biases to propagate to subsequent layer
104
+ if getattr(module, "_bias", None) is not None:
105
+ pruned_biases = cast(Tensor, module._bias)[~mask]
106
+ else:
107
+ pruned_biases = None
108
+
109
+ if hasattr(module, "_bias"):
110
+ delattr(module, "_bias")
111
+
112
+ return pruned_biases
113
+
114
+
115
+ # LINEAR
116
+ def _prune_linear_helper(linear: nn.Linear) -> Tensor:
117
+ # expects linear to be a parameterized linear module
118
+ parametrization_dict = cast(nn.ModuleDict, linear.parametrizations)
119
+ weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
120
+ for p in weight_parameterizations:
121
+ if isinstance(p, FakeStructuredSparsity):
122
+ mask = cast(Tensor, p.mask)
123
+
124
+ with torch.no_grad():
125
+ parametrize.remove_parametrizations(linear, "weight", leave_parametrized=True)
126
+ linear.weight = nn.Parameter(linear.weight[mask]) # type: ignore[possibly-undefined]
127
+ linear.out_features = linear.weight.shape[0]
128
+ _remove_bias_handles(linear)
129
+
130
+ # pyrefly: ignore [unbound-name]
131
+ return mask
132
+
133
+
134
+ def prune_linear(linear: nn.Linear) -> None:
135
+ mask = _prune_linear_helper(linear)
136
+ if getattr(linear, "prune_bias", False):
137
+ _prune_module_bias(linear, mask)
138
+
139
+
140
+ def prune_linear_linear(linear1: nn.Linear, linear2: nn.Linear) -> None:
141
+ prune_linear_activation_linear(linear1, None, linear2)
142
+
143
+
144
+ def prune_linear_activation_linear(
145
+ linear1: nn.Linear,
146
+ activation: Callable[[Tensor], Tensor] | None,
147
+ linear2: nn.Linear,
148
+ ):
149
+ mask = _prune_linear_helper(linear1)
150
+ if getattr(linear1, "prune_bias", False):
151
+ _prune_module_bias(linear1, mask)
152
+ else:
153
+ pruned_biases = _propagate_module_bias(linear1, mask)
154
+ if pruned_biases is not None:
155
+ if activation:
156
+ pruned_biases = activation(pruned_biases)
157
+ linear2.bias = _get_adjusted_next_layer_bias(linear2, pruned_biases, mask)
158
+
159
+ with torch.no_grad():
160
+ if parametrize.is_parametrized(linear2):
161
+ parametrization_dict = cast(nn.ModuleDict, linear2.parametrizations)
162
+ weight_parameterizations = cast(
163
+ ParametrizationList, parametrization_dict.weight
164
+ )
165
+
166
+ weight_parameterizations.original = nn.Parameter(
167
+ weight_parameterizations.original[:, mask]
168
+ )
169
+ linear2.in_features = weight_parameterizations.original.shape[1]
170
+ else:
171
+ linear2.weight = nn.Parameter(linear2.weight[:, mask])
172
+ linear2.in_features = linear2.weight.shape[1]
173
+
174
+
175
+ # CONV2D
176
+ def _prune_conv2d_helper(conv2d: nn.Conv2d) -> Tensor:
177
+ parametrization_dict = cast(nn.ModuleDict, conv2d.parametrizations)
178
+ weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
179
+ for p in weight_parameterizations:
180
+ if isinstance(p, FakeStructuredSparsity):
181
+ mask = cast(Tensor, p.mask)
182
+
183
+ with torch.no_grad():
184
+ parametrize.remove_parametrizations(conv2d, "weight", leave_parametrized=True)
185
+ conv2d.weight = nn.Parameter(conv2d.weight[mask]) # type: ignore[possibly-undefined]
186
+ conv2d.out_channels = conv2d.weight.shape[0]
187
+
188
+ _remove_bias_handles(conv2d)
189
+ # pyrefly: ignore [unbound-name]
190
+ return mask
191
+
192
+
193
+ def prune_conv2d_padded(conv2d_1: nn.Conv2d) -> None:
194
+ parametrization_dict = cast(nn.ModuleDict, conv2d_1.parametrizations)
195
+ weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
196
+ for p in weight_parameterizations:
197
+ if isinstance(p, FakeStructuredSparsity):
198
+ mask = cast(Tensor, p.mask)
199
+
200
+ with torch.no_grad():
201
+ parametrize.remove_parametrizations(conv2d_1, "weight", leave_parametrized=True)
202
+
203
+ if getattr(conv2d_1, "_bias", None) is not None:
204
+ if (
205
+ conv2d_1.bias is not None
206
+ ): # conv2d_1 has original bias and bias propagated from previous layer
207
+ new_bias = torch.zeros(conv2d_1.bias.shape)
208
+ new_bias[mask] = conv2d_1.bias[mask] # type: ignore[possibly-undefined]
209
+ # adjusted bias that to keep in conv2d_1
210
+ # pyrefly: ignore [unbound-name]
211
+ new_bias[~mask] = cast(Tensor, conv2d_1._bias)[~mask]
212
+ # pruned biases that are kept instead of propagated
213
+ conv2d_1.bias = nn.Parameter(new_bias)
214
+ else: # conv2d_1 has only original bias
215
+ conv2d_1.bias = nn.Parameter(cast(Tensor, conv2d_1._bias))
216
+ else:
217
+ # no original bias, only propagated bias
218
+ if (
219
+ conv2d_1.bias is not None
220
+ ): # conv2d_1 has bias propagated from previous layer
221
+ conv2d_1.bias.data[~mask] = 0 # type: ignore[possibly-undefined]
222
+
223
+ if hasattr(conv2d_1, "_bias"):
224
+ delattr(conv2d_1, "_bias")
225
+
226
+
227
+ def prune_conv2d(conv2d: nn.Conv2d) -> None:
228
+ mask = _prune_conv2d_helper(conv2d)
229
+ if getattr(conv2d, "prune_bias", False):
230
+ _prune_module_bias(conv2d, mask)
231
+
232
+
233
+ def prune_conv2d_conv2d(conv2d_1: nn.Conv2d, conv2d_2: nn.Conv2d) -> None:
234
+ prune_conv2d_activation_conv2d(conv2d_1, None, conv2d_2)
235
+
236
+
237
+ def prune_conv2d_activation_conv2d(
238
+ conv2d_1: nn.Conv2d,
239
+ activation: Callable[[Tensor], Tensor] | None,
240
+ conv2d_2: nn.Conv2d,
241
+ ):
242
+ r"""
243
+ Fusion Pattern for conv2d -> some activation module / function -> conv2d layers
244
+ """
245
+ parametrization_dict = cast(nn.ModuleDict, conv2d_1.parametrizations)
246
+ weight_parameterizations = cast(ParametrizationList, parametrization_dict.weight)
247
+ for p in weight_parameterizations:
248
+ if isinstance(p, FakeStructuredSparsity):
249
+ mask = cast(Tensor, p.mask)
250
+
251
+ prune_bias = getattr(conv2d_1, "prune_bias", False)
252
+ if (
253
+ hasattr(conv2d_2, "padding")
254
+ and cast(tuple[int], conv2d_2.padding) > (0, 0)
255
+ and (conv2d_1.bias is not None or getattr(conv2d_1, "_bias", None) is not None)
256
+ ):
257
+ prune_conv2d_padded(conv2d_1)
258
+ else:
259
+ mask = _prune_conv2d_helper(conv2d_1)
260
+ if prune_bias:
261
+ _prune_module_bias(conv2d_1, mask)
262
+ else:
263
+ pruned_biases = _propagate_module_bias(conv2d_1, mask)
264
+ if pruned_biases is not None:
265
+ if activation:
266
+ pruned_biases = activation(pruned_biases)
267
+ conv2d_2.bias = _get_adjusted_next_layer_bias(
268
+ conv2d_2, pruned_biases, mask
269
+ )
270
+
271
+ if (
272
+ not (
273
+ hasattr(conv2d_2, "padding")
274
+ and cast(tuple[int], conv2d_2.padding) > (0, 0)
275
+ )
276
+ or conv2d_1.bias is None
277
+ ):
278
+ with torch.no_grad():
279
+ if parametrize.is_parametrized(conv2d_2):
280
+ parametrization_dict = cast(
281
+ nn.ModuleDict, conv2d_2.parametrizations
282
+ )
283
+ weight_parameterizations = cast(
284
+ ParametrizationList, parametrization_dict.weight
285
+ )
286
+ weight_parameterizations.original = nn.Parameter(
287
+ weight_parameterizations.original[:, mask]
288
+ )
289
+ conv2d_2.in_channels = weight_parameterizations.original.shape[1]
290
+ else:
291
+ conv2d_2.weight = nn.Parameter(conv2d_2.weight[:, mask])
292
+ conv2d_2.in_channels = conv2d_2.weight.shape[1]
293
+
294
+
295
+ def prune_conv2d_pool_activation_conv2d(
296
+ c1: nn.Conv2d,
297
+ pool: nn.Module,
298
+ activation: Callable[[Tensor], Tensor] | None,
299
+ c2: nn.Conv2d,
300
+ ) -> None:
301
+ prune_conv2d_activation_conv2d(c1, activation, c2)
302
+
303
+
304
+ def prune_conv2d_activation_pool_conv2d(
305
+ c1: nn.Conv2d,
306
+ activation: Callable[[Tensor], Tensor] | None,
307
+ pool: nn.Module,
308
+ c2: nn.Conv2d,
309
+ ) -> None:
310
+ prune_conv2d_activation_conv2d(c1, activation, c2)
311
+
312
+
313
+ def prune_conv2d_pool_flatten_linear(
314
+ conv2d: nn.Conv2d,
315
+ pool: nn.Module,
316
+ flatten: Callable[[Tensor], Tensor] | None,
317
+ linear: nn.Linear,
318
+ ) -> None:
319
+ mask = _prune_conv2d_helper(conv2d)
320
+
321
+ # We map the pruned indices of the Conv2d output to the flattened indices of the Linear following the Flatten layer.
322
+ # we determine the flattening scale (h * w), and readjust `first_pruned_indices`
323
+ # (each idx maps to range idx * h * w to (idx+1) * h * w), `first_valid_indices`,
324
+ # and `pruned_biases` (repeat each bias by h * w).
325
+ if parametrize.is_parametrized(linear):
326
+ parametrization_dict = cast(nn.ModuleDict, linear.parametrizations)
327
+ weight_parameterizations = cast(
328
+ ParametrizationList, parametrization_dict.weight
329
+ )
330
+ linear_ic = weight_parameterizations.original.shape[1]
331
+ else:
332
+ linear_ic = linear.weight.shape[1]
333
+
334
+ conv2d_oc = len(mask)
335
+ if linear_ic % conv2d_oc != 0:
336
+ raise AssertionError(
337
+ f"Flattening from dimensions {conv2d_oc} to {linear_ic} not supported"
338
+ )
339
+
340
+ flatten_scale = linear_ic // conv2d_oc
341
+ flattened_mask = torch.tensor(
342
+ [[val] * flatten_scale for val in mask], dtype=torch.bool, device=mask.device
343
+ ).flatten()
344
+
345
+ if getattr(conv2d, "prune_bias", False):
346
+ _prune_module_bias(conv2d, mask)
347
+ else:
348
+ pruned_biases = cast(Tensor, _propagate_module_bias(conv2d, mask))
349
+ flattened_pruned_biases = torch.tensor(
350
+ [[bias] * flatten_scale for bias in pruned_biases], device=mask.device
351
+ ).flatten()
352
+ linear.bias = _get_adjusted_next_layer_bias(
353
+ linear, flattened_pruned_biases, flattened_mask
354
+ )
355
+
356
+ with torch.no_grad():
357
+ if parametrize.is_parametrized(linear):
358
+ parametrization_dict = cast(nn.ModuleDict, linear.parametrizations)
359
+ weight_parameterizations = cast(
360
+ ParametrizationList, parametrization_dict.weight
361
+ )
362
+ weight_parameterizations.original = nn.Parameter(
363
+ weight_parameterizations.original[:, flattened_mask]
364
+ )
365
+ linear.in_features = weight_parameterizations.original.shape[1]
366
+ else:
367
+ linear.weight = nn.Parameter(linear.weight[:, flattened_mask])
368
+ linear.in_features = linear.weight.shape[1]
369
+
370
+
371
+ def prune_lstm_output_linear(
372
+ lstm: nn.LSTM, getitem: Callable, linear: nn.Linear
373
+ ) -> None:
374
+ prune_lstm_output_layernorm_linear(lstm, getitem, None, linear)
375
+
376
+
377
+ def prune_lstm_output_layernorm_linear(
378
+ lstm: nn.LSTM,
379
+ getitem: Callable,
380
+ layernorm: nn.LayerNorm | None,
381
+ linear: nn.Linear,
382
+ ) -> None:
383
+ for i in range(lstm.num_layers):
384
+ if parametrize.is_parametrized(lstm, f"weight_ih_l{i}"):
385
+ parametrization_dict = cast(nn.ModuleDict, lstm.parametrizations)
386
+ weight_parameterizations = cast(
387
+ ParametrizationList, parametrization_dict[f"weight_ih_l{i}"]
388
+ )
389
+ mask = weight_parameterizations[0].mask
390
+
391
+ with torch.no_grad():
392
+ parametrize.remove_parametrizations(
393
+ lstm, f"weight_ih_l{i}", leave_parametrized=True
394
+ )
395
+ setattr(
396
+ lstm,
397
+ f"weight_ih_l{i}",
398
+ nn.Parameter(getattr(lstm, f"weight_ih_l{i}")[mask]),
399
+ )
400
+ setattr(
401
+ lstm,
402
+ f"bias_ih_l{i}",
403
+ nn.Parameter(getattr(lstm, f"bias_ih_l{i}")[mask]),
404
+ )
405
+
406
+ if parametrize.is_parametrized(lstm, f"weight_hh_l{i}"):
407
+ parametrization_dict = cast(nn.ModuleDict, lstm.parametrizations)
408
+ weight_parameterizations = cast(
409
+ ParametrizationList, parametrization_dict[f"weight_hh_l{i}"]
410
+ )
411
+ mask = weight_parameterizations[0].mask
412
+
413
+ with torch.no_grad():
414
+ parametrize.remove_parametrizations(
415
+ lstm, f"weight_hh_l{i}", leave_parametrized=True
416
+ )
417
+ # splitting out hidden-hidden masks
418
+ W_hi, W_hf, W_hg, W_ho = torch.split(
419
+ getattr(lstm, f"weight_hh_l{i}"), lstm.hidden_size
420
+ )
421
+ M_hi, M_hf, M_hg, M_ho = torch.split(mask, lstm.hidden_size) # type: ignore[arg-type]
422
+
423
+ # resize each individual weight separately
424
+ W_hi = W_hi[M_hi][:, M_hi]
425
+ W_hf = W_hf[M_hf][:, M_hf]
426
+ W_hg = W_hg[M_hg][:, M_hg]
427
+ W_ho = W_ho[M_ho][:, M_ho]
428
+
429
+ # concat, use this as new weight
430
+ new_weight = torch.cat((W_hi, W_hf, W_hg, W_ho))
431
+ setattr(lstm, f"weight_hh_l{i}", nn.Parameter(new_weight))
432
+ setattr(
433
+ lstm,
434
+ f"bias_hh_l{i}",
435
+ nn.Parameter(getattr(lstm, f"bias_hh_l{i}")[mask]),
436
+ )
437
+
438
+ # If this is the final layer, then we need to prune linear layer columns
439
+ if i + 1 == lstm.num_layers:
440
+ lstm.hidden_size = int(M_hi.sum())
441
+ with torch.no_grad():
442
+ if parametrize.is_parametrized(linear):
443
+ parametrization_dict = cast(
444
+ nn.ModuleDict, linear.parametrizations
445
+ )
446
+ weight_parameterizations = cast(
447
+ ParametrizationList, parametrization_dict.weight
448
+ )
449
+
450
+ weight_parameterizations.original = nn.Parameter(
451
+ weight_parameterizations.original[:, M_ho]
452
+ )
453
+ linear.in_features = weight_parameterizations.original.shape[1]
454
+ else:
455
+ linear.weight = nn.Parameter(linear.weight[:, M_ho])
456
+ linear.in_features = linear.weight.shape[1]
457
+
458
+ # if layernorm module, prune weight and bias
459
+ if layernorm is not None:
460
+ layernorm.normalized_shape = (linear.in_features,)
461
+ layernorm.weight = nn.Parameter(layernorm.weight[M_ho])
462
+ layernorm.bias = nn.Parameter(layernorm.bias[M_ho])
463
+
464
+ # otherwise need to prune the columns of the input of the next LSTM layer
465
+ else:
466
+ with torch.no_grad():
467
+ if parametrize.is_parametrized(lstm, f"weight_ih_l{i + 1}"):
468
+ parametrization_dict = cast(
469
+ nn.ModuleDict, lstm.parametrizations
470
+ )
471
+ weight_parameterizations = cast(
472
+ ParametrizationList,
473
+ getattr(parametrization_dict, f"weight_ih_l{i + 1}"),
474
+ )
475
+
476
+ weight_parameterizations.original = nn.Parameter(
477
+ weight_parameterizations.original[:, M_ho]
478
+ )
479
+ else:
480
+ next_layer_weight = getattr(lstm, f"weight_ih_l{i + 1}")
481
+ setattr(
482
+ lstm,
483
+ f"weight_ih_l{i + 1}",
484
+ nn.Parameter(next_layer_weight[:, M_ho]),
485
+ )
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_experimental/pruner/saliency_pruner.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from .base_structured_sparsifier import BaseStructuredSparsifier
3
+
4
+
5
+ class SaliencyPruner(BaseStructuredSparsifier):
6
+ """
7
+ Prune rows based on the saliency (L1 norm) of each row.
8
+
9
+ This pruner works on N-Dimensional weight tensors.
10
+ For each row, we will calculate the saliency, which is the sum the L1 norm of all weights in that row.
11
+ We expect that the resulting saliency vector has the same shape as our mask.
12
+ We then pick elements to remove until we reach the target sparsity_level.
13
+ """
14
+
15
+ def update_mask(self, module, tensor_name, **kwargs):
16
+ # tensor_name will give you the FQN, all other entries in sparse config is present in kwargs
17
+ weights = getattr(module, tensor_name)
18
+ mask = getattr(module.parametrizations, tensor_name)[0].mask
19
+
20
+ # use negative weights so we can use topk (we prune out the smallest)
21
+ if weights.dim() <= 1:
22
+ raise Exception( # noqa: TRY002
23
+ "Structured pruning can only be applied to a 2+dim weight tensor!"
24
+ )
25
+ saliency = -weights.norm(dim=tuple(range(1, weights.dim())), p=1)
26
+ if saliency.shape != mask.shape:
27
+ raise AssertionError(
28
+ f"saliency shape ({saliency.shape}) must match mask shape ({mask.shape})"
29
+ )
30
+
31
+ num_to_pick = int(len(mask) * kwargs["sparsity_level"])
32
+ prune = saliency.topk(num_to_pick).indices
33
+
34
+ # Set the mask to be false for the rows we want to prune
35
+ mask.data[prune] = False
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/_mappings.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ __all__ = [
3
+ "get_static_sparse_quantized_mapping",
4
+ "get_dynamic_sparse_quantized_mapping",
5
+ ]
6
+
7
+
8
+ def get_static_sparse_quantized_mapping():
9
+ import torch.ao.nn.sparse
10
+
11
+ _static_sparse_quantized_mapping = {
12
+ torch.nn.Linear: torch.ao.nn.sparse.quantized.Linear,
13
+ }
14
+ return _static_sparse_quantized_mapping
15
+
16
+
17
+ def get_dynamic_sparse_quantized_mapping():
18
+ import torch.ao.nn.sparse
19
+
20
+ _dynamic_sparse_quantized_mapping = {
21
+ torch.nn.Linear: torch.ao.nn.sparse.quantized.dynamic.Linear,
22
+ }
23
+ return _dynamic_sparse_quantized_mapping
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/scheduler/__init__.py ADDED
File without changes
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/scheduler/base_scheduler.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import warnings
4
+ import weakref
5
+ from functools import wraps
6
+
7
+ from torch.ao.pruning.sparsifier.base_sparsifier import BaseSparsifier
8
+
9
+
10
+ __all__ = ["BaseScheduler"]
11
+
12
+
13
+ class BaseScheduler:
14
+ def __init__(self, sparsifier, last_epoch=-1, verbose=False):
15
+ # Attach sparsifier
16
+ if not isinstance(sparsifier, BaseSparsifier):
17
+ raise TypeError(
18
+ f"{type(sparsifier).__name__} is not an instance of torch.ao.pruning.BaseSparsifier"
19
+ )
20
+ self.sparsifier = sparsifier
21
+
22
+ # Initialize epoch and base sparsity levels
23
+
24
+ self.base_sl = [group["sparsity_level"] for group in sparsifier.groups]
25
+ self.last_epoch = last_epoch
26
+
27
+ # Following https://github.com/pytorch/pytorch/issues/20124
28
+ # We would like to ensure that `scheduler.step()` is called after
29
+ # `sparsifier.step()`
30
+ def with_counter(method):
31
+ if getattr(method, "_with_counter", False):
32
+ # `sparsifier.step()` has already been replaced, return.
33
+ return method
34
+
35
+ # Keep a weak reference to the sparsifier instance to prevent
36
+ # cyclic references.
37
+ instance_ref = weakref.ref(method.__self__)
38
+ # Get the unbound method for the same purpose.
39
+ func = method.__func__
40
+ cls = instance_ref().__class__
41
+ del method
42
+
43
+ @wraps(func)
44
+ def wrapper(*args, **kwargs):
45
+ instance = instance_ref()
46
+ instance._step_count += 1 # type: ignore[union-attr]
47
+ wrapped = func.__get__(instance, cls)
48
+ return wrapped(*args, **kwargs)
49
+
50
+ # Note that the returned function here is no longer a bound method,
51
+ # so attributes like `__func__` and `__self__` no longer exist.
52
+ wrapper._with_counter = True # type: ignore[attr-defined]
53
+ return wrapper
54
+
55
+ self.sparsifier.step = with_counter(self.sparsifier.step) # type: ignore[assignment]
56
+ self.sparsifier._step_count = 0 # type: ignore[attr-defined]
57
+ self._step_count: int = 0
58
+ self.verbose = verbose
59
+
60
+ # Housekeeping
61
+ self._get_sl_called_within_step: bool = False
62
+
63
+ self.step()
64
+
65
+ def state_dict(self):
66
+ """Returns the state of the scheduler as a :class:`dict`.
67
+
68
+ It contains an entry for every variable in self.__dict__ which
69
+ is not the sparsifier.
70
+ """
71
+ return {
72
+ key: value for key, value in self.__dict__.items() if key != "sparsifier"
73
+ }
74
+
75
+ def load_state_dict(self, state_dict):
76
+ """Loads the schedulers state.
77
+
78
+ Args:
79
+ state_dict (dict): scheduler state. Should be an object returned
80
+ from a call to :meth:`state_dict`.
81
+ """
82
+ self.__dict__.update(state_dict)
83
+
84
+ def get_last_sl(self):
85
+ """Return last computed sparsity level by current scheduler."""
86
+ return self._last_sl
87
+
88
+ def get_sl(self):
89
+ # Compute sparsity level using chainable form of the scheduler
90
+ # Note: This method is not intended to be called directly, and is only
91
+ # used by the ".step" method. Use .get_last_sl() instead.
92
+ if not self._get_sl_called_within_step:
93
+ warnings.warn(
94
+ "To get the last sparsity level computed by the scheduler, "
95
+ "please use `get_last_sl()`.",
96
+ stacklevel=2,
97
+ )
98
+ raise NotImplementedError
99
+
100
+ def print_sl(self, is_verbose, group, sl, epoch=None):
101
+ """Display the current sparsity level."""
102
+ if is_verbose:
103
+ if epoch is None:
104
+ print(f"Adjusting sparsity level of group {group} to {sl:.4e}.")
105
+ else:
106
+ print(
107
+ f"Epoch {epoch:5d}: adjusting sparsity level of group {group} to {sl:.4e}."
108
+ )
109
+
110
+ def __repr__(self):
111
+ format_string = self.__class__.__name__ + " ("
112
+ format_string += "\n"
113
+ format_string += f"Sparsifier {self.sparsifier}\n"
114
+ format_string += f" base_sl: {self.base_sl}\n"
115
+ format_string += ")"
116
+ return format_string
117
+
118
+ def step(self, epoch=None):
119
+ # Raise warning if trying to call scheduler step before the sparsifier.
120
+ # https://github.com/pytorch/pytorch/issues/20124
121
+ if self._step_count == 1:
122
+ if not hasattr(self.sparsifier.step, "_with_counter"):
123
+ warnings.warn(
124
+ "Seems like `sparsifier.step()` has been overridden after sparsity scheduler "
125
+ "initialization. Please, make sure to call `sparsifier.step()` before "
126
+ "`scheduler.step()`.",
127
+ UserWarning,
128
+ stacklevel=2,
129
+ )
130
+
131
+ # Just check if there were two first scheduler.step() calls before sparsifier.step()
132
+ elif self.sparsifier._step_count < 1: # type: ignore[attr-defined]
133
+ warnings.warn(
134
+ "Detected call of `scheduler.step()` before `sparsifier.step()`. "
135
+ "You have to make sure you run the sparsifier.step() BEFORE any "
136
+ "calls to the scheduler.step().",
137
+ UserWarning,
138
+ stacklevel=2,
139
+ )
140
+ self._step_count += 1
141
+
142
+ class _enable_get_sl_call:
143
+ def __init__(self, o):
144
+ self.o = o
145
+
146
+ def __enter__(self):
147
+ self.o._get_sl_called_within_step = True
148
+ return self
149
+
150
+ def __exit__(self, type, value, traceback):
151
+ self.o._get_sl_called_within_step = False
152
+
153
+ with _enable_get_sl_call(self):
154
+ self.last_epoch += 1
155
+ values = self.get_sl()
156
+
157
+ for i, data in enumerate(zip(self.sparsifier.groups, values)):
158
+ param_group, sl = data
159
+ param_group["sparsity_level"] = sl
160
+ self.print_sl(self.verbose, i, sl, epoch)
161
+
162
+ self._last_sl = [group["sparsity_level"] for group in self.sparsifier.groups]
163
+ self.sparsifier.enable_mask_update = True
164
+
165
+ def _make_sure_a_list(self, var):
166
+ r"""Utility that extends it to the same length as the .groups, ensuring it is a list"""
167
+ n = len(self.sparsifier.groups)
168
+ if not isinstance(var, (list, tuple)):
169
+ return [var] * n
170
+ else:
171
+ if len(var) != n:
172
+ raise ValueError(f"Expected variable of length {n}, but got {len(var)}")
173
+ return list(var) # We want the result to be in a list, not tuple
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/scheduler/cubic_scheduler.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import warnings
3
+
4
+ from .base_scheduler import BaseScheduler
5
+
6
+
7
+ __all__ = ["CubicSL"]
8
+
9
+
10
+ def _clamp(x, lo, hi):
11
+ return max(lo, min(hi, x))
12
+
13
+
14
+ class CubicSL(BaseScheduler):
15
+ r"""Sets the sparsity level of each parameter group to the final sl
16
+ plus a given exponential function.
17
+
18
+ .. math::
19
+
20
+ s_i = s_f + (s_0 - s_f) \cdot \left( 1 - \frac{t - t_0}{n\Delta t} \right)^3
21
+
22
+ where :math:`s_i` is the sparsity at epoch :math:`t`, :math;`s_f` is the final
23
+ sparsity level, :math:`f(i)` is the function to be applied to the current epoch
24
+ :math:`t`, initial epoch :math:`t_0`, and final epoch :math:`t_f`.
25
+ :math:`\Delta t` is used to control how often the update of the sparsity level
26
+ happens. By default,
27
+
28
+ Args:
29
+ sparsifier (BaseSparsifier): Wrapped sparsifier.
30
+ init_sl (int, list): Initial level of sparsity
31
+ init_t (int, list): Initial step, when pruning starts
32
+ delta_t (int, list): Pruning frequency
33
+ total_t (int, list): Total number of pruning steps
34
+ initially_zero (bool, list): If True, sets the level of sparsity to 0
35
+ before init_t (:math:`t_0`). Otherwise, the sparsity level before
36
+ init_t (:math:`t_0`) is set to init_sl(:math:`s_0`)
37
+ last_epoch (int): The index of last epoch. Default: -1.
38
+ verbose (bool): If ``True``, prints a message to stdout for
39
+ each update. Default: ``False``.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ sparsifier,
45
+ init_sl=0.0,
46
+ init_t=0,
47
+ delta_t=10,
48
+ total_t=100,
49
+ initially_zero=False,
50
+ last_epoch=-1,
51
+ verbose=False,
52
+ ):
53
+ self.sparsifier = sparsifier
54
+
55
+ self.init_sl = self._make_sure_a_list(init_sl)
56
+ self.init_t = self._make_sure_a_list(init_t)
57
+ self.delta_t = self._make_sure_a_list(delta_t)
58
+ self.total_t = self._make_sure_a_list(total_t)
59
+
60
+ self.initially_zero = self._make_sure_a_list(initially_zero)
61
+
62
+ super().__init__(sparsifier, last_epoch, verbose)
63
+
64
+ @staticmethod
65
+ def sparsity_compute_fn(s_0, s_f, t, t_0, dt, n, initially_zero=False):
66
+ r""" "Computes the current level of sparsity.
67
+
68
+ Based on https://arxiv.org/pdf/1710.01878.pdf
69
+
70
+ Args:
71
+ s_0: Initial level of sparsity, :math:`s_i`
72
+ s_f: Target level of sparsity, :math:`s_f`
73
+ t: Current step, :math:`t`
74
+ t_0: Initial step, :math:`t_0`
75
+ dt: Pruning frequency, :math:`\Delta T`
76
+ n: Pruning steps, :math:`n`
77
+ initially_zero: Sets the level of sparsity to 0 before t_0.
78
+ If False, sets to s_0
79
+
80
+ Returns:
81
+ The sparsity level :math:`s_t` at the current step :math:`t`
82
+ """
83
+ if initially_zero and t < t_0:
84
+ return 0
85
+ s_t = s_f + (s_0 - s_f) * (1.0 - (t - t_0) / (dt * n)) ** 3
86
+ s_t = _clamp(s_t, s_0, s_f)
87
+ return s_t
88
+
89
+ def get_sl(self):
90
+ if not self._get_sl_called_within_step:
91
+ warnings.warn(
92
+ "To get the last sparsity level computed by the scheduler, "
93
+ "please use `get_last_sl()`.",
94
+ stacklevel=2,
95
+ )
96
+ return [
97
+ self.sparsity_compute_fn(
98
+ s_0=initial_sparsity,
99
+ s_f=final_sparsity,
100
+ t=self.last_epoch,
101
+ t_0=initial_epoch,
102
+ dt=delta_epoch,
103
+ n=interval_epochs,
104
+ initially_zero=initially_zero,
105
+ )
106
+ for initial_sparsity, final_sparsity, initial_epoch, delta_epoch, interval_epochs, initially_zero in zip(
107
+ self.init_sl,
108
+ self.base_sl,
109
+ self.init_t,
110
+ self.delta_t,
111
+ self.total_t,
112
+ self.initially_zero,
113
+ )
114
+ ]
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/ao/pruning/scheduler/lambda_scheduler.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from collections.abc import Callable
3
+
4
+ from torch.ao.pruning.sparsifier.base_sparsifier import BaseSparsifier
5
+
6
+ from .base_scheduler import BaseScheduler
7
+
8
+
9
+ __all__ = ["LambdaSL"]
10
+
11
+
12
+ class LambdaSL(BaseScheduler):
13
+ """Sets the sparsity level of each parameter group to the final sl
14
+ times a given function. When last_epoch=-1, sets initial sl as zero.
15
+ Args:
16
+ sparsifier (BaseSparsifier): Wrapped sparsifier.
17
+ sl_lambda (function or list): A function which computes a multiplicative
18
+ factor given an integer parameter epoch, or a list of such
19
+ functions, one for each group in sparsifier.param_groups.
20
+ last_epoch (int): The index of last epoch. Default: -1.
21
+ verbose (bool): If ``True``, prints a message to stdout for
22
+ each update. Default: ``False``.
23
+ Example:
24
+ >>> # Assuming sparsifier has two groups.
25
+ >>> lambda1 = lambda epoch: epoch // 30
26
+ >>> lambda2 = lambda epoch: 0.95**epoch
27
+ >>> # xdoctest: +SKIP
28
+ >>> scheduler = LambdaSL(sparsifier, sl_lambda=[lambda1, lambda2])
29
+ >>> for epoch in range(100):
30
+ >>> train(...)
31
+ >>> validate(...)
32
+ >>> scheduler.step()
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ sparsifier: BaseSparsifier,
38
+ sl_lambda: Callable[[int], float] | list[Callable[[int], float]],
39
+ last_epoch: int = -1,
40
+ verbose: bool = False,
41
+ ) -> None:
42
+ self.sparsifier = sparsifier
43
+
44
+ if not isinstance(sl_lambda, list) and not isinstance(sl_lambda, tuple):
45
+ self.sl_lambdas = [sl_lambda] * len(sparsifier.groups)
46
+ else:
47
+ if len(sl_lambda) != len(sparsifier.groups):
48
+ raise ValueError(
49
+ f"Expected {len(sparsifier.groups)} lr_lambdas, but got {len(sl_lambda)}"
50
+ )
51
+ self.sl_lambdas = list(sl_lambda)
52
+ super().__init__(sparsifier, last_epoch, verbose) # type: ignore[no-untyped-call]
53
+
54
+ def get_sl(self) -> list[float]:
55
+ if not self._get_sl_called_within_step:
56
+ warnings.warn(
57
+ "To get the last sparsity level computed by the scheduler, "
58
+ "please use `get_last_sl()`.",
59
+ stacklevel=2,
60
+ )
61
+ return [
62
+ base_sl * lmbda(self.last_epoch)
63
+ for lmbda, base_sl in zip(self.sl_lambdas, self.base_sl)
64
+ ]