By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
Transformers are deep‑learning architectures that replace recurrent or convolutional layers with self‑attention, letting the model weigh every token (word, sub‑word, or image patch) against every other token in a single pass. This makes them exceptionally good at capturing long‑range dependencies in text, code, or multimodal data. In a data‑science workflow they are the go‑to for any NLP problem—e.g., building a BERT‑based churn‑prediction model that reads free‑form support tickets and flags at‑risk customers, or fine‑tuning GPT‑2 to generate personalized product descriptions for a recommendation engine.
Self‑Attention – Computes a weighted sum of values V using similarity scores between queries Q and keys K: [ \text{Attention}(Q,K,V)=\text{softmax}!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right)V ] (d_k) = dimensionality of the key vectors; softmax turns scores into probabilities.
Multi‑Head Attention – Runs h parallel self‑attention layers (heads) and concatenates their outputs: [ \text{MHA}(Q,K,V)=\text{Concat}(\text{head}_1,\dots,\text{head}_h)W^O ] Each head learns a different representation subspace; (W^O) projects back to model dimension.
Positional Encoding – Adds deterministic or learned vectors to token embeddings so the model knows token order: [ PE_{(pos,2i)}=\sin!\left(\frac{pos}{10000^{2i/d_{model}}}\right),\; PE_{(pos,2i+1)}=\cos!\left(\frac{pos}{10000^{2i/d_{model}}}\right) ]
BERT (Bidirectional Encoder Representations from Transformers) – A stack of encoder layers trained with Masked Language Modeling (MLM) and Next Sentence Prediction (NSP) objectives. Use bert-base-uncased for downstream fine‑tuning.
bert-base-uncased
GPT (Generative Pre‑trained Transformer) – Decoder‑only stack trained with causal (autoregressive) language modeling: predict next token given all previous tokens.
Tokenization – Splits raw text into atomic units. WordPiece/BPE builds a vocabulary of sub‑words; e.g., “un‑##affordable” → ["un", "##affordable"].
["un", "##affordable"]
Masking Ratio (MLM) – Fraction of tokens replaced by [MASK] during pre‑training (commonly 15%).
[MASK]
Layer Normalization – Normalizes across the feature dimension per token: [ \text{LN}(x)=\frac{x-\mu}{\sigma}\gamma+\beta ] (\mu,\sigma) are mean & std of the token’s features; (\gamma,\beta) are learnable scale/shift.
Feed‑Forward Network (FFN) – Position‑wise MLP applied after attention: [ \text{FFN}(x)=\text{GELU}(xW_1+b_1)W_2+b_2 ] Typically expands dimension 4× then projects back.
Adam Optimizer – Default for transformer training: [ m_t=\beta_1 m_{t-1}+(1-\beta_1)g_t,\; v_t=\beta_2 v_{t-1}+(1-\beta_2)g_t^2,\; \theta_{t+1}=\theta_t-\alpha\frac{m_t}{\sqrt{v_t}+\epsilon} ] (g_t) = gradient; (\alpha) = learning rate.
Fine‑Tuning – Freeze most layers, replace the final classification head, and train on task‑specific data (often with a lower LR, e.g., 2e‑5).
python df = pd.read_csv('tickets.csv') df['text'] = df['text'].astype(str).str.normalize('NFKC')
AutoTokenizer
python from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased') enc = tokenizer(df['text'].tolist(), padding='max_length', truncation=True, max_length=128, return_tensors='pt')
torch.utils.data.Dataset
python train_idx, val_idx = train_test_split( range(len(df)), test_size=0.2, stratify=df['churn']) train_ds = TensorDataset(enc['input_ids'][train_idx], enc['attention_mask'][train_idx], torch.tensor(df['churn'][train_idx]))
BertModel
python from transformers import AutoModel bert = AutoModel.from_pretrained('bert-base-uncased') class ChurnClassifier(nn.Module): def __init__(self): super().__init__() self.bert = bert self.head = nn.Linear(bert.config.hidden_size, 1) def forward(self, ids, mask): out = self.bert(ids, attention_mask=mask).pooler_output return torch.sigmoid(self.head(out))
python optimizer = AdamW(model.parameters(), lr=2e-5) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=total_steps)
Mistake: Feeding raw text directly into a transformer without tokenization. Correction: Always run the text through the matching tokenizer; it handles sub‑word vocab, adds special tokens, and creates attention masks.
Mistake: Using the maximum sequence length of 512 for every dataset, causing unnecessary memory use. Correction: Profile the typical length of your documents and set max_length just above the 95th percentile (e.g., 128 for short tickets).
max_length
Mistake: Fine‑tuning with a high learning rate (≥1e‑3) and expecting convergence. Correction: Start with 1e‑5 – 5e‑5; transformers are sensitive to LR because the pre‑trained weights are already near a good optimum.
Mistake: Ignoring the [CLS] vs. mean‑pooling debate and always using the first token. Correction: For classification, the [CLS] token is standard, but for regression or similarity tasks, mean‑pool the last hidden states.
[CLS]
Mistake: Forgetting to set torch.no_grad() during inference, leading to huge GPU memory consumption. Correction: Wrap evaluation loops with model.eval(); with torch.no_grad(): ….
torch.no_grad()
model.eval(); with torch.no_grad(): …
Scenario: Your BERT fine‑tune on churn data overfits after 2 epochs. Answer: Reduce learning rate and add dropout (e.g., model.bert.config.hidden_dropout_prob = 0.3). Why: Smaller LR lets the model adjust gently; dropout regularizes the large hidden layers.
model.bert.config.hidden_dropout_prob = 0.3
Scenario: You need to generate a product description given a few bullet points. Answer: Use a decoder‑only model (GPT‑2/3) with causal masking and prompt engineering. Why: GPT is built for autoregressive generation, while BERT cannot generate text beyond masked tokens.
Scenario: Your tokenized sequences contain many [PAD] tokens, and validation loss is high. Answer: Ensure the attention mask is passed to the model so padded positions are ignored. Why: Without the mask, the model treats pads as real tokens, corrupting gradients.
[PAD]
[SEP]
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.