NCT Morphological Tokenizer
Source: nct_tokenizer/tokenizer.py Lines: 695
Neuroscience Motivation
The NCT tokenizer implements the Dual Route Cascaded (DRC) model of visual word recognition (Coltheart et al., 2001), the most comprehensive computational model of how the brain reads words. In the DRC model, two parallel processing routes compete to identify a word:
Route 1, Lexical (direct): High-frequency words are recognized as wholes via direct lookup in the orthographic input lexicon. Words like “the,” “and,” “is” bypass any form of decomposition. This route is fast (150ms from fixation to lexical access) but limited to words already stored in the mental lexicon. Functional MRI studies show that this route activates the visual word form area (VWFA) in the left fusiform gyrus.
Route 2, Sublexical (morphological): Unknown or low-frequency words are processed through grapheme-to-phoneme conversion rules and morphological decomposition. “Unhappiness” is decomposed into “un-” + “happy” + “-ness” via the morphology engine described in Section 2. This route is slower (250ms) but generalizes to novel words and non-words. It relies on left inferior frontal regions (Broca’s area) for assembly.
Route 3, Byte fallback: A safety net not present in the biological DRC model but necessary for computational universality. Any character sequence that cannot be processed by Routes 1 or 2 is encoded byte-by-byte using <byte:0> through <byte:255> tokens. This guarantees lossless coverage for arbitrary Unicode input.
Each NCT token corresponds to approximately one gamma cycle (25ms one morpheme). This creates a natural alignment between the tokenization granularity and the cortical column’s oscillatory hierarchy:
Token 1 gamma cycle 1 morpheme
Word 1 theta cycle (8–16 tokens) 3–7 morphemes
Phrase 1 alpha cycle (20 tokens) 8–15 morphemes
The L2/3 windowed Hebbian association (window tokens = 2 theta cycles) thus operates at the word/phrase boundary, consistent with how the brain binds lexical items into phrases via theta-gamma phase-amplitude coupling.
Vocabulary Architecture
The vocabulary is organized into seven contiguous regions, ordered from most fundamental (special tokens, byte fallback) to most language-specific (whole words):
Encoding Process
The encoding algorithm processes each pre-tokenized piece through the dual-route cascade:
Special Token Design
Six special tokens serve specific functions:
| Token | ID | Function |
|---|---|---|
<pad> | 0 | Padding for batch alignment |
<unk> | 1 | Unknown token (should never appear, byte fallback covers everything) |
<bos> | 2 | Beginning of sequence |
<eos> | 3 | End of sequence |
<cap> | 4 | Next token’s first character is uppercase |
<allcap> | 5 | Next token is ALL UPPERCASE |
The capitalization factoring (<cap> and <allcap>) is a key design choice: it allows the same morpheme token to represent both “Happy” and “happy,” reducing vocabulary size by 30% compared to case-sensitive tokenizers while preserving capitalization information for proper noun detection and sentence boundaries.
Comparison with BPE
| Property | NCT Morphological | BPE (GPT/LLaMA) |
|---|---|---|
| Vocab size | 13,817 | 32,000–100,000 |
| Split unit | Morpheme (linguistic) | Byte pair (statistical) |
| Cross-word merges | Never | Common |
| Mid-morpheme splits | Never | Common |
| Biological basis | DRC model (Coltheart 2001) | None |
| Lossless | Yes (byte fallback) | Yes (byte fallback) |
| Deterministic | Yes | Yes |
| Oscillatory alignment | 1 token 1 gamma cycle | No alignment |
| Coverage of novel words | Decompose morphemes byte | Byte fallback only |
Vocabulary Construction Process
Building the vocabulary from a corpus is a five-step pipeline that mirrors how a child acquires vocabulary, first learning common whole words, then discovering morphological patterns:
Step 1, Pre-tokenize and count: The regex pre-tokenizer splits the entire corpus into word pieces. Word frequencies are counted (case-insensitive for alphabetic words), producing a frequency distribution over the vocabulary. Punctuation, whitespace, and digits are counted separately.
Step 2, Build known-words set: Words appearing times form the known-words set . This set serves as the ground truth for root validation during morphological decomposition. Typically – for a corpus like WikiText-2.
Step 3, Morphological decomposition: Every word is decomposed using the morphology engine (Section 2). Morpheme frequencies are counted by type (prefix, suffix, root). Words that decompose into multiple morphemes contribute to all their constituent morpheme frequencies. Monomorphemic words (no valid decomposition) are counted as whole words.
Step 4, Construct vocabulary in priority order: Tokens are assigned IDs in a fixed order: special tokens (6) byte fallback (256) whitespace/punctuation (variable) contraction pieces (“’t”, “’s”, etc.) digit tokens prefix morphemes (all productive, freq ) suffix morphemes (all productive, freq ) root morphemes (top 8,000 by frequency) whole words (top 5,000 monomorphemic by frequency). This ordering ensures that affixes always have lower IDs than roots/words, which can be exploited for efficient morphological type checking.
Step 5, Build decomposition cache: For each word in the corpus, if all its morpheme segments are present in the vocabulary, the decomposition is cached for lookup during encoding. Words whose morphemes are not all in the vocabulary fall through to byte encoding at runtime.
Source Code
# ===========================================================================
# Tokenizer — NCT Brain-Inspired Morphological Tokenizer
# Source: nct_tokenizer/tokenizer.py
# ===========================================================================
"""
tokenizer.py — NCT Brain-Inspired Morphological Tokenizer
Dual-route architecture (Coltheart et al. 2001 DRC model):
Route 1 (Lexical): Whole-word lookup for high-frequency words
Route 2 (Sublexical): Morphological decomposition via affix stripping
Fallback: Byte-level encoding for truly novel/non-alphabetic input
Design constraints:
- Lossless: encode → decode = identity
- Deterministic: same text → same tokens always
- Morphologically faithful: never split mid-morpheme
- Cross-word safe: never merge across word boundaries
Oscillatory alignment (Giraud & Poeppel 2012):
- Each token ≈ 1 gamma cycle (1-2T) ≈ 1 morpheme
- Words span theta cycles (8-16T) ≈ 3-7 morphemes
- Phrases span alpha cycles (~20T) ≈ 8-15 morphemes
"""
# [bundled] from .morphology import (
# ── Pre-tokenization regex ────────────────────────────────────────────
# Splits text into: contractions, words, numbers, punctuation, whitespace
# Contractions split at apostrophe: "don" + "'t", "she" + "'s", "they" + "'re"
# Unicode letters supported for accented chars (café, résumé)
PRETOK_PATTERN = re.compile(
r"""'s|'t|'re|'ve|'m|'ll|'d""" # contractions
r"""|[A-Za-z\u00C0-\u024F\u1E00-\u1EFF]+""" # words (ASCII + Latin Extended)
r"""|\d+""" # numbers
r"""|\s""" # single whitespace character
r"""|[^\s]""", # single non-whitespace character
re.VERBOSE,
)
# Special tokens
PAD_TOKEN = "<pad>"
UNK_TOKEN = "<unk>"
BOS_TOKEN = "<bos>"
EOS_TOKEN = "<eos>"
CAP_TOKEN = "<cap>" # next token's first char is uppercase
ALLCAP_TOKEN = "<allcap>" # next token is ALL UPPERCASE
SPECIAL_TOKENS = [PAD_TOKEN, UNK_TOKEN, BOS_TOKEN, EOS_TOKEN, CAP_TOKEN, ALLCAP_TOKEN]
NUM_SPECIAL = len(SPECIAL_TOKENS)
# Byte tokens: <byte:0> through <byte:255>
NUM_BYTES = 256
class Encoding:
"""Minimal encoding result compatible with HuggingFace tokenizers API."""
__slots__ = ("ids", "tokens", "morpheme_types")
def __init__(self, ids: List[int], tokens: List[str],
morpheme_types: Optional[List[str]] = None):
self.ids = ids
self.tokens = tokens
self.morpheme_types = morpheme_types
class NCTTokenizer:
"""
Brain-inspired morphological tokenizer for NCT.
Vocabulary structure:
[0..3] Special tokens: <pad>, <unk>, <bos>, <eos>
[4..259] Byte fallback tokens: <byte:0>..<byte:255>
[260..] Morpheme/word tokens (sorted by type then frequency)
- Whitespace/punctuation tokens
- Prefix tokens
- Suffix tokens
- Root morpheme tokens
- Whole-word tokens (high-frequency, monomorphemic)
"""
def __init__(self):
# Token → ID mapping
self.token_to_id: Dict[str, int] = {}
# ID → token mapping
self.id_to_token: Dict[int, str] = {}
# Token → morpheme type
self.token_types: Dict[str, str] = {}
# Pre-computed decomposition cache (word → list of token strings)
self.decomposition_cache: Dict[str, List[str]] = {}
# Set of known words for morphological validation
self.known_words: Set[str] = set()
# Vocabulary size
self.vocab_size: int = 0
# Initialize special tokens and byte fallback
self._init_base_vocab()
def _init_base_vocab(self):
"""Initialize special tokens and byte-level fallback."""
idx = 0
# Special tokens
for tok in SPECIAL_TOKENS:
self.token_to_id[tok] = idx
self.id_to_token[idx] = tok
self.token_types[tok] = "special"
idx += 1
# Byte fallback tokens
for b in range(NUM_BYTES):
tok = f"<byte:{b}>"
self.token_to_id[tok] = idx
self.id_to_token[idx] = tok
self.token_types[tok] = "byte"
idx += 1
self.vocab_size = idx
def build_vocab(
self,
corpus_text: str,
max_roots: int = 8000,
max_whole_words: int = 5000,
min_word_freq: int = 5,
min_morpheme_freq: int = 3,
):
"""
Build vocabulary from a text corpus.
Algorithm:
1. Pre-tokenize corpus into words
2. Count word frequencies → known_words set
3. Decompose each word morphologically
4. Count morpheme frequencies
5. Build vocabulary: special + bytes + punctuation + affixes + roots + whole words
"""
print("[NCTTokenizer] Building vocabulary from corpus...")
# Step 1: Pre-tokenize and count word frequencies
pieces = PRETOK_PATTERN.findall(corpus_text)
word_freq = Counter()
punct_freq = Counter()
ws_freq = Counter()
for piece in pieces:
if piece.isalpha():
word_freq[piece.lower()] += 1
elif piece.isdigit():
word_freq[piece] += 1 # numbers as-is
elif piece.isspace():
ws_freq[piece] += 1
else:
punct_freq[piece] += 1
print(f" Unique words: {len(word_freq):,}")
print(f" Total word tokens: {sum(word_freq.values()):,}")
# Step 2: Build known_words set (words appearing ≥ min_word_freq times)
self.known_words = {w for w, c in word_freq.items()
if c >= min_word_freq and w.isalpha()}
print(f" Known words (freq≥{min_word_freq}): {len(self.known_words):,}")
# Step 3: Decompose all words
print(" Decomposing words morphologically...")
decompositions = {}
morpheme_freq = Counter()
prefix_freq = Counter()
suffix_freq = Counter()
root_freq = Counter()
whole_word_freq = Counter()
for word, freq in word_freq.most_common():
if not word.isalpha():
# Numbers and other non-alpha → treat as whole tokens
whole_word_freq[word] += freq
decompositions[word] = [word]
continue
morphemes = decompose_word(word, self.known_words)
if len(morphemes) == 1 and morphemes[0].mtype == MorphemeType.WORD:
# Monomorphemic word
whole_word_freq[word] += freq
decompositions[word] = [word]
else:
# Successfully decomposed
surfaces = [m.surface.lower() for m in morphemes]
decompositions[word] = surfaces
for m in morphemes:
s = m.surface.lower()
morpheme_freq[s] += freq
if m.mtype == MorphemeType.PREFIX:
prefix_freq[s] += freq
elif m.mtype == MorphemeType.SUFFIX:
suffix_freq[s] += freq
elif m.mtype == MorphemeType.ROOT:
root_freq[s] += freq
n_decomposed = sum(1 for d in decompositions.values() if len(d) > 1)
print(f" Decomposed: {n_decomposed:,} words")
print(f" Monomorphemic: {len(decompositions) - n_decomposed:,} words")
print(f" Unique prefixes found: {len(prefix_freq)}")
print(f" Unique suffixes found: {len(suffix_freq)}")
print(f" Unique roots found: {len(root_freq)}")
# Step 4: Build vocabulary
idx = self.vocab_size # start after special + byte tokens
# 4a. Whitespace tokens
for ws_tok in [" ", "\n", "\t", "\r"]:
if ws_tok not in self.token_to_id:
self.token_to_id[ws_tok] = idx
self.id_to_token[idx] = ws_tok
self.token_types[ws_tok] = "whitespace"
idx += 1
# 4b. Contraction pieces (pre-tokenizer splits "shouldn't" → "shouldn" + "'t")
contraction_stems = [
"shouldn", "wouldn", "couldn", "doesn", "hasn", "hadn",
"wasn", "weren", "aren", "isn", "didn", "mustn", "needn",
]
contraction_tails = ["'t", "'s", "'re", "'ve", "'m", "'ll", "'d"]
for ct in contraction_stems + contraction_tails:
if ct not in self.token_to_id:
self.token_to_id[ct] = idx
self.id_to_token[idx] = ct
self.token_types[ct] = "contraction"
idx += 1
# 4c. Punctuation tokens
punct_list = sorted(punct_freq.keys(), key=lambda x: -punct_freq[x])
for p in punct_list:
if p not in self.token_to_id:
self.token_to_id[p] = idx
self.id_to_token[idx] = p
self.token_types[p] = "punctuation"
idx += 1
# Individual digit tokens (0-9)
for d in "0123456789":
if d not in self.token_to_id:
self.token_to_id[d] = idx
self.id_to_token[idx] = d
self.token_types[d] = "digit"
idx += 1
# Common multi-digit numbers
for n in range(10, 100):
ns = str(n)
if word_freq.get(ns, 0) >= min_word_freq and ns not in self.token_to_id:
self.token_to_id[ns] = idx
self.id_to_token[idx] = ns
self.token_types[ns] = "number"
idx += 1
# 4c. Prefix tokens (all productive prefixes in the affix inventory)
for prefix, freq in prefix_freq.most_common():
if freq >= min_morpheme_freq and prefix not in self.token_to_id:
self.token_to_id[prefix] = idx
self.id_to_token[idx] = prefix
self.token_types[prefix] = "prefix"
idx += 1
# 4d. Suffix tokens
for suffix, freq in suffix_freq.most_common():
if freq >= min_morpheme_freq and suffix not in self.token_to_id:
self.token_to_id[suffix] = idx
self.id_to_token[idx] = suffix
self.token_types[suffix] = "suffix"
idx += 1
# 4e. Root morpheme tokens (top max_roots by frequency)
added_roots = 0
for root, freq in root_freq.most_common():
if added_roots >= max_roots:
break
if freq >= min_morpheme_freq and root not in self.token_to_id:
self.token_to_id[root] = idx
self.id_to_token[idx] = root
self.token_types[root] = "root"
idx += 1
added_roots += 1
# 4f. Whole-word tokens (top max_whole_words by frequency)
added_words = 0
for word, freq in whole_word_freq.most_common():
if added_words >= max_whole_words:
break
if freq >= min_word_freq and word not in self.token_to_id:
self.token_to_id[word] = idx
self.id_to_token[idx] = word
self.token_types[word] = "word"
idx += 1
added_words += 1
self.vocab_size = idx
# Step 5: Build decomposition cache
# Only cache decompositions where ALL segments are in vocabulary
for word, segments in decompositions.items():
lower_segs = [s.lower() for s in segments]
if all(s in self.token_to_id for s in lower_segs):
self.decomposition_cache[word] = lower_segs
print(f"\n Vocabulary size: {self.vocab_size:,}")
print(f" Special: {NUM_SPECIAL}")
print(f" Byte fallback: {NUM_BYTES}")
n_ws = sum(1 for t in self.token_types.values() if t == "whitespace")
n_punct = sum(1 for t in self.token_types.values() if t in ("punctuation", "digit"))
n_prefix = sum(1 for t in self.token_types.values() if t == "prefix")
n_suffix = sum(1 for t in self.token_types.values() if t == "suffix")
n_root = sum(1 for t in self.token_types.values() if t == "root")
n_word = sum(1 for t in self.token_types.values() if t == "word")
print(f" Whitespace: {n_ws}")
print(f" Punctuation/digits: {n_punct}")
print(f" Prefixes: {n_prefix}")
print(f" Suffixes: {n_suffix}")
print(f" Roots: {n_root}")
print(f" Whole words: {n_word}")
print(f" Decomposition cache: {len(self.decomposition_cache):,} words")
def encode(self, text: str, skip_whitespace: bool = False) -> Encoding:
"""
Encode text into token IDs.
Algorithm:
1. Unicode normalize (NFC)
2. Pre-tokenize into words, punctuation, whitespace
3. For each piece:
a. Whitespace/punctuation → direct lookup
b. Word → decomposition cache lookup (lexical route)
c. Word not cached → morphological decomposition (sublexical route)
d. Still unknown → byte-level fallback
Args:
skip_whitespace: If True, omit whitespace tokens from output.
Use True for training data (compact sequences, ~38% fewer tokens).
Use False for interactive use (lossless roundtrip).
Returns:
Encoding object with .ids (List[int]) and .tokens (List[str])
"""
text = unicodedata.normalize("NFC", text)
pieces = PRETOK_PATTERN.findall(text)
ids = []
tokens = []
mtypes = []
for piece in pieces:
if skip_whitespace and piece.isspace():
continue
piece_ids, piece_toks, piece_types = self._encode_piece(piece)
ids.extend(piece_ids)
tokens.extend(piece_toks)
mtypes.extend(piece_types)
return Encoding(ids, tokens, mtypes)
def _encode_piece(self, piece: str) -> Tuple[List[int], List[str], List[str]]:
"""Encode a single pre-tokenized piece."""
# Direct lookup (punctuation, whitespace, known whole tokens)
if piece in self.token_to_id:
tid = self.token_to_id[piece]
return [tid], [piece], [self.token_types.get(piece, "unknown")]
# Detect case pattern and work with lowercase for morpheme lookup
lower = piece.lower()
case_type = self._detect_case(piece)
# Mixed case (e.g., "MiXeD") — byte encode to preserve exact casing
if case_type == "mixed":
return self._encode_bytes(piece)
# Direct lookup with lowercase
if lower in self.token_to_id:
ids, toks, types = [self.token_to_id[lower]], [lower], [self.token_types.get(lower, "unknown")]
return self._apply_case_marker(ids, toks, types, case_type)
# Decomposition cache (fast path — lexical route)
if lower in self.decomposition_cache:
segments = self.decomposition_cache[lower]
result_ids = []
result_toks = []
result_types = []
for seg in segments:
if seg in self.token_to_id:
result_ids.append(self.token_to_id[seg])
result_toks.append(seg)
result_types.append(self.token_types.get(seg, "unknown"))
else:
byte_ids, byte_toks, byte_types = self._encode_bytes(seg)
result_ids.extend(byte_ids)
result_toks.extend(byte_toks)
result_types.extend(byte_types)
return self._apply_case_marker(result_ids, result_toks, result_types, case_type)
# Sublexical route: try morphological decomposition at runtime
if lower.isalpha() and len(lower) > 3:
morphemes = decompose_word(lower, self.known_words)
if len(morphemes) > 1:
result_ids = []
result_toks = []
result_types = []
n_in_vocab = 0
for m in morphemes:
seg = m.surface.lower()
if seg in self.token_to_id:
result_ids.append(self.token_to_id[seg])
result_toks.append(seg)
result_types.append(m.mtype.value)
n_in_vocab += 1
else:
# Byte-encode unknown segments (partial decomposition)
byte_ids, byte_toks, byte_types = self._encode_bytes(seg)
result_ids.extend(byte_ids)
result_toks.extend(byte_toks)
result_types.extend(byte_types)
# Use partial decomposition if at least one affix was found in vocab
if n_in_vocab >= 1:
return self._apply_case_marker(
result_ids, result_toks, result_types, case_type)
# For digit sequences: try splitting into known number tokens
if piece.isdigit():
return self._encode_digits(piece)
# Byte-level fallback (preserves case naturally)
return self._encode_bytes(piece)
def _encode_digits(self, digits: str) -> Tuple[List[int], List[str], List[str]]:
"""Encode a digit sequence using number tokens with greedy matching."""
ids, toks, types = [], [], []
i = 0
while i < len(digits):
# Try 2-digit, then 1-digit
matched = False
for length in (2, 1):
if i + length <= len(digits):
chunk = digits[i:i+length]
if chunk in self.token_to_id:
ids.append(self.token_to_id[chunk])
toks.append(chunk)
types.append(self.token_types.get(chunk, "digit"))
i += length
matched = True
break
if not matched:
# Single byte fallback
b_ids, b_toks, b_types = self._encode_bytes(digits[i])
ids.extend(b_ids)
toks.extend(b_toks)
types.extend(b_types)
i += 1
return ids, toks, types
def _detect_case(self, piece: str) -> str:
"""Detect the case pattern of a text piece."""
if not piece or not piece[0].isalpha():
return "lower"
if piece.islower():
return "lower"
if piece.isupper() and len(piece) > 1:
return "upper"
if piece[0].isupper() and (len(piece) == 1 or piece[1:].islower()):
return "title"
# Arbitrary mixed case (e.g., "MiXeD") — cannot be recovered from lowercase
return "mixed"
def _apply_case_marker(
self,
ids: List[int],
toks: List[str],
types: List[str],
case_type: str,
) -> Tuple[List[int], List[str], List[str]]:
"""Prepend case marker token if needed."""
if case_type == "title":
cap_id = self.token_to_id[CAP_TOKEN]
return [cap_id] + ids, [CAP_TOKEN] + toks, ["special"] + types
elif case_type == "upper":
allcap_id = self.token_to_id[ALLCAP_TOKEN]
return [allcap_id] + ids, [ALLCAP_TOKEN] + toks, ["special"] + types
return ids, toks, types
def _encode_bytes(self, text: str) -> Tuple[List[int], List[str], List[str]]:
"""Encode text as byte tokens (fallback for unknown tokens)."""
ids = []
toks = []
types = []
for byte_val in text.encode("utf-8"):
tok = f"<byte:{byte_val}>"
tid = self.token_to_id.get(tok, self.token_to_id[UNK_TOKEN])
ids.append(tid)
toks.append(tok)
types.append("byte")
return ids, toks, types
def decode(self, ids: List[int]) -> str:
"""
Decode token IDs back to text.
Handles:
- <cap> marker → capitalize first char of next token
- <allcap> marker → uppercase all chars of next token
- Byte tokens → decode UTF-8 byte sequences
- Regular tokens → concatenate strings
- Special tokens → skip (pad, bos, eos) or replace (unk → ?)
"""
parts = []
byte_buffer = []
pending_case = None # "title" or "upper"
for tid in ids:
tok = self.id_to_token.get(tid, UNK_TOKEN)
if tok.startswith("<byte:"):
byte_val = int(tok[6:-1])
byte_buffer.append(byte_val)
continue
# Flush any pending byte buffer
if byte_buffer:
try:
decoded = bytes(byte_buffer).decode("utf-8", errors="replace")
except Exception:
decoded = "".join(chr(b) if b < 128 else "?" for b in byte_buffer)
if pending_case == "title":
decoded = decoded[0].upper() + decoded[1:] if decoded else decoded
pending_case = None
elif pending_case == "upper":
decoded = decoded.upper()
pending_case = None
parts.append(decoded)
byte_buffer = []
if tok == CAP_TOKEN:
pending_case = "title"
continue
elif tok == ALLCAP_TOKEN:
pending_case = "upper"
continue
elif tok in (PAD_TOKEN, BOS_TOKEN, EOS_TOKEN):
continue
elif tok == UNK_TOKEN:
parts.append("?")
pending_case = None
else:
if pending_case == "title":
tok = tok[0].upper() + tok[1:] if tok else tok
pending_case = None
elif pending_case == "upper":
tok = tok.upper()
pending_case = None
parts.append(tok)
# Flush remaining bytes
if byte_buffer:
try:
decoded = bytes(byte_buffer).decode("utf-8", errors="replace")
except Exception:
decoded = "".join(chr(b) if b < 128 else "?" for b in byte_buffer)
if pending_case == "title":
decoded = decoded[0].upper() + decoded[1:] if decoded else decoded
elif pending_case == "upper":
decoded = decoded.upper()
parts.append(decoded)
return "".join(parts)
def save(self, path: str):
"""Save tokenizer to a directory."""
os.makedirs(path, exist_ok=True)
# Save vocabulary
vocab_data = {
"version": "0.1.0",
"vocab_size": self.vocab_size,
"token_to_id": self.token_to_id,
"token_types": self.token_types,
}
with open(os.path.join(path, "vocab.json"), "w", encoding="utf-8") as f:
json.dump(vocab_data, f, ensure_ascii=False, indent=2)
# Save decomposition cache (separate file, can be large)
with open(os.path.join(path, "decompositions.json"), "w", encoding="utf-8") as f:
json.dump(self.decomposition_cache, f, ensure_ascii=False)
# Save known words
with open(os.path.join(path, "known_words.json"), "w", encoding="utf-8") as f:
json.dump(sorted(self.known_words), f)
print(f"[NCTTokenizer] Saved to {path}/")
print(f" vocab.json: {self.vocab_size} tokens")
print(f" decompositions.json: {len(self.decomposition_cache)} entries")
print(f" known_words.json: {len(self.known_words)} words")
@classmethod
def load(cls, path: str) -> "NCTTokenizer":
"""Load tokenizer from a directory."""
tok = cls.__new__(cls)
tok.decomposition_cache = {}
tok.known_words = set()
# Load vocabulary
with open(os.path.join(path, "vocab.json"), "r", encoding="utf-8") as f:
vocab_data = json.load(f)
tok.token_to_id = vocab_data["token_to_id"]
tok.id_to_token = {int(v): k for k, v in tok.token_to_id.items()}
tok.token_types = vocab_data.get("token_types", {})
tok.vocab_size = vocab_data["vocab_size"]
# Load decomposition cache
decomp_path = os.path.join(path, "decompositions.json")
if os.path.exists(decomp_path):
with open(decomp_path, "r", encoding="utf-8") as f:
tok.decomposition_cache = json.load(f)
# Load known words
kw_path = os.path.join(path, "known_words.json")
if os.path.exists(kw_path):
with open(kw_path, "r", encoding="utf-8") as f:
tok.known_words = set(json.load(f))
print(f"[NCTTokenizer] Loaded from {path}/")
print(f" Vocab size: {tok.vocab_size}")
print(f" Decomposition cache: {len(tok.decomposition_cache)} entries")
print(f" Known words: {len(tok.known_words)}")
return tok
@classmethod
def from_pretrained(cls, path: str) -> "NCTTokenizer":
"""Alias for load(), matching HuggingFace tokenizers API."""
return cls.load(path)
def get_vocab_size(self) -> int:
return self.vocab_size
def get_vocab(self) -> Dict[str, int]:
return dict(self.token_to_id)
def token_to_morpheme_type(self, token_id: int) -> str:
"""Get the morpheme type for a token ID."""
tok = self.id_to_token.get(token_id, UNK_TOKEN)
return self.token_types.get(tok, "unknown")
def analyze(self, text: str) -> List[dict]:
"""
Encode text and return detailed analysis of each token.
Useful for debugging and understanding tokenization quality.
"""
enc = self.encode(text)
result = []
for tid, tok, mtype in zip(enc.ids, enc.tokens, enc.morpheme_types):
result.append({
"id": tid,
"token": tok,
"type": mtype,
"repr": repr(tok),
})
return result
def compare_with_bpe(self, text: str):
"""Compare NCT tokenization with GPT-2 BPE for analysis."""
nct_enc = self.encode(text)
print(f"Text: {repr(text)}")
print(f"\nNCT Morpheme Tokenization ({len(nct_enc.ids)} tokens):")
for tid, tok, mtype in zip(nct_enc.ids, nct_enc.tokens, nct_enc.morpheme_types):
print(f" {tid:5d} | {mtype:10s} | {repr(tok)}")
try:
from tokenizers import Tokenizer as HFTokenizer
bpe = HFTokenizer.from_pretrained("gpt2")
bpe_enc = bpe.encode(text)
print(f"\nGPT-2 BPE Tokenization ({len(bpe_enc.ids)} tokens):")
for tid, tok in zip(bpe_enc.ids, bpe_enc.tokens):
print(f" {tid:5d} | {'bpe':10s} | {repr(tok)}")
except ImportError:
print("\n(GPT-2 BPE comparison not available — tokenizers not installed)")
def stats(self) -> dict:
"""Return tokenizer statistics."""
type_counts = Counter(self.token_types.values())
return {
"vocab_size": self.vocab_size,
"type_counts": dict(type_counts),
"decomposition_cache_size": len(self.decomposition_cache),
"known_words": len(self.known_words),
}