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

Upload src/mine_memorized.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/mine_memorized.py +430 -0
src/mine_memorized.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Memorization Mining
3
+
4
+ Utilities for finding memorized sequences from training data.
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, Iterator
13
+ from dataclasses import dataclass
14
+ import json
15
+ from tqdm import tqdm
16
+ import random
17
+
18
+
19
+ @dataclass
20
+ class MemorizedSequence:
21
+ """A memorized sequence with prefix and suffix."""
22
+
23
+ prefix: str
24
+ suffix: str
25
+ prefix_ids: list[int]
26
+ suffix_ids: list[int]
27
+ source: str = "" # Dataset source
28
+
29
+ def to_dict(self) -> dict:
30
+ return {
31
+ "prefix": self.prefix,
32
+ "suffix": self.suffix,
33
+ "prefix_ids": self.prefix_ids,
34
+ "suffix_ids": self.suffix_ids,
35
+ "source": self.source,
36
+ }
37
+
38
+ @classmethod
39
+ def from_dict(cls, d: dict) -> "MemorizedSequence":
40
+ return cls(**d)
41
+
42
+
43
+ def sample_sequences(
44
+ dataset_name: str,
45
+ tokenizer,
46
+ num_sequences: int = 10000,
47
+ prefix_len: int = 64,
48
+ suffix_len: int = 48,
49
+ min_text_tokens: int = None,
50
+ seed: int = 42,
51
+ streaming: bool = True,
52
+ dataset_config: Optional[str] = None,
53
+ text_column: str = "text",
54
+ ) -> list[MemorizedSequence]:
55
+ """
56
+ Sample candidate (prefix, suffix) pairs from a dataset.
57
+
58
+ The sequences are drawn by:
59
+ 1. Streaming text from the dataset
60
+ 2. Tokenizing each text
61
+ 3. Extracting windows of (prefix_len + suffix_len) tokens
62
+
63
+ Args:
64
+ dataset_name: HuggingFace dataset name
65
+ tokenizer: Tokenizer for the model
66
+ num_sequences: Number of sequences to sample
67
+ prefix_len: Length of prefix in tokens
68
+ suffix_len: Length of suffix in tokens
69
+ min_text_tokens: Minimum tokens in text to be considered
70
+ seed: Random seed
71
+ streaming: Use streaming mode
72
+ dataset_config: Dataset configuration/subset
73
+ text_column: Name of the text column
74
+
75
+ Returns:
76
+ List of MemorizedSequence candidates
77
+ """
78
+ from datasets import load_dataset
79
+
80
+ random.seed(seed)
81
+
82
+ total_len = prefix_len + suffix_len
83
+ min_text_tokens = min_text_tokens or total_len + 10
84
+
85
+ # Load dataset
86
+ if dataset_config:
87
+ ds = load_dataset(dataset_name, name=dataset_config, split="train", streaming=streaming)
88
+ else:
89
+ ds = load_dataset(dataset_name, split="train", streaming=streaming)
90
+
91
+ if streaming:
92
+ ds = ds.shuffle(buffer_size=10000, seed=seed)
93
+
94
+ sequences = []
95
+ seen_prefixes = set() # For deduplication
96
+
97
+ pbar = tqdm(total=num_sequences, desc="Sampling sequences")
98
+
99
+ for example in ds:
100
+ if len(sequences) >= num_sequences:
101
+ break
102
+
103
+ # Get text
104
+ text = example.get(text_column)
105
+ if not text:
106
+ continue
107
+
108
+ # Tokenize
109
+ tokens = tokenizer.encode(text, add_special_tokens=False)
110
+
111
+ if len(tokens) < min_text_tokens:
112
+ continue
113
+
114
+ # Sample a random window
115
+ max_start = len(tokens) - total_len
116
+ if max_start <= 0:
117
+ continue
118
+
119
+ start_idx = random.randint(0, max_start)
120
+
121
+ prefix_ids = tokens[start_idx:start_idx + prefix_len]
122
+ suffix_ids = tokens[start_idx + prefix_len:start_idx + total_len]
123
+
124
+ # Deduplicate by prefix
125
+ prefix_tuple = tuple(prefix_ids)
126
+ if prefix_tuple in seen_prefixes:
127
+ continue
128
+ seen_prefixes.add(prefix_tuple)
129
+
130
+ # Decode back to text
131
+ prefix = tokenizer.decode(prefix_ids)
132
+ suffix = tokenizer.decode(suffix_ids)
133
+
134
+ sequences.append(MemorizedSequence(
135
+ prefix=prefix,
136
+ suffix=suffix,
137
+ prefix_ids=prefix_ids,
138
+ suffix_ids=suffix_ids,
139
+ source=dataset_name,
140
+ ))
141
+
142
+ pbar.update(1)
143
+
144
+ pbar.close()
145
+ return sequences
146
+
147
+
148
+ @torch.no_grad()
149
+ def check_memorization_batch(
150
+ model: nn.Module,
151
+ tokenizer,
152
+ sequences: list[MemorizedSequence],
153
+ strict: bool = True,
154
+ ) -> list[tuple[MemorizedSequence, bool, float]]:
155
+ """
156
+ Check if a batch of sequences is memorized.
157
+
158
+ Args:
159
+ model: Language model
160
+ tokenizer: Tokenizer
161
+ sequences: List of sequences to check
162
+ strict: If True, require exact match; if False, use overlap threshold
163
+
164
+ Returns:
165
+ List of (sequence, is_memorized, overlap_score) tuples
166
+ """
167
+ model.eval()
168
+ device = next(model.parameters()).device
169
+
170
+ # Prepare batch
171
+ prefixes = [seq.prefix for seq in sequences]
172
+ suffix_lengths = [len(seq.suffix_ids) for seq in sequences]
173
+ max_suffix_len = max(suffix_lengths)
174
+
175
+ # Tokenize prefixes
176
+ encoded = tokenizer(
177
+ prefixes,
178
+ return_tensors="pt",
179
+ padding=True,
180
+ truncation=True,
181
+ )
182
+ input_ids = encoded["input_ids"].to(device)
183
+ attention_mask = encoded["attention_mask"].to(device)
184
+
185
+ # Generate
186
+ from .evaluate import generate_greedy
187
+ generated = generate_greedy(
188
+ model, input_ids, max_suffix_len,
189
+ attention_mask=attention_mask,
190
+ pad_token_id=tokenizer.pad_token_id,
191
+ )
192
+
193
+ results = []
194
+ for i, (seq, gen_ids) in enumerate(zip(sequences, generated)):
195
+ gen_list = gen_ids.tolist()[:len(seq.suffix_ids)]
196
+ target_list = seq.suffix_ids
197
+
198
+ # Check match
199
+ is_exact = gen_list == target_list
200
+
201
+ # Compute overlap
202
+ matches = sum(g == t for g, t in zip(gen_list, target_list))
203
+ overlap = matches / len(target_list) if target_list else 0
204
+
205
+ is_memorized = is_exact if strict else (overlap >= 0.75)
206
+
207
+ results.append((seq, is_memorized, overlap))
208
+
209
+ return results
210
+
211
+
212
+ def filter_memorized(
213
+ model: nn.Module,
214
+ tokenizer,
215
+ candidates: list[MemorizedSequence],
216
+ batch_size: int = 8,
217
+ strict: bool = True,
218
+ progress_bar: bool = True,
219
+ ) -> list[MemorizedSequence]:
220
+ """
221
+ Filter candidates to keep only memorized sequences.
222
+
223
+ Args:
224
+ model: Language model
225
+ tokenizer: Tokenizer
226
+ candidates: List of candidate sequences
227
+ batch_size: Batch size for inference
228
+ strict: Require exact match
229
+ progress_bar: Show progress bar
230
+
231
+ Returns:
232
+ List of memorized sequences
233
+ """
234
+ memorized = []
235
+
236
+ iterator = range(0, len(candidates), batch_size)
237
+ if progress_bar:
238
+ iterator = tqdm(iterator, desc="Filtering memorized")
239
+
240
+ for batch_start in iterator:
241
+ batch_end = min(batch_start + batch_size, len(candidates))
242
+ batch = candidates[batch_start:batch_end]
243
+
244
+ results = check_memorization_batch(model, tokenizer, batch, strict)
245
+
246
+ for seq, is_mem, overlap in results:
247
+ if is_mem:
248
+ memorized.append(seq)
249
+
250
+ return memorized
251
+
252
+
253
+ def mine_memorized_sequences(
254
+ model: nn.Module,
255
+ tokenizer,
256
+ dataset_name: str = "allenai/olmo-mix-1124",
257
+ target_count: int = 1000,
258
+ max_candidates: int = 50000,
259
+ prefix_len: int = 64,
260
+ suffix_len: int = 48,
261
+ batch_size: int = 8,
262
+ seed: int = 42,
263
+ dataset_config: Optional[str] = None,
264
+ strict: bool = True,
265
+ ) -> list[MemorizedSequence]:
266
+ """
267
+ Mine memorized sequences from training data.
268
+
269
+ This is the main pipeline for finding sequences that the model
270
+ has memorized verbatim.
271
+
272
+ Args:
273
+ model: Language model
274
+ tokenizer: Tokenizer
275
+ dataset_name: HuggingFace dataset name (should be training data)
276
+ target_count: Desired number of memorized sequences
277
+ max_candidates: Maximum candidates to sample
278
+ prefix_len: Prefix length in tokens
279
+ suffix_len: Suffix length in tokens
280
+ batch_size: Batch size for inference
281
+ seed: Random seed
282
+ dataset_config: Dataset configuration
283
+ strict: Require exact match
284
+
285
+ Returns:
286
+ List of memorized sequences
287
+ """
288
+ print(f"Mining memorized sequences from {dataset_name}")
289
+ print(f"Target: {target_count} memorized, max candidates: {max_candidates}")
290
+
291
+ # Sample candidates
292
+ print("\nStep 1: Sampling candidates...")
293
+ candidates = sample_sequences(
294
+ dataset_name=dataset_name,
295
+ tokenizer=tokenizer,
296
+ num_sequences=max_candidates,
297
+ prefix_len=prefix_len,
298
+ suffix_len=suffix_len,
299
+ seed=seed,
300
+ dataset_config=dataset_config,
301
+ )
302
+ print(f"Sampled {len(candidates)} candidates")
303
+
304
+ # Filter for memorized
305
+ print("\nStep 2: Filtering for memorized sequences...")
306
+ memorized = filter_memorized(
307
+ model=model,
308
+ tokenizer=tokenizer,
309
+ candidates=candidates,
310
+ batch_size=batch_size,
311
+ strict=strict,
312
+ )
313
+
314
+ print(f"\nFound {len(memorized)} memorized sequences "
315
+ f"({len(memorized)/len(candidates)*100:.1f}% of candidates)")
316
+
317
+ # Truncate if we found more than needed
318
+ if len(memorized) > target_count:
319
+ random.seed(seed)
320
+ memorized = random.sample(memorized, target_count)
321
+ print(f"Truncated to {target_count} sequences")
322
+
323
+ return memorized
324
+
325
+
326
+ def save_sequences(sequences: list[MemorizedSequence], path: str) -> None:
327
+ """Save sequences to a JSON file."""
328
+ data = [seq.to_dict() for seq in sequences]
329
+ with open(path, "w") as f:
330
+ json.dump(data, f, indent=2)
331
+ print(f"Saved {len(sequences)} sequences to {path}")
332
+
333
+
334
+ def load_sequences(path: str) -> list[MemorizedSequence]:
335
+ """Load sequences from a JSON file."""
336
+ with open(path, "r") as f:
337
+ data = json.load(f)
338
+ sequences = [MemorizedSequence.from_dict(d) for d in data]
339
+ print(f"Loaded {len(sequences)} sequences from {path}")
340
+ return sequences
341
+
342
+
343
+ def split_sequences(
344
+ sequences: list[MemorizedSequence],
345
+ train_ratio: float = 0.8,
346
+ seed: int = 42,
347
+ ) -> tuple[list[MemorizedSequence], list[MemorizedSequence]]:
348
+ """
349
+ Split sequences into train and validation sets.
350
+
351
+ Args:
352
+ sequences: List of sequences
353
+ train_ratio: Fraction for training set
354
+ seed: Random seed
355
+
356
+ Returns:
357
+ Tuple of (train_sequences, val_sequences)
358
+ """
359
+ random.seed(seed)
360
+ shuffled = sequences.copy()
361
+ random.shuffle(shuffled)
362
+
363
+ split_idx = int(len(shuffled) * train_ratio)
364
+ train = shuffled[:split_idx]
365
+ val = shuffled[split_idx:]
366
+
367
+ return train, val
368
+
369
+
370
+ def get_prefixes_and_suffixes(
371
+ sequences: list[MemorizedSequence],
372
+ ) -> tuple[list[str], list[str]]:
373
+ """
374
+ Extract prefix and suffix strings from sequences.
375
+
376
+ Useful for passing to evaluation functions.
377
+ """
378
+ prefixes = [seq.prefix for seq in sequences]
379
+ suffixes = [seq.suffix for seq in sequences]
380
+ return prefixes, suffixes
381
+
382
+
383
+ # Historical quotes dataset (for out-of-distribution testing)
384
+ HISTORICAL_QUOTES = [
385
+ # Famous quotes that models often memorize
386
+ ("To be, or not to be, that is the question:", " Whether 'tis nobler in the mind to suffer"),
387
+ ("Four score and seven years ago our fathers brought forth", " on this continent, a new nation, conceived in Liberty"),
388
+ ("I have a dream that one day this nation will rise up", " and live out the true meaning of its creed"),
389
+ ("Ask not what your country can do for you", " — ask what you can do for your country"),
390
+ ("The only thing we have to fear is", " fear itself"),
391
+ ("In the beginning God created", " the heavens and the earth"),
392
+ ("It was the best of times, it was the worst of times,", " it was the age of wisdom, it was the age of foolishness"),
393
+ ("Call me Ishmael. Some years ago—never mind how long precisely", "—having little or no money in my purse"),
394
+ ("All happy families are alike; each unhappy family is", " unhappy in its own way"),
395
+ ("It is a truth universally acknowledged, that a single man in possession", " of a good fortune, must be in want of a wife"),
396
+ ]
397
+
398
+
399
+ def create_quotes_dataset(
400
+ tokenizer,
401
+ additional_quotes: Optional[list[tuple[str, str]]] = None,
402
+ ) -> list[MemorizedSequence]:
403
+ """
404
+ Create a dataset of historical quotes for OOD memorization testing.
405
+
406
+ Args:
407
+ tokenizer: Tokenizer
408
+ additional_quotes: Additional (prefix, suffix) tuples to include
409
+
410
+ Returns:
411
+ List of MemorizedSequence objects
412
+ """
413
+ quotes = HISTORICAL_QUOTES.copy()
414
+ if additional_quotes:
415
+ quotes.extend(additional_quotes)
416
+
417
+ sequences = []
418
+ for prefix, suffix in quotes:
419
+ prefix_ids = tokenizer.encode(prefix, add_special_tokens=False)
420
+ suffix_ids = tokenizer.encode(suffix, add_special_tokens=False)
421
+
422
+ sequences.append(MemorizedSequence(
423
+ prefix=prefix,
424
+ suffix=suffix,
425
+ prefix_ids=prefix_ids,
426
+ suffix_ids=suffix_ids,
427
+ source="historical_quotes",
428
+ ))
429
+
430
+ return sequences