Contrastive estimation¶
Overview¶
For an observed word \(x\), contrastive estimation chooses a neighborhood \(N(x)\) that contains \(x\). Let \(W_\theta(y)\) be the sum of the unnormalized weights of all model paths that emit \(y\). The training objective for one observation is
QVR source¶
The model relation assigns weights to paths that read candidate words. The script in Try it builds a neighborhood relation and joins it to this model.
object Symbols : FinSet 2
relation model [algebra=logprob, states=11]
input Symbols
initial 0 [weight=unit_weight]
arc 0 -> 1 [labels=(0), weight=feature]
arc 1 -> 2 [labels=(0), weight=unit_weight]
arc 1 -> 2 [labels=(0), weight=feature]
arc 2 -> 3 [labels=(1), weight=unit_weight]
arc 0 -> 4 [labels=(0), weight=unit_weight]
arc 4 -> 5 [labels=(0), weight=unit_weight]
arc 1 -> 6 [labels=(1), weight=unit_weight]
arc 6 -> 7 [labels=(eps), weight=feature]
arc 7 -> 8 [labels=(0), weight=feature]
arc 0 -> 9 [labels=(1), weight=feature]
arc 9 -> 10 [labels=(1), weight=feature]
final 3 [weight=unit_weight]
final 5 [weight=unit_weight]
final 6 [weight=unit_weight]
final 8 [weight=unit_weight]
final 10 [weight=unit_weight]
Understanding the model¶
The neighborhood in this example contains \(x\), the results of deleting one symbol, and the results of swapping two adjacent symbols. If two deletions produce the same word, that word contributes once to the denominator. Each of its distinct model paths still contributes its weight. The paper calls this neighborhood DELORTRANS1. Smith and Eisner (2005), §§3–4.
The Python code constructs a unit-weight trie and passes it to QVR as a two-tape relation. Its first tape consumes the observed context \(x\). Its second emits a candidate \(y\). QVR joins this relation to a latent model along the candidate tape. Each model path emitting \(y\in N(x)\) has one compatible trie path. The filtered join represents that pair once, including when either operand takes epsilon steps. Scoring both tapes gives \(W_\theta(x)\) when \(y=x\). Projection erases the candidate labels and retains the individual path weights, giving the neighborhood sum at the same context. Both scores use the model's original parameter.
Walkthrough¶
At the initial parameter, the two partitions have masses 2 and 5. Compare the objective and derivative with enumeration, then omit the transposed word and admit a word outside the neighborhood in separate runs.
Try it¶
import math
import torch
from quivers.core.relations import RelationLimitError
from quivers.dsl import Compiler, parse
from quivers.qiec import (
FixedRelationRuntimeProvider,
FixedTransformedRelationRequest,
ParameterId,
RuntimeConfiguration,
dumps,
loads,
run_named,
)
def deletion_or_swap(word, *, max_length, max_neighbors):
if len(word) > max_length:
raise ValueError("observed word exceeds max_length")
neighbors = {}
def retain(candidate):
if candidate not in neighbors:
if len(neighbors) >= max_neighbors:
raise ValueError("neighborhood exceeds max_neighbors")
neighbors[candidate] = None
retain(word)
for i in range(len(word)):
retain(word[:i] + word[i + 1:])
for i in range(len(word) - 1):
retain(word[:i] + (word[i + 1], word[i]) + word[i + 2:])
return tuple(neighbors)
def neighborhood_source(context, neighbors, *, max_states):
if len(context) + 1 > max_states:
raise ValueError("neighborhood exceeds max_states")
edges = [
f" arc {i} -> {i + 1} [labels=({symbol}, eps), weight=unit_weight]"
for i, symbol in enumerate(context)
]
transitions = {}
finals = []
for word in neighbors:
state = len(context)
for symbol in word:
key = (state, symbol)
if key not in transitions:
target = len(context) + len(transitions) + 1
if target >= max_states:
raise ValueError("neighborhood exceeds max_states")
transitions[key] = target
edges.append(
f" arc {state} -> {target} [labels=(eps, {symbol}), weight=unit_weight]"
)
state = transitions[key]
finals.append(f" final {state} [weight=unit_weight]")
states = len(context) + len(transitions) + 1
lines = [
f"relation neighborhood [algebra=logprob, states={states}]",
" input Symbols",
" output Symbols",
" initial 0 [weight=unit_weight]",
*edges,
*finals,
]
return "\n".join(lines) + "\n"
model_source = """
object Symbols : FinSet 2
relation model [algebra=logprob, states=11]
input Symbols
initial 0 [weight=unit_weight]
arc 0 -> 1 [labels=(0), weight=feature]
arc 1 -> 2 [labels=(0), weight=unit_weight]
arc 1 -> 2 [labels=(0), weight=feature]
arc 2 -> 3 [labels=(1), weight=unit_weight]
arc 0 -> 4 [labels=(0), weight=unit_weight]
arc 4 -> 5 [labels=(0), weight=unit_weight]
arc 1 -> 6 [labels=(1), weight=unit_weight]
arc 6 -> 7 [labels=(eps), weight=feature]
arc 7 -> 8 [labels=(0), weight=feature]
arc 0 -> 9 [labels=(1), weight=feature]
arc 9 -> 10 [labels=(1), weight=feature]
final 3 [weight=unit_weight]
final 5 [weight=unit_weight]
final 6 [weight=unit_weight]
final 8 [weight=unit_weight]
final 10 [weight=unit_weight]
relation joint = join(neighborhood, model, 1, 0, keep_shared=true)
relation total = project(joint, (0))
define observed_weight : LogWeight = pair_weight(joint)
define neighborhood_weight : LogWeight = pair_weight(total)
define objective() : Real !{} =
let numerator <- observed_weight()
let denominator <- neighborhood_weight()
return weight_value(numerator) - weight_value(denominator)
"""
observed = (0, 0, 1)
neighbors = deletion_or_swap(observed, max_length=3, max_neighbors=4)
assert len(neighbors) == 4
assert set(neighbors) == {(0, 0, 1), (0, 1), (0, 0), (0, 1, 0)}
theta = torch.nn.Parameter(torch.tensor(0.0, dtype=torch.float64))
module_name = "contrastive"
weights = {
ParameterId.derive(module_name, "relation_weights", "feature"): theta,
ParameterId.derive(module_name, "relation_weights", "unit_weight"): theta.new_zeros(()),
}
def bind_objective(candidates, *, max_work=1024):
source = model_source + neighborhood_source(observed, candidates, max_states=16)
compiler = Compiler(parse(source), module_name=module_name)
module = loads(dumps(compiler.qiec_module))
providers = []
for score, relation, words in (
("observed_weight", "joint", (observed, observed)),
("neighborhood_weight", "total", (observed,)),
):
request = FixedTransformedRelationRequest(
relation=compiler.transformed_relation_specs[relation],
words=words,
max_states=128,
max_work=max_work,
)
providers.append(
FixedRelationRuntimeProvider.for_score(score, loads(dumps(request)), weights)
)
return module, RuntimeConfiguration(providers=tuple(providers))
module, runtime = bind_objective(neighbors)
log_observed = run_named(module, "observed_weight", runtime=runtime).value
log_neighborhood = run_named(module, "neighborhood_weight", runtime=runtime).value
assert math.isclose(log_observed.item(), math.log(2), abs_tol=1e-14)
assert math.isclose(log_neighborhood.item(), math.log(5), abs_tol=1e-14)
for candidates, expected_mass, expected_gradient in (
(tuple(word for word in neighbors if word != (0, 1, 0)), 4, 1 / 2),
(neighbors + ((1, 1),), 6, 0),
):
changed_module, changed_runtime = bind_objective(candidates)
objective = run_named(changed_module, "objective", runtime=changed_runtime).value
(gradient,) = torch.autograd.grad(objective, theta)
assert math.isclose(objective.item(), math.log(2 / expected_mass), abs_tol=1e-14)
assert math.isclose(gradient.item(), expected_gradient, abs_tol=1e-14)
try:
bind_objective(neighbors, max_work=1)
except RelationLimitError:
pass
else:
raise AssertionError("the checked sparse query accepted insufficient work")
optimizer = torch.optim.SGD([theta], lr=1 / 16, maximize=True)
for _ in range(6):
optimizer.zero_grad()
p = math.exp(theta.item())
observed_mass = p + p**2
neighborhood_mass = 1 + 2 * p + p**2 + p**3
expected = math.log(observed_mass) - math.log(neighborhood_mass)
expected_gradient = (
(p + 2 * p**2) / observed_mass
- (2 * p + 2 * p**2 + 3 * p**3) / neighborhood_mass
)
objective = run_named(module, "objective", runtime=runtime).value
objective.backward()
assert math.isclose(objective.item(), expected, abs_tol=1e-14)
assert math.isclose(theta.grad.item(), expected_gradient, abs_tol=1e-14)
optimizer.step()
assert theta.item() > 0
The four neighborhood words \(001\), \(01\), \(00\), and \(010\) have path weights \(p+p^2\), \(p\), \(1\), and \(p^3\), respectively, with \(p=e^\theta\). The two paths for \(001\) use parallel arcs with distinct weights. Both paths contribute to the observed mass. At \(\theta=0\), the two partitions have masses 2 and 5. The derivative is \(3/2-7/5=1/10\), the difference between the expected feature counts under the observed and neighborhood path laws. The two changed executions omit the swapped word or admit the outside word \(11\). Both change the objective and gradient.
For observed length \(m\), the constructor inspects at most \(2m\) edit scripts plus the identity, with at most \(m\) symbols per script. It caps the input length, the number of distinct neighbors, and the number of trie states. Each checked score separately bounds sparse product states and work. The denominator shares prefix states across candidates and sums their latent paths in one sparse query. The fit compares values and live gradients against the explicit polynomials for six float64 updates on this acyclic model.