Matra

A sentence-constrained superword tokenizer for Indic scripts. On the MUTANT eval set: aggregate fertility 1.78, 72.5% sequence reduction, 9.10 bytes per token. Produces 31% fewer tokens than Gemini 3.5 Flash, 62% fewer than Qwen-3.6-MoE, and 22% fewer than Sarvam-105B across 24 languages.

UPDATES 2026-07-08 | 10:00 AM Released arXiv preprint: Matra achieves aggregate fertility 1.78, 72.5% sequence reduction, and 9.10 BPT on the MUTANT evaluation set across 24 languages. Outperforms GPT-5, Gemma-4-31B, Gemini 3.5 Flash, Qwen-3.6-MoE, Sarvam-105B, and Sutra-v2. Trains on a 16 GB CPU in 41 minutes from 10 GB of streaming data.
+5 more
Table of Contents

Technical report (arXiv preprint): matra-arxiv-pre.pdf | Previous report: matra_paper_200k.pdf

LLM with Matra as tokenizer is still pending. If anyone wants to help me with compute, hmu @ e-mail

Live Demo

note: visit huggingface space link if the embed fails to load.

Matra: Sentence-Constrained Superword Tokenization for Indic Scripts

200k vocab size. 24 languages. Aggregate fertility 1.78, 72.5% sequence reduction, 9.10 bytes per token.

In active development; more optimization, tests, and language-specific tokenizers coming soon.

Standard byte-pair encoding tokenizers trained on English-centric corpora fragment Indic scripts into single-character tokens, inflating sequence lengths by 3–8× relative to English. Matra addresses this with two modifications to the BPE training pipeline: a sentence-boundary constraint that prohibits cross-sentence merges, and word-level script-frequency weighting that applies XLM-R alpha-smoothing to individual token frequencies. On the MUTANT evaluation set across 22 Indic languages, English, and code, Matra produces fewer tokens and lower fertility than GPT-5, Gemini 3.5 Flash, Gemma-4-31B, Qwen-3.6-MoE, Sarvam-105B, and Sutra-v2.

2,125,481 total tokens to encode the entire MUTANT evaluation corpus: 31% fewer than Gemini 3.5 Flash (3,079,018), 62% fewer than Qwen-3.6-MoE (5,560,104), and 22% fewer than Sarvam-105B (2,714,325).


Architectural Innovations

Tokenization for Indic scripts is hard for a structural reason. A single syllable in Hindi, Tamil, or Kannada may be encoded as 2–4 UTF-8 bytes. A tokenizer trained predominantly on English text will decompose that syllable into individual bytes or Unicode code-points, producing a cascade of single-character tokens. Each extra token increases inference cost and reduces effective context length.

Matra addresses this with the following modifications.

Unicode-Aware Pre-Tokenization

The pre-tokenizer uses a hand-crafted regex pattern that respects Unicode letter, mark, and number categories (\p{L}, \p{M}, \p{N}). Diacritics are kept attached to their base letters. CJK characters are split individually (they are morphologically atomic). Right-to-left scripts and Arabic extensions are handled natively. Whitespace, four-space indents, tabs, newlines are preserved as explicit tokens for code-aware applications.

Language-Weighted Training (XLM-R Scaling)

A two-stage merge strategy with script-aware frequency scaling. During Stage 1, word frequencies are multiplied by a lang_weight factor when the word contains target-script characters - detected via is_target_script() across Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada, Malayalam, Sinhala, Arabic/Perso-Arabic (Urdu, Kashmiri, Sindhi), Ol Chiki (Santali), and Meetei Mayek (Manipuri).

The scaling follows the XLM-R alpha-smoothing formula:

$$w_w = w^{\frac{1-\alpha}{\alpha}}$$

With $\alpha = 0.75$, target-script words receive a ~1.33× frequency boost while English remains unscaled. Stage 2 uses a blended sentence-level multiplier: a sentence with 80% Hindi and 20% English gets 80% of the full weight, preventing code-switched “Hinglish” from distorting the merge budget.

Two-Stage Merge Strategy

Stage 1 learns intra-word subword merges (morphological prefixes, suffixes, character n-grams) constrained within word boundaries. Stage 2 extends merges across word boundaries within a sentence, learning multi-word “superword” compounds. The merge budget is split: transition_vocab_size tokens allocated to Stage 1, the remainder to Stage 2. This decouples morphological learning from syntactic collocation, and no single-character fragment is promoted until both stages complete.

Sentence-Boundary Constraint

Pre-tokenized word tokens are grouped into sentences using a zero-width lookbehind split on [.!?\n।] followed by a lookahead for whitespace. During Stage 2, any merge whose resulting token contains a sentence-terminal character (. ! ? \n ) is permanently prohibited. This prevents semantically invalid tokens like "city.The" or "delhi|mumbai" from ever being learned, preserving clean sentence boundaries for downstream transformer models.

This constraint is absent from both SuperBPE and MUTANT; removing it produces 23 delimiter-spanning tokens in the MUTANT vocabulary and 17 in Sutra-v2. Matra contains zero by construction.

R2L Digit Grouping

Following Singh & Strouse (2024), digit sequences are chunked right-to-left in groups of three using a positive-lookahead regex:

(?:\p{N}{1,3}(?=(?:\p{N}{3})*(?!\p{N})))

This preserves base-10 alignment in right-to-left scripts and prevents the arithmetic hallucination that arises when digit strings are fragmented across arbitrary byte boundaries.

Hapax Legomena Pruning

The drop_singletons flag removes word entries with frequency ≤ 1.0 between Pass 1 and Stage 1. Hapax legomena - words appearing exactly once in the corpus - contribute noise to merge statistics without providing generalizable patterns. Pruning them frees the merge budget for higher-frequency morphological units. Sentences containing pruned words are also filtered before Stage 2.

This is mathematically defensible as a data-efficiency choice; for maximally pure results, drop_singletons defaults to False.


Benchmark Results: MUTANT Evaluation Set (24 Languages)

Benchmark date: July 2026. Evaluation set: MUTANT (22 Indic languages, English, and code). Tokenizers evaluated: Matra, GPT-5, Gemma-4-31B, Gemini 3.5 Flash, Qwen-3.6-MoE, Sarvam-105B, Sutra-v2.

Metrics:

  • SeqRed (Sequence Reduction): percentage reduction in token count versus the raw byte sequence. Higher is better.
  • NSL (Normalised Sequence Length): token count divided by the character count of the source text. Lower is better.
  • BPT (Bytes Per Token): average bytes encoded per token. Higher is better.
  • Fert (Fertility): average tokens produced per word. Lower is better.
  • 1ch%: percentage of tokens that encode a single character. Lower is better.

Aggregate values are language-averaged (mean of per-language values) to give equal weight to each language regardless of corpus size.

Aggregate across all 24 languages

TokenizerSeqRedNSLBPTFert1ch%Total Tokens
Matra72.5%0.13049.101.788.52,125,481
Sarvam-105B65.9%0.15967.082.2328.02,714,325
Sutra-v265.0%0.16106.852.2925.02,820,114
Gemini 3.5 Flash59.9%0.18286.392.600.03,079,018
Gemma-4-31B59.9%0.18286.392.6034.83,078,994
GPT-550.6%0.21635.753.1737.33,593,865
Qwen-3.6-MoE27.4%0.31163.484.8272.85,560,104

Matra encodes the full MUTANT evaluation set in 2,125,481 tokens: 31% fewer than Gemini 3.5 Flash (3,079,018), 62% fewer than Qwen-3.6-MoE (5,560,104), and 22% fewer than Sarvam-105B (2,714,325). The aggregate fertility of 1.78 means the average word across all 24 languages is encoded in under two tokens; the next-best competitor (Sarvam-105B) requires 2.23. At fixed context length, a 22% reduction in token count translates directly to inference cost and latency savings.

Selected per-language highlights

Hindi: Matra achieves a fertility of 1.02, the lowest in the entire benchmark. The next-best is Sarvam-105B at 1.47.

Bengali: Matra achieves fertility 1.30, a 25.3% improvement over MUTANT-Indic (1.74) and well ahead of Sarvam-105B (1.69).

Tamil: Matra achieves fertility 1.91, outperforming Sarvam-105B (2.60) and Sutra-v2 (2.63).

Malayalam: Matra achieves fertility 2.44, the highest among Matra’s own results, reflecting the script’s heavy agglutination. Still ahead of Sarvam-105B (3.45) and Sutra-v2 (3.39).

Manipuri (Meetei Mayek): Where five of seven baselines collapse entirely (GPT-5 fertility 2.21, but with negative sequence reduction in prior benchmarks), Matra achieves fertility 1.91, matching Sarvam-105B and outperforming Sutra-v2 (2.23).

Odia: Where GPT-5 collapses to near-zero sequence reduction and fertility of 6.97, Matra achieves fertility 1.70.

Santali (Ol Chiki): Matra achieves fertility 2.72; Sarvam-105B leads at 2.01 and Sutra-v2 at 2.09. This is a known limitation of the current training corpus on Ol Chiki specifically.

English: Matra achieves fertility 1.15, outperforming all baselines including Sutra-v2 (1.19) and GPT-5 (1.34). Indic gains do not come at the cost of English regression.

Per-language fertility (MUTANT evaluation set)

LanguageMatraSarvam-105BSutra-v2GPT-5
Hindi1.021.471.641.78
Bengali1.301.692.092.47
Tamil1.912.602.633.33
Malayalam2.443.453.393.87
Urdu1.171.441.551.51
Manipuri1.911.912.232.21
Santali2.722.012.0913.57
Odia1.702.252.466.97
English1.151.401.191.34

The gains are not concentrated in a single script family. Devanagari languages achieve fertility between 1.02 and 2.12; Dravidian languages between 1.91 and 2.44; Perso-Arabic scripts between 1.17 and 1.46. The method targets structural properties of all Indic orthographies rather than handcrafted rules for specific languages.

Head-to-head with MUTANT-Indic

On 18 overlapping languages from the MUTANT evaluation set, Matra achieves lower fertility on 15 of 18 languages versus MUTANT-Indic, with a language-averaged fertility of 1.66 versus 1.89 (12.2% improvement).

LanguageMatraMUTANT-IndicGain
Hindi1.021.23+17.1%
Bengali1.301.74+25.3%
Gujarati1.521.77+14.1%
Punjabi1.231.39+11.5%
Tamil1.912.12+9.9%
Assamese1.681.85+9.2%
Kannada2.032.19+7.3%
Nepali1.511.62+6.8%
Marathi1.551.63+4.9%
Dogri1.391.45+4.1%
Bodo2.122.04−3.9%
Odia1.701.65−3.0%
English1.151.12−2.7%
Maithili1.691.58−7.0%
Malayalam2.442.30−6.1%
Sanskrit2.892.59−11.6%
Telugu2.221.88−18.1%
Santali2.723.72+26.9%
Average1.661.89+12.2%

Delimiter-spanning token analysis

A preliminary analysis of baseline vocabularies reveals semantically invalid tokens produced by cross-boundary merges:

TokenizerCountExamples
MUTANT23"hi. the", "delhi|mumbai"
Sutra-v217"word1. word2", "end!next"
Matra0None (prohibited by construction)

The sentence-boundary constraint eliminates an entire class of alignment artifacts without any cost to compression ratio. When a high-frequency merge is prohibited, the merge budget is simply filled by the next-most-frequent valid pair.

Cross-lingual parity

Under GPT-5, English achieves fertility 1.34 while the average Indic fertility is 3.17 a ratio of 2.4×. Under Matra, English achieves 1.15 and the average Indic fertility is 1.78 a ratio of 1.5×. The script-frequency weighting closes roughly half of the parity gap without any degradation to English compression.

Vocab size scaling: 128K vs. 200K

MetricMatra 128KMatra 200KChange
Aggregate Fertility ↓1.911.78−6.8%
BPT ↑8.219.10+10.8%

Scaling from 128K to 200K follows a logarithmic law consistent with SuperBPE’s English results. The 128K variant remains a compact alternative for deployment environments where embedding table size is at a premium.


Previous Benchmark: IN22-Gen (23 Languages)

The following results are from the June 2026 IN22-Gen benchmark at 200K tokens per language. They are preserved for reference and comparison with the newer MUTANT evaluation above.

TokenizerSeqRedNSLBPTFert1ch%Total Tokens
Matra70.3%0.12258.902.067.51,103,089
Sutra-v264.6%0.14537.292.4725.11,311,098
Sarvam-105B64.9%0.14547.352.4529.21,301,947
Gemini 3.5 Flash51.5%0.19596.283.340.01,794,568
Gemma-4-31B51.5%0.19596.283.3439.31,794,545
GPT-537.4%0.24945.584.2744.72,327,945
Qwen-3.6-MoE13.2%0.34183.356.0777.63,225,298
Full IN22-Gen per-language breakdown (23 languages × 8 tokenizers): click to expand
LanguageTokenizerSeqRed↑NSL↓BPT↑Fert↓1ch%↓Tokens
as (Assamese)GPT-557.4%0.15976.262.9738.068,816
Gemini 3.5 Flash58.9%0.15416.492.870.066,401
Gemma-4-31B58.9%0.15416.492.8740.666,400
Matra71.9%0.10539.501.966.745,342
Qwen-3.6-MoE23.9%0.28533.505.3180.7122,906
Sarvam-105B58.9%0.15416.492.8740.666,400
Sutra-v267.3%0.12258.162.2826.252,789
bn (Bengali)GPT-563.0%0.13867.212.5631.155,995
Gemini 3.5 Flash72.9%0.10149.871.870.040,951
Gemma-4-31B72.9%0.10149.871.8719.740,950
Matra77.4%0.084611.821.567.534,179
Qwen-3.6-MoE31.1%0.25763.884.7668.6104,090
Sarvam-105B72.9%0.10149.871.8719.740,950
Sutra-v268.1%0.11938.382.2124.348,208
brx (Bodo)GPT-548.5%0.19315.183.9642.684,466
Gemini 3.5 Flash53.9%0.17295.783.540.075,637
Gemma-4-31B53.9%0.17295.783.5433.675,636
Matra65.1%0.13127.622.695.757,376
Qwen-3.6-MoE28.1%0.26973.715.5276.4117,971
Sarvam-105B53.9%0.17295.783.5433.675,636
Sutra-v249.6%0.18935.283.8839.282,800
doi (Dogri)GPT-557.5%0.16566.042.3141.067,844
Gemini 3.5 Flash62.7%0.14536.882.030.059,505
Gemma-4-31B62.7%0.14536.882.0332.459,504
Matra67.4%0.12687.881.773.851,960
Qwen-3.6-MoE30.5%0.27063.703.7879.0110,857
Sarvam-105B62.7%0.14536.882.0332.459,504
Sutra-v259.1%0.15926.282.2235.165,232
en (English)GPT-579.1%0.20894.791.3215.333,561
Gemini 3.5 Flash78.3%0.21734.601.380.034,920
Gemma-4-31B78.3%0.21734.601.3820.234,919
Matra81.0%0.19045.251.2111.430,595
Qwen-3.6-MoE77.7%0.22324.481.4218.835,869
Sarvam-105B78.3%0.21734.601.3820.234,919
Sutra-v280.9%0.19095.241.215.330,675
gu (Gujarati)GPT-560.2%0.15146.612.5634.659,667
Gemini 3.5 Flash57.7%0.16106.212.730.063,455
Gemma-4-31B57.7%0.16106.212.7336.163,454
Matra73.4%0.10149.861.729.139,973
Qwen-3.6-MoE18.4%0.31053.225.2691.4122,402
Sarvam-105B65.9%0.12987.702.2026.951,161
Sutra-v264.5%0.13517.402.2926.453,260
hi (Hindi)GPT-567.7%0.12587.951.7622.451,905
Gemini 3.5 Flash72.1%0.10889.191.520.044,886
Gemma-4-31B72.1%0.10889.191.5218.144,885
Matra79.9%0.078112.801.096.032,218
Qwen-3.6-MoE34.3%0.25603.913.5773.1105,590
Sarvam-105B72.1%0.10889.191.5218.144,885
Sutra-v269.4%0.11928.391.6617.349,182
kn (Kannada)GPT-558.9%0.15076.643.7840.171,024
Gemini 3.5 Flash59.4%0.14876.723.730.070,092
Gemma-4-31B59.4%0.14876.723.7337.670,091
Matra72.7%0.100010.002.509.947,119
Qwen-3.6-MoE19.6%0.29473.397.3883.9138,860
Sarvam-105B68.0%0.11748.522.9428.255,326
Sutra-v267.2%0.12008.333.0126.056,554
kok (Konkani)GPT-556.5%0.16476.073.1338.266,568
Gemini 3.5 Flash59.9%0.15206.582.880.061,431
Gemma-4-31B59.9%0.15206.582.8832.561,430
Matra70.7%0.11129.002.117.744,936
Qwen-3.6-MoE27.8%0.27353.665.1978.0110,566
Sarvam-105B59.9%0.15206.582.8832.561,430
Sutra-v258.9%0.15596.412.9632.963,018
ks (Kashmiri)GPT-535.9%0.35452.823.6867.3104,745
Gemini 3.5 Flash43.1%0.31443.183.260.092,891
Gemma-4-31B43.1%0.31443.183.2661.092,890
Matra55.2%0.24754.042.577.373,121
Qwen-3.6-MoE30.6%0.38392.603.9872.7113,435
Sarvam-105B43.1%0.31443.183.2661.092,890
Sutra-v245.1%0.30323.303.1546.889,598
mai (Maithili)GPT-561.7%0.14546.882.3135.257,157
Gemini 3.5 Flash64.9%0.13327.512.110.052,360
Gemma-4-31B64.9%0.13327.512.1134.552,359
Matra72.2%0.10549.491.675.041,417
Qwen-3.6-MoE29.1%0.26943.714.2877.5105,896
Sarvam-105B64.9%0.13327.512.1134.552,359
Sutra-v260.6%0.14976.682.3838.658,848
ml (Malayalam)GPT-562.9%0.13477.434.0134.368,334
Gemini 3.5 Flash64.4%0.12947.733.850.065,635
Gemma-4-31B64.4%0.12947.733.8532.165,634
Matra72.3%0.10069.942.996.951,027
Qwen-3.6-MoE16.7%0.30233.319.0086.5153,397
Sarvam-105B68.1%0.11598.633.4527.658,822
Sutra-v268.5%0.11438.753.4025.058,019
mni (Manipuri)GPT-5-151.4%0.94611.0616.5099.6386,349
Gemini 3.5 Flash-85.6%0.69841.4312.180.0285,205
Gemma-4-31B-85.6%0.69841.4312.1891.9285,204
Matra53.6%0.17475.723.0512.371,346
Qwen-3.6-MoE-151.4%0.94611.0616.5099.6386,359
Sarvam-105B66.7%0.12547.972.1923.351,212
Sutra-v267.3%0.12308.132.155.650,247
mr (Marathi)GPT-562.5%0.14047.122.7331.060,860
Gemini 3.5 Flash70.3%0.11148.982.170.048,287
Gemma-4-31B70.3%0.11148.982.1721.048,286
Matra76.5%0.088011.371.719.438,130
Qwen-3.6-MoE27.7%0.27073.695.2776.3117,368
Sarvam-105B70.3%0.11148.982.1721.048,286
Sutra-v268.9%0.11658.592.2722.450,484
ne (Nepali)GPT-564.8%0.13087.652.5427.354,170
Gemini 3.5 Flash67.6%0.12068.292.340.049,957
Gemma-4-31B67.6%0.12068.292.3422.849,956
Matra76.4%0.087811.381.705.936,387
Qwen-3.6-MoE29.5%0.26193.825.0873.0108,505
Sarvam-105B67.6%0.12068.292.3422.849,956
Sutra-v269.4%0.11398.782.2121.447,170
or (Odia)GPT-5-0.1%0.37462.677.3198.6175,015
Gemini 3.5 Flash28.1%0.26903.725.250.0125,669
Gemma-4-31B28.1%0.26903.725.2574.4125,668
Matra71.5%0.10659.392.087.849,755
Qwen-3.6-MoE11.4%0.33143.026.4792.7154,810
Sarvam-105B68.7%0.11708.552.2828.354,656
Sutra-v267.3%0.12228.182.3930.057,095
pa (Punjabi)GPT-545.8%0.21464.662.7656.879,889
Gemini 3.5 Flash43.2%0.22504.442.900.083,750
Gemma-4-31B43.2%0.22504.442.9061.283,749
Matra72.4%0.10949.141.414.940,728
Qwen-3.6-MoE16.6%0.33013.034.2594.9122,894
Sarvam-105B64.5%0.14047.121.8127.852,261
Sutra-v269.5%0.12088.281.5518.644,952
sa (Sanskrit)GPT-552.5%0.17515.714.5644.075,377
Gemini 3.5 Flash58.4%0.15356.523.990.066,066
Gemma-4-31B58.4%0.15356.523.9935.966,065
Matra70.9%0.10719.342.796.446,087
Qwen-3.6-MoE23.9%0.28053.577.3075.8120,747
Sarvam-105B58.4%0.15356.523.9935.966,065
Sutra-v255.8%0.16306.144.2437.670,150
sat (Santali)GPT-5-164.5%0.99611.0016.5993.9442,477
Gemini 3.5 Flash-2.0%0.38432.606.400.0170,688
Gemma-4-31B-2.0%0.38432.606.4084.5170,687
Matra47.4%0.19805.053.3012.687,934
Qwen-3.6-MoE-150.2%0.94251.0615.6999.6418,656
Sarvam-105B65.1%0.13137.612.1926.958,338
Sutra-v267.1%0.12408.072.063.755,070
sd (Sindhi)GPT-553.4%0.18165.512.5746.274,948
Gemini 3.5 Flash56.8%0.16845.942.380.069,496
Gemma-4-31B56.8%0.16845.942.3839.869,495
Matra62.8%0.14496.902.056.059,806
Qwen-3.6-MoE27.6%0.28233.543.9981.0116,498
Sarvam-105B56.8%0.16845.942.3839.869,495
Sutra-v255.7%0.17295.792.4436.071,326
ta (Tamil)GPT-563.7%0.13307.523.3930.268,509
Gemini 3.5 Flash71.8%0.10359.672.630.053,282
Gemma-4-31B71.8%0.10359.672.6321.353,281
Matra77.3%0.083112.032.118.442,797
Qwen-3.6-MoE26.0%0.27153.686.9176.6139,809
Sarvam-105B71.8%0.10359.672.6321.353,281
Sutra-v271.3%0.10519.512.6819.654,142
te (Telugu)GPT-558.7%0.15436.483.3037.265,917
Gemini 3.5 Flash61.2%0.14486.903.100.061,879
Gemma-4-31B61.2%0.14486.903.1032.361,878
Matra72.8%0.10179.842.188.643,437
Qwen-3.6-MoE18.0%0.30633.266.5590.1130,885
Sarvam-105B67.4%0.12178.222.6027.351,991
Sutra-v267.1%0.12318.132.6323.752,576
ur (Urdu)GPT-565.1%0.19625.101.6922.954,352
Gemini 3.5 Flash66.5%0.18825.311.620.052,125
Gemma-4-31B66.5%0.18825.311.6220.852,124
Matra76.0%0.13517.401.162.337,419
Qwen-3.6-MoE57.0%0.24164.142.0839.166,928
Sarvam-105B66.5%0.18825.311.6220.852,124
Sutra-v268.1%0.17945.571.5416.549,703

Limitations and Known Behaviour

Matra underperforms Sarvam-105B and Sutra-v2 on Santali in absolute fertility (2.72 vs. 2.01 and 2.09 respectively). These systems appear to have greater Ol Chiki representation in their training corpora. On Telugu, MUTANT-Indic achieves 1.88 versus Matra’s 2.22, and on Malayalam, MUTANT-Indic achieves 2.30 versus Matra’s 2.44. These are training data limitations, not algorithmic ones.

Downstream task evaluation is absent from the current paper. Fertility improvements are necessary but not sufficient evidence that a tokenizer improves model quality. Perplexity and task accuracy experiments require training language models on comparable data with comparable compute budgets, which is compute-intensive. This is an explicit limitation and future work direction.

The sentence-boundary constraint assumes that sentence boundaries are unambiguous and correctly detected by the pre-tokenizer. For highly informal text with non-standard punctuation, this assumption may fail. Evaluating on social media or conversational data is not done in this work.

Cython compilation is optional. The pure-Python pipeline is identical in output; only training speed differs (4-5× slower without the compiled extensions).


Reproducing the Benchmark

The primary benchmark was run on the MUTANT evaluation set using the script included in the repository. Tokenizer weights for GPT-5, Gemma-4-31B, Gemini 3.5 Flash, Qwen-3.6-MoE, Sarvam-105B, and Sutra-v2 were loaded from their respective public releases. Matra was trained on 10 GB of curated multilingual text; the benchmark corpus was not seen during training.

All metrics are computed at the token level against the original UTF-8 byte stream. The tokenizer serializes to a standard GPT-2-compatible JSON format (vocab + merges) that loads directly into HuggingFace tokenizers. Round-trip fidelity is guaranteed: decode(encode(x)) = x for any valid UTF-8 input x.


System Implementation

2-Pass Streaming Architecture

A naive in-memory BPE trainer accumulates four large dicts simultaneously: word sequences, word frequencies, word-to-string maps, and sentence counters. On a 10 GB corpus, this peaks at ~75 GB RAM.

Matra splits training into two streaming passes:

  1. Pass 1: Stream the corpus, populate word-level dicts, run Stage 1 BPE, then delete all word dicts and call gc.collect().
  2. Pass 2: Re-stream the corpus, populate sentence-level statistics, and run Stage 2 BPE.
Phase1-Pass RAM2-Pass RAM
Word accumulation~60 GB~2-3 GB
Stage 1 BPE~70 GB~3-4 GB
Sentence accumulation~75 GB~1-2 GB
Stage 2 BPE~75 GB~3-4 GB
Peak~75 GB~5-6 GB

On a 16 GB machine, training completes in ~41 minutes from 10 GB of streaming data. No GPU or external compiler is required.

Memory Cap

Stage 2 operates on a single concatenated 1D array. Each merge creates new pairs at affected boundaries, most of which are singletons (freq=1). BPE requires freq >= 2 to merge, but the dict still holds singletons. With millions of merges, the dict grows unboundedly.

When len(pair_counts) > max_pairs (default 3,000,000), all singleton pairs are purged and the heap is rebuilt. No pair with freq <= 1 can ever be selected for merging, so this is lossless. Early stopping terminates the loop when the top heap entry drops below frequency 2. Combined effect: Stage 2 peak RSS stays below ~2.5 GB.

Checkpointing

The trainer auto-saves a .ckpt file after each phase boundary, keyed by a SHA-256 hash of the training config. This enables crash recovery and hyperparameter sweeps: a killed run can be resumed from any phase boundary, and re-running with a different vocab_size but identical earlier config skips completed passes from cache.

Checkpoints are written atomically (.tmp + os.replace()). On load, __version__, __stage__, and config_hash are verified against the current run; mismatches raise ValueError.

Cython Compilation

The inner merge loop and pair-position builder are optionally compiled with Cython via pyximport. When available, they replace the equivalent Python loops at the two points that dominate training time. On a 200k-token corpus the difference is roughly 4–5× wall-clock time. The pure-Python fallback remains correct and usable without a build step.

Inference Optimizations

At inference time, the byte-to-token mapping is pre-computed as a 256-entry tuple indexed by raw byte value, eliminating per-byte dictionary lookups. The merge pass uses a lazy min-heap with integer-keyed _merge_ranks_int maps pairs are resolved via (id0, id1) → rank lookups instead of string hashing. A bounded LRU cache (default 2,000,000 entries) means repeated subwords pay zero merge cost after the first occurrence. End-to-end complexity is $O(n \log n)$ per sentence in the number of pre-tokenization tokens.