Multilingual language models handle English well and Spanish well, yet they often fail on a sentence that moves from one language to the other. That alternation is called code-switching. One explanation is that the models were pre-trained almost entirely on single-language text. A token that follows a language switch therefore receives an internal representation unlike anything the model saw in training, and the task layers above it misread it. Corpus evidence suggests this disruption is local. In both Spanish-English and Mandarin-English conversation, part-of-speech statistics spike at the switched token and return to baseline within three to four tokens (Analyzing the Role of Part-of-Speech in Code-Switching). If the damage is local, the repair can be local too.
We propose a token-level version of adversarial domain adaptation. Adversarial domain adaptation is the technique of training a small classifier, the discriminator, to tell two domains apart, while reversing its gradient into the main encoder so the encoder learns features the discriminator cannot separate. Our discriminator looks at one token's contextual representation and guesses whether that token sits in a mixed-language sentence or a single-language sentence. It is told the token's own language and part of speech, so the encoder is never pushed to forget which language a word belongs to. Its loss is weighted toward tokens within a few positions of a switch. The goal is narrow: a Spanish noun right after an English verb should look to the model like a Spanish noun in a Spanish sentence. Training needs labeled monolingual data and unlabeled code-switched text, nothing more.
Core Claim
Monolingual training bias is a context-distribution shift concentrated near switch points. It can be reduced by adversarial alignment that is conditional (on token language and part of speech) and local (weighted by distance to the nearest switch). This should beat both sentence-level adversarial alignment and unconditional token-level alignment. The first spends its capacity on the many tokens that are not disturbed. The second destroys language identity, which the model needs.
Let $h_t$ be the encoder's representation of token $t$. Let $c_t \in \{0,1\}$ indicate whether its sentence is monolingual or code-switched. Let $\ell_t$ and $p_t$ be its automatically predicted language tag and part-of-speech tag, and let $d_t$ be its distance in tokens to the nearest switch point ($d_t=\infty$ in monolingual sentences). The discriminator $D$ minimizes
$$ \mathcal{L}_{adv} = \sum_t w(d_t)\, \mathrm{CE}\big(D(h_t, \ell_t, p_t),\, c_t\big), \qquad w(d) = \max\!\big(\epsilon,\, e^{-d/\tau}\big). $$
Here CE is cross-entropy. $\tau$ sets the window width, and we expect it to land near 2 to 3 tokens given the reported decay. $\epsilon$ is a small floor that keeps distant and monolingual tokens in play. Monolingual tokens are sampled to match the language and part-of-speech mix of the weighted target tokens. A gradient reversal layer with scale $\lambda$ sits between $h_t$ and $D$, so the encoder is trained to maximize $\mathcal{L}_{adv}$ while the task head trains only on labeled monolingual examples.
Relation to Prior Work
The closest work is Learning not to Discriminate. It attaches a gradient-reversal discriminator for "monolingual vs. code-switched" to a speech encoder and reports gains such as Tamil code-switched word error rate falling from 55.93% to 53.15%. This paper motivates our approach and supplies the mechanism. However, its discriminator judges whole utterances, and its system needs oracle knowledge at test time of which output head to use. We change three things: we move to the token level, we condition on language and part of speech, and we keep a single task head so no routing is needed. We also work on text encoders rather than acoustic features.
Improving Code-Switching Language Modeling with Artificially Generated Texts Using Cycle-Consistent Adversarial Networks uses adversarial networks only to generate synthetic code-switched text, and it reports semantic drift in that text. We use the adversarial game inside the representation instead, and we treat synthetic text as a competing baseline.
Two papers learn invariance without an adversary. Code-switching Mediated Sentence-level Semantic Learning minimizes the distance between sentence embeddings of parallel monolingual and code-switched versions of the same utterance. That requires triplet corpora, which our setting lacks. Language Informed Modeling of Code-Switched Text adds a language-identification prediction objective so hidden states encode where switches happen. Their effect runs opposite to ours: they make switches more visible, while we make the context around a switch less distinctive.
A constraint from the adaptation literature shapes the design. Aggressive invariance erases task signal, as in FAN-Net's finding that altering more than a small fraction of the Fourier amplitude spectrum degrades segmentation (FAN-Net). This is why we condition and localize rather than align everything. The benchmark evidence that motivates the problem is the gap between strong low-level tagging and weak semantic tasks reported in GLUECoS, LinCE, and Multilingual Large Language Models Are Not (Yet) Code-Switchers.
Research Program
We fine-tune mBERT and XLM-R encoders, the models used throughout the GLUECoS and LinCE comparisons, and set up two regimes.
In the main regime, unsupervised adaptation, we split each benchmark's training data. Sentences with no switch keep their labels and serve as the labeled source. Code-switched sentences lose their labels and serve as the unlabeled target. Evaluation is on the original code-switched test sets. This split needs no external data, and it isolates monolingual training bias directly. Language tags come from an off-the-shelf code-switched identification tagger, which is reliable at this level (GLUECoS reports 96.6 F1 for English-Hindi identification). Part-of-speech tags come from a tagger trained on the same benchmark.
The second regime is few-shot. It adds 100 to 1000 labeled code-switched sentences, to test whether the gain survives once some in-domain supervision exists.
Tasks cover tagging and semantic understanding. They are Spanish-English named-entity recognition and Hindi-English part-of-speech tagging from LinCE, and English-Hindi natural language inference and sentiment from GLUECoS. The Spanish-English Bangor-Miami corpus, where only 8% of sentences switch, gives a naturally source-heavy split for tagging analyses.
Beyond accuracy, we build two diagnostics. The first is an error profile: error rate as a function of distance from the nearest switch. The second is a post-hoc probe, trained after the model is frozen, that tries to recover "mixed vs. monolingual context" from $h_t$ at each distance. The mechanistic prediction is that baseline errors and probe accuracy both peak at distances 0 to 3, and that our method flattens both curves without lowering language-identification probe accuracy.
Baselines
The naive reference is the same encoder fine-tuned only on the labeled monolingual subset and evaluated zero-shot on the code-switched test set. This is the setting in which GLUECoS documents transfer failure.
The fully supervised reference fine-tunes on all labeled training data, including the code-switched sentences. It serves as a ceiling and as a calibration against published numbers. GLUECoS reports 63.1% accuracy on code-switched natural language inference with its modified mBERT. LinCE reports 63.56 micro-F1 for mBERT on Spanish-English named-entity recognition and an 82.93% average across its tasks. Our reruns should land near these figures before any comparison is trusted.
The strongest existing competitor is continued masked-language-model pre-training on the same unlabeled code-switched sentences before task fine-tuning. It uses exactly the data our method uses and directly exposes the model to switch-boundary statistics. We run it with the same number of target-side passes, the same learning-rate search budget (an equal number of trials per method), and the same seeds. We also run it combined with our loss.
The second competitor is sentence-level gradient-reversal adaptation in the style of Learning not to Discriminate. It is ported to text, uses a pooled sentence representation and a single shared head, and receives an identical $\lambda$ search.
The third competitor is synthetic code-switching. Nouns in the labeled monolingual sentences are translated using a bilingual dictionary, in the spirit of MIGRATE's noun substitution, and the labels are carried over.
Two ablations isolate the key ingredients: uniform weighting ($w \equiv 1$) removes locality, and dropping $\ell_t, p_t$ from the discriminator input removes conditioning.
Beating the field means three things. Across at least three of the four tasks, averaged over five seeds, the method must exceed continued pre-training by a margin larger than the seed standard deviation, alone or as an addition on top of it. It must recover a meaningful fraction of the gap between the naive and fully supervised references. Its gains must concentrate on tokens near switch points.
Why not just…?
Why not just continue masked-language-model pre-training on the unlabeled code-switched text? This is the real threat. Exposing the encoder to mixed text may fix boundary representations without any adversary. Our bet is that pre-training on a few thousand sentences shifts the representation in ways unrelated to the task, while the adversarial loss aligns exactly the features the task head reads. The experiment settles it in two ways. We sweep unlabeled-set size from 1k sentences to the full split. We test whether our loss still adds accuracy on top of pre-training. If pre-training matches us at every size and the combination adds nothing, the conclusion is that boundary drift is fixed by exposure alone, and we will report it that way.
Why not just generate synthetic code-switched training data? Generated text inherits the generator's view of where switches occur. CycleGAN-generated text showed semantic corruption, and the gain was modest (evaluation-set mixed error rate fell from 22.4% to 21.0%). Noun-only substitution, as in MIGRATE, by construction avoids switches at verbs, which is where the part-of-speech study finds grammatical clashes. Our error profiles, split by the part of speech of the switched token, will show whether synthetic data helps only at noun switches while our method also helps elsewhere.
Why not just use a sentence-level discriminator, which already worked for speech? A pooled representation is dominated by the many tokens far from any switch. The discriminator can then succeed or fail on surface cues such as script or vocabulary, rather than on the distorted boundary representations. The uniform-weight ablation and the sentence-level baseline test this directly. If either matches the windowed version, locality is not the active ingredient.
Why not just add a language-identification objective? That objective teaches the model where switches are, which helps language modeling: perplexity fell from 20.92 to 19.52 in Language Informed Modeling. It does not make the representations after a switch resemble those the task head was trained on. We include it as an additional baseline under the same tuning budget, and we check whether it is complementary to our loss.
Decisive Checks
The idea stands or falls on three results. First, the naive model's error-by-distance curve must actually peak within a few tokens of switch points; if errors are uniform across the sentence, the local hypothesis is wrong from the start. Second, our method must flatten that peak more than continued pre-training does, at matched data and tuning budget. Third, the unconditional ablation must lose language-identification probe accuracy and named-entity performance while the conditional version keeps them. That outcome would show that conditioning is what lets adversarial alignment remove the bias without removing the language signal.
References
- Analyzing the Role of Part-of-Speech in Code-Switching: A Corpus-Based Study
- Learning not to Discriminate: Task Agnostic Learning for Improving Monolingual and Code-switched Speech Recognition
- Improving Code-Switching Language Modeling with Artificially Generated Texts Using Cycle-Consistent Adversarial Networks
- Code-switching Mediated Sentence-level Semantic Learning
- Language Informed Modeling of Code-Switched Text
- Fan-Net: Fourier-Based Adaptive Normalization for Cross-Domain Stroke Lesion Segmentation
- GLUECoS: An Evaluation Benchmark for Code-Switched NLP
- LinCE: A Centralized Benchmark for Linguistic Code-switching Evaluation
- Multilingual Large Language Models Are Not (Yet) Code-Switchers
- MIGRATE: Cross-Lingual Adaptation of Domain-Specific LLMs through Code-Switching and Embedding Transfer