Search

Search papers and lessons

Toolformer: Language Models Can Teach Themselves to Use Tools

Timo Schick, Jane Dwivedi-Yu, Roberto Dessì et al. · 2023

Toolformer teaches a language model to insert API calls into its own text, keeping only the calls that make the following words easier to predict, then fine-tunes on the result.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Architectures
  • Discrete math
  • Sign in to see your progress

TL;DR

Toolformer is a language model that learns to call external tools, such as a calculator, a search engine or a translator, by writing the calls into its own training text. The authors keep a call only if its result makes the next words easier to predict, then fine-tune the model on the augmented text. A 6.7B-parameter model trained this way beats a 175B model on several zero-shot benchmarks.

Where you'll see it: language-model agents that decide for themselves when a lookup or a calculation is worth making, and the self-supervised idea of filtering generated training data by its effect on the model's own loss.

The problem

The paper lists five limits of large language models that scaling alone only partly fixes: they cannot access up-to-date information, they hallucinate facts, they struggle with low-resource languages, they make arithmetic errors, and they have no awareness of the progression of time.

Tool use is an obvious fix. A calculator is exact where the model is approximate, and a search index knows what the model has not seen. The difficulty is that the paper says existing approaches either rely on large amounts of human annotation or limit tool use to task-specific settings. The authors also argue that what humans find useful may differ from what a model finds useful.

Key idea

Toolformer generates its own tool-use training data and checks it with the model's own prediction loss. The procedure has three steps:

  1. Sample. Given a few human-written examples of one API, the model proposes API calls at many positions in a large text corpus.
  2. Execute and filter. Run each call. Keep it only if inserting the call and its result lowers the loss on the tokens that follow, compared with no call and with a call that has no result.
  3. Fine-tune. Insert the surviving calls into the original text and train the model on the result with an ordinary language-modeling loss.

The picture is a student who writes margin notes in a textbook and keeps only the notes that made the next paragraph easier to understand. The text itself does not change, so the model keeps its general language ability while learning when to look things up.

The method

Linearized API calls

Each call is a pair c=(ac,ic)c = (a_c, i_c), where aca_c is the API name and ici_c is its input. Given a result rr, the paper writes the call without and with its result as

e(c)=\ltAPI\gt ac(ic) \lt/API\gt,e(c,r)=\ltAPI\gt ac(ic)→r \lt/API\gte(c) = \texttt{\lt API\gt}\, a_c(i_c)\, \texttt{\lt /API\gt}, \qquad e(c, r) = \texttt{\lt API\gt}\, a_c(i_c) \rightarrow r\, \texttt{\lt /API\gt}

In practice the special tokens are ordinary text sequences such as "[" and "]" and "->", so the vocabulary does not change. Each tool must take text in and return text out, which is the only interface requirement.

Sampling calls

For a text x=x1,…,xn\mathbf{x} = x_1, \dots, x_n and a prompt P(x)P(\mathbf{x}) with a few demonstrations, the model computes at each position ii the probability pip_i that it would begin an API call there. Positions with pip_i above a threshold τs\tau_s are kept, up to kk of them. At each kept position the model samples up to mm candidate calls, and calls that never close with the end token are discarded.

Executing and filtering

The filter is the core of the method. Let Li(z)L_i(\mathbf{z}) be the weighted cross-entropy loss over the tokens xi,…,xnx_i, \dots, x_n when the model is first shown the prefix z\mathbf{z}:

Li(z)=−∑j=inwj−i log⁡pM(xj∣z,x1:j−1)L_i(\mathbf{z}) = -\sum_{j=i}^{n} w_{j-i}\,\log p_M(x_j \mid \mathbf{z}, x_{1:j-1})

Two losses are compared:

Li+=Li(e(ci,ri)),Li−=min⁡(Li(ε), Li(e(ci,ε)))L_i^{+} = L_i(e(c_i, r_i)), \qquad L_i^{-} = \min\left(L_i(\varepsilon),\, L_i(e(c_i, \varepsilon))\right)

Here ε\varepsilon is the empty sequence. Li+L_i^{+} is the loss when the model sees the call and its result. Li−L_i^{-} is the better of two baselines: no call at all, or a call without its result. A call is kept when

Li−−Li+≥τfL_i^{-} - L_i^{+} \geq \tau_f

so the call must reduce the loss by at least τf\tau_f. The weights are wt=w~t/∑sw~sw_t = \tilde{w}_t / \sum_s \tilde{w}_s with w~t=max⁡(0, 1−0.2 t)\tilde{w}_t = \max(0,\, 1 - 0.2\,t), so tokens close to the call count most. The paper's Table 10 shows that high values of Li−−Li+L_i^{-} - L_i^{+} usually correspond to calls a person would judge useful, and low or negative values to calls that add nothing.

The result is inserted at position ii only after filtering. Before fine-tuning, the paper puts e(ci,ri)e(c_i, r_i) as a prefix during scoring rather than inline, because the unmodified model has never seen such text and an inline insertion would hurt its perplexity.

Fine-tuning and inference

The surviving calls are merged into the original text, giving x∗=x1:i−1,e(ci,ri),xi:n\mathbf{x}^{*} = x_{1:i-1}, e(c_i, r_i), x_{i:n}. The augmented corpus contains the same texts as the original apart from the inserted calls, so the model sees the same content. The model is fine-tuned with the standard language-modeling objective.

At inference the model decodes normally until it produces the "->" token, which signals that it expects a result. Decoding then pauses, the API is called, and the response and the closing token are inserted before decoding resumes.

Experimental setup

The base model is GPT-J with 6.7B parameters. The language-modeling corpus is a subset of CCNet. Heuristics pick texts likely to need each tool; for the calculator, only documents that contain a number that is the result of an operation on two others, an equation-like phrase such as "total of", or at least three numbers (a random 1% of those that match only the last criterion). Fine-tuning uses batch size 128, learning rate 1×10−51 \times 10^{-5} and linear warmup over the first 10% of training. Evaluation is zero-shot: the model is told the task in natural language and given no examples. At decoding the model may start a call whenever the call token is among its top k=10k=10 next tokens, and it may make at most one call per input.

Results

Every number below is from the paper's tables. The paper's comparisons use GPT-J (6.7B) against OPT (66B) and GPT-3 (175B).

Question answering over facts (LAMA, Table 3). Toolformer scores 33.8 on SQuAD, 11.5 on Google-RE and 53.5 on T-REx. GPT-3 scores 26.8, 7.0 and 39.8. The paper reports improvements of 11.7, 5.2 and 18.6 points over the best GPT-J baseline. The model calls the question-answering tool on 98.1% of examples.

Math (Table 4). On ASDiv, SVAMP and MAWPS, Toolformer scores 40.4, 29.4 and 44.0. GPT-3 scores 14.0, 10.0 and 19.8. With calls disabled, Toolformer still beats GPT-J (14.8 versus 7.5 on ASDiv), which the authors attribute to training on many examples of calls and their results. The calculator is used for 97.9% of examples.

Open-domain question answering (Table 5). Toolformer scores 26.3 on WebQS, 17.7 on Natural Questions and 48.8 on TriviaQA. GPT-3 scores 29.0, 22.6 and 65.9. The model relies on Wikipedia search for 99.3% of examples. The authors blame their simple search engine and the lack of any way to reformulate queries, and they name that as future work.

Multilingual QA (Table 6). Calls to the translation tool improve results in every language, and the tool is used for 63.8% to 94.9% of examples except Hindi, which is 7.3%. Toolformer does not consistently beat plain GPT-J, because further training on CCNet hurts some languages.

Dates (Table 7). On TempLAMA, Toolformer scores 16.3 against GPT-3's 15.5. The calendar tool is used for only 0.2% of those examples, so the gain comes from search and QA, not from knowing the date. On the authors' Dateset, which needs the current date, Toolformer scores 27.3 against 0.8 for GPT-3, and the calendar is used for 54.8% of examples. The paper credits the calendar for this gain.

Language modeling (Table 8). Perplexity on WikiText is 9.9 for GPT-J, 10.3 for GPT-J fine-tuned on CCNet, and 10.3 for Toolformer with calls disabled. On CCNet it is 10.6, 10.5 and 10.5. Adding calls does not cost perplexity on plain text.

Decoding threshold (Table 9). On T-REx, raising kk from 1 to 10 raises the fraction of examples with a call from 40.3% to 98.1%, and raises overall accuracy from 47.8 to 53.5. On WebQS the fraction goes from 8.5% to 100%, but accuracy stays at 26.3 from k=3k=3 onward.

Scale (Figure 4). The ability to use the tools appears at about 775M parameters. Smaller GPT-2 models score about the same with and without tools. The authors note a large gap between predictions with and without calls even for their largest model.

Why it mattered

The paper states what it changed. It shows that a language model can learn to use tools from a few demonstrations per tool, with no task-specific supervision and no loss of language-modeling quality. Its central result is that a 6.7B model with tools beats 175B GPT-3 on the authors' factual, math and temporal benchmarks, though not on open-domain QA. It also introduces the self-supervised filter: a generated training example is kept only when it reduces the model's own loss on future tokens.

The paper names its own limits. Tools are called independently, so the model cannot chain one tool's output into another, and no training example shows chained use. It cannot use a tool interactively, such as reformulating a failed search or browsing several results. It is often sensitive to the exact wording of its input when deciding whether to call a tool, and it is sample-inefficient for some tools: processing more than a million documents gives only a few thousand useful calculator calls. It also needs a few hand-written demonstrations per tool.

Reading guide

Read the paper in this order and use these lessons for the sections that need them.

  1. Introduction (Section 1): Language Model for what a language model predicts, and In-Context Learning for the few-shot prompts that generate the calls.
  2. Approach (Section 2): In-Context Learning for sampling calls from a prompt, Cross-Entropy Loss for the loss LiL_i and the filter, and Fine-Tuning for training on the augmented corpus. Autoregressive Model explains why the loss is taken over the following tokens.
  3. Tools (Section 3): no new prerequisites. The tools are ordinary functions with text in and text out, and the Calendar and Calculator need no background beyond the paper's text.
  4. Experiments (Section 4): Zero-Shot Learning for the evaluation setup and Transfer Learning for why a model pretrained on general text can be used on specific tasks. Retrieval-Augmented Generation is the closest related approach for the question-answering tool.
  5. Analysis and limitations (Sections 5 and 7): Self-Supervised Learning for the training signal behind the filter, and Subword Tokenization for why API names and results are read as ordinary tokens.

Check yourself

QuestionWhy does the filter compare the loss with the call against the minimum of two baselines, rather than against the loss without any call?Show answer
If the filter only compared against no call, a call that merely repeats the surrounding text would look useful, and so would any call whose result happened to share words with the next tokens. Comparing against a call with no result also controls for the call itself. The call must therefore help the model predict the next tokens because of what the tool returned, which is the thing the method is trying to learn.
QuestionSuppose the weighted loss over the next tokens is Li−=2.40L_i^{-} = 2.40 with no call and Li+=1.95L_i^{+} = 1.95 with the call and result. The filter threshold is τf=0.4\tau_f = 0.4. Is the call kept?Show answer
Compute Li−−Li+=2.40−1.95=0.45L_i^{-} - L_i^{+} = 2.40 - 1.95 = 0.45. Since 0.45≥0.40.45 \geq 0.4, the call is kept. The reduction in loss is larger than the threshold, so the call counts as helpful under the paper's rule.
QuestionOn the Dateset benchmark Toolformer scores 27.3 and GPT-3 scores 0.8, but on TempLAMA the calendar is used for only 0.2% of examples. What does this contrast show about how to read tool results?Show answer
It shows that a benchmark gain does not identify the tool that caused it. On Dateset the calendar is used for 54.8% of examples and the authors credit it for the gain, because the question depends on today's date. On TempLAMA the gain comes from search and question answering, because the named entities are so specific that the date alone would not help. The usage rates are needed before attributing a gain to a tool.
QuestionA team wants a model to answer a question that needs a search, then a calculation on the search result. Based on the paper's limitations, what should they expect?Show answer
The paper's Toolformer generates calls independently, and its training data contains no chained calls, so it is unlikely to use the output of the search as the input to the calculator. The team should either build the chain outside the model, or fine-tune on examples that include chained calls, which the paper does not test.

Sources

Read the full paper

Timo Schick, Jane Dwivedi-Yu, Roberto Dessì et al., 2023. arXiv:2302.04761