Skip to content
class

BERTModel

extendsPretrainedModel
BERTModel(config: BERTConfig)

Bare BERT encoder returning hidden states and pooled CLS embedding.

Implements the bidirectional transformer encoder of Devlin et al., 2018. Token, position, and segment embeddings are summed, LayerNormed, and dropout-regularised, then passed through LL transformer blocks of multi-head self-attention plus position-wise feed-forward. A single tanh-activated linear ("pooler") on the first [CLS] token produces a sentence-level embedding used by classification heads.

Use this class as the trunk when you want raw hidden states; the task-specific subclasses (BERTFor*) wrap it with appropriate heads.

Parameters

Hyperparameters controlling vocabulary, depth, width, head count, and regularisation. See BERTConfig for the full field list.

Attributes

embeddingsnn.Module
Token + position + token-type embedding block followed by LayerNorm and dropout.
encodernn.Module
Stack of config.num_hidden_layers transformer encoder layers.
poolernn.Module
Dense + tanh projection of the [CLS] hidden state.
config_classtype[BERTConfig]
Class-level pointer used by the registry to instantiate a matching config from disk.
base_model_prefixstr
Prefix ("bert") under which sub-module checkpoints are nested in task-head variants — used during weight loading.

Notes

Reference: Devlin, Chang, Lee, and Toutanova, "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding", NAACL 2019 (arXiv:1810.04805).

Self-attention follows the scaled dot-product form

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left( \frac{Q K^{\top}}{\sqrt{d_k}} \right) V

with dk=H/Ad_k = H / A. Each layer applies multi-head attention, followed by a feed-forward block

FFN(x)=GELU(xW1+b1)W2+b2,\mathrm{FFN}(x) = \mathrm{GELU}(x W_1 + b_1) W_2 + b_2,

each wrapped by a residual connection and post-LayerNorm.

Examples

>>> import lucid
>>> from lucid.models.text.bert import BERTConfig, BERTModel
>>> cfg = BERTConfig(num_hidden_layers=2, hidden_size=128, num_attention_heads=2,
...                  intermediate_size=512)
>>> model = BERTModel(cfg).eval()
>>> input_ids = lucid.tensor([[101, 7592, 2088, 102]])   # [CLS] hello world [SEP]
>>> out = model(input_ids)
>>> out.last_hidden_state.shape   # (B=1, T=4, H=128)
(1, 4, 128)
>>> out.pooler_output.shape       # (B=1, H=128)
(1, 128)

Used by 2

Constructors

1
dunder

__init__

→None
__init__(config: BERTConfig)

Instance methods

1
forward(input_ids: Tensor | None = None, attention_mask: Tensor | None = None, token_type_ids: Tensor | None = None, position_ids: Tensor | None = None, inputs_embeds: Tensor | None = None, output_hidden_states: bool = False, head_mask: Tensor | None = None, output_attentions: bool = False, past_key_values: Cache | None = None)

Encode a batch and return the sequence output plus the pooled CLS.

position_ids and inputs_embeds are forwarded to the embedding layer; see _BERTEmbeddings.forward. output_hidden_states additionally returns every layer's output, embedding first.

head_mask and output_attentions both need the per-head attention weights, so requesting either switches that layer to the unfused softmax(qk^T) v path — the fused kernel never materialises the (B, H, T, T) matrix, which is exactly why it is fast. Neither flag changes the result when off, and the fused path stays the default.

past_key_values is a lucid.utils.cache.DynamicCache holding one (key, value) pair per layer, which every position attends to in front of its own keys and values. An encoder has no history to extend, so the cache is only read, and attention_mask is as wide as prefix + input. The prefix takes the positions in front of the input, as the reference numbers them after the cache: with no position_ids the input's are P .. P + T - 1 for a prefix of length P; position_ids given are used as they are.