mcut 0.1.0

Zero-copy, low-memory multilingual word segmenter using pointwise linear classification and minimal FST
Documentation

crates.io docs.rs license

English 简体中文 Français Deutsch Español 日本語 العربية Português Русский Italiano Nederlands 한국어 Türkçe Indonesia 正體中文 हिन्दी Polski தமிழ் Gaeilge Svenska বাংলা עברית ไทย Norsk Tiếng Việt मराठी Bahasa Melayu Dansk Română اردو Čeština فارسی తెలుగు ਪੰਜਾਬੀ ಕನ್ನಡ ગુજરાતી Ελληνικά Suomi Català Gàidhlig Қазақша Filipino Kiswahili ئۇيغۇرچە Magyar Українська Oʻzbekcha മലയാളം Slovenčina Afrikaans Hrvatski Српски Български አማርኛ Cymraeg ଓଡ଼ିଆ සිංහල Euskara Lietuvių Беларуская Galego မြန်မာ Slovenščina Azərbaycanca অসমীয়া ខ្មែរ नेपाली Kurdî Latviešu Eesti Татарча Íslenska ქართული Shqip Հայերեն Монгол Кыргызча Македонски ລາວ Тоҷикӣ Esperanto Nynorsk سۆرانی

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

Comparison of mcut and Mainstream Rust Tokenizers on Memory Footprint and Multilingual Throughput

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 14.35 0.0 10224 230.66 239.73 87.55 0 allocs / 0 B
mcut-sm 6.70 0.0 5776 254.50 267.76 85.98 0 allocs / 0 B
jieba-rs 42.49 33273.4 39360 207.33 168.45 - 1 alloc / 142416 B
charabia 104.75 45791.6 50800 24.59 25.27 33.54 2525 allocs / 662424 B
  • Zero heap residency & extremely low RSS: mcut-stream / mcut-sm rely solely on read-only page-fault mappings via &'static [u8], with Init Heap = 0.0 KB — roughly an order of magnitude less physical memory than jieba-rs (32.5 MB heap) and charabia (44.7 MB heap).
  • Zero heap allocation on the hot path: the cut_each streaming interface performs 0 heap allocations per document segmentation; jieba-rs and charabia trigger 1 and thousands of heap allocations per call, respectively.
  • Simplified/Traditional Chinese & full multilingual coverage: mcut-stream and mcut-sm natively support Simplified Chinese, Traditional Chinese, Japanese, Thai, and mixed seven-language text; charabia omits 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 mcut::{
  Cut, CutMode, CutOption, Cutter, Lang, LangCut, MCUT, Model, OwnedUserDict, Token, UserDict,
};

struct LaoCut;

impl LangCut for LaoCut {
  fn matches(&self, ch: char) -> bool {
    matches!(ch as u32, 0x0E80..=0x0EFF)
  }

  fn cut_run<'a, F: FnMut(Token<'a>)>(&self, run: &'a str, _mode: CutMode, mut emit: F) {
    emit(Token::word(run, 0, run.len()));
  }
}

fn main() {
  // 1. Out-of-the-box global instance MCUT demonstrating precise, full, and search modes
  let text = "Nanjing Yangtze River Bridge";
  for mode in CutMode::ALL {
    let word_li: Vec<&str> = MCUT.cut(text, *mode).into_iter().map(|t| t.text).collect();
    println!("zh [{mode}]: {word_li:?}");
  }

  // 2. Auto-detect mixed scripts, Traditional Chinese, and English/numeric/version identifiers
  let mixed = "Qdrantのコードで単体テスト,Rust 1.85 supports UTF-8 and GPT-4o";
  let auto_li: Vec<&str> = MCUT
    .cut(mixed, CutMode::Precise)
    .into_iter()
    .map(|t| t.text)
    .collect();
  println!("auto: {auto_li:?}");

  let zht_mixed = "Traditional Chinese and Japanese テスト and Rust 1.85 mixed search engine";
  let zht_li: Vec<&str> = MCUT
    .cut(zht_mixed, CutMode::Precise)
    .into_iter()
    .map(|t| t.text)
    .collect();
  println!("zht+ja+en: {zht_li:?}");

  // 3. Zero-heap-allocation streaming output while preserving whitespace and punctuation byte offsets
  let opt = CutOption::precise().with_separator();
  print!("stream: ");
  MCUT.cut_each("Hello, World 2026!", opt, |tok| {
    print!("[{}:{}] ", tok.text, tok.start);
  });
  println!();

  // 4. Pre-built .mdict zero-copy user dictionary override (supports cross-script domain terms such as Rust语言 / GPT-4o模型)
  let owned = OwnedUserDict::from_word_li(["Rust language", "GPT-4o model"]).expect("valid user dict");
  let mdict_byte = owned.as_slice();
  let user_dict = UserDict::from_slice(mdict_byte).expect("valid mdict");
  let custom = Cutter::builder().with_user_dict(user_dict).build();
  let custom_li: Vec<&str> = custom
    .cut("I like to use Rust language to call the GPT-4o model", CutMode::Precise)
    .into_iter()
    .map(|t| t.text)
    .collect();
  println!("user_dict: {custom_li:?}");

  // 5. Plug in a new language via LangCut while retaining built-in multilingual mixed routing
  let ext = Cutter::builder().with_lang(LaoCut).build();
  let ext_li: Vec<&str> = ext
    .cut("Hello ສະບາຍດີ Nanjing!", CutMode::Precise)
    .into_iter()
    .map(|t| t.text)
    .collect();
  println!("ext_lang: {ext_li:?}");

  // 6. Inspect zero-copy empty-model statistics
  let empty = Model::empty(Lang::Zh);
  println!("empty stat: {}", empty.stat());
}

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) 159,094 words / 328,704 slots 4.16 MiB 2.12 MiB Simplified 0.9813 (boundary 0.9933) · Traditional 0.9693
mcut_ja (ja, default) 60,000 words / 160,968 slots 2.07 MiB 1.02 MiB Japanese 0.9847 (boundary 0.9943)
mcut_th (th, default) 35,000 words / 160,864 slots 2.02 MiB 1.01 MiB Thai 0.9196 (boundary 0.9695)
mcut_zh_sm (zh-sm) 48,000 words / 101,208 slots 1.34 MiB 0.68 MiB Simplified 0.9197 (boundary 0.9708) · Traditional 0.8852
mcut_ja_sm (ja-sm) 25,000 words / 60,168 slots 0.82 MiB 0.39 MiB Japanese 0.9812 (boundary 0.9931)
mcut_th_sm (th-sm) 24,000 words / 109,464 slots 1.38 MiB 0.69 MiB Thai 0.9007 (boundary 0.9606)
  • Default features: default = ["global", "lg"] (enables global MCUT and zh/ja/th large vocabularies; three languages total 8.25 MiB raw / 4.15 MiB gz download).
  • Lightweight edge build: default-features = false, features = ["global", "sm"] (three languages' small vocabularies total 3.54 MiB raw / 1.76 MiB gz download).
  • Per-language trimming and mixing: supports enabling zh alone, or mixing such as ["global", "zh", "ja-sm"].
  • External zero-embedding: default-features = false embeds no model or MCUT at all; pair with Model::from_slice / UserDict::from_slice to zero-copy map runtime mmap slices directly; when overriding a language via Cutter::builder().with_model(model), the corresponding built-in .rodata pages 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 / Japan / Japanese / テス / スト / テスト / and / Rust / 1.85 / mixed / search / engine

Algorithm and Design

  • Block-vectorized Pointwise Linear Classification (PLC): drawing on Vaporetto, tokenization is modeled as a linear score at every character gap, completely eliminating Viterbi lattices and heap-allocated dynamic arrays. The regular path uses a fixed 128-slot contiguous stack buffer with fearless_simd i16x8 batch boundary detection; pure-BMP CJK short sentences further hit a 67-slot minimal stack fast path, decoding in 3-byte steps directly, pre-folding HAN4 type bias, and accumulating via single-instruction wrapping_add under the mathematically proven absence of i16 overflow—extra working memory is a constant $O(1)$.
  • 8-slot SWAR SwissTable Fused Trie (FusedTrie): fuses single-character weights, 2/3-gram weights, and two-level dictionary prefix matching into a single static zero-copy structure. Hot-zone BMP CJK characters are mapped in one step via a direct-index array to compact 14-bit character IDs; the 4-byte single-character weight table resides in L1 cache; transition slots at depth ≥ 2 use u64 carryless SWAR 7-bit tag concurrent comparison in groups of 8 slots—approximately 95% of miss queries terminate after loading the single-character control byte without touching the main slot table; internal nodes carry an additional 20-bit child Bloom filter and 2-bit vocabulary strength/weakness tier bits, with 4-character-ahead software prefetch to mask memory latency.
  • SIMD sentence-boundary scanning and cross-script routing: documents without hiragana are fast-judged in bulk via fearless_simd u8x16 to 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: Cut unifies the MCUT, Cutter, and PlcSegmenter entry points; LangCut and LangPack extend new languages through the compile-time generic chain LangChain<L, E> (or slice/Vec), and the zero-size placeholder NoLang::IS_EMPTY eliminates redundant branches at compile time.
  • .mcut and .mdict binary 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 an ihash::hash32 checksum; once validated, they can be referenced zero-copy.

Offline Training and Pre-built Dictionaries

Pre-built dictionaries are continuously iterated, keeping corpora fresher than traditional static lexicons: beyond the Ultra-FineWeb-zh, FineWeb-2, and Universal Dependencies base corpora, real-time buzzwords from the Bluesky social network are also ingested, so contemporary new words like 嘉豪, 草台班子, 打工人, 小红书, 脆友, 松弛感, 智能体, 豆包, 青鳥 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): builds multilingual follow-relationship graphs by combining live-stream feeds with topic seeds, filters high-influence active accounts via topic-aware Personalized PageRank, and incrementally persists to per-language directories under data/{zh,zh-TW,ja,th} with one NestedText (.nt) file per user, automatically filtering adult and spam accounts.
  • 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 via filter/*.txt and 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 .mcut packages.

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
git clone https://atomgit.com/i18n-site/mcut_train
cd mcut_train

# 2. Incrementally crawl the latest Bluesky corpus via PageRank into data/{zh,zh-TW,ja,th}
./script/crawl.sh

# 3. Semantic-hash dedup, dual-stream new-word mining, EM re-segmentation, and retrain the 6-tier models into mcut_dict
./script/train_all.sh

# 4. Audit newly added OOV vocabulary and compare tokenization between old and new models (append noise words to filter/zh.txt then re-run)
cargo run --release --bin mcut_train -- \
  audit --base-dict "${TMPDIR:-/tmp}/mcut_corpus/base_zh_dict.tsv" \
  --lexicon "${TMPDIR:-/tmp}/mcut_corpus/lexicon_zh_em.tsv" \
  --social-mined "${TMPDIR:-/tmp}/mcut_corpus/mined_bsky_zh.tsv" \
  --model ~/i18n/rs/mcut_dict/zh/model.mcut

# 5. Compile the text dictionary into a zero-copy .mdict binary, or inspect model/dictionary statistics
cargo run --release --bin mcut_train -- pack-dict --dict custom_words.txt --out domain.mdict
cargo run --release --bin mcut_train -- inspect --model ~/i18n/rs/mcut_dict/zh/model.mcut

Performance Benchmark Details

mcut vs. mainstream Rust tokenizers: cold start, heap allocation, and full-scenario throughput 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 14.35 0.0 0.0 0 10224
mcut-sm 6.70 0.0 0.0 0 5776
mcut-vec 1.63 0.0 0.0 0 10208
mcut-zh 0.73 0.0 0.0 0 6112
jieba-rs 42.49 33273.4 33297.4 155 39360
charabia 104.75 45791.6 45802.1 352329 50800
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 208.56 230.66 239.73 108.81 107.04 61.43 87.55
mcut-sm 230.91 254.50 267.76 132.15 105.99 59.77 85.98
mcut-vec 175.89 206.81 208.95 112.49 97.33 56.87 78.72
mcut-zh 206.95 230.75 241.60 110.88 - - -
jieba-rs 205.33 207.33 168.45 161.53 - - -
charabia 28.46 24.59 25.27 - - 42.64 33.54
unicode-seg 140.50 99.92 104.93 - 94.76 95.51 120.08

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 150 33aee52c596d90d9 33aee52c596d90d9 PASS
zh_doc 1050 d358d7be51e0535e d358d7be51e0535e PASS
zht_doc 490 621825e507aae566 621825e507aae566 PASS
zh_search 1176 97f0fa624b579ab5 97f0fa624b579ab5 PASS
ja_doc 412 6c6fed1b58378798 6c6fed1b58378798 PASS
th_doc 194 b6fea31c9ee2ac54 b6fea31c9ee2ac54 PASS
mixed_doc 321 ad3d673661d8346e ad3d673661d8346e 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.