File size: 14,657 Bytes
3bbd5dd | 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 | """Phase 4a: gradient conflict between the next-token objective and the
further-ahead objectives on the shared trunk, split by word boundaries.
Multi-token prediction trains one shared trunk under a sum of objectives,
sum_k L_k, where predictor k reads the trunk at position p and predicts the
token at p + k. D = BPB(MTP) - BPB(NTP) > 0 says the extra objectives cost
the next-token objective something; this script measures where that
competition happens.
For a trained stack, the frozen backbone encodes held-out documents once
(no gradient) and the trunk output is the meeting point of the objectives.
Per position p:
g_k(p) = d loss_k(p) / d trunk_output(p)
cos(g_1(p), g_k(p)) > 0 means predictor k pulls the shared representation
the same way as the next-token predictor; < 0 means it pulls against it
(conflict). Backpropagating g_k through the trunk gives the parameter-space
gradient G_k, and cos(G_1, G_k) is the conflict the optimizer actually sees
when it sums the losses.
Positions are split two ways, for the pair (1, k) at position p:
* crosses_word: predictor k's target (token p+k) lies in a different word
from the next token (token p+1), i.e. a word starts somewhere in
tokens p+2 .. p+k;
* next_starts_word: the next token (p+1) itself begins a word.
Word starts use the same offset rule as the Phase 3 per-head accuracy split
(src.train.evaluate.word_start_flags), so the two analyses agree on what a
boundary is.
"""
import argparse
import csv
import logging
import os
import sys
import time
from pathlib import Path
os.environ.setdefault("CUDA_DEVICE_ORDER", "PCI_BUS_ID")
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import torch
import torch.nn.functional as F
import yaml
from src.train.evaluate import word_start_flags
from src.train.model import MTPStack
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("huggingface_hub").setLevel(logging.WARNING)
logger = logging.getLogger("phase4a")
DEVICE = "cuda:0" # the caller restricts the process to one physical GPU
N_HEADS = 4
PARAM_SPLITS = ("all", "crosses_word", "same_word")
def pair_masks(starts: list, k: int) -> tuple:
"""Boundary masks for the predictor pair (1, k) over positions p = 0 .. len(starts) - k - 1.
Predictor 1 at p targets token p+1; predictor k at p targets token p+k.
Only positions where both have a target are returned.
Args:
starts: per-token word-start flags for the whole document.
k: the further predictor's offset, >= 2.
Returns:
(next_starts_word, crosses_word): two lists of bools, one per position.
"""
n_positions = len(starts) - k
next_starts = [bool(starts[p + 1]) for p in range(n_positions)]
crosses = [any(starts[p + 2 : p + k + 1]) for p in range(n_positions)]
return next_starts, crosses
def per_position_grads(stack: MTPStack, trunk_out: torch.Tensor, block: torch.Tensor) -> dict:
"""Gradient of each predictor's summed loss with respect to the trunk output.
Every head is position-wise (ResBlock then unembedding), so row p of the
returned (seq, hidden) tensor is exactly d loss_k(p) / d trunk_output(p);
rows p >= seq - k have no target and come back as zeros.
Args:
stack: the trained multi-head stack.
trunk_out: (1, seq, hidden) trunk output, a leaf requiring grad.
block: (1, seq) token ids.
"""
seq = block.shape[1]
grads = {}
for k in range(1, stack.n_heads + 1):
logits = stack.head_logits(trunk_out, k - 1)[:, : seq - k, :]
targets = block[:, k:]
loss = F.cross_entropy(logits.reshape(-1, logits.shape[-1]), targets.reshape(-1), reduction="sum")
grads[k] = torch.autograd.grad(loss, trunk_out)[0][0].detach()
del logits, loss
return grads
def load_stack(backbone, ckpt_path: Path) -> MTPStack:
"""Rebuild a trained shared-trunk stack around the backbone's frozen unembedding.
The checkpoint also stores the unembedding under every head; those
entries are the backbone's own frozen lm_head and are skipped rather
than copied back over it.
"""
stack = MTPStack(backbone.config.hidden_size, backbone.lm_head, N_HEADS, use_shared_trunk=True).to(DEVICE)
state = torch.load(ckpt_path, map_location="cpu", weights_only=True)
state = {k: v for k, v in state.items() if ".unembedding." not in k}
missing, unexpected = stack.load_state_dict(state, strict=False)
if unexpected or any(".unembedding." not in m for m in missing):
raise RuntimeError(f"checkpoint mismatch: missing={missing} unexpected={unexpected}")
for p in stack.parameters():
p.requires_grad_(False)
for p in stack.trunk.parameters():
p.requires_grad_(True)
stack.eval()
return stack
def summarize(values: torch.Tensor) -> dict:
if values.numel() == 0:
return {"mean": float("nan"), "median": float("nan"), "frac_negative": float("nan"), "n": 0}
return {
"mean": float(values.mean()),
"median": float(values.median()),
"frac_negative": float((values < 0).float().mean()),
"n": int(values.numel()),
}
def analyse_checkpoint(backbone, tokenizer, stack: MTPStack, texts: list, max_tokens: int) -> list:
"""Per-position and parameter-level conflict for one checkpoint; returns CSV-ready dicts."""
trunk_params = list(stack.trunk.parameters())
cos_by = {k: {"all": [], "crosses_word": [], "same_word": [], "next_starts_word": [], "next_continues_word": []} for k in range(2, N_HEADS + 1)}
cells = {k: {(c, s): [] for c in (True, False) for s in (True, False)} for k in range(2, N_HEADS + 1)}
norm1 = {k: [] for k in range(2, N_HEADS + 1)}
normk = {k: [] for k in range(2, N_HEADS + 1)}
param_acc = {(k, split, who): None for k in range(2, N_HEADS + 1) for split in PARAM_SPLITS for who in (1, k)}
per_doc_param_cos = {k: [] for k in range(2, N_HEADS + 1)}
n_docs = 0
n_positions = 0
for text in texts:
enc = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True, truncation=True, max_length=max_tokens)
ids = enc.input_ids
if len(ids) < N_HEADS + 4:
continue
starts = word_start_flags(text, enc.offset_mapping)
block = torch.tensor([ids], dtype=torch.long, device=DEVICE)
seq = len(ids)
with torch.no_grad():
hidden = backbone.model(input_ids=block).last_hidden_state
with torch.enable_grad():
trunk_out = stack.trunk_states(hidden)
leaf = trunk_out.detach().requires_grad_(True)
grads = per_position_grads(stack, leaf, block)
for k in range(2, N_HEADS + 1):
valid = seq - k
g1 = grads[1][:valid]
gk = grads[k][:valid]
cos = F.cosine_similarity(g1, gk, dim=-1, eps=1e-12).cpu()
next_starts, crosses = pair_masks(starts, k)
next_starts_t = torch.tensor(next_starts, dtype=torch.bool)
crosses_t = torch.tensor(crosses, dtype=torch.bool)
cos_by[k]["all"].append(cos)
cos_by[k]["crosses_word"].append(cos[crosses_t])
cos_by[k]["same_word"].append(cos[~crosses_t])
cos_by[k]["next_starts_word"].append(cos[next_starts_t])
cos_by[k]["next_continues_word"].append(cos[~next_starts_t])
for c in (True, False):
for s in (True, False):
mask = (crosses_t == c) & (next_starts_t == s)
cells[k][(c, s)].append(cos[mask])
norm1[k].append(g1.norm(dim=-1).cpu())
normk[k].append(gk.norm(dim=-1).cpu())
# parameter space: push the masked per-position gradients back through the trunk
masks = {
"all": torch.ones(valid, dtype=torch.bool),
"crosses_word": crosses_t,
"same_word": ~crosses_t,
}
for split, mask in masks.items():
weight = torch.zeros(seq, device=DEVICE)
weight[:valid] = mask.to(DEVICE).float()
for who, g in ((1, grads[1]), (k, grads[k])):
out_grad = (g * weight[:, None]).unsqueeze(0)
pg = torch.autograd.grad(trunk_out, trunk_params, grad_outputs=out_grad, retain_graph=True)
flat = torch.cat([t.reshape(-1) for t in pg])
key = (k, split, who)
param_acc[key] = flat if param_acc[key] is None else param_acc[key] + flat
if split == "all":
if who == 1:
doc_g1 = flat
else:
per_doc_param_cos[k].append(float(F.cosine_similarity(doc_g1, flat, dim=0, eps=1e-12)))
del trunk_out, leaf, grads
n_docs += 1
n_positions += seq
rows = []
for k in range(2, N_HEADS + 1):
for split, chunks in cos_by[k].items():
s = summarize(torch.cat(chunks))
for metric in ("mean", "median", "frac_negative"):
rows.append({"k": k, "level": "position", "split": split, "metric": f"cos_{metric}" if metric != "frac_negative" else "frac_conflict", "value": s[metric], "n": s["n"]})
for (c, s_), chunks in cells[k].items():
split = f"{'crosses' if c else 'same'}_word__next_{'starts' if s_ else 'continues'}"
s = summarize(torch.cat(chunks))
rows.append({"k": k, "level": "position", "split": split, "metric": "cos_mean", "value": s["mean"], "n": s["n"]})
rows.append({"k": k, "level": "position", "split": split, "metric": "frac_conflict", "value": s["frac_negative"], "n": s["n"]})
n1 = torch.cat(norm1[k])
nk = torch.cat(normk[k])
rows.append({"k": k, "level": "position", "split": "all", "metric": "grad_norm_pred1_mean", "value": float(n1.mean()), "n": int(n1.numel())})
rows.append({"k": k, "level": "position", "split": "all", "metric": f"grad_norm_pred{k}_mean", "value": float(nk.mean()), "n": int(nk.numel())})
for split in PARAM_SPLITS:
g1 = param_acc[(k, split, 1)]
gk = param_acc[(k, split, k)]
rows.append({"k": k, "level": "parameter", "split": split, "metric": "cos_aggregate", "value": float(F.cosine_similarity(g1, gk, dim=0, eps=1e-12)), "n": n_docs})
rows.append({"k": k, "level": "parameter", "split": split, "metric": "norm_ratio_predk_over_pred1", "value": float(gk.norm() / g1.norm()), "n": n_docs})
doc_cos = torch.tensor(per_doc_param_cos[k])
rows.append({"k": k, "level": "parameter", "split": "all", "metric": "cos_per_doc_mean", "value": float(doc_cos.mean()), "n": int(doc_cos.numel())})
rows.append({"k": k, "level": "parameter", "split": "all", "metric": "cos_per_doc_std", "value": float(doc_cos.std()), "n": int(doc_cos.numel())})
rows.append({"k": k, "level": "parameter", "split": "all", "metric": "frac_docs_conflict", "value": float((doc_cos < 0).float().mean()), "n": int(doc_cos.numel())})
rows.append({"k": 0, "level": "meta", "split": "all", "metric": "docs", "value": n_docs, "n": n_docs})
rows.append({"k": 0, "level": "meta", "split": "all", "metric": "tokens", "value": n_positions, "n": n_docs})
return rows
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--config", default="configs/phase3.yaml")
p.add_argument("--runs", nargs="+", default=["L4_seed0", "L4_seed1", "L2_seed0", "E1_seed0"], help="checkpoint directory names")
p.add_argument("--n-docs", type=int, default=128)
p.add_argument("--max-tokens", type=int, default=512)
p.add_argument("--out", default="results/phase4_gradient_conflict.csv")
return p.parse_args()
def main() -> None:
from transformers import AutoModelForCausalLM, AutoTokenizer
from src.train.data import load_heldout_texts
args = parse_args()
with open(args.config, encoding="utf-8") as f:
cfg = yaml.safe_load(f)
started = time.perf_counter()
tokenizer = AutoTokenizer.from_pretrained(cfg["backbone"]["hf_id"])
backbone = AutoModelForCausalLM.from_pretrained(cfg["backbone"]["hf_id"], dtype=torch.float32).to(DEVICE)
backbone.eval()
for param in backbone.parameters():
param.requires_grad = False
out_rows = [["run", "condition", "seed", "k", "level", "split", "metric", "value", "n"]]
for run in args.runs:
condition, seed = run.split("_")
run_start = time.perf_counter()
stack = load_stack(backbone, Path(cfg["checkpoint_dir"]) / run / "mtp.pt")
texts = load_heldout_texts(str(Path(cfg["data_dir"]) / f"{condition}_heldout.jsonl"))[: args.n_docs]
rows = analyse_checkpoint(backbone, tokenizer, stack, texts, args.max_tokens)
for r in rows:
out_rows.append([run, condition, seed, r["k"], r["level"], r["split"], r["metric"], f"{r['value']:.6f}" if isinstance(r["value"], float) else r["value"], r["n"]])
elapsed = time.perf_counter() - run_start
out_rows.append([run, condition, seed, 0, "meta", "all", "wall_seconds", f"{elapsed:.1f}", 1])
summary = {(r["k"], r["level"], r["split"], r["metric"]): r["value"] for r in rows}
logger.info(
"%s: pos cos(1,2)=%.3f cos(1,4)=%.3f | param cos(1,2)=%.3f cos(1,4)=%.3f | %.0fs",
run,
summary[(2, "position", "all", "cos_mean")], summary[(4, "position", "all", "cos_mean")],
summary[(2, "parameter", "all", "cos_aggregate")], summary[(4, "parameter", "all", "cos_aggregate")],
elapsed,
)
del stack
torch.cuda.empty_cache()
peak = torch.cuda.max_memory_allocated(DEVICE) / (1024**2)
out_rows.append(["all", "all", "all", 0, "meta", "all", "peak_gpu_mib", f"{peak:.1f}", 1])
out_rows.append(["all", "all", "all", 0, "meta", "all", "total_wall_seconds", f"{time.perf_counter() - started:.1f}", 1])
out_rows.append(["all", "all", "all", 0, "meta", "all", "gpu", torch.cuda.get_device_name(DEVICE), 1])
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
with open(args.out, "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(out_rows)
logger.info("wrote %s", args.out)
if __name__ == "__main__":
main()
|