# Evaluating the fine-tuned model {#sec-evaluating}
**You will learn:**
- the two ways of giving a model the history of a conversation, and why the one that matters is the harder one;
- how a model's outputs are scored, and what happens to an output that is not a valid program;
- how far the adapter of @sec-training takes the model on the validation split, by execution accuracy and by the
stricter program accuracy;
- what the remaining mistakes are, and how close the model was to the right token when it went wrong;
- whether a prompt, merging the adapter, or more samples per turn change the answers, and what each costs.
@sec-training ended with a quick check: a sample of turns, with the gold history, to see that the adapter that was
saved is the one that learned. This chapter is the evaluation itself: every turn of the split, with the history the model
would have in use, scored the way the untuned baseline of @sec-baseline was scored, so that the two can be compared.
Everything here is measured on the **validation** split, which is where the book makes its choices. The development
split is used once, at the end, for the final numbers of the fine-tuned model and of the untuned baselines it is compared with
(the two histories, with the code of this chapter and nothing else): the evaluations are artifacts named by the split, and the final
chapter asks for the same ones with `dev`. The other comparisons of this chapter (the examples on the tuned model, the extra compute, the merged adapter) are
validation results only.
## Two histories
A conversation is a sequence of questions, and each answer can use the earlier ones: "and what is that as a
percentage?" is a question about the answer before it. When the model answers turn $k$, the prompt holds the turns
before it, and there are two ways to fill in the model's side of them.
- **Gold history.** The earlier answers are the gold programs, as in training. This is called *teacher forcing*: the
model is never shown its own mistakes. Each turn is an independent question with the right context, so the score
says how well the model answers when everything before it was right.
- **Predicted history.** The earlier answers are the model's own outputs, exactly as generated, valid or not. This is
how the model would be used: a mistake at turn 2 is in the prompt at turn 3. It is the **headline** mode of the book.
Gold-history accuracy is what predicted-history accuracy would be if no earlier mistake carried over, and the gap
between the two, turn by turn, shows how far errors compound. No conversation and no turn is dropped in either mode:
a turn that follows a wrong answer is still scored.
## The policy for invalid outputs
Decoding is greedy, with **one attempt** per turn, and an output that is not a valid program, or that does not
execute, **counts as wrong**. The denominator is every turn. This is what the official ConvFinQA evaluation does, and
what the published numbers we compare with assume. In predicted history, an [invalid output](901_glossary.qmd#gloss-invalid-output) stays in the history as it
was generated. The share of invalid outputs is reported next to the accuracy, by cause, because it says where the
errors are: not being able to write the language, or writing it wrongly.
## The code
Two artifacts evaluate a run. Both are named by the split, the run, the seed of the training and the history mode.
`tuned_{split}_{run}_{seed}_{mode}` loads the adapter of @sec-training and writes one output per turn, with the
training prompt and no examples; like the baseline's, it refuses `dev` until the freeze file exists.
`scores_tuned_…` is light: it executes and scores the outputs. The generation is `convfinqa.tuned_eval.generate_tuned`.
```{python}
from convfinqa.artifacts import artifact, get
@artifact(
"tuned_{split}_{run}_{seed}_{mode}",
deps=[
"train_val_split", "eval_turns",
"lora_{run}_{seed}", "train_config_{run}",
],
heavy=True,
)
def build_tuned(out, deps, *, split: str, run: str, seed: int, mode: str):
"""Generate the fine-tuned model's output for every turn of a split.
Args:
out: Output directory; `predictions.jsonl` is written to it.
deps: The adapter, its settings and the conversations.
split: `val`, or `dev` once `configs/FROZEN` exists.
run: The training run (`main`).
seed: The seed of the training.
mode: `gold` or `pred`, the history of the earlier turns.
"""
import json
import time
from convfinqa.tuned_eval import generate_tuned, split_conversations
cfg = deps[f"train_config_{run}"].json("config.json")
convs = split_conversations(
split,
list(deps["train_val_split"].jsonl("val.jsonl")),
list(deps["eval_turns"].jsonl("dev.jsonl")),
)
start, done = time.perf_counter(), 0
with open(out / "predictions.jsonl", "w") as f:
def sink(row):
nonlocal done
f.write(json.dumps({
k: v for k, v in row.items() if k != "seconds"
}) + "\n") # timing is not an output
f.flush()
done += 1
if done % 50 == 0:
print(
f"{done} turns, {time.perf_counter() - start:.0f} s",
flush=True
)
generate_tuned(
cfg, deps[f"lora_{run}_{seed}"].path / "adapter",
convs, mode, sink
)
print(f"done: {done} turns in {time.perf_counter() - start:.0f} s")
@artifact(
"scores_tuned_{split}_{run}_{seed}_{mode}",
deps=["tuned_{split}_{run}_{seed}_{mode}", "eval_turns"],
)
def build_scores_tuned(out, deps, *, split: str, run: str, seed: int, mode: str):
"""Execute and score the outputs of `tuned_{split}_{run}_{seed}_{mode}`."""
import json
from convfinqa.evaluate import score_rows, summarize
from convfinqa.program_match import add_program_match
rows = list(
deps[f"tuned_{split}_{run}_{seed}_{mode}"].jsonl("predictions.jsonl")
)
turns = list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl"))
scores = add_program_match(score_rows(rows, turns), rows, turns)
(out / "scores.jsonl").write_text(
"".join(json.dumps(s) + "\n" for s in scores)
)
(out / "summary.json").write_text(
json.dumps(summarize(scores), indent=2)
)
```
## Results on the validation split
The fine-tuned model uses the adapter that @sec-training kept (the checkpoint with the lowest validation loss, seed 0). We run this model using the same prompt as in training: the
one-line system message and no examples, denoted `e0p` in @sec-baseline. This is compared against the untuned model
using both `e0p` and `e3p`, which adds three examples to the system prompt: the former shows what fine-tuning
changed, while the latter shows what is left for fine-tuning to add after the prompt has done its best. All the
systems are scored on the same validation turns, so differences between them are measured *paired*, by resampling whole report pages (@sec-baseline, "Under the hood: why
pair, and why resample pages").
```{python}
#HEAVY
import matplotlib.pyplot as plt
import pandas as pd
from convfinqa.stats import bootstrap_accuracy, paired_difference
SYSTEMS = {
"untuned, e0p (predicted history)": "scores_untuned_val_e0p_0_pred",
"untuned, e3p (predicted history)": "scores_untuned_val_e3p_0_pred",
"fine-tuned, predicted history": "scores_tuned_val_main_0_pred",
"fine-tuned, gold history": "scores_tuned_val_main_0_gold",
}
scores = {
"zero": list(get("scores_untuned_val_e0p_0_pred").jsonl("scores.jsonl")),
"base": list(get("scores_untuned_val_e3p_0_pred").jsonl("scores.jsonl")),
"pred": list(get("scores_tuned_val_main_0_pred").jsonl("scores.jsonl")),
"gold": list(get("scores_tuned_val_main_0_gold").jsonl("scores.jsonl")),
}
summary = {
"zero": get("scores_untuned_val_e0p_0_pred").json("summary.json"),
"base": get("scores_untuned_val_e3p_0_pred").json("summary.json"),
"pred": get("scores_tuned_val_main_0_pred").json("summary.json"),
"gold": get("scores_tuned_val_main_0_gold").json("summary.json"),
}
ci = {k: bootstrap_accuracy(v) for k, v in scores.items()}
rows = []
for (label, _), key in zip(SYSTEMS.items(), scores):
rows.append({
"system": label,
"accuracy": f"{ci[key]['accuracy']:.1%}",
"95% interval": f"[{ci[key]['low']:.1%}, {ci[key]['high']:.1%}]",
"invalid outputs": f"{summary[key]['invalid_rate']:.1%}",
})
pd.DataFrame(rows).set_index("system")
```
```{python}
#HEAVY
gain = paired_difference(scores["pred"], scores["base"])
gain_zero = paired_difference(scores["pred"], scores["zero"])
gap = paired_difference(scores["gold"], scores["pred"])
# fine-tuning beats the best prompt, and the gold history beats the predicted
# one, each by more than the resampling noise
assert gain["low"] > 0 and gain_zero["low"] > 0 and gap["low"] > 0
assert gain_zero["difference"] > gain["difference"]
assert len({summary[k]["n"] for k in summary}) == 1
```
On the same input, the untuned model gets `{python} f"{ci['zero']['accuracy']:.1%}"` of the turns right and the
fine-tuned model `{python} f"{ci['pred']['accuracy']:.1%}"` (predicted history throughout): a difference of
`{python} f"{100 * gain_zero['difference']:+.1f}"` points, with a paired 95% interval of
[`{python} f"{100 * gain_zero['low']:+.1f}"`, `{python} f"{100 * gain_zero['high']:+.1f}"`]. Prompting recovers part of
that: with the best prompt the untuned model reaches `{python} f"{ci['base']['accuracy']:.1%}"`, and fine-tuning is
still ahead of it by
`{python} f"{100 * gain['difference']:+.1f}"` points, with a paired 95% interval of
[`{python} f"{100 * gain['low']:+.1f}"`, `{python} f"{100 * gain['high']:+.1f}"`]. The interval is far from zero, so
this is not noise of the validation sample. Giving the model the gold history raises its accuracy to
`{python} f"{ci['gold']['accuracy']:.1%}"`, `{python} f"{100 * gap['difference']:+.1f}"` points
([`{python} f"{100 * gap['low']:+.1f}"`, `{python} f"{100 * gap['high']:+.1f}"`]) over its predicted-history score: that
gap is what the model loses to its own earlier mistakes.
### Accuracy by turn and type of conversation
```{python}
#| label: fig-by-turn
#| fig-cap: "Execution accuracy by turn index, on the validation split, for the fine-tuned model with the predicted history and with the gold history. The label under each turn is the number of turns of that index."
#| fig-alt: "Line chart of accuracy against turn index, 1 to 6. The two lines meet at turn 1. After that the gold-history line stays well above the predicted-history line, which declines slowly with the turn index."
shown_turns = [t for t, v in summary["pred"]["by_turn"].items() if v["n"] >= 20]
fig, ax = plt.subplots(figsize=(7, 3.2))
for key, label, colour in (
("gold", "gold history", "#3b6ea5"),
("pred", "predicted history", "#b85450")
):
ax.plot(
[int(t) for t in shown_turns],
[summary[key]["by_turn"][t]["accuracy"] for t in shown_turns],
"o-", color=colour, label=label
)
ax.set_xticks(
[int(t) for t in shown_turns],
[f"{t}\n(n={summary['pred']['by_turn'][t]['n']})" for t in shown_turns]
)
ax.set_xlabel("turn index")
ax.set_ylabel("execution accuracy")
ax.legend(frameon=False)
fig.tight_layout()
plt.show()
```
```{python}
#HEAVY
by_turn = {key: summary[key]["by_turn"] for key in ("pred", "gold")}
gap_by_turn = {
int(t): by_turn["gold"][t]["accuracy"] - by_turn["pred"][t]["accuracy"]
for t in shown_turns
}
# no history, no gap: the first turn is answered identically in both modes
assert gap_by_turn[1] == 0
# the gap opens at turn 2 and stays open through turn 5
assert all(gap_by_turn[t] > 0.05 for t in (2, 3, 4, 5))
```
At turn 1 there is no history, so the two modes ask the same question and get the same answers: the gap is zero. It
opens at turn 2, where the model has one earlier answer of its own to build on, and stays between
`{python} f"{100 * min(gap_by_turn[t] for t in (2, 3, 4, 5)):.0f}"` and
`{python} f"{100 * max(gap_by_turn[t] for t in (2, 3, 4, 5)):.0f}"` points through turn 5. From turn 6 on, the groups
are too small to read: the smallest holds `{python} min(v["n"] for v in by_turn["pred"].values())` turn.
```{python}
#HEAVY
by_type = pd.DataFrame({
key: {
f"type {t}": f"{v['accuracy']:.1%} (n={v['n']})"
for t, v in summary[key]["by_type"].items()
}
for key in ("base", "pred", "gold")
}).rename(columns={
"base": "untuned, e3p", "pred": "fine-tuned, predicted",
"gold": "fine-tuned, gold",
})
by_type
```
Type I conversations come from one annotated question, and type II from two questions joined into one conversation
(@sec-convfinqa).
## Beyond execution accuracy
Execution accuracy asks only whether the number is right. Two further measures look at the program itself and at the
numbers it is written with, and the error analysis below uses both.
### Program accuracy
Execution accuracy asks whether the program gives the right number. **[Program accuracy](901_glossary.qmd#gloss-program-accuracy)** asks whether it is the right
program, by the rule of the official ConvFinQA script. The two programs are compared as expressions, so the operands of
an `add` or a `multiply` may come in either order, and a calculation may be split over the steps in another way. The
arguments are compared as exact text: the numbers must be copied off the page as they are, so `2.70` is not `2.7`, and
`17%` is not `0.17`. A program that reaches the right answer from other numbers is not the gold program either.
Because the gold program gives the gold answer, a turn that is right by program is right by execution too. The
interesting counts are the other way round: how much program accuracy loses against execution accuracy, and what the
turns in between look like.
```{python}
#HEAVY
import re
from convfinqa.program_match import equal_up_to_constants
names = {
"zero": "untuned_val_e0p_0_pred",
"base": "untuned_val_e3p_0_pred",
"pred": "tuned_val_main_0_pred",
"gold": "tuned_val_main_0_gold",
}
for key, name in names.items():
scores[key] = list(get(f"scores_{name}").jsonl("scores.jsonl"))
program = {
key: [{**s, "correct": s["program_correct"]} for s in rows_]
for key, rows_ in scores.items()
}
ci_program = {k: bootstrap_accuracy(v) for k, v in program.items()}
exact_text = {
k: sum(s["text_match"] for s in v) / len(v)
for k, v in scores.items()
}
swapped = { # the same program, written in another order
k: sum(s["program_correct"] and not s["text_match"] for s in v)
for k, v in scores.items()
}
loses = {
k: sum(s["correct"] and not s["program_correct"] for s in v)
for k, v in scores.items()
}
# program-correct implies execution-correct
assert not any(
s["program_correct"] and not s["correct"]
for v in scores.values()
for s in v
)
pd.DataFrame({
label: {
"execution accuracy": f"{ci[k]['accuracy']:.1%}",
"program accuracy": f"{ci_program[k]['accuracy']:.1%}",
"95% interval":
f"[{ci_program[k]['low']:.1%}, {ci_program[k]['high']:.1%}]",
"same text as gold": f"{exact_text[k]:.1%}",
"right answer, other program": loses[k],
}
for label, k in (
("untuned, e0p", "zero"),
("untuned, e3p", "base"),
("fine-tuned, predicted", "pred"),
("fine-tuned, gold", "gold"),
)
}).T
```
The row "same text as gold" is the stricter reading, in which the program must also have its operands in the gold order.
For the fine-tuned model with the predicted history, the symbolic comparison accepts
`{python} swapped["pred"]` programs that the text comparison rejects, which is
`{python} f"{100 * (ci_program['pred']['accuracy'] - exact_text['pred']):.1f}"` points of accuracy.
#### Examples with swapped operands in sums and products
```{python}
#HEAVY
gold_of = {
(t["id"], t["turn"]): t["program"]
for t in get("eval_turns").jsonl("val_turns.jsonl")
}
output_of = {
(r["id"], r["turn"]): r["output"]
for r in get(f"{names['pred']}").jsonl("predictions.jsonl")
}
def show(selected, n=5):
pd.set_option("display.max_colwidth", None)
return pd.DataFrame([
{
"fine-tuned model": output_of[(s["id"], s["turn"])],
"gold program": gold_of[(s["id"], s["turn"])]
}
for s in selected[:n]
])
reordered = [
s for s in scores["pred"]
if s["program_correct"] and not s["text_match"]
]
# swapped operands are a small share of the turns
assert len(reordered) < 0.05 * len(scores["pred"])
show(reordered)
```
These are the same program with the operands of a sum or a product swapped, and they are a small share of the turns.
One of the two comparisons has to be chosen: the book uses the symbolic one, as the official script does.
#### Other programs with the right answer
What does the fine-tuned model lose against its execution accuracy? The turns that have the right answer and another
program, grouped by how the program differs from the gold one:
```{python}
#HEAVY
from convfinqa.mistake_kinds import KINDS, minimal_explanations
other = [s for s in scores["pred"] if s["correct"] and not s["program_correct"]]
GROUPS = {
("constants",): "a constant written as a number",
("constants", "zeros"): "that, with trailing zeros",
("signs",): "signs dropped, cancelling in a ratio",
}
def group_of(s):
key = (s["id"], s["turn"])
found = minimal_explanations(output_of[key], gold_of[key])
return tuple(k for k in KINDS if found and k in found[0]) if found else None
members = {}
for s in other:
members.setdefault(GROUPS.get(group_of(s), "other"), []).append(s)
sizes = [len(v) for k, v in members.items() if k != "other"]
# the spelling of a constant is the largest group
assert max(members, key=lambda k: len(members[k])) == "a constant written as a number"
# execution accuracy is much closer to program accuracy for the
# fine-tuned model than for the untuned one
assert loses["pred"] < loses["base"] / 2
# the three named groups hold most of these turns
assert sum(sizes) > 3 / 4 * len(other)
pd.DataFrame([
{
"difference from the gold program": label,
"turns": len(v),
"model": output_of[(v[0]["id"], v[0]["turn"])],
"gold": gold_of[(v[0]["id"], v[0]["turn"])],
}
for label, v in sorted(
members.items(),
key=lambda kv: (kv[0] == "other", -len(kv[1]))
)
]).set_index("difference from the gold program")
```
`{python} len(other)` turns have the right answer with another program. The largest group is the spelling of a
constant: the gold programs write the number 100 as `const_100` in some conversations and as `100` in others, and the
model chooses one of them. The official rule counts that as a different program, and so do we, but it says little
about the model. The gold also writes a loss as a negative number, and where the model drops the sign the answer
survives only if the signs cancel, as in a ratio of two losses. The other
`{python} len(members["other"])` turns differ in other ways. For the untuned model with `e3p`, many more turns have the
right answer with another program (`{python} loses["base"]`).
### Where the numbers come from
Program accuracy compares whole programs. The **[literal check](901_glossary.qmd#gloss-literal-check)** looks only at the numbers a program is written with,
and so it works for any output format. For each turn it asks three things: are the numbers the same as the gold
program's *as text*, are they the same *as values* (`2.70` is `2.7`, `17%` is `0.17`, `const_100` is `100`), and is
every number that is not a named constant *from the page*, as text. The gap between the first two is formatting;
the third says whether the numbers were copied, not made up. The **[scale check](901_glossary.qmd#gloss-scale-check)** is separate: it asks whether the answer
is the gold answer times a power of ten.
```{python}
@artifact(
"checks_untuned_{split}_{variant}_{seed}_{mode}",
deps=[
"untuned_{split}_{variant}_{seed}_{mode}",
"eval_turns", "train_val_split",
],
)
def build_checks_untuned(
out, deps, *, split: str, variant: str, seed: int, mode: str
):
"""The literal and scale checks of an untuned run."""
import json
from convfinqa.output_checks import check_rows
from convfinqa.tuned_eval import split_conversations
convs = split_conversations(
split,
list(deps["train_val_split"].jsonl("val.jsonl")),
list(deps["eval_turns"].jsonl("dev.jsonl")),
)
rows = list(
deps[f"untuned_{split}_{variant}_{seed}_{mode}"]
.jsonl("predictions.jsonl")
)
checks = check_rows(
rows, list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl")), convs
)
(out / "checks.jsonl").write_text(
"".join(json.dumps(c) + "\n" for c in checks)
)
@artifact(
"checks_tuned_{split}_{run}_{seed}_{mode}",
deps=[
"tuned_{split}_{run}_{seed}_{mode}", "eval_turns", "train_val_split",
],
)
def build_checks_tuned(out, deps, *, split: str, run: str, seed: int, mode: str):
"""The literal and scale checks of a fine-tuned run."""
import json
from convfinqa.output_checks import check_rows
from convfinqa.tuned_eval import split_conversations
convs = split_conversations(
split,
list(deps["train_val_split"].jsonl("val.jsonl")),
list(deps["eval_turns"].jsonl("dev.jsonl")),
)
rows = list(
deps[f"tuned_{split}_{run}_{seed}_{mode}"].jsonl("predictions.jsonl")
)
checks = check_rows(
rows, list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl")), convs
)
(out / "checks.jsonl").write_text(
"".join(json.dumps(c) + "\n" for c in checks)
)
```
```{python}
#HEAVY
checks = {
"zero": list(get("checks_untuned_val_e0p_0_pred").jsonl("checks.jsonl")),
"base": list(get("checks_untuned_val_e3p_0_pred").jsonl("checks.jsonl")),
"pred": list(get("checks_tuned_val_main_0_pred").jsonl("checks.jsonl")),
"gold": list(get("checks_tuned_val_main_0_gold").jsonl("checks.jsonl")),
}
LABELS = {
"zero": "untuned, e0p", "base": "untuned, e3p",
"pred": "fine-tuned, predicted", "gold": "fine-tuned, gold",
}
ran = {k: [c for c in v if c["runs"]] for k, v in checks.items()}
def share(rows_, flag):
return f"{sum(c[flag] for c in rows_) / len(rows_):.1%}"
# the same check on the gold programs themselves: the page,
# as defined here, holds all of their numbers
from convfinqa.output_checks import check_rows
val_turns = list(get("eval_turns").jsonl("val_turns.jsonl"))
gold_checks = check_rows(
[{"id": t["id"], "turn": t["turn"], "output": t["program"]} for t in val_turns],
val_turns, list(get("train_val_split").jsonl("val.jsonl")),
)
assert all(c["lit_grounded"] for c in gold_checks)
# the fine-tuned model writes only numbers of the page,
# the untuned one with e3p does not
assert all(c["lit_grounded"] for c in ran["pred"] + ran["gold"])
assert sum(c["lit_grounded"] for c in ran["base"]) < 0.9 * len(ran["base"])
pd.DataFrame({
LABELS[k]: {
"outputs that run": len(ran[k]),
"same numbers as gold, as text": share(ran[k], "lit_text"),
"same numbers as gold, as values": share(ran[k], "lit_value"),
"every number comes from the page": share(ran[k], "lit_grounded"),
}
for k in ran
}).T
```
The table counts the outputs that run, so that an output that is not a program (the untuned model's explanations)
does not count. For the fine-tuned model with the predicted history, the gap between the first two columns is
`{python} f"{100 * (sum(c['lit_value'] for c in ran['pred']) - sum(c['lit_text'] for c in ran['pred'])) / len(ran['pred']):.1f}"`
points of the turns that run: the numbers are right but not written as the gold writes them. Every number it
writes comes from the page (`{python} share(ran["pred"], "lit_grounded")` of its turns), as does every number of the gold
programs, so the model does not invent numbers; where it is wrong, it picks another number of the page. The test is
weak, because a page holds many numbers, but the untuned model with `e3p` fails it on
`{python} f"{100 - 100 * sum(c['lit_grounded'] for c in ran['base']) / len(ran['base']):.0f}"`% of its turns.
The scale check counts the turns whose answer is the gold answer times, or divided by, a power of ten: by exactly 100
(a proportion where a percentage was asked for, or the reverse), or by another power of ten, from 10 to 10^9 (a
different unit, a dropped digit, a multiplication where the gold divides).
```{python}
#HEAVY
by_scale = pd.DataFrame({
LABELS[k]: {
"answer off by ×100 or ÷100": sum(c["scale"] == "factor_100" for c in v),
"answer off by another power of ten":
sum(c["scale"] == "other_power" for c in v),
}
for k, v in checks.items()
})
by_scale
```
The following table shows the execution accuracy of each model, separated by whether the question involves percentages,
and by how the gold answer handles them:
```{python}
#HEAVY
wrong_scale = {
k: sum(c["scale"] is not None for c in v) for k, v in checks.items()
}
# a wrong scale is a small part of the failures of the fine-tuned model
assert wrong_scale["pred"] < 0.15 * sum(not x["correct"] for x in scores["pred"])
PROPORTION = "\"percent\" in the question, gold does not multiply by 100"
PERCENT = "\"percent\" in the question, gold multiplies by 100"
def form(c):
if not c["percent_style"]:
return "no \"percent\" in the question"
if c["gold_percent"]:
return PERCENT
return PROPORTION
percent_rows = {}
for k in ("base", "pred", "gold"):
correct_of = {(sc["id"], sc["turn"]): sc["correct"] for sc in scores[k]}
for c in checks[k]:
percent_rows.setdefault(form(c), {}).setdefault(k, [])\
.append(correct_of[(c["id"], c["turn"])])
accuracy_of = {
f: {k: sum(v[k]) / len(v[k]) for k in v}
for f, v in percent_rows.items()
}
# the untuned model with e3p gets few of the proportion questions
# right, the fine-tuned model most
assert accuracy_of[PROPORTION]["base"] < 0.3 and accuracy_of[PROPORTION]["pred"] > 0.8
# the percent-by-100 turns are too few to read
assert len(percent_rows[PERCENT]["pred"]) < 20
pd.DataFrame({
form_: {
"turns": len(v["pred"]),
**{
LABELS[k]: f"{sum(v[k]) / len(v[k]):.1%}"
for k in ("base", "pred", "gold")
},
}
for form_, v in percent_rows.items()
}).T
```
A wrong scale is a small part of the fine-tuned model's failures: `{python} wrong_scale["pred"]` of its
`{python} sum(not x["correct"] for x in scores["pred"])` wrong turns, `{python} int(by_scale.loc["answer off by ×100 or ÷100", LABELS["pred"]])`
of them by a factor of 100. The last table separates the questions that contain the word "percent" by what the gold does: it multiplies
by 100 to give the percentage itself, or it does not (almost always it ends with a division, so the answer is a
proportion such as `0.14136`, not `14.136`). Most are of the second kind, and on those the untuned model with `e3p` is
right on
`{python} f"{accuracy_of[PROPORTION]['base']:.0%}"` of the turns and the fine-tuned model on
`{python} f"{accuracy_of[PROPORTION]['pred']:.0%}"`. Only `{python} len(percent_rows[PERCENT]["pred"])` turns want the
percentage itself, too few to say anything about them.
## Error analysis
This section asks what the fine-tuned model gets wrong: first by the kind of outcome, then by the likely
cause, and then by how close the model was to the right token at the point where it went wrong.
### Where the failures are
```{python}
#HEAVY
from convfinqa.evaluate import RUNS
from convfinqa.final_results import outcome_counts
outcomes = pd.DataFrame({
"untuned, e0p": outcome_counts(summary["zero"]),
"untuned, e3p": outcome_counts(summary["base"]),
"fine-tuned, predicted": outcome_counts(summary["pred"]),
"fine-tuned, gold": outcome_counts(summary["gold"]),
})
invalid = {key: outcome_counts(summary[key])["invalid output"] for key in summary}
wrong = {
key: summary[key]["n"] - summary[key]["by_kind"]["correct"]
for key in summary
}
causes = {k: v for k, v in summary["zero"]["by_kind"].items() if k not in RUNS}
fence = causes["code_fence"]
# what is left after fine-tuning is almost all valid programs that are wrong
assert invalid["pred"] <= 0.05 * wrong["pred"]
assert invalid["pred"] < invalid["base"]
# most of the untuned model's invalid outputs are a program in a code fence
assert fence == max(causes.values()) and fence > invalid["zero"] / 2
# the most common failure of the fine-tuned model is other numbers
assert outcomes.loc["wrong numbers", "fine-tuned, predicted"]\
== outcomes.loc[
["wrong operations", "wrong numbers", "wrong answer, right shape"],
"fine-tuned, predicted"
].max()
outcomes
```
The untuned model failed on the format of its answer: with the same prompt as the fine-tuned model, `{python} invalid["zero"]`
of its `{python} wrong["zero"]` wrong turns are not valid programs, `{python} fence` of them a program wrapped in a code
fence, and even with the three examples of `e3p`, `{python} invalid["base"]` of `{python} wrong["base"]`. After
fine-tuning it is `{python} invalid["pred"]` of `{python} wrong["pred"]` (`{python} invalid["gold"]` with the gold
history). What is left is a valid program that is wrong: a different operation, different numbers, or the right shape
with the wrong value. Different numbers are the largest of the three,
`{python} int(outcomes.loc["wrong numbers", "fine-tuned, predicted"])` of the `{python} wrong["pred"]` wrong turns. That is a
failure of reading the page and reasoning, and not of writing the language.
### What the fine-tuned model gets wrong {#sec-evaluating-errors}
The turns the fine-tuned model gets wrong are valid programs, so the question is why they are wrong. Each wrong turn
of the predicted-history run gets one label, the first of these that applies: it is not a program that runs; it is
right when the earlier answers are the gold ones, so the history is the likely cause; the answer is
off by a power of ten; it is the negative of the gold answer, because a sign was dropped or the operands of a
subtraction were reversed; a number is not from the page; the program has the same operations as the gold with other
numbers (or another number was copied where a number was asked for); it has other operations; or none of these.
```{python}
#HEAVY
from collections import Counter
from convfinqa.error_labels import label_turns
from convfinqa.mistake_kinds import count_minimal_sets
pred_rows = list(get("tuned_val_main_0_pred").jsonl("predictions.jsonl"))
labels = label_turns(
scores["pred"], checks["pred"], pred_rows, val_turns, scores["gold"]
)
counts = Counter(labels.values())
gap_turns = sum(x["correct"] for x in scores["gold"]) - sum(x["correct"] for x in scores["pred"])
# the turns that are wrong only because of the history are nearly all of the gap between the histories
assert abs(counts["right with the gold history"] - gap_turns) < 0.1 * gap_turns
n_wrong = len(labels)
ranked = sorted(counts, key=lambda k: -counts[k])
shown, rest_labels = ranked[:4], ranked[4:]
def example(label):
key = next(k for k, v in labels.items() if v == label)
return output_of[key], gold_of[key]
# the labels cover every wrong turn, and nothing here is from outside the page
assert n_wrong == sum(not x["correct"] for x in scores["pred"])
assert counts["number not from the page"] == 0
# other numbers and other operations are most of the rest
rest = n_wrong - counts["right with the gold history"]
assert counts["other numbers"] + counts["wrong operation"] > rest / 2
# four types hold nearly all of the wrong turns
assert sum(counts[k] for k in shown) > 0.9 * n_wrong
rows_ = [
{
"type": label, "turns": counts[label],
"share": f"{counts[label] / n_wrong:.0%}",
"model": example(label)[0],
"gold": example(label)[1],
}
for label in shown
]
rows_.append({
"type": "all other types", "turns": sum(counts[k] for k in rest_labels),
"share": f"{sum(counts[k] for k in rest_labels) / n_wrong:.0%}",
"model": "",
"gold": "",
})
pd.DataFrame(rows_).set_index("type")
```
`{python} counts["right with the gold history"]` of the `{python} n_wrong` wrong turns are right when the earlier answers
are the gold ones. With the predicted history, a mistake at one turn can make the next turns wrong, and these turns
are about as many as the `{python} gap_turns` turns by which the gold history is ahead; the model is not wrong at
them for a reason of its own. Of the rest,
`{python} counts["other numbers"]` have the right operations with other numbers, or another number where a number was
asked for, and `{python} counts["wrong operation"]` have other operations. The remaining types are
`{python} ", ".join(f"{k} ({counts[k]})" for k in rest_labels)`.
```{python}
#HEAVY
minimal = count_minimal_sets([
(output_of[(t["id"], t["turn"])], t["program"]) for t in val_turns
])
differ = minimal["n"] - minimal["equal"]
explained = differ - minimal["unexplained"]
# no turn has two alternative smallest explanations
assert minimal["multiple"] == 0
```
The program differs from the gold in `{python} differ` of the `{python} minimal["n"]` turns. Four kinds of difference
are about the form and not the content: a constant written as a number, trailing zeros, signs, and the order of the
operands of a subtraction or a division. They explain `{python} explained` of the `{python} differ`, alone or together,
and no turn has two alternative explanations. The other `{python} minimal["unexplained"]` differ in what the program
says.
### How close was the right token? {#sec-evaluating-close}
A wrong program is a sequence of token choices. The gold program and the model's are the same text up to the first
token where they differ, so up to there the model chose as the gold program does, and its distribution at that
position is the one it wrote its own token from. Its *rank* for the gold token there (1 is the most probable token), and the
*ratio* of the gold token's probability to the probability of the token it wrote, say whether the right answer
was a near miss or far away. `divergence_{split}_{run}_{seed}` scores the wrong turns of the predicted-history run
with the same prompts, in one forward pass each.
```{python}
@artifact(
"divergence_{split}_{run}_{seed}",
deps=[
"train_val_split", "eval_turns",
"lora_{run}_{seed}", "train_config_{run}",
"tuned_{split}_{run}_{seed}_pred",
"scores_tuned_{split}_{run}_{seed}_pred",
],
heavy=True,
)
def build_divergence(out, deps, *, split: str, run: str, seed: int):
"""Score the first token where each wrong program differs from the gold one.
Args:
out: Output directory; `divergences.jsonl` is written to it.
deps: The adapter, the conversations and the predicted-history run.
split: `val`, or `dev` once `configs/FROZEN` exists.
run: The training run (`main`).
seed: The seed of the training.
"""
import json
from convfinqa.divergence import score_divergences
from convfinqa.tuned_eval import split_conversations
cfg = deps[f"train_config_{run}"].json("config.json")
convs = split_conversations(
split,
list(deps["train_val_split"].jsonl("val.jsonl")),
list(deps["eval_turns"].jsonl("dev.jsonl")),
)
rows = list(
deps[f"tuned_{split}_{run}_{seed}_pred"].jsonl("predictions.jsonl")
)
turns = list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl"))
scores = deps[f"scores_tuned_{split}_{run}_{seed}_pred"].jsonl(
"scores.jsonl"
)
wrong = {(s["id"], s["turn"]) for s in scores if not s["correct"]}
results = score_divergences(
cfg, deps[f"lora_{run}_{seed}"].path / "adapter",
convs, rows, turns, wrong
)
(out / "divergences.jsonl").write_text(
"".join(json.dumps(r) + "\n" for r in results)
)
```
```{python}
#HEAVY
import numpy as np
div = pd.DataFrame(get("divergence_val_main_0").jsonl("divergences.jsonl"))
div["label"] = [labels[(i, t)] for i, t in zip(div.id, div.turn)]
div["close"] = div.gold_over_pred > 0.1
assert len(div) == n_wrong and div.position.notna().all()
top3 = (div.rank_gold <= 3).mean()
top1 = int((div.rank_gold == 1).sum())
# the gold token is usually among the first few choices, and the model's token
# is the top one
assert top3 > 0.8
assert div.chosen_is_top.mean() > 0.95
# in a tie the two tokens have the same probability
assert (div[div.rank_gold == 1].gold_over_pred == 1).all()
assert np.exp(div.logp_pred).median() > 0.9
by_label = div.groupby("label").agg(
turns=("rank_gold", "size"),
top3=("rank_gold", lambda r: (r <= 3).mean()),
median_ratio=("gold_over_pred", "median"),
close=("close", "mean"),
).loc[shown + [k for k in rest_labels if k in set(div.label)]]
assert by_label.close["sign dropped"]\
> by_label.close["right with the gold history"]
by_label.assign(
**{
"gold token in top 3": by_label.top3.map("{:.0%}".format),
"median probability ratio": by_label.median_ratio.map("{:.3f}".format),
"within a factor of 10": by_label.close.map("{:.0%}".format),
}
)[[
"turns",
"gold token in top 3",
"median probability ratio",
"within a factor of 10"
]]
```
At the first token where the two programs differ, the gold token is among the model's top three in
`{python} f"{top3:.0%}"` of the `{python} len(div)` wrong turns, and in the second place in
`{python} int((div.rank_gold == 2).sum())` of them. The model's own token was the most probable one in
`{python} f"{div.chosen_is_top.mean():.0%}"` of the turns, so the re-scoring reproduces what it wrote.
The gold token ranks first in `{python} top1` turns, where it shares the first place with the model's token in an exact tie. The gap in
probability is usually larger than the gap in rank suggests: the median ratio of the gold token's probability to the
model's is `{python} f"{div.gold_over_pred.median():.3f}"`, and the gold token comes within a factor of ten in
`{python} f"{div.close.mean():.0%}"` of the turns. The model is rarely lost; at the point where it goes wrong it
had the right token near the top, but gave the token it wrote a median probability of `{python} f"{np.exp(div.logp_pred).median():.0%}"`.
By type of mistake, the dropped signs are the near misses (the gold token is within a factor of ten in
`{python} f"{by_label.close['sign dropped']:.0%}"` of those turns), while in the turns that are wrong only because of
the earlier answers it is within a factor of ten in `{python} f"{by_label.close['right with the gold history']:.0%}"`:
with its own history in the prompt, the model was sure of the program it wrote.
## Variations on the setup
### Does a prompt still help the tuned model?
The adapter was trained on the one-line prompt and no examples. Fine-tuning and prompting are two routes to the same
end, and nothing says that they cannot be taken together: the same three examples that did the most for the untuned
model (`e3p`) can be put in front of the tuned one. If they help, the two routes add up. If they do not, the adapter
has already taken up what the examples were teaching, or the examples are now an input unlike any that it was trained
on, and get in the way.
`prompted_tuned_{split}_{run}_{seed}_{variant}_{shots}_{mode}` asks the tuned model with a prompt variant of
@sec-baseline: `variant` names the variant and `shots` the example set, as in the baseline's artifacts. The examples
come from the training conversations, as they did there.
```{python}
@artifact(
"prompted_tuned_{split}_{run}_{seed}_{variant}_{shots}_{mode}",
deps=[
"train_val_split", "eval_turns", "example_sets",
"lora_{run}_{seed}", "train_config_{run}",
],
files=["configs/baseline.json"],
heavy=True,
)
def build_prompted_tuned(
out, deps, files, *,
split: str, run: str, seed: int, variant: str, shots: int, mode: str
):
"""Generate the fine-tuned model's output with a baseline prompt.
Args:
out: Output directory; `predictions.jsonl` is written to it.
deps: The adapter, its settings, the conversations and the example sets.
files: `configs/baseline.json`, which holds the system messages.
split: `val`, or `dev` once `configs/FROZEN` exists.
run: The training run (`main`).
seed: The seed of the training.
variant: The prompt variant of the baseline (`e3p`).
shots: The example set.
mode: `gold` or `pred`, the history of the earlier turns.
"""
import json
import time
from convfinqa.tuned_eval import split_conversations
from convfinqa.tuned_prompted import (
baseline_prompt, generate_tuned_prompted
)
cfg = deps[f"train_config_{run}"].json("config.json")
convs = split_conversations(
split,
list(deps["train_val_split"].jsonl("val.jsonl")),
list(deps["eval_turns"].jsonl("dev.jsonl")),
)
pool = {
c["id"]: c for c in deps["train_val_split"].jsonl("train_fit.jsonl")
}
system, examples = baseline_prompt(
files["configs/baseline.json"].json(),
deps["example_sets"].json("sets.json"), pool, variant, shots
)
start, done = time.perf_counter(), 0
with open(out / "predictions.jsonl", "w") as f:
def sink(row):
nonlocal done
f.write(json.dumps({
k: v for k, v in row.items() if k != "seconds"
}) + "\n") # timing is not an output
f.flush()
done += 1
if done % 50 == 0:
print(
f"{done} turns, {time.perf_counter() - start:.0f} s",
flush=True
)
generate_tuned_prompted(
cfg, deps[f"lora_{run}_{seed}"].path / "adapter",
convs, system, examples, mode, sink
)
print(f"done: {done} turns in {time.perf_counter() - start:.0f} s")
@artifact(
"scores_prompted_tuned_{split}_{run}_{seed}_{variant}_{shots}_{mode}",
deps=[
"prompted_tuned_{split}_{run}_{seed}_{variant}_{shots}_{mode}",
"eval_turns",
],
)
def build_scores_prompted_tuned(
out, deps, *,
split: str, run: str, seed: int, variant: str, shots: int, mode: str
):
"""Execute and score the outputs of `prompted_tuned_…`."""
import json
from convfinqa.evaluate import score_rows, summarize
from convfinqa.program_match import add_program_match
name = f"{split}_{run}_{seed}_{variant}_{shots}_{mode}"
rows = list(deps[f"prompted_tuned_{name}"].jsonl("predictions.jsonl"))
turns = list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl"))
scores = add_program_match(score_rows(rows, turns), rows, turns)
(out / "scores.jsonl").write_text(
"".join(json.dumps(s) + "\n" for s in scores)
)
(out / "summary.json").write_text(
json.dumps(summarize(scores), indent=2)
)
```
```{python}
#HEAVY
shots_name = "scores_prompted_tuned_val_main_0_e3p_0_pred"
scores["shots"] = list(get(shots_name).jsonl("scores.jsonl"))
summary["shots"] = get(shots_name).json("summary.json")
ci["shots"] = bootstrap_accuracy(scores["shots"])
extra = paired_difference(scores["shots"], scores["pred"])
def mean_prompt_tokens(name):
return pd.DataFrame(get(name).jsonl("predictions.jsonl")).prompt_tokens.mean()
tokens_zero = mean_prompt_tokens("tuned_val_main_0_pred")
tokens_shots = mean_prompt_tokens("prompted_tuned_val_main_0_e3p_0_pred")
# the examples do not make the tuned model worse by more than a few points (the
# text quotes the lower end of the interval), and the validation split cannot say
# that they make it better
assert extra["low"] > -0.03
assert extra["high"] < gain["difference"] / 2
assert not extra["excludes_zero"]
assert summary["shots"]["invalid_rate"] == 0
pd.DataFrame([
{
"tuned model, predicted history": label,
"accuracy": f"{ci[key]['accuracy']:.1%}",
"95% interval": f"[{ci[key]['low']:.1%}, {ci[key]['high']:.1%}]",
"prompt tokens per turn": f"{tokens:,.0f}",
}
for label, key, tokens in (
("training prompt, no examples", "pred", tokens_zero),
("e3p prompt, three examples", "shots", tokens_shots),
)
]).set_index("tuned model, predicted history")
```
With the three examples the tuned model gets `{python} f"{ci['shots']['accuracy']:.1%}"`, against
`{python} f"{ci['pred']['accuracy']:.1%}"` without them: a difference of
`{python} f"{100 * extra['difference']:+.1f}"` points, with a paired 95% interval of
[`{python} f"{100 * extra['low']:+.1f}"`, `{python} f"{100 * extra['high']:+.1f}"`]. The interval includes zero, so the
validation split cannot say whether the examples help. What it does show is that they do not hurt by more than
`{python} f"{-100 * extra['low']:.1f}"` points (the lower end of the interval), and that the effect, if there is one, is small next to the `{python} f"{100 * gain['difference']:.0f}"` points
that fine-tuning added to the best prompt of the untuned model. The effect, if any, is not free: the prompt is
`{python} f"{tokens_shots / tokens_zero:.1f}"` times as long (`{python} f"{tokens_shots:,.0f}"` tokens against
`{python} f"{tokens_zero:,.0f}"`), and every turn pays for it. So for this model, the two routes do not clearly add up:
once the adapter is trained, the examples are worth little, and they cost several times the prompt.
Note this is one example set (set 0) on one training seed, with no examples in the prompt during training.
A model trained *with* examples in its prompt might use them
better, but that is a different training run, and this chapter does not make it.
### Does merging the adapter change the answers?
Everything above ran the adapter *separately*: a bf16 base model with the adapter's own weights in fp32, as in
training. A model that is deployed is usually *merged*, with the adapter's correction $\tfrac{\alpha}{r}BA$ added into
the base weights once, so that inference costs nothing extra. @sec-lora showed on a random adapter that this is the same
function in fp32 but not in bf16, where rounding the sum back to bf16 can change the model as much as the adapter did.
The trained adapter is smaller and has structure, so the effect may be smaller; here we measure it, on the same
validation turns, with the predicted history: the merge rounded into bf16 weights, and the whole model kept in fp32.
```{python}
@artifact(
"merged_{split}_{run}_{seed}_{precision}_{mode}",
deps=[
"train_val_split", "eval_turns",
"lora_{run}_{seed}", "train_config_{run}",
],
heavy=True,
)
def build_merged(
out, deps, *, split: str, run: str, seed: int, precision: str, mode: str
):
"""Generate the output of the merged adapter for every turn of a split.
Args:
out: Output directory; `predictions.jsonl` is written to it.
deps: The adapter, its settings and the conversations.
split: `val`, or `dev` once `configs/FROZEN` exists.
run: The training run (`main`).
seed: The seed of the training.
precision: `bf16` (the merge rounded into bf16 weights) or `fp32`.
mode: `gold` or `pred`, the history of the earlier turns.
"""
import json
import time
from convfinqa.merged_eval import generate_merged
from convfinqa.tuned_eval import split_conversations
cfg = deps[f"train_config_{run}"].json("config.json")
convs = split_conversations(
split,
list(deps["train_val_split"].jsonl("val.jsonl")),
list(deps["eval_turns"].jsonl("dev.jsonl")),
)
start, done = time.perf_counter(), 0
with open(out / "predictions.jsonl", "w") as f:
def sink(row):
nonlocal done
f.write(json.dumps({
k: v for k, v in row.items() if k != "seconds"
}) + "\n")
f.flush()
done += 1
if done % 50 == 0:
print(
f"{done} turns, {time.perf_counter() - start:.0f} s",
flush=True
)
generate_merged(
cfg, deps[f"lora_{run}_{seed}"].path / "adapter",
convs, mode, precision, sink
)
print(f"done: {done} turns in {time.perf_counter() - start:.0f} s")
@artifact(
"scores_merged_{split}_{run}_{seed}_{precision}_{mode}",
deps=["merged_{split}_{run}_{seed}_{precision}_{mode}", "eval_turns"],
)
def build_scores_merged(
out, deps, *, split: str, run: str, seed: int, precision: str, mode: str
):
"""Execute and score the outputs of `merged_…`."""
import json
from convfinqa.evaluate import score_rows, summarize
from convfinqa.program_match import add_program_match
rows = list(
deps[f"merged_{split}_{run}_{seed}_{precision}_{mode}"]
.jsonl("predictions.jsonl")
)
turns = list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl"))
scores = add_program_match(score_rows(rows, turns), rows, turns)
(out / "scores.jsonl").write_text(
"".join(json.dumps(s) + "\n" for s in scores)
)
(out / "summary.json").write_text(
json.dumps(summarize(scores), indent=2)
)
```
```{python}
#HEAVY
MERGED = {
"bf16": "merged_val_main_0_bf16_pred",
"fp32": "merged_val_main_0_fp32_pred",
}
reference = {
(r["id"], r["turn"]): r["output"]
for r in get("tuned_val_main_0_pred").jsonl("predictions.jsonl")
}
merged_rows, merged_stats = [], {}
for precision, name in MERGED.items():
out = {
(r["id"], r["turn"]): r["output"]
for r in get(name).jsonl("predictions.jsonl")
}
sc = list(get(f"scores_{name}").jsonl("scores.jsonl"))
assert out.keys() == reference.keys()
diff = paired_difference(sc, scores["pred"])
by_key = {(s["id"], s["turn"]): s["correct"] for s in scores["pred"]}
flips = sum(by_key[(s["id"], s["turn"])] != s["correct"] for s in sc)
merged_stats[precision] = {
"different": sum(out[k] != reference[k] for k in reference),
"flips": flips,
"acc": bootstrap_accuracy(sc)["accuracy"],
"diff": diff,
}
merged_rows.append({
"weights": f"merged, {precision}",
"accuracy": f"{merged_stats[precision]['acc']:.1%}",
"difference to separate adapter": (
f"{100 * diff['difference']:+.1f} "
f"[{100 * diff['low']:+.1f}, {100 * diff['high']:+.1f}]"
),
"outputs with different text": merged_stats[precision]["different"],
"turns whose correctness changes": flips,
})
pd.DataFrame(merged_rows).set_index("weights")
```
```{python}
#HEAVY
assert all(not s["diff"]["excludes_zero"] for s in merged_stats.values())
assert all(
s["different"] < 0.05 * len(reference) for s in merged_stats.values()
)
```
Merging leaves the accuracy unchanged: the paired difference is
`{python} f"{100 * merged_stats['bf16']['diff']['difference']:+.1f}"` points for bf16 and
`{python} f"{100 * merged_stats['fp32']['diff']['difference']:+.1f}"` for fp32, and both intervals contain zero. The text of
`{python} merged_stats['bf16']['different']` of the
`{python} f"{len(reference):,}"` outputs differs after the bf16 merge, and
`{python} merged_stats['fp32']['different']` after the fp32 merge, so the merge is not invisible. The fp32 model
also differs from the separate adapter, although the sum is exact there; the cause is not something this check
isolates. For this adapter the answers of this chapter hold for a merged model, at the precision of either row.
### Does extra compute at inference help?
Everything above is one greedy attempt per turn. The cheapest way to spend more generations on a turn is
*[self-consistency](901_glossary.qmd#gloss-self-consistency)* (@wang2023selfconsistency): sample several programs at a temperature, drop those that do not
run, and take the answer most of them agree on; the history takes the first program with that answer. The
temperature is only there to make the samples differ, since greedy decoding would give the same program every
time. The number of samples and the temperature are in `configs/extra_compute.json`. The question is whether five
generations per turn beat one, so the row reports its cost in generations and tokens, which do not depend on the
machine, next to its accuracy. It is a separate row and never enters the headline.
```{python}
@artifact(
"extra_{split}_{run}_{seed}_{strategy}_{scope}",
deps=[
"train_val_split", "eval_turns",
"lora_{run}_{seed}", "train_config_{run}",
],
files=["configs/extra_compute.json"],
heavy=True,
)
def build_extra(
out, deps, files, *, split: str, run: str, seed: int, strategy: str,
scope: str
):
"""Generate the fine-tuned model's output with an extra-compute strategy.
Args:
out: Output directory; `predictions.jsonl` is written to it.
deps: The adapter, its settings and the conversations.
files: `configs/extra_compute.json`.
split: `val`, or `dev` once `configs/FROZEN` exists.
run: The training run (`main`).
seed: The seed of the training.
strategy: `retry` or `vote`.
scope: `probe` (the first conversations only) or `full`.
"""
import json
import time
from convfinqa.extra_compute import first_conversations, generate_extra
from convfinqa.tuned_eval import split_conversations
settings = files["configs/extra_compute.json"].json()
cfg = deps[f"train_config_{run}"].json("config.json")
convs = split_conversations(
split,
list(deps["train_val_split"].jsonl("val.jsonl")),
list(deps["eval_turns"].jsonl("dev.jsonl")),
)
if scope == "probe":
convs = first_conversations(convs, settings["probe_turns"])
elif scope != "full":
raise ValueError(f"scope must be 'probe' or 'full', not {scope!r}")
start, done = time.perf_counter(), 0
with open(out / "predictions.jsonl", "w") as f:
def sink(row):
nonlocal done
f.write(json.dumps({
k: v for k, v in row.items() if k != "seconds"
}) + "\n")
f.flush()
done += 1
if done % 50 == 0:
print(
f"{done} turns, {time.perf_counter() - start:.0f} s",
flush=True
)
generate_extra(
cfg, deps[f"lora_{run}_{seed}"].path / "adapter",
convs, strategy, settings, sink
)
print(f"done: {done} turns in {time.perf_counter() - start:.0f} s")
@artifact(
"scores_extra_{split}_{run}_{seed}_{strategy}_{scope}",
deps=["extra_{split}_{run}_{seed}_{strategy}_{scope}", "eval_turns"],
)
def build_scores_extra(
out, deps, *, split: str, run: str, seed: int, strategy: str, scope: str
):
"""Execute and score the outputs of `extra_…`; a probe scores its
turns only."""
import json
from convfinqa.evaluate import score_rows, summarize
from convfinqa.program_match import add_program_match
rows = list(
deps[f"extra_{split}_{run}_{seed}_{strategy}_{scope}"]
.jsonl("predictions.jsonl")
)
turns = list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl"))
if scope == "probe":
keys = {(r["id"], r["turn"]) for r in rows}
turns = [t for t in turns if (t["id"], t["turn"]) in keys]
scores = add_program_match(score_rows(rows, turns), rows, turns)
(out / "scores.jsonl").write_text(
"".join(json.dumps(s) + "\n" for s in scores)
)
(out / "summary.json").write_text(
json.dumps(summarize(scores), indent=2)
)
```
```{python}
#HEAVY
greedy_rows = pd.DataFrame(get("tuned_val_main_0_pred")\
.jsonl("predictions.jsonl"))
```
```{python}
#HEAVY
vote_full = pd.DataFrame(
get("extra_val_main_0_vote_full").jsonl("predictions.jsonl")
)
scores["vote"] = list(
get("scores_extra_val_main_0_vote_full").jsonl("scores.jsonl")
)
ci["vote"] = bootstrap_accuracy(scores["vote"])
vote_diff = paired_difference(scores["vote"], scores["pred"])
assert not (vote_diff["excludes_zero"] and vote_diff["difference"] > 0)
assert not vote_diff["excludes_zero"]
per_turn = (
pd.DataFrame(scores["vote"])[["id", "turn", "correct"]]
.merge(pd.DataFrame(scores["pred"])[["id", "turn", "correct"]],
on=["id", "turn"], suffixes=("_vote", "_greedy"))
.merge(vote_full[["id", "turn", "agreement"]], on=["id", "turn"])
)
per_turn["unanimous"] = per_turn.agreement == 1
by_agreement = per_turn.groupby("unanimous").agg(
turns=("correct_vote", "size"),
vote=("correct_vote", "mean"),
greedy=("correct_greedy", "mean"),
)
unanimous_share = by_agreement.loc[True, "turns"] / by_agreement.turns.sum()
assert unanimous_share > 0.8
assert by_agreement.loc[True, "vote"] > by_agreement.loc[False, "vote"]
wrong_vote = per_turn[~per_turn.correct_vote]
wrong_unanimous = wrong_vote.unanimous.mean()
assert wrong_unanimous > 0.5
rows_full = [
("greedy, one attempt", "pred", 1.0,
greedy_rows.prompt_tokens.mean(), greedy_rows.new_tokens.mean()),
("self-consistency, 5 samples", "vote",
vote_full.generations.mean(),
vote_full.prompt_tokens.mean(), vote_full.new_tokens.mean()),
]
pd.DataFrame([
{
"system": label,
"accuracy": f"{ci[key]['accuracy']:.1%}",
"95% interval": f"[{ci[key]['low']:.1%}, {ci[key]['high']:.1%}]",
"generations per turn": f"{gens:.1f}",
"prompt tokens per turn": f"{prompt:,.0f}",
"generated tokens per turn": f"{new:.1f}",
}
for label, key, gens, prompt, new in rows_full
]).set_index("system")
```
On the whole validation split, five samples with a vote reach
`{python} f"{ci['vote']['accuracy']:.1%}"` against `{python} f"{ci['pred']['accuracy']:.1%}"` for one greedy
answer, a paired difference of `{python} f"{100 * vote_diff['difference']:+.1f}"` points (95% interval
`{python} f"{100 * vote_diff['low']:+.1f}"` to `{python} f"{100 * vote_diff['high']:+.1f}"`), for
`{python} f"{vote_full.generations.mean():.0f}"` times the generations and
`{python} f"{vote_full.new_tokens.mean() / greedy_rows.new_tokens.mean():.1f}"` times the generated tokens. The
extra generations do not buy accuracy here. The samples are unanimous on
`{python} f"{unanimous_share:.0%}"` of the turns, so on most turns there is nothing for a vote to decide, and the
turns where they disagree are the hard ones (`{python} f"{by_agreement.loc[False, 'vote']:.0%}"` correct, against
`{python} f"{by_agreement.loc[True, 'vote']:.0%}"` when unanimous). Of the turns the vote gets wrong,
`{python} f"{wrong_unanimous:.0%}"` are turns where all five samples gave the same answer: a majority cannot
repair an error that the model makes every time. What is wrong is mostly the program, not its syntax
(@sec-evaluating-errors), and sampling the same model more often does not change that.
## What a turn costs
The systems of this chapter differ in what they cost as well as in what they get right. The cost is counted in
units that do not depend on the machine: generations per turn, prompt tokens (read once, in one pass) and generated
tokens (produced one at a time, so a generated token is dearer than a prompt token, and the table keeps them apart).
Seconds depend on the device and its settings, so they are left out.
```{python}
#HEAVY
COST = [
("untuned, e0p", "untuned_val_e0p_0_pred", "zero"),
("untuned, e3p", "untuned_val_e3p_0_pred", "base"),
("fine-tuned", "tuned_val_main_0_pred", "pred"),
("fine-tuned, e3p prompt", "prompted_tuned_val_main_0_e3p_0_pred", "shots"),
("fine-tuned, 5-sample vote", "extra_val_main_0_vote_full", "vote"),
]
cost_rows = {}
for label, name, key in COST:
frame = pd.DataFrame(get(name).jsonl("predictions.jsonl"))
cost_rows[key] = {
"label": label,
"generations": frame.get(
"generations", pd.Series(1, index=frame.index)
).mean(),
"prompt": frame.prompt_tokens.mean(),
"generated": frame.new_tokens.mean(),
}
assert cost_rows["pred"]["generated"] < cost_rows["zero"]["generated"]
assert cost_rows["shots"]["prompt"] > 3 * cost_rows["pred"]["prompt"]
assert cost_rows["vote"]["generations"] == 5
assert all(
cost_rows["pred"][k] == min(c[k] for c in cost_rows.values())
for k in ("prompt", "generated")
)
pd.DataFrame([
{
"system": c["label"],
"accuracy": f"{ci[key]['accuracy']:.1%}",
"generations per turn": f"{c['generations']:.0f}",
"prompt tokens per turn": f"{c['prompt']:,.0f}",
"generated tokens per turn": f"{c['generated']:.1f}",
}
for key, c in cost_rows.items()
]).set_index("system")
```
The fine-tuned model with its training prompt reads the fewest prompt tokens and writes the fewest generated tokens
of the five: it reads `{python} f"{cost_rows['pred']['prompt']:,.0f}"` prompt tokens (the table and the
conversation, with no examples) and writes `{python} f"{cost_rows['pred']['generated']:.1f}"`, where the untuned
model with the same prompt writes `{python} f"{cost_rows['zero']['generated']:.1f}"`. The three examples of `e3p`
make the prompt `{python} f"{cost_rows['shots']['prompt'] / cost_rows['pred']['prompt']:.1f}"` times as long, whether
the model is tuned or not, and the five-sample vote pays for five of everything. Fine-tuning moves the cost of the
examples from every call to the training run, which is paid once.
## Summary
- **Accuracy.** On the validation split, with the predicted history, the fine-tuned model gets
`{python} f"{ci['pred']['accuracy']:.1%}"` of the turns right, against `{python} f"{ci['zero']['accuracy']:.1%}"` for
the untuned model with the same prompt and `{python} f"{ci['base']['accuracy']:.1%}"` with the best prompt. With the
gold history it gets `{python} f"{ci['gold']['accuracy']:.1%}"`. By program accuracy, the stricter measure, it gets
`{python} f"{ci_program['pred']['accuracy']:.1%}"`.
- **Where it goes wrong.** The wrong outputs are valid programs
(`{python} invalid["pred"]` of `{python} wrong["pred"]` is not). `{python} counts["right with the gold history"]` of the
`{python} n_wrong` wrong turns are right once the earlier answers are the gold ones, and most of the rest use other
numbers or other operations. At the first token where a wrong program departs from the gold one, the gold token is
among the model's top three in `{python} f"{top3:.0%}"` of the turns.
- **What does not change it.** Three examples in the prompt change the accuracy by
`{python} f"{100 * extra['difference']:+.1f}"` points, merging the adapter by
`{python} f"{100 * merged_stats['bf16']['diff']['difference']:+.1f}"` points, and a vote of five samples by
`{python} f"{100 * vote_diff['difference']:+.1f}"` points; the paired interval of each includes zero.
- **What it costs.** One greedy generation reading
`{python} f"{cost_rows['pred']['prompt']:,.0f}"` prompt tokens and writing
`{python} f"{cost_rows['pred']['generated']:.1f}"`, the fewest of every system compared here.
These are validation numbers, used to choose between options. The development split gives the final numbers of the headline comparison, once, in
the last part of the book.