Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 6 of 13
Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
Follow SmolLM2-135M from files on disk to words on screen: a 269.1 MB weights file, 134,515,008 parameters in memory, text turned into token ids, the top-5 next tokens after "The capital of France is", and generate with greedy and temperature settings.
What you will learn
- Download a model's files once and know which file holds the weights
- Load a tokenizer and a model with AutoTokenizer and AutoModelForCausalLM
- Read the next-token probabilities from one forward pass
- Generate text with greedy decoding and with temperature
Before you start
- Pretrained Models from Hugging Face
- Basic Python
You type a question into a local chatbot, and a moment later the answer appears, one token at a time. Something happens in the middle: files, memory, numbers. This article opens up that middle part.
Two reminders before we start. A model is a big pile of learned numbers called weights. A language model uses those weights to predict the next token, again and again. That's all you need.
A recipe book and a cook
You buy a recipe book once and put it on the shelf. That's the download: the files stay on your disk, in a folder called the cache. When the cook wants to use it, the book is opened on the counter. That's loading: the weights go into your computer's memory. Then every day the cook makes a dish from the open book. That's inference, and every question is one more dish.
So download happens once. Load happens once per program. Inference happens for every single question.
All the code uses HuggingFaceTB/SmolLM2-135M-Instruct, a small model that runs on a CPU with no API key. The numbers below came from one laptop; yours will differ.
Step 1: download the files once
"""Step 1 - download the model files once and look at what is on disk."""
from pathlib import Path
from huggingface_hub import snapshot_download
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
NEEDED = ["config.json", "generation_config.json", "tokenizer.json", "tokenizer_config.json",
"vocab.json", "merges.txt", "special_tokens_map.json", "model.safetensors"]
folder = Path(snapshot_download(MODEL, allow_patterns=NEEDED))
for name in NEEDED:
size = (folder / name).resolve().stat().st_size
shown = f"{size / 1_000_000:.1f} MB" if size >= 1_000_000 else f"{size / 1_000:.1f} KB"
print(f"{name:26} {shown:>9}")
config.json 0.9 KB
generation_config.json 0.1 KB
tokenizer.json 2.1 MB
tokenizer_config.json 3.8 KB
vocab.json 800.7 KB
merges.txt 466.4 KB
special_tokens_map.json 0.7 KB
model.safetensors 269.1 MB
The first time, snapshot_download fetches the files from Hugging Face. After that it simply reads them from the cache.
Look at the sizes. model.safetensors is 269.1 MB, and everything else is small. That one file is the model: all the weights live there. config.json describes the shape of the network, and the tokenizer files know how to cut text into pieces.
Step 2: load the weights into memory
"""Step 2 - load the tokenizer and the weights into memory."""
import time
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
start = time.perf_counter()
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL)
seconds = time.perf_counter() - start
parameters = sum(p.numel() for p in model.parameters())
print(f"load time: {seconds:.1f} s")
print(f"parameters: {parameters:,}")
print(f"dtype: {next(model.parameters()).dtype}")
print(f"vocabulary: {len(tokenizer):,} tokens")
load time: 5.9 s
parameters: 134,515,008
dtype: torch.bfloat16
vocabulary: 49,152 tokens
Two objects come out. The tokenizer handles the text side, and the model holds the weights. Adding up numel() for every weight tensor gives 134,515,008 parameters, now in memory. The load took about 5.9 seconds on this laptop. A bigger model takes longer and needs more memory; Model Size, Memory and Ways to Run It works out how much.
Step 3: the tokenizer turns text into numbers
The model can't read letters. It only understands numbers.
"""Step 3 - the tokenizer turns text into numbers and back."""
from transformers import AutoTokenizer
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
text = "Python makes AI engineering fun."
ids = tokenizer.encode(text)
pieces = tokenizer.convert_ids_to_tokens(ids)
print("text: ", text)
print("ids: ", ids)
print("pieces:", pieces)
print("back: ", tokenizer.decode(ids))
text: Python makes AI engineering fun.
ids: [23297, 2022, 5646, 4665, 1037, 30]
pieces: ['Python', 'Ġmakes', 'ĠAI', 'Ġengineering', 'Ġfun', '.']
back: Python makes AI engineering fun.
encode cuts the sentence into pieces and gives each piece a number. The Ġ at the start of a piece just means there was a space before the word. The sentence became six numbers, and decode turns the same numbers back into the original sentence. Text in, numbers through, text out. (Tokens are also what you pay for with hosted models; see LLM Tokens, Context Windows and Cost.)
Step 4: one prediction
"""Step 4 - one forward pass: how likely is each possible next token?"""
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL)
prompt = "The capital of France is"
inputs = tokenizer(prompt, return_tensors="pt")
with torch.no_grad():
logits = model(**inputs).logits[0, -1]
probabilities = torch.softmax(logits, dim=-1)
top = torch.topk(probabilities, 5)
print("prompt:", prompt)
for p, token_id in zip(top.values, top.indices):
print(f"{tokenizer.decode(token_id)!r:12} {p.item():.1%}")
prompt: The capital of France is
' Paris' 41.8%
' the' 28.7%
' located' 9.3%
' called' 1.8%
' Le' 1.6%
The model runs once on the prompt. logits[0, -1] takes the scores for the last position, the slot where the next token goes, and softmax turns them into probabilities that add up to 1.
The model didn't pick an answer. It gave a chance to every token in its 49,152-token vocabulary. " Paris" is most likely at 41.8%, but " the" is close behind at 28.7%. Choosing one is a separate step.
Inference is a loop
- The tokenizer turns the prompt into ids.
- The model does one forward pass and gives chances for the next token.
- We choose one. Always taking the top token is called greedy; here it would be " Paris".
- The new token is added to the ids, and we go back to step 2.
When we hit the length limit, or the model produces its end token, the tokenizer decodes all the new ids into the text you read.
Step 5: generate, three ways
"""Step 5 - generate text: greedy, then two temperatures. Load time vs generate time."""
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
start = time.perf_counter()
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForCausalLM.from_pretrained(MODEL)
load_seconds = time.perf_counter() - start
messages = [{"role": "user", "content": "Give me one tip for learning Python."}]
prompt = tokenizer.apply_chat_template(
messages, add_generation_prompt=True, return_tensors="pt", return_dict=True
)
prompt_length = prompt["input_ids"].shape[1]
def ask(**settings):
start = time.perf_counter()
output = model.generate(
**prompt, max_new_tokens=40, pad_token_id=tokenizer.eos_token_id, **settings
)
seconds = time.perf_counter() - start
new_tokens = output[0][prompt_length:]
text = tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
return text, len(new_tokens), seconds
print(f"load: {load_seconds:.1f} s")
runs = [("greedy", dict(do_sample=False)),
("temperature 0.7", dict(do_sample=True, temperature=0.7)),
("temperature 1.2", dict(do_sample=True, temperature=1.2))]
for name, settings in runs:
torch.manual_seed(42)
text, count, seconds = ask(**settings)
print(f"--- {name}: {count} tokens in {seconds:.1f} s")
print(text)
What each part does:
- The load is timed on its own, because it happens once.
apply_chat_templatewraps the question in the format this instruct model was trained on.generateis the loop from the diagram.max_new_tokens=40stops it after 40 tokens.- Three settings: greedy, then sampling (
do_sample=True) at temperature 0.7 and 1.2. torch.manual_seed(42)fixes the dice, so a sampled run can be repeated.
load: 2.9 s
--- greedy: 40 tokens in 11.5 s
One tip for learning Python is to use the `itertools` module, which provides a `zip_longest` function to iterate over multiple iterables simultaneously. This can be a great way to
--- temperature 0.7: 40 tokens in 18.9 s
One tip for learning Python is to start with the basics and gradually move on to more advanced topics. Here are a few key concepts to get you started:
1. Variables: Variables in Python are
--- temperature 1.2: 40 tokens in 13.8 s
One tip for learning Python is to start with interactive coding environments, libraries, and frameworks, like Jupyter Notebooks, Panda Books, and the Pandas Library. Here are two key concepts:
Same question, three answers. Greedy always takes the top token and talks about itertools. At temperature 0.7 it starts with the basics and begins a numbered list. At 1.2 the wording gets more adventurous, and "Panda Books" shows a small model drifting. A higher temperature gives more varied wording, and every answer stops mid-sentence because of the 40-token cap.
Now the times. Loading took 2.9 seconds in this run, and we pay that once. Each answer took between 11.5 and 18.9 seconds. This small model is quick to open, but every answer costs time, on every question.
Common mistakes
- Loading the model inside the request handler. Load once when the program starts; only inference should run per question.
- Thinking the model returns an answer. It returns a probability for every possible next token. Decoding settings choose the words.
- Skipping the chat template with an instruct model. It was trained on that format; a bare string gets weaker answers.
- Comparing sampled outputs without a seed. With
do_sample=True, every run differs unless you fix the seed. - Forgetting
max_new_tokens. It caps both the length and the time each answer costs.
Quick recap
| Step | Happens | In this run |
|---|---|---|
| Download | Once, into the cache | model.safetensors 269.1 MB |
| Load | Once per program | 134,515,008 parameters, 5.9 s |
| Tokenize | Every question | 6 ids for "Python makes AI engineering fun." |
| Predict | Every new token | " Paris" 41.8%, " the" 28.7% |
| Generate | The predict step in a loop | 40 tokens in 11.5 to 18.9 s |
Try it yourself
Change the prompt in step 4 and read the new top 5. Change max_new_tokens in step 5 and watch the time move. Then swap in another small model and compare its file sizes and load time.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
Next →Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.