mcut
A zero-copy, low-memory, high-throughput tokenization library supporting mixed-script input (Simplified Chinese, Traditional Chinese, Japanese, Thai, etc.), designed for full-text search, hit highlighting, and resource-constrained scenarios.
New words and contemporary social-media buzzwords are naturally segmented without manual rules (e.g., 企业的护城河是什么 → 企业 / 的 / 护城河 / 是 / 什么, 新能源汽车供应链、高性价比微服务、去中心化区块链与半导体光刻机 → 新能源汽车 / 供应链 / 高性价比 / 微服务 / 去中心化 / 区块链 / 与 / 半导体 / 光刻机, 这一届网友都说嘉豪很有松弛感,打工人面对草台班子,逛小红书看脆友聊智能体和豆包还有青鳥行动 → 这 / 一届 / 网友 / 都 / 说 / 嘉豪 / 很 / 有 / 松弛感 / 打工人 / 面对 / 草台班子 / 逛 / 小红书 / 看 / 脆友 / 聊 / 智能体 / 和 / 豆包 / 还有 / 青鳥 / 行动). For cross-script domain-specific terms such as C++, Rust语言, GPT-4o模型, they can be pinned as atomic tokens directly via a pre-built .mdict user dictionary.
Exposes only a unified multilingual auto-detection interface: both the out-of-the-box global instance MCUT and the configurable Cutter::builder() implement the zero-cost static-dispatch trait Cut. The core logic crate mcut is fully decoupled from language-partitioned optional model packages (defaults to embedding the large vocabulary; small vocabulary or full exclusion via external mounting are also available); all models are lazily page-mapped on demand through &'static [u8] read-only slices, with zero heap allocation at cold start. Inference uses a pure CJK-stack fast path + fearless_simd vectorized boundary detection; steady-state cut_each incurs zero heap allocation. The entire crate is #![forbid(unsafe_code)].
- Performance Benchmarks
- Usage and Tokenization Modes
- Tokenization Results for Common Chinese Sentences
- Algorithm and Design
- Offline Training and Pre-built Dictionaries
- Performance Benchmark Details
Performance Benchmarks
Test platform: Apple M2 Max (darwin · arm64 · local benchmark · bench profile (LTO=fat)); each engine benchmarked in an isolated child process (mcut_bench):
| Engine | Cold Start (ms) | Resident Live Heap (KB) | Max RSS (KB) | zh_doc (MB/s) | zht_doc (MB/s) | mixed_doc (MB/s) | Steady-state Allocs/Call |
|---|---|---|---|---|---|---|---|
mcut-stream |
15.22 | 0.0 | 10560 | 234.20 | 245.84 | 84.16 | 0 allocs / 0 B |
mcut-sm |
6.77 | 0.0 | 5760 | 255.18 | 265.73 | 82.80 | 0 allocs / 0 B |
jieba-rs |
52.59 | 33273.4 | 39376 | 206.29 | 171.57 | - | 1 alloc / 142416 B |
charabia |
106.58 | 45791.6 | 50704 | 24.75 | 26.87 | 33.12 | 2525 allocs / 662424 B |
- Zero heap residency & extremely low RSS:
mcut-stream/mcut-smrely solely on read-only page-fault mappings via&'static [u8], withInit Heap = 0.0 KB— roughly an order of magnitude less physical memory thanjieba-rs(32.5 MB heap) andcharabia(44.7 MB heap). - Zero heap allocation on the hot path: the
cut_eachstreaming interface performs0heap allocations per document segmentation;jieba-rsandcharabiatrigger1and thousands of heap allocations per call, respectively. - Simplified/Traditional Chinese & full multilingual coverage:
mcut-streamandmcut-smnatively support Simplified Chinese, Traditional Chinese, Japanese, Thai, and mixed seven-language text;charabiaomits Japanese under its default offline feature set — see full benchmark details.
Usage and Tokenization Modes
The examples below are logically consistent with cut.rs:
use ;
;
Tokenization Modes
CutMode::Precise: single-pass optimal segmentation based on point-wise boundary scores, with protection for Thai TCC syllable clusters and user-dictionary hard boundaries.CutMode::Search: on top of precise terms, supplements dictionary-hit 2/3-character subwords for words longer than 2 characters; long out-of-vocabulary words that miss dictionary subwords are split at weak boundaries by a negative threshold before emitting the original word, improving inverted-index recall for search engines.CutMode::Full: enumerates all dictionary prefix matches (including cross-script user dictionaries), suitable for dictionary-hit analysis; CJK characters with no dictionary hit fall back to single characters, Japanese to fine-grained script segments, and Thai to TCC clusters.
Non-space-delimited scripts (Korean, English, Russian, Arabic, Greek, Hebrew, Devanagari, etc.) automatically preserve intra-word apostrophes, hyphens, underscores, and thousands/decimal-point connectors in both precise and search modes (e.g., UTF-8, GPT-4o, v1.20.3, 1,000,000, 3.5, don't, по-русски, foo_bar); all numerals are uniformly tagged as TokenKind::Number.
Vocabulary Tiering, Package Splitting, and Feature Gating
Model weights are partitioned by "language × scale" into 6 zero-dependency #![no_std] data crates, strictly gated via dep: for on-demand pull-in; future algorithm-crate upgrades no longer require re-downloading dictionary data. When large and small features for the same language are both enabled (e.g., --all-features or mixed multi-crate dependencies), additive priority selects the large vocabulary and the linker's dead-code elimination removes the small one:
| Feature / vocab package | Vocabulary / slot size | Raw size | Compressed download (gz) |
Held-out eval word_F1 |
|---|---|---|---|---|
mcut_zh (zh, default) |
158,000 words / 328,032 slots | 4.15 MiB | 2.12 MiB | Simplified Chinese 0.9804 (boundary 0.9930) · Traditional Chinese 0.9591 |
mcut_ja (ja, default) |
60,000 words / 161,960 slots | 2.09 MiB | 1.03 MiB | Japanese 0.9843 (boundary 0.9943) |
mcut_th (th, default) |
35,000 words / 158,360 slots | 1.99 MiB | 1.00 MiB | Thai 0.9214 (boundary 0.9703) |
mcut_zh_sm (zh-sm) |
48,000 words / 101,360 slots | 1.35 MiB | 0.68 MiB | Simplified Chinese 0.9162 (boundary 0.9695) · Traditional Chinese 0.8863 |
mcut_ja_sm (ja-sm) |
25,000 words / 60,328 slots | 0.82 MiB | 0.39 MiB | Japanese 0.9816 (boundary 0.9933) |
mcut_th_sm (th-sm) |
24,000 words / 108,576 slots | 1.37 MiB | 0.68 MiB | Thai 0.9015 (boundary 0.9629) |
- Default features:
default = ["global", "lg"](enables the globalMCUTand the large vocabularies forzh/ja/th, totaling8.23 MiBraw /4.15 MiBgzdownload across the three languages). - Lightweight edge build:
default-features = false, features = ["global", "sm"](three languages' small vocabularies total3.54 MiBraw /1.76 MiBgzdownload). - Per-language trimming and mixing: supports enabling
zhalone, or mixing such as["global", "zh", "ja-sm"]. - External zero-embedding:
default-features = falseembeds no model orMCUTat all; pair withModel::from_slice/UserDict::from_sliceto zero-copy map runtimemmapslices directly; when overriding a language viaCutter::builder().with_model(model), the corresponding built-in.rodatapages are never accessed.
Tokenization Results for Common Chinese Sentences
The following is the measured output of MCUT via mcut_bench -- --sample on common Chinese ambiguous sentences, Traditional Chinese sentences, and multilingual mixed sentences:
| Source | Precise mode | Search mode |
|---|---|---|
| Nanjing Yangtze River Bridge | Nanjing / Yangtze River Bridge | Nanjing / Nanjing / Yangtze / Bridge / Yangtze River Bridge |
| The married and the not-yet-married | married / 's / and / not yet / married / 's | married / 's / and / not yet / married / 's |
| Study the origin of life | study / life / 's / origin | study / life / 's / origin |
| Table tennis auction finished | table tennis / auction / finished | ping-pong / table tennis / auction / finished |
| On a rainy day keep the guest, the sky keeps the person, not keep | rainy day / keep / guest / day / keep person / not keep | rain / rainy day / rainy day / keep / guest / day / keep person / not keep |
| The female officer of the Industry and Information Technology Department must, every month as she passes through the subordinate offices, personally hand over instructions on the installation of 24-port switches and other technical components | industry / information / female / officer / every month / pass / subordinate / office / all / need / personally / hand over / 24 / port / switch / etc / technical / component / 's / installation / work | industry / information / female / officer / every month / pass / subordinate / office / all / need / personally / hand over / 24 / port / switch / switch / etc / technical / technical / component / 's / installation / work |
| The People's Bank of China announces a cut in the deposit reserve ratio | People's Bank of China / announce / cut / deposit / reserve / ratio | China / Chinese / people / bank / Chinese / People's Bank of China / announce / cut / deposit / prepare / reserve / ratio |
| Rust 1.85 supports UTF-8, GPT-4o and v1.20.3 high-performance full-text search | Rust / 1.85 / supports / UTF-8 / GPT-4o / and / v1.20.3 / high-performance / full-text / search | Rust / 1.85 / supports / UTF-8 / UTF / 8 / GPT-4o / GPT / 4o / and / v1.20.3 / v1 / 20 / 3 / performance / high-performance / full-text / search |
| I use C++ and the Rust language to develop a search engine | I / use / C / and / Rust / language / develop / search engine | I / use / C / and / Rust / language / develop / search / index / engine / search engine |
| Today I go to the Nanjing Yangtze River Bridge. 明日は東京でテストします。 | today / go / Nanjing City / Yangtze River Bridge / 明日 / は / 東京 / で / テスト / し / ます | today / go / Nanjing / Nanjing City / Yangtze / Bridge / Yangtze River Bridge / 明日 / は / 東京 / で / テス / スト / テスト / し / ます |
| Traditional Chinese search engine and artificial intelligence database system | traditional / Chinese / search / engine / and / artificial intelligence / database / system | traditional / Chinese / search / engine / and / artificial / intelligence / artificial intelligence / data / database / system |
| The Taipei City Government promotes high-speed rail and natural language processing technology | Taipei City / government / promote / high-speed rail / and / natural language / processing / technology | Taipei / Taipei City / government / promote / high-speed / rail / high-speed rail / and / natural / language / natural language / processing / technology |
| Traditional Chinese and Japanese テスト and Rust 1.85 mixed search engine | Traditional / Chinese / and / Japanese / テスト / and / Rust / 1.85 / mixed / search / engine | Traditional / Chinese / and / Japanese / テス / スト / テスト / and / Rust / 1.85 / mixed / search / engine |
New words and contemporary social buzzwords are likewise segmented naturally without manual rules (e.g. 这一届网友都说嘉豪很有松弛感,打工人面对草台班子,需要情绪价值也被视频硬控,逛小红书看脆友聊大模型、智能体和豆包还有青鳥行动 → 这 / 一届 / 网友 / 都 / 说 / 嘉豪 / 很 / 有 / 松弛感 / 打工人 / 面对 / 草台班子 / 需要 / 情绪价值 / 也 / 被 / 视频 / 硬控 / 逛 / 小红书 / 看 / 脆友 / 聊 / 大模型 / 智能体 / 和 / 豆包 / 还有 / 青鳥 / 行动). For cross-script domain-specific terms such as C++, Rust语言, and GPT-4o模型, you can lock whole words directly via a prebuilt .mdict user dictionary (see step 4 in the previous section).
Algorithm and Design
- Block-vectorized dot-product linear classification (PLC): Drawing on Vaporetto, tokenization is modeled as linear scoring at each character gap, eliminating the Viterbi lattice and heap-allocated dynamic arrays entirely. The regular path employs a fixed 128-slot contiguous stack buffer with fearless_simd
i16x8prefix-trimmed batch boundary detection; pure BMP Chinese short phrases further fall into a minimal stack fast path, decoding directly with 3-byte steps, pre-foldingHAN4type bias, and—under a mathematically proven guarantee of noi16overflow—accumulating via a single-instructionwrapping_add, with constant $O(1)$ extra working memory.Searchmode reuses 2/3-character dictionary hit results recorded intou64/u128bitmasks during the scoring phase, eliminating a second lookup for long words. - 8-slot SWAR SwissTable fused prefix trie (
FusedTrie): Fuses single-character weights, 2/3-gram weights, and two-level dictionary prefix matching into a single static zero-copy structure, validated at load time via fixed slot-group slicing to avoid hot-path segmentation and division overhead. Hot-zone BMP Chinese characters map in one step through a direct-index array to 14-bit compact character IDs; the 4-byte single-character weight table resides in L1 cache; transition slots at depth ≥ 2 employ per-group-of-8u64carryless SWAR 7-bit label parallel comparison, so that ~95% of miss queries terminate after loading the single-character control byte without touching the main slot table; internal nodes additionally carry a 20-bit child bloom filter and 2-bit dictionary strength level bits, paired with 4-character-ahead software prefetch to mask memory access latency. - SIMD sentence-boundary scanning and cross-script routing: documents without hiragana are fast-judged in bulk via
fearless_simdu8x16to skip sentence-level segmentation entirely; CJK punctuation and fullwidth symbols bypass the Unicode slow-table lookup through interval fast paths; documents containing hiragana combine kana with 515 mutually exclusive Sino-Japanese characters (a compile-time[u64; 328]bitmap lookup,O(1)) to automatically determine Chinese, Japanese, or intra-sentence mixed segmentation routing. - Unified zero-cost trait abstraction:
Cutunifies theMCUT,Cutter, andPlcSegmenterentry points;LangCutandLangPackextend new languages through the compile-time generic chainLangChain<L, E>(or slice/Vec), and the zero-size placeholderNoLang::IS_EMPTYeliminates redundant branches at compile time. .mcutand.mdictbinary formats:.mcut(80-byte file header containing 30 bytes of two-level dictionary weights + type table +FusedTrie) and.mdict(32-byte file header + mixed-script marker + Daciuk minimal acyclic FST) both carry a magic number, load-time bounds checking, and anihash::hash32checksum; once validated, they can be referenced zero-copy.
Offline Training and Pre-built Dictionaries
Prebuilt dictionaries are continuously iterated, and their corpora update more promptly than traditional static lexicons: in addition to the base corpora Ultra-FineWeb-zh, FineWeb-2, and Universal Dependencies, they also ingest real-time buzzwords from the real social network Bluesky, so contemporary neologisms such as 嘉豪, 情绪价值, 硬控, 草台班子, 打工人, 大模型, 小红书, 脆友, 松弛感, 智能体, 豆包, and 青鳥 are accurately segmented out of the box.
The complete corpus, crawler, and training tooling are independently hosted at mcut_train:
- PageRank-based social corpus collection (
mcut_train crawl): combines live streams and topic seeds to build a multilingual follow graph, screens active accounts via topic-sensitive Personalized PageRank (defaultmin_follower = 10; for Simplified and Traditional Chinese there is no upper limit—collect as many as possible), filters out low-posting and follow-spamming accounts, then stores them by language indata/{zh,zh-TW,ja,th}directories, with one NestedText (.nt) file per person; before writing, it automatically performs within-author original-post deduplication and SimHash deduplication, and supports checkpoint-based incremental updates vialast_rkey. - Semantic-hash deduplication (
mcut_train dedup): uses 64-bit Charikar SimHash with 5-band LSH (Hamming distance ≤ 4 deemed similar) to deduplicate across posts and split into independent sentences, while simultaneously emitting author-tagged corpus streams to measure cross-author distribution. - Dual-stream unsupervised new-word mining (
mcut_train mine): fuses multi-shard web corpora with social multi-author corpus streams, combining Min-Split Pointwise Mutual Information (PMI), left/right branch entropy (Jin & Tanaka-Ishii 2006), adjacency type count (Feng et al. 2004), and C-value substring-absorption correction to discover new words, then filters fragments and noise viafilter/*.txtand manual lexicon audit. - AutoPhrase POS-boundary + word-level MDL EM self-distillation (
mcut_train em-segment): drawing on AutoPhrase and Unigram LM (Kudo 2018), only high-cohesion new words that pass POS-boundary and word-level MDL compression-gain tests are merged into the vocabulary; 3 rounds of EM Viterbi re-segmentation are performed, then fused with OpenCC (s2twp/s2hk) and real Traditional-Chinese social neologisms to generate a two-level core/extended vocabulary. - L1-L2 linear SVM with impact-based pruning (
mcut_train train): coordinate descent solves the L1-regularized L2-loss linear SVM; high-yield n-grams are selected by frequency-weighted impact $\sum |w| \cdot \sqrt{f}$ and quantized into.mcutpackages.
When periodic re-crawling of the latest social corpus and dictionary retraining are needed, follow the steps below:
# 1. Clone the standalone corpus and training repository
# 2. Incrementally crawl the latest Bluesky corpus via PageRank into data/{zh,zh-TW,ja,th}
# 3. Semantic-hash dedup, dual-stream new-word mining, EM re-segmentation, and retrain the 6-tier models into mcut_dict
# 4. Audit newly added OOV vocabulary and compare tokenization between old and new models (append noise words to filter/zh.txt then re-run)
# 5. Compile the text dictionary into a zero-copy .mdict binary, or inspect model/dictionary statistics
Performance Benchmark Details
Test environment: Apple M2 Max (darwin · arm64 · local benchmark · bench profile (LTO=fat)); build profile profile.bench (opt-level = 3, lto = "fat", codegen-units = 1); each test runs 8 warm-up rounds and auto-calibrates to ≥ 350 ms.
Test corpora: zh_short (1026 B), zh_doc (5934 B), zht_doc (2652 B), zh_search (5934 B), ja_doc (2304 B), th_doc (2830 B), mixed_doc (3126 B).
Memory & Cold-Start Overhead
| Engine | Init (ms) | Heap Live (KB) | Heap Peak (KB) | Init Allocs | Max RSS (KB) |
|---|---|---|---|---|---|
mcut-stream |
15.22 | 0.0 | 0.0 | 0 | 10560 |
mcut-sm |
6.77 | 0.0 | 0.0 | 0 | 5760 |
mcut-vec |
1.80 | 0.0 | 0.0 | 0 | 10560 |
mcut-zh |
0.86 | 0.0 | 0.0 | 0 | 6336 |
jieba-rs |
52.59 | 33273.4 | 33297.4 | 155 | 39376 |
charabia |
106.58 | 45791.6 | 45802.1 | 352329 | 50704 |
unicode-seg |
0.04 | 0.0 | 0.0 | 0 | 2000 |
Throughput Comparison by Scenario (MB/s; higher is better)
| Engine | zh_short | zh_doc | zht_doc | zh_search | ja_doc | th_doc | mixed_doc |
|---|---|---|---|---|---|---|---|
mcut-stream |
207.87 | 234.20 | 245.84 | 222.16 | 106.40 | 60.62 | 84.16 |
mcut-sm |
224.52 | 255.18 | 265.73 | 241.00 | 108.23 | 61.13 | 82.80 |
mcut-vec |
183.75 | 212.97 | 224.67 | 204.05 | 100.79 | 59.11 | 80.68 |
mcut-zh |
207.90 | 238.68 | 251.64 | 224.92 | - | - | - |
jieba-rs |
203.59 | 206.29 | 171.57 | 159.87 | - | - | - |
charabia |
28.78 | 24.75 | 26.87 | - | - | 42.06 | 33.12 |
unicode-seg |
143.37 | 103.16 | 105.98 | - | 93.56 | 93.98 | 119.58 |
Steady-State Single-Pass Tokenization Heap Allocation (zh_doc)
| Engine | Allocs / call | Bytes / call |
|---|---|---|
mcut-stream |
0 | 0 |
mcut-sm |
0 | 0 |
mcut-vec |
10 | 163680 |
mcut-zh |
0 | 0 |
jieba-rs |
1 | 142416 |
charabia |
2525 | 662424 |
unicode-seg |
0 | 0 |
Streaming vs. Slice Output Consistency Check
| Scenario | Token Count | cut_each 64-bit Fingerprint | cut 64-bit Fingerprint | Match |
|---|---|---|---|---|
zh_short |
149 | 5933f66f24268cd2 |
5933f66f24268cd2 |
PASS |
zh_doc |
1048 | 91ccee723623b9f6 |
91ccee723623b9f6 |
PASS |
zht_doc |
490 | 3b8d62f6af91d2bb |
3b8d62f6af91d2bb |
PASS |
zh_search |
1180 | cc752f05eb54f13c |
cc752f05eb54f13c |
PASS |
ja_doc |
412 | 6c6fed1b58378798 |
6c6fed1b58378798 |
PASS |
th_doc |
194 | 1a018e1d6291fde1 |
1a018e1d6291fde1 |
PASS |
mixed_doc |
318 | 75d6ab296548b535 |
75d6ab296548b535 |
PASS |
Note: mcut-zh initializes only the Simplified/Traditional Chinese model; mcut-stream and mcut-sm warm up all three Chinese, Japanese, and Thai language models (lg and sm vocabularies respectively); charabia enables the chinese,thai,hebrew,greek,vietnamese,khmer,german-segmentation,turkish,swedish-recomposition features in offline mode.