Skip to content
class

T5ForSeq2SeqLM

extendsLanguageModelingModel
T5ForSeq2SeqLM(config: T5Config)

T5 with its language-modelling head — the model every T5 task trains.

Wraps T5Model with a bias-free projection to the vocabulary. With config.tie_word_embeddings (the paper's setting) the projection is the shared token table, and the decoder output is scaled by dmodel−1/2d_{\text{model}}^{-1/2} first: the table is drawn at unit variance for the input side, so the tied output would otherwise be dmodel\sqrt{d_{\text{model}}} too large.

Pass labels alone and the decoder input is built from them — decoder_start_token_id followed by the labels shifted right, with -100 replaced by the pad id — as the paper's teacher forcing does.

Parameters

configT5Config
Hyperparameters; tie_word_embeddings and decoder_start_token_id shape the head.

Attributes

The encoder-decoder trunk.
lm_headnn.Linear
(d_model → vocab_size) projection, the shared table when tied.

Notes

Reference: Raffel et al., JMLR 2020 (arXiv:1910.10683), §2.1 and §3.1.4.

With labels the loss is the mean per-token cross-entropy over positions not labelled -100:

L=−1∣V∣∑(b,t)∈Vlog⁡pθ(yb,t∣xb, yb,<t).\mathcal{L} = -\frac{1}{|V|} \sum_{(b, t) \in V} \log p_\theta(y_{b,t} \mid x_b,\, y_{b,<t}).

Examples

>>> import lucid
>>> from lucid.models.text.t5 import T5Config, T5ForSeq2SeqLM
>>> 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 = T5ForSeq2SeqLM(cfg).eval()
>>> src = lucid.tensor([[13, 5, 42, 1]])
>>> labels = lucid.tensor([[7, 9, 1]])
>>> out = model(src, labels=labels)
>>> out.logits.shape, out.loss.shape
((1, 3, 100), ())

Used by 2

Constructors

1
dunder

__init__

→None
__init__(config: T5Config)

Initialise the model. See the class docstring for parameters.

Instance methods

4
fn

forward

→Seq2SeqLMOutput
forward(input_ids: Tensor, decoder_input_ids: Tensor | None = None, attention_mask: Tensor | None = None, decoder_attention_mask: Tensor | None = None, labels: Tensor | None = None)

Teacher-forced pass, with the loss when labels are given.

Parameters

input_idsTensor
(B, S) source token ids.
decoder_input_idsTensor or None= None
(B, T) target ids, shifted right. Built from labels when omitted.
attention_maskTensor or None= None
(B, S) source padding mask.
decoder_attention_maskTensor or None= None
(B, T) target padding mask.
labelsTensor or None= None
(B, T) target ids; -100 marks a position the loss skips.

Returns

Seq2SeqLMOutput

logits of shape (B, T, vocab_size), the loss when labels were given, and the encoder output.

Raises

ValueError
If neither decoder_input_ids nor labels is given.
fn

generate

→Tensor
generate(input_ids: Tensor, max_length: int = 20, max_new_tokens: int | None = None, attention_mask: Tensor | None = None, decoder_start_token_id: int | None = None, eos_token_id: int | None = None, pad_token_id: int | None = None, do_sample: bool = False, temperature: float = 1.0, top_k: int | None = None, top_p: float | None = None, repetition_penalty: float = 1.0, use_cache: bool = True, cache_implementation: str = 'dynamic', max_cache_len: int | None = None)

Decode an answer for each source — greedy unless do_sample.

Parameters

input_idsTensor
(B, S) source ids, task prefix included ("translate English to German: …").
max_lengthint= 20, keyword-only
Cap on the returned length, start token included.
max_new_tokens(int or None, optional, keyword - only)= None
Cap on the tokens after the start token (>= 0); wins over max_length.
attention_mask(Tensor or None, optional, keyword - only)= None
(B, S) source padding mask.
use_cachebool= True, keyword-only
Decode one token per step against an encoder-decoder cache.
cache_implementationstr= "dynamic", keyword-only
"dynamic" → DynamicCache; "static" → fixed-size StaticCache; "compiled" → StaticCache + compiled_decode_step (one executable).
max_cache_len(int or None, optional, keyword - only)= None
Self-attention buffer size for "static"/"compiled"; default: the length cap.
do_samplebool= False, keyword-only
Sample instead of taking the argmax.
temperaturefloat= 1.0, keyword-only
Logit temperature, strictly positive; only read under do_sample.
top_k(int or None, optional, keyword - only)= None
Sample among the top_k most likely tokens only; None or 0 disables.
top_p(float or None, optional, keyword - only)= None
Sample from the smallest set reaching top_p, in [0, 1]; None/1.0 is off.
repetition_penaltyfloat= 1.0, keyword-only
Down-weights tokens already produced; strictly positive, 1.0 is off.
decoder_start_token_id(int or None, optional, keyword - only)= None
First target token; config.decoder_start_token_id (the pad id) by default.
eos_token_id(int or None, optional, keyword - only)= None
Token that finishes a row; config.eos_token_id by default.
pad_token_id(int or None, optional, keyword - only)= None
Fills a finished row; config.pad_token_id by default.

Returns

Tensor

(B, T_out) int64 target ids beginning with the start token.

Raises

ValueError
A sampling argument or cache_implementation is out of range, before encoding.