Skip to content

Appendix A · Glossary

🌐 中文版 | English

Appendix A | Previous: Chapter 10 · Ecosystem Comparison | Next: Appendix B · Struct Reference

This glossary organizes the terms that appear throughout the book (Chapters 1-10) by category. When you run into a word you don't understand while reading other chapters, look it up here. Every term is labeled with its English / full name, for easy cross-referencing with the HuggingFace docs and papers.


Table of Contents


A.1 Model-Structure Terms

TermEnglishMeaning
Residual-stream widthhidden size / dimtoken-vector length (Qwen2.5-0.5B is 896)
MLP intermediate widthintermediate sizefeed-forward network's middle layer (4864)
Number of layersnum layersTransformer repeat count (24)
Headheadattention's parallel unit
Head dimensionhead dimeach head's vector length (64)
Vocabulary sizevocab sizehow many tokens it knows (151936)
Sequence lengthseq lenmaximum token count (2048)
Token embeddingembeddingthe token → vector lookup table
Projectionprojectionmatrix multiply y = Wx + b
Biasbiasthe constant vector added after a projection
Residual connectionresidualx = x + layer(x), lets information skip certain layers
Feed-forward networkFFN / MLPthe "independent thinking" submodule inside each layer
Decoderdecoderthe Transformer part that generates words left to right
Autoregressiveautoregressiveoutput becomes input again, looping to generate
Parameter countparameterstotal elements across all weight matrices (0.5B ≈ 494 million)
Tensortensormulti-dimensional array
Scalarscalar0-dimensional tensor (a single number)
Vectorvector1-dimensional tensor (a row of numbers)
Matrixmatrix2-dimensional tensor (a grid of rows and columns)
Feature dimensionfeature dimcolumn count of each token vector (896), independent of the row count (seq_len)

A.2 Attention Terms

TermEnglishMeaning
QueryQthe "what am I looking for" vector of the current token
KeyKthe "what am I" vector of each token
ValueVthe content vector of each token
Attentionattentionlets each word look at other words and decide whom to focus on
Attention scoreattention scorethe relatedness computed by Q·Kᵀ
Scaling factorscale (√d)prevents the dot-product value from being too large; divide by √head_dim
softmaxnormalizes scores into probabilities (summing to 1)
Causal attentioncausal attentiononly looks left, not right (for t<=pos)
GQAGrouped Query Attentionmultiple Q heads share KV (Qwen has 14 Q heads sharing 2 KV heads)
KV CacheKey-Value Cachecaches historical K/V to avoid recomputation, drops generation complexity from O(N²) to O(N)
RoPERotary Position Embeddingrotary position encoding, encodes position via rotation
rope_thetaRoPE base frequencybase frequency; the larger, the farther positions can be encoded (Qwen uses 1e6)
Dot productdot productmultiply corresponding positions of two vectors and sum; measures direction agreement
Causalitycausalitythe current token can only see tokens before it

A.3 Normalization & Activation Terms

TermEnglishMeaning
Normalizationnormalizationpulls the vector back to a standard magnitude, preventing multi-layer accumulation from exploding
RMSNormRoot Mean Square Normdivides by the root mean square (one fewer step than LayerNorm — no mean subtraction)
LayerNormLayer Normalizationsubtract mean → divide by standard deviation → multiply by weight (three steps)
epsepsilona small constant that prevents division by zero (1e-6)
Root mean squareRMSRoot Mean Square, √(Σx²/n)
SwiGLUSwish-Gated Linear Unitgated feed-forward network, silu(gate) × up
siluSigmoid Linear Unitx · sigmoid(x), smoother than ReLU
gategatingdynamically decides which channels activate (soft gate, 0 to 1)
ReLURectified Linear Unitmax(0, x), a hard gate (either 0 or the original value)
Activation functionactivation functiona function that introduces non-linearity
Activation ratioactive ratiothe fraction of channels above a threshold; reflects MLP sparsity
NormL2 normthe "length" of a vector √(Σx²); used in logs to summarize vector magnitude

A.4 Tokenization Terms

TermEnglishMeaning
Tokenizertokenizerthe bridge between text and token ids
tokenthe smallest unit the model processes (a word / a character / a chunk of bytes)
token idthe integer index of a token in the vocabulary
BPEByte-Pair Encodingbyte-pair encoding tokenization; repeatedly merges the most frequent adjacent pair
pre-tokenthe text fragments split out before BPE (e.g. splitting words by whitespace)
byte-levelbyte → unicode mapping (GPT-2's solution)
mergea BPE merge rule
vocabvocabularythe vocabulary, the set of all tokens
BOSBeginning Of Sequencesequence-start token
EOSEnd Of Sequencesequence-end token (generation stops when this is hit)
PADPaddingpadding token (for batch alignment)
Hash tablehash tableuses a hash function to speed up "string → id" lookup
FNV-1aa simple fast string hash algorithm
Chainingchaininga solution that strings collided entries together with a linked list
Hash collisionhash collisiondifferent strings hashing to the same value
teacher forcingteacher forcingin the prefill phase, follow the gold answer instead of sampling

A.5 Data-Format Terms

TermEnglishMeaning
safetensorsHuggingFace's binary tensor format (safe + mmap friendly)
dtypedata typetensor data type
fp32float3232-bit standard float (sign 1 + exponent 8 + mantissa 23)
bf16bfloat1616-bit float (sign 1 + exponent 8 + mantissa 7); fp32 with the low 16 bits chopped
fp16float1616-bit float (sign 1 + exponent 5 + mantissa 10); smaller dynamic range
mmapmemory mapmemory-mapped file; accessing memory is equivalent to reading the file
little-endianlittle-endianthe low byte is stored at the low address
headerthe JSON metadata table at the start of a safetensors file
raw bufferthe contiguous binary tensor data after the safetensors header
data_offsetsthe [start, end) range of a tensor inside the raw buffer
Quantizationquantizationapproximate weights with fewer bits (e.g. int4)
int4 / int84-bit / 8-bit integer representation
scalescale factorthe divisor that compresses the floating-point range into an integer interval during quantization

A.6 C / Engineering Terms

TermMeaning
row-majormatrix stored row by row (C default); W[i*n+j] is row i, column j
strict aliasingstrict aliasing rule; float* and uint32_t* pointing at the same memory is undefined behavior
memcpymemory copy; the compiler optimizes it to zero overhead (the standard way to bypass strict aliasing)
recursive descentthe parser recurses top-down (e.g. the JSON parser calling parse_object when it sees {)
RFCinternet standard document (e.g. RFC 8259 = the JSON standard)
unescapeunescape, restoring \" back to "
surrogate pairsurrogate pair; UTF-16 uses two 16-bit codes to represent a rare character
BMPBasic Multilingual Plane; the Unicode basic plane (code points 0-65535)
chainingstring collided hash entries together with a linked list
FNV-1aa string hash algorithm
xorshifta pseudo-random-number algorithm (uses XOR and shifts)
PRNGPseudo Random Number Generator
seedseed, the PRNG's initial state
argmaxtake the index of the maximum value
roulette wheelroulette wheel, sampling by probability distribution
top-kkeep only the k highest-probability entries
temperaturetemperature, the parameter that scales logits before softmax
softmaxthe function that normalizes scores into probabilities
ANSI escape codeterminal color-control sequences (\033[31m etc.)
TTYTeleTYpewriter, terminal
isattychecks whether a file descriptor is a terminal
stderrstandard error stream (logs go here)
stdoutstandard output stream (generated text goes here)
va_listC variadic-argument mechanism (makes printf("a=%d", a) work)
va_start / va_endinitialize / finalize va_list iteration
vsnprintfthe va_list version of printf
ASanAddressSanitizer, the compiler's built-in memory-error detector
UBSanUndefinedBehaviorSanitizer, undefined-behavior detector
sanitizergeneric term for memory / behavior detection tools

A.7 Ecosystem & Performance Terms

TermEnglishMeaning
Inferenceinferencecomputing a result with a trained model (forward only, no weight updates)
Forward passforward passcompute from layer 1 through layer N
Backward passbackward passduring training, compute gradients back from the output; this project doesn't do it
prefillprefillthe phase that fills the KV Cache for the entire prompt
decodedecodethe phase that autoregressively generates new tokens one slot at a time
TTFTtime-to-first-tokenthe latency to generate the first token (the prefill cost)
Continuous Batchingcontinuous batchingevery step batches all active requests together; the GPU never idles
PagedAttentionpaged attentionslices the KV Cache into fixed-size pages allocated on demand (vLLM innovation)
Prefix Cachingprefix cachingcaches the KV Cache of shared prefixes to reuse compute
RadixAttentionradix-tree attentionSGLang caches prefixes with a radix tree, caching more combinations than a hash table
FlashAttentionflash attentiontiled attention computation; VRAM goes from O(seq²) down to O(seq)
Speculative Decodingspeculative decodingsmall model guesses + large model verifies; one forward pass produces multiple tokens
Tensor Parallelismtensor parallelismslice a large matrix by rows / columns across multiple cards
Pipeline Parallelismpipeline parallelismslice by layer across multiple cards; each card handles a few layers
CPU OffloadingCPU offloadingweights stay in main memory; move each layer to VRAM when needed
MoEMixture of Expertsmixture of experts; only a fraction of expert weights are used per token
SIMDSingle Instruction Multiple Datasingle-instruction multiple-data; CPU parallelism (AVX / NEON)
Tensor Corethe hardware unit on a GPU purpose-built for matrix multiplies
cuBLASNVIDIA's linear algebra library (the GPU version of BLAS)
cuDNNNVIDIA's deep-learning operator library
GGUFllama.cpp's model format (includes quantized weights)
ggmlllama.cpp's self-developed tensor compute library
GQAGrouped Query Attentionmultiple Q heads share KV (see A.2)
MLAMulti-head Latent AttentionDeepSeek's attention structure, replacing GQA
All-Gathermulti-card communication primitive; each card gets all cards' partial results stitched together
logitsthe raw scores projected to the vocabulary at the end (before softmax)
Reference implementationreference implementationthe comparison baseline (this project uses PyTorch transformers)
top-5 logitsthe 5 highest-scoring tokens, used to verify the forward pass
tie_word_embeddingsthe output head reuses the embedding weights (Qwen sets this to true; no lm_head)

Quick Reference: Key Numbers of This Project

ItemValue
Parameter count494,032,768 (≈0.49B, called "0.5B")
safetensors file size988 MB (bf16 storage)
fp32 memory footprint1.97 GB
dim (feature dim)896
hidden_dim (MLP intermediate width)4864
n_layers24
n_heads (Q heads)14
n_kv_heads (KV heads)2
head_dim64
vocab_size151936
seq_len2048
rope_theta1,000,000
rms_eps1e-6
BOS / EOS id151643 (`<
Speed (CPU fp32)~3 tok/s
Speed (vLLM A100 concurrent)~8000 tok/s

This glossary is the index for the whole book (Chapters 1-10). Whenever you hit a word you don't understand in any chapter, look it up here first; if it's not here, go to the relevant chapter's body text for the detailed explanation.

MIT Licensed