Model merging: coordinates matter before weights are averaged
模型合并
Break an equivalent two-unit network by averaging, then inspect task vectors and TIES.
model-mergingTwo correct networks average to zero
One two-unit network computes ReLU(x)+ReLU(−x), which is |x|. Another swaps its hidden units and computes exactly the same function. Average their hidden weights coordinate by coordinate: both become zero. The merged network now outputs zero for every input. Averaging predictions would have kept |x|.
This original counterexample explains why model merging needs compatible parameter coordinates. Equal architecture and equal behavior are not sufficient. A shared initialization helps maintain correspondence, but does not guarantee that all fine-tuning directions can be combined without damage. Model soups studies averaging models fine-tuned from a common pretrained model, including validation-based selection. Its inference-cost claim concerns the resulting single model, not the cost of creating all candidate models. Model soups
From weights to task differences
For nonnegative mixture weights summing to one, parameter averaging and output ensembling are different operations. A nonlinear model need not commute with the average:
If models share base parameters theta_0, define a task vector as a fine-tuned parameter difference. Task arithmetic combines such differences with chosen scales; useful behavior must be evaluated rather than inferred from the name “arithmetic.” Task arithmetic
Different tasks can push the same coordinate in opposite directions. The TIES method trims small updates, elects a sign from the sum of retained updates, and averages only nonzero updates agreeing with that sign. Our implementation keeps the largest ceil(rD) absolute coordinates per task for fraction r and dimension D; magnitude ties use coordinate order. This makes the finite example deterministic. TIES v1
Define A_j as the indices with nonzero retained updates of the elected sign. Average those entries; if the set is empty, use zero. Our zero-sum sign convention elects zero and accepts no nonzero updates.
The final update is lambda times delta. Sign election is magnitude-sensitive: updates 3,−1,−1 elect positive, although two of three signs are negative. Including trimmed zeros in the denominator would implement a different algorithm.
There is no guarantee that this recipe minimizes every downstream loss. For authored target vectors t_i and squared distance averaged over coordinates and tasks, write their mean as bar t. Expanding the square cancels the centered cross term:
Thus uniform averaging is already optimal for this particular quadratic objective. TIES can be useful under other objectives without improving this one. A merging rule and an evaluation objective are separate choices.
Check alignment, then check the objective
Run with Python 3.12 and NumPy 1.26.4. The first experiment evaluates nine scalar inputs from −2 to 2. The second uses three explicitly listed six-dimensional task vectors, a 50% keep fraction and scale one. These are invented vectors, not downloaded model checkpoints.
"""Parameter alignment and signed task-vector merging in original finite models."""
import json,math
import numpy as np
def relu_model(x,hidden,output):
x=np.asarray(x,dtype=float);hidden=np.asarray(hidden,dtype=float);output=np.asarray(output,dtype=float)
if x.ndim!=1 or hidden.shape!=(2,) or output.shape!=(2,) or not all(np.isfinite(v).all() for v in [x,hidden,output]):raise ValueError('finite scalar inputs and two hidden units required')
return np.maximum(x[:,None]*hidden[None,:],0)@output
def trim(vectors,keep):
d=np.asarray(vectors,dtype=float)
if d.ndim!=2 or not d.size or d.shape[0]>20 or d.shape[1]>100 or not np.isfinite(d).all():raise ValueError('bounded nonempty task-vector matrix required')
if isinstance(keep,bool) or not math.isfinite(keep) or not 0<=keep<=1:raise ValueError('keep fraction in[0,1] required')
out=np.zeros_like(d);count=math.ceil(keep*d.shape[1])
if count:
for i,row in enumerate(d):
chosen=np.argsort(-np.abs(row),kind='stable')[:count];out[i,chosen]=row[chosen]
return out
def ties(vectors,keep=.5,scale=1.0):
if isinstance(scale,bool) or not math.isfinite(scale) or not 0<=scale<=2:raise ValueError('scale in[0,2] required')
d=trim(vectors,keep);sign=np.sign(d.sum(axis=0));aligned=(np.sign(d)==sign[None,:])&(d!=0)
counts=aligned.sum(axis=0);summed=np.where(aligned,d,0).sum(axis=0)
mean=np.divide(summed,counts,out=np.zeros_like(summed),where=counts>0)
return dict(trimmed=d.tolist(),elected_sign=sign.tolist(),matching_counts=counts.tolist(),delta=(scale*mean).tolist())
def average_task_loss(weight,targets):
w=np.asarray(weight,dtype=float);t=np.asarray(targets,dtype=float)
if t.ndim!=2 or not t.size or w.shape!=(t.shape[1],) or not np.isfinite(w).all() or not np.isfinite(t).all():raise ValueError('finite vector and aligned target matrix required')
return float(np.mean((t-w)**2))
def demo():
x=np.linspace(-2,2,9);ha=np.array([1.,-1.]);hb=ha[::-1];out=np.ones(2)
ya=relu_model(x,ha,out);yb=relu_model(x,hb,out)
naive=relu_model(x,(ha+hb)/2,out);aligned=relu_model(x,(ha+hb[::-1])/2,out)
vectors=np.array([[.8,.1,-.5,0,.7,-.2],[.7,-.6,-.4,.2,-.6,.1],[-.1,-.5,-.2,.1,.5,-.9]])
mean=vectors.mean(axis=0);merged=ties(vectors);delta=np.array(merged['delta'])
return dict(x=x.tolist(),model_a=ya.tolist(),model_b=yb.tolist(),output_ensemble=((ya+yb)/2).tolist(),naive_parameter_mean=naive.tolist(),aligned_parameter_mean=aligned.tolist(),naive_mse=float(np.mean((naive-ya)**2)),aligned_mse=float(np.mean((aligned-ya)**2)),task_vectors=vectors.tolist(),uniform_delta=mean.tolist(),ties=merged,quadratic_losses=dict(uniform=average_task_loss(mean,vectors),ties=average_task_loss(delta,vectors)),scale_curve=[dict(scale=float(s),loss=average_task_loss(ties(vectors,scale=s)['delta'],vectors)) for s in np.linspace(0,2,9)],scope='Two-unit ReLU identity and three authored vector targets; not pretrained LLM checkpoints or benchmark results.')
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
The two original networks and their output ensemble agree on |x|. Naive parameter averaging has mean squared error 5/3 on the nine inputs. Undoing the known permutation before averaging gives zero error. We provide the permutation; the program does not solve general neuron alignment.
TIES produces the update [0.75,−0.55,−0.5,0,0.6,−0.9]. Its average coordinate-squared loss against the three targets is about 0.236389, versus 0.130370 for the uniform mean. The scale curve changes lambda while retaining the same updates; it is a diagnostic on authored targets, not held-out validation performance.
Sorting magnitudes costs O(KD log D) for K task vectors of dimension D; sign election and averaging cost O(KD). The implementation stores O(KD) values. Merged inference uses one parameter array. Output ensembling normally evaluates multiple models; merging still requires obtaining, loading and checking the source weights.
A useful merge needs a validation plan
A practical baseline is the best individual model under a declared task mixture. Compare it with uniform averaging, a candidate-selection method and the proposed merge. Model soups’ greedy procedure orders candidates by validation performance and accepts an addition when the validation score improves; final evaluation needs untouched data. Repeated choices of keep fraction, scale or task weights also spend validation information. Selection procedure
For language models, verify base checkpoint identity, parameter naming, architecture, tokenizer behavior and any adapter-to-weight conversion before combining values. Equal tensor shapes alone do not prove compatibility. Report per-task regressions, retention of base capabilities, memory and latency; a global average can conceal a lost task. If merging fails, retain separate models with routing or use output ensembling when its cost is acceptable. Distillation is another route, but needs training and its own targets. See LLM distillation.
Predict the merged behavior
- Why does swapping hidden units preserve the network but break naive averaging?
Answer: The sum of the two ReLU contributions is unchanged by permutation. Coordinate-wise averaging pairs opposite hidden weights, producing two zero units.
- Which sign wins for retained updates 3,−1,−1, and what is their disjoint mean?
Answer: Their sum is 1, so positive wins. Only 3 agrees, giving mean 3; this is not a majority vote.
- What happens when retained updates are 2 and −2 in one coordinate?
Answer: The sum and elected sign are zero. Under our declared convention no nonzero update matches; the merged coordinate is zero, with no division by an empty count.
- A merge improves a weighted average but damages one essential task. Is the aggregate sufficient for release?
Answer: No. Apply the task’s minimum acceptance constraint and inspect its cases. Change selection or retain a separate model; do not hide the regression by changing the reported mixture after seeing results.
Three different merging questions
Model soups asks when weight averaging among related fine-tunes works. Task arithmetic uses differences from a common base. TIES addresses interference among those updates. The finite ReLU counterexample and quadratic loss comparison are original teaching experiments; they neither reproduce nor refute the papers’ reported benchmark results.
Make a prediction, then check
Must two functionally identical networks have a useful parameter average?
Learning objectives
- Distinguish output ensembles, parameter averaging and signed task-vector merging.
- Run the original finite experiment and explain its counterexample and scope.
Prerequisites & connections
Explore related knowledge →References
- Model soups: averaging weights of multiple fine-tuned models improves accuracy without increasing inference time — v1
Mitchell Wortsman; Gabriel Ilharco; Samir Yitzhak Gadre and coauthors · 2022 - Editing Models with Task Arithmetic — v1
Gabriel Ilharco; Marco Tulio Ribeiro; Mitchell Wortsman; Suchin Gururangan; Ludwig Schmidt; Hannaneh Hajishirzi; Ali Farhadi · 2022 - Resolving Interference When Merging Models — v1
Prateek Yadav; Derek Tam; Leshem Choshen; Colin Raffel; Mohit Bansal · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Viewed PDF3: shared pretrained initialization, uniform/greedy/learned soups and validation-based selection. Viewed PDF2: task vectors relative to a common initialization; validation scale and empirical scope. Viewed PDF5: trim, sign of summed updates and disjoint mean; preserve original v1 title. 5 paired equations and four explained exercises. Permutation collapse, independent quadratic identity, TIES magnitude sign election, nonzero denominator, ties and zero-sum convention checked.
- Permutation collapse, independent quadratic identity, TIES magnitude sign election, nonzero denominator, ties and zero-sum convention checked.
- Four computed SVG variants per topic;11 numeric/geometry tests and36 responsive cases passed. Twelve selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- Model soups: averaging weights of multiple fine-tuned models improves accuracy without increasing inference time — v1 · Viewed PDF3: shared pretrained initialization, uniform/greedy/learned soups and validation-based selection.
- Editing Models with Task Arithmetic — v1 · Viewed PDF2: task vectors relative to a common initialization; validation scale and empirical scope.
- Resolving Interference When Merging Models — v1 · Viewed PDF5: trim, sign of summed updates and disjoint mean; preserve original v1 title.
Related topics