Bare T5 encoder-decoder trunk.
Implements the architecture of Raffel, Shazeer, Roberts, Lee, Narang, Matena, Zhou, Li and Liu, 2020. One token table embeds both the source and the target. The encoder stack reads the source with bidirectional attention; the decoder stack reads the target causally and cross-attends to the encoder output. Neither side adds a position to its tokens: each stack's blocks add one learned per-head bias, indexed by bucketed relative distance, to their self-attention logits.
Parameters
configT5ConfigAttributes
sharednn.Embedding(vocab_size, d_model) table both stacks embed with.encodernn.Modulenum_hidden_layers blocks.decodernn.Modulenum_decoder_layers blocks with cross-attention.Notes
Reference: Raffel et al., "Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer", JMLR 21(140), 2020 (arXiv:1910.10683), §2.1 and §3.1.
Head of every block scores query against key as
unscaled, and every sub-layer updates the stream as .
Examples
>>> import lucid
>>> from lucid.models.text.t5 import T5Config, T5Model
>>> cfg = T5Config(vocab_size=100, hidden_size=32, num_hidden_layers=2,
... num_decoder_layers=2, num_attention_heads=4,
... head_dim=8, intermediate_size=64)
>>> model = T5Model(cfg).eval()
>>> src = lucid.tensor([[13, 5, 42, 1]])
>>> tgt = lucid.tensor([[0, 7, 9]])
>>> out = model(src, decoder_input_ids=tgt)
>>> out.last_hidden_state.shape, out.encoder_last_hidden_state.shape
((1, 3, 32), (1, 4, 32))Used by 2
Constructors
1Instance methods
5decode(tgt_ids: Tensor, memory: Tensor, tgt_attention_mask: Tensor | None = None, memory_attention_mask: Tensor | None = None, past_key_value: EncoderDecoderCache | None = None, use_cache: bool = False, cache_position: Tensor | None = None)Run the decoder against an already-computed encoder output.
Parameters
tgt_ idsTensor(B, T) target ids to decode now — the whole prefix, or
only the new ones when a cache holds the rest.memoryTensor(B, S, d_model) from encode.T.(B, S) source padding mask, applied in cross-attention.use_ cachebool= False, keyword-onlypast_key_value.StaticCache.Returns
Tensor(B, T, d_model) decoder output for the T new positions.
forward(input_ids: Tensor, decoder_input_ids: Tensor, attention_mask: Tensor | None = None, decoder_attention_mask: Tensor | None = None)Encode the source and decode the target against it.
Parameters
Returns
T5ModelOutputDecoder and encoder outputs; T5ForSeq2SeqLM projects
the decoder side to the vocabulary.
The decoder stack, which reads the encoder output as memory and an optional cache.
The encoder stack: forward(embeddings, attention_mask) to the encoder output.