Jakubrd4 commited on
Commit
5428d4e
·
verified ·
1 Parent(s): 7aee0d3

Upload variant_a/scripts/eval_polish_quip.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. variant_a/scripts/eval_polish_quip.py +481 -0
variant_a/scripts/eval_polish_quip.py ADDED
@@ -0,0 +1,481 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Polish LLM Leaderboard evaluation for QuIP# Bielik-Q2-Sharp Variant A.
4
+
5
+ Custom wrapper that loads QuIP# model via quip-sharp and runs eval
6
+ through speakleash/lm-evaluation-harness (polish3 branch).
7
+
8
+ Task groups:
9
+ - polish_generate_few (5-shot generative: polemo2, 8tags, cbd, ppc, psc)
10
+ - polish_mc (5-shot multiple choice variants)
11
+
12
+ Usage:
13
+ python eval_polish_quip.py \
14
+ --model_path /dev/shm/eval/model \
15
+ --tokenizer speakleash/Bielik-11B-v2.3-Instruct \
16
+ --output_dir /dev/shm/eval/results_a \
17
+ --num_fewshot 5
18
+ """
19
+ import sys
20
+ import os
21
+ import json
22
+ import time
23
+ import argparse
24
+
25
+ # Add quip-sharp to path BEFORE other imports
26
+ QUIP_DIR = os.environ.get('QUIP_DIR', '/dev/shm/eval/quip-sharp')
27
+ sys.path.insert(0, QUIP_DIR)
28
+
29
+ import torch
30
+
31
+ # PyTorch 2.10+ changed torch.load default to weights_only=True
32
+ _orig_load = torch.load
33
+ def _compat_load(*a, **kw):
34
+ kw.setdefault('weights_only', False)
35
+ return _orig_load(*a, **kw)
36
+ torch.load = _compat_load
37
+ torch.set_grad_enabled(False)
38
+
39
+ import numpy as np
40
+ from transformers import AutoTokenizer
41
+
42
+ # quip-sharp model loading
43
+ from lib.utils.unsafe_import import model_from_hf_path
44
+
45
+ # lm-eval imports — detect API version
46
+ import lm_eval
47
+ from lm_eval import evaluator
48
+
49
+ # Try new API (v0.4.x) first, fall back to old (v0.3.x)
50
+ try:
51
+ from lm_eval.api.model import LM as BaseLMClass
52
+ API_VERSION = "new"
53
+ except ImportError:
54
+ from lm_eval.base import BaseLM as BaseLMClass
55
+ API_VERSION = "old"
56
+
57
+
58
+ def log(msg):
59
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
60
+
61
+
62
+ class QuIPSharpLM(BaseLMClass):
63
+ """
64
+ lm-eval compatible wrapper for QuIP# quantized models.
65
+
66
+ Supports both old (BaseLM) and new (LM) lm-eval APIs.
67
+ Old API: implements _model_call / _model_generate (batching handled by BaseLM).
68
+ New API: implements loglikelihood / loglikelihood_rolling / generate_until directly.
69
+ """
70
+
71
+ def __init__(self, model_path, tokenizer_path, batch_size=1, max_length=2048):
72
+ super().__init__()
73
+ log(f"Loading QuIP# model from {model_path}...")
74
+ t0 = time.time()
75
+ self._model, _ = model_from_hf_path(model_path, use_cuda_graph=False)
76
+ self._model.eval()
77
+ log(f"Model loaded in {time.time()-t0:.1f}s")
78
+
79
+ self._tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
80
+ if self._tokenizer.pad_token is None:
81
+ self._tokenizer.pad_token = self._tokenizer.eos_token
82
+ log(f"Tokenizer: {tokenizer_path} (vocab={self._tokenizer.vocab_size})")
83
+
84
+ self._batch_size = batch_size
85
+ self._max_length = max_length
86
+ self._device = torch.device("cuda")
87
+
88
+ # ─── Properties (both APIs) ─────────────────────────────────
89
+ @property
90
+ def eot_token_id(self):
91
+ return self._tokenizer.eos_token_id
92
+
93
+ @property
94
+ def max_length(self):
95
+ return self._max_length
96
+
97
+ @property
98
+ def max_gen_toks(self):
99
+ return 64
100
+
101
+ @property
102
+ def batch_size(self):
103
+ return self._batch_size
104
+
105
+ @property
106
+ def device(self):
107
+ return self._device
108
+
109
+ @property
110
+ def rank(self):
111
+ return 0
112
+
113
+ @property
114
+ def world_size(self):
115
+ return 1
116
+
117
+ @property
118
+ def tokenizer_name(self):
119
+ return self._tokenizer.name_or_path
120
+
121
+ def tok_encode(self, string, **kwargs):
122
+ return self._tokenizer.encode(string, add_special_tokens=False)
123
+
124
+ def tok_decode(self, tokens, **kwargs):
125
+ return self._tokenizer.decode(tokens)
126
+
127
+ # ─── Old API (BaseLM) ──────────────────────────────────────
128
+ def _model_call(self, inps):
129
+ """Forward pass — used by BaseLM for loglikelihood."""
130
+ with torch.no_grad():
131
+ return self._model(inps.to(self._device)).logits
132
+
133
+ def _model_generate(self, context, max_length, eos_token_id):
134
+ """Generate — used by BaseLM for generate_until."""
135
+ with torch.no_grad():
136
+ return self._model.generate(
137
+ context.to(self._device),
138
+ max_length=max_length,
139
+ eos_token_id=eos_token_id,
140
+ do_sample=False,
141
+ )
142
+
143
+ # ─── New API (LM v0.4.x) — batched ─────────────────────────
144
+ def _encode_pair(self, ctx, cont):
145
+ """Encode context+continuation, return (full_tokens, cont_length)."""
146
+ ctx_enc = self._tokenizer.encode(ctx, add_special_tokens=False)
147
+ cont_enc = self._tokenizer.encode(cont, add_special_tokens=False)
148
+ full = ctx_enc + cont_enc
149
+ if len(full) > self._max_length:
150
+ full = full[-self._max_length:]
151
+ cont_len = min(len(cont_enc), len(full))
152
+ else:
153
+ cont_len = len(cont_enc)
154
+ return full, cont_len
155
+
156
+ def loglikelihood(self, requests):
157
+ """Compute log-likelihood with length-sorted batching for speed."""
158
+ if API_VERSION == "old":
159
+ return super().loglikelihood(requests)
160
+
161
+ # Prepare all encodings
162
+ encoded = []
163
+ for req in requests:
164
+ ctx, cont = req.args if hasattr(req, 'args') else req
165
+ full, cont_len = self._encode_pair(ctx, cont)
166
+ encoded.append((full, cont_len))
167
+
168
+ total = len(encoded)
169
+ results = [None] * total
170
+ bs = max(self._batch_size, 8) # Use at least 8 for length-sorted batching
171
+ pad_id = self._tokenizer.pad_token_id or 0
172
+
173
+ # Sort by sequence length for efficient batching (less padding waste)
174
+ sorted_indices = sorted(range(total), key=lambda i: len(encoded[i][0]))
175
+
176
+ log(f" loglikelihood: {total} requests, batch_size={bs} (length-sorted)")
177
+ lens = [len(encoded[i][0]) for i in sorted_indices]
178
+ log(f" sequence lengths: min={lens[0]}, max={lens[-1]}, "
179
+ f"median={lens[len(lens)//2]}")
180
+ t0 = time.time()
181
+ processed = 0
182
+
183
+ for batch_start in range(0, total, bs):
184
+ batch_end = min(batch_start + bs, total)
185
+ batch_indices = sorted_indices[batch_start:batch_end]
186
+ batch = [encoded[i] for i in batch_indices]
187
+
188
+ # Pad to same length within batch (minimal waste due to sorting)
189
+ max_len = len(batch[-1][0]) # Last item is longest (sorted)
190
+
191
+ input_ids = torch.full(
192
+ (len(batch), max_len), pad_id,
193
+ dtype=torch.long, device=self._device
194
+ )
195
+ attention_mask = torch.zeros(
196
+ (len(batch), max_len),
197
+ dtype=torch.long, device=self._device
198
+ )
199
+
200
+ for i, (tokens, _) in enumerate(batch):
201
+ # Right-align (pad on left)
202
+ offset = max_len - len(tokens)
203
+ input_ids[i, offset:] = torch.tensor(tokens, dtype=torch.long)
204
+ attention_mask[i, offset:] = 1
205
+
206
+ with torch.no_grad():
207
+ logits = self._model(
208
+ input_ids, attention_mask=attention_mask
209
+ ).logits
210
+
211
+ # Extract log probs for each item (vectorized)
212
+ for i, (tokens, cont_len) in enumerate(batch):
213
+ offset = max_len - len(tokens)
214
+ seq_logits = logits[i, offset:] # unpadded logits
215
+ seq_ids = input_ids[i, offset:]
216
+
217
+ shift_logits = seq_logits[:-1]
218
+ shift_labels = seq_ids[1:]
219
+ log_probs = torch.nn.functional.log_softmax(shift_logits, dim=-1)
220
+
221
+ cont_start = len(tokens) - cont_len - 1
222
+ if cont_start < 0:
223
+ cont_start = 0
224
+
225
+ # Vectorized log prob computation
226
+ cont_labels = shift_labels[cont_start:]
227
+ cont_lps = log_probs[cont_start:]
228
+ cont_log_prob = cont_lps[
229
+ torch.arange(len(cont_labels), device=self._device),
230
+ cont_labels
231
+ ].sum().item()
232
+ is_greedy = (
233
+ shift_logits[cont_start:].argmax(dim=-1) == cont_labels
234
+ ).all().item()
235
+
236
+ results[batch_indices[i]] = (cont_log_prob, is_greedy)
237
+
238
+ processed += len(batch)
239
+ if processed % (bs * 50) < bs:
240
+ elapsed = time.time() - t0
241
+ speed = processed / elapsed
242
+ eta = (total - processed) / speed if speed > 0 else 0
243
+ log(f" loglikelihood: {processed}/{total} "
244
+ f"({speed:.1f} req/s, ETA {eta/60:.1f}min)")
245
+
246
+ elapsed = time.time() - t0
247
+ log(f" loglikelihood done: {total} in {elapsed:.0f}s "
248
+ f"({total/elapsed:.1f} req/s)")
249
+ return results
250
+
251
+ def loglikelihood_rolling(self, requests):
252
+ """Compute full-string log-likelihood (for perplexity)."""
253
+ if API_VERSION == "old":
254
+ return super().loglikelihood_rolling(requests)
255
+
256
+ results = []
257
+ for req in requests:
258
+ text = req.args[0] if hasattr(req, 'args') else req[0]
259
+ enc = self._tokenizer.encode(text, add_special_tokens=False)
260
+ if len(enc) > self._max_length:
261
+ enc = enc[-self._max_length:]
262
+
263
+ inp = torch.tensor([enc], device=self._device)
264
+ with torch.no_grad():
265
+ logits = self._model(inp).logits
266
+
267
+ shift_logits = logits[0, :-1]
268
+ shift_labels = inp[0, 1:]
269
+ log_probs = torch.nn.functional.log_softmax(shift_logits, dim=-1)
270
+ total_lp = sum(
271
+ log_probs[i, shift_labels[i]].item()
272
+ for i in range(len(shift_labels))
273
+ )
274
+ results.append(total_lp)
275
+ return results
276
+
277
+ def generate_until(self, requests):
278
+ """Generate text with batched inference for speed."""
279
+ if API_VERSION == "old":
280
+ return super().generate_until(requests)
281
+
282
+ total = len(requests)
283
+ results = [None] * total
284
+ bs = max(self._batch_size, 8)
285
+ pad_id = self._tokenizer.pad_token_id or 0
286
+
287
+ # Parse all requests
288
+ parsed = []
289
+ for idx, req in enumerate(requests):
290
+ if hasattr(req, 'args'):
291
+ ctx, gen_kwargs = req.args
292
+ else:
293
+ ctx, gen_kwargs = req
294
+ until = gen_kwargs.get('until', [self._tokenizer.eos_token])
295
+ if '\n' not in until:
296
+ until = until + ['\n']
297
+ max_gen = gen_kwargs.get('max_gen_toks', self.max_gen_toks)
298
+ enc = self._tokenizer.encode(ctx, add_special_tokens=False)
299
+ if len(enc) > self._max_length - max_gen:
300
+ enc = enc[-(self._max_length - max_gen):]
301
+ parsed.append((enc, until, max_gen))
302
+
303
+ # Sort by length for efficient batching
304
+ sorted_indices = sorted(range(total), key=lambda i: len(parsed[i][0]))
305
+
306
+ lens = [len(parsed[i][0]) for i in sorted_indices]
307
+ t0 = time.time()
308
+ log(f" generate_until: {total} requests, batch_size={bs} (length-sorted)")
309
+ log(f" context lengths: min={lens[0]}, max={lens[-1]}, "
310
+ f"median={lens[len(lens)//2]}, max_gen_toks={self.max_gen_toks}")
311
+ processed = 0
312
+
313
+ for batch_start in range(0, total, bs):
314
+ batch_end = min(batch_start + bs, total)
315
+ batch_indices = sorted_indices[batch_start:batch_end]
316
+ batch = [parsed[i] for i in batch_indices]
317
+
318
+ # Use the max_gen from the first item (should be same for all)
319
+ max_gen = batch[0][2]
320
+
321
+ # Pad contexts to same length (left-pad)
322
+ max_ctx_len = max(len(enc) for enc, _, _ in batch)
323
+ input_ids = torch.full(
324
+ (len(batch), max_ctx_len), pad_id,
325
+ dtype=torch.long, device=self._device
326
+ )
327
+ attention_mask = torch.zeros(
328
+ (len(batch), max_ctx_len),
329
+ dtype=torch.long, device=self._device
330
+ )
331
+ ctx_lengths = []
332
+ for i, (enc, _, _) in enumerate(batch):
333
+ offset = max_ctx_len - len(enc)
334
+ input_ids[i, offset:] = torch.tensor(enc, dtype=torch.long)
335
+ attention_mask[i, offset:] = 1
336
+ ctx_lengths.append(len(enc))
337
+
338
+ # Batched generate
339
+ with torch.no_grad():
340
+ out = self._model.generate(
341
+ input_ids,
342
+ attention_mask=attention_mask,
343
+ max_new_tokens=max_gen,
344
+ do_sample=False,
345
+ eos_token_id=self._tokenizer.eos_token_id,
346
+ )
347
+
348
+ # Extract generated text per item
349
+ for i, (enc, until, _) in enumerate(batch):
350
+ offset = max_ctx_len - len(enc)
351
+ gen_start = max_ctx_len # generated tokens start after context
352
+ gen_tokens = out[i, gen_start:]
353
+ text = self._tokenizer.decode(gen_tokens, skip_special_tokens=True)
354
+ for stop in until:
355
+ if stop in text:
356
+ text = text[:text.index(stop)]
357
+ results[batch_indices[i]] = text
358
+
359
+ processed += len(batch)
360
+ if processed % (bs * 10) < bs:
361
+ elapsed = time.time() - t0
362
+ speed = processed / elapsed * 60
363
+ eta = (total - processed) / (processed / elapsed) if processed > 0 else 0
364
+ log(f" generate_until: {processed}/{total} "
365
+ f"({speed:.1f} req/min, ETA {eta/60:.1f}min)")
366
+
367
+ elapsed = time.time() - t0
368
+ log(f" generate_until done: {total} in {elapsed:.0f}s "
369
+ f"({total/elapsed*60:.1f} req/min)")
370
+ return results
371
+
372
+
373
+ def main():
374
+ parser = argparse.ArgumentParser(
375
+ description="Polish LLM Leaderboard eval for QuIP# models"
376
+ )
377
+ parser.add_argument('--model_path', default='/dev/shm/eval/model',
378
+ help='Path to QuIP# model directory')
379
+ parser.add_argument('--tokenizer', default='speakleash/Bielik-11B-v2.3-Instruct',
380
+ help='Tokenizer name or path')
381
+ parser.add_argument('--output_dir', default='/dev/shm/eval/results_a',
382
+ help='Output directory for results')
383
+ parser.add_argument('--batch_size', type=int, default=1,
384
+ help='Batch size for eval')
385
+ parser.add_argument('--num_fewshot', type=int, default=5,
386
+ help='Number of few-shot examples')
387
+ parser.add_argument('--tasks', nargs='+',
388
+ default=['polish_generate_few', 'polish_mc'],
389
+ help='Task groups to evaluate')
390
+ args = parser.parse_args()
391
+
392
+ os.makedirs(args.output_dir, exist_ok=True)
393
+
394
+ log("=" * 60)
395
+ log(" Polish LLM Leaderboard Eval")
396
+ log(" Model: QuIP# Bielik-Q2-Sharp Variant A")
397
+ log(f" lm-eval API: {API_VERSION}")
398
+ log(f" Tasks: {args.tasks}")
399
+ log(f" Few-shot: {args.num_fewshot}")
400
+ log("=" * 60)
401
+
402
+ # Load model once
403
+ model = QuIPSharpLM(
404
+ model_path=args.model_path,
405
+ tokenizer_path=args.tokenizer,
406
+ batch_size=args.batch_size,
407
+ )
408
+
409
+ # Run all tasks in a single evaluate call
410
+ log(f"\nRunning {len(args.tasks)} tasks...")
411
+ t0 = time.time()
412
+
413
+ try:
414
+ results = evaluator.simple_evaluate(
415
+ model=model,
416
+ tasks=args.tasks,
417
+ num_fewshot=args.num_fewshot,
418
+ log_samples=True,
419
+ batch_size=args.batch_size,
420
+ )
421
+ except TypeError as e:
422
+ log(f"simple_evaluate TypeError ({e}), trying older signature...")
423
+ results = evaluator.simple_evaluate(
424
+ model=model,
425
+ tasks=args.tasks,
426
+ num_fewshot=args.num_fewshot,
427
+ no_cache=True,
428
+ )
429
+
430
+ elapsed = time.time() - t0
431
+ log(f"\nAll tasks completed in {elapsed:.0f}s")
432
+
433
+ # Save full results
434
+ out_file = os.path.join(args.output_dir, 'full_results.json')
435
+ with open(out_file, 'w') as f:
436
+ json.dump(results, f, indent=2, default=str)
437
+ log(f"Saved: {out_file}")
438
+
439
+ # Print per-task summary
440
+ all_results = {}
441
+ if 'results' in results:
442
+ for task_name, metrics in results['results'].items():
443
+ log(f"\n {task_name}:")
444
+ for k, v in metrics.items():
445
+ if isinstance(v, (int, float)):
446
+ log(f" {k}: {v:.4f}" if isinstance(v, float) else f" {k}: {v}")
447
+ all_results[task_name] = metrics
448
+
449
+ # Print final summary
450
+ log("\n" + "=" * 60)
451
+ log(" FINAL RESULTS SUMMARY")
452
+ log("=" * 60)
453
+ scores = []
454
+ for group, tasks_res in all_results.items():
455
+ for task_name, metrics in tasks_res.items():
456
+ # Find the main accuracy metric
457
+ for key in ['acc_norm', 'acc', 'f1', 'exact_match']:
458
+ if key in metrics:
459
+ val = metrics[key]
460
+ if isinstance(val, (int, float)):
461
+ scores.append((task_name, key, val))
462
+ log(f" {task_name}: {key}={val:.4f}")
463
+ break
464
+
465
+ if scores:
466
+ avg = np.mean([s[2] for s in scores])
467
+ log(f"\n Average score: {avg:.4f} ({avg*100:.2f}%)")
468
+ log(f" Baseline (IQ2_XXS): 61.34%")
469
+ log(f" FP16 Instruct: 65.71%")
470
+ if avg * 100 > 61.34:
471
+ log(f" >>> BEATS BASELINE by {avg*100 - 61.34:.2f}pp <<<")
472
+ else:
473
+ log(f" >>> Below baseline by {61.34 - avg*100:.2f}pp <<<")
474
+
475
+ log("=" * 60)
476
+ log(" EVALUATION COMPLETE")
477
+ log("=" * 60)
478
+
479
+
480
+ if __name__ == '__main__':
481
+ main()