Skill-Based Few-Shot Selection for In-Context Learning
Paper · 2023 · Shengnan An, Bo Zhou, Zeqi Lin et al.
Summary
When a system answers a question by learning from examples in its prompt, the examples can look relevant and still teach the wrong operation. A question about cities with several young employees may retrieve another question about employees and cities that asks for the city with the largest workforce. The vocabulary overlaps, but the first question calls for filtering by age, grouping by city and keeping groups that meet a count threshold. The paper asks how to find demonstrations that share this kind of underlying procedure. Its answer, Skill-KNN, changes what the retrieval system compares in few-shot learning.
The authors first show a frozen text generator how to describe the skills required by a task. For a database question, a description might say to join tables and count distinct values. They generate descriptions for the queries in an example bank and for each new query, encode the descriptions as vectors, and retrieve nearby examples. The prompt for the final answer uses the original examples, complete with their answers. The authors also try several orders of their hand-annotated examples, since a change in order can change the generated descriptions. One variant compares the average vectors across rewrites. The other looks for the strongest match between any pair of rewrites. Both use existing components without fine-tuning.
The main evaluation spans database querying and a benchmark for interpreting sentence structure, both instances of semantic parsing. Across the reported main comparisons, a Skill-KNN configuration gives the best result among selectors that can operate without the test answer. On the Spider development split with text-chat-davinci-002, its best configuration achieves 78.3% execution accuracy. The strongest baseline based on the wording of the input reaches 74.6%, while retrieval that can compare the reference SQL with candidate answers reaches 78.6% under Target-KNN. A smaller experiment on math word problems also reports an improvement over the baselines tested there.
The controlled comparisons show that the rewriting prompt can help even with only 4 hand-annotated examples and retains much of its benefit when those examples cover a narrower range of databases or operations. The rewrites sometimes omit relevant details, and the most successful way of combining them varies across settings. The evidence is strongest for tasks where inputs from different domains still call for similar operations. It shows that changing the text passed to a fixed encoder can make its nearest neighbors more useful as demonstrations.
Deep dive: Skill-Based Few-Shot Selection for In-Context Learning
Skill-KNN selects few-shot examples by matching the operations a task requires, improving cross-domain text-to-SQL and semantic parsing. · about 33 minutes to read
The problem and its context
What makes an example relevant?
In-context learning gives a text generator examples of a task inside the prompt. Say the task is to translate a database question into SQL. The prompt can show earlier questions with their SQL answers, then present a new question and its database schema. The generator uses the examples while producing the new answer, with its parameters held fixed. The paper takes this setup from work such as Language Models are Few-Shot Learners.
The prompt has room for only a small share of a large example bank. A selection rule therefore has to make a judgment for each input about which examples deserve that space. The rule matters because a demonstration can supply more than a template for formatting the answer. Its output can illustrate how a question maps to a grouping operation, how a condition applies to the groups, or how information from several tables comes together. The choice of demonstration determines which of those patterns is available in the prompt.
A standard way to make the choice is to put the new input and each candidate input through a pretrained text encoder. The encoder gives each input an embedding, a vector that represents the text. A nearest-neighbor search ranks the candidate vectors by their similarity to the new one. That arrangement is broadly usable because the selector can work with an existing encoder and an ordinary set of solved examples. The paper traces this approach to work including What Makes Good In-Context Examples for GPT-3? and Making Pre-trained Language Models Better Few-shot Learners.
The difficulty is that relevance depends on what the system must produce. The paper illustrates it with a query about cities where more than one employee is younger than 30. Among the questions retrieved, one asks which location has the largest number of employees living there and what that number is. Both questions mention cities and employees. Both involve counting. But finding the largest group illustrates a different form of SQL from retaining every group that qualifies after the employee records have been filtered by age. A question on a different subject could demonstrate that pattern more directly. This is a mismatch between the textual cues the retriever can readily compare and the structure that would make a useful example of the answer.
That mismatch is especially important in cross-domain text-to-SQL. The bank may contain examples from entirely different databases, with different names for tables and columns. The same operations can recur across these databases. Selecting a value only once, combining records from related tables, taking a maximum, and comparing a group count with a threshold all describe patterns that can transfer across topics. An input representation that preserves these distinctions has a chance of finding useful examples even when the new question has very little vocabulary in common with them.
COGS, the paper's other main kind of parsing task, brings out a related issue without a database. Its output represents the roles and relationships in a sentence. An example about an completely different person or object can still demonstrate how a passive construction expresses an agent or recipient. Conversely, two sentences involving similar entities may give those entities different roles. Here, too, the relevance of an example is partly a question about the structure of its answer. The authors use that resemblance between the tasks to motivate a common retrieval procedure with different descriptions for different kinds of skills.
What earlier selection methods tried to learn
Several methods discussed by the authors already recognized that ordinary text similarity was an imperfect retrieval criterion. One line of work trained a selector using evidence about which demonstrations helped a generator predict a correct answer. A separate approach trained the encoder to recognize questions whose target programs resemble one another. The paper also discusses training based on similarities in dialogue state changes and training that accounts for how demonstrations interact when they appear together. These methods give the selector a task-specific notion of relevance through its learned parameters.
The authors see a practical cost in that arrangement. Separate tasks can require separate fitted encoders, and a bank that changes frequently can make it inconvenient to repeat the fitting procedure. Skill-KNN takes the existing encoder and changes the representation it receives. Its supervision consists of examples of how to describe an operation or a construction in ordinary language. Those examples can influence retrieval through prompting, while the code for comparing two vectors stays the same.
Other training-free directions in the paper's account include distilling an example bank into a smaller collection of exemplars, approaching classification through information compression, and choosing examples that offer complementary explanations. The paper also notes work that brings symbolic systems into the generation process. Skill-KNN intervenes before the task answer is generated. It uses a description of the required procedure as a search representation, then supplies solved examples as context for the original problem.
The work also builds on earlier observations about semantic parsing with prompts. The authors cite findings about the relative ease of generating English-like descriptions, the importance of prompt design for SQL generation, and the gains that can come from dividing that generation into stages. Earlier work on prompt order supplies a more specific reason to be cautious about the rewriting stage. Skill-KNN adds a prompt whose examples teach the generator how to describe an input, so the order of those examples creates another source of variation before the final answer prompt is assembled. Fantastically Ordered Prompts and Where to Find Them
The resulting problem is narrower than designing the best possible semantic parser. The paper changes the selection rule and asks how well the same answer generator can use the examples selected under different rules. A good rewrite has value because of the neighbors it produces and the answers those neighbors help generate. The rewrite itself can remain an informal description. Its role is to bring useful comparisons within reach of a general-purpose encoder.
The method, step by step
From a database question to a search representation
Skill-KNN uses two prompts for different purposes. The first prompt teaches a generator to describe the skills an input requires. Its demonstrations pair original inputs with hand-written descriptions. The second prompt teaches the answer generator by example. Its demonstrations pair original inputs with their task outputs, such as SQL queries. The rewrite determines which input-output pairs go into the second prompt. Keeping these roles clear helps explain why the method can benefit from descriptions that are too general to serve as answers.
Consider the paper's example about counting the distinct colleges attended by players associated with a named team. The schema shows how player and team information is arranged. The annotated description emphasizes joining the relevant tables and counting distinct values. It leaves the team name out of the description. A retriever can now look for similar operations across the bank, even if the subject of another example has nothing to do with players or colleges. The actual demonstration eventually shown to the answer generator still includes its original question, schema and SQL.
The paper's example about product catalog entries makes a different distinction. The requested result is a name, and the qualifying condition concerns how a stock identifier begins. The description identifies a column to return and a constraint on the form of a value. A search driven by general topic might emphasize the catalog terminology. A search driven by this description has a basis for retrieving a demonstration of pattern-based filtering. It can also distinguish that condition from an interval condition on a numerical value, another pattern covered in the annotations.
The authors write the skills in natural language. Their rationale is that the encoders used for selection already represent ordinary text, so the descriptions can make use of that ability. The method does not define a formal inventory in which every input must be assigned a fixed list of operation codes. Descriptions can mention sequences and combinations of operations, as in a case where the system first calculates an average and then uses it as a threshold. For COGS the descriptions discuss grammatical constructions instead, including embedded clauses, passive voice and phrases that express the recipient of an action.
How Skill-KNN selects examples and generates an answer
The steps in order.
Creating the rewriting prompt
The standard setup starts with 16 manually described inputs. For the shared text-to-SQL prompt, these come from the Spider example bank. The authors look at the logical operations represented in the bank and choose examples greedily to cover them. At each stage of a greedy procedure, the immediate choice is directed toward covering operations that still need representation. The authors then fill the annotation set by sampling additional examples from varied databases. This gives the prompt a range of operations and database contexts without requiring a description for every bank entry.
The hand-written descriptions for Spider serve more than one evaluation dataset. Dr. Spider and KaggleDBQA draw their candidate demonstrations from the Spider training bank, so the same rewriting guidance can be used for their incoming questions. BIRD gets a separate prompt with 12 annotated demonstrations because each of its inputs includes supplementary evidence. COGS gets its own set of 16 annotations for describing sentence structure. In each case the annotations establish what counts as a useful description for that task.
The authors use gpt-3.5-turbo to generate skill descriptions. They present the annotated examples and append the input whose required skills should be described. For text-to-SQL, the rewriting input includes the question and schema. This lets a description reflect decisions that depend on where data are stored, such as whether the query needs to join tables. An ordinary raw-input retriever in the experiments embeds the question on its own, since a full schema can add material irrelevant to the similarity calculation. BIRD has an additional arrangement for its evidence, described below.
Once the descriptions have been generated, the authors use a fixed text encoder to represent them. The compared Skill-KNN settings use SBERT or OpenAI Ada. The nearest-neighbor search retrieves the original examples indexed by the descriptions. It selects 4 examples for the answer prompt, with higher-ranked examples placed closer to the new query. The original query remains at the end of that prompt. Rewriting is therefore an intermediate operation on the search inputs, while the example outputs and the question to be answered retain their normal task format. Sentence-BERT
The retrieval and generation equations
The paper starts with a general description of answering from selected examples. The selector returns an ordered sequence of examples from the bank, and the generator receives that sequence followed by the new input.
yₜ ∼ LLM(θ, τ)[R(xₜ, B) ⊕ xₜ]
Here, xₜ is the test input and yₜ is the generated output for it. The subscript t denotes the test case. B is the bank of input-output examples. R is the selection function, so R(xₜ, B) is the sequence of demonstrations it returns. The symbol ⊕ joins sequences in the order shown, and the square brackets enclose the resulting prompt. LLM denotes the generator, θ its frozen parameters, and τ its sampling temperature. The symbol ∼ says that the output is drawn from the generator's distribution under those conditions. The default temperature is 0, which gives greedy decoding. The authors set the maximum decoding length to 200 for their inference setup.
For ordinary nearest-neighbor retrieval, the selector compares the original texts through cosine similarity. Cosine similarity measures how closely the directions of the two vectors align after accounting for their lengths.
sim(xₜ, xᵢ) = Emb(xₜ) Emb(xᵢ)ᵀ / (‖Emb(xₜ)‖ ‖Emb(xᵢ)‖)
The function sim returns the similarity score. The symbol xᵢ is the input of the bank example indexed by i, and xₜ is the test input. Emb is the fixed text encoder. The superscript ᵀ denotes a transpose, and the adjacent vectors in the numerator give their dot product. The double bars denote vector length. The slash divides the dot product by the product of the lengths in parentheses. Ranking by this score supplies the nearest examples. Semantic similarity
Skill-KNN produces a different input for that same kind of comparison. The generator is shown the examples of how to write skill descriptions, and then it writes one for the appended input.
sᵢ = LLM[{xₐ → sₐ} ⊕ xᵢ]
Here, sᵢ is the generated description for xᵢ, the input being rewritten. The braces enclose the annotated demonstrations, with a indexing an annotation, xₐ denoting its input, and sₐ denoting its human-written description. The arrow marks the pairing shown in a demonstration. The demonstrations appear in an order in the prompt even though the notation collects them in braces. The operator ⊕ appends xᵢ to that sequence. The brackets enclose the prompt for LLM, which in this equation is the generator doing the rewriting. The same procedure gives a description for xₜ.
The base selector applies the raw-input cosine calculation to the two descriptions. That substitution is the central change to the retrieval procedure.
sim(sₜ, sᵢ) = Emb(sₜ) Emb(sᵢ)ᵀ / (‖Emb(sₜ)‖ ‖Emb(sᵢ)‖)
The test description is sₜ and the description indexed by bank example i is sᵢ. The function sim gives their score, Emb takes each description to a vector, and ᵀ transposes the second vector for the dot product. The double bars give the two lengths. The slash again divides by their product. The retrieved item is the input-output pair associated with sᵢ. In the reported base experiments, the authors use shuffled annotation orders to generate 5 descriptions per input and average the results of the base procedure. The variants use those descriptions together inside retrieval.
Using several rewrites for each input
Even with greedy decoding, changing the order of the demonstrations changes the rewriting prompt. A description may mention a secondary filter under one order and omit it under another. One phrasing might clearly express a key operation, while another gives a more general account of the same request. The variants turn this sensitivity into a collection of candidate views of each input. They use the same hand-annotated examples and generate the candidates by shuffling those examples.
The consistency variant averages the embeddings for the candidate descriptions of each input. This produces a single vector for the test query and a single vector for each eligible example. The idea resembles a vote in embedding space. Features that recur across the candidates contribute consistently to the mean, while features that vary can have less influence. The motivating analogy is to combining different generations for reasoning, though here the objects combined are description vectors used for selection. Self-Consistency Improves Chain of Thought Reasoning in Language Models
e(S) = (1 / m) ∑ⱼ Emb(sʲ)
The symbol S denotes all candidate descriptions of one input. The index j runs over its candidates, and sʲ denotes the candidate at that index. Emb gives each candidate's vector, and ∑ⱼ adds the vectors across candidates. The symbol m is the number of candidates. The factor in parentheses divides the sum by m, so e(S) is the mean vector for that input.
simᶜ(Sₜ, Sᵢ) = e(Sₜ) e(Sᵢ)ᵀ / (‖e(Sₜ)‖ ‖e(Sᵢ)‖)
The superscript c indicates consistency. Sₜ is the set of descriptions for the test query, and Sᵢ is the set for example i in the bank. The function e gives the mean vector defined above. The numerator is the dot product of those mean vectors, using the transpose ᵀ, and the double bars give their lengths. The slash indicates division by the product of the lengths. The selector ranks bank examples by the resulting cosine.
The distinctiveness variant instead asks how similar the best-matching pair of descriptions is. It can favor an example when a particularly informative rewrite of the test question aligns with a similarly informative rewrite of the candidate question. This matters when several descriptions are generic and a more specific description captures the operation that makes the example useful. The match is computed independently for each bank example, so different descriptions of the test query can supply the strongest match to different candidates.
simᵈ(Sₜ, Sᵢ) = maxⱼ,ₖ [Emb(sₜʲ) Emb(sᵢᵏ)ᵀ / (‖Emb(sₜʲ)‖ ‖Emb(sᵢᵏ)‖)]
The superscript d indicates distinctiveness. The sets Sₜ and Sᵢ again belong to the test input and bank example i. The candidate sₜʲ is indexed by j in the test set, and sᵢᵏ by k in the example set. Here k is a candidate index. Emb gives the vectors, ᵀ denotes the transpose used for their dot product, and the double bars give their lengths. The bracketed quantity is the cosine for one pair, with the slash denoting division by the product of the lengths. The maximum runs over all choices of j and k. A single high-scoring pair is sufficient to give the bank example a high score.
The two rules make different use of agreement. The consistency variant lets all candidates influence a shared representation, which can dilute a specific feature that appears sparsely. The distinctiveness variant can preserve such a feature through one good match. Its maximum can also be high if two rewrites happen to share a misleading description. There is no separate correctness test on a rewrite before it contributes to the score. Both variants ultimately produce the same kind of object for the answer stage, an ordered collection of solved examples.
The two oracles and what they measure
The paper uses selectors with access to the reference output as diagnostics. Target-KNN embeds the reference answer for the test case and compares it with the known answers in the bank. Target Sketch Matching compares selected structural features of the answers. In the SQL tasks, its score is the overlap of a pre-defined set of keywords and operators found in the two queries. The inventory includes cues for selecting, filtering, grouping, joining, ordering and aggregating.
simₖ(yₜ, yᵢ) = |KW(yₜ) ∩ KW(yᵢ)|
Here, simₖ is the keyword-overlap score. The symbol yₜ denotes the reference SQL for the test input, and yᵢ denotes the SQL answer of bank example i. KW returns the set of recognized keywords and operators that occur in a query. The symbol ∩ takes the intersection of the two sets, and the single bars count its elements. For COGS, the authors use a separate target-side structural comparison suited to its logical forms.
The SQL sketch score can identify programs that both contain grouping and counting. As a set intersection, it ignores repetitions, the order of the terms and the arguments to an operator. That makes it a different proxy for demonstration utility from target embeddings, which compare whole encoded answers. Both selectors can exploit information unavailable to Skill-KNN at test time. Neither is designed to search for the combination of demonstrations that maximizes the final answer's probability of being correct.
Experiments and results
Where the candidate demonstrations come from
The main experiments use cross-domain or distribution-shifted settings. In Spider, the example bank is the training split of 7,000 examples and the evaluation is the development split of 1,034 examples. The splits share no database. A retrieved example can show useful SQL structure, but the answer generator has to apply it with the tables and columns of the new database. This makes Spider the central test of the paper's hypothesis about shared operations across different domains.
Dr. Spider is a diagnostic benchmark derived from Spider. Its 15,269 examples are divided by what was perturbed. DB denotes changes involving the database, NLQ changes involving the natural-language question, and SQL changes involving the target query. The authors still retrieve from Spider's training split. This makes the results a test of whether the selection method continues to help when aspects of the evaluation inputs or tasks are deliberately changed.
KaggleDBQA, abbreviated KDBQA in the results, contains 8 real web databases and 275 unrestricted questions. The paper treats it as an evaluation set and again uses Spider training examples as the bank. The question is whether examples prepared for one collection of databases can help with another collection, in this case one intended to reflect realistic queries and database formatting. Together these benchmarks let the authors reuse the same bank while changing the demands on the selector.
BIRD contributes 9,428 training examples and 1,534 development cases. Its questions include evidence about how to interpret them. The authors include that evidence in the answer prompt, append it to the question for the raw-input retrievers, and give it to the Skill-KNN rewriter. The schemas are too large for the authors' prompting setup, so they reduce them by comparing the question and evidence with table and column names. The grounding procedure retains 8 tables and 16 columns per table for each question-schema pair. BIRD therefore tests the skill representation in a pipeline that already does some input-dependent selection of schema information.
COGS uses synthetic sentences to assess compositional generalization, the ability to interpret familiar elements when they occur in unfamiliar combinations or structural contexts. Its training set contains 24,155 examples and its generalization set contains 21,000. For computational reasons, the authors sample 2,000 training examples as the bank and report sampling 1,000 evaluation examples from the primitive substitution and primitive structural alternation subtasks, abbreviated P.S. and P.A. Their output representation expresses thematic roles, modifications and relations among clauses in a compact function-call form. It omits the original markers for definite descriptions and the original Skolem constants. The evaluation thus concerns the paper's chosen representation and sampled settings.
What the systems are compared on
The principal comparison is among selectors. The random baseline samples examples from the bank and averages over 3 selections per test case. Raw-input KNN ranks by cosine similarity using one of several encoders, including SBERT, OpenAI Babbage and OpenAI Ada. MMR, a diversity-aware baseline, uses Ada and applies a penalty for similarity to examples already chosen. Its score can favor a demonstration that adds something to the prompt over one that mostly repeats an existing selection.
The authors also compare with supervised selectors on Spider. EPR uses a separate scoring generator to produce positive and negative cases for fitting its encoder. The paper uses GPT-J, with 6B parameters, for that scoring step. CEIL learns about interactions between an input and combinations of demonstrations through a contrastive training objective. TST tunes for similarity on the target side, seeking questions whose programs are alike despite differences in phrasing. These baselines test whether a prompting-based change to the retrieval input can compete with fitting a task-specific selector.
Target-KNN and Target Sketch Matching receive the reference answer at selection time. For Target-KNN, the authors try OpenAI Babbage and OpenAI Ada and report the better result for each task. Those comparisons address how informative the generated skills are relative to answer-side similarity. The random, raw-input and supervised comparisons address the more practical question of what can be selected given the new input alone. A separate Spider comparison with Din-SQL includes an approach that changes the SQL generation process by dividing it into stages.
The broad comparison uses text-chat-davinci-002, code-davinci-002, text-davinci-003 and code-cushman-002 as answer generators. The authors also run Spider development experiments with gpt-35-turbo and gpt-4. They call the frozen answer generator the backbone. Changing the backbone can change how well a given set of demonstrations works, even when their usefulness as retrieval results appears similar. The separate rewriting generator stays fixed across the main comparison.
The SQL tasks are evaluated by execution-with-values accuracy. The question is whether running the generated query yields the correct result under the evaluation, with values included. The authors use Spider's official test-suite SQL evaluation scripts for Spider. COGS uses exact-match accuracy for its logical forms, so success requires a match to the target representation. The paper also tabulates wins across tasks and subtasks. A win summarizes which setting came out best in a comparison, while the underlying accuracy scores show the magnitude of the performance in that setting.
The Spider results
On the Spider development split with text-chat-davinci-002, base Skill-KNN with SBERT reaches 76.8% execution accuracy. Raw-question retrieval with the same encoder reaches 73.0%. The best configuration for this backbone uses SBERT with distinctiveness and reaches 78.3%. MMR with Ada, the best baseline in the main comparison that retrieves from raw inputs, reaches 74.6%. The two answer-side diagnostics reach 78.6% for Target-KNN and 79.5% for Target Sketch Matching.
Retrieval methods on Spider dev with text-chat-davinci-002, execution accuracy
The strongest Skill-KNN setting leads the input-based baselines and approaches the answer-based selectors.
The numbers
| System or setting | execution accuracy % |
|---|---|
| Random | 72.9 |
| Raw KNN with SBERT | 73.0 |
| MMR with OpenAI Ada | 74.6 |
| Base Skill-KNN with SBERT | 76.8 |
| Distinctiveness Skill-KNN with SBERT (this paper) | 78.3 |
| Target-KNN oracle | 78.6 |
| Target Sketch Matching oracle | 79.5 |
The SBERT comparison is particularly informative because the encoder stays fixed. In both cases it maps text to vectors, but the texts differ, and the rewrite has been informed by the database schema. The downstream improvement shows what the combination of task-oriented rewriting and the fixed encoder can accomplish. The comparison with raw-input MMR makes a separate point. Selecting more diverse examples using an input-similarity ranking is useful as a baseline, yet a better representation of the required operations can also change which examples are worth selecting in the first place.
Other backbones show the same broad advantage for skill-based retrieval on Spider, with different winning settings. With code-davinci-002, distinctiveness with SBERT reaches 77.4% execution accuracy and MMR with Ada reaches 74.8%. With text-davinci-003, distinctiveness with SBERT reaches 76.6% and MMR with Ada reaches 72.4%. With code-cushman-002, consistency with SBERT reaches 74.7% and random selection reaches 72.2%. That last setting illustrates why the comparisons include random selection. A more elaborate input-similarity search only helps if its chosen examples provide better context than a draw from the bank.
The supervised Spider comparison provides a stronger test of the training-free approach. With text-chat-davinci-002, the base SBERT version reaches 76.8% execution accuracy, alongside 74.4% for EPR, 75.0% for CEIL and 76.3% for TST. With code-davinci-002, EPR reaches 75.9% and the Skill-KNN distinctiveness setting with SBERT reaches 77.4%. The code-cushman-002 comparison is closer. EPR reaches 74.6%, Skill-KNN consistency with SBERT reaches 74.7%, and distinctiveness with the same encoder reaches 72.8%. These results compare named configurations on one development split and give concrete examples of when the choice of skill variant matters.
On the same split with gpt-4, consistency with SBERT reaches 82.7% execution accuracy, the highest result in that comparison. Distinctiveness reaches 82.3%, and the base setting reaches 81.3%. With gpt-35-turbo, the best result is instead the distinctiveness setting at 76.8%, alongside 76.3% for consistency and 76.2% for the base version. The skill-based representation helps with both backbones, and changing the scoring rule changes the ordering of the results.
Selection and prompting settings on Spider dev with gpt-4, execution accuracy
All the Skill-KNN settings score above the baselines in this comparison, with consistency giving the highest accuracy.
The numbers
| System or setting | execution accuracy % |
|---|---|
| Random | 76.1 |
| Raw KNN with SBERT | 76.7 |
| Din-SQL | 74.2 |
| Base Skill-KNN with SBERT | 81.3 |
| Consistency Skill-KNN with SBERT (this paper) | 82.7 |
| Distinctiveness Skill-KNN with SBERT | 82.3 |
Perturbed data, other databases and sentence structure
Dr. Spider provides evidence about performance under designed changes to the data. With text-chat-davinci-002, raw SBERT retrieval scores 51.6% execution accuracy on database perturbations, and random selection scores 54.1%. Distinctiveness with SBERT reaches 57.0%. On SQL perturbations, raw SBERT retrieval scores 67.3%, random selection 68.2%, and the base Skill-KNN setting with SBERT reaches 72.1%. The paper notes that skill-based retrieval improves on random across the perturbation categories with this backbone. The categories retain separate scores because sensitivity to a shift in database information is a different diagnostic from sensitivity to a shift in question wording or target structure.
On KDBQA with text-chat-davinci-002, the strongest reported skill-based settings reach 40.0% execution accuracy, while MMR with Ada reaches 37.3%. The answer-side comparisons reach 37.8% with Target-KNN and 40.4% with Target Sketch Matching. Here the candidate examples come from Spider, and the queries to answer come from KDBQA. The accuracy gives an indication of the difficulty of that transfer even though the skill-based settings improve on every deployable baseline in the comparison.
BIRD results also vary with the backbone and selector. With text-davinci-003, consistency with Ada reaches 40.2% execution accuracy on the development set. In the same comparison, the strongest raw-input scores are 37.7%, and Target-KNN reaches 40.0%. This is a pipeline result under the evidence and schema-grounding procedure. The selected examples help the generator produce executable answers in that setup. The evidence and the shortened schema are also part of what the generator sees, so the score describes the combined task setting.
For COGS, the results are for the sampled compositional generalization cases. With text-chat-davinci-002 on primitive substitution, consistency with Ada reaches 95.2% exact-match accuracy. Raw KNN with OpenAI Babbage reaches 88.3%, and Target Sketch Matching reaches 96.9%. On primitive structural alternation, distinctiveness with Ada reaches 97.0%. Raw-input MMR with Ada reaches 78.9%, and Target Sketch Matching reaches 95.7%. The two subtasks show that descriptions of constructions and roles can help a retriever find demonstrations in a setting where the desired answer is a logical form for a sentence.
Across the main table, the authors summarize the variant comparison as 19 wins for distinctiveness and 15 for consistency. Those counts aggregate settings with different datasets, subtasks, encoders and backbones. They support the authors' preference for trying distinctiveness, while the individual accuracies show why the choice can be consequential. A win count gives each comparison a place in the tally. It does not convey how far apart the scores are or how frequently a small change in the selected demonstrations would alter the ranking.
Math reasoning and multiple answer samples
The paper reports a smaller experiment on GSM8K, a dataset of math word problems. With text-chat-davinci-002, base Skill-KNN with SBERT scores 71.0% accuracy. Raw SBERT retrieval scores 69.9%, and random selection scores 69.1%. This is evidence of a gain outside the semantic parsing benchmarks for the tested setup. The paper's investigation of annotated operation coverage, variant behavior and robustness comes from the parsing work, so the math comparison offers a narrower view of transfer. Training Verifiers to Solve Math Word Problems
An appendix experiment asks what happens when the answer generator gets several chances to complete the same prompt. The authors keep the distinctiveness selector on Spider development with text-chat-davinci-002, set the sampling temperature to 0.7, draw 100 answer sequences and rank outputs by how frequently they occur. The top-ranked answer gives 80.3% on the reported recall measure, compared with 78.3% execution accuracy for the greedy answer. The appendix reports recall above 90% when the candidate list is taken to N = 10. A correct answer somewhere in a list is useful evidence about candidate generation. Returning that list and choosing the correct answer from it are different evaluation conditions from scoring a single greedy completion.
What the ablations show
How much annotation the rewriting prompt needs
The main annotation ablations evaluate base Skill-KNN with SBERT on Spider. The authors vary the number of manually described examples in the rewrite prompt while keeping the general retrieval and answer procedure. Starting from the default of 16, they consider prompts with 4, 8 and 12 examples. The reported curve shows modest improvements as more annotations are included. Even with 4 examples, the system retains an advantage over raw-input selection. This is evidence that the rewriter can apply the annotation format to cases beyond the ones it saw in the prompt.
The authors also vary how the annotation cases are chosen. By default they first select examples to cover SQL operations and then add examples drawn from different databases. To test reduced operation coverage, they remove the first selection stage. To test reduced database diversity, they restrict the annotations to 2 databases. Each restriction produces a small decline in the reported Spider comparison, and the method still outperforms raw-input retrieval. These interventions concern the hand-annotated examples shown to the rewriter. The answer generator still receives retrieved task examples, and the bank still has the broader range of solved problems.
The two interventions tell complementary stories. The operation-coverage test asks how much deliberate curation by the annotators contributes to the description prompt. The database restriction asks how closely the rewriting prompt depends on examples covering multiple subject areas. In both cases the generator has prior capabilities and receives several demonstrations of the intended level of detail. It can draw on both when describing a new input. The results show that the gains are robust to these specific reductions. They give no direct estimate of how performance changes for a particular operation that is absent from both the annotation prompt and the relevant parts of the bank.
A manual review gives more direct evidence about what the rewriter generates. The authors inspect 100 examples and judge 86/100 descriptions exactly correct, 12/100 close enough to need only a partial correction, and 2/100 wholly incorrect. A partial correction might involve the number of tables required for a join. Their examples include descriptions of a null condition and of selecting all columns, operations that the authors identify as going beyond the annotation examples. These observations support some generalization in the writing of descriptions. They measure the judged quality of sampled descriptions, while the execution results measure the suitability of the demonstrations retrieved through those descriptions.
When averaging and best-pair matching help
The authors propose two ways that prompt order could disturb a description. Small, frequent changes can make individual descriptions omit a detail or add a little redundant material. Averaging the vectors could suppress some of that variation. Larger occasional deviations can pull a mean away from the skill it represents. Best-pair matching can still retrieve an example on the strength of a pair in which the relevant information survived. These are proposed explanations of the variant behavior. They motivate a synthetic experiment in which the kind of disturbance is known.
In that experiment the authors use 1,000 unique embeddings of skill descriptions as the references. They add synthetic noise to construct sets of perturbed versions and check whether each scoring rule retrieves the original embedding. With zero-mean white noise, consistency gives 95.4% selection accuracy and distinctiveness gives 90.4%. With spike noise, consistency gives 81.9% and distinctiveness gives 87.9%. The outcome changes with the noise pattern. This is recovery of a reference embedding in a constructed selection problem, a different metric from accuracy at generating the SQL answer.
Retrieval variants under spike noise in the synthetic embedding experiment, selection accuracy
Best-pair matching recovers more of the original description embeddings when candidate sets contain large disturbances.
The numbers
| System or setting | selection accuracy % |
|---|---|
| Consistency Skill-KNN | 81.9 |
| Distinctiveness Skill-KNN (this paper) | 87.9 |
The authors look for a corresponding pattern in real rewrites. On Spider development they select cases for which one variant consistently succeeds across different answer generators and the other consistently fails. Their review of 23 examples finds 0.4 spike-noise samples per set where consistency wins and 1.6 per set where distinctiveness wins. The cases were deliberately selected for disagreement, so this compares two informative groups. It provides evidence for an association between conspicuous rewrite errors and relative variant performance in those cases. The overall frequency of such errors among Spider queries is a separate question.
The paper also tests the number of shuffles. With code-cushman-002 and consistency on Spider, 3 candidate descriptions give 72.8% execution accuracy and 5 give 74.7%. With 7 the score is 75.1%, and with 9 it is 75.0%. Generating more candidates takes more work, and the measured gains beyond 5 are small in this comparison. The authors choose 5 for the main setup. The controlled result explains their choice for that configuration, while other distributions of rewrite quality could change the tradeoff.
What changes in the retrieved examples
Skill-KNN sometimes scores above a selector that has access to the correct answer. The authors investigate whether the breadth of the retrieved examples could help explain this. They count the databases represented among the demonstrations selected by distinctiveness and Target-KNN. On Spider, the reported counts are 2.83 for Skill-KNN and 2.18 for Target-KNN. On Dr. Spider, they are 2.84 and 2.16, respectively. On KDBQA, they are 2.88 and 2.21. The counts measure diversity across databases in the retrieved prompts, giving a concrete way to compare the behavior of the two selectors.
An output-based selector can find a set of highly similar SQL programs. In a cross-domain experiment, a set drawn from more databases could expose the answer generator to ways of expressing a common operation across different schemas. That is the authors' hypothesis about why a skill-based selector can sometimes generate better downstream results. The database counts show that the selectors differ on this property. They do not hold the other characteristics of the selected examples fixed, so they leave the contribution of that diversity to execution accuracy unresolved.
The authors also visualize embeddings of Spider training-bank and development inputs using t-SNE, a projection that places high-dimensional vectors in a space that can be plotted. The comparison uses SBERT, the consistency variant for skill descriptions, and only cases of medium difficulty. In the raw-input plot, development examples are concentrated in parts of the space. In the skill-description plot, the authors see closer correspondence between the locations occupied by the bank and the development cases, as well as visibly more clustered representations. This is consistent with the idea that shared operations can bring training and development inputs together even when their subjects differ.
The projection is descriptive. It helps illustrate what a changed representation might do, while the retrieval itself happens in the original vector space. Visual clusters alone cannot show which input pairs moved closer under the scoring rule or which of those moves improved an answer. The diagnostic performance on Dr. Spider is direct evidence of how the complete selection procedure behaves under the benchmark's perturbations. The plot suggests a way to understand that behavior.
A final analysis considers the complexity of the retrieved demonstrations. The authors measure how many tables the demonstration's database contains and how long its SQL query is when split at spaces. Consistency retrieves examples with higher values on both measures throughout the text-to-SQL comparisons in that analysis. The authors suggest a connection to the observed differences across backbones. Some backbones may work better with simpler examples, while others may cope more readily with longer queries or larger schemas. The measured result is that the variants bring different examples into the prompt. Whether complexity determines the backbone's preference remains a hypothesis.
Limitations
Limits the authors state
The authors emphasize the computational cost of the study. The experiments use a station with 8 NVIDIA A100 GPUs. They report about 2 x 8 GPU hours for generation per 10,000 examples at inference and estimate 400 ∼ 500 x 8 GPU hours to reproduce the main results table. Avoiding an encoder training run therefore addresses a particular cost of maintaining a selector. The system still has to generate descriptions, embed them and run the answer prompts. Several candidate rewrites add to that work.
They also limit the scope of the empirical claim. The main evidence comes from cross-domain semantic parsing, where the same underlying operation can be described using different entities or vocabulary. The authors expect the benefit to be smaller when useful examples are already well identified by surface similarity. GSM8K shows a gain in one math reasoning comparison. The paper does not extend the broad parsing analyses to a comparably broad evaluation of other tasks.
The authors present consistency and distinctiveness as separate ways to use the rewrites and leave a method that incorporates both principles to future work. This matters at the level of an individual query. A set of rewrites may show broad agreement while varying on a rare but important condition. Averaging and maximum similarity act differently on that condition, and the paper's tested rules give the selector no way to adapt between them according to the reliability of the candidate descriptions for the current query.
Limits visible in the evaluation
Training-free selection still requires task-specific preparation. A human decides which descriptions should serve as examples of how to express a skill. The main SQL setup draws on operation coverage in the bank, BIRD uses special annotations with evidence, and COGS uses annotations about constructions and roles. The ablations show that this preparation can be lighter within the Spider setup. A task with a different output format or a different notion of useful structure can require a fresh decision about what the annotations should describe.
The raw-input and skill-based retrievers also receive differently prepared inputs. In text-to-SQL, the rewriter can see the schema, whereas the raw encoder generally sees the question, with evidence appended for BIRD. That is a reasonable comparison of the two complete pipelines as designed by the authors. It does leave a more specific attribution open. A gain can reflect the emphasis on operations, the opportunity to use schema information before encoding, or both. A raw-question comparison with the same encoder controls the encoder choice. It does not by itself isolate the effect of suppressing topical wording.
An accurate description of an operation does not guarantee useful neighbors. The bank must contain applicable solved examples, and the encoder must put the descriptions close enough to retrieve them. Conversely, a rough description may still retrieve a highly useful demonstration. Execution accuracy measures what happens after retrieval and answer generation, so it can establish improvement in the whole procedure without locating every individual success or failure. The human check and synthetic retrieval study examine intermediate behavior, with their own sampling and construction limits.
The oracle results have a related interpretation. Reference programs provide helpful information, but target-vector similarity and keyword overlap optimize specific scores. A set of examples with very high target similarity may offer limited variety. It can also omit a simpler demonstration that the answer generator would use more effectively. When Skill-KNN scores above an oracle, it has beaten that oracle's way of choosing examples in the reported comparison. The result does not give an upper bound on how much access to a reference answer could help a different selector.
Some results depend on deliberate restrictions in the evaluations. BIRD uses schema grounding, so useful information must survive that preprocessing as well as the skill-based retrieval. COGS uses sampled cases from selected subtasks and a transformed logical form. Its exact-match scores describe that representation and evaluation sample. Spider's split and the diagnostics built around it provide repeated views of cross-domain parsing, while KDBQA, BIRD and COGS change different aspects of the task. The benchmark suite supports a claim across those settings without making all the scores interchangeable.
The timing figures concern running the experiments. The motivation about banks that change frequently is based on the ability to avoid refitting a selector and to generate descriptions for additional entries. The paper does not report a longitudinal test in which a live bank changes and the quality and cost of maintenance are measured over time. It also uses a single generator for the rewriting stage. The range of answer backbones therefore establishes more about portability of the retrieved prompts across backbones than about how reliably another rewriter could produce the same search representations.
What came after
Later citing work addresses several parts of the same broad problem. Some of it treats demonstration selection as one component of a larger evaluation. Other work makes selection itself the object of study, asking how to combine strategies, how learned selectors work, or how to estimate what demonstrations cover. These are different connections to Skill-KNN, which locates a concrete intervention in the representation used to compare an input with an example bank.
Laskar and colleagues take an evaluation perspective in their systematic survey and critical review. The connection is to what an evaluation measures when a system's examples are chosen by a separate procedure. On Spider, changing that procedure changes execution accuracy while the answer backbone stays fixed. The survey's subject is the broader set of challenges and limitations in evaluation. Its citation places the Skill-KNN experiments in that wider discussion, without establishing a separate test of the method.
Liu and colleagues focus on the mechanics of learning-based demonstration selection. Skill-KNN supplies a point of comparison for that question because it changes the input to a fixed similarity encoder, whereas the methods discussed under learning-based selection can encode relevance through training. The relationship is about where a selector gets its criterion for a good demonstration. The later work's stated focus is the behavior of learned selection. Its title and citation establish a connection to the problem without specifying whether it uses the rewriting procedure.
Pecher and colleagues make the automatic combination of sample selection strategies their subject. The connection to Skill-KNN is at the level of selection strategy. The original paper describes ways of aggregating several descriptions within one strategy and finds that their relative performance varies across settings. Combining sample-selection strategies addresses a broader choice about which selection mechanisms to bring together. The citing relationship does not specify which Skill-KNN components, if any, participate in that combination.
Xin and colleagues frame UCS around estimating unseen coverage to improve in-context learning. Coverage also arises in Skill-KNN, where the authors curate annotation examples to span SQL operations and separately look at the diversity of retrieved demonstrations. There it is a property of the annotations or a diagnostic of the selected examples, while the retrieval scores are based on description similarity. UCS puts unseen coverage at the center of its stated problem. The two works therefore connect through a question that a nearest-neighbor score only partly addresses: how much of what a new input requires is illustrated by the demonstrations it receives.
Cite
Cite as Shengnan An, Bo Zhou, Zeqi Lin, Qiang Fu, Bei Chen, Nanning Zheng, Weizhu Chen and Jian-Guang Lou. 2023. Skill-Based Few-Shot Selection for In-Context Learning. Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing.
@inproceedings{an2023skill,
title = {{Skill-Based Few-Shot Selection for In-Context Learning}},
author = {Shengnan An, Bo Zhou, Zeqi Lin, Qiang Fu, Bei Chen, Nanning Zheng, Weizhu Chen and Jian-Guang Lou},
booktitle = {Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing},
year = {2023},
doi = {10.18653/v1/2023.emnlp-main.831},
url = {https://doi.org/10.18653/v1/2023.emnlp-main.831}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/an-2023-skill-based-few-shot-selection/