You will learn:

Every program in this book so far is in the ConvFinQA DSL: subtract(5, 3), divide(#0, 3). The DSL is small and exact, and it is also unlike anything the model saw in pretraining. A model trained on a great deal of code might write Python, which it knows, more reliably than a language invented for one dataset. The ConvFinQA paper (Chen et al. 2022) reports that GPT-3 did better with ordinary math notation than with the DSL, and program-of-thought prompting (Chen et al. 2023) writes Python for the same reason. This chapter tests it on our model.

The test is on the untuned model first. The question is how well the model already knows Python, and an adapter trained to write one format or the other would answer a different question. A second stage trains an adapter for Python, and compares it with the DSL adapter of Chapter 12, because a difference between the untuned models might not survive fine-tuning. That stage was planned to run only if the untuned model did clearly better in Python, and it did. Every number in this chapter is measured on the validation split; the development split is not used.

14.1 Python as an output format

A program in the DSL is a list of steps. The Python form keeps the arithmetic and writes it the way a person would: a step that is used once is put inside the expression that uses it, a step that is used more than once is named, and the answer is assigned to ans. convfinqa.dsl.python_format.to_python does the translation, and it keeps the structure of the program exactly, with parentheses where it needs them, so that the operations are the same and in the same order.

Code
import pandas as pd

from convfinqa.artifacts import artifact, get
from convfinqa.data.tables import turn_rows
from convfinqa.dsl import executor, python_format

train_fit = list(get("train_val_split").jsonl("train_fit.jsonl"))
programs = [r["program"] for r in turn_rows(train_fit)]
translated = [python_format.to_python(p) for p in programs]
same_answer = [
    python_format.try_execute_python(code)[0] == executor.try_execute(p)[0]
    for p, code in zip(programs, translated)
]
named = [p for p, code in zip(programs, translated) if "\n" in code]
assert all(same_answer)
# naming a step is the exception
assert len(named) < 0.01 * len(programs)


def first(condition):
    return next(p for p in programs if condition(p, python_format.to_python(p)))


examples = [
    first(lambda p, c: "(" not in p),
    first(lambda p, c: p.count("(") == 1 and "%" not in p and "greater" not in p),
    first(lambda p, c: p.count("(") == 2 and "\n" not in c and "%" not in p),
    first(lambda p, c: "%" in p),
    first(lambda p, c: "greater" in p),
    first(lambda p, c: "\n" in c),
]
pd.DataFrame({
    "DSL": examples,
    "Python": [python_format.to_python(p).replace("\n", "; ") for p in examples],
    "answer": [executor.execute(p) for p in examples],
}).set_index("DSL")
Python answer
DSL
9362.2 ans = 9362.2 9362.2
subtract(9362.2, 9244.9) ans = 9362.2 - 9244.9 117.3
subtract(9362.2, 9244.9), divide(#0, 9244.9) ans = (9362.2 - 9244.9) / 9244.9 0.01269
multiply(1.5, const_1000), multiply(#0, 4.02%) ans = 1.5 * 1000 * (4.02 / 100) 60.3
subtract(1018.5, 907.0), subtract(1033.9, 792.9), greater(#0, #1) ans = 1018.5 - 907.0 > 1033.9 - 792.9 no
add(0.10, 0.10), add(#0, 0.10), add(#1, #0) v0 = 0.10 + 0.10; ans = v0 + 0.10 + v0 0.5

A percentage such as 4.02% is written 4.02 / 100, which keeps the digits that are on the page. The constants const_100 and const_m1 become the numbers 100 and -1. Of the 9,979 gold programs in the training conversations, every one gives the same answer in Python as in the DSL, and only 15 need a named step.

14.2 Running Python written by a model

A model asked for “a valid Python program” may write anything. Running that with exec would run whatever it wrote. Instead, python_format.execute_python parses the code with ast and walks the tree itself. It accepts assignments; arithmetic and comparisons on numbers; names that were assigned; and the calls round, abs, min, max and sum. All numbers are floats, so a huge power overflows and does not hang. The answer is the value of ans, rounded to five places as in the DSL, or yes or no for a comparison.

Code that is valid Python but outside this list, such as a function definition, an import, a loop or math.sqrt, is not run, and it is reported as its own kind of invalid output, outside the subset. The limit of the evaluator is then visible in the results, and is not mistaken for a mistake of the model.

Code
SNIPPETS = [
    "ans = (5 - 3) / 3",
    "x = 4\nans = round(x * 2.567, 1)",
    "ans = 3 > 2",
    "```python\nans = 1 + 2\n```",
    "import math\nans = math.sqrt(4)",
    "def f():\n    return 1\nans = f()",
    "ans = 1 +",
    "ans = x + 1",
    "ans = 1 / 0",
    "result = 5",
]
pd.DataFrame([
    {
        "code": code.replace("\n", "; "),
        "value": python_format.try_execute_python(code)[0],
        "kind": python_format.try_execute_python(code)[1] or "runs",
    }
    for code in SNIPPETS
]).set_index("code")
value kind
code
ans = (5 - 3) / 3 0.66667 runs
x = 4; ans = round(x * 2.567, 1) 10.3 runs
ans = 3 > 2 yes runs
```python; ans = 1 + 2; ``` None code_fence
import math; ans = math.sqrt(4) None outside_subset
def f():;     return 1; ans = f() None outside_subset
ans = 1 + None syntax
ans = x + 1 None runtime
ans = 1 / 0 None runtime
result = 5 None no_ans

14.3 The prompt

The DSL prompts of Chapter 11 describe the language. The Python prompt has three rules and nothing else, so that it measures what the model already knows: a valid Python program, numbers that appear on the page, and the answer assigned to ans. It says nothing about the structure of the program and nothing about the syntax.

Code
from convfinqa.python_eval import MAX_NEW_TOKENS, SYSTEM_PYTHON
from convfinqa.tuned_eval import MAX_NEW_TOKENS as DSL_MAX_NEW_TOKENS

print(SYSTEM_PYTHON)
Answer with a valid Python program. Use only numbers that appear on the page. Assign the final answer to ans.

There are two variants. With no examples the prompt is these rules alone. With examples, the three conversations of example set 0 are shown first, as in Chapter 11, with their gold programs translated by to_python. This is the chat for the first question of a validation conversation, with the long texts cut:

Code
from textwrap import shorten

from convfinqa.prompts import prompt_chat
from convfinqa.python_eval import python_conversation

pool = {c["id"]: c for c in train_fit}
shown = get("example_sets").json("sets.json")["sets"]["0"][:3]
first_val = list(get("train_val_split").jsonl("val.jsonl"))[0]
chat = prompt_chat(
    python_conversation(first_val), 0, SYSTEM_PYTHON,
    [python_conversation(pool[i]) for i in shown],
)
for message in chat:
    print(f"[{message['role']}] " + shorten(
        message["content"].replace("\n", " "), 100, placeholder=" ..."
    ))
single = sum(p.count("(") <= 1 for p in programs) / len(programs)
assert single > 0.5
[system] Answer with a valid Python program. Use only numbers that appear on the page. Assign the final ...
[user] the pension plan investments are held in a master trust , with the northern trust company . ...
[assistant] ans = 14 + 14
[user] what was the value of thrift plan contributions in 2006?
[assistant] ans = 13
[user] what is the total sum?
[assistant] ans = 14 + 14 + 13
[user] what is the total sum divided by 3?
[assistant] ans = (14 + 14 + 13) / 3
[user] hologic , inc . notes to consolidated financial statements ( continued ) ( in thousands , except ...
[assistant] ans = 145900 / 220600
[user] what portion of the estimated purchase price is developed technology and know how?
[assistant] ans = 39500 / 220600
[user] part iii item 10 . directors , executive officers and corporate governance for the information ...
[assistant] ans = 1233672
[user] and what is the number of securities remaining available for future issuance under equity ...
[assistant] ans = 4903018
[user] what is, then, the combined total of those numbers of securities?
[assistant] ans = 1233672 + 4903018
[user] what is the number of securities to be issued upon exercise of outstanding options warrants and ...
[assistant] ans = 1233672
[user] and how much does this number of securities represent in relation to that combined total?
[assistant] ans = 1233672 / (1233672 + 4903018)
[user] 26 | 2009 annual report in fiscal 2008 , revenues in the credit union systems and services ...

Most answers in the examples are short: 70% of the gold programs of the training conversations are a number or a single operation, which Python writes as ans = a - b. The style of the translation is therefore part of what the examples teach, and the results with examples are partly a result about that style.

A fence around the code counts as invalid, as in the DSL, and the fence rate is reported next to the accuracy. Free-form Python is longer than a DSL program, so the generation limit is 256 tokens and not 96, and the share of generations that reach it is reported.

14.4 The code

python_untuned_{split}_{variant}_{seed}_{mode} generates the answers with the untuned model; the variant e0 has no examples and e3 has three from example set seed. scores_python_untuned_… is light: it executes and scores the outputs. The scores have the fields of the DSL scores, so everything that compares systems works on them.

Code
@artifact(
    "python_untuned_{split}_{variant}_{seed}_{mode}",
    deps=["train_val_split", "eval_turns", "example_sets"],
    files=["configs/baseline.json"],
    heavy=True,
)
def build_python_untuned(
    out, deps, files, *, split: str, variant: str, seed: int, mode: str
):
    """Generate the untuned model's Python answer for every turn of a split.

    Args:
        out: Output directory; `predictions.jsonl` is written to it.
        deps: The conversations and the example sets.
        files: `configs/baseline.json` (the model).
        split: `val`, or `dev` once `configs/FROZEN` exists.
        variant: `e0` (no examples) or `e3` (three examples).
        seed: The example set; 0 for `e0`.
        mode: `gold` or `pred`, the history of the earlier turns.
    """
    import json
    import time

    from convfinqa.python_eval import generate_untuned_python
    from convfinqa.tuned_eval import split_conversations

    cfg = files["configs/baseline.json"].json()
    if variant not in ("e0", "e3"):
        raise ValueError(f"variant must be 'e0' or 'e3', not {variant!r}")
    n_examples = int(variant[1:])
    if n_examples == 0 and seed != 0:
        raise ValueError(
            "a variant with no examples has no example set: use seed 0"
        )
    convs = split_conversations(
        split,
        list(deps["train_val_split"].jsonl("val.jsonl")),
        list(deps["eval_turns"].jsonl("dev.jsonl")),
    )
    examples = []
    if n_examples:
        wanted = deps["example_sets"].json(
            "sets.json"
        )["sets"][str(seed)][:n_examples]
        pool = {
            c["id"]: c
            for c in deps["train_val_split"].jsonl("train_fit.jsonl")
        }
        examples = [pool[i] for i in wanted]
    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_untuned_python(cfg, convs, examples, mode, sink)
    print(f"done: {done} turns in {time.perf_counter() - start:.0f} s")


@artifact(
    "scores_python_untuned_{split}_{variant}_{seed}_{mode}",
    deps=["python_untuned_{split}_{variant}_{seed}_{mode}", "eval_turns"],
)
def build_scores_python_untuned(
    out, deps, *, split: str, variant: str, seed: int, mode: str
):
    """Execute and score the outputs of `python_untuned_…`."""
    import json

    from convfinqa.evaluate import summarize
    from convfinqa.python_eval import score_python_rows

    rows = list(
        deps[f"python_untuned_{split}_{variant}_{seed}_{mode}"]
        .jsonl("predictions.jsonl")
    )
    turns = list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl"))
    scores = score_python_rows(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)
    )

14.5 Untuned, Python against the DSL

Four conditions: with and without examples, and with the earlier turns of the conversation filled in with the model’s own answers (predicted history) or with the gold ones. The DSL runs are those of Chapter 11 with the plain system message (e0p and e3p), on the same validation turns and, for the runs with examples, the same example set. Python has three examples translated to Python, and the DSL has the same three in the DSL.

Code
#HEAVY
from convfinqa.python_eval import score_python_rows
from convfinqa.stats import bootstrap_accuracy, paired_difference

CONDITIONS = {
    "no examples, predicted history": ("e0", "pred"),
    "three examples, predicted history": ("e3", "pred"),
    "no examples, gold history": ("e0", "gold"),
    "three examples, gold history": ("e3", "gold"),
}
PYTHON = {
    ("e0", "pred"): get("scores_python_untuned_val_e0_0_pred"),
    ("e3", "pred"): get("scores_python_untuned_val_e3_0_pred"),
    ("e0", "gold"): get("scores_python_untuned_val_e0_0_gold"),
    ("e3", "gold"): get("scores_python_untuned_val_e3_0_gold"),
}
DSL = {
    ("e0", "pred"): get("scores_untuned_val_e0p_0_pred"),
    ("e3", "pred"): get("scores_untuned_val_e3p_0_pred"),
    ("e0", "gold"): get("scores_untuned_val_e0p_0_gold"),
    ("e3", "gold"): get("scores_untuned_val_e3p_0_gold"),
}
py_scores = {k: list(h.jsonl("scores.jsonl")) for k, h in PYTHON.items()}
dsl_scores = {k: list(h.jsonl("scores.jsonl")) for k, h in DSL.items()}
py_summary = {k: h.json("summary.json") for k, h in PYTHON.items()}
dsl_summary = {k: h.json("summary.json") for k, h in DSL.items()}
py_ci = {k: bootstrap_accuracy(v) for k, v in py_scores.items()}
dsl_ci = {k: bootstrap_accuracy(v) for k, v in dsl_scores.items()}
lead = {k: paired_difference(py_scores[k], dsl_scores[k]) for k in PYTHON}
n_turns = py_summary[("e3", "pred")]["n"]
assert all(
    s["n"] == n_turns for s in [*py_summary.values(), *dsl_summary.values()]
)

pct = lambda x: f"{100 * x:.1f}%"
pts = lambda x: f"{100 * x:+.1f}"
rows = []
for label, key in CONDITIONS.items():
    for name, ci, summary in [
        ("DSL", dsl_ci, dsl_summary),
        ("Python", py_ci, py_summary),
    ]:
        rows.append({
            "condition": label,
            "output": name,
            "accuracy": pct(ci[key]["accuracy"]),
            "95% interval":
                f"[{pct(ci[key]['low'])}, {pct(ci[key]['high'])}]",
            "invalid": pct(summary[key]["invalid_rate"]),
            "hit the limit": pct(summary[key]["truncated"] / n_turns),
        })
pd.DataFrame(rows).set_index(["condition", "output"])
accuracy 95% interval invalid hit the limit
condition output
no examples, predicted history DSL 0.3% [0.0%, 0.7%] 99.2% 32.9%
Python 0.0% [0.0%, 0.0%] 100.0% 15.8%
three examples, predicted history DSL 57.2% [53.1%, 61.2%] 16.4% 1.5%
Python 64.5% [60.2%, 68.6%] 8.9% 1.4%
no examples, gold history DSL 28.1% [25.9%, 30.3%] 64.3% 15.7%
Python 38.8% [35.9%, 41.8%] 46.7% 5.8%
three examples, gold history DSL 66.0% [63.1%, 69.0%] 12.4% 0.9%
Python 74.7% [71.7%, 77.5%] 5.1% 0.7%
Code
#HEAVY
# the lead of Python over the DSL, in every condition but the one where
# neither can answer
assert py_ci[("e0", "pred")]["accuracy"] < 0.01
assert dsl_ci[("e0", "pred")]["accuracy"] < 0.01
assert not lead[("e0", "pred")]["excludes_zero"]
for key in [("e3", "pred"), ("e0", "gold"), ("e3", "gold")]:
    assert lead[key]["low"] > 0, key
pd.DataFrame([
    {
        "condition": label,
        "Python − DSL (points)": pts(lead[key]["difference"]),
        "95% paired interval":
            f"[{pts(lead[key]['low'])}, {pts(lead[key]['high'])}]",
    }
    for label, key in CONDITIONS.items()
]).set_index("condition")
Python − DSL (points) 95% paired interval
condition
no examples, predicted history -0.3 [-0.7, +0.0]
three examples, predicted history +7.4 [+4.1, +10.5]
no examples, gold history +10.8 [+7.9, +13.5]
three examples, gold history +8.6 [+6.1, +11.1]
Code
#HEAVY
dsl_fence = dsl_summary[("e0", "pred")]["by_kind"]["code_fence"] / n_turns
py_unparsed = py_summary[("e0", "pred")]["by_kind"]["syntax"] / n_turns
assert dsl_fence > 0.5 and py_unparsed > 0.9

Without examples and with the model’s own history, neither format works: 98.8% of the Python outputs do not parse as Python, and 71.6% of the DSL outputs are code fences. The accuracy of Python is 0.0%, against 0.3% for the DSL. Three rules about what to write are not a format the model follows by itself.

With three examples it does, in both formats, and Python is ahead by +7.4 points with predicted history (paired interval [+4.1, +10.5]) and by +8.6 points with the gold history ([+6.1, +11.1]). Both intervals are far from zero.

Gold history without examples is the surprise: the only difference from the run above is that the earlier turns of the conversation are written in the format, and the model reaches 38.8% in Python and 28.1% in the DSL (a lead of +10.8 points, interval [+7.9, +13.5]). With its own history the same prompt reaches 0.0% and 0.3%.

14.5.1 What the Python runs produce

Code
#HEAVY
KINDS = [
    "correct", "wrong_answer", "code_fence", "syntax", "outside_subset",
    "runtime", "no_ans", "not_a_number", "empty"
]
kind_rows = {}
for label, key in CONDITIONS.items():
    counts = py_summary[key]["by_kind"]
    kind_rows[label] = {k: counts.get(k, 0) for k in KINDS if k in counts}
    assert sum(counts.values()) == n_turns
pd.DataFrame(kind_rows).fillna(0).astype(int)
no examples, predicted history three examples, predicted history no examples, gold history three examples, gold history
code_fence 14 0 5 0
syntax 1111 100 520 57
correct 0 726 437 840
wrong_answer 0 299 163 228
Code
#HEAVY
PREDICTIONS = {
    ("e0", "pred"): get("python_untuned_val_e0_0_pred"),
    ("e3", "pred"): get("python_untuned_val_e3_0_pred"),
    ("e0", "gold"): get("python_untuned_val_e0_0_gold"),
    ("e3", "gold"): get("python_untuned_val_e3_0_gold"),
}
val_turns = list(get("eval_turns").jsonl("val_turns.jsonl"))
stripped = {
    k: score_python_rows(
        list(h.jsonl("predictions.jsonl")), val_turns, strip_fences=True
    )
    for k, h in PREDICTIONS.items()
}
stripped_acc = {
    k: sum(s["correct"] for s in v) / len(v) for k, v in stripped.items()
}
fence_rate = {
    k: py_summary[k]["by_kind"].get("code_fence", 0) / n_turns for k in PYTHON
}
outside = {
    k: py_summary[k]["by_kind"].get("outside_subset", 0) for k in PYTHON
}

An output that is invalid in Python is, in every condition, a syntax error or a code fence; the evaluator’s own limit does not appear: 0 outputs are valid Python outside the subset. A fence is rare once the model has seen examples (0.0% of the turns with predicted history, 0.0% with the gold history). Stripping the fences before running leaves the accuracy of the runs with examples at 64.5% (predicted history) and 74.7% (gold history).

Code
#HEAVY
# the claims of the paragraph above
assert sum(outside.values()) == 0
assert all(
    set(py_summary[k]["by_kind"]) <= {"correct", "wrong_answer", "syntax", "code_fence"}
    for k in PYTHON
)
assert all(
    py_summary[k]["by_kind"].get("syntax", 0)
    > py_summary[k]["by_kind"].get("code_fence", 0)
    for k in PYTHON
)
assert all(
    py_summary[("e0", m)]["truncated"] > 3 * py_summary[("e3", m)]["truncated"]
    for m in ("pred", "gold")
)
assert fence_rate[("e3", "pred")] < 0.01 and fence_rate[("e3", "gold")] < 0.01
assert all(
    abs(stripped_acc[k] - py_ci[k]["accuracy"]) < 0.01
    for k in PYTHON if k[0] == "e3"
)

The generation limit is 256 tokens for Python and 96 for the DSL, and the share of turns that hit it is in the table: it is much larger without examples than with them.

14.5.2 By kind of turn

Code
#HEAVY
by_turn = {}
for label, key in [
    ("predicted history", ("e3", "pred")),
    ("gold history", ("e3", "gold")),
]:
    for name, summary in [("DSL", dsl_summary), ("Python", py_summary)]:
        by_turn[(label, name)] = {
            kind: pct(summary[key]["by_number_turn"][kind]["accuracy"])
            for kind in ("number", "program")
        }
pd.DataFrame(by_turn).T.rename(
    columns={
        "number": "answer is a number on the page",
        "program": "answer needs a computation"
    }
)
answer is a number on the page answer needs a computation
predicted history DSL 78.9% 45.3%
Python 82.2% 54.9%
gold history DSL 86.2% 55.0%
Python 88.2% 67.3%
Code
#HEAVY
number_gap = {
    k: py_summary[k]["by_number_turn"]["number"]["accuracy"]
    - dsl_summary[k]["by_number_turn"]["number"]["accuracy"]
    for k in [("e3", "pred"), ("e3", "gold")]
}
program_gap = {
    k: py_summary[k]["by_number_turn"]["program"]["accuracy"]
    - dsl_summary[k]["by_number_turn"]["program"]["accuracy"]
    for k in [("e3", "pred"), ("e3", "gold")]
}
# Python is ahead on both kinds, and by more on the turns that need a computation
assert all(g > 0 for g in number_gap.values())
assert all(program_gap[k] > number_gap[k] for k in number_gap)

Python is ahead on both kinds of turn, and by more where a computation is needed: on the turns that need one, by +9.6 points with predicted history and +12.2 with the gold history, and on the turns whose answer is a number from the page, by +3.3 and +2.0.

14.5.3 First turns and follow-ups

The first turn of a conversation has no history, so the two history modes give it the same prompt. The follow-up turns are where they differ.

Code
#HEAVY
def split_first(scores):
    """Accuracy of the first turn of each conversation, and of the others."""
    first_turn = {}
    for s in scores:
        first_turn[s["id"]] = min(first_turn.get(s["id"], s["turn"]), s["turn"])
    groups = {True: [], False: []}
    for s in scores:
        groups[s["turn"] == first_turn[s["id"]]].append(s["correct"])
    return {
        "first": sum(groups[True]) / len(groups[True]),
        "later": sum(groups[False]) / len(groups[False]),
        "n_first": len(groups[True]),
        "n_later": len(groups[False]),
    }


split = {
    (fmt, v, m): split_first(sc[(v, m)])
    for fmt, sc in [("DSL", dsl_scores), ("Python", py_scores)]
    for v in ("e0", "e3")
    for m in ("pred", "gold")
}
pd.DataFrame(
    [
        {
            "output": fmt,
            "examples": "none" if v == "e0" else "three",
            "history": m,
            "first turn": pct(r["first"]),
            "follow-ups": pct(r["later"]),
        }
        for (fmt, v, m), r in split.items()
    ]
).set_index(["output", "examples", "history"])
first turn follow-ups
output examples history
DSL none pred 0.7% 0.1%
gold 0.7% 38.3%
three pred 74.5% 50.7%
gold 74.5% 62.9%
Python none pred 0.0% 0.0%
gold 0.0% 53.4%
three pred 71.2% 62.0%
gold 71.2% 75.9%
Code
#HEAVY
for fmt in ("DSL", "Python"):
    for v in ("e0", "e3"):
        # the same prompt, so the same answers
        assert split[(fmt, v, "pred")]["first"] \
            == split[(fmt, v, "gold")]["first"]
    # without examples, nothing is right until the history shows the format
    assert split[(fmt, "e0", "pred")]["later"] < 0.01
    assert split[(fmt, "e0", "gold")]["later"] > 0.3
    assert split[(fmt, "e0", "gold")]["first"] < 0.01
    # with examples, the gold history is worth something on follow-ups
    assert split[(fmt, "e3", "gold")]["later"] \
        > split[(fmt, "e3", "pred")]["later"]
    # and with the model's own history, follow-ups are worse than first turns
    assert split[(fmt, "e3", "pred")]["later"] \
        < split[(fmt, "e3", "pred")]["first"]
# the first turns do not favour Python
assert split[("DSL", "e3", "pred")]["first"] \
    > split[("Python", "e3", "pred")]["first"]
# with gold history they are worse in the DSL and better in Python
assert split[("DSL", "e3", "gold")]["later"] \
    < split[("DSL", "e3", "gold")]["first"]
assert split[("Python", "e3", "gold")]["later"] \
    > split[("Python", "e3", "gold")]["first"]

Without examples, all of the gain from the gold history is on the follow-ups. The first turn is 0.0% in Python and 0.7% in the DSL, whichever history it is given. The follow-ups go from 0.0% to 53.4% in Python and from 0.1% to 38.3% in the DSL. This fits the gold turns doing the work of the examples that the prompt does not have: once the answer to the first question is in the conversation in the right format, the model follows it.

With examples, the follow-ups are worse than the first turn when the model’s own answers are the history (62.0% against 71.2% in Python, 50.7% against 74.5% in the DSL). The gold history helps them (+13.9 and +12.2 points), but not to the level of the first turn in the DSL (62.9%), while in Python it is above it (75.9%). This table does not separate how hard the follow-up questions are from how well the model uses the history. What it shows is that the Python lead sits on the follow-ups: on first turns the DSL is ahead by +3.3 points.

14.6 Is a Python adapter worth training?

The rule set before the runs was to train one only if untuned Python is clearly ahead of untuned DSL. It is: in every condition where either format works, the paired interval of the lead excludes zero. That is a statement about the untuned model, and what the model does after fine-tuning is a separate question.

Code
#HEAVY
fewer_invalid = {
    k: dsl_summary[k]["invalid_rate"] - py_summary[k]["invalid_rate"]
    for k in [("e3", "pred"), ("e3", "gold")]
}
# most of the lead is invalid outputs that the DSL runs produce and the
# Python runs do not
assert all(fewer_invalid[k] > 0.8 * lead[k]["difference"] for k in fewer_invalid)

With examples, the DSL runs produce +7.5 and +7.3 points more invalid outputs than the Python runs (predicted and gold history), against leads of +7.4 and +8.6. The lead is about as large as the difference in invalid output, so it may be largely the untuned model failing to write the DSL, which tuning removes: an adapter for the DSL writes a valid program on essentially every turn of the validation data (Section 13.6.2). If a lead remains after tuning, it is a lead in the reasoning, and the only way to see it is to train.

The next step is one adapter for Python with the hyperparameters of the DSL adapter, scored on the validation data in both history modes. It reaches the development data only if its lead over the DSL adapter has a paired interval that excludes zero.

14.7 The Python adapter

The adapter for Python is trained like the DSL adapter of Chapter 8, with the same settings: the run python of configs/train.json has the same entries as main, so train_config_python is the same configuration. Only the data differ. Every gold program is translated by to_python, and the system message is the Python prompt, so the adapter is trained on the prompt it is evaluated with, and the loss counts the Python answers only. convfinqa.python_finetune holds the data and the call; the training is finetune.train_lora.

Code
@artifact(
    "python_lora_{seed}",
    deps=["train_val_split", "train_config_python"],
    heavy=True,
)
def build_python_lora(out, deps, *, seed: int):
    """Train the Python adapter on the train-fit split.

    Args:
        out: The output directory for the adapter and training state.
        deps: The conversations and the `python` run's settings.
        seed: The random seed for training.
    """
    import json

    from convfinqa.python_finetune import train_lora_python

    cfg = deps["train_config_python"].json("config.json")
    fit = list(deps["train_val_split"].jsonl("train_fit.jsonl"))
    val = list(deps["train_val_split"].jsonl("val.jsonl"))
    result = train_lora_python(cfg, fit, val, out, seed)
    history = {k: result.pop(k) for k in ("log_history", "max_steps")}
    (out / "trainer_state.json").write_text(json.dumps(history))
    (out / "metrics.json").write_text(json.dumps(result, indent=2))


@artifact(
    "python_tuned_{split}_{seed}_{mode}",
    deps=[
        "python_lora_{seed}", "train_config_python",
        "train_val_split", "eval_turns",
    ],
    heavy=True,
)
def build_python_tuned(out, deps, *, split: str, seed: int, mode: str):
    """Generate the Python adapter's answer 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.
        seed: The training seed of the adapter.
        mode: `gold` or `pred`, the history of the earlier turns.
    """
    import json
    import time

    from convfinqa.python_finetune import generate_tuned_python
    from convfinqa.tuned_eval import split_conversations

    cfg = deps["train_config_python"].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_tuned_python(
            cfg, deps[f"python_lora_{seed}"].path / "adapter",
            convs, mode, sink,
        )
    print(f"done: {done} turns in {time.perf_counter() - start:.0f} s")


@artifact(
    "scores_python_tuned_{split}_{seed}_{mode}",
    deps=["python_tuned_{split}_{seed}_{mode}", "eval_turns"],
)
def build_scores_python_tuned(out, deps, *, split: str, seed: int, mode: str):
    """Execute and score the outputs of `python_tuned_…`."""
    import json

    from convfinqa.evaluate import summarize
    from convfinqa.python_eval import score_python_rows

    rows = list(
        deps[f"python_tuned_{split}_{seed}_{mode}"].jsonl("predictions.jsonl")
    )
    turns = list(deps["eval_turns"].jsonl(f"{split}_turns.jsonl"))
    scores = score_python_rows(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)
    )

14.8 Fine-tuned, Python against the DSL

The Python adapter is scored on the same validation turns as the DSL adapter of Chapter 12, with the same history modes and the same bootstrap.

Code
#HEAVY
tuned_py_h = {
    "pred": get("scores_python_tuned_val_0_pred"),
    "gold": get("scores_python_tuned_val_0_gold"),
}
tuned_dsl_h = {
    "pred": get("scores_tuned_val_main_0_pred"),
    "gold": get("scores_tuned_val_main_0_gold"),
}
tuned_py = {m: list(h.jsonl("scores.jsonl")) for m, h in tuned_py_h.items()}
tuned_dsl = {m: list(h.jsonl("scores.jsonl")) for m, h in tuned_dsl_h.items()}
tuned_py_summary = {m: h.json("summary.json") for m, h in tuned_py_h.items()}
tuned_dsl_summary = {m: h.json("summary.json") for m, h in tuned_dsl_h.items()}
tuned_py_ci = {m: bootstrap_accuracy(v) for m, v in tuned_py.items()}
tuned_dsl_ci = {m: bootstrap_accuracy(v) for m, v in tuned_dsl.items()}
tuned_lead = {m: paired_difference(tuned_py[m], tuned_dsl[m]) for m in tuned_py}
assert all(
    s["n"] == n_turns
    for s in [*tuned_py_summary.values(), *tuned_dsl_summary.values()]
)

rows = []
for m, label in [("pred", "predicted history"), ("gold", "gold history")]:
    for name, ci, summary in [
        ("DSL", tuned_dsl_ci, tuned_dsl_summary),
        ("Python", tuned_py_ci, tuned_py_summary),
    ]:
        rows.append({
            "history": label,
            "output": name,
            "accuracy": pct(ci[m]["accuracy"]),
            "95% interval": f"[{pct(ci[m]['low'])}, {pct(ci[m]['high'])}]",
            "invalid": pct(summary[m]["invalid_rate"]),
            "hit the limit": pct(summary[m]["truncated"] / n_turns),
        })
pd.DataFrame(rows).set_index(["history", "output"])
accuracy 95% interval invalid hit the limit
history output
predicted history DSL 83.7% [79.7%, 87.4%] 0.0% 0.0%
Python 83.5% [79.1%, 87.5%] 0.0% 0.0%
gold history DSL 90.6% [88.2%, 92.7%] 0.0% 0.0%
Python 91.4% [89.2%, 93.4%] 0.0% 0.0%
Code
#HEAVY
# no lead in either history mode: the intervals of the difference contain zero
assert not any(lead["excludes_zero"] for lead in tuned_lead.values())

# the untuned lead is gone, not reversed: the untuned leads are clear
assert lead[("e3", "pred")]["excludes_zero"] \
    and lead[("e3", "gold")]["excludes_zero"]

# neither adapter has invalid outputs to speak of
assert all(
    s[m]["invalid_rate"] < 0.01
    for s in (tuned_py_summary, tuned_dsl_summary)
    for m in ("pred", "gold")
)

pd.DataFrame([
    {
        "history": label,
        "untuned, three examples": f"{pts(lead[('e3', m)]['difference'])} [{pts(lead[('e3', m)]['low'])}, {pts(lead[('e3', m)]['high'])}]",
        "fine-tuned": f"{pts(tuned_lead[m]['difference'])} [{pts(tuned_lead[m]['low'])}, {pts(tuned_lead[m]['high'])}]",
    }
    for m, label in [("pred", "predicted history"), ("gold", "gold history")]
]).set_index("history")
untuned, three examples fine-tuned
history
predicted history +7.4 [+4.1, +10.5] -0.3 [-2.4, +1.7]
gold history +8.6 [+6.1, +11.1] +0.8 [-0.4, +2.0]

The table above gives, in points of accuracy, the lead of Python over the DSL, with its paired 95% interval: for the untuned model with three examples, and for the fine-tuned adapters. Fine-tuning takes the untuned lead of +7.4 points with predicted history to -0.3 (interval [-2.4, +1.7]), and the lead of +8.6 points with gold history to +0.8 ([-0.4, +2.0]). Both intervals contain zero: once the model is fine-tuned, the data do not show a difference between the formats, in either direction. The adapters make 0 invalid outputs in Python and 0 in the DSL with predicted history, out of 1,125 turns. That fits the untuned lead being mostly about how well the model follows the format, which the adapters have learned in either language.

Each adapter is one training run (seed 0). The intervals above cover the variation between validation conversations, and not the variation between training runs, so a difference of a point or two between the formats could be hidden by either.

Code
#HEAVY
metrics_py = get("python_lora_0").json("metrics.json")
metrics_dsl = get("lora_main_0").json("metrics.json")
# both runs converge: each ends within 2% of its best validation loss, and the two
# best losses are within 5% of each other (the best step itself is where noise puts it)
for m in (metrics_py, metrics_dsl):
    assert m["final_eval_loss"] <= 1.02 * m["best_eval_loss"]
assert abs(metrics_py["best_eval_loss"] / metrics_dsl["best_eval_loss"] - 1) < 0.05

The training runs agree. The validation loss starts at 2.21 for the DSL and 1.45 for Python, and ends at 0.0357 and 0.0357 (best at step 250 for the DSL and 342 for Python; both curves are flat by then). The two losses are measured on different token sequences, so they say that both runs converge, not that one format is easier.

By the rule of the plan, then, the fine-tuned Python rows are not run on the development data, and the book keeps the DSL for the rest of the work. The untuned Python rows are not run on the development data either: the final results keep the one comparison that decides the book, the untuned DSL models against the fine-tuned one, and this chapter’s comparison stays a validation result.

14.9 Numbers from the page, and the scale

The prompt asks for numbers that appear on the page. Two checks from Section 13.6.2 show whether the outputs follow it, here for Python. The literal check compares the numbers written in the code with those of the translated gold program, as text and as values, and tests whether each comes from the page. Python has no named constants, so a program that needs 100 writes 100; the numbers the DSL’s named constants stand for (1 to 9, the powers of ten up to 10^9, and -1) count as allowed. The scale check runs the code and looks for an answer that is the gold answer times, or over, a power of ten. convfinqa.python_checks holds both.

Code
@artifact(
    "checks_python_untuned_{split}_{variant}_{seed}_{mode}",
    deps=[
        "python_untuned_{split}_{variant}_{seed}_{mode}",
        "eval_turns", "train_val_split",
    ],
)
def build_checks_python_untuned(
    out, deps, *, split: str, variant: str, seed: int, mode: str
):
    """The literal and scale checks of an untuned Python run."""
    import json

    from convfinqa.python_checks import check_python_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"python_untuned_{split}_{variant}_{seed}_{mode}"]
        .jsonl("predictions.jsonl")
    )
    checks = check_python_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_python_tuned_{split}_{seed}_{mode}",
    deps=[
        "python_tuned_{split}_{seed}_{mode}", "eval_turns", "train_val_split",
    ],
)
def build_checks_python_tuned(out, deps, *, split: str, seed: int, mode: str):
    """The literal and scale checks of a Python adapter run."""
    import json

    from convfinqa.python_checks import check_python_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"python_tuned_{split}_{seed}_{mode}"].jsonl("predictions.jsonl")
    )
    checks = check_python_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
from convfinqa.python_checks import check_python_rows

py_checks = {
    "untuned, three examples, predicted": list(
        get("checks_python_untuned_val_e3_0_pred").jsonl("checks.jsonl")
    ),
    "untuned, three examples, gold": list(
        get("checks_python_untuned_val_e3_0_gold").jsonl("checks.jsonl")
    ),
    "fine-tuned, predicted": list(
        get("checks_python_tuned_val_0_pred").jsonl("checks.jsonl")
    ),
    "fine-tuned, gold": list(
        get("checks_python_tuned_val_0_gold").jsonl("checks.jsonl")
    ),
}
py_ran = {k: [c for c in v if c["runs"]] for k, v in py_checks.items()}

# the same check on the translated gold programs: the page holds all of their numbers
gold_python = check_python_rows(
    [
        {"id": t["id"], "turn": t["turn"], "output": python_format.to_python(t["program"])}
        for t in val_turns
    ],
    val_turns, list(get("train_val_split").jsonl("val.jsonl")),
)
assert all(c["lit_grounded"] and c["lit_text"] for c in gold_python)

share = lambda rows_, flag: pct(sum(c[flag] for c in rows_) / len(rows_))
ungrounded = {
    k: 1 - sum(c["lit_grounded"] for c in v) / len(v) for k, v in py_ran.items()
}
off_scale = {
    k: sum(c["scale"] is not None for c in v) for k, v in py_checks.items()
}
# the adapters write only numbers of the page; the untuned model does not
assert ungrounded["fine-tuned, predicted"] == 0
assert ungrounded["fine-tuned, gold"] == 0
assert all(ungrounded[k] > 0.02 for k in py_ran if k.startswith("untuned"))
# and the adapters are off by a power of ten on fewer turns
assert all(
    off_scale[a] > 2 * off_scale[b]
    for a, b in [
        ("untuned, three examples, predicted", "fine-tuned, predicted"),
        ("untuned, three examples, gold", "fine-tuned, gold"),
    ]
)

pd.DataFrame({
    k: {
        "outputs that run": len(v),
        "same numbers as gold, as text": share(v, "lit_text"),
        "same numbers as gold, as values": share(v, "lit_value"),
        "every number comes from the page": share(v, "lit_grounded"),
        "answer off by a power of ten (of all turns)": off_scale[k],
    }
    for k, v in py_ran.items()
}).T
outputs that run same numbers as gold, as text same numbers as gold, as values every number comes from the page answer off by a power of ten (of all turns)
untuned, three examples, predicted 1025 67.6% 70.3% 91.4% 111
untuned, three examples, gold 1068 78.5% 79.7% 95.7% 93
fine-tuned, predicted 1125 83.1% 83.9% 100.0% 18
fine-tuned, gold 1125 91.6% 91.8% 100.0% 8

Every number in the translated gold programs is on the page or is a constant, so the check can pass. The adapters pass it on every turn that runs: they write only numbers from the page, so their mistakes are not invented numbers. The untuned model with examples fails it on 8.6% of its turns that run with predicted history and 4.3% with the gold history. The untuned model is also off by a power of ten on 111 and 93 turns, against 18 and 8 for the adapters. The test for numbers from the page is weak, since a page holds many numbers, so it can show that a model invents numbers, and not that it picks the right ones.

14.10 Summary

  • A ConvFinQA program written as Python is the same computation: all 9,979 training programs give the same answer in both, and only 15 need a named step. Python written by a model is run by a whitelist evaluator, never by exec.
  • Untuned, with three examples, Python is +7.4 points ahead of the DSL with predicted history and +8.6 with gold history, and both intervals exclude zero. The lead is about as large as the difference in invalid output, so much of it may be the untuned model not yet writing the DSL.
  • After fine-tuning the formats are not different on validation data: the leads are -0.3 and +0.8 points, and both intervals include zero.
  • Without examples, all of the gain from the gold history is on the follow-up turns, where the earlier answers show the format. With examples, the Python lead is on the follow-ups too: on first turns the DSL is slightly ahead.
  • Checked on the outputs that run, the adapters write only numbers from the page and are rarely off by a power of ten; the untuned model with examples is not, so these checks separate tuned from untuned and not Python from the DSL.
  • Python is not carried forward: the fine-tuned Python rows stay on the validation data, and the later stages use the DSL.