MergeKit: merge methods, YAML recipes, frankenmerges, MoE merges and evolutionary merging
Read first: Model soups: averaging fine-tuned weights, and why merging works · TIES-Merging: Task Vectors, Interference, TIES and DARE
TL;DR. MergeKit is the open-source toolkit behind most community LLM merges. You write a YAML recipe: input models, a merge method, and parameters that can vary by tensor name and by layer depth. The planner turns it into a graph of small per-tensor tasks, so each output tensor is computed from the matching input tensors, written to disk and freed. That is why a 70B merge can run on a CPU or with 8 GB of VRAM. Besides weight averaging (linear, SLERP, and the task-vector family: TIES, DARE, DELLA, Breadcrumbs, SCE), it can stack layers from several models (“frankenmerges”, the first step of SOLAR 10.7B’s depth up-scaling), build a Mixtral-style mixture of experts (MoE) from dense fine-tunes with prompt-initialised routers, extract a LoRA from a fine-tune, chain merges, and search merge parameters with an evolutionary algorithm, after Sakana’s evolutionary model merging.
Why it matters for you. Merging is now a standard, nearly free step in post-training recipes, including for retrievers: Qwen3 Embedding merges checkpoints with SLERP. When a paper says “we SLERP-merged checkpoints” or “TIES with density 0.5”, this page tells you exactly what happened to each tensor and which knobs were chosen.
Sources. The MergeKit paper (EMNLP 2024 Industry), the repo README and its docs/ folder (method guide, moe.md, evolve.md, multimerge.md), with code statements checked against commit 0f1423e (main in November 2026), SOLAR 10.7B (NAACL 2024 Industry), and Evolutionary Optimization of Model Merging Recipes (Akiba et al., Sakana AI; Nature Machine Intelligence, January 2025).
First read. First pass: the tensor pipeline (“What the code does to a tensor”) → “SLERP by hand” → “Tokenizers”. Then choose one extension: layer stacking, prompt-routed MoE, or evolutionary search. The complete method catalog and the YAML are reference material, not prerequisites for understanding a reported merge. The math of TIES and DARE is covered on the task arithmetic, TIES & DARE page; this page shows how MergeKit’s code departs from it (defaults, mask granularity, where weights enter, L1 rescaling).
Key idea: what the code does to a tensor
Section titled “Key idea: what the code does to a tensor”Plain words first. A Hugging Face checkpoint is a dictionary from tensor names (such as model.layers.12.self_attn.q_proj.weight) to arrays. If several models share an architecture, every name exists in all of them with the same shape. A merge is then a function applied name by name: take tensor with the same name from each model (and if the method needs one), and produce one output tensor.
The pipeline, as implemented:
- Plan (
plan.py). For each output tensor, create a task that names its input tensors, the merge method, and the parameter values resolved for that tensor. Embeddings come first, then each layer slice, then the final norm and LM head. - Resolve parameters (
parameter_resolver.py,config.py). A parameter such astorweightcan be a scalar, a list (a gradient), or a list offilter/valuepairs. A filter is a plain substring test on the tensor name ("mlp"matches...layers.3.mlp.down_proj.weight). Precedence goes from most to least specific: slice source, output slice, per-model, global. - Load lazily (
io/lazy_tensor_loader.py). Only the requested tensor is read from its safetensors shard. - Execute (
graph.py). The paper describes the merge as a directed acyclic graph of tasks, scheduled “such that the working set needed at any given time is minimized”. The executor records each result’s last use and deletes it after that point.
The working set is roughly (number of inputs) × (largest tensor), not (number of inputs) × (model size). For Mistral-7B the largest tensor is the 32000 × 4096 embedding, ≈ 262 MB in bf16, so a three-model merge needs on the order of a gigabyte at a time. This is how MergeKit can run “entirely on CPU or accelerated with as little as 8 GB of VRAM” (README).
Gradients across layers. For a slice of layers, layer gets the normalised position ; for the code uses . A list of numeric values is spread evenly over and linearly interpolated: with , , and fractional part ,
Worked example (the repo’s gradient-slerp.yml, 40 layers): self_attn: [0, 0.5, 0.3, 0.7, 1] and mlp: [1, 0.5, 0.7, 0.3, 0].
| Layer | attention | MLP | ||
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 1 |
| 10 | 0.256 | 1.026 | 0.5 + 0.026 × (0.3 − 0.5) ≈ 0.495 | 0.505 |
| 20 | 0.513 | 2.051 | 0.3 + 0.051 × 0.4 ≈ 0.321 | 0.679 |
| 30 | 0.769 | 3.077 | 0.7 + 0.077 × 0.3 ≈ 0.723 | 0.277 |
| 39 | 1 | 4 | 1 | 0 |
The two lists sum to 1 at every point, so attention takes mostly from one parent where the MLP takes mostly from the other. Tensors matching neither filter fall back to value: 0.5. Positions restart in each slice, so splitting the same 40 layers into two slices changes the schedule.
Precision. Linear and SLERP compute in float32 for 16-bit inputs, then cast back. A normalised linear merge whose weights sum to zero produces NaN or infinity (README).
The merge methods in the current README
Section titled “The merge methods in the current README”# is the number of main input models; Base means base_model is required (✓), optional (*) or unused (−). A task vector is , the change fine-tuning made ( is the of the sibling pages). In the table, is model ‘s sparsification mask and the global lambda (default 1).
What base_model means depends on the method. For slerp it names one of the two interpolation endpoints ( returns it), not a third pretrained ancestor. For task arithmetic, TIES and DARE it is the reference subtracted to form deltas. For nuslerp with a base, the two endpoints are interpolated as task vectors plus a distinct reference base. The # column counts main inputs only, so include the extra reference model when budgeting memory.
Method (value) | What it does to each tensor | Key knobs | # | Base |
|---|---|---|---|---|
linear | (model soups) | weight, normalize | ≥2 | − |
slerp | spherical interpolation of the two flattened raw tensors (below) | t | 2 | ✓ |
nuslerp | SLERP with weights; with a base, SLERPs the two task vectors; optional row/column-wise | weight, nuslerp_flatten, nuslerp_row_wise | 2 | * |
task_arithmetic | (no normalisation by default) | weight, lambda | ≥2 | ✓ |
ties | keep the top-density magnitudes of each tensor of each task vector, weight, elect a sign per entry, divide by the agreeing weights | weight, density | ≥2 | ✓ |
dare_linear, dare_ties | per-entry Bernoulli keep with rate density, L1 rescale (below); dare_ties adds sign election | weight, density, rescale | ≥2 | ✓ |
passthrough | copy one input tensor unchanged, optionally multiplied by scale | scale | 1 | − |
Implementation details that change the algebra. These are where MergeKit’s code differs from the papers and from PEFT; the canonical equations are on the task arithmetic, TIES & DARE page.
- Where weights enter. For the task-vector family,
merge_methods/generalized_task_arithmetic.pysparsifies each delta, multiplies it by itsweight, elects each entry’s sign from the sum of the weighted deltas (ties go positive), and, withnormalize, divides by the sum of the weights of the models that agree with that sign. PEFT’stiesinstead elects signs on the unweighted pruned deltas, applies the weights afterwards, and divides by the number of agreeing entries. Both are faithful to their own code, but with unequal weights the sameweightvalues give different merges. - Defaults change the algebra. At the pinned revision
ties(anddella) default tonormalize: true, buttask_arithmetic,dare_linearanddare_tiesdefault tofalse. Sodare_tiesis not automatically the same disjoint-mean rule asties: it sums the agreeing weighted deltas. With normalisation on, multiplying every positive weight by the same constant cancels between numerator and denominator; use the globallambdato scale the merged delta. - Mask granularity. The TIES paper trims over the whole model at once. MergeKit’s magnitude trims (
ties,breadcrumbs) keep aboutdensity × numelentries per tensor, DELLA ranks magnitudes within each row, and DARE draws an independent Bernoulli keep per entry. - L1 rescaling is not DARE’s fixed . With
rescale: true(the default fordare_*anddella*),sparsify.pymultiplies a nonempty masked tensor by the ratio of its original to its surviving L1 norm. This is not the paper’s fixed multiplier and does not in general preserve each delta coordinate in expectation, so DARE’s exact fixed-input expectation argument does not apply. For a large tensor whose surviving L1 mass concentrates neardensitytimes the original, the two multipliers are approximately equal. A tensor whose original or surviving L1 norm is below (e.g. everything dropped) is returned without rescaling. MergeKit’s DELLA likewise restores the L1 norm instead of using the paper’s per-entry inverse keep probabilities.
Tiny check. Delta , density 0.5. The four equally likely masks give, after L1 rescaling, , , and : mean , not . The paper’s fixed gives , , , : mean exactly .
The guide’s advice: start with linear, nuslerp or task_arithmetic, then try ties, dare_ties or della when many models interfere. It also says method choice “is often more art than science”.
Optional method catalog
Section titled “Optional method catalog”Reference only; none of these rows is needed to follow the rest of the page.
Method (value) | What it does to each tensor | Key knobs | # | Base |
|---|---|---|---|---|
multislerp | barycentric SLERP for more than two models | weight | ≥2 | * |
karcher | Riemannian (Karcher/Fréchet) mean, iterative | max_iter, tol | ≥2 | − |
della, della_linear | like DARE but keep probability rises with magnitude within a row: density ± epsilon | density, epsilon | ≥2 | ✓ |
breadcrumbs, breadcrumbs_ties | drop the largest gamma fraction and the smallest, keep the middle | density, gamma | ≥2 | ✓ |
sce | keep high-variance positions across models (select_topk), weight each matrix by its mean squared task vector, TIES sign election | select_topk | ≥2 | ✓ |
model_stock | interpolate base ↔ average of fine-tunes, with from the pairwise cosines of their task vectors | filter_wise | ≥3 | ✓ |
nearswap | per entry, weight : take the other model only where values are already close | t | 2 | ✓ |
arcee_fusion | importance from absolute parameter differences times a KL-like divergence between softmax-normalised parameter rows; dynamic threshold; fuse masked changes | none | 2 | ✓ |
The method guide also lists RAM (ram, ramplus_tl, arXiv 2601.13572), designed for RL-trained agents whose task vectors are sparse. In ram, changes above epsilon contributed by one model are kept intact, while changes contributed by several models are averaged over the contributors. ramplus_tl additionally scales each model’s unique changes using its shared-to-unique count ratio within the tensor, controlled by r and alpha.
SLERP by hand: why it preserves the norm
Section titled “SLERP by hand: why it preserves the norm”Plain words. Averaging two vectors that point in different directions partly cancels them, so the midpoint is shorter than either. Spherical linear interpolation (SLERP), borrowed from animating rotations (Shoemake, 1985), walks along the arc between the two directions at constant angular speed. When both vectors have the same length, it keeps that length.
With :
2-D example. , , both unit length, , .
| norm | angle from | norm | angle | |||
|---|---|---|---|---|---|---|
| LERP | (0.800, 0.400) | 0.894 | 26.6° | (0.900, 0.200) | 0.922 | 12.5° |
| SLERP | (0.894, 0.447) | 1.000 | 26.6° | (0.973, 0.230) | 1.000 | 13.3° = θ/4 |
At both coefficients are , so SLERP is LERP stretched back to unit length. In general, for unit vectors, .
What MergeKit actually does (merge_methods/slerp.py). It flattens each whole tensor, computes one angle per tensor, applies the two coefficients to the raw tensors, and falls back to LERP when . That threshold matters. Two fine-tunes of one base are and , and if the task vectors are small next to , their cosine is close to 1. At cosine 0.9995 the LERP midpoint is shorter by only 0.01% (); at cosine 0.9 it would be 2.5%. So for sibling fine-tunes, SLERP and LERP give nearly the same model. The paper’s own medical merge agrees: LERP and SLERP rows are within about half a point everywhere (table below). The paper’s justification, a spherical path “with a lower loss barrier”, is an intuition here rather than a measured result. nuslerp with a base model applies SLERP to the task vectors instead, where the angle can be much larger.
Frankenmerges and depth up-scaling
Section titled “Frankenmerges and depth up-scaling”passthrough with slices copies whole layer ranges from different models into a deeper model, without combining any parameters. The repo’s example takes layers [0, 24) of one Llama-2-13B fine-tune and [20, 40) of another to build a 44-layer model. At about 317M parameters per 13B layer, the 4 extra layers add ≈ 1.3B. The paper credits this “FrankenMerging” for Goliath-120b and as “the first step” of depth up-scaling.
SOLAR’s depth up-scaling (DUS). Start from an -layer base (Mistral-7B weights in a Llama-2 architecture, ). Duplicate it, drop the last layers from one copy and the first from the other, and concatenate them: layers. With , : base layers 0–23 followed by layers 8–31.
- Parameter check. Per layer: attention M (8 KV heads), MLP M. That is 218.1M per layer, and × 48 ≈ 10.47B. Embeddings and head add B, giving ≈ 10.7B.
- Why drop 2m middle layers rather than repeat all 32? Plain repetition joins layer 31 directly to layer 0, the largest possible “layer distance” at the seam. DUS joins layer 23 to layer 8 instead. The authors argue this smaller discrepancy is what lets continued pretraining recover quickly.
- It is not training-free. The stacked model “initially drops below” the base, and SOLAR continues pretraining before instruction tuning and alignment. The released SOLAR-10.7B-Instruct reached an H6 average of 74.20 against 72.62 for Mixtral-8x7B-Instruct (SOLAR Table 2). Continued pretraining is essential to this result, since the freshly stacked model starts below its base, but the paper does not quantify how much of the final H6 gain comes separately from stacking, continued pretraining, SFT, alignment and the final averaging.
- Merging inside SOLAR. The final model is itself an average of two DPO candidates. The four merges tried, three weightings and one SLERP, score 74.00, 73.93, 74.05 and 73.96 H6 (Table 7).
IR analogy. A frankenmerge is like concatenating two rankers’ feature pipelines without retraining the scorer on top: each block expects the input distribution of its own model, and the seam is where that assumption breaks.
MoE from dense models (mergekit-moe)
Section titled “MoE from dense models (mergekit-moe)”mergekit-moe builds a Mixtral, DeepSeek-MoE or Qwen-MoE checkpoint. Self-attention and norms come from one base_model; each expert’s MLP comes from a different fine-tune (of the same base). Only the router (gate) is new. Gate modes:
hidden(default). For each expert, run itspositive_promptsthrough the base model and collect the block-input residual states (output.hidden_states[:-1]inmoe/router.py).hidden(orhidden_last) uses the last token andhidden_avga padding-masked mean over tokens. Average over prompts, subtract the same fornegative_prompts, and L2-normalise. That unit vector becomes the expert’s router row for that layer.cheap_embed: the same idea with raw token embeddings, one vector for all layers. “Distinctly less effective”.random: for sparse upcycling, where you train afterwards.docs/moe.mdsays thehiddenandcheap_embedoutputs are usable without further training, whilerandomis meant for a model you will train.
What the router then computes. For a token with hidden state at layer , the logit for expert is , and the top experts_per_token (default 2) are used. This is nearest-prototype routing. In IR terms it is Rocchio relevance feedback: positive centroid minus negative centroid, then route each token to the closest “query profile”. MergeKit warns when a layer’s gate matrix is badly conditioned (condition number above 5), meaning the prototypes are nearly collinear and cannot separate the experts.
Where the prototypes come from versus where they are used. A Mixtral router does not see the block input: it receives the residual state after attention, the residual add and post_attention_layernorm. Both have the hidden width and related residual coordinates, but they are not the same activations or distribution, so prompt initialisation is a useful heuristic, not exact nearest-centroid fitting on router inputs.
The rest of the forward pass. In a Mixtral output, a softmax turns the logits into weights, top-k selects the experts, the selected weights are renormalised to sum to one, and the chosen experts’ MLP outputs are summed with those weights. The query for the prototype match is one token’s router-input state, not the whole request.
Cost arithmetic (four Mistral-7B experts, top-2). The MLPs are 32 × 176.2M ≈ 5.64B per expert. Total ≈ 4 × 5.64 + 1.34 (attention) + 0.26 (embeddings and head) ≈ 24.2B parameters; active per token ≈ 2 × 5.64 + 1.60 ≈ 12.9B. The same shapes give Mixtral’s 47B/13B with eight experts (see Mixtral). You pay memory for every expert, while routing is per token, not per request, so a “medical expert” will not handle a whole medical question by itself.
Evolutionary merging (Sakana) and mergekit-evolve
Section titled “Evolutionary merging (Sakana) and mergekit-evolve”Akiba et al. treat the merge recipe as the thing to optimise, with a black-box evolutionary search (CMA-ES, a method that adapts a Gaussian over parameters from the scores of sampled candidates) scoring each candidate merge on a task.
- Parameter space (PS). TIES+DARE density and weight for each layer, including the embeddings, searched for three Mistral-7B fine-tunes: a Japanese LLM and two English math LLMs. Fitness is accuracy on 1,069 Japanese-translated GSM8K test problems that do not overlap the MGSM test set; 1,000 trials.
- Data-flow space (DFS). Weights stay frozen; the search chooses one fixed layer sequence, used for every token, possibly hopping across models. DFS is static architecture search, not a token-dependent router like MoE. The naive space is . Instead, all layers of the two models are laid out times and an indicator array of bits switches each slot on or off (). A matrix scales the input when a hop goes from layer to layer . The motivation: even swapping two neighbouring layers hurts, so a layer fed another model’s activations needs recalibration. Model A’s tokenizer, embeddings and first and last layers are fixed.
| Model (MGSM-JA zero-shot pass@1: correct numerical answer and Japanese reasoning text) | Size | Score |
|---|---|---|
| Japanese LLM / WizardMath / Abel (sources) | 7B | 9.6 / 18.4 / 30.0 |
| PS merge of all three | 7B | 52.0 |
| DFS merge (Abel + Japanese LLM) | 10B | 36.4 |
| PS merge, then DFS with the Japanese LLM | 10B | 55.2 |
These scores are not numerical-answer accuracy alone: the authors take the last number in the output and use fastText to check that the reasoning is in Japanese, which partly explains the English math models’ low scores.
PS does most of the work; DFS adds a few points at the cost of 3B more parameters, and its JP-LMEH general Japanese score falls (53.2 for DFS alone, 66.2 for PS+DFS versus 70.5 for PS).
Is W needed? The paper’s separate 13B-source study (Table 4) has a no-W run: PS+DFS without W scores 26.4 MGSM-JA (19B output) against 34.0 with W (21B output), and below the 31.2 of its PS source. That supports seam scaling, but it is not a fixed-architecture ablation, because the searched output depths differ.
mergekit-evolve implements the parameter-space part only. A genome lists the models, a method (linear, slerp, task_arithmetic, ties or dare_ties), and layer_granularity: one parameter set per block of that many layers. smooth interpolates across blocks, and filters split attention from MLP, which triples the search space. Fitness is a weighted sum of lm-evaluation-harness tasks. The default budget is 100 merge evaluations (--max-fevals), and --in-memory updates a resident vLLM model instead of writing each candidate to disk. The docs nudge users to define custom tasks, not built-in ones (“don’t be naughty”), which is the overfitting risk discussed below.
Tokenizers, chat templates and the rest of the toolbox
Section titled “Tokenizers, chat templates and the rest of the toolbox”Why vocabulary mismatch matters. An embedding matrix (and the LM head) is indexed by token ID. Merging takes “row 32001 of model A” and “row 32001 of model B”, so if that ID means <|im_start|> in one model and nothing (or another token) in the other, you average unrelated vectors. MergeKit therefore aligns vocabularies by token string before merging:
tokenizer.source:union(default when configured),base, or a model path.- A model missing a token gets a filled-in row: the base model’s row if the base has the token; otherwise the row of the only model that has it; otherwise the average of the available rows. The merge method then combines the per-model rows.
- Per-token overrides: take a token from a named model,
forceit for all inputs, map it to another token’s row, or use zeros. - Without any tokenizer setting, different vocabulary sizes are an error.
--unsafe-truncate-embeddingsjust drops trailing rows and checks no IDs. chat_template:auto(most common among inputs), a built-in (alpaca,chatml,llama3,mistral,exaone) or a Jinja string. Merging a ChatML model with a Llama-3-format model creates a model that half-knows both formats; pick one and test it.
For models with different tokenizers, mergekit-tokensurgeon transplants a tokenizer (e.g. to build speculative-decoding drafts).
Other tools. mergekit-extract-lora takes the SVD of each task vector , keeps the top singular values (default --max-rank 128), and writes and as a PEFT adapter: the best rank- approximation of the fine-tune (see LoRA). mergekit-multi runs several named merges from one YAML file in dependency order, caching intermediates. mergekit-pytorch applies the methods to raw PyTorch checkpoints.
What the numbers say
Section titled “What the numbers say”The paper’s only experiment merges Meditron-7B (medical continued pretraining of Llama-2-7B) with Llama-2-7B-Chat (Table 1):
| Model | USMLE | MedMCQA | PubMedQA | ARC-C | HellaSwag | MMLU |
|---|---|---|---|---|---|---|
| Llama2-7B-Chat | 35.90 | 35.45 | 73.40 | 44.20 | 55.40 | 46.37 |
| Meditron-7B | 38.40 | 24.07 | 71.40 | 40.20 | 54.50 | 33.06 |
| LERP merge | 39.10 | 36.65 | 75.60 | 46.76 | 58.66 | 48.44 |
| SLERP merge | 39.20 | 36.91 | 75.60 | 46.84 | 58.67 | 47.97 |
| TIES merge | 38.73 | 32.27 | 75.60 | 45.05 | 58.23 | 45.03 |
| DARE-TIES merge | 36.37 | 27.56 | 72.20 | 42.92 | 54.79 | 41.17 |
- Merges beat both parents on most columns; LERP and SLERP beat the chat model on all three general benchmarks.
- LERP ≈ SLERP, as the threshold analysis above predicts for siblings.
- Sparsifying methods did worse here, perhaps because there are only two models and little interference to resolve, though hyperparameters are not reported.
- No variance, seeds or merge hyperparameters are given, so differences under a point are not interpretable.
Caveats / What to be careful about
Section titled “Caveats / What to be careful about”- It is a systems paper. Its contribution is the toolkit and a taxonomy, not evidence about which method is best. The method guide says as much.
- The 2024 leaderboard merge craze. The Sakana paper notes that the Open LLM Leaderboard “is now dominated by merged models”. Its maintainers began auto-flagging merges because “some users removed the merge tag from their model’s metadata to appear in the main view of the leaderboard” (discussion #510, January 2024). A community post (#544) traced how one model suspected of GSM8K contamination was merged into many descendants. Two mechanisms are at work. Inheritance: a merge can retain contaminated behaviour from a contributing parent, to a degree that depends on the method and weights (the #544 thread is a community suspicion, not independent proof). Selection: choosing among many recipes by the same six public benchmarks (the H6 suite) is adaptive overfitting to the test set; SOLAR’s four candidate merges span 0.12 H6 points, too small to rank reliably without uncertainty estimates. See contamination.
- Shared initialisation is assumed. Merging independently trained models needs permutation alignment (Git Re-Basin, ZipIt, OT fusion), which the paper lists as future work.
- Separate the recovery requirements. SOLAR stacks weights and then trains. Sakana optimises a fixed path and seam scales against task data. Prompt-initialised MergeKit MoEs are intended to be usable without gradient training, although they still need held-out evaluation; random-gate sparse upcycling is intended to be trained. Treat zero-training claims for stacked models with suspicion until evaluated on held-out tasks.
- Code moves fast. Method defaults (e.g. DARE’s L1-norm rescaling, which is a different estimator from the paper’s fixed ) differ from the original papers and change between releases. Record the MergeKit commit with any merge you report.
If you want to try it (optional)
Section titled “If you want to try it (optional)”Install with pip install -e . from the repo, then run mergekit-yaml config.yml ./out [--cuda]. Two configs from the repo’s examples/, shortened:
# gradient-slerp.yml: layer-varying SLERP between two Llama-2-13B fine-tunesslices: - sources: - model: psmathur/orca_mini_v3_13b layer_range: [0, 40] - model: garage-bAInd/Platypus2-13B layer_range: [0, 40]merge_method: slerpbase_model: psmathur/orca_mini_v3_13bparameters: t: - filter: self_attn value: [0, 0.5, 0.3, 0.7, 1] - filter: mlp value: [1, 0.5, 0.7, 0.3, 0] - value: 0.5dtype: float16# orcamini-platy-44layer.yml: a 44-layer frankenmerge by passthroughslices: - sources: - model: psmathur/orca_mini_v3_13b layer_range: [0, 24] - sources: - model: garage-bAInd/Platypus2-13B layer_range: [20, 40]merge_method: passthroughdtype: float16Connections
Section titled “Connections”- Why merging works at all: model soups & weight averaging (the
linearmethod) and task arithmetic, TIES & DARE (the math behind most rows of the method table). - Where it is used: merging in practice covers post-training and retriever recipes. Qwen3 Embedding SLERP-merges checkpoints (worth ≈ 1.8 MMTEB points at 0.6B); Llama-Embed-Nemotron and Gemini Embedding average fine-tuned runs, which is
linearin MergeKit terms. OLMo soups mid-training runs; WARM averages reward models. - Merging without weight averaging: MOPD combines RL specialists by on-policy distillation instead, and knowledge distillation is the trained alternative when parents do not share an initialisation.
- MoE:
mergekit-moebuilds the same block as Mixtral; random gates correspond to the sparse upcycling discussed in the MoE handbook and used by Nomic Embed v2. - LoRA:
mergekit-extract-lorais the reverse of LoRA: instead of training a low-rank update, it compresses a finished fine-tune into one. - Smaller models from merged ones: pruning LLMs is the opposite move from depth up-scaling: remove layers or width, then recover with distillation.
You should now be able to…
- Read a MergeKit YAML and say, for any tensor, which inputs and which parameter value produce it.
- Compute SLERP vs LERP by hand and explain why they coincide for close sibling fine-tunes.
- Explain how a frankenmerge, SOLAR’s DUS and a
mergekit-moemodel are built, and what each needs afterwards (continued training, searched seam scaling, or at least held-out evaluation). - Configure tokenizer alignment and chat templates so special tokens survive a merge.
- Critique a merged model’s leaderboard score for inherited contamination and selection on the test set.
Questions to think through
These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.
- Derive / compute
Treat two unit-norm tensors as 2-D vectors v0 = (1, 0) and v1 = (0.6, 0.8). Compute LERP and SLERP at t = 0.5 and t = 0.25, with their norms and angles from v0. Then compute how much LERP at t = 0.5 shrinks the norm when two flattened tensors have cosine 0.9995 (MergeKit's fallback threshold) and 0.9, and say what this implies for merging two fine-tunes of one base.
What a strong answer covers
- cos θ = 0.6, so θ ≈ 53.13°. At t = 0.5, LERP = (0.8, 0.4) with norm ≈ 0.894. SLERP uses sin(26.57°)/sin(53.13°) ≈ 0.559 for both, giving (0.894, 0.447): same direction, norm exactly 1.
- At t = 0.25, SLERP coefficients ≈ 0.801 and 0.287 give (0.973, 0.230), norm 1, at 13.28° = 0.25θ. LERP gives (0.9, 0.2), norm ≈ 0.922, at 12.5°, so LERP also moves at non-constant angular speed.
- For unit vectors, |LERP(0.5)| = cos(θ/2) = √((1 + cos θ)/2). That is ≈ 0.99987 at cos 0.9995 (a 0.01% shrink) and ≈ 0.975 at cos 0.9 (a 2.5% shrink).
- Two fine-tunes are b + τ₁ and b + τ₂. When the task vectors are small next to the shared base weights, the tensors are nearly collinear. MergeKit then falls back to linear interpolation (|cos| > 0.9995), so SLERP ≈ LERP. This fits the near-identical LERP and SLERP rows of the paper's Table 1. Near collinearity makes the interpolation coefficients close; it does not itself prove comparable downstream quality.
- Derive / compute
MergeKit's gradient-SLERP example sets t for self_attn to [0, 0.5, 0.3, 0.7, 1] and for mlp to [1, 0.5, 0.7, 0.3, 0] over a 40-layer slice. Layer i gets position u_i = i/39, which is scaled onto the list and linearly interpolated. (a) Compute t for both at layers 10 and 20. (b) Separately, write SOLAR's depth up-scaling as a passthrough recipe (which layer ranges, how many layers) and derive its parameter count from Mistral-7B shapes: hidden 4096, 8 KV heads of 128, MLP width 14336, vocabulary 32000.
What a strong answer covers
- (a) Layer 10: u = 10/39 ≈ 0.256, scaled ×4 ≈ 1.026, so attention t ≈ 0.5 + 0.026 × (0.3 − 0.5) ≈ 0.495 and MLP t ≈ 0.505. Layer 20: u ≈ 0.513, scaled ≈ 2.051, so attention ≈ 0.3 + 0.051 × 0.4 ≈ 0.321 and MLP ≈ 0.679.
- The two lists sum to 1 element by element, so at every layer attention leans towards one parent exactly as much as the MLP leans towards the other. Tensors that match neither filter use the 0.5 fallback; a norm nested under a matching module name would match that module's filter. Positions restart in every slice.
- (b) DUS with n = 32 and m = 8: base layers [0, 24) followed by a copy's layers [8, 32), with passthrough. That gives s = 2(n − m) = 48 layers, and layers 8–23 appear twice.
- Per layer: attention 2·4096² + 2·4096·1024 ≈ 41.9M and MLP 3·4096·14336 ≈ 176.2M, so ≈ 218.1M. 48 layers ≈ 10.47B, plus 2·32000·4096 ≈ 0.26B for embeddings and head, gives ≈ 10.7B, matching the model's name.
- The stacked model scores below the base until continued pretraining. Passthrough gives an initialisation, not a finished model.
- Mechanism
MergeKit initialises prompt-based MoE gates from base-model block-input states, while a Mixtral router consumes post-attention, post-normalisation states. Explain why this can still be a useful heuristic, trace top-k routing and the weighted expert combination for one token, and design an ablation comparing these two prototype-collection locations.
What a strong answer covers
- Collection: the base model runs each expert's prompts; output.hidden_states[:-1] gives the input to every block. "hidden" takes the last token, "hidden_avg" a padding-masked token mean; both average over prompts.
- Prototype: positive centroid minus negative centroid, L2-normalised, becomes the expert's gate row at that layer. IR analogy: Rocchio relevance feedback, a nearest-centroid classifier, with no guarantee that experts separate semantically.
- Mismatch: the router actually sees the residual state after attention, the residual add and post_attention_layernorm. Same width and related coordinates, but not the same activations or distribution, so prompt initialisation is a heuristic, not exact centroid fitting on router inputs.
- Forward pass for one token: logits h·g_e, softmax, keep the top-k (default 2), renormalise those weights to sum to 1, and sum the chosen experts' MLP outputs with them. Routing is per token, not per request.
- Ablation: same expert weights and prompts, gates built from block inputs versus from the post-attention-norm router inputs (collected with a hook). Compare gate utilisation, routing entropy, condition-number warnings and held-out per-domain quality.
- What if…
In the 7B-source evolutionary-merging experiment, PS/DFS/PS+DFS score 52.0/36.4/55.2 on MGSM-JA. In the separate 13B-source Table 4, PS scores 31.2, PS+DFS without W scores 26.4 at 19B, and PS+DFS with W scores 34.0 at 21B. Explain the two search spaces, interpret the evidence for seam scaling, and design a fixed-path ablation that removes the depth confound.
What a strong answer covers
- PS: CMA-ES tunes per-layer TIES+DARE density and weight (embeddings included). Fitness is accuracy on 1,069 translated GSM8K test problems that do not overlap MGSM; 1,000 trials. DFS freezes weights and searches one static layer sequence used by every token.
- DFS search space: the naive (M + 1)^T is intractable, so in the 7B run all M = 64 layers are laid out r = 3 times and a T = 64 × 3 = 192 indicator array switches each slot on or off: 2^192 inclusion choices.
- W scales the input of a layer fed from a different position or model; the motivation is that even swapping neighbouring layers hurts.
- Evidence: without W the 13B PS+DFS model (26.4) falls below its PS source (31.2), and 7.6 points below the W version. That supports seam scaling but is confounded, because the searched outputs differ in depth (19B vs 21B).
- Fixed-path ablation: freeze one searched layer path, then compare W = 1 against fitted W on held-out data. Separately predict and test r = 1 (no layer reuse) rather than claiming an unreported result.
- Critique
By early 2024 merged models dominated the Open LLM Leaderboard, and its maintainers began flagging mislabelled merges and contaminated models. Explain two mechanisms by which merging can inflate leaderboard scores without making a better model. Use SOLAR's final-merge choice (H6 averages of 74.00, 73.93, 74.05 and 73.96) as a concrete case, and design an experiment that separates a genuine merge gain from these effects.
What a strong answer covers
- Inheritance: a merge can retain contaminated behaviour from a contributing parent; how much is retained depends on the method and weights. Later merges can spread it further. The community's Marcoroni-7B-v3 thread is a suspicion report, not independent proof of contamination.
- Selection: picking among many recipes by the same public benchmark is adaptive overfitting. The four SOLAR merges span 0.12 H6 points, too small to rank reliably without uncertainty estimates (no variance is reported), so the choice is not evidence for one method.
- Evolutionary merging makes this selection pressure explicit. Sakana's fitness set (GSM8K test IDs 250–1318) does not overlap the test set but comes from the same distribution as MGSM. That is better than tuning on the test set, but weaker than a fresh benchmark.
- Experiment: freeze recipes in advance; evaluate on a benchmark built after all parents were released, or a private one; run contamination probes on each parent; report variance over seeds and recipes; compare with the best single parent and with a plain linear average.
- Design
You want to merge Llama-3-8B-Instruct with a RAG answer-generation fine-tune of the same base that was trained in ChatML format and added the <|im_start|> and <|im_end|> tokens. Choose the merge method and parameters, the tokenizer and chat-template settings, and the evaluation. Justify each choice using how MergeKit aligns embedding rows.
What a strong answer covers
- They share a base, so task-vector methods apply (task_arithmetic or TIES with base_model set to the pretrained Llama-3-8B, the reference subtracted to form deltas). SLERP between the two, perhaps with an attention/MLP gradient, is the simple alternative; there base_model names one of the two endpoints, not a third ancestor. Sweep weight or t, not just one setting.
- Tokenizer: source union keeps both formats. The ChatML tokens exist only in the fine-tune, so every input gets the fine-tune's row for them and the merge returns that row. Pin Llama-3 special tokens such as <|eot_id|> to the instruct model with force if the fine-tune moved them. force controls embedding and LM-head rows only, not whether the merged model follows a chat format.
- Without alignment, rows are merged by index. Different vocabulary sizes make MergeKit refuse; equal sizes with different meanings silently average unrelated tokens. --unsafe-truncate-embeddings only drops trailing rows and checks nothing.
- chat_template: set it explicitly rather than "auto" (the most common among inputs, which is meaningless with two models), and test prompts in both formats.
- Evaluation: grounded answer quality and citation accuracy on held-out RAG queries, general instruction following, and a check that generations stop at the end-of-turn token. A broken end-of-turn embedding shows up as run-on output.