Skip to content

Path-dependent particle smoothing

Overview

Two marked arcs can emit the same symbols and end in the same transducer state while leaving different recurrent states. A later arc can then have a different score on each history. A particle represents one of those histories, retaining the original action indices when it copies an ancestor. Lin, Zhu, Gormley, and Eisner (2019), §§2–3.

QVR source

The QVR computations define the recurrent state and path weight, a lookahead depending on the next observation, and the objective used to train the proposal.

define target(previous : Real, symbol : Real, action : Real, theta : Real) : Real * LogWeight !{} =
    let state = tanh(0.4 * previous + theta * (1.0 + action) + 0.1 * symbol)
    return (state, weight((1.0 + action) * previous + 0.25 * state))

define lookahead(state : Real, following : Real, phi : Real) : Real !{} =
    return phi * tanh(state * following)

define proposal_kl(target_odds : Real, base_odds : Real, feature_gap : Real, phi : Real) : Real !{} =
    let odds = base_odds + phi * feature_gap
    let q = 1.0 / (1.0 + exp(-odds))
    let log_q0 = -log(1.0 + exp(odds))
    let log_p0 = -log(1.0 + exp(target_odds))
    return log_q0 - log_p0 + q * (odds - target_odds)

Understanding the model

Here the input has two symbols. Each stage has two possible actions. The actions at the first stage both emit 0. An action at the second stage emits its own index. An authored recurrent computation gives the next state and target log potential. A second computation uses the remaining input to choose a positive lookahead twist. Lin and Eisner (2018), §§3–4.

The target and lookahead run as checked QVR computations. The particle engine applies the proposal correction and resamples between stages. The last weighted population estimates the probability of each output. It also gives a target gradient estimate for the unnormalized mass of the paths ending in 1.

Walkthrough

Evaluate the filter at a fixed parameter and compare its estimates with enumeration of the four histories. Then fit the lookahead and compare its proposal with the exact one-step odds.

Try it

Run this from the repository root.

Check the particle estimates against enumeration

import math
from pathlib import Path

import torch

from quivers.dsl import Compiler, parse
from quivers.inference import sequence_particle_filter
from quivers.qiec import dumps, loads, run_named

source = Path("docs/examples/qiec/path-dependent-particle-smoothing.qvr").read_text()
module = loads(dumps(Compiler(parse(source)).qiec_module))
theta = torch.nn.Parameter(torch.tensor(0.3, dtype=torch.float64))
phi = torch.nn.Parameter(theta.new_tensor(0.5))
symbols = (0.0, 2.0)
population = 8


def evaluate(name, arguments):
    return run_named(module, name, arguments, fuel=128, record_trace=False).value


def advance(step, current_states):
    values = [
        evaluate("target", (row[0], symbols[step], float(action), theta))
        for row in current_states
        for action in range(2)
    ]
    states, scores = zip(*values, strict=True)
    return torch.stack(states).reshape(population, 2, 1), torch.stack(scores).reshape(
        population, 2
    )


def propose(step, successors, log_target):
    if step == len(symbols) - 1:
        return log_target, torch.zeros_like(log_target)
    twist = torch.stack([
        evaluate("lookahead", (state, symbols[step + 1], phi))
        for state in successors.flatten()
    ]).reshape_as(log_target)
    return log_target + twist, twist


def particle_run(seed):
    return sequence_particle_filter(
        theta.new_zeros(1),
        advance,
        propose,
        steps=len(symbols),
        particles=population,
        actions=2,
        max_candidates=32,
        max_state_elements=16,
        generator=torch.Generator().manual_seed(seed),
    )


result = particle_run(7)
assert result.candidate_count == 32
event = result.paths[:, 1] == 1
probability_of_01 = result.log_probabilities[event].exp().sum()
assert 0 <= probability_of_01 <= 1 + 2e-14


def enumerate_score(path):
    h = derivative = log_weight = score_derivative = 0.0
    for symbol, action in zip(symbols, path, strict=True):
        following = math.tanh(0.4 * h + theta.item() * (1 + action) + 0.1 * symbol)
        d_following = (1 - following**2) * (0.4 * derivative + 1 + action)
        log_weight += (1 + action) * h + 0.25 * following
        score_derivative += (1 + action) * derivative + 0.25 * d_following
        h, derivative = following, d_following
    return log_weight, score_derivative


assert enumerate_score((0, 1))[0] != enumerate_score((1, 1))[0]
expected_gradient = 0.0
for path, score, log_probability in zip(
    result.paths.tolist(), result.target_log_scores, result.log_probabilities, strict=True
):
    expected_score, derivative = enumerate_score(path)
    assert math.isclose(score.item(), expected_score, abs_tol=2e-14)
    if path[-1] == 1:
        expected_gradient += math.exp(
            result.log_normalizer.item() + log_probability.item()
        ) * derivative

gradient, proposal_gradient = torch.autograd.grad(
    result.score_surrogate(event), (theta, phi), allow_unused=True
)
assert math.isclose(gradient.item(), expected_gradient, rel_tol=2e-14)
assert proposal_gradient is None

Both histories \((0,1)\) and \((1,1)\) emit the word 01. Their different scores follow from the recurrent state at the second position. The oracle checks the score and its derivative along each sampled history. The finite population can miss an output with positive model probability. The unnormalized gradient estimator has a separate expectation identity under the sampling law.

Fit the lookahead proposal

At the last step the proposal normalizes the two target potentials given the first action. It is thus the target's exact conditional law there. The exclusive KL divergence between the proposal and the target path distributions reduces to the divergence between their first-action marginals. This small model lets us enumerate the target marginal. Lin and Eisner (2018), §5 and Appendix B.

Write \(z_\phi=b+\phi\Delta f\) for the proposal log odds of first action 1, with \(b\) the difference in first-step target scores and \(\Delta f\) the difference in the lookahead features. Write \(z_*\) for the true target log odds. If \(q=\operatorname{sigmoid}(z_\phi)\), the derivative of the exclusive KL objective is \(\Delta f\,q(1-q)(z_\phi-z_*)\). Here \(\Delta f\ne0\), so the optimum is \(\phi_*=(z_*-b)/\Delta f\). The code checks the authored gradient at every update while holding the original target fixed.

with torch.no_grad():
    prefixes = [evaluate("target", (0.0, symbols[0], float(a), theta)) for a in range(2)]
    first_scores = torch.stack([score for _, score in prefixes])
    first_log_masses = torch.stack([
        score + torch.logsumexp(
            torch.stack([
                evaluate("target", (state, symbols[1], float(b), theta))[1]
                for b in range(2)
            ]),
            dim=0,
        )
        for state, score in prefixes
    ])
    features = torch.stack([
        evaluate("lookahead", (state, symbols[1], 1.0)) for state, _ in prefixes
    ])
    target_odds = first_log_masses[1] - first_log_masses[0]
    base_odds = first_scores[1] - first_scores[0]
    feature_gap = features[1] - features[0]

masses = [
    math.fsum(math.exp(enumerate_score((a, b))[0]) for b in range(2))
    for a in range(2)
]
exact_z = math.fsum(masses)
exact_p = masses[1] / exact_z
reference_odds = math.log(masses[1] / masses[0])
states = [math.tanh(theta.item() * (1 + a) + 0.1 * symbols[0]) for a in range(2)]
reference_base = 0.25 * (states[1] - states[0])
reference_gap = math.tanh(states[1] * symbols[1]) - math.tanh(states[0] * symbols[1])
optimum = (reference_odds - reference_base) / reference_gap

rate = 2.0 / feature_gap.item()**2
for _ in range(64):
    loss = evaluate("proposal_kl", (target_odds, base_odds, feature_gap, phi))
    target_gradient, proposal_gradient = torch.autograd.grad(
        loss, (theta, phi), allow_unused=True
    )
    q_odds = reference_base + phi.item() * reference_gap
    q = 1 / (1 + math.exp(-q_odds))
    exact_loss = (
        q * math.log(q / exact_p) + (1 - q) * math.log((1 - q) / (1 - exact_p))
    )
    exact_gradient = reference_gap * q * (1 - q) * (q_odds - reference_odds)
    assert math.isclose(loss.item(), exact_loss, rel_tol=0, abs_tol=2e-14)
    assert math.isclose(proposal_gradient.item(), exact_gradient, rel_tol=0, abs_tol=2e-14)
    assert target_gradient is None
    with torch.no_grad():
        phi.sub_(proposal_gradient, alpha=rate)
assert math.isclose(phi.item(), optimum, rel_tol=0, abs_tol=1e-12)

assert abs(result.log_normalizer.exp().item() - exact_z) > 1e-3
for seed in (3, 7, 12):
    fitted = particle_run(seed)
    assert math.isclose(fitted.log_normalizer.exp().item(), exact_z, rel_tol=0, abs_tol=2e-11)
    target_gradient, proposal_gradient = torch.autograd.grad(
        fitted.score_surrogate(fitted.paths[:, 1] == 1),
        (theta, phi),
        allow_unused=True,
    )
    assert torch.isfinite(target_gradient)
    assert proposal_gradient is None

The chosen gradient step multiplies the error in \(\phi\) by \(1-2q(1-q)\), so the iterates approach \(\phi_*\) within the interval between the start and the optimum. At the optimum, the first-step twist is a constant \(k>0\) times the exact suffix mass for either action. The first-stage weights all equal \(kZ\), and the last-stage weights all equal \(1/k\). The estimated normalizer is thus \(Z\) for every draw in exact arithmetic. The normalized output estimates still reflect the sampled histories.

See the sequential path particle API for the support conditions, estimator identities, and cost bounds.