Semantic parsing: a correct answer can come from the wrong program
语义解析
Build a bounded compositional parser and typed executor, derive learning from answers, and expose the ambiguity that answer-only supervision leaves behind.
semantic-parsingCounting the right objects requires choosing what the question means
An invented catalogue lists objects by color, shape, size and weight. Ask “How many light objects?” The word light might mean low weight or pale color. Suppose this task’s annotation protocol intends low weight. If the catalogue happens to contain two lightweight objects and two pale objects, both interpretations return 2. A program that simply returns the constant 2 also passes this one test.
Semantic parsing maps an utterance to a machine-interpretable meaning representation. That representation might be a logical form, a database query or another typed program. Executing it in a supplied world produces an answer. Syntactic parsing instead describes linguistic structure; an executable interpretation must also connect words to predicates, arguments and operations. Task definition
For a narrow catalogue, a controlled form with explicit fields is a useful baseline. A semantic parser adds value when users can compose requests in language, but its input coverage and ambiguity policy must be stated. The program here accepts a small English-like query grammar, keeps lexical alternatives and evaluates typed expressions. It does not learn an unrestricted language encoder.
Liang, Jordan and Klein study learning from question–answer pairs with a latent logical form. Dong and Lapata study neural mappings from utterances to logical-form sequences or trees using paired meaning representations. These supervision settings provide different evidence. A target program reveals more structure than one answer obtained in one database. Latent logical forms Paired meaning representations
Separate parsing, execution and the supervision signal
Let x be the utterance, z a candidate program and w the supplied world. A typed executor determines its denotation, or computed meaning:
Our expressions filter sets of object IDs, combine them with intersection, union and complement, then optionally count them or test whether they are nonempty. A set, an integer and a Boolean are different output types. Treating Boolean true as integer 1 merely because a programming language compares them as equal would corrupt answer supervision.
The controlled grammar gives not higher precedence than and, and and higher precedence than or; parentheses override the order. For example, pale or red and square selects pale objects together with objects that are both red and square. (pale or red) and square keeps only squares. The lexicon gives light two predicate alternatives instead of silently choosing one.
Given a finite candidate set C(x), assign each program a feature vector and score it with parameters theta:
Candidate generation already depends on the input. Our features count particular predicate choices, a deliberately added constant and logical operators. They are a small shared scoring model, not representations learned from raw sentences. The DCS paper uses a log-linear distribution over its own logical forms; this example borrows the learning question while using a different grammar and exact enumeration. Model and learning, printed page 596
With only answer y available, collect the candidates that execute to that answer with the correct type. The answer-supervised loss is:
This rewards probability assigned to any accepted execution, not necessarily to the intended reasoning. If no candidate returns the answer, the finite model gives it zero probability. Our implementation reports an error so the missing candidate or annotation can be investigated; it does not silently count the example as learned.
Differentiate the two log-sum-exp terms. Let q normalize the same scores only over the accepted candidates:
The gradient compares the feature expectation under all candidates with the expectation under answer-compatible candidates. It has no direct way to distinguish two programs that always receive the same training answers. Full logical-form supervision would instead select the annotated program and optimize its probability.
In world A, both light predicates and the optional constant program return 2. Then G equals the whole candidate set:
Every parameter setting fits this answer, including one that strongly prefers the constant. In world B, only one object is lightweight while two remain pale. Under the declared intended sense, the correct answer is now 1. The constant and pale-color interpretations fail. Adding B with its answer supplies a distinguishing training constraint; after adding it, B is no longer held-out evaluation data.
Prediction introduces another choice. Selecting the single best program need not yield the most probable answer after grouping programs by denotation:
For probabilities [3/7,2/7,2/7] on lightweight-count, pale-count and constant 2, the best program answers 1 in world B. The last two programs together assign answer 2 probability 4/7, so marginal-answer prediction returns 2. The DCS paper describes prediction that sums over latent forms; report which decision rule a comparison uses. Prediction after training
Parse controlled expressions and inspect every candidate
The complete original program uses Python 3.12 and NumPy 1.26.4. Input forms begin with which, how many or are any, followed by a supported adjective expression and objects. This is a declared command grammar, not a claim to understand arbitrary English questions. Unknown characters, words and malformed expressions are rejected rather than dropped.
"""Original bounded grammar, typed executor and denotation-supervised parser.
English toy queries use a supplied lexicon. No neural encoder, SQL service or
reproduction of DCS/SEQ2TREE. Optional constant programs expose spurious fits.
"""
import json
import re
import numpy as np
FIELDS=('color','shape','size','weight')
LEXICON={'red':[('color','red')],'blue':[('color','blue')],'pale':[('color','pale')],
'light':[('weight','light'),('color','pale')],'heavy':[('weight','heavy')],
'round':[('shape','circle')],'square':[('shape','square')],
'small':[('size','small')],'large':[('size','large')]}
FEATURES=('color:pale','weight:light','literal','other','and','or','not')
def programs(query,constants=False):
if not isinstance(query,str) or len(query)>500 or not re.fullmatch(r'[A-Za-z ()]+\??',query):raise ValueError('Use the declared English query grammar')
words=re.findall(r'[a-z]+|[()]',query.lower())
if len(words)>40:raise ValueError('Query token cap exceeded')
if words[:2]==['how','many']:kind='count';words=words[2:]
elif words[:1]==['which']:kind='select';words=words[1:]
elif words[:2]==['are','any']:kind='exists';words=words[2:]
else:raise ValueError('Unknown question form')
if not words or words[-1]!='objects':raise ValueError('Queries must end in objects')
words=words[:-1];position=0
def combine(op,left,right):
result=[(op,a,b) for a in left for b in right]
if len(result)>64:raise ValueError('Ambiguity cap exceeded')
return result
def atom(depth):
nonlocal position
if depth>12 or position>=len(words):raise ValueError('Incomplete or excessively nested expression')
word=words[position];position+=1
if word=='not':return [('not',x) for x in atom(depth+1)]
if word=='(':
result=expression(depth+1)
if position>=len(words) or words[position]!=')':raise ValueError('Unclosed parenthesis')
position+=1;return result
if word not in LEXICON:raise ValueError('Unknown adjective')
return [('eq',field,value) for field,value in LEXICON[word]]
def term(depth):
nonlocal position
left=atom(depth)
while position<len(words) and words[position]=='and':
position+=1;left=combine('and',left,atom(depth))
return left
def expression(depth):
nonlocal position
left=term(depth)
while position<len(words) and words[position]=='or':
position+=1;left=combine('or',left,term(depth))
return left
forms=expression(0)
if position!=len(words):raise ValueError('Unexpected trailing tokens')
result=[(kind,p) for p in forms]
if constants:
if kind!='count':raise ValueError('Spurious integer constants are only defined for count questions')
result.append(('literal',2))
return result
def world(rows):
rows=[dict(r) for r in rows]
if not 1<=len(rows)<=32:raise ValueError('Use 1..32 invented objects')
if any(set(r)!=set(FIELDS)|{'id'} or any(not isinstance(v,str) or not v or len(v)>40 for v in r.values()) for r in rows):raise ValueError('Complete short string-valued records required')
if len({r['id'] for r in rows})!=len(rows):raise ValueError('Object IDs must be unique')
return rows
def result_type(p,depth=0):
if not isinstance(p,tuple) or not p or depth>20:raise ValueError('Invalid bounded logical form')
op=p[0]
if op=='eq' and len(p)==3 and p[1] in FIELDS and isinstance(p[2],str):return 'set'
if op=='literal' and len(p)==2 and type(p[1]) is int and 0<=p[1]<=32:return 'int'
if op in ('not','select','count','exists') and len(p)==2 and result_type(p[1],depth+1)=='set':
return {'not':'set','select':'set','count':'int','exists':'bool'}[op]
if op in ('and','or') and len(p)==3 and result_type(p[1],depth+1)==result_type(p[2],depth+1)=='set':return 'set'
raise ValueError('Ill-typed or unsupported logical form')
def execute(p,rows):
rows=world(rows);result_type(p);universe=frozenset(r['id'] for r in rows)
def visit(p):
op=p[0]
if op=='eq':return frozenset(r['id'] for r in rows if r[p[1]]==p[2])
if op=='literal':return p[1]
if op=='not':return universe-visit(p[1])
if op=='and':return visit(p[1])&visit(p[2])
if op=='or':return visit(p[1])|visit(p[2])
if op=='select':return visit(p[1])
if op=='count':return len(visit(p[1]))
return bool(visit(p[1]))
return visit(p)
def features(forms):
def visit(p,x):
if p[0]=='eq':key=p[1]+':'+p[2];x[FEATURES.index(key) if key in FEATURES else 3]+=1
elif p[0]=='literal':x[2]+=1
else:
if p[0] in FEATURES:x[FEATURES.index(p[0])]+=1
for child in p[1:]:visit(child,x)
rows=[]
for p in forms:
result_type(p);x=np.zeros(len(FEATURES));visit(p,x);rows.append(x)
if not 1<=len(rows)<=65:raise ValueError('Use a bounded nonempty candidate list')
return np.array(rows)
def distribution(theta,forms):
theta=np.asarray(theta,float)
if theta.shape!=(len(FEATURES),) or not np.isfinite(theta).all() or (np.abs(theta)>100).any():raise ValueError('Bounded feature weights required')
x=features(forms);scores=x@theta;shift=scores.max();weights=np.exp(scores-shift);z=weights.sum()
return dict(features=x,probabilities=weights/z,log_partition=float(shift+np.log(z)),scores=scores)
def equal(a,b):return type(a) is type(b) and a==b
def loss_grad(theta,forms,rows,answer):
d=distribution(theta,forms);mask=np.array([equal(execute(p,rows),answer) for p in forms])
if not mask.any():raise ValueError('The candidate set contains no correct typed denotation')
selected=d['scores'][mask];maximum=selected.max();w=np.exp(selected-maximum);posterior=w/w.sum()
gradient=d['probabilities']@d['features']-posterior@d['features'][mask]
return dict(loss=float(d['log_partition']-maximum-np.log(w.sum())),gradient=gradient,correct_candidates=np.flatnonzero(mask).tolist())
def predict(theta,forms,rows):
d=distribution(theta,forms);index=int(np.argmax(d['scores']));groups={}
for p,prob in zip(forms,d['probabilities']):
value=execute(p,rows);key=(type(value).__name__,tuple(sorted(value)) if isinstance(value,frozenset) else value)
groups[key]=groups.get(key,0.)+float(prob)
answers=[dict(type=key[0],answer=list(key[1]) if key[0]=='frozenset' else key[1],probability=value) for key,value in groups.items()]
best=max(answers,key=lambda x:x['probability'])
value=execute(forms[index],rows)
return dict(best_program=forms[index],program_answer=sorted(value) if isinstance(value,frozenset) else value,
marginal_answer=best['answer'],answer_distribution=answers,probabilities=d['probabilities'].tolist())
def demo():
a=world([dict(id='a',color='pale',shape='circle',size='small',weight='light'),
dict(id='b',color='pale',shape='square',size='large',weight='light'),
dict(id='c',color='red',shape='circle',size='large',weight='heavy')])
b=[dict(x) for x in a];b[1]['weight']='heavy'
forms=programs('how many light objects?',constants=True);initial=np.array([1.,0.,2.,0.,0.,0.,0.])
before=loss_grad(initial,forms,a,2);theta=initial.copy();curve=[]
for step in range(101):
first=loss_grad(theta,forms,a,2);second=loss_grad(theta,forms,b,1)
curve.append((first['loss']+second['loss'])/2)
if step<100:theta-=.4*(first['gradient']+second['gradient'])/2
marginal=np.zeros(7);marginal[1]=np.log(1.5)
return dict(query='how many light objects?',forms=forms,world_a=a,world_b=b,
initial_weights=initial.tolist(),initial_training_loss=before['loss'],initial_training_gradient=before['gradient'].tolist(),
initial_on_a=predict(initial,forms,a),initial_on_b=predict(initial,forms,b),
training_loss=curve,trained_weights=theta.tolist(),trained_on_b=predict(theta,forms,b),
marginal_vs_program=predict(marginal,forms,b),
conditions='Handwritten lexical candidates; an optional constant2 is deliberately spurious. World B becomes training data in the second experiment, not a held-out generalization claim.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
The typed executor never evaluates Python supplied by a user or sends SQL to a service. It reads a bounded in-memory catalogue. The optional constant candidate is inserted only for counting questions to demonstrate spurious answer fits; it is not justified as a semantic interpretation of the utterance.
Initial feature weights prefer constant 2. The world-A training loss and gradient are zero, while the same program gives the wrong intended answer on B. A second experiment trains on both A and B for 100 updates and selects the lightweight interpretation on B. The output retains both experiments and the separate marginal-versus-program example, so changing the supervision is visible.
Independent checks cover operator precedence, negation and parentheses, exact set/integer/Boolean distinctions, every feature derivative by central differences, missing correct candidates and reordered candidate lists. Reordering floating-point sums can change the last few bits; probability comparisons use an explicit tolerance while answer identities remain exact.
Candidate generation can grow with lexical ambiguity and composition. The program caps ordinary candidates at 64, with at most one extra constant. Queries have at most 40 tokens and parsing depth 12; worlds have at most 32 objects. For C candidates with tree size K and R records, the simple set executor costs roughly O(CKR), with O(C(K+F)) feature/scoring work for F features. These bounds describe this enumerator, not DCS or a neural tree decoder.
Execution success is weaker than semantic generalization
A well-typed program may still bind the wrong relation, choose the wrong word sense or omit a condition. Type checking rules out some invalid compositions; it cannot supply the user’s intended interpretation. Similarly, exact answer match in one world may accept a constant or another accidental solution.
Evaluate both the output contract and the supervision setting. Program exact match can reject semantically equivalent expressions, while execution accuracy can accept programs that coincide only on the tested database. Counterfactual worlds with changed records help expose the latter problem. Keep any new worlds used for training separate from those used to measure generalization.
Template, schema and entity overlap also matter when splitting data. A random utterance split can leave near-identical programs on both sides; a compositional or new-schema split asks a harder question. State whether entities, schemas, executable environments and examples are available during candidate generation or tuning. Our catalogue schema and lexical alternatives are all supplied in advance.
Neural sequence or tree decoders can expand language coverage, but they introduce their own search, syntax and grounding failures. The historical lang2logic implementation provides concrete sequence/tree and attention configurations; it is a reference for that research approach, not a dependency of this program. Neural representation mapping Pinned implementation
Test the meaning rather than only the answer string
-
Why must an executor distinguish an integer answer 1 from Boolean true?
Answer: They answer different kinds of questions: a count versus an existence test. Accepting them as interchangeable can make an incorrectly typed program appear correct. The example compares both type and value.
-
All three candidates return 2 in world A. What can answer-only likelihood learn about which one is intended?
Answer: Nothing from that example alone. Their total accepted probability is 1 for every parameter setting, so loss and gradient are zero. A distinguishing world, program annotation or other supervision is needed.
-
Candidate probabilities are [3/7,2/7,2/7]; their answers are [1,2,2]. What do best-program and marginal-answer prediction return?
Answer: Best-program prediction returns 1. Marginal-answer prediction returns 2 because its two programs contribute 4/7 in total. State the prediction rule before comparing accuracy.
-
After using world B and answer 1 to retrain the parser, can a correct answer on B demonstrate held-out generalization?
Answer: No. B now supplies training evidence. Report the improved fit as such and evaluate on additional untouched worlds or compositions. Otherwise the test has become part of the learning procedure.
What changes when the logical form is observed?
The DCS work uses a latent representation and answer supervision, with approximate candidate search in its own semantic formalism. The neural-attention work learns sequence or tree outputs from paired meaning representations. Read the representation, supervision and decoding assumptions together; a reported answer score does not make these settings equivalent. DCS learning and prediction Neural attention
This article’s controlled grammar, feature model, executor and worlds isolate those distinctions with exact small computations. Extending it to realistic questions requires better coverage and interpretation evidence, while preserving the distinction between a valid program, a correct execution and the intended meaning.
Make a prediction, then check
All candidates return 2 in the training world. What does answer-only likelihood establish?
Learning objectives
- Trace a controlled utterance through logical form and typed execution.
- Derive answer-supervised marginal loss and its feature gradient.
- Explain why a correct denotation can leave the program unidentified.
- Distinguish best-program from marginal-answer prediction.
Prerequisites & connections
Explore related knowledge →References
- Learning Dependency-Based Compositional Semantics
Percy Liang, Michael I. Jordan, Dan Klein · 2011 - Language to Logical Form with Neural Attention
Li Dong, Mirella Lapata · 2016 - Language to Logical Form: pinned implementation README and MIT license
Li Dong · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-13 · Single AI author checked a controlled grammar and typed execution against scoped Liang answer marginalization and Dong neural semantic parsing context. Six paired equations and four explained exercises: program normalization, denotation marginal likelihood, expected-feature gradient, finite differences, spurious constants and program versus answer MAP. A and B are both training worlds after fitting; this is not DCS or neural parsing reproduction.
- Typed bool/int distinctions, finite grammar limits, operator precedence, spurious-answer supervision, independent feature-gradient differences and answer marginalization checked. Initial exact floating-probability comparison and later zero-loss assertion corrections preserved; programs unchanged.
- Four computed SVGs bind exact bilingual MDX. The four-topic group passed nine numeric/encoding checks and 24 isolated language/width cases with four fallback fonts; eight actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.
Source locations checked:
- Learning Dependency-Based Compositional Semantics · Abstract and visually read PDF page7, printed596: type filtering, log-linear forms, marginal answer supervision, approximate candidate search and answer marginal prediction. Original finite grammar here, not DCS replication.
- Language to Logical Form with Neural Attention · Title/authors, abstract and opening introduction layout12–37: attention encoder-decoder with sequence/tree meaning outputs; official code link291–292. Detailed decoder and experiments not reproduced.
- Language to Logical Form: pinned implementation README and MIT license · Commit 2019-11-09; README 1–25 and visible mode lines 41–74, full MIT license read. Historical Torch7 sequence/tree modes; no environment changes or upstream execution.
Related topics