AI and machine learning · Intermediate · 25 min
Run a small language model with Hugging Face Transformers
By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · transformers 5.24.1 · PyTorch 2.15.0 (CPU)
You will load SmolLM2-135M-Instruct with Transformers on a CPU, inspect its tokens and chat template, generate answers with greedy and sampled decoding, limit and stream the output, and pin the exact model files after checking their licence.
On this page
A packaged runtime such as Ollama hides the moving parts of a language model behind one command. That is what you want in production, but it leaves you guessing when an answer comes out cut short, repeats itself or changes between runs. The Hugging Face Transformers library shows those parts in plain Python: a tokenizer that turns text into numbers, a model that predicts the next number, a chat template that wraps your message the way the model was trained on, and a generate() call whose settings decide how each next token is chosen.
In this tutorial you run HuggingFaceTB/SmolLM2-135M-Instruct on a CPU. It has 135 million parameters, which is small enough for an ordinary laptop and about 270 MB to download. It is far weaker than the models behind hosted chat products, and that is useful here: its mistakes are plain to see, and every script finishes in seconds. Everything you learn carries over to larger models, and it is the base that fine-tuning a small language model with LoRA builds on.
Step 1 · Create a project and install the libraries
Make a throwaway folder and a virtual environment:
mkdir -p ~/transformers-demo
cd ~/transformers-demo
python3 -m venv .venv
source .venv/bin/activateInstall PyTorch from its CPU-only index first. If pip pulls PyTorch in as a dependency on Linux, it can fetch the far larger build with GPU libraries, which you do not need. Then install Transformers at a pinned version:
pip install --quiet torch==2.15.0 --index-url https://download.pytorch.org/whl/cpu
pip install --quiet transformers==5.24.1The PyTorch download is a few hundred megabytes. If you pay for prepaid mobile data, do this step on Wi-Fi; it happens once.
Check it worked
python -c "import torch, transformers; print(torch.__version__, transformers.__version__, torch.cuda.is_available())"The output is 2.15.0+cpu 5.24.1 False on Linux. On macOS the PyTorch version has no +cpu suffix. False confirms that no GPU is involved.
Step 2 · Check the licence and pin a revision
Before you download a model, read its licence. Some open models allow any use, others forbid commercial use or set conditions once you pass a number of users, and the model card is where that is stated. SmolLM2-135M-Instruct is published under Apache 2.0, which allows commercial use as long as you keep the licence notice.
A model repository on the Hugging Face Hub is a Git repository, and its files can change after you start using it. Pin the commit you checked, so the licence you read and the weights you run stay the same. Put the model name and commit in one file that every later script imports:
cat > common.py <<'PY'
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL_ID = "HuggingFaceTB/SmolLM2-135M-Instruct"
REVISION = "12fd25f77366fa6b3b4b768ec3050bf629380bac"
def load():
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, revision=REVISION)
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, revision=REVISION, dtype=torch.float32)
model.eval()
return tokenizer, model
def chat_inputs(tokenizer, question):
messages = [{"role": "user", "content": question}]
return tokenizer.apply_chat_template(
messages, add_generation_prompt=True, return_tensors="pt", return_dict=True
)
PYdtype=torch.float32 asks for 32-bit weights. The files are stored in bfloat16, and many CPUs run float32 faster and with fewer surprises.
Now ask the Hub what that exact commit says about itself. This downloads only metadata, not the weights:
cat > licence.py <<'PY'
from huggingface_hub import model_info
from common import MODEL_ID, REVISION
info = model_info(MODEL_ID, revision=REVISION)
print("model:", info.id)
print("revision:", info.sha)
print("licence:", info.card_data.license)
print("weights:", [s.rfilename for s in info.siblings if s.rfilename.endswith(".safetensors")])
assert info.sha == REVISION
assert info.card_data.license == "apache-2.0"
PY
python licence.pyCheck it worked
The script prints the model name, the same 40-character revision you pinned, licence: apache-2.0 and weights: ['model.safetensors']. The metadata tag is a summary: open the model card at huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct and read its License and Limitations sections yourself before you ship anything built on it. When you want a newer version later, read the card again and then change REVISION on purpose.
Step 3 · Load the tokenizer and look at token ids
A model never sees letters. The tokenizer splits text into pieces from a fixed vocabulary and replaces each piece with its number. Load both parts and look at what two sentences become:
cat > tokens.py <<'PY'
from common import load
tokenizer, model = load()
print("parameters:", sum(p.numel() for p in model.parameters()))
print("vocabulary size:", len(tokenizer))
for text in ["Mobile money makes it easy to pay for airtime.",
"Ẹ jọ̀ọ́, ẹ ràn mí lọ́wọ́ láti san owó iná."]:
ids = tokenizer(text)["input_ids"]
print(len(text.split()), "words ->", len(ids), "tokens")
print(" ids: ", ids[:10])
print(" pieces:", tokenizer.convert_ids_to_tokens(ids)[:10])
assert tokenizer.decode(ids) == text
print("end-of-sequence token:", tokenizer.eos_token, tokenizer.eos_token_id)
PY
python tokens.pyThe first run downloads the model into ~/.cache/huggingface. Later runs read it from there.
Check it worked
The model has 134515008 parameters, the 135 million in its name, and a vocabulary of 49152 pieces. The English sentence of 9 words becomes 11 tokens, and most pieces are whole words: 'Ġmoney', 'Ġpay', then 'Ġair' and 'time' for the one word it does not know. The Ġ at the start of a piece stands for a space. The Yoruba sentence ("Please help me pay the electricity bill") has 10 words but becomes 39 tokens, and its pieces look like 'áº' and '¸'. This tokenizer was built mostly from English text, so it has no pieces for tone-marked letters and falls back to their raw bytes, which print as odd characters. Decoding the ids gives back the original text exactly, which the assert checks. The last line, end-of-sequence token: <|im_end|> 2, names the token the model emits when it has finished an answer; you use it in a later step.
Token counts matter. They set how much text fits in the model's context, how long generation takes and, with hosted APIs, what you pay. If your users write in Yoruba, Hausa, Amharic or a mix of English and Pidgin, measure token counts on their real text before you plan limits, and expect the output quality of an English-trained model to be lower in those languages too.
Step 4 · Apply the chat template
An instruct model was trained on conversations written in a particular format, with markers for who is speaking. If you feed it a bare question, it often carries on the text instead of answering. The tokenizer stores that format as a chat template. See what it produces:
cat > template.py <<'PY'
from common import chat_inputs, load
tokenizer, model = load()
messages = [{"role": "user", "content": "What is the capital of Kenya?"}]
prompt = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
print(prompt)
inputs = chat_inputs(tokenizer, "What is the capital of Kenya?")
print("prompt length in tokens:", inputs["input_ids"].shape[1])
assert prompt.rstrip().endswith("<|im_start|>assistant")
PY
python template.pyCheck it worked
The printed prompt has three parts, each opened by <|im_start|> and closed by <|im_end|>: a system message the template adds for you (You are a helpful AI assistant named SmolLM, trained by Hugging Face), your user message, and a final <|im_start|>assistant line with nothing after it. That last line is what add_generation_prompt=True adds; it tells the model that the next tokens are its answer. The last line reports prompt length in tokens: 37, about four times the length of the question itself. Every model family has its own template, so always build prompts with apply_chat_template rather than writing the markers by hand.
Step 5 · Generate with greedy decoding
At each step the model scores every token in its vocabulary. Greedy decoding picks the highest score every time, so the same prompt always gives the same answer on the same setup. Ask a question twice and compare:
cat > greedy.py <<'PY'
import torch
from common import chat_inputs, load
tokenizer, model = load()
inputs = chat_inputs(tokenizer, "What is the capital of Kenya? Answer in one sentence.")
prompt_len = inputs["input_ids"].shape[1]
answers = []
for run in range(2):
with torch.no_grad():
output = model.generate(**inputs, do_sample=False, max_new_tokens=40)
new_tokens = output[0, prompt_len:]
answers.append(tokenizer.decode(new_tokens, skip_special_tokens=True))
print(f"run {run + 1}: {answers[-1]!r}")
print("identical:", answers[0] == answers[1])
assert answers[0] == answers[1]
PY
python greedy.pygenerate() returns the prompt and the answer as one sequence of ids, so the script slices off the first prompt_len tokens before decoding. torch.no_grad() tells PyTorch not to record the arithmetic for training, which saves memory.
Check it worked
Both runs print the same sentence and the last line is identical: True. The answer is 'The capital of Kenya is Nairobi.', or something very close on another CPU. Read it rather than trusting it: a model this size states wrong facts with the same confidence as right ones, and the model card says so. Any feature you build on a language model needs a step where a person, or a test against known answers, checks what it says.
Step 6 · Sample with temperature and a seed
Greedy answers can be flat and repetitive. Sampling picks the next token at random, in proportion to its score. temperature below 1 sharpens the scores towards the likeliest tokens and above 1 flattens them; top_p=0.9 drops the unlikely tail that together makes up the last 10 per cent. A seed makes the random choices repeatable:
cat > sample.py <<'PY'
import torch
from common import chat_inputs, load
tokenizer, model = load()
inputs = chat_inputs(tokenizer, "Suggest a name for a small shop that sells phone accessories.")
prompt_len = inputs["input_ids"].shape[1]
def sample(seed):
torch.manual_seed(seed)
with torch.no_grad():
output = model.generate(**inputs, do_sample=True, temperature=0.8, top_p=0.9, max_new_tokens=30)
return tokenizer.decode(output[0, prompt_len:], skip_special_tokens=True)
results = {seed: sample(seed) for seed in (1, 2, 3)}
for seed, text in results.items():
print(f"seed {seed}: {text!r}")
again = sample(1)
print("seed 1 again matches:", again == results[1])
assert again == results[1]
assert len(set(results.values())) > 1
PY
python sample.pyCheck it worked
The three seeds give at least two different suggestions, and seed 1 again matches: True shows that the same seed reproduces the same text. Your wording will differ from anyone else's, and it can change between machines or library versions even with the same seed, so never write tests that expect exact sampled text. Use greedy decoding when you need repeatable output, such as for tests or data extraction, and sampling when you want variety, such as for suggestions or drafts.
Step 7 · Limit the answer with max_new_tokens
max_new_tokens caps how many tokens the model may add. It is your main control over time and memory, but it cuts the answer mid-sentence rather than asking the model to be brief. Run one question with a tight limit and a looser one, and check why each run stopped:
cat > length.py <<'PY'
import torch
from common import chat_inputs, load
tokenizer, model = load()
inputs = chat_inputs(tokenizer, "Explain in detail how a solar panel produces electricity.")
prompt_len = inputs["input_ids"].shape[1]
for limit in (10, 60):
with torch.no_grad():
output = model.generate(**inputs, do_sample=False, max_new_tokens=limit)
new_tokens = output[0, prompt_len:]
hit_limit = new_tokens[-1].item() != tokenizer.eos_token_id
print(f"max_new_tokens={limit}: generated {len(new_tokens)} tokens, stopped at limit: {hit_limit}")
print(" ", repr(tokenizer.decode(new_tokens, skip_special_tokens=True)))
assert len(new_tokens) <= limit
if limit == 10:
assert hit_limit
PY
python length.pyCheck it worked
With max_new_tokens=10 the script reports generated 10 tokens, stopped at limit: True, and the text breaks off mid-sentence. With 60 the answer is a numbered explanation that also stops at the limit, part way through a sentence. The greedy answer about Kenya, by contrast, ended well inside its limit of 40. A run that ends on the end-of-sequence token (<|im_end|>, id 2 for this model, which tokens.py printed) finished on its own; one that does not was cut short. Check that in your own code and tell the user, or ask for a shorter answer in the prompt, rather than showing a truncated sentence as if it were complete.
Step 8 · Stream tokens as they are generated
On a slow CPU a long answer can take several seconds. Printing tokens as they arrive makes the wait feel shorter and lets the reader stop early. TextStreamer prints to the terminal while generate() runs:
cat > stream.py <<'PY'
import torch
from transformers import TextStreamer
from common import chat_inputs, load
tokenizer, model = load()
inputs = chat_inputs(tokenizer, "Give three tips for saving mobile data on a phone.")
streamer = TextStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
with torch.no_grad():
model.generate(**inputs, do_sample=False, max_new_tokens=80, streamer=streamer)
PY
python stream.py | tee stream.txtCheck it worked
The answer appears a few words at a time instead of all at once. skip_prompt=True keeps the chat template out of the output, so you see only the answer, with no <|im_start|> markers. Read the tips critically. This model's advice often sounds reasonable and is wrong; a run while writing this suggested cloud storage as a way to save mobile data, which uses more. TextStreamer only prints; to send tokens to a web page or another thread, Transformers also has TextIteratorStreamer, which you read in a loop.
Step 9 · Run offline and clean up
The model is now in your cache, so you can run without a connection. This also stops the library spending data on update checks:
HF_HUB_OFFLINE=1 python greedy.pyCheck it worked
The same two identical answers print, with no download. Because REVISION is pinned, the offline run uses exactly the files you checked.
When you have finished, remove the project and the cached model. If you are going on to fine-tune this model with LoRA, keep the cache to save the download:
deactivate
cd ~
rm -rf ~/transformers-demo ~/.cache/huggingface/hub/models--HuggingFaceTB--SmolLM2-135M-Instruct
ls ~/transformers-demo 2>/dev/null || echo "removed"The last command prints removed.
Next steps
Related tutorials
- Write a system prompt that sets the role, the rules and the output formatYou will turn a one-line prompt into a structured system prompt for a solar installer's support assistant, keep it in a template file that Python renders, and prove with deterministic tests that it is built correctly, stays cacheable and has a format your code can parse.
- Tune model settings with grid search and random searchYou will tune a gradient-boosting churn model with GridSearchCV, RandomizedSearchCV and HalvingRandomSearchCV, compare what each costs and finds, read cv_results_ to see how flat the top is, and report an honest score with nested cross-validation and an untouched test set.
- Train a small convolutional network to read handwritten digitsYou will train a two-layer convolutional network in PyTorch on scikit-learn's bundled 8x8 digits, compare it with logistic regression, read its confusion matrix and mistakes, and make it robust to shifted digits with data augmentation.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials