Collapsed morphological paradigm reanalysis¶
Overview¶
A lexeme in this example has a present and a past spelling. The corpus
contains the word tokens ta, ka, ta. A token identifies one spelling
in its lexeme's paradigm, and repeated tokens in the same slot share that
spelling. The same spelling can occur in different slots or in paradigms of
distinct lexemes. We condition on a fixed part of speech and start from a
proposed assignment of tokens to lexemes and slots. Dreyer and Eisner (2011), §§2, 6.9 and 7.1.
QVR source¶
# Finite transducers for two inflections over two possible lemma strings.
object Symbols : FinSet 3
object Token : FinSet 3
object Result : Real 1
relation present [algebra=markov, states=3]
input Symbols
output Symbols
initial 0 [weight=one]
arc 0 -> 1 [labels=(0, 0), weight=present_same]
arc 0 -> 1 [labels=(0, 0), weight=parallel]
arc 0 -> 1 [labels=(1, 1), weight=present_same]
arc 0 -> 1 [labels=(0, 1), weight=present_change]
arc 0 -> 1 [labels=(1, 0), weight=present_change]
arc 1 -> 2 [labels=(eps, 2), weight=one]
final 2 [weight=one]
relation past [algebra=markov, states=3]
input Symbols
output Symbols
initial 0 [weight=one]
arc 0 -> 1 [labels=(0, 0), weight=past_same]
arc 0 -> 1 [labels=(1, 1), weight=past_same]
arc 0 -> 1 [labels=(0, 1), weight=past_change]
arc 0 -> 1 [labels=(1, 0), weight=past_change]
arc 1 -> 2 [labels=(eps, 2), weight=one]
final 2 [weight=one]
define present_00 : LogWeight = conditional_log_prob(present)
define present_01 : LogWeight = conditional_log_prob(present)
define present_10 : LogWeight = conditional_log_prob(present)
define present_11 : LogWeight = conditional_log_prob(present)
define past_00 : LogWeight = conditional_log_prob(past)
define past_01 : LogWeight = conditional_log_prob(past)
define past_10 : LogWeight = conditional_log_prob(past)
define past_11 : LogWeight = conditional_log_prob(past)
define spellings() : Real[Fin 2, Fin 2, Fin 2] !{} =
let present_zero_zero <- present_00()
let present_zero_one <- present_01()
let present_one_zero <- present_10()
let present_one_one <- present_11()
let past_zero_zero <- past_00()
let past_zero_one <- past_01()
let past_one_zero <- past_10()
let past_one_one <- past_11()
let present_rows = [[weight_value(present_zero_zero), weight_value(present_zero_one)], [weight_value(present_one_zero), weight_value(present_one_one)]]
let past_rows = [[weight_value(past_zero_zero), weight_value(past_zero_one)], [weight_value(past_one_zero), weight_value(past_one_one)]]
return [present_rows, past_rows]
define placement_weights(channel : Real[Fin 2, Fin 2, Fin 2], words : Int[Fin 3], tables : Int[Fin 3], seats : Int[Fin 3], held : Int, table_concentration : Real, seat_concentration : Real) : Real[Fin 6] !{} =
let positions = [0, 1, 2]
let bits = [0, 1]
let valid_indices = min(words) >= 0 && max(words) <= 1 && min(tables) >= 0 && max(tables) <= 2 && min(seats) >= 0 && max(seats) <= 1 && held >= 0 && held <= 2
let hist = map(positions, table -> map(bits, seat -> map(bits, word -> sum(map(positions, i -> int(i != held && tables[i] == table && seats[i] == seat && words[i] == word))))))
let next_word = words[select(held >= 0 && held <= 2, held, 0)]
let candidates <- retained_weights(channel, hist, next_word, valid_indices, table_concentration, seat_concentration)
return candidates
define retained_weights(channel : Real[Fin 2, Fin 2, Fin 2], hist : Int[Fin 3, Fin 2, Fin 2], next_word : Int, valid_indices : Bool, table_concentration : Real, seat_concentration : Real) : Real[Fin 6] !{} =
let positions = [0, 1, 2]
let bits = [0, 1]
let joint_index = [0, 0, 1, 1, 2, 2]
let slot_index = [0, 1, 0, 1, 0, 1]
let minus_inf = log_probability(0.0)
let lemma_log_prior = log([0.6, 0.4])
let seat_log_prior = log([0.65, 0.35])
let seat_counts = map(positions, table -> map(bits, seat -> sum(hist[table, seat])))
let table_counts = map(positions, table -> sum(seat_counts[table]))
let lock_masks = map(positions, table -> map(bits, seat -> hist[table, seat, 0] == 0 || hist[table, seat, 1] == 0))
let valid_locks = min(map(positions, table -> min(map(bits, seat -> int(lock_masks[table, seat]))))) == 1
let locked = map(positions, table -> map(bits, seat -> int(hist[table, seat, 1] > 0)))
let table_lemmas = map(positions, table -> map(bits, lemma -> lemma_log_prior[lemma] + sum(map(bits, seat -> select(seat_counts[table, seat] > 0, channel[seat, lemma, locked[table, seat]], 0.0)))))
let evidence = map(positions, table -> logsumexp(table_lemmas[table]))
let valid_evidence = min(evidence) > minus_inf
let check = positive_parameter(select(valid_indices && valid_locks && valid_evidence, 1.0, 0.0))
let alpha = positive_parameter(table_concentration) * check
let beta = positive_parameter(seat_concentration)
let occupied = map(positions, table -> table_counts[table] > 0)
let prior_empty = map(positions, table -> sum(map(positions, other -> int(other < table && not occupied[other]))))
let available = map(positions, table -> occupied[table] || prior_empty[table] == 0)
let table_log_mass = log(select(occupied, real(table_counts), alpha))
let seen_counts = real(seat_counts)
let log_counts = select(seen_counts > 0.0, log(max(1.0, seen_counts)), minus_inf)
let log_base = log(beta) + seat_log_prior
let log_denominator = log(real(table_counts) + beta)
let seat_prior = map(positions, table -> map(bits, seat -> select(occupied[table], logsumexp([log_counts[table, seat], log_base[seat]]) - log_denominator[table], seat_log_prior[seat])))
let open_slots = map(positions, table -> map(bits, seat -> logsumexp(map(bits, lemma -> table_lemmas[table, lemma] + channel[seat, lemma, next_word])) - evidence[table]))
let slot_likelihood = map(positions, table -> map(bits, seat -> select(seat_counts[table, seat] == 0, open_slots[table, seat], select(locked[table, seat] == next_word, 0.0, minus_inf))))
let proposal = map(positions, table -> map(bits, seat -> table_log_mass[table] + seat_prior[table, seat] + slot_likelihood[table, seat]))
return map([0, 1, 2, 3, 4, 5], cell -> select(available[joint_index[cell]], proposal[joint_index[cell], slot_index[cell]], minus_inf))
program reassign(words : Int[Fin Token], tables : Int[Fin Token], seats : Int[Fin Token], held : Int, table_concentration : Real, seat_concentration : Real) : Token -> Result
let channel <- spellings()
let candidates <- placement_weights(channel, words, tables, seats, held, table_concentration, seat_concentration)
let marginal = logsumexp(candidates)
let log_predictive = marginal - log(2.0 + table_concentration)
score spelling = log_predictive
let check_mass = positive_parameter(select(marginal > log_probability(0.0), 1.0, 0.0))
let logits = candidates - marginal * check_mass
let placement <- sample Categorical(logits=logits)
let placements = [0, 0, 1, 1, 2, 2]
let seat_numbers = [0, 1, 0, 1, 0, 1]
let table_choice = placements[placement]
let seat_choice = seat_numbers[placement]
let next_tables = map([0, 1, 2], i -> select(i == held, table_choice, tables[i]))
let next_seats = map([0, 1, 2], i -> select(i == held, seat_choice, seats[i]))
return (next_tables, next_seats, logits, spelling, placement)
export reassign
# The retained histogram and spelling define this conditional on their own.
# The host snapshot owns their relation to the token assignment.
program reassign_retained(hist : Int[Fin 3, Fin 2, Fin 2], next_word : Int, table_concentration : Real, seat_concentration : Real) : Token -> Result
let positions = [0, 1, 2]
let bits = [0, 1]
let count_bounds = map(positions, table -> map(bits, seat -> int(min(hist[table, seat]) >= 0 && max(hist[table, seat]) <= 2)))
let retained_count = sum(map(positions, table -> sum(map(bits, seat -> sum(hist[table, seat])))))
let valid = min(map(positions, table -> min(count_bounds[table]))) == 1 && retained_count == 2 && next_word >= 0 && next_word <= 1
let channel <- spellings()
let candidates <- retained_weights(channel, hist, next_word, valid, table_concentration, seat_concentration)
let marginal = logsumexp(candidates)
let log_predictive = marginal - log(2.0 + table_concentration)
score spelling = log_predictive
let check_mass = positive_parameter(select(marginal > log_probability(0.0), 1.0, 0.0))
let logits = candidates - marginal * check_mass
let placement <- sample Categorical(logits=logits)
return (logits, spelling, placement)
export reassign_retained
Understanding the model¶
Two finite-state transducers define the present and past distributions.
Both start from one of the lemma strings t and k, and can emit ta
or ka. Each accepting path writes a stem and then the suffix a.
One pair in the present transducer admits two paths. The normalized
relation query sums both paths and normalizes over the two accepted
outputs for the given lemma. Its weights stay live across reassignments.
This is the directed lemma-to-slot base law from §2.2 restricted to
these finite vocabularies. Dreyer and Eisner (2011), §2.2.
Walkthrough¶
The initial tables below put tokens 0 and 2 in the present slot of one lexeme, and token 1 in the present slot of another. Removing token 1 releases its table. The program considers both slots of the surviving lexeme and both slots of one new lexeme. It keeps the table identifiers of the remaining tokens and assigns a new lexeme the first free label. Eight fixed relation requests bind the spellings in lexical order to the checked source declarations.
Calculate the collapsed update¶
After removal, let \(n_b\) be the size of occupied table \(b\), \(n_{bs}\) its count at slot \(s\), and \(C_b\) the partial map from occupied slots to their spellings. Let \(q\) be the lemma law and \(T_s\) the slot transducer's conditional law. The probability that a base paradigm agrees with \(C\) is
This sum integrates the lemma and every unconstrained spelling. The product carries one factor per occupied slot. Conflicting spellings in a retained slot mean the retained state is impossible. The source refuses that state or a retained table with zero \(L(C_b)\).
Let \(\alpha\) be the concentration of the Chinese restaurant process (CRP), \(\beta\) the concentration of the slot Dirichlet, and \(h_s\) its mean. For the held-out spelling \(w\), the unnormalized placement weight is
The CRP gives the table factors, and the Dirichlet posterior predictive gives the slot factors. The spelling term is one for an already occupied compatible slot and zero for an incompatible slot. If \(N\) tokens remain, the sum of \(U_{bs}(w)/(N+\alpha)\) is the predictive spelling probability. Dividing the \(U\) by their sum instead gives the distribution of the placement conditional on \(w\). The program scores the first probability and samples from the second. This gives the joint probability of spelling and placement under the collapsed model. Dreyer and Eisner (2011), §§6.9 and 7.1.
The transition is defined on partitions, so renaming all table labels leaves its law unchanged. Choosing one vacant label represents one CRP birth event even when several labels are free. Equal paradigms at distinct tables remain distinct events. At fixed retained assignments, the probability of an old and a new placement is the retained-state probability times the product of their two conditional probabilities. This is symmetric in the placements, establishing detailed balance for each coordinate update. A sweep of such updates preserves the posterior.
Each table uses one normalized distribution over lemmas to score all its open slots. For a retained lock, the derivative of \(\log L(C)\) is the posterior average over compatible lemmas of the sum of that lemma's slot log-probability derivatives. The conditional spelling gradient is the difference between the gradients of the two log evidences. The source retains the transducer scores and concentration parameters through these reductions. The test oracle independently sums the full paradigm and assignment space, compares these gradients through live refits, and checks the transition matrix for every positive-mass canonical state.
Reuse the counts and spell-out plans¶
Let \(H(b,s,v)\) count tokens assigned to table \(b\) and slot \(s\) with spelling \(v\). The initial snapshot counts every token once. For a held token, the helper subtracts its cell from \(H\). The retained slot stays locked if another token has that spelling. The checked program validates the retained counts, evaluates the live factors in \(U\), and chooses a placement. After a positive choice, the helper adds the token to the selected cell. The receiver stays intact, so two proposals from the same snapshot see the same retained state. Changing the corpus or assignments outside this update requires constructing a new snapshot.
For \(N\) token positions, \(K\) table labels, \(S\) slots and \(W\) surface words, the original count scan reads \(KSWN\) token/cell contributions. The initial snapshot uses \(N\) indexed increments and stores \(KSW\) counts. A move changes one count at removal and one at acceptance. The immutable tuples copy \(O(K+S+W)\) count references for each change and share unaffected rows. The accepted assignment tuples cost \(O(N)\) to copy. The checked program reads the dense \(KSW\) counts and scores all reachable choices. The fixture has 36 token/cell contributions per scan and two single-cell adjustments per move. All sizes here are the declared finite fixture sizes.
Each of the eight fixed relation requests keeps its all-output plan and the fixed-output plan it builds on its first evaluation. The first coordinate builds eight output plans with 24 active states and 17 active arcs in total. Later coordinates reuse them and still evaluate the eight live scores. Both path sums use the same current weight vector for a request. The cache holds integer counts and graph plans. Refitting reads fresh transducer weights and concentrations and builds a new derivative graph for the numeric reductions. The tests count output-plan builds, spell-out calls and cell adjustments across a sequence of updates with live refits.
The three tokens admit every partition of the fixture. The paper's corpus-scale method also uses approximate missing-spelling messages and specialized moves that remove several tokens together. Dreyer and Eisner (2011), §§3.3 and 7.1.
Try it¶
from itertools import product
from pathlib import Path
from runpy import run_path
import torch
from quivers.dsl import Compiler, parse
from quivers.qiec import FixedRelationRequest, FixedRelationRuntimeProvider
ParadigmAssignments = run_path("docs/examples/helpers/paradigm_reanalysis.py")[
"ParadigmAssignments"
]
source = Path("docs/examples/qiec/paradigm-reanalysis.qvr").read_text()
compiler = Compiler(parse(source), module_name="paradigm_reanalysis")
checked = compiler.qiec_module
weights = {name: torch.tensor(value, dtype=torch.float64) for name, value in {
"one": 1.0, "present_same": 2.0, "present_change": 1.0, "parallel": 0.5,
"past_same": 1.0, "past_change": 3.0,
}.items()}
providers = []
for inflection, relation in compiler.relation_specs.items():
parameters = dict(zip(relation.weight_parameters,
(weights[name] for name in relation.weight_names), strict=True))
for lemma, form in product(range(2), repeat=2):
request = FixedRelationRequest(
relation=relation, operation="conditional_log_prob",
words=((lemma,), (form, 2)), max_states=24, max_work=192,
)
providers.append(FixedRelationRuntimeProvider.for_score(
f"{inflection}_{lemma}{form}", request, parameters,
))
state = ParadigmAssignments(words=(0, 1, 0), tables=(0, 1, 0), seats=(0, 0, 0))
concentrations = {"table_concentration": 1.3, "seat_concentration": 1.1}
with torch.random.fork_rng(devices=[]):
torch.manual_seed(11)
step, state = state.step(checked, tuple(providers), held=1, **concentrations)
logits, spelling, placement = step.value
assert logits[placement].isfinite() and spelling <= 0
torch.testing.assert_close(logits.exp().sum(), spelling.new_tensor(1.0))
next_step, state = state.step(checked, tuple(providers), held=0, **concentrations)
assert next_step.log_joint.isfinite()
The assignment helper owns the corpus,
the current assignments and their integer counts. Its step method
calls the checked reassign_retained program with the retained counts
and held spelling. Passing placement replays the named Categorical
draw. The method leaves the current snapshot available when a replay
has zero mass. The original reassign export accepts full assignments
and reconstructs the retained counts. Each export records its own
spelling and placement sites. The full example needs the installed
finite-state relation providers, which the target transpilers cannot emit. Marginalizing the allocation would
retain the predictive spelling mass in a target that already has the
same relation weights. Such a scalar score would omit the sampled table
and slot needed for the next update.