The First Step Every Model Takes
Neural networks operate on numbers, not words. When you type "The beam deflection exceeds the serviceability limit" into a language model, the very first operation is tokenization — splitting that sentence into discrete pieces called tokens and assigning each token a unique integer ID from a fixed vocabulary.
The way text is split has profound consequences. A poor tokenization scheme wastes the model's limited context window on redundant or meaningless fragments. A good scheme balances vocabulary size, coverage of rare words, and computational efficiency. Getting this step right is not optional — it determines the upper bound of everything the model can do.
Tokenization is often treated as a mundane preprocessing detail, but it is anything but. The choice of tokenization algorithm directly affects model performance on rare technical terms (like "prestressed" or "geosynthetic"), multilingual text, numerical values, and code. For civil engineers who work with domain-specific vocabulary, understanding tokenization is essential for diagnosing when and why a language model struggles with engineering text.
This sub-chapter assumes familiarity with the Transformer architecture from Sub-chapter 5.3 and the GPT/BERT models from Sub-chapters 5.4 and 5.5. We will frequently reference attention mechanisms, context windows, and pre-training objectives.
Why Civil Engineers Should Care
When you paste a 200-page structural calculation into a language model and it truncates at page 40, the culprit is tokenization: your document consumed more tokens than the model's context window allows. When GPT misspells "geotechnical" as "ge" + "ot" + "echnical" and assigns confused meanings to the fragments, that is also tokenization. When a model cannot parse the number "28,000 kPa" correctly, the tokenizer likely split it into ["28", ",", "000", " k", "Pa"] — five tokens that individually carry no engineering meaning.
The Material Breakdown Analogy
Tokenization is like breaking down a composite construction material into its constituent components. Consider concrete: to a layperson, it is a single grey substance. But a civil engineer knows that concrete = cement + sand + water + coarse aggregate (+ optional admixtures). Each constituent has its own properties — particle size distribution, specific gravity, chemical reactivity — and the mix design (proportions) determines the final performance of the composite.
Similarly, a tokenizer breaks down a sentence into sub-units. Word-level tokenization is like treating each bag of pre-mixed concrete as a single item — simple but inflexible. Character-level tokenization is like decomposing everything down to individual chemical elements — maximally flexible but losing all practical structure. Subword tokenization (BPE, WordPiece) strikes the balance: cement, sand, water, aggregate. Each piece is meaningful on its own and combines to form the whole.
Embeddings are like material property vectors. In civil engineering, every material is characterised by a set of numerical properties: compressive strength, tensile strength, elastic modulus, density, thermal conductivity, Poisson's ratio, and so on. These properties form a vector that uniquely describes the material and allows engineers to compare, group, and reason about materials quantitatively.
Word embeddings work identically. Each token is mapped to a dense numerical vector (typically 256–4096 dimensions) that captures its semantic properties. Just as steel and aluminium have similar property vectors (high strength, high modulus, metallic) compared to timber (lower strength, lower modulus, organic), the embeddings for "beam" and "girder" will be close together in vector space while "beam" and "rainfall" will be far apart.
Word-Level Tokenization
The simplest tokenization strategy splits text on whitespace and punctuation. Each unique word in the training corpus gets its own vocabulary entry and integer ID:
Word-Level Example
Input: "The beam deflects under load"
Tokens: ["The", "beam", "deflects", "under", "load"]
IDs: [1, 4821, 19304, 73, 2917]
This approach is intuitive and works well for common words. But it suffers from a fatal flaw: the out-of-vocabulary (OOV) problem. Any word not seen during training — a misspelling, a rare technical term, a foreign word — is replaced with a generic <UNK> token, destroying its meaning entirely.
The Vocabulary Explosion
English alone has over a million distinct word forms when you include technical jargon, proper nouns, and morphological variants ("deflect", "deflects", "deflected", "deflecting", "deflection", "deflections"). A word-level vocabulary that covers even common engineering text would need 200,000+ entries. Each entry requires its own embedding vector, so a 200,000-word vocabulary with 768-dimensional embeddings means 153 million parameters just for the embedding table — before the model has processed a single token.
Limitations of Word-Level Tokenization
- OOV problem: Rare words like "geosynthetic" or "prestressing" may not be in the vocabulary
- Vocabulary size: Must be very large to cover morphological variants
- No subword sharing: "deflect" and "deflection" are treated as completely unrelated tokens
- Poor generalisation: Cannot handle novel word formations or compound technical terms
Character-Level Tokenization
At the opposite extreme, character-level tokenization treats every individual character (letter, digit, punctuation mark) as a separate token. The vocabulary becomes tiny — perhaps 256 entries for ASCII plus Unicode characters — and the OOV problem vanishes entirely.
Character-Level Example
Input: "beam"
Tokens: ["b", "e", "a", "m"]
IDs: [98, 101, 97, 109]
A 20-word engineering sentence might become 100+ character tokens — consuming 5x more of the model's context window than necessary.
The problem is sequence length. A sentence that requires 20 word-level tokens might need 100 character-level tokens. Since Transformers have quadratic attention complexity (O(n2)), this 5x increase in sequence length results in a 25x increase in attention computation. Worse, the model must learn to compose characters into meaningful units entirely from scratch, which requires far more training data and compute.
Subword Tokenization: The Sweet Spot
Subword tokenization finds the middle ground. Common words like "the", "beam", and "load" are kept intact as single tokens, while rare or compound words are split into meaningful subword units. The word "geotechnical" might become ["geo", "technical"], and "prestressed" might become ["pre", "stressed"]. Each subword is itself meaningful, and the model can compose them.
This approach provides a fixed, manageable vocabulary (typically 32,000 to 100,000 tokens) while being able to represent any text — even words never seen during training. Three major subword algorithms dominate modern NLP.
BPE (Byte-Pair Encoding)
How BPE Works
BPE was originally a data compression algorithm, repurposed for NLP by Sennrich et al. (2016). The training process:
- Start with a vocabulary of all individual characters in the training corpus
- Count all adjacent character pairs (bigrams) in the corpus
- Merge the most frequent pair into a new single token
- Repeat steps 2–3 until the vocabulary reaches the desired size
For example, if "d" + "e" is the most frequent pair, merge them into "de". Then if "de" + "f" is next, merge into "def". Then "def" + "l" into "defl", and so on. Frequent words like "deflection" will eventually be merged into a single token, while rare words are composed of smaller learned subwords.
GPT-2, GPT-3, GPT-4, and LLaMA all use variants of BPE. The GPT-2 tokenizer has a vocabulary of 50,257 tokens. GPT-4's tokenizer (cl100k_base) uses approximately 100,000 tokens, which is more efficient at encoding technical text, mathematical notation, and non-English languages.
WordPiece
WordPiece Algorithm
WordPiece, developed by Google for BERT, is similar to BPE but uses a different merge criterion. Instead of merging the most frequent pair, it merges the pair that maximises the likelihood of the training data under a language model. Subword pieces that are not the start of a word are prefixed with "##".
"geotechnical" → ["geo", "##tech", "##nical"]
"deflection" → ["deflection"] (common enough to be a single token)
"prestressed" → ["pre", "##stre", "##ssed"]
SentencePiece
SentencePiece (Kudo & Richardson, 2018) treats the input as a raw byte stream, making it language-agnostic. It does not require pre-tokenization (splitting on whitespace first) and can handle any language, including those without explicit word boundaries like Chinese and Japanese. SentencePiece can implement either BPE or a Unigram model internally. Models like T5, ALBERT, and XLNet use SentencePiece.
Comparison of Tokenization Approaches
| Method | Vocab Size | OOV? | Used By |
|---|---|---|---|
| Word-level | 100K–200K+ | Yes | Early models (Word2Vec, GloVe) |
| Character | ~256 | No | Some specialised tasks |
| BPE | 32K–100K | No | GPT-2/3/4, LLaMA, Mistral |
| WordPiece | 30K–50K | No | BERT, DistilBERT, ELECTRA |
| SentencePiece | 32K–256K | No | T5, ALBERT, XLNet, LLaMA |
Vocabulary Size Tradeoffs
Choosing the vocabulary size is an engineering decision with direct parallels to choosing a mesh density in finite element analysis. A finer mesh (larger vocabulary) captures more detail but costs more memory and computation. A coarser mesh (smaller vocabulary) is efficient but may miss important features.
The Vocabulary Size Spectrum
- Too small (e.g., 8K): Common words are split into many subword pieces, sequences become very long, context windows fill quickly, and the model struggles to learn word-level semantics
- Sweet spot (32K–100K): Common words are single tokens, rare words are composed of 2–4 meaningful subwords, and the embedding table is manageable
- Too large (e.g., 500K): Many tokens are rarely seen during training, leading to poorly trained embeddings. The embedding table becomes a significant fraction of total parameters
GPT-2's vocabulary of ~50K tokens uses roughly 38 million embedding parameters (50,257 tokens x 768 dimensions). GPT-4's ~100K vocabulary with higher-dimensional embeddings uses significantly more. The tradeoff is always the same: more tokens mean shorter sequences (good for context length) but a larger embedding matrix (more parameters to train).
Impact on Engineering Text
Engineering text is particularly sensitive to vocabulary design. Technical terms like "prestressed", "geosynthetic", "shotcrete", and "formwork" may not appear frequently enough in general web text to earn their own token. A model with a 32K vocabulary might tokenize "shotcrete" as ["shot", "cre", "te"] (3 tokens), while a 100K vocabulary might represent it as ["shot", "crete"] (2 tokens) or even a single token. Fewer tokens per word means more words fit in the context window and the model can attend to them as coherent units.
Word Embeddings: From IDs to Meaning
A token ID like 4821 is just an index. It tells the model nothing about meaning, similarity, or relationships. The embedding layer transforms each token ID into a dense numerical vector — a list of floating-point numbers that encodes the token's semantic properties.
Word2Vec
Word2Vec (Mikolov et al., 2013)
Word2Vec was a breakthrough: a simple neural network trained on the task of predicting a word from its context (CBOW) or predicting context from a word (Skip-gram). The hidden layer weights, after training, become the word embeddings.
The famous result: vector arithmetic captures semantic relationships. "king" − "man" + "woman" ≈ "queen". In a civil engineering embedding space, you might find:
"beam" − "bending" + "torsion" ≈ "shaft"
"concrete" − "compression" + "tension" ≈ "steel"
"foundation" + "deep" ≈ "pile"
GloVe
GloVe (Global Vectors for Word Representation, Pennington et al., 2014) takes a different approach. Instead of training a neural network, it constructs a global word co-occurrence matrix from the entire corpus and factorises it to produce embeddings. The key insight: the ratio of co-occurrence probabilities encodes meaning. If "ice" co-occurs frequently with "solid" but not "gas", and "steam" co-occurs frequently with "gas" but not "solid", then the ratio of co-occurrences distinguishes their meanings.
Word2Vec vs. GloVe
- Word2Vec: Local context windows (5–10 words), trained via stochastic gradient descent, captures local syntactic patterns well
- GloVe: Global co-occurrence statistics, matrix factorisation, captures broader semantic relationships
- Both: Produce static embeddings — a word has the same vector regardless of context. "bank" (river) and "bank" (financial) share one vector
- Limitation: No contextual sensitivity. This is the fundamental gap that contextual embeddings (ELMo, BERT) address
Contextual Embeddings
Static embeddings (Word2Vec, GloVe) assign one fixed vector per word. But words change meaning in context: "bearing" in "bearing capacity" (geotechnical) vs. "bearing" in "roller bearing" (mechanical) vs. "load-bearing wall" (structural). Contextual embeddings solve this by producing a different vector for each occurrence of a word, conditioned on its surrounding context.
ELMo (Embeddings from Language Models)
ELMo (Peters et al., 2018)
ELMo was the first widely successful contextual embedding method. It trains a deep bidirectional LSTM language model and extracts embeddings by taking a weighted combination of all LSTM layers' hidden states. Lower layers capture syntax; higher layers capture semantics.
ELMo showed that "bearing" in "bearing capacity" and "bearing" in "roller bearing" would receive different vectors because the LSTM processes the surrounding context before producing each word's representation.
BERT Embeddings
BERT (Sub-chapter 5.4) produces contextual embeddings as a byproduct of its masked language model training. The output vector for each token at each layer is a contextual embedding. BERT embeddings are generally more powerful than ELMo because Transformers capture longer-range dependencies than LSTMs, and bidirectional attention (seeing both left and right context simultaneously) produces richer representations.
The Embedding Evolution
- 2013 — Word2Vec: Static embeddings, one vector per word, 100–300 dimensions
- 2014 — GloVe: Static embeddings from global co-occurrence, 50–300 dimensions
- 2018 — ELMo: Contextual embeddings from bidirectional LSTMs, ~1024 dimensions
- 2018 — BERT: Contextual embeddings from bidirectional Transformers, 768–1024 dimensions
- 2020+ — GPT-3/4: Contextual embeddings from decoder Transformers, 4096–12288+ dimensions
Embedding Dimensions
The dimensionality of an embedding vector determines how much information it can encode. A 2D embedding can only place words on a flat plane; a 768D embedding can capture hundreds of independent semantic features.
What Do Dimensions Represent?
Individual embedding dimensions do not have human-interpretable meanings (unlike material properties where dimension 1 = compressive strength, dimension 2 = density, etc.). Instead, each dimension captures a distributed feature. Meaning emerges from the pattern across all dimensions simultaneously.
Research has shown that certain directions in embedding space do correspond to interpretable concepts: there are directions for gender, tense, formality, and even domain (structural vs. geotechnical vs. hydraulic engineering). But these directions are not aligned with individual axes — they are diagonal directions through the high-dimensional space.
Typical Embedding Dimensions by Model
- Word2Vec / GloVe: 50, 100, 200, or 300 dimensions
- BERT-base: 768 dimensions
- BERT-large: 1024 dimensions
- GPT-2: 768 (small) to 1600 (XL) dimensions
- GPT-3: 12,288 dimensions
- LLaMA-2 70B: 8,192 dimensions
Higher dimensions allow the model to represent more nuanced distinctions, but at the cost of more parameters, more memory, and more computation. Diminishing returns apply: going from 100 to 300 dimensions dramatically improves quality, but going from 4096 to 8192 provides only incremental gains.
Positional Encodings
Transformers process all tokens in parallel, with no inherent notion of order. Without positional information, the model would see "The dog bit the man" and "The man bit the dog" as identical — the same set of tokens, just rearranged. Positional encodings inject information about each token's position in the sequence so the model can distinguish order.
Sinusoidal Positional Encoding
The Original Transformer Approach
Vaswani et al. (2017) used sine and cosine functions of different frequencies to encode positions:
PE(pos, 2i) = sin(pos / 10000^(2i/d))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d))
where pos is the token position, i is the dimension index, and d is the embedding dimension. Each dimension uses a sinusoid of a different frequency, creating a unique "fingerprint" for each position.
The key property: relative positions can be expressed as linear functions. The encoding for position pos + k can be computed from the encoding at position pos via a fixed linear transformation, regardless of pos.
Learned Positional Embeddings
An alternative approach, used by GPT and BERT, is to learn positional embeddings during training. Each position (0, 1, 2, ..., max_length-1) gets its own trainable embedding vector that is added to the token embedding. The model discovers the optimal positional representation through gradient descent.
Sinusoidal vs. Learned Positional Encodings
- Sinusoidal: No parameters to train, can theoretically generalise to unseen sequence lengths, used in the original Transformer
- Learned: Slightly better empirical performance, but limited to the maximum length seen during training (e.g., 512 for BERT, 2048 for GPT-2)
- RoPE (Rotary): A modern alternative used by LLaMA and others, encodes relative positions via rotation matrices. Enables extrapolation to longer sequences
- ALiBi: Used by BLOOM, adds a linear bias to attention scores based on distance. Simple and effective for length generalisation
Positional encodings are like chainage markers along a road alignment. The chainage tells you exactly where you are along the route (position 0+000, 0+100, 0+200, etc.). Without chainage, you have a set of cross-sections but no idea how they are ordered or spaced. The road design is meaningless without position. Similarly, a Transformer without positional encodings sees tokens as an unordered bag of words — the sequence structure is invisible.
Token Limits & Context Windows
Every Transformer model has a maximum context window — the total number of tokens it can process at once. This limit is architectural: the attention mechanism computes pairwise interactions between all tokens, and the positional encoding system must support the sequence length.
Context Window Sizes
- BERT: 512 tokens (~400 words, ~1 page)
- GPT-2: 1,024 tokens (~750 words, ~2 pages)
- GPT-3: 4,096 tokens (~3,000 words, ~8 pages)
- GPT-4: 8,192 or 32,768 tokens (~25,000 words, ~60 pages)
- GPT-4 Turbo: 128,000 tokens (~96,000 words, ~240 pages)
- Claude 3: 200,000 tokens (~150,000 words, ~375 pages)
- Gemini 1.5: 1,000,000+ tokens
For civil engineers, context window limits are a practical constraint. A full structural calculation report (100+ pages) may exceed even GPT-4's context window. A complete design code like Eurocode 2 runs to ~300 pages. Understanding how many tokens your document consumes helps you decide whether to summarise, chunk, or use a model with a larger window.
Token Counting Rules of Thumb
Estimating Token Counts
- English text: ~1 token per 0.75 words (or ~1.33 tokens per word)
- Code: ~1 token per 2–3 characters (more tokens per line than prose)
- Numbers: Each digit or group may be a separate token. "28,000" = 3–5 tokens
- Engineering symbols: Special characters (MPa, m2, °C) often split into multiple tokens
- One page of text: ~400–500 tokens
Demo 1: Interactive BPE Tokenizer
Type or paste any civil engineering text into the input below and watch it get split into BPE-style subword tokens. Each token is highlighted with a unique colour and assigned a simulated token ID. Notice how common words remain intact while rare technical terms are split into subword pieces.
Press "Tokenize" to see the BPE token breakdown with token IDs. Try engineering terms like "geosynthetic" or "shotcrete".
Observe how the tokenizer handles different types of input: common English words ("the", "under") are single tokens, standard engineering terms ("concrete", "beam") are also single tokens, but rarer compound terms ("prestressed", "serviceability") may be split into subword pieces. Numbers and units can be particularly surprising — try "28,000 kPa" or "f'c = 40 MPa".
Demo 2: Embedding Similarity Scatter
This 2D scatter plot visualises word embeddings for civil engineering terms, projected from high-dimensional space using simulated t-SNE reduction. Words that are semantically similar cluster together. Notice how structural, geotechnical, and hydraulic terms form distinct clusters, reflecting the model's learned understanding of engineering sub-domains.
Hover over points to see word labels and cosine similarity to neighbours. Select a cluster to highlight a specific engineering domain.
The clustering structure demonstrates a fundamental property of embeddings: words that appear in similar contexts end up near each other in vector space. "Beam", "column", "slab", and "truss" are all structural elements that co-occur with words like "load", "moment", "deflection", and "reinforcement". The embedding space captures this co-occurrence structure automatically, without any engineering knowledge being explicitly programmed.
The Full Pipeline: Text to Vectors
Let us trace the complete journey of a civil engineering sentence through the tokenization and embedding pipeline:
Step-by-Step Pipeline
- Raw text: "The beam deflection is 12mm"
- Tokenization (BPE): ["The", " beam", " defl", "ection", " is", " 12", "mm"]
- Token IDs: [464, 16577, 3979, 2379, 318, 1105, 3020]
- Token embeddings: Look up each ID in the embedding matrix → 7 vectors of dimension d
- Positional encodings: Add position-specific vectors to encode order (position 0, 1, 2, ...)
- Combined input: Token embedding + positional encoding = the input to the first Transformer layer
The output of step 6 is a matrix of shape [7, d] — seven d-dimensional vectors, one for each token, ready for the self-attention mechanism. From here, the Transformer layers process these vectors to produce the model's final output.
Every word of every prompt you have ever sent to ChatGPT, Claude, or any other LLM has gone through exactly this pipeline. Understanding it demystifies the model's behaviour: if "12mm" is tokenized as ["12", "mm"], the model must learn from context that these two tokens together represent a physical measurement. If the tokenizer had a dedicated "12mm" token, this learning would be unnecessary.
CE Applications: Tokenization Challenges in Engineering
Engineering text is filled with domain-specific terms, abbreviations, and numerical codes that standard tokenizers struggle with — directly impacting LLM performance on CE tasks.
Code Reference Splitting
"ACI 318-19 §20.6.1.3.4" gets tokenized into 8+ tokens, making it hard for LLMs to treat it as a single reference. Domain-aware tokenizers keep code references intact for better retrieval accuracy.
Unit-Aware Embeddings
"25 MPa" vs "25 kPa" differ by a factor of 1000 but may tokenize identically except the unit token. Specialized embeddings encode magnitude and units together for accurate engineering reasoning.
Vocabulary Gaps in CE Terms
Terms like "prestressed", "geosynthetics", "shotcrete" are split into subwords by general tokenizers. This means LLMs need more context to understand these as single engineering concepts.
Knowledge Check
Test your understanding of tokenization and embeddings with these four questions.
What is the main advantage of subword tokenization (BPE / WordPiece) over word-level tokenization?
What fundamental limitation do Word2Vec and GloVe embeddings share that contextual embeddings (ELMo, BERT) solve?
Why are positional encodings necessary in Transformer models?
A civil engineer pastes a 100-page structural report into a language model with a 4,096-token context window. Roughly how many pages can the model process?
Summary
Key Takeaways
- Tokenization: The process of splitting text into discrete units (tokens) and mapping them to integer IDs. The choice of algorithm directly affects model performance on rare and technical text
- Word-level: Simple but suffers from out-of-vocabulary problems and vocabulary explosion
- Character-level: No OOV issues but produces extremely long sequences
- Subword (BPE / WordPiece / SentencePiece): The dominant modern approach. Fixed vocabulary size, no OOV, meaningful subword units
- Vocabulary size tradeoff: Larger vocabularies = shorter sequences but more parameters; 32K–100K is the sweet spot
- Static embeddings (Word2Vec, GloVe): One fixed vector per word, cannot handle polysemy
- Contextual embeddings (ELMo, BERT): Different vectors for different contexts, capturing polysemy and nuance
- Positional encodings: Inject order information into Transformers (sinusoidal, learned, or rotary)
- Context windows: The maximum token count a model can process, ranging from 512 (BERT) to 1M+ (Gemini)
- CE analogy: Tokenization = material breakdown (concrete into cement, sand, water, aggregate); embeddings = material property vectors
In the next sub-chapter, we will explore Fine-Tuning & Prompt Engineering — how to adapt pre-trained models to specific civil engineering tasks through parameter updates (fine-tuning) or clever input design (prompting), and the tradeoffs between these two approaches.