class
BERTForSequenceClassification
extends
PretrainedModelBERTForSequenceClassification(config: BERTConfig)BERT with a pooled-CLS linear classifier for sequence-level tasks.
Wraps the bidirectional encoder with a dropout-regularised linear head
operating on the [CLS] pooled embedding. This is the standard
fine-tuning recipe for GLUE-style sentence/sentence-pair tasks (SST-2,
MNLI, QQP, RTE, ...) introduced in Devlin et al., 2018 §4.1.
Parameters
configBERTConfigBERT hyperparameters.
config.num_labels sets the output
dimension; config.classifier_dropout (falling back to
hidden_dropout) sets the dropout applied before the linear.Attributes
bertBERTModelUnderlying bidirectional encoder trunk.
dropoutnn.DropoutDropout layer applied to the pooled
[CLS] embedding.classifiernn.LinearFinal linear of shape
(hidden_size, num_labels) producing logits.Notes
Reference: Devlin, Chang, Lee, and Toutanova, "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding", NAACL 2019 (arXiv:1810.04805).
The pooled representation is
,
and the final logits are .
When labels is provided, cross-entropy over num_labels classes is
computed and exposed as output.loss.
Examples
>>> import lucid
>>> from lucid.models.text.bert import BERTConfig, BERTForSequenceClassification
>>> cfg = BERTConfig(num_labels=3, num_hidden_layers=2, hidden_size=128,
... num_attention_heads=2, intermediate_size=512)
>>> model = BERTForSequenceClassification(cfg).eval()
>>> input_ids = lucid.tensor([[101, 7592, 102]])
>>> out = model(input_ids)
>>> out.logits.shape # (B=1, num_labels=3)
(1, 3)Used by 2
Constructors
1Instance methods
1forward(input_ids: Tensor, attention_mask: Tensor | None = None, token_type_ids: Tensor | None = None, labels: Tensor | None = None)Full encode + decode pass.
Parameters
input_ids(B, S) source token ids.decoder_input_ids(B, T) target token ids (right-shifted).attention_maskOptional
(B, S) HF-style padding mask.decoder_attention_maskOptional
(B, T) HF-style padding mask.Returns
MaskedLMOutputclass:Seq2SeqLMOutput carrying decoder hidden states as