Embeddings and encoders
Source encoders (character RNN, frozen ByT5, soter T5) and the sentence encoder.
Generated from the source by tools/make_api.py; do not edit by hand.
papie.layers.embedding
Largely taken from pie.models.embedding: https://github.com/emanjavacas/pie/blob/0ca4311a57b2439994e5fcdc02f4d008ee268a9c/pie/models/embedding.py
class WordEmbedding (nn.Module)
WordEmbedding(self, num_embeddings, embedding_dim, label_encoder, dropout=0.0)
Module for word embeddings
WordEmbedding.forward
forward(self, word)
WordEmbedding.word_dropout
word_dropout(self, inp)
Drop input words based on frequency Originally, this method was in pie.torch_utils
class RNNEmbedding (nn.Module)
RNNEmbedding(self, num_embeddings, embedding_dim, padding_idx=None, num_layers=1, dropout=0.0, cell='GRU')
Create module with 1 Embeddings layer followed with a bidirectional RNN-like module (1+ layer(s))
RNNEmbedding.enable_cache
enable_cache(self, maxsize=100000)
Enable the inference char-embedding cache (e.g. for serving).
RNNEmbedding.disable_cache
disable_cache(self)
RNNEmbedding.clear_cache
clear_cache(self)
RNNEmbedding.forward
forward(self, char, nchars, nwords)
Forward pass of the RNNEmbedding module.
Parameters
===========
char : torch.Tensor
Tensor of shape ((longest_word x) batch_words) containing the character indices
for each word in the batch.
nchars : torch.Tensor
Tensor of shape (batch_words,) representing the number of characters per word.
nwords : torch.Tensor
Tensor of shape (batch_sentences,) representing the number of words per sentence.
Returns
=======
emb : torch.Tensor
Tensor of shape (longest_sentence, batch_sentences, 2 * hidden_dim) containing
the final word embeddings, where longest_sentence = max(nwords).
outs : torch.Tensor
Tensor of shape (longest_word, batch_words, 2 * hidden_dim) containing
the character-level RNN outputs, where longest_word = max(nchars).class ByT5Embedding (nn.Module)
ByT5Embedding(self, model_name='google/byt5-small', num_layers=1, output_dim=400, dropout=0.0, normalization=None)
Frozen ByT5 (HuggingFace) source encoder, a drop-in replacement forRNNEmbedding. Encodes each sentence's raw bytes *contextually* (the whole sentence at once, so every byte attends over the full sentence) with the **firstnum_layersencoder blocks** of a frozen ByT5, then derives the per-word representations the rest of the model expects: -emb:(longest_sentence_words, batch_sentences, output_dim)-- a masked mean-pool of each word's byte states (feeds the sentence encoder or, with the encoder bypassed, the decoders directly). -outs:(longest_word_bytes, batch_words, output_dim)-- the per-byte states sliced per word, for the lemma decoder's cross-attention. -src_lengths:(batch_words,)-- per-word byte length (replaces the char lengths for the decoder's attention masking / length head). ByT5 maps a UTF-8 bytebto idb + 3(pad=0, eos=1, unk=2). The byte ids and per-word spans are built manually (not via the tokenizer) so the byte->word alignment is exact. The frozen ByT5 weights are **not** saved in our checkpoint (re-loaded from HF at construction); only the trainable projection head is. Context-dependent, so the inference cache does not apply.
ByT5Embedding.train
train(self, mode=True)
ByT5Embedding.enable_cache
enable_cache(self, maxsize=100000)
ByT5Embedding.disable_cache
disable_cache(self)
ByT5Embedding.state_dict
state_dict(self, *args, **kwargs)
ByT5Embedding.forward
forward(self, raw_words, nwords)
raw_words: List[List[str]] (sentence-major). nwords: (batch_sentences,).
Returns (emb, outs, src_lengths) -- see the class docstring.class PIEEmbedding (nn.Module)
PIEEmbedding(self, wemb_embedding, cemb_rnn_embedding, candidates=None)
Embedding module consisting of an optional word embedding layer and a mandatory char-level module (RNNEmbeddingorByT5Embedding).
PIEEmbedding.forward
forward(self, word, wlen, char, clen, raw_words=None)
papie.layers.soter
Soter-style byte-level T5 source encoder (student for embedding distillation). soter-mini (HFZual/soter-mini) is a byte-level T5 that lemmatises one word at a time from a prompt:: "<form, letters space-separated> <sep> <left words> <tgt> form </tgt> <right words>"build_soter_prompt_idsbuilds those ids directly (no tokenizer at runtime) andSoterEmbeddingencodes the per-word prompts with a (tiny) T5 encoder, exposing the same contract asByT5Embedding:forward(raw_words, nwords) -> (emb, outs, src_lengths).
build_soter_prompt_ids
build_soter_prompt_ids(words, i, context_window=8, space_letters=True, normalization='NFD', max_bytes=384, mask_target=False)
Build the prompt ids for wordiofwords. Returns(ids, (start, end))where(start, end)is the byte span of the target form between<tgt>and</tgt>andidsends with</s>. Withspace_lettersthe layout isspaced_form <sep> left <tgt> form </tgt> rightwith single spaces between segments (so an empty left context yields a double space, as in the soter-minibuild_input). Without it the spelled prefix and its<sep>are dropped. If the prompt exceedsmax_bytesthe outermost context words are dropped (never cut mid-word).mask_target=Truebuilds an *infilling* prompt: the target form is removed (<tgt> </tgt>stays, with an empty span) and the spelled prefix is dropped (it would leak the answer).
class SoterEmbedding (nn.Module)
SoterEmbedding(self, soter_model_name=None, t5_config=None, soter_init='scratch', checkpoint=None, freeze=False, output_dim=400, dropout=0.0, context_window=8, space_letters=True, normalization='NFD', outs_scope='target', encode_chunk_size=256, max_bytes=384, head_checkpoint=None)
Byte-level T5 encoder over per-word soter prompts (drop-in forByT5Embedding).outs_scope='target'returns the states of the target-form bytes (compatible with the masked char decoder);'prompt'returns all prompt states (for a future T5 decoder).embis a masked mean over the target-span states passed through Linear+LayerNorm.
SoterEmbedding.head_state_dict
head_state_dict(self)
SoterEmbedding.load_head
load_head(self, path)
SoterEmbedding.train
train(self, mode=True)
SoterEmbedding.enable_cache
enable_cache(self, maxsize=100000)
SoterEmbedding.disable_cache
disable_cache(self)
SoterEmbedding.state_dict
state_dict(self, *args, **kwargs)
SoterEmbedding.encode_prompts
encode_prompts(self, prompts, device)
Encode a list of id lists -> (hidden (N, L, d), attention mask (N, L)).
SoterEmbedding.encode_words
encode_words(self, raw_words, device)
Encode every word's prompt (sentence-major flat order). Returns(hidden (N, L, hidden_size), prompts, spans);spans[k]is the target-form byte span of wordkinside its prompt. Raw encoder states (before the Linear+LayerNorm head), used by distillation.
SoterEmbedding.encode_masked
encode_masked(self, raw_words, pairs, device)
Infilling inputs: for each(sentence_idx, word_idx)inpairsencode a prompt with that word *removed*. Returns(memory (T, N, output_dim), lengths (N,), golds)wheregoldsare the (normalised) removed forms.
SoterEmbedding.forward
forward(self, raw_words, nwords)
papie.layers.encoder
Inspired from pie.models.encoder: https://github.com/emanjavacas/pie/blob/0ca4311a57b2439994e5fcdc02f4d008ee268a9c/pie/models/encoder.py
class RNNEncoder (nn.Module)
RNNEncoder(self, in_size, hidden_size, num_layers=1, dropout=0.0, cell='GRU')
Sentence-level RNN Encoder with one or multiple layers
Build and initialize layers of RNN encoder
RNNEncoder.forward
forward(self, inp, lengths, hidden=None)
papie.layers.attention
Ported verbatim (modulo imports) from pie.models.attention: https://github.com/emanjavacas/pie/blob/master/pie/models/attention.py Global attention implementing the three scorer modules from Luong 15. Attribute names are kept identical to PaPie so that convertedstate_dictkeys (attn.scorer.W_a.weight,attn.linear_out.{weight,bias}) line up.
DotScorer
DotScorer(dec_out, enc_outs, **kwargs)
Score for query decoder state and the ith encoder state is given by their dot product. dec_outs: (trg_seq_len x batch x hid_dim) enc_outs: (src_seq_len x batch x hid_dim) output: ((trg_seq_len x) batch x src_seq_len)
class GeneralScorer (nn.Module)
GeneralScorer(self, dim)
Inserts a linear projection to the query state before the dot product
GeneralScorer.init
init(self)
GeneralScorer.forward
forward(self, dec_out, enc_outs, **kwargs)
class BahdanauScorer (nn.Module)
BahdanauScorer(self, hid_dim, att_dim)
Projects both query decoder state and encoder states to an attention space.
The scores are computed by a dot product with a learnable param v_a after
transforming the sum of query decoder state and encoder state with a tanh.
score(a_i_j) = a_v \dot tanh(W_s @ h_s_j + W_t @ h_t_i)BahdanauScorer.init
init(self)
BahdanauScorer.project_enc_outs
project_enc_outs(self, enc_outs)
mapping: (seq_len x batch x hid_dim) -> (seq_len x batch x att_dim)
Returns:
--------
torch.Tensor (seq_len x batch x att_dim),
Projection of encoder output onto attention spaceBahdanauScorer.forward
forward(self, dec_out, enc_outs, enc_att=None)
class Attention (nn.Module)
Attention(self, hid_dim, att_dim=None, scorer='general')
Global attention implementing the three scorer modules from Luong 15.
Parameters:
-----------
- hid_dim: int, dimensionality of the query vector
- att_dim: (optional) int, dimensionality of the attention space (only
used by the bahdanau scorer). If not given it will default to hid_dim.
- scorer: str, one of ('dot', 'general', 'bahdanau')Attention.init
init(self)
Attention.forward
forward(self, dec_out, enc_outs, lengths)
Parameters: ----------- - dec_outs: torch.Tensor(trg_seq_len x batch_size x hid_dim) - enc_outs: torch.Tensor(seq_len x batch_size x hid_dim) - lengths: torch.LongTensor(batch), source lengths Returns: -------- - context: (trg_seq_len x batch x hid_dim) - weights: (trg_seq_len x batch x seq_len)