1: import torch
2: from typing import Any, Dict, List, Optional, Tuple
3: from transformers.cache_utils import DynamicCache, CacheConfig, QuantizedCacheConfig, is_optimum_quanto_available
4: from transformers.utils import is_hqq_available
5: 
6: from .vanilla_quantizer import VanillaQuantizer
7: 
8: if is_hqq_available():
9:     from hqq.core.quantize import Quantizer as HQQQuantizer
10: 
11: '''
12: per_head_config = {
13:     {n_layer}: {
14:         {head_idx}: {
15:             'nbits_key': 4,
16:             'nbits_value': 4,
17:         }
18:     }
19: '''
20: 
21: class FlexibleQuantizedCacheConfig(QuantizedCacheConfig):
22:     """
23:     Configuration for flexible quantized cache.
24: 
25:     Attributes:
26:         backend (str): Backend for quantization. Options: "quanto", "hqq", "vanilla".
27:         nbits (Optional[int]): Precision for both key and value. Used if `nbits_key` and `nbits_value` are not set.
28:                                For per-layer or per-head quantization, set `nbits` to -1.
29:         nbits_key (Optional[int]): Precision for key quantization. For per-layer or per-head quantization, set to -1.
30:         nbits_value (Optional[int]): Precision for value quantization. For per-layer or per-head quantization, set to -1.
31:         axis_key (Optional[int]): Axis for key quantization. In Vanilla mode:
32:                                   - 0: Per-token quantization
33:                                   - 1: Per-channel quantization
34:         axis_value (Optional[int]): Axis for value quantization. In Vanilla mode:
35:                                     - 0: Per-token quantization
36:                                     - 1: Per-channel quantization
37:         asym (Optional[bool]): Whether to use asymmetric quantization. Works only for Vanilla mode.
38:         q_group_size (Optional[int]): Group size for quantization. Use -1 for per-token quantization.
39:         residual_length (Optional[int]): Length of residual tokens that are not quantized.
40:                                          Must be a multiple of `q_group_size`. Use 0 for per-token quantization.
41:         compute_dtype (Optional[torch.dtype]): Compute dtype for the model. Default: `torch.float16`.
42:         device (Optional[str]): Device for the cache. Default: `"cpu"`.
43:         force_quant (Optional[bool]): Whether to quantize the cache during the pre-filling stage.
44:         per_layer_quant (Optional[bool]): Whether to use per-layer quantization.
45:         per_layer_config (Optional[Dict[str, Any]]): If `per_layer_quant` is True, provides the quantization config
46:                                                      for each layer. Alternatively, use `per_layer_config_path`.
47:         per_layer_config_path (Optional[str]): Path to the quantization config for each layer.
48:                                                Used if `per_layer_quant` is True.
49:         per_head_quant (Optional[bool]): Whether to use per-head quantization.
50:         per_head_config (Optional[Dict[str, Any]]): If `per_head_quant` is True, provides the quantization config
51:                                                     for each head. Alternatively, use `per_head_config_path`.
52:         per_head_config_path (Optional[str]): Path to the quantization config for each head.
53:                                               Used if `per_head_quant` is True.
54:     """
55: 
56:     cache_implementation = "flexible"
57:     
58:     def __init__(
59:         self,
60:         backend: str = "quanto",
61:         nbits: Optional[int] = 4,
62:         nbits_key: Optional[int] = 0,
63:         nbits_value: Optional[int] = 0,
64:         axis_key: Optional[int] = 0,
65:         axis_value: Optional[int] = 0,
66:         asym: Optional[bool] = False,
67:         q_group_size: Optional[int] = 64,
68:         residual_length: Optional[int] = 128,
69:         compute_dtype: Optional[torch.dtype] = torch.float16,
70:         device: Optional[str] = "cpu",
71:         force_quant: Optional[bool] = False,
72:         per_layer_quant: Optional[bool] = False,
73:         per_layer_config: Optional[Dict[str, Any]] = None,
74:         per_layer_config_path: Optional[str] = None,
75:         per_head_quant: Optional[bool] = False,
76:         per_head_config: Optional[Dict[str, Any]] = None,
77:         per_head_config_path: Optional[str] = None,
78:     ):
79:         super().__init__(
80:             backend=backend,
81:             nbits=nbits,
82:             axis_key=axis_key,
83:             axis_value=axis_value,
84:             q_group_size=q_group_size,
85:             residual_length=residual_length,
86:             compute_dtype=compute_dtype,
87:             device=device,
88:         )
89:         self.nbits_key = nbits_key if nbits_key else nbits
90:         self.nbits_value = nbits_value if nbits_value else nbits
91:         self.asym = asym
92:         self.force_quant = force_quant
93:         if per_head_quant and per_layer_quant:
94:             raise ValueError("per_layer_quant and per_head_quant cannot be Enabled at the same time.")
95:         self.per_layer_quant = per_layer_quant
96:         if per_layer_quant:
97:             if per_layer_config is not None:
98:                 self.per_layer_config = per_layer_config
99:             elif per_layer_config_path is not None:
100:                 import yaml
101:                 with open(per_layer_config_path, 'r') as f:
102:                     self.per_layer_config = yaml.safe_load(f)
103:             else:
104:                 raise ValueError("per_layer_quant is set to True but per_layer_config or per_layer_config_path is not provided.")
105:         self.per_head_quant = per_head_quant
106:         if per_head_quant:
107:             if per_head_config is not None:
108:                 self.per_head_config = per_head_config
109:             elif per_head_config_path is not None:
110:                 import yaml
111:                 with open(per_head_config_path, 'r') as f:
112:                     self.per_head_config = yaml.safe_load(f)
113:             else:
114:                 raise ValueError("per_head_quant is set to True but per_head_config or per_head_config_path is not provided.")
115: 
116: 
117: class FlexibleQuantizedCache(DynamicCache):
118:     """
119:     A quantizer cache similar to what is described in the [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper](https://arxiv.org/abs/2402.02750).
120:     It allows the model to generate longer sequence length without allocating too much memory for Key and Value cache by applying quantization.
121: 
122:     The cache has two types of storage, one for original precision and one for the quantized cache. A `residual length` is set as a maximum capacity for the
123:     original precision cache. When the length goes beyond maximum capacity, the original precision cache is discarded and moved into the quantized cache. The
124:     quantization is done per-channel with a set `q_group_size` for both Keys and Values, in contrast to what was described in the paper.
125: 
126:     It stores Keys and Values a list of quantized tensors (tuples in case we need to store metadata), one for each layer. Additionally, it stores the Key and
127:     Value in original precision states as a list of tensors, one for each layer. The size of each tensor
128:     is `[batch_size, num_heads, seq_len - residual_length, head_dim]`
129:     """
130: 
131:     def __init__(self, cache_config: FlexibleQuantizedCacheConfig) -> None:
132:         super().__init__()
133:         self._quantized_key_cache: List[torch.Tensor] = []
134:         self._quantized_value_cache: List[torch.Tensor] = []
135: 
136:         self.nbits = cache_config.nbits
137:         self.nbits_key = cache_config.nbits_key
138:         self.nbits_value = cache_config.nbits_value
139:         self.residual_length = cache_config.residual_length
140:         self.q_group_size = cache_config.q_group_size
141:         self.axis_key = cache_config.axis_key
142:         self.axis_value = cache_config.axis_value
143:         self.asym = cache_config.asym
144:         self.compute_dtype = cache_config.compute_dtype
145:         self.device = cache_config.device
146:         self.force_quant = cache_config.force_quant
147:         self.per_layer_quant = cache_config.per_layer_quant
148:         if self.per_layer_quant:
149:             self.per_layer_config = cache_config.per_layer_config
150:         self.per_head_quant = cache_config.per_head_quant
151:         if self.per_head_quant:
152:             self.per_head_config = cache_config.per_head_config
153: 
154:         super().__init__()
155: 
156:     def update(
157:         self,
158:         key_states: torch.Tensor,
159:         value_states: torch.Tensor,
160:         layer_idx: int,
161:         cache_kwargs: Optional[Dict[str, Any]] = None,
162:     ) -> Tuple[torch.Tensor, torch.Tensor]:
163:         # Update the number of seen tokens
164:         # print('Called Update, {}, {}'.format(self.nbits_key, self.nbits_value))
165:         if layer_idx == 0:
166:             self._seen_tokens += key_states.shape[-2]
167:         if len(self.key_cache) < layer_idx:
168:             raise ValueError("QuantizedCache does not support model usage where layers are skipped. Use DynamicCache.")
169: 
170:         if not self.per_head_quant:
171:             nbits_key = self.nbits_key if not self.per_layer_quant else self.per_layer_config[layer_idx]['nbits_key']
172:             nbits_value = self.nbits_value if not self.per_layer_quant else self.per_layer_config[layer_idx]['nbits_value']
173:             if len(self.key_cache) == layer_idx:
174:                 if self.force_quant:
175:                     # quirk: use dequantized key/value instead of original key/value
176:                     if self.residual_length:
177:                         tokens_to_keep = key_states.shape[-2] % self.residual_length
178:                         # keep tokens_to_keep by slicing the cache in axis -2
179:                         self._quantized_key_cache.append(self._quantize(key_states[..., :-tokens_to_keep, :], axis=self.axis_key, nbits=nbits_key))
180:                         self._quantized_value_cache.append(self._quantize(value_states[..., :-tokens_to_keep, :], axis=self.axis_value, nbits=nbits_value))
181:                         self.key_cache.append(key_states[..., -tokens_to_keep:, :])
182:                         self.value_cache.append(value_states[..., -tokens_to_keep:, :])
183:                     else:
184:                         self._quantized_key_cache.append(self._quantize(key_states, axis=self.axis_key, nbits=nbits_key))
185:                         self._quantized_value_cache.append(self._quantize(value_states, axis=self.axis_value, nbits=nbits_value))
186:                         self.key_cache.append(torch.zeros(0, dtype=key_states.dtype, device=key_states.device))
187:                         self.value_cache.append(torch.zeros(0, dtype=key_states.dtype, device=key_states.device))
188:                     keys_to_return = [self._dequantize(self._quantized_key_cache[layer_idx]), self.key_cache[layer_idx]]
189:                     values_to_return = [self._dequantize(self._quantized_value_cache[layer_idx]), self.value_cache[layer_idx]]
190:                     keys_to_return = torch.cat(keys_to_return, dim=-2)
191:                     values_to_return = torch.cat(values_to_return, dim=-2)
192:                 else:
193:                     self._quantized_key_cache.append(self._quantize(key_states.contiguous(), axis=self.axis_key, nbits=nbits_key))
194:                     self._quantized_value_cache.append(self._quantize(value_states.contiguous(), axis=self.axis_value, nbits=nbits_value))
195:                     self.key_cache.append(torch.zeros(0, dtype=key_states.dtype, device=key_states.device))
196:                     self.value_cache.append(torch.zeros(0, dtype=key_states.dtype, device=key_states.device))
197:                     keys_to_return, values_to_return = key_states, value_states
198:             else:
199:                 dequant_key = self._dequantize(self._quantized_key_cache[layer_idx])
200:                 dequant_value = self._dequantize(self._quantized_value_cache[layer_idx])
201:                 keys_to_return = [dequant_key, self.key_cache[layer_idx], key_states]
202:                 values_to_return = [dequant_value, self.value_cache[layer_idx], value_states]
203: 
204:                 keys_to_return = torch.cat(keys_to_return, dim=-2)
205:                 values_to_return = torch.cat(values_to_return, dim=-2)
206:                 if (
207:                     self.key_cache[layer_idx].dim() == 4
208:                     and self.key_cache[layer_idx].shape[-2] + 1 >= self.residual_length
209:                 ):
210:                     self._quantized_key_cache[layer_idx] = self._quantize(keys_to_return.contiguous(), axis=self.axis_key, nbits=nbits_key)
211:                     self._quantized_value_cache[layer_idx] = self._quantize(
212:                         values_to_return.contiguous(), axis=self.axis_value, nbits=nbits_value
213:                     )
214:                     self.key_cache[layer_idx] = torch.zeros(0, dtype=key_states.dtype, device=key_states.device)
215:                     self.value_cache[layer_idx] = torch.zeros(0, dtype=key_states.dtype, device=key_states.device)
216:                 else:
217:                     self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=-2)
218:                     self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=-2)
219:         else: # per head quant
220:             assert key_states.dim() == 4 and value_states.dim() == 4
221:             key_states, value_states = key_states.transpose(0, 1).contiguous(), value_states.transpose(0, 1).contiguous()
222:             assert key_states.shape[0]  == value_states.shape[0]
223:             if key_states.shape[0] != len(self.per_head_config[layer_idx]):
224:                 raise ValueError("Number of heads in the model does not match the number of heads in the per_head_config, you may loaded a invalid config file.")
225:             keys_to_return, values_to_return = [], []
226:             if len(self.key_cache) == layer_idx:
227:                 self._quantized_key_cache.append([])
228:                 self._quantized_value_cache.append([])
229:                 self.key_cache.append([])
230:                 self.value_cache.append([])
231:                 for head_idx, config in self.per_head_config[layer_idx].items():
232:                     if self.force_quant:
233:                         if self.residual_length:
234:                             tokens_to_keep = key_states.shape[-2] % self.residual_length
235:                             self._quantized_key_cache[layer_idx].append(self._quantize(key_states[head_idx][..., :-tokens_to_keep, :], axis=self.axis_key, nbits=config['nbits_key']))
236:                             self._quantized_value_cache[layer_idx].append(self._quantize(value_states[head_idx][..., :-tokens_to_keep, :], axis=self.axis_value, nbits=config['nbits_value']))
237:                             self.key_cache[layer_idx].append(key_states[head_idx][..., -tokens_to_keep:, :])
238:                             self.value_cache[layer_idx].append(value_states[head_idx][..., -tokens_to_keep:, :])
239:                         else:
240:                             self._quantized_key_cache[layer_idx].append(self._quantize(key_states[head_idx], axis=self.axis_key, nbits=config['nbits_key']))
241:                             self._quantized_value_cache[layer_idx].append(self._quantize(value_states[head_idx], axis=self.axis_value, nbits=config['nbits_value']))
242:                             self.key_cache[layer_idx].append(torch.zeros(0, dtype=key_states.dtype, device=key_states.device))
243:                             self.value_cache[layer_idx].append(torch.zeros(0, dtype=key_states.dtype, device=key_states.device))
244:                         keys_to_return.append(torch.cat([self._dequantize(self._quantized_key_cache[layer_idx][-1]), self.key_cache[layer_idx][-1]], dim=-2))
245:                         values_to_return.append(torch.cat([self._dequantize(self._quantized_value_cache[layer_idx][-1]), self.value_cache[layer_idx][-1]], dim=-2))
246:                     else:
247:                         self._quantized_key_cache[layer_idx].append(self._quantize(key_states[head_idx].contiguous(), axis=self.axis_key, nbits=config['nbits_key']))
248:                         self._quantized_value_cache[layer_idx].append(self._quantize(value_states[head_idx].contiguous(), axis=self.axis_value, nbits=config['nbits_value']))
249:                         self.key_cache[layer_idx].append(torch.zeros(0, dtype=key_states.dtype, device=key_states.device))
250:                         self.value_cache[layer_idx].append(torch.zeros(0, dtype=key_states.dtype, device=key_states.device))
251:                         keys_to_return.append(key_states[head_idx])
252:                         values_to_return.append(value_states[head_idx])
253:             else:
254:                 for head_idx, config in self.per_head_config[layer_idx].items():
255:                     dequant_key = self._dequantize(self._quantized_key_cache[layer_idx][head_idx])
256:                     dequant_value = self._dequantize(self._quantized_value_cache[layer_idx][head_idx])
257:                     keys_to_return.append(torch.cat([dequant_key, self.key_cache[layer_idx][head_idx], key_states[head_idx]], dim=-2))
258:                     values_to_return.append(torch.cat([dequant_value, self.value_cache[layer_idx][head_idx], value_states[head_idx]], dim=-2))
259:                     if (
260:                         self.key_cache[layer_idx][head_idx].dim() == 3
261:                         and self.key_cache[layer_idx][head_idx].shape[-2] + 1 >= self.residual_length
262:                     ):
263:                         self._quantized_key_cache[layer_idx][head_idx] = self._quantize(keys_to_return[head_idx].contiguous(), axis=self.axis_key, nbits=config['nbits_key'])
264:                         self._quantized_value_cache[layer_idx][head_idx] = self._quantize(values_to_return[head_idx].contiguous(), axis=self.axis_value, nbits=config['nbits_value'])
265:                         self.key_cache[layer_idx][head_idx] = torch.zeros(0, dtype=key_states.dtype, device=key_states.device)
266:                         self.value_cache[layer_idx][head_idx] = torch.zeros(0, dtype=key_states.dtype, device=key_states.device)
267:                     else:
268:                         self.key_cache[layer_idx][head_idx] = torch.cat([self.key_cache[layer_idx][head_idx], key_states[head_idx]], dim=-2)
269:                         self.value_cache[layer_idx][head_idx] = torch.cat([self.value_cache[layer_idx][head_idx], value_states[head_idx]], dim=-2)
270:             keys_to_return, values_to_return = torch.stack(keys_to_return), torch.stack(values_to_return)
271:             keys_to_return, values_to_return = keys_to_return.transpose(0, 1).contiguous(), values_to_return.transpose(0, 1).contiguous()
272:         return keys_to_return, values_to_return
273: 
274:     def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
275:         """Returns the sequence length of the cached states. A layer index can be optionally passed."""
276:         if len(self.key_cache) <= layer_idx:
277:             return 0
278:         # since we cannot get the seq_length of each layer directly and rely on `_seen_tokens` which is
279:         # updated every "layer_idx" == 0, this is a hack to get the actual seq_length for the given layer_idx
280:         # this part of code otherwise fails when used to verify attn_weight shape in some models
281:         return self._seen_tokens if layer_idx == 0 else self._seen_tokens - 1
282: 
283:     def _quantize(self, tensor, axis, nbits):
284:         """Quantizes a key/value using a defined quantization method."""
285:         raise NotImplementedError("Make sure to implement `_quantize` in a subclass.")
286: 
287:     def _dequantize(self, q_tensor):
288:         """Dequantizes back the tensor that was quantized by `self._quantize()`"""
289:         raise NotImplementedError("Make sure to implement `_dequantize` in a subclass.")
290: 
291: class FlexibleQuantoQuantizedCache(FlexibleQuantizedCache):
292:     """
293:     Quantized Cache class that uses `quanto` as a backend to perform quantization. Current implementation supports `int2` and `int4` dtypes only.
294: 
295:     Parameters:
296:         cache_config (`QuantizedCacheConfig`):
297:             A configuration containing all the arguments to be used by the quantizer, including axis, qtype and group size.
298: 
299:     Example:
300: 
301:         ```python
302:         >>> # Run pip install quanto first if you don't have it yet
303:         >>> from transformers import AutoTokenizer, AutoModelForCausalLM, QuantoQuantizedCache, QuantizedCacheConfig
304: 
305:         >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
306:         >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
307: 
308:         >>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")
309: 
310:         >>> # Prepare a cache class and pass it to model's forward
311:         >>> cache_config = QuantizedCacheConfig(nbits=4)
312:         >>> past_key_values = QuantoQuantizedCache(cache_config=cache_config)
313:         >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
314:         >>> outputs.past_key_values # access cache filled with key/values from generation
315:         QuantoQuantizedCache()
316:         ```
317:     """
318: 
319:     def __init__(self, cache_config: CacheConfig) -> None:
320:         super().__init__(cache_config)
321: 
322:         if is_optimum_quanto_available():
323:             from optimum.quanto import MaxOptimizer, qint2, qint4
324:         # elif is_quanto_available():
325:         #     logger.warning_once(
326:         #         "Importing from quanto will be deprecated in v4.47. Please install optimum-quanto instead `pip install optimum-quanto`"
327:         #     )
328:         #     quanto_version = version.parse(importlib.metadata.version("quanto"))
329:         #     if quanto_version < version.parse("0.2.0"):
330:         #         raise ImportError(
331:         #             f"You need quanto package version to be greater or equal than 0.2.0 to use `QuantoQuantizedCache`. Detected version {quanto_version}. "
332:         #             f"Since quanto will be deprecated, please install optimum-quanto instead with `pip install -U optimum-quanto`"
333:         #         )
334:         #     from quanto import MaxOptimizer, qint2, qint4, qint8
335: 
336:         if self.nbits not in [2, 4, 8]:
337:             raise ValueError(f"`nbits` for `quanto` backend has to be one of [`2`, `4`, `8`] but got {self.nbits}")
338: 
339:         if self.axis_key not in [0, -1]:
340:             raise ValueError(f"`axis_key` for `quanto` backend has to be one of [`0`, `-1`] but got {self.axis_key}")
341: 
342:         if self.axis_value not in [0, -1]:
343:             raise ValueError(
344:                 f"`axis_value` for `quanto` backend has to be one of [`0`, `-1`] but got {self.axis_value}"
345:             )
346: 
347:         # self.qtype = qint4 if self.nbits == 4 else qint2
348:         self.optimizer = MaxOptimizer()  # hardcode as it's the only one for per-channel quantization
349:     
350:     def get_qtype(self, nbits):
351:         if is_optimum_quanto_available():
352:             from optimum.quanto import qint2, qint4, qint8
353:         # elif is_quanto_available():
354:         #     from quanto import qint2, qint4, qint8
355:         if nbits == 2:
356:             return qint2
357:         elif nbits == 4:
358:             return qint4
359:         elif nbits == 8:
360:             return qint8
361: 
362:     def _quantize(self, tensor, axis, nbits):
363:         # We have two different API since in optimum-quanto, we don't use AffineQuantizer anymore
364:         if is_optimum_quanto_available():
365:             from optimum.quanto import quantize_weight
366: 
367:             qtensor = quantize_weight(tensor, self.get_qtype(nbits), axis, self.q_group_size)
368:             return qtensor
369:         # elif is_quanto_available():
370:         #     logger.warning_once(
371:         #         "Importing from quanto will be deprecated in v4.47. Please install optimum-quanto instead `pip install optimum-quanto`"
372:         #     )
373:         #     from quanto import AffineQuantizer
374: 
375:         #     scale, zeropoint = self.optimizer(tensor, nbits, axis, self.q_group_size)
376:         #     qtensor = AffineQuantizer.apply(tensor, self.get_qtype(nbits), axis, self.q_group_size, scale, zeropoint)
377: 
378:         return qtensor
379: 
380:     def _dequantize(self, qtensor):
381:         return qtensor.dequantize()
382: 
383: class FlexibleHQQQuantizedCache(FlexibleQuantizedCache):
384:     """
385:     Quantized Cache class that uses `HQQ` as a backend to perform quantization. Current implementation supports `int2`, `int4`, `int8` dtypes.
386: 
387:     Parameters:
388:         cache_config (`QuantizedCacheConfig`):
389:             A configuration containing all the arguments to be used by the quantizer, including axis, qtype and group size.
390: 
391:     Example:
392: 
393:         ```python
394:         >>> # Run pip install hqq first if you don't have it yet
395:         >>> from transformers import AutoTokenizer, AutoModelForCausalLM, HQQQuantizedCache, QuantizedCacheConfig
396: 
397:         >>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
398:         >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
399: 
400:         >>> inputs = tokenizer(text="My name is Qwen2", return_tensors="pt")
401: 
402:         >>> # Prepare a cache class and pass it to model's forward
403:         >>> cache_config = QuantizedCacheConfig(nbits=4, axis_key=1, axis_value=1)
404:         >>> past_key_values = HQQQuantizedCache(cache_config=cache_config)
405:         >>> outputs = model(**inputs, past_key_values=past_key_values, use_cache=True)
406:         >>> outputs.past_key_values # access cache filled with key/values from generation
407:         HQQQuantizedCache()
408:         ```
409:     """
410: 
411:     def __init__(self, cache_config: CacheConfig) -> None:
412:         super().__init__(cache_config)
413:         if self.nbits not in [1, 2, 3, 4, 8]:
414:             raise ValueError(
415:                 f"`nbits` for `HQQ` backend has to be one of [`1`, `2`, `3`, `4`, `8`] but got {self.nbits}"
416:             )
417: 
418:         if self.axis_key not in [0, 1]:
419:             raise ValueError(f"`axis_key` for `HQQ` backend has to be one of [`0`, `1`] but got {self.axis_key}")
420: 
421:         if self.axis_value not in [0, 1]:
422:             raise ValueError(f"`axis_value` for `HQQ` backend has to be one of [`0`, `1`] but got {self.axis_value}")
423: 
424:         self.quantizer = HQQQuantizer
425: 
426:     def _quantize(self, tensor, axis, nbits):
427:         qtensor, meta = self.quantizer.quantize(
428:             tensor,
429:             axis=axis,
430:             device=self.device,
431:             compute_dtype=self.compute_dtype,
432:             nbits=nbits,
433:             group_size=self.q_group_size,
434:             channel_wise=True,
435:         )
436:         meta["compute_dtype"] = self.compute_dtype
437:         self.quantizer.cuda(qtensor, meta=meta, device=self.device)  # Move to device and cast to dtype
438:         return qtensor, meta
439: 
440:     def _dequantize(self, qtensor):
441:         quant_tensor, meta = qtensor
442:         tensor = self.quantizer.dequantize(quant_tensor, meta)
443:         return tensor
444: 
445: class FlexibleVanillaQuantizedCache(FlexibleQuantizedCache):
446:     def __init__(self, cache_config: CacheConfig) -> None:
447:         super().__init__(cache_config)
448: 
449:         if self.axis_key not in [0, 1]:
450:             raise ValueError(f"`axis_key` for `Vanilla` backend has to be one of [`0`, `1`] but got {self.axis_key}")
451: 
452:         if self.axis_value not in [0, 1]:
453:             raise ValueError(f"`axis_value` for `Vanilla` backend has to be one of [`0`, `1`] but got {self.axis_value}")
454:         
455:         self.quantilizers = {}
456: 
457:     def _quantize(self, tensor, axis, nbits):
458:         if (nbits, axis) not in self.quantilizers:
459:             self.quantilizers[(nbits, axis)] = VanillaQuantizer(nbits, self.asym, self.compute_dtype)
460:         quantilizer = self.quantilizers[(nbits, axis)]        
461:         return quantilizer.quantize(tensor, self.q_group_size, axis)
462:     
463:     def _dequantize(self, qtensor):
464:         return qtensor.dequantize()
465:     
