Skip to content

Language Modeling Difficulty

Overview

A language model may assign high surprisal to a sentence because the sentence expresses more information, or because the model predicts that language less well. Mielke et al.'s multiplicative mixed-effects regression uses aligned texts to estimate these sources separately. We implement their heteroscedastic Model 2 with explicit priors and a small partially aligned dataset. Mielke et al. (2019), ยง3

QVR source

Open the complete QVR source. The program reads parallel intent and language indices and scores only their observed rows.

object Intent : FinSet 4
object Language : FinSet 3
object Pair : FinSet 8
object Surprisal : Real 1

# Each row indexes an observed intent-language pair.
program language_difficulty(intent : Int[Fin Pair], language : Int[Fin Pair]) : Pair -> Surprisal
    let log_size : Intent <- sample Normal(loc=2.0, scale=1.0)
    let difficulty : Language <- sample Normal(loc=0.0, scale=0.5)
    let sigma <- sample HalfNormal(scale=0.6)
    let row_log_size = log_size[intent]
    let language_effect = difficulty[language]
    let base_variance = pow(sigma, 2.0)
    let log_excess = base_variance + log(-expm1(-base_variance))
    let variance = softplus(log_excess - row_log_size)
    let location = row_log_size + language_effect + 0.5 * (base_variance - variance)
    let scale = sqrt(variance)
    observe bits : Pair <- LogNormal(loc=location, scale=scale)
    return bits

export language_difficulty

Understanding the model

Model

An intent \(i\) has size \(n_i>0\). Language \(j\) has log difficulty \(d_j\). To motivate the observation model, suppose that each of the \(n_i\) units contributes independent log-normal noise with log variance \(\sigma^2\). For a positive integer \(n_i\), the mean and variance of the resulting surprisal \(Y_{ij}\) are

\[ \operatorname{E}[Y_{ij}]=n_i e^{d_j+\sigma^2/2}, \qquad \operatorname{Var}(Y_{ij})= n_i e^{2d_j+\sigma^2}(e^{\sigma^2}-1). \]

Model 2 uses a log-normal distribution that matches both moments and extends the resulting formula to any \(n_i>0\). Its log variance \(v_i\) and log location \(\ell_{ij}\) are

\[ v_i=\log\left(1+\frac{e^{\sigma^2}-1}{n_i}\right), \qquad \ell_{ij}=\log n_i+d_j+\frac{\sigma^2-v_i}{2}. \]

This gives less variable log surprisals to larger intents. QVR computes the variance in log space and observes the positive surprisal in bits, so the log-normal density includes the Jacobian for that outcome scale. Each observed row provides an intent index and a language index. The likelihood is a product over those rows, with no imputed scores for absent translations. Interpreting the fitted difficulties requires assumptions about the absence of translations, such as the missing-completely-at-random assumption discussed in Appendix A of the paper. The difficulties describe the language models that provided the surprisals.

Computing the log joint and its first derivatives requires linear time and space in the number of intents, languages, and observed pairs. The QVR source uses four intents, three languages, and eight observed pairs in the example below.

Walkthrough

Check the likelihood

For each observed pair, evaluate the Normal log density at the log surprisal and subtract that log surprisal to obtain the log density on the original scale. Add the log prior terms, then compare the result and its gradient with both QVR execution paths.

Fit and compare the languages

Fit the joint posterior mode. The observed pairs overlap across languages even though no intent occurs in all three, so the model can compare difficulties through shared intents.

Try it

Run this from the repository root. The script uses binary64 for both the authored distribution constants and the independent calculations.

from pathlib import Path

import torch
from torch.distributions import HalfNormal, Normal

from quivers.continuous.tensor_backend import TensorBackend
from quivers.dsl import loads
from quivers.qiec import run_program

torch.set_default_dtype(torch.float64)
source = Path("docs/examples/qiec/language-difficulty.qvr").read_text()
program = loads(source)
intent = torch.tensor((0, 0, 1, 1, 2, 2, 3, 3))
language = torch.tensor((0, 1, 1, 2, 2, 0, 1, 2))


def real(values):
    return torch.tensor(values, dtype=torch.float64)


def moments(log_size, difficulty, sigma):
    size = log_size[intent].exp()
    scale = difficulty[language].exp()
    mean = size * scale * (sigma.square() / 2).exp()
    variance = size * scale.square() * sigma.square().exp() * sigma.square().expm1()
    return mean, variance


def matched_parameters(log_size, difficulty, sigma):
    mean, variance = moments(log_size, difficulty, sigma)
    log_variance = (variance / mean.square()).log1p()
    return mean.log() - log_variance / 2, log_variance.sqrt()


truth = real((1.2, 2.0, 2.6, 3.2)), real((-0.45, 0.05, 0.5)), real(0.55)
location, scale = matched_parameters(*truth)
bits = (location + scale * real((-0.6, 0.5, 0.9, -0.3, -0.2, 0.6, -0.5, 0.4))).exp()
data = {"intent": intent, "language": language, "bits": bits}
names = ("log_size", "difficulty", "sigma")


def native(log_size, difficulties, sigma, model=program.qiec):
    return run_program(
        model, "language_difficulty", data=data,
        sites=dict(zip(names, (log_size, difficulties, sigma), strict=True)),
        distributions=TensorBackend(),
    ).log_joint


def oracle(log_size, difficulty, sigma):
    location, scale = matched_parameters(log_size, difficulty, sigma)
    observation = Normal(location, scale).log_prob(bits.log()) - bits.log()
    return (
        observation.sum()
        + Normal(2.0, 1.0).log_prob(log_size).sum()
        + Normal(0.0, 0.5).log_prob(difficulty).sum()
        + HalfNormal(sigma.new_tensor(0.6)).log_prob(sigma)
    )


point = tuple(t.clone().requires_grad_() for t in truth)
expected = oracle(*point)
actual = native(*point)
values = dict(data, **dict(zip(names, point, strict=True)))
compiled = program.morphism.log_joint(torch.zeros(1, dtype=torch.long), values).sum()
expected_gradient = torch.autograd.grad(expected, point)
for result in (actual, compiled):
    torch.testing.assert_close(result, expected, rtol=1e-10, atol=1e-10)
    for actual_grad, expected_grad in zip(
        torch.autograd.grad(result, point), expected_gradient, strict=True
    ):
        torch.testing.assert_close(actual_grad, expected_grad, rtol=1e-9, atol=1e-9)

for original, replacement in (
    ("softplus(log_excess - row_log_size)", "base_variance"),
    ("0.5 * (base_variance - variance)", "0.0"),
):
    assert source.count(original) == 1
    mutant = loads(source.replace(original, replacement)).qiec
    assert abs(native(*point, model=mutant) - actual) > 1e-3

log_size, difficulty, raw_sigma = (
    real((2.0, 2.1, 2.3, 2.7)).requires_grad_(),
    real((0.0, 0.0, 0.0)).requires_grad_(),
    real(-0.4).requires_grad_(),
)
optimizer = torch.optim.LBFGS(
    (log_size, difficulty, raw_sigma), max_iter=90, line_search_fn="strong_wolfe"
)


def closure():
    optimizer.zero_grad()
    # Optimize the density on sigma > 0 via unconstrained coordinates.
    loss = -native(log_size, difficulty, raw_sigma.exp())
    loss.backward()
    return loss


start = closure().detach()
optimizer.step(closure)
finish = closure().detach()
assert finish < start - 1.0
assert difficulty[0] < difficulty[1] < difficulty[2]