<?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 Mohammedsafa on Medium]]></title>
        <description><![CDATA[Stories by Mohammedsafa on Medium]]></description>
        <link>https://medium.com/@mohammed-safa?source=rss-7d2805a6d963------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TzQjadY7kbDh_dDomNWSJg.jpeg</url>
            <title>Stories by Mohammedsafa on Medium</title>
            <link>https://medium.com/@mohammed-safa?source=rss-7d2805a6d963------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:01:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohammed-safa/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[Why LLMs Break Words Into Weird Pieces: BPE vs WordPiece Explained Clearly]]></title>
            <link>https://mohammed-safa.medium.com/why-llms-break-words-into-weird-pieces-bpe-vs-wordpiece-explained-clearly-7d8c8a30e0d2?source=rss-7d2805a6d963------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d8c8a30e0d2</guid>
            <category><![CDATA[wordpiece]]></category>
            <category><![CDATA[byte-pair-encoding]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Mohammedsafa]]></dc:creator>
            <pubDate>Mon, 04 May 2026 07:01:02 GMT</pubDate>
            <atom:updated>2026-05-04T07:14:29.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNYumMD96V3a4NfcyNCLYA.png" /></figure><p>unbelievable → [“un”, “##believ”, “##able”]</p><p>or</p><p>hello world → [“hello”, “Ġworld”]</p><blockquote>Before a Transformer can process text, the text must be broken into tokens and converted into IDs.<br>This step looks simple, but it affects context length, cost, unknown words, multilingual performance, and even how models “see” text.</blockquote><h4>So why does Tokenization exist?</h4><p>Transformers do <strong>not</strong> read raw text directly. They read <strong>token IDs</strong>.</p><p>text → tokens → token IDs → embeddings → Transformer</p><p>Tokenization is the bridge between human text and Transformer numbers.</p><h3>1. Types of tokenization</h3><h4>Word-level tokenization</h4><p>It stores the full words.</p><p><strong>Example:</strong></p><blockquote>“playing football” → [“playing”, “football”]</blockquote><p><strong>Problems:</strong></p><ul><li>vocabulary becomes huge</li><li>rare words get bad embeddings</li><li>unseen words may become [UNK]</li><li>related words may not share information</li></ul><p><strong>Example:</strong></p><ul><li>cat</li><li>cats</li><li>catlike</li><li>catty</li></ul><p>A word-level tokenizer may treat these as unrelated tokens.</p><h4>Character-level tokenization</h4><p>It splits the words into letters.</p><p><strong>Example:</strong></p><blockquote>playing → [&quot;p&quot;, &quot;l&quot;, &quot;a&quot;, &quot;y&quot;, &quot;i&quot;, &quot;n&quot;, &quot;g&quot;]</blockquote><p><strong>Good:</strong></p><ul><li>handles unseen words</li><li>small vocabulary</li></ul><p><strong>Bad:</strong></p><ul><li>sequences become long</li><li>attention becomes expensive</li><li>characters have weak meaning alone</li></ul><p>Transformer self-attention cost is roughly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/51/0*lH31cFlte0IsGyJf.png" /></figure><h4>Subword-level tokenization</h4><p>It is the middle ground.</p><p><strong>Examples:</strong></p><ul><li>playing → [&quot;play&quot;, &quot;ing&quot;]</li><li>cats → [&quot;cat&quot;, &quot;s&quot;]</li><li>unbelievable → [&quot;un&quot;, &quot;believ&quot;, &quot;able&quot;]</li></ul><p><strong>Benefits:</strong></p><ul><li>smaller vocabulary than word-level</li><li>shorter sequences than character-level</li><li>better handling of rare/unseen words</li><li>shared meaning across related words</li></ul><h3>2. Byte-Pair Encoding — BPE</h3><blockquote>BPE starts with small units and repeatedly merges the most frequent neighboring pair.</blockquote><p><strong>Example corpus:</strong></p><ul><li>low</li><li>lower</li><li>lowest</li></ul><p><strong>Initial:</strong></p><ul><li>l o w</li><li>l o w e r</li><li>l o w e s t</li></ul><p><strong>Merge frequent pairs:</strong></p><pre>l + o → lo<br>lo + w → low<br>e + s → es<br>es + t → est</pre><p><strong>Final example:</strong></p><blockquote>lowest → [“low”, “est”]</blockquote><h3>2.2 BPE math</h3><p>For a pair ((a,b)), count how often (a) appears immediately before (b).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/0*lvUph_g6UW-K_nhv.png" /></figure><p><strong>Where:</strong></p><ul><li>(w_i) = word type</li><li>(f_i) = frequency of word (w_i)</li><li>(#_{w_i}(a,b)) = number of times pair ((a,b)) appears in (w_i)</li></ul><p><strong>BPE chooses:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/0*JV52Uy8ZZSBpi-yn.png" /></figure><p><strong>Then merges:</strong></p><blockquote>a* b* → a*b*</blockquote><h4>Intuition</h4><blockquote>At each step, BPE chooses the adjacent pair with the highest count.</blockquote><h3>2.3 BPE from-scratch code (Basic version)</h3><p><strong>Train Phase</strong></p><pre>from collections import Counter<br><br><br>def split_word(corpus: dict )-&gt; dict:<br>    &quot;&quot;&quot;<br>    summary: Split the word into char-level and add end of the word label &quot;&lt;/w&gt;&quot;<br><br>    Args:<br>        corpus (dict): A dictionary contains words and thier frequencies<br><br>    Return:<br>        new_corpus (dict): A dictionary after splitting the words <br>    &quot;&quot;&quot;<br><br>    new_corpus = {<br>        tuple(word) + (&quot;&lt;/w&gt;&quot;,) : freq for word, freq in corpus.items()<br>    }<br><br>    return new_corpus<br><br>def get_pair_counts(corpus: dict)-&gt; Counter:<br>    &quot;&quot;&quot;<br>    summary: Get the pair counts of each two adjacent letters <br><br>    Args:<br>        corpus (dict): A dictionary contains words at letter-level and thier frequencies<br><br>    Return:<br>        pairs (Counter): A counter that contain the pairs and thier frequencies<br>    &quot;&quot;&quot;<br><br>    pairs = Counter()<br><br>    for symbols, freq in corpus.items():<br>        for i in range(len(symbols) - 1):<br>            pairs[symbols[i], symbols[i+1]] += freq<br>    <br>    return pairs<br><br><br>def merge_pair(pair: Counter, corpus:dict)-&gt; dict:<br>    &quot;&quot;&quot;<br>    summary: Merge pairs based on the highest count<br><br>    Args:<br>        pair (tuple): A tuple that contain the best pair<br>        corpus (dict): A dictionary contains words at letter-level and thier frequencies<br><br>    Return:<br>        new_corpus (dict): A dictionary that holds the new vocab after updating the merges<br>        merged (list): A list that holds the merged pair BPE style.  <br>    &quot;&quot;&quot;<br><br>    new_corpus = {}<br>    merged = pair[0] + pair[1]<br><br>    for symbols, freq in corpus.items():<br>        new_symbol = []<br>        i = 0<br>        while i &lt; len(symbols):<br>            if i &lt; len(symbols) - 1 and (symbols[i], symbols[i+1]) == pair:<br>                new_symbol.append(merged)<br>                i += 2<br>            else:<br>                new_symbol.append(symbols[i])<br>                i += 1<br>        new_corpus[tuple(new_symbol)] = freq<br>    <br>    return new_corpus , merged<br><br><br>def train_bpe(corpus: dict, num_merges: int)-&gt; tuple[list, dict]:<br>    &quot;&quot;&quot;<br>    Summary: Train a tiny educational BPE tokenizer.<br><br>    Args:<br>        corpus (dict): A dictionary contains words and thier frequencies<br>        num_merges (int): A num of iterations to merge<br><br>    Returns:<br>        vocab (set): final compressed vocabulary representation<br>        merges (list): ordered list of merge rules<br>        corpus (dict): final compressed vocabulary representation with thier freqs<br>    &quot;&quot;&quot;<br>    corpus = split_word(corpus)<br><br>    vocab = set()<br>    for pieces in corpus.keys():<br>        vocab.update(pieces)<br><br>    merges = []<br><br>    print(&quot;Initial corpus:&quot;)<br>    for pieces, freq in corpus.items():<br>        print(f&quot;  {pieces}: {freq}&quot;)<br><br>    for step in range(num_merges):<br>        pair_counts = get_pair_counts(corpus)<br><br>        if not pair_counts: break<br><br>        best_pair = max(pair_counts, key=pair_counts.get)<br>        best_count = pair_counts[best_pair]<br>        <br>        corpus, merged_token = merge_pair(best_pair, corpus)<br>        merges.append((best_pair, merged_token))<br>        vocab.add(merged_token)<br><br>        print(f&quot;\nStep {step + 1}&quot;)<br>        print(f&quot;Best pair: {best_pair}, count={best_count}&quot;)<br>        print(f&quot;Merged token: {merged_token}&quot;)<br>        print(&quot;Updated corpus:&quot;)<br><br>        for pieces, freq in corpus.items():<br>            print(f&quot;  {pieces}: {freq}&quot;)<br><br>    return vocab, merges, corpus<br>corpus = {<br>    &quot;low&quot;: 5,<br>    &quot;lower&quot;: 2,<br>    &quot;newest&quot;: 6,<br>    &quot;widest&quot;: 3,<br>    &quot;newer&quot;: 4<br>}<br><br>bpe_vocab, bpe_merges, bpe_corpus = train_bpe(corpus, num_merges=6)</pre><p><strong>The output:</strong></p><pre>Initial corpus:<br>  (&#39;l&#39;, &#39;o&#39;, &#39;w&#39;, &#39;&lt;/w&gt;&#39;): 5<br>  (&#39;l&#39;, &#39;o&#39;, &#39;w&#39;, &#39;e&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 2<br>  (&#39;n&#39;, &#39;e&#39;, &#39;w&#39;, &#39;e&#39;, &#39;s&#39;, &#39;t&#39;, &#39;&lt;/w&gt;&#39;): 6<br>  (&#39;w&#39;, &#39;i&#39;, &#39;d&#39;, &#39;e&#39;, &#39;s&#39;, &#39;t&#39;, &#39;&lt;/w&gt;&#39;): 3<br>  (&#39;n&#39;, &#39;e&#39;, &#39;w&#39;, &#39;e&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 4<br><br>Step 1<br>Best pair: (&#39;w&#39;, &#39;e&#39;), count=12<br>Merged token: we<br>Updated corpus:<br>  (&#39;l&#39;, &#39;o&#39;, &#39;w&#39;, &#39;&lt;/w&gt;&#39;): 5<br>  (&#39;l&#39;, &#39;o&#39;, &#39;we&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 2<br>  (&#39;n&#39;, &#39;e&#39;, &#39;we&#39;, &#39;s&#39;, &#39;t&#39;, &#39;&lt;/w&gt;&#39;): 6<br>  (&#39;w&#39;, &#39;i&#39;, &#39;d&#39;, &#39;e&#39;, &#39;s&#39;, &#39;t&#39;, &#39;&lt;/w&gt;&#39;): 3<br>  (&#39;n&#39;, &#39;e&#39;, &#39;we&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 4<br><br>Step 2<br>Best pair: (&#39;n&#39;, &#39;e&#39;), count=10<br>Merged token: ne<br>Updated corpus:<br>  (&#39;l&#39;, &#39;o&#39;, &#39;w&#39;, &#39;&lt;/w&gt;&#39;): 5<br>  (&#39;l&#39;, &#39;o&#39;, &#39;we&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 2<br>  (&#39;ne&#39;, &#39;we&#39;, &#39;s&#39;, &#39;t&#39;, &#39;&lt;/w&gt;&#39;): 6<br>  (&#39;w&#39;, &#39;i&#39;, &#39;d&#39;, &#39;e&#39;, &#39;s&#39;, &#39;t&#39;, &#39;&lt;/w&gt;&#39;): 3<br>  (&#39;ne&#39;, &#39;we&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 4<br><br>Step 3<br>Best pair: (&#39;ne&#39;, &#39;we&#39;), count=10<br>Merged token: newe<br>Updated corpus:<br>  (&#39;l&#39;, &#39;o&#39;, &#39;w&#39;, &#39;&lt;/w&gt;&#39;): 5<br>  (&#39;l&#39;, &#39;o&#39;, &#39;we&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 2<br>  (&#39;newe&#39;, &#39;s&#39;, &#39;t&#39;, &#39;&lt;/w&gt;&#39;): 6<br>  (&#39;w&#39;, &#39;i&#39;, &#39;d&#39;, &#39;e&#39;, &#39;s&#39;, &#39;t&#39;, &#39;&lt;/w&gt;&#39;): 3<br>  (&#39;newe&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 4<br><br>Step 4<br>Best pair: (&#39;s&#39;, &#39;t&#39;), count=9<br>Merged token: st<br>Updated corpus:<br>  (&#39;l&#39;, &#39;o&#39;, &#39;w&#39;, &#39;&lt;/w&gt;&#39;): 5<br>  (&#39;l&#39;, &#39;o&#39;, &#39;we&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 2<br>  (&#39;newe&#39;, &#39;st&#39;, &#39;&lt;/w&gt;&#39;): 6<br>  (&#39;w&#39;, &#39;i&#39;, &#39;d&#39;, &#39;e&#39;, &#39;st&#39;, &#39;&lt;/w&gt;&#39;): 3<br>  (&#39;newe&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 4<br><br>Step 5<br>Best pair: (&#39;st&#39;, &#39;&lt;/w&gt;&#39;), count=9<br>Merged token: st&lt;/w&gt;<br>Updated corpus:<br>  (&#39;l&#39;, &#39;o&#39;, &#39;w&#39;, &#39;&lt;/w&gt;&#39;): 5<br>  (&#39;l&#39;, &#39;o&#39;, &#39;we&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 2<br>  (&#39;newe&#39;, &#39;st&lt;/w&gt;&#39;): 6<br>  (&#39;w&#39;, &#39;i&#39;, &#39;d&#39;, &#39;e&#39;, &#39;st&lt;/w&gt;&#39;): 3<br>  (&#39;newe&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 4<br><br>Step 6<br>Best pair: (&#39;l&#39;, &#39;o&#39;), count=7<br>Merged token: lo<br>Updated corpus:<br>  (&#39;lo&#39;, &#39;w&#39;, &#39;&lt;/w&gt;&#39;): 5<br>  (&#39;lo&#39;, &#39;we&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 2<br>  (&#39;newe&#39;, &#39;st&lt;/w&gt;&#39;): 6<br>  (&#39;w&#39;, &#39;i&#39;, &#39;d&#39;, &#39;e&#39;, &#39;st&lt;/w&gt;&#39;): 3<br>  (&#39;newe&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;): 4</pre><p><strong>Inference:</strong></p><pre>def bpe_tokenize_word(word: str, merges: list, unk_token: str=&quot;[UNK]&quot;, max_chars_per_word: int=100):<br>    &quot;&quot;&quot;<br>    Summary: Tokenize a word using learned BPE merges.<br><br>    Args:<br>        word (str): A word input<br>        merges (list): A list that contains the merge rules<br>        unk_token (str): Unknown token [UNK] <br>        max_chars_per_word (int): Maximum length <br><br>    Return:<br>        tokens (list): A list contains the tokenization<br>        <br>    &quot;&quot;&quot;<br>    if len(word) &gt; max_chars_per_word:<br>        return [unk_token]<br>    <br>    tokens = list(word) + [&quot;&lt;/w&gt;&quot;]<br><br>    for pair, res in merges:<br>        new_tokens = []<br>        i = 0<br><br>        while i &lt; len(tokens):<br>            if i &lt; len(tokens) - 1 and (tokens[i], tokens[i+1]) == pair:<br>                new_tokens.append(res)<br>                i += 2<br>            else:<br>                new_tokens.append(tokens[i])<br>                i += 1<br><br>        tokens = new_tokens<br><br>    return tokens<br><br>def clean_bpe_output(tokens: list)-&gt; list:<br>    &quot;&quot;&quot;<br>    Summary: Remove or prettify &lt;/w&gt; marker.<br><br>    Args: <br>        tokens (list):  A list contains the tokenization<br><br>    Return:<br>        cleaned (list): A list contains the cleaned tokenization<br>    &quot;&quot;&quot;<br>    cleaned = []<br><br>    for symbol in tokens:<br>        if symbol == &quot;&lt;/w&gt;&quot;:<br>            continue<br>        elif symbol.endswith(&quot;&lt;/w&gt;&quot;):<br>            cleaned.append(symbol.replace(&quot;&lt;/w&gt;&quot;, &quot;&quot;))<br>        else:<br>            cleaned.append(symbol)<br><br>    return cleaned<br><br>test_word = &quot;newer&quot;<br>tokens = apply_bpe_to_word(test_word, bpe_merges)<br>clean_tokens = clean_bpe_output(tokens)<br>print(test_word)<br>print(&quot;  raw:  &quot;, tokens)<br>print(&quot;  clean:&quot;, clean_tokens)</pre><p><strong>The output:</strong></p><pre>newer<br>  raw:   [&#39;newe&#39;, &#39;r&#39;, &#39;&lt;/w&gt;&#39;]<br>  clean: [&#39;newe&#39;, &#39;r&#39;]</pre><h3>2.4 BPE using Hugging Face</h3><pre>from transformers import AutoTokenizer<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;gpt2&quot;)<br><br>text = &quot;unbelievable tokenization 🙂&quot;<br><br>tokens = tokenizer.tokenize(text)<br><br>print(tokens)</pre><p><strong>The output:</strong></p><pre>[&#39;un&#39;, &#39;bel&#39;, &#39;iev&#39;, &#39;able&#39;, &#39;Ġtoken&#39;, &#39;ization&#39;, &#39;ĠðŁĻĤ&#39;]</pre><blockquote>Exact tokens depend on the tokenizer vocabulary and training data.</blockquote><h3>2.5 BPE edge cases</h3><p>Good edge cases:</p><ul><li>whitespace handling: Ġword</li><li>emojis</li><li>rare Unicode symbols</li><li>code-like text</li><li>weird spacing</li><li>multilingual text</li></ul><p><strong>Example:</strong></p><blockquote>“hello world” → [“hello”, “Ġworld”]</blockquote><p>Explain that Ġ often marks a leading space in GPT-2/RoBERTa-style tokenizers.</p><blockquote>Byte-level BPE reduces unknown-character problems because every string can be represented as bytes.</blockquote><h3>3. WordPiece</h3><blockquote>WordPiece also builds subword units, but instead of simply merging the most frequent pair, it prefers pairs that are strongly associated.</blockquote><p><strong>Examples:</strong></p><ul><li>playing → [&quot;play&quot;, &quot;##ing&quot;]</li><li>cats → [&quot;cat&quot;, &quot;##s&quot;]</li><li>unbelievable → [&quot;un&quot;, &quot;##believ&quot;, &quot;##able&quot;]</li></ul><p><strong>The </strong><strong>## means:</strong></p><p>this piece continues the current word</p><h3>3.2 WordPiece math</h3><p><strong>A common simplified WordPiece score is the following:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/0*eczB8PV1PyWRMOaq.png" /></figure><p><strong>Where:</strong></p><ul><li>freq(a,b) = how often a is followed by b</li><li>freq(a) = how often a appears</li><li>freq(b) = how often b appears</li></ul><p><strong>WordPiece chooses:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/0*hy_IevwanEKLZqtt.png" /></figure><p><strong>WordPiece score intuition</strong></p><ul><li>Pair A:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*i0P9GajVQhOzU8GY.png" /></figure><ul><li>Pair B:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/0*mCn2uxdhNdEOToXZ.png" /></figure><p>Even though er appears more often, WordPiece may prefer qu.</p><blockquote>BPE asks: “How often together?”<br>WordPiece asks: “Do they belong together more than expected?”</blockquote><h3>3.4 WordPiece from-scratch code (Basic version)</h3><pre><br>def wordpiece_initial_split(corpus: dict)-&gt; dict:<br>    &quot;&quot;&quot;<br>    Summary: Split the word into letters and add ## means continuation inside the same word.<br><br>    Args:<br>        corpus (dict): A dictionary contains words and thier frequencies<br><br>    Return:<br>        vocab (dict): A dictionary after splitting the words <br>    &quot;&quot;&quot;<br>    vocab = {}<br><br>    for symbols, freq in corpus.items():<br>        pieces = [symbols[0]]<br>        for char in symbols[1:]:<br>            pieces.append(&quot;##&quot; + char)<br>        vocab[tuple(pieces)] = freq<br>    <br>    return vocab<br> <br>def get_token_freqs(vocab: dict)-&gt; Counter:<br>    &quot;&quot;&quot;<br>    summary: Get the token counts <br><br>    Args:<br>        vocab (dict): A dictionary contains words at letter-level and thier frequencies<br><br>    Return:<br>        token_freqs (Counter): A counter that contains frequencies of each token<br>    &quot;&quot;&quot;<br>    token_freqs = Counter()<br><br>    for pieces, freq in vocab.items():<br>        for piece in pieces:<br>            token_freqs[piece] += freq<br><br>    return token_freqs<br><br><br>def get_pair_counts(vocab: dict)-&gt; Counter:<br>    &quot;&quot;&quot;<br>    summary: Get the pair counts of each two adjacent letters <br><br>    Args:<br>        vocab (dict): A dictionary contains words at letter-level and thier frequencies<br><br>    Return:<br>        pairs (Counter): A counter that contains the pairs and thier frequencies<br>    &quot;&quot;&quot;<br><br>    pairs = Counter()<br><br>    for symbols, freq in vocab.items():<br>        for i in range(len(symbols) - 1):<br>            pairs[symbols[i], symbols[i+1]] += freq<br>    <br>    return pairs<br><br>def compute_wordpiece_scores(vocab: dict)-&gt; tuple[dict, Counter, Counter]: <br>    &quot;&quot;&quot;<br>    summary: Calculate the score of each pair<br><br>    Args:<br>        vocab (dict): A dictionary contains words at letter-level and thier frequencies<br><br>    Returns:<br>        scores (dict): A dictionary that contains the scores for each pair<br>        token_freqs (Counter): A counter that contains frequencies of each token<br>        pair_freqs (Counter): A counter that contains the pairs and thier frequencies<br>    &quot;&quot;&quot;<br><br>    token_freqs = get_token_freqs(vocab)<br>    pair_freqs = get_pair_counts(vocab)<br>    <br>    scores = {}<br><br>    for pair, pair_freq in pair_freqs.items():<br>        a, b = pair<br><br>        score = pair_freq / (token_freqs[a] * token_freqs[b])<br>        scores[pair] = score<br><br>    return scores, token_freqs, pair_freqs<br><br>def merge_wordpiece_pair(pair: Counter, vocab: dict)-&gt; tuple[dict, list]:<br>    &quot;&quot;&quot;<br>    Summary: Merge pair in WordPiece style.<br><br>    Args:<br>        pair (tuple): A tuple that contain the best pair<br>        vocab (dict): A dictionary contains words at letter-level and thier frequencies<br><br>    Returns:<br>        new_vocab (dict): A dictionary that holds the new vocab after updating the merges<br>        merged (list): A list that holds the merged pair WordPiece style.  <br>    &quot;&quot;&quot;<br>    a, b = pair<br><br>    if b.startswith(&quot;##&quot;):<br>        merged = a + b[2:]<br>    else:<br>        merged = a + b<br><br>    new_vocab = {}<br><br>    for pieces, freq in vocab.items():<br>        new_pieces = []<br>        i = 0<br><br>        while i &lt; len(pieces):<br>            if (<br>                i &lt; len(pieces) - 1<br>                and pieces[i] == a<br>                and pieces[i + 1] == b<br>            ):<br>                new_pieces.append(merged)<br>                i += 2<br>            else:<br>                new_pieces.append(pieces[i])<br>                i += 1<br><br>        new_vocab[tuple(new_pieces)] = freq<br><br>    return new_vocab, merged<br><br>def train_wordpiece_tiny(corpus, num_merges):<br>    &quot;&quot;&quot;<br>    Summary: Train a tiny educational WordPiece tokenizer.<br><br>    Args:<br>        corpus (dict): A dictionary contains words and thier frequencies<br>        num_merges (int): A num of iterations to merge<br><br>    Returns:<br>        vocab (set): final compressed vocabulary representation<br>        merges (list): ordered list of merge rules<br>        corpus (dict): final compressed vocabulary representation with thier freqs<br>      <br>    &quot;&quot;&quot;<br>    corpus = wordpiece_initial_split(corpus)<br>    vocab = set()<br><br>    for pieces in corpus.keys():<br>        vocab.update(pieces)<br><br>    merges = []<br><br>    print(&quot;Initial corpus:&quot;)<br>    for pieces, freq in corpus.items():<br>        print(f&quot;  {pieces}: {freq}&quot;)<br><br>    for step in range(num_merges):<br>        scores, _, pair_freqs = compute_wordpiece_scores(corpus)<br><br>        if not scores: break<br><br>        best_pair = max(scores, key=scores.get)<br>        best_score = scores[best_pair]<br>        best_pair_freq = pair_freqs[best_pair]<br><br>        corpus, merged_token = merge_wordpiece_pair(best_pair, corpus)<br>        vocab.add(merged_token)<br>        merges.append((best_pair, merged_token))<br><br>        print(f&quot;\nStep {step + 1}&quot;)<br>        print(f&quot;Best pair: {best_pair}&quot;)<br>        print(f&quot;Pair frequency: {best_pair_freq}&quot;)<br>        print(f&quot;Score: {best_score:.6f}&quot;)<br>        print(f&quot;Merged token: {merged_token}&quot;)<br>        print(&quot;Updated corpus:&quot;)<br><br>        for pieces, freq in corpus.items():<br>            print(f&quot;  {pieces}: {freq}&quot;)<br><br>    return vocab, merges, corpus<br><br>word_freqs = {<br>    &quot;hug&quot;: 10,<br>    &quot;hugs&quot;: 5,<br>    &quot;hugging&quot;: 4,<br>    &quot;bug&quot;: 3,<br>    &quot;bugs&quot;: 2<br>}<br><br>wp_vocab, wp_merges, wp_corpus = train_wordpiece_tiny(word_freqs, num_merges=6)</pre><p><strong>The output:</strong></p><pre>Initial corpus:<br>  (&#39;h&#39;, &#39;##u&#39;, &#39;##g&#39;): 10<br>  (&#39;h&#39;, &#39;##u&#39;, &#39;##g&#39;, &#39;##s&#39;): 5<br>  (&#39;h&#39;, &#39;##u&#39;, &#39;##g&#39;, &#39;##g&#39;, &#39;##i&#39;, &#39;##n&#39;, &#39;##g&#39;): 4<br>  (&#39;b&#39;, &#39;##u&#39;, &#39;##g&#39;): 3<br>  (&#39;b&#39;, &#39;##u&#39;, &#39;##g&#39;, &#39;##s&#39;): 2<br><br>Step 1<br>Best pair: (&#39;##i&#39;, &#39;##n&#39;)<br>Pair frequency: 4<br>Score: 0.250000<br>Merged token: ##in<br>Updated corpus:<br>  (&#39;h&#39;, &#39;##u&#39;, &#39;##g&#39;): 10<br>  (&#39;h&#39;, &#39;##u&#39;, &#39;##g&#39;, &#39;##s&#39;): 5<br>  (&#39;h&#39;, &#39;##u&#39;, &#39;##g&#39;, &#39;##g&#39;, &#39;##in&#39;, &#39;##g&#39;): 4<br>  (&#39;b&#39;, &#39;##u&#39;, &#39;##g&#39;): 3<br>  (&#39;b&#39;, &#39;##u&#39;, &#39;##g&#39;, &#39;##s&#39;): 2<br><br>Step 2<br>Best pair: (&#39;h&#39;, &#39;##u&#39;)<br>Pair frequency: 19<br>Score: 0.041667<br>Merged token: hu<br>Updated corpus:<br>  (&#39;hu&#39;, &#39;##g&#39;): 10<br>  (&#39;hu&#39;, &#39;##g&#39;, &#39;##s&#39;): 5<br>  (&#39;hu&#39;, &#39;##g&#39;, &#39;##g&#39;, &#39;##in&#39;, &#39;##g&#39;): 4<br>  (&#39;b&#39;, &#39;##u&#39;, &#39;##g&#39;): 3<br>  (&#39;b&#39;, &#39;##u&#39;, &#39;##g&#39;, &#39;##s&#39;): 2<br><br>Step 3<br>Best pair: (&#39;b&#39;, &#39;##u&#39;)<br>Pair frequency: 5<br>Score: 0.200000<br>Merged token: bu<br>Updated corpus:<br>  (&#39;hu&#39;, &#39;##g&#39;): 10<br>  (&#39;hu&#39;, &#39;##g&#39;, &#39;##s&#39;): 5<br>  (&#39;hu&#39;, &#39;##g&#39;, &#39;##g&#39;, &#39;##in&#39;, &#39;##g&#39;): 4<br>  (&#39;bu&#39;, &#39;##g&#39;): 3<br>  (&#39;bu&#39;, &#39;##g&#39;, &#39;##s&#39;): 2<br><br>Step 4<br>Best pair: (&#39;hu&#39;, &#39;##g&#39;)<br>Pair frequency: 19<br>Score: 0.031250<br>Merged token: hug<br>Updated corpus:<br>  (&#39;hug&#39;,): 10<br>  (&#39;hug&#39;, &#39;##s&#39;): 5<br>  (&#39;hug&#39;, &#39;##g&#39;, &#39;##in&#39;, &#39;##g&#39;): 4<br>  (&#39;bu&#39;, &#39;##g&#39;): 3<br>  (&#39;bu&#39;, &#39;##g&#39;, &#39;##s&#39;): 2<br><br>Step 5<br>Best pair: (&#39;##g&#39;, &#39;##in&#39;)<br>Pair frequency: 4<br>Score: 0.076923<br>Merged token: ##gin<br>Updated corpus:<br>  (&#39;hug&#39;,): 10<br>  (&#39;hug&#39;, &#39;##s&#39;): 5<br>  (&#39;hug&#39;, &#39;##gin&#39;, &#39;##g&#39;): 4<br>  (&#39;bu&#39;, &#39;##g&#39;): 3<br>  (&#39;bu&#39;, &#39;##g&#39;, &#39;##s&#39;): 2<br><br>Step 6<br>Best pair: (&#39;##gin&#39;, &#39;##g&#39;)<br>Pair frequency: 4<br>Score: 0.111111<br>Merged token: ##ging<br>Updated corpus:<br>  (&#39;hug&#39;,): 10<br>  (&#39;hug&#39;, &#39;##s&#39;): 5<br>  (&#39;hug&#39;, &#39;##ging&#39;): 4<br>  (&#39;bu&#39;, &#39;##g&#39;): 3<br>  (&#39;bu&#39;, &#39;##g&#39;, &#39;##s&#39;): 2</pre><p><strong>Inference:</strong></p><pre>def wordpiece_tokenize_word(word: str, vocab: list, unk_token: str=&quot;[UNK]&quot;, max_chars_per_word: int=100):<br>    &quot;&quot;&quot;<br>    Summary: Tokenize a word using learned WordPiece merges.<br><br>    Args:<br>        word (str): A word input<br>        merges (list): A list that contains the merge rules<br>        unk_token (str): Unknown token [UNK] <br>        max_chars_per_word (int): Maximum length <br><br>    Return:<br>        tokens (list): A list contains the tokenization<br>        <br>    &quot;&quot;&quot;<br><br>    if len(word) &gt; max_chars_per_word:<br>        return [unk_token]<br>    <br>    tokens = []<br>    start = 0<br><br>    while start &lt; len(word):<br>        end = len(word)<br>        current_match = None<br>        <br>        while start &lt; end:<br>            piece = word[start:end]<br>            if start &gt; 0:<br>                piece = &quot;##&quot; + piece<br>            <br>            if piece in vocab:<br>                current_match = piece<br>                break<br><br>            end -= 1<br>        <br>        if current_match is None:<br>            return [unk_token]<br>        <br>        tokens.append(current_match)<br><br>        if current_match.startswith(&quot;##&quot;):<br>            matched_length = len(current_match) - 2<br>        else:<br>            matched_length = len(current_match)<br>        <br>        start += matched_length<br>    <br>    return tokens<br><br>def clean_wordpiece_output(tokens: list)-&gt; list:<br>    &quot;&quot;&quot;<br>    Summary: Remove or prettify ## marker.<br><br>    Args: <br>        tokens (list):  A list contains the tokenization<br><br>    Return:<br>        cleaned (list): A list contains the cleaned tokenization<br>    &quot;&quot;&quot;<br>    cleaned = []<br><br>    for symbol in tokens:<br>        <br>        if symbol.startswith(&quot;##&quot;):<br>            cleaned.append(symbol.replace(&quot;##&quot;, &quot;&quot;))<br>        else:<br>            cleaned.append(symbol)<br><br>    return cleaned<br><br><br>test_word = &quot;bugs&quot;<br>tokens = wordpiece_tokenize_word(test_word, wp_vocab)<br>clean_tokens = clean_wordpiece_output(tokens)<br>print(test_word)<br>print(&quot;  raw:  &quot;, tokens)<br>print(&quot;  clean:&quot;, clean_tokens)</pre><p><strong>The output:</strong></p><pre>bugs<br>  raw:   [&#39;bu&#39;, &#39;##g&#39;, &#39;##s&#39;]<br>  clean: [&#39;bu&#39;, &#39;g&#39;, &#39;s&#39;]</pre><h3>3.5 WordPiece with Hugging Face</h3><pre>from transformers import AutoTokenizer<br><br>tokenizer = AutoTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br><br>text = &quot;unbelievable tokenization 🙂&quot;<br><br>tokens = tokenizer.tokenize(text)<br><br>print(tokens)</pre><p><strong>The output:</strong></p><pre>[&#39;unbelievable&#39;, &#39;token&#39;, &#39;##ization&#39;, &#39;[UNK]&#39;]</pre><ul><li>lowercasing for bert-base-uncased</li><li>## continuation tokens</li><li>possible [UNK] depending on input and preprocessing, like emoji &quot;🙂&quot;</li></ul><h3>3.6 WordPiece edge cases</h3><p><strong>Include:</strong></p><ul><li>unknown characters [UNK]</li><li>casing: BERT vs bert-base-uncased</li><li>continuation tokens cannot always stand alone</li><li>punctuation splitting</li><li>languages without whitespace boundaries</li></ul><p><strong>Example</strong>:</p><blockquote>“Playing” with bert-base-uncased may become similar to “playing” because the tokenizer lowercase input</blockquote><h3>4. Conclusion</h3><ul><li>Word-level: short but brittle.</li><li>Character-level: balanced</li><li>BPE: merge what appears together often.</li><li>WordPiece: merge what belongs together strongly.</li></ul><blockquote>Tokenization is not just preprocessing. It affects how many tokens the model sees, how much context fits, how rare words are represented, and how text becomes numbers.</blockquote><p>I hope this guide helped you see inside the “Black Box” of Tokenizer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d8c8a30e0d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Story of Attention from simple math to Modern Shift]]></title>
            <link>https://mohammed-safa.medium.com/story-of-attention-from-simple-math-to-modern-shift-de6bdbfd8316?source=rss-7d2805a6d963------2</link>
            <guid isPermaLink="false">https://medium.com/p/de6bdbfd8316</guid>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[tech-simplified]]></category>
            <category><![CDATA[reduced-rank]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[attention]]></category>
            <dc:creator><![CDATA[Mohammedsafa]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 13:09:37 GMT</pubDate>
            <atom:updated>2026-04-19T13:09:37.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rc_9qNRhLgE6pt8T9WpL-w.png" /></figure><p>Everyone talks about <strong>Attention</strong> as if it’s just one fixed formula.</p><p>But if you treat it as a black box, you’re missing the evolution that led to modern breakthroughs like <strong>LoRA</strong>. The truth? Not all Attention is created equal.</p><p>To understand the variations, you first have to understand the “trio”:</p><ul><li><strong>Query (Q):</strong> What you are looking for.</li><li><strong>Key (K):</strong> What you are looking at (the “index”).</li><li><strong>Value (V):</strong> The actual information you want to extract.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/0*RHCrBBEjlO1zX5O5.png" /></figure><p>It started with a simple question: How do we align two different vector spaces?</p><h3><strong>1. Dot-Product Attention (The Handshake):</strong></h3><h4>Equation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/0*aduzOmXk1ZzK4nNm.png" /></figure><p>Where:</p><ul><li>s = query vector</li><li>h_i = key vector at position i</li></ul><h4>Intuition</h4><p>It measures <strong>cosine-like similarity</strong> between query and key, without any learned parameters.</p><p>It assumes the query and key already live in the same vector space.</p><p>This score will be high if the two vectors point in similar directions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1maK8aP2gy9-4RMcg6IQzA.png" /></figure><h4>Limitation</h4><p>If query and key spaces differ in meaning or dimension, the raw dot product can be unreliable.</p><h4>Code snippet</h4><pre>import torch<br>import torch.nn.functional as F<br><br>def dot_product_attention(query, keys, values, mask=None):<br>    &quot;&quot;&quot;<br>    Compute Dot-Product Attention.<br>    <br>    Args:<br>        query: [batch_size, d_model] - The search vector<br>        keys:  [batch_size, seq_len, d_model] - The index vectors<br>        values: [batch_size, seq_len, d_value] - The information vectors<br>        mask:  [batch_size, seq_len] (optional) - To ignore padding<br>        <br>    Returns:<br>        context_vector: [batch_size, d_value]<br>        attention_weights: [batch_size, seq_len]<br>    &quot;&quot;&quot;<br>    <br>    # 1. Calculate raw alignment scores (the &quot;Handshake&quot;)<br>    # query.unsqueeze(1) shape: [batch, 1, d_model]<br>    # keys.transpose(1, 2) shape: [batch, d_model, seq_len]<br>    scores = torch.bmm(query.unsqueeze(1), keys.transpose(1, 2))<br>    scores = scores.squeeze(1) # [batch, seq_len]<br><br>    if mask is not None:<br>        scores = scores.masked_fill(mask == 0, -1e9)<br><br>    # 3. Get probability distribution via Softmax<br>    weights = F.softmax(scores, dim=-1) # [batch, seq_len]<br><br>    # 4. Apply weights to values to get the final context vector<br>    # weights.unsqueeze(1) shape: [batch, 1, seq_len]<br>    # values shape: [batch, seq_len, d_value]<br>    context = torch.bmm(weights.unsqueeze(1), values)<br>    <br>    return context.squeeze(1), weights</pre><h3>2. Additive (Bahdanau) Attention</h3><h4>Equation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/0*dYYRKvK_UISpEh8F.png" /></figure><p>Where:</p><ul><li>W_1 projects the query</li><li>W_2 projects the key</li><li>v maps the hidden state to a scalar score</li></ul><h4><strong>intuition</strong></h4><p>This treats the query and key as inputs to a <strong>small feed-forward neural network</strong> with one hidden layer and tanh activation.</p><p>The network outputs a non-linear compatibility score.</p><p>Additive attention can handle query and key vectors of different dimensions naturally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKDi-lO8O6gkdGgzYpqNsw.png" /></figure><h4>Limitation</h4><p>Additive attention is slower than dot-product variants because of the extra matrix multiplications and non-linearity</p><h4>Code Snippet</h4><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class AdditiveAttention(nn.Module):<br>    def __init__(self, query_dim, key_dim, hidden_dim):<br>        super(AdditiveAttention, self).__init__()<br>        <br>        # W1 projects the query, W2 projects the keys<br>        self.W1 = nn.Linear(query_dim, hidden_dim, bias=False)<br>        self.W2 = nn.Linear(key_dim, hidden_dim, bias=False)<br>        <br>        # v projects the hidden representation to a single scalar score<br>        self.v = nn.Linear(hidden_dim, 1, bias=False)<br><br>    def forward(self, query, keys, values, mask=None):<br>        &quot;&quot;&quot;<br>        Args:<br>            query: [batch, query_dim]<br>            keys:  [batch, seq_len, key_dim]<br>            values: [batch, seq_len, value_dim]<br>        &quot;&quot;&quot;<br>        # 1. Project Query and Keys to the same hidden dimension<br>        # query_proj: [batch, 1, hidden_dim]<br>        query_proj = self.W1(query).unsqueeze(1) <br>        <br>        # keys_proj: [batch, seq_len, hidden_dim]<br>        keys_proj = self.W2(keys) <br>        <br>        # 2. Add them and pass through tanh (The MLP bottleneck)<br>        # combined: [batch, seq_len, hidden_dim]<br>        combined = torch.tanh(query_proj + keys_proj)<br>        <br>        # 3. Calculate raw scores<br>        # scores: [batch, seq_len, 1] -&gt; squeeze to [batch, seq_len]<br>        scores = self.v(combined).squeeze(-1)<br><br>        # 4. Masking (if needed)<br>        if mask is not None:<br>            scores = scores.masked_fill(mask == 0, -1e9)<br><br>        # 5. Softmax to get Attention Weights<br>        weights = F.softmax(scores, dim=-1) # [batch, seq_len]<br><br>        # 6. Context vector (Weighted sum of values)<br>        # context: [batch, value_dim]<br>        context = torch.bmm(weights.unsqueeze(1), values).squeeze(1)<br><br>        return context, weights</pre><h3>3. Multiplicative (Luong) Attention</h3><h4>Equation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/0*ipV29RTU6K_0LP5x.png" /></figure><p>Where:</p><ul><li>W is a learned weight matrix</li></ul><h4>Intuition</h4><p>The matrix W learns:</p><ul><li>which dimensions matter for matching</li><li>how to “rotate” the key space to align with the query space</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cmnXY18HAs1mPZifveh2XA.png" /></figure><h4>Limitation</h4><p>For large dimensions, the matrix can be very expensive in parameters and memory.</p><h4>Code Snippet</h4><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class MultiplicativeAttention(nn.Module):<br>    def __init__(self, query_dim, key_dim):<br>        super(MultiplicativeAttention, self).__init__()<br>        <br>        # The weight matrix W that &quot;rotates&quot; the key space <br>        # to align with the query space.<br>        # Shape: [key_dim, query_dim]<br>        self.W = nn.Linear(key_dim, query_dim, bias=False)<br><br>    def forward(self, query, keys, values, mask=None):<br>        &quot;&quot;&quot;<br>        Args:<br>            query: [batch, query_dim]<br>            keys:  [batch, seq_len, key_dim]<br>            values: [batch, seq_len, value_dim]<br>        &quot;&quot;&quot;<br>        # 1. Transform the keys using the weight matrix W<br>        # projected_keys: [batch, seq_len, query_dim]<br>        projected_keys = self.W(keys)<br>        <br>        # 2. Compute scores: s^T * (W * h)<br>        # query.unsqueeze(1): [batch, 1, query_dim]<br>        # projected_keys.transpose(1, 2): [batch, query_dim, seq_len]<br>        scores = torch.bmm(query.unsqueeze(1), projected_keys.transpose(1, 2))<br>        scores = scores.squeeze(1) # [batch, seq_len]<br><br>        # 3. Masking<br>        if mask is not None:<br>            scores = scores.masked_fill(mask == 0, -1e9)<br><br>        # 4. Softmax<br>        weights = F.softmax(scores, dim=-1) # [batch, seq_len]<br><br>        # 5. Context vector<br>        context = torch.bmm(weights.unsqueeze(1), values).squeeze(1)<br><br>        return context, weights</pre><h3>4. Reduced-Rank Multiplicative Attention</h3><h4>Equation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/0*zc3iLGsQJqpvMbs-.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/0*ItiJvUiNOgVeudgE.png" /></figure><h4>Intuition</h4><p>Instead of learning a full d_2 times d_1 matrix, we approximate it with two smaller matrices.</p><p>This is equivalent to:</p><ol><li>project the key down to k dimensions using V</li><li>project the query down to k dimensions using U</li><li>compute the dot product in this compressed space</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37R9aXmqQdXM6Na6o6zDmQ.png" /></figure><h4>Connection to LoRA</h4><p>LoRA (Low-Rank Adaptation) uses exactly this idea to fine-tune Large Language Models.</p><p>Instead of updating a full weight matrix, LoRA only updates small U and V matrices, drastically reducing memory and compute.</p><h4>Code Snippet</h4><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br>class ReducedRankAttention(nn.Module):<br>    def __init__(self, query_dim, key_dim, rank):<br>        super(ReducedRankAttention, self).__init__()<br>        self.rank = rank<br>        <br>        # Instead of a massive [key_dim x query_dim] matrix (W),<br>        # we learn two small &quot;skinny&quot; matrices.<br>        # V projects Key down to rank &#39;k&#39;<br>        # U projects Query down to rank &#39;k&#39;<br>        self.V = nn.Linear(key_dim, rank, bias=False)<br>        self.U = nn.Linear(query_dim, rank, bias=False)<br><br>    def forward(self, query, keys, values, mask=None):<br>        &quot;&quot;&quot;<br>        Args:<br>            query: [batch, query_dim]<br>            keys:  [batch, seq_len, key_dim]<br>            values: [batch, seq_len, value_dim]<br>        &quot;&quot;&quot;<br>        # 1. Low-Rank Projection<br>        # Project both to the small dimension &#39;k&#39;<br>        # q_proj: [batch, rank]<br>        q_proj = self.U(query) <br>        <br>        # k_proj: [batch, seq_len, rank]<br>        k_proj = self.V(keys) <br>        <br>        # 2. Compute scores: (U*s)^T * (V*h)<br>        # We align them in the compressed &#39;k&#39; space<br>        # q_proj.unsqueeze(1): [batch, 1, rank]<br>        # k_proj.transpose(1, 2): [batch, rank, seq_len]<br>        scores = torch.bmm(q_proj.unsqueeze(1), k_proj.transpose(1, 2))<br>        scores = scores.squeeze(1) # [batch, seq_len]<br><br>        # 3. Masking<br>        if mask is not None:<br>            scores = scores.masked_fill(mask == 0, -1e9)<br><br>        # 4. Softmax<br>        weights = F.softmax(scores, dim=-1)<br><br>        # 5. Context Vector<br>        context = torch.bmm(weights.unsqueeze(1), values).squeeze(1)<br><br>        return context, weights</pre><h4>Limitation</h4><p><strong>Information Loss:</strong> Risk of “underfitting” if the rank k is too small to capture complex patterns.</p><h3>Conclusion: Choosing the Right Attention</h3><p>We didn’t study these four types just for theory. Understanding them is the key to knowing how modern AI works and how it stays efficient.</p><ul><li><strong>Dot-Product:</strong> The fast “handshake” — no learning, just math.</li><li><strong>Additive:</strong> The slow “interpreter” — flexible but heavy on the CPU.</li><li><strong>Multiplicative:</strong> The “standard”—smart and powerful, but uses too much memory.</li><li><strong>Reduced-Rank:</strong> The “hero”—it gives us the power of big models with a tiny fraction of the cost.</li></ul><h4>The Big Picture</h4><p>Today, we use <strong>Reduced-Rank Attention</strong> every time we train a <strong>LoRA</strong>. It is the reason we can fine-tune giant models on a single GPU. By breaking down big matrices into smaller pieces, we made AI accessible to everyone.</p><h4>Which one should you use?</h4><p>It is all about the <strong>trade-off</strong>:</p><ul><li>Need <strong>Speed</strong>? Go for <strong>Dot-Product</strong>.</li><li>Need <strong>Flexibility</strong>? Use <strong>Additive</strong>.</li><li>Need <strong>Performance</strong>? Use <strong>Multiplicative</strong>.</li><li>Need <strong>Efficiency</strong>? <strong>Reduced-Rank</strong> is your best friend.</li></ul><p>I hope this guide helped you see inside the “Black Box” of Attention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de6bdbfd8316" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do Static Word Embeddings Really Fail on Polysemy?]]></title>
            <link>https://mohammed-safa.medium.com/do-static-word-embeddings-really-fail-on-polysemy-95b33e7eadb6?source=rss-7d2805a6d963------2</link>
            <guid isPermaLink="false">https://medium.com/p/95b33e7eadb6</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[gloves]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[polysemy]]></category>
            <dc:creator><![CDATA[Mohammedsafa]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 21:35:36 GMT</pubDate>
            <atom:updated>2026-04-12T21:35:36.942Z</atom:updated>
            <content:encoded><![CDATA[<p>We usually say static embeddings fail on polysemy. And in one important sense, they do. But that may not be the whole story.</p><p>When we first learn about static word embeddings like Word2Vec or GloVe, we often hear the same criticism:</p><blockquote>one word gets one vector</blockquote><p>This is true, and it creates a problem for polysemy.</p><p>A polysemous word has more than one meaning. For example:</p><ul><li>bank can mean a financial institution or the side of a river</li><li>tie can mean clothing, a draw in sports, a cable, and more</li><li>pike can mean a fish, a weapon, or a place name</li></ul><p>So the natural question is:</p><p><strong>If a word has many meanings, how can one vector represent it?</strong></p><p>A very interesting answer comes from the paper:</p><p><strong>Linear Algebraic Structure of Word Senses, with Applications to Polysemy</strong><br>by <strong>Sanjeev Arora, Yingyu Liang, Tengyu Ma, and others</strong></p><p>The main idea is simple but powerful:</p><blockquote>A static word embedding may be a weighted linear mixture of the different senses of a word.</blockquote><h3>The basic idea</h3><p>Instead of thinking like this:</p><p><strong>one word = one meaning</strong></p><p>we can think like this:</p><p><strong>one word vector = mixture of several meanings</strong></p><p>In mathematical form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*XAPl_27O_MK6PoSI" /></figure><p>Where:</p><ul><li>(v_{word}) is the usual static embedding</li><li>(v_{sense_i}) is the vector of one sense</li><li>(\alpha_i) is the weight of that sense</li></ul><p>Usually, the weights are non-negative and sum to 1.</p><p>This means the final word vector can be seen as a kind of average of its meanings.</p><h3>Example: bank</h3><p>Suppose the word bank appears in a dataset like this:</p><ul><li>finance meaning: 80 times</li><li>river meaning: 20 times</li></ul><p>Then we can imagine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/0*Y67g3lauUbBlusuq" /></figure><p>So the static vector for “bank” is mostly about finance, but it still contains some “river” meaning.</p><p>This is a simple way to understand why static embeddings sometimes work better than we expect, even though they do not explicitly separate senses.</p><h3>Example: pike</h3><p>Now take the word pike.</p><p>Suppose its meanings appear like this:</p><ul><li>fish: 50</li><li>weapon: 30</li><li>place or road name: 20</li></ul><p>Then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/0*Y-zmSn0dM9Fv_yfR" /></figure><p>Again, one vector may contain several meanings at the same time.</p><h3>Why this matters</h3><p>This idea changes the usual story.</p><p>The common view is:</p><ul><li>static embeddings are bad for polysemy</li><li>because one word has only one vector</li></ul><p>That criticism is still valid.</p><p>But this paper suggests something more subtle:</p><p><strong>the senses may not be fully lost</strong><br>they may be mixed together in a linear structure</p><p>So the problem is not only that the meanings are missing.<br>The problem may be that they are superposed inside the same vector.</p><p>This is an important difference.</p><h3>Connection to CS224n</h3><p>This idea is also mentioned in <strong>CS224n</strong> when discussing word vectors and the limits of static embeddings.</p><p>Usually, the course explains that static embeddings cannot adapt to context the way contextual models do. That is why models like ELMo, BERT, and later transformer-based systems became so important.</p><p>But before we move to contextual embeddings, it is useful to notice this point:</p><p><strong>even static embeddings may contain more structure than we first think.</strong></p><h3>The case of “tie”</h3><p>One interesting example is the word “tie”.</p><p>Different nearest-neighbor groups can reflect different meanings, such as:</p><ul><li>clothing</li><li>sports match or draw</li><li>score-related usage</li><li>cable or wire</li><li>music or opera-related usage</li></ul><p>This suggests that one word vector may carry several semantic directions at once.</p><p>It is not a perfect separation, but it is still meaningful.</p><h3>Can we recover the hidden senses?</h3><p>The paper connects this idea to <strong>sparse coding.</strong></p><p>In simple words, if the word vector is a mixture of sense vectors, then maybe we can try to recover these hidden parts from the mixed vector.</p><p>This does not mean the decomposition is exact in all cases.<br>It is an approximate result and depends on some assumptions.</p><p>Still, the idea is exciting:</p><p><strong>polysemy may be hidden inside the embedding, not completely erased.</strong></p><h3>Important limitation</h3><p>We should be careful here.</p><p>This does not mean that static embeddings solve polysemy perfectly.</p><p>They still give only one vector for each word type.<br>They still do not use sentence context directly.<br>And in many tasks, contextual embeddings are much better.</p><p>The point is smaller, but still important:</p><blockquote>a static word vector may contain multiple senses in a structured linear way</blockquote><p>That is a more interesting picture than simply saying, “static embeddings fail.”</p><h3>Final thought</h3><p>For me, this idea makes static embeddings more interesting.</p><p>They are limited, yes.<br>But maybe they are not as simple as “one vector, one meaning.”</p><p>Maybe a word vector is more like a compressed semantic mixture, where frequent senses get larger weight and rare senses get smaller weight.</p><p>So when we look at a word like “bank”, “tie”, or “pike”, we should not always think that the model keeps only one meaning.</p><p>It may be keeping several meanings together in one vector.</p><p>And that is a very elegant idea</p><h3>Reference</h3><p><strong>Arora, Liang, Ma, et al.<br>Linear Algebraic Structure of Word Senses, with Applications to Polysemy</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95b33e7eadb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From RGB to YUV: What I Learned While Implementing a Traffic Sign Recognition Project]]></title>
            <link>https://mohammed-safa.medium.com/from-rgb-to-yuv-what-i-learned-while-implementing-a-traffic-sign-recognition-project-e2a4f7f144c1?source=rss-7d2805a6d963------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2a4f7f144c1</guid>
            <category><![CDATA[yuv]]></category>
            <category><![CDATA[traffic-sign-recognition]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[cnn-model]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Mohammedsafa]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 20:35:27 GMT</pubDate>
            <atom:updated>2026-04-05T20:35:27.386Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>From RGB to YUV: What I Learned While Implementing a Traffic Sign Recognition Project</strong></h3><p>As part of the Deep Learning course at ITI, I worked with two teammates on a project implementing a classic paper on traffic sign recognition.</p><p>While the project itself was centered around a convolutional network architecture, one of the things that stood out to me personally was something much more basic: **image representation**.</p><p>Until now, most of my experience with image data has been limited to the following:</p><ul><li><strong>RGB</strong></li><li>or <strong>grayscale</strong></li></ul><p>But during this project, I came across <strong>YUV</strong> <strong>color space</strong> for the first time.</p><p>That pushed me to ask a few simple questions:</p><ul><li>What exactly is YUV?</li><li>How is it different from RGB?</li><li>Why would we use it instead of grayscale or RGB?</li><li>And how can we convert an image from RGB to YUV in practice?</li></ul><p>This article is my attempt to answer those questions clearly and practically.</p><h4>1. The familiar starting point: RGB and grayscale</h4><p>In most computer vision projects, image data is usually represented in one of two common forms:</p><p><strong>RGB</strong><br>RGB stands for:</p><ul><li><strong>R</strong>: Red</li><li><strong>G</strong>: Green</li><li><strong>B</strong>: Blue</li></ul><p>This is the standard way digital images are stored and displayed. <br>Each image is represented using three color channels.</p><p>RGB preserves full color information, which is useful in many tasks. However, brightness and color are mixed together across the three channels.</p><p><strong>Grayscale<br></strong>Grayscale reduces the image to a single channel that represents <strong>intensity</strong> only.</p><p>This makes the input simpler and smaller, but it removes all color information.</p><p>So if we compare them quickly:</p><ul><li><strong>RGB: </strong>keeps all color information</li><li><strong>Grayscale: </strong>keeps only intensity</li><li><strong>YUV: </strong>gives us something in between, but in a more structured way</li></ul><h4>2. What is YUV?</h4><p>YUV is a color representation that separates an image into:</p><ul><li><strong>Y: </strong>luminance</li></ul><blockquote>This represents brightness or intensity.</blockquote><ul><li><strong>U</strong>: chrominance</li></ul><blockquote>This carries part of the color information.</blockquote><ul><li><strong>V</strong>: chrominance</li></ul><blockquote>This carries the remaining color information.</blockquote><p>The key idea is simple:</p><blockquote>YUV separates brightness from color</blockquote><p>This is what makes it different from RGB.</p><p>In RGB, brightness and color are entangled across the red, green, and blue channels. <br>In YUV, brightness is explicitly isolated in the <strong>Y</strong> channel, while color information is stored separately in <strong>U</strong> and <strong>V</strong>.</p><h4>3. Why is this separation useful?</h4><p>This matters because not every computer vision task needs raw color in the same way.</p><p>In many tasks, the most useful cues come from:</p><ul><li>edges</li><li>contrast</li><li>shapes</li><li>illumination patterns</li><li>object structure</li></ul><p>These are often more closely related to <strong>brightness</strong> than to raw color values.</p><p>By separating luminance from chrominance, YUV gives us a representation where:</p><ul><li><strong>Y channel:</strong> emphasizes visual structure and intensity</li><li><strong>U/V channels:</strong> preserve color information without mixing it directly with brightness</li></ul><p>This can be helpful when:</p><ul><li>lighting conditions vary</li><li>shapes and edges are strong signals</li><li>color is useful, but not the only important feature</li><li>we want the model to process brightness and color differently</li></ul><h4>4. Why might YUV help in traffic sign recognition?</h4><p>Traffic sign recognition is a good example of a task where this idea can make sense.</p><p>A traffic sign is not identified only by color:</p><ul><li>its <strong>shape</strong> matters</li><li>its <strong>border and contrast</strong> matter</li><li>its <strong>symbol structure</strong> matters</li><li>and its <strong>visibility under different lighting conditions</strong> also matters</li></ul><p>Color still helps, of course, but separating luminance from chrominance may allow the model to focus more clearly on the sign structure while still preserving color cues.</p><p>That was one of the interesting ideas I encountered while working on this project.</p><h4>5. How do we convert RGB to YUV?</h4><p>At a mathematical level, YUV is computed as a transformation of the RGB channels.</p><p>A common form of the conversion is<br>Y = 0.299R + 0.587G + 0.114B<br>U = -0.14713R — 0.28886G + 0.436B<br>V = 0.615R — 0.51499G — 0.10001B</p><p>The exact coefficients can vary slightly depending on the convention or library being used, but the main principle stays the same:</p><ul><li><strong>Y is</strong> a weighted combination representing brightness</li><li><strong>U</strong> and <strong>V</strong> encode color differences</li></ul><h4>6. Converting RGB to YUV in Python using Pytorch</h4><pre>import torch<br><br>def rgb_to_yuv(img):<br>    &quot;&quot;&quot;<br>    img: Tensor of shape (3, H, W) with values in [0, 1]<br>    returns: Tensor of shape (3, H, W)<br>    &quot;&quot;&quot;<br>    r, g, b = img[0], img[1], img[2]<br><br>    y = 0.299 * r + 0.587 * g + 0.114 * b<br>    u = -0.14713 * r - 0.28886 * g + 0.436 * b<br>    v = 0.615 * r - 0.51499 * g - 0.10001 * b<br><br>    return torch.stack([y, u, v], dim=0)</pre><h3>7. When should we use YUV?</h3><p>There is no universal rule, but YUV can be worth trying when:</p><ul><li>the task depends heavily on shape and contrast</li><li>color matters, but not as much as intensity structure</li><li>illumination variation is expected</li><li>you want to experiment with alternative input representations</li></ul><p>That said, whether YUV helps or not should always be validated experimentally.</p><h3>9. One important takeaway</h3><p>This project reminded me that in deep learning, performance is not only about choosing a model architecture.</p><p>Sometimes, the way we represent the input image can be just as important.</p><p>It is easy to focus only on the following:</p><ul><li>CNN layers</li><li>optimizers</li><li>loss functions</li><li>training schedules</li></ul><p>But preprocessing decisions, such as whether we use RGB, grayscale, or YUV, can also shape what the model learns.</p><p>For me, that was one of the most useful lessons from this project.</p><h3>10. Project context</h3><p>This insight came from a team project completed as part of the Deep Learning track at ITI, where I worked with two teammates on implementing the following:</p><p><strong>Traffic Sign Recognition with Multi-Scale Convolutional Networks<br>by Pierre Sermanet and Yann LeCun</strong></p><p>If you are interested, you can check out the project repository here:</p><p>GitHub Repo: [<a href="https://github.com/ahmednashatnoaman-svg/Traffic-Sign-Recognition-Multiscale-CNN">https://github.com/ahmednashatnoaman-svg/Traffic-Sign-Recognition-Multiscale-CNN</a>]</p><h3>Final thoughts</h3><p>YUV was new to me, but learning it helped me better appreciate a simple idea:</p><blockquote>image representation is not just a preprocessing detail — it can be part of the modeling decision itself.</blockquote><p>If you have worked with YUV, HSV, Lab, or other color spaces in computer vision, I would be interested to know when and why you used them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2a4f7f144c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>