GPT-2 decoder trunk — N pre-LN transformer blocks topped by ln_f.
Implements the modified architecture of Radford, Wu, Child, Luan, Amodei,
and Sutskever, 2019. Differs from GPT-1 in three ways: (i) pre-LN
blocks — LayerNorm is applied to the residual input of each
sub-layer rather than after the residual add, which stabilises
optimisation past depth ; (ii) a final LayerNorm
(ln_f) caps the trunk; (iii) residual-output projection weights are
initialised with an extra factor (Radford 2019
§2.3) to keep activation variance roughly invariant to depth.
Parameters
configGPT2ConfigAttributes
wtenn.Embedding(vocab_size, hidden_size).
HuggingFace name retained verbatim for state-dict portability.wpenn.Embedding(max_position_embeddings, hidden_size).dropnn.Dropoutconfig.num_hidden_layers pre-LN transformer blocks.ln_fnn.LayerNormconfig_classtype[GPT2Config]base_model_prefixstr"transformer") under which the trunk is
nested in task-head variants.Notes
Reference: Radford, Wu, Child, Luan, Amodei, and Sutskever, "Language Models are Unsupervised Multitask Learners", OpenAI Technical Report, 2019.
Each pre-LN block computes
so the residual stream carries un-normalised state. The trunk produces final hidden states which the LM head projects to vocabulary logits.
Examples
>>> import lucid
>>> from lucid.models.text.gpt2 import GPT2Config, GPT2Model
>>> cfg = GPT2Config(num_hidden_layers=2, hidden_size=128,
... num_attention_heads=2, intermediate_size=512)
>>> model = GPT2Model(cfg).eval()
>>> input_ids = lucid.tensor([[15496, 11, 995, 13]]) # "Hello, world."
>>> out = model(input_ids)
>>> out.last_hidden_state.shape # (B=1, T=4, H=128)
(1, 4, 128)Used by 2
Constructors
1Instance methods
3forward(input_ids: Tensor, attention_mask: Tensor | None = None, past_key_values: Cache | None = None, use_cache: bool = False, cache_position: Tensor | None = None)