The Hugging Face Hub holds hundreds of thousands of open models, and the transformers library loads almost any of them with two lines: a tokenizer that turns text into token IDs, and a model that turns IDs into predictions. Using them in production means knowing what the tokenizer does to your text, how long inputs can be, how batching and padding work, how much memory a model needs, and pinning exactly which version you run. This lesson classifies support tickets with a pretrained model, and shows the two quiet failures: silent truncation of long text, and a model that changes because nobody pinned its revision.
Difficulty: Advanced · Know this first: Lesson 253, Lesson 234
This bar adds up minutes to put the model to work, including what its quiet failures cost. It is a worked example, not a measurement. The length and pin hops are where it changes behind your back.
Set the length of a ticket in words and the model's token limit. English averages about 1.3 tokens per word.
Blind spot: the model never sees the last 56% of this ticket
Three questions. No score is saved anywhere — this is just you against the material.
Working with Hugging Face grows in four levels: using pipelines, controlling tokenizers and models, running them efficiently, and operating them in production.
At the basic level you can run a pretrained model.
pipeline("sentiment-analysis"), pipeline("summarization"), pipeline("feature-extraction").~/.cache/huggingface.Where it breaks: using a model whose licence does not allow your use.
Try it: Basic
Where do you find whether a Hub model may be used commercially?
Now do it: Read the licence and evaluation sections of a model you use.
At the intermediate level you control the steps.
AutoTokenizer, AutoModelFor..., id2label.padding, truncation, max_length, return_tensors="pt"; the attention mask.Try it: Intermediate
Why must you use the tokenizer that came with the model?
Now do it: Tokenize one sentence with two different tokenizers and compare the IDs.
At the advanced level inference is fast and fits the hardware.
torch.inference_mode(); bfloat16.device_map="auto"; 8-bit and 4-bit quantisation; Optimum and ONNX Runtime exports.Try it: Advanced
Throughput is low and the GPU is mostly idle when classifying one text per request. What helps most?
Now do it: Measure throughput at batch sizes 1 and 32.
At the master level models are versioned dependencies.
Trade-off: mirroring models internally makes deploys reliable and adds storage and a process for updates; pulling from the Hub is simple and makes production depend on someone else's repository.
Try it: Master
What should run before upgrading a model revision or the transformers library?
Now do it: Build a 200-example evaluation set for one model you use.
Classify text with a pinned model, measure truncation, and chunk long inputs. Install with pip install transformers torch.
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
NAME = "distilbert-base-uncased-finetuned-sst-2-english"
REV = "main" # in production: the exact commit sha you evaluated
tok = AutoTokenizer.from_pretrained(NAME, revision=REV)
model = AutoModelForSequenceClassification.from_pretrained(NAME, revision=REV).eval()
labels = model.config.id2label # never hard-code
texts = ["The new release is great.", "Login keeps failing. " * 300]
lengths = [len(tok(t)["input_ids"]) for t in texts]
print("tokens:", lengths, "over 512:", sum(n > 512 for n in lengths))
def classify(text, window=510, stride=384):
ids = tok(text, add_special_tokens=False)["input_ids"]
chunks = [ids[i:i + window] for i in range(0, max(len(ids) - window, 0) + 1, stride)] or [ids]
batch = tok.pad({"input_ids": [[tok.cls_token_id] + c + [tok.sep_token_id] for c in chunks]}, return_tensors="pt")
with torch.inference_mode():
probs = model(**batch).logits.softmax(-1).mean(0) # average over chunks
i = int(probs.argmax())
return labels[i], round(float(probs[i]), 3), len(chunks)
for t in texts:
print(classify(t))
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A ticket router got worse without a single code change.
Model files are baked into images by commit sha, HF_HUB_OFFLINE=1 is set in production, labels come from model.config, and a 300-ticket evaluation runs on every model change.
How text becomes tokens and tokens become model outputs. These examples build a tokenizer and a tiny randomly initialised model on your machine, so nothing is downloaded; with a real model you change one line to from_pretrained("name"). Each example is a whole program: save it under the name in its first line, run it with python3, and you should see exactly the output below it.
Before you start: These examples need transformers tokenizers torch: make a virtual environment and install them with python3 -m venv .venv && . .venv/bin/activate && pip install transformers tokenizers torch. Versions differ in small ways, so a number in the last decimal place may not match yours.
Byte-pair encoding learns frequent pieces of words from text; common words become one token, rare ones split.
# example_01.py
from tokenizers import Tokenizer, models, trainers, pre_tokenizers
corpus = ["deploy the service", "deploy failed", "the service restarted", "rollback the deploy"] * 50
tok = Tokenizer(models.BPE(unk_token="[UNK]"))
tok.pre_tokenizer = pre_tokenizers.Whitespace()
tok.train_from_iterator(corpus, trainers.BpeTrainer(vocab_size=60, special_tokens=["[UNK]", "[PAD]"]))
enc = tok.encode("deploy the rollback")
print(enc.tokens)
print(enc.ids)
print(tok.encode("kubernetes").tokens)
$ python3 example_01.py ['deploy', 'the', 'rollback'] [25, 23, 49] ['k', '[UNK]', 'b', 'er', '[UNK]', 'e', 't', 'es']
Count tokens before you send text to a model: limits and prices are per token, not per character.
# example_02.py
from tokenizers import Tokenizer, models, trainers, pre_tokenizers
tok = Tokenizer(models.BPE(unk_token="[UNK]"))
tok.pre_tokenizer = pre_tokenizers.Whitespace()
tok.train_from_iterator(["error in service api", "error in service web", "timeout"] * 30, trainers.BpeTrainer(vocab_size=40, special_tokens=["[UNK]"]))
for text in ["error in service api", "service api error error error", "unexpected"]:
print(f"{len(text):2d} chars -> {len(tok.encode(text).ids):2d} tokens: {text}")
$ python3 example_02.py 20 chars -> 4 tokens: error in service api 29 chars -> 5 tokens: service api error error error 10 chars -> 10 tokens: unexpected
A batch needs equal lengths: short inputs get padding, and the attention mask tells the model to ignore it.
# example_03.py
from tokenizers import Tokenizer, models, trainers, pre_tokenizers
tok = Tokenizer(models.WordLevel(unk_token="[UNK]"))
tok.pre_tokenizer = pre_tokenizers.Whitespace()
tok.train_from_iterator(["the api is down", "web ok"], trainers.WordLevelTrainer(special_tokens=["[PAD]", "[UNK]"]))
tok.enable_padding(pad_id=0, pad_token="[PAD]")
for e in tok.encode_batch(["the api is down", "web ok"]):
print(e.tokens, e.attention_mask)
$ python3 example_03.py ['the', 'api', 'is', 'down'] [1, 1, 1, 1] ['web', 'ok', '[PAD]', '[PAD]'] [1, 1, 0, 0]
Make a GPT-2 shaped model from a config, with random weights: same code path as a real one, small enough to run anywhere.
# example_04.py import torch from transformers import GPT2Config, GPT2LMHeadModel torch.manual_seed(0) cfg = GPT2Config(vocab_size=100, n_positions=32, n_embd=32, n_layer=2, n_head=2) model = GPT2LMHeadModel(cfg) print(sum(p.numel() for p in model.parameters()), "parameters") ids = torch.tensor([[5, 17, 42, 8]]) out = model(ids) print(out.logits.shape, "= batch x tokens x vocabulary")
$ python3 example_04.py 29696 parameters torch.Size([1, 4, 100]) = batch x tokens x vocabulary
The model scores every token in the vocabulary; softmax turns scores into probabilities; greedy decoding picks the highest.
# example_05.py
import torch
logits = torch.tensor([2.0, 1.0, 0.1, -1.0])
vocab = ["deploy", "rollback", "wait", "panic"]
p = torch.softmax(logits, dim=-1)
print([f"{w}={x:.3f}" for w, x in zip(vocab, p.tolist())])
print("greedy:", vocab[int(p.argmax())])
for t in (0.5, 2.0):
pt = torch.softmax(logits / t, dim=-1)
print(f"temperature {t}: top prob {pt.max().item():.3f}")
$ python3 example_05.py ['deploy=0.638', 'rollback=0.235', 'wait=0.095', 'panic=0.032'] greedy: deploy temperature 0.5: top prob 0.862 temperature 2.0: top prob 0.451
generate runs the decode loop for you; with random weights the tokens are nonsense, but the mechanics are real.
# example_06.py import torch from transformers import GPT2Config, GPT2LMHeadModel torch.manual_seed(0) model = GPT2LMHeadModel(GPT2Config(vocab_size=50, n_positions=32, n_embd=32, n_layer=2, n_head=2)).eval() out = model.generate(torch.tensor([[1, 2, 3]]), max_new_tokens=5, do_sample=False, pad_token_id=0) print(out.tolist(), "-> 3 prompt tokens + 5 new ones")
$ python3 example_06.py [[1, 2, 3, 3, 3, 3, 3, 3]] -> 3 prompt tokens + 5 new ones
Average a model's last hidden states (ignoring padding) to get one vector per text: the input to semantic search.
# example_07.py
import torch
from transformers import BertConfig, BertModel
torch.manual_seed(0)
m = BertModel(BertConfig(vocab_size=100, hidden_size=16, num_hidden_layers=1, num_attention_heads=2, intermediate_size=32)).eval()
ids = torch.tensor([[5, 6, 7, 0], [5, 6, 0, 0]])
mask = (ids != 0).long()
with torch.no_grad():
h = m(input_ids=ids, attention_mask=mask).last_hidden_state
emb = (h * mask.unsqueeze(-1)).sum(1) / mask.sum(1, keepdim=True)
print(h.shape, emb.shape)
$ python3 example_07.py torch.Size([2, 4, 16]) torch.Size([2, 16])
Weights x bytes per weight is the memory just to load a model: why 7B models need quantisation on small GPUs.
# example_08.py
for name, params in [("tiny", 1.2e5), ("7B", 7e9), ("70B", 70e9)]:
row = [f"{name:>5}"]
for dtype, nbytes in [("fp32", 4), ("bf16", 2), ("int8", 1), ("int4", 0.5)]:
row.append(f"{dtype} {params * nbytes / 2**30:8.2f} GiB")
print(" ".join(row))
$ python3 example_08.py tiny fp32 0.00 GiB bf16 0.00 GiB int8 0.00 GiB int4 0.00 GiB 7B fp32 26.08 GiB bf16 13.04 GiB int8 6.52 GiB int4 3.26 GiB 70B fp32 260.77 GiB bf16 130.39 GiB int8 65.19 GiB int4 32.60 GiB
Write each one from scratch before you open the solution. The output under each solution is what it really prints.
Train a WordLevel tokenizer on ["start api", "stop api", "start web"] and print the ids for "start web".
# task_1.py
from tokenizers import Tokenizer, models, trainers, pre_tokenizers
t = Tokenizer(models.WordLevel(unk_token="[UNK]"))
t.pre_tokenizer = pre_tokenizers.Whitespace()
t.train_from_iterator(["start api", "stop api", "start web"], trainers.WordLevelTrainer(special_tokens=["[UNK]"]))
print(t.encode("start web").tokens, len(t.get_vocab()))$ python3 task_1.py ['start', 'web'] 5
Apply softmax to [1.0, 2.0, 3.0] with torch and print the probabilities rounded to 3 decimals and their sum.
# task_2.py import torch p = torch.softmax(torch.tensor([1.0, 2.0, 3.0]), dim=0) print([round(x, 3) for x in p.tolist()], round(p.sum().item(), 3))
$ python3 task_2.py [0.09, 0.245, 0.665] 1.0
Build a GPT-2 config with 4 layers, 64-dim embeddings, 4 heads, vocabulary 200, and print the model's parameter count.
# task_3.py from transformers import GPT2Config, GPT2LMHeadModel m = GPT2LMHeadModel(GPT2Config(vocab_size=200, n_positions=64, n_embd=64, n_layer=4, n_head=4)) print(sum(p.numel() for p in m.parameters()))
$ python3 task_3.py 216960
How many GiB do the weights of a 13B-parameter model take in bf16 and in int4?
# task_4.py p = 13e9 print(round(p * 2 / 2**30, 1), round(p * 0.5 / 2**30, 1))
$ python3 task_4.py 24.2 6.1
You need Python 3 on Linux, macOS, or WSL on Windows (run wsl --install in PowerShell once); check with python3 --version. The terminal is only for setting Python up and running it and its tools: the Python itself goes in .py files, in part 2 and in "Python, example by example" above.
Before you start: A virtual environment: python3 -m venv ~/py-lab && . ~/py-lab/bin/activate. Then pip install transformers torch for the commands (they download a small model).
Type each one, read what it prints, and compare it with the note above it.
Make a folder for this lesson with its own virtual environment, and install what the lesson needs into it. Every command after this runs inside it; deactivate leaves it, and source .venv/bin/activate brings it back.
mkdir -p ~/labs/hugging-face-transformers-and-tokenizers && cd ~/labs/hugging-face-transformers-and-tokenizers python3 -m venv .venv || echo "No venv module: on Debian or Ubuntu run sudo apt install -y python3-venv and try again" source .venv/bin/activate && python --version pip install transformers torch
Tokens are not words: count them for a real sentence (this downloads a small tokenizer the first time).
python -c "from transformers import AutoTokenizer; t = AutoTokenizer.from_pretrained('distilbert-base-uncased'); s = 'Login fails with error E1043 after password reset.'; ids = t(s)['input_ids']; print(len(s.split()), 'words,', len(ids), 'tokens:', t.convert_ids_to_tokens(ids))"truncation=True cuts silently at the model's limit.
python -c "from transformers import AutoTokenizer; t = AutoTokenizer.from_pretrained('distilbert-base-uncased'); s = 'word ' * 2000; print(len(t(s)['input_ids']), len(t(s, truncation=True)['input_ids']))" 2>/dev/nullDownloaded models live in a cache folder: how big it is, and what is in it.
du -sh ~/.cache/huggingface 2>/dev/null; ls ~/.cache/huggingface/hub 2>/dev/null | head
Work offline once the model is cached: no network calls, and an error instead of a silent download.
HF_HUB_OFFLINE=1 python -c "from transformers import AutoTokenizer; print(AutoTokenizer.from_pretrained('distilbert-base-uncased').vocab_size)"truncation_audit.pyThis program audits truncation before deploying a 512-token classifier: it estimates token counts for a batch of tickets and reports how many would be cut and how much text the model would never see. Save it as truncation_audit.py in the lesson folder, then run it.
# truncation_audit.py
import random
random.seed(5)
LIMIT, TOKENS_PER_WORD = 512, 1.3
lengths = [int(random.lognormvariate(5.4, 0.7)) for _ in range(1000)] # words per ticket
tokens = [round(w * TOKENS_PER_WORD) + 2 for w in lengths] # + [CLS] and [SEP]
over = [t for t in tokens if t > LIMIT]
lost = sum(t - LIMIT for t in over)
print(f"{len(tokens)} tickets, median {sorted(tokens)[len(tokens) // 2]} tokens, longest {max(tokens):,}")
print(f"over the {LIMIT}-token limit: {len(over)} ({len(over) / len(tokens):.0%}); tokens never seen: {lost:,} ({lost / sum(tokens):.0%} of all text)")
chunks = sum(-(-t // (LIMIT - 64)) for t in over)
print(f"chunking with 64-token overlap instead: {chunks} chunks for those tickets, nothing lost")
Run it, and you should see this output:
$ python3 truncation_audit.py 1000 tickets, median 285 tokens, longest 2,958 over the 512-token limit: 224 (22%); tokens never seen: 71,150 (18% of all text) chunking with 64-token overlap instead: 537 chunks for those tickets, nothing lost
A program you keep needs a test, so you know at once when a change alters what it does. This one uses unittest, which comes with Python: it runs truncation_audit.py and checks that it exits cleanly and prints exactly the output above. Save it as test_truncation_audit.py next to the program.
# test_truncation_audit.py: checks that truncation_audit.py still prints exactly what this lesson shows.
# Run it with: python3 -m unittest -v test_truncation_audit
import subprocess
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
EXPECTED = r"""
1000 tickets, median 285 tokens, longest 2,958
over the 512-token limit: 224 (22%); tokens never seen: 71,150 (18% of all text)
chunking with 64-token overlap instead: 537 chunks for those tickets, nothing lost
""".strip("\n")
class TestTruncationAudit(unittest.TestCase):
def run_program(self):
return subprocess.run([sys.executable, str(HERE / "truncation_audit.py")], cwd=HERE,
capture_output=True, text=True, timeout=60)
def test_exits_cleanly(self):
result = self.run_program()
self.assertEqual(result.returncode, 0, result.stderr)
def test_prints_the_expected_output(self):
result = self.run_program()
self.assertEqual(result.stdout.rstrip(), EXPECTED)
if __name__ == "__main__":
unittest.main()
Run it: you should see both tests end in ok, then OK. Then change one value in the program, run it again, and read how the failure shows you the difference. pytest runs the same file unchanged, if you prefer it.
python3 -m unittest -v test_truncation_audit
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
head, du, mkdir, echo, ls, cd, Pipes, Redirection, If...Else, Variables.Deploy an embedding model for semantic search over 2 million internal documents, re-embedding 50,000 changed documents nightly.
Which model, and how do you choose? How long are documents in tokens, and what happens to long ones? How fast must nightly embedding be, and on what hardware? How do you make sure queries and documents always use the same model version?
Say documents average 900 tokens with a long tail to 20,000, a 512-token model limit, a 2-hour nightly window, and one GPU.
Two or three candidate models evaluated on 500 real query-document pairs; documents chunked to 512 tokens with overlap; batched bfloat16 inference sorted by length; the model revision pinned and stored with every embedding; queries refused if their model revision differs from the index; files baked into the image, offline mode on.
Smaller chunks retrieve more precisely and create more vectors to store and search. Changing the embedding model means re-embedding everything, so pin it and plan upgrades as migrations.