Semantic role labeling: who did what to whom?
语义角色标注
Separate role definitions from syntax, derive constrained span selection and gradients, and test a complete small model.
semantic-role-labelingWho handed what to whom?
In the invented sentence Mina handed Jo a map on Monday, detecting three names or nouns does not tell us who gave the map. A useful representation associates handed with a giver, a recipient, a transferred object and a time. Semantic role labeling, SRL, identifies such predicate–argument relations.
Change the sentence to A map was handed to Jo by Mina. The grammatical subject changes, but the giver need not. Syntax supplies evidence; a subject label is not itself a semantic role. Gildea and Jurafsky’s statistical system used cues including phrase type, position, voice and head words. Its initial role-classification experiment supplied argument boundaries, separating label choice from finding the arguments. Method and features, §4
A label inventory is part of the task. FrameNet associates roles with semantic frames. PropBank assigns numbered roles within a predicate’s frameset: ARG0 often resembles an agent and ARG1 a patient or theme, but the numbers are not universal definitions. Higher-numbered roles especially require that predicate’s documentation. Role inventories, §2 PropBank, §3
For our invented transfer frame, declare ARG0=giver, ARG1=object, ARG2=recipient and ARGM-TMP=time. These are teaching definitions, not a claim that we inspected the actual hand frames file. The program receives the predicate position and candidate spans. It answers which candidates can coexist; it does not discover them from raw text.
Choose a compatible set, not a label in isolation
State the output space
Number tokens from zero and write spans as half-open intervals [a,b). The example has seven tokens and predicate index1. Its target arguments are [0,1), [2,3), [3,5) and [5,7). Each candidate c supplies a start, end, role and feature vector x_c. With weight vector w, a selected set Y receives an additive score:
Within this one predicate’s output, require non-overlapping spans, exclude the predicate token, and allow each declared core role at most once. Modifiers may repeat. An empty set is legal; no role is mandatory. Different predicates can reuse a token in their own argument structures. These are our decoder’s assumptions, not the full PropBank annotation rules.
Let V be the finite family of compatible sets. A conditional log-linear model normalizes whole sets:
Taking the largest candidate scores independently can select overlapping spans or duplicate ARG0. Normalizing each candidate independently also describes a different output space.
A dynamic program with memory for used roles
A state (t,M) says that tokens before t have been processed and bitmask M records used core roles. Start at (0,0). One edge skips token t with score0. A candidate starting at t jumps to its end, adding its score and setting its role bit if that bit is unused; a modifier sets no bit. Every compatible set has exactly one path: skip its uncovered tokens and take each selected span once.
For an edge e from u to v with score s_e, accumulate forward log-mass alpha. Initialize alpha(0,0)=0 and all other entries to negative infinity. Sum over every final mask; no extra end score is used.
Replacing logaddexp by max gives Viterbi scores and backpointers. For marginals, compute backward log-mass beta, initialized to0 at every final mask. A candidate may occur on edges from several masks, so add all its edge probabilities:
Given a legal gold set G, negative log-likelihood has a useful gradient: expected selected features minus gold features. If matrix X has candidate features as rows and g is their gold indicator vector:
A three-candidate check
Take a=[0,1)/ARG0, b=[1,2)/ARG0 and c=[1,2)/ARG1 with exponentiated scores2,3,5. Legal sets are empty, a, b, c and {a,c}. The pair {a,b} violates role uniqueness; {b,c} overlaps.
With n tokens, C candidates and R unique roles, each forward, backward or marginal pass costs O((n+C)2^R). Tables and backpointers use O(n2^R+C) space. Linear scoring and its gradient add O(CD) work for D features. These are the implemented dense-mask bounds, not a claim that every SRL system uses exponential role states.
Run the complete constrained example
Python3.12 and NumPy1.26 suffice; there are no downloads, models or API calls. Run the block as one file. Candidate boundaries and three numeric features per candidate are deliberately supplied. The first feature contains an invented base score; the other two distinguish compatible and competing choices. The fitting exercise therefore demonstrates an objective and its derivatives, not learned language understanding.
The initial best set selects Mina/ARG0, Jo/ARG2, a map/ARG1 and on Monday/ARGM-TMP, scoring11.5. A competing Jo/ARG0 has the largest single score5, but choosing it prevents a better combination. Fifty deterministic line-search steps reduce this example’s loss from0.823570 to0.007673. The printed marginals, hand case and entire loss trace can be checked independently.
"""Original span-selection SRL teaching model; gold predicate/candidates supplied."""
import json, math
import numpy as np
def validate(n, predicate, spans, scores, core):
if type(n) is not int or not 0 <= n <= 80: raise ValueError('token count must be 0..80')
if predicate is not None and (type(predicate) is not int or not 0 <= predicate < n):
raise ValueError('predicate index outside sentence')
if len(spans) > 2000 or len(core) > 8 or len(set(core)) != len(core):
raise ValueError('candidate/unique-role limit or duplicate core role')
if any(not isinstance(r,str) or not r for r in core): raise ValueError('invalid core role')
normalized=[]
for item in spans:
if len(item) != 3: raise ValueError('span needs start,end,role')
start,end,role=item
if type(start) is not int or type(end) is not int or not 0 <= start < end <= n:
raise ValueError('invalid half-open span')
if not isinstance(role,str) or not role: raise ValueError('invalid role')
if predicate is not None and start <= predicate < end: raise ValueError('argument includes predicate')
normalized.append((start,end,role))
if len(set(normalized)) != len(normalized): raise ValueError('duplicate labelled candidate')
scores=np.asarray(scores,dtype=float)
if scores.shape != (len(spans),) or not np.isfinite(scores).all() or np.any(np.abs(scores)>1e100):
raise ValueError('finite bounded score vector required')
return normalized,scores
def infer(n, predicate, spans, scores, core=('ARG0','ARG1','ARG2')):
spans,scores=validate(n,predicate,spans,scores,core)
bits={role:1<<i for i,role in enumerate(core)};states=1<<len(core)
starts=[[] for _ in range(n)]
for index,(start,end,role) in enumerate(spans): starts[start].append((index,end,bits.get(role,0)))
def edges(position,mask):
yield position+1,mask,0.,-1
for index,end,bit in starts[position]:
if not mask & bit: yield end,mask|bit,float(scores[index]),index
alpha=np.full((n+1,states),-np.inf);best=alpha.copy();alpha[0,0]=best[0,0]=0.
previous={}
for position in range(n):
for mask in range(states):
if not np.isfinite(alpha[position,mask]): continue
for end,next_mask,score,index in edges(position,mask):
alpha[end,next_mask]=np.logaddexp(alpha[end,next_mask],alpha[position,mask]+score)
value=best[position,mask]+score
if value > best[end,next_mask]:
best[end,next_mask]=value;previous[end,next_mask]=(position,mask,index)
logz=float(np.logaddexp.reduce(alpha[n]));final=int(np.argmax(best[n]));best_score=float(best[n,final])
selected=[];position=n;mask=final
while position:
position,mask,index=previous[position,mask]
if index>=0:selected.append(index)
selected.reverse()
beta=np.full_like(alpha,-np.inf);beta[n,:]=0.
for position in range(n-1,-1,-1):
for mask in range(states):
for end,next_mask,score,index in edges(position,mask):
beta[position,mask]=np.logaddexp(beta[position,mask],score+beta[end,next_mask])
marginals=np.zeros(len(spans))
for position in range(n):
for mask in range(states):
if not np.isfinite(alpha[position,mask]):continue
for end,next_mask,score,index in edges(position,mask):
if index>=0:marginals[index]+=math.exp(float(alpha[position,mask]+score+beta[end,next_mask]-logz))
return {'log_partition':logz,'best_score':best_score,'selected':selected,'marginals':marginals.tolist()}
def loss_gradient(n,predicate,spans,features,weights,gold,core=('ARG0','ARG1','ARG2')):
x=np.asarray(features,dtype=float);w=np.asarray(weights,dtype=float)
if w.ndim!=1 or not 1<=len(w)<=64 or x.shape!=(len(spans),len(w)):
raise ValueError('feature/weight shapes')
if not np.isfinite(x).all() or not np.isfinite(w).all():raise ValueError('finite parameters required')
result=infer(n,predicate,spans,x@w,core)
if any(type(i) is not int or not 0<=i<len(spans) for i in gold) or len(set(gold))!=len(gold):
raise ValueError('invalid gold indices')
chosen=sorted((spans[i] for i in gold),key=lambda s:s[0]);used=[]
for k,(start,end,role) in enumerate(chosen):
if k and start<chosen[k-1][1]:raise ValueError('overlapping gold arguments')
if role in core:
if role in used:raise ValueError('repeated gold core role')
used.append(role)
indicator=np.zeros(len(spans));indicator[list(gold)]=1
loss=result['log_partition']-float(indicator@(x@w))
gradient=x.T@(np.asarray(result['marginals'])-indicator)
return loss,gradient,result
def fit(example,steps=50):
if type(steps) is not int or not 0<=steps<=1000:raise ValueError('steps must be 0..1000')
w=np.array([1.,0.,0.]);trace=[]
args=(example['n'],example['predicate'],example['spans'],example['features'])
for step in range(steps+1):
loss,gradient,_=loss_gradient(*args,w,example['gold']);trace.append(loss)
if step==steps:break
rate=1.
for _ in range(40):
candidate=w-rate*gradient;new,_,_=loss_gradient(*args,candidate,example['gold'])
if new<=loss-1e-4*rate*float(gradient@gradient):w=candidate;break
rate*=.5
else:raise ArithmeticError('line search did not accept a step')
return w,trace
def demo():
spans=[(0,1,'ARG0'),(2,3,'ARG0'),(2,3,'ARG2'),(3,5,'ARG1'),(3,5,'ARG2'),(2,5,'ARG1'),(5,7,'ARGM-TMP')]
example={'tokens':['Mina','handed','Jo','a','map','on','Monday'],'n':7,'predicate':1,'spans':spans,
'features':[[4,1,0],[5,0,1],[3.5,1,0],[3,1,0],[3.8,0,1],[5,0,1],[1,1,0]],'gold':[0,2,3,6]}
initial=infer(7,1,spans,np.asarray(example['features'])@np.array([1.,0.,0.]))
weights,trace=fit(example);final=infer(7,1,spans,np.asarray(example['features'])@weights)
hand=infer(2,None,[(0,1,'ARG0'),(1,2,'ARG0'),(1,2,'ARG1')],np.log([2.,3.,5.]))
return {'example':example,'initial':initial,'final':final,'weights':weights.tolist(),'loss_trace':trace,
'hand':hand,'scope':'Given predicate and candidates; original linear constrained toy fit, not an automatic parser or corpus benchmark.'}
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
The code caps tokens at80, candidates at2,000 and unique roles at8. It rejects duplicate labelled candidates, spans covering the predicate, overlapping gold arguments, non-finite scores and repeated gold core roles. The decoder permits repeated modifiers and an empty answer. A training iteration can try up to40 step sizes; that bound is not a convergence guarantee.
A correct decoder can still label the wrong event
If the candidate list omits a map, no score can recover its exact boundary. Predicate detection, predicate sense selection, candidate generation and language representation are separate sources of error. Discontinuous arguments, continuation/reference labels, implicit participants and overlapping annotation conventions need a richer output space. Do not silently remove these cases from an evaluation and call the result general SRL.
Semantic plausibility is not evidence that an event happened. Roles can describe a negated, hypothetical or quoted event. A downstream information-extraction system must preserve those distinctions. PropBank includes negation and modality among its general annotation labels; our example does not implement their interpretation. ArgM categories, §3
With predicate identity fixed, exact labelled-span evaluation counts a correct boundary with a wrong role as an error. Micro precision and recall aggregate counts before taking their ratio. Report whether predicates and boundaries were supplied, the label inventory, and the test split.
Zero-denominator policies must be explicit. Accuracy on supplied candidates and end-to-end labelled-span F1 are not interchangeable.
Predict, calculate, change and evaluate
- In the active/passive sentence pair, must ARG0 move to the new grammatical subject?
Answer: No. Under the declared transfer frame, Mina remains the giver. The grammatical subject changes to the map, so a subject-only rule would fail. Role numbers depend on the frame definition.
- In the three-candidate example, remove ARG0 uniqueness while keeping non-overlap. What changes?
Answer: {a,b} becomes legal and adds mass6, so Z becomes27. Its probability was exactly0 under the old constraint. The old gold-set loss was log(21/10); using the relaxed model changes it to log(27/10).
- In the initial seven-token example, increase only the score of Jo a map/ARG1. When does it beat separate Jo/ARG2 and a map/ARG1?
Answer: The separate spans contribute3.5+3=6.5. Above6.5 the long candidate wins that comparison; at6.5 they tie and the declared implementation’s deterministic tie handling selects one. Mina and the time span contribute equally to both alternatives. This change suppresses the recipient role without breaking the constraints.
- Gold has four labelled spans. A system outputs four, three exact and one with the wrong boundary. What is F1, and what remains untested?
Answer: TP=3, FP=1 and FN=1, giving P=R=F1=0.75. The number does not establish predicate detection, out-of-domain performance or the truth of the described event.
From syntactic cues to learned representations
Gildea and Jurafsky’s 2002 study makes the feature pipeline and boundary assumption explicit. PropBank’s 2005 account explains why annotation conventions and framesets are part of the problem, rather than clerical details. They support different parts of this article; neither is the source of our custom role-mask decoder. Statistical features Annotation scheme
To extend the example, retain its output contract and replace supplied numeric features with representations from a contextual encoder. Then evaluate candidate recall separately from label choice. Constituency parsing provides phrase structure; dependency parsing supplies word relations. Neither alone specifies who filled the semantic roles. Follow the information-extraction topic for the larger task of turning statements into records.
Make a prediction, then check
Two disjoint candidates both receive ARG0. What does the declared decoder require?
Learning objectives
- Separate predicate sense, argument boundaries and semantic role labels.
- Derive a normalized distribution over compatible labelled spans.
- Compute global decoding, span marginals and linear-score gradients.
- Explain the limits of supplied candidates and exact-span evaluation.
Prerequisites & connections
Explore related knowledge →References
- Automatic Labeling of Semantic Roles
Daniel Gildea and Daniel Jurafsky · 2002 - The Proposition Bank: An Annotated Corpus of Semantic Roles
Martha Palmer, Daniel Gildea and Paul Kingsbury · 2005
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-12 · Single AI author checked eight paired equations and four explained exercises against scoped Gildea/Jurafsky and PropBank passages. Given predicates and spans; optional unique core roles, repeated modifiers, non-overlap and predicate exclusion. Independent subset enumeration validates partition, marginals, maximum set and all linear-score gradients. Hand Z=21, marginals12/21,3/21,15/21 and alternative threshold6.5 checked. Toy training is not automatic full SRL or a corpus result.
- Single AI author checked eight paired equations and four explained exercises against scoped Gildea/Jurafsky and PropBank passages. Given predicates and spans; optional unique core roles, repeated modifiers, non-overlap and predicate exclusion. Independent subset enumeration validates partition, marginals, maximum set and all linear-score gradients. Hand Z=21, marginals12/21,3/21,15/21 and alternative threshold6.5 checked. Toy training is not automatic full SRL or a corpus result.
- Four original computed SVGs bind exact bilingual MDX. Eleven figure checks and36 isolated language/width cases with four fallback fonts passed; six actual desktop/mobile screenshots inspected by this AI author. This is separate from final full-page browser acceptance, with no human peer-review claim.
- Post-freeze presentation correction: literal-set delimiters escaped after an actual Astro prerender failure. Frozen original, failure log and before/after patch retained at editorial/corrections/011a-literal-sets; program, equations and wording unchanged. Corrected-render validation is recorded separately.
Source locations checked:
- Automatic Labeling of Semantic Roles · Scoped text144–215,414–456,727–788: frame roles, supplied boundaries, phrase/position/voice/head features and split opening. Not full estimator, experiments or history.
- The Proposition Bank: An Annotated Corpus of Semantic Roles · Scoped §3 text231–355, rolesets/framesets and ArgM table; physical page5 (printed75) visually inspected. Verb-specific numbering; no full annotation or corpus reproduction.
Related topics