{"id":1030,"date":"2026-07-03T09:58:50","date_gmt":"2026-07-03T09:58:50","guid":{"rendered":"https:\/\/learnerbox.net\/blog\/?p=1030"},"modified":"2026-07-04T17:15:16","modified_gmt":"2026-07-04T17:15:16","slug":"how-large-language-models-work-part-1-tokenization-and-embeddings","status":"publish","type":"post","link":"https:\/\/learnerbox.net\/blog\/ai-theory\/how-large-language-models-work-part-1-tokenization-and-embeddings\/","title":{"rendered":"How Large Language Models Work \u2014 Part 1: Tokenization and Embeddings"},"content":{"rendered":"\n<h6 class=\"wp-block-heading\"><em><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">This is Part 1 of a five-part deep-dive series on the internal mechanics of large language models. This series is written for engineers, ML practitioners, and technically advanced readers. Part 1 covers tokenization and embeddings \u2014 the first two stages through which raw text becomes a mathematical object a neural network can reason over.<\/mark><\/em><\/h6>\n\n\n\n<h4 class=\"wp-block-heading\">Why Text Must Be Transformed<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Neural networks are, at their core, mathematical functions that operate on tensors, which are multi-dimensional arrays of floating-point numbers. They cannot accept raw text strings as input. Before a language model can do anything useful, it must convert a sequence of characters into a sequence of numbers. This two-step process of tokenization followed by embedding is where all LLM processing begins, and understanding it deeply is prerequisite to understanding everything that follows.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Stage 1: Tokenization<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">What a Tokenizer Does<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">A tokenizer breaks a raw string into a sequence of discrete units called <strong>tokens<\/strong>, and maps each token to an integer index in a fixed vocabulary. Given the input string:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><code>\"The cat sat on the mat\"<\/code><\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">a tokenizer might produce the token sequence: [464,&nbsp;5171,&nbsp;7231,&nbsp;322,&nbsp;464,&nbsp;8114]<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each integer is an index into a vocabulary table of size <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi mathvariant=\"normal\">\u2223<\/mi><mi>V<\/mi><mi mathvariant=\"normal\">\u2223<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">|V|<\/annotation><\/semantics><\/math>, typically between 32,000 and 100,000 entries for modern models. GPT-4 uses a vocabulary of approximately 100,277 tokens. Llama 3 uses 128,256.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"614\" src=\"https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/positional_encoding_comparison-1024x614.png\" alt=\"\" class=\"wp-image-1032\" title=\"\" srcset=\"https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/positional_encoding_comparison-1024x614.png 1024w, https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/positional_encoding_comparison-300x180.png 300w, https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/positional_encoding_comparison-768x460.png 768w, https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/positional_encoding_comparison-1536x920.png 1536w, https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/positional_encoding_comparison-2048x1227.png 2048w, https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/positional_encoding_comparison-1140x683.png 1140w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"767\" src=\"https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/tokenization_bpe_diagram-1024x767.png\" alt=\"\" class=\"wp-image-1031\" title=\"\" srcset=\"https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/tokenization_bpe_diagram-1024x767.png 1024w, https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/tokenization_bpe_diagram-300x225.png 300w, https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/tokenization_bpe_diagram-768x575.png 768w, https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/tokenization_bpe_diagram-1536x1151.png 1536w, https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/tokenization_bpe_diagram-2048x1534.png 2048w, https:\/\/learnerbox.net\/blog\/wp-content\/uploads\/2026\/07\/tokenization_bpe_diagram-1140x854.png 1140w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<h4 class=\"wp-block-heading\">Byte-Pair Encoding (BPE)<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The dominant tokenization algorithm used in modern LLMs is <strong>Byte-Pair Encoding (BPE)<\/strong>, originally a data compression algorithm adapted for NLP by <a href=\"https:\/\/aclanthology.org\/P16-1162\/\" rel=\"noopener\">Sennrich et al. in 2016<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">BPE builds its vocabulary through an iterative merging process:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Initialise the vocabulary with every individual character (or byte) in the training corpus.<\/li>\n\n\n\n<li>Count all adjacent symbol pairs across the corpus.<\/li>\n\n\n\n<li>Merge the most frequent pair into a single new symbol.<\/li>\n\n\n\n<li>Repeat steps 2\u20133 until the vocabulary reaches the target size <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi mathvariant=\"normal\">\u2223<\/mi><mi>V<\/mi><mi mathvariant=\"normal\">\u2223<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">|V|<\/annotation><\/semantics><\/math>\u2223V\u2223.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">The result is a vocabulary that contains individual characters, common subwords, and frequent whole words. The word <em>&#8220;tokenization&#8221;<\/em> might be represented as three tokens: <code>token<\/code>, <code>ization<\/code> is further split into <code>iz<\/code>, <code>ation<\/code> depending on training corpus frequency.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This has a critical practical consequence: <strong>no word is ever truly unknown to a BPE tokenizer.<\/strong> Any string, including code, URLs, foreign scripts, or novel proper nouns, can be decomposed into its constituent bytes if nothing else matches. This is why BPE-based models generalise to inputs they have never seen verbatim.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Token Fertility and Efficiency<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Not all languages tokenize equally efficiently. English text typically tokenizes at roughly 0.75 tokens per word. Languages with richer morphology, such as Finnish, Turkish, Arabic, or non-Latin scripts, tokenize less efficiently, sometimes requiring 3\u20135 tokens per word. This has practical implications: a context window of 128,000 tokens holds far more English prose than it does Thai or Arabic text, a bias baked into the model&#8217;s architecture from the vocabulary construction stage.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <strong>fertility<\/strong> of a tokenizer, or the average number of tokens per word, is a meaningful measure of how well it serves a given language or domain. Code-optimised models like DeepSeek Coder use vocabularies with explicit code tokens to reduce the fertility of common programming constructs.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">WordPiece and SentencePiece<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Two notable alternatives to BPE are worth knowing:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>WordPiece<\/strong>, used in BERT and its derivatives, is similar to BPE but merges pairs that maximise the likelihood of the training data under a language model, rather than simply the most frequent pair. This produces slightly different vocabulary distributions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>SentencePiece<\/strong>, used in models including Llama and T5, treats the input as a raw unicode byte stream with no pre-tokenization step (no whitespace splitting). This makes it language-agnostic and particularly well-suited for multilingual models.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Stage 2: Token Embeddings<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">The Embedding Matrix<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Once tokenization has produced a sequence of integer indices <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mo stretchy=\"false\">[<\/mo><msub><mi>t<\/mi><mn>1<\/mn><\/msub><mo separator=\"true\">,<\/mo><msub><mi>t<\/mi><mn>2<\/mn><\/msub><mo separator=\"true\">,<\/mo><mo>\u2026<\/mo><mo separator=\"true\">,<\/mo><msub><mi>t<\/mi><mi>n<\/mi><\/msub><mo stretchy=\"false\">]<\/mo><\/mrow><annotation encoding=\"application\/x-tex\">[t_1, t_2, \\ldots, t_n]<\/annotation><\/semantics><\/math>, each index must be converted into a dense vector. This is done via an <strong>embedding matrix<\/strong> <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>W<\/mi><mi>E<\/mi><\/msub><mo>\u2208<\/mo><msup><mi mathvariant=\"double-struck\">R<\/mi><mrow><mi mathvariant=\"normal\">\u2223<\/mi><mi>V<\/mi><mi mathvariant=\"normal\">\u2223<\/mi><mo>\u00d7<\/mo><mi>d<\/mi><\/mrow><\/msup><\/mrow><annotation encoding=\"application\/x-tex\">W_E \\in \\mathbb{R}^{|V| \\times d}<\/annotation><\/semantics><\/math>, where <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>d<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">d<\/annotation><\/semantics><\/math> is the model&#8217;s hidden dimension (also called the embedding dimension or <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>d<\/mi><mtext>model<\/mtext><\/msub><\/mrow><annotation encoding=\"application\/x-tex\">d_{\\text{model}}<\/annotation><\/semantics><\/math>\u200b).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The embedding for token <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>t<\/mi><mi>i<\/mi><\/msub><\/mrow><annotation encoding=\"application\/x-tex\">t_i<\/annotation><\/semantics><\/math>ti\u200b is simply a row lookup:<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\" display=\"block\"><semantics><mrow><msub><mi mathvariant=\"bold\">e<\/mi><mi>i<\/mi><\/msub><mo>=<\/mo><msub><mi>W<\/mi><mi>E<\/mi><\/msub><mo stretchy=\"false\">[<\/mo><msub><mi>t<\/mi><mi>i<\/mi><\/msub><mo stretchy=\"false\">]<\/mo><mo>\u2208<\/mo><msup><mi mathvariant=\"double-struck\">R<\/mi><mi>d<\/mi><\/msup><\/mrow><annotation encoding=\"application\/x-tex\">\\mathbf{e}_i = W_E[t_i] \\in \\mathbb{R}^d<\/annotation><\/semantics><\/math>In GPT-3, <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>d<\/mi><mo>=<\/mo><mn>12288<\/mn><\/mrow><annotation encoding=\"application\/x-tex\">d = 12288<\/annotation><\/semantics><\/math>. In Llama 3 8B, <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>d<\/mi><mo>=<\/mo><mn>4096<\/mn><\/mrow><annotation encoding=\"application\/x-tex\">d = 4096<\/annotation><\/semantics><\/math>. This single matrix, learned entirely from data during pre-training, is responsible for encoding the semantic relationships between all tokens in the vocabulary.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The number of parameters in the embedding matrix alone is <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi mathvariant=\"normal\">\u2223<\/mi><mi>V<\/mi><mi mathvariant=\"normal\">\u2223<\/mi><mo>\u00d7<\/mo><mi>d<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">|V| \\times d<\/annotation><\/semantics><\/math>. For GPT-4&#8217;s approximate configuration, that is <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mn>100,277<\/mn><mo>\u00d7<\/mo><msub><mi>d<\/mi><mtext>model<\/mtext><\/msub><\/mrow><annotation encoding=\"application\/x-tex\">100{,}277 \\times d_{\\text{model}}<\/annotation><\/semantics><\/math> which is often hundreds of millions of parameters just for this one component.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Why Dense Vectors Work: The Geometry of Meaning<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The remarkable property of learned embeddings is that semantic relationships emerge as geometric relationships in <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msup><mi mathvariant=\"double-struck\">R<\/mi><mi>d<\/mi><\/msup><\/mrow><annotation encoding=\"application\/x-tex\">\\mathbb{R}^d<\/annotation><\/semantics><\/math>. The classic demonstration is the linear analogy:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\" display=\"block\"><semantics><mrow><mi mathvariant=\"bold\">e<\/mi><mo stretchy=\"false\">(<\/mo><mtext>&#8220;king&#8221;<\/mtext><mo stretchy=\"false\">)<\/mo><mo>\u2212<\/mo><mi mathvariant=\"bold\">e<\/mi><mo stretchy=\"false\">(<\/mo><mtext>&#8220;man&#8221;<\/mtext><mo stretchy=\"false\">)<\/mo><mo>+<\/mo><mi mathvariant=\"bold\">e<\/mi><mo stretchy=\"false\">(<\/mo><mtext>&#8220;woman&#8221;<\/mtext><mo stretchy=\"false\">)<\/mo><mo>\u2248<\/mo><mi mathvariant=\"bold\">e<\/mi><mo stretchy=\"false\">(<\/mo><mtext>&#8220;queen&#8221;<\/mtext><mo stretchy=\"false\">)<\/mo><\/mrow><annotation encoding=\"application\/x-tex\">\\mathbf{e}(\\text{&#8220;king&#8221;}) &#8211; \\mathbf{e}(\\text{&#8220;man&#8221;}) + \\mathbf{e}(\\text{&#8220;woman&#8221;}) \\approx \\mathbf{e}(\\text{&#8220;queen&#8221;})<\/annotation><\/semantics><\/math><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is not programmed. It emerges from the statistical structure of co-occurrence patterns in the training corpus. Words that appear in similar contexts end up with similar embedding vectors, measured by cosine similarity:<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\" display=\"block\"><semantics><mrow><mtext>sim<\/mtext><mo stretchy=\"false\">(<\/mo><mi mathvariant=\"bold\">u<\/mi><mo separator=\"true\">,<\/mo><mi mathvariant=\"bold\">v<\/mi><mo stretchy=\"false\">)<\/mo><mo>=<\/mo><mfrac><mrow><mi mathvariant=\"bold\">u<\/mi><mo>\u22c5<\/mo><mi mathvariant=\"bold\">v<\/mi><\/mrow><mrow><mi mathvariant=\"normal\">\u2225<\/mi><mi mathvariant=\"bold\">u<\/mi><mi mathvariant=\"normal\">\u2225<\/mi><mi mathvariant=\"normal\">\u2225<\/mi><mi mathvariant=\"bold\">v<\/mi><mi mathvariant=\"normal\">\u2225<\/mi><\/mrow><\/mfrac><\/mrow><annotation encoding=\"application\/x-tex\">\\text{sim}(\\mathbf{u}, \\mathbf{v}) = \\frac{\\mathbf{u} \\cdot \\mathbf{v}}{\\|\\mathbf{u}\\| \\|\\mathbf{v}\\|}<\/annotation><\/semantics><\/math>In high-dimensional spaces, this geometry becomes extraordinarily rich. Directions in embedding space can encode syntactic roles, semantic fields, sentiment polarities, and factual associations \u2014 all simultaneously, in different orthogonal subspaces of the same <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msup><mi mathvariant=\"double-struck\">R<\/mi><mi>d<\/mi><\/msup><\/mrow><annotation encoding=\"application\/x-tex\">\\mathbb{R}^d<\/annotation><\/semantics><\/math>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Stage 3: Positional Encoding<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Token embeddings encode <em>what<\/em> each token is, but they contain no information about <em>where<\/em> in the sequence each token appears. The sequence <code>\"dog bites man\"<\/code> and <code>\"man bites dog\"<\/code> would produce identical sets of token embeddings in a different order and would be catastrophic for a model that needs to understand syntax and word order.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Positional information must therefore be injected explicitly.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Sinusoidal Positional Encoding (Original Transformer)<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The original transformer paper (<a href=\"https:\/\/en.wikipedia.org\/wiki\/Attention_Is_All_You_Need\" rel=\"noopener\">Vaswani et al., 2017<\/a>) proposed adding a fixed sinusoidal signal to each token embedding. For position <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>p<\/mi><mi>o<\/mi><mi>s<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">pos<\/annotation><\/semantics><\/math>pos and dimension <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>i<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">i<\/annotation><\/semantics><\/math>i:<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\" display=\"block\"><semantics><mrow><mi>P<\/mi><msub><mi>E<\/mi><mrow><mo stretchy=\"false\">(<\/mo><mi>p<\/mi><mi>o<\/mi><mi>s<\/mi><mo separator=\"true\">,<\/mo><mn>2<\/mn><mi>i<\/mi><mo stretchy=\"false\">)<\/mo><\/mrow><\/msub><mo>=<\/mo><mi>sin<\/mi><mo>\u2061<\/mo><mtext>\u2009\u2063<\/mtext><mrow><mo fence=\"true\">(<\/mo><mfrac><mrow><mi>p<\/mi><mi>o<\/mi><mi>s<\/mi><\/mrow><msup><mn>10000<\/mn><mrow><mn>2<\/mn><mi>i<\/mi><mi mathvariant=\"normal\">\/<\/mi><mi>d<\/mi><\/mrow><\/msup><\/mfrac><mo fence=\"true\">)<\/mo><\/mrow><\/mrow><annotation encoding=\"application\/x-tex\">PE_{(pos, 2i)} = \\sin\\!\\left(\\frac{pos}{10000^{2i\/d}}\\right)<\/annotation><\/semantics><\/math> <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\" display=\"block\"><semantics><mrow><mi>P<\/mi><msub><mi>E<\/mi><mrow><mo stretchy=\"false\">(<\/mo><mi>p<\/mi><mi>o<\/mi><mi>s<\/mi><mo separator=\"true\">,<\/mo><mn>2<\/mn><mi>i<\/mi><mo>+<\/mo><mn>1<\/mn><mo stretchy=\"false\">)<\/mo><\/mrow><\/msub><mo>=<\/mo><mi>cos<\/mi><mo>\u2061<\/mo><mtext>\u2009\u2063<\/mtext><mrow><mo fence=\"true\">(<\/mo><mfrac><mrow><mi>p<\/mi><mi>o<\/mi><mi>s<\/mi><\/mrow><msup><mn>10000<\/mn><mrow><mn>2<\/mn><mi>i<\/mi><mi mathvariant=\"normal\">\/<\/mi><mi>d<\/mi><\/mrow><\/msup><\/mfrac><mo fence=\"true\">)<\/mo><\/mrow><\/mrow><annotation encoding=\"application\/x-tex\">PE_{(pos, 2i+1)} = \\cos\\!\\left(\\frac{pos}{10000^{2i\/d}}\\right)<\/annotation><\/semantics><\/math><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The input to the first transformer layer is then:<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\" display=\"block\"><semantics><mrow><msub><mi mathvariant=\"bold\">x<\/mi><mi>i<\/mi><\/msub><mo>=<\/mo><msub><mi mathvariant=\"bold\">e<\/mi><mi>i<\/mi><\/msub><mo>+<\/mo><mi>P<\/mi><msub><mi>E<\/mi><mi>i<\/mi><\/msub><\/mrow><annotation encoding=\"application\/x-tex\">\\mathbf{x}_i = \\mathbf{e}_i + PE_i<\/annotation><\/semantics><\/math><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The sinusoidal formulation has a useful property: the positional encoding of position <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>p<\/mi><mi>o<\/mi><mi>s<\/mi><mo>+<\/mo><mi>k<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">pos + k<\/annotation><\/semantics><\/math> can be expressed as a linear function of the encoding at <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>p<\/mi><mi>o<\/mi><mi>s<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">pos<\/annotation><\/semantics><\/math>pos, which makes it easy for attention heads to learn to attend to tokens at a fixed relative offset.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Learned Positional Embeddings<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">GPT-2 and GPT-3 replaced sinusoidal encodings with <strong>learned positional embeddings<\/strong>: a second matrix <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>W<\/mi><mi>P<\/mi><\/msub><mo>\u2208<\/mo><msup><mi mathvariant=\"double-struck\">R<\/mi><mrow><msub><mi>n<\/mi><mtext>max<\/mtext><\/msub><mo>\u00d7<\/mo><mi>d<\/mi><\/mrow><\/msup><\/mrow><annotation encoding=\"application\/x-tex\">W_P \\in \\mathbb{R}^{n_{\\text{max}} \\times d}<\/annotation><\/semantics><\/math>\u200b, where <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>n<\/mi><mtext>max<\/mtext><\/msub><\/mrow><annotation encoding=\"application\/x-tex\">n_{\\text{max}}<\/annotation><\/semantics><\/math>\u200b is the maximum context length. Position <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>p<\/mi><mi>o<\/mi><mi>s<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">pos<\/annotation><\/semantics><\/math>pos adds the row <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>W<\/mi><mi>P<\/mi><\/msub><mo stretchy=\"false\">[<\/mo><mi>p<\/mi><mi>o<\/mi><mi>s<\/mi><mo stretchy=\"false\">]<\/mo><\/mrow><annotation encoding=\"application\/x-tex\">W_P[pos]<\/annotation><\/semantics><\/math> to the token embedding. These are learned end-to-end during pre-training and tend to slightly outperform sinusoidal encodings on benchmarks, at the cost of a hard context length ceiling \u2014 the model cannot generalise beyond <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>n<\/mi><mtext>max<\/mtext><\/msub><\/mrow><annotation encoding=\"application\/x-tex\">n_{\\text{max}}<\/annotation><\/semantics><\/math>\u200b positions it has seen during training.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Rotary Positional Embedding (RoPE)<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The current state of the art for most frontier models, including Llama, Mistral, GPT-4, and Gemini, is <strong>Rotary Positional Embedding (RoPE)<\/strong>, introduced by <a href=\"https:\/\/arxiv.org\/abs\/2104.09864\" rel=\"noopener\">Su et al. in 2021<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Rather than adding a positional vector to the token embedding, RoPE encodes position by rotating the Query and Key vectors in the attention mechanism (covered in Part 2) by a position-dependent angle. For a vector at position <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>m<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">m<\/annotation><\/semantics><\/math>m in dimension pair <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mo stretchy=\"false\">(<\/mo><mn>2<\/mn><mi>i<\/mi><mo separator=\"true\">,<\/mo><mn>2<\/mn><mi>i<\/mi><mo>+<\/mo><mn>1<\/mn><mo stretchy=\"false\">)<\/mo><\/mrow><annotation encoding=\"application\/x-tex\">(2i, 2i+1)<\/annotation><\/semantics><\/math>:<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\" display=\"block\"><semantics><mrow><msubsup><mi mathvariant=\"bold\">q<\/mi><mi>m<\/mi><mrow><mo stretchy=\"false\">(<\/mo><mi>i<\/mi><mo stretchy=\"false\">)<\/mo><\/mrow><\/msubsup><mo>=<\/mo><mrow><mo fence=\"true\">(<\/mo><mtable rowspacing=\"0.16em\" columnalign=\"center\" columnspacing=\"1em\"><mtr><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><msub><mi>q<\/mi><mrow><mn>2<\/mn><mi>i<\/mi><\/mrow><\/msub><\/mstyle><\/mtd><\/mtr><mtr><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><msub><mi>q<\/mi><mrow><mn>2<\/mn><mi>i<\/mi><mo>+<\/mo><mn>1<\/mn><\/mrow><\/msub><\/mstyle><\/mtd><\/mtr><\/mtable><mo fence=\"true\">)<\/mo><\/mrow><mrow><mo fence=\"true\">(<\/mo><mtable rowspacing=\"0.16em\" columnalign=\"center center\" columnspacing=\"1em\"><mtr><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><mrow><mi>cos<\/mi><mo>\u2061<\/mo><mi>m<\/mi><msub><mi>\u03b8<\/mi><mi>i<\/mi><\/msub><\/mrow><\/mstyle><\/mtd><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><mrow><mo>\u2212<\/mo><mi>sin<\/mi><mo>\u2061<\/mo><mi>m<\/mi><msub><mi>\u03b8<\/mi><mi>i<\/mi><\/msub><\/mrow><\/mstyle><\/mtd><\/mtr><mtr><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><mrow><mi>sin<\/mi><mo>\u2061<\/mo><mi>m<\/mi><msub><mi>\u03b8<\/mi><mi>i<\/mi><\/msub><\/mrow><\/mstyle><\/mtd><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><mrow><mi>cos<\/mi><mo>\u2061<\/mo><mi>m<\/mi><msub><mi>\u03b8<\/mi><mi>i<\/mi><\/msub><\/mrow><\/mstyle><\/mtd><\/mtr><\/mtable><mo fence=\"true\">)<\/mo><\/mrow><\/mrow><annotation encoding=\"application\/x-tex\">\\mathbf{q}_m^{(i)} = \\begin{pmatrix} q_{2i} \\\\ q_{2i+1} \\end{pmatrix} \\begin{pmatrix} \\cos m\\theta_i &amp; -\\sin m\\theta_i \\\\ \\sin m\\theta_i &amp; \\cos m\\theta_i \\end{pmatrix}<\/annotation><\/semantics><\/math><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">where <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>\u03b8<\/mi><mi>i<\/mi><\/msub><mo>=<\/mo><msup><mn>10000<\/mn><mrow><mo>\u2212<\/mo><mn>2<\/mn><mi>i<\/mi><mi mathvariant=\"normal\">\/<\/mi><mi>d<\/mi><\/mrow><\/msup><\/mrow><annotation encoding=\"application\/x-tex\">\\theta_i = 10000^{-2i\/d}<\/annotation><\/semantics><\/math>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The critical advantage: the dot product between a query at position <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>m<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">m<\/annotation><\/semantics><\/math>m and a key at position <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>n<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">n<\/annotation><\/semantics><\/math>n depends only on their <strong>relative<\/strong> offset <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>m<\/mi><mo>\u2212<\/mo><mi>n<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">m &#8211; n<\/annotation><\/semantics><\/math>, not their absolute positions. This gives the model a natural inductive bias toward relative position awareness, and with extensions like YaRN makes it possible to extend the effective context window well beyond what the model was trained on.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">RoPE is why modern models can be fine-tuned to handle 128K or even 1M token context windows without retraining the entire model from scratch.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Putting It Together: The Input Representation<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The final input to the first transformer layer for a sequence of <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>n<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">n<\/annotation><\/semantics><\/math>n tokens is a matrix <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>X<\/mi><mo>\u2208<\/mo><msup><mi mathvariant=\"double-struck\">R<\/mi><mrow><mi>n<\/mi><mo>\u00d7<\/mo><mi>d<\/mi><\/mrow><\/msup><\/mrow><annotation encoding=\"application\/x-tex\">X \\in \\mathbb{R}^{n \\times d}<\/annotation><\/semantics><\/math>:<math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\" display=\"block\"><semantics><mrow><mi>X<\/mi><mo>=<\/mo><mrow><mo fence=\"true\">(<\/mo><mtable rowspacing=\"0.16em\" columnalign=\"center\" columnspacing=\"1em\"><mtr><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><mrow><msub><mi mathvariant=\"bold\">e<\/mi><mn>1<\/mn><\/msub><mo>+<\/mo><msub><mi mathvariant=\"bold\">p<\/mi><mn>1<\/mn><\/msub><\/mrow><\/mstyle><\/mtd><\/mtr><mtr><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><mrow><msub><mi mathvariant=\"bold\">e<\/mi><mn>2<\/mn><\/msub><mo>+<\/mo><msub><mi mathvariant=\"bold\">p<\/mi><mn>2<\/mn><\/msub><\/mrow><\/mstyle><\/mtd><\/mtr><mtr><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><mrow><mi mathvariant=\"normal\">\u22ee<\/mi><mpadded height=\"0em\" voffset=\"0em\"><mspace mathbackground=\"black\" width=\"0em\" height=\"1.5em\"><\/mspace><\/mpadded><\/mrow><\/mstyle><\/mtd><\/mtr><mtr><mtd><mstyle scriptlevel=\"0\" displaystyle=\"false\"><mrow><msub><mi mathvariant=\"bold\">e<\/mi><mi>n<\/mi><\/msub><mo>+<\/mo><msub><mi mathvariant=\"bold\">p<\/mi><mi>n<\/mi><\/msub><\/mrow><\/mstyle><\/mtd><\/mtr><\/mtable><mo fence=\"true\">)<\/mo><\/mrow><\/mrow><annotation encoding=\"application\/x-tex\">X = \\begin{pmatrix} \\mathbf{e}_1 + \\mathbf{p}_1 \\\\ \\mathbf{e}_2 + \\mathbf{p}_2 \\\\ \\vdots \\\\ \\mathbf{e}_n + \\mathbf{p}_n \\end{pmatrix}<\/annotation><\/semantics><\/math>where <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi mathvariant=\"bold\">p<\/mi><mi>i<\/mi><\/msub><\/mrow><annotation encoding=\"application\/x-tex\">\\mathbf{p}_i<\/annotation><\/semantics><\/math> is the positional encoding for position <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>i<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">i<\/annotation><\/semantics><\/math> (sinusoidal, learned, or RoPE-derived). Each row of <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>X<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">X<\/annotation><\/semantics><\/math> is a <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>d<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">d<\/annotation><\/semantics><\/math>-dimensional vector carrying both the semantic identity of the token and its position in the sequence. This matrix is what flows into the self-attention mechanism, which is the subject of <a href=\"https:\/\/learnerbox.net\/blog\/ai-theory\/how-large-language-models-work-part-2-the-attention-mechanism\/\">Part 2<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h4 class=\"wp-block-heading\">Key Numbers to Anchor Your Intuition<\/h4>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Model<\/th><th>Vocabulary <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi mathvariant=\"normal\">\u2225<\/mi><mi>V<\/mi><mi mathvariant=\"normal\">\u2225<\/mi><\/mrow><annotation encoding=\"application\/x-tex\">\\|V\\|<\/annotation><\/semantics><\/math><\/th><th><math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><msub><mi>d<\/mi><mtext>model<\/mtext><\/msub><\/mrow><annotation encoding=\"application\/x-tex\">d_{\\text{model}}<\/annotation><\/semantics><\/math><\/th><th>Positional scheme<\/th><\/tr><\/thead><tbody><tr><td>GPT-2<\/td><td>50,257<\/td><td>768\u20131,600<\/td><td>Learned<\/td><\/tr><tr><td>GPT-3<\/td><td>50,257<\/td><td>12,288<\/td><td>Learned<\/td><\/tr><tr><td>Llama 3 8B<\/td><td>128,256<\/td><td>4,096<\/td><td>RoPE<\/td><\/tr><tr><td>Mistral 7B<\/td><td>32,000<\/td><td>4,096<\/td><td>RoPE<\/td><\/tr><tr><td>Gemma 2<\/td><td>256,000<\/td><td>2,304\u20133,584<\/td><td>RoPE<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h4 class=\"wp-block-heading\">Conclusion<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Before a single attention head fires, a large language model has already done substantial mathematical work. A raw string has been segmented into subword tokens by a BPE or SentencePiece algorithm, each token has been projected into a high-dimensional vector space where geometry encodes meaning, and position information has been woven in either additively or, in modern models, rotationally via RoPE. The quality of this input representation has an outsized effect on everything downstream: models with poorly constructed vocabularies or weak embedding initialisations are harder to train and less capable at convergence.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/learnerbox.net\/blog\/ai-theory\/how-large-language-models-work-part-2-the-attention-mechanism\/\">Part 2<\/a> will take this matrix <math xmlns=\"http:\/\/www.w3.org\/1998\/Math\/MathML\"><semantics><mrow><mi>X<\/mi><mo>\u2208<\/mo><msup><mi mathvariant=\"double-struck\">R<\/mi><mrow><mi>n<\/mi><mo>\u00d7<\/mo><mi>d<\/mi><\/mrow><\/msup><\/mrow><annotation encoding=\"application\/x-tex\">X \\in \\mathbb{R}^{n \\times d}<\/annotation><\/semantics><\/math> and walk through exactly what the self-attention mechanism does with it, including the full mathematical derivation of scaled dot-product attention, multi-head attention, and what different heads actually learn to represent.<\/p>\n\n\n\n<h6 class=\"wp-block-heading\"><em><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">Coming next in the AI Engineering series is <a href=\"https:\/\/learnerbox.net\/blog\/ai-theory\/how-large-language-models-work-part-2-the-attention-mechanism\/\">Part 2<\/a>: The Attention Mechanism.<\/mark><\/em><\/h6>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This is Part 1 of a five-part deep-dive series on the internal mechanics of large language models. This series is written for engineers, ML practitioners, and technically advanced readers. Part 1 covers tokenization and embeddings \u2014 the first two stages through which raw text becomes a mathematical object a neural network can reason over. Why Text Must Be Transformed Neural networks are, at their core, mathematical functions that operate on tensors, which are multi-dimensional arrays of floating-point numbers. They cannot accept raw text strings as input. Before a language model can do anything useful, it must convert a sequence of characters into a sequence of numbers. This two-step process of tokenization followed by embedding is where all LLM processing begins, and understanding it deeply is prerequisite to understanding everything that follows. Stage 1: Tokenization What a Tokenizer Does A tokenizer breaks a raw string into a sequence of discrete units called tokens, and maps each token to an integer index in a fixed vocabulary. Given the input string: &#8220;The cat sat on the mat&#8221; a tokenizer might produce the token sequence: [464,&nbsp;5171,&nbsp;7231,&nbsp;322,&nbsp;464,&nbsp;8114] Each integer is an index into a vocabulary table of size \u2223V\u2223|V|, typically between 32,000 and 100,000 entries for modern models. GPT-4 uses a vocabulary of approximately 100,277 tokens. Llama 3 uses 128,256. Byte-Pair Encoding (BPE) The dominant tokenization algorithm used in modern LLMs is Byte-Pair Encoding (BPE), originally a data compression algorithm adapted for NLP by Sennrich et al. in 2016. BPE builds its vocabulary through an iterative merging process: The result is a vocabulary that contains individual characters, common subwords, and frequent whole words. The word &#8220;tokenization&#8221; might be represented as three tokens: token, ization is further split into iz, ation depending on training corpus frequency. This has a critical practical consequence: no word is ever truly unknown to a BPE tokenizer. Any string, including code, URLs, foreign scripts, or novel proper nouns, can be decomposed into its constituent bytes if nothing else matches. This is why BPE-based models generalise to inputs they have never seen verbatim. Token Fertility and Efficiency Not all languages tokenize equally efficiently. English text typically tokenizes at roughly 0.75 tokens per word. Languages with richer morphology, such as Finnish, Turkish, Arabic, or non-Latin scripts, tokenize less efficiently, sometimes requiring 3\u20135 tokens per word. This has practical implications: a context window of 128,000 tokens holds far more English prose than it does Thai or Arabic text, a bias baked into the model&#8217;s architecture from the vocabulary construction stage. The fertility of a tokenizer, or the average number of tokens per word, is a meaningful measure of how well it serves a given language or domain. Code-optimised models like DeepSeek Coder use vocabularies with explicit code tokens to reduce the fertility of common programming constructs. WordPiece and SentencePiece Two notable alternatives to BPE are worth knowing: WordPiece, used in BERT and its derivatives, is similar to BPE but merges pairs that maximise the likelihood of the training data under a language model, rather than simply the most frequent pair. This produces slightly different vocabulary distributions. SentencePiece, used in models including Llama and T5, treats the input as a raw unicode byte stream with no pre-tokenization step (no whitespace splitting). This makes it language-agnostic and particularly well-suited for multilingual models. Stage 2: Token Embeddings The Embedding Matrix Once tokenization has produced a sequence of integer indices [t1,t2,\u2026,tn][t_1, t_2, \\ldots, t_n], each index must be converted into a dense vector. This is done via an embedding matrix WE\u2208R\u2223V\u2223\u00d7dW_E \\in \\mathbb{R}^{|V| \\times d}, where dd is the model&#8217;s hidden dimension (also called the embedding dimension or dmodeld_{\\text{model}}\u200b). The embedding for token tit_iti\u200b is simply a row lookup:ei=WE[ti]\u2208Rd\\mathbf{e}_i = W_E[t_i] \\in \\mathbb{R}^dIn GPT-3, d=12288d = 12288. In Llama 3 8B, d=4096d = 4096. This single matrix, learned entirely from data during pre-training, is responsible for encoding the semantic relationships between all tokens in the vocabulary. The number of parameters in the embedding matrix alone is \u2223V\u2223\u00d7d|V| \\times d. For GPT-4&#8217;s approximate configuration, that is 100,277\u00d7dmodel100{,}277 \\times d_{\\text{model}} which is often hundreds of millions of parameters just for this one component. Why Dense Vectors Work: The Geometry of Meaning The remarkable property of learned embeddings is that semantic relationships emerge as geometric relationships in Rd\\mathbb{R}^d. The classic demonstration is the linear analogy: e(&#8220;king&#8221;)\u2212e(&#8220;man&#8221;)+e(&#8220;woman&#8221;)\u2248e(&#8220;queen&#8221;)\\mathbf{e}(\\text{&#8220;king&#8221;}) &#8211; \\mathbf{e}(\\text{&#8220;man&#8221;}) + \\mathbf{e}(\\text{&#8220;woman&#8221;}) \\approx \\mathbf{e}(\\text{&#8220;queen&#8221;}) This is not programmed. It emerges from the statistical structure of co-occurrence patterns in the training corpus. Words that appear in similar contexts end up with similar embedding vectors, measured by cosine similarity:sim(u,v)=u\u22c5v\u2225u\u2225\u2225v\u2225\\text{sim}(\\mathbf{u}, \\mathbf{v}) = \\frac{\\mathbf{u} \\cdot \\mathbf{v}}{\\|\\mathbf{u}\\| \\|\\mathbf{v}\\|}In high-dimensional spaces, this geometry becomes extraordinarily rich. Directions in embedding space can encode syntactic roles, semantic fields, sentiment polarities, and factual associations \u2014 all simultaneously, in different orthogonal subspaces of the same Rd\\mathbb{R}^d. Stage 3: Positional Encoding Token embeddings encode what each token is, but they contain no information about where in the sequence each token appears. The sequence &#8220;dog bites man&#8221; and &#8220;man bites dog&#8221; would produce identical sets of token embeddings in a different order and would be catastrophic for a model that needs to understand syntax and word order. Positional information must therefore be injected explicitly. Sinusoidal Positional Encoding (Original Transformer) The original transformer paper (Vaswani et al., 2017) proposed adding a fixed sinusoidal signal to each token embedding. For position pospospos and dimension iii:PE(pos,2i)=sin\u2061\u2009\u2063(pos100002i\/d)PE_{(pos, 2i)} = \\sin\\!\\left(\\frac{pos}{10000^{2i\/d}}\\right) PE(pos,2i+1)=cos\u2061\u2009\u2063(pos100002i\/d)PE_{(pos, 2i+1)} = \\cos\\!\\left(\\frac{pos}{10000^{2i\/d}}\\right) The input to the first transformer layer is then:xi=ei+PEi\\mathbf{x}_i = \\mathbf{e}_i + PE_i The sinusoidal formulation has a useful property: the positional encoding of position pos+kpos + k can be expressed as a linear function of the encoding at pospospos, which makes it easy for attention heads to learn to attend to tokens at a fixed relative offset. Learned Positional Embeddings GPT-2 and GPT-3 replaced sinusoidal encodings with learned positional embeddings: a second matrix WP\u2208Rnmax\u00d7dW_P \\in \\mathbb{R}^{n_{\\text{max}} \\times d}\u200b, where nmaxn_{\\text{max}}\u200b is the maximum context length. Position pospospos adds the row WP[pos]W_P[pos] to the token embedding. These are learned end-to-end during pre-training and tend to slightly outperform sinusoidal encodings on benchmarks, at the cost of a hard context length ceiling \u2014 the model cannot generalise beyond nmaxn_{\\text{max}}\u200b positions it has seen during training. Rotary Positional Embedding (RoPE) The current state of the art for most frontier models, including Llama, Mistral, GPT-4, and Gemini, is Rotary Positional Embedding (RoPE), introduced by Su et al. in 2021. Rather than adding a positional vector to the token embedding, RoPE encodes position by rotating the Query and Key vectors in the attention mechanism (covered in Part 2) by a position-dependent angle. For a vector at position mmm in dimension pair (2i,2i+1)(2i, 2i+1):qm(i)=(q2iq2i+1)(cos\u2061m\u03b8i\u2212sin\u2061m\u03b8isin\u2061m\u03b8icos\u2061m\u03b8i)\\mathbf{q}_m^{(i)} = \\begin{pmatrix} q_{2i} \\\\ q_{2i+1} \\end{pmatrix} \\begin{pmatrix} \\cos m\\theta_i &amp; -\\sin m\\theta_i \\\\ \\sin m\\theta_i &amp; \\cos m\\theta_i \\end{pmatrix} where \u03b8i=10000\u22122i\/d\\theta_i = 10000^{-2i\/d}. The critical advantage: the dot product between a query at position mmm and a key at position nnn depends only on their relative offset m\u2212nm &#8211; n, not their absolute positions. This gives the model a natural inductive bias toward relative position awareness, and with extensions like YaRN makes it possible to extend the effective context window well beyond what the model was trained on. RoPE is why modern models can be fine-tuned to handle 128K or even 1M token context windows without retraining the entire model from scratch. Putting It Together: The Input Representation The final input to the first transformer layer for a sequence of nnn tokens is a matrix X\u2208Rn\u00d7dX \\in \\mathbb{R}^{n \\times d}:X=(e1+p1e2+p2\u22eeen+pn)X = \\begin{pmatrix} \\mathbf{e}_1 + \\mathbf{p}_1 \\\\ \\mathbf{e}_2 + \\mathbf{p}_2 \\\\ \\vdots \\\\ \\mathbf{e}_n + \\mathbf{p}_n \\end{pmatrix}where pi\\mathbf{p}_i is the positional encoding for position ii (sinusoidal, learned, or RoPE-derived). Each row of XX is a dd-dimensional vector carrying both the semantic identity of the token and its position in the sequence. This matrix is what flows into the self-attention mechanism, which is the subject of Part 2. Key Numbers to Anchor Your Intuition Model Vocabulary \u2225V\u2225\\|V\\| dmodeld_{\\text{model}} Positional scheme GPT-2 50,257 768\u20131,600 Learned GPT-3 50,257 12,288 Learned Llama 3 8B 128,256 4,096 RoPE Mistral 7B 32,000 4,096 RoPE Gemma 2 256,000 2,304\u20133,584 RoPE Conclusion Before a single attention head fires, a large language model has already done substantial mathematical work. A raw string has been segmented into subword tokens by a BPE or SentencePiece algorithm, each token has been projected into a high-dimensional vector space where geometry encodes meaning, and position information has been woven in either additively or, in modern models, rotationally via RoPE. The quality of this input representation has an outsized effect on everything downstream: models with poorly constructed vocabularies or weak embedding initialisations are harder to train and less capable at convergence. Part 2 will take this matrix X\u2208Rn\u00d7dX \\in \\mathbb{R}^{n \\times d} and walk through exactly what the self-attention mechanism does with it, including the full mathematical derivation of scaled dot-product attention, multi-head attention, and what different heads actually learn to represent. Coming next in the AI Engineering series is Part 2: The Attention Mechanism.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[38],"tags":[],"class_list":["post-1030","post","type-post","status-publish","format-standard","hentry","category-ai-theory"],"_links":{"self":[{"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/posts\/1030","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/comments?post=1030"}],"version-history":[{"count":2,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/posts\/1030\/revisions"}],"predecessor-version":[{"id":1039,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/posts\/1030\/revisions\/1039"}],"wp:attachment":[{"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/media?parent=1030"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/categories?post=1030"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnerbox.net\/blog\/wp-json\/wp\/v2\/tags?post=1030"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}