---
title: "How Do In-Context Examples Affect Compositional Generalization?"
description: "How the COFE benchmark tests which in-context examples help GPT systems interpret familiar words in unfamiliar grammatical combinations."
canonical: "https://research.elamur.ai/free/en/papers/an-2023-how-do-context-examples-affect/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/an-2023-how-do-context-examples-affect/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2023](https://md.research.elamur.ai/free/en/papers/2023/) / How Do In-Context Examples Affect Compositional Generalization?

# How Do In-Context Examples Affect Compositional Generalization?

Paper · 2023 · Shengnan An, Zeqi Lin, Qiang Fu et al.

**Authors:** [Shengnan An](https://md.research.elamur.ai/free/en/authors/shengnan-an/), [Zeqi Lin](https://md.research.elamur.ai/free/en/authors/zeqi-lin/), [Qiang Fu](https://md.research.elamur.ai/free/en/authors/qiang-fu/), [Bei Chen](https://md.research.elamur.ai/free/en/authors/bei-chen/), [Nanning Zheng](https://md.research.elamur.ai/free/en/authors/nanning-zheng/), [Jian-Guang Lou](https://md.research.elamur.ai/free/en/authors/jian-guang-lou/) and [Dongmei Zhang](https://md.research.elamur.ai/free/en/authors/dongmei-zhang/) · **Year:** 2023 · **Venue:** Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers) · **Licence:** [CC BY 4.0 (ACL Anthology)](https://creativecommons.org/licenses/by/4.0/)

[Cited by **32** papers in our library of the 163,136 papers whose bibliographies we read](https://md.research.elamur.ai/free/en/papers/an-2023-how-do-context-examples-affect/cited-by/) · Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers) · [licence](https://creativecommons.org/licenses/by/4.0/)

- [Publisher's page](https://aclanthology.org/2023.acl-long.618/)
- [PDF](https://aclanthology.org/2023.acl-long.618.pdf)
- [DOI 10.18653/v1/2023.acl-long.618](https://doi.org/10.18653/v1/2023.acl-long.618)

## Summary

A system can know what a word means and still misread it when it turns up in a new grammatical role. The same problem arises with whole phrases. Seeing a phrase such as *in a room* attached to the object of a sentence gives some evidence about how to interpret it when it attaches to the subject. Applying that evidence takes more than recognizing the words. The system has to preserve what the phrase means while changing what it describes. An and colleagues ask whether a handful of worked examples can support this kind of transfer, known as compositional generalization, and which examples make the transfer easier.

The authors build COFE from COGS, a benchmark for [semantic parsing](https://md.research.elamur.ai/free/en/concepts/semantic-parsing/). The task pairs a sentence with a formal expression that makes its meaning explicit. At test time, the system reads a prompt containing worked sentence–expression pairs, then writes the formal expression for a new sentence. The examples are selected for that sentence. They are intended to show its basic ingredients while withholding the particular combination under examination. The authors vary how closely the examples match parts of the test sentence’s structure, how often they repeat the same patterns, and how much structure each example contains.

Structural similarity gives the broadest improvement. Across the COFE test categories, code-davinci-002 rises from 60.9% average exact-match accuracy with primitive coverage alone to 75.6% when selection also rewards structural matches. The fine-tuned GPT2-Large baseline scores 42.2% on the same category average. With structural matching, code-davinci-002 reaches 99.8% when the task is to use a familiar word in a new grammatical role, but only 26.0% when it has to interpret deeply nested phrases. Selecting examples that repeat fewer relevant patterns or that are individually simpler helps most clearly on phrase recombination.

The authors also change what the examples make easy to recognize. Withholding the test sentence’s grammatical construction hurts even when examples can offer other ways to express similar meanings. Replacing recognizable words in the formal answers with invented strings hurts both whole-answer accuracy and a measure that checks the arrangement of structural punctuation alone. The experiments show that the choice of examples can change what a compositional test reveals. They also show that success with familiar words and closely related constructions gives limited evidence about how well the same system will transfer to unfamiliar labels or less familiar ways of organizing a sentence.

## Deep dive: How Do In-Context Examples Affect Compositional Generalization?

How the COFE benchmark tests which in-context examples help GPT systems interpret familiar words in unfamiliar grammatical combinations. · about 33 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### What counts as a new combination

A new sentence can be new in several ways. It may contain an unfamiliar word, or it may express a familiar idea through a grammatical construction the reader has rarely seen. The paper focuses on a more specific case. The basic pieces are available, and the required arrangement of those pieces is missing from the examples. A noun seen in one grammatical role has to be understood in another. An expression used to describe the object of a sentence has to be interpreted when it describes the subject. In the recursive cases, the reader must apply a familiar operation more times than any example shows.

To test this ability, the experiment has to make the missing combination identifiable. Encountering an unfamiliar sentence is insufficient evidence that a particular composition was new. Two sentences with different words can share the exact structure being tested. Conversely, the reuse of a noun or verb tells little about whether a demonstration shows the relevant use of that word. The authors draw the boundary through the grammar. They identify what the test case requires, use the example bank to supply its elementary pieces, and keep the designated combination out of the prompt.

Semantic parsing makes the consequence of a wrong combination visible. The answer represents which participants belong to an event, which phrases describe them, and how clauses or modifiers fit together. A response can mention every relevant noun and still be wrong if it attaches a location to the wrong participant. A sentence about one entity beside another can also contain a phrase locating the second entity, which creates a question about scope. A formal answer has to preserve these distinctions in its arrangement of functions and arguments. That requirement gives the authors a way to check the output for each sentence.

#### From training splits to prompts

The paper places COFE alongside SCAN, CFQ, and [COGS](https://md.research.elamur.ai/free/en/papers/kim-2020-cogs-compositional-generalization-challenge-based/), earlier benchmarks that reserve particular combinations for testing while supplying their components in training. The usual setup discussed by the authors uses [fine-tuning](https://md.research.elamur.ai/free/en/concepts/fine-tuning/). A system updates its parameters on a task’s training examples and then receives test inputs with combinations omitted during that task-specific training. The paper describes earlier work as finding that general-purpose neural systems frequently struggled on these splits. It also notes attempts to improve transfer through general-purpose changes and approaches designed specifically for the task. Earlier analyses identified such influences as length, the format of the formal answer, and gaps in the local structures available during training. [Compositional Generalization and Natural Language Variation](https://md.research.elamur.ai/free/en/papers/shaw-2021-compositional-generalization-natural-language-variation/)

In-context learning changes how task examples are supplied. A pretrained system reads worked cases alongside the query and generates its answer with its parameters fixed. In this form of [few-shot learning](https://md.research.elamur.ai/free/en/concepts/few-shot-learning/), the examples for a particular question can be selected from a much larger collection. The experimenter therefore has a choice that goes beyond the design of a training split. The example bank can contain a useful analogue for a sentence, yet the prompt can omit that analogue. It can also contain several distinct ways to support the answer, while the prompt spends much of its space on similar illustrations of the same rule.

This difference matters for interpreting a failed test. Suppose the relevant noun appears in the prompt, but the surrounding demonstrations give little guidance about the grammatical position it occupies in the new sentence. The system has seen the noun and has been asked to apply it in a withheld combination. Its failure still leaves open whether a different set of permitted examples would have helped. The authors make this variation part of the experiment. They look at the support the prompt provides between the level of individual words and the level of the withheld combination.

#### Why example selection needs more than a similarity score

The paper describes several ways earlier work had selected demonstrations. One approach compared sentence embeddings and used near neighbors. Another used a pretrained system’s conditional probabilities as a similarity signal. Other work trained a retriever or estimated how closely examples resembled the required answer on the formal side. These approaches offer different senses of relevance. An input can be close to a query because it discusses similar entities, because it shares a grammatical construction, or because its answer uses related formal operations. The paper singles out structural overlap because recombination requires the parts of an expression to be put into a new configuration. [What Makes Good In-Context Examples for GPT-3?](https://md.research.elamur.ai/free/en/papers/liu-2022-what-makes-good-context-examples/) [Constrained Language Models Yield Few-Shot Semantic Parsers](https://md.research.elamur.ai/free/en/papers/shin-2021-constrained-language-models-yield-few/) [Learning To Retrieve Prompts for In-Context Learning](https://md.research.elamur.ai/free/en/papers/rubin-2021-learning-retrieve-prompts-context-learning/)

The authors also distinguish finding a relevant example from building a useful collection. An example can qualify as relevant based on the test sentence alone. Whether it adds something to a prompt depends on what the other examples already show. If successive selections all have the same straightforward subject and verb pattern, the pattern may be well illustrated while other relevant material remains scarce. A measure that rewards new structural coverage can rank those candidates differently as the prompt fills up.

The amount of material inside each example raises another question. A long demonstration may provide useful guidance about how several operations fit together. It may also surround the relevant operation with extra material that the reader has to separate from the part that matters. This is distinct from repetition across examples. A collection can consist of individually short examples that all show the same pattern, or of individually complex examples that illustrate different patterns. The paper treats relevance to the query, repetition in the collection, and the depth of individual examples as influences that can be adjusted separately.

The introduction situates this investigation near work that used target-side fragments to select examples for COGS, and near a task-specific approach that organized compositional inference from simpler steps to harder ones. COFE takes a different experimental route through the question posed by those efforts. It uses the known structures of a benchmark to change the evidence available in the prompt, while keeping the general task of translating a sentence into a formal expression fixed.

### The method, step by step

#### Build a task from sentences and their meanings

COFE starts with COGS and retains the distinction between a bank of worked cases and cases reserved for testing. The bank is the COGS training set, which the paper calls `B`. Each bank entry contains a natural-language expression and its formal answer. For a test case, the experiment constructs a fresh collection of demonstrations from that bank. The study thus uses *context* to mean the worked pairs immediately preceding a particular query. The full bank is available to the selection procedure, while only the chosen pairs are available as demonstrations when the query is answered.

The authors change the form of the COGS answers before running the tests. They replace variables with the corresponding terminals, capitalize output words, and group the clauses into function-style expressions. A predicate can then take arguments occupying fixed positions for roles such as agent, theme, and recipient. `NONE` fills a position when the predicate has no participant in that role. The output convention gives the position of an argument a direct interpretation. Producing the right noun in a recipient position can still yield an incorrect answer if that noun belongs in the theme position.

The authors use different forms of composition for different constructions. Clausal complements can extend a chain, with `CCOMP` marking the connection. Prepositional modification can instead put a function inside another function. For instance, a locative expression may occupy one argument position of a predicate, and part of that locative expression may itself contain another location. Distinguishing these formats lets the authors test extension along a clause chain separately from expansion inside an argument. They remove the original notation for definite descriptions and omit Skolem constants. The resulting forms retain the distinctions the authors use to test participant roles, attachment, and ordering.

In ordinary COFE, there is a visible bridge between many input words and their formal counterparts. A word such as *cat* has the upper-case form `CAT` on the answer side. The punctuation and predicate–argument conventions still have to be learned from the demonstrations. Capitalization supplies a recognizable way to link the word to a formal terminal. The fictional-word experiment changes this bridge while keeping the source sentences and formal construction rules in place.

#### Decide what the examples must leave out

For each test case the authors identify an *aiming combination*, their term for the combination whose transfer is under examination. The prompt is supposed to meet two conditions. Its demonstrations must leave out that combination, and they should collectively show the case’s primitives. The paper mainly treats lexical items as primitives, such as a noun or a verb. A prompt can therefore show a word in one example and a useful configuration in another without showing the word used in that configuration.

The test categories specify what has to be withheld. In **Primitive Substitution**, or PrimSubs, the new combination pairs a familiar lexical item with a grammatical role. The paper gives the example of *shark* and subject position. A demonstration can show *shark* used elsewhere, and another can show a different noun serving as subject. The test asks whether that support is enough for the system to assign the familiar noun its new role.

In **Primitive Structural Alternation**, or PrimAlte, the novelty is the pairing of a word with a sentence construction. The paper uses *baked* to illustrate the sort of predicate whose use in a particular subject–verb–object arrangement may be held out. The relevant question is how the predicate participates in a construction. Evidence for the construction can come from examples built around other predicates, and evidence for the predicate can come from its use in another arrangement.

In **Phrase Recombination**, or PhraReco, a prepositional phrase is combined with a grammatical role. The opening illustration moves from examples in which a prepositional phrase modifies an object to a query in which the phrase modifies the subject. The transfer involves a phrase with its own internal structure. The system must interpret that structure and then attach the phrase in the right place in the larger answer.

**Longer Chain**, or LongChain, examines recursion through clauses. The operation that links a clause to a complement can recur along the formal expression. The paper gives a maximum of 2 recursive repetitions in the example bank and 12 in the test cases. The prompt shows the operation in shorter forms, and the test asks the system to keep applying it while preserving the content and order of the clauses.

**Deeper Nesting**, or DeepNest, uses the same reported repetition limits for recursive prepositional constructions. The recursion expands an argument of a function, as when an expression involving `IN`, `ON`, or `BESIDE` contains another expression of the same family. With each new level, the output must specify the local relation, the entity it applies to, and the correct location of that relation inside the larger expression. The paper calls the lexical-role and lexical-construction tasks low-level combinations and groups the other categories as high-level combinations.

#### Describe the evidence in a candidate

The experiment uses the underlying grammar to obtain a parse tree for each side of a case. A parse tree represents how an expression is built from parts. Its leaves carry lexical or other terminal material. Internal nodes identify units such as a subject, an object, or a clause and connect them to the parts that constitute them. A test tree and a candidate tree can share a fragment even if their full sentences are different. A general subject–verb–object pattern, for instance, can be present with different words and different structures inside the subject and object.

The paper describes a one-level fragment as a parent with its children. A more detailed fragment combines such local expansions. It can show how a grammatical slot and its contents participate in the larger expression. The fragments must be complete in the sense defined by the authors. If a fragment includes an internal node and descends to one of its children, it includes the other children of that node as well. It may stop at a lower node without expanding it. This rule preserves the group of children associated with a grammar expansion when that expansion is counted as evidence.

```
P(T) = Tᴸ
```

`T` is the parse tree of an expression. `P` is the operation that extracts the primitives used for comparison. `Tᴸ` denotes the leaf nodes of `T`, which supply those primitives.

```
S(T) = Tₛ¹ ∪ Tₛ⁾¹
```

`S` extracts the partial structures in tree `T`. `Tₛ¹` denotes the set of one-level fragments, and `Tₛ⁾¹` denotes the set of deeper fragments formed by joining local expansions. The raised `⁾¹` marks the paper’s greater-than-one class of fragments. `∪` takes the union of the sets. The paper also tracks internal-node coverage, denoted by `Tᴺ`, in its descriptive statistics. Coverage of internal-node labels and coverage of the structures those labels participate in are different quantities. A prompt can contain a subject, a verb, and an object somewhere without showing how they occur together in the query.

For selection on the recursive tasks, the implementation description caps the depth of deeper matchable fragments at 2. The candidates can supply a local instance of the operation from which a long structure is made. The ranking has no way to fill the bank with demonstrations of the entire extended structure demanded by the hardest queries. The held-out combination is also excluded from the candidates. Increasing similarity therefore increases the amount of permitted evidence for the query around the withheld part.

#### Rank candidates and form a prompt

How COFE selects demonstrations for a test sentence The steps in order.

The score starts with an overlap on primitives. A candidate can then gain credit for having parts of the test structure. When diversity is enabled, a fragment earns that credit only while it adds coverage to the context already selected. A signed term based on the candidate’s depth can favor either simpler or more complex examples. These adjustments make it possible to generate different versions of the benchmark without replacing the test with a different kind of language task.

```
Match(T, T′) = wₚ · |P(T) ∩ P(T′)| + wₛ · |(S(T) ∩ S(T′)) ∖ S(C)| − w꜀ · depth(T′)
```

`Match` is the tree-to-tree scoring function. `T` is the test tree and `T′` is the candidate tree. `P` gives the primitives and `S` gives the structural fragments. `C` is the collection of examples already selected, and `S(C)` contains the fragments that collection already covers. `∩` takes a set intersection, `∖` removes elements in the set that follows it, and the vertical bars count the elements left in a set. `wₚ` weights the primitive overlap, `wₛ` weights the structural overlap, and `w꜀` controls the effect of candidate depth. `depth(T′)` is the depth of the candidate tree, and `·` indicates multiplication. Omitting the set difference makes matching fragments eligible for credit even if an earlier example covers them.

Primitive matching is the first priority. The authors set its weight to 100. In the main structural-similarity condition, the structural weight is 1 and the complexity weight is 0. The condition scores both levels of fragment detail, with no deduction for fragments already represented. For the diversity condition, the authors keep the other settings and stop awarding structural credit for fragments already in the context. Thus diversity here means reduced repetition of particular structures relevant to the query. It can change which example wins a selection round even if the pool of candidates stays fixed.

In the complexity comparison, the depth weight is 0.01 to prefer simpler examples and −0.01 to prefer more complex ones. The sign matters because the expression subtracts the depth term. With a positive weight, depth lowers the score. With a negative weight, depth raises it. The authors describe the depth contribution as small enough to preserve the priority of structural overlap. In these comparisons they omit the adjustment for already covered fragments. Complexity therefore expresses a preference among candidates that provide comparable matching evidence under the earlier parts of the score.

```
score꜀ = Match(X, X꜀) + Match(Y, Y꜀)
```

`score꜀` is the overall score for candidate `c`. `X` and `Y` are the source and target trees for the test case, respectively. `X꜀` is the tree of the candidate sentence and `Y꜀` is the tree of the candidate’s formal answer. `Match` has the definition given above, and `+` adds the source-side and target-side contributions. The source side measures overlap in how the input is constructed. The target side measures overlap in how its meaning is formally represented.

This use of `Y` is possible because COFE is constructing controlled test prompts with access to annotated cases. The target tree helps select demonstrations. The system answering the query receives the worked examples and the test sentence. The study can therefore ask what happens when examples provide a certain kind of structural support, even when finding that support from an unannotated query would be a separate problem. The authors also test a version of the score that uses only the input side.

The procedure is greedy. It builds up the context one example at a time, scoring candidates against the test case and adding a highest-scoring eligible candidate at each step. Selection continues until there are 10 examples. In the diversity setting, the latest addition affects the structural credit available in the next round. Greedy selection makes a sequence of local decisions. The authors present the resulting contexts as a way to vary properties of the evidence, with the coverage statistics providing a check on what those choices actually achieved.

The prose and pseudocode agree on this sequential construction, but the appendix’s complexity line differs from the main scoring equation. The pseudocode writes the primitive weight on a source-tree depth term, whereas the main text uses the dedicated complexity weight and gives its signed settings. The definitions of the low- and high-complexity conditions above follow the main experimental description.

#### Arrange the examples and prepare the variants

The default arrangement places examples with stronger structural overlap closer to the query. Selection and placement are separate decisions. A candidate may be included because it is useful to the collection, then placed according to its structural score. The authors can assess the effect of order by reusing the selected examples and changing where they appear. They compare the default with a random arrangement and an arrangement that moves examples with more primitive overlap towards the query.

For the variant with less input-side support, the authors remove the source contribution from the score and enforce an additional constraint. The prompt must omit the sentence rule used by the test query. A sentence rule here is a grammar expansion whose left-hand side is the sentence category. Cases for which the constraint cannot be satisfied are filtered out, leaving 1,037 of the original 4,785 test cases. The procedure makes the contrast stronger than an ordinary switch from a two-sided score to a target-only one. It actively prevents an exact kind of input-side support.

The fictional-word variant keeps the ordinary sentence on the input side and replaces words in the formal expression with strings made by randomly sampling characters from the alphabet. A replacement has as many characters as the target word it replaces. For example, the normal label `CAT` can become `MXR`. The demonstrations use the altered vocabulary, so the contextual task includes recovering the correspondence as well as placing the resulting labels into the answer. The paper uses the primitive-closer order for this comparison. COFE itself is publicly available in the ContextualSP repository.

### Experiments and results

#### Data, systems, and scoring

The full COFE test suite contains 4,785 cases, and the bank contains 24,155 examples. PrimSubs contributes 1,100 test cases and PrimAlte contributes 700. There are 1,000 cases each for PhraReco and LongChain, and 985 for DeepNest. The counts matter when reading a category result. A PhraReco score describes performance on a test of phrase attachment, whereas a LongChain score describes performance on a separate collection featuring recursive clause extension.

The paper reports a coverage check for the full structural-similarity setting. Across the COFE test cases, the contexts cover 99.7% of the test leaves on average and 100% of the internal nodes. For the shallow structural fragments the reported coverage is 88.9%, and for the deeper fragments it is 49.3%. The lower fragment coverage is informative because even very high coverage of words and node labels can coexist with gaps in how those pieces fit together. Complete structural coverage would also violate the experimental design for a withheld combination.

The observed coverage of the recursive categories makes the boundary between the principle and its implementation visible. Leaf coverage is 99.8% for LongChain and 98.8% for DeepNest. The other categories each report 100% leaf coverage. The method strongly prioritizes lexical coverage, and the data show how closely the selected contexts approach that goal. They also leave a small fraction of uncovered material in the recursive categories by the paper’s measure. The bank and test sets differ in the amount of material found in a typical case. The reported average input and output lengths in the bank are 7.5 and 10.5. On the LongChain test set the corresponding means are 32.4 and 76.7.

The authors evaluate three davinci variants that respond to in-context demonstrations, namely code-davinci-002, text-davinci-002, and text-chat-davinci-002. The other systems in this part of the comparison are davinci, code-cushman-001, and code-cushman-002. All use temperature 0 and a maximum decoding length of 500. Temperature 0 is the greedy generation setting in the paper. At each decoding step the system chooses its preferred continuation, under the setting used for these experiments.

The comparison system is GPT2-Large, fine-tuned on the entire bank and then tested without worked examples in its input. The appendix gives its size as 762M parameters. Fine-tuning lasts 50,000 training steps with batch size 8 and a learning rate of 1e-5. The training setup uses weight decay of 1e-2 and label smoothing of 1e-1. At inference, it uses beam size 5 and a maximum length of 1,024. The beam keeps more than one candidate continuation under consideration. The baseline provides a comparison against learning the task from the bank through parameter updates, with a different system and decoding procedure.

The principal measure is exact-match accuracy. The generated formal answer must match the reference for the case. A misplaced noun, a wrong preposition, or an added layer of nesting can make the whole answer incorrect. This makes the score appropriate for checking whether the system completed the requested composition, while leaving open whether a wrong answer recovered substantial parts of it. The authors later use diagnostics that examine what is preserved within failures.

#### From lexical coverage to structural overlap

The first comparison concentrates on PrimSubs. The authors initially draw 10 examples subject to the primitive-coverage requirement, without favoring other properties. On PrimSubs, every prompted GPT system in that comparison falls behind the fine-tuned GPT2-Large baseline. For davinci, the authors report a 24.2% accuracy gap. They then prefer examples whose structures share more with the query. In that condition davinci scores 97.5% exact match on PrimSubs, compared with the baseline’s 93.6%. Code-davinci-002 reaches 99.8%.

The broader comparison asks whether the same preference helps with the other withheld combinations. In the chart, the primitive-only settings prioritize the words, and full structural matching also scores shallow and deeper fragments. Both are evaluated on COFE. The fine-tuned GPT2-Large reference result uses the same test categories.

COFE average exact-match accuracy with primitive coverage or structural matching Structural matching lifts average accuracy for each prompted system shown.

**The numbers**

| System or setting | exact-match accuracy % |
| --- | --- |
| Davinci, primitive coverage | 26.7 |
| Davinci, full structural matching | 44.0 |
| Text-davinci-002, primitive coverage | 48.6 |
| Text-davinci-002, full structural matching | 66.3 |
| Code-davinci-002, primitive coverage | 60.9 |
| Code-davinci-002, full structural matching (this paper) | 75.6 |
| Fine-tuned GPT2-Large | 42.2 |

The systems omitted from the chart show the same direction of change. Across COFE categories, text-chat-davinci-002 goes from 57.2% average exact-match accuracy under primitive coverage to 71.8% with structural matching. Code-cushman-002 moves from 38.8% to 61.1%, and code-cushman-001 moves from 32.0% to 47.6%. The table in the paper reports an increase for each category within each prompted system. The gains vary in size with both the system and the category.

Davinci shows why the category breakdown matters even when the average crosses the baseline. With full structural matching, it scores 95.4% exact match on PrimAlte, below the fine-tuned baseline’s 97.9%. On LongChain, davinci scores 13.4%, against the baseline’s 5.4%. An average can reflect improved transfer for some constructions alongside continuing difficulty for others. It also leaves the initial PrimSubs comparison easier to interpret on its own terms. The early result tests a particular kind of lexical transfer, while the average spans cases in which a whole phrase or a recursive operation must be recombined.

#### Where each kind of recombination stands

On PrimSubs and PrimAlte, the strongest prompted results approach the top of the exact-match scale. Code-davinci-002 with full structural overlap scores 99.8% on PrimSubs and 99.7% on PrimAlte. On the same categories, text-davinci-002 scores 99.7% and 99.4%. The fine-tuned baseline is already strong on both. In this setting, supplying relevant local structures with the familiar words gives several prompted systems much of the evidence necessary to apply a word in its new role or construction.

For PhraReco, the full-similarity score of code-davinci-002 is 65.3%, while the fine-tuned baseline reaches 14.0%. Text-chat-davinci-002 reaches 53.4% and text-davinci-002 reaches 39.4%. The task remains considerably harder than using a familiar word in a different slot. Transferring the phrase requires both forming its internal representation and putting it under the intended participant. The results are consistent with the paper’s decision to treat a phrase as a more substantial unit of recombination than a lexical item.

Code-davinci-002 scores 87.0% on LongChain with full structural matching, and text-chat-davinci-002 scores 87.7%. The baseline reaches 5.4% there. These are whole-category exact-match scores, so a high value means many outputs reproduce the entire reference for a test designed around extension beyond the demonstrations. The scores pool cases within the category. They give no separate estimate for questions at the maximum recursion described in the grammar.

DeepNest produces much lower exact-match results. With full structural matching, code-davinci-002 reaches 26.0%, text-chat-davinci-002 reaches 18.9%, and the fine-tuned baseline scores 0.0%. Code-cushman-002 reaches 15.1%. The contrast with LongChain is especially relevant because both involve repeated application of a grammatical rule. A result on clause-chain extension cannot stand in for performance on recursive prepositional attachment. The form of the recursion matters for what the system must preserve as it proceeds.

The paper’s appendix includes an assembly of the best results observed under the settings tested for each category. For code-davinci-002 the assembled average is 78.7%. Its PhraReco entry is 80.0% and its DeepNest entry is 26.2%. These entries summarize the best category outcomes available across the comparisons. The assembled average consequently describes what was attained by choosing settings category by category. The full-similarity average in the earlier chart describes one specified selection policy applied across the categories.

### What the ablations show

#### How much structural detail helps

The comparison between primitive coverage and full similarity establishes that structural matching can improve results while the examples still respect the intended holdout. The authors next remove deeper fragments from the structural score. Selection can still favor one-level expansions, so candidates retain some of the test sentence’s local organization. The change removes the incentive to prefer examples whose adjacent grammatical parts combine in a more precise way.

In the reported detailed comparison, both code-davinci-002 and text-davinci-002 lose accuracy on PrimSubs, PrimAlte, LongChain, and DeepNest when matching is restricted to shallow fragments. For code-davinci-002, LongChain is at 80.4% exact match with rough similarity and 87.0% with full similarity. DeepNest is at 18.3% and 26.0%, respectively. The additional fragments supply information about how local expansions fit together. On the recursive categories, matching such a fragment is compatible with withholding the longer or deeper construction. The evidence concerns how to join several parts at a time, while the query still requires continuing the operation.

PhraReco reverses that pattern. With code-davinci-002, rough matching reaches 77.6%, compared with 65.3% for full matching under the default settings. Text-davinci-002 scores 55.9% with rough matching and 39.4% with the full score. The exception qualifies the broad gains over lexical coverage. A more precise selection criterion can change which demonstrations compete successfully for a limited number of places. It can favor examples that repeatedly realize the same local configuration, or examples whose deeper structure comes with other material.

#### What changes when repetitions or depth are penalized

The diversity experiment continues to reward overlap with the query. It changes which overlap can earn credit after a pattern has been demonstrated. An illustration in the paper uses a test sentence about a girl situated in a house who slept. In the lower-diversity prompt, the subject-and-sleeping pattern is repeated. In the higher-diversity prompt it occurs once, leaving the context to present the relevant evidence in a different mixture. The system gives the correct formal answer in the latter case. This example shows an effect of repetition in the sense the scoring rule measures, where examples can share a pattern without repeating the same words throughout.

In the complexity experiment, the authors use the depth preference in either direction while preserving the structural match as the stronger criterion. A demonstration can have the desired local piece in a short tree or inside a larger construction. The paper gives an example in which short, simple demonstrations support the correct PhraReco answer, while a context built from longer, deeper demonstrations precedes an incorrect answer. This illustrates why the part of an example that matters to the query can be easier to recognize when there is less material around it.

The controlled coverage comparison makes these results easier to interpret. For PhraReco, the full-similarity default, the high-diversity variant, and both complexity variants all have 100% average coverage of leaves and 100% of internal nodes. Shallow-fragment coverage is 84.4%, and deeper-fragment coverage is 19.8%, in each of those settings. The figures describe the kinds of elements present at least once according to the paper’s coverage measures. They allow the comparisons to focus on arrangements of examples that change repetition or depth while preserving the reported aggregate coverage.

Code-davinci-002 exact-match accuracy on COFE Phrase Recombination With structural coverage held steady in the reported statistics, rewarding diversity or preferring simpler examples improves on the default.

**The numbers**

| System or setting | exact-match accuracy % |
| --- | --- |
| Full similarity, default selection | 65.3 |
| Full similarity, higher diversity (this paper) | 80.0 |
| Full similarity, lower complexity | 67.6 |
| Full similarity, higher complexity | 56.9 |

The complexity comparison is most directly read between its low- and high-complexity ends. The paper describes the improvement for PhraReco as ∼10% in accuracy when it moves from the high-complexity setting to the low-complexity one. In the chart, the default retains structural matching without a depth preference. The diversity setting has a different intervention. Its larger PhraReco score for code-davinci-002 comes from changing how often a matched structure can earn credit in the selection process.

The recursive categories show much smaller changes when the authors adjust diversity or complexity. A broader set of short demonstrations can still leave the system to extrapolate beyond the range any demonstration reaches. The authors interpret the weaker effects on LongChain and DeepNest in terms of this length gap. On PhraReco, the available examples can directly illustrate relevant structures that are distributed differently across the prompt. On the recursive tasks, the selection variants vary the evidence within a bank whose examples remain much shallower or shorter than the hardest queries.

#### Which side of an example matters

The input-side comparison asks whether pretraining and target-side examples are enough when the prompt omits the exact sentence rule needed by the query. The authors report lower exact-match accuracy across the categories in the variant that limits this support. The stated intervention has two parts. The ranking ceases to reward matching on the input side, and the eligible contexts must leave out the query’s sentence rule. The result concerns the availability of that linguistic construction in the prompt, instead of the effect of a single coefficient considered in isolation.

The paper illustrates the problem with a sentence in which Matthew sends a chair to a professor. The test expresses the recipient and the thing transferred as successive noun phrases. A context without that construction includes a related sentence pattern that uses a phrase introduced by *to* for the recipient. In the reported case, the answer is correct when the prompt includes the query’s arrangement. With only the related arrangement, the proposed formal analysis confuses the participant roles. This shows how a system can have evidence for the intended event and still misread the form that introduces its arguments.

The reverse intervention gives a different result. The authors remove the target-side term from candidate scoring while retaining source-side matching. For code-davinci-002, the COFE category average is 75.6% exact match with both sides and 75.4% with only the source side. For code-cushman-002 those averages are 61.1% and 61.6%. The aggregate similarity allows movement on individual categories. For example, code-davinci-002 scores 65.3% on PhraReco when both terms are present and 63.2% when only the source term is present. On LongChain the corresponding scores are 87.0% and 88.9%.

The source-only experiment still has formal answers in the demonstrations. What disappears is the use of the reference target tree in ranking candidates. The authors suggest that source matching can provide indirect target matching on this benchmark because multiple rules or terminals in the source grammar can map to the same element in the target grammar. Choosing candidates that preserve parts of the input structure can therefore bring related answer structures into the prompt. Their explanation is tied to COFE’s mapping and its deliberately withheld combinations. The paper contrasts this observation with earlier work that had found target-side similarity important in code generation.

#### What changes when the answer vocabulary is unfamiliar

In ordinary COFE a system can use the visual relationship between a source word and its upper-case counterpart. In the alternate setting it encounters arbitrary strings in the formal outputs. The supplied cases teach the task with these new labels. The exact-match result drops substantially. If errors in copying or recalling those labels were the only consequence, a comparison of structural punctuation could still show that the system had built an otherwise correct expression.

The authors make that comparison by retaining structural terminals such as commas and parentheses and evaluating the resulting form. Accuracy on this structural diagnostic also declines with fictional words. In one case illustrated in the paper, the answer misses labels corresponding to source words and has a nesting depth of 2 where the reference has a depth of 3. The formal grammar permits the normal answer with the fictional labels substituted. The error shows that changing the labels can affect the generation of the containing structure as well as the labels themselves.

The experiment thus probes a different dependency from the input-side comparison. The sentence can retain a familiar arrangement while its answer vocabulary becomes harder to recognize. The punctuation diagnostic checks one consequence of that change. A system may appear to handle the grammar more reliably under the ordinary lexical convention than it does when the mapping must be recovered from examples containing arbitrary targets.

#### Prompt placement and the anatomy of a failed answer

The authors compare alternate orders for the selected demonstrations in the full-similarity setting. One arrangement places stronger structural matches close to the query. Another prioritizes proximity for examples that match more primitives. A third uses a random order. This comparison responds to earlier work showing that where examples sit in a prompt can change few-shot performance. [Fantastically Ordered Prompts and Where to Find Them](https://md.research.elamur.ai/free/en/papers/lu-2022-fantastically-ordered-prompts-where-find/) [Calibrate Before Use](https://md.research.elamur.ai/free/en/papers/zhao-2021-calibrate-before-use-improving-few/)

For code-davinci-002, the COFE category averages are 75.6% in the structure-closer order, 74.2% in the primitive-closer order, and 74.5% with random placement. Text-davinci-002 has 66.3%, 66.0%, and 66.3% in those settings. The paper’s reported maximum differences range from 0.3 for text-davinci-002 to 1.5 for davinci on the average exact-match measure. The results indicate that the principal observations survive these changes in placement for the selected contexts. This check varies the order of the content that has already been chosen, a narrower change than drawing a fresh set of examples.

The analysis of DeepNest looks inside wrong answers. A prediction can approximate the general pattern of nested calls but use the wrong preposition at a level, place a word under the wrong operation, or add an extra component. One of the paper’s examples retains much of the sequence of entities while changing several local spatial relations and introducing redundant material. Exact match counts this as a failure, as it should for a formal representation whose interpretation depends on those local choices.

In the paper’s word-coverage diagnostic, code-davinci-002’s DeepNest predictions contain 96.8% of the reference words, while the GPT2-Large predictions contain 48.8%. This diagnostic counts the presence of words from the reference. It leaves their positions and the presence of redundant words to other checks. The authors infer that errors in the position and use of words account for much of the low exact-match accuracy of code-davinci-002 on DeepNest. The examples of incorrect local relations support that reading. They also make clear how much work remains after the system has generated a plausible overall shape.

### Limitations

#### Limits the authors identify

COFE uses synthetic data derived from COGS. The authors point to an estimate that the source-side constructions account for 70–80% of naturally occurring English sentences. They use that estimate to motivate the practical relevance of the grammar. It concerns the coverage of sentence structures, while COFE accuracy concerns prompts, formal meanings, and held-out combinations on the synthetic test. The estimate supplies no measurement of accuracy on naturally collected sentences. It also leaves the handling of natural lexical variation and alternative formal representations outside the tested setting.

Computing requirements limit repetition of the experiments. The authors report an 8 x NVIDIA A100 GPU setup and a maximum inference time of ∼ 8 hours for a COFE version containing 4,785 cases. Their maximum estimate for the study is ∼ 500 x 8 GPU hours. They say they did not run the same conditions repeatedly with different sets of examples or draw multiple outputs at temperatures above 0. The comparisons use the runs and choices described in the paper, leaving variation across independent draws unmeasured. Consistency across systems and the small prompt-order changes address aspects of robustness, but they do not quantify the run-to-run variability that repeated draws could reveal.

The authors identify knowledge of the grammar as a barrier to using the method outside COFE. In the benchmark, the selector can see the structures whose coverage the experiment tries to manipulate. With ordinary queries, those structures must be estimated in some way. The authors propose obtaining parse trees from a pretrained parser or using embeddings trained to reflect structural distinctions. These are directions for taking the experimental lesson beyond the benchmark. The paper’s results measure selection based on the known structure, so they leave open how much of the effect each proposed approximation would preserve.

The authors also identify two limits of the behavior they observe. Familiar surface labels support performance more strongly than arbitrary strings in their fictional-word test, and matching the linguistic construction of the input remains important even after pretraining. Each conclusion has a concrete interpretation within the test. The first concerns replacing answer-side words with random characters. The second concerns selecting contexts that explicitly omit the test sentence’s rule. The results give reason to qualify how widely good performance with the standard COFE prompts should be taken to apply.

#### Additional limits of the experimental comparison

The comparison with GPT2-Large combines several differences. The baseline learns through parameter updates across the entire bank. The prompted systems are different pretrained systems and see a small, query-specific selection at inference time. Decoding differs too. The comparison establishes how the tested setups perform on the same tasks. It cannot isolate the contribution of parameter updates, system size, or pretraining. The closest evidence on the causal role of the prompt comes from changing selection rules while evaluating the same system on the same category.

The designated combination is withheld from task demonstrations. The experiment has no corresponding control that excludes every relevant expression from pretraining. Familiar word meanings and grammatical patterns can therefore contribute alongside what readers infer from the worked cases. The fictional-word intervention weakens a specific lexical bridge on the target side and is informative about that bridge. It simultaneously makes the target labels unfamiliar and removes the direct visual correspondence with input words. The accuracy drop cannot identify how much each of those changes contributes, or infer the effect of making the input vocabulary unfamiliar.

Some of the closest comparisons preserve aggregate coverage while still changing the examples. For PhraReco, identical group-level coverage rates help rule out a simple explanation in which one condition wins because it covers substantially more material by the reported measures. Those rates do not identify which fragment was most informative on an individual query, or separate tree depth from all other differences among the examples selected. Likewise, the input-side ablation changes the scoring rule and restricts the test subset to cases for which the authors can construct contexts under the added constraint. It gives a controlled test of withholding a sentence rule on that subset. The full-suite accuracy figures answer a different question.

Exact match is exacting by design. The formal answer represents multiple decisions about words, roles, and recursive structure, all of which can affect meaning. A small local error can therefore yield the same case score as a substantially wrong analysis. The paper’s structural-punctuation and word-coverage measures address different parts of this problem, but neither is a complete semantic assessment of a partially correct answer. Punctuation alone does not locate the attachment of a particular noun, and word coverage alone does not establish who did what. Interpreting the results requires keeping these diagnostics tied to the properties they actually measure.

Finally, the data support a narrower conclusion about higher diversity and lower complexity than about structural similarity. The strongest diversity and complexity evidence comes from phrase recombination, and diversity is measured as repetition of relevant grammar fragments. Complexity is represented by parse-tree depth. A different task could make longer demonstrations useful because they show how several steps interact, or reward repetition of evidence that is hard to recognize. COFE isolates a case in which the underlined issue is how a familiar structure is presented around a withheld combination. It does not establish a universal rule for filling prompts.

### What came after

The later citing work approaches generalization through several different questions. One surveys how systems make use of examples in a prompt. Another evaluates deductive reasoning on cases designed to be outside the usual distribution. A third places the emphasis on foresight in strategic reasoning. The citation establishes a connection to the paper. The details available for these works give different amounts of evidence about how directly they use COFE’s method.

[A Survey on In-context Learning](https://md.research.elamur.ai/free/en/papers/dong-2023-survey-context-learning/) addresses the wider research area to which COFE belongs. The connection is the choice of examples as part of an in-context task. COFE contributes a specific case to that subject by distinguishing the relevance of an example to the query from the diversity of the examples as a group and the complexity of each example. The bibliographic record identifies the work as a survey and establishes that it cites the paper. It leaves open how the survey classifies COFE or which findings it discusses in detail.

[Testing General Deductive Reasoning with OOD Examples](https://md.research.elamur.ai/free/en/papers/saparov-2023-testing-general-deductive-reasoning-capacity/) applies the question of generalization to deduction. Its stated evaluation uses out-of-distribution examples to test the generality of deductive performance. The conceptual connection is the importance of specifying what familiarity with the test might buy. In COFE, the challenge comes from withholding a word–role pairing, a phrase attachment, or a more extensive recursive structure from the examples. In a deductive test, the title identifies inference on atypical cases as the target. The citation does not establish that the deduction study uses COFE’s grammar, its held-out categories, or its demonstration-selection score.

[Foresight Optimization for Strategic Reasoning](https://md.research.elamur.ai/free/en/papers/wang-2026-foresight-optimization-strategic-reasoning-large/) takes up another kind of reasoning and identifies foresight optimization as its approach. Its citation places COFE in the background of work on strategic reasoning. COFE asks what can be inferred from examples that provide the necessary ingredients while leaving a particular composition to be worked out. A strategic reasoning study raises a different problem about how a system reasons ahead. The citation alone supplies no detail about whether the later work adopts structural matching, varies the examples in a prompt, or uses the earlier findings to motivate its evaluation.

## Cite

Cite as Shengnan An, Zeqi Lin, Qiang Fu, Bei Chen, Nanning Zheng, Jian-Guang Lou and Dongmei Zhang. 2023. How Do In-Context Examples Affect Compositional Generalization?. Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers).

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.18653/v1/2023.acl-long.618](https://doi.org/10.18653/v1/2023.acl-long.618)

```bibtex
@inproceedings{an2023how,
  title = {{How Do In-Context Examples Affect Compositional Generalization?}},
  author = {Shengnan An, Zeqi Lin, Qiang Fu, Bei Chen, Nanning Zheng, Jian-Guang Lou and Dongmei Zhang},
  booktitle = {Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)},
  year = {2023},
  doi = {10.18653/v1/2023.acl-long.618},
  url = {https://doi.org/10.18653/v1/2023.acl-long.618}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
