Semantic Parsing: Meaning Representation and Code Generation
What You'll Learn
- 1Describe AMR graphs and why they abstract away surface form
- 2Train a sequence-to-sequence parser with grammar-constrained decoding
- 3Score parsers with Smatch, exact match, and execution accuracy
- 4Compute sequence log-probability and perplexity for a parsed output
Semantic parsing maps a natural language utterance onto a formal object that a machine can execute: a logical form, a database query, an API call, or a program. The task matters because it is the bridge between language and action, and because a parse is checkable, so a wrong output can be diagnosed rather than merely disliked. This lesson covers Abstract Meaning Representation as a target structure, the sequence-to-sequence parsers that produce it, the grammar constraints that keep them legal, and the metrics that score them honestly.
Meaning Representation
Abstract Meaning Representation (Banarescu et al., 2013) represents a sentence as a rooted, directed acyclic graph whose nodes are PropBank predicates such as want-01 or have-org-role-91 and whose edges are labeled roles such as :ARG0 and :ARG1. Reentrancies let one entity play two roles without repeating words, and the graph drops tense, number, and articles so that paraphrases share a single form.
The official corpora are large enough to fine-tune Transformers on: AMR 2.0 (LDC2017T10) holds 39,260 sentence-graph pairs split 36,521 / 1,368 / 1,371, and AMR 3.0 (LDC2020T02) extends it to 59,255 pairs split 55,635 / 1,722 / 1,898 across newswire, forums, and proxy reports.
Sequence-to-Sequence Parsing
The dominant architecture encodes the utterance with a Transformer and decodes the linearized graph token by token, maximizing the conditional log-likelihood:
Decoding is where most practical errors appear. An unconstrained decoder can emit unbalanced parentheses or unknown predicates, so grammar-constrained decoding masks the vocabulary at each step to the tokens the partial structure still admits:
where is the language of grammar . The mask reduces per-step work from logits to the allowed subset, which for an SQL grammar is often fewer than 40 tokens, and it drives invalid-output rates to zero.
Evaluating a Graph
Structural output needs structural metrics. Smatch (Cai and Knight, 2013) finds the variable mapping that maximizes the number of shared triples between predicted and gold graphs, then reports precision, recall, and F1 over those triples:
For executable output the field prefers execution accuracy: run the predicted query against the gold database and count exact result matches, which tolerates different but equivalent SQL.
| Target | Corpus | Size | Metric | Best reported |
|---|---|---|---|---|
| AMR graph | AMR 2.0 (2017) | 39,260 pairs | Smatch F1 | 84.5 (SPRING, 2022) |
| AMR graph | AMR 3.0 (2020) | 59,255 pairs | Smatch F1 | above 83 |
| SQL query | Spider (2018) | 10,181 questions | execution accuracy | above 80 on dev |
| SQL query | WikiSQL (2017) | 87,766 questions | logical form accuracy | above 90 |
| Python program | HumanEval (2021) | 164 problems | pass at 1 | 67.0 for GPT-4 |
| Python program | MBPP (2021) | 974 problems | pass at 1 | above 75 for large models |
Worked Examples
Worked Code
import re
from itertools import permutations
def to_triples(amr):
"""Linearize AMR into (parent, role, child) triples."""
nodes, roles, out, pending = [], [], [], []
for tok in re.findall(r"\(|\)|[^\s()]+", amr):
if tok == "(":
nodes.append(None)
roles.append(pending[0] if pending else None)
pending = []
elif tok == ")":
nodes.pop(); roles.pop(); pending = []
elif tok.startswith(":"):
pending = [tok[1:]]
elif nodes and nodes[-1] is None:
nodes[-1] = tok
if roles[-1]:
out.append((nodes[-2] if len(nodes) > 1 else "root", roles[-1], tok))
elif pending:
out.append((nodes[-1], pending[0], tok)); pending = []
elif tok == "/":
pending = ["/"]
else:
nodes[-1] = tok
return set(out)
def smatch_f1(pred, gold):
"""Triple-level F1 after the best mapping of node identifiers."""
p, g = to_triples(pred), to_triples(gold)
left, right = sorted({t[0] for t in p}), sorted({t[0] for t in g})
maps = ([dict(zip(left, q)) for q in permutations(right, len(left))]
if len(left) <= len(right) else [{n: n for n in left}])
best = max(len({(m.get(a, a), r, b) for a, r, b in p} & g) for m in maps)
prec, rec = best / len(p), best / len(g)
return 2 * prec * rec / (prec + rec)
gold = "(w / want-01 :ARG0 (b / boy) :ARG1 (r / run))"
pred = gold[:-1] + " :time (n / now))"
print("Smatch F1:", round(smatch_f1(pred, gold), 3)) # 0.833
class TrieGrammarMask:
"""Mask decoder logits to tokens that keep the output grammatical."""
def __init__(self, trie, vocab_size):
self.trie, self.vocab_size = trie, vocab_size
def apply(self, logits, prefix_ids, fill=-1e9):
node = self.trie
for tok in prefix_ids:
node = node.get(tok, {})
if not node:
return list(logits)
allowed = set(node)
return [logits[i] if i in allowed else fill for i in range(len(logits))]
vocab = ["SELECT", "COUNT", "DISTINCT", "*", "WHERE", "1", "2", "0"]
grammar = {0: {2: {5: {6: {7: {}}}}}, 1: {3: {6: {}}}}
mask = TrieGrammarMask(grammar, len(vocab))
logits = [2.1, 1.4, 0.3, 1.7, 1.9, 0.1, 0.2, 0.0]
for prefix in ([], [0]):
kept = [vocab[i] for i, v in enumerate(mask.apply(logits, prefix)) if v > -1e9]
print(prefix, "->", kept) # [] -> ['SELECT', 'COUNT'], [0] -> ['DISTINCT']
Real-World Applications
- Text-to-SQL assistants - Spider's 10,181 question-query pairs train the schema-linking parsers shipped inside BI tools that answer "top five regions by revenue" as SQL.
- Voice assistants - Intent plus slot parsing turns "set a timer for nine minutes" into a typed API call, where grammar masks guarantee a valid JSON argument list.
- Repository-scale code generation - Codex 12B scored 28.8 percent pass at 1 on HumanEval while GPT-4 reaches 67.0 percent, which is why pair programming tools now default to completion.
- Knowledge graph construction - AMR parsers over newswire extract who-did-what-to-whom triples at 84.5 Smatch without a relation inventory.
đĄMask the grammar, not just the beam
Common Mistakes
Judging AMR output with BLEU
Fix: Word overlap ignores graph structure, so use Smatch with the Damonte et al. scoring tool.
Reporting exact match only on SQL
Fix: Equivalent queries differ in formatting, so report execution accuracy alongside exact match.
Training without the grammar mask
Fix: Constrained decoding both speeds training and removes the invalid-output failure mode.
Best Practices
- Linearize graphs depth first, which SPRING showed beats breadth first by up to 2 Smatch points
- Report execution accuracy for any target that can be run
- Check invalid-output rate separately from accuracy so grammar fixes stay visible
Key Takeaways
- AMR 2.0 holds 39,260 sentence-graph pairs and AMR 3.0 holds 59,255
- Constrained decoding maximizes log P(y given x) over only the strings grammar G admits
- Smatch F1 is 2 times matched triples divided by predicted plus gold triples
- Pass at 1 on HumanEval ranges from 28.8 percent for Codex 12B to 67.0 percent for GPT-4
Frequently Asked Questions
Why not just evaluate with ROUGE or BLEU?
ROUGE rewards surface overlap, and AMR deliberately deletes tense and function words, so a paraphrase with a perfect graph can score poorly on n-grams. Smatch aligns graph triples instead, which is why every AMR leaderboard since 2013 uses it.
How does grammar-constrained decoding change complexity?
An unconstrained step scores logits, often 32,000, while a masked step scores only the tokens legal in the current state. For SQL that is typically under 40 candidates, so each step is cheaper and the search never wastes beams on syntax errors.
Is code generation just semantic parsing?
Structurally yes: the utterance is a docstring and the program is the formal object. The difference is the checker, since unit tests give execution accuracy a much stronger signal than string comparison, which is why HumanEval reports pass at k.
Interview Questions
Q1: Explain how Smatch handles two graphs that use different variable names.
It searches the mapping between node identifiers that maximizes shared triples, so (a / run) and (x / run) align to the same triple and score full credit when roles match.
Q2: What breaks first when a semantic parser is moved to a new domain?
Vocabulary and grammar coverage, not the encoder; unseen predicates and column names cause most errors, which is why schema linking lifts Spider execution accuracy by several points.