Name phylogeny¶
Overview¶
The observed data are name types \(w_1,\ldots,w_n\) and their token counts \(n_1,\ldots,n_n\). Each name has one parent in a directed tree rooted at a distinguished source \(\diamond\). An edge from the source generates a new name. An edge from another name derives the child by string transduction.
QVR source¶
The likelihood computation combines string edit scores and count factors into arc weights, then sums over rooted trees. The Python script binds the foreign handler that computes the edit scores.
instance edits : Compute[Unit, LogWeight[Fin 6]]
handler name_edit_scores for Compute[Unit, LogWeight[Fin 6]] : LogWeight[Fin 6] -> LogWeight[Fin 6] [coverage=total, forwards=none, implementation=foreign]
apply resumes 1
define alignment_scores : LogWeight[Fin 6] !{} =
handle edits with name_edit_scores in
let scores <- perform edits.apply(unit)
return scores
define likelihood(root_arcs : Real[Fin 3], count_factors : Real[Fin 6], mask : Bool[Fin 4, Fin 4]) : LogWeight * Real[Fin 4, Fin 4] !{} =
let scores <- alignment_scores()
let root_row = [0.0, root_arcs[0], root_arcs[1], root_arcs[2]]
let ana_row = [0.0, 0.0, weight_value(scores[0]) + count_factors[0], weight_value(scores[1]) + count_factors[1]]
let ann_row = [0.0, weight_value(scores[2]) + count_factors[2], 0.0, weight_value(scores[3]) + count_factors[3]]
let an_row = [0.0, weight_value(scores[4]) + count_factors[4], weight_value(scores[5]) + count_factors[5], 0.0]
let arcs = [root_row, ana_row, ann_row, an_row]
let total = directed_tree_log_partition(arcs, 0, mask)
return (total, arcs)
Understanding the model¶
We use the edge-factored approximation in ยง5.2 of Andrews, Eisner, and Dredze (2012). In this approximation, \(n_x/(n_y+1)\) is the expected number of tokens of \(x\) before the first token of \(y\) in a uniformly random token ordering. The product of edge weight expectations replaces the expectation of the joint product over token orders. With source probability \(p_0\) and conditional mutation probability \(p_\theta\), the edge weights are
The root language draws a geometric length and then independent uniform symbols. The transducer deletes each input symbol with probability \(d\). A retained symbol stays unchanged with probability \(\sigma(\theta)\) and flips to the other symbol of the binary alphabet otherwise. These three possibilities sum to one at each input position, so the transducer is a normalized conditional distribution for every fixed input. Its fixed-word queries sum all deletion alignments.
Walkthrough¶
Enumerate root-connected trees to check the partition and each edge marginal. Then fit the shared edit weight and check whether derivatives through the nominal attachment agree with the independent calculation.
Try it¶
Run this from the repository root.
from pathlib import Path
from itertools import combinations, permutations, product
from math import log
import torch
from torch import nn
from torch.nn import functional as F
from quivers import FinSet, StringSet
from quivers.core.relations import ContextualEditChannel
from quivers.dsl import Compiler, parse
from quivers.qiec import (
AttachmentId,
ContextualEditRuntimeProvider,
CoreRuntimeProvider,
FixedContextualEditRequest,
RuntimeConfiguration,
dumps,
loads,
run_named,
)
names = ("ana", "ann", "an")
counts = (7, 4, 2)
symbols = {"a": 0, "n": 1}
words = tuple(tuple(symbols[c] for c in name) for name in names)
deletion, continuation = 0.23, 0.6
alpha, mu = 1.0, 0.2
nodes = range(1, len(words) + 1)
pairs = tuple(permutations(nodes, 2))
class MutationWeights(nn.Module):
def __init__(self):
super().__init__()
self.theta = nn.Parameter(torch.tensor(-1.0, dtype=torch.float64))
def forward(self, inputs):
width = 1 + max(map(len, inputs))
letters = torch.tensor(
[word + (0,) * (width - len(word)) for word in inputs],
device=self.theta.device,
)
keep = log(1 - deletion)
same = keep + F.logsigmoid(self.theta)
change = keep + F.logsigmoid(-self.theta)
zero = self.theta.new_zeros(letters.shape)
# Delete, stop, two masked insertion actions, then emit 0 or 1.
return torch.stack((
zero + log(deletion), zero, zero, zero,
torch.where(letters == 0, same, change),
torch.where(letters == 1, same, change),
), dim=-1).unsqueeze(2)
weights = MutationWeights()
tape = StringSet(alphabet=FinSet(name="NameAlphabet", cardinality=2))
channel = ContextualEditChannel(tape, tape, weights, max_insertions=0)
owner = AttachmentId.derive("name_phylogeny", "mutation")
request = FixedContextualEditRequest(
channel=owner,
input_alphabet=("NameAlphabet", 2),
output_alphabet=("NameAlphabet", 2),
inputs=tuple(words[x - 1] for x, _ in pairs),
outputs=tuple(words[y - 1] for _, y in pairs),
max_insertions=0,
max_states=256,
max_work=512,
)
source = Path("docs/examples/qiec/name-phylogeny.qvr").read_text().replace(
"name_edit_scores", request.handler_name
)
compiler = Compiler(parse(source), module_name="name_phylogeny")
wire = dumps(compiler.qiec_module)
module = loads(wire)
assert dumps(module) == wire
provider = ContextualEditRuntimeProvider(request, {owner: channel})
runtime = RuntimeConfiguration(
selections=(), providers=(CoreRuntimeProvider(), provider)
)
root_arcs = weights.theta.new_tensor([
log(alpha * (1 - continuation)) + len(w) * log(continuation / 2) for w in words
])
count_factors = weights.theta.new_tensor([
log(mu * counts[x - 1] / (counts[y - 1] + 1)) for x, y in pairs
])
mask = ~torch.eye(len(words) + 1, dtype=torch.bool)
mask[:, 0] = False
def tree():
return run_named(
module, "likelihood", (root_arcs, count_factors, mask),
runtime=runtime, record_trace=False,
).value
def enumerate_trees():
theta = weights.theta
fidelity = theta.sigmoid()
edge = {}
for y in nodes:
target = words[y - 1]
edge[0, y] = theta.new_tensor(
alpha * (1 - continuation) * (continuation / 2) ** len(target)
)
for x, y in permutations(nodes, 2):
source, target = words[x - 1], words[y - 1]
if len(source) < len(target):
edge[x, y] = theta.new_zeros(())
continue
alignments = []
for kept in combinations(range(len(source)), len(target)):
matches = sum(source[i] == c for i, c in zip(kept, target, strict=True))
alignments.append(
fidelity**matches * (1 - fidelity)**(len(target) - matches)
)
alignment_mass = sum(alignments, theta.new_zeros(()))
edge[x, y] = (
mu * counts[x - 1] / (counts[y - 1] + 1)
* deletion**(len(source) - len(target))
* (1 - deletion)**len(target) * alignment_mass
)
total = theta.new_zeros(())
marginals = theta.new_zeros((len(words) + 1, len(words) + 1))
possible_parents = [tuple(x for x in range(len(words) + 1) if x != y) for y in nodes]
for choices in product(*possible_parents):
parent = dict(zip(nodes, choices, strict=True))
for start in nodes:
seen = set()
cursor = start
while cursor and cursor not in seen:
seen.add(cursor)
cursor = parent[cursor]
if cursor:
break
else:
edges = [(parent[y], y) for y in nodes]
mass = torch.stack(tuple(edge[e] for e in edges)).prod()
total = total + mass
for x, y in edges:
marginals[x, y] += mass.detach()
return total.log(), marginals / total.detach()
def check_enumeration():
actual, scores = tree()
expected, edge_probabilities = enumerate_trees()
torch.testing.assert_close(actual, expected)
(marginals,) = torch.autograd.grad(actual, scores, retain_graph=True)
torch.testing.assert_close(marginals, edge_probabilities)
(actual_sensitivity,) = torch.autograd.grad(actual, weights.theta)
(expected_sensitivity,) = torch.autograd.grad(expected, weights.theta)
torch.testing.assert_close(actual_sensitivity, expected_sensitivity)
return actual.detach()
before = check_enumeration()
optimizer = torch.optim.SGD(weights.parameters(), lr=0.5)
for _ in range(12):
optimizer.zero_grad()
total, _ = tree()
(-total).backward()
optimizer.step()
after = check_enumeration()
assert after > before
The checked QVR computation fills the score matrix and sums the product of edge weights over root-connected trees. The root has index zero and may have several children. A matrix entry has its parent on the first axis and its child on the second. The derivative with respect to one edge log weight is that edge's posterior probability. The example checks the partition, every edge marginal, and the derivative of the shared mutation parameter by independent enumeration before and after training. The corpus factor in the approximate likelihood is constant in \(\theta\) for fixed \(\alpha\) and \(\mu\), so optimizing the log partition fits the transducer under this approximation.
The nominal attachment keeps one packed plan for the six ordered name pairs. Each invocation computes their conditional scores from the current mutation parameter and passes the scores to the tree query with their derivatives intact. The exact tree sum uses the paper's expected-count edge weights for this fixed corpus. The updates fit the single mutation parameter with the source and mutation coefficients fixed. See the checked directed-tree query.