Skip to content

Mention Phylogeny

Overview

An entity may be mentioned under several names. Conversely, two observed mentions with the same name may have different referents. In a mention phylogeny, each mention either starts an entity or copies an earlier mention from a latent ordering, with a stochastic edit channel relating the two names. We use observed contexts and a single entity type in this example. Andrews, Eisner, and Dredze (2014), §§3–5

QVR source

Open the complete QVR source. The program scores one proposed order using the fixed-word edit masses and the parent logits.

object Mention : FinSet 3
object Parent : FinSet 4
object Result : Real 1

# The parent lanes of both tensors use the same ordering mask.
# The last parent lane is the source of a new entity.
program order_log_mass(prior : Real[Fin Mention, Fin Parent], joint : Real[Fin Mention, Fin Parent]) : Mention -> Result
    let mass_by_mention = logsumexp(joint) - logsumexp(prior)
    let total = sum(mass_by_mention)
    return total

export order_log_mass

Understanding the model

Model and inference

Let \(S_j\) be the set of mentions earlier than mention \(j\) in the proposed order. The parent candidates are \(S_j\cup\{\diamond\}\), where \(\diamond\) starts a new entity and passes the empty name to the edit channel. At a fixed order, a prior logit \(a_{jp}\) controls how likely \(j\) is to choose parent \(p\) and the edit channel assigns probability \(m_{jp}\) to the name at \(j\) given the name at \(p\). The marginal likelihood of the observed name at \(j\) is

\[ \frac{\sum_{p\in S_j\cup\{\diamond\}} e^{a_{jp}}m_{jp}} {\sum_{p\in S_j\cup\{\diamond\}} e^{a_{jp}}}. \]

Because the parent choices are independent given the order and observed names, we can sum them out before sampling the order. The QVR source returns the log product of these likelihoods. Under a uniform order prior, a proposal that swaps one adjacent pair has a Metropolis acceptance probability given by the clipped ratio of this product at the proposed order and the current order. The candidate sets of only the two swapped mentions change. Given a sampled order, we draw each parent from the corresponding numerator weights and group the mentions by their first ancestor below \(\diamond\).

For \(n\) mentions, the packed word-pair plans and a snapshot of their scores are built once per parameter setting. The dense pair-score table has \(O(n^2)\) entries. Each order proposal scores two changed candidate sets using \(O(n)\) work on this snapshot. Drawing the complete parent block costs \(O(n^2)\). Finite-run cluster frequencies are Monte Carlo estimates of posterior quantities. The example checks stationarity by enumeration and uses the exact small-order likelihood when checking derivatives.

Walkthrough

Score and sample mention orders

Precompute the edit scores for ordered mention pairs and for links from the empty-name root. Enumerate the order posterior for the three mentions and verify that it is stationary under the adjacent-swap Metropolis transition.

Draw the parent choices

At a sampled order, draw a parent for each mention from its earlier candidates and the root. Group mentions that descend from the same first ancestor below the root.

Try it

Run this from the repository root.

from itertools import permutations, product
from math import factorial
from pathlib import Path

import torch
from torch import nn

from quivers import FinSet, StringSet
from quivers.core.relations.contextual_edit import ContextualEditChannel
from quivers.dsl import load
from quivers.qiec import run_program

words = ((0, 1), (0, 1), (1, 0))
n = len(words)
root = n
mentions = range(n)
orders = tuple(permutations(mentions))
contexts = (0, 0, 1)
module = load("docs/examples/qiec/mention-phylogeny.qvr").qiec


class EditLogits(nn.Module):
    def __init__(self):
        super().__init__()
        self.copy = nn.Parameter(torch.tensor(1.4, dtype=torch.float64))

    def forward(self, inputs):
        width = max(map(len, inputs)) + 1
        next_symbol = torch.tensor([word + (2,) * (width - len(word)) for word in inputs])
        copy = torch.stack((next_symbol == 0, next_symbol == 1), dim=-1)
        bonus = torch.cat((self.copy.new_zeros((*next_symbol.shape, 4)), copy), dim=-1)
        base = self.copy.new_tensor((-1.0, 0.0, -1.6, -1.6, 0.0, 0.0))
        return (base + self.copy * bonus).unsqueeze(2).expand(-1, -1, 3, -1)


tape = StringSet(alphabet=FinSet(name="NameSymbols", cardinality=2))
edit = EditLogits()
channel = ContextualEditChannel(tape, tape, edit, max_insertions=2)
plan = channel.plan(
    tuple(original for target in words for original in (*words, ())),
    tuple(target for target in words for _ in range(n + 1)),
    max_states=2_000,
    max_work=10_000,
)
context_weight = nn.Parameter(torch.tensor(0.4, dtype=torch.float64))
same = torch.tensor([
    [float(contexts[j] == contexts[p]) for p in mentions] + [0.0]
    for j in mentions
], dtype=torch.float64)


def pair_scores():
    prior = context_weight * same
    return prior, prior + plan.log_prob().view(n, n + 1)


def allowed(order):
    return {j: (root, *order[:i]) for i, j in enumerate(order)}


def order_mass(order, prior, joint):
    mask = torch.zeros_like(prior, dtype=torch.bool)
    for mention, candidates in allowed(order).items():
        mask[mention, candidates] = True
    return run_program(
        module, "order_log_mass",
        data={
            "prior": prior.masked_fill(~mask, -torch.inf),
            "joint": joint.masked_fill(~mask, -torch.inf),
        },
        sites={},
    ).value


def summed_parents(order, prior, joint):
    # Sum explicit parent maps in probability space.
    permitted = allowed(order)
    normalizer = torch.stack([prior[j, permitted[j]].exp().sum() for j in mentions])
    mass = prior.new_zeros(())
    for parents in product(*(permitted[j] for j in mentions)):
        mass = mass + (joint[list(mentions), parents].exp() / normalizer).prod()
    return mass


def swap_mass(order, index, prior, joint):
    shifted = list(order)
    shifted[index], shifted[index + 1] = shifted[index + 1], shifted[index]
    proposal = tuple(shifted)

    def local_masses(arrangement):
        first, second = arrangement[index:index + 2]
        preceding = (root, *arrangement[:index])
        candidates = ((first, preceding), (second, (*preceding, first)))
        return sum(
            joint[j, parents].logsumexp(0) - prior[j, parents].logsumexp(0)
            for j, parents in candidates
        )

    return proposal, local_masses(proposal) - local_masses(order)


prior, joint = pair_scores()
checked = torch.stack([order_mass(order, prior, joint) for order in orders])
independent = torch.stack([summed_parents(order, prior, joint) for order in orders])
torch.testing.assert_close(checked.exp(), independent, rtol=1e-11, atol=1e-13)
assert checked.max() - checked.min() > 1e-3
parameters = (edit.copy, context_weight)
log_likelihood = (checked.exp().sum() / factorial(n)).log()
reference = (independent.sum() / factorial(n)).log()
oracle_gradient = torch.autograd.grad(reference, parameters, retain_graph=True)
for got, target in zip(torch.autograd.grad(log_likelihood, parameters), oracle_gradient, strict=True):
    torch.testing.assert_close(got, target, rtol=1e-11, atol=1e-12)
    assert got.abs() > 1e-4

with torch.no_grad():
    prior, joint = pair_scores()
    masses = checked.detach().softmax(0)
    transition = torch.zeros((len(orders), len(orders)), dtype=prior.dtype)
    for row, order in enumerate(orders):
        for pos in range(n - 1):
            proposed, delta = swap_mass(order, pos, prior, joint)
            col = orders.index(proposed)
            torch.testing.assert_close(delta, checked[col] - checked[row], rtol=1e-11, atol=1e-12)
            move = delta.clamp_max(0).exp() / (n - 1)
            transition[row, col] += move
            transition[row, row] += 1 / (n - 1) - move
    torch.testing.assert_close(masses @ transition, masses, rtol=1e-11, atol=1e-12)
    flux = masses[:, None] * transition
    torch.testing.assert_close(flux, flux.T, rtol=1e-11, atol=1e-12)
    # Accepting every swap would yield a uniform stationary law on this graph.
    assert (masses - 1 / len(orders)).abs().max() > 1e-3

    generator = torch.Generator().manual_seed(26)
    order = orders[0]
    clusters = set()
    for _ in range(80):
        index = int(torch.randint(n - 1, (), generator=generator))
        proposed, delta = swap_mass(order, index, prior, joint)
        if torch.rand((), generator=generator) < delta.clamp_max(0).exp():
            order = proposed
        ancestor = {}
        permitted = allowed(order)
        for mention in order:
            candidates = permitted[mention]
            pick = int(torch.multinomial(joint[mention, candidates].softmax(0), 1, generator=generator))
            parent = candidates[pick]
            ancestor[mention] = mention if parent == root else ancestor[parent]
        clusters.add(tuple(ancestor[i] == ancestor[j] for j in mentions for i in range(j)))
    assert len(clusters) > 1

# Re-evaluate the packed edit plan after each weight update.
optimizer = torch.optim.SGD(parameters, lr=0.1)
initial = log_likelihood.detach()
for _ in range(4):
    optimizer.zero_grad()
    prior, joint = pair_scores()
    log_masses = torch.stack([order_mass(order, prior, joint) for order in orders])
    objective = log_masses.logsumexp(0) - prior.new_tensor(factorial(n)).log()
    (-objective).backward()
    optimizer.step()
with torch.no_grad():
    prior, joint = pair_scores()
    fitted = torch.stack([order_mass(order, prior, joint) for order in orders])
    expected = torch.stack([summed_parents(order, prior, joint) for order in orders])
    torch.testing.assert_close(fitted.exp(), expected, rtol=1e-11, atol=1e-13)
    assert (fitted.exp().sum() / factorial(n)).log() > initial + 1e-3