<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Unica2804</title>
    <description>The latest articles on DEV Community by Unica2804 (@unica_2804).</description>
    <link>https://dev.to/unica_2804</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3280121%2F291ff15d-3380-454b-a932-271ff953962e.png</url>
      <title>DEV Community: Unica2804</title>
      <link>https://dev.to/unica_2804</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/unica_2804"/>
    <language>en</language>
    <item>
      <title>TokenBpe A editorial on how tokenizers can be sped up.</title>
      <dc:creator>Unica2804</dc:creator>
      <pubDate>Sun, 15 Nov 2026 14:44:55 +0000</pubDate>
      <link>https://dev.to/unica_2804/tokenbpe-a-editorial-on-how-tokenizers-can-be-sped-up-57j5</link>
      <guid>https://dev.to/unica_2804/tokenbpe-a-editorial-on-how-tokenizers-can-be-sped-up-57j5</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;Every LLM pipeline starts with a tokenizer and almost no one thinks about it. The model gets the headlines, the tokenizer is quietly burning microseconds per token per request, forever. If you're serving millions of requests or just training on a corpus that doesn't fit in memory that "quietly" adds up.&lt;/p&gt;

&lt;p&gt;This post is a walk through TokenBpe, a BPE tokenizer that I've written from the ground up in C++20. It covers what the various components are, how each one works, what specific techniques give you a performance gain and why. All of this is based on the actual code (include/tokenizer/, src/, utils/) and the benchmark figures are from a properly audited 3 way comparison against OpenAI's tiktoken (Rust) and Hugging Face tokenizers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Headline numbers&lt;/strong&gt; (Shakespeare corpus, 1.06 MB, GPT-2 vocabulary, 12 hardware threads, Intel i5-11260H):&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Operation&lt;/th&gt;
&lt;th&gt;TokenBpe&lt;/th&gt;
&lt;th&gt;tiktoken&lt;/th&gt;
&lt;th&gt;HF tokenizers&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Encode, 12T (zero-copy)&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;239.98 MB/s&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;45.83 MB/s&lt;/td&gt;
&lt;td&gt;12.08 MB/s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Encode, 1T&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;34.22 MB/s&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;11.55 MB/s&lt;/td&gt;
&lt;td&gt;2.11 MB/s&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Decode, 1T (zero-copy)&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;341.01 MB/s&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;117.34 MB/s&lt;/td&gt;
&lt;td&gt;24.93 MB/s&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;~5.2× tiktoken and ~19.9× HF on 12-thread encoding. And ~6.1× scaling from 1 to 12 threads natively. Let's open the hood.&lt;/p&gt;




&lt;h2&gt;
  
  
  What a BPE tokenizer actually does
&lt;/h2&gt;

&lt;p&gt;BPE encoding has two phases:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Pre-tokenisation: split the raw text into word-like pieces ("pre-tokens"). GPT-2's approach is to split on letter runs, digit runs, whitespace runs, contractions (i.e. 's, 're, 'll etc), punctuation runs and to fold the leading space into the next token (so " hello" is one pre-token rather than " " + "hello").&lt;/li&gt;
&lt;li&gt;Merge based encoding: each pre-token is a sequence of single bytes. You repeatedly find the adjacent pair with the lowest merge rank and replace it with the merged token id, until no more merges can be applied.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Decoding is trivial really: just map each token id to its bytes and concatenate.&lt;/p&gt;

&lt;p&gt;The naive implementation of this is fine. The real question is where the time goes and the answer, as ever, is everywhere, a little bit at a time. So TokenBpe attacks every layer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;text ─▶ SWAR pre-tokenizer ─▶ dual-cursor split ─▶ per-thread cache ─▶ linked-list merge ─▶ token ids
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;with a persistent thread pool under the whole thing, a flat binary model format and a zero copy NumPy boundary on top.&lt;/p&gt;




&lt;h2&gt;
  
  
  Component tour
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. The pre-tokenizer: SWAR instead of regex
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;The problem is GPT-2's official tokenizer uses a regular expression to split the text. Regex engines are general purpose monsters backtracking, capture groups, Unicode classes all of which are completely unnecessary when you're just trying to determine if a run of bytes is letters or not.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;The technique.&lt;/strong&gt; SWAR (SIMD Within A Register) does the 8 bytes per 64 bit word classification using pure integer arithmetic. No SSE/AVX intrinsics at all, it's all done in the 64 bit ALU.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="c1"&gt;// swar.hpp (simplified)&lt;/span&gt;
&lt;span class="c1"&gt;// All 8 lanes are bytes; HIGH_BITS is OR'd in before subtracting&lt;/span&gt;
&lt;span class="c1"&gt;// min so no lane can borrow from its neighbour.&lt;/span&gt;
&lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nf"&gt;all_bytes_in_range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;uint64_t&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;uint8_t&lt;/span&gt; &lt;span class="n"&gt;min&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;uint8_t&lt;/span&gt; &lt;span class="n"&gt;max&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nf"&gt;all_ascii_lower&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;uint64_t&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;   &lt;span class="c1"&gt;// [a-z]&lt;/span&gt;
&lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nf"&gt;all_ascii_upper&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;uint64_t&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;   &lt;span class="c1"&gt;// [A-Z]&lt;/span&gt;
&lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nf"&gt;all_ascii_letters&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;uint64_t&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// both, via v | 0x20&lt;/span&gt;
&lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nf"&gt;all_ascii_digits&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;uint64_t&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  &lt;span class="c1"&gt;// [0-9]&lt;/span&gt;
&lt;span class="kt"&gt;bool&lt;/span&gt; &lt;span class="nf"&gt;all_bytes_equal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;uint64_t&lt;/span&gt; &lt;span class="n"&gt;v&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;uint8_t&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The range check is written very carefully indeed: it rejects the high bit bytes first, then ORs in HIGH_BITS prior to subtracting min, so a lane can never borrow from its neighbour. load64 does an unaligned 64-bit load via memcpy which ends up as a single instruction.&lt;/p&gt;

&lt;p&gt;The splitter (&lt;code&gt;pre_tokenizer.hpp&lt;/code&gt;) then scans:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;letter runs and digit runs 8 bytes at a time, scalar tail;&lt;/li&gt;
&lt;li&gt;space runs 8 bytes at a time with &lt;code&gt;all_bytes_equal&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;contractions&lt;code&gt;'s&lt;/code&gt;, &lt;code&gt;'t&lt;/code&gt;, &lt;code&gt;'m&lt;/code&gt;, &lt;code&gt;'d&lt;/code&gt;, &lt;code&gt;'re&lt;/code&gt;, &lt;code&gt;'ve&lt;/code&gt;, &lt;code&gt;'ll&lt;/code&gt;;&lt;/li&gt;
&lt;li&gt;punctuation runs (all other non-alphanumeric/non-space/non-apostrophe characters are grouped)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;And crucially next_token() returns a std::string_view into the original buffer. No pre-token is ever materialised as a string. The caller owns the text lifetime, the splitter just points into it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The speed payoff.&lt;/strong&gt; Byte classification goes from one branch per byte to one instruction per eight bytes for the majority of the scan. No regex engine is actually invoked at all. The only caveat here is that it's an approximation of GPT-2's regex (exotic Unicode whitespace can have different effects on splitting), which is why the token counts on the Shakespeare corpus differ by ~1.9% from tiktoken. Roundtrips are always exact though.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. The dual cursor: instruction-level parallelism without threads
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;The problem&lt;/strong&gt;. Pre-tokenising left to right is a single dependency chain: scan, emit, scan, emit. The CPU can't get ahead of itself as each step is dependent on where the last one left off.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The technique.&lt;/strong&gt; &lt;code&gt;dual_cursor.hpp&lt;/code&gt; finds a safe split point a space or newline within ±128 bytes of the midpoint, searching backwards first (inputs under 256 bytes aren't split) and runs &lt;strong&gt;two &lt;code&gt;LexerCursor&lt;/code&gt;s alternately in one fused loop&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="c1"&gt;// dual_cursor.hpp — sketch&lt;/span&gt;
&lt;span class="nf"&gt;find_safe_split_boundary&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;          &lt;span class="c1"&gt;// near midpoint, whitespace-aligned&lt;/span&gt;
&lt;span class="nc"&gt;LexerCursor&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;begin&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;split&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="n"&gt;split&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;end&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;while&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;has_more&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;has_more&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;has_more&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nf"&gt;emit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;next_token&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;out_a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;has_more&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nf"&gt;emit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;next_token&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;out_b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each cursor's dependency chain is independent so the superscalar core has two instruction streams to work on. Output order is preserved by writing the first half into out_a and the second half into out_b and then concatenating.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What it is NOT:&lt;/strong&gt; threading. It's a fused, allocation-free iteration that also eschews the need to materialise a std::vector&lt;a&gt;std::string_view&lt;/a&gt; of pre-tokens.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. The merge loop: intrusive linked list, no allocations
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;The problem is the naive BPE merge is "find the lowest rank adjacent pair, replace it and repeat" and with vectors that's an O(n) erase and shift per merge plus string building for the merged tokens.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;The technique.&lt;/strong&gt; &lt;code&gt;encode_chunk_uncached_to_buffer()&lt;/code&gt; (the heart of &lt;code&gt;src/encoder.cpp&lt;/code&gt;) represents the pre-token as a thread-local array of nodes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;struct&lt;/span&gt; &lt;span class="nc"&gt;ListNode&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nc"&gt;TokenId&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="kt"&gt;int32_t&lt;/span&gt; &lt;span class="n"&gt;prev&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="kt"&gt;int32_t&lt;/span&gt; &lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The algorithm:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Reset the thread local scratchpad (g_scratchpad) and lay out one ListNode per byte.&lt;/li&gt;
&lt;li&gt;Repeat: go through the list once. For every adjacent pair in &lt;code&gt;merge_ranks_&lt;/code&gt;, keep the one with the globally lowest rank (not the first one encountered, training order takes priority regardless of position). If none, stop.&lt;/li&gt;
&lt;li&gt;Splice: overwrite the left node's token with the new id, point its next past the right node and fix the back-pointer. O(1) unlink, zero allocation.**&lt;/li&gt;
&lt;li&gt;Just go through the list and output the ids.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;The speed payoff.&lt;/strong&gt; No string allocations at all during merging, ever. The merged bytes were already computed by add_merge() when the model was built. The cost is an O(n) scan per merge and for pre-tokens (which are almost always very short) that's a very reasonable trade.&lt;/p&gt;

&lt;p&gt;This is also where the TokenPairHash comes in: a splitmix64 style mixer on first &amp;lt;&amp;lt; 32 | second, giving us unordered_map lookups that won't pathologically collide.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. The pre-token cache: 512 KiB of direct-mapped memoization per thread
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;The problem is of course that pre-tokens are repeating all the time ("the", "and", common names). Running the merge loop for every instance of that is absolutely wasted work.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;The technique.&lt;/strong&gt; Each thread gets an 8 192-slot, direct-mapped cache:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight cpp"&gt;&lt;code&gt;&lt;span class="k"&gt;static_assert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;sizeof&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CacheSlot&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;64&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  &lt;span class="c1"&gt;// exactly one cache line&lt;/span&gt;
&lt;span class="c1"&gt;// slot = fnv1a64(word) &amp;amp; 0x1FFF&lt;/span&gt;
&lt;span class="c1"&gt;// slot = { hash, word_len, token_count, char word[22], TokenId tokens[8] }&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Direct-mapped: no probing, no chaining, no eviction policy. One line load plus a memcmp on a hit.&lt;/li&gt;
&lt;li&gt;Collisions just overwrite correctness has nothing to do with a hit so it's all speed.&lt;/li&gt;
&lt;li&gt;Only pre-tokens of 22 bytes or less which produce 8 tokens or less are cached (the short pre-tokens are by far the majority of the real text).&lt;/li&gt;
&lt;li&gt;get() returns a std::span into the slot (zero copy, the ids are just inserted directly into the output).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;The speed payoff.&lt;/strong&gt; A cache hit bypasses the scratchpad, the list construction, the merge scans and the hash-map probes of the pair table it's just a single line lookup and a bulk insert. The 512kib/thread footprint remains in L2 on most cores.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Decode: flat table, two passes, one allocation
&lt;/h3&gt;

&lt;p&gt;Decoding looks up &lt;code&gt;decode_table_[id].size()&lt;/code&gt; to get the total output size, calls &lt;code&gt;resize()&lt;/code&gt; once and then &lt;code&gt;memcpy&lt;/code&gt;s each token's bytes forward. The table is id-indexed so decode never touches a hash map. Any ids outside the table are silently skipped (a corrupt stream just degrades rather than aborting). Result: 341mb/s, ~2.9x tiktoken, ~13.7x HF.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. The thread pool: persistent, dynamic, warm
&lt;/h3&gt;

&lt;p&gt;Spawning a thread per batch kills you twice: on thread creation and on cold thread local state. TokenBpe uses a PersistentThreadPool: &lt;code&gt;hardware_concurrency() - 1&lt;/code&gt; workers &lt;strong&gt;plus the calling thread&lt;/strong&gt;, work distributed via a shared atomic cursor (&lt;code&gt;fetch_add&lt;/code&gt;) a dynamic schedule with no per-item queue. The workers keep their TokenCache and ThreadScratchpad warm across calls for the life of the process.&lt;/p&gt;

&lt;p&gt;Batches go through parallel_tokenize_flat() which returns a single contiguous token array plus a prefix sum offsets array (a FlatBatch) such that chunk i is in tokens[offsets[i] .. offsets[i+1]]. No per-chunk vectors, no copies.&lt;/p&gt;

&lt;p&gt;Honest limitation: one shared task slot, non-reentrant, &lt;code&gt;threads&lt;/code&gt; parameter is advisory. It's a very simple pool really, does one thing and does it well.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. The zero-copy boundary: C++ → NumPy without &lt;code&gt;tolist()&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;The nanobind FFI (in utils/bindings.cpp) is where the vast majority of the "fast" tokenizers just quietly fall apart, they're fast at computing, then they copy everything into Python objects. TokenBpe:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;releases the GIL around every compute phase;&lt;/li&gt;
&lt;li&gt;returns &lt;code&gt;encode_flat&lt;/code&gt; / &lt;code&gt;encode_batch_flat&lt;/code&gt; as &lt;code&gt;numpy.uint32&lt;/code&gt; ndarrays whose &lt;code&gt;std::vector&lt;/code&gt; is moved to the heap and owned by an &lt;code&gt;nb::capsule&lt;/code&gt; — ownership transfers to NumPy, no &lt;code&gt;tolist()&lt;/code&gt; round-trip;&lt;/li&gt;
&lt;li&gt;will accept a 1-D contiguous uint32 ndarray directly as input to decode, reading in place.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Measured effect: ndarray encode at 239.98 MB/s vs 137.40 MB/s for the equivalent &lt;code&gt;list[list[int]]&lt;/code&gt; path &lt;strong&gt;1.75x purely from the boundary&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  8. The BPE1 binary format: microsecond loads
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;save()&lt;/code&gt;/&lt;code&gt;load()&lt;/code&gt; use a compact, order-independent binary:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Header     : magic "BPE1" | version u8 | vocab_size u32 | merge_count u32
Vocabulary : vocab_size × { id u32 | len u32 | bytes[len] }
Merges     : merge_count × { left u32 | right u32 | rank u32 | result u32 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Load validates magic/version, clears all tables &lt;strong&gt;and the thread-local cache&lt;/strong&gt;, then rebuilds &lt;code&gt;byte_to_token_id&lt;/code&gt; (from length-1 vocab entries essential for imported GPT-2, whose byte tokens are permuted), &lt;code&gt;merge_ranks_&lt;/code&gt;, and the flat decode table. A 50 257-token / 49 992-merge GPT-2 model is ~1.5 MB and loads in microseconds. There's also a trainer (frequency-weighted, recompute-based, deliberately simple) and a Hugging Face importer (&lt;code&gt;convert_hf_to_bpe.py&lt;/code&gt;) that reverses GPT-2's byte-to-unicode map.&lt;/p&gt;




&lt;h2&gt;
  
  
  Why it's fast the short version
&lt;/h2&gt;

&lt;p&gt;Every technique maps to a specific cost it eliminates:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Technique&lt;/th&gt;
&lt;th&gt;Eliminates&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;SWAR pre-tokenization&lt;/td&gt;
&lt;td&gt;Regex engine overhead; 8× fewer classification steps&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;string_view&lt;/code&gt; pre-tokens&lt;/td&gt;
&lt;td&gt;String materialization + allocator traffic&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Dual cursor&lt;/td&gt;
&lt;td&gt;Single dependency chain; enables ILP&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Linked-list merge&lt;/td&gt;
&lt;td&gt;O(n²) vector erase-and-shift; string building&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Global lowest-rank selection&lt;/td&gt;
&lt;td&gt;Correctness of merge priority (a subtle bug source, not just speed)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Direct-mapped 64 B cache&lt;/td&gt;
&lt;td&gt;Scratchpad setup + merge work for common pre-tokens&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Thread-local scratchpad/cache&lt;/td&gt;
&lt;td&gt;Cross-thread synchronization + allocation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Persistent pool + atomic cursor&lt;/td&gt;
&lt;td&gt;Thread spawn cost; queue allocation&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Flat decode table + single &lt;code&gt;resize&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Hash lookups; multiple allocations&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Flat batch + prefix-sum offsets&lt;/td&gt;
&lt;td&gt;Per-chunk vector overhead&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Zero-copy ndarray + GIL release&lt;/td&gt;
&lt;td&gt;Python object overhead; interpreter serialization&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;code&gt;BPE1&lt;/code&gt; binary model&lt;/td&gt;
&lt;td&gt;Parse overhead at load time&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;-O3 -march=native -flto&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;The compiler's chances to help&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;The big lesson: &lt;strong&gt;no single trick wins&lt;/strong&gt;. The speedup is the product of a dozen multiplicative factors, boundary copies, allocations, cache misses, dependency chains, each small, all compounding.&lt;/p&gt;




&lt;h2&gt;
  
  
  Benchmarking methodology
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Same ~64 KiB &lt;strong&gt;newline-aligned&lt;/strong&gt; chunks for all engines (no mid-word cuts penalizing anyone).&lt;/li&gt;
&lt;li&gt;Same GPT-2 vocabulary for every engine.&lt;/li&gt;
&lt;li&gt;Rust Rayon pinned with &lt;code&gt;RAYON_NUM_THREADS&lt;/code&gt; to the C++ pool's thread count.&lt;/li&gt;
&lt;li&gt;Roundtrip verified (decode → compare) for &lt;code&gt;fast_bpe&lt;/code&gt; and &lt;code&gt;tiktoken&lt;/code&gt; &lt;strong&gt;before&lt;/strong&gt; timing.&lt;/li&gt;
&lt;li&gt;Both &lt;code&gt;fast_bpe&lt;/code&gt; boundary types measured (ndarray vs list) so the FFI cost is visible.&lt;/li&gt;
&lt;li&gt;Median of 9 runs after 3 warm-ups; numbers vary ±5% run to run.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fast_bpe (C++20)   Encode 12T   239.98 MB/s   74.80 Mtok/s   zero-copy ndarray
fast_bpe (C++20)   Encode 12T   137.40 MB/s   42.83 Mtok/s   Python list[list[int]]
tiktoken (Rust)    Encode 12T    45.83 MB/s   14.56 Mtok/s
HF tokenizers      Encode 12T    12.08 MB/s    3.84 Mtok/s
fast_bpe (C++20)   Decode 1T    341.01 MB/s  106.30 Mtok/s   zero-copy ndarray
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Native C++ suite: 41.81 MB/s single-threaded → 254.88 MB/s on 12 threads = &lt;strong&gt;6.10×&lt;/strong&gt; scaling. (Not a perfect 12× memory bandwidth and the single split point in the dual cursor, among other things.)&lt;/p&gt;

&lt;p&gt;Caveats to state in the post: the pre-tokenizer is an approximation (~1.9% fewer tokens on this corpus), roundtrips are exact, and &lt;code&gt;fast_bpe&lt;/code&gt; vs tiktoken is not a byte-identical id comparison.&lt;/p&gt;




&lt;h2&gt;
  
  
  Try it out
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Build
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;git clone &lt;span class="o"&gt;&amp;lt;&lt;/span&gt;https://github.com/Unica2804/Token_BPE.git&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nb"&gt;cd&lt;/span&gt; BPE_Tokenizer
python -m venv .venv &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nb"&gt;source&lt;/span&gt; .venv/bin/activate
pip install nanobind numpy
&lt;span class="c"&gt;# optional, for the 3-way benchmark:&lt;/span&gt;
pip install tiktoken tokenizers

cmake -S . -B build
cmake --build build -j
ctest --test-dir build --output-on-failure   &lt;span class="c"&gt;# 10 tests, 52 assertions&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Artifacts in &lt;code&gt;build/&lt;/code&gt;: &lt;code&gt;libbpe_core.a&lt;/code&gt;, &lt;code&gt;tokenizer_cli&lt;/code&gt;, &lt;code&gt;tokenizer_bench&lt;/code&gt;, &lt;code&gt;tokenizer_tests&lt;/code&gt;, &lt;code&gt;fast_bpe.*.so&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Convert the GPT-2 model (or use the committed gpt2.bpe)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;python utils/convert_hf_to_bpe.py \
    --vocab  gpt2_tokenizer/vocab.json \
    --merges gpt2_tokenizer/merges.txt \
    --out    gpt2.bpe
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Python quickstart
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;sys&lt;/span&gt;
&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"./build"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;fast_bpe&lt;/span&gt;

&lt;span class="n"&gt;enc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;fast_bpe&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;BpeEncoder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;enc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;load&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"gpt2.bpe"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="n"&gt;enc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, world!"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;          &lt;span class="c1"&gt;# -&amp;gt; list[int]&lt;/span&gt;
&lt;span class="n"&gt;enc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encode_flat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Hello, world!"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;     &lt;span class="c1"&gt;# -&amp;gt; numpy.uint32 ndarray (zero-copy)&lt;/span&gt;

&lt;span class="n"&gt;tokens&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;offsets&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;enc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;encode_batch_flat&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"line 1"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"line 2"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="c1"&gt;# chunk i -&amp;gt; tokens[offsets[i]:offsets[i+1]]&lt;/span&gt;

&lt;span class="n"&gt;enc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;decode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tokens&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                   &lt;span class="c1"&gt;# -&amp;gt; str&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Re-run the benchmarks
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# MUST run from repo root&lt;/span&gt;
.venv/bin/python benchmark.py --chunk-kb 64 --warmup 3 --runs 9
./build/tokenizer_bench
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Takeaways
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Tokenizers are real software with real performance engineering in them.&lt;/li&gt;
&lt;li&gt;Profile the boundary you cross most often for Python bindings, that's the FFI, not the algorithm.&lt;/li&gt;
&lt;li&gt;Allocation-free hot paths (thread-local scratchpads, inline cache slots) beat clever data structures.&lt;/li&gt;
&lt;li&gt;Measure against independent implementations; "it roundtrips" beats "it matches somewhere".&lt;/li&gt;
&lt;/ol&gt;




&lt;p&gt;&lt;em&gt;Built with C++20, nanobind, Catch2. Code, benchmarks, and the audited comparison script are in the repo.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>tutorial</category>
      <category>cpp</category>
      <category>tokenizers</category>
    </item>
    <item>
      <title>StarWatch: an offline pocket stargazing PWA that names what you point at</title>
      <dc:creator>Unica2804</dc:creator>
      <pubDate>Sun, 11 Oct 2026 17:56:31 +0000</pubDate>
      <link>https://dev.to/unica_2804/starwatch-an-offline-pocket-stargazing-pwa-that-names-what-you-point-at-302d</link>
      <guid>https://dev.to/unica_2804/starwatch-an-offline-pocket-stargazing-pwa-that-names-what-you-point-at-302d</guid>
      <description>&lt;h2&gt;
  
  
  What I built
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;StarWatch&lt;/strong&gt; is an offline-only pocket stargazing PWA: open your camera, point it at the sky, and it names the star or constellation in frame. When city haze wins, a one tap fallback opens a full sky map driven by the same compass, gyro, and GPS Google-Sky-Map mode, no camera needed.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Repo: &lt;a href="https://github.com/Unica2804/starwatch" rel="noopener noreferrer"&gt;https://github.com/Unica2804/starwatch&lt;/a&gt; (MIT, built Oct 6–11)&lt;/li&gt;
&lt;li&gt;Live demo (Render Static): &lt;a href="https://starwatch.onrender.com" rel="noopener noreferrer"&gt;https://starwatch.onrender.com&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Touch Grass fit: the whole point is going outside after dark and looking up. The screen is a viewfinder, not the destination.&lt;/p&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[GPS + compass + gyro + camera]
  → astronomy-engine + 43-star seed catalog → what should be there
  → classical star-point detection on a 320px frame (adaptive threshold
    over a background map, milliseconds, no model) → what is visible
  → nearest-neighbor match (24px tolerance) → verified / hidden / unknown
  → canvas overlay draws constellation lines ONLY through verified stars
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;No lines through haze, ever. Geometrically-present-but-unseen stars are listed as "washed out." A covered lens yields an honest empty state instead of a guess.&lt;/p&gt;

&lt;p&gt;An explicit anti hallucination gate (&lt;code&gt;crossValidate&lt;/code&gt;) stands ready for the vision model: ephemeris proposes, detection verifies, the model may only confirm. A 0.99-confidence claim for a constellation that isn't there is rejected by construction and there's a test proving it.&lt;/p&gt;

&lt;h2&gt;
  
  
  The VLM spike we refused to ship
&lt;/h2&gt;

&lt;p&gt;With hours left I tried to plug a small open VLM instead of training: Florence-2-base (232M, MIT, ONNX q4 via Transformers.js) captioned our Orion photo in ~2s on desktop CPU but only generically ("night sky filled with stars"), never naming anything. SigLIP zero shot scoring looked better at first: &lt;strong&gt;Orion 0.52&lt;/strong&gt; with descriptive labels. Then the control run with bare constellation names put &lt;strong&gt;Scorpius 0.354 over Orion 0.221 on a photo of Orion&lt;/strong&gt;. Prompt-fragile, confidently wrong, and our own 0.5 gate would have rejected every claim. So it stays out: shipping that as "AI identification" would be a lie with good latency. The slot, the gate, and the gauntlet stay ready for a fine-tuned model that earns its place.&lt;/p&gt;

&lt;h2&gt;
  
  
  Verifying without a sky
&lt;/h2&gt;

&lt;p&gt;Daylight didn't stop verification:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Synthetic skies&lt;/strong&gt;: a rendered Scorpius frame with known ground truth plus a decoy plane-light runs the exact production path — all three stars named, decoy quarantined as unknown, lying model overruled.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Real photons&lt;/strong&gt;: our detector over a NASA public-domain Orion photo found &lt;strong&gt;200 star points in 16.7ms across 60/64 frame cells&lt;/strong&gt;. Getting there caught a real bug: the first version flooded on gradients, which forced background subtraction before thresholding.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;60 tests green&lt;/strong&gt;, strict TypeScript, PWA precache verified live.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The Brave war story
&lt;/h2&gt;

&lt;p&gt;Testing stalled for a day on "compass silent" on Brave Android, motion sensors are blocked by default with no per site prompt, and since Chrome 50, plain orientation events carry &lt;em&gt;relative&lt;/em&gt; drift that silently corrupts headings. Both got fixed (absolute only alpha, in app settings guidance, manual look around that hands control back when sensors wake). Boring, unglamorous, and exactly the kind of thing a field app lives or dies on.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why open beats closed here
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Runs with zero bars&lt;/strong&gt;: the whole pipeline is on-device. A backcountry ridge with no signal gets the same app as downtown.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Location never leaves the phone&lt;/strong&gt;: sky math needs your GPS no server ever sees it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Swap, don't beg&lt;/strong&gt;: catalog, detector, and (next) model weights are all swappable files, not API tiers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;$0 to run&lt;/strong&gt;: static hosting, no inference bill, no keys to leak.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Honest scope
&lt;/h2&gt;

&lt;p&gt;No model ships in this build the fine tune didn't fit the week and the zero shot shortcut failed our own tests, so I'm entering &lt;strong&gt;Overall + Best Use of Render only&lt;/strong&gt;, no AI track claims. Classical detection tonight; open-weight vision when it passes the gauntlet.&lt;/p&gt;

&lt;p&gt;Built irritation-first, tested against lies, and it works under the exact polluted sky I live under.&lt;/p&gt;

</description>
      <category>hf26challenge</category>
      <category>pwa</category>
      <category>opensource</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Tiny Diffusion</title>
      <dc:creator>Unica2804</dc:creator>
      <pubDate>Tue, 24 Feb 2026 12:01:21 +0000</pubDate>
      <link>https://dev.to/unica_2804/tiny-diffusion-5g8k</link>
      <guid>https://dev.to/unica_2804/tiny-diffusion-5g8k</guid>
      <description>&lt;p&gt;Have you ever wondered how the diffusion model works? I also wondered about it for a long time. It's so fancy; you type a prompt and, magically, a picture or video is created within a few seconds to minutes.&lt;br&gt;
Introduction&lt;/p&gt;

&lt;p&gt;Diffusion is a process of transferring energy from a high-energy state to a lower-energy state, as described in thermodynamics. The Diffusion model we use follows a similar technique. Imagine dropping an ink into a glass of water. At first, a shape forms, then slowly the ink diffuses with water and turns into a uniform blue color. In our model, we did a similar thing; we turned a perfectly good image into total noise by adding a little bit of noise in each step. This process is called Forward Diffusion.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs29cogzdihw0i8uoktrf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs29cogzdihw0i8uoktrf.png" alt="Forward process" width="800" height="102"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, coming back to the example of a glass of water. What if we filmed the whole process of ink diffusing and reversed it? Then we would see the blue-colored water reverse and form the initial blue dot shape. In the case of our model, we train our model to predict the noise and subtract the noise from the original image by showing it the process of adding noise thousands of times. This process is called Reverse Diffusion.&lt;/p&gt;

&lt;p&gt;These two are the core philosophies behind diffusion, though there is a concept of a scheduler that decides how noise is added over time to the image and the algorithm that helps us reverse the noise, etc. Though nowadays people have moved from U net diffusion and moved to Diffusion Transformers.&lt;/p&gt;
&lt;h2&gt;
  
  
  Moving From Images to&amp;nbsp;Motion
&lt;/h2&gt;

&lt;p&gt;This is the Interesting part for a 2D diffusion model, it just needs to fix one single frame, but while we are dealing with time as a third Dimension for a video, we need consistency, i.e. If the model denoises Frame 1 into a "3" and Frame 2 into a "5," the animation would look like a flickering nightmare. For this, we need temporal attention, i.e., the model shouldn't only look at the pixel but look through time before and after the frame. For this, we ran Euclidean distance algorithm with masking to convert a static 28x28 MNIST image into a 15x28x28 batch of images. So now a single MNIST digit is a batch of 15 images that cover the digit's transformation during different timesteps. So now we have solved the problem of Data and we have to make a modified architecture.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6y8ztliuedt84z07ebdb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6y8ztliuedt84z07ebdb.png" alt="EDT transformed data" width="800" height="175"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Motion MNIST Architecture
&lt;/h2&gt;

&lt;p&gt;The architecture follows the architecture from the DDPM paper, but with some modifications since we are dealing with video. Normally, you would use a 3D convolution layer and pass everything to it. But due to memory constraint I had to choose a different technique of splitting it into 2. One layer is responsible for spatial data, and another for temporal(time) data. That's why I used a kernel of (1x3x3) and (3x1x1).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;nn.Conv3d&lt;span class="o"&gt;(&lt;/span&gt;in_ch,out_ch,kernel_size&lt;span class="o"&gt;=(&lt;/span&gt;1,3,3&lt;span class="o"&gt;)&lt;/span&gt;, &lt;span class="nv"&gt;padding&lt;/span&gt;&lt;span class="o"&gt;=(&lt;/span&gt;0,1,1&lt;span class="o"&gt;))&lt;/span&gt;,
nn.BatchNorm3d&lt;span class="o"&gt;(&lt;/span&gt;out_ch&lt;span class="o"&gt;)&lt;/span&gt;,
nn.ReLU&lt;span class="o"&gt;()&lt;/span&gt;,
nn.Conv3d&lt;span class="o"&gt;(&lt;/span&gt;out_ch,out_ch,kernel_size&lt;span class="o"&gt;=(&lt;/span&gt;3,1,1&lt;span class="o"&gt;)&lt;/span&gt;, &lt;span class="nv"&gt;padding&lt;/span&gt;&lt;span class="o"&gt;=(&lt;/span&gt;1,0,0&lt;span class="o"&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the time embedding in the DDPM paper, you will see a Sinusoidal embedding inspired by the transformer positional embedding. But I used a simple time embedding, and it worked.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;self.time_mlp &lt;span class="o"&gt;=&lt;/span&gt; nn.Sequential&lt;span class="o"&gt;(&lt;/span&gt;
            nn.Linear&lt;span class="o"&gt;(&lt;/span&gt;1,t_dim&lt;span class="o"&gt;)&lt;/span&gt;,
            nn.ReLU&lt;span class="o"&gt;()&lt;/span&gt;,
            nn.Linear&lt;span class="o"&gt;(&lt;/span&gt;t_dim,t_dim&lt;span class="o"&gt;)&lt;/span&gt;
        &lt;span class="o"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It worked because the problem was easy, i.e. It was predicting geometry since the data is EDT (Euclidean Distance Transform), which is a linear function and a low-frequency task. For a real video, there are low-frequency and high-frequency components. The network has to understand physics, which is not at all smooth. So that's why Sinusoidal embedding is required in that case.&lt;br&gt;
So after that, everything is a simple U-net architecture. Where the image data is compressed, and more non-linearity is increased to learn complex patterns. Then it's upscaled again and concatenated with a similar downscaled step using residual connections. So it can learn both the Simple and Complex Structure.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd80v6bqmu2ail36rce41.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd80v6bqmu2ail36rce41.jpg" alt="Architecture Image" width="800" height="495"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Fun fact: UNET was first introduced for medical image segmentation.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;
  
  
  Training loop
&lt;/h2&gt;

&lt;p&gt;It consists of a scheduler and a normal training loop. The Scheduler decides how much noise should be added at each step. In the original DDPM theory, to get to step 500, you'd logically have to add noise 500 times in a row. That is slow and costly. To fix this, the authors used a property of Gaussians, adding Gaussian noise to Gaussian noise just results in a bigger Gaussian. Instead of stepping through the mud 1,000 times, we use a formula that lets us teleport from the clean image x_0 directly to any noisy step x_t.&lt;br&gt;
The Refinement: It's not just that noise is treated like a constant, but rather that we can express the noisy image at step t as a linear combination of the original image and one single chunk of noise.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqw380jim1aj7xsacnn3r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqw380jim1aj7xsacnn3r.png" alt="Scheduler Equation" width="800" height="206"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The loss function is simple: get the frame where the digit is full, and add noise at that step. Predict the noise against the original noise, calculate Mean Squared Error, and repeat until the loss minimizes.&lt;/p&gt;
&lt;h2&gt;
  
  
  Inference
&lt;/h2&gt;

&lt;p&gt;This is where the actual magic usually happens. During Training we jumped steps using the reparameterization trick. But here we can't do that to reverse the noise. Since the model doesn't know what the image is, i.e. It doesn't have any idea about the global structure, whether it will be '3' or '5'. It only knows how to predict the amount of noise in each step. So it has to go through 1000 steps as per DDPM. But there is a faster method also, which helps us to do that in 50 steps, it is known as DDIM. After the model gives the amount of noise to subtract, the Sampler subtracts the noise from the image.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr32fjwiek5zjscfqi4r4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr32fjwiek5zjscfqi4r4.png" alt="Sampler Equation" width="800" height="170"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Secret Sauce: Temporal Consistency&lt;br&gt;
Since we are building an Animation Model, our sampler has an extra responsibility. In a normal image model, the sampler only cares about one frame. In ours, the sampler ensures that as Frame 1 becomes a "3," Frame 2 is doing the same thing in a slightly different position. By running the denoising process across the entire Temporal Volume (Frames x C x H x W) simultaneously, the sampler ensures that the "movement" is fluid. If we didn't do this, our animation would look like a flickering glitch rather than a moving digit.&lt;/p&gt;

&lt;p&gt;  &lt;iframe src="https://www.youtube.com/embed/RFZZ-EBinIY" width="710" height="399"&gt;
  &lt;/iframe&gt;
&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;So that's what I did for the project. Though the project can't capture the whole essence of video diffusion, it gives a rather simplified approach to how it works. In real video diffusion The conditioning is done on text and time. If you need a more conceptual understanding of diffusion models, you can check out &lt;a href="https://youtu.be/iv-5mZ_9CPY?si=VusdSx_PiHzt4I-E" rel="noopener noreferrer"&gt;3blue1Brown and Welch Lab's video on how do ai images and video works&lt;/a&gt;. If you want to check out my code, you can go through my &lt;a href="https://github.com/Unica2804/Tiny_Diffusion" rel="noopener noreferrer"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>programming</category>
      <category>tutorial</category>
      <category>machinelearning</category>
    </item>
  </channel>
</rss>
