Variational Information Bottleneck for Parsing¶
Overview¶
How much information about a word's context does a parser need? Li and Eisner's variational information bottleneck (VIB) learns a distribution over compressed token representations, using a parsing loss and two Kullback–Leibler (KL) penalties. We use the continuous objective in their equation (3) with a scalar Gaussian encoder and a globally normalized, unlabeled projective decoder. Li and Eisner (2019)
QVR source¶
Open the complete QVR source. The program computes the Gaussian encodings, projective tree loss, and analytic KL terms.
object Word : FinSet 3
object Node : FinSet 4
object Result : Real 1
# The final node is the artificial root. It has a learned code and no KL term.
program bottleneck(x : Real[Fin Word], x_type : Real[Fin Word], noise : Real[Fin Word], gold : Real[Fin Node, Fin Node], encoder : Real[Fin 5], prior : Real[Fin 2], type_encoder : Real[Fin 3], decoder : Real[Fin 3]) : Node -> Result
let hidden = tanh(encoder[0] * x + encoder[1])
let mu = encoder[2] * hidden
let log_sd = encoder[3] * hidden + encoder[4]
let ref_delta = log_sd - prior[1]
let type_mu = type_encoder[0] * x_type + type_encoder[1]
let type_delta = log_sd - type_encoder[2]
let kl_ref = 0.5 * (expm1(2.0 * ref_delta) - 2.0 * ref_delta + pow((mu - prior[0]) * exp(-prior[1]), 2.0))
let kl_type = 0.5 * (expm1(2.0 * type_delta) - 2.0 * type_delta + pow((mu - type_mu) * exp(-type_encoder[2]), 2.0))
let code = concat(mu + exp(log_sd) * noise, [decoder[0]])
let arcs = factor h : Node in factor d : Node in decoder[1] * code[h] * code[d] + decoder[2] * code[h]
let nll = projective_tree_partition(arcs) - sum(sum(gold * arcs))
let loss = nll + 0.4 * sum(kl_ref) + 0.3 * sum(kl_type)
return loss
export bottleneck
Understanding the model¶
Objective¶
For each token, the encoder maps a contextual feature \(x_i\) to a Normal distribution \(p_i=\mathcal{N}(\mu_i,\sigma_i^2)\). The reference distribution \(r\) is shared across tokens. A second encoder maps a context-independent feature \(\hat x_i\) to a Normal distribution \(s_i\). For an observed sentence and dependency tree \(y\), the loss is
The decoder scores each arc from the codes at its two endpoints. The gold tree's score is the sum over its arcs. Subtracting this score from the log partition over projective single-root trees gives the negative log probability. The artificial root has a learned deterministic code and contributes no KL term. The example uses three words per sentence and \(\beta=0.4\), \(\gamma=0.3\).
QVR takes standard Normal noise as an explicit input and computes \(t_i=\mu_i+\sigma_i\epsilon_i\). This makes the pathwise derivative available at the same noise values used for the forward pass. Each draw estimates the expected parsing loss, while the KL terms are analytic. For finite parameter values the decoder scores and their derivatives grow at most polynomially in the Gaussian noise in a compact parameter neighborhood. This permits differentiation under the Gaussian expectation. For a sentence of length \(n\) with scalar codes, the dense arc construction costs \(O(n^2)\) and the tree partition and its first reverse pass each cost \(O(n^3)\) time and \(O(n^2)\) space. Averaging \(k\) independent draws multiplies the parsing work by \(k\).
Walkthrough¶
Check the loss and its derivative¶
Fix the encoder noise so the QVR computation and the independent calculation score the same codes. Enumerate projective trees for the partition term and compute both Gaussian KL terms in closed form. Compare the QVR derivative with the derivative of this calculation and with a directional finite difference.
Fit the encoder and decoder¶
Average the loss over sampled noises for two synthetic sentences. The optimizer updates both encoders, the shared reference distribution, and the decoder, including its artificial root code.
Try it¶
Run this from the repository root. The Python code provides the observed trees, the encoder noise, and the optimizer state.
from itertools import product
from pathlib import Path
import torch
from torch.distributions import Normal, kl_divergence
from quivers.dsl import loads
from quivers.qiec import run_program
source = Path("docs/examples/qiec/variational-parsing-bottleneck.qvr").read_text()
module = loads(source).qiec
words = range(3)
root = 3
def projective_trees():
for parents in product(range(4), repeat=3):
if parents.count(root) != 1:
continue
spans = [{i} for i in words]
for child in words:
visited = {child}
head = parents[child]
while head != root and head not in visited:
spans[head].add(child)
visited.add(head)
head = parents[head]
if head != root:
break
else:
if all(len(span) == max(span) - min(span) + 1 for span in spans):
yield parents
trees = tuple(projective_trees())
def point(values):
return torch.tensor(values, dtype=torch.float64)
def sentence(x, x_type, parents):
assert parents in trees
gold = point([[0.0] * 4 for _ in range(4)])
gold[parents, tuple(words)] = 1
return {"x": point(x), "x_type": point(x_type), "gold": gold}
examples = (
sentence((-1.2, 0.6, 1.4), (-0.7, 0.1, 0.4), (3, 0, 0)),
sentence((0.6, 1.4, -1.2), (0.1, 0.4, -0.7), (2, 2, 3)),
)
names = ("encoder", "prior", "type_encoder", "decoder")
parameters = (
point((0.8, 0.1, 0.9, -0.3, -0.5)).requires_grad_(),
point((0.2, -0.1)).requires_grad_(),
point((0.1, -0.4, -0.6)).requires_grad_(),
point((0.6, 0.5, -0.8)).requires_grad_(),
)
def loss(parameters, example, noise, model=module):
data = dict(example, noise=noise, **dict(zip(names, parameters, strict=True)))
return run_program(model, "bottleneck", data=data, sites={}).value
def oracle(parameters, example, noise):
enc, prior, type_enc, dec = parameters
h = (enc[0] * example["x"] + enc[1]).tanh()
token = Normal(enc[2] * h, (enc[3] * h + enc[4]).exp())
ref = Normal(prior[0], prior[1].exp())
type_ = Normal(type_enc[0] * example["x_type"] + type_enc[1], type_enc[2].exp())
t = torch.cat((token.loc + token.scale * noise, dec[0:1]))
scores = dec[1] * torch.outer(t, t) + dec[2] * t[:, None]
tree_scores = torch.stack([scores[heads, tuple(words)].sum() for heads in trees])
nll = tree_scores.logsumexp(0) - (scores * example["gold"]).sum()
return (
nll + 0.4 * kl_divergence(token, ref).sum()
+ 0.3 * kl_divergence(token, type_).sum()
)
assert len(trees) == 7
noise = point((-0.8, 1.3, 0.2))
observed = loss(parameters, examples[0], noise)
expected = oracle(parameters, examples[0], noise)
torch.testing.assert_close(observed, expected, rtol=1e-11, atol=1e-11)
gradient = torch.autograd.grad(observed, parameters)
expected_gradient = torch.autograd.grad(expected, parameters)
for actual, target in zip(gradient, expected_gradient, strict=True):
torch.testing.assert_close(actual, target, rtol=1e-10, atol=1e-11)
assert torch.linalg.vector_norm(actual) > 1e-3
direction = tuple(torch.linspace(-0.4, 0.7, p.numel(), dtype=p.dtype) for p in parameters)
step = 1e-5
plus = tuple(p + step * d for p, d in zip(parameters, direction, strict=True))
minus = tuple(p - step * d for p, d in zip(parameters, direction, strict=True))
finite_difference = (loss(plus, examples[0], noise) - loss(minus, examples[0], noise)) / (2 * step)
directional = sum(g @ d for g, d in zip(gradient, direction, strict=True))
torch.testing.assert_close(directional, finite_difference, rtol=1e-8, atol=1e-9)
for old, new in (
("0.3 * sum(kl_type)", "0.0 * sum(kl_type)"),
("exp(log_sd) * noise", "noise"),
):
assert source.count(old) == 1
mutant = loads(source.replace(old, new)).qiec
assert abs(loss(parameters, examples[0], noise, mutant) - observed) > 1e-3
generator = torch.Generator().manual_seed(71)
def draw_noises(count):
return torch.randn((count, len(examples), 3), generator=generator, dtype=torch.float64)
def mean_loss(noises):
return torch.stack([
loss(parameters, example, sample)
for batch in noises
for example, sample in zip(examples, batch, strict=True)
]).mean()
evaluation = draw_noises(12)
with torch.no_grad():
start = mean_loss(evaluation)
optimizer = torch.optim.Adam(parameters, lr=0.045)
for _ in range(35):
optimizer.zero_grad()
mean_loss(draw_noises(4)).backward()
optimizer.step()
with torch.no_grad():
finish = mean_loss(evaluation)
assert finish < start - 0.5