Python for AI Engineers · Part C · Lesson 26 of 26
Pretrained models with Hugging Face: pipelines, tokenizers, embeddings and LoRA fine-tuning
Use pretrained models from Python: Hugging Face pipeline(), AutoTokenizer and AutoModel, embeddings with sentence-transformers next to Ollama, model cards and licences, when to fine-tune instead of prompting or RAG, and LoRA explained in NumPy, then trained with peft on a CPU.
⏱ 50 min3 exercises that check your codeRuns in your browser
By the end you can
- Run a pretrained model in three lines with
pipeline(), and load any model withAutoTokenizerandAutoModel - Read what a tokenizer produces (ids, pieces, special tokens, the attention mask) and turn token vectors into one sentence embedding
- Compare a local
sentence-transformersmodel with the Ollama embeddings from lab 5, and check a model card and licence before you ship - Decide between prompting, RAG and fine-tuning, and explain why LoRA trains less than 1% of the weights
- Set up LoRA with
peft, check the trainable parameter count, train an adapter on a CPU and load it back
1Pretrained models and the Hugging Face Hub
Training a language model from scratch costs millions of dollars. A pretrained model is one somebody already trained, published with its weights so you can download it and use it. The Hugging Face Hub is where most open models live: think of it as Maven Central or npm, but for models. Every model has a name of the form owner/model, a page with a model card (its documentation) and files: the weights (usually a .safetensors file), a config.json that describes the architecture, and the tokenizer files.
Three Python libraries from Hugging Face do the work. transformers loads and runs the models. sentence-transformers wraps it for embeddings. peft adds fine-tuning methods such as LoRA. All three run on top of PyTorch from the PyTorch basics lesson. None of them can run in these browser boxes, so most examples here are files you run on your machine; each shows the exact output it printed. Create a project and add them, pinned so your output matches this page:
uv init hf-demo --python 3.12
cd hf-demo
uv add torch==2.15.0 transformers==5.24.1 sentence-transformers==6.3.0 peft==0.22.0 + peft==0.22.0 + sentence-transformers==6.3.0 + torch==2.15.0 + transformers==5.24.1 (plus helper packages such as huggingface-hub, tokenizers, safetensors and accelerate)
from transformers import pipeline
classifier = pipeline(
"sentiment-analysis",
model="distilbert/distilbert-base-uncased-finetuned-sst-2-english",
)
reviews = [
"The answer was fast and exactly right.",
"It made up a citation that does not exist.",
]
for review, result in zip(reviews, classifier(reviews)):
print(f"{result['label']:8} {result['score']:.3f} {review}") pipelineis the shortest way to use a model: one object that tokenizes the text, runs the model and turns the raw numbers into a readable answer.line 1- The **task**. Others include
"text-generation","summarization","translation","zero-shot-classification"and"feature-extraction".line 4 - Which model to use, by its Hub name. This one is DistilBERT fine-tuned on movie-review sentiment (the SST-2 dataset). The first run downloads its weights, about 270 MB.line 5
- Calling the pipeline with a list returns one dict per text, such as
{"label": "POSITIVE", "score": 0.99}.zippairs each review with its result, like walking two arrays with one index.line 12 :8pads the label to 8 characters so the columns line up, and:.3fprints 3 decimals.line 13
POSITIVE 1.000 The answer was fast and exactly right. NEGATIVE 0.998 It made up a citation that does not exist.
Run it with uv run python classify.py. The first time, you also see download progress bars and a warning that you are sending unauthenticated requests to the HF Hub. That warning is harmless: public models download without an account. A free token (set as the HF_TOKEN environment variable) only raises your rate limits and is required for gated models, which you will meet in section 6.
Downloads are cached in ~/.cache/huggingface/hub (set HF_HOME to move it), so the second run starts in a few seconds, and with the environment variable HF_HUB_OFFLINE=1 it runs with no network at all. The score is the model's confidence: a softmax over its two labels. It is not a guarantee: a confident model can still be wrong.
Tip Always pass model=. If you leave it out, transformers picks a default model for the task and prints No model was supplied, defaulted to ... with a note that this is not recommended in production. The default can change between releases, and your app silently changes with it.
2Tokenizers: text in, token ids out
A model never sees text, only token ids, as the tokens lesson explained. Every model comes with its own tokenizer, and you must use that one: the ids only mean something to the model they were trained with. AutoTokenizer.from_pretrained(name) reads the model's tokenizer files and gives you the right tokenizer class, so you never have to know which one it is. The Auto classes are a factory, the same idea as a Java ServiceLoader picking an implementation from a config file.
This example uses the tokenizer of all-MiniLM-L6-v2, the small embedding model of the next sections. It is a WordPiece tokenizer inherited from BERT: common words are one piece, rare words are split, and a piece that continues the previous one starts with ##.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
text = "Tokenizers split unbelievably long words."
enc = tok(text)
print(enc["input_ids"])
print(tok.convert_ids_to_tokens(enc["input_ids"]))
print(tok.decode(enc["input_ids"]))
print("vocab size:", tok.vocab_size)
batch = tok(["Hi there", "A slightly longer sentence"], padding=True, return_tensors="pt")
print(batch["input_ids"])
print(batch["attention_mask"]) - Downloads (once) and loads the tokenizer files of that model from the Hub.line 3
- Calling the tokenizer returns a dict-like object.
input_idsis the list of token ids.line 6 - Shows the piece behind each id.
[CLS](id 101) and[SEP](id 102) are **special tokens** the tokenizer adds at the start and end, because the model was trained with them.line 8 decodeturns ids back into text. This tokenizer lowercases everything first ("uncased"), so the capital T is gone.line 9- A **batch** of texts of different lengths.
padding=Truefills the short ones up to the longest with the[PAD]token (id 0), so they fit in one rectangular tensor.return_tensors="pt"asks for PyTorch tensors instead of Python lists.line 12 - The **attention mask**: 1 for a real token, 0 for padding. The model uses it to ignore the padding, and so must you (next section).line 14
[101, 19204, 17629, 2015, 3975, 4895, 8671, 2666, 3567, 6321, 2146, 2616, 1012, 102]
['[CLS]', 'token', '##izer', '##s', 'split', 'un', '##bel', '##ie', '##va', '##bly', 'long', 'words', '.', '[SEP]']
[CLS] tokenizers split unbelievably long words. [SEP]
vocab size: 30522
tensor([[ 101, 7632, 2045, 102, 0, 0],
[ 101, 1037, 3621, 2936, 6251, 102]])
tensor([[1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 1]]) "Tokenizers" became four pieces and "unbelievably" five, while "split", "long" and "words" are single tokens. That is why token counts, and API bills, are always higher than word counts. Other models use other tokenizers: Llama-style models use byte-level BPE, which marks a leading space instead of using ##. The same sentence gives different ids and a different count with every model, so always count tokens with the tokenizer of the model you call.
Watch out Mixing tokenizers and models. Ids from one tokenizer fed into another model run without any error and produce garbage, because id 2015 means a different piece (or nothing) in another vocabulary. Load both from the same name.
3From token vectors to one sentence vector (mean pooling)
An encoder model such as MiniLM returns one vector per token, each one already mixed with its context by attention (the attention lesson built that). Search needs one vector per text. The usual recipe is mean pooling: average the token vectors.
The catch is padding. In a batch, the short text was padded, and the model still produced vectors for the padding positions. Average them in and the short text's embedding changes depending on what else was in the batch. So you average only where the attention mask is 1, then normalize the result to length 1, so that cosine similarity is a plain dot product (as in the NumPy lesson). Here is the arithmetic with tiny numbers you can check by hand:
import numpy as np
np.set_printoptions(precision=2, suppress=True)
# What a model returns for a batch of 2 texts: one 3-number vector per token.
# Text 0 has 2 real tokens, text 1 has 4. Text 0 was padded with 2 filler tokens.
tokens = np.array([
[[1.0, 0.0, 2.0], [3.0, 2.0, 0.0], [9.0, 9.0, 9.0], [9.0, 9.0, 9.0]],
[[0.0, 1.0, 1.0], [2.0, 1.0, 0.0], [1.0, 3.0, 1.0], [1.0, 3.0, 2.0]],
])
mask = np.array([[1, 1, 0, 0],
[1, 1, 1, 1]]) # 1 = real token, 0 = padding
print("naive mean of text 0:", tokens[0].mean(axis=0)) # padding leaks in
m = mask[:, :, None] # shape (2, 4, 1), so it lines up with tokens
sentence = (tokens * m).sum(axis=1) / m.sum(axis=1)
print("masked mean:")
print(sentence)
unit = sentence / np.linalg.norm(sentence, axis=1, keepdims=True)
print("lengths after normalize:", np.linalg.norm(unit, axis=1))
print(f"cosine(text 0, text 1) = {float(unit[0] @ unit[1]):.3f}")
Expected output
naive mean of text 0: [5.5 5. 5. ] masked mean: [[2. 1. 1.] [1. 2. 1.]] lengths after normalize: [1. 1.] cosine(text 0, text 1) = 0.833
tokens has shape (2, 4, 3): 2 texts, 4 positions, 3 numbers per token. The two 9.0 rows stand for padding. The naive mean of text 0 is dragged up to [5.5 5. 5.] by the padding; the masked mean [2. 1. 1.] is the real average of its two tokens. mask[:, :, None] adds a dimension of size 1 at the end (shape (2, 4, 1)), so NumPy's broadcasting multiplies every number of a token by that token's 0 or 1. .sum(axis=1) adds along the token positions, and m.sum(axis=1) counts the real tokens of each text. keepdims=True keeps the lengths as a column, so each row is divided by its own length.
Tip Mean pooling is not the only recipe. Some models use the [CLS] vector or the last token's vector instead. The model card says which one the model was trained with, and sentence-transformers reads it from the model's files, so you rarely write this yourself. Knowing it helps when results look wrong.
4AutoModel: embeddings by hand
Now the same with a real model. AutoModel.from_pretrained(name) loads the model's architecture from config.json and its weights from the .safetensors file. It returns a normal PyTorch nn.Module, so everything from the neural network lesson applies: model(**batch) runs the forward pass, .eval() switches off training behaviour such as dropout, and torch.no_grad() skips the gradient bookkeeping you only need for training.
all-MiniLM-L6-v2 is a 6-layer encoder with 384 numbers per vector, and its card says it was trained with mean pooling and normalized vectors. The last line checks the hand-written version against the sentence-transformers library.
import torch
from sentence_transformers import SentenceTransformer
from transformers import AutoModel, AutoTokenizer
NAME = "sentence-transformers/all-MiniLM-L6-v2"
tok = AutoTokenizer.from_pretrained(NAME)
model = AutoModel.from_pretrained(NAME)
model.eval()
print("parameters:", sum(p.numel() for p in model.parameters()))
texts = ["How do I reset my password?", "I forgot my login details"]
batch = tok(texts, padding=True, truncation=True, return_tensors="pt")
with torch.no_grad():
out = model(**batch)
tokens = out.last_hidden_state
print("one vector per token:", tuple(tokens.shape))
mask = batch["attention_mask"].unsqueeze(-1).float()
sentence = (tokens * mask).sum(dim=1) / mask.sum(dim=1)
sentence = torch.nn.functional.normalize(sentence, dim=1)
print("one vector per text: ", tuple(sentence.shape))
print("cosine:", round(float(sentence[0] @ sentence[1]), 3))
library = SentenceTransformer(NAME).encode(texts, convert_to_tensor=True, normalize_embeddings=True)
print("same as sentence-transformers:", torch.allclose(sentence, library, atol=1e-5)) AutoModelloads the bare model with no task "head" on top: it returns vectors, not labels. Task versions exist too, such asAutoModelForSequenceClassificationandAutoModelForCausalLM(section 9).line 7numel()is the number of values in one weight tensor. Summed over all of them: 22.7 million parameters, tiny next to the 3 billion ofllama3.2:3b.line 9truncation=Truecuts a text longer than the tokenizer's limit (512 pieces for this one) instead of failing.sentence-transformerscuts MiniLM at 256 pieces, the limit its card gives. Either way the end of a long text is silently ignored, so chunk long documents (as in the RAG lab) instead.line 12**batchspreads the dict into keyword arguments:model(input_ids=..., attention_mask=..., ...), the**kwargstrick from lesson 4.line 15- The output of the last layer: shape
(texts, tokens, 384). The batch was padded to 9 tokens.line 17 unsqueeze(-1)adds a size-1 dimension at the end, the PyTorch spelling of[:, :, None]..float()turns the 0/1 integers into floats so they can multiply the vectors.line 20- Scales each row to length 1, like dividing by
np.linalg.normin the previous section.line 22 allclosecompares with a small tolerance, because adding the same numbers in a different order changes the last digits of a float.line 27
parameters: 22713216 one vector per token: (2, 9, 384) one vector per text: (2, 384) cosine: 0.584 same as sentence-transformers: True
Run it with uv run python embed_by_hand.py. The two questions share no important words, yet their cosine is 0.584, far higher than unrelated sentences get with this model. The hand-written pooling matches the library exactly, so there is no magic in sentence-transformers: it is a tokenizer, a model and the pooling you just wrote.
5sentence-transformers, next to Ollama's embeddings
In real code you let sentence-transformers do all of that. SentenceTransformer(name) loads the tokenizer, the model and the right pooling, and encode turns a list of texts into a NumPy array, one row per text. This is the same tiny search as in lab 5, but with the model running inside your Python process instead of in an Ollama server.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
print("dimensions:", model.get_embedding_dimension())
docs = [
"To change your password, open Settings and choose Security.",
"Invoices are emailed on the first day of each month.",
"You can export your data as CSV from the Reports page.",
]
query = "I forgot my login details"
doc_vecs = model.encode(docs, normalize_embeddings=True)
query_vec = model.encode(query, normalize_embeddings=True)
print("shapes:", doc_vecs.shape, query_vec.shape)
scores = model.similarity(query_vec, doc_vecs)[0]
for score, doc in sorted(zip(scores.tolist(), docs), reverse=True):
print(f"{score:.3f} {doc}") - Loads tokenizer, model and pooling settings in one call. Runs on the CPU unless you pass
device="cuda"(or"mps"on a Mac).line 3 - How many numbers each vector has: 384 for this model.line 4
- A list in, a 2-D NumPy array out: shape
(3, 384).normalize_embeddings=Truemakes every row length 1.line 13 - A single string in, a 1-D array out: shape
(384,).line 14 similaritycomputes the cosine of every query against every document and returns a(1, 3)tensor;[0]takes the one row..tolist()turns it into plain Python floats.line 17
dimensions: 384 shapes: (3, 384) (384,) 0.363 To change your password, open Settings and choose Security. 0.077 You can export your data as CSV from the Reports page. 0.013 Invoices are emailed on the first day of each month.
The right article wins even though it shares no words with the question. To compare with Ollama, start it with nomic-embed-text pulled as in lab 5, run uv add openai numpy, and run this file. It embeds the same texts through Ollama's OpenAI-compatible API (not runnable in the page: it needs the server):
import numpy as np
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
docs = [
"To change your password, open Settings and choose Security.",
"Invoices are emailed on the first day of each month.",
"You can export your data as CSV from the Reports page.",
]
query = "I forgot my login details"
resp = client.embeddings.create(
model="nomic-embed-text",
input=["search_query: " + query] + ["search_document: " + d for d in docs],
)
vecs = np.array([item.embedding for item in resp.data])
vecs = vecs / np.linalg.norm(vecs, axis=1, keepdims=True)
print("dimensions:", vecs.shape[1])
scores = vecs[1:] @ vecs[0]
for score, doc in sorted(zip(scores.tolist(), docs), reverse=True):
print(f"{score:.3f} {doc}")
What you will see, and what it means:
- 768 dimensions instead of 384. Bigger vectors usually capture more, and cost twice the memory and storage in your vector database.
- Different scores. Each model has its own scale. MiniLM's best match scores 0.363 here; nomic's numbers are not comparable with that. A similarity threshold such as "ignore anything under 0.3" must be tuned per model.
- Prefixes.
nomic-embed-textexpectssearch_query:andsearch_document:in front of the text (lab 5 explained why). MiniLM was trained without them. The model card tells you which. - Where it runs.
sentence-transformersruns in your process: no server, but your app now loads PyTorch (hundreds of megabytes of memory). Ollama runs as a separate server any language can call, Java included, which is how Spring AI uses it.
Judge the two on your data with recall@k, as in lab 5, not on one example.
Watch out Mixing vectors from two models. A 384-number MiniLM vector and a 768-number nomic vector cannot even be multiplied (NumPy raises a shape error), and two models with the same size are still different spaces whose scores mean nothing together. Changing the embedding model means re-embedding every document.
6Model cards and licences
Before you build on a model, read its model card: the README on its Hub page. A good card says what the model is for, what it was trained on, how it was evaluated, its limits and biases, how to use it (prefixes, pooling, prompt format) and its licence. The same information is also available as data, so you can check it in code or in CI:
from huggingface_hub import model_info
for name in [
"sentence-transformers/all-MiniLM-L6-v2",
"HuggingFaceTB/SmolLM2-135M",
"meta-llama/Llama-3.2-1B",
]:
info = model_info(name)
card = info.card_data or {}
print(f"{name}")
print(f" licence: {card.get('license')} gated: {info.gated} task: {info.pipeline_tag}") huggingface_hubis the Hub's client library. It came with transformers, so there is nothing new to install.line 1- Meta's Llama 3.2 1B, for contrast. Reading its metadata works without an account; downloading its weights does not.line 6
- One HTTP call that returns the model's metadata: tags, files, downloads and the card's header.line 8
- The YAML header of the model card as a dict-like object.
or {}covers models whose card has no header.line 9 gatedisFalsefor open models, or"auto"/"manual"when you must accept terms on the website (and use a token) before downloading.line 11
sentence-transformers/all-MiniLM-L6-v2 licence: apache-2.0 gated: False task: sentence-similarity HuggingFaceTB/SmolLM2-135M licence: apache-2.0 gated: False task: text-generation meta-llama/Llama-3.2-1B licence: llama3.2 gated: manual task: text-generation
Apache 2.0 and MIT allow commercial use, changes and redistribution, with small conditions such as keeping the licence notice. Many popular models have custom licences instead. The Llama 3.2 Community License, for example, requires you to accept it before downloading, to follow an acceptable use policy, to show "Built with Llama", and to ask Meta for a separate licence if your products have more than 700 million monthly active users. Others, such as anything marked CC BY-NC, forbid commercial use altogether.
Three habits for production. Check the licence of the model and of any data you fine-tune it on. Treat a fine-tuned model or adapter as a derivative of its base model: the base model's licence still applies to it. And pin the exact version with from_pretrained(name, revision="<commit hash>"), because a model repository can change after you tested it, just like a latest Docker tag.
Watch out trust_remote_code=True (some models ask for it, for example nomic-ai/nomic-embed-text-v1.5 in sentence-transformers) downloads Python code from the model's repository and runs it on your machine. Only use it for publishers you trust, and pin a revision so the code cannot change under you.
7Prompt, RAG or fine-tune?
Fine-tuning means continuing to train a pretrained model on your own examples, so its weights change. It is powerful, but it is the most expensive option to build and to maintain, so it comes last. Ask in this order:
- Prompting first. Clear instructions plus a few examples in the prompt (few-shot) fix most problems, cost nothing to change, and work with any model, including the best hosted ones.
- RAG when the model is missing facts. Private documents, data that changes every day, answers that need sources: retrieve the facts and put them in the prompt, as in the RAG lab. Fine-tuning is a poor way to add facts: the model learns them unreliably, cannot cite them, and you must train again whenever they change.
- Fine-tune for behaviour. A fixed output format or style the model keeps getting wrong, a narrow task (classify tickets, extract fields) where a small fine-tuned model can replace a big expensive one, shorter prompts and lower latency because the instructions are now in the weights. You need hundreds to thousands of good examples, and an eval set to prove the tuned model is better.
They combine well: a RAG system can use a small fine-tuned model to rerank or to answer in the house format. And there are two ways to fine-tune. Full fine-tuning updates every weight. Training with the AdamW optimizer in 32-bit floats needs about 16 bytes per parameter (the weight, its gradient and two optimizer values), so an 8 billion parameter model needs over 120 GB of GPU memory before counting activations, and every fine-tuned copy is another full-size model. LoRA freezes all the original weights and trains a small add-on instead: the next two sections show how.
Tip Before any fine-tune, write the eval first: a few hundred inputs with expected outputs, scored automatically. Run it on the prompt-only version. If prompting already scores well enough, you just saved weeks.
8LoRA: the low-rank trick, in NumPy
A layer of a model is a weight matrix W with d rows and k columns. Fine-tuning changes it to W + ΔW. The idea of LoRA (Low-Rank Adaptation) is that the useful change ΔW can be written as the product of two thin matrices: ΔW = B @ A, where B is d × r and A is r × k, with a small rank r such as 8. You freeze W and train only A and B.
"Low rank" means the change can only point in r independent directions, which turns out to be enough to adapt a model to a task. B starts at zero, so at the start B @ A is zero and the model behaves exactly like the original. The update is scaled by lora_alpha / r, a constant that keeps the step size steady when you change r. Run the example to see every claim checked, and the parameter counts:
import numpy as np
rng = np.random.default_rng(0)
d, k, r = 6, 6, 2 # a 6 x 6 layer, LoRA rank 2
alpha = 4 # lora_alpha: the update is scaled by alpha / r
W = rng.normal(size=(d, k)) # pretrained weights: frozen, never changed
A = rng.normal(size=(r, k)) * 0.1 # trainable, starts small and random
B = np.zeros((d, r)) # trainable, starts at zero
x = rng.normal(size=k) # one input vector
scale = alpha / r
def lora_layer(x):
return W @ x + scale * (B @ (A @ x))
print("same as the original at the start:", np.allclose(lora_layer(x), W @ x))
B = rng.normal(size=(d, r)) * 0.1 # pretend training has moved B
delta = scale * (B @ A) # the full-size change LoRA describes
print("delta shape:", delta.shape, " rank:", int(np.linalg.matrix_rank(delta)))
merged = W + delta # fold the adapter into the weights
print("merged layer gives the same output:", np.allclose(merged @ x, lora_layer(x)))
print("full fine-tune trains", W.size, "numbers; LoRA trains", A.size + B.size)
def lora_params(d_out, d_in, r):
return r * (d_in + d_out) # A is r x d_in, B is d_out x r
big = 4096 * 4096
print(f"one 4096 x 4096 layer: {big:,} vs LoRA r=8: {lora_params(4096, 4096, 8):,}"
f" ({lora_params(4096, 4096, 8) / big:.2%})")
# SmolLM2-135M: 30 layers; q_proj is 576 -> 576, v_proj is 576 -> 192
per_layer = lora_params(576, 576, 8) + lora_params(192, 576, 8)
print(f"SmolLM2-135M, r=8 on q_proj and v_proj: {30 * per_layer:,} trainable")
Expected output
same as the original at the start: True delta shape: (6, 6) rank: 2 merged layer gives the same output: True full fine-tune trains 36 numbers; LoRA trains 24 one 4096 x 4096 layer: 16,777,216 vs LoRA r=8: 65,536 (0.39%) SmolLM2-135M, r=8 on q_proj and v_proj: 460,800 trainable
W @ x is the original layer; B @ (A @ x) is the LoRA side path, computed as two small multiplications so the full d × k change is never built during training. np.linalg.matrix_rank confirms the 6 × 6 change has rank 2. After training you can merge the change into W (W + delta), so the merged model is exactly as fast as the original. On a tiny 6 × 6 layer LoRA saves little (24 numbers against 36), but the saving grows with the size: for a 4096 × 4096 layer, rank 8 trains 0.39% of the numbers. The last line predicts the exact count peft will report for SmolLM2 in the next section.
Tip Typical settings: r between 8 and 64, lora_alpha equal to r or twice it, applied to the attention projections (q_proj, v_proj) or to every linear layer (target_modules="all-linear" in peft). A higher r can learn more, and needs more data to do so.
9LoRA with peft: set up, train, save
Now a real fine-tune, small enough for a laptop CPU. The base model is HuggingFaceTB/SmolLM2-135M, a 135 million parameter text generator under Apache 2.0 (a 270 MB download). The task: read a support ticket and answer with one label, account, billing or bug. Nine examples are far too few for a real project, but enough to watch LoRA work in under a minute.
AutoModelForCausalLM is the model plus its language-model head: it predicts the next token. LoraConfig holds the settings from the previous section, and get_peft_model swaps every targeted layer for a LoRA version and freezes everything else. The training loop is the same five lines as in the neural network lesson.
import torch
from peft import LoraConfig, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer
torch.manual_seed(0)
NAME = "HuggingFaceTB/SmolLM2-135M"
tok = AutoTokenizer.from_pretrained(NAME)
tok.pad_token = tok.eos_token
model = AutoModelForCausalLM.from_pretrained(NAME)
TRAIN = [
("I cannot log in to my account", "account"),
("My password reset email never arrived", "account"),
("How do I change my username?", "account"),
("I was charged twice this month", "billing"),
("Please send me last month's invoice", "billing"),
("Can I pay by bank transfer?", "billing"),
("The app crashes when I open a report", "bug"),
("The export button does nothing", "bug"),
("Charts show the wrong dates", "bug"),
]
TEST = ["I was billed for a plan I cancelled", "The page goes blank after I click save"]
def prompt(ticket):
return f"Ticket: {ticket}\nLabel:"
def label_of(ticket):
ids = tok(prompt(ticket), return_tensors="pt")
with torch.no_grad():
out = model.generate(**ids, max_new_tokens=3, do_sample=False,
pad_token_id=tok.eos_token_id)
new_tokens = out[0, ids["input_ids"].shape[1]:]
return tok.decode(new_tokens).split("\n")[0].strip()
print("before:", [label_of(t) for t in TEST])
config = LoraConfig(
r=8,
lora_alpha=16,
lora_dropout=0.05,
target_modules=["q_proj", "v_proj"],
task_type="CAUSAL_LM",
)
model = get_peft_model(model, config)
model.print_trainable_parameters()
q = model.base_model.model.model.layers[0].self_attn.q_proj
print("A:", tuple(q.lora_A["default"].weight.shape), "B:", tuple(q.lora_B["default"].weight.shape))
texts = [f"{prompt(t)} {label}\n" for t, label in TRAIN]
batch = tok(texts, padding=True, return_tensors="pt")
labels = batch["input_ids"].clone()
labels[batch["attention_mask"] == 0] = -100
trainable = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.AdamW(trainable, lr=2e-3)
model.train()
for step in range(1, 31):
loss = model(**batch, labels=labels).loss
loss.backward()
optimizer.step()
optimizer.zero_grad()
if step == 1 or step % 10 == 0:
print(f"step {step:2} loss {loss.item():.3f}")
model.eval()
print("after: ", [label_of(t) for t in TEST])
model.save_pretrained("ticket-lora") - SmolLM2's tokenizer has no padding token, and padding a batch without one raises
ValueError: Asking to pad but the tokenizer does not have a padding token. Reusing the end-of-text token is the standard fix; the attention mask still marks it as padding.line 8 - Loads the base model. transformers 5 keeps the dtype the weights were saved in, here bfloat16 (2 bytes per number).line 9
- The prompt format. Training and use must share it exactly, down to the newline and the space.line 26
generatewrites up to 3 new tokens.do_sample=Falsealways picks the most likely token (greedy), so the result is repeatable.pad_token_idtells it which id means padding.line 32- The output contains the prompt too. Slicing from the prompt length keeps only the newly written tokens.line 34
- Which layers get a LoRA pair, by name: the query and value projections inside every attention block.line 44
- Tells peft this is a next-token model, so it wraps it the right way.line 45
- Freezes all 134.5 million original weights and inserts the trainable
AandBmatrices.line 47 - Prints trainable against total parameters. 460,800 is exactly the number the NumPy section predicted.line 48
- peft can hold several adapters on one model, so each is stored under a name. Unnamed means
"default".line 50 - The **labels** are the input ids themselves: the model learns to predict each next token (it shifts them by one internally).
-100means "no loss here", so the padding is not trained on.line 55 - Only the LoRA matrices have
requires_grad=True, so the optimizer only gets those.line 57 - Training mode: switches on the
lora_dropoutfrom the config.line 59 - With
labels=the model computes the cross-entropy loss itself. Then the usual backward, step, zero_grad.line 61 - Saves only the adapter:
adapter_config.jsonplusadapter_model.safetensors, about 1.9 MB, not the 270 MB base model.line 70
before: ['I was b', 'The page goes'] trainable params: 460,800 || all params: 134,975,808 || trainable%: 0.3414 A: (8, 576) B: (576, 8) step 1 loss 4.871 step 10 loss 1.415 step 20 loss 0.448 step 30 loss 0.198 after: ['billing', 'bug']
Run it with uv run python lora_train.py. It takes about half a minute on a laptop CPU after the download. Before training, the base model just keeps writing ticket-like text ("I was b..."), because it has never seen this format. After 30 steps it answers with the right labels for two tickets it never saw. On another machine the losses can differ in the last digits.
To use the adapter later, load the base model and put the adapter on top. merge_and_unload() folds B @ A into the weights, exactly like W + delta in NumPy, and gives back a plain transformers model with no LoRA layers left. This prints LlamaForCausalLM (SmolLM2 uses the Llama architecture) and then billing:
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
NAME = "HuggingFaceTB/SmolLM2-135M"
tok = AutoTokenizer.from_pretrained(NAME)
base = AutoModelForCausalLM.from_pretrained(NAME)
model = PeftModel.from_pretrained(base, "ticket-lora")
model = model.merge_and_unload()
print(type(model).__name__)
ids = tok("Ticket: My card was declined\nLabel:", return_tensors="pt")
out = model.generate(**ids, max_new_tokens=3, do_sample=False, pad_token_id=tok.eos_token_id)
print(tok.decode(out[0, ids["input_ids"].shape[1]:]).split("\n")[0].strip())
Real fine-tunes differ in scale, not in kind: thousands of examples, a held-out eval set, the loss computed only on the answer tokens (set the prompt positions in labels to -100 too), and usually the Trainer class from transformers or SFTTrainer from the trl library, which write this loop for you. QLoRA loads the frozen base model in 4-bit to fit bigger models on one GPU. An adapter is small enough to keep one per customer or per task and swap them on one base model.
Watch out Training on nine examples and calling it done. A model this small, tuned on this little data, mostly learns the format; it will mislabel plenty of real tickets. Measure it on a few hundred held-out tickets, and compare with simply prompting a bigger model, before you trust it.
Common mistakes
- Leaving out
model=inpipeline(), so a default model you never chose ends up in production and changes when transformers changes. - Using a tokenizer from one model with another model. There is no error, just garbage. Load both from the same name.
- Averaging token vectors without the attention mask, so the padding changes a text's embedding depending on its batch.
- Mixing embeddings from two models in one index, or reusing a similarity threshold tuned for another model.
- Fine-tuning to teach the model facts. Use RAG for facts, and fine-tuning for format, style and narrow tasks.
- Skipping the model card: missing the prefixes an embedding model needs, or shipping a model whose licence forbids commercial use.
Practice
Write the code, then press Check. Your work is saved in this browser.
1Count LoRA parameters
Write lora_trainable(layers, r). layers is a list of (d_out, d_in) pairs, one per weight matrix that gets a LoRA adapter. For each, A has r × d_in numbers and B has d_out × r. Return the total number of trainable numbers.
def lora_trainable(layers, r):
# A is r x d_in, B is d_out x r
return 0
print(lora_trainable([(4096, 4096)], 8))
Hint
Sum `r * d_in + d_out * r` over the pairs: `sum(r * (d_in + d_out) for d_out, d_in in layers)`.
2Mean pooling with a mask
Write mean_pool(vectors, mask) in plain Python (no NumPy). vectors is a list of token vectors (each a list of floats) for one text, and mask is a list of 1s and 0s of the same length. Return the average of the vectors whose mask is 1, as a list of floats. Raise ValueError if no position has mask 1.
def mean_pool(vectors, mask):
# averages everything, padding included
n = len(vectors)
return [sum(v[i] for v in vectors) / n for i in range(len(vectors[0]))]
print(mean_pool([[1.0, 0.0], [3.0, 2.0], [9.0, 9.0]], [1, 1, 0]))
Hint
Keep only the vectors where the mask is 1 (`[v for v, m in zip(vectors, mask) if m]`), raise if that list is empty, then average each position.
3Merge a LoRA adapter
Write merge(W, A, B, alpha) in plain Python. W is d × k, B is d × r and A is r × k, all lists of lists. Return the merged weights W + (alpha / r) * (B @ A) as a new list of lists, where r is the number of rows of A. Do not change W.
def merge(W, A, B, alpha):
# forgets the adapter
return [row[:] for row in W]
print(merge([[1, 0], [0, 1]], [[1, 2]], [[1], [0]], 1))
Hint
`r = len(A)` and `scale = alpha / r`. Entry `(i, j)` of `B @ A` is `sum(B[i][t] * A[t][j] for t in range(r))`.
Interview questions
Q1What do AutoTokenizer and AutoModel do?
They are factories. from_pretrained(name) reads the model's config from the Hub (or the local cache) and builds the right tokenizer or model class with its trained weights, so the same code works for BERT, Llama or any other architecture. Task variants such as AutoModelForCausalLM add the right output head.
Q2How do you get one embedding for a sentence from a transformer encoder?
Run the tokenized batch through the model to get one vector per token, then pool them, usually a mean over the positions where the attention mask is 1, and normalize to length 1 so cosine similarity is a dot product. The model card says which pooling the model was trained with.
Q3When would you fine-tune instead of using RAG or prompting?
Prompting first, because it is cheap and fast to change. RAG when the model lacks knowledge, especially private or changing facts that need sources. Fine-tuning when you need consistent behaviour (format, style, a narrow task such as classification), or a smaller cheaper model that matches a big one on that task, and you have enough good examples and an eval set to prove it helps.
Q4Explain LoRA.
LoRA freezes the pretrained weights and learns each layer's change as a product of two small matrices, ΔW = B A with rank r (often 8 to 64), scaled by alpha / r. B starts at zero so training starts from the original model. Only A and B are trained, typically under 1% of the parameters, which cuts memory, gives adapters of a few megabytes, and they can be merged into the weights afterwards with no extra inference cost.
Q5What do you check before using an open model in production?
The licence (commercial use, attribution, user limits, whether it is gated) and the licence of any fine-tuning data; the model card for intended use, training data, limits and usage details such as prefixes or prompt format; quality on your own eval set; size and latency on your hardware; and a pinned revision so the model cannot change under you. Avoid trust_remote_code unless you trust the publisher.