# DSL or Python? {#sec-python-format}
**You will learn:**
- why the book's program language is a question worth testing, and what a fair test of it looks like;
- how a ConvFinQA program is written as Python, and how Python written by a model is run without trusting it;
- how much of the DSL's difficulty the untuned model already avoids when it writes Python, and whether the difference
survives fine-tuning.
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
[@chen2022convfinqa] reports that GPT-3 did better with ordinary math notation than with the DSL, and
program-of-thought prompting [@chen2022program] 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 @sec-training, 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.
## 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.
```{python}
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")
```
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 `{python} f"{len(programs):,}"` gold programs in the
training conversations, every one gives the same answer in Python as in the DSL, and only `{python} len(named)` need a
named step.
## 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.
```{python}
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")
```
## The prompt
The DSL prompts of @sec-baseline 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.
```{python}
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)
```
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 @sec-baseline, 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:
```{python}
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
```
Most answers in the examples are short: `{python} f"{100 * single:.0f}"`% 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 `{python} MAX_NEW_TOKENS` tokens and not
`{python} DSL_MAX_NEW_TOKENS`, and the share of generations that reach it is reported.
## 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.
```{python}
@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)
)
```
## Untuned, Python against the DSL {#sec-python-untuned}
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 @sec-baseline 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.
```{python}
#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"])
```
```{python}
#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}
#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: `{python} pct(py_unparsed)` of the Python
outputs do not parse as Python, and `{python} pct(dsl_fence)` of the DSL outputs
are code fences. The accuracy of Python is `{python} pct(py_ci[("e0", "pred")]["accuracy"])`, against
`{python} pct(dsl_ci[("e0", "pred")]["accuracy"])` 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
`{python} pts(lead[("e3", "pred")]["difference"])` points with predicted history (paired interval
[`{python} pts(lead[("e3", "pred")]["low"])`, `{python} pts(lead[("e3", "pred")]["high"])`]) and by
`{python} pts(lead[("e3", "gold")]["difference"])` points with the gold history
([`{python} pts(lead[("e3", "gold")]["low"])`, `{python} pts(lead[("e3", "gold")]["high"])`]). 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 `{python} pct(py_ci[("e0", "gold")]["accuracy"])` in Python and
`{python} pct(dsl_ci[("e0", "gold")]["accuracy"])` in the DSL
(a lead of `{python} pts(lead[("e0", "gold")]["difference"])` points, interval
[`{python} pts(lead[("e0", "gold")]["low"])`, `{python} pts(lead[("e0", "gold")]["high"])`]). With its own history the same
prompt reaches `{python} pct(py_ci[("e0", "pred")]["accuracy"])` and `{python} pct(dsl_ci[("e0", "pred")]["accuracy"])`.
### What the Python runs produce
```{python}
#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)
```
```{python}
#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: `{python} sum(outside.values())` outputs are valid Python outside the subset. A fence is rare
once the model has seen examples (`{python} pct(fence_rate[("e3", "pred")])` of the turns with predicted history,
`{python} pct(fence_rate[("e3", "gold")])` with the gold history). Stripping the fences before running leaves the
accuracy of the runs with examples at `{python} pct(stripped_acc[("e3", "pred")])` (predicted history) and
`{python} pct(stripped_acc[("e3", "gold")])` (gold history).
```{python}
#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 `{python} MAX_NEW_TOKENS` tokens for Python and `{python} DSL_MAX_NEW_TOKENS` for the DSL, and the
share of turns that hit it is in the table: it is much larger without examples than with them.
### By kind of turn
```{python}
#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"
}
)
```
```{python}
#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
`{python} pts(program_gap[("e3", "pred")])` points with predicted history and `{python} pts(program_gap[("e3", "gold")])` with the
gold history, and on the turns whose answer is a number from the page, by `{python} pts(number_gap[("e3", "pred")])` and
`{python} pts(number_gap[("e3", "gold")])`.
### 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.
```{python}
#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"])
```
```{python}
#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
`{python} pct(split[("Python", "e0", "gold")]["first"])` in Python and `{python} pct(split[("DSL", "e0", "gold")]["first"])`
in the DSL, whichever history it is given. The follow-ups go from `{python} pct(split[("Python", "e0", "pred")]["later"])` to
`{python} pct(split[("Python", "e0", "gold")]["later"])` in Python and from
`{python} pct(split[("DSL", "e0", "pred")]["later"])` to `{python} pct(split[("DSL", "e0", "gold")]["later"])` 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
(`{python} pct(split[("Python", "e3", "pred")]["later"])` against `{python} pct(split[("Python", "e3", "pred")]["first"])` in
Python, `{python} pct(split[("DSL", "e3", "pred")]["later"])` against `{python} pct(split[("DSL", "e3", "pred")]["first"])` in
the DSL). The gold history helps them
(`{python} pts(split[("Python", "e3", "gold")]["later"] - split[("Python", "e3", "pred")]["later"])` and
`{python} pts(split[("DSL", "e3", "gold")]["later"] - split[("DSL", "e3", "pred")]["later"])` points), but not to the level of the first
turn in the DSL (`{python} pct(split[("DSL", "e3", "gold")]["later"])`), while in Python it is above it
(`{python} pct(split[("Python", "e3", "gold")]["later"])`). 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
`{python} pts(split[("DSL", "e3", "pred")]["first"] - split[("Python", "e3", "pred")]["first"])` points.
## 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.
```{python}
#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 `{python} pts(fewer_invalid[("e3", "pred")])` and
`{python} pts(fewer_invalid[("e3", "gold")])` points more invalid outputs than the Python runs (predicted and gold
history), against leads of `{python} pts(lead[("e3", "pred")]["difference"])` and
`{python} pts(lead[("e3", "gold")]["difference"])`. 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 (@sec-evaluating-errors). 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.
## The Python adapter
The adapter for Python is trained like the DSL adapter of @sec-fine-tuning, 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`.
```{python}
@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)
)
```
## Fine-tuned, Python against the DSL {#sec-python-tuned}
The Python adapter is scored on the same validation turns as the DSL adapter of @sec-training, with the same
history modes and the same bootstrap.
```{python}
#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"])
```
```{python}
#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")
```
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
`{python} pts(lead[("e3", "pred")]["difference"])` points with predicted history to
`{python} pts(tuned_lead["pred"]["difference"])` (interval [`{python} pts(tuned_lead["pred"]["low"])`,
`{python} pts(tuned_lead["pred"]["high"])`]), and the lead of `{python} pts(lead[("e3", "gold")]["difference"])`
points with gold history to `{python} pts(tuned_lead["gold"]["difference"])`
([`{python} pts(tuned_lead["gold"]["low"])`, `{python} pts(tuned_lead["gold"]["high"])`]). 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 `{python} tuned_py_summary["pred"]["by_kind"].get("code_fence", 0) + tuned_py_summary["pred"]["by_kind"].get("syntax", 0)`
invalid outputs in Python and
`{python} round(tuned_dsl_summary["pred"]["invalid_rate"] * n_turns)` in the DSL with predicted history, out of
`{python} f"{n_turns:,}"` 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.
```{python}
#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 `{python} f"{metrics_dsl['step0_eval_loss']:.2f}"` for the DSL and
`{python} f"{metrics_py['step0_eval_loss']:.2f}"` for Python, and ends at `{python} f"{metrics_dsl['best_eval_loss']:.4f}"` and
`{python} f"{metrics_py['best_eval_loss']:.4f}"` (best at step `{python} metrics_dsl["best_step"]` for the DSL and
`{python} metrics_py["best_step"]` 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.
## Numbers from the page, and the scale {#sec-python-numbers}
The prompt asks for numbers that appear on the page. Two checks from @sec-evaluating-errors 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.
```{python}
@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)
)
```
```{python}
#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
```
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 `{python} pct(ungrounded["untuned, three examples, predicted"])` of
its turns that run with predicted history and `{python} pct(ungrounded["untuned, three examples, gold"])` with the gold
history. The untuned model is also off by a power of ten on `{python} off_scale["untuned, three examples, predicted"]`
and `{python} off_scale["untuned, three examples, gold"]` turns, against
`{python} off_scale["fine-tuned, predicted"]` and `{python} off_scale["fine-tuned, gold"]` 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.
## Summary
- A ConvFinQA program written as Python is the same computation: all `{python} f"{len(programs):,}"` training programs give
the same answer in both, and only `{python} len(named)` need a named step. Python written by a model is run by a
whitelist evaluator, never by `exec`.
- Untuned, with three examples, Python is `{python} pts(lead[("e3", "pred")]["difference"])` points ahead of the DSL with
predicted history and `{python} pts(lead[("e3", "gold")]["difference"])` 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
`{python} pts(tuned_lead["pred"]["difference"])` and `{python} pts(tuned_lead["gold"]["difference"])` 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.