2  What ConvFinQA looks like

You will learn:

ConvFinQA (Chen et al. 2022) turns FinQA questions about earnings-report pages into multi-turn conversations. Each page has text before a table, the table, and text after it. A conversation asks a chain of questions about that page, and each turn has a small program in a domain-specific language (DSL) that computes the answer.

2.1 Getting the data

The code lives in src/convfinqa/data/. The download clones the authors’ repository and unzips data.zip into data/raw/, and does nothing if the data is already there.

Code
import json
from collections import Counter
from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd

from convfinqa import data
from convfinqa.dsl import steps

data.download_data()

splits = {
    name: data.load_split(name)
    for name in ["train", "dev", "test", "train_turn", "dev_turn"]
}

pd.DataFrame({
    "rows": {k: len(v) for k, v in splits.items()},
    "has labels": {
        k: "annotation" in v[0] and "turn_program" in v[0]["annotation"]
        for k, v in splits.items()
    }
})
rows has labels
train 3037 True
dev 421 True
test 434 False
train_turn 11104 True
dev_turn 1490 True

The official test split has questions but no answers, so we use dev as our test set. For tuning we carve a validation split out of train in a later chapter. The *_turn files hold the same conversations unrolled to one row per turn. We work from the conversation files and unroll ourselves, which the counts above confirm gives the same number of turns:

Code
n_turns = {
    s: sum(len(c["annotation"]["dialogue_break"])
    for c in splits[s]) for s in ["train", "dev"]
}

assert n_turns["train"] == len(splits["train_turn"])\
    and n_turns["dev"] == len(splits["dev_turn"])

n_turns
{'train': 11104, 'dev': 1490}

2.2 One record

A conversation is a JSON object. The fields we use are pre_text, table, post_text, and under annotation: dialogue_break (the questions), turn_program, exe_ans_list (the answers) and qa_split (see Type II below).

Code
by_id = {c["id"]: c for c in splits["train"]}
conv_I = by_id["Single_AAPL/2002/page_23.pdf-1"]

print("Top-level keys of the conversation:")
print(sorted(conv_I.keys()))

print("Annotation keys of the conversation:")
print(sorted(conv_I["annotation"].keys()))
Top-level keys of the conversation:
['annotation', 'filename', 'id', 'post_text', 'pre_text', 'qa', 'table', 'table_ori']
Annotation keys of the conversation:
['amt_post_text', 'amt_pre_text', 'amt_table', 'answer_list', 'dialogue_break', 'dialogue_break_ori', 'exe_ans_list', 'original_program', 'qa_split', 'step_list', 'turn_program', 'turn_program_ori']

2.3 A Type I conversation

Type I conversations decompose one FinQA question into a chain of turns. First the page the model sees: the text before the table (shortened here), the table as markdown, and the text after.

Code
from IPython.display import Markdown

def show_page(conv, n=300):
    pre = " ".join(conv["pre_text"])
    post = " ".join(conv["post_text"])
    return Markdown(
        f"*pre_text ({len(conv['pre_text'])} sentences):* …{pre[-n:]}\n\n"
        + data.table_to_markdown(conv["table"])
        + f"\n\n*post_text ({len(conv['post_text'])} sentences):* {post[:n]}…"
    )

show_page(conv_I)

pre_text (22 sentences): … declined to 23% ( 23 % ) of net sales in 2001 from 27% ( 27 % ) in 2000 . this decline resulted primarily from gross margin of negative 2% ( 2 % ) experienced during the first quarter of 2001 compared to 26% ( 26 % ) gross margin for the same quarter in 2000 . in addition to lower than normal net .

2002 2001 2000
net sales $ 5742 $ 5363 $ 7983
cost of sales 4139 4128 5817
gross margin $ 1603 $ 1235 $ 2166
gross margin percentage 28% ( 28 % ) 23% ( 23 % ) 27% ( 27 % )

post_text (1 sentences): .…

Then the conversation, one turn per line: question, gold program, and the number the program computes.

Code
print(data.format_conversation(conv_I))
Single_AAPL/2002/page_23.pdf-1  (Type I)
  [1] Q: what was the total of net sales in 2001?
      program: 5363
      answer:  5363
  [2] Q: and what was that in 2000?
      program: 7983
      answer:  7983
  [3] Q: what was, then, the change in the total of net sales over the year?
      program: subtract(5363, 7983)
      answer:  -2620
  [4] Q: and how much does this change represent in relation to that total in 2000, in percentage?
      program: subtract(5363, 7983), divide(#0, 7983)
      answer:  -0.3282

The first turns just select a number from the table. Later turns compute with them. The last turn restates the full calculation, using #0 for “the result of step 0” so the program stays self-contained.

2.4 A Type I conversation with a garbled table

Not every page is this clean. Here is another Type I conversation, whose table header is garbled in the dataset.

Code
conv_garbled = by_id["Single_JKHY/2009/page_28.pdf-3"]
show_page(conv_garbled)

pre_text (9 sentences): …tal requirements . we expect this trend to continue in the future . the company 2019s cash and cash equivalents increased to $ 118251 at june 30 , 2009 from $ 65565 at june 30 , 2008 . the following table summarizes net cash from operating activities in the statement of cash flows : 2009 2008 2007 .

2008 year ended june 30 2009 2008 year ended june 30 2009 2008 year ended june 30 2009
net income $ 103102 $ 104222 $ 104681
non-cash expenses 74397 70420 56348
change in receivables 21214 -2913 ( 2913 ) -28853 ( 28853 )
change in deferred revenue 21943 5100 24576
change in other assets and liabilities -14068 ( 14068 ) 4172 17495
net cash from operating activities $ 206588 $ 181001 $ 174247

post_text (15 sentences): year ended june 30 , cash provided by operations increased $ 25587 to $ 206588 for the fiscal year ended june 30 , 2009 as compared to $ 181001 for the fiscal year ended june 30 , 2008 . this increase is primarily attributable to a decrease in receivables compared to the same period a year ago of $ …

WarningThe header of this table is garbled in the dataset

The raw table_ori shows what went wrong. The header was split across two rows:

Code
for row in conv_garbled["table_ori"][:3]:
    print(row)
['', 'Year ended June 30, 2009']
['2008', '2007']
['Net income', '$103,102', '$104,222', '$104,681']

Read together, the first two rows are a single header row, ['', 'Year ended June 30, 2009', '2008', '2007'], whose first label was extracted on a separate line from the other two. The cleaned table then built a header from the broken pieces: its columns repeat fragments of “year ended june 30 2009”, and the year labels also show up in pre_text (the trailing : 2009 2008 2007 .). This is how the data ships, not a parsing error of ours.

The model must work out that the columns are 2009, 2008 and 2007 from the table and the surrounding text, which is part of the task.

Code
print(data.format_conversation(conv_garbled))
Single_JKHY/2009/page_28.pdf-3  (Type I)
  [1] Q: what is the net cash from operating activities in 2009?
      program: 206588
      answer:  206588
  [2] Q: what about in 2008?
      program: 181001
      answer:  181001
  [3] Q: what is the difference?
      program: subtract(206588, 181001)
      answer:  25587
  [4] Q: what percentage change does this represent?
      program: subtract(206588, 181001), divide(#0, 181001)
      answer:  0.14136

Most tables are clean. The check below counts how many have repeated header cells:

Code
dup_header = sum(
    len(set(c["table"][0])) < len(c["table"][0])
    for c in splits["train"]
)
print(
    f"{dup_header} of {len(splits['train'])} train tables repeat a header "
    f"cell ({dup_header / len(splits['train']):.1%})"
)
66 of 3037 train tables repeat a header cell (2.2%)

2.5 A Type II conversation

Type II conversations merge two FinQA questions about the same page. qa_split marks which turns belong to which: 0s, then 1s.

Code
conv_II = next(
    c for c in splits["train"]
    if data.conversation_type(c) == "II"
    and len(c["annotation"]["dialogue_break"]) == 6
)
print(data.format_conversation(conv_II))
print("qa_split:", conv_II["annotation"]["qa_split"])
Double_AWK/2013/page_123.pdf  (Type II)
  [1] Q: what is the net valuation allowance as of december 31, 2013?
      program: subtract(13555, 2979)
      answer:  10576   (part 1)
  [2] Q: what is the value of decreases in current period tax positions in 2011?
      program: 3734
      answer:  3734   (part 2)
  [3] Q: what about in 2012?
      program: 2059
      answer:  2059   (part 2)
  [4] Q: what is the total for these two years?
      program: add(3734, 2059)
      answer:  5793   (part 2)
  [5] Q: what about if 2013 is included?
      program: add(3734, 2059), add(#0, 5965)
      answer:  11758   (part 2)
  [6] Q: what is the average for three years?
      program: add(3734, 2059), add(#0, 5965), divide(#1, const_3)
      answer:  3919.33   (part 2)
qa_split: [0, 1, 1, 1, 1, 1]

2.6 The DSL

A program is a comma-separated list of steps, op(arg, arg). A turn that only selects a number has a bare number as its program. The operations are add, subtract, multiply, divide, exp and greater. (The authors’ code also lists FinQA’s table_sum, table_average, table_max and table_min, but no ConvFinQA gold program uses them.) An argument is one of:

  • a number literal copied from the page, such as 206588 or 0.14136, possibly with a % sign, such as 19%;
  • a step reference #k, the result of step k;
  • a constant from a fixed list.

The chapter on the DSL and its executor covers the grammar and the executor in detail. Here we look at what makes an argument a literal or a constant, and how the paper’s model decides what it may write.

2.6.1 Constants

The constants are not read from the page. The authors’ code defines a fixed list of constants, and every constant in the train and dev programs is in it:

Code
import re

const_use = Counter(
    c
    for s in ["train", "dev"]
    for conv in splits[s]
    for p in conv["annotation"]["turn_program"]
    for c in re.findall(r"const_\w+", p)
)
assert set(const_use) <= set(steps.CONSTANTS)

pd.Series(
    {c: const_use.get(c, 0) for c in steps.CONSTANTS},
    name="uses (train + dev)"
).to_frame().T
const_1 const_2 const_3 const_4 const_5 const_6 const_7 const_8 const_9 const_10 const_100 const_1000 const_10000 const_100000 const_1000000 const_10000000 const_1000000000 const_m1
uses (train + dev) 132 136 138 36 28 14 12 12 18 7 1147 344 0 1 197 0 1 19

The list has 18 constants.

They are mostly scale factors and counts: const_100 turns a ratio into a percentage, const_1000 and const_1000000 convert units, and small integers such as const_3 count years for an average (the Type II example above ends with divide(#1, const_3)). The rule is by convention, not by whether the digits occur on the page: a number the question needs but does not read from the document is a constant, and the same digits read off the page are a literal.

2.6.2 Percentages and the executor

The official executor (str_to_num in the authors’ general_utils.py) strips commas and tries to read a float. If that fails and the string contains %, it removes the sign and divides by 100, so 19% is evaluated as 0.19. A const_ token is replaced by its number (const_m1 is -1). The executor never looks at the page: whether a program may use 19% at all is decided elsewhere.

2.6.3 What the paper’s decoder may write

FinQANet’s generator (Chen et al. 2022) is restricted: at each step it can emit an operator, a constant from the list, a step reference, or a number copied from its input. Its input is the question plus the context it is given (supporting text and table rows), split on spaces, and a token counts as a copyable number if, after removing commas, it parses as a number or ends with %. This is the rule, implemented in steps.copyable_numbers:

Code
row = " ".join(conv_I["table"][-1])
print(row)
print(steps.copyable_numbers(row))
gross margin percentage 28% ( 28 % ) 23% ( 23 % ) 27% ( 27 % )
['28%', '28', '%', '23%', '23', '%', '27%', '27', '%']

This works because the page text is pre-tokenized: punctuation and symbols are separated from the surrounding text by spaces ($ 103102, june 30 , 2009, ( 2913 )), so numbers can be extracted cleanly. The exception is %, which the data keeps attached to its number in the first form (28%) and also writes as a separate token in the parenthesised form (( 28 % )). The attached 28% is a candidate. In the spaced form, 28 is a candidate and the lone % also passes the rule, which looks like an accidental quirk of the check.

Whether our own models should be restricted this way is a separate question, taken up in the constrained-decoding chapter.

2.7 How big is it?

Code
rows = []
for split in ["train", "dev"]:
    for c in splits[split]:
        for t in data.turns(c):
            rows.append({
                "split": split,
                "id": c["id"],
                "type": data.conversation_type(c),
                "turn": t.index + 1,
                "number_turn": steps.is_number_turn(t.program),
                "program": t.program
            })
df = pd.DataFrame(rows)

per_conv = df.groupby(["split", "id", "type"]).size()\
    .rename("turns").reset_index()

summary = per_conv.groupby("split").agg(
    conversations=("id", "count"),
    turns=("turns", "sum"),
    mean_turns=("turns", "mean")
)

summary["type II share"] = per_conv.assign(ii=per_conv.type == "II")\
    .groupby("split").ii.mean()

summary.round(2)
conversations turns mean_turns type II share
split
dev 421 1490 3.54 0.29
train 3037 11104 3.66 0.31
Code
fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
pivot = per_conv.groupby(["turns", "type"]).size().unstack(fill_value=0)
pivot.plot.bar(stacked=True, ax=ax[0], rot=0)

ax[0].set(
    xlabel="turns in conversation",
    ylabel="conversations",
    title="Conversation length"
)

share = df.groupby("split").number_turn.mean()

share.rename("number-selection").to_frame().assign(program=1 - share)\
    .plot.bar(stacked=True, ax=ax[1], rot=0)

ax[1].set(ylabel="share of turns", title="Turn kind")
plt.tight_layout()

Turns per conversation (train + dev) and the share of number-selection vs. program turns.

The DSL operations are counted from the new step each turn adds: the last step of its program, since each program repeats the earlier steps.

Code
ops = Counter()
for p in df[(df.split == "train") & ~df.number_turn].program:
    ops[steps.split_steps(p)[-1].split("(")[0]] += 1
pd.Series(ops).sort_values().plot.barh(figsize=(5, 2.5), xlabel="turns")
plt.tight_layout()
ops
Counter({'divide': 3254,
         'subtract': 2307,
         'add': 1119,
         'multiply': 475,
         'greater': 36,
         'exp': 2})

How often each DSL operation is the new step of a turn (train).

2.8 How long is a conversation in tokens?

Training uses one sequence per full conversation: the system prompt, the page, and every question and answer. So the longest conversations set the memory we need. Turning a data row into token ids takes three steps:

  1. Row to messages. Our own choice, in conversation_messages (src/convfinqa/formatting.py): a system prompt, then the page and the first question as the first user message, then the gold program as the assistant’s reply, and so on for every turn. The experiments part extends this module for training.
  2. Messages to one string. The model’s own chat template, which ships with its tokenizer. It wraps each message in the special markers that the model was trained with.
  3. String to token ids. The tokenizer itself.

Here is step 2 for the clean Type I conversation from above. The page text and table are cut out so the structure is visible.

Code
from transformers import AutoTokenizer

from convfinqa.formatting import conversation_messages

tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B-Instruct-2507")

text = tok.apply_chat_template(conversation_messages(conv_I), tokenize=False)
cut = text.index("\n\nQuestion:")
print(text[:260] + "\n[... page text and table omitted ...]" + text[cut:])
<|im_start|>system
Answer with a program in the ConvFinQA DSL.<|im_end|>
<|im_start|>user
in a new business model such as the retail segment is inherently risky , particularly in light of the significant investment involved , the current economic climate , and
[... page text and table omitted ...]

Question: what was the total of net sales in 2001?<|im_end|>
<|im_start|>assistant
5363<|im_end|>
<|im_start|>user
and what was that in 2000?<|im_end|>
<|im_start|>assistant
7983<|im_end|>
<|im_start|>user
what was, then, the change in the total of net sales over the year?<|im_end|>
<|im_start|>assistant
subtract(5363, 7983)<|im_end|>
<|im_start|>user
and how much does this change represent in relation to that total in 2000, in percentage?<|im_end|>
<|im_start|>assistant
subtract(5363, 7983), divide(#0, 7983)<|im_end|>

The <|im_start|> and <|im_end|> markers delimit each message and carry its role. The model learns to end every answer with <|im_end|>, and that token is part of what we train on.

NoteWhich tokenizer, and why it matters

The ConvFinQA paper doesn’t prescribe a tokenizer; it predates our model. We use the tokenizer and chat template of the model we will fine-tune, Qwen/Qwen3-4B-Instruct-2507, so that the lengths below are what training will see. The numbers, and the max_length we derive from them, belong to this tokenizer and to our formatting. A different base model would give slightly different counts, so check them again before reusing the value.

Now we count tokens for every conversation of train and dev (step 3). The count is made by convfinqa.lengths, with add_special_tokens=False because the template has already written the special tokens into the string. It is the artifact conversation_lengths, so that the chapters that need the longest conversation read it from there, and a rebuild from a clean checkout makes it again.

Code
import pandas as pd

from convfinqa.artifacts import artifact, get


@artifact("conversation_lengths")
def build_conversation_lengths(out, deps):
    import json

    from transformers import AutoTokenizer

    from convfinqa import data
    from convfinqa.lengths import conversation_lengths, max_length_for

    tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B-Instruct-2507")
    rows = conversation_lengths(
        tok, {name: data.load_split(name) for name in ["train", "dev"]}
    )
    longest = max(r["tokens"] for r in rows)
    (out / "lengths.jsonl").write_text(
        "".join(json.dumps(r) + "\n" for r in rows)
    )
    (out / "lengths.json").write_text(json.dumps(
        {"longest": longest, "max_length": max_length_for(longest)}
    ))


lengths = pd.DataFrame(get("conversation_lengths").jsonl("lengths.jsonl"))
lengths.groupby("split").tokens.describe(percentiles=[0.5, 0.9, 0.99, 0.999])\
    .round(0)
count mean std min 50% 90% 99% 99.9% max
split
dev 421.0 1129.0 348.0 451.0 1073.0 1553.0 2150.0 2284.0 2291.0
train 3037.0 1161.0 361.0 272.0 1131.0 1573.0 2422.0 3349.0 3460.0
Code
lengths.groupby("split").tokens.plot.hist(
    bins=60, alpha=0.6, legend=True, figsize=(6, 3)
)
plt.xlabel("tokens in conversation")
plt.tight_layout()

Tokens per full conversation.

We pick max_length as the longest conversation rounded up to a multiple of 256, so that no training conversation is truncated. Truncating would cut off assistant tokens, which are exactly what the loss is computed on. The value is saved in the same artifact for later chapters, since stages pass data through files.

Code
chosen = get("conversation_lengths").json("lengths.json")
print(
    f"longest conversation: {chosen['longest']} tokens"
    f" -> max_length = {chosen['max_length']}"
)
longest conversation: 3460 tokens -> max_length = 3584
NoteUnder the hood

Notice how numbers like 206588 cost one token per digit in this tokenizer. The foundations part looks at tokenization properly. It is one reason the model writes a program and a Python executor does the arithmetic.

TipFurther reading

The ConvFinQA paper (Chen et al. 2022) describes how the conversations were built and annotated. The dataset repository is at https://github.com/czyssrs/ConvFinQA.