Your BPE encode() is correct but tokenizing a 2TB corpus takes three weeks. The tech lead suggests a Rust rewrite. Why is that the second priority, not the first?

The Problem: A pretraining team’s byte-level BPE encode() produces the right token IDs, but one Python process on a 64-core machine pushes the 2 TB corpus through at 1.1 MB/s, an ETA of 21 days. A profile puts 70% of the time inside encode(), and the tech lead proposes a Rust rewrite estimated at 10x on that step.
Answer
A Rust rewrite attacks the wrong number first. Rewriting encode() only accelerates the share of runtime spent inside it. By Amdahl’s law, a 10x faster encode on a 70% share yields 2.70x end to end, and even an infinitely fast one caps at 3.33x. Meanwhile 63 of 64 cores sit idle, and tokenization is embarrassingly parallel across documents, so one process per core gives roughly 57x with no change to the encoding logic. Overlapping storage waits with compute and caching repeated pre-tokens recover most of the remaining waste. Only after the pipeline saturates every core does per-core speed decide the bill, and then the right move is usually to adopt an existing Rust tokenizer behind a byte-exact differential test.
(1) Profile Before Choosing A Lever: A sampling profiler such as py-spy splits wall-clock time into read wait, parse, encode, and write wait. Those shares decide which speedups are even reachable.
(2) Amdahl Caps Any Single-Stage Rewrite: Speeding up a stage that takes a fraction of runtime can never beat
, which is 3.33x here no matter how good the Rust code is.
(3) Shard First, Because Documents Are Independent: Run one worker process per core, not threads, since the GIL serializes pure-Python BPE. Pass shard paths rather than text, and the output stays byte-identical because encode() is untouched.
(4) Overlap IO With Compute: Prefetch the next shard and write asynchronously through bounded queues, so a worker runs at the pace of its slowest stage instead of the sum of all stages.
(5) Fix The Algorithm Before The Language: A pre-token cache skips repeated merge loops on Zipfian text, and a priority-queue merge removes the quadratic worst case on long pre-tokens.
(6) Rust Comes Last, And Usually Off The Shelf: Once every core is busy, per-core cost equals core-hours, so a native encoder pays. Adopt Hugging Face tokenizers or tiktoken and gate it on a token-ID differential test against the Python reference.
Mathematical Formulation:
Where:
is the end-to-end speedup when only encode() becomes
times faster, and
is encode’s share of single-process runtime (0.70 in this job).
is the Amdahl ceiling reached by an infinitely fast encoder, because the other
of the time is untouched.
is the speedup from
parallel workers, and
is the serial fraction (shard listing, manifest merge) that no worker count shrinks, about 0.002 here.
is the per-shard time of stage
, so
is a blocking worker and
a worker whose stages overlap.
Worked Example (504 hours today, p = 0.70, f = 0.002):
The two levers are not symmetric. Every encode-only change competes for the same 70% slice, whether it is a Rust port, a C extension, or a cache, and none of them can beat 151 hours on one process. Sharding instead multiplies the whole pipeline. Each of the 4,000 shards tokenizes independently, and the only serial work is roughly an hour of listing and manifest merging. It also leaves encode() untouched, so the output is byte-identical to today’s and needs no new correctness argument. The levers compose rather than compete: once the job is sharded, a faster encoder still divides the 7.86 parallel hours by 2.70. That is why the Rust work is deferred, not cancelled.

Figure 1: Left, the two levers on the same log axes. Making encode() faster flattens at the 3.33x Amdahl ceiling however good the rewrite is, while adding shard workers keeps paying until the 0.2% serial share starts to bite. Right, the resulting wall-clock: the Rust-only plan still takes 7.8 days, 64 workers finish in 8.9 hours, and adding the Rust encoder brings that to 3.9 hours.
Two cheaper fixes sit between sharding and a rewrite. The first is to overlap IO with compute. Today each worker idles for 15% of a shard waiting on reads and 10% waiting on writes. A background thread that prefetches the next shard into a bounded queue, plus an asynchronous writer, removes those stalls because blocking syscalls release the GIL. The second is to fix the algorithm. Byte-level BPE runs its merges inside each regex pre-token, and pre-token frequencies are Zipfian, so a pre-token cache from word to IDs skips most merge loops (GPT-2’s reference encoder already memoizes this way). A merge loop that rescans every adjacent pair on each step is quadratic in pre-token length, so a single 1 MB base64 blob can stall a shard for minutes. A priority-queue merge over a linked list brings that to , and a pre-token length cap guards the rest. After all of this plus Rust, 64 workers consume close to 200 MB/s of text, so the next bottleneck is often storage rather than code.
| Property | Shard workers and IO overlap | Pre-token cache and heap merge | Rust rewrite of encode() |
|---|---|---|---|
| What it targets | The whole pipeline: 63 idle cores and 25% storage stalls | The 70% encode share, by skipping repeated and quadratic work | The 70% encode share, by a constant factor per core |
| Engineering effort | About a day: process pool over shard paths, prefetch thread, async writer | A few days: memo dict on pre-tokens, priority-queue merge, length cap | Weeks to write, or hours to adopt an existing library |
| Effect on the 504 h job | About 57x, down to 8.9 h, before counting the overlap gain | Depends on hit rate, and capped at 3.33x like any encode-only fix | 2.70x alone (187 h); multiplies on top of sharding (3.9 h) |
| Risk to token IDs | None: encode logic is unchanged | Low: the cache returns the function’s own output | High: pre-tokenizer regex and merge tie-breaks must match byte for byte |
Leave a Reply