"""A deliberately small residual classifier and model-specific transformations. The pruning routine is valid for this Linear -> GELU -> Linear branch only. It is not a general Transformer, diffusion, or HDemucs pruning implementation. """ from __future__ import annotations from copy import deepcopy from dataclasses import asdict, dataclass from pathlib import Path import torch from torch import nn @dataclass(frozen=True) class Config: inputs: int = 16 width: int = 32 inner: int = 64 depth: int = 3 classes: int = 3 def __post_init__(self) -> None: if min(self.inputs, self.width, self.inner, self.classes) < 1: raise ValueError("Feature dimensions and class count must be positive.") if self.depth < 0: raise ValueError("Depth must be nonnegative.") class ResidualFFN(nn.Module): def __init__(self, width: int, inner: int) -> None: super().__init__() self.up = nn.Linear(width, inner) self.act = nn.GELU() self.down = nn.Linear(inner, width) def forward(self, x: torch.Tensor) -> torch.Tensor: return x + self.down(self.act(self.up(x))) class TinyNet(nn.Module): def __init__(self, config: Config = Config()) -> None: super().__init__() self.config = config self.stem = nn.Linear(config.inputs, config.width) self.blocks = nn.ModuleList([ ResidualFFN(config.width, config.inner) for _ in range(config.depth) ]) self.head = nn.Linear(config.width, config.classes) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.stem(x) for block in self.blocks: x = block(x) return self.head(x) # Raw class scores, not probabilities. def parameter_count(model: nn.Module) -> int: return sum(p.numel() for p in model.parameters()) def drop_block(model: TinyNet, index: int) -> TinyNet: if index != int(index): # A fractional index passes the range check below and then matches no block, # silently returning an unmodified copy. raise TypeError(f"Block index must be integral, got {index!r}.") index = int(index) if not 0 <= index < len(model.blocks): raise IndexError("Block index is out of range.") result = deepcopy(model) result.blocks = nn.ModuleList([ block for i, block in enumerate(result.blocks) if i != index ]) result.config = Config(**{**asdict(model.config), "depth": len(result.blocks)}) return result def prune_ffn(block: ResidualFFN, keep: torch.Tensor) -> ResidualFFN: """Physically retain selected inner units, preserving the residual width.""" if keep.ndim != 1 or keep.dtype != torch.long or keep.numel() == 0: raise ValueError("keep must be a nonempty one-dimensional int64 tensor.") if keep.unique().numel() != keep.numel(): raise ValueError("Duplicate channel indices are not allowed.") if int(keep.min()) < 0 or int(keep.max()) >= block.up.out_features: raise ValueError("Channel index is outside the original inner width.") device, dtype = block.up.weight.device, block.up.weight.dtype keep = keep.to(device) small = ResidualFFN(block.up.in_features, keep.numel()).to(device=device, dtype=dtype) with torch.no_grad(): small.up.weight.copy_(block.up.weight.index_select(0, keep)) small.up.bias.copy_(block.up.bias.index_select(0, keep)) small.down.weight.copy_(block.down.weight.index_select(1, keep)) small.down.bias.copy_(block.down.bias) small.train(block.training) # requires_grad is not part of state_dict, so a freshly constructed module is # trainable regardless of the source block. Restore the caller's flags, or a # frozen block silently becomes trainable again after pruning. for dst, src in zip(small.parameters(), block.parameters()): dst.requires_grad_(src.requires_grad) return small def shrink_inner(model: TinyNet, inner: int) -> TinyNet: if not 1 <= inner <= model.config.inner: raise ValueError("Requested inner width must be in [1, original width].") result = deepcopy(model) for i, block in enumerate(result.blocks): # A ranking heuristic, not a proof of task importance. score = block.up.weight.detach().abs().sum(dim=1) keep = torch.topk(score, k=inner).indices.sort().values result.blocks[i] = prune_ffn(block, keep) result.config = Config(**{**asdict(result.config), "inner": inner}) return result def save_model(model: TinyNet, path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) torch.save({"schema": 1, "config": asdict(model.config), # Record the dtype: state_dict alone does not tell load_model what # precision to reconstruct, so a half-precision model would come back # as float32 while the file on disk was genuinely smaller. "dtype": str(next(model.parameters()).dtype), "state_dict": model.state_dict()}, path) def load_model(path: Path) -> TinyNet: # Use only trusted artifacts. weights_only reduces the pickle attack surface; # it is not a trust guarantee for an arbitrary download. payload = torch.load(path, map_location="cpu", weights_only=True) if payload.get("schema") != 1: raise ValueError("Unsupported checkpoint schema.") model = TinyNet(Config(**payload["config"])) # load_state_dict copies into the existing parameters, so without this a # half-precision checkpoint would silently load back as float32. stored = payload.get("dtype") if stored is not None: model = model.to(getattr(torch, str(stored).replace("torch.", ""))) model.load_state_dict(payload["state_dict"], strict=True) return model.eval()