Skip to content

Finite-state Dirichlet allocation

Overview

Two documents follow the same two-state hidden Markov topology. Each document \(d\) draws its own transition row \(A_{di}\) for every source state \(i\). Rows for the same source state share a concentration vector \(\alpha_i\). They are conditionally independent given that vector. The program draws each \(\alpha_{ij}\) from \(\mathrm{Gamma}(2,1)\) and uses one initial distribution \(\pi\) and emission matrix \(B\) across documents. Every transition emits one symbol, and the sequence length comes from the observations.

QVR source

# Two observed documents share a prior over their transition matrices.
# Every hidden-state transition emits one symbol.
object State : FinSet 2
object Symbol : FinSet 2
object StateProbs : Real 2

program step_a(symbol, previous) : Symbol * State -> State
    marginalize z : State <- Categorical(probs=transition_a[previous])
        observe symbol <- Categorical(probs=emission[z])
    return z

program step_b(symbol, previous) : Symbol * State -> State
    marginalize z : State <- Categorical(probs=transition_b[previous])
        observe symbol_b <- Categorical(probs=emission[z])
    return z

define chain_a = scan(step_a, init=initial)
define chain_b = scan(step_b, init=initial)

program fsda : Symbol -> StateProbs
    let alpha : State <- sample Gamma(concentration=2.0, rate=1.0) [over=State, iid_over=State]
    let transition_a : State <- sample Dirichlet(concentration=alpha) [over=State, iid_over=State]
    let transition_b : State <- sample Dirichlet(concentration=alpha) [over=State, iid_over=State]
    let emission : State <- sample Dirichlet(concentration=1.0) [over=Symbol, iid_over=State]
    let initial <- sample Dirichlet(concentration=1.0) [over=State]
    let path_a <- apply chain_a [transition_a, emission, initial]
    let path_b <- apply chain_b [transition_b, emission, initial]
    return initial

export fsda

Understanding the model

Given the rows, document \(d\) contributes the likelihood

\[ p(y_d\mid A_d,\pi,B) = \sum_{z_0,\ldots,z_T} \pi_{z_0} \prod_{t=1}^{T} A_{d,z_{t-1},z_t}\, B_{z_t,y_{dt}}. \]

The joint density multiplies these likelihoods by the two sets of Dirichlet row densities and the shared hyperprior. The same row can be visited several times along one path. Integrating that row out then requires its joint moments. The scans below sum the hidden states conditional on the sampled rows. This example uses a fixed epsilon-free HMM and a hyperprior on \(\alpha\). The paper formulates a broader probabilistic finite-state model with silent transitions and halting and learns the Dirichlet concentrations by variational empirical Bayes. Cui and Eisner (2006), §§1.3, 2.2, and 3.

Walkthrough

Each scan carries a marginalized state and scores one document. The first uses the sequence input as its observations. The second takes an observation sequence with the same extent through symbol_b. The initial state emits nothing. Each chain starts with its own initial state distributed as \(\pi\).

The complete log joint and its gradients are checked by independently enumerating the 32 paths for each of two four-symbol documents. For a two-state transition row, write \(A_{di}=(p,1-p)\) and \(\eta_{di}=\log(p/(1-p))\). A path contributes the derivative \(n_{i0}(1-p)-n_{i1}p\) to its log weight, where \(n_{ij}\) is the number of times it uses the edge \(i\to j\). The derivative of the document's log likelihood is the path-weighted mean of those derivatives. The Dirichlet and Gamma density derivatives give the remaining joint terms.

Try it

import itertools
import math
from fractions import Fraction
from pathlib import Path

import torch

from quivers.continuous.tensor_backend import TensorBackend
from quivers.dsl import Compiler, parse
from quivers.qiec import dumps, loads, run_program

source = Path("docs/examples/source/finite_state_dirichlet_allocation.qvr").read_text()
compiler = Compiler(parse(source))
program = compiler.compile()
module = loads(dumps(compiler.qiec_module))

documents = ((0, 0, 1, 0), (1, 0, 1, 1))
first, second = torch.tensor(documents)
data = {"symbol": first, "symbol_b": second}
dtype = torch.float64
initial = torch.tensor([1 / 4, 3 / 4], dtype=dtype)
emission = torch.tensor([[7 / 8, 1 / 8], [1 / 4, 3 / 4]], dtype=dtype)
log_alpha = torch.nn.Parameter(torch.tensor([[3.0, 2.0], [1.5, 4.0]], dtype=dtype).log())
logits = torch.nn.Parameter(
    torch.logit(torch.tensor([[7 / 8, 1 / 4], [3 / 8, 5 / 8]], dtype=dtype))
)
table_names = ("transition_a", "transition_b")


def site_values():
    p = logits.sigmoid()
    rows = torch.stack((p, 1 - p), dim=-1)
    return {
        "alpha": log_alpha.exp(),
        **dict(zip(table_names, rows, strict=True)),
        "emission": emission,
        "initial": initial,
    }


def path_oracle(transition, symbols):
    start = tuple(map(Fraction, initial.tolist()))
    emit = tuple(tuple(map(Fraction, row)) for row in emission.tolist())
    rows = tuple(tuple(map(Fraction, row)) for row in transition.detach().tolist())
    total = Fraction(0)
    derivative = [Fraction(0), Fraction(0)]
    for states in itertools.product(range(2), repeat=len(symbols) + 1):
        edges = tuple(zip(states[:-1], states[1:], strict=True))
        mass = start[states[0]] * math.prod(
            rows[i][j] * emit[j][symbol]
            for (i, j), symbol in zip(edges, symbols, strict=True)
        )
        total += mass
        for i, j in edges:
            derivative[i] += mass * (int(j == 0) - rows[i][0])
    return math.log(float(total)), [float(value / total) for value in derivative]


def joint_oracle(sites):
    alpha = sites["alpha"].detach()
    # Gamma(2, 1) has density x exp(-x). The Dirichlet(1, 1)
    # initial and emission priors have constant unit density.
    value = math.fsum(math.log(a) - a for a in alpha.flatten().tolist())
    d_alpha = 1 / alpha - 1
    row_totals = alpha.sum(dim=1, keepdim=True)
    prior_gradient = torch.special.digamma(row_totals) - torch.special.digamma(alpha)
    d_logits = torch.empty_like(logits)
    for d, (name, symbols) in enumerate(zip(table_names, documents, strict=True)):
        transition = sites[name].detach()
        log_likelihood, d_likelihood = path_oracle(transition, symbols)
        for a, row in zip(alpha.tolist(), transition.tolist(), strict=True):
            value += math.lgamma(math.fsum(a))
            value += math.fsum(
                (concentration - 1) * math.log(probability) - math.lgamma(concentration)
                for concentration, probability in zip(a, row, strict=True)
            )
        value += log_likelihood
        d_alpha += prior_gradient + transition.log()
        p = transition[:, 0]
        d_logits[d] = (
            logits.new_tensor(d_likelihood)
            + (alpha[:, 0] - 1) * (1 - p)
            - (alpha[:, 1] - 1) * p
        )
    return value, (d_alpha * alpha, d_logits)


def checked_score(sites, checked_module=module):
    return run_program(
        checked_module, "fsda", data=data, sites=sites, distributions=TensorBackend()
    ).log_joint


starting = site_values()
initial_joint, initial_grads = joint_oracle(starting)
reference = program.run(
    "fsda", data=data, sites={name: value.detach() for name, value in starting.items()}
).log_joint
assert math.isclose(reference.item(), initial_joint, rel_tol=0.0, abs_tol=2e-12)

for mutation in (
    source.replace("probs=transition_b[previous]", "probs=transition_a[previous]").replace(
        "apply chain_b [transition_b, emission, initial]",
        "apply chain_b [transition_a, emission, initial]",
    ),
    source.replace(
        "let transition_b : State <- sample Dirichlet(concentration=alpha)",
        "let transition_b : State <- sample Dirichlet(concentration=1.0)",
    ),
):
    changed = Compiler(parse(mutation)).qiec_module
    wrong = checked_score(site_values(), changed)
    wrong_grads = torch.autograd.grad(wrong, (log_alpha, logits))
    assert abs(wrong.item() - initial_joint) > 0.1
    gradient_errors = (
        (actual - exact).abs().max().item()
        for actual, exact in zip(wrong_grads, initial_grads, strict=True)
    )
    assert max(gradient_errors) > 0.1

coordinates = (log_alpha, logits)
for _ in range(4):
    sites = site_values()
    expected, gradients = joint_oracle(sites)
    compiled = program.morphism.log_joint(
        first[None], sites | {"symbol_b": second[None]}
    )
    checked = checked_score(sites)
    for score, tolerance in ((compiled.sum(), 2e-6), (checked, 2e-12)):
        assert math.isclose(score.item(), expected, rel_tol=0.0, abs_tol=tolerance)
        actual_grads = torch.autograd.grad(score, coordinates, retain_graph=True)
        for actual, exact in zip(actual_grads, gradients, strict=True):
            torch.testing.assert_close(actual, exact, rtol=0.0, atol=tolerance)
    update = torch.autograd.grad(checked, coordinates)
    with torch.no_grad():
        for value, gradient in zip(coordinates, update, strict=True):
            value.add_(gradient, alpha=1 / 64)

fitted = site_values()
fitted_joint = checked_score(fitted).item()
assert math.isclose(fitted_joint, joint_oracle(fitted)[0], rel_tol=0.0, abs_tol=2e-12)
assert fitted_joint > initial_joint

The two changes respectively pool the document transitions in the second chain and give its transition rows a separate flat prior. Both produce a different joint and derivative at the same parameter values. The four updates use the differentiable reference machine with the tensor backend. The replay on the host-number backend checks the value, and the compiled PyTorch execution checks both the value and gradient.

For \(K\) states and equal length \(T\), \(D\) documents have \(D K^{T+1}\) path terms across the separate likelihood sums. Each dense forward step combines \(K^2\) source–destination pairs. The scans use \(O(D T K^2)\) arithmetic, and the row priors add \(O(D K^2)\). The forward recurrence carries \(K\) entries per chain. The differentiable execution may retain pairwise work from each position for its backward pass. Here the exhaustive path and density oracle checks the native values and gradients at absolute tolerance \(2\cdot10^{-12}\). The compiled PyTorch check uses \(2\cdot10^{-6}\) to account for scalar family literals in the default tensor dtype. External code targets report the existing marginalized scan capability requirement.