Download code/wp/rank.py from Broyojo/world-pretraining-runs: direct link, hf CLI and curl.
- Browser
- Download file 3.01 kB
-
https://huggingface.co/Broyojo/world-pretraining-runs/resolve/main/code/wp/rank.py
- Command line
-
hf download hf://Broyojo/world-pretraining-runs/code/wp/rank.py
-
curl -L -o rank.py https://huggingface.co/Broyojo/world-pretraining-runs/resolve/main/code/wp/rank.py
3.01 kB
| """Effective rank of final-layer features and per-layer dormant MLP units, at init and after training. | |
| Effective rank (Roy & Vetterli 2007): exp(entropy of the normalized singular values). | |
| Dormant units (Sokar et al. 2023, ReDo): mean |activation| / layer mean <= tau, for the inputs to down_proj. | |
| Usage: python wp/rank.py --data val.bin --out rank.json \ | |
| --init name:repo:init[:lambda[:shuffle]] ... --runs RUN ... | |
| """ | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| from types import SimpleNamespace | |
| import numpy as np | |
| import torch | |
| from huggingface_hub import snapshot_download | |
| from transformers import LlamaForCausalLM | |
| from train import build_model | |
| REPO = "Broyojo/world-pretraining-runs" | |
| N_SEQ, SEQ, TAU = 16, 512, 0.1 | |
| def measure(model, x): | |
| feats, scores, hooks = [], [], [] | |
| for layer in model.model.layers: | |
| hooks.append(layer.mlp.down_proj.register_forward_pre_hook( | |
| lambda _, inp: scores.append(inp[0].float().abs().mean((0, 1)).cpu()))) | |
| h = model.model(input_ids=x).last_hidden_state.float() | |
| for hook in hooks: | |
| hook.remove() | |
| s = torch.linalg.svdvals(h.flatten(0, 1)) | |
| p = s / s.sum() | |
| per_layer = [float((u / u.mean() <= TAU).float().mean()) for u in scores] | |
| return {"eff_rank": float((-(p * torch.log(p.clamp_min(1e-12))).sum()).exp()), | |
| "dormant": float(np.mean(per_layer)), "per_layer_dormant": [round(v, 4) for v in per_layer]} | |
| def main(): | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--data", required=True) | |
| p.add_argument("--out", required=True) | |
| p.add_argument("--init", nargs="*", default=[]) | |
| p.add_argument("--runs", nargs="*", default=[]) | |
| p.add_argument("--cache", default="rank_cache") | |
| args = p.parse_args() | |
| device = "cuda" | |
| val = np.memmap(args.data, dtype=np.uint16, mode="r") | |
| x = torch.from_numpy(np.stack([val[i * SEQ:(i + 1) * SEQ] for i in range(N_SEQ)]).astype(np.int64)).to(device) | |
| results = {} | |
| for spec in args.init: | |
| name, repo, init, *rest = spec.split(":") | |
| lam = float(rest[0]) if rest else 0.5 | |
| a = SimpleNamespace(repo=repo, init=init, extra_layers=0, seq_len=1024, seed=0, sp_lambda=lam, | |
| sp_only="all", sp_shuffle=len(rest) > 1) | |
| model = build_model(a).to(device).eval() | |
| results[f"init/{name}"] = measure(model, x) | |
| print(name, results[f"init/{name}"]["eff_rank"], results[f"init/{name}"]["dormant"], flush=True) | |
| del model | |
| for run in args.runs: | |
| path = snapshot_download(REPO, allow_patterns=f"runs/{run}/*", local_dir=Path(args.cache)) | |
| model = LlamaForCausalLM.from_pretrained(f"{path}/runs/{run}", torch_dtype=torch.float32).to(device).eval() | |
| results[f"trained/{run}"] = measure(model, x) | |
| print(run, results[f"trained/{run}"]["eff_rank"], results[f"trained/{run}"]["dormant"], flush=True) | |
| del model | |
| Path(args.out).write_text(json.dumps(results, indent=1)) | |
| if __name__ == "__main__": | |
| main() | |