""" 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