From Raw Text to Tokens: Subword Tokenizers and Modern LLM Blocks
Machine LearningModel answerLast updated
Describe how subword tokenizers such as SentencePiece work, what a Transformer block contains, and why recent LLMs replaced parts of the original design with RMSNorm, RoPE, and MoE.
You are asked to walk through the path from raw text to a modern large language model, covering both the input side and the network itself.
Answer the following:
- SentencePiece. What is it, and how does it work? Describe what makes it different from tokenizers that split on whitespace first, and name the training algorithms it supports.
- Tokenizer choices. Which tokenizers do BERT and typical Transformer-based language models use, and what motivates those choices? Discuss vocabulary size as a trade-off.
- Block anatomy. List the main components inside a Transformer block and explain the role of each.
- Architecture comparison. Contrast the original 2017 Transformer with LLaMA-style and Qwen-style decoder-only models. Cover normalization, positional information, feed-forward design, attention variants, and sparsity.
- Design trade-offs. For Mixture-of-Experts (MoE), RMSNorm, and Rotary Position Embeddings (RoPE), explain the benefit and the cost of each.
A strong answer is structured, uses concrete details (formulas, typical vocabulary sizes, example models), and states a trade-off with every design choice.
Hints
Hint 1
Start from the problem each component solves: word-level vocabularies have out-of-vocabulary words, character-level sequences are too long, and subwords sit between the two.
Hint 2
For the block, separate what mixes information across tokens (attention) from what transforms each token independently (the feed-forward network), then cover what keeps training stable (residuals and normalization).
Hint 3
For each modern change (pre-norm, RMSNorm, RoPE, SwiGLU, grouped-query attention, MoE), state what it replaced, what it improves, and what it costs, for example compute versus memory for MoE.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The question spans the LLM pipeline: how text becomes integer IDs, what each layer computes, and why the 2017 design was modified. Good answers give a reason and a cost for every choice.
1. SentencePiece
SentencePiece is a language-agnostic subword tokenization library, not a single algorithm.
- Raw-text input. It does not require a pre-tokenization step. The input is treated as a Unicode stream, and whitespace becomes a normal symbol (
▁). Tokenization is therefore lossless: decoding the tokens reproduces the original string exactly. It also works for languages written without spaces, such as Chinese, Japanese, and Thai. - Two training algorithms.
- BPE: start from characters and repeatedly merge the most frequent adjacent pair until the target vocabulary size is reached.
- Unigram language model: start from a large candidate vocabulary, assign each piece a probability fitted with EM, and prune the pieces whose removal least reduces corpus likelihood. Repeat until the target size is reached. Encoding uses Viterbi decoding to find the most probable segmentation.
- Extras. Unicode normalization, a fixed vocabulary size chosen up front, optional byte fallback for unseen characters, and subword regularization (sampling alternative segmentations during training as augmentation).
2. Tokenizers in practice and why
| Model family | Tokenizer | Notes |
|---|---|---|
| BERT | WordPiece, about 30k | Pre-split on whitespace and punctuation, continuation pieces marked ##, merges chosen by likelihood gain |
| GPT-style | Byte-level BPE | 256-byte base alphabet, so no unknown tokens |
| LLaMA 1/2 | SentencePiece BPE, 32k | Byte fallback |
| Newer LLaMA, Qwen | Byte-level BPE, roughly 128k to 150k | Larger vocabulary for multilingual text and code |
Why subwords. Word-level vocabularies grow huge and still miss rare words. Character or byte sequences are long, and attention costs O(n²) in length. Subwords give common words a single token and break rare words into meaningful pieces.
Vocabulary-size trade-off. A larger vocabulary shortens sequences, which lowers cost per context window and speeds up generation. The price is larger embedding and output matrices, and sparse training signal for rare tokens. Byte-level designs became the default for generative models because any string is encodable.
3. Components of a Transformer block
- Multi-head self-attention. Project to Q, K, V and compute
softmax(QKᵀ/√d_k + mask)Vper head, then concatenate and project. It mixes information across positions. In decoders a causal mask blocks attention to the future. - Position-wise feed-forward network. Two linear layers with a nonlinearity, hidden size around 4d in the original. It transforms each token independently, holds about two thirds of the parameters, and acts as much of the model's capacity for stored knowledge.
- Residual connections. They keep a clean gradient path so each sublayer learns a refinement.
- Normalization. Post-norm (
x = LN(x + f(x))) was original. Pre-norm (x = x + f(LN(x))) is now standard because deep stacks train more stably with less warmup. - Dropout. Useful in small-data regimes, often turned off in large pretraining.
- Cross-attention. Only in encoder-decoder models: queries from the decoder, keys and values from the encoder.
Outside the blocks sit token embeddings, positional information, a final norm, and the output head (sometimes tied to the embeddings).
4. Vanilla vs. LLaMA vs. Qwen
| Aspect | Vanilla (2017) | LLaMA-style | Qwen-style |
|---|---|---|---|
| Layout | Encoder-decoder | Decoder-only | Decoder-only |
| Norm | Post-LN LayerNorm | Pre-norm RMSNorm | Pre-norm RMSNorm |
| Positions | Sinusoidal, added at input | RoPE applied to Q/K in every layer | RoPE, with base adjustment and scaling methods for long context |
| FFN | ReLU, 4d | SwiGLU, hidden about (8/3)d | SwiGLU |
| Attention | Multi-head | Grouped-query attention in larger/later models | Grouped-query attention; QKV bias in some versions, QK-Norm in later ones |
| Sparsity | Dense | Dense in most versions | Dense and MoE variants |
In short, LLaMA popularized the "modern recipe" of pre-RMSNorm, RoPE, SwiGLU, and GQA. Qwen follows it and adds a large multilingual vocabulary, long-context positional scaling, attention-stability tweaks, and extensive MoE use.
5. Trade-offs of the key choices
Mixture-of-Experts. The FFN is replaced with N expert FFNs; a router sends each token to its top-k experts and mixes their outputs by gate weight.
- Benefit: total parameters decouple from per-token compute. A model with hundreds of billions of parameters but only tens of billions active costs roughly the FLOPs of the smaller dense model while offering more capacity.
- Costs: all experts must live in memory; expert parallelism needs all-to-all communication; routers can collapse onto a few experts, so you need load-balancing losses or bias-based balancing and capacity limits; training can be less stable; at small batch sizes inference is memory-bandwidth bound, so the compute savings shrink; fine-tuning is trickier.
RMSNorm. y = x / sqrt(mean(x²) + ε) · g. It drops LayerNorm's mean subtraction and bias.
- Benefit: fewer operations and reductions, easier kernel fusion, and quality that matches LayerNorm in practice, suggesting re-scaling matters more than re-centering.
- Cost: a small loss of invariance to mean shifts; the gain is modest, since normalization is a small fraction of total compute.
RoPE. Each pair of query/key dimensions is rotated by an angle proportional to position, so the dot product depends on relative offset.
- Benefit: encodes relative position naturally inside attention, adds no learned position parameters, and extends to longer contexts through base changes or interpolation (NTK-style, YaRN).
- Costs: extrapolation beyond the trained length degrades without such scaling; extra per-layer computation on Q/K; high-frequency dimensions can alias at long range.
Common mistakes
- Calling SentencePiece an algorithm rather than a library that implements BPE and Unigram.
- Claiming BERT uses BPE (it uses WordPiece).
- Saying MoE reduces memory; it reduces per-token compute, not memory.
- Forgetting that the FFN, not attention, holds most parameters.
- Listing architecture changes without saying what each improves and what it costs.