# Toolformer: Scoring Tool Calls by How Much They Cut the Loss, So a Language Model Learns When to Ask for Help

> Toolformer lets a language model decide when to call a calculator, QA system, search engine, translator or calendar: a call is kept only if its result clearly lowers the loss on the next tokens. This post covers the method, rechecks the tables and measures the filter on two Qwen2.5 models.

- URL: https://dmxsf.com/en/blog/toolformer-self-supervised-tool-use-for-language-models/
- [DMXSF](https://dmxsf.com/en/about/)
- Published: 2023-02-21
- Updated: 2026-11-13
- Paper notes
- Paper: [Toolformer: Language Models Can Teach Themselves to Use Tools](https://arxiv.org/abs/2302.04761) (Timo Schick, Jane Dwivedi-Yu, Roberto Dessì, et al. · NeurIPS 2023, 2023)

"Toolformer: Language Models Can Teach Themselves to Use Tools" (Schick et al., Meta AI Research and Universitat Pompeu Fabra, February 2023, NeurIPS 2023; the Toolformer paper below) asks whether a language model can learn, without large amounts of human annotation, when to call a calculator, a question answering system, a search engine, a translator and a calendar. Its recipe has four steps. First, a handful of demonstrations per tool let GPT-J (6.7B parameters) write candidate API calls into ordinary text. Second, the calls are executed. Third, only one kind of call is kept: those that, when the call and its result are placed in front of the text, lower the model's weighted cross entropy on the next few tokens by at least $\tau_f$ compared with both "no call" and "the call without its result". Fourth, the model is fine-tuned on the surviving text with the ordinary language modeling loss. The paper reports that on math benchmarks the same model more than doubles its score with the calculator switched on (2.7 to 4.7 times, recomputed from Table 4), that question answering and temporal datasets improve too, and that perplexity with API calls disabled equals that of a model fine-tuned on the same corpus. It also reports that Toolformer stays below GPT-3 175B on all three open-domain QA sets and does not beat the original GPT-J across multilingual QA overall.

After walking through the paper, this post does two things, both repeatable on a laptop. **Recheck:** the numbers of the paper's Tables 2 to 9 are copied into a script that recomputes the claims in the text ("more than doubled", "better than GPT-3" and so on) and points out one row of Table 9 that does not add up. **Small-scale reproduction:** only the filtering criterion itself (no sampling, no fine-tuning, none of the paper's downstream results), scored with Qwen2.5-0.5B and Qwen2.5-7B on 96 controlled sentences and 200 real candidates from WikiText-2, measuring $L^- - L^+$. The result is that the criterion is clearly relative to the model and the wording and very demanding on real text; the experiment can neither confirm nor refute the paper's conclusions.

## Why this paper is worth reading

- **It turns "should the model call a tool here?" into a number.** No annotator is needed: ask whether, given the result of this call, the following text becomes easier to predict. "Useful" becomes something you can compute and threshold instead of a human judgment.
- **The criterion is relative to the model.** The paper's first requirement comes with this reason: what humans find useful may differ from what a model finds useful. The same call can help one model and not another, so the data has to be filtered by the model that will be fine-tuned. The experiment below measures exactly that.
- **The evaluation includes the places where it did not win.** QA stays below GPT-3, multilingual QA is mixed, and the calendar was barely used on TEMPLAMA; the paper says all of this in the text.
- **It is part of the prehistory of function calling.** Today's models learn structured tool calls through supervised fine-tuning and reinforcement learning, and both the formats and the training have changed, but the question was already stated completely here: the model decides when to call, what arguments to pass, and how to use the result. Related pages: [Agents and Tool Calling](https://dmxsf.com/en/wiki/applications/agents-and-tool-calling/), [Structured Output and Function Calling](https://dmxsf.com/en/wiki/applications/structured-output-and-function-calling/), and the [ReAct explainer](https://dmxsf.com/en/blog/react-reasoning-and-acting/), which implements multi-step tool use through prompting from the same period.

## Background: existing routes and the two requirements

Giving a language model tools was not new. The paper sorts earlier work into two groups. One relies on large amounts of human supervision: annotators demonstrate how to use a search engine, a browser or a translation system, as in WebGPT and LaMDA. The other relies on prompting, with task-specific few-shot examples that show how a tool is used for this particular task, as in PAL and ReAct. Both have costs: the first needs annotation, and what humans find useful is not necessarily what the model finds useful; the second ties tool use to a task. The paper regards TALM as the closest relative: it also uses a self-supervised objective to teach a model to use a calculator and a search engine, but only in settings where the model is fine-tuned for a downstream task.

Toolformer therefore sets two requirements:

1. **Tool use must be learned in a self-supervised way**, with no large annotation effort, only a few demonstrations per tool.
2. **The model must not lose its generality**: it should decide for itself when, how and which tool to use, not learn a fixed recipe for one task.

The core design idea is that the model was trained by predicting the next token anyway, so "predicts better" can serve as the judge of "this call was useful"; and the annotation runs on the very corpus the model was pretrained on, so the fine-tuned model sees the same text as before.

## Method: sample, execute, filter, fine-tune

### Writing calls as text

The paper requires each API's input and output to be representable as text, so that a call can be inserted into any text. A call is $c=(a_c,i_c)$, where $a_c$ is the API name and $i_c$ its input. The linearized forms without and with the result are:

$$
\begin{aligned}
e(c) &= \texttt{<API>}\; a_c(i_c)\; \texttt{</API>} \\
e(c,r) &= \texttt{<API>}\; a_c(i_c) \to r\; \texttt{</API>}
\end{aligned}
$$

In practice `<API>`, `</API>` and `→` are written with ordinary token sequences, ` [`, `]` and `->`, so the vocabulary is untouched. The example in the paper's Figure 1 is `Out of 1400 participants, 400 (or [Calculator(400 / 1400) → 0.29] 29%) passed the test.`

*Figure: Figure 1  Toolformer's data construction, drawn on the example of the paper's Figure 2. All three losses are weighted cross entropy over the following tokens; see the formulas below.*

### Step 1: sample calls

For each API the authors write a prompt $P(x)$ that asks the model to annotate a text $x=x_1,\dots,x_n$ with API calls, containing a few demonstrations for that API (the paper's Figure 3 shows the QA prompt). Candidate positions come first: for every position $i$ compute the probability that the model starts a call after $P(x)$ and the prefix $x_{1:i-1}$:

$$
p_i = p_M\bigl(\texttt{<API>} \mid P(x),\, x_{1:i-1}\bigr)
$$

Keep the positions with $p_i>\tau_s$, and only the top $k$ if there are more. For each kept position, sample up to $m$ calls given $[P(x),x_1,\dots,x_{i-1},\texttt{<API>}]$ as the prefix and `</API>` as the end-of-sequence token. The defaults are $\tau_s=0.05$, $k=5$, $m=5$. The calculator and machine translation are rare in the corpus, so they use $\tau_s=0$, $k=20$, $m=10$ and a relaxed filtering threshold of $\tau_f=0.5$.

To save compute, some APIs first narrow the corpus with heuristics. The calculator only processes documents that (i) contain at least three numbers within a window of 100 tokens, one of which is the result of an operation on the other two; or (ii) contain "=", "equals", "equal to", "total of" or "average of" followed by a number; or (iii) contain at least three numbers, in which case only a random 1% is kept.

### Step 2: execute calls

How a call is executed depends entirely on the API: it can query another neural network, run a Python script or search a corpus. The response must be a single text sequence $r_i$. The paper uses five tools:

| Tool | Implementation | Example input and output |
| --- | --- | --- |
| Question answering | Atlas, a retrieval-augmented language model fine-tuned on Natural Questions (Atlas-large to build the data, Atlas-xxl at inference) | `Where was the Knights of Columbus founded?` → `New Haven, Connecticut` |
| Calculator | A simple Python script with the four basic operations only, results rounded to two decimals, no result for invalid equations | `27 + 4 * 2` → `35` |
| Wikipedia search | BM25 over the KILT Wikipedia dump, returning short snippets | `Fishing Reel Types` → `Spin fishing > ...` |
| Machine translation | The 600M-parameter NLLB, source language detected with fastText, target language always English | `sûreté nucléaire` → `nuclear safety` |
| Calendar | Takes no input and returns the current date | `Today is Monday, January 30, 2023.` |

### Step 3: filter calls

Let $c_i$ be the call at position $i$ and $r_i$ its response. Given weights $w_t$, define the weighted cross entropy of $x_i,\dots,x_n$ when the model is prefixed with $z$:

$$
L_i(z) = -\sum_{j=i}^{n} w_{j-i}\,\log p_M\bigl(x_j \mid z,\, x_{1:j-1}\bigr)
$$

Compare two quantities, where $\varepsilon$ is the empty sequence:

$$
\begin{aligned}
L_i^{+} &= L_i\bigl(e(c_i,r_i)\bigr) \\
L_i^{-} &= \min\bigl(L_i(\varepsilon),\; L_i(e(c_i,\varepsilon))\bigr)
\end{aligned}
$$

$L_i^{+}$ is the loss when both the call and its result are given as a prefix; $L_i^{-}$ is the smaller of "no call at all" and "the call without its result". A call is kept when

$$
L_i^{-} - L_i^{+} \ge \tau_f
$$

that is, when adding the call and its result lowers the loss by at least $\tau_f$ relative to no call, or to a call with no result. The paper's intuition is that a call helps only if giving both its input and its output makes the future tokens easier to predict than giving nothing or only the input. If writing the input alone (say, a question that already hints at the answer) lowers the loss, that benefit goes into $L_i^{-}$ and is not credited to the result.

The weights are

$$
w_t = \frac{\tilde w_t}{\sum_{s}\tilde w_s},\qquad \tilde w_t=\max(0,\;1-0.2\,t)
$$

so only the next five tokens carry weight; the paper says this makes sure that calls happen close to where the information provided by the API is actually helpful. Plugging in $t=0,\dots,4$ and normalizing gives 0.333, 0.267, 0.200, 0.133 and 0.067 (the check script below prints them).

A footnote explains that the paper supplies $e(c_i,r_i)$ as a prefix to the whole text instead of inserting it at position $i$: the model has not yet been fine-tuned on any text containing API calls, so inserting a call in the middle would interrupt the flow, clash with the patterns of the pretraining corpus and hurt perplexity.

### Step 4: fine-tune and decode

The surviving calls of all tools are merged and interleaved with the original text: for a text $x$ with a call and result $(c_i,r_i)$ at position $i$, the new sequence is $x^*=x_{1:i-1},\,e(c_i,r_i),\,x_{i:n}$, and likewise for several calls. Apart from the inserted calls, the resulting dataset $C^*$ contains exactly the same texts as the original $C$, so fine-tuning on $C^*$ exposes the model to the same content as fine-tuning on $C$. The paper uses a subset of CCNet as $C$ and GPT-J as $M$. The fine-tuning uses a batch size of 128 and a learning rate of $1\times10^{-5}$ with linear warmup over the first 10% of training, at most 25k examples per API, a maximum sequence length of 1,024, DeepSpeed ZeRO-3 with BF16 on 8 NVIDIA A100 40GB GPUs for up to 2,000 steps, with perplexity on 1,000 CCNet development examples every 500 steps and the best checkpoint kept.

At inference the model decodes as usual until it writes "→" (that is, `->`), which means it now expects the response of an API. Decoding pauses, the API is called, the response and `</API>` are inserted, and decoding continues. The paper changes decoding in one respect: instead of starting a call only when `<API>` is the most likely token, it starts one whenever `<API>` is among the $k$ most likely tokens, with $k=10$ in the experiments, and it allows at most one call per input so that the model cannot get stuck calling APIs forever without producing text.

## What the paper reports

### Setup

All experiments are zero-shot: the model gets a natural language task description and no in-context examples, unlike earlier work that relied on dataset-specific demonstrations. The comparison models are:

- **GPT-J**: the original model, no fine-tuning.
- **GPT-J + CC**: GPT-J fine-tuned on $C$, the CCNet subset without any API calls.
- **Toolformer (disabled)**: the same model as Toolformer with the probability of `<API>` set to 0 during decoding.
- **Toolformer**: GPT-J fine-tuned on $C^*$.
- **OPT (66B) and GPT-3 (175B)**: about 10 and 25 times larger than Toolformer; GPT-3 is the original davinci, not fine-tuned on instructions.

### The numbers

The next three tables copy the paper's Tables 3 to 5.

**Paper Table 3: three LAMA subsets (correct if the right word is among the first five predicted words; Toolformer may not use Wikipedia search).**

| Model | SQuAD | Google-RE | T-REx |
| --- | --- | --- | --- |
| GPT-J | 17.8 | 4.9 | 31.9 |
| GPT-J + CC | 19.2 | 5.6 | 33.2 |
| Toolformer (disabled) | 22.1 | 6.3 | 34.9 |
| Toolformer | 33.8 | 11.5 | 53.5 |
| OPT (66B) | 21.6 | 2.9 | 30.1 |
| GPT-3 (175B) | 26.8 | 7.0 | 39.8 |

**Paper Table 4: math word problems (the first number the model generates is taken as the answer).**

| Model | ASDiv | SVAMP | MAWPS |
| --- | --- | --- | --- |
| GPT-J | 7.5 | 5.2 | 9.9 |
| GPT-J + CC | 9.6 | 5.0 | 9.3 |
| Toolformer (disabled) | 14.8 | 6.3 | 15.0 |
| Toolformer | 40.4 | 29.4 | 44.0 |
| OPT (66B) | 6.0 | 4.9 | 7.9 |
| GPT-3 (175B) | 14.0 | 10.0 | 19.8 |

**Paper Table 5: open-domain question answering.**

| Model | WebQS | NQ | TriviaQA |
| --- | --- | --- | --- |
| GPT-J | 18.5 | 12.8 | 43.9 |
| GPT-J + CC | 18.4 | 12.2 | 45.6 |
| Toolformer (disabled) | 18.9 | 12.6 | 46.7 |
| Toolformer | 26.3 | 17.7 | 48.8 |
| OPT (66B) | 18.6 | 11.4 | 45.7 |
| GPT-3 (175B) | 29.0 | 22.6 | 65.9 |

The paper's reading matches the check below:

- **LAMA.** Toolformer improves on the best same-size baseline by 11.7, 5.2 and 18.6 points, mostly through the question answering tool, and it also beats OPT and GPT-3.
- **Math.** Allowing API calls more than doubles performance on every task, and across all benchmarks the model asks the calculator for 97.9% of the examples. Note that Toolformer with API calls disabled is already better than GPT-J (ASDiv 14.8 against 7.5); the authors surmise that fine-tuning on many examples of API calls and their results improved the model's own mathematical ability.
- **Question answering.** The model relies mostly on Wikipedia search (99.3%) and clearly beats the same-size models but stays behind GPT-3. The paper attributes this both to the simplicity of the search engine, which often returns results that clearly do not match the query, and to Toolformer's inability to interact with it by reformulating the query or browsing several results.
- **Multilingual QA (MLQA, paper Table 6).** Switching the translation tool on helps in every language, but fine-tuning on CCNet hurts some languages (a distribution shift), so Toolformer does not consistently beat the original GPT-J. OPT and GPT-3 do very poorly here, mostly because they fail to answer in English as instructed.
- **Temporal datasets (paper Table 7).** Toolformer is best on both TEMPLAMA and the authors' DATESET. The TEMPLAMA gain cannot be credited to the calendar tool, which is used on only 0.2% of the examples; it comes from question answering and search. The DATESET gain comes entirely from the calendar, used on 54.8% of the examples.
- **Language modeling (paper Table 8).** Fine-tuning on $C^*$ does not raise perplexity: with API calls disabled Toolformer equals GPT-J + CC exactly, 10.3 on WikiText and 10.5 on CCNet.
- **Model size (paper Figure 4).** On the GPT-2 family (124M, 355M, 775M and 1.6B parameters) and GPT-J, the ability to use tools emerges at around 775M parameters; smaller models do about equally well with and without tools. The exception is Wikipedia search, which the authors guess is comparatively easy to use.
- **The $k$ used in decoding (paper Table 9).** A larger $k$ makes the model call APIs more often: on the T-REx subset the share of calling examples rises from 40.3% at $k=1$ to 98.1% at $k=10$, and on WebQS from 8.5% to 100%. At $k=1$ the model is somewhat calibrated: the examples where it chooses not to call are examples it would have done better on anyway (44.3 against 34.9 on T-REx, 19.9 against 18.9 on WebQS); this calibration disappears at larger $k$.

### Things to keep in mind when reading the tables

- **The metrics are more lenient than usual.** LAMA counts a hit if the right word is among the first five predicted words; the math tasks look only at the first number generated; MLQA checks whether the generation, cut at 10 words, contains the answer. These numbers cannot be compared with exact-match results from elsewhere.
- **The results depend on the decoding setting.** The main tables use $k=10$, which encourages tool use. Table 9 shows 47.8 rather than 53.5 on T-REx and 19.3 rather than 26.3 on WebQS at $k=1$.
- **The paper reports no repeated runs, seeds or error bars**, and the text does not list the number of examples in each evaluation set.
- **"Better than GPT-3" depends on which columns you count.** The check below counts them.

## Check: recompute the text's claims from the paper's tables

The script below needs no GPU and finishes in milliseconds. It copies the numbers of the paper's Tables 2 to 9 into dictionaries (I transcribed them from the PDF text and checked them against the page layout) and recomputes several things: how many examples survive each step up in the filtering threshold; the text's "improves on the best same-size baseline by" and "more than doubles" claims; the MLQA comparison by language and the averages; the wins and losses of Toolformer against GPT-3 over 17 columns; and whether the "All" column of Table 9 equals the share of calling examples times the two subset scores.

<details>
<summary>Full code (about 139 lines)</summary>

```python
"""Checking Toolformer: recompute the text's claims from the paper's tables"""
from itertools import product

# --- Numbers from arXiv 2302.04761, copied table by table ---
W = [max(0, 1 - 0.2 * t) for t in range(5)]
T2 = {  # Table 2: examples with API calls kept at each tau_f
    "QA": (51987, 18526, 5135), "WikiSearch": (207241, 60974, 13944),
    "Calculator": (3680, 994, 138), "Calendar": (61811, 20587, 3007),
    "MT": (3156, 1034, 229)}
SAME = ("GPT-J", "GPT-J+CC", "TF disabled")  # baselines of the same size
T3 = {"GPT-J": (17.8, 4.9, 31.9), "GPT-J+CC": (19.2, 5.6, 33.2),
      "TF disabled": (22.1, 6.3, 34.9), "Toolformer": (33.8, 11.5, 53.5),
      "OPT-66B": (21.6, 2.9, 30.1), "GPT-3": (26.8, 7.0, 39.8)}
T4 = {"GPT-J": (7.5, 5.2, 9.9), "GPT-J+CC": (9.6, 5.0, 9.3),
      "TF disabled": (14.8, 6.3, 15.0), "Toolformer": (40.4, 29.4, 44.0),
      "OPT-66B": (6.0, 4.9, 7.9), "GPT-3": (14.0, 10.0, 19.8)}
T5 = {"GPT-J": (18.5, 12.8, 43.9), "GPT-J+CC": (18.4, 12.2, 45.6),
      "TF disabled": (18.9, 12.6, 46.7), "Toolformer": (26.3, 17.7, 48.8),
      "OPT-66B": (18.6, 11.4, 45.7), "GPT-3": (29.0, 22.6, 65.9)}
T6 = {"GPT-J": (15.2, 16.5, 1.3, 8.2, 18.2, 8.2),
      "GPT-J+CC": (15.7, 14.9, 0.5, 8.3, 13.7, 4.6),
      "TF disabled": (19.8, 11.9, 1.2, 10.1, 15.0, 3.1),
      "Toolformer": (20.6, 13.5, 1.4, 10.6, 16.8, 3.7),
      "OPT-66B": (0.3, 0.1, 1.1, 0.2, 0.7, 0.1),
      "GPT-3": (3.4, 1.1, 0.1, 1.7, 17.7, 0.1)}
LANGS = ("Es", "De", "Hi", "Vi", "Zh", "Ar")
T7 = {"GPT-J": (13.7, 3.9), "GPT-J+CC": (12.9, 2.9),
      "TF disabled": (12.7, 5.9), "Toolformer": (16.3, 27.3),
      "OPT-66B": (14.5, 1.3), "GPT-3": (15.5, 0.8)}
T8 = {"GPT-J": (9.9, 10.6), "GPT-J+CC": (10.3, 10.5),
      "TF disabled": (10.3, 10.5)}  # perplexity: WikiText, CCNet
T9 = {  # (k, All, AC, NC, % that call)
    "T-REx": [(0, 34.9, None, 34.9, 0.0), (1, 47.8, 53.0, 44.3, 40.3),
              (3, 52.9, 58.0, 29.0, 82.8), (10, 53.5, 54.0, 22.5, 98.1)],
    "WebQS": [(0, 18.9, None, 18.9, 0.0), (1, 19.3, 17.1, 19.9, 8.5),
              (3, 26.3, 26.5, 6.6, 99.3), (10, 26.3, 26.4, None, 100.0)]}

def ints(xs):
    return " ".join(f"{x:.1f}" for x in xs)

# --- 1. The filter weights and data volume (Table 2) ---
print("1. Before normalising, max(0, 1 - 0.2t): " + ints(W))
print("   The normalised weights w_t: "
      + " ".join(f"{w / sum(W):.3f}" for w in W))
print("\n   Table 2: examples kept; last two columns: share kept per step")
print(f"   {'API':<12}{'0.5':>9}{'1.0':>9}{'2.0':>9}{'to 1.0':>9}{'to 2.0':>9}")
for name, (a, b, c) in T2.items():
    print(f"   {name:<12}{a:>9,}{b:>9,}{c:>9,}{b / a:>9.1%}{c / b:>9.1%}")
tot = [sum(v[i] for v in T2.values()) for i in range(3)]
print(f"   {'total':<12}{tot[0]:>9,}{tot[1]:>9,}{tot[2]:>9,}"
      f"{tot[1] / tot[0]:>9.1%}{tot[2] / tot[1]:>9.1%}")
share = [f"{T2['Calculator'][i] / tot[i]:.1%}" for i in range(3)]
print("   Calculator share of the total (0.5, 1.0, 2.0): "
      + ", ".join(share))

# --- 2. The text's improvements (Tables 3 to 7) ---
def gain(rows, ref):
    return [x - max(rows[m][i] for m in ref)
            for i, x in enumerate(rows["Toolformer"])]

print("\n2. LAMA (Table 3), Toolformer minus the best same-size baseline: "
      + ints(gain(T3, SAME)))
print("   minus GPT-3: " + ints(gain(T3, ("GPT-3",))))
print("   Math (Table 4), Toolformer over the same model with API off: "
      + " ".join(f"{a / b:.2f}x"
                 for a, b in zip(T4["Toolformer"], T4["TF disabled"])))
print("   QA (Table 5), minus the best same-size baseline: "
      + ints(gain(T5, SAME)))
print("   minus GPT-3: " + ints(gain(T5, ("GPT-3",))))

print("\n   MLQA (Table 6) by language:")
print(f"   {'':<12}" + "".join(f"{x:>6}" for x in LANGS) + f"{'mean':>7}")
for name in ("GPT-J", "GPT-J+CC", "TF disabled", "Toolformer", "GPT-3"):
    row = T6[name]
    print(f"   {name:<12}" + "".join(f"{x:>6.1f}" for x in row)
          + f"{sum(row) / 6:>7.2f}")
for x, y in (("Toolformer", "TF disabled"), ("Toolformer", "GPT-J"),
             ("GPT-J+CC", "GPT-J"), ("Toolformer", "GPT-3")):
    d = [u - v for u, v in zip(T6[x], T6[y])]
    print(f"   {x} - {y}: " + " ".join(f"{u:+.1f}" for u in d)
          + f" ({sum(u > 0 for u in d)} languages higher)")

wins = sum(u > v for t in (T3, T4, T5, T6, T7)
           for u, v in zip(t["Toolformer"], t["GPT-3"]))
cols = sum(len(t["GPT-3"]) for t in (T3, T4, T5, T6, T7))
print(f"\n   Toolformer beats GPT-3 175B on {wins} of {cols} columns (T3-T7)")
for title, t in (("LAMA", T3), ("Math", T4), ("QA", T5), ("MLQA", T6),
                 ("Temporal", T7)):
    lost = sum(u <= v for u, v in zip(t["Toolformer"], t["GPT-3"]))
    n = len(t["GPT-3"])
    print(f"   {title}: " + f"{lost} of {n} columns not beaten")
print("   Temporal (Table 7), Toolformer minus the same model with API off: "
      + ints(u - v for u, v in zip(T7["Toolformer"], T7["TF disabled"])))

# --- 3. Language modelling (Table 8) and decoding k (Table 9) ---
print("\n3. Perplexity (Table 8):")
print(f"   {'':<12}{'WikiText':>10}{'CCNet':>8}")
for name, (w_ppl, c_ppl) in T8.items():
    print(f"   {name:<12}{w_ppl:>10.1f}{c_ppl:>8.1f}")
base, plus_cc = T8["GPT-J"], T8["GPT-J+CC"]
print("   GPT-J+CC relative to GPT-J: "
      + f"WikiText {plus_cc[0] / base[0] - 1:+.1%}, "
      f"CCNet {plus_cc[1] / base[1] - 1:+.1%}")
print("   Toolformer with API off equals GPT-J+CC: "
      + str(T8["TF disabled"] == T8["GPT-J+CC"]))

def reachable(p, ac, nc):
    """range of the weighted mean if each printed value is rounded to 0.05"""
    vals = []
    for sp, sa, sn in product((-1, 1), repeat=3):
        q = (p + 0.05 * sp) / 100
        rest = 0 if nc is None else (1 - q) * (nc + 0.05 * sn)
        vals.append(q * (ac + 0.05 * sa) + rest)
    return min(vals), max(vals)

print("\n   Table 9: does All = share x AC + (1 - share) x NC hold?")
print(f"   {'':<7}{'k':>3}{'All':>7}{'reachable range':>22}")
for ds, rows in T9.items():
    for k, al, ac, nc, p in rows[1:]:
        lo, hi = reachable(p, ac, nc)
        ok = lo <= al + 0.05 and hi >= al - 0.05
        print(f"   {ds:<7}{k:>3}{al:>7.1f}{lo:>10.2f} .. {hi:<6.2f}"
              + ("ok" if ok else "MISMATCH"))

# --- 4. Tool-use rates that appear only in the text (percent) ---
USE = [("math benchmarks, calculator", "97.9"),
       ("QA benchmarks (T5), Wikipedia search", "99.3"),
       ("MLQA, translation, lowest to highest", "63.8 to 94.9"),
       ("MLQA Hindi, translation", "7.3"),
       ("TEMPLAMA, calendar", "0.2"), ("DATESET, calendar", "54.8")]
print("\n4. Tool-use rates quoted in the paper's text (%)")
for what, rate in USE:
    print(f"   {rate:>13}   {what}")
```

</details>

Output:

```text
1. Before normalising, max(0, 1 - 0.2t): 1.0 0.8 0.6 0.4 0.2
   The normalised weights w_t: 0.333 0.267 0.200 0.133 0.067

   Table 2: examples kept; last two columns: share kept per step
   API               0.5      1.0      2.0   to 1.0   to 2.0
   QA             51,987   18,526    5,135    35.6%    27.7%
   WikiSearch    207,241   60,974   13,944    29.4%    22.9%
   Calculator      3,680      994      138    27.0%    13.9%
   Calendar       61,811   20,587    3,007    33.3%    14.6%
   MT              3,156    1,034      229    32.8%    22.1%
   total         327,875  102,115   22,453    31.1%    22.0%
   Calculator share of the total (0.5, 1.0, 2.0): 1.1%, 1.0%, 0.6%

2. LAMA (Table 3), Toolformer minus the best same-size baseline: 11.7 5.2 18.6
   minus GPT-3: 7.0 4.5 13.7
   Math (Table 4), Toolformer over the same model with API off: 2.73x 4.67x 2.93x
   QA (Table 5), minus the best same-size baseline: 7.4 4.9 2.1
   minus GPT-3: -2.7 -4.9 -17.1

   MLQA (Table 6) by language:
                   Es    De    Hi    Vi    Zh    Ar   mean
   GPT-J         15.2  16.5   1.3   8.2  18.2   8.2  11.27
   GPT-J+CC      15.7  14.9   0.5   8.3  13.7   4.6   9.62
   TF disabled   19.8  11.9   1.2  10.1  15.0   3.1  10.18
   Toolformer    20.6  13.5   1.4  10.6  16.8   3.7  11.10
   GPT-3          3.4   1.1   0.1   1.7  17.7   0.1   4.02
   Toolformer - TF disabled: +0.8 +1.6 +0.2 +0.5 +1.8 +0.6 (6 languages higher)
   Toolformer - GPT-J: +5.4 -3.0 +0.1 +2.4 -1.4 -4.5 (3 languages higher)
   GPT-J+CC - GPT-J: +0.5 -1.6 -0.8 +0.1 -4.5 -3.6 (2 languages higher)
   Toolformer - GPT-3: +17.2 +12.4 +1.3 +8.9 -0.9 +3.6 (5 languages higher)

   Toolformer beats GPT-3 175B on 13 of 17 columns (T3-T7)
   LAMA: 0 of 3 columns not beaten
   Math: 0 of 3 columns not beaten
   QA: 3 of 3 columns not beaten
   MLQA: 1 of 6 columns not beaten
   Temporal: 0 of 2 columns not beaten
   Temporal (Table 7), Toolformer minus the same model with API off: 3.6 21.4

3. Perplexity (Table 8):
                 WikiText   CCNet
   GPT-J              9.9    10.6
   GPT-J+CC          10.3    10.5
   TF disabled       10.3    10.5
   GPT-J+CC relative to GPT-J: WikiText +4.0%, CCNet -0.9%
   Toolformer with API off equals GPT-J+CC: True

   Table 9: does All = share x AC + (1 - share) x NC hold?
            k    All       reachable range
   T-REx    1   47.8     47.75 .. 47.86 ok
   T-REx    3   52.9     52.95 .. 53.08 ok
   T-REx   10   53.5     53.34 .. 53.47 ok
   WebQS    1   19.3     19.61 .. 19.71 MISMATCH
   WebQS    3   26.3     26.30 .. 26.42 ok
   WebQS   10   26.3     26.34 .. 26.46 ok

4. Tool-use rates quoted in the paper's text (%)
            97.9   math benchmarks, calculator
            99.3   QA benchmarks (T5), Wikipedia search
    63.8 to 94.9   MLQA, translation, lowest to highest
             7.3   MLQA Hindi, translation
             0.2   TEMPLAMA, calendar
            54.8   DATESET, calendar
```

Reading it item by item:

- **Weights.** $\max(0,1-0.2t)$ is 1.0, 0.8, 0.6, 0.4, 0.2 for $t=0,\dots,4$; normalized, 0.333, 0.267, 0.200, 0.133, 0.067. The first token after the call carries the most weight, 5 times the fifth, and tokens further out do not count.
- **The filtering thresholds of Table 2.** Raising $\tau_f$ from 0.5 to 1.0 cuts the examples from 327,875 to 102,115, only 31.1% of them; raising it to 2.0 leaves 22,453, which is 22.0% of the previous level. The calculator is the rarest API, only 1.1%, 1.0% and 0.6% of the total at the three levels.
- **"How much higher" in the text.** On LAMA, Toolformer is 11.7, 5.2 and 18.6 points above the best baseline of the same size, as the text says. On math, the score with the API enabled is 2.73, 4.67 and 2.93 times that of the same model with the API disabled; the text says "more than doubles", and the real factors are much larger. On open-domain QA it is 7.4, 4.9 and 2.1 points higher, but below GPT-3 in all three columns (by 2.7, 4.9 and 17.1).
- **The tally against GPT-3.** Over the 17 columns of Tables 3 to 7, Toolformer is above GPT-3 175B in 13: all 3 LAMA columns, all 3 math columns and both temporal datasets, 5 of the 6 MLQA columns (only Chinese is lower), and none of the 3 open-domain QA columns. So "a small model beating a large one" holds on LAMA and math and does not hold on open-domain QA.
- **MLQA.** With the translation tool on, all 6 languages beat the same model with the API disabled (+0.2 to +1.8). But fine-tuning on CCNet itself hurts 4 of them (GPT-J+CC beats GPT-J in only 2 languages, mean 9.62 against 11.27), so Toolformer (mean 11.10) beats the original GPT-J in only 3 languages and its mean is slightly lower. The paper says it "does not always outperform" GPT-J, and the numbers agree.
- **Perplexity.** The paper says fine-tuning on $C^*$ does not raise perplexity, comparing with GPT-J+CC, which is fine-tuned on $C$ without API calls; the script confirms the two rows are identical. Against the original GPT-J, however, fine-tuning on CCNet itself raises the WikiText perplexity by 4.0% (9.9 to 10.3) and lowers the CCNet perplexity by 0.9% (10.6 to 10.5): that is a distribution shift of the fine-tuning corpus, unrelated to API calls.
- **Internal consistency of Table 9.** The "All" column should equal the fraction of calls times the score on the called subset plus one minus the fraction times the score on the rest. Widening every number to its rounding range of 0.05, 5 of the 6 rows are consistent. The WebQS row at $k=1$ is not: the table says 19.3, while the fraction and the two subset scores can only give a value between 19.61 and 19.71. The gap is about 0.3 points; I cannot tell whether it is a typo or a different convention, it does not change any conclusion, but do not read that row as exact.
- **Rates that appear only in the text.** 97.9% (the calculator on the math benchmarks), 99.3% (wiki search on question answering), 63.8% to 94.9% for the translation tool on MLQA (Hindi only 7.3%), 0.2% for the calendar on TEMPLAMA and 54.8% for the calendar on DATESET; these have no counterpart in a table, so the script merely copies them together and cannot recompute them.

## Experiment: what the filter criterion actually measures

The paper's filtering criterion is a single number. What does it measure, and when is it large or small? The script below reproduces only the criterion itself: given a sentence and a calculator call, it computes $L^- - L^+$ with the paper's formulas. It does no sampling and no fine-tuning, and it does not reproduce the paper's downstream results, so it can neither confirm nor refute the paper's conclusions; it only makes the behavior of the criterion visible.

Environment: Apple M2 Max (MPS backend, 64 GB of memory), Python 3.14.3, PyTorch 2.10.0, Transformers 5.3.0, pandas 3.0.1; the models are `Qwen/Qwen2.5-0.5B` and `Qwen/Qwen2.5-7B` (Apache-2.0, float32), and the corpus is the `wikitext-2-raw-v1` configuration of `Salesforce/wikitext` (CC BY-SA 3.0). A full run takes about 1 minute for the 0.5B model and about 6 minutes for the 7B model. Nothing is sampled, so each model's output is deterministic, but a different machine or library version may change individual numbers slightly.

A few things about the setup first:

- **Scoring follows the paper.** The weights are $\max(0,1-0.2t)$, normalized to 0.333, 0.267, 0.200, 0.133 and 0.067, and only the five tokens after the call are scored. $L^-$ is the smaller of the loss with no call and the loss with the call but no result. Following the paper's footnote, the whole string `[Calculator(...) -> result] ` is placed at the very start of the sentence and the window starts at the position of the result. The paper does not say how long its text segments are; here a segment is one sentence.
- **Controlled sentences.** Four operations, two difficulty levels and 12 sentences each make 96 sentences. Each uses a fixed template that tells a small arithmetic story (loaves baked on two days, books left in a library, and so on) and is paired with a **correct** calculator call. The easy level uses two-digit addition and subtraction, single-digit multiplication and division with a single-digit quotient; the hard level uses four-digit addition and subtraction, three-digit by three-digit multiplication, and division of a number 12 to 49 times a three-digit divisor by that divisor (a two-digit quotient). The numbers come from a fixed seed (7); the Chinese and English editions of this post use the same numbers with different wording.
- **The call position $d$.** In the controlled sentences the window can start $d$ tokens before the first token of the result: $d=0$ means the window starts at the first digit, and for $d\ge 5$ the five-token window lies entirely before the result. The Qwen2.5 tokenizer splits numbers into single digits and the two models share one vocabulary, so both models see exactly the same tokens.
- **Real text.** WikiText-2 is split into sentences, and candidate calls are found by a rule: a number in the sentence equals the sum, difference, product or quotient of two earlier numbers (similar to the heuristic the paper uses for the calculator, but the candidates are not sampled from a model). 200 candidates are drawn at random with a fixed seed (11). As a control, the operator is replaced by the next one (plus to minus, minus to times, times to divide, divide to plus): same operands, wrong result.
- **The paper's thresholds do not transfer.** $\tau_f=1.0$ and 0.5 are values chosen for GPT-J; for another model or corpus the same number means a different strictness. The figure and tables treat them as reference lines, not verdicts.
- **What the intervals mean.** The 95% bootstrap intervals only say what would happen if these 48 sentences were replaced by another draw (2,000 resamples of sentences with replacement); the proportions among the 200 real candidates use Wilson intervals. Neither includes the variation from a different template or wording, which turns out to be larger.

<details>
<summary>Full code (about 208 lines)</summary>

```python
"""The Toolformer filter: can L- minus L+ tell useful calls apart"""
import glob
import itertools
import random
import re
import sys

import pandas as pd
import torch
from huggingface_hub import snapshot_download
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.utils import logging as hf_logging

hf_logging.set_verbosity_error()
hf_logging.disable_progress_bar()
NAME = sys.argv[1]
DEV = sys.argv[2] if len(sys.argv) > 2 else "mps"
W = [max(0.0, 1 - 0.2 * t) for t in range(5)]  # paper: w~_t = max(0, 1 - 0.2 t)
W = [w / sum(W) for w in W]
OPS = {"+": lambda a, b: a + b, "-": lambda a, b: a - b,
       "*": lambda a, b: a * b, "/": lambda a, b: a / b if b else None}
NEXT = {"+": "-", "-": "*", "*": "/", "/": "+"}  # wrong call: next operator
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModelForCausalLM.from_pretrained(
    NAME, dtype=torch.float32).to(DEV).eval()

def fmt(x):
    return f"{x:.2f}".rstrip("0").rstrip(".")  # the calculator keeps 2 decimals

def call(a, op, b, with_result=True):
    """e(c, r) or e(c) in the paper's notation, with the markers [ ] and ->"""
    r = OPS[op](a, b)
    tail = f" -> {fmt(r)}" if with_result else ""
    return f"[Calculator({fmt(a)} {op} {fmt(b)}){tail}] "

def logprobs(prefix, ids):
    """log p of each token of ids (the first one has no context)"""
    pre = tok(prefix).input_ids if prefix else []
    x = torch.tensor([pre + ids]).to(DEV)
    with torch.no_grad():
        lp = model(x).logits[0].float().log_softmax(-1)
    return [None if not pre and j == 0 else lp[len(pre) + j - 1, ids[j]].item()
            for j in range(len(ids))]

def loss(lp, i):
    """L_i(z): weighted cross entropy of the five tokens from position i"""
    return -sum(w * lp[i + t] for t, w in enumerate(W) if i + t < len(lp))

def evaluate(text, pos, a, op, b):
    """(index of the result token, [none, call only, call + result, wrong])"""
    enc = tok(text, return_offsets_mapping=True)
    r0 = next(j for j, (s, _) in enumerate(enc.offset_mapping) if s >= pos)
    prefixes = ["", call(a, op, b, False), call(a, op, b),
                call(a, NEXT[op], b)]
    return r0, [logprobs(p, enc.input_ids) for p in prefixes]

def score(lp, i):
    """L- - L+ for a call inserted at position i"""
    return min(loss(lp[0], i), loss(lp[1], i)) - loss(lp[2], i)

def mean(xs):
    return sum(xs) / len(xs)

def boot(xs, n=2000, seed=0):
    """95% bootstrap interval of the mean (sentences resampled)"""
    r = random.Random(seed)
    ms = sorted(mean([r.choice(xs) for _ in xs]) for _ in range(n))
    return ms[int(0.025 * n)], ms[int(0.975 * n)]

def wilson(k, n, z=1.96):
    """Wilson 95% interval of a share (in %)"""
    p, d = k / n, 1 + z * z / n
    c = (p + z * z / (2 * n)) / d
    h = z * (p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5 / d
    return 100 * (c - h), 100 * (c + h)

print(f"{NAME}, float32, {DEV}")
print("Weights on the five tokens after the call: "
      + " ".join(f"{w:.3f}" for w in W))

# --- 1. Controlled test ---
TPL = {
    "+": "The bakery baked {a} loaves on Monday and {b} loaves on Tuesday, "
         "so over the two days it baked {r} loaves in total.",
    "-": "The library owned {a} books and lent out {b} of them, "
         "so only {r} books were left on the shelves.",
    "*": "Each of the {a} boxes holds {b} pencils, "
         "so the boxes hold {r} pencils altogether.",
    "/": "The school has {a} pupils and puts {b} pupils in each class, "
         "so it needs {r} classes."}
RANGE = {  # (level, op): (range of a, range of b)
    ("easy", "+"): ((10, 49), (10, 49)), ("easy", "-"): ((30, 99), (10, 29)),
    ("easy", "*"): ((3, 9), (3, 9)), ("easy", "/"): ((3, 9), (3, 9)),
    ("hard", "+"): ((2000, 8999), (2000, 8999)),
    ("hard", "-"): ((5000, 9999), (1000, 4999)),
    ("hard", "*"): ((100, 499), (100, 499)),
    ("hard", "/"): ((12, 49), (100, 499))}
rng, rows = random.Random(7), {"easy": [], "hard": []}
for (level, op), (ra, rb) in RANGE.items():
    for _ in range(12):
        a, b = rng.randint(*ra), rng.randint(*rb)
        if op == "/":  # division: the dividend is a multiple of b
            a = a * b
        res = fmt(OPS[op](a, b))
        text = TPL[op].format(a=a, b=b, r=res)
        r0, lp = evaluate(text, text.rindex(res, text.index(str(b))), a, op, b)
        rows[level].append((r0, lp))
n = sum(len(v) for v in rows.values())
print(f"\n1. Controlled test: {n} sentences, one correct call each")
print("   The call goes d tokens before the first token of the result")
print("   Mean L- - L+ (in brackets: share of calls at least 1.0)")
print(f"   {'d':>3}{'easy':>16}{'hard':>16}")
for d in range(8):
    cells = []
    for level in ("easy", "hard"):
        s = [score(lp, r0 - d) for r0, lp in rows[level]]
        cells.append(f"{mean(s):6.2f} ({mean([x >= 1 for x in s]):4.0%})")
    print(f"   {d:>3}{cells[0]:>16}{cells[1]:>16}")
print("\n   d = 0: mean and 95% bootstrap interval (2,000 resamples)")
for level in ("easy", "hard"):
    s = [score(lp, r0) for r0, lp in rows[level]]
    lo, hi = boot(s)
    print(f"   {level:<6}{mean(s):6.2f}  [{lo:5.2f}, {hi:5.2f}]")
print("\n   Losses at d = 0 under the four prefixes (means)")
print(f"   {'':<6}{'none':>8}{'call':>8}{'call+r':>8}{'wrong':>8}")
for level in ("easy", "hard"):
    ls = [[loss(x, r0) for x in lp] for r0, lp in rows[level]]
    print(f"   {level:<6}" + "".join(f"{mean([x[k] for x in ls]):8.2f}"
                                     for k in range(4)))

# --- 2. Real text ---
NUM = re.compile(r"(?<![\w.,])\d{1,3}(?:,\d{3})+(?:\.\d+)?(?!\w)"
                 r"|(?<![\w.,])\d+(?:\.\d+)?(?!\w)")

def wikitext_sentences():
    root = snapshot_download("Salesforce/wikitext", repo_type="dataset",
                             allow_patterns="wikitext-2-raw-v1/*",
                             local_files_only=True)
    out = []
    for f in sorted(glob.glob(root + "/wikitext-2-raw-v1/*.parquet")):
        for p in pd.read_parquet(f)["text"]:
            if p.strip() and not p.strip().startswith("="):
                p = p.replace(" @,@ ", ",").replace(" @.@ ", ".")
                p = p.replace(" @-@ ", "-")
                p = re.sub(r" ([,.;:!?%)])", r"\1", p.strip())
                out += re.split(r"(?<=[.!?]) (?=[A-Z])", p)
    return out

def triples(s):
    """a number that is a op b of two earlier numbers"""
    nums = [(m.start(), float(m.group().replace(",", "")))
            for m in NUM.finditer(s)]
    out = []
    for (pa, a), (pb, b) in itertools.permutations(nums, 2):
        for op, f in OPS.items():
            if (op in "+*" and pa > pb) or a <= 1 or b <= 1:
                continue
            r = f(a, b)
            out += [(pc, a, op, b) for pc, c in nums
                    if pc > max(pa, pb) and c >= 10 and c not in (a, b)
                    and r is not None and round(r, 2) == c]
    return out

sents = wikitext_sentences()
many = [s for s in sents if len(NUM.findall(s)) >= 3]
cands = list(dict.fromkeys((s, t) for s in many for t in triples(s)))
picked = random.Random(11).sample(cands, 200)
print(f"\n2. Real text: WikiText-2 has {len(sents):,} sentences")
print(f"   with at least 3 numbers: {len(many):,}")
print(f"   with a number equal to a op b of two earlier ones: "
      f"{len({s for s, _ in cands})} sentences,\n"
      f"   {len(cands)} candidate calls")
print(f"   {len(picked)} are drawn at random and scored (seed 11)")
res = []
for s, (pc, a, op, b) in picked:
    r0, lp = evaluate(s, pc, a, op, b)
    res.append((score(lp, r0), loss(lp[0], r0) - loss(lp[3], r0),
                s, pc, a, op, b))
sc = [x[0] for x in res]
print("   L- - L+ >= 0.5:", sum(x >= .5 for x in sc),
      "  >= 1.0:", sum(x >= 1 for x in sc),
      "  >= 2.0:", sum(x >= 2 for x in sc), "  < 0:", sum(x < 0 for x in sc))
k05 = sum(x >= .5 for x in sc)
lo, hi = wilson(k05, len(sc))
print(f"   Share >= 0.5: {100 * k05 / len(sc):.1f}%, "
      f"Wilson 95% interval {lo:.1f}% to {hi:.1f}%")
ctrl = [x[1] for x in res]
print(f"   Control with the wrong operator: L(none) - L(wrong) averages "
      f"{mean(ctrl):.2f},\n   {sum(x >= 1 for x in ctrl)} of them at least 1.0")
for title, part in (("The 4 highest", sorted(res, reverse=True)[:4]),
                    ("The 3 lowest", sorted(res)[:3])):
    print("   " + title)
    for g, _, s, pc, a, op, b in part:
        print(f"   {g:+5.2f} ..{s[max(0, pc - 24):pc]}[{fmt(a)} {op} {fmt(b)}]"
              f"{s[pc:pc + 14]}..")
```

</details>

Output for Qwen2.5-0.5B:

```text
Qwen/Qwen2.5-0.5B, float32, mps
Weights on the five tokens after the call: 0.333 0.267 0.200 0.133 0.067

1. Controlled test: 96 sentences, one correct call each
   The call goes d tokens before the first token of the result
   Mean L- - L+ (in brackets: share of calls at least 1.0)
     d            easy            hard
     0     0.05 (  0%)     0.82 ( 31%)
     1     0.04 (  0%)     0.57 ( 25%)
     2    -0.11 (  0%)     0.18 (  6%)
     3     0.17 (  0%)     0.26 (  0%)
     4     0.24 (  0%)     0.22 (  0%)
     5     0.36 (  0%)     0.29 (  0%)
     6     0.35 (  0%)     0.27 (  0%)
     7     0.11 (  0%)     0.05 (  0%)

   d = 0: mean and 95% bootstrap interval (2,000 resamples)
   easy    0.05  [-0.02,  0.11]
   hard    0.82  [ 0.54,  1.09]

   Losses at d = 0 under the four prefixes (means)
             none    call  call+r   wrong
   easy      0.87    0.79    0.57    0.90
   hard      1.47    1.51    0.48    1.90

2. Real text: WikiText-2 has 85,009 sentences
   with at least 3 numbers: 6,415
   with a number equal to a op b of two earlier ones: 229 sentences,
   432 candidate calls
   200 are drawn at random and scored (seed 11)
   L- - L+ >= 0.5: 9   >= 1.0: 1   >= 2.0: 0   < 0: 114
   Share >= 0.5: 4.5%, Wilson 95% interval 2.4% to 8.3%
   Control with the wrong operator: L(none) - L(wrong) averages -0.06,
   0 of them at least 1.0
   The 4 highest
   +1.16 ..ft) and a saddle DEM of [3184 - 2187]997 metres ( 3..
   +0.94 ..e winning percentage of [66.7 - 7.5]59.2%...
   +0.87 ..; 1,210 mi) and, later, [1940 - 1050]890-nautical-m..
   +0.85 ..n his season average of [270 - 13]257 yards...
   The 3 lowest
   -1.30 .. 16 by 4 metres ( 52 by [52 / 4]13 ft) stucco ..
   -1.10 .. with 4 × 100 m and 4 × [100 * 4]400 m events, ..
   -0.82 ..– 97, 1898 – 99, 1899 – [7 + 1893]1900, 1909 – 1..
```

Output for Qwen2.5-7B:

```text
Qwen/Qwen2.5-7B, float32, mps
Weights on the five tokens after the call: 0.333 0.267 0.200 0.133 0.067

1. Controlled test: 96 sentences, one correct call each
   The call goes d tokens before the first token of the result
   Mean L- - L+ (in brackets: share of calls at least 1.0)
     d            easy            hard
     0    -0.17 (  0%)     0.17 ( 12%)
     1    -0.05 (  0%)     0.23 (  4%)
     2    -0.08 (  0%)     0.11 (  0%)
     3    -0.01 (  0%)     0.05 (  0%)
     4     0.05 (  0%)     0.06 (  0%)
     5     0.15 (  0%)     0.16 (  2%)
     6     0.10 (  0%)     0.05 (  0%)
     7     0.06 (  4%)    -0.01 (  0%)

   d = 0: mean and 95% bootstrap interval (2,000 resamples)
   easy   -0.17  [-0.23, -0.12]
   hard    0.17  [ 0.02,  0.31]

   Losses at d = 0 under the four prefixes (means)
             none    call  call+r   wrong
   easy      0.80    0.65    0.70    1.14
   hard      0.91    0.59    0.36    1.53

2. Real text: WikiText-2 has 85,009 sentences
   with at least 3 numbers: 6,415
   with a number equal to a op b of two earlier ones: 229 sentences,
   432 candidate calls
   200 are drawn at random and scored (seed 11)
   L- - L+ >= 0.5: 5   >= 1.0: 2   >= 2.0: 0   < 0: 122
   Share >= 0.5: 2.5%, Wilson 95% interval 1.1% to 5.7%
   Control with the wrong operator: L(none) - L(wrong) averages -0.02,
   0 of them at least 1.0
   The 4 highest
   +1.33 ..e winning percentage of [66.7 - 7.5]59.2%...
   +1.12 ..; 1,210 mi) and, later, [1940 - 1050]890-nautical-m..
   +0.62 ..ft) and a saddle DEM of [3184 - 2187]997 metres ( 3..
   +0.56 ..le, while the remaining [43 - 28]15 were exclud..
   The 3 lowest
   -0.46 ..– 97, 1898 – 99, 1899 – [7 + 1893]1900, 1909 – 1..
   -0.46 .. inches ( 42 m) long by [42 / 3]14 feet ( 4.3 ..
   -0.41 ..eing the 4 × 200 m, 4 × [4 * 200]800 m and 4 × ..
```

*Figure: Figure 2: values of the filter on two models. Left: 96 controlled sentences (48 easy and 48 hard, 12 per operator at each level). Right: 200 calls drawn at random from 432 candidates. Numbers come from one complete run of this page's script; the Qwen2.5 tokenizer splits numbers into single digits, so they are not comparable with the paper's GPT-J.*

Reading the results:

- **Harder sentences score higher.** At $d=0$ the 0.5B model gives 0.05 on easy and 0.82 on hard sentences, and the 7B model gives −0.17 and 0.17; for both models the easy and hard intervals do not overlap (0.5B: easy [−0.02, 0.11], hard [0.54, 1.09]; 7B: easy [−0.23, −0.12], hard [0.02, 0.31]), and the Chinese edition's run points the same way. That agrees with the paper's intuition: a result the model could guess anyway adds nothing, while a result it could not guess is new information. One confound is not separated here: the results of the hard sentences are longer, so more of the five scored tokens are result digits, whereas an easy sentence spends part of the window on tokens after the result (a closing word and a period) that are easy to guess whatever the call says, which dilutes the average. So "hard scores higher" mixes the arithmetic being harder to guess with the share of the window that is result digits, and this experiment does not tell them apart.
- **Writing only the call can already help, which is why $L^-$ takes a minimum.** For the 7B model on hard sentences the loss is 0.91 with no call, 0.59 with the call only and 0.36 with the call and the result: just writing the two operands at the start of the text already makes the digits easier to predict (the model can copy them and estimate), and taking the smaller of the two losses keeps that benefit from being credited to the result. The 0.5B model barely reacts to the call alone: 0.79 against 0.87 with no call on easy sentences and 1.51 against 1.47 on hard ones, so for it $L^-$ is close to the no-call loss.
- **Position matters, at least for the 0.5B model on hard sentences:** the score is 0.82 at $d=0$, 0.57 at $d=1$ and 0.18 at $d=2$. The share of hard sentences at or above 1.0 at $d=0$ is 31% for the 0.5B model and 12% for the 7B model. This fits the paper's choice of weights that cover only five tokens: a call survives only if it sits where the information is actually useful. My inference is that the paper's sampler (a call is proposed only where $p_i>\tau_s$) together with this filter pushes calls toward the place where the answer is about to appear, but the paper has no separate experiment on that. The 7B model's English scores are small at every $d$ (at most 0.23), so there is little to decay.
- **The criterion is relative to the model and to the wording, and the numbers can even change sign.** The 7B model scores −0.17 [−0.23, −0.12] on the easy sentences here; the Chinese edition of this post reruns the same experiment with Chinese sentences (same numbers, different wording), and there the same model scores 0.62 [0.50, 0.76]. In the English sentences the loss with the call only is already 0.65 and adding the result raises it to 0.70: with the expression written in front, the model is fairly confident, the result lowers the loss no further, and the filter would drop this call. I did not chase down why the Chinese wording still "needs" the result (candidate reasons: the tokens after the result differ between the two wordings, and so does the model's confidence in arithmetic inside the sentence), but it is enough to show that the quantity measures how much this model needs the result in this text, not how useful the call is in itself. The order of the models flips with the wording too: here the 7B model scores well below the 0.5B model on hard sentences (0.17 against 0.82), while in the Chinese edition the 7B model is higher (1.15 against 0.99, with overlapping intervals). The reasoning behind the paper's first requirement, that what humans find useful may differ from what a model finds useful, gets a concrete example.
- **On real text the criterion is very demanding.** Of the 200 candidates only 1 (0.5B) and 2 (7B) reach 1.0, 9 (4.5%, Wilson interval 2.4% to 8.3%) and 5 (2.5%, 1.1% to 5.7%) reach 0.5, and the largest group scores below zero, 114 and 122, meaning the result made the text harder to predict than the better of the two alternatives. The top scorers are cases where the digits of the result are hard to guess from the context, such as `[66.7 - 7.5]59.2%` (first or second for the two models) and `[3184 - 2187]997 metres`, so the result really is new information; the rule only guarantees that the numbers agree, and I did not check one by one whether the original text derived them from the two earlier numbers. The bottom scorers are coincidences or typographic patterns, such as `4 × 100 m and 4 × [100 * 4]400 m` (second lowest for the 0.5B model) and `4 × 200 m, 4 × [4 * 200]800 m` (third lowest for the 7B model): the way relay events are written makes the second number easy to guess, and it has nothing to do with multiplication. That is the behavior the criterion is meant to have: it filters out numbers that merely happen to equal an operation's result. In the paper's Table 2 the calculator makes up only 1.1%, 1.0% and 0.6% of the kept samples at the three thresholds, which is also scarce, but the corpus, the models and the way candidates are produced all differ here, so I do not compare the two figures.
- **The wrong-operator control.** On real text, $L(\text{none})-L(\text{wrong})$ averages −0.06 for the 0.5B model and −0.02 for the 7B model, and none of the 200 reaches 1.0: a wrong result neither helps nor clearly hurts, and in real text it is close to writing nothing. In the controlled sentences the models do copy wrong results and pay for it: the loss with the wrong result is above the no-call loss for the 7B model (1.14 against 0.80 on easy, 1.53 against 0.91 on hard) and for the 0.5B model on hard sentences (1.90 against 1.47), and about equal for the 0.5B model on easy sentences (0.90 against 0.87).
- **One thing I could not explain.** In this run the 0.5B curves do not fall to zero for $d=3$ to 6 but stay around 0.2 to 0.4 (easy 0.17 to 0.36, hard 0.22 to 0.29), although the result is mostly outside the window; the Chinese edition's curves are near zero at the same positions. I did not investigate, so I read nothing into the values for $d\ge 3$ and use only $d=0$ to 2 for the statement that the score decays with distance.

### What this experiment does and does not show

- **It shows:** in controlled sentences $L^- - L^+$ does separate "the result carries new information" from "the result is redundant"; it is very sensitive to the position of the call, the model and the wording; and on real Wikipedia text, even among sentences with a number that equals an operation on two earlier numbers (where calculator calls are most likely), only 0.5% to 1% get past 1.0 (with very few samples, see below).
- **It does not show:** what dataset or downstream results the paper's full pipeline (the model samples calls, filters them and is fine-tuned) would produce with these two models, because I only did the scoring step; how loose or strict $\tau_f=1.0$ is on GPT-J; whether "hard" or "longer result" is doing the work (first bullet above); why the two wordings differ; or how much of the low real-text scores comes from putting the call at the start of the sentence, far from the result (the paper's footnote requires this because the model has not yet been fine-tuned on text with calls, and whether the model can use a result placed far away itself affects the score). I did not separate that last factor.
- **Scale:** the controlled part has only 96 sentences per model and language (4 operations × 2 levels × 12), 48 per cell of the table, from only four templates, so the numbers carry the wording of those templates; the real-text part has 200 candidates (drawn from 432), and the 1 and 2 that pass 1.0 are single digits, too few for fine comparisons; both models belong to the Qwen2.5 family and share a vocabulary, so they do not represent other models.

## Limitations and what came next

The paper's own "Limitations" section lists these:

- **No chained tool use.** API calls for each tool are generated independently, so the fine-tuning data has no example where the output of one tool becomes the input of another.
- **No interactive tool use.** A search engine can return hundreds of results, and for some applications it matters that the model can browse them or rewrite its query. This method cannot. The paper attributes the open-domain QA gap to GPT-3 to two things: the simple BM25 search engine (it often returns results that clearly do not match the question) and the model's inability to reformulate a query or browse several top results.
- **Sensitivity to input wording.** When deciding whether to call an API, the model is often sensitive to the exact wording of its input. The paper calls this unsurprising, since language models are known to be sensitive to prompts in zero-shot and few-shot settings.
- **Low sample efficiency.** Depending on the tool, processing more than a million documents yields only a few thousand useful calls to the calculator. Table 2 in the check above gives the actual counts: for $\tau_f$ of 0.5, 1.0 and 2.0, the calculator has 3,680, 994 and 138 samples. The paper suggests applying the procedure iteratively, as other bootstrapping methods do.
- **No cost awareness.** The decision whether to call ignores the computational cost of each tool.

The first two points are exactly where ReAct-style methods are strong: the model alternates between thinking and calling across several steps, and the next query can be rewritten from the last observation (see the [ReAct explainer](https://dmxsf.com/en/blog/react-reasoning-and-acting/)). The price is equally clear: ReAct needs task-specific examples in the prompt (or extra training), while Toolformer, once fine-tuned, needs no task-specific prompt, which is the selling point the paper stresses. The two routes address different sides of the same problem; neither replaces the other.

## What to take away from this paper

1. **It turns "should a tool be called?" into something computable.** $L^- - L^+$ needs no human labels: the model's own prediction loss is the judge. The paper's contribution is to connect this criterion with sampling, execution and fine-tuning into a pipeline that needs almost no annotation.
2. **The criterion is relative to the model and to the wording.** In this post's experiment the same expressions on the same 7B model score -0.17 on easy sentences in English wording and 0.62 in Chinese wording (the Chinese edition's run). Before filtering another model or corpus with the paper's $\tau_f=1.0$, look at the distribution of scores first.
3. **It is demanding, and that is a feature.** Among 200 WikiText-2 candidates where a number happens to equal an operation on two earlier numbers, only 1 (0.5B) and 2 (7B) reach 1.0 and most scores are negative; what remains are the calls whose result the model really needs.
4. **The limitations mark the method's boundary.** No chaining, no interaction, sensitivity to wording, low sample efficiency, no notion of cost; later interactive methods such as ReAct and today's function-calling training fill these gaps.
5. **Recompute the tables when you read a paper.** "More than doubled" is actually 2.7 to 4.7 times, "better than GPT-3" holds in 13 of 17 columns, and one row of Table 9 does not add up.

## Further reading

- Paper: [Toolformer (arXiv 2302.04761)](https://arxiv.org/abs/2302.04761), this page follows v1 (9 February 2023).
- Models and data the paper uses: [GPT-J](https://github.com/kingoflolz/mesh-transformer-jax), [Atlas (arXiv 2208.03299)](https://arxiv.org/abs/2208.03299), [NLLB (arXiv 2207.04672)](https://arxiv.org/abs/2207.04672), [LAMA (arXiv 1909.01066)](https://arxiv.org/abs/1909.01066), [CCNet (arXiv 1911.00359)](https://arxiv.org/abs/1911.00359).
- Contemporary and later tool-use methods: [WebGPT (arXiv 2112.09332)](https://arxiv.org/abs/2112.09332), [PAL (arXiv 2211.10435)](https://arxiv.org/abs/2211.10435), [TALM (arXiv 2205.12255)](https://arxiv.org/abs/2205.12255), [ReAct (arXiv 2210.03629)](https://arxiv.org/abs/2210.03629).
- On this site: [Agents and Tool Calling](https://dmxsf.com/en/wiki/applications/agents-and-tool-calling/), [Structured Output and Function Calling](https://dmxsf.com/en/wiki/applications/structured-output-and-function-calling/), [ReAct explainer](https://dmxsf.com/en/blog/react-reasoning-and-acting/).

## FAQ

### What is Toolformer, and how does it differ from ReAct and function calling?

Toolformer is a self-supervised tool-learning method from Meta AI and collaborators (2023): a language model writes API calls into ordinary text by itself, the calls are executed, only those after which the following text is clearly easier to predict are kept, and the model is fine-tuned on the kept text with the ordinary language-modeling loss. It trains when to call a tool into the parameters, so after fine-tuning no task-specific prompt is needed. ReAct relies on examples in the prompt to make the model alternate thoughts and actions, which allows multi-step, interactive tool use but needs examples for each task. Today's function calling trains structured calls into the model with supervised fine-tuning and reinforcement learning.

### How does Toolformer decide which API calls to keep?

For each candidate call it compares two losses: L+ is the weighted cross entropy of the next five tokens when the call and its result are placed before the text, and L- is the smaller of the losses with no call and with the call but no result. A call is kept only if L- minus L+ is at least a threshold; the paper's default is 1.0, relaxed to 0.5 for the calculator and machine translation because useful examples are rare. The weights are max(0, 1 - 0.2t), normalized, so only the five tokens right after the call have non-zero weight.

### Does Toolformer need human annotation? Where does the training data come from?

It needs no large-scale annotation, only a handful of demonstrations per tool. The demonstrations go into a prompt, and the 6.7B-parameter GPT-J marks likely call positions and samples calls on a subset of CCNet; the calls are executed and filtered with the loss criterion above, the kept calls are inserted back into the original text, and the model is fine-tuned on this dataset, which is identical to the original text except for the inserted calls. The paper uses at most 25,000 samples per API.

### Is Toolformer really better than GPT-3?

It depends on the task. Across the 17 columns of the paper's Tables 3 to 7, Toolformer (6.7B parameters) is above GPT-3 175B in 13: all 3 LAMA columns, all 3 math word-problem columns and both temporal datasets, and 5 of the 6 MLQA columns, but it is below GPT-3 in all 3 open-domain QA columns (WebQS, NQ, TriviaQA). The paper attributes the QA gap to the simple search engine it uses and to the model's inability to rewrite queries or browse several results.

### What are Toolformer's limitations?

The paper lists five: tools cannot be chained (one tool's output cannot be another's input); tools cannot be used interactively (no browsing of search results, no query rewriting); the model is sensitive to the wording of the input; sample efficiency is low (processing over a million documents yields only a few thousand useful calculator calls); and the cost of calling a tool is not taken into account. The first two are exactly where ReAct-style methods are strong.
