ADAPT-Chase commited on
Commit
e7cbe8a
·
verified ·
1 Parent(s): f3f0896

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. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/__pycache__/__init__.cpython-312.pyc +0 -0
  2. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc +0 -0
  3. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/conv.cpython-312.pyc +0 -0
  4. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/linear.cpython-312.pyc +0 -0
  5. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/rnn.cpython-312.pyc +0 -0
  6. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/rnn.py +1359 -0
  7. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/__init__.cpython-312.pyc +0 -0
  8. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/activation.cpython-312.pyc +0 -0
  9. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/batchnorm.cpython-312.pyc +0 -0
  10. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/conv.cpython-312.pyc +0 -0
  11. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/dropout.cpython-312.pyc +0 -0
  12. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-312.pyc +0 -0
  13. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/functional_modules.cpython-312.pyc +0 -0
  14. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/linear.cpython-312.pyc +0 -0
  15. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/normalization.cpython-312.pyc +0 -0
  16. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/rnn.cpython-312.pyc +0 -0
  17. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/utils.cpython-312.pyc +0 -0
  18. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/__pycache__/__init__.cpython-312.pyc +0 -0
  19. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__init__.py +29 -0
  20. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/__init__.cpython-312.pyc +0 -0
  21. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/conv.cpython-312.pyc +0 -0
  22. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/linear.cpython-312.pyc +0 -0
  23. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/rnn.cpython-312.pyc +0 -0
  24. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/sparse.cpython-312.pyc +0 -0
  25. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/utils.cpython-312.pyc +0 -0
  26. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/conv.py +511 -0
  27. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/linear.py +69 -0
  28. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/rnn.py +845 -0
  29. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/sparse.py +162 -0
  30. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/utils.py +431 -0
  31. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/__pycache__/__init__.cpython-312.pyc +0 -0
  32. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__init__.py +10 -0
  33. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/__init__.cpython-312.pyc +0 -0
  34. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/linear.cpython-312.pyc +0 -0
  35. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/utils.cpython-312.pyc +0 -0
  36. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__init__.py +6 -0
  37. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__pycache__/__init__.cpython-312.pyc +0 -0
  38. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__pycache__/linear.cpython-312.pyc +0 -0
  39. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/linear.py +188 -0
  40. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/linear.py +272 -0
  41. tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/utils.py +63 -0
  42. tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/__init__.cpython-312.pyc +0 -0
  43. tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/_numeric_suite.cpython-312.pyc +0 -0
  44. tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/_numeric_suite_fx.cpython-312.pyc +0 -0
  45. tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__init__.py +0 -0
  46. tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/__init__.cpython-312.pyc +0 -0
  47. tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/graph_matcher.cpython-312.pyc +0 -0
  48. tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/graph_passes.cpython-312.pyc +0 -0
  49. tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/mappings.cpython-312.pyc +0 -0
  50. tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/n_shadows_utils.cpython-312.pyc +0 -0
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (228 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (595 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/conv.cpython-312.pyc ADDED
Binary file (19 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/linear.cpython-312.pyc ADDED
Binary file (8.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/__pycache__/rnn.cpython-312.pyc ADDED
Binary file (56.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/dynamic/modules/rnn.py ADDED
@@ -0,0 +1,1359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import numbers
4
+ import warnings
5
+ from typing_extensions import deprecated
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ from torch import Tensor # noqa: F401
10
+ from torch._jit_internal import Dict, List, Optional, Tuple, Union # noqa: F401
11
+ from torch.ao.nn.quantized.modules.utils import _quantize_weight
12
+ from torch.nn.utils.rnn import PackedSequence
13
+
14
+
15
+ __all__ = [
16
+ "pack_weight_bias",
17
+ "PackedParameter",
18
+ "RNNBase",
19
+ "LSTM",
20
+ "GRU",
21
+ "RNNCellBase",
22
+ "RNNCell",
23
+ "LSTMCell",
24
+ "GRUCell",
25
+ "apply_permutation",
26
+ ]
27
+
28
+
29
+ def _apply_permutation(tensor: Tensor, permutation: Tensor, dim: int = 1) -> Tensor:
30
+ return tensor.index_select(dim, permutation)
31
+
32
+
33
+ @deprecated(
34
+ "`apply_permutation` is deprecated, please use `tensor.index_select(dim, permutation)` instead",
35
+ category=FutureWarning,
36
+ )
37
+ def apply_permutation(tensor: Tensor, permutation: Tensor, dim: int = 1) -> Tensor:
38
+ return _apply_permutation(tensor, permutation, dim)
39
+
40
+
41
+ def pack_weight_bias(qweight, bias, dtype):
42
+ if dtype == torch.qint8:
43
+ # for each layer, for each direction we need to quantize and pack
44
+ # weights and pack parameters in this order:
45
+ #
46
+ # w_ih, w_hh
47
+ packed_weight = torch.ops.quantized.linear_prepack(qweight, bias)
48
+
49
+ return packed_weight
50
+ else:
51
+ # for each layer, for each direction we need to quantize and pack
52
+ # weights and pack parameters in this order:
53
+ #
54
+ # packed_ih, packed_hh, b_ih, b_hh
55
+ packed_weight = torch.ops.quantized.linear_prepack_fp16(qweight, bias)
56
+
57
+ return packed_weight
58
+
59
+
60
+ class PackedParameter(torch.nn.Module):
61
+ def __init__(self, param):
62
+ super().__init__()
63
+ self.param = param
64
+
65
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
66
+ super()._save_to_state_dict(destination, prefix, keep_vars)
67
+ destination[prefix + "param"] = self.param
68
+
69
+ def _load_from_state_dict(
70
+ self,
71
+ state_dict,
72
+ prefix,
73
+ local_metadata,
74
+ strict,
75
+ missing_keys,
76
+ unexpected_keys,
77
+ error_msgs,
78
+ ):
79
+ self.param = state_dict[prefix + "param"]
80
+ super()._load_from_state_dict(
81
+ state_dict,
82
+ prefix,
83
+ local_metadata,
84
+ False,
85
+ missing_keys,
86
+ unexpected_keys,
87
+ error_msgs,
88
+ )
89
+
90
+
91
+ class RNNBase(torch.nn.Module):
92
+ _FLOAT_MODULE = nn.RNNBase
93
+
94
+ _version = 2
95
+
96
+ def __init__(
97
+ self,
98
+ mode,
99
+ input_size,
100
+ hidden_size,
101
+ num_layers=1,
102
+ bias=True,
103
+ batch_first=False,
104
+ dropout=0.0,
105
+ bidirectional=False,
106
+ dtype=torch.qint8,
107
+ ):
108
+ super().__init__()
109
+
110
+ self.mode = mode
111
+ self.input_size = input_size
112
+ self.hidden_size = hidden_size
113
+ self.num_layers = num_layers
114
+ self.bias = bias
115
+ self.batch_first = batch_first
116
+ self.dropout = float(dropout)
117
+ self.bidirectional = bidirectional
118
+ self.dtype = dtype
119
+ self.version = 2
120
+ self.training = False
121
+ num_directions = 2 if bidirectional else 1
122
+
123
+ # "type: ignore" is required since ints and Numbers are not fully comparable
124
+ # https://github.com/python/mypy/issues/8566
125
+ if (
126
+ not isinstance(dropout, numbers.Number)
127
+ or not 0 <= dropout <= 1 # type: ignore[operator]
128
+ or isinstance(dropout, bool)
129
+ ):
130
+ raise ValueError(
131
+ "dropout should be a number in range [0, 1] "
132
+ "representing the probability of an element being "
133
+ "zeroed"
134
+ )
135
+ if dropout > 0 and num_layers == 1: # type: ignore[operator]
136
+ warnings.warn(
137
+ "dropout option adds dropout after all but last "
138
+ "recurrent layer, so non-zero dropout expects "
139
+ f"num_layers greater than 1, but got dropout={dropout} and "
140
+ f"num_layers={num_layers}"
141
+ )
142
+
143
+ if mode == "LSTM":
144
+ gate_size = 4 * hidden_size
145
+ elif mode == "GRU":
146
+ gate_size = 3 * hidden_size
147
+ else:
148
+ raise ValueError("Unrecognized RNN mode: " + mode)
149
+
150
+ _all_weight_values = []
151
+ for layer in range(num_layers):
152
+ for _ in range(num_directions):
153
+ layer_input_size = (
154
+ input_size if layer == 0 else hidden_size * num_directions
155
+ )
156
+
157
+ w_ih = torch.randn(gate_size, layer_input_size).to(torch.float)
158
+ w_hh = torch.randn(gate_size, hidden_size).to(torch.float)
159
+ b_ih = torch.randn(gate_size).to(torch.float)
160
+ b_hh = torch.randn(gate_size).to(torch.float)
161
+ if dtype == torch.qint8:
162
+ w_ih = torch.quantize_per_tensor(
163
+ w_ih, scale=0.1, zero_point=0, dtype=torch.qint8
164
+ )
165
+ w_hh = torch.quantize_per_tensor(
166
+ w_hh, scale=0.1, zero_point=0, dtype=torch.qint8
167
+ )
168
+ packed_ih = torch.ops.quantized.linear_prepack(w_ih, b_ih)
169
+ packed_hh = torch.ops.quantized.linear_prepack(w_hh, b_hh)
170
+ if self.version is None or self.version < 2:
171
+ cell_params = (
172
+ torch.ops.quantized.make_quantized_cell_params_dynamic(
173
+ packed_ih, packed_hh, b_ih, b_hh
174
+ )
175
+ )
176
+ else:
177
+ cell_params = (
178
+ torch.ops.quantized.make_quantized_cell_params_dynamic(
179
+ packed_ih, packed_hh, b_ih, b_hh, True
180
+ )
181
+ )
182
+ else:
183
+ packed_ih = torch.ops.quantized.linear_prepack_fp16(w_ih, b_ih)
184
+ packed_hh = torch.ops.quantized.linear_prepack_fp16(w_hh, b_hh)
185
+ cell_params = torch.ops.quantized.make_quantized_cell_params_fp16(
186
+ packed_ih, packed_hh
187
+ )
188
+
189
+ _all_weight_values.append(PackedParameter(cell_params))
190
+ self._all_weight_values = torch.nn.ModuleList(_all_weight_values)
191
+
192
+ def _get_name(self):
193
+ return "DynamicQuantizedRNN"
194
+
195
+ def extra_repr(self):
196
+ s = "{input_size}, {hidden_size}"
197
+ if self.num_layers != 1:
198
+ s += ", num_layers={num_layers}"
199
+ if self.bias is not True:
200
+ s += ", bias={bias}"
201
+ if self.batch_first is not False:
202
+ s += ", batch_first={batch_first}"
203
+ if self.dropout != 0:
204
+ s += ", dropout={dropout}"
205
+ if self.bidirectional is not False:
206
+ s += ", bidirectional={bidirectional}"
207
+ return s.format(**self.__dict__)
208
+
209
+ def __repr__(self):
210
+ # We don't want to show `ModuleList` children, hence custom
211
+ # `__repr__`. This is the same as nn.Module.__repr__, except the check
212
+ # for the `PackedParameter` and `nn.ModuleList`.
213
+ # You should still override `extra_repr` to add more info.
214
+ extra_lines = []
215
+ extra_repr = self.extra_repr()
216
+ # empty string will be split into list ['']
217
+ if extra_repr:
218
+ extra_lines = extra_repr.split("\n")
219
+ child_lines = []
220
+ for key, module in self._modules.items():
221
+ if isinstance(module, (PackedParameter, nn.ModuleList)):
222
+ continue
223
+ mod_str = repr(module)
224
+ mod_str = nn.modules.module._addindent(mod_str, 2)
225
+ child_lines.append("(" + key + "): " + mod_str)
226
+ lines = extra_lines + child_lines
227
+
228
+ main_str = self._get_name() + "("
229
+ if lines:
230
+ # simple one-liner info, which most builtin Modules will use
231
+ if len(extra_lines) == 1 and not child_lines:
232
+ main_str += extra_lines[0]
233
+ else:
234
+ main_str += "\n " + "\n ".join(lines) + "\n"
235
+
236
+ main_str += ")"
237
+ return main_str
238
+
239
+ def check_input(self, input: Tensor, batch_sizes: Optional[Tensor]) -> None:
240
+ expected_input_dim = 2 if batch_sizes is not None else 3
241
+ if input.dim() != expected_input_dim:
242
+ raise RuntimeError(
243
+ f"input must have {expected_input_dim} dimensions, got {input.dim()}"
244
+ )
245
+ if self.input_size != input.size(-1):
246
+ raise RuntimeError(
247
+ f"input.size(-1) must be equal to input_size. Expected {self.input_size}, got {input.size(-1)}"
248
+ )
249
+
250
+ def get_expected_hidden_size(
251
+ self, input: Tensor, batch_sizes: Optional[Tensor]
252
+ ) -> tuple[int, int, int]:
253
+ if batch_sizes is not None:
254
+ mini_batch = int(batch_sizes[0])
255
+ else:
256
+ mini_batch = input.size(0) if self.batch_first else input.size(1)
257
+ num_directions = 2 if self.bidirectional else 1
258
+ expected_hidden_size = (
259
+ self.num_layers * num_directions,
260
+ mini_batch,
261
+ self.hidden_size,
262
+ )
263
+ return expected_hidden_size
264
+
265
+ def check_hidden_size(
266
+ self,
267
+ hx: Tensor,
268
+ expected_hidden_size: tuple[int, int, int],
269
+ msg: str = "Expected hidden size {}, got {}",
270
+ ) -> None:
271
+ if hx.size() != expected_hidden_size:
272
+ raise RuntimeError(msg.format(expected_hidden_size, list(hx.size())))
273
+
274
+ def check_forward_args(
275
+ self, input: Tensor, hidden: Tensor, batch_sizes: Optional[Tensor]
276
+ ) -> None:
277
+ self.check_input(input, batch_sizes)
278
+ expected_hidden_size = self.get_expected_hidden_size(input, batch_sizes)
279
+ self.check_hidden_size(
280
+ hidden, expected_hidden_size, msg="Expected hidden size {}, got {}"
281
+ )
282
+
283
+ def permute_hidden(self, hx: Tensor, permutation: Optional[Tensor]) -> Tensor:
284
+ if permutation is None:
285
+ return hx
286
+ return _apply_permutation(hx, permutation)
287
+
288
+ def _load_from_state_dict(
289
+ self,
290
+ state_dict,
291
+ prefix,
292
+ local_metadata,
293
+ strict,
294
+ missing_keys,
295
+ unexpected_keys,
296
+ error_msgs,
297
+ ):
298
+ version = local_metadata.get("version", None)
299
+ self.version = version
300
+ super()._load_from_state_dict(
301
+ state_dict,
302
+ prefix,
303
+ local_metadata,
304
+ False,
305
+ missing_keys,
306
+ unexpected_keys,
307
+ error_msgs,
308
+ )
309
+
310
+ def set_weight_bias(self, weight_bias_dict):
311
+ def weight_bias_name(ihhh, layer, suffix):
312
+ weight_name = f"weight_{ihhh}_l{layer}{suffix}"
313
+ bias_name = f"bias_{ihhh}_l{layer}{suffix}"
314
+ return weight_name, bias_name
315
+
316
+ num_directions = 2 if self.bidirectional else 1
317
+ # TODO: dedup with __init__ of RNNBase
318
+ _all_weight_values = []
319
+ for layer in range(self.num_layers):
320
+ for direction in range(num_directions):
321
+ suffix = "_reverse" if direction == 1 else ""
322
+ w_ih_name, b_ih_name = weight_bias_name("ih", layer, suffix)
323
+ w_hh_name, b_hh_name = weight_bias_name("hh", layer, suffix)
324
+ w_ih = weight_bias_dict[w_ih_name]
325
+ b_ih = weight_bias_dict[b_ih_name]
326
+ w_hh = weight_bias_dict[w_hh_name]
327
+ b_hh = weight_bias_dict[b_hh_name]
328
+ if w_ih.dtype == torch.qint8:
329
+ packed_ih = torch.ops.quantized.linear_prepack(w_ih, b_ih)
330
+ packed_hh = torch.ops.quantized.linear_prepack(w_hh, b_hh)
331
+ if self.version is None or self.version < 2:
332
+ cell_params = (
333
+ torch.ops.quantized.make_quantized_cell_params_dynamic(
334
+ packed_ih, packed_hh, b_ih, b_hh
335
+ )
336
+ )
337
+ else:
338
+ cell_params = (
339
+ torch.ops.quantized.make_quantized_cell_params_dynamic(
340
+ packed_ih, packed_hh, b_ih, b_hh, True
341
+ )
342
+ )
343
+ else:
344
+ packed_ih = torch.ops.quantized.linear_prepack_fp16(w_ih, b_ih)
345
+ packed_hh = torch.ops.quantized.linear_prepack_fp16(w_hh, b_hh)
346
+ cell_params = torch.ops.quantized.make_quantized_cell_params_fp16(
347
+ packed_ih, packed_hh
348
+ )
349
+
350
+ _all_weight_values.append(PackedParameter(cell_params))
351
+ self._all_weight_values = torch.nn.ModuleList(_all_weight_values)
352
+
353
+ @classmethod
354
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
355
+ assert type(mod) in {
356
+ torch.nn.LSTM,
357
+ torch.nn.GRU,
358
+ }, "nn.quantized.dynamic.RNNBase.from_float only works for nn.LSTM and nn.GRU"
359
+ assert hasattr(mod, "qconfig"), "Input float module must have qconfig defined"
360
+
361
+ if mod.qconfig is not None and mod.qconfig.weight is not None:
362
+ weight_observer_method = mod.qconfig.weight
363
+ else:
364
+ # We have the circular import issues if we import the qconfig in the beginning of this file:
365
+ # https://github.com/pytorch/pytorch/pull/24231. The current workaround is to postpone the
366
+ # import until we need it.
367
+ from torch.ao.quantization.qconfig import default_dynamic_qconfig
368
+
369
+ weight_observer_method = default_dynamic_qconfig.weight
370
+
371
+ dtype = weight_observer_method().dtype
372
+ supported_scalar_types = [torch.qint8, torch.float16]
373
+ if dtype not in supported_scalar_types:
374
+ raise RuntimeError(
375
+ f"Unsupported dtype for dynamic RNN quantization: {dtype}"
376
+ )
377
+ # RNNBase can be either LSTM or GRU
378
+ qRNNBase: Union[LSTM, GRU]
379
+ if mod.mode == "LSTM":
380
+ qRNNBase = LSTM(
381
+ mod.input_size,
382
+ mod.hidden_size,
383
+ mod.num_layers,
384
+ mod.bias,
385
+ mod.batch_first,
386
+ mod.dropout,
387
+ mod.bidirectional,
388
+ dtype,
389
+ )
390
+ elif mod.mode == "GRU":
391
+ qRNNBase = GRU(
392
+ mod.input_size,
393
+ mod.hidden_size,
394
+ mod.num_layers,
395
+ mod.bias,
396
+ mod.batch_first,
397
+ mod.dropout,
398
+ mod.bidirectional,
399
+ dtype,
400
+ )
401
+ else:
402
+ raise NotImplementedError(
403
+ "Only LSTM/GRU is supported for QuantizedRNN for now"
404
+ )
405
+
406
+ num_directions = 2 if mod.bidirectional else 1
407
+
408
+ assert mod.bias
409
+
410
+ _all_weight_values = []
411
+ for layer in range(qRNNBase.num_layers):
412
+ for direction in range(num_directions):
413
+ suffix = "_reverse" if direction == 1 else ""
414
+
415
+ def retrieve_weight_bias(ihhh):
416
+ weight_name = f"weight_{ihhh}_l{layer}{suffix}"
417
+ bias_name = f"bias_{ihhh}_l{layer}{suffix}"
418
+ weight = getattr(mod, weight_name)
419
+ bias = getattr(mod, bias_name)
420
+ return weight, bias
421
+
422
+ weight_ih, bias_ih = retrieve_weight_bias("ih")
423
+ weight_hh, bias_hh = retrieve_weight_bias("hh")
424
+
425
+ if dtype == torch.qint8:
426
+
427
+ def quantize_and_pack(w, b):
428
+ weight_observer = weight_observer_method()
429
+ weight_observer(w)
430
+ qweight = _quantize_weight(w.float(), weight_observer)
431
+ packed_weight = torch.ops.quantized.linear_prepack(qweight, b)
432
+ return packed_weight
433
+
434
+ packed_ih = quantize_and_pack(weight_ih, bias_ih)
435
+ packed_hh = quantize_and_pack(weight_hh, bias_hh)
436
+ if qRNNBase.version is None or qRNNBase.version < 2:
437
+ cell_params = (
438
+ torch.ops.quantized.make_quantized_cell_params_dynamic(
439
+ packed_ih, packed_hh, bias_ih, bias_hh
440
+ )
441
+ )
442
+ else:
443
+ cell_params = (
444
+ torch.ops.quantized.make_quantized_cell_params_dynamic(
445
+ packed_ih, packed_hh, bias_ih, bias_hh, True
446
+ )
447
+ )
448
+
449
+ elif dtype == torch.float16:
450
+ packed_ih = torch.ops.quantized.linear_prepack_fp16(
451
+ weight_ih.float(), bias_ih
452
+ )
453
+ packed_hh = torch.ops.quantized.linear_prepack_fp16(
454
+ weight_hh.float(), bias_hh
455
+ )
456
+
457
+ cell_params = torch.ops.quantized.make_quantized_cell_params_fp16(
458
+ packed_ih, packed_hh
459
+ )
460
+ else:
461
+ raise RuntimeError(
462
+ "Unsupported dtype specified for dynamic quantized LSTM!"
463
+ )
464
+
465
+ _all_weight_values.append(PackedParameter(cell_params))
466
+ qRNNBase._all_weight_values = torch.nn.ModuleList(_all_weight_values)
467
+
468
+ return qRNNBase
469
+
470
+ def _weight_bias(self):
471
+ # Returns a dict of weights and biases
472
+ weight_bias_dict: Dict[str, Dict] = {"weight": {}, "bias": {}}
473
+ count = 0
474
+ num_directions = 2 if self.bidirectional else 1
475
+ for layer in range(self.num_layers):
476
+ for direction in range(num_directions):
477
+ suffix = "_reverse" if direction == 1 else ""
478
+ key_name1 = f"weight_ih_l{layer}{suffix}"
479
+ key_name2 = f"weight_hh_l{layer}{suffix}"
480
+ # packed weights are part of torchbind class, CellParamsSerializationType
481
+ # Within the packed weight class, the weight and bias are accessible as Tensors
482
+ packed_weight_bias = self._all_weight_values[ # type: ignore[index]
483
+ count
484
+ ].param.__getstate__()[0][4]
485
+ weight_bias_dict["weight"][key_name1] = packed_weight_bias[
486
+ 0
487
+ ].__getstate__()[0][0]
488
+ weight_bias_dict["weight"][key_name2] = packed_weight_bias[
489
+ 1
490
+ ].__getstate__()[0][0]
491
+ key_name1 = f"bias_ih_l{layer}{suffix}"
492
+ key_name2 = f"bias_hh_l{layer}{suffix}"
493
+ weight_bias_dict["bias"][key_name1] = packed_weight_bias[
494
+ 0
495
+ ].__getstate__()[0][1]
496
+ weight_bias_dict["bias"][key_name2] = packed_weight_bias[
497
+ 1
498
+ ].__getstate__()[0][1]
499
+ count = count + 1
500
+ return weight_bias_dict
501
+
502
+ def get_weight(self):
503
+ return self._weight_bias()["weight"]
504
+
505
+ def get_bias(self):
506
+ return self._weight_bias()["bias"]
507
+
508
+
509
+ class LSTM(RNNBase):
510
+ r"""
511
+ A dynamic quantized LSTM module with floating point tensor as inputs and outputs.
512
+ We adopt the same interface as `torch.nn.LSTM`, please see
513
+ https://pytorch.org/docs/stable/nn.html#torch.nn.LSTM for documentation.
514
+
515
+ Examples::
516
+
517
+ >>> # xdoctest: +SKIP
518
+ >>> rnn = nn.LSTM(10, 20, 2)
519
+ >>> input = torch.randn(5, 3, 10)
520
+ >>> h0 = torch.randn(2, 3, 20)
521
+ >>> c0 = torch.randn(2, 3, 20)
522
+ >>> output, (hn, cn) = rnn(input, (h0, c0))
523
+ """
524
+ _FLOAT_MODULE = nn.LSTM
525
+
526
+ __overloads__ = {"forward": ["forward_packed", "forward_tensor"]}
527
+
528
+ def __init__(self, *args, **kwargs):
529
+ super().__init__("LSTM", *args, **kwargs)
530
+
531
+ def _get_name(self):
532
+ return "DynamicQuantizedLSTM"
533
+
534
+ def forward_impl(
535
+ self,
536
+ input: Tensor,
537
+ hx: Optional[tuple[Tensor, Tensor]],
538
+ batch_sizes: Optional[Tensor],
539
+ max_batch_size: int,
540
+ sorted_indices: Optional[Tensor],
541
+ ) -> tuple[Tensor, tuple[Tensor, Tensor]]:
542
+ if hx is None:
543
+ num_directions = 2 if self.bidirectional else 1
544
+ zeros = torch.zeros(
545
+ self.num_layers * num_directions,
546
+ max_batch_size,
547
+ self.hidden_size,
548
+ dtype=input.dtype,
549
+ device=input.device,
550
+ )
551
+ hx = (zeros, zeros)
552
+ else:
553
+ # Each batch of the hidden state should match the input sequence that
554
+ # the user believes he/she is passing in.
555
+ hx = self.permute_hidden(hx, sorted_indices)
556
+
557
+ self.check_forward_args(input, hx, batch_sizes)
558
+
559
+ _all_params = [m.param for m in self._all_weight_values]
560
+ if batch_sizes is None:
561
+ result = torch.quantized_lstm(
562
+ input,
563
+ hx,
564
+ _all_params,
565
+ self.bias,
566
+ self.num_layers,
567
+ float(self.dropout),
568
+ self.training,
569
+ self.bidirectional,
570
+ self.batch_first,
571
+ dtype=self.dtype,
572
+ use_dynamic=True,
573
+ )
574
+ else:
575
+ result = torch.quantized_lstm(
576
+ input,
577
+ batch_sizes,
578
+ hx,
579
+ _all_params,
580
+ self.bias,
581
+ self.num_layers,
582
+ float(self.dropout),
583
+ self.training,
584
+ self.bidirectional,
585
+ dtype=self.dtype,
586
+ use_dynamic=True,
587
+ )
588
+ output = result[0]
589
+ hidden = result[1:]
590
+
591
+ return output, hidden
592
+
593
+ @torch.jit.export
594
+ def forward_tensor(
595
+ self, input: Tensor, hx: Optional[tuple[Tensor, Tensor]] = None
596
+ ) -> tuple[Tensor, tuple[Tensor, Tensor]]:
597
+ batch_sizes = None
598
+ max_batch_size = input.size(0) if self.batch_first else input.size(1)
599
+ sorted_indices = None
600
+ unsorted_indices = None
601
+
602
+ output, hidden = self.forward_impl(
603
+ input, hx, batch_sizes, max_batch_size, sorted_indices
604
+ )
605
+
606
+ return output, self.permute_hidden(hidden, unsorted_indices)
607
+
608
+ @torch.jit.export
609
+ def forward_packed(
610
+ self, input: PackedSequence, hx: Optional[tuple[Tensor, Tensor]] = None
611
+ ) -> tuple[PackedSequence, tuple[Tensor, Tensor]]:
612
+ input_, batch_sizes, sorted_indices, unsorted_indices = input
613
+ max_batch_size = int(batch_sizes[0])
614
+
615
+ output_, hidden = self.forward_impl(
616
+ input_, hx, batch_sizes, max_batch_size, sorted_indices
617
+ )
618
+
619
+ output = PackedSequence(output_, batch_sizes, sorted_indices, unsorted_indices)
620
+ return output, self.permute_hidden(hidden, unsorted_indices)
621
+
622
+ # "type: ignore" is required due to issue #43072
623
+ def permute_hidden( # type: ignore[override]
624
+ self,
625
+ hx: tuple[Tensor, Tensor],
626
+ permutation: Optional[Tensor],
627
+ ) -> tuple[Tensor, Tensor]:
628
+ if permutation is None:
629
+ return hx
630
+ return _apply_permutation(hx[0], permutation), _apply_permutation(
631
+ hx[1], permutation
632
+ )
633
+
634
+ # "type: ignore" is required due to issue #43072
635
+ def check_forward_args( # type: ignore[override]
636
+ self,
637
+ input: Tensor,
638
+ hidden: tuple[Tensor, Tensor],
639
+ batch_sizes: Optional[Tensor],
640
+ ) -> None:
641
+ self.check_input(input, batch_sizes)
642
+ expected_hidden_size = self.get_expected_hidden_size(input, batch_sizes)
643
+
644
+ self.check_hidden_size(
645
+ hidden[0], expected_hidden_size, "Expected hidden[0] size {}, got {}"
646
+ )
647
+ self.check_hidden_size(
648
+ hidden[1], expected_hidden_size, "Expected hidden[1] size {}, got {}"
649
+ )
650
+
651
+ @torch.jit.ignore
652
+ def forward(self, input, hx=None):
653
+ if isinstance(input, PackedSequence):
654
+ return self.forward_packed(input, hx)
655
+ else:
656
+ return self.forward_tensor(input, hx)
657
+
658
+ @classmethod
659
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
660
+ return super().from_float(
661
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
662
+ )
663
+
664
+ @classmethod
665
+ def from_reference(cls, ref_mod):
666
+ assert hasattr(ref_mod, "weight_ih_l0_dtype"), "We are assuming weight_ih_l0 "
667
+ "exists in LSTM, may need to relax the assumption to support the use case"
668
+ qmod = cls(
669
+ ref_mod.input_size,
670
+ ref_mod.hidden_size,
671
+ ref_mod.num_layers,
672
+ ref_mod.bias,
673
+ ref_mod.batch_first,
674
+ ref_mod.dropout,
675
+ ref_mod.bidirectional,
676
+ # assuming there is layer 0, which should be OK
677
+ ref_mod.weight_ih_l0_dtype,
678
+ )
679
+ qmod.set_weight_bias(ref_mod.get_quantized_weight_bias_dict())
680
+ return qmod
681
+
682
+
683
+ class GRU(RNNBase):
684
+ r"""Applies a multi-layer gated recurrent unit (GRU) RNN to an input sequence.
685
+
686
+
687
+ For each element in the input sequence, each layer computes the following
688
+ function:
689
+
690
+ .. math::
691
+ \begin{array}{ll}
692
+ r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\
693
+ z_t = \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\
694
+ n_t = \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{(t-1)}+ b_{hn})) \\
695
+ h_t = (1 - z_t) \odot n_t + z_t \odot h_{(t-1)}
696
+ \end{array}
697
+
698
+ where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is the input
699
+ at time `t`, :math:`h_{(t-1)}` is the hidden state of the layer
700
+ at time `t-1` or the initial hidden state at time `0`, and :math:`r_t`,
701
+ :math:`z_t`, :math:`n_t` are the reset, update, and new gates, respectively.
702
+ :math:`\sigma` is the sigmoid function, and :math:`\odot` is the Hadamard product.
703
+
704
+ In a multilayer GRU, the input :math:`x^{(l)}_t` of the :math:`l` -th layer
705
+ (:math:`l >= 2`) is the hidden state :math:`h^{(l-1)}_t` of the previous layer multiplied by
706
+ dropout :math:`\delta^{(l-1)}_t` where each :math:`\delta^{(l-1)}_t` is a Bernoulli random
707
+ variable which is :math:`0` with probability :attr:`dropout`.
708
+
709
+ Args:
710
+ input_size: The number of expected features in the input `x`
711
+ hidden_size: The number of features in the hidden state `h`
712
+ num_layers: Number of recurrent layers. E.g., setting ``num_layers=2``
713
+ would mean stacking two GRUs together to form a `stacked GRU`,
714
+ with the second GRU taking in outputs of the first GRU and
715
+ computing the final results. Default: 1
716
+ bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`.
717
+ Default: ``True``
718
+ batch_first: If ``True``, then the input and output tensors are provided
719
+ as (batch, seq, feature). Default: ``False``
720
+ dropout: If non-zero, introduces a `Dropout` layer on the outputs of each
721
+ GRU layer except the last layer, with dropout probability equal to
722
+ :attr:`dropout`. Default: 0
723
+ bidirectional: If ``True``, becomes a bidirectional GRU. Default: ``False``
724
+
725
+ Inputs: input, h_0
726
+ - **input** of shape `(seq_len, batch, input_size)`: tensor containing the features
727
+ of the input sequence. The input can also be a packed variable length
728
+ sequence. See :func:`torch.nn.utils.rnn.pack_padded_sequence`
729
+ for details.
730
+ - **h_0** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
731
+ containing the initial hidden state for each element in the batch.
732
+ Defaults to zero if not provided. If the RNN is bidirectional,
733
+ num_directions should be 2, else it should be 1.
734
+
735
+ Outputs: output, h_n
736
+ - **output** of shape `(seq_len, batch, num_directions * hidden_size)`: tensor
737
+ containing the output features h_t from the last layer of the GRU,
738
+ for each `t`. If a :class:`torch.nn.utils.rnn.PackedSequence` has been
739
+ given as the input, the output will also be a packed sequence.
740
+ For the unpacked case, the directions can be separated
741
+ using ``output.view(seq_len, batch, num_directions, hidden_size)``,
742
+ with forward and backward being direction `0` and `1` respectively.
743
+
744
+ Similarly, the directions can be separated in the packed case.
745
+ - **h_n** of shape `(num_layers * num_directions, batch, hidden_size)`: tensor
746
+ containing the hidden state for `t = seq_len`
747
+
748
+ Like *output*, the layers can be separated using
749
+ ``h_n.view(num_layers, num_directions, batch, hidden_size)``.
750
+
751
+ Shape:
752
+ - Input1: :math:`(L, N, H_{in})` tensor containing input features where
753
+ :math:`H_{in}=\text{input\_size}` and `L` represents a sequence length.
754
+ - Input2: :math:`(S, N, H_{out})` tensor
755
+ containing the initial hidden state for each element in the batch.
756
+ :math:`H_{out}=\text{hidden\_size}`
757
+ Defaults to zero if not provided. where :math:`S=\text{num\_layers} * \text{num\_directions}`
758
+ If the RNN is bidirectional, num_directions should be 2, else it should be 1.
759
+ - Output1: :math:`(L, N, H_{all})` where :math:`H_{all}=\text{num\_directions} * \text{hidden\_size}`
760
+ - Output2: :math:`(S, N, H_{out})` tensor containing the next hidden state
761
+ for each element in the batch
762
+
763
+ Attributes:
764
+ weight_ih_l[k] : the learnable input-hidden weights of the :math:`\text{k}^{th}` layer
765
+ (W_ir|W_iz|W_in), of shape `(3*hidden_size, input_size)` for `k = 0`.
766
+ Otherwise, the shape is `(3*hidden_size, num_directions * hidden_size)`
767
+ weight_hh_l[k] : the learnable hidden-hidden weights of the :math:`\text{k}^{th}` layer
768
+ (W_hr|W_hz|W_hn), of shape `(3*hidden_size, hidden_size)`
769
+ bias_ih_l[k] : the learnable input-hidden bias of the :math:`\text{k}^{th}` layer
770
+ (b_ir|b_iz|b_in), of shape `(3*hidden_size)`
771
+ bias_hh_l[k] : the learnable hidden-hidden bias of the :math:`\text{k}^{th}` layer
772
+ (b_hr|b_hz|b_hn), of shape `(3*hidden_size)`
773
+
774
+ .. note::
775
+ All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`
776
+ where :math:`k = \frac{1}{\text{hidden\_size}}`
777
+
778
+ .. note::
779
+ The calculation of new gate :math:`n_t` subtly differs from the original paper and other frameworks.
780
+ In the original implementation, the Hadamard product :math:`(\odot)` between :math:`r_t` and the
781
+ previous hidden state :math:`h_{(t-1)}` is done before the multiplication with the weight matrix
782
+ `W` and addition of bias:
783
+
784
+ .. math::
785
+ \begin{aligned}
786
+ n_t = \tanh(W_{in} x_t + b_{in} + W_{hn} ( r_t \odot h_{(t-1)} ) + b_{hn})
787
+ \end{aligned}
788
+
789
+ This is in contrast to PyTorch implementation, which is done after :math:`W_{hn} h_{(t-1)}`
790
+
791
+ .. math::
792
+ \begin{aligned}
793
+ n_t = \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{(t-1)}+ b_{hn}))
794
+ \end{aligned}
795
+
796
+ This implementation differs on purpose for efficiency.
797
+
798
+ .. include:: ../cudnn_persistent_rnn.rst
799
+
800
+ Examples::
801
+
802
+ >>> # xdoctest: +SKIP
803
+ >>> rnn = nn.GRU(10, 20, 2)
804
+ >>> input = torch.randn(5, 3, 10)
805
+ >>> h0 = torch.randn(2, 3, 20)
806
+ >>> output, hn = rnn(input, h0)
807
+ """
808
+ _FLOAT_MODULE = nn.GRU
809
+
810
+ __overloads__ = {"forward": ["forward_packed", "forward_tensor"]}
811
+
812
+ def __init__(self, *args, **kwargs):
813
+ super().__init__("GRU", *args, **kwargs)
814
+
815
+ def _get_name(self):
816
+ return "DynamicQuantizedGRU"
817
+
818
+ def check_forward_args(
819
+ self, input: Tensor, hidden: Tensor, batch_sizes: Optional[Tensor]
820
+ ) -> None:
821
+ self.check_input(input, batch_sizes)
822
+ expected_hidden_size = self.get_expected_hidden_size(input, batch_sizes)
823
+
824
+ self.check_hidden_size(
825
+ hidden, expected_hidden_size, "Expected hidden size {}, got {}"
826
+ )
827
+
828
+ def forward_impl(
829
+ self,
830
+ input: Tensor,
831
+ hx: Optional[Tensor],
832
+ batch_sizes: Optional[Tensor],
833
+ max_batch_size: int,
834
+ sorted_indices: Optional[Tensor],
835
+ ) -> tuple[Tensor, Tensor]:
836
+ if hx is None:
837
+ num_directions = 2 if self.bidirectional else 1
838
+ zeros = torch.zeros(
839
+ self.num_layers * num_directions,
840
+ max_batch_size,
841
+ self.hidden_size,
842
+ dtype=input.dtype,
843
+ device=input.device,
844
+ )
845
+ hx = zeros
846
+ else:
847
+ # Each batch of the hidden state should match the input sequence that
848
+ # the user believes he/she is passing in.
849
+ hx = self.permute_hidden(hx, sorted_indices)
850
+
851
+ self.check_forward_args(input, hx, batch_sizes)
852
+
853
+ _all_params = [m.param for m in self._all_weight_values]
854
+ if batch_sizes is None:
855
+ result = torch.quantized_gru(
856
+ input,
857
+ hx,
858
+ _all_params,
859
+ self.bias,
860
+ self.num_layers,
861
+ self.dropout,
862
+ self.training,
863
+ self.bidirectional,
864
+ self.batch_first,
865
+ )
866
+ else:
867
+ result = torch.quantized_gru(
868
+ input,
869
+ batch_sizes,
870
+ hx,
871
+ _all_params,
872
+ self.bias,
873
+ self.num_layers,
874
+ self.dropout,
875
+ self.training,
876
+ self.bidirectional,
877
+ )
878
+ output = result[0]
879
+ hidden = result[1]
880
+
881
+ return output, hidden
882
+
883
+ @torch.jit.export
884
+ def forward_tensor(
885
+ self, input: Tensor, hx: Optional[Tensor] = None
886
+ ) -> tuple[Tensor, Tensor]:
887
+ batch_sizes = None
888
+ max_batch_size = input.size(0) if self.batch_first else input.size(1)
889
+ sorted_indices = None
890
+ unsorted_indices = None
891
+
892
+ output, hidden = self.forward_impl(
893
+ input, hx, batch_sizes, max_batch_size, sorted_indices
894
+ )
895
+
896
+ return output, self.permute_hidden(hidden, unsorted_indices)
897
+
898
+ @torch.jit.export
899
+ def forward_packed(
900
+ self, input: PackedSequence, hx: Optional[Tensor] = None
901
+ ) -> tuple[PackedSequence, Tensor]:
902
+ input_, batch_sizes, sorted_indices, unsorted_indices = input
903
+ max_batch_size = int(batch_sizes[0])
904
+ output_, hidden = self.forward_impl(
905
+ input_, hx, batch_sizes, max_batch_size, sorted_indices
906
+ )
907
+
908
+ output = PackedSequence(output_, batch_sizes, sorted_indices, unsorted_indices)
909
+ return output, self.permute_hidden(hidden, unsorted_indices)
910
+
911
+ def permute_hidden(self, hx: Tensor, permutation: Optional[Tensor]) -> Tensor:
912
+ if permutation is None:
913
+ return hx
914
+ return _apply_permutation(hx, permutation)
915
+
916
+ @torch.jit.ignore
917
+ def forward(self, input, hx=None):
918
+ if isinstance(input, PackedSequence):
919
+ return self.forward_packed(input, hx)
920
+ else:
921
+ return self.forward_tensor(input, hx)
922
+
923
+ @classmethod
924
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
925
+ return super().from_float(
926
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
927
+ )
928
+
929
+ @classmethod
930
+ def from_reference(cls, ref_mod):
931
+ assert hasattr(ref_mod, "weight_ih_l0_dtype"), "We are assuming weight_ih_l0 "
932
+ "exists in LSTM, may need to relax the assumption to support the use case"
933
+ qmod = cls(
934
+ ref_mod.input_size,
935
+ ref_mod.hidden_size,
936
+ ref_mod.num_layers,
937
+ ref_mod.bias,
938
+ ref_mod.batch_first,
939
+ ref_mod.dropout,
940
+ ref_mod.bidirectional,
941
+ # assuming there is layer 0, which should be OK
942
+ ref_mod.weight_ih_l0_dtype,
943
+ )
944
+ qmod.set_weight_bias(ref_mod.get_quantized_weight_bias_dict())
945
+ return qmod
946
+
947
+
948
+ class RNNCellBase(torch.nn.Module):
949
+ # _FLOAT_MODULE = nn.CellRNNBase
950
+ __constants__ = ["input_size", "hidden_size", "bias"]
951
+
952
+ def __init__(
953
+ self, input_size, hidden_size, bias=True, num_chunks=4, dtype=torch.qint8
954
+ ):
955
+ super().__init__()
956
+ self.input_size = input_size
957
+ self.hidden_size = hidden_size
958
+ self.bias = bias
959
+ self.weight_dtype = dtype
960
+ if bias:
961
+ self.bias_ih = torch.randn(num_chunks * hidden_size).to(dtype=torch.float)
962
+ self.bias_hh = torch.randn(num_chunks * hidden_size).to(dtype=torch.float)
963
+ else:
964
+ self.register_parameter("bias_ih", None)
965
+ self.register_parameter("bias_hh", None)
966
+
967
+ weight_ih = torch.randn(num_chunks * hidden_size, input_size).to(torch.float)
968
+ weight_hh = torch.randn(num_chunks * hidden_size, hidden_size).to(torch.float)
969
+ if dtype == torch.qint8:
970
+ weight_ih = torch.quantize_per_tensor(
971
+ weight_ih, scale=1, zero_point=0, dtype=torch.qint8
972
+ )
973
+ weight_hh = torch.quantize_per_tensor(
974
+ weight_hh, scale=1, zero_point=0, dtype=torch.qint8
975
+ )
976
+
977
+ if dtype == torch.qint8:
978
+ # for each layer, for each direction we need to quantize and pack
979
+ # weights and pack parameters in this order:
980
+ #
981
+ # w_ih, w_hh
982
+ packed_weight_ih = torch.ops.quantized.linear_prepack(
983
+ weight_ih, self.bias_ih
984
+ )
985
+ packed_weight_hh = torch.ops.quantized.linear_prepack(
986
+ weight_hh, self.bias_hh
987
+ )
988
+ else:
989
+ # for each layer, for each direction we need to quantize and pack
990
+ # weights and pack parameters in this order:
991
+ #
992
+ # packed_ih, packed_hh, b_ih, b_hh
993
+ packed_weight_ih = torch.ops.quantized.linear_prepack_fp16(
994
+ weight_ih, self.bias_ih
995
+ )
996
+ packed_weight_hh = torch.ops.quantized.linear_prepack_fp16(
997
+ weight_hh, self.bias_hh
998
+ )
999
+
1000
+ self._packed_weight_ih = packed_weight_ih
1001
+ self._packed_weight_hh = packed_weight_hh
1002
+
1003
+ def _get_name(self):
1004
+ return "DynamicQuantizedRNNBase"
1005
+
1006
+ def extra_repr(self):
1007
+ s = "{input_size}, {hidden_size}"
1008
+ if "bias" in self.__dict__ and self.bias is not True:
1009
+ s += ", bias={bias}"
1010
+ if "nonlinearity" in self.__dict__ and self.nonlinearity != "tanh":
1011
+ s += ", nonlinearity={nonlinearity}"
1012
+ return s.format(**self.__dict__)
1013
+
1014
+ def check_forward_input(self, input):
1015
+ if input.size(1) != self.input_size:
1016
+ raise RuntimeError(
1017
+ f"input has inconsistent input_size: got {input.size(1)}, expected {self.input_size}"
1018
+ )
1019
+
1020
+ def check_forward_hidden(
1021
+ self, input: Tensor, hx: Tensor, hidden_label: str = ""
1022
+ ) -> None:
1023
+ if input.size(0) != hx.size(0):
1024
+ raise RuntimeError(
1025
+ f"Input batch size {input.size(0)} doesn't match hidden{hidden_label} batch size {hx.size(0)}"
1026
+ )
1027
+
1028
+ if hx.size(1) != self.hidden_size:
1029
+ raise RuntimeError(
1030
+ f"hidden{hidden_label} has inconsistent hidden_size: got {hx.size(1)}, expected {self.hidden_size}"
1031
+ )
1032
+
1033
+ @classmethod
1034
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
1035
+ assert type(mod) in {
1036
+ torch.nn.LSTMCell,
1037
+ torch.nn.GRUCell,
1038
+ torch.nn.RNNCell,
1039
+ }, "nn.quantized.dynamic.RNNCellBase.from_float \
1040
+ only works for nn.LSTMCell, nn.GRUCell and nn.RNNCell"
1041
+ assert hasattr(mod, "qconfig"), "Input float module must have qconfig defined"
1042
+
1043
+ if mod.qconfig is not None and mod.qconfig.weight is not None:
1044
+ weight_observer_method = mod.qconfig.weight
1045
+ else:
1046
+ # We have the circular import issues if we import the qconfig in the beginning of this file:
1047
+ # https://github.com/pytorch/pytorch/pull/24231. The current workaround is to postpone the
1048
+ # import until we need it.
1049
+ from torch.ao.quantization.qconfig import default_dynamic_qconfig
1050
+
1051
+ weight_observer_method = default_dynamic_qconfig.weight
1052
+
1053
+ dtype = weight_observer_method().dtype
1054
+ supported_scalar_types = [torch.qint8, torch.float16]
1055
+ if dtype not in supported_scalar_types:
1056
+ raise RuntimeError(
1057
+ f"Unsupported dtype for dynamic RNN quantization: {dtype}"
1058
+ )
1059
+
1060
+ qRNNCellBase: Union[LSTMCell, GRUCell, RNNCell]
1061
+
1062
+ if type(mod) == torch.nn.LSTMCell:
1063
+ qRNNCellBase = LSTMCell(
1064
+ mod.input_size, mod.hidden_size, bias=mod.bias, dtype=dtype
1065
+ )
1066
+ elif type(mod) == torch.nn.GRUCell:
1067
+ qRNNCellBase = GRUCell(
1068
+ mod.input_size, mod.hidden_size, bias=mod.bias, dtype=dtype
1069
+ )
1070
+ elif type(mod) == torch.nn.RNNCell:
1071
+ qRNNCellBase = RNNCell(
1072
+ mod.input_size,
1073
+ mod.hidden_size,
1074
+ bias=mod.bias,
1075
+ nonlinearity=mod.nonlinearity,
1076
+ dtype=dtype,
1077
+ )
1078
+ else:
1079
+ raise NotImplementedError(
1080
+ "Only LSTMCell, GRUCell and RNNCell \
1081
+ are supported for QuantizedRNN for now"
1082
+ )
1083
+
1084
+ assert mod.bias
1085
+
1086
+ def _observe_and_quantize_weight(weight):
1087
+ if dtype == torch.qint8:
1088
+ weight_observer = weight_observer_method()
1089
+ weight_observer(weight)
1090
+ qweight = _quantize_weight(weight.float(), weight_observer)
1091
+ return qweight
1092
+ else:
1093
+ return weight.float()
1094
+
1095
+ qRNNCellBase._packed_weight_ih = pack_weight_bias(
1096
+ _observe_and_quantize_weight(mod.weight_ih), mod.bias_ih, dtype
1097
+ )
1098
+ qRNNCellBase._packed_weight_hh = pack_weight_bias(
1099
+ _observe_and_quantize_weight(mod.weight_hh), mod.bias_hh, dtype
1100
+ )
1101
+ return qRNNCellBase
1102
+
1103
+ @classmethod
1104
+ def from_reference(cls, ref_mod):
1105
+ assert hasattr(ref_mod, "weight_ih_dtype"), "We are assuming weight_ih "
1106
+ "exists in reference module, may need to relax the assumption to support the use case"
1107
+ if hasattr(ref_mod, "nonlinearity"):
1108
+ qmod = cls(
1109
+ ref_mod.input_size,
1110
+ ref_mod.hidden_size,
1111
+ ref_mod.bias,
1112
+ ref_mod.nonlinearity,
1113
+ dtype=ref_mod.weight_ih_dtype,
1114
+ )
1115
+ else:
1116
+ qmod = cls(
1117
+ ref_mod.input_size,
1118
+ ref_mod.hidden_size,
1119
+ ref_mod.bias,
1120
+ dtype=ref_mod.weight_ih_dtype,
1121
+ )
1122
+ weight_bias_dict = {
1123
+ "weight": {
1124
+ "weight_ih": ref_mod.get_quantized_weight_ih(),
1125
+ "weight_hh": ref_mod.get_quantized_weight_hh(),
1126
+ },
1127
+ "bias": {
1128
+ "bias_ih": ref_mod.bias_ih,
1129
+ "bias_hh": ref_mod.bias_hh,
1130
+ },
1131
+ }
1132
+ qmod.set_weight_bias(weight_bias_dict)
1133
+ return qmod
1134
+
1135
+ def _weight_bias(self):
1136
+ # Returns a dict of weights and biases
1137
+ weight_bias_dict: Dict[str, Dict] = {"weight": {}, "bias": {}}
1138
+ w1, b1 = self._packed_weight_ih.__getstate__()[0]
1139
+ w2, b2 = self._packed_weight_hh.__getstate__()[0]
1140
+ # TODO: these can be simplified to one level? e.g. using weight_ih as key
1141
+ # directly
1142
+ weight_bias_dict["weight"]["weight_ih"] = w1
1143
+ weight_bias_dict["weight"]["weight_hh"] = w2
1144
+ weight_bias_dict["bias"]["bias_ih"] = b1
1145
+ weight_bias_dict["bias"]["bias_hh"] = b2
1146
+ return weight_bias_dict
1147
+
1148
+ def get_weight(self):
1149
+ return self._weight_bias()["weight"]
1150
+
1151
+ def get_bias(self):
1152
+ return self._weight_bias()["bias"]
1153
+
1154
+ def set_weight_bias(self, weight_bias_dict):
1155
+ # TODO: these can be simplified to one level? e.g. using weight_ih as key
1156
+ # directly
1157
+ self._packed_weight_ih = pack_weight_bias(
1158
+ weight_bias_dict["weight"]["weight_ih"],
1159
+ weight_bias_dict["bias"]["bias_ih"],
1160
+ self.weight_dtype,
1161
+ )
1162
+ self._packed_weight_hh = pack_weight_bias(
1163
+ weight_bias_dict["weight"]["weight_hh"],
1164
+ weight_bias_dict["bias"]["bias_hh"],
1165
+ self.weight_dtype,
1166
+ )
1167
+
1168
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
1169
+ super()._save_to_state_dict(destination, prefix, keep_vars)
1170
+ destination[prefix + "_packed_weight_ih"] = self._packed_weight_ih
1171
+ destination[prefix + "_packed_weight_hh"] = self._packed_weight_hh
1172
+
1173
+ def _load_from_state_dict(
1174
+ self,
1175
+ state_dict,
1176
+ prefix,
1177
+ local_metadata,
1178
+ strict,
1179
+ missing_keys,
1180
+ unexpected_keys,
1181
+ error_msgs,
1182
+ ):
1183
+ self._packed_weight_ih = state_dict.pop(prefix + "_packed_weight_ih")
1184
+ self._packed_weight_hh = state_dict.pop(prefix + "_packed_weight_hh")
1185
+ super()._load_from_state_dict(
1186
+ state_dict,
1187
+ prefix,
1188
+ local_metadata,
1189
+ False,
1190
+ missing_keys,
1191
+ unexpected_keys,
1192
+ error_msgs,
1193
+ )
1194
+
1195
+
1196
+ class RNNCell(RNNCellBase):
1197
+ r"""An Elman RNN cell with tanh or ReLU non-linearity.
1198
+ A dynamic quantized RNNCell module with floating point tensor as inputs and outputs.
1199
+ Weights are quantized to 8 bits. We adopt the same interface as `torch.nn.RNNCell`,
1200
+ please see https://pytorch.org/docs/stable/nn.html#torch.nn.RNNCell for documentation.
1201
+
1202
+ Examples::
1203
+
1204
+ >>> # xdoctest: +SKIP
1205
+ >>> rnn = nn.RNNCell(10, 20)
1206
+ >>> input = torch.randn(6, 3, 10)
1207
+ >>> hx = torch.randn(3, 20)
1208
+ >>> output = []
1209
+ >>> for i in range(6):
1210
+ ... hx = rnn(input[i], hx)
1211
+ ... output.append(hx)
1212
+ """
1213
+ __constants__ = ["input_size", "hidden_size", "bias", "nonlinearity"]
1214
+
1215
+ def __init__(
1216
+ self, input_size, hidden_size, bias=True, nonlinearity="tanh", dtype=torch.qint8
1217
+ ):
1218
+ super().__init__(input_size, hidden_size, bias, num_chunks=1, dtype=dtype)
1219
+ self.nonlinearity = nonlinearity
1220
+
1221
+ def _get_name(self):
1222
+ return "DynamicQuantizedRNNCell"
1223
+
1224
+ def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tensor:
1225
+ self.check_forward_input(input)
1226
+ if hx is None:
1227
+ hx = torch.zeros(
1228
+ input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
1229
+ )
1230
+ self.check_forward_hidden(input, hx, "")
1231
+ if self.nonlinearity == "tanh":
1232
+ ret = torch.ops.quantized.quantized_rnn_tanh_cell_dynamic(
1233
+ input,
1234
+ hx,
1235
+ self._packed_weight_ih,
1236
+ self._packed_weight_hh,
1237
+ self.bias_ih,
1238
+ self.bias_hh,
1239
+ )
1240
+ elif self.nonlinearity == "relu":
1241
+ ret = torch.ops.quantized.quantized_rnn_relu_cell_dynamic(
1242
+ input,
1243
+ hx,
1244
+ self._packed_weight_ih,
1245
+ self._packed_weight_hh,
1246
+ self.bias_ih,
1247
+ self.bias_hh,
1248
+ )
1249
+ else:
1250
+ ret = input # TODO: remove when jit supports exception flow
1251
+ raise RuntimeError(f"Unknown nonlinearity: {self.nonlinearity}")
1252
+ return ret
1253
+
1254
+ @classmethod
1255
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
1256
+ return super().from_float(
1257
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
1258
+ )
1259
+
1260
+
1261
+ class LSTMCell(RNNCellBase):
1262
+ r"""A long short-term memory (LSTM) cell.
1263
+
1264
+ A dynamic quantized LSTMCell module with floating point tensor as inputs and outputs.
1265
+ Weights are quantized to 8 bits. We adopt the same interface as `torch.nn.LSTMCell`,
1266
+ please see https://pytorch.org/docs/stable/nn.html#torch.nn.LSTMCell for documentation.
1267
+
1268
+ Examples::
1269
+
1270
+ >>> # xdoctest: +SKIP
1271
+ >>> rnn = nn.LSTMCell(10, 20)
1272
+ >>> input = torch.randn(6, 3, 10)
1273
+ >>> hx = torch.randn(3, 20)
1274
+ >>> cx = torch.randn(3, 20)
1275
+ >>> output = []
1276
+ >>> for i in range(6):
1277
+ ... hx, cx = rnn(input[i], (hx, cx))
1278
+ ... output.append(hx)
1279
+ """
1280
+
1281
+ def __init__(self, *args, **kwargs):
1282
+ super().__init__(*args, num_chunks=4, **kwargs) # type: ignore[misc]
1283
+
1284
+ def _get_name(self):
1285
+ return "DynamicQuantizedLSTMCell"
1286
+
1287
+ def forward(
1288
+ self, input: Tensor, hx: Optional[tuple[Tensor, Tensor]] = None
1289
+ ) -> tuple[Tensor, Tensor]:
1290
+ self.check_forward_input(input)
1291
+ if hx is None:
1292
+ zeros = torch.zeros(
1293
+ input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
1294
+ )
1295
+ hx = (zeros, zeros)
1296
+ self.check_forward_hidden(input, hx[0], "[0]")
1297
+ self.check_forward_hidden(input, hx[1], "[1]")
1298
+ return torch.ops.quantized.quantized_lstm_cell_dynamic(
1299
+ input,
1300
+ hx,
1301
+ self._packed_weight_ih,
1302
+ self._packed_weight_hh,
1303
+ self.bias_ih,
1304
+ self.bias_hh,
1305
+ )
1306
+
1307
+ @classmethod
1308
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
1309
+ return super().from_float(
1310
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
1311
+ )
1312
+
1313
+
1314
+ class GRUCell(RNNCellBase):
1315
+ r"""A gated recurrent unit (GRU) cell
1316
+
1317
+ A dynamic quantized GRUCell module with floating point tensor as inputs and outputs.
1318
+ Weights are quantized to 8 bits. We adopt the same interface as `torch.nn.GRUCell`,
1319
+ please see https://pytorch.org/docs/stable/nn.html#torch.nn.GRUCell for documentation.
1320
+
1321
+ Examples::
1322
+
1323
+ >>> # xdoctest: +SKIP
1324
+ >>> rnn = nn.GRUCell(10, 20)
1325
+ >>> input = torch.randn(6, 3, 10)
1326
+ >>> hx = torch.randn(3, 20)
1327
+ >>> output = []
1328
+ >>> for i in range(6):
1329
+ ... hx = rnn(input[i], hx)
1330
+ ... output.append(hx)
1331
+ """
1332
+
1333
+ def __init__(self, input_size, hidden_size, bias=True, dtype=torch.qint8):
1334
+ super().__init__(input_size, hidden_size, bias, num_chunks=3, dtype=dtype)
1335
+
1336
+ def _get_name(self):
1337
+ return "DynamicQuantizedGRUCell"
1338
+
1339
+ def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tensor:
1340
+ self.check_forward_input(input)
1341
+ if hx is None:
1342
+ hx = torch.zeros(
1343
+ input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
1344
+ )
1345
+ self.check_forward_hidden(input, hx, "")
1346
+ return torch.ops.quantized.quantized_gru_cell_dynamic(
1347
+ input,
1348
+ hx,
1349
+ self._packed_weight_ih,
1350
+ self._packed_weight_hh,
1351
+ self.bias_ih,
1352
+ self.bias_hh,
1353
+ )
1354
+
1355
+ @classmethod
1356
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
1357
+ return super().from_float(
1358
+ mod, use_precomputed_fake_quant=use_precomputed_fake_quant
1359
+ )
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (5.95 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/activation.cpython-312.pyc ADDED
Binary file (18.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/batchnorm.cpython-312.pyc ADDED
Binary file (6.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/conv.cpython-312.pyc ADDED
Binary file (48.9 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/dropout.cpython-312.pyc ADDED
Binary file (1.64 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/embedding_ops.cpython-312.pyc ADDED
Binary file (18.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/functional_modules.cpython-312.pyc ADDED
Binary file (12.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/linear.cpython-312.pyc ADDED
Binary file (15.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/normalization.cpython-312.pyc ADDED
Binary file (11.9 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/rnn.cpython-312.pyc ADDED
Binary file (2.55 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/modules/__pycache__/utils.cpython-312.pyc ADDED
Binary file (7.02 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (403 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .conv import (
2
+ Conv1d,
3
+ Conv2d,
4
+ Conv3d,
5
+ ConvTranspose1d,
6
+ ConvTranspose2d,
7
+ ConvTranspose3d,
8
+ )
9
+ from .linear import Linear
10
+ from .rnn import GRU, GRUCell, LSTM, LSTMCell, RNNCell
11
+ from .sparse import Embedding, EmbeddingBag
12
+
13
+
14
+ __all__ = [
15
+ "Linear",
16
+ "Conv1d",
17
+ "Conv2d",
18
+ "Conv3d",
19
+ "ConvTranspose1d",
20
+ "ConvTranspose2d",
21
+ "ConvTranspose3d",
22
+ "RNNCell",
23
+ "LSTMCell",
24
+ "GRUCell",
25
+ "LSTM",
26
+ "GRU",
27
+ "Embedding",
28
+ "EmbeddingBag",
29
+ ]
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (671 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/conv.cpython-312.pyc ADDED
Binary file (16.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/linear.cpython-312.pyc ADDED
Binary file (3.62 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/rnn.cpython-312.pyc ADDED
Binary file (30.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/sparse.cpython-312.pyc ADDED
Binary file (5.96 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/__pycache__/utils.cpython-312.pyc ADDED
Binary file (15.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/conv.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Any, Optional
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from torch.nn.common_types import _size_1_t
8
+
9
+ from .utils import ReferenceQuantizedModule
10
+
11
+
12
+ __all__ = [
13
+ "Conv1d",
14
+ "Conv2d",
15
+ "Conv3d",
16
+ "ConvTranspose1d",
17
+ "ConvTranspose2d",
18
+ "ConvTranspose3d",
19
+ ]
20
+
21
+
22
+ class _ConvNd(torch.nn.modules.conv._ConvNd, ReferenceQuantizedModule):
23
+ """A reference version of nn.quantized.Conv2d
24
+ we will not pack the parameters in this module, since weight packing is an
25
+ optimization for quantized backends supported in PyTorch (fbgemm/qnnpack),
26
+ this is useful when user want to use this module in other backends like Glow.
27
+ """
28
+
29
+ __annotations__ = {"bias": Optional[torch.Tensor]}
30
+ _IS_REFERENCE = True
31
+
32
+ @staticmethod
33
+ def from_float(cls, float_conv, weight_qparams):
34
+ qref_conv = cls(
35
+ float_conv.in_channels,
36
+ float_conv.out_channels,
37
+ float_conv.kernel_size, # type: ignore[arg-type]
38
+ float_conv.stride, # type: ignore[arg-type]
39
+ float_conv.padding, # type: ignore[arg-type]
40
+ float_conv.dilation, # type: ignore[arg-type]
41
+ float_conv.groups,
42
+ float_conv.bias is not None, # type: ignore[arg-type]
43
+ float_conv.padding_mode,
44
+ device=float_conv.weight.device,
45
+ dtype=float_conv.weight.dtype,
46
+ weight_qparams=weight_qparams,
47
+ )
48
+ qref_conv.weight = torch.nn.Parameter(float_conv.weight.detach())
49
+ if float_conv.bias is not None:
50
+ qref_conv.bias = torch.nn.Parameter(float_conv.bias.detach())
51
+ return qref_conv
52
+
53
+
54
+ class Conv1d(_ConvNd, nn.Conv1d):
55
+ def __init__(
56
+ self,
57
+ in_channels: int,
58
+ out_channels: int,
59
+ kernel_size: _size_1_t,
60
+ stride: _size_1_t = 1,
61
+ padding: _size_1_t = 0,
62
+ dilation: _size_1_t = 1,
63
+ groups: int = 1,
64
+ bias: bool = True,
65
+ padding_mode: str = "zeros",
66
+ device=None,
67
+ dtype=None,
68
+ weight_qparams: Optional[dict[str, Any]] = None,
69
+ ):
70
+ nn.Conv1d.__init__(
71
+ self,
72
+ in_channels,
73
+ out_channels,
74
+ kernel_size,
75
+ stride,
76
+ padding,
77
+ dilation,
78
+ groups,
79
+ bias,
80
+ padding_mode,
81
+ device,
82
+ dtype,
83
+ )
84
+ self._init_weight_qparams(weight_qparams, device)
85
+
86
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
87
+ """
88
+ we have:
89
+ w(float) -- quant - dequant \
90
+ x(float) ------------- F.conv1d ---
91
+
92
+ In the full model, we will see
93
+ w(float) -- quant - *dequant \
94
+ x -- quant --- *dequant -- *F.conv1d --- *quant - dequant
95
+ and the backend should be able to fuse the ops with `*` into a quantized conv1d
96
+ """
97
+ weight_quant_dequant = self.get_weight()
98
+ result = F.conv1d(
99
+ x,
100
+ weight_quant_dequant,
101
+ self.bias,
102
+ self.stride,
103
+ self.padding,
104
+ self.dilation,
105
+ self.groups,
106
+ )
107
+ return result
108
+
109
+ def _get_name(self):
110
+ return "QuantizedConv1d(Reference)"
111
+
112
+ @classmethod
113
+ def from_float(cls, float_conv, weight_qparams):
114
+ return _ConvNd.from_float(cls, float_conv, weight_qparams)
115
+
116
+
117
+ class Conv2d(_ConvNd, nn.Conv2d):
118
+ def __init__(
119
+ self,
120
+ in_channels,
121
+ out_channels,
122
+ kernel_size,
123
+ stride=1,
124
+ padding=0,
125
+ dilation=1,
126
+ groups=1,
127
+ bias=True,
128
+ padding_mode="zeros",
129
+ device=None,
130
+ dtype=None,
131
+ weight_qparams: Optional[dict[str, Any]] = None,
132
+ ):
133
+ nn.Conv2d.__init__(
134
+ self,
135
+ in_channels,
136
+ out_channels,
137
+ kernel_size,
138
+ stride,
139
+ padding,
140
+ dilation,
141
+ groups,
142
+ bias,
143
+ padding_mode,
144
+ device,
145
+ dtype,
146
+ )
147
+ self._init_weight_qparams(weight_qparams, device)
148
+
149
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
150
+ """
151
+ we have:
152
+ w(float) -- quant - dequant \
153
+ x(float) ------------- F.conv2d ---
154
+
155
+ In the full model, we will see
156
+ w(float) -- quant - *dequant \
157
+ x -- quant --- *dequant -- *F.conv2d --- *quant - dequant
158
+ and the backend should be able to fuse the ops with `*` into a quantized conv2d
159
+ """
160
+ weight_quant_dequant = self.get_weight()
161
+ result = F.conv2d(
162
+ x,
163
+ weight_quant_dequant,
164
+ self.bias,
165
+ self.stride,
166
+ self.padding,
167
+ self.dilation,
168
+ self.groups,
169
+ )
170
+ return result
171
+
172
+ def _get_name(self):
173
+ return "QuantizedConv2d(Reference)"
174
+
175
+ @classmethod
176
+ def from_float(cls, float_conv, weight_qparams):
177
+ return _ConvNd.from_float(cls, float_conv, weight_qparams)
178
+
179
+
180
+ class Conv3d(_ConvNd, nn.Conv3d):
181
+ def __init__(
182
+ self,
183
+ in_channels,
184
+ out_channels,
185
+ kernel_size,
186
+ stride=1,
187
+ padding=0,
188
+ dilation=1,
189
+ groups=1,
190
+ bias=True,
191
+ padding_mode="zeros",
192
+ device=None,
193
+ dtype=None,
194
+ weight_qparams: Optional[dict[str, Any]] = None,
195
+ ):
196
+ nn.Conv3d.__init__(
197
+ self,
198
+ in_channels,
199
+ out_channels,
200
+ kernel_size,
201
+ stride,
202
+ padding,
203
+ dilation,
204
+ groups,
205
+ bias,
206
+ padding_mode,
207
+ device,
208
+ dtype,
209
+ )
210
+ self._init_weight_qparams(weight_qparams, device)
211
+
212
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
213
+ """
214
+ we have:
215
+ w(float) -- quant - dequant \
216
+ x(float) ------------- F.conv3d ---
217
+
218
+ In the full model, we will see
219
+ w(float) -- quant - *dequant \
220
+ x -- quant --- *dequant -- *F.conv3d --- *quant - dequant
221
+ and the backend should be able to fuse the ops with `*` into a quantized conv3d
222
+ """
223
+ weight_quant_dequant = self.get_weight()
224
+ result = F.conv3d(
225
+ x,
226
+ weight_quant_dequant,
227
+ self.bias,
228
+ self.stride,
229
+ self.padding,
230
+ self.dilation,
231
+ self.groups,
232
+ )
233
+ return result
234
+
235
+ def _get_name(self):
236
+ return "QuantizedConv3d(Reference)"
237
+
238
+ @classmethod
239
+ def from_float(cls, float_conv, weight_qparams):
240
+ return _ConvNd.from_float(cls, float_conv, weight_qparams)
241
+
242
+
243
+ class _ConvTransposeNd(_ConvNd, torch.nn.modules.conv._ConvTransposeNd):
244
+ """A reference version of nn.quantized.ConvTranspose2d
245
+ we will not pack the parameters in this module, since weight packing is an
246
+ optimization for quantized backends supported in PyTorch (fbgemm/qnnpack),
247
+ this is useful when user want to use this module in other backends like Glow.
248
+ """
249
+
250
+ @staticmethod
251
+ def from_float(cls, float_conv, weight_qparams):
252
+ qref_conv = cls(
253
+ float_conv.in_channels,
254
+ float_conv.out_channels,
255
+ float_conv.kernel_size, # type: ignore[arg-type]
256
+ float_conv.stride, # type: ignore[arg-type]
257
+ float_conv.padding, # type: ignore[arg-type]
258
+ float_conv.output_padding, # type: ignore[arg-type]
259
+ float_conv.groups,
260
+ float_conv.bias is not None, # type: ignore[arg-type]
261
+ float_conv.dilation, # type: ignore[arg-type]
262
+ float_conv.padding_mode,
263
+ device=float_conv.weight.device,
264
+ dtype=float_conv.weight.dtype,
265
+ weight_qparams=weight_qparams,
266
+ )
267
+ qref_conv.weight = torch.nn.Parameter(float_conv.weight.detach())
268
+ if float_conv.bias is not None:
269
+ qref_conv.bias = torch.nn.Parameter(float_conv.bias.detach())
270
+ return qref_conv
271
+
272
+
273
+ class ConvTranspose1d(_ConvTransposeNd, nn.ConvTranspose1d):
274
+ def __init__(
275
+ self,
276
+ in_channels: int,
277
+ out_channels: int,
278
+ kernel_size: _size_1_t,
279
+ stride: _size_1_t = 1,
280
+ padding: _size_1_t = 0,
281
+ output_padding: _size_1_t = 0,
282
+ groups: int = 1,
283
+ bias: bool = True,
284
+ dilation: _size_1_t = 1,
285
+ padding_mode: str = "zeros",
286
+ device=None,
287
+ dtype=None,
288
+ weight_qparams: Optional[dict[str, Any]] = None,
289
+ ):
290
+ nn.ConvTranspose1d.__init__(
291
+ self,
292
+ in_channels,
293
+ out_channels,
294
+ kernel_size,
295
+ stride,
296
+ padding,
297
+ output_padding,
298
+ groups,
299
+ bias,
300
+ dilation,
301
+ padding_mode,
302
+ device,
303
+ dtype,
304
+ )
305
+ self._init_weight_qparams(weight_qparams, device)
306
+
307
+ def forward(
308
+ self, x: torch.Tensor, output_size: Optional[list[int]] = None
309
+ ) -> torch.Tensor:
310
+ """
311
+ we have:
312
+ w(float) -- quant - dequant \
313
+ x(float) ------------- F.convTranspose1d ---
314
+ In the full model, we will see
315
+ w(float) -- quant - *dequant \
316
+ x -- quant --- *dequant -- *F.convTranspose1d --- *quant - dequant
317
+ and the backend should be able to fuse the ops with `*` into a quantized conv1d
318
+ """
319
+
320
+ assert isinstance(self.padding, tuple)
321
+ # One cannot replace List by Tuple or Sequence in "_output_padding" because
322
+ # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
323
+ output_padding = self._output_padding(
324
+ input, # type: ignore[arg-type]
325
+ output_size,
326
+ self.stride, # type: ignore[arg-type]
327
+ self.padding, # type: ignore[arg-type]
328
+ self.kernel_size, # type: ignore[arg-type]
329
+ self.dilation, # type: ignore[arg-type]
330
+ )
331
+
332
+ weight_quant_dequant = self.get_weight()
333
+ result = F.conv_transpose1d(
334
+ x,
335
+ weight_quant_dequant,
336
+ self.bias,
337
+ self.stride,
338
+ self.padding,
339
+ output_padding,
340
+ self.groups,
341
+ self.dilation,
342
+ )
343
+ return result
344
+
345
+ def _get_name(self):
346
+ return "QuantizedConvTranspose1d(Reference)"
347
+
348
+ @classmethod
349
+ def from_float(cls, float_conv, weight_qparams):
350
+ return _ConvTransposeNd.from_float(cls, float_conv, weight_qparams)
351
+
352
+
353
+ class ConvTranspose2d(_ConvTransposeNd, nn.ConvTranspose2d):
354
+ def __init__(
355
+ self,
356
+ in_channels,
357
+ out_channels,
358
+ kernel_size,
359
+ stride=1,
360
+ padding=0,
361
+ output_padding=0,
362
+ groups=1,
363
+ bias=True,
364
+ dilation=1,
365
+ padding_mode="zeros",
366
+ device=None,
367
+ dtype=None,
368
+ weight_qparams: Optional[dict[str, Any]] = None,
369
+ ):
370
+ nn.ConvTranspose2d.__init__(
371
+ self,
372
+ in_channels,
373
+ out_channels,
374
+ kernel_size,
375
+ stride,
376
+ padding,
377
+ output_padding,
378
+ groups,
379
+ bias,
380
+ dilation,
381
+ padding_mode,
382
+ device,
383
+ dtype,
384
+ )
385
+ self._init_weight_qparams(weight_qparams, device)
386
+
387
+ def forward(
388
+ self, x: torch.Tensor, output_size: Optional[list[int]] = None
389
+ ) -> torch.Tensor:
390
+ """
391
+ we have:
392
+ w(float) -- quant - dequant \
393
+ x(float) ------------- F.convTranspose2d ---
394
+ In the full model, we will see
395
+ w(float) -- quant - *dequant \
396
+ x -- quant --- *dequant -- *F.convTranspose2d --- *quant - dequant
397
+ and the backend should be able to fuse the ops with `*` into a quantized conv2d
398
+ """
399
+ assert isinstance(self.padding, tuple)
400
+ # One cannot replace List by Tuple or Sequence in "_output_padding" because
401
+ # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
402
+
403
+ output_padding = self._output_padding(
404
+ input, # type: ignore[arg-type]
405
+ output_size,
406
+ self.stride, # type: ignore[arg-type]
407
+ self.padding, # type: ignore[arg-type]
408
+ self.kernel_size, # type: ignore[arg-type]
409
+ self.dilation, # type: ignore[arg-type]
410
+ )
411
+
412
+ weight_quant_dequant = self.get_weight()
413
+ result = F.conv_transpose2d(
414
+ x,
415
+ weight_quant_dequant,
416
+ self.bias,
417
+ self.stride,
418
+ self.padding,
419
+ output_padding,
420
+ self.groups,
421
+ self.dilation,
422
+ )
423
+
424
+ return result
425
+
426
+ def _get_name(self):
427
+ return "QuantizedConvTranspose2d(Reference)"
428
+
429
+ @classmethod
430
+ def from_float(cls, float_conv, weight_qparams):
431
+ return _ConvTransposeNd.from_float(cls, float_conv, weight_qparams)
432
+
433
+
434
+ class ConvTranspose3d(_ConvTransposeNd, nn.ConvTranspose3d):
435
+ def __init__(
436
+ self,
437
+ in_channels,
438
+ out_channels,
439
+ kernel_size,
440
+ stride=1,
441
+ padding=0,
442
+ output_padding=0,
443
+ groups=1,
444
+ bias=True,
445
+ dilation=1,
446
+ padding_mode="zeros",
447
+ device=None,
448
+ dtype=None,
449
+ weight_qparams: Optional[dict[str, Any]] = None,
450
+ ):
451
+ nn.ConvTranspose3d.__init__(
452
+ self,
453
+ in_channels,
454
+ out_channels,
455
+ kernel_size,
456
+ stride,
457
+ padding,
458
+ output_padding,
459
+ groups,
460
+ bias,
461
+ dilation,
462
+ padding_mode,
463
+ device,
464
+ dtype,
465
+ )
466
+ self._init_weight_qparams(weight_qparams, device)
467
+
468
+ def forward(
469
+ self, x: torch.Tensor, output_size: Optional[list[int]] = None
470
+ ) -> torch.Tensor:
471
+ """
472
+ we have:
473
+ w(float) -- quant - dequant \
474
+ x(float) ------------- F.convTranspose3d ---
475
+ In the full model, we will see
476
+ w(float) -- quant - *dequant \
477
+ x -- quant --- *dequant -- *F.convTranspose3d --- *quant - dequant
478
+ and the backend should be able to fuse the ops with `*` into a quantized conv3d
479
+ """
480
+
481
+ assert isinstance(self.padding, tuple)
482
+ # One cannot replace List by Tuple or Sequence in "_output_padding" because
483
+ # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
484
+ output_padding = self._output_padding(
485
+ input, # type: ignore[arg-type]
486
+ output_size,
487
+ self.stride, # type: ignore[arg-type]
488
+ self.padding, # type: ignore[arg-type]
489
+ self.kernel_size, # type: ignore[arg-type]
490
+ self.dilation, # type: ignore[arg-type]
491
+ )
492
+
493
+ weight_quant_dequant = self.get_weight()
494
+ result = F.conv_transpose3d(
495
+ x,
496
+ weight_quant_dequant,
497
+ self.bias,
498
+ self.stride,
499
+ self.padding,
500
+ output_padding,
501
+ self.groups,
502
+ self.dilation,
503
+ )
504
+ return result
505
+
506
+ def _get_name(self):
507
+ return "QuantizedConvTranspose3d(Reference)"
508
+
509
+ @classmethod
510
+ def from_float(cls, float_conv, weight_qparams):
511
+ return _ConvTransposeNd.from_float(cls, float_conv, weight_qparams)
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/linear.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional
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: Optional[torch.device] = None,
30
+ dtype: Optional[torch.dtype] = None,
31
+ weight_qparams: Optional[dict[str, Any]] = 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
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/rnn.py ADDED
@@ -0,0 +1,845 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Any, Optional
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 (
86
+ len(weight_qparams_dict) == 3
87
+ ), "Expected length for weight_qparams_dict to be 3 for QuantizedRNNCellBase(Reference)"
88
+ self._init_weight_qparams_dict(weight_qparams_dict, device)
89
+
90
+ def _init_weight_qparams_dict(self, weight_qparams_dict, device):
91
+ assert weight_qparams_dict is not None
92
+ self.is_decomposed = weight_qparams_dict["is_decomposed"]
93
+ for key, weight_qparams in weight_qparams_dict.items():
94
+ if key == "is_decomposed":
95
+ continue
96
+ # TODO: refactor the duplicated code to utils.py
97
+ weight_qscheme = weight_qparams["qscheme"]
98
+ weight_dtype = weight_qparams["dtype"]
99
+ setattr(self, key + "_qscheme", weight_qscheme)
100
+ setattr(self, key + "_dtype", weight_dtype)
101
+ assert weight_qscheme in [
102
+ None,
103
+ torch.per_tensor_affine,
104
+ torch.per_channel_affine,
105
+ ], Exception(
106
+ f"qscheme: {weight_qscheme} is not support in {self._get_name()}"
107
+ )
108
+ if weight_qscheme is not None:
109
+ scale = weight_qparams["scale"]
110
+ scale_tensor = (
111
+ scale.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: Optional[dict[str, Any]] = None,
170
+ ) -> None:
171
+ factory_kwargs = {
172
+ "device": device,
173
+ "dtype": dtype,
174
+ "weight_qparams_dict": weight_qparams_dict,
175
+ }
176
+ super().__init__(input_size, hidden_size, bias, num_chunks=1, **factory_kwargs)
177
+ self.nonlinearity = nonlinearity
178
+
179
+ def _get_name(self):
180
+ return "QuantizedRNNCell(Reference)"
181
+
182
+ # TODO: refactor nn.RNNCell to have a _forward that takes weight_ih and weight_hh as input
183
+ # and remove duplicated code, same for the other two Cell modules
184
+ def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tensor:
185
+ assert input.dim() in (
186
+ 1,
187
+ 2,
188
+ ), f"RNNCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
189
+ is_batched = input.dim() == 2
190
+ if not is_batched:
191
+ input = input.unsqueeze(0)
192
+
193
+ if hx is None:
194
+ hx = torch.zeros(
195
+ input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
196
+ )
197
+ else:
198
+ hx = hx.unsqueeze(0) if not is_batched else hx
199
+
200
+ if self.nonlinearity == "tanh":
201
+ ret = _VF.rnn_tanh_cell(
202
+ input,
203
+ hx,
204
+ self.get_weight_ih(),
205
+ self.get_weight_hh(),
206
+ self.bias_ih,
207
+ self.bias_hh,
208
+ )
209
+ elif self.nonlinearity == "relu":
210
+ ret = _VF.rnn_relu_cell(
211
+ input,
212
+ hx,
213
+ self.get_weight_ih(),
214
+ self.get_weight_hh(),
215
+ self.bias_ih,
216
+ self.bias_hh,
217
+ )
218
+ else:
219
+ ret = input # TODO: remove when jit supports exception flow
220
+ raise RuntimeError(f"Unknown nonlinearity: {self.nonlinearity}")
221
+
222
+ if not is_batched:
223
+ ret = ret.squeeze(0)
224
+
225
+ return ret
226
+
227
+ @classmethod
228
+ def from_float(cls, mod, weight_qparams_dict):
229
+ ref_mod = cls(
230
+ mod.input_size,
231
+ mod.hidden_size,
232
+ mod.bias,
233
+ mod.nonlinearity,
234
+ mod.weight_ih.device,
235
+ mod.weight_ih.dtype,
236
+ weight_qparams_dict,
237
+ )
238
+ ref_mod.weight_ih = mod.weight_ih
239
+ ref_mod.weight_hh = mod.weight_hh
240
+ ref_mod.bias_ih = mod.bias_ih
241
+ ref_mod.bias_hh = mod.bias_hh
242
+ return ref_mod
243
+
244
+
245
+ class LSTMCell(RNNCellBase):
246
+ """
247
+ We'll store weight_qparams for all the weights (weight_ih and weight_hh),
248
+ we need to pass in a `weight_qparams_dict` that maps from weight name,
249
+ e.g. weight_ih, to the weight_qparams for that weight
250
+ """
251
+
252
+ def __init__(
253
+ self,
254
+ input_size: int,
255
+ hidden_size: int,
256
+ bias: bool = True,
257
+ device=None,
258
+ dtype=None,
259
+ weight_qparams_dict: Optional[dict[str, Any]] = None,
260
+ ) -> None:
261
+ factory_kwargs = {
262
+ "device": device,
263
+ "dtype": dtype,
264
+ "weight_qparams_dict": weight_qparams_dict,
265
+ }
266
+ super().__init__(input_size, hidden_size, bias, num_chunks=4, **factory_kwargs)
267
+
268
+ def _get_name(self):
269
+ return "QuantizedLSTMCell(Reference)"
270
+
271
+ def forward(
272
+ self, input: Tensor, hx: Optional[tuple[Tensor, Tensor]] = None
273
+ ) -> tuple[Tensor, Tensor]:
274
+ assert input.dim() in (
275
+ 1,
276
+ 2,
277
+ ), f"LSTMCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
278
+ is_batched = input.dim() == 2
279
+ if not is_batched:
280
+ input = input.unsqueeze(0)
281
+
282
+ if hx is None:
283
+ zeros = torch.zeros(
284
+ input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
285
+ )
286
+ hx = (zeros, zeros)
287
+ else:
288
+ hx = (hx[0].unsqueeze(0), hx[1].unsqueeze(0)) if not is_batched else hx
289
+
290
+ ret = _VF.lstm_cell(
291
+ input,
292
+ hx,
293
+ self.get_weight_ih(),
294
+ self.get_weight_hh(),
295
+ self.bias_ih,
296
+ self.bias_hh,
297
+ )
298
+
299
+ if not is_batched:
300
+ ret = (ret[0].squeeze(0), ret[1].squeeze(0))
301
+ return ret
302
+
303
+ @classmethod
304
+ def from_float(cls, mod, weight_qparams_dict, use_precomputed_fake_quant=False):
305
+ ref_mod = cls(
306
+ mod.input_size,
307
+ mod.hidden_size,
308
+ mod.bias,
309
+ mod.weight_ih.device,
310
+ mod.weight_ih.dtype,
311
+ weight_qparams_dict,
312
+ )
313
+ ref_mod.weight_ih = mod.weight_ih
314
+ ref_mod.weight_hh = mod.weight_hh
315
+ ref_mod.bias_ih = mod.bias_ih
316
+ ref_mod.bias_hh = mod.bias_hh
317
+ return ref_mod
318
+
319
+
320
+ class GRUCell(RNNCellBase):
321
+ """
322
+ We'll store weight_qparams for all the weights (weight_ih and weight_hh),
323
+ we need to pass in a `weight_qparams_dict` that maps from weight name,
324
+ e.g. weight_ih, to the weight_qparams for that weight
325
+ """
326
+
327
+ def __init__(
328
+ self,
329
+ input_size: int,
330
+ hidden_size: int,
331
+ bias: bool = True,
332
+ device=None,
333
+ dtype=None,
334
+ weight_qparams_dict: Optional[dict[str, Any]] = None,
335
+ ) -> None:
336
+ factory_kwargs = {
337
+ "device": device,
338
+ "dtype": dtype,
339
+ "weight_qparams_dict": weight_qparams_dict,
340
+ }
341
+ super().__init__(input_size, hidden_size, bias, num_chunks=3, **factory_kwargs)
342
+
343
+ def _get_name(self):
344
+ return "QuantizedGRUCell(Reference)"
345
+
346
+ def forward(self, input: Tensor, hx: Optional[Tensor] = None) -> Tensor:
347
+ assert input.dim() in (
348
+ 1,
349
+ 2,
350
+ ), f"GRUCell: Expected input to be 1-D or 2-D but received {input.dim()}-D tensor"
351
+ is_batched = input.dim() == 2
352
+ if not is_batched:
353
+ input = input.unsqueeze(0)
354
+
355
+ if hx is None:
356
+ hx = torch.zeros(
357
+ input.size(0), self.hidden_size, dtype=input.dtype, device=input.device
358
+ )
359
+ else:
360
+ hx = hx.unsqueeze(0) if not is_batched else hx
361
+
362
+ ret = _VF.gru_cell(
363
+ input,
364
+ hx,
365
+ self.get_weight_ih(),
366
+ self.get_weight_hh(),
367
+ self.bias_ih,
368
+ self.bias_hh,
369
+ )
370
+
371
+ if not is_batched:
372
+ ret = ret.squeeze(0)
373
+
374
+ return ret
375
+
376
+ @classmethod
377
+ def from_float(cls, mod, weight_qparams_dict):
378
+ ref_mod = cls(
379
+ mod.input_size,
380
+ mod.hidden_size,
381
+ mod.bias,
382
+ mod.weight_ih.device,
383
+ mod.weight_ih.dtype,
384
+ weight_qparams_dict,
385
+ )
386
+ ref_mod.weight_ih = mod.weight_ih
387
+ ref_mod.weight_hh = mod.weight_hh
388
+ ref_mod.bias_ih = mod.bias_ih
389
+ ref_mod.bias_hh = mod.bias_hh
390
+ return ref_mod
391
+
392
+
393
+ class RNNBase(nn.RNNBase):
394
+ def __init__(
395
+ self,
396
+ mode: str,
397
+ input_size: int,
398
+ hidden_size: int,
399
+ num_layers: int = 1,
400
+ bias: bool = True,
401
+ batch_first: bool = False,
402
+ dropout: float = 0.0,
403
+ bidirectional: bool = False,
404
+ proj_size: int = 0,
405
+ device=None,
406
+ dtype=None,
407
+ weight_qparams_dict: Optional[dict[str, Any]] = None,
408
+ ) -> None:
409
+ super().__init__(
410
+ mode,
411
+ input_size,
412
+ hidden_size,
413
+ num_layers,
414
+ bias,
415
+ batch_first,
416
+ dropout,
417
+ bidirectional,
418
+ proj_size,
419
+ device,
420
+ dtype,
421
+ )
422
+ # TODO(jerryzh168): maybe make this arg a required arg
423
+ if weight_qparams_dict is None:
424
+ weight_qparams = {
425
+ "qscheme": torch.per_tensor_affine,
426
+ "dtype": torch.quint8,
427
+ "scale": 1.0,
428
+ "zero_point": 0,
429
+ }
430
+ weight_qparams_dict = {"is_decomposed": False} # type: ignore[dict-item]
431
+ for wn in self._flat_weights_names:
432
+ if wn.startswith("weight"):
433
+ weight_qparams_dict[wn] = weight_qparams
434
+ self._init_weight_qparams_dict(weight_qparams_dict, device)
435
+
436
+ def _init_weight_qparams_dict(self, weight_qparams_dict, device):
437
+ self.is_decomposed = weight_qparams_dict["is_decomposed"]
438
+ for key, weight_qparams in weight_qparams_dict.items():
439
+ if key == "is_decomposed":
440
+ continue
441
+ weight_qscheme = weight_qparams["qscheme"]
442
+ weight_dtype = weight_qparams["dtype"]
443
+ setattr(self, key + "_qscheme", weight_qscheme)
444
+ setattr(self, key + "_dtype", weight_dtype)
445
+ assert weight_qscheme in [
446
+ None,
447
+ torch.per_tensor_affine,
448
+ torch.per_channel_affine,
449
+ ], Exception(
450
+ f"qscheme: {weight_qscheme} is not support in {self._get_name()}"
451
+ )
452
+ if weight_qscheme is not None:
453
+ self.register_buffer(
454
+ key + "_scale",
455
+ torch.tensor(
456
+ weight_qparams["scale"], dtype=torch.float, device=device
457
+ ),
458
+ )
459
+ self.register_buffer(
460
+ key + "_zero_point",
461
+ torch.tensor(
462
+ weight_qparams["zero_point"], dtype=torch.int, device=device
463
+ ),
464
+ )
465
+ if weight_qscheme == torch.per_channel_affine:
466
+ self.register_buffer(
467
+ key + "_axis",
468
+ torch.tensor(
469
+ weight_qparams["axis"], dtype=torch.int, device=device
470
+ ),
471
+ )
472
+ else:
473
+ # added for TorchScriptability, not used
474
+ self.register_buffer(
475
+ key + "_axis", torch.tensor(0, dtype=torch.int, device=device)
476
+ )
477
+ setattr(self, key + "_axis_int", getattr(self, key + "_axis").item())
478
+
479
+
480
+ class LSTM(RNNBase):
481
+ """Reference Quantized LSTM Module
482
+ We'll store weight_qparams for all the weights in _flat_weights, we need to pass in
483
+ a `weight_qparams_dict` that maps from weight name, e.g. weight_ih_l0,
484
+ to the weight_qparams for that weight
485
+ """
486
+
487
+ def __init__(self, *args, **kwargs):
488
+ super().__init__("LSTM", *args, **kwargs)
489
+
490
+ # Same as above, see torch/nn/modules/module.py::_forward_unimplemented
491
+ def permute_hidden( # type: ignore[override]
492
+ self,
493
+ hx: tuple[Tensor, Tensor],
494
+ permutation: Optional[Tensor],
495
+ ) -> tuple[Tensor, Tensor]:
496
+ if permutation is None:
497
+ return hx
498
+ return _apply_permutation(hx[0], permutation), _apply_permutation(
499
+ hx[1], permutation
500
+ )
501
+
502
+ def get_expected_cell_size(
503
+ self, input: Tensor, batch_sizes: Optional[Tensor]
504
+ ) -> tuple[int, int, int]:
505
+ if batch_sizes is not None:
506
+ mini_batch = int(batch_sizes[0])
507
+ else:
508
+ mini_batch = input.size(0) if self.batch_first else input.size(1)
509
+ num_directions = 2 if self.bidirectional else 1
510
+ expected_hidden_size = (
511
+ self.num_layers * num_directions,
512
+ mini_batch,
513
+ self.hidden_size,
514
+ )
515
+ return expected_hidden_size
516
+
517
+ # In the future, we should prevent mypy from applying contravariance rules here.
518
+ # See torch/nn/modules/module.py::_forward_unimplemented
519
+ def check_forward_args( # type: ignore[override]
520
+ self,
521
+ input: Tensor,
522
+ hidden: tuple[Tensor, Tensor],
523
+ batch_sizes: Optional[Tensor],
524
+ ):
525
+ self.check_input(input, batch_sizes)
526
+ self.check_hidden_size(
527
+ hidden[0],
528
+ self.get_expected_hidden_size(input, batch_sizes),
529
+ "Expected hidden[0] size {}, got {}",
530
+ )
531
+ self.check_hidden_size(
532
+ hidden[1],
533
+ self.get_expected_cell_size(input, batch_sizes),
534
+ "Expected hidden[1] size {}, got {}",
535
+ )
536
+
537
+ def get_quantized_weight_bias_dict(self):
538
+ """dictionary from flat_weight_name to quantized weight or (unquantized) bias
539
+ e.g.
540
+ {
541
+ "weight_ih_l0": quantized_weight,
542
+ "bias_ih_l0": unquantized_bias,
543
+ ...
544
+ }
545
+ """
546
+ quantized_weight_bias_dict = {}
547
+ for wn in self._flat_weights_names:
548
+ if hasattr(self, wn):
549
+ if wn.startswith("weight"):
550
+ weight_or_bias = get_quantized_weight(self, wn)
551
+ else:
552
+ weight_or_bias = getattr(self, wn)
553
+ else:
554
+ weight_or_bias = None
555
+ quantized_weight_bias_dict[wn] = weight_or_bias
556
+ return quantized_weight_bias_dict
557
+
558
+ def get_flat_weights(self):
559
+ flat_weights = []
560
+ for wn in self._flat_weights_names:
561
+ if hasattr(self, wn):
562
+ weight = getattr(self, wn)
563
+ if wn.startswith("weight"):
564
+ params = _get_weight_and_quantization_params(self, wn)
565
+ weight = _quantize_and_dequantize_weight(*params)
566
+ else:
567
+ weight = None
568
+ flat_weights.append(weight)
569
+ return flat_weights
570
+
571
+ def forward(self, input, hx=None): # noqa: F811
572
+ orig_input = input
573
+ # xxx: isinstance check needs to be in conditional for TorchScript to compile
574
+ batch_sizes = None
575
+ if isinstance(orig_input, PackedSequence):
576
+ input, batch_sizes, sorted_indices, unsorted_indices = input
577
+ max_batch_size = int(batch_sizes[0])
578
+ else:
579
+ batch_sizes = None
580
+ is_batched = input.dim() == 3
581
+ batch_dim = 0 if self.batch_first else 1
582
+ if not is_batched:
583
+ input = input.unsqueeze(batch_dim)
584
+ max_batch_size = input.size(0) if self.batch_first else input.size(1)
585
+ sorted_indices = None
586
+ unsorted_indices = None
587
+
588
+ if hx is None:
589
+ num_directions = 2 if self.bidirectional else 1
590
+ real_hidden_size = (
591
+ self.proj_size if self.proj_size > 0 else self.hidden_size
592
+ )
593
+ h_zeros = torch.zeros(
594
+ self.num_layers * num_directions,
595
+ max_batch_size,
596
+ real_hidden_size,
597
+ dtype=input.dtype,
598
+ device=input.device,
599
+ )
600
+ c_zeros = torch.zeros(
601
+ self.num_layers * num_directions,
602
+ max_batch_size,
603
+ self.hidden_size,
604
+ dtype=input.dtype,
605
+ device=input.device,
606
+ )
607
+ hx = (h_zeros, c_zeros)
608
+ else:
609
+ if batch_sizes is None: # If not PackedSequence input.
610
+ if is_batched: # type: ignore[possibly-undefined]
611
+ if hx[0].dim() != 3 or hx[1].dim() != 3:
612
+ msg = (
613
+ "For batched 3-D input, hx and cx should "
614
+ f"also be 3-D but got ({hx[0].dim()}-D, {hx[1].dim()}-D) tensors"
615
+ )
616
+ raise RuntimeError(msg)
617
+ else:
618
+ if hx[0].dim() != 2 or hx[1].dim() != 2:
619
+ msg = (
620
+ "For unbatched 2-D input, hx and cx should "
621
+ f"also be 2-D but got ({hx[0].dim()}-D, {hx[1].dim()}-D) tensors"
622
+ )
623
+ raise RuntimeError(msg)
624
+ hx = (hx[0].unsqueeze(1), hx[1].unsqueeze(1))
625
+
626
+ # Each batch of the hidden state should match the input sequence that
627
+ # the user believes he/she is passing in.
628
+ hx = self.permute_hidden(hx, sorted_indices)
629
+
630
+ self.check_forward_args(input, hx, batch_sizes)
631
+ if batch_sizes is None:
632
+ result = _VF.lstm(
633
+ input,
634
+ hx,
635
+ self.get_flat_weights(),
636
+ self.bias,
637
+ self.num_layers,
638
+ self.dropout,
639
+ self.training,
640
+ self.bidirectional,
641
+ self.batch_first,
642
+ )
643
+ else:
644
+ result = _VF.lstm(
645
+ input,
646
+ batch_sizes,
647
+ hx,
648
+ self.get_flat_weights(),
649
+ self.bias,
650
+ self.num_layers,
651
+ self.dropout,
652
+ self.training,
653
+ self.bidirectional,
654
+ )
655
+ output = result[0]
656
+ hidden = result[1:]
657
+ # xxx: isinstance check needs to be in conditional for TorchScript to compile
658
+ if isinstance(orig_input, PackedSequence):
659
+ output_packed = PackedSequence(
660
+ output, batch_sizes, sorted_indices, unsorted_indices
661
+ )
662
+ return output_packed, self.permute_hidden(hidden, unsorted_indices)
663
+ else:
664
+ if not is_batched: # type: ignore[possibly-undefined]
665
+ output = output.squeeze(batch_dim) # type: ignore[possibly-undefined]
666
+ hidden = (hidden[0].squeeze(1), hidden[1].squeeze(1))
667
+ return output, self.permute_hidden(hidden, unsorted_indices)
668
+
669
+ def _get_name(self):
670
+ return "QuantizedLSTM(Reference)"
671
+
672
+ @classmethod
673
+ def from_float(cls, mod, weight_qparams_dict):
674
+ ref_mod = cls(
675
+ mod.input_size,
676
+ mod.hidden_size,
677
+ mod.num_layers,
678
+ mod.bias,
679
+ mod.batch_first,
680
+ mod.dropout,
681
+ mod.bidirectional,
682
+ weight_qparams_dict=weight_qparams_dict,
683
+ )
684
+ for wn in mod._flat_weights_names:
685
+ setattr(ref_mod, wn, getattr(mod, wn))
686
+ return ref_mod
687
+
688
+
689
+ class GRU(RNNBase):
690
+ """Reference Quantized GRU Module
691
+ We'll store weight_qparams for all the weights in _flat_weights, we need to pass in
692
+ a `weight_qparams_dict` that maps from weight name, e.g. weight_ih_l0,
693
+ to the weight_qparams for that weight
694
+ """
695
+
696
+ def __init__(self, *args, **kwargs):
697
+ if "proj_size" in kwargs:
698
+ raise ValueError(
699
+ "proj_size argument is only supported for LSTM, not RNN or GRU"
700
+ )
701
+ super().__init__("GRU", *args, **kwargs)
702
+
703
+ def get_quantized_weight_bias_dict(self):
704
+ """dictionary from flat_weight_name to quantized weight or (unquantized) bias
705
+ e.g.
706
+ {
707
+ "weight_ih_l0": quantized_weight,
708
+ "bias_ih_l0": unquantized_bias,
709
+ ...
710
+ }
711
+ """
712
+ quantized_weight_bias_dict = {}
713
+ for wn in self._flat_weights_names:
714
+ if hasattr(self, wn):
715
+ if wn.startswith("weight"):
716
+ weight_or_bias = get_quantized_weight(self, wn)
717
+ else:
718
+ weight_or_bias = getattr(self, wn)
719
+ else:
720
+ weight_or_bias = None
721
+ quantized_weight_bias_dict[wn] = weight_or_bias
722
+ return quantized_weight_bias_dict
723
+
724
+ def get_flat_weights(self):
725
+ flat_weights = []
726
+ for wn in self._flat_weights_names:
727
+ if hasattr(self, wn):
728
+ weight = getattr(self, wn)
729
+ if wn.startswith("weight"):
730
+ params = _get_weight_and_quantization_params(self, wn)
731
+ weight = _quantize_and_dequantize_weight(*params)
732
+ else:
733
+ weight = None
734
+ flat_weights.append(weight)
735
+ return flat_weights
736
+
737
+ def forward(self, input, hx=None): # noqa: F811
738
+ # Note: this is copied from the forward of GRU in https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/rnn.py
739
+ # only changed self._flat_weights to self.get_flat_weights()
740
+ # TODO: maybe we can try inheriting from that class and define get_flat_weights
741
+ # as a @property? this might interfere with TorchScript, if we remove that
742
+ # requirement in the future we should be able to do this
743
+ orig_input = input
744
+ # xxx: isinstance check needs to be in conditional for TorchScript to compile
745
+ if isinstance(orig_input, PackedSequence):
746
+ input, batch_sizes, sorted_indices, unsorted_indices = input
747
+ max_batch_size = int(batch_sizes[0])
748
+ else:
749
+ batch_sizes = None
750
+ assert input.dim() in (
751
+ 2,
752
+ 3,
753
+ ), f"GRU: Expected input to be 2-D or 3-D but received {input.dim()}-D tensor"
754
+ is_batched = input.dim() == 3
755
+ batch_dim = 0 if self.batch_first else 1
756
+ if not is_batched:
757
+ input = input.unsqueeze(batch_dim)
758
+ if hx is not None:
759
+ if hx.dim() != 2:
760
+ raise RuntimeError(
761
+ f"For unbatched 2-D input, hx should also be 2-D but got {hx.dim()}-D tensor"
762
+ )
763
+ hx = hx.unsqueeze(1)
764
+ else:
765
+ if hx is not None and hx.dim() != 3:
766
+ raise RuntimeError(
767
+ f"For batched 3-D input, hx should also be 3-D but got {hx.dim()}-D tensor"
768
+ )
769
+ max_batch_size = input.size(0) if self.batch_first else input.size(1)
770
+ sorted_indices = None
771
+ unsorted_indices = None
772
+
773
+ if hx is None:
774
+ num_directions = 2 if self.bidirectional else 1
775
+ hx = torch.zeros(
776
+ self.num_layers * num_directions,
777
+ max_batch_size,
778
+ self.hidden_size,
779
+ dtype=input.dtype,
780
+ device=input.device,
781
+ )
782
+ else:
783
+ # Each batch of the hidden state should match the input sequence that
784
+ # the user believes he/she is passing in.
785
+ hx = self.permute_hidden(hx, sorted_indices)
786
+
787
+ self.check_forward_args(input, hx, batch_sizes)
788
+ if batch_sizes is None:
789
+ result = _VF.gru(
790
+ input,
791
+ hx,
792
+ self.get_flat_weights(),
793
+ self.bias,
794
+ self.num_layers,
795
+ self.dropout,
796
+ self.training,
797
+ self.bidirectional,
798
+ self.batch_first,
799
+ )
800
+ else:
801
+ result = _VF.gru(
802
+ input,
803
+ batch_sizes,
804
+ hx,
805
+ self.get_flat_weights(),
806
+ self.bias,
807
+ self.num_layers,
808
+ self.dropout,
809
+ self.training,
810
+ self.bidirectional,
811
+ )
812
+ output = result[0]
813
+ hidden = result[1]
814
+
815
+ # xxx: isinstance check needs to be in conditional for TorchScript to compile
816
+ if isinstance(orig_input, PackedSequence):
817
+ output_packed = PackedSequence(
818
+ output, batch_sizes, sorted_indices, unsorted_indices
819
+ )
820
+ return output_packed, self.permute_hidden(hidden, unsorted_indices)
821
+ else:
822
+ if not is_batched: # type: ignore[possibly-undefined]
823
+ output = output.squeeze(batch_dim) # type: ignore[possibly-undefined]
824
+ hidden = hidden.squeeze(1)
825
+
826
+ return output, self.permute_hidden(hidden, unsorted_indices)
827
+
828
+ def _get_name(self):
829
+ return "QuantizedGRU(Reference)"
830
+
831
+ @classmethod
832
+ def from_float(cls, mod, weight_qparams_dict):
833
+ ref_mod = cls(
834
+ mod.input_size,
835
+ mod.hidden_size,
836
+ mod.num_layers,
837
+ mod.bias,
838
+ mod.batch_first,
839
+ mod.dropout,
840
+ mod.bidirectional,
841
+ weight_qparams_dict=weight_qparams_dict,
842
+ )
843
+ for wn in mod._flat_weights_names:
844
+ setattr(ref_mod, wn, getattr(mod, wn))
845
+ return ref_mod
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/sparse.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Any, Optional
3
+
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from torch import Tensor
7
+
8
+ from .utils import ReferenceQuantizedModule
9
+
10
+
11
+ __all__ = ["Embedding", "EmbeddingBag"]
12
+
13
+
14
+ class Embedding(nn.Embedding, ReferenceQuantizedModule):
15
+ """A reference quantized Embedding module that fits into the
16
+ FX Graph Mode Quantization workflow, activation will be floating point Tensor,
17
+ we will store floating point weight as well in the module, but in forward we'll
18
+ quantize and dequantize the weight before running the floating point functional
19
+ embedding operator.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ num_embeddings: int,
25
+ embedding_dim: int,
26
+ padding_idx: Optional[int] = None,
27
+ max_norm: Optional[float] = None,
28
+ norm_type: float = 2.0,
29
+ scale_grad_by_freq: bool = False,
30
+ sparse: bool = False,
31
+ _weight: Optional[Tensor] = None,
32
+ device=None,
33
+ dtype=None,
34
+ weight_qparams: Optional[dict[str, Any]] = None,
35
+ ) -> None:
36
+ super().__init__(
37
+ num_embeddings,
38
+ embedding_dim,
39
+ padding_idx,
40
+ max_norm,
41
+ norm_type,
42
+ scale_grad_by_freq,
43
+ sparse,
44
+ _weight,
45
+ device,
46
+ dtype,
47
+ )
48
+ self._init_weight_qparams(weight_qparams, device)
49
+
50
+ def _get_name(self):
51
+ return "QuantizedEmbedding(Reference)"
52
+
53
+ def forward(self, input: Tensor) -> Tensor:
54
+ weight_quant_dequant = self.get_weight()
55
+ return F.embedding(
56
+ input,
57
+ weight_quant_dequant,
58
+ self.padding_idx,
59
+ self.max_norm,
60
+ self.norm_type,
61
+ self.scale_grad_by_freq,
62
+ self.sparse,
63
+ )
64
+
65
+ @classmethod
66
+ def from_float(cls, mod, weight_qparams):
67
+ return cls(
68
+ mod.num_embeddings,
69
+ mod.embedding_dim,
70
+ mod.padding_idx,
71
+ mod.max_norm,
72
+ mod.norm_type,
73
+ mod.scale_grad_by_freq,
74
+ mod.sparse,
75
+ mod.weight,
76
+ mod.weight.device,
77
+ mod.weight.dtype,
78
+ weight_qparams,
79
+ )
80
+
81
+
82
+ class EmbeddingBag(nn.EmbeddingBag, ReferenceQuantizedModule):
83
+ """A reference quantized EmbeddingBag module that fits into the
84
+ FX Graph Mode Quantization workflow, activation will be floating point Tensor,
85
+ we will store floating point weight as well in the module, but in forward we'll
86
+ quantize and dequantize the weight before running the floating point functional
87
+ embedding operator.
88
+ """
89
+
90
+ def __init__(
91
+ self,
92
+ num_embeddings: int,
93
+ embedding_dim: int,
94
+ max_norm: Optional[float] = None,
95
+ norm_type: float = 2.0,
96
+ scale_grad_by_freq: bool = False,
97
+ mode: str = "mean",
98
+ sparse: bool = False,
99
+ _weight: Optional[Tensor] = None,
100
+ include_last_offset: bool = False,
101
+ padding_idx: Optional[int] = None,
102
+ device=None,
103
+ dtype=None,
104
+ weight_qparams: Optional[dict[str, Any]] = None,
105
+ ) -> None:
106
+ super().__init__(
107
+ num_embeddings,
108
+ embedding_dim,
109
+ max_norm,
110
+ norm_type,
111
+ scale_grad_by_freq,
112
+ mode,
113
+ sparse,
114
+ _weight,
115
+ include_last_offset,
116
+ padding_idx,
117
+ device,
118
+ dtype,
119
+ )
120
+ self._init_weight_qparams(weight_qparams, device)
121
+
122
+ def _get_name(self):
123
+ return "QuantizedEmbedding(Reference)"
124
+
125
+ def forward(
126
+ self,
127
+ input: Tensor,
128
+ offsets: Optional[Tensor] = None,
129
+ per_sample_weights: Optional[Tensor] = None,
130
+ ) -> Tensor:
131
+ weight_quant_dequant = self.get_weight()
132
+ return F.embedding_bag(
133
+ input,
134
+ weight_quant_dequant,
135
+ offsets,
136
+ self.max_norm,
137
+ self.norm_type,
138
+ self.scale_grad_by_freq,
139
+ self.mode,
140
+ self.sparse,
141
+ per_sample_weights,
142
+ self.include_last_offset,
143
+ self.padding_idx,
144
+ )
145
+
146
+ @classmethod
147
+ def from_float(cls, mod, weight_qparams, use_precomputed_fake_quant=False):
148
+ return cls(
149
+ mod.num_embeddings,
150
+ mod.embedding_dim,
151
+ mod.max_norm,
152
+ mod.norm_type,
153
+ mod.scale_grad_by_freq,
154
+ mod.mode,
155
+ mod.sparse,
156
+ mod.weight,
157
+ mod.include_last_offset,
158
+ mod.padding_idx,
159
+ mod.weight.device,
160
+ mod.weight.dtype,
161
+ weight_qparams,
162
+ )
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/quantized/reference/modules/utils.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import typing
3
+
4
+ import torch
5
+
6
+
7
+ __all__ = [
8
+ "ReferenceQuantizedModule",
9
+ ]
10
+
11
+
12
+ class ReferenceQuantizedModule(torch.nn.Module):
13
+ def _init_weight_qparams(self, weight_qparams, device):
14
+ if weight_qparams is None:
15
+ weight_qparams = {
16
+ "qscheme": torch.per_tensor_affine,
17
+ "dtype": torch.quint8,
18
+ "scale": 1.0,
19
+ "zero_point": 0,
20
+ }
21
+ self.weight_qscheme: torch.qscheme = weight_qparams["qscheme"]
22
+ self.weight_dtype = weight_qparams["dtype"]
23
+ assert self.weight_qscheme in [
24
+ None,
25
+ torch.per_tensor_affine,
26
+ torch.per_channel_affine,
27
+ torch.per_channel_affine_float_qparams,
28
+ ], f"qscheme: {self.weight_qscheme} is not support in reference quantized {self._get_name()}"
29
+ if self.weight_dtype in [
30
+ torch.quint8,
31
+ torch.qint8,
32
+ torch.quint4x2,
33
+ torch.qint32,
34
+ ]:
35
+ zero_point_dtype = (
36
+ weight_qparams["zero_point"].dtype
37
+ if isinstance(weight_qparams["zero_point"], torch.Tensor)
38
+ else torch.int
39
+ )
40
+ w_scale = weight_qparams["scale"]
41
+ w_scale_tensor = (
42
+ w_scale.detach().clone()
43
+ if isinstance(w_scale, torch.Tensor)
44
+ else torch.tensor(w_scale, dtype=torch.float, device=device)
45
+ )
46
+ self.register_buffer("weight_scale", w_scale_tensor)
47
+ w_zp = weight_qparams["zero_point"]
48
+ w_zp_tensor = (
49
+ w_zp.detach().clone()
50
+ if isinstance(w_zp, torch.Tensor)
51
+ else torch.tensor(w_zp, dtype=zero_point_dtype, device=device)
52
+ )
53
+ self.register_buffer("weight_zero_point", w_zp_tensor)
54
+ if self.weight_qscheme in [
55
+ torch.per_channel_affine,
56
+ torch.per_channel_affine_float_qparams,
57
+ ]:
58
+ w_axis = weight_qparams["axis"]
59
+ w_axis_tensor = (
60
+ w_axis.detach().clone()
61
+ if isinstance(w_axis, torch.Tensor)
62
+ else torch.tensor(w_axis, dtype=torch.int, device=device)
63
+ )
64
+ self.register_buffer("weight_axis", w_axis_tensor)
65
+ else:
66
+ # added for TorchScriptability, not used
67
+ self.register_buffer(
68
+ "weight_axis", torch.tensor(0, dtype=torch.int, device=device)
69
+ )
70
+ else:
71
+ # added for TorchScriptability, and for torch.float
72
+ self.register_buffer(
73
+ "weight_scale", torch.tensor(1.0, dtype=torch.float, device=device)
74
+ )
75
+ self.register_buffer(
76
+ "weight_zero_point", torch.tensor(0, dtype=torch.int, device=device)
77
+ )
78
+ self.register_buffer(
79
+ "weight_axis", torch.tensor(0, dtype=torch.int, device=device)
80
+ )
81
+ self.is_decomposed: bool = weight_qparams.get("is_decomposed", False)
82
+ # store weight_axis as weight_axis_int due to some constraints of torchdynamo.export
83
+ # for capturing `.item` operations
84
+ self.weight_axis_int: int = self.weight_axis.item() # type: ignore[operator, assignment]
85
+ self.weight_quant_min: typing.Optional[int] = weight_qparams.get(
86
+ "quant_min", None
87
+ )
88
+ self.weight_quant_max: typing.Optional[int] = weight_qparams.get(
89
+ "quant_max", None
90
+ )
91
+
92
+ def get_weight(self):
93
+ """
94
+ Fake quantize (quantize and dequantize) the weight with
95
+ the quantization parameters for weight, this is used to
96
+ simulate the numerics for the quantized weight in a quantized
97
+ model
98
+ """
99
+ # suppress mypy warning
100
+ assert isinstance(self.weight_scale, torch.Tensor)
101
+ assert isinstance(self.weight_zero_point, torch.Tensor)
102
+ if self.is_decomposed:
103
+ return _quantize_and_dequantize_weight_decomposed(
104
+ self.weight, # type: ignore[arg-type]
105
+ self.weight_qscheme,
106
+ self.weight_dtype,
107
+ self.weight_scale,
108
+ self.weight_zero_point,
109
+ self.weight_axis_int,
110
+ self.weight_quant_min,
111
+ self.weight_quant_max,
112
+ )
113
+ else:
114
+ return _quantize_and_dequantize_weight(
115
+ self.weight, # type: ignore[arg-type]
116
+ self.weight_qscheme,
117
+ self.weight_dtype,
118
+ self.weight_scale,
119
+ self.weight_zero_point,
120
+ self.weight_axis_int,
121
+ )
122
+
123
+ def get_quantized_weight(self):
124
+ # suppress mypy warning
125
+ assert isinstance(self.weight_scale, torch.Tensor)
126
+ assert isinstance(self.weight_zero_point, torch.Tensor)
127
+ # assert isinstance(self.weight_axis, torch.Tensor)
128
+ if self.is_decomposed:
129
+ return _quantize_weight_decomposed(
130
+ self.weight, # type: ignore[arg-type]
131
+ self.weight_qscheme,
132
+ self.weight_dtype,
133
+ self.weight_scale,
134
+ self.weight_zero_point,
135
+ self.weight_axis_int,
136
+ self.weight_quant_min,
137
+ self.weight_quant_max,
138
+ )
139
+ else:
140
+ return _quantize_weight(
141
+ self.weight, # type: ignore[arg-type]
142
+ self.weight_qscheme,
143
+ self.weight_dtype,
144
+ self.weight_scale,
145
+ self.weight_zero_point,
146
+ self.weight_axis_int,
147
+ )
148
+
149
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
150
+ super()._save_to_state_dict(destination, prefix, keep_vars)
151
+ _save_weight_qparams(
152
+ destination,
153
+ prefix,
154
+ self.weight_qscheme,
155
+ self.weight_dtype,
156
+ self.weight_scale,
157
+ self.weight_zero_point,
158
+ self.weight_axis,
159
+ )
160
+
161
+ def _load_from_state_dict(
162
+ self,
163
+ state_dict,
164
+ prefix,
165
+ local_metadata,
166
+ strict,
167
+ missing_keys,
168
+ unexpected_keys,
169
+ error_msgs,
170
+ ):
171
+ for key in _get_weight_qparam_keys(state_dict, prefix):
172
+ setattr(self, key, state_dict[prefix + key])
173
+ state_dict.pop(prefix + key)
174
+
175
+ super()._load_from_state_dict(
176
+ state_dict,
177
+ prefix,
178
+ local_metadata,
179
+ False,
180
+ missing_keys,
181
+ unexpected_keys,
182
+ error_msgs,
183
+ )
184
+
185
+
186
+ def _quantize_weight_decomposed(
187
+ weight: torch.Tensor,
188
+ weight_qscheme: torch.qscheme,
189
+ weight_dtype: torch.dtype,
190
+ weight_scale: torch.Tensor,
191
+ weight_zero_point: torch.Tensor,
192
+ weight_axis: int,
193
+ weight_quant_min: typing.Optional[int],
194
+ weight_quant_max: typing.Optional[int],
195
+ ) -> torch.Tensor:
196
+ _DTYPE_TO_QVALUE_BOUNDS = {
197
+ torch.uint8: (0, 255),
198
+ torch.int8: (-128, 127),
199
+ torch.int32: (-(2**31), 2**31 - 1),
200
+ }
201
+ # TODO: add an util function for converting qdtype to dtype
202
+ _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE = {
203
+ torch.quint8: torch.uint8,
204
+ torch.qint8: torch.int8,
205
+ torch.qint32: torch.int32,
206
+ }
207
+ if weight_qscheme == torch.per_tensor_affine:
208
+ if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
209
+ weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
210
+ if weight_quant_min is None or weight_quant_max is None:
211
+ weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[
212
+ weight_dtype_
213
+ ]
214
+ weight = torch.ops.quantized_decomposed.quantize_per_tensor(
215
+ weight,
216
+ weight_scale,
217
+ weight_zero_point,
218
+ weight_quant_min,
219
+ weight_quant_max,
220
+ weight_dtype_,
221
+ )
222
+ return weight
223
+ elif weight_qscheme in [
224
+ torch.per_channel_affine,
225
+ torch.per_channel_affine_float_qparams,
226
+ ]:
227
+ # TODO: torch.quint4x2 is not supported
228
+ if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
229
+ weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
230
+ if weight_quant_min is None or weight_quant_max is None:
231
+ weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[
232
+ weight_dtype_
233
+ ]
234
+ weight = torch.ops.quantized_decomposed.quantize_per_channel(
235
+ weight,
236
+ weight_scale,
237
+ weight_zero_point,
238
+ weight_axis,
239
+ weight_quant_min,
240
+ weight_quant_max,
241
+ weight_dtype_,
242
+ ) # type: ignore[arg-type]
243
+ return weight
244
+ raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
245
+
246
+
247
+ def _dequantize_weight_decomposed(
248
+ weight: torch.Tensor,
249
+ weight_qscheme: torch.qscheme,
250
+ weight_dtype: torch.dtype,
251
+ weight_scale: torch.Tensor,
252
+ weight_zero_point: torch.Tensor,
253
+ weight_axis: int,
254
+ weight_quant_min: typing.Optional[int],
255
+ weight_quant_max: typing.Optional[int],
256
+ ) -> torch.Tensor:
257
+ # TODO: get the quant_min and quant_max from activation_post_process
258
+ _DTYPE_TO_QVALUE_BOUNDS = {
259
+ torch.uint8: (0, 255),
260
+ torch.int8: (-128, 127),
261
+ torch.int32: (-(2**31), 2**31 - 1),
262
+ }
263
+ # TODO: add an util function for converting qdtype to dtype
264
+ _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE = {
265
+ torch.quint8: torch.uint8,
266
+ torch.qint8: torch.int8,
267
+ torch.qint32: torch.int32,
268
+ }
269
+ weight_dtype_ = _QDTYPE_TO_UNDERLYING_INT_REPR_DTYPE[weight_dtype]
270
+ if weight_quant_min is None or weight_quant_max is None:
271
+ weight_quant_min, weight_quant_max = _DTYPE_TO_QVALUE_BOUNDS[weight_dtype_]
272
+ if weight_qscheme == torch.per_tensor_affine:
273
+ if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
274
+ weight = torch.ops.quantized_decomposed.dequantize_per_tensor(
275
+ weight,
276
+ weight_scale,
277
+ weight_zero_point,
278
+ weight_quant_min,
279
+ weight_quant_max,
280
+ weight_dtype_,
281
+ )
282
+ return weight
283
+ elif weight_qscheme in [
284
+ torch.per_channel_affine,
285
+ torch.per_channel_affine_float_qparams,
286
+ ]:
287
+ # TODO: torch.quint4x2 is not supported
288
+ if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
289
+ weight = torch.ops.quantized_decomposed.dequantize_per_channel(
290
+ weight,
291
+ weight_scale,
292
+ weight_zero_point,
293
+ weight_axis,
294
+ weight_quant_min,
295
+ weight_quant_max,
296
+ weight_dtype_,
297
+ ) # type: ignore[arg-type]
298
+ return weight
299
+ raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
300
+
301
+
302
+ def _quantize_weight(
303
+ weight: torch.Tensor,
304
+ weight_qscheme: torch.qscheme,
305
+ weight_dtype: torch.dtype,
306
+ weight_scale: torch.Tensor,
307
+ weight_zero_point: torch.Tensor,
308
+ weight_axis_int: int,
309
+ ) -> torch.Tensor:
310
+ if weight_dtype == torch.float16:
311
+ weight = weight.to(weight_dtype)
312
+ return weight
313
+
314
+ if weight_qscheme == torch.per_tensor_affine:
315
+ if weight_dtype in [torch.quint8, torch.qint8, torch.qint32]:
316
+ weight = torch.quantize_per_tensor(
317
+ weight, weight_scale, weight_zero_point, weight_dtype
318
+ )
319
+ return weight
320
+ elif weight_qscheme in [
321
+ torch.per_channel_affine,
322
+ torch.per_channel_affine_float_qparams,
323
+ ]:
324
+ if weight_dtype in [torch.quint8, torch.qint8, torch.quint4x2, torch.qint32]:
325
+ weight = torch.quantize_per_channel(
326
+ weight, weight_scale, weight_zero_point, weight_axis_int, weight_dtype
327
+ ) # type: ignore[arg-type]
328
+ return weight
329
+ raise ValueError(f"Unsupported dtype and qscheme: {weight_dtype}, {weight_qscheme}")
330
+
331
+
332
+ def _quantize_and_dequantize_weight_decomposed(
333
+ weight: torch.Tensor,
334
+ weight_qscheme: torch.qscheme,
335
+ weight_dtype: torch.dtype,
336
+ weight_scale: torch.Tensor,
337
+ weight_zero_point: torch.Tensor,
338
+ weight_axis_int: int,
339
+ weight_quant_min: typing.Optional[int],
340
+ weight_quant_max: typing.Optional[int],
341
+ ) -> torch.Tensor:
342
+ """Quantize and then dequantize the weight based on
343
+ the quantization parameters
344
+ """
345
+ if weight_qscheme in [
346
+ torch.per_tensor_affine,
347
+ torch.per_channel_affine,
348
+ torch.per_channel_affine_float_qparams,
349
+ ]:
350
+ weight_quant = _quantize_weight_decomposed(
351
+ weight,
352
+ weight_qscheme,
353
+ weight_dtype,
354
+ weight_scale,
355
+ weight_zero_point,
356
+ weight_axis_int,
357
+ weight_quant_min,
358
+ weight_quant_max,
359
+ )
360
+ weight_dequant = _dequantize_weight_decomposed(
361
+ weight_quant,
362
+ weight_qscheme,
363
+ weight_dtype,
364
+ weight_scale,
365
+ weight_zero_point,
366
+ weight_axis_int,
367
+ weight_quant_min,
368
+ weight_quant_max,
369
+ )
370
+ else:
371
+ weight_dequant = weight
372
+ return weight_dequant
373
+
374
+
375
+ def _quantize_and_dequantize_weight(
376
+ weight: torch.Tensor,
377
+ weight_qscheme: torch.qscheme,
378
+ weight_dtype: torch.dtype,
379
+ weight_scale: torch.Tensor,
380
+ weight_zero_point: torch.Tensor,
381
+ weight_axis_int: int,
382
+ ) -> torch.Tensor:
383
+ """Quantize and then dequantize the weight based on
384
+ the quantization parameters
385
+ """
386
+ if weight_qscheme in [
387
+ torch.per_tensor_affine,
388
+ torch.per_channel_affine,
389
+ torch.per_channel_affine_float_qparams,
390
+ ]:
391
+ weight_quant = _quantize_weight(
392
+ weight,
393
+ weight_qscheme,
394
+ weight_dtype,
395
+ weight_scale,
396
+ weight_zero_point,
397
+ weight_axis_int,
398
+ )
399
+ weight_dequant = weight_quant.dequantize()
400
+ else:
401
+ weight_dequant = weight
402
+ return weight_dequant
403
+
404
+
405
+ def _save_weight_qparams(
406
+ destination,
407
+ prefix,
408
+ weight_qscheme,
409
+ weight_dtype,
410
+ weight_scale,
411
+ weight_zero_point,
412
+ weight_axis,
413
+ ):
414
+ destination[prefix + "weight_qscheme"] = weight_qscheme
415
+ destination[prefix + "weight_dtype"] = weight_dtype
416
+ if weight_qscheme is not None:
417
+ destination[prefix + "weight_scale"] = weight_scale
418
+ destination[prefix + "weight_zero_point"] = weight_zero_point
419
+ if weight_qscheme == torch.per_channel_affine:
420
+ destination[prefix + "weight_axis"] = weight_axis
421
+
422
+
423
+ def _get_weight_qparam_keys(state_dict: dict[str, typing.Any], prefix: str):
424
+ keys = ["weight_qscheme", "weight_dtype"]
425
+ weight_qscheme = state_dict[prefix + "weight_qscheme"]
426
+ if weight_qscheme is not None:
427
+ keys.append("weight_scale")
428
+ keys.append("weight_zero_point")
429
+ if weight_qscheme == torch.quantize_per_channel:
430
+ keys.append("weight_axis")
431
+ return keys
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (225 Bytes). View file
 
tool_server/.venv/lib/python3.12/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
+ ]
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (374 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/linear.cpython-312.pyc ADDED
Binary file (12.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/__pycache__/utils.cpython-312.pyc ADDED
Binary file (2.68 kB). View file
 
tool_server/.venv/lib/python3.12/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
+ ]
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (278 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/__pycache__/linear.cpython-312.pyc ADDED
Binary file (8.29 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/dynamic/linear.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional
3
+
4
+ import torch
5
+ import torch.ao.nn.intrinsic as nni
6
+ from torch.ao.nn.quantized.modules.utils import (
7
+ _hide_packed_params_repr,
8
+ _quantize_weight,
9
+ )
10
+ from torch.ao.nn.sparse.quantized import linear
11
+ from torch.ao.nn.sparse.quantized.utils import LinearBlockSparsePattern
12
+
13
+
14
+ __all__ = ["Linear"]
15
+
16
+
17
+ class Linear(torch.nn.Module):
18
+ r"""
19
+ A dynamically quantized sparse linear module with float tensor as inputs and outputs.
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 (
87
+ op_type == "sparse"
88
+ ), f"Cannot load from op_type [{op_type}], expecting [{self._op_type}]"
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: Optional[torch.Tensor],
128
+ row_block_size: Optional[int],
129
+ col_block_size: Optional[int],
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) == 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) == nni.LinearReLU:
152
+ mod = mod[0]
153
+ if mod.qconfig is not None and mod.qconfig.weight is not None:
154
+ weight_observer = mod.qconfig.weight()
155
+ else:
156
+ # We have the circular import issues if we import the qconfig in the beginning of this file:
157
+ # https://github.com/pytorch/pytorch/pull/24231. The current workaround is to postpone the
158
+ # import until we need it.
159
+ from torch.ao.quantization.qconfig import default_dynamic_qconfig
160
+
161
+ weight_observer = default_dynamic_qconfig.weight()
162
+
163
+ # It is important to multiply by the mask BEFORE calling the `weight_observer`
164
+ # TODO (zaf): Mask might not be part of the qconfig (T83295194)
165
+ weight = mod.weight
166
+ if getattr(mod.qconfig, "mask", False):
167
+ weight = mod.qconfig.mask * mod.weight
168
+
169
+ weight_observer(weight)
170
+ dtype = weight_observer.dtype
171
+ assert dtype == torch.qint8, "Weight observer must have dtype torch.qint8"
172
+ _w_sc, w_zp = weight_observer.calculate_qparams()
173
+ if isinstance(w_zp, torch.Tensor):
174
+ assert not torch.any(w_zp.bool()), "All weight zero points must map to 0"
175
+ else:
176
+ assert w_zp == 0, "Weight zero point must map to 0"
177
+ qweight = _quantize_weight(weight.float(), weight_observer)
178
+
179
+ row_block_size, col_block_size = LinearBlockSparsePattern.block_size()
180
+ qlinear = cls(
181
+ mod.in_features,
182
+ mod.out_features,
183
+ row_block_size,
184
+ col_block_size,
185
+ dtype=dtype,
186
+ )
187
+ qlinear.set_weight_bias(qweight, mod.bias, row_block_size, col_block_size)
188
+ return qlinear
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/linear.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ from typing import Optional
4
+
5
+ import torch
6
+ from torch.ao.nn.quantized.modules.utils import (
7
+ _hide_packed_params_repr,
8
+ _quantize_weight,
9
+ )
10
+
11
+
12
+ __all__ = ["LinearPackedParams", "Linear"]
13
+
14
+
15
+ # TODO (zaf): Inherit from `quantized.LinearPackedParams` (T83294430)
16
+ class LinearPackedParams(torch.nn.Module):
17
+ _version = 1
18
+
19
+ def __init__(self, row_block_size=1, col_block_size=4, dtype=torch.qint8):
20
+ super().__init__()
21
+
22
+ if dtype != torch.qint8:
23
+ raise NotImplementedError("Linear prepacking only supports QINT8")
24
+ self.dtype = dtype
25
+ wq = torch._empty_affine_quantized(
26
+ [1, 1], scale=1.0, zero_point=0, dtype=torch.qint8
27
+ )
28
+ self.set_weight_bias(wq, None, row_block_size, col_block_size)
29
+
30
+ def _get_name(self):
31
+ return "SparseQuantizedLinearPackedParams"
32
+
33
+ @torch.jit.export
34
+ def set_weight_bias(
35
+ self,
36
+ weight: torch.Tensor,
37
+ bias: Optional[torch.Tensor],
38
+ row_block_size: Optional[int],
39
+ col_block_size: Optional[int],
40
+ ) -> None:
41
+ assert row_block_size is not None and col_block_size is not None
42
+ self._packed_params = torch.ops.sparse.qlinear_prepack(
43
+ weight, bias, row_block_size, col_block_size
44
+ )
45
+
46
+ @torch.jit.export
47
+ def _weight_bias(self):
48
+ (weight, bias, block_sizes) = torch.ops.sparse.qlinear_unpack(
49
+ self._packed_params
50
+ )
51
+ return (weight, bias, block_sizes[0], block_sizes[1])
52
+
53
+ def forward(self, x):
54
+ return x
55
+
56
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
57
+ super()._save_to_state_dict(destination, prefix, keep_vars)
58
+ destination[prefix + "dtype"] = self.dtype
59
+ destination[prefix + "_packed_params"] = self._weight_bias()
60
+
61
+ def _load_from_state_dict(
62
+ self,
63
+ state_dict,
64
+ prefix,
65
+ local_metadata,
66
+ strict,
67
+ missing_keys,
68
+ unexpected_keys,
69
+ error_msgs,
70
+ ):
71
+ version = local_metadata.get("version", None)
72
+ assert version <= self._version
73
+
74
+ self.dtype = state_dict.pop(prefix + "dtype")
75
+ weight, bias, row_block_size, col_block_size = state_dict.pop(
76
+ prefix + "_packed_params"
77
+ )
78
+ self.set_weight_bias(weight, bias, row_block_size, col_block_size)
79
+
80
+ super()._load_from_state_dict(
81
+ state_dict,
82
+ prefix,
83
+ local_metadata,
84
+ False,
85
+ missing_keys,
86
+ unexpected_keys,
87
+ error_msgs,
88
+ )
89
+
90
+ @torch.jit.export
91
+ def __getstate__(self):
92
+ return self._packed_params, self.training, self.dtype
93
+
94
+ @torch.jit.export
95
+ def __setstate__(self, state):
96
+ (self._packed_params, self.training, self.dtype) = state
97
+
98
+ def __repr__(self):
99
+ return self._weight_bias().__repr__()
100
+
101
+
102
+ # TODO (zaf): Inherit from `quantized.Linear` (T83294430)
103
+ class Linear(torch.nn.Module):
104
+ r"""
105
+ A quantized sparse linear module with quantized tensor as inputs and outputs.
106
+ """
107
+ _version = 1
108
+ _FLOAT_MODULE = torch.nn.Linear
109
+
110
+ def __init__(
111
+ self,
112
+ in_features,
113
+ out_features,
114
+ row_block_size,
115
+ col_block_size,
116
+ bias=True,
117
+ dtype=torch.qint8,
118
+ ):
119
+ super().__init__()
120
+
121
+ if dtype != torch.qint8:
122
+ raise NotImplementedError(
123
+ "Only QINT8 is supported for Sparse Quantized Linear"
124
+ )
125
+
126
+ self.in_features = in_features
127
+ self.out_features = out_features
128
+
129
+ if bias:
130
+ bias = torch.zeros(self.out_features, dtype=torch.float)
131
+ else:
132
+ bias = None
133
+
134
+ qweight = torch._empty_affine_quantized(
135
+ [out_features, in_features], scale=1, zero_point=0, dtype=torch.qint8
136
+ )
137
+ self._packed_params = LinearPackedParams(
138
+ row_block_size=row_block_size, col_block_size=col_block_size, dtype=dtype
139
+ )
140
+ self._packed_params.set_weight_bias(
141
+ qweight, bias, row_block_size, col_block_size
142
+ )
143
+ self.scale = 1.0
144
+ self.zero_point = 0
145
+
146
+ @classmethod
147
+ def _get_name(cls):
148
+ return "SparseQuantizedLinear"
149
+
150
+ def extra_repr(self):
151
+ return (
152
+ f"in_features={self.in_features}, out_features={self.out_features}, scale={self.scale}, "
153
+ f"zero_point={self.zero_point}, qscheme={self.weight().qscheme()}"
154
+ )
155
+
156
+ def __repr__(self):
157
+ return _hide_packed_params_repr(self, LinearPackedParams)
158
+
159
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
160
+ return torch.ops.sparse.qlinear(
161
+ x, self._packed_params._packed_params, self.scale, self.zero_point
162
+ )
163
+
164
+ def _save_to_state_dict(self, destination, prefix, keep_vars):
165
+ super()._save_to_state_dict(destination, prefix, keep_vars)
166
+ destination[prefix + "scale"] = torch.tensor(self.scale)
167
+ destination[prefix + "zero_point"] = torch.tensor(self.zero_point)
168
+
169
+ def _load_from_state_dict(
170
+ self,
171
+ state_dict,
172
+ prefix,
173
+ local_metadata,
174
+ strict,
175
+ missing_keys,
176
+ unexpected_keys,
177
+ error_msgs,
178
+ ):
179
+ self.scale = float(state_dict[prefix + "scale"])
180
+ state_dict.pop(prefix + "scale")
181
+
182
+ self.zero_point = int(state_dict[prefix + "zero_point"])
183
+ state_dict.pop(prefix + "zero_point")
184
+
185
+ state_dict.pop(prefix + "op_type")
186
+
187
+ version = local_metadata.get("version", None)
188
+ assert version <= self._version
189
+
190
+ super()._load_from_state_dict(
191
+ state_dict,
192
+ prefix,
193
+ local_metadata,
194
+ False,
195
+ missing_keys,
196
+ unexpected_keys,
197
+ error_msgs,
198
+ )
199
+
200
+ def _weight_bias(self):
201
+ return self._packed_params._weight_bias()
202
+
203
+ def weight(self):
204
+ return self._weight_bias()[0]
205
+
206
+ def bias(self):
207
+ return self._weight_bias()[1]
208
+
209
+ def set_weight_bias(
210
+ self,
211
+ w: torch.Tensor,
212
+ b: Optional[torch.Tensor],
213
+ row_block_size: Optional[int],
214
+ col_block_size: Optional[int],
215
+ ) -> None:
216
+ assert row_block_size is not None and col_block_size is not None
217
+ self._packed_params.set_weight_bias(w, b, row_block_size, col_block_size)
218
+
219
+ @classmethod
220
+ def from_float(cls, mod, use_precomputed_fake_quant=False):
221
+ r"""Create a quantized sparse module from a float module.
222
+
223
+ We only care about the convert at this stage, no need for observers just yet.
224
+
225
+ TODO(zaf): Need to add the sparse params to the qconfig
226
+ """
227
+ assert type(mod) == cls._FLOAT_MODULE, (
228
+ cls._get_name() + ".from_float only works for " + cls._FLOAT_MODULE.__name__
229
+ )
230
+ assert hasattr(mod, "sparse_params"), (
231
+ "Expecting the Linear to have `sparse_params`. Make sure you have provided arguments "
232
+ 'in the `sparsifier.squash_mask(params_to_save=("sparse_block_shape",))` method.'
233
+ )
234
+ sparse_block_shape = mod.sparse_params.get("sparse_block_shape", None) # type: ignore[operator, union-attr]
235
+ assert isinstance(sparse_block_shape, (tuple, list))
236
+ assert len(sparse_block_shape) == 2
237
+ # TODO: Need to add options to qconfig to avoid the calibration.
238
+ # TODO: Add calibration for the sparsity
239
+ assert hasattr(mod, "qconfig"), "Input float module must have qconfig defined"
240
+ activation_post_process = mod.activation_post_process
241
+ weight_post_process = mod.qconfig.weight() # type: ignore[operator, union-attr]
242
+
243
+ # Assumption is that the weight is already sparsified by the
244
+ # `sparsifier.convert`
245
+ weight = mod.weight
246
+
247
+ weight_post_process(weight)
248
+ dtype = weight_post_process.dtype
249
+ act_scale, act_zp = activation_post_process.calculate_qparams() # type: ignore[operator, union-attr]
250
+ assert dtype == torch.qint8, "Weight observer must have dtype torch.qint8"
251
+ w_sc, w_zp = weight_post_process.calculate_qparams()
252
+ if isinstance(w_zp, torch.Tensor):
253
+ assert not torch.any(w_zp.bool()), "All weight zero points must map to 0"
254
+ else:
255
+ assert w_zp == 0, "Weight zero point must map to 0"
256
+ qweight = _quantize_weight(weight.float(), weight_post_process)
257
+
258
+ row_block_size = mod.sparse_params["sparse_block_shape"][0] # type: ignore[index]
259
+ col_block_size = mod.sparse_params["sparse_block_shape"][1] # type: ignore[index]
260
+ qlinear = cls(
261
+ mod.in_features,
262
+ mod.out_features,
263
+ row_block_size,
264
+ col_block_size,
265
+ dtype=dtype,
266
+ )
267
+ qlinear.set_weight_bias(
268
+ qweight, mod.bias, row_block_size, col_block_size # type: ignore[arg-type]
269
+ )
270
+ qlinear.scale = float(act_scale)
271
+ qlinear.zero_point = int(act_zp)
272
+ return qlinear
tool_server/.venv/lib/python3.12/site-packages/torch/ao/nn/sparse/quantized/utils.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ from typing import Optional
3
+
4
+
5
+ __all__ = ["LinearBlockSparsePattern"]
6
+
7
+
8
+ def _is_valid_linear_block_sparse_pattern(
9
+ row_block_size: int, col_block_size: int
10
+ ) -> bool:
11
+ return (row_block_size == 1 and col_block_size == 4) or (
12
+ row_block_size == 8 and col_block_size == 1
13
+ )
14
+
15
+
16
+ # This is a stop-gap measure as current flow does not allow module
17
+ # specific block sparse pattern.
18
+ # Infact there is no way to convey sparse pattern via module config
19
+ # of quantization flow. Thus using the global context to convey
20
+ # sparsity pattern.
21
+ # Once the flow supports it, this should be removed.
22
+ class LinearBlockSparsePattern:
23
+ rlock = threading.RLock()
24
+ row_block_size: int = 1
25
+ col_block_size: int = 4
26
+ prev_row_block_size: int = 1
27
+ prev_col_block_size: int = 4
28
+
29
+ def __init__(self, row_block_size: int = 1, col_block_size: int = 4):
30
+ assert _is_valid_linear_block_sparse_pattern(row_block_size, col_block_size)
31
+ LinearBlockSparsePattern.rlock.acquire()
32
+ LinearBlockSparsePattern.prev_row_block_size = (
33
+ LinearBlockSparsePattern.row_block_size
34
+ )
35
+ LinearBlockSparsePattern.prev_col_block_size = (
36
+ LinearBlockSparsePattern.col_block_size
37
+ )
38
+ LinearBlockSparsePattern.row_block_size = row_block_size
39
+ LinearBlockSparsePattern.col_block_size = col_block_size
40
+
41
+ def __enter__(self) -> None:
42
+ pass
43
+
44
+ def __exit__(
45
+ self,
46
+ exc_type: Optional[type[BaseException]],
47
+ exc_value: Optional[BaseException],
48
+ backtrace: Optional[object],
49
+ ) -> None:
50
+ LinearBlockSparsePattern.row_block_size = (
51
+ LinearBlockSparsePattern.prev_row_block_size
52
+ )
53
+ LinearBlockSparsePattern.col_block_size = (
54
+ LinearBlockSparsePattern.prev_col_block_size
55
+ )
56
+ LinearBlockSparsePattern.rlock.release()
57
+
58
+ @staticmethod
59
+ def block_size() -> tuple[int, int]:
60
+ return (
61
+ LinearBlockSparsePattern.row_block_size,
62
+ LinearBlockSparsePattern.col_block_size,
63
+ )
tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (181 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/_numeric_suite.cpython-312.pyc ADDED
Binary file (24.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/__pycache__/_numeric_suite_fx.cpython-312.pyc ADDED
Binary file (37.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__init__.py ADDED
File without changes
tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (184 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/graph_matcher.cpython-312.pyc ADDED
Binary file (17.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/graph_passes.cpython-312.pyc ADDED
Binary file (30.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/mappings.cpython-312.pyc ADDED
Binary file (23.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/ns/fx/__pycache__/n_shadows_utils.cpython-312.pyc ADDED
Binary file (39 kB). View file