1: import warnings
2: warnings.filterwarnings("ignore")
3: import torch
4: import random
5: import argparse
6: import torch
7: import optuna
8: import lm_eval
9: from lm_eval.models.huggingface_quant import HFLM_Quant
10: import logging
11: import sys
12: 
13: # For reproducibility
14: random.seed(0)
15: torch.manual_seed(0)
16: CACHE_DIR = "./models_storage"
17: 
18: 
19: 
20: LAYER_GROUPING_CONFIG = {
21:     'Meta-Llama-3.1-8B-Instruct': {
22:         'per-token-asym': [[0], [1, 2, 3, 4, 7, 13, 18, 25, 27, 31], [5, 6, 12, 21, 26, 28], [8, 9, 10, 11, 14, 15, 16, 17, 20, 30], [19, 22], [23, 24, 29]],
23:         'per-channel-asym': [[0], [1, 2, 3, 7, 29, 31], [4, 25, 27], [5, 21, 23, 24], [6, 8, 9, 10, 11, 12, 14, 15, 16, 18, 19, 20, 22, 26, 28, 30], [13, 17]],
24:     },
25:     'Mistral-7B-Instruct-v0.3': {
26:         'per-token-asym': [[0], [1, 2], [3, 4, 23, 31], [5, 6], [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30]],
27:         'per-channel-asym': [[0, 1, 31], [2, 3, 4], [6, 27, 29], [7, 8, 10, 18], [9, 14], [5, 21, 22, 23, 24, 25, 26, 28, 30], [11, 12, 13, 15, 17, 19, 20], [16]],
28:     },
29:     'Qwen2.5-3B-Instruct': {
30:         'per-token-asym': [[0], [1, 3, 4, 5, 6, 8, 9, 12, 13, 15, 20], [2, 14, 23, 35], [7, 11, 16, 25, 28, 32], [10, 19, 24, 26, 33], [17, 30, 31, 34], [21, 22], [18, 27, 29]],
31:         'per-channel-asym': [[0, 1], [2, 4], [34, 35], [3, 6, 11, 13, 23], [5, 7, 25, 32, 33], [8, 16, 18, 21, 22, 24, 26, 27, 30], [9, 10, 14, 15, 17, 19, 20, 29, 31], [12, 28]],
32:     },
33:     'Qwen2.5-7B-Instruct': {
34:         'per-token-asym': [[0], [1, 2, 4, 5, 25], [6, 19], [7, 10, 11, 15, 23], [8, 24], [9, 12, 16, 17, 18, 21, 22, 26], [14, 20], [3, 13, 27]],
35:         'per-channel-asym': [[0, 2], [1, 3], [4, 5, 12, 22, 23, 24, 25], [7, 9, 10, 13, 14, 16, 18, 19, 20, 21, 27], [8, 26], [11, 15, 17], [6]],
36:     },
37:     'Qwen2.5-14B-Instruct': {
38:         'per-token-asym': [[0, 1, 2, 6, 11, 12, 19, 23, 24, 25, 41], [3, 4, 5, 8], [7, 10, 15], [9, 13, 14, 31, 38, 39], [16, 17, 18, 20, 21, 27, 28, 30, 32, 33, 34, 35, 36, 37, 40, 42, 43, 44, 46, 47], [22, 26, 29, 45]],
39:         'per-channel-asym': [[0, 2], [1, 3, 4], [5, 6, 8, 9, 12], [7, 10, 13, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 44, 45, 46, 47], [11, 25, 41, 42], [14, 39, 40, 43], [22, 34]],
40:     },
41:     'Qwen2.5-32B-Instruct': {
42:         'per-token-asym': [[0, 2, 11, 12, 15, 33, 54, 57], [1, 5, 7, 8, 9, 10, 13, 14, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 55, 56, 58, 59, 60, 61, 62, 63], [3, 4], [6, 16]],
43:         'per-channel-asym': [[0, 1, 2, 3, 4], [11], [5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 32], [13, 15, 17, 22, 24, 25, 29, 30, 31, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62], [63]]
44:     }
45: }
46: 
47: SPECIAL_LAYERS = {
48:     'Meta-Llama-3.1-8B-Instruct': {
49:         'per-token-asym': {
50:             (0,): ['KV8', 'K4V8', 'KV4', 'K4V2', 'KV2'],
51:         },
52:         'per-channel-asym': {
53:             (0,): ['KV8', 'K4V8', 'KV4', 'K2V4', 'KV2'],
54:             (1, 2, 3, 7, 29, 31): ['KV8', 'K4V8', 'KV4', 'K4V2', 'KV2'],
55:         },
56:     },
57:     'Mistral-7B-Instruct-v0.3': {
58:         'per-token-asym': {
59:             (0,): ['KV8', 'K4V8', 'KV4', 'K2V4', 'KV2'],
60:         },
61:         'per-channel-asym': {
62:             # (0,): ['KV8', 'K4V8', 'KV4', 'K2V4', 'KV2'],
63:             (0, 1, 31): ['KV8', 'K4V8', 'KV4', 'K2V4', 'KV2'], # fix: grouping
64:             (2, 3, 4, 6, 7, 8, 9, 10, 14, 18, 27, 29): ['KV8', 'K4V8', 'KV4', 'K4V2', 'KV2'],
65:         },
66:     },
67:     'Qwen2.5-3B-Instruct': {
68:         'per-token-asym': {
69:             (0,): ['KV8', 'K8V4', 'K8V2', 'K4V2', 'KV2'],
70:             (18, 27, 29): ['KV8', 'K8V4', 'K8V2', 'KV4', 'K4V2', 'KV2'],
71:         },
72:         'per-channel-asym': {
73:             (0, 1, 2, 4, 34, 35): ['KV8', 'K4V8', 'KV4', 'K2V4', 'KV2'],
74:             (3, 6, 11, 13, 23): ['KV8', 'K4V8', 'KV4', 'K4V2', 'KV2'],
75:         },
76:     },
77:     'Qwen2.5-7B-Instruct': {
78:         'per-token-asym': {
79:             (0,): ['KV8', 'K8V4', 'K8V2', 'K4V2', 'KV2'],
80:             (3, 13, 27): ['KV8', 'K8V4', 'K8V2', 'KV4', 'K4V2', 'KV2'],
81:         },
82:         'per-channel-asym': {
83:             (0, 1, 2, 3): ['KV8', 'K4V8', 'KV4', 'K2V4', 'KV2'],
84:             (6,): ['KV8', 'K4V8', 'KV4', 'K4V2', 'KV2'],
85:         },
86:     },
87:     'Qwen2.5-14B-Instruct': {
88:         'per-token-asym': {
89:             # no layers listed
90:         },
91:         'per-channel-asym': {
92:             (0, 1, 2, 3, 4): ['KV8', 'K4V8', 'KV4', 'K2V4', 'KV2'],
93:             (5, 6, 8, 9, 12): ['KV8', 'K4V8', 'KV4', 'K4V2', 'KV2'],
94:         },
95:     },
96:     'Qwen2.5-32B-Instruct': {
97:         'per-token-asym': {
98:             # no layers listed
99:         },
100:         'per-channel-asym': {
101:             (0, 1, 2, 3, 4, 11): ['KV8', 'K4V8', 'KV4', 'K2V4', 'KV2'],
102:             (5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 19, 20, 21, 23, 26, 27, 28, 32): ['KV8', 'K4V8', 'KV4', 'K4V2', 'KV2'],
103:             (63,): ['KV8', 'K8V4', 'KV4', 'K2V4', 'KV2'],
104:         },
105:     },
106: }
107: 
108: 
109: TOT_LAYER = {
110:     'Meta-Llama-3.1-8B-Instruct': 32,
111:     'Mistral-7B-Instruct-v0.3': 32,
112:     'Qwen2.5-3B-Instruct': 36,
113:     'Qwen2.5-7B-Instruct': 28,
114:     'Qwen2.5-14B-Instruct': 48,
115:     'Qwen2.5-32B-Instruct': 64,
116: }
117: 
118: STANDARD_KV_QUANT_CONFIG = ['KV8', 'K8V4', 'KV4', 'K4V2', 'KV2']
119: 
120: global_args = {}
121: model = None
122: tokenizer = None
123: dataset = None
124: 
125: num_fewshots = None
126: limit = None
127: device = None
128: 
129: quant_scheme = None
130: max_per_layer_scale = None
131: 
132: current_layer_grouping = []
133: current_special_layers = {}
134: current_grouping_quant_template = []
135: current_tot_layers = -1
136: debug_constraint = False
137: 
138: def parse_args(args=None):
139:     parser = argparse.ArgumentParser()
140:     # parser.add_argument('--model_name', type=str, default="meta-llama/Llama-2-7b-hf")
141:     # parser.add_argument('--model_name', type=str, default="Qwen/Qwen2.5-3B-Instruct-AWQ")
142:     # parser.add_argument('--model_name', type=str, default="Qwen/Qwen2.5-7B-Instruct")
143:     # parser.add_argument('--model_name', type=str, default="mistralai/Mistral-7B-Instruct-v0.3")
144:     parser.add_argument('--model_name', type=str, default="meta-llama/Meta-Llama-3.1-8B-Instruct")
145:     # parser.add_argument('--residual_length', type=int, default=0)
146:     # parser.add_argument('--group_size', type=int, default=-1)
147:     parser.add_argument('--quant_scheme', type=str, default="per-token-asym") # per-token-asym or per-channel-asym
148:     parser.add_argument('--asym', type=bool, default=True)
149:     # in Vanilla, 0 for per-token, 1 for per-channel, we have to use per-channel there as residual_length is 0
150:     parser.add_argument('--axis_key', type=int, default=0)
151:     parser.add_argument('--axis_value', type=int, default=0)
152:     parser.add_argument('--limit', type=int, default=20)
153:     parser.add_argument('--num_fewshots', type=int, default=4)
154:     parser.add_argument('--max_per_layer_scale', type=str, default='8')
155:     parser.add_argument('--n_trials', type=int, default=100)
156:     parser.add_argument('--device', type=str, default="cuda")
157:     parser.add_argument('--debug_constraint', default=False, action='store_true')
158:     return parser.parse_args(args)
159: 
160: 
161: def parse_quant_config(quant_config: str):
162:     if len(quant_config) == 3:
163:         precision = int(quant_config[2])
164:         return {'nbits_key': precision, 'nbits_value': precision}
165:     precision_key = int(quant_config[1])
166:     precision_value = int(quant_config[3])
167:     return {'nbits_key': precision_key, 'nbits_value': precision_value}
168: 
169: def prepare_layer_grouping_config(model_name: str, quant_scheme: str):
170:     model_name = model_name.split('/')[-1]
171:     model_name = model_name.replace('-AWQ', '') # Qwen2.5-3B-Instruct-AWQ -> Qwen2.5-3B-Instruct
172:     global current_layer_grouping, current_special_layers, current_grouping_quant_template, current_tot_layers
173:     current_layer_grouping = LAYER_GROUPING_CONFIG[model_name][quant_scheme]
174:     current_special_layers = SPECIAL_LAYERS[model_name][quant_scheme]
175:     current_tot_layers = TOT_LAYER[model_name]
176:     # check if current_special_layers breaks the current_layer_grouping
177:     for group in current_layer_grouping:
178:         group_quant_template = STANDARD_KV_QUANT_CONFIG
179:         for layer in group:
180:             for special_layer in current_special_layers.keys():
181:                 if layer in special_layer:
182:                     group_quant_template = current_special_layers[special_layer]
183:                     for other_layer in group:
184:                         if not other_layer in special_layer:
185:                             raise ValueError("Special layer {} breaks the layer grouping for model {}, quant scheme {}".format(special_layer, model_name, quant_scheme))
186:         if debug_constraint:
187:             group_quant_template = [i for i in group_quant_template if i != 'KV2'] # remove KV2
188:         current_grouping_quant_template.append(group_quant_template)
189: 
190: def run_gsm8k(per_layer_config: dict, model_name: str, num_fewshots: int, limit: int, device: str):
191:     results = lm_eval.simple_evaluate(
192:         model='hf-quant',
193:         model_args={
194:             'pretrained': model_name,
195:             'nbits_key': -1,
196:             'nbits_value': -1,
197:             'residual_length': 32 if quant_scheme == 'per-channel-asym' else 0,
198:             'q_group_size': 32 if quant_scheme == 'per-channel-asym' else -1,
199:             'asym': True,
200:             'axis_key': 1 if quant_scheme == 'per-channel-asym' else 0,
201:             'axis_value': 0,
202:             'dtype': torch.bfloat16,
203:             'force_quant': False,
204:             'per_layer_quant': True,
205:             'per_layer_config': per_layer_config,
206:             'quantilizer': 'vanilla',
207:             'device_map': 'auto',
208:             'parallelize': True,
209:         },
210:         tasks=["gsm8k"],
211:         num_fewshot=num_fewshots,
212:         limit=limit,
213:         # device=device
214:     )
215:     print(results['results']['gsm8k']['exact_match,flexible-extract'])
216:     return float(results['results']['gsm8k']['exact_match,flexible-extract'])
217: 
218: 
219: def build_per_layer_config(config_list: int):
220:     per_layer_config = {}
221:     tot_scale = 0
222:     for i, config in enumerate(config_list):
223:         layers = current_layer_grouping[i]
224:         quant_config = parse_quant_config(current_grouping_quant_template[i][config])
225:         for layer in layers:
226:             per_layer_config[layer] = quant_config
227:         tot_scale += (quant_config['nbits_key'] + quant_config['nbits_value']) * len(layers)
228:     tot_scale /= current_tot_layers * 2
229:     return per_layer_config, tot_scale
230: 
231: 
232: def objective(trial):    
233:     config_list = []
234:     for i in range(0, len(current_layer_grouping)):
235:         config_current_layer = trial.suggest_int('group_{}'.format(i), 0, len(current_grouping_quant_template[i]) - 1)
236:         config_list.append(config_current_layer)
237:     
238:     per_layer_config, tot_scale = build_per_layer_config(config_list)
239:     
240:     # Constraints which are considered feasible if less than or equal to zero.
241:     
242:     c = tot_scale - max_per_layer_scale
243:     print('c = ', c)
244:     
245:     if not debug_constraint:
246:         trial.set_user_attr('constraints', (c, ))
247:     
248:     accuracy = run_gsm8k(per_layer_config,  model, num_fewshots, limit, device)
249:     
250:     c2 = 0.6 - accuracy
251:     
252:     if debug_constraint:
253:         print('c2 = ', c2)
254:         trial.set_user_attr('constraints', (c, c2))
255:     
256:     
257:     return accuracy, tot_scale
258: 
259: def constraints(trial):
260:     return trial.user_attrs["constraints"]
261: 
262: if __name__ == "__main__":
263:     args = parse_args()
264:     model = args.model_name
265:     quant_scheme = args.quant_scheme
266:     max_per_layer_scale = float(args.max_per_layer_scale)
267:     num_fewshots = args.num_fewshots
268:     limit = args.limit
269:     device = args.device
270:     debug_constraint = args.debug_constraint
271:     
272:     
273:     optuna.logging.get_logger("optuna").addHandler(logging.StreamHandler(sys.stdout))
274:     study_name = "OPTUNA_SEARCH_ADAPTIVE_{}_GSM8K_FIRST{}_{}SHOTS_MAXSCALE{}_SCHEME{}".format(model.replace("/", "_"), limit, num_fewshots, max_per_layer_scale, quant_scheme)
275:     storage_name = "sqlite:///{}.db".format(study_name)
276:     sampler = optuna.samplers.NSGAIISampler(constraints_func=constraints)
277:     study = optuna.create_study(directions=["maximize", "minimize"], study_name=study_name, storage=storage_name, sampler=sampler)
278:     
279:     print(args)
280:     print('Preparing layer grouping config...')
281:     prepare_layer_grouping_config(model, quant_scheme)
282:     print('Layer grouping: ', current_layer_grouping)
283:     print('Special layers: ', current_special_layers)
284:     print('Grouping quant template: ', current_grouping_quant_template)
285:     print('Total layers: ', current_tot_layers)
286:     
287:     study.optimize(objective, n_trials=args.n_trials)
