Sub topic 12
Language adapters and parameter-efficient adaptation
This chapter assumes you have fine-tuned a pretrained transformer for classification with Hugging Face transformers. It also assumes you know what a weight matrix and a gradient update are, and that you have read the earlier chapters on zero-shot transfer and the curse of multilinguality. The question here is how to adapt a multilingual model to a new language or task without retraining all of it.
Why full fine-tuning is a poor fit
Full fine-tuning updates every weight. XLM-R base has about 278 million parameters, and a copy of that size is needed for every task, and for every language if you also adapt per language. Three problems follow:
- Storage and serving cost. Ten tasks across twenty languages could mean two hundred full checkpoints.
- Interference. Updating all weights on one language can degrade the others. This is catastrophic forgetting.
- Capacity limits. The curse of multilinguality says a fixed-size model spreads its capacity thin across languages. Low-resource languages and languages unseen in pretraining suffer most. Making the whole model bigger is expensive. Adding a small number of language-specific parameters is cheap.
Parameter-efficient adaptation freezes the pretrained model and trains a small set of new parameters, typically 0.1% to 5% of the total. The frozen model stays shared, and only the small module is stored per task or language.
Bottleneck adapters
An adapter is a small feed-forward network inserted inside each transformer layer, usually after the attention or feed-forward sublayer. It projects the hidden vector down to a small dimension, applies a nonlinearity, projects back up, and adds the result to the input through a residual connection:
h' = h + W_up · GELU(W_down · h)
The ratio between the hidden size and the small dimension is the reduction factor. A larger factor gives a smaller adapter. The up-projection is initialized near zero, so the adapter starts as an identity function and does not disturb the pretrained model at the start of training.
import torch
from torch import nn
class BottleneckAdapter(nn.Module):
def __init__(self, hidden=768, reduction=16):
super().__init__()
self.down = nn.Linear(hidden, hidden // reduction)
self.up = nn.Linear(hidden // reduction, hidden)
self.act = nn.GELU()
nn.init.zeros_(self.up.weight)
nn.init.zeros_(self.up.bias)
def forward(self, x):
return x + self.up(self.act(self.down(x)))
adapter = BottleneckAdapter()
n_params = sum(p.numel() for p in adapter.parameters())
print("params per adapter:", n_params)
print("params for 12 layers:", n_params * 12)
x = torch.randn(2, 10, 768)
print("identity at init:", torch.allclose(adapter(x), x))One adapter has 74,544 parameters. Twelve of them total about 0.9 million, roughly 0.3% of XLM-R base. During training you freeze every original weight and update only the adapters. Many setups also train the layer norms and the task head.
Language adapters and task adapters: MAD-X
MAD-X (Multiple ADapters for Cross-lingual transfer) splits adaptation into two kinds of adapter, so that language knowledge and task knowledge can be trained separately and combined later.
- Language adapter. Train one per language on masked language modeling over unlabeled text in that language, with the base model frozen. This needs no labels. Wikipedia or web text is enough.
- Task adapter. Train one on labeled data in a source language such as English. During this step the English language adapter is stacked underneath, and only the task adapter receives gradients.
- Zero-shot inference. For a target language, swap the English language adapter for the target language adapter and keep the task adapter. The task adapter was trained to read the representations produced by an English language adapter, so it can work on the target-language representations the swapped-in adapter produces.
The original MAD-X also adds invertible adapters at the embedding layer. These adjust the token embeddings to the target language's vocabulary distribution. They matter most for languages and scripts that the pretrained model covers poorly. For a language the model never saw, you may also need to extend the vocabulary and train new embeddings, because a tokenizer that splits every word into single characters wastes sequence length and gives the model little to work with.
Strengths and limits of the approach
- Language adapters are reusable. One Swahili adapter serves every task, and one NLI task adapter serves every language.
- The cost of a new language is one cheap unsupervised training run.
- Adapters add layers, so inference is slightly slower unless you merge or remove them.
- Swapping works best when the task adapter was trained with a frozen language adapter. If the language adapter was updated during task training, the representations drift and swapping breaks.
- Gains are largest for low-resource and unseen languages. For high-resource languages already well covered by XLM-R, a swapped adapter gives little or nothing over plain zero-shot transfer.
LoRA and other parameter-efficient methods
Adapters are one family. Others you will meet:
| Method | What is trained | Typical size | Notes |
|---|---|---|---|
| Bottleneck adapters | Small MLP inserted in each layer | 0.5% to 3% | Adds inference latency, supports stacking |
| LoRA | Low-rank update to chosen weight matrices | 0.1% to 1% | Can be merged into the weights, no extra latency |
| Prefix and prompt tuning | Learned vectors prepended to the input or attention keys and values | Under 0.1% | Weakest on smaller models, sensitive to hyperparameters |
| BitFit | Only the bias terms | Under 0.1% | Simple baseline |
LoRA (Low-Rank Adaptation) replaces a weight update ΔW with the product of two thin matrices, B · A, where the rank r is small, such as 8. For a 768 × 768 matrix, a rank-8 update has 12,288 trainable parameters instead of 589,824. After training you can add B · A into the original weight, so inference costs the same as the base model.
from peft import LoraConfig, TaskType, get_peft_model
from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained(
"xlm-roberta-base", num_labels=3
)
config = LoraConfig(
task_type=TaskType.SEQ_CLS,
r=8,
lora_alpha=16,
lora_dropout=0.1,
target_modules=["query", "value"],
)
peft_model = get_peft_model(model, config)
peft_model.print_trainable_parameters()With TaskType.SEQ_CLS, PEFT also keeps the classification head trainable. The printed fraction is under 1% of the model. You can pass peft_model to the same Trainer setup from the zero-shot chapter, with the same English XNLI training data and the same German and Swahili test sets. peft_model.save_pretrained("xlmr-lora-xnli-en") stores only the small adapter files, not the 278-million-parameter base.
Because LoRA can be trained on any text, you can use it in the MAD-X style too. Train one LoRA on target-language masked language modeling and another on the task, then combine them. This works less reliably than MAD-X's purpose-built stacking, because LoRA updates modify the same weights and can interact. Check combined results on a validation set in the target language before you trust them.
Choosing a strategy
- Target language is well covered in pretraining and you have English labels: plain zero-shot transfer is the baseline. Adapters add cost for little gain.
- Target language is low-resource, with unlabeled text available: train a language adapter, and consider extending the vocabulary. This is the case MAD-X was built for.
- You have a small labeled set in the target language: train a task adapter or LoRA on it, starting from a model already fine-tuned on source data. Few-shot target data usually beats pure zero-shot.
- You serve many languages and tasks from one model: adapters or LoRA keep one base copy in memory and load small files per request. Mind the engineering cost of managing many adapter files.
- You need the lowest latency: use LoRA and merge the weights before deployment.
Common errors
- Forgetting to freeze the base model. Check the trainable-parameter count. If it matches the full model, nothing is frozen.
- Learning rate copied from full fine-tuning. Adapters and LoRA usually need a larger rate, often 1e-4 to 1e-3, because few parameters are doing all the learning.
- Judging with the wrong baseline. Compare the adapter against zero-shot transfer from the same base model, not against a weaker model.
- Reporting only an average. As with any cross-lingual evaluation, report per-language scores, because gains concentrate in a few languages.
- Tokenizer mismatch. An adapter trained with one vocabulary cannot be used with a different tokenizer. If you extend the vocabulary, the new embeddings must travel with the adapter.
Exercise
You trained an NLI task adapter on English with a frozen English language adapter underneath. For Swahili, a teammate suggests also fine-tuning the English language adapter during task training "for better accuracy" and then swapping in the Swahili adapter. Why is this likely to hurt, and what would you do instead?
Show answer
If the English language adapter changes during task training, the task adapter learns to read representations from a modified adapter that no Swahili adapter was trained to reproduce. The swap then feeds the task adapter inputs it has never seen. Keep the language adapter frozen while training the task adapter, so the interface between the two stays fixed, and train the Swahili adapter separately with masked language modeling on Swahili text.
Exercise
A 768 × 768 attention weight matrix gets a LoRA update of rank r = 8. How many trainable parameters does it add, and what fraction of the original matrix's 589,824 parameters is that?
Show answer
LoRA adds two matrices, A of size 8 × 768 and B of size 768 × 8, so 2 × 8 × 768 = 12,288 parameters. That is 12,288 / 589,824, about 2.1% of the matrix.