omrifahn commited on
Commit
fef00d1
·
verified ·
1 Parent(s): 4325287

Upload src/evaluate.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/evaluate.py +530 -0
src/evaluate.py ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Evaluation Metrics
3
+
4
+ Metrics for measuring memorization suppression and capability preservation.
5
+
6
+ Based on: "From Memorization to Reasoning in the Spectrum of Loss Curvature"
7
+ """
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from torch import Tensor
12
+ from typing import Optional
13
+ from dataclasses import dataclass
14
+ from tqdm import tqdm
15
+ import numpy as np
16
+
17
+
18
+ def levenshtein_distance(seq1: list, seq2: list) -> int:
19
+ """
20
+ Compute the Levenshtein (edit) distance between two sequences.
21
+
22
+ This is the minimum number of single-element edits (insertions,
23
+ deletions, substitutions) needed to transform seq1 into seq2.
24
+ """
25
+ # Try to use fast C implementation if available
26
+ try:
27
+ import Levenshtein
28
+ # Convert to strings for the library
29
+ s1 = " ".join(map(str, seq1))
30
+ s2 = " ".join(map(str, seq2))
31
+ return Levenshtein.distance(s1, s2)
32
+ except ImportError:
33
+ pass
34
+
35
+ # Pure Python implementation
36
+ m, n = len(seq1), len(seq2)
37
+
38
+ # Create distance matrix
39
+ dp = [[0] * (n + 1) for _ in range(m + 1)]
40
+
41
+ # Initialize base cases
42
+ for i in range(m + 1):
43
+ dp[i][0] = i
44
+ for j in range(n + 1):
45
+ dp[0][j] = j
46
+
47
+ # Fill the matrix
48
+ for i in range(1, m + 1):
49
+ for j in range(1, n + 1):
50
+ if seq1[i - 1] == seq2[j - 1]:
51
+ dp[i][j] = dp[i - 1][j - 1]
52
+ else:
53
+ dp[i][j] = 1 + min(
54
+ dp[i - 1][j], # deletion
55
+ dp[i][j - 1], # insertion
56
+ dp[i - 1][j - 1] # substitution
57
+ )
58
+
59
+ return dp[m][n]
60
+
61
+
62
+ def token_level_levenshtein(generated_ids: list[int], target_ids: list[int]) -> int:
63
+ """Compute Levenshtein distance at the token level."""
64
+ return levenshtein_distance(generated_ids, target_ids)
65
+
66
+
67
+ @torch.no_grad()
68
+ def generate_greedy(
69
+ model: nn.Module,
70
+ input_ids: Tensor,
71
+ max_new_tokens: int,
72
+ attention_mask: Optional[Tensor] = None,
73
+ pad_token_id: Optional[int] = None,
74
+ ) -> Tensor:
75
+ """
76
+ Generate tokens using greedy decoding.
77
+
78
+ Args:
79
+ model: Language model
80
+ input_ids: Input token IDs (batch, seq_len)
81
+ max_new_tokens: Number of tokens to generate
82
+ attention_mask: Attention mask
83
+ pad_token_id: Token ID for padding
84
+
85
+ Returns:
86
+ Generated token IDs (batch, max_new_tokens)
87
+ """
88
+ model.eval()
89
+ device = next(model.parameters()).device
90
+
91
+ input_ids = input_ids.to(device)
92
+ if attention_mask is not None:
93
+ attention_mask = attention_mask.to(device)
94
+
95
+ batch_size = input_ids.shape[0]
96
+ generated = []
97
+
98
+ # Use KV cache for efficiency
99
+ past_key_values = None
100
+ current_input = input_ids
101
+
102
+ for _ in range(max_new_tokens):
103
+ outputs = model(
104
+ input_ids=current_input,
105
+ attention_mask=attention_mask,
106
+ past_key_values=past_key_values,
107
+ use_cache=True,
108
+ )
109
+
110
+ # Get logits for last position
111
+ logits = outputs.logits[:, -1, :]
112
+
113
+ # Greedy selection
114
+ next_token = logits.argmax(dim=-1, keepdim=True)
115
+ generated.append(next_token)
116
+
117
+ # Update for next iteration
118
+ current_input = next_token
119
+ past_key_values = outputs.past_key_values
120
+
121
+ # Update attention mask if provided
122
+ if attention_mask is not None:
123
+ attention_mask = torch.cat([
124
+ attention_mask,
125
+ torch.ones((batch_size, 1), device=device, dtype=attention_mask.dtype)
126
+ ], dim=1)
127
+
128
+ return torch.cat(generated, dim=1)
129
+
130
+
131
+ @dataclass
132
+ class MemorizationResult:
133
+ """Results from memorization evaluation."""
134
+
135
+ # Metrics
136
+ strict_accuracy: float # Exact match rate
137
+ loose_accuracy: float # >=threshold match rate
138
+ avg_levenshtein: float # Average normalized Levenshtein distance
139
+
140
+ # Counts
141
+ n_samples: int
142
+ n_strict_match: int
143
+ n_loose_match: int
144
+
145
+ # Details (optional)
146
+ per_sample_results: Optional[list[dict]] = None
147
+
148
+
149
+ def strict_accuracy(
150
+ model: nn.Module,
151
+ tokenizer,
152
+ prefixes: list[str],
153
+ suffixes: list[str],
154
+ batch_size: int = 8,
155
+ progress_bar: bool = True,
156
+ ) -> float:
157
+ """
158
+ Compute strict accuracy: fraction of exact suffix matches.
159
+
160
+ Args:
161
+ model: Language model
162
+ tokenizer: Tokenizer
163
+ prefixes: List of prefix strings
164
+ suffixes: List of expected suffix strings
165
+ batch_size: Batch size for generation
166
+ progress_bar: Show progress bar
167
+
168
+ Returns:
169
+ Strict accuracy (0-1)
170
+ """
171
+ result = memorization_score(
172
+ model, tokenizer, prefixes, suffixes,
173
+ batch_size=batch_size, progress_bar=progress_bar
174
+ )
175
+ return result.strict_accuracy
176
+
177
+
178
+ def loose_accuracy(
179
+ model: nn.Module,
180
+ tokenizer,
181
+ prefixes: list[str],
182
+ suffixes: list[str],
183
+ threshold: float = 0.75,
184
+ batch_size: int = 8,
185
+ progress_bar: bool = True,
186
+ ) -> float:
187
+ """
188
+ Compute loose accuracy: fraction with >=threshold token overlap.
189
+
190
+ Args:
191
+ model: Language model
192
+ tokenizer: Tokenizer
193
+ prefixes: List of prefix strings
194
+ suffixes: List of expected suffix strings
195
+ threshold: Minimum overlap ratio (default 0.75 = 75%)
196
+ batch_size: Batch size for generation
197
+ progress_bar: Show progress bar
198
+
199
+ Returns:
200
+ Loose accuracy (0-1)
201
+ """
202
+ result = memorization_score(
203
+ model, tokenizer, prefixes, suffixes,
204
+ loose_threshold=threshold,
205
+ batch_size=batch_size, progress_bar=progress_bar
206
+ )
207
+ return result.loose_accuracy
208
+
209
+
210
+ def memorization_score(
211
+ model: nn.Module,
212
+ tokenizer,
213
+ prefixes: list[str],
214
+ suffixes: list[str],
215
+ suffix_length: Optional[int] = None,
216
+ loose_threshold: float = 0.75,
217
+ batch_size: int = 8,
218
+ progress_bar: bool = True,
219
+ return_details: bool = False,
220
+ ) -> MemorizationResult:
221
+ """
222
+ Compute comprehensive memorization metrics.
223
+
224
+ For each (prefix, suffix) pair:
225
+ 1. Generate suffix_length tokens given the prefix
226
+ 2. Compare generated tokens to expected suffix
227
+ 3. Compute strict match, loose match, and Levenshtein distance
228
+
229
+ Args:
230
+ model: Language model
231
+ tokenizer: Tokenizer
232
+ prefixes: List of prefix strings
233
+ suffixes: List of expected suffix strings
234
+ suffix_length: Number of tokens to generate (default: infer from suffixes)
235
+ loose_threshold: Threshold for loose accuracy (default 0.75)
236
+ batch_size: Batch size for generation
237
+ progress_bar: Show progress bar
238
+ return_details: Include per-sample results
239
+
240
+ Returns:
241
+ MemorizationResult with computed metrics
242
+ """
243
+ model.eval()
244
+ device = next(model.parameters()).device
245
+
246
+ assert len(prefixes) == len(suffixes), "Prefixes and suffixes must have same length"
247
+ n_samples = len(prefixes)
248
+
249
+ # Tokenize suffixes to get target IDs and determine generation length
250
+ suffix_ids_list = []
251
+ for suffix in suffixes:
252
+ ids = tokenizer.encode(suffix, add_special_tokens=False)
253
+ suffix_ids_list.append(ids)
254
+
255
+ if suffix_length is None:
256
+ # Use max suffix length
257
+ suffix_length = max(len(ids) for ids in suffix_ids_list)
258
+
259
+ # Process in batches
260
+ n_strict = 0
261
+ n_loose = 0
262
+ total_lev_normalized = 0.0
263
+ per_sample = [] if return_details else None
264
+
265
+ iterator = range(0, n_samples, batch_size)
266
+ if progress_bar:
267
+ iterator = tqdm(iterator, desc="Evaluating memorization")
268
+
269
+ for batch_start in iterator:
270
+ batch_end = min(batch_start + batch_size, n_samples)
271
+ batch_prefixes = prefixes[batch_start:batch_end]
272
+ batch_suffix_ids = suffix_ids_list[batch_start:batch_end]
273
+
274
+ # Tokenize prefixes
275
+ encoded = tokenizer(
276
+ batch_prefixes,
277
+ return_tensors="pt",
278
+ padding=True,
279
+ truncation=True,
280
+ )
281
+ input_ids = encoded["input_ids"].to(device)
282
+ attention_mask = encoded["attention_mask"].to(device)
283
+
284
+ # Generate
285
+ generated = generate_greedy(
286
+ model, input_ids, suffix_length,
287
+ attention_mask=attention_mask,
288
+ pad_token_id=tokenizer.pad_token_id,
289
+ )
290
+
291
+ # Compare each sample
292
+ for i, (gen_ids, target_ids) in enumerate(zip(generated, batch_suffix_ids)):
293
+ gen_list = gen_ids.tolist()
294
+ target_list = target_ids[:suffix_length] # Truncate target to generation length
295
+
296
+ # Pad target if shorter
297
+ if len(target_list) < len(gen_list):
298
+ target_list = target_list + [tokenizer.pad_token_id] * (len(gen_list) - len(target_list))
299
+
300
+ # Strict match
301
+ is_strict = gen_list == target_list
302
+ if is_strict:
303
+ n_strict += 1
304
+
305
+ # Levenshtein distance
306
+ lev_dist = token_level_levenshtein(gen_list, target_list)
307
+ lev_normalized = lev_dist / max(len(gen_list), len(target_list), 1)
308
+ total_lev_normalized += lev_normalized
309
+
310
+ # Loose match: 1 - normalized_distance >= threshold
311
+ overlap = 1 - lev_normalized
312
+ is_loose = overlap >= loose_threshold
313
+ if is_loose:
314
+ n_loose += 1
315
+
316
+ if return_details:
317
+ per_sample.append({
318
+ "prefix_idx": batch_start + i,
319
+ "generated_ids": gen_list,
320
+ "target_ids": target_list,
321
+ "strict_match": is_strict,
322
+ "loose_match": is_loose,
323
+ "levenshtein": lev_dist,
324
+ "overlap": overlap,
325
+ })
326
+
327
+ return MemorizationResult(
328
+ strict_accuracy=n_strict / n_samples if n_samples > 0 else 0,
329
+ loose_accuracy=n_loose / n_samples if n_samples > 0 else 0,
330
+ avg_levenshtein=total_lev_normalized / n_samples if n_samples > 0 else 0,
331
+ n_samples=n_samples,
332
+ n_strict_match=n_strict,
333
+ n_loose_match=n_loose,
334
+ per_sample_results=per_sample,
335
+ )
336
+
337
+
338
+ @torch.no_grad()
339
+ def perplexity(
340
+ model: nn.Module,
341
+ tokenizer,
342
+ texts: list[str],
343
+ batch_size: int = 8,
344
+ max_length: int = 512,
345
+ progress_bar: bool = True,
346
+ ) -> float:
347
+ """
348
+ Compute perplexity on a set of texts.
349
+
350
+ Perplexity = exp(average cross-entropy loss)
351
+
352
+ Args:
353
+ model: Language model
354
+ tokenizer: Tokenizer
355
+ texts: List of text strings
356
+ batch_size: Batch size
357
+ max_length: Maximum sequence length
358
+ progress_bar: Show progress bar
359
+
360
+ Returns:
361
+ Perplexity value
362
+ """
363
+ model.eval()
364
+ device = next(model.parameters()).device
365
+
366
+ total_loss = 0.0
367
+ total_tokens = 0
368
+
369
+ iterator = range(0, len(texts), batch_size)
370
+ if progress_bar:
371
+ iterator = tqdm(iterator, desc="Computing perplexity")
372
+
373
+ for batch_start in iterator:
374
+ batch_end = min(batch_start + batch_size, len(texts))
375
+ batch_texts = texts[batch_start:batch_end]
376
+
377
+ # Tokenize
378
+ encoded = tokenizer(
379
+ batch_texts,
380
+ return_tensors="pt",
381
+ padding=True,
382
+ truncation=True,
383
+ max_length=max_length,
384
+ )
385
+ input_ids = encoded["input_ids"].to(device)
386
+ attention_mask = encoded["attention_mask"].to(device)
387
+
388
+ # Create labels: set padding positions to -100 so they're ignored in loss
389
+ labels = input_ids.clone()
390
+ labels[attention_mask == 0] = -100
391
+
392
+ # Forward pass
393
+ outputs = model(
394
+ input_ids=input_ids,
395
+ attention_mask=attention_mask,
396
+ labels=labels,
397
+ )
398
+
399
+ # Get loss (already averaged over non-padding tokens by the model)
400
+ # We need to weight by number of tokens
401
+
402
+ # Count non-padding tokens (excluding first position since no loss there)
403
+ n_tokens = attention_mask[:, 1:].sum().item()
404
+
405
+ # Accumulate
406
+ total_loss += outputs.loss.item() * n_tokens
407
+ total_tokens += n_tokens
408
+
409
+ # Compute perplexity
410
+ avg_loss = total_loss / total_tokens if total_tokens > 0 else float('inf')
411
+ ppl = np.exp(avg_loss)
412
+
413
+ return ppl
414
+
415
+
416
+ def perplexity_from_dataset(
417
+ model: nn.Module,
418
+ tokenizer,
419
+ dataset_name: str = "NeelNanda/pile-10k",
420
+ max_samples: int = 1000,
421
+ batch_size: int = 8,
422
+ max_length: int = 512,
423
+ text_column: str = "text",
424
+ progress_bar: bool = True,
425
+ ) -> float:
426
+ """
427
+ Compute perplexity on a HuggingFace dataset.
428
+
429
+ Args:
430
+ model: Language model
431
+ tokenizer: Tokenizer
432
+ dataset_name: HuggingFace dataset name
433
+ max_samples: Maximum number of samples to use
434
+ batch_size: Batch size
435
+ max_length: Maximum sequence length
436
+ text_column: Name of the text column in the dataset
437
+ progress_bar: Show progress bar
438
+
439
+ Returns:
440
+ Perplexity value
441
+ """
442
+ from datasets import load_dataset
443
+
444
+ # Load dataset
445
+ ds = load_dataset(dataset_name, split="train")
446
+
447
+ # Sample if needed
448
+ if max_samples and len(ds) > max_samples:
449
+ ds = ds.shuffle(seed=42).select(range(max_samples))
450
+
451
+ # Extract texts
452
+ texts = [ex[text_column] for ex in ds]
453
+
454
+ return perplexity(
455
+ model, tokenizer, texts,
456
+ batch_size=batch_size,
457
+ max_length=max_length,
458
+ progress_bar=progress_bar,
459
+ )
460
+
461
+
462
+ def evaluate_all(
463
+ model: nn.Module,
464
+ tokenizer,
465
+ memorized_prefixes: list[str],
466
+ memorized_suffixes: list[str],
467
+ perplexity_texts: Optional[list[str]] = None,
468
+ perplexity_dataset: str = "NeelNanda/pile-10k",
469
+ batch_size: int = 8,
470
+ progress_bar: bool = True,
471
+ ) -> dict:
472
+ """
473
+ Run full evaluation suite.
474
+
475
+ Args:
476
+ model: Language model
477
+ tokenizer: Tokenizer
478
+ memorized_prefixes: Prefixes for memorization test
479
+ memorized_suffixes: Expected suffixes for memorization test
480
+ perplexity_texts: Texts for perplexity (if None, uses dataset)
481
+ perplexity_dataset: Dataset for perplexity if texts not provided
482
+ batch_size: Batch size
483
+ progress_bar: Show progress bar
484
+
485
+ Returns:
486
+ Dictionary with all metrics
487
+ """
488
+ results = {}
489
+
490
+ # Memorization metrics
491
+ print("Evaluating memorization...")
492
+ mem_result = memorization_score(
493
+ model, tokenizer,
494
+ memorized_prefixes, memorized_suffixes,
495
+ batch_size=batch_size,
496
+ progress_bar=progress_bar,
497
+ )
498
+
499
+ results["memorization"] = {
500
+ "strict_accuracy": mem_result.strict_accuracy,
501
+ "loose_accuracy": mem_result.loose_accuracy,
502
+ "avg_levenshtein": mem_result.avg_levenshtein,
503
+ "n_samples": mem_result.n_samples,
504
+ }
505
+
506
+ # Perplexity
507
+ print("Computing perplexity...")
508
+ if perplexity_texts:
509
+ ppl = perplexity(
510
+ model, tokenizer, perplexity_texts,
511
+ batch_size=batch_size,
512
+ progress_bar=progress_bar,
513
+ )
514
+ else:
515
+ ppl = perplexity_from_dataset(
516
+ model, tokenizer,
517
+ dataset_name=perplexity_dataset,
518
+ batch_size=batch_size,
519
+ progress_bar=progress_bar,
520
+ )
521
+
522
+ results["perplexity"] = ppl
523
+
524
+ print(f"\nResults:")
525
+ print(f" Strict accuracy: {results['memorization']['strict_accuracy']*100:.1f}%")
526
+ print(f" Loose accuracy: {results['memorization']['loose_accuracy']*100:.1f}%")
527
+ print(f" Avg Levenshtein: {results['memorization']['avg_levenshtein']:.3f}")
528
+ print(f" Perplexity: {results['perplexity']:.2f}")
529
+
530
+ return results