File size: 11,003 Bytes
29973d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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(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(min(3, torch.get_num_threads()))
    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}