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