Simple Algorithm
Deep Learning · Emergence · 26 min

Model Merging & Task Arithmetic

Adding and subtracting fine-tuned weights to combine or remove skills.

Fine-tune one pretrained model on eight tasks and you get eight sets of weights. Add their differences from the original back onto it and a single model does most of all eight jobs; subtract one difference and the model unlearns a behavior. Such arithmetic on the weights of nonlinear networks with millions of parameters has no obvious reason to work. This lesson shows when it does, why, and how merging methods deal with the interference when it does not.

What you’ll learn

  • Define task vectors and use addition, negation and analogies to edit a model, and quote what the experiments achieved.
  • Explain why merging works from a shared pretrained start but fails between independently initialized networks without permutation alignment.
  • Apply TIES-merging and DARE to resolve interference, and show that DARE's rescaling preserves the task vector in expectation.
  • Derive Fisher-weighted averaging from a product of Laplace posteriors and RegMean's closed form for a linear layer.
  • State weight disentanglement and explain why fine-tuning in the tangent space improves task arithmetic.

Merging from a shared start

Model merging combines trained networks by operating on their weights, with no further training. The simplest case, averaging models fine-tuned from the same pretrained weights with different hyperparameters, is a model soup (Wortsman et al., 2022; Weight Averaging: SWA, EMA & Model Soups). Interpolating between a zero-shot CLIP model and its fine-tuned version, (1−α)θzero-shot+αθft(1-\alpha)\boldsymbol\theta_{\text{zero-shot}}+\alpha\boldsymbol\theta_{\text{ft}}, kept the fine-tuned accuracy while recovering much of the zero-shot model's robustness to distribution shift (WiSE-FT; Wortsman et al., 2022).

The ambitious version merges models fine-tuned on different tasks. Write θpre\boldsymbol\theta_{\text{pre}} for the pretrained weights and θt\boldsymbol\theta_t for the weights fine-tuned on task tt. Why would averaging such networks give anything but noise? Because fine-tuning moves them only a little and they stay in one basin: models fine-tuned from the same pretrained checkpoint are close in parameter space and connected by low-loss straight paths (Neyshabur, Sedghi & Zhang, 2020), the linear mode connectivity that Frankle, Dziugaite, Roy & Carbin (2020) found between copies of one network trained onward from a shared, partly trained starting point with different data orders. Networks trained from different random initializations are another matter.

Task arithmetic

Ilharco, Ribeiro, Wortsman, Gururangan, Schmidt, Hajishirzi & Farhadi (2023) treated the change made by fine-tuning as an object of its own. A task vector is τt=θt−θpre\boldsymbol\tau_t=\boldsymbol\theta_t-\boldsymbol\theta_{\text{pre}}, and editing means adding a scaled combination of task vectors to the pretrained weights, with the scale λ\lambda chosen on held-out data:

θnew=θpre+λ∑tτt(addition),θpre−λτ(negation),θpre+λ(τC+τB−τA)(analogy)\boldsymbol\theta_{\text{new}}=\boldsymbol\theta_{\text{pre}}+\lambda\sum_t\boldsymbol\tau_t\quad\text{(addition)},\qquad\boldsymbol\theta_{\text{pre}}-\lambda\boldsymbol\tau\quad\text{(negation)},\qquad\boldsymbol\theta_{\text{pre}}+\lambda\big(\boldsymbol\tau_C+\boldsymbol\tau_B-\boldsymbol\tau_A\big)\quad\text{(analogy)}
This is task arithmetic. All their experiments used task vectors fine-tuned from the same pretrained model, a requirement they list among the limitations.
OperationExperimentResult
NegationGPT-2 Large; task vector from fine-tuning on toxic text, subtractedtoxic generations fell from 4.8% to 0.8%, while perplexity on WikiText-103 rose only from 16.4 to 16.9
NegationCLIP ViT-L/14; task vectors of eight image classification tasksaverage accuracy on the target tasks fell from 64.8% to 19.0%, while ImageNet accuracy moved from 75.5% to 72.9%
AdditionCLIP; sum of task vectors for pairs of tasks, and for all eight98.9% of the specialized models' accuracy for pairs, 91.2% for all eight in one model
AnalogyT5-small; sentiment on Yelp from an Amazon sentiment vector plus (Yelp − Amazon) language-modeling vectorsYelp accuracy rose from 88.6% to 89.9% with no labeled Yelp data, against 91.1% for fine-tuning on Yelp
Accuracies for addition are normalized by those of the individually fine-tuned models.
Check your understanding

You have a pretrained language model and a copy fine-tuned on a corpus of toxic text. How does task arithmetic make the original model less toxic?

  1. Average the two models' weights
  2. Fine-tune the original on non-toxic text instead
  3. Subtract a scaled copy of the difference between the toxic model and the original from the original's weights, with the scale chosen so that behavior on control tasks barely changes
  4. Add the toxic model's weights to the original's
Show the answer

C. Subtract a scaled copy of the difference between the toxic model and the original from the original's weights, with the scale chosen so that behavior on control tasks barely changes

The task vector τ=θtoxic−θpre\boldsymbol\tau=\boldsymbol\theta_{\text{toxic}}-\boldsymbol\theta_{\text{pre}} points toward toxicity; θpre−λτ\boldsymbol\theta_{\text{pre}}-\lambda\boldsymbol\tau moves away from it. On GPT-2 Large this cut toxic generations about sixfold at a cost of half a point of perplexity.

Interference: TIES and DARE

Adding task vectors works for a few tasks and degrades as more are added, because they interfere. Yadav, Tam, Choshen, Raffel & Bansal (2023) identified two sources. Redundant entries, small changes that matter little for their own task, add noise to the others. Sign conflicts, where one task pushes a weight up and another down, cancel each other in a sum. TIES-merging handles both in three steps, applied to every coordinate pp:

  1. Trim. In each task vector keep only the largest-magnitude entries (the top 20% in the paper's default) and set the rest to zero, giving τ^t\hat{\boldsymbol\tau}_t.
  2. Elect. Choose each coordinate's sign by total mass: γp=sign⁡(∑tτ^tp)\gamma^p=\sign\big(\sum_t\hat\tau_t^p\big).
  3. Disjoint merge. Average only the entries that agree with the elected sign, ignoring zeros: τmp=1∣Ap∣∑t∈Apτ^tp\tau^p_m=\frac1{\lvert A^p\rvert}\sum_{t\in A^p}\hat\tau^p_t with Ap={t:sign⁡(τ^tp)=γp}A^p=\{t:\sign(\hat\tau^p_t)=\gamma^p\}, and set θm=θpre+λτm\boldsymbol\theta_m=\boldsymbol\theta_{\text{pre}}+\lambda\boldsymbol\tau_m.

Sign resolution mattered most: replacing the elected signs by those of a model trained on all tasks jointly closed most of the remaining gap to multitask training.

Predict before you look

After trimming, three task vectors have the values +0.5+0.5, +0.2+0.2 and −0.6-0.6 at one coordinate. What is the TIES-merged value τm\tau_m there, before scaling by λ\lambda?

Show the answer

0.35

The total mass is 0.5+0.2−0.6=+0.10.5+0.2-0.6=+0.1, so the elected sign is positive; the disjoint mean of the agreeing entries is (0.5+0.2)/2=0.35(0.5+0.2)/2=0.35. A plain average would give 0.1/3≈0.030.1/3\approx0.03, letting the conflict nearly cancel two tasks' shared push. The third task's preference is overruled at this coordinate, which is the price of resolving the conflict.

DARE (Yu, Yu, Yu, Huang & Li, 2024) attacks redundancy at random. Each entry δi\delta_i of a task vector (the paper's delta parameters) is dropped with probability pp, and the survivors are rescaled so that nothing changes on average:

δ~i=mi1−p δi,mi∼Bernoulli(1−p)⟹E[δ~i]=1−p1−p δi=δi\tilde\delta_i=\frac{m_i}{1-p}\,\delta_i,\quad m_i\sim\text{Bernoulli}(1-p)\qquad\Longrightarrow\qquad\E\big[\tilde\delta_i\big]=\frac{1-p}{1-p}\,\delta_i=\delta_i
For fine-tuned language models, whose delta parameters are tiny, dropping 90% or even 99% of them left the fine-tuned abilities largely intact. Sparsifying each model's deltas before task arithmetic or TIES reduces the overlap between them, and the authors found the benefit of merging larger in larger models.
Think first Each layer's output depends on a sum over many weights. Why does DARE's rescaling keep that output close to the original, not just correct on average?

A pre-activation receives a sum of many small delta contributions ∑iδixi\sum_i\delta_ix_i. After dropping and rescaling, each term is unbiased and the terms are independent, so the sum keeps its mean and its relative fluctuation shrinks as more terms contribute (like averaging many noisy estimates). This works when the deltas are small and spread over many weights, as they are after fine-tuning; it would fail for a single large, important weight, whose loss is not compensated by anything else.

Weighted merging: Fisher and RegMean

Plain averaging treats every coordinate of every model as equally trustworthy. Matena & Raffel (2022) weighted each model's coordinates by how much its own task depends on them, with the same Bayesian reasoning behind elastic weight consolidation (Catastrophic Forgetting & Continual Learning).

DerivationFisher merging as a product of Laplace posteriors
  1. θ⋆=arg max⁡θ∑iλilog⁡p(θ∣Di)≈arg min⁡θ∑iλi∑jFi(j)2(θ(j)−θi(j))2\boldsymbol\theta^\star=\argmax_{\boldsymbol\theta}\sum_i\lambda_i\log p(\boldsymbol\theta\mid\data_i)\approx\argmin_{\boldsymbol\theta}\sum_i\lambda_i\sum_j\frac{F_i^{(j)}}2\big(\theta^{(j)}-\theta_i^{(j)}\big)^2

    Approximate the posterior of each fine-tuned model ii by a Gaussian centered at its weights, with diagonal precision given by its Fisher information FiF_i (a Laplace approximation). Merging asks for the weights that are most probable under all the posteriors at once, with importance weights λi\lambda_i:

  2. θ⋆(j)=∑iλiFi(j)θi(j)∑iλiFi(j)\theta^{\star(j)}=\frac{\sum_i\lambda_iF_i^{(j)}\theta_i^{(j)}}{\sum_i\lambda_iF_i^{(j)}}

    The objective separates over coordinates jj, and each is a weighted least-squares problem. Setting its derivative to zero:

  3. With equal Fisher values this is the plain weighted average, so a model soup is Fisher merging with isotropic posteriors. Where one model's task is sensitive to a coordinate and another's is not, the merge follows the sensitive one.

RegMean (Jin, Ren, Preotiuc-Pietro & Cheng, 2023) is exact for linear layers instead. Let model ii's layer map inputs Xi∈Rni×dinX_i\in\R^{n_i\times d_{\text{in}}} (rows are the inputs it saw on its own task) to outputs XiWiX_iW_i. Choose one merged weight that reproduces every model's outputs on its own inputs as well as possible:

min⁡W∑i∥XiW−XiWi∥F2⟹∑iXi⊤Xi (W−Wi)=0⟹W⋆=(∑iXi⊤Xi)−1∑iXi⊤XiWi\min_W\sum_i\norm{X_iW-X_iW_i}_F^2\quad\Longrightarrow\quad\sum_iX_i^\top X_i\,(W-W_i)=0\quad\Longrightarrow\quad W^\star=\Big(\sum_iX_i^\top X_i\Big)^{-1}\sum_iX_i^\top X_iW_i
Only the Gram matrices Xi⊤XiX_i^\top X_i of each layer's inputs are needed, not the data, hence the paper's title phrase "dataless knowledge fusion". In practice the off-diagonal entries are shrunk toward zero for stability; with diagonal Gram matrices the formula reduces to a per-input-feature weighted average.

Why task arithmetic works

Ortiz-Jiménez, Favero & Frossard (2023) named the property that addition and negation need. A network is weight-disentangled with respect to tasks t=1,…,Tt=1,\dots,T, with input domains Dt\data_t, if adding task vectors changes its function only on each vector's own domain:

f(x; θpre+∑tαtτt)=∑tgt(x;αtτt)+g0(x),gt(x;αtτt)=0  for x∉Dtf\Big(\mathbf x;\ \boldsymbol\theta_{\text{pre}}+\sum_t\alpha_t\boldsymbol\tau_t\Big)=\sum_tg_t(\mathbf x;\alpha_t\boldsymbol\tau_t)+g_0(\mathbf x),\qquad g_t(\mathbf x;\alpha_t\boldsymbol\tau_t)=0\ \text{ for }\mathbf x\notin\data_t
g0g_0 is the network's output away from all the task domains and vanishes on them; there it is the pretrained model's output, which no task vector changes. If this holds, adding τt\boldsymbol\tau_t acts only on task tt's inputs and negating it removes only task tt.

A linear model would make the sum exact, so it is natural to look at the first-order expansion around θpre\boldsymbol\theta_{\text{pre}}, the regime of the neural tangent kernel: flin(x;θ)=f(x;θpre)+(θ−θpre)⊤∇θf(x;θpre)f_{\text{lin}}(\mathbf x;\boldsymbol\theta)=f(\mathbf x;\boldsymbol\theta_{\text{pre}})+(\boldsymbol\theta-\boldsymbol\theta_{\text{pre}})^\top\nabla_{\boldsymbol\theta}f(\mathbf x;\boldsymbol\theta_{\text{pre}}). In it, each task vector contributes τt⊤∇θf(x;θpre)\boldsymbol\tau_t^\top\nabla_{\boldsymbol\theta}f(\mathbf x;\boldsymbol\theta_{\text{pre}}), and the contributions add. Additivity alone is not disentanglement, though: each contribution must also be near zero on the other tasks' inputs.

Their findings, on CLIP models: task arithmetic is not explained by the networks fine-tuning in the linear regime, since ordinary fine-tuning leaves it. Weight disentanglement instead emerges during pretraining, and it is tied to the eigenfunctions of the neural tangent kernel being localized on the different tasks' inputs. And fine-tuning the linearized model, training θ\boldsymbol\theta inside flinf_{\text{lin}} so that the task vectors live in the tangent space, amplified disentanglement and gave substantial gains on task-arithmetic benchmarks, at the cost of somewhat lower single-task accuracy and a more expensive forward pass.

Key takeaways

  • Merging works from a shared pretrained start because fine-tuned models stay in one low-loss basin; independently initialized networks first need their units aligned by a permutation.
  • Task vectors τt=θt−θpre\boldsymbol\tau_t=\boldsymbol\theta_t-\boldsymbol\theta_{\text{pre}} can be added to learn several tasks at once (91% of specialized accuracy for eight CLIP tasks), negated to remove a behavior (toxic generations from 4.8% to 0.8%), and combined into analogies.
  • Interference comes from redundant entries and sign conflicts: TIES trims, elects signs by total mass and averages only agreeing entries; DARE drops most deltas at random and rescales the rest by 1/(1−p)1/(1-p), which preserves them in expectation.
  • Fisher merging, θ⋆(j)=∑iλiFi(j)θi(j)/∑iλiFi(j)\theta^{\star(j)}=\sum_i\lambda_iF_i^{(j)}\theta_i^{(j)}/\sum_i\lambda_iF_i^{(j)}, follows from a product of Laplace posteriors; RegMean solves least squares for each linear layer using only Gram matrices.
  • Task arithmetic relies on weight disentanglement, which emerges in pretraining; fine-tuning in the tangent space strengthens it.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why can models fine-tuned from the same pretrained checkpoint be averaged, while two networks trained from different random initializations usually cannot?

  1. Fine-tuned models have fewer parameters
  2. Fine-tuning moves the weights only a little, keeping the models in one low-loss basin; independent runs settle in different, permutation-shuffled solutions with a high-loss barrier between them
  3. Pretrained models are linear, so any average works
  4. Independently trained networks never reach low loss
Show the answer

B. Fine-tuning moves the weights only a little, keeping the models in one low-loss basin; independent runs settle in different, permutation-shuffled solutions with a high-loss barrier between them

Fine-tuned models from one checkpoint are close in weight space and connected by low-loss straight paths. Independent runs order their hidden units arbitrarily, so their average mixes unrelated units; in the widget, the path between two independent networks had a barrier of 0.7110.711, which aligning the units reduced to 0.0210.021.

Question 2

In TIES-merging, how is the sign of each merged coordinate chosen?

  1. By majority vote, counting how many task vectors are positive
  2. From the first task vector
  3. Always positive
  4. As the sign of the sum of the trimmed task vectors' entries, i.e. the sign with the larger total magnitude
Show the answer

D. As the sign of the sum of the trimmed task vectors' entries, i.e. the sign with the larger total magnitude

γp=sign⁡(∑tτ^tp)\gamma^p=\sign(\sum_t\hat\tau^p_t) weighs each vote by its size, so one large push can outvote two small ones. Then only entries with that sign are averaged.

Question 3

When does Fisher-weighted merging reduce to plain (weighted) averaging of the models' weights?

  1. When all models have the same Fisher information at every coordinate
  2. When the models were trained on the same task
  3. When the Fisher information is zero
  4. Never: it always differs from averaging
Show the answer

A. When all models have the same Fisher information at every coordinate

θ⋆(j)=∑iλiFi(j)θi(j)/∑iλiFi(j)\theta^{\star(j)}=\sum_i\lambda_iF_i^{(j)}\theta_i^{(j)}/\sum_i\lambda_iF_i^{(j)}; if Fi(j)F_i^{(j)} is the same for every model, it cancels and leaves ∑iλiθi(j)/∑iλi\sum_i\lambda_i\theta_i^{(j)}/\sum_i\lambda_i.

Question 4

DARE drops each delta parameter with probability p=0.9p=0.9. By what factor must the surviving deltas be multiplied so that the task vector is unchanged in expectation?

  1. 0.90.9
  2. 0.10.1
  3. 1010
  4. 11: no rescaling is needed
Show the answer

C. 1010

Each delta survives with probability 1−p=0.11-p=0.1, so multiplying survivors by 1/(1−p)=101/(1-p)=10 gives E[δ~i]=0.1×10 δi=δi\E[\tilde\delta_i]=0.1\times10\,\delta_i=\delta_i.

Further reading

  • G. Ilharco, M. T. Ribeiro, M. Wortsman, S. Gururangan, L. Schmidt, H. Hajishirzi & A. Farhadi, "Editing models with task arithmetic," ICLR (2023).
  • P. Yadav, D. Tam, L. Choshen, C. Raffel & M. Bansal, "TIES-Merging: resolving interference when merging models," NeurIPS (2023).
  • M. Matena & C. Raffel, "Merging models with Fisher-weighted averaging," NeurIPS (2022).
  • G. Ortiz-Jiménez, A. Favero & P. Frossard, "Task arithmetic in the tangent space: improved editing of pre-trained models," NeurIPS (2023).
  • L. Yu, B. Yu, H. Yu, F. Huang & Y. Li, "Language models are Super Mario: absorbing abilities from homologous models as a free lunch," ICML (2024).