1: # KVTuner: Sensitivity-Aware Layer-wise Mixed Precision KV Cache Quantization for Efficient and Nearly Lossless LLM Inference
2: 
3: Official implementation of the ICML25 paper: KVTuner: Sensitivity-Aware Layer-wise Mixed Precision KV Cache Quantization for Efficient and Nearly Lossless LLM Inference
4: 
5: ## Installation
6: ```sh
7: cd flexible_quant
8: pip install -e .
9: ```
10: 
11: ## Run Example codes
12: ```sh
13: python3 flexible_quant_example.py
14: ```
15: Then you will run a simple example from `GSM8K` with `meta-llama/Meta-Llama-3-8B` and `KV4` quantization.
16: 
17: Change line 17 in `flexible_quant_example.py` to run different quantization methods.
18: 
19: ### Run GSM8K
20: ```bash
21: cd benchmarks
22: # GSM8K K8V4 with KiVi quantization scheme
23: python3 example_gsm8k_cot_manyshot.py --model_name="mistralai/Mistral-7B-Instruct-v0.2" --k_bits=8 --v_bits=4 --residual_length=32 --group_size=32 --axis_key=1 --axis_value=0
24: # GSM8K K8V4 with Per-Token quantization scheme
25: python3 example_gsm8k_cot_manyshot.py --model_name="mistralai/Mistral-7B-Instruct-v0.2" --k_bits=8 --v_bits=4 --residual_length=0 --group_size=-1 --axis_key=0 --axis_value=0
26: ```
27: 
28: ##### Parameters
29: 
30: - `model_name`: the model name from Hugging Face model hub.
31: - `nshots`: the number of shots for the few-shot inference.
32: - `k_bits`: the precision for the key.
33: - `v_bits`: the precision for the value.
34: - `asym`: whether to use asymmetric quantization.
35: - `residual_length`: the length of the residual tokens which are not quantized. must be a multiple of `group_size`, use 0 for per-token quantization.
36: - `group_size`: the size of the group for quantization, use -1 for per-token quantization.
37: - `axis_key`: the axis for key quantization, 0 for per-token quantization, 1 for per-channel quantization.
38: - `axis_value`: the axis for value quantization, 0 for per-token quantization, 1 for per-channel quantization.
39: 
40: 
41: #### Run LongBench
42: ```sh
43: cd benchmarks
44: PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True python3 pred_longbench.py
45: ```
46: 
47: Same parameters as GSM8K.
48: 
49: #### Run lm-eval
50: 
51: This repo provides a modified version of `lm-eval` to support the quantization evaluation.
52: 
53: Refer to `lm-evaluation-harness-X/lm_eval/models/huggingface_quant.py`
54: 
55: ## Use `FlexibleQuantizedCache` in your code
56: ```python
57: # Define your model
58: from transformers import AutoTokenizer, AutoModelForCausalLM, 
59: model_name = 'meta-llama/Meta-Llama-3-8B'
60: model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16).cuda()
61: tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False, trust_remote_code=True)
62: 
63: # Define the cache
64: from flexible_quant.flexible_quantized_cache import FlexibleQuantizedCacheConfig, FlexibleVanillaQuantizedCache
65: cache_config = FlexibleQuantizedCacheConfig(nbits_key=4, nbits_value=4, asym=True, axis_key=0, axis_value=0, device='cuda', q_group_size=-1)
66: # By default we use FlexibleVanillaQuantizedCache, you can switch to FlexibleHQQQuantizedCache and FlexibleQuantoQuantizedCache
67: past_key_values = FlexibleVanillaQuantizedCache(cache_config=cache_config)
68: 
69: # Prompt and generate
70: prompt = '''The quick brown fox jumps over the lazy dog.'''
71: inputs = tokenizer(prompt, return_tensors="pt").input_ids.cuda()
72: outputs = model.generate(inputs, past_key_values=past_key_values, use_cache=True, max_new_tokens=256)
73: ```
74: 
75: 
76: ## FlexibleQuantizedCacheConfig
77: 
78: ```python
79: """
80: Configuration for flexible quantized cache.
81: 
82: Attributes:
83:     backend (str): Backend for quantization. Options: "quanto", "hqq", "vanilla".
84:     nbits (Optional[int]): Precision for both key and value. Used if `nbits_key` and `nbits_value` are not set.
85:                             For per-layer or per-head quantization, set `nbits` to -1.
86:     nbits_key (Optional[int]): Precision for key quantization. For per-layer or per-head quantization, set to -1.
87:     nbits_value (Optional[int]): Precision for value quantization. For per-layer or per-head quantization, set to -1.
88:     axis_key (Optional[int]): Axis for key quantization. In Vanilla mode:
89:                                 - 0: Per-token quantization
90:                                 - 1: Per-channel quantization
91:     axis_value (Optional[int]): Axis for value quantization. In Vanilla mode:
92:                                 - 0: Per-token quantization
93:                                 - 1: Per-channel quantization
94:     asym (Optional[bool]): Whether to use asymmetric quantization. Works only for Vanilla mode.
95:     q_group_size (Optional[int]): Group size for quantization. Use -1 for per-token quantization.
96:     residual_length (Optional[int]): Length of residual tokens that are not quantized.
97:                                         Must be a multiple of `q_group_size`. Use 0 for per-token quantization.
98:     compute_dtype (Optional[torch.dtype]): Compute dtype for the model. Default: `torch.float16`.
99:     device (Optional[str]): Device for the cache. Default: `"cpu"`.
100:     force_quant (Optional[bool]): Whether to quantize the cache during the pre-filling stage.
101:     per_layer_quant (Optional[bool]): Whether to use per-layer quantization.
102:     per_layer_config (Optional[Dict[str, Any]]): If `per_layer_quant` is True, provides the quantization config
103:                                                     for each layer. Alternatively, use `per_layer_config_path`.
104:     per_layer_config_path (Optional[str]): Path to the quantization config for each layer.
105:                                             Used if `per_layer_quant` is True.
106:     per_head_quant (Optional[bool]): Whether to use per-head quantization.
107:     per_head_config (Optional[Dict[str, Any]]): If `per_head_quant` is True, provides the quantization config
108:                                                 for each head. Alternatively, use `per_head_config_path`.
109:     per_head_config_path (Optional[str]): Path to the quantization config for each head.
110:                                             Used if `per_head_quant` is True.
111: """
112: ```
113: 
114: ### Example for per_layer_config
115: ```python
116: per_layer_config = {
117:     {n_layer}: {
118:         'nbits_key': 4,
119:         'nbits_value': 4,
120:     },
121:     # ...
122: ```
123: 
124: ### Example for per_head_config
125: ```python
126: per_head_config = {
127:     {n_layer}: {
128:         {head_idx}: {
129:             'nbits_key': 4,
130:             'nbits_value': 4,
131:         },
132:         # ...
133:     },
134:     # ...
135: ```
136: 
137: ## Citation
138: ```bibtex
139: @inproceedings{
140: li2025kvtuner,
141: title={{KVT}uner: Sensitivity-Aware Layer-Wise Mixed-Precision {KV} Cache Quantization for Efficient and Nearly Lossless {LLM} Inference},
142: author={Xing Li and Zeyu XING and Yiming Li and Linping Qu and Hui-Ling Zhen and Yiwu Yao and Wulong Liu and Sinno Jialin Pan and Mingxuan Yuan},
143: booktitle={Forty-second International Conference on Machine Learning},
144: year={2025},
145: url={https://openreview.net/forum?id=zDwipF6h06}
146: }
147: ```
