<?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 Sujit Maity Consultancy Group &amp; Co on Medium]]></title>
        <description><![CDATA[Stories by Sujit Maity Consultancy Group &amp; Co on Medium]]></description>
        <link>https://medium.com/@smcgandco?source=rss-f1b580cee382------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fQphhiY1Ln1vwJyXlvT1VA.png</url>
            <title>Stories by Sujit Maity Consultancy Group &amp;amp; Co on Medium</title>
            <link>https://medium.com/@smcgandco?source=rss-f1b580cee382------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:17:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smcgandco/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[MS3P Sushima: Engineering a Production-Grade Byte-Level BPE Tokenizer from Scratch]]></title>
            <link>https://medium.com/@smcgandco/ms3p-sushima-engineering-a-production-grade-byte-level-bpe-tokenizer-from-scratch-a18b5a6f22f3?source=rss-f1b580cee382------2</link>
            <guid isPermaLink="false">https://medium.com/p/a18b5a6f22f3</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[dl]]></category>
            <category><![CDATA[sd]]></category>
            <dc:creator><![CDATA[Sujit Maity Consultancy Group & Co]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 08:04:18 GMT</pubDate>
            <atom:updated>2026-07-23T08:04:18.566Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Case Study in Hardening a Multilingual Byte-Level BPE Tokenizer Through Three Engineering Iterations</h3><h4>Here’s What Broke and Why It Mattered</h4><p><em>A production tokenizer isn’t defined by its algorithm alone. It’s defined by the engineering decisions that make it correct, scalable, and reliable under real-world workloads.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ppx_YMXMMn6EW2MmF6jgEw.png" /><figcaption>MS3P SUSHIMA ENGINE</figcaption></figure><p>Tokenization gets almost no glory. It’s the thing that happens before the “real” machine learning starts, so it’s easy to treat as plumbing — write it once, move on to the model. But here’s the uncomfortable truth: every mistake your tokenizer makes gets baked into everything downstream of it, silently and permanently. A model can’t un-learn a bad tokenization scheme. It just quietly underperforms, and nobody thinks to look upstream.</p><p>That’s the premise behind <strong>MS3P Sushima</strong>, a byte-level Byte-Pair Encoding (BPE) tokenizer I built from scratch — not just the encoding algorithm, but a deterministic multilingual data generator to train it on, and three successive engine revisions that trace the unglamorous but essential path from “it works” to “it works under load, at scale, in production.”</p><p>This is the story of that path — the architecture, the algorithm, and three specific bugs that never would have shown up in a quick demo but would absolutely have shown up in someone’s production logs six months later.</p><p><strong>Repo:</strong> <a href="https://github.com/smcgandco/ms3p_sushima_engine_tokenizer">github.com/smcgandco/ms3p_sushima_engine_tokenizer</a><br> <strong>PyPI:</strong> pip install ms3p-sushima-tokenizer</p><h4>The shape of the system</h4><p>MS3P Sushima has three moving parts:</p><ul><li>A <strong>corpus generator</strong> that deterministically produces synthetic multilingual training text — 30+ languages, plus numbers, code tokens, URLs, emails, symbols, emoji.</li><li>A <strong>tokenizer engine</strong> (three versions of it — more on that in a second) that trains a BPE vocabulary and applies it at inference time.</li><li>A <strong>model artifact</strong> — the trained vocabulary and merge rules, saved to disk atomically so a crash mid-save can’t corrupt it.</li></ul><p>The design principle threading through all of it is reproducibility: same seed, same config, same output — every time, regardless of how many worker processes you throw at it. That’s not just nice hygiene. It’s what makes bugs <em>findable</em>. If your system is nondeterministic, bugs hide inside the noise. If it’s deterministic, they can’t hide — they show up as reproducible, diagnosable failures.</p><h4>Inside the corpus generator</h4><p>This part doesn’t get talked about much when people discuss tokenizers, but it matters just as much as the algorithm itself — a tokenizer is only as good as what it’s trained on, and if your test corpus can’t reproduce a bug, you’ll never find it.</p><p>The generator is config-driven. Every language gets a word list and a sampling weight:</p><pre>DEFAULT_LANGUAGES: LanguageSpec = {<br>    &quot;english&quot;: ([&quot;data&quot;, &quot;science&quot;, &quot;machine&quot;, &quot;learning&quot;, &quot;model&quot;, &quot;analysis&quot;], 0.30),<br>    &quot;hindi&quot;: ([&quot;डेटा&quot;, &quot;विज्ञान&quot;, &quot;मशीन&quot;, &quot;सीखना&quot;], 0.07),<br>    &quot;bengali&quot;: ([&quot;ডাটা&quot;, &quot;বিজ্ঞান&quot;, &quot;মেশিন&quot;], 0.05),<br>    &quot;chinese&quot;: ([&quot;数据&quot;, &quot;科学&quot;, &quot;学习&quot;], 0.05),<br>    &quot;japanese&quot;: ([&quot;データ&quot;, &quot;科学&quot;, &quot;学習&quot;], 0.04),<br>    &quot;arabic&quot;: ([&quot;بيانات&quot;, &quot;علم&quot;], 0.04),<br>    # ...30+ languages total<br>}</pre><p>And token <em>type</em> is sampled from its own distribution — not every token is a word. Real text has numbers, punctuation, emoji, URLs, code fragments:</p><pre>token_distribution: Dict[str, float] = field(<br>    default_factory=lambda: {<br>        &quot;multilingual&quot;: 0.60,<br>        &quot;random_word&quot;: 0.15,<br>        &quot;number&quot;: 0.10,<br>        &quot;code&quot;: 0.07,<br>        &quot;url&quot;: 0.04,<br>        &quot;email&quot;: 0.02,<br>        &quot;symbol&quot;: 0.01,<br>        &quot;emoji&quot;: 0.01,<br>    }<br>)</pre><p>Reproducibility here isn’t a nice-to-have, it’s structural. Every SentenceGenerator owns its own random.Random(seed) instance — never the shared global RNG — because shared global state is exactly what breaks determinism the moment you add worker processes:</p><pre>class SentenceGenerator:<br>    def __init__(self, config: GeneratorConfig, seed: int) -&gt; None:<br>        self.config = config<br>        self.rng = random.Random(seed)<br>        # ...</pre><p>Multiprocess generation splits the corpus into chunks, hands each chunk a <em>different derived seed</em> (config.seed + idx), and then — critically — reassembles the output in chunk order rather than completion order, so that a run with 8 workers produces byte-identical output to a run with 1 worker:</p><pre>def _generate_multiprocess(config, chunks, file_handle, aggregate_counts, start_time):<br>    job_args = [<br>        (config, config.seed + idx, num_lines) for idx, num_lines in enumerate(chunks)<br>    ]<br>    pending_chunks: Dict[int, Tuple[List[str], TokenCounts]] = {}<br>    next_chunk_to_write = 0<br><br>    def consume_ready_chunks():<br>        nonlocal next_chunk_to_write, lines_written, output_buffer<br>        while next_chunk_to_write in pending_chunks:<br>            chunk_lines, chunk_counts = pending_chunks.pop(next_chunk_to_write)<br>            # ...write chunk_lines in order, advance next_chunk_to_write<br>            next_chunk_to_write += 1<br><br>    with ProcessPoolExecutor(max_workers=config.num_workers) as executor:<br>        futures = {executor.submit(_generate_chunk, args): idx for idx, args in enumerate(job_args)}<br>        for future in as_completed(futures):<br>            idx = futures[future]<br>            pending_chunks[idx] = future.result()<br>            consume_ready_chunks()  # only flushes what&#39;s contiguous from the start</pre><p>Workers can finish in any order — that’s the whole point of a process pool — but the buffering logic holds results until they can be written in the <em>original</em> chunk order. Worker 3 might finish before worker 1, but its output waits in pending_chunks until worker 1&#39;s output has been flushed. That&#39;s a small amount of extra bookkeeping in exchange for a guarantee that&#39;s easy to take for granted until you don&#39;t have it: --workers 8 and --workers 1 produce the exact same file, line for line.</p><p>Sentence construction itself has a couple of deliberately realistic quirks — capitalization on the first word and randomly thereafter, occasional word duplication (the way real typed text sometimes stutters), optional trailing punctuation:</p><pre>def sentence(self) -&gt; Tuple[str, TokenCounts]:<br>    num_words = self.rng.randint(self.config.min_words_per_line, self.config.max_words_per_line)<br>    words, token_types, counts = [], [], {}<br><br>    for idx in range(num_words):<br>        token, token_type = self._token()<br>        counts[token_type] = counts.get(token_type, 0) + 1<br>        if idx == 0 or self.rng.random() &lt; 0.10:<br>            token = token.capitalize()<br>        words.append(token)<br>        token_types.append(token_type)<br><br>    if words and self.rng.random() &lt; 0.10:<br>        index = self.rng.randrange(len(words))<br>        words.append(words[index])  # occasional repeated word<br>        counts[token_types[index]] = counts.get(token_types[index], 0) + 1<br><br>    sentence = &quot; &quot;.join(words)<br>    if self.rng.random() &gt; 0.5:<br>        sentence += self.rng.choice(PUNCTUATIONS)<br>    return sentence, counts</pre><p>CLI usage:</p><pre>ms3p-generate-corpus \<br>    --num-lines 100000 \<br>    --output corpus.txt \<br>    --seed 42 \<br>    --workers 4 \<br>    --stats-file corpus_stats.json</pre><p>Which emits a JSON stats file with throughput, per-token-kind counts, and the exact config used — useful for confirming two runs actually match before you go hunting for a “nondeterminism” bug that’s actually a config drift bug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIP0IZLGq8jbySQ8Fwda0g.png" /><figcaption>Token-&gt;ID</figcaption></figure><h4>The algorithm, in more depth</h4><p>BPE at the byte level means the base vocabulary is just the 256 possible byte values — every input is representable, full stop. No undefined-input edge case, just a worst-case fallback to raw bytes.</p><p>Training proceeds in four stages: pre-tokenize with a GPT-2-style regex after NFKC normalization, decompose each word into UTF-8 bytes, count adjacent byte-pair frequencies weighted by word frequency, then repeatedly merge the globally most frequent pair.</p><p>The pre-tokenizer regex itself is worth looking at directly, because the ordering of its alternatives is load-bearing:</p><pre>self.pattern = re.compile(<br>    r&quot;[\&#39;\u2019]s|[\&#39;\u2019]t|[\&#39;\u2019]re|[\&#39;\u2019]ve&quot;<br>    r&quot;|[\&#39;\u2019]m|[\&#39;\u2019]ll|[\&#39;\u2019]d&quot;<br>    r&quot;| ?\d+&quot;<br>    r&quot;| ?[^\W\d_]+&quot;<br>    r&quot;| ?[^\w\s]+&quot;<br>    r&quot;|\s+&quot;,<br>    re.UNICODE,<br>)</pre><p>Contractions are matched <em>before</em> generic word runs, so don&#39;t splits into don + &#39;t rather than being swallowed whole. Digit runs are matched before word runs, so abc123 splits into abc + 123 rather than one blended token — which matters a lot for a model&#39;s ability to generalize across numbers it&#39;s never seen mixed with words it has.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KY1SKkk4R5O7ToN3TN6UxA.png" /><figcaption>MS3P SUSHIMA ENGINE</figcaption></figure><p>The full initial pair-counting pass, before any merging happens:</p><pre>pair_freq: Dict[Tuple[bytes, bytes], int] = {}<br>pair_to_words: Dict[Tuple[bytes, bytes], Set[int]] = defaultdict(set)<br><br>for wid, tokens in enumerate(words):<br>    freq = frequencies[wid]<br>    local_pairs: Set[Tuple[bytes, bytes]] = set()<br>    for i in range(len(tokens) - 1):<br>        pair = (tokens[i], tokens[i + 1])<br>        pair_freq[pair] = pair_freq.get(pair, 0) + freq<br>        local_pairs.add(pair)<br>    for pair in local_pairs:<br>        pair_to_words[pair].add(wid)</pre><p>Note the local_pairs set — a word is only registered <em>once</em> per unique pair it contains in pair_to_words, even if that pair appears multiple times inside the same word (e.g., &quot;mississippi&quot; has ss twice). That distinction matters later: pair_to_words[pair] needs to answer &quot;which words contain this pair at all,&quot; not &quot;how many times,&quot; because the frequency count is already tracked separately in pair_freq.</p><p>The merge loop itself, in full:</p><pre>while merges_done &lt; num_merges and heap:<br>    neg_freq, pair = heapq.heappop(heap)<br>    current_freq = pair_freq.get(pair, 0)<br><br>    if current_freq == 0 or current_freq != -neg_freq:<br>        stale_counter += 1<br>        continue  # frequency changed since this was pushed — discard<br><br>    if current_freq &lt; min_pair_freq:<br>        break  # nothing left worth merging<br><br>    left, right = pair<br>    merged_token = left + right<br><br>    if len(merged_token) &gt; self.config.max_token_length:<br>        pair_freq.pop(pair, None)<br>        pair_to_words.pop(pair, None)<br>        blocked_pairs.add(pair)<br>        continue<br><br>    if self.get_vocab_size() &gt;= self.config.vocab_size:<br>        break<br><br>    rank = len(self.merge_ranks)<br>    self.merge_ranks[pair] = rank<br><br>    if merged_token not in self.vocab:<br>        token_id = self.next_token_id<br>        self.vocab[merged_token] = token_id<br>        self.inverse_vocab[token_id] = merged_token<br>        self.next_token_id += 1<br><br>    # Rewrite every affected word, compute pair frequency deltas,<br>    # push newly-adjacent pairs back onto the heap.<br>    for wid in list(pair_to_words.get(pair, ())):<br>        ...</pre><p>Two things worth calling out. First, stale_counter — the heap will inevitably accumulate entries whose frequency has since changed because of an earlier merge. Rather than trying to update or remove them eagerly (expensive), the code just lets them go stale and discards them cheaply on pop. But left unchecked, a heap full of stale garbage stops paying for itself, so there&#39;s a periodic rebuild:</p><pre>if stale_counter &gt; len(heap) * 0.5 or stale_counter &gt; 10000:<br>    logger.info(&quot;Rebuilding heap (stale=%d, heap_size=%d)...&quot;, stale_counter, len(heap))<br>    heap = [(-freq, p) for p, freq in pair_freq.items()]<br>    heapq.heapify(heap)<br>    stale_counter = 0</pre><p>Second, the delta computation per affected word — this is the actual heart of “only touch what changed”:</p><pre>old_pairs, new_pairs = {}, {}<br>for i in range(len(tokens) - 1):<br>    p = (tokens[i], tokens[i + 1])<br>    old_pairs[p] = old_pairs.get(p, 0) + 1<br><br>new_tokens = []<br>i = 0<br>while i &lt; len(tokens):<br>    if i &lt; len(tokens) - 1 and (tokens[i], tokens[i + 1]) == pair:<br>        new_tokens.append(merged_token)<br>        i += 2<br>    else:<br>        new_tokens.append(tokens[i])<br>        i += 1<br><br>for i in range(len(new_tokens) - 1):<br>    p = (new_tokens[i], new_tokens[i + 1])<br>    new_pairs[p] = new_pairs.get(p, 0) + 1<br><br>for p in set(old_pairs) | set(new_pairs):<br>    if p in blocked_pairs:<br>        continue<br>    delta = (new_pairs.get(p, 0) - old_pairs.get(p, 0)) * freq<br>    if delta == 0:<br>        continue<br>    updated = pair_freq.get(p, 0) + delta<br>    if updated &lt;= 0:<br>        pair_freq.pop(p, None)<br>        pair_to_words.pop(p, None)<br>    else:<br>        pair_freq[p] = updated<br>        heapq.heappush(heap, (-updated, p))</pre><p>Nothing here touches the rest of the corpus. A merge that occurs 4,000 times across a 2-million-word corpus triggers work proportional to 4,000 word rewrites, not 2 million.</p><h4>Engineering hardening: three revisions, three classes of defect</h4><p>Each of the following bugs was caught through systematic testing against the multilingual, mixed-token-class corpus described above — none would surface against English-only test data.</p><p>Bug #1: I got the algorithm right for training and wrong for inference</p><p>Here’s the thing about heap-based incremental updates: I’d built them for training and assumed I could skip the same rigor at inference time — “it’s just applying a fixed set of merges to a word, how expensive can that be?”</p><p>Turns out: pretty expensive. v1&#39;s _apply_bpe rescanned every adjacent pair in a token on <em>every single merge step</em> — O(n²) per word:</p><pre># v1 — quietly quadratic<br>def _apply_bpe(self, byte_values):<br>    tokens = [bytes([b]) for b in byte_values]<br>    while True:<br>        best_rank = None<br>        best_index = None<br>        for i in range(len(tokens) - 1):<br>            pair = (tokens[i], tokens[i + 1])<br>            rank = self.merge_ranks.get(pair)<br>            if rank is not None and (best_rank is None or rank &lt; best_rank):<br>                best_rank = rank<br>                best_index = i<br>        if best_index is None:<br>            break<br>        merged = tokens[best_index] + tokens[best_index + 1]<br>        tokens[best_index:best_index + 2] = [merged]<br>    return tokens</pre><p>This is exactly the kind of bug that survives a demo. Short words, short tokens, nobody notices the cost curve. Feed it long, unfamiliar strings — which is exactly what real production traffic looks like once users start pasting URLs, code, or text in a language your dev corpus barely covered — and the cost compounds fast.</p><p>The v2/v3 fix reuses the training-time machinery: a doubly linked list over byte positions, a min-heap seeded with every currently-adjacent pair that has a known merge rank, and incremental splicing:</p><pre># v2/v3 — O(n log n), touches only what actually changed<br>def _apply_bpe(self, byte_values: List[int]) -&gt; List[bytes]:<br>    n = len(byte_values)<br>    if n == 0:<br>        return []<br>    if n == 1:<br>        return [bytes([byte_values[0]])]<br><br>    tokens: List[bytes] = [bytes([b]) for b in byte_values]<br>    prev = list(range(-1, n - 1))<br>    next_ = list(range(1, n + 1))<br>    next_[-1] = -1<br>    alive = [True] * n<br>    heap: List[Tuple[int, int, int, bytes, bytes]] = []<br><br>    def push_pair(left: int, right: int) -&gt; None:<br>        tl, tr = tokens[left], tokens[right]<br>        rank = self.merge_ranks.get((tl, tr))<br>        if rank is not None:<br>            heapq.heappush(heap, (rank, left, right, tl, tr))<br><br>    for i in range(n - 1):<br>        push_pair(i, i + 1)<br><br>    while heap:<br>        rank, left, right, tok_left, tok_right = heapq.heappop(heap)<br><br>        if not alive[left] or not alive[right]:<br>            continue<br>        if next_[left] != right:<br>            continue<br>        if tokens[left] != tok_left or tokens[right] != tok_right:<br>            continue  # stale: superseded by an earlier merge<br><br>        merged_token = tok_left + tok_right<br>        if len(merged_token) &gt; self.config.max_token_length:<br>            continue  # respect the cap; don&#39;t merge, don&#39;t re-enqueue<br><br>        tokens[left] = merged_token<br>        alive[right] = False<br>        new_next = next_[right]<br>        next_[left] = new_next<br>        if new_next != -1:<br>            prev[new_next] = left<br><br>        left_prev = prev[left]<br>        if left_prev != -1:<br>            push_pair(left_prev, left)<br>        if new_next != -1:<br>            push_pair(left, new_next)<br><br>    result: List[bytes] = []<br>    idx = 0<br>    while idx != -1:<br>        result.append(tokens[idx])<br>        idx = next_[idx]<br>    return result</pre><p>Same merge rules, same output — the regression suite pins this down explicitly by running the same long strings through both implementations and diffing the results. What changes is that a stale heap entry gets discarded on the cheap next_[left] != right check alone: any merge that changes a node&#39;s content also rewires its next_ pointer in the same operation, so no rank re-derivation is ever needed.</p><p>Bug #2: off by seven, and nobody would notice until it was a crash</p><p>This one’s my favorite because of how boring the root cause is and how not-boring the consequence is.</p><p>vocab_size=50000 is a contract. It means: the model addresses at most 50,000 token IDs. Downstream, that number gets used to size an embedding table — the single most common integration pattern there is.</p><p>v1 broke that contract. get_vocab_size() counted byte tokens and merges but forgot the seven special tokens:</p><pre>self.special_tokens: Dict[str, int] = {<br>    &quot;&lt;PAD&gt;&quot;: 0, &quot;&lt;UNK&gt;&quot;: 1, &quot;&lt;BOS&gt;&quot;: 2, &quot;&lt;EOS&gt;&quot;: 3,<br>    &quot;&lt;MASK&gt;&quot;: 4, &quot;&lt;CLS&gt;&quot;: 5, &quot;&lt;SEP&gt;&quot;: 6,<br>}</pre><p>Ask for 50,000, get 50,007. Nothing crashes at training time. Everything crashes later, somewhere else, in someone else’s code, with an out-of-range index error that has nothing obviously to do with tokenizer configuration.</p><pre>def get_vocab_size(self) -&gt; int:<br>    &quot;&quot;&quot;Total addressable ids: special tokens + byte tokens + merges.&quot;&quot;&quot;<br>    return len(self.special_tokens) + len(self.vocab)<br><br># The training stop condition checks the SAME total —<br># not just the byte+merge subset — before permitting another merge:<br>if self.get_vocab_size() &gt;= self.config.vocab_size:<br>    logger.info(&quot;Target vocabulary reached.&quot;)<br>    break</pre><p>The constructor also enforces a floor so this class of misconfiguration can’t happen the other direction either — you can’t ask for a vocab smaller than the specials-plus-bytes minimum:</p><pre>min_required = self.NUM_SPECIAL_TOKENS + 256<br>if vocab_size &lt; min_required:<br>    raise ValueError(<br>        f&quot;vocab_size must be &gt;= {min_required} &quot;<br>        f&quot;({self.NUM_SPECIAL_TOKENS} special tokens + 256 byte tokens)&quot;<br>    )</pre><p>The fix for the original bug is one function. The point isn’t the difficulty of the fix — it’s that a single silent accounting error is exactly the kind of thing that’s invisible until it’s a production incident.</p><p>Bug #3: the leak that only shows up on the corpora that matter</p><p>BPE has a max_token_length cap — you don&#39;t want merges producing absurdly long tokens. When a candidate pair would exceed that cap, you reject it. Correct behavior.</p><p>v1&#39;s rejection path just continued, without removing anything:</p><pre># v1 — rejected, but never cleaned up<br>if len(merged_token) &gt; self.config.max_token_length:<br>    continue   # pair_freq[pair] and pair_to_words[pair] persist indefinitely</pre><p>Since a rejected pair can never legitimately become a real merge, it just sat there. Forever. Accumulating, on corpora that can contain millions of unique pairs — and worse, it kept getting incidentally <em>updated</em> by unrelated merges’ delta calculations, since nothing told those updates to skip it.</p><p>The fix removes it from tracking the moment it’s rejected, and remembers that it was blocked so future delta updates don’t accidentally resurrect it:</p><pre># v2/v3 — removed immediately, and remembered<br>if len(merged_token) &gt; self.config.max_token_length:<br>    pair_freq.pop(pair, None)<br>    pair_to_words.pop(pair, None)<br>    blocked_pairs.add(pair)<br>    continue<br><br># ...enforced everywhere a merge&#39;s ripple effects touch neighboring pairs:<br>for p in impacted_pairs:<br>    if p in blocked_pairs:<br>        continue<br>    # update pair_freq[p], pair_to_words[p]</pre><p>Small diff, disproportionate consequence: an unbounded memory-growth pattern in exactly the long-running jobs where you can least afford one.</p><h4>The persistence layer — because “save the model” is deceptively hard to get right</h4><p>Model files carry an 8-byte magic header so load() can detect format without guessing:</p><pre>_MAGIC_MSGPACK = b&quot;MSGPACK1&quot;<br>_MAGIC_JSON = b&quot;JSON0001&quot;<br>_MAGIC_LEN = 8</pre><p>msgpack is preferred when available — binary-safe, compact, no encode step needed for raw bytes:</p><pre>payload = {<br>    &quot;schema_version&quot;: self.SCHEMA_VERSION,<br>    &quot;version&quot;: self.VERSION,<br>    &quot;special_tokens&quot;: self.special_tokens,<br>    &quot;next_token_id&quot;: self.next_token_id,<br>    &quot;vocab&quot;: [(token, token_id) for token, token_id in self.vocab.items()],<br>    &quot;merge_order&quot;: [<br>        (left, right, rank)<br>        for (left, right), rank in sorted(self.merge_ranks.items(), key=lambda x: x[1])<br>    ],<br>}</pre><p>JSON is the dependency-free fallback, and since JSON can’t hold raw binary, vocab entries get hex-encoded specifically for that path:</p><pre>&quot;vocab&quot;: {token.hex(): token_id for token, token_id in self.vocab.items()},<br>&quot;merge_order&quot;: [<br>    (left.hex(), right.hex(), rank)<br>    for (left, right), rank in sorted(self.merge_ranks.items(), key=lambda x: x[1])<br>],</pre><p>The write itself is atomic — this is the part I’d flag as non-negotiable for anything that touches production. Write to a temp file <em>in the same directory</em> (so the final rename is on the same filesystem), flush, fsync, then swap it into place with os.replace:</p><pre>directory = os.path.dirname(os.path.abspath(path))<br>os.makedirs(directory, exist_ok=True)<br><br>with tempfile.NamedTemporaryFile(mode=&quot;wb&quot;, dir=directory, delete=False) as tmp:<br>    tmp_path = tmp.name<br>    try:<br>        tmp.write(magic)<br>        if use_msgpack:<br>            tmp.write(msgpack.packb(payload, use_bin_type=True))<br>        else:<br>            tmp.write(json.dumps(payload, ensure_ascii=False).encode(&quot;utf-8&quot;))<br>        tmp.flush()<br>        os.fsync(tmp.fileno())<br>    except Exception as e:<br>        try:<br>            os.remove(tmp_path)<br>        except Exception:<br>            pass<br>        logger.error(&quot;Failed to save model: %s&quot;, e)<br>        raise<br><br>os.replace(tmp_path, path)</pre><p>os.replace is atomic at the OS level on both POSIX and Windows — a process killed mid-save leaves either the fully-written temp file (never linked to the real path) or the previous, still-intact model file. There&#39;s no state where tokenizer.ms3p exists but is half-written garbage.</p><p>Loading mirrors this — detect format from the magic header, fall back to best-effort legacy detection for files saved without one, and normalize bytes defensively since msgpack’s exact return type for binary data can vary by packer version:</p><pre>def _as_bytes(x: Any) -&gt; bytes:<br>    return bytes(x) if not isinstance(x, bytes) else x<br><br>vocab_items = data[&quot;vocab&quot;]<br>self.vocab = {_as_bytes(tok): int(tid) for tok, tid in vocab_items}</pre><h4>Graceful degradation — optional dependencies that don’t take the whole library down</h4><p>Both msgpack and cachetools are optional:</p><pre>try:<br>    import msgpack<br>    HAS_MSGPACK = True<br>except Exception:<br>    msgpack = None<br>    HAS_MSGPACK = False<br><br>try:<br>    from cachetools import LRUCache<br>    HAS_CACHETOOLS = True<br>except Exception:<br>    LRUCache = None<br>    HAS_CACHETOOLS = False</pre><p>Without cachetools, the engine falls back to a small hand-rolled LRU built on OrderedDict:</p><pre>class SimpleLRU:<br>    def __init__(self, maxsize: int = 65536):<br>        self.maxsize = int(maxsize)<br>        self.data: OrderedDict[Any, Any] = OrderedDict()<br><br>    def get(self, key, default=None):<br>        if key not in self.data:<br>            return default<br>        value = self.data.pop(key)<br>        self.data[key] = value  # move to most-recently-used<br>        return value<br><br>    def set(self, key, value):<br>        if key in self.data:<br>            self.data.pop(key)<br>        self.data[key] = value<br>        while len(self.data) &gt; self.maxsize:<br>            self.data.popitem(last=False)  # evict least-recently-used</pre><p>This backs the word-level encode cache, guarded by a single lock (thread safety here is scoped deliberately — the lock protects the cache only, not vocab/merge_ranks, because training is documented as not safe to run concurrently with encoding):</p><pre>def _cache_get(self, key: str) -&gt; Optional[List[int]]:<br>    with self._lock:<br>        result = self.word_cache.get(key)<br>        if result is not None:<br>            self._cache_hits += 1<br>        else:<br>            self._cache_misses += 1<br>        return result</pre><p>Without msgpack, save()/load() transparently fall back to the JSON format — no exception, no crash on import, just a smaller feature surface. This is the difference between a library you can drop into a minimal container and one that demands a specific dependency stack before it&#39;ll even import.</p><h4>Logging that survives a read-only filesystem</h4><p>v3 replaces a bare logging.basicConfig() call with a proper setup_logging() — configurable via environment variables, idempotent, and specifically designed not to take the whole import down if the log path isn&#39;t writable:</p><pre>def setup_logging(log_file=None, level=None, max_bytes=None, backup_count=None, disable_file=None):<br>    resolved_level = (level or os.environ.get(&quot;MS3P_LOG_LEVEL&quot;, &quot;INFO&quot;)).upper()<br>    resolved_log_file = log_file or os.environ.get(&quot;MS3P_LOG_FILE&quot;, &quot;ms3p_sushima.log&quot;)<br>    resolved_max_bytes = int(max_bytes if max_bytes is not None<br>                              else os.environ.get(&quot;MS3P_LOG_MAX_BYTES&quot;, 10 * 1024 * 1024))<br>    resolved_backup_count = int(backup_count if backup_count is not None<br>                                 else os.environ.get(&quot;MS3P_LOG_BACKUPS&quot;, 5))<br>    if disable_file is None:<br>        disable_file = os.environ.get(&quot;MS3P_LOG_DISABLE_FILE&quot;, &quot;0&quot;) == &quot;1&quot;<br><br>    logger.setLevel(getattr(logging, resolved_level, logging.INFO))<br><br>    # Idempotent: clear existing handlers before adding new ones.<br>    for handler in list(logger.handlers):<br>        logger.removeHandler(handler)<br>        handler.close()<br><br>    formatter = logging.Formatter(_LOG_FORMAT)<br>    console_handler = logging.StreamHandler()<br>    console_handler.setFormatter(formatter)<br>    logger.addHandler(console_handler)<br><br>    if not disable_file:<br>        try:<br>            log_dir = os.path.dirname(os.path.abspath(resolved_log_file))<br>            if log_dir:<br>                os.makedirs(log_dir, exist_ok=True)<br>            file_handler = RotatingFileHandler(<br>                resolved_log_file, maxBytes=resolved_max_bytes,<br>                backupCount=resolved_backup_count, encoding=&quot;utf-8&quot;,<br>            )<br>            file_handler.setFormatter(formatter)<br>            logger.addHandler(file_handler)<br>        except OSError as e:<br>            logger.warning(<br>                &quot;Could not open log file &#39;%s&#39; (%s); logging to console only.&quot;,<br>                resolved_log_file, e,<br>            )<br><br>    logger.propagate = False  # don&#39;t double-log if root logger also has handlers<br>    return logger</pre><p>Five environment variables cover the deployment knobs that actually matter: MS3P_LOG_FILE, MS3P_LOG_LEVEL, MS3P_LOG_MAX_BYTES, MS3P_LOG_BACKUPS, MS3P_LOG_DISABLE_FILE. The read-only-filesystem case isn&#39;t hypothetical — it&#39;s the normal state of a lot of container deployments — and the difference between &quot;logs to console with a warning&quot; and &quot;ImportError on startup&quot; is the difference between a shippable library and one that only works on someone&#39;s laptop.</p><h4>What the regression suite actually checks</h4><p>Each version ships its own smoke test, and the assertions are worth reading because they encode exactly the failure modes above:</p><pre># Vocab must never exceed the configured total budget — guards Bug #2<br>assert tokenizer.get_vocab_size() &lt;= tokenizer.config.vocab_size<br><br># Round-trip fidelity, including the curly-apostrophe fix<br>for text in [&quot;hello sushima 42&quot;, &quot;don&#39;t stop, it&#39;s fine&quot;]:<br>    encoded = tokenizer.encode(text)<br>    decoded = tokenizer.decode(encoded)<br>    assert decoded == text<br><br># Long, unique strings that force many merges — regression guard<br># specifically for the encode-path rewrite in Bug #1<br>long_text = &quot;supercalifragilisticexpialidocious &quot; * 5 + &quot;abcdefghijklmnopqrstuvwxyz0123456789&quot;<br>enc = tokenizer.encode(long_text)<br>dec = tokenizer.decode(enc)<br>assert dec == long_text<br><br># Both persistence formats round-trip to identical encode/decode behavior<br>for use_msgpack in (True, False):<br>    tokenizer.save(model_path, use_msgpack=use_msgpack)<br>    loaded = MS3P_sushima_tokenizer_v3(vocab_size=tokenizer.config.vocab_size)<br>    loaded.load(model_path)<br>    assert loaded.encode(&quot;hello sushima 42&quot;) == reference_encoded<br>    assert loaded.validate() is True</pre><p>And v3 adds one more, specifically because version bumps are the kind of change that&#39;s trivial to apply in one spot and forget in another:</p><pre># Version metadata consistency — VERSION, stats(), and export_metadata()<br># must never drift apart.<br>assert tokenizer.VERSION == &quot;3&quot;<br>assert tokenizer.stats()[&quot;version&quot;] == tokenizer.VERSION<br>assert tokenizer.export_metadata()[&quot;version&quot;] == tokenizer.VERSION</pre><p>There’s also a structural validate() method that checks internal consistency independent of any specific test — every merge pair&#39;s constituent tokens must actually exist in the vocab, vocab and inverse-vocab must be the same size, ranks must be integers:</p><pre>def validate(self) -&gt; bool:<br>    if len(self.vocab) != len(self.inverse_vocab):<br>        raise ValueError(&quot;Vocabulary mismatch.&quot;)<br>    for pair, rank in self.merge_ranks.items():<br>        left, right = pair<br>        if left not in self.vocab:<br>            raise ValueError(f&quot;Merge pair left token not in vocab: {left!r}&quot;)<br>        if right not in self.vocab:<br>            raise ValueError(f&quot;Merge pair right token not in vocab: {right!r}&quot;)<br>        if not isinstance(rank, int):<br>            raise ValueError(f&quot;Invalid merge rank: {rank}&quot;)<br>    return True</pre><p>Try It</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FW__mbTFROvvrfuroz7a_Q.png" /><figcaption>MS3P SUSHIMA ENGINE</figcaption></figure><pre>pip install ms3p-sushima-tokenizer<br><br># with msgpack persistence and accelerated LRU caching<br>pip install &quot;ms3p-sushima-tokenizer[all]&quot;</pre><pre>from ms3p_sushima_tokenizer import MS3P_sushima_tokenizer_v3<br><br># Train<br>tokenizer = MS3P_sushima_tokenizer_v3(vocab_size=32000)<br>tokenizer.train(&quot;corpus.txt&quot;, min_pair_freq=2)<br>tokenizer.save(&quot;tokenizer.ms3p&quot;)  # msgpack by default; atomic write<br><br># Load and use<br>tokenizer = MS3P_sushima_tokenizer_v3(vocab_size=32000)<br>tokenizer.load(&quot;tokenizer.ms3p&quot;)<br><br>ids = tokenizer.encode(&quot;Byte-pair encoding is deceptively simple.&quot;)<br>text = tokenizer.decode(ids)<br>coverage = tokenizer.vocabulary_coverage(&quot;some unfamiliar text&quot;)<br><br># Batch operations, padded for model input<br>batch = tokenizer.encode_batch([&quot;hello world&quot;, &quot;byte pair encoding&quot;], padding=True)</pre><p>v1 and v2 still ship in the package for anyone pinned to an earlier revision. Everyone else should be on v3.</p><h4>The actual takeaway</h4><p>None of these three bugs needed exotic input to surface. No adversarial fuzzing, no edge-case hunting. They needed <em>scale</em> and <em>linguistic diversity</em> — the two things a quick demo almost never has and production traffic always does.</p><p>So if you’re evaluating a tokenizer — yours or someone else’s — these are the questions worth asking: Is merge application at inference time actually sub-quadratic, or does it just look that way because you tested it on short strings? Does the configured vocab size match what the model actually addresses? When a merge candidate gets rejected, does it actually leave the bookkeeping, or does it just sit there, quietly growing? Is the save path atomic, or can a crash mid-write leave you with a corrupted model file? And do the optional dependencies degrade gracefully, or does their absence take the whole import down?</p><p>None of these are hard questions to answer. They’re just easy to forget to ask.</p><p>Repo: <a href="https://github.com/smcgandco/ms3p_sushima_engine_tokenizer">github.com/smcgandco/ms3p_sushima_engine_tokenizer</a> — PyPI: pip install ms3p-sushima-tokenizer</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a18b5a6f22f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>