omrifahn commited on
Commit
96080d7
·
verified ·
1 Parent(s): d3465ec

Upload src/kfac_collector.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/kfac_collector.py +579 -0
src/kfac_collector.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ K-FAC Statistics Collector
3
+
4
+ Collects activation covariance (A) and gradient covariance (G) matrices
5
+ for MLP layers to approximate the Fisher Information Matrix.
6
+
7
+ Based on: "From Memorization to Reasoning in the Spectrum of Loss Curvature"
8
+ """
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ from torch import Tensor
13
+ from typing import Optional, Callable
14
+ from dataclasses import dataclass, field
15
+ from tqdm import tqdm
16
+
17
+
18
+ @dataclass
19
+ class LayerStatistics:
20
+ """K-FAC statistics for a single layer."""
21
+
22
+ # Covariance matrices
23
+ A: Optional[Tensor] = None # Activation covariance (d_in x d_in)
24
+ G: Optional[Tensor] = None # Gradient covariance (d_out x d_out)
25
+
26
+ # Running sums for incremental computation
27
+ A_sum: Optional[Tensor] = None
28
+ G_sum: Optional[Tensor] = None
29
+
30
+ # Counts
31
+ n_samples_A: int = 0
32
+ n_samples_G: int = 0
33
+
34
+ def finalize(self) -> None:
35
+ """Convert running sums to means."""
36
+ if self.A_sum is not None and self.n_samples_A > 0:
37
+ self.A = self.A_sum / self.n_samples_A
38
+ self.A_sum = None
39
+ if self.G_sum is not None and self.n_samples_G > 0:
40
+ self.G = self.G_sum / self.n_samples_G
41
+ self.G_sum = None
42
+
43
+
44
+ @dataclass
45
+ class KFACConfig:
46
+ """Configuration for K-FAC collection."""
47
+
48
+ # Target layers (layer indices)
49
+ target_layers: list[int] = field(default_factory=lambda: [11, 12, 13])
50
+
51
+ # Target projections within MLP
52
+ target_projections: list[str] = field(default_factory=lambda: ["gate_proj", "up_proj"])
53
+
54
+ # Sequence length for batching
55
+ seq_length: int = 512
56
+
57
+ # Whether to exclude last position (for causal LM)
58
+ exclude_last_position: bool = True
59
+
60
+ # Use sampled labels instead of ground truth for proper FIM
61
+ sample_labels: bool = True
62
+
63
+ # Device
64
+ device: str = "cuda"
65
+
66
+
67
+ class KFACCollector:
68
+ """
69
+ Collects K-FAC statistics (activation and gradient covariances) for MLP layers.
70
+
71
+ The K-FAC approximation factorizes the Fisher Information Matrix as:
72
+ F_W ≈ G ⊗ A = E[gg^T] ⊗ E[aa^T]
73
+
74
+ where:
75
+ - A is the covariance of activations going into the layer
76
+ - G is the covariance of gradients on the layer's output
77
+
78
+ Usage:
79
+ collector = KFACCollector(model, config)
80
+ collector.register_hooks()
81
+
82
+ for batch in dataloader:
83
+ collector.collect_batch(batch, tokenizer)
84
+
85
+ collector.finalize()
86
+ collector.save("kfac_stats.pt")
87
+ """
88
+
89
+ def __init__(
90
+ self,
91
+ model: nn.Module,
92
+ config: Optional[KFACConfig] = None,
93
+ ):
94
+ self.model = model
95
+ self.config = config or KFACConfig()
96
+
97
+ # Storage for statistics
98
+ self.stats: dict[str, LayerStatistics] = {}
99
+
100
+ # Hooks
101
+ self._forward_hooks: list = []
102
+ self._backward_hooks: list = []
103
+
104
+ # Buffers for current batch
105
+ self._activation_buffer: dict[str, Tensor] = {}
106
+ self._gradient_buffer: dict[str, Tensor] = {}
107
+
108
+ # Track registration state
109
+ self._hooks_registered = False
110
+
111
+ def _get_layer_name(self, layer_idx: int, proj_name: str) -> str:
112
+ """Generate a unique name for a layer/projection combination."""
113
+ return f"layer_{layer_idx}.{proj_name}"
114
+
115
+ def _get_target_modules(self) -> dict[str, nn.Linear]:
116
+ """Find all target modules in the model."""
117
+ targets = {}
118
+
119
+ # Handle different model architectures
120
+ # OLMo-2 / LLaMA style: model.layers[i].mlp.{gate_proj, up_proj, down_proj}
121
+
122
+ layers = None
123
+ if hasattr(self.model, "model") and hasattr(self.model.model, "layers"):
124
+ # HF style (e.g., OLMoForCausalLM)
125
+ layers = self.model.model.layers
126
+ elif hasattr(self.model, "transformer") and hasattr(self.model.transformer, "blocks"):
127
+ # GPT style
128
+ layers = self.model.transformer.blocks
129
+ elif hasattr(self.model, "layers"):
130
+ # Direct access
131
+ layers = self.model.layers
132
+
133
+ if layers is None:
134
+ raise ValueError(
135
+ "Could not find transformer layers. "
136
+ "Model architecture not recognized. "
137
+ f"Model type: {type(self.model)}"
138
+ )
139
+
140
+ for layer_idx in self.config.target_layers:
141
+ if layer_idx >= len(layers):
142
+ print(f"Warning: Layer {layer_idx} does not exist (model has {len(layers)} layers)")
143
+ continue
144
+
145
+ layer = layers[layer_idx]
146
+
147
+ # Find MLP submodule
148
+ mlp = None
149
+ if hasattr(layer, "mlp"):
150
+ mlp = layer.mlp
151
+ elif hasattr(layer, "feed_forward"):
152
+ mlp = layer.feed_forward
153
+ elif hasattr(layer, "ff"):
154
+ mlp = layer.ff
155
+
156
+ if mlp is None:
157
+ print(f"Warning: Could not find MLP in layer {layer_idx}")
158
+ continue
159
+
160
+ for proj_name in self.config.target_projections:
161
+ if hasattr(mlp, proj_name):
162
+ proj = getattr(mlp, proj_name)
163
+ if isinstance(proj, nn.Linear):
164
+ name = self._get_layer_name(layer_idx, proj_name)
165
+ targets[name] = proj
166
+ self.stats[name] = LayerStatistics()
167
+ else:
168
+ print(f"Warning: {proj_name} not found in layer {layer_idx}")
169
+
170
+ return targets
171
+
172
+ def register_hooks(self) -> None:
173
+ """Register forward and backward hooks on target modules."""
174
+ if self._hooks_registered:
175
+ print("Hooks already registered")
176
+ return
177
+
178
+ targets = self._get_target_modules()
179
+
180
+ if not targets:
181
+ raise ValueError("No target modules found to hook")
182
+
183
+ print(f"Registering hooks on {len(targets)} modules:")
184
+ for name in targets:
185
+ print(f" - {name}")
186
+
187
+ for name, module in targets.items():
188
+ # Forward hook: capture input activations
189
+ def make_forward_hook(layer_name: str):
190
+ def hook(module: nn.Module, input: tuple, output: Tensor) -> None:
191
+ # input is a tuple, first element is the activation tensor
192
+ x = input[0]
193
+ if x.requires_grad:
194
+ # Store for backward pass
195
+ self._activation_buffer[layer_name] = x.detach()
196
+ return hook
197
+
198
+ # Backward hook: capture output gradients
199
+ def make_backward_hook(layer_name: str):
200
+ def hook(module: nn.Module, grad_input: tuple, grad_output: tuple) -> None:
201
+ # grad_output is tuple, first element is gradient w.r.t. output
202
+ g = grad_output[0]
203
+ if g is not None:
204
+ self._gradient_buffer[layer_name] = g.detach()
205
+ return hook
206
+
207
+ fh = module.register_forward_hook(make_forward_hook(name))
208
+ bh = module.register_full_backward_hook(make_backward_hook(name))
209
+
210
+ self._forward_hooks.append(fh)
211
+ self._backward_hooks.append(bh)
212
+
213
+ self._hooks_registered = True
214
+
215
+ def remove_hooks(self) -> None:
216
+ """Remove all registered hooks."""
217
+ for hook in self._forward_hooks:
218
+ hook.remove()
219
+ for hook in self._backward_hooks:
220
+ hook.remove()
221
+
222
+ self._forward_hooks = []
223
+ self._backward_hooks = []
224
+ self._hooks_registered = False
225
+
226
+ def _update_statistics(self) -> None:
227
+ """Update running statistics from current buffers."""
228
+ for name in self.stats:
229
+ if name in self._activation_buffer:
230
+ x = self._activation_buffer[name]
231
+ # x shape: (batch, seq_len, d_in)
232
+
233
+ # Optionally exclude last position
234
+ if self.config.exclude_last_position and x.shape[1] > 1:
235
+ x = x[:, :-1, :]
236
+
237
+ # Flatten batch and sequence dimensions
238
+ x_flat = x.reshape(-1, x.shape[-1]) # (batch * seq, d_in)
239
+ n_positions = x_flat.shape[0]
240
+
241
+ # Compute A contribution: x^T @ x
242
+ A_batch = x_flat.T @ x_flat # (d_in, d_in)
243
+
244
+ # Update running sum
245
+ if self.stats[name].A_sum is None:
246
+ self.stats[name].A_sum = A_batch
247
+ else:
248
+ self.stats[name].A_sum = self.stats[name].A_sum + A_batch
249
+ self.stats[name].n_samples_A += n_positions
250
+
251
+ if name in self._gradient_buffer:
252
+ g = self._gradient_buffer[name]
253
+ # g shape: (batch, seq_len, d_out)
254
+
255
+ # Optionally exclude last position
256
+ if self.config.exclude_last_position and g.shape[1] > 1:
257
+ g = g[:, :-1, :]
258
+
259
+ # Flatten batch and sequence dimensions
260
+ g_flat = g.reshape(-1, g.shape[-1]) # (batch * seq, d_out)
261
+ n_positions = g_flat.shape[0]
262
+
263
+ # Compute G contribution: g^T @ g
264
+ G_batch = g_flat.T @ g_flat # (d_out, d_out)
265
+
266
+ # Update running sum
267
+ if self.stats[name].G_sum is None:
268
+ self.stats[name].G_sum = G_batch
269
+ else:
270
+ self.stats[name].G_sum = self.stats[name].G_sum + G_batch
271
+ self.stats[name].n_samples_G += n_positions
272
+
273
+ # Clear buffers
274
+ self._activation_buffer.clear()
275
+ self._gradient_buffer.clear()
276
+
277
+ @torch.no_grad()
278
+ def _sample_labels(self, logits: Tensor) -> Tensor:
279
+ """
280
+ Sample labels from model's predicted distribution.
281
+
282
+ For proper FIM computation, we sample ŷ ~ p(y|x) rather than
283
+ using ground truth labels.
284
+ """
285
+ # logits shape: (batch, seq_len, vocab_size)
286
+ probs = torch.softmax(logits, dim=-1)
287
+ # Sample from categorical distribution
288
+ sampled = torch.multinomial(
289
+ probs.view(-1, probs.shape[-1]),
290
+ num_samples=1
291
+ ).view(probs.shape[:-1])
292
+ return sampled
293
+
294
+ def collect_batch(
295
+ self,
296
+ input_ids: Tensor,
297
+ attention_mask: Optional[Tensor] = None,
298
+ labels: Optional[Tensor] = None,
299
+ ) -> float:
300
+ """
301
+ Collect K-FAC statistics from a single batch.
302
+
303
+ Args:
304
+ input_ids: Token IDs (batch, seq_len)
305
+ attention_mask: Attention mask (batch, seq_len)
306
+ labels: Ground truth labels (optional, will be sampled if not provided
307
+ or if config.sample_labels is True)
308
+
309
+ Returns:
310
+ Loss value for this batch
311
+ """
312
+ self.model.train() # Need gradients
313
+
314
+ # Move to device
315
+ input_ids = input_ids.to(self.config.device)
316
+ if attention_mask is not None:
317
+ attention_mask = attention_mask.to(self.config.device)
318
+
319
+ # Forward pass
320
+ with torch.enable_grad():
321
+ outputs = self.model(
322
+ input_ids=input_ids,
323
+ attention_mask=attention_mask,
324
+ use_cache=False,
325
+ )
326
+ logits = outputs.logits
327
+
328
+ # Get labels for loss computation
329
+ if self.config.sample_labels or labels is None:
330
+ # Sample from model's distribution (proper FIM)
331
+ sampled_labels = self._sample_labels(logits)
332
+ # Shift for causal LM
333
+ shift_labels = sampled_labels[:, 1:].contiguous()
334
+ shift_logits = logits[:, :-1, :].contiguous()
335
+ else:
336
+ # Use provided labels
337
+ shift_labels = labels[:, 1:].contiguous().to(self.config.device)
338
+ shift_logits = logits[:, :-1, :].contiguous()
339
+
340
+ # Compute loss
341
+ loss_fn = nn.CrossEntropyLoss()
342
+ loss = loss_fn(
343
+ shift_logits.view(-1, shift_logits.shape[-1]),
344
+ shift_labels.view(-1)
345
+ )
346
+
347
+ # Backward pass to populate gradient buffers
348
+ loss.backward()
349
+
350
+ # Update statistics from buffers
351
+ self._update_statistics()
352
+
353
+ # Zero gradients for next batch
354
+ self.model.zero_grad()
355
+
356
+ return loss.item()
357
+
358
+ def collect_from_dataloader(
359
+ self,
360
+ dataloader,
361
+ max_tokens: int = 20_000_000,
362
+ progress_bar: bool = True,
363
+ ) -> dict:
364
+ """
365
+ Collect K-FAC statistics from a dataloader.
366
+
367
+ Args:
368
+ dataloader: PyTorch DataLoader yielding batches with input_ids
369
+ max_tokens: Maximum number of tokens to process
370
+ progress_bar: Whether to show progress bar
371
+
372
+ Returns:
373
+ Dictionary with collection statistics
374
+ """
375
+ if not self._hooks_registered:
376
+ self.register_hooks()
377
+
378
+ total_tokens = 0
379
+ total_loss = 0.0
380
+ n_batches = 0
381
+
382
+ iterator = tqdm(dataloader, desc="Collecting K-FAC stats") if progress_bar else dataloader
383
+
384
+ for batch in iterator:
385
+ if isinstance(batch, dict):
386
+ input_ids = batch["input_ids"]
387
+ attention_mask = batch.get("attention_mask")
388
+ else:
389
+ input_ids = batch[0]
390
+ attention_mask = batch[1] if len(batch) > 1 else None
391
+
392
+ batch_tokens = input_ids.numel()
393
+
394
+ loss = self.collect_batch(input_ids, attention_mask)
395
+
396
+ total_tokens += batch_tokens
397
+ total_loss += loss
398
+ n_batches += 1
399
+
400
+ if progress_bar:
401
+ iterator.set_postfix({
402
+ "tokens": f"{total_tokens/1e6:.1f}M",
403
+ "loss": f"{loss:.3f}"
404
+ })
405
+
406
+ if total_tokens >= max_tokens:
407
+ break
408
+
409
+ return {
410
+ "total_tokens": total_tokens,
411
+ "n_batches": n_batches,
412
+ "avg_loss": total_loss / max(n_batches, 1),
413
+ }
414
+
415
+ def finalize(self) -> None:
416
+ """Finalize statistics by converting sums to means."""
417
+ for name, stat in self.stats.items():
418
+ stat.finalize()
419
+ print(f"Finalized {name}: A={stat.A.shape if stat.A is not None else None}, "
420
+ f"G={stat.G.shape if stat.G is not None else None}")
421
+
422
+ def save(self, path: str) -> None:
423
+ """Save K-FAC statistics to file."""
424
+ save_dict = {
425
+ "config": {
426
+ "target_layers": self.config.target_layers,
427
+ "target_projections": self.config.target_projections,
428
+ "seq_length": self.config.seq_length,
429
+ },
430
+ "statistics": {}
431
+ }
432
+
433
+ for name, stat in self.stats.items():
434
+ save_dict["statistics"][name] = {
435
+ "A": stat.A.cpu() if stat.A is not None else None,
436
+ "G": stat.G.cpu() if stat.G is not None else None,
437
+ "n_samples_A": stat.n_samples_A,
438
+ "n_samples_G": stat.n_samples_G,
439
+ }
440
+
441
+ torch.save(save_dict, path)
442
+ print(f"Saved K-FAC statistics to {path}")
443
+
444
+ @classmethod
445
+ def load(cls, path: str, model: nn.Module) -> "KFACCollector":
446
+ """Load K-FAC statistics from file."""
447
+ data = torch.load(path, map_location="cpu")
448
+
449
+ config = KFACConfig(
450
+ target_layers=data["config"]["target_layers"],
451
+ target_projections=data["config"]["target_projections"],
452
+ seq_length=data["config"]["seq_length"],
453
+ )
454
+
455
+ collector = cls(model, config)
456
+
457
+ for name, stat_data in data["statistics"].items():
458
+ collector.stats[name] = LayerStatistics(
459
+ A=stat_data["A"],
460
+ G=stat_data["G"],
461
+ n_samples_A=stat_data["n_samples_A"],
462
+ n_samples_G=stat_data["n_samples_G"],
463
+ )
464
+
465
+ print(f"Loaded K-FAC statistics from {path}")
466
+ return collector
467
+
468
+ def get_statistics(self) -> dict[str, tuple[Tensor, Tensor]]:
469
+ """
470
+ Get computed A and G matrices for all layers.
471
+
472
+ Returns:
473
+ Dictionary mapping layer names to (A, G) tuples
474
+ """
475
+ result = {}
476
+ for name, stat in self.stats.items():
477
+ if stat.A is not None and stat.G is not None:
478
+ result[name] = (stat.A, stat.G)
479
+ return result
480
+
481
+
482
+ def create_dataloader(
483
+ dataset_name: str = "allenai/dolma",
484
+ dataset_config: str = "v1_6-sample",
485
+ tokenizer = None,
486
+ batch_size: int = 4,
487
+ seq_length: int = 512,
488
+ max_samples: Optional[int] = None,
489
+ streaming: bool = True,
490
+ shuffle_buffer: int = 10000,
491
+ seed: int = 42,
492
+ ):
493
+ """
494
+ Create a DataLoader for K-FAC collection.
495
+
496
+ Args:
497
+ dataset_name: HuggingFace dataset name
498
+ dataset_config: Dataset configuration/subset name
499
+ tokenizer: Tokenizer for the model
500
+ batch_size: Batch size
501
+ seq_length: Sequence length for tokenization
502
+ max_samples: Maximum number of samples to load
503
+ streaming: Whether to use streaming mode
504
+ shuffle_buffer: Buffer size for streaming shuffle
505
+ seed: Random seed
506
+
507
+ Returns:
508
+ PyTorch DataLoader
509
+ """
510
+ from datasets import load_dataset
511
+ from torch.utils.data import DataLoader, IterableDataset
512
+
513
+ # Load dataset
514
+ if dataset_config:
515
+ ds = load_dataset(dataset_name, name=dataset_config, split="train", streaming=streaming)
516
+ else:
517
+ ds = load_dataset(dataset_name, split="train", streaming=streaming)
518
+
519
+ if streaming:
520
+ ds = ds.shuffle(buffer_size=shuffle_buffer, seed=seed)
521
+
522
+ # Tokenization function
523
+ def tokenize_fn(examples):
524
+ # Handle different column names
525
+ text_column = "text" if "text" in examples else list(examples.keys())[0]
526
+ texts = examples[text_column]
527
+
528
+ tokenized = tokenizer(
529
+ texts,
530
+ truncation=True,
531
+ max_length=seq_length,
532
+ padding="max_length",
533
+ return_tensors="pt",
534
+ )
535
+ return tokenized
536
+
537
+ # Create streaming dataset wrapper
538
+ class TokenizedIterableDataset(IterableDataset):
539
+ def __init__(self, dataset, tokenizer, seq_length, max_samples):
540
+ self.dataset = dataset
541
+ self.tokenizer = tokenizer
542
+ self.seq_length = seq_length
543
+ self.max_samples = max_samples
544
+
545
+ def __iter__(self):
546
+ count = 0
547
+ for example in self.dataset:
548
+ if self.max_samples and count >= self.max_samples:
549
+ break
550
+
551
+ # Get text
552
+ text = example.get("text", list(example.values())[0])
553
+ if not text:
554
+ continue
555
+
556
+ # Tokenize
557
+ tokens = self.tokenizer(
558
+ text,
559
+ truncation=True,
560
+ max_length=self.seq_length,
561
+ padding="max_length",
562
+ return_tensors="pt",
563
+ )
564
+
565
+ yield {
566
+ "input_ids": tokens["input_ids"].squeeze(0),
567
+ "attention_mask": tokens["attention_mask"].squeeze(0),
568
+ }
569
+ count += 1
570
+
571
+ torch_dataset = TokenizedIterableDataset(ds, tokenizer, seq_length, max_samples)
572
+
573
+ dataloader = DataLoader(
574
+ torch_dataset,
575
+ batch_size=batch_size,
576
+ num_workers=0, # Streaming doesn't work well with multiple workers
577
+ )
578
+
579
+ return dataloader