7  Probing the untuned model on ConvFinQA

You will learn:

The earlier chapters used one conversation. Here we look at a sample of them. The model is Qwen3-4B-Instruct-2507, untuned, and every example comes from the validation split, never from dev.

7.1 The validation split

train.json is the training file. We hold out a tenth of its conversations for tuning decisions (which prompt, which checkpoint) and train on the rest. The split is made by report page: several conversations are written from the same page, and if one were in training and its sibling in validation, the model could be graded on a page it had been trained on. Dev stays untouched, for the final numbers.

Code
import pandas as pd

from convfinqa import data
from convfinqa.artifacts import get, artifact

split = get("train_val_split")
fit = list(split.jsonl("train_fit.jsonl"))
val = list(split.jsonl("val.jsonl"))

pages = lambda convs: {data.page_group(c["id"]) for c in convs}
n_turns = lambda convs: sum(len(c["annotation"]["dialogue_break"]) for c in convs)
print(
    f"train-fit: {len(fit):,} conversations, {n_turns(fit):,} turns, "
    f"{len(pages(fit)):,} pages"
)
print(
    f"val:       {len(val):,} conversations, {n_turns(val):,} turns, "
    f"{len(pages(val)):,} pages"
)
assert not pages(fit) & pages(val)
train-fit: 2,731 conversations, 9,979 turns, 1,429 pages
val:       306 conversations, 1,125 turns, 159 pages

Together that is 3,037 conversations, the whole of train.json.

The split is deterministic (pages are drawn with seed 0), and it is saved as the artifact train_val_split, so later chapters read exactly these files.

7.2 Asking the untuned model

We take a small random sample of validation conversations and ask the model for every turn. Each turn is a separate request with the gold history (the earlier answers are the dataset’s programs), so the requests are independent and each one measures a single turn. Decoding is greedy and the answer is judged exactly as generated: no cleaning, and an answer the executor rejects is wrong. That is the rule the headline evaluation will use.

We try two prompts. Zero-shot is the system prompt Answer with a program in the ConvFinQA DSL., the page and the question, and nothing else. Few-shot puts two complete conversations, with their gold programs, in front of the same request, drawn from train-fit.

These runs take a few minutes (they load the 4B model and generate every answer twice), so they are an artifact: built once in a subprocess, and loaded here. The same artifact holds the gold programs’ token probabilities that we read in the next section.

Code
#HEAVY
@artifact("probe_val_sample", deps=["train_val_split"], heavy=True)
def build_probe_val_sample(out, deps):
    import json
    import random

    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer

    from convfinqa.probing import probe_sample

    name = "Qwen/Qwen3-4B-Instruct-2507"
    tok = AutoTokenizer.from_pretrained(name)
    model = AutoModelForCausalLM.from_pretrained(
        name, dtype=torch.bfloat16, device_map="cuda"
    ).eval()
    fit = list(deps["train_val_split"].jsonl("train_fit.jsonl"))
    val = list(deps["train_val_split"].jsonl("val.jsonl"))
    rng = random.Random(0)
    sample = rng.sample(val, 20)
    shots = rng.sample(fit, 2)
    result = probe_sample(model, tok, sample, shots)
    for key, rows in result.items():
        (out / f"{key}.jsonl").write_text(
            "".join(json.dumps(r) + "\n" for r in rows)
        )

probe = get("probe_val_sample")
results = pd.DataFrame(probe.jsonl("answers.jsonl"))
surprisal = list(probe.jsonl("surprisal.jsonl"))
outputs = results.setting.unique()
by_id = {c["id"]: c for c in val}
sample = [by_id[s["id"]] for s in surprisal]
print(f"{len(results) // len(outputs)} turns from {len(sample)} conversations")
results.groupby("setting").kind.value_counts().unstack(0)\
    .fillna(0).astype(int).sort_values("few-shot", ascending=False)
68 turns from 20 conversations
setting few-shot zero-shot
kind
correct 46 16
wrong_answer 6 4
wrong_numbers 6 0
syntax 4 16
wrong_operations 3 4
bad_number 2 11
unknown_operator 1 1
code_fence 0 16

With twenty conversations these counts are rough: a few turns move a row by several points. The real measurement is the baseline chapter’s, on many more. What we want here is to read the failures.

Code
accuracy = results.assign(ok=results.kind == "correct")\
    .groupby("setting").ok.mean()
print(accuracy.map("{:.0%}".format).to_string())
setting
few-shot     68%
zero-shot    24%

7.2.1 What the failures look like

Each kind of failure, with one real output per setting. The gold program is on the right.

Code
def show(setting, kind):
    r = results[(results.setting == setting) & (results.kind == kind)]
    if r.empty:
        return
    r = r.iloc[0]
    print(f"- **{setting}, `{kind}`**, turn {r.turn + 1} of `{r.id}`\n")
    print(
        f"  ````\n  "
        + r.output.strip().replace("\n", "\n  ")[:400]
        + "\n  ````\n"
    )
    print(f"  gold: `{r.gold}`\n")

for kind in results.kind.unique():
    if kind != "correct":
        for setting in outputs:
            show(setting, kind)
  • zero-shot, code_fence, turn 1 of Single_KIM/2008/page_126.pdf-1

    To find the difference in income from investment in the retail store leases between 2006 and 2007:
    
    - Income in 2006: $1.3 million  
    - Income in 2007: $1.2 million  
    
    Difference = $1.3 million - $1.2 million = **$0.1 million**
    
    ```convfinqa
    0.1
    ```

    gold: subtract(1.2, 1.3)

  • zero-shot, syntax, turn 3 of Single_ECL/2017/page_96.pdf-3

    The net difference between R&D costs in 2016 and 2015 is:
    
    $191 million (2015) - $189 million (2016) = **$2 million**
    
    So, the net difference is **$2 million**.

    gold: subtract(189, 191)

  • few-shot, syntax, turn 5 of Single_ECL/2017/page_96.pdf-3

    divide(191 - 189, 189) * 100

    gold: subtract(189, 191), divide(#0, 191)

  • zero-shot, wrong_answer, turn 1 of Single_LMT/2014/page_46.pdf-3

    699

    gold: 759

  • few-shot, wrong_answer, turn 3 of Single_ECL/2017/page_96.pdf-3

    subtract(191, 189)

    gold: subtract(189, 191)

  • zero-shot, bad_number, turn 3 of Single_LMT/2014/page_46.pdf-3

    The operating profit in 2013 was $759 million, and in 2012 it was $808 million.  
    
    The change over the year was a decrease of $49 million, or approximately 6%.

    gold: subtract(759, 808)

  • few-shot, bad_number, turn 2 of Single_KIM/2008/page_126.pdf-1

    divide(1.2 - 1.3, 1.3)

    gold: subtract(1.2, 1.3), divide(#0, 1.3)

  • zero-shot, wrong_operations, turn 3 of Single_ETR/2008/page_313.pdf-1

    -32.1

    gold: subtract(959.2, 991.1)

  • few-shot, wrong_operations, turn 3 of Double_AES/2018/page_168.pdf

    340

    gold: divide(340, 17%)

  • zero-shot, unknown_operator, turn 2 of Single_MRO/2008/page_99.pdf-2

    average(20000, 15000)

    gold: add(20000, 15000), divide(#0, const_2)

  • few-shot, unknown_operator, turn 2 of Single_MRO/2008/page_99.pdf-2

    average(20000, 15000)

    gold: add(20000, 15000), divide(#0, const_2)

  • few-shot, wrong_numbers, turn 2 of Double_AES/2018/page_168.pdf

    subtract(348, 352), divide(#0, 364)

    gold: subtract(348, 352), divide(#0, 352)

The kinds, as probing.classify_output defines them:

  • code_fence: the answer is wrapped in a markdown fence, usually with invented syntax inside.
  • syntax, bad_number, unknown_operator: the executor could not read it. These are format failures: the model answered in some language, but not the DSL.
  • wrong_operations, wrong_numbers, wrong_answer: a valid program with the wrong answer. These are reasoning or reading failures: a different list of operations, different numbers picked from the page, or the right shape with the wrong value.

Examples shift the balance from the first group to the second: the model learns the format from two conversations, but picking the right cells and the right operation is a different skill. Fine-tuning has to teach both, and the invalid rate it removes is the easy part.

7.3 How surprised is the model by the gold program?

Generation shows what the model does. We can also ask how likely it finds the gold answer. One forward pass over the whole conversation gives, for every token, the probability the model assigned to it given everything before it. The negative log of that probability is the token’s surprisal, in nats (natural log). It is the surprisal of the gold token given the gold tokens before it (teacher forcing), with no comparison to what the model would have chosen. The cross-entropy loss fine-tuning minimizes is the mean surprisal over the answer tokens.

Code
from IPython.display import HTML

from math import exp
from inspect import signature

from convfinqa.book.viz import surprisal_html

# the surprisal (nats) at which the red is darkest
full = signature(surprisal_html).parameters["full"].default

row = next(
    r for r in surprisal
    if len(by_id[r["id"]]["annotation"]["dialogue_break"]) >= 4
)
conv = by_id[row["id"]]
pieces, logp = row["tokens"], row["logprobs"]

for k, t in enumerate(data.turns(conv)):
    print(f"turn {k + 1}: {t.question}")
HTML(surprisal_html(pieces, logp))
turn 1: what were the r&d costs in 2016?
turn 2: what were the r&d costs in 2015?
turn 3: what is the net difference?
turn 4: what were the r&d costs in 2015?
turn 5: what was the percent change?
189<|im_end|>191<|im_end|>subtract(189, 191)<|im_end|>191<|im_end|>subtract(189, 191), divide(#0, 191)<|im_end|>

Hover over a token for its probability. The answers are printed one after the other, each ending with <|im_end|>, the token that closes the turn. The red deepens with the token’s surprisal and is darkest for a token the model gave a probability of 1.8% or less.

The red is not where we might expect. The numbers, which the model has to find on the page, are mostly pale, because it copies them well. The surprise is in the DSL’s own words: the operator that opens a program, the ), between two steps, the (# of a reference to an earlier step. We can measure it across the sample, by kind of token:

Code
def token_class(piece):
    text = piece.strip()
    if piece == "<|im_end|>":
        return "end of turn"
    if "#" in text:
        return "#k reference"
    if text.startswith(")") and "," in text:
        return "step separator"
    if text.replace("_", "").isalpha():
        return "operator / constant name"
    if text and all(ch.isdigit() or ch in ".%,-" for ch in text):
        return "number"
    return "bracket / other"

records = []
for row in surprisal:
    turn = 0
    for piece, lp in zip(row["tokens"], row["logprobs"]):
        records.append({
            "class": token_class(piece),
            "turn": min(turn, 4) + 1,
            "surprisal": -lp
        })
        turn += piece == "<|im_end|>"
tokens = pd.DataFrame(records)
by_class = tokens.groupby("class").surprisal.agg(["count", "mean", "sum"])
by_class["share of total"] = by_class["sum"] / by_class["sum"].sum()
by_class.drop(columns="sum").sort_values("share of total", ascending=False)\
    .round(3)
count mean share of total
class
operator / constant name 85 8.341 0.330
number 613 0.711 0.203
step separator 23 11.655 0.125
end of turn 68 3.760 0.119
bracket / other 163 1.480 0.112
#k reference 21 11.269 0.110
Code
tokens.groupby("turn").surprisal.agg(["count", "mean"])\
    .rename_axis("turn (5 = 5 or later)").round(2)
count mean
turn (5 = 5 or later)
1 203 2.62
2 249 2.87
3 192 2.68
4 157 1.73
5 172 0.66

Most of the loss comes from a few token kinds that a trained model would predict with near certainty: which operator comes first, whether the program goes on (),) or stops (<|im_end|>), and whether the next argument is a reference ((#). The mean surprisal also falls from turn to turn as earlier answers in the chat show the format, but only a little at first: the model does not pick the format up from one or two answers. Numbers cost little, and what is left for fine-tuning is the reasoning that decides the operator and the arguments.

7.4 The number fine-tuning starts from

For the whole validation split we compute the mean surprisal of the gold tokens: one forward pass per conversation, token-weighted. This is a model run over the whole split, so it is built once as an artifact, in a subprocess.

Code
#HEAVY
@artifact("val_gold_nll", deps=["train_val_split"], heavy=True)
def build_val_gold_nll(out, deps):
    import json

    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer

    from convfinqa.formatting import conversation_messages
    from convfinqa.probing import mean_gold_nll

    name = "Qwen/Qwen3-4B-Instruct-2507"
    tok = AutoTokenizer.from_pretrained(name)
    model = AutoModelForCausalLM.from_pretrained(
        name, dtype=torch.bfloat16, device_map="cuda"
    ).eval()
    chats = [
        conversation_messages(c)
        for c in deps["train_val_split"].jsonl("val.jsonl")
    ]
    (out / "nll.json").write_text(json.dumps(mean_gold_nll(model, tok, chats)))

val_nll = get("val_gold_nll").json("nll.json")
print(
    f"val: {val_nll['conversations']} conversations, "
    f"{val_nll['tokens']:,} answer tokens"
)
print(
    f"mean gold-program negative log-likelihood: "
    f"{val_nll['nll']:.4f} nats per token"
)

from math import exp
print(f"perplexity: {exp(val_nll['nll']):.3f}")
val: 306 conversations, 16,417 answer tokens
mean gold-program negative log-likelihood: 2.2062 nats per token
perplexity: 9.081

The perplexity is the exponential of this mean: the model is as uncertain, on average, as if it were choosing uniformly among that many tokens at each gold position. A perplexity of 1 would mean every gold token had probability 1. It is an average of a lopsided distribution (the earlier table shows a few very costly tokens among many nearly free ones), it is per token, so it depends on the tokenizer, and it covers the answer tokens only. It carries the same information as the loss; we report both because the training logs show the loss and the perplexity is easier to picture.

The mean negative log-likelihood is the loss of the untuned model on the validation split, with the data in exactly the format the training will use. Chapter 12 uses the same format, so its step-0 validation loss should agree with it within a few percent: if it doesn’t, the formatting or the label mask differs between the two, and we look there first. After training we expect the loss to fall, and the same heatmap to be much paler.

NoteUnder the hood

The loss is a mean over tokens, not over conversations or turns, so long conversations weigh more. probing.gold_logprobs scores token t with the logits at position t - 1, which is how the model’s own labels= loss is defined; Chapter 8 shows the two agree. Attention maps from a copied number back to table cells are a natural next probe, but they are only suggestive: a head that attends to a cell is not thereby the reason for the answer (Vaswani et al. 2017). We leave them out.

TipFurther reading
  • The ConvFinQA paper measured GPT-3 with the same DSL and found the unfamiliar syntax hurt it (Chen et al. 2022).