Skip to content

A contextual edit channel

Overview

A channel can assign different edit probabilities to the same symbol depending on what follows it. In this example, an embedding of the remaining input predicts the logits for the next edit. The same parameters score all alignments of all observed pairs.

QVR source

The batch request returns one log weight per observed pair. The program sums those weights. The Python script binds the foreign handler to the edit network.

instance batch : Compute[Unit, LogWeight[Fin 4]]
handler contextual_edits for Compute[Unit, LogWeight[Fin 4]] : LogWeight[Fin 4] -> LogWeight[Fin 4] [coverage=total, forwards=none, implementation=foreign]
    apply resumes 1

define likelihoods : LogWeight[Fin 4] !{} =
    handle batch with contextual_edits in
        let values <- perform batch.apply(unit)
        return values

object Trial : FinSet 1
object Result : Real 1

program observed_pairs : Trial -> Result
    let values <- likelihoods()
    let terms = map([0, 1, 2, 3], i -> weight_value(values[i]))
    score pairs = sum(terms)
    return pairs

export observed_pairs

Understanding the model

The channel allows deletion, replacement, and insertion. It allows one consecutive insertion, including at the end of the input. At each step, the normalization includes all legal edits, including edits incompatible with the observed output. The likelihood then sums just the alignments of the observed pair.

Walkthrough

Score the four input–output pairs and take one optimizer step on the contextual network. The same checked program reads the updated weights when it scores the batch again.

Try it

Run this from the repository root.

from pathlib import Path

import torch
from torch import nn

from quivers import FinSet, StringSet
from quivers.core.relations import ContextualEditChannel
from quivers.dsl import Compiler, parse
from quivers.qiec import (
    AttachmentId,
    ContextualEditRuntimeProvider,
    FixedContextualEditRequest,
    run_program,
)
from quivers.qiec.numbers import NumberDomain


class InputContext(nn.Module):
    def __init__(self):
        super().__init__()
        self.symbols = nn.Embedding(3, 8, padding_idx=2)
        self.edits = nn.Linear(8, 6)

    def forward(self, words):
        width = max(map(len, words)) + 1
        padded = torch.tensor(
            [word + (2,) * (width - len(word)) for word in words],
            device=self.symbols.weight.device,
        )
        encoded = self.symbols(padded)
        remaining = encoded.flip((1,)).cumsum(dim=1).flip((1,))
        return self.edits(remaining).unsqueeze(2).expand(-1, -1, 2, -1)


tape = StringSet(alphabet=FinSet(name="TwoSymbols", cardinality=2))
with torch.random.fork_rng(devices=[]):
    torch.manual_seed(713)
    channel = ContextualEditChannel(tape, tape, InputContext(), max_insertions=1)
owner = AttachmentId.derive("contextual_edit", "channel")
request = FixedContextualEditRequest(
    channel=owner,
    input_alphabet=("TwoSymbols", 2),
    output_alphabet=("TwoSymbols", 2),
    inputs=((0, 1), (0, 0), (), (1,)),
    outputs=((0,), (1, 0), (1,), ()),
    max_insertions=1,
    max_states=256,
    max_work=512,
)
source = Path("docs/examples/qiec/contextual-edit-channel.qvr").read_text().replace(
    "contextual_edits", request.handler_name
)
compiler = Compiler(parse(source), module_name="contextual_edit")
compiler.compile()
module = compiler.qiec_module
assert module is not None
provider = ContextualEditRuntimeProvider(request, {owner: channel})
numbers = NumberDomain.of(next(channel.parameters()))


def scored_batch():
    return run_program(
        module, "observed_pairs", data={}, sites={}, providers=(provider,), numbers=numbers,
    )


optimizer = torch.optim.Adam(channel.parameters(), lr=0.03)
initial = scored_batch()
torch.testing.assert_close(initial.log_joint, initial.value)
negative_log_likelihood = -initial.log_joint
negative_log_likelihood.backward()
assert all(parameter.grad is not None for parameter in channel.parameters())
assert torch.isfinite(negative_log_likelihood)
optimizer.step()
updated = scored_batch()
assert torch.isfinite(updated.log_joint) and updated.log_joint > initial.log_joint

The provider keeps one packed alignment plan. The QVR program sums its conditional log probabilities into the checked joint. Running the same program after an optimizer step reads the updated network weights.