13  Evaluating the fine-tuned model

You will learn:

Chapter 12 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 Chapter 11 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.

13.1 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.

13.2 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 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.

13.3 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 Chapter 12 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.

Code
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)
    )

13.4 Results on the validation split

The fine-tuned model uses the adapter that Chapter 12 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 Chapter 11. 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 (Chapter 11, “Under the hood: why pair, and why resample pages”).

Code
#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")
accuracy 95% interval invalid outputs
system
untuned, e0p (predicted history) 0.3% [0.0%, 0.7%] 99.2%
untuned, e3p (predicted history) 57.2% [53.1%, 61.2%] 16.4%
fine-tuned, predicted history 83.7% [79.7%, 87.4%] 0.0%
fine-tuned, gold history 90.6% [88.2%, 92.7%] 0.0%
Code
#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 0.3% of the turns right and the fine-tuned model 83.7% (predicted history throughout): a difference of +83.5 points, with a paired 95% interval of [+79.4, +87.1]. Prompting recovers part of that: with the best prompt the untuned model reaches 57.2%, and fine-tuning is still ahead of it by +26.6 points, with a paired 95% interval of [+22.9, +30.2]. 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 90.6%, +6.8 points ([+4.8, +9.1]) over its predicted-history score: that gap is what the model loses to its own earlier mistakes.

13.4.1 Accuracy by turn and type of conversation

Code
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()
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.
Figure 13.1: 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.
Code
#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 7 and 13 points through turn 5. From turn 6 on, the groups are too small to read: the smallest holds 1 turn.

Code
#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
untuned, e3p fine-tuned, predicted fine-tuned, gold
type I 58.2% (n=748) 84.8% (n=748) 92.8% (n=748)
type II 55.2% (n=377) 81.7% (n=377) 86.2% (n=377)

Type I conversations come from one annotated question, and type II from two questions joined into one conversation (Chapter 2).

13.5 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.

13.5.1 Program accuracy

Execution accuracy asks whether the program gives the right number. 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.

Code
#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
execution accuracy program accuracy 95% interval same text as gold right answer, other program
untuned, e0p 0.3% 0.2% [0.0%, 0.6%] 0.2% 1
untuned, e3p 57.2% 49.7% [45.4%, 53.9%] 47.6% 84
fine-tuned, predicted 83.7% 81.7% [77.3%, 85.7%] 80.0% 23
fine-tuned, gold 90.6% 89.8% [87.3%, 91.9%] 88.5% 9

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 19 programs that the text comparison rejects, which is 1.7 points of accuracy.

13.5.1.1 Examples with swapped operands in sums and products

Code
#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)
fine-tuned model gold program
0 divide(const_100, 28), multiply(840, #0) divide(const_100, 28), multiply(#0, 840)
1 add(262.9, 690.6) add(690.6, 262.9)
2 add(3.1, 5.7) add(5.7, 3.1)
3 add(3.1, 5.7), subtract(19.8, #0) add(5.7, 3.1), subtract(19.8, #0)
4 multiply(1.6, const_1000) multiply(const_1000, 1.6)

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.

13.5.1.2 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:

Code
#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")
turns model gold
difference from the gold program
a constant written as a number 11 subtract(206, 100) subtract(206, const_100)
that, with trailing zeros 4 subtract(331.43, 100.00) subtract(331.43, const_100)
signs dropped, cancelling in a ratio 3 subtract(4027, 1280), divide(#0, 1280) subtract(-4027, -1280), divide(#0, -1280)
other 5 529370 subtract(2291520, 1762150)

23 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 5 turns differ in other ways. For the untuned model with e3p, many more turns have the right answer with another program (84).

13.5.2 Where the numbers come from

Program accuracy compares whole programs. The 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 is separate: it asks whether the answer is the gold answer times a power of ten.

Code
@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)
    )
Code
#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
outputs that run same numbers as gold, as text same numbers as gold, as values every number comes from the page
untuned, e0p 9 22.2% 22.2% 100.0%
untuned, e3p 941 62.2% 65.7% 84.1%
fine-tuned, predicted 1125 82.7% 83.8% 100.0%
fine-tuned, gold 1125 91.0% 91.6% 100.0%

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 1.2 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 (100.0% 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 16% 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).

Code
#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
untuned, e0p untuned, e3p fine-tuned, predicted fine-tuned, gold
answer off by ×100 or ÷100 4 60 9 4
answer off by another power of ten 0 36 9 9

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:

Code
#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
turns untuned, e3p fine-tuned, predicted fine-tuned, gold
no "percent" in the question 959 64.5% 82.9% 89.7%
"percent" in the question, gold does not multiply by 100 159 15.1% 88.7% 95.6%
"percent" in the question, gold multiplies by 100 7 0.0% 85.7% 100.0%

A wrong scale is a small part of the fine-tuned model’s failures: 18 of its 183 wrong turns, 9 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 15% of the turns and the fine-tuned model on 89%. Only 7 turns want the percentage itself, too few to say anything about them.

13.6 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.

13.6.1 Where the failures are

Code
#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
untuned, e0p untuned, e3p fine-tuned, predicted fine-tuned, gold
correct 3 643 942 1019
invalid output 1116 184 0 0
wrong operations 0 151 62 38
wrong numbers 0 65 74 37
wrong answer, right shape 6 82 47 31

The untuned model failed on the format of its answer: with the same prompt as the fine-tuned model, 1116 of its 1122 wrong turns are not valid programs, 805 of them a program wrapped in a code fence, and even with the three examples of e3p, 184 of 482. After fine-tuning it is 0 of 183 (0 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, 74 of the 183 wrong turns. That is a failure of reading the page and reasoning, and not of writing the language.

13.6.2 What the fine-tuned model gets wrong

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.

Code
#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")
turns share model gold
type
right with the gold history 81 44% add(4.8, 6.7), divide(#0, const_2) add(12.3, 11.0), divide(#0, const_2)
other numbers 48 26% add(4.8, 6.7) add(12.3, 11.0)
wrong operation 31 17% divide(228, 100), subtract(#0, const_1) divide(228, 100), divide(#0, 100)
wrong scale 11 6% add(7, 1) add(1%, 7%)
all other types 12 7%

81 of the 183 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 77 turns by which the gold history is ahead; the model is not wrong at them for a reason of its own. Of the rest, 48 have the right operations with other numbers, or another number where a number was asked for, and 31 have other operations. The remaining types are sign dropped (10), other (1), operands reversed (1).

Code
#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 206 of the 1125 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 46 of the 206, alone or together, and no turn has two alternative explanations. The other 160 differ in what the program says.

13.6.3 How close was the right token?

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.

Code
@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)
    )
Code
#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"
]]
turns gold token in top 3 median probability ratio within a factor of 10
label
right with the gold history 81 88% 0.000 11%
other numbers 48 94% 0.041 29%
wrong operation 31 77% 0.024 35%
wrong scale 11 91% 0.153 55%
sign dropped 10 100% 0.274 70%
other 1 100% 0.325 100%
operands reversed 1 100% 0.607 100%

At the first token where the two programs differ, the gold token is among the model’s top three in 89% of the 183 wrong turns, and in the second place in 128 of them. The model’s own token was the most probable one in 100% of the turns, so the re-scoring reproduces what it wrote. The gold token ranks first in 0 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 0.013, and the gold token comes within a factor of ten in 27% 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 98%. By type of mistake, the dropped signs are the near misses (the gold token is within a factor of ten in 70% of those turns), while in the turns that are wrong only because of the earlier answers it is within a factor of ten in 11%: with its own history in the prompt, the model was sure of the program it wrote.

13.7 Variations on the setup

13.7.1 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 Chapter 11: 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.

Code
@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)
    )
Code
#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")
accuracy 95% interval prompt tokens per turn
tuned model, predicted history
training prompt, no examples 83.7% [79.7%, 87.4%] 1,065
e3p prompt, three examples 84.4% [80.3%, 88.0%] 4,463

With the three examples the tuned model gets 84.4%, against 83.7% without them: a difference of +0.6 points, with a paired 95% interval of [-1.2, +2.6]. 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 1.2 points (the lower end of the interval), and that the effect, if there is one, is small next to the 27 points that fine-tuning added to the best prompt of the untuned model. The effect, if any, is not free: the prompt is 4.2 times as long (4,463 tokens against 1,065), 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.

13.7.2 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. Chapter 9 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.

Code
@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)
    )
Code
#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")
accuracy difference to separate adapter outputs with different text turns whose correctness changes
weights
merged, bf16 83.6% -0.1 [-0.3, +0.0] 11 1
merged, fp32 83.6% -0.1 [-0.3, +0.0] 7 1
Code
#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 -0.1 points for bf16 and -0.1 for fp32, and both intervals contain zero. The text of 11 of the 1,125 outputs differs after the bf16 merge, and 7 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.

13.7.3 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 (Wang et al. (2023)): 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.

Code
@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)
    )
Code
#HEAVY
greedy_rows = pd.DataFrame(get("tuned_val_main_0_pred")\
    .jsonl("predictions.jsonl"))
Code
#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")
accuracy 95% interval generations per turn prompt tokens per turn generated tokens per turn
system
greedy, one attempt 83.7% [79.7%, 87.4%] 1.0 1,065 14.7
self-consistency, 5 samples 83.0% [79.1%, 86.7%] 5.0 5,327 73.4

On the whole validation split, five samples with a vote reach 83.0% against 83.7% for one greedy answer, a paired difference of -0.7 points (95% interval -1.7 to +0.2), for 5 times the generations and 5.0 times the generated tokens. The extra generations do not buy accuracy here. The samples are unanimous on 91% 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 (39% correct, against 87% when unanimous). Of the turns the vote gets wrong, 68% 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 (Section 13.6.2), and sampling the same model more often does not change that.

13.8 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.

Code
#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")
accuracy generations per turn prompt tokens per turn generated tokens per turn
system
untuned, e0p 0.3% 1 1,132 61.6
untuned, e3p 57.2% 1 4,466 17.3
fine-tuned 83.7% 1 1,065 14.7
fine-tuned, e3p prompt 84.4% 1 4,463 14.9
fine-tuned, 5-sample vote 83.0% 5 5,327 73.4

The fine-tuned model with its training prompt reads the fewest prompt tokens and writes the fewest generated tokens of the five: it reads 1,065 prompt tokens (the table and the conversation, with no examples) and writes 14.7, where the untuned model with the same prompt writes 61.6. The three examples of e3p make the prompt 4.2 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.

13.9 Summary

  • Accuracy. On the validation split, with the predicted history, the fine-tuned model gets 83.7% of the turns right, against 0.3% for the untuned model with the same prompt and 57.2% with the best prompt. With the gold history it gets 90.6%. By program accuracy, the stricter measure, it gets 81.7%.
  • Where it goes wrong. The wrong outputs are valid programs (0 of 183 is not). 81 of the 183 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 89% of the turns.
  • What does not change it. Three examples in the prompt change the accuracy by +0.6 points, merging the adapter by -0.1 points, and a vote of five samples by -0.7 points; the paired interval of each includes zero.
  • What it costs. One greedy generation reading 1,065 prompt tokens and writing 14.7, 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.