Code-Switching and Mixed-Language Text

Michael BrenndoerferNovember 26, 202645 min read

Learn how code-switching breaks language ID, tokenization, and generation pipelines. Covers switch-point F1, mixed scripts, Unicode traps, and evaluation.

Language AI HandbookAll chapters
Part 26 of 67Multilingual Language Models and Cross-Lingual Transfer
Chapter 188Code-Switching and Mixed-Language Text
Reading the full chapter · 13 sections · 45 min13 sections · 45 min

All 13 sections · 45 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Code-Switching and Mixed-Language Text

Consider a message you might hear between friends in Delhi. "Yaar, I'll call you back, mujhe ek call aaya." Both Hindi and English appear in one turn. A Spanish-English conversation might place an English noun inside a Spanish clause, and a Korean commit message might retain English identifiers from the codebase.

Code-switching is the use of more than one language in a conversation or utterance. If a system uses one language label to route this entire message, the selected pipeline may only handle part of it. The system can return an ordinary-looking result even when its language label has lost information the next step needs.

This chapter looks at what breaks when that assumption fails. It covers:

  • The linguistics of code-switching, because the categories matter for how you design and evaluate a system.
  • Language identification at sentence and word resolution. A sentence label can represent a monolingual segment but cannot locate a switch within it.
  • Mixed scripts, including romanization, transliteration, homoglyphs, and Unicode normalization traps that silently corrupt data.
  • Tokenization economics, showing how the same meaning can cost very different numbers of tokens depending on script and vocabulary.
  • Generation, where models drift into a single language even when asked not to.
  • Evaluation, where BLEU, accuracy, and single-label LID all give misleading results.
  • Deployment failure modes, the silent problems that rarely show up in a demo but appear at scale.

The examples build on language identification and the Part V: Subword Tokenization. We use small labeled examples to show what happens when a sentence crosses a language boundary.

The Shape of Code-Switching

Start by locating each switch. Record which pipeline decisions depend on passage, sentence, token, or morpheme boundaries before choosing a language label.

Locate each switch relative to sentence and word boundaries. A word-internal switch also occurs within a sentence. Record discourse tags separately, since a tag can appear inside a sentence. Use the resolution your system needs for routing, retrieval, or annotation.

Intersentential switching

Here, an intersentential switch occurs between complete sentences. A switch at an embedded clause boundary inside one sentence is intrasentential under this convention.

"I finished the report last night. Phir main so gaya." ("...Then I fell asleep.")

Each sentence in the example uses one language. Sentence-level labels can represent both parts if the classifier identifies them correctly. A router that accepts only one language label for the whole document has to discard one of those labels. If a ticket starts in Spanish and ends in English, a Spanish-only queue may handle the opening and miss the English request.

When switches coincide with known sentence or turn breaks, label those units first. For routing, a per-segment classifier with a mixed label is one possible design.

Intrasentential switching

The switch happens inside a single sentence, often at a constituent boundary:

"I told him ki main kal nahi aa sakta." ("I told him that I can't come tomorrow.")

A single sentence label leaves the switch boundary unmarked. For the example above, compare the adjacent word labels and inspect which parts the deployed tokenizer separates before choosing a routing or retrieval policy.

Poplack’s 1980 Spanish–English study describes two proposals. The equivalence constraint favors places where the surface structures line up. The free morpheme constraint limits switches at bound morphemes and makes a qualification for forms phonologically integrated into the other language. The paper’s bound-morpheme examples come from Spanish and English. Myers-Scotton’s Matrix Language Frame distinguishes a grammatical frame from contributions of an embedded language. Muysken (2000) distinguishes insertion into a frame, alternation between structures, and congruent lexicalization, where languages supply lexical items within a shared structure.

Use these analyses to decide what to observe in the target corpus:

  • Count switches by the grammatical categories on either side of the boundary.
  • Compare boundary prediction with and without syntactic features.
  • Compare the boundary distributions of naturally occurring text and synthetic text before using the latter for evaluation.
Matrix language

The framework uses a matrix and an embedded language to describe how mixed material is organized. Use the English main clause and Hindi complement above as an example of nested material. State which structural unit you analyze before assigning a matrix language.

Tag switching and discourse markers

A single tag or discourse particle is inserted:

"That's a great idea, yaar." "Entonces, we should probably leave."

If a whole-sentence label ignores one discourse marker, the tag can still matter to a token-level annotation task. Decide whether an item such as yaar should count as a switched tag, a borrowing, or an unresolved label for the community whose text you are annotating.

Use target-speaker review to check whether discourse particles such as yaar, entonces, and n’est-ce pas suit the requested register.

When evaluating a generated reply, ask reviewers to judge the discourse markers and grammatical form separately.

Intra-word switching and morphological mixing

A stem from one language can take a suffix from another. Das and Gambäck (2014), §2 report an English example with Bengali plural morphology. Their source writes admirer der, with a space, and analyzes -der as the plural suffix.

In Vamos a parquear el carro, ASALE records parquear as a regional Spanish verb from English to park. In Mujhe WhatsApp karna hai, the brand name WhatsApp and the Hindi light verb karna are separate words.

Decide how your corpus distinguishes a switched item from an established loan. Poplack excluded habitual, socially integrated items from her Spanish–English switch counts and considered phonological integration separately. A system might recognize parquear as a whole word or identify a stem and ending. Test how your analyzer treats it and the Hindi light-verb example under the annotation policy used for your task.

If a written stem and suffix use different scripts, record both scripts for that token. Apply that test to the written form and use language or morphological evidence separately.

Borrowing versus code-switching: the definitional trap

Consider ‘I need to download the file’ quoted in a Hindi conversation. The full sentence is English, so the English spelling of download cannot establish its loan status in Hindi. To test a loan policy, annotate an example that embeds it in a Hindi phrase, such as download karna.

Define whether the label describes a form’s origin, its use in the speech community, or an operation such as selecting an index. Apply both candidate policies to one borrowed word in a small fixture. If changing a label changes the counts used by CMI, recalculate the score and inspect whether the downstream decision also changes.

Write down the loanword and unknown-label policies. Check both before comparing results from different corpora.

Why Code-Switching Breaks Standard Pipelines

A monolingual assumption can cause problems in routing, tokenization, lexical processing, evaluation, or generation. Check what each stage expects.

Language routing. A router can use a language tag to select a model, tokenizer, index, or prompt. In the routing test, send the annotated span and its predicted label through the real consumer and check the result even when the system reports success.

Tokenizers. Measure the token count on the actual tokenizer and held-out variants. A larger count occupies more of a token-limited context under the same accounting rules. Measure latency and task quality on the service you use.

Lexical resources. Check which words your stemmer, lemmatizer, stopword list, or gazetteer handles. An English-only stoplist in the Hinglish example will leave romanized Hindi function words absent from that list.

Evaluation. Compare monolingual and mixed inputs separately. Include labels and metrics that match the consumer’s task and resolution.

Generation. Test whether the language shares and boundary placement change from the opening to the end of a reply. Use the same definition for each segment so the results remain comparable.

We will work through each of these. The remainder of the chapter alternates between mechanism and demonstration, and the notebook calculations use explicitly listed inputs. The aim is not to survey every technique but to give you the diagnostic instincts to recognize each failure when it appears in your own pipeline.

Language Identification on Mixed Text

Language identification means assigning a label to a specified unit of text. Check the unit supported by the identifier and the unit required by the consumer. A whole-text label and a token sequence answer different questions.

A high whole-text score identifies a preferred class among that model’s labels. Check the token or span output separately before inferring where a boundary occurs.

The examples run in the locked book environment. The language identification calculations use Python and small offline fixtures. The tokenizer experiment later trains two miniature vocabularies with the installed tokenizers package.

We will work with hand-written mixed-language examples to exercise the pipeline choices. They are illustrative fixtures, with no estimate of how often these constructions occur.

PythonIn [3]
CollapseExpand
examples = [
    ("Hinglish", "Yaar I am not coming to the party tonight, mujhe kaam hai."),
    (
        "Spanglish",
        "Voy al grocery store para comprar leche y huevos, pero no tengo cash.",
    ),
    (
        "Franglais",
        "J'ai envoyé le email à mon boss hier, mais il n'a pas répondu.",
    ),
    (
        "Taglish",
        "I'll go to the mall later, pero kailangan ko muna magpaalam kay nanay.",
    ),
    ("Mandarin-English", "我明天有 meeting at 3pm, 然后 we can grab dinner."),
    (
        "Arabic-English",
        "Ana going to the meeting at 3pm, بس الملف لسه مش جاهز.",
    ),
]

Comparing whole-string language labels

The langdetect Python package and Lui and Baldwin's langid.py illustrate off-the-shelf single-label interfaces.

A list of alternate language hypotheses for a whole input does not identify which words belong to which language. Their scores also require checking the API conventions before interpreting them, and a normalized score alone does not establish calibration.

The executable comparison uses two small baselines to expose this design choice without model downloads. They share a fixed language inventory and use separate monolingual profile sentences. The first counts exact matches to a profile's words. The second compares within-word character trigrams by cosine similarity, which permits partial matches. Their scores have different units, so we compare their labels and plot the number of examples assigned to each language. This fixture case-folds words and maps the typographic apostrophe U+2019 to ASCII U+0027 for matching. An apostrophe is kept inside a word when letters appear on both sides.

PythonIn [4]
CollapseExpand
profile_texts = {
    "en": "I will call the team this evening and ask them to share a report.",
    "hi": "Yaar mujhe kal bazaar jaana hai aur kaam khatam karna hai.",
    "es": "Voy a la tienda para comprar pan y queso, pero no tengo dinero.",
    "fr": "J'ai envoyé un message à mon collègue, mais il n'a pas répondu.",
    "tl": "Mamaya ako pupunta sa palengke pero kailangan ko munang magpaalam sa nanay.",
    "zh": "我明天要出门,然后我们一起吃晚饭。",
    "ar": "بس الاجتماع خلص والملف لسه مش مكتوب.",
}


def words(text):
    normalized = text.casefold().replace("’", "'")
    return regex.findall(
        r"\p{L}[\p{L}\p{M}]*(?:'\p{L}[\p{L}\p{M}]*)*", normalized
    )


assert words("J'ai") == words("J’ai") == ["j'ai"]
assert words("’bonjour’ l’été") == ["bonjour", "l'été"]


def trigrams(word_list):
    counts = Counter()
    for word in word_list:
        padded = f"^{word}$"
        counts.update(padded[i : i + 3] for i in range(len(padded) - 2))
    return counts


word_profiles = {lang: set(words(text)) for lang, text in profile_texts.items()}
trigram_profiles = {
    lang: trigrams(words(text)) for lang, text in profile_texts.items()
}


def pick_language(scores):
    top = max(scores.values())
    winners = [lang for lang, score in scores.items() if score == top]
    return winners[0] if top > 0 and len(winners) == 1 else "unk"


def word_lid(text):
    return pick_language(
        {
            lang: sum(word in profile for word in words(text))
            for lang, profile in word_profiles.items()
        }
    )


def trigram_lid(text):
    query = trigrams(words(text))
    query_norm = math.sqrt(sum(count**2 for count in query.values()))
    scores = {}
    for lang, profile in trigram_profiles.items():
        profile_norm = math.sqrt(sum(count**2 for count in profile.values()))
        numerator = sum(count * profile[tri] for tri, count in query.items())
        denominator = query_norm * profile_norm
        scores[lang] = numerator / denominator if denominator else 0.0
    return pick_language(scores)


rows = [(name, word_lid(text), trigram_lid(text)) for name, text in examples]
predicted_languages = sorted({label for _, a, b in rows for label in (a, b)})
language_positions = np.arange(len(predicted_languages))
word_assignments = Counter(a for _, a, _ in rows)
trigram_assignments = Counter(b for _, _, b in rows)
word_counts = [word_assignments[lang] for lang in predicted_languages]
trigram_counts = [trigram_assignments[lang] for lang in predicted_languages]
ConsoleOut [5]
CollapseExpand
Hinglish           exact words:  hi  trigrams:  hi
Spanglish          exact words:  es  trigrams:  es
Franglais          exact words:  fr  trigrams:  fr
Taglish            exact words:  tl  trigrams:  tl
Mandarin-English   exact words: unk  trigrams:  zh
Arabic-English     exact words:  ar  trigrams:  ar

The two baselines agree on five of the six examples. On the Mandarin–English example, the exact-word baseline abstains (unk), and the trigram baseline returns zh.

The table reports whole-string labels, which you can use to compare the baselines' decisions on these fixtures.

VisualizationOut [6]
CollapseExpand
Grouped bars show matching counts for five language labels. The exact-word baseline has one `unk` result, and the trigram baseline has one `zh` result.
Counts of whole-string labels for six hand-written examples. The exact-word baseline abstains on one input, shown as `unk`, and the trigram baseline labels that input `zh`.

An English-only index can mishandle the non-English content if routing commits to a whole-string English label. Log the evidence used to make that routing decision.

If a classifier produces scores, test how they behave on monolingual and mixed inputs separately before using a threshold.

Confidence is not calibration

A single-label model scores only the labels it can return. A large score for one label does not show that the input contains only that language. Calibration is a separate property evaluated using labeled examples from the target setting.

What modern LID looks like

When you choose a language identifier, check its label inventory and the units it can label.

  • Language coverage. GlotLID-M reports 1,665 languages. OpenLID-v2 lists 200 language varieties with script-aware labels. The generic fastText lid.176 release lists 176 languages and a 917 kB compressed model. The separate IndicLID study evaluated Bhasha-Abhijnaanam on 22 Indic languages in native scripts and 21 in Latin script. Table 1 and §2.2 exclude Santali from the Latin-script test set. The paper separately reports that its romanized checkpoint does not support Dogri. Its test data are predominantly clean sentences, so use naturally mixed text from the target domain to evaluate boundaries.
  • Token-level or span-level output. A dedicated sequence labeler can return a label per token. The exercise below runs a span classifier over sliding windows and assigns its label to each window's center token. Compare both approaches on your annotated boundaries if both are available.

Choose your LID granularity based on what the downstream task needs.

Possible resolutions for language identification decisions.
Downstream taskUseful granularity
Choosing a translation directionDocument or segment
Routing to a monolingual modelSegment, with a mixed label
NER over code-switched textToken
Filtering training dataDocument, plus a mixed-tag
ASR language modelingFrame or word
Search indexingPer-field, plus script detection

Choose the granularity for each downstream decision. If a document labeled English contains substantial Devanagari text, inspect the relevant spans before routing it to an English-only index. Script composition can flag the discrepancy. It cannot identify the language of a span by itself.

Sliding-window token-level LID

Classify overlapping windows of whitespace-delimited tokens and assign each window's label to the center token. Here we reuse the exact-word baseline, shorten windows at the ends, and leave an unknown label when the word evidence is tied or absent.

PythonIn [7]
CollapseExpand
def sliding_window_lid(text, k=5):
    if k < 1 or k % 2 == 0:
        raise ValueError("Window length must be a positive odd number.")
    tokens = text.split()
    radius = k // 2
    labels = [
        word_lid(" ".join(tokens[max(0, i - radius) : i + radius + 1]))
        for i in range(len(tokens))
    ]
    return tokens, labels


tokens, pred = sliding_window_lid(examples[0][1], k=5)
ConsoleOut [8]
CollapseExpand
 0  Yaar         unk
 1  I            unk
 2  am           unk
 3  not          en
 4  coming       en
 5  to           en
 6  the          en
 7  party        en
 8  tonight,     hi
 9  mujhe        hi
10  kaam         hi
11  hai.         hi

Compare the switch-point sets below. The five-word baseline misses both gold boundaries and predicts one boundary outside the gold set.

This one sentence illustrates smoothing across boundaries, not the expected accuracy of a real classifier.

Romanized Hindi and English both use Latin characters. Check lexical and contextual evidence on held-out examples representative of the intended writing conventions.

Tag romanized text explicitly

In a catalog that tracks writing systems, language tags such as hi-Latn, ur-Latn, and ar-Latn use the Latn script subtag to record Latin-script forms explicitly. Preserve both the original text and the tagging provenance so routing decisions can be revisited.

The code-mixing index

The code-mixing index (CMI) in Das and Gambäck (2014) measures the fraction of language-assigned tokens outside the largest language category. This counts tokens by label and ignores their order.

CMI=100(1−max⁡iwin),n>0\mathrm{CMI} = 100 \left(1 - \frac{\max_i w_i}{n}\right),\qquad n>0

Here nn is the number of tokens assigned a language from the declared inventory LL. The count wiw_i is the number of those tokens in language ii. Both score helpers accept labels from LL plus the reserved labels unk and other. The latter two are excluded from the count. Fix an unrecognized label at input or explicitly map it to unk under the annotation policy before scoring. When n=0n=0, we return zero and report label coverage separately.

For two languages, an even split gives 50 and a monolingual sequence gives zero. When the majority count is fixed, growing the span adds minority-language tokens and raises CMI.

The plot shows only valid combinations for two languages, where the majority count is at least half of the span.

PythonIn [9]
CollapseExpand
hinglish_languages = frozenset({"hi", "en"})
excluded_labels = frozenset({"unk", "other"})


def check_language_labels(labels, languages):
    if not languages or languages & excluded_labels:
        raise ValueError(
            "Choose a nonempty language inventory without reserved labels."
        )
    invalid = set(labels) - languages - excluded_labels
    if invalid:
        raise ValueError(f"Unknown labels: {sorted(invalid)}")


def code_mixing_index(labels, languages):
    check_language_labels(labels, languages)
    counts = Counter(label for label in labels if label in languages)
    total = sum(counts.values())
    return 100.0 * (1 - max(counts.values()) / total) if total else 0.0


gold_hinglish = [
    "hi",
    "en",
    "en",
    "en",
    "en",
    "en",
    "en",
    "en",
    "en",
    "hi",
    "hi",
    "hi",
]
assert len(tokens) == len(gold_hinglish)
cmi_curves = {}
for majority in (2, 4, 8):
    lengths = np.arange(majority, 2 * majority + 1)
    cmi_curves[majority] = (lengths, 100 * (1 - majority / lengths))
VisualizationOut [10]
CollapseExpand
Three curves rise from zero at a monolingual span to 50 at an even two-language split.
CMI at valid span lengths for three fixed majority-language counts in a two-language example. Each line ends where the two language counts are equal and CMI is 50.
ConsoleOut [11]
CollapseExpand
Gold distribution: Counter({'en': 8, 'hi': 4})
Gold CMI: 33.33
Windowed distribution: Counter({'en': 5, 'hi': 4, 'unk': 3})
Windowed CMI: 44.44
Windowed label coverage: 9/12

The gold annotation has four Hindi and eight English tokens, giving a CMI of 33.33. The window baseline assigns four Hindi and five English labels, with three unknowns. Its CMI is 44.44 at 9/12 label coverage.

Even when the two scores agree, the labels can differ at individual positions.

Switch-point detection

If you want to know where a system gets mixed-language wrong, the switch points are the right unit of analysis.

Define the set of switch points in a label sequence as

S(ℓ)={ t:2≤t≤T, ℓt,ℓt−1∈L, ℓt≠ℓt−1 }S(\ell) = \{\, t : 2 \le t \le T,\ \ell_t,\ell_{t-1} \in L,\ \ell_t \neq \ell_{t-1} \,\}

where:

  • ℓ=(ℓ1,…,ℓT)\ell = (\ell_1, \ldots, \ell_T): the sequence of language labels over TT tokens
  • ℓt\ell_t: the label assigned to token tt
  • tt: a token position from 2 through TT (position 1 has no predecessor)
  • LL: the set of language labels, excluding unknown and language-independent labels

The set contains a boundary only when both neighboring tokens carry different language labels. Unknown and language-independent labels prevent either neighboring pair from counting as a switch. Align gold and predicted labels to the same ordered token spans before comparing them. Equal lengths alone cannot verify this alignment.

P=∣Spred∩Sgold∣∣Spred∣,R=∣Spred∩Sgold∣∣Sgold∣,F1=2PRP+RP = \frac{|S_{\text{pred}} \cap S_{\text{gold}}|}{|S_{\text{pred}}|}, \quad R = \frac{|S_{\text{pred}} \cap S_{\text{gold}}|}{|S_{\text{gold}}|}, \quad F_1 = \frac{2PR}{P+R}

where:

  • SpredS_{\text{pred}}: the set of switch points detected in the predicted label sequence
  • SgoldS_{\text{gold}}: the set of switch points in the gold label sequence
  • PP: precision, the fraction of predicted switch points that are correct
  • RR: recall, the fraction of gold switch points that were predicted
  • F1F_1: the harmonic mean of precision and recall

A predicted boundary outside the gold set is a false positive, and a missed gold boundary is a false negative. The implementation uses zero for each undefined rate and prints both boundary sets so empty-boundary cases remain visible.

The equations use one-based positions and the code reports zero-based positions.

PythonIn [12]
CollapseExpand
def switch_points(labels, languages):
    check_language_labels(labels, languages)
    return {
        i
        for i, (left, right) in enumerate(zip(labels, labels[1:]), start=1)
        if left != right and left in languages and right in languages
    }


def switch_point_f1(gold, pred, languages):
    """Score label sequences already aligned to the same ordered token spans."""
    if len(gold) != len(pred):
        raise ValueError(
            "Gold and predicted labels must align to the same tokens."
        )
    g, p = switch_points(gold, languages), switch_points(pred, languages)
    tp = len(g & p)
    prec = tp / len(p) if p else 0.0
    rec = tp / len(g) if g else 0.0
    f1 = 2 * prec * rec / (prec + rec) if (prec + rec) else 0.0
    return prec, rec, f1, g, p


prec, rec, f1, g_pts, p_pts = switch_point_f1(
    gold_hinglish, pred, hinglish_languages
)
for score in (code_mixing_index, switch_points):
    try:
        score(["en", "eng"], hinglish_languages)
    except ValueError as exc:
        assert str(exc) == "Unknown labels: ['eng']"
    else:
        raise AssertionError("An out-of-inventory label was accepted.")
ConsoleOut [13]
CollapseExpand
gold switch points:      [1, 9]
predicted switch points: [8]
precision=0.00  recall=0.00  F1=0.00

Switch-point F1F_1 is a much better diagnostic than sentence accuracy for code-switched LID, because it directly measures the thing you care about: does the system know where the language changes? Sentence accuracy can be at 95% on a corpus where only 5% of sentences are mixed, while the system is useless on exactly those sentences.

The gold switch points are {1, 9} and the window baseline predicts {8}, using zero-based indices. The sets do not intersect, so precision, recall, and F1F_1 are each zero. More generally, if the gold set is nonempty and every gold boundary is missed, exact switch-point F1F_1 is zero under this convention.

Let's visualize gold versus predicted labels for this sentence. The rendering is separated from the label computation so that the figure depends only on precomputed values.

VisualizationOut [14]
CollapseExpand
Two-row grid of gold and predicted per-token language labels for a Hinglish sentence.
Gold and sliding-window labels for one Hinglish sentence. Gray cells indicate that the window classifier abstained. A correct boundary requires the language change to occur at the same token index.

The two rows make the metric interpretable. The prediction at position 8 is a false positive here because 8 is outside the gold set. The missed gold boundaries at 1 and 9 are false negatives. Where either adjacent prediction is unknown, the baseline emits no boundary.

Token coverage, token-level errors, and boundary errors answer different questions, so keep all three in the evaluation report.

Mixed Scripts and Unicode Traps

Before you can classify a language, you have to see the text correctly. In mixed-language text this is harder than it sounds, and the failure modes are silent. A string that looks right on screen can be wrong in ways that only appear when you compare byte sequences, and the wrongness can survive every stage of a pipeline until it shows up as a quality problem that nobody can trace back to its source.

As we covered in Character Encoding and Text Normalization, different code-point sequences can be canonically equivalent. Applying the same normalization form gives them a common representation. Unicode normalization treats equivalence separately from visual resemblance.

Script composition per token

For each whitespace-delimited token, inspect the Unicode Script property of its letters. Match a small, named set of scripts with regex and record letters outside that set separately. Marks and punctuation are excluded from this particular diagnostic. Unicode Standard Annex #24 specifies the Script and Script_Extensions properties.

PythonIn [15]
CollapseExpand
scripts_to_track = (
    "Latin",
    "Han",
    "Arabic",
    "Cyrillic",
    "Greek",
    "Devanagari",
    "Hiragana",
    "Katakana",
)
script_patterns = {
    name: regex.compile(rf"\p{{Script={name}}}") for name in scripts_to_track
}


def token_scripts(token):
    scripts = set()
    for char in token:
        if char.isalpha():
            script = next(
                (
                    name
                    for name, pattern in script_patterns.items()
                    if pattern.fullmatch(char)
                ),
                "Untracked",
            )
            scripts.add(script)
    return sorted(scripts)


mixed_samples = [
    "我明天有 meeting at 3pm",
    "بس الملف لسه مش جاهز",
    "食べる",
    "Ελληνικά and English",
]
script_rows = [
    (text, [(token, token_scripts(token)) for token in text.split()])
    for text in mixed_samples
]
ConsoleOut [16]
CollapseExpand
我明天有 meeting at 3pm
    我明天有         ['Han']
    meeting      ['Latin']
    at           ['Latin']
    3pm          ['Latin']

بس الملف لسه مش جاهز
    بس           ['Arabic']
    الملف        ['Arabic']
    لسه          ['Arabic']
    مش           ['Arabic']
    جاهز         ['Arabic']

食べる
    食べる          ['Han', 'Hiragana']

Ελληνικά and English
    Ελληνικά     ['Greek']
    and          ['Latin']
    English      ['Latin']

The Mandarin–English and Greek–English examples have tokens in more than one script across the sentence. The Japanese word mixes Han and Hiragana inside a single token as part of its ordinary spelling. The Arabic example stays in one script. These are observations about writing systems. For example, a Romanized Hindi word and an English word can both be Latin-only.

A character filter designed for Latin text would lose information in these examples. A separate policy may be useful for identifier security. Unicode's UTS #39 describes how script mixing and visual confusability differ. This diagnostic counts scripts and does not attempt to infer intent or visual confusability.

PythonIn [17]
CollapseExpand
script_sample_labels = ["Han + Latin", "Arabic", "Japanese", "Greek + Latin"]
script_latin_only = []
script_non_latin = []
script_mixed_or_other = []
for text, per_token in script_rows:
    latin_only = non_latin = mixed_or_other = 0
    for tok, scripts in per_token:
        if scripts == ["Latin"]:
            latin_only += 1
        elif len(scripts) == 1 and scripts != ["Untracked"]:
            non_latin += 1
        else:
            mixed_or_other += 1
    script_latin_only.append(latin_only)
    script_non_latin.append(non_latin)
    script_mixed_or_other.append(mixed_or_other)

script_left_nonlatin = script_latin_only
script_left_mixed = [a + b for a, b in zip(script_latin_only, script_non_latin)]
VisualizationOut [18]
CollapseExpand
Stacked bars of Latin-only, non-Latin, and mixed-script token counts for four samples.
Script composition of whitespace-delimited tokens in four examples. The Japanese word contains Han and Hiragana in one token, while the Greek–English example mixes scripts across tokens.

Normalization hazards

Unicode normalization can support exact matching on canonically equivalent strings. The form you choose determines whether compatibility distinctions survive. See Unicode Standard Annex #15.

PythonIn [19]
CollapseExpand
norm_samples = [
    "Café",  # composed form
    "Cafe\u0301",  # decomposed form
    "CAFE",  # fullwidth Latin
    "カフェ",  # halfwidth Katakana
    "①",  # circled digit
]

norm_rows = []
for s in norm_samples:
    for form in ("NFC", "NFKC"):
        norm_rows.append((s, form, unicodedata.normalize(form, s)))
ConsoleOut [20]
CollapseExpand
NFC   'Café'                 -> 'Café'  (len 4 -> 4)
NFKC  'Café'                 -> 'Café'  (len 4 -> 4)
NFC   'Café'                -> 'Café'  (len 5 -> 4)
NFKC  'Café'                -> 'Café'  (len 5 -> 4)
NFC   'CAFE'                 -> 'CAFE'  (len 4 -> 4)
NFKC  'CAFE'                 -> 'CAFE'  (len 4 -> 4)
NFC   'カフェ'                  -> 'カフェ'  (len 3 -> 3)
NFKC  'カフェ'                  -> 'カフェ'  (len 3 -> 3)
NFC   '①'                    -> '①'  (len 1 -> 1)
NFKC  '①'                    -> '1'  (len 1 -> 1)
Logical offsets [3:7]: '\u0633\u0644\u0627\u0645'

The important observations:

  • NFC preserves these compatibility-only distinctions; NFKC folds them. Fullwidth Latin collapses to ASCII. Halfwidth Katakana collapses to fullwidth. Circled numerals become plain digits. If your corpus distinguishes Japanese halfwidth and fullwidth forms for any downstream reason, NFKC erases that distinction permanently.
  • Decomposed versus composed forms affect deduplication. A crawler that hashes raw bytes will see Café and Cafe\u0301 as different strings. If two otherwise identical documents differ in this sequence, a raw-byte deduplication pass will keep both.
  • Character filters can remove required marks. As a separate check, evaluate ''.join(ch for ch in 'कि' if ch.isalnum()). It returns क and drops the vowel sign ि. Keep a fixture for each relevant script before using a character whitelist.

Decode the input using its known encoding. Record the normalization form and apply it consistently. The two spellings of Café in the cell give the same NFC string, so the normalized value alone cannot tell you which sequence was supplied. Keep the raw text when you may need the original code-point sequence. Derive any script-specific whitelist from the corpus.

Bidirectional text

Ordinary Arabic-script and Hebrew-script letters display right to left. The Unicode Bidirectional Algorithm determines how mixed-direction text is displayed. The cell above checks that logical offsets [3:7] select the four Arabic letters in the test string. Test the visual order in the annotation tool separately.

Use logical text offsets to associate tokens with annotations. Verify that your interface displays each selected span correctly, including mixed-direction reference and hypothesis fields. Test isolation and index mapping together in the annotation UI.

Render a known mixed-direction sentence in the annotation tool and ask a bilingual reader to confirm its order. Select a span and check the stored offsets against the original logical string.

Tokenization Economics

Token counts determine how much of a token-limited context the input occupies. To estimate costs, apply the deployed service’s billing rules to those counts. Measure latency and quality separately on the serving path.

Train two byte-level BPE tokenizers with the same 360-entry vocabulary budget and the same preprocessing. The first sees eight English training sentences. The second sees four of those English sentences and four Hindi sentences in Devanagari. The four manually written test variants are held out. The Hindi text and its romanization share meaning, though they use different spaces, punctuation, and encodings where those conventions differ.

PythonIn [21]
CollapseExpand
english_training = [
    "Please check the cable before bringing the laptop to the office.",
    "I will ask the team about the schedule this morning.",
    "They are bringing work to the next meeting.",
    "Could you come over after we finish charging the battery?",
    "The room is busy tonight because several people are there.",
    "Please call me at home and tell me how the party went.",
    "I could not go after all because I had other work.",
    "We shared the plans and moved the morning meeting.",
]
hindi_training = [
    "मैं आज सुबह काम पर जा रहा हूँ।",
    "आज रात घर पर खाना नहीं है।",
    "मैं कल बैठक में आ रहा हूँ क्योंकि काम है।",
    "तुम पार्टी में कब आ रहे हो और फिर कहाँ जाओगे।",
]
forms = {
    "English": "I am not coming to the party tonight because I have work.",
    "Devanagari Hindi": "मैं आज रात पार्टी में नहीं आ रहा हूँ क्योंकि मेरा काम है।",
    "Romanized Hindi": "Main aaj raat party mein nahi aa raha hoon kyunki mera kaam hai.",
    "Mixed Hindi–English": "Yaar main aaj night party mein nahi aa raha, because I have work.",
}


def train_byte_bpe(corpus):
    tokenizer = Tokenizer(models.BPE())
    tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
    tokenizer.decoder = decoders.ByteLevel()
    tokenizer.train_from_iterator(
        corpus,
        trainer=trainers.BpeTrainer(
            vocab_size=360,
            initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
            show_progress=False,
        ),
    )
    return tokenizer


training_sets = {
    "English training": english_training,
    "English + Hindi training": english_training[:4] + hindi_training,
}
bpe_models = {
    name: train_byte_bpe(texts) for name, texts in training_sets.items()
}
counts = {}
for name, tokenizer in bpe_models.items():
    encoded = [tokenizer.encode(text).ids for text in forms.values()]
    assert all(
        tokenizer.decode(ids) == text
        for ids, text in zip(encoded, forms.values())
    )
    counts[name] = [len(ids) for ids in encoded]

form_names = list(forms)
form_positions = np.arange(len(form_names))
ConsoleOut [22]
CollapseExpand
English {'English training': 24, 'English + Hindi training': 42}
Devanagari Hindi {'English training': 147, 'English + Hindi training': 42}
Romanized Hindi {'English training': 47, 'English + Hindi training': 54}
Mixed Hindi–English {'English training': 36, 'English + Hindi training': 54}

Adding Devanagari training text gives the second tokenizer opportunities to learn Devanagari merges. It has no Romanized Hindi training sentences, so the result for Romanized Hindi remains a measure of what it can reuse from the training mixture. The output varies with the training fixtures and the chosen input. In the displayed order (English, Devanagari Hindi, Romanized Hindi, mixed Hindi–English), English-only training gives 24, 147, 47, and 36 tokens. English-plus-Hindi training gives 42, 42, 54, and 54 tokens.

VisualizationOut [23]
CollapseExpand
Grouped horizontal bars compare token counts from English-only and English-plus-Hindi toy BPE training.
Total tokens in four held-out strings under two byte-level BPE tokenizers with the same vocabulary budget. The first training set uses English, and the second includes English and Devanagari Hindi.
Token counts are not a fair cross-lingual comparison

The experiment measures segmentation under explicitly limited training mixtures. An application comparison should use several independently validated examples, the exact deployed tokenizers, and end-task measurements in the intended languages. Petrov et al. (2023) use a parallel corpus to compare token-count disparities across many real tokenizer and language pairs.

Modeling Code-Switched Text

Consider three starting points for mixed-language models: a direct model, augmentation, or a cascade. Compare them on the same task and sampled data, and track annotation and serving costs alongside quality.

Direct multilingual pretraining

Train or fine-tune one model to accept the whole input without routing it through a language-specific model for each span. mBERT uses Wikipedia across languages, and XLM-R and mT5 use multilingual web corpora. Check the training data for examples that match your deployment inputs. If you expect Hindi in Devanagari, romanized Hindi, and Hindi–English mixtures, include each in your evaluation and measure whether fine-tuning on matched examples helps.

mT5 uses a shared vocabulary and pretrained parameters across languages. Inspect actual subword segmentations and evaluate transfer in both directions on the text and task you intend to support.

Check where the corpus has gaps in script and topic coverage. If almost all your mixed-language training examples come from casual conversation, measure performance on formal or technical samples before using the model for those inputs.

Data augmentation and synthetic code-switching

With parallel examples, generate mixed candidates by substituting aligned spans. Pratapa et al. study synthesis guided by linguistic constraints. Winata et al. use aligned parallel sentences to build synthetic examples. State which alignment and constraints your implementation uses.

Compare the resulting switch positions, span lengths, and registers against a naturally occurring sample. Test whether any repeated alignment heuristic changed the generated distribution.

Compare real-only, synthetic-only, and mixed training sets at specified sizes. Use naturally occurring held-out examples for the comparison and report the language pair, task, and acquisition conditions.

Translationese

Use translated and naturally occurring examples as separate data sources. Inspect the converted examples for word order, discourse markers, and register. State which source supplies your evaluation and verify that the reported score applies to your intended setting.

Cascaded pipelines

A cascade segments the input, routes each segment to its assigned model, then merges the results. Evaluate that full path separately on reliable long spans and ambiguous short spans.

Test whether segmentation errors propagate by comparing a cascade with annotated spans and with predicted spans. Inspect entity spans that cross a boundary and compare translation and retrieval independently. Recovery depends on which information reaches the next stage.

A rough decision guide

Candidate modeling approaches by task and data availability.
SituationReasonable starting point
Plenty of in-language text, few labelsDirect multilingual fine-tune
Little in-language text, parallel data availableSynthesize + mix with any real CS data
Long segments, per-language tools already existCascade with span segmentation
Token-level task on romanized textDirect model; treat script as an explicit feature
Very low-resource language pairCross-lingual transfer from a high-resource relative

None of these is a substitute for measuring on real code-switched evaluation data. The next section shows why.

Generating Code-Switched Output

A bilingual support assistant may need to reply in the mix and register a user requests. Decide which combinations, scripts, and styles the task supports, then evaluate sample replies with readers from the intended setting.

An autoregressive model predicts each next token from the prompt and preceding output available within its context window. Test whether changing the prompt, recent user turn, or example replies changes the target language proportions.

What the prompt has to specify

A prompt for code-switched output should specify at least four things.

  • The language pair. "Hinglish" is not enough; specify the Hindi, English, romanized-or-Devanagari script, and the register.
  • The switching pattern. Say whether switches may occur between sentences, within sentences, or both.
  • The length. Compare like-length answers when you measure switch placement or language proportions.
  • An anchor. Include example turns that demonstrate the target mix and register. Test their effect against a prompt without those examples.

A prompt that names all four looks like this:

Code
CollapseExpand
You are a bilingual assistant for users in urban North India.
Reply in Hinglish: Hindi syntax and function words written in Latin
script, mixed with English content words. Switch within sentences,
not only between them, and roughly 40 percent of the words should be
English. Do not reply in pure English or pure Hindi, even if the user
does. Keep replies to two or three sentences.

Example turn:
  User: bhai laptop ki battery kharab ho gayi, kya karun
  Assistant: Pehle charger aur cable check karo, yaar. Agar woh theek
  hai to battery calibration try karo, aur agar phir bhi issue hai
  to service center hi jana padega.

User: mujhe ek naya phone lena hai, budget 20k

The example turn illustrates script, register, and switch placement. Use the separately labeled response exercise to measure how close an answer comes to the rough 40% English target. Compare prompts with and without the example on matched inputs.

Drift

Include four checks in the generation evaluation:

Language collapse. Compare the language distribution for the whole reply with its trailing window. The hand-written fixture below contains one reply that starts mixed and ends in English.

Turn-dependent collapse. Vary the last user turn while holding earlier turns fixed. Check whether the reply still follows the requested conversation-wide language policy.

Register mismatch. Ask target readers whether formal Devanagari Hindi mixed with English suits a request written in casual romanized Hindi. Review the register even when language and script labels match their targets.

Script and spelling inconsistency. Check changes in script separately from spelling variation such as mujhe and mujhey. Test whether your lexical matcher handles the variants the application accepts.

Use separate checks for label proportions, switch placement, spelling, and register. Report the checks and their known limits. CMI measures language-label balance and cannot by itself establish naturalness or the position of a shift.

Evaluating Mixed-Language Output

Choose metrics for the decision at hand. First check what their units, denominators, and reference representations permit them to measure.

Why accuracy and BLEU mislead

Sentence-level LID accuracy compares each selected label with a single reference label. If 95% of the dataset has the same monolingual reference label and the remaining 5% is labeled mixed, always returning the majority label scores 95% and misses all mixed items.

Token-level LID accuracy is better but still misleads if it is computed only on tokens within the dominant language. Report it stratified by gold label, and report switch-point F1F_1 alongside it. Note also that token-level accuracy hides the granularity mismatch: a token is not the same unit as a switch point, and a system can score high per-token while systematically erring exactly at the boundaries. This is the LID version of the class-imbalance problem, and it has the same fix: report the metric per class and report the metric on the rare class separately.

CMI matched against gold. The code-mixing index, computed on predicted versus gold labels, gives a scalar sense of how mixed the prediction is compared with the reference. A much lower CMI than gold can indicate a dominant-label bias. Check coverage because unknown labels can also change the denominator. CMI is invariant to token order and language-name permutations. It measures label balance rather than switch placement or the direction of a monolingual collapse.

BLEU on mixed output. Compare outputs with references written for the same target language policy and stated tokenization. BLEU rewards matching n-grams, so alternate switch placements and paraphrases can change the score. Use semantic and style judgments for distinctions that the overlap score leaves open.

Perplexity. Specify the evaluated model, token representation, and matching inputs before comparing likelihoods. Evaluate whether readers find the outputs natural separately.

Metrics that measure mixing

Four metric families are worth building into your evaluation harness.

  1. Language proportions. Measure each language's share of the labeled words and check it against a specified target range. Report tagger coverage and validate tags on a sample of the intended style.
  2. Switch-point density. Divide the number of switches by the number of adjacent word pairs. The exercise reports zero for a one-word response, which has no adjacent pair. Compare with a reference corpus measured the same way.
  3. Script and spelling consistency. Use Unicode properties to check script composition. Comparing romanization variants requires a separate spelling convention and annotations, even when all the characters are Latin.
  4. Human judgments. Ask bilingual readers to assess meaning, naturalness, and register. Report mixed and monolingual slices separately.

The following four responses are hand-written. The helper accepts one hi or en label per whitespace-delimited word, and the response must contain at least one word. Punctuation stays attached to its word. The Hindi-only control uses Latin letters. For inputs with unknown labels, report annotation coverage before choosing a denominator, then use a calculation designed for those labels.

PythonIn [24]
CollapseExpand
candidates = {
    "Mixed": (
        "Pehle charger aur cable check karo yaar. Agar woh theek hai to battery calibration try karo.",
        "hi en hi en en hi hi hi hi hi hi hi en en en hi",
    ),
    "English only": (
        "First check the charger and cable. Then try calibrating the battery.",
        "en en en en en en en en en en en",
    ),
    "Hindi only": (
        "Pehle taar aur jod ki jaanch karo. Phir dobara koshish karo.",
        "hi hi hi hi hi hi hi hi hi hi hi",
    ),
    "Shifts to English": (
        "Pehle charger aur cable check karo yaar. Then run a battery calibration cycle.",
        "hi en hi en en hi hi en en en en en en",
    ),
}


def evaluate_response(text, label_string):
    answer_tokens, labels = text.split(), label_string.split()
    if not answer_tokens or len(answer_tokens) != len(labels):
        raise ValueError("Provide a nonempty response and one label per word.")
    if set(labels) - hinglish_languages:
        raise ValueError("The fixture accepts only hi and en word labels.")
    n = len(labels)
    switches = len(switch_points(labels, hinglish_languages))
    full_english = labels.count("en") / n
    end_english = labels[-5:].count("en") / len(labels[-5:])
    return {
        "words": n,
        "switches": switches,
        "switch_density": switches / (n - 1) if n > 1 else 0.0,
        "cmi": code_mixing_index(labels, hinglish_languages),
        "english_share": full_english,
        "end_english_share": end_english,
        "latin_only_share": sum(
            token_scripts(t) == ["Latin"] for t in answer_tokens
        )
        / n,
    }


reports = {name: evaluate_response(*item) for name, item in candidates.items()}
drift_x = np.arange(len(reports))
whole_english = [r["english_share"] for r in reports.values()]
last_english = [r["end_english_share"] for r in reports.values()]
ConsoleOut [25]
CollapseExpand
Mixed              switches= 6  density=0.400  CMI= 37.5  English=37.5%  final five English=60%  Latin-only=100%
English only       switches= 0  density=0.000  CMI=  0.0  English=100.0%  final five English=100%  Latin-only=100%
Hindi only         switches= 0  density=0.000  CMI=  0.0  English=0.0%  final five English=0%  Latin-only=100%
Shifts to English  switches= 5  density=0.417  CMI= 30.8  English=69.2%  final five English=100%  Latin-only=100%

The mixed reply has six switches across 15 adjacent pairs. Its CMI is 37.5, and its English share is 6/16 (37.5%) overall and 3/5 (60%) at the end. The drift reply has five switches across 12 pairs and a CMI of about 30.8. Its English share is 9/13 (69.2%) overall and 5/5 (100%) at the end. Both monolingual controls have zero CMI and zero switches, with English shares of 100% and 0% respectively. All four replies have a Latin-only share of 100%.

VisualizationOut [26]
CollapseExpand
Grouped bars compare full-response and ending English shares for mixed, monolingual, and drifting fixtures.
Share of English labels in each hand-annotated response and in its last five words. The response that shifts to English has both languages overall and only English in its final window.

Data contamination and benchmark blindness

Two contamination-adjacent problems bite code-switched evaluation specifically.

Check benchmark provenance. GLUECoS and LinCE are public. Check for overlap where the training corpus is available and record which benchmark split you used. Report results on a documented held-out sample when available.

Check annotation policies. Before combining corpora, compare their treatment of loans and unknown words. State the adopted policy in the reported results.

GLUECoS and LinCE

The original GLUECoS paper covers Hindi–English and Spanish–English across language identification, part-of-speech tagging, named entity recognition, sentiment, question answering, and natural language inference. LinCE combines data for Spanish–English, Nepali–English, Hindi–English, and Modern Standard Arabic–Egyptian Arabic across four tasks. Report the pair, task, and split when comparing results.

Deployment Failure Modes

Use this checklist to trace where mixed-language text can fail during routing, evaluation, and serving.

Silent LID misrouting. Suppose a document tagged en goes to an English-only pipeline even though part of it uses another language. Log the label and available scores. A top-two score margin can flag close classifications for review. Measure what your threshold catches and audit confident assignments on mixed inputs too.

Romanized text treated as English. In the example ‘Mujhe kal call karna’, the Hindi phrase and the English-origin call appear in Latin letters. Test what a script-only router selects and compare it with the search or moderation policy for the intended content.

Normalization can remove distinctions. In the fixture, NFKC merges halfwidth and fullwidth variants. An ASCII-only whitelist can remove the code points in an Indic or Arabic word. Test your chosen cleaning rules with those examples and keep the original where exact spelling matters.

Bidi display. Check the visual display and the mapping from a selected span to logical offsets in the original text. Test isolation of reference and hypothesis fields before annotating production examples.

Moderation errors. Evaluate moderation on reviewed mixed-language examples, including benign and policy-violating content. Report false positives and false negatives separately for the language combinations your service handles.

Output language drift. Measure each turn and the trailing window of each reply. Evaluate whether a retry or repair improves the intended behavior on reviewed examples. A session-wide average can conceal a monolingual final turn.

Token cost. Compare the same deployed tokenizer on verified Romanized Hindi, Devanagari Hindi, English, and mixed-language variants. Report the measured input lengths by slice, then apply the service’s billing rules and benchmark latency independently.

Search and retrieval asymmetry. Test whether a mixed query retrieves a valid monolingual document. Report lexical and dense retrieval separately on matched language and script slices; recompute the aggregate to see whether a large slice masks a smaller one.

Annotation drift. Record the loanword policy and compare agreement on mixed and monolingual spans. Inspect disagreements before treating them as model errors or changing the annotation rules.

Cache and deduplication keys. The Café example shows that distinct byte sequences can become identical after normalization. First decide which requests are equivalent for response reuse. Include the text representation and the relevant context, such as tenant or authorization scope, model and prompt version, response language, history, and tool options. Keep raw text when an output depends on its exact signs or spelling. Use a separate content-comparison key and test identical text under different request settings.

Check which failure modes occur in your own traffic before using aggregate completions or quality metrics as evidence about mixed-language support.

Limitations and Impact

Review mixed-language examples at the point where the system makes a decision. An English-only index can return an ordinary result for a bilingual query while missing the part that carries the request. In that case, check the language labels and the retrieval result together.

Document who supplied the data, how word and span boundaries were annotated, and how borrowings and uncertain cases were handled. Repeat the evaluation across the groups and writing styles the system is designed for. A corpus policy tells the reader what its labels mean, including cases where the text alone leaves the intended interpretation open.

Otheguy, García, and Reid (2015) describe translanguaging as drawing on a speaker's full repertoire and propose a unitary account of bilingual grammar. MacSwan (2017) also distinguishes a speaker's repertoire from named languages and proposes an internally diverse grammar. For an engineering task, define the token-label policy against the decision it serves. If those labels route queries to an index, measure whether users can find the intended documents as well as whether the model matches the annotations.

A test set made of formal paragraphs can miss the spellings and switching patterns in a customer's chat messages. Sample the settings you plan to support and report results by language combination, script, and task.

When you deploy a system for mixed-language text, build these checks into your workflow.

  • Measure script composition and language at multiple granularities.
  • Log LID scores alongside the chosen labels.
  • Tag romanized text explicitly.
  • Evaluate on naturally occurring code-switched text with switch-aware metrics.
  • Check generated output for language drift.

Summary

For mixed-language inputs, test what information each stage passes to the next one.

  • Switch location. Check whether the decisions you need align with sentence, span, token, or morpheme boundaries.
  • Language labels. Use span or token labels when you need to locate changes within a sentence. Exact switch-point F1F_1 measures boundary placement.
  • Romanized text. Hindi written as hi-Latn shares Latin script with English. Keep both language and script in catalog tags when they are known.
  • Script composition. The Japanese fixture combines Han and Hiragana inside a token. Check visual lookalikes separately from script composition.
  • Normalization. Test exactly which code-point distinctions your cleaner removes and keep source text when those distinctions matter.
  • Token counts depend on the tokenizer and representation. Compare deployed tokenizers on spelling variants and in-domain mixed-language inputs to estimate context usage and input-token billing.
  • Generation. Check language proportions, placement, script, spelling, and register in each turn and in its trailing window.
  • Use several evaluation measures. Report label coverage, CMI, switch boundaries, and language proportions at the granularity the task needs. Evaluate meaning, register, and naturalness with bilingual readers.
  • Deployment checks. Log the selected labels and available scores. Test normalization, caching, retrieval, and moderation separately on multilingual samples.

Compare the language combinations, spellings, and settings in your benchmark with those your users rely on, then evaluate any missing slices directly.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about code-switching, language identification granularity, and evaluating mixed-language systems.

Code-Switching and Mixed-Language Text

Question 1 of 80 of 8 completed
In the sentence "I told him ki main kal nahi aa sakta", the switch happens inside a single sentence, often at a constituent boundary. Which category does the chapter use for this?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 8

Cross-Lingual Transfer and Alignment

Learn how cross-lingual transfer works: shared representations, zero-shot and translate-train designs, alignment objectives, adapters, diagnostics, and evaluation.

43 min read
Language AI Handbook · Vol. 8

Cultural and Multilingual Evaluation

Measure what multilingual benchmarks miss: translationese, construct validity, cultural knowledge, local harms, and native-speaker-led evaluation design.

54 min read
Language AI Handbook · Vol. 8

Multilingual Pre-training and Data Balancing

Learn how multilingual language models allocate training budgets across languages using temperature-based sampling, effective epochs, capacity trade-offs, and per-language diagnostics.

57 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026codeswitching, author = {Michael Brenndoerfer}, title = {Code-Switching and Mixed-Language Text}, year = {2026}, url = {https://mbrenndoerfer.com/writing/code-switching-mixed-language-text-nlp-pipelines}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Code-Switching and Mixed-Language Text. Retrieved from https://mbrenndoerfer.com/writing/code-switching-mixed-language-text-nlp-pipelines
MLAAcademic
Michael Brenndoerfer. "Code-Switching and Mixed-Language Text." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/code-switching-mixed-language-text-nlp-pipelines>.
CHICAGOAcademic
Michael Brenndoerfer. "Code-Switching and Mixed-Language Text." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/code-switching-mixed-language-text-nlp-pipelines.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Code-Switching and Mixed-Language Text'. Available at: https://mbrenndoerfer.com/writing/code-switching-mixed-language-text-nlp-pipelines (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Code-Switching and Mixed-Language Text. https://mbrenndoerfer.com/writing/code-switching-mixed-language-text-nlp-pipelines
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy