Module 5 of 6 · 50 minutes

Transformers and LLMs for NLP

LLMs can do many NLP tasks with no training data. This module shows how to use them for classic tasks — and when a cheaper model is the better choice.

By · Last updated

Learning objectives

  • Outline the evolution from bag of words to transformers
  • Explain attention in plain language
  • Run zero- and few-shot classification
  • Choose between classic NLP and LLMs
  • Estimate the token cost of an LLM task before running it
  • Describe what small language models offer
Setup: the data and models from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport random
import re
import numpy as np
import pandas as pd

random.seed(7)
templates = {
    "delivery": ["My parcel arrived {d} days late and the box was crushed",
                 "Delivery took {d} days and the courier left it in the rain",
                 "Still waiting for my order after {d} days, no update",
                 "The tracking link never updated and delivery was {d} days late"],
    "product":  ["The {p} broke after a week",
                 "Love the {p}, great quality and well made",
                 "The {p} is much smaller than the photos suggest",
                 "Excellent {p}, works perfectly"],
    "billing":  ["I was charged twice for order {o}",
                 "Refund for order {o} still not received",
                 "The discount code did not apply at checkout",
                 "Invoice for order {o} shows the wrong amount"],
}
products = ["chopping board", "kettle", "desk lamp", "backpack", "water bottle"]
rows = []
for i in range(400):
    cat = random.choice(list(templates))
    msg = random.choice(templates[cat]).format(
        d=random.randint(2, 9), p=random.choice(products), o="GFY-%05d" % random.randint(10000, 99999))
    label = cat if random.random() > 0.08 else random.choice(list(templates))  # ~8% noisy labels
    rows.append({"text": msg, "category": label})
messages = pd.DataFrame(rows)

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression

X_train, X_test, y_train, y_test = train_test_split(
    messages["text"], messages["category"], test_size=0.25, random_state=0, stratify=messages["category"])
clf = make_pipeline(TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True),
                    LogisticRegression(max_iter=1000))
clf.fit(X_train, y_train)

import anthropic
client = anthropic.Anthropic()
MODEL = "YOUR-MODEL-NAME"

5.1 From word counts to transformers

NLP moved through three broad stages: rules and counts (regex, bag of words, TF-IDF), learned representations (word embeddings and recurrent networks that read text in order) and, since 2017, transformers — the architecture behind today's LLMs. The background is covered in How AI and LLMs Work; here we focus on what it means for practical NLP.

Practice mode on this page

Calling a real AI model needs a secret API key, and a key must never sit in a web page. So the cells that call a model on this page talk to a small pretend model built into the page. The code is what you'd write for the real thing, but the replies come from simple rules, not real AI. To use a real model, copy the code into a notebook such as Colab and add your own key (see Python for AI, Module 5).

5.2 Attention in one idea

A transformer's key mechanism, attention, lets every token look at every other token and decide which ones matter for its meaning. In "The parcel didn't fit in the box because it was too big", attention helps the model link "it" to "parcel". Because attention handles context directly and runs in parallel, transformers can be trained on enormous amounts of text.

Theparceldidn'tfitintheboxbecauseitwastoobigstrong linkwhat does “it” refer to?
Attention lets the token “it” weigh every other token; the strongest link is to “parcel”. This is how transformers use context.

5.3 Tokens, again — and why they cost money

LLMs read subword tokens, not words: common words are one token, rare words and names split into several. API pricing, speed limits and context windows are all measured in tokens, so long inputs cost more and run slower. Non-English text and code often use more tokens per word.

You can estimate cost before you spend anything. A common rule of thumb for English is about four characters per token:

Python · a back-of-envelope cost estimatedef estimate_tokens(text):
    return max(1, round(len(text) / 4))          # rule of thumb for English; real tokenisers differ

instructions = 300                               # tokens of prompt and examples sent with every message
per_message = messages["text"].map(estimate_tokens).mean() + instructions
reply_tokens = 5                                 # a one-word answer

PRICE_IN, PRICE_OUT = 1.00, 5.00                 # EXAMPLE prices in £ per million tokens — check your provider
for volume in [1_000, 100_000, 10_000_000]:
    cost = volume * (per_message * PRICE_IN + reply_tokens * PRICE_OUT) / 1_000_000
    print(f"{volume:>10,} messages: about £{cost:,.2f}")

Two things stand out. The instructions you repeat with every message cost far more than the messages themselves, so a short prompt matters at volume (providers also offer cheaper rates for repeated prompt text and for batch jobs that can wait). And the cost is strictly per message: ten million messages cost ten thousand times as much as a thousand, where a classic model's cost is close to zero either way.

5.4 Zero-shot and few-shot classification

An LLM can classify text with no training data (zero-shot) or with a handful of examples in the prompt (few-shot) — ideal when you have no labels or categories change often.

Python · few-shot classification with an LLM (practice mode on this page)EXAMPLES = """Message: The kettle stopped working after two days -> product
Message: I was billed twice this month -> billing
Message: Courier left my parcel in the rain -> delivery"""

def llm_classify(message):
    prompt = (f"Classify the customer message as delivery, product or billing. "
              f"Reply with one word.\n\n{EXAMPLES}\nMessage: {message} ->")
    reply = client.messages.create(model=MODEL, max_tokens=5,
                                   messages=[{"role": "user", "content": prompt}])
    return reply.content[0].text.strip().lower()

sample = X_test.head(20)
llm_preds = [llm_classify(m) for m in sample]
print(llm_preds[:5])
print("Agreement with labels:", np.mean(np.array(llm_preds) == y_test.head(20).values).round(2))

Always measure an LLM classifier on labelled examples exactly as you would a classic model — prompts that look fine on three messages can fail on the three-hundredth.

5.5 Classic NLP, LLM, or both?

TF-IDF + classic modelLLM (prompted)
Labelled data neededHundreds or moreNone to a few examples
Cost per messageAlmost zeroPaid per token
SpeedThousands per secondSeconds per call (batching helps)
Handles nuance, new categories, other languagesPoorlyWell
PredictabilitySame input, same outputCan vary; needs validation

A common pattern: use an LLM to label a few thousand examples, have humans check a sample, then train a cheap classic model on those labels for high-volume use — and send low-confidence cases back to the LLM or a person.

5.6 Compare them on the same test

The only fair comparison uses the same messages and the same labels for both. Here both classifiers face 60 test messages, plus two that are unlike anything in the training data:

Python · classic model and LLM, same test setsubset_text, subset_labels = X_test.head(60), y_test.head(60)
classic_preds = clf.predict(subset_text)
llm_preds = np.array([llm_classify(m) for m in subset_text])

print("Classic model accuracy:", (classic_preds == subset_labels.values).mean().round(2))
print("LLM accuracy:          ", (llm_preds == subset_labels.values).mean().round(2))
print("They agree with each other on", (classic_preds == llm_preds).mean().round(2), "of messages")

for text in ["Money taken from my account two times", "Der Wasserkocher ist kaputt"]:
    print(f"\n{text}\n  classic: {clf.predict([text])[0]}  ({clf.predict_proba([text]).max():.2f} confident)   LLM: {llm_classify(text)}")

On the test set the two score about the same, and where they disagree with the label they usually agree with each other: those are the noisy labels again. The two unusual messages are more revealing. Neither shares vocabulary with the training data, so the classic model is guessing, and its low confidence says so. (On this page the "LLM" is the practice model, which only knows English keywords, so it struggles too. A real LLM would read "two times" as a double charge and the German sentence as a broken kettle without difficulty — that flexibility is what you pay for.)

5.7 Small language models

The choice is no longer just "classic model or giant LLM". Small language models — language models compact enough to run on a laptop, a phone or a modest server — now handle classification, extraction and short summaries well. They sit between the two columns of the table in 5.5:

  • Privacy — text never leaves your own hardware, which can settle a data-protection question before it starts.
  • Cost and speed — no per-token bill, and no network delay.
  • Flexibility — they follow instructions and examples like a large model, so there is no training set to build.
  • Limits — weaker on long documents, subtle reasoning and less common languages; they need testing on your task like anything else.

A sensible order of questions for any text task: can a rule or a list do it? If not, can a classic model trained on labels I have? If not, can a small language model? Reach for the largest model when the task needs it, not by default.

Exercise: route by confidence

Using clf, write route(messages, threshold=0.7) that returns a DataFrame with each message's predicted category and confidence, plus a column needs_review that is True when confidence is below the threshold. What share of the test set would go to review?

Your turn# Write your code here, then press Run
Show a solution
def route(texts, threshold=0.7):
    probs = clf.predict_proba(texts)
    out = pd.DataFrame({"text": list(texts),
                        "predicted": clf.classes_[probs.argmax(axis=1)],
                        "confidence": probs.max(axis=1).round(2)})
    out["needs_review"] = out["confidence"] < threshold
    return out

r = route(X_test)
print(r["needs_review"].mean().round(2), "of messages need review")
print(r.sort_values("confidence").head())
# None here: the test messages follow the same patterns as the training data.
# Unfamiliar wording is what lowers confidence:
print(route(["It stopped working", "Money taken from my account two times"]))
Exercise: classic first, LLM for the hard ones

Build the hybrid from 5.5: classify every message in incoming with clf; where its confidence is below 0.6, use llm_classify instead. Print each message with the final category and which model decided. How many LLM calls did you save?

Your turnincoming = ["My parcel arrived 5 days late and the box was crushed",
            "I was charged twice for order GFY-33120",
            "Excellent backpack, works perfectly",
            "Money taken from my account two times",
            "It stopped working"]

# Write your code here, then press Run
Show a solution
incoming = ["My parcel arrived 5 days late and the box was crushed",
            "I was charged twice for order GFY-33120",
            "Excellent backpack, works perfectly",
            "Money taken from my account two times",
            "It stopped working"]

calls = 0
for text in incoming:
    probs = clf.predict_proba([text])[0]
    if probs.max() >= 0.6:
        label, who = clf.classes_[probs.argmax()], "classic"
    else:
        label, who = llm_classify(text), "LLM"
        calls += 1
    print(f"{who:8} {label:9} {text}")
print("LLM calls:", calls, "of", len(incoming))
# The cheap model handles the routine messages; the expensive one is kept for the unclear ones.
LLM labels asampleHumans checklabelsTrain cheapclassifierScore allmessagesLow confidence?→ LLM / person
A common hybrid: an LLM provides labels, people verify them, and a classic model handles volume.

Key takeaways

  • Transformers use attention to model context.
  • LLM cost, speed and limits are measured in tokens.
  • Few-shot prompts classify without training data — but measure them.
  • Classic models are cheap and predictable; LLMs handle nuance.
  • Combine them: LLM labels, classic model at scale, humans for edge cases.
  • Instructions repeated with every message often cost more than the messages; estimate before you run.
  • Small language models run on your own hardware: private and cheap, with limits to test.