compressed-tensors-nightly 0.7.1.20241030__py3-none-any.whl → 0.7.1.20241101__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (20) hide show
  1. compressed_tensors/quantization/__init__.py +0 -1
  2. compressed_tensors/quantization/lifecycle/__init__.py +0 -2
  3. compressed_tensors/quantization/lifecycle/apply.py +1 -16
  4. compressed_tensors/quantization/lifecycle/forward.py +13 -107
  5. compressed_tensors/quantization/lifecycle/initialize.py +18 -21
  6. compressed_tensors/quantization/quant_args.py +1 -8
  7. compressed_tensors/quantization/utils/helpers.py +127 -8
  8. {compressed_tensors_nightly-0.7.1.20241030.dist-info → compressed_tensors_nightly-0.7.1.20241101.dist-info}/METADATA +1 -1
  9. {compressed_tensors_nightly-0.7.1.20241030.dist-info → compressed_tensors_nightly-0.7.1.20241101.dist-info}/RECORD +12 -20
  10. compressed_tensors/quantization/cache.py +0 -200
  11. compressed_tensors/quantization/lifecycle/calibration.py +0 -80
  12. compressed_tensors/quantization/lifecycle/frozen.py +0 -50
  13. compressed_tensors/quantization/observers/__init__.py +0 -21
  14. compressed_tensors/quantization/observers/base.py +0 -213
  15. compressed_tensors/quantization/observers/helpers.py +0 -149
  16. compressed_tensors/quantization/observers/min_max.py +0 -104
  17. compressed_tensors/quantization/observers/mse.py +0 -164
  18. {compressed_tensors_nightly-0.7.1.20241030.dist-info → compressed_tensors_nightly-0.7.1.20241101.dist-info}/LICENSE +0 -0
  19. {compressed_tensors_nightly-0.7.1.20241030.dist-info → compressed_tensors_nightly-0.7.1.20241101.dist-info}/WHEEL +0 -0
  20. {compressed_tensors_nightly-0.7.1.20241030.dist-info → compressed_tensors_nightly-0.7.1.20241101.dist-info}/top_level.txt +0 -0
@@ -1,200 +0,0 @@
1
- # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing,
10
- # software distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
-
16
- from enum import Enum
17
- from typing import Any, Dict, List, Optional, Tuple
18
-
19
- from compressed_tensors.quantization.observers import Observer
20
- from compressed_tensors.quantization.quant_args import QuantizationArgs
21
- from torch import Tensor
22
- from transformers import DynamicCache as HFDyanmicCache
23
-
24
-
25
- class KVCacheScaleType(Enum):
26
- KEY = "k_scale"
27
- VALUE = "v_scale"
28
-
29
-
30
- class QuantizedKVParameterCache(HFDyanmicCache):
31
- """
32
- Quantized KV cache used in the forward call based on HF's dynamic cache.
33
- Quantization strategy (tensor, group, channel) set from Quantization arg's strategy
34
- Singleton, so that the same cache gets reused in all forward call of self_attn.
35
- Each time forward is called, .update() is called, and ._quantize(), ._dequantize()
36
- gets called appropriately.
37
- The size of tensor is
38
- `[batch_size, num_heads, seq_len - residual_length, head_dim]`.
39
-
40
-
41
- Triggered by adding kv_cache_scheme in the recipe.
42
-
43
- Example:
44
-
45
- ```python3
46
- recipe = '''
47
- quant_stage:
48
- quant_modifiers:
49
- QuantizationModifier:
50
- kv_cache_scheme:
51
- num_bits: 8
52
- type: float
53
- strategy: tensor
54
- dynamic: false
55
- symmetric: true
56
- '''
57
-
58
- """
59
-
60
- _instance = None
61
- _initialized = False
62
-
63
- def __new__(cls, *args, **kwargs):
64
- """Singleton"""
65
- if cls._instance is None:
66
- cls._instance = super(QuantizedKVParameterCache, cls).__new__(cls)
67
- return cls._instance
68
-
69
- def __init__(self, quantization_args: QuantizationArgs):
70
- if not self._initialized:
71
- super().__init__()
72
-
73
- self.quantization_args = quantization_args
74
-
75
- self.k_observers: List[Observer] = []
76
- self.v_observers: List[Observer] = []
77
-
78
- # each index corresponds to layer_idx of the attention layer
79
- self.k_scales: List[Tensor] = []
80
- self.v_scales: List[Tensor] = []
81
-
82
- self.k_zps: List[Tensor] = []
83
- self.v_zps: List[Tensor] = []
84
-
85
- self._initialized = True
86
-
87
- def update(
88
- self,
89
- key_states: Tensor,
90
- value_states: Tensor,
91
- layer_idx: int,
92
- cache_kwargs: Optional[Dict[str, Any]] = None,
93
- ) -> Tuple[Tensor, Tensor]:
94
- """
95
- Get the k_scale and v_scale and output the
96
- fakequant-ed key_states and value_states
97
- """
98
-
99
- if len(self.k_observers) <= layer_idx:
100
- k_observer = self.quantization_args.get_observer()
101
- v_observer = self.quantization_args.get_observer()
102
-
103
- self.k_observers.append(k_observer)
104
- self.v_observers.append(v_observer)
105
-
106
- q_key_states = self._quantize(
107
- key_states.contiguous(), KVCacheScaleType.KEY, layer_idx
108
- )
109
- q_value_states = self._quantize(
110
- value_states.contiguous(), KVCacheScaleType.VALUE, layer_idx
111
- )
112
-
113
- qdq_key_states = self._dequantize(q_key_states, KVCacheScaleType.KEY, layer_idx)
114
- qdq_value_states = self._dequantize(
115
- q_value_states, KVCacheScaleType.VALUE, layer_idx
116
- )
117
-
118
- keys_to_return, values_to_return = qdq_key_states, qdq_value_states
119
-
120
- return keys_to_return, values_to_return
121
-
122
- def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
123
- """
124
- Returns the sequence length of the cached states.
125
- A layer index can be optionally passed.
126
- """
127
- if len(self.key_cache) <= layer_idx:
128
- return 0
129
- # since we cannot get the seq_length of each layer directly and
130
- # rely on `_seen_tokens` which is updated every "layer_idx" == 0,
131
- # this is a hack to get the actual seq_length for the given layer_idx
132
- # this part of code otherwise fails when used to
133
- # verify attn_weight shape in some models
134
- return self._seen_tokens if layer_idx == 0 else self._seen_tokens - 1
135
-
136
- def reset_states(self):
137
- """reset the kv states (used in calibration)"""
138
- self.key_cache: List[Tensor] = []
139
- self.value_cache: List[Tensor] = []
140
- # Used in `generate` to keep tally of how many tokens the cache has seen
141
- self._seen_tokens = 0
142
- self._quantized_key_cache: List[Tensor] = []
143
- self._quantized_value_cache: List[Tensor] = []
144
-
145
- def reset(self):
146
- """
147
- Reset the instantiation, create new instance on init
148
- """
149
- QuantizedKVParameterCache._instance = None
150
- QuantizedKVParameterCache._initialized = False
151
-
152
- def _quantize(self, tensor, kv_type, layer_idx):
153
- """Quantizes a key/value using a defined quantization method."""
154
- from compressed_tensors.quantization.lifecycle.forward import quantize
155
-
156
- if kv_type == KVCacheScaleType.KEY: # key type
157
- observer = self.k_observers[layer_idx]
158
- scales = self.k_scales
159
- zps = self.k_zps
160
- else:
161
- assert kv_type == KVCacheScaleType.VALUE
162
- observer = self.v_observers[layer_idx]
163
- scales = self.v_scales
164
- zps = self.v_zps
165
-
166
- scale, zp = observer(tensor)
167
- if len(scales) <= layer_idx:
168
- scales.append(scale)
169
- zps.append(zp)
170
- else:
171
- scales[layer_idx] = scale
172
- zps[layer_idx] = scale
173
-
174
- q_tensor = quantize(
175
- x=tensor,
176
- scale=scale,
177
- zero_point=zp,
178
- args=self.quantization_args,
179
- )
180
- return q_tensor
181
-
182
- def _dequantize(self, qtensor, kv_type, layer_idx):
183
- """Dequantizes back the tensor that was quantized by `self._quantize()`"""
184
- from compressed_tensors.quantization.lifecycle.forward import dequantize
185
-
186
- if kv_type == KVCacheScaleType.KEY:
187
- scale = self.k_scales[layer_idx]
188
- zp = self.k_zps[layer_idx]
189
- else:
190
- assert kv_type == KVCacheScaleType.VALUE
191
- scale = self.v_scales[layer_idx]
192
- zp = self.v_zps[layer_idx]
193
-
194
- qdq_tensor = dequantize(
195
- x_q=qtensor,
196
- scale=scale,
197
- zero_point=zp,
198
- args=self.quantization_args,
199
- )
200
- return qdq_tensor
@@ -1,80 +0,0 @@
1
- # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing,
10
- # software distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
-
16
- import logging
17
-
18
- from compressed_tensors.quantization.quant_config import QuantizationStatus
19
- from compressed_tensors.utils import is_module_offloaded, update_parameter_data
20
- from torch.nn import Module
21
-
22
-
23
- __all__ = [
24
- "set_module_for_calibration",
25
- ]
26
-
27
-
28
- _LOGGER = logging.getLogger(__name__)
29
-
30
-
31
- def set_module_for_calibration(module: Module, quantize_weights_upfront: bool = True):
32
- """
33
- marks a layer as ready for calibration which activates observers
34
- to update scales and zero points on each forward pass
35
-
36
- apply to full model with `model.apply(set_module_for_calibration)`
37
-
38
- :param module: module to set for calibration
39
- :param quantize_weights_upfront: whether to automatically
40
- run weight quantization at the start of calibration
41
- """
42
- if not getattr(module, "quantization_scheme", None):
43
- # no quantization scheme nothing to do
44
- return
45
- status = getattr(module, "quantization_status", None)
46
- if not status or status != QuantizationStatus.INITIALIZED:
47
- _LOGGER.warning(
48
- f"Attempting set module with status {status} to calibration mode. "
49
- f"but status is not {QuantizationStatus.INITIALIZED} - you may "
50
- "be calibrating an uninitialized module which may fail or attempting "
51
- "to re-calibrate a frozen module"
52
- )
53
-
54
- if quantize_weights_upfront and module.quantization_scheme.weights is not None:
55
- # set weight scale and zero_point up front, calibration data doesn't affect it
56
- if not hasattr(module, "weight_observer"):
57
- from compressed_tensors.quantization.lifecycle.initialize import (
58
- initialize_observers,
59
- )
60
-
61
- initialize_observers(
62
- module=module,
63
- base_name="weight",
64
- quantization_args=module.quantization_scheme.weights,
65
- )
66
-
67
- offloaded = is_module_offloaded(module)
68
- if offloaded:
69
- module._hf_hook.pre_forward(module)
70
-
71
- observer = module.weight_observer
72
- g_idx = getattr(module, "weight_g_idx", None)
73
- scale, zero_point = observer(module.weight, g_idx=g_idx)
74
- update_parameter_data(module, scale, "weight_scale")
75
- update_parameter_data(module, zero_point, "weight_zero_point")
76
-
77
- if offloaded:
78
- module._hf_hook.post_forward(module, None)
79
-
80
- module.quantization_status = QuantizationStatus.CALIBRATION
@@ -1,50 +0,0 @@
1
- # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing,
10
- # software distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
-
16
- from compressed_tensors.quantization.quant_config import QuantizationStatus
17
- from torch.nn import Module
18
-
19
-
20
- __all__ = [
21
- "freeze_module_quantization",
22
- ]
23
-
24
-
25
- def freeze_module_quantization(module: Module):
26
- """
27
- deletes observers so static quantization is completed.
28
-
29
- apply to full model with `model.apply(freeze_module_quantization)`
30
-
31
- :param module: module to freeze quantization for
32
- """
33
- scheme = getattr(module, "quantization_scheme", None)
34
- if not scheme:
35
- # no quantization scheme nothing to do
36
- return
37
-
38
- if module.quantization_status == QuantizationStatus.FROZEN:
39
- # nothing to do, already frozen
40
- return
41
-
42
- # delete observers from module if not dynamic
43
- if hasattr(module, "input_observer") and not scheme.input_activations.dynamic:
44
- delattr(module, "input_observer")
45
- if hasattr(module, "weight_observer") and not scheme.weights.dynamic:
46
- delattr(module, "weight_observer")
47
- if hasattr(module, "output_observer") and not scheme.output_activations.dynamic:
48
- delattr(module, "output_observer")
49
-
50
- module.quantization_status = QuantizationStatus.FROZEN
@@ -1,21 +0,0 @@
1
- # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing,
10
- # software distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- # flake8: noqa
16
- # isort: skip_file
17
-
18
- from .helpers import *
19
- from .base import *
20
- from .min_max import *
21
- from .mse import *
@@ -1,213 +0,0 @@
1
- # Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing,
10
- # software distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- import logging
16
- from math import ceil
17
- from typing import Any, Iterable, Optional, Tuple, Union
18
-
19
- import torch
20
- from compressed_tensors.quantization.quant_args import (
21
- QuantizationArgs,
22
- QuantizationStrategy,
23
- )
24
- from compressed_tensors.registry.registry import RegistryMixin
25
- from compressed_tensors.utils import safe_permute
26
- from torch import FloatTensor, IntTensor, Tensor
27
- from torch.nn import Module
28
-
29
-
30
- _LOGGER = logging.getLogger(__name__)
31
-
32
-
33
- __all__ = ["Observer"]
34
-
35
-
36
- class Observer(Module, RegistryMixin):
37
- """
38
- Base Observer class to be subclassed for specific implementation.
39
- Subclasses should override `calculate_qparams` to return a scale, zero_point
40
- pair
41
- """
42
-
43
- def __init__(self, quantization_args: QuantizationArgs):
44
- self.quantization_args: QuantizationArgs = quantization_args
45
- super().__init__()
46
- self._scale = None
47
- self._zero_point = None
48
- self._num_observed_tokens = None
49
-
50
- @torch.no_grad()
51
- def forward(
52
- self, observed: Tensor, g_idx: Optional[Tensor] = None
53
- ) -> Tuple[FloatTensor, IntTensor]:
54
- """
55
- maps directly to get_qparams
56
- :param observed: optional observed tensor from which to calculate
57
- quantization parameters
58
- :param g_idx: optional mapping from column index to group index
59
- :return: tuple of scale and zero point based on last observed value
60
- """
61
- self.record_observed_tokens(observed)
62
- return self.get_qparams(observed=observed, g_idx=g_idx)
63
-
64
- def calculate_qparams(
65
- self,
66
- observed: Tensor,
67
- reduce_dims: Optional[Tuple[int]] = None,
68
- ) -> Tuple[FloatTensor, IntTensor]:
69
- """
70
- :param observed: observed tensor to calculate quantization parameters for
71
- :param reduce_dims: optional tuple of dimensions to reduce along,
72
- returned scale and zero point will be shaped (1,) along the
73
- reduced dimensions
74
- :return: tuple of scale and zero point derived from the observed tensor
75
- """
76
- raise NotImplementedError(f"{self.__class__} must implement calculate_qparams")
77
-
78
- def post_calculate_qparams(self) -> None:
79
- """
80
- Run any logic specific to its observers after running calculate_qparams
81
- """
82
- ...
83
-
84
- def get_qparams(
85
- self,
86
- observed: Optional[Tensor] = None,
87
- g_idx: Optional[Tensor] = None,
88
- ) -> Tuple[FloatTensor, IntTensor]:
89
- """
90
- Convenience function to wrap overwritten calculate_qparams
91
- adds support to make observed tensor optional and support for tracking latest
92
- calculated scale and zero point
93
-
94
- :param observed: optional observed tensor to calculate quantization parameters
95
- from
96
- :param g_idx: optional mapping from column index to group index
97
- :return: tuple of scale and zero point based on last observed value
98
- """
99
- if observed is not None:
100
- group_size = self.quantization_args.group_size
101
-
102
- if self.quantization_args.strategy == QuantizationStrategy.TENSOR:
103
-
104
- # re-calculate scale and zero point, update the stored value
105
- self._scale, self._zero_point = self.calculate_qparams(observed)
106
-
107
- elif self.quantization_args.strategy == QuantizationStrategy.GROUP:
108
- rows = observed.shape[0]
109
- columns = observed.shape[1]
110
- num_groups = int(ceil(columns / group_size))
111
- self._scale = torch.empty(
112
- (rows, num_groups), dtype=observed.dtype, device=observed.device
113
- )
114
- zp_dtype = self.quantization_args.pytorch_dtype()
115
- self._zero_point = torch.empty(
116
- (rows, num_groups), dtype=zp_dtype, device=observed.device
117
- )
118
-
119
- # support column-order (default) quantization as well as other orderings
120
- # such as activation ordering. Below checks if g_idx has initialized
121
- is_column_order = g_idx is None or -1 in g_idx
122
- if is_column_order:
123
- group_sizes = torch.full((num_groups,), group_size, dtype=torch.int)
124
- else:
125
- group_indices, group_sizes = torch.unique(g_idx, return_counts=True)
126
- group_sizes = group_sizes[torch.argsort(group_indices)]
127
-
128
- perm = torch.argsort(g_idx)
129
- observed = safe_permute(observed, perm, dim=1)
130
-
131
- # TODO: experiment with vectorizing for loop for performance
132
- end = 0
133
- for group_index, group_count in enumerate(group_sizes):
134
- start = end
135
- end = start + group_count
136
- scale, zero_point = self.get_qparams_along_dim(
137
- observed[:, start:end],
138
- 0,
139
- tensor_id=group_index,
140
- )
141
-
142
- self._scale[:, group_index] = scale.squeeze(1)
143
- self._zero_point[:, group_index] = zero_point.squeeze(1)
144
-
145
- elif self.quantization_args.strategy == QuantizationStrategy.CHANNEL:
146
- # assume observed is transposed, because its the output, hence use dim 0
147
- self._scale, self._zero_point = self.get_qparams_along_dim(observed, 0)
148
-
149
- elif self.quantization_args.strategy == QuantizationStrategy.TOKEN:
150
- # use dim 1, assume the obsersed.shape = [batch, token, hidden]
151
- # should be batch, token
152
- self._scale, self._zero_point = self.get_qparams_along_dim(
153
- observed,
154
- dim={0, 1},
155
- )
156
-
157
- return self._scale, self._zero_point
158
-
159
- def get_qparams_along_dim(
160
- self,
161
- observed,
162
- dim: Union[int, Iterable[int]],
163
- tensor_id: Optional[Any] = None,
164
- ):
165
- if isinstance(dim, int):
166
- dim = [dim]
167
- dim = set(dim)
168
-
169
- reduce_dims = tuple(idx for idx in range(observed.ndim) if idx not in dim)
170
- return self.calculate_qparams(
171
- observed, reduce_dims=reduce_dims, tensor_id=tensor_id
172
- )
173
-
174
- def record_observed_tokens(self, batch_tensor: Tensor):
175
- """
176
- Counts the number of tokens observed during the
177
- forward passes. The count is aggregated in the
178
- _num_observed_tokens attribute of the class.
179
-
180
- Note: The batch_tensor is expected to have two dimensions
181
- (batch_size * sequence_length, num_features). This is the
182
- general shape expected by the forward pass of the expert
183
- layers in a MOE model. If the input tensor does not have
184
- two dimensions, the _num_observed_tokens attribute will be set
185
- to None.
186
- """
187
- if not isinstance(batch_tensor, Tensor):
188
- raise ValueError(f"Expected value to be a tensor, got {type(batch_tensor)}")
189
-
190
- if batch_tensor.ndim != 2:
191
- _LOGGER.debug(
192
- "The input tensor is expected to have two dimensions "
193
- "(batch_size * sequence_length, num_features). "
194
- f"The input tensor has {batch_tensor.ndim} dimensions."
195
- )
196
- return
197
-
198
- if self._num_observed_tokens is None:
199
- # initialize the count
200
- self._num_observed_tokens = 0
201
-
202
- # batch_tensor (batch_size * sequence_length, num_features)
203
- # observed_tokens (batch_size * sequence_length)
204
- observed_tokens, _ = batch_tensor.shape
205
- self._num_observed_tokens += observed_tokens
206
-
207
- def reset(self):
208
- """
209
- Reset the state of the observer
210
- """
211
- self._num_observed_tokens = None
212
- self._scale = None
213
- self._zero_point = None