Advanced NLP with Transformers and Fine-Tuning
The transformer replaced recurrence with a mechanism that lets every token look at every other token directly, and that single change is why modern language models can hold a whole document in view rather than compressing it through a fixed hidden state. Understanding that mechanism well enough to debug it is what separates practitioners who can fine-tune reliably from those who can only call an API. This lesson builds attention by hand, maps it onto the blocks you will fine-tune, then moves through parameter-efficient adaptation, prompt design, and retrieval-augmented generation.
What attention computes, in plain terms
Attention takes three projections of the same input: a query that describes what each token is looking for, a key that describes what each token offers, and a value that carries the content to be aggregated. Scores come from the dot product of queries with keys, which measures how well each offer matches each request. Those scores are divided by the square root of the key dimension so that the softmax does not saturate when vectors are long, normalised into a distribution, and then used to take a weighted sum of values.
Two properties follow immediately. First, attention is permutation-equivariant: without positional information the model would see a bag of tokens, which is why positional encodings exist. Second, the cost grows with the square of sequence length, so doubling the context quadruples the attention work. That tradeoff explains the industry obsession with long-context efficiency and the arrival of alternatives such as state space models.
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadSelfAttention(nn.Module):
def __init__(self, embed_dim: int, num_heads: int, dropout: float = 0.0):
super().__init__()
assert embed_dim % num_heads == 0, "embed dimension must divide evenly"
self.num_heads = num_heads
self.head_dim = embed_dim // num_heads
self.qkv = nn.Linear(embed_dim, 3 * embed_dim)
self.out = nn.Linear(embed_dim, embed_dim)
self.dropout = nn.Dropout(dropout)
def forward(self, x: torch.Tensor, mask: torch.Tensor = None) -> torch.Tensor:
batch, seq_len, embed_dim = x.size()
q, k, v = self.qkv(x).chunk(3, dim=-1)
q = q.view(batch, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
k = k.view(batch, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
v = v.view(batch, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
scores = q @ k.transpose(-2, -1) / math.sqrt(self.head_dim)
if mask is not None:
scores = scores.masked_fill(mask == 0, float("-inf"))
weights = self.dropout(F.softmax(scores, dim=-1))
context = (weights @ v).transpose(1, 2).contiguous()
return self.out(context.view(batch, seq_len, embed_dim))
block = MultiHeadSelfAttention(embed_dim=512, num_heads=8)
tokens = torch.randn(2, 12, 512)
print(block(tokens).shape)
The single fused query, key, and value projection is a memory optimisation over three separate matrices, and it is what production implementations do. The causal mask is what turns an encoder into a decoder: without it every token can see the answer it is supposed to predict.
Residuals, normalisation, and why blocks stack
Attention alone does not train deeply. Each transformer block wraps its sub-layer in a residual connection followed by layer normalisation, so gradients have a short path to the bottom of the stack and each layer only has to learn a correction. The pre-norm variant normalises before the sub-layer and is generally easier to train at depth; the original post-norm formulation places normalisation after the residual addition and needs warmup to stay stable.
The feed-forward network between attention layers is where much of the stored knowledge lives. It expands the dimension by a factor of four, applies a non-linearity, and projects back down, giving each position room to transform its representation independently of every other position. Removing it collapses model quality dramatically, which is a useful reminder that attention routes information while the feed-forward layers rewrite it.
Choosing a fine-tuning strategy
Full fine-tuning updates every parameter and works best when you have substantial in-domain data and the compute to match. It also risks catastrophic forgetting, where the model loses general ability because the learning rate was too aggressive for the amount of data supplied. Parameter-efficient methods constrain the update instead, which usually means a better accuracy-to-risk ratio for teams without large training clusters.
| Strategy | Trainable parameters | Data needed | Typical use | Risk |
|---|---|---|---|---|
| Full fine-tuning | 100 percent | Large, clean labelled set | Domain adaptation at scale | Forgetting, high cost |
| LoRA adapters | 0.1 to 1 percent | Moderate | Per-task or per-tenant behaviour | Over-tight rank on complex tasks |
| Prompt tuning | A few thousand soft tokens | Small | Steering a frozen model | Fragile across model versions |
| Few-shot prompting | None | Examples in context | Prototyping, low-volume tasks | Context limits, no learning |
from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
from peft import LoraConfig, get_peft_model, TaskType
def build_lora_classifier(model_name: str = "bert-base-uncased", num_labels: int = 2):
base = AutoModelForSequenceClassification.from_pretrained(
model_name, num_labels=num_labels
)
config = LoraConfig(
task_type=TaskType.SEQ_CLS,
r=8,
lora_alpha=32,
lora_dropout=0.1,
target_modules=["query", "value"],
)
model = get_peft_model(base, config)
model.print_trainable_parameters()
args = TrainingArguments(
output_dir="./runs/lora-sst2",
num_train_epochs=3,
per_device_train_batch_size=32,
evaluation_strategy="epoch",
learning_rate=2e-4,
weight_decay=0.01,
fp16=True,
save_strategy="epoch",
load_best_model_at_end=True,
)
return model, args
model, args = build_lora_classifier()
Start with a low rank such as eight and increase it only if the adapter underfits. The learning rate for adapters should be noticeably higher than for full fine-tuning, because the vast majority of weights are frozen and the small trainable subset needs larger steps to move.
Prompt patterns that change behaviour
Prompting is not a substitute for training when accuracy matters, but it is the cheapest experiment you can run and often the right first move. The useful patterns are few-shot examples that pin down the output format, explicit instruction of the task before the input rather than after it, and step-by-step decomposition for problems where the model must reason rather than recognise. Constraining the output schema matters just as much as the reasoning: a model asked for labelled fields in a fixed order is far easier to validate downstream than one asked to answer freely.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
class PromptRunner:
def __init__(self, model_name: str = "gpt2"):
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModelForCausalLM.from_pretrained(model_name)
self.model.eval()
def few_shot(self, task: str, examples: list, input_text: str,
max_new_tokens: int = 40) -> str:
shots = "\n\n".join(
f"Input: {ex['input']}\nOutput: {ex['output']}" for ex in examples
)
prompt = f"{task}\n\n{shots}\n\nInput: {input_text}\nOutput:"
return self._generate(prompt, max_new_tokens)
def chain_of_thought(self, question: str, max_new_tokens: int = 200) -> str:
prompt = ("Work through this step by step.\n\n"
f"Question: {question}\n\nStep 1:")
return self._generate(prompt, max_new_tokens)
def _generate(self, prompt: str, max_new_tokens: int) -> str:
inputs = self.tokenizer(prompt, return_tensors="pt")
with torch.no_grad():
output = self.model.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=True,
temperature=0.7,
top_p=0.9,
)
return self.tokenizer.decode(output[0], skip_special_tokens=True)
runner = PromptRunner()
examples = [
{"input": "Absolutely loved it, would watch again.", "output": "positive"},
{"input": "A complete waste of two hours.", "output": "negative"},
]
print(runner.few_shot(
"Classify the review sentiment as positive or negative.",
examples,
"The plot was predictable but the cast saved it.",
))
Evaluate prompts the same way you would evaluate a model: a fixed held-out set, a named metric, and a baseline. Prompt changes that win on three cherry-picked examples usually lose on thirty.
Retrieval-augmented generation, minimally
Retrieval-augmented generation grounds generation in documents you control, which addresses two failures at once: stale knowledge and unverifiable claims. The pipeline is unglamorous. Chunk documents, embed each chunk, store the vectors, embed the incoming query, take the nearest neighbours, and place them in the prompt ahead of the question with an instruction to answer only from that context.
import numpy as np
class MiniRAG:
def __init__(self, embedder):
self.embedder = embedder
self.chunks: list = []
self.matrix: np.ndarray = None
def add(self, texts: list) -> None:
vectors = self.embedder(texts)
self.chunks.extend(texts)
self.matrix = vectors if self.matrix is None else np.vstack([self.matrix, vectors])
def retrieve(self, query: str, top_k: int = 3) -> list:
vector = np.asarray(self.embedder([query])).reshape(1, -1)
scores = (self.matrix @ vector.T).ravel()
order = np.argsort(scores)[::-1][:top_k]
return [{"text": self.chunks[i], "score": float(scores[i])} for i in order]
def build_prompt(self, query: str, top_k: int = 3) -> str:
context = "\n\n".join(hit["text"] for hit in self.retrieve(query, top_k))
return ("Answer using only the context below. If the context does not "
f"contain the answer, say so.\n\nContext:\n{context}\n\n"
f"Question: {query}\nAnswer:")
def hash_embed(texts: list, dim: int = 256) -> np.ndarray:
"""Deterministic stand-in embedder so the pipeline runs without downloads."""
out = np.zeros((len(texts), dim))
for i, text in enumerate(texts):
for token in text.lower().split():
out[i, hash(token) % dim] += 1.0
norm = np.linalg.norm(out[i])
if norm:
out[i] /= norm
return out
rag = MiniRAG(hash_embed)
rag.add([
"Retrieval augmented generation grounds model answers in retrieved documents.",
"Feature stores keep training and serving feature definitions consistent.",
"Bayesian models express uncertainty as posterior distributions.",
])
print(rag.build_prompt("How does retrieval grounding reduce hallucination?"))
Two evaluation numbers matter more than the demo: retrieval recall at k, which measures whether the right chunk was ever presented, and answer faithfulness, which measures whether the generated text is actually supported by it. Improving the generator while retrieval recall sits at sixty percent is optimisation in the wrong place.
Evaluating beyond exact match
Exact match is a blunt instrument for open-ended generation. Use task-appropriate measures instead: token-level F1 for short answers, rubric-based grading for structured outputs, and pairwise human comparison when two systems are close. For retrieval, report recall at k and mean reciprocal rank separately from generation quality, because conflating them hides which half of the system is failing.
Track regressions on a fixed evaluation set that includes adversarial cases, ambiguous queries, and out-of-domain inputs. A system that only ever sees easy examples will look stable right up until a user asks the first question that mattered.
One last practical note concerns decoding. Temperature and top-p control the shape of the sampled distribution, and they should be tuned against the task rather than copied from a blog post. Classification-style prompts want deterministic decoding so results are reproducible across runs, while open-ended drafting benefits from moderate sampling that avoids repetitive loops. Whatever you choose, record it with the results, because a comparison between two systems that used different decoding settings is not a comparison at all.
Common Mistakes
Jumping straight to full fine-tuning on a few hundred labelled examples
Fix: Try prompting and few-shot baselines first, then LoRA, and only pay for full fine-tuning when the data and the gap both justify it.
Tuning the generator while retrieval recall remains poor
Fix: Measure recall at k on a fixed query set and fix chunking, embeddings, or ranking before touching generation.
Reporting a single accuracy number without an evaluation set or baseline
Fix: Pin a held-out set, include hard and out-of-domain cases, and compare against the previous system on every change.
Best Practices
- Keep the fused query, key, and value projection to reduce memory during training
- Use pre-norm blocks and warmup when stacking many layers
- Set adapter learning rates higher than full fine-tuning learning rates
- Specify output format explicitly in the prompt so downstream validation is cheap
- Report retrieval and generation metrics separately to locate failures
Key Takeaways
- Attention routes information with query, key, and value projections scaled before softmax
- Residual connections and layer normalisation are what make deep stacks trainable
- Parameter-efficient fine-tuning usually beats full updates when data is limited
- Prompt design is an experiment and needs a held-out set like any other change
- Retrieval quality bounds answer quality, so measure recall before improving prompts