Morphological Decomposition Engine
Source: nct_tokenizer/morphology.py Lines: 388
Neuroscience Motivation
The human brain does not process words as opaque byte sequences. Over four decades of psycholinguistic research, starting with Taft and Forster (1975) and culminating in the comprehensive review by Rastle and Davis (2008), demonstrates that morphological decomposition is obligatory during reading. When the brain encounters the written word “unhappiness,” it automatically decomposes it into its constituent morphemes, the prefix “un-,” the root “happy,” and the suffix “-ness”, before accessing lexical representations. This decomposition occurs even for words that merely appear to contain affixes but do not (pseudo-affixed words like “corner,” which looks like “corn” + “-er” but is monomorphemic).
The processing pipeline follows Taft’s (2004) Obligatory Decomposition model:
Suffix stripping: The rightmost suffix is identified and removed, working from the word’s end.
Stem lookup: The remaining stem is checked against the mental lexicon.
Recombination: If the stem is recognized, the full word’s meaning is composed from the morpheme meanings. If not, the next-longest suffix is tried.
This is fundamentally different from BPE (Byte Pair Encoding) used by GPT, LLaMA, and virtually all modern language models. BPE splits words at statistically frequent byte boundaries with no linguistic knowledge. It produces splits like “un + happen + ing” but also “hap + pen + ing”, linguistically incoherent. The NCT tokenizer never splits mid-morpheme, aligning each token with approximately one gamma cycle (25ms 30–40Hz) of neural processing.
BPE optimizes for compression (minimize token count). NCT’s tokenizer optimizes for neural alignment (each token = one morpheme = one gamma cycle). This is why NCT uses tokens instead of BPE’s typical 32K–100K: morphemes are fewer but linguistically meaningful.
Formal Definition
Definition 1 (Morphological Decomposition). Given a word over alphabet , a morphological decomposition is a sequence of morphemes where each has a surface form and a type , such that:
Theorem 1 (Lossless Decomposition). For any input string , the NCT morphological decomposition satisfies: This holds because: (1) surface forms concatenate to the original word, (2) byte-level fallback covers any character not in the morpheme vocabulary, and (3) capitalization is factored out via marker tokens and restored during decoding.
Decomposition Algorithm
The core algorithm implements a modified version of Taft’s (2004) model with a three-tier scoring system for root quality:
Morphophonemic Normalization
English morphology modifies stem surfaces when affixes attach. The normalize_stem function generates candidate canonical roots:
False Decomposition Guard
A curated list of 300 English words prevents incorrect morphological analysis. These are words where an apparent affix is actually part of the root:
| Word | Apparent Analysis | Why Wrong |
|---|---|---|
| under | un- + der | “der” is not a word |
| interest | inter- + est | Not “between” + “est” |
| discover | dis- + cover | Not “reverse” + “cover” |
| surprise | sur- + prise | “prise” is not the root |
| corner | corn + -er | Not “one who corns” |
Architecture Diagram
Complexity Analysis
Theorem 2 (Decomposition Complexity). The morphological decomposition of a single word has worst-case time complexity: where , , , , and lookup is with a hash set. In practice, this is 0.5s per word, negligible compared to model forward pass time.
Source Code
# ===========================================================================
# Tokenizer — Morphological Decomposition Engine
# Source: nct_tokenizer/morphology.py
# ===========================================================================
"""
morphology.py — English Morphological Decomposition Engine
Implements rule-based morphological decomposition grounded in:
- Rastle & Davis (2008): Obligatory morphological decomposition in reading
- Taft (2004): Affix stripping → stem lookup → recombination
- Clements (1990): Sonority-based syllabification as fallback
The decomposition produces SURFACE-FORM segments that concatenate to the
original word (lossless). Canonical morpheme identification is separate
from surface splitting.
Architecture:
1. English affix inventory (~200 productive affixes)
2. Morphophonemic rules (consonant doubling, e-dropping, y→i)
3. Greedy longest-match affix stripping (suffix-first, then prefix)
4. Root validation against a known-word set
"""
class MorphemeType(Enum):
PREFIX = "prefix"
ROOT = "root"
SUFFIX = "suffix"
WORD = "word" # monomorphemic whole word
UNKNOWN = "unknown" # byte-level fallback
@dataclass
class Morpheme:
surface: str # surface form (concatenates to original word)
mtype: MorphemeType
canonical: str = "" # canonical morpheme (e.g., "run" for surface "runn")
# ── English Affix Inventory ──────────────────────────────────────────────
# Sorted by descending length within each category for longest-match-first.
# Sources: MorphoLex (Sanchez-Gutierrez et al. 2018), Bauer (1983)
PREFIXES = [
# 7+ chars
"counter", "circum",
# 6 chars
"pseudo", "proto", "super", "under", "trans", "extra", "intra",
"infra", "ultra", "multi", "inter", "supra",
# 5 chars
"hyper", "hypo", "anti", "semi", "over", "fore", "mega", "meta",
"para", "retro", "micro", "macro", "mini", "mono", "poly",
# 4 chars
"arch", "auto", "hemi", "equi", "omni", "post", "self", "vice",
"down", "with",
# 3 chars
"dis", "mis", "non", "out", "pre", "sub", "tri", "pan", "neo",
"pro", "mid",
# 2 chars
"un", "re", "in", "im", "il", "ir", "en", "em", "de", "co",
"ex", "bi", "up",
# 1 char
"a",
]
SUFFIXES = [
# 7+ chars
"ization", "isation",
# 6 chars
"ically", "lessly",
# 5 chars
"ation", "ition", "ments", "iness", "ously", "ively", "fully",
"wards", "ences", "ances", "ities",
# 4 chars
"tion", "sion", "ment", "ness", "able", "ible", "less", "like",
"ship", "hood", "ward", "wise", "ical", "ious", "eous", "ance",
"ence", "ally", "ized", "ised", "izes", "ises", "ists",
"isms", "doms", "ings", "ated", "ates", "ling", "ster",
"ette",
# 3 chars
"ing", "ful", "ous", "ive", "ize", "ise", "ist", "ism", "ity",
"dom", "age", "ant", "ent", "ary", "ory", "ate", "ify", "ial",
"ion", "ure", "ile", "ine", "ery", "est", "ily", "ers",
# 2 chars
"ly", "er", "ed", "en", "al", "ar", "or", "ic", "ty", "th",
"ee", "es",
# 1 char
"s", "y",
]
# Remove duplicates while preserving order
_seen_p = set()
PREFIXES = [p for p in PREFIXES if not (p in _seen_p or _seen_p.add(p))]
_seen_s = set()
SUFFIXES = [s for s in SUFFIXES if not (s in _seen_s or _seen_s.add(s))]
# Pre-sort by length descending (longest match first)
PREFIXES.sort(key=len, reverse=True)
SUFFIXES.sort(key=len, reverse=True)
# Words that LOOK like they have affixes but don't (false decompositions)
# These should NOT be decomposed. The brain learns these as exceptions.
FALSE_DECOMPOSITION_PREFIXES = {
# Words where apparent prefix is part of the root
"under", "uncle", "unit", "union", "unique", "until", "upon",
"interest", "interim", "intern", "internal", "internet",
"into", "income", "indeed", "index", "india", "indicate",
"industry", "include", "increase", "independent",
"individual", "information", "initial", "inner",
"instead", "institute", "instrument", "insurance",
"integer", "intense", "intent", "interview",
"invest", "invite", "iron",
"discover", "discuss", "display", "distance", "distinct",
"distribute", "district", "dinner", "direct", "differ",
"matter", "mission", "minute", "million", "minister",
"minor", "minus", "middle", "military", "mistake",
"desert", "design", "desire", "desk", "detail", "detect",
"develop", "device", "demand", "democracy", "demonstrate",
"depend", "deploy", "describe", "despite", "destroy",
"determine", "delay", "deliver", "defend", "defeat",
"decline", "declare", "decide", "debate", "degree", "deep",
"super", "sugar", "suffer", "summer", "summer", "sudden",
"submit", "success", "support", "suppose", "supply",
"surprise", "surgery", "surface", "survive", "suspect",
"energy", "engine", "enjoy", "enough", "ensure", "enter",
"entire", "entry", "enemy", "engage", "enhance",
"enormous", "enterprise", "entertain", "environment",
"episode", "equal", "error", "escape", "essay", "essential",
"establish", "estate", "estimate", "ethnic", "evaluate",
"even", "event", "ever", "every", "evidence", "evil",
"exact", "exam", "example", "excellent", "except", "exchange",
"execute", "exercise", "exhibit", "exist", "expand", "expect",
"expense", "experience", "experiment", "expert", "explain",
"explore", "export", "expose", "express", "extend", "extra",
"extreme", "eye",
"cover", "corner", "counter", "country", "couple", "course",
"cousin", "comment", "commit", "common", "community",
"company", "compare", "compete", "complete", "complex",
"conduct", "confirm", "congress", "connect", "consider",
"consist", "constant", "construct", "consult", "consume",
"contain", "content", "context", "continue", "contract",
"control", "convert", "convince", "correct", "corrupt",
"pretty", "present", "president", "press", "pressure",
"prevent", "previous", "price", "primary", "prince",
"principle", "print", "prior", "prison", "private",
"probably", "problem", "process", "produce", "product",
"professor", "profit", "program", "project", "promise",
"promote", "proper", "property", "propose", "protect",
"protest", "prove", "provide", "public",
"other", "over", "out",
"forest", "forget", "form", "former", "formula", "forth",
"fortune", "forward", "found", "foundation", "four",
"foreign", "forever", "formal",
}
# Minimum root length after stripping (brain constraint: roots are ≥ 3 chars)
MIN_ROOT_LEN = 3
# Maximum number of affixes to strip (brain processes 1-2 prefixes, 1-3 suffixes)
MAX_PREFIXES = 2
MAX_SUFFIXES = 3
def normalize_stem(stem: str) -> List[str]:
"""
Generate candidate canonical roots from a surface stem.
Handles common English morphophonemic alternations:
- Consonant doubling: "runn" → "run"
- E-dropping: "mak" → "make"
- Y→I change: "happi" → "happy"
- IE→Y change: "dri" → "dry"
"""
candidates = [stem]
if len(stem) < 2:
return candidates
# Consonant doubling: "runn" → "run", "sitt" → "sit"
if len(stem) >= 3 and stem[-1] == stem[-2] and stem[-1].isalpha():
candidates.append(stem[:-1])
# E-dropping: "mak" → "make", "hop" → "hope"
candidates.append(stem + "e")
# Y→I: "happi" → "happy", "easi" → "easy"
if stem.endswith("i"):
candidates.append(stem[:-1] + "y")
# IE→Y: "dri" → "dry" (before -ed, -er, -es)
if stem.endswith("i"):
candidates.append(stem[:-1] + "y")
# F→V: "calv" → "calf" (halves → half)
if stem.endswith("v"):
candidates.append(stem[:-1] + "f")
candidates.append(stem[:-1] + "fe")
return candidates
def decompose_word(
word: str,
known_words: Optional[Set[str]] = None,
min_root: int = MIN_ROOT_LEN,
) -> List[Morpheme]:
"""
Decompose a word into morphemes using greedy affix stripping.
Fast greedy algorithm (following Taft 2004):
1. Strip suffixes (right-to-left, longest match first, one at a time)
2. At each step, check if remainder is a known root → stop if yes
3. Strip prefixes (left-to-right, longest match first)
4. Validate final root against known_words (with morphophonemic normalization)
5. Return surface-form segments that concatenate to original word
Complexity: O(|SUFFIXES| × MAX_SUFFIXES + |PREFIXES| × MAX_PREFIXES) per word
"""
if not word or not word.isalpha():
return [Morpheme(surface=word, mtype=MorphemeType.WORD)]
lower = word.lower()
# Check false decomposition list
if lower in FALSE_DECOMPOSITION_PREFIXES:
return [Morpheme(surface=word, mtype=MorphemeType.WORD)]
# If word is very short (≤ 3 chars), don't decompose
if len(lower) <= 3:
return [Morpheme(surface=word, mtype=MorphemeType.WORD)]
# ── Smart suffix stripping: prefer decompositions with known roots ──
suffix_surfaces = []
remaining = lower
for _ in range(MAX_SUFFIXES):
# Try all matching suffixes and score by root quality
candidates = []
for suffix in SUFFIXES:
if remaining.endswith(suffix) and len(remaining) - len(suffix) >= min_root:
rem = remaining[:-len(suffix)]
# Three-tier scoring: direct match (2) > normalized match (1) > unknown (0)
# Known roots: prefer longer roots (preserves more meaning)
# Unknown roots: prefer longer suffixes (shorter remainder is easier
# to decompose further with prefixes)
quality = _root_quality(rem, known_words) if known_words else 0
score = quality * 1000 + (len(rem) if quality > 0 else len(suffix))
candidates.append((suffix, rem, score))
if not candidates:
break
# Pick the candidate with the best score (known root > longer root)
candidates.sort(key=lambda x: -x[2])
best_suffix, best_rem, best_score = candidates[0]
suffix_surfaces.insert(0, best_suffix)
remaining = best_rem
# Early exit: if remainder is a known word, stop stripping
if known_words and _is_known_root(remaining, known_words):
break
# ── Greedy prefix stripping ──
prefix_surfaces = []
for _ in range(MAX_PREFIXES):
best_prefix = None
for prefix in PREFIXES:
if remaining.startswith(prefix) and len(remaining) - len(prefix) >= min_root:
if best_prefix is None or len(prefix) > len(best_prefix):
best_prefix = prefix
if best_prefix is None:
break
# Check: does the word after this prefix look like a real root?
candidate_root = remaining[len(best_prefix):]
root_known = known_words and _is_known_root(candidate_root, known_words)
if not root_known:
# For novel words with suffixes already stripped, allow ONE prefix if:
# 1. Remainder is long enough (≥4 chars)
# 2. Prefix is meaningful (≥3 chars — avoids spurious "co", "re", "de" splits)
# OR if there are no prefixes yet (first prefix gets lenient treatment)
if len(suffix_surfaces) == 0 or len(candidate_root) < 4:
break
if len(prefix_surfaces) >= 1:
# Already have one prefix — don't stack another on unknown root
break
if len(best_prefix) < 3 and len(candidate_root) < 5:
# Short prefix on short unknown root is likely spurious
break
prefix_surfaces.append(best_prefix)
remaining = candidate_root
root_surface = remaining
n_affixes = len(prefix_surfaces) + len(suffix_surfaces)
# ── Validate decomposition ──
if n_affixes == 0:
return [Morpheme(surface=word, mtype=MorphemeType.WORD)]
# Check: is the base form (root without any affixes) in false decomposition list?
# This catches "discovered" → "discover" is a false decomposition base
base_form = lower
for s in suffix_surfaces:
if base_form.endswith(s):
base_form = base_form[:-len(s)]
# Also try morphophonemic normalization of the base
base_candidates = [base_form] + normalize_stem(base_form)
for bc in base_candidates:
if bc in FALSE_DECOMPOSITION_PREFIXES:
return [Morpheme(surface=word, mtype=MorphemeType.WORD)]
decomp_valid = False
if known_words:
if _is_known_root(root_surface, known_words):
decomp_valid = True
elif len(root_surface) >= 4 and n_affixes >= 1:
decomp_valid = True
else:
decomp_valid = len(root_surface) >= 4
if not decomp_valid:
return [Morpheme(surface=word, mtype=MorphemeType.WORD)]
# ── Build morpheme list with original case preserved ──
morphemes = []
pos = 0
for p in prefix_surfaces:
morphemes.append(Morpheme(
surface=word[pos:pos + len(p)],
mtype=MorphemeType.PREFIX,
canonical=p,
))
pos += len(p)
morphemes.append(Morpheme(
surface=word[pos:pos + len(root_surface)],
mtype=MorphemeType.ROOT,
canonical=root_surface,
))
pos += len(root_surface)
for s in suffix_surfaces:
morphemes.append(Morpheme(
surface=word[pos:pos + len(s)],
mtype=MorphemeType.SUFFIX,
canonical=s,
))
pos += len(s)
return morphemes
def _is_known_root(stem: str, known_words: Set[str]) -> bool:
"""Check if a stem (or its morphophonemic variant) is a known word."""
if stem in known_words:
return True
for candidate in normalize_stem(stem):
if candidate in known_words:
return True
return False
def _root_quality(stem: str, known_words: Set[str]) -> int:
"""Score how well a stem matches the known word set.
Returns:
2 — direct match (stem itself is in known_words)
1 — normalized match (morphophonemic variant is in known_words)
0 — not known
"""
if stem in known_words:
return 2
for candidate in normalize_stem(stem):
if candidate in known_words:
return 1
return 0
def batch_decompose(
words: List[str],
known_words: Optional[Set[str]] = None,
) -> Dict[str, List[Morpheme]]:
"""
Decompose a batch of words. Returns word → morpheme list mapping.
"""
results = {}
for word in words:
results[word] = decompose_word(word, known_words)
return results