Building a Scalable Word Sense Disambiguation Service: The Mandora Case Study
Polysemous and homonymous terms are a persistent source of errors in NLP. Using “Mandora,” which can refer to a plucked string instrument or to place names, this article explains how to build an extensible word sense disambiguation (WSD) service. It covers a three-layer architecture of lexicon and knowledge base, context model, and online routing; sense inventory design, including keeping Chinese “mandala” entries separate; the features, model choices, and output formats of disambiguation models; annotation guidelines and quality control; and service design with caching, tiered fallback, observability, and compliance. It also provides evaluation guidance, from macro-F1 and confidence calibration to online metrics, four common pitfalls and fixes, and a four-phase rollout roadmap.
1. Problem Definition: Why Polysemy Is Hard
Polysemous and homonymous terms are a recurring hotspot in NLP error analysis. Take “Mandora” as an example:
- As a common noun, it can refer to a large mandolin-family plucked string instrument.
- In other contexts, it is a place name, such as an airport or a locality in Australia.
Without context, any single mapping between the word and one meaning is bound to be wrong. In multilingual text, the judgment becomes even harder because look-alike spellings, inconsistent capitalization, transliteration differences, and mixed Chinese and English can all occur at once. Common cases include:
- Proper nouns confused with common nouns (for example, “Mandora” as an instrument vs. as a place or other proper name)
- Title abbreviations, noise, interjections, and URL fragments that introduce spurious features
- Missing synonym and hypernym relations (for example, 曼陀琳, 曼陀林, and 曼多拉乐器 [“mandala instrument”])
- Spelling variants and transliterations (“Mandora,” “Mandola,” and “Mandolin” differ for historical and language-specific reasons)
The goal of a disambiguation service is therefore not to “look up a single dictionary definition.” Instead, it should output ranked sense slots with confidence scores under contextual constraints, together with an explanation of the evidence behind each decision.
2. Overall Architecture: Offline Lexicon + Context Model + Online Routing
A three-layer architecture can balance accuracy against cost:
- Lexicon / KB layer: holds the inventory of possible senses.
- Lightweight context model: a contextual classifier or sequence tagger.
- Online service and routing: a gateway, cache, and fallback paths.
Query / text│▼Gateway (authentication, rate limiting, caching)│├─ Candidate generation (dictionary lookup, entity linking, embeddings)│ ││ ├─ Lexicon / knowledge graph candidates (sense inventory)│ ├─ Vector neighbors (pre-trained sentence embeddings)│ └─ Rules / templates (capitalization, parentheses, proper-name suffixes, etc.)│▼Context model (sequence tagging / classification / generative disambiguation)│ - Identify ambiguous tokens│ - Infer sense labels (instrument / location / proper name / other)│ - Calibrate confidence▼Post-processing (synonym normalization, alias expansion, locale and language adaptation)│▼Result (sense, confidence, evidence, spans)
Key design points:
- Layered decoupling: the lexicon layer defines the set of possible meanings, the model layer ranks them, and the service layer ensures availability.
- Explainability: every decision includes evidence, such as the lexicon entries that matched or relevant snippets from the context window.
- Graceful degradation: if the model is unavailable, the lexicon and rules still provide a baseline.
3. Modeling the Lexicon and Knowledge Layer (Sense Inventory)
The first step in disambiguation is to make the possible meanings explicit. For a term like “Mandora,” build a three-layer sense inventory:
- Entity senses
- Instrument: a plucked string instrument in the mandolin family.
- Place names: an airport, an Australian locality.
- Proper names: organizations and project names (handle these cautiously and avoid over-generalization).
- Lexical senses
- Common noun: the instrument.
- Transliterated proper noun: the place name.
- Relations and attributes
- Hypernymy: Mandora → plucked string instrument.
- Aliases and variants: Mandora; Mandola (its similar historical relation requires caution); Mandolin (a different but related instrument).
- Collocation constraints: the instrument sense tends to co-occur with words like “play,” “strum,” “string,” and “tuning.” The place sense tends to co-occur with words like “airport,” “located,” “near,” and “region.”
Implementation sketch (illustrative and independent of any specific product):
sense_inventory:lemma: "mandora"senses:- id: "mandora.instrument"type: "entity"label_zh: "曼陀琳 (plucked string instrument)" # mandolin-family instrumentsynonyms: ["曼陀琳", "曼陀林 (informal / misspelling)", "mandora"]attributes:category: "string_instrument"family: "lute_family"contexts:keywords_en: ["play", "strum", "tuning", "strings", "lute"]keywords_zh: ["弹奏 (to play a stringed instrument)", "拨弦 (to pluck the strings)", "调音 (tuning)", "琴弦 (strings)"]- id: "mandora.location"type: "entity"label_zh: "地名 (澳大利亚某地) [place name (a locality in Australia)]"attributes:geo: truecontexts:keywords_en: ["airport", "located", "region", "suburb", "city"]keywords_zh: ["机场 (airport)", "位于 (located)", "地区 (region)", "郊区 (suburb)"]
Note: Chinese texts often use forms such as 曼陀罗 or 蔓陀萝, which in Chinese usually refer to the mandala plant (such as Datura species). Sources sometimes mix these forms with the instrument term. If your system handles Chinese text, the lexicon layer should define separate slots for the instrument, the plant, and proper names. That way, “曼陀罗” (the plant) is not incorrectly folded into the instrument sense. If Chinese corpora show a clear predominance of the plant sense, the system should model them as separate entries (mandora instrument vs. mandala plant) rather than merge them into one entry.
4. Context-Based Disambiguation Model: From Candidates to Ranking
4.1 Task Formulations
Given an input text and a candidate sense set S = {s1, s2, …, sk}, the model does one of the following for each target token t:
- Multi-class classification: for a single target token.
- Sequence tagging: when a sentence contains multiple target tokens.
- Generative disambiguation: a prompt that outputs JSON, e.g.,
{"token":"mandora","sense":"...","confidence":0.xx}.
In practice:
- Sequence tagging is more convenient when a text has multiple disambiguation points.
- Classification offers lower latency.
- Generative disambiguation is more amenable to explanations and cold starts, but its cost and stability need careful evaluation.
4.2 Features and Signals
- Morphological features: capitalization, proper-noun status, spelling variants, and affixes. Some word endings, such as -a or -o, can reflect etymological or transliteration patterns.
- Neighborhood features: left and right context window n-grams and keyword co-occurrence, such as “airport” versus “strings” or “tuning.”
- Structural features: parentheses, quotation marks, title capitalization, and place-name suffixes (e.g., “Airport,” “Suburb”).
- External knowledge: entity-linking candidates and priors based on locale, language, and domain.
- User intent: search queries and click behavior, where the business permits and compliance allows.
4.3 Model Choices
- Lightweight baseline: TF-IDF combined with logistic regression or other linear models. It is quick to deploy and easy to interpret.
- Sequence models: BiLSTM-CRF, or a Transformer encoder with a token-classification head.
- Zero-shot / few-shot: similarity between sentence embeddings and sense descriptions, retrieved by embedding lookup.
- Generative models: structured JSON output as an optional channel.
Example structured output contract (to simplify downstream parsing):
{"text": "Mandora Airport is located in Western Australia.","targets": [{"token": "Mandora","span": [0, 7],"sense": "mandora.location","confidence": 0.93,"evidence": ["airport", "located", "Western Australia"]}]}
5. Training Data and Annotation Guidelines
High-quality annotations set the upper bound of a disambiguation system. Define explicit annotation guidelines that cover:
- Sense definitions: for each sense, provide a definition, positive examples, negative examples, and commonly confused boundaries.
- Context window: give annotators the surrounding sentences, so they never have to guess a meaning without context.
- Conflict handling: when the context is insufficient, allow annotators to label the case as UNKNOWN or AMBIGUOUS.
- Variant normalization: establish rules to merge informal and misspelled Chinese forms, such as “曼陀琳 / 曼陀林 / 曼多拉,” while retaining the original spans for audit purposes.
- Domain stratification: sample general text and domain-specific text (music, geography, aviation) separately to avoid domain bias.
Annotation quality assessment:
- Two-annotator labeling plus adjudication.
- Inter-annotator agreement metrics (e.g., Cohen’s κ).
- A hard-case set covering abbreviations, titles, mixed-language text, and spelling errors.
6. Service Design: Low Latency, High Availability, Observability
Disambiguation is usually embedded as an online capability in search, recommendation, customer service, or translation pipelines. Its service design largely determines whether it can go into production.
1. Caching Strategy
- Use the normalized text as the cache key and store results with a time-to-live (TTL) and a version number.
- Warm the cache for high-frequency queries.
- Add cache-penetration protection for the long tail.
2. Routing and Fallback
- Tier 1: a lexicon hit with high confidence is returned directly.
- Tier 2: a lightweight model handles medium-confidence cases.
- Tier 3: a heavier model or a generative model handles low-confidence cases or complex contexts.
- Fallback: return the candidate list with confidence scores rather than forcing a single choice.
3. Observability
- Metrics: QPS, P95/P99 latency, distribution of senses, distribution of confidence scores, and fallback rate.
- Logs: de-identified summaries of the input, the candidates, the final sense, and the rules that were triggered.
- Audit: consistent versioning of annotation data, the lexicon, and the models, so all three can be aligned.
4. Security and Compliance
- De-identify inputs and retain the minimum data necessary.
- Avoid exposing sensitive user location context tied to proper nouns or place names where relevant.
7. Evaluation: From Offline to Online
Offline evaluation should not rely on accuracy alone. Recommended measures:
- Macro-averaged F1: average F1 across senses so that frequent senses do not mask rare ones.
- Confidence calibration (ECE / Brier score): ensure that a score of 0.9 really does correspond to a high probability of being correct.
- Ambiguity rejection rate: how reliably UNKNOWN cases are detected.
- Latency and cost: report the latency distribution and cost broken down by routing tier.
Online evaluation:
- Shadow traffic: compare a new model against the baseline on mirrored traffic.
- Task metrics: depending on what the business makes available, track search click-through rate, zero-result rate, manual correction rate, and translation post-editing distance.
- Attribution: relate disambiguation errors to downstream metrics, so you do not end up with “metrics up, experience down.”
8. Common Pitfalls and Fixes
1. Over-merging Chinese Homonyms
- Symptom: merging “曼陀罗” (the plant) with “mandora” (the instrument) causes systematic errors.
- Fix: model the Chinese and English entries separately, and use cross-lingual entity alignment instead of forced merging.
2. Proper-Name Contamination
- Symptom: place names or organization names are treated as common nouns, or the other way around.
- Fix: add features such as proper-name suffixes, capitalization, and neighboring place-name cues. Define their priority in the annotation guidelines.
3. Spelling Variants and Noise
- Symptom: “Mandora,” “Mandola,” and “Mandolin” get confused for historical and language-specific reasons. Users may also enter misspellings with missing letters.
- Fix: combine edit-distance candidates, prior probabilities, and contextual disambiguation. Do not map low-confidence spelling variants directly to the instrument sense.
4. Unstable Generative Output
- Symptom: malformed JSON, hallucinated senses, and distorted confidence scores.
- Fix: validate output against a schema. Derive confidence scores from an external classifier rather than the model’s self-reported values. Retry or fall back on invalid output.
9. Rollout Roadmap (Suggested 4 Phases)
Phase 1: Lexicon and Rules MVP (1–2 weeks)
- Build the sense inventory and variant-merging rules.
- Ship caching, fallback, logging, and basic metrics.
Phase 2: Lightweight Model (2–4 weeks)
- Train a TF-IDF / linear model or a small encoder.
- Establish annotation guidelines v1 and a hard-case set.
Phase 3: Sequence Tagging / Enhanced Entity Linking (4–8 weeks)
- Add multi-target disambiguation and wider context windows.
- Calibrate confidence and tune routing strategies.
Phase 4: Continuous Optimization (ongoing)
- Use active learning, prioritizing low-confidence samples for annotation.
- Iterate on the lexicon and models jointly through versioned releases.
10. Conclusion
“Mandora” is just one example. In real-world applications, the boundaries between proper nouns, common nouns, place names, and transliterations are often highly ambiguous. Rather than pursuing a single all-purpose “word-to-meaning function,” build an engineering system with these properties:
- Candidate senses are explicit.
- Context enables ranking.
- Confidence scores are calibrated.
- The service degrades gracefully.
To deploy such a system in the cloud, you can rely on common capabilities such as container platforms, object storage, logging services, and monitoring and alerting to handle releases and operations. The real competitive advantage, however, comes from lexicon quality, annotation guidelines, and continuous iteration, not from model size alone.
