🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Semantic Parsing: Meaning Representation and Code Generation

Natural Language ProcessingSemantic Parsing: Meaning Representation and Code GenerationđŸŸĸ Free Lesson

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.

TargetCorpusSizeMetricBest reported
AMR graphAMR 2.0 (2017)39,260 pairsSmatch F184.5 (SPRING, 2022)
AMR graphAMR 3.0 (2020)59,255 pairsSmatch F1above 83
SQL querySpider (2018)10,181 questionsexecution accuracyabove 80 on dev
SQL queryWikiSQL (2017)87,766 questionslogical form accuracyabove 90
Python programHumanEval (2021)164 problemspass at 167.0 for GPT-4
Python programMBPP (2021)974 problemspass at 1above 75 for large models

Worked Examples

Worked Code

python
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
python
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

Beam search alone still returns illegal structures; a trie or Earley mask applied to the logits before sampling eliminates malformed output entirely and usually improves execution accuracy by several points on Spider.

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.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-07

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement