Skip to content

Commit bb2e524

Browse files
committed
Score probes by answer log-probability and interpolate convergence steps
Candidates are scored with a terminating newline so a one-digit answer no longer wins over a two-digit answer it prefixes. Probe claims use the gain in candidate-normalised answer log-probability; accuracy is kept alongside. Convergence deltas interpolate between eval points and are negative when the task-pretrained run ends worse.
1 parent f5f48d9 commit bb2e524

7 files changed

Lines changed: 284 additions & 120 deletions

File tree

‎src/pptrain/replication/probes.py‎

Lines changed: 66 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -27,38 +27,69 @@ def _prepare_model_for_generation(model: PreTrainedModel) -> PreTrainedModel:
2727
return model
2828

2929

30+
# Every candidate is scored with this terminator appended, so a short answer that is a prefix
31+
# of a longer one (" 2" vs " 24") does not win just by having fewer tokens to pay for.
32+
ANSWER_TERMINATOR = "\n"
33+
34+
3035
def _score_candidates(
3136
*,
3237
model: PreTrainedModel,
3338
tokenizer: PreTrainedTokenizerBase,
3439
prompt: str,
3540
candidates: list[str],
3641
) -> dict[str, float]:
42+
"""Return log p(" <candidate>\\n" | prompt) for every candidate.
43+
44+
The prompt is encoded once; its key-value cache is shared by one batched forward over
45+
the right-padded continuations (padding sits after every scored position, so causal
46+
attention leaves the scored positions unaffected).
47+
"""
3748
device = next(model.parameters()).device
3849
prompt_ids = tokenizer(prompt, add_special_tokens=False, return_tensors="pt")["input_ids"].to(device)
39-
scores: dict[str, float] = {}
50+
continuations = [
51+
tokenizer(f" {candidate}{ANSWER_TERMINATOR}", add_special_tokens=False)["input_ids"] for candidate in candidates
52+
]
53+
max_length = max(len(ids) for ids in continuations)
54+
pad_id = continuations[0][-1]
55+
batch = torch.tensor([ids + [pad_id] * (max_length - len(ids)) for ids in continuations], device=device)
56+
lengths = torch.tensor([len(ids) for ids in continuations], device=device)
4057
with torch.no_grad():
41-
for candidate in candidates:
42-
continuation = tokenizer(f" {candidate}", add_special_tokens=False, return_tensors="pt")["input_ids"].to(device)
43-
full_ids = torch.cat([prompt_ids, continuation], dim=1)
44-
logits = model(full_ids).logits[:, :-1, :]
45-
target_ids = full_ids[:, 1:]
46-
log_probs = F.log_softmax(logits, dim=-1)
47-
gathered = log_probs.gather(-1, target_ids.unsqueeze(-1)).squeeze(-1)
48-
continuation_log_probs = gathered[:, prompt_ids.shape[1] - 1 :]
49-
scores[candidate] = float(continuation_log_probs.sum().item())
50-
return scores
51-
52-
53-
def _select_best_candidate(
54-
*,
55-
model: PreTrainedModel,
56-
tokenizer: PreTrainedTokenizerBase,
57-
prompt: str,
58-
candidates: list[str],
59-
) -> str:
60-
scores = _score_candidates(model=model, tokenizer=tokenizer, prompt=prompt, candidates=candidates)
61-
return max(candidates, key=lambda candidate: scores[candidate])
58+
prompt_out = model(prompt_ids, use_cache=True, logits_to_keep=1)
59+
cache = prompt_out.past_key_values
60+
cache.batch_repeat_interleave(len(candidates))
61+
first_log_probs = F.log_softmax(prompt_out.logits[:, -1, :].float(), dim=-1)
62+
rest_logits = model(batch[:, :-1], past_key_values=cache, use_cache=True).logits if max_length > 1 else None
63+
token_log_probs = first_log_probs.expand(len(candidates), -1).gather(-1, batch[:, :1])
64+
if rest_logits is not None:
65+
rest_log_probs = F.log_softmax(rest_logits.float(), dim=-1).gather(-1, batch[:, 1:].unsqueeze(-1)).squeeze(-1)
66+
token_log_probs = torch.cat([token_log_probs, rest_log_probs], dim=1)
67+
mask = torch.arange(max_length, device=device).unsqueeze(0) < lengths.unsqueeze(1)
68+
totals = (token_log_probs * mask).sum(dim=1).tolist()
69+
return {candidate: float(total) for candidate, total in zip(candidates, totals)}
70+
71+
72+
def _answer_metrics(scores: list[dict[str, float]], answers: list[str]) -> dict[str, float]:
73+
"""Exact-answer accuracy plus the continuous answer log-probability.
74+
75+
``answer_log_prob`` is the mean log-probability of the correct answer after renormalising
76+
over the candidate set; ``chance_log_prob`` = -log(number of candidates) is its value for a
77+
model that is indifferent between candidates.
78+
"""
79+
correct = 0
80+
log_probs = []
81+
for candidate_scores, answer in zip(scores, answers):
82+
values = np.asarray(list(candidate_scores.values()), dtype=float)
83+
normaliser = float(np.logaddexp.reduce(values))
84+
log_probs.append(candidate_scores[answer] - normaliser)
85+
correct += int(max(candidate_scores, key=candidate_scores.__getitem__) == answer)
86+
count = max(len(answers), 1)
87+
num_candidates = len(scores[0]) if scores else 1
88+
return {
89+
"accuracy": correct / count,
90+
"answer_log_prob": float(np.mean(log_probs)) if log_probs else float("nan"),
91+
"chance_log_prob": -float(np.log(num_candidates)),
92+
}
6293

6394

6495
def run_arithmetic_probe(
@@ -69,26 +100,22 @@ def run_arithmetic_probe(
69100
) -> EvalResult:
70101
model = _prepare_model_for_generation(model)
71102
rng = np.random.default_rng(42)
72-
correct = 0
103+
candidates = [str(value) for value in range(2, config.max_addend * 2 + 1)]
104+
scores = []
105+
answers = []
73106
for _ in range(config.num_examples):
74107
left = int(rng.integers(1, config.max_addend + 1))
75108
right = int(rng.integers(1, config.max_addend + 1))
76109
prompt = (
77110
"Solve the arithmetic problem and answer with the number only.\n"
78111
f"Question: What is {left} + {right}?\nAnswer:"
79112
)
80-
prediction = _select_best_candidate(
81-
model=model,
82-
tokenizer=tokenizer,
83-
prompt=prompt,
84-
candidates=[str(value) for value in range(2, config.max_addend * 2 + 1)],
85-
)
86-
correct += int(prediction == str(left + right))
87-
accuracy = correct / max(config.num_examples, 1)
113+
scores.append(_score_candidates(model=model, tokenizer=tokenizer, prompt=prompt, candidates=candidates))
114+
answers.append(str(left + right))
88115
return EvalResult(
89116
name="arithmetic_probe",
90-
metrics={"accuracy": accuracy},
91-
artifacts={"num_examples": config.num_examples, "mode": "candidate_logprob"},
117+
metrics=_answer_metrics(scores, answers),
118+
artifacts={"num_examples": config.num_examples, "mode": "candidate_logprob_terminated"},
92119
)
93120

94121

@@ -101,7 +128,8 @@ def run_needle_probe(
101128
model = _prepare_model_for_generation(model)
102129
rng = np.random.default_rng(13)
103130
values = list("123456789")
104-
correct = 0
131+
scores = []
132+
answers = []
105133
for example_index in range(config.num_examples):
106134
target_slot = int(rng.integers(0, config.haystack_size))
107135
lines = ["Remember the key value map and answer with the value only."]
@@ -115,18 +143,12 @@ def run_needle_probe(
115143
lines.append(f"{key}: {value}")
116144
lines.append(f"Question: What is the value for {target_key}?")
117145
lines.append("Answer:")
118-
prediction = _select_best_candidate(
119-
model=model,
120-
tokenizer=tokenizer,
121-
prompt="\n".join(lines),
122-
candidates=values,
123-
)
124-
correct += int(prediction == target_answer)
125-
accuracy = correct / max(config.num_examples, 1)
146+
scores.append(_score_candidates(model=model, tokenizer=tokenizer, prompt="\n".join(lines), candidates=values))
147+
answers.append(target_answer)
126148
return EvalResult(
127149
name="needle_probe",
128-
metrics={"accuracy": accuracy},
129-
artifacts={"num_examples": config.num_examples, "mode": "candidate_logprob"},
150+
metrics=_answer_metrics(scores, answers),
151+
artifacts={"num_examples": config.num_examples, "mode": "candidate_logprob_terminated"},
130152
)
131153

132154

‎src/pptrain/replication/reporting.py‎

Lines changed: 44 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ def _build_report_markdown(
312312
"",
313313
f"![Convergence step delta]({convergence_plot_path.name})",
314314
"",
315-
"This plot shows how many optimization steps earlier the task-pretrained model reaches the baseline run's final loss level. Positive values indicate faster convergence.",
315+
"This plot shows how many downstream steps the task-pretrained run saves relative to the baseline run with no pre-pre-training, with standard deviation across seeds. If the task-pretrained run ends below the baseline's final eval loss, the value is how many steps before the end it reached that loss; otherwise it is minus the number of steps before the end at which the baseline reached the task-pretrained run's final loss. Crossings are linearly interpolated between eval points, so the resolution is limited by the eval interval.",
316316
"",
317317
"### Loss Overlays",
318318
"",
@@ -324,11 +324,12 @@ def _build_report_markdown(
324324
if probe_plot_path is not None:
325325
sections.extend(
326326
[
327-
"### Probe Accuracy Gains",
327+
"### Probe Answer Log-Probability Gains",
328328
"",
329329
f"![Probe gains]({probe_plot_path.name})",
330330
"",
331-
"This plot shows mean accuracy-point gains on the reasoning and algorithmic probes, with standard deviation across seeds. These probe metrics are only shown when they carry non-trivial signal in the current profile.",
331+
"This plot shows the gain of the task-pretrained run over the baseline with no pre-pre-training in the mean log-probability of the correct probe answer, with standard deviation across seeds. Each answer candidate is scored with a terminating newline, and the log-probability of the correct candidate is renormalised over the candidate set, so a model indifferent between candidates scores -log(number of candidates). Exact-answer accuracy is listed alongside but sits at the floor for small models.",
332+
"",
332333
probe_note,
333334
"",
334335
]
@@ -474,8 +475,8 @@ def _save_probe_gain_plot(payload: dict[str, Any], output_path: Path) -> Path |
474475
items = []
475476
for task_name, result in _payload_tasks(payload).items():
476477
metrics = result.get("metrics", {})
477-
reasoning = metrics.get("reasoning_accuracy_gain")
478-
algorithmic = metrics.get("algorithmic_accuracy_gain")
478+
reasoning = metrics.get("reasoning_log_prob_gain")
479+
algorithmic = metrics.get("algorithmic_log_prob_gain")
479480
if reasoning is not None and reasoning.get("mean") is not None:
480481
mean = float(reasoning["mean"])
481482
std = float(reasoning.get("std") or 0.0)
@@ -501,8 +502,8 @@ def _save_probe_gain_plot(payload: dict[str, Any], output_path: Path) -> Path |
501502
axis.axvline(0.0, color="#444444", linewidth=0.8)
502503
axis.set_yticks(positions)
503504
axis.set_yticklabels(labels)
504-
axis.set_xlabel("Probe accuracy-point gain vs baseline (positive is better)")
505-
limit = max(np.max(np.abs(values) + errors), 0.1)
505+
axis.set_xlabel("Answer log-probability gain vs baseline (nats, positive is better)")
506+
limit = max(np.max(np.abs(values) + errors), 0.01)
506507
axis.set_xlim(-1.15 * limit, 1.15 * limit)
507508
figure.tight_layout()
508509
figure.savefig(output_path, dpi=150, bbox_inches="tight", transparent=True)
@@ -750,8 +751,8 @@ def _save_effect_summary_plot(payload: dict[str, Any], output_path: Path) -> Pat
750751
("transfer_gap_percent", "Transfer gap\n(%)"),
751752
("compute_matched_gap_percent", "NLP method gap\n(%)"),
752753
("convergence_step_delta", "Convergence\n(steps)"),
753-
("reasoning_accuracy_gain", "Reasoning\n(points)"),
754-
("algorithmic_accuracy_gain", "Algorithmic\n(points)"),
754+
("reasoning_log_prob_gain", "Reasoning\n(nats)"),
755+
("algorithmic_log_prob_gain", "Algorithmic\n(nats)"),
755756
)
756757
for task_name, result in _payload_tasks(payload).items():
757758
metrics = result.get("metrics", {})
@@ -814,8 +815,8 @@ def _build_metrics_table_markdown(payload: dict[str, Any]) -> str:
814815
"task-pretrained gap %",
815816
"NLP method gap %",
816817
"convergence delta",
817-
"reasoning gain",
818-
"algorithmic gain",
818+
"reasoning log-prob gain",
819+
"algorithmic log-prob gain",
819820
"task-pretrained KL",
820821
"task-pretrained CKA",
821822
"task-pretrained rank",
@@ -834,8 +835,8 @@ def _build_metrics_table_markdown(payload: dict[str, Any]) -> str:
834835
_format_summary(metrics.get("transfer_gap_percent"), suffix=" %"),
835836
_format_summary(metrics.get("compute_matched_gap_percent"), suffix=" %"),
836837
_format_summary(metrics.get("convergence_step_delta")),
837-
_format_summary(metrics.get("reasoning_accuracy_gain"), suffix=" pts"),
838-
_format_summary(metrics.get("algorithmic_accuracy_gain"), suffix=" pts"),
838+
_format_summary(metrics.get("reasoning_log_prob_gain"), suffix=" nats"),
839+
_format_summary(metrics.get("algorithmic_log_prob_gain"), suffix=" nats"),
839840
_format_diagnostic_summary(result.get("diagnostics", {}).get("logit_divergence_to_baseline"), "transferred", scientific=True),
840841
_format_diagnostic_summary(result.get("diagnostics", {}).get("activation_cka_to_baseline"), "transferred"),
841842
_format_diagnostic_summary(result.get("diagnostics", {}).get("activation_effective_rank"), "transferred"),
@@ -883,20 +884,37 @@ def _build_nca_note(payload: dict[str, Any]) -> str:
883884

884885

885886
def _build_probe_note(payload: dict[str, Any]) -> str:
886-
values = []
887-
for result in _payload_tasks(payload).values():
887+
columns = [
888+
"task",
889+
"probe",
890+
"no-prepretraining log-prob",
891+
"task-pretrained log-prob",
892+
"chance log-prob",
893+
"no-prepretraining acc %",
894+
"task-pretrained acc %",
895+
]
896+
rows = []
897+
for task_name, result in _payload_tasks(payload).items():
888898
metrics = result.get("metrics", {})
889-
for metric_name in ("reasoning_accuracy_gain", "algorithmic_accuracy_gain"):
890-
summary = metrics.get(metric_name)
891-
if summary is not None and summary.get("mean") is not None:
892-
values.append(abs(float(summary["mean"])))
893-
if values and max(values) == 0.0:
894-
return (
895-
"In this smoke run, all exact-match probe gains were 0.0, which means the probes are acting only as a floor check here rather than a meaningful ranking signal."
896-
)
897-
return (
898-
"Probe gains are computed as transferred exact-answer accuracy minus baseline exact-answer accuracy on the configured reasoning or algorithmic probe."
899-
)
899+
for prefix in ("reasoning", "algorithmic"):
900+
if metrics.get(f"{prefix}_log_prob_gain") is None:
901+
continue
902+
rows.append(
903+
[
904+
TASK_LABELS.get(task_name, task_name),
905+
prefix,
906+
_format_summary(metrics.get(f"scratch_{prefix}_answer_log_prob")),
907+
_format_summary(metrics.get(f"transferred_{prefix}_answer_log_prob")),
908+
_format_summary(metrics.get(f"{prefix}_chance_log_prob")),
909+
_format_summary(metrics.get(f"scratch_{prefix}_accuracy")),
910+
_format_summary(metrics.get(f"transferred_{prefix}_accuracy")),
911+
]
912+
)
913+
if not rows:
914+
return "No probe metrics were available for this run."
915+
lines = ["| " + " | ".join(columns) + " |", "| " + " | ".join(["---"] * len(columns)) + " |"]
916+
lines.extend("| " + " | ".join(row) + " |" for row in rows)
917+
return "\n".join(lines) + "\n"
900918

901919

902920
def _set_plot_style() -> None:

0 commit comments

Comments
 (0)