🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

NLP Fundamentals: Tokens, Embeddings and Attention

🟢 Free Lesson

NLP Fundamentals

Prerequisites

  • !Python lists, NumPy arrays and matrix multiplication
  • !Probability basics: softmax and expectation
  • !What a language model predicts at each step

What You'll Learn

  • 1Explain why vocabulary size is a three-way trade-off between sequence length and out-of-vocabulary words
  • 2Implement byte-pair encoding and verify a tokenization round-trip
  • 3Read an embedding space geometrically and say what cosine similarity does and does not mean
  • 4Derive scaled dot-product attention and explain the role of the scaling factor

What a model actually sees when it reads

Nothing in a transformer touches letters. A pipeline converts a string into integer ids, the ids select rows from an embedding matrix, and those rows are mixed by attention until every position carries a representation of its context. Three conversions happen in sequence, and each one loses information that later stages must recover or work around.

The first conversion is segmentation: deciding where one token ends and the next begins. The second is representation: turning each id into a dense vector whose direction encodes something about meaning. The third is contextualisation: letting every position re-weight every other position so that "bank" near "river" and "bank" near "interest" stop sharing a vector. Understanding modern NLP is largely understanding what each conversion can and cannot preserve.

Tokenization and the vocabulary trade-off

Vocabulary design is a three-way tension. A large word-level vocabulary keeps sequences short but leaves rare words as unknowns; a character-level vocabulary never has unknowns but produces sequences so long that attention cost grows quadratically. Subword methods sit in the middle, and the choice shows up directly in your bill and your context window.

SchemeTypical vocabSequence lengthUnknown wordsNotes
Word-level50k–250kShortestFrequent for rare namesNeeds heavy normalization
Character-level256–10003–5× longerNeverWeak per-step semantics
Byte-pair (BPE)32k–100kModerateRareLearned by merge frequency
WordPiece30k–110kModerateRareMaximize likelihood, not frequency
Unigram32k–64kModerateRareProbabilistic, supports sampling
Byte fallback256 addedModerateNoneSplits anything into bytes

The arithmetic matters in practice. If a 4,000-character document averages 750 tokens under BPE but 3,200 tokens at character level, attention cost — which grows with the square of sequence length — rises by roughly 18×, while the API price for that document rises about 4×. Tokenization is an economic decision as much as a modelling one.

Building a byte-pair encoder you can step through

BPE learns merges by repeatedly joining the most frequent pair of adjacent symbols. Training is simple enough to read in one sitting, which is exactly why it is worth implementing once.

python
from collections import Counter, defaultdict


def train_bpe(corpus: list[str], num_merges: int, vocab_size: int = 8000):
    words = [tuple(w) for w in corpus]
    # Seed the alphabet so no character is ever unrepresentable.
    vocab = set(ch for w in words for ch in w)
    merges = []

    for _ in range(num_merges):
        pair_counts = Counter()
        for w in words:
            pair_counts.update(zip(w, w[1:]))
        if not pair_counts or len(vocab) >= vocab_size:
            break
        best = max(pair_counts, key=pair_counts.get)
        merges.append(best)
        merged = "".join(best)
        new_words = []
        for w in words:
            out, i = [], 0
            while i < len(w):
                if i + 1 < len(w) and (w[i], w[i + 1]) == best:
                    out.append(merged)
                    i += 2
                else:
                    out.append(w[i])
                    i += 1
            new_words.append(tuple(out))
        words = new_words
        vocab.add(merged)
    return merges, vocab


def encode(text: str, merges: list[tuple]) -> list[str]:
    tokens = list(text.lower())
    for a, b in merges:
        out, i = [], 0
        joined = a + b
        while i < len(tokens):
            if i + 1 < len(tokens) and tokens[i] == a and tokens[i + 1] == b:
                out.append(joined)
                i += 2
            else:
                out.append(tokens[i])
                i += 1
        tokens = out
    return tokens


def roundtrip(text: str, merges: list[tuple]) -> bool:
    """A tokenizer is only usable if decode(encode(x)) reproduces x."""
    return "".join(encode(text, merges)) == text.lower()

The round-trip test is the check that matters. Tokenizers that drop whitespace, normalise Unicode, or silently map a rare glyph to a placeholder break downstream tasks in ways that look like model failures. Test the encoder, not just the model.

Embeddings: geometry you can compute with

Once a token is an id, it becomes a row in a matrix of learned vectors. In a static embedding such as Word2Vec each id has exactly one vector, so every sense of a word shares a direction. In a contextual model the row is only a starting point — attention rewrites it — which is why one model can place the same token in two different places depending on the sentence.

Similarity is almost always cosine: the angle, not the length, because magnitude tends to track frequency rather than meaning.

python
import numpy as np


def cosine(a: np.ndarray, b: np.ndarray) -> float:
    return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))


def analogy(emb: dict[str, np.ndarray], a: str, b: str, c: str, topk: int = 3):
    """Solve a - b + c, excluding the words already used."""
    guess = emb[a] - emb[b] + emb[c]
    used = {a, b, c}
    scored = [(w, cosine(guess, v)) for w, v in emb.items() if w not in used]
    return sorted(scored, key=lambda kv: kv[1], reverse=True)[:topk]


def soft_nearest(tokens: list[str], emb: dict[str, np.ndarray],
                 query: str, temperature: float = 0.2) -> list[tuple[str, float]]:
    scores = np.array([cosine(emb[query], emb[t]) for t in tokens])
    exp = np.exp(scores / temperature)
    probs = exp / exp.sum()
    return sorted(zip(tokens, probs.tolist()), key=lambda kv: kv[1], reverse=True)

Two cautions. A cosine of 0.8 between two product reviews says they sit in a similar region of topic space, not that they agree — sentiment and topic are different axes. And arithmetic analogies flatter the method: they work well for frequent, well-isolated relations and degrade badly for anything noisy. Treat them as an inspection tool, not a benchmark.

Attention: how one token gathers context

Attention answers a single question for each position: how much should every other position influence me? Stacked as three projections — query, key, value — the answer becomes a softmax over dot products.

python
import numpy as np


def scaled_dot_product_attention(Q, K, V, mask=None):
    """Q, K, V: (seq, dim). Returns output and the weight matrix."""
    scores = Q @ K.T / np.sqrt(Q.shape[-1])
    if mask is not None:
        scores = np.where(mask, scores, -1e9)
    scores -= scores.max(axis=-1, keepdims=True)      # numerically safe softmax
    exp = np.exp(scores)
    weights = exp / exp.sum(axis=-1, keepdims=True)
    return weights @ V, weights


# Causal mask: position i may only look at positions <= i.
seq = 6
causal = np.tril(np.ones((seq, seq), dtype=bool))
rng = np.random.default_rng(0)
x = rng.normal(size=(seq, 16))
out, w = scaled_dot_product_attention(x, x, x, mask=causal)
assert np.allclose(w[np.triu_indices(seq, k=1)], 0)  # no peeking forward

The division by the square root of the key dimension is not cosmetic. Dot products of random vectors grow with dimension, pushing softmax into saturation where gradients vanish; scaling keeps the logits in a range where the model can still learn to be uncertain. The causal mask is what makes the whole system autoregressive — without it, every position would see the answer it is supposed to predict.

Stacking blocks without losing the signal

A transformer block wraps attention and a small feed-forward network with residual connections and layer normalisation, so the input to each sub-layer is added back to its output. That identity path is why networks hundreds of layers deep remain trainable: gradients have a highway to the bottom that does not pass through every matrix. The feed-forward layer is where per-token processing happens — attention only mixes positions, while the two-matrix MLP transforms each position independently, typically expanding the dimension fourfold before compressing it back.

Rough sizing guides the intuition: a block with model dimension 768 and feed-forward width 3072 holds roughly 7 million parameters in the MLP and 2.4 million in attention projections. Most of a transformer's capacity lives in the MLP, which is one reason low-rank adaptation methods target the attention and MLP weights differently.

ℹ️Why depth beats width in practice

Equal parameter counts favour deeper stacks over wider ones on language tasks, because each additional layer adds another round of context mixing. Width buys parallel representational capacity; depth buys sequential reasoning steps.

The objective decides what the vectors know

Representations are shaped by what the model was forced to predict during training. A masked language model sees both sides of a hole and reconstructs the missing token, so its internal states specialize in understanding — which is why encoders of that kind win at classification and retrieval. A causal model predicts the next token given only the left context, so it specializes in production — fluent, but with hidden states that are optimised for continuation rather than analysis.

Two practical consequences follow. Feed a causal model a sentence and ask for its embedding, and you get a vector dominated by the final tokens, because those were the ones the model had to reason about most recently; pooling strategies partly repair this but never fully. Conversely, use an encoder for free-form generation and you discover it has no mechanism for deciding what to say next. Choosing a pretraining objective is therefore choosing which half of the NLP toolkit you get: understanding tasks or generation tasks, rarely both from one checkpoint.

Checking a pipeline before trusting its output

NLP systems fail in quiet ways, so test the layers separately. Verify the tokenizer round-trips on whitespace, punctuation, emoji, and non-Latin scripts. Check that embedding lookups handle unseen ids without crashing. Assert attention weights sum to one per row and respect the mask. For downstream tasks, prefer metrics that match the failure you care about: token accuracy hides a single wrong entity, sequence accuracy exposes it; BLEU rewards fluent phrasing even when the fact is wrong, so pair it with an entailment or faithfulness check. A pipeline with layer-level assertions produces errors you can locate; a pipeline with only end-to-end accuracy produces mysteries.

Common Mistakes

Shipping a tokenizer without a decode round-trip test

Fix: Assert encode-then-decode reproduces the original string across scripts, whitespace and punctuation

Reading cosine similarity as agreement rather than topical closeness

Fix: Separate axes: measure sentiment or stance with a classifier, use embeddings for candidate retrieval

Applying causal attention in an encoder that should see both directions

Fix: Match the mask to the task: bidirectional for classification, causal for generation

Ignoring the scaling factor because it looks like a constant

Fix: Keep the square-root-of-dimension division; removing it saturates softmax and stalls training

Best Practices

  • Profile token counts on real documents before choosing a vocabulary size — context window and cost both follow from it
  • Keep one shared tokenizer implementation across training, serving and evaluation
  • Inspect attention weights on a handful of hand-checked examples after any architecture change
  • Choose evaluation metrics that fail when the specific bug you fear occurs

Key Takeaways

  • NLP pipelines make three lossy conversions — segmentation, representation, contextualisation — and each needs its own test
  • Vocabulary size trades sequence length against unknown-word risk, with direct effects on price and context limits
  • BPE is learnable in a few dozen lines; a round-trip assertion is the property that makes any tokenizer usable
  • Cosine similarity measures angle, not agreement, and contextual models beat static ones because the same token moves with its context
  • Scaled dot-product attention needs its scaling factor and its mask — one keeps gradients alive, the other keeps the task honest
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement