papie lemmatization · tagging · any language

Decoders

One class per decoder: value; AdvancedAttentionalDecoder subclasses AttentionalDecoder.

Generated from the source by tools/make_api.py; do not edit by hand.

papie.layers.decoders.attentional

Ported from pie.models.decoder.AttentionalDecoder:
https://github.com/emanjavacas/pie/blob/master/pie/models/decoder.py

Char-level seq2seq decoder with attention, used for lemmatization. Submodule
names (nll_weight buffer, embs, rnn, attn, proj) are kept
identical to PaPie so converted state_dict keys line up. The greedy
predict_max inference path is ported verbatim (it already keeps per-step
results on-device and stringifies once); predict_beam is not ported (no
Beam search in papie yet).

class AttentionalDecoder (nn.Module)

AttentionalDecoder(self, label_encoder, in_dim, hidden_size, dropout=0.0, num_layers=1, cell='LSTM', init_rnn='default', scorer='general', context_dim=0)
Decoder using attention over the entire input sequence

Parameters
===========
label_encoder : LabelEncoder of the task
in_dim : int, embedding dimension of the task.
    It should be the same as the corresponding encoder to ensure that weights
    can be shared.
hidden_size : int, hidden size of the encoder, decoder and attention modules.
context_dim : int (optional), dimensionality of additional context vectors

AttentionalDecoder.init

init(self)

AttentionalDecoder.forward

forward(self, targets, lengths, enc_outs, src_lengths, context=None)
Decoding routine for training. Returns the logits corresponding to
the targets for the loss method. Takes care of padding.

AttentionalDecoder.loss

loss(self, logits, targets)
Compute loss from logits (output of forward)

Parameters
===========
logits : tensor(seq_len x batch x vocab)
targets : tensor(seq_len x batch)

AttentionalDecoder.predict_max

predict_max(self, enc_outs, lengths, max_seq_len=20, bos=None, eos=None, context=None)
Decoding routine for inference with step-wise argmax procedure

Parameters
===========
enc_outs : tensor(src_seq_len x batch x hidden_size)
context : tensor(batch x hidden_size), optional

AttentionalDecoder.predict_beam

predict_beam(self, *args, **kwargs)

papie.layers.decoders.advanced_attentional

AdvancedAttentionalDecoder -- a drop-in upgrade of AttentionalDecoder.

Subclasses AttentionalDecoder (so it reuses embs/rnn/attn/proj/nll_weight
and satisfies every isinstance(decoder, AttentionalDecoder) check) and adds three
opt-in improvements for lemmatization:

1. **Copy / pointer-generator** (use_copy): mixes a copy distribution over the source
   characters (built from the attention weights scattered via the lemma-vocab source ids)
   with the generation softmax, gated by a learned p_gen. Lemmatization is mostly
   copying, so this helps rare/OOV forms (same idea the masked/Levenshtein decoders use).
2. **Source-conditioned init** (source_init): seeds the decoder's initial hidden state
   from a masked-mean summary of the source character states instead of zeros.
3. **Scheduled sampling** (scheduled_sampling > 0): during training, sometimes feed the
   model's own previous prediction instead of the gold char, reducing the teacher-forcing
   vs free-running exposure-bias mismatch. Needs a step-wise training forward; ε ramps
   scheduled_sampling_start -> scheduled_sampling_end over training.

The original AttentionalDecoder is untouched (its state_dict keys must keep matching
converted PaPie checkpoints).

class AdvancedAttentionalDecoder (AttentionalDecoder)

AdvancedAttentionalDecoder(self, label_encoder, in_dim, hidden_size, dropout=0.0, num_layers=1, cell='LSTM', init_rnn='default', scorer='general', context_dim=0, use_copy=True, source_init=True, scheduled_sampling=0.0, scheduled_sampling_start=0.0, scheduled_sampling_end=None, scheduled_sampling_max_epochs=None)

AdvancedAttentionalDecoder.update_curriculum

update_curriculum(self, progress)
Ramp scheduled-sampling ε from ss_start to ss_end by training
progress in [0, 1]. Called from PaPie.on_train_epoch_start.

AdvancedAttentionalDecoder.forward

forward(self, targets, lengths, enc_outs, src_lengths, context=None, source_ids=None)

AdvancedAttentionalDecoder.loss

loss(self, logits, targets)

AdvancedAttentionalDecoder.predict_max

predict_max(self, enc_outs, lengths, max_seq_len=20, bos=None, eos=None, context=None, source_ids=None, prune=True)
Greedy decode, seeded with the source-conditioned hidden state and using
the copy mixture; returns (hyps, scores) like the parent.

With prune (default) words that emitted <eos> leave the batch, and the
source states are trimmed to the longest remaining word, so later steps get
cheaper: the output is identical to prune=False (which keeps every word
until all are done, the previous behaviour).

papie.layers.decoders.levenshtein

Fully-parallel Levenshtein (edit-based) non-autoregressive lemma decoder.

Instead of generating the lemma from scratch, it predicts -- in a single forward
pass, with no decoding loop -- a per-source-position edit (COPY / DELETE /
REPLACE) plus a small bounded insertion in the gap after each position, applied
to the source surface form. A leading sentinel position carries prefix
insertions. Supervised by an edit-distance alignment of source vs gold lemma
(see edit_targets.build_edit_targets).

Source representation: the embedding's per-source-char states (enc_outs,
same tensor the attentional/masked decoders attend over) are the contextual
backbone; a learned embedding of the source ids (the copy signal), positional
embeddings and an optional per-word sentence context are added, then a
TransformerEncoder mixes positions. Three linear heads read out the edits.

Assumes char-aligned source states (use with the char BiRNN embedding, not the
byte-level ByT5 embedding).

class LevenshteinDecoder (nn.Module)

LevenshteinDecoder(self, label_encoder, in_dim, hidden_size, context_dim=0, num_heads=4, num_layers=2, dropout=0.1, max_insert_len=3, action_weight=1.0, replace_weight=0.7, insert_weight=0.5)

LevenshteinDecoder.init

init(self)

LevenshteinDecoder.forward

forward(self, source_ids, src_lengths, enc_outs, context=None, gold_ids=None)
Compute edit logits and stash the alignment targets for loss.

source_ids : (S, B) lemma-vocab ids of the source chars (index-aligned
    to enc_outs).
gold_ids : (T, B) gold lemma ids (with specials), for the alignment.

LevenshteinDecoder.loss

loss(self, outputs, targets)

LevenshteinDecoder.reconstruct

reconstruct(self, outputs, source_ids, src_lengths, decode=True, return_scores=False)
Apply the argmax edits in outputs to the source forms.

Returns a per-word list (char tokens if decode else lemma-vocab ids);
with return_scores also returns a per-word mean action log-prob.

LevenshteinDecoder.predict_max

predict_max(self, enc_outs, src_lengths, context=None, source_ids=None, **kwargs)
Single forward pass -> argmax edits -> reconstructed lemma per word.
Returns (hyps, scores) matching the other char decoders (each hyp is
a list of char tokens that ''.join rebuilds).

papie.layers.decoders.masked

Non-autoregressive, Mask-Predict-style char-level decoder for lemmatization.

Unlike AttentionalDecoder (RNN, autoregressive, one char per step), this
decoder predicts every position of a lemma slate in parallel and refines
uncertain positions over a few rounds (Ghazvininejad et al. 2019, "Mask-Predict:
Parallel Decoding of Conditional Masked Language Models"). Not ported from PaPie
-- there is no upstream equivalent.

Termination is handled the CMLM/Mask-Predict way: a source-conditioned **length
head** predicts the target length (as an offset from the source length), and at
inference the slate is sized to exactly that many slots -- the positions past it
are frozen to <pad> and never decoded. This replaces the previous design,
which started from a fixed-width all-<mask> slate and *hoped* the model would
emit <eos> at the right slot; with no reliable length signal that produced
non-terminating, repeated-character garbage tails ("utinam"->"utinummm") and
near-zero exact-match accuracy.

Each output slot's representation is a learnable positional embedding summed with
the embedding of that slot's current token (gold char during masked-LM training,
<mask>/a previous round's prediction at inference) and a gated projection of
the source word's same-index char encoder state (_source_term); the
source-copy term gives a monotonic "copy by default" prior so the model doesn't
have to discover the source<->lemma alignment from cross-attention alone. A stock
nn.TransformerDecoder (self-attention among slots + cross-attention over the
per-word char encoder outputs) produces the per-slot logits; there is no causal
mask -- every slot may attend to every other slot.

class MaskedCharacterDecoder (nn.Module)

MaskedCharacterDecoder(self, label_encoder, in_dim, hidden_size, dropout=0.0, context_dim=0, max_lemma_len=20, num_layers=2, num_heads=4, mask_ratio=0.3, full_mask_probability=0.5, full_mask_start=0.0, n_refinement_steps=3, label_smoothing=0.1, pad_loss_weight=0.1, use_length_head=True, max_off=10, length_weight=1.0, length_weight_end=0.3, curriculum=True, curriculum_max_epochs=None, copy_init=False, copy_init_prob=0.5, length_beam=1)
Non-autoregressive char-level decoder predicting a fixed-length lemma
slate in parallel, with iterative (Mask-Predict) refinement at inference
and a source-conditioned length head driving termination.

Parameters
===========
label_encoder : LabelEncoder of the task. Must have <pad>, <eos> and
    <mask> (the decoder raises if <mask> is missing; <eos> is required by
    label_encoder.stringify at inference).
in_dim : int, embedding dimension of the task (char + position embedding
    width).
hidden_size : int, width of enc_outs and of the transformer stack. Must
    match enc_outs's feature dim (as for AttentionalDecoder).
context_dim : int (optional), dimensionality of additional context vectors.
max_lemma_len : int, maximum number of output slots (incl. <bos>/<eos>).
num_layers : int, number of stacked TransformerDecoderLayers.
num_heads : int, attention heads per layer.
mask_ratio : float, fraction of valid positions masked at random during
    training (when not fully masking).
full_mask_probability : float, *steady-state* probability (per word) of
    masking the word's entire valid span during training, mimicking the
    all-masked state inference starts from. With curriculum=True this
    is the *end* value, ramped from full_mask_start.
full_mask_start : float, curriculum start value for full_mask_probability.
n_refinement_steps : int, number of Mask-Predict rounds at inference.
label_smoothing : float, label smoothing on the masked-position CE.
pad_loss_weight : float, weight given to <pad> targets in the token CE. Kept
    small (not zero): the length head is the primary termination mechanism,
    so pad reconstruction is only a light safety net -- weighting it like a
    normal class would let the long pad tail of short words dominate the
    full-mask loss and collapse the model to predicting <pad> everywhere.
max_off : int, half-width of the length head's offset classification range
    (predicts target_len - src_len clamped to [-max_off, +max_off]).
length_weight : float, weight of the length-head loss. With
    curriculum=True this is the *start* (early, high) value, ramped to
    length_weight_end so termination is learned first.
length_weight_end : float, curriculum end value for length_weight.
curriculum : bool, whether update_curriculum ramps
    full_mask_probability/length_weight across training.
copy_init : bool, source-copy initialization (Levenshtein-Transformer-style).
    When on, training fills a fraction of masked slots with the *source*
    character (index-aligned, in the lemma vocab) instead of <mask> so
    the model learns to *correct a copied surface form*, and inference seeds
    round 0 with the source slate rather than all-<mask>. Requires
    source_ids to be passed to forward/predict_max (built by
    PIEModel from the source char ids via a vocab translation table).
copy_init_prob : float, per-word probability of a copy-init draw in training.
length_beam : int, number of candidate lengths decoded in parallel at
    inference (top-k of the length head) and reranked by mean token log-prob
    + length log-prob. 1 = the single argmax length (no reranking). Only used
    when use_length_head=True.

MaskedCharacterDecoder.init

init(self)

MaskedCharacterDecoder.update_curriculum

update_curriculum(self, progress)
Ramp training hyperparameters by progress in [0, 1] (epoch /
(max_epochs-1)). Called from PaPie.on_train_epoch_start.

- full_mask_probability: full_mask_start -> full_mask_probability
  (low -> high), so early epochs lean on easy partial denoising and
  gradually approach the all-masked inference regime.
- length_weight: length_weight -> length_weight_end
  (high -> low), so termination/length is learned first then settles.

MaskedCharacterDecoder.length_loss

length_loss(self, length_logits, gold_lengths, src_lengths)
Cross-entropy over the offset class target_len - src_len.

MaskedCharacterDecoder.forward

forward(self, targets, lengths, enc_outs, src_lengths, context=None, source_ids=None)
Masked-LM training forward: builds a (partially or fully) masked version
of the gold target slate, returns char logits for every position
(loss selects the relevant subset), and stashes the length-head
prediction + gold/src lengths for loss.

source_ids (src_len, batch): lemma-vocab ids of the source chars,
only used (and required) when copy_init is on.

MaskedCharacterDecoder.loss

loss(self, logits, targets)

MaskedCharacterDecoder.predict_max

predict_max(self, enc_outs, lengths, max_seq_len=None, bos=None, eos=None, context=None, source_ids=None)
Iterative (Mask-Predict) decoding sized by the length head: predict each
word's target length, allocate exactly that many <mask> slots (freezing
the rest to <pad>), run n_refinement_steps parallel decode rounds
remasking the lowest-confidence slots between rounds.

With length_beam>1 the top-k lengths from the head are each decoded
and reranked by mean token log-prob + length log-prob, so a single wrong
argmax length no longer dooms the whole word. With copy_init the
round-0 slate is seeded from source_ids (the source surface form) so
the model edits a copy rather than generating from scratch.

Parameters
===========
enc_outs : tensor(src_seq_len x batch x hidden_size)
lengths : tensor(batch), source (char) lengths, for cross-attention
    masking and the length head (same role as src_lengths in forward).
max_seq_len : int (optional), overrides self.max_lemma_len.
bos/eos : accepted for interface symmetry; termination is length-driven.
context : tensor(batch x context_dim), optional.
source_ids : tensor(src_seq_len x batch), lemma-vocab ids of the source
    chars; required when copy_init is on.

MaskedCharacterDecoder.predict_beam

predict_beam(self, *args, **kwargs)

papie.layers.decoders.linear

Largely taken from pie.models.decoder.LinearDecoder: https://github.com/emanjavacas/pie/blob/master/pie/models/decoder.py

class LinearDecoder (nn.Module)

LinearDecoder(self, label_encoder, in_features, loss_ignore_index=None, hidden_size=0, dropout=0.0)
Simple Linear Decoder that outputs a probability distribution
over the vocabulary

Parameters
===========
label_encoder : LabelEncoder
in_features : int, input dimension
hidden_size : int, if >0 a hidden layer (Linear -> GELU -> Dropout) precedes the
    output projection (a 2-layer head). The output layer stays self.decoder so
    label-wise weight transfer keeps working.
dropout : float, dropout inside the hidden layer

LinearDecoder.forward

forward(self, enc_outs)

LinearDecoder.loss

loss(self, logits, targets)

LinearDecoder.logits_to_preds

logits_to_preds(self, logits, lengths, decode=True)
:param logits: torch.tensor output of self.forward() (batch x seq_len x vocab)?  # TODO Check shape
:param lengths: torch.tensor(batch,): length of each sequence of the batch (to ignore padding)
:return:

LinearDecoder.decode_preds

decode_preds(self, preds)
:param preds: list of tensors (batch of predictions)
:return: list of decoded (string) predictions

LinearDecoder.predict

predict(self, enc_outs, lengths)
Parameters
==========
enc_outs : torch.tensor(seq_len x batch x hidden_size): output logits of the previous layer
lengths: torch.tensor(batch,): length of each sequence of the batch (to ignore padding)

papie.layers.decoders.t5

T5 (transformer) lemma decoder: a small HuggingFace T5Stack decoder that
cross-attends over the source encoder states (soter prompt states or byte states).

Interface-compatible with AttentionalDecoder (forward / loss / predict_max,
teacher-forced logits drop <bos>), so it subclasses it: every
isinstance(.., AttentionalDecoder) branch of PIEModel / PaPie covers it
with no extra wiring. The RNN/attention parts of the parent are NOT built.

The target vocabulary is the task's own LabelEncoder vocabulary. With a byte-encoded
lemma target that table is fixed (reserved symbols + 256 bytes), so a decoder pretrained by
infilling (see papie.pretrain.distill) transfers to any lemma task whose reserved
symbols match; load_pretrained checks that.

class T5LemmaDecoder (AttentionalDecoder)

T5LemmaDecoder(self, label_encoder, memory_dim, d_model=128, d_kv=32, d_ff=512, num_layers=3, num_heads=4, dropout=0.1, label_smoothing=0.1, max_len=40)

T5LemmaDecoder.forward

forward(self, targets, lengths, enc_outs, src_lengths, context=None)
Teacher-forced logits (seq_len-1, batch, vocab) for loss (drops <bos>).

T5LemmaDecoder.loss

loss(self, logits, targets)

T5LemmaDecoder.predict_max

predict_max(self, enc_outs, lengths, max_seq_len=None, bos=None, eos=None, context=None)
Greedy decoding (re-runs the short prefix each step; no KV cache needed at
this size). Returns (per-word symbol lists, per-word mean log-prob).

T5LemmaDecoder.save

save(self, path)

T5LemmaDecoder.load_pretrained

load_pretrained(self, path)