Elamur Research

Leveraging Code to Improve In-Context Learning for Semantic Parsing

Paper · 2024 · Ben Bogin, Shivanshu Gupta, Peter Clark et al.

Summary

A calendar assistant has to do more than recognize that someone wants a meeting. It has to determine who should attend, resolve references such as “my team,” and translate the requested date and time into operations the calendar can perform. Semantic parsing turns a request like this into a structured representation that a computer can use. In the setting studied by Bogin and colleagues, that representation is a program. A few worked examples may show how to create an event, while leaving the parser to infer how an unfamiliar programming language expresses a team lookup or combines it with a scheduling operation.

The authors change what the parser is asked to write and what it knows about the system it is writing for. They replace the original domain-specific language with a general-purpose language such as Python. They also put a structured domain description in the prompt, where it declares available objects, fields, methods, and types. The description supplies local knowledge, such as which method finds someone’s manager. Familiar programming constructs supply other operations, such as filtering a collection or selecting the item with the greatest value. A small set of request–program examples shows how to bring these pieces together.

The study covers geography questions in GeoQuery, social-network questions in Overnight, and calendar requests in SMCalFlow. The researchers run the generated programs and check their answers or effects against those of reference programs. In the ChatGPT test comparison using 10 demonstrations, execution accuracy on the GeoQuery length split rises from 31.0% with FunQL and no description to 80.7% with Python and the full description. On SMCalFlow’s compositional 0-C test split, the corresponding configurations score 7.3% and 66.7%. These harder splits ask the parser to produce programs with properties or combinations that the training split withholds. The Python setup narrows the differences between random and compositional splits, although the size of the remaining gap varies.

The comparisons also show where the gain comes from and where the explanation remains open. On the main ChatGPT tests, Python improves execution accuracy even without a description. A list of operator names can supply much of the benefit of documentation on some splits, while detailed interfaces help more on others. Scala and JavaScript are competitive in spite of very different shares of the code corpus used as a reference for language prevalence. A redesigned version of the calendar language also approaches general-purpose code on one split when given a description. The evidence favors giving the parser familiar ways to express a program and explicit information about the domain. The experiments leave open how much of the improvement depends on specific language features or prior exposure to similar code.

Deep dive: Leveraging Code to Improve In-Context Learning for Semantic Parsing

Bogin and colleagues test how Python and descriptions of domain interfaces improve semantic parsing from a small set of examples. · about 34 minutes to read

The problem and its context

A request has to become an operation

The work concerns requests whose meaning can be checked against an environment. A geography question might call for finding a river, identifying the states it crosses, and returning those states. The answer has to come from the geography database. A calendar instruction calls for a change to the environment, such as the creation of an event with the appropriate participants and time. In both cases, the program is the bridge from the wording of the request to the data or state change that satisfies it.

A domain-specific language, or DSL, gives that bridge a vocabulary tailored to its destination. In GeoQuery’s FunQL, for instance, there are dedicated operations for identifying entities, traversing geographic relationships, counting results, and selecting extremes. These operations can express a complex question compactly. Their conventions still have to be learned. An operation that looks like ordinary English may expect a particular kind of collection, return a particular kind of entity, or require a surrounding expression. The utterance alone rarely provides those details.

The authors illustrate the problem with a question about which state has the most major cities. In FunQL, the operation most is useful when the program arranges the relevant items in the form that the operator expects. A demonstration about the largest state or the longest river does little to explain that convention. Python makes another route available. The program can filter a state’s cities, count the cities that pass the filter, and use the count to choose a state. The data still have to identify which cities belong to each state and which qualify as major. What changes is how the program expresses the computation over those data. Code & programming languages

The distinction applies to actions as well as queries. Take a request to put a meeting on the calendar for someone’s manager. The parser needs to connect the possessive phrase to a specific person, obtain the manager through an organizational relationship, and use the result as a meeting participant. It also needs to know how the calendar represents the event and its time. Ordinary programming constructs can carry the result of the lookup into the event creation call. The interface has to tell the parser which lookup and calendar operations exist. Dialogue systems

Why examples can leave gaps

The paper situates the work between fine-tuning and in-context learning. Fine-tuning updates the parameters of a pretrained system using task data. In semantic parsing, that data commonly consists of utterances paired with programs in the task’s formalism. The authors emphasize the effort involved in producing a substantial set of such pairs. They also describe earlier findings that training on more examples or increasing system size can leave pronounced difficulties with new program structures. Work they cite explored specialized architectures, augmentation that recombines existing material, and selection of training examples for structural diversity. Span-based semantic parsing · Good-Enough Compositional Data Augmentation

In-context learning conveys the task in the input. The prompt includes solved requests followed by the new request to solve. The demonstrations show how the output is written and how program fragments correspond to language. They can do so without a task-specific parameter update. That makes prompting attractive where annotations are scarce. It also gives each example several jobs. A solved request may have to teach the target syntax, introduce operations and constants, show which operation corresponds to a phrase, and illustrate how a result is returned. With only a small set of examples, entire parts of the interface can go unmentioned. Few-shot learning · Language Models are Few-Shot Learners

One line of prior work tried to make the demonstrations more informative. An example selector can seek requests that resemble the current input or choose examples whose programs collectively cover a wider range of structures. The paper describes this as a useful approach when there is a substantial annotated collection to search. A user who has only the examples that will fit in the prompt cannot count on drawing a more suitable set for a particular question. The authors call their primary resource setting true few-shot learning to emphasize that the task should be specified with a small fixed set rather than relying on retrieval from a large labeled collection. In-context example selection · Diverse Demonstrations

Other work approached the difficulty through the output representation. The paper describes efforts to simplify meaning representations, substitute synthetic natural-language formulations, or include the grammar of the target language in a prompt. It also cites earlier use of Python for virtual-assistant requests. Work on code prompting had already explored arithmetic and commonsense tasks. The authors’ question is how to make use of code when the desired output is itself an executable program, and how to distinguish the benefits of the programming language from those of the information supplied about the domain. Constrained few-shot semantic parsers · Code and few-shot commonsense learning

What has to generalize

Compositional generalization concerns what happens when familiar pieces have to be assembled in a way that the demonstrations or training data do not illustrate. In the calendar task, examples of finding a person’s manager and examples of creating an event can both be available, even though no training example shows how to create an event involving the manager. The required knowledge is distributed across the input, the interface, and the examples. A successful program has to put it together in the appropriate order and preserve the intended relationships as it goes.

A random split can include an unfamiliar structure by chance. Its construction does not deliberately keep particular combinations apart. A compositional split makes that separation part of the design. Depending on the benchmark, it may withhold templates, change which structures are represented together, or test longer programs. Earlier work cited by the paper uses these distinctions to examine what a test score establishes about generalization. They matter here because a representation can be easy to imitate on familiar examples and difficult to use when the relevant operation or arrangement is missing from the prompt. Text-to-SQL evaluation methodology · Compositional generalization and natural language variation

The experiment therefore has to preserve the underlying request while changing the form of its solution. If a representation gives the parser a shorter route through a particular task, that route is part of what the study measures. The outcome is still judged against the reference answer or event. This makes it possible to ask whether a parser can carry out the same work with a different division between general programming knowledge and domain-specific knowledge.

The method, step by step

Define what the program must accomplish

The formal setup starts with a request (x) and an environment (e). The request is the natural-language input. The environment holds the relevant data and exposes operations that can read or modify it. The parser supplies a program (z). For an information request, running the program should return the correct answer (y). For an action request, running it should make the requested change in (e). The appropriate behavior is therefore conditional on the kind of request. A list of states is a result to return, while an event is a change to create.

The authors assume access to the operators and formal conventions that the environment supports. The labeled examples available to specify the task are expressed as follows.

{(xᵢ, zᵢ)}ᵏᵢ₌₁

The braces enclose the collection of demonstrations. Each parenthesized pair associates the utterance (xᵢ) with its solution program (zᵢ). The subscript (i) identifies a demonstration, and the bounds indicate that the index runs from the first demonstration through the last. The symbol (k) is the number of demonstrations.

k ≤ 10

Here (k) retains its meaning as the demonstration count, and the inequality gives the upper bound of 10 in the primary few-shot setup. The assumption excludes access to other task examples for selecting the fixed prompt in this setting. The paper also runs separate experiments with larger prompts and with selection from a larger annotated pool. Those experiments address how the approach behaves when the resource assumption changes.

From an utterance to a checked program outcome

The steps in order.

From an utterance to a checked program outcomeStep 1: Define the domain interface1. Define the domain interfaceStep 2: Prepare verified request–program examples2. Prepare verified request–program examplesStep 3: Add the interface description when used3. Add the interface description when usedStep 4: Append demonstrations and the new request4. Append demonstrations and the new requestStep 5: Generate the program in the target language5. Generate the program in the target languageStep 6: Execute it in the benchmark environment6. Execute it in the benchmark environmentStep 7: Compare the answer or event with the reference7. Compare the answer or event with the reference

Build the interface and describe it in the prompt

The Python environments begin with an inventory of what programs in the original language have to accomplish. The authors inspect those programs to identify the types of entities that must be represented, the properties they need, and the operations that act on them. They then implement an interface that provides this functionality in Python and retain existing names for properties and constants where practical. Keeping those names reduces a source of variation. A gain from changing the representation is easier to interpret when the names of domain concepts remain recognizable across the formats.

An interface declaration gives the parser a map of what it can use. In the calendar description, a person has a name and exposes methods for finding a manager, a team, or direct reports. An event has fields for attendees, location, timing, and other properties. A method signature can show whether an operation takes a person’s name as text, expects an event object, or returns a list of people. These distinctions matter when composing calls. A returned list can fill an attendees field directly in a way that a lone person might not, even when both values concern the same people in the user’s request.

The authors call the prompt prefix that contains these declarations the domain description, abbreviated DD. For a general-purpose language, the full version includes definitions of objects, methods, fields, and constants. It leaves method bodies out. The reader of the prompt sees how to call an operation and what sort of result to expect, while the implementation lives in the executable environment. This lets the prompt describe a fairly broad interface without also reproducing the code that implements it.

A declaration can support a combination that the solved examples never show. Suppose the prompt contains a meeting example with a named attendee and another example that uses an organizational lookup. A description of the manager method and the event fields tells the parser how values can pass between these operations. The worked examples still matter, since the method signature alone does not explain how a phrase such as “my team” relates to the current calendar user. The design gives the example and the declaration different information to convey.

The original domain languages also receive descriptions. The authors write these by hand from the existing environments. The usual form lists the operators and explains allowable inputs and outputs in natural language. For FunQL they test a second form with signatures written in a Python-like style. A FunQL program still has to follow FunQL conventions when the accompanying documentation takes this form. That comparison helps test whether writing documentation as code is sufficient to account for the gains from requesting Python output.

The authors prepare shorter alternatives as well. The operator-list condition supplies names without the complete signatures or typing information. The Python condition described as “DD w/o typing” retains the shape of the fuller declarations and removes type information. These are changes to what the parser sees. The operations in the runtime remain available even if they are absent from the prompt or are only named there. This separation lets the experiment examine what explicit documentation contributes over whatever can be inferred from examples and prior knowledge.

Make the same tasks runnable in their new form

GeoQuery’s original FunQL programs run using a Prolog-based system through SWI-Prolog. The authors implement a Python interface to the GeoBase data, with code to load the database and operations for querying it. The geography entities expose relationships and properties such as the cities in a state or the path of a river. Having these relationships as attributes lets a Python program combine domain data with ordinary selection and filtering.

One example in the paper asks for the elevation of the highest point in the largest state. The FunQL solution represents the question as nested operations. The outer part returns an elevation, and the inner parts determine which place and state that elevation is about. The Python example first assigns the largest state to a variable and then reads the elevation through that state’s high-point property. Both programs can return the same number. The Python version places the state selection and the property lookup in forms that also occur outside geographic applications.

For Overnight, the authors work with the social-network domain. They export the entities from Sempre, the system used to execute the original λ-DCS queries, and build the Python environment over those entities. The data include people and information about their education, employment, and relationships. A conjunction about a person’s birth date and gender can be expressed in λ-DCS with nested filters. In Python, a program can filter the collection of people by one property and then filter the result by the other. The paper also illustrates a more demanding case that compares dates in education records with dates in a named person’s employment records. That program has to identify the right collections and compare values across them.

SMCalFlow uses a different route to execution. The paper’s Dataflow interpreter path simplifies original Dataflow programs into Dataflow-Simple before executing them. The Python interface also leads to Dataflow-Simple. A Python domain operation constructs a corresponding fragment of an abstract syntax tree, which represents the parts of the program and how they are nested. For example, the Python manager lookup yields a fragment representing Dataflow-Simple’s manager lookup. The translation is deterministic. The resulting program can then be executed using the same underlying Dataflow-Simple machinery.

This design allows Python and the original calendar language to reach the same event backend through different front ends. In a request to arrange an event at a named location on Friday, a Python program can supply the location and starting time when constructing an event. The simplified calendar language can express those details as event clauses. The environment then has to interpret the date and location and create the resulting event. The execution comparison is about that outcome, while the language comparison is about which instructions the parser can supply successfully.

Prepare verified examples, then prompt the parser

The benchmarks already have reference programs in their original formalisms. The experiments need corresponding Python demonstrations. The authors manually translate 2-10 examples to start a pool of verified Python annotations. They then sample from that pool and combine those examples with the Python domain description to prompt gpt-3.5-turbo or gpt-4 to annotate further requests. A generated program joins the pool only if it passes the task’s execution-based check. The resulting collections contain 824 annotated programs for GeoQuery, 128 for SMCalFlow, and 60 for Overnight.

The check tests whether the proposed example works for the request and benchmark environment. It does not require the generated program to follow a particular Python style. A verified program can use a different sequence of operations from the original so long as its observed result agrees with the reference. The procedure is therefore both a way to expand the pool and a source of variation in how the Python demonstrations are written.

For each primary run, the authors sample a small fixed set of demonstrations from the annotated training examples. In comparisons across output languages, the demonstration requests can stay the same while their solution programs are expressed in the relevant formalism. A demonstration about a particular river, for example, can teach the underlying geography task in both conditions. Any difference in how that example expresses selection or returns a result is part of the representation being compared.

The prompt starts with the domain description in conditions that include one. Next come solved requests, each paired with a program in the requested language. The final item is the new request, whose program is to be generated. Conditions without documentation start with the demonstrations. The paper uses temperature 0 for this generation, described as greedy decoding. The experimental repetitions vary the sampled demonstrations. The same demonstration set for a given seed is used across test requests and corresponding prompt comparisons.

The primary ChatGPT experiments use gpt-3.5-turbo-0613 with 10 demonstrations. The primary StarCoder experiments use 5 because the available context is shorter. These settings keep comparisons within a system tied to a shared demonstration budget. The authors make the implementation available through their code-semparse repository.

Select demonstrations when more examples are available

The paper also examines a setting where a larger training pool can be used before the final prompt is assembled. One option is to find examples that cover a range of operations. Here the objects counted for coverage are individual operator names in the chosen formalism. The authors score coverage by asking, for each operator, whether any of the chosen programs contains it.

setcov(S, Z) = ∑ₛ ∈ S max𝓏 ∈ Z 1[s ∈ S𝓏]

Here setcov gives the number of operators covered by the demonstration set. (S) is the inventory of operators considered, and (Z) is the set of demonstration programs being scored. The summation goes over each operator (s) in (S). The maximum ranges over each program (z), shown as 𝓏 in the block, in (Z). The set (S𝓏) contains the operators that occur in that program. The brackets are an indicator worth 1 when the operator belongs to the program’s set and worth zero otherwise. The maximum means repeated occurrences across demonstrations contribute no more to coverage than a single occurrence. The outer sum counts every operator that appears anywhere in the set.

The algorithm maintains a set of all selected demonstrations and a current set for accumulating coverage. It checks unused candidates from the instance pool (T) and chooses the candidate that yields the best coverage when added to the current set. If the score improves, the candidate joins both sets. If coverage stops increasing, the algorithm clears its current set and starts accumulating coverage again from the remaining candidates. The overall selection is retained, and the procedure continues until it reaches the demonstration budget (k). This reset gives the algorithm a way to continue choosing examples after progress in the current cover stalls. The selected set is shared across test requests.

The other option uses BM25, a retrieval method, to rank training utterances by similarity to the new utterance. Here each test request can receive a different set of solved examples. The selector compares the input wording with training inputs, since the desired program for the new request is what the parser has yet to produce. An utterance about neighboring states may retrieve questions with nearby wording, whereas the operator-coverage method could include an example about adjacency as part of a common prompt for all requests. The two selectors therefore test different uses of the available annotations. Information retrieval & search

Experiments and results

What the splits and scores measure

GeoQuery includes questions about geographic facts. Its test conditions include the original random split, labeled i.i.d. for independently and identically distributed, and the Template, TMCD, and length compositional splits. The length condition tests generalization to longer programs. The paper groups Template and TMCD with the tests of compositional generalization and reports them separately. The GeoQuery test sets range from 279 to 331 examples, and the authors use each complete test set for the primary comparisons.

In SMCalFlow, the tested requests all involve creating calendar events. The compositional 0-C split keeps event creation and organizational-chart examples separate in training and evaluates requests that combine them. A training example may teach the parser how to find a team, or how to create a meeting, while the test case can require an event whose participants are the result of the team lookup. When the prompt has 5 or more demonstrations on this split, the authors include at least two examples from each component domain. The primary comparison samples 250 examples from the test sets for SMCalFlow.

Overnight supplies both a random split and a Template split for the social-network domain. The authors select the published partition named template/split_0 arbitrarily. The experiment samples 250 test examples from the relevant Overnight test sets. Where a development set is available, the paper uses development results for most of its additional comparisons. The main ChatGPT and StarCoder comparisons use test sets. For Overnight, where the authors lacked a separate development set, they used 50 training examples to check that programs ran as expected.

The primary metric is execution accuracy. For geography questions, the comparison is between the returned number or set of entities and the result of running the reference program. Order does not affect GeoQuery’s set comparison. Overnight uses equality of the returned entity lists. The calendar evaluator compares the event created by each program, with specific normalization choices. It uses a small database of people and applies the same mapping of names to database entries in the reference and candidate programs for a given example. It ignores the generated event subject because the reference annotations are inconsistent on underspecified subjects.

The reported accuracies average runs over three seeds with different demonstration samples. Holding those samples fixed across corresponding conditions helps isolate the prompt changes being compared. The appendix reports standard deviations for the main ChatGPT results. It also reports exact match for the DSL outputs, which checks the generated program against the annotated program itself. Exact match and execution accuracy can reward different behavior. An expression using traverse_2 can count the rivers associated with a state and agree with the answer from a reference that performs the same count using a different expression. On GeoQuery’s random test split, giving FunQL the full natural-language description moves execution accuracy from 37.6% to 61.0%. The corresponding exact-match results are 20.7% and 27.6%.

What changes when the output is Python

The main baseline uses the benchmark’s original language with demonstrations and no description. The other baseline conditions give that language an operator list or fuller documentation. The Python conditions vary the documentation in parallel, with the additional comparison that preserves full declarations while removing types. This means the results can be read across representations or within a single representation while varying the amount of information supplied.

On the GeoQuery length test split, the baseline has to infer both how a long FunQL program is assembled and which operations should go into it. The Python condition improves substantially with demonstrations alone. Further increases follow as information about the available interface is supplied. Full Python documentation gives the highest execution accuracy in this comparison. The FunQL description written with code-like signatures helps as well, which shows that giving the original language more information is a meaningful baseline.

ChatGPT execution accuracy on the GeoQuery length test split with 10 demonstrations

Python improves with each richer description condition shown, and the full description gives the highest execution accuracy.

ChatGPT execution accuracy on the GeoQuery length test split with 10 demonstrationsFunQL without a description: 31.0FunQL without a description31.0FunQL with a full natural-language description: 39.4FunQL with a full natural-languagedescription39.4FunQL with a full code-style description: 43.9FunQL with a full code-style description43.9Python without a description: 57.3Python without a description57.3Python with an operator list: 75.3Python with an operator list75.3Python with declarations without types: 75.7Python with declarations without types75.7Python with the full description (this paper): 80.7Python with the full description (thispaper)80.7
The numbers
System or settingexecution accuracy %
FunQL without a description31.0
FunQL with a full natural-language description39.4
FunQL with a full code-style description43.9
Python without a description57.3
Python with an operator list75.3
Python with declarations without types75.7
Python with the full description (this paper)80.7

The SMCalFlow compositional test comparison shows what happens when the program must draw on scheduling and organizational lookup in the same request. The original Dataflow language with only examples scores low. The operator list and full natural-language description leave substantial difficulty. In Python the list of operators improves execution accuracy markedly, and retaining declarations without their type information raises it further. This comparison concerns the contents of the prompt, with the same calendar evaluation applied to the generated outputs.

ChatGPT execution accuracy on the SMCalFlow compositional 0-C test split with 10 demonstrations

Python gains substantially from interface documentation, while additional information gives Dataflow a smaller improvement.

ChatGPT execution accuracy on the SMCalFlow compositional 0-C test split with 10 demonstrationsDataflow without a description: 7.3Dataflow without a description7.3Dataflow with an operator list: 20.1Dataflow with an operator list20.1Dataflow with a full natural-language description: 20.7Dataflow with a full natural-languagedescription20.7Python without a description: 28.0Python without a description28.0Python with an operator list: 46.9Python with an operator list46.9Python with declarations without types: 65.6Python with declarations without types65.6Python with the full description (this paper): 66.7Python with the full description (thispaper)66.7
The numbers
System or settingexecution accuracy %
Dataflow without a description7.3
Dataflow with an operator list20.1
Dataflow with a full natural-language description20.7
Python without a description28.0
Python with an operator list46.9
Python with declarations without types65.6
Python with the full description (this paper)66.7

The main ChatGPT table gives Python with the full description the highest score on all 8 tested splits. GeoQuery illustrates how the gap between split types changes in absolute accuracy. With FunQL and no description, the random test split scores 37.6%, the Template test split 34.2%, and the TMCD test split 43.5%. With Python and the full description, those splits score 84.4%, 84.4%, and 84.9%, respectively. The length test result of 80.7% puts the remaining GeoQuery split much closer to the others. The random split is a reference point for the paper’s discussion of a compositionality gap. Some compositional scores can exceed it, as the TMCD figures illustrate.

On SMCalFlow, the full Python description brings the 0-C result closer to the corresponding random test accuracy of 69.2%. With Dataflow and no description, the random test result is 42.9% and the 0-C result is 7.3%. The improvement thus involves raising the performance on the harder split while also improving the random-split result. The magnitude of the remaining difference should be read with the variation across samples in mind. For ChatGPT with full Python documentation, the reported standard deviations in execution accuracy are 3.4 on the SMCalFlow random test split and 10.9 on 0-C.

The Overnight Template test is another case where the ordering of split scores depends on the representation. With λ-DCS and no description, execution accuracy is 34.0% on the random test split and 23.1% on the Template test split. Python with the full description scores 64.5% on the random test split and 72.9% on the Template test split. The study establishes better execution in both conditions. The reversal also shows why the split label alone does not determine what accuracy a particular prompt will attain.

StarCoder supports the main comparison under a smaller demonstration budget. On the GeoQuery length test split with 5 demonstrations, FunQL scores 14.7% without a description and 38.9% with the full description. Python scores 32.4% without a description and 68.6% with the full description. On the SMCalFlow 0-C test split, full documentation gives Dataflow 2.0% and Python 33.2%. Across the StarCoder comparisons, full Python documentation beats each original DSL setup on every split and gives the best result on 5 splits. On the Overnight Template test split, Python with no description scores 39.9% and full documentation scores 36.9%. The broad advantage of the representation is more consistent here than the benefit of adding the fullest available documentation.

The paper’s headline result is that a small prompt can yield much better executable programs when the interface is explicit and the output language offers familiar ways to use it. The size of the increase depends on which comparison is made. Changing both the language and its documentation yields the largest headline gains. The within-language comparisons show how much the description can do while leaving the output language fixed.

What the ablations show

Which parts of the description matter

On the GeoQuery random test split, Python with no description reaches 72.6%. An operator list brings it to 83.5%, and the full description reaches 84.4%. Declarations with types removed score 82.1%. Availability of operation names appears to be the main benefit of explicit documentation in this comparison. A name can tell the parser that a geographic relation is available through the interface. Familiar code can then express how to filter the retrieved values or compute a maximum. The test does not establish which particular names account for the gain.

On the GeoQuery length split, the operator list already improves accuracy, and full documentation raises it further. On the SMCalFlow 0-C split, declarations without typing account for much of the improvement beyond the names alone. The result fits a distinction between locating an operation and assembling a legal call. A name can suggest what a method does, but parameters and fields help specify how the result of a lookup fits into a calendar event. Full type information can add support. The ordering across splits indicates that type annotations have a variable contribution in these prompts.

The FunQL comparison tests an alternative explanation for the Python advantage. If the primary difference were simply whether the documentation looked formal, presenting FunQL signatures in code style should make the results more similar. On the GeoQuery length test, code-style documentation helps FunQL more than natural-language documentation does. On the random test split, the full code-style FunQL description yields 51.9%, compared with 61.0% for the full natural-language version. Python with no description scores 72.6%. The formalization of the documentation can affect results, with the direction depending on the split. Familiarity with the requested output and the operations available within it remains relevant even after this comparison.

How examples compete with documentation for space

The demonstration-count experiments examine a practical question. A fixed-size prompt can spend space showing more complete examples or explaining operations that many examples may omit. In GeoQuery and SMCalFlow, the count curves show that a single Python demonstration with a description can outperform a prompt with 25 demonstrations and no description. The paper also highlights a GeoQuery compositional comparison in which a single Python demonstration with a description reaches 80% accuracy and DSL prompting without a description yields 17%. A demonstration illustrates usage in one setting. A description can make an operation available for a range of requests, which is especially relevant when none of the sampled examples uses it.

Counting demonstrations alone favors neither a direct inference about cost nor an inference about information. A Python example can occupy more space than its DSL counterpart, and a description can take up space that could otherwise hold several examples. For the full-description Dataflow prompt in the SMCalFlow demonstration-count experiment, the context limit allows no more than 15 examples. The paper therefore also compares the Python conditions by total prompt tokens. Tokenization

In the token-budget comparison, the full description performs well for GeoQuery and SMCalFlow when it fits. For Overnight, the curves indicate that demonstrations alone can suffice. That is consistent with the narrower set of entities and operations used in the selected social-network domain. An example that filters people by a field can cover more of what will recur across that task than a meeting example can cover of the operations needed to create events with organizational, temporal, and attendance constraints. The evidence comes from the selected domains and measured prompt lengths. The paper gives no general rule for how much space to reserve for documentation.

The authors also test whether stronger demonstration selection removes the representation advantage. For GeoQuery, where they have Python annotations for the whole training set, they compare the fixed random prompts with greedy operator coverage and with the BM25 selection that adapts to the test utterance. The greedy sets cover 68% to 81% of the operators with 10 demonstrations, depending on the split. Even a prompt chosen specifically to cover operations therefore leaves some operations outside its demonstrations.

Across the GeoQuery split comparisons, Python stays ahead of FunQL under each selection method, both with documentation and without. Selecting similar requests can teach how a preceding case was solved, while a structured interface still supplies facts that those requests leave implicit. Selecting for operator coverage may make more of the DSL available through examples, while the parser still has to express the new arrangement in that language. The larger-pool experiment shows that the measured advantage survives both selection strategies on GeoQuery. The corresponding comparison was not established for the other benchmark domains.

Whether language frequency predicts the scores

Python may be effective because its constructs are familiar from pretraining, because the representation offers convenient ways to assemble the tasks’ operations, or because both conditions hold. To investigate the role of frequency, the authors compare Python with Scala and JavaScript. For GeoQuery they also include SQL. The Stack, a corpus of code from GitHub, gives the paper an external reference for the relative prevalence of these languages. In that corpus, JavaScript accounts for 19.6%, Scala for 0.1%, Python for 2.5%, and SQL for 4.9%.

Scala and JavaScript receive their own descriptions and examples. The resulting outputs are translated into Python for execution. The translation prompt includes the source and Python descriptions and examples of how to convert between the languages. It receives the generated program without the natural-language request that originally elicited it. This helps make translation a question of preserving what the source program says. To check fidelity, the authors manually inspect 100 random conversions, 50 for each language. They find 1 unfaithful conversion in each group.

SQL is evaluated through a separate executable route. The study uses the original GeoQuery SQL annotations, supplies the database schema in the descriptive condition, and runs the queries with SQLite. The schema lists the database structure available to the query. It serves a role similar to the description of the interfaces in the other languages, though its contents and the form of the resulting program differ. SQL’s target for evaluation comes from the reference SQL query.

Execution accuracy across described languages on the GeoQuery Template development split

Scala and Python lead this comparison despite Scala having the smallest share of the reference code corpus.

Execution accuracy across described languages on the GeoQuery Template development splitFunQL with a full description: 44.8FunQL with a full description44.8SQL with the database schema: 68.7SQL with the database schema68.7JavaScript with a full description: 80.0JavaScript with a full description80.0Python with a full description (this paper): 80.6Python with a full description (thispaper)80.6Scala with a full description: 83.3Scala with a full description83.3
The numbers
System or settingexecution accuracy %
FunQL with a full description44.8
SQL with the database schema68.7
JavaScript with a full description80.0
Python with a full description (this paper)80.6
Scala with a full description83.3

The GeoQuery Template development scores show why the corpus percentages are an incomplete predictor. Scala has the smallest share of the reference corpus and reaches the highest score in the chart. JavaScript has the largest share, with execution accuracy close to Python’s here. SQL improves on FunQL on this split while falling below the three general-purpose languages. On the GeoQuery length development split with documentation, Scala reaches 82.1%, Python reaches 80.9%, JavaScript reaches 73.6%, and SQL with the schema reaches 62.7%. The paper emphasizes the variations across comparisons and the absence of a single language ordering derived from corpus share.

The experiment measures the performance of each language with a particular prompt, interface, and execution path. Its narrower conclusion is that the order of prevalence in the reference corpus fails to explain the order of performance. The results can coexist with an important role for prior exposure to general-purpose code. For example, a familiar idea such as selecting an element by the value of one of its attributes is expressible in more than one language. A system could draw on that pattern even in a language with a small share of this particular corpus. The comparison cannot track which examples in pretraining contributed to any specific generated program.

What happens when the domain language changes

The authors look at two ways to simplify a domain language. For Overnight, they remove syntax that can be restored before evaluation. This includes the explicit call marker, the SW namespace, some parentheses, and wrappers for values such as strings, dates, and numbers. The shortened λ-DCS programs are 42% shorter on average by the paper’s measure of program length. The underlying operations still include retrieving properties and applying the domain’s specific filter expressions. The simplification yields only a marginal performance improvement in the reported comparisons.

Dataflow-Simple changes more. It uses fewer operators and function calls styled more like those of commonly used programming languages. An event can be built from separate clauses for its location or starting time. The language has less expressive scope than the original Dataflow, while covering the requests evaluated here. That makes it possible to keep the benchmark outcome fixed while changing the way the action is expressed.

On the SMCalFlow 0-C development split, Dataflow-Simple scores 22.7% without a description and 63.9% with the full description. The original Dataflow conditions score 7.5% and 20.7%, respectively. Python with the full description scores 69.9% on that development split. The strong result for the documented simplified language demonstrates that a domain-specific target can approach the performance of Python in this comparison. It also puts the description and the redesigned representation in the same successful condition. The difference between the documented and undocumented Dataflow-Simple prompts is large enough that the redesign alone gives an incomplete account.

The Overnight and calendar changes test different interventions. Removing redundant surface material from λ-DCS keeps its general way of composing expressions. Dataflow-Simple changes how its operations are presented and which operations are needed, in addition to changing syntax. The experiments give evidence about the two packages of changes. They cannot attribute Dataflow-Simple’s advantage to the call syntax, the reduced inventory, or the way event constraints are grouped in isolation.

Whether demonstrations benefit from intermediate steps

The authors also test a property that many Python demonstrations exhibit. A program can name an intermediate result and then use that value later. To ask about states with points higher than Colorado’s highest point, for example, a program can first find Colorado, then obtain its highest elevation, then use that value to filter other states. A one-line version can put the lookup and threshold inside the filter expression. Execution can produce the same answer even though the examples expose different ways of organizing the computation.

The experiment uses GPT-4 to expand compact demonstrations or compress multi-line ones. The authors check the converted programs by execution and regenerate invalid conversions at temperature 0.4 until a correct one is obtained. The full domain description remains in the prompt. Only the demonstrations are rewritten. The generator is still free to return a program with whichever line structure it uses. The experiment thus measures whether presenting intermediate steps in the examples improves the subsequent predictions.

The effect varies by split. On the SMCalFlow 0-C development comparison, execution accuracy is 60.4% with single-line demonstrations and 70.0% with multi-line ones. On the Overnight Template development comparison, the figures are 57.6% and 72.9%. GeoQuery’s Template development results are 80.9% and 80.6%, respectively, while the length results are 79.1% and 80.3%. The gains are substantial in some settings and slight or absent in others. The paper also finds that the single-line demonstrations still outperform the original DSL prompts. Naming intermediate results can help, while only part of the overall difference between the languages is captured by this intervention.

What remains difficult even with a full description

The authors examine individual errors from ChatGPT using Python and the full description. In one seed on the SMCalFlow compositional development set of 250 examples, they find 78 errors. Of those, 42, or 54%, are programs that fail to execute, and the remaining 36 execute incorrectly. The analysis identifies 11 errors, reported as 14% of that error sample, involving requests that the original environment or the Python reimplementation does not support. The authors distinguish these from failures of interpretation and failures to use the interface correctly.

Some examples clarify how different failures can look in the final score. One program selects an invalid date value and fails when run. Another attempts to drop a person from a team with a standard list operation, even though the supplied calendar interface records exclusions in an event field. A separate error involves the meaning of “skip” as a manager’s manager, where the generated lookup follows only one managerial relationship. Here the operation can be legal while the interpretation of the request is incomplete. Successful generation requires both following the interface and choosing operations that correspond to the words.

On the GeoQuery TMCD development set, one seed has 18 errors among 100 examples. The authors attribute 8 to the parser, 8 to dataset discrepancies, and 2 to limits of the environment. An ambiguity in the database’s names for Mount McKinley is one example of a discrepancy that can affect the result. These counts show why execution accuracy is informative without directly classifying the cause of every failure. It records whether the predicted program and the reference agree under the evaluation. Investigation of specific examples is needed to locate the source of a disagreement.

Limitations

Limits the authors identify

The authors note that their Python environments can diverge from the original systems they approximate. This concern is especially visible in SMCalFlow, where the benchmark formalism includes seldom-used operations that were omitted from the implementation. A request may be intelligible and expressible in the original task while lacking the support it needs in the reimplementation. Conversely, a result obtained through a convenient Python interface measures what can be done with that interface. The error analysis makes some missing support visible, but it does not quantify equivalence across the full range of programs that either language can express.

Most Python demonstrations are annotated with assistance from OpenAI’s API. Validation confirms successful execution for the examples that enter the pool. Choices about program structure remain open within that requirement. A generator may prefer certain ways of naming variables, breaking up a computation, or calling an interface. Those preferences could affect how well later prompting works with the accepted examples. The authors identify this as a potential source of bias. Hand-translated annotation and execution-verified generation play different roles in the pipeline, and the paper does not compare their effects as independent annotation strategies.

The Stack percentages are an approximation of how common the languages are in publicly available code. The authors do not know their proportions in the actual OpenAI training data. They also leave open how much of the observed performance reflects compositional generalization and how much reflects remembering similar code from pretraining. The tests demonstrate generalization relative to the benchmark split and the examples in the prompt. Those splits place no known restrictions on everything encountered during pretraining. The results with relatively rare Scala and with Dataflow-Simple make a simple frequency explanation less convincing, while leaving the contribution of prior exposure unresolved.

The authors suggest that a programming language might also be useful for other outputs that follow a structure and unfold in steps, such as recipes and travel itineraries. Those tasks are proposed extensions. The experiments test semantic parsing against executable benchmark environments, where the result can be compared to a reference answer or an environment change. A different structured generation task would need its own account of what counts as satisfying a request.

Additional limits of the comparisons

The few-shot claim concerns the information available to construct a prompt in the primary setting. The broader experimental workflow uses existing benchmark annotations, an executable reference, verified Python examples, and authored descriptions of the environments. A real application would need to establish that its interface and descriptions cover the requests it expects. The paper measures prompt performance given these resources. It does not compare the total effort of building or maintaining a new interface with that of collecting additional examples for an existing domain language.

The scope of the action evaluation is also specific. The SMCalFlow test cases studied here require event creation, and the evaluator compares events after mapping names into a small database. Event subjects are omitted from the check because some requests do not provide enough information to determine the intended subject and the annotations are inconsistent. Consequently, a high score under this evaluation establishes agreement on the included event properties under the benchmark’s normalization. Correct subject generation, behavior across a live organization’s data, and handling of calendar actions outside the tested requests remain separate questions.

Likewise, passing the execution check on a geography or social-network request establishes agreement on the measured output in the benchmark environment. Two distinct programs can agree there and produce different answers if relevant facts are changed. This possibility matters for the example-conversion checks as well as for the main results. Execution is well suited to accepting harmless variation in program wording. Showing that two programs always have the same interpretation would require evidence beyond agreement on the evaluated instance.

Some language comparisons also involve different routes to a score. JavaScript and Scala pass through a generated translation to Python, while GeoQuery SQL uses its own engine, schema, and reference queries. The manual audit of translations gives evidence about the fidelity of that procedure. Its finite sample leaves uncertainty about translation errors in the full evaluation, including the possibility that a translation occasionally helps or hurts a candidate. The end-to-end comparison still compares useful ways to prompt for programs, with less control over the language as an isolated causal variable.

The small sets of demonstrations can affect both means and variation. The reported standard deviations help show how much performance changes with sampling under particular conditions. On SMCalFlow’s 0-C test, the full Python description yields a high mean with visible variability. Indeed, this is the sort of domain in which a selected demonstration might happen to clarify a particular construction, such as excluding an attendee, that the interface alone leaves underspecified. The paper’s split-level gains support the combined approach while leaving sensitivity to the demonstrations as an important feature of the observed results.

Finally, the controlled comparisons leave some of the proposed design explanations coupled. Changing from FunQL to Python changes syntax, program decomposition, available generic operations, and the natural way to present the domain interface together. The single-line study controls the organization of the demonstrations and still permits arbitrary generated output. The simplified calendar language changes both syntax and the set of operators. The strongest conclusion lies at the level of the tested designs. Familiar programming constructs and domain documentation improve these parsers in combination, while the contribution of particular constructs remains open.

What came after

The later citations come from surveys of retrieval-augmented generation. That topic concerns supplying information retrieved from a collection to a generator. In Bogin and colleagues’ main experiments, the domain description is a fixed part of the prompt. Request-specific retrieval appears in the separate GeoQuery comparison, where BM25 chooses worked examples from the annotated training pool. The study consequently touches on both fixed interface documentation and retrieval of examples adapted to a request, with different evidence for each.

Retrieval-Augmented Generation for AI-Generated Content cites the semantic-parsing study in a survey with a broad focus on retrieval-augmented generation. A point of contact is how information supplied at generation time helps determine the form and usefulness of the result. In the semantic parser, retrieved examples can illustrate a likely operation, while the domain description conveys the interface available to the generated program. The citation establishes a connection to the survey. It does not establish whether the survey discusses the BM25 experiment, the domain descriptions, or another aspect of the paper. Retrieval-Augmented Generation for AI-Generated Content: A Survey

The other citing survey focuses on retrieval-augmented generation in software engineering. Its subject brings the comparison closer to the paper’s use of code and documented interfaces. Bogin and colleagues test how declarations about callable operations can help a generator write code compatible with a particular environment. That is a thematic connection with the survey’s scope. The citation gives no basis for attributing a new implementation, replication, or benchmark result to the survey. 检索增强生成在软件工程中的应用综述

Cite

Cite as Ben Bogin, Shivanshu Gupta, Peter Clark and Ashish Sabharwal. 2024. Leveraging Code to Improve In-Context Learning for Semantic Parsing. Proceedings of the 2024 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies (Volume 1: Long Papers).

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.18653/v1/2024.naacl-long.279

@inproceedings{bogin2024leveraging,
  title = {{Leveraging Code to Improve In-Context Learning for Semantic Parsing}},
  author = {Ben Bogin, Shivanshu Gupta, Peter Clark and Ashish Sabharwal},
  booktitle = {Proceedings of the 2024 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies (Volume 1: Long Papers)},
  year = {2024},
  doi = {10.18653/v1/2024.naacl-long.279},
  url = {https://doi.org/10.18653/v1/2024.naacl-long.279}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/bogin-2024-leveraging-code-improve-context-learning/