<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Swayammhaskar on Medium]]></title>
        <description><![CDATA[Stories by Swayammhaskar on Medium]]></description>
        <link>https://medium.com/@swayammhaskar01?source=rss-e1170c1c2fe8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*q7fic6cNmeMDdD_wjRdFNQ.jpeg</url>
            <title>Stories by Swayammhaskar on Medium</title>
            <link>https://medium.com/@swayammhaskar01?source=rss-e1170c1c2fe8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:07:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swayammhaskar01/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SLMs-01 Tokenization: Byte Pair Encoding (BPE)]]></title>
            <link>https://medium.com/building-a-small-language-model-from-scratch/slms-01-tokenization-byte-pair-encoding-bpe-82d3503a7433?source=rss-e1170c1c2fe8------2</link>
            <guid isPermaLink="false">https://medium.com/p/82d3503a7433</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[byte-pair-encoding]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[small-language-model]]></category>
            <dc:creator><![CDATA[Swayammhaskar]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 18:14:54 GMT</pubDate>
            <atom:updated>2026-11-23T14:45:12.898Z</atom:updated>
            <content:encoded><![CDATA[<h3>SLMs-01: Byte Pair Encoding (BPE)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKdrthirGWP7TKnDv2yU_A.png" /></figure><h3>Table of Contents</h3><ol><li><a href="#bd02"><strong>Introduction</strong></a></li><li><a href="#8855"><strong>Tokenization Techniques</strong></a></li><li><a href="#233d"><strong>The Intuition Behind Byte Pair Encoding (BPE)</strong></a></li><li><a href="#91f1"><strong>Implementation</strong></a></li><li><a href="#43e7"><strong>Conclusion</strong></a></li></ol><h3><strong>Introduction</strong></h3><p>Before jumping into fancy Transformer architectures, we first need to understand one of the most fundamental building blocks of language models: <strong>Tokenization</strong>.</p><p>How does an LLM actually understand and generate text?</p><p>Well, LLMs don’t directly process text written in human language like English or Marathi. They work with numerical representations of text called <strong>tokens</strong>. Before any text reaches the model, it is broken down into smaller units and converted into numbers that the neural network can process.</p><p>At their core, these models perform mathematical operations on numerical data. They don’t read language the way humans do; instead, they learn statistical patterns and relationships between tokens to predict what comes next.</p><h3>Tokenization Techniques</h3><p>There are multiple ways to break text into smaller units, and each approach comes with its own advantages and limitations.</p><h4>1. Word-Level Tokenization</h4><p>The simplest approach is to split text into individual words.</p><pre>&quot;A little progress is still progress.&quot;</pre><p>becomes</p><pre><strong>Tokens:</strong><br>[&quot;A&quot;, &quot;little&quot;, &quot;progress&quot;, &quot;is&quot;, &quot;still&quot;, &quot;progress&quot;, &quot;.&quot;]</pre><p>Each unique word gets its own token ID.</p><p><strong>The problem:</strong> Language is incredibly diverse. New words, misspellings, and variations can lead to an ever-growing vocabulary. This is known as the Out-of-Vocabulary (OOV) problem.</p><h4>2. Character-Level Tokenization</h4><p>Instead of splitting text into words, we split it into individual characters.</p><pre>&quot;Hello.&quot;</pre><p>becomes</p><pre><strong>Tokens:</strong><br>[&quot;H&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;, &quot;.&quot;]</pre><p>This approach has a very small vocabulary and can represent almost any word.</p><p><strong>The problem:</strong> A single word now requires multiple tokens. This creates longer sequences, making training and processing more computationally expensive. It also makes it harder for the model to learn meaningful word-level patterns.</p><h4>3. Subword Tokenization</h4><p>Subword tokenization gives a middle ground between word-level and character-level approaches.</p><p>It breaks words into smaller meaningful units, allowing the model to reuse common word fragments.</p><pre>&quot;Tokenization makes language models powerful.&quot;</pre><p>becomes</p><pre><strong>Tokens:</strong><br>[&quot;Token&quot;, &quot;ization&quot;, &quot; makes&quot;, &quot; language&quot;, &quot; models&quot;, &quot; powerful&quot;, &quot;.&quot;]</pre><p>Popular subword tokenization algorithms include:</p><ul><li><strong>BPE (Byte Pair Encoding):</strong> Builds a vocabulary by repeatedly merging frequently occurring token pairs.</li><li><strong>WordPiece:</strong> Uses a statistical scoring approach to learn useful subword units.</li><li><strong>Unigram Language Model:</strong> Starts with a large vocabulary and removes less useful tokens based on probability.</li></ul><h3><strong>The Intuition Behind Byte Pair Encoding (BPE)</strong></h3><p>The main intuition behind BPE is to start with the smallest possible units (bytes) and gradually merge frequently occurring pairs to create larger tokens.</p><p>Instead of manually defining words as tokens, BPE learns useful subword units from the training data.</p><h4>Step-by-step Algorithm</h4><p>1. Start with byte-level tokenization: Convert the input text into its UTF-8 byte representation, treating each byte as an individual token.</p><blockquote>Example: Hello → 72, 101, 108, 108, 111 (UTF-8 byte values).</blockquote><p>2. Count adjacent pairs: Find how frequently each pair of consecutive bytes/tokens occurs in the training corpus.</p><blockquote>Example: (72, 101), (101, 108), (108, 108), (108, 111).</blockquote><p>3. Find the most frequent pair: Identify the adjacent pair that occurs most frequently across the corpus. If ll occurs frequently in the corpus, merge it into a single token to reduce the token count.</p><p>4. Merge the pair: Combine the most frequent pair into a single new token.</p><blockquote>Example: (108, 108) → 108108 (a new merged token representing ll).</blockquote><p>5. Update the vocabulary: Add the newly merged token to the vocabulary and replace its occurrences in the corpus.</p><p>6. Repeat the process: Recalculate adjacent pair frequencies and continue merging the most frequent pairs.</p><p>It will be easier to understand the process with a simple example.</p><pre>low<br>lower<br>lowest</pre><p>Here is our massive corpus that we’ll feed into the tokenizer for training. First, we convert the entire corpus into UTF-8 encoded bytes.</p><pre>low      → 108 111 119<br>lower    → 108 111 119 101 114<br>lowest   → 108 111 119 101 115 116</pre><p>We form all adjacent byte pairs and count how frequently each pair appears in the corpus.</p><pre><strong>Pairs:</strong><br>(l, o)  (o, w)<br>(l, o)  (o, w)  (w, e)  (e, r)<br>(l, o)  (o, w)  (w, e)  (e, s)  (s, t)<br><br><strong>Byte pairs:</strong><br>(108, 111)  (111, 119)<br>(108, 111)  (111, 119)  (119, 101)  (101, 114)<br>(108, 111)  (111, 119)  (119, 101)  (101, 115)  (115, 116)</pre><p>Below are the frequency counts of each adjacent pair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LlaJoZFJULf8_x6By45Mw.png" /></figure><p>Now, we repeatedly merge the most frequent adjacent byte pairs.</p><p><strong>New Token:</strong> &quot;lo&quot; → 108 + 111 = [108, 111]</p><p>so the new pairs will become</p><pre>Pairs:<br>(lo, w)<br>(lo, w) (w, e)  (e, r)<br>(lo, w) (w, e)  (e, s)  (s, t)<br><br>Byte pairs:<br>([108, 111], 119)<br>([108, 111], 119) (119, 101)  (101, 114)<br>([108, 111], 119) (119, 101)  (101, 115)  (115, 116)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5gu41B2XzRS8MYA7n2pVQ.png" /></figure><p>We continue the merge loop until we obtain the final set of tokens: l, o, w, e, r, s, t, lo, low, lowe, st</p><h3><strong>Implementation</strong></h3><p>Let’s now look at the Python implementation. This is my own simplified version, not optimized for performance, so take it with a grain of salt.</p><p>We replace the tokens with ids so “lo” [108, 111] → 257 (id)</p><pre>vocab: dict[int, bytes] = {}<br>inverse_vocab: dict[bytes, int] = {}<br>bpe_merges: dict[tuple[int, int]] = {}</pre><ul><li>vocab: Maps each token ID to its corresponding byte sequence.</li><li>inverse_vocab: Maps each byte sequence back to its token ID.</li><li>bpe_merges: Stores each merged pair of token IDs along with the newly assigned token ID.</li></ul><pre># Base vocab made up of individual utf-8 bytes<br>for i in range(256):<br>    byte_val = bytes([i])<br>    vocab[i] = byte_val<br>    inverse_vocab[byte_val] = i<br><br># Converts the entire corpus into UTF-8 encoded bytes.<br>tokens = list(text.encode(&quot;utf-8&quot;))</pre><pre>@staticmethod<br>def find_best_pair(token_ids):<br>    if len(token_ids) &lt; 2:<br>        return None<br><br>    pairs = Counter(pairwise(token_ids))<br><br>    return max(pairs, key=pairs.get)</pre><p>Above function finds the most frequent byte-pair</p><pre># BPE merge loop starts here<br># num_merges = vocab_size - base_vocab_size + num_special_tokens<br>for new_id in range(len(vocab), vocab_size):<br>    best_pair_token = self.find_best_pair(token_ids)<br>    if best_pair_token is None:<br>        break<br><br>    new_token_ids = []<br>    i = 0<br><br>    while i &lt; len(tokens):<br>        # Check if the current pair matches the best pair<br>        if (<br>            i &lt; len(tokens) - 1<br>            and (token_ids[i], token_ids[i + 1]) == best_pair_token<br>        ):<br>            new_token_ids.append(new_id)  # Replace pair with the new token ID<br>            i += 2  # Skip the next element since it was merged<br>        else:<br>            new_token_ids.append(token_ids[i])<br>            i += 1  # Move to the next token<br><br>    token_ids = new_token_ids<br><br>    p0, p1 = best_pair_token<br>    merged_token = self.vocab[p0] + self.vocab[p1]<br>    self.bpe_merges[best_pair_token] = new_id<br>    self.vocab[new_id] = merged_token<br>    self.inverse_vocab[merged_token] = new_id</pre><p>num_merges = vocab_size — base_vocab_size + num_special_tokens</p><p>This formula tells us how many merge operations BPE needs to perform to reach the desired vocabulary size. like for gpt-2 there are 50,257 tokens</p><ul><li>best_pair_token = self.find_best_pair(token_ids): finds the best pair</li></ul><p>The loop replaces the most frequent adjacent token pair with a single new token, updating the corpus</p><pre>lo, w<br>lo, w, e, r<br>lo, w, e, s, t</pre><p>• merged_token = vocab[p0] + vocab[p1]: Combines the byte sequences of two tokens to create a new merged token (e.g., l + o → lo).</p><p>• bpe_merges[best_pair_token] = new_id: Stores the merged pair along with its newly assigned token ID.</p><p>• vocab[new_id] = merged_token: Adds the new token to the vocabulary by mapping its ID to its byte sequence.</p><p>• inverse_vocab[merged_token] = new_id: Updates the reverse vocabulary by mapping the merged token back to its ID.</p><p>And continue the merge loop till required vocab size is reached</p><pre>def encode(self, text):<br>    token_ids = list(text.encode(&quot;utf-8&quot;))<br><br>    for pair, new_id in self.bpe_merges.items():<br>        i = 0<br>        while i &lt; len(token_ids) - 1:<br>            if (token_ids[i], token_ids[i + 1]) == pair:<br>                token_ids[i:i+2] = [new_id]<br>            else:<br>                i += 1<br><br>    return token_ids</pre><p>Now we use the bpe_merges to iteratively make pairs into tokens that we learned from the training corpus.</p><p>Take a look at the code it just loops over the text and finds weather that pair is a valid token as per bpe_merges if it is then combine it and map to its token id. At the end you end up with a stream of tokens that the LLMs take as input.</p><p>Now we know that LLMs predict the next token and output a token stream so we now need to decode that so that we can understand it.</p><pre>def decode(self, token_ids):<br>    byte_sequence = b&quot;&quot;.join(<br>        self.vocab[token_id] for token_id in token_ids<br>    )<br><br>    return byte_sequence.decode(&quot;utf-8&quot;, errors=&quot;replace&quot;)</pre><p>Decoding is straight forward we get the tokens from our model then map it to corresponding bytes in vocabulary and decode using utf-8 because we encoded the text so you know the drill.</p><blockquote>Example: 257 → [108, 111] we get these bytes from vocab[int, bytes]</blockquote><p>then decoding it gives [108, 111] → [“l”, “o”]</p><h3><strong>Conclusion</strong></h3><p>BPE efficiently converts text into numerical token IDs by repeatedly merging frequently occurring pairs. We learned how to train a tokenizer, build its vocabulary, encode text into token IDs, and decode those IDs back into readable text.</p><p>Now we understand how raw text becomes the token stream that an LLM processes to generate language.</p><p>In future posts, we’ll dive deeper into building our own Small Language Model (SLM). Stay tuned!</p><p>Feedback, suggestions, and constructive criticism are always welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82d3503a7433" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-a-small-language-model-from-scratch/slms-01-tokenization-byte-pair-encoding-bpe-82d3503a7433">SLMs-01 Tokenization: Byte Pair Encoding (BPE)</a> was originally published in <a href="https://medium.com/building-a-small-language-model-from-scratch">Building a Small Language Model from Scratch</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>