Skip to content

Minimum-risk annealing

Overview

A latent alignment path \(p\) has a log score \(s_\theta(p)\) and an additive loss \(C(p)\). At inverse temperature \(\gamma\), the risk is

\[ R_\gamma(\theta) = \frac{\sum_p \exp(\gamma s_\theta(p)) C(p)} {\sum_p \exp(\gamma s_\theta(p))}. \]

QVR source

The QVR program queries path mass, entropy, and expected cost for two groups, then computes the annealed risk.

object Letters : FinSet 2
object ScoreClass : FinSet 2

relation aligner [algebra=logprob, states=4]
    input Letters
    output Letters
    output ScoreClass
    initial 0 [weight=unit_weight]
    arc 0 -> 1 [labels=(0, eps, 0), weight=feature]
    arc 0 -> 1 [labels=(0, eps, 0), weight=feature]
    arc 1 -> 2 [labels=(eps, 1, eps), weight=feature]
    arc 0 -> 3 [labels=(0, 1, 1), weight=unit_weight]
    arc 0 -> 2 [labels=(0, 0, 0), weight=unit_weight]
    final 2 [weight=unit_weight]
    final 3 [weight=bonus]

define left_partition : LogWeight = pair_weight(aligner)
define right_partition : LogWeight = pair_weight(aligner)
define left_entropy : Real = path_entropy(aligner)
define right_entropy : Real = path_entropy(aligner)
define left_loss : Real = expected_path_cost(aligner)
define right_loss : Real = expected_path_cost(aligner)

define temper(log_mass : LogWeight, entropy : Real, gamma : Real) : Real !{} =
    return exp(gamma * (weight_value(log_mass) - entropy) + entropy)

define annealed_risk(gamma : Real) : Real !{} =
    let z0 <- left_partition()
    let z1 <- right_partition()
    let h0 <- left_entropy()
    let h1 <- right_entropy()
    let r0 <- left_loss()
    let r1 <- right_loss()
    let a <- temper(z0, h0, gamma)
    let b <- temper(z1, h1, gamma)
    return (a * r0 + b * r1) / (a + b)

Understanding the model

The example keeps the same finite set of paths and successively fits the live parameter at \(\gamma=0, 1/2, 1, 2\). At zero, the fixed support has a uniform distribution. At one, the objective is ordinary expected path loss. Increasing \(\gamma\) favors high-scoring paths. Each stage uses the fixed-\(\gamma\) expected-loss objective from equation (6). Smith and Eisner (2006), ยง3.

The relation has an extra tape identifying two score classes. In each class \(j\), all \(m_j\) paths have the same finite log score \(s_j\) for every parameter value. The two paths of the first class use parallel arcs with a shared weight and can incur different losses.

QVR queries the original relation for the class log mass \(L_j\), path entropy \(H_j\), and expected additive loss \(R_j\). Equal path scores give \(H_j=\log m_j\) and \(L_j=s_j+H_j\). The class log mass after tempering is

\[ \log Z_{\gamma,j}=H_j+\gamma(L_j-H_j). \]

The distribution within each class remains uniform. QVR can thus reuse the class expected loss and combine the class masses in one authored objective. The equality of path scores follows from the shared weight occurrences in this relation. It is a precondition for this construction.

Walkthrough

Evaluate the objective at four inverse temperatures. At the final value of \(\gamma\), temper each class sum directly to see how that changes both the objective and its derivative.

Try it

Run this from the repository root.

import math
from pathlib import Path

import torch

from quivers.dsl import Compiler, parse
from quivers.qiec import (
    FixedRelationCostRequest,
    FixedRelationRequest,
    FixedRelationRuntimeProvider,
    ParameterId,
    RuntimeConfiguration,
    dumps,
    loads,
    run_named,
)

source = Path("docs/examples/qiec/minimum-risk-annealing.qvr").read_text()

module_name = "annealed_minimum_risk"
compiler = Compiler(parse(source), module_name=module_name)
relation = compiler.relation_specs["aligner"]
module = loads(dumps(compiler.qiec_module))
theta = torch.nn.Parameter(torch.tensor(0.0, dtype=torch.float64))
weights = {
    ParameterId.derive(module_name, "relation_weights", "feature"): theta,
    ParameterId.derive(module_name, "relation_weights", "unit_weight"): theta.new_zeros(()),
    ParameterId.derive(module_name, "relation_weights", "bonus"): theta.new_tensor(math.log(2)),
}
providers = []
for prefix, group in (("left", 0), ("right", 1)):
    observation = dict(
        relation=relation,
        words=((0,), (1,), (group,)),
        max_states=16,
        max_work=32,
    )
    requests = {
        "partition": FixedRelationRequest(operation="pair_weight", **observation),
        "entropy": FixedRelationRequest(operation="path_entropy", **observation),
        "loss": FixedRelationCostRequest(
            arc_costs=(3.0, 1.0, 0.0, 0.0, 100.0), **observation,
        ),
    }
    providers.extend(
        FixedRelationRuntimeProvider.for_score(
            f"{prefix}_{score}", loads(dumps(request)), weights
        )
        for score, request in requests.items()
    )
runtime = RuntimeConfiguration(providers=tuple(providers))


def risk_at(gamma, checked_module=module):
    return run_named(
        checked_module, "annealed_risk", (gamma,), runtime=runtime
    ).value


def check_at(loss, expected, derivative):
    (gradient,) = torch.autograd.grad(loss, theta)
    assert math.isclose(loss.item(), expected, rel_tol=0.0, abs_tol=1e-14)
    assert math.isclose(gradient.item(), derivative, rel_tol=0.0, abs_tol=1e-14)


check_at(risk_at(0.0), 4 / 3, 0)
check_at(risk_at(1.0), 1, 1)
check_at(risk_at(2.0), 2 / 3, 16 / 9)
assert not math.isclose(risk_at(1.0).item(), 2 / 3)

# Temper the class sum as if it were the score of a single path.
wrong_source = source.replace(
    "gamma * (weight_value(log_mass) - entropy) + entropy",
    "gamma * weight_value(log_mass)",
)
wrong_module = Compiler(parse(wrong_source), module_name=module_name).qiec_module
check_at(risk_at(2.0, wrong_module), 1, 2)

optimizer = torch.optim.SGD([theta], lr=1 / 32)
for gamma in (0.0, 0.5, 1.0, 2.0):
    for _ in range(2):
        optimizer.zero_grad()
        left_mass = 2 * math.exp(2 * gamma * theta.item())
        right_mass = 2**gamma
        total_mass = left_mass + right_mass
        expected = 2 * left_mass / total_mass
        derivative = 2 * gamma * expected * right_mass / total_mass

        risk = risk_at(gamma)
        risk.backward()
        assert math.isclose(risk.item(), expected, rel_tol=0.0, abs_tol=1e-14)
        assert math.isclose(theta.grad.item(), derivative, rel_tol=0.0, abs_tol=1e-14)
        optimizer.step()
assert theta.item() < 0.0

The first two paths score \(2\theta\) and cost 3 and 1. The third scores \(\log 2\) at its final mark and costs 0. For observed pair \((0,1)\) these are all the paths. The fourth structural route emits \((0,0)\) and its cost contributes zero to this objective. At \(\theta=0\) and \(\gamma=2\), the first class has mass 2 and the second has mass 4. The risk is \(2/3\) and its derivative is \(16/9\). Tempering the class sum as a single path would give the first class mass 4, raising the risk to 1 and changing the derivative to 2.

Each fixed observation has a sparse state and arc budget. The requests and original weights stay in place across the schedule. The comparison uses all three accepting paths to check binary64 values and derivatives after each of eight local gradient evaluations. This bounded construction applies to finite positive path sets with a known partition by identical log score. The number of distinct score classes determines how many sparse queries and class terms it requires.