"""Train an option scorer, then adapt the last pinned MiniLM transformer block.""" from collections import defaultdict from hashlib import sha256 from pathlib import Path import resource from time import perf_counter import numpy as np import torch from safetensors.torch import load_file, save_file from torch import nn from transformers import AutoModel, AutoTokenizer from .baseline import by_cell, scores from .sources import AGES, CELLS, EDUCATION, digest, object_hash, write BASE_FILES = ("config.json", "model.safetensors", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json", "vocab.txt") class OptionScorer(nn.Module): def __init__(self, hidden): super().__init__() self.population = nn.Embedding(len(CELLS) + 1, 12) self.scorer = nn.Sequential(nn.Linear(hidden + 12, 64), nn.GELU(), nn.Linear(64, 1)) def forward(self, text): # Population interactions are inside the nonlinear option scorer. population = self.population.weight[:, None, :].expand(-1, text.shape[0], -1) option_text = text[None, :, :].expand(population.shape[0], -1, -1) return self.scorer(torch.cat([option_text, population], dim=-1)).squeeze(-1) def inputs(question): ordered = question["options"] instrument = " | ".join(filter(None, [question["preceding_context"], question["question_text"], question["stimulus_text"]])) prompt = ("2024 CES pre-election survey, US citizen adults, English. " f"Format: {question['response_type']}. {instrument} " f"Offered answers in order: {' | '.join(o['label'] for o in ordered)}.") return [[prompt, option["label"]] for option in ordered] def encode_tokens(tokenizer, question, maximum): pairs = inputs(question) result = tokenizer([p[0] for p in pairs], [p[1] for p in pairs], padding=True, truncation=False, return_tensors="pt") if result.input_ids.shape[1] > maximum: raise ValueError(f"Instrument exceeds {maximum} tokens: {question['question_id']}") return result def pooled(encoder, tokens): hidden = encoder(**tokens).last_hidden_state mask = tokens.attention_mask[..., None] return torch.nn.functional.normalize((hidden * mask).sum(1) / mask.sum(1), dim=-1) def examples(df, rows): result = [] for q in rows: cells = by_cell(df, q) masses = [cells[key]["weight_sum"] for key in [*CELLS, "unknown"]] proportions = [cells[key]["probabilities"] or [0.] * len(q["options"]) for key in [*CELLS, "unknown"]] result.append((q, torch.tensor(proportions, dtype=torch.float32), torch.tensor(np.asarray(masses) / sum(masses), dtype=torch.float32))) return result def loss(logits, distribution, mass): return -(mass * (distribution * logits.log_softmax(dim=-1)).sum(-1)).sum() @torch.no_grad() def evaluate(model, embeddings, examples, detailed=False): sums = defaultdict(list) report = {} for q, reference, mass in examples: predicted = model(embeddings(q)).softmax(dim=-1) p = (mass @ predicted).numpy() observed = (mass @ reference).numpy() uniform = np.full(len(p), 1 / len(p)) reference_loss = scores(p, observed, q["ordinal_order"]) baseline = scores(uniform, observed, q["ordinal_order"]) row = {"prediction": p.tolist(), "observed": observed.tolist(), "scores": reference_loss, "uniform": baseline} if detailed: report[q["question_id"]] = row sums["cell_cross_entropy"].append(float(-(mass * (reference * predicted.log()).sum(-1)).sum())) for key in ("total_variation", "half_multiclass_brier"): sums[key].append(reference_loss[key]) sums[f"uniform_{key}"].append(baseline[key]) return {"means": {key: float(np.mean(values)) for key, values in sums.items()}, "rows": report} def optimize(model, embeddings, train, dev, params, count, batch, lr, generator, checkpoint): optimizer = torch.optim.AdamW(params, lr=lr) best, trace, best_step = float("inf"), [], 0 for step in range(1, count + 1): indices = generator.choice(len(train), size=batch, replace=False) optimizer.zero_grad() losses = [] for index in indices: question, distribution, mass = train[index] losses.append(loss(model(embeddings(question)), distribution, mass)) objective = torch.stack(losses).mean() if not torch.isfinite(objective): raise ValueError("Nonfinite training objective") objective.backward() torch.nn.utils.clip_grad_norm_(params, 1.0) optimizer.step() if step in (1, count) or step % max(1, count // 8) == 0: dev_objective = evaluate(model, embeddings, dev)["means"]["cell_cross_entropy"] trace.append({"step": step, "train_minibatch_cross_entropy": float(objective.detach()), "dev_cell_cross_entropy": dev_objective}) if dev_objective < best: best, best_step = dev_objective, step checkpoint() return {"steps": count, "selected_step": best_step, "trainable_parameters": sum(p.numel() for p in params), "trace": trace} def block_hash(block): h = sha256() for name, value in block.state_dict().items(): h.update(name.encode()) h.update(value.detach().contiguous().numpy().tobytes()) return h.hexdigest() def run(df, items, frozen, config, base_dir, output): t0 = perf_counter() seed = frozen["protocol"]["seed"] torch.set_num_threads(config["threads"]) torch.manual_seed(seed) torch.use_deterministic_algorithms(True) generator = np.random.default_rng(seed) tokenizer = AutoTokenizer.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False) encoder = AutoModel.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False).eval() encoder.requires_grad_(False) model = OptionScorer(encoder.config.hidden_size) block = encoder.encoder.layer[-1] initial_block_hash = block_hash(block) tokens = {q["question_id"]: encode_tokens(tokenizer, q, config["max_tokens"]) for q in items} groups = {s: [q for q in items if q["question_family_id"] in fs] for s, fs in frozen["protocol"]["family_split"].items()} train, dev = [examples(df[df.split == split], groups[split]) for split in ("train","dev")] def embed(q): return pooled(encoder, tokens[q["question_id"]]) with torch.no_grad(): cache = {q["question_id"]: embed(q) for q in groups["train"] + groups["dev"]} def cached(q): return cache[q["question_id"]] output = Path(output) output.mkdir(parents=True, exist_ok=True) probe_file = output / "probe.safetensors" adaptation_file = output / "adapter.safetensors" def save_probe(): save_file(model.state_dict(), probe_file) probe = optimize(model, cached, train, dev, list(model.parameters()), config["probe_steps"], config["batch_items"], config["probe_lr"], generator, save_probe) model.load_state_dict(load_file(probe_file)) block.requires_grad_(True) def save_adapter(): save_file({**{f"head.{k}": v for k,v in model.state_dict().items()}, **{f"last_block.{k}": v for k,v in block.state_dict().items()}}, adaptation_file) adapted = optimize(model, embed, train, dev, list(model.parameters()) + list(block.parameters()), config["adapt_steps"], config["batch_items"], config["adapt_lr"], generator, save_adapter) checkpoint = load_file(adaptation_file) adapted_block = {k.removeprefix("last_block."): v for k,v in checkpoint.items() if k.startswith("last_block.")} block.load_state_dict(adapted_block) selected_block_hash = block_hash(block) if initial_block_hash == selected_block_hash: raise ValueError("Selected encoder checkpoint did not change the final block") receipt = { "config": config, "base_files_sha256": {name: digest(Path(base_dir) / name) for name in BASE_FILES}, "protocol_sha256": object_hash(frozen), "probe": {**probe, "sha256": digest(probe_file)}, "encoder_finetuned": {**adapted, "sha256": digest(adaptation_file), "initial_block_sha256": initial_block_hash, "selected_block_sha256": selected_block_hash}, "final_test_opened_after_checkpoint_selection": True } write(output / "training.json", receipt) unseen = examples(df[df.split == "test"], groups["test"]) model.load_state_dict({k.removeprefix("head."): v for k,v in checkpoint.items() if k.startswith("head.")}) adapted_score = evaluate(model, embed, unseen, detailed=True) model.load_state_dict(load_file(probe_file)) encoder = AutoModel.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False).eval() probe_score = evaluate(model, embed, unseen, detailed=True) receipt.update({"elapsed_seconds": perf_counter() - t0, "linux_peak_rss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss}) write(output / "training.json", receipt) policy = frozen["protocol"]["unseen_family"] passed = len({q["question_family_id"] for q in groups["test"]}) >= policy["minimum_test_families_for_promotion"] passed = passed and adapted_score["means"]["total_variation"] <= policy["maximum_mean_tv_for_promotion"] passed = passed and (adapted_score["means"]["uniform_half_multiclass_brier"] - adapted_score["means"]["half_multiclass_brier"] >= policy["minimum_half_brier_improvement_for_promotion"]) write(output / "evaluation.json", {"track": "unseen_family_and_person", "family_counts": frozen["unseen_families_by_split"], "promotion_passed": passed, "frozen_encoder_probe": probe_score, "encoder_finetuned": adapted_score}) return receipt def predict_checkpoint(base_dir, checkpoint_path, question, cells, max_tokens=256): """Reproduce option-identified cell predictions from a published adapter.""" torch.set_num_threads(1) encoder = AutoModel.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False).eval() tokenizer = AutoTokenizer.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False) scorer = OptionScorer(encoder.config.hidden_size).eval() checkpoint = load_file(checkpoint_path) scorer.load_state_dict({k.removeprefix("head."): v for k,v in checkpoint.items() if k.startswith("head.")}) encoder.encoder.layer[-1].load_state_dict({k.removeprefix("last_block."): v for k,v in checkpoint.items() if k.startswith("last_block.")}) with torch.no_grad(): predicted = scorer(pooled(encoder, encode_tokens(tokenizer, question, max_tokens))).softmax(dim=-1) options = [o["id"] for o in question["options"]] return {cell: dict(zip(options, predicted[[*CELLS, "unknown"].index(cell)].tolist())) for cell in cells}