Skip to content
class

TransformerForSequenceClassification

extendsSequenceClassificationModel
TransformerForSequenceClassification(config: TransformerConfig)

Encoder-only sentence classifier — pools the first source-side token.

Wraps TransformerModel and runs only the encoder half during forward; the first source-side token's hidden state is dropout-regularised and projected through a linear of output width config.num_labels. Pattern mirrors BERTForSequenceClassification — the decoder half of the trunk is unused so this head trains the same encoder weights efficiently for GLUE-style fine-tunes on the Vaswani backbone.

Parameters

Hyperparameters. config.num_labels sets the output dimension; config.classifier_dropout (falling back to hidden_dropout) sets the dropout applied before the linear.

Attributes

transformerTransformerModel
Underlying encoder-decoder trunk; only encode is invoked here.
dropoutnn.Dropout
Dropout layer applied to the pooled first-token embedding.
classifiernn.Linear
Final linear of shape (d_model, num_labels) producing per-class logits.

Notes

Reference: Vaswani et al., "Attention Is All You Need", NeurIPS, 2017 (arXiv:1706.03762).

When labels is supplied, the loss is the standard cross-entropy:

L=−1B∑b=1Blog⁡pθ(yb∣xb).\mathcal{L} = -\frac{1}{B} \sum_{b=1}^{B} \log p_\theta(y_b \mid x_b).

Examples

>>> import lucid
>>> from lucid.models.text.transformer import (
...     TransformerConfig, TransformerForSequenceClassification,
... )
>>> cfg = TransformerConfig(num_labels=3, num_hidden_layers=2,
...                         hidden_size=64, num_attention_heads=2,
...                         intermediate_size=128, vocab_size=1000)
>>> model = TransformerForSequenceClassification(cfg).eval()
>>> input_ids = lucid.tensor([[1, 234, 567, 2]])
>>> out = model(input_ids)
>>> out.logits.shape   # (B=1, num_labels=3)
(1, 3)

Used by 2

Constructors

1
dunder

__init__

→None
__init__(config: TransformerConfig)

Instance methods

1
forward(input_ids: Tensor, attention_mask: Tensor | None = None, labels: Tensor | None = None)

Override in subclasses to define the computation.